@warlock.js/core 5.6.0 → 5.7.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (62) hide show
  1. package/CHANGELOG.md +18 -0
  2. package/esm/benchmark/profiler.d.mts.map +1 -1
  3. package/esm/benchmark/profiler.mjs +4 -3
  4. package/esm/benchmark/profiler.mjs.map +1 -1
  5. package/esm/cli/cli-commands.manager.mjs +10 -7
  6. package/esm/cli/cli-commands.manager.mjs.map +1 -1
  7. package/esm/cli/commands/routes/format-routes-table.mjs +3 -3
  8. package/esm/cli/commands/routes/format-routes-table.mjs.map +1 -1
  9. package/esm/cli/parse-cli-args.mjs +1 -0
  10. package/esm/cli/parse-cli-args.mjs.map +1 -1
  11. package/esm/cli/string-similarity.mjs +13 -4
  12. package/esm/cli/string-similarity.mjs.map +1 -1
  13. package/esm/commands/cli-command.d.mts.map +1 -1
  14. package/esm/commands/cli-command.mjs +5 -2
  15. package/esm/commands/cli-command.mjs.map +1 -1
  16. package/esm/config/config-loader.mjs +3 -1
  17. package/esm/config/config-loader.mjs.map +1 -1
  18. package/esm/dev-server/dependency-graph.d.mts.map +1 -1
  19. package/esm/dev-server/dependency-graph.mjs +2 -1
  20. package/esm/dev-server/dependency-graph.mjs.map +1 -1
  21. package/esm/dev-server/dev-logger.mjs +7 -5
  22. package/esm/dev-server/dev-logger.mjs.map +1 -1
  23. package/esm/dev-server/files-orchestrator.mjs +1 -1
  24. package/esm/dev-server/files-orchestrator.mjs.map +1 -1
  25. package/esm/dev-server/parse-imports.mjs +22 -8
  26. package/esm/dev-server/parse-imports.mjs.map +1 -1
  27. package/esm/encryption/encrypt.mjs +1 -0
  28. package/esm/encryption/encrypt.mjs.map +1 -1
  29. package/esm/generations/add-command.action.mjs +8 -2
  30. package/esm/generations/add-command.action.mjs.map +1 -1
  31. package/esm/generations/features/shared/relocate-conflicting-home-route.mjs +6 -1
  32. package/esm/generations/features/shared/relocate-conflicting-home-route.mjs.map +1 -1
  33. package/esm/http/middleware/maintenance.middleware.mjs +1 -2
  34. package/esm/http/middleware/maintenance.middleware.mjs.map +1 -1
  35. package/esm/http/middleware/utils/cidr-match.d.mts.map +1 -1
  36. package/esm/http/middleware/utils/cidr-match.mjs +1 -0
  37. package/esm/http/middleware/utils/cidr-match.mjs.map +1 -1
  38. package/esm/http/request.d.mts.map +1 -1
  39. package/esm/http/request.mjs +14 -7
  40. package/esm/http/request.mjs.map +1 -1
  41. package/esm/repositories/adapters/cascade/filter-applicator.mjs +4 -2
  42. package/esm/repositories/adapters/cascade/filter-applicator.mjs.map +1 -1
  43. package/esm/router/positional-handler-diagnostics.d.mts.map +1 -1
  44. package/esm/router/positional-handler-diagnostics.mjs +9 -3
  45. package/esm/router/positional-handler-diagnostics.mjs.map +1 -1
  46. package/esm/router/route-registry.mjs +1 -1
  47. package/esm/router/route-registry.mjs.map +1 -1
  48. package/esm/storage/scoped-storage.d.mts.map +1 -1
  49. package/esm/storage/scoped-storage.mjs +1 -0
  50. package/esm/storage/scoped-storage.mjs.map +1 -1
  51. package/esm/storage/storage.d.mts.map +1 -1
  52. package/esm/storage/storage.mjs +6 -2
  53. package/esm/storage/storage.mjs.map +1 -1
  54. package/esm/storage/utils/safe-fetch.d.mts.map +1 -1
  55. package/esm/storage/utils/safe-fetch.mjs +6 -1
  56. package/esm/storage/utils/safe-fetch.mjs.map +1 -1
  57. package/esm/utils/version-compare.d.mts.map +1 -1
  58. package/esm/utils/version-compare.mjs +12 -4
  59. package/esm/utils/version-compare.mjs.map +1 -1
  60. package/esm/vite/lower-stage3-decorators.mjs +1 -0
  61. package/esm/vite/lower-stage3-decorators.mjs.map +1 -1
  62. package/package.json +12 -12
