powerlines 0.41.13 → 0.41.14

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1 +1 @@
1
- {"version":3,"file":"api-bp9wqF60.mjs","names":["ROOT_HASH_LENGTH","defu","DEFAULT_ENVIRONMENT","defu","joinPaths","#context","#normalizePath","#storage","#normalizeId","#getStorage","capnp","#log","#metadata","#ids","#paths","#resolverCache","#resolver","#getStorages","Blob","#innerResolve","#innerResolveSync","#isDisposed","joinPaths","#internal","#tsconfig","#fs","#checksum","#buildId","#releaseId","#timestamp","ROOT_HASH_LENGTH","CACHE_HASH_LENGTH","#workspaceConfig","#parserCache","#requestCache","defu","#getConfigProps","#hooks","PLUGIN_NON_HOOK_FIELDS","#environments","#log","#plugins","GLOBAL_ENVIRONMENT","#context","#addPlugin","packageJson.version","#executeEnvironments","#handleBuild","#getEnvironments","#initPlugin","#resolvePlugin","isPlugin","isPluginConfig"],"sources":["../package.json","../src/_internal/helpers/generate-types.ts","../src/_internal/helpers/hooks.ts","../src/_internal/helpers/install.ts","../src/_internal/helpers/install-dependencies.ts","../src/_internal/helpers/meta.ts","../src/_internal/helpers/resolve-tsconfig.ts","../src/_internal/helpers/environment.ts","../src/_internal/helpers/resolver.ts","../schemas/fs.ts","../src/_internal/helpers/constants.ts","../src/_internal/vfs.ts","../src/context/context.ts","../src/unplugin.ts","../src/context/plugin-context.ts","../src/context/environment-context.ts","../src/context/api-context.ts","../src/api.ts"],"sourcesContent":["","/* -------------------------------------------------------------------\n\n ⚡ Storm Software - Powerlines\n\n This code was released as part of the Powerlines project. Powerlines\n is maintained by Storm Software under the Apache-2.0 license, and is\n free for commercial and private use. For more information, please visit\n our licensing page at https://stormsoftware.com/licenses/projects/powerlines.\n\n Website: https://stormsoftware.com\n Repository: https://github.com/storm-software/powerlines\n Documentation: https://docs.stormsoftware.com/projects/powerlines\n Contact: https://stormsoftware.com/contact\n\n SPDX-License-Identifier: Apache-2.0\n\n ------------------------------------------------------------------- */\n\nimport { toArray } from \"@stryke/convert/to-array\";\nimport { appendPath } from \"@stryke/path/append\";\nimport { findFileName } from \"@stryke/path/file-path-fns\";\nimport { isParentPath } from \"@stryke/path/is-parent-path\";\nimport { replaceExtension, replacePath } from \"@stryke/path/replace\";\nimport { prettyBytes } from \"@stryke/string-format/pretty-bytes\";\nimport { isSetString } from \"@stryke/type-checks/is-set-string\";\nimport { DiagnosticCategory } from \"ts-morph\";\nimport { Context } from \"../../types\";\nimport { createProgram } from \"../../typescript/ts-morph\";\n\nconst getModuleCommentBlockRegex = (moduleId: string) =>\n new RegExp(`\\\\/\\\\*\\\\*(?s:.)*?@module\\\\s+${moduleId}(?s:.)*?\\\\*\\\\/\\\\s+`);\n\n/**\n * Formats the generated TypeScript types source code.\n *\n * @param code - The generated TypeScript code.\n * @returns The formatted TypeScript code.\n */\nexport function formatTypes(code: string): string {\n return code\n .replace(\n // eslint-disable-next-line regexp/no-super-linear-backtracking\n /import\\s*(?:type\\s*)?\\{?[\\w,\\s]*(?:\\}\\s*)?from\\s*(?:'|\")@?[a-zA-Z0-9-\\\\/.]*(?:'|\");?/g,\n \"\"\n )\n .replaceAll(\"#private;\", \"\")\n .replace(/__Ω/g, \"\");\n}\n\n/**\n * Emits TypeScript declaration types for the provided files using the given TypeScript configuration.\n *\n * @param context - The context containing options and environment paths.\n * @param files - The list of files to generate types for.\n * @returns A promise that resolves to the generated TypeScript declaration types.\n */\nexport async function emitBuiltinTypes<TContext extends Context>(\n context: TContext,\n files: string[]\n) {\n if (files.length === 0) {\n context.debug(\n \"No files provided for TypeScript types generation. Typescript compilation for built-in modules will be skipped.\"\n );\n return \"\";\n }\n\n context.debug(\n `Running the TypeScript compiler for ${\n files.length\n } generated built-in module files.`\n );\n\n const program = createProgram(context, {\n skipAddingFilesFromTsConfig: true,\n compilerOptions: {\n declaration: true,\n declarationMap: false,\n emitDeclarationOnly: true,\n sourceMap: false,\n outDir: replacePath(\n context.builtinsPath,\n context.workspaceConfig.workspaceRoot\n ),\n composite: false,\n incremental: false,\n tsBuildInfoFile: undefined\n }\n });\n\n program.addSourceFilesAtPaths(files);\n const result = program.emitToMemory({ emitOnlyDtsFiles: true });\n\n const diagnostics = result.getDiagnostics();\n if (diagnostics && diagnostics.length > 0) {\n if (diagnostics.some(d => d.getCategory() === DiagnosticCategory.Error)) {\n throw new Error(\n `The Typescript emit process failed while generating built-in types: \\n ${diagnostics\n .filter(d => d.getCategory() === DiagnosticCategory.Error)\n .map(\n d =>\n `-${d.getSourceFile() ? `${d.getSourceFile()?.getFilePath()}:` : \"\"} ${String(\n d.getMessageText()\n )} (at ${d.getStart()}:${d.getLength()})`\n )\n .join(\"\\n\")}`\n );\n } else if (\n diagnostics.some(d => d.getCategory() === DiagnosticCategory.Warning)\n ) {\n context.warn(\n `The Typescript emit process completed with warnings while generating built-in types: \\n ${diagnostics\n .filter(d => d.getCategory() === DiagnosticCategory.Warning)\n .map(\n d =>\n `-${d.getSourceFile() ? `${d.getSourceFile()?.getFilePath()}:` : \"\"} ${String(\n d.getMessageText()\n )} (at ${d.getStart()}:${d.getLength()})`\n )\n .join(\"\\n\")}`\n );\n } else {\n context.debug(\n `The Typescript emit process completed with diagnostic messages while generating built-in types: \\n ${diagnostics\n .map(\n d =>\n `-${d.getSourceFile() ? `${d.getSourceFile()?.getFilePath()}:` : \"\"} ${String(\n d.getMessageText()\n )} (at ${d.getStart()}:${d.getLength()})`\n )\n .join(\"\\n\")}`\n );\n }\n }\n\n const emittedFiles = result.getFiles();\n context.debug(\n `The TypeScript compiler emitted ${emittedFiles.length} files for built-in types.`\n );\n\n let builtinModules = \"\";\n for (const emittedFile of emittedFiles) {\n context.trace(\n `Processing emitted type declaration file: ${emittedFile.filePath}`\n );\n\n const filePath = appendPath(\n emittedFile.filePath,\n context.workspaceConfig.workspaceRoot\n );\n\n if (\n !filePath.endsWith(\".map\") &&\n findFileName(filePath) !== \"tsconfig.tsbuildinfo\" &&\n isParentPath(filePath, context.builtinsPath)\n ) {\n const moduleId = `${context.config.framework}:${replaceExtension(\n replacePath(filePath, context.builtinsPath),\n \"\",\n {\n fullExtension: true\n }\n )}`;\n const moduleComment = emittedFile.text\n .match(getModuleCommentBlockRegex(moduleId))\n ?.find(comment => isSetString(comment?.trim()));\n\n builtinModules += `${moduleComment ? `\\n${moduleComment.trim()}` : \"\"}\ndeclare module \"${moduleId}\" {\n ${emittedFile.text\n .replace(moduleComment ?? \"\", \"\")\n .trim()\n .replace(/^\\s*export\\s*declare\\s*/gm, \"export \")\n .replace(/^\\s*declare\\s*/gm, \"\")}\n}\n`;\n }\n }\n\n builtinModules = formatTypes(builtinModules);\n context.debug(\n `A TypeScript declaration file (size: ${prettyBytes(\n new Blob(toArray(builtinModules)).size\n )}) emitted for the built-in modules types.`\n );\n\n return builtinModules;\n}\n","/* -------------------------------------------------------------------\n\n ⚡ Storm Software - Powerlines\n\n This code was released as part of the Powerlines project. Powerlines\n is maintained by Storm Software under the Apache-2.0 license, and is\n free for commercial and private use. For more information, please visit\n our licensing page at https://stormsoftware.com/licenses/projects/powerlines.\n\n Website: https://stormsoftware.com\n Repository: https://github.com/storm-software/powerlines\n Documentation: https://docs.stormsoftware.com/projects/powerlines\n Contact: https://stormsoftware.com/contact\n\n SPDX-License-Identifier: Apache-2.0\n\n ------------------------------------------------------------------- */\n\nimport { isFunction } from \"@stryke/type-checks/is-function\";\nimport { isObject } from \"@stryke/type-checks/is-object\";\nimport { isSet } from \"@stryke/type-checks/is-set\";\nimport { isString } from \"@stryke/type-checks/is-string\";\nimport { ArrayValues } from \"@stryke/types/array\";\nimport chalk from \"chalk\";\nimport { createDefu, defu } from \"defu\";\nimport { mergeConfig } from \"../../plugin-utils\";\nimport {\n CallHookOptions,\n EnvironmentContext,\n InferHookParameters,\n InferHookReturnType,\n PluginContext,\n ResolvedConfig\n} from \"../../types\";\n\nconst mergeResultObjects = createDefu(<T>(obj: T, key: keyof T, value: any) => {\n if (isString(obj[key]) && isString(value)) {\n obj[key] = `${obj[key] || \"\"}\\n${value || \"\"}`.trim() as T[keyof T];\n\n return true;\n }\n\n return false;\n});\n\n/**\n * Merges the current hook result with the previous results based on their types.\n *\n * @param currentResult - The current hook result to merge with the previous results.\n * @param previousResults - The previous hook results to merge with the current result.\n * @returns The merged result.\n */\nexport function mergeResults<T>(currentResult: T, previousResults: T[]): T[] {\n if (isString(currentResult)) {\n previousResults = [\n `${isString(previousResults[0]) ? previousResults[0] || \"\" : \"\"}\\n${currentResult || \"\"}`.trim() as T\n ];\n } else if (isObject(currentResult)) {\n previousResults = [\n mergeResultObjects(currentResult, previousResults[0] ?? {})\n ];\n }\n\n return previousResults;\n}\n\n/**\n * Merges multiple hook results together, with special handling for string values and object values.\n *\n * @param currentResult - The current hook result to merge with the previous results.\n * @param previousResults - The previous hook results to merge with the current result.\n * @returns The merged result.\n */\nexport function mergeConfigs<T>(currentResult: T, previousResults: T[]): T[] {\n if (isString(currentResult)) {\n previousResults = [\n `${isString(previousResults[0]) ? previousResults[0] || \"\" : \"\"}\\n${currentResult || \"\"}`.trim() as T\n ];\n } else if (isObject(currentResult)) {\n previousResults = [\n mergeConfig(currentResult, previousResults[0] ?? {}) as T\n ];\n }\n\n return previousResults;\n}\n\n/**\n * Calls a hook with the given context, options, and arguments.\n *\n * @param context - The context to use when calling the hook.\n * @param key - The hook to call.\n * @param options - Options for calling the hook.\n * @param args - Arguments to pass to the hook.\n * @returns The return value of the hook.\n */\nexport async function callHook<\n TResolvedConfig extends ResolvedConfig,\n TKey extends string\n>(\n context: EnvironmentContext<TResolvedConfig>,\n key: TKey,\n options: CallHookOptions,\n ...args: InferHookParameters<PluginContext<TResolvedConfig>, TKey>\n): Promise<\n InferHookReturnType<PluginContext<TResolvedConfig>, TKey> | undefined\n> {\n const hooks = context.selectHooks(key, options);\n if (hooks.length > 0) {\n context.debug(\n ` 🧩 Calling plugin hook: ${chalk.bold.cyanBright(\n `${key}${options?.order ? ` (${options.order})` : \"\"}`\n )}`\n );\n\n const invokeHook = async (\n hook: ArrayValues<typeof hooks>,\n hookArgs: InferHookParameters<PluginContext<TResolvedConfig>, TKey>\n ) => {\n return Reflect.apply(hook.handler, hook.context, hookArgs);\n };\n\n let results = [] as InferHookReturnType<\n PluginContext<TResolvedConfig>,\n TKey\n >[];\n if (options?.sequential === false) {\n results = (await Promise.all(\n hooks.map(async hook => {\n if (!isFunction(hook.handler)) {\n throw new Error(\n `Plugin hook handler for hook \"${key}\" is not a function.`\n );\n }\n\n return invokeHook(hook, [...args]);\n })\n )) as InferHookReturnType<PluginContext<TResolvedConfig>, TKey>[];\n } else {\n for (const hook of hooks) {\n if (!isFunction(hook.handler)) {\n throw new Error(\n `Plugin hook handler for hook \"${key}\" is not a function.`\n );\n }\n\n if (options?.result === \"first\" || options?.asNextParam === false) {\n results.push(\n (await Promise.resolve(\n invokeHook(hook, [...args])\n )) as InferHookReturnType<PluginContext<TResolvedConfig>, TKey>\n );\n if (\n options?.result === \"first\" &&\n isSet(results[results.length - 1])\n ) {\n break;\n }\n } else {\n const sequenceArgs = [...args];\n if (results.length > 0 && sequenceArgs.length > 0) {\n sequenceArgs[0] = isFunction(options.asNextParam)\n ? await Promise.resolve(options.asNextParam(results[0]))\n : results[0];\n }\n\n const result = await Promise.resolve(\n invokeHook(hook, [...sequenceArgs] as InferHookParameters<\n PluginContext<TResolvedConfig>,\n TKey\n >)\n );\n if (result) {\n if (options.result === \"last\") {\n results = [result];\n } else if (options.result === \"merge\" && options.merge) {\n results = options.merge(result, results);\n } else {\n results = mergeResults(result, results);\n }\n }\n }\n }\n }\n\n const definedResults = results.filter(\n (\n result\n ): result is NonNullable<\n InferHookReturnType<PluginContext<TResolvedConfig>, TKey>\n > => isSet(result)\n );\n\n if (definedResults.length > 0) {\n let mergedResult = undefined as\n | InferHookReturnType<PluginContext<TResolvedConfig>, TKey>\n | undefined;\n\n for (const result of definedResults) {\n mergedResult = defu(\n result as Record<string, unknown>,\n (mergedResult ?? {}) as Record<string, unknown>\n ) as InferHookReturnType<PluginContext<TResolvedConfig>, TKey>;\n }\n\n return mergedResult;\n }\n }\n\n return undefined;\n}\n","/* -------------------------------------------------------------------\n\n ⚡ Storm Software - Powerlines\n\n This code was released as part of the Powerlines project. Powerlines\n is maintained by Storm Software under the Apache-2.0 license, and is\n free for commercial and private use. For more information, please visit\n our licensing page at https://stormsoftware.com/licenses/projects/powerlines.\n\n Website: https://stormsoftware.com\n Repository: https://github.com/storm-software/powerlines\n Documentation: https://docs.stormsoftware.com/projects/powerlines\n Contact: https://stormsoftware.com/contact\n\n SPDX-License-Identifier: Apache-2.0\n\n ------------------------------------------------------------------- */\n\nimport { install } from \"@stryke/fs/install\";\nimport {\n doesPackageMatch,\n getPackageListing,\n isPackageListed\n} from \"@stryke/fs/package-fns\";\nimport {\n getPackageName,\n getPackageVersion,\n hasPackageVersion\n} from \"@stryke/string-format/package\";\nimport { isNumber } from \"@stryke/type-checks/is-number\";\nimport type { Context } from \"../../types\";\n\n/**\n * Installs a package if it is not already installed.\n *\n * @param context - The resolved options\n * @param packageName - The name of the package to install\n * @param dev - Whether to install the package as a dev dependency\n */\nexport async function installPackage(\n context: Context,\n packageName: string,\n dev = false\n) {\n if (\n !(await isPackageListed(getPackageName(packageName), {\n cwd: context.config.root\n }))\n ) {\n if (context.config.autoInstall) {\n context.warn(\n `The package \"${packageName}\" is not installed. It will be installed automatically.`\n );\n\n const result = await install(packageName, {\n cwd: context.config.root,\n dev\n });\n if (isNumber(result.exitCode) && result.exitCode > 0) {\n context.error(result.stderr);\n throw new Error(\n `An error occurred while installing the package \"${packageName}\"`\n );\n }\n } else {\n context.warn(\n `The package \"${packageName}\" is not installed. Since the \"autoInstall\" option is set to false, it will not be installed automatically.`\n );\n }\n } else if (\n hasPackageVersion(packageName) &&\n !process.env.POWERLINES_SKIP_VERSION_CHECK\n ) {\n const isMatching = await doesPackageMatch(\n getPackageName(packageName),\n getPackageVersion(packageName)!,\n context.config.root\n );\n if (!isMatching) {\n const packageListing = await getPackageListing(\n getPackageName(packageName),\n {\n cwd: context.config.root\n }\n );\n if (\n !packageListing?.version.startsWith(\"catalog:\") &&\n !packageListing?.version.startsWith(\"workspace:\")\n ) {\n context.warn(\n `The package \"${getPackageName(packageName)}\" is installed but does not match the expected version ${getPackageVersion(\n packageName\n )} (installed version: ${packageListing?.version || \"<Unknown>\"}). Please ensure this is intentional before proceeding. Note: You can skip this validation with the \"STORM_STACK_SKIP_VERSION_CHECK\" environment variable.`\n );\n }\n }\n }\n}\n\n/**\n * Installs a package if it is not already installed.\n *\n * @param context - The resolved options\n * @param packages - The list of packages to install\n */\nexport async function installPackages(\n context: Context,\n packages: Array<{ name: string; dev?: boolean }>\n) {\n return Promise.all(\n packages.map(async pkg => installPackage(context, pkg.name, pkg.dev))\n );\n}\n","/* -------------------------------------------------------------------\n\n ⚡ Storm Software - Powerlines\n\n This code was released as part of the Powerlines project. Powerlines\n is maintained by Storm Software under the Apache-2.0 license, and is\n free for commercial and private use. For more information, please visit\n our licensing page at https://stormsoftware.com/licenses/projects/powerlines.\n\n Website: https://stormsoftware.com\n Repository: https://github.com/storm-software/powerlines\n Documentation: https://docs.stormsoftware.com/projects/powerlines\n Contact: https://stormsoftware.com/contact\n\n SPDX-License-Identifier: Apache-2.0\n\n ------------------------------------------------------------------- */\n\nimport { getPackageName } from \"@stryke/string-format/package\";\nimport { Context } from \"../../types\";\nimport { installPackage } from \"./install\";\n\n/**\n * Install missing project dependencies.\n *\n * @param context - The build context.\n */\nexport async function installDependencies<TContext extends Context = Context>(\n context: TContext\n): Promise<void> {\n context.debug(`Checking and installing missing project dependencies.`);\n\n context.dependencies ??= {};\n context.devDependencies ??= {};\n\n if (\n Object.keys(context.dependencies).length === 0 &&\n Object.keys(context.devDependencies).length === 0\n ) {\n context.debug(\n `No dependencies or devDependencies to install. Skipping installation step.`\n );\n return;\n }\n\n context.debug(\n `The following packages are required: \\nDependencies: \\n${Object.entries(\n context.dependencies\n )\n .map(([name, version]) => `- ${name}@${String(version)}`)\n .join(\" \\n\")}\\n\\nDevDependencies: \\n${Object.entries(\n context.devDependencies\n )\n .map(([name, version]) => `- ${name}@${String(version)}`)\n .join(\" \\n\")}`\n );\n\n await Promise.all([\n Promise.all(\n Object.entries(context.dependencies).map(async ([name, version]) =>\n installPackage(\n context,\n `${getPackageName(name)}@${String(version)}`,\n false\n )\n )\n ),\n Promise.all(\n Object.entries(context.devDependencies).map(async ([name, version]) =>\n installPackage(\n context,\n `${getPackageName(name)}@${String(version)}`,\n true\n )\n )\n )\n ]);\n}\n","/* -------------------------------------------------------------------\n\n ⚡ Storm Software - Powerlines\n\n This code was released as part of the Powerlines project. Powerlines\n is maintained by Storm Software under the Apache-2.0 license, and is\n free for commercial and private use. For more information, please visit\n our licensing page at https://stormsoftware.com/licenses/projects/powerlines.\n\n Website: https://stormsoftware.com\n Repository: https://github.com/storm-software/powerlines\n Documentation: https://docs.stormsoftware.com/projects/powerlines\n Contact: https://stormsoftware.com/contact\n\n SPDX-License-Identifier: Apache-2.0\n\n ------------------------------------------------------------------- */\n\nimport { existsSync } from \"@stryke/fs/exists\";\nimport { readJsonFile } from \"@stryke/fs/json\";\nimport { removeFile } from \"@stryke/fs/remove-file\";\nimport { joinPaths } from \"@stryke/path/join-paths\";\nimport { kebabCase } from \"@stryke/string-format/kebab-case\";\nimport { ROOT_HASH_LENGTH } from \"../../constants\";\nimport type { Context, MetaInfo } from \"../../types\";\n\nexport interface CreateContextOptions {\n name?: string;\n}\n\n/**\n * Generates a prefixed project root hash object.\n *\n * @remarks\n * This function returns a string where the project root hash is prefixed with the project name plus a hyphen. If the total length of this string combination exceeds 45 characters, it will truncate the hash.\n *\n * @param name - The name of the project.\n * @param rootHash - The hash of the project root.\n * @returns An object containing the name and project root hash.\n */\nexport function getPrefixedRootHash(name: string, rootHash: string): string {\n const combined = `${kebabCase(name)}_${rootHash}`;\n\n return combined.length > ROOT_HASH_LENGTH\n ? combined.slice(0, ROOT_HASH_LENGTH)\n : combined;\n}\n\n/**\n * Retrieves the persisted meta information from the context's data path.\n *\n * @param context - The build context.\n * @returns A promise that resolves to the persisted meta information, or undefined if not found.\n */\nexport async function getPersistedMeta(\n context: Context\n): Promise<MetaInfo | undefined> {\n const metaFilePath = joinPaths(context.dataPath, \"meta.json\");\n if (existsSync(metaFilePath)) {\n try {\n return await readJsonFile<MetaInfo>(metaFilePath);\n } catch {\n context.warn(\n `Failed to read meta file at ${metaFilePath}. It may be corrupted.`\n );\n await removeFile(metaFilePath);\n\n context.persistedMeta = undefined;\n }\n }\n\n return undefined;\n}\n\n/**\n * Writes the meta file for the context.\n *\n * @param context - The context to write the meta file for.\n * @returns A promise that resolves when the meta file has been written.\n */\nexport async function writeMetaFile(context: Context): Promise<void> {\n const metaFilePath = joinPaths(context.dataPath, \"meta.json\");\n\n context.debug(`Writing runtime metadata to ${metaFilePath}`);\n\n await context.fs.write(metaFilePath, JSON.stringify(context.meta, null, 2));\n}\n","/* -------------------------------------------------------------------\n\n ⚡ Storm Software - Powerlines\n\n This code was released as part of the Powerlines project. Powerlines\n is maintained by Storm Software under the Apache-2.0 license, and is\n free for commercial and private use. For more information, please visit\n our licensing page at https://stormsoftware.com/licenses/projects/powerlines.\n\n Website: https://stormsoftware.com\n Repository: https://github.com/storm-software/powerlines\n Documentation: https://docs.stormsoftware.com/projects/powerlines\n Contact: https://stormsoftware.com/contact\n\n SPDX-License-Identifier: Apache-2.0\n\n ------------------------------------------------------------------- */\n\nimport type { Diff, ObjectData } from \"@donedeal0/superdiff\";\nimport { getObjectDiff } from \"@donedeal0/superdiff\";\nimport { readJsonFile } from \"@stryke/fs/json\";\nimport { isPackageExists } from \"@stryke/fs/package-fns\";\nimport { StormJSON } from \"@stryke/json/storm-json\";\nimport {\n findFileName,\n findFilePath,\n relativePath\n} from \"@stryke/path/file-path-fns\";\nimport { joinPaths } from \"@stryke/path/join-paths\";\nimport { titleCase } from \"@stryke/string-format/title-case\";\nimport { TsConfigJson } from \"@stryke/types/tsconfig\";\nimport chalk from \"chalk\";\nimport type { EnvironmentContext } from \"../../types\";\nimport { ResolvedConfig } from \"../../types\";\nimport {\n getParsedTypeScriptConfig,\n getTsconfigFilePath,\n isIncludeMatchFound\n} from \"../../typescript/tsconfig\";\n\nexport function getTsconfigDtsPath<\n TResolvedConfig extends ResolvedConfig = ResolvedConfig\n>(context: EnvironmentContext<TResolvedConfig>): string {\n const dtsRelativePath = joinPaths(\n relativePath(\n joinPaths(context.workspaceConfig.workspaceRoot, context.config.root),\n findFilePath(context.dtsPath)\n ),\n findFileName(context.dtsPath)\n );\n\n return dtsRelativePath;\n}\n\nasync function resolveTsconfigChanges<\n TResolvedConfig extends ResolvedConfig = ResolvedConfig\n>(context: EnvironmentContext<TResolvedConfig>): Promise<TsConfigJson> {\n const tsconfig = getParsedTypeScriptConfig(\n context.workspaceConfig.workspaceRoot,\n context.config.root,\n context.config.tsconfig,\n context.config.tsconfigRaw\n );\n\n const tsconfigFilePath = getTsconfigFilePath(\n context.workspaceConfig.workspaceRoot,\n context.config.root,\n context.config.tsconfig\n );\n\n const tsconfigJson = await readJsonFile<TsConfigJson>(tsconfigFilePath);\n tsconfigJson.compilerOptions ??= {};\n\n if (context.config.output.dts !== false) {\n const dtsRelativePath = getTsconfigDtsPath(context);\n\n if (\n !tsconfigJson.include?.some(filePattern =>\n isIncludeMatchFound(filePattern, [context.dtsPath, dtsRelativePath])\n )\n ) {\n tsconfigJson.include ??= [];\n tsconfigJson.include.push(\n dtsRelativePath.startsWith(\"./\")\n ? dtsRelativePath.slice(2)\n : dtsRelativePath\n );\n }\n }\n\n if (\n !tsconfig.options.lib?.some(lib =>\n [\n \"lib.esnext.d.ts\",\n \"lib.es2021.d.ts\",\n \"lib.es2022.d.ts\",\n \"lib.es2023.d.ts\"\n ].includes(lib.toLowerCase())\n )\n ) {\n tsconfigJson.compilerOptions.lib ??= [];\n tsconfigJson.compilerOptions.lib.push(\"esnext\");\n }\n\n // if (tsconfig.options.module !== ts.ModuleKind.ESNext) {\n // tsconfigJson.compilerOptions.module = \"ESNext\";\n // }\n\n // if (\n // !tsconfig.options.target ||\n // ![\n // ts.ScriptTarget.ESNext,\n // ts.ScriptTarget.ES2024,\n // ts.ScriptTarget.ES2023,\n // ts.ScriptTarget.ES2022,\n // ts.ScriptTarget.ES2021\n // ].includes(tsconfig.options.target)\n // ) {\n // tsconfigJson.compilerOptions.target = \"ESNext\";\n // }\n\n // if (tsconfig.options.moduleResolution !== ts.ModuleResolutionKind.Bundler) {\n // tsconfigJson.compilerOptions.moduleResolution = \"Bundler\";\n // }\n\n // if (tsconfig.options.moduleDetection !== ts.ModuleDetectionKind.Force) {\n // tsconfigJson.compilerOptions.moduleDetection = \"force\";\n // }\n\n // if (tsconfig.options.allowSyntheticDefaultImports !== true) {\n // tsconfigJson.compilerOptions.allowSyntheticDefaultImports = true;\n // }\n\n // if (tsconfig.options.noImplicitOverride !== true) {\n // tsconfigJson.compilerOptions.noImplicitOverride = true;\n // }\n\n // if (tsconfig.options.noUncheckedIndexedAccess !== true) {\n // tsconfigJson.compilerOptions.noUncheckedIndexedAccess = true;\n // }\n\n // if (tsconfig.options.skipLibCheck !== true) {\n // tsconfigJson.compilerOptions.skipLibCheck = true;\n // }\n\n // if (tsconfig.options.resolveJsonModule !== true) {\n // tsconfigJson.compilerOptions.resolveJsonModule = true;\n // }\n\n // if (tsconfig.options.verbatimModuleSyntax !== false) {\n // tsconfigJson.compilerOptions.verbatimModuleSyntax = false;\n // }\n\n // if (tsconfig.options.allowJs !== true) {\n // tsconfigJson.compilerOptions.allowJs = true;\n // }\n\n // if (tsconfig.options.declaration !== true) {\n // tsconfigJson.compilerOptions.declaration = true;\n // }\n\n if (tsconfig.options.esModuleInterop !== true) {\n tsconfigJson.compilerOptions.esModuleInterop = true;\n }\n\n if (tsconfig.options.isolatedModules !== true) {\n tsconfigJson.compilerOptions.isolatedModules = true;\n }\n\n if (context.config.platform === \"node\") {\n if (\n !tsconfig.options.types?.some(\n type =>\n type.toLowerCase() === \"node\" || type.toLowerCase() === \"@types/node\"\n )\n ) {\n tsconfigJson.compilerOptions.types ??= [];\n tsconfigJson.compilerOptions.types.push(\"node\");\n }\n }\n\n return tsconfigJson;\n}\n\nexport async function initializeTsconfig<\n TResolvedConfig extends ResolvedConfig = ResolvedConfig,\n TContext extends EnvironmentContext<TResolvedConfig> =\n EnvironmentContext<TResolvedConfig>\n>(context: TContext): Promise<void> {\n context.debug(\n \"Initializing TypeScript configuration (tsconfig.json) for the Powerlines project.\"\n );\n\n if (!isPackageExists(\"typescript\")) {\n throw new Error(\n 'The TypeScript package is not installed. Please install the package using the command: \"npm install typescript --save-dev\"'\n );\n }\n\n const tsconfigFilePath = getTsconfigFilePath(\n context.workspaceConfig.workspaceRoot,\n context.config.root,\n context.config.tsconfig\n );\n\n context.tsconfig.originalTsconfigJson =\n await readJsonFile<TsConfigJson>(tsconfigFilePath);\n\n context.tsconfig.tsconfigJson =\n await resolveTsconfigChanges<TResolvedConfig>(context);\n\n context.debug(\n \"Writing updated TypeScript configuration (tsconfig.json) file to disk.\"\n );\n\n await context.fs.write(\n tsconfigFilePath,\n StormJSON.stringify(context.tsconfig.tsconfigJson)\n );\n\n context.tsconfig = getParsedTypeScriptConfig(\n context.workspaceConfig.workspaceRoot,\n context.config.root,\n context.config.tsconfig,\n context.config.tsconfigRaw,\n context.tsconfig.originalTsconfigJson\n );\n}\n\nexport async function resolveTsconfig<\n TResolvedConfig extends ResolvedConfig = ResolvedConfig,\n TContext extends EnvironmentContext<TResolvedConfig> =\n EnvironmentContext<TResolvedConfig>\n>(context: TContext): Promise<void> {\n const updateTsconfigJson = await readJsonFile<TsConfigJson>(\n context.tsconfig.tsconfigFilePath\n );\n if (\n updateTsconfigJson?.compilerOptions?.types &&\n Array.isArray(updateTsconfigJson.compilerOptions.types) &&\n !updateTsconfigJson.compilerOptions.types.length\n ) {\n // If the types array is empty, we can safely remove it\n delete updateTsconfigJson.compilerOptions.types;\n }\n\n const result = getObjectDiff(\n context.tsconfig.originalTsconfigJson as NonNullable<ObjectData>,\n updateTsconfigJson as ObjectData,\n {\n ignoreArrayOrder: true,\n showOnly: {\n statuses: [\"added\", \"deleted\", \"updated\"],\n granularity: \"deep\"\n }\n }\n );\n\n const changes = [] as {\n field: string;\n status: \"added\" | \"deleted\" | \"updated\";\n previous: string;\n current: string;\n }[];\n const getChanges = (difference: Diff, property?: string) => {\n if (\n difference.status === \"added\" ||\n difference.status === \"deleted\" ||\n difference.status === \"updated\"\n ) {\n if (difference.diff) {\n for (const diff of difference.diff) {\n getChanges(\n diff,\n property\n ? `${property}.${difference.property}`\n : difference.property\n );\n }\n } else {\n changes.push({\n field: property\n ? `${property}.${difference.property}`\n : difference.property,\n status: difference.status,\n previous:\n difference.status === \"added\"\n ? \"---\"\n : StormJSON.stringify(difference.previousValue),\n current:\n difference.status === \"deleted\"\n ? \"---\"\n : StormJSON.stringify(difference.currentValue)\n });\n }\n }\n };\n\n for (const diff of result.diff) {\n getChanges(diff);\n }\n\n if (changes.length > 0) {\n context.warn(\n `Updating the following configuration values in \"${context.tsconfig.tsconfigFilePath}\" file:\n\n ${changes\n .map(\n (change, i) => `${chalk.bold.whiteBright(\n `${i + 1}. ${titleCase(change.status)} the ${change.field} field: `\n )}\n ${chalk.red(` - Previous: ${change.previous} `)}\n ${chalk.green(` - Updated: ${change.current} `)}\n `\n )\n .join(\"\\n\")}\n `\n );\n }\n\n await context.fs.write(\n context.tsconfig.tsconfigFilePath,\n StormJSON.stringify(updateTsconfigJson)\n );\n\n context.tsconfig = getParsedTypeScriptConfig(\n context.workspaceConfig.workspaceRoot,\n context.config.root,\n context.config.tsconfig\n );\n if (!context.tsconfig) {\n throw new Error(\"Failed to parse the TypeScript configuration file.\");\n }\n}\n","/* -------------------------------------------------------------------\n\n ⚡ Storm Software - Powerlines\n\n This code was released as part of the Powerlines project. Powerlines\n is maintained by Storm Software under the Apache-2.0 license, and is\n free for commercial and private use. For more information, please visit\n our licensing page at https://stormsoftware.com/licenses/projects/powerlines.\n\n Website: https://stormsoftware.com\n Repository: https://github.com/storm-software/powerlines\n Documentation: https://docs.stormsoftware.com/projects/powerlines\n Contact: https://stormsoftware.com/contact\n\n SPDX-License-Identifier: Apache-2.0\n\n ------------------------------------------------------------------- */\n\nimport { titleCase } from \"@stryke/string-format/title-case\";\nimport defu from \"defu\";\nimport { DEFAULT_ENVIRONMENT } from \"../../constants\";\nimport { APIContext, Context, EnvironmentResolvedConfig } from \"../../types\";\n\nexport function createEnvironment<TContext extends Context = Context>(\n name: string,\n userConfig: TContext[\"config\"][\"userConfig\"]\n): EnvironmentResolvedConfig {\n return defu(\n userConfig.environments?.[name] ?? {},\n {\n name,\n title: userConfig.title || titleCase(userConfig.name),\n ssr: false,\n mainFields:\n userConfig?.platform === \"browser\"\n ? [\"browser\", \"module\", \"jsnext:main\", \"jsnext\"]\n : [\"module\", \"jsnext:main\", \"jsnext\"],\n extensions: [\".mjs\", \".js\", \".mts\", \".ts\", \".jsx\", \".tsx\", \".json\"],\n consumer: userConfig?.platform === \"browser\" ? \"client\" : \"server\",\n preview:\n userConfig?.platform === \"browser\"\n ? {\n port: 5173,\n open: true,\n strictPort: false,\n // https: false,\n host: \"localhost\",\n allowedHosts: [\".\"],\n cors: true,\n headers: {}\n }\n : undefined\n },\n userConfig\n ) as EnvironmentResolvedConfig;\n}\n\nexport function createDefaultEnvironment<\n TContext extends APIContext = APIContext\n>(userConfig: TContext[\"config\"][\"userConfig\"]): EnvironmentResolvedConfig {\n return createEnvironment(DEFAULT_ENVIRONMENT, userConfig);\n}\n","/* -------------------------------------------------------------------\n\n ⚡ Storm Software - Powerlines\n\n This code was released as part of the Powerlines project. Powerlines\n is maintained by Storm Software under the Apache-2.0 license, and is\n free for commercial and private use. For more information, please visit\n our licensing page at https://stormsoftware.com/licenses/projects/powerlines.\n\n Website: https://stormsoftware.com\n Repository: https://github.com/storm-software/powerlines\n Documentation: https://docs.stormsoftware.com/projects/powerlines\n Contact: https://stormsoftware.com/contact\n\n SPDX-License-Identifier: Apache-2.0\n\n ------------------------------------------------------------------- */\n\nimport { joinPaths } from \"@stryke/path/join-paths\";\nimport defu from \"defu\";\nimport { JitiOptions, createJiti } from \"jiti\";\nimport { ResolvedConfig, Resolver } from \"../../types\";\n\nexport type CreateResolverOptions = Omit<\n JitiOptions,\n \"fsCache\" | \"moduleCache\" | \"interopDefault\"\n> &\n Pick<ResolvedConfig, \"mode\" | \"logLevel\" | \"skipCache\"> & {\n workspaceRoot: string;\n root: string;\n cacheDir: string;\n };\n\n/**\n * Create a Jiti resolver for the given workspace and project root.\n *\n * @param options - The options for creating the resolver.\n * @returns A Jiti instance configured for the specified workspace and project root.\n */\nfunction resolveOptions(options: CreateResolverOptions): JitiOptions {\n return defu(options, {\n interopDefault: true,\n fsCache:\n options.mode !== \"development\"\n ? joinPaths(options.cacheDir, \"jiti\")\n : false,\n moduleCache: options.mode !== \"development\"\n });\n}\n\n/**\n * Create a Jiti resolver for the given workspace and project root.\n *\n * @param options - The options for creating the resolver.\n * @returns A Jiti instance configured for the specified workspace and project root.\n */\nexport function createResolver(options: CreateResolverOptions): Resolver {\n const baseResolver = createJiti(\n joinPaths(options.workspaceRoot, options.root),\n resolveOptions(options)\n ) as Resolver;\n baseResolver.plugin = createJiti(\n joinPaths(options.workspaceRoot, options.root),\n resolveOptions(options)\n );\n\n return baseResolver;\n}\n","/* eslint-disable */\n// biome-ignore lint: disable\n// Generated by storm-capnpc\n// Note: Do not edit this file manually - it will be overwritten automatically\nimport * as $ from \"@stryke/capnp\";\nexport const _capnpFileId = BigInt(\"0xa56c61324b9d6e49\");\nexport class FileMetadata_KeyValuePair extends $.Struct {\n public static override readonly _capnp = {\n displayName: \"KeyValuePair\",\n id: \"eabb26cf58b2a14c\",\n size: new $.ObjectSize(0, 2),\n };\n get key(): string {\n return $.utils.getText(0, this);\n }\n set key(value: string) {\n $.utils.setText(0, value, this);\n }\n get value(): string {\n return $.utils.getText(1, this);\n }\n set value(value: string) {\n $.utils.setText(1, value, this);\n }\n public override toString(): string { return \"FileMetadata_KeyValuePair_\" + super.toString(); }\n}\n/**\n* The identifier for the file data.\n*\n*/\nexport class FileMetadata extends $.Struct {\n static readonly KeyValuePair = FileMetadata_KeyValuePair;\n public static override readonly _capnp = {\n displayName: \"FileMetadata\",\n id: \"8e2cab5d7e28c7b3\",\n size: new $.ObjectSize(8, 3),\n defaultType: \"normal\"\n };\n static _Properties: $.ListCtor<FileMetadata_KeyValuePair>;\n /**\n* The type of the file.\n*\n*/\n get id(): string {\n return $.utils.getText(0, this);\n }\n set id(value: string) {\n $.utils.setText(0, value, this);\n }\n /**\n* The timestamp representing the file's creation date.\n*\n*/\n get type(): string {\n return $.utils.getText(1, this, FileMetadata._capnp.defaultType);\n }\n set type(value: string) {\n $.utils.setText(1, value, this);\n }\n /**\n* Additional metadata associated with the file.\n*\n*/\n get timestamp(): number {\n return $.utils.getUint32(0, this);\n }\n set timestamp(value: number) {\n $.utils.setUint32(0, value, this);\n }\n _adoptProperties(value: $.Orphan<$.List<FileMetadata_KeyValuePair>>): void {\n $.utils.adopt(value, $.utils.getPointer(2, this));\n }\n _disownProperties(): $.Orphan<$.List<FileMetadata_KeyValuePair>> {\n return $.utils.disown(this.properties);\n }\n get properties(): $.List<FileMetadata_KeyValuePair> {\n return $.utils.getList(2, FileMetadata._Properties, this);\n }\n _hasProperties(): boolean {\n return !$.utils.isNull($.utils.getPointer(2, this));\n }\n _initProperties(length: number): $.List<FileMetadata_KeyValuePair> {\n return $.utils.initList(2, FileMetadata._Properties, length, this);\n }\n set properties(value: $.List<FileMetadata_KeyValuePair>) {\n $.utils.copyFrom(value, $.utils.getPointer(2, this));\n }\n public override toString(): string { return \"FileMetadata_\" + super.toString(); }\n}\n/**\n* An identifier for the file.\n*\n*/\nexport class FileId extends $.Struct {\n public static override readonly _capnp = {\n displayName: \"FileId\",\n id: \"990d6a471072f997\",\n size: new $.ObjectSize(0, 2),\n };\n /**\n* A virtual (or actual) path to the file in the file system.\n*\n*/\n get id(): string {\n return $.utils.getText(0, this);\n }\n set id(value: string) {\n $.utils.setText(0, value, this);\n }\n get path(): string {\n return $.utils.getText(1, this);\n }\n set path(value: string) {\n $.utils.setText(1, value, this);\n }\n public override toString(): string { return \"FileId_\" + super.toString(); }\n}\n/**\n* An identifier for the file.\n*\n*/\nexport class FileStorage extends $.Struct {\n public static override readonly _capnp = {\n displayName: \"FileStorage\",\n id: \"9dca66ac858c9ebe\",\n size: new $.ObjectSize(0, 2),\n };\n /**\n* A virtual (or actual) path to the file in the file system.\n*\n*/\n get path(): string {\n return $.utils.getText(0, this);\n }\n set path(value: string) {\n $.utils.setText(0, value, this);\n }\n get code(): string {\n return $.utils.getText(1, this);\n }\n set code(value: string) {\n $.utils.setText(1, value, this);\n }\n public override toString(): string { return \"FileStorage_\" + super.toString(); }\n}\nexport class FileSystem extends $.Struct {\n public static override readonly _capnp = {\n displayName: \"FileSystem\",\n id: \"ae0c23d43e56abcf\",\n size: new $.ObjectSize(0, 3),\n };\n static _Ids: $.ListCtor<FileId>;\n static _Storage: $.ListCtor<FileStorage>;\n static _Metadata: $.ListCtor<FileMetadata>;\n _adoptIds(value: $.Orphan<$.List<FileId>>): void {\n $.utils.adopt(value, $.utils.getPointer(0, this));\n }\n _disownIds(): $.Orphan<$.List<FileId>> {\n return $.utils.disown(this.ids);\n }\n get ids(): $.List<FileId> {\n return $.utils.getList(0, FileSystem._Ids, this);\n }\n _hasIds(): boolean {\n return !$.utils.isNull($.utils.getPointer(0, this));\n }\n _initIds(length: number): $.List<FileId> {\n return $.utils.initList(0, FileSystem._Ids, length, this);\n }\n set ids(value: $.List<FileId>) {\n $.utils.copyFrom(value, $.utils.getPointer(0, this));\n }\n _adoptStorage(value: $.Orphan<$.List<FileStorage>>): void {\n $.utils.adopt(value, $.utils.getPointer(1, this));\n }\n _disownStorage(): $.Orphan<$.List<FileStorage>> {\n return $.utils.disown(this.storage);\n }\n get storage(): $.List<FileStorage> {\n return $.utils.getList(1, FileSystem._Storage, this);\n }\n _hasStorage(): boolean {\n return !$.utils.isNull($.utils.getPointer(1, this));\n }\n _initStorage(length: number): $.List<FileStorage> {\n return $.utils.initList(1, FileSystem._Storage, length, this);\n }\n set storage(value: $.List<FileStorage>) {\n $.utils.copyFrom(value, $.utils.getPointer(1, this));\n }\n _adoptMetadata(value: $.Orphan<$.List<FileMetadata>>): void {\n $.utils.adopt(value, $.utils.getPointer(2, this));\n }\n _disownMetadata(): $.Orphan<$.List<FileMetadata>> {\n return $.utils.disown(this.metadata);\n }\n get metadata(): $.List<FileMetadata> {\n return $.utils.getList(2, FileSystem._Metadata, this);\n }\n _hasMetadata(): boolean {\n return !$.utils.isNull($.utils.getPointer(2, this));\n }\n _initMetadata(length: number): $.List<FileMetadata> {\n return $.utils.initList(2, FileSystem._Metadata, length, this);\n }\n set metadata(value: $.List<FileMetadata>) {\n $.utils.copyFrom(value, $.utils.getPointer(2, this));\n }\n public override toString(): string { return \"FileSystem_\" + super.toString(); }\n}\nFileMetadata._Properties = $.CompositeList(FileMetadata_KeyValuePair);\nFileSystem._Ids = $.CompositeList(FileId);\nFileSystem._Storage = $.CompositeList(FileStorage);\nFileSystem._Metadata = $.CompositeList(FileMetadata);\n","/* -------------------------------------------------------------------\n\n ⚡ Storm Software - Powerlines\n\n This code was released as part of the Powerlines project. Powerlines\n is maintained by Storm Software under the Apache-2.0 license, and is\n free for commercial and private use. For more information, please visit\n our licensing page at https://stormsoftware.com/licenses/projects/powerlines.\n\n Website: https://stormsoftware.com\n Repository: https://github.com/storm-software/powerlines\n Documentation: https://docs.stormsoftware.com/projects/powerlines\n Contact: https://stormsoftware.com/contact\n\n SPDX-License-Identifier: Apache-2.0\n\n ------------------------------------------------------------------- */\n\nexport const DEFAULT_EXTENSIONS = [\n \"js\",\n \"ts\",\n \"cjs\",\n \"cts\",\n \"mjs\",\n \"mts\",\n \"tsx\",\n \"jsx\",\n \"json\",\n \"json5\",\n \"jsonc\",\n \"md\",\n \"mdx\"\n];\n","/* -------------------------------------------------------------------\n\n ⚡ Storm Software - Powerlines\n\n This code was released as part of the Powerlines project. Powerlines\n is maintained by Storm Software under the Apache-2.0 license, and is\n free for commercial and private use. For more information, please visit\n our licensing page at https://stormsoftware.com/licenses/projects/powerlines.\n\n Website: https://stormsoftware.com\n Repository: https://github.com/storm-software/powerlines\n Documentation: https://docs.stormsoftware.com/projects/powerlines\n Contact: https://stormsoftware.com/contact\n\n SPDX-License-Identifier: Apache-2.0\n\n ------------------------------------------------------------------- */\n\nimport { LogLevelLabel } from \"@storm-software/config-tools/types\";\nimport * as capnp from \"@stryke/capnp\";\nimport { toArray } from \"@stryke/convert/to-array\";\nimport {\n readFileBuffer,\n readFileBufferSync,\n writeFileBuffer\n} from \"@stryke/fs/buffer\";\nimport { existsSync } from \"@stryke/fs/exists\";\nimport {\n getResolutionCombinations,\n resolve,\n resolveSync\n} from \"@stryke/fs/resolve\";\nimport { murmurhash } from \"@stryke/hash\";\nimport { getUnique } from \"@stryke/helpers/get-unique\";\nimport { appendPath } from \"@stryke/path/append\";\nimport { correctPath, stripStars } from \"@stryke/path/correct-path\";\nimport {\n findFileExtensionSafe,\n findFileName,\n findFilePath,\n hasFileExtension\n} from \"@stryke/path/file-path-fns\";\nimport { globToRegex } from \"@stryke/path/glob-to-regex\";\nimport { isParentPath } from \"@stryke/path/is-parent-path\";\nimport { isAbsolutePath } from \"@stryke/path/is-type\";\nimport { joinPaths } from \"@stryke/path/join\";\nimport { replaceExtension, replacePath } from \"@stryke/path/replace\";\nimport { slash } from \"@stryke/path/slash\";\nimport { prettyBytes } from \"@stryke/string-format/pretty-bytes\";\nimport { isRegExp } from \"@stryke/type-checks/is-regexp\";\nimport { isSetObject } from \"@stryke/type-checks/is-set-object\";\nimport { isSetString } from \"@stryke/type-checks/is-set-string\";\nimport { isString } from \"@stryke/type-checks/is-string\";\nimport { AssetGlob } from \"@stryke/types/file\";\nimport { create, FlatCache } from \"flat-cache\";\nimport { Blob } from \"node:buffer\";\nimport { PathOrFileDescriptor } from \"node:fs\";\nimport { fileURLToPath } from \"node:url\";\nimport { ResolverFactory } from \"oxc-resolver\";\nimport { FileId, FileMetadata, FileSystem } from \"../../schemas/fs\";\nimport { replacePathTokens } from \"../plugin-utils\";\nimport { FileSystemStorageAdapter } from \"../storage/file-system\";\nimport { VirtualStorageAdapter } from \"../storage/virtual\";\nimport {\n Context,\n LogFn,\n ResolveOptions,\n StorageAdapter,\n StoragePort,\n StoragePreset,\n VirtualFileMetadata,\n VirtualFileSystemInterface,\n WriteOptions\n} from \"../types\";\nimport { extendLog, format } from \"../utils\";\nimport { DEFAULT_EXTENSIONS } from \"./helpers/constants\";\n\ninterface StorageAdapterState {\n adapter: StorageAdapter;\n relativeKey: string;\n base: string;\n}\n\nfunction toFilePath(path: PathOrFileDescriptor): string {\n return correctPath(slash(path?.toString() || \".\").replace(/^file:\\/\\//, \"\"));\n}\n\n/**\n * Checks if a given file id is valid based on the specified prefix.\n *\n * @param id - The file ID to check.\n * @param prefix - The prefix to use for built-in files. Default is \"powerlines\".\n * @returns `true` if the file ID is valid, otherwise `false`.\n */\nfunction isValidId(id: string, prefix = \"powerlines\"): boolean {\n return id.replace(/^\\\\0/, \"\").startsWith(`${prefix.replace(/:$/, \"\")}`);\n}\n\n/**\n * Formats a file id by removing the file extension and prepended runtime prefix.\n *\n * @param id - The file ID to format.\n * @param prefix - The prefix to use for built-in files. Default is \"powerlines\".\n * @returns The formatted file ID.\n */\nfunction normalizeId(id: string, prefix = \"powerlines\"): string {\n // return `${prefix.replace(/:$/, \"\")}:${toFilePath(id)\n // .replace(new RegExp(`^${prefix.replace(/:$/, \"\")}:`), \"\")\n // .replace(/^\\\\0/, \"\")\n // .replace(findFileDotExtensionSafe(toFilePath(id)), \"\")}`;\n\n return replaceExtension(toFilePath(id))\n .replace(/^\\\\0/, \"\")\n .replace(/^powerlines:/, \"\")\n .replace(new RegExp(`^${prefix.replace(/:$/, \"\")}:`), \"\");\n}\n\n/**\n * Normalizes a given path by resolving it against the project root, workspace root, and built-ins path.\n *\n * @param path - The path to normalize.\n * @param builtinsPath - The path to built-in files.\n * @param prefix - The prefix to use for built-in files. Default is \"powerlines\".\n * @returns The normalized path.\n */\nfunction normalizePath(\n path: string,\n builtinsPath: string,\n prefix = \"powerlines\"\n): string {\n return isAbsolutePath(path)\n ? path\n : isValidId(toFilePath(path), prefix)\n ? normalizeId(toFilePath(path), prefix).replace(\n new RegExp(`^${prefix.replace(/:$/, \"\")}:`),\n builtinsPath\n )\n : toFilePath(path);\n}\n\n/**\n * Normalizes glob patterns by resolving them against the workspace root.\n *\n * @param workspaceRoot - The root directory of the workspace.\n * @param patterns - The glob patterns to normalize.\n * @returns An array of normalized glob patterns.\n */\nfunction normalizeGlobPatterns(\n workspaceRoot: string,\n patterns:\n | string\n | Omit<AssetGlob, \"output\">\n | (string | Omit<AssetGlob, \"output\">)[]\n): string[] {\n return getUnique(\n toArray(patterns)\n .map(pattern => {\n if (\n isSetObject(pattern) &&\n (isSetString(pattern.input) || isSetString(pattern.glob))\n ) {\n return joinPaths(\n pattern.input || workspaceRoot,\n pattern.glob || \"**/*\"\n );\n } else if (!isSetString(pattern)) {\n return undefined;\n }\n\n return pattern;\n })\n .filter(isSetString)\n );\n}\n\n/**\n * Represents a virtual file system (VFS) that stores files and their associated metadata in virtual memory.\n *\n * @remarks\n * This class provides methods to manage virtual files, check their existence, retrieve their content, and manipulate the virtual file system. It allows for efficient file management and retrieval without relying on the actual file system.\n */\nexport class VirtualFileSystem implements VirtualFileSystemInterface {\n /**\n * A map of virtual file IDs to their associated metadata.\n */\n #metadata: Record<string, VirtualFileMetadata>;\n\n /**\n * A map of underlying file paths to their virtual file IDs.\n */\n #ids: Record<string, string>;\n\n /**\n * A map of virtual file IDs to their underlying file paths.\n */\n #paths: Record<string, string>;\n\n /**\n * The unified volume that combines the virtual file system with the real file system.\n *\n * @remarks\n * This volume allows for seamless access to both virtual and real files.\n */\n #storage: StoragePort;\n\n /**\n * The resolver factory used during module resolution within the virtual file system.\n *\n * @see https://github.com/oxc-project/oxc-resolver\n */\n #resolver!: ResolverFactory;\n\n /**\n * A cache for module resolution results.\n */\n #resolverCache!: FlatCache;\n\n /**\n * Indicator specifying if the virtual file system (VFS) is disposed\n */\n #isDisposed = false;\n\n /**\n * The context of the virtual file system.\n */\n #context: Context;\n\n /**\n * The file system's logging function.\n */\n #log: LogFn;\n\n /**\n * Normalizes a given module id by resolving it against the built-ins path.\n *\n * @param id - The module id to normalize.\n * @returns The normalized module id.\n */\n #normalizeId(id: string): string {\n let normalized = id;\n if (isParentPath(normalized, this.#context.builtinsPath)) {\n normalized = replacePath(normalized, this.#context.builtinsPath);\n }\n\n return normalizeId(normalized, this.#context.config.framework);\n }\n\n /**\n * Normalizes a given path by resolving it against the project root, workspace root, and built-ins path.\n *\n * @param path - The path to normalize.\n * @returns The normalized path.\n */\n #normalizePath(path: string): string {\n return normalizePath(\n path.includes(\"{\") || path.includes(\"}\")\n ? replacePathTokens(this.#context, path)\n : path,\n this.#context.builtinsPath,\n this.#context.config.framework\n );\n }\n\n /**\n * Gets the storage adapter and relative key for a given key.\n *\n * @remarks\n * The `key` can be either a path or a storage adapter name.\n *\n * @param key - The key to get the storage adapter for.\n * @returns The storage adapter and relative key for the given key.\n */\n #getStorage(key: string, preset?: StoragePreset): StorageAdapterState {\n const path = this.resolveSync(this.#normalizePath(key)) || key;\n for (const base of Object.keys(this.#storage)\n .filter(Boolean)\n .sort()\n .reverse()) {\n if (\n (path === base || isParentPath(path, base)) &&\n (!preset ||\n this.#storage[base]?.preset?.toLowerCase() === preset.toLowerCase())\n ) {\n return {\n base,\n relativeKey: replacePath(path, base),\n adapter: this.#storage[base]!\n };\n }\n }\n\n if (\n !preset ||\n this.#storage[\"\"]?.preset?.toLowerCase() === preset.toLowerCase()\n ) {\n return {\n base: \"\",\n relativeKey: path,\n adapter: this.#storage[\"\"]!\n };\n }\n\n this.#storage[path] =\n preset === \"virtual\"\n ? new VirtualStorageAdapter(this.#context, {\n base: path\n })\n : new FileSystemStorageAdapter(this.#context, {\n base: path\n });\n\n return {\n base: path,\n relativeKey: \"\",\n adapter: this.#storage[path]\n };\n }\n\n /**\n * Gets all storage adapters that match a given base key.\n *\n * @param base - The base key to match storage adapters against.\n * @param includeParent - Whether to include parent storage adapters.\n * @returns An array of storage adapters that match the given base key.\n */\n #getStorages(base = \"\", includeParent = false) {\n const baseKey = this.resolveSync(base) || base;\n\n return Object.keys(this.#storage)\n .sort()\n .reverse()\n .filter(\n key =>\n isParentPath(key, baseKey) ||\n (includeParent && isParentPath(baseKey, key)) ||\n (baseKey.includes(\"*\") &&\n (isParentPath(stripStars(baseKey), key) ||\n globToRegex(replaceExtension(baseKey)).test(key)))\n )\n .map(key => ({\n relativeBase:\n baseKey.length > key.length ? baseKey.slice(key.length) : undefined,\n base: key,\n adapter: this.#storage[key]!\n }));\n }\n\n /**\n * A helper function to resolve modules in the virtual file system (VFS).\n *\n * @remarks\n * This function can be used to resolve modules relative to the project root directory.\n *\n * @example\n * ```ts\n * const resolved = await context.resolvePath(\"some-module\", \"/path/to/importer\");\n * ```\n *\n * @param id - The module to resolve.\n * @param importer - An optional path to the importer module.\n * @param options - Additional resolution options.\n * @returns A promise that resolves to the resolved module path.\n */\n #innerResolve = async (\n id: string,\n importer?: string,\n options: ResolveOptions = {}\n ): Promise<string | undefined> => {\n let path = id;\n if (path.includes(\"{\") || path.includes(\"}\")) {\n path = replacePathTokens(this.#context, path);\n }\n\n if (options.skipAlias !== true) {\n path = this.resolveAlias(path);\n }\n\n if (\n isAbsolutePath(path) &&\n (!options.isFile || !(await this.isDirectory(path)))\n ) {\n return path;\n }\n\n const resolverCacheKey = murmurhash({\n path: this.#normalizeId(path),\n importer,\n options\n });\n\n let result!: string | undefined;\n if (!this.#context.config.skipCache) {\n result = this.resolverCache.get<string | undefined>(resolverCacheKey);\n if (result) {\n return result;\n }\n }\n\n result = this.paths[this.#normalizeId(path)];\n if (!result) {\n const paths = options.paths ?? [];\n if (importer && !paths.includes(importer)) {\n paths.push(importer);\n }\n\n if (!importer) {\n paths.push(this.#context.workspaceConfig.workspaceRoot);\n paths.push(\n appendPath(\n this.#context.config.root,\n this.#context.workspaceConfig.workspaceRoot\n )\n );\n paths.push(\n appendPath(\n joinPaths(this.#context.config.root, \"src\"),\n this.#context.workspaceConfig.workspaceRoot\n )\n );\n }\n\n paths.push(\n ...(\n Object.keys(this.#context.tsconfig?.options?.paths ?? {})\n .filter(tsconfigPath =>\n path.startsWith(tsconfigPath.replace(/\\*$/, \"\"))\n )\n .map(\n tsconfigPath =>\n this.#context.tsconfig?.options?.paths?.[tsconfigPath]\n )\n .flat()\n .filter(Boolean) as string[]\n ).map(tsconfigPath =>\n appendPath(tsconfigPath, this.#context.workspaceConfig.workspaceRoot)\n )\n );\n\n for (const combination of getResolutionCombinations(path, { paths })) {\n const { relativeKey, adapter } = this.#getStorage(combination);\n if (await adapter.exists(relativeKey)) {\n result = combination;\n break;\n }\n }\n\n if (!result) {\n try {\n result = await resolve(path, { ...options, paths });\n } catch {\n // Do nothing\n }\n\n if (!result) {\n let index = 0;\n do {\n const resolveResult = await this.resolver.async(\n (paths.length > index ? paths[index] : undefined) ||\n this.#context.config.root,\n path\n );\n if (resolveResult.path) {\n result = resolveResult.path;\n }\n\n index++;\n } while (!result && index < paths.length);\n }\n }\n }\n\n if (result && !this.#context.config.skipCache) {\n this.resolverCache.set(resolverCacheKey, result);\n }\n\n return result;\n };\n\n /**\n * A synchronous helper function to resolve modules using the Jiti resolver\n *\n * @remarks\n * This function can be used to resolve modules relative to the project root directory.\n *\n * @example\n * ```ts\n * const resolvedPath = context.resolveSync(\"some-module\", \"/path/to/importer\");\n * ```\n *\n * @param id - The module to resolve.\n * @param importer - An optional path to the importer module.\n * @param options - Additional resolution options.\n * @returns The resolved module path.\n */\n #innerResolveSync = (\n id: string,\n importer?: string,\n options: ResolveOptions = {}\n ): string | undefined => {\n let path = id;\n if (path.includes(\"{\") || path.includes(\"}\")) {\n path = replacePathTokens(this.#context, path);\n }\n\n if (options.skipAlias !== true) {\n path = this.resolveAlias(path);\n }\n\n if (\n isAbsolutePath(path) &&\n (!options.isFile || !this.isDirectorySync(path))\n ) {\n return path;\n }\n\n let result!: string | undefined;\n if (!this.#context.config.skipCache) {\n result = this.resolverCache.get<string | undefined>(\n this.#normalizeId(path)\n );\n if (result) {\n return result;\n }\n }\n\n result = this.paths[this.#normalizeId(path)];\n if (!result) {\n const paths = options.paths ?? [];\n if (importer && !paths.includes(importer)) {\n paths.push(importer);\n }\n\n if (!importer) {\n paths.push(this.#context.workspaceConfig.workspaceRoot);\n paths.push(\n appendPath(\n this.#context.config.root,\n this.#context.workspaceConfig.workspaceRoot\n )\n );\n paths.push(\n appendPath(\n joinPaths(this.#context.config.root, \"src\"),\n this.#context.workspaceConfig.workspaceRoot\n )\n );\n }\n\n paths.push(\n ...(\n Object.keys(this.#context.tsconfig?.options?.paths ?? {})\n .filter(tsconfigPath =>\n path.startsWith(tsconfigPath.replace(/\\*$/, \"\"))\n )\n .map(\n tsconfigPath =>\n this.#context.tsconfig?.options?.paths?.[tsconfigPath]\n )\n .flat()\n .filter(Boolean) as string[]\n ).map(tsconfigPath =>\n appendPath(tsconfigPath, this.#context.workspaceConfig.workspaceRoot)\n )\n );\n\n for (const combination of getResolutionCombinations(path, { paths })) {\n const { relativeKey, adapter } = this.#getStorage(combination);\n if (adapter.existsSync(relativeKey)) {\n result = combination;\n break;\n }\n }\n\n if (!result) {\n try {\n result = resolveSync(path, { ...options, paths });\n } catch {\n // Do nothing\n }\n\n if (!result) {\n let index = 0;\n do {\n const resolveResult = this.resolver.sync(\n (paths.length > index ? paths[index] : undefined) ||\n this.#context.config.root,\n path\n );\n if (resolveResult.path) {\n result = resolveResult.path;\n }\n\n index++;\n } while (!result && index < paths.length);\n }\n }\n }\n\n if (result && !this.#context.config.skipCache) {\n this.resolverCache.set(this.#normalizeId(path), result);\n }\n\n return result;\n };\n\n /**\n * Creates a virtual file system (VFS) that is backed up to a Cap'n Proto message buffer.\n *\n * @param context - The context of the virtual file system, typically containing options and logging functions.\n * @returns A promise that resolves to a new virtual file system instance.\n */\n public static async create(context: Context): Promise<VirtualFileSystem> {\n context.debug(\n \"Starting virtual file system (VFS) initialization processes...\"\n );\n\n let result!: VirtualFileSystem;\n if (\n !context.config.skipCache &&\n existsSync(joinPaths(context.dataPath, \"fs.bin\"))\n ) {\n const buffer = await readFileBuffer(\n joinPaths(context.dataPath, \"fs.bin\")\n );\n\n const message = new capnp.Message(buffer, false);\n const fs = message.getRoot(FileSystem);\n\n result = new VirtualFileSystem(context, fs);\n\n if (fs._hasStorage() && fs.storage.length > 0) {\n await Promise.all(\n fs.storage.values().map(async file => {\n if (file.path && file.code) {\n let id: FileId | undefined;\n if (fs._hasIds()) {\n id = fs.ids.find((fileId: FileId) => fileId.path === file.path);\n }\n\n let metadata: FileMetadata | undefined;\n if (fs._hasMetadata()) {\n metadata = fs.metadata.find(\n (meta: FileMetadata) =>\n meta.id === result.#normalizeId(id?.id ?? file.path)\n );\n }\n\n await result.write(file.path, file.code, {\n meta: {\n id: result.#normalizeId(id?.id ?? metadata?.id ?? file.path),\n type: metadata?.type || \"normal\",\n properties: metadata?._hasProperties()\n ? metadata?.properties.values().reduce(\n (ret, kvp) => {\n ret[kvp.key] = kvp.value;\n return ret;\n },\n {} as Record<string, string>\n )\n : undefined,\n timestamp: metadata?.timestamp\n }\n });\n }\n })\n );\n }\n } else {\n const message = new capnp.Message();\n result = new VirtualFileSystem(context, message.initRoot(FileSystem));\n }\n\n result.#log(\n LogLevelLabel.DEBUG,\n \"Successfully completed virtual file system (VFS) initialization.\"\n );\n\n return result;\n }\n\n /**\n * Synchronously creates a virtual file system (VFS) that is backed up to a Cap'n Proto message buffer.\n *\n * @param context - The context of the virtual file system, typically containing options and logging functions.\n * @returns A new virtual file system instance.\n */\n public static createSync(context: Context): VirtualFileSystem {\n context.debug(\n \"Starting virtual file system (VFS) initialization processes...\"\n );\n\n let result!: VirtualFileSystem;\n if (\n !context.config.skipCache &&\n existsSync(joinPaths(context.dataPath, \"fs.bin\"))\n ) {\n const buffer = readFileBufferSync(joinPaths(context.dataPath, \"fs.bin\"));\n\n const message = new capnp.Message(buffer, false);\n const fs = message.getRoot(FileSystem);\n\n result = new VirtualFileSystem(context, fs);\n\n if (fs._hasStorage() && fs.storage.length > 0) {\n fs.storage.values().forEach(file => {\n if (file.path && file.code) {\n let id: FileId | undefined;\n if (fs._hasIds()) {\n id = fs.ids.find((fileId: FileId) => fileId.path === file.path);\n }\n\n let metadata: FileMetadata | undefined;\n if (fs._hasMetadata()) {\n metadata = fs.metadata.find(\n (meta: FileMetadata) =>\n meta.id === result.#normalizeId(id?.id ?? file.path)\n );\n }\n\n result.writeSync(file.path, file.code, {\n meta: {\n id: result.#normalizeId(id?.id ?? metadata?.id ?? file.path),\n type: metadata?.type,\n properties: metadata?._hasProperties()\n ? metadata?.properties.values().reduce(\n (ret, kvp) => {\n ret[kvp.key] = kvp.value;\n return ret;\n },\n {} as Record<string, string>\n )\n : undefined,\n timestamp: metadata?.timestamp\n }\n });\n }\n });\n }\n } else {\n const message = new capnp.Message();\n result = new VirtualFileSystem(context, message.initRoot(FileSystem));\n }\n\n result.#log(\n LogLevelLabel.DEBUG,\n \"Successfully completed virtual file system (VFS) initialization.\"\n );\n\n return result;\n }\n\n /**\n * A map of file ids to their metadata.\n */\n public get metadata(): Record<string, VirtualFileMetadata> {\n return new Proxy(this.#metadata, {\n get: (target, prop: string) => {\n return target[this.#normalizeId(prop)];\n },\n set: (target, prop: string, value) => {\n target[this.#normalizeId(prop)] = value;\n return true;\n },\n deleteProperty: (target, prop: string) => {\n delete target[this.#normalizeId(prop)];\n return true;\n },\n has: (target, prop: string) => {\n return this.#normalizeId(prop) in target;\n },\n ownKeys: target => {\n return getUnique(\n Reflect.ownKeys(target).map(key => this.#normalizeId(key as string))\n );\n }\n });\n }\n\n /**\n * A map of file paths to their module ids.\n */\n public get ids(): Record<string, string> {\n return new Proxy(this.#ids, {\n get: (target, prop: string) => {\n return target[this.#normalizePath(prop)];\n },\n set: (target, prop: string, value) => {\n target[this.#normalizePath(prop)] = value;\n return true;\n },\n deleteProperty: (target, prop: string) => {\n delete target[this.#normalizePath(prop)];\n return true;\n },\n has: (target, prop: string) => {\n return this.#normalizePath(prop) in target;\n },\n ownKeys: target => {\n return getUnique(\n Reflect.ownKeys(target).map(key => this.#normalizePath(key as string))\n );\n }\n });\n }\n\n /**\n * A map of module ids to their file paths.\n */\n public get paths(): Record<string, string> {\n return new Proxy(this.#paths, {\n get: (target, prop: string) => {\n return target[this.#normalizeId(prop)];\n },\n set: (target, prop: string, value) => {\n target[this.#normalizeId(prop)] = value;\n return true;\n },\n deleteProperty: (target, prop: string) => {\n delete target[this.#normalizeId(prop)];\n return true;\n },\n has: (target, prop: string) => {\n return this.#normalizeId(prop) in target;\n },\n ownKeys: target => {\n return getUnique(\n Reflect.ownKeys(target).map(key => this.#normalizeId(key as string))\n );\n }\n });\n }\n\n /**\n * Gets the resolver cache.\n */\n protected get resolverCache(): FlatCache {\n if (!this.#resolverCache) {\n this.#resolverCache = create({\n cacheId: \"module-resolution\",\n cacheDir: this.#context.cachePath,\n ttl: 60 * 60 * 1000,\n lruSize: 5000,\n persistInterval: 100\n });\n }\n\n return this.#resolverCache;\n }\n\n /**\n * The resolver factory used during module resolution within the virtual file system.\n *\n * @remarks\n * This resolver is configured with the workspace root, project root, TypeScript configuration, alias mappings, and other resolution options specified in the context. It is lazily initialized on first access to optimize performance.\n *\n * @see https://github.com/oxc-project/oxc-resolver\n */\n protected get resolver(): ResolverFactory {\n if (!this.#resolver) {\n this.#resolver = new ResolverFactory({\n roots: [\n this.#context.workspaceConfig.workspaceRoot,\n appendPath(\n this.#context.config.root,\n this.#context.workspaceConfig.workspaceRoot\n )\n ],\n tsconfig: {\n configFile: this.#context.tsconfig.tsconfigFilePath,\n references:\n this.#context.tsconfig.projectReferences &&\n this.#context.tsconfig.projectReferences.length > 0\n ? \"auto\"\n : undefined\n },\n alias: Object.fromEntries(\n Object.entries(this.#context.alias).map(([key, value]) => [\n key,\n [value]\n ])\n ),\n extensions: this.#context.config.resolve.extensions,\n mainFields: this.#context.config.resolve.mainFields,\n conditionNames: this.#context.config.resolve.conditions,\n symlinks: this.#context.config.resolve.preserveSymlinks,\n allowPackageExportsInDirectoryResolve: true\n });\n }\n\n return this.#resolver;\n }\n\n /**\n * Creates a new instance of the {@link VirtualFileSystem}.\n *\n * @param context - The context of the virtual file system, typically containing options and logging functions.\n * @param fs - A buffer containing the serialized virtual file system data.\n */\n private constructor(context: Context, fs: FileSystem) {\n this.#context = context;\n this.#storage = { \"\": new FileSystemStorageAdapter(context) };\n\n if (isSetObject(this.#context.config.output.storage)) {\n this.#storage = {\n ...this.#storage,\n ...this.#context.config.output.storage\n };\n }\n\n this.#storage.virtual ??= new VirtualStorageAdapter(context, {\n base: \"/_virtual\"\n });\n\n this.#storage[this.#context.config.output.outputPath] ??=\n new FileSystemStorageAdapter(context, {\n base: this.#context.config.output.outputPath\n });\n this.#storage[this.#context.config.output.buildPath] ??=\n new FileSystemStorageAdapter(context, {\n base: this.#context.config.output.buildPath\n });\n\n if (this.#context.config.output.storage !== \"fs\") {\n this.#storage[this.#context.artifactsPath] ??= new VirtualStorageAdapter(\n context,\n {\n base: this.#context.artifactsPath\n }\n );\n this.#storage[this.#context.builtinsPath] ??= new VirtualStorageAdapter(\n context,\n {\n base: this.#context.builtinsPath\n }\n );\n this.#storage[this.#context.entryPath] ??= new VirtualStorageAdapter(\n context,\n {\n base: this.#context.entryPath\n }\n );\n }\n\n this.#metadata = {} as Record<string, VirtualFileMetadata>;\n if (fs._hasMetadata()) {\n this.#metadata = fs.metadata.values().reduce(\n (ret, metadata) => {\n ret[metadata.id] = {\n id: metadata.id,\n type: metadata.type,\n timestamp: metadata.timestamp ?? Date.now(),\n properties: metadata._hasProperties()\n ? metadata.properties.values().reduce(\n (ret, item) => {\n ret[item.key] = item.value;\n return ret;\n },\n {} as Record<string, string>\n )\n : {}\n };\n\n return ret;\n },\n {} as Record<string, VirtualFileMetadata>\n );\n }\n\n this.#ids = {} as Record<string, string>;\n this.#paths = {} as Record<string, string>;\n\n if (fs._hasIds()) {\n this.#ids = fs.ids.values().reduce(\n (ret, identifier) => {\n ret[identifier.path] ??= identifier.id;\n\n return ret;\n },\n {} as Record<string, string>\n );\n\n this.#paths = fs.ids.values().reduce(\n (ret, identifier) => {\n ret[identifier.id] ??= identifier.path;\n return ret;\n },\n {} as Record<string, string>\n );\n }\n\n this.#log = extendLog(this.#context.log, \"file-system\");\n }\n\n /**\n * Asynchronously checks if a file exists in the virtual file system (VFS).\n *\n * @param path - The path to the file.\n * @returns A promise that resolves to `true` if the file exists, otherwise `false`.\n */\n public async exists(path: string): Promise<boolean> {\n const { relativeKey, adapter } = this.#getStorage(path);\n\n return adapter.exists(relativeKey);\n }\n\n /**\n * Synchronously checks if a file exists in the virtual file system (VFS).\n *\n * @param path - The path to the file.\n * @returns `true` if the file exists, otherwise `false`.\n */\n public existsSync(path: string): boolean {\n const { relativeKey, adapter } = this.#getStorage(path);\n\n return adapter.existsSync(relativeKey);\n }\n\n /**\n * Checks if a file is virtual in the virtual file system (VFS).\n *\n * @param path - The path to the file.\n * @returns `true` if the file is virtual, otherwise `false`.\n */\n public isVirtual(path: string): boolean {\n const resolved = this.resolveSync(path);\n if (!resolved) {\n return false;\n }\n\n return this.#getStorage(resolved)?.adapter?.preset === \"virtual\";\n }\n\n /**\n * Checks if a path is a directory in the virtual file system (VFS).\n *\n * @param path - The path to check.\n * @returns `true` if the path is a directory, otherwise `false`.\n */\n public isDirectorySync(path: string): boolean {\n const resolved = this.resolveSync(path);\n if (!resolved) {\n return false;\n }\n\n return !!(\n this.existsSync(resolved) &&\n this.#getStorage(resolved)?.adapter?.isDirectorySync(resolved)\n );\n }\n\n /**\n * Checks if a path is a directory in the virtual file system (VFS).\n *\n * @param path - The path to check.\n * @returns `true` if the path is a directory, otherwise `false`.\n */\n public async isDirectory(path: string): Promise<boolean> {\n const resolved = await this.resolve(path);\n if (!resolved) {\n return false;\n }\n\n return !!(\n (await this.exists(resolved)) &&\n (await this.#getStorage(resolved)?.adapter?.isDirectory(resolved))\n );\n }\n\n /**\n * Checks if a path is a file in the virtual file system (VFS).\n *\n * @param path - The path to check.\n * @returns `true` if the path is a file, otherwise `false`.\n */\n public isFileSync(path: string): boolean {\n const resolved = this.resolveSync(path);\n if (!resolved) {\n return false;\n }\n\n return this.#getStorage(resolved)?.adapter?.isFileSync(resolved) ?? false;\n }\n\n /**\n * Checks if a path is a file in the virtual file system (VFS).\n *\n * @param path - The path to check.\n * @returns `true` if the path is a file, otherwise `false`.\n */\n public async isFile(path: string): Promise<boolean> {\n const resolved = await this.resolve(path);\n if (!resolved) {\n return false;\n }\n\n return (\n (await this.#getStorage(resolved)?.adapter?.isFile(resolved)) ?? false\n );\n }\n\n /**\n * Lists files in a given path.\n *\n * @param path - The path to list files from.\n * @returns An array of file names in the specified path.\n */\n public listSync(path: string): string[] {\n let resolvedPath = path;\n if (resolvedPath.includes(\"*\")) {\n this.#log(\n LogLevelLabel.WARN,\n `Invoking \"listSync\" with a glob pattern is not supported. It is likely you meant to use \"globSync\". Path: ${path}`\n );\n resolvedPath = stripStars(resolvedPath);\n }\n\n return getUnique(\n this.#getStorages(resolvedPath, true)\n .map(storage =>\n storage.adapter.listSync(\n storage.relativeBase\n ? storage.base\n ? appendPath(storage.relativeBase, storage.base)\n : storage.relativeBase\n : storage.base\n )\n )\n .flat()\n .filter(Boolean)\n );\n }\n\n /**\n * Lists files in a given path.\n *\n * @param path - The path to list files from.\n * @returns An array of file names in the specified path.\n */\n public async list(path: string): Promise<string[]> {\n let resolvedPath = path;\n if (resolvedPath.includes(\"*\")) {\n this.#log(\n LogLevelLabel.WARN,\n `Invoking \"list\" with a glob pattern is not supported. It is likely you meant to use \"glob\". Path: ${path}`\n );\n resolvedPath = stripStars(resolvedPath);\n }\n\n return getUnique(\n (\n await Promise.all(\n this.#getStorages(resolvedPath, true).map(async storage =>\n storage.adapter.list(\n storage.relativeBase\n ? storage.base\n ? appendPath(storage.relativeBase, storage.base)\n : storage.relativeBase\n : storage.base\n )\n )\n )\n )\n .flat()\n .filter(Boolean)\n );\n }\n\n /**\n * Removes a file in the virtual file system (VFS).\n *\n * @param path - The path to create the directory at.\n */\n public async remove(path: string): Promise<void> {\n const normalizedPath = this.#normalizePath(path);\n this.#log(LogLevelLabel.TRACE, `Removing file: ${normalizedPath}`);\n\n const { relativeKey, adapter } = this.#getStorage(normalizedPath);\n\n if (hasFileExtension(normalizedPath)) {\n await adapter.remove(relativeKey);\n } else {\n await adapter.clear(relativeKey);\n }\n\n const id = this.#ids[normalizedPath];\n if (id && this.#metadata[id]) {\n delete this.#metadata[id];\n delete this.#ids[normalizedPath];\n delete this.#paths[id];\n }\n }\n\n /**\n * Removes a file in the virtual file system (VFS).\n *\n * @param path - The path to create the directory at.\n */\n public removeSync(path: string) {\n const normalizedPath = this.#normalizePath(path);\n this.#log(LogLevelLabel.TRACE, `Removing file: ${normalizedPath}`);\n\n const { relativeKey, adapter } = this.#getStorage(normalizedPath);\n\n if (hasFileExtension(normalizedPath)) {\n adapter.removeSync(relativeKey);\n } else {\n adapter.clearSync(relativeKey);\n }\n\n const id = this.#ids[normalizedPath];\n if (id && this.#metadata[id]) {\n delete this.#metadata[id];\n delete this.#ids[normalizedPath];\n delete this.#paths[id];\n }\n }\n\n /**\n * Glob files in the virtual file system (VFS) based on the provided pattern(s).\n *\n * @param patterns - A pattern (or multiple patterns) to use to determine the file paths to return\n * @returns An array of file paths matching the provided pattern(s)\n */\n public async glob(\n patterns:\n | string\n | Omit<AssetGlob, \"output\">\n | (string | Omit<AssetGlob, \"output\">)[]\n ): Promise<string[]> {\n const results: string[] = [];\n for (const pattern of normalizeGlobPatterns(\n this.#context.workspaceConfig.workspaceRoot,\n patterns\n )) {\n const normalized = this.#normalizePath(pattern);\n if (!/[*?[\\]{}]/.test(normalized) && !normalized.includes(\"*\")) {\n if (this.isDirectorySync(normalized)) {\n results.push(...(await this.list(normalized)));\n } else {\n const resolved = await this.resolve(normalized);\n if (resolved && !results.includes(resolved)) {\n results.push(resolved);\n }\n }\n } else {\n const absPattern = isAbsolutePath(normalized)\n ? normalized\n : this.#normalizePath(\n appendPath(\n normalized,\n this.#context.workspaceConfig.workspaceRoot\n )\n );\n\n await Promise.all(\n (await this.list(stripStars(absPattern))).map(async file => {\n if (globToRegex(absPattern).test(file)) {\n const resolved = await this.resolve(file);\n if (resolved && !results.includes(resolved)) {\n results.push(resolved);\n }\n }\n })\n );\n }\n }\n\n return results;\n }\n\n /**\n * Synchronously glob files in the virtual file system (VFS) based on the provided pattern(s).\n *\n * @param patterns - A pattern (or multiple patterns) to use to determine the file paths to return\n * @returns An array of file paths matching the provided pattern(s)\n */\n public globSync(\n patterns:\n | string\n | Omit<AssetGlob, \"output\">\n | (string | Omit<AssetGlob, \"output\">)[]\n ): string[] {\n const results: string[] = [];\n for (const pattern of normalizeGlobPatterns(\n this.#context.workspaceConfig.workspaceRoot,\n patterns\n )) {\n const normalized = this.#normalizePath(pattern);\n if (!/[*?[\\]{}]/.test(normalized) && !normalized.includes(\"*\")) {\n if (this.isDirectorySync(normalized)) {\n results.push(...this.listSync(normalized));\n } else {\n const resolved = this.resolveSync(normalized);\n if (resolved && !results.includes(resolved)) {\n results.push(resolved);\n }\n }\n } else {\n const absPattern = isAbsolutePath(normalized)\n ? normalized\n : this.#normalizePath(\n appendPath(\n normalized,\n this.#context.workspaceConfig.workspaceRoot\n )\n );\n\n const files = this.listSync(stripStars(absPattern));\n for (const file of files) {\n const regex = globToRegex(absPattern);\n if (regex.test(file)) {\n const resolved = this.resolveSync(file);\n if (resolved && !results.includes(resolved)) {\n results.push(resolved);\n }\n }\n }\n }\n }\n\n return results;\n }\n\n /**\n * Copies a file from one path to another in the virtual file system (VFS).\n *\n * @param srcPath - The source path to copy\n * @param destPath - The destination path to copy to\n */\n public async copy(\n srcPath: string | URL | Omit<AssetGlob, \"output\">,\n destPath: string | URL\n ) {\n const src = srcPath instanceof URL ? fileURLToPath(srcPath) : srcPath;\n const dest = destPath instanceof URL ? fileURLToPath(destPath) : destPath;\n\n if (\n (!isSetString(src) && (!isSetObject(src) || !isSetString(src.input))) ||\n !isSetString(dest)\n ) {\n return;\n }\n\n const sourceStr = isString(src)\n ? src\n : src.input\n ? src.input\n : this.#context.workspaceConfig.workspaceRoot;\n const source = await this.resolve(sourceStr);\n if (!source) {\n return;\n }\n\n if (\n this.isDirectorySync(source) ||\n (isSetString(src) && src.includes(\"*\")) ||\n (isSetObject(src) && isSetString(src.glob))\n ) {\n await Promise.all(\n (await this.glob(src)).map(async file => {\n return this.copy(\n file,\n appendPath(replacePath(file, sourceStr), dest)\n );\n })\n );\n } else {\n const content = await this.read(source);\n if (content !== undefined) {\n await this.write(this.#normalizePath(dest), content, {\n skipFormat: true\n });\n }\n }\n }\n\n /**\n * Synchronously copies a file from one path to another in the virtual file system (VFS).\n *\n * @param srcPath - The source path to copy\n * @param destPath - The destination path to copy to\n */\n public copySync(\n srcPath: string | URL | Omit<AssetGlob, \"output\">,\n destPath: string | URL\n ) {\n const src = srcPath instanceof URL ? fileURLToPath(srcPath) : srcPath;\n const dest = destPath instanceof URL ? fileURLToPath(destPath) : destPath;\n\n if (\n (!isSetString(src) && (!isSetObject(src) || !isSetString(src.input))) ||\n !isSetString(dest)\n ) {\n return;\n }\n\n const sourceStr = isString(src)\n ? src\n : src.input\n ? src.input\n : this.#context.workspaceConfig.workspaceRoot;\n const source = this.resolveSync(sourceStr);\n if (!source) {\n return;\n }\n\n if (\n this.isDirectorySync(source) ||\n (isSetString(src) && src.includes(\"*\")) ||\n (isSetObject(src) && isSetString(src.glob))\n ) {\n this.globSync(src).map(file => {\n return this.copySync(\n file,\n appendPath(findFilePath(replacePath(file, sourceStr)), dest)\n );\n });\n } else {\n const content = this.readSync(source);\n if (content !== undefined) {\n this.writeSync(\n this.#normalizePath(\n hasFileExtension(dest)\n ? dest\n : appendPath(findFileName(source), dest)\n ),\n content,\n { skipFormat: true }\n );\n }\n }\n }\n\n /**\n * Moves a file (or files) from one path to another in the virtual file system (VFS).\n *\n * @param srcPath - The source path to move\n * @param destPath - The destination path to move to\n */\n public async move(srcPath: string, destPath: string) {\n if (hasFileExtension(srcPath)) {\n await this.copy(srcPath, destPath);\n await this.remove(srcPath);\n } else {\n await Promise.all(\n (await this.list(srcPath)).map(async file => {\n await this.copy(file, destPath);\n await this.remove(file);\n })\n );\n }\n }\n\n /**\n * Synchronously moves a file (or files) from one path to another in the virtual file system (VFS).\n *\n * @param srcPath - The source path to move\n * @param destPath - The destination path to move to\n */\n public moveSync(srcPath: string, destPath: string) {\n if (hasFileExtension(srcPath)) {\n this.copySync(srcPath, destPath);\n this.removeSync(srcPath);\n } else {\n this.listSync(srcPath).forEach(file => {\n this.copySync(file, destPath);\n this.removeSync(file);\n });\n }\n }\n\n /**\n * Asynchronously reads a file from the virtual file system (VFS).\n *\n * @param path - The path or ID of the file to read.\n * @returns A promise that resolves to the contents of the file as a string, or undefined if the file does not exist.\n */\n public async read(path: string): Promise<string | undefined> {\n const filePath = await this.resolve(path, undefined, { isFile: true });\n if (!filePath || !this.existsSync(filePath)) {\n return undefined;\n }\n\n const { adapter } = this.#getStorage(filePath);\n this.#log(LogLevelLabel.TRACE, `Reading ${adapter.name} file: ${filePath}`);\n\n return (await adapter.get(filePath)) ?? undefined;\n }\n\n /**\n * Synchronously reads a file from the virtual file system (VFS).\n *\n * @param path - The path or ID of the file to read.\n * @returns The contents of the file as a string, or undefined if the file does not exist.\n */\n public readSync(path: string): string | undefined {\n const filePath = this.resolveSync(path, undefined, { isFile: true });\n if (!filePath || !this.existsSync(filePath)) {\n return undefined;\n }\n\n const { adapter } = this.#getStorage(filePath);\n this.#log(LogLevelLabel.TRACE, `Reading ${adapter.name} file: ${filePath}`);\n\n return adapter.getSync(filePath) ?? undefined;\n }\n\n /**\n * Writes a file to the virtual file system (VFS).\n *\n * @param path - The path to the file.\n * @param data - The contents of the file.\n * @param options - Optional parameters for writing the file.\n * @returns A promise that resolves when the file is written.\n */\n public async write(\n path: string,\n data: string = \"\",\n options: WriteOptions = {}\n ): Promise<void> {\n const meta = options.meta ?? {};\n const resolvedPath =\n (await this.resolve(this.#normalizePath(path))) || path;\n\n const { relativeKey, adapter } = this.#getStorage(\n resolvedPath,\n options.storage as StoragePreset\n );\n\n this.#log(\n LogLevelLabel.TRACE,\n `Writing ${resolvedPath} to ${\n adapter.name === \"virtual\"\n ? \"the virtual file system\"\n : adapter.name === \"file-system\"\n ? \"the local file system\"\n : adapter.name\n } (size: ${prettyBytes(new Blob(toArray(data)).size)})`\n );\n\n let code = data;\n try {\n if (!options.skipFormat) {\n code = await format(this.#context, resolvedPath, data);\n }\n } catch (err) {\n // Only warn about formatting errors for certain file types\n if (\n DEFAULT_EXTENSIONS.includes(\n findFileExtensionSafe(resolvedPath, {\n fullExtension: true\n })\n )\n ) {\n this.#log(\n LogLevelLabel.WARN,\n `Failed to format file ${resolvedPath} before writing: ${(err as Error).message}`\n );\n }\n code = data;\n }\n\n this.#log(\n LogLevelLabel.TRACE,\n `Writing ${resolvedPath} to ${\n adapter.name === \"virtual\"\n ? \"the virtual file system\"\n : adapter.name === \"file-system\"\n ? \"the local file system\"\n : adapter.name\n } (size: ${prettyBytes(new Blob(toArray(code)).size)})`\n );\n\n const id = this.#normalizeId(meta.id || resolvedPath);\n this.metadata[id] = {\n type: \"normal\",\n timestamp: Date.now(),\n ...(this.metadata[id] ?? {}),\n ...meta\n } as VirtualFileMetadata;\n this.paths[id] = resolvedPath;\n this.ids[resolvedPath] = id;\n\n return adapter.set(relativeKey, code);\n }\n\n /**\n * Synchronously writes a file to the virtual file system (VFS).\n *\n * @param path - The file to write.\n * @param data - The contents of the file.\n * @param options - Optional parameters for writing the file.\n */\n public writeSync(\n path: string,\n data: string = \"\",\n options: WriteOptions = {}\n ): void {\n const meta = options.meta ?? {};\n const resolvedPath = this.resolveSync(this.#normalizePath(path)) || path;\n\n const { relativeKey, adapter } = this.#getStorage(\n resolvedPath,\n options.storage as StoragePreset\n );\n\n this.#log(\n LogLevelLabel.TRACE,\n `Writing ${resolvedPath} file to ${\n adapter.name === \"virtual\"\n ? \"the virtual file system\"\n : adapter.name === \"file-system\"\n ? \"the local file system\"\n : adapter.name\n } (size: ${prettyBytes(new Blob(toArray(data)).size)})`\n );\n\n const id = this.#normalizeId(meta.id || resolvedPath);\n this.metadata[id] = {\n type: \"normal\",\n timestamp: Date.now(),\n ...(this.metadata[id] ?? {}),\n ...meta\n } as VirtualFileMetadata;\n this.paths[id] = resolvedPath;\n this.ids[resolvedPath] = id;\n\n return adapter.setSync(relativeKey, data);\n }\n\n /**\n * Synchronously creates a directory at the specified path.\n *\n * @param dirPath - The path of the directory to create.\n */\n public mkdirSync(dirPath: string) {\n return this.#getStorage(dirPath)?.adapter?.mkdirSync(dirPath);\n }\n\n /**\n * Creates a directory at the specified path.\n *\n * @param path - The path of the directory to create.\n */\n public async mkdir(path: string): Promise<void> {\n return this.#getStorage(path)?.adapter?.mkdir(path);\n }\n\n /**\n * Retrieves the metadata of a file in the virtual file system (VFS).\n *\n * @param pathOrId - The path or ID of the file to retrieve metadata for.\n * @returns The metadata of the file, or undefined if the file does not exist.\n */\n public getMetadata(pathOrId: string): VirtualFileMetadata | undefined {\n const resolved = this.resolveSync(pathOrId);\n if (resolved && this.metadata[resolved]) {\n return this.metadata[resolved];\n }\n\n return undefined;\n }\n\n /**\n * Resolves a given module ID using the configured aliases.\n *\n * @remarks\n * This function can be used to map module IDs to different paths based on the alias configuration.\n *\n * @param id - The module ID to resolve.\n * @returns The resolved module ID - after applying any configured aliases (this will be the same as the input ID if no aliases match).\n */\n public resolveAlias(id: string): string {\n let path = id;\n\n if (this.#context.config.resolve.alias) {\n if (\n Array.isArray(this.#context.config.resolve.alias) &&\n this.#context.config.resolve.alias.length > 0\n ) {\n const found = this.#context.config.resolve.alias.filter(\n alias =>\n (isSetString(alias.find) &&\n (alias.find === path || path.startsWith(`${alias.find}/`))) ||\n (isRegExp(alias.find) && alias.find.test(path))\n );\n if (found.length > 0) {\n const alias = found.reduce((ret, current) => {\n const retLength = isSetString(ret.find)\n ? ret.find.length\n : isRegExp(ret.find)\n ? ret.find.source.length\n : 0;\n const currentLength = isSetString(current.find)\n ? current.find.length\n : isRegExp(current.find)\n ? current.find.source.length\n : 0;\n\n return retLength > currentLength ? ret : current;\n });\n\n if (isSetString(alias.find)) {\n path = path.replace(\n new RegExp(`^${alias.find}`),\n alias.replacement\n );\n } else if (isRegExp(alias.find)) {\n path = path.replace(alias.find, alias.replacement);\n }\n }\n } else if (isSetObject(this.#context.config.resolve.alias)) {\n const found = Object.keys(\n this.#context.config.resolve.alias as Record<string, string>\n ).filter(key => key === path || path.startsWith(`${key}/`));\n if (found.length > 0) {\n const alias = found.reduce((ret, current) => {\n return ret.length > current.length ? ret : current;\n });\n\n path = path.replace(\n new RegExp(`^${alias}`),\n (this.#context.config.resolve.alias as Record<string, string>)[\n alias\n ]!\n );\n }\n }\n }\n\n return path;\n }\n\n /**\n * A helper function to resolve modules in the virtual file system (VFS).\n *\n * @remarks\n * This function can be used to resolve modules relative to the project root directory.\n *\n * @example\n * ```ts\n * const resolved = await context.resolvePath(\"some-module\", \"/path/to/importer\");\n * ```\n *\n * @param id - The module to resolve.\n * @param importer - An optional path to the importer module.\n * @param options - Additional resolution options.\n * @returns A promise that resolves to the resolved module path.\n */\n public async resolve(\n id: string,\n importer?: string,\n options: ResolveOptions = {}\n ): Promise<string | undefined> {\n const origResult = await this.#innerResolve(id, importer, options);\n if (origResult && options.isFile && (await this.isDirectory(origResult))) {\n const indexResult = await this.resolve(\n joinPaths(origResult, \"index\"),\n importer,\n options\n );\n if (indexResult) {\n return indexResult;\n }\n\n if (!hasFileExtension(origResult)) {\n for (const ext of DEFAULT_EXTENSIONS) {\n const extResult = await this.resolve(\n `${origResult}.${ext}`,\n importer,\n options\n );\n if (extResult) {\n return extResult;\n }\n }\n }\n\n return undefined;\n }\n\n return origResult;\n }\n\n /**\n * A synchronous helper function to resolve modules using the Jiti resolver\n *\n * @remarks\n * This function can be used to resolve modules relative to the project root directory.\n *\n * @example\n * ```ts\n * const resolvedPath = context.resolveSync(\"some-module\", \"/path/to/importer\");\n * ```\n *\n * @param id - The module to resolve.\n * @param importer - An optional path to the importer module.\n * @param options - Additional resolution options.\n * @returns The resolved module path.\n */\n public resolveSync(\n id: string,\n importer?: string,\n options: ResolveOptions = {}\n ): string | undefined {\n const origResult = this.#innerResolveSync(id, importer, options);\n if (origResult && options.isFile && this.isDirectorySync(origResult)) {\n const indexResult = this.resolveSync(\n joinPaths(origResult, \"index\"),\n importer,\n options\n );\n if (indexResult) {\n return indexResult;\n }\n\n if (!hasFileExtension(origResult)) {\n for (const ext of DEFAULT_EXTENSIONS) {\n const extResult = this.resolveSync(\n `${origResult}.${ext}`,\n importer,\n options\n );\n if (extResult) {\n return extResult;\n }\n }\n }\n\n return undefined;\n }\n\n return origResult;\n }\n\n /**\n * Disposes of the virtual file system (VFS) by saving its state to disk.\n */\n public async dispose() {\n if (!this.#isDisposed) {\n this.#isDisposed = true;\n\n this.#log(LogLevelLabel.DEBUG, \"Disposing virtual file system...\");\n await this.remove(joinPaths(this.#context.dataPath, \"fs.bin\"));\n\n const message = new capnp.Message();\n const fs = message.initRoot(FileSystem);\n\n const storage = fs._initStorage(Object.keys(this.#paths).length);\n await Promise.all(\n Object.values(this.#paths).map(async (path, index) => {\n const code = await this.read(path);\n\n const fd = storage.get(index);\n fd.path = path;\n fd.code = code || \"\";\n })\n );\n\n const ids = fs._initIds(Object.keys(this.#ids).length);\n Object.entries(this.#ids)\n .filter(([, id]) => id)\n .forEach(([path, id], index) => {\n const fileId = ids.get(index);\n fileId.id = id;\n fileId.path = path;\n });\n\n const metadata = fs._initMetadata(Object.keys(this.#metadata).length);\n Object.entries(this.#metadata)\n .filter(([, value]) => value)\n .forEach(([id, value], index) => {\n const fileMetadata = metadata.get(index);\n fileMetadata.id = id;\n fileMetadata.type = value.type;\n fileMetadata.timestamp = value.timestamp ?? Date.now();\n\n if (value.properties) {\n const props = fileMetadata._initProperties(\n Object.keys(value.properties).length\n );\n Object.entries(value.properties)\n .filter(([, val]) => isSetString(val))\n .forEach(([key, val], index) => {\n const prop = props.get(index);\n prop.key = key;\n prop.value = val!;\n });\n }\n });\n\n await writeFileBuffer(\n joinPaths(this.#context.dataPath, \"fs.bin\"),\n message.toArrayBuffer()\n );\n\n if (!this.#context.config.skipCache) {\n this.#resolverCache.save(true);\n }\n\n await Promise.all(\n this.#getStorages().map(async storage => storage.adapter.dispose())\n );\n\n this.#log(LogLevelLabel.TRACE, \"Virtual file system has been disposed.\");\n }\n }\n\n // /**\n // * Initializes the virtual file system (VFS) by patching the file system module if necessary.\n // */\n // public [__VFS_PATCH__]() {\n // if (!this.#isPatched && this.#context.config.output.mode !== \"fs\") {\n // this.#revert = patchFS(fs, this);\n // this.#isPatched = true;\n // }\n // }\n\n // /**\n // * Reverts the file system module to its original state if it was previously patched.\n // */\n // public [__VFS_REVERT__]() {\n // if (this.#isPatched && this.#context.config.output.mode !== \"fs\") {\n // if (!this.#revert) {\n // throw new Error(\n // \"Attempting to revert File System patch prior to calling `__init__` function\"\n // );\n // }\n\n // this.#revert?.();\n // this.#isPatched = false;\n // }\n // }\n\n async [Symbol.asyncDispose]() {\n return this.dispose();\n }\n}\n","/* -------------------------------------------------------------------\n\n ⚡ Storm Software - Powerlines\n\n This code was released as part of the Powerlines project. Powerlines\n is maintained by Storm Software under the Apache-2.0 license, and is\n free for commercial and private use. For more information, please visit\n our licensing page at https://stormsoftware.com/licenses/projects/powerlines.\n\n Website: https://stormsoftware.com\n Repository: https://github.com/storm-software/powerlines\n Documentation: https://docs.stormsoftware.com/projects/powerlines\n Contact: https://stormsoftware.com/contact\n\n SPDX-License-Identifier: Apache-2.0\n\n ------------------------------------------------------------------- */\n\nimport { UNSAFE_ContextInternal } from \"@powerlines/core/types/_internal\";\nimport { LogLevelLabel } from \"@storm-software/config-tools/types\";\nimport { toArray } from \"@stryke/convert/to-array\";\nimport { EnvPaths, getEnvPaths } from \"@stryke/env/get-env-paths\";\nimport { existsSync } from \"@stryke/fs/exists\";\nimport { relativeToWorkspaceRoot } from \"@stryke/fs/get-workspace-root\";\nimport { readJsonFile } from \"@stryke/fs/json\";\nimport { resolvePackage } from \"@stryke/fs/resolve\";\nimport { murmurhash } from \"@stryke/hash\";\nimport { hashDirectory } from \"@stryke/hash/node\";\nimport { getUnique, getUniqueBy } from \"@stryke/helpers/get-unique\";\nimport { omit } from \"@stryke/helpers/omit\";\nimport { fetchRequest } from \"@stryke/http/fetch\";\nimport { StormJSON } from \"@stryke/json/storm-json\";\nimport { appendPath } from \"@stryke/path/append\";\nimport {\n findFileDotExtensionSafe,\n findFileExtensionSafe\n} from \"@stryke/path/file-path-fns\";\nimport { isParentPath } from \"@stryke/path/is-parent-path\";\nimport { joinPaths } from \"@stryke/path/join\";\nimport { replacePath } from \"@stryke/path/replace\";\nimport { titleCase } from \"@stryke/string-format/title-case\";\nimport { isFunction } from \"@stryke/type-checks/is-function\";\nimport { isNull } from \"@stryke/type-checks/is-null\";\nimport { isRegExp } from \"@stryke/type-checks/is-regexp\";\nimport { isSetObject } from \"@stryke/type-checks/is-set-object\";\nimport { isSetString } from \"@stryke/type-checks/is-set-string\";\nimport { isString } from \"@stryke/type-checks/is-string\";\nimport { TypeDefinition } from \"@stryke/types/configuration\";\nimport { PackageJson } from \"@stryke/types/package-json\";\nimport { uuid } from \"@stryke/unique-id/uuid\";\nimport { match, tsconfigPathsToRegExp } from \"bundle-require\";\nimport { resolveCompatibilityDates } from \"compatx\";\nimport defu from \"defu\";\nimport { create, FlatCache } from \"flat-cache\";\nimport { parse, ParseResult } from \"oxc-parser\";\nimport { Range } from \"semver\";\nimport {\n Agent,\n BodyInit,\n interceptors,\n RequestInfo,\n Response,\n setGlobalDispatcher\n} from \"undici\";\nimport { UnpluginBuildContext, UnpluginMessage } from \"unplugin\";\nimport { getPrefixedRootHash } from \"../_internal/helpers/meta\";\nimport {\n createResolver,\n CreateResolverOptions\n} from \"../_internal/helpers/resolver\";\nimport { VirtualFileSystem } from \"../_internal/vfs\";\nimport { loadUserConfigFile, loadWorkspaceConfig } from \"../config\";\nimport { CACHE_HASH_LENGTH, ROOT_HASH_LENGTH } from \"../constants\";\nimport {\n checkDedupe,\n isPlugin,\n mergeConfig,\n replacePathTokens\n} from \"../plugin-utils\";\nimport type {\n Context,\n EmitEntryOptions,\n EmitOptions,\n FetchOptions,\n InitContextOptions,\n InitialUserConfig,\n LogFn,\n MetaInfo,\n ParsedTypeScriptConfig,\n ParsedUserConfig,\n ParseOptions,\n PluginConfig,\n PowerlinesCommand,\n ResolveConfig,\n ResolvedAssetGlob,\n ResolvedConfig,\n ResolvedEntryTypeDefinition,\n ResolveOptions,\n Resolver,\n ResolveResult,\n TransformResult,\n VirtualFile,\n VirtualFileSystemInterface,\n WorkspaceConfig\n} from \"../types\";\nimport { getTsconfigFilePath } from \"../typescript/tsconfig\";\nimport {\n createLog,\n extendLog,\n getUniqueInputs,\n isTypeDefinition,\n resolveInputsSync\n} from \"../utils\";\n\ninterface ConfigCacheKey {\n root: string;\n mode: \"test\" | \"development\" | \"production\";\n skipCache: boolean;\n configFile?: string;\n framework: string;\n command?: string;\n alias?: ResolveConfig[\"alias\"];\n}\n\ninterface ConfigCacheResult {\n projectJson: Context[\"projectJson\"];\n packageJson: Context[\"packageJson\"];\n checksum: string;\n resolver: Resolver;\n userConfig: ParsedUserConfig;\n}\n\nconst configCache = new WeakMap<ConfigCacheKey, ConfigCacheResult>();\n\ninterface EnvPathCacheKey {\n framework: string;\n workspaceRoot: string;\n}\n\nconst envPathCache = new WeakMap<EnvPathCacheKey, EnvPaths>();\n\nconst agent = new Agent({ keepAliveTimeout: 10000 });\nsetGlobalDispatcher(\n agent.compose(\n interceptors.retry({\n maxRetries: 3,\n minTimeout: 1000,\n maxTimeout: 10000,\n timeoutFactor: 2,\n retryAfter: true\n })\n )\n);\n\nexport class PowerlinesContext<\n TResolvedConfig extends ResolvedConfig = ResolvedConfig\n> implements Context<TResolvedConfig> {\n /**\n * Internal references storage\n *\n * @danger\n * This field is for internal use only and should not be accessed or modified directly. It is unstable and can be changed at anytime.\n *\n * @internal\n */\n #internal = {} as UNSAFE_ContextInternal<TResolvedConfig>;\n\n #workspaceConfig: WorkspaceConfig;\n\n #checksum: string | null = null;\n\n #buildId: string = uuid();\n\n #releaseId: string = uuid();\n\n #timestamp: number = Date.now();\n\n #fs!: VirtualFileSystemInterface;\n\n #tsconfig!: ParsedTypeScriptConfig;\n\n #parserCache!: FlatCache;\n\n #requestCache!: FlatCache;\n\n #getConfigProps(config: Partial<TResolvedConfig[\"userConfig\"]> = {}) {\n return mergeConfig(\n {\n root: config.root,\n name: config.name,\n title: config.title,\n organization: config.organization,\n compatibilityDate: resolveCompatibilityDates(\n config.compatibilityDate,\n \"latest\"\n ),\n description: config.description,\n configFile: config.configFile,\n projectType: config.projectType,\n customLogger: config.customLogger,\n logLevel: config.logLevel,\n tsconfig: config.tsconfig,\n tsconfigRaw: config.tsconfigRaw,\n skipCache: config.skipCache,\n autoInstall: config.autoInstall,\n input: config.input,\n output: config.output,\n plugins: config.plugins,\n mode: config.mode,\n resolve: config.resolve,\n framework: config.framework,\n ...config\n },\n {\n output: config.framework\n ? {\n artifactsPath: `.${config.framework ?? \"powerlines\"}`,\n dts: joinPaths(\n config.root ?? this.config.root,\n `${config.framework ?? \"powerlines\"}.d.ts`\n )\n }\n : {}\n }\n );\n }\n\n /**\n * Create a new Storm context from the workspace root and user config.\n *\n * @param workspaceRoot - The root directory of the workspace.\n * @param config - The user configuration options.\n * @returns A promise that resolves to the new context.\n */\n public static async from<\n TResolvedConfig extends ResolvedConfig = ResolvedConfig\n >(\n workspaceRoot: string,\n config: InitialUserConfig<TResolvedConfig[\"userConfig\"]>\n ): Promise<Context> {\n const context = new PowerlinesContext<TResolvedConfig>(\n await loadWorkspaceConfig(workspaceRoot, config.root)\n );\n await context.withUserConfig(config);\n\n const powerlinesPath = await resolvePackage(\"powerlines\");\n if (!powerlinesPath) {\n throw new Error(\"Could not resolve `powerlines` package location.\");\n }\n\n context.powerlinesPath = powerlinesPath;\n\n return context;\n }\n\n /**\n * An object containing the dependencies that should be installed for the project\n */\n public dependencies: Record<string, string | Range> = {};\n\n /**\n * An object containing the development dependencies that should be installed for the project\n */\n public devDependencies: Record<string, string | Range> = {};\n\n /**\n * The persisted meta information about the current build\n */\n public persistedMeta: MetaInfo | undefined = undefined;\n\n /**\n * The path to the Powerlines package\n */\n public powerlinesPath!: string;\n\n /**\n * The parsed `package.json` file for the project\n */\n public packageJson!: PackageJson;\n\n /**\n * The parsed `project.json` file for the project\n */\n public projectJson: Record<string, any> | undefined = undefined;\n\n /**\n * The module resolver for the project\n */\n public resolver!: Resolver;\n\n /**\n * The resolved configuration options\n */\n private resolvePatterns: RegExp[] = [];\n\n /**\n * Internal context fields and methods\n *\n * @danger\n * This field is for internal use only and should not be accessed or modified directly. It is unstable and can be changed at anytime.\n *\n * @internal\n */\n public get $$internal(): UNSAFE_ContextInternal<TResolvedConfig> {\n return this.#internal;\n }\n\n /**\n * Internal context fields and methods\n *\n * @danger\n * This field is for internal use only and should not be accessed or modified directly. It is unstable and can be changed at anytime.\n *\n * @internal\n */\n public set $$internal(value: UNSAFE_ContextInternal<TResolvedConfig>) {\n this.#internal = value;\n }\n\n /**\n * The resolved entry type definitions for the project\n */\n public get entry(): ResolvedEntryTypeDefinition[] {\n const entry = this.resolvedEntry;\n\n return resolveInputsSync(\n this,\n entry && entry.length > 0\n ? entry\n : Array.isArray(this.config.input) ||\n (isSetObject(this.config.input) &&\n !isTypeDefinition(this.config.input))\n ? this.config.input\n : toArray(this.config.input).flat()\n );\n }\n\n /**\n * The TypeScript configuration parsed from the tsconfig file\n */\n public get tsconfig(): ParsedTypeScriptConfig {\n if (!this.#tsconfig) {\n this.tsconfig = {\n tsconfigFilePath: this.config.tsconfig\n } as ParsedTypeScriptConfig;\n }\n\n return this.#tsconfig;\n }\n\n /**\n * Sets the TypeScript configuration parsed from the tsconfig file\n */\n public set tsconfig(value: ParsedTypeScriptConfig) {\n this.#tsconfig = value;\n this.resolvePatterns = tsconfigPathsToRegExp(value?.options?.paths ?? {});\n }\n\n /**\n * The virtual file system interface for the project\n */\n public get fs(): VirtualFileSystemInterface {\n if (!this.#fs) {\n this.#fs = VirtualFileSystem.createSync(this);\n }\n\n return this.#fs;\n }\n\n /**\n * Get the checksum of the project's current state\n */\n public get checksum(): string | null {\n return this.#checksum;\n }\n\n /**\n * The meta information about the current build\n */\n public get meta() {\n return {\n buildId: this.#buildId,\n releaseId: this.#releaseId,\n checksum: this.#checksum,\n timestamp: this.#timestamp,\n rootHash: murmurhash(\n {\n workspaceRoot: this.workspaceConfig?.workspaceRoot,\n root: this.config?.root\n },\n {\n maxLength: ROOT_HASH_LENGTH\n }\n ),\n configHash: murmurhash(this.config, {\n maxLength: CACHE_HASH_LENGTH\n })\n } as MetaInfo;\n }\n\n /**\n * The resolved configuration options\n */\n public get config(): TResolvedConfig {\n return this.resolvedConfig ?? {};\n }\n\n /**\n * The logger function\n */\n public get log(): LogFn {\n if (!this.logFn) {\n this.logFn = this.createLog();\n }\n\n return this.logFn;\n }\n\n /**\n * The workspace configuration\n */\n public get workspaceConfig(): WorkspaceConfig {\n return this.#workspaceConfig;\n }\n\n /**\n * The environment paths for the project\n */\n public get envPaths(): EnvPaths {\n if (\n envPathCache.has({\n workspaceRoot: this.workspaceConfig.workspaceRoot,\n framework: this.config?.framework || \"powerlines\"\n })\n ) {\n return envPathCache.get({\n workspaceRoot: this.workspaceConfig.workspaceRoot,\n framework: this.config?.framework || \"powerlines\"\n })!;\n }\n\n const envPaths = getEnvPaths({\n orgId: \"storm-software\",\n appId: this.config?.framework || \"powerlines\",\n workspaceRoot: this.workspaceConfig.workspaceRoot\n });\n envPathCache.set(\n {\n workspaceRoot: this.workspaceConfig.workspaceRoot,\n framework: this.config?.framework || \"powerlines\"\n },\n envPaths\n );\n\n return envPaths;\n }\n\n /**\n * Get the path to the artifacts directory for the project\n */\n public get artifactsPath(): string {\n return joinPaths(\n this.workspaceConfig.workspaceRoot,\n this.config.root,\n this.config.output.artifactsPath\n );\n }\n\n /**\n * Get the path to the builtin modules used by the project\n */\n public get builtinsPath(): string {\n return joinPaths(this.artifactsPath, \"builtins\");\n }\n\n /**\n * Get the path to the entry directory for the project\n */\n public get entryPath(): string {\n return joinPaths(this.artifactsPath, \"entry\");\n }\n\n /**\n * Get the path to the infrastructure modules used by the project\n */\n public get infrastructurePath(): string {\n return joinPaths(this.artifactsPath, \"infrastructure\");\n }\n\n /**\n * Get the path to the data directory for the project\n */\n public get dataPath(): string {\n return joinPaths(\n this.envPaths.data,\n \"projects\",\n getPrefixedRootHash(this.config.name, this.meta.rootHash)\n );\n }\n\n /**\n * Get the path to the cache directory for the project\n */\n public get cachePath(): string {\n return joinPaths(\n this.envPaths.cache,\n \"projects\",\n murmurhash(\n {\n checksum: this.#checksum,\n config: this.meta.configHash\n },\n {\n maxLength: CACHE_HASH_LENGTH\n }\n )\n );\n }\n\n /**\n * Get the path to the generated declaration file for the project\n */\n public get dtsPath(): string {\n return this.config.output.dts\n ? appendPath(this.config.output.dts, this.workspaceConfig.workspaceRoot)\n : joinPaths(\n this.workspaceConfig.workspaceRoot,\n this.config.root,\n \"powerlines.d.ts\"\n );\n }\n\n /**\n * Get the project root relative to the workspace root\n */\n public get relativeToWorkspaceRoot() {\n return relativeToWorkspaceRoot(this.config.root);\n }\n\n /**\n * The builtin module id that exist in the Powerlines virtual file system\n */\n public get builtins(): string[] {\n return Object.values(this.fs.metadata)\n .filter(meta => meta && meta.type === \"builtin\")\n .map(meta => meta?.id)\n .filter(Boolean);\n }\n\n /**\n * The alias mappings for the project used during module resolution\n *\n * @remarks\n * This includes both the built-in module aliases as well as any custom aliases defined in the build configuration.\n */\n public get alias(): Record<string, string> {\n return this.builtins.reduce(\n (ret, id) => {\n const moduleId = `${\n this.config?.framework || \"powerlines\"\n }:${id.replace(/^.*?:/, \"\")}`;\n if (!ret[moduleId]) {\n const path = this.fs.paths[id];\n if (path) {\n ret[moduleId] = path;\n }\n }\n\n return ret;\n },\n this.config.resolve.alias\n ? Array.isArray(this.config.resolve.alias)\n ? this.config.resolve.alias.reduce(\n (ret, alias) => {\n if (!ret[alias.find.toString()]) {\n ret[alias.find.toString()] = alias.replacement;\n }\n\n return ret;\n },\n {} as Record<string, string>\n )\n : this.config.resolve.alias\n : {}\n );\n }\n\n /**\n * Gets the parser cache.\n */\n protected get parserCache(): FlatCache {\n if (!this.#parserCache) {\n this.#parserCache = create({\n cacheId: \"parser\",\n cacheDir: this.cachePath,\n ttl: 2 * 60 * 60 * 1000,\n lruSize: 5000,\n persistInterval: 250\n });\n }\n\n return this.#parserCache;\n }\n\n /**\n * Gets the request cache.\n */\n protected get requestCache(): FlatCache {\n if (!this.#requestCache) {\n this.#requestCache = create({\n cacheId: \"http\",\n cacheDir: this.cachePath,\n ttl: 6 * 60 * 60 * 1000,\n lruSize: 5000,\n persistInterval: 250\n });\n }\n\n return this.#requestCache;\n }\n\n /**\n * The entry points that exist in the Powerlines virtual file system\n */\n protected get resolvedEntry(): ResolvedEntryTypeDefinition[] {\n return Object.entries(this.fs.metadata)\n .filter(([, meta]) => meta && meta.type === \"entry\")\n .map(([path, meta]) => {\n const typeDefinition = {\n file: path\n } as ResolvedEntryTypeDefinition;\n\n if (meta.properties) {\n if (isSetString(meta.properties.file)) {\n typeDefinition.file = meta.properties.file;\n }\n if (isSetString(meta.properties.name)) {\n typeDefinition.name = meta.properties.name;\n }\n if (\n isSetString(meta.properties[\"input.file\"]) ||\n isSetString(meta.properties[\"input.name\"])\n ) {\n typeDefinition.input ??= {} as TypeDefinition;\n if (isSetString(meta.properties[\"input.file\"])) {\n typeDefinition.input.file = meta.properties[\"input.file\"];\n }\n if (isSetString(meta.properties[\"input.name\"])) {\n typeDefinition.input.name = meta.properties[\"input.name\"];\n }\n }\n if (isSetString(meta.properties.output)) {\n typeDefinition.output = meta.properties.output;\n }\n }\n\n return typeDefinition;\n })\n .filter(Boolean);\n }\n\n /**\n * A function to perform HTTP fetch requests\n *\n * @remarks\n * This function uses a caching layer to avoid duplicate requests during the Powerlines process.\n *\n * @example\n * ```ts\n * const response = await context.fetch(\"https://api.example.com/data\");\n * const data = await response.json();\n * ```\n *\n * @see https://github.com/nodejs/undici\n *\n * @param input - The URL to fetch.\n * @param options - The fetch request options.\n * @returns A promise that resolves to a response returned by the fetch.\n */\n public async fetch(\n input: RequestInfo,\n options: FetchOptions = {}\n ): Promise<Response> {\n const cacheKey = murmurhash({\n input: input.toString(),\n options: JSON.stringify(options)\n });\n\n if (!this.config.skipCache && !options.skipCache) {\n const cached = this.requestCache.get<\n {\n body: BodyInit;\n } & Pick<Response, \"status\" | \"statusText\" | \"headers\">\n >(cacheKey);\n if (cached) {\n return new Response(cached.body, {\n status: cached.status,\n statusText: cached.statusText,\n headers: cached.headers\n });\n }\n }\n\n const response = await fetchRequest(input, { timeout: 12_000, ...options });\n const result = {\n body: await response.text(),\n status: response.status,\n statusText: response.statusText,\n headers: Object.fromEntries(response.headers.entries())\n };\n\n if (!this.config.skipCache && !options.skipCache) {\n try {\n this.requestCache.set(cacheKey, result);\n } catch {\n // Do nothing\n }\n }\n\n return new Response(result.body, {\n status: result.status,\n statusText: result.statusText,\n headers: result.headers\n });\n }\n\n /**\n * Parse code using [Oxc-Parser](https://github.com/oxc/oxc) into an (ESTree-compatible)[https://github.com/estree/estree] AST object.\n *\n * @remarks\n * This function can be used to parse TypeScript code into an AST for further analysis or transformation.\n *\n * @example\n * ```ts\n * const ast = context.parse(\"const x: number = 42;\");\n * ```\n *\n * @see https://rollupjs.org/plugin-development/#this-parse\n * @see https://github.com/oxc/oxc\n *\n * @param code - The source code to parse.\n * @param options - The options to pass to the parser.\n * @returns An (ESTree-compatible)[https://github.com/estree/estree] AST object.\n */\n public async parse(code: string, options: ParseOptions = {}) {\n const cacheKey = murmurhash({\n code,\n options\n });\n\n let result!: ParseResult;\n if (!this.config.skipCache) {\n result = this.parserCache.get<ParseResult>(cacheKey);\n if (result) {\n return result;\n }\n }\n\n result = await parse(`source.${options.lang || \"ts\"}`, code, {\n ...options,\n sourceType: \"module\",\n showSemanticErrors: this.config.mode === \"development\"\n });\n\n if (!this.config.skipCache) {\n this.parserCache.set(cacheKey, result);\n }\n\n return result;\n }\n\n /**\n * A helper function to resolve modules in the Virtual File System\n *\n * @remarks\n * This function can be used to resolve modules relative to the project root directory.\n *\n * @example\n * ```ts\n * const resolved = await context.resolve(\"some-module\", \"/path/to/importer\");\n * ```\n *\n * @param id - The module to resolve.\n * @param importer - An optional path to the importer module.\n * @param options - Additional resolution options.\n * @returns A promise that resolves to the resolved module path.\n */\n public async resolve(\n id: string,\n importer?: string,\n options: ResolveOptions = {}\n ): Promise<ResolveResult | undefined> {\n let moduleId = id;\n if (this.config.resolve.alias) {\n if (Array.isArray(this.config.resolve.alias)) {\n const alias = this.config.resolve.alias.find(a =>\n match(moduleId, [a.find])\n );\n if (alias) {\n moduleId = alias.replacement;\n }\n } else if (\n isSetObject(this.config.resolve.alias) &&\n this.config.resolve.alias[id]\n ) {\n moduleId = this.config.resolve.alias[id];\n }\n }\n\n if (\n this.fs.isVirtual(moduleId) ||\n (importer && this.fs.isVirtual(importer))\n ) {\n let resolvedImporter = importer;\n if (importer && this.fs.isVirtual(importer)) {\n resolvedImporter = await this.fs.resolve(importer, undefined, {\n conditions: this.config.resolve.conditions,\n extensions: this.config.resolve.extensions,\n ...options\n });\n }\n\n const result = await this.fs.resolve(moduleId, resolvedImporter, {\n conditions: this.config.resolve.conditions,\n extensions: this.config.resolve.extensions,\n ...options\n });\n if (!result) {\n return undefined;\n }\n\n const external =\n !match(moduleId, this.config.resolve.noExternal) &&\n (match(moduleId, this.config.resolve.external) ||\n moduleId.startsWith(\"node:\") ||\n (this.fs.isVirtual(moduleId) &&\n this.config.projectType !== \"application\") ||\n (this.config.resolve.skipNodeModulesBundle &&\n !/^[A-Z]:[/\\\\]|^\\.{0,2}\\/|^\\.{1,2}$/.test(moduleId)));\n\n return {\n id: result,\n external,\n virtual: !external\n };\n }\n\n if (this.config.resolve.skipNodeModulesBundle) {\n if (\n match(moduleId, this.resolvePatterns) ||\n match(moduleId, this.config.resolve.noExternal)\n ) {\n return undefined;\n }\n\n if (\n match(moduleId, this.config.resolve.external) ||\n moduleId.startsWith(\"node:\")\n ) {\n return { id: moduleId, external: true, virtual: false };\n }\n\n // Exclude any other import that looks like a Node module\n if (!/^[A-Z]:[/\\\\]|^\\.{0,2}\\/|^\\.{1,2}$/.test(moduleId)) {\n return {\n id: moduleId,\n external: true,\n virtual: false\n };\n }\n } else {\n if (match(moduleId, this.config.resolve.noExternal)) {\n return undefined;\n }\n\n if (\n match(moduleId, this.config.resolve.external) ||\n moduleId.startsWith(\"node:\")\n ) {\n return { id: moduleId, external: true, virtual: false };\n }\n }\n\n return undefined;\n }\n\n /**\n * A helper function to load modules from the Virtual File System\n *\n * @remarks\n * This function can be used to load modules relative to the project root directory.\n *\n * @example\n * ```ts\n * const module = await context.load(\"some-module\", \"/path/to/importer\");\n * ```\n *\n * @param id - The module to load.\n * @returns A promise that resolves to the loaded module.\n */\n public async load(id: string): Promise<TransformResult | undefined> {\n const resolvedId = await this.fs.resolve(id);\n if (!resolvedId) {\n return undefined;\n }\n\n const code = await this.fs.read(resolvedId);\n if (!code) {\n return undefined;\n }\n\n return { code, map: null };\n }\n\n /**\n * Get the builtin virtual files that exist in the Powerlines virtual file system\n */\n public async getBuiltins() {\n return Promise.all(\n Object.entries(this.fs.metadata)\n .filter(([, meta]) => meta && meta.type === \"builtin\")\n .map(async ([id, meta]) => {\n const code = await this.fs.read(id);\n const path = this.fs.paths[id];\n\n return { ...meta, path, code } as VirtualFile;\n })\n );\n }\n\n /**\n * Resolves a file and writes it to the VFS if it does not already exist\n *\n * @param code - The source code of the file\n * @param path - The path to write the file to\n * @param options - Additional options for writing the file\n */\n public async emit(\n code: string,\n path: string,\n options: EmitOptions = {}\n ): Promise<void> {\n const filePath = options.extension\n ? findFileExtensionSafe(path)\n ? options.extension.startsWith(\".\")\n ? path.replace(findFileDotExtensionSafe(path), options.extension)\n : path.replace(findFileExtensionSafe(path), options.extension)\n : options.extension.startsWith(\".\")\n ? `${path}${options.extension}`\n : `${path}.${options.extension}`\n : findFileExtensionSafe(path)\n ? path\n : `${path}.ts`;\n\n if (\n isFunction((this as unknown as UnpluginBuildContext).emitFile) &&\n options.emitWithBundler\n ) {\n return (this as unknown as UnpluginBuildContext).emitFile({\n needsCodeReference: options.needsCodeReference,\n originalFileName: options.originalFileName,\n fileName: filePath,\n source: code,\n type: \"asset\"\n });\n }\n\n return this.fs.write(filePath, code, options);\n }\n\n /**\n * Synchronously resolves a file and writes it to the VFS if it does not already exist\n *\n * @param code - The source code of the file\n * @param path - The path to write the file to\n * @param options - Additional options for writing the file\n */\n public emitSync(code: string, path: string, options: EmitOptions = {}) {\n const filePath = options.extension\n ? findFileExtensionSafe(path)\n ? options.extension.startsWith(\".\")\n ? path.replace(findFileDotExtensionSafe(path), options.extension)\n : path.replace(findFileExtensionSafe(path), options.extension)\n : options.extension.startsWith(\".\")\n ? `${path}${options.extension}`\n : `${path}.${options.extension}`\n : findFileExtensionSafe(path)\n ? path\n : `${path}.ts`;\n\n if (\n isFunction((this as unknown as UnpluginBuildContext).emitFile) &&\n options.emitWithBundler\n ) {\n return (this as unknown as UnpluginBuildContext).emitFile({\n needsCodeReference: options.needsCodeReference,\n originalFileName: options.originalFileName,\n fileName: filePath,\n source: code,\n type: \"asset\"\n });\n }\n\n return this.fs.writeSync(filePath, code, options);\n }\n\n /**\n * Resolves a entry virtual file and writes it to the VFS if it does not already exist\n *\n * @param code - The source code of the entry file\n * @param path - A path to write the entry file to\n * @param options - Optional write file options\n */\n public async emitEntry(\n code: string,\n path: string,\n options: EmitEntryOptions = {}\n ): Promise<void> {\n return this.emit(\n code,\n appendPath(path, this.entryPath),\n defu(\n {\n meta: {\n type: \"entry\",\n properties: {\n file: appendPath(path, this.entryPath),\n name: options?.name,\n output: options?.output,\n \"input.file\": options?.input?.file,\n \"input.name\": options?.input?.name\n }\n }\n },\n omit(options, [\"name\"])\n )\n );\n }\n\n /**\n * Synchronously resolves a entry virtual file and writes it to the VFS if it does not already exist\n *\n * @param code - The source code of the entry file\n * @param path - A path to write the entry file to\n * @param options - Optional write file options\n */\n public emitEntrySync(\n code: string,\n path: string,\n options: EmitEntryOptions = {}\n ): void {\n return this.emitSync(\n code,\n appendPath(path, this.entryPath),\n defu(\n {\n meta: {\n type: \"entry\",\n properties: {\n file: appendPath(path, this.entryPath),\n name: options?.name,\n output: options?.output,\n \"input.file\": options?.input?.file,\n \"input.name\": options?.input?.name\n }\n }\n },\n omit(options, [\"name\"])\n )\n );\n }\n\n /**\n * Resolves a builtin virtual file and writes it to the VFS if it does not already exist\n *\n * @param code - The source code of the builtin file\n * @param id - The unique identifier of the builtin file\n * @param options - Optional write file options\n */\n public async emitBuiltin(\n code: string,\n id: string,\n options: EmitOptions = {}\n ): Promise<void> {\n if (!this.builtinsPath) {\n throw new Error(\n `The builtins path is not set. Cannot emit builtin file with id \"${id}\".`\n );\n }\n\n if (!isSetString(id)) {\n throw new Error(\n `The builtin id must be a non-empty string. Received: ${String(id)}`\n );\n }\n\n return this.emit(\n code,\n appendPath(id, this.builtinsPath),\n defu(options, { meta: { type: \"builtin\", id } })\n );\n }\n\n /**\n * Synchronously resolves a builtin virtual file and writes it to the VFS if it does not already exist\n *\n * @param code - The source code of the builtin file\n * @param id - The unique identifier of the builtin file\n * @param options - Optional write file options\n */\n public emitBuiltinSync(code: string, id: string, options: EmitOptions = {}) {\n if (!this.builtinsPath) {\n throw new Error(\n `The builtins path is not set. Cannot emit builtin file with id \"${id}\".`\n );\n }\n\n if (!isSetString(id)) {\n throw new Error(\n `The builtin id must be a non-empty string. Received: ${String(id)}`\n );\n }\n\n return this.emitSync(\n code,\n appendPath(id, this.builtinsPath),\n defu(options, { meta: { type: \"builtin\", id } })\n );\n }\n\n /**\n * Resolves a builtin virtual file and writes it to the VFS if it does not already exist\n *\n * @param code - The source code of the builtin file\n * @param id - The unique identifier of the builtin file\n * @param options - Optional write file options\n */\n public async emitInfrastructure(\n code: string,\n id: string,\n options: EmitOptions = {}\n ): Promise<void> {\n if (!this.infrastructurePath) {\n throw new Error(\n `The infrastructure path is not set. Cannot emit infrastructure file with id \"${id}\".`\n );\n }\n\n if (!isSetString(id)) {\n throw new Error(\n `The infrastructure id must be a non-empty string. Received: ${String(id)}`\n );\n }\n\n return this.emit(\n code,\n appendPath(id, this.infrastructurePath),\n defu(options, { meta: { type: \"infrastructure\", id } })\n );\n }\n\n /**\n * Synchronously resolves an infrastructure virtual file and writes it to the VFS if it does not already exist\n *\n * @param code - The source code of the infrastructure file\n * @param id - The unique identifier of the infrastructure file\n * @param options - Optional write file options\n */\n public emitInfrastructureSync(\n code: string,\n id: string,\n options: EmitOptions = {}\n ) {\n if (!this.infrastructurePath) {\n throw new Error(\n `The infrastructure path is not set. Cannot emit infrastructure file with id \"${id}\".`\n );\n }\n\n if (!isSetString(id)) {\n throw new Error(\n `The infrastructure id must be a non-empty string. Received: ${String(id)}`\n );\n }\n\n return this.emitSync(\n code,\n appendPath(id, this.infrastructurePath),\n defu(options, { meta: { type: \"infrastructure\", id } })\n );\n }\n\n /**\n * Update the context using a new user configuration options\n *\n * @param userConfig - The new user configuration options.\n */\n public async withUserConfig(\n userConfig: InitialUserConfig<TResolvedConfig[\"userConfig\"]>,\n options: InitContextOptions = {\n isHighPriority: true\n }\n ) {\n this.mergeUserConfig(userConfig as Partial<TResolvedConfig[\"userConfig\"]>);\n\n await this.init(this.config.userConfig, options);\n }\n\n /**\n * Update the context using a new inline configuration options\n *\n * @param inlineConfig - The new inline configuration options.\n */\n public async withInlineConfig(\n inlineConfig: TResolvedConfig[\"inlineConfig\"],\n options: InitContextOptions = {\n isHighPriority: true\n }\n ) {\n this.config.inlineConfig = inlineConfig;\n\n if (inlineConfig.command === \"new\") {\n const workspacePackageJsonPath = joinPaths(\n this.workspaceConfig.workspaceRoot,\n \"package.json\"\n );\n if (!existsSync(workspacePackageJsonPath)) {\n throw new Error(\n `The workspace package.json file could not be found at ${workspacePackageJsonPath}`\n );\n }\n\n this.packageJson = await readJsonFile<PackageJson>(\n workspacePackageJsonPath\n );\n\n this.workspaceConfig.repository ??= isSetString(\n this.packageJson?.repository\n )\n ? this.packageJson.repository\n : this.packageJson?.repository?.url;\n }\n\n await this.init(this.config.inlineConfig, options);\n }\n\n /**\n * A logging function for fatal messages\n *\n * @param message - The message to log.\n */\n public fatal(message: string | UnpluginMessage) {\n this.log(\n LogLevelLabel.FATAL,\n isString(message) ? message : StormJSON.stringify(message)\n );\n }\n\n /**\n * A logging function for error messages\n *\n * @param message - The message to log.\n */\n public error(message: string | UnpluginMessage) {\n this.log(\n LogLevelLabel.ERROR,\n isString(message) ? message : StormJSON.stringify(message)\n );\n }\n\n /**\n * A logging function for warning messages\n *\n * @param message - The message to log.\n */\n public warn(message: string | UnpluginMessage) {\n this.log(\n LogLevelLabel.WARN,\n isString(message) ? message : StormJSON.stringify(message)\n );\n }\n\n /**\n * A logging function for informational messages\n *\n * @param message - The message to log.\n */\n public info(message: string | UnpluginMessage) {\n this.log(\n LogLevelLabel.INFO,\n isString(message) ? message : StormJSON.stringify(message)\n );\n }\n\n /**\n * A logging function for debug messages\n *\n * @param message - The message to log.\n */\n public debug(message: string | UnpluginMessage) {\n this.log(\n LogLevelLabel.DEBUG,\n isString(message) ? message : StormJSON.stringify(message)\n );\n }\n\n /**\n * A logging function for trace messages\n *\n * @param message - The message to log.\n */\n public trace(message: string | UnpluginMessage) {\n this.log(\n LogLevelLabel.TRACE,\n isString(message) ? message : StormJSON.stringify(message)\n );\n }\n\n /**\n * Create a new logger instance\n *\n * @param name - The name to use for the logger instance\n * @returns A logger function\n */\n public createLog(name: string | null = null): LogFn {\n return createLog(name, {\n ...this.config,\n logLevel: isNull(this.config.logLevel) ? \"silent\" : this.config.logLevel\n });\n }\n\n /**\n * Extend the current logger instance with a new name\n *\n * @param name - The name to use for the extended logger instance\n * @returns A logger function\n */\n public extendLog(name: string): LogFn {\n return extendLog(this.log, name);\n }\n\n /**\n * Generates a checksum representing the current context state\n *\n * @param root - The root directory of the project to generate the checksum for\n * @returns A promise that resolves to a string representing the checksum\n */\n public async generateChecksum(root = this.config.root): Promise<string> {\n this.#checksum = await hashDirectory(root, {\n ignore: [\"node_modules\", \".git\", \".nx\", \".cache\", \"tmp\", \"dist\"]\n });\n\n return this.#checksum;\n }\n\n /**\n * Creates a new StormContext instance.\n *\n * @param workspaceConfig - The workspace configuration.\n */\n protected constructor(workspaceConfig: WorkspaceConfig) {\n this.#workspaceConfig = workspaceConfig;\n\n envPathCache.set(\n {\n workspaceRoot: workspaceConfig.workspaceRoot,\n framework: \"powerlines\"\n },\n getEnvPaths({\n orgId:\n (isSetObject(workspaceConfig.organization)\n ? workspaceConfig.organization.name\n : workspaceConfig.organization) || \"storm-software\",\n appId: \"powerlines\",\n workspaceRoot: workspaceConfig.workspaceRoot\n })\n );\n }\n\n /**\n * The resolved configuration for this context\n */\n protected resolvedConfig: TResolvedConfig = {} as TResolvedConfig;\n\n /**\n * A logger function specific to this context\n */\n protected logFn!: LogFn;\n\n /**\n * Initialize the context with the provided configuration options\n *\n * @param config - The partial user configuration to use for initialization.\n */\n protected async init(\n config: Partial<TResolvedConfig[\"userConfig\"]> = {},\n options: InitContextOptions = {\n isHighPriority: true\n }\n ) {\n const cacheKey: ConfigCacheKey = {\n root:\n config.root ??\n this.config.root ??\n this.config.userConfig?.root ??\n this.config.inlineConfig?.root,\n mode: (config.mode ?? this.config.mode) || this.workspaceConfig.mode,\n skipCache: config.skipCache ?? this.config.skipCache ?? false,\n configFile: config.configFile ?? this.config.configFile,\n framework: config.framework ?? this.config.framework ?? \"powerlines\",\n command: this.config.inlineConfig?.command,\n alias: this.config.resolve?.alias ?? config.resolve?.alias\n };\n\n if (configCache.has(cacheKey)) {\n const result = configCache.get(cacheKey)!;\n\n this.projectJson = result.projectJson;\n this.packageJson = result.packageJson;\n this.#checksum = result.checksum;\n this.resolver = result.resolver;\n\n this.mergeUserConfig(result.userConfig.config, this.config.userConfig);\n } else {\n const projectJsonPath = joinPaths(cacheKey.root, \"project.json\");\n if (existsSync(projectJsonPath)) {\n this.projectJson = await readJsonFile(projectJsonPath);\n }\n\n const packageJsonPath = joinPaths(cacheKey.root, \"package.json\");\n if (existsSync(packageJsonPath)) {\n this.packageJson = await readJsonFile<PackageJson>(packageJsonPath);\n }\n\n this.#checksum = await this.generateChecksum(cacheKey.root);\n this.resolver = createResolver({\n workspaceRoot: this.workspaceConfig.workspaceRoot,\n root: cacheKey.root,\n cacheDir: this.cachePath,\n mode: cacheKey.mode,\n logLevel: (config.logLevel ||\n this.config.logLevel ||\n this.workspaceConfig.logLevel ||\n \"info\") as CreateResolverOptions[\"logLevel\"],\n skipCache: cacheKey.skipCache,\n alias: this.config.resolve?.alias\n ? Array.isArray(this.config.resolve.alias)\n ? this.config.resolve.alias.reduce(\n (ret, alias) => {\n ret[alias.find.toString()] = alias.replacement;\n return ret;\n },\n {} as Record<string, string>\n )\n : this.config.resolve.alias\n : {}\n });\n\n const userConfig = await loadUserConfigFile(\n cacheKey.root,\n this.workspaceConfig.workspaceRoot,\n this.resolver,\n cacheKey.command as PowerlinesCommand | undefined,\n cacheKey.mode,\n cacheKey.configFile,\n cacheKey.framework\n );\n this.mergeUserConfig(userConfig.config);\n\n configCache.set(cacheKey, {\n projectJson: this.projectJson,\n packageJson: this.packageJson,\n checksum: this.#checksum,\n resolver: this.resolver,\n userConfig\n });\n }\n\n config.tsconfig ??= getTsconfigFilePath(\n this.workspaceConfig.workspaceRoot,\n cacheKey.root,\n config.tsconfig\n );\n\n if (isSetObject(config)) {\n this.resolvedConfig = mergeConfig(\n {\n inlineConfig: this.config.inlineConfig,\n userConfig: this.config.userConfig\n },\n options.isHighPriority ? this.#getConfigProps(config) : {},\n {\n ...this.#getConfigProps(this.config.inlineConfig),\n command: this.config.inlineConfig?.command\n },\n this.#getConfigProps(this.config.userConfig),\n {\n mode: this.workspaceConfig?.mode,\n logLevel: this.workspaceConfig?.logLevel,\n skipCache: this.workspaceConfig?.skipCache\n },\n {\n name: this.projectJson?.name || this.packageJson?.name,\n version: this.packageJson?.version,\n description: this.packageJson?.description,\n output: mergeConfig(config.output ?? {}, {\n outputPath: cacheKey.root\n ? joinPaths(\n this.workspaceConfig?.directories?.build || \"dist\",\n cacheKey.root\n )\n : this.workspaceConfig?.directories?.build || \"dist\",\n artifactsPath: `.${config.framework ?? \"powerlines\"}`,\n dts: joinPaths(\n cacheKey.root,\n `${config.framework ?? \"powerlines\"}.d.ts`\n ),\n assets: [\n {\n glob: \"LICENSE\"\n },\n {\n input: cacheKey.root,\n glob: \"*.md\"\n },\n {\n input: cacheKey.root,\n glob: \"package.json\"\n }\n ]\n })\n },\n options.isHighPriority ? {} : this.#getConfigProps(config),\n {\n inlineConfig: {},\n userConfig: {},\n framework: \"powerlines\",\n mode: \"production\",\n projectType: \"application\",\n platform: \"neutral\",\n logLevel: \"info\",\n preview: false,\n environments: {},\n resolve: {}\n }\n ) as TResolvedConfig;\n }\n\n this.config.input = getUniqueInputs(this.config.input);\n\n if (\n this.config.name?.startsWith(\"@\") &&\n this.config.name.split(\"/\").filter(Boolean).length > 1\n ) {\n this.config.name = this.config.name.split(\"/\").filter(Boolean)[1]!;\n }\n\n this.config.title ??= titleCase(this.config.name);\n\n this.config.organization ??=\n (isSetObject(this.workspaceConfig.organization)\n ? this.workspaceConfig.organization.name\n : this.workspaceConfig.organization) ||\n (isSetObject(this.packageJson?.author)\n ? this.packageJson?.author?.name\n : this.packageJson?.author) ||\n this.config.name;\n\n if (this.config.userConfig.resolve?.external) {\n this.config.userConfig.resolve.external = getUnique(\n this.config.userConfig.resolve.external\n );\n }\n if (this.config.userConfig.resolve?.noExternal) {\n this.config.userConfig.resolve.noExternal = getUnique(\n this.config.userConfig.resolve.noExternal\n );\n }\n\n if (this.config.resolve.external) {\n this.config.resolve.external = getUnique(this.config.resolve.external);\n }\n if (this.config.resolve.noExternal) {\n this.config.resolve.noExternal = getUnique(\n this.config.resolve.noExternal\n );\n }\n\n this.config.output.format = getUnique(\n toArray(\n this.config.output?.format ??\n (this.config.projectType === \"library\" ? [\"cjs\", \"esm\"] : [\"esm\"])\n )\n );\n\n if (\n this.config.root &&\n this.config.root !== \".\" &&\n this.config.root !== \"./\" &&\n this.config.root !== this.workspaceConfig.workspaceRoot\n ) {\n this.config.output.outputPath ??= joinPaths(\"dist\", this.config.root);\n this.config.output.buildPath ??= joinPaths(this.config.root, \"dist\");\n } else {\n this.config.output.outputPath ??= \"dist\";\n this.config.output.buildPath ??= \"dist\";\n }\n\n this.config.output.assets = getUniqueBy(\n this.config.output.assets.map(asset => {\n return {\n glob: isSetObject(asset) ? asset.glob : asset,\n input:\n isString(asset) ||\n !asset.input ||\n asset.input === \".\" ||\n asset.input === \"/\" ||\n asset.input === \"./\"\n ? this.workspaceConfig.workspaceRoot\n : isParentPath(asset.input, this.workspaceConfig.workspaceRoot) ||\n asset.input === this.workspaceConfig.workspaceRoot\n ? asset.input\n : appendPath(asset.input, this.workspaceConfig.workspaceRoot),\n output:\n isSetObject(asset) && asset.output\n ? isParentPath(asset.output, this.workspaceConfig.workspaceRoot)\n ? asset.output\n : appendPath(\n joinPaths(\n this.config.output.outputPath,\n replacePath(\n replacePath(\n asset.output,\n replacePath(\n this.config.output.outputPath,\n this.workspaceConfig.workspaceRoot\n )\n ),\n this.config.output.outputPath\n )\n ),\n this.workspaceConfig.workspaceRoot\n )\n : appendPath(\n this.config.output.outputPath,\n this.workspaceConfig.workspaceRoot\n ),\n ignore:\n isSetObject(asset) && asset.ignore\n ? toArray(asset.ignore)\n : undefined\n };\n }),\n (a: ResolvedAssetGlob) => `${a.input}-${a.glob}-${a.output}`\n );\n\n this.config.plugins = (this.config.plugins ?? [])\n .filter(Boolean)\n .reduce((ret, plugin) => {\n if (\n isPlugin(plugin) &&\n checkDedupe(\n plugin,\n ret.filter(p => isPlugin(p))\n )\n ) {\n return ret;\n }\n\n ret.push(plugin);\n\n return ret;\n }, [] as PluginConfig[]);\n\n // Apply path token replacements\n\n if (this.config.tsconfig) {\n this.config.tsconfig = replacePathTokens(this, this.config.tsconfig);\n }\n\n if (this.config.output.dts) {\n if (isSetString(this.config.output.dts)) {\n this.config.output.dts = replacePathTokens(\n this,\n this.config.output.dts\n );\n } else {\n this.config.output.dts = joinPaths(\n this.config.root,\n `${this.config.framework ?? \"powerlines\"}.d.ts`\n );\n }\n }\n\n if (this.config.output.assets) {\n this.config.output.assets = this.config.output.assets.map(asset => ({\n ...asset,\n glob: replacePathTokens(this, asset.glob),\n ignore: asset.ignore\n ? asset.ignore.map(ignore => replacePathTokens(this, ignore))\n : undefined,\n input: replacePathTokens(this, asset.input),\n output: replacePathTokens(this, asset.output)\n }));\n }\n\n if (\n (isSetString(config.output?.storage) &&\n config.output.storage === \"virtual\") ||\n (isSetObject(config.output?.storage) &&\n Object.values(config.output.storage).every(\n adapter => adapter.preset === \"virtual\"\n ))\n ) {\n this.config.output.overwrite = true;\n }\n\n this.#fs ??= await VirtualFileSystem.create(this);\n }\n\n protected mergeUserConfig(\n from: Partial<TResolvedConfig[\"userConfig\"]> = {},\n into: Partial<TResolvedConfig[\"userConfig\"]> = this.config.userConfig ?? {}\n ) {\n this.config.userConfig = mergeConfig(\n {\n input:\n isSetObject(from.input) &&\n !isRegExp(from.input) &&\n !Array.isArray(from.input) &&\n from.input.file\n ? from.input.file\n : isSetObject(into?.input) &&\n !isRegExp(into.input) &&\n !Array.isArray(into.input) &&\n into.input.file\n ? into.input.file\n : Array.isArray(from.input) && from.input.length > 0\n ? from.input\n : Array.isArray(into?.input) && into.input.length > 0\n ? into.input\n : []\n },\n omit(from ?? {}, [\"input\"]),\n omit(into ?? {}, [\"input\"])\n ) as TResolvedConfig[\"userConfig\"];\n\n if (this.config.userConfig.output?.format) {\n this.config.userConfig.output.format = getUnique(\n toArray(this.config.userConfig.output?.format)\n );\n }\n\n this.config.userConfig.plugins = (this.config.userConfig.plugins ?? [])\n .filter(Boolean)\n .reduce((ret, plugin) => {\n if (\n isPlugin(plugin) &&\n checkDedupe(\n plugin,\n ret.filter(p => isPlugin(p))\n )\n ) {\n return ret;\n }\n\n ret.push(plugin);\n\n return ret;\n }, [] as PluginConfig[]);\n }\n}\n","/* -------------------------------------------------------------------\n\n ⚡ Storm Software - Powerlines\n\n This code was released as part of the Powerlines project. Powerlines\n is maintained by Storm Software under the Apache-2.0 license, and is\n free for commercial and private use. For more information, please visit\n our licensing page at https://stormsoftware.com/licenses/projects/powerlines.\n\n Website: https://stormsoftware.com\n Repository: https://github.com/storm-software/powerlines\n Documentation: https://docs.stormsoftware.com/projects/powerlines\n Contact: https://stormsoftware.com/contact\n\n SPDX-License-Identifier: Apache-2.0\n\n ------------------------------------------------------------------- */\n\n/* -------------------------------------------------------------------\n\n ⚡ Storm Software - Powerlines\n\n This code was released as part of the Powerlines project. Powerlines\n is maintained by Storm Software under the Apache-2.0 license, and is\n free for commercial and private use. For more information, please visit\n our licensing page at https://stormsoftware.com/licenses/projects/powerlines.\n\n Website: https://stormsoftware.com\n Repository: https://github.com/storm-software/powerlines\n Documentation: https://docs.stormsoftware.com/projects/powerlines\n Contact: https://stormsoftware.com/contact\n\n SPDX-License-Identifier: Apache-2.0\n\n ------------------------------------------------------------------- */\n\nimport type {\n API,\n Context,\n UnpluginBuilderVariant,\n UnpluginFactory,\n UnpluginOptions\n} from \"@powerlines/core\";\nimport { createLog } from \"@powerlines/core/lib/logger\";\nimport { getString } from \"@powerlines/core/lib/utilities/source-file\";\nimport { LogLevelLabel } from \"@storm-software/config-tools/types\";\nimport { getWorkspaceRoot } from \"@stryke/fs/get-workspace-root\";\nimport { LoadResult } from \"rolldown\";\nimport type {\n UnpluginOptions as BaseUnpluginOptions,\n TransformResult,\n UnpluginBuildContext,\n UnpluginContext\n} from \"unplugin\";\nimport { setParseImpl } from \"unplugin\";\nimport { PowerlinesAPI } from \"./api\";\n\nexport * from \"@powerlines/core/lib/unplugin\";\n\n/**\n * Creates a Powerlines unplugin factory that generates a plugin instance.\n *\n * @param variant - The build variant for which to create the unplugin.\n * @param decorate - An optional function to decorate the unplugin options.\n * @returns The unplugin factory that generates a plugin instance.\n */\nexport function createUnpluginFactory<\n TContext extends Context,\n TUnpluginBuilderVariant extends UnpluginBuilderVariant =\n UnpluginBuilderVariant\n>(\n variant: TUnpluginBuilderVariant,\n decorate?: (\n api: API<TContext[\"config\"]>,\n plugin: UnpluginOptions<TContext>\n ) => BaseUnpluginOptions\n): UnpluginFactory<TContext> {\n return (config, meta): UnpluginOptions<TContext> => {\n const log = createLog(\"unplugin\", config);\n log(LogLevelLabel.DEBUG, \"Initializing Unplugin\");\n\n try {\n const userConfig = {\n ...config,\n variant,\n unplugin: meta\n } as TContext[\"config\"][\"userConfig\"];\n\n let api!: API<TContext[\"config\"]>;\n\n async function buildStart(this: UnpluginBuildContext): Promise<void> {\n log(LogLevelLabel.DEBUG, \"Powerlines build plugin starting...\");\n\n api = await PowerlinesAPI.from(\n getWorkspaceRoot(process.cwd()),\n userConfig\n );\n setParseImpl(api.context.parse);\n\n log(\n LogLevelLabel.DEBUG,\n \"Preparing build artifacts for the Powerlines project...\"\n );\n\n await api.prepare({\n command: \"build\"\n });\n }\n\n async function resolveId(\n this: UnpluginBuildContext & UnpluginContext,\n id: string,\n importer?: string,\n options: {\n isEntry: boolean;\n } = { isEntry: false }\n ) {\n return api.context.resolve(id, importer, options);\n }\n\n async function load(\n this: UnpluginBuildContext & UnpluginContext,\n id: string\n ): Promise<LoadResult> {\n const environment = await api.context.getEnvironment();\n\n let result = await api.callHook(\n \"load\",\n { environment, order: \"pre\" },\n id\n );\n if (result) {\n return result;\n }\n\n result = await api.callHook(\n \"load\",\n { environment, order: \"normal\" },\n id\n );\n if (result) {\n return result;\n }\n\n result = await environment.load(id);\n if (result) {\n return result;\n }\n\n return api.callHook(\"load\", { environment, order: \"post\" }, id);\n }\n\n async function transform(\n code: string,\n id: string\n ): Promise<TransformResult> {\n return api.callHook(\n \"transform\",\n {\n environment: await api.context.getEnvironment(),\n result: \"merge\",\n asNextParam: previousResult => getString(previousResult)\n },\n getString(code),\n id\n );\n }\n\n async function writeBundle(): Promise<void> {\n log(LogLevelLabel.DEBUG, \"Finalizing Powerlines project output...\");\n\n await api.callHook(\"writeBundle\", {\n environment: await api.context.getEnvironment()\n });\n }\n\n const options = {\n name: \"powerlines\",\n api,\n resolveId: {\n filter: {\n id: {\n include: [/.*/]\n }\n },\n handler: resolveId\n },\n load: {\n filter: {\n id: {\n include: [/.*/, /^storm:/]\n }\n },\n handler: load\n },\n transform,\n buildStart,\n writeBundle\n } as UnpluginOptions<TContext>;\n\n const result = decorate ? decorate(api, options) : options;\n\n log(LogLevelLabel.DEBUG, \"Unplugin initialized successfully.\");\n\n return { api, ...result };\n } catch (error) {\n log(LogLevelLabel.FATAL, (error as Error)?.message);\n\n throw error;\n }\n };\n}\n","/* -------------------------------------------------------------------\n\n ⚡ Storm Software - Powerlines\n\n This code was released as part of the Powerlines project. Powerlines\n is maintained by Storm Software under the Apache-2.0 license, and is\n free for commercial and private use. For more information, please visit\n our licensing page at https://stormsoftware.com/licenses/projects/powerlines.\n\n Website: https://stormsoftware.com\n Repository: https://github.com/storm-software/powerlines\n Documentation: https://docs.stormsoftware.com/projects/powerlines\n Contact: https://stormsoftware.com/contact\n\n SPDX-License-Identifier: Apache-2.0\n\n ------------------------------------------------------------------- */\n\nimport {\n UNSAFE_EnvironmentContext,\n UNSAFE_PluginContext\n} from \"@powerlines/core/types/_internal\";\nimport { LogLevelLabel } from \"@storm-software/config-tools/types\";\nimport { isString } from \"@stryke/type-checks/is-string\";\nimport { UnpluginMessage } from \"unplugin\";\nimport type {\n CallHookOptions,\n EnvironmentContext,\n InferHookParameters,\n InferHookReturnType,\n LogFn,\n Plugin,\n PluginContext,\n ResolvedConfig\n} from \"../types\";\n\n/**\n * Create a Proxy-based PluginContext\n *\n * @param plugin - The plugin instance\n * @param environment - The environment context\n * @returns The proxied plugin context\n */\nexport function createPluginContext<\n TResolvedConfig extends ResolvedConfig = ResolvedConfig\n>(\n plugin: Plugin<PluginContext<TResolvedConfig>>,\n environment: UNSAFE_EnvironmentContext<TResolvedConfig>\n): UNSAFE_PluginContext<TResolvedConfig> {\n const normalizeMessage = (message: string | UnpluginMessage): string => {\n return isString(message) ? message : message.message;\n };\n\n const log: LogFn = environment.extendLog(plugin.name.replaceAll(\":\", \" - \"));\n\n const callHookFn = async <TKey extends string>(\n hook: TKey,\n options: CallHookOptions,\n ...args: InferHookParameters<PluginContext<TResolvedConfig>, TKey>\n ): Promise<\n InferHookReturnType<PluginContext<TResolvedConfig>, TKey> | undefined\n > => {\n return environment.$$internal.api.callHook(\n hook,\n {\n sequential: true,\n result: \"merge\",\n ...options,\n environment\n } as Parameters<typeof environment.$$internal.api.callHook>[1],\n ...args\n );\n };\n\n const meta = {} as Record<string, any>;\n\n return new Proxy({} as UNSAFE_PluginContext<TResolvedConfig>, {\n get(_, prop) {\n if (prop === \"$$internal\") {\n return {\n ...environment.$$internal,\n environment,\n callHook: callHookFn,\n meta\n };\n }\n\n if (prop === \"log\" || prop === \"logger\") {\n return log;\n }\n\n if (prop === \"fatal\") {\n return (message: string | UnpluginMessage) => {\n log(LogLevelLabel.FATAL, normalizeMessage(message));\n };\n }\n\n if (prop === \"error\") {\n return (message: string | UnpluginMessage) => {\n log(LogLevelLabel.ERROR, normalizeMessage(message));\n };\n }\n\n if (prop === \"warn\") {\n return (message: string | UnpluginMessage) => {\n log(LogLevelLabel.WARN, normalizeMessage(message));\n };\n }\n\n if (prop === \"info\") {\n return (message: string | UnpluginMessage) => {\n log(LogLevelLabel.INFO, normalizeMessage(message));\n };\n }\n\n if (prop === \"debug\") {\n return (message: string | UnpluginMessage) => {\n log(LogLevelLabel.DEBUG, normalizeMessage(message));\n };\n }\n\n if (prop === \"trace\") {\n return (message: string | UnpluginMessage) => {\n log(LogLevelLabel.TRACE, normalizeMessage(message));\n };\n }\n\n return environment[prop as keyof EnvironmentContext<TResolvedConfig>];\n },\n set(_, prop, value) {\n if (\n [\n \"$$internal\",\n \"environment\",\n \"config\",\n \"log\",\n \"logger\",\n \"error\",\n \"warn\",\n \"plugins\",\n \"hooks\",\n \"addPlugin\",\n \"selectHooks\"\n ].includes(prop as string)\n ) {\n log(\n LogLevelLabel.WARN,\n `Cannot set read-only property \"${String(prop)}\"`\n );\n\n return false;\n }\n\n environment[prop as keyof EnvironmentContext<TResolvedConfig>] = value;\n return true;\n }\n });\n}\n","/* -------------------------------------------------------------------\n\n ⚡ Storm Software - Powerlines\n\n This code was released as part of the Powerlines project. Powerlines\n is maintained by Storm Software under the Apache-2.0 license, and is\n free for commercial and private use. For more information, please visit\n our licensing page at https://stormsoftware.com/licenses/projects/powerlines.\n\n Website: https://stormsoftware.com\n Repository: https://github.com/storm-software/powerlines\n Documentation: https://docs.stormsoftware.com/projects/powerlines\n Contact: https://stormsoftware.com/contact\n\n SPDX-License-Identifier: Apache-2.0\n\n ------------------------------------------------------------------- */\n\nimport { resolvePackage } from \"@stryke/fs/resolve\";\nimport { isFunction } from \"@stryke/type-checks/is-function\";\nimport { isObject } from \"@stryke/type-checks/is-object\";\nimport { isSetObject } from \"@stryke/type-checks/is-set-object\";\nimport { ArrayValues } from \"@stryke/types/array\";\nimport { AnyFunction } from \"@stryke/types/base\";\nimport { PLUGIN_NON_HOOK_FIELDS } from \"../constants\";\nimport {\n addPluginHook,\n isPlugin,\n isPluginConfig,\n isPluginHook,\n isPluginHookField,\n isUnpluginHookField,\n isUnpluginHookKey\n} from \"../plugin-utils\";\nimport type {\n EnvironmentContext,\n EnvironmentContextPlugin,\n EnvironmentResolvedConfig,\n HookFields,\n HookListOrders,\n HooksList,\n InferHooksListItem,\n Plugin,\n PluginConfig,\n PluginContext,\n PluginHook,\n PluginHookFields,\n PluginHooksListItem,\n ResolvedConfig,\n SelectHookResult,\n SelectHookResultItem,\n SelectHooksOptions,\n UnpluginHookList,\n UnpluginHooksListItem,\n UnpluginOptions,\n WorkspaceConfig\n} from \"../types\";\nimport { isUnpluginBuilderVariant } from \"../unplugin\";\nimport { PowerlinesContext } from \"./context\";\nimport { createPluginContext } from \"./plugin-context\";\n\nexport class PowerlinesEnvironmentContext<\n TResolvedConfig extends ResolvedConfig = ResolvedConfig\n>\n extends PowerlinesContext<TResolvedConfig>\n implements EnvironmentContext<TResolvedConfig>\n{\n /**\n * The hooks registered by plugins in this environment\n */\n #hooks: HooksList<PluginContext<TResolvedConfig>> = {} as HooksList<\n PluginContext<TResolvedConfig>\n >;\n\n /**\n * Create a new Storm context from the workspace root and user config.\n *\n * @param workspaceConfig - The root directory of the workspace.\n * @param config - The user configuration options.\n * @returns A promise that resolves to the new context.\n */\n public static async fromConfig<\n TResolvedConfig extends ResolvedConfig = ResolvedConfig\n >(\n workspaceConfig: WorkspaceConfig,\n config: TResolvedConfig\n ): Promise<PowerlinesEnvironmentContext<TResolvedConfig>> {\n const context = new PowerlinesEnvironmentContext<TResolvedConfig>(\n config,\n workspaceConfig\n );\n await context.init();\n\n const powerlinesPath = await resolvePackage(\"powerlines\");\n if (!powerlinesPath) {\n throw new Error(\"Could not resolve `powerlines` package location.\");\n }\n\n context.powerlinesPath = powerlinesPath;\n\n return context;\n }\n\n /**\n * The resolved environment configuration\n */\n public environment!: EnvironmentResolvedConfig;\n\n /**\n * The list of plugins applied to this environment\n */\n public plugins: EnvironmentContextPlugin<TResolvedConfig>[] = [];\n\n /**\n * The resolved configuration options\n */\n public override get config(): TResolvedConfig {\n return super.config;\n }\n\n public get hooks(): HooksList<PluginContext<TResolvedConfig>> {\n return this.#hooks;\n }\n\n public async addPlugin(plugin: Plugin<PluginContext<TResolvedConfig>>) {\n let resolvedPlugin = plugin;\n if (isFunction(plugin.applyToEnvironment)) {\n const result = (await Promise.resolve(\n plugin.applyToEnvironment(this.environment) as Promise<any>\n )) as boolean | PluginConfig<PluginContext<TResolvedConfig>>;\n\n if (!result || (isObject(result) && Object.keys(result).length === 0)) {\n return;\n }\n\n if (isPluginConfig<PluginContext<TResolvedConfig>>(result)) {\n return this.$$internal.addPlugin(result);\n }\n\n resolvedPlugin = isPlugin<PluginContext<TResolvedConfig>>(result)\n ? result\n : plugin;\n }\n\n const context = createPluginContext<TResolvedConfig>(resolvedPlugin, this);\n\n this.plugins.push({\n plugin: resolvedPlugin,\n context\n });\n\n this.#hooks = Object.keys(resolvedPlugin)\n .filter(\n key =>\n !PLUGIN_NON_HOOK_FIELDS.includes(\n key as ArrayValues<typeof PLUGIN_NON_HOOK_FIELDS>\n )\n )\n .reduce((ret, key) => {\n const hook = key as HookFields<PluginContext<TResolvedConfig>>;\n\n if (isPluginHookField<PluginContext<TResolvedConfig>>(hook)) {\n const pluginHook = resolvedPlugin[hook];\n if (!isPluginHook(pluginHook)) {\n return ret;\n }\n\n ret[hook] ??= {\n preEnforced: [],\n preOrdered: [],\n normal: [],\n postEnforced: [],\n postOrdered: []\n };\n\n if (resolvedPlugin.enforce) {\n const hookListOrder =\n `${resolvedPlugin.enforce}Enforced` as HookListOrders;\n ret[hook][hookListOrder] ??= [];\n\n const bucket = ret[hook][hookListOrder];\n addPluginHook<\n PluginContext<TResolvedConfig>,\n PluginHookFields<PluginContext<TResolvedConfig>>\n >(context, resolvedPlugin, pluginHook, bucket);\n\n return ret;\n }\n\n if (isFunction(pluginHook) || !pluginHook.order) {\n ret[hook].normal ??= [];\n\n const bucket = ret[hook].normal;\n addPluginHook<\n PluginContext<TResolvedConfig>,\n PluginHookFields<PluginContext<TResolvedConfig>>\n >(context, resolvedPlugin, pluginHook, bucket);\n\n return ret;\n }\n\n const hookListOrder = `${pluginHook.order}Ordered` as HookListOrders;\n ret[hook][hookListOrder] ??= [];\n\n addPluginHook(\n context,\n resolvedPlugin,\n pluginHook,\n ret[hook][hookListOrder] as PluginHooksListItem<\n PluginContext<TResolvedConfig>\n >[]\n );\n\n return ret;\n } else if (isUnpluginHookField(hook)) {\n const unpluginPlugin = resolvedPlugin[hook];\n if (!isSetObject(unpluginPlugin)) {\n return ret;\n }\n\n for (const field of Object.keys(unpluginPlugin)) {\n const variantField = field as keyof UnpluginOptions[typeof hook];\n\n const pluginHook = unpluginPlugin[\n variantField\n ] as PluginHook<AnyFunction>;\n if (!isPluginHook(pluginHook)) {\n continue;\n }\n\n ret[hook] ??= {};\n (ret[hook][variantField] as UnpluginHookList<\n PluginContext<TResolvedConfig>,\n typeof variantField\n >) ??= {\n preEnforced: [],\n preOrdered: [],\n normal: [],\n postEnforced: [],\n postOrdered: []\n };\n\n if (resolvedPlugin.enforce) {\n addPluginHook(\n context,\n resolvedPlugin,\n pluginHook,\n ret[hook][variantField][\n `${resolvedPlugin.enforce}Enforced`\n ] as UnpluginHooksListItem<PluginContext<TResolvedConfig>>[]\n );\n\n return ret;\n }\n\n if (isFunction(pluginHook) || !pluginHook.order) {\n addPluginHook(\n context,\n resolvedPlugin,\n pluginHook,\n\n (\n ret[hook][variantField] as UnpluginHookList<\n PluginContext<TResolvedConfig>,\n typeof variantField\n >\n ).normal!\n );\n\n return ret;\n }\n\n addPluginHook(\n context,\n resolvedPlugin,\n pluginHook,\n ret[hook][variantField][\n `${pluginHook.order}Ordered`\n ] as UnpluginHooksListItem<PluginContext<TResolvedConfig>>[]\n );\n }\n } else {\n this.warn(`Unknown plugin hook field: ${String(hook)}`);\n }\n\n return ret;\n }, this.hooks);\n }\n\n /**\n * Retrieves the hook handlers for a specific hook name\n */\n public selectHooks<TKey extends string>(\n key: TKey,\n options?: SelectHooksOptions\n ): SelectHookResult<PluginContext<TResolvedConfig>, TKey> {\n const result = [] as SelectHookResult<PluginContext<TResolvedConfig>, TKey>;\n\n if (isUnpluginHookKey(key)) {\n const variant = String(key).split(\":\")[0];\n if (isUnpluginBuilderVariant(variant)) {\n const hooks = this.hooks[variant];\n if (hooks) {\n const field = String(key).split(\":\")[1] as keyof typeof hooks;\n if (field && hooks[field]) {\n const fieldHooks = hooks[field] as Record<\n HookListOrders,\n InferHooksListItem<PluginContext<TResolvedConfig>, TKey>[]\n >;\n\n if (options?.order) {\n const mapHooksToResult = (\n hooksList: InferHooksListItem<\n PluginContext<TResolvedConfig>,\n TKey\n >[]\n ): SelectHookResult<PluginContext<TResolvedConfig>, TKey> =>\n hooksList.map(hook => {\n const plugin = this.plugins.find(\n p => p.plugin.name === hook.plugin.name\n );\n if (!plugin) {\n throw new Error(\n `Could not find plugin context for plugin \"${\n hook.plugin.name\n }\".`\n );\n }\n\n return {\n handler: hook.handler,\n plugin: hook.plugin,\n context: plugin.context\n } as SelectHookResultItem<\n PluginContext<TResolvedConfig>,\n TKey\n >;\n });\n\n if (options?.order === \"pre\") {\n result.push(...mapHooksToResult(fieldHooks.preOrdered ?? []));\n result.push(...mapHooksToResult(fieldHooks.preEnforced ?? []));\n } else if (options?.order === \"post\") {\n result.push(...mapHooksToResult(fieldHooks.postOrdered ?? []));\n result.push(...mapHooksToResult(fieldHooks.postEnforced ?? []));\n } else {\n result.push(...mapHooksToResult(fieldHooks.normal ?? []));\n }\n } else {\n result.push(...this.selectHooks(key, { order: \"pre\" }));\n result.push(...this.selectHooks(key, { order: \"normal\" }));\n result.push(...this.selectHooks(key, { order: \"post\" }));\n }\n }\n }\n }\n } else if (isPluginHookField<PluginContext<TResolvedConfig>>(key)) {\n if (this.hooks[key]) {\n const fieldHooks = this.hooks[key] as Record<\n HookListOrders,\n InferHooksListItem<PluginContext<TResolvedConfig>, TKey>[]\n >;\n\n if (options?.order) {\n const mapHooksToResult = (\n hooksList: InferHooksListItem<\n PluginContext<TResolvedConfig>,\n TKey\n >[]\n ): SelectHookResult<PluginContext<TResolvedConfig>, TKey> =>\n hooksList.map(hook => {\n const plugin = this.plugins.find(\n p => p.plugin.name === hook.plugin.name\n );\n if (!plugin) {\n throw new Error(\n `Could not find plugin context for plugin \"${\n hook.plugin.name\n }\".`\n );\n }\n\n return {\n handler: hook.handler,\n plugin: hook.plugin,\n context: plugin.context\n } as SelectHookResultItem<PluginContext<TResolvedConfig>, TKey>;\n });\n\n if (options?.order === \"pre\") {\n result.push(...mapHooksToResult(fieldHooks.preOrdered ?? []));\n result.push(...mapHooksToResult(fieldHooks.preEnforced ?? []));\n } else if (options?.order === \"post\") {\n result.push(...mapHooksToResult(fieldHooks.postOrdered ?? []));\n result.push(...mapHooksToResult(fieldHooks.postEnforced ?? []));\n } else {\n result.push(...mapHooksToResult(fieldHooks.normal ?? []));\n }\n } else {\n result.push(...this.selectHooks(key, { order: \"pre\" }));\n result.push(...this.selectHooks(key, { order: \"normal\" }));\n result.push(...this.selectHooks(key, { order: \"post\" }));\n }\n }\n } else {\n throw new Error(`Unknown plugin hook key: ${String(key)}`);\n }\n\n return result;\n }\n\n protected constructor(\n config: TResolvedConfig,\n workspaceConfig: WorkspaceConfig\n ) {\n super(workspaceConfig);\n\n this.resolvedConfig = config;\n }\n}\n","/* -------------------------------------------------------------------\n\n ⚡ Storm Software - Powerlines\n\n This code was released as part of the Powerlines project. Powerlines\n is maintained by Storm Software under the Apache-2.0 license, and is\n free for commercial and private use. For more information, please visit\n our licensing page at https://stormsoftware.com/licenses/projects/powerlines.\n\n Website: https://stormsoftware.com\n Repository: https://github.com/storm-software/powerlines\n Documentation: https://docs.stormsoftware.com/projects/powerlines\n Contact: https://stormsoftware.com/contact\n\n SPDX-License-Identifier: Apache-2.0\n\n ------------------------------------------------------------------- */\n\nimport {\n UNSAFE_ContextInternal,\n UNSAFE_EnvironmentContext\n} from \"@powerlines/core/types/_internal\";\nimport { toArray } from \"@stryke/convert/to-array\";\nimport { resolvePackage } from \"@stryke/fs/resolve\";\nimport { isSetObject } from \"@stryke/type-checks/is-set-object\";\nimport chalk from \"chalk\";\nimport {\n createDefaultEnvironment,\n createEnvironment\n} from \"../_internal/helpers/environment\";\nimport { loadWorkspaceConfig } from \"../config\";\nimport { GLOBAL_ENVIRONMENT } from \"../constants\";\nimport type {\n APIContext,\n EnvironmentContext,\n EnvironmentResolvedConfig,\n InitContextOptions,\n InitialUserConfig,\n InlineConfig,\n LogFn,\n Plugin,\n PluginContext,\n ResolvedConfig,\n UserConfig,\n WorkspaceConfig\n} from \"../types\";\nimport { PowerlinesContext } from \"./context\";\nimport { PowerlinesEnvironmentContext } from \"./environment-context\";\n\nexport class PowerlinesAPIContext<\n TResolvedConfig extends ResolvedConfig = ResolvedConfig\n>\n extends PowerlinesContext<TResolvedConfig>\n implements APIContext<TResolvedConfig>\n{\n #environments: Record<string, UNSAFE_EnvironmentContext<TResolvedConfig>> =\n {};\n\n #plugins: Plugin<PluginContext<TResolvedConfig>>[] = [];\n\n #log!: LogFn;\n\n /**\n * Create a new Storm context from the workspace root and user config.\n *\n * @param workspaceRoot - The root directory of the workspace.\n * @param config - The user configuration options.\n * @returns A promise that resolves to the new context.\n */\n public static override async from<\n TResolvedConfig extends ResolvedConfig = ResolvedConfig\n >(\n workspaceRoot: string,\n config: InitialUserConfig<TResolvedConfig[\"userConfig\"]>\n ): Promise<APIContext<TResolvedConfig>> {\n const context = new PowerlinesAPIContext<TResolvedConfig>(\n await loadWorkspaceConfig(workspaceRoot, config.root)\n );\n await context.withUserConfig(config);\n\n const powerlinesPath = await resolvePackage(\"powerlines\");\n if (!powerlinesPath) {\n throw new Error(\"Could not resolve `powerlines` package location.\");\n }\n\n context.powerlinesPath = powerlinesPath;\n\n return context;\n }\n\n /**\n * Internal context fields and methods\n *\n * @danger\n * This field is for internal use only and should not be accessed or modified directly. It is unstable and can be changed at anytime.\n *\n * @internal\n */\n public override get $$internal(): UNSAFE_ContextInternal<TResolvedConfig> {\n return super.$$internal;\n }\n\n /**\n * Internal context fields and methods\n *\n * @danger\n * This field is for internal use only and should not be accessed or modified directly. It is unstable and can be changed at anytime.\n *\n * @internal\n */\n public override set $$internal(\n value: UNSAFE_ContextInternal<TResolvedConfig>\n ) {\n super.$$internal = value;\n for (const environment of Object.values(this.environments)) {\n environment.$$internal = super.$$internal;\n }\n }\n\n /**\n * A record of all environments by name\n */\n public get environments(): Record<\n string,\n UNSAFE_EnvironmentContext<TResolvedConfig>\n > {\n return this.#environments;\n }\n\n public override get log(): LogFn {\n if (!this.#log) {\n this.#log = this.createLog();\n }\n\n return this.#log;\n }\n\n public get plugins(): Array<Plugin<PluginContext<TResolvedConfig>>> {\n return this.#plugins;\n }\n\n protected constructor(workspaceConfig: WorkspaceConfig) {\n super(workspaceConfig);\n }\n\n /**\n * Initialize the context with the provided configuration options\n *\n * @param config - The partial user configuration to use for initialization.\n */\n protected override async init(\n config: Partial<TResolvedConfig[\"userConfig\"]> = {}\n ) {\n await super.init(config);\n\n await Promise.all(\n toArray(\n this.config.userConfig.environments &&\n Object.keys(this.config.userConfig.environments).length > 0\n ? Object.keys(this.config.userConfig.environments).map(name =>\n createEnvironment(name, this.config.userConfig)\n )\n : createDefaultEnvironment(this.config.userConfig)\n ).map(async env => {\n this.#environments[env.name] = await this.in(env);\n })\n );\n }\n\n /**\n * A function to copy the context and update the fields for a specific environment\n *\n * @param environment - The environment configuration to use.\n * @returns A new context instance with the updated environment.\n */\n public async in(\n environment: EnvironmentResolvedConfig\n ): Promise<UNSAFE_EnvironmentContext<TResolvedConfig>> {\n let context: UNSAFE_EnvironmentContext<TResolvedConfig>;\n if (this.environments[environment.name]) {\n context = this.environments[environment.name] as any;\n } else {\n context = (await PowerlinesEnvironmentContext.fromConfig(\n this.workspaceConfig,\n this.config\n )) as any;\n }\n\n if (isSetObject(this.config.inlineConfig)) {\n await context.withInlineConfig(this.config.inlineConfig);\n }\n\n context.environment = environment;\n context.plugins = [];\n\n for (const plugin of this.plugins) {\n await context.addPlugin(plugin);\n }\n\n return context;\n }\n\n /**\n * Update the context using a new user configuration options\n *\n * @param userConfig - The new user configuration options.\n */\n public override async withUserConfig(\n userConfig: InitialUserConfig<TResolvedConfig[\"userConfig\"]>,\n options: InitContextOptions = {\n isHighPriority: true\n }\n ) {\n await super.withUserConfig(userConfig, options);\n\n await Promise.all(\n Object.keys(this.#environments).map(async name => {\n await this.#environments[name]!.withUserConfig(\n userConfig as UserConfig,\n options\n );\n })\n );\n }\n\n /**\n * Update the context using a new inline configuration options\n *\n * @param inlineConfig - The new inline configuration options.\n */\n public override async withInlineConfig(\n inlineConfig: TResolvedConfig[\"inlineConfig\"],\n options: InitContextOptions = {\n isHighPriority: true\n }\n ) {\n await super.withInlineConfig(inlineConfig, options);\n\n await Promise.all(\n Object.keys(this.#environments).map(async name => {\n await this.#environments[name]!.withInlineConfig(\n inlineConfig as InlineConfig,\n options\n );\n })\n );\n }\n\n /**\n * Add a plugin to the API context and all environments\n *\n * @param plugin - The plugin to add.\n */\n public async addPlugin(plugin: Plugin<PluginContext<TResolvedConfig>>) {\n this.plugins.push(plugin);\n\n await Promise.all(\n Object.keys(this.environments).map(async name => {\n await this.environments[name]!.addPlugin(plugin);\n })\n );\n }\n\n /**\n * Get an environment by name, or the default environment if no name is provided\n *\n * @param name - The name of the environment to retrieve.\n * @returns The requested environment context.\n */\n public async getEnvironment(name?: string) {\n let environment: EnvironmentContext<TResolvedConfig> | undefined;\n if (name) {\n environment = this.environments[name];\n }\n\n if (Object.keys(this.environments).length === 1) {\n environment = this.environments[Object.keys(this.environments)[0]!];\n\n this.debug(\n `Applying the only configured environment: ${chalk.bold.cyanBright(\n environment?.environment.name\n )}`\n );\n }\n\n if (!environment) {\n if (name) {\n throw new Error(`Environment \"${name}\" not found.`);\n }\n\n environment = await this.in(\n createDefaultEnvironment(this.config.userConfig)\n );\n\n this.warn(\n `No environment specified, and no default environment found. Using a temporary default environment: ${chalk.bold.cyanBright(\n environment?.environment.name\n )}`\n );\n }\n\n return environment;\n }\n\n /**\n * A safe version of `getEnvironment` that returns `undefined` if the environment is not found\n *\n * @param name - The name of the environment to retrieve.\n * @returns The requested environment context or `undefined` if not found.\n */\n public async getEnvironmentSafe(\n name?: string\n ): Promise<EnvironmentContext<TResolvedConfig> | undefined> {\n try {\n return await this.getEnvironment(name);\n } catch {\n return undefined;\n }\n }\n\n /**\n * A function to merge all configured environments into a single context.\n *\n * @remarks\n * If only one environment is configured, that environment will be returned directly.\n *\n * @returns A promise that resolves to a merged/global environment context.\n */\n public async toEnvironment(): Promise<EnvironmentContext<TResolvedConfig>> {\n let environment: EnvironmentContext<TResolvedConfig>;\n if (Object.keys(this.environments).length > 1) {\n environment = await this.in(\n createEnvironment(GLOBAL_ENVIRONMENT, this.config.userConfig)\n );\n\n this.debug(\n `Combined all ${Object.keys(this.environments).length} environments into a single global context.`\n );\n } else {\n environment = await this.getEnvironment();\n }\n\n return environment;\n }\n}\n","/* -------------------------------------------------------------------\n\n ⚡ Storm Software - Powerlines\n\n This code was released as part of the Powerlines project. Powerlines\n is maintained by Storm Software under the Apache-2.0 license, and is\n free for commercial and private use. For more information, please visit\n our licensing page at https://stormsoftware.com/licenses/projects/powerlines.\n\n Website: https://stormsoftware.com\n Repository: https://github.com/storm-software/powerlines\n Documentation: https://docs.stormsoftware.com/projects/powerlines\n Contact: https://stormsoftware.com/contact\n\n SPDX-License-Identifier: Apache-2.0\n\n ------------------------------------------------------------------- */\n\nimport { UNSAFE_APIContext } from \"@powerlines/core/types/_internal\";\nimport { formatLogMessage } from \"@storm-software/config-tools/logger/console\";\nimport { toArray } from \"@stryke/convert/to-array\";\nimport { createDirectory } from \"@stryke/fs/helpers\";\nimport { install } from \"@stryke/fs/install\";\nimport { listFiles } from \"@stryke/fs/list-files\";\nimport { isPackageExists } from \"@stryke/fs/package-fns\";\nimport { resolvePackage } from \"@stryke/fs/resolve\";\nimport { omit } from \"@stryke/helpers/omit\";\nimport { appendPath } from \"@stryke/path/append\";\nimport { joinPaths } from \"@stryke/path/join-paths\";\nimport { replacePath } from \"@stryke/path/replace\";\nimport { isError } from \"@stryke/type-checks/is-error\";\nimport { isFunction } from \"@stryke/type-checks/is-function\";\nimport { isNumber } from \"@stryke/type-checks/is-number\";\nimport { isObject } from \"@stryke/type-checks/is-object\";\nimport { isPromiseLike } from \"@stryke/type-checks/is-promise\";\nimport { isSet } from \"@stryke/type-checks/is-set\";\nimport { isSetObject } from \"@stryke/type-checks/is-set-object\";\nimport { isSetString } from \"@stryke/type-checks/is-set-string\";\nimport { isString } from \"@stryke/type-checks/is-string\";\nimport { MaybePromise } from \"@stryke/types/base\";\nimport chalk from \"chalk\";\nimport Handlebars from \"handlebars\";\nimport packageJson from \"../package.json\" assert { type: \"json\" };\nimport {\n emitBuiltinTypes,\n formatTypes\n} from \"./_internal/helpers/generate-types\";\nimport { callHook, mergeConfigs } from \"./_internal/helpers/hooks\";\nimport { installDependencies } from \"./_internal/helpers/install-dependencies\";\nimport { writeMetaFile } from \"./_internal/helpers/meta\";\nimport {\n getTsconfigDtsPath,\n initializeTsconfig,\n resolveTsconfig\n} from \"./_internal/helpers/resolve-tsconfig\";\nimport { PowerlinesAPIContext } from \"./context/api-context\";\nimport {\n checkDedupe,\n findInvalidPluginConfig,\n isPlugin,\n isPluginConfig,\n isPluginConfigObject,\n isPluginConfigTuple\n} from \"./plugin-utils\";\nimport type {\n APIContext,\n BuildInlineConfig,\n CleanInlineConfig,\n DeployInlineConfig,\n DocsInlineConfig,\n EnvironmentContext,\n InitialUserConfig,\n LintInlineConfig,\n NewInlineConfig,\n Plugin,\n PluginConfig,\n PluginConfigObject,\n PluginConfigTuple,\n PluginContext,\n PluginFactory,\n PrepareInlineConfig,\n TypesResult\n} from \"./types\";\nimport {\n API,\n CallHookOptions,\n EnvironmentResolvedConfig,\n InferHookParameters,\n ResolvedConfig\n} from \"./types\";\nimport {\n getParsedTypeScriptConfig,\n isIncludeMatchFound\n} from \"./typescript/tsconfig\";\nimport { formatFolder, getTypescriptFileHeader } from \"./utils\";\n\n/**\n * The Powerlines API class\n *\n * @remarks\n * This class is responsible for managing the Powerlines project lifecycle, including initialization, building, and finalization.\n *\n * @public\n */\nexport class PowerlinesAPI<\n TResolvedConfig extends ResolvedConfig = ResolvedConfig\n>\n implements API<TResolvedConfig>, AsyncDisposable\n{\n /**\n * The Powerlines context\n */\n #context: UNSAFE_APIContext<TResolvedConfig>;\n\n /**\n * The Powerlines context\n */\n public get context(): APIContext<TResolvedConfig> {\n return this.#context;\n }\n\n /**\n * Create a new Powerlines API instance\n *\n * @param context - The Powerlines context\n */\n private constructor(context: APIContext<TResolvedConfig>) {\n this.#context = context as UNSAFE_APIContext<TResolvedConfig>;\n }\n\n /**\n * Initialize a Powerlines API instance\n *\n * @param workspaceRoot - The directory of the underlying workspace the Powerlines project exists in\n * @param config - An object containing the configuration required to run Powerlines tasks.\n * @returns A new instance of the Powerlines API\n */\n public static async from<\n TResolvedConfig extends ResolvedConfig = ResolvedConfig\n >(\n workspaceRoot: string,\n config: InitialUserConfig<TResolvedConfig[\"userConfig\"]>\n ): Promise<PowerlinesAPI<TResolvedConfig>> {\n const api = new PowerlinesAPI<TResolvedConfig>(\n await PowerlinesAPIContext.from(workspaceRoot, config)\n );\n api.#context.$$internal = {\n api,\n addPlugin: api.#addPlugin.bind(api)\n };\n\n api.context.info(\n `🔌 The Powerlines Engine v${packageJson.version} has started`\n );\n\n for (const plugin of api.context.config.plugins ?? []) {\n await api.#addPlugin(plugin);\n }\n\n if (api.context.plugins.length === 0) {\n api.context.warn(\n \"No Powerlines plugins were specified in the options. Please ensure this is correct, as it is generally not recommended.\"\n );\n }\n\n const pluginConfig = await api.callHook(\"config\", {\n environment: await api.context.getEnvironment(),\n sequential: true,\n result: \"merge\",\n merge: mergeConfigs\n });\n await api.context.withUserConfig(\n pluginConfig as TResolvedConfig[\"userConfig\"],\n { isHighPriority: false }\n );\n\n return api;\n }\n\n /**\n * Prepare the Powerlines API\n *\n * @remarks\n * This method will prepare the Powerlines API for use, initializing any necessary resources.\n *\n * @param inlineConfig - The inline configuration for the prepare command\n */\n public async prepare(\n inlineConfig:\n | PrepareInlineConfig\n | NewInlineConfig\n | CleanInlineConfig\n | BuildInlineConfig\n | LintInlineConfig\n | DocsInlineConfig\n | DeployInlineConfig = { command: \"prepare\" }\n ) {\n this.context.info(\" 🏗️ Preparing the Powerlines project\");\n\n this.context.debug(\n \" Aggregating configuration options for the Powerlines project\"\n );\n\n await this.context.withInlineConfig(inlineConfig);\n await this.#executeEnvironments(async context => {\n context.debug(\n `Initializing the processing options for the Powerlines project.`\n );\n\n await this.callHook(\"configResolved\", {\n environment: context,\n order: \"pre\"\n });\n\n await initializeTsconfig<TResolvedConfig>(context);\n\n await this.callHook(\"configResolved\", {\n environment: context,\n order: \"normal\"\n });\n\n if (context.entry.length > 0) {\n context.debug(\n `The configuration provided ${\n isObject(context.config.input)\n ? Object.keys(context.config.input).length\n : toArray(context.config.input).length\n } entry point(s), Powerlines has found ${\n context.entry.length\n } entry files(s) for the ${context.config.title} project${\n context.entry.length > 0 && context.entry.length < 10\n ? `: \\n${context.entry\n .map(\n entry =>\n `- ${entry.file}${\n entry.output ? ` -> ${entry.output}` : \"\"\n }`\n )\n .join(\" \\n\")}`\n : \"\"\n }`\n );\n } else {\n context.warn(\n `No entry files were found for the ${\n context.config.title\n } project. Please ensure this is correct. Powerlines plugins generally require at least one entry point to function properly.`\n );\n }\n\n await resolveTsconfig<TResolvedConfig>(context);\n await installDependencies(context);\n\n await this.callHook(\"configResolved\", {\n environment: context,\n order: \"post\"\n });\n\n context.trace(\n `Powerlines configuration has been resolved: \\n\\n${formatLogMessage({\n ...context.config,\n userConfig: isSetObject(context.config.userConfig)\n ? omit(context.config.userConfig, [\"plugins\"])\n : undefined,\n inlineConfig: isSetObject(context.config.inlineConfig)\n ? omit(context.config.inlineConfig, [\"plugins\"])\n : undefined,\n plugins: context.plugins.map(plugin => plugin.plugin.name)\n })}`\n );\n\n if (!context.fs.existsSync(context.cachePath)) {\n await createDirectory(context.cachePath);\n }\n\n if (!context.fs.existsSync(context.dataPath)) {\n await createDirectory(context.dataPath);\n }\n\n await this.callHook(\"prepare\", {\n environment: context,\n order: \"pre\"\n });\n await this.callHook(\"prepare\", {\n environment: context,\n order: \"normal\"\n });\n\n await this.callHook(\"prepare\", {\n environment: context,\n order: \"post\"\n });\n\n if (context.config.output.dts !== false) {\n context.debug(\n `Preparing the TypeScript definitions for the Powerlines project.`\n );\n\n if (context.fs.existsSync(context.dtsPath)) {\n await context.fs.remove(context.dtsPath);\n }\n\n const typescriptPath = await resolvePackage(\"typescript\");\n if (!typescriptPath) {\n throw new Error(\n \"Could not resolve TypeScript package location. Please ensure TypeScript is installed.\"\n );\n }\n\n context.debug(\n \"Running TypeScript compiler for built-in runtime module files.\"\n );\n\n let types = await emitBuiltinTypes(\n context,\n (await context.getBuiltins()).reduce<string[]>((ret, builtin) => {\n const formatted = replacePath(\n builtin.path,\n context.workspaceConfig.workspaceRoot\n );\n if (!ret.includes(formatted)) {\n ret.push(formatted);\n }\n\n return ret;\n }, [])\n );\n\n context.debug(\n `Generating TypeScript declaration file ${context.dtsPath}.`\n );\n\n const directives = [] as string[];\n const asNextParam = (\n previousResult: string | TypesResult | null | undefined\n ) => (isObject(previousResult) ? previousResult.code : previousResult);\n\n let result = await this.callHook(\n \"types\",\n {\n environment: context,\n sequential: true,\n order: \"pre\",\n result: \"merge\",\n asNextParam\n },\n types\n );\n if (result) {\n if (isSetObject(result)) {\n types = result.code;\n if (\n Array.isArray(result.directives) &&\n result.directives.length > 0\n ) {\n directives.push(...result.directives);\n }\n } else if (isSetString(result)) {\n types = result;\n }\n }\n\n result = await this.callHook(\n \"types\",\n {\n environment: context,\n sequential: true,\n order: \"normal\",\n result: \"merge\",\n asNextParam\n },\n types\n );\n if (result) {\n if (isSetObject(result)) {\n types = result.code;\n if (\n Array.isArray(result.directives) &&\n result.directives.length > 0\n ) {\n directives.push(...result.directives);\n }\n } else if (isSetString(result)) {\n types = result;\n }\n }\n\n result = await this.callHook(\n \"types\",\n {\n environment: context,\n sequential: true,\n order: \"post\",\n result: \"merge\",\n asNextParam\n },\n types\n );\n if (result) {\n if (isSetObject(result)) {\n types = result.code;\n if (\n Array.isArray(result.directives) &&\n result.directives.length > 0\n ) {\n directives.push(...result.directives);\n }\n } else if (isSetString(result)) {\n types = result;\n }\n }\n\n if (isSetString(types?.trim()) || directives.length > 0) {\n await context.fs.write(\n context.dtsPath,\n `${\n directives.length > 0\n ? `${directives.map(directive => `/// <reference types=\"${directive}\" />`).join(\"\\n\")}\n\n`\n : \"\"\n }${getTypescriptFileHeader(context, { directive: null, prettierIgnore: false })}\n\n${formatTypes(types)}\n`\n );\n } else {\n const dtsRelativePath = getTsconfigDtsPath(context);\n if (\n context.tsconfig.tsconfigJson.include &&\n isIncludeMatchFound(\n dtsRelativePath,\n context.tsconfig.tsconfigJson.include\n )\n ) {\n const normalizedDtsRelativePath = dtsRelativePath.startsWith(\"./\")\n ? dtsRelativePath.slice(2)\n : dtsRelativePath;\n context.tsconfig.tsconfigJson.include =\n context.tsconfig.tsconfigJson.include.filter(\n includeValue =>\n includeValue?.toString() !== normalizedDtsRelativePath\n );\n\n await context.fs.write(\n context.tsconfig.tsconfigFilePath,\n JSON.stringify(context.tsconfig.tsconfigJson, null, 2)\n );\n }\n }\n }\n\n // Re-resolve the tsconfig to ensure it is up to date\n context.tsconfig = getParsedTypeScriptConfig(\n context.workspaceConfig.workspaceRoot,\n context.config.root,\n context.config.tsconfig\n );\n if (!context.tsconfig) {\n throw new Error(\"Failed to parse the TypeScript configuration file.\");\n }\n\n this.context.debug(\"Formatting files generated during the prepare step.\");\n\n await Promise.all([\n formatFolder(context, context.builtinsPath),\n formatFolder(context, context.entryPath)\n ]);\n\n await writeMetaFile(context);\n context.persistedMeta = context.meta;\n });\n\n this.context.debug(\"✔ Powerlines preparation has completed successfully\");\n }\n\n /**\n * Create a new Powerlines project\n *\n * @remarks\n * This method will create a new Powerlines project in the current directory.\n *\n * @param inlineConfig - The inline configuration for the new command\n * @returns A promise that resolves when the project has been created\n */\n public async new(inlineConfig: NewInlineConfig) {\n this.context.info(\" 🆕 Creating a new Powerlines project\");\n\n await this.prepare(inlineConfig);\n await this.#executeEnvironments(async context => {\n context.debug(\n \"Initializing the processing options for the Powerlines project.\"\n );\n\n await this.callHook(\"new\", {\n environment: context,\n order: \"pre\"\n });\n\n const files = await listFiles(\n joinPaths(context.powerlinesPath, \"files/common/**/*.hbs\")\n );\n for (const file of files) {\n context.trace(`Adding template file to project: ${file}`);\n\n const template = Handlebars.compile(file);\n await context.fs.write(\n joinPaths(context.config.root, file.replace(\".hbs\", \"\")),\n template(context)\n );\n }\n\n await this.callHook(\"new\", {\n environment: context,\n order: \"normal\"\n });\n\n if (context.config.projectType === \"application\") {\n const files = await listFiles(\n joinPaths(context.powerlinesPath, \"files/application/**/*.hbs\")\n );\n for (const file of files) {\n context.trace(`Adding application template file: ${file}`);\n\n const template = Handlebars.compile(file);\n await context.fs.write(\n joinPaths(context.config.root, file.replace(\".hbs\", \"\")),\n template(context)\n );\n }\n } else {\n const files = await listFiles(\n joinPaths(context.powerlinesPath, \"files/library/**/*.hbs\")\n );\n for (const file of files) {\n context.trace(`Adding library template file: ${file}`);\n\n const template = Handlebars.compile(file);\n await context.fs.write(\n joinPaths(context.config.root, file.replace(\".hbs\", \"\")),\n template(context)\n );\n }\n }\n\n await this.callHook(\"new\", {\n environment: context,\n order: \"post\"\n });\n });\n\n this.context.debug(\"✔ Powerlines new command completed successfully\");\n }\n\n /**\n * Clean any previously prepared artifacts\n *\n * @remarks\n * This method will remove the previous Powerlines artifacts from the project.\n *\n * @param inlineConfig - The inline configuration for the clean command\n * @returns A promise that resolves when the clean command has completed\n */\n public async clean(\n inlineConfig: CleanInlineConfig | PrepareInlineConfig = {\n command: \"clean\"\n }\n ) {\n this.context.info(\" 🧹 Cleaning the previous Powerlines artifacts\");\n\n await this.prepare(inlineConfig);\n await this.#executeEnvironments(async context => {\n context.debug(\"Cleaning the project's dist and artifacts directories.\");\n\n await context.fs.remove(\n joinPaths(\n context.workspaceConfig.workspaceRoot,\n context.config.output.buildPath\n )\n );\n await context.fs.remove(\n joinPaths(\n context.workspaceConfig.workspaceRoot,\n context.config.root,\n context.config.output.artifactsPath\n )\n );\n\n await this.callHook(\"clean\", {\n environment: context,\n sequential: false\n });\n });\n\n this.context.debug(\"✔ Powerlines cleaning completed successfully\");\n }\n\n /**\n * Lint the project\n *\n * @param inlineConfig - The inline configuration for the lint command\n * @returns A promise that resolves when the lint command has completed\n */\n public async lint(\n inlineConfig: LintInlineConfig | BuildInlineConfig = { command: \"lint\" }\n ) {\n this.context.info(\" 📝 Linting the Powerlines project\");\n\n await this.prepare(inlineConfig);\n await this.#executeEnvironments(async context => {\n await this.callHook(\"lint\", {\n environment: context,\n sequential: false\n });\n });\n\n this.context.debug(\"✔ Powerlines linting completed successfully\");\n }\n\n /**\n * Build the project\n *\n * @remarks\n * This method will build the Powerlines project, generating the necessary artifacts.\n *\n * @param inlineConfig - The inline configuration for the build command\n * @returns A promise that resolves when the build command has completed\n */\n public async build(inlineConfig: BuildInlineConfig = { command: \"build\" }) {\n this.context.info(\" 📦 Building the Powerlines project\");\n\n await this.context.generateChecksum();\n if (\n this.context.meta.checksum !== this.context.persistedMeta?.checksum ||\n this.context.config.skipCache\n ) {\n this.context.info(\n \"The project has been modified since the last time `prepare` was ran. Re-preparing the project.\"\n );\n\n await this.prepare(inlineConfig);\n }\n\n if (this.context.config.singleBuild) {\n await this.#handleBuild(await this.#context.toEnvironment());\n } else {\n await this.#executeEnvironments(async context => {\n await this.#handleBuild(context);\n });\n }\n\n this.context.debug(\"✔ Powerlines build completed successfully\");\n }\n\n /**\n * Prepare the documentation for the project\n *\n * @param inlineConfig - The inline configuration for the docs command\n * @returns A promise that resolves when the documentation generation has completed\n */\n public async docs(inlineConfig: DocsInlineConfig = { command: \"docs\" }) {\n this.context.info(\n \" 📓 Generating documentation for the Powerlines project\"\n );\n\n await this.prepare(inlineConfig);\n await this.#executeEnvironments(async context => {\n context.debug(\n \"Writing documentation for the Powerlines project artifacts.\"\n );\n\n await this.prepare(inlineConfig);\n await this.#executeEnvironments(async context => {\n await this.callHook(\"docs\", {\n environment: context\n });\n });\n });\n\n this.context.debug(\n \"✔ Powerlines documentation generation completed successfully\"\n );\n }\n\n /**\n * Deploy the project source code\n *\n * @remarks\n * This method will prepare and build the Powerlines project, generating the necessary artifacts for the deployment.\n *\n * @param inlineConfig - The inline configuration for the deploy command\n */\n public async deploy(\n inlineConfig: DeployInlineConfig = { command: \"deploy\" }\n ) {\n this.context.info(\" 🚀 Deploying the Powerlines project\");\n\n await this.prepare(inlineConfig);\n await this.#executeEnvironments(async context => {\n await this.callHook(\"deploy\", { environment: context });\n });\n\n this.context.debug(\"✔ Powerlines deploy completed successfully\");\n }\n\n /**\n * Finalization process\n *\n * @remarks\n * This step includes any final processes or clean up required by Powerlines. It will be run after each Powerlines command.\n *\n * @returns A promise that resolves when the finalization process has completed\n */\n public async finalize() {\n this.context.info(\" 🏁 Powerlines finalization processes started\");\n\n await this.#executeEnvironments(async context => {\n await this.callHook(\"finalize\", { environment: context });\n await context.fs.dispose();\n });\n\n this.context.debug(\"✔ Powerlines finalization completed successfully\");\n }\n\n /**\n * Invokes the configured plugin hooks\n *\n * @remarks\n * By default, it will call the `\"pre\"`, `\"normal\"`, and `\"post\"` ordered hooks in sequence\n *\n * @param hook - The hook to call\n * @param options - The options to provide to the hook\n * @param args - The arguments to pass to the hook\n * @returns The result of the hook call\n */\n public async callHook<TKey extends string>(\n hook: TKey,\n options: CallHookOptions & {\n environment?: string | EnvironmentContext<TResolvedConfig>;\n },\n ...args: InferHookParameters<PluginContext<TResolvedConfig>, TKey>\n ) {\n return callHook<TResolvedConfig, TKey>(\n isSetObject(options?.environment)\n ? options.environment\n : await this.#context.getEnvironment(options?.environment),\n hook,\n { sequential: true, ...options },\n ...args\n );\n }\n\n /**\n * Dispose of the Powerlines API instance\n *\n * @remarks\n * This method will finalize the Powerlines API instance, cleaning up any resources used.\n */\n public async [Symbol.asyncDispose]() {\n await this.finalize();\n }\n\n async #handleBuild(context: EnvironmentContext<TResolvedConfig>) {\n await this.callHook(\"build\", {\n environment: context,\n order: \"pre\"\n });\n\n context.debug(\n \"Formatting the generated entry files before the build process starts.\"\n );\n await formatFolder(context, context.entryPath);\n\n await this.callHook(\"build\", {\n environment: context,\n order: \"normal\"\n });\n\n if (context.config.output.buildPath !== context.config.output.outputPath) {\n const sourcePath = appendPath(\n context.config.output.buildPath,\n context.workspaceConfig.workspaceRoot\n );\n const destinationPath = joinPaths(\n appendPath(\n context.config.output.outputPath,\n context.workspaceConfig.workspaceRoot\n ),\n \"dist\"\n );\n\n if (context.fs.existsSync(sourcePath) && sourcePath !== destinationPath) {\n context.debug(\n `Copying build output files from project's build directory (${\n context.config.output.buildPath\n }) to the workspace's output directory (${context.config.output.outputPath}).`\n );\n\n await context.fs.copy(sourcePath, destinationPath);\n }\n }\n\n await Promise.all(\n context.config.output.assets.map(async asset => {\n context.trace(\n `Copying asset(s): ${chalk.redBright(\n context.workspaceConfig.workspaceRoot === asset.input\n ? asset.glob\n : joinPaths(\n replacePath(\n asset.input,\n context.workspaceConfig.workspaceRoot\n ),\n asset.glob\n )\n )} -> ${chalk.greenBright(\n joinPaths(\n replacePath(asset.output, context.workspaceConfig.workspaceRoot),\n asset.glob\n )\n )} ${\n Array.isArray(asset.ignore) && asset.ignore.length > 0\n ? ` (ignoring: ${asset.ignore\n .map(i => chalk.yellowBright(i))\n .join(\", \")})`\n : \"\"\n }`\n );\n\n await context.fs.copy(asset, asset.output);\n })\n );\n\n await this.callHook(\"build\", {\n environment: context,\n order: \"post\"\n });\n }\n\n /**\n * Get the configured environments\n *\n * @returns The configured environments\n */\n async #getEnvironments() {\n if (\n !this.context.config.environments ||\n Object.keys(this.context.config.environments).length <= 1\n ) {\n this.context.debug(\n \"No environments are configured for this Powerlines project. Using the default environment.\"\n );\n\n return [await this.context.getEnvironment()];\n }\n\n this.context.debug(\n `Found ${Object.keys(this.context.config.environments).length} configured environment(s) for this Powerlines project.`\n );\n\n return (\n await Promise.all(\n Object.entries(this.context.config.environments).map(\n async ([name, config]) => {\n const environment = await this.context.getEnvironmentSafe(name);\n if (!environment) {\n const resolvedEnvironment = await this.callHook(\n \"configEnvironment\",\n {\n environment: name\n },\n name,\n config\n );\n\n if (resolvedEnvironment) {\n this.context.environments[name] = await this.context.in(\n resolvedEnvironment as EnvironmentResolvedConfig\n );\n }\n }\n\n return this.context.environments[name];\n }\n )\n )\n ).filter(context => isSet(context));\n }\n\n /**\n * Execute a handler function for each environment\n *\n * @param handle - The handler function to execute for each environment\n */\n async #executeEnvironments(\n handle: (context: EnvironmentContext<TResolvedConfig>) => MaybePromise<void>\n ) {\n await Promise.all(\n (await this.#getEnvironments()).map(async context => {\n return Promise.resolve(handle(context));\n })\n );\n }\n\n /**\n * Add a Powerlines plugin used in the build process\n *\n * @param config - The import path of the plugin to add\n */\n async #addPlugin(config: PluginConfig<PluginContext<TResolvedConfig>>) {\n if (config) {\n const result = await this.#initPlugin(config);\n if (!result) {\n return;\n }\n\n for (const plugin of result) {\n this.context.debug(\n `Successfully initialized the ${chalk.bold.cyanBright(\n plugin.name\n )} plugin`\n );\n\n await this.context.addPlugin(plugin);\n }\n }\n }\n\n /**\n * Initialize a Powerlines plugin\n *\n * @param config - The configuration for the plugin\n * @returns The initialized plugin instance, or null if the plugin was a duplicate\n * @throws Will throw an error if the plugin cannot be found or is invalid\n */\n async #initPlugin(\n config: PluginConfig<PluginContext<TResolvedConfig>>\n ): Promise<Plugin<PluginContext<TResolvedConfig>>[] | null> {\n let awaited = config;\n if (isPromiseLike(config)) {\n awaited = (await Promise.resolve(config as Promise<any>)) as PluginConfig<\n PluginContext<TResolvedConfig>\n >;\n }\n\n if (!isPluginConfig<PluginContext<TResolvedConfig>>(awaited)) {\n const invalid = findInvalidPluginConfig(awaited);\n\n throw new Error(\n `Invalid ${\n invalid && invalid.length > 1 ? \"plugins\" : \"plugin\"\n } specified in the configuration - ${\n invalid && invalid.length > 0\n ? JSON.stringify(awaited)\n : invalid?.join(\"\\n\\n\")\n } \\n\\nPlease ensure the value is one of the following: \\n - an instance of \\`Plugin\\` \\n - a plugin name \\n - an object with the \\`plugin\\` and \\`options\\` properties \\n - a tuple array with the plugin and options \\n - a factory function that returns a plugin or array of plugins \\n - an array of plugins or plugin configurations`\n );\n }\n\n let plugins!: Plugin<PluginContext<TResolvedConfig>>[];\n if (isPlugin<PluginContext<TResolvedConfig>>(awaited)) {\n plugins = [awaited];\n } else if (isFunction(awaited)) {\n plugins = toArray(await Promise.resolve(awaited()));\n } else if (isString(awaited)) {\n const resolved = await this.#resolvePlugin(awaited);\n if (isFunction(resolved)) {\n plugins = toArray(await Promise.resolve(resolved()));\n } else {\n plugins = toArray(resolved);\n }\n } else if (\n Array.isArray(awaited) &&\n (awaited as PluginContext<TResolvedConfig>[]).every(\n isPlugin<PluginContext<TResolvedConfig>>\n )\n ) {\n plugins = awaited as Plugin<PluginContext<TResolvedConfig>>[];\n } else if (\n Array.isArray(awaited) &&\n (awaited as PluginConfig<PluginContext<TResolvedConfig>>[]).every(\n isPluginConfig<PluginContext<TResolvedConfig>>\n )\n ) {\n plugins = [];\n for (const pluginConfig of awaited as PluginConfig<\n PluginContext<TResolvedConfig>\n >[]) {\n const initialized = await this.#initPlugin(pluginConfig);\n if (initialized) {\n plugins.push(...initialized);\n }\n }\n } else if (\n isPluginConfigTuple<PluginContext<TResolvedConfig>>(awaited) ||\n isPluginConfigObject<PluginContext<TResolvedConfig>>(awaited)\n ) {\n let pluginConfig!:\n | string\n | PluginFactory<PluginContext<TResolvedConfig>>\n | Plugin<PluginContext<TResolvedConfig>>;\n let pluginOptions: any;\n\n if (isPluginConfigTuple<PluginContext<TResolvedConfig>>(awaited)) {\n pluginConfig = awaited[0] as Plugin<PluginContext<TResolvedConfig>>;\n pluginOptions =\n (awaited as PluginConfigTuple)?.length === 2 ? awaited[1] : undefined;\n } else {\n pluginConfig = (awaited as PluginConfigObject).plugin as Plugin<\n PluginContext<TResolvedConfig>\n >;\n pluginOptions = (awaited as PluginConfigObject).options;\n }\n\n if (isSetString(pluginConfig)) {\n const resolved = await this.#resolvePlugin(pluginConfig);\n if (isFunction(resolved)) {\n plugins = toArray(\n await Promise.resolve(\n pluginOptions ? resolved(pluginOptions) : resolved()\n )\n );\n } else {\n plugins = toArray(resolved);\n }\n } else if (isFunction(pluginConfig)) {\n plugins = toArray(await Promise.resolve(pluginConfig(pluginOptions)));\n } else if (\n Array.isArray(pluginConfig) &&\n pluginConfig.every(isPlugin<PluginContext<TResolvedConfig>>)\n ) {\n plugins = pluginConfig;\n } else if (isPlugin<PluginContext<TResolvedConfig>>(pluginConfig)) {\n plugins = toArray(pluginConfig);\n }\n }\n\n if (!plugins) {\n throw new Error(\n `The plugin configuration ${JSON.stringify(awaited)} is invalid. This configuration must point to a valid Powerlines plugin module.`\n );\n }\n\n if (\n plugins.length > 0 &&\n !plugins.every(isPlugin<PluginContext<TResolvedConfig>>)\n ) {\n throw new Error(\n `The plugin option ${JSON.stringify(plugins)} does not export a valid module. This configuration must point to a valid Powerlines plugin module.`\n );\n }\n\n const result = [] as Plugin<PluginContext<TResolvedConfig>>[];\n for (const plugin of plugins) {\n if (checkDedupe<TResolvedConfig>(plugin, this.context.plugins)) {\n this.context.trace(\n `Duplicate ${chalk.bold.cyanBright(\n plugin.name\n )} plugin dependency detected - Skipping initialization.`\n );\n } else {\n result.push(plugin);\n\n this.context.trace(\n `Initializing the ${chalk.bold.cyanBright(plugin.name)} plugin...`\n );\n }\n }\n\n return result;\n }\n\n async #resolvePlugin<TOptions>(\n pluginPath: string\n ): Promise<\n | Plugin<PluginContext<TResolvedConfig>>\n | Plugin<PluginContext<TResolvedConfig>>[]\n | ((\n options?: TOptions\n ) => MaybePromise<\n | Plugin<PluginContext<TResolvedConfig>>\n | Plugin<PluginContext<TResolvedConfig>>[]\n >)\n > {\n if (\n pluginPath.startsWith(\"@\") &&\n pluginPath.split(\"/\").filter(Boolean).length > 2\n ) {\n const splits = pluginPath.split(\"/\").filter(Boolean);\n pluginPath = `${splits[0]}/${splits[1]}`;\n }\n\n const isInstalled = isPackageExists(pluginPath, {\n paths: [\n this.context.workspaceConfig.workspaceRoot,\n this.context.config.root\n ]\n });\n if (!isInstalled && this.context.config.autoInstall) {\n this.#context.warn(\n `The plugin package \"${\n pluginPath\n }\" is not installed. It will be installed automatically.`\n );\n\n const result = await install(pluginPath, {\n cwd: this.context.config.root\n });\n if (isNumber(result.exitCode) && result.exitCode > 0) {\n this.#context.error(result.stderr);\n\n throw new Error(\n `An error occurred while installing the build plugin package \"${\n pluginPath\n }\" `\n );\n }\n }\n\n try {\n // First check if the package has a \"plugin\" subdirectory - @scope/package/plugin\n const module = await this.context.resolver.plugin.import<{\n plugin?:\n | Plugin<PluginContext<TResolvedConfig>>\n | ((\n options?: TOptions\n ) => MaybePromise<Plugin<PluginContext<TResolvedConfig>>>);\n default?:\n | Plugin<PluginContext<TResolvedConfig>>\n | ((\n options?: TOptions\n ) => MaybePromise<Plugin<PluginContext<TResolvedConfig>>>);\n }>(\n this.context.resolver.plugin.esmResolve(joinPaths(pluginPath, \"plugin\"))\n );\n\n const result = module.plugin ?? module.default;\n if (!result) {\n throw new Error(\n `The plugin package \"${pluginPath}\" does not export a valid module.`\n );\n }\n\n return result;\n } catch (error) {\n try {\n const module = await this.context.resolver.plugin.import<{\n plugin?:\n | Plugin<PluginContext<TResolvedConfig>>\n | ((\n options?: TOptions\n ) => MaybePromise<Plugin<PluginContext<TResolvedConfig>>>);\n default?:\n | Plugin<PluginContext<TResolvedConfig>>\n | ((\n options?: TOptions\n ) => MaybePromise<Plugin<PluginContext<TResolvedConfig>>>);\n }>(this.context.resolver.plugin.esmResolve(pluginPath));\n\n const result = module.plugin ?? module.default;\n if (!result) {\n throw new Error(\n `The plugin package \"${pluginPath}\" does not export a valid module.`\n );\n }\n\n return result;\n } catch {\n if (!isInstalled) {\n throw new Error(\n `The plugin package \"${\n pluginPath\n }\" is not installed. Please install the package using the command: \"npm install ${\n pluginPath\n } --save-dev\"`\n );\n } else {\n throw new Error(\n `An error occurred while importing the build plugin package \"${\n pluginPath\n }\":\n${isError(error) ? error.message : String(error)}\n\nNote: Please ensure the plugin package's default export is a class that extends \\`Plugin\\` with a constructor that excepts a single arguments of type \\`PluginOptions\\`.`\n );\n }\n }\n }\n }\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AC6BA,MAAM,8BAA8B,aAClC,IAAI,OAAO,+BAA+B,SAAS,oBAAoB;;;;;;;AAQzE,SAAgB,YAAY,MAAsB;AAChD,QAAO,KACJ,QAEC,yFACA,GACD,CACA,WAAW,aAAa,GAAG,CAC3B,QAAQ,QAAQ,GAAG;;;;;;;;;AAUxB,eAAsB,iBACpB,SACA,OACA;AACA,KAAI,MAAM,WAAW,GAAG;AACtB,UAAQ,MACN,kHACD;AACD,SAAO;;AAGT,SAAQ,MACN,uCACE,MAAM,OACP,mCACF;CAED,MAAM,UAAU,cAAc,SAAS;EACrC,6BAA6B;EAC7B,iBAAiB;GACf,aAAa;GACb,gBAAgB;GAChB,qBAAqB;GACrB,WAAW;GACX,QAAQ,YACN,QAAQ,cACR,QAAQ,gBAAgB,cACzB;GACD,WAAW;GACX,aAAa;GACb,iBAAiB;GAClB;EACF,CAAC;AAEF,SAAQ,sBAAsB,MAAM;CACpC,MAAM,SAAS,QAAQ,aAAa,EAAE,kBAAkB,MAAM,CAAC;CAE/D,MAAM,cAAc,OAAO,gBAAgB;AAC3C,KAAI,eAAe,YAAY,SAAS,EACtC,KAAI,YAAY,MAAK,MAAK,EAAE,aAAa,KAAK,mBAAmB,MAAM,CACrE,OAAM,IAAI,MACR,0EAA0E,YACvE,QAAO,MAAK,EAAE,aAAa,KAAK,mBAAmB,MAAM,CACzD,KACC,MACE,IAAI,EAAE,eAAe,GAAG,GAAG,EAAE,eAAe,EAAE,aAAa,CAAC,KAAK,GAAG,GAAG,OACrE,EAAE,gBAAgB,CACnB,CAAC,OAAO,EAAE,UAAU,CAAC,GAAG,EA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api-CTPU8bg3.mjs","names":["ROOT_HASH_LENGTH","defu","DEFAULT_ENVIRONMENT","defu","joinPaths","#context","#normalizePath","#storage","#normalizeId","#getStorage","capnp","#log","#metadata","#ids","#paths","#resolverCache","#resolver","#getStorages","Blob","#innerResolve","#innerResolveSync","#isDisposed","joinPaths","#internal","#tsconfig","#fs","#checksum","#buildId","#releaseId","#timestamp","ROOT_HASH_LENGTH","CACHE_HASH_LENGTH","#workspaceConfig","#parserCache","#requestCache","defu","#getConfigProps","#hooks","PLUGIN_NON_HOOK_FIELDS","#environments","#log","#plugins","GLOBAL_ENVIRONMENT","#context","#addPlugin","packageJson.version","#executeEnvironments","#handleBuild","#getEnvironments","#initPlugin","#resolvePlugin","isPlugin","isPluginConfig"],"sources":["../package.json","../src/_internal/helpers/generate-types.ts","../src/_internal/helpers/hooks.ts","../src/_internal/helpers/install.ts","../src/_internal/helpers/install-dependencies.ts","../src/_internal/helpers/meta.ts","../src/_internal/helpers/resolve-tsconfig.ts","../src/_internal/helpers/environment.ts","../src/_internal/helpers/resolver.ts","../schemas/fs.ts","../src/_internal/helpers/constants.ts","../src/_internal/vfs.ts","../src/context/context.ts","../src/unplugin.ts","../src/context/plugin-context.ts","../src/context/environment-context.ts","../src/context/api-context.ts","../src/api.ts"],"sourcesContent":["","/* -------------------------------------------------------------------\n\n ⚡ Storm Software - Powerlines\n\n This code was released as part of the Powerlines project. Powerlines\n is maintained by Storm Software under the Apache-2.0 license, and is\n free for commercial and private use. For more information, please visit\n our licensing page at https://stormsoftware.com/licenses/projects/powerlines.\n\n Website: https://stormsoftware.com\n Repository: https://github.com/storm-software/powerlines\n Documentation: https://docs.stormsoftware.com/projects/powerlines\n Contact: https://stormsoftware.com/contact\n\n SPDX-License-Identifier: Apache-2.0\n\n ------------------------------------------------------------------- */\n\nimport { toArray } from \"@stryke/convert/to-array\";\nimport { appendPath } from \"@stryke/path/append\";\nimport { findFileName } from \"@stryke/path/file-path-fns\";\nimport { isParentPath } from \"@stryke/path/is-parent-path\";\nimport { replaceExtension, replacePath } from \"@stryke/path/replace\";\nimport { prettyBytes } from \"@stryke/string-format/pretty-bytes\";\nimport { isSetString } from \"@stryke/type-checks/is-set-string\";\nimport { DiagnosticCategory } from \"ts-morph\";\nimport { Context } from \"../../types\";\nimport { createProgram } from \"../../typescript/ts-morph\";\n\nconst getModuleCommentBlockRegex = (moduleId: string) =>\n new RegExp(`\\\\/\\\\*\\\\*(?s:.)*?@module\\\\s+${moduleId}(?s:.)*?\\\\*\\\\/\\\\s+`);\n\n/**\n * Formats the generated TypeScript types source code.\n *\n * @param code - The generated TypeScript code.\n * @returns The formatted TypeScript code.\n */\nexport function formatTypes(code: string): string {\n return code\n .replace(\n // eslint-disable-next-line regexp/no-super-linear-backtracking\n /import\\s*(?:type\\s*)?\\{?[\\w,\\s]*(?:\\}\\s*)?from\\s*(?:'|\")@?[a-zA-Z0-9-\\\\/.]*(?:'|\");?/g,\n \"\"\n )\n .replaceAll(\"#private;\", \"\")\n .replace(/__Ω/g, \"\");\n}\n\n/**\n * Emits TypeScript declaration types for the provided files using the given TypeScript configuration.\n *\n * @param context - The context containing options and environment paths.\n * @param files - The list of files to generate types for.\n * @returns A promise that resolves to the generated TypeScript declaration types.\n */\nexport async function emitBuiltinTypes<TContext extends Context>(\n context: TContext,\n files: string[]\n) {\n if (files.length === 0) {\n context.debug(\n \"No files provided for TypeScript types generation. Typescript compilation for built-in modules will be skipped.\"\n );\n return \"\";\n }\n\n context.debug(\n `Running the TypeScript compiler for ${\n files.length\n } generated built-in module files.`\n );\n\n const program = createProgram(context, {\n skipAddingFilesFromTsConfig: true,\n compilerOptions: {\n declaration: true,\n declarationMap: false,\n emitDeclarationOnly: true,\n sourceMap: false,\n outDir: replacePath(\n context.builtinsPath,\n context.workspaceConfig.workspaceRoot\n ),\n composite: false,\n incremental: false,\n tsBuildInfoFile: undefined\n }\n });\n\n program.addSourceFilesAtPaths(files);\n const result = program.emitToMemory({ emitOnlyDtsFiles: true });\n\n const diagnostics = result.getDiagnostics();\n if (diagnostics && diagnostics.length > 0) {\n if (diagnostics.some(d => d.getCategory() === DiagnosticCategory.Error)) {\n throw new Error(\n `The Typescript emit process failed while generating built-in types: \\n ${diagnostics\n .filter(d => d.getCategory() === DiagnosticCategory.Error)\n .map(\n d =>\n `-${d.getSourceFile() ? `${d.getSourceFile()?.getFilePath()}:` : \"\"} ${String(\n d.getMessageText()\n )} (at ${d.getStart()}:${d.getLength()})`\n )\n .join(\"\\n\")}`\n );\n } else if (\n diagnostics.some(d => d.getCategory() === DiagnosticCategory.Warning)\n ) {\n context.warn(\n `The Typescript emit process completed with warnings while generating built-in types: \\n ${diagnostics\n .filter(d => d.getCategory() === DiagnosticCategory.Warning)\n .map(\n d =>\n `-${d.getSourceFile() ? `${d.getSourceFile()?.getFilePath()}:` : \"\"} ${String(\n d.getMessageText()\n )} (at ${d.getStart()}:${d.getLength()})`\n )\n .join(\"\\n\")}`\n );\n } else {\n context.debug(\n `The Typescript emit process completed with diagnostic messages while generating built-in types: \\n ${diagnostics\n .map(\n d =>\n `-${d.getSourceFile() ? `${d.getSourceFile()?.getFilePath()}:` : \"\"} ${String(\n d.getMessageText()\n )} (at ${d.getStart()}:${d.getLength()})`\n )\n .join(\"\\n\")}`\n );\n }\n }\n\n const emittedFiles = result.getFiles();\n context.debug(\n `The TypeScript compiler emitted ${emittedFiles.length} files for built-in types.`\n );\n\n let builtinModules = \"\";\n for (const emittedFile of emittedFiles) {\n context.trace(\n `Processing emitted type declaration file: ${emittedFile.filePath}`\n );\n\n const filePath = appendPath(\n emittedFile.filePath,\n context.workspaceConfig.workspaceRoot\n );\n\n if (\n !filePath.endsWith(\".map\") &&\n findFileName(filePath) !== \"tsconfig.tsbuildinfo\" &&\n isParentPath(filePath, context.builtinsPath)\n ) {\n const moduleId = `${context.config.framework}:${replaceExtension(\n replacePath(filePath, context.builtinsPath),\n \"\",\n {\n fullExtension: true\n }\n )}`;\n const moduleComment = emittedFile.text\n .match(getModuleCommentBlockRegex(moduleId))\n ?.find(comment => isSetString(comment?.trim()));\n\n builtinModules += `${moduleComment ? `\\n${moduleComment.trim()}` : \"\"}\ndeclare module \"${moduleId}\" {\n ${emittedFile.text\n .replace(moduleComment ?? \"\", \"\")\n .trim()\n .replace(/^\\s*export\\s*declare\\s*/gm, \"export \")\n .replace(/^\\s*declare\\s*/gm, \"\")}\n}\n`;\n }\n }\n\n builtinModules = formatTypes(builtinModules);\n context.debug(\n `A TypeScript declaration file (size: ${prettyBytes(\n new Blob(toArray(builtinModules)).size\n )}) emitted for the built-in modules types.`\n );\n\n return builtinModules;\n}\n","/* -------------------------------------------------------------------\n\n ⚡ Storm Software - Powerlines\n\n This code was released as part of the Powerlines project. Powerlines\n is maintained by Storm Software under the Apache-2.0 license, and is\n free for commercial and private use. For more information, please visit\n our licensing page at https://stormsoftware.com/licenses/projects/powerlines.\n\n Website: https://stormsoftware.com\n Repository: https://github.com/storm-software/powerlines\n Documentation: https://docs.stormsoftware.com/projects/powerlines\n Contact: https://stormsoftware.com/contact\n\n SPDX-License-Identifier: Apache-2.0\n\n ------------------------------------------------------------------- */\n\nimport { isFunction } from \"@stryke/type-checks/is-function\";\nimport { isObject } from \"@stryke/type-checks/is-object\";\nimport { isSet } from \"@stryke/type-checks/is-set\";\nimport { isString } from \"@stryke/type-checks/is-string\";\nimport { ArrayValues } from \"@stryke/types/array\";\nimport chalk from \"chalk\";\nimport { createDefu, defu } from \"defu\";\nimport { mergeConfig } from \"../../plugin-utils\";\nimport {\n CallHookOptions,\n EnvironmentContext,\n InferHookParameters,\n InferHookReturnType,\n PluginContext,\n ResolvedConfig\n} from \"../../types\";\n\nconst mergeResultObjects = createDefu(<T>(obj: T, key: keyof T, value: any) => {\n if (isString(obj[key]) && isString(value)) {\n obj[key] = `${obj[key] || \"\"}\\n${value || \"\"}`.trim() as T[keyof T];\n\n return true;\n }\n\n return false;\n});\n\n/**\n * Merges the current hook result with the previous results based on their types.\n *\n * @param currentResult - The current hook result to merge with the previous results.\n * @param previousResults - The previous hook results to merge with the current result.\n * @returns The merged result.\n */\nexport function mergeResults<T>(currentResult: T, previousResults: T[]): T[] {\n if (isString(currentResult)) {\n previousResults = [\n `${isString(previousResults[0]) ? previousResults[0] || \"\" : \"\"}\\n${currentResult || \"\"}`.trim() as T\n ];\n } else if (isObject(currentResult)) {\n previousResults = [\n mergeResultObjects(currentResult, previousResults[0] ?? {})\n ];\n }\n\n return previousResults;\n}\n\n/**\n * Merges multiple hook results together, with special handling for string values and object values.\n *\n * @param currentResult - The current hook result to merge with the previous results.\n * @param previousResults - The previous hook results to merge with the current result.\n * @returns The merged result.\n */\nexport function mergeConfigs<T>(currentResult: T, previousResults: T[]): T[] {\n if (isString(currentResult)) {\n previousResults = [\n `${isString(previousResults[0]) ? previousResults[0] || \"\" : \"\"}\\n${currentResult || \"\"}`.trim() as T\n ];\n } else if (isObject(currentResult)) {\n previousResults = [\n mergeConfig(currentResult, previousResults[0] ?? {}) as T\n ];\n }\n\n return previousResults;\n}\n\n/**\n * Calls a hook with the given context, options, and arguments.\n *\n * @param context - The context to use when calling the hook.\n * @param key - The hook to call.\n * @param options - Options for calling the hook.\n * @param args - Arguments to pass to the hook.\n * @returns The return value of the hook.\n */\nexport async function callHook<\n TResolvedConfig extends ResolvedConfig,\n TKey extends string\n>(\n context: EnvironmentContext<TResolvedConfig>,\n key: TKey,\n options: CallHookOptions,\n ...args: InferHookParameters<PluginContext<TResolvedConfig>, TKey>\n): Promise<\n InferHookReturnType<PluginContext<TResolvedConfig>, TKey> | undefined\n> {\n const hooks = context.selectHooks(key, options);\n if (hooks.length > 0) {\n context.debug(\n ` 🧩 Calling plugin hook: ${chalk.bold.cyanBright(\n `${key}${options?.order ? ` (${options.order})` : \"\"}`\n )}`\n );\n\n const invokeHook = async (\n hook: ArrayValues<typeof hooks>,\n hookArgs: InferHookParameters<PluginContext<TResolvedConfig>, TKey>\n ) => {\n return Reflect.apply(hook.handler, hook.context, hookArgs);\n };\n\n let results = [] as InferHookReturnType<\n PluginContext<TResolvedConfig>,\n TKey\n >[];\n if (options?.sequential === false) {\n results = (await Promise.all(\n hooks.map(async hook => {\n if (!isFunction(hook.handler)) {\n throw new Error(\n `Plugin hook handler for hook \"${key}\" is not a function.`\n );\n }\n\n return invokeHook(hook, [...args]);\n })\n )) as InferHookReturnType<PluginContext<TResolvedConfig>, TKey>[];\n } else {\n for (const hook of hooks) {\n if (!isFunction(hook.handler)) {\n throw new Error(\n `Plugin hook handler for hook \"${key}\" is not a function.`\n );\n }\n\n if (options?.result === \"first\" || options?.asNextParam === false) {\n results.push(\n (await Promise.resolve(\n invokeHook(hook, [...args])\n )) as InferHookReturnType<PluginContext<TResolvedConfig>, TKey>\n );\n if (\n options?.result === \"first\" &&\n isSet(results[results.length - 1])\n ) {\n break;\n }\n } else {\n const sequenceArgs = [...args];\n if (results.length > 0 && sequenceArgs.length > 0) {\n sequenceArgs[0] = isFunction(options.asNextParam)\n ? await Promise.resolve(options.asNextParam(results[0]))\n : results[0];\n }\n\n const result = await Promise.resolve(\n invokeHook(hook, [...sequenceArgs] as InferHookParameters<\n PluginContext<TResolvedConfig>,\n TKey\n >)\n );\n if (result) {\n if (options.result === \"last\") {\n results = [result];\n } else if (options.result === \"merge\" && options.merge) {\n results = options.merge(result, results);\n } else {\n results = mergeResults(result, results);\n }\n }\n }\n }\n }\n\n const definedResults = results.filter(\n (\n result\n ): result is NonNullable<\n InferHookReturnType<PluginContext<TResolvedConfig>, TKey>\n > => isSet(result)\n );\n\n if (definedResults.length > 0) {\n let mergedResult = undefined as\n | InferHookReturnType<PluginContext<TResolvedConfig>, TKey>\n | undefined;\n\n for (const result of definedResults) {\n mergedResult = defu(\n result as Record<string, unknown>,\n (mergedResult ?? {}) as Record<string, unknown>\n ) as InferHookReturnType<PluginContext<TResolvedConfig>, TKey>;\n }\n\n return mergedResult;\n }\n }\n\n return undefined;\n}\n","/* -------------------------------------------------------------------\n\n ⚡ Storm Software - Powerlines\n\n This code was released as part of the Powerlines project. Powerlines\n is maintained by Storm Software under the Apache-2.0 license, and is\n free for commercial and private use. For more information, please visit\n our licensing page at https://stormsoftware.com/licenses/projects/powerlines.\n\n Website: https://stormsoftware.com\n Repository: https://github.com/storm-software/powerlines\n Documentation: https://docs.stormsoftware.com/projects/powerlines\n Contact: https://stormsoftware.com/contact\n\n SPDX-License-Identifier: Apache-2.0\n\n ------------------------------------------------------------------- */\n\nimport { install } from \"@stryke/fs/install\";\nimport {\n doesPackageMatch,\n getPackageListing,\n isPackageListed\n} from \"@stryke/fs/package-fns\";\nimport {\n getPackageName,\n getPackageVersion,\n hasPackageVersion\n} from \"@stryke/string-format/package\";\nimport { isNumber } from \"@stryke/type-checks/is-number\";\nimport type { Context } from \"../../types\";\n\n/**\n * Installs a package if it is not already installed.\n *\n * @param context - The resolved options\n * @param packageName - The name of the package to install\n * @param dev - Whether to install the package as a dev dependency\n */\nexport async function installPackage(\n context: Context,\n packageName: string,\n dev = false\n) {\n if (\n !(await isPackageListed(getPackageName(packageName), {\n cwd: context.config.root\n }))\n ) {\n if (context.config.autoInstall) {\n context.warn(\n `The package \"${packageName}\" is not installed. It will be installed automatically.`\n );\n\n const result = await install(packageName, {\n cwd: context.config.root,\n dev\n });\n if (isNumber(result.exitCode) && result.exitCode > 0) {\n context.error(result.stderr);\n throw new Error(\n `An error occurred while installing the package \"${packageName}\"`\n );\n }\n } else {\n context.warn(\n `The package \"${packageName}\" is not installed. Since the \"autoInstall\" option is set to false, it will not be installed automatically.`\n );\n }\n } else if (\n hasPackageVersion(packageName) &&\n !process.env.POWERLINES_SKIP_VERSION_CHECK\n ) {\n const isMatching = await doesPackageMatch(\n getPackageName(packageName),\n getPackageVersion(packageName)!,\n context.config.root\n );\n if (!isMatching) {\n const packageListing = await getPackageListing(\n getPackageName(packageName),\n {\n cwd: context.config.root\n }\n );\n if (\n !packageListing?.version.startsWith(\"catalog:\") &&\n !packageListing?.version.startsWith(\"workspace:\")\n ) {\n context.warn(\n `The package \"${getPackageName(packageName)}\" is installed but does not match the expected version ${getPackageVersion(\n packageName\n )} (installed version: ${packageListing?.version || \"<Unknown>\"}). Please ensure this is intentional before proceeding. Note: You can skip this validation with the \"STORM_STACK_SKIP_VERSION_CHECK\" environment variable.`\n );\n }\n }\n }\n}\n\n/**\n * Installs a package if it is not already installed.\n *\n * @param context - The resolved options\n * @param packages - The list of packages to install\n */\nexport async function installPackages(\n context: Context,\n packages: Array<{ name: string; dev?: boolean }>\n) {\n return Promise.all(\n packages.map(async pkg => installPackage(context, pkg.name, pkg.dev))\n );\n}\n","/* -------------------------------------------------------------------\n\n ⚡ Storm Software - Powerlines\n\n This code was released as part of the Powerlines project. Powerlines\n is maintained by Storm Software under the Apache-2.0 license, and is\n free for commercial and private use. For more information, please visit\n our licensing page at https://stormsoftware.com/licenses/projects/powerlines.\n\n Website: https://stormsoftware.com\n Repository: https://github.com/storm-software/powerlines\n Documentation: https://docs.stormsoftware.com/projects/powerlines\n Contact: https://stormsoftware.com/contact\n\n SPDX-License-Identifier: Apache-2.0\n\n ------------------------------------------------------------------- */\n\nimport { getPackageName } from \"@stryke/string-format/package\";\nimport { Context } from \"../../types\";\nimport { installPackage } from \"./install\";\n\n/**\n * Install missing project dependencies.\n *\n * @param context - The build context.\n */\nexport async function installDependencies<TContext extends Context = Context>(\n context: TContext\n): Promise<void> {\n context.debug(`Checking and installing missing project dependencies.`);\n\n context.dependencies ??= {};\n context.devDependencies ??= {};\n\n if (\n Object.keys(context.dependencies).length === 0 &&\n Object.keys(context.devDependencies).length === 0\n ) {\n context.debug(\n `No dependencies or devDependencies to install. Skipping installation step.`\n );\n return;\n }\n\n context.debug(\n `The following packages are required: \\nDependencies: \\n${Object.entries(\n context.dependencies\n )\n .map(([name, version]) => `- ${name}@${String(version)}`)\n .join(\" \\n\")}\\n\\nDevDependencies: \\n${Object.entries(\n context.devDependencies\n )\n .map(([name, version]) => `- ${name}@${String(version)}`)\n .join(\" \\n\")}`\n );\n\n await Promise.all([\n Promise.all(\n Object.entries(context.dependencies).map(async ([name, version]) =>\n installPackage(\n context,\n `${getPackageName(name)}@${String(version)}`,\n false\n )\n )\n ),\n Promise.all(\n Object.entries(context.devDependencies).map(async ([name, version]) =>\n installPackage(\n context,\n `${getPackageName(name)}@${String(version)}`,\n true\n )\n )\n )\n ]);\n}\n","/* -------------------------------------------------------------------\n\n ⚡ Storm Software - Powerlines\n\n This code was released as part of the Powerlines project. Powerlines\n is maintained by Storm Software under the Apache-2.0 license, and is\n free for commercial and private use. For more information, please visit\n our licensing page at https://stormsoftware.com/licenses/projects/powerlines.\n\n Website: https://stormsoftware.com\n Repository: https://github.com/storm-software/powerlines\n Documentation: https://docs.stormsoftware.com/projects/powerlines\n Contact: https://stormsoftware.com/contact\n\n SPDX-License-Identifier: Apache-2.0\n\n ------------------------------------------------------------------- */\n\nimport { existsSync } from \"@stryke/fs/exists\";\nimport { readJsonFile } from \"@stryke/fs/json\";\nimport { removeFile } from \"@stryke/fs/remove-file\";\nimport { joinPaths } from \"@stryke/path/join-paths\";\nimport { kebabCase } from \"@stryke/string-format/kebab-case\";\nimport { ROOT_HASH_LENGTH } from \"../../constants\";\nimport type { Context, MetaInfo } from \"../../types\";\n\nexport interface CreateContextOptions {\n name?: string;\n}\n\n/**\n * Generates a prefixed project root hash object.\n *\n * @remarks\n * This function returns a string where the project root hash is prefixed with the project name plus a hyphen. If the total length of this string combination exceeds 45 characters, it will truncate the hash.\n *\n * @param name - The name of the project.\n * @param rootHash - The hash of the project root.\n * @returns An object containing the name and project root hash.\n */\nexport function getPrefixedRootHash(name: string, rootHash: string): string {\n const combined = `${kebabCase(name)}_${rootHash}`;\n\n return combined.length > ROOT_HASH_LENGTH\n ? combined.slice(0, ROOT_HASH_LENGTH)\n : combined;\n}\n\n/**\n * Retrieves the persisted meta information from the context's data path.\n *\n * @param context - The build context.\n * @returns A promise that resolves to the persisted meta information, or undefined if not found.\n */\nexport async function getPersistedMeta(\n context: Context\n): Promise<MetaInfo | undefined> {\n const metaFilePath = joinPaths(context.dataPath, \"meta.json\");\n if (existsSync(metaFilePath)) {\n try {\n return await readJsonFile<MetaInfo>(metaFilePath);\n } catch {\n context.warn(\n `Failed to read meta file at ${metaFilePath}. It may be corrupted.`\n );\n await removeFile(metaFilePath);\n\n context.persistedMeta = undefined;\n }\n }\n\n return undefined;\n}\n\n/**\n * Writes the meta file for the context.\n *\n * @param context - The context to write the meta file for.\n * @returns A promise that resolves when the meta file has been written.\n */\nexport async function writeMetaFile(context: Context): Promise<void> {\n const metaFilePath = joinPaths(context.dataPath, \"meta.json\");\n\n context.debug(`Writing runtime metadata to ${metaFilePath}`);\n\n await context.fs.write(metaFilePath, JSON.stringify(context.meta, null, 2));\n}\n","/* -------------------------------------------------------------------\n\n ⚡ Storm Software - Powerlines\n\n This code was released as part of the Powerlines project. Powerlines\n is maintained by Storm Software under the Apache-2.0 license, and is\n free for commercial and private use. For more information, please visit\n our licensing page at https://stormsoftware.com/licenses/projects/powerlines.\n\n Website: https://stormsoftware.com\n Repository: https://github.com/storm-software/powerlines\n Documentation: https://docs.stormsoftware.com/projects/powerlines\n Contact: https://stormsoftware.com/contact\n\n SPDX-License-Identifier: Apache-2.0\n\n ------------------------------------------------------------------- */\n\nimport type { Diff, ObjectData } from \"@donedeal0/superdiff\";\nimport { getObjectDiff } from \"@donedeal0/superdiff\";\nimport { readJsonFile } from \"@stryke/fs/json\";\nimport { isPackageExists } from \"@stryke/fs/package-fns\";\nimport { StormJSON } from \"@stryke/json/storm-json\";\nimport {\n findFileName,\n findFilePath,\n relativePath\n} from \"@stryke/path/file-path-fns\";\nimport { joinPaths } from \"@stryke/path/join-paths\";\nimport { titleCase } from \"@stryke/string-format/title-case\";\nimport { TsConfigJson } from \"@stryke/types/tsconfig\";\nimport chalk from \"chalk\";\nimport type { EnvironmentContext } from \"../../types\";\nimport { ResolvedConfig } from \"../../types\";\nimport {\n getParsedTypeScriptConfig,\n getTsconfigFilePath,\n isIncludeMatchFound\n} from \"../../typescript/tsconfig\";\n\nexport function getTsconfigDtsPath<\n TResolvedConfig extends ResolvedConfig = ResolvedConfig\n>(context: EnvironmentContext<TResolvedConfig>): string {\n const dtsRelativePath = joinPaths(\n relativePath(\n joinPaths(context.workspaceConfig.workspaceRoot, context.config.root),\n findFilePath(context.dtsPath)\n ),\n findFileName(context.dtsPath)\n );\n\n return dtsRelativePath;\n}\n\nasync function resolveTsconfigChanges<\n TResolvedConfig extends ResolvedConfig = ResolvedConfig\n>(context: EnvironmentContext<TResolvedConfig>): Promise<TsConfigJson> {\n const tsconfig = getParsedTypeScriptConfig(\n context.workspaceConfig.workspaceRoot,\n context.config.root,\n context.config.tsconfig,\n context.config.tsconfigRaw\n );\n\n const tsconfigFilePath = getTsconfigFilePath(\n context.workspaceConfig.workspaceRoot,\n context.config.root,\n context.config.tsconfig\n );\n\n const tsconfigJson = await readJsonFile<TsConfigJson>(tsconfigFilePath);\n tsconfigJson.compilerOptions ??= {};\n\n if (context.config.output.dts !== false) {\n const dtsRelativePath = getTsconfigDtsPath(context);\n\n if (\n !tsconfigJson.include?.some(filePattern =>\n isIncludeMatchFound(filePattern, [context.dtsPath, dtsRelativePath])\n )\n ) {\n tsconfigJson.include ??= [];\n tsconfigJson.include.push(\n dtsRelativePath.startsWith(\"./\")\n ? dtsRelativePath.slice(2)\n : dtsRelativePath\n );\n }\n }\n\n if (\n !tsconfig.options.lib?.some(lib =>\n [\n \"lib.esnext.d.ts\",\n \"lib.es2021.d.ts\",\n \"lib.es2022.d.ts\",\n \"lib.es2023.d.ts\"\n ].includes(lib.toLowerCase())\n )\n ) {\n tsconfigJson.compilerOptions.lib ??= [];\n tsconfigJson.compilerOptions.lib.push(\"esnext\");\n }\n\n // if (tsconfig.options.module !== ts.ModuleKind.ESNext) {\n // tsconfigJson.compilerOptions.module = \"ESNext\";\n // }\n\n // if (\n // !tsconfig.options.target ||\n // ![\n // ts.ScriptTarget.ESNext,\n // ts.ScriptTarget.ES2024,\n // ts.ScriptTarget.ES2023,\n // ts.ScriptTarget.ES2022,\n // ts.ScriptTarget.ES2021\n // ].includes(tsconfig.options.target)\n // ) {\n // tsconfigJson.compilerOptions.target = \"ESNext\";\n // }\n\n // if (tsconfig.options.moduleResolution !== ts.ModuleResolutionKind.Bundler) {\n // tsconfigJson.compilerOptions.moduleResolution = \"Bundler\";\n // }\n\n // if (tsconfig.options.moduleDetection !== ts.ModuleDetectionKind.Force) {\n // tsconfigJson.compilerOptions.moduleDetection = \"force\";\n // }\n\n // if (tsconfig.options.allowSyntheticDefaultImports !== true) {\n // tsconfigJson.compilerOptions.allowSyntheticDefaultImports = true;\n // }\n\n // if (tsconfig.options.noImplicitOverride !== true) {\n // tsconfigJson.compilerOptions.noImplicitOverride = true;\n // }\n\n // if (tsconfig.options.noUncheckedIndexedAccess !== true) {\n // tsconfigJson.compilerOptions.noUncheckedIndexedAccess = true;\n // }\n\n // if (tsconfig.options.skipLibCheck !== true) {\n // tsconfigJson.compilerOptions.skipLibCheck = true;\n // }\n\n // if (tsconfig.options.resolveJsonModule !== true) {\n // tsconfigJson.compilerOptions.resolveJsonModule = true;\n // }\n\n // if (tsconfig.options.verbatimModuleSyntax !== false) {\n // tsconfigJson.compilerOptions.verbatimModuleSyntax = false;\n // }\n\n // if (tsconfig.options.allowJs !== true) {\n // tsconfigJson.compilerOptions.allowJs = true;\n // }\n\n // if (tsconfig.options.declaration !== true) {\n // tsconfigJson.compilerOptions.declaration = true;\n // }\n\n if (tsconfig.options.esModuleInterop !== true) {\n tsconfigJson.compilerOptions.esModuleInterop = true;\n }\n\n if (tsconfig.options.isolatedModules !== true) {\n tsconfigJson.compilerOptions.isolatedModules = true;\n }\n\n if (context.config.platform === \"node\") {\n if (\n !tsconfig.options.types?.some(\n type =>\n type.toLowerCase() === \"node\" || type.toLowerCase() === \"@types/node\"\n )\n ) {\n tsconfigJson.compilerOptions.types ??= [];\n tsconfigJson.compilerOptions.types.push(\"node\");\n }\n }\n\n return tsconfigJson;\n}\n\nexport async function initializeTsconfig<\n TResolvedConfig extends ResolvedConfig = ResolvedConfig,\n TContext extends EnvironmentContext<TResolvedConfig> =\n EnvironmentContext<TResolvedConfig>\n>(context: TContext): Promise<void> {\n context.debug(\n \"Initializing TypeScript configuration (tsconfig.json) for the Powerlines project.\"\n );\n\n if (!isPackageExists(\"typescript\")) {\n throw new Error(\n 'The TypeScript package is not installed. Please install the package using the command: \"npm install typescript --save-dev\"'\n );\n }\n\n const tsconfigFilePath = getTsconfigFilePath(\n context.workspaceConfig.workspaceRoot,\n context.config.root,\n context.config.tsconfig\n );\n\n context.tsconfig.originalTsconfigJson =\n await readJsonFile<TsConfigJson>(tsconfigFilePath);\n\n context.tsconfig.tsconfigJson =\n await resolveTsconfigChanges<TResolvedConfig>(context);\n\n context.debug(\n \"Writing updated TypeScript configuration (tsconfig.json) file to disk.\"\n );\n\n await context.fs.write(\n tsconfigFilePath,\n StormJSON.stringify(context.tsconfig.tsconfigJson)\n );\n\n context.tsconfig = getParsedTypeScriptConfig(\n context.workspaceConfig.workspaceRoot,\n context.config.root,\n context.config.tsconfig,\n context.config.tsconfigRaw,\n context.tsconfig.originalTsconfigJson\n );\n}\n\nexport async function resolveTsconfig<\n TResolvedConfig extends ResolvedConfig = ResolvedConfig,\n TContext extends EnvironmentContext<TResolvedConfig> =\n EnvironmentContext<TResolvedConfig>\n>(context: TContext): Promise<void> {\n const updateTsconfigJson = await readJsonFile<TsConfigJson>(\n context.tsconfig.tsconfigFilePath\n );\n if (\n updateTsconfigJson?.compilerOptions?.types &&\n Array.isArray(updateTsconfigJson.compilerOptions.types) &&\n !updateTsconfigJson.compilerOptions.types.length\n ) {\n // If the types array is empty, we can safely remove it\n delete updateTsconfigJson.compilerOptions.types;\n }\n\n const result = getObjectDiff(\n context.tsconfig.originalTsconfigJson as NonNullable<ObjectData>,\n updateTsconfigJson as ObjectData,\n {\n ignoreArrayOrder: true,\n showOnly: {\n statuses: [\"added\", \"deleted\", \"updated\"],\n granularity: \"deep\"\n }\n }\n );\n\n const changes = [] as {\n field: string;\n status: \"added\" | \"deleted\" | \"updated\";\n previous: string;\n current: string;\n }[];\n const getChanges = (difference: Diff, property?: string) => {\n if (\n difference.status === \"added\" ||\n difference.status === \"deleted\" ||\n difference.status === \"updated\"\n ) {\n if (difference.diff) {\n for (const diff of difference.diff) {\n getChanges(\n diff,\n property\n ? `${property}.${difference.property}`\n : difference.property\n );\n }\n } else {\n changes.push({\n field: property\n ? `${property}.${difference.property}`\n : difference.property,\n status: difference.status,\n previous:\n difference.status === \"added\"\n ? \"---\"\n : StormJSON.stringify(difference.previousValue),\n current:\n difference.status === \"deleted\"\n ? \"---\"\n : StormJSON.stringify(difference.currentValue)\n });\n }\n }\n };\n\n for (const diff of result.diff) {\n getChanges(diff);\n }\n\n if (changes.length > 0) {\n context.warn(\n `Updating the following configuration values in \"${context.tsconfig.tsconfigFilePath}\" file:\n\n ${changes\n .map(\n (change, i) => `${chalk.bold.whiteBright(\n `${i + 1}. ${titleCase(change.status)} the ${change.field} field: `\n )}\n ${chalk.red(` - Previous: ${change.previous} `)}\n ${chalk.green(` - Updated: ${change.current} `)}\n `\n )\n .join(\"\\n\")}\n `\n );\n }\n\n await context.fs.write(\n context.tsconfig.tsconfigFilePath,\n StormJSON.stringify(updateTsconfigJson)\n );\n\n context.tsconfig = getParsedTypeScriptConfig(\n context.workspaceConfig.workspaceRoot,\n context.config.root,\n context.config.tsconfig\n );\n if (!context.tsconfig) {\n throw new Error(\"Failed to parse the TypeScript configuration file.\");\n }\n}\n","/* -------------------------------------------------------------------\n\n ⚡ Storm Software - Powerlines\n\n This code was released as part of the Powerlines project. Powerlines\n is maintained by Storm Software under the Apache-2.0 license, and is\n free for commercial and private use. For more information, please visit\n our licensing page at https://stormsoftware.com/licenses/projects/powerlines.\n\n Website: https://stormsoftware.com\n Repository: https://github.com/storm-software/powerlines\n Documentation: https://docs.stormsoftware.com/projects/powerlines\n Contact: https://stormsoftware.com/contact\n\n SPDX-License-Identifier: Apache-2.0\n\n ------------------------------------------------------------------- */\n\nimport { titleCase } from \"@stryke/string-format/title-case\";\nimport defu from \"defu\";\nimport { DEFAULT_ENVIRONMENT } from \"../../constants\";\nimport { APIContext, Context, EnvironmentResolvedConfig } from \"../../types\";\n\nexport function createEnvironment<TContext extends Context = Context>(\n name: string,\n userConfig: TContext[\"config\"][\"userConfig\"]\n): EnvironmentResolvedConfig {\n return defu(\n userConfig.environments?.[name] ?? {},\n {\n name,\n title: userConfig.title || titleCase(userConfig.name),\n ssr: false,\n mainFields:\n userConfig?.platform === \"browser\"\n ? [\"browser\", \"module\", \"jsnext:main\", \"jsnext\"]\n : [\"module\", \"jsnext:main\", \"jsnext\"],\n extensions: [\".mjs\", \".js\", \".mts\", \".ts\", \".jsx\", \".tsx\", \".json\"],\n consumer: userConfig?.platform === \"browser\" ? \"client\" : \"server\",\n preview:\n userConfig?.platform === \"browser\"\n ? {\n port: 5173,\n open: true,\n strictPort: false,\n // https: false,\n host: \"localhost\",\n allowedHosts: [\".\"],\n cors: true,\n headers: {}\n }\n : undefined\n },\n userConfig\n ) as EnvironmentResolvedConfig;\n}\n\nexport function createDefaultEnvironment<\n TContext extends APIContext = APIContext\n>(userConfig: TContext[\"config\"][\"userConfig\"]): EnvironmentResolvedConfig {\n return createEnvironment(DEFAULT_ENVIRONMENT, userConfig);\n}\n","/* -------------------------------------------------------------------\n\n ⚡ Storm Software - Powerlines\n\n This code was released as part of the Powerlines project. Powerlines\n is maintained by Storm Software under the Apache-2.0 license, and is\n free for commercial and private use. For more information, please visit\n our licensing page at https://stormsoftware.com/licenses/projects/powerlines.\n\n Website: https://stormsoftware.com\n Repository: https://github.com/storm-software/powerlines\n Documentation: https://docs.stormsoftware.com/projects/powerlines\n Contact: https://stormsoftware.com/contact\n\n SPDX-License-Identifier: Apache-2.0\n\n ------------------------------------------------------------------- */\n\nimport { joinPaths } from \"@stryke/path/join-paths\";\nimport defu from \"defu\";\nimport { JitiOptions, createJiti } from \"jiti\";\nimport { ResolvedConfig, Resolver } from \"../../types\";\n\nexport type CreateResolverOptions = Omit<\n JitiOptions,\n \"fsCache\" | \"moduleCache\" | \"interopDefault\"\n> &\n Pick<ResolvedConfig, \"mode\" | \"logLevel\" | \"skipCache\"> & {\n workspaceRoot: string;\n root: string;\n cacheDir: string;\n };\n\n/**\n * Create a Jiti resolver for the given workspace and project root.\n *\n * @param options - The options for creating the resolver.\n * @returns A Jiti instance configured for the specified workspace and project root.\n */\nfunction resolveOptions(options: CreateResolverOptions): JitiOptions {\n return defu(options, {\n interopDefault: true,\n fsCache:\n options.mode !== \"development\"\n ? joinPaths(options.cacheDir, \"jiti\")\n : false,\n moduleCache: options.mode !== \"development\"\n });\n}\n\n/**\n * Create a Jiti resolver for the given workspace and project root.\n *\n * @param options - The options for creating the resolver.\n * @returns A Jiti instance configured for the specified workspace and project root.\n */\nexport function createResolver(options: CreateResolverOptions): Resolver {\n const baseResolver = createJiti(\n joinPaths(options.workspaceRoot, options.root),\n resolveOptions(options)\n ) as Resolver;\n baseResolver.plugin = createJiti(\n joinPaths(options.workspaceRoot, options.root),\n resolveOptions(options)\n );\n\n return baseResolver;\n}\n","/* eslint-disable */\n// biome-ignore lint: disable\n// Generated by storm-capnpc\n// Note: Do not edit this file manually - it will be overwritten automatically\nimport * as $ from \"@stryke/capnp\";\nexport const _capnpFileId = BigInt(\"0xa56c61324b9d6e49\");\nexport class FileMetadata_KeyValuePair extends $.Struct {\n public static override readonly _capnp = {\n displayName: \"KeyValuePair\",\n id: \"eabb26cf58b2a14c\",\n size: new $.ObjectSize(0, 2),\n };\n get key(): string {\n return $.utils.getText(0, this);\n }\n set key(value: string) {\n $.utils.setText(0, value, this);\n }\n get value(): string {\n return $.utils.getText(1, this);\n }\n set value(value: string) {\n $.utils.setText(1, value, this);\n }\n public override toString(): string { return \"FileMetadata_KeyValuePair_\" + super.toString(); }\n}\n/**\n* The identifier for the file data.\n*\n*/\nexport class FileMetadata extends $.Struct {\n static readonly KeyValuePair = FileMetadata_KeyValuePair;\n public static override readonly _capnp = {\n displayName: \"FileMetadata\",\n id: \"8e2cab5d7e28c7b3\",\n size: new $.ObjectSize(8, 3),\n defaultType: \"normal\"\n };\n static _Properties: $.ListCtor<FileMetadata_KeyValuePair>;\n /**\n* The type of the file.\n*\n*/\n get id(): string {\n return $.utils.getText(0, this);\n }\n set id(value: string) {\n $.utils.setText(0, value, this);\n }\n /**\n* The timestamp representing the file's creation date.\n*\n*/\n get type(): string {\n return $.utils.getText(1, this, FileMetadata._capnp.defaultType);\n }\n set type(value: string) {\n $.utils.setText(1, value, this);\n }\n /**\n* Additional metadata associated with the file.\n*\n*/\n get timestamp(): number {\n return $.utils.getUint32(0, this);\n }\n set timestamp(value: number) {\n $.utils.setUint32(0, value, this);\n }\n _adoptProperties(value: $.Orphan<$.List<FileMetadata_KeyValuePair>>): void {\n $.utils.adopt(value, $.utils.getPointer(2, this));\n }\n _disownProperties(): $.Orphan<$.List<FileMetadata_KeyValuePair>> {\n return $.utils.disown(this.properties);\n }\n get properties(): $.List<FileMetadata_KeyValuePair> {\n return $.utils.getList(2, FileMetadata._Properties, this);\n }\n _hasProperties(): boolean {\n return !$.utils.isNull($.utils.getPointer(2, this));\n }\n _initProperties(length: number): $.List<FileMetadata_KeyValuePair> {\n return $.utils.initList(2, FileMetadata._Properties, length, this);\n }\n set properties(value: $.List<FileMetadata_KeyValuePair>) {\n $.utils.copyFrom(value, $.utils.getPointer(2, this));\n }\n public override toString(): string { return \"FileMetadata_\" + super.toString(); }\n}\n/**\n* An identifier for the file.\n*\n*/\nexport class FileId extends $.Struct {\n public static override readonly _capnp = {\n displayName: \"FileId\",\n id: \"990d6a471072f997\",\n size: new $.ObjectSize(0, 2),\n };\n /**\n* A virtual (or actual) path to the file in the file system.\n*\n*/\n get id(): string {\n return $.utils.getText(0, this);\n }\n set id(value: string) {\n $.utils.setText(0, value, this);\n }\n get path(): string {\n return $.utils.getText(1, this);\n }\n set path(value: string) {\n $.utils.setText(1, value, this);\n }\n public override toString(): string { return \"FileId_\" + super.toString(); }\n}\n/**\n* An identifier for the file.\n*\n*/\nexport class FileStorage extends $.Struct {\n public static override readonly _capnp = {\n displayName: \"FileStorage\",\n id: \"9dca66ac858c9ebe\",\n size: new $.ObjectSize(0, 2),\n };\n /**\n* A virtual (or actual) path to the file in the file system.\n*\n*/\n get path(): string {\n return $.utils.getText(0, this);\n }\n set path(value: string) {\n $.utils.setText(0, value, this);\n }\n get code(): string {\n return $.utils.getText(1, this);\n }\n set code(value: string) {\n $.utils.setText(1, value, this);\n }\n public override toString(): string { return \"FileStorage_\" + super.toString(); }\n}\nexport class FileSystem extends $.Struct {\n public static override readonly _capnp = {\n displayName: \"FileSystem\",\n id: \"ae0c23d43e56abcf\",\n size: new $.ObjectSize(0, 3),\n };\n static _Ids: $.ListCtor<FileId>;\n static _Storage: $.ListCtor<FileStorage>;\n static _Metadata: $.ListCtor<FileMetadata>;\n _adoptIds(value: $.Orphan<$.List<FileId>>): void {\n $.utils.adopt(value, $.utils.getPointer(0, this));\n }\n _disownIds(): $.Orphan<$.List<FileId>> {\n return $.utils.disown(this.ids);\n }\n get ids(): $.List<FileId> {\n return $.utils.getList(0, FileSystem._Ids, this);\n }\n _hasIds(): boolean {\n return !$.utils.isNull($.utils.getPointer(0, this));\n }\n _initIds(length: number): $.List<FileId> {\n return $.utils.initList(0, FileSystem._Ids, length, this);\n }\n set ids(value: $.List<FileId>) {\n $.utils.copyFrom(value, $.utils.getPointer(0, this));\n }\n _adoptStorage(value: $.Orphan<$.List<FileStorage>>): void {\n $.utils.adopt(value, $.utils.getPointer(1, this));\n }\n _disownStorage(): $.Orphan<$.List<FileStorage>> {\n return $.utils.disown(this.storage);\n }\n get storage(): $.List<FileStorage> {\n return $.utils.getList(1, FileSystem._Storage, this);\n }\n _hasStorage(): boolean {\n return !$.utils.isNull($.utils.getPointer(1, this));\n }\n _initStorage(length: number): $.List<FileStorage> {\n return $.utils.initList(1, FileSystem._Storage, length, this);\n }\n set storage(value: $.List<FileStorage>) {\n $.utils.copyFrom(value, $.utils.getPointer(1, this));\n }\n _adoptMetadata(value: $.Orphan<$.List<FileMetadata>>): void {\n $.utils.adopt(value, $.utils.getPointer(2, this));\n }\n _disownMetadata(): $.Orphan<$.List<FileMetadata>> {\n return $.utils.disown(this.metadata);\n }\n get metadata(): $.List<FileMetadata> {\n return $.utils.getList(2, FileSystem._Metadata, this);\n }\n _hasMetadata(): boolean {\n return !$.utils.isNull($.utils.getPointer(2, this));\n }\n _initMetadata(length: number): $.List<FileMetadata> {\n return $.utils.initList(2, FileSystem._Metadata, length, this);\n }\n set metadata(value: $.List<FileMetadata>) {\n $.utils.copyFrom(value, $.utils.getPointer(2, this));\n }\n public override toString(): string { return \"FileSystem_\" + super.toString(); }\n}\nFileMetadata._Properties = $.CompositeList(FileMetadata_KeyValuePair);\nFileSystem._Ids = $.CompositeList(FileId);\nFileSystem._Storage = $.CompositeList(FileStorage);\nFileSystem._Metadata = $.CompositeList(FileMetadata);\n","/* -------------------------------------------------------------------\n\n ⚡ Storm Software - Powerlines\n\n This code was released as part of the Powerlines project. Powerlines\n is maintained by Storm Software under the Apache-2.0 license, and is\n free for commercial and private use. For more information, please visit\n our licensing page at https://stormsoftware.com/licenses/projects/powerlines.\n\n Website: https://stormsoftware.com\n Repository: https://github.com/storm-software/powerlines\n Documentation: https://docs.stormsoftware.com/projects/powerlines\n Contact: https://stormsoftware.com/contact\n\n SPDX-License-Identifier: Apache-2.0\n\n ------------------------------------------------------------------- */\n\nexport const DEFAULT_EXTENSIONS = [\n \"js\",\n \"ts\",\n \"cjs\",\n \"cts\",\n \"mjs\",\n \"mts\",\n \"tsx\",\n \"jsx\",\n \"json\",\n \"json5\",\n \"jsonc\",\n \"md\",\n \"mdx\"\n];\n","/* -------------------------------------------------------------------\n\n ⚡ Storm Software - Powerlines\n\n This code was released as part of the Powerlines project. Powerlines\n is maintained by Storm Software under the Apache-2.0 license, and is\n free for commercial and private use. For more information, please visit\n our licensing page at https://stormsoftware.com/licenses/projects/powerlines.\n\n Website: https://stormsoftware.com\n Repository: https://github.com/storm-software/powerlines\n Documentation: https://docs.stormsoftware.com/projects/powerlines\n Contact: https://stormsoftware.com/contact\n\n SPDX-License-Identifier: Apache-2.0\n\n ------------------------------------------------------------------- */\n\nimport { LogLevelLabel } from \"@storm-software/config-tools/types\";\nimport * as capnp from \"@stryke/capnp\";\nimport { toArray } from \"@stryke/convert/to-array\";\nimport {\n readFileBuffer,\n readFileBufferSync,\n writeFileBuffer\n} from \"@stryke/fs/buffer\";\nimport { existsSync } from \"@stryke/fs/exists\";\nimport {\n getResolutionCombinations,\n resolve,\n resolveSync\n} from \"@stryke/fs/resolve\";\nimport { murmurhash } from \"@stryke/hash\";\nimport { getUnique } from \"@stryke/helpers/get-unique\";\nimport { appendPath } from \"@stryke/path/append\";\nimport { correctPath, stripStars } from \"@stryke/path/correct-path\";\nimport {\n findFileExtensionSafe,\n findFileName,\n findFilePath,\n hasFileExtension\n} from \"@stryke/path/file-path-fns\";\nimport { globToRegex } from \"@stryke/path/glob-to-regex\";\nimport { isParentPath } from \"@stryke/path/is-parent-path\";\nimport { isAbsolutePath } from \"@stryke/path/is-type\";\nimport { joinPaths } from \"@stryke/path/join\";\nimport { replaceExtension, replacePath } from \"@stryke/path/replace\";\nimport { slash } from \"@stryke/path/slash\";\nimport { prettyBytes } from \"@stryke/string-format/pretty-bytes\";\nimport { isRegExp } from \"@stryke/type-checks/is-regexp\";\nimport { isSetObject } from \"@stryke/type-checks/is-set-object\";\nimport { isSetString } from \"@stryke/type-checks/is-set-string\";\nimport { isString } from \"@stryke/type-checks/is-string\";\nimport { AssetGlob } from \"@stryke/types/file\";\nimport { create, FlatCache } from \"flat-cache\";\nimport { Blob } from \"node:buffer\";\nimport { PathOrFileDescriptor } from \"node:fs\";\nimport { fileURLToPath } from \"node:url\";\nimport { ResolverFactory } from \"oxc-resolver\";\nimport { FileId, FileMetadata, FileSystem } from \"../../schemas/fs\";\nimport { replacePathTokens } from \"../plugin-utils\";\nimport { FileSystemStorageAdapter } from \"../storage/file-system\";\nimport { VirtualStorageAdapter } from \"../storage/virtual\";\nimport {\n Context,\n LogFn,\n ResolveOptions,\n StorageAdapter,\n StoragePort,\n StoragePreset,\n VirtualFileMetadata,\n VirtualFileSystemInterface,\n WriteOptions\n} from \"../types\";\nimport { extendLog, format } from \"../utils\";\nimport { DEFAULT_EXTENSIONS } from \"./helpers/constants\";\n\ninterface StorageAdapterState {\n adapter: StorageAdapter;\n relativeKey: string;\n base: string;\n}\n\nfunction toFilePath(path: PathOrFileDescriptor): string {\n return correctPath(slash(path?.toString() || \".\").replace(/^file:\\/\\//, \"\"));\n}\n\n/**\n * Checks if a given file id is valid based on the specified prefix.\n *\n * @param id - The file ID to check.\n * @param prefix - The prefix to use for built-in files. Default is \"powerlines\".\n * @returns `true` if the file ID is valid, otherwise `false`.\n */\nfunction isValidId(id: string, prefix = \"powerlines\"): boolean {\n return id.replace(/^\\\\0/, \"\").startsWith(`${prefix.replace(/:$/, \"\")}`);\n}\n\n/**\n * Formats a file id by removing the file extension and prepended runtime prefix.\n *\n * @param id - The file ID to format.\n * @param prefix - The prefix to use for built-in files. Default is \"powerlines\".\n * @returns The formatted file ID.\n */\nfunction normalizeId(id: string, prefix = \"powerlines\"): string {\n // return `${prefix.replace(/:$/, \"\")}:${toFilePath(id)\n // .replace(new RegExp(`^${prefix.replace(/:$/, \"\")}:`), \"\")\n // .replace(/^\\\\0/, \"\")\n // .replace(findFileDotExtensionSafe(toFilePath(id)), \"\")}`;\n\n return replaceExtension(toFilePath(id))\n .replace(/^\\\\0/, \"\")\n .replace(/^powerlines:/, \"\")\n .replace(new RegExp(`^${prefix.replace(/:$/, \"\")}:`), \"\");\n}\n\n/**\n * Normalizes a given path by resolving it against the project root, workspace root, and built-ins path.\n *\n * @param path - The path to normalize.\n * @param builtinsPath - The path to built-in files.\n * @param prefix - The prefix to use for built-in files. Default is \"powerlines\".\n * @returns The normalized path.\n */\nfunction normalizePath(\n path: string,\n builtinsPath: string,\n prefix = \"powerlines\"\n): string {\n return isAbsolutePath(path)\n ? path\n : isValidId(toFilePath(path), prefix)\n ? normalizeId(toFilePath(path), prefix).replace(\n new RegExp(`^${prefix.replace(/:$/, \"\")}:`),\n builtinsPath\n )\n : toFilePath(path);\n}\n\n/**\n * Normalizes glob patterns by resolving them against the workspace root.\n *\n * @param workspaceRoot - The root directory of the workspace.\n * @param patterns - The glob patterns to normalize.\n * @returns An array of normalized glob patterns.\n */\nfunction normalizeGlobPatterns(\n workspaceRoot: string,\n patterns:\n | string\n | Omit<AssetGlob, \"output\">\n | (string | Omit<AssetGlob, \"output\">)[]\n): string[] {\n return getUnique(\n toArray(patterns)\n .map(pattern => {\n if (\n isSetObject(pattern) &&\n (isSetString(pattern.input) || isSetString(pattern.glob))\n ) {\n return joinPaths(\n pattern.input || workspaceRoot,\n pattern.glob || \"**/*\"\n );\n } else if (!isSetString(pattern)) {\n return undefined;\n }\n\n return pattern;\n })\n .filter(isSetString)\n );\n}\n\n/**\n * Represents a virtual file system (VFS) that stores files and their associated metadata in virtual memory.\n *\n * @remarks\n * This class provides methods to manage virtual files, check their existence, retrieve their content, and manipulate the virtual file system. It allows for efficient file management and retrieval without relying on the actual file system.\n */\nexport class VirtualFileSystem implements VirtualFileSystemInterface {\n /**\n * A map of virtual file IDs to their associated metadata.\n */\n #metadata: Record<string, VirtualFileMetadata>;\n\n /**\n * A map of underlying file paths to their virtual file IDs.\n */\n #ids: Record<string, string>;\n\n /**\n * A map of virtual file IDs to their underlying file paths.\n */\n #paths: Record<string, string>;\n\n /**\n * The unified volume that combines the virtual file system with the real file system.\n *\n * @remarks\n * This volume allows for seamless access to both virtual and real files.\n */\n #storage: StoragePort;\n\n /**\n * The resolver factory used during module resolution within the virtual file system.\n *\n * @see https://github.com/oxc-project/oxc-resolver\n */\n #resolver!: ResolverFactory;\n\n /**\n * A cache for module resolution results.\n */\n #resolverCache!: FlatCache;\n\n /**\n * Indicator specifying if the virtual file system (VFS) is disposed\n */\n #isDisposed = false;\n\n /**\n * The context of the virtual file system.\n */\n #context: Context;\n\n /**\n * The file system's logging function.\n */\n #log: LogFn;\n\n /**\n * Normalizes a given module id by resolving it against the built-ins path.\n *\n * @param id - The module id to normalize.\n * @returns The normalized module id.\n */\n #normalizeId(id: string): string {\n let normalized = id;\n if (isParentPath(normalized, this.#context.builtinsPath)) {\n normalized = replacePath(normalized, this.#context.builtinsPath);\n }\n\n return normalizeId(normalized, this.#context.config.framework);\n }\n\n /**\n * Normalizes a given path by resolving it against the project root, workspace root, and built-ins path.\n *\n * @param path - The path to normalize.\n * @returns The normalized path.\n */\n #normalizePath(path: string): string {\n return normalizePath(\n path.includes(\"{\") || path.includes(\"}\")\n ? replacePathTokens(this.#context, path)\n : path,\n this.#context.builtinsPath,\n this.#context.config.framework\n );\n }\n\n /**\n * Gets the storage adapter and relative key for a given key.\n *\n * @remarks\n * The `key` can be either a path or a storage adapter name.\n *\n * @param key - The key to get the storage adapter for.\n * @returns The storage adapter and relative key for the given key.\n */\n #getStorage(key: string, preset?: StoragePreset): StorageAdapterState {\n const path = this.resolveSync(this.#normalizePath(key)) || key;\n for (const base of Object.keys(this.#storage)\n .filter(Boolean)\n .sort()\n .reverse()) {\n if (\n (path === base || isParentPath(path, base)) &&\n (!preset ||\n this.#storage[base]?.preset?.toLowerCase() === preset.toLowerCase())\n ) {\n return {\n base,\n relativeKey: replacePath(path, base),\n adapter: this.#storage[base]!\n };\n }\n }\n\n if (\n !preset ||\n this.#storage[\"\"]?.preset?.toLowerCase() === preset.toLowerCase()\n ) {\n return {\n base: \"\",\n relativeKey: path,\n adapter: this.#storage[\"\"]!\n };\n }\n\n this.#storage[path] =\n preset === \"virtual\"\n ? new VirtualStorageAdapter(this.#context, {\n base: path\n })\n : new FileSystemStorageAdapter(this.#context, {\n base: path\n });\n\n return {\n base: path,\n relativeKey: \"\",\n adapter: this.#storage[path]\n };\n }\n\n /**\n * Gets all storage adapters that match a given base key.\n *\n * @param base - The base key to match storage adapters against.\n * @param includeParent - Whether to include parent storage adapters.\n * @returns An array of storage adapters that match the given base key.\n */\n #getStorages(base = \"\", includeParent = false) {\n const baseKey = this.resolveSync(base) || base;\n\n return Object.keys(this.#storage)\n .sort()\n .reverse()\n .filter(\n key =>\n isParentPath(key, baseKey) ||\n (includeParent && isParentPath(baseKey, key)) ||\n (baseKey.includes(\"*\") &&\n (isParentPath(stripStars(baseKey), key) ||\n globToRegex(replaceExtension(baseKey)).test(key)))\n )\n .map(key => ({\n relativeBase:\n baseKey.length > key.length ? baseKey.slice(key.length) : undefined,\n base: key,\n adapter: this.#storage[key]!\n }));\n }\n\n /**\n * A helper function to resolve modules in the virtual file system (VFS).\n *\n * @remarks\n * This function can be used to resolve modules relative to the project root directory.\n *\n * @example\n * ```ts\n * const resolved = await context.resolvePath(\"some-module\", \"/path/to/importer\");\n * ```\n *\n * @param id - The module to resolve.\n * @param importer - An optional path to the importer module.\n * @param options - Additional resolution options.\n * @returns A promise that resolves to the resolved module path.\n */\n #innerResolve = async (\n id: string,\n importer?: string,\n options: ResolveOptions = {}\n ): Promise<string | undefined> => {\n let path = id;\n if (path.includes(\"{\") || path.includes(\"}\")) {\n path = replacePathTokens(this.#context, path);\n }\n\n if (options.skipAlias !== true) {\n path = this.resolveAlias(path);\n }\n\n if (\n isAbsolutePath(path) &&\n (!options.isFile || !(await this.isDirectory(path)))\n ) {\n return path;\n }\n\n const resolverCacheKey = murmurhash({\n path: this.#normalizeId(path),\n importer,\n options\n });\n\n let result!: string | undefined;\n if (!this.#context.config.skipCache) {\n result = this.resolverCache.get<string | undefined>(resolverCacheKey);\n if (result) {\n return result;\n }\n }\n\n result = this.paths[this.#normalizeId(path)];\n if (!result) {\n const paths = options.paths ?? [];\n if (importer && !paths.includes(importer)) {\n paths.push(importer);\n }\n\n if (!importer) {\n paths.push(this.#context.workspaceConfig.workspaceRoot);\n paths.push(\n appendPath(\n this.#context.config.root,\n this.#context.workspaceConfig.workspaceRoot\n )\n );\n paths.push(\n appendPath(\n joinPaths(this.#context.config.root, \"src\"),\n this.#context.workspaceConfig.workspaceRoot\n )\n );\n }\n\n paths.push(\n ...(\n Object.keys(this.#context.tsconfig?.options?.paths ?? {})\n .filter(tsconfigPath =>\n path.startsWith(tsconfigPath.replace(/\\*$/, \"\"))\n )\n .map(\n tsconfigPath =>\n this.#context.tsconfig?.options?.paths?.[tsconfigPath]\n )\n .flat()\n .filter(Boolean) as string[]\n ).map(tsconfigPath =>\n appendPath(tsconfigPath, this.#context.workspaceConfig.workspaceRoot)\n )\n );\n\n for (const combination of getResolutionCombinations(path, { paths })) {\n const { relativeKey, adapter } = this.#getStorage(combination);\n if (await adapter.exists(relativeKey)) {\n result = combination;\n break;\n }\n }\n\n if (!result) {\n try {\n result = await resolve(path, { ...options, paths });\n } catch {\n // Do nothing\n }\n\n if (!result) {\n let index = 0;\n do {\n const resolveResult = await this.resolver.async(\n (paths.length > index ? paths[index] : undefined) ||\n this.#context.config.root,\n path\n );\n if (resolveResult.path) {\n result = resolveResult.path;\n }\n\n index++;\n } while (!result && index < paths.length);\n }\n }\n }\n\n if (result && !this.#context.config.skipCache) {\n this.resolverCache.set(resolverCacheKey, result);\n }\n\n return result;\n };\n\n /**\n * A synchronous helper function to resolve modules using the Jiti resolver\n *\n * @remarks\n * This function can be used to resolve modules relative to the project root directory.\n *\n * @example\n * ```ts\n * const resolvedPath = context.resolveSync(\"some-module\", \"/path/to/importer\");\n * ```\n *\n * @param id - The module to resolve.\n * @param importer - An optional path to the importer module.\n * @param options - Additional resolution options.\n * @returns The resolved module path.\n */\n #innerResolveSync = (\n id: string,\n importer?: string,\n options: ResolveOptions = {}\n ): string | undefined => {\n let path = id;\n if (path.includes(\"{\") || path.includes(\"}\")) {\n path = replacePathTokens(this.#context, path);\n }\n\n if (options.skipAlias !== true) {\n path = this.resolveAlias(path);\n }\n\n if (\n isAbsolutePath(path) &&\n (!options.isFile || !this.isDirectorySync(path))\n ) {\n return path;\n }\n\n let result!: string | undefined;\n if (!this.#context.config.skipCache) {\n result = this.resolverCache.get<string | undefined>(\n this.#normalizeId(path)\n );\n if (result) {\n return result;\n }\n }\n\n result = this.paths[this.#normalizeId(path)];\n if (!result) {\n const paths = options.paths ?? [];\n if (importer && !paths.includes(importer)) {\n paths.push(importer);\n }\n\n if (!importer) {\n paths.push(this.#context.workspaceConfig.workspaceRoot);\n paths.push(\n appendPath(\n this.#context.config.root,\n this.#context.workspaceConfig.workspaceRoot\n )\n );\n paths.push(\n appendPath(\n joinPaths(this.#context.config.root, \"src\"),\n this.#context.workspaceConfig.workspaceRoot\n )\n );\n }\n\n paths.push(\n ...(\n Object.keys(this.#context.tsconfig?.options?.paths ?? {})\n .filter(tsconfigPath =>\n path.startsWith(tsconfigPath.replace(/\\*$/, \"\"))\n )\n .map(\n tsconfigPath =>\n this.#context.tsconfig?.options?.paths?.[tsconfigPath]\n )\n .flat()\n .filter(Boolean) as string[]\n ).map(tsconfigPath =>\n appendPath(tsconfigPath, this.#context.workspaceConfig.workspaceRoot)\n )\n );\n\n for (const combination of getResolutionCombinations(path, { paths })) {\n const { relativeKey, adapter } = this.#getStorage(combination);\n if (adapter.existsSync(relativeKey)) {\n result = combination;\n break;\n }\n }\n\n if (!result) {\n try {\n result = resolveSync(path, { ...options, paths });\n } catch {\n // Do nothing\n }\n\n if (!result) {\n let index = 0;\n do {\n const resolveResult = this.resolver.sync(\n (paths.length > index ? paths[index] : undefined) ||\n this.#context.config.root,\n path\n );\n if (resolveResult.path) {\n result = resolveResult.path;\n }\n\n index++;\n } while (!result && index < paths.length);\n }\n }\n }\n\n if (result && !this.#context.config.skipCache) {\n this.resolverCache.set(this.#normalizeId(path), result);\n }\n\n return result;\n };\n\n /**\n * Creates a virtual file system (VFS) that is backed up to a Cap'n Proto message buffer.\n *\n * @param context - The context of the virtual file system, typically containing options and logging functions.\n * @returns A promise that resolves to a new virtual file system instance.\n */\n public static async create(context: Context): Promise<VirtualFileSystem> {\n context.debug(\n \"Starting virtual file system (VFS) initialization processes...\"\n );\n\n let result!: VirtualFileSystem;\n if (\n !context.config.skipCache &&\n existsSync(joinPaths(context.dataPath, \"fs.bin\"))\n ) {\n const buffer = await readFileBuffer(\n joinPaths(context.dataPath, \"fs.bin\")\n );\n\n const message = new capnp.Message(buffer, false);\n const fs = message.getRoot(FileSystem);\n\n result = new VirtualFileSystem(context, fs);\n\n if (fs._hasStorage() && fs.storage.length > 0) {\n await Promise.all(\n fs.storage.values().map(async file => {\n if (file.path && file.code) {\n let id: FileId | undefined;\n if (fs._hasIds()) {\n id = fs.ids.find((fileId: FileId) => fileId.path === file.path);\n }\n\n let metadata: FileMetadata | undefined;\n if (fs._hasMetadata()) {\n metadata = fs.metadata.find(\n (meta: FileMetadata) =>\n meta.id === result.#normalizeId(id?.id ?? file.path)\n );\n }\n\n await result.write(file.path, file.code, {\n meta: {\n id: result.#normalizeId(id?.id ?? metadata?.id ?? file.path),\n type: metadata?.type || \"normal\",\n properties: metadata?._hasProperties()\n ? metadata?.properties.values().reduce(\n (ret, kvp) => {\n ret[kvp.key] = kvp.value;\n return ret;\n },\n {} as Record<string, string>\n )\n : undefined,\n timestamp: metadata?.timestamp\n }\n });\n }\n })\n );\n }\n } else {\n const message = new capnp.Message();\n result = new VirtualFileSystem(context, message.initRoot(FileSystem));\n }\n\n result.#log(\n LogLevelLabel.DEBUG,\n \"Successfully completed virtual file system (VFS) initialization.\"\n );\n\n return result;\n }\n\n /**\n * Synchronously creates a virtual file system (VFS) that is backed up to a Cap'n Proto message buffer.\n *\n * @param context - The context of the virtual file system, typically containing options and logging functions.\n * @returns A new virtual file system instance.\n */\n public static createSync(context: Context): VirtualFileSystem {\n context.debug(\n \"Starting virtual file system (VFS) initialization processes...\"\n );\n\n let result!: VirtualFileSystem;\n if (\n !context.config.skipCache &&\n existsSync(joinPaths(context.dataPath, \"fs.bin\"))\n ) {\n const buffer = readFileBufferSync(joinPaths(context.dataPath, \"fs.bin\"));\n\n const message = new capnp.Message(buffer, false);\n const fs = message.getRoot(FileSystem);\n\n result = new VirtualFileSystem(context, fs);\n\n if (fs._hasStorage() && fs.storage.length > 0) {\n fs.storage.values().forEach(file => {\n if (file.path && file.code) {\n let id: FileId | undefined;\n if (fs._hasIds()) {\n id = fs.ids.find((fileId: FileId) => fileId.path === file.path);\n }\n\n let metadata: FileMetadata | undefined;\n if (fs._hasMetadata()) {\n metadata = fs.metadata.find(\n (meta: FileMetadata) =>\n meta.id === result.#normalizeId(id?.id ?? file.path)\n );\n }\n\n result.writeSync(file.path, file.code, {\n meta: {\n id: result.#normalizeId(id?.id ?? metadata?.id ?? file.path),\n type: metadata?.type,\n properties: metadata?._hasProperties()\n ? metadata?.properties.values().reduce(\n (ret, kvp) => {\n ret[kvp.key] = kvp.value;\n return ret;\n },\n {} as Record<string, string>\n )\n : undefined,\n timestamp: metadata?.timestamp\n }\n });\n }\n });\n }\n } else {\n const message = new capnp.Message();\n result = new VirtualFileSystem(context, message.initRoot(FileSystem));\n }\n\n result.#log(\n LogLevelLabel.DEBUG,\n \"Successfully completed virtual file system (VFS) initialization.\"\n );\n\n return result;\n }\n\n /**\n * A map of file ids to their metadata.\n */\n public get metadata(): Record<string, VirtualFileMetadata> {\n return new Proxy(this.#metadata, {\n get: (target, prop: string) => {\n return target[this.#normalizeId(prop)];\n },\n set: (target, prop: string, value) => {\n target[this.#normalizeId(prop)] = value;\n return true;\n },\n deleteProperty: (target, prop: string) => {\n delete target[this.#normalizeId(prop)];\n return true;\n },\n has: (target, prop: string) => {\n return this.#normalizeId(prop) in target;\n },\n ownKeys: target => {\n return getUnique(\n Reflect.ownKeys(target).map(key => this.#normalizeId(key as string))\n );\n }\n });\n }\n\n /**\n * A map of file paths to their module ids.\n */\n public get ids(): Record<string, string> {\n return new Proxy(this.#ids, {\n get: (target, prop: string) => {\n return target[this.#normalizePath(prop)];\n },\n set: (target, prop: string, value) => {\n target[this.#normalizePath(prop)] = value;\n return true;\n },\n deleteProperty: (target, prop: string) => {\n delete target[this.#normalizePath(prop)];\n return true;\n },\n has: (target, prop: string) => {\n return this.#normalizePath(prop) in target;\n },\n ownKeys: target => {\n return getUnique(\n Reflect.ownKeys(target).map(key => this.#normalizePath(key as string))\n );\n }\n });\n }\n\n /**\n * A map of module ids to their file paths.\n */\n public get paths(): Record<string, string> {\n return new Proxy(this.#paths, {\n get: (target, prop: string) => {\n return target[this.#normalizeId(prop)];\n },\n set: (target, prop: string, value) => {\n target[this.#normalizeId(prop)] = value;\n return true;\n },\n deleteProperty: (target, prop: string) => {\n delete target[this.#normalizeId(prop)];\n return true;\n },\n has: (target, prop: string) => {\n return this.#normalizeId(prop) in target;\n },\n ownKeys: target => {\n return getUnique(\n Reflect.ownKeys(target).map(key => this.#normalizeId(key as string))\n );\n }\n });\n }\n\n /**\n * Gets the resolver cache.\n */\n protected get resolverCache(): FlatCache {\n if (!this.#resolverCache) {\n this.#resolverCache = create({\n cacheId: \"module-resolution\",\n cacheDir: this.#context.cachePath,\n ttl: 60 * 60 * 1000,\n lruSize: 5000,\n persistInterval: 100\n });\n }\n\n return this.#resolverCache;\n }\n\n /**\n * The resolver factory used during module resolution within the virtual file system.\n *\n * @remarks\n * This resolver is configured with the workspace root, project root, TypeScript configuration, alias mappings, and other resolution options specified in the context. It is lazily initialized on first access to optimize performance.\n *\n * @see https://github.com/oxc-project/oxc-resolver\n */\n protected get resolver(): ResolverFactory {\n if (!this.#resolver) {\n this.#resolver = new ResolverFactory({\n roots: [\n this.#context.workspaceConfig.workspaceRoot,\n appendPath(\n this.#context.config.root,\n this.#context.workspaceConfig.workspaceRoot\n )\n ],\n tsconfig: {\n configFile: this.#context.tsconfig.tsconfigFilePath,\n references:\n this.#context.tsconfig.projectReferences &&\n this.#context.tsconfig.projectReferences.length > 0\n ? \"auto\"\n : undefined\n },\n alias: Object.fromEntries(\n Object.entries(this.#context.alias).map(([key, value]) => [\n key,\n [value]\n ])\n ),\n extensions: this.#context.config.resolve.extensions,\n mainFields: this.#context.config.resolve.mainFields,\n conditionNames: this.#context.config.resolve.conditions,\n symlinks: this.#context.config.resolve.preserveSymlinks,\n allowPackageExportsInDirectoryResolve: true\n });\n }\n\n return this.#resolver;\n }\n\n /**\n * Creates a new instance of the {@link VirtualFileSystem}.\n *\n * @param context - The context of the virtual file system, typically containing options and logging functions.\n * @param fs - A buffer containing the serialized virtual file system data.\n */\n private constructor(context: Context, fs: FileSystem) {\n this.#context = context;\n this.#storage = { \"\": new FileSystemStorageAdapter(context) };\n\n if (isSetObject(this.#context.config.output.storage)) {\n this.#storage = {\n ...this.#storage,\n ...this.#context.config.output.storage\n };\n }\n\n this.#storage.virtual ??= new VirtualStorageAdapter(context, {\n base: \"/_virtual\"\n });\n\n this.#storage[this.#context.config.output.outputPath] ??=\n new FileSystemStorageAdapter(context, {\n base: this.#context.config.output.outputPath\n });\n this.#storage[this.#context.config.output.buildPath] ??=\n new FileSystemStorageAdapter(context, {\n base: this.#context.config.output.buildPath\n });\n\n if (this.#context.config.output.storage !== \"fs\") {\n this.#storage[this.#context.artifactsPath] ??= new VirtualStorageAdapter(\n context,\n {\n base: this.#context.artifactsPath\n }\n );\n this.#storage[this.#context.builtinsPath] ??= new VirtualStorageAdapter(\n context,\n {\n base: this.#context.builtinsPath\n }\n );\n this.#storage[this.#context.entryPath] ??= new VirtualStorageAdapter(\n context,\n {\n base: this.#context.entryPath\n }\n );\n }\n\n this.#metadata = {} as Record<string, VirtualFileMetadata>;\n if (fs._hasMetadata()) {\n this.#metadata = fs.metadata.values().reduce(\n (ret, metadata) => {\n ret[metadata.id] = {\n id: metadata.id,\n type: metadata.type,\n timestamp: metadata.timestamp ?? Date.now(),\n properties: metadata._hasProperties()\n ? metadata.properties.values().reduce(\n (ret, item) => {\n ret[item.key] = item.value;\n return ret;\n },\n {} as Record<string, string>\n )\n : {}\n };\n\n return ret;\n },\n {} as Record<string, VirtualFileMetadata>\n );\n }\n\n this.#ids = {} as Record<string, string>;\n this.#paths = {} as Record<string, string>;\n\n if (fs._hasIds()) {\n this.#ids = fs.ids.values().reduce(\n (ret, identifier) => {\n ret[identifier.path] ??= identifier.id;\n\n return ret;\n },\n {} as Record<string, string>\n );\n\n this.#paths = fs.ids.values().reduce(\n (ret, identifier) => {\n ret[identifier.id] ??= identifier.path;\n return ret;\n },\n {} as Record<string, string>\n );\n }\n\n this.#log = extendLog(this.#context.log, \"file-system\");\n }\n\n /**\n * Asynchronously checks if a file exists in the virtual file system (VFS).\n *\n * @param path - The path to the file.\n * @returns A promise that resolves to `true` if the file exists, otherwise `false`.\n */\n public async exists(path: string): Promise<boolean> {\n const { relativeKey, adapter } = this.#getStorage(path);\n\n return adapter.exists(relativeKey);\n }\n\n /**\n * Synchronously checks if a file exists in the virtual file system (VFS).\n *\n * @param path - The path to the file.\n * @returns `true` if the file exists, otherwise `false`.\n */\n public existsSync(path: string): boolean {\n const { relativeKey, adapter } = this.#getStorage(path);\n\n return adapter.existsSync(relativeKey);\n }\n\n /**\n * Checks if a file is virtual in the virtual file system (VFS).\n *\n * @param path - The path to the file.\n * @returns `true` if the file is virtual, otherwise `false`.\n */\n public isVirtual(path: string): boolean {\n const resolved = this.resolveSync(path);\n if (!resolved) {\n return false;\n }\n\n return this.#getStorage(resolved)?.adapter?.preset === \"virtual\";\n }\n\n /**\n * Checks if a path is a directory in the virtual file system (VFS).\n *\n * @param path - The path to check.\n * @returns `true` if the path is a directory, otherwise `false`.\n */\n public isDirectorySync(path: string): boolean {\n const resolved = this.resolveSync(path);\n if (!resolved) {\n return false;\n }\n\n return !!(\n this.existsSync(resolved) &&\n this.#getStorage(resolved)?.adapter?.isDirectorySync(resolved)\n );\n }\n\n /**\n * Checks if a path is a directory in the virtual file system (VFS).\n *\n * @param path - The path to check.\n * @returns `true` if the path is a directory, otherwise `false`.\n */\n public async isDirectory(path: string): Promise<boolean> {\n const resolved = await this.resolve(path);\n if (!resolved) {\n return false;\n }\n\n return !!(\n (await this.exists(resolved)) &&\n (await this.#getStorage(resolved)?.adapter?.isDirectory(resolved))\n );\n }\n\n /**\n * Checks if a path is a file in the virtual file system (VFS).\n *\n * @param path - The path to check.\n * @returns `true` if the path is a file, otherwise `false`.\n */\n public isFileSync(path: string): boolean {\n const resolved = this.resolveSync(path);\n if (!resolved) {\n return false;\n }\n\n return this.#getStorage(resolved)?.adapter?.isFileSync(resolved) ?? false;\n }\n\n /**\n * Checks if a path is a file in the virtual file system (VFS).\n *\n * @param path - The path to check.\n * @returns `true` if the path is a file, otherwise `false`.\n */\n public async isFile(path: string): Promise<boolean> {\n const resolved = await this.resolve(path);\n if (!resolved) {\n return false;\n }\n\n return (\n (await this.#getStorage(resolved)?.adapter?.isFile(resolved)) ?? false\n );\n }\n\n /**\n * Lists files in a given path.\n *\n * @param path - The path to list files from.\n * @returns An array of file names in the specified path.\n */\n public listSync(path: string): string[] {\n let resolvedPath = path;\n if (resolvedPath.includes(\"*\")) {\n this.#log(\n LogLevelLabel.WARN,\n `Invoking \"listSync\" with a glob pattern is not supported. It is likely you meant to use \"globSync\". Path: ${path}`\n );\n resolvedPath = stripStars(resolvedPath);\n }\n\n return getUnique(\n this.#getStorages(resolvedPath, true)\n .map(storage =>\n storage.adapter.listSync(\n storage.relativeBase\n ? storage.base\n ? appendPath(storage.relativeBase, storage.base)\n : storage.relativeBase\n : storage.base\n )\n )\n .flat()\n .filter(Boolean)\n );\n }\n\n /**\n * Lists files in a given path.\n *\n * @param path - The path to list files from.\n * @returns An array of file names in the specified path.\n */\n public async list(path: string): Promise<string[]> {\n let resolvedPath = path;\n if (resolvedPath.includes(\"*\")) {\n this.#log(\n LogLevelLabel.WARN,\n `Invoking \"list\" with a glob pattern is not supported. It is likely you meant to use \"glob\". Path: ${path}`\n );\n resolvedPath = stripStars(resolvedPath);\n }\n\n return getUnique(\n (\n await Promise.all(\n this.#getStorages(resolvedPath, true).map(async storage =>\n storage.adapter.list(\n storage.relativeBase\n ? storage.base\n ? appendPath(storage.relativeBase, storage.base)\n : storage.relativeBase\n : storage.base\n )\n )\n )\n )\n .flat()\n .filter(Boolean)\n );\n }\n\n /**\n * Removes a file in the virtual file system (VFS).\n *\n * @param path - The path to create the directory at.\n */\n public async remove(path: string): Promise<void> {\n const normalizedPath = this.#normalizePath(path);\n this.#log(LogLevelLabel.TRACE, `Removing file: ${normalizedPath}`);\n\n const { relativeKey, adapter } = this.#getStorage(normalizedPath);\n\n if (hasFileExtension(normalizedPath)) {\n await adapter.remove(relativeKey);\n } else {\n await adapter.clear(relativeKey);\n }\n\n const id = this.#ids[normalizedPath];\n if (id && this.#metadata[id]) {\n delete this.#metadata[id];\n delete this.#ids[normalizedPath];\n delete this.#paths[id];\n }\n }\n\n /**\n * Removes a file in the virtual file system (VFS).\n *\n * @param path - The path to create the directory at.\n */\n public removeSync(path: string) {\n const normalizedPath = this.#normalizePath(path);\n this.#log(LogLevelLabel.TRACE, `Removing file: ${normalizedPath}`);\n\n const { relativeKey, adapter } = this.#getStorage(normalizedPath);\n\n if (hasFileExtension(normalizedPath)) {\n adapter.removeSync(relativeKey);\n } else {\n adapter.clearSync(relativeKey);\n }\n\n const id = this.#ids[normalizedPath];\n if (id && this.#metadata[id]) {\n delete this.#metadata[id];\n delete this.#ids[normalizedPath];\n delete this.#paths[id];\n }\n }\n\n /**\n * Glob files in the virtual file system (VFS) based on the provided pattern(s).\n *\n * @param patterns - A pattern (or multiple patterns) to use to determine the file paths to return\n * @returns An array of file paths matching the provided pattern(s)\n */\n public async glob(\n patterns:\n | string\n | Omit<AssetGlob, \"output\">\n | (string | Omit<AssetGlob, \"output\">)[]\n ): Promise<string[]> {\n const results: string[] = [];\n for (const pattern of normalizeGlobPatterns(\n this.#context.workspaceConfig.workspaceRoot,\n patterns\n )) {\n const normalized = this.#normalizePath(pattern);\n if (!/[*?[\\]{}]/.test(normalized) && !normalized.includes(\"*\")) {\n if (this.isDirectorySync(normalized)) {\n results.push(...(await this.list(normalized)));\n } else {\n const resolved = await this.resolve(normalized);\n if (resolved && !results.includes(resolved)) {\n results.push(resolved);\n }\n }\n } else {\n const absPattern = isAbsolutePath(normalized)\n ? normalized\n : this.#normalizePath(\n appendPath(\n normalized,\n this.#context.workspaceConfig.workspaceRoot\n )\n );\n\n await Promise.all(\n (await this.list(stripStars(absPattern))).map(async file => {\n if (globToRegex(absPattern).test(file)) {\n const resolved = await this.resolve(file);\n if (resolved && !results.includes(resolved)) {\n results.push(resolved);\n }\n }\n })\n );\n }\n }\n\n return results;\n }\n\n /**\n * Synchronously glob files in the virtual file system (VFS) based on the provided pattern(s).\n *\n * @param patterns - A pattern (or multiple patterns) to use to determine the file paths to return\n * @returns An array of file paths matching the provided pattern(s)\n */\n public globSync(\n patterns:\n | string\n | Omit<AssetGlob, \"output\">\n | (string | Omit<AssetGlob, \"output\">)[]\n ): string[] {\n const results: string[] = [];\n for (const pattern of normalizeGlobPatterns(\n this.#context.workspaceConfig.workspaceRoot,\n patterns\n )) {\n const normalized = this.#normalizePath(pattern);\n if (!/[*?[\\]{}]/.test(normalized) && !normalized.includes(\"*\")) {\n if (this.isDirectorySync(normalized)) {\n results.push(...this.listSync(normalized));\n } else {\n const resolved = this.resolveSync(normalized);\n if (resolved && !results.includes(resolved)) {\n results.push(resolved);\n }\n }\n } else {\n const absPattern = isAbsolutePath(normalized)\n ? normalized\n : this.#normalizePath(\n appendPath(\n normalized,\n this.#context.workspaceConfig.workspaceRoot\n )\n );\n\n const files = this.listSync(stripStars(absPattern));\n for (const file of files) {\n const regex = globToRegex(absPattern);\n if (regex.test(file)) {\n const resolved = this.resolveSync(file);\n if (resolved && !results.includes(resolved)) {\n results.push(resolved);\n }\n }\n }\n }\n }\n\n return results;\n }\n\n /**\n * Copies a file from one path to another in the virtual file system (VFS).\n *\n * @param srcPath - The source path to copy\n * @param destPath - The destination path to copy to\n */\n public async copy(\n srcPath: string | URL | Omit<AssetGlob, \"output\">,\n destPath: string | URL\n ) {\n const src = srcPath instanceof URL ? fileURLToPath(srcPath) : srcPath;\n const dest = destPath instanceof URL ? fileURLToPath(destPath) : destPath;\n\n if (\n (!isSetString(src) && (!isSetObject(src) || !isSetString(src.input))) ||\n !isSetString(dest)\n ) {\n return;\n }\n\n const sourceStr = isString(src)\n ? src\n : src.input\n ? src.input\n : this.#context.workspaceConfig.workspaceRoot;\n const source = await this.resolve(sourceStr);\n if (!source) {\n return;\n }\n\n if (\n this.isDirectorySync(source) ||\n (isSetString(src) && src.includes(\"*\")) ||\n (isSetObject(src) && isSetString(src.glob))\n ) {\n await Promise.all(\n (await this.glob(src)).map(async file => {\n return this.copy(\n file,\n appendPath(replacePath(file, sourceStr), dest)\n );\n })\n );\n } else {\n const content = await this.read(source);\n if (content !== undefined) {\n await this.write(this.#normalizePath(dest), content, {\n skipFormat: true\n });\n }\n }\n }\n\n /**\n * Synchronously copies a file from one path to another in the virtual file system (VFS).\n *\n * @param srcPath - The source path to copy\n * @param destPath - The destination path to copy to\n */\n public copySync(\n srcPath: string | URL | Omit<AssetGlob, \"output\">,\n destPath: string | URL\n ) {\n const src = srcPath instanceof URL ? fileURLToPath(srcPath) : srcPath;\n const dest = destPath instanceof URL ? fileURLToPath(destPath) : destPath;\n\n if (\n (!isSetString(src) && (!isSetObject(src) || !isSetString(src.input))) ||\n !isSetString(dest)\n ) {\n return;\n }\n\n const sourceStr = isString(src)\n ? src\n : src.input\n ? src.input\n : this.#context.workspaceConfig.workspaceRoot;\n const source = this.resolveSync(sourceStr);\n if (!source) {\n return;\n }\n\n if (\n this.isDirectorySync(source) ||\n (isSetString(src) && src.includes(\"*\")) ||\n (isSetObject(src) && isSetString(src.glob))\n ) {\n this.globSync(src).map(file => {\n return this.copySync(\n file,\n appendPath(findFilePath(replacePath(file, sourceStr)), dest)\n );\n });\n } else {\n const content = this.readSync(source);\n if (content !== undefined) {\n this.writeSync(\n this.#normalizePath(\n hasFileExtension(dest)\n ? dest\n : appendPath(findFileName(source), dest)\n ),\n content,\n { skipFormat: true }\n );\n }\n }\n }\n\n /**\n * Moves a file (or files) from one path to another in the virtual file system (VFS).\n *\n * @param srcPath - The source path to move\n * @param destPath - The destination path to move to\n */\n public async move(srcPath: string, destPath: string) {\n if (hasFileExtension(srcPath)) {\n await this.copy(srcPath, destPath);\n await this.remove(srcPath);\n } else {\n await Promise.all(\n (await this.list(srcPath)).map(async file => {\n await this.copy(file, destPath);\n await this.remove(file);\n })\n );\n }\n }\n\n /**\n * Synchronously moves a file (or files) from one path to another in the virtual file system (VFS).\n *\n * @param srcPath - The source path to move\n * @param destPath - The destination path to move to\n */\n public moveSync(srcPath: string, destPath: string) {\n if (hasFileExtension(srcPath)) {\n this.copySync(srcPath, destPath);\n this.removeSync(srcPath);\n } else {\n this.listSync(srcPath).forEach(file => {\n this.copySync(file, destPath);\n this.removeSync(file);\n });\n }\n }\n\n /**\n * Asynchronously reads a file from the virtual file system (VFS).\n *\n * @param path - The path or ID of the file to read.\n * @returns A promise that resolves to the contents of the file as a string, or undefined if the file does not exist.\n */\n public async read(path: string): Promise<string | undefined> {\n const filePath = await this.resolve(path, undefined, { isFile: true });\n if (!filePath || !this.existsSync(filePath)) {\n return undefined;\n }\n\n const { adapter } = this.#getStorage(filePath);\n this.#log(LogLevelLabel.TRACE, `Reading ${adapter.name} file: ${filePath}`);\n\n return (await adapter.get(filePath)) ?? undefined;\n }\n\n /**\n * Synchronously reads a file from the virtual file system (VFS).\n *\n * @param path - The path or ID of the file to read.\n * @returns The contents of the file as a string, or undefined if the file does not exist.\n */\n public readSync(path: string): string | undefined {\n const filePath = this.resolveSync(path, undefined, { isFile: true });\n if (!filePath || !this.existsSync(filePath)) {\n return undefined;\n }\n\n const { adapter } = this.#getStorage(filePath);\n this.#log(LogLevelLabel.TRACE, `Reading ${adapter.name} file: ${filePath}`);\n\n return adapter.getSync(filePath) ?? undefined;\n }\n\n /**\n * Writes a file to the virtual file system (VFS).\n *\n * @param path - The path to the file.\n * @param data - The contents of the file.\n * @param options - Optional parameters for writing the file.\n * @returns A promise that resolves when the file is written.\n */\n public async write(\n path: string,\n data: string = \"\",\n options: WriteOptions = {}\n ): Promise<void> {\n const meta = options.meta ?? {};\n const resolvedPath =\n (await this.resolve(this.#normalizePath(path))) || path;\n\n const { relativeKey, adapter } = this.#getStorage(\n resolvedPath,\n options.storage as StoragePreset\n );\n\n this.#log(\n LogLevelLabel.TRACE,\n `Writing ${resolvedPath} to ${\n adapter.name === \"virtual\"\n ? \"the virtual file system\"\n : adapter.name === \"file-system\"\n ? \"the local file system\"\n : adapter.name\n } (size: ${prettyBytes(new Blob(toArray(data)).size)})`\n );\n\n let code = data;\n try {\n if (!options.skipFormat) {\n code = await format(this.#context, resolvedPath, data);\n }\n } catch (err) {\n // Only warn about formatting errors for certain file types\n if (\n DEFAULT_EXTENSIONS.includes(\n findFileExtensionSafe(resolvedPath, {\n fullExtension: true\n })\n )\n ) {\n this.#log(\n LogLevelLabel.WARN,\n `Failed to format file ${resolvedPath} before writing: ${(err as Error).message}`\n );\n }\n code = data;\n }\n\n this.#log(\n LogLevelLabel.TRACE,\n `Writing ${resolvedPath} to ${\n adapter.name === \"virtual\"\n ? \"the virtual file system\"\n : adapter.name === \"file-system\"\n ? \"the local file system\"\n : adapter.name\n } (size: ${prettyBytes(new Blob(toArray(code)).size)})`\n );\n\n const id = this.#normalizeId(meta.id || resolvedPath);\n this.metadata[id] = {\n type: \"normal\",\n timestamp: Date.now(),\n ...(this.metadata[id] ?? {}),\n ...meta\n } as VirtualFileMetadata;\n this.paths[id] = resolvedPath;\n this.ids[resolvedPath] = id;\n\n return adapter.set(relativeKey, code);\n }\n\n /**\n * Synchronously writes a file to the virtual file system (VFS).\n *\n * @param path - The file to write.\n * @param data - The contents of the file.\n * @param options - Optional parameters for writing the file.\n */\n public writeSync(\n path: string,\n data: string = \"\",\n options: WriteOptions = {}\n ): void {\n const meta = options.meta ?? {};\n const resolvedPath = this.resolveSync(this.#normalizePath(path)) || path;\n\n const { relativeKey, adapter } = this.#getStorage(\n resolvedPath,\n options.storage as StoragePreset\n );\n\n this.#log(\n LogLevelLabel.TRACE,\n `Writing ${resolvedPath} file to ${\n adapter.name === \"virtual\"\n ? \"the virtual file system\"\n : adapter.name === \"file-system\"\n ? \"the local file system\"\n : adapter.name\n } (size: ${prettyBytes(new Blob(toArray(data)).size)})`\n );\n\n const id = this.#normalizeId(meta.id || resolvedPath);\n this.metadata[id] = {\n type: \"normal\",\n timestamp: Date.now(),\n ...(this.metadata[id] ?? {}),\n ...meta\n } as VirtualFileMetadata;\n this.paths[id] = resolvedPath;\n this.ids[resolvedPath] = id;\n\n return adapter.setSync(relativeKey, data);\n }\n\n /**\n * Synchronously creates a directory at the specified path.\n *\n * @param dirPath - The path of the directory to create.\n */\n public mkdirSync(dirPath: string) {\n return this.#getStorage(dirPath)?.adapter?.mkdirSync(dirPath);\n }\n\n /**\n * Creates a directory at the specified path.\n *\n * @param path - The path of the directory to create.\n */\n public async mkdir(path: string): Promise<void> {\n return this.#getStorage(path)?.adapter?.mkdir(path);\n }\n\n /**\n * Retrieves the metadata of a file in the virtual file system (VFS).\n *\n * @param pathOrId - The path or ID of the file to retrieve metadata for.\n * @returns The metadata of the file, or undefined if the file does not exist.\n */\n public getMetadata(pathOrId: string): VirtualFileMetadata | undefined {\n const resolved = this.resolveSync(pathOrId);\n if (resolved && this.metadata[resolved]) {\n return this.metadata[resolved];\n }\n\n return undefined;\n }\n\n /**\n * Resolves a given module ID using the configured aliases.\n *\n * @remarks\n * This function can be used to map module IDs to different paths based on the alias configuration.\n *\n * @param id - The module ID to resolve.\n * @returns The resolved module ID - after applying any configured aliases (this will be the same as the input ID if no aliases match).\n */\n public resolveAlias(id: string): string {\n let path = id;\n\n if (this.#context.config.resolve.alias) {\n if (\n Array.isArray(this.#context.config.resolve.alias) &&\n this.#context.config.resolve.alias.length > 0\n ) {\n const found = this.#context.config.resolve.alias.filter(\n alias =>\n (isSetString(alias.find) &&\n (alias.find === path || path.startsWith(`${alias.find}/`))) ||\n (isRegExp(alias.find) && alias.find.test(path))\n );\n if (found.length > 0) {\n const alias = found.reduce((ret, current) => {\n const retLength = isSetString(ret.find)\n ? ret.find.length\n : isRegExp(ret.find)\n ? ret.find.source.length\n : 0;\n const currentLength = isSetString(current.find)\n ? current.find.length\n : isRegExp(current.find)\n ? current.find.source.length\n : 0;\n\n return retLength > currentLength ? ret : current;\n });\n\n if (isSetString(alias.find)) {\n path = path.replace(\n new RegExp(`^${alias.find}`),\n alias.replacement\n );\n } else if (isRegExp(alias.find)) {\n path = path.replace(alias.find, alias.replacement);\n }\n }\n } else if (isSetObject(this.#context.config.resolve.alias)) {\n const found = Object.keys(\n this.#context.config.resolve.alias as Record<string, string>\n ).filter(key => key === path || path.startsWith(`${key}/`));\n if (found.length > 0) {\n const alias = found.reduce((ret, current) => {\n return ret.length > current.length ? ret : current;\n });\n\n path = path.replace(\n new RegExp(`^${alias}`),\n (this.#context.config.resolve.alias as Record<string, string>)[\n alias\n ]!\n );\n }\n }\n }\n\n return path;\n }\n\n /**\n * A helper function to resolve modules in the virtual file system (VFS).\n *\n * @remarks\n * This function can be used to resolve modules relative to the project root directory.\n *\n * @example\n * ```ts\n * const resolved = await context.resolvePath(\"some-module\", \"/path/to/importer\");\n * ```\n *\n * @param id - The module to resolve.\n * @param importer - An optional path to the importer module.\n * @param options - Additional resolution options.\n * @returns A promise that resolves to the resolved module path.\n */\n public async resolve(\n id: string,\n importer?: string,\n options: ResolveOptions = {}\n ): Promise<string | undefined> {\n const origResult = await this.#innerResolve(id, importer, options);\n if (origResult && options.isFile && (await this.isDirectory(origResult))) {\n const indexResult = await this.resolve(\n joinPaths(origResult, \"index\"),\n importer,\n options\n );\n if (indexResult) {\n return indexResult;\n }\n\n if (!hasFileExtension(origResult)) {\n for (const ext of DEFAULT_EXTENSIONS) {\n const extResult = await this.resolve(\n `${origResult}.${ext}`,\n importer,\n options\n );\n if (extResult) {\n return extResult;\n }\n }\n }\n\n return undefined;\n }\n\n return origResult;\n }\n\n /**\n * A synchronous helper function to resolve modules using the Jiti resolver\n *\n * @remarks\n * This function can be used to resolve modules relative to the project root directory.\n *\n * @example\n * ```ts\n * const resolvedPath = context.resolveSync(\"some-module\", \"/path/to/importer\");\n * ```\n *\n * @param id - The module to resolve.\n * @param importer - An optional path to the importer module.\n * @param options - Additional resolution options.\n * @returns The resolved module path.\n */\n public resolveSync(\n id: string,\n importer?: string,\n options: ResolveOptions = {}\n ): string | undefined {\n const origResult = this.#innerResolveSync(id, importer, options);\n if (origResult && options.isFile && this.isDirectorySync(origResult)) {\n const indexResult = this.resolveSync(\n joinPaths(origResult, \"index\"),\n importer,\n options\n );\n if (indexResult) {\n return indexResult;\n }\n\n if (!hasFileExtension(origResult)) {\n for (const ext of DEFAULT_EXTENSIONS) {\n const extResult = this.resolveSync(\n `${origResult}.${ext}`,\n importer,\n options\n );\n if (extResult) {\n return extResult;\n }\n }\n }\n\n return undefined;\n }\n\n return origResult;\n }\n\n /**\n * Disposes of the virtual file system (VFS) by saving its state to disk.\n */\n public async dispose() {\n if (!this.#isDisposed) {\n this.#isDisposed = true;\n\n this.#log(LogLevelLabel.DEBUG, \"Disposing virtual file system...\");\n await this.remove(joinPaths(this.#context.dataPath, \"fs.bin\"));\n\n const message = new capnp.Message();\n const fs = message.initRoot(FileSystem);\n\n const storage = fs._initStorage(Object.keys(this.#paths).length);\n await Promise.all(\n Object.values(this.#paths).map(async (path, index) => {\n const code = await this.read(path);\n\n const fd = storage.get(index);\n fd.path = path;\n fd.code = code || \"\";\n })\n );\n\n const ids = fs._initIds(Object.keys(this.#ids).length);\n Object.entries(this.#ids)\n .filter(([, id]) => id)\n .forEach(([path, id], index) => {\n const fileId = ids.get(index);\n fileId.id = id;\n fileId.path = path;\n });\n\n const metadata = fs._initMetadata(Object.keys(this.#metadata).length);\n Object.entries(this.#metadata)\n .filter(([, value]) => value)\n .forEach(([id, value], index) => {\n const fileMetadata = metadata.get(index);\n fileMetadata.id = id;\n fileMetadata.type = value.type;\n fileMetadata.timestamp = value.timestamp ?? Date.now();\n\n if (value.properties) {\n const props = fileMetadata._initProperties(\n Object.keys(value.properties).length\n );\n Object.entries(value.properties)\n .filter(([, val]) => isSetString(val))\n .forEach(([key, val], index) => {\n const prop = props.get(index);\n prop.key = key;\n prop.value = val!;\n });\n }\n });\n\n await writeFileBuffer(\n joinPaths(this.#context.dataPath, \"fs.bin\"),\n message.toArrayBuffer()\n );\n\n if (!this.#context.config.skipCache) {\n this.#resolverCache.save(true);\n }\n\n await Promise.all(\n this.#getStorages().map(async storage => storage.adapter.dispose())\n );\n\n this.#log(LogLevelLabel.TRACE, \"Virtual file system has been disposed.\");\n }\n }\n\n // /**\n // * Initializes the virtual file system (VFS) by patching the file system module if necessary.\n // */\n // public [__VFS_PATCH__]() {\n // if (!this.#isPatched && this.#context.config.output.mode !== \"fs\") {\n // this.#revert = patchFS(fs, this);\n // this.#isPatched = true;\n // }\n // }\n\n // /**\n // * Reverts the file system module to its original state if it was previously patched.\n // */\n // public [__VFS_REVERT__]() {\n // if (this.#isPatched && this.#context.config.output.mode !== \"fs\") {\n // if (!this.#revert) {\n // throw new Error(\n // \"Attempting to revert File System patch prior to calling `__init__` function\"\n // );\n // }\n\n // this.#revert?.();\n // this.#isPatched = false;\n // }\n // }\n\n async [Symbol.asyncDispose]() {\n return this.dispose();\n }\n}\n","/* -------------------------------------------------------------------\n\n ⚡ Storm Software - Powerlines\n\n This code was released as part of the Powerlines project. Powerlines\n is maintained by Storm Software under the Apache-2.0 license, and is\n free for commercial and private use. For more information, please visit\n our licensing page at https://stormsoftware.com/licenses/projects/powerlines.\n\n Website: https://stormsoftware.com\n Repository: https://github.com/storm-software/powerlines\n Documentation: https://docs.stormsoftware.com/projects/powerlines\n Contact: https://stormsoftware.com/contact\n\n SPDX-License-Identifier: Apache-2.0\n\n ------------------------------------------------------------------- */\n\nimport { UNSAFE_ContextInternal } from \"@powerlines/core/types/_internal\";\nimport { LogLevelLabel } from \"@storm-software/config-tools/types\";\nimport { toArray } from \"@stryke/convert/to-array\";\nimport { EnvPaths, getEnvPaths } from \"@stryke/env/get-env-paths\";\nimport { existsSync } from \"@stryke/fs/exists\";\nimport { relativeToWorkspaceRoot } from \"@stryke/fs/get-workspace-root\";\nimport { readJsonFile } from \"@stryke/fs/json\";\nimport { resolvePackage } from \"@stryke/fs/resolve\";\nimport { murmurhash } from \"@stryke/hash\";\nimport { hashDirectory } from \"@stryke/hash/node\";\nimport { getUnique, getUniqueBy } from \"@stryke/helpers/get-unique\";\nimport { omit } from \"@stryke/helpers/omit\";\nimport { fetchRequest } from \"@stryke/http/fetch\";\nimport { StormJSON } from \"@stryke/json/storm-json\";\nimport { appendPath } from \"@stryke/path/append\";\nimport {\n findFileDotExtensionSafe,\n findFileExtensionSafe\n} from \"@stryke/path/file-path-fns\";\nimport { isParentPath } from \"@stryke/path/is-parent-path\";\nimport { joinPaths } from \"@stryke/path/join\";\nimport { replacePath } from \"@stryke/path/replace\";\nimport { titleCase } from \"@stryke/string-format/title-case\";\nimport { isFunction } from \"@stryke/type-checks/is-function\";\nimport { isNull } from \"@stryke/type-checks/is-null\";\nimport { isRegExp } from \"@stryke/type-checks/is-regexp\";\nimport { isSetObject } from \"@stryke/type-checks/is-set-object\";\nimport { isSetString } from \"@stryke/type-checks/is-set-string\";\nimport { isString } from \"@stryke/type-checks/is-string\";\nimport { TypeDefinition } from \"@stryke/types/configuration\";\nimport { PackageJson } from \"@stryke/types/package-json\";\nimport { uuid } from \"@stryke/unique-id/uuid\";\nimport { match, tsconfigPathsToRegExp } from \"bundle-require\";\nimport { resolveCompatibilityDates } from \"compatx\";\nimport defu from \"defu\";\nimport { create, FlatCache } from \"flat-cache\";\nimport { parse, ParseResult } from \"oxc-parser\";\nimport { Range } from \"semver\";\nimport {\n Agent,\n BodyInit,\n interceptors,\n RequestInfo,\n Response,\n setGlobalDispatcher\n} from \"undici\";\nimport { UnpluginBuildContext, UnpluginMessage } from \"unplugin\";\nimport { getPrefixedRootHash } from \"../_internal/helpers/meta\";\nimport {\n createResolver,\n CreateResolverOptions\n} from \"../_internal/helpers/resolver\";\nimport { VirtualFileSystem } from \"../_internal/vfs\";\nimport { loadUserConfigFile, loadWorkspaceConfig } from \"../config\";\nimport { CACHE_HASH_LENGTH, ROOT_HASH_LENGTH } from \"../constants\";\nimport {\n checkDedupe,\n isPlugin,\n mergeConfig,\n replacePathTokens\n} from \"../plugin-utils\";\nimport type {\n Context,\n EmitEntryOptions,\n EmitOptions,\n FetchOptions,\n InitContextOptions,\n InitialUserConfig,\n LogFn,\n MetaInfo,\n ParsedTypeScriptConfig,\n ParsedUserConfig,\n ParseOptions,\n PluginConfig,\n PowerlinesCommand,\n ResolveConfig,\n ResolvedAssetGlob,\n ResolvedConfig,\n ResolvedEntryTypeDefinition,\n ResolveOptions,\n Resolver,\n ResolveResult,\n TransformResult,\n VirtualFile,\n VirtualFileSystemInterface,\n WorkspaceConfig\n} from \"../types\";\nimport { getTsconfigFilePath } from \"../typescript/tsconfig\";\nimport {\n createLog,\n extendLog,\n getUniqueInputs,\n isTypeDefinition,\n resolveInputsSync\n} from \"../utils\";\n\ninterface ConfigCacheKey {\n root: string;\n mode: \"test\" | \"development\" | \"production\";\n skipCache: boolean;\n configFile?: string;\n framework: string;\n command?: string;\n alias?: ResolveConfig[\"alias\"];\n}\n\ninterface ConfigCacheResult {\n projectJson: Context[\"projectJson\"];\n packageJson: Context[\"packageJson\"];\n checksum: string;\n resolver: Resolver;\n userConfig: ParsedUserConfig;\n}\n\nconst configCache = new WeakMap<ConfigCacheKey, ConfigCacheResult>();\n\ninterface EnvPathCacheKey {\n framework: string;\n workspaceRoot: string;\n}\n\nconst envPathCache = new WeakMap<EnvPathCacheKey, EnvPaths>();\n\nconst agent = new Agent({ keepAliveTimeout: 10000 });\nsetGlobalDispatcher(\n agent.compose(\n interceptors.retry({\n maxRetries: 3,\n minTimeout: 1000,\n maxTimeout: 10000,\n timeoutFactor: 2,\n retryAfter: true\n })\n )\n);\n\nexport class PowerlinesContext<\n TResolvedConfig extends ResolvedConfig = ResolvedConfig\n> implements Context<TResolvedConfig> {\n /**\n * Internal references storage\n *\n * @danger\n * This field is for internal use only and should not be accessed or modified directly. It is unstable and can be changed at anytime.\n *\n * @internal\n */\n #internal = {} as UNSAFE_ContextInternal<TResolvedConfig>;\n\n #workspaceConfig: WorkspaceConfig;\n\n #checksum: string | null = null;\n\n #buildId: string = uuid();\n\n #releaseId: string = uuid();\n\n #timestamp: number = Date.now();\n\n #fs!: VirtualFileSystemInterface;\n\n #tsconfig!: ParsedTypeScriptConfig;\n\n #parserCache!: FlatCache;\n\n #requestCache!: FlatCache;\n\n #getConfigProps(config: Partial<TResolvedConfig[\"userConfig\"]> = {}) {\n return mergeConfig(\n {\n root: config.root,\n name: config.name,\n title: config.title,\n organization: config.organization,\n compatibilityDate: resolveCompatibilityDates(\n config.compatibilityDate,\n \"latest\"\n ),\n description: config.description,\n configFile: config.configFile,\n projectType: config.projectType,\n customLogger: config.customLogger,\n logLevel: config.logLevel,\n tsconfig: config.tsconfig,\n tsconfigRaw: config.tsconfigRaw,\n skipCache: config.skipCache,\n autoInstall: config.autoInstall,\n input: config.input,\n output: config.output,\n plugins: config.plugins,\n mode: config.mode,\n resolve: config.resolve,\n framework: config.framework,\n ...config\n },\n {\n output: config.framework\n ? {\n artifactsPath: `.${config.framework ?? \"powerlines\"}`,\n dts: joinPaths(\n config.root ?? this.config.root,\n `${config.framework ?? \"powerlines\"}.d.ts`\n )\n }\n : {}\n }\n );\n }\n\n /**\n * Create a new Storm context from the workspace root and user config.\n *\n * @param workspaceRoot - The root directory of the workspace.\n * @param config - The user configuration options.\n * @returns A promise that resolves to the new context.\n */\n public static async from<\n TResolvedConfig extends ResolvedConfig = ResolvedConfig\n >(\n workspaceRoot: string,\n config: InitialUserConfig<TResolvedConfig[\"userConfig\"]>\n ): Promise<Context> {\n const context = new PowerlinesContext<TResolvedConfig>(\n await loadWorkspaceConfig(workspaceRoot, config.root)\n );\n await context.withUserConfig(config);\n\n const powerlinesPath = await resolvePackage(\"powerlines\");\n if (!powerlinesPath) {\n throw new Error(\"Could not resolve `powerlines` package location.\");\n }\n\n context.powerlinesPath = powerlinesPath;\n\n return context;\n }\n\n /**\n * An object containing the dependencies that should be installed for the project\n */\n public dependencies: Record<string, string | Range> = {};\n\n /**\n * An object containing the development dependencies that should be installed for the project\n */\n public devDependencies: Record<string, string | Range> = {};\n\n /**\n * The persisted meta information about the current build\n */\n public persistedMeta: MetaInfo | undefined = undefined;\n\n /**\n * The path to the Powerlines package\n */\n public powerlinesPath!: string;\n\n /**\n * The parsed `package.json` file for the project\n */\n public packageJson!: PackageJson;\n\n /**\n * The parsed `project.json` file for the project\n */\n public projectJson: Record<string, any> | undefined = undefined;\n\n /**\n * The module resolver for the project\n */\n public resolver!: Resolver;\n\n /**\n * The resolved configuration options\n */\n private resolvePatterns: RegExp[] = [];\n\n /**\n * Internal context fields and methods\n *\n * @danger\n * This field is for internal use only and should not be accessed or modified directly. It is unstable and can be changed at anytime.\n *\n * @internal\n */\n public get $$internal(): UNSAFE_ContextInternal<TResolvedConfig> {\n return this.#internal;\n }\n\n /**\n * Internal context fields and methods\n *\n * @danger\n * This field is for internal use only and should not be accessed or modified directly. It is unstable and can be changed at anytime.\n *\n * @internal\n */\n public set $$internal(value: UNSAFE_ContextInternal<TResolvedConfig>) {\n this.#internal = value;\n }\n\n /**\n * The resolved entry type definitions for the project\n */\n public get entry(): ResolvedEntryTypeDefinition[] {\n const entry = this.resolvedEntry;\n\n return resolveInputsSync(\n this,\n entry && entry.length > 0\n ? entry\n : Array.isArray(this.config.input) ||\n (isSetObject(this.config.input) &&\n !isTypeDefinition(this.config.input))\n ? this.config.input\n : toArray(this.config.input).flat()\n );\n }\n\n /**\n * The TypeScript configuration parsed from the tsconfig file\n */\n public get tsconfig(): ParsedTypeScriptConfig {\n if (!this.#tsconfig) {\n this.tsconfig = {\n tsconfigFilePath: this.config.tsconfig\n } as ParsedTypeScriptConfig;\n }\n\n return this.#tsconfig;\n }\n\n /**\n * Sets the TypeScript configuration parsed from the tsconfig file\n */\n public set tsconfig(value: ParsedTypeScriptConfig) {\n this.#tsconfig = value;\n this.resolvePatterns = tsconfigPathsToRegExp(value?.options?.paths ?? {});\n }\n\n /**\n * The virtual file system interface for the project\n */\n public get fs(): VirtualFileSystemInterface {\n if (!this.#fs) {\n this.#fs = VirtualFileSystem.createSync(this);\n }\n\n return this.#fs;\n }\n\n /**\n * Get the checksum of the project's current state\n */\n public get checksum(): string | null {\n return this.#checksum;\n }\n\n /**\n * The meta information about the current build\n */\n public get meta() {\n return {\n buildId: this.#buildId,\n releaseId: this.#releaseId,\n checksum: this.#checksum,\n timestamp: this.#timestamp,\n rootHash: murmurhash(\n {\n workspaceRoot: this.workspaceConfig?.workspaceRoot,\n root: this.config?.root\n },\n {\n maxLength: ROOT_HASH_LENGTH\n }\n ),\n configHash: murmurhash(this.config, {\n maxLength: CACHE_HASH_LENGTH\n })\n } as MetaInfo;\n }\n\n /**\n * The resolved configuration options\n */\n public get config(): TResolvedConfig {\n return this.resolvedConfig ?? {};\n }\n\n /**\n * The logger function\n */\n public get log(): LogFn {\n if (!this.logFn) {\n this.logFn = this.createLog();\n }\n\n return this.logFn;\n }\n\n /**\n * The workspace configuration\n */\n public get workspaceConfig(): WorkspaceConfig {\n return this.#workspaceConfig;\n }\n\n /**\n * The environment paths for the project\n */\n public get envPaths(): EnvPaths {\n if (\n envPathCache.has({\n workspaceRoot: this.workspaceConfig.workspaceRoot,\n framework: this.config?.framework || \"powerlines\"\n })\n ) {\n return envPathCache.get({\n workspaceRoot: this.workspaceConfig.workspaceRoot,\n framework: this.config?.framework || \"powerlines\"\n })!;\n }\n\n const envPaths = getEnvPaths({\n orgId: \"storm-software\",\n appId: this.config?.framework || \"powerlines\",\n workspaceRoot: this.workspaceConfig.workspaceRoot\n });\n envPathCache.set(\n {\n workspaceRoot: this.workspaceConfig.workspaceRoot,\n framework: this.config?.framework || \"powerlines\"\n },\n envPaths\n );\n\n return envPaths;\n }\n\n /**\n * Get the path to the artifacts directory for the project\n */\n public get artifactsPath(): string {\n return joinPaths(\n this.workspaceConfig.workspaceRoot,\n this.config.root,\n this.config.output.artifactsPath\n );\n }\n\n /**\n * Get the path to the builtin modules used by the project\n */\n public get builtinsPath(): string {\n return joinPaths(this.artifactsPath, \"builtins\");\n }\n\n /**\n * Get the path to the entry directory for the project\n */\n public get entryPath(): string {\n return joinPaths(this.artifactsPath, \"entry\");\n }\n\n /**\n * Get the path to the infrastructure modules used by the project\n */\n public get infrastructurePath(): string {\n return joinPaths(this.artifactsPath, \"infrastructure\");\n }\n\n /**\n * Get the path to the data directory for the project\n */\n public get dataPath(): string {\n return joinPaths(\n this.envPaths.data,\n \"projects\",\n getPrefixedRootHash(this.config.name, this.meta.rootHash)\n );\n }\n\n /**\n * Get the path to the cache directory for the project\n */\n public get cachePath(): string {\n return joinPaths(\n this.envPaths.cache,\n \"projects\",\n murmurhash(\n {\n checksum: this.#checksum,\n config: this.meta.configHash\n },\n {\n maxLength: CACHE_HASH_LENGTH\n }\n )\n );\n }\n\n /**\n * Get the path to the generated declaration file for the project\n */\n public get dtsPath(): string {\n return this.config.output.dts\n ? appendPath(this.config.output.dts, this.workspaceConfig.workspaceRoot)\n : joinPaths(\n this.workspaceConfig.workspaceRoot,\n this.config.root,\n \"powerlines.d.ts\"\n );\n }\n\n /**\n * Get the project root relative to the workspace root\n */\n public get relativeToWorkspaceRoot() {\n return relativeToWorkspaceRoot(this.config.root);\n }\n\n /**\n * The builtin module id that exist in the Powerlines virtual file system\n */\n public get builtins(): string[] {\n return Object.values(this.fs.metadata)\n .filter(meta => meta && meta.type === \"builtin\")\n .map(meta => meta?.id)\n .filter(Boolean);\n }\n\n /**\n * The alias mappings for the project used during module resolution\n *\n * @remarks\n * This includes both the built-in module aliases as well as any custom aliases defined in the build configuration.\n */\n public get alias(): Record<string, string> {\n return this.builtins.reduce(\n (ret, id) => {\n const moduleId = `${\n this.config?.framework || \"powerlines\"\n }:${id.replace(/^.*?:/, \"\")}`;\n if (!ret[moduleId]) {\n const path = this.fs.paths[id];\n if (path) {\n ret[moduleId] = path;\n }\n }\n\n return ret;\n },\n this.config.resolve.alias\n ? Array.isArray(this.config.resolve.alias)\n ? this.config.resolve.alias.reduce(\n (ret, alias) => {\n if (!ret[alias.find.toString()]) {\n ret[alias.find.toString()] = alias.replacement;\n }\n\n return ret;\n },\n {} as Record<string, string>\n )\n : this.config.resolve.alias\n : {}\n );\n }\n\n /**\n * Gets the parser cache.\n */\n protected get parserCache(): FlatCache {\n if (!this.#parserCache) {\n this.#parserCache = create({\n cacheId: \"parser\",\n cacheDir: this.cachePath,\n ttl: 2 * 60 * 60 * 1000,\n lruSize: 5000,\n persistInterval: 250\n });\n }\n\n return this.#parserCache;\n }\n\n /**\n * Gets the request cache.\n */\n protected get requestCache(): FlatCache {\n if (!this.#requestCache) {\n this.#requestCache = create({\n cacheId: \"http\",\n cacheDir: this.cachePath,\n ttl: 6 * 60 * 60 * 1000,\n lruSize: 5000,\n persistInterval: 250\n });\n }\n\n return this.#requestCache;\n }\n\n /**\n * The entry points that exist in the Powerlines virtual file system\n */\n protected get resolvedEntry(): ResolvedEntryTypeDefinition[] {\n return Object.entries(this.fs.metadata)\n .filter(([, meta]) => meta && meta.type === \"entry\")\n .map(([path, meta]) => {\n const typeDefinition = {\n file: path\n } as ResolvedEntryTypeDefinition;\n\n if (meta.properties) {\n if (isSetString(meta.properties.file)) {\n typeDefinition.file = meta.properties.file;\n }\n if (isSetString(meta.properties.name)) {\n typeDefinition.name = meta.properties.name;\n }\n if (\n isSetString(meta.properties[\"input.file\"]) ||\n isSetString(meta.properties[\"input.name\"])\n ) {\n typeDefinition.input ??= {} as TypeDefinition;\n if (isSetString(meta.properties[\"input.file\"])) {\n typeDefinition.input.file = meta.properties[\"input.file\"];\n }\n if (isSetString(meta.properties[\"input.name\"])) {\n typeDefinition.input.name = meta.properties[\"input.name\"];\n }\n }\n if (isSetString(meta.properties.output)) {\n typeDefinition.output = meta.properties.output;\n }\n }\n\n return typeDefinition;\n })\n .filter(Boolean);\n }\n\n /**\n * A function to perform HTTP fetch requests\n *\n * @remarks\n * This function uses a caching layer to avoid duplicate requests during the Powerlines process.\n *\n * @example\n * ```ts\n * const response = await context.fetch(\"https://api.example.com/data\");\n * const data = await response.json();\n * ```\n *\n * @see https://github.com/nodejs/undici\n *\n * @param input - The URL to fetch.\n * @param options - The fetch request options.\n * @returns A promise that resolves to a response returned by the fetch.\n */\n public async fetch(\n input: RequestInfo,\n options: FetchOptions = {}\n ): Promise<Response> {\n const cacheKey = murmurhash({\n input: input.toString(),\n options: JSON.stringify(options)\n });\n\n if (!this.config.skipCache && !options.skipCache) {\n const cached = this.requestCache.get<\n {\n body: BodyInit;\n } & Pick<Response, \"status\" | \"statusText\" | \"headers\">\n >(cacheKey);\n if (cached) {\n return new Response(cached.body, {\n status: cached.status,\n statusText: cached.statusText,\n headers: cached.headers\n });\n }\n }\n\n const response = await fetchRequest(input, { timeout: 12_000, ...options });\n const result = {\n body: await response.text(),\n status: response.status,\n statusText: response.statusText,\n headers: Object.fromEntries(response.headers.entries())\n };\n\n if (!this.config.skipCache && !options.skipCache) {\n try {\n this.requestCache.set(cacheKey, result);\n } catch {\n // Do nothing\n }\n }\n\n return new Response(result.body, {\n status: result.status,\n statusText: result.statusText,\n headers: result.headers\n });\n }\n\n /**\n * Parse code using [Oxc-Parser](https://github.com/oxc/oxc) into an (ESTree-compatible)[https://github.com/estree/estree] AST object.\n *\n * @remarks\n * This function can be used to parse TypeScript code into an AST for further analysis or transformation.\n *\n * @example\n * ```ts\n * const ast = context.parse(\"const x: number = 42;\");\n * ```\n *\n * @see https://rollupjs.org/plugin-development/#this-parse\n * @see https://github.com/oxc/oxc\n *\n * @param code - The source code to parse.\n * @param options - The options to pass to the parser.\n * @returns An (ESTree-compatible)[https://github.com/estree/estree] AST object.\n */\n public async parse(code: string, options: ParseOptions = {}) {\n const cacheKey = murmurhash({\n code,\n options\n });\n\n let result!: ParseResult;\n if (!this.config.skipCache) {\n result = this.parserCache.get<ParseResult>(cacheKey);\n if (result) {\n return result;\n }\n }\n\n result = await parse(`source.${options.lang || \"ts\"}`, code, {\n ...options,\n sourceType: \"module\",\n showSemanticErrors: this.config.mode === \"development\"\n });\n\n if (!this.config.skipCache) {\n this.parserCache.set(cacheKey, result);\n }\n\n return result;\n }\n\n /**\n * A helper function to resolve modules in the Virtual File System\n *\n * @remarks\n * This function can be used to resolve modules relative to the project root directory.\n *\n * @example\n * ```ts\n * const resolved = await context.resolve(\"some-module\", \"/path/to/importer\");\n * ```\n *\n * @param id - The module to resolve.\n * @param importer - An optional path to the importer module.\n * @param options - Additional resolution options.\n * @returns A promise that resolves to the resolved module path.\n */\n public async resolve(\n id: string,\n importer?: string,\n options: ResolveOptions = {}\n ): Promise<ResolveResult | undefined> {\n let moduleId = id;\n if (this.config.resolve.alias) {\n if (Array.isArray(this.config.resolve.alias)) {\n const alias = this.config.resolve.alias.find(a =>\n match(moduleId, [a.find])\n );\n if (alias) {\n moduleId = alias.replacement;\n }\n } else if (\n isSetObject(this.config.resolve.alias) &&\n this.config.resolve.alias[id]\n ) {\n moduleId = this.config.resolve.alias[id];\n }\n }\n\n if (\n this.fs.isVirtual(moduleId) ||\n (importer && this.fs.isVirtual(importer))\n ) {\n let resolvedImporter = importer;\n if (importer && this.fs.isVirtual(importer)) {\n resolvedImporter = await this.fs.resolve(importer, undefined, {\n conditions: this.config.resolve.conditions,\n extensions: this.config.resolve.extensions,\n ...options\n });\n }\n\n const result = await this.fs.resolve(moduleId, resolvedImporter, {\n conditions: this.config.resolve.conditions,\n extensions: this.config.resolve.extensions,\n ...options\n });\n if (!result) {\n return undefined;\n }\n\n const external =\n !match(moduleId, this.config.resolve.noExternal) &&\n (match(moduleId, this.config.resolve.external) ||\n moduleId.startsWith(\"node:\") ||\n (this.fs.isVirtual(moduleId) &&\n this.config.projectType !== \"application\") ||\n (this.config.resolve.skipNodeModulesBundle &&\n !/^[A-Z]:[/\\\\]|^\\.{0,2}\\/|^\\.{1,2}$/.test(moduleId)));\n\n return {\n id: result,\n external,\n virtual: !external\n };\n }\n\n if (this.config.resolve.skipNodeModulesBundle) {\n if (\n match(moduleId, this.resolvePatterns) ||\n match(moduleId, this.config.resolve.noExternal)\n ) {\n return undefined;\n }\n\n if (\n match(moduleId, this.config.resolve.external) ||\n moduleId.startsWith(\"node:\")\n ) {\n return { id: moduleId, external: true, virtual: false };\n }\n\n // Exclude any other import that looks like a Node module\n if (!/^[A-Z]:[/\\\\]|^\\.{0,2}\\/|^\\.{1,2}$/.test(moduleId)) {\n return {\n id: moduleId,\n external: true,\n virtual: false\n };\n }\n } else {\n if (match(moduleId, this.config.resolve.noExternal)) {\n return undefined;\n }\n\n if (\n match(moduleId, this.config.resolve.external) ||\n moduleId.startsWith(\"node:\")\n ) {\n return { id: moduleId, external: true, virtual: false };\n }\n }\n\n return undefined;\n }\n\n /**\n * A helper function to load modules from the Virtual File System\n *\n * @remarks\n * This function can be used to load modules relative to the project root directory.\n *\n * @example\n * ```ts\n * const module = await context.load(\"some-module\", \"/path/to/importer\");\n * ```\n *\n * @param id - The module to load.\n * @returns A promise that resolves to the loaded module.\n */\n public async load(id: string): Promise<TransformResult | undefined> {\n const resolvedId = await this.fs.resolve(id);\n if (!resolvedId) {\n return undefined;\n }\n\n const code = await this.fs.read(resolvedId);\n if (!code) {\n return undefined;\n }\n\n return { code, map: null };\n }\n\n /**\n * Get the builtin virtual files that exist in the Powerlines virtual file system\n */\n public async getBuiltins() {\n return Promise.all(\n Object.entries(this.fs.metadata)\n .filter(([, meta]) => meta && meta.type === \"builtin\")\n .map(async ([id, meta]) => {\n const code = await this.fs.read(id);\n const path = this.fs.paths[id];\n\n return { ...meta, path, code } as VirtualFile;\n })\n );\n }\n\n /**\n * Resolves a file and writes it to the VFS if it does not already exist\n *\n * @param code - The source code of the file\n * @param path - The path to write the file to\n * @param options - Additional options for writing the file\n */\n public async emit(\n code: string,\n path: string,\n options: EmitOptions = {}\n ): Promise<void> {\n const filePath = options.extension\n ? findFileExtensionSafe(path)\n ? options.extension.startsWith(\".\")\n ? path.replace(findFileDotExtensionSafe(path), options.extension)\n : path.replace(findFileExtensionSafe(path), options.extension)\n : options.extension.startsWith(\".\")\n ? `${path}${options.extension}`\n : `${path}.${options.extension}`\n : findFileExtensionSafe(path)\n ? path\n : `${path}.ts`;\n\n if (\n isFunction((this as unknown as UnpluginBuildContext).emitFile) &&\n options.emitWithBundler\n ) {\n return (this as unknown as UnpluginBuildContext).emitFile({\n needsCodeReference: options.needsCodeReference,\n originalFileName: options.originalFileName,\n fileName: filePath,\n source: code,\n type: \"asset\"\n });\n }\n\n return this.fs.write(filePath, code, options);\n }\n\n /**\n * Synchronously resolves a file and writes it to the VFS if it does not already exist\n *\n * @param code - The source code of the file\n * @param path - The path to write the file to\n * @param options - Additional options for writing the file\n */\n public emitSync(code: string, path: string, options: EmitOptions = {}) {\n const filePath = options.extension\n ? findFileExtensionSafe(path)\n ? options.extension.startsWith(\".\")\n ? path.replace(findFileDotExtensionSafe(path), options.extension)\n : path.replace(findFileExtensionSafe(path), options.extension)\n : options.extension.startsWith(\".\")\n ? `${path}${options.extension}`\n : `${path}.${options.extension}`\n : findFileExtensionSafe(path)\n ? path\n : `${path}.ts`;\n\n if (\n isFunction((this as unknown as UnpluginBuildContext).emitFile) &&\n options.emitWithBundler\n ) {\n return (this as unknown as UnpluginBuildContext).emitFile({\n needsCodeReference: options.needsCodeReference,\n originalFileName: options.originalFileName,\n fileName: filePath,\n source: code,\n type: \"asset\"\n });\n }\n\n return this.fs.writeSync(filePath, code, options);\n }\n\n /**\n * Resolves a entry virtual file and writes it to the VFS if it does not already exist\n *\n * @param code - The source code of the entry file\n * @param path - A path to write the entry file to\n * @param options - Optional write file options\n */\n public async emitEntry(\n code: string,\n path: string,\n options: EmitEntryOptions = {}\n ): Promise<void> {\n return this.emit(\n code,\n appendPath(path, this.entryPath),\n defu(\n {\n meta: {\n type: \"entry\",\n properties: {\n file: appendPath(path, this.entryPath),\n name: options?.name,\n output: options?.output,\n \"input.file\": options?.input?.file,\n \"input.name\": options?.input?.name\n }\n }\n },\n omit(options, [\"name\"])\n )\n );\n }\n\n /**\n * Synchronously resolves a entry virtual file and writes it to the VFS if it does not already exist\n *\n * @param code - The source code of the entry file\n * @param path - A path to write the entry file to\n * @param options - Optional write file options\n */\n public emitEntrySync(\n code: string,\n path: string,\n options: EmitEntryOptions = {}\n ): void {\n return this.emitSync(\n code,\n appendPath(path, this.entryPath),\n defu(\n {\n meta: {\n type: \"entry\",\n properties: {\n file: appendPath(path, this.entryPath),\n name: options?.name,\n output: options?.output,\n \"input.file\": options?.input?.file,\n \"input.name\": options?.input?.name\n }\n }\n },\n omit(options, [\"name\"])\n )\n );\n }\n\n /**\n * Resolves a builtin virtual file and writes it to the VFS if it does not already exist\n *\n * @param code - The source code of the builtin file\n * @param id - The unique identifier of the builtin file\n * @param options - Optional write file options\n */\n public async emitBuiltin(\n code: string,\n id: string,\n options: EmitOptions = {}\n ): Promise<void> {\n if (!this.builtinsPath) {\n throw new Error(\n `The builtins path is not set. Cannot emit builtin file with id \"${id}\".`\n );\n }\n\n if (!isSetString(id)) {\n throw new Error(\n `The builtin id must be a non-empty string. Received: ${String(id)}`\n );\n }\n\n return this.emit(\n code,\n appendPath(id, this.builtinsPath),\n defu(options, { meta: { type: \"builtin\", id } })\n );\n }\n\n /**\n * Synchronously resolves a builtin virtual file and writes it to the VFS if it does not already exist\n *\n * @param code - The source code of the builtin file\n * @param id - The unique identifier of the builtin file\n * @param options - Optional write file options\n */\n public emitBuiltinSync(code: string, id: string, options: EmitOptions = {}) {\n if (!this.builtinsPath) {\n throw new Error(\n `The builtins path is not set. Cannot emit builtin file with id \"${id}\".`\n );\n }\n\n if (!isSetString(id)) {\n throw new Error(\n `The builtin id must be a non-empty string. Received: ${String(id)}`\n );\n }\n\n return this.emitSync(\n code,\n appendPath(id, this.builtinsPath),\n defu(options, { meta: { type: \"builtin\", id } })\n );\n }\n\n /**\n * Resolves a builtin virtual file and writes it to the VFS if it does not already exist\n *\n * @param code - The source code of the builtin file\n * @param id - The unique identifier of the builtin file\n * @param options - Optional write file options\n */\n public async emitInfrastructure(\n code: string,\n id: string,\n options: EmitOptions = {}\n ): Promise<void> {\n if (!this.infrastructurePath) {\n throw new Error(\n `The infrastructure path is not set. Cannot emit infrastructure file with id \"${id}\".`\n );\n }\n\n if (!isSetString(id)) {\n throw new Error(\n `The infrastructure id must be a non-empty string. Received: ${String(id)}`\n );\n }\n\n return this.emit(\n code,\n appendPath(id, this.infrastructurePath),\n defu(options, { meta: { type: \"infrastructure\", id } })\n );\n }\n\n /**\n * Synchronously resolves an infrastructure virtual file and writes it to the VFS if it does not already exist\n *\n * @param code - The source code of the infrastructure file\n * @param id - The unique identifier of the infrastructure file\n * @param options - Optional write file options\n */\n public emitInfrastructureSync(\n code: string,\n id: string,\n options: EmitOptions = {}\n ) {\n if (!this.infrastructurePath) {\n throw new Error(\n `The infrastructure path is not set. Cannot emit infrastructure file with id \"${id}\".`\n );\n }\n\n if (!isSetString(id)) {\n throw new Error(\n `The infrastructure id must be a non-empty string. Received: ${String(id)}`\n );\n }\n\n return this.emitSync(\n code,\n appendPath(id, this.infrastructurePath),\n defu(options, { meta: { type: \"infrastructure\", id } })\n );\n }\n\n /**\n * Update the context using a new user configuration options\n *\n * @param userConfig - The new user configuration options.\n */\n public async withUserConfig(\n userConfig: InitialUserConfig<TResolvedConfig[\"userConfig\"]>,\n options: InitContextOptions = {\n isHighPriority: true\n }\n ) {\n this.mergeUserConfig(userConfig as Partial<TResolvedConfig[\"userConfig\"]>);\n\n await this.init(this.config.userConfig, options);\n }\n\n /**\n * Update the context using a new inline configuration options\n *\n * @param inlineConfig - The new inline configuration options.\n */\n public async withInlineConfig(\n inlineConfig: TResolvedConfig[\"inlineConfig\"],\n options: InitContextOptions = {\n isHighPriority: true\n }\n ) {\n this.config.inlineConfig = inlineConfig;\n\n if (inlineConfig.command === \"new\") {\n const workspacePackageJsonPath = joinPaths(\n this.workspaceConfig.workspaceRoot,\n \"package.json\"\n );\n if (!existsSync(workspacePackageJsonPath)) {\n throw new Error(\n `The workspace package.json file could not be found at ${workspacePackageJsonPath}`\n );\n }\n\n this.packageJson = await readJsonFile<PackageJson>(\n workspacePackageJsonPath\n );\n\n this.workspaceConfig.repository ??= isSetString(\n this.packageJson?.repository\n )\n ? this.packageJson.repository\n : this.packageJson?.repository?.url;\n }\n\n await this.init(this.config.inlineConfig, options);\n }\n\n /**\n * A logging function for fatal messages\n *\n * @param message - The message to log.\n */\n public fatal(message: string | UnpluginMessage) {\n this.log(\n LogLevelLabel.FATAL,\n isString(message) ? message : StormJSON.stringify(message)\n );\n }\n\n /**\n * A logging function for error messages\n *\n * @param message - The message to log.\n */\n public error(message: string | UnpluginMessage) {\n this.log(\n LogLevelLabel.ERROR,\n isString(message) ? message : StormJSON.stringify(message)\n );\n }\n\n /**\n * A logging function for warning messages\n *\n * @param message - The message to log.\n */\n public warn(message: string | UnpluginMessage) {\n this.log(\n LogLevelLabel.WARN,\n isString(message) ? message : StormJSON.stringify(message)\n );\n }\n\n /**\n * A logging function for informational messages\n *\n * @param message - The message to log.\n */\n public info(message: string | UnpluginMessage) {\n this.log(\n LogLevelLabel.INFO,\n isString(message) ? message : StormJSON.stringify(message)\n );\n }\n\n /**\n * A logging function for debug messages\n *\n * @param message - The message to log.\n */\n public debug(message: string | UnpluginMessage) {\n this.log(\n LogLevelLabel.DEBUG,\n isString(message) ? message : StormJSON.stringify(message)\n );\n }\n\n /**\n * A logging function for trace messages\n *\n * @param message - The message to log.\n */\n public trace(message: string | UnpluginMessage) {\n this.log(\n LogLevelLabel.TRACE,\n isString(message) ? message : StormJSON.stringify(message)\n );\n }\n\n /**\n * Create a new logger instance\n *\n * @param name - The name to use for the logger instance\n * @returns A logger function\n */\n public createLog(name: string | null = null): LogFn {\n return createLog(name, {\n ...this.config,\n logLevel: isNull(this.config.logLevel) ? \"silent\" : this.config.logLevel\n });\n }\n\n /**\n * Extend the current logger instance with a new name\n *\n * @param name - The name to use for the extended logger instance\n * @returns A logger function\n */\n public extendLog(name: string): LogFn {\n return extendLog(this.log, name);\n }\n\n /**\n * Generates a checksum representing the current context state\n *\n * @param root - The root directory of the project to generate the checksum for\n * @returns A promise that resolves to a string representing the checksum\n */\n public async generateChecksum(root = this.config.root): Promise<string> {\n this.#checksum = await hashDirectory(root, {\n ignore: [\"node_modules\", \".git\", \".nx\", \".cache\", \"tmp\", \"dist\"]\n });\n\n return this.#checksum;\n }\n\n /**\n * Creates a new StormContext instance.\n *\n * @param workspaceConfig - The workspace configuration.\n */\n protected constructor(workspaceConfig: WorkspaceConfig) {\n this.#workspaceConfig = workspaceConfig;\n\n envPathCache.set(\n {\n workspaceRoot: workspaceConfig.workspaceRoot,\n framework: \"powerlines\"\n },\n getEnvPaths({\n orgId:\n (isSetObject(workspaceConfig.organization)\n ? workspaceConfig.organization.name\n : workspaceConfig.organization) || \"storm-software\",\n appId: \"powerlines\",\n workspaceRoot: workspaceConfig.workspaceRoot\n })\n );\n }\n\n /**\n * The resolved configuration for this context\n */\n protected resolvedConfig: TResolvedConfig = {} as TResolvedConfig;\n\n /**\n * A logger function specific to this context\n */\n protected logFn!: LogFn;\n\n /**\n * Initialize the context with the provided configuration options\n *\n * @param config - The partial user configuration to use for initialization.\n */\n protected async init(\n config: Partial<TResolvedConfig[\"userConfig\"]> = {},\n options: InitContextOptions = {\n isHighPriority: true\n }\n ) {\n const cacheKey: ConfigCacheKey = {\n root:\n config.root ??\n this.config.root ??\n this.config.userConfig?.root ??\n this.config.inlineConfig?.root,\n mode: (config.mode ?? this.config.mode) || this.workspaceConfig.mode,\n skipCache: config.skipCache ?? this.config.skipCache ?? false,\n configFile: config.configFile ?? this.config.configFile,\n framework: config.framework ?? this.config.framework ?? \"powerlines\",\n command: this.config.inlineConfig?.command,\n alias: this.config.resolve?.alias ?? config.resolve?.alias\n };\n\n if (configCache.has(cacheKey)) {\n const result = configCache.get(cacheKey)!;\n\n this.projectJson = result.projectJson;\n this.packageJson = result.packageJson;\n this.#checksum = result.checksum;\n this.resolver = result.resolver;\n\n this.mergeUserConfig(result.userConfig.config, this.config.userConfig);\n } else {\n const projectJsonPath = joinPaths(cacheKey.root, \"project.json\");\n if (existsSync(projectJsonPath)) {\n this.projectJson = await readJsonFile(projectJsonPath);\n }\n\n const packageJsonPath = joinPaths(cacheKey.root, \"package.json\");\n if (existsSync(packageJsonPath)) {\n this.packageJson = await readJsonFile<PackageJson>(packageJsonPath);\n }\n\n this.#checksum = await this.generateChecksum(cacheKey.root);\n this.resolver = createResolver({\n workspaceRoot: this.workspaceConfig.workspaceRoot,\n root: cacheKey.root,\n cacheDir: this.cachePath,\n mode: cacheKey.mode,\n logLevel: (config.logLevel ||\n this.config.logLevel ||\n this.workspaceConfig.logLevel ||\n \"info\") as CreateResolverOptions[\"logLevel\"],\n skipCache: cacheKey.skipCache,\n alias: this.config.resolve?.alias\n ? Array.isArray(this.config.resolve.alias)\n ? this.config.resolve.alias.reduce(\n (ret, alias) => {\n ret[alias.find.toString()] = alias.replacement;\n return ret;\n },\n {} as Record<string, string>\n )\n : this.config.resolve.alias\n : {}\n });\n\n const userConfig = await loadUserConfigFile(\n cacheKey.root,\n this.workspaceConfig.workspaceRoot,\n this.resolver,\n cacheKey.command as PowerlinesCommand | undefined,\n cacheKey.mode,\n cacheKey.configFile,\n cacheKey.framework\n );\n this.mergeUserConfig(userConfig.config);\n\n configCache.set(cacheKey, {\n projectJson: this.projectJson,\n packageJson: this.packageJson,\n checksum: this.#checksum,\n resolver: this.resolver,\n userConfig\n });\n }\n\n config.tsconfig ??= getTsconfigFilePath(\n this.workspaceConfig.workspaceRoot,\n cacheKey.root,\n config.tsconfig\n );\n\n if (isSetObject(config)) {\n this.resolvedConfig = mergeConfig(\n {\n inlineConfig: this.config.inlineConfig,\n userConfig: this.config.userConfig\n },\n options.isHighPriority ? this.#getConfigProps(config) : {},\n {\n ...this.#getConfigProps(this.config.inlineConfig),\n command: this.config.inlineConfig?.command\n },\n this.#getConfigProps(this.config.userConfig),\n {\n mode: this.workspaceConfig?.mode,\n logLevel: this.workspaceConfig?.logLevel,\n skipCache: this.workspaceConfig?.skipCache\n },\n {\n name: this.projectJson?.name || this.packageJson?.name,\n version: this.packageJson?.version,\n description: this.packageJson?.description,\n output: mergeConfig(config.output ?? {}, {\n outputPath: cacheKey.root\n ? joinPaths(\n this.workspaceConfig?.directories?.build || \"dist\",\n cacheKey.root\n )\n : this.workspaceConfig?.directories?.build || \"dist\",\n artifactsPath: `.${config.framework ?? \"powerlines\"}`,\n dts: joinPaths(\n cacheKey.root,\n `${config.framework ?? \"powerlines\"}.d.ts`\n ),\n assets: [\n {\n glob: \"LICENSE\"\n },\n {\n input: cacheKey.root,\n glob: \"*.md\"\n },\n {\n input: cacheKey.root,\n glob: \"package.json\"\n }\n ]\n })\n },\n options.isHighPriority ? {} : this.#getConfigProps(config),\n {\n inlineConfig: {},\n userConfig: {},\n framework: \"powerlines\",\n mode: \"production\",\n projectType: \"application\",\n platform: \"neutral\",\n logLevel: \"info\",\n preview: false,\n environments: {},\n resolve: {}\n }\n ) as TResolvedConfig;\n }\n\n this.config.input = getUniqueInputs(this.config.input);\n\n if (\n this.config.name?.startsWith(\"@\") &&\n this.config.name.split(\"/\").filter(Boolean).length > 1\n ) {\n this.config.name = this.config.name.split(\"/\").filter(Boolean)[1]!;\n }\n\n this.config.title ??= titleCase(this.config.name);\n\n this.config.organization ??=\n (isSetObject(this.workspaceConfig.organization)\n ? this.workspaceConfig.organization.name\n : this.workspaceConfig.organization) ||\n (isSetObject(this.packageJson?.author)\n ? this.packageJson?.author?.name\n : this.packageJson?.author) ||\n this.config.name;\n\n if (this.config.userConfig.resolve?.external) {\n this.config.userConfig.resolve.external = getUnique(\n this.config.userConfig.resolve.external\n );\n }\n if (this.config.userConfig.resolve?.noExternal) {\n this.config.userConfig.resolve.noExternal = getUnique(\n this.config.userConfig.resolve.noExternal\n );\n }\n\n if (this.config.resolve.external) {\n this.config.resolve.external = getUnique(this.config.resolve.external);\n }\n if (this.config.resolve.noExternal) {\n this.config.resolve.noExternal = getUnique(\n this.config.resolve.noExternal\n );\n }\n\n this.config.output.format = getUnique(\n toArray(\n this.config.output?.format ??\n (this.config.projectType === \"library\" ? [\"cjs\", \"esm\"] : [\"esm\"])\n )\n );\n\n if (\n this.config.root &&\n this.config.root !== \".\" &&\n this.config.root !== \"./\" &&\n this.config.root !== this.workspaceConfig.workspaceRoot\n ) {\n this.config.output.outputPath ??= joinPaths(\"dist\", this.config.root);\n this.config.output.buildPath ??= joinPaths(this.config.root, \"dist\");\n } else {\n this.config.output.outputPath ??= \"dist\";\n this.config.output.buildPath ??= \"dist\";\n }\n\n this.config.output.assets = getUniqueBy(\n this.config.output.assets.map(asset => {\n return {\n glob: isSetObject(asset) ? asset.glob : asset,\n input:\n isString(asset) ||\n !asset.input ||\n asset.input === \".\" ||\n asset.input === \"/\" ||\n asset.input === \"./\"\n ? this.workspaceConfig.workspaceRoot\n : isParentPath(asset.input, this.workspaceConfig.workspaceRoot) ||\n asset.input === this.workspaceConfig.workspaceRoot\n ? asset.input\n : appendPath(asset.input, this.workspaceConfig.workspaceRoot),\n output:\n isSetObject(asset) && asset.output\n ? isParentPath(asset.output, this.workspaceConfig.workspaceRoot)\n ? asset.output\n : appendPath(\n joinPaths(\n this.config.output.outputPath,\n replacePath(\n replacePath(\n asset.output,\n replacePath(\n this.config.output.outputPath,\n this.workspaceConfig.workspaceRoot\n )\n ),\n this.config.output.outputPath\n )\n ),\n this.workspaceConfig.workspaceRoot\n )\n : appendPath(\n this.config.output.outputPath,\n this.workspaceConfig.workspaceRoot\n ),\n ignore:\n isSetObject(asset) && asset.ignore\n ? toArray(asset.ignore)\n : undefined\n };\n }),\n (a: ResolvedAssetGlob) => `${a.input}-${a.glob}-${a.output}`\n );\n\n this.config.plugins = (this.config.plugins ?? [])\n .filter(Boolean)\n .reduce((ret, plugin) => {\n if (\n isPlugin(plugin) &&\n checkDedupe(\n plugin,\n ret.filter(p => isPlugin(p))\n )\n ) {\n return ret;\n }\n\n ret.push(plugin);\n\n return ret;\n }, [] as PluginConfig[]);\n\n // Apply path token replacements\n\n if (this.config.tsconfig) {\n this.config.tsconfig = replacePathTokens(this, this.config.tsconfig);\n }\n\n if (this.config.output.dts) {\n if (isSetString(this.config.output.dts)) {\n this.config.output.dts = replacePathTokens(\n this,\n this.config.output.dts\n );\n } else {\n this.config.output.dts = joinPaths(\n this.config.root,\n `${this.config.framework ?? \"powerlines\"}.d.ts`\n );\n }\n }\n\n if (this.config.output.assets) {\n this.config.output.assets = this.config.output.assets.map(asset => ({\n ...asset,\n glob: replacePathTokens(this, asset.glob),\n ignore: asset.ignore\n ? asset.ignore.map(ignore => replacePathTokens(this, ignore))\n : undefined,\n input: replacePathTokens(this, asset.input),\n output: replacePathTokens(this, asset.output)\n }));\n }\n\n if (\n (isSetString(config.output?.storage) &&\n config.output.storage === \"virtual\") ||\n (isSetObject(config.output?.storage) &&\n Object.values(config.output.storage).every(\n adapter => adapter.preset === \"virtual\"\n ))\n ) {\n this.config.output.overwrite = true;\n }\n\n this.#fs ??= await VirtualFileSystem.create(this);\n }\n\n protected mergeUserConfig(\n from: Partial<TResolvedConfig[\"userConfig\"]> = {},\n into: Partial<TResolvedConfig[\"userConfig\"]> = this.config.userConfig ?? {}\n ) {\n this.config.userConfig = mergeConfig(\n {\n input:\n isSetObject(from.input) &&\n !isRegExp(from.input) &&\n !Array.isArray(from.input) &&\n from.input.file\n ? from.input.file\n : isSetObject(into?.input) &&\n !isRegExp(into.input) &&\n !Array.isArray(into.input) &&\n into.input.file\n ? into.input.file\n : Array.isArray(from.input) && from.input.length > 0\n ? from.input\n : Array.isArray(into?.input) && into.input.length > 0\n ? into.input\n : []\n },\n omit(from ?? {}, [\"input\"]),\n omit(into ?? {}, [\"input\"])\n ) as TResolvedConfig[\"userConfig\"];\n\n if (this.config.userConfig.output?.format) {\n this.config.userConfig.output.format = getUnique(\n toArray(this.config.userConfig.output?.format)\n );\n }\n\n this.config.userConfig.plugins = (this.config.userConfig.plugins ?? [])\n .filter(Boolean)\n .reduce((ret, plugin) => {\n if (\n isPlugin(plugin) &&\n checkDedupe(\n plugin,\n ret.filter(p => isPlugin(p))\n )\n ) {\n return ret;\n }\n\n ret.push(plugin);\n\n return ret;\n }, [] as PluginConfig[]);\n }\n}\n","/* -------------------------------------------------------------------\n\n ⚡ Storm Software - Powerlines\n\n This code was released as part of the Powerlines project. Powerlines\n is maintained by Storm Software under the Apache-2.0 license, and is\n free for commercial and private use. For more information, please visit\n our licensing page at https://stormsoftware.com/licenses/projects/powerlines.\n\n Website: https://stormsoftware.com\n Repository: https://github.com/storm-software/powerlines\n Documentation: https://docs.stormsoftware.com/projects/powerlines\n Contact: https://stormsoftware.com/contact\n\n SPDX-License-Identifier: Apache-2.0\n\n ------------------------------------------------------------------- */\n\n/* -------------------------------------------------------------------\n\n ⚡ Storm Software - Powerlines\n\n This code was released as part of the Powerlines project. Powerlines\n is maintained by Storm Software under the Apache-2.0 license, and is\n free for commercial and private use. For more information, please visit\n our licensing page at https://stormsoftware.com/licenses/projects/powerlines.\n\n Website: https://stormsoftware.com\n Repository: https://github.com/storm-software/powerlines\n Documentation: https://docs.stormsoftware.com/projects/powerlines\n Contact: https://stormsoftware.com/contact\n\n SPDX-License-Identifier: Apache-2.0\n\n ------------------------------------------------------------------- */\n\nimport type {\n API,\n Context,\n UnpluginBuilderVariant,\n UnpluginFactory,\n UnpluginOptions\n} from \"@powerlines/core\";\nimport { createLog } from \"@powerlines/core/lib/logger\";\nimport { getString } from \"@powerlines/core/lib/utilities/source-file\";\nimport { LogLevelLabel } from \"@storm-software/config-tools/types\";\nimport { getWorkspaceRoot } from \"@stryke/fs/get-workspace-root\";\nimport { LoadResult } from \"rolldown\";\nimport type {\n UnpluginOptions as BaseUnpluginOptions,\n TransformResult,\n UnpluginBuildContext,\n UnpluginContext\n} from \"unplugin\";\nimport { setParseImpl } from \"unplugin\";\nimport { PowerlinesAPI } from \"./api\";\n\nexport * from \"@powerlines/core/lib/unplugin\";\n\n/**\n * Creates a Powerlines unplugin factory that generates a plugin instance.\n *\n * @param variant - The build variant for which to create the unplugin.\n * @param decorate - An optional function to decorate the unplugin options.\n * @returns The unplugin factory that generates a plugin instance.\n */\nexport function createUnpluginFactory<\n TContext extends Context,\n TUnpluginBuilderVariant extends UnpluginBuilderVariant =\n UnpluginBuilderVariant\n>(\n variant: TUnpluginBuilderVariant,\n decorate?: (\n api: API<TContext[\"config\"]>,\n plugin: UnpluginOptions<TContext>\n ) => BaseUnpluginOptions\n): UnpluginFactory<TContext> {\n return (config, meta): UnpluginOptions<TContext> => {\n const log = createLog(\"unplugin\", config);\n log(LogLevelLabel.DEBUG, \"Initializing Unplugin\");\n\n try {\n const userConfig = {\n ...config,\n variant,\n unplugin: meta\n } as TContext[\"config\"][\"userConfig\"];\n\n let api!: API<TContext[\"config\"]>;\n\n async function buildStart(this: UnpluginBuildContext): Promise<void> {\n log(LogLevelLabel.DEBUG, \"Powerlines build plugin starting...\");\n\n api = await PowerlinesAPI.from(\n getWorkspaceRoot(process.cwd()),\n userConfig\n );\n setParseImpl(api.context.parse);\n\n log(\n LogLevelLabel.DEBUG,\n \"Preparing build artifacts for the Powerlines project...\"\n );\n\n await api.prepare({\n command: \"build\"\n });\n }\n\n async function resolveId(\n this: UnpluginBuildContext & UnpluginContext,\n id: string,\n importer?: string,\n options: {\n isEntry: boolean;\n } = { isEntry: false }\n ) {\n return api.context.resolve(id, importer, options);\n }\n\n async function load(\n this: UnpluginBuildContext & UnpluginContext,\n id: string\n ): Promise<LoadResult> {\n const environment = await api.context.getEnvironment();\n\n let result = await api.callHook(\n \"load\",\n { environment, order: \"pre\" },\n id\n );\n if (result) {\n return result;\n }\n\n result = await api.callHook(\n \"load\",\n { environment, order: \"normal\" },\n id\n );\n if (result) {\n return result;\n }\n\n result = await environment.load(id);\n if (result) {\n return result;\n }\n\n return api.callHook(\"load\", { environment, order: \"post\" }, id);\n }\n\n async function transform(\n code: string,\n id: string\n ): Promise<TransformResult> {\n return api.callHook(\n \"transform\",\n {\n environment: await api.context.getEnvironment(),\n result: \"merge\",\n asNextParam: previousResult => getString(previousResult)\n },\n getString(code),\n id\n );\n }\n\n async function writeBundle(): Promise<void> {\n log(LogLevelLabel.DEBUG, \"Finalizing Powerlines project output...\");\n\n await api.callHook(\"writeBundle\", {\n environment: await api.context.getEnvironment()\n });\n }\n\n const options = {\n name: \"powerlines\",\n api,\n resolveId: {\n filter: {\n id: {\n include: [/.*/]\n }\n },\n handler: resolveId\n },\n load: {\n filter: {\n id: {\n include: [/.*/, /^storm:/]\n }\n },\n handler: load\n },\n transform,\n buildStart,\n writeBundle\n } as UnpluginOptions<TContext>;\n\n const result = decorate ? decorate(api, options) : options;\n\n log(LogLevelLabel.DEBUG, \"Unplugin initialized successfully.\");\n\n return { api, ...result };\n } catch (error) {\n log(LogLevelLabel.FATAL, (error as Error)?.message);\n\n throw error;\n }\n };\n}\n","/* -------------------------------------------------------------------\n\n ⚡ Storm Software - Powerlines\n\n This code was released as part of the Powerlines project. Powerlines\n is maintained by Storm Software under the Apache-2.0 license, and is\n free for commercial and private use. For more information, please visit\n our licensing page at https://stormsoftware.com/licenses/projects/powerlines.\n\n Website: https://stormsoftware.com\n Repository: https://github.com/storm-software/powerlines\n Documentation: https://docs.stormsoftware.com/projects/powerlines\n Contact: https://stormsoftware.com/contact\n\n SPDX-License-Identifier: Apache-2.0\n\n ------------------------------------------------------------------- */\n\nimport {\n UNSAFE_EnvironmentContext,\n UNSAFE_PluginContext\n} from \"@powerlines/core/types/_internal\";\nimport { LogLevelLabel } from \"@storm-software/config-tools/types\";\nimport { isString } from \"@stryke/type-checks/is-string\";\nimport { UnpluginMessage } from \"unplugin\";\nimport type {\n CallHookOptions,\n EnvironmentContext,\n InferHookParameters,\n InferHookReturnType,\n LogFn,\n Plugin,\n PluginContext,\n ResolvedConfig\n} from \"../types\";\n\n/**\n * Create a Proxy-based PluginContext\n *\n * @param plugin - The plugin instance\n * @param environment - The environment context\n * @returns The proxied plugin context\n */\nexport function createPluginContext<\n TResolvedConfig extends ResolvedConfig = ResolvedConfig\n>(\n plugin: Plugin<PluginContext<TResolvedConfig>>,\n environment: UNSAFE_EnvironmentContext<TResolvedConfig>\n): UNSAFE_PluginContext<TResolvedConfig> {\n const normalizeMessage = (message: string | UnpluginMessage): string => {\n return isString(message) ? message : message.message;\n };\n\n const log: LogFn = environment.extendLog(plugin.name.replaceAll(\":\", \" - \"));\n\n const callHookFn = async <TKey extends string>(\n hook: TKey,\n options: CallHookOptions,\n ...args: InferHookParameters<PluginContext<TResolvedConfig>, TKey>\n ): Promise<\n InferHookReturnType<PluginContext<TResolvedConfig>, TKey> | undefined\n > => {\n return environment.$$internal.api.callHook(\n hook,\n {\n sequential: true,\n result: \"merge\",\n ...options,\n environment\n } as Parameters<typeof environment.$$internal.api.callHook>[1],\n ...args\n );\n };\n\n const meta = {} as Record<string, any>;\n\n return new Proxy({} as UNSAFE_PluginContext<TResolvedConfig>, {\n get(_, prop) {\n if (prop === \"$$internal\") {\n return {\n ...environment.$$internal,\n environment,\n callHook: callHookFn,\n meta\n };\n }\n\n if (prop === \"log\" || prop === \"logger\") {\n return log;\n }\n\n if (prop === \"fatal\") {\n return (message: string | UnpluginMessage) => {\n log(LogLevelLabel.FATAL, normalizeMessage(message));\n };\n }\n\n if (prop === \"error\") {\n return (message: string | UnpluginMessage) => {\n log(LogLevelLabel.ERROR, normalizeMessage(message));\n };\n }\n\n if (prop === \"warn\") {\n return (message: string | UnpluginMessage) => {\n log(LogLevelLabel.WARN, normalizeMessage(message));\n };\n }\n\n if (prop === \"info\") {\n return (message: string | UnpluginMessage) => {\n log(LogLevelLabel.INFO, normalizeMessage(message));\n };\n }\n\n if (prop === \"debug\") {\n return (message: string | UnpluginMessage) => {\n log(LogLevelLabel.DEBUG, normalizeMessage(message));\n };\n }\n\n if (prop === \"trace\") {\n return (message: string | UnpluginMessage) => {\n log(LogLevelLabel.TRACE, normalizeMessage(message));\n };\n }\n\n return environment[prop as keyof EnvironmentContext<TResolvedConfig>];\n },\n set(_, prop, value) {\n if (\n [\n \"$$internal\",\n \"environment\",\n \"config\",\n \"log\",\n \"logger\",\n \"error\",\n \"warn\",\n \"plugins\",\n \"hooks\",\n \"addPlugin\",\n \"selectHooks\"\n ].includes(prop as string)\n ) {\n log(\n LogLevelLabel.WARN,\n `Cannot set read-only property \"${String(prop)}\"`\n );\n\n return false;\n }\n\n environment[prop as keyof EnvironmentContext<TResolvedConfig>] = value;\n return true;\n }\n });\n}\n","/* -------------------------------------------------------------------\n\n ⚡ Storm Software - Powerlines\n\n This code was released as part of the Powerlines project. Powerlines\n is maintained by Storm Software under the Apache-2.0 license, and is\n free for commercial and private use. For more information, please visit\n our licensing page at https://stormsoftware.com/licenses/projects/powerlines.\n\n Website: https://stormsoftware.com\n Repository: https://github.com/storm-software/powerlines\n Documentation: https://docs.stormsoftware.com/projects/powerlines\n Contact: https://stormsoftware.com/contact\n\n SPDX-License-Identifier: Apache-2.0\n\n ------------------------------------------------------------------- */\n\nimport { resolvePackage } from \"@stryke/fs/resolve\";\nimport { isFunction } from \"@stryke/type-checks/is-function\";\nimport { isObject } from \"@stryke/type-checks/is-object\";\nimport { isSetObject } from \"@stryke/type-checks/is-set-object\";\nimport { ArrayValues } from \"@stryke/types/array\";\nimport { AnyFunction } from \"@stryke/types/base\";\nimport { PLUGIN_NON_HOOK_FIELDS } from \"../constants\";\nimport {\n addPluginHook,\n isPlugin,\n isPluginConfig,\n isPluginHook,\n isPluginHookField,\n isUnpluginHookField,\n isUnpluginHookKey\n} from \"../plugin-utils\";\nimport type {\n EnvironmentContext,\n EnvironmentContextPlugin,\n EnvironmentResolvedConfig,\n HookFields,\n HookListOrders,\n HooksList,\n InferHooksListItem,\n Plugin,\n PluginConfig,\n PluginContext,\n PluginHook,\n PluginHookFields,\n PluginHooksListItem,\n ResolvedConfig,\n SelectHookResult,\n SelectHookResultItem,\n SelectHooksOptions,\n UnpluginHookList,\n UnpluginHooksListItem,\n UnpluginOptions,\n WorkspaceConfig\n} from \"../types\";\nimport { isUnpluginBuilderVariant } from \"../unplugin\";\nimport { PowerlinesContext } from \"./context\";\nimport { createPluginContext } from \"./plugin-context\";\n\nexport class PowerlinesEnvironmentContext<\n TResolvedConfig extends ResolvedConfig = ResolvedConfig\n>\n extends PowerlinesContext<TResolvedConfig>\n implements EnvironmentContext<TResolvedConfig>\n{\n /**\n * The hooks registered by plugins in this environment\n */\n #hooks: HooksList<PluginContext<TResolvedConfig>> = {} as HooksList<\n PluginContext<TResolvedConfig>\n >;\n\n /**\n * Create a new Storm context from the workspace root and user config.\n *\n * @param workspaceConfig - The root directory of the workspace.\n * @param config - The user configuration options.\n * @returns A promise that resolves to the new context.\n */\n public static async fromConfig<\n TResolvedConfig extends ResolvedConfig = ResolvedConfig\n >(\n workspaceConfig: WorkspaceConfig,\n config: TResolvedConfig\n ): Promise<PowerlinesEnvironmentContext<TResolvedConfig>> {\n const context = new PowerlinesEnvironmentContext<TResolvedConfig>(\n config,\n workspaceConfig\n );\n await context.init();\n\n const powerlinesPath = await resolvePackage(\"powerlines\");\n if (!powerlinesPath) {\n throw new Error(\"Could not resolve `powerlines` package location.\");\n }\n\n context.powerlinesPath = powerlinesPath;\n\n return context;\n }\n\n /**\n * The resolved environment configuration\n */\n public environment!: EnvironmentResolvedConfig;\n\n /**\n * The list of plugins applied to this environment\n */\n public plugins: EnvironmentContextPlugin<TResolvedConfig>[] = [];\n\n /**\n * The resolved configuration options\n */\n public override get config(): TResolvedConfig {\n return super.config;\n }\n\n public get hooks(): HooksList<PluginContext<TResolvedConfig>> {\n return this.#hooks;\n }\n\n public async addPlugin(plugin: Plugin<PluginContext<TResolvedConfig>>) {\n let resolvedPlugin = plugin;\n if (isFunction(plugin.applyToEnvironment)) {\n const result = (await Promise.resolve(\n plugin.applyToEnvironment(this.environment) as Promise<any>\n )) as boolean | PluginConfig<PluginContext<TResolvedConfig>>;\n\n if (!result || (isObject(result) && Object.keys(result).length === 0)) {\n return;\n }\n\n if (isPluginConfig<PluginContext<TResolvedConfig>>(result)) {\n return this.$$internal.addPlugin(result);\n }\n\n resolvedPlugin = isPlugin<PluginContext<TResolvedConfig>>(result)\n ? result\n : plugin;\n }\n\n const context = createPluginContext<TResolvedConfig>(resolvedPlugin, this);\n\n this.plugins.push({\n plugin: resolvedPlugin,\n context\n });\n\n this.#hooks = Object.keys(resolvedPlugin)\n .filter(\n key =>\n !PLUGIN_NON_HOOK_FIELDS.includes(\n key as ArrayValues<typeof PLUGIN_NON_HOOK_FIELDS>\n )\n )\n .reduce((ret, key) => {\n const hook = key as HookFields<PluginContext<TResolvedConfig>>;\n\n if (isPluginHookField<PluginContext<TResolvedConfig>>(hook)) {\n const pluginHook = resolvedPlugin[hook];\n if (!isPluginHook(pluginHook)) {\n return ret;\n }\n\n ret[hook] ??= {\n preEnforced: [],\n preOrdered: [],\n normal: [],\n postEnforced: [],\n postOrdered: []\n };\n\n if (resolvedPlugin.enforce) {\n const hookListOrder =\n `${resolvedPlugin.enforce}Enforced` as HookListOrders;\n ret[hook][hookListOrder] ??= [];\n\n const bucket = ret[hook][hookListOrder];\n addPluginHook<\n PluginContext<TResolvedConfig>,\n PluginHookFields<PluginContext<TResolvedConfig>>\n >(context, resolvedPlugin, pluginHook, bucket);\n\n return ret;\n }\n\n if (isFunction(pluginHook) || !pluginHook.order) {\n ret[hook].normal ??= [];\n\n const bucket = ret[hook].normal;\n addPluginHook<\n PluginContext<TResolvedConfig>,\n PluginHookFields<PluginContext<TResolvedConfig>>\n >(context, resolvedPlugin, pluginHook, bucket);\n\n return ret;\n }\n\n const hookListOrder = `${pluginHook.order}Ordered` as HookListOrders;\n ret[hook][hookListOrder] ??= [];\n\n addPluginHook(\n context,\n resolvedPlugin,\n pluginHook,\n ret[hook][hookListOrder] as PluginHooksListItem<\n PluginContext<TResolvedConfig>\n >[]\n );\n\n return ret;\n } else if (isUnpluginHookField(hook)) {\n const unpluginPlugin = resolvedPlugin[hook];\n if (!isSetObject(unpluginPlugin)) {\n return ret;\n }\n\n for (const field of Object.keys(unpluginPlugin)) {\n const variantField = field as keyof UnpluginOptions[typeof hook];\n\n const pluginHook = unpluginPlugin[\n variantField\n ] as PluginHook<AnyFunction>;\n if (!isPluginHook(pluginHook)) {\n continue;\n }\n\n ret[hook] ??= {};\n (ret[hook][variantField] as UnpluginHookList<\n PluginContext<TResolvedConfig>,\n typeof variantField\n >) ??= {\n preEnforced: [],\n preOrdered: [],\n normal: [],\n postEnforced: [],\n postOrdered: []\n };\n\n if (resolvedPlugin.enforce) {\n addPluginHook(\n context,\n resolvedPlugin,\n pluginHook,\n ret[hook][variantField][\n `${resolvedPlugin.enforce}Enforced`\n ] as UnpluginHooksListItem<PluginContext<TResolvedConfig>>[]\n );\n\n return ret;\n }\n\n if (isFunction(pluginHook) || !pluginHook.order) {\n addPluginHook(\n context,\n resolvedPlugin,\n pluginHook,\n\n (\n ret[hook][variantField] as UnpluginHookList<\n PluginContext<TResolvedConfig>,\n typeof variantField\n >\n ).normal!\n );\n\n return ret;\n }\n\n addPluginHook(\n context,\n resolvedPlugin,\n pluginHook,\n ret[hook][variantField][\n `${pluginHook.order}Ordered`\n ] as UnpluginHooksListItem<PluginContext<TResolvedConfig>>[]\n );\n }\n } else {\n this.warn(`Unknown plugin hook field: ${String(hook)}`);\n }\n\n return ret;\n }, this.hooks);\n }\n\n /**\n * Retrieves the hook handlers for a specific hook name\n */\n public selectHooks<TKey extends string>(\n key: TKey,\n options?: SelectHooksOptions\n ): SelectHookResult<PluginContext<TResolvedConfig>, TKey> {\n const result = [] as SelectHookResult<PluginContext<TResolvedConfig>, TKey>;\n\n if (isUnpluginHookKey(key)) {\n const variant = String(key).split(\":\")[0];\n if (isUnpluginBuilderVariant(variant)) {\n const hooks = this.hooks[variant];\n if (hooks) {\n const field = String(key).split(\":\")[1] as keyof typeof hooks;\n if (field && hooks[field]) {\n const fieldHooks = hooks[field] as Record<\n HookListOrders,\n InferHooksListItem<PluginContext<TResolvedConfig>, TKey>[]\n >;\n\n if (options?.order) {\n const mapHooksToResult = (\n hooksList: InferHooksListItem<\n PluginContext<TResolvedConfig>,\n TKey\n >[]\n ): SelectHookResult<PluginContext<TResolvedConfig>, TKey> =>\n hooksList.map(hook => {\n const plugin = this.plugins.find(\n p => p.plugin.name === hook.plugin.name\n );\n if (!plugin) {\n throw new Error(\n `Could not find plugin context for plugin \"${\n hook.plugin.name\n }\".`\n );\n }\n\n return {\n handler: hook.handler,\n plugin: hook.plugin,\n context: plugin.context\n } as SelectHookResultItem<\n PluginContext<TResolvedConfig>,\n TKey\n >;\n });\n\n if (options?.order === \"pre\") {\n result.push(...mapHooksToResult(fieldHooks.preOrdered ?? []));\n result.push(...mapHooksToResult(fieldHooks.preEnforced ?? []));\n } else if (options?.order === \"post\") {\n result.push(...mapHooksToResult(fieldHooks.postOrdered ?? []));\n result.push(...mapHooksToResult(fieldHooks.postEnforced ?? []));\n } else {\n result.push(...mapHooksToResult(fieldHooks.normal ?? []));\n }\n } else {\n result.push(...this.selectHooks(key, { order: \"pre\" }));\n result.push(...this.selectHooks(key, { order: \"normal\" }));\n result.push(...this.selectHooks(key, { order: \"post\" }));\n }\n }\n }\n }\n } else if (isPluginHookField<PluginContext<TResolvedConfig>>(key)) {\n if (this.hooks[key]) {\n const fieldHooks = this.hooks[key] as Record<\n HookListOrders,\n InferHooksListItem<PluginContext<TResolvedConfig>, TKey>[]\n >;\n\n if (options?.order) {\n const mapHooksToResult = (\n hooksList: InferHooksListItem<\n PluginContext<TResolvedConfig>,\n TKey\n >[]\n ): SelectHookResult<PluginContext<TResolvedConfig>, TKey> =>\n hooksList.map(hook => {\n const plugin = this.plugins.find(\n p => p.plugin.name === hook.plugin.name\n );\n if (!plugin) {\n throw new Error(\n `Could not find plugin context for plugin \"${\n hook.plugin.name\n }\".`\n );\n }\n\n return {\n handler: hook.handler,\n plugin: hook.plugin,\n context: plugin.context\n } as SelectHookResultItem<PluginContext<TResolvedConfig>, TKey>;\n });\n\n if (options?.order === \"pre\") {\n result.push(...mapHooksToResult(fieldHooks.preOrdered ?? []));\n result.push(...mapHooksToResult(fieldHooks.preEnforced ?? []));\n } else if (options?.order === \"post\") {\n result.push(...mapHooksToResult(fieldHooks.postOrdered ?? []));\n result.push(...mapHooksToResult(fieldHooks.postEnforced ?? []));\n } else {\n result.push(...mapHooksToResult(fieldHooks.normal ?? []));\n }\n } else {\n result.push(...this.selectHooks(key, { order: \"pre\" }));\n result.push(...this.selectHooks(key, { order: \"normal\" }));\n result.push(...this.selectHooks(key, { order: \"post\" }));\n }\n }\n } else {\n throw new Error(`Unknown plugin hook key: ${String(key)}`);\n }\n\n return result;\n }\n\n protected constructor(\n config: TResolvedConfig,\n workspaceConfig: WorkspaceConfig\n ) {\n super(workspaceConfig);\n\n this.resolvedConfig = config;\n }\n}\n","/* -------------------------------------------------------------------\n\n ⚡ Storm Software - Powerlines\n\n This code was released as part of the Powerlines project. Powerlines\n is maintained by Storm Software under the Apache-2.0 license, and is\n free for commercial and private use. For more information, please visit\n our licensing page at https://stormsoftware.com/licenses/projects/powerlines.\n\n Website: https://stormsoftware.com\n Repository: https://github.com/storm-software/powerlines\n Documentation: https://docs.stormsoftware.com/projects/powerlines\n Contact: https://stormsoftware.com/contact\n\n SPDX-License-Identifier: Apache-2.0\n\n ------------------------------------------------------------------- */\n\nimport {\n UNSAFE_ContextInternal,\n UNSAFE_EnvironmentContext\n} from \"@powerlines/core/types/_internal\";\nimport { toArray } from \"@stryke/convert/to-array\";\nimport { resolvePackage } from \"@stryke/fs/resolve\";\nimport { isSetObject } from \"@stryke/type-checks/is-set-object\";\nimport chalk from \"chalk\";\nimport {\n createDefaultEnvironment,\n createEnvironment\n} from \"../_internal/helpers/environment\";\nimport { loadWorkspaceConfig } from \"../config\";\nimport { GLOBAL_ENVIRONMENT } from \"../constants\";\nimport type {\n APIContext,\n EnvironmentContext,\n EnvironmentResolvedConfig,\n InitContextOptions,\n InitialUserConfig,\n InlineConfig,\n LogFn,\n Plugin,\n PluginContext,\n ResolvedConfig,\n UserConfig,\n WorkspaceConfig\n} from \"../types\";\nimport { PowerlinesContext } from \"./context\";\nimport { PowerlinesEnvironmentContext } from \"./environment-context\";\n\nexport class PowerlinesAPIContext<\n TResolvedConfig extends ResolvedConfig = ResolvedConfig\n>\n extends PowerlinesContext<TResolvedConfig>\n implements APIContext<TResolvedConfig>\n{\n #environments: Record<string, UNSAFE_EnvironmentContext<TResolvedConfig>> =\n {};\n\n #plugins: Plugin<PluginContext<TResolvedConfig>>[] = [];\n\n #log!: LogFn;\n\n /**\n * Create a new Storm context from the workspace root and user config.\n *\n * @param workspaceRoot - The root directory of the workspace.\n * @param config - The user configuration options.\n * @returns A promise that resolves to the new context.\n */\n public static override async from<\n TResolvedConfig extends ResolvedConfig = ResolvedConfig\n >(\n workspaceRoot: string,\n config: InitialUserConfig<TResolvedConfig[\"userConfig\"]>\n ): Promise<APIContext<TResolvedConfig>> {\n const context = new PowerlinesAPIContext<TResolvedConfig>(\n await loadWorkspaceConfig(workspaceRoot, config.root)\n );\n await context.withUserConfig(config);\n\n const powerlinesPath = await resolvePackage(\"powerlines\");\n if (!powerlinesPath) {\n throw new Error(\"Could not resolve `powerlines` package location.\");\n }\n\n context.powerlinesPath = powerlinesPath;\n\n return context;\n }\n\n /**\n * Internal context fields and methods\n *\n * @danger\n * This field is for internal use only and should not be accessed or modified directly. It is unstable and can be changed at anytime.\n *\n * @internal\n */\n public override get $$internal(): UNSAFE_ContextInternal<TResolvedConfig> {\n return super.$$internal;\n }\n\n /**\n * Internal context fields and methods\n *\n * @danger\n * This field is for internal use only and should not be accessed or modified directly. It is unstable and can be changed at anytime.\n *\n * @internal\n */\n public override set $$internal(\n value: UNSAFE_ContextInternal<TResolvedConfig>\n ) {\n super.$$internal = value;\n for (const environment of Object.values(this.environments)) {\n environment.$$internal = super.$$internal;\n }\n }\n\n /**\n * A record of all environments by name\n */\n public get environments(): Record<\n string,\n UNSAFE_EnvironmentContext<TResolvedConfig>\n > {\n return this.#environments;\n }\n\n public override get log(): LogFn {\n if (!this.#log) {\n this.#log = this.createLog();\n }\n\n return this.#log;\n }\n\n public get plugins(): Array<Plugin<PluginContext<TResolvedConfig>>> {\n return this.#plugins;\n }\n\n protected constructor(workspaceConfig: WorkspaceConfig) {\n super(workspaceConfig);\n }\n\n /**\n * Initialize the context with the provided configuration options\n *\n * @param config - The partial user configuration to use for initialization.\n */\n protected override async init(\n config: Partial<TResolvedConfig[\"userConfig\"]> = {}\n ) {\n await super.init(config);\n\n await Promise.all(\n toArray(\n this.config.userConfig.environments &&\n Object.keys(this.config.userConfig.environments).length > 0\n ? Object.keys(this.config.userConfig.environments).map(name =>\n createEnvironment(name, this.config.userConfig)\n )\n : createDefaultEnvironment(this.config.userConfig)\n ).map(async env => {\n this.#environments[env.name] = await this.in(env);\n })\n );\n }\n\n /**\n * A function to copy the context and update the fields for a specific environment\n *\n * @param environment - The environment configuration to use.\n * @returns A new context instance with the updated environment.\n */\n public async in(\n environment: EnvironmentResolvedConfig\n ): Promise<UNSAFE_EnvironmentContext<TResolvedConfig>> {\n let context: UNSAFE_EnvironmentContext<TResolvedConfig>;\n if (this.environments[environment.name]) {\n context = this.environments[environment.name] as any;\n } else {\n context = (await PowerlinesEnvironmentContext.fromConfig(\n this.workspaceConfig,\n this.config\n )) as any;\n }\n\n if (isSetObject(this.config.inlineConfig)) {\n await context.withInlineConfig(this.config.inlineConfig);\n }\n\n context.environment = environment;\n context.plugins = [];\n\n for (const plugin of this.plugins) {\n await context.addPlugin(plugin);\n }\n\n return context;\n }\n\n /**\n * Update the context using a new user configuration options\n *\n * @param userConfig - The new user configuration options.\n */\n public override async withUserConfig(\n userConfig: InitialUserConfig<TResolvedConfig[\"userConfig\"]>,\n options: InitContextOptions = {\n isHighPriority: true\n }\n ) {\n await super.withUserConfig(userConfig, options);\n\n await Promise.all(\n Object.keys(this.#environments).map(async name => {\n await this.#environments[name]!.withUserConfig(\n userConfig as UserConfig,\n options\n );\n })\n );\n }\n\n /**\n * Update the context using a new inline configuration options\n *\n * @param inlineConfig - The new inline configuration options.\n */\n public override async withInlineConfig(\n inlineConfig: TResolvedConfig[\"inlineConfig\"],\n options: InitContextOptions = {\n isHighPriority: true\n }\n ) {\n await super.withInlineConfig(inlineConfig, options);\n\n await Promise.all(\n Object.keys(this.#environments).map(async name => {\n await this.#environments[name]!.withInlineConfig(\n inlineConfig as InlineConfig,\n options\n );\n })\n );\n }\n\n /**\n * Add a plugin to the API context and all environments\n *\n * @param plugin - The plugin to add.\n */\n public async addPlugin(plugin: Plugin<PluginContext<TResolvedConfig>>) {\n this.plugins.push(plugin);\n\n await Promise.all(\n Object.keys(this.environments).map(async name => {\n await this.environments[name]!.addPlugin(plugin);\n })\n );\n }\n\n /**\n * Get an environment by name, or the default environment if no name is provided\n *\n * @param name - The name of the environment to retrieve.\n * @returns The requested environment context.\n */\n public async getEnvironment(name?: string) {\n let environment: EnvironmentContext<TResolvedConfig> | undefined;\n if (name) {\n environment = this.environments[name];\n }\n\n if (Object.keys(this.environments).length === 1) {\n environment = this.environments[Object.keys(this.environments)[0]!];\n\n this.debug(\n `Applying the only configured environment: ${chalk.bold.cyanBright(\n environment?.environment.name\n )}`\n );\n }\n\n if (!environment) {\n if (name) {\n throw new Error(`Environment \"${name}\" not found.`);\n }\n\n environment = await this.in(\n createDefaultEnvironment(this.config.userConfig)\n );\n\n this.warn(\n `No environment specified, and no default environment found. Using a temporary default environment: ${chalk.bold.cyanBright(\n environment?.environment.name\n )}`\n );\n }\n\n return environment;\n }\n\n /**\n * A safe version of `getEnvironment` that returns `undefined` if the environment is not found\n *\n * @param name - The name of the environment to retrieve.\n * @returns The requested environment context or `undefined` if not found.\n */\n public async getEnvironmentSafe(\n name?: string\n ): Promise<EnvironmentContext<TResolvedConfig> | undefined> {\n try {\n return await this.getEnvironment(name);\n } catch {\n return undefined;\n }\n }\n\n /**\n * A function to merge all configured environments into a single context.\n *\n * @remarks\n * If only one environment is configured, that environment will be returned directly.\n *\n * @returns A promise that resolves to a merged/global environment context.\n */\n public async toEnvironment(): Promise<EnvironmentContext<TResolvedConfig>> {\n let environment: EnvironmentContext<TResolvedConfig>;\n if (Object.keys(this.environments).length > 1) {\n environment = await this.in(\n createEnvironment(GLOBAL_ENVIRONMENT, this.config.userConfig)\n );\n\n this.debug(\n `Combined all ${Object.keys(this.environments).length} environments into a single global context.`\n );\n } else {\n environment = await this.getEnvironment();\n }\n\n return environment;\n }\n}\n","/* -------------------------------------------------------------------\n\n ⚡ Storm Software - Powerlines\n\n This code was released as part of the Powerlines project. Powerlines\n is maintained by Storm Software under the Apache-2.0 license, and is\n free for commercial and private use. For more information, please visit\n our licensing page at https://stormsoftware.com/licenses/projects/powerlines.\n\n Website: https://stormsoftware.com\n Repository: https://github.com/storm-software/powerlines\n Documentation: https://docs.stormsoftware.com/projects/powerlines\n Contact: https://stormsoftware.com/contact\n\n SPDX-License-Identifier: Apache-2.0\n\n ------------------------------------------------------------------- */\n\nimport { UNSAFE_APIContext } from \"@powerlines/core/types/_internal\";\nimport { formatLogMessage } from \"@storm-software/config-tools/logger/console\";\nimport { toArray } from \"@stryke/convert/to-array\";\nimport { createDirectory } from \"@stryke/fs/helpers\";\nimport { install } from \"@stryke/fs/install\";\nimport { listFiles } from \"@stryke/fs/list-files\";\nimport { isPackageExists } from \"@stryke/fs/package-fns\";\nimport { resolvePackage } from \"@stryke/fs/resolve\";\nimport { omit } from \"@stryke/helpers/omit\";\nimport { appendPath } from \"@stryke/path/append\";\nimport { joinPaths } from \"@stryke/path/join-paths\";\nimport { replacePath } from \"@stryke/path/replace\";\nimport { isError } from \"@stryke/type-checks/is-error\";\nimport { isFunction } from \"@stryke/type-checks/is-function\";\nimport { isNumber } from \"@stryke/type-checks/is-number\";\nimport { isObject } from \"@stryke/type-checks/is-object\";\nimport { isPromiseLike } from \"@stryke/type-checks/is-promise\";\nimport { isSet } from \"@stryke/type-checks/is-set\";\nimport { isSetObject } from \"@stryke/type-checks/is-set-object\";\nimport { isSetString } from \"@stryke/type-checks/is-set-string\";\nimport { isString } from \"@stryke/type-checks/is-string\";\nimport { MaybePromise } from \"@stryke/types/base\";\nimport chalk from \"chalk\";\nimport Handlebars from \"handlebars\";\nimport packageJson from \"../package.json\" assert { type: \"json\" };\nimport {\n emitBuiltinTypes,\n formatTypes\n} from \"./_internal/helpers/generate-types\";\nimport { callHook, mergeConfigs } from \"./_internal/helpers/hooks\";\nimport { installDependencies } from \"./_internal/helpers/install-dependencies\";\nimport { writeMetaFile } from \"./_internal/helpers/meta\";\nimport {\n getTsconfigDtsPath,\n initializeTsconfig,\n resolveTsconfig\n} from \"./_internal/helpers/resolve-tsconfig\";\nimport { PowerlinesAPIContext } from \"./context/api-context\";\nimport {\n checkDedupe,\n findInvalidPluginConfig,\n isPlugin,\n isPluginConfig,\n isPluginConfigObject,\n isPluginConfigTuple\n} from \"./plugin-utils\";\nimport type {\n APIContext,\n BuildInlineConfig,\n CleanInlineConfig,\n DeployInlineConfig,\n DocsInlineConfig,\n EnvironmentContext,\n InitialUserConfig,\n LintInlineConfig,\n NewInlineConfig,\n Plugin,\n PluginConfig,\n PluginConfigObject,\n PluginConfigTuple,\n PluginContext,\n PluginFactory,\n PrepareInlineConfig,\n TypesResult\n} from \"./types\";\nimport {\n API,\n CallHookOptions,\n EnvironmentResolvedConfig,\n InferHookParameters,\n ResolvedConfig\n} from \"./types\";\nimport {\n getParsedTypeScriptConfig,\n isIncludeMatchFound\n} from \"./typescript/tsconfig\";\nimport { formatFolder, getTypescriptFileHeader } from \"./utils\";\n\n/**\n * The Powerlines API class\n *\n * @remarks\n * This class is responsible for managing the Powerlines project lifecycle, including initialization, building, and finalization.\n *\n * @public\n */\nexport class PowerlinesAPI<\n TResolvedConfig extends ResolvedConfig = ResolvedConfig\n>\n implements API<TResolvedConfig>, AsyncDisposable\n{\n /**\n * The Powerlines context\n */\n #context: UNSAFE_APIContext<TResolvedConfig>;\n\n /**\n * The Powerlines context\n */\n public get context(): APIContext<TResolvedConfig> {\n return this.#context;\n }\n\n /**\n * Create a new Powerlines API instance\n *\n * @param context - The Powerlines context\n */\n private constructor(context: APIContext<TResolvedConfig>) {\n this.#context = context as UNSAFE_APIContext<TResolvedConfig>;\n }\n\n /**\n * Initialize a Powerlines API instance\n *\n * @param workspaceRoot - The directory of the underlying workspace the Powerlines project exists in\n * @param config - An object containing the configuration required to run Powerlines tasks.\n * @returns A new instance of the Powerlines API\n */\n public static async from<\n TResolvedConfig extends ResolvedConfig = ResolvedConfig\n >(\n workspaceRoot: string,\n config: InitialUserConfig<TResolvedConfig[\"userConfig\"]>\n ): Promise<PowerlinesAPI<TResolvedConfig>> {\n const api = new PowerlinesAPI<TResolvedConfig>(\n await PowerlinesAPIContext.from(workspaceRoot, config)\n );\n api.#context.$$internal = {\n api,\n addPlugin: api.#addPlugin.bind(api)\n };\n\n api.context.info(\n `🔌 The Powerlines Engine v${packageJson.version} has started`\n );\n\n for (const plugin of api.context.config.plugins ?? []) {\n await api.#addPlugin(plugin);\n }\n\n if (api.context.plugins.length === 0) {\n api.context.warn(\n \"No Powerlines plugins were specified in the options. Please ensure this is correct, as it is generally not recommended.\"\n );\n }\n\n const pluginConfig = await api.callHook(\"config\", {\n environment: await api.context.getEnvironment(),\n sequential: true,\n result: \"merge\",\n merge: mergeConfigs\n });\n await api.context.withUserConfig(\n pluginConfig as TResolvedConfig[\"userConfig\"],\n { isHighPriority: false }\n );\n\n return api;\n }\n\n /**\n * Prepare the Powerlines API\n *\n * @remarks\n * This method will prepare the Powerlines API for use, initializing any necessary resources.\n *\n * @param inlineConfig - The inline configuration for the prepare command\n */\n public async prepare(\n inlineConfig:\n | PrepareInlineConfig\n | NewInlineConfig\n | CleanInlineConfig\n | BuildInlineConfig\n | LintInlineConfig\n | DocsInlineConfig\n | DeployInlineConfig = { command: \"prepare\" }\n ) {\n this.context.info(\" 🏗️ Preparing the Powerlines project\");\n\n this.context.debug(\n \" Aggregating configuration options for the Powerlines project\"\n );\n\n await this.context.withInlineConfig(inlineConfig);\n await this.#executeEnvironments(async context => {\n context.debug(\n `Initializing the processing options for the Powerlines project.`\n );\n\n await this.callHook(\"configResolved\", {\n environment: context,\n order: \"pre\"\n });\n\n await initializeTsconfig<TResolvedConfig>(context);\n\n await this.callHook(\"configResolved\", {\n environment: context,\n order: \"normal\"\n });\n\n if (context.entry.length > 0) {\n context.debug(\n `The configuration provided ${\n isObject(context.config.input)\n ? Object.keys(context.config.input).length\n : toArray(context.config.input).length\n } entry point(s), Powerlines has found ${\n context.entry.length\n } entry files(s) for the ${context.config.title} project${\n context.entry.length > 0 && context.entry.length < 10\n ? `: \\n${context.entry\n .map(\n entry =>\n `- ${entry.file}${\n entry.output ? ` -> ${entry.output}` : \"\"\n }`\n )\n .join(\" \\n\")}`\n : \"\"\n }`\n );\n } else {\n context.warn(\n `No entry files were found for the ${\n context.config.title\n } project. Please ensure this is correct. Powerlines plugins generally require at least one entry point to function properly.`\n );\n }\n\n await resolveTsconfig<TResolvedConfig>(context);\n await installDependencies(context);\n\n await this.callHook(\"configResolved\", {\n environment: context,\n order: \"post\"\n });\n\n context.trace(\n `Powerlines configuration has been resolved: \\n\\n${formatLogMessage({\n ...context.config,\n userConfig: isSetObject(context.config.userConfig)\n ? omit(context.config.userConfig, [\"plugins\"])\n : undefined,\n inlineConfig: isSetObject(context.config.inlineConfig)\n ? omit(context.config.inlineConfig, [\"plugins\"])\n : undefined,\n plugins: context.plugins.map(plugin => plugin.plugin.name)\n })}`\n );\n\n if (!context.fs.existsSync(context.cachePath)) {\n await createDirectory(context.cachePath);\n }\n\n if (!context.fs.existsSync(context.dataPath)) {\n await createDirectory(context.dataPath);\n }\n\n await this.callHook(\"prepare\", {\n environment: context,\n order: \"pre\"\n });\n await this.callHook(\"prepare\", {\n environment: context,\n order: \"normal\"\n });\n\n await this.callHook(\"prepare\", {\n environment: context,\n order: \"post\"\n });\n\n if (context.config.output.dts !== false) {\n context.debug(\n `Preparing the TypeScript definitions for the Powerlines project.`\n );\n\n if (context.fs.existsSync(context.dtsPath)) {\n await context.fs.remove(context.dtsPath);\n }\n\n const typescriptPath = await resolvePackage(\"typescript\");\n if (!typescriptPath) {\n throw new Error(\n \"Could not resolve TypeScript package location. Please ensure TypeScript is installed.\"\n );\n }\n\n context.debug(\n \"Running TypeScript compiler for built-in runtime module files.\"\n );\n\n let types = await emitBuiltinTypes(\n context,\n (await context.getBuiltins()).reduce<string[]>((ret, builtin) => {\n const formatted = replacePath(\n builtin.path,\n context.workspaceConfig.workspaceRoot\n );\n if (!ret.includes(formatted)) {\n ret.push(formatted);\n }\n\n return ret;\n }, [])\n );\n\n context.debug(\n `Generating TypeScript declaration file ${context.dtsPath}.`\n );\n\n const directives = [] as string[];\n const asNextParam = (\n previousResult: string | TypesResult | null | undefined\n ) => (isObject(previousResult) ? previousResult.code : previousResult);\n\n let result = await this.callHook(\n \"types\",\n {\n environment: context,\n sequential: true,\n order: \"pre\",\n result: \"merge\",\n asNextParam\n },\n types\n );\n if (result) {\n if (isSetObject(result)) {\n types = result.code;\n if (\n Array.isArray(result.directives) &&\n result.directives.length > 0\n ) {\n directives.push(...result.directives);\n }\n } else if (isSetString(result)) {\n types = result;\n }\n }\n\n result = await this.callHook(\n \"types\",\n {\n environment: context,\n sequential: true,\n order: \"normal\",\n result: \"merge\",\n asNextParam\n },\n types\n );\n if (result) {\n if (isSetObject(result)) {\n types = result.code;\n if (\n Array.isArray(result.directives) &&\n result.directives.length > 0\n ) {\n directives.push(...result.directives);\n }\n } else if (isSetString(result)) {\n types = result;\n }\n }\n\n result = await this.callHook(\n \"types\",\n {\n environment: context,\n sequential: true,\n order: \"post\",\n result: \"merge\",\n asNextParam\n },\n types\n );\n if (result) {\n if (isSetObject(result)) {\n types = result.code;\n if (\n Array.isArray(result.directives) &&\n result.directives.length > 0\n ) {\n directives.push(...result.directives);\n }\n } else if (isSetString(result)) {\n types = result;\n }\n }\n\n if (isSetString(types?.trim()) || directives.length > 0) {\n await context.fs.write(\n context.dtsPath,\n `${\n directives.length > 0\n ? `${directives.map(directive => `/// <reference types=\"${directive}\" />`).join(\"\\n\")}\n\n`\n : \"\"\n }${getTypescriptFileHeader(context, { directive: null, prettierIgnore: false })}\n\n${formatTypes(types)}\n`\n );\n } else {\n const dtsRelativePath = getTsconfigDtsPath(context);\n if (\n context.tsconfig.tsconfigJson.include &&\n isIncludeMatchFound(\n dtsRelativePath,\n context.tsconfig.tsconfigJson.include\n )\n ) {\n const normalizedDtsRelativePath = dtsRelativePath.startsWith(\"./\")\n ? dtsRelativePath.slice(2)\n : dtsRelativePath;\n context.tsconfig.tsconfigJson.include =\n context.tsconfig.tsconfigJson.include.filter(\n includeValue =>\n includeValue?.toString() !== normalizedDtsRelativePath\n );\n\n await context.fs.write(\n context.tsconfig.tsconfigFilePath,\n JSON.stringify(context.tsconfig.tsconfigJson, null, 2)\n );\n }\n }\n }\n\n // Re-resolve the tsconfig to ensure it is up to date\n context.tsconfig = getParsedTypeScriptConfig(\n context.workspaceConfig.workspaceRoot,\n context.config.root,\n context.config.tsconfig\n );\n if (!context.tsconfig) {\n throw new Error(\"Failed to parse the TypeScript configuration file.\");\n }\n\n this.context.debug(\"Formatting files generated during the prepare step.\");\n\n await Promise.all([\n formatFolder(context, context.builtinsPath),\n formatFolder(context, context.entryPath)\n ]);\n\n await writeMetaFile(context);\n context.persistedMeta = context.meta;\n });\n\n this.context.debug(\"✔ Powerlines preparation has completed successfully\");\n }\n\n /**\n * Create a new Powerlines project\n *\n * @remarks\n * This method will create a new Powerlines project in the current directory.\n *\n * @param inlineConfig - The inline configuration for the new command\n * @returns A promise that resolves when the project has been created\n */\n public async new(inlineConfig: NewInlineConfig) {\n this.context.info(\" 🆕 Creating a new Powerlines project\");\n\n await this.prepare(inlineConfig);\n await this.#executeEnvironments(async context => {\n context.debug(\n \"Initializing the processing options for the Powerlines project.\"\n );\n\n await this.callHook(\"new\", {\n environment: context,\n order: \"pre\"\n });\n\n const files = await listFiles(\n joinPaths(context.powerlinesPath, \"files/common/**/*.hbs\")\n );\n for (const file of files) {\n context.trace(`Adding template file to project: ${file}`);\n\n const template = Handlebars.compile(file);\n await context.fs.write(\n joinPaths(context.config.root, file.replace(\".hbs\", \"\")),\n template(context)\n );\n }\n\n await this.callHook(\"new\", {\n environment: context,\n order: \"normal\"\n });\n\n if (context.config.projectType === \"application\") {\n const files = await listFiles(\n joinPaths(context.powerlinesPath, \"files/application/**/*.hbs\")\n );\n for (const file of files) {\n context.trace(`Adding application template file: ${file}`);\n\n const template = Handlebars.compile(file);\n await context.fs.write(\n joinPaths(context.config.root, file.replace(\".hbs\", \"\")),\n template(context)\n );\n }\n } else {\n const files = await listFiles(\n joinPaths(context.powerlinesPath, \"files/library/**/*.hbs\")\n );\n for (const file of files) {\n context.trace(`Adding library template file: ${file}`);\n\n const template = Handlebars.compile(file);\n await context.fs.write(\n joinPaths(context.config.root, file.replace(\".hbs\", \"\")),\n template(context)\n );\n }\n }\n\n await this.callHook(\"new\", {\n environment: context,\n order: \"post\"\n });\n });\n\n this.context.debug(\"✔ Powerlines new command completed successfully\");\n }\n\n /**\n * Clean any previously prepared artifacts\n *\n * @remarks\n * This method will remove the previous Powerlines artifacts from the project.\n *\n * @param inlineConfig - The inline configuration for the clean command\n * @returns A promise that resolves when the clean command has completed\n */\n public async clean(\n inlineConfig: CleanInlineConfig | PrepareInlineConfig = {\n command: \"clean\"\n }\n ) {\n this.context.info(\" 🧹 Cleaning the previous Powerlines artifacts\");\n\n await this.prepare(inlineConfig);\n await this.#executeEnvironments(async context => {\n context.debug(\"Cleaning the project's dist and artifacts directories.\");\n\n await context.fs.remove(\n joinPaths(\n context.workspaceConfig.workspaceRoot,\n context.config.output.buildPath\n )\n );\n await context.fs.remove(\n joinPaths(\n context.workspaceConfig.workspaceRoot,\n context.config.root,\n context.config.output.artifactsPath\n )\n );\n\n await this.callHook(\"clean\", {\n environment: context,\n sequential: false\n });\n });\n\n this.context.debug(\"✔ Powerlines cleaning completed successfully\");\n }\n\n /**\n * Lint the project\n *\n * @param inlineConfig - The inline configuration for the lint command\n * @returns A promise that resolves when the lint command has completed\n */\n public async lint(\n inlineConfig: LintInlineConfig | BuildInlineConfig = { command: \"lint\" }\n ) {\n this.context.info(\" 📝 Linting the Powerlines project\");\n\n await this.prepare(inlineConfig);\n await this.#executeEnvironments(async context => {\n await this.callHook(\"lint\", {\n environment: context,\n sequential: false\n });\n });\n\n this.context.debug(\"✔ Powerlines linting completed successfully\");\n }\n\n /**\n * Build the project\n *\n * @remarks\n * This method will build the Powerlines project, generating the necessary artifacts.\n *\n * @param inlineConfig - The inline configuration for the build command\n * @returns A promise that resolves when the build command has completed\n */\n public async build(inlineConfig: BuildInlineConfig = { command: \"build\" }) {\n this.context.info(\" 📦 Building the Powerlines project\");\n\n await this.context.generateChecksum();\n if (\n this.context.meta.checksum !== this.context.persistedMeta?.checksum ||\n this.context.config.skipCache\n ) {\n this.context.info(\n \"The project has been modified since the last time `prepare` was ran. Re-preparing the project.\"\n );\n\n await this.prepare(inlineConfig);\n }\n\n if (this.context.config.singleBuild) {\n await this.#handleBuild(await this.#context.toEnvironment());\n } else {\n await this.#executeEnvironments(async context => {\n await this.#handleBuild(context);\n });\n }\n\n this.context.debug(\"✔ Powerlines build completed successfully\");\n }\n\n /**\n * Prepare the documentation for the project\n *\n * @param inlineConfig - The inline configuration for the docs command\n * @returns A promise that resolves when the documentation generation has completed\n */\n public async docs(inlineConfig: DocsInlineConfig = { command: \"docs\" }) {\n this.context.info(\n \" 📓 Generating documentation for the Powerlines project\"\n );\n\n await this.prepare(inlineConfig);\n await this.#executeEnvironments(async context => {\n context.debug(\n \"Writing documentation for the Powerlines project artifacts.\"\n );\n\n await this.prepare(inlineConfig);\n await this.#executeEnvironments(async context => {\n await this.callHook(\"docs\", {\n environment: context\n });\n });\n });\n\n this.context.debug(\n \"✔ Powerlines documentation generation completed successfully\"\n );\n }\n\n /**\n * Deploy the project source code\n *\n * @remarks\n * This method will prepare and build the Powerlines project, generating the necessary artifacts for the deployment.\n *\n * @param inlineConfig - The inline configuration for the deploy command\n */\n public async deploy(\n inlineConfig: DeployInlineConfig = { command: \"deploy\" }\n ) {\n this.context.info(\" 🚀 Deploying the Powerlines project\");\n\n await this.prepare(inlineConfig);\n await this.#executeEnvironments(async context => {\n await this.callHook(\"deploy\", { environment: context });\n });\n\n this.context.debug(\"✔ Powerlines deploy completed successfully\");\n }\n\n /**\n * Finalization process\n *\n * @remarks\n * This step includes any final processes or clean up required by Powerlines. It will be run after each Powerlines command.\n *\n * @returns A promise that resolves when the finalization process has completed\n */\n public async finalize() {\n this.context.info(\" 🏁 Powerlines finalization processes started\");\n\n await this.#executeEnvironments(async context => {\n await this.callHook(\"finalize\", { environment: context });\n await context.fs.dispose();\n });\n\n this.context.debug(\"✔ Powerlines finalization completed successfully\");\n }\n\n /**\n * Invokes the configured plugin hooks\n *\n * @remarks\n * By default, it will call the `\"pre\"`, `\"normal\"`, and `\"post\"` ordered hooks in sequence\n *\n * @param hook - The hook to call\n * @param options - The options to provide to the hook\n * @param args - The arguments to pass to the hook\n * @returns The result of the hook call\n */\n public async callHook<TKey extends string>(\n hook: TKey,\n options: CallHookOptions & {\n environment?: string | EnvironmentContext<TResolvedConfig>;\n },\n ...args: InferHookParameters<PluginContext<TResolvedConfig>, TKey>\n ) {\n return callHook<TResolvedConfig, TKey>(\n isSetObject(options?.environment)\n ? options.environment\n : await this.#context.getEnvironment(options?.environment),\n hook,\n { sequential: true, ...options },\n ...args\n );\n }\n\n /**\n * Dispose of the Powerlines API instance\n *\n * @remarks\n * This method will finalize the Powerlines API instance, cleaning up any resources used.\n */\n public async [Symbol.asyncDispose]() {\n await this.finalize();\n }\n\n async #handleBuild(context: EnvironmentContext<TResolvedConfig>) {\n await this.callHook(\"build\", {\n environment: context,\n order: \"pre\"\n });\n\n context.debug(\n \"Formatting the generated entry files before the build process starts.\"\n );\n await formatFolder(context, context.entryPath);\n\n await this.callHook(\"build\", {\n environment: context,\n order: \"normal\"\n });\n\n if (context.config.output.buildPath !== context.config.output.outputPath) {\n const sourcePath = appendPath(\n context.config.output.buildPath,\n context.workspaceConfig.workspaceRoot\n );\n const destinationPath = joinPaths(\n appendPath(\n context.config.output.outputPath,\n context.workspaceConfig.workspaceRoot\n ),\n \"dist\"\n );\n\n if (context.fs.existsSync(sourcePath) && sourcePath !== destinationPath) {\n context.debug(\n `Copying build output files from project's build directory (${\n context.config.output.buildPath\n }) to the workspace's output directory (${context.config.output.outputPath}).`\n );\n\n await context.fs.copy(sourcePath, destinationPath);\n }\n }\n\n await Promise.all(\n context.config.output.assets.map(async asset => {\n context.trace(\n `Copying asset(s): ${chalk.redBright(\n context.workspaceConfig.workspaceRoot === asset.input\n ? asset.glob\n : joinPaths(\n replacePath(\n asset.input,\n context.workspaceConfig.workspaceRoot\n ),\n asset.glob\n )\n )} -> ${chalk.greenBright(\n joinPaths(\n replacePath(asset.output, context.workspaceConfig.workspaceRoot),\n asset.glob\n )\n )} ${\n Array.isArray(asset.ignore) && asset.ignore.length > 0\n ? ` (ignoring: ${asset.ignore\n .map(i => chalk.yellowBright(i))\n .join(\", \")})`\n : \"\"\n }`\n );\n\n await context.fs.copy(asset, asset.output);\n })\n );\n\n await this.callHook(\"build\", {\n environment: context,\n order: \"post\"\n });\n }\n\n /**\n * Get the configured environments\n *\n * @returns The configured environments\n */\n async #getEnvironments() {\n if (\n !this.context.config.environments ||\n Object.keys(this.context.config.environments).length <= 1\n ) {\n this.context.debug(\n \"No environments are configured for this Powerlines project. Using the default environment.\"\n );\n\n return [await this.context.getEnvironment()];\n }\n\n this.context.debug(\n `Found ${Object.keys(this.context.config.environments).length} configured environment(s) for this Powerlines project.`\n );\n\n return (\n await Promise.all(\n Object.entries(this.context.config.environments).map(\n async ([name, config]) => {\n const environment = await this.context.getEnvironmentSafe(name);\n if (!environment) {\n const resolvedEnvironment = await this.callHook(\n \"configEnvironment\",\n {\n environment: name\n },\n name,\n config\n );\n\n if (resolvedEnvironment) {\n this.context.environments[name] = await this.context.in(\n resolvedEnvironment as EnvironmentResolvedConfig\n );\n }\n }\n\n return this.context.environments[name];\n }\n )\n )\n ).filter(context => isSet(context));\n }\n\n /**\n * Execute a handler function for each environment\n *\n * @param handle - The handler function to execute for each environment\n */\n async #executeEnvironments(\n handle: (context: EnvironmentContext<TResolvedConfig>) => MaybePromise<void>\n ) {\n await Promise.all(\n (await this.#getEnvironments()).map(async context => {\n return Promise.resolve(handle(context));\n })\n );\n }\n\n /**\n * Add a Powerlines plugin used in the build process\n *\n * @param config - The import path of the plugin to add\n */\n async #addPlugin(config: PluginConfig<PluginContext<TResolvedConfig>>) {\n if (config) {\n const result = await this.#initPlugin(config);\n if (!result) {\n return;\n }\n\n for (const plugin of result) {\n this.context.debug(\n `Successfully initialized the ${chalk.bold.cyanBright(\n plugin.name\n )} plugin`\n );\n\n await this.context.addPlugin(plugin);\n }\n }\n }\n\n /**\n * Initialize a Powerlines plugin\n *\n * @param config - The configuration for the plugin\n * @returns The initialized plugin instance, or null if the plugin was a duplicate\n * @throws Will throw an error if the plugin cannot be found or is invalid\n */\n async #initPlugin(\n config: PluginConfig<PluginContext<TResolvedConfig>>\n ): Promise<Plugin<PluginContext<TResolvedConfig>>[] | null> {\n let awaited = config;\n if (isPromiseLike(config)) {\n awaited = (await Promise.resolve(config as Promise<any>)) as PluginConfig<\n PluginContext<TResolvedConfig>\n >;\n }\n\n if (!isPluginConfig<PluginContext<TResolvedConfig>>(awaited)) {\n const invalid = findInvalidPluginConfig(awaited);\n\n throw new Error(\n `Invalid ${\n invalid && invalid.length > 1 ? \"plugins\" : \"plugin\"\n } specified in the configuration - ${\n invalid && invalid.length > 0\n ? JSON.stringify(awaited)\n : invalid?.join(\"\\n\\n\")\n } \\n\\nPlease ensure the value is one of the following: \\n - an instance of \\`Plugin\\` \\n - a plugin name \\n - an object with the \\`plugin\\` and \\`options\\` properties \\n - a tuple array with the plugin and options \\n - a factory function that returns a plugin or array of plugins \\n - an array of plugins or plugin configurations`\n );\n }\n\n let plugins!: Plugin<PluginContext<TResolvedConfig>>[];\n if (isPlugin<PluginContext<TResolvedConfig>>(awaited)) {\n plugins = [awaited];\n } else if (isFunction(awaited)) {\n plugins = toArray(await Promise.resolve(awaited()));\n } else if (isString(awaited)) {\n const resolved = await this.#resolvePlugin(awaited);\n if (isFunction(resolved)) {\n plugins = toArray(await Promise.resolve(resolved()));\n } else {\n plugins = toArray(resolved);\n }\n } else if (\n Array.isArray(awaited) &&\n (awaited as PluginContext<TResolvedConfig>[]).every(\n isPlugin<PluginContext<TResolvedConfig>>\n )\n ) {\n plugins = awaited as Plugin<PluginContext<TResolvedConfig>>[];\n } else if (\n Array.isArray(awaited) &&\n (awaited as PluginConfig<PluginContext<TResolvedConfig>>[]).every(\n isPluginConfig<PluginContext<TResolvedConfig>>\n )\n ) {\n plugins = [];\n for (const pluginConfig of awaited as PluginConfig<\n PluginContext<TResolvedConfig>\n >[]) {\n const initialized = await this.#initPlugin(pluginConfig);\n if (initialized) {\n plugins.push(...initialized);\n }\n }\n } else if (\n isPluginConfigTuple<PluginContext<TResolvedConfig>>(awaited) ||\n isPluginConfigObject<PluginContext<TResolvedConfig>>(awaited)\n ) {\n let pluginConfig!:\n | string\n | PluginFactory<PluginContext<TResolvedConfig>>\n | Plugin<PluginContext<TResolvedConfig>>;\n let pluginOptions: any;\n\n if (isPluginConfigTuple<PluginContext<TResolvedConfig>>(awaited)) {\n pluginConfig = awaited[0] as Plugin<PluginContext<TResolvedConfig>>;\n pluginOptions =\n (awaited as PluginConfigTuple)?.length === 2 ? awaited[1] : undefined;\n } else {\n pluginConfig = (awaited as PluginConfigObject).plugin as Plugin<\n PluginContext<TResolvedConfig>\n >;\n pluginOptions = (awaited as PluginConfigObject).options;\n }\n\n if (isSetString(pluginConfig)) {\n const resolved = await this.#resolvePlugin(pluginConfig);\n if (isFunction(resolved)) {\n plugins = toArray(\n await Promise.resolve(\n pluginOptions ? resolved(pluginOptions) : resolved()\n )\n );\n } else {\n plugins = toArray(resolved);\n }\n } else if (isFunction(pluginConfig)) {\n plugins = toArray(await Promise.resolve(pluginConfig(pluginOptions)));\n } else if (\n Array.isArray(pluginConfig) &&\n pluginConfig.every(isPlugin<PluginContext<TResolvedConfig>>)\n ) {\n plugins = pluginConfig;\n } else if (isPlugin<PluginContext<TResolvedConfig>>(pluginConfig)) {\n plugins = toArray(pluginConfig);\n }\n }\n\n if (!plugins) {\n throw new Error(\n `The plugin configuration ${JSON.stringify(awaited)} is invalid. This configuration must point to a valid Powerlines plugin module.`\n );\n }\n\n if (\n plugins.length > 0 &&\n !plugins.every(isPlugin<PluginContext<TResolvedConfig>>)\n ) {\n throw new Error(\n `The plugin option ${JSON.stringify(plugins)} does not export a valid module. This configuration must point to a valid Powerlines plugin module.`\n );\n }\n\n const result = [] as Plugin<PluginContext<TResolvedConfig>>[];\n for (const plugin of plugins) {\n if (checkDedupe<TResolvedConfig>(plugin, this.context.plugins)) {\n this.context.trace(\n `Duplicate ${chalk.bold.cyanBright(\n plugin.name\n )} plugin dependency detected - Skipping initialization.`\n );\n } else {\n result.push(plugin);\n\n this.context.trace(\n `Initializing the ${chalk.bold.cyanBright(plugin.name)} plugin...`\n );\n }\n }\n\n return result;\n }\n\n async #resolvePlugin<TOptions>(\n pluginPath: string\n ): Promise<\n | Plugin<PluginContext<TResolvedConfig>>\n | Plugin<PluginContext<TResolvedConfig>>[]\n | ((\n options?: TOptions\n ) => MaybePromise<\n | Plugin<PluginContext<TResolvedConfig>>\n | Plugin<PluginContext<TResolvedConfig>>[]\n >)\n > {\n if (\n pluginPath.startsWith(\"@\") &&\n pluginPath.split(\"/\").filter(Boolean).length > 2\n ) {\n const splits = pluginPath.split(\"/\").filter(Boolean);\n pluginPath = `${splits[0]}/${splits[1]}`;\n }\n\n const isInstalled = isPackageExists(pluginPath, {\n paths: [\n this.context.workspaceConfig.workspaceRoot,\n this.context.config.root\n ]\n });\n if (!isInstalled && this.context.config.autoInstall) {\n this.#context.warn(\n `The plugin package \"${\n pluginPath\n }\" is not installed. It will be installed automatically.`\n );\n\n const result = await install(pluginPath, {\n cwd: this.context.config.root\n });\n if (isNumber(result.exitCode) && result.exitCode > 0) {\n this.#context.error(result.stderr);\n\n throw new Error(\n `An error occurred while installing the build plugin package \"${\n pluginPath\n }\" `\n );\n }\n }\n\n try {\n // First check if the package has a \"plugin\" subdirectory - @scope/package/plugin\n const module = await this.context.resolver.plugin.import<{\n plugin?:\n | Plugin<PluginContext<TResolvedConfig>>\n | ((\n options?: TOptions\n ) => MaybePromise<Plugin<PluginContext<TResolvedConfig>>>);\n default?:\n | Plugin<PluginContext<TResolvedConfig>>\n | ((\n options?: TOptions\n ) => MaybePromise<Plugin<PluginContext<TResolvedConfig>>>);\n }>(\n this.context.resolver.plugin.esmResolve(joinPaths(pluginPath, \"plugin\"))\n );\n\n const result = module.plugin ?? module.default;\n if (!result) {\n throw new Error(\n `The plugin package \"${pluginPath}\" does not export a valid module.`\n );\n }\n\n return result;\n } catch (error) {\n try {\n const module = await this.context.resolver.plugin.import<{\n plugin?:\n | Plugin<PluginContext<TResolvedConfig>>\n | ((\n options?: TOptions\n ) => MaybePromise<Plugin<PluginContext<TResolvedConfig>>>);\n default?:\n | Plugin<PluginContext<TResolvedConfig>>\n | ((\n options?: TOptions\n ) => MaybePromise<Plugin<PluginContext<TResolvedConfig>>>);\n }>(this.context.resolver.plugin.esmResolve(pluginPath));\n\n const result = module.plugin ?? module.default;\n if (!result) {\n throw new Error(\n `The plugin package \"${pluginPath}\" does not export a valid module.`\n );\n }\n\n return result;\n } catch {\n if (!isInstalled) {\n throw new Error(\n `The plugin package \"${\n pluginPath\n }\" is not installed. Please install the package using the command: \"npm install ${\n pluginPath\n } --save-dev\"`\n );\n } else {\n throw new Error(\n `An error occurred while importing the build plugin package \"${\n pluginPath\n }\":\n${isError(error) ? error.message : String(error)}\n\nNote: Please ensure the plugin package's default export is a class that extends \\`Plugin\\` with a constructor that excepts a single arguments of type \\`PluginOptions\\`.`\n );\n }\n }\n }\n }\n}\n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