@powerlines/plugin-rollup 0.7.56 → 0.7.58

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.
Files changed (59) hide show
  1. package/README.md +8 -2
  2. package/dist/helpers/index.cjs +1 -1
  3. package/dist/helpers/index.d.cts +4 -25
  4. package/dist/helpers/index.d.mts +4 -0
  5. package/dist/helpers/index.mjs +1 -0
  6. package/dist/helpers/unplugin.cjs +1 -7
  7. package/dist/helpers/unplugin.d.cts +3 -28
  8. package/dist/helpers/unplugin.d.mts +3 -0
  9. package/dist/helpers/unplugin.mjs +1 -0
  10. package/dist/helpers-CRPRhztf.mjs +1 -0
  11. package/dist/index-9iG2qHLe.d.mts +1 -0
  12. package/dist/index-D4ELpJXS.d.cts +1 -0
  13. package/dist/index-D6CnpA_r.d.cts +1 -0
  14. package/dist/index-DL0uimUT.d.mts +1 -0
  15. package/dist/index.cjs +1 -7
  16. package/dist/index.d.cts +9 -28
  17. package/dist/index.d.cts.map +1 -0
  18. package/dist/index.d.mts +14 -0
  19. package/dist/index.d.mts.map +1 -0
  20. package/dist/index.mjs +2 -0
  21. package/dist/index.mjs.map +1 -0
  22. package/dist/plugin-BjiGfRHE.mjs +1 -0
  23. package/dist/plugin-bQr2Yzym.d.cts +1656 -0
  24. package/dist/plugin-bQr2Yzym.d.cts.map +1 -0
  25. package/dist/plugin-pBKbb5K9.cjs +0 -0
  26. package/dist/plugin-ziWFtAvF.d.mts +1659 -0
  27. package/dist/plugin-ziWFtAvF.d.mts.map +1 -0
  28. package/dist/types/index.cjs +1 -1
  29. package/dist/types/index.d.cts +3 -23
  30. package/dist/types/index.d.mts +3 -0
  31. package/dist/types/index.mjs +1 -0
  32. package/dist/types/plugin.cjs +1 -1
  33. package/dist/types/plugin.d.cts +2 -23
  34. package/dist/types/plugin.d.mts +2 -0
  35. package/dist/types/plugin.mjs +1 -0
  36. package/dist/types-n6NgD0QK.mjs +1 -0
  37. package/dist/types-o3zWarRp.cjs +0 -0
  38. package/dist/unplugin-Bx3t7ZoA.d.cts +8 -0
  39. package/dist/unplugin-Bx3t7ZoA.d.cts.map +1 -0
  40. package/dist/unplugin-CLsmVZMo.cjs +44 -0
  41. package/dist/unplugin-Rgj8lLxv.mjs +7 -0
  42. package/dist/unplugin-Rgj8lLxv.mjs.map +1 -0
  43. package/dist/unplugin-jgdfbAHn.d.mts +8 -0
  44. package/dist/unplugin-jgdfbAHn.d.mts.map +1 -0
  45. package/package.json +52 -34
  46. package/dist/chunk-FBBMZ4NC.cjs +0 -7
  47. package/dist/chunk-UCUR73HG.js +0 -7
  48. package/dist/helpers/index.d.ts +0 -25
  49. package/dist/helpers/index.js +0 -1
  50. package/dist/helpers/unplugin.d.ts +0 -28
  51. package/dist/helpers/unplugin.js +0 -7
  52. package/dist/index-DwNsvBx_.d.cts +0 -1567
  53. package/dist/index-DwNsvBx_.d.ts +0 -1567
  54. package/dist/index.d.ts +0 -33
  55. package/dist/index.js +0 -7
  56. package/dist/types/index.d.ts +0 -23
  57. package/dist/types/index.js +0 -1
  58. package/dist/types/plugin.d.ts +0 -23
  59. /package/dist/{types/plugin.js → helpers-LF26RHol.cjs} +0 -0
