@powerlines/engine 0.45.0 → 0.45.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/_internal/worker.cjs +3 -1
- package/dist/_internal/worker.mjs +3 -1
- package/dist/_internal/worker.mjs.map +1 -1
- package/dist/api.cjs +1 -1
- package/dist/api.mjs +1 -1
- package/dist/context/index.cjs +1 -1
- package/dist/context/index.d.cts +1 -1
- package/dist/context/index.d.cts.map +1 -1
- package/dist/context/index.d.mts +1 -1
- package/dist/context/index.d.mts.map +1 -1
- package/dist/context/index.mjs +1 -1
- package/dist/{execution-context-Cr_VUBrP.mjs → execution-context-O6eXdsCn.mjs} +4 -2
- package/dist/execution-context-O6eXdsCn.mjs.map +1 -0
- package/dist/{execution-context-BFCOc0mH.cjs → execution-context-SXtPe9Ae.cjs} +3 -1
- package/package.json +3 -3
- package/dist/execution-context-Cr_VUBrP.mjs.map +0 -1
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@powerlines/engine",
|
|
3
|
-
"version": "0.45.
|
|
3
|
+
"version": "0.45.1",
|
|
4
4
|
"private": false,
|
|
5
5
|
"description": "An internal package containing the core engine modules for Powerlines.",
|
|
6
6
|
"homepage": "https://stormsoftware.com",
|
|
@@ -137,7 +137,7 @@
|
|
|
137
137
|
"@cacheable/memory": "^2.0.8",
|
|
138
138
|
"@donedeal0/superdiff": "^3.2.0",
|
|
139
139
|
"@jridgewell/sourcemap-codec": "^1.5.5",
|
|
140
|
-
"@powerlines/core": "^0.45.
|
|
140
|
+
"@powerlines/core": "^0.45.1",
|
|
141
141
|
"@storm-software/config": "^1.137.34",
|
|
142
142
|
"@storm-software/config-tools": "^1.190.1",
|
|
143
143
|
"@stryke/async": "^0.1.0",
|
|
@@ -180,5 +180,5 @@
|
|
|
180
180
|
"typescript": "^6.0.3",
|
|
181
181
|
"undici-types": "^7.25.0"
|
|
182
182
|
},
|
|
183
|
-
"gitHead": "
|
|
183
|
+
"gitHead": "4efe7574db32436446080cdc605fd2819e192457"
|
|
184
184
|
}
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"file":"execution-context-Cr_VUBrP.mjs","names":["joinPaths","#context","#normalizePath","#storage","#normalizeId","#getStorage","#logger","#metadata","#ids","#paths","#resolverCache","#getStorages","#innerResolve","#innerResolveSync","#isDisposed","#internal","#tsconfig","#fs","#checksum","#buildId","#releaseId","#parserCache","#requestCache","defu","#hooks","#environments","#plugins"],"sources":["../src/_internal/helpers/environment.ts","../src/_internal/helpers/context.ts","../src/_internal/helpers/meta.ts","../src/_internal/ipc/send.ts","../src/_internal/helpers/constants.ts","../src/_internal/vfs.ts","../src/context/context.ts","../src/_internal/helpers/hooks.ts","../src/context/plugin-context.ts","../src/context/environment-context.ts","../src/context/execution-context.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 type {\n Context,\n EnvironmentResolvedConfig,\n ExecutionContext\n} from \"@powerlines/core\";\nimport { DEFAULT_ENVIRONMENT } from \"@powerlines/core/constants\";\nimport { titleCase } from \"@stryke/string-format/title-case\";\nimport { uuid } from \"@stryke/unique-id/uuid\";\nimport defu from \"defu\";\n\nexport function createEnvironment<TContext extends Context = Context>(\n name: string,\n config: Partial<TContext[\"config\"]> = {}\n): EnvironmentResolvedConfig {\n return defu(config.environments?.[name] ?? {}, {\n environmentId: uuid(),\n name,\n title: config.title ?? titleCase(config.name),\n ssr: false,\n resolve: {\n mainFields:\n config.platform === \"browser\"\n ? [\"browser\", \"module\", \"jsnext:main\", \"jsnext\"]\n : [\"module\", \"jsnext:main\", \"jsnext\"]\n },\n consumer: config.platform === \"browser\" ? \"client\" : \"server\",\n preview:\n config.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 }) as EnvironmentResolvedConfig;\n}\n\nexport function createDefaultEnvironment<\n TContext extends ExecutionContext = ExecutionContext\n>(config: Partial<TContext[\"config\"]> = {}): EnvironmentResolvedConfig {\n return createEnvironment(DEFAULT_ENVIRONMENT, config);\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 { UserConfig } from \"@powerlines/core\";\nimport { isSetString } from \"@stryke/type-checks/is-set-string\";\n\nexport function getConfigProps(config: Partial<UserConfig> = {}) {\n return {\n name: config.name,\n title: config.title,\n description: config.description,\n projectType: config.projectType,\n customLogger: config.customLogger,\n logLevel: config.logLevel,\n tsconfig: config.tsconfig,\n tsconfigRaw: config.tsconfigRaw,\n skipCache: config.skipCache,\n autoInstall: config.autoInstall,\n input: isSetString(config.input) ? [config.input] : config.input,\n plugins: config.plugins,\n mode: config.mode,\n resolve: config.resolve,\n framework: config.framework,\n ...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 type { Context, MetaInfo } from \"@powerlines/core\";\nimport { ROOT_HASH_LENGTH } from \"@powerlines/core/constants\";\nimport { existsSync } from \"@stryke/fs/exists\";\nimport { readJsonFile } from \"@stryke/fs/json\";\nimport { removeFile } from \"@stryke/fs/remove-file\";\nimport { joinPaths } from \"@stryke/path/join-paths\";\nimport { kebabCase } from \"@stryke/string-format/kebab-case\";\n\nexport interface CreateContextOptions {\n name?: string;\n}\n\n/**\n * Generates a prefixed project root hash object.\n *\n * @remarks\n * This function returns a string where the project root hash is prefixed with the project name plus a hyphen. If the total length of this string combination exceeds 45 characters, it will truncate the hash.\n *\n * @param name - The name of the project.\n * @param rootHash - The hash of the project root.\n * @returns An object containing the name and project root hash.\n */\nexport function getPrefixedRootHash(name: string, rootHash: string): string {\n const combined = `${kebabCase(name)}_${rootHash}`;\n\n return combined.length > ROOT_HASH_LENGTH\n ? combined.slice(0, ROOT_HASH_LENGTH)\n : combined;\n}\n\n/**\n * Retrieves the persisted meta information from the context's data path.\n *\n * @param context - The build context.\n * @returns A promise that resolves to the persisted meta information, or undefined if not found.\n */\nexport async function getPersistedMeta(\n context: Context\n): Promise<MetaInfo | undefined> {\n const metaFilePath = joinPaths(context.dataPath, \"meta.json\");\n if (existsSync(metaFilePath)) {\n try {\n return await readJsonFile<MetaInfo>(metaFilePath);\n } catch {\n context.warn(\n `Failed to read meta file at ${metaFilePath}. It may be corrupted.`\n );\n await removeFile(metaFilePath);\n\n context.persistedMeta = undefined;\n }\n }\n\n return undefined;\n}\n\n/**\n * Writes the meta file for the context.\n *\n * @param context - The context to write the meta file for.\n * @returns A promise that resolves when the meta file has been written.\n */\nexport async function writeMetaFile(context: Context): Promise<void> {\n const metaFilePath = joinPaths(context.dataPath, \"meta.json\");\n\n context.debug(`Writing runtime metadata to ${metaFilePath}`);\n\n await context.fs.write(metaFilePath, JSON.stringify(context.meta, null, 2));\n}\n","/* -------------------------------------------------------------------\n\n ⚡ Storm Software - Powerlines\n\n This code was released as part of the Powerlines project. Powerlines\n is maintained by Storm Software under the Apache-2.0 license, and is\n free for commercial and private use. For more information, please visit\n our licensing page at https://stormsoftware.com/licenses/projects/powerlines.\n\n Website: https://stormsoftware.com\n Repository: https://github.com/storm-software/powerlines\n Documentation: https://docs.stormsoftware.com/projects/powerlines\n Contact: https://stormsoftware.com/contact\n\n SPDX-License-Identifier: Apache-2.0\n\n ------------------------------------------------------------------- */\n\nimport { Context, LogCategories, LogFnMeta } from \"@powerlines/core\";\nimport { isSetObject } from \"@stryke/type-checks/is-set-object\";\nimport { uuid } from \"@stryke/unique-id/uuid\";\nimport { IpcMessageType } from \"./messages\";\n\nexport function sendWriteLogMessage<TContext extends Context = Context>(\n context: TContext,\n meta: LogFnMeta,\n message: string\n) {\n const combinedMeta = {\n ...context.logger.options,\n ...(isSetObject(meta) ? meta : { type: meta })\n };\n\n process.send?.({\n id: uuid(),\n type: IpcMessageType.WRITE_LOG,\n executionId: combinedMeta.executionId || context.config.executionId,\n executionIndex:\n combinedMeta.executionIndex ?? context.config.executionIndex,\n environment: combinedMeta.environment,\n timestamp: Date.now(),\n payload: {\n meta: {\n type: combinedMeta.type,\n category: combinedMeta.category || LogCategories.GENERAL,\n logId: combinedMeta.logId || uuid(),\n timestamp: combinedMeta.timestamp ?? Date.now(),\n name: combinedMeta.name || context.config.name,\n executionId: combinedMeta.executionId || context.config.executionId,\n executionIndex:\n combinedMeta.executionIndex ?? context.config.executionIndex,\n command: combinedMeta.command || context.config.command,\n hook: combinedMeta.hook,\n environment: combinedMeta.environment,\n plugin: combinedMeta.plugin,\n source: combinedMeta.source\n },\n message\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\nexport const DEFAULT_EXTENSIONS = [\n \"js\",\n \"ts\",\n \"cjs\",\n \"cts\",\n \"mjs\",\n \"mts\",\n \"tsx\",\n \"jsx\",\n \"json\",\n \"json5\",\n \"jsonc\",\n \"md\",\n \"mdx\"\n];\n","/* -------------------------------------------------------------------\n\n ⚡ Storm Software - Powerlines\n\n This code was released as part of the Powerlines project. Powerlines\n is maintained by Storm Software under the Apache-2.0 license, and is\n free for commercial and private use. For more information, please visit\n our licensing page at https://stormsoftware.com/licenses/projects/powerlines.\n\n Website: https://stormsoftware.com\n Repository: https://github.com/storm-software/powerlines\n Documentation: https://docs.stormsoftware.com/projects/powerlines\n Contact: https://stormsoftware.com/contact\n\n SPDX-License-Identifier: Apache-2.0\n\n ------------------------------------------------------------------- */\n\nimport type {\n Context,\n Logger,\n ResolveOptions,\n StorageAdapter,\n StoragePort,\n StoragePreset,\n VirtualFileMetadata,\n VirtualFileSystemInterface,\n WriteOptions\n} from \"@powerlines/core\";\nimport { format } from \"@powerlines/core/lib/utilities/format\";\nimport { replacePathTokens } from \"@powerlines/core/plugin-utils\";\nimport * as capnp from \"@stryke/capnp\";\nimport { toArray } from \"@stryke/convert/to-array\";\nimport {\n readFileBuffer,\n readFileBufferSync,\n writeFileBuffer\n} from \"@stryke/fs/buffer\";\nimport { existsSync } from \"@stryke/fs/exists\";\nimport {\n getResolutionCombinations,\n resolve,\n resolveSync\n} from \"@stryke/fs/resolve\";\nimport { murmurhash } from \"@stryke/hash\";\nimport { getUnique } from \"@stryke/helpers/get-unique\";\nimport { appendPath } from \"@stryke/path/append\";\nimport { correctPath, stripStars } from \"@stryke/path/correct-path\";\nimport {\n findFileExtensionSafe,\n findFileName,\n findFilePath,\n hasFileExtension\n} from \"@stryke/path/file-path-fns\";\nimport { globToRegex } from \"@stryke/path/glob-to-regex\";\nimport { isParentPath } from \"@stryke/path/is-parent-path\";\nimport { isAbsolutePath } from \"@stryke/path/is-type\";\nimport { joinPaths } from \"@stryke/path/join\";\nimport { replaceExtension, replacePath } from \"@stryke/path/replace\";\nimport { slash } from \"@stryke/path/slash\";\nimport { prettyBytes } from \"@stryke/string-format/pretty-bytes\";\nimport { isRegExp } from \"@stryke/type-checks/is-regexp\";\nimport { isSet } from \"@stryke/type-checks/is-set\";\nimport { isSetObject } from \"@stryke/type-checks/is-set-object\";\nimport { isSetString } from \"@stryke/type-checks/is-set-string\";\nimport { isString } from \"@stryke/type-checks/is-string\";\nimport { AssetGlob } from \"@stryke/types/file\";\nimport { match } from \"bundle-require\";\nimport { create, FlatCache } from \"flat-cache\";\nimport { Blob } from \"node:buffer\";\nimport { PathOrFileDescriptor } from \"node:fs\";\nimport { fileURLToPath } from \"node:url\";\nimport { FileId, FileMetadata, FileSystem } from \"../../schemas/fs\";\nimport { FileSystemStorageAdapter } from \"../storage/file-system\";\nimport { VirtualStorageAdapter } from \"../storage/virtual\";\nimport { DEFAULT_EXTENSIONS } from \"./helpers/constants\";\n\ninterface StorageAdapterState {\n adapter: StorageAdapter;\n relativeKey: string;\n base: string;\n}\n\nfunction toFilePath(path: PathOrFileDescriptor): string {\n return correctPath(slash(path?.toString() || \".\").replace(/^file:\\/\\//, \"\"));\n}\n\n/**\n * Checks if a given file id is valid based on the specified prefix.\n *\n * @param id - The file ID to check.\n * @param prefix - The prefix to use for built-in files. Default is \"powerlines\".\n * @returns `true` if the file ID is valid, otherwise `false`.\n */\nfunction isValidId(id: string, prefix = \"powerlines\"): boolean {\n return id.replace(/^\\\\0/, \"\").startsWith(`${prefix.replace(/:$/, \"\")}`);\n}\n\n/**\n * Formats a file id by removing the file extension and prepended runtime prefix.\n *\n * @param id - The file ID to format.\n * @param prefix - The prefix to use for built-in files. Default is \"powerlines\".\n * @returns The formatted file ID.\n */\nfunction normalizeId(id: string, prefix = \"powerlines\"): string {\n // return `${prefix.replace(/:$/, \"\")}:${toFilePath(id)\n // .replace(new RegExp(`^${prefix.replace(/:$/, \"\")}:`), \"\")\n // .replace(/^\\\\0/, \"\")\n // .replace(findFileDotExtensionSafe(toFilePath(id)), \"\")}`;\n\n return replaceExtension(toFilePath(id))\n .replace(/^\\\\0/, \"\")\n .replace(/^powerlines:/, \"\")\n .replace(new RegExp(`^${prefix.replace(/:$/, \"\")}:`), \"\");\n}\n\n/**\n * Normalizes a given path by resolving it against the project root, workspace root, and built-ins path.\n *\n * @param path - The path to normalize.\n * @param builtinsPath - The path to built-in files.\n * @param prefix - The prefix to use for built-in files. Default is \"powerlines\".\n * @returns The normalized path.\n */\nfunction normalizePath(\n path: string,\n builtinsPath: string,\n prefix = \"powerlines\"\n): string {\n if (!isSetString(path)) {\n if (!isString(path)) {\n throw new Error(\"Path type must be a string or a file descriptor\");\n }\n throw new Error(\"Path cannot be empty\");\n }\n\n return isAbsolutePath(path)\n ? path\n : isValidId(toFilePath(path), prefix)\n ? normalizeId(toFilePath(path), prefix).replace(\n new RegExp(`^${prefix.replace(/:$/, \"\")}:`),\n builtinsPath\n )\n : toFilePath(path);\n}\n\n/**\n * Normalizes glob patterns by resolving them against the workspace root.\n *\n * @param workspaceRoot - The root directory of the workspace.\n * @param patterns - The glob patterns to normalize.\n * @returns An array of normalized glob patterns.\n */\nfunction normalizeGlobPatterns(\n workspaceRoot: string,\n patterns:\n | string\n | Omit<AssetGlob, \"output\">\n | (string | Omit<AssetGlob, \"output\">)[]\n): string[] {\n return getUnique(\n toArray(patterns)\n .map(pattern => {\n if (\n isSetObject(pattern) &&\n (isSetString(pattern.input) || isSetString(pattern.glob))\n ) {\n return joinPaths(\n pattern.input || workspaceRoot,\n pattern.glob || \"**/*\"\n );\n } else if (!isSetString(pattern)) {\n return undefined;\n }\n\n return pattern;\n })\n .filter(isSetString)\n );\n}\n\n/**\n * Represents a virtual file system (VFS) that stores files and their associated metadata in virtual memory.\n *\n * @remarks\n * This class provides methods to manage virtual files, check their existence, retrieve their content, and manipulate the virtual file system. It allows for efficient file management and retrieval without relying on the actual file system.\n */\nexport class VirtualFileSystem implements VirtualFileSystemInterface {\n /**\n * A map of virtual file IDs to their associated metadata.\n */\n #metadata: Record<string, VirtualFileMetadata>;\n\n /**\n * A map of underlying file paths to their virtual file IDs.\n */\n #ids: Record<string, string>;\n\n /**\n * A map of virtual file IDs to their underlying file paths.\n */\n #paths: Record<string, string>;\n\n /**\n * The unified volume that combines the virtual file system with the real file system.\n *\n * @remarks\n * This volume allows for seamless access to both virtual and real files.\n */\n #storage: StoragePort;\n\n // /**\n // * The resolver factory used during module resolution within the virtual file system.\n // *\n // * @see https://github.com/oxc-project/oxc-resolver\n // */\n // #resolver!: ResolverFactory;\n\n /**\n * A cache for module resolution results.\n */\n #resolverCache!: FlatCache;\n\n /**\n * Indicator specifying if the virtual file system (VFS) is disposed\n */\n #isDisposed = false;\n\n /**\n * The context of the virtual file system.\n */\n #context: Context;\n\n /**\n * The file system's logger client utility.\n */\n #logger: Logger;\n\n /**\n * Normalizes a given module id by resolving it against the built-ins path.\n *\n * @param id - The module id to normalize.\n * @returns The normalized module id.\n */\n #normalizeId(id: string): string {\n let normalized = id;\n if (isParentPath(normalized, this.#context.builtinsPath)) {\n normalized = replacePath(normalized, this.#context.builtinsPath);\n }\n\n return normalizeId(normalized, this.#context.config.framework);\n }\n\n /**\n * Normalizes a given path by resolving it against the project root, workspace root, and built-ins path.\n *\n * @param path - The path to normalize.\n * @returns The normalized path.\n */\n #normalizePath(path: string): string {\n if (!isSetString(path)) {\n if (!isString(path)) {\n throw new Error(\"Path type must be a string or a file descriptor\");\n }\n throw new Error(\"Path cannot be empty\");\n }\n\n return normalizePath(\n path.includes(\"{\") || path.includes(\"}\")\n ? replacePathTokens(this.#context, path)\n : path,\n this.#context.builtinsPath,\n this.#context.config.framework\n );\n }\n\n /**\n * Gets the storage adapter and relative key for a given key.\n *\n * @remarks\n * The `key` can be either a path or a storage adapter name.\n *\n * @param key - The key to get the storage adapter for.\n * @returns The storage adapter and relative key for the given key.\n */\n #getStorage(key: string, preset?: StoragePreset): StorageAdapterState {\n const path = this.resolveSync(this.#normalizePath(key)) || key;\n for (const base of Object.keys(this.#storage)\n .filter(Boolean)\n .sort()\n .reverse()) {\n if (\n (path === base || isParentPath(path, base)) &&\n (!preset ||\n this.#storage[base]?.preset?.toLowerCase() === preset.toLowerCase())\n ) {\n return {\n base,\n relativeKey: replacePath(path, base),\n adapter: this.#storage[base]!\n };\n }\n }\n\n if (\n !preset ||\n this.#storage[\"\"]?.preset?.toLowerCase() === preset.toLowerCase()\n ) {\n return {\n base: \"\",\n relativeKey: path,\n adapter: this.#storage[\"\"]!\n };\n }\n\n this.#storage[path] =\n preset === \"virtual\"\n ? new VirtualStorageAdapter(this.#context, {\n base: path\n })\n : new FileSystemStorageAdapter(this.#context, {\n base: path\n });\n\n return {\n base: path,\n relativeKey: \"\",\n adapter: this.#storage[path]\n };\n }\n\n /**\n * Gets all storage adapters that match a given base key.\n *\n * @param base - The base key to match storage adapters against.\n * @param includeParent - Whether to include parent storage adapters.\n * @returns An array of storage adapters that match the given base key.\n */\n #getStorages(base = \"\", includeParent = false) {\n const baseKey = this.resolveSync(base) || base;\n\n return Object.keys(this.#storage)\n .sort()\n .reverse()\n .filter(\n key =>\n isParentPath(key, baseKey) ||\n (includeParent && isParentPath(baseKey, key)) ||\n (baseKey.includes(\"*\") &&\n (isParentPath(stripStars(baseKey), key) ||\n globToRegex(replaceExtension(baseKey)).test(key)))\n )\n .map(key => ({\n relativeBase:\n baseKey.length > key.length ? baseKey.slice(key.length) : undefined,\n base: key,\n adapter: this.#storage[key]!\n }));\n }\n\n /**\n * A helper function to resolve modules in the virtual file system (VFS).\n *\n * @remarks\n * This function can be used to resolve modules relative to the project root directory.\n *\n * @example\n * ```ts\n * const resolved = await context.resolvePath(\"some-module\", \"/path/to/importer\");\n * ```\n *\n * @param id - The module to resolve.\n * @param importer - An optional path to the importer module.\n * @param options - Additional resolution options.\n * @returns A promise that resolves to the resolved module path.\n */\n #innerResolve = async (\n id: string,\n importer?: string,\n options: ResolveOptions = {}\n ): Promise<string | undefined> => {\n let path = id;\n if (path.includes(\"{\") || path.includes(\"}\")) {\n path = replacePathTokens(this.#context, path);\n }\n\n if (options.skipAlias !== true) {\n path = this.resolveAlias(path);\n }\n\n if (\n isAbsolutePath(path) &&\n (!options.isFile || !(await this.isDirectory(path)))\n ) {\n return path;\n }\n\n const resolverCacheKey = murmurhash({\n path: this.#normalizeId(path),\n importer,\n options\n });\n\n let result!: string | undefined;\n if (!this.#context.config.skipCache) {\n result = this.resolverCache.get<string | undefined>(resolverCacheKey);\n if (result) {\n return result;\n }\n }\n\n result = this.paths[this.#normalizeId(path)];\n if (!isSetString(result)) {\n const paths = options.paths ?? [];\n if (importer && !paths.includes(importer)) {\n paths.push(importer);\n }\n\n if (!importer) {\n paths.push(this.#context.config.cwd);\n paths.push(\n appendPath(this.#context.config.root, this.#context.config.cwd)\n );\n paths.push(\n appendPath(\n joinPaths(this.#context.config.root, \"src\"),\n this.#context.config.cwd\n )\n );\n }\n\n paths.push(\n ...(\n Object.keys(this.#context.tsconfig?.options?.paths ?? {})\n .filter(tsconfigPath =>\n path.startsWith(tsconfigPath.replace(/\\*$/, \"\"))\n )\n .map(\n tsconfigPath =>\n this.#context.tsconfig?.options?.paths?.[tsconfigPath]\n )\n .flat()\n .filter(Boolean) as string[]\n ).map(tsconfigPath =>\n appendPath(tsconfigPath, this.#context.config.cwd)\n )\n );\n\n for (const combination of getResolutionCombinations(path, {\n paths: getUnique(paths)\n })) {\n const { relativeKey, adapter } = this.#getStorage(combination);\n if (await adapter.exists(relativeKey)) {\n result = combination;\n break;\n }\n }\n\n if (!isSetString(result)) {\n try {\n result = await resolve(path, { ...options, paths });\n } catch {\n // Do nothing\n }\n\n // if (!result) {\n // let index = 0;\n // do {\n // const resolveResult = await this.resolver.async(\n // (paths.length > index ? paths[index] : undefined) ||\n // this.#context.config.root,\n // path\n // );\n // if (resolveResult.path) {\n // result = resolveResult.path;\n // }\n\n // index++;\n // } while (!result && index < paths.length);\n // }\n }\n }\n\n if (isSetString(result)) {\n if (!this.#context.config.skipCache) {\n this.resolverCache.set(this.#normalizeId(path), result);\n }\n\n return result;\n }\n\n return undefined;\n };\n\n /**\n * A synchronous helper function to resolve modules using the Jiti resolver\n *\n * @remarks\n * This function can be used to resolve modules relative to the project root directory.\n *\n * @example\n * ```ts\n * const resolvedPath = context.resolveSync(\"some-module\", \"/path/to/importer\");\n * ```\n *\n * @param id - The module to resolve.\n * @param importer - An optional path to the importer module.\n * @param options - Additional resolution options.\n * @returns The resolved module path.\n */\n #innerResolveSync = (\n id: string,\n importer?: string,\n options: ResolveOptions = {}\n ): string | undefined => {\n let path = id;\n if (path.includes(\"{\") || path.includes(\"}\")) {\n path = replacePathTokens(this.#context, path);\n }\n\n if (options.skipAlias !== true) {\n path = this.resolveAlias(path);\n }\n\n if (\n isAbsolutePath(path) &&\n (!options.isFile || !this.isDirectorySync(path))\n ) {\n return path;\n }\n\n let result!: string | undefined;\n if (!this.#context.config.skipCache) {\n result = this.resolverCache.get<string | undefined>(\n this.#normalizeId(path)\n );\n if (isSetString(result)) {\n return result;\n }\n }\n\n result = this.paths[this.#normalizeId(path)];\n if (!isSetString(result)) {\n const paths = options.paths ?? [];\n if (importer && !paths.includes(importer)) {\n paths.push(importer);\n }\n\n if (!importer) {\n paths.push(this.#context.config.cwd);\n paths.push(\n appendPath(this.#context.config.root, this.#context.config.cwd)\n );\n paths.push(\n appendPath(\n joinPaths(this.#context.config.root, \"src\"),\n this.#context.config.cwd\n )\n );\n }\n\n paths.push(\n ...(\n Object.keys(this.#context.tsconfig?.options?.paths ?? {})\n .filter(tsconfigPath =>\n path.startsWith(tsconfigPath.replace(/\\*$/, \"\"))\n )\n .map(\n tsconfigPath =>\n this.#context.tsconfig?.options?.paths?.[tsconfigPath]\n )\n .flat()\n .filter(Boolean) as string[]\n ).map(tsconfigPath =>\n appendPath(tsconfigPath, this.#context.config.cwd)\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 (!isSetString(result)) {\n try {\n result = resolveSync(path, { ...options, paths });\n } catch {\n // Do nothing\n }\n\n // if (!result) {\n // let index = 0;\n // do {\n // const resolveResult = this.resolver.sync(\n // (paths.length > index ? paths[index] : undefined) ||\n // this.#context.config.root,\n // path\n // );\n // if (resolveResult.path) {\n // result = resolveResult.path;\n // }\n\n // index++;\n // } while (!result && index < paths.length);\n // }\n }\n }\n\n if (isSetString(result)) {\n if (!this.#context.config.skipCache) {\n this.resolverCache.set(this.#normalizeId(path), result);\n }\n\n return result;\n }\n\n return undefined;\n };\n\n /**\n * Creates a virtual file system (VFS) that is backed up to a Cap'n Proto message buffer.\n *\n * @param context - The context of the virtual file system, typically containing options and logging functions.\n * @returns A promise that resolves to a new virtual file system instance.\n */\n public static async create(context: Context): Promise<VirtualFileSystem> {\n context.debug(\n \"Starting virtual file system (VFS) initialization processes...\"\n );\n\n let result!: VirtualFileSystem;\n if (\n !context.config.skipCache &&\n existsSync(joinPaths(context.dataPath, \"fs.bin\"))\n ) {\n const buffer = await readFileBuffer(\n joinPaths(context.dataPath, \"fs.bin\")\n );\n\n const message = new capnp.Message(buffer, false);\n const fs = message.getRoot(FileSystem);\n\n result = new VirtualFileSystem(context, fs);\n\n if (fs._hasStorage() && fs.storage.length > 0) {\n await Promise.all(\n fs.storage.values().map(async file => {\n if (file.path && file.code) {\n let id: FileId | undefined;\n if (fs._hasIds()) {\n id = fs.ids.find((fileId: FileId) => fileId.path === file.path);\n }\n\n let metadata: FileMetadata | undefined;\n if (fs._hasMetadata()) {\n metadata = fs.metadata.find(\n (meta: FileMetadata) =>\n meta.id === result.#normalizeId(id?.id ?? file.path)\n );\n }\n\n await result.write(file.path, file.code, {\n meta: {\n id: result.#normalizeId(id?.id ?? metadata?.id ?? file.path),\n type: metadata?.type || \"normal\",\n properties: metadata?._hasProperties()\n ? metadata?.properties.values().reduce(\n (ret, kvp) => {\n ret[kvp.key] = kvp.value;\n return ret;\n },\n {} as Record<string, string>\n )\n : undefined,\n timestamp: metadata?.timestamp\n }\n });\n }\n })\n );\n }\n } else {\n const message = new capnp.Message();\n result = new VirtualFileSystem(context, message.initRoot(FileSystem));\n }\n\n result.#logger.debug(\n \"Successfully completed virtual file system (VFS) initialization.\"\n );\n\n return result;\n }\n\n /**\n * Synchronously creates a virtual file system (VFS) that is backed up to a Cap'n Proto message buffer.\n *\n * @param context - The context of the virtual file system, typically containing options and logging functions.\n * @returns A new virtual file system instance.\n */\n public static createSync(context: Context): VirtualFileSystem {\n context.debug(\n \"Starting virtual file system (VFS) initialization processes...\"\n );\n\n let result!: VirtualFileSystem;\n if (\n !context.config.skipCache &&\n existsSync(joinPaths(context.dataPath, \"fs.bin\"))\n ) {\n const buffer = readFileBufferSync(joinPaths(context.dataPath, \"fs.bin\"));\n\n const message = new capnp.Message(buffer, false);\n const fs = message.getRoot(FileSystem);\n\n result = new VirtualFileSystem(context, fs);\n\n if (fs._hasStorage() && fs.storage.length > 0) {\n fs.storage.values().forEach(file => {\n if (file.path && file.code) {\n let id: FileId | undefined;\n if (fs._hasIds()) {\n id = fs.ids.find((fileId: FileId) => fileId.path === file.path);\n }\n\n let metadata: FileMetadata | undefined;\n if (fs._hasMetadata()) {\n metadata = fs.metadata.find(\n (meta: FileMetadata) =>\n meta.id === result.#normalizeId(id?.id ?? file.path)\n );\n }\n\n result.writeSync(file.path, file.code, {\n meta: {\n id: result.#normalizeId(id?.id ?? metadata?.id ?? file.path),\n type: metadata?.type,\n properties: metadata?._hasProperties()\n ? metadata?.properties.values().reduce(\n (ret, kvp) => {\n ret[kvp.key] = kvp.value;\n return ret;\n },\n {} as Record<string, string>\n )\n : undefined,\n timestamp: metadata?.timestamp\n }\n });\n }\n });\n }\n } else {\n const message = new capnp.Message();\n result = new VirtualFileSystem(context, message.initRoot(FileSystem));\n }\n\n result.#logger.debug(\n \"Successfully completed virtual file system (VFS) initialization.\"\n );\n\n return result;\n }\n\n /**\n * A map of file ids to their metadata.\n */\n public get metadata(): Record<string, VirtualFileMetadata> {\n return new Proxy(this.#metadata, {\n get: (target, prop: string) => {\n return target[this.#normalizeId(prop)];\n },\n set: (target, prop: string, value) => {\n target[this.#normalizeId(prop)] = value;\n return true;\n },\n deleteProperty: (target, prop: string) => {\n delete target[this.#normalizeId(prop)];\n return true;\n },\n has: (target, prop: string) => {\n return this.#normalizeId(prop) in target;\n },\n ownKeys: target => {\n return getUnique(\n Reflect.ownKeys(target).map(key => this.#normalizeId(key as string))\n );\n }\n });\n }\n\n /**\n * A map of file paths to their module ids.\n */\n public get ids(): Record<string, string> {\n return new Proxy(this.#ids, {\n get: (target, prop: string) => {\n return target[this.#normalizePath(prop)];\n },\n set: (target, prop: string, value) => {\n target[this.#normalizePath(prop)] = value;\n return true;\n },\n deleteProperty: (target, prop: string) => {\n delete target[this.#normalizePath(prop)];\n return true;\n },\n has: (target, prop: string) => {\n return this.#normalizePath(prop) in target;\n },\n ownKeys: target => {\n return getUnique(\n Reflect.ownKeys(target).map(key => this.#normalizePath(key as string))\n );\n }\n });\n }\n\n /**\n * A map of module ids to their file paths.\n */\n public get paths(): Record<string, string> {\n return new Proxy(this.#paths, {\n get: (target, prop: string) => {\n return this.#normalizeId(prop) in target\n ? target[this.#normalizeId(prop)]\n : undefined;\n },\n set: (target, prop: string, value) => {\n target[this.#normalizeId(prop)] = value;\n return true;\n },\n deleteProperty: (target, prop: string) => {\n delete target[this.#normalizeId(prop)];\n return true;\n },\n has: (target, prop: string) => {\n return this.#normalizeId(prop) in target;\n },\n ownKeys: target => {\n return getUnique(\n Reflect.ownKeys(target).map(key => this.#normalizeId(key as string))\n );\n }\n });\n }\n\n /**\n * Gets the resolver cache.\n */\n protected get resolverCache(): FlatCache {\n if (!this.#resolverCache) {\n this.#resolverCache = create({\n cacheId: \"module-resolution\",\n cacheDir: this.#context.cachePath,\n ttl: 2.5 * 60 * 1000,\n lruSize: 8000,\n persistInterval: 100\n });\n }\n\n return this.#resolverCache;\n }\n\n // /**\n // * The resolver factory used during module resolution within the virtual file system.\n // *\n // * @remarks\n // * This resolver is configured with the workspace root, project root, TypeScript configuration, alias mappings, and other resolution options specified in the context. It is lazily initialized on first access to optimize performance.\n // *\n // * @see https://github.com/oxc-project/oxc-resolver\n // */\n // protected get resolver(): ResolverFactory {\n // if (!this.#resolver) {\n // this.#resolver = new ResolverFactory({\n // roots: [\n // this.#context.config.cwd,\n // appendPath(\n // this.#context.config.root,\n // this.#context.config.cwd\n // )\n // ],\n // tsconfig: {\n // configFile: this.#context.tsconfig.tsconfigFilePath,\n // references:\n // this.#context.tsconfig.projectReferences &&\n // this.#context.tsconfig.projectReferences.length > 0\n // ? \"auto\"\n // : undefined\n // },\n // alias: Object.fromEntries(\n // Object.entries(this.#context.alias).map(([key, value]) => [\n // key,\n // [value]\n // ])\n // ),\n // extensions: this.#context.config.resolve.extensions,\n // mainFields: this.#context.config.resolve.mainFields,\n // conditionNames: this.#context.config.resolve.conditions,\n // symlinks: this.#context.config.resolve.preserveSymlinks,\n // allowPackageExportsInDirectoryResolve: true\n // });\n // }\n\n // return this.#resolver;\n // }\n\n /**\n * Creates a new instance of the {@link VirtualFileSystem}.\n *\n * @param context - The context of the virtual file system, typically containing options and logging functions.\n * @param fs - A buffer containing the serialized virtual file system data.\n */\n private constructor(context: Context, fs: FileSystem) {\n this.#context = context;\n this.#storage = { \"\": new FileSystemStorageAdapter(context) };\n\n if (isSetObject(this.#context.config.output.storage)) {\n this.#storage = {\n ...this.#storage,\n ...this.#context.config.output.storage\n };\n }\n\n this.#storage.virtual ??= new VirtualStorageAdapter(context, {\n base: \"/_virtual\"\n });\n\n this.#storage[this.#context.config.output.path] ??=\n new FileSystemStorageAdapter(context, {\n base: this.#context.config.output.path\n });\n\n if (\n this.#context.config.output.copy &&\n this.#context.config.output.copy.path\n ) {\n this.#storage[this.#context.config.output.copy.path] ??=\n new FileSystemStorageAdapter(context, {\n base: this.#context.config.output.copy.path\n });\n }\n\n if (this.#context.config.output.storage !== \"fs\") {\n this.#storage[this.#context.artifactsPath] ??= new VirtualStorageAdapter(\n context,\n {\n base: this.#context.artifactsPath\n }\n );\n this.#storage[this.#context.builtinsPath] ??= new VirtualStorageAdapter(\n context,\n {\n base: this.#context.builtinsPath\n }\n );\n this.#storage[this.#context.entryPath] ??= new VirtualStorageAdapter(\n context,\n {\n base: this.#context.entryPath\n }\n );\n }\n\n this.#metadata = {};\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 = {};\n this.#paths = {};\n\n if (fs._hasIds()) {\n this.#ids = fs.ids.values().reduce(\n (ret, identifier) => {\n ret[identifier.path] ??= identifier.id;\n\n return ret;\n },\n {} as Record<string, string>\n );\n\n this.#paths = fs.ids.values().reduce(\n (ret, identifier) => {\n ret[identifier.id] ??= identifier.path;\n return ret;\n },\n {} as Record<string, string>\n );\n }\n\n this.#logger = context.extendLogger({ category: \"fs\" });\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 * @param importer - An optional path to the importer module.\n * @param options - Additional resolution options.\n * @returns `true` if the file is virtual, otherwise `false`.\n */\n public isVirtual(\n path: string,\n importer?: string | undefined,\n options?: ResolveOptions\n ): boolean {\n const resolved = this.resolveSync(path, importer, options);\n if (!isSetString(resolved)) {\n if (isSet(resolved)) {\n throw new Error(`Resolved path is not a string: ${String(resolved)}`);\n }\n return false;\n }\n\n return (\n this.#getStorage(resolved)?.adapter?.preset === \"virtual\" ||\n resolved.startsWith(`${this.#context.config.framework}:`) ||\n path.startsWith(`${this.#context.config.framework}:`)\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 * @param importer - An optional path to the importer module.\n * @param options - Additional resolution options.\n * @returns `true` if the path is a directory, otherwise `false`.\n */\n public isDirectorySync(\n path: string,\n importer?: string | undefined,\n options?: ResolveOptions\n ): boolean {\n const resolved = this.resolveSync(path, importer, options);\n if (!isSetString(resolved)) {\n if (isSet(resolved)) {\n throw new Error(`Resolved path is not a string: ${String(resolved)}`);\n }\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 * @param importer - An optional path to the importer module.\n * @param options - Additional resolution options.\n * @returns `true` if the path is a directory, otherwise `false`.\n */\n public async isDirectory(\n path: string,\n importer?: string | undefined,\n options?: ResolveOptions\n ): Promise<boolean> {\n const resolved = await this.resolve(path, importer, options);\n if (!isSetString(resolved)) {\n if (isSet(resolved)) {\n throw new Error(`Resolved path is not a string: ${String(resolved)}`);\n }\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 * @param importer - An optional path to the importer module.\n * @param options - Additional resolution options.\n * @returns `true` if the path is a file, otherwise `false`.\n */\n public isFileSync(\n path: string,\n importer?: string | undefined,\n options?: ResolveOptions\n ): boolean {\n const resolved = this.resolveSync(path, importer, options);\n if (!isSetString(resolved)) {\n if (isSet(resolved)) {\n throw new Error(`Resolved path is not a string: ${String(resolved)}`);\n }\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 * @param importer - An optional path to the importer module.\n * @param options - Additional resolution options.\n * @returns `true` if the path is a file, otherwise `false`.\n */\n public async isFile(\n path: string,\n importer?: string | undefined,\n options?: ResolveOptions\n ): Promise<boolean> {\n const resolved = await this.resolve(path, importer, options);\n if (!isSetString(resolved)) {\n if (isSet(resolved)) {\n throw new Error(`Resolved path is not a string: ${String(resolved)}`);\n }\n return false;\n }\n\n return (\n (await this.#getStorage(resolved)?.adapter?.isFile(resolved)) ?? false\n );\n }\n\n /**\n * Checks if a file Id must be resolved by the virtual file system (VFS).\n *\n * @remarks\n * Examples of file Ids that would be considered virtual include:\n * - Ids that start with the framework specific prefix (e.g. `powerlines:`)\n * - Ids that match a configured alias for virtual modules (returned true from {@link VirtualFileSystemInterface.isVirtual})\n *\n * @param path - The path or id of the file.\n * @param importer - An optional path to the importer module, used for resolving the file path.\n * @param options - Additional options for resolving the file path.\n * @returns `true` if the file is virtual, otherwise `false`.\n */\n public isResolvableId(\n path: string,\n importer?: string | undefined,\n options?: ResolveOptions\n ): boolean {\n return (\n path.startsWith(`${this.#context.config.framework}:`) ||\n this.isVirtual(path, importer, options) ||\n this.isAlias(path) ||\n this.isTsconfigPath(path)\n );\n }\n\n /**\n * Lists files in a given path.\n *\n * @param path - The path to list files from.\n * @returns An array of file names in the specified path.\n */\n public listSync(path: string): string[] {\n let resolvedPath = path;\n if (resolvedPath.includes(\"*\")) {\n this.#logger.warn(\n `Invoking \"listSync\" with a glob pattern is not supported. It is likely you meant to use \"globSync\". Path: ${path}`\n );\n resolvedPath = stripStars(resolvedPath);\n }\n\n return getUnique(\n this.#getStorages(resolvedPath, true)\n .map(storage =>\n storage.adapter.listSync(\n storage.relativeBase\n ? storage.base\n ? appendPath(storage.relativeBase, storage.base)\n : storage.relativeBase\n : storage.base\n )\n )\n .flat()\n .filter(Boolean)\n );\n }\n\n /**\n * Lists files in a given path.\n *\n * @param path - The path to list files from.\n * @returns An array of file names in the specified path.\n */\n public async list(path: string): Promise<string[]> {\n let resolvedPath = path;\n if (resolvedPath.includes(\"*\")) {\n this.#logger.warn(\n `Invoking \"list\" with a glob pattern is not supported. It is likely you meant to use \"glob\". Path: ${path}`\n );\n resolvedPath = stripStars(resolvedPath);\n }\n\n return getUnique(\n (\n await Promise.all(\n this.#getStorages(resolvedPath, true).map(async storage =>\n storage.adapter.list(\n storage.relativeBase\n ? storage.base\n ? appendPath(storage.relativeBase, storage.base)\n : storage.relativeBase\n : storage.base\n )\n )\n )\n )\n .flat()\n .filter(Boolean)\n );\n }\n\n /**\n * Removes a file in the virtual file system (VFS).\n *\n * @param path - The path to create the directory at.\n */\n public async remove(path: string): Promise<void> {\n const normalizedPath = this.#normalizePath(path);\n this.#logger.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.#logger.trace(`Removing file: ${normalizedPath}`);\n\n const { relativeKey, adapter } = this.#getStorage(normalizedPath);\n\n if (hasFileExtension(normalizedPath)) {\n adapter.removeSync(relativeKey);\n } else {\n adapter.clearSync(relativeKey);\n }\n\n const id = this.#ids[normalizedPath];\n if (id && this.#metadata[id]) {\n delete this.#metadata[id];\n delete this.#ids[normalizedPath];\n delete this.#paths[id];\n }\n }\n\n /**\n * Glob files in the virtual file system (VFS) based on the provided pattern(s).\n *\n * @param patterns - A pattern (or multiple patterns) to use to determine the file paths to return\n * @returns An array of file paths matching the provided pattern(s)\n */\n public async glob(\n patterns:\n | string\n | Omit<AssetGlob, \"output\">\n | (string | Omit<AssetGlob, \"output\">)[]\n ): Promise<string[]> {\n const results: string[] = [];\n for (const pattern of normalizeGlobPatterns(\n this.#context.config.cwd,\n patterns\n )) {\n const normalized = this.#normalizePath(pattern);\n if (!/[*?[\\]{}]/.test(normalized) && !normalized.includes(\"*\")) {\n if (this.isDirectorySync(normalized)) {\n results.push(...(await this.list(normalized)));\n } else {\n const resolved = await this.resolve(normalized);\n if (resolved && !results.includes(resolved)) {\n results.push(resolved);\n }\n }\n } else {\n const absPattern = isAbsolutePath(normalized)\n ? normalized\n : this.#normalizePath(\n appendPath(normalized, this.#context.config.cwd)\n );\n\n await Promise.all(\n (await this.list(stripStars(absPattern))).map(async file => {\n if (globToRegex(absPattern).test(file)) {\n const resolved = await this.resolve(file);\n if (resolved && !results.includes(resolved)) {\n results.push(resolved);\n }\n }\n })\n );\n }\n }\n\n return results;\n }\n\n /**\n * Synchronously glob files in the virtual file system (VFS) based on the provided pattern(s).\n *\n * @param patterns - A pattern (or multiple patterns) to use to determine the file paths to return\n * @returns An array of file paths matching the provided pattern(s)\n */\n public globSync(\n patterns:\n | string\n | Omit<AssetGlob, \"output\">\n | (string | Omit<AssetGlob, \"output\">)[]\n ): string[] {\n const results: string[] = [];\n for (const pattern of normalizeGlobPatterns(\n this.#context.config.cwd,\n patterns\n )) {\n const normalized = this.#normalizePath(pattern);\n if (!/[*?[\\]{}]/.test(normalized) && !normalized.includes(\"*\")) {\n if (this.isDirectorySync(normalized)) {\n results.push(...this.listSync(normalized));\n } else {\n const resolved = this.resolveSync(normalized);\n if (resolved && !results.includes(resolved)) {\n results.push(resolved);\n }\n }\n } else {\n const absPattern = isAbsolutePath(normalized)\n ? normalized\n : this.#normalizePath(\n appendPath(normalized, this.#context.config.cwd)\n );\n\n const files = this.listSync(stripStars(absPattern));\n for (const file of files) {\n const regex = globToRegex(absPattern);\n if (regex.test(file)) {\n const resolved = this.resolveSync(file);\n if (resolved && !results.includes(resolved)) {\n results.push(resolved);\n }\n }\n }\n }\n }\n\n return results;\n }\n\n /**\n * Copies a file from one path to another in the virtual file system (VFS).\n *\n * @param srcPath - The source path to copy\n * @param destPath - The destination path to copy to\n */\n public async copy(\n srcPath: string | URL | Omit<AssetGlob, \"output\">,\n destPath: string | URL\n ) {\n const src = srcPath instanceof URL ? fileURLToPath(srcPath) : srcPath;\n const dest = destPath instanceof URL ? fileURLToPath(destPath) : destPath;\n\n if (\n (!isSetString(src) && (!isSetObject(src) || !isSetString(src.input))) ||\n !isSetString(dest)\n ) {\n return;\n }\n\n const sourceStr = isString(src)\n ? src\n : src.input\n ? src.input\n : this.#context.config.cwd;\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.config.cwd;\n const source = this.resolveSync(sourceStr);\n if (!source) {\n return;\n }\n\n if (\n this.isDirectorySync(source) ||\n (isSetString(src) && src.includes(\"*\")) ||\n (isSetObject(src) && isSetString(src.glob))\n ) {\n this.globSync(src).map(file => {\n return this.copySync(\n file,\n appendPath(findFilePath(replacePath(file, sourceStr)), dest)\n );\n });\n } else {\n const content = this.readSync(source);\n if (content !== undefined) {\n this.writeSync(\n this.#normalizePath(\n hasFileExtension(dest)\n ? dest\n : appendPath(findFileName(source), dest)\n ),\n content,\n { skipFormat: true }\n );\n }\n }\n }\n\n /**\n * Moves a file (or files) from one path to another in the virtual file system (VFS).\n *\n * @param srcPath - The source path to move\n * @param destPath - The destination path to move to\n */\n public async move(srcPath: string, destPath: string) {\n if (hasFileExtension(srcPath)) {\n await this.copy(srcPath, destPath);\n await this.remove(srcPath);\n } else {\n await Promise.all(\n (await this.list(srcPath)).map(async file => {\n await this.copy(file, destPath);\n await this.remove(file);\n })\n );\n }\n }\n\n /**\n * Synchronously moves a file (or files) from one path to another in the virtual file system (VFS).\n *\n * @param srcPath - The source path to move\n * @param destPath - The destination path to move to\n */\n public moveSync(srcPath: string, destPath: string) {\n if (hasFileExtension(srcPath)) {\n this.copySync(srcPath, destPath);\n this.removeSync(srcPath);\n } else {\n this.listSync(srcPath).forEach(file => {\n this.copySync(file, destPath);\n this.removeSync(file);\n });\n }\n }\n\n /**\n * Asynchronously reads a file from the virtual file system (VFS).\n *\n * @param path - The path or ID of the file to read.\n * @returns A promise that resolves to the contents of the file as a string, or undefined if the file does not exist.\n */\n public async read(path: string): Promise<string | undefined> {\n const filePath = await this.resolve(path, undefined, { isFile: true });\n if (!filePath || !this.existsSync(filePath)) {\n return undefined;\n }\n\n const { adapter } = this.#getStorage(filePath);\n this.#logger.trace(`Reading ${adapter.name} file: ${filePath}`);\n\n return (await adapter.get(filePath)) ?? undefined;\n }\n\n /**\n * Synchronously reads a file from the virtual file system (VFS).\n *\n * @param path - The path or ID of the file to read.\n * @returns The contents of the file as a string, or undefined if the file does not exist.\n */\n public readSync(path: string): string | undefined {\n const filePath = this.resolveSync(path, undefined, { isFile: true });\n if (!filePath || !this.existsSync(filePath)) {\n return undefined;\n }\n\n const { adapter } = this.#getStorage(filePath);\n this.#logger.trace(`Reading ${adapter.name} file: ${filePath}`);\n\n return adapter.getSync(filePath) ?? undefined;\n }\n\n /**\n * Writes a file to the virtual file system (VFS).\n *\n * @param path - The path to the file.\n * @param data - The contents of the file.\n * @param options - Optional parameters for writing the file.\n * @returns A promise that resolves when the file is written.\n */\n public async write(\n path: string,\n data: string = \"\",\n options: WriteOptions = {}\n ): Promise<void> {\n const meta = options.meta ?? {};\n const resolvedPath =\n (await this.resolve(this.#normalizePath(path))) || path;\n\n const { relativeKey, adapter } = this.#getStorage(\n resolvedPath,\n options.storage as StoragePreset\n );\n\n this.#logger.trace(\n `Writing ${resolvedPath} to ${\n adapter.name === \"virtual\"\n ? \"the virtual file system\"\n : adapter.name === \"file-system\"\n ? \"the local file system\"\n : adapter.name\n } (size: ${prettyBytes(new Blob(toArray(data)).size)})`\n );\n\n let code = data;\n try {\n if (!options.skipFormat) {\n code = await format(this.#context, resolvedPath, data);\n }\n } catch (err) {\n // Only warn about formatting errors for certain file types\n if (\n DEFAULT_EXTENSIONS.includes(\n findFileExtensionSafe(resolvedPath, {\n fullExtension: true\n })\n )\n ) {\n this.#logger.warn(\n `Failed to format file ${resolvedPath} before writing: ${(err as Error).message}`\n );\n }\n code = data;\n }\n\n this.#logger.trace(\n `Writing ${resolvedPath} to ${\n adapter.name === \"virtual\"\n ? \"the virtual file system\"\n : adapter.name === \"file-system\"\n ? \"the local file system\"\n : adapter.name\n } (size: ${prettyBytes(new Blob(toArray(code)).size)})`\n );\n\n const id = this.#normalizeId(meta.id || resolvedPath);\n this.metadata[id] = {\n type: \"normal\",\n timestamp: Date.now(),\n ...(this.metadata[id] ?? {}),\n ...meta\n } as VirtualFileMetadata;\n this.paths[id] = resolvedPath;\n this.ids[resolvedPath] = id;\n\n return adapter.set(relativeKey, code);\n }\n\n /**\n * Synchronously writes a file to the virtual file system (VFS).\n *\n * @param path - The file to write.\n * @param data - The contents of the file.\n * @param options - Optional parameters for writing the file.\n */\n public writeSync(\n path: string,\n data: string = \"\",\n options: WriteOptions = {}\n ): void {\n const meta = options.meta ?? {};\n const resolvedPath = this.resolveSync(this.#normalizePath(path)) || path;\n\n const { relativeKey, adapter } = this.#getStorage(\n resolvedPath,\n options.storage as StoragePreset\n );\n\n this.#logger.trace(\n `Writing ${resolvedPath} file to ${\n adapter.name === \"virtual\"\n ? \"the virtual file system\"\n : adapter.name === \"file-system\"\n ? \"the local file system\"\n : adapter.name\n } (size: ${prettyBytes(new Blob(toArray(data)).size)})`\n );\n\n const id = this.#normalizeId(meta.id || resolvedPath);\n this.metadata[id] = {\n type: \"normal\",\n timestamp: Date.now(),\n ...(this.metadata[id] ?? {}),\n ...meta\n } as VirtualFileMetadata;\n this.paths[id] = resolvedPath;\n this.ids[resolvedPath] = id;\n\n return adapter.setSync(relativeKey, data);\n }\n\n /**\n * Synchronously creates a directory at the specified path.\n *\n * @param dirPath - The path of the directory to create.\n */\n public mkdirSync(dirPath: string) {\n return this.#getStorage(dirPath)?.adapter?.mkdirSync(dirPath);\n }\n\n /**\n * Creates a directory at the specified path.\n *\n * @param path - The path of the directory to create.\n */\n public async mkdir(path: string): Promise<void> {\n return this.#getStorage(path)?.adapter?.mkdir(path);\n }\n\n /**\n * Retrieves the metadata of a file in the virtual file system (VFS).\n *\n * @param pathOrId - The path or ID of the file to retrieve metadata for.\n * @returns The metadata of the file, or undefined if the file does not exist.\n */\n public getMetadata(pathOrId: string): VirtualFileMetadata | undefined {\n const resolved = this.resolveSync(pathOrId);\n if (resolved && this.metadata[resolved]) {\n return this.metadata[resolved];\n }\n\n return undefined;\n }\n\n /**\n * Resolves a given module ID using the configured aliases.\n *\n * @remarks\n * This function can be used to map module IDs to different paths based on the alias configuration.\n *\n * @param id - The module ID to resolve.\n * @returns The resolved module ID - after applying any configured aliases (this will be the same as the input ID if no aliases match).\n */\n public resolveAlias(id: string): string {\n let path = id;\n\n if (this.#context.config.resolve.alias) {\n if (\n Array.isArray(this.#context.config.resolve.alias) &&\n this.#context.config.resolve.alias.length > 0\n ) {\n const found = this.#context.config.resolve.alias.filter(\n alias =>\n (isSetString(alias.find) &&\n (alias.find === path || path.startsWith(`${alias.find}/`))) ||\n (isRegExp(alias.find) && alias.find.test(path))\n );\n if (found.length > 0) {\n const alias = found.reduce((ret, current) => {\n const retLength = isSetString(ret.find)\n ? ret.find.length\n : isRegExp(ret.find)\n ? ret.find.source.length\n : 0;\n const currentLength = isSetString(current.find)\n ? current.find.length\n : isRegExp(current.find)\n ? current.find.source.length\n : 0;\n\n return retLength > currentLength ? ret : current;\n });\n\n if (isSetString(alias.find)) {\n path = path.replace(\n new RegExp(`^${alias.find}`),\n alias.replacement\n );\n } else if (isRegExp(alias.find)) {\n path = path.replace(alias.find, alias.replacement);\n }\n }\n } else if (isSetObject(this.#context.config.resolve.alias)) {\n const found = Object.keys(\n this.#context.config.resolve.alias as Record<string, string>\n ).filter(key => key === path || path.startsWith(`${key}/`));\n if (found.length > 0) {\n const alias = found.reduce((ret, current) => {\n return ret.length > current.length ? ret : current;\n });\n\n path = path.replace(\n new RegExp(`^${alias}`),\n (this.#context.config.resolve.alias as Record<string, string>)[\n alias\n ]!\n );\n }\n }\n }\n\n return path;\n }\n\n /**\n * Checks if a given module ID is an alias.\n *\n * @remarks\n * This function can be used to determine if a module ID matches any configured aliases.\n *\n * @param id - The module ID to check.\n * @returns A boolean indicating whether the module ID is an alias.\n */\n public isAlias(id: string): boolean {\n const path = id;\n\n if (this.#context.config.resolve.alias) {\n if (\n Array.isArray(this.#context.config.resolve.alias) &&\n this.#context.config.resolve.alias.length > 0\n ) {\n return (\n this.#context.config.resolve.alias.filter(\n alias =>\n (isSetString(alias.find) &&\n (alias.find === path || path.startsWith(`${alias.find}/`))) ||\n (isRegExp(alias.find) && alias.find.test(path))\n ).length > 0\n );\n } else if (isSetObject(this.#context.config.resolve.alias)) {\n return (\n Object.keys(\n this.#context.config.resolve.alias as Record<string, string>\n ).filter(key => key === path || path.startsWith(`${key}/`)).length > 0\n );\n }\n }\n\n return false;\n }\n\n /**\n * Checks if a given module ID is a tsconfig path.\n *\n * @remarks\n * This function can be used to determine if a module ID matches any configured tsconfig paths.\n *\n * @param id - The module ID to check.\n * @returns A boolean indicating whether the module ID is a tsconfig path.\n */\n public isTsconfigPath(id: string): boolean {\n return !!(\n this.#context.tsconfig.options.paths &&\n Object.keys(this.#context.tsconfig.options.paths).length > 0 &&\n match(id, this.#context.resolvePatterns)\n );\n }\n\n /**\n * A helper function to resolve modules in the virtual file system (VFS).\n *\n * @remarks\n * This function can be used to resolve modules relative to the project root directory.\n *\n * @example\n * ```ts\n * const resolved = await context.resolvePath(\"some-module\", \"/path/to/importer\");\n * ```\n *\n * @param id - The module to resolve.\n * @param importer - An optional path to the importer module.\n * @param options - Additional resolution options.\n * @returns A promise that resolves to the resolved module path.\n */\n public async resolve(\n id: string,\n importer?: string,\n options: ResolveOptions = {}\n ): Promise<string | undefined> {\n const origResult = await this.#innerResolve(id, importer, options);\n if (origResult && options.isFile && (await this.isDirectory(origResult))) {\n const indexResult = await this.resolve(\n joinPaths(origResult, \"index\"),\n importer,\n options\n );\n if (indexResult) {\n return indexResult;\n }\n\n if (!hasFileExtension(origResult)) {\n for (const ext of DEFAULT_EXTENSIONS) {\n const extResult = await this.resolve(\n `${origResult}.${ext}`,\n importer,\n options\n );\n if (extResult) {\n return extResult;\n }\n }\n }\n\n return undefined;\n }\n\n return origResult;\n }\n\n /**\n * A synchronous helper function to resolve modules using the Jiti resolver\n *\n * @remarks\n * This function can be used to resolve modules relative to the project root directory.\n *\n * @example\n * ```ts\n * const resolvedPath = context.resolveSync(\"some-module\", \"/path/to/importer\");\n * ```\n *\n * @param id - The module to resolve.\n * @param importer - An optional path to the importer module.\n * @param options - Additional resolution options.\n * @returns The resolved module path.\n */\n public resolveSync(\n id: string,\n importer?: string,\n options: ResolveOptions = {}\n ): string | undefined {\n const origResult = this.#innerResolveSync(id, importer, options);\n if (origResult && options.isFile && this.isDirectorySync(origResult)) {\n const indexResult = this.resolveSync(\n joinPaths(origResult, \"index\"),\n importer,\n options\n );\n if (indexResult) {\n return indexResult;\n }\n\n if (!hasFileExtension(origResult)) {\n for (const ext of DEFAULT_EXTENSIONS) {\n const extResult = this.resolveSync(\n `${origResult}.${ext}`,\n importer,\n options\n );\n if (extResult) {\n return extResult;\n }\n }\n }\n\n return undefined;\n }\n\n return origResult;\n }\n\n /**\n * Disposes of the virtual file system (VFS) by saving its state to disk.\n */\n public async dispose() {\n if (!this.#isDisposed) {\n this.#isDisposed = true;\n\n this.#logger.debug(\"Disposing virtual file system...\");\n await this.remove(joinPaths(this.#context.dataPath, \"fs.bin\"));\n\n const message = new capnp.Message();\n const fs = message.initRoot(FileSystem);\n\n const storage = fs._initStorage(Object.keys(this.#paths).length);\n await Promise.all(\n Object.values(this.#paths).map(async (path, index) => {\n const code = await this.read(path);\n\n const fd = storage.get(index);\n fd.path = path;\n fd.code = code || \"\";\n })\n );\n\n const ids = fs._initIds(Object.keys(this.#ids).length);\n Object.entries(this.#ids)\n .filter(([, id]) => id)\n .forEach(([path, id], index) => {\n const fileId = ids.get(index);\n fileId.id = id;\n fileId.path = path;\n });\n\n const metadata = fs._initMetadata(Object.keys(this.#metadata).length);\n Object.entries(this.#metadata)\n .filter(([, value]) => value)\n .forEach(([id, value], index) => {\n const fileMetadata = metadata.get(index);\n fileMetadata.id = id;\n fileMetadata.type = value.type;\n fileMetadata.timestamp = value.timestamp ?? Date.now();\n\n if (value.properties) {\n const props = fileMetadata._initProperties(\n Object.keys(value.properties).length\n );\n Object.entries(value.properties)\n .filter(([, val]) => isSetString(val))\n .forEach(([key, val], index) => {\n const prop = props.get(index);\n prop.key = key;\n prop.value = val!;\n });\n }\n });\n\n await writeFileBuffer(\n joinPaths(this.#context.dataPath, \"fs.bin\"),\n message.toArrayBuffer()\n );\n\n if (!this.#context.config.skipCache) {\n this.resolverCache.save(true);\n }\n\n await Promise.all(\n this.#getStorages().map(async storage => storage.adapter.dispose())\n );\n\n this.#logger.trace(\"Virtual file system has been disposed.\");\n }\n }\n\n /**\n * Asynchronously disposes of the virtual file system (VFS) by saving its state to disk.\n *\n * @remarks\n * This method is automatically called when the VFS instance is used within a `using` block, or can be manually invoked to ensure that the VFS state is saved and resources are cleaned up properly.\n */\n public 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 type {\n Context,\n CopyConfig,\n CopyResolvedConfig,\n EmitEntryOptions,\n EmitOptions,\n ExecutionOptions,\n FetchOptions,\n InitialConfig,\n LogFn,\n LogFnMeta,\n Logger,\n LoggerOptions,\n MetaInfo,\n OutputResolvedConfig,\n ParsedTypeScriptConfig,\n ParseOptions,\n PluginConfig,\n ResolvedAssetGlob,\n ResolvedConfig,\n ResolvedEntryTypeDefinition,\n ResolveOptions,\n ResolveResult,\n TransformResult,\n VirtualFile,\n VirtualFileSystemInterface\n} from \"@powerlines/core\";\nimport { LogLevelResolvedConfig } from \"@powerlines/core\";\nimport {\n CACHE_HASH_LENGTH,\n DEFAULT_DEVELOPMENT_LOG_LEVEL,\n DEFAULT_PRODUCTION_LOG_LEVEL,\n DEFAULT_TEST_LOG_LEVEL,\n ROOT_HASH_LENGTH\n} from \"@powerlines/core/constants\";\nimport {\n getUniqueInputs,\n isTypeDefinition,\n resolveInputsSync\n} from \"@powerlines/core/lib/entry\";\nimport {\n createLogger,\n isDuplicate,\n isPlugin,\n mergeConfig,\n replacePathTokens,\n resolveLogLevel,\n withCustomLogger,\n withLogFn\n} from \"@powerlines/core/plugin-utils\";\nimport { Unstable_ContextInternal } from \"@powerlines/core/types/_internal\";\nimport { formatLogMessage } from \"@storm-software/config-tools/logger/console\";\nimport { toArray } from \"@stryke/convert/to-array\";\nimport { toBool } from \"@stryke/convert/to-bool\";\nimport { EnvPaths, getEnvPaths } from \"@stryke/env/get-env-paths\";\nimport { existsSync } from \"@stryke/fs/exists\";\nimport { relativeToWorkspaceRoot } from \"@stryke/fs/get-workspace-root\";\nimport { readJsonFile } from \"@stryke/fs/json\";\nimport { resolvePackage } from \"@stryke/fs/resolve\";\nimport { murmurhash } from \"@stryke/hash\";\nimport { hashDirectory } from \"@stryke/hash/node\";\nimport { deepClone } from \"@stryke/helpers/deep-clone\";\nimport { getUnique, getUniqueBy } from \"@stryke/helpers/get-unique\";\nimport { omit } from \"@stryke/helpers/omit\";\nimport { fetchRequest } from \"@stryke/http/fetch\";\nimport { appendPath } from \"@stryke/path/append\";\nimport {\n findFileDotExtensionSafe,\n findFileExtensionSafe\n} from \"@stryke/path/file-path-fns\";\nimport { isEqual } from \"@stryke/path/is-equal\";\nimport { isParentPath } from \"@stryke/path/is-parent-path\";\nimport { joinPaths } from \"@stryke/path/join\";\nimport { replacePath } from \"@stryke/path/replace\";\nimport { kebabCase } from \"@stryke/string-format/kebab-case\";\nimport { titleCase } from \"@stryke/string-format/title-case\";\nimport { isFunction } from \"@stryke/type-checks/is-function\";\nimport { isObject } from \"@stryke/type-checks/is-object\";\nimport { isSetObject } from \"@stryke/type-checks/is-set-object\";\nimport { isSetString } from \"@stryke/type-checks/is-set-string\";\nimport { isString } from \"@stryke/type-checks/is-string\";\nimport { TypeDefinition } from \"@stryke/types/configuration\";\nimport { PackageJson } from \"@stryke/types/package-json\";\nimport { uuid } from \"@stryke/unique-id/uuid\";\nimport { match, tsconfigPathsToRegExp } from \"bundle-require\";\nimport { resolveCompatibilityDates } from \"compatx\";\nimport defu from \"defu\";\nimport { create, FlatCache } from \"flat-cache\";\nimport { parse, ParseResult } from \"oxc-parser\";\nimport { Range } from \"semver\";\nimport {\n Agent,\n BodyInit,\n interceptors,\n RequestInfo,\n Response,\n setGlobalDispatcher\n} from \"undici\";\nimport { UnpluginBuildContext } from \"unplugin\";\nimport { getConfigProps } from \"../_internal/helpers/context\";\nimport { getPrefixedRootHash } from \"../_internal/helpers/meta\";\nimport { sendWriteLogMessage } from \"../_internal/ipc/send\";\nimport { VirtualFileSystem } from \"../_internal/vfs\";\nimport { getTsconfigFilePath } from \"../typescript/tsconfig\";\nimport { PowerlinesBaseContext } from \"./base-context\";\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\nconst SKIP_CLONING_PROPS = [\n \"dependencies\",\n \"devDependencies\",\n \"persistedMeta\",\n \"packageJson\",\n \"projectJson\",\n \"tsconfig\",\n \"resolver\",\n \"fs\",\n \"$$internal\"\n];\n\nexport class PowerlinesContext<\n TResolvedConfig extends ResolvedConfig = ResolvedConfig\n>\n extends PowerlinesBaseContext\n implements Context<TResolvedConfig>\n{\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 Unstable_ContextInternal<TResolvedConfig>;\n\n #checksum: string | null = null;\n\n #buildId: string = uuid();\n\n #releaseId: string = uuid();\n\n #fs!: VirtualFileSystemInterface;\n\n #tsconfig!: ParsedTypeScriptConfig;\n\n #parserCache!: FlatCache;\n\n #requestCache!: FlatCache;\n\n /**\n * Create a new Storm context from the workspace root and user config.\n *\n * @param options - The options for resolving the context.\n * @returns A promise that resolves to the new context.\n */\n public static async init<\n TResolvedConfig extends ResolvedConfig = ResolvedConfig\n >(\n options: ExecutionOptions,\n initialConfig: InitialConfig<any>\n ): Promise<Context<TResolvedConfig>> {\n const context = new PowerlinesContext<TResolvedConfig>(options);\n await context.init(options, initialConfig);\n\n const powerlinesPath = await resolvePackage(\"powerlines\");\n if (!powerlinesPath) {\n throw new Error(\"Could not resolve `powerlines` package location.\");\n }\n context.powerlinesPath = powerlinesPath;\n\n return context;\n }\n\n /**\n * The options provided to the Powerlines process\n */\n public override options: ExecutionOptions;\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 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 resolved tsconfig file paths for the project\n */\n public 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(): Unstable_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: Unstable_ContextInternal<TResolvedConfig>) {\n this.#internal = value;\n }\n\n /**\n * The resolved entry type definitions for the project\n */\n public get entry(): ResolvedEntryTypeDefinition[] {\n const entry = this.resolvedEntry;\n\n return resolveInputsSync(\n this,\n entry && entry.length > 0\n ? entry\n : Array.isArray(this.config.input) ||\n (isSetObject(this.config.input) &&\n !isTypeDefinition(this.config.input))\n ? this.config.input\n : toArray(this.config.input).flat()\n );\n }\n\n /**\n * The TypeScript configuration parsed from the tsconfig file\n */\n public get tsconfig(): ParsedTypeScriptConfig {\n if (!this.#tsconfig) {\n this.tsconfig = {\n tsconfigFilePath: this.config.tsconfig\n } as ParsedTypeScriptConfig;\n }\n\n return this.#tsconfig;\n }\n\n /**\n * Sets the TypeScript configuration parsed from the tsconfig file\n */\n public set tsconfig(value: ParsedTypeScriptConfig) {\n this.#tsconfig = value;\n this.resolvePatterns = tsconfigPathsToRegExp(value?.options?.paths ?? {});\n }\n\n /**\n * The virtual file system interface for the project\n */\n public get fs(): VirtualFileSystemInterface {\n if (!this.#fs) {\n this.#fs = VirtualFileSystem.createSync(this);\n }\n\n return this.#fs;\n }\n\n /**\n * Get the checksum of the project's current state\n */\n public get checksum(): string | null {\n return this.#checksum;\n }\n\n /**\n * The meta information about the current build\n */\n public get meta() {\n return {\n buildId: this.#buildId,\n releaseId: this.#releaseId,\n checksum: this.#checksum,\n timestamp: this.timestamp,\n rootHash: murmurhash(\n {\n workspaceRoot: this.options?.cwd,\n root: this.config?.root\n },\n {\n maxLength: ROOT_HASH_LENGTH\n }\n ),\n configHash: murmurhash(this.config, {\n maxLength: CACHE_HASH_LENGTH\n })\n } as MetaInfo;\n }\n\n /**\n * The resolved configuration options\n */\n public get config(): TResolvedConfig {\n return this.resolvedConfig;\n }\n\n /**\n * Get the path to the artifacts directory for the project\n */\n public get artifactsPath(): string {\n return joinPaths(\n this.config.cwd,\n this.config.root,\n this.config.output.artifactsPath\n );\n }\n\n /**\n * Get the path to the builtin modules used by the project\n */\n public get builtinsPath(): string {\n return joinPaths(this.artifactsPath, \"builtins\");\n }\n\n /**\n * Get the path to the entry directory for the project\n */\n public get entryPath(): string {\n return joinPaths(this.artifactsPath, \"entry\");\n }\n\n /**\n * Get the path to the infrastructure modules used by the project\n */\n public get infrastructurePath(): string {\n return joinPaths(this.artifactsPath, \"infrastructure\");\n }\n\n /**\n * Get the path to the data directory for the project\n */\n public get dataPath(): string {\n return joinPaths(\n this.envPaths.data,\n \"projects\",\n getPrefixedRootHash(this.config.name, this.meta.rootHash)\n );\n }\n\n /**\n * Get the path to the cache directory for the project\n */\n public get cachePath(): string {\n return joinPaths(\n this.envPaths.cache,\n \"projects\",\n murmurhash(\n {\n checksum: this.#checksum,\n config: this.meta.configHash\n },\n {\n maxLength: CACHE_HASH_LENGTH\n }\n )\n );\n }\n\n /**\n * Get the path to the generated declaration file for the project\n */\n public get typesPath(): string {\n return this.config.output.types\n ? appendPath(this.config.output.types, this.config.cwd)\n : joinPaths(this.config.cwd, this.config.root, \"powerlines.d.ts\");\n }\n\n /**\n * Get the project root relative to the workspace root\n */\n public get relativeToWorkspaceRoot() {\n return relativeToWorkspaceRoot(this.config.root);\n }\n\n /**\n * The builtin module id that exist in the Powerlines virtual file system\n */\n public get builtins(): string[] {\n return Object.values(this.fs.metadata)\n .filter(meta => meta && meta.type === \"builtin\")\n .map(meta => meta?.id)\n .filter(Boolean);\n }\n\n /**\n * Additional arguments provided during execution of the command, such as CLI flags or other parameters that may be relevant to the command being executed.\n */\n public get additionalArgs(): Record<string, string | string[]> {\n return Object.entries(\n this.config.inlineConfig?.additionalArgs ?? {}\n ).reduce(\n (ret, [key, value]) => {\n const formattedKey = key.replace(/^--?/, \"\");\n\n if (ret[formattedKey]) {\n if (Array.isArray(ret[formattedKey])) {\n if (Array.isArray(value)) {\n ret[formattedKey] = [...toArray(ret[formattedKey]), ...value];\n } else {\n ret[formattedKey] = [...toArray(ret[formattedKey]), value];\n }\n } else {\n ret[formattedKey] = [\n ret[formattedKey],\n ...(Array.isArray(value) ? value : [value])\n ];\n }\n } else {\n ret[formattedKey] = value;\n }\n return ret;\n },\n {} as Record<string, string | string[]>\n );\n }\n\n /**\n * The alias mappings for the project used during module resolution\n *\n * @remarks\n * This includes both the built-in module aliases as well as any custom aliases defined in the build configuration.\n */\n public get alias(): Record<string, string> {\n return this.builtins.reduce(\n (ret, id) => {\n const moduleId = `${\n this.config?.framework || \"powerlines\"\n }:${id.replace(/^.*:/, \"\")}`;\n if (!ret[moduleId]) {\n const path = this.fs.paths[id];\n if (path) {\n ret[moduleId] = path;\n }\n }\n\n return ret;\n },\n this.config.resolve.alias\n ? Array.isArray(this.config.resolve.alias)\n ? this.config.resolve.alias.reduce(\n (ret, alias) => {\n if (!ret[alias.find.toString()]) {\n ret[alias.find.toString()] = alias.replacement;\n }\n\n return ret;\n },\n {} as Record<string, string>\n )\n : this.config.resolve.alias\n : {}\n );\n }\n\n /**\n * Create a new logger instance\n *\n * @param options - The configuration options to use for the logger instance, which can be used to customize the appearance and behavior of the log messages generated by the logger. This is typically the name of the plugin or module that is creating the logger instance.\n * @param logFn - The custom logging function to use for logging messages, which can be used to override the default logging behavior of the original logger.\n * @returns A logger client instance that can be used to generate log messages with consistent formatting and metadata.\n */\n public override createLogger(options: LoggerOptions, logFn?: LogFn): Logger {\n let logger!: Logger;\n if (toBool(process.env.POWERLINES_WORKER_THREAD_EXECUTION)) {\n logger = createLogger(\n this.config.name,\n { ...this.options, ...this.config, ...options },\n (meta: LogFnMeta, message: string) =>\n sendWriteLogMessage(this, meta, message)\n );\n } else {\n logger = createLogger(this.config.name, {\n ...this.options,\n ...this.config,\n ...options\n });\n }\n\n if (this.config.customLogger) {\n logger = withCustomLogger(logger, this.config.customLogger);\n }\n\n if (logFn) {\n logger = withLogFn(logger, logFn);\n }\n\n return logger;\n }\n\n /**\n * The log level for the context, which determines the minimum level of log messages that will be emitted by the logger. This is resolved based on the configuration options provided by the user, and can be set to different levels for development, production, and test environments. The log level can also be overridden by plugins or other parts of the build process to provide more granular control over logging output.\n */\n public override get logLevel(): LogLevelResolvedConfig {\n return resolveLogLevel(this.config.logLevel, this.config.mode);\n }\n\n /**\n * The environment paths for the project, which provide the locations of various directories and files used by the Powerlines framework. These paths are resolved based on the organization ID, application ID, and workspace root directory, and can be used to access configuration files, cache directories, and other resources in a consistent manner.\n */\n public override get envPaths(): EnvPaths {\n return getEnvPaths({\n orgId: this.config.organization,\n appId: this.config.framework || \"powerlines\",\n workspaceRoot: this.config.cwd\n });\n }\n\n /**\n * Gets the parser cache.\n */\n protected get parserCache(): FlatCache {\n if (!this.#parserCache) {\n this.#parserCache = create({\n cacheId: \"parser\",\n cacheDir: this.cachePath,\n ttl: 2 * 60 * 60 * 1000,\n lruSize: 5000,\n persistInterval: 250\n });\n }\n\n return this.#parserCache;\n }\n\n /**\n * Gets the request cache.\n */\n protected get requestCache(): FlatCache {\n if (!this.#requestCache) {\n this.#requestCache = create({\n cacheId: \"http\",\n cacheDir: this.cachePath,\n ttl: 6 * 60 * 60 * 1000,\n lruSize: 5000,\n persistInterval: 250\n });\n }\n\n return this.#requestCache;\n }\n\n /**\n * The entry points that exist in the Powerlines virtual file system\n */\n protected get resolvedEntry(): ResolvedEntryTypeDefinition[] {\n return Object.entries(this.fs.metadata)\n .filter(([, meta]) => meta && meta.type === \"entry\")\n .map(([path, meta]) => {\n const typeDefinition = {\n file: path\n } as ResolvedEntryTypeDefinition;\n\n if (meta.properties) {\n if (isSetString(meta.properties.file)) {\n typeDefinition.file = meta.properties.file;\n }\n if (isSetString(meta.properties.name)) {\n typeDefinition.name = meta.properties.name;\n }\n if (\n isSetString(meta.properties[\"input.file\"]) ||\n isSetString(meta.properties[\"input.name\"])\n ) {\n typeDefinition.input ??= {} as TypeDefinition;\n if (isSetString(meta.properties[\"input.file\"])) {\n typeDefinition.input.file = meta.properties[\"input.file\"];\n }\n if (isSetString(meta.properties[\"input.name\"])) {\n typeDefinition.input.name = meta.properties[\"input.name\"];\n }\n }\n if (isSetString(meta.properties.output)) {\n typeDefinition.output = meta.properties.output;\n }\n }\n\n return typeDefinition;\n })\n .filter(Boolean);\n }\n\n /**\n * Creates a new StormContext instance.\n *\n * @param options - The options to use for creating the context, including the resolved configuration and workspace settings.\n */\n protected constructor(options: ExecutionOptions) {\n super();\n this.options = options;\n }\n\n /**\n * Creates a clone of the current context with the same configuration and workspace settings. This can be useful for running multiple builds in parallel or for creating isolated contexts for different parts of the build process.\n *\n * @remarks\n * The cloned context will have the same configuration and workspace settings as the original context, but will have a different build ID, release ID, and timestamp. The virtual file system and caches will also be separate between the original and cloned contexts.\n *\n * @returns A promise that resolves to the cloned context.\n */\n public override async clone(): Promise<Context<TResolvedConfig>> {\n const clone = await PowerlinesContext.init<TResolvedConfig>(\n this.options,\n this.initialConfig\n );\n\n return this.copyTo(clone);\n }\n\n /**\n * A function to perform HTTP fetch requests\n *\n * @remarks\n * This function uses a caching layer to avoid duplicate requests during the Powerlines process.\n *\n * @example\n * ```ts\n * const response = await context.fetch(\"https://api.example.com/data\");\n * const data = await response.json();\n * ```\n *\n * @see https://github.com/nodejs/undici\n *\n * @param input - The URL to fetch.\n * @param options - The fetch request options.\n * @returns A promise that resolves to a response returned by the fetch.\n */\n public async fetch(\n input: RequestInfo,\n options: FetchOptions = {}\n ): Promise<Response> {\n const cacheKey = murmurhash({\n input: input.toString(),\n options: JSON.stringify(options)\n });\n\n if (!this.config.skipCache && !options.skipCache) {\n const cached = this.requestCache.get<\n {\n body: BodyInit;\n } & Pick<Response, \"status\" | \"statusText\" | \"headers\">\n >(cacheKey);\n if (cached) {\n return new Response(cached.body, {\n status: cached.status,\n statusText: cached.statusText,\n headers: cached.headers\n });\n }\n }\n\n const logger = this.extendLogger({ category: \"network\" });\n const startTime = Date.now();\n\n logger.trace(\n `Sending fetch request (${\n options.method?.toUpperCase() || \"GET\"\n }): ${input.toString()}`\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 logger.trace(\n `Fetch request (${\n options.method?.toUpperCase() || \"GET\"\n }) completed in ${Date.now() - startTime}ms: ${input.toString()} - ${\n response.status\n } / ${response.statusText} \\n - Response Headers: ${JSON.stringify(\n result.headers\n )}\\n - Response Body: ${\n typeof result.body === \"string\"\n ? result.body.length > 1000\n ? `${result.body.slice(0, 1000)}... (truncated, total length: ${\n result.body.length\n })`\n : result.body\n : \"[Non-string body]\"\n }`\n );\n\n return new Response(result.body, {\n status: result.status,\n statusText: result.statusText,\n headers: result.headers\n });\n }\n\n /**\n * Parse code using [Oxc-Parser](https://github.com/oxc/oxc) into an (ESTree-compatible)[https://github.com/estree/estree] AST object.\n *\n * @remarks\n * This function can be used to parse TypeScript code into an AST for further analysis or transformation.\n *\n * @example\n * ```ts\n * const ast = context.parse(\"const x: number = 42;\");\n * ```\n *\n * @see https://rollupjs.org/plugin-development/#this-parse\n * @see https://github.com/oxc/oxc\n *\n * @param code - The source code to parse.\n * @param options - The options to pass to the parser.\n * @returns An (ESTree-compatible)[https://github.com/estree/estree] AST object.\n */\n public async parse(code: string, options: ParseOptions = {}) {\n const cacheKey = murmurhash({\n code,\n options\n });\n\n let result!: ParseResult;\n if (!this.config.skipCache) {\n result = this.parserCache.get<ParseResult>(cacheKey);\n if (result) {\n return result;\n }\n }\n\n result = await parse(`source.${options.lang || \"ts\"}`, code, {\n ...options,\n sourceType: \"module\",\n showSemanticErrors: this.config.mode === \"development\"\n });\n\n if (!this.config.skipCache) {\n this.parserCache.set(cacheKey, result);\n }\n\n return result;\n }\n\n /**\n * A helper function to resolve modules in the Virtual File System\n *\n * @remarks\n * This function can be used to resolve modules relative to the project root directory.\n *\n * @example\n * ```ts\n * const resolved = await context.resolve(\"some-module\", \"/path/to/importer\");\n * ```\n *\n * @param id - The module to resolve.\n * @param importer - An optional path to the importer module.\n * @param options - Additional resolution options.\n * @returns A promise that resolves to the resolved module path.\n */\n public async resolve(\n id: string,\n importer?: string,\n options: ResolveOptions = {}\n ): Promise<ResolveResult | undefined> {\n let moduleId = id;\n if (this.config.resolve.alias) {\n if (Array.isArray(this.config.resolve.alias)) {\n const alias = this.config.resolve.alias.find(a =>\n match(moduleId, [a.find])\n );\n if (alias) {\n moduleId = alias.replacement;\n }\n } else if (\n isSetObject(this.config.resolve.alias) &&\n this.config.resolve.alias[id]\n ) {\n moduleId = this.config.resolve.alias[id];\n }\n }\n\n if (\n this.fs.isResolvableId(moduleId) ||\n (importer && this.fs.isResolvableId(importer))\n ) {\n let resolvedImporter = importer;\n if (importer && this.fs.isResolvableId(importer)) {\n resolvedImporter = await this.fs.resolve(\n importer,\n undefined,\n defu(\n {\n conditions: this.config.resolve.conditions,\n extensions: this.config.resolve.extensions\n },\n options\n )\n );\n }\n\n const result = await this.fs.resolve(\n moduleId,\n resolvedImporter,\n defu(\n {\n conditions: this.config.resolve.conditions,\n extensions: this.config.resolve.extensions\n },\n options\n )\n );\n if (!result) {\n return undefined;\n }\n\n const external = Boolean(\n !match(moduleId, this.config.resolve.noExternal) &&\n (match(moduleId, this.config.resolve.external) ||\n moduleId.startsWith(\"node:\") ||\n ((!this.fs.isVirtual(moduleId, importer, options) ||\n (this.fs.isVirtual(moduleId, importer, options) &&\n this.config.projectType !== \"application\")) &&\n this.config.resolve.skipNodeModulesBundle &&\n !/^[A-Z]:[/\\\\]|^\\.{0,2}\\/|^\\.{1,2}$/.test(moduleId)))\n );\n\n return {\n id: result,\n external,\n virtual: !external\n };\n }\n\n if (this.config.resolve.skipNodeModulesBundle) {\n if (\n match(moduleId, this.resolvePatterns) ||\n match(moduleId, this.config.resolve.noExternal)\n ) {\n return undefined;\n }\n\n if (\n match(moduleId, this.config.resolve.external) ||\n moduleId.startsWith(\"node:\")\n ) {\n return { id: moduleId, external: true, virtual: false };\n }\n\n // Exclude any other import that looks like a Node module\n if (!/^[A-Z]:[/\\\\]|^\\.{0,2}\\/|^\\.{1,2}$/.test(moduleId)) {\n return {\n id: moduleId,\n external: true,\n virtual: false\n };\n }\n } else {\n if (match(moduleId, this.config.resolve.noExternal)) {\n return undefined;\n }\n\n if (\n match(moduleId, this.config.resolve.external) ||\n moduleId.startsWith(\"node:\")\n ) {\n return { id: moduleId, external: true, virtual: false };\n }\n }\n\n return undefined;\n }\n\n /**\n * A helper function to load modules from the Virtual File System\n *\n * @remarks\n * This function can be used to load modules relative to the project root directory.\n *\n * @example\n * ```ts\n * const module = await context.load(\"some-module\", \"/path/to/importer\");\n * ```\n *\n * @param id - The module to load.\n * @returns A promise that resolves to the loaded module.\n */\n public async load(id: string): Promise<TransformResult | undefined> {\n const resolvedId = await this.fs.resolve(id);\n if (!resolvedId) {\n return undefined;\n }\n\n const code = await this.fs.read(resolvedId);\n if (!code) {\n return undefined;\n }\n\n return { code, map: null };\n }\n\n /**\n * Get the builtin virtual files that exist in the Powerlines virtual file system\n */\n public async getBuiltins() {\n return Promise.all(\n Object.entries(this.fs.metadata)\n .filter(([, meta]) => meta && meta.type === \"builtin\")\n .map(async ([id, meta]) => {\n const code = await this.fs.read(id);\n const path = this.fs.paths[id];\n\n return { ...meta, path, code } as VirtualFile;\n })\n );\n }\n\n /**\n * Resolves a file and writes it to the VFS if it does not already exist\n *\n * @param code - The source code of the file\n * @param path - The path to write the file to\n * @param options - Additional options for writing the file\n */\n public async emit(\n code: string,\n path: string,\n options: EmitOptions = {}\n ): Promise<void> {\n const filePath = options.extension\n ? findFileExtensionSafe(path)\n ? options.extension.startsWith(\".\")\n ? path.replace(findFileDotExtensionSafe(path), options.extension)\n : path.replace(findFileExtensionSafe(path), options.extension)\n : options.extension.startsWith(\".\")\n ? `${path}${options.extension}`\n : `${path}.${options.extension}`\n : findFileExtensionSafe(path)\n ? path\n : `${path}.ts`;\n\n if (\n isFunction((this as unknown as UnpluginBuildContext).emitFile) &&\n options.emitWithBundler\n ) {\n return (this as unknown as UnpluginBuildContext).emitFile({\n needsCodeReference: options.needsCodeReference,\n originalFileName: options.originalFileName,\n fileName: filePath,\n source: code,\n type: \"asset\"\n });\n }\n\n return this.fs.write(filePath, code, options);\n }\n\n /**\n * Synchronously resolves a file and writes it to the VFS if it does not already exist\n *\n * @param code - The source code of the file\n * @param path - The path to write the file to\n * @param options - Additional options for writing the file\n */\n public emitSync(code: string, path: string, options: EmitOptions = {}) {\n const filePath = options.extension\n ? findFileExtensionSafe(path)\n ? options.extension.startsWith(\".\")\n ? path.replace(findFileDotExtensionSafe(path), options.extension)\n : path.replace(findFileExtensionSafe(path), options.extension)\n : options.extension.startsWith(\".\")\n ? `${path}${options.extension}`\n : `${path}.${options.extension}`\n : findFileExtensionSafe(path)\n ? path\n : `${path}.ts`;\n\n if (\n isFunction((this as unknown as UnpluginBuildContext).emitFile) &&\n options.emitWithBundler\n ) {\n return (this as unknown as UnpluginBuildContext).emitFile({\n needsCodeReference: options.needsCodeReference,\n originalFileName: options.originalFileName,\n fileName: filePath,\n source: code,\n type: \"asset\"\n });\n }\n\n return this.fs.writeSync(filePath, code, options);\n }\n\n /**\n * Resolves a entry virtual file and writes it to the VFS if it does not already exist\n *\n * @param code - The source code of the entry file\n * @param path - A path to write the entry file to\n * @param options - Optional write file options\n */\n public async emitEntry(\n code: string,\n path: string,\n options: EmitEntryOptions = {}\n ): Promise<void> {\n return this.emit(\n code,\n appendPath(path, this.entryPath),\n defu(\n {\n meta: {\n type: \"entry\",\n properties: {\n file: appendPath(path, this.entryPath),\n name: options?.name,\n output: options?.output,\n \"input.file\": options?.input?.file,\n \"input.name\": options?.input?.name\n }\n }\n },\n omit(options, [\"name\"])\n )\n );\n }\n\n /**\n * Synchronously resolves a entry virtual file and writes it to the VFS if it does not already exist\n *\n * @param code - The source code of the entry file\n * @param path - A path to write the entry file to\n * @param options - Optional write file options\n */\n public emitEntrySync(\n code: string,\n path: string,\n options: EmitEntryOptions = {}\n ): void {\n return this.emitSync(\n code,\n appendPath(path, this.entryPath),\n defu(\n {\n meta: {\n type: \"entry\",\n properties: {\n file: appendPath(path, this.entryPath),\n name: options?.name,\n output: options?.output,\n \"input.file\": options?.input?.file,\n \"input.name\": options?.input?.name\n }\n }\n },\n omit(options, [\"name\"])\n )\n );\n }\n\n /**\n * Resolves a builtin virtual file and writes it to the VFS if it does not already exist\n *\n * @param code - The source code of the builtin file\n * @param id - The unique identifier of the builtin file\n * @param options - Optional write file options\n */\n public async emitBuiltin(\n code: string,\n id: string,\n options: EmitOptions = {}\n ): Promise<void> {\n if (!this.builtinsPath) {\n throw new Error(\n `The builtins path is not set. Cannot emit builtin file with id \"${id}\".`\n );\n }\n\n if (!isSetString(id)) {\n throw new Error(\n `The builtin id must be a non-empty string. Received: ${String(id)}`\n );\n }\n\n return this.emit(\n code,\n appendPath(id, this.builtinsPath),\n defu(options, { meta: { type: \"builtin\", id } })\n );\n }\n\n /**\n * Synchronously resolves a builtin virtual file and writes it to the VFS if it does not already exist\n *\n * @param code - The source code of the builtin file\n * @param id - The unique identifier of the builtin file\n * @param options - Optional write file options\n */\n public emitBuiltinSync(code: string, id: string, options: EmitOptions = {}) {\n if (!this.builtinsPath) {\n throw new Error(\n `The builtins path is not set. Cannot emit builtin file with id \"${id}\".`\n );\n }\n\n if (!isSetString(id)) {\n throw new Error(\n `The builtin id must be a non-empty string. Received: ${String(id)}`\n );\n }\n\n return this.emitSync(\n code,\n appendPath(id, this.builtinsPath),\n defu(options, { meta: { type: \"builtin\", id } })\n );\n }\n\n /**\n * Resolves a builtin virtual file and writes it to the VFS if it does not already exist\n *\n * @param code - The source code of the builtin file\n * @param id - The unique identifier of the builtin file\n * @param options - Optional write file options\n */\n public async emitInfrastructure(\n code: string,\n id: string,\n options: EmitOptions = {}\n ): Promise<void> {\n if (!this.infrastructurePath) {\n throw new Error(\n `The infrastructure path is not set. Cannot emit infrastructure file with id \"${id}\".`\n );\n }\n\n if (!isSetString(id)) {\n throw new Error(\n `The infrastructure id must be a non-empty string. Received: ${String(id)}`\n );\n }\n\n return this.emit(\n code,\n appendPath(id, this.infrastructurePath),\n defu(options, { meta: { type: \"infrastructure\", id } })\n );\n }\n\n /**\n * Synchronously resolves an infrastructure virtual file and writes it to the VFS if it does not already exist\n *\n * @param code - The source code of the infrastructure file\n * @param id - The unique identifier of the infrastructure file\n * @param options - Optional write file options\n */\n public emitInfrastructureSync(\n code: string,\n id: string,\n options: EmitOptions = {}\n ) {\n if (!this.infrastructurePath) {\n throw new Error(\n `The infrastructure path is not set. Cannot emit infrastructure file with id \"${id}\".`\n );\n }\n\n if (!isSetString(id)) {\n throw new Error(\n `The infrastructure id must be a non-empty string. Received: ${String(id)}`\n );\n }\n\n return this.emitSync(\n code,\n appendPath(id, this.infrastructurePath),\n defu(options, { meta: { type: \"infrastructure\", id } })\n );\n }\n\n /**\n * Generates a checksum representing the current context state\n *\n * @param root - The root directory of the project to generate the checksum for\n * @returns A promise that resolves to a string representing the checksum\n */\n public async generateChecksum(root = this.config.root): Promise<string> {\n this.#checksum = await hashDirectory(root, {\n ignore: [\"node_modules\", \".git\", \".nx\", \".cache\", \"tmp\", \"dist\"]\n });\n\n return this.#checksum;\n }\n\n /**\n * Initialize the context with the provided configuration options\n */\n public async setup(): Promise<void> {\n this.resolvedConfig = mergeConfig(\n {\n root: this.options.root,\n cwd: this.options.cwd,\n inlineConfig: this.config.inlineConfig ?? {},\n userConfig: this.config.userConfig ?? {},\n initialConfig: this.config.initialConfig ?? {},\n pluginConfig: this.config.pluginConfig ?? {}\n },\n getConfigProps(this.config.inlineConfig),\n getConfigProps(this.config.userConfig),\n getConfigProps(this.config.initialConfig),\n getConfigProps(this.config.pluginConfig),\n this.options,\n {\n name: this.projectJson?.name || this.packageJson?.name,\n version: this.packageJson?.version,\n description: this.packageJson?.description\n },\n {\n environments: {},\n resolve: {}\n }\n ) as TResolvedConfig;\n\n await this.innerSetup();\n }\n\n /**\n * The resolved configuration for this context\n */\n protected resolvedConfig: TResolvedConfig = {} as TResolvedConfig;\n\n /**\n * Creates a clone of the current context with the same configuration and workspace settings. This can be useful for running multiple builds in parallel or for creating isolated contexts for different parts of the build process.\n *\n * @remarks\n * The cloned context will have the same configuration and workspace settings as the original context, but will have a different build ID, release ID, and timestamp. The virtual file system and caches will also be separate between the original and cloned contexts.\n *\n * @returns The cloned context.\n */\n protected copyTo(\n context: Context<TResolvedConfig>\n ): Context<TResolvedConfig> {\n for (const [key, value] of Object.entries(this)) {\n if (!SKIP_CLONING_PROPS.includes(key)) {\n if (isObject(value) || Array.isArray(value)) {\n (context as any)[key] = deepClone(value);\n } else {\n (context as any)[key] = value;\n }\n }\n }\n\n context.initialConfig = deepClone<typeof this.initialConfig>(\n this.initialConfig\n );\n context.initialOptions = deepClone<typeof this.initialOptions>(\n this.initialOptions\n );\n context.options = deepClone<typeof this.options>(this.options);\n\n context.dependencies = deepClone<typeof this.dependencies>(\n this.dependencies\n );\n context.devDependencies = deepClone<typeof this.devDependencies>(\n this.devDependencies\n );\n context.persistedMeta = this.persistedMeta\n ? deepClone<typeof this.persistedMeta>(this.persistedMeta)\n : undefined;\n context.packageJson = deepClone<typeof this.packageJson>(this.packageJson);\n context.projectJson = this.projectJson\n ? deepClone<typeof this.projectJson>(this.projectJson)\n : undefined;\n context.tsconfig ??= deepClone<typeof this.tsconfig>(\n this.tsconfig\n ) as ParsedTypeScriptConfig;\n\n context.resolver ??= this.resolver;\n context.fs ??= this.#fs;\n\n (context as PowerlinesContext<TResolvedConfig>).$$internal =\n this.$$internal;\n\n return context;\n }\n\n /**\n * Initialize the context with the provided configuration options\n *\n * @remarks\n * This method will set up the resolver and load the user configuration file based on the provided options. It is called during the construction of the context and can also be called when cloning the context to ensure that the new context has the same configuration and resolver setup.\n *\n * @param options - The configuration options to initialize the context with\n */\n protected override async init(\n options: ExecutionOptions,\n initialConfig?: InitialConfig<any>\n ) {\n await super.init(options, initialConfig ?? {});\n\n this.options.executionId = options.executionId ?? this.options.executionId;\n this.options.executionIndex =\n options.executionIndex ?? this.options.executionIndex ?? 0;\n\n const projectJsonPath = joinPaths(\n this.options.cwd,\n this.options.root,\n \"project.json\"\n );\n if (existsSync(projectJsonPath)) {\n this.projectJson = await readJsonFile(projectJsonPath);\n }\n\n const packageJsonPath = joinPaths(\n this.options.cwd,\n this.options.root,\n \"package.json\"\n );\n if (existsSync(packageJsonPath)) {\n this.packageJson = await readJsonFile<PackageJson>(packageJsonPath);\n this.options.organization ??= isSetObject(this.packageJson?.author)\n ? kebabCase(this.packageJson?.author?.name)\n : kebabCase(this.packageJson?.author);\n }\n\n this.#checksum = await this.generateChecksum(\n joinPaths(this.options.cwd, this.options.root)\n );\n\n const userConfig = this.configFile.config\n ? Array.isArray(this.configFile.config) &&\n this.configFile.config.length > this.options.executionIndex\n ? this.configFile.config[this.options.executionIndex]!\n : this.configFile.config\n : {};\n\n this.resolvedConfig = {\n cwd: this.options.cwd,\n root: this.options.root,\n ...this.initialOptions,\n ...initialConfig,\n ...userConfig,\n initialConfig,\n userConfig\n };\n }\n\n /**\n * Initialize the context with the provided configuration options\n */\n protected async innerSetup(): Promise<void> {\n const logger = this.extendLogger({ category: \"config\" });\n\n this.config.output = defu(this.config.output ?? {}, {\n copy: {\n assets: [\n {\n glob: \"LICENSE\"\n },\n {\n input: this.config.root,\n glob: \"*.md\"\n },\n {\n input: this.config.root,\n glob: \"package.json\"\n }\n ]\n },\n dts: true\n }) as OutputResolvedConfig;\n\n logger.trace(\n `Pre-setup Powerlines configuration object: \\n${formatLogMessage({\n ...omit(this.config, [\n \"inlineConfig\",\n \"userConfig\",\n \"initialConfig\",\n \"pluginConfig\",\n \"plugins\"\n ]),\n inlineConfig: isSetObject(this.config.inlineConfig)\n ? omit(this.config.inlineConfig, [\"plugins\"])\n : undefined,\n userConfig: isSetObject(this.config.userConfig)\n ? omit(this.config.userConfig, [\"plugins\"])\n : undefined,\n initialConfig: isSetObject(this.config.initialConfig)\n ? omit(this.config.initialConfig, [\"plugins\"])\n : undefined,\n pluginConfig: isSetObject(this.config.pluginConfig)\n ? omit(this.config.pluginConfig, [\"plugins\"])\n : undefined\n })}`\n );\n\n if (\n !this.initialOptions.mode &&\n !this.config.userConfig?.mode &&\n !this.config.inlineConfig?.mode &&\n !this.config.initialConfig?.mode &&\n !this.config.pluginConfig?.mode\n ) {\n this.options.mode = \"production\";\n this.config.mode = \"production\";\n }\n\n if (\n !this.initialOptions.framework &&\n !this.config.userConfig?.framework &&\n !this.config.inlineConfig?.framework &&\n !this.config.initialConfig?.framework &&\n !this.config.pluginConfig?.framework\n ) {\n this.options.framework = \"powerlines\";\n this.config.framework = \"powerlines\";\n }\n\n if (\n !this.config.userConfig?.projectType &&\n !this.config.inlineConfig?.projectType &&\n !this.config.initialConfig?.projectType &&\n !this.config.pluginConfig?.projectType\n ) {\n this.config.projectType = \"application\";\n }\n\n if (\n !this.config.userConfig?.platform &&\n !this.config.inlineConfig?.platform &&\n !this.config.initialConfig?.platform &&\n !this.config.pluginConfig?.platform\n ) {\n this.config.platform = \"neutral\";\n }\n\n this.resolvedConfig.compatibilityDate = resolveCompatibilityDates(\n this.config.inlineConfig.compatibilityDate ??\n this.config.userConfig.compatibilityDate ??\n this.config.initialConfig.compatibilityDate ??\n this.config.pluginConfig.compatibilityDate,\n \"latest\"\n );\n\n this.config.input = getUniqueInputs(this.config.input);\n\n if (\n this.config.name?.startsWith(\"@\") &&\n this.config.name.split(\"/\").filter(Boolean).length > 1\n ) {\n this.config.name = this.config.name.split(\"/\").filter(Boolean)[1]!;\n }\n\n this.config.title ??= titleCase(this.config.name);\n\n if (this.config.resolve.external) {\n this.config.resolve.external = getUnique(this.config.resolve.external);\n }\n if (this.config.resolve.noExternal) {\n this.config.resolve.noExternal = getUnique(\n this.config.resolve.noExternal\n );\n }\n\n this.config.plugins = (this.config.plugins ?? [])\n .flatMap(plugin => toArray(plugin))\n .filter(Boolean)\n .reduce((ret, plugin) => {\n if (\n isPlugin(plugin) &&\n isDuplicate(\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 if (\n !this.config.userConfig?.logLevel &&\n !this.config.initialConfig?.logLevel &&\n !this.config.pluginConfig?.logLevel &&\n !this.config.inlineConfig?.logLevel\n ) {\n if (this.config.mode === \"development\") {\n this.config.logLevel = DEFAULT_DEVELOPMENT_LOG_LEVEL;\n } else if (this.config.mode === \"test\") {\n this.config.logLevel = DEFAULT_TEST_LOG_LEVEL;\n } else {\n this.config.logLevel = DEFAULT_PRODUCTION_LOG_LEVEL;\n }\n }\n\n if (\n !this.config.userConfig?.tsconfig &&\n !this.config.initialConfig?.tsconfig &&\n !this.config.pluginConfig?.tsconfig &&\n !this.config.inlineConfig?.tsconfig\n ) {\n this.config.tsconfig = getTsconfigFilePath(\n this.config.cwd,\n this.config.root\n );\n } else if (this.config.tsconfig) {\n this.config.tsconfig = replacePath(\n replacePathTokens(this, this.config.tsconfig),\n this.config.cwd\n );\n }\n\n // #region Configure output\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 (this.config.output.path) {\n this.config.output.path = appendPath(\n replacePathTokens(this, this.config.output.path),\n this.config.cwd\n );\n } else {\n this.config.output.path = appendPath(\n joinPaths(this.config.root, \"dist\"),\n this.config.cwd\n );\n }\n\n if (this.config.output.copy !== false) {\n this.config.output.copy ??= {} as CopyResolvedConfig;\n if (!this.config.root.replace(/^\\.\\/?/, \"\")) {\n this.config.output.copy.path = this.config.output.copy.path\n ? appendPath(\n replacePathTokens(this, this.config.output.copy.path),\n this.config.cwd\n )\n : this.config.output.path;\n } else {\n this.config.output.copy.path = appendPath(\n replacePathTokens(\n this,\n this.config.output.copy.path || joinPaths(\"dist\", this.config.root)\n ),\n this.config.cwd\n );\n }\n }\n\n if (this.config.output.types !== false) {\n this.config.output.types = appendPath(\n replacePathTokens(\n this,\n this.config.userConfig?.output?.types ||\n this.config.inlineConfig?.output?.types ||\n this.config.initialConfig?.output?.types ||\n this.config.pluginConfig?.output?.types ||\n joinPaths(\n this.config.root,\n `${this.config.framework ?? \"powerlines\"}.d.ts`\n )\n ),\n this.config.cwd\n );\n }\n\n if (\n this.config.output.copy &&\n this.config.output.copy.path &&\n this.config.output.copy.assets &&\n Array.isArray(this.config.output.copy.assets)\n ) {\n this.config.output.copy.assets = getUniqueBy(\n this.config.output.copy.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.options.cwd\n : isParentPath(asset.input, this.config.cwd) ||\n isEqual(asset.input, this.config.cwd)\n ? asset.input\n : appendPath(asset.input, this.config.cwd),\n output:\n isSetObject(asset) && asset.output\n ? isParentPath(asset.output, this.config.cwd)\n ? asset.output\n : appendPath(\n joinPaths(\n (this.config.output.copy as CopyConfig).path,\n replacePath(\n replacePath(\n asset.output,\n replacePath(\n (this.config.output.copy as CopyConfig).path,\n this.config.cwd\n )\n ),\n (this.config.output.copy as CopyConfig).path\n )\n ),\n this.config.cwd\n )\n : appendPath(\n (this.config.output.copy as CopyConfig).path,\n this.config.cwd\n ),\n ignore:\n isSetObject(asset) && asset.ignore\n ? toArray(asset.ignore)\n : undefined\n };\n }),\n (a: ResolvedAssetGlob) => `${a.input}-${a.glob}-${a.output}`\n );\n }\n\n if (\n !this.config.userConfig?.output?.sourceMap &&\n !this.config.initialConfig?.output?.sourceMap &&\n !this.config.inlineConfig?.output?.sourceMap &&\n !this.config.pluginConfig?.output?.sourceMap\n ) {\n if (this.config.mode === \"development\") {\n this.config.output.sourceMap = true;\n } else {\n this.config.output.sourceMap = false;\n }\n }\n\n if (\n !this.config.userConfig?.output?.minify &&\n !this.config.initialConfig?.output?.minify &&\n !this.config.inlineConfig?.output?.minify &&\n !this.config.pluginConfig?.output?.minify\n ) {\n if (this.config.mode === \"production\") {\n this.config.output.minify = true;\n } else {\n this.config.output.minify = false;\n }\n }\n\n if (\n !this.config.userConfig?.output?.artifactsPath &&\n !this.config.initialConfig?.output?.artifactsPath &&\n !this.config.inlineConfig?.output?.artifactsPath &&\n !this.config.pluginConfig?.output?.artifactsPath\n ) {\n this.config.output.artifactsPath = `.${\n this.config.framework || \"powerlines\"\n }`;\n }\n\n if (this.config.output.copy && this.config.output.copy.assets) {\n this.config.output.copy.assets = this.config.output.copy.assets.map(\n 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\n if (\n (isSetString(this.config.output?.storage) &&\n this.config.output.storage === \"virtual\") ||\n (isSetObject(this.config.output?.storage) &&\n Object.values(this.config.output.storage).every(\n adapter => adapter.preset === \"virtual\"\n ))\n ) {\n this.config.output.overwrite = true;\n }\n\n this.#fs ??= await VirtualFileSystem.create(this);\n\n // #endregion Configure output\n\n if (\n isSetObject(this.config.inlineConfig) &&\n isSetObject(this.config.userConfig) &&\n isSetObject(this.config.initialConfig) &&\n isSetObject(this.config.pluginConfig)\n ) {\n logger.debug(\n `Resolved Powerlines configuration object: \\n${formatLogMessage({\n ...omit(this.config, [\n \"inlineConfig\",\n \"userConfig\",\n \"initialConfig\",\n \"pluginConfig\",\n \"plugins\"\n ]),\n inlineConfig: isSetObject(this.config.inlineConfig)\n ? omit(this.config.inlineConfig, [\"plugins\"])\n : undefined,\n userConfig: isSetObject(this.config.userConfig)\n ? omit(this.config.userConfig, [\"plugins\"])\n : undefined,\n initialConfig: isSetObject(this.config.initialConfig)\n ? omit(this.config.initialConfig, [\"plugins\"])\n : undefined,\n pluginConfig: isSetObject(this.config.pluginConfig)\n ? omit(this.config.pluginConfig, [\"plugins\"])\n : undefined\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 type {\n CallHookOptions,\n EnvironmentContext,\n HookListOrders,\n HooksList,\n HooksListItem,\n InferHookParameters,\n InferHookReturnType,\n Plugin,\n PluginContext,\n PluginHookFields,\n ResolvedConfig\n} from \"@powerlines/core\";\nimport {\n addPluginHook,\n isPluginHook,\n isPluginHookField,\n mergeConfig\n} from \"@powerlines/core/plugin-utils\";\nimport { colorText } from \"@powerlines/core/plugin-utils/logging\";\nimport { getField } from \"@stryke/helpers/get-field\";\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 { 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 { ArrayValues } from \"@stryke/types/array\";\nimport { AnyFunction } from \"@stryke/types/base\";\nimport chalk from \"chalk\";\nimport { defu } from \"defu\";\n\n/**\n * Merges the current hook result with the previous results based on their types.\n *\n * @param currentResult - The current hook result to merge with the previous results.\n * @param previousResults - The previous hook results to merge with the current result.\n * @returns The merged result.\n */\nexport function mergeResults<\n T extends Record<string | number | symbol, any> | string\n>(currentResult: T, previousResults: T[]): T[] {\n if (!previousResults || previousResults.length === 0) {\n return [currentResult];\n }\n\n if (isSetString(currentResult)) {\n previousResults = [\n `${isSetString(previousResults[0]) ? previousResults[0] || \"\" : \"\"}\\n${\n isSetString(previousResults[0])\n ? currentResult.replace(previousResults[0], \"\")\n : currentResult\n }`.trim() as T\n ];\n } else if (isObject(currentResult)) {\n previousResults =\n previousResults.length > 0\n ? [defu(currentResult, previousResults[0])]\n : [currentResult];\n }\n\n return previousResults;\n}\n\n/**\n * Merges multiple hook results together, with special handling for string values and object values.\n *\n * @param currentResult - The current hook result to merge with the previous results.\n * @param previousResults - The previous hook results to merge with the current result.\n * @returns The merged result.\n */\nexport function mergeConfigs<T>(currentResult: T, previousResults: T): T {\n if (isString(currentResult)) {\n previousResults =\n `${isString(previousResults) ? previousResults || \"\" : \"\"}\\n${\n currentResult || \"\"\n }`.trim() as T;\n } else if (isObject(currentResult)) {\n previousResults = mergeConfig(currentResult, previousResults ?? {}) as T;\n }\n\n return previousResults;\n}\n\n/**\n * Calls a hook with the given context, options, and arguments.\n *\n * @param context - The context to use when calling the hook.\n * @param key - The hook to call.\n * @param options - Options for calling the hook.\n * @param args - Arguments to pass to the hook.\n * @returns The return value of the hook.\n */\nexport async function callHook<\n TResolvedConfig extends ResolvedConfig,\n TKey extends string\n>(\n context: EnvironmentContext<TResolvedConfig>,\n key: TKey,\n options: CallHookOptions,\n ...args: InferHookParameters<PluginContext<TResolvedConfig>, TKey>\n): Promise<\n InferHookReturnType<PluginContext<TResolvedConfig>, TKey> | undefined\n> {\n const hooks = context.selectHooks(key, options);\n if (hooks.length > 0) {\n const logger = context.extendLogger({ category: \"hooks\" });\n\n logger.debug(\n `🧩 Calling ${hooks.length} ${chalk.bold.cyanBright(\n `${key}${options?.order ? ` (${options.order})` : \"\"}`\n )} plugin hook${hooks.length > 1 ? \"s\" : \"\"}:\\n${hooks\n .map((hook, index) => ` ${index + 1}. ${colorText(hook.plugin.name)}`)\n .join(\"\\n\")}`\n );\n\n const invokeHook = async (\n hook: ArrayValues<typeof hooks>,\n hookArgs: InferHookParameters<PluginContext<TResolvedConfig>, TKey>\n ) => {\n return Reflect.apply(hook.handler as AnyFunction, hook.context, hookArgs);\n };\n\n let results = [] as InferHookReturnType<\n PluginContext<TResolvedConfig>,\n TKey\n >[];\n if (options?.sequential === false) {\n results = (await Promise.all(\n hooks.map(async hook => {\n if (!isFunction(hook.handler)) {\n throw new Error(\n `Plugin hook handler for hook \"${key}\" is not a function.`\n );\n }\n\n return invokeHook(hook, [...args]);\n })\n )) as InferHookReturnType<PluginContext<TResolvedConfig>, TKey>[];\n } else {\n for (const hook of hooks) {\n if (!isFunction(hook.handler)) {\n throw new Error(\n `Plugin hook handler for hook \"${key}\" is not a function.`\n );\n }\n\n if (options?.result === \"first\" || options?.asNextParam === false) {\n results.push(\n (await Promise.resolve(\n invokeHook(hook, [...args])\n )) as InferHookReturnType<PluginContext<TResolvedConfig>, TKey>\n );\n if (\n options?.result === \"first\" &&\n isSet(results[results.length - 1])\n ) {\n break;\n }\n } else {\n const sequenceArgs = [...args];\n if (results.length > 0 && sequenceArgs.length > 0) {\n sequenceArgs[0] = isFunction(options.asNextParam)\n ? await Promise.resolve(options.asNextParam(results[0]))\n : results[0];\n }\n\n const result = await Promise.resolve(\n invokeHook(hook, [...sequenceArgs] as InferHookParameters<\n PluginContext<TResolvedConfig>,\n TKey\n >)\n );\n if (result) {\n if (options.result === \"last\") {\n results = [result];\n } else if (options.result === \"merge\" && options.merge) {\n results = [\n results.length > 0 && results[0]\n ? await Promise.resolve(options.merge(result, results[0]))\n : result\n ];\n } else {\n results = mergeResults(result, results);\n }\n }\n }\n }\n }\n\n const definedResults = results.filter(\n (\n result\n ): result is NonNullable<\n InferHookReturnType<PluginContext<TResolvedConfig>, TKey>\n > => isSet(result)\n );\n\n if (definedResults.length > 0) {\n let mergedResult = undefined as\n | InferHookReturnType<PluginContext<TResolvedConfig>, TKey>\n | undefined;\n\n for (const result of definedResults) {\n mergedResult = defu(\n result as Record<string, unknown>,\n mergedResult ?? {}\n ) as InferHookReturnType<PluginContext<TResolvedConfig>, TKey>;\n }\n\n return mergedResult;\n }\n }\n\n return undefined;\n}\n\nexport function extractHooks<\n TResolvedConfig extends ResolvedConfig = ResolvedConfig\n>(\n context: PluginContext<TResolvedConfig>,\n hooks: Record<string, HooksList<PluginContext<TResolvedConfig>>>,\n plugin: Plugin<PluginContext<TResolvedConfig>>,\n key: string,\n parentKey?: string\n): Record<string, HooksList<PluginContext<TResolvedConfig>>> {\n const combinedKey = parentKey ? `${parentKey}:${key}` : key;\n const pluginField = getField(plugin, combinedKey.replace(/:/g, \".\"));\n if (\n isPluginHookField<PluginContext<TResolvedConfig>>(combinedKey) &&\n isPluginHook(pluginField)\n ) {\n const pluginHook = pluginField;\n if (!isPluginHook(pluginHook)) {\n return hooks;\n }\n\n hooks[combinedKey] ??= {\n preEnforced: [] as HooksListItem<PluginContext<TResolvedConfig>>[],\n preOrdered: [] as HooksListItem<PluginContext<TResolvedConfig>>[],\n normal: [] as HooksListItem<PluginContext<TResolvedConfig>>[],\n postEnforced: [] as HooksListItem<PluginContext<TResolvedConfig>>[],\n postOrdered: [] as HooksListItem<PluginContext<TResolvedConfig>>[]\n };\n\n if (plugin.enforce) {\n const hookListOrder = `${plugin.enforce}Enforced` as HookListOrders;\n hooks[combinedKey][hookListOrder] ??= [] as HooksListItem<\n PluginContext<TResolvedConfig>\n >[];\n\n hooks[combinedKey][hookListOrder] = addPluginHook<\n PluginContext<TResolvedConfig>,\n PluginHookFields<PluginContext<TResolvedConfig>>\n >(context, plugin, pluginHook, hooks[combinedKey][hookListOrder]);\n\n return hooks;\n }\n\n if (isFunction(pluginHook) || !pluginHook.order) {\n hooks[combinedKey].normal ??= [];\n\n hooks[combinedKey].normal = addPluginHook<\n PluginContext<TResolvedConfig>,\n PluginHookFields<PluginContext<TResolvedConfig>>\n >(context, plugin, pluginHook, hooks[combinedKey].normal);\n\n return hooks;\n }\n\n const hookListOrder = `${pluginHook.order}Ordered` as HookListOrders;\n hooks[combinedKey][hookListOrder] ??= [];\n\n hooks[combinedKey][hookListOrder] = addPluginHook<\n PluginContext<TResolvedConfig>,\n PluginHookFields<PluginContext<TResolvedConfig>>\n >(context, plugin, pluginHook, hooks[combinedKey][hookListOrder]);\n\n return hooks;\n } else if (isSetObject(pluginField)) {\n return Object.keys(pluginField)\n .map(pluginKey =>\n extractHooks(context, hooks, plugin, pluginKey, combinedKey)\n )\n .reduce((ret, current) => {\n Object.keys(current).forEach(key => {\n ret[key] ??= {\n preEnforced: [] as HooksListItem<PluginContext<TResolvedConfig>>[],\n preOrdered: [] as HooksListItem<PluginContext<TResolvedConfig>>[],\n normal: [] as HooksListItem<PluginContext<TResolvedConfig>>[],\n postEnforced: [] as HooksListItem<PluginContext<TResolvedConfig>>[],\n postOrdered: [] as HooksListItem<PluginContext<TResolvedConfig>>[]\n };\n\n [\n \"preEnforced\",\n \"preOrdered\",\n \"normal\",\n \"postEnforced\",\n \"postOrdered\"\n ].forEach(order => {\n if (\n current[key]?.[\n order as keyof HooksList<PluginContext<TResolvedConfig>>\n ]\n ) {\n ret[key]![\n order as keyof HooksList<PluginContext<TResolvedConfig>>\n ] ??= [];\n ret[key]![\n order as keyof HooksList<PluginContext<TResolvedConfig>>\n ] = ret[key]![\n order as keyof HooksList<PluginContext<TResolvedConfig>>\n ]!.concat(\n current[key][\n order as keyof HooksList<PluginContext<TResolvedConfig>>\n ]!\n );\n }\n });\n });\n\n return ret;\n }, hooks);\n }\n\n return hooks;\n}\n","/* -------------------------------------------------------------------\n\n ⚡ Storm Software - Powerlines\n\n This code was released as part of the Powerlines project. Powerlines\n is maintained by Storm Software under the Apache-2.0 license, and is\n free for commercial and private use. For more information, please visit\n our licensing page at https://stormsoftware.com/licenses/projects/powerlines.\n\n Website: https://stormsoftware.com\n Repository: https://github.com/storm-software/powerlines\n Documentation: https://docs.stormsoftware.com/projects/powerlines\n Contact: https://stormsoftware.com/contact\n\n SPDX-License-Identifier: Apache-2.0\n\n ------------------------------------------------------------------- */\n\nimport type {\n CallHookOptions,\n EnvironmentContext,\n InferHookParameters,\n InferHookReturnType,\n LoggerMessage,\n LogLevel,\n Plugin,\n PluginContext,\n ResolvedConfig\n} from \"@powerlines/core\";\nimport {\n Unstable_EnvironmentContext,\n Unstable_PluginContext\n} from \"@powerlines/core/types/_internal\";\nimport { isSetObject } from \"@stryke/type-checks/is-set-object\";\nimport { isString } from \"@stryke/type-checks/is-string\";\nimport { UnpluginMessage } from \"unplugin\";\n\n/**\n * Create a Proxy-based PluginContext\n *\n * @param pluginId - The unique identifier of the plugin\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 pluginId: string,\n plugin: Plugin<PluginContext<TResolvedConfig>>,\n environment: Unstable_EnvironmentContext<TResolvedConfig>\n): Unstable_PluginContext<TResolvedConfig> {\n const logger = environment.extendLogger({\n plugin: plugin.name\n });\n\n const normalizeMessage = (\n message: string | UnpluginMessage\n ): LoggerMessage => {\n return {\n meta: {\n ...(isSetObject(message) ? message.meta : {}),\n environment: environment.environment?.name,\n plugin: plugin.name\n },\n message: isString(message) ? message : message.message\n };\n };\n\n const callHookFn = async <TKey extends string>(\n hook: TKey,\n options: CallHookOptions,\n ...args: InferHookParameters<PluginContext<TResolvedConfig>, TKey>\n ): Promise<\n InferHookReturnType<PluginContext<TResolvedConfig>, TKey> | undefined\n > => {\n return environment.$$internal.api.callHook(\n hook,\n {\n sequential: true,\n result: \"merge\",\n ...options,\n environment\n } as Parameters<typeof environment.$$internal.api.callHook>[1],\n ...args\n );\n };\n\n const meta = {} as Record<string, any>;\n\n return new Proxy({} as Unstable_PluginContext<TResolvedConfig>, {\n get(_, prop) {\n if (prop === \"$$internal\") {\n return {\n ...environment.$$internal,\n environment,\n callHook: callHookFn,\n meta\n };\n }\n\n if (prop === \"id\") {\n return pluginId;\n }\n\n if (prop === \"logger\") {\n return logger;\n }\n\n if (prop === \"log\") {\n return (type: LogLevel, message: string | UnpluginMessage) => {\n logger.log(type, normalizeMessage(message));\n };\n }\n\n if (prop === \"fatal\") {\n return (message: string | UnpluginMessage) => {\n logger.error(normalizeMessage(message));\n };\n }\n\n if (prop === \"error\") {\n return (message: string | UnpluginMessage) => {\n logger.error(normalizeMessage(message));\n };\n }\n\n if (prop === \"warn\") {\n return (message: string | UnpluginMessage) => {\n logger.warn(normalizeMessage(message));\n };\n }\n\n if (prop === \"info\") {\n return (message: string | UnpluginMessage) => {\n logger.info(normalizeMessage(message));\n };\n }\n\n if (prop === \"debug\") {\n return (message: string | UnpluginMessage) => {\n logger.debug(normalizeMessage(message));\n };\n }\n\n if (prop === \"trace\") {\n return (message: string | UnpluginMessage) => {\n logger.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 \"id\",\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 logger.warn(`Cannot set the read-only \"${String(prop)}\" property`);\n\n return false;\n }\n\n (environment as Record<string, any>)[prop as string] = 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 type {\n EnvironmentContext,\n EnvironmentContextPlugin,\n EnvironmentResolvedConfig,\n ExecutionOptions,\n HooksList,\n HooksListItem,\n LogFn,\n Logger,\n LoggerOptions,\n Plugin,\n PluginConfig,\n PluginContext,\n ResolvedConfig,\n SelectHookResult,\n SelectHooksOptions\n} from \"@powerlines/core\";\nimport { PLUGIN_NON_HOOK_FIELDS } from \"@powerlines/core/constants\";\nimport {\n dedupeHooklist,\n isPlugin,\n isPluginConfig,\n isPluginHookField,\n mergeConfig\n} from \"@powerlines/core/plugin-utils\";\nimport { resolvePackage } from \"@stryke/fs/resolve\";\nimport { deepClone } from \"@stryke/helpers/deep-clone\";\nimport { isFunction } from \"@stryke/type-checks/is-function\";\nimport { isObject } from \"@stryke/type-checks/is-object\";\nimport { isSetObject } from \"@stryke/type-checks/is-set-object\";\nimport { ArrayValues } from \"@stryke/types/array\";\nimport { uuid } from \"@stryke/unique-id/uuid\";\nimport { getConfigProps } from \"../_internal/helpers/context\";\nimport { extractHooks } from \"../_internal/helpers/hooks\";\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: Record<string, HooksList<PluginContext<TResolvedConfig>>> = {};\n\n /**\n * Create a new context from the config.\n *\n * @param options - The resolved execution options.\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 options: ExecutionOptions,\n config: TResolvedConfig,\n environment: EnvironmentResolvedConfig\n ): Promise<PowerlinesEnvironmentContext<TResolvedConfig>> {\n const context = new PowerlinesEnvironmentContext<TResolvedConfig>(\n options,\n config,\n environment\n );\n await context.setup();\n\n const powerlinesPath = await resolvePackage(\"powerlines\");\n if (!powerlinesPath) {\n throw new Error(\"Could not resolve `powerlines` package location.\");\n }\n\n context.powerlinesPath = powerlinesPath;\n\n return context;\n }\n\n /**\n * The resolved environment configuration\n */\n public environment: EnvironmentResolvedConfig;\n\n /**\n * The list of plugins applied to this environment\n */\n public plugins: EnvironmentContextPlugin<TResolvedConfig>[] = [];\n\n /**\n * The unique identifier of the environment associated with this context, which can be used for logging and other purposes to distinguish between different environments in the same process.\n */\n public get id(): string {\n return this.environment.environmentId;\n }\n\n /**\n * The hooks registered by plugins in this environment\n */\n public get hooks(): Record<\n string,\n HooksList<PluginContext<TResolvedConfig>>\n > {\n return this.#hooks;\n }\n\n /**\n * Create a new logger instance\n *\n * @param options - The configuration options to use for the logger instance, which can be used to customize the appearance and behavior of the log messages generated by the logger. This is typically the name of the plugin or module that is creating the logger instance.\n * @param logFn - The custom logging function to use for logging messages, which can be used to override the default logging behavior of the original logger.\n * @returns A logger client instance that can be used to generate log messages with consistent formatting and metadata.\n */\n public override createLogger(options: LoggerOptions, logFn?: LogFn): Logger {\n return super.createLogger(\n {\n ...options,\n environment: this.environment?.name\n },\n logFn\n );\n }\n\n /**\n * Extend the base logger with additional configuration options\n *\n * @param options - The configuration options to extend the base logger with, which can be used to add additional metadata or customize the appearance of log messages generated by the logger. This is typically the name of the plugin or module that is creating the logger instance, as well as any additional metadata such as the plugin category or environment.\n * @returns A new logger client instance that extends the base logger with the provided configuration options.\n */\n public override extendLogger(options: LoggerOptions): Logger {\n return super.extendLogger({\n ...options,\n environment: this.environment?.name\n });\n }\n\n /**\n * Creates a clone of the current context with the same configuration and workspace settings. This can be useful for running multiple builds in parallel or for creating isolated contexts for different parts of the build process.\n *\n * @remarks\n * The cloned context will have the same configuration and workspace settings as the original context, but will have a different build ID, release ID, and timestamp. The virtual file system and caches will also be separate between the original and cloned contexts.\n *\n * @returns A promise that resolves to the cloned context.\n */\n public override async clone(): Promise<EnvironmentContext<TResolvedConfig>> {\n const context =\n (await PowerlinesEnvironmentContext.fromConfig<TResolvedConfig>(\n deepClone(this.options),\n deepClone(this.config) as TResolvedConfig,\n deepClone(this.environment) as EnvironmentResolvedConfig\n )) as any;\n\n return this.copyTo(context);\n }\n\n /**\n * Initialize the context with the provided configuration options\n */\n public override async setup(): Promise<void> {\n this.resolvedConfig = mergeConfig(\n {\n name: this.config.name,\n title: this.config.title\n },\n getConfigProps({\n ...this.environment,\n root: this.options.root,\n cwd: this.options.cwd\n }),\n this.config\n ) as TResolvedConfig;\n\n await this.innerSetup();\n }\n\n public async addPlugin(plugin: Plugin<PluginContext<TResolvedConfig>>) {\n let resolvedPlugin = plugin;\n if (isFunction(plugin.applyToEnvironment)) {\n const result = (await Promise.resolve(\n plugin.applyToEnvironment(this.environment) as Promise<any>\n )) as boolean | PluginConfig<PluginContext<TResolvedConfig>>;\n\n if (!result || (isObject(result) && Object.keys(result).length === 0)) {\n return;\n }\n\n if (isPluginConfig<PluginContext<TResolvedConfig>>(result)) {\n return this.$$internal.addPlugin(result);\n }\n\n resolvedPlugin = isPlugin<PluginContext<TResolvedConfig>>(result)\n ? result\n : plugin;\n }\n\n const pluginId = uuid();\n const context = createPluginContext<TResolvedConfig>(\n pluginId,\n resolvedPlugin,\n this\n );\n\n this.plugins.push({\n pluginId,\n plugin: resolvedPlugin,\n context\n });\n\n this.#hooks = Object.entries(\n 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(\n (ret, key) =>\n extractHooks<TResolvedConfig>(context, ret, resolvedPlugin, key),\n this.hooks\n )\n ).reduce(\n (ret, [key, value]) => {\n if (isSetObject(value)) {\n Object.entries(value).forEach(([type, list]) => {\n ret[key] ??= {};\n ret[key][type as keyof (typeof ret)[typeof key]] =\n dedupeHooklist<PluginContext<TResolvedConfig>>(list);\n });\n }\n\n return ret;\n },\n {} as Record<string, HooksList<PluginContext<TResolvedConfig>>>\n );\n }\n\n /**\n * Retrieves the hook handlers for a specific hook name\n */\n public selectHooks<TKey extends string>(\n key: TKey,\n options?: SelectHooksOptions\n ): SelectHookResult<PluginContext<TResolvedConfig>, TKey> {\n const result = [] as SelectHookResult<PluginContext<TResolvedConfig>, TKey>;\n\n if (\n isPluginHookField<PluginContext<TResolvedConfig>>(key) &&\n this.hooks[key]\n ) {\n if (this.hooks[key]) {\n if (options?.order) {\n const mapHooksToResult = (\n hooksList: HooksListItem<PluginContext<TResolvedConfig>, string>[]\n ): SelectHookResult<PluginContext<TResolvedConfig>, TKey> =>\n hooksList.map(hook => {\n const plugin = this.plugins.find(\n p => p.plugin.name === hook.plugin.name\n );\n if (!plugin) {\n throw new Error(\n `Could not find plugin context for plugin \"${\n hook.plugin.name\n }\".`\n );\n }\n\n return {\n handler: hook.handler,\n plugin: hook.plugin,\n context: plugin.context\n };\n });\n\n if (options?.order === \"pre\") {\n result.push(...mapHooksToResult(this.hooks[key].preOrdered ?? []));\n result.push(...mapHooksToResult(this.hooks[key].preEnforced ?? []));\n } else if (options?.order === \"post\") {\n result.push(...mapHooksToResult(this.hooks[key].postOrdered ?? []));\n result.push(\n ...mapHooksToResult(this.hooks[key].postEnforced ?? [])\n );\n } else {\n result.push(...mapHooksToResult(this.hooks[key].normal ?? []));\n }\n } else {\n result.push(...this.selectHooks(key, { order: \"pre\" }));\n result.push(...this.selectHooks(key, { order: \"normal\" }));\n result.push(...this.selectHooks(key, { order: \"post\" }));\n }\n }\n }\n\n return result;\n }\n\n protected constructor(\n options: ExecutionOptions,\n config: TResolvedConfig,\n environment: EnvironmentResolvedConfig\n ) {\n super(options);\n\n this.resolvedConfig = config;\n this.environment = environment;\n }\n\n /**\n * Creates a clone of the current context with the same configuration and workspace settings. This can be useful for running multiple builds in parallel or for creating isolated contexts for different parts of the build process.\n *\n * @remarks\n * The cloned context will have the same configuration and workspace settings as the original context, but will have a different build ID, release ID, and timestamp. The virtual file system and caches will also be separate between the original and cloned contexts.\n *\n * @returns The cloned context.\n */\n protected override copyTo(\n context: EnvironmentContext<TResolvedConfig>\n ): EnvironmentContext<TResolvedConfig> {\n context.plugins = this.plugins;\n\n return super.copyTo(context) as EnvironmentContext<TResolvedConfig>;\n }\n}\n","/* -------------------------------------------------------------------\n\n ⚡ Storm Software - Powerlines\n\n This code was released as part of the Powerlines project. Powerlines\n is maintained by Storm Software under the Apache-2.0 license, and is\n free for commercial and private use. For more information, please visit\n our licensing page at https://stormsoftware.com/licenses/projects/powerlines.\n\n Website: https://stormsoftware.com\n Repository: https://github.com/storm-software/powerlines\n Documentation: https://docs.stormsoftware.com/projects/powerlines\n Contact: https://stormsoftware.com/contact\n\n SPDX-License-Identifier: Apache-2.0\n\n ------------------------------------------------------------------- */\n\nimport type {\n EnvironmentContext,\n EnvironmentResolvedConfig,\n ExecutionContext,\n InitialConfig,\n InlineConfig,\n LogFn,\n Logger,\n LoggerOptions,\n Plugin,\n PluginContext,\n ResolvedConfig\n} from \"@powerlines/core\";\nimport { ExecutionOptions } from \"@powerlines/core\";\nimport { GLOBAL_ENVIRONMENT } from \"@powerlines/core/constants\";\nimport type {\n Unstable_ContextInternal,\n Unstable_EnvironmentContext,\n Unstable_ExecutionContext\n} from \"@powerlines/core/types/_internal\";\nimport { toArray } from \"@stryke/convert/to-array\";\nimport { existsSync } from \"@stryke/fs/exists\";\nimport { readJsonFile } from \"@stryke/fs/json\";\nimport { resolvePackage } from \"@stryke/fs/resolve\";\nimport { deepClone } from \"@stryke/helpers/deep-clone\";\nimport { joinPaths } from \"@stryke/path/join\";\nimport { PackageJson } from \"@stryke/types/package-json\";\nimport chalk from \"chalk\";\nimport {\n createDefaultEnvironment,\n createEnvironment\n} from \"../_internal/helpers/environment\";\nimport { PowerlinesContext } from \"./context\";\nimport { PowerlinesEnvironmentContext } from \"./environment-context\";\n\nexport class PowerlinesExecutionContext<\n TResolvedConfig extends ResolvedConfig = ResolvedConfig\n>\n extends PowerlinesContext<TResolvedConfig>\n implements ExecutionContext<TResolvedConfig>\n{\n #environments: Record<string, Unstable_EnvironmentContext<TResolvedConfig>> =\n {};\n\n #plugins: Plugin<PluginContext<TResolvedConfig>>[] = [];\n\n /**\n * Create a new Storm context from the workspace root and user config.\n *\n * @param options - The options for resolving the context.\n * @returns A promise that resolves to the new context.\n */\n public static override async init<\n TResolvedConfig extends ResolvedConfig = ResolvedConfig\n >(\n options: ExecutionOptions,\n initialConfig: InitialConfig<TResolvedConfig[\"userConfig\"]>\n ): Promise<ExecutionContext<TResolvedConfig>> {\n const context = new PowerlinesExecutionContext<TResolvedConfig>(options);\n await context.init(options, initialConfig);\n\n const powerlinesPath = await resolvePackage(\"powerlines\");\n if (!powerlinesPath) {\n throw new Error(\"Could not resolve `powerlines` package location.\");\n }\n context.powerlinesPath = powerlinesPath;\n\n return context;\n }\n\n /**\n * Create a new Storm context from the workspace root and user config.\n *\n * @param options - The options for resolving the context.\n * @returns A promise that resolves to the new context.\n */\n public static async inline<\n TResolvedConfig extends ResolvedConfig = ResolvedConfig\n >(\n options: ExecutionOptions,\n initialConfig: InitialConfig<TResolvedConfig[\"userConfig\"]>,\n inlineConfig: InlineConfig<TResolvedConfig[\"userConfig\"]>\n ): Promise<ExecutionContext<TResolvedConfig>> {\n const context = new PowerlinesExecutionContext<TResolvedConfig>(options);\n await context.init(options, initialConfig);\n\n context.config.inlineConfig = inlineConfig;\n if (context.config.inlineConfig.command === \"new\") {\n const workspacePackageJsonPath = joinPaths(\n context.config.cwd,\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 context.packageJson = await readJsonFile<PackageJson>(\n workspacePackageJsonPath\n );\n }\n\n await context.setup();\n\n const powerlinesPath = await resolvePackage(\"powerlines\");\n if (!powerlinesPath) {\n throw new Error(\"Could not resolve `powerlines` package location.\");\n }\n context.powerlinesPath = powerlinesPath;\n\n return context;\n }\n\n /**\n * Internal context fields and methods\n *\n * @danger\n * This field is for internal use only and should not be accessed or modified directly. It is unstable and can be changed at anytime.\n *\n * @internal\n */\n public override get $$internal(): Unstable_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: Unstable_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 * The unique identifier of the execution context, which can be used for logging and other purposes to distinguish between different executions in the same process.\n */\n public get id(): string {\n return this.options.executionId;\n }\n\n /**\n * A record of all environments by name\n */\n public get environments(): Record<\n string,\n Unstable_EnvironmentContext<TResolvedConfig>\n > {\n return this.#environments;\n }\n\n public get plugins(): Array<Plugin<PluginContext<TResolvedConfig>>> {\n return this.#plugins;\n }\n\n /**\n * Creates a new instance.\n *\n * @param options - The options to use for creating the context, including the resolved configuration and workspace settings.\n */\n protected constructor(options: ExecutionOptions) {\n super(options);\n }\n\n /**\n * Create a new logger instance\n *\n * @param options - The configuration options to use for the logger instance, which can be used to customize the appearance and behavior of the log messages generated by the logger. This is typically the name of the plugin or module that is creating the logger instance.\n * @param logFn - The custom logging function to use for logging messages, which can be used to override the default logging behavior of the original logger.\n * @returns A logger client instance that can be used to generate log messages with consistent formatting and metadata.\n */\n public override createLogger(options: LoggerOptions, logFn?: LogFn): Logger {\n return super.createLogger(\n {\n ...options,\n executionId: this.id,\n executionIndex: this.options.executionIndex\n },\n logFn\n );\n }\n\n /**\n * Extend the base logger with additional configuration options\n *\n * @param options - The configuration options to extend the base logger with, which can be used to add additional metadata or customize the appearance of log messages generated by the logger. This is typically the name of the plugin or module that is creating the logger instance, as well as any additional metadata such as the plugin category or environment.\n * @returns A new logger client instance that extends the base logger with the provided configuration options.\n */\n public override extendLogger(options: LoggerOptions): Logger {\n return super.extendLogger({\n ...options,\n executionId: this.id,\n executionIndex: this.options.executionIndex\n });\n }\n\n /**\n * Creates a clone of the current context with the same configuration and workspace settings. This can be useful for running multiple builds in parallel or for creating isolated contexts for different parts of the build process.\n *\n * @remarks\n * The cloned context will have the same configuration and workspace settings as the original context, but will have a different build ID, release ID, and timestamp. The virtual file system and caches will also be separate between the original and cloned contexts.\n *\n * @returns A promise that resolves to the cloned context.\n */\n public override async clone(): Promise<ExecutionContext<TResolvedConfig>> {\n const clone = (await PowerlinesExecutionContext.init<TResolvedConfig>(\n this.options,\n this.initialConfig\n )) as Unstable_ExecutionContext<TResolvedConfig>;\n\n clone.config.userConfig = deepClone(\n this.config.userConfig\n ) as TResolvedConfig[\"userConfig\"];\n clone.config.initialConfig = deepClone(\n this.config.initialConfig\n ) as InitialConfig<TResolvedConfig[\"userConfig\"]>;\n clone.config.inlineConfig = deepClone(\n this.config.inlineConfig\n ) as InlineConfig<TResolvedConfig[\"userConfig\"]>;\n clone.config.pluginConfig = deepClone(this.config.pluginConfig) as Partial<\n TResolvedConfig[\"userConfig\"]\n >;\n\n await clone.setup();\n clone.$$internal = this.$$internal;\n\n return this.copyTo(clone) as ExecutionContext<TResolvedConfig>;\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<Unstable_EnvironmentContext<TResolvedConfig>> {\n // let environmentContext!: PowerlinesEnvironmentContext<TResolvedConfig>;\n // if (this.environments[environment.name]) {\n // environmentContext = this.environments[\n // environment.name\n // ]! as PowerlinesEnvironmentContext<TResolvedConfig>;\n // }\n\n const context = this.copyTo(\n await PowerlinesEnvironmentContext.fromConfig(\n deepClone(this.options),\n deepClone(this.config) as TResolvedConfig,\n deepClone(environment) as EnvironmentResolvedConfig\n )\n ) as PowerlinesEnvironmentContext<TResolvedConfig>;\n\n context.plugins = [];\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 inline configuration options\n */\n public override async setup() {\n await super.setup();\n\n await Promise.all(\n toArray(\n this.config.environments &&\n Object.keys(this.config.environments).length > 0\n ? Object.keys(this.config.environments).map(name =>\n createEnvironment(name, this.config)\n )\n : createDefaultEnvironment(this.config)\n ).map(async env => {\n this.#environments[env.name] = await this.in(env);\n })\n );\n }\n\n /**\n * Add a plugin to the API context and all environments\n *\n * @param plugin - The plugin to add.\n */\n public async addPlugin(plugin: Plugin<PluginContext<TResolvedConfig>>) {\n this.plugins.push(plugin);\n\n await Promise.all(\n Object.keys(this.environments).map(async name => {\n await this.environments[name]!.addPlugin(plugin);\n })\n );\n }\n\n /**\n * Get an environment by name, or the default environment if no name is provided\n *\n * @param name - The name of the environment to retrieve.\n * @returns The requested environment context.\n */\n public async getEnvironment(name?: string) {\n let environment: EnvironmentContext<TResolvedConfig> | undefined;\n if (name) {\n environment = this.environments[name];\n }\n\n if (Object.keys(this.environments).length === 1) {\n environment = this.environments[Object.keys(this.environments)[0]!];\n\n this.debug(\n `Applying the only configured environment: ${chalk.bold.cyanBright(\n environment?.environment.name\n )}`\n );\n }\n\n if (!environment) {\n if (name) {\n throw new Error(`Environment \"${name}\" not found.`);\n }\n\n environment = await this.in(createDefaultEnvironment(this.config));\n\n this.warn(\n `No environment specified, and no default environment found. Using a temporary default environment: ${chalk.bold.cyanBright(\n environment?.environment.name\n )}`\n );\n }\n\n return environment;\n }\n\n /**\n * A safe version of `getEnvironment` that returns `undefined` if the environment is not found\n *\n * @param name - The name of the environment to retrieve.\n * @returns The requested environment context or `undefined` if not found.\n */\n public async getEnvironmentSafe(\n name?: string\n ): Promise<EnvironmentContext<TResolvedConfig> | undefined> {\n try {\n return await this.getEnvironment(name);\n } catch {\n return undefined;\n }\n }\n\n /**\n * A function to merge all configured environments into a single context.\n *\n * @remarks\n * If only one environment is configured, that environment will be returned directly.\n *\n * @returns A promise that resolves to a merged/global environment context.\n */\n public async toEnvironment(): Promise<EnvironmentContext<TResolvedConfig>> {\n let environment: EnvironmentContext<TResolvedConfig>;\n if (Object.keys(this.environments).length > 1) {\n environment = await this.in(\n createEnvironment(GLOBAL_ENVIRONMENT, this.config)\n );\n\n this.debug(\n `Combined all ${Object.keys(this.environments).length} environments into a single global context.`\n );\n } else {\n environment = await this.getEnvironment();\n }\n\n return environment;\n }\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AA4BA,SAAgB,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