@@ -1 +1 @@
1
- {"version":3,"file":"config-loader.mjs","names":[],"sources":["../../../../../../../core/src/config/config-loader.ts"],"sourcesContent":["import config from \"@mongez/config\";\r\nimport { colors } from \"@mongez/copper\";\r\nimport { pathToFileURL } from \"node:url\";\r\nimport type { FileManager } from \"../dev-server/file-manager\";\r\nimport { configSpecialHandlers } from \"./config-special-handlers\";\r\n\r\n/**\r\n * Special Config Handler\r\n * A function that handles special configuration loading\r\n */\r\n// Returns unknown, not void: ConfigSpecialHandlers.execute() RETURNS handler(config)\r\n// rather than discarding it, and a test pins that (\"returns the handler's resolved\r\n// value\"). The implementation and the test agreed; only this type said handlers\r\n// produce nothing, which made any value-returning handler fail to typecheck.\r\nexport type SpecialConfigHandler = (configValue: any) => unknown | Promise<unknown>;\r\n\r\n/**\r\n * Config Loader\r\n * Dynamically loads all configuration files and registers them with @mongez/config\r\n * Supports special handlers for configs that require additional processing\r\n */\r\nexport class ConfigLoader {\r\n public async loadAll(configFiles: FileManager[]): Promise<void> {\r\n for (const file of configFiles) {\r\n await this.loadConfig(file);\r\n }\r\n }\r\n\r\n /**\r\n * Load a single configuration file.\r\n *\r\n * The ESM loader hook stamps a version token onto the URL so that each HMR\r\n * cycle gets a fresh module — no manual cache-busting needed here.\r\n */\r\n public async loadConfig(file: FileManager): Promise<void> {\r\n const configName = this.getConfigName(file.relativePath);\r\n\r\n try {\r\n const fileUrl = pathToFileURL(file.absolutePath).href;\r\n const configModule = await import(fileUrl);\r\n const configValue = configModule.default;\r\n\r\n if (configValue === undefined) {\r\n console.log(\r\n colors.red(`config error: `),\r\n `Config file ${colors.yellow(file.relativePath)} does not have a default export`,\r\n );\r\n return;\r\n }\r\n\r\n config.set(configName, configValue);\r\n await configSpecialHandlers.execute(configName, configValue);\r\n } catch (error) {\r\n throw error;\r\n }\r\n }\r\n\r\n public async reloadConfig(file: FileManager): Promise<void> {\r\n await this.loadConfig(file);\r\n }\r\n\r\n private getConfigName(relativePath: string): string {\r\n const match = relativePath.match(/^src\\/config\\/(.+)\\.(ts|tsx)$/);\r\n\r\n if (!match) {\r\n throw new Error(`Invalid config file path: ${relativePath}`);\r\n }\r\n\r\n return match[1];\r\n }\r\n}\r\n"],"mappings":";;;;;;;;;;;AAqBA,IAAa,eAAb,MAA0B;CACxB,MAAa,QAAQ,aAA2C;EAC9D,KAAK,MAAM,QAAQ,aACjB,MAAM,KAAK,WAAW,IAAI;CAE9B;;;;;;;CAQA,MAAa,WAAW,MAAkC;EACxD,MAAM,aAAa,KAAK,cAAc,KAAK,YAAY;EAEvD,IAAI;GAGF,MAAM,eAAc,MADO,OADX,cAAc,KAAK,YAAY,CAAC,CAAC,MAEjB,CAAC;GAEjC,IAAI,gBAAgB,QAAW;IAC7B,QAAQ,IACN,OAAO,IAAI,gBAAgB,GAC3B,eAAe,OAAO,OAAO,KAAK,YAAY,EAAE,gCAClD;IACA;GACF;GAEA,OAAO,IAAI,YAAY,WAAW;GAClC,MAAM,sBAAsB,QAAQ,YAAY,WAAW;EAC7D,SAAS,OAAO;GACd,MAAM;EACR;CACF;CAEA,MAAa,aAAa,MAAkC;EAC1D,MAAM,KAAK,WAAW,IAAI;CAC5B;CAEA,AAAQ,cAAc,cAA8B;EAClD,MAAM,QAAQ,aAAa,MAAM,+BAA+B;EAEhE,IAAI,CAAC,OACH,MAAM,IAAI,MAAM,6BAA6B,cAAc;EAG7D,OAAO,MAAM;CACf;AACF"}
1
+ {"version":3,"file":"config-loader.mjs","names":[],"sources":["../../../../../../../core/src/config/config-loader.ts"],"sourcesContent":["import config from \"@mongez/config\";\r\nimport { colors } from \"@mongez/copper\";\r\nimport { pathToFileURL } from \"node:url\";\r\nimport type { FileManager } from \"../dev-server/file-manager\";\r\nimport { configSpecialHandlers } from \"./config-special-handlers\";\r\n\r\n/**\r\n * Special Config Handler\r\n * A function that handles special configuration loading\r\n */\r\n// Returns unknown, not void: ConfigSpecialHandlers.execute() RETURNS handler(config)\r\n// rather than discarding it, and a test pins that (\"returns the handler's resolved\r\n// value\"). The implementation and the test agreed; only this type said handlers\r\n// produce nothing, which made any value-returning handler fail to typecheck.\r\nexport type SpecialConfigHandler = (configValue: any) => unknown | Promise<unknown>;\r\n\r\n/**\r\n * Config Loader\r\n * Dynamically loads all configuration files and registers them with @mongez/config\r\n * Supports special handlers for configs that require additional processing\r\n */\r\nexport class ConfigLoader {\r\n public async loadAll(configFiles: FileManager[]): Promise<void> {\r\n for (const file of configFiles) {\r\n await this.loadConfig(file);\r\n }\r\n }\r\n\r\n /**\r\n * Load a single configuration file.\r\n *\r\n * The ESM loader hook stamps a version token onto the URL so that each HMR\r\n * cycle gets a fresh module — no manual cache-busting needed here.\r\n */\r\n public async loadConfig(file: FileManager): Promise<void> {\r\n const configName = this.getConfigName(file.relativePath);\r\n\r\n try {\r\n const fileUrl = pathToFileURL(file.absolutePath).href;\r\n const configModule = await import(fileUrl);\r\n const configValue = configModule.default;\r\n\r\n if (configValue === undefined) {\r\n console.log(\r\n colors.red(`config error: `),\r\n `Config file ${colors.yellow(file.relativePath)} does not have a default export`,\r\n );\r\n return;\r\n }\r\n\r\n config.set(configName, configValue);\r\n await configSpecialHandlers.execute(configName, configValue);\r\n } catch (error) {\r\n throw error;\r\n }\r\n }\r\n\r\n public async reloadConfig(file: FileManager): Promise<void> {\r\n await this.loadConfig(file);\r\n }\r\n\r\n private getConfigName(relativePath: string): string {\r\n const match = relativePath.match(/^src\\/config\\/(.+)\\.(ts|tsx)$/);\r\n\r\n if (!match) {\r\n throw new Error(`Invalid config file path: ${relativePath}`);\r\n }\r\n\r\n const configName = match[1];\n\n if (!configName) {\n throw new Error(`Invalid config file path: ${relativePath}`);\n }\n\n return configName;\n }\r\n}\r\n"],"mappings":";;;;;;;;;;;AAqBA,IAAa,eAAb,MAA0B;CACxB,MAAa,QAAQ,aAA2C;EAC9D,KAAK,MAAM,QAAQ,aACjB,MAAM,KAAK,WAAW,IAAI;CAE9B;;;;;;;CAQA,MAAa,WAAW,MAAkC;EACxD,MAAM,aAAa,KAAK,cAAc,KAAK,YAAY;EAEvD,IAAI;GAGF,MAAM,eAAc,MADO,OADX,cAAc,KAAK,YAAY,CAAC,CAAC,MAEjB,CAAC;GAEjC,IAAI,gBAAgB,QAAW;IAC7B,QAAQ,IACN,OAAO,IAAI,gBAAgB,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AoGD,QAAA"}
1
+ {"version":3,"file":"dependency-graph.d.mts","names":[],"sources":["../../../../../../../core/src/dev-server/dependency-graph.ts"],"mappings":";;;;;AAYA;;;;;;;;cAAa,eAAA;EA0L4B;;;;;EAAA,QApL/B,YAAA;EAkBY;;;;;EAAA,QAXZ,UAAA;EAiD+C;;;;EAAA,QA3C/C,KAAA;EA8EU;;;EAzEX,KAAA,CAAM,KAAA,EAAO,GAAA,SAAY,WAAA;EA2G9B;;;;;;;;;EArEK,aAAA,CAAc,IAAA,UAAc,UAAA,UAAoB,UAAA;EA4HlC;;;;;EAlGd,gBAAA,CAAiB,IAAA,UAAc,UAAA;EA+M9B;;;;EAtMD,UAAA,CAAW,IAAA;;;;;;;;;;;;EAgCX,UAAA,CACL,IAAA,UACA,eAAA,EAAiB,GAAA,UACjB,oBAAA,GAAsB,GAAA;;;;;;EA+BjB,eAAA,CAAgB,IAAA,WAAe,GAAA;;;;;EAc/B,cAAA,CAAe,IAAA,UAAc,UAAA;;;;;;EAS7B,aAAA,CAAc,IAAA,WAAe,GAAA;;;;;;;;EAW7B,oBAAA,CAAqB,IAAA;;;;;;;;;;;;;EA+BrB,0BAAA;;;;;;;UA2CC,cAAA;;;;;UAwBA,iCAAA;;;;EAwGD,QAAA"}
@@ -186,6 +186,7 @@ var DependencyGraph = class {
186
186
  for (let index = 0; index < cycle.length - 1; index++) {
187
187
  const from = cycle[index];
188
188
  const to = cycle[index + 1];
189
+ if (from === void 0 || to === void 0) continue;
189
190
  if (this.isEdgeTypeOnly(from, to)) return false;
190
191
  }
191
192
  return true;
@@ -224,7 +225,7 @@ var DependencyGraph = class {
224
225
  console.log(colors.dim("━".repeat(60)));
225
226
  console.log(colors.yellow("💡 How to Fix:"));
226
227
  console.log("");
227
- const exampleCycle = cycles[0];
228
+ const exampleCycle = cycles[0] ?? [];
228
229
  const fileA = exampleCycle[0]?.split("/").pop() || "fileA.ts";
229
230
  const fileB = exampleCycle[1]?.split("/").pop() || "fileB.ts";
230
231
  const stripExt = (file) => file.replace(/\.tsx?$/, "");
@@ -1 +1 @@
1
- {"version":3,"file":"dependency-graph.mjs","names":[],"sources":["../../../../../../../core/src/dev-server/dependency-graph.ts"],"sourcesContent":["import type { FileManager } from \"./file-manager\";\r\n\r\n/**\r\n * Dependency Graph\r\n * Tracks bidirectional relationships between files:\r\n * - dependencies: files that this file imports\r\n * - dependents: files that import this file\r\n *\r\n * Each forward edge also carries an `isTypeOnly` flag so cycle detection\r\n * can distinguish runtime cycles from ones formed purely by `import type`\r\n * edges — the latter are erased by TypeScript and have no runtime effect.\r\n */\r\nexport class DependencyGraph {\r\n /**\r\n * Map of file -> files it depends on (imports).\r\n * Key: relative file path.\r\n * Value: relative dependency path → `{ isTypeOnly }` for that edge.\r\n */\r\n private dependencies = new Map<string, Map<string, { isTypeOnly: boolean }>>();\r\n\r\n /**\r\n * Map of file -> files that depend on it (importers)\r\n * Key: relative file path\r\n * Value: Set of relative file paths that import this file\r\n */\r\n private dependents = new Map<string, Set<string>>();\r\n\r\n /**\r\n * Reference to the files map for accessing FileManager instances\r\n * Used to read per-file typeOnlyDependencies during graph build.\r\n */\r\n private files: Map<string, FileManager> | null = null;\r\n\r\n /**\r\n * Build dependency graph from FileManager map\r\n */\r\n public build(files: Map<string, FileManager>) {\r\n this.files = files;\r\n\r\n this.dependencies.clear();\r\n this.dependents.clear();\r\n\r\n for (const [relativePath, fileManager] of files) {\r\n if (!this.dependencies.has(relativePath)) {\r\n this.dependencies.set(relativePath, new Map());\r\n }\r\n\r\n if (!this.dependents.has(relativePath)) {\r\n this.dependents.set(relativePath, new Set());\r\n }\r\n\r\n for (const dependency of fileManager.dependencies) {\r\n const isTypeOnly = fileManager.typeOnlyDependencies.has(dependency);\r\n\r\n this.addDependency(relativePath, dependency, isTypeOnly);\r\n }\r\n }\r\n\r\n const cycles = this.detectCircularDependencies();\r\n\r\n if (cycles.length > 0) {\r\n this.displayCircularDependencyWarnings(cycles);\r\n }\r\n }\r\n\r\n /**\r\n * Add a dependency relationship.\r\n * If the edge already exists, the type-only flag is ANDed: any runtime\r\n * statement between the two files makes the edge runtime permanently.\r\n *\r\n * @param file The file that has the dependency\r\n * @param dependency The file being depended upon\r\n * @param isTypeOnly Whether every reference from `file` to `dependency` is type-only\r\n */\r\n public addDependency(file: string, dependency: string, isTypeOnly: boolean = false) {\r\n if (!this.dependencies.has(file)) {\r\n this.dependencies.set(file, new Map());\r\n }\r\n\r\n if (!this.dependents.has(dependency)) {\r\n this.dependents.set(dependency, new Set());\r\n }\r\n\r\n const edges = this.dependencies.get(file)!;\r\n const existing = edges.get(dependency);\r\n\r\n if (existing) {\r\n existing.isTypeOnly = existing.isTypeOnly && isTypeOnly;\r\n } else {\r\n edges.set(dependency, { isTypeOnly });\r\n }\r\n\r\n this.dependents.get(dependency)!.add(file);\r\n }\r\n\r\n /**\r\n * Remove a dependency relationship\r\n * @param file The file that has the dependency\r\n * @param dependency The file being depended upon\r\n */\r\n public removeDependency(file: string, dependency: string) {\r\n this.dependencies.get(file)?.delete(dependency);\r\n this.dependents.get(dependency)?.delete(file);\r\n }\r\n\r\n /**\r\n * Remove all relationships for a file\r\n * @param file The file to remove\r\n */\r\n public removeFile(file: string) {\r\n const deps = this.dependencies.get(file);\r\n\r\n if (deps) {\r\n for (const dependency of deps.keys()) {\r\n this.dependents.get(dependency)?.delete(file);\r\n }\r\n }\r\n\r\n const dependents = this.dependents.get(file);\r\n\r\n if (dependents) {\r\n for (const dependent of dependents) {\r\n this.dependencies.get(dependent)?.delete(file);\r\n }\r\n }\r\n\r\n this.dependencies.delete(file);\r\n this.dependents.delete(file);\r\n }\r\n\r\n /**\r\n * Update dependencies for a file.\r\n *\r\n * Accepts the updated `Set<string>` of dependency paths; when the caller\r\n * has per-edge type-only info, pass `typeOnlyDependencies` so the new\r\n * edges get the correct flag. Missing flag defaults to runtime.\r\n *\r\n * @param file The file to update\r\n * @param newDependencies New set of dependency paths\r\n * @param typeOnlyDependencies Subset of `newDependencies` whose edges are type-only\r\n */\r\n public updateFile(\r\n file: string,\r\n newDependencies: Set<string>,\r\n typeOnlyDependencies: Set<string> = new Set(),\r\n ) {\r\n const oldEdges = this.dependencies.get(file) ?? new Map<string, { isTypeOnly: boolean }>();\r\n\r\n for (const oldDep of oldEdges.keys()) {\r\n if (!newDependencies.has(oldDep)) {\r\n this.removeDependency(file, oldDep);\r\n }\r\n }\r\n\r\n for (const newDep of newDependencies) {\r\n const isTypeOnly = typeOnlyDependencies.has(newDep);\r\n const existing = oldEdges.get(newDep);\r\n\r\n if (!existing) {\r\n this.addDependency(file, newDep, isTypeOnly);\r\n\r\n continue;\r\n }\r\n\r\n if (existing.isTypeOnly !== isTypeOnly) {\r\n existing.isTypeOnly = isTypeOnly;\r\n }\r\n }\r\n }\r\n\r\n /**\r\n * Get files that this file depends on (imports)\r\n * @param file The file to check\r\n * @returns Set of files this file imports\r\n */\r\n public getDependencies(file: string): Set<string> {\r\n const edges = this.dependencies.get(file);\r\n\r\n if (!edges) {\r\n return new Set();\r\n }\r\n\r\n return new Set(edges.keys());\r\n }\r\n\r\n /**\r\n * Check whether the edge `file → dependency` is type-only.\r\n * Returns false if the edge does not exist.\r\n */\r\n public isEdgeTypeOnly(file: string, dependency: string): boolean {\r\n return this.dependencies.get(file)?.get(dependency)?.isTypeOnly === true;\r\n }\r\n\r\n /**\r\n * Get files that depend on this file (importers)\r\n * @param file The file to check\r\n * @returns Set of files that import this file\r\n */\r\n public getDependents(file: string): Set<string> {\r\n return this.dependents.get(file) || new Set();\r\n }\r\n\r\n /**\r\n * Get invalidation chain for a file\r\n * Returns all files that need to be reloaded when this file changes\r\n * Includes the file itself and all transitive dependents\r\n * @param file The file that changed\r\n * @returns Array of files to invalidate (in order)\r\n */\r\n public getInvalidationChain(file: string): string[] {\r\n const chain: string[] = [file];\r\n const visited = new Set([file]);\r\n\r\n const traverse = (current: string) => {\r\n const deps = this.getDependents(current);\r\n for (const dep of deps) {\r\n if (!visited.has(dep)) {\r\n visited.add(dep);\r\n chain.push(dep);\r\n traverse(dep); // Recursive traversal\r\n }\r\n }\r\n };\r\n\r\n traverse(file);\r\n return chain;\r\n }\r\n\r\n /**\r\n * Detect circular dependencies in the dependency graph.\r\n * Uses depth-first search to find cycles.\r\n *\r\n * Filtering rule (per-edge): a cycle is suppressed when **any** edge in\r\n * the chain is type-only. TypeScript erases type-only imports entirely,\r\n * so a single type-only edge breaks the cycle at runtime. Only warn when\r\n * every edge is a runtime binding — that's the cycle that actually loops\r\n * at load time.\r\n *\r\n * @returns Array of circular dependency chains (each chain is an array of file paths)\r\n */\r\n public detectCircularDependencies(): string[][] {\r\n const cycles: string[][] = [];\r\n const visited = new Set<string>();\r\n const recursionStack = new Set<string>();\r\n\r\n const dfs = (file: string, path: string[]): void => {\r\n visited.add(file);\r\n recursionStack.add(file);\r\n path.push(file);\r\n\r\n const edges = this.dependencies.get(file);\r\n\r\n if (edges) {\r\n for (const dep of edges.keys()) {\r\n if (!visited.has(dep)) {\r\n dfs(dep, [...path]);\r\n } else if (recursionStack.has(dep)) {\r\n const cycleStart = path.indexOf(dep);\r\n const cycle = [...path.slice(cycleStart), dep];\r\n\r\n cycles.push(cycle);\r\n }\r\n }\r\n }\r\n\r\n recursionStack.delete(file);\r\n };\r\n\r\n for (const file of this.dependencies.keys()) {\r\n if (!visited.has(file)) {\r\n dfs(file, []);\r\n }\r\n }\r\n\r\n return cycles.filter((cycle) => this.isRuntimeCycle(cycle));\r\n }\r\n\r\n /**\r\n * True iff every edge in the cycle is a runtime binding. The cycle array\r\n * ends with a duplicate of its start (`[A, B, C, A]`) so we walk the\r\n * consecutive pairs once — any type-only edge means TS erases the loop\r\n * and there is no runtime cycle to report.\r\n */\r\n private isRuntimeCycle(cycle: string[]): boolean {\r\n for (let index = 0; index < cycle.length - 1; index++) {\r\n const from = cycle[index];\r\n const to = cycle[index + 1];\r\n\r\n if (this.isEdgeTypeOnly(from, to)) {\r\n return false;\r\n }\r\n }\r\n\r\n return true;\r\n }\r\n\r\n /**\r\n * Display circular dependency warnings in a formatted, user-friendly way\r\n * Shows each cycle with visual tree structure and helpful recommendations\r\n */\r\n private displayCircularDependencyWarnings(cycles: string[][]): void {\r\n const colors = {\r\n yellow: (text: string) => `\\x1b[33m${text}\\x1b[0m`,\r\n cyan: (text: string) => `\\x1b[36m${text}\\x1b[0m`,\r\n dim: (text: string) => `\\x1b[2m${text}\\x1b[0m`,\r\n bold: (text: string) => `\\x1b[1m${text}\\x1b[0m`,\r\n green: (text: string) => `\\x1b[32m${text}\\x1b[0m`,\r\n };\r\n\r\n console.log(\"\");\r\n console.log(colors.yellow(\"⚠️ Circular Dependencies Detected\"));\r\n console.log(colors.dim(\"━\".repeat(60)));\r\n console.log(\"\");\r\n console.log(\r\n colors.dim(\r\n `Found ${colors.bold(cycles.length.toString())} circular dependency chain${cycles.length > 1 ? \"s\" : \"\"}`,\r\n ),\r\n );\r\n console.log(\"\");\r\n\r\n cycles.forEach((cycle, index) => {\r\n console.log(colors.cyan(` ${index + 1}. Cycle with ${cycle.length - 1} files:`));\r\n console.log(\"\");\r\n\r\n // Display the cycle chain\r\n cycle.forEach((file, fileIndex) => {\r\n const isLast = fileIndex === cycle.length - 1;\r\n const arrow = isLast ? colors.dim(\" └─→ \") : colors.dim(\" ├─→ \");\r\n const fileName = file.split(\"/\").pop() || file;\r\n const filePath = colors.dim(file.replace(fileName, \"\"));\r\n\r\n if (isLast) {\r\n // Last item is the same as first (completes the cycle)\r\n console.log(\r\n arrow + colors.yellow(`${filePath}${colors.bold(fileName)} (cycle completes)`),\r\n );\r\n } else {\r\n console.log(arrow + filePath + colors.bold(fileName));\r\n }\r\n });\r\n\r\n console.log(\"\");\r\n });\r\n\r\n console.log(colors.dim(\"━\".repeat(60)));\r\n console.log(colors.yellow(\"💡 How to Fix:\"));\r\n console.log(\"\");\r\n\r\n const exampleCycle = cycles[0];\r\n const fileA = exampleCycle[0]?.split(\"/\").pop() || \"fileA.ts\";\r\n const fileB = exampleCycle[1]?.split(\"/\").pop() || \"fileB.ts\";\r\n const stripExt = (file: string) => file.replace(/\\.tsx?$/, \"\");\r\n\r\n const kind = classifyCycle(exampleCycle);\r\n\r\n if (kind === \"resource\" || kind === \"model\") {\r\n // Cascade's `lazy()` is purpose-built for circular relations between\r\n // resources and models — recommend it first, not as a footnote.\r\n console.log(colors.green(` ✨ Use lazy() for the back-reference`));\r\n console.log(\r\n colors.dim(\r\n ` ${kind === \"resource\" ? \"Resources\" : \"Models\"} that reference each other should declare`,\r\n ),\r\n );\r\n console.log(colors.dim(` one side with lazy() so the import resolves at access time:`));\r\n console.log(\"\");\r\n console.log(colors.dim(` import { lazy } from \"@warlock.js/cascade\";`));\r\n console.log(colors.dim(` // inside ${fileB}:`));\r\n console.log(\r\n colors.dim(\r\n ` other: lazy(() => ${kind === \"resource\" ? \"OtherResource\" : \"OtherModel\"})`,\r\n ),\r\n );\r\n console.log(\"\");\r\n } else {\r\n // Generic cycle — dynamic import is the most common reliable fix.\r\n console.log(colors.green(` ✨ Convert one edge to a dynamic import`));\r\n console.log(colors.dim(` In ${fileB}, change:`));\r\n console.log(colors.dim(` import { SomeClass } from \"./${stripExt(fileA)}\";`));\r\n console.log(colors.dim(` To:`));\r\n console.log(colors.dim(` const { SomeClass } = await import(\"./${stripExt(fileA)}\");`));\r\n console.log(\"\");\r\n }\r\n\r\n console.log(colors.dim(\" Other options:\"));\r\n console.log(colors.dim(\" • Extract the shared symbols into a third file both can import.\"));\r\n console.log(\r\n colors.dim(\" • Pass the dependency as a constructor/function parameter instead.\"),\r\n );\r\n console.log(\"\");\r\n\r\n console.log(colors.dim(\"━\".repeat(60)));\r\n console.log(colors.dim(\" Circular dependencies can cause HMR issues and hard-to-debug\"));\r\n console.log(colors.dim(\" initialization order problems. Consider refactoring.\"));\r\n console.log(\"\");\r\n }\r\n\r\n /**\r\n * Get statistics about the dependency graph\r\n */\r\n public getStats() {\r\n let totalDependencies = 0;\r\n let maxDependencies = 0;\r\n let maxDependents = 0;\r\n let mostDependedFile = \"\";\r\n let mostDependingFile = \"\";\r\n\r\n for (const [file, deps] of this.dependencies) {\r\n totalDependencies += deps.size;\r\n if (deps.size > maxDependencies) {\r\n maxDependencies = deps.size;\r\n mostDependingFile = file;\r\n }\r\n }\r\n\r\n for (const [file, deps] of this.dependents) {\r\n if (deps.size > maxDependents) {\r\n maxDependents = deps.size;\r\n mostDependedFile = file;\r\n }\r\n }\r\n\r\n return {\r\n totalFiles: this.dependencies.size,\r\n totalDependencies,\r\n avgDependenciesPerFile: totalDependencies / this.dependencies.size || 0,\r\n maxDependencies,\r\n maxDependents,\r\n mostDependingFile,\r\n mostDependedFile,\r\n };\r\n }\r\n}\r\n\r\n/**\r\n * Pick the most useful \"fix-it\" hint for a cycle by inspecting the file\r\n * extensions involved. Cascade resources/models have a first-class fix\r\n * (`lazy()`); generic cycles just want a dynamic import.\r\n */\r\nfunction classifyCycle(cycle: string[]): \"resource\" | \"model\" | \"generic\" {\r\n const files = cycle.slice(0, -1); // last entry repeats the first\r\n if (files.every((file) => file.endsWith(\".resource.ts\") || file.endsWith(\".resource.tsx\"))) {\r\n return \"resource\";\r\n }\r\n if (files.every((file) => file.endsWith(\".model.ts\") || file.endsWith(\".model.tsx\"))) {\r\n return \"model\";\r\n }\r\n return \"generic\";\r\n}\r\n"],"mappings":";;;;;;;;;;;AAYA,IAAa,kBAAb,MAA6B;;sCAMJ,IAAI,IAAkD;oCAOxD,IAAI,IAAyB;eAMD;;;;;CAKjD,AAAO,MAAM,OAAiC;EAC5C,KAAK,QAAQ;EAEb,KAAK,aAAa,MAAM;EACxB,KAAK,WAAW,MAAM;EAEtB,KAAK,MAAM,CAAC,cAAc,gBAAgB,OAAO;GAC/C,IAAI,CAAC,KAAK,aAAa,IAAI,YAAY,GACrC,KAAK,aAAa,IAAI,8BAAc,IAAI,IAAI,CAAC;GAG/C,IAAI,CAAC,KAAK,WAAW,IAAI,YAAY,GACnC,KAAK,WAAW,IAAI,8BAAc,IAAI,IAAI,CAAC;GAG7C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EACvB,IAAI,oBAAoB;EAExB,KAAK,MAAM,CAAC,MAAM,SAAS,KAAK,cAAc;GAC5C,qBAAqB,KAAK;GAC1B,IAAI,KAAK,OAAO,iBAAiB;IAC/B,kBAAkB,KAAK;IACvB,oBAAoB;GACtB;EACF;EAEA,KAAK,MAAM,CAAC,MAAM,SAAS,KAAK,YAC9B,IAAI,KAAK,OAAO,eAAe;GAC7B,gBAAgB,KAAK;GACrB,mBAAmB;EACrB;EAGF,OAAO;GACL,YAAY,KAAK,aAAa;GAC9B;GACA,wBAAwB,oBAAoB,KAAK,aAAa,QAAQ;GACtE;GACA;GACA;GACA;EACF;CACF;AACF;;;;;;AAOA,SAAS,cAAc,OAAmD;CACxE,MAAM,QAAQ,MAAM,MAAM,GAAG,EAAE;CAC/B,IAAI,MAAM,OAAO,SAAS,KAAK,SAAS,cAAc,KAAK,KAAK,SAAS,eAAe,CAAC,GACvF,OAAO;CAET,IAAI,MAAM,OAAO,SAAS,KAAK,SAAS,WAAW,KAAK,KAAK,SAAS,YAAY,CAAC,GACjF,OAAO;CAET,OAAO;AACT"}
1
+ {"version":3,"file":"dependency-graph.mjs","names":[],"sources":["../../../../../../../core/src/dev-server/dependency-graph.ts"],"sourcesContent":["import type { FileManager } from \"./file-manager\";\r\n\r\n/**\r\n * Dependency Graph\r\n * Tracks bidirectional relationships between files:\r\n * - dependencies: files that this file imports\r\n * - dependents: files that import this file\r\n *\r\n * Each forward edge also carries an `isTypeOnly` flag so cycle detection\r\n * can distinguish runtime cycles from ones formed purely by `import type`\r\n * edges — the latter are erased by TypeScript and have no runtime effect.\r\n */\r\nexport class DependencyGraph {\r\n /**\r\n * Map of file -> files it depends on (imports).\r\n * Key: relative file path.\r\n * Value: relative dependency path → `{ isTypeOnly }` for that edge.\r\n */\r\n private dependencies = new Map<string, Map<string, { isTypeOnly: boolean }>>();\r\n\r\n /**\r\n * Map of file -> files that depend on it (importers)\r\n * Key: relative file path\r\n * Value: Set of relative file paths that import this file\r\n */\r\n private dependents = new Map<string, Set<string>>();\r\n\r\n /**\r\n * Reference to the files map for accessing FileManager instances\r\n * Used to read per-file typeOnlyDependencies during graph build.\r\n */\r\n private files: Map<string, FileManager> | null = null;\r\n\r\n /**\r\n * Build dependency graph from FileManager map\r\n */\r\n public build(files: Map<string, FileManager>) {\r\n this.files = files;\r\n\r\n this.dependencies.clear();\r\n this.dependents.clear();\r\n\r\n for (const [relativePath, fileManager] of files) {\r\n if (!this.dependencies.has(relativePath)) {\r\n this.dependencies.set(relativePath, new Map());\r\n }\r\n\r\n if (!this.dependents.has(relativePath)) {\r\n this.dependents.set(relativePath, new Set());\r\n }\r\n\r\n for (const dependency of fileManager.dependencies) {\r\n const isTypeOnly = fileManager.typeOnlyDependencies.has(dependency);\r\n\r\n this.addDependency(relativePath, dependency, isTypeOnly);\r\n }\r\n }\r\n\r\n const cycles = this.detectCircularDependencies();\r\n\r\n if (cycles.length > 0) {\r\n this.displayCircularDependencyWarnings(cycles);\r\n }\r\n }\r\n\r\n /**\r\n * Add a dependency relationship.\r\n * If the edge already exists, the type-only flag is ANDed: any runtime\r\n * statement between the two files makes the edge runtime permanently.\r\n *\r\n * @param file The file that has the dependency\r\n * @param dependency The file being depended upon\r\n * @param isTypeOnly Whether every reference from `file` to `dependency` is type-only\r\n */\r\n public addDependency(file: string, dependency: string, isTypeOnly: boolean = false) {\r\n if (!this.dependencies.has(file)) {\r\n this.dependencies.set(file, new Map());\r\n }\r\n\r\n if (!this.dependents.has(dependency)) {\r\n this.dependents.set(dependency, new Set());\r\n }\r\n\r\n const edges = this.dependencies.get(file)!;\r\n const existing = edges.get(dependency);\r\n\r\n if (existing) {\r\n existing.isTypeOnly = existing.isTypeOnly && isTypeOnly;\r\n } else {\r\n edges.set(dependency, { isTypeOnly });\r\n }\r\n\r\n this.dependents.get(dependency)!.add(file);\r\n }\r\n\r\n /**\r\n * Remove a dependency relationship\r\n * @param file The file that has the dependency\r\n * @param dependency The file being depended upon\r\n */\r\n public removeDependency(file: string, dependency: string) {\r\n this.dependencies.get(file)?.delete(dependency);\r\n this.dependents.get(dependency)?.delete(file);\r\n }\r\n\r\n /**\r\n * Remove all relationships for a file\r\n * @param file The file to remove\r\n */\r\n public removeFile(file: string) {\r\n const deps = this.dependencies.get(file);\r\n\r\n if (deps) {\r\n for (const dependency of deps.keys()) {\r\n this.dependents.get(dependency)?.delete(file);\r\n }\r\n }\r\n\r\n const dependents = this.dependents.get(file);\r\n\r\n if (dependents) {\r\n for (const dependent of dependents) {\r\n this.dependencies.get(dependent)?.delete(file);\r\n }\r\n }\r\n\r\n this.dependencies.delete(file);\r\n this.dependents.delete(file);\r\n }\r\n\r\n /**\r\n * Update dependencies for a file.\r\n *\r\n * Accepts the updated `Set<string>` of dependency paths; when the caller\r\n * has per-edge type-only info, pass `typeOnlyDependencies` so the new\r\n * edges get the correct flag. Missing flag defaults to runtime.\r\n *\r\n * @param file The file to update\r\n * @param newDependencies New set of dependency paths\r\n * @param typeOnlyDependencies Subset of `newDependencies` whose edges are type-only\r\n */\r\n public updateFile(\r\n file: string,\r\n newDependencies: Set<string>,\r\n typeOnlyDependencies: Set<string> = new Set(),\r\n ) {\r\n const oldEdges = this.dependencies.get(file) ?? new Map<string, { isTypeOnly: boolean }>();\r\n\r\n for (const oldDep of oldEdges.keys()) {\r\n if (!newDependencies.has(oldDep)) {\r\n this.removeDependency(file, oldDep);\r\n }\r\n }\r\n\r\n for (const newDep of newDependencies) {\r\n const isTypeOnly = typeOnlyDependencies.has(newDep);\r\n const existing = oldEdges.get(newDep);\r\n\r\n if (!existing) {\r\n this.addDependency(file, newDep, isTypeOnly);\r\n\r\n continue;\r\n }\r\n\r\n if (existing.isTypeOnly !== isTypeOnly) {\r\n existing.isTypeOnly = isTypeOnly;\r\n }\r\n }\r\n }\r\n\r\n /**\r\n * Get files that this file depends on (imports)\r\n * @param file The file to check\r\n * @returns Set of files this file imports\r\n */\r\n public getDependencies(file: string): Set<string> {\r\n const edges = this.dependencies.get(file);\r\n\r\n if (!edges) {\r\n return new Set();\r\n }\r\n\r\n return new Set(edges.keys());\r\n }\r\n\r\n /**\r\n * Check whether the edge `file → dependency` is type-only.\r\n * Returns false if the edge does not exist.\r\n */\r\n public isEdgeTypeOnly(file: string, dependency: string): boolean {\r\n return this.dependencies.get(file)?.get(dependency)?.isTypeOnly === true;\r\n }\r\n\r\n /**\r\n * Get files that depend on this file (importers)\r\n * @param file The file to check\r\n * @returns Set of files that import this file\r\n */\r\n public getDependents(file: string): Set<string> {\r\n return this.dependents.get(file) || new Set();\r\n }\r\n\r\n /**\r\n * Get invalidation chain for a file\r\n * Returns all files that need to be reloaded when this file changes\r\n * Includes the file itself and all transitive dependents\r\n * @param file The file that changed\r\n * @returns Array of files to invalidate (in order)\r\n */\r\n public getInvalidationChain(file: string): string[] {\r\n const chain: string[] = [file];\r\n const visited = new Set([file]);\r\n\r\n const traverse = (current: string) => {\r\n const deps = this.getDependents(current);\r\n for (const dep of deps) {\r\n if (!visited.has(dep)) {\r\n visited.add(dep);\r\n chain.push(dep);\r\n traverse(dep); // Recursive traversal\r\n }\r\n }\r\n };\r\n\r\n traverse(file);\r\n return chain;\r\n }\r\n\r\n /**\r\n * Detect circular dependencies in the dependency graph.\r\n * Uses depth-first search to find cycles.\r\n *\r\n * Filtering rule (per-edge): a cycle is suppressed when **any** edge in\r\n * the chain is type-only. TypeScript erases type-only imports entirely,\r\n * so a single type-only edge breaks the cycle at runtime. Only warn when\r\n * every edge is a runtime binding — that's the cycle that actually loops\r\n * at load time.\r\n *\r\n * @returns Array of circular dependency chains (each chain is an array of file paths)\r\n */\r\n public detectCircularDependencies(): string[][] {\r\n const cycles: string[][] = [];\r\n const visited = new Set<string>();\r\n const recursionStack = new Set<string>();\r\n\r\n const dfs = (file: string, path: string[]): void => {\r\n visited.add(file);\r\n recursionStack.add(file);\r\n path.push(file);\r\n\r\n const edges = this.dependencies.get(file);\r\n\r\n if (edges) {\r\n for (const dep of edges.keys()) {\r\n if (!visited.has(dep)) {\r\n dfs(dep, [...path]);\r\n } else if (recursionStack.has(dep)) {\r\n const cycleStart = path.indexOf(dep);\r\n const cycle = [...path.slice(cycleStart), dep];\r\n\r\n cycles.push(cycle);\r\n }\r\n }\r\n }\r\n\r\n recursionStack.delete(file);\r\n };\r\n\r\n for (const file of this.dependencies.keys()) {\r\n if (!visited.has(file)) {\r\n dfs(file, []);\r\n }\r\n }\r\n\r\n return cycles.filter((cycle) => this.isRuntimeCycle(cycle));\r\n }\r\n\r\n /**\r\n * True iff every edge in the cycle is a runtime binding. The cycle array\r\n * ends with a duplicate of its start (`[A, B, C, A]`) so we walk the\r\n * consecutive pairs once — any type-only edge means TS erases the loop\r\n * and there is no runtime cycle to report.\r\n */\r\n private isRuntimeCycle(cycle: string[]): boolean {\r\n for (let index = 0; index < cycle.length - 1; index++) {\r\n const from = cycle[index];\r\n const to = cycle[index + 1];\r\n\r\n // `index < cycle.length - 1` bounds both reads. Skipping an unreadable\r\n // edge rather than defaulting: this decides whether a cycle is\r\n // TYPE-ONLY, and a `?? \"\"` would ask `isEdgeTypeOnly(\"\", \"\")`, whose\r\n // answer is about a pair of edges that do not exist. A cycle wrongly\r\n // classified as type-only is a real circular import reported as harmless.\r\n if (from === undefined || to === undefined) continue;\r\n\r\n if (this.isEdgeTypeOnly(from, to)) {\r\n return false;\r\n }\r\n }\r\n\r\n return true;\r\n }\r\n\r\n /**\r\n * Display circular dependency warnings in a formatted, user-friendly way\r\n * Shows each cycle with visual tree structure and helpful recommendations\r\n */\r\n private displayCircularDependencyWarnings(cycles: string[][]): void {\r\n const colors = {\r\n yellow: (text: string) => `\\x1b[33m${text}\\x1b[0m`,\r\n cyan: (text: string) => `\\x1b[36m${text}\\x1b[0m`,\r\n dim: (text: string) => `\\x1b[2m${text}\\x1b[0m`,\r\n bold: (text: string) => `\\x1b[1m${text}\\x1b[0m`,\r\n green: (text: string) => `\\x1b[32m${text}\\x1b[0m`,\r\n };\r\n\r\n console.log(\"\");\r\n console.log(colors.yellow(\"⚠️ Circular Dependencies Detected\"));\r\n console.log(colors.dim(\"━\".repeat(60)));\r\n console.log(\"\");\r\n console.log(\r\n colors.dim(\r\n `Found ${colors.bold(cycles.length.toString())} circular dependency chain${cycles.length > 1 ? \"s\" : \"\"}`,\r\n ),\r\n );\r\n console.log(\"\");\r\n\r\n cycles.forEach((cycle, index) => {\r\n console.log(colors.cyan(` ${index + 1}. Cycle with ${cycle.length - 1} files:`));\r\n console.log(\"\");\r\n\r\n // Display the cycle chain\r\n cycle.forEach((file, fileIndex) => {\r\n const isLast = fileIndex === cycle.length - 1;\r\n const arrow = isLast ? colors.dim(\" └─→ \") : colors.dim(\" ├─→ \");\r\n const fileName = file.split(\"/\").pop() || file;\r\n const filePath = colors.dim(file.replace(fileName, \"\"));\r\n\r\n if (isLast) {\r\n // Last item is the same as first (completes the cycle)\r\n console.log(\r\n arrow + colors.yellow(`${filePath}${colors.bold(fileName)} (cycle completes)`),\r\n );\r\n } else {\r\n console.log(arrow + filePath + colors.bold(fileName));\r\n }\r\n });\r\n\r\n console.log(\"\");\r\n });\r\n\r\n console.log(colors.dim(\"━\".repeat(60)));\r\n console.log(colors.yellow(\"💡 How to Fix:\"));\r\n console.log(\"\");\r\n\r\n // This whole block prints \"How to Fix\" advice for a cycle that was just\r\n // reported, so there is always one — but this is diagnostic OUTPUT, and a\r\n // formatter that throws while explaining a problem replaces the problem\r\n // with itself. An empty list simply has no example to show.\r\n const exampleCycle = cycles[0] ?? [];\r\n const fileA = exampleCycle[0]?.split(\"/\").pop() || \"fileA.ts\";\r\n const fileB = exampleCycle[1]?.split(\"/\").pop() || \"fileB.ts\";\r\n const stripExt = (file: string) => file.replace(/\\.tsx?$/, \"\");\r\n\r\n const kind = classifyCycle(exampleCycle);\r\n\r\n if (kind === \"resource\" || kind === \"model\") {\r\n // Cascade's `lazy()` is purpose-built for circular relations between\r\n // resources and models — recommend it first, not as a footnote.\r\n console.log(colors.green(` ✨ Use lazy() for the back-reference`));\r\n console.log(\r\n colors.dim(\r\n ` ${kind === \"resource\" ? \"Resources\" : \"Models\"} that reference each other should declare`,\r\n ),\r\n );\r\n console.log(colors.dim(` one side with lazy() so the import resolves at access time:`));\r\n console.log(\"\");\r\n console.log(colors.dim(` import { lazy } from \"@warlock.js/cascade\";`));\r\n console.log(colors.dim(` // inside ${fileB}:`));\r\n console.log(\r\n colors.dim(\r\n ` other: lazy(() => ${kind === \"resource\" ? \"OtherResource\" : \"OtherModel\"})`,\r\n ),\r\n );\r\n console.log(\"\");\r\n } else {\r\n // Generic cycle — dynamic import is the most common reliable fix.\r\n console.log(colors.green(` ✨ Convert one edge to a dynamic import`));\r\n console.log(colors.dim(` In ${fileB}, change:`));\r\n console.log(colors.dim(` import { SomeClass } from \"./${stripExt(fileA)}\";`));\r\n console.log(colors.dim(` To:`));\r\n console.log(colors.dim(` const { SomeClass } = await import(\"./${stripExt(fileA)}\");`));\r\n console.log(\"\");\r\n }\r\n\r\n console.log(colors.dim(\" Other options:\"));\r\n console.log(colors.dim(\" • Extract the shared symbols into a third file both can import.\"));\r\n console.log(\r\n colors.dim(\" • Pass the dependency as a constructor/function parameter instead.\"),\r\n );\r\n console.log(\"\");\r\n\r\n console.log(colors.dim(\"━\".repeat(60)));\r\n console.log(colors.dim(\" Circular dependencies can cause HMR issues and hard-to-debug\"));\r\n console.log(colors.dim(\" initialization order problems. Consider refactoring.\"));\r\n console.log(\"\");\r\n }\r\n\r\n /**\r\n * Get statistics about the dependency graph\r\n */\r\n public getStats() {\r\n let totalDependencies = 0;\r\n let maxDependencies = 0;\r\n let maxDependents = 0;\r\n let mostDependedFile = \"\";\r\n let mostDependingFile = \"\";\r\n\r\n for (const [file, deps] of this.dependencies) {\r\n totalDependencies += deps.size;\r\n if (deps.size > maxDependencies) {\r\n maxDependencies = deps.size;\r\n mostDependingFile = file;\r\n }\r\n }\r\n\r\n for (const [file, deps] of this.dependents) {\r\n if (deps.size > maxDependents) {\r\n maxDependents = deps.size;\r\n mostDependedFile = file;\r\n }\r\n }\r\n\r\n return {\r\n totalFiles: this.dependencies.size,\r\n totalDependencies,\r\n avgDependenciesPerFile: totalDependencies / this.dependencies.size || 0,\r\n maxDependencies,\r\n maxDependents,\r\n mostDependingFile,\r\n mostDependedFile,\r\n };\r\n }\r\n}\r\n\r\n/**\r\n * Pick the most useful \"fix-it\" hint for a cycle by inspecting the file\r\n * extensions involved. Cascade resources/models have a first-class fix\r\n * (`lazy()`); generic cycles just want a dynamic import.\r\n */\r\nfunction classifyCycle(cycle: string[]): \"resource\" | \"model\" | \"generic\" {\r\n const files = cycle.slice(0, -1); // last entry repeats the first\r\n if (files.every((file) => file.endsWith(\".resource.ts\") || file.endsWith(\".resource.tsx\"))) {\r\n return \"resource\";\r\n }\r\n if (files.every((file) => file.endsWith(\".model.ts\") || file.endsWith(\".model.tsx\"))) {\r\n return \"model\";\r\n }\r\n return \"generic\";\r\n}\r\n"],"mappings":";;;;;;;;;;;AAYA,IAAa,kBAAb,MAA6B;;sCAMJ,IAAI,IAAkD;oCAOxD,IAAI,IAAyB;eAMD;;;;;CAKjD,AAAO,MAAM,OAAiC;EAC5C,KAAK,QAAQ;EAEb,KAAK,aAAa,MAAM;EACxB,KAAK,WAAW,MAAM;EAEtB,KAAK,MAAM,CAAC,cAAc,gBAAgB,OAAO;GAC/C,IAAI,CAAC,KAAK,aAAa,IAAI,YAAY,GACrC,KAAK,aAAa,IAAI,8BAAc,IAAI,IAAI,CAAC;GAG/C,IAAI,CAAC,KAAK,WAAW,IAAI,YAAY,GACnC,KAAK,WAAW,IAAI,8BAAc,IAAI,IAAI,CAAC;GAG7C,KAAK,MAAM,cAAc,YAAY,cAAc;IACjD,MAAM,aAAa,YAAY,qBAAqB,IAAI,UAAU;IAElE,KAAK,cAAc,cAAc,YAAY,UAAU;GACzD;EACF;EAEA,MAAM,SAAS,KAAK,2BAA2B;EAE/C,IAAI,OAAO,SAAS,GAClB,KAAK,kCAAkC,MAAM;CAEjD;;;;;;;;;;CAWA,AAAO,cAAc,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MAAM,SAAS,KAAK,YAC9B,IAAI,KAAK,OAAO,eAAe;GAC7B,gBAAgB,KAAK;GACrB,mBAAmB;EACrB;EAGF,OAAO;GACL,YAAY,KAAK,aAAa;GAC9B;GACA,wBAAwB,oBAAoB,KAAK,aAAa,QAAQ;GACtE;GACA;GACA;GACA;EACF;CACF;AACF;;;;;;AAOA,SAAS,cAAc,OAAmD;CACxE,MAAM,QAAQ,MAAM,MAAM,GAAG,EAAE;CAC/B,IAAI,MAAM,OAAO,SAAS,KAAK,SAAS,cAAc,KAAK,KAAK,SAAS,eAAe,CAAC,GACvF,OAAO;CAET,IAAI,MAAM,OAAO,SAAS,KAAK,SAAS,WAAW,KAAK,KAAK,SAAS,YAAY,CAAC,GACjF,OAAO;CAET,OAAO;AACT"}
@@ -37,10 +37,10 @@ function formatErrorStack(stack) {
37
37
  const bare = line.match(bareFrame);
38
38
  if (!withFn && !bare) return headerDone ? colors.dim(line) : colors.bold(colors.red(line));
39
39
  headerDone = true;
40
- const fn = withFn ? withFn[2] : "";
41
- const file = withFn ? withFn[3] : bare[2];
42
- const lineNo = withFn ? withFn[4] : bare[3];
43
- const col = withFn ? withFn[5] : bare[4];
40
+ const fn = (withFn ? withFn[2] : "") ?? "";
41
+ const file = (withFn ? withFn[3] : bare?.[2]) ?? "";
42
+ const lineNo = (withFn ? withFn[4] : bare?.[3]) ?? "";
43
+ const col = (withFn ? withFn[5] : bare?.[4]) ?? "";
44
44
  const isNodeInternal = file.startsWith("node:");
45
45
  const isDep = file.includes("node_modules");
46
46
  const isFramework = /[\\/]@warlock\.js[\\/]/.test(file);
@@ -81,7 +81,9 @@ function devLogSection(title) {
81
81
  function formatModuleNotFoundError(error, suggestions) {
82
82
  const match = error.message.match(/Cannot find module '([^']+)' imported from '([^']+)'/);
83
83
  if (!match) return error.message;
84
- const [, modulePath, importerPath] = match;
84
+ const [, rawModulePath, rawImporterPath] = match;
85
+ const modulePath = rawModulePath ?? "";
86
+ const importerPath = rawImporterPath ?? "";
85
87
  const lines = [
86
88
  "",
87
89
  `${colors.red("❌ MODULE NOT FOUND")}`,
@@ -1 +1 @@
1
- {"version":3,"file":"dev-logger.mjs","names":[],"sources":["../../../../../../../core/src/dev-server/dev-logger.ts"],"sourcesContent":["import { colors } from \"@mongez/copper\";\nimport dayjs from \"dayjs\";\nimport { Path } from \"../utils/normalized-path\";\n\n/**\n * Dev server logger — Vite-style formatting helpers.\n */\n\nfunction timestamp(): string {\n return colors.dim(`${dayjs().format(\"HH:mm:ss A\")}`);\n}\n\nexport function devLog(message: string) {\n console.log(`${timestamp()} ${message}`);\n}\n\nexport function devLogSuccess(message: string) {\n console.log(`${timestamp()} ${colors.green(\"✓\")} ${colors.green(message)}`);\n}\n\n/**\n * Colourise a stack trace so the eye lands on *your* code.\n *\n * - Error header (`ReferenceError: x is not defined`) → bold red.\n * - Frames in project `src/` → highlighted: a green `›` pointer, yellow\n * function name, cyan relative path, dim `:line:col`. These are almost\n * always where the bug is.\n * - Framework (`@warlock.js`), `node_modules`, and `node:` internal frames\n * → dimmed and relativised. Still there for context, just out of the way.\n *\n * Source maps are enabled in dev, so the paths/lines here are already the\n * original `.ts` locations — this only changes how they're painted.\n */\nexport function formatErrorStack(stack: string): string {\n const frame = /^(\\s*)at (.+?) \\((.+):(\\d+):(\\d+)\\)$/;\n const bareFrame = /^(\\s*)at (.+):(\\d+):(\\d+)$/;\n let headerDone = false;\n\n return stack\n .split(\"\\n\")\n .map((line) => {\n const withFn = line.match(frame);\n const bare = line.match(bareFrame);\n\n if (!withFn && !bare) {\n // Header line(s) before the first frame.\n const painted = headerDone ? colors.dim(line) : colors.bold(colors.red(line));\n return painted;\n }\n\n headerDone = true;\n\n const fn = withFn ? withFn[2] : \"\";\n const file = withFn ? withFn[3] : bare![2];\n const lineNo = withFn ? withFn[4] : bare![3];\n const col = withFn ? withFn[5] : bare![4];\n\n const isNodeInternal = file.startsWith(\"node:\");\n const isDep = file.includes(\"node_modules\");\n const isFramework = /[\\\\/]@warlock\\.js[\\\\/]/.test(file);\n const isUserCode = !isNodeInternal && !isDep && !isFramework;\n\n const rel = isNodeInternal ? file : Path.toRelative(file);\n const loc = `:${lineNo}:${col}`;\n\n if (isUserCode) {\n return (\n ` ${colors.green(\"›\")} ${colors.dim(\"at\")} ` +\n `${colors.yellow(fn || \"<anonymous>\")} ` +\n `${colors.cyan(rel)}${colors.dim(loc)}`\n );\n }\n\n const label = fn ? `at ${fn} ${rel}${loc}` : `at ${rel}${loc}`;\n return ` ${colors.dim(label)}`;\n })\n .join(\"\\n\");\n}\n\nexport function devLogError(message: string, error?: any) {\n console.log(`${timestamp()} ${colors.red(\"✗\")} ${colors.red(message)}`);\n if (error?.stack) console.log(formatErrorStack(error.stack));\n}\n\nexport function devLogWarn(message: string) {\n console.log(`${timestamp()} ${colors.yellow(\"⚠\")} ${colors.yellow(message)}`);\n}\n\nexport function devLogInfo(message: string) {\n console.log(`${timestamp()} ${colors.cyan(message)}`);\n}\n\nexport function devLogDim(message: string) {\n console.log(`${timestamp()} ${colors.dim(message)}`);\n}\n\nexport function devLogHMR(file: string, dependents?: number) {\n const relativePath = Path.toRelative(file);\n const depInfo = dependents\n ? colors.dim(` +${dependents} module${dependents > 1 ? \"s\" : \"\"}`)\n : \"\";\n console.log(\n `${timestamp()} 🔥 ${colors.green(\"hmr update\")} ${colors.dim(relativePath)}${depInfo}`,\n );\n}\n\nexport function devLogConfig(file: string, connectors?: string[]) {\n const relativePath = Path.toRelative(file);\n const connectorInfo =\n connectors && connectors.length > 0 ? colors.dim(` → restarting ${connectors.join(\", \")}`) : \"\";\n console.log(\n `${timestamp()} ${colors.cyan(\"config reload\")} ${colors.dim(relativePath)}${connectorInfo}`,\n );\n}\n\nexport function devLogReady(message: string) {\n console.log(`\\n${timestamp()} ${colors.green(\"➜\")} ${colors.bold(message)}`);\n}\n\nexport function devLogSection(title: string) {\n console.log(`\\n${timestamp()} ${colors.bold(colors.cyan(title))}`);\n}\n\n/**\n * Format ERR_MODULE_NOT_FOUND so the displayed paths are relative to the\n * project root. The loader hook keeps source paths in the URL so we only\n * need to strip the absolute prefix — no cache-path translation any more.\n */\nexport function formatModuleNotFoundError(error: Error, suggestions?: string[]): string {\n const match = error.message.match(/Cannot find module '([^']+)' imported from '([^']+)'/);\n if (!match) return error.message;\n\n const [, modulePath, importerPath] = match;\n const lines: string[] = [\n \"\",\n `${colors.red(\"❌ MODULE NOT FOUND\")}`,\n \"\",\n `${colors.dim(\"Cannot find:\")} ${colors.cyan(Path.toRelative(modulePath))}`,\n \"\",\n `${colors.dim(\"Imported by:\")}`,\n ` ${colors.yellow(\"→\")} ${colors.white(Path.toRelative(importerPath))}`,\n ];\n\n if (suggestions && suggestions.length > 0) {\n lines.push(\"\");\n lines.push(`${colors.dim(\"Did you mean?\")}`);\n suggestions.forEach((s) => lines.push(` ${colors.cyan(\"→\")} ${colors.green(s)}`));\n }\n\n lines.push(\"\");\n return lines.join(\"\\n\");\n}\n\n/** @deprecated alias retained for older callers. Use `devLog` directly. */\nexport const devServeLog = devLog;\n"],"mappings":";;;;;;;;AAQA,SAAS,YAAoB;CAC3B,OAAO,OAAO,IAAI,GAAG,MAAM,CAAC,CAAC,OAAO,YAAY,GAAG;AACrD;AAEA,SAAgB,OAAO,SAAiB;CACtC,QAAQ,IAAI,GAAG,UAAU,EAAE,GAAG,SAAS;AACzC;AAEA,SAAgB,cAAc,SAAiB;CAC7C,QAAQ,IAAI,GAAG,UAAU,EAAE,GAAG,OAAO,MAAM,GAAG,EAAE,GAAG,OAAO,MAAM,OAAO,GAAG;AAC5E;;;;;;;;;;;;;;AAeA,SAAgB,iBAAiB,OAAuB;CACtD,MAAM,QAAQ;CACd,MAAM,YAAY;CAClB,IAAI,aAAa;CAEjB,OAAO,MACJ,MAAM,IAAI,CAAC,CACX,KAAK,SAAS;EACb,MAAM,SAAS,KAAK,MAAM,KAAK;EAC/B,MAAM,OAAO,KAAK,MAAM,SAAS;EAEjC,IAAI,CAAC,UAAU,CAAC,MAGd,OAD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-logger.mjs","names":[],"sources":["../../../../../../../core/src/dev-server/dev-logger.ts"],"sourcesContent":["import { colors } from \"@mongez/copper\";\nimport dayjs from \"dayjs\";\nimport { Path } from \"../utils/normalized-path\";\n\n/**\n * Dev server logger — Vite-style formatting helpers.\n */\n\nfunction timestamp(): string {\n return colors.dim(`${dayjs().format(\"HH:mm:ss A\")}`);\n}\n\nexport function devLog(message: string) {\n console.log(`${timestamp()} ${message}`);\n}\n\nexport function devLogSuccess(message: string) {\n console.log(`${timestamp()} ${colors.green(\"✓\")} ${colors.green(message)}`);\n}\n\n/**\n * Colourise a stack trace so the eye lands on *your* code.\n *\n * - Error header (`ReferenceError: x is not defined`) → bold red.\n * - Frames in project `src/` → highlighted: a green `›` pointer, yellow\n * function name, cyan relative path, dim `:line:col`. These are almost\n * always where the bug is.\n * - Framework (`@warlock.js`), `node_modules`, and `node:` internal frames\n * → dimmed and relativised. Still there for context, just out of the way.\n *\n * Source maps are enabled in dev, so the paths/lines here are already the\n * original `.ts` locations — this only changes how they're painted.\n */\nexport function formatErrorStack(stack: string): string {\n const frame = /^(\\s*)at (.+?) \\((.+):(\\d+):(\\d+)\\)$/;\n const bareFrame = /^(\\s*)at (.+):(\\d+):(\\d+)$/;\n let headerDone = false;\n\n return stack\n .split(\"\\n\")\n .map((line) => {\n const withFn = line.match(frame);\n const bare = line.match(bareFrame);\n\n if (!withFn && !bare) {\n // Header line(s) before the first frame.\n const painted = headerDone ? colors.dim(line) : colors.bold(colors.red(line));\n return painted;\n }\n\n headerDone = true;\n\n // Every read here is defaulted rather than asserted, and the reason is\n // what this function IS: a stack-trace formatter. If it throws while\n // formatting, it throws INSIDE error reporting — and what the developer\n // then sees is this function's failure instead of the error they were\n // actually chasing. An unreadable frame should degrade to a blank field,\n // never take the report down with it (canon `8d3c13a8`: every fatal\n // needs an unconditional floor).\n const fn = (withFn ? withFn[2] : \"\") ?? \"\";\n const file = (withFn ? withFn[3] : bare?.[2]) ?? \"\";\n const lineNo = (withFn ? withFn[4] : bare?.[3]) ?? \"\";\n const col = (withFn ? withFn[5] : bare?.[4]) ?? \"\";\n\n const isNodeInternal = file.startsWith(\"node:\");\n const isDep = file.includes(\"node_modules\");\n const isFramework = /[\\\\/]@warlock\\.js[\\\\/]/.test(file);\n const isUserCode = !isNodeInternal && !isDep && !isFramework;\n\n const rel = isNodeInternal ? file : Path.toRelative(file);\n const loc = `:${lineNo}:${col}`;\n\n if (isUserCode) {\n return (\n ` ${colors.green(\"›\")} ${colors.dim(\"at\")} ` +\n `${colors.yellow(fn || \"<anonymous>\")} ` +\n `${colors.cyan(rel)}${colors.dim(loc)}`\n );\n }\n\n const label = fn ? `at ${fn} ${rel}${loc}` : `at ${rel}${loc}`;\n return ` ${colors.dim(label)}`;\n })\n .join(\"\\n\");\n}\n\nexport function devLogError(message: string, error?: any) {\n console.log(`${timestamp()} ${colors.red(\"✗\")} ${colors.red(message)}`);\n if (error?.stack) console.log(formatErrorStack(error.stack));\n}\n\nexport function devLogWarn(message: string) {\n console.log(`${timestamp()} ${colors.yellow(\"⚠\")} ${colors.yellow(message)}`);\n}\n\nexport function devLogInfo(message: string) {\n console.log(`${timestamp()} ${colors.cyan(message)}`);\n}\n\nexport function devLogDim(message: string) {\n console.log(`${timestamp()} ${colors.dim(message)}`);\n}\n\nexport function devLogHMR(file: string, dependents?: number) {\n const relativePath = Path.toRelative(file);\n const depInfo = dependents\n ? colors.dim(` +${dependents} module${dependents > 1 ? \"s\" : \"\"}`)\n : \"\";\n console.log(\n `${timestamp()} 🔥 ${colors.green(\"hmr update\")} ${colors.dim(relativePath)}${depInfo}`,\n );\n}\n\nexport function devLogConfig(file: string, connectors?: string[]) {\n const relativePath = Path.toRelative(file);\n const connectorInfo =\n connectors && connectors.length > 0 ? colors.dim(` → restarting ${connectors.join(\", \")}`) : \"\";\n console.log(\n `${timestamp()} ${colors.cyan(\"config reload\")} ${colors.dim(relativePath)}${connectorInfo}`,\n );\n}\n\nexport function devLogReady(message: string) {\n console.log(`\\n${timestamp()} ${colors.green(\"➜\")} ${colors.bold(message)}`);\n}\n\nexport function devLogSection(title: string) {\n console.log(`\\n${timestamp()} ${colors.bold(colors.cyan(title))}`);\n}\n\n/**\n * Format ERR_MODULE_NOT_FOUND so the displayed paths are relative to the\n * project root. The loader hook keeps source paths in the URL so we only\n * need to strip the absolute prefix — no cache-path translation any more.\n */\nexport function formatModuleNotFoundError(error: Error, suggestions?: string[]): string {\n const match = error.message.match(/Cannot find module '([^']+)' imported from '([^']+)'/);\n if (!match) return error.message;\n\n // Same rule as the frame formatter above: this renders a MODULE NOT FOUND\n // report, so a missing capture must degrade the message, not replace the\n // user's error with a crash inside the reporter.\n const [, rawModulePath, rawImporterPath] = match;\n const modulePath = rawModulePath ?? \"\";\n const importerPath = rawImporterPath ?? \"\";\n const lines: string[] = [\n \"\",\n `${colors.red(\"❌ MODULE NOT FOUND\")}`,\n \"\",\n `${colors.dim(\"Cannot find:\")} ${colors.cyan(Path.toRelative(modulePath))}`,\n \"\",\n `${colors.dim(\"Imported by:\")}`,\n ` ${colors.yellow(\"→\")} ${colors.white(Path.toRelative(importerPath))}`,\n ];\n\n if (suggestions && suggestions.length > 0) {\n lines.push(\"\");\n lines.push(`${colors.dim(\"Did you mean?\")}`);\n suggestions.forEach((s) => lines.push(` ${colors.cyan(\"→\")} ${colors.green(s)}`));\n }\n\n lines.push(\"\");\n return lines.join(\"\\n\");\n}\n\n/** @deprecated alias retained for older callers. Use `devLog` directly. */\nexport const devServeLog = devLog;\n"],"mappings":";;;;;;;;AAQA,SAAS,YAAoB;CAC3B,OAAO,OAAO,IAAI,GAAG,MAAM,CAAC,CAAC,OAAO,YAAY,GAAG;AACrD;AAEA,SAAgB,OAAO,SAAiB;CACtC,QAAQ,IAAI,GAAG,UAAU,EAAE,GAAG,SAAS;AACzC;AAEA,SAAgB,cAAc,SAAiB;CAC7C,QAAQ,IAAI,GAAG,UAAU,EAAE,GAAG,OAAO,MAAM,GAAG,EAAE,GAAG,OAAO,MA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GAAG,OAAO,MAAM,KAAK,WAAW,YAAY,CAAC;CACvE;CAEA,IAAI,eAAe,YAAY,SAAS,GAAG;EACzC,MAAM,KAAK,EAAE;EACb,MAAM,KAAK,GAAG,OAAO,IAAI,eAAe,GAAG;EAC3C,YAAY,SAAS,MAAM,MAAM,KAAK,KAAK,OAAO,KAAK,GAAG,EAAE,GAAG,OAAO,MAAM,CAAC,GAAG,CAAC;CACnF;CAEA,MAAM,KAAK,EAAE;CACb,OAAO,MAAM,KAAK,IAAI;AACxB;;AAGA,MAAa,cAAc"}
@@ -167,7 +167,7 @@ var FilesOrchestrator = class {
167
167
  });
168
168
  }
169
169
  async watchFiles() {
170
- devLogSuccess("watching for file changes");
170
+ devLogSuccess("watching for file changes (not serving yet)");
171
171
  this.filesWatcher.onFileChange((p) => this.eventHandler.handleFileChange(p));
172
172
  this.filesWatcher.onFileAdd((p) => this.eventHandler.handleFileAdd(p));
173
173
  this.filesWatcher.onFileDelete((p) => this.eventHandler.handleFileDelete(p));
@@ -1 +1 @@
1
- {"version":3,"file":"files-orchestrator.mjs","names":[],"sources":["../../../../../../../core/src/dev-server/files-orchestrator.ts"],"sourcesContent":["import { colors } from \"@mongez/copper\";\r\nimport { init } from \"es-module-lexer\";\r\nimport type { MessagePort } from \"node:worker_threads\";\r\nimport { warlockConfigManager } from \"../warlock-config/warlock-config.manager\";\r\nimport { DependencyGraph } from \"./dependency-graph\";\r\nimport { devLogDim, devLogSuccess } from \"./dev-logger\";\r\nimport { FileEventHandler } from \"./file-event-handler\";\r\nimport { FileManager } from \"./file-manager\";\r\nimport { FileOperations } from \"./file-operations\";\r\nimport { FilesWatcher } from \"./files-watcher\";\r\nimport { FILE_PROCESSING_BATCH_SIZE } from \"./flags\";\r\nimport { EslintHealthChecker } from \"./health-checker/checkers/eslint-health-checker\";\r\nimport { TypescriptHealthChecker } from \"./health-checker/checkers/typescript-health-checker\";\r\nimport type { FileHealthCheckerContract } from \"./health-checker/file-health-checker.contract\";\r\nimport { FilesHealthcareManager } from \"./health-checker/files-healthcare.manager\";\r\nimport { buildTranspileInit } from \"./loader/build-transpile-init.js\";\r\nimport { registerLoader } from \"./loader/register-loader.js\";\r\nimport { ManifestManager } from \"./manifest-manager\";\r\nimport { ModuleLoader } from \"./module-loader\";\r\nimport { packageJsonManager } from \"./package-json-manager\";\r\nimport { Path } from \"../utils/normalized-path\";\r\nimport { SpecialFilesCollector } from \"./special-files-collector\";\r\nimport { tsconfigManager } from \"./tsconfig-manager\";\r\nimport { ensureWarlockDirectory, getFilesFromDirectory } from \"./utils\";\r\n\r\n/**\r\n * Register a cleanup callback that fires before the current module is\r\n * unloaded by HMR. Stack-inspects the caller so user code doesn't need to\r\n * thread the FileManager through.\r\n */\r\nexport function onCleanup(callback: () => any) {\r\n if (globalThis.__currentModuleFile) {\r\n globalThis.__currentModuleFile.addCleanup(callback);\r\n return;\r\n }\r\n\r\n const stack = new Error().stack;\r\n const callerLine = stack?.split(\"\\n\")[2];\r\n const match = callerLine?.match(/\\((.+?):\\d+:\\d+\\)/) || callerLine?.match(/at (.+?):\\d+:\\d+/);\r\n const callerFile = match?.[1];\r\n\r\n if (!callerFile) return;\r\n const fileManager = filesOrchestrator.files.get(Path.toRelative(callerFile));\r\n fileManager?.addCleanup(callback);\r\n}\r\n\r\n/**\r\n * Top-level coordinator for the dev server's file system.\r\n *\r\n * Owns: file discovery, the dependency graph, the manifest, the special-files\r\n * index, the file watcher, and the lifecycle of the ESM loader hook (which\r\n * provides cache-busting via `?v=N` version tokens).\r\n */\r\nexport class FilesOrchestrator {\r\n public readonly filesWatcher = new FilesWatcher();\r\n public readonly files = new Map<string, FileManager>();\r\n private readonly manifest = new ManifestManager(this.files);\r\n private readonly dependencyGraph = new DependencyGraph();\r\n private readonly healthCheckerManager = new FilesHealthcareManager(this.files);\r\n public readonly specialFilesCollector = new SpecialFilesCollector();\r\n public readonly moduleLoader = new ModuleLoader(this.specialFilesCollector);\r\n public readonly fileOperations: FileOperations;\r\n private readonly eventHandler: FileEventHandler;\r\n\r\n /** Main-thread end of the MessageChannel to the loader hook worker. */\r\n private loaderPort: MessagePort | null = null;\r\n\r\n /** Resolve callbacks for pending `flushVersionBumps()` calls. */\r\n private readonly pendingFlushes: Array<() => void> = [];\r\n\r\n public isInitialized = false;\r\n\r\n public constructor() {\r\n this.fileOperations = new FileOperations(\r\n this.files,\r\n this.dependencyGraph,\r\n this.manifest,\r\n this.specialFilesCollector,\r\n );\r\n\r\n this.eventHandler = new FileEventHandler(\r\n this.fileOperations,\r\n this.manifest,\r\n this.dependencyGraph,\r\n this.files,\r\n );\r\n }\r\n\r\n public async add(relativePath: string): Promise<FileManager> {\r\n return this.fileOperations.addFile(relativePath);\r\n }\r\n\r\n public async load<T>(relativePath: string, type = \"other\") {\r\n const fileManager = await this.add(relativePath);\r\n return this.moduleLoader.loadModule<T>(fileManager, fileManager.type || type);\r\n }\r\n\r\n public getDependencyGraph(): DependencyGraph {\r\n return this.dependencyGraph;\r\n }\r\n\r\n public getInvalidationChain(file: string): string[] {\r\n return this.dependencyGraph.getInvalidationChain(file);\r\n }\r\n\r\n public getFiles(): Map<string, FileManager> {\r\n return this.files;\r\n }\r\n\r\n public getHealthCheckerManager(): FilesHealthcareManager {\r\n return this.healthCheckerManager;\r\n }\r\n\r\n /**\r\n * Initialise managers and register the ESM loader hook. Must be called\r\n * before any user `src/` module is dynamically imported.\r\n */\r\n public async init() {\r\n if (this.isInitialized) return;\r\n this.isInitialized = true;\r\n\r\n await init;\r\n await Promise.all([tsconfigManager.init(), packageJsonManager.init()]);\r\n\r\n // The loader hook writes itself into .warlock/, so ensure the dir exists.\r\n await ensureWarlockDirectory();\r\n\r\n const devServerConfig = await warlockConfigManager.lazyGet(\"devServer\");\r\n const transpileInit = buildTranspileInit(\r\n tsconfigManager.tsconfig?.compilerOptions,\r\n devServerConfig?.transpileCacheDebug === true,\r\n );\r\n\r\n this.loaderPort = await registerLoader(transpileInit);\r\n\r\n this.loaderPort.on(\"message\", (msg: { type: string }) => {\r\n if (msg.type === \"sync-ack\") {\r\n this.pendingFlushes.shift()?.();\r\n }\r\n });\r\n }\r\n\r\n /**\r\n * Tell the hook worker a file changed. The next `import()` of it will get\r\n * a fresh `?v=N` URL → Node cache miss → fresh content.\r\n */\r\n public bumpVersion(absolutePath: string): void {\r\n this.loaderPort?.postMessage({ type: \"bump\", absolutePath });\r\n }\r\n\r\n /**\r\n * Wait until the hook worker has processed every pending bump.\r\n *\r\n * `postMessage` is async — without this, a follow-up `import()` may\r\n * resolve before the worker increments the counter and Node will return\r\n * the cached old module.\r\n */\r\n public flushVersionBumps(): Promise<void> {\r\n if (!this.loaderPort) return Promise.resolve();\r\n\r\n return new Promise<void>((resolve) => {\r\n this.pendingFlushes.push(resolve);\r\n this.loaderPort!.postMessage({ type: \"sync\" });\r\n });\r\n }\r\n\r\n /**\r\n * Discover files on disk, reconcile against the manifest, build the dep\r\n * graph, and persist the new manifest. Idempotent.\r\n */\r\n public async initializeAll() {\r\n const [filesInFilesystem, manifestExists] = await Promise.all([\r\n this.getAllFilesFromFilesystem(),\r\n this.manifest.init(),\r\n ]);\r\n\r\n if (!manifestExists) {\r\n await this.processFiles(filesInFilesystem);\r\n } else {\r\n await this.reconcileFiles(filesInFilesystem);\r\n }\r\n\r\n this.dependencyGraph.build(this.files);\r\n this.fileOperations.updateFileDependents();\r\n this.fileOperations.syncFilesToManifest();\r\n await this.manifest.save();\r\n }\r\n\r\n public async checkHealth(files: { added: string[]; changed: string[]; deleted: string[] }) {\r\n const filesToCheck = [...files.added, ...files.changed]\r\n .map((file) => this.files.get(Path.toRelative(file)))\r\n .filter((file): file is FileManager => !!file);\r\n\r\n const filesToDelete = files.deleted\r\n .map((file) => this.files.get(Path.toRelative(file)))\r\n .filter((file): file is FileManager => !!file);\r\n\r\n await this.healthCheckerManager.onFileChanges(filesToCheck);\r\n this.healthCheckerManager.removeFiles(filesToDelete);\r\n this.healthCheckerManager.checkFiles(filesToCheck);\r\n }\r\n\r\n public async startCheckingHealth(healthCheckers?: FileHealthCheckerContract[]): Promise<void> {\r\n devLogDim(\"Started File Health Checks in the background.\");\r\n\r\n const checkers = healthCheckers ?? [new TypescriptHealthChecker(), new EslintHealthChecker()];\r\n await this.healthCheckerManager.setHealthCheckers(checkers).initialize();\r\n await this.healthCheckerManager.validateAllFiles();\r\n }\r\n\r\n /**\r\n * Glob the src directory, returning relative paths.\r\n */\r\n public async getAllFilesFromFilesystem(): Promise<string[]> {\r\n const absolutePaths = await getFilesFromDirectory();\r\n return absolutePaths.map((absPath) => Path.toRelative(absPath));\r\n }\r\n\r\n /**\r\n * Process every file from scratch — used when no manifest exists.\r\n */\r\n private async processFiles(filePaths: string[]) {\r\n devLogDim(`processing ${filePaths.length} files...`);\r\n await runInBatches(filePaths, FILE_PROCESSING_BATCH_SIZE, async (relativePath) => {\r\n const fileManager = new FileManager(\r\n Path.toAbsolute(relativePath),\r\n this.files,\r\n this.fileOperations,\r\n );\r\n this.files.set(relativePath, fileManager);\r\n await fileManager.process();\r\n });\r\n devLogSuccess(`processed ${filePaths.length} files`);\r\n }\r\n\r\n private async reconcileFiles(filesInFilesystem: string[]) {\r\n const filesInManifest = new Set(this.manifest.getAllFilePaths());\r\n const filesInFilesystemSet = new Set(filesInFilesystem);\r\n\r\n const newFiles = filesInFilesystem.filter((f) => !filesInManifest.has(f));\r\n const deletedFiles = Array.from(filesInManifest).filter((f) => !filesInFilesystemSet.has(f));\r\n const existingFiles = filesInFilesystem.filter((f) => filesInManifest.has(f));\r\n\r\n if (newFiles.length > 0 || deletedFiles.length > 0) {\r\n devLogDim(\r\n `reconciling: ${colors.green(newFiles.length)} new, ${colors.red(deletedFiles.length)} deleted, ${colors.blue(existingFiles.length)} existing`,\r\n );\r\n }\r\n\r\n await this.processFiles(newFiles);\r\n\r\n for (const relativePath of deletedFiles) {\r\n this.manifest.removeFile(relativePath);\r\n this.files.delete(relativePath);\r\n }\r\n\r\n await runInBatches(existingFiles, FILE_PROCESSING_BATCH_SIZE, async (relativePath) => {\r\n const fileManager = new FileManager(\r\n Path.toAbsolute(relativePath),\r\n this.files,\r\n this.fileOperations,\r\n );\r\n this.files.set(relativePath, fileManager);\r\n await fileManager.init(this.manifest.getFile(relativePath));\r\n });\r\n }\r\n\r\n public async watchFiles() {\r\n devLogSuccess(\"watching for file changes\");\r\n\r\n this.filesWatcher.onFileChange((p) => this.eventHandler.handleFileChange(p));\r\n this.filesWatcher.onFileAdd((p) => this.eventHandler.handleFileAdd(p));\r\n this.filesWatcher.onFileDelete((p) => this.eventHandler.handleFileDelete(p));\r\n\r\n const watchConfig = warlockConfigManager.get(\"devServer\")?.watch;\r\n await this.filesWatcher.watch(watchConfig);\r\n }\r\n}\r\n\r\nasync function runInBatches<T>(\r\n items: T[],\r\n size: number,\r\n fn: (item: T) => Promise<unknown>,\r\n): Promise<void> {\r\n if (items.length === 0) return;\r\n for (let i = 0; i < items.length; i += size) {\r\n await Promise.all(items.slice(i, i + size).map(fn));\r\n }\r\n}\r\n\r\nexport const filesOrchestrator = new FilesOrchestrator();\r\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAqDA,IAAa,oBAAb,MAA+B;CAmB7B,AAAO,cAAc;sBAlBU,IAAI,aAAa;+BACxB,IAAI,IAAyB;kBACzB,IAAI,gBAAgB,KAAK,KAAK;yBACvB,IAAI,gBAAgB;8BACf,IAAI,uBAAuB,KAAK,KAAK;+BACrC,IAAI,sBAAsB;sBACnC,IAAI,aAAa,KAAK,qBAAqB;oBAKjC;wBAGY,CAAC;uBAE/B;EAGrB,KAAK,iBAAiB,IAAI,eACxB,KAAK,OACL,KAAK,iBACL,KAAK,UACL,KAAK,qBACP;EAEA,KAAK,eAAe,IAAI,iBACtB,KAAK,gBACL,KAAK,UACL,KAAK,iBACL,KAAK,KACP;CACF;CAEA,MAAa,IAAI,cAA4C;EAC3D,OAAO,KAAK,eAAe,QAAQ,YAAY;CACjD;CAEA,MAAa,KAAQ,cAAsB,OAAO,SAAS;EAC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,MAAM,WAAW;CAC3C;AACF;AAEA,eAAe,aACb,OACA,MACA,IACe;CACf,IAAI,MAAM,WAAW,GAAG;CACxB,KAAK,IAAI,IAAI,GAAG,IAAI,MAAM,QAAQ,KAAK,MACrC,MAAM,QAAQ,IAAI,MAAM,MAAM,GAAG,IAAI,IAAI,CAAC,CAAC,IAAI,EAAE,CAAC;AAEtD;AAEA,MAAa,oBAAoB,IAAI,kBAAkB"}
1
+ {"version":3,"file":"files-orchestrator.mjs","names":[],"sources":["../../../../../../../core/src/dev-server/files-orchestrator.ts"],"sourcesContent":["import { colors } from \"@mongez/copper\";\r\nimport { init } from \"es-module-lexer\";\r\nimport type { MessagePort } from \"node:worker_threads\";\r\nimport { warlockConfigManager } from \"../warlock-config/warlock-config.manager\";\r\nimport { DependencyGraph } from \"./dependency-graph\";\r\nimport { devLogDim, devLogSuccess } from \"./dev-logger\";\r\nimport { FileEventHandler } from \"./file-event-handler\";\r\nimport { FileManager } from \"./file-manager\";\r\nimport { FileOperations } from \"./file-operations\";\r\nimport { FilesWatcher } from \"./files-watcher\";\r\nimport { FILE_PROCESSING_BATCH_SIZE } from \"./flags\";\r\nimport { EslintHealthChecker } from \"./health-checker/checkers/eslint-health-checker\";\r\nimport { TypescriptHealthChecker } from \"./health-checker/checkers/typescript-health-checker\";\r\nimport type { FileHealthCheckerContract } from \"./health-checker/file-health-checker.contract\";\r\nimport { FilesHealthcareManager } from \"./health-checker/files-healthcare.manager\";\r\nimport { buildTranspileInit } from \"./loader/build-transpile-init.js\";\r\nimport { registerLoader } from \"./loader/register-loader.js\";\r\nimport { ManifestManager } from \"./manifest-manager\";\r\nimport { ModuleLoader } from \"./module-loader\";\r\nimport { packageJsonManager } from \"./package-json-manager\";\r\nimport { Path } from \"../utils/normalized-path\";\r\nimport { SpecialFilesCollector } from \"./special-files-collector\";\r\nimport { tsconfigManager } from \"./tsconfig-manager\";\r\nimport { ensureWarlockDirectory, getFilesFromDirectory } from \"./utils\";\r\n\r\n/**\r\n * Register a cleanup callback that fires before the current module is\r\n * unloaded by HMR. Stack-inspects the caller so user code doesn't need to\r\n * thread the FileManager through.\r\n */\r\nexport function onCleanup(callback: () => any) {\r\n if (globalThis.__currentModuleFile) {\r\n globalThis.__currentModuleFile.addCleanup(callback);\r\n return;\r\n }\r\n\r\n const stack = new Error().stack;\r\n const callerLine = stack?.split(\"\\n\")[2];\r\n const match = callerLine?.match(/\\((.+?):\\d+:\\d+\\)/) || callerLine?.match(/at (.+?):\\d+:\\d+/);\r\n const callerFile = match?.[1];\r\n\r\n if (!callerFile) return;\r\n const fileManager = filesOrchestrator.files.get(Path.toRelative(callerFile));\r\n fileManager?.addCleanup(callback);\r\n}\r\n\r\n/**\r\n * Top-level coordinator for the dev server's file system.\r\n *\r\n * Owns: file discovery, the dependency graph, the manifest, the special-files\r\n * index, the file watcher, and the lifecycle of the ESM loader hook (which\r\n * provides cache-busting via `?v=N` version tokens).\r\n */\r\nexport class FilesOrchestrator {\r\n public readonly filesWatcher = new FilesWatcher();\r\n public readonly files = new Map<string, FileManager>();\r\n private readonly manifest = new ManifestManager(this.files);\r\n private readonly dependencyGraph = new DependencyGraph();\r\n private readonly healthCheckerManager = new FilesHealthcareManager(this.files);\r\n public readonly specialFilesCollector = new SpecialFilesCollector();\r\n public readonly moduleLoader = new ModuleLoader(this.specialFilesCollector);\r\n public readonly fileOperations: FileOperations;\r\n private readonly eventHandler: FileEventHandler;\r\n\r\n /** Main-thread end of the MessageChannel to the loader hook worker. */\r\n private loaderPort: MessagePort | null = null;\r\n\r\n /** Resolve callbacks for pending `flushVersionBumps()` calls. */\r\n private readonly pendingFlushes: Array<() => void> = [];\r\n\r\n public isInitialized = false;\r\n\r\n public constructor() {\r\n this.fileOperations = new FileOperations(\r\n this.files,\r\n this.dependencyGraph,\r\n this.manifest,\r\n this.specialFilesCollector,\r\n );\r\n\r\n this.eventHandler = new FileEventHandler(\r\n this.fileOperations,\r\n this.manifest,\r\n this.dependencyGraph,\r\n this.files,\r\n );\r\n }\r\n\r\n public async add(relativePath: string): Promise<FileManager> {\r\n return this.fileOperations.addFile(relativePath);\r\n }\r\n\r\n public async load<T>(relativePath: string, type = \"other\") {\r\n const fileManager = await this.add(relativePath);\r\n return this.moduleLoader.loadModule<T>(fileManager, fileManager.type || type);\r\n }\r\n\r\n public getDependencyGraph(): DependencyGraph {\r\n return this.dependencyGraph;\r\n }\r\n\r\n public getInvalidationChain(file: string): string[] {\r\n return this.dependencyGraph.getInvalidationChain(file);\r\n }\r\n\r\n public getFiles(): Map<string, FileManager> {\r\n return this.files;\r\n }\r\n\r\n public getHealthCheckerManager(): FilesHealthcareManager {\r\n return this.healthCheckerManager;\r\n }\r\n\r\n /**\r\n * Initialise managers and register the ESM loader hook. Must be called\r\n * before any user `src/` module is dynamically imported.\r\n */\r\n public async init() {\r\n if (this.isInitialized) return;\r\n this.isInitialized = true;\r\n\r\n await init;\r\n await Promise.all([tsconfigManager.init(), packageJsonManager.init()]);\r\n\r\n // The loader hook writes itself into .warlock/, so ensure the dir exists.\r\n await ensureWarlockDirectory();\r\n\r\n const devServerConfig = await warlockConfigManager.lazyGet(\"devServer\");\r\n const transpileInit = buildTranspileInit(\r\n tsconfigManager.tsconfig?.compilerOptions,\r\n devServerConfig?.transpileCacheDebug === true,\r\n );\r\n\r\n this.loaderPort = await registerLoader(transpileInit);\r\n\r\n this.loaderPort.on(\"message\", (msg: { type: string }) => {\r\n if (msg.type === \"sync-ack\") {\r\n this.pendingFlushes.shift()?.();\r\n }\r\n });\r\n }\r\n\r\n /**\r\n * Tell the hook worker a file changed. The next `import()` of it will get\r\n * a fresh `?v=N` URL → Node cache miss → fresh content.\r\n */\r\n public bumpVersion(absolutePath: string): void {\r\n this.loaderPort?.postMessage({ type: \"bump\", absolutePath });\r\n }\r\n\r\n /**\r\n * Wait until the hook worker has processed every pending bump.\r\n *\r\n * `postMessage` is async — without this, a follow-up `import()` may\r\n * resolve before the worker increments the counter and Node will return\r\n * the cached old module.\r\n */\r\n public flushVersionBumps(): Promise<void> {\r\n if (!this.loaderPort) return Promise.resolve();\r\n\r\n return new Promise<void>((resolve) => {\r\n this.pendingFlushes.push(resolve);\r\n this.loaderPort!.postMessage({ type: \"sync\" });\r\n });\r\n }\r\n\r\n /**\r\n * Discover files on disk, reconcile against the manifest, build the dep\r\n * graph, and persist the new manifest. Idempotent.\r\n */\r\n public async initializeAll() {\r\n const [filesInFilesystem, manifestExists] = await Promise.all([\r\n this.getAllFilesFromFilesystem(),\r\n this.manifest.init(),\r\n ]);\r\n\r\n if (!manifestExists) {\r\n await this.processFiles(filesInFilesystem);\r\n } else {\r\n await this.reconcileFiles(filesInFilesystem);\r\n }\r\n\r\n this.dependencyGraph.build(this.files);\r\n this.fileOperations.updateFileDependents();\r\n this.fileOperations.syncFilesToManifest();\r\n await this.manifest.save();\r\n }\r\n\r\n public async checkHealth(files: { added: string[]; changed: string[]; deleted: string[] }) {\r\n const filesToCheck = [...files.added, ...files.changed]\r\n .map((file) => this.files.get(Path.toRelative(file)))\r\n .filter((file): file is FileManager => !!file);\r\n\r\n const filesToDelete = files.deleted\r\n .map((file) => this.files.get(Path.toRelative(file)))\r\n .filter((file): file is FileManager => !!file);\r\n\r\n await this.healthCheckerManager.onFileChanges(filesToCheck);\r\n this.healthCheckerManager.removeFiles(filesToDelete);\r\n this.healthCheckerManager.checkFiles(filesToCheck);\r\n }\r\n\r\n public async startCheckingHealth(healthCheckers?: FileHealthCheckerContract[]): Promise<void> {\r\n devLogDim(\"Started File Health Checks in the background.\");\r\n\r\n const checkers = healthCheckers ?? [new TypescriptHealthChecker(), new EslintHealthChecker()];\r\n await this.healthCheckerManager.setHealthCheckers(checkers).initialize();\r\n await this.healthCheckerManager.validateAllFiles();\r\n }\r\n\r\n /**\r\n * Glob the src directory, returning relative paths.\r\n */\r\n public async getAllFilesFromFilesystem(): Promise<string[]> {\r\n const absolutePaths = await getFilesFromDirectory();\r\n return absolutePaths.map((absPath) => Path.toRelative(absPath));\r\n }\r\n\r\n /**\r\n * Process every file from scratch — used when no manifest exists.\r\n */\r\n private async processFiles(filePaths: string[]) {\r\n devLogDim(`processing ${filePaths.length} files...`);\r\n await runInBatches(filePaths, FILE_PROCESSING_BATCH_SIZE, async (relativePath) => {\r\n const fileManager = new FileManager(\r\n Path.toAbsolute(relativePath),\r\n this.files,\r\n this.fileOperations,\r\n );\r\n this.files.set(relativePath, fileManager);\r\n await fileManager.process();\r\n });\r\n devLogSuccess(`processed ${filePaths.length} files`);\r\n }\r\n\r\n private async reconcileFiles(filesInFilesystem: string[]) {\r\n const filesInManifest = new Set(this.manifest.getAllFilePaths());\r\n const filesInFilesystemSet = new Set(filesInFilesystem);\r\n\r\n const newFiles = filesInFilesystem.filter((f) => !filesInManifest.has(f));\r\n const deletedFiles = Array.from(filesInManifest).filter((f) => !filesInFilesystemSet.has(f));\r\n const existingFiles = filesInFilesystem.filter((f) => filesInManifest.has(f));\r\n\r\n if (newFiles.length > 0 || deletedFiles.length > 0) {\r\n devLogDim(\r\n `reconciling: ${colors.green(newFiles.length)} new, ${colors.red(deletedFiles.length)} deleted, ${colors.blue(existingFiles.length)} existing`,\r\n );\r\n }\r\n\r\n await this.processFiles(newFiles);\r\n\r\n for (const relativePath of deletedFiles) {\r\n this.manifest.removeFile(relativePath);\r\n this.files.delete(relativePath);\r\n }\r\n\r\n await runInBatches(existingFiles, FILE_PROCESSING_BATCH_SIZE, async (relativePath) => {\r\n const fileManager = new FileManager(\r\n Path.toAbsolute(relativePath),\r\n this.files,\r\n this.fileOperations,\r\n );\r\n this.files.set(relativePath, fileManager);\r\n await fileManager.init(this.manifest.getFile(relativePath));\r\n });\r\n }\r\n\r\n public async watchFiles() {\n devLogSuccess(\"watching for file changes (not serving yet)\");\n\r\n this.filesWatcher.onFileChange((p) => this.eventHandler.handleFileChange(p));\r\n this.filesWatcher.onFileAdd((p) => this.eventHandler.handleFileAdd(p));\r\n this.filesWatcher.onFileDelete((p) => this.eventHandler.handleFileDelete(p));\r\n\r\n const watchConfig = warlockConfigManager.get(\"devServer\")?.watch;\r\n await this.filesWatcher.watch(watchConfig);\r\n }\r\n}\r\n\r\nasync function runInBatches<T>(\r\n items: T[],\r\n size: number,\r\n fn: (item: T) => Promise<unknown>,\r\n): Promise<void> {\r\n if (items.length === 0) return;\r\n for (let i = 0; i < items.length; i += size) {\r\n await Promise.all(items.slice(i, i + size).map(fn));\r\n }\r\n}\r\n\r\nexport const filesOrchestrator = new FilesOrchestrator();\r\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAqDA,IAAa,oBAAb,MAA+B;CAmB7B,AAAO,cAAc;sBAlBU,IAAI,aAAa;+BACxB,IAAI,IAAyB;kBACzB,IAAI,gBAAgB,KAAK,KAAK;yBACvB,IAAI,gBAAgB;8BACf,IAAI,uBAAuB,KAAK,KAAK;+BACrC,IAAI,sBAAsB;sBACnC,IAAI,aAAa,KAAK,qBAAqB;oBAKjC;wBAGY,CAAC;uBAE/B;EAGrB,KAAK,iBAAiB,IAAI,eACxB,KAAK,OACL,KAAK,iBACL,KAAK,UACL,KAAK,qBACP;EAEA,KAAK,eAAe,IAAI,iBACtB,KAAK,gBACL,KAAK,UACL,KAAK,iBACL,KAAK,KACP;CACF;CAEA,MAAa,IAAI,cAA4C;EAC3D,OAAO,KAAK,eAAe,QAAQ,YAAY;CACjD;CAEA,MAAa,KAAQ,cAAsB,OAAO,SAAS;EACzD,MAAM,cAAc,MAAM,KAAK,IAAI,YAAY;EAC/C,OAAO,KAAK,aAAa,WAAc,aAAa,YAAY,QAAQ,IAAI;CAC9E;CAEA,AAAO,qBAAsC;EAC3C,OAAO,KAAK;CACd;CAEA,AAAO,qBAAqB,MAAwB;EAClD,OAAO,KAAK,gBAAgB,qBAAqB,IAAI;CACvD;CAEA,AAAO,WAAqC;EAC1C,OAAO,KAAK;CACd;CAEA,AAAO,0BAAkD;EACvD,OAAO,KAAK;CACd;;;;;CAMA,MAAa,OAAO;EAClB,IAAI,KAAK,eAAe;EACxB,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match(/export\s+\{([^}]*)\}/);
56
56
  if (specifiersMatch) {
57
- if (specifiersMatch[1].split(",").map((s) => s.trim()).filter(Boolean).some((item) => !item.startsWith("type "))) return false;
57
+ if ((specifiersMatch[1] ?? "").split(",").map((s) => s.trim()).filter(Boolean).some((item) => !item.startsWith("type "))) return false;
58
58
  }
59
59
  }
60
60
  continue;
@@ -85,7 +85,7 @@ function hasRuntimeImports(line) {
85
85
  if (isTypeOnlyImport(trimmed)) return false;
86
86
  const specifiersMatch = trimmed.match(/import\s+(?:type\s+)?\{([^}]+)\}/);
87
87
  if (!specifiersMatch) return true;
88
- return !specifiersMatch[1].split(",").map((s) => s.trim()).filter(Boolean).every((item) => /^type\s+\w+/.test(item));
88
+ return !(specifiersMatch[1] ?? "").split(",").map((s) => s.trim()).filter(Boolean).every((item) => /^type\s+\w+/.test(item));
89
89
  }
90
90
  /**
91
91
  * Decide whether an `export ... from "m"` statement re-exports only types.
@@ -97,7 +97,7 @@ function isExportTypeOnlyStatement(line) {
97
97
  if (/^export\s+type\s+/.test(trimmed)) return true;
98
98
  const specifiersMatch = trimmed.match(/export\s+\{([^}]+)\}/);
99
99
  if (!specifiersMatch) return false;
100
- return specifiersMatch[1].split(",").map((s) => s.trim()).filter(Boolean).every((item) => /^type\s+\w+/.test(item));
100
+ return (specifiersMatch[1] ?? "").split(",").map((s) => s.trim()).filter(Boolean).every((item) => /^type\s+\w+/.test(item));
101
101
  }
102
102
  /**
103
103
  * Extract import paths using regex (more reliable for TypeScript).
@@ -125,23 +125,37 @@ function extractImportPathsWithRegex(source) {
125
125
  });
126
126
  return;
127
127
  }
128
- if (!isTypeOnly) imports[existingIndex].isTypeOnly = false;
128
+ if (!isTypeOnly) {
129
+ const existing = imports[existingIndex];
130
+ if (existing) existing.isTypeOnly = false;
131
+ }
129
132
  };
130
133
  const importRegex = /import\s+(?:type\s+)?(\{[\s\S]*?\}|\*\s+as\s+\w+|\w+(?:\s*,\s*\{[\s\S]*?\})?)\s+from\s+['"]([^'"]+)['"]/g;
131
134
  let match;
132
135
  while ((match = importRegex.exec(source)) !== null) {
133
136
  const fullMatch = match[0];
134
137
  const importPath = match[2];
138
+ if (importPath === void 0) continue;
135
139
  record(importPath, fullMatch, !hasRuntimeImports(fullMatch));
136
140
  }
137
141
  const sideEffectRegex = /import\s+['"]([^'"]+)['"]/g;
138
- while ((match = sideEffectRegex.exec(source)) !== null) record(match[1], match[0], false);
142
+ while ((match = sideEffectRegex.exec(source)) !== null) {
143
+ const sideEffectPath = match[1];
144
+ if (sideEffectPath === void 0) continue;
145
+ record(sideEffectPath, match[0], false);
146
+ }
139
147
  const dynamicImportPattern = /import\s*\(\s*['"]([^'"]+)['"]\s*\)/g;
140
- while ((match = dynamicImportPattern.exec(source)) !== null) record(match[1], match[0], false);
148
+ while ((match = dynamicImportPattern.exec(source)) !== null) {
149
+ const dynamicPath = match[1];
150
+ if (dynamicPath === void 0) continue;
151
+ record(dynamicPath, match[0], false);
152
+ }
141
153
  const exportFromPattern = /export\s+(?:\{[^}]*\}|\*|\w+)\s+from\s+['"]([^'"]+)['"]/g;
142
154
  while ((match = exportFromPattern.exec(source)) !== null) {
143
155
  const fullMatch = match[0];
144
- record(match[1], fullMatch, isExportTypeOnlyStatement(fullMatch));
156
+ const exportPath = match[1];
157
+ if (exportPath === void 0) continue;
158
+ record(exportPath, fullMatch, isExportTypeOnlyStatement(fullMatch));
145
159
  }
146
160
  return imports;
147
161
  }
@@ -339,7 +353,7 @@ function isNodeBuiltin(importPath) {
339
353
  "v8"
340
354
  ];
341
355
  if (importPath.startsWith("node:")) return true;
342
- const moduleName = importPath.split("/")[0];
356
+ const moduleName = importPath.split("/")[0] ?? importPath;
343
357
  return builtins.includes(moduleName);
344
358
  }
345
359
 
@@ -1 +1 @@
1
- {"version":3,"file":"parse-imports.mjs","names":[],"sources":["../../../../../../../core/src/dev-server/parse-imports.ts"],"sourcesContent":["import { fileExistsAsync, directoryExistsAsync } from \"@warlock.js/fs\";\nimport { type ImportSpecifier, parse } from \"es-module-lexer\";\nimport path from \"node:path\";\nimport { Path } from \"../utils/normalized-path\";\nimport { tsconfigManager } from \"./tsconfig-manager\";\n\n/**\n * Detect if a file contains only type definitions (no runtime code)\n *\n * A file is considered type-only if ALL its exports are:\n * - interface declarations\n * - type alias declarations\n * - export type { ... } statements\n * - export type { ... } from \"...\" statements\n *\n * Files with any of these are NOT type-only:\n * - export const/let/var\n * - export function\n * - export class\n * - export default (non-type)\n * - export { ... } (without type keyword)\n * - export * from (without type keyword)\n *\n * @param source - The source code to analyze\n * @returns true if the file exports only types\n */\nexport function isTypeOnlyFile(source: string): boolean {\n // Remove comments to avoid false positives\n const withoutComments = source\n .replace(/\\/\\*[\\s\\S]*?\\*\\//g, \"\") // block comments\n .replace(/\\/\\/.*$/gm, \"\"); // line comments\n\n // Remove string literals to avoid false positives\n const withoutStrings = withoutComments\n .replace(/'(?:[^'\\\\]|\\\\.)*'/g, \"''\")\n .replace(/\"(?:[^\"\\\\]|\\\\.)*\"/g, '\"\"')\n .replace(/`(?:[^`\\\\]|\\\\.)*`/g, \"``\");\n\n // Patterns for type-only exports (these are safe)\n const typeOnlyPatterns = [\n /export\\s+type\\s+\\{[^}]*\\}/g, // export type { Foo, Bar }\n /export\\s+type\\s+\\{[^}]*\\}\\s+from\\s+['\"]/g, // export type { Foo } from \"...\"\n /export\\s+interface\\s+\\w+/g, // export interface Foo\n /export\\s+type\\s+\\w+\\s*=/g, // export type Foo =\n ];\n\n // Remove all type-only exports from consideration\n let remaining = withoutStrings;\n for (const pattern of typeOnlyPatterns) {\n remaining = remaining.replace(pattern, \"\");\n }\n\n // Patterns for runtime exports (these make the file NOT type-only)\n const runtimeExportPatterns = [\n /export\\s+(?:const|let|var)\\s+\\w+/g, // export const/let/var foo\n /export\\s+function\\s+\\w+/g, // export function foo\n /export\\s+async\\s+function\\s+\\w+/g, // export async function foo\n /export\\s+class\\s+\\w+/g, // export class Foo\n /export\\s+enum\\s+\\w+/g, // export enum Foo (enums have runtime value)\n /export\\s+default\\s+(?!type\\s)/g, // export default (not type)\n /export\\s+\\{[^}]*\\}(?!\\s+from)/g, // export { foo } (local re-export without type)\n /export\\s+\\{[^}]*\\}\\s+from\\s+['\"][^'\"]+['\"]/g, // export { foo } from (without type)\n /export\\s+\\*\\s+from\\s+['\"][^'\"]+['\"]/g, // export * from (re-exports everything)\n /export\\s+\\*\\s+as\\s+\\w+/g, // export * as namespace\n ];\n\n for (const pattern of runtimeExportPatterns) {\n if (pattern.test(remaining)) {\n // Reset regex lastIndex for subsequent tests\n pattern.lastIndex = 0;\n\n // Special case: check if export { } contains only type exports\n if (pattern.source.includes(\"export\\\\s+\\\\{\")) {\n const matches = remaining.match(/export\\s+\\{([^}]*)\\}(?:\\s+from\\s+['\"][^'\"]+['\"])?/g);\n if (matches) {\n for (const match of matches) {\n // Skip if it's already a type export\n if (/^export\\s+type\\s+/.test(match)) continue;\n\n // Extract the specifiers\n const specifiersMatch = match.match(/export\\s+\\{([^}]*)\\}/);\n if (specifiersMatch) {\n const specifiers = specifiersMatch[1];\n const items = specifiers\n .split(\",\")\n .map((s) => s.trim())\n .filter(Boolean);\n\n // If any specifier is NOT prefixed with \"type \", this is a runtime export\n const hasRuntimeSpecifier = items.some((item) => !item.startsWith(\"type \"));\n if (hasRuntimeSpecifier) {\n return false;\n }\n }\n }\n }\n continue;\n }\n\n return false;\n }\n }\n\n // If we get here, no runtime exports were found\n // But we should also verify the file has at least some type exports\n // (an empty file or file with only imports is not really \"type-only\")\n const hasTypeExports = typeOnlyPatterns.some((pattern) => {\n pattern.lastIndex = 0;\n return pattern.test(withoutStrings);\n });\n\n return hasTypeExports;\n}\n\n/**\n * Check if an import statement is a pure `import type` (the keyword sits\n * immediately after `import`, covering `import type { X }`, `import type Foo`,\n * and `import type * as Ns`).\n */\nfunction isTypeOnlyImport(line: string): boolean {\n const trimmed = line.trim();\n\n return trimmed.startsWith(\"import type \") || !!trimmed.match(/^import\\s+type\\s+[\\{\\*]/);\n}\n\n/**\n * Decide whether an `import ... from \"m\"` statement contributes any runtime\n * binding. Returns false for pure `import type` and for destructured imports\n * where every specifier is prefixed with the `type` keyword.\n */\nfunction hasRuntimeImports(line: string): boolean {\n const trimmed = line.trim();\n\n if (isTypeOnlyImport(trimmed)) {\n return false;\n }\n\n const specifiersMatch = trimmed.match(/import\\s+(?:type\\s+)?\\{([^}]+)\\}/);\n\n if (!specifiersMatch) {\n return true;\n }\n\n const items = specifiersMatch[1]\n .split(\",\")\n .map((s) => s.trim())\n .filter(Boolean);\n\n return !items.every((item) => /^type\\s+\\w+/.test(item));\n}\n\n/**\n * Decide whether an `export ... from \"m\"` statement re-exports only types.\n * Covers `export type { X } from`, `export type * from`, and\n * `export { type X, type Y } from`.\n */\nfunction isExportTypeOnlyStatement(line: string): boolean {\n const trimmed = line.trim();\n\n if (/^export\\s+type\\s+/.test(trimmed)) {\n return true;\n }\n\n const specifiersMatch = trimmed.match(/export\\s+\\{([^}]+)\\}/);\n\n if (!specifiersMatch) {\n return false;\n }\n\n const items = specifiersMatch[1]\n .split(\",\")\n .map((s) => s.trim())\n .filter(Boolean);\n\n return items.every((item) => /^type\\s+\\w+/.test(item));\n}\n\n/**\n * Extract import paths using regex (more reliable for TypeScript).\n * Each entry carries an `isTypeOnly` flag: true when every occurrence of the\n * path in the source is a type-only statement (no runtime binding).\n * A single runtime occurrence makes the path runtime.\n */\nfunction extractImportPathsWithRegex(\n source: string,\n): Array<{ path: string; originalLine: string; isTypeOnly: boolean }> {\n const imports: Array<{ path: string; originalLine: string; isTypeOnly: boolean }> = [];\n const seenPaths = new Map<string, number>();\n\n /**\n * Record an import path with its type-only flag.\n * If the same path appears in multiple statements, the edge is type-only\n * iff every occurrence is type-only — a single runtime statement makes it runtime.\n */\n const record = (importPath: string, originalLine: string, isTypeOnly: boolean): void => {\n if (!importPath) {\n return;\n }\n\n const existingIndex = seenPaths.get(importPath);\n\n if (existingIndex === undefined) {\n seenPaths.set(importPath, imports.length);\n imports.push({ path: importPath, originalLine, isTypeOnly });\n\n return;\n }\n\n if (!isTypeOnly) {\n imports[existingIndex].isTypeOnly = false;\n }\n };\n\n // Pattern 1: Standard ES module imports (handles multiline)\n // Matches: import { ... } from \"path\", import Foo from \"path\", import Foo, { ... } from \"path\"\n const importRegex =\n /import\\s+(?:type\\s+)?(\\{[\\s\\S]*?\\}|\\*\\s+as\\s+\\w+|\\w+(?:\\s*,\\s*\\{[\\s\\S]*?\\})?)\\s+from\\s+['\"]([^'\"]+)['\"]/g;\n\n let match;\n\n while ((match = importRegex.exec(source)) !== null) {\n const fullMatch = match[0];\n const importPath = match[2];\n const isTypeOnly = !hasRuntimeImports(fullMatch);\n\n record(importPath, fullMatch, isTypeOnly);\n }\n\n // Pattern 1b: Side-effect imports - import \"path\" — always runtime\n const sideEffectRegex = /import\\s+['\"]([^'\"]+)['\"]/g;\n\n while ((match = sideEffectRegex.exec(source)) !== null) {\n record(match[1], match[0], false);\n }\n\n // Pattern 2: Dynamic imports - import(\"path\") — always runtime\n const dynamicImportPattern = /import\\s*\\(\\s*['\"]([^'\"]+)['\"]\\s*\\)/g;\n\n while ((match = dynamicImportPattern.exec(source)) !== null) {\n record(match[1], match[0], false);\n }\n\n // Pattern 3: Export from - export ... from \"path\"\n const exportFromPattern = /export\\s+(?:\\{[^}]*\\}|\\*|\\w+)\\s+from\\s+['\"]([^'\"]+)['\"]/g;\n\n while ((match = exportFromPattern.exec(source)) !== null) {\n const fullMatch = match[0];\n\n record(match[1], fullMatch, isExportTypeOnlyStatement(fullMatch));\n }\n\n return imports;\n}\n\n/**\n * Metadata for a single resolved import edge.\n * `isTypeOnly` is true iff every import/export statement that references this\n * path is type-only (pure `import type`, `export type`, or destructured lists\n * where every specifier carries the `type` keyword). A single runtime\n * occurrence flips the flag to false — that's what matters for cycle detection.\n */\nexport type ResolvedImport = {\n absolutePath: string;\n isTypeOnly: boolean;\n};\n\n/**\n * Parse import/export statements in a TS/JS source file and return the\n * resolved dependency edges keyed by the original import path. Includes\n * type-only edges (flagged) so downstream consumers can distinguish runtime\n * cycles from type-only ones.\n *\n * @example\n * const importMap = await parseImports(source, \"/abs/path/to/file.ts\");\n * for (const [importPath, { absolutePath, isTypeOnly }] of importMap) {\n * // ...\n * }\n */\nexport async function parseImports(\n source: string,\n filePath: string,\n): Promise<Map<string, ResolvedImport>> {\n try {\n // Skip .d.ts files - they're type declarations, not runtime code\n if (filePath.endsWith(\".d.ts\")) {\n return new Map();\n }\n\n // Try es-module-lexer first (faster and more accurate for simple cases)\n try {\n const [imports] = await parse(source);\n\n if (imports && imports.length > 0) {\n return await resolveImports(imports as ImportSpecifier[], source, filePath);\n }\n } catch (lexerError) {\n // es-module-lexer failed, fall back to regex-based extraction\n // This is common with TypeScript files that have complex syntax\n }\n\n // Fallback: Use regex-based extraction (more forgiving with TypeScript)\n const regexImports = extractImportPathsWithRegex(source);\n const resolvedImports = new Map<string, ResolvedImport>();\n\n for (const { path: importPath, isTypeOnly } of regexImports) {\n if (isNodeBuiltin(importPath)) {\n continue;\n }\n\n if (!importPath.startsWith(\".\") && !tsconfigManager.isAlias(importPath)) {\n continue;\n }\n\n let resolvedPath: string | null = null;\n\n if (tsconfigManager.isAlias(importPath)) {\n resolvedPath = await resolveAliasImport(importPath);\n } else if (importPath.startsWith(\".\")) {\n resolvedPath = await resolveRelativeImport(importPath, filePath);\n }\n\n if (resolvedPath) {\n mergeResolvedImport(resolvedImports, importPath, resolvedPath, isTypeOnly);\n }\n }\n\n return resolvedImports;\n } catch (error) {\n console.error(`Error parsing imports for ${filePath}:`, error);\n\n return new Map();\n }\n}\n\n/**\n * Merge a resolved import into the output map, preserving the type-only rule:\n * a path is type-only iff every statement that references it is type-only.\n */\nfunction mergeResolvedImport(\n target: Map<string, ResolvedImport>,\n importPath: string,\n absolutePath: string,\n isTypeOnly: boolean,\n): void {\n const existing = target.get(importPath);\n\n if (!existing) {\n target.set(importPath, { absolutePath, isTypeOnly });\n\n return;\n }\n\n if (!isTypeOnly) {\n existing.isTypeOnly = false;\n }\n}\n\n/**\n * Resolve imports from `es-module-lexer` output. For each specifier, slice the\n * raw statement (`ss..se`) and re-run the type-only heuristic so we can flag\n * the edge correctly — the lexer itself does not distinguish `import type`.\n */\nasync function resolveImports(\n imports: ImportSpecifier[],\n source: string,\n filePath: string,\n): Promise<Map<string, ResolvedImport>> {\n const resolvedImports = new Map<string, ResolvedImport>();\n\n for (const imp of imports) {\n const importPath = imp.n;\n\n if (!importPath) {\n continue;\n }\n\n if (isNodeBuiltin(importPath)) {\n continue;\n }\n\n if (!importPath.startsWith(\".\") && !tsconfigManager.isAlias(importPath)) {\n continue;\n }\n\n let resolvedPath: string | null = null;\n\n if (tsconfigManager.isAlias(importPath)) {\n resolvedPath = await resolveAliasImport(importPath);\n } else if (importPath.startsWith(\".\")) {\n resolvedPath = await resolveRelativeImport(importPath, filePath);\n }\n\n if (!resolvedPath) {\n continue;\n }\n\n const isTypeOnly = isLexerStatementTypeOnly(imp, source);\n\n mergeResolvedImport(resolvedImports, importPath, resolvedPath, isTypeOnly);\n }\n\n return resolvedImports;\n}\n\n/**\n * Classify a single lexer-reported statement as type-only or runtime.\n * Dynamic imports (`import(...)`) are always runtime. For static\n * imports/export-from we slice the raw source and apply the same heuristic\n * the regex fallback uses.\n */\nfunction isLexerStatementTypeOnly(imp: ImportSpecifier, source: string): boolean {\n // Dynamic imports always execute — they cannot be type-only.\n // es-module-lexer reports dynamic with a.n === undefined typically, but\n // we guard by checking the statement prefix too.\n const statementStart = imp.ss;\n const statementEnd = imp.se;\n\n if (\n typeof statementStart !== \"number\" ||\n typeof statementEnd !== \"number\" ||\n statementEnd <= statementStart\n ) {\n return false;\n }\n\n const statement = source.slice(statementStart, statementEnd);\n const trimmed = statement.trim();\n\n if (trimmed.startsWith(\"import(\") || /^\\bimport\\s*\\(/.test(trimmed)) {\n return false;\n }\n\n if (trimmed.startsWith(\"export\")) {\n return isExportTypeOnlyStatement(statement);\n }\n\n return !hasRuntimeImports(statement);\n}\n\n/**\n * Resolve alias imports to actual file paths with extensions\n * Example: app/users/services/get-users.service -> /absolute/path/to/src/app/users/services/get-users.service.ts\n */\nasync function resolveAliasImport(importPath: string): Promise<string | null> {\n // Use tsconfig manager to resolve the alias to an absolute path\n const resolvedBase = tsconfigManager.resolveAliasToAbsolute(importPath);\n\n if (!resolvedBase) return null;\n\n // Try to resolve with extensions\n const resolvedPath = await tryResolveWithExtensions(resolvedBase);\n\n return resolvedPath;\n}\n\n/**\n * Resolve relative imports to actual file paths\n * Example: ./../services/get-user.service -> /absolute/path/to/services/get-user.service.ts\n */\nasync function resolveRelativeImport(\n importPath: string,\n currentFilePath: string,\n): Promise<string | null> {\n const dir = path.dirname(currentFilePath);\n // Use path.resolve to handle .. and . properly, then normalize to forward slashes\n const resolvedBase = Path.normalize(path.resolve(dir, importPath));\n\n // Try to resolve with extensions\n const resolvedPath = await tryResolveWithExtensions(resolvedBase);\n\n return resolvedPath;\n}\n\n/**\n * Try to resolve a file path by checking different extensions\n * TypeScript/JavaScript files can be imported without extensions\n *\n * @TODO: For better performance, we need to check the files in files orchestrator\n * instead of using the file system as we will be fetching all project files anyway.\n */\n// Cache for file existence checks to avoid redundant filesystem calls\nconst fileExistsCache = new Map<string, boolean>();\n\n/**\n * Clear the file exists cache\n * Should be called when new files are created to ensure fresh lookups\n */\nexport function clearFileExistsCache(): void {\n fileExistsCache.clear();\n}\n\nasync function cachedFileExists(filePath: string): Promise<boolean> {\n if (fileExistsCache.has(filePath)) {\n return fileExistsCache.get(filePath)!;\n }\n const exists = (await fileExistsAsync(filePath)) as boolean;\n fileExistsCache.set(filePath, exists);\n return exists;\n}\n\nasync function tryResolveWithExtensions(basePath: string): Promise<string | null> {\n // Normalize the base path first (handle Windows paths)\n const normalizedBase = Path.normalize(basePath);\n\n // List of extensions to try, in order of preference\n const extensions = [\".ts\", \".tsx\", \".js\", \".jsx\", \".mjs\", \".cjs\"];\n const validExtensions = new Set(extensions);\n\n // If the path already has a VALID code file extension, check if it exists\n const ext = path.extname(normalizedBase);\n if (ext && validExtensions.has(ext)) {\n if (await cachedFileExists(normalizedBase)) {\n return normalizedBase;\n }\n // If explicit extension doesn't exist, return null\n return null;\n }\n\n // Try all extensions in parallel for better performance\n const pathsToCheck = extensions.map((extension) => normalizedBase + extension);\n const results = await Promise.all(\n pathsToCheck.map(async (p) => ({ path: p, exists: await cachedFileExists(p) })),\n );\n\n // Return the first one that exists (in order of preference)\n for (const result of results) {\n if (result.exists) {\n return result.path;\n }\n }\n\n // Try index files in directory\n if (await directoryExistsAsync(normalizedBase)) {\n const indexPaths = extensions.map((extension) =>\n Path.join(normalizedBase, `index${extension}`),\n );\n const indexResults = await Promise.all(\n indexPaths.map(async (p) => ({ path: p, exists: await cachedFileExists(p) })),\n );\n\n for (const result of indexResults) {\n if (result.exists) {\n return result.path;\n }\n }\n }\n\n return null;\n}\n\n/**\n * Check if import is a Node.js built-in module\n */\nfunction isNodeBuiltin(importPath: string): boolean {\n const builtins = [\n \"fs\",\n \"path\",\n \"http\",\n \"https\",\n \"crypto\",\n \"stream\",\n \"util\",\n \"events\",\n \"buffer\",\n \"child_process\",\n \"os\",\n \"url\",\n \"querystring\",\n \"zlib\",\n \"net\",\n \"tls\",\n \"dns\",\n \"dgram\",\n \"cluster\",\n \"worker_threads\",\n \"perf_hooks\",\n \"async_hooks\",\n \"timers\",\n \"readline\",\n \"repl\",\n \"vm\",\n \"assert\",\n \"console\",\n \"process\",\n \"v8\",\n ];\n\n // Check for node: prefix or direct builtin name\n if (importPath.startsWith(\"node:\")) return true;\n\n const moduleName = importPath.split(\"/\")[0];\n return builtins.includes(moduleName);\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;AA0BA,SAAgB,eAAe,QAAyB;CAOtD,MAAM,iBALkB,OACrB,QAAQ,qBAAqB,EAAE,CAAC,CAChC,QAAQ,aAAa,EAGa,CAAC,CACnC,QAAQ,sBAAsB,IAAI,CAAC,CACnC,QAAQ,sBAAsB,MAAI,CAAC,C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ACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;CACF;CAGA,IAAI,WAAW,WAAW,OAAO,GAAG,OAAO;CAE3C,MAAM,aAAa,WAAW,MAAM,GAAG,CAAC,CAAC;CACzC,OAAO,SAAS,SAAS,UAAU;AACrC"}
1
+ {"version":3,"file":"parse-imports.mjs","names":[],"sources":["../../../../../../../core/src/dev-server/parse-imports.ts"],"sourcesContent":["import { fileExistsAsync, directoryExistsAsync } from \"@warlock.js/fs\";\nimport { type ImportSpecifier, parse } from \"es-module-lexer\";\nimport path from \"node:path\";\nimport { Path } from \"../utils/normalized-path\";\nimport { tsconfigManager } from \"./tsconfig-manager\";\n\n/**\n * Detect if a file contains only type definitions (no runtime code)\n *\n * A file is considered type-only if ALL its exports are:\n * - interface declarations\n * - type alias declarations\n * - export type { ... } statements\n * - export type { ... } from \"...\" statements\n *\n * Files with any of these are NOT type-only:\n * - export const/let/var\n * - export function\n * - export class\n * - export default (non-type)\n * - export { ... } (without type keyword)\n * - export * from (without type keyword)\n *\n * @param source - The source code to analyze\n * @returns true if the file exports only types\n */\nexport function isTypeOnlyFile(source: string): boolean {\n // Remove comments to avoid false positives\n const withoutComments = source\n .replace(/\\/\\*[\\s\\S]*?\\*\\//g, \"\") // block comments\n .replace(/\\/\\/.*$/gm, \"\"); // line comments\n\n // Remove string literals to avoid false positives\n const withoutStrings = withoutComments\n .replace(/'(?:[^'\\\\]|\\\\.)*'/g, \"''\")\n .replace(/\"(?:[^\"\\\\]|\\\\.)*\"/g, '\"\"')\n .replace(/`(?:[^`\\\\]|\\\\.)*`/g, \"``\");\n\n // Patterns for type-only exports (these are safe)\n const typeOnlyPatterns = [\n /export\\s+type\\s+\\{[^}]*\\}/g, // export type { Foo, Bar }\n /export\\s+type\\s+\\{[^}]*\\}\\s+from\\s+['\"]/g, // export type { Foo } from \"...\"\n /export\\s+interface\\s+\\w+/g, // export interface Foo\n /export\\s+type\\s+\\w+\\s*=/g, // export type Foo =\n ];\n\n // Remove all type-only exports from consideration\n let remaining = withoutStrings;\n for (const pattern of typeOnlyPatterns) {\n remaining = remaining.replace(pattern, \"\");\n }\n\n // Patterns for runtime exports (these make the file NOT type-only)\n const runtimeExportPatterns = [\n /export\\s+(?:const|let|var)\\s+\\w+/g, // export const/let/var foo\n /export\\s+function\\s+\\w+/g, // export function foo\n /export\\s+async\\s+function\\s+\\w+/g, // export async function foo\n /export\\s+class\\s+\\w+/g, // export class Foo\n /export\\s+enum\\s+\\w+/g, // export enum Foo (enums have runtime value)\n /export\\s+default\\s+(?!type\\s)/g, // export default (not type)\n /export\\s+\\{[^}]*\\}(?!\\s+from)/g, // export { foo } (local re-export without type)\n /export\\s+\\{[^}]*\\}\\s+from\\s+['\"][^'\"]+['\"]/g, // export { foo } from (without type)\n /export\\s+\\*\\s+from\\s+['\"][^'\"]+['\"]/g, // export * from (re-exports everything)\n /export\\s+\\*\\s+as\\s+\\w+/g, // export * as namespace\n ];\n\n for (const pattern of runtimeExportPatterns) {\n if (pattern.test(remaining)) {\n // Reset regex lastIndex for subsequent tests\n pattern.lastIndex = 0;\n\n // Special case: check if export { } contains only type exports\n if (pattern.source.includes(\"export\\\\s+\\\\{\")) {\n const matches = remaining.match(/export\\s+\\{([^}]*)\\}(?:\\s+from\\s+['\"][^'\"]+['\"])?/g);\n if (matches) {\n for (const match of matches) {\n // Skip if it's already a type export\n if (/^export\\s+type\\s+/.test(match)) continue;\n\n // Extract the specifiers\n const specifiersMatch = match.match(/export\\s+\\{([^}]*)\\}/);\n if (specifiersMatch) {\n // Capture group 1 exists whenever the pattern matched. `?? \"\"`\n // yields an empty specifier list, which `some()` below reads as\n // \"no runtime specifier\" — the same answer an empty `{}` gives.\n const specifiers = specifiersMatch[1] ?? \"\";\n const items = specifiers\n .split(\",\")\n .map((s) => s.trim())\n .filter(Boolean);\n\n // If any specifier is NOT prefixed with \"type \", this is a runtime export\n const hasRuntimeSpecifier = items.some((item) => !item.startsWith(\"type \"));\n if (hasRuntimeSpecifier) {\n return false;\n }\n }\n }\n }\n continue;\n }\n\n return false;\n }\n }\n\n // If we get here, no runtime exports were found\n // But we should also verify the file has at least some type exports\n // (an empty file or file with only imports is not really \"type-only\")\n const hasTypeExports = typeOnlyPatterns.some((pattern) => {\n pattern.lastIndex = 0;\n return pattern.test(withoutStrings);\n });\n\n return hasTypeExports;\n}\n\n/**\n * Check if an import statement is a pure `import type` (the keyword sits\n * immediately after `import`, covering `import type { X }`, `import type Foo`,\n * and `import type * as Ns`).\n */\nfunction isTypeOnlyImport(line: string): boolean {\n const trimmed = line.trim();\n\n return trimmed.startsWith(\"import type \") || !!trimmed.match(/^import\\s+type\\s+[\\{\\*]/);\n}\n\n/**\n * Decide whether an `import ... from \"m\"` statement contributes any runtime\n * binding. Returns false for pure `import type` and for destructured imports\n * where every specifier is prefixed with the `type` keyword.\n */\nfunction hasRuntimeImports(line: string): boolean {\n const trimmed = line.trim();\n\n if (isTypeOnlyImport(trimmed)) {\n return false;\n }\n\n const specifiersMatch = trimmed.match(/import\\s+(?:type\\s+)?\\{([^}]+)\\}/);\n\n if (!specifiersMatch) {\n return true;\n }\n\n const items = (specifiersMatch[1] ?? \"\")\n .split(\",\")\n .map((s) => s.trim())\n .filter(Boolean);\n\n return !items.every((item) => /^type\\s+\\w+/.test(item));\n}\n\n/**\n * Decide whether an `export ... from \"m\"` statement re-exports only types.\n * Covers `export type { X } from`, `export type * from`, and\n * `export { type X, type Y } from`.\n */\nfunction isExportTypeOnlyStatement(line: string): boolean {\n const trimmed = line.trim();\n\n if (/^export\\s+type\\s+/.test(trimmed)) {\n return true;\n }\n\n const specifiersMatch = trimmed.match(/export\\s+\\{([^}]+)\\}/);\n\n if (!specifiersMatch) {\n return false;\n }\n\n const items = (specifiersMatch[1] ?? \"\")\n .split(\",\")\n .map((s) => s.trim())\n .filter(Boolean);\n\n return items.every((item) => /^type\\s+\\w+/.test(item));\n}\n\n/**\n * Extract import paths using regex (more reliable for TypeScript).\n * Each entry carries an `isTypeOnly` flag: true when every occurrence of the\n * path in the source is a type-only statement (no runtime binding).\n * A single runtime occurrence makes the path runtime.\n */\nfunction extractImportPathsWithRegex(\n source: string,\n): Array<{ path: string; originalLine: string; isTypeOnly: boolean }> {\n const imports: Array<{ path: string; originalLine: string; isTypeOnly: boolean }> = [];\n const seenPaths = new Map<string, number>();\n\n /**\n * Record an import path with its type-only flag.\n * If the same path appears in multiple statements, the edge is type-only\n * iff every occurrence is type-only — a single runtime statement makes it runtime.\n */\n const record = (importPath: string, originalLine: string, isTypeOnly: boolean): void => {\n if (!importPath) {\n return;\n }\n\n const existingIndex = seenPaths.get(importPath);\n\n if (existingIndex === undefined) {\n seenPaths.set(importPath, imports.length);\n imports.push({ path: importPath, originalLine, isTypeOnly });\n\n return;\n }\n\n if (!isTypeOnly) {\n const existing = imports[existingIndex];\n\n // `existingIndex` came from findIndex on this same array, so it is in\n // range; the compiler does not carry that here.\n if (existing) existing.isTypeOnly = false;\n }\n };\n\n // Pattern 1: Standard ES module imports (handles multiline)\n // Matches: import { ... } from \"path\", import Foo from \"path\", import Foo, { ... } from \"path\"\n const importRegex =\n /import\\s+(?:type\\s+)?(\\{[\\s\\S]*?\\}|\\*\\s+as\\s+\\w+|\\w+(?:\\s*,\\s*\\{[\\s\\S]*?\\})?)\\s+from\\s+['\"]([^'\"]+)['\"]/g;\n\n let match;\n\n while ((match = importRegex.exec(source)) !== null) {\n const fullMatch = match[0];\n const importPath = match[2];\n\n // Each pattern here captures its path in a group, so a match always carries\n // one. Skipping rather than recording keeps a malformed match out of the\n // dependency graph entirely — recording `undefined` would add an import\n // edge to a module named \"undefined\", which the dev server would then\n // watch, fail to resolve, and report against the wrong file.\n if (importPath === undefined) continue;\n\n const isTypeOnly = !hasRuntimeImports(fullMatch);\n\n record(importPath, fullMatch, isTypeOnly);\n }\n\n // Pattern 1b: Side-effect imports - import \"path\" — always runtime\n const sideEffectRegex = /import\\s+['\"]([^'\"]+)['\"]/g;\n\n while ((match = sideEffectRegex.exec(source)) !== null) {\n const sideEffectPath = match[1];\n\n if (sideEffectPath === undefined) continue;\n\n record(sideEffectPath, match[0], false);\n }\n\n // Pattern 2: Dynamic imports - import(\"path\") — always runtime\n const dynamicImportPattern = /import\\s*\\(\\s*['\"]([^'\"]+)['\"]\\s*\\)/g;\n\n while ((match = dynamicImportPattern.exec(source)) !== null) {\n const dynamicPath = match[1];\n\n if (dynamicPath === undefined) continue;\n\n record(dynamicPath, match[0], false);\n }\n\n // Pattern 3: Export from - export ... from \"path\"\n const exportFromPattern = /export\\s+(?:\\{[^}]*\\}|\\*|\\w+)\\s+from\\s+['\"]([^'\"]+)['\"]/g;\n\n while ((match = exportFromPattern.exec(source)) !== null) {\n const fullMatch = match[0];\n const exportPath = match[1];\n\n if (exportPath === undefined) continue;\n\n record(exportPath, fullMatch, isExportTypeOnlyStatement(fullMatch));\n }\n\n return imports;\n}\n\n/**\n * Metadata for a single resolved import edge.\n * `isTypeOnly` is true iff every import/export statement that references this\n * path is type-only (pure `import type`, `export type`, or destructured lists\n * where every specifier carries the `type` keyword). A single runtime\n * occurrence flips the flag to false — that's what matters for cycle detection.\n */\nexport type ResolvedImport = {\n absolutePath: string;\n isTypeOnly: boolean;\n};\n\n/**\n * Parse import/export statements in a TS/JS source file and return the\n * resolved dependency edges keyed by the original import path. Includes\n * type-only edges (flagged) so downstream consumers can distinguish runtime\n * cycles from type-only ones.\n *\n * @example\n * const importMap = await parseImports(source, \"/abs/path/to/file.ts\");\n * for (const [importPath, { absolutePath, isTypeOnly }] of importMap) {\n * // ...\n * }\n */\nexport async function parseImports(\n source: string,\n filePath: string,\n): Promise<Map<string, ResolvedImport>> {\n try {\n // Skip .d.ts files - they're type declarations, not runtime code\n if (filePath.endsWith(\".d.ts\")) {\n return new Map();\n }\n\n // Try es-module-lexer first (faster and more accurate for simple cases)\n try {\n const [imports] = await parse(source);\n\n if (imports && imports.length > 0) {\n return await resolveImports(imports as ImportSpecifier[], source, filePath);\n }\n } catch (lexerError) {\n // es-module-lexer failed, fall back to regex-based extraction\n // This is common with TypeScript files that have complex syntax\n }\n\n // Fallback: Use regex-based extraction (more forgiving with TypeScript)\n const regexImports = extractImportPathsWithRegex(source);\n const resolvedImports = new Map<string, ResolvedImport>();\n\n for (const { path: importPath, isTypeOnly } of regexImports) {\n if (isNodeBuiltin(importPath)) {\n continue;\n }\n\n if (!importPath.startsWith(\".\") && !tsconfigManager.isAlias(importPath)) {\n continue;\n }\n\n let resolvedPath: string | null = null;\n\n if (tsconfigManager.isAlias(importPath)) {\n resolvedPath = await resolveAliasImport(importPath);\n } else if (importPath.startsWith(\".\")) {\n resolvedPath = await resolveRelativeImport(importPath, filePath);\n }\n\n if (resolvedPath) {\n mergeResolvedImport(resolvedImports, importPath, resolvedPath, isTypeOnly);\n }\n }\n\n return resolvedImports;\n } catch (error) {\n console.error(`Error parsing imports for ${filePath}:`, error);\n\n return new Map();\n }\n}\n\n/**\n * Merge a resolved import into the output map, preserving the type-only rule:\n * a path is type-only iff every statement that references it is type-only.\n */\nfunction mergeResolvedImport(\n target: Map<string, ResolvedImport>,\n importPath: string,\n absolutePath: string,\n isTypeOnly: boolean,\n): void {\n const existing = target.get(importPath);\n\n if (!existing) {\n target.set(importPath, { absolutePath, isTypeOnly });\n\n return;\n }\n\n if (!isTypeOnly) {\n existing.isTypeOnly = false;\n }\n}\n\n/**\n * Resolve imports from `es-module-lexer` output. For each specifier, slice the\n * raw statement (`ss..se`) and re-run the type-only heuristic so we can flag\n * the edge correctly — the lexer itself does not distinguish `import type`.\n */\nasync function resolveImports(\n imports: ImportSpecifier[],\n source: string,\n filePath: string,\n): Promise<Map<string, ResolvedImport>> {\n const resolvedImports = new Map<string, ResolvedImport>();\n\n for (const imp of imports) {\n const importPath = imp.n;\n\n if (!importPath) {\n continue;\n }\n\n if (isNodeBuiltin(importPath)) {\n continue;\n }\n\n if (!importPath.startsWith(\".\") && !tsconfigManager.isAlias(importPath)) {\n continue;\n }\n\n let resolvedPath: string | null = null;\n\n if (tsconfigManager.isAlias(importPath)) {\n resolvedPath = await resolveAliasImport(importPath);\n } else if (importPath.startsWith(\".\")) {\n resolvedPath = await resolveRelativeImport(importPath, filePath);\n }\n\n if (!resolvedPath) {\n continue;\n }\n\n const isTypeOnly = isLexerStatementTypeOnly(imp, source);\n\n mergeResolvedImport(resolvedImports, importPath, resolvedPath, isTypeOnly);\n }\n\n return resolvedImports;\n}\n\n/**\n * Classify a single lexer-reported statement as type-only or runtime.\n * Dynamic imports (`import(...)`) are always runtime. For static\n * imports/export-from we slice the raw source and apply the same heuristic\n * the regex fallback uses.\n */\nfunction isLexerStatementTypeOnly(imp: ImportSpecifier, source: string): boolean {\n // Dynamic imports always execute — they cannot be type-only.\n // es-module-lexer reports dynamic with a.n === undefined typically, but\n // we guard by checking the statement prefix too.\n const statementStart = imp.ss;\n const statementEnd = imp.se;\n\n if (\n typeof statementStart !== \"number\" ||\n typeof statementEnd !== \"number\" ||\n statementEnd <= statementStart\n ) {\n return false;\n }\n\n const statement = source.slice(statementStart, statementEnd);\n const trimmed = statement.trim();\n\n if (trimmed.startsWith(\"import(\") || /^\\bimport\\s*\\(/.test(trimmed)) {\n return false;\n }\n\n if (trimmed.startsWith(\"export\")) {\n return isExportTypeOnlyStatement(statement);\n }\n\n return !hasRuntimeImports(statement);\n}\n\n/**\n * Resolve alias imports to actual file paths with extensions\n * Example: app/users/services/get-users.service -> /absolute/path/to/src/app/users/services/get-users.service.ts\n */\nasync function resolveAliasImport(importPath: string): Promise<string | null> {\n // Use tsconfig manager to resolve the alias to an absolute path\n const resolvedBase = tsconfigManager.resolveAliasToAbsolute(importPath);\n\n if (!resolvedBase) return null;\n\n // Try to resolve with extensions\n const resolvedPath = await tryResolveWithExtensions(resolvedBase);\n\n return resolvedPath;\n}\n\n/**\n * Resolve relative imports to actual file paths\n * Example: ./../services/get-user.service -> /absolute/path/to/services/get-user.service.ts\n */\nasync function resolveRelativeImport(\n importPath: string,\n currentFilePath: string,\n): Promise<string | null> {\n const dir = path.dirname(currentFilePath);\n // Use path.resolve to handle .. and . properly, then normalize to forward slashes\n const resolvedBase = Path.normalize(path.resolve(dir, importPath));\n\n // Try to resolve with extensions\n const resolvedPath = await tryResolveWithExtensions(resolvedBase);\n\n return resolvedPath;\n}\n\n/**\n * Try to resolve a file path by checking different extensions\n * TypeScript/JavaScript files can be imported without extensions\n *\n * @TODO: For better performance, we need to check the files in files orchestrator\n * instead of using the file system as we will be fetching all project files anyway.\n */\n// Cache for file existence checks to avoid redundant filesystem calls\nconst fileExistsCache = new Map<string, boolean>();\n\n/**\n * Clear the file exists cache\n * Should be called when new files are created to ensure fresh lookups\n */\nexport function clearFileExistsCache(): void {\n fileExistsCache.clear();\n}\n\nasync function cachedFileExists(filePath: string): Promise<boolean> {\n if (fileExistsCache.has(filePath)) {\n return fileExistsCache.get(filePath)!;\n }\n const exists = (await fileExistsAsync(filePath)) as boolean;\n fileExistsCache.set(filePath, exists);\n return exists;\n}\n\nasync function tryResolveWithExtensions(basePath: string): Promise<string | null> {\n // Normalize the base path first (handle Windows paths)\n const normalizedBase = Path.normalize(basePath);\n\n // List of extensions to try, in order of preference\n const extensions = [\".ts\", \".tsx\", \".js\", \".jsx\", \".mjs\", \".cjs\"];\n const validExtensions = new Set(extensions);\n\n // If the path already has a VALID code file extension, check if it exists\n const ext = path.extname(normalizedBase);\n if (ext && validExtensions.has(ext)) {\n if (await cachedFileExists(normalizedBase)) {\n return normalizedBase;\n }\n // If explicit extension doesn't exist, return null\n return null;\n }\n\n // Try all extensions in parallel for better performance\n const pathsToCheck = extensions.map((extension) => normalizedBase + extension);\n const results = await Promise.all(\n pathsToCheck.map(async (p) => ({ path: p, exists: await cachedFileExists(p) })),\n );\n\n // Return the first one that exists (in order of preference)\n for (const result of results) {\n if (result.exists) {\n return result.path;\n }\n }\n\n // Try index files in directory\n if (await directoryExistsAsync(normalizedBase)) {\n const indexPaths = extensions.map((extension) =>\n Path.join(normalizedBase, `index${extension}`),\n );\n const indexResults = await Promise.all(\n indexPaths.map(async (p) => ({ path: p, exists: await cachedFileExists(p) })),\n );\n\n for (const result of indexResults) {\n if (result.exists) {\n return result.path;\n }\n }\n }\n\n return null;\n}\n\n/**\n * Check if import is a Node.js built-in module\n */\nfunction isNodeBuiltin(importPath: string): boolean {\n const builtins = [\n \"fs\",\n \"path\",\n \"http\",\n \"https\",\n \"crypto\",\n \"stream\",\n \"util\",\n \"events\",\n \"buffer\",\n \"child_process\",\n \"os\",\n \"url\",\n \"querystring\",\n \"zlib\",\n \"net\",\n \"tls\",\n \"dns\",\n \"dgram\",\n \"cluster\",\n \"worker_threads\",\n \"perf_hooks\",\n \"async_hooks\",\n \"timers\",\n \"readline\",\n \"repl\",\n \"vm\",\n \"assert\",\n \"console\",\n \"process\",\n \"v8\",\n ];\n\n // Check for node: prefix or direct builtin name\n if (importPath.startsWith(\"node:\")) return true;\n\n // `split` always yields a first element. Falling back to the whole path\n // keeps the builtin check answering about a real name rather than undefined.\n const moduleName = importPath.split(\"/\")[0] ?? importPath;\n\n return builtins.includes(moduleName);\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;AA0BA,SAAgB,eAAe,QAAyB;CAOtD,MAAM,iBALkB,OACrB,QAAQ,qBAAqB,EAAE,CAAC,CAChC,QAAQ,aAAa,EAGa,CAAC,CACnC,QAAQ,sBAAsB,IAAI,CAAC,CACnC,QAAQ,sBAAsB,MAAI,CAAC,CACnC,QAAQ,sBAAsB,IAAI;CAGrC,MAAM,mBAAmB;EACvB;EACA;EACA;EACA;CACF;CAGA,IAAI,YAAY;CAChB,KAAK,MAAM,WAAW,kBACpB,YAAY,UAAU,QAAQ,SAAS,EAAE;CAiB3C,KAAK,MAAM,WAAW;EAZpB;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;CAGwC,GACxC,IAAI,QAAQ,KAAK,SAAS,GAAG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ACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;CACF;CAGA,IAAI,WAAW,WAAW,OAAO,GAAG,OAAO;CAI3C,MAAM,aAAa,WAAW,MAAM,GAAG,CAAC,CAAC,MAAM;CAE/C,OAAO,SAAS,SAAS,UAAU;AACrC"}
@@ -66,6 +66,7 @@ function decrypt(cipherText) {
66
66
  const parts = cipherText.split(":");
67
67
  if (parts.length !== 3) throw new Error("Invalid encrypted format. Expected iv:ciphertext:authTag");
68
68
  const [ivHex, encryptedHex, authTagHex] = parts;
69
+ if (ivHex === void 0 || encryptedHex === void 0 || authTagHex === void 0) throw new Error("Invalid encrypted format. Expected iv:ciphertext:authTag");
69
70
  const decipher = crypto.createDecipheriv(algorithm, keyBuffer, Buffer.from(ivHex, "hex"));
70
71
  decipher.setAuthTag(Buffer.from(authTagHex, "hex"));
71
72
  let decrypted = decipher.update(encryptedHex, "hex", "utf8");
@@ -1 +1 @@
1
- {"version":3,"file":"encrypt.mjs","names":[],"sources":["../../../../../../../core/src/encryption/encrypt.ts"],"sourcesContent":["import crypto from \"crypto\";\nimport { config } from \"../config\";\nimport { type EncryptionConfigurations } from \"./types\";\n\n/**\n * Default encryption algorithm.\n */\nconst DEFAULT_ALGORITHM = \"aes-256-gcm\";\n\n/**\n * Get the encryption key from config, validated as a 32-byte hex string.\n */\nfunction getEncryptionKey(): Buffer {\n const key = config.key<EncryptionConfigurations[\"key\"]>(\"encryption.key\");\n\n if (!key) {\n throw new Error(\n \"Missing encryption key. Set 'encryption.key' in your config (64 hex characters = 32 bytes).\",\n );\n }\n\n const buffer = Buffer.from(key, \"hex\");\n\n if (buffer.length !== 32) {\n throw new Error(\n `Encryption key must be exactly 32 bytes (64 hex characters). Got ${buffer.length} bytes for key ${key}.`,\n );\n }\n\n return buffer;\n}\n\n/**\n * Get the configured encryption algorithm, defaults to aes-256-gcm.\n */\nfunction getAlgorithm(): string {\n return config.key<EncryptionConfigurations[\"algorithm\"]>(\n \"encryption.algorithm\",\n DEFAULT_ALGORITHM,\n )!;\n}\n\n/**\n * Encrypts a plaintext string using AES-256-GCM (or the configured algorithm).\n * Returns a combined string in the format `iv:ciphertext:authTag`.\n *\n * @example\n * import { encrypt } from \"@warlock.js/core\";\n *\n * const encrypted = encrypt(\"sk-proj-12345\");\n * // => \"a1b2c3...:d4e5f6...:g7h8i9...\"\n */\nexport function encrypt(plainText: string): string {\n if (!plainText) return plainText;\n\n const keyBuffer = getEncryptionKey();\n const algorithm = getAlgorithm();\n\n try {\n // IV must be unique per encryption. 16 bytes is standard for AES.\n const iv = crypto.randomBytes(16);\n const cipher = crypto.createCipheriv(algorithm, keyBuffer, iv);\n\n let encrypted = cipher.update(plainText, \"utf8\", \"hex\");\n encrypted += cipher.final(\"hex\");\n\n // Auth tag validates ciphertext integrity (tamper detection)\n const authTag = (cipher as crypto.CipherGCM).getAuthTag().toString(\"hex\");\n\n return `${iv.toString(\"hex\")}:${encrypted}:${authTag}`;\n } catch (error) {\n throw new Error(`Encryption failed: ${(error as Error).message}`);\n }\n}\n\n/**\n * Decrypts a string previously encrypted with {@link encrypt}.\n * Expects the format `iv:ciphertext:authTag`.\n *\n * @example\n * import { decrypt } from \"@warlock.js/core\";\n *\n * const original = decrypt(encryptedString);\n * // => \"sk-proj-12345\"\n */\nexport function decrypt(cipherText: string): string {\n if (!cipherText) return cipherText;\n\n const keyBuffer = getEncryptionKey();\n const algorithm = getAlgorithm();\n\n try {\n const parts = cipherText.split(\":\");\n\n if (parts.length !== 3) {\n throw new Error(\"Invalid encrypted format. Expected iv:ciphertext:authTag\");\n }\n\n const [ivHex, encryptedHex, authTagHex] = parts;\n\n const decipher = crypto.createDecipheriv(algorithm, keyBuffer, Buffer.from(ivHex, \"hex\"));\n\n (decipher as crypto.DecipherGCM).setAuthTag(Buffer.from(authTagHex, \"hex\"));\n\n let decrypted = decipher.update(encryptedHex, \"hex\", \"utf8\");\n // .final() throws if auth tag is invalid (data tampered)\n decrypted += decipher.final(\"utf8\");\n\n return decrypted;\n } catch (error) {\n throw new Error(`Decryption failed: ${(error as Error).message}`);\n }\n}\n"],"mappings":";;;;;;;;AAOA,MAAM,oBAAoB;;;;AAK1B,SAAS,mBAA2B;CAClC,MAAM,MAAM,OAAO,IAAqC,gBAAgB;CAExE,IAAI,CAAC,KACH,MAAM,IAAI,MACR,6FACF;CAGF,MAAM,SAAS,OAAO,KAAK,KAAK,KAAK;CAErC,IAAI,OAAO,WAAW,IACpB,MAAM,IAAI,MACR,oEAAoE,OAAO,OAAO,iBAAiB,IAAI,EACzG;CAGF,OAAO;AACT;;;;AAKA,SAAS,eAAuB;CAC9B,OAAO,OAAO,IACZ,wBACA,iBACF;AACF;;;;;;;;;;;AAYA,SAAgB,QAAQ,WAA2B;CACjD,IAAI,CAAC,WAAW,OAAO;CAEvB,MAAM,YAAY,iBAAiB;CACnC,MAAM,YAAY,aAAa;CAE/B,IAAI;EAEF,MAAM,KAAK,OAAO,YAAY,EAAE;EAChC,MAAM,SAAS,OAAO,eAAe,WAAW,WAAW,EAAE;EAE7D,IAAI,YAAY,OAAO,OAAO,WAAW,QAAQ,KAAK;EACtD,aAAa,OAAO,MAAM,KAAK;EAG/B,MAAM,UAAW,OAA4B,WAAW,CAAC,CAAC,SAAS,KAAK;EAExE,OAAO,GAAG,GAAG,SAAS,KAAK,EAAE,GAAG,UAAU,GAAG;CAC/C,SAAS,OAAO;EACd,MAAM,IAAI,MAAM,sBAAuB,MAAgB,SAAS;CAClE;AACF;;;;;;;;;;;AAYA,SAAgB,QAAQ,YAA4B;CAClD,IAAI,CAAC,YAAY,OAAO;CAExB,MAAM,YAAY,iBAAiB;CACnC,MAAM,YAAY,aAAa;CAE/B,IAAI;EACF,MAAM,QAAQ,WAAW,MAAM,GAAG;EAElC,IAAI,MAAM,WAAW,GACnB,MAAM,IAAI,MAAM,0DAA0D;EAG5E,MAAM,CAAC,OAAO,cAAc,cAAc;EAE1C,MAAM,WAAW,OAAO,iBAAiB,WAAW,WAAW,OAAO,KAAK,OAAO,KAAK,CAAC;EAExF,AAAC,SAAgC,WAAW,OAAO,KAAK,YAAY,KAAK,CAAC;EAE1E,IAAI,YAAY,SAAS,OAAO,cAAc,OAAO,MAAM;EAE3D,aAAa,SAAS,MAAM,MAAM;EAElC,OAAO;CACT,SAAS,OAAO;EACd,MAAM,IAAI,MAAM,sBAAuB,MAAgB,SAAS;CAClE;AACF"}
1
+ {"version":3,"file":"encrypt.mjs","names":[],"sources":["../../../../../../../core/src/encryption/encrypt.ts"],"sourcesContent":["import crypto from \"crypto\";\nimport { config } from \"../config\";\nimport { type EncryptionConfigurations } from \"./types\";\n\n/**\n * Default encryption algorithm.\n */\nconst DEFAULT_ALGORITHM = \"aes-256-gcm\";\n\n/**\n * Get the encryption key from config, validated as a 32-byte hex string.\n */\nfunction getEncryptionKey(): Buffer {\n const key = config.key<EncryptionConfigurations[\"key\"]>(\"encryption.key\");\n\n if (!key) {\n throw new Error(\n \"Missing encryption key. Set 'encryption.key' in your config (64 hex characters = 32 bytes).\",\n );\n }\n\n const buffer = Buffer.from(key, \"hex\");\n\n if (buffer.length !== 32) {\n throw new Error(\n `Encryption key must be exactly 32 bytes (64 hex characters). Got ${buffer.length} bytes for key ${key}.`,\n );\n }\n\n return buffer;\n}\n\n/**\n * Get the configured encryption algorithm, defaults to aes-256-gcm.\n */\nfunction getAlgorithm(): string {\n return config.key<EncryptionConfigurations[\"algorithm\"]>(\n \"encryption.algorithm\",\n DEFAULT_ALGORITHM,\n )!;\n}\n\n/**\n * Encrypts a plaintext string using AES-256-GCM (or the configured algorithm).\n * Returns a combined string in the format `iv:ciphertext:authTag`.\n *\n * @example\n * import { encrypt } from \"@warlock.js/core\";\n *\n * const encrypted = encrypt(\"sk-proj-12345\");\n * // => \"a1b2c3...:d4e5f6...:g7h8i9...\"\n */\nexport function encrypt(plainText: string): string {\n if (!plainText) return plainText;\n\n const keyBuffer = getEncryptionKey();\n const algorithm = getAlgorithm();\n\n try {\n // IV must be unique per encryption. 16 bytes is standard for AES.\n const iv = crypto.randomBytes(16);\n const cipher = crypto.createCipheriv(algorithm, keyBuffer, iv);\n\n let encrypted = cipher.update(plainText, \"utf8\", \"hex\");\n encrypted += cipher.final(\"hex\");\n\n // Auth tag validates ciphertext integrity (tamper detection)\n const authTag = (cipher as crypto.CipherGCM).getAuthTag().toString(\"hex\");\n\n return `${iv.toString(\"hex\")}:${encrypted}:${authTag}`;\n } catch (error) {\n throw new Error(`Encryption failed: ${(error as Error).message}`);\n }\n}\n\n/**\n * Decrypts a string previously encrypted with {@link encrypt}.\n * Expects the format `iv:ciphertext:authTag`.\n *\n * @example\n * import { decrypt } from \"@warlock.js/core\";\n *\n * const original = decrypt(encryptedString);\n * // => \"sk-proj-12345\"\n */\nexport function decrypt(cipherText: string): string {\n if (!cipherText) return cipherText;\n\n const keyBuffer = getEncryptionKey();\n const algorithm = getAlgorithm();\n\n try {\n const parts = cipherText.split(\":\");\n\n if (parts.length !== 3) {\n throw new Error(\"Invalid encrypted format. Expected iv:ciphertext:authTag\");\n }\n\n const [ivHex, encryptedHex, authTagHex] = parts;\n\n if (ivHex === undefined || encryptedHex === undefined || authTagHex === undefined) {\n throw new Error(\"Invalid encrypted format. Expected iv:ciphertext:authTag\");\n }\n\n const decipher = crypto.createDecipheriv(algorithm, keyBuffer, Buffer.from(ivHex, \"hex\"));\n\n (decipher as crypto.DecipherGCM).setAuthTag(Buffer.from(authTagHex, \"hex\"));\n\n let decrypted = decipher.update(encryptedHex, \"hex\", \"utf8\");\n // .final() throws if auth tag is invalid (data tampered)\n decrypted += decipher.final(\"utf8\");\n\n return decrypted;\n } catch (error) {\n throw new Error(`Decryption failed: ${(error as Error).message}`);\n }\n}\n"],"mappings":";;;;;;;;AAOA,MAAM,oBAAoB;;;;AAK1B,SAAS,mBAA2B;CAClC,MAAM,MAAM,OAAO,IAAqC,gBAAgB;CAExE,IAAI,CAAC,KACH,MAAM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