@@ -0,0 +1 @@
1
+ {"version":3,"file":"unplugin-Rgj8lLxv.mjs","names":["#context","defu","diagnosticMessages: string[]","tsconfigFilePath: string | undefined","defu","defu","defu","resolvedUserConfig: Partial<ParsedUserConfig>","resolvedUserConfigFile: string | undefined","loadConfigC12","defu","joinPaths","resolve","joinPaths","#isDisposed","#context","#normalizePath","#storage","capnp","#metadata","#normalizeId","#paths","#resolverCache","ret","#ids","#log","#getStorage","#getStorages","results: string[]","#buildRegex","result!: string | undefined","#isDisposed","index","storage","#internal","#tsconfig","#fs","#checksum","#buildId","#releaseId","#timestamp","#workspaceConfig","#envPaths","joinPaths","#program","#parserCache","#requestCache","result!: ParseResult","defu","cacheKey: ConfigCacheKey","#getConfigProps","log: LogFn","#hooks","#environments","#log","#plugins","context: UNSAFE_EnvironmentContext<TResolvedConfig>","environment: EnvironmentContext<TResolvedConfig> | undefined","#context","#addPlugin","#executeEnvironments","result","files","context","#getEnvironments","#initPlugin","plugin!: Plugin<PluginContext<TResolvedConfig>>","#resolvePlugin","pluginConfig!:\n | string\n | PluginFactory<PluginContext<TResolvedConfig>>\n | Plugin<PluginContext<TResolvedConfig>>","pluginOptions: any","entry","transformed: TransformResult | string","result: TransformResult | string | undefined"],"sources":["../../powerlines/src/internal/babel/module-resolver-plugin.ts","../../powerlines/src/lib/typescript/ts-morph.ts","../../powerlines/src/internal/helpers/generate-types.ts","../../powerlines/src/internal/helpers/hooks.ts","../../powerlines/src/internal/helpers/install.ts","../../powerlines/src/internal/helpers/install-dependencies.ts","../../powerlines/src/lib/typescript/tsconfig.ts","../../powerlines/src/internal/helpers/resolve-tsconfig.ts","../../powerlines/src/internal/helpers/environment.ts","../../powerlines/src/lib/config-file.ts","../../powerlines/src/internal/helpers/resolver.ts","../../powerlines/src/types/commands.ts","../../powerlines/src/plugin-utils/helpers.ts","../../powerlines/src/plugin-utils/paths.ts","../../powerlines/src/lib/entry.ts","../../powerlines/schemas/fs.ts","../../powerlines/src/types/fs.ts","../../powerlines/src/lib/logger.ts","../../powerlines/src/lib/fs/helpers.ts","../../powerlines/src/lib/fs/storage/base.ts","../../powerlines/src/lib/fs/storage/file-system.ts","../../powerlines/src/lib/fs/storage/virtual.ts","../../powerlines/src/lib/fs/vfs.ts","../../powerlines/src/lib/utilities/meta.ts","../../powerlines/src/lib/contexts/context.ts","../../powerlines/src/types/plugin.ts","../../powerlines/src/lib/contexts/plugin-context.ts","../../powerlines/src/lib/contexts/environment-context.ts","../../powerlines/src/lib/contexts/api-context.ts","../../powerlines/src/lib/utilities/file-header.ts","../../powerlines/src/api.ts","../../powerlines/src/lib/utilities/source-file.ts","../../powerlines/src/lib/unplugin/helpers.ts","../../powerlines/src/lib/unplugin/plugin.ts","../src/helpers/unplugin.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 { NodePath, PluginPass, Visitor } from \"@babel/core\";\nimport { BabelAPI, declare } from \"@babel/helper-plugin-utils\";\nimport * as t from \"@babel/types\";\nimport { Context } from \"../../types/context\";\n\ntype ModuleResolverPluginPass = PluginPass & {\n context: Context;\n moduleResolverVisited: Set<any>;\n api: BabelAPI;\n};\n\nfunction resolveModulePath(\n nodePath: NodePath<t.StringLiteral | null | undefined>,\n state: ModuleResolverPluginPass\n) {\n if (!t.isStringLiteral(nodePath.node)) {\n return;\n }\n\n const sourcePath = nodePath.node.value;\n // const currentFile = state.file.opts.filename;\n\n const resolvedPath = state.context?.fs.resolveSync(sourcePath);\n if (resolvedPath) {\n nodePath.replaceWith(\n t.stringLiteral(\n // Remove the file extension if it exists\n resolvedPath.replace(/\\.(?:ts|mts|cts)x?$/, \"\")\n )\n );\n }\n}\n\nconst TRANSFORM_FUNCTIONS = [\n \"require\",\n \"require.resolve\",\n \"System.import\",\n\n // Jest methods\n \"jest.genMockFromModule\",\n \"jest.mock\",\n \"jest.unmock\",\n \"jest.doMock\",\n // eslint-disable-next-line @cspell/spellchecker\n \"jest.dontMock\",\n \"jest.setMock\",\n \"jest.requireActual\",\n \"jest.requireMock\",\n\n // Older Jest methods\n \"require.requireActual\",\n \"require.requireMock\"\n];\n\nfunction matchesPattern(\n state: ModuleResolverPluginPass,\n calleePath: NodePath,\n pattern: string\n) {\n const { node } = calleePath;\n\n if (t.isMemberExpression(node)) {\n return calleePath.matchesPattern(pattern);\n }\n\n if (!t.isIdentifier(node) || pattern.includes(\".\")) {\n return false;\n }\n\n const name = pattern.split(\".\")[0];\n\n return node.name === name;\n}\n\nconst importVisitors = {\n CallExpression: (\n nodePath: NodePath<t.CallExpression>,\n state: ModuleResolverPluginPass\n ) => {\n if (state.moduleResolverVisited.has(nodePath)) {\n return;\n }\n\n const calleePath = nodePath.get(\"callee\");\n if (\n (calleePath &&\n TRANSFORM_FUNCTIONS.some(pattern =>\n matchesPattern(state, calleePath, pattern)\n )) ||\n t.isImport(nodePath.node.callee)\n ) {\n state.moduleResolverVisited.add(nodePath);\n resolveModulePath(\n nodePath.get(\"arguments.0\") as NodePath<t.StringLiteral>,\n state\n );\n }\n },\n // eslint-disable-next-line ts/naming-convention\n \"ImportDeclaration|ExportDeclaration|ExportAllDeclaration\": (\n nodePath: NodePath<\n t.ImportDeclaration | t.ExportDeclaration | t.ExportAllDeclaration\n >,\n state: ModuleResolverPluginPass\n ) => {\n if (\n !nodePath ||\n !nodePath.get(\"source\") ||\n state.moduleResolverVisited.has(nodePath)\n ) {\n return;\n }\n\n state.moduleResolverVisited.add(nodePath);\n resolveModulePath(nodePath.get(\"source\"), state);\n }\n} as Visitor<ModuleResolverPluginPass>;\n\nexport const moduleResolverBabelPlugin = (context: Context) => {\n return declare(function builder(api: BabelAPI) {\n let moduleResolverVisited = new Set();\n\n return {\n name: \"powerlines:module-resolver\",\n manipulateOptions(opts) {\n opts.filename ??= \"unknown\";\n },\n\n pre() {\n // We need to keep track of all handled nodes so we do not try to transform them twice,\n // because we run before (enter) and after (exit) all nodes are handled\n moduleResolverVisited = new Set();\n },\n\n visitor: {\n Program: {\n enter(programPath: NodePath<t.Program>, state: PluginPass) {\n programPath.traverse(importVisitors, {\n ...state,\n context,\n moduleResolverVisited,\n api\n } as ModuleResolverPluginPass);\n },\n exit(programPath, state) {\n programPath.traverse(importVisitors, {\n ...state,\n context,\n moduleResolverVisited,\n api\n } as ModuleResolverPluginPass);\n }\n }\n },\n\n post() {\n moduleResolverVisited.clear();\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 { LogLevelLabel } from \"@storm-software/config-tools/types\";\nimport defu from \"defu\";\nimport {\n CompilerOptions,\n FileSystemHost,\n InMemoryFileSystemHost,\n Project,\n ProjectOptions,\n RuntimeDirEntry\n} from \"ts-morph\";\nimport { Context } from \"../../types/context\";\n\nexport class VirtualFileSystemHost\n extends InMemoryFileSystemHost\n implements FileSystemHost\n{\n #context: Context;\n\n public constructor(context: Context) {\n super();\n\n this.#context = context;\n }\n\n public override deleteSync(path: string) {\n this.#context.fs.removeSync(path);\n }\n\n public override readDirSync(dirPath: string): RuntimeDirEntry[] {\n if (!this.#context.fs.isDirectorySync(dirPath)) {\n return [];\n }\n\n return this.#context.fs.listSync(dirPath).reduce((ret, entry) => {\n const fullPath = this.#context.fs.resolveSync(entry);\n if (fullPath) {\n ret.push({\n name: entry,\n isDirectory: this.#context.fs.isDirectorySync(fullPath),\n isFile: this.#context.fs.isFileSync(fullPath),\n isSymlink: false\n });\n }\n\n return ret;\n }, [] as RuntimeDirEntry[]);\n }\n\n public override async readFile(filePath: string) {\n if (!this.#context.fs.isFileSync(filePath)) {\n return \"\";\n }\n\n return (await this.#context.fs.read(filePath))!;\n }\n\n public override readFileSync(filePath: string) {\n if (!this.#context.fs.isFileSync(filePath)) {\n return \"\";\n }\n\n return this.#context.fs.readSync(filePath)!;\n }\n\n public override async writeFile(filePath: string, fileText: string) {\n return this.#context.fs.write(filePath, fileText);\n }\n\n public override writeFileSync(filePath: string, fileText: string) {\n this.#context.fs.writeSync(filePath, fileText);\n }\n\n public override async mkdir(dirPath: string) {\n await this.#context.fs.mkdir(dirPath);\n }\n\n public override mkdirSync(dirPath: string) {\n this.#context.fs.mkdirSync(dirPath);\n }\n\n public override async move(srcPath: string, destPath: string) {\n await this.#context.fs.move(srcPath, destPath);\n }\n\n public override moveSync(srcPath: string, destPath: string) {\n this.#context.fs.moveSync(srcPath, destPath);\n }\n\n public override async copy(srcPath: string, destPath: string) {\n await this.#context.fs.copy(srcPath, destPath);\n }\n\n public override copySync(srcPath: string, destPath: string) {\n this.#context.fs.copySync(srcPath, destPath);\n }\n\n public override async fileExists(filePath: string) {\n return this.#context.fs.isFile(filePath);\n }\n\n public override fileExistsSync(filePath: string) {\n return this.#context.fs.isFileSync(filePath);\n }\n\n public override async directoryExists(dirPath: string) {\n return this.#context.fs.isDirectory(dirPath);\n }\n\n public override directoryExistsSync(dirPath: string): boolean {\n return this.#context.fs.isDirectorySync(dirPath);\n }\n\n public override realpathSync(path: string) {\n return this.#context.fs.resolveSync(path) || path;\n }\n\n public override getCurrentDirectory() {\n return this.#context.workspaceConfig.workspaceRoot;\n }\n\n public override async glob(\n patterns: ReadonlyArray<string>\n ): Promise<string[]> {\n return this.#context.fs.glob(patterns as string[]);\n }\n\n public override globSync(patterns: ReadonlyArray<string>): string[] {\n return this.#context.fs.globSync(patterns as string[]);\n }\n}\n\n/**\n * Create a ts-morph {@link Project} instance used for type reflection and module manipulation during processing\n *\n * @param context - The Powerlines context\n * @returns A ts-morph {@link Project} instance\n */\nexport function createProgram(\n context: Context,\n override: Partial<ProjectOptions>\n): Project {\n context.log(\n LogLevelLabel.TRACE,\n `Creating ts-morph Project instance with configuration from: ${\n context.tsconfig.tsconfigFilePath\n }.`\n );\n\n const project = new Project(\n defu(override ?? {}, {\n skipAddingFilesFromTsConfig: false,\n tsConfigFilePath: context.tsconfig.tsconfigFilePath,\n fileSystem: new VirtualFileSystemHost(context),\n compilerOptions: defu(context.tsconfig.options ?? {}, {\n lib: [\"lib.esnext.full.d.ts\"]\n }) as CompilerOptions\n })\n );\n\n return project;\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 { flattenDiagnosticMessageText } from \"typescript\";\nimport { createProgram } from \"../../lib/typescript/ts-morph\";\nimport { Context } from \"../../types/context\";\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 emitTypes<TContext extends Context>(\n context: TContext,\n files: string[]\n) {\n context.log(\n LogLevelLabel.TRACE,\n `Running the TypeScript compiler for ${\n files.length\n } generated runtime files.`\n );\n\n const program = createProgram(context, {\n skipAddingFilesFromTsConfig: true\n });\n\n program.addSourceFilesAtPaths(files);\n const result = program.emitToMemory({ emitOnlyDtsFiles: true });\n\n let builtinModules = \"\";\n for (const file of result.getFiles()) {\n if (!file.filePath.endsWith(\".map\")) {\n if (\n context.builtins.some(\n builtin =>\n builtin === file.filePath ||\n (context.fs.metadata[builtin]?.id &&\n context.fs.metadata[builtin]?.id === file.filePath)\n )\n ) {\n const module = await context.fs.resolve(file.filePath);\n\n builtinModules += `\n declare module \"${module}\" {\n ${file.text\n .trim()\n .replace(/^\\s*export\\s*declare\\s*/gm, \"export \")\n .replace(/^\\s*declare\\s*/gm, \"\")}\n }\n `;\n }\n }\n }\n\n const diagnosticMessages: string[] = [];\n result.getDiagnostics().forEach(diagnostic => {\n if (diagnostic.getSourceFile()?.getBaseName()) {\n diagnosticMessages.push(\n `${diagnostic.getSourceFile()?.getBaseName()} (${\n (diagnostic.getLineNumber() ?? 0) + 1\n }): ${flattenDiagnosticMessageText(\n diagnostic.getMessageText().toString(),\n \"\\n\"\n )}`\n );\n } else {\n diagnosticMessages.push(\n flattenDiagnosticMessageText(\n diagnostic.getMessageText().toString(),\n \"\\n\"\n )\n );\n }\n });\n\n const diagnosticMessage = diagnosticMessages.join(\"\\n\");\n if (diagnosticMessage) {\n throw new Error(\n `TypeScript compilation failed: \\n\\n${\n diagnosticMessage.length > 5000\n ? `${diagnosticMessage.slice(0, 5000)}...`\n : diagnosticMessage\n }`\n );\n }\n\n return formatTypes(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 { LogLevelLabel } from \"@storm-software/config-tools/types\";\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 { MaybePromise } from \"@stryke/types/base\";\nimport chalk from \"chalk\";\nimport { createDefu, defu } from \"defu\";\nimport {\n EnvironmentContext,\n PluginContext,\n SelectHooksOptions\n} from \"../../types/context\";\nimport {\n HookKeys,\n InferHookParameters,\n InferHookReturnType\n} from \"../../types/hooks\";\nimport { ResolvedConfig } from \"../../types/resolved\";\n\nexport type CallHookOptions = SelectHooksOptions &\n (\n | ({\n /**\n * Whether to call the hooks sequentially or in parallel.\n *\n * @defaultValue true\n */\n sequential?: true;\n } & (\n | {\n /**\n * How to handle multiple return values from hooks.\n * - \"merge\": Merge all non-undefined return values (if they are objects).\n * - \"first\": Return the first non-undefined value.\n *\n * @remarks\n * Merging only works if the return values are objects.\n *\n * @defaultValue \"merge\"\n */\n result: \"first\";\n }\n | {\n /**\n * How to handle multiple return values from hooks.\n * - \"merge\": Merge all non-undefined return values (if they are objects).\n * - \"first\": Return the first non-undefined value.\n *\n * @remarks\n * Merging only works if the return values are objects.\n *\n * @defaultValue \"merge\"\n */\n result?: \"merge\" | \"last\";\n\n /**\n * An indicator specifying if the results of the previous hook should be provided as the **first** parameter of the next hook function, or a function to process the result of the previous hook function and pass the returned value as the next hook's **first** parameter\n */\n asNextParam?: false | ((previousResult: any) => MaybePromise<any>);\n }\n ))\n | {\n /**\n * Whether to call the hooks sequentially or in parallel.\n */\n sequential: false;\n }\n );\n\nconst mergeResults = 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 * Calls a hook with the given context, options, and arguments.\n *\n * @param context - The context to use when calling the hook.\n * @param hook - 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 TContext extends EnvironmentContext<TResolvedConfig> =\n EnvironmentContext<TResolvedConfig>,\n TKey extends HookKeys<ArrayValues<TContext[\"plugins\"]>[\"context\"]> = HookKeys<\n ArrayValues<TContext[\"plugins\"]>[\"context\"]\n >\n>(\n context: TContext,\n hook: TKey,\n options: CallHookOptions,\n ...args: InferHookParameters<PluginContext<TContext[\"config\"]>, TKey>\n): Promise<\n InferHookReturnType<PluginContext<TContext[\"config\"]>, TKey> | undefined\n> {\n const handlers = context.selectHooks(hook, options);\n if (handlers.length > 0) {\n context.log(\n LogLevelLabel.DEBUG,\n ` 🧩 Calling plugin hook: ${chalk.bold.cyanBright(\n `${hook}${options?.order ? ` (${options.order})` : \"\"}`\n )}`\n );\n\n let results = [] as InferHookReturnType<\n PluginContext<TContext[\"config\"]>,\n TKey\n >[];\n if (options?.sequential === false) {\n results = await Promise.all(\n handlers.map(async handler => {\n if (!isFunction(handler.handle)) {\n throw new Error(\n `Plugin hook handler for hook \"${hook}\" is not a function.`\n );\n }\n\n return Promise.resolve(\n // eslint-disable-next-line ts/no-unsafe-call\n handler.handle.apply(handler.context, [...args])\n );\n })\n );\n } else {\n for (const handler of handlers) {\n if (!isFunction(handler.handle)) {\n throw new Error(\n `Plugin hook handler for hook \"${hook}\" is not a function.`\n );\n }\n\n if (options?.result === \"first\" || options?.asNextParam === false) {\n results.push(\n await Promise.resolve(\n // eslint-disable-next-line ts/no-unsafe-call\n handler.handle.apply(handler.context, [...args])\n )\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 // eslint-disable-next-line ts/no-unsafe-call\n handler.handle.apply(handler.context, [...sequenceArgs])\n );\n if (result) {\n if (options?.result === \"last\") {\n results = [result];\n } else if (isString(result)) {\n results = [\n `${isString(results[0]) ? results[0] || \"\" : \"\"}\\n${result || \"\"}`.trim() as InferHookReturnType<\n PluginContext<TContext[\"config\"]>,\n TKey\n >\n ];\n } else if (isObject(result)) {\n results = [\n mergeResults(result, results[0] ?? {}) as InferHookReturnType<\n PluginContext<TContext[\"config\"]>,\n TKey\n >\n ];\n }\n }\n }\n }\n }\n\n const definedResults = results.filter(\n (\n result\n ): result is NonNullable<\n InferHookReturnType<PluginContext<TContext[\"config\"]>, TKey>\n > => isSet(result)\n );\n\n if (definedResults.length > 0) {\n let mergedResult = undefined as\n | InferHookReturnType<PluginContext<TContext[\"config\"]>, 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<TContext[\"config\"]>, 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 { LogLevelLabel } from \"@storm-software/config-tools/types\";\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/context\";\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.projectRoot\n }))\n ) {\n if (context.config.skipInstalls !== true) {\n context.log(\n LogLevelLabel.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.projectRoot,\n dev\n });\n if (isNumber(result.exitCode) && result.exitCode > 0) {\n context.log(LogLevelLabel.ERROR, result.stderr);\n throw new Error(\n `An error occurred while installing the package \"${packageName}\"`\n );\n }\n } else {\n context.log(\n LogLevelLabel.WARN,\n `The package \"${packageName}\" is not installed. Since the \"skipInstalls\" option is set to true, 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.projectRoot\n );\n if (!isMatching) {\n const packageListing = await getPackageListing(\n getPackageName(packageName),\n {\n cwd: context.config.projectRoot\n }\n );\n if (\n !packageListing?.version.startsWith(\"catalog:\") &&\n !packageListing?.version.startsWith(\"workspace:\")\n ) {\n context.log(\n LogLevelLabel.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 { LogLevelLabel } from \"@storm-software/config-tools/types\";\nimport { getPackageName } from \"@stryke/string-format/package\";\nimport { Context } from \"../../types/context\";\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.log(\n LogLevelLabel.TRACE,\n `Checking and installing missing project dependencies.`\n );\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.log(\n LogLevelLabel.TRACE,\n `No dependencies or devDependencies to install. Skipping installation step.`\n );\n return;\n }\n\n context.log(\n LogLevelLabel.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 { readJsonFileSync } from \"@stryke/fs/json\";\nimport { appendPath } from \"@stryke/path/append\";\nimport { joinPaths } from \"@stryke/path/join-paths\";\nimport { FilterPattern } from \"@stryke/types/file\";\nimport { TsConfigJson } from \"@stryke/types/tsconfig\";\nimport defu from \"defu\";\nimport ts from \"typescript\";\nimport { ParsedTypeScriptConfig, TSConfig } from \"../../types/tsconfig\";\n\n/**\n * Get the path to the tsconfig.json file.\n *\n * @param workspaceRoot - The root directory of the workspace.\n * @param projectRoot - The root directory of the project.\n * @param tsconfig - The path to the tsconfig.json file.\n * @returns The absolute path to the tsconfig.json file.\n * @throws If the tsconfig.json file does not exist.\n */\nexport function getTsconfigFilePath(\n workspaceRoot: string,\n projectRoot: string,\n tsconfig?: string\n): string {\n let tsconfigFilePath: string | undefined;\n if (tsconfig) {\n tsconfigFilePath = tryTsconfigFilePath(\n workspaceRoot,\n projectRoot,\n tsconfig\n );\n } else {\n tsconfigFilePath = tryTsconfigFilePath(\n workspaceRoot,\n projectRoot,\n \"tsconfig.app.json\"\n );\n if (!tsconfigFilePath) {\n tsconfigFilePath = tryTsconfigFilePath(\n workspaceRoot,\n projectRoot,\n \"tsconfig.lib.json\"\n );\n if (!tsconfigFilePath) {\n tsconfigFilePath = tryTsconfigFilePath(\n workspaceRoot,\n projectRoot,\n \"tsconfig.json\"\n );\n }\n }\n }\n\n if (!tsconfigFilePath) {\n throw new Error(\n `Cannot find the \\`tsconfig.json\\` configuration file for the project at ${\n projectRoot\n }.`\n );\n }\n\n return tsconfigFilePath;\n}\n\n/**\n * Get the path to the tsconfig.json file.\n *\n * @param workspaceRoot - The root directory of the workspace.\n * @param projectRoot - The root directory of the project.\n * @param tsconfig - The path to the tsconfig.json file.\n * @returns The absolute path to the tsconfig.json file.\n * @throws If the tsconfig.json file does not exist.\n */\nexport function tryTsconfigFilePath(\n workspaceRoot: string,\n projectRoot: string,\n tsconfig: string\n): string | undefined {\n let tsconfigFilePath = tsconfig;\n if (!existsSync(tsconfigFilePath)) {\n tsconfigFilePath = appendPath(tsconfig, projectRoot);\n if (!existsSync(tsconfigFilePath)) {\n tsconfigFilePath = appendPath(\n tsconfig,\n appendPath(projectRoot, workspaceRoot)\n );\n if (!existsSync(tsconfigFilePath)) {\n return undefined;\n }\n }\n }\n\n return tsconfigFilePath;\n}\n\n/**\n * Check if the TypeScript configuration type matches any of the provided types.\n *\n * @param tsconfigType - The type from the TypeScript configuration.\n * @param types - An array of type names to check against.\n * @returns True if the TypeScript configuration type matches any of the provided types, false otherwise.\n */\nexport function findMatch(\n tsconfigType: string | RegExp | null,\n types: (string | RegExp | null)[],\n extensions: string[] = [\".ts\", \".tsx\", \".d.ts\"]\n): string | RegExp | null | undefined {\n return types.find(\n type =>\n tsconfigType?.toString().toLowerCase() ===\n type?.toString().toLowerCase() ||\n tsconfigType?.toString().toLowerCase() ===\n `./${type?.toString().toLowerCase()}` ||\n `./${tsconfigType?.toString().toLowerCase()}` ===\n type?.toString().toLowerCase() ||\n extensions.some(\n ext =>\n `${tsconfigType?.toString().toLowerCase()}${ext}` ===\n type?.toString().toLowerCase() ||\n `${tsconfigType?.toString().toLowerCase()}${ext}` ===\n `./${type?.toString().toLowerCase()}` ||\n `${type?.toString().toLowerCase()}${ext}` ===\n `./${tsconfigType?.toString().toLowerCase()}` ||\n tsconfigType?.toString().toLowerCase() ===\n `${type?.toString().toLowerCase()}${ext}` ||\n tsconfigType?.toString().toLowerCase() ===\n `./${type?.toString().toLowerCase()}${ext}` ||\n type?.toString().toLowerCase() ===\n `./${tsconfigType?.toString().toLowerCase()}${ext}`\n )\n );\n}\n\n/**\n * Check if the TypeScript configuration type matches any of the provided types.\n *\n * @param tsconfigType - The type from the TypeScript configuration.\n * @param types - An array of type names to check against.\n * @returns True if the TypeScript configuration type matches any of the provided types, false otherwise.\n */\nexport function findIncludeMatch(\n tsconfigType: string | RegExp | null,\n types: (string | RegExp | null)[]\n): string | RegExp | null | undefined {\n return findMatch(tsconfigType, types, [\n \".ts\",\n \".tsx\",\n \".d.ts\",\n \".js\",\n \".jsx\",\n \".mjs\",\n \".cjs\",\n \".mts\",\n \".cts\",\n \"/*.ts\",\n \"/*.tsx\",\n \"/*.d.ts\",\n \"/*.js\",\n \"/*.jsx\",\n \"/*.mjs\",\n \"/*.cjs\",\n \"/*.mts\",\n \"/*.cts\",\n \"/**/*.ts\",\n \"/**/*.tsx\",\n \"/**/*.d.ts\",\n \"/**/*.js\",\n \"/**/*.jsx\",\n \"/**/*.mjs\",\n \"/**/*.cjs\",\n \"/**/*.mts\",\n \"/**/*.cts\"\n ]);\n}\n\n/**\n * Check if the TypeScript configuration type matches any of the provided types.\n *\n * @param tsconfigType - The type from the TypeScript configuration.\n * @param types - An array of type names to check against.\n * @returns True if the TypeScript configuration type matches any of the provided types, false otherwise.\n */\nexport function isMatchFound(\n tsconfigType: string | RegExp | null,\n types: (string | RegExp | null)[]\n): boolean {\n return findMatch(tsconfigType, types) !== undefined;\n}\n\n/**\n * Check if the TypeScript configuration type matches any of the provided types.\n *\n * @param tsconfigType - The type from the TypeScript configuration.\n * @param types - An array of type names to check against.\n * @returns True if the TypeScript configuration type matches any of the provided types, false otherwise.\n */\nexport function isIncludeMatchFound(\n tsconfigType: FilterPattern,\n types: FilterPattern[]\n): boolean {\n return (\n findIncludeMatch(\n tsconfigType as string | RegExp | null,\n types as (string | RegExp | null)[]\n ) !== undefined\n );\n}\n\n/**\n * Get the parsed TypeScript configuration.\n *\n * @param workspaceRoot - The root directory of the workspace.\n * @param projectRoot - The root directory of the project.\n * @param tsconfig - The path to the tsconfig.json file.\n * @param tsconfigRaw - The raw tsconfig.json content.\n * @param originalTsconfigJson - The original tsconfig.json content.\n * @param host - The TypeScript parse config host.\n * @returns The resolved TypeScript configuration.\n */\nexport function getParsedTypeScriptConfig(\n workspaceRoot: string,\n projectRoot: string,\n tsconfig?: string,\n tsconfigRaw: TSConfig = {},\n originalTsconfigJson?: TSConfig,\n host: ts.ParseConfigHost = ts.sys\n): ParsedTypeScriptConfig {\n const tsconfigFilePath = getTsconfigFilePath(\n workspaceRoot,\n projectRoot,\n tsconfig\n );\n const tsconfigJson = readJsonFileSync<TSConfig>(tsconfigFilePath);\n if (!tsconfigJson) {\n throw new Error(\n `Cannot find the \\`tsconfig.json\\` configuration file at ${joinPaths(\n projectRoot,\n tsconfig ?? \"tsconfig.json\"\n )}`\n );\n }\n\n const parsedCommandLine = ts.parseJsonConfigFileContent(\n defu(tsconfigRaw ?? {}, tsconfigJson),\n host,\n appendPath(projectRoot, workspaceRoot)\n );\n if (parsedCommandLine.errors.length > 0) {\n const errorMessage = `Cannot parse the TypeScript compiler options. Please investigate the following issues:\n${parsedCommandLine.errors\n .map(\n error =>\n `- ${\n (error.category !== undefined && error.code\n ? `[${error.category}-${error.code}]: `\n : \"\") + error.messageText.toString()\n }`\n )\n .join(\"\\n\")}\n `;\n\n throw new Error(errorMessage);\n }\n\n return {\n ...parsedCommandLine,\n originalTsconfigJson: (originalTsconfigJson ??\n tsconfigJson) as TsConfigJson,\n tsconfigJson,\n tsconfigFilePath\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 { Diff, ObjectData } from \"@donedeal0/superdiff\";\nimport { getObjectDiff } from \"@donedeal0/superdiff\";\nimport { LogLevelLabel } from \"@storm-software/config-tools/types\";\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 {\n getParsedTypeScriptConfig,\n getTsconfigFilePath,\n isIncludeMatchFound\n} from \"../../lib/typescript/tsconfig\";\nimport type { EnvironmentContext } from \"../../types/context\";\nimport { ResolvedConfig } from \"../../types/resolved\";\n\nexport function getTsconfigDtsPath<\n TResolvedConfig extends ResolvedConfig = ResolvedConfig\n>(context: EnvironmentContext<TResolvedConfig>): string {\n const dtsRelativePath = joinPaths(\n relativePath(\n joinPaths(\n context.workspaceConfig.workspaceRoot,\n context.config.projectRoot\n ),\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.projectRoot,\n context.config.tsconfig,\n context.config.tsconfigRaw\n );\n\n const tsconfigFilePath = getTsconfigFilePath(\n context.workspaceConfig.workspaceRoot,\n context.config.projectRoot,\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.build.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.log(\n LogLevelLabel.TRACE,\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.projectRoot,\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.log(\n LogLevelLabel.TRACE,\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.projectRoot,\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.log(\n LogLevelLabel.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.projectRoot,\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 { APIContext, Context } from \"../../types/context\";\nimport { EnvironmentResolvedConfig } from \"../../types/resolved\";\n\nexport const DEFAULT_ENVIRONMENT = \"default\" as const;\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.build?.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.build?.platform === \"browser\" ? \"client\" : \"server\",\n preview:\n userConfig.build?.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 { getWorkspaceConfig } from \"@storm-software/config-tools/get-config\";\nimport { existsSync } from \"@stryke/fs/exists\";\nimport { appendPath } from \"@stryke/path/append\";\nimport { joinPaths } from \"@stryke/path/join-paths\";\nimport { replacePath } from \"@stryke/path/replace\";\nimport { isFunction } from \"@stryke/type-checks/is-function\";\nimport { isSetObject } from \"@stryke/type-checks/is-set-object\";\nimport { loadConfig as loadConfigC12 } from \"c12\";\nimport defu from \"defu\";\nimport type { Jiti } from \"jiti\";\nimport type {\n ParsedUserConfig,\n PowerlinesCommand,\n UserConfig,\n WorkspaceConfig\n} from \"../types/config\";\nimport { Context } from \"../types/context\";\n\nexport type PartiallyResolvedContext<TContext extends Context = Context> = Omit<\n TContext,\n \"config\" | \"tsconfig\" | \"entry\" | \"fs\" | \"compiler\" | \"unimport\"\n> &\n Partial<TContext> & {\n config: TContext[\"config\"];\n };\n\n/**\n * Loads the workspace configuration.\n *\n * @param workspaceRoot - The root directory of the workspace.\n * @param cwd - The current working directory to start searching from.\n * @returns A promise that resolves to the loaded workspace configuration.\n */\nexport async function loadWorkspaceConfig(\n workspaceRoot: string,\n cwd: string\n): Promise<WorkspaceConfig> {\n return defu(\n {\n workspaceRoot\n },\n await getWorkspaceConfig(true, {\n cwd,\n workspaceRoot,\n useDefault: true\n })\n );\n}\n\n/**\n * Loads the user configuration file for the project.\n *\n * @param projectRoot - The root directory of the project.\n * @param workspaceRoot - The root directory of the workspace.\n * @param jiti - An instance of Jiti to resolve modules from\n * @param command - The {@link PowerlinesCommand} string associated with the current running process\n * @param mode - The mode in which the project is running (default is \"production\").\n * @param configFile - An optional path to a specific configuration file.\n * @param framework - The framework name to use for default configuration file names.\n * @returns A promise that resolves to the resolved user configuration.\n */\nexport async function loadUserConfigFile(\n projectRoot: string,\n workspaceRoot: string,\n jiti: Jiti,\n command?: PowerlinesCommand,\n mode = \"production\",\n configFile?: string,\n framework = \"powerlines\"\n): Promise<ParsedUserConfig> {\n let resolvedUserConfig: Partial<ParsedUserConfig> = {};\n\n let resolvedUserConfigFile: string | undefined;\n if (configFile) {\n resolvedUserConfigFile = existsSync(replacePath(configFile, projectRoot))\n ? replacePath(configFile, projectRoot)\n : existsSync(\n joinPaths(\n appendPath(projectRoot, workspaceRoot),\n replacePath(configFile, projectRoot)\n )\n )\n ? joinPaths(\n appendPath(projectRoot, workspaceRoot),\n replacePath(configFile, projectRoot)\n )\n : existsSync(\n joinPaths(appendPath(projectRoot, workspaceRoot), configFile)\n )\n ? joinPaths(appendPath(projectRoot, workspaceRoot), configFile)\n : undefined;\n }\n\n if (!resolvedUserConfigFile) {\n resolvedUserConfigFile = existsSync(\n joinPaths(\n appendPath(projectRoot, workspaceRoot),\n `${framework}.${mode}.config.ts`\n )\n )\n ? joinPaths(\n appendPath(projectRoot, workspaceRoot),\n `${framework}.${mode}.config.ts`\n )\n : existsSync(\n joinPaths(\n appendPath(projectRoot, workspaceRoot),\n `${framework}.${mode}.config.js`\n )\n )\n ? joinPaths(\n appendPath(projectRoot, workspaceRoot),\n `${framework}.${mode}.config.js`\n )\n : existsSync(\n joinPaths(\n appendPath(projectRoot, workspaceRoot),\n `${framework}.${mode}.config.mts`\n )\n )\n ? joinPaths(\n appendPath(projectRoot, workspaceRoot),\n `${framework}.${mode}.config.mts`\n )\n : existsSync(\n joinPaths(\n appendPath(projectRoot, workspaceRoot),\n `${framework}.${mode}.config.mjs`\n )\n )\n ? joinPaths(\n appendPath(projectRoot, workspaceRoot),\n `${framework}.${mode}.config.mjs`\n )\n : existsSync(\n joinPaths(\n appendPath(projectRoot, workspaceRoot),\n `${framework}.config.ts`\n )\n )\n ? joinPaths(\n appendPath(projectRoot, workspaceRoot),\n `${framework}.config.ts`\n )\n : existsSync(\n joinPaths(\n appendPath(projectRoot, workspaceRoot),\n `${framework}.config.js`\n )\n )\n ? joinPaths(\n appendPath(projectRoot, workspaceRoot),\n `${framework}.config.js`\n )\n : existsSync(\n joinPaths(\n appendPath(projectRoot, workspaceRoot),\n `${framework}.config.mts`\n )\n )\n ? joinPaths(\n appendPath(projectRoot, workspaceRoot),\n `${framework}.config.mts`\n )\n : existsSync(\n joinPaths(\n appendPath(projectRoot, workspaceRoot),\n `${framework}.config.mjs`\n )\n )\n ? joinPaths(\n appendPath(projectRoot, workspaceRoot),\n `${framework}.config.mjs`\n )\n : undefined;\n }\n\n if (resolvedUserConfigFile) {\n const resolved = await jiti.import(jiti.esmResolve(resolvedUserConfigFile));\n if (resolved) {\n let config = {};\n if (isFunction(resolved)) {\n config = await Promise.resolve(\n resolved({\n command,\n mode,\n isSsrBuild: false,\n isPreview: false\n })\n );\n }\n\n if (isSetObject(config)) {\n resolvedUserConfig = {\n ...config,\n config: config as UserConfig,\n configFile: resolvedUserConfigFile\n };\n }\n }\n }\n\n const result = await loadConfigC12({\n cwd: projectRoot,\n name: framework,\n envName: mode,\n globalRc: true,\n packageJson: true,\n dotenv: true,\n jiti\n });\n\n return defu(\n resolvedUserConfig,\n isSetObject(result?.config) ? { ...result.config, ...result } : {}\n ) as ParsedUserConfig;\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 { Jiti, JitiOptions, createJiti } from \"jiti\";\nimport { Resolver } from \"../../types/context\";\nimport { ResolvedConfig } from \"../../types/resolved\";\n\nexport type CreateResolverOptions = Omit<\n JitiOptions,\n \"fsCache\" | \"moduleCache\" | \"interopDefault\"\n> &\n Pick<ResolvedConfig, \"mode\" | \"logLevel\" | \"skipCache\"> & {\n workspaceRoot: string;\n projectRoot: 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 */\nfunction createPluginResolver(options: CreateResolverOptions): Jiti {\n return createJiti(\n joinPaths(options.workspaceRoot, options.projectRoot),\n resolveOptions({\n ...options\n\n // transform: (params: TransformOptions): TransformResult => {\n // if (!params.filename) {\n // return {\n // code: params.source\n // };\n // }\n\n // const babelOptions = {\n // babelrc: false,\n // configFile: false,\n // compact: false,\n // retainLines: isBoolean(params.retainLines)\n // ? params.retainLines\n // : true,\n // filename: params.filename,\n // plugins: [\n // [\n // transformModuleBabelPlugin,\n // {\n // allowTopLevelThis: true,\n // noInterop: !params.interopDefault,\n // async: params.async\n // }\n // ],\n // [importMetaPathsBabelPlugin, { filename: params.filename }],\n // [importMetaEnvBabelPlugin],\n // [transformMetadataBabelPlugin],\n // [syntaxClassPropertiesPlugin],\n // [transformExportNamespaceFromPlugin]\n // ]\n // } as BabelTransformOptions;\n\n // if (\n // findFileExtension(params.filename) === \"jsx\" ||\n // findFileExtension(params.filename) === \"tsx\"\n // ) {\n // babelOptions.plugins!.push([syntaxJSXPlugin]);\n // babelOptions.plugins!.push([\n // alloyPlugin,\n // {\n // alloyModuleName: \"@alloy-js/core\"\n // }\n // ]);\n // babelOptions.plugins!.push([\n // jsxDomExpressionsPlugin,\n // {\n // alloyModuleName: \"@alloy-js/core\",\n // moduleName: \"@alloy-js/core/jsx-runtime\",\n // generate: \"universal\",\n // wrapConditionals: true,\n // preserveWhitespace: true\n // }\n // ]);\n // }\n\n // if (\n // findFileExtension(params.filename) === \"ts\" ||\n // findFileExtension(params.filename) === \"tsx\"\n // ) {\n // babelOptions.plugins!.push([\n // typescriptPlugin,\n // {\n // allowDeclareFields: true,\n // isTSX: findFileExtension(params.filename) === \"tsx\"\n // }\n // ]);\n\n // babelOptions.plugins!.unshift([transformMetadataBabelPlugin]);\n // babelOptions.plugins!.unshift([\n // proposalDecoratorsPlugin,\n // { legacy: true }\n // ]);\n\n // babelOptions.plugins!.push([parameterDecoratorPlugin]);\n // babelOptions.plugins!.push([syntaxImportAssertionsPlugin]);\n // }\n\n // const result = transformSync(params.source, babelOptions);\n // if (!result?.code) {\n // return {\n // code: params.source,\n // error: new Error(\"Failed to transform source code.\")\n // };\n // }\n\n // return {\n // code: result.code\n // };\n // }\n } as CreateResolverOptions)\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.projectRoot),\n resolveOptions(options)\n ) as Resolver;\n baseResolver.plugin = createPluginResolver(options);\n\n return baseResolver;\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 { ArrayValues } from \"@stryke/types/array\";\nimport type { MaybePromise } from \"@stryke/types/base\";\nimport type { Context } from \"./context\";\n\nexport const SUPPORTED_COMMANDS = [\n \"new\",\n \"clean\",\n \"prepare\",\n \"lint\",\n \"test\",\n \"build\",\n \"docs\",\n \"deploy\",\n \"finalize\"\n] as const;\n\nexport type CommandType = ArrayValues<typeof SUPPORTED_COMMANDS>;\nexport type Commands<TContext extends Context = Context> = Record<\n CommandType,\n (this: TContext) => MaybePromise<void>\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 { isSetObject } from \"@stryke/type-checks/is-set-object\";\nimport { isSetString } from \"@stryke/type-checks/is-set-string\";\nimport { isUndefined } from \"@stryke/type-checks/is-undefined\";\nimport { AnyFunction } from \"@stryke/types/base\";\nimport { SUPPORTED_COMMANDS } from \"../types/commands\";\nimport {\n PluginConfig,\n PluginConfigObject,\n PluginConfigTuple\n} from \"../types/config\";\nimport { PluginContext } from \"../types/context\";\nimport {\n BaseHookKeys,\n BaseHooksListItem,\n ExternalHookKeys,\n HookKeys\n} from \"../types/hooks\";\nimport { Plugin, PluginHook, PluginHookObject } from \"../types/plugin\";\nimport { ResolvedConfig } from \"../types/resolved\";\n\n/**\n * Type guard to check if an object is a {@link Plugin}\n *\n * @param value - The object to check\n * @returns True if the object is a {@link Plugin}, false otherwise\n */\nexport function isPlugin<\n TResolvedConfig extends ResolvedConfig = ResolvedConfig\n>(value: unknown): value is Plugin<PluginContext<TResolvedConfig>> {\n return (\n isSetObject(value) &&\n \"name\" in value &&\n isSetString(value.name) &&\n (isUndefined(\n (value as Plugin<PluginContext<TResolvedConfig>>).applyToEnvironment\n ) ||\n (\"applyToEnvironment\" in value &&\n isFunction(value.applyToEnvironment))) &&\n (isUndefined((value as Plugin<PluginContext<TResolvedConfig>>).dedupe) ||\n (\"dedupe\" in value && isFunction(value.dedupe))) &&\n (isUndefined((value as Plugin<PluginContext<TResolvedConfig>>).dependsOn) ||\n (\"dependsOn\" in value &&\n Array.isArray(value.dependsOn) &&\n value.dependsOn.every(isPluginConfig))) &&\n SUPPORTED_COMMANDS.every(\n command =>\n isUndefined(\n (value as Plugin<PluginContext<TResolvedConfig>>)[command]\n ) ||\n (command in value &&\n (isFunction((value as Record<string, any>)[command]) ||\n (isSetObject((value as Record<string, any>)[command]) &&\n \"handler\" in (value as Record<string, any>)[command] &&\n isFunction((value as Record<string, any>)[command].handler))))\n )\n );\n}\n\n/**\n * Type guard to check if an object is a {@link PluginConfigObject}\n *\n * @param value - The object to check\n * @returns True if the object is a {@link PluginConfigObject}, false otherwise\n */\nexport function isPluginConfigObject(\n value: unknown\n): value is PluginConfigObject {\n return (\n isSetObject(value) &&\n \"plugin\" in value &&\n (((isSetString(value.plugin) || isFunction(value.plugin)) &&\n \"options\" in value &&\n isSetObject(value.options)) ||\n isPlugin(value.plugin))\n );\n}\n\n/**\n * Type guard to check if an object is a {@link PluginConfigTuple}\n *\n * @param value - The object to check\n * @returns True if the object is a {@link PluginConfigTuple}, false otherwise\n */\nexport function isPluginConfigTuple(\n value: unknown\n): value is PluginConfigTuple {\n return (\n Array.isArray(value) &&\n (value.length === 1 || value.length === 2) &&\n (((isSetString(value[0]) || isFunction(value[0])) &&\n value.length > 1 &&\n isSetObject(value[1])) ||\n isPlugin(value[0]))\n );\n}\n\n/**\n * Type guard to check if an object is a {@link PluginConfig}\n *\n * @param value - The object to check\n * @returns True if the object is a {@link PluginConfig}, false otherwise\n */\nexport function isPluginConfig(value: unknown): value is PluginConfig {\n return (\n isSetString(value) ||\n isFunction(value) ||\n isPlugin(value) ||\n isPluginConfigObject(value) ||\n isPluginConfigTuple(value)\n );\n}\n\n/**\n * Type guard to check if an value is a {@link PluginHook} function\n *\n * @param value - The value to check\n * @returns True if the value is a {@link PluginHook} function, false otherwise\n */\nexport function isPluginHookFunction(value: unknown): value is AnyFunction {\n return (\n isFunction(value) ||\n (isSetObject(value) && \"handler\" in value && isFunction(value.handler))\n );\n}\n\n/**\n * Type guard to check if an value is a {@link PluginHook} function\n *\n * @param value - The value to check\n * @returns True if the value is a {@link PluginHook} function, false otherwise\n */\nexport function isPluginHookObject(\n value: unknown\n): value is PluginHookObject<AnyFunction> {\n return isSetObject(value) && \"handler\" in value && isFunction(value.handler);\n}\n\n/**\n * Type guard to check if an object is a {@link PluginHook}\n *\n * @param value - The object to check\n * @returns True if the object is a {@link PluginHook}, false otherwise\n */\nexport function isPluginHook(value: unknown): value is PluginHook<AnyFunction> {\n return isPluginHookFunction(value) || isPluginHookObject(value);\n}\n\n/**\n * Extract the hook handler function from a plugin hook\n *\n * @param pluginHook - The plugin hook to extract the handler function from\n * @returns The hook handler function\n */\nexport function getHookHandler(\n pluginHook: PluginHook<AnyFunction>\n): AnyFunction {\n return isFunction(pluginHook) ? pluginHook : pluginHook.handler;\n}\n\n/**\n * Extract a plugin hook from a plugin\n *\n * @param context - The build context\n * @param plugin - The plugin to extract the hook from\n * @param hook - The name of the hook to extract\n * @returns The extracted hook, or undefined if the hook does not exist\n */\nexport function extractPluginHook<\n TContext extends PluginContext = PluginContext,\n TPlugin extends Plugin<TContext> = Plugin<TContext>\n>(context: TContext, plugin: TPlugin, hook: BaseHookKeys<TContext>) {\n const pluginHook = plugin[hook];\n if (!isPluginHook(pluginHook)) {\n return undefined;\n }\n\n return isFunction(pluginHook)\n ? {\n normal: pluginHook.bind(context)\n }\n : {\n [pluginHook.order ? pluginHook.order : \"normal\"]:\n pluginHook.handler.bind(context)\n };\n}\n\n/**\n * Check if a hook is external.\n *\n * @param hook - The name of the hook to check.\n * @returns True if the hook is external, false otherwise.\n */\nexport function isHookExternal(hook: HookKeys): hook is ExternalHookKeys {\n return (\n hook.startsWith(\"vite:\") ||\n hook.startsWith(\"esbuild:\") ||\n hook.startsWith(\"rolldown:\") ||\n hook.startsWith(\"rollup:\") ||\n hook.startsWith(\"webpack:\") ||\n hook.startsWith(\"rspack:\") ||\n hook.startsWith(\"farm:\")\n );\n}\n\n/**\n * Check if a hook is internal.\n *\n * @param hook - The name of the hook to check.\n * @returns True if the hook is external, false otherwise.\n */\nexport function isHookInternal(hook: HookKeys): hook is BaseHookKeys {\n return !isHookExternal(hook);\n}\n\n/**\n * Check if a plugin should be deduplicated.\n *\n * @param plugin - The plugin to check\n * @param plugins - The list of plugins to check against\n * @returns True if the plugin should be deduplicated, false otherwise\n */\nexport function checkDedupe<\n TResolvedConfig extends ResolvedConfig = ResolvedConfig,\n TContext extends PluginContext<TResolvedConfig> =\n PluginContext<TResolvedConfig>\n>(plugin: Plugin<TContext>, plugins: Plugin<TContext>[]) {\n return (\n plugin.dedupe === false ||\n plugins.some(\n p =>\n p.dedupe !== false &&\n ((isFunction(p.dedupe) && p.dedupe(plugin)) || p.name === plugin.name)\n )\n );\n}\n\n/**\n * Add a plugin hook to the hooks list.\n *\n * @param context - The plugin context\n * @param plugin - The plugin to add the hook from\n * @param pluginHook - The plugin hook to add\n * @param hooksList - The list of hooks to add to\n */\nexport function addPluginHook<TContext extends PluginContext = PluginContext>(\n context: TContext,\n plugin: Plugin<TContext>,\n pluginHook: PluginHook<AnyFunction>,\n hooksList: BaseHooksListItem<TContext, BaseHookKeys<TContext>>[]\n) {\n if (\n !checkDedupe(\n plugin,\n hooksList.map(hook => hook.plugin)\n )\n ) {\n hooksList.push(\n isFunction(pluginHook)\n ? {\n plugin,\n handler: getHookHandler(pluginHook).bind(context)\n }\n : {\n plugin,\n ...pluginHook,\n handler: getHookHandler(pluginHook).bind(context)\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 { replacePath } from \"@stryke/path/replace\";\nimport { IsUndefined } from \"@stryke/types/base\";\nimport { UnresolvedContext } from \"../types/context\";\n\n/**\n * Replaces tokens in the given path string with their corresponding values from the context.\n *\n * @remarks\n * The following tokens are supported:\n * - `{workspaceRoot}` - The root directory of the workspace.\n * - `{root}` - The root directory of the project (same as `{projectRoot}`).\n * - `{projectRoot}` - The root directory of the project (same as `{root}`).\n * - `{sourceRoot}` - The source root directory of the project (usually `./src`).\n * - `{powerlinesPath}` - The directory where Powerlines is installed.\n * - `{cachePath}` - The environment's directory for cached files.\n * - `{dataPath}` - The environment's directory for data files.\n * - `{logPath}` - The environment's directory for log files.\n * - `{tempPath}` - The environment's directory for temporary files.\n * - `{configPath}` - The environment's directory for configuration files.\n * - `{outputPath}` - The configured output directory for the project.\n * - `{buildPath}` - The configured distribution directory for the project.\n * - `{artifactsPath}` - The configured directory for build artifacts.\n * - `{builtinPath}` - The configured directory for generated built-in plugins.\n * - `{entryPath}` - The configured directory for generated entry files.\n *\n * @param context - The context containing the values for the path tokens.\n * @param path - The path string with tokens to replace.\n * @returns The path string with tokens replaced by their corresponding values from the context.\n */\nexport function replacePathTokens(\n context: UnresolvedContext,\n path?: string\n): IsUndefined<typeof path> extends true ? undefined : string {\n if (!path) {\n return path as IsUndefined<typeof path> extends true ? undefined : string;\n }\n\n return path\n .replaceAll(\"{workspaceRoot}\", context.workspaceConfig.workspaceRoot)\n .replaceAll(\"{root}\", context.config.projectRoot)\n .replaceAll(\"{projectRoot}\", context.config.projectRoot)\n .replaceAll(\"{sourceRoot}\", context.config.sourceRoot)\n .replaceAll(\"{powerlinesPath}\", context.powerlinesPath)\n .replaceAll(\"{cachePath}\", context.cachePath)\n .replaceAll(\"{dataPath}\", context.dataPath)\n .replaceAll(\"{logPath}\", context.envPaths.log)\n .replaceAll(\"{tempPath}\", context.envPaths.temp)\n .replaceAll(\"{configPath}\", context.envPaths.config)\n .replaceAll(\"{outputPath}\", context.config.output.outputPath)\n .replaceAll(\"{buildPath}\", context.config.output.buildPath)\n .replaceAll(\n \"{artifactsPath}\",\n replacePath(context.artifactsPath, context.workspaceConfig.workspaceRoot)\n )\n .replaceAll(\n \"{builtinPath}\",\n replacePath(context.builtinsPath, context.workspaceConfig.workspaceRoot)\n )\n .replaceAll(\n \"{entryPath}\",\n replacePath(context.entryPath, context.workspaceConfig.workspaceRoot)\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 { parseTypeDefinition } from \"@stryke/convert/parse-type-definition\";\nimport { toArray } from \"@stryke/convert/to-array\";\nimport { isFile } from \"@stryke/fs/is-file\";\nimport { listFiles, listFilesSync } from \"@stryke/fs/list-files\";\nimport { murmurhash } from \"@stryke/hash/murmurhash\";\nimport { getUniqueBy } from \"@stryke/helpers/get-unique\";\nimport { appendPath } from \"@stryke/path/append\";\nimport { joinPaths } from \"@stryke/path/join-paths\";\nimport { replaceExtension, replacePath } from \"@stryke/path/replace\";\nimport { isSetString } from \"@stryke/type-checks/is-set-string\";\nimport { isString } from \"@stryke/type-checks/is-string\";\nimport type {\n TypeDefinition,\n TypeDefinitionParameter\n} from \"@stryke/types/configuration\";\nimport { replacePathTokens } from \"../plugin-utils/paths\";\nimport type { Context } from \"../types/context\";\nimport { ResolvedEntryTypeDefinition } from \"../types/resolved\";\n\nexport function resolveEntryInputFile(\n context: Context,\n typeDefinition: TypeDefinition\n): string {\n return replacePath(\n typeDefinition.file,\n joinPaths(context.workspaceConfig.workspaceRoot, context.config.projectRoot)\n );\n}\n\nexport function resolveEntryInput(\n context: Context,\n typeDefinition: TypeDefinition\n): TypeDefinition {\n return {\n file: resolveEntryInputFile(context, typeDefinition),\n name: typeDefinition.name\n };\n}\n\nexport function resolveEntryOutput(\n context: Context,\n typeDefinition: TypeDefinition\n): string {\n return replaceExtension(\n replacePath(\n replacePath(\n replacePath(\n replacePath(\n replacePath(\n typeDefinition.file,\n joinPaths(\n context.workspaceConfig.workspaceRoot,\n context.config.sourceRoot\n )\n ),\n joinPaths(\n context.workspaceConfig.workspaceRoot,\n context.config.projectRoot\n )\n ),\n context.config.sourceRoot\n ),\n context.config.projectRoot\n ),\n replacePath(context.config.sourceRoot, context.config.projectRoot)\n )\n );\n}\n\nexport function resolveEntry(\n context: Context,\n typeDefinition: TypeDefinition\n): ResolvedEntryTypeDefinition {\n const input = resolveEntryInput(context, typeDefinition);\n\n return {\n ...input,\n input,\n output: resolveEntryOutput(context, typeDefinition)\n };\n}\n\n/**\n * Resolves multiple type definitions into their corresponding resolved entry type definitions.\n *\n * @param context - The current context\n * @param typeDefinitions - The type definitions to resolve.\n * @returns A promise that resolves to an array of resolved entry type definitions.\n */\nexport async function resolveEntries(\n context: Context,\n typeDefinitions: TypeDefinitionParameter[]\n): Promise<ResolvedEntryTypeDefinition[]> {\n return (\n await Promise.all(\n typeDefinitions.map(async typeDefinition => {\n const parsed = parseTypeDefinition(typeDefinition)!;\n\n const filePath = appendPath(parsed.file, context.config.projectRoot);\n if (isFile(filePath)) {\n return resolveEntry(context, {\n file: replacePath(filePath, context.config.projectRoot),\n name: parsed.name\n });\n }\n\n return (\n await listFiles(appendPath(parsed.file, context.config.projectRoot))\n ).map(file =>\n resolveEntry(context, {\n file,\n name: parsed.name\n })\n );\n })\n )\n )\n .flat()\n .filter(Boolean);\n}\n\n/**\n * Resolves multiple type definitions into their corresponding resolved entry type definitions.\n *\n * @param context - The current context\n * @param typeDefinitions - The type definitions to resolve.\n * @returns A promise that resolves to an array of resolved entry type definitions.\n */\nexport function resolveEntriesSync(\n context: Context,\n typeDefinitions: TypeDefinitionParameter[]\n): ResolvedEntryTypeDefinition[] {\n return typeDefinitions\n .map(entry =>\n isString(entry)\n ? replacePathTokens(context, entry)\n : replacePathTokens(context, entry.file)\n )\n .map(typeDefinition => {\n const parsed = parseTypeDefinition(typeDefinition)!;\n\n const filePath = appendPath(parsed.file, context.config.projectRoot);\n if (isFile(filePath)) {\n return resolveEntry(context, {\n file: replacePath(filePath, context.config.projectRoot),\n name: parsed.name\n });\n }\n\n return listFilesSync(filePath).map(file =>\n resolveEntry(context, {\n file,\n name: parsed.name\n })\n );\n })\n .flat()\n .filter(Boolean);\n}\n\n/** Resolve a virtual entry point by generating a unique file path in the artifacts directory.\n *\n * @param context - The current context\n * @param typeDefinition - The type definition to resolve.\n * @returns The resolved entry type definition with a unique virtual file path.\n */\nexport function resolveVirtualEntry(\n context: Context,\n typeDefinition: TypeDefinitionParameter\n): ResolvedEntryTypeDefinition {\n const parsed = parseTypeDefinition(typeDefinition)!;\n const resolved = resolveEntry(context, parsed);\n const file = joinPaths(\n context.artifactsPath,\n `entry-${murmurhash(\n { file: resolved.file, name: resolved.name },\n { maxLength: 24 }\n )\n .replaceAll(\"-\", \"0\")\n .replaceAll(\"_\", \"1\")}.ts`\n );\n\n return {\n file,\n name: resolved.name,\n input: {\n file,\n name: resolved.name\n },\n output: file\n };\n}\n\n/**\n * Get unique entries from the provided list.\n *\n * @param entries - The entries to process.\n * @returns An array of unique entries (by file path or content hash).\n */\nexport function getUniqueEntries(\n entries: TypeDefinitionParameter | TypeDefinitionParameter[] = []\n): TypeDefinitionParameter[] {\n return getUniqueBy(toArray(entries), (item: TypeDefinitionParameter) =>\n isSetString(item) ? item : murmurhash(item ?? {}, { maxLength: 24 })\n );\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\nimport type { ResolveOptions as BaseResolveOptions } from \"@stryke/fs/resolve\";\nimport { MaybePromise } from \"@stryke/types/base\";\nimport { AssetGlob } from \"@stryke/types/file\";\n\nexport type VirtualFileExtension = \"js\" | \"ts\" | \"jsx\" | \"tsx\";\n\n// eslint-disable-next-line ts/naming-convention\nexport const __VFS_PATCH__ = \"__VFS_PATCH__\";\n\n// eslint-disable-next-line ts/naming-convention\nexport const __VFS_REVERT__ = \"__VFS_REVERT__\";\n\nexport enum StoragePreset {\n VIRTUAL = \"virtual\",\n FS = \"fs\"\n}\n\n/**\n * Interface defining the methods and properties for a storage adapter.\n */\nexport interface StorageAdapter {\n /**\n * A name identifying the storage adapter type.\n */\n name: string;\n\n /**\n * Checks if a key exists in the storage.\n *\n * @param key - The key to check for existence.\n * @returns A promise that resolves to `true` if the key exists, otherwise `false`.\n */\n exists: (key: string) => Promise<boolean>;\n\n /**\n * Synchronously checks if a key exists in the storage.\n *\n * @param key - The key to check for existence.\n * @returns Returns `true` if the key exists, otherwise `false`.\n */\n existsSync: (key: string) => boolean;\n\n /**\n * Read a value associated with a key from the storage.\n *\n * @param key - The key to read the value for.\n * @returns A promise that resolves to the value if found, otherwise `null`.\n */\n get: (key: string) => Promise<string | null>;\n\n /**\n * Synchronously reads the value associated with a key from the storage.\n *\n * @param key - The key to read the value for.\n * @returns The value if found, otherwise `null`.\n */\n getSync: (key: string) => string | null;\n\n /**\n * Writes a value to the storage for the given key.\n *\n * @param key - The key to associate the value with.\n * @param value - The value to store.\n */\n set: (key: string, value: string) => Promise<void>;\n\n /**\n * Synchronously writes a value to the storage for the given key.\n *\n * @param key - The key to associate the value with.\n * @param value - The value to store.\n */\n setSync: (key: string, value: string) => void;\n\n /**\n * Removes a value from the storage.\n *\n * @param key - The key whose value should be removed.\n */\n remove: (key: string) => Promise<void>;\n\n /**\n * Synchronously removes a value from the storage.\n *\n * @param key - The key whose value should be removed.\n */\n removeSync: (key: string) => void;\n\n /**\n * Creates a directory at the specified path.\n *\n * @param dirPath - The path of the directory to create.\n */\n mkdir: (dirPath: string) => Promise<void>;\n\n /**\n * Synchronously creates a directory at the specified path.\n *\n * @param dirPath - The path of the directory to create.\n */\n mkdirSync: (dirPath: string) => void;\n\n /**\n * Remove all entries from the storage that match the provided base path.\n *\n * @param base - The base path or prefix to clear entries from.\n */\n clear: (base?: string) => Promise<void>;\n\n /**\n * Synchronously remove all entries from the storage that match the provided base path.\n *\n * @param base - The base path or prefix to clear entries from.\n */\n clearSync: (base?: string) => void;\n\n /**\n * Lists all keys under the provided base path.\n *\n * @param base - The base path or prefix to list keys from.\n * @returns A promise resolving to the list of keys.\n */\n list: (base?: string) => Promise<string[]>;\n\n /**\n * Synchronously lists all keys under the provided base path.\n *\n * @param base - The base path or prefix to list keys from.\n * @returns The list of keys.\n */\n listSync: (base?: string) => string[];\n\n /**\n * Checks if the given key is a directory.\n *\n * @param key - The key to check.\n * @returns A promise that resolves to `true` if the key is a directory, otherwise `false`.\n */\n isDirectory: (key: string) => Promise<boolean>;\n\n /**\n * Synchronously checks if the given key is a directory.\n *\n * @param key - The key to check.\n * @returns `true` if the key is a directory, otherwise `false`.\n */\n isDirectorySync: (key: string) => boolean;\n\n /**\n * Checks if the given key is a file.\n *\n * @param key - The key to check.\n * @returns A promise that resolves to `true` if the key is a file, otherwise `false`.\n */\n isFile: (key: string) => Promise<boolean>;\n\n /**\n * Synchronously checks if the given key is a file.\n *\n * @param key - The key to check.\n * @returns `true` if the key is a file, otherwise `false`.\n */\n isFileSync: (key: string) => boolean;\n\n /**\n * Releases any resources held by the storage adapter.\n */\n dispose: () => MaybePromise<void>;\n}\n\n/**\n * A mapping of file paths to storage adapter names and their corresponding {@link StorageAdapter} instances.\n */\nexport type StoragePort = Record<string, StorageAdapter>;\n\nexport interface VirtualFileMetadata {\n /**\n * The identifier for the file data.\n */\n id: string;\n\n /**\n * The timestamp of the virtual file.\n */\n timestamp: number;\n\n /**\n * The type of the file.\n *\n * @remarks\n * This string represents the purpose/function of the file in the virtual file system. A potential list of variants includes:\n * - `builtin`: Indicates that the file is a built-in module provided by the system.\n * - `entry`: Indicates that the file is an entry point for execution.\n * - `normal`: Indicates that the file is a standard file without any special role.\n */\n type: string;\n\n /**\n * Additional metadata associated with the file.\n */\n properties: Record<string, string>;\n}\n\nexport interface VirtualFileData {\n /**\n * The identifier for the file data.\n */\n id?: string;\n\n /**\n * The contents of the virtual file.\n */\n code: string;\n\n /**\n * The type of the file.\n *\n * @remarks\n * This string represents the purpose/function of the file in the virtual file system. A potential list of variants includes:\n * - `builtin`: Indicates that the file is a built-in module provided by the system.\n * - `entry`: Indicates that the file is an entry point for execution.\n * - `normal`: Indicates that the file is a standard file without any special role.\n */\n type?: string;\n\n /**\n * Additional metadata associated with the file.\n */\n properties?: Record<string, string>;\n}\n\nexport interface VirtualFile\n extends Required<VirtualFileData>, VirtualFileMetadata {\n /**\n * An additional name for the file.\n */\n path: string;\n\n /**\n * The timestamp of the virtual file.\n */\n timestamp: number;\n}\n\nexport interface WriteOptions {\n /**\n * Should the file skip formatting before being written?\n *\n * @defaultValue false\n */\n skipFormat?: boolean;\n\n /**\n * Additional metadata for the file.\n */\n meta?: VirtualFileMetadata;\n}\n\nexport type WriteData = string | NodeJS.ArrayBufferView | VirtualFileData;\n\nexport interface ResolveOptions extends BaseResolveOptions {\n /**\n * If true, the module is being resolved as an entry point.\n */\n isEntry?: boolean;\n\n /**\n * If true, the resolver will skip using the cache when resolving modules.\n */\n skipCache?: boolean;\n\n /**\n * An array of external modules or patterns to exclude from resolution.\n */\n external?: (string | RegExp)[];\n\n /**\n * An array of modules or patterns to include in the resolution, even if they are marked as external.\n */\n noExternal?: (string | RegExp)[];\n\n /**\n * An array of patterns to match when resolving modules.\n */\n skipNodeModulesBundle?: boolean;\n}\n\nexport interface VirtualFileSystemInterface {\n /**\n * The underlying file metadata.\n */\n metadata: Readonly<Record<string, VirtualFileMetadata>>;\n\n /**\n * A map of file paths to their module ids.\n */\n ids: Readonly<Record<string, string>>;\n\n /**\n * A map of module ids to their file paths.\n */\n paths: Readonly<Record<string, string>>;\n\n /**\n * Checks if a file exists in the virtual file system (VFS).\n *\n * @param path - The path or id of the file.\n * @returns `true` if the file exists, otherwise `false`.\n */\n exists: (path: string) => Promise<boolean>;\n\n /**\n * Synchronously Checks if a file exists in the virtual file system (VFS).\n *\n * @param path - The path or id of the file.\n * @returns `true` if the file exists, otherwise `false`.\n */\n existsSync: (path: string) => boolean;\n\n /**\n * Checks if a file is virtual in the virtual file system (VFS).\n *\n * @param path - The path or id of the file.\n * @returns `true` if the file is virtual, otherwise `false`.\n */\n isVirtual: (path: string) => boolean;\n\n /**\n * Checks if the given key is a directory.\n *\n * @param key - The key to check.\n * @returns A promise that resolves to `true` if the key is a directory, otherwise `false`.\n */\n isDirectory: (key: string) => Promise<boolean>;\n\n /**\n * Synchronously checks if the given key is a directory.\n *\n * @param key - The key to check.\n * @returns `true` if the key is a directory, otherwise `false`.\n */\n isDirectorySync: (key: string) => boolean;\n\n /**\n * Checks if the given key is a file.\n *\n * @param key - The key to check.\n * @returns A promise that resolves to `true` if the key is a file, otherwise `false`.\n */\n isFile: (key: string) => Promise<boolean>;\n\n /**\n * Synchronously checks if the given key is a file.\n *\n * @param key - The key to check.\n * @returns `true` if the key is a file, otherwise `false`.\n */\n isFileSync: (key: string) => boolean;\n\n /**\n * Gets the metadata of a file in the virtual file system (VFS).\n *\n * @param path - The path or id of the file.\n * @returns The metadata of the file if it exists, otherwise undefined.\n */\n getMetadata: (path: string) => VirtualFileMetadata | undefined;\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 listSync: (path: string) => string[];\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 list: (path: string) => Promise<string[]>;\n\n /**\n * Removes a file or symbolic link in the virtual file system (VFS).\n *\n * @param path - The path to the file to remove.\n * @returns A promise that resolves when the file is removed.\n */\n removeSync: (path: string) => void;\n\n /**\n * Asynchronously removes a file or symbolic link in the virtual file system (VFS).\n *\n * @param path - The path to the file to remove.\n * @returns A promise that resolves when the file is removed.\n */\n remove: (path: string) => Promise<void>;\n\n /**\n * Reads a file from the virtual file system (VFS).\n *\n * @param path - The path or id of the file.\n * @returns The contents of the file if it exists, otherwise undefined.\n */\n read: (path: string) => Promise<string | undefined>;\n\n /**\n * Reads a file from the virtual file system (VFS).\n *\n * @param path - The path or id of the file.\n */\n readSync: (path: string) => string | undefined;\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 - Options for writing the file.\n * @returns A promise that resolves when the file is written.\n */\n write: (path: string, data: string, options?: WriteOptions) => Promise<void>;\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 - Options for writing the file.\n */\n writeSync: (path: string, data: string, options?: WriteOptions) => void;\n\n /**\n * Creates a directory at the specified path.\n *\n * @param dirPath - The path of the directory to create.\n */\n mkdir: (dirPath: string) => Promise<void>;\n\n /**\n * Synchronously creates a directory at the specified path.\n *\n * @param dirPath - The path of the directory to create.\n */\n mkdirSync: (dirPath: string) => void;\n\n /**\n * Moves a file 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 move: (srcPath: string, destPath: string) => Promise<void>;\n\n /**\n * Synchronously moves a file 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 moveSync: (srcPath: string, destPath: string) => void;\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 copy: (\n srcPath: string | URL | Omit<AssetGlob, \"output\">,\n destPath: string | URL\n ) => Promise<void>;\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 copySync: (\n srcPath: string | URL | Omit<AssetGlob, \"output\">,\n destPath: string | URL\n ) => void;\n\n /**\n * Glob files in the virtual file system (VFS) based on the provided pattern(s).\n *\n * @param pattern - 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 glob: (\n patterns:\n | string\n | Omit<AssetGlob, \"output\">\n | (string | Omit<AssetGlob, \"output\">)[]\n ) => Promise<string[]>;\n\n /**\n * Synchronously glob files in the virtual file system (VFS) based on the provided pattern(s).\n *\n * @param pattern - 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 globSync: (\n patterns:\n | string\n | Omit<AssetGlob, \"output\">\n | (string | Omit<AssetGlob, \"output\">)[]\n ) => string[];\n\n /**\n * A 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 = 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 resolve: (\n id: string,\n importer?: string,\n options?: ResolveOptions\n ) => Promise<string | undefined>;\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 resolveSync: (\n id: string,\n importer?: string,\n options?: ResolveOptions\n ) => string | undefined;\n\n /**\n * Disposes of the virtual file system (VFS), writes any virtual file changes to disk, and releases any associated resources.\n */\n dispose: () => Promise<void>;\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 { getLogFn, getLogLevel } from \"@storm-software/config-tools/logger\";\nimport { LogLevelLabel } from \"@storm-software/config-tools/types\";\nimport { getColor } from \"@storm-software/config-tools/utilities/colors\";\nimport { noop } from \"@stryke/helpers/noop\";\nimport { titleCase } from \"@stryke/string-format/title-case\";\nimport chalk from \"chalk\";\nimport type { LogFn, WorkspaceConfig } from \"../types\";\n\nexport interface CreateLogOptions {\n name?: string;\n logLevel?: LogLevelLabel | null;\n customLogger?: LogFn;\n colors?: WorkspaceConfig[\"colors\"];\n}\n\n/**\n * Create a logging function with a specific name and options.\n *\n * @param name - The name of the logging function.\n * @param options - The options to configure the logging function.\n * @returns A logging function.\n */\nexport const createLog = (\n name: string | null,\n options: CreateLogOptions = {}\n): LogFn => {\n const logLevel =\n options.logLevel === null\n ? LogLevelLabel.SILENT\n : options.logLevel || LogLevelLabel.INFO;\n if (logLevel === LogLevelLabel.SILENT) {\n return noop;\n }\n\n if (options.customLogger) {\n return options.customLogger;\n }\n\n return (type: LogLevelLabel, ...args: string[]) =>\n getLogFn(getLogLevel(type), {\n ...options,\n logLevel\n })(\n `${chalk.bold.hex(\n getColor(\"brand\", options as Parameters<typeof getColor>[1])\n )(\n `powerlines${name ? `:${name}` : \"\"}${\n options.name ? ` ${chalk.gray(\"> \")}${options.name}` : \"\"\n } ${chalk.gray(\"> \")}`\n )}${args.join(\" \")} `.trim()\n );\n};\n\nconst BADGE_COLORS = [\n \"#00A0DD\",\n \"#6FCE4E\",\n \"#FBBF24\",\n \"#F43F5E\",\n \"#3B82F6\",\n \"#A855F7\",\n \"#469592\",\n \"#288EDF\",\n \"#10B981\",\n \"#EF4444\",\n \"#F0EC56\",\n \"#F472B6\",\n \"#22D3EE\",\n \"#EAB308\",\n \"#84CC16\",\n \"#F87171\",\n \"#0EA5E9\",\n \"#D946EF\",\n \"#FACC15\",\n \"#34D399\"\n] as const;\n\nexport const extendLog = (logFn: LogFn, name: string): LogFn => {\n return (type: LogLevelLabel, ...args: string[]) =>\n logFn(\n type,\n ` ${chalk.inverse.hex(\n BADGE_COLORS[\n name\n .split(\"\")\n .map(char => char.charCodeAt(0))\n .reduce((ret, charCode) => ret + charCode, 0) % BADGE_COLORS.length\n ] || BADGE_COLORS[0]\n )(` ${titleCase(name)} `)} ${args.join(\" \")} `\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 { toArray } from \"@stryke/convert/to-array\";\nimport { getUnique } from \"@stryke/helpers/get-unique\";\nimport { correctPath } from \"@stryke/path/correct-path\";\nimport { findFileDotExtensionSafe } from \"@stryke/path/file-path-fns\";\nimport { isAbsolutePath } from \"@stryke/path/is-type\";\nimport { joinPaths } from \"@stryke/path/join\";\nimport { slash } from \"@stryke/path/slash\";\nimport { isError } from \"@stryke/type-checks/is-error\";\nimport { isSetObject } from \"@stryke/type-checks/is-set-object\";\nimport { isSetString } from \"@stryke/type-checks/is-set-string\";\nimport { AssetGlob } from \"@stryke/types/file\";\nimport { PathOrFileDescriptor } from \"node:fs\";\n\n/**\n * Checks if an error is a file system error.\n *\n * @param err - The error to check.\n * @returns `true` if the error is a file system error, otherwise `false`.\n */\nexport function isFileError(err: any) {\n return isError(err) && \"code\" in err && err.code;\n}\n\n/**\n * Ignores file not found errors.\n *\n * @param err - The error to check.\n * @returns `null` if the error is a file not found error, otherwise returns the error.\n */\nexport function ignoreNotfound(err: any) {\n return (\n isFileError(err) &&\n (err.code === \"ENOENT\" || err.code === \"EISDIR\" ? null : err)\n );\n}\n\n/**\n * Ignores file exists errors.\n *\n * @param err - The error to check.\n * @returns `null` if the error is a file exists error, otherwise returns the error.\n */\nexport function ignoreExists(err: any) {\n return isFileError(err) && err.code === \"EEXIST\" ? null : err;\n}\n\nexport function 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 */\nexport function 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 prepending the 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 */\nexport function 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\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 */\nexport function 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 a storage key by replacing all path separators with the specified separator.\n *\n * @param key - The storage key to normalize.\n * @param sep - The separator to use for normalization. Default is \":\".\n * @returns The normalized storage key.\n */\nexport function normalizeKey(\n key: string | undefined,\n sep: \":\" | \"/\" = \":\"\n): string {\n if (!key) {\n return \"\";\n }\n return key.replace(/[:/\\\\]/g, sep).replace(/^[:/\\\\]|[:/\\\\]$/g, \"\");\n}\n\n/**\n * Normalizes the base key for storage operations.\n *\n * @param base - The base key to normalize.\n * @returns The normalized base key with a trailing colon if not empty.\n */\nexport function normalizeBaseKey(base?: string) {\n base = normalizeKey(base);\n return base ? `${base}:` : \"\";\n}\n\n/**\n * Filters a storage key based on the specified base path.\n *\n * @param key - The storage key to filter.\n * @param base - The base path to filter by.\n * @returns `true` if the key matches the base path criteria, otherwise `false`.\n */\nexport function filterKeyByBase(\n key: string,\n base: string | undefined\n): boolean {\n if (base) {\n return key.startsWith(base) && key[key.length - 1] !== \"$\";\n }\n\n return key[key.length - 1] !== \"$\";\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 */\nexport function 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 ⚡ 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 { appendPath } from \"@stryke/path/append\";\nimport { correctPath } from \"@stryke/path/correct-path\";\nimport { joinPaths } from \"@stryke/path/join\";\nimport { MaybePromise } from \"@stryke/types/base\";\nimport { resolve } from \"node:path\";\nimport { StorageAdapter } from \"../../../types/fs\";\n\nexport interface StorageAdapterOptions {\n base: string;\n isReadOnly?: boolean;\n ignore?: string | string[];\n}\n\n/**\n * Abstract base class for storage adapters, providing a template for storage operations.\n */\nexport abstract class BaseStorageAdapter<\n TOptions extends StorageAdapterOptions = StorageAdapterOptions\n> implements StorageAdapter {\n /**\n * Indicates whether the storage adapter has been disposed.\n */\n #isDisposed = false;\n\n /**\n * A name identifying the storage adapter type.\n */\n public abstract name: string;\n\n /**\n * Configuration options for the storage adapter.\n */\n public options: TOptions;\n\n /**\n * Constructor for the BaseStorageAdapter.\n *\n * @param options - Configuration options for the storage adapter.\n */\n public constructor(options: TOptions = { base: \"/\" } as TOptions) {\n this.options = options;\n this.options.base = resolve(options.base);\n this.options.isReadOnly = !!options.isReadOnly;\n }\n\n /**\n * Synchronously checks if a key exists in the storage.\n *\n * @param key - The key to check for existence.\n * @returns Returns `true` if the key exists, otherwise `false`.\n */\n public abstract existsSync(key: string): boolean;\n\n /**\n * Asynchronously checks if a key exists in the storage.\n *\n * @param key - The key to check for existence.\n * @returns A promise that resolves to `true` if the key exists, otherwise `false`.\n */\n public async exists(key: string): Promise<boolean> {\n return this.existsSync(key);\n }\n\n /**\n * Synchronously retrieves the value associated with a given key.\n *\n * @param key - The key whose value is to be retrieved.\n * @returns The value associated with the key, or `null` if the key does not exist.\n */\n public abstract getSync(key: string): string | null;\n\n /**\n * Asynchronously retrieves the value associated with a given key.\n *\n * @param key - The key whose value is to be retrieved.\n * @returns A promise that resolves to the value associated with the key, or `null` if the key does not exist.\n */\n public async get(key: string): Promise<string | null> {\n return this.getSync(key);\n }\n\n /**\n * Synchronously sets the value for a given key.\n *\n * @param key - The key to set the value for.\n * @param value - The value to set.\n */\n public abstract setSync(key: string, value: string): void;\n\n /**\n * Asynchronously sets the value for a given key.\n *\n * @param key - The key to set the value for.\n * @param value - The value to set.\n */\n public async set(key: string, value: string): Promise<void> {\n if (!this.options.isReadOnly) {\n this.setSync(key, value);\n }\n }\n\n /**\n * Synchronously creates a directory at the specified path.\n *\n * @param _ - The path of the directory to create.\n */\n public mkdirSync(_: string) {}\n\n /**\n * Creates a directory at the specified path.\n *\n * @param dirPath - The path of the directory to create.\n */\n public async mkdir(dirPath: string): Promise<void> {\n return Promise.resolve(this.mkdirSync(dirPath));\n }\n\n /**\n * Synchronously removes a key from the storage.\n *\n * @param key - The key to remove.\n */\n public abstract removeSync(key: string): void;\n\n /**\n * Asynchronously removes a key from the storage.\n *\n * @param key - The key to remove.\n */\n public async remove(key: string): Promise<void> {\n if (!this.options.isReadOnly) {\n this.removeSync(key);\n }\n }\n\n /**\n * Synchronously removes all entries from the storage that match the provided base path.\n *\n * @param base - The base path to clear keys from.\n */\n public clearSync(base?: string) {\n if (!this.options.isReadOnly) {\n const keys = this.listSync(base || this.options.base);\n if (!keys.length) {\n return;\n }\n\n keys.map(key =>\n this.removeSync(\n base && !key.startsWith(base) ? joinPaths(base, key) : key\n )\n );\n }\n }\n\n /**\n * Asynchronously removes all entries from the storage that match the provided base path.\n *\n * @param base - The base path to clear keys from.\n * @returns A promise that resolves when the operation is complete.\n */\n public async clear(base?: string): Promise<void> {\n if (!this.options.isReadOnly) {\n const keys = await this.list(base || this.options.base);\n if (!keys.length) {\n return;\n }\n\n await Promise.all(\n keys.map(async key =>\n this.remove(\n base && !key.startsWith(base) ? joinPaths(base, key) : key\n )\n )\n );\n }\n }\n\n /**\n * Lists all keys under a given base path synchronously.\n *\n * @param base - The base path to list keys from.\n * @returns An array of keys under the specified base path.\n */\n public abstract listSync(base?: string): string[];\n\n /**\n * Asynchronously lists all keys under a given base path.\n *\n * @param base - The base path to list keys from.\n * @returns A promise that resolves to an array of keys under the specified base path.\n */\n public async list(base?: string): Promise<string[]> {\n return this.listSync(base);\n }\n\n /**\n * Synchronously checks if the given key is a directory.\n *\n * @param _ - The key to check.\n * @returns `true` if the key is a directory, otherwise `false`.\n */\n public isDirectorySync(_: string): boolean {\n return false;\n }\n\n /**\n * Checks if the given key is a directory.\n *\n * @param key - The key to check.\n * @returns A promise that resolves to `true` if the key is a directory, otherwise `false`.\n */\n public async isDirectory(key: string) {\n return Promise.resolve(this.isDirectorySync(key));\n }\n\n /**\n * Synchronously checks if the given key is a file.\n *\n * @param key - The key to check.\n * @returns `true` if the key is a file, otherwise `false`.\n */\n public isFileSync(key: string): boolean {\n return this.existsSync(key) && !this.isDirectorySync(key);\n }\n\n /**\n * Checks if the given key is a file.\n *\n * @param key - The key to check.\n * @returns A promise that resolves to `true` if the key is a file, otherwise `false`.\n */\n public async isFile(key: string) {\n return Promise.resolve(this.isFileSync(key));\n }\n\n /**\n * Disposes of the storage adapter, releasing any held resources.\n *\n * @returns A promise that resolves when the disposal is complete.\n */\n public dispose(): MaybePromise<void> {\n return Promise.resolve();\n }\n\n /**\n * Async dispose method to clean up resources.\n *\n * @returns A promise that resolves when disposal is complete.\n */\n public async [Symbol.asyncDispose]() {\n return this._dispose();\n }\n\n /**\n * Resolves a given key to its full path within the storage adapter.\n *\n * @param key - The key to resolve.\n * @returns The resolved full path for the key.\n */\n protected resolve(key: string = this.options.base) {\n if (/\\.\\.:|\\.\\.$/.test(key)) {\n throw new Error(\n `[${this.name}]: Invalid key: ${JSON.stringify(key)} provided to storage adapter.`\n );\n }\n\n return appendPath(correctPath(key).replace(/:/g, \"/\"), this.options.base);\n }\n\n /**\n * Disposes of the storage adapter, releasing any held resources.\n *\n * @returns A promise that resolves when the disposal is complete.\n */\n protected async _dispose(): Promise<void> {\n if (!this.#isDisposed) {\n await Promise.resolve(this.dispose());\n this.#isDisposed = 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 { exists, existsSync } from \"@stryke/fs/exists\";\nimport { createDirectory, createDirectorySync } from \"@stryke/fs/helpers\";\nimport { isDirectory, isFile } from \"@stryke/fs/is-file\";\nimport { listFiles, listFilesSync } from \"@stryke/fs/list-files\";\nimport { readFile, readFileSync } from \"@stryke/fs/read-file\";\nimport { writeFile, writeFileSync } from \"@stryke/fs/write-file\";\nimport { unlinkSync } from \"node:fs\";\nimport { unlink } from \"node:fs/promises\";\nimport { ignoreNotfound } from \"../helpers\";\nimport { BaseStorageAdapter, StorageAdapterOptions } from \"./base\";\n\nexport type SetSyncOptions = Parameters<typeof writeFileSync>[2];\nexport type SetOptions = Parameters<typeof writeFile>[2];\n\n/**\n * File system storage adapter implementation.\n */\nexport class FileSystemStorageAdapter extends BaseStorageAdapter {\n /**\n * A name identifying the storage adapter type.\n */\n public name = \"file-system\";\n\n /**\n * Constructor for the FileSystemStorageAdapter.\n *\n * @param options - Configuration options for the storage adapter.\n */\n public constructor(options?: StorageAdapterOptions) {\n super(options);\n }\n\n /**\n * Synchronously checks if a key exists in the storage.\n *\n * @param key - The key to check for existence.\n * @returns Returns `true` if the key exists, otherwise `false`.\n */\n public existsSync(key: string): boolean {\n return existsSync(this.resolve(key));\n }\n\n /**\n * Asynchronously checks if a key exists in the storage.\n *\n * @param key - The key to check for existence.\n * @returns A promise that resolves to `true` if the key exists, otherwise `false`.\n */\n public override async exists(key: string): Promise<boolean> {\n return exists(this.resolve(key));\n }\n\n /**\n * Synchronously retrieves the value associated with a given key.\n *\n * @param key - The key whose value is to be retrieved.\n * @returns The value associated with the key, or `null` if the key does not exist.\n */\n public getSync(key: string): string | null {\n return readFileSync(this.resolve(key));\n }\n\n /**\n * Asynchronously retrieves the value associated with a given key.\n *\n * @param key - The key whose value is to be retrieved.\n * @returns A promise that resolves to the value associated with the key, or `null` if the key does not exist.\n */\n public override async get(key: string): Promise<string | null> {\n return readFile(this.resolve(key));\n }\n\n /**\n * Synchronously sets the value for a given key.\n *\n * @param key - The key to set the value for.\n * @param value - The value to set.\n */\n public setSync(key: string, value: string) {\n if (!this.options.isReadOnly) {\n return writeFileSync(this.resolve(key), value);\n }\n }\n\n /**\n * Asynchronously sets the value for a given key.\n *\n * @param key - The key to set the value for.\n * @param value - The value to set.\n */\n public override async set(key: string, value: string): Promise<void> {\n if (!this.options.isReadOnly) {\n return writeFile(this.resolve(key), value);\n }\n }\n\n /**\n * Synchronously removes a key from the storage.\n *\n * @param key - The key to remove.\n */\n public removeSync(key: string) {\n if (!this.options.isReadOnly) {\n try {\n return unlinkSync(this.resolve(key));\n } catch (err) {\n return ignoreNotfound(err);\n }\n }\n }\n\n /**\n * Asynchronously removes a key from the storage.\n *\n * @param key - The key to remove.\n */\n public override async remove(key: string): Promise<void> {\n if (!this.options.isReadOnly) {\n return unlink(this.resolve(key)).catch(ignoreNotfound);\n }\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 override mkdirSync(dirPath: string) {\n createDirectorySync(this.resolve(dirPath));\n }\n\n /**\n * Creates a directory at the specified path.\n *\n * @param dirPath - The path of the directory to create.\n */\n public override async mkdir(dirPath: string): Promise<void> {\n await createDirectory(this.resolve(dirPath));\n }\n\n /**\n * Lists all keys under a given base path synchronously.\n *\n * @param base - The base path to list keys from.\n * @returns An array of keys under the specified base path.\n */\n public listSync(base?: string): string[] {\n try {\n return listFilesSync(this.resolve(base), {\n ignore: this.options.ignore\n });\n } catch (err) {\n return ignoreNotfound(err) ?? [];\n }\n }\n\n /**\n * Asynchronously lists all keys under a given base path.\n *\n * @param base - The base path to list keys from.\n * @returns A promise that resolves to an array of keys under the specified base path.\n */\n public override async list(base?: string): Promise<string[]> {\n return listFiles(this.resolve(base), {\n ignore: this.options.ignore\n })\n .catch(ignoreNotfound)\n .then(r => r || []);\n }\n\n /**\n * Synchronously checks if the given key is a directory.\n *\n * @param key - The key to check.\n * @returns `true` if the key is a directory, otherwise `false`.\n */\n public override isDirectorySync(key: string): boolean {\n return isDirectory(this.resolve(key));\n }\n\n /**\n * Synchronously checks if the given key is a file.\n *\n * @param key - The key to check.\n * @returns `true` if the key is a file, otherwise `false`.\n */\n public override isFileSync(key: string): boolean {\n return !isFile(this.resolve(key));\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 { isParentPath } from \"@stryke/path/is-parent-path\";\nimport { BaseStorageAdapter, StorageAdapterOptions } from \"./base\";\n\n/**\n * Virtual/in-memory storage adapter implementation.\n */\nexport class VirtualStorageAdapter extends BaseStorageAdapter {\n /**\n * A name identifying the storage adapter type.\n */\n public name = \"virtual\";\n\n /**\n * In-memory data storage.\n */\n protected data = new Map<string, any>();\n\n /**\n * Constructor for the VirtualStorageAdapter.\n *\n * @param options - Configuration options for the storage adapter.\n */\n public constructor(options?: StorageAdapterOptions) {\n super(options);\n }\n\n /**\n * Synchronously checks if a key exists in the storage.\n *\n * @param key - The key to check for existence.\n * @returns Returns `true` if the key exists, otherwise `false`.\n */\n public existsSync(key: string): boolean {\n return this.data.has(this.resolve(key));\n }\n\n /**\n * Synchronously retrieves the value associated with a given key.\n *\n * @param key - The key whose value is to be retrieved.\n * @returns The value associated with the key, or `null` if the key does not exist.\n */\n public getSync(key: string): string | null {\n return this.data.get(this.resolve(key)) ?? null;\n }\n\n /**\n * Synchronously sets the value for a given key.\n *\n * @param key - The key to set the value for.\n * @param value - The value to set.\n */\n public setSync(key: string, value: string) {\n if (!this.options.isReadOnly) {\n this.data.set(this.resolve(key), value);\n }\n }\n\n /**\n * Synchronously removes a key from the storage.\n *\n * @param key - The key to remove.\n */\n public removeSync(key: string) {\n if (!this.options.isReadOnly) {\n this.data.delete(this.resolve(key));\n }\n }\n\n /**\n * Lists all keys under a given base path synchronously.\n *\n * @param base - The base path to list keys from.\n * @returns An array of keys under the specified base path.\n */\n public listSync(base?: string): string[] {\n return [\n ...this.data\n .keys()\n .filter(key => (!base ? true : isParentPath(key, this.resolve(base))))\n ];\n }\n\n /**\n * Disposes of the storage adapter, releasing any held resources.\n *\n * @returns A promise that resolves when the disposal is complete.\n */\n public override async dispose(): Promise<void> {\n return this.clear();\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 { 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/murmurhash\";\nimport { getUnique } from \"@stryke/helpers/get-unique\";\nimport { appendPath } from \"@stryke/path/append\";\nimport {\n findFileName,\n findFilePath,\n hasFileExtension\n} from \"@stryke/path/file-path-fns\";\nimport { isParentPath } from \"@stryke/path/is-parent-path\";\nimport { isAbsolutePath } from \"@stryke/path/is-type\";\nimport { joinPaths } from \"@stryke/path/join-paths\";\nimport { replacePath } from \"@stryke/path/replace\";\nimport { prettyBytes } from \"@stryke/string-format/pretty-bytes\";\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 { fileURLToPath } from \"node:url\";\nimport { format, resolveConfig } from \"prettier\";\nimport { FileSystem } from \"../../../schemas/fs\";\nimport { replacePathTokens } from \"../../plugin-utils/paths\";\nimport { LogFn } from \"../../types/config\";\nimport { Context } from \"../../types/context\";\nimport {\n ResolveOptions,\n StorageAdapter,\n StoragePort,\n StoragePreset,\n VirtualFileMetadata,\n VirtualFileSystemInterface,\n WriteOptions\n} from \"../../types/fs\";\nimport { extendLog } from \"../logger\";\nimport { normalizeGlobPatterns, normalizeId, normalizePath } from \"./helpers\";\nimport { FileSystemStorageAdapter } from \"./storage/file-system\";\nimport { VirtualStorageAdapter } from \"./storage/virtual\";\n\ninterface StorageAdapterState {\n adapter: StorageAdapter;\n relativeKey: string;\n base: string;\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 virtual file IDs to their underlying file paths.\n */\n #ids: Record<string, string>;\n\n /**\n * A map of underlying file paths to their virtual file IDs.\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 = { \"\": new FileSystemStorageAdapter() };\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.output.builtinPrefix);\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.output.builtinPrefix\n );\n }\n\n /**\n * Builds a regular expression from a string pattern for path matching.\n *\n * @param path - The string pattern to convert.\n * @returns A regular expression for matching paths.\n */\n #buildRegex(path: string): RegExp {\n const token = \"::GLOBSTAR::\";\n\n return new RegExp(\n `^${this.#normalizePath(path)\n .replace(/\\*\\*/g, token)\n .replace(/[.+^${}()|[\\]\\\\]/g, \"\\\\$&\")\n .replace(/\\*/g, \"[^/]*\")\n .replace(/\\?/g, \"[^/]\")\n .replace(new RegExp(token, \"g\"), \".*\")}$`\n );\n }\n\n /**\n * Gets the storage adapter and relative key for a given key.\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): 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 (isParentPath(path, base)) {\n return {\n base,\n relativeKey: replacePath(path, base),\n adapter: this.#storage[base]!\n };\n }\n }\n\n return {\n base: \"\",\n relativeKey: path,\n adapter: this.#storage[\"\"]!\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 return Object.keys(this.#storage)\n .sort()\n .reverse()\n .filter(\n key =>\n isParentPath(key, base) || (includeParent && isParentPath(base, key))\n )\n .map(key => ({\n relativeBase:\n base.length > key.length ? base.slice(key.length) : undefined,\n base: key,\n adapter: this.#storage[key]!\n }));\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 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 const 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 await result.write(file.path, file.code);\n })\n );\n }\n }\n\n const message = new capnp.Message();\n\n return new VirtualFileSystem(context, message.initRoot(FileSystem));\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 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 const result = new VirtualFileSystem(context, fs);\n\n if (fs._hasStorage() && fs.storage.length > 0) {\n fs.storage.values().map(file => {\n result.writeSync(file.path, file.code);\n });\n }\n }\n\n const message = new capnp.Message();\n\n return new VirtualFileSystem(context, message.initRoot(FileSystem));\n }\n\n /**\n * A map of file ids to their metadata.\n */\n public get metadata(): Readonly<Record<string, VirtualFileMetadata>> {\n return new Proxy(this.#metadata, {\n get: (target, prop: string) => {\n return target[this.#normalizeId(prop)];\n }\n });\n }\n\n /**\n * A map of file paths to their module ids.\n */\n public get ids(): Readonly<Record<string, string>> {\n return new Proxy(this.#paths, {\n get: (target, prop: string) => {\n return target[this.#normalizePath(prop)];\n }\n });\n }\n\n /**\n * A map of module ids to their file paths.\n */\n public get paths(): Readonly<Record<string, string>> {\n return new Proxy(this.#paths, {\n get: (target, prop: string) => {\n return target[this.#normalizeId(prop)];\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 * 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\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({\n base: \"/_virtual\"\n });\n\n if (this.#context.config.output.storage !== StoragePreset.FS) {\n this.#storage[this.#context.artifactsPath] ??= new VirtualStorageAdapter({\n base: this.#context.artifactsPath\n });\n this.#storage[this.#context.builtinsPath] ??= new VirtualStorageAdapter({\n base: this.#context.builtinsPath\n });\n this.#storage[this.#context.entryPath] ??= new VirtualStorageAdapter({\n base: this.#context.entryPath\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 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?.name === \"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 return getUnique(\n this.#getStorages(path, 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 );\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 return getUnique(\n (\n await Promise.all(\n this.#getStorages(path, 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 ).flat()\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\n for (const pattern of normalizeGlobPatterns(\n this.#context.workspaceConfig.workspaceRoot,\n patterns\n )) {\n const normalized = this.#normalizePath(pattern);\n\n // No glob characters: treat as a single file path\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\n continue;\n }\n\n // Make absolute pattern for matching\n const absPattern = isAbsolutePath(normalized)\n ? normalized\n : this.#normalizePath(\n joinPaths(this.#context.workspaceConfig.workspaceRoot, normalized)\n );\n\n // Determine the base directory to start walking from (up to the first glob segment)\n const firstGlobIdx = absPattern.search(/[*?[\\]{}]/);\n const baseDir =\n firstGlobIdx === -1\n ? findFilePath(absPattern)\n : absPattern.slice(\n 0,\n Math.max(0, absPattern.lastIndexOf(\"/\", firstGlobIdx))\n );\n\n await Promise.all(\n (\n await this.list(\n baseDir && isAbsolutePath(baseDir)\n ? baseDir\n : this.#context.workspaceConfig.workspaceRoot\n )\n ).map(async file => {\n if (this.#buildRegex(absPattern).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 * 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\n for (const pattern of normalizeGlobPatterns(\n this.#context.workspaceConfig.workspaceRoot,\n patterns\n )) {\n const normalized = this.#normalizePath(pattern);\n\n // No glob characters: treat as a single file path\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\n continue;\n }\n\n // Make absolute pattern for matching\n const absPattern = isAbsolutePath(normalized)\n ? normalized\n : this.#normalizePath(\n joinPaths(this.#context.workspaceConfig.workspaceRoot, normalized)\n );\n\n // Determine the base directory to start walking from (up to the first glob segment)\n const firstGlobIdx = absPattern.search(/[*?[\\]{}]/);\n const baseDir =\n firstGlobIdx === -1\n ? findFilePath(absPattern)\n : absPattern.slice(\n 0,\n Math.max(0, absPattern.lastIndexOf(\"/\", firstGlobIdx))\n );\n\n const files = this.listSync(\n baseDir && isAbsolutePath(baseDir)\n ? baseDir\n : this.#context.workspaceConfig.workspaceRoot\n );\n for (const file of files) {\n if (this.#buildRegex(absPattern).test(file)) {\n const resolved = this.resolveSync(file);\n if (resolved && !results.includes(resolved)) {\n results.push(resolved);\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);\n if (!filePath) {\n return undefined;\n }\n\n const { relativeKey, adapter } = this.#getStorage(filePath);\n this.#log(LogLevelLabel.TRACE, `Reading ${adapter.name} file: ${filePath}`);\n\n return (await adapter.get(relativeKey)) ?? 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);\n if (!filePath) {\n return undefined;\n }\n\n const { relativeKey, adapter } = this.#getStorage(filePath);\n this.#log(LogLevelLabel.TRACE, `Reading ${adapter.name} file: ${filePath}`);\n\n return adapter.getSync(relativeKey) ?? 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 let code = data;\n if (!options.skipFormat) {\n const resolvedConfig = await resolveConfig(this.#normalizePath(path));\n if (resolvedConfig) {\n code = await format(data, {\n absolutePath: this.#normalizePath(path),\n ...resolvedConfig\n });\n }\n }\n\n const { relativeKey, adapter } = this.#getStorage(path);\n\n this.#log(\n LogLevelLabel.TRACE,\n `Writing ${this.#normalizePath(relativeKey)} 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 = options?.meta?.id || this.#normalizeId(relativeKey);\n this.#metadata[id] = {\n variant: \"normal\",\n timestamp: Date.now(),\n ...(options.meta ?? {})\n } as VirtualFileMetadata;\n this.#paths[id] = this.#normalizePath(relativeKey);\n this.#ids[this.#normalizePath(relativeKey)] = 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 { relativeKey, adapter } = this.#getStorage(path);\n\n this.#log(\n LogLevelLabel.TRACE,\n `Writing ${this.#normalizePath(relativeKey)} 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 = options?.meta?.id || this.#normalizeId(relativeKey);\n this.#metadata[id] = {\n variant: \"normal\",\n timestamp: Date.now(),\n ...(options.meta ?? {})\n } as VirtualFileMetadata;\n this.#paths[id] = this.#normalizePath(relativeKey);\n this.#ids[this.#normalizePath(relativeKey)] = 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 * 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 let path = id;\n if (path.includes(\"{\") || path.includes(\"}\")) {\n path = replacePathTokens(this.#context, path);\n }\n\n if (isAbsolutePath(path)) {\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 paths.push(this.#context.workspaceConfig.workspaceRoot);\n paths.push(\n appendPath(\n this.#context.config.projectRoot,\n this.#context.workspaceConfig.workspaceRoot\n )\n );\n paths.push(\n appendPath(\n this.#context.config.sourceRoot,\n this.#context.workspaceConfig.workspaceRoot\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 }\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 public resolveSync(\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 (isAbsolutePath(path)) {\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 paths.push(this.#context.workspaceConfig.workspaceRoot);\n paths.push(\n appendPath(\n this.#context.config.projectRoot,\n this.#context.workspaceConfig.workspaceRoot\n )\n );\n paths.push(\n appendPath(\n this.#context.config.sourceRoot,\n this.#context.workspaceConfig.workspaceRoot\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 }\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 * 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 paths = await this.list();\n\n const storage = fs._initStorage(paths.length);\n await Promise.all(\n 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(([, path]) => path)\n .forEach(([id, path], 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 ?? BigInt(Date.now());\n\n if (value.properties) {\n const props = fileMetadata._initProperties(\n Object.keys(value.properties).length\n );\n Object.entries(value.properties).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 { LogLevelLabel } from \"@storm-software/config-tools/types\";\nimport { existsSync } from \"@stryke/fs/exists\";\nimport { readJsonFile } from \"@stryke/fs/json\";\nimport { listFiles } from \"@stryke/fs/list-files\";\nimport { removeFile } from \"@stryke/fs/remove-file\";\nimport { getUnique } from \"@stryke/helpers/get-unique\";\nimport { hasFileExtension } from \"@stryke/path/file-path-fns\";\nimport { joinPaths } from \"@stryke/path/join-paths\";\nimport { kebabCase } from \"@stryke/string-format/kebab-case\";\nimport { Context, MetaInfo } from \"../../types/context\";\n\nexport interface CreateContextOptions {\n name?: string;\n}\n\nexport const PROJECT_ROOT_HASH_LENGTH = 45;\nexport const CACHE_HASH_LENGTH = 62;\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 projectRootHash - The hash of the project root.\n * @returns An object containing the name and project root hash.\n */\nexport function getPrefixedProjectRootHash(\n name: string,\n projectRootHash: string\n): string {\n const combined = `${kebabCase(name)}_${projectRootHash}`;\n\n return combined.length > PROJECT_ROOT_HASH_LENGTH\n ? combined.slice(0, PROJECT_ROOT_HASH_LENGTH)\n : combined;\n}\n\nasync function discoverTemplatePath(path: string): Promise<string[]> {\n return (\n await Promise.all([\n Promise.resolve(/.tsx?$/.test(path) && !path.includes(\"*\") && path),\n Promise.resolve(!hasFileExtension(path) && joinPaths(path, \".ts\")),\n Promise.resolve(!hasFileExtension(path) && joinPaths(path, \".tsx\")),\n Promise.resolve(\n !hasFileExtension(path) && listFiles(joinPaths(path, \"**/*.ts\"))\n ),\n Promise.resolve(\n !hasFileExtension(path) && listFiles(joinPaths(path, \"**/*.tsx\"))\n )\n ])\n )\n .flat()\n .filter(Boolean) as string[];\n}\n\nexport async function discoverTemplates(\n context: Context,\n paths: string[] = []\n): Promise<string[]> {\n return getUnique(\n (\n await Promise.all([\n ...paths.map(discoverTemplatePath),\n discoverTemplatePath(joinPaths(context.config.sourceRoot, \"plugin\")),\n discoverTemplatePath(joinPaths(context.envPaths.config, \"templates\")),\n discoverTemplatePath(joinPaths(context.config.projectRoot, \"templates\"))\n ])\n )\n .flat()\n .reduce((ret, path) => {\n if (existsSync(path)) {\n ret.push(path);\n }\n\n return ret;\n }, [] as string[])\n );\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.log(\n LogLevelLabel.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.log(\n LogLevelLabel.DEBUG,\n `Writing runtime metadata to ${metaFilePath}`\n );\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 { 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 { hashDirectory } from \"@stryke/hash/hash-files\";\nimport { murmurhash } from \"@stryke/hash/murmurhash\";\nimport { getUnique } 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 { isAbsolute } from \"@stryke/path/is-type\";\nimport { joinPaths } from \"@stryke/path/join\";\nimport { replacePath } from \"@stryke/path/replace\";\nimport { titleCase } from \"@stryke/string-format/title-case\";\nimport { isNull } from \"@stryke/type-checks/is-null\";\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 { PackageJson } from \"@stryke/types/package-json\";\nimport { uuid } from \"@stryke/unique-id/uuid\";\nimport { match, tsconfigPathsToRegExp } from \"bundle-require\";\nimport defu from \"defu\";\nimport { create, FlatCache } from \"flat-cache\";\nimport { parse, ParseResult } from \"oxc-parser\";\nimport { Range } from \"semver\";\nimport { Project } from \"ts-morph\";\nimport {\n Agent,\n BodyInit,\n interceptors,\n RequestInfo,\n Response,\n setGlobalDispatcher\n} from \"undici\";\nimport { ExternalIdResult, UnpluginMessage } from \"unplugin\";\nimport {\n createResolver,\n CreateResolverOptions\n} from \"../../internal/helpers/resolver\";\nimport { checkDedupe, isPlugin } from \"../../plugin-utils/helpers\";\nimport { replacePathTokens } from \"../../plugin-utils/paths\";\nimport {\n InitialUserConfig,\n LogFn,\n ParsedUserConfig,\n PluginConfig,\n PowerlinesCommand,\n WorkspaceConfig\n} from \"../../types/config\";\nimport {\n Context,\n FetchOptions,\n InitContextOptions,\n MetaInfo,\n ParseOptions,\n Resolver,\n TransformResult\n} from \"../../types/context\";\nimport {\n ResolveOptions,\n VirtualFile,\n VirtualFileSystemInterface,\n WriteOptions\n} from \"../../types/fs\";\nimport { UNSAFE_ContextInternal } from \"../../types/internal\";\nimport {\n ResolvedConfig,\n ResolvedEntryTypeDefinition\n} from \"../../types/resolved\";\nimport { ParsedTypeScriptConfig } from \"../../types/tsconfig\";\nimport { loadUserConfigFile, loadWorkspaceConfig } from \"../config-file\";\nimport { getUniqueEntries, resolveEntriesSync } from \"../entry\";\nimport { VirtualFileSystem } from \"../fs/vfs\";\nimport { createLog, extendLog } from \"../logger\";\nimport { createProgram } from \"../typescript/ts-morph\";\nimport { getTsconfigFilePath } from \"../typescript/tsconfig\";\nimport {\n CACHE_HASH_LENGTH,\n getPrefixedProjectRootHash,\n PROJECT_ROOT_HASH_LENGTH\n} from \"../utilities/meta\";\n\ninterface ConfigCacheKey {\n projectRoot: string;\n mode: \"test\" | \"development\" | \"production\";\n skipCache: boolean;\n configFile?: string;\n framework: string;\n command?: string;\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\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 #envPaths: EnvPaths;\n\n #fs!: VirtualFileSystemInterface;\n\n #tsconfig!: ParsedTypeScriptConfig;\n\n #program!: Project;\n\n #parserCache!: FlatCache;\n\n #requestCache!: FlatCache;\n\n #getConfigProps(config: Partial<TResolvedConfig[\"userConfig\"]> = {}) {\n return {\n variant: config.build?.variant,\n projectType: config.type,\n projectRoot: config.root,\n name: config.name,\n title: config.title,\n description: config.description,\n sourceRoot: config.sourceRoot,\n configFile: config.configFile,\n customLogger: config.customLogger,\n logLevel: config.logLevel,\n tsconfig: config.tsconfig,\n tsconfigRaw: config.tsconfigRaw,\n skipCache: config.skipCache,\n skipInstalls: config.skipInstalls,\n entry: config.entry,\n output: config.output,\n plugins: config.plugins,\n mode: config.mode,\n lint: config.lint,\n transform: config.transform,\n build: config.build,\n framework: config.framework,\n ...config\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 context.powerlinesPath = await resolvePackage(\"powerlines\");\n if (!context.powerlinesPath) {\n throw new Error(\"Could not resolve `powerlines` package location.\");\n }\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 return resolveEntriesSync(this, toArray(this.config.entry));\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 projectRootHash: murmurhash(\n {\n workspaceRoot: this.workspaceConfig?.workspaceRoot,\n projectRoot: this.config?.projectRoot\n },\n {\n maxLength: PROJECT_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 (!this.#envPaths) {\n this.#envPaths = getEnvPaths({\n orgId: \"storm-software\",\n appId: \"powerlines\",\n workspaceRoot: this.workspaceConfig.workspaceRoot\n });\n }\n\n return this.#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.projectRoot,\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 data directory for the project\n */\n public get dataPath(): string {\n return joinPaths(\n this.envPaths.data,\n \"projects\",\n getPrefixedProjectRootHash(this.config.name, this.meta.projectRootHash)\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.projectRoot,\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.projectRoot);\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 {@link Project} instance used for type reflection and module manipulation\n *\n * @see https://ts-morph.com/\n *\n * @remarks\n * This instance is created lazily on first access.\n */\n public get program(): Project {\n if (!this.#program) {\n this.#program = createProgram(this, {\n skipAddingFilesFromTsConfig: true\n });\n }\n\n return this.#program;\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: 5 * 60 * 1000,\n lruSize: 5000,\n persistInterval: 250\n });\n }\n\n return this.#requestCache;\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<{ body: BodyInit } & ResponseInit>(\n cacheKey\n );\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<ExternalIdResult | undefined> {\n let moduleId = id;\n if (this.config.build.alias) {\n if (Array.isArray(this.config.build.alias)) {\n const alias = this.config.build.alias.find(a =>\n match(moduleId, [a.find])\n );\n if (alias) {\n moduleId = alias.replacement;\n }\n } else if (\n isSetObject(this.config.build.alias) &&\n this.config.build.alias[id]\n ) {\n moduleId = this.config.build.alias[id];\n }\n }\n\n if (this.fs.isVirtual(moduleId)) {\n const result = await this.fs.resolve(moduleId, importer, {\n conditions: this.config.build.conditions,\n extensions: this.config.build.extensions,\n ...options\n });\n if (!result) {\n return undefined;\n }\n\n return {\n id: `\\0${result}`,\n external: this.config.projectType !== \"application\"\n };\n }\n\n if (this.config.build.skipNodeModulesBundle) {\n if (\n match(moduleId, this.resolvePatterns) ||\n match(moduleId, this.config.build.noExternal)\n ) {\n return undefined;\n }\n\n if (\n match(moduleId, this.config.build.external) ||\n moduleId.startsWith(\"node:\")\n ) {\n return { id: moduleId, external: true };\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 };\n }\n } else {\n if (match(moduleId, this.config.build.noExternal)) {\n return undefined;\n }\n\n if (\n match(moduleId, this.config.build.external) ||\n moduleId.startsWith(\"node:\")\n ) {\n return { id: moduleId, external: true };\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 ([path, meta]) => {\n const code = await this.fs.read(path);\n\n return { ...meta, path, code } as VirtualFile;\n })\n );\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: WriteOptions = {}\n ): Promise<void> {\n return this.fs.write(\n isAbsolute(path) ? path : appendPath(path, this.entryPath),\n code,\n defu(options, { type: \"entry\" })\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 path - An optional path to write the builtin file to\n * @param options - Optional write file options\n */\n public async emitBuiltin(\n code: string,\n id: string,\n path?: string,\n options: WriteOptions = {}\n ): Promise<void> {\n return this.fs.write(\n path\n ? isAbsolute(path)\n ? path\n : joinPaths(this.builtinsPath, path)\n : appendPath(id, this.builtinsPath),\n code,\n defu(options, { type: \"builtin\" })\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(\n root = this.config.projectRoot\n ): Promise<string> {\n this.#checksum = await hashDirectory(root, {\n ignore: [\"node_modules\", \".git\", \".nx\", \".cache\", \".storm\", \"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 this.#envPaths = getEnvPaths({\n orgId: \"storm-software\",\n appId: \"powerlines\",\n workspaceRoot: workspaceConfig.workspaceRoot\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 projectRoot:\n config.root ??\n this.config.projectRoot ??\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 };\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.projectRoot, \"project.json\");\n if (existsSync(projectJsonPath)) {\n this.projectJson = await readJsonFile(projectJsonPath);\n }\n\n const packageJsonPath = joinPaths(cacheKey.projectRoot, \"package.json\");\n if (existsSync(packageJsonPath)) {\n this.packageJson = await readJsonFile<PackageJson>(packageJsonPath);\n }\n\n this.#checksum = await this.generateChecksum(cacheKey.projectRoot);\n this.resolver = createResolver({\n workspaceRoot: this.workspaceConfig.workspaceRoot,\n projectRoot: cacheKey.projectRoot,\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 });\n\n const userConfig = await loadUserConfigFile(\n cacheKey.projectRoot,\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.projectRoot,\n config.tsconfig\n );\n\n if (isSetObject(config)) {\n this.resolvedConfig = defu(\n {\n inlineConfig: this.config.inlineConfig,\n userConfig: this.config.userConfig\n },\n options.isHighPriority ? this.#getConfigProps(config) : {},\n {\n command: this.config.inlineConfig?.command,\n ...this.#getConfigProps(this.config.inlineConfig)\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 sourceRoot:\n this.projectJson?.sourceRoot ||\n appendPath(\"src\", cacheKey.projectRoot),\n output: defu(config.output ?? {}, {\n outputPath: cacheKey.projectRoot\n ? joinPaths(\n this.workspaceConfig?.directories?.build || \"dist\",\n cacheKey.projectRoot\n )\n : this.workspaceConfig?.directories?.build || \"dist\",\n artifactsPath: joinPaths(\n cacheKey.projectRoot,\n `.${config.framework ?? \"powerlines\"}`\n ),\n dts: joinPaths(\n cacheKey.projectRoot,\n `${config.framework ?? \"powerlines\"}.d.ts`\n ),\n builtinPrefix: config.framework ?? \"powerlines\",\n assets: [\n {\n glob: \"LICENSE\"\n },\n {\n input: cacheKey.projectRoot,\n glob: \"*.md\"\n },\n {\n input: cacheKey.projectRoot,\n glob: \"package.json\"\n }\n ]\n })\n },\n options.isHighPriority ? {} : this.#getConfigProps(config),\n {\n inlineConfig: {},\n userConfig: {},\n framework: \"powerlines\",\n platform: \"neutral\",\n mode: \"production\",\n projectType: \"application\",\n logLevel: \"info\",\n preview: false,\n environments: {},\n transform: {\n babel: {\n plugins: [],\n presets: []\n }\n },\n lint: {\n eslint: {}\n },\n build: {\n target: \"esnext\",\n override: {}\n }\n }\n ) as any;\n }\n\n this.config.entry = getUniqueEntries(this.config.entry);\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 if (this.config.userConfig.build?.external) {\n this.config.userConfig.build.external = getUnique(\n this.config.userConfig.build.external\n );\n }\n if (this.config.userConfig.build?.noExternal) {\n this.config.userConfig.build.noExternal = getUnique(\n this.config.userConfig.build.noExternal\n );\n }\n\n if (this.config.build.external) {\n this.config.build.external = getUnique(this.config.build.external);\n }\n if (this.config.build.noExternal) {\n this.config.build.noExternal = getUnique(this.config.build.noExternal);\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.projectRoot &&\n this.config.projectRoot !== \".\" &&\n this.config.projectRoot !== \"./\" &&\n this.config.projectRoot !== this.workspaceConfig.workspaceRoot\n ) {\n this.config.output.outputPath ??= joinPaths(\n \"dist\",\n this.config.projectRoot\n );\n this.config.output.buildPath ??= joinPaths(\n this.config.projectRoot,\n \"dist\"\n );\n } else {\n this.config.output.outputPath ??= \"dist\";\n this.config.output.buildPath ??= \"dist\";\n }\n\n this.config.output.assets = getUnique(\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 : appendPath(asset.input, this.workspaceConfig.workspaceRoot),\n output: appendPath(\n isSetObject(asset) && asset.output\n ? joinPaths(\n this.config.output.outputPath,\n replacePath(asset.output, this.config.output.outputPath)\n )\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 );\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 this.config.output.dts = replacePathTokens(this, this.config.output.dts);\n }\n\n if (this.config.build.polyfill) {\n this.config.build.polyfill = this.config.build.polyfill.map(polyfill =>\n replacePathTokens(this, polyfill)\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 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 = defu(\n {\n entry:\n Array.isArray(from.entry) && from.entry.length > 0\n ? from.entry\n : Array.isArray(into?.entry) && into.entry.length > 0\n ? into.entry\n : []\n },\n omit(from ?? {}, [\"entry\"]),\n omit(into ?? {}, [\"entry\"])\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\nimport type { ArrayValues } from \"@stryke/types/array\";\nimport type { FunctionLike, MaybePromise } from \"@stryke/types/base\";\nimport type {\n ExternalIdResult,\n HookFilter,\n TransformResult,\n UnpluginOptions\n} from \"unplugin\";\nimport type { UnpluginBuildVariant } from \"./build\";\nimport type { CommandType } from \"./commands\";\nimport type { EnvironmentConfig, PluginConfig } from \"./config\";\nimport type {\n BuildPluginContext,\n PluginContext,\n UnresolvedContext\n} from \"./context\";\nimport type { EnvironmentResolvedConfig, ResolvedConfig } from \"./resolved\";\n\nexport interface PluginHookObject<\n THookFunction extends FunctionLike,\n TFilter extends keyof HookFilter = never\n> {\n /**\n * The order in which the plugin should be applied.\n */\n order?: \"pre\" | \"post\" | null | undefined;\n\n /**\n * A filter to determine when the hook should be called.\n */\n filter?: Pick<HookFilter, TFilter>;\n\n /**\n * The hook function to be called.\n */\n handler: THookFunction;\n}\n\nexport type PluginHook<\n THookFunction extends FunctionLike,\n TFilter extends keyof HookFilter = never\n> = THookFunction | PluginHookObject<THookFunction, TFilter>;\n\n/**\n * A result returned by the plugin from the `types` hook that describes the declaration types output file.\n */\nexport interface TypesResult {\n directives?: string[];\n code: string;\n}\n\ntype DeepPartial<T> = {\n [K in keyof T]?: DeepPartial<T[K]>;\n};\n\nexport type ConfigResult<TContext extends PluginContext = PluginContext> =\n DeepPartial<TContext[\"config\"]> & Record<string, any>;\n\nexport interface BasePluginHookFunctions<\n TContext extends PluginContext = PluginContext\n> extends Record<CommandType, (this: TContext) => MaybePromise<void>> {\n /**\n * A function that returns configuration options to be merged with the build context's options.\n *\n * @remarks\n * Modify config before it's resolved. The hook can either mutate {@link Context.config} on the passed-in context directly, or return a partial config object that will be deeply merged into existing config.\n *\n * @warning User plugins are resolved before running this hook so injecting other plugins inside the config hook will have no effect. If you want to add plugins, consider doing so in the {@link Plugin.dependsOn} property instead.\n *\n * @see https://vitejs.dev/guide/api-plugin#config\n *\n * @param this - The build context.\n * @param config - The partial configuration object to be modified.\n * @returns A promise that resolves to a partial configuration object.\n */\n config: (\n this: UnresolvedContext<TContext[\"config\"]>\n ) => MaybePromise<ConfigResult<TContext>>;\n\n /**\n * Modify environment configs before it's resolved. The hook can either mutate the passed-in environment config directly, or return a partial config object that will be deeply merged into existing config.\n *\n * @remarks\n * This hook is called for each environment with a partially resolved environment config that already accounts for the default environment config values set at the root level. If plugins need to modify the config of a given environment, they should do it in this hook instead of the config hook. Leaving the config hook only for modifying the root default environment config.\n *\n * @see https://vitejs.dev/guide/api-plugin#configenvironment\n *\n * @param this - The build context.\n * @param name - The name of the environment being configured.\n * @param environment - The Vite-like environment object containing information about the current build environment.\n * @returns A promise that resolves when the hook is complete.\n */\n configEnvironment: (\n this: TContext,\n name: string,\n environment: EnvironmentConfig\n ) => MaybePromise<Partial<EnvironmentResolvedConfig> | undefined | null>;\n\n /**\n * A hook that is called when the plugin is resolved.\n *\n * @see https://vitejs.dev/guide/api-plugin#configresolved\n *\n * @param this - The build context.\n * @returns A promise that resolves when the hook is complete.\n */\n configResolved: (this: TContext) => MaybePromise<void>;\n\n /**\n * A hook that is called to overwrite the generated declaration types file (.d.ts). The generated type definitions should describe the built-in modules/logic added during the `prepare` task.\n *\n * @param this - The build context.\n * @param code - The source code to generate types for.\n * @returns A promise that resolves when the hook is complete.\n */\n types: (\n this: TContext,\n code: string\n ) => MaybePromise<TypesResult | string | undefined | null>;\n\n /**\n * A hook that is called at the start of the build process.\n *\n * @param this - The build context and unplugin build context.\n * @returns A promise that resolves when the hook is complete.\n */\n buildStart: (\n this: BuildPluginContext<TContext[\"config\"]> & TContext\n ) => MaybePromise<void>;\n\n /**\n * A hook that is called at the end of the build process.\n *\n * @param this - The build context and unplugin build context.\n * @returns A promise that resolves when the hook is complete.\n */\n buildEnd: (\n this: BuildPluginContext<TContext[\"config\"]> & TContext\n ) => MaybePromise<void>;\n\n /**\n * A hook that is called to transform the source code.\n *\n * @param this - The build context, unplugin build context, and unplugin context.\n * @param code - The source code to transform.\n * @param id - The identifier of the source code.\n * @returns A promise that resolves when the hook is complete.\n */\n transform: (\n this: BuildPluginContext<TContext[\"config\"]> & TContext,\n code: string,\n id: string\n ) => MaybePromise<TransformResult>;\n\n /**\n * A hook that is called to load the source code.\n *\n * @param this - The build context, unplugin build context, and unplugin context.\n * @param id - The identifier of the source code.\n * @returns A promise that resolves when the hook is complete.\n */\n load: (\n this: BuildPluginContext<TContext[\"config\"]> & TContext,\n id: string\n ) => MaybePromise<TransformResult>;\n\n /**\n * A hook that is called to resolve the identifier of the source code.\n *\n * @param this - The build context, unplugin build context, and unplugin context.\n * @param id - The identifier of the source code.\n * @param importer - The importer of the source code.\n * @param options - The options for resolving the identifier.\n * @returns A promise that resolves when the hook is complete.\n */\n resolveId: (\n this: BuildPluginContext<TContext[\"config\"]> & TContext,\n id: string,\n importer: string | undefined,\n options: { isEntry: boolean }\n ) => MaybePromise<string | ExternalIdResult | null | undefined>;\n\n /**\n * A hook that is called to write the bundle to disk.\n *\n * @param this - The build context.\n * @returns A promise that resolves when the hook is complete.\n */\n writeBundle: (this: TContext) => MaybePromise<void>;\n}\n\nexport type BuildPlugin<\n TContext extends PluginContext = PluginContext,\n TBuildVariant extends UnpluginBuildVariant = UnpluginBuildVariant,\n TOptions extends Required<UnpluginOptions>[TBuildVariant] =\n Required<UnpluginOptions>[TBuildVariant]\n> = {\n [TKey in keyof TOptions]: TOptions[TKey] extends FunctionLike\n ? (\n this: ThisParameterType<TOptions[TKey]> & TContext,\n ...args: Parameters<TOptions[TKey]>\n ) => ReturnType<TOptions[TKey]> | MaybePromise<ReturnType<TOptions[TKey]>>\n : TOptions[TKey];\n};\n\nexport type ExternalPluginHookFunctionsVariant<\n TContext extends PluginContext = PluginContext,\n TBuildVariant extends UnpluginBuildVariant = UnpluginBuildVariant\n> = {\n [TKey in keyof BuildPlugin<TContext, TBuildVariant> &\n string as `${TBuildVariant}:${TKey}`]: BuildPlugin<\n TContext,\n TBuildVariant\n >[TKey];\n};\n\nexport type ExternalPluginHookFunctions<TContext extends PluginContext> =\n ExternalPluginHookFunctionsVariant<TContext, \"vite\"> &\n ExternalPluginHookFunctionsVariant<TContext, \"esbuild\"> &\n ExternalPluginHookFunctionsVariant<TContext, \"rolldown\"> &\n ExternalPluginHookFunctionsVariant<TContext, \"rollup\"> &\n ExternalPluginHookFunctionsVariant<TContext, \"webpack\"> &\n ExternalPluginHookFunctionsVariant<TContext, \"rspack\"> &\n ExternalPluginHookFunctionsVariant<TContext, \"farm\">;\n\nexport type PluginHookFunctions<\n TContext extends PluginContext = PluginContext\n> = BasePluginHookFunctions<TContext> & ExternalPluginHookFunctions<TContext>;\n\nexport type PluginHooks<TContext extends PluginContext = PluginContext> = {\n [TKey in keyof BasePluginHookFunctions<TContext>]: PluginHook<\n BasePluginHookFunctions<TContext>[TKey]\n >;\n} & {\n /**\n * A function that returns configuration options to be merged with the build context's options.\n *\n * @remarks\n * Modify config before it's resolved. The hook can either mutate {@link Context.config} on the passed-in context directly, or return a partial config object that will be deeply merged into existing config.\n *\n * @warning User plugins are resolved before running this hook so injecting other plugins inside the config hook will have no effect. If you want to add plugins, consider doing so in the {@link Plugin.dependsOn} property instead.\n *\n * @see https://vitejs.dev/guide/api-plugin#config\n *\n * @param this - The build context.\n * @param config - The partial configuration object to be modified.\n * @returns A promise that resolves to a partial configuration object.\n */\n config:\n | PluginHook<\n (\n this: UnresolvedContext<TContext[\"config\"]>\n ) => MaybePromise<ConfigResult<TContext>>\n >\n | ConfigResult<TContext>;\n\n /**\n * A hook that is called to transform the source code.\n *\n * @param this - The build context, unplugin build context, and unplugin context.\n * @param code - The source code to transform.\n * @param id - The identifier of the source code.\n * @returns A promise that resolves when the hook is complete.\n */\n transform: PluginHook<\n (\n this: BuildPluginContext<TContext[\"config\"]> & TContext,\n code: string,\n id: string\n ) => MaybePromise<TransformResult>,\n \"code\" | \"id\"\n >;\n\n /**\n * A hook that is called to load the source code.\n *\n * @param this - The build context, unplugin build context, and unplugin context.\n * @param id - The identifier of the source code.\n * @returns A promise that resolves when the hook is complete.\n */\n load: PluginHook<\n (\n this: BuildPluginContext<TContext[\"config\"]> & TContext,\n id: string\n ) => MaybePromise<TransformResult>,\n \"id\"\n >;\n\n /**\n * A hook that is called to resolve the identifier of the source code.\n *\n * @param this - The build context, unplugin build context, and unplugin context.\n * @param id - The identifier of the source code.\n * @param importer - The importer of the source code.\n * @param options - The options for resolving the identifier.\n * @returns A promise that resolves when the hook is complete.\n */\n resolveId: PluginHook<\n (\n this: BuildPluginContext<TContext[\"config\"]> & TContext,\n id: string,\n importer: string | undefined,\n options: { isEntry: boolean }\n ) => MaybePromise<string | ExternalIdResult | null | undefined>,\n \"id\"\n >;\n};\n\nexport type PluginBuildPlugins<TContext extends PluginContext = PluginContext> =\n {\n [TBuildVariant in UnpluginBuildVariant]?: BuildPlugin<\n TContext,\n TBuildVariant\n >;\n };\n\nexport interface Plugin<\n in out TContext extends PluginContext<ResolvedConfig> =\n PluginContext<ResolvedConfig>\n>\n extends Partial<PluginHooks<TContext>>, PluginBuildPlugins<TContext> {\n /**\n * The name of the plugin, for use in deduplication, error messages and logs.\n */\n name: string;\n\n /**\n * An API object that can be used for inter-plugin communication.\n *\n * @see https://rollupjs.org/plugin-development/#direct-plugin-communication\n */\n api?: Record<string, any>;\n\n /**\n * Enforce plugin invocation tier similar to webpack loaders. Hooks ordering is still subject to the `order` property in the hook object.\n *\n * @remarks\n * The Plugin invocation order is as follows:\n * - `enforce: 'pre'` plugins\n * - `order: 'pre'` plugin hooks\n * - any other plugins (normal)\n * - `order: 'post'` plugin hooks\n * - `enforce: 'post'` plugins\n *\n * @see https://vitejs.dev/guide/api-plugin.html#plugin-ordering\n * @see https://rollupjs.org/plugin-development/#build-hooks\n * @see https://webpack.js.org/concepts/loaders/#enforce---pre-and-post\n * @see https://esbuild.github.io/plugins/#concepts\n */\n enforce?: \"pre\" | \"post\";\n\n /**\n * A function to determine if two plugins are the same and can be de-duplicated.\n *\n * @remarks\n * If this is not provided, plugins are de-duplicated by comparing their names.\n *\n * @param other - The other plugin to compare against.\n * @returns `true` if the two plugins are the same, `false` otherwise.\n */\n dedupe?: false | ((other: Plugin<any>) => boolean);\n\n /**\n * A list of pre-requisite plugins that must be loaded before this plugin can be used.\n */\n dependsOn?: PluginConfig<any>[];\n\n /**\n * Define environments where this plugin should be active. By default, the plugin is active in all environments.\n *\n * @param environment - The environment to check.\n * @returns `true` if the plugin should be active in the specified environment, `false` otherwise.\n */\n applyToEnvironment?: (\n environment: EnvironmentResolvedConfig\n ) => MaybePromise<boolean | Plugin<TContext>>;\n}\n\nexport const PLUGIN_NON_HOOK_FIELDS = [\n \"name\",\n \"api\",\n \"enforce\",\n \"dedupe\",\n \"dependsOn\",\n \"applyToEnvironment\"\n] as const;\n\nexport type PluginNonHookFields =\n | ArrayValues<typeof PLUGIN_NON_HOOK_FIELDS>\n | UnpluginBuildVariant;\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 { isString } from \"@stryke/type-checks/is-string\";\nimport { UnpluginMessage } from \"unplugin\";\nimport { CallHookOptions } from \"../../internal/helpers/hooks\";\nimport { LogFn } from \"../../types/config\";\nimport { EnvironmentContext, PluginContext } from \"../../types/context\";\nimport {\n HookKeys,\n InferHookParameters,\n InferHookReturnType\n} from \"../../types/hooks\";\nimport {\n UNSAFE_EnvironmentContext,\n UNSAFE_PluginContext\n} from \"../../types/internal\";\nimport { Plugin } from \"../../types/plugin\";\nimport { ResolvedConfig } from \"../../types/resolved\";\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);\n\n const callHookFn = async <\n TKey extends HookKeys<PluginContext<TResolvedConfig>>\n >(\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 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 };\n }\n\n if (prop === \"log\" || prop === \"logger\") {\n return log;\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 { ArrayValues } from \"@stryke/types/array\";\nimport {\n addPluginHook,\n getHookHandler,\n isHookExternal,\n isPlugin,\n isPluginHook\n} from \"../../plugin-utils/helpers\";\nimport { WorkspaceConfig } from \"../../types/config\";\nimport {\n EnvironmentContext,\n EnvironmentContextPlugin,\n PluginContext,\n SelectHooksOptions,\n SelectHooksResult\n} from \"../../types/context\";\nimport { BaseHooksList, HookKeys, HooksList } from \"../../types/hooks\";\nimport { Plugin, PLUGIN_NON_HOOK_FIELDS } from \"../../types/plugin\";\nimport {\n EnvironmentResolvedConfig,\n ResolvedConfig\n} from \"../../types/resolved\";\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 context.powerlinesPath = await resolvePackage(\"powerlines\");\n if (!context.powerlinesPath) {\n throw new Error(\"Could not resolve `powerlines` package location.\");\n }\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 (plugin.applyToEnvironment) {\n const result = await Promise.resolve(\n plugin.applyToEnvironment(this.environment)\n );\n if (!result || (isObject(result) && Object.keys(result).length === 0)) {\n return;\n }\n\n resolvedPlugin = isPlugin<TResolvedConfig>(result) ? result : 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 keyof HooksList<PluginContext<TResolvedConfig>>;\n const pluginHook = resolvedPlugin[hook as keyof typeof resolvedPlugin];\n if (!isPluginHook(pluginHook)) {\n return ret;\n }\n\n if (!isHookExternal(hook)) {\n ret[hook] ??= {};\n if (resolvedPlugin.enforce) {\n ret[hook][`${resolvedPlugin.enforce}Enforced`] ??= [];\n\n addPluginHook(\n context,\n resolvedPlugin,\n pluginHook,\n ret[hook][`${resolvedPlugin.enforce}Enforced`]!\n );\n\n return ret;\n }\n\n if (isFunction(pluginHook) || !pluginHook.order) {\n ret[hook].normal ??= [];\n\n addPluginHook(\n context,\n resolvedPlugin,\n pluginHook,\n ret[hook].normal\n );\n\n return ret;\n }\n\n ret[hook][`${pluginHook.order}Ordered`] ??= [];\n\n addPluginHook(\n context,\n resolvedPlugin,\n pluginHook,\n ret[hook][`${pluginHook.order}Ordered`]!\n );\n } else {\n ret[hook] ??= [];\n ret[hook].push({\n plugin: resolvedPlugin,\n hook: getHookHandler(pluginHook).bind(context)\n } as any);\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 HookKeys<PluginContext<TResolvedConfig>>>(\n hook: TKey,\n options?: SelectHooksOptions\n ): SelectHooksResult<TResolvedConfig, TKey>[] {\n const result = [] as SelectHooksResult<TResolvedConfig, TKey>[];\n\n if (this.hooks[hook]) {\n if (!isHookExternal(hook)) {\n const hooks = this.hooks[hook] as BaseHooksList<\n PluginContext<TResolvedConfig>\n >;\n if (options?.order) {\n if (options?.order === \"pre\") {\n result.push(\n ...(hooks.preOrdered ?? []).map(h => {\n const plugin = this.plugins.find(\n p => p.plugin.name === h.plugin.name\n );\n if (!plugin) {\n throw new Error(\n `Could not find plugin context for plugin \"${\n h.plugin.name\n }\".`\n );\n }\n\n return {\n handle: h.handler,\n context: plugin.context\n };\n })\n );\n result.push(\n ...(hooks.preEnforced ?? []).map(h => {\n const plugin = this.plugins.find(\n p => p.plugin.name === h.plugin.name\n );\n if (!plugin) {\n throw new Error(\n `Could not find plugin context for plugin \"${\n h.plugin.name\n }\".`\n );\n }\n\n return {\n handle: h.handler,\n context: plugin.context\n };\n })\n );\n } else if (options?.order === \"post\") {\n result.push(\n ...(hooks.postOrdered ?? []).map(h => {\n const plugin = this.plugins.find(\n p => p.plugin.name === h.plugin.name\n );\n if (!plugin) {\n throw new Error(\n `Could not find plugin context for plugin \"${\n h.plugin.name\n }\".`\n );\n }\n\n return {\n handle: h.handler,\n context: plugin.context\n };\n })\n );\n result.push(\n ...(hooks.postEnforced ?? []).map(h => {\n const plugin = this.plugins.find(\n p => p.plugin.name === h.plugin.name\n );\n if (!plugin) {\n throw new Error(\n `Could not find plugin context for plugin \"${\n h.plugin.name\n }\".`\n );\n }\n\n return {\n handle: h.handler,\n context: plugin.context\n };\n })\n );\n } else {\n result.push(\n ...(hooks.normal ?? []).map(h => {\n const plugin = this.plugins.find(\n p => p.plugin.name === h.plugin.name\n );\n if (!plugin) {\n throw new Error(\n `Could not find plugin context for plugin \"${\n h.plugin.name\n }\".`\n );\n }\n\n return {\n handle: h.handler,\n context: plugin.context\n };\n })\n );\n }\n } else {\n result.push(...this.selectHooks(hook, { order: \"pre\" }));\n result.push(...this.selectHooks(hook, { order: \"normal\" }));\n result.push(...this.selectHooks(hook, { order: \"post\" }));\n }\n } else {\n result.push(\n ...this.hooks[hook].map(h => {\n const plugin = this.plugins.find(\n p => p.plugin.name === h.plugin.name\n );\n if (!plugin) {\n throw new Error(\n `Could not find plugin context for plugin \"${h.plugin.name}\".`\n );\n }\n\n return {\n handle: h.handler,\n context: plugin.context\n };\n })\n );\n }\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 { LogLevelLabel } from \"@storm-software/config-tools/types\";\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 {\n InitialUserConfig,\n InlineConfig,\n LogFn,\n UserConfig,\n WorkspaceConfig\n} from \"../../types/config\";\nimport {\n APIContext,\n EnvironmentContext,\n InitContextOptions,\n PluginContext\n} from \"../../types/context\";\nimport {\n UNSAFE_ContextInternal,\n UNSAFE_EnvironmentContext\n} from \"../../types/internal\";\nimport { Plugin } from \"../../types/plugin\";\nimport {\n EnvironmentResolvedConfig,\n ResolvedConfig\n} from \"../../types/resolved\";\nimport { loadWorkspaceConfig } from \"../config-file\";\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 context.powerlinesPath = await resolvePackage(\"powerlines\");\n if (!context.powerlinesPath) {\n throw new Error(\"Could not resolve `powerlines` package location.\");\n }\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(\"engine\");\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.log(\n LogLevelLabel.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.log(\n LogLevelLabel.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 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\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 { Context } from \"../../types/context\";\n\nexport interface FileHeaderOptions {\n directive?: string | null;\n prettierIgnore?: boolean;\n}\n\nexport function getBaseFileHeader(context: Context): string {\n return `\n// Generated with ${titleCase(context.config.framework)}\n// Note: Do not edit this file manually - it will be overwritten automatically\n`;\n}\n\nexport function getFileHeader(\n context: Context,\n options: FileHeaderOptions = {}\n): string {\n const { directive = null, prettierIgnore = false } = options;\n\n return `/* eslint-disable */\n// biome-ignore lint: disable\n${prettierIgnore ? `// prettier-ignore` : \"\"}${directive ? `\\n\\n${directive}\\n` : \"\\n\"}\n${getBaseFileHeader(context)}\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 { transformAsync } from \"@babel/core\";\nimport { formatLogMessage } from \"@storm-software/config-tools/logger/console\";\nimport { LogLevelLabel } from \"@storm-software/config-tools/types\";\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 { 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 { MaybePromise } from \"@stryke/types/base\";\nimport chalk from \"chalk\";\nimport Handlebars from \"handlebars\";\nimport { moduleResolverBabelPlugin } from \"./internal/babel/module-resolver-plugin\";\nimport { emitTypes, formatTypes } from \"./internal/helpers/generate-types\";\nimport { callHook, CallHookOptions } from \"./internal/helpers/hooks\";\nimport { installDependencies } from \"./internal/helpers/install-dependencies\";\nimport {\n getTsconfigDtsPath,\n initializeTsconfig,\n resolveTsconfig\n} from \"./internal/helpers/resolve-tsconfig\";\nimport { PowerlinesAPIContext } from \"./lib/contexts/api-context\";\nimport {\n getParsedTypeScriptConfig,\n isIncludeMatchFound\n} from \"./lib/typescript/tsconfig\";\nimport { getFileHeader } from \"./lib/utilities/file-header\";\nimport { writeMetaFile } from \"./lib/utilities/meta\";\nimport {\n checkDedupe,\n isPlugin,\n isPluginConfig,\n isPluginConfigObject,\n isPluginConfigTuple\n} from \"./plugin-utils/helpers\";\nimport { API } from \"./types/api\";\nimport type {\n BuildInlineConfig,\n CleanInlineConfig,\n DeployInlineConfig,\n DocsInlineConfig,\n InitialUserConfig,\n LintInlineConfig,\n NewInlineConfig,\n PluginConfig,\n PluginConfigObject,\n PluginConfigTuple,\n PluginFactory,\n PrepareInlineConfig\n} from \"./types/config\";\nimport type {\n APIContext,\n EnvironmentContext,\n PluginContext\n} from \"./types/context\";\nimport { HookKeys, InferHookParameters } from \"./types/hooks\";\nimport { UNSAFE_APIContext } from \"./types/internal\";\nimport type { Plugin, TypesResult } from \"./types/plugin\";\nimport { EnvironmentResolvedConfig, ResolvedConfig } from \"./types/resolved\";\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 = { api };\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.log(\n LogLevelLabel.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 });\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.log(\n LogLevelLabel.TRACE,\n \" 🏗️ Preparing the Powerlines project\"\n );\n\n this.context.log(\n LogLevelLabel.TRACE,\n \" ⚙️ Aggregating configuration options for the Powerlines project\"\n );\n\n await this.context.withInlineConfig(inlineConfig);\n await this.#executeEnvironments(async context => {\n context.log(\n LogLevelLabel.TRACE,\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 context.log(\n LogLevelLabel.DEBUG,\n `The configuration provided ${\n toArray(context.config.entry).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.input.file || entry.file}${\n entry.output ? ` -> ${entry.output}` : \"\"\n }`\n )\n .join(\" \\n\")}`\n : \"\"\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.log(\n LogLevelLabel.TRACE,\n `Powerlines configuration has been resolved: \\n\\n${formatLogMessage(\n context.config\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 if (context.config.output.dts !== false) {\n context.log(\n LogLevelLabel.TRACE,\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 context.log(\n LogLevelLabel.TRACE,\n \"Transforming built-ins runtime modules files.\"\n );\n\n const builtinFilePaths = await Promise.all(\n (await context.getBuiltins()).map(async file => {\n const result = await transformAsync(file.code.toString(), {\n highlightCode: true,\n code: true,\n ast: false,\n cloneInputAst: false,\n comments: true,\n sourceType: \"module\",\n configFile: false,\n babelrc: false,\n envName: context.config.mode,\n caller: {\n name: \"powerlines\"\n },\n ...context.config.transform.babel,\n filename: file.path,\n plugins: [\n [\"@babel/plugin-syntax-typescript\"],\n [moduleResolverBabelPlugin(context)]\n ]\n });\n if (!result?.code) {\n throw new Error(\n `Powerlines - Generate Types failed to compile ${file.id}`\n );\n }\n\n context.log(\n LogLevelLabel.TRACE,\n `Writing transformed built-in runtime file ${file.id}.`\n );\n\n await context.emitBuiltin(result.code, file.id, file.path);\n return file.path;\n })\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 const files = builtinFilePaths.reduce<string[]>(\n (ret, fileName) => {\n const formatted = replacePath(\n fileName,\n context.workspaceConfig.workspaceRoot\n );\n if (!ret.includes(formatted)) {\n ret.push(formatted);\n }\n\n return ret;\n },\n [] // [joinPaths(typescriptPath, \"lib\", \"lib.esnext.full.d.ts\")]\n );\n\n context.log(\n LogLevelLabel.TRACE,\n \"Parsing TypeScript configuration for the Powerlines project.\"\n );\n\n let generatedTypes = await emitTypes(context, files);\n\n context.log(\n LogLevelLabel.TRACE,\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 generatedTypes\n );\n if (result) {\n if (isSetObject(result)) {\n generatedTypes = 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 generatedTypes = 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 generatedTypes\n );\n if (result) {\n if (isSetObject(result)) {\n generatedTypes = 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 generatedTypes = 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 generatedTypes\n );\n if (result) {\n if (isSetObject(result)) {\n generatedTypes = 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 generatedTypes = result;\n }\n }\n\n if (generatedTypes?.trim() || directives.length > 0) {\n await context.fs.write(\n context.dtsPath,\n `${\n directives\n ? `${directives.map(directive => `/// <reference types=\"${directive}\" />`).join(\"\\n\")}\n\n`\n : \"\"\n }${getFileHeader(context, { directive: null, prettierIgnore: false })}\n\n${formatTypes(generatedTypes)}\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.projectRoot,\n context.config.tsconfig\n );\n if (!context.tsconfig) {\n throw new Error(\"Failed to parse the TypeScript configuration file.\");\n }\n\n await this.callHook(\"prepare\", {\n environment: context,\n order: \"post\"\n });\n\n await writeMetaFile(context);\n context.persistedMeta = context.meta;\n });\n\n this.context.log(\n LogLevelLabel.INFO,\n \"Powerlines API has been prepared successfully\"\n );\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.log(\n LogLevelLabel.INFO,\n \"🆕 Creating a new Powerlines project\"\n );\n\n await this.prepare(inlineConfig);\n await this.#executeEnvironments(async context => {\n context.log(\n LogLevelLabel.TRACE,\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.log(LogLevelLabel.TRACE, `Adding template file: ${file}`);\n\n const template = Handlebars.compile(file);\n await context.fs.write(\n joinPaths(context.config.projectRoot, 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.log(\n LogLevelLabel.TRACE,\n `Adding application template file: ${file}`\n );\n\n const template = Handlebars.compile(file);\n await context.fs.write(\n joinPaths(context.config.projectRoot, 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.log(\n LogLevelLabel.TRACE,\n `Adding library template file: ${file}`\n );\n\n const template = Handlebars.compile(file);\n await context.fs.write(\n joinPaths(context.config.projectRoot, 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.log(LogLevelLabel.TRACE, \"Powerlines - New command completed\");\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.log(\n LogLevelLabel.INFO,\n \"🧹 Cleaning the previous Powerlines artifacts\"\n );\n\n await this.prepare(inlineConfig);\n await this.#executeEnvironments(async context => {\n this.context.log(\n LogLevelLabel.TRACE,\n \"Cleaning the project's dist and artifacts directories.\"\n );\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.output.artifactsPath\n )\n );\n\n await this.callHook(\"clean\", {\n environment: context,\n sequential: false\n });\n });\n\n this.context.log(\n LogLevelLabel.TRACE,\n \"Powerlines - Clean command completed\"\n );\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.log(LogLevelLabel.INFO, \"📋 Linting the Powerlines project\");\n\n await this.prepare(inlineConfig);\n await this.#executeEnvironments(async context => {\n if (context.config.lint !== false) {\n await this.callHook(\"lint\", {\n environment: context,\n sequential: false\n });\n }\n });\n\n this.context.log(LogLevelLabel.TRACE, \"Powerlines linting completed\");\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.log(LogLevelLabel.INFO, \"📦 Building the Powerlines project\");\n\n // const checksum = await this.context.generateChecksum();\n // if (checksum !== this.context.persistedMeta?.checksum) {\n // this.context.log(\n // LogLevelLabel.INFO,\n // \"The Powerlines 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 await this.prepare(inlineConfig);\n await this.#executeEnvironments(async context => {\n await this.callHook(\"build\", {\n environment: context,\n order: \"pre\"\n });\n await this.callHook(\"build\", {\n environment: context,\n order: \"normal\"\n });\n\n if (\n context.config.output.buildPath !== context.config.output.outputPath\n ) {\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 (sourcePath !== destinationPath) {\n context.log(\n LogLevelLabel.INFO,\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.log(\n LogLevelLabel.DEBUG,\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(\n asset.output,\n context.workspaceConfig.workspaceRoot\n ),\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 this.context.log(LogLevelLabel.TRACE, \"Powerlines build completed\");\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.log(\n LogLevelLabel.INFO,\n \"📓 Generating documentation for the Powerlines project\"\n );\n\n await this.prepare(inlineConfig);\n await this.#executeEnvironments(async context => {\n context.log(\n LogLevelLabel.TRACE,\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.log(\n LogLevelLabel.TRACE,\n \"Powerlines documentation generation completed\"\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.log(LogLevelLabel.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.log(LogLevelLabel.TRACE, \"Powerlines deploy completed\");\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.log(\n LogLevelLabel.TRACE,\n \"Powerlines finalize execution started\"\n );\n\n await this.#executeEnvironments(async context => {\n await this.callHook(\"finalize\", { environment: context });\n await context.fs.dispose();\n });\n\n this.context.log(\n LogLevelLabel.TRACE,\n \"Powerlines finalize execution completed\"\n );\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 HookKeys<PluginContext<TResolvedConfig>>>(\n hook: TKey,\n options: CallHookOptions & {\n environment?: string | EnvironmentContext<TResolvedConfig>;\n },\n ...args: InferHookParameters<PluginContext<TResolvedConfig>, TKey>\n ) {\n return callHook<TResolvedConfig, EnvironmentContext<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 /**\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.log(\n LogLevelLabel.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.log(\n LogLevelLabel.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 plugin = await this.#initPlugin(config);\n if (!plugin) {\n return;\n }\n\n if (plugin.dependsOn) {\n for (const required of plugin.dependsOn) {\n await this.#addPlugin(required);\n }\n }\n\n this.context.log(\n LogLevelLabel.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 * 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);\n }\n\n if (!isPluginConfig(awaited)) {\n throw new Error(\n `Invalid plugin specified in the configuration - ${JSON.stringify(awaited)}. Please ensure the value is a plugin name, an object with the \\`plugin\\` and \\`props\\` properties, or an instance of \\`Plugin\\`.`\n );\n }\n\n let plugin!: Plugin<PluginContext<TResolvedConfig>>;\n if (isPlugin<TResolvedConfig>(awaited)) {\n plugin = awaited;\n } else if (isFunction(awaited)) {\n plugin = await Promise.resolve(awaited());\n } else if (isSetString(awaited)) {\n const resolved = await this.#resolvePlugin(awaited);\n if (isFunction(resolved)) {\n plugin = await Promise.resolve(resolved());\n } else {\n plugin = resolved;\n }\n } else if (isPluginConfigTuple(awaited) || isPluginConfigObject(awaited)) {\n let pluginConfig!:\n | string\n | PluginFactory<PluginContext<TResolvedConfig>>\n | Plugin<PluginContext<TResolvedConfig>>;\n let pluginOptions: any;\n\n if (isPluginConfigTuple(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 plugin = await Promise.resolve(\n pluginOptions ? resolved(pluginOptions) : resolved()\n );\n } else {\n plugin = resolved;\n }\n } else if (isFunction(pluginConfig)) {\n plugin = await Promise.resolve(pluginConfig(pluginOptions));\n } else if (isPlugin(pluginConfig)) {\n plugin = pluginConfig;\n }\n }\n\n if (!plugin) {\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 (!isPlugin(plugin)) {\n throw new Error(\n `The plugin option ${JSON.stringify(plugin)} does not export a valid module. This configuration must point to a valid Powerlines plugin module.`\n );\n }\n\n if (checkDedupe<TResolvedConfig>(plugin, this.context.plugins)) {\n this.context.log(\n LogLevelLabel.TRACE,\n `Duplicate ${chalk.bold.cyanBright(\n plugin.name\n )} plugin dependency detected - Skipping initialization.`\n );\n\n return null;\n }\n\n this.context.log(\n LogLevelLabel.TRACE,\n `Initializing the ${chalk.bold.cyanBright(plugin.name)} plugin...`\n );\n\n return plugin;\n }\n\n async #resolvePlugin<TOptions>(\n pluginPath: string\n ): Promise<\n | Plugin<PluginContext<TResolvedConfig>>\n | ((\n options?: TOptions\n ) => MaybePromise<Plugin<PluginContext<TResolvedConfig>>>)\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.projectRoot\n ]\n });\n if (!isInstalled && this.context.config.skipInstalls !== true) {\n this.#context.log(\n LogLevelLabel.WARN,\n `The plugin package \"${pluginPath}\" is not installed. It will be installed automatically.`\n );\n\n const result = await install(pluginPath, {\n cwd: this.context.config.projectRoot\n });\n if (isNumber(result.exitCode) && result.exitCode > 0) {\n this.#context.log(LogLevelLabel.ERROR, result.stderr);\n throw new Error(\n `An error occurred while installing the build plugin package \"${pluginPath}\" `\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","/* -------------------------------------------------------------------\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 { readFileIfExistingSync } from \"@stryke/fs/read-file\";\nimport { isSetObject } from \"@stryke/type-checks/is-set-object\";\nimport { isString } from \"@stryke/type-checks/is-string\";\nimport MagicString from \"magic-string\";\nimport { TransformResult } from \"unplugin\";\nimport { SourceFile } from \"../../types/context\";\n\n/**\n * Get the string from the source.\n *\n * @param code - The source string or magic string.\n * @returns The source string.\n */\nexport function getString(\n code: string | MagicString | TransformResult\n): string {\n if (!code) {\n return \"\";\n }\n\n if (isString(code)) {\n return code;\n }\n\n if (isSetObject(code) && \"code\" in code) {\n return code.code;\n }\n\n return code.toString();\n}\n\n/**\n * Get the magic string.\n *\n * @param code - The source string or magic string.\n * @returns The magic string.\n */\nexport function getMagicString(code: string | MagicString): MagicString {\n if (isString(code)) {\n return new MagicString(code);\n }\n\n return code;\n}\n\n/**\n * Get the source file.\n *\n * @param code - The source code.\n * @param id - The name of the file.\n * @returns The source file.\n */\nexport function getSourceFile(\n code: string | MagicString,\n id: string\n): SourceFile {\n const content = code ?? readFileIfExistingSync(id);\n\n return {\n id,\n code: getMagicString(content),\n env: []\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 { defu } from \"defu\";\nimport { UnpluginBuildContext, UnpluginContext } from \"unplugin\";\nimport { PluginContext } from \"../../types/context\";\n\n/**\n * Merges a base plugin context with an unplugin context, combining their properties.\n *\n * @param context - The base plugin context to merge into.\n * @param unplugin - The unplugin context to merge from.\n * @returns The merged context.\n */\nexport function combineContexts<TContext extends PluginContext = PluginContext>(\n context: TContext,\n unplugin: UnpluginBuildContext & UnpluginContext\n) {\n return defu(context, unplugin);\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 { findFileName } from \"@stryke/path/file-path-fns\";\nimport { replaceExtension } from \"@stryke/path/replace\";\nimport { isString } from \"@stryke/type-checks/is-string\";\nimport type {\n ExternalIdResult,\n TransformResult,\n UnpluginBuildContext,\n UnpluginContext\n} from \"unplugin\";\nimport { setParseImpl } from \"unplugin\";\nimport { UnpluginBuildVariant } from \"../../types/build\";\nimport { PluginContext } from \"../../types/context\";\nimport { UNSAFE_PluginContext } from \"../../types/internal\";\nimport { PowerlinesUnpluginFactory } from \"../../types/unplugin\";\nimport { extendLog } from \"../logger\";\nimport { getString } from \"../utilities/source-file\";\nimport { combineContexts } from \"./helpers\";\n\n/**\n * Creates a Powerlines unplugin instance.\n *\n * @param context - The plugin context.\n * @returns The unplugin instance.\n */\nexport function createUnplugin<TContext extends PluginContext = PluginContext>(\n context: TContext\n): PowerlinesUnpluginFactory<UnpluginBuildVariant> {\n const ctx = context as unknown as UNSAFE_PluginContext;\n setParseImpl(ctx.parse);\n\n return () => {\n const log = extendLog(ctx.log, \"unplugin\");\n log(LogLevelLabel.DEBUG, \"Initializing Unplugin\");\n\n try {\n async function buildStart(this: UnpluginBuildContext) {\n log(LogLevelLabel.DEBUG, \"Powerlines build plugin starting...\");\n\n await ctx.$$internal.callHook(\"buildStart\", {\n sequential: true\n });\n }\n\n async function resolveId(\n this: UnpluginBuildContext & UnpluginContext,\n id: string,\n importer?: string,\n opts: {\n isEntry: boolean;\n } = { isEntry: false }\n ): Promise<string | ExternalIdResult | null | undefined> {\n const resolved = await (async () => {\n let result = await ctx.$$internal.callHook(\n \"resolveId\",\n {\n sequential: true,\n result: \"first\",\n order: \"pre\"\n },\n id,\n importer,\n opts\n );\n if (result) {\n return result;\n }\n\n result = await ctx.$$internal.callHook(\n \"resolveId\",\n {\n sequential: true,\n result: \"first\",\n order: \"normal\"\n },\n id,\n importer,\n opts\n );\n if (result) {\n return result;\n }\n\n result = await ctx.resolve(id, importer, opts);\n if (result) {\n return result;\n }\n\n return ctx.$$internal.callHook(\n \"resolveId\",\n {\n sequential: true,\n result: \"first\",\n order: \"post\"\n },\n id,\n importer,\n opts\n );\n })();\n if (\n resolved &&\n opts.isEntry &&\n ctx.config.build.polyfill &&\n ctx.config.build.polyfill.length > 0\n ) {\n const entry = ctx.entry.find(\n entry =>\n entry.file === (isString(resolved) ? resolved : resolved.id)\n );\n if (entry) {\n entry.file = `${replaceExtension(isString(resolved) ? resolved : resolved.id)}-polyfill.ts`;\n entry.output ||= entry.output?.replace(\n findFileName(entry.output, { withExtension: true }),\n entry.file\n );\n\n await ctx.emitEntry(\n `\n${ctx.config.build.polyfill.map(p => `import \"${p}\";`).join(\"\\n\")}\n\nexport * from \"${isString(resolved) ? resolved : resolved.id}\";\n`,\n entry.file\n );\n\n return entry.file;\n }\n }\n\n return resolved;\n }\n\n async function load(\n this: UnpluginBuildContext & UnpluginContext,\n id: string\n ): Promise<TransformResult | null | undefined> {\n let result = await ctx.$$internal.callHook(\n \"load\",\n {\n sequential: true,\n result: \"first\",\n order: \"pre\"\n },\n id\n );\n if (result) {\n return result;\n }\n\n result = await ctx.$$internal.callHook(\n \"load\",\n {\n sequential: true,\n result: \"first\",\n order: \"normal\"\n },\n id\n );\n if (result) {\n return result;\n }\n\n result = await ctx.load(id);\n if (result) {\n return result;\n }\n\n return ctx.$$internal.callHook(\n \"load\",\n {\n sequential: true,\n result: \"first\",\n order: \"post\"\n },\n id\n );\n }\n\n async function transform(\n this: UnpluginBuildContext & UnpluginContext,\n code: string,\n id: string\n ): Promise<TransformResult | null | undefined> {\n let transformed: TransformResult | string = code;\n\n for (const handler of ctx.$$internal.environment.selectHooks(\n \"transform\"\n )) {\n const result: TransformResult | string | undefined =\n await handler.handle.apply(combineContexts(ctx, this), [\n getString(transformed),\n id\n ]);\n if (result) {\n transformed = result;\n }\n }\n\n return transformed;\n }\n\n async function buildEnd(this: UnpluginBuildContext): Promise<void> {\n log(LogLevelLabel.DEBUG, \"Powerlines build plugin finishing...\");\n\n return ctx.$$internal.callHook(\"buildEnd\", {\n sequential: true\n });\n }\n\n async function writeBundle(): Promise<void> {\n log(LogLevelLabel.DEBUG, \"Finalizing Powerlines project output...\");\n\n return ctx.$$internal.callHook(\"writeBundle\", {\n sequential: true\n });\n }\n\n return {\n name: \"powerlines\",\n api: ctx.$$internal.api,\n resolveId: {\n filter: {\n id: {\n include: [/.*/]\n }\n },\n handler: resolveId\n },\n load: {\n filter: {\n id: {\n include: [/.*/]\n }\n },\n handler: load\n },\n transform,\n buildStart,\n buildEnd,\n writeBundle,\n vite: {\n sharedDuringBuild: true\n }\n };\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 { createUnplugin } from \"powerlines/lib/unplugin\";\nimport { createEsbuildPlugin } from \"unplugin\";\nimport { RollupPluginContext } from \"../types/plugin\";\n\nexport function createRollupPlugin(context: RollupPluginContext) {\n return createEsbuildPlugin(createUnplugin(context))({});\n}\n"],"mappings":"4+IGyFqB,GAAe,EAAQ,EAAc,IACpD,EAAS,EAAI,GAAK,EAAI,EAAS,EAAM,EACvC,EAAI,GAAO,GAAG,EAAI,IAAQ,GAAG,IAAI,GAAS,KAAK,MAAM,CAE9C,IAGF,GACP,CQ3EF,MAAa,EAAqB,CAChC,MACA,QACA,UACA,OACA,OACA,QACA,OACA,SACA,WACD,CCaD,SAAgB,EAEd,EAAiE,CACjE,OACE,EAAY,EAAM,EAClB,SAAU,GACV,EAAY,EAAM,KAAK,GACtB,EACE,EAAiD,mBACnD,EACE,uBAAwB,GACvB,EAAW,EAAM,mBAAmB,IACvC,EAAa,EAAiD,OAAO,EACnE,WAAY,GAAS,EAAW,EAAM,OAAO,IAC/C,EAAa,EAAiD,UAAU,EACtE,cAAe,GACd,MAAM,QAAQ,EAAM,UAAU,EAC9B,EAAM,UAAU,MAAM,EAAe,GACzC,EAAmB,MACjB,GACE,EACG,EAAiD,GACnD,EACA,KAAW,IACT,EAAY,EAA8B,GAAS,EACjD,EAAa,EAA8B,GAAS,EACnD,YAAc,EAA8B,IAC5C,EAAY,EAA8B,GAAS,QAAQ,EACpE,CAUL,SAAgB,EACd,EAC6B,CAC7B,OACE,EAAY,EAAM,EAClB,WAAY,KACT,EAAY,EAAM,OAAO,EAAI,EAAW,EAAM,OAAO,GACtD,YAAa,GACb,EAAY,EAAM,QAAQ,EAC1B,EAAS,EAAM,OAAO,EAU5B,SAAgB,EACd,EAC4B,CAC5B,OACE,MAAM,QAAQ,EAAM,GACnB,EAAM,SAAW,GAAK,EAAM,SAAW,MACrC,EAAY,EAAM,GAAG,EAAI,EAAW,EAAM,GAAG,GAC9C,EAAM,OAAS,GACf,EAAY,EAAM,GAAG,EACrB,EAAS,EAAM,GAAG,EAUxB,SAAgB,EAAe,EAAuC,CACpE,OACE,EAAY,EAAM,EAClB,EAAW,EAAM,EACjB,EAAS,EAAM,EACf,EAAqB,EAAM,EAC3B,EAAoB,EAAM,CGzH9B,IAAa,EAAb,cAA+C,EAAE,MAAO,CACtD,OAAgC,OAAS,CACvC,YAAa,eACb,GAAI,mBACJ,KAAM,IAAI,EAAE,WAAW,EAAG,EAAE,CAC7B,CACD,IAAI,KAAc,CAChB,OAAO,EAAE,MAAM,QAAQ,EAAG,KAAK,CAEjC,IAAI,IAAI,EAAe,CACrB,EAAE,MAAM,QAAQ,EAAG,EAAO,KAAK,CAEjC,IAAI,OAAgB,CAClB,OAAO,EAAE,MAAM,QAAQ,EAAG,KAAK,CAEjC,IAAI,MAAM,EAAe,CACvB,EAAE,MAAM,QAAQ,EAAG,EAAO,KAAK,CAEjC,UAAmC,CAAE,MAAO,6BAA+B,MAAM,UAAU,GAMhF,EAAb,MAAa,UAAqB,EAAE,MAAO,CACzC,OAAgB,aAAe,EAC/B,OAAgC,OAAS,CACvC,YAAa,eACb,GAAI,mBACJ,KAAM,IAAI,EAAE,WAAW,EAAG,EAAE,CAC5B,YAAa,SACd,CACD,OAAO,YAKP,IAAI,IAAa,CACf,OAAO,EAAE,MAAM,QAAQ,EAAG,KAAK,CAEjC,IAAI,GAAG,EAAe,CACpB,EAAE,MAAM,QAAQ,EAAG,EAAO,KAAK,CAMjC,IAAI,MAAe,CACjB,OAAO,EAAE,MAAM,QAAQ,EAAG,KAAM,EAAa,OAAO,YAAY,CAElE,IAAI,KAAK,EAAe,CACtB,EAAE,MAAM,QAAQ,EAAG,EAAO,KAAK,CAMjC,IAAI,WAAoB,CACtB,OAAO,EAAE,MAAM,UAAU,EAAG,KAAK,CAEnC,IAAI,UAAU,EAAe,CAC3B,EAAE,MAAM,UAAU,EAAG,EAAO,KAAK,CAEnC,iBAAiB,EAA0D,CACzE,EAAE,MAAM,MAAM,EAAO,EAAE,MAAM,WAAW,EAAG,KAAK,CAAC,CAEnD,mBAAiE,CAC/D,OAAO,EAAE,MAAM,OAAO,KAAK,WAAW,CAExC,IAAI,YAAgD,CAClD,OAAO,EAAE,MAAM,QAAQ,EAAG,EAAa,YAAa,KAAK,CAE3D,gBAA0B,CACxB,MAAO,CAAC,EAAE,MAAM,OAAO,EAAE,MAAM,WAAW,EAAG,KAAK,CAAC,CAErD,gBAAgB,EAAmD,CACjE,OAAO,EAAE,MAAM,SAAS,EAAG,EAAa,YAAa,EAAQ,KAAK,CAEpE,IAAI,WAAW,EAA0C,CACvD,EAAE,MAAM,SAAS,EAAO,EAAE,MAAM,WAAW,EAAG,KAAK,CAAC,CAEtD,UAAmC,CAAE,MAAO,gBAAkB,MAAM,UAAU,GAMnE,EAAb,cAA4B,EAAE,MAAO,CACnC,OAAgC,OAAS,CACvC,YAAa,SACb,GAAI,mBACJ,KAAM,IAAI,EAAE,WAAW,EAAG,EAAE,CAC7B,CAKD,IAAI,IAAa,CACf,OAAO,EAAE,MAAM,QAAQ,EAAG,KAAK,CAEjC,IAAI,GAAG,EAAe,CACpB,EAAE,MAAM,QAAQ,EAAG,EAAO,KAAK,CAEjC,IAAI,MAAe,CACjB,OAAO,EAAE,MAAM,QAAQ,EAAG,KAAK,CAEjC,IAAI,KAAK,EAAe,CACtB,EAAE,MAAM,QAAQ,EAAG,EAAO,KAAK,CAEjC,UAAmC,CAAE,MAAO,UAAY,MAAM,UAAU,GAM7D,EAAb,cAAiC,EAAE,MAAO,CACxC,OAAgC,OAAS,CACvC,YAAa,cACb,GAAI,mBACJ,KAAM,IAAI,EAAE,WAAW,EAAG,EAAE,CAC7B,CAKD,IAAI,MAAe,CACjB,OAAO,EAAE,MAAM,QAAQ,EAAG,KAAK,CAEjC,IAAI,KAAK,EAAe,CACtB,EAAE,MAAM,QAAQ,EAAG,EAAO,KAAK,CAEjC,IAAI,MAAe,CACjB,OAAO,EAAE,MAAM,QAAQ,EAAG,KAAK,CAEjC,IAAI,KAAK,EAAe,CACtB,EAAE,MAAM,QAAQ,EAAG,EAAO,KAAK,CAEjC,UAAmC,CAAE,MAAO,eAAiB,MAAM,UAAU,GAElE,EAAb,MAAa,UAAmB,EAAE,MAAO,CACvC,OAAgC,OAAS,CACvC,YAAa,aACb,GAAI,mBACJ,KAAM,IAAI,EAAE,WAAW,EAAG,EAAE,CAC7B,CACD,OAAO,KACP,OAAO,SACP,OAAO,UACP,UAAU,EAAuC,CAC/C,EAAE,MAAM,MAAM,EAAO,EAAE,MAAM,WAAW,EAAG,KAAK,CAAC,CAEnD,YAAuC,CACrC,OAAO,EAAE,MAAM,OAAO,KAAK,IAAI,CAEjC,IAAI,KAAsB,CACxB,OAAO,EAAE,MAAM,QAAQ,EAAG,EAAW,KAAM,KAAK,CAElD,SAAmB,CACjB,MAAO,CAAC,EAAE,MAAM,OAAO,EAAE,MAAM,WAAW,EAAG,KAAK,CAAC,CAErD,SAAS,EAAgC,CACvC,OAAO,EAAE,MAAM,SAAS,EAAG,EAAW,KAAM,EAAQ,KAAK,CAE3D,IAAI,IAAI,EAAuB,CAC7B,EAAE,MAAM,SAAS,EAAO,EAAE,MAAM,WAAW,EAAG,KAAK,CAAC,CAEtD,cAAc,EAA4C,CACxD,EAAE,MAAM,MAAM,EAAO,EAAE,MAAM,WAAW,EAAG,KAAK,CAAC,CAEnD,gBAAgD,CAC9C,OAAO,EAAE,MAAM,OAAO,KAAK,QAAQ,CAErC,IAAI,SAA+B,CACjC,OAAO,EAAE,MAAM,QAAQ,EAAG,EAAW,SAAU,KAAK,CAEtD,aAAuB,CACrB,MAAO,CAAC,EAAE,MAAM,OAAO,EAAE,MAAM,WAAW,EAAG,KAAK,CAAC,CAErD,aAAa,EAAqC,CAChD,OAAO,EAAE,MAAM,SAAS,EAAG,EAAW,SAAU,EAAQ,KAAK,CAE/D,IAAI,QAAQ,EAA4B,CACtC,EAAE,MAAM,SAAS,EAAO,EAAE,MAAM,WAAW,EAAG,KAAK,CAAC,CAEtD,eAAe,EAA6C,CAC1D,EAAE,MAAM,MAAM,EAAO,EAAE,MAAM,WAAW,EAAG,KAAK,CAAC,CAEnD,iBAAkD,CAChD,OAAO,EAAE,MAAM,OAAO,KAAK,SAAS,CAEtC,IAAI,UAAiC,CACnC,OAAO,EAAE,MAAM,QAAQ,EAAG,EAAW,UAAW,KAAK,CAEvD,cAAwB,CACtB,MAAO,CAAC,EAAE,MAAM,OAAO,EAAE,MAAM,WAAW,EAAG,KAAK,CAAC,CAErD,cAAc,EAAsC,CAClD,OAAO,EAAE,MAAM,SAAS,EAAG,EAAW,UAAW,EAAQ,KAAK,CAEhE,IAAI,SAAS,EAA6B,CACxC,EAAE,MAAM,SAAS,EAAO,EAAE,MAAM,WAAW,EAAG,KAAK,CAAC,CAEtD,UAAmC,CAAE,MAAO,cAAgB,MAAM,UAAU,GAE9E,EAAa,YAAc,EAAE,cAAc,EAA0B,CACrE,EAAW,KAAO,EAAE,cAAc,EAAO,CACzC,EAAW,SAAW,EAAE,cAAc,EAAY,CAClD,EAAW,UAAY,EAAE,cAAc,EAAa,CE7KpD,MA+BM,EAAe,CACnB,UACA,UACA,UACA,UACA,UACA,UACA,UACA,UACA,UACA,UACA,UACA,UACA,UACA,UACA,UACA,UACA,UACA,UACA,UACA,UACD,CAEY,GAAa,EAAc,KAC9B,EAAqB,GAAG,IAC9B,EACE,EACA,IAAI,EAAM,QAAQ,IAChB,EACE,EACG,MAAM,GAAG,CACT,IAAI,GAAQ,EAAK,WAAW,EAAE,CAAC,CAC/B,QAAQ,EAAK,IAAa,EAAM,EAAU,EAAE,CAAG,EAAa,SAC5D,EAAa,GACnB,CAAC,IAAI,EAAU,EAAK,CAAC,GAAG,CAAC,IAAI,EAAK,KAAK,IAAI,CAAC,GAC9C,CEkKW,OAAO,aGmlCd,OAAO,aEnuChB,EADc,IAAI,EAAM,CAAE,iBAAkB,IAAO,CAAC,CAE5C,QACJ,EAAa,MAAM,CACjB,WAAY,EACZ,WAAY,IACZ,WAAY,IACZ,cAAe,EACf,WAAY,GACb,CAAC,CACH,CACF,CMsuBe,OAAO,aC70BvB,SAAgB,EACd,EACQ,CAaR,OAZK,EAID,EAAS,EAAK,CACT,EAGL,EAAY,EAAK,EAAI,SAAU,EAC1B,EAAK,KAGP,EAAK,UAAU,CAXb,GCNX,SAAgB,EACd,EACA,EACA,CACA,OAAO,EAAK,EAAS,EAAS,CCUhC,SAAgB,EACd,EACiD,CACjD,IAAM,EAAM,EAGZ,OAFA,EAAa,EAAI,MAAM,KAEV,CACX,IAAM,EAAM,EAAU,EAAI,IAAK,WAAW,CAC1C,EAAI,EAAc,MAAO,wBAAwB,CAEjD,GAAI,CACF,eAAe,GAAuC,CACpD,EAAI,EAAc,MAAO,sCAAsC,CAE/D,MAAM,EAAI,WAAW,SAAS,aAAc,CAC1C,WAAY,GACb,CAAC,CAGJ,eAAe,EAEb,EACA,EACA,EAEI,CAAE,QAAS,GAAO,CACiC,CACvD,IAAM,EAAW,MAAO,SAAY,CAClC,IAAI,EAAS,MAAM,EAAI,WAAW,SAChC,YACA,CACE,WAAY,GACZ,OAAQ,QACR,MAAO,MACR,CACD,EACA,EACA,EACD,CAyBD,OAxBI,IAIJ,EAAS,MAAM,EAAI,WAAW,SAC5B,YACA,CACE,WAAY,GACZ,OAAQ,QACR,MAAO,SACR,CACD,EACA,EACA,EACD,CACG,KAIJ,EAAS,MAAM,EAAI,QAAQ,EAAI,EAAU,EAAK,CAC1C,GACK,EAGF,EAAI,WAAW,SACpB,YACA,CACE,WAAY,GACZ,OAAQ,QACR,MAAO,OACR,CACD,EACA,EACA,EACD,IACC,CACJ,GACE,GACA,EAAK,SACL,EAAI,OAAO,MAAM,UACjB,EAAI,OAAO,MAAM,SAAS,OAAS,EACnC,CACA,IAAM,EAAQ,EAAI,MAAM,KACtB,GACEsE,EAAM,QAAU,EAAS,EAAS,CAAG,EAAW,EAAS,IAC5D,CACD,GAAI,EAgBF,MAfA,GAAM,KAAO,GAAG,EAAiB,EAAS,EAAS,CAAG,EAAW,EAAS,GAAG,CAAC,cAC9E,EAAM,SAAW,EAAM,QAAQ,QAC7B,EAAa,EAAM,OAAQ,CAAE,cAAe,GAAM,CAAC,CACnD,EAAM,KACP,CAED,MAAM,EAAI,UACR;EACZ,EAAI,OAAO,MAAM,SAAS,IAAI,GAAK,WAAW,EAAE,IAAI,CAAC,KAAK;EAAK,CAAC;;iBAEjD,EAAS,EAAS,CAAG,EAAW,EAAS,GAAG;EAE/C,EAAM,KACP,CAEM,EAAM,KAIjB,OAAO,EAGT,eAAe,EAEb,EAC6C,CAC7C,IAAI,EAAS,MAAM,EAAI,WAAW,SAChC,OACA,CACE,WAAY,GACZ,OAAQ,QACR,MAAO,MACR,CACD,EACD,CAuBD,OAtBI,IAIJ,EAAS,MAAM,EAAI,WAAW,SAC5B,OACA,CACE,WAAY,GACZ,OAAQ,QACR,MAAO,SACR,CACD,EACD,CACG,KAIJ,EAAS,MAAM,EAAI,KAAK,EAAG,CACvB,GACK,EAGF,EAAI,WAAW,SACpB,OACA,CACE,WAAY,GACZ,OAAQ,QACR,MAAO,OACR,CACD,EACD,CAGH,eAAe,EAEb,EACA,EAC6C,CAC7C,IAAIC,EAAwC,EAE5C,IAAK,IAAM,KAAW,EAAI,WAAW,YAAY,YAC/C,YACD,CAAE,CACD,IAAMC,EACJ,MAAM,EAAQ,OAAO,MAAM,EAAgB,EAAK,KAAK,CAAE,CACrD,EAAU,EAAY,CACtB,EACD,CAAC,CACA,IACF,EAAc,GAIlB,OAAO,EAGT,eAAe,GAAoD,CAGjE,OAFA,EAAI,EAAc,MAAO,uCAAuC,CAEzD,EAAI,WAAW,SAAS,WAAY,CACzC,WAAY,GACb,CAAC,CAGJ,eAAe,GAA6B,CAG1C,OAFA,EAAI,EAAc,MAAO,0CAA0C,CAE5D,EAAI,WAAW,SAAS,cAAe,CAC5C,WAAY,GACb,CAAC,CAGJ,MAAO,CACL,KAAM,aACN,IAAK,EAAI,WAAW,IACpB,UAAW,CACT,OAAQ,CACN,GAAI,CACF,QAAS,CAAC,KAAK,CAChB,CACF,CACD,QAAS,EACV,CACD,KAAM,CACJ,OAAQ,CACN,GAAI,CACF,QAAS,CAAC,KAAK,CAChB,CACF,CACD,QAAS,EACV,CACD,YACA,aACA,WACA,cACA,KAAM,CACJ,kBAAmB,GACpB,CACF,OACM,EAAO,CAGd,MAFA,EAAI,EAAc,MAAQ,GAAiB,QAAQ,CAE7C,ICpPZ,SAAgB,EAAmB,EAA8B,CAC/D,OAAO,EAAoB,EAAe,EAAQ,CAAC,CAAC,EAAE,CAAC"}