@warlock.js/core 5.5.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 (171) hide show
  1. package/CHANGELOG.md +32 -0
  2. package/esm/application/app.d.mts.map +1 -1
  3. package/esm/application/app.mjs +7 -1
  4. package/esm/application/app.mjs.map +1 -1
  5. package/esm/benchmark/profiler.d.mts.map +1 -1
  6. package/esm/benchmark/profiler.mjs +4 -3
  7. package/esm/benchmark/profiler.mjs.map +1 -1
  8. package/esm/cli/cli-commands.manager.mjs +10 -7
  9. package/esm/cli/cli-commands.manager.mjs.map +1 -1
  10. package/esm/cli/cli-commands.utils.mjs.map +1 -1
  11. package/esm/cli/commands/doctor/checks/optional-peers.check.mjs.map +1 -1
  12. package/esm/cli/commands/doctor/checks/release-hygiene.check.mjs.map +1 -1
  13. package/esm/cli/commands/generate/generators/column-dsl-parser.mjs.map +1 -1
  14. package/esm/cli/commands/generate/generators/migration.generator.mjs.map +1 -1
  15. package/esm/cli/commands/routes/format-routes-table.mjs +3 -3
  16. package/esm/cli/commands/routes/format-routes-table.mjs.map +1 -1
  17. package/esm/cli/commands/routes/route-row.mjs.map +1 -1
  18. package/esm/cli/commands/routes.command.mjs.map +1 -1
  19. package/esm/cli/framework-cli-commands.mjs.map +1 -1
  20. package/esm/cli/parse-cli-args.mjs +1 -0
  21. package/esm/cli/parse-cli-args.mjs.map +1 -1
  22. package/esm/cli/string-similarity.mjs +13 -4
  23. package/esm/cli/string-similarity.mjs.map +1 -1
  24. package/esm/commands/cli-command.d.mts.map +1 -1
  25. package/esm/commands/cli-command.mjs +5 -2
  26. package/esm/commands/cli-command.mjs.map +1 -1
  27. package/esm/config/config-loader.mjs +3 -1
  28. package/esm/config/config-loader.mjs.map +1 -1
  29. package/esm/config/locale-configuration.mjs +11 -1
  30. package/esm/config/locale-configuration.mjs.map +1 -1
  31. package/esm/container/container-instance-registry.mjs +40 -0
  32. package/esm/container/container-instance-registry.mjs.map +1 -0
  33. package/esm/container/index.d.mts +11 -0
  34. package/esm/container/index.d.mts.map +1 -1
  35. package/esm/container/index.mjs +11 -0
  36. package/esm/container/index.mjs.map +1 -1
  37. package/esm/database/drop-tables-action.mjs.map +1 -1
  38. package/esm/database/migrate-action.mjs.map +1 -1
  39. package/esm/database/seed-command-action.mjs.map +1 -1
  40. package/esm/dev-server/dependency-graph.d.mts.map +1 -1
  41. package/esm/dev-server/dependency-graph.mjs +2 -1
  42. package/esm/dev-server/dependency-graph.mjs.map +1 -1
  43. package/esm/dev-server/dev-logger.mjs +7 -5
  44. package/esm/dev-server/dev-logger.mjs.map +1 -1
  45. package/esm/dev-server/file-event-handler.mjs.map +1 -1
  46. package/esm/dev-server/files-orchestrator.mjs +1 -1
  47. package/esm/dev-server/files-orchestrator.mjs.map +1 -1
  48. package/esm/dev-server/layer-executor.mjs.map +1 -1
  49. package/esm/dev-server/loader/build-transpile-init.mjs.map +1 -1
  50. package/esm/dev-server/loader/load-hook.mjs.map +1 -1
  51. package/esm/dev-server/loader/register-loader.mjs.map +1 -1
  52. package/esm/dev-server/loader/resolve-hook.mjs.map +1 -1
  53. package/esm/dev-server/loader/transpile-cache.mjs.map +1 -1
  54. package/esm/dev-server/module-loader.mjs.map +1 -1
  55. package/esm/dev-server/parse-imports.mjs +22 -8
  56. package/esm/dev-server/parse-imports.mjs.map +1 -1
  57. package/esm/dev-server/type-generator.mjs.map +1 -1
  58. package/esm/dev-server/types.d.mts.map +1 -1
  59. package/esm/dev-server/utils.mjs.map +1 -1
  60. package/esm/encryption/encrypt.mjs +1 -0
  61. package/esm/encryption/encrypt.mjs.map +1 -1
  62. package/esm/errors/container-key-missing-error.mjs +28 -0
  63. package/esm/errors/container-key-missing-error.mjs.map +1 -0
  64. package/esm/errors/unknown-locale-error.mjs +28 -0
  65. package/esm/errors/unknown-locale-error.mjs.map +1 -0
  66. package/esm/generations/add-command.action.mjs +8 -2
  67. package/esm/generations/add-command.action.mjs.map +1 -1
  68. package/esm/generations/features/access.feature.mjs.map +1 -1
  69. package/esm/generations/features/ai-anthropic.feature.mjs.map +1 -1
  70. package/esm/generations/features/ai-bedrock.feature.mjs.map +1 -1
  71. package/esm/generations/features/ai-google.feature.mjs.map +1 -1
  72. package/esm/generations/features/ai-ollama.feature.mjs.map +1 -1
  73. package/esm/generations/features/ai-openai.feature.mjs.map +1 -1
  74. package/esm/generations/features/ai-panoptic.feature.mjs.map +1 -1
  75. package/esm/generations/features/ai-tools.feature.mjs.map +1 -1
  76. package/esm/generations/features/ai-workspace.feature.mjs.map +1 -1
  77. package/esm/generations/features/ai.feature.mjs.map +1 -1
  78. package/esm/generations/features/herald.feature.mjs.map +1 -1
  79. package/esm/generations/features/notifications.feature.mjs.map +1 -1
  80. package/esm/generations/features/scheduler.feature.mjs.map +1 -1
  81. package/esm/generations/features/shared/patch-tsconfig-include.mjs.map +1 -1
  82. package/esm/generations/features/shared/relocate-conflicting-home-route.mjs +6 -1
  83. package/esm/generations/features/shared/relocate-conflicting-home-route.mjs.map +1 -1
  84. package/esm/generations/features/tailwind.feature.mjs.map +1 -1
  85. package/esm/generations/features/types.mjs.map +1 -1
  86. package/esm/generations/features/web.feature.mjs.map +1 -1
  87. package/esm/http/context/request-memo.mjs.map +1 -1
  88. package/esm/http/middleware/cache-response-middleware.d.mts.map +1 -1
  89. package/esm/http/middleware/cache-response-middleware.mjs.map +1 -1
  90. package/esm/http/middleware/concurrency-limit.middleware.mjs.map +1 -1
  91. package/esm/http/middleware/idempotency.middleware.d.mts.map +1 -1
  92. package/esm/http/middleware/idempotency.middleware.mjs.map +1 -1
  93. package/esm/http/middleware/maintenance.middleware.mjs +1 -2
  94. package/esm/http/middleware/maintenance.middleware.mjs.map +1 -1
  95. package/esm/http/middleware/max-body-size.middleware.mjs.map +1 -1
  96. package/esm/http/middleware/rate-limit.middleware.mjs.map +1 -1
  97. package/esm/http/middleware/utils/cidr-match.d.mts.map +1 -1
  98. package/esm/http/middleware/utils/cidr-match.mjs +1 -0
  99. package/esm/http/middleware/utils/cidr-match.mjs.map +1 -1
  100. package/esm/http/port-preflight.d.mts.map +1 -1
  101. package/esm/http/port-preflight.mjs.map +1 -1
  102. package/esm/http/request.d.mts.map +1 -1
  103. package/esm/http/request.mjs +16 -9
  104. package/esm/http/request.mjs.map +1 -1
  105. package/esm/http/response.d.mts +38 -0
  106. package/esm/http/response.d.mts.map +1 -1
  107. package/esm/http/response.mjs +47 -0
  108. package/esm/http/response.mjs.map +1 -1
  109. package/esm/http/server.d.mts.map +1 -1
  110. package/esm/http/server.mjs.map +1 -1
  111. package/esm/http/types.d.mts.map +1 -1
  112. package/esm/image/image.d.mts.map +1 -1
  113. package/esm/image/image.mjs.map +1 -1
  114. package/esm/mail/send-mail.mjs.map +1 -1
  115. package/esm/production/build-contributions.mjs.map +1 -1
  116. package/esm/production/bundle-framework-dependencies.mjs +152 -0
  117. package/esm/production/bundle-framework-dependencies.mjs.map +1 -0
  118. package/esm/production/production-builder.mjs +30 -3
  119. package/esm/production/production-builder.mjs.map +1 -1
  120. package/esm/production/production-supervisor.mjs.map +1 -1
  121. package/esm/production/tsconfig-path-aliases.mjs +99 -0
  122. package/esm/production/tsconfig-path-aliases.mjs.map +1 -0
  123. package/esm/react/index.d.mts.map +1 -1
  124. package/esm/react/index.mjs.map +1 -1
  125. package/esm/repositories/adapters/cascade/filter-applicator.mjs +4 -2
  126. package/esm/repositories/adapters/cascade/filter-applicator.mjs.map +1 -1
  127. package/esm/repositories/contracts/query-builder.contract.d.mts.map +1 -1
  128. package/esm/repositories/contracts/types.d.mts.map +1 -1
  129. package/esm/resource/resource-field-builder.d.mts.map +1 -1
  130. package/esm/resource/resource-field-builder.mjs.map +1 -1
  131. package/esm/resource/types.d.mts.map +1 -1
  132. package/esm/router/positional-handler-diagnostics.d.mts.map +1 -1
  133. package/esm/router/positional-handler-diagnostics.mjs +9 -3
  134. package/esm/router/positional-handler-diagnostics.mjs.map +1 -1
  135. package/esm/router/route-registry.mjs +1 -1
  136. package/esm/router/route-registry.mjs.map +1 -1
  137. package/esm/router/router.d.mts.map +1 -1
  138. package/esm/router/router.mjs +1 -2
  139. package/esm/router/router.mjs.map +1 -1
  140. package/esm/router/types.d.mts.map +1 -1
  141. package/esm/storage/drivers/cloud-driver.d.mts.map +1 -1
  142. package/esm/storage/drivers/cloud-driver.mjs.map +1 -1
  143. package/esm/storage/scoped-storage.d.mts.map +1 -1
  144. package/esm/storage/scoped-storage.mjs +1 -0
  145. package/esm/storage/scoped-storage.mjs.map +1 -1
  146. package/esm/storage/storage.d.mts.map +1 -1
  147. package/esm/storage/storage.mjs +6 -2
  148. package/esm/storage/storage.mjs.map +1 -1
  149. package/esm/storage/types.d.mts.map +1 -1
  150. package/esm/storage/utils/contain-path.mjs.map +1 -1
  151. package/esm/storage/utils/safe-fetch.d.mts.map +1 -1
  152. package/esm/storage/utils/safe-fetch.mjs +6 -1
  153. package/esm/storage/utils/safe-fetch.mjs.map +1 -1
  154. package/esm/tests/start-http-development-server.d.mts.map +1 -1
  155. package/esm/tests/start-http-development-server.mjs.map +1 -1
  156. package/esm/tests/test-lifecycle-state.mjs.map +1 -1
  157. package/esm/tests/test-setup-timeout.mjs.map +1 -1
  158. package/esm/tests/vitest-setup.d.mts.map +1 -1
  159. package/esm/tests/vitest-setup.mjs.map +1 -1
  160. package/esm/use-cases/use-cases-registry.d.mts.map +1 -1
  161. package/esm/use-cases/use-cases-registry.mjs.map +1 -1
  162. package/esm/utils/app-log.mjs.map +1 -1
  163. package/esm/utils/queue.mjs.map +1 -1
  164. package/esm/utils/sleep.mjs.map +1 -1
  165. package/esm/utils/version-compare.d.mts.map +1 -1
  166. package/esm/utils/version-compare.mjs +12 -4
  167. package/esm/utils/version-compare.mjs.map +1 -1
  168. package/esm/validation/plugins/database-plugin.mjs.map +1 -1
  169. package/esm/vite/lower-stage3-decorators.mjs +1 -0
  170. package/esm/vite/lower-stage3-decorators.mjs.map +1 -1
  171. package/package.json +12 -12
@@ -1 +1 @@
1
- {"version":3,"file":"migrate-action.mjs","names":[],"sources":["../../../../../../../core/src/database/migrate-action.ts"],"sourcesContent":["import { colors } from \"@mongez/copper\";\r\nimport {\r\n exportMigrationsSQL,\r\n freshMigrate,\r\n listExecutedMigrations,\r\n Migration,\n type MigrationConstructor,\r\n migrationRunner,\r\n rollbackMigrations,\r\n runMigrations,\r\n} from \"@warlock.js/cascade\";\r\nimport dayjs from \"dayjs\";\r\nimport path from \"path\";\r\nimport type { CommandActionData } from \"../commands/types\";\r\nimport { filesOrchestrator } from \"../dev-server/files-orchestrator\";\r\nimport { Path } from \"../utils/normalized-path\";\r\nimport { getFilesFromDirectory } from \"../dev-server/utils\";\r\nimport { srcPath } from \"../utils\";\r\nimport { warlockConfigManager } from \"../warlock-config/warlock-config.manager\";\r\nimport { exitCodeFor, PENDING_EXIT_CODE } from \"./pending-exit-code\";\r\nimport {\r\n resolvePendingMigrations,\r\n type PendingMigrationsResult,\r\n} from \"./resolve-pending-migrations\";\r\n\r\n/**\r\n * `--list` — print the migration state: what has run, then what will run next.\r\n *\r\n * The executed section is printed FIRST and unconditionally, before anything\r\n * touches disk or config. That ordering is the contract: reading migrations\r\n * from the table cannot fail because of a broken migration file, and `--list`\r\n * is the command an operator reaches for *during* an incident. The pending\r\n * section is best-effort on top of an answer that is already on screen.\r\n *\r\n * Always exits 0. It is a report; `--pending` is the gate.\r\n */\r\nasync function listMigrationsAction() {\r\n await printExecutedMigrations();\r\n\r\n const pending = await resolvePendingMigrations(loadAllMigrations);\r\n\r\n printPendingMigrations(pending);\r\n}\r\n\r\nasync function printExecutedMigrations() {\r\n const createdMigrations = await listExecutedMigrations();\r\n\r\n console.log(`\\nTotal Executed Migrations: ${colors.green(createdMigrations.length)}\\n`);\r\n\r\n if (createdMigrations.length === 0) {\r\n console.log(colors.gray(\" No migrations have been executed yet.\\n\"));\r\n return;\r\n }\r\n\r\n // Display each migration as a block\r\n for (const migration of createdMigrations) {\r\n const executedAt = dayjs(migration.executedAt).format(\"DD-MM-YYYY hh:mm:ss A\");\r\n const createdAt = migration.createdAt\r\n ? dayjs(migration.createdAt).format(\"DD-MM-YYYY hh:mm:ss A\")\r\n : null;\r\n\r\n // Migration name with checkmark icon\r\n console.log(` ${colors.green(\"✔\")} ${colors.cyanBright(migration.name)}`);\r\n\r\n // Executed date\r\n console.log(` ${colors.gray(\"Executed:\")} ${colors.white(executedAt)}`);\r\n\r\n // Created date (if available)\r\n if (createdAt) {\r\n console.log(` ${colors.gray(\"Created:\")} ${colors.yellow(createdAt)}`);\r\n }\r\n\r\n console.log(\"\"); // Empty line between migrations\r\n }\r\n}\r\n\r\n/**\r\n * Print the pending section shared by `--list` and `--pending`.\r\n *\r\n * An unavailable result prints an explicit line and NEVER a count. \"0 pending\"\r\n * over a tree we failed to read is the one output this whole feature exists to\r\n * prevent.\r\n */\r\nfunction printPendingMigrations(result: PendingMigrationsResult) {\r\n if (result.type === \"unavailable\") {\r\n console.log(\r\n `${colors.yellowBright(\"Pending: unavailable\")} — ${result.reason}\\n` +\r\n colors.gray(\" The executed list above is still accurate.\\n\"),\r\n );\r\n return;\r\n }\r\n\r\n const { migrations } = result;\r\n\r\n console.log(`Total Pending Migrations: ${colors.green(migrations.length)}\\n`);\r\n\r\n if (migrations.length === 0) {\r\n console.log(colors.gray(\" Nothing pending — the database is up to date.\\n\"));\r\n return;\r\n }\r\n\r\n // Numbered because the ORDER is the answer: this is what the next\r\n // `warlock migrate` will do, in the sequence it will do it.\r\n migrations.forEach((migration, index) => {\r\n console.log(` ${colors.gray(`${index + 1}.`)} ${colors.cyanBright(migration.name)}`);\r\n });\r\n\r\n console.log(\"\");\r\n}\r\n\r\n/**\r\n * `--pending` — the scriptable half. Same computation as `--list`'s pending\r\n * section, different exit contract: see {@link PENDING_EXIT_CODE}.\r\n */\r\nasync function pendingMigrationsAction() {\r\n const result = await resolvePendingMigrations(loadAllMigrations);\r\n\r\n printPendingMigrations(result);\r\n\r\n const exitCode = exitCodeFor(result);\r\n\r\n if (exitCode === PENDING_EXIT_CODE.unavailable) {\r\n console.error(\r\n colors.redBright(\"Could not determine the pending set — exiting 2 rather than reporting 0.\"),\r\n );\r\n }\r\n\r\n process.exit(exitCode);\r\n}\r\n\r\nasync function allMigrationsFilesAction() {\r\n // get all available migration files in the project\r\n const files = (await migrationFiles()).map((path) => Path.toRelative(path));\r\n console.log(`Total Migration Files: ${colors.green(files.length)}`);\r\n\r\n for (const file of files) {\r\n console.log(colors.yellowBright(file));\r\n }\r\n}\r\n\r\n/**\r\n * If path is provided, then run the migration runner against that file only\r\n * If fresh is provided, then rollback all migrations and run all migrations\r\n * If rollback is provided, then run the migration runner against all files in reverse order\r\n */\r\nexport async function migrateAction(options: CommandActionData) {\r\n const { fresh, path, rollback, all, list, pending, sql, pendingOnly, compact } = options.options;\r\n\r\n if (list) {\r\n return await listMigrationsAction();\r\n }\r\n\r\n if (pending) {\r\n return await pendingMigrationsAction();\r\n }\r\n\r\n if (all) {\r\n return await allMigrationsFilesAction();\r\n }\r\n\r\n if (path) {\r\n await loadMigrationFile(Path.toAbsolute(path as string));\r\n } else {\r\n await loadAllMigrations();\r\n }\r\n\r\n if (fresh && rollback) {\r\n console.log(colors.redBright(\"You can't use --fresh and --rollback together\"));\r\n process.exit(1);\r\n }\r\n\r\n if (rollback) {\r\n await rollbackMigrations({ all: true });\r\n return;\r\n }\r\n\r\n if (sql) {\r\n await exportMigrationsSQL({\r\n pendingOnly: pendingOnly as boolean,\r\n compact: compact as boolean,\r\n });\r\n return;\r\n }\r\n\r\n if (fresh) {\r\n await freshMigrate();\r\n return;\r\n }\r\n\r\n await runMigrations();\r\n}\r\n\r\nasync function loadMigrationFile(absPath: string) {\r\n const relativePath = Path.toRelative(absPath);\r\n\r\n // MigrationConstructor, not `typeof Migration`: a migration file default-exports a\r\n // CONCRETE subclass, while Migration itself is abstract and so cannot satisfy a\r\n // `new () => ...` parameter. The annotation described the base class rather than\r\n // what is actually loaded, and that is what migrationRunner.register() rejected.\r\n const loadedModule = await filesOrchestrator.load<{ default: MigrationConstructor }>(relativePath);\r\n\r\n if (!loadedModule?.default) {\r\n throw new Error(`${Path.toRelative(absPath)} must have a default export`);\r\n }\r\n\r\n const MigrationClass = loadedModule.default;\r\n\r\n if (!MigrationClass.migrationName) {\r\n MigrationClass.migrationName = path\r\n .basename(absPath)\r\n .split(\".\")[0]\r\n .replace(\"-migration\", \"\")\r\n .replace(\"_migration\", \"\");\r\n }\r\n\r\n // Extract createdAt timestamp from filename if not already set\r\n // Expected format: MM-DD-YYYY_HH-MM-SS-name.migration.ts\r\n if (!MigrationClass.createdAt) {\r\n const filename = path.basename(absPath);\r\n const timestampMatch = filename.match(/^(\\d{2}-\\d{2}-\\d{4}_\\d{2}-\\d{2}-\\d{2})/);\r\n if (timestampMatch) {\r\n MigrationClass.createdAt = timestampMatch[1];\r\n }\r\n }\r\n\r\n migrationRunner.register(MigrationClass);\r\n}\r\n\r\n/**\r\n *\r\n * @returns List of absolute paths to migration files\r\n */\r\nasync function migrationFiles() {\r\n const migrationFiles = await getFilesFromDirectory(srcPath(\"app\"), \"*/models/*/migrations/*\");\r\n const separateMigrationsFolderFIles = await getFilesFromDirectory(\r\n srcPath(\"app\"),\r\n \"*/migrations/*\",\r\n );\r\n\r\n const migrations = [...migrationFiles, ...separateMigrationsFolderFIles];\r\n\r\n return migrations;\r\n}\r\n\r\nasync function loadAllMigrations() {\r\n // Load config-registered migrations (from packages like @warlock.js/auth)\r\n const configMigrations = warlockConfigManager.get(\"database\")?.migrations || [];\r\n\r\n for (const MigrationClass of configMigrations) {\r\n // Use class name as migration name if not set\r\n if (!MigrationClass.migrationName) {\r\n MigrationClass.migrationName = MigrationClass.name;\r\n }\r\n migrationRunner.register(MigrationClass);\r\n }\r\n\r\n // Always load file-based migrations from src/app, regardless of config\r\n const migrations = await migrationFiles();\r\n for (const migrationFile of migrations) {\r\n await loadMigrationFile(migrationFile);\r\n }\r\n}\r\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;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MAAM,eAAe,MAAM,kBAAkB,KAAwC,YAAY;CAEjG,IAAI,CAAC,cAAc,SACjB,MAAM,IAAI,MAAM,GAAG,KAAK,WAAW,OAAO,EAAE,4BAA4B;CAG1E,MAAM,iBAAiB,aAAa;CAEpC,IAAI,CAAC,eAAe,eAClB,eAAe,gBAAgB,KAC5B,SAAS,OAAO,CAAC,CACjB,MAAM,GAAG,CAAC,CAAC,EAAE,CACb,QAAQ,cAAc,EAAE,CAAC,CACzB,QAAQ,cAAc,EAAE;CAK7B,IAAI,CAAC,eAAe,WAAW;EAE7B,MAAM,iBADW,KAAK,SAAS,OACD,CAAC,CAAC,MAAM,wCAAwC;EAC9E,IAAI,gBACF,eAAe,YAAY,eAAe;CAE9C;CAEA,gBAAgB,SAAS,cAAc;AACzC;;;;;AAMA,eAAe,iBAAiB;CAC9B,MAAM,iBAAiB,MAAM,sBAAsB,QAAQ,KAAK,GAAG,yBAAyB;CAC5F,MAAM,gCAAgC,MAAM,sBAC1C,QAAQ,KAAK,GACb,gBACF;CAIA,OAAO,CAFa,GAAG,gBAAgB,GAAG,6BAE1B;AAClB;AAEA,eAAe,oBAAoB;CAEjC,MAAM,mBAAmB,qBAAqB,IAAI,UAAU,CAAC,EAAE,cAAc,CAAC;CAE9E,KAAK,MAAM,kBAAkB,kBAAkB;EAE7C,IAAI,CAAC,eAAe,eAClB,eAAe,gBAAgB,eAAe;EAEhD,gBAAgB,SAAS,cAAc;CACzC;CAGA,MAAM,aAAa,MAAM,eAAe;CACxC,KAAK,MAAM,iBAAiB,YAC1B,MAAM,kBAAkB,aAAa;AAEzC"}
1
+ {"version":3,"file":"migrate-action.mjs","names":[],"sources":["../../../../../../../core/src/database/migrate-action.ts"],"sourcesContent":["import { colors } from \"@mongez/copper\";\r\nimport {\r\n exportMigrationsSQL,\r\n freshMigrate,\r\n listExecutedMigrations,\r\n Migration,\r\n type MigrationConstructor,\r\n migrationRunner,\r\n rollbackMigrations,\r\n runMigrations,\r\n} from \"@warlock.js/cascade\";\r\nimport dayjs from \"dayjs\";\r\nimport path from \"path\";\r\nimport type { CommandActionData } from \"../commands/types\";\r\nimport { filesOrchestrator } from \"../dev-server/files-orchestrator\";\r\nimport { Path } from \"../utils/normalized-path\";\r\nimport { getFilesFromDirectory } from \"../dev-server/utils\";\r\nimport { srcPath } from \"../utils\";\r\nimport { warlockConfigManager } from \"../warlock-config/warlock-config.manager\";\r\nimport { exitCodeFor, PENDING_EXIT_CODE } from \"./pending-exit-code\";\r\nimport {\r\n resolvePendingMigrations,\r\n type PendingMigrationsResult,\r\n} from \"./resolve-pending-migrations\";\r\n\r\n/**\r\n * `--list` — print the migration state: what has run, then what will run next.\r\n *\r\n * The executed section is printed FIRST and unconditionally, before anything\r\n * touches disk or config. That ordering is the contract: reading migrations\r\n * from the table cannot fail because of a broken migration file, and `--list`\r\n * is the command an operator reaches for *during* an incident. The pending\r\n * section is best-effort on top of an answer that is already on screen.\r\n *\r\n * Always exits 0. It is a report; `--pending` is the gate.\r\n */\r\nasync function listMigrationsAction() {\r\n await printExecutedMigrations();\r\n\r\n const pending = await resolvePendingMigrations(loadAllMigrations);\r\n\r\n printPendingMigrations(pending);\r\n}\r\n\r\nasync function printExecutedMigrations() {\r\n const createdMigrations = await listExecutedMigrations();\r\n\r\n console.log(`\\nTotal Executed Migrations: ${colors.green(createdMigrations.length)}\\n`);\r\n\r\n if (createdMigrations.length === 0) {\r\n console.log(colors.gray(\" No migrations have been executed yet.\\n\"));\r\n return;\r\n }\r\n\r\n // Display each migration as a block\r\n for (const migration of createdMigrations) {\r\n const executedAt = dayjs(migration.executedAt).format(\"DD-MM-YYYY hh:mm:ss A\");\r\n const createdAt = migration.createdAt\r\n ? dayjs(migration.createdAt).format(\"DD-MM-YYYY hh:mm:ss A\")\r\n : null;\r\n\r\n // Migration name with checkmark icon\r\n console.log(` ${colors.green(\"✔\")} ${colors.cyanBright(migration.name)}`);\r\n\r\n // Executed date\r\n console.log(` ${colors.gray(\"Executed:\")} ${colors.white(executedAt)}`);\r\n\r\n // Created date (if available)\r\n if (createdAt) {\r\n console.log(` ${colors.gray(\"Created:\")} ${colors.yellow(createdAt)}`);\r\n }\r\n\r\n console.log(\"\"); // Empty line between migrations\r\n }\r\n}\r\n\r\n/**\r\n * Print the pending section shared by `--list` and `--pending`.\r\n *\r\n * An unavailable result prints an explicit line and NEVER a count. \"0 pending\"\r\n * over a tree we failed to read is the one output this whole feature exists to\r\n * prevent.\r\n */\r\nfunction printPendingMigrations(result: PendingMigrationsResult) {\r\n if (result.type === \"unavailable\") {\r\n console.log(\r\n `${colors.yellowBright(\"Pending: unavailable\")} — ${result.reason}\\n` +\r\n colors.gray(\" The executed list above is still accurate.\\n\"),\r\n );\r\n return;\r\n }\r\n\r\n const { migrations } = result;\r\n\r\n console.log(`Total Pending Migrations: ${colors.green(migrations.length)}\\n`);\r\n\r\n if (migrations.length === 0) {\r\n console.log(colors.gray(\" Nothing pending — the database is up to date.\\n\"));\r\n return;\r\n }\r\n\r\n // Numbered because the ORDER is the answer: this is what the next\r\n // `warlock migrate` will do, in the sequence it will do it.\r\n migrations.forEach((migration, index) => {\r\n console.log(` ${colors.gray(`${index + 1}.`)} ${colors.cyanBright(migration.name)}`);\r\n });\r\n\r\n console.log(\"\");\r\n}\r\n\r\n/**\r\n * `--pending` — the scriptable half. Same computation as `--list`'s pending\r\n * section, different exit contract: see {@link PENDING_EXIT_CODE}.\r\n */\r\nasync function pendingMigrationsAction() {\r\n const result = await resolvePendingMigrations(loadAllMigrations);\r\n\r\n printPendingMigrations(result);\r\n\r\n const exitCode = exitCodeFor(result);\r\n\r\n if (exitCode === PENDING_EXIT_CODE.unavailable) {\r\n console.error(\r\n colors.redBright(\"Could not determine the pending set — exiting 2 rather than reporting 0.\"),\r\n );\r\n }\r\n\r\n process.exit(exitCode);\r\n}\r\n\r\nasync function allMigrationsFilesAction() {\r\n // get all available migration files in the project\r\n const files = (await migrationFiles()).map((path) => Path.toRelative(path));\r\n console.log(`Total Migration Files: ${colors.green(files.length)}`);\r\n\r\n for (const file of files) {\r\n console.log(colors.yellowBright(file));\r\n }\r\n}\r\n\r\n/**\r\n * If path is provided, then run the migration runner against that file only\r\n * If fresh is provided, then rollback all migrations and run all migrations\r\n * If rollback is provided, then run the migration runner against all files in reverse order\r\n */\r\nexport async function migrateAction(options: CommandActionData) {\r\n const { fresh, path, rollback, all, list, pending, sql, pendingOnly, compact } = options.options;\r\n\r\n if (list) {\r\n return await listMigrationsAction();\r\n }\r\n\r\n if (pending) {\r\n return await pendingMigrationsAction();\r\n }\r\n\r\n if (all) {\r\n return await allMigrationsFilesAction();\r\n }\r\n\r\n if (path) {\r\n await loadMigrationFile(Path.toAbsolute(path as string));\r\n } else {\r\n await loadAllMigrations();\r\n }\r\n\r\n if (fresh && rollback) {\r\n console.log(colors.redBright(\"You can't use --fresh and --rollback together\"));\r\n process.exit(1);\r\n }\r\n\r\n if (rollback) {\r\n await rollbackMigrations({ all: true });\r\n return;\r\n }\r\n\r\n if (sql) {\r\n await exportMigrationsSQL({\r\n pendingOnly: pendingOnly as boolean,\r\n compact: compact as boolean,\r\n });\r\n return;\r\n }\r\n\r\n if (fresh) {\r\n await freshMigrate();\r\n return;\r\n }\r\n\r\n await runMigrations();\r\n}\r\n\r\nasync function loadMigrationFile(absPath: string) {\r\n const relativePath = Path.toRelative(absPath);\r\n\r\n // MigrationConstructor, not `typeof Migration`: a migration file default-exports a\r\n // CONCRETE subclass, while Migration itself is abstract and so cannot satisfy a\r\n // `new () => ...` parameter. The annotation described the base class rather than\r\n // what is actually loaded, and that is what migrationRunner.register() rejected.\r\n const loadedModule = await filesOrchestrator.load<{ default: MigrationConstructor }>(\r\n relativePath,\r\n );\r\n\r\n if (!loadedModule?.default) {\r\n throw new Error(`${Path.toRelative(absPath)} must have a default export`);\r\n }\r\n\r\n const MigrationClass = loadedModule.default;\r\n\r\n if (!MigrationClass.migrationName) {\r\n MigrationClass.migrationName = path\r\n .basename(absPath)\r\n .split(\".\")[0]\r\n .replace(\"-migration\", \"\")\r\n .replace(\"_migration\", \"\");\r\n }\r\n\r\n // Extract createdAt timestamp from filename if not already set\r\n // Expected format: MM-DD-YYYY_HH-MM-SS-name.migration.ts\r\n if (!MigrationClass.createdAt) {\r\n const filename = path.basename(absPath);\r\n const timestampMatch = filename.match(/^(\\d{2}-\\d{2}-\\d{4}_\\d{2}-\\d{2}-\\d{2})/);\r\n if (timestampMatch) {\r\n MigrationClass.createdAt = timestampMatch[1];\r\n }\r\n }\r\n\r\n migrationRunner.register(MigrationClass);\r\n}\r\n\r\n/**\r\n *\r\n * @returns List of absolute paths to migration files\r\n */\r\nasync function migrationFiles() {\r\n const migrationFiles = await getFilesFromDirectory(srcPath(\"app\"), \"*/models/*/migrations/*\");\r\n const separateMigrationsFolderFIles = await getFilesFromDirectory(\r\n srcPath(\"app\"),\r\n \"*/migrations/*\",\r\n );\r\n\r\n const migrations = [...migrationFiles, ...separateMigrationsFolderFIles];\r\n\r\n return migrations;\r\n}\r\n\r\nasync function loadAllMigrations() {\r\n // Load config-registered migrations (from packages like @warlock.js/auth)\r\n const configMigrations = warlockConfigManager.get(\"database\")?.migrations || [];\r\n\r\n for (const MigrationClass of configMigrations) {\r\n // Use class name as migration name if not set\r\n if (!MigrationClass.migrationName) {\r\n MigrationClass.migrationName = MigrationClass.name;\r\n }\r\n migrationRunner.register(MigrationClass);\r\n }\r\n\r\n // Always load file-based migrations from src/app, regardless of config\r\n const migrations = await migrationFiles();\r\n for (const migrationFile of migrations) {\r\n await loadMigrationFile(migrationFile);\r\n }\r\n}\r\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;AAoCA,eAAe,uBAAuB;CACpC,MAAM,wBAAwB;CAI9B,uBAAuB,MAFD,yBAAyB,iBAAiB,CAElC;AAChC;AAEA,eAAe,0BAA0B;CACvC,MAAM,oBAAoB,MAAM,uBAAuB;CAEvD,QAAQ,IAAI,gCAAgC,OAAO,MAAM,kBAAkB,MAAM,EAAE,GAAG;CAEtF,IAA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B,MAAM,GAAG,CAAC,CAAC,EAAE,CACb,QAAQ,cAAc,EAAE,CAAC,CACzB,QAAQ,cAAc,EAAE;CAK7B,IAAI,CAAC,eAAe,WAAW;EAE7B,MAAM,iBADW,KAAK,SAAS,OACD,CAAC,CAAC,MAAM,wCAAwC;EAC9E,IAAI,gBACF,eAAe,YAAY,eAAe;CAE9C;CAEA,gBAAgB,SAAS,cAAc;AACzC;;;;;AAMA,eAAe,iBAAiB;CAC9B,MAAM,iBAAiB,MAAM,sBAAsB,QAAQ,KAAK,GAAG,yBAAyB;CAC5F,MAAM,gCAAgC,MAAM,sBAC1C,QAAQ,KAAK,GACb,gBACF;CAIA,OAAO,CAFa,GAAG,gBAAgB,GAAG,6BAE1B;AAClB;AAEA,eAAe,oBAAoB;CAEjC,MAAM,mBAAmB,qBAAqB,IAAI,UAAU,CAAC,EAAE,cAAc,CAAC;CAE9E,KAAK,MAAM,kBAAkB,kBAAkB;EAE7C,IAAI,CAAC,eAAe,eAClB,eAAe,gBAAgB,eAAe;EAEhD,gBAAgB,SAAS,cAAc;CACzC;CAGA,MAAM,aAAa,MAAM,eAAe;CACxC,KAAK,MAAM,iBAAiB,YAC1B,MAAM,kBAAkB,aAAa;AAEzC"}
@@ -1 +1 @@
1
- {"version":3,"file":"seed-command-action.mjs","names":["runInTransaction"],"sources":["../../../../../../../core/src/database/seed-command-action.ts"],"sourcesContent":["import { colors } from \"@mongez/copper\";\r\nimport {\r\n DataSource,\r\n dataSourceRegistry,\r\n transaction as runInTransaction,\r\n} from \"@warlock.js/cascade\";\r\nimport type { CommandActionData } from \"../commands/types\";\r\nimport { filesOrchestrator } from \"../dev-server/files-orchestrator\";\r\nimport { Path } from \"../utils/normalized-path\";\r\nimport { getFilesFromDirectory } from \"../dev-server/utils\";\r\nimport { srcPath } from \"../utils\";\r\nimport type { Seeder } from \"./seeds/seeder\";\r\nimport { SeedersManager } from \"./seeds/seeders.manager\";\r\nimport type { SeedClock, SeedRecordRef } from \"./seeds/types\";\r\nimport { seedRecordsTableName, seedsTableName } from \"./seeds/utils\";\r\n\r\n/**\r\n * Programmatic-only overrides for {@link seedCommandAction}.\r\n *\r\n * Not derived from CLI flags (the CLI passes only {@link CommandActionData}),\r\n * so a back-fill script or a test can inject behaviour the command line can't\r\n * express.\r\n */\r\nexport type SeedCommandOverrides = {\r\n /**\r\n * Clock the run reads for the `now` handed to each seeder and for the\r\n * seeds-log metadata timestamps. Defaults to `() => new Date()`. Forwarded to\r\n * {@link SeedersManager}'s `clock` option.\r\n */\r\n clock?: SeedClock;\r\n};\r\n\r\nasync function clearAllTables(datasource: DataSource) {\r\n const tables = await datasource.driver.blueprint.listTables();\r\n\r\n for (const table of tables) {\r\n await datasource.driver.truncateTable(table, { cascade: true });\r\n }\r\n}\r\n\r\ntype SeedRecordRow = SeedRecordRef & { id: number };\r\n\r\n/**\r\n * Undo seeded data by deleting the records a seeder tracked via `track`.\r\n *\r\n * Reads `seed_records` (all seeders, or a single `seederName`), then deletes\r\n * the referenced records in REVERSE seed-order and, within each seed, in\r\n * reverse insertion-order. Insertion id is strictly increasing across the\r\n * whole run, so deleting by descending `id` satisfies both at once. The whole\r\n * operation runs in a single transaction, and the matching seeds-log rows are\r\n * reset afterwards so `once: true` seeds re-run on the next `warlock seed`.\r\n *\r\n * @returns the number of tracked records deleted.\r\n */\r\nexport async function dropSeedRecords(\r\n datasource: DataSource,\r\n seederName?: string,\r\n): Promise<number> {\r\n const driver = datasource.driver;\r\n\r\n if (!(await driver.blueprint.tableExists(seedRecordsTableName))) {\r\n return 0;\r\n }\r\n\r\n const query = driver.queryBuilder<SeedRecordRow>(seedRecordsTableName);\r\n\r\n if (seederName) {\r\n query.where(\"seeder\", seederName);\r\n }\r\n\r\n const rows = await query.get();\r\n\r\n if (rows.length === 0) {\r\n return 0;\r\n }\r\n\r\n // Descending insertion id == reverse seed-order + reverse within-seed order.\r\n const ordered = [...rows].sort((a, b) => b.id - a.id);\r\n\r\n await runInTransaction(async () => {\r\n for (const row of ordered) {\r\n await driver.deleteMany(row.table, { id: row.recordId });\r\n }\r\n\r\n // Clear the tracked refs we just acted on.\r\n if (seederName) {\r\n await driver.deleteMany(seedRecordsTableName, { seeder: seederName });\r\n } else {\r\n await driver.deleteMany(seedRecordsTableName, {});\r\n }\r\n\r\n // Reset the seeds-log rows so `once: true` seeds re-run.\r\n const seederNames = seederName\r\n ? [seederName]\r\n : [...new Set(ordered.map((row) => row.seeder))];\r\n\r\n for (const name of seederNames) {\r\n await driver.deleteMany(seedsTableName, { name });\r\n }\r\n });\r\n\r\n return ordered.length;\r\n}\r\n\r\n/**\r\n * Run database seeds.\r\n *\r\n * @example\r\n * ```ts\r\n * import { seedCommandAction } from \"@warlock.js/core\";\r\n *\r\n * await seedCommandAction({\r\n * command: \"seed\",\r\n * options: { fresh: true, list: false }\r\n * });\r\n * ```\r\n *\r\n * @param overrides Programmatic-only overrides (e.g. an injected `clock`); the\r\n * CLI never passes this, so the command-line signature stays unchanged.\r\n */\r\nexport async function seedCommandAction(\r\n options: CommandActionData,\r\n overrides?: SeedCommandOverrides,\r\n) {\r\n const { path, fresh, transaction, list, drop } = options.options;\r\n\r\n const datasource = dataSourceRegistry.get();\r\n\r\n if (drop) {\r\n // `--drop` (boolean) undoes every tracked record; `--drop=<name>` scopes to\r\n // a single seeder.\r\n const seederName = typeof drop === \"string\" ? drop : undefined;\r\n\r\n const deleted = await dropSeedRecords(datasource, seederName);\r\n\r\n const scope = seederName ? colors.cyan(seederName) : \"all seeders\";\r\n console.log(\r\n `🗑️ Dropped ${colors.redBright(deleted)} tracked record(s) for ${scope}; matching seeds-log entries reset.`,\r\n );\r\n return;\r\n }\r\n\r\n if (fresh) {\r\n await clearAllTables(datasource);\r\n }\r\n\r\n if (list) {\r\n const seedFiles = await listSeedsFiles();\r\n\r\n if (seedFiles.length === 0) {\r\n console.log(\"No seeds found.\");\r\n return;\r\n }\r\n\r\n const seedersManager = new SeedersManager();\r\n\r\n seedersManager.register(...seedFiles);\r\n\r\n const seeds = seedersManager.sort().seeders.map((seed) => {\r\n return {\r\n name: seed.name,\r\n order: seed.order,\r\n enabled: seed.enabled,\r\n };\r\n });\r\n\r\n console.table(seeds);\r\n\r\n console.log(\r\n `Total Seeds: ${colors.blueBright(seeds.length)}, enabled: ${colors.greenBright(seeds.filter((seed) => seed.enabled !== false).length)}, disabled: ${colors.redBright(seeds.filter((seed) => seed.enabled === false).length)}`,\r\n );\r\n return;\r\n }\r\n\r\n const seeds = path\r\n ? [await loadSeedFile(Path.toAbsolute(path as string))]\r\n : await listSeedsFiles();\r\n\r\n const seedersManager = new SeedersManager({ clock: overrides?.clock });\r\n\r\n seedersManager.register(...seeds);\r\n\r\n await seedersManager.run(transaction as boolean);\r\n}\r\n\r\nasync function listSeedsFiles() {\r\n const seedsFiles = await getFilesFromDirectory(srcPath(\"app\"), \"*/seeds/*.ts\");\r\n\r\n const seeds = [];\r\n\r\n for (const seedFile of seedsFiles) {\r\n const seed = await loadSeedFile(seedFile);\r\n seeds.push(seed);\r\n }\r\n\r\n return seeds;\r\n}\r\n\r\nasync function loadSeedFile(absPath: string): Promise<Seeder> {\r\n const relativePath = Path.toRelative(absPath);\r\n const seedImport = await filesOrchestrator.load<{ default: Seeder }>(relativePath);\r\n\r\n if (!seedImport || !seedImport.default) {\r\n throw new Error(`Seeder file ${relativePath} does not export a default seeder.`);\r\n }\r\n\r\n return seedImport.default;\r\n}\r\n"],"mappings":";;;;;;;;;;;AAgCA,eAAe,eAAe,YAAwB;CACpD,MAAM,SAAS,MAAM,WAAW,OAAO,UAAU,WAAW;CAE5D,KAAK,MAAM,SAAS,QAClB,MAAM,WAAW,OAAO,cAAc,OAAO,EAAE,SAAS,KAAK,CAAC;AAElE;;;;;;;;;;;;;AAgBA,eAAsB,gBACpB,YACA,YACiB;CACjB,MAAM,SAAS,WAAW;CAE1B,IAAI,CAAE,MAAM,OAAO,UAAU,2BAAgC,GAC3D,OAAO;CAGT,MAAM,QAAQ,OAAO,aAA4B,oBAA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;EAE1C,eAAe,SAAS,GAAG,SAAS;EAEpC,MAAM,QAAQ,eAAe,KAAK,CAAC,CAAC,QAAQ,KAAK,SAAS;GACxD,OAAO;IACL,MAAM,KAAK;IACX,OAAO,KAAK;IACZ,SAAS,KAAK;GAChB;EACF,CAAC;EAED,QAAQ,MAAM,KAAK;EAEnB,QAAQ,IACN,gBAAgB,OAAO,WAAW,MAAM,MAAM,EAAE,aAAa,OAAO,YAAY,MAAM,QAAQ,SAAS,KAAK,YAAY,KAAK,CAAC,CAAC,MAAM,EAAE,cAAc,OAAO,UAAU,MAAM,QAAQ,SAAS,KAAK,YAAY,KAAK,CAAC,CAAC,MAAM,GAC7N;EACA;CACF;CAEA,MAAM,QAAQ,OACV,CAAC,MAAM,aAAa,KAAK,WAAW,IAAc,CAAC,CAAC,IACpD,MAAM,eAAe;CAEzB,MAAM,iBAAiB,IAAI,eAAe,EAAE,OAAO,WAAW,MAAM,CAAC;CAErE,eAAe,SAAS,GAAG,KAAK;CAEhC,MAAM,eAAe,IAAI,WAAsB;AACjD;AAEA,eAAe,iBAAiB;CAC9B,MAAM,aAAa,MAAM,sBAAsB,QAAQ,KAAK,GAAG,cAAc;CAE7E,MAAM,QAAQ,CAAC;CAEf,KAAK,MAAM,YAAY,YAAY;EACjC,MAAM,OAAO,MAAM,aAAa,QAAQ;EACxC,MAAM,KAAK,IAAI;CACjB;CAEA,OAAO;AACT;AAEA,eAAe,aAAa,SAAkC;CAC5D,MAAM,eAAe,KAAK,WAAW,OAAO;CAC5C,MAAM,aAAa,MAAM,kBAAkB,KAA0B,YAAY;CAEjF,IAAI,CAAC,cAAc,CAAC,WAAW,SAC7B,MAAM,IAAI,MAAM,eAAe,aAAa,mCAAmC;CAGjF,OAAO,WAAW;AACpB"}
1
+ {"version":3,"file":"seed-command-action.mjs","names":["runInTransaction"],"sources":["../../../../../../../core/src/database/seed-command-action.ts"],"sourcesContent":["import { colors } from \"@mongez/copper\";\r\nimport {\r\n DataSource,\r\n dataSourceRegistry,\r\n transaction as runInTransaction,\r\n} from \"@warlock.js/cascade\";\r\nimport type { CommandActionData } from \"../commands/types\";\r\nimport { filesOrchestrator } from \"../dev-server/files-orchestrator\";\r\nimport { Path } from \"../utils/normalized-path\";\r\nimport { getFilesFromDirectory } from \"../dev-server/utils\";\r\nimport { srcPath } from \"../utils\";\r\nimport type { Seeder } from \"./seeds/seeder\";\r\nimport { SeedersManager } from \"./seeds/seeders.manager\";\r\nimport type { SeedClock, SeedRecordRef } from \"./seeds/types\";\r\nimport { seedRecordsTableName, seedsTableName } from \"./seeds/utils\";\r\n\r\n/**\r\n * Programmatic-only overrides for {@link seedCommandAction}.\r\n *\r\n * Not derived from CLI flags (the CLI passes only {@link CommandActionData}),\r\n * so a back-fill script or a test can inject behaviour the command line can't\r\n * express.\r\n */\r\nexport type SeedCommandOverrides = {\r\n /**\r\n * Clock the run reads for the `now` handed to each seeder and for the\r\n * seeds-log metadata timestamps. Defaults to `() => new Date()`. Forwarded to\r\n * {@link SeedersManager}'s `clock` option.\r\n */\r\n clock?: SeedClock;\r\n};\r\n\r\nasync function clearAllTables(datasource: DataSource) {\r\n const tables = await datasource.driver.blueprint.listTables();\r\n\r\n for (const table of tables) {\r\n await datasource.driver.truncateTable(table, { cascade: true });\r\n }\r\n}\r\n\r\ntype SeedRecordRow = SeedRecordRef & { id: number };\r\n\r\n/**\r\n * Undo seeded data by deleting the records a seeder tracked via `track`.\r\n *\r\n * Reads `seed_records` (all seeders, or a single `seederName`), then deletes\r\n * the referenced records in REVERSE seed-order and, within each seed, in\r\n * reverse insertion-order. Insertion id is strictly increasing across the\r\n * whole run, so deleting by descending `id` satisfies both at once. The whole\r\n * operation runs in a single transaction, and the matching seeds-log rows are\r\n * reset afterwards so `once: true` seeds re-run on the next `warlock seed`.\r\n *\r\n * @returns the number of tracked records deleted.\r\n */\r\nexport async function dropSeedRecords(\r\n datasource: DataSource,\r\n seederName?: string,\r\n): Promise<number> {\r\n const driver = datasource.driver;\r\n\r\n if (!(await driver.blueprint.tableExists(seedRecordsTableName))) {\r\n return 0;\r\n }\r\n\r\n const query = driver.queryBuilder<SeedRecordRow>(seedRecordsTableName);\r\n\r\n if (seederName) {\r\n query.where(\"seeder\", seederName);\r\n }\r\n\r\n const rows = await query.get();\r\n\r\n if (rows.length === 0) {\r\n return 0;\r\n }\r\n\r\n // Descending insertion id == reverse seed-order + reverse within-seed order.\r\n const ordered = [...rows].sort((a, b) => b.id - a.id);\r\n\r\n await runInTransaction(async () => {\r\n for (const row of ordered) {\r\n await driver.deleteMany(row.table, { id: row.recordId });\r\n }\r\n\r\n // Clear the tracked refs we just acted on.\r\n if (seederName) {\r\n await driver.deleteMany(seedRecordsTableName, { seeder: seederName });\r\n } else {\r\n await driver.deleteMany(seedRecordsTableName, {});\r\n }\r\n\r\n // Reset the seeds-log rows so `once: true` seeds re-run.\r\n const seederNames = seederName ? [seederName] : [...new Set(ordered.map((row) => row.seeder))];\r\n\r\n for (const name of seederNames) {\r\n await driver.deleteMany(seedsTableName, { name });\r\n }\r\n });\r\n\r\n return ordered.length;\r\n}\r\n\r\n/**\r\n * Run database seeds.\r\n *\r\n * @example\r\n * ```ts\r\n * import { seedCommandAction } from \"@warlock.js/core\";\r\n *\r\n * await seedCommandAction({\r\n * command: \"seed\",\r\n * options: { fresh: true, list: false }\r\n * });\r\n * ```\r\n *\r\n * @param overrides Programmatic-only overrides (e.g. an injected `clock`); the\r\n * CLI never passes this, so the command-line signature stays unchanged.\r\n */\r\nexport async function seedCommandAction(\r\n options: CommandActionData,\r\n overrides?: SeedCommandOverrides,\r\n) {\r\n const { path, fresh, transaction, list, drop } = options.options;\r\n\r\n const datasource = dataSourceRegistry.get();\r\n\r\n if (drop) {\r\n // `--drop` (boolean) undoes every tracked record; `--drop=<name>` scopes to\r\n // a single seeder.\r\n const seederName = typeof drop === \"string\" ? drop : undefined;\r\n\r\n const deleted = await dropSeedRecords(datasource, seederName);\r\n\r\n const scope = seederName ? colors.cyan(seederName) : \"all seeders\";\r\n console.log(\r\n `🗑️ Dropped ${colors.redBright(deleted)} tracked record(s) for ${scope}; matching seeds-log entries reset.`,\r\n );\r\n return;\r\n }\r\n\r\n if (fresh) {\r\n await clearAllTables(datasource);\r\n }\r\n\r\n if (list) {\r\n const seedFiles = await listSeedsFiles();\r\n\r\n if (seedFiles.length === 0) {\r\n console.log(\"No seeds found.\");\r\n return;\r\n }\r\n\r\n const seedersManager = new SeedersManager();\r\n\r\n seedersManager.register(...seedFiles);\r\n\r\n const seeds = seedersManager.sort().seeders.map((seed) => {\r\n return {\r\n name: seed.name,\r\n order: seed.order,\r\n enabled: seed.enabled,\r\n };\r\n });\r\n\r\n console.table(seeds);\r\n\r\n console.log(\r\n `Total Seeds: ${colors.blueBright(seeds.length)}, enabled: ${colors.greenBright(seeds.filter((seed) => seed.enabled !== false).length)}, disabled: ${colors.redBright(seeds.filter((seed) => seed.enabled === false).length)}`,\r\n );\r\n return;\r\n }\r\n\r\n const seeds = path\r\n ? [await loadSeedFile(Path.toAbsolute(path as string))]\r\n : await listSeedsFiles();\r\n\r\n const seedersManager = new SeedersManager({ clock: overrides?.clock });\r\n\r\n seedersManager.register(...seeds);\r\n\r\n await seedersManager.run(transaction as boolean);\r\n}\r\n\r\nasync function listSeedsFiles() {\r\n const seedsFiles = await getFilesFromDirectory(srcPath(\"app\"), \"*/seeds/*.ts\");\r\n\r\n const seeds = [];\r\n\r\n for (const seedFile of seedsFiles) {\r\n const seed = await loadSeedFile(seedFile);\r\n seeds.push(seed);\r\n }\r\n\r\n return seeds;\r\n}\r\n\r\nasync function loadSeedFile(absPath: string): Promise<Seeder> {\r\n const relativePath = Path.toRelative(absPath);\r\n const seedImport = await filesOrchestrator.load<{ default: Seeder }>(relativePath);\r\n\r\n if (!seedImport || !seedImport.default) {\r\n throw new Error(`Seeder file ${relativePath} does not export a default seeder.`);\r\n }\r\n\r\n return seedImport.default;\r\n}\r\n"],"mappings":";;;;;;;;;;;AAgCA,eAAe,eAAe,YAAwB;C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W,OAAO;CAC5C,MAAM,aAAa,MAAM,kBAAkB,KAA0B,YAAY;CAEjF,IAAI,CAAC,cAAc,CAAC,WAAW,SAC7B,MAAM,IAAI,MAAM,eAAe,aAAa,mCAAmC;CAGjF,OAAO,WAAW;AACpB"}
@@ -1 +1 @@
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;EAwM9B;;;;EA/LD,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;;;;;UAiBA,iCAAA;;;;EAgGD,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(colors.dim(` other: lazy(() => ${kind === \"resource\" ? \"OtherResource\" : \"OtherModel\"})`));\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(\r\n colors.dim(` const { SomeClass } = await import(\"./${stripExt(fileA)}\");`),\r\n );\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(colors.dim(\" • Pass the dependency as a constructor/function parameter instead.\"));\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,MAAc,YAAoB,aAAsB,OAAO;EAClF,IAAI,CAAC,KAAK,aAAa,IAAI,IAAI,GAC7B,KAAK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a;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,OAAM,SAAQ,KAAK,SAAS,cAAc,KAAK,KAAK,SAAS,eAAe,CAAC,GACrF,OAAO;CAET,IAAI,MAAM,OAAM,SAAQ,KAAK,SAAS,WAAW,KAAK,KAAK,SAAS,YAAY,CAAC,GAC/E,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,MAAc,YAAoB,aAAsB,OAAO;EAClF,IAAI,CAAC,KAAK,aAAa,IAAI,IAAI,GAC7B,KAAK,aAAa,IAAI,sBAAM,IAAI,IAAI,CAAC;EAGvC,IAAI,CAAC,KAAK,WAAW,IAAI,UAAU,GACjC,KAAK,WAAW,IAAI,4BAAY,IAAI,IAAI,CAAC;EAG3C,MAAM,QAAQ,KAAK,aAAa,IAAI,IAAI;EACxC,MAAM,WAAW,MAAM,IAAI,UAAU;EAErC,IAAI,UACF,SAAS,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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,KAAI,SAAQ;EACX,MAAM,SAAS,KAAK,MAAM,KAAK;EAC/B,MAAM,OAAO,KAAK,MAAM,SAAS;EAEjC,IAAI,CAAC,UAAU,CAAC,MAGd,OADgB,aAAa,OAAO,IAAI,IAAI,IAAI,OAAO,KAAK,OAAO,IAAI,IAAI,CAAC;EAI9E,aAAa;EAEb,MAAM,KAAK,SAAS,OAAO,KAAK;EAChC,MAAM,OAAO,SAAS,OAAO,KAAK,KAAM;EACxC,MAAM,SAAS,SAAS,OAAO,KAAK,KAAM;EAC1C,MAAM,MAAM,SAAS,OAAO,KAAK,KAAM;EAEvC,MAAM,iBAAiB,KAAK,WAAW,OAAO;EAC9C,MAAM,QAAQ,KAAK,SAA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AAO,MAAM,YAAY,EAAE,GAAG,OAAO,IAAI,YAAY,IAAI,SAChF;AACF;AAeA,SAAgB,cAAc,OAAe;CAC3C,QAAQ,IAAI,KAAK,UAAU,EAAE,GAAG,OAAO,KAAK,OAAO,KAAK,KAAK,CAAC,GAAG;AACnE;;;;;;AAOA,SAAgB,0BAA0B,OAAc,aAAgC;CACtF,MAAM,QAAQ,MAAM,QAAQ,MAAM,sDAAsD;CACxF,IAAI,CAAC,OAAO,OAAO,MAAM;CAEzB,MAAM,GAAG,YAAY,gBAAgB;CACrC,MAAM,QAAkB;EACtB;EACA,GAAG,OAAO,IAAI,oBAAoB;EAClC;EACA,GAAG,OAAO,IAAI,cAAc,EAAE,GAAG,OAAO,KAAK,KAAK,WAAW,UAAU,CAAC;EACxE;EACA,GAAG,OAAO,IAAI,cAAc;EAC5B,KAAK,OAAO,OAAO,GAAG,EAAE,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,SAAQ,MAAK,MAAM,KAAK,KAAK,OAAO,KAAK,GAAG,EAAE,GAAG,OAAO,MAAM,CAAC,GAAG,CAAC;CACjF;CAEA,MAAM,KAAK,EAAE;CACb,OAAO,MAAM,KAAK,IAAI;AACxB;;AAGA,MAAa,cAAc"}
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 // 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,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,OADgB,aAAa,OAAO,IAAI,IAAI,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I;AACxB;;AAGA,MAAa,cAAc"}
@@ -1 +1 @@
1
- {"version":3,"file":"file-event-handler.mjs","names":[],"sources":["../../../../../../../core/src/dev-server/file-event-handler.ts"],"sourcesContent":["import events from \"@mongez/events\";\nimport { debounce } from \"@mongez/reinforcements\";\nimport type { DependencyGraph } from \"./dependency-graph\";\nimport { devLogSuccess } from \"./dev-logger\";\nimport type { FileManager } from \"./file-manager\";\nimport type { FileOperations } from \"./file-operations\";\nimport { FILE_PROCESSING_BATCH_SIZE } from \"./flags\";\nimport type { ManifestManager } from \"./manifest-manager\";\nimport { clearFileExistsCache } from \"./parse-imports\";\nimport { Path } from \"../utils/normalized-path\";\n\n/**\n * Receives raw watcher events and processes them in a single debounced batch.\n * Order within a batch: adds → changes → deletes, so changes can reference\n * newly-added files and deletes fire last.\n */\nexport class FileEventHandler {\n private pendingChanges = new Set<string>();\n private pendingAdds = new Set<string>();\n private pendingDeletes = new Set<string>();\n\n private readonly processPendingEvents = debounce(() => this.processBatch(), 150);\n\n constructor(\n private readonly fileOperations: FileOperations,\n private readonly manifest: ManifestManager,\n private readonly dependencyGraph: DependencyGraph,\n private readonly files: Map<string, FileManager>,\n ) {}\n\n public handleFileChange(absolutePath: string): void {\n this.pendingChanges.add(Path.toRelative(absolutePath));\n this.processPendingEvents();\n }\n\n public handleFileAdd(absolutePath: string): void {\n this.pendingAdds.add(Path.toRelative(absolutePath));\n this.processPendingEvents();\n }\n\n public handleFileDelete(absolutePath: string): void {\n this.pendingDeletes.add(Path.toRelative(absolutePath));\n this.processPendingEvents();\n }\n\n private async processBatch(): Promise<void> {\n const changes = Array.from(this.pendingChanges);\n const adds = Array.from(this.pendingAdds);\n const deletes = Array.from(this.pendingDeletes);\n\n this.pendingChanges.clear();\n this.pendingAdds.clear();\n this.pendingDeletes.clear();\n\n if (changes.length === 0 && adds.length === 0 && deletes.length === 0) return;\n\n // Both .env files and warlock.config.ts live outside src/ — they should\n // never enter the dep graph, only ride along in the batch event so the\n // dev server can react (config reload / restart warning).\n const externalChanges = changes.filter(isExternalPath);\n const codeChanges = changes.filter(p => !isExternalPath(p));\n const codeAdds = adds.filter(p => !isExternalPath(p));\n\n // Multi-file batches can race the filesystem on Windows.\n if (codeAdds.length + codeChanges.length > 1) {\n await new Promise(resolve => setTimeout(resolve, 500));\n clearFileExistsCache();\n }\n\n await this.processBatchAdds(codeAdds);\n const changedCodePaths = await this.processBatchChanges(codeChanges);\n await this.processBatchDeletes(deletes);\n\n this.fileOperations.updateFileDependents();\n this.fileOperations.syncFilesToManifest();\n await this.manifest.save();\n\n // Emit only the code paths that genuinely changed (hash differs). A no-op\n // save — an editor that fsyncs without writing — reports no change and is\n // dropped here, where we still know the pre-change hash. (Doing this\n // downstream is impossible: the source has already been overwritten, so a\n // content compare always looks unchanged — which is exactly why emptying a\n // file used to silently skip HMR.) External paths (.env / warlock.config.ts)\n // ride along untouched so the dev server can still react to them.\n events.trigger(\"dev-server:batch-complete\", {\n added: adds,\n changed: [...externalChanges, ...changedCodePaths],\n deleted: deletes,\n });\n }\n\n /**\n * Reprocess each changed file and return only the paths that genuinely\n * changed. `updateFile` returns false when the on-disk hash matches the\n * last-processed hash (e.g. an editor that fsyncs on save without writing),\n * so those no-ops are kept out of the reload batch. Emptying a file changes\n * its hash, so it is correctly reported as changed.\n */\n private async processBatchChanges(relativePaths: string[]): Promise<string[]> {\n const changed: string[] = [];\n await runInBatches(relativePaths, FILE_PROCESSING_BATCH_SIZE, async path => {\n if (await this.fileOperations.updateFile(path)) {\n changed.push(path);\n }\n });\n return changed;\n }\n\n private async processBatchAdds(relativePaths: string[]): Promise<void> {\n await runInBatches(relativePaths, FILE_PROCESSING_BATCH_SIZE, async path => {\n try {\n await this.fileOperations.addFile(path);\n devLogSuccess(`Added file: ${path}`);\n } catch (error) {\n console.error(`Failed to add file ${path}:`, error);\n }\n });\n }\n\n private async processBatchDeletes(relativePaths: string[]): Promise<void> {\n for (const relativePath of relativePaths) {\n await this.fileOperations.deleteFile(relativePath);\n devLogSuccess(`Deleted file: ${relativePath}`);\n }\n }\n}\n\nfunction isEnvFile(path: string): boolean {\n const basename = path.split(\"/\").pop() || path;\n return basename === \".env\" || basename.startsWith(\".env.\");\n}\n\n/** Paths watched but never added to the dependency graph. */\nfunction isExternalPath(path: string): boolean {\n return isEnvFile(path) || path === \"warlock.config.ts\";\n}\n\nasync function runInBatches<T>(\n items: T[],\n size: number,\n fn: (item: T) => Promise<unknown>,\n): Promise<void> {\n if (items.length === 0) return;\n for (let i = 0; i < items.length; i += size) {\n await Promise.all(items.slice(i, i + size).map(fn));\n }\n}\n"],"mappings":";;;;;;;;;;;;;AAgBA,IAAa,mBAAb,MAA8B;CAO5B,YACE,AAAiB,gBACjB,AAAiB,UACjB,AAAiB,iBACjB,AAAiB,OACjB;EAJiB;EACA;EACA;EACA;wCAVM,IAAI,IAAY;qCACnB,IAAI,IAAY;wCACb,IAAI,IAAY;8BAED,eAAe,KAAK,aAAa,GAAG,GAAG;CAO5E;CAEH,AAAO,iBAAiB,cAA4B;EAClD,KAAK,eAAe,IAAI,KAAK,WAAW,YAAY,CAAC;EACrD,KAAK,qBAAqB;CAC5B;CAEA,AAAO,cAAc,cAA4B;EAC/C,KAAK,YAAY,IAAI,KAAK,WAAW,YAAY,CAAC;EAClD,KAAK,qBAAqB;CAC5B;CAEA,AAAO,iBAAiB,cAA4B;EAClD,KAAK,eAAe,IAAI,KAAK,WAAW,YAAY,CAAC;EACrD,KAAK,qBAAqB;CAC5B;CAEA,MAAc,eAA8B;EAC1C,MAAM,UAAU,MAAM,KAAK,KAAK,cAAc;EAC9C,MAAM,OAAO,MAAM,KAAK,KAAK,WAAW;EACxC,MAAM,UAAU,MAAM,KAAK,KAAK,cAAc;EAE9C,KAAK,eAAe,MAAM;EAC1B,KAAK,YAAY,MAAM;EACvB,KAAK,eAAe,MAAM;EAE1B,IAAI,QAAQ,WAAW,KAAK,KAAK,WAAW,KAAK,QAAQ,WAAW,GAAG;EAKvE,MAAM,kBAAkB,Q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AO,aAAa,UAAU,SAAS,WAAW,OAAO;AAC3D;;AAGA,SAAS,eAAe,MAAuB;CAC7C,OAAO,UAAU,IAAI,KAAK,SAAS;AACrC;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"}
1
+ {"version":3,"file":"file-event-handler.mjs","names":[],"sources":["../../../../../../../core/src/dev-server/file-event-handler.ts"],"sourcesContent":["import events from \"@mongez/events\";\nimport { debounce } from \"@mongez/reinforcements\";\nimport type { DependencyGraph } from \"./dependency-graph\";\nimport { devLogSuccess } from \"./dev-logger\";\nimport type { FileManager } from \"./file-manager\";\nimport type { FileOperations } from \"./file-operations\";\nimport { FILE_PROCESSING_BATCH_SIZE } from \"./flags\";\nimport type { ManifestManager } from \"./manifest-manager\";\nimport { clearFileExistsCache } from \"./parse-imports\";\nimport { Path } from \"../utils/normalized-path\";\n\n/**\n * Receives raw watcher events and processes them in a single debounced batch.\n * Order within a batch: adds → changes → deletes, so changes can reference\n * newly-added files and deletes fire last.\n */\nexport class FileEventHandler {\n private pendingChanges = new Set<string>();\n private pendingAdds = new Set<string>();\n private pendingDeletes = new Set<string>();\n\n private readonly processPendingEvents = debounce(() => this.processBatch(), 150);\n\n constructor(\n private readonly fileOperations: FileOperations,\n private readonly manifest: ManifestManager,\n private readonly dependencyGraph: DependencyGraph,\n private readonly files: Map<string, FileManager>,\n ) {}\n\n public handleFileChange(absolutePath: string): void {\n this.pendingChanges.add(Path.toRelative(absolutePath));\n this.processPendingEvents();\n }\n\n public handleFileAdd(absolutePath: string): void {\n this.pendingAdds.add(Path.toRelative(absolutePath));\n this.processPendingEvents();\n }\n\n public handleFileDelete(absolutePath: string): void {\n this.pendingDeletes.add(Path.toRelative(absolutePath));\n this.processPendingEvents();\n }\n\n private async processBatch(): Promise<void> {\n const changes = Array.from(this.pendingChanges);\n const adds = Array.from(this.pendingAdds);\n const deletes = Array.from(this.pendingDeletes);\n\n this.pendingChanges.clear();\n this.pendingAdds.clear();\n this.pendingDeletes.clear();\n\n if (changes.length === 0 && adds.length === 0 && deletes.length === 0) return;\n\n // Both .env files and warlock.config.ts live outside src/ — they should\n // never enter the dep graph, only ride along in the batch event so the\n // dev server can react (config reload / restart warning).\n const externalChanges = changes.filter(isExternalPath);\n const codeChanges = changes.filter((p) => !isExternalPath(p));\n const codeAdds = adds.filter((p) => !isExternalPath(p));\n\n // Multi-file batches can race the filesystem on Windows.\n if (codeAdds.length + codeChanges.length > 1) {\n await new Promise((resolve) => setTimeout(resolve, 500));\n clearFileExistsCache();\n }\n\n await this.processBatchAdds(codeAdds);\n const changedCodePaths = await this.processBatchChanges(codeChanges);\n await this.processBatchDeletes(deletes);\n\n this.fileOperations.updateFileDependents();\n this.fileOperations.syncFilesToManifest();\n await this.manifest.save();\n\n // Emit only the code paths that genuinely changed (hash differs). A no-op\n // save — an editor that fsyncs without writing — reports no change and is\n // dropped here, where we still know the pre-change hash. (Doing this\n // downstream is impossible: the source has already been overwritten, so a\n // content compare always looks unchanged — which is exactly why emptying a\n // file used to silently skip HMR.) External paths (.env / warlock.config.ts)\n // ride along untouched so the dev server can still react to them.\n events.trigger(\"dev-server:batch-complete\", {\n added: adds,\n changed: [...externalChanges, ...changedCodePaths],\n deleted: deletes,\n });\n }\n\n /**\n * Reprocess each changed file and return only the paths that genuinely\n * changed. `updateFile` returns false when the on-disk hash matches the\n * last-processed hash (e.g. an editor that fsyncs on save without writing),\n * so those no-ops are kept out of the reload batch. Emptying a file changes\n * its hash, so it is correctly reported as changed.\n */\n private async processBatchChanges(relativePaths: string[]): Promise<string[]> {\n const changed: string[] = [];\n await runInBatches(relativePaths, FILE_PROCESSING_BATCH_SIZE, async (path) => {\n if (await this.fileOperations.updateFile(path)) {\n changed.push(path);\n }\n });\n return changed;\n }\n\n private async processBatchAdds(relativePaths: string[]): Promise<void> {\n await runInBatches(relativePaths, FILE_PROCESSING_BATCH_SIZE, async (path) => {\n try {\n await this.fileOperations.addFile(path);\n devLogSuccess(`Added file: ${path}`);\n } catch (error) {\n console.error(`Failed to add file ${path}:`, error);\n }\n });\n }\n\n private async processBatchDeletes(relativePaths: string[]): Promise<void> {\n for (const relativePath of relativePaths) {\n await this.fileOperations.deleteFile(relativePath);\n devLogSuccess(`Deleted file: ${relativePath}`);\n }\n }\n}\n\nfunction isEnvFile(path: string): boolean {\n const basename = path.split(\"/\").pop() || path;\n return basename === \".env\" || basename.startsWith(\".env.\");\n}\n\n/** Paths watched but never added to the dependency graph. */\nfunction isExternalPath(path: string): boolean {\n return isEnvFile(path) || path === \"warlock.config.ts\";\n}\n\nasync function runInBatches<T>(\n items: T[],\n size: number,\n fn: (item: T) => Promise<unknown>,\n): Promise<void> {\n if (items.length === 0) return;\n for (let i = 0; i < items.length; i += size) {\n await Promise.all(items.slice(i, i + size).map(fn));\n }\n}\n"],"mappings":";;;;;;;;;;;;;AAgBA,IAAa,mBAAb,MAA8B;CAO5B,YACE,AAAiB,gBACjB,AAAiB,UACjB,AAAiB,iBACjB,AAAiB,OACjB;EAJiB;EACA;EACA;EACA;wCAVM,IAAI,IAAY;qCACnB,IAAI,IAAY;wCACb,IAAI,IAAY;8BAED,eAAe,KAAK,aAAa,GAAG,GAAG;CAO5E;CAEH,AAAO,iBAAiB,cAA4B;EAClD,KAAK,eAAe,IAAI,KAAK,WAAW,YAAY,CAAC;EACrD,KAAK,qBAAqB;CAC5B;CAEA,AAAO,cAAc,cAA4B;EAC/C,KAAK,YAAY,IAAI,KAAK,WAAW,YAAY,CAAC;EAClD,KAAK,qBAAqB;CAC5B;CAEA,AAAO,iBAAiB,cAA4B;EAClD,KAAK,eAAe,IAAI,KAAK,WAAW,YAAY,CAAC;EACrD,KAAK,qBAAqB;CAC5B;CAEA,MAAc,eAA8B;EAC1C,MA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M,sBAAsB,KAAK,IAAI,KAAK;GACpD;EACF,CAAC;CACH;CAEA,MAAc,oBAAoB,eAAwC;EACxE,KAAK,MAAM,gBAAgB,eAAe;GACxC,MAAM,KAAK,eAAe,WAAW,YAAY;GACjD,cAAc,iBAAiB,cAAc;EAC/C;CACF;AACF;AAEA,SAAS,UAAU,MAAuB;CACxC,MAAM,WAAW,KAAK,MAAM,GAAG,CAAC,CAAC,IAAI,KAAK;CAC1C,OAAO,aAAa,UAAU,SAAS,WAAW,OAAO;AAC3D;;AAGA,SAAS,eAAe,MAAuB;CAC7C,OAAO,UAAU,IAAI,KAAK,SAAS;AACrC;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"}
@@ -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,KAA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EzC,KAAK,aAAa,cAAc,MAAM,KAAK,aAAa,iBAAiB,CAAC,CAAC;EAC3E,KAAK,aAAa,WAAW,MAAM,KAAK,aAAa,cAAc,CAAC,CAAC;EACrE,KAAK,aAAa,cAAc,MAAM,KAAK,aAAa,iBAAiB,CAAC,CAAC;EAE3E,MAAM,cAAc,qBAAqB,IAAI,WAAW,CAAC,EAAE;EAC3D,MAAM,KAAK,aAAa,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;CAC9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I,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 +1 @@
1
- {"version":3,"file":"layer-executor.mjs","names":[],"sources":["../../../../../../../core/src/dev-server/layer-executor.ts"],"sourcesContent":["import { loadEnv } from \"@mongez/dotenv\";\r\nimport { configManager } from \"../config/config-manager\";\r\nimport { connectorsManager } from \"../connectors/connectors-manager\";\r\nimport type { DependencyGraph } from \"./dependency-graph\";\r\nimport { devLogHMR } from \"./dev-logger\";\r\nimport { FileManager } from \"./file-manager\";\r\nimport type { ModuleLoader } from \"./module-loader\";\r\nimport type { SpecialFilesCollector } from \"./special-files-collector\";\r\nimport { environmentLoaderOptions } from \"../utils/load-environment\";\r\n\r\n/**\r\n * Decides what to reload when a batch of files changes.\r\n *\r\n * Strategy: bump the hook's version counter for every file in the\r\n * invalidation chain, wait for the hook worker to flush, then re-import\r\n * any special files (config / main / routes / events / locales) the chain\r\n * touched and restart any connector whose watched-files overlap the change.\r\n */\r\nexport class LayerExecutor {\r\n public constructor(\r\n private readonly dependencyGraph: DependencyGraph,\r\n private readonly specialFilesCollector: SpecialFilesCollector,\r\n private readonly moduleLoader: ModuleLoader,\r\n private readonly bumpVersion: (absolutePath: string) => void,\r\n private readonly flushVersionBumps: () => Promise<void>,\r\n ) {}\r\n\r\n /**\r\n * Entry point for the file watcher batch.\r\n *\r\n * @param changedPaths - code files added or changed in this batch\r\n * @param filesMap - all tracked files (relativePath → FileManager)\r\n * @param deletedFiles - paths that were removed from disk\r\n * @param allChangedPaths - includes .env so we can detect config reloads\r\n */\r\n public async executeBatchReload(\r\n changedPaths: string[],\r\n filesMap: Map<string, FileManager>,\r\n deletedFiles: string[],\r\n allChangedPaths?: string[],\r\n ): Promise<void> {\r\n const envFilesChanged = (allChangedPaths ?? []).some(isEnvPath);\r\n\r\n if (changedPaths.length === 0 && deletedFiles.length === 0 && !envFilesChanged) {\r\n return;\r\n }\r\n\r\n // Deletes: clean up routes/cleanup hooks for files that no longer exist.\r\n for (const path of deletedFiles) {\r\n const file = filesMap.get(path);\r\n if (file) this.moduleLoader.cleanupDeletedModule(file);\r\n }\r\n\r\n // Env-only change: reload all configs, restart connectors that watch them.\n if (changedPaths.length === 0 && envFilesChanged) {\n const configPaths = await this.reloadAffectedModules([\".env\"], filesMap);\n await this.restartAffectedConnectors([...deletedFiles, ...configPaths]);\n return;\n }\n\n if (changedPaths.length === 0) {\n await this.restartAffectedConnectors(deletedFiles);\n return;\n }\n\r\n const invalidationChain = new Set<string>();\r\n for (const path of changedPaths) {\r\n for (const file of this.dependencyGraph.getInvalidationChain(path)) {\r\n invalidationChain.add(file);\r\n }\r\n devLogHMR(path, invalidationChain.size - 1);\r\n }\r\n\r\n const chain = Array.from(invalidationChain);\r\n\r\n // Step 1: bump version counters so the next import() is fresh.\r\n for (const relativePath of chain) {\r\n const file = filesMap.get(relativePath);\r\n if (!file) continue;\r\n this.moduleLoader.runCleanup(file);\r\n this.bumpVersion(file.absolutePath);\r\n await file.process({ force: true });\r\n }\r\n\r\n // Step 2: wait for the hook worker to ack every bump.\r\n // Without this, resolve() may still return the old ?v=N URL.\r\n await this.flushVersionBumps();\r\n\r\n // Step 3: re-import affected special files.\r\n const affectedConfigPaths = await this.reloadAffectedModules(chain, filesMap);\n\n // Step 4: restart any connector whose watched-files overlap the chain.\n await this.restartAffectedConnectors([\n ...changedPaths,\n ...deletedFiles,\n ...affectedConfigPaths,\n ]);\n }\n\r\n private async restartAffectedConnectors(affectedFiles: string[]): Promise<void> {\r\n const toRestart = connectorsManager\r\n .list()\r\n .filter(connector => connector.shouldRestart(affectedFiles));\r\n\r\n for (const connector of toRestart) {\r\n await connector.restart();\r\n }\r\n }\r\n\r\n /**\r\n * Re-import every special file whose path or dependency-set intersects the\r\n * invalidation chain. Returns the relative paths of any config files that\r\n * reloaded so the caller can pass them to the connector-restart pass.\r\n */\r\n private async reloadAffectedModules(\r\n chain: string[],\r\n filesMap: Map<string, FileManager>,\r\n ): Promise<string[]> {\r\n const isEnvAffected = chain.some(isEnvPath);\r\n // Same precedence policy as the boot-time load: an exported variable is not\r\n // demoted to the file's value just because the file was touched.\r\n if (isEnvAffected) await loadEnv(undefined, environmentLoaderOptions);\r\n\r\n const isAffected = (file: FileManager) => isFileAffected(file, chain);\r\n\r\n // Models self-register via the @RegisterModel decorator and rely on the\r\n // module-loader's registerCleanup() to attach Model.$cleanup (which\r\n // unregisters them on the next reload). That only happens inside\r\n // loadModule(), which models hit exactly once — at boot, via\r\n // autoDiscoverFiles. During HMR they're otherwise re-imported\r\n // *transitively* through routes, which never re-runs registerCleanup, so\r\n // after the first reload the cleanup list is empty and the registration\r\n // leaks (\"Model X is already registered\" on every subsequent edit).\r\n //\r\n // Re-importing changed model files through loadModule here re-attaches\r\n // $cleanup every cycle. It runs before the route pass so the decorator\r\n // registers once; the transitive route import then hits the cached ?v=N\r\n // and does not double-register.\r\n const affectedModels = chain\r\n .map(path => filesMap.get(path))\r\n .filter((file): file is FileManager => !!file && file.type === \"model\");\r\n\r\n for (const file of affectedModels) {\r\n await this.moduleLoader.loadModule(file, \"model\");\r\n }\r\n\r\n const collector = this.specialFilesCollector;\r\n const affectedConfigs = collector\r\n .getFilesByType(\"config\")\r\n .filter(file => (isEnvAffected ? true : isAffected(file)));\r\n const affectedMains = collector.getFilesByType(\"main\").filter(isAffected);\r\n const affectedRoutes = collector.getFilesByType(\"route\").filter(isAffected);\r\n const affectedEvents = collector.getFilesByType(\"event\").filter(isAffected);\r\n const affectedLocales = collector.getFilesByType(\"locale\").filter(isAffected);\r\n\r\n const hasSpecialFiles =\r\n affectedConfigs.length > 0 ||\r\n affectedMains.length > 0 ||\r\n affectedRoutes.length > 0 ||\r\n affectedEvents.length > 0 ||\r\n affectedLocales.length > 0;\r\n\r\n // No entry points touched: reloading internal files alone is wasted work\r\n // because the hook will re-import them on next access anyway. But the\r\n // dep chain's last hop is usually the user-facing edge — give it a kick.\r\n if (!hasSpecialFiles) {\r\n const tail = filesMap.get(chain[chain.length - 1]);\r\n if (tail) await this.moduleLoader.reloadModule(tail);\r\n return [];\r\n }\r\n\r\n const configPaths: string[] = [];\r\n for (const file of affectedConfigs) {\r\n await configManager.reload(file);\r\n configPaths.push(file.relativePath);\r\n }\r\n\r\n // Order matters: locales first (translations used by main), main before\r\n // routes (registers state routes consume), events between (listeners).\r\n for (const file of affectedLocales) await this.moduleLoader.reloadModule(file);\r\n for (const file of affectedMains) await this.moduleLoader.reloadModule(file);\r\n for (const file of affectedEvents) await this.moduleLoader.reloadModule(file);\r\n for (const file of affectedRoutes) await this.moduleLoader.reloadModule(file);\r\n\r\n return configPaths;\r\n }\r\n}\r\n\r\nfunction isEnvPath(path: string): boolean {\r\n const basename = path.split(\"/\").pop() ?? path;\r\n return basename === \".env\" || basename.startsWith(\".env.\");\r\n}\r\n\r\n/**\r\n * A file is \"affected\" if it itself is in the chain or imports something in it.\r\n */\r\nfunction isFileAffected(file: FileManager, chain: string[]): boolean {\r\n if (chain.includes(file.relativePath)) return true;\r\n for (const dep of file.dependencies) {\r\n if (chain.includes(dep)) return true;\r\n }\r\n return false;\r\n}\r\n"],"mappings":";;;;;;;;;;;;;;;AAkBA,IAAa,gBAAb,MAA2B;CACzB,AAAO,YACL,AAAiB,iBACjB,AAAiB,uBACjB,AAAiB,cACjB,AAAiB,aACjB,AAAiB,mBACjB;EALiB;EACA;EACA;EACA;EACA;CAChB;;;;;;;;;CAUH,MAAa,mBACX,cACA,UACA,cACA,iBACe;EACf,MAAM,mBAAmB,mBAAmB,CAAC,EAAC,CAAE,KAAK,SAAS;EAE9D,IAAI,aAAa,WAAW,KAAK,aAAa,WAAW,KAAK,CAAC,iBAC7D;EAIF,KAAK,MAAM,QAAQ,cAAc;GAC/B,MAAM,OAAO,SAAS,IAAI,IAAI;GAC9B,IAAI,MAAM,KAAK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,WAAW,KAAK,MAAM,GAAG,CAAC,CAAC,IAAI,KAAK;CAC1C,OAAO,aAAa,UAAU,SAAS,WAAW,OAAO;AAC3D;;;;AAKA,SAAS,eAAe,MAAmB,OAA0B;CACnE,IAAI,MAAM,SAAS,KAAK,YAAY,GAAG,OAAO;CAC9C,KAAK,MAAM,OAAO,KAAK,cACrB,IAAI,MAAM,SAAS,GAAG,GAAG,OAAO;CAElC,OAAO;AACT"}
1
+ {"version":3,"file":"layer-executor.mjs","names":[],"sources":["../../../../../../../core/src/dev-server/layer-executor.ts"],"sourcesContent":["import { loadEnv } from \"@mongez/dotenv\";\r\nimport { configManager } from \"../config/config-manager\";\r\nimport { connectorsManager } from \"../connectors/connectors-manager\";\r\nimport type { DependencyGraph } from \"./dependency-graph\";\r\nimport { devLogHMR } from \"./dev-logger\";\r\nimport { FileManager } from \"./file-manager\";\r\nimport type { ModuleLoader } from \"./module-loader\";\r\nimport type { SpecialFilesCollector } from \"./special-files-collector\";\r\nimport { environmentLoaderOptions } from \"../utils/load-environment\";\r\n\r\n/**\r\n * Decides what to reload when a batch of files changes.\r\n *\r\n * Strategy: bump the hook's version counter for every file in the\r\n * invalidation chain, wait for the hook worker to flush, then re-import\r\n * any special files (config / main / routes / events / locales) the chain\r\n * touched and restart any connector whose watched-files overlap the change.\r\n */\r\nexport class LayerExecutor {\r\n public constructor(\r\n private readonly dependencyGraph: DependencyGraph,\r\n private readonly specialFilesCollector: SpecialFilesCollector,\r\n private readonly moduleLoader: ModuleLoader,\r\n private readonly bumpVersion: (absolutePath: string) => void,\r\n private readonly flushVersionBumps: () => Promise<void>,\r\n ) {}\r\n\r\n /**\r\n * Entry point for the file watcher batch.\r\n *\r\n * @param changedPaths - code files added or changed in this batch\r\n * @param filesMap - all tracked files (relativePath → FileManager)\r\n * @param deletedFiles - paths that were removed from disk\r\n * @param allChangedPaths - includes .env so we can detect config reloads\r\n */\r\n public async executeBatchReload(\r\n changedPaths: string[],\r\n filesMap: Map<string, FileManager>,\r\n deletedFiles: string[],\r\n allChangedPaths?: string[],\r\n ): Promise<void> {\r\n const envFilesChanged = (allChangedPaths ?? []).some(isEnvPath);\r\n\r\n if (changedPaths.length === 0 && deletedFiles.length === 0 && !envFilesChanged) {\r\n return;\r\n }\r\n\r\n // Deletes: clean up routes/cleanup hooks for files that no longer exist.\r\n for (const path of deletedFiles) {\r\n const file = filesMap.get(path);\r\n if (file) this.moduleLoader.cleanupDeletedModule(file);\r\n }\r\n\r\n // Env-only change: reload all configs, restart connectors that watch them.\r\n if (changedPaths.length === 0 && envFilesChanged) {\r\n const configPaths = await this.reloadAffectedModules([\".env\"], filesMap);\r\n await this.restartAffectedConnectors([...deletedFiles, ...configPaths]);\r\n return;\r\n }\r\n\r\n if (changedPaths.length === 0) {\r\n await this.restartAffectedConnectors(deletedFiles);\r\n return;\r\n }\r\n\r\n const invalidationChain = new Set<string>();\r\n for (const path of changedPaths) {\r\n for (const file of this.dependencyGraph.getInvalidationChain(path)) {\r\n invalidationChain.add(file);\r\n }\r\n devLogHMR(path, invalidationChain.size - 1);\r\n }\r\n\r\n const chain = Array.from(invalidationChain);\r\n\r\n // Step 1: bump version counters so the next import() is fresh.\r\n for (const relativePath of chain) {\r\n const file = filesMap.get(relativePath);\r\n if (!file) continue;\r\n this.moduleLoader.runCleanup(file);\r\n this.bumpVersion(file.absolutePath);\r\n await file.process({ force: true });\r\n }\r\n\r\n // Step 2: wait for the hook worker to ack every bump.\r\n // Without this, resolve() may still return the old ?v=N URL.\r\n await this.flushVersionBumps();\r\n\r\n // Step 3: re-import affected special files.\r\n const affectedConfigPaths = await this.reloadAffectedModules(chain, filesMap);\r\n\r\n // Step 4: restart any connector whose watched-files overlap the chain.\r\n await this.restartAffectedConnectors([\r\n ...changedPaths,\r\n ...deletedFiles,\r\n ...affectedConfigPaths,\r\n ]);\r\n }\r\n\r\n private async restartAffectedConnectors(affectedFiles: string[]): Promise<void> {\r\n const toRestart = connectorsManager\r\n .list()\r\n .filter((connector) => connector.shouldRestart(affectedFiles));\r\n\r\n for (const connector of toRestart) {\r\n await connector.restart();\r\n }\r\n }\r\n\r\n /**\r\n * Re-import every special file whose path or dependency-set intersects the\r\n * invalidation chain. Returns the relative paths of any config files that\r\n * reloaded so the caller can pass them to the connector-restart pass.\r\n */\r\n private async reloadAffectedModules(\r\n chain: string[],\r\n filesMap: Map<string, FileManager>,\r\n ): Promise<string[]> {\r\n const isEnvAffected = chain.some(isEnvPath);\r\n // Same precedence policy as the boot-time load: an exported variable is not\r\n // demoted to the file's value just because the file was touched.\r\n if (isEnvAffected) await loadEnv(undefined, environmentLoaderOptions);\r\n\r\n const isAffected = (file: FileManager) => isFileAffected(file, chain);\r\n\r\n // Models self-register via the @RegisterModel decorator and rely on the\r\n // module-loader's registerCleanup() to attach Model.$cleanup (which\r\n // unregisters them on the next reload). That only happens inside\r\n // loadModule(), which models hit exactly once — at boot, via\r\n // autoDiscoverFiles. During HMR they're otherwise re-imported\r\n // *transitively* through routes, which never re-runs registerCleanup, so\r\n // after the first reload the cleanup list is empty and the registration\r\n // leaks (\"Model X is already registered\" on every subsequent edit).\r\n //\r\n // Re-importing changed model files through loadModule here re-attaches\r\n // $cleanup every cycle. It runs before the route pass so the decorator\r\n // registers once; the transitive route import then hits the cached ?v=N\r\n // and does not double-register.\r\n const affectedModels = chain\r\n .map((path) => filesMap.get(path))\r\n .filter((file): file is FileManager => !!file && file.type === \"model\");\r\n\r\n for (const file of affectedModels) {\r\n await this.moduleLoader.loadModule(file, \"model\");\r\n }\r\n\r\n const collector = this.specialFilesCollector;\r\n const affectedConfigs = collector\r\n .getFilesByType(\"config\")\r\n .filter((file) => (isEnvAffected ? true : isAffected(file)));\r\n const affectedMains = collector.getFilesByType(\"main\").filter(isAffected);\r\n const affectedRoutes = collector.getFilesByType(\"route\").filter(isAffected);\r\n const affectedEvents = collector.getFilesByType(\"event\").filter(isAffected);\r\n const affectedLocales = collector.getFilesByType(\"locale\").filter(isAffected);\r\n\r\n const hasSpecialFiles =\r\n affectedConfigs.length > 0 ||\r\n affectedMains.length > 0 ||\r\n affectedRoutes.length > 0 ||\r\n affectedEvents.length > 0 ||\r\n affectedLocales.length > 0;\r\n\r\n // No entry points touched: reloading internal files alone is wasted work\r\n // because the hook will re-import them on next access anyway. But the\r\n // dep chain's last hop is usually the user-facing edge — give it a kick.\r\n if (!hasSpecialFiles) {\r\n const tail = filesMap.get(chain[chain.length - 1]);\r\n if (tail) await this.moduleLoader.reloadModule(tail);\r\n return [];\r\n }\r\n\r\n const configPaths: string[] = [];\r\n for (const file of affectedConfigs) {\r\n await configManager.reload(file);\r\n configPaths.push(file.relativePath);\r\n }\r\n\r\n // Order matters: locales first (translations used by main), main before\r\n // routes (registers state routes consume), events between (listeners).\r\n for (const file of affectedLocales) await this.moduleLoader.reloadModule(file);\r\n for (const file of affectedMains) await this.moduleLoader.reloadModule(file);\r\n for (const file of affectedEvents) await this.moduleLoader.reloadModule(file);\r\n for (const file of affectedRoutes) await this.moduleLoader.reloadModule(file);\r\n\r\n return configPaths;\r\n }\r\n}\r\n\r\nfunction isEnvPath(path: string): boolean {\r\n const basename = path.split(\"/\").pop() ?? path;\r\n return basename === \".env\" || basename.startsWith(\".env.\");\r\n}\r\n\r\n/**\r\n * A file is \"affected\" if it itself is in the chain or imports something in it.\r\n */\r\nfunction isFileAffected(file: FileManager, chain: string[]): boolean {\r\n if (chain.includes(file.relativePath)) return true;\r\n for (const dep of file.dependencies) {\r\n if (chain.includes(dep)) return true;\r\n }\r\n return false;\r\n}\r\n"],"mappings":";;;;;;;;;;;;;;;AAkBA,IAAa,gBAAb,MAA2B;CACzB,AAAO,YACL,AAAiB,iBACjB,AAAiB,uBACjB,AAAiB,cACjB,AAAiB,aACjB,AAAiB,mBACjB;EALiB;EACA;EACA;EACA;EACA;CAChB;;;;;;;;;CAUH,MAAa,mBACX,cACA,UACA,cACA,iBACe;EACf,MAAM,mBAAmB,mBAAmB,CAAC,EAAC,CAAE,KAAK,SAAS;EAE9D,IAA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AK,aAAa,aAAa,IAAI;EAC5E,KAAK,MAAM,QAAQ,gBAAgB,MAAM,KAAK,aAAa,aAAa,IAAI;EAE5E,OAAO;CACT;AACF;AAEA,SAAS,UAAU,MAAuB;CACxC,MAAM,WAAW,KAAK,MAAM,GAAG,CAAC,CAAC,IAAI,KAAK;CAC1C,OAAO,aAAa,UAAU,SAAS,WAAW,OAAO;AAC3D;;;;AAKA,SAAS,eAAe,MAAmB,OAA0B;CACnE,IAAI,MAAM,SAAS,KAAK,YAAY,GAAG,OAAO;CAC9C,KAAK,MAAM,OAAO,KAAK,cACrB,IAAI,MAAM,SAAS,GAAG,GAAG,OAAO;CAElC,OAAO;AACT"}
@@ -1 +1 @@
1
- {"version":3,"file":"build-transpile-init.mjs","names":[],"sources":["../../../../../../../../core/src/dev-server/loader/build-transpile-init.ts"],"sourcesContent":["import { version as esbuildVersion } from \"esbuild\";\nimport { warlockPath } from \"../../utils\";\nimport type { TranspileInit } from \"./load-hook.js\";\nimport { CACHE_EPOCH, computeFingerprint } from \"./transpile-cache.js\";\n\n/**\n * esbuild `target` for the dev transform. Pinned to the same value the\n * production builder uses so dev and prod lower TC39 decorators (Cascade\n * leans on them) to identical helper output — a file transpiled in dev and\n * the same file built for prod must behave the same.\n */\nconst TRANSPILE_TARGET = \"node22\";\n\n/**\n * Build the transpile payload shipped into the hook worker. Always\n * returned — esbuild transpile is unconditional (tsx is no longer in the\n * TypeScript path); persistence to `.warlock/transpile` is intrinsic.\n *\n * The fingerprint folds esbuild's version, the cache-format epoch and the\n * whole tsconfig `compilerOptions` blob (plus the target) so any change to\n * the transform contract invalidates every entry structurally — no sweep,\n * no stale output.\n *\n * @param compilerOptions - Raw tsconfig `compilerOptions` (handed to esbuild\n * as `tsconfigRaw` and hashed wholesale into the fingerprint).\n * @param debugNames - `devServer.transpileCacheDebug` — cosmetic readable\n * cache filenames. Default off.\n */\nexport function buildTranspileInit(\n compilerOptions: unknown,\n debugNames: boolean,\n): TranspileInit {\n const fingerprint = computeFingerprint({\n esbuildVersion,\n cacheEpoch: CACHE_EPOCH,\n compilerOptions: { compilerOptions, target: TRANSPILE_TARGET },\n });\n\n return {\n cacheDir: warlockPath(\"transpile\"),\n fingerprint,\n target: TRANSPILE_TARGET,\n tsconfigRaw: JSON.stringify({ compilerOptions: compilerOptions ?? {} }),\n debugNames,\n };\n}\n"],"mappings":";;;;;;;;;;;;AAWA,MAAM,mBAAmB;;;;;;;;;;;;;;;;AAiBzB,SAAgB,mBACd,iBACA,YACe;CACf,MAAM,cAAc,mBAAmB;EACrC;EACA;EACA,iBAAiB;GAAE;GAAiB,QAAQ;EAAiB;CAC/D,CAAC;CAED,OAAO;EACL,UAAU,YAAY,WAAW;EACjC;EACA,QAAQ;EACR,aAAa,KAAK,UAAU,EAAE,iBAAiB,mBAAmB,CAAC,EAAE,CAAC;EACtE;CACF;AACF"}
1
+ {"version":3,"file":"build-transpile-init.mjs","names":[],"sources":["../../../../../../../../core/src/dev-server/loader/build-transpile-init.ts"],"sourcesContent":["import { version as esbuildVersion } from \"esbuild\";\nimport { warlockPath } from \"../../utils\";\nimport type { TranspileInit } from \"./load-hook.js\";\nimport { CACHE_EPOCH, computeFingerprint } from \"./transpile-cache.js\";\n\n/**\n * esbuild `target` for the dev transform. Pinned to the same value the\n * production builder uses so dev and prod lower TC39 decorators (Cascade\n * leans on them) to identical helper output — a file transpiled in dev and\n * the same file built for prod must behave the same.\n */\nconst TRANSPILE_TARGET = \"node22\";\n\n/**\n * Build the transpile payload shipped into the hook worker. Always\n * returned — esbuild transpile is unconditional (tsx is no longer in the\n * TypeScript path); persistence to `.warlock/transpile` is intrinsic.\n *\n * The fingerprint folds esbuild's version, the cache-format epoch and the\n * whole tsconfig `compilerOptions` blob (plus the target) so any change to\n * the transform contract invalidates every entry structurally — no sweep,\n * no stale output.\n *\n * @param compilerOptions - Raw tsconfig `compilerOptions` (handed to esbuild\n * as `tsconfigRaw` and hashed wholesale into the fingerprint).\n * @param debugNames - `devServer.transpileCacheDebug` — cosmetic readable\n * cache filenames. Default off.\n */\nexport function buildTranspileInit(compilerOptions: unknown, debugNames: boolean): TranspileInit {\n const fingerprint = computeFingerprint({\n esbuildVersion,\n cacheEpoch: CACHE_EPOCH,\n compilerOptions: { compilerOptions, target: TRANSPILE_TARGET },\n });\n\n return {\n cacheDir: warlockPath(\"transpile\"),\n fingerprint,\n target: TRANSPILE_TARGET,\n tsconfigRaw: JSON.stringify({ compilerOptions: compilerOptions ?? {} }),\n debugNames,\n };\n}\n"],"mappings":";;;;;;;;;;;;AAWA,MAAM,mBAAmB;;;;;;;;;;;;;;;;AAiBzB,SAAgB,mBAAmB,iBAA0B,YAAoC;CAC/F,MAAM,cAAc,mBAAmB;EACrC;EACA;EACA,iBAAiB;GAAE;GAAiB,QAAQ;EAAiB;CAC/D,CAAC;CAED,OAAO;EACL,UAAU,YAAY,WAAW;EACjC;EACA,QAAQ;EACR,aAAa,KAAK,UAAU,EAAE,iBAAiB,mBAAmB,CAAC,EAAE,CAAC;EACtE;CACF;AACF"}
@@ -1 +1 @@
1
- {"version":3,"file":"load-hook.mjs","names":[],"sources":["../../../../../../../../core/src/dev-server/loader/load-hook.ts"],"sourcesContent":["import { transformSync } from \"esbuild\";\nimport { readFileSync } from \"node:fs\";\nimport { fileURLToPath } from \"node:url\";\nimport { sourceSlug } from \"./source-slug.js\";\nimport { cacheKey, TranspileCache } from \"./transpile-cache.js\";\n\ntype LoadContext = {\n format?: string;\n importAttributes?: Record<string, string>;\n};\n\ntype LoadResult = {\n format: string;\n source: string | Buffer;\n shortCircuit?: boolean;\n};\n\ntype NextLoad = (url: string, context?: LoadContext) => Promise<LoadResult>;\n\n/**\n * Everything the transpile path needs, computed once on the main thread and\n * shipped into the hook worker via `initialize()`. Always present — esbuild\n * transpile is unconditional now (tsx is no longer in the TS path).\n */\nexport type TranspileInit = {\n /** Absolute `.warlock/transpile` directory. */\n cacheDir: string;\n /** Source-content key salt: esbuild version + epoch + tsconfig blob. */\n fingerprint: string;\n /** esbuild `target` (e.g. `\"node22\"` — must match the prod builder). */\n target: string;\n /** JSON string of `{ compilerOptions }` handed to esbuild as tsconfigRaw. */\n tsconfigRaw: string;\n /**\n * Debug-only: name cache files `<slug>.<hash>.js` and append a trailing\n * `// @source <path>` marker so entries are eyeball-identifiable. Off by\n * default (opaque `<hash>.js`). Cosmetic — never affects keys or lookup.\n */\n debugNames: boolean;\n};\n\nconst VERSION_QUERY = /\\?v=\\d+$/;\nconst TS_FILE = /\\.(ts|tsx|mts|cts)$/;\n\nlet transpile: TranspileInit;\nlet cache: TranspileCache;\n\n/**\n * Called once from the hook worker's `initialize()`. Wires the persisted\n * transpile cache and runs one opportunistic GC pass at boot — cheap, off\n * the hot path, single directory scan.\n */\nexport function configureTranspile(init: TranspileInit): void {\n transpile = init;\n cache = new TranspileCache(init.cacheDir);\n\n // Boot-time eviction so the cache can't grow unbounded across weeks of\n // dev. Bounds are generous; correctness never depends on GC (content\n // hashing already guarantees that) — this is purely disk hygiene.\n cache.gc({\n maxBytes: 256 * 1024 * 1024,\n maxAgeMs: 14 * 24 * 60 * 60 * 1000,\n });\n}\n\n/**\n * ESM loader `load()` hook.\n *\n * Owns the transpile for **every** TypeScript file — project `src/`,\n * `@warlock.js/*` framework source, and `warlock.config.ts` alike. There\n * is no tsx in the TypeScript path any more: we read the source, key it by\n * a content hash + options fingerprint, serve the cached JS on a hit, and\n * otherwise transform it with esbuild directly and persist. Non-TypeScript\n * URLs (npm `.js`/`.cjs`/`.mjs`, `node:` builtins, JSON) are not ours —\n * they fall through to the next loader (Node's default).\n *\n * The `?v=<N>` query drives Node's module identity (HMR) for `src/` files\n * and is **never** part of the cache key — the cache is keyed purely by\n * source content, so the two mechanisms are fully orthogonal. Framework\n * and config `.ts` carry no `?v` (no HMR) but are transpiled and cached\n * exactly the same way.\n *\n * The source map esbuild emits is inline base64 with `sourcefile` set to\n * the clean absolute `.ts` path, so V8 (run with source maps enabled)\n * reports stack frames at the original TypeScript location.\n *\n * @example\n * // load(\"file:///src/user.model.ts?v=3\") → esbuild transpile + cache\n * // load(\"file:///@warlock.js/core/src/x.ts\") → esbuild transpile + cache\n * // load(\"file:///node_modules/ms/index.js\") → nextLoad (Node default)\n */\nexport async function load(\n url: string,\n context: LoadContext,\n nextLoad: NextLoad,\n): Promise<LoadResult> {\n const cleanUrl = url.replace(VERSION_QUERY, \"\");\n\n // Not TypeScript → not ours. npm packages, node: builtins, JSON, etc.\n if (!TS_FILE.test(cleanUrl)) {\n return nextLoad(url, context);\n }\n\n const absolutePath = fileURLToPath(cleanUrl);\n const source = readFileSync(absolutePath, \"utf8\");\n const key = cacheKey(source, transpile.fingerprint);\n\n // Cosmetic filename label; undefined keeps opaque <hash>.js names.\n const label = transpile.debugNames ? sourceSlug(absolutePath) : undefined;\n\n const hit = cache.get(key, label);\n if (hit) {\n return { format: \"module\", source: hit.code, shortCircuit: true };\n }\n\n const loader = absolutePath.endsWith(\".tsx\") ? \"tsx\" : \"ts\";\n\n const result = transformSync(source, {\n loader,\n format: \"esm\",\n target: transpile.target,\n sourcefile: absolutePath,\n // Inline base64 map, self-contained (sourcesContent on by default), so\n // it survives the ?v=N URL with no extra resolution step.\n sourcemap: \"inline\",\n tsconfigRaw: transpile.tsconfigRaw,\n });\n\n // result.code already carries the inline //# sourceMappingURL. The\n // marker goes AFTER that line: a trailing comment can't shift earlier\n // generated lines, so the inline map (and therefore stack-frame line\n // numbers) stays exact. A leading marker would desync it by one line.\n const code = label\n ? `${result.code}\\n// @source ${absolutePath}\\n`\n : result.code;\n\n cache.put(key, { code, map: \"\" }, label);\n\n return { format: \"module\", source: code, shortCircuit: true };\n}\n"],"mappings":";;;;;;;AAyCA,MAAM,gBAAgB;AACtB,MAAM,UAAU;AAEhB,IAAI;AACJ,IAAI;;;;;;AAOJ,SAAgB,mBAAmB,MAA2B;CAC5D,YAAY;CACZ,QAAQ,IAAI,eAAe,KAAK,QAAQ;CAKxC,MAAM,GAAG;EACP,UAAU,MAAM,OAAO;EACvB,UAAU,MAAU,KAAK,KAAK;CAChC,CAAC;AACH;;;;;;;;;;;;;;;;;;;;;;;;;;;AA4BA,eAAsB,KACpB,KACA,SACA,UACqB;CACrB,MAAM,WAAW,IAAI,QAAQ,eAAe,EAAE;CAG9C,IAAI,CAAC,QAAQ,KAAK,QAAQ,GACxB,OAAO,SAAS,KAAK,OAAO;CAG9B,MAAM,eAAe,cAAc,QAAQ;CAC3C,MAAM,SAAS,aAAa,cAAc,MAAM;CAChD,MAAM,MAAM,SAAS,QAAQ,UAAU,WAAW;CAGlD,MAAM,QAAQ,UAAU,aAAa,WAAW,YAAY,IAAI;CAEhE,MAAM,MAAM,MAAM,IAAI,KAAK,KAAK;CAChC,IAAI,KACF,OAAO;EAAE,QAAQ;EAAU,QAAQ,IAAI;EAAM,cAAc;CAAK;CAKlE,MAAM,SAAS,cAAc,QAAQ;EACnC,QAHa,aAAa,SAAS,MAAM,IAAI,QAAQ;EAIrD,QAAQ;EACR,QAAQ,UAAU;EAClB,YAAY;EAGZ,WAAW;EACX,aAAa,UAAU;CACzB,CAAC;CAMD,MAAM,OAAO,QACT,GAAG,OAAO,KAAK,eAAe,aAAa,MAC3C,OAAO;CAEX,MAAM,IAAI,KAAK;EAAE;EAAM,KAAK;CAAG,GAAG,KAAK;CAEvC,OAAO;EAAE,QAAQ;EAAU,QAAQ;EAAM,cAAc;CAAK;AAC9D"}
1
+ {"version":3,"file":"load-hook.mjs","names":[],"sources":["../../../../../../../../core/src/dev-server/loader/load-hook.ts"],"sourcesContent":["import { transformSync } from \"esbuild\";\nimport { readFileSync } from \"node:fs\";\nimport { fileURLToPath } from \"node:url\";\nimport { sourceSlug } from \"./source-slug.js\";\nimport { cacheKey, TranspileCache } from \"./transpile-cache.js\";\n\ntype LoadContext = {\n format?: string;\n importAttributes?: Record<string, string>;\n};\n\ntype LoadResult = {\n format: string;\n source: string | Buffer;\n shortCircuit?: boolean;\n};\n\ntype NextLoad = (url: string, context?: LoadContext) => Promise<LoadResult>;\n\n/**\n * Everything the transpile path needs, computed once on the main thread and\n * shipped into the hook worker via `initialize()`. Always present — esbuild\n * transpile is unconditional now (tsx is no longer in the TS path).\n */\nexport type TranspileInit = {\n /** Absolute `.warlock/transpile` directory. */\n cacheDir: string;\n /** Source-content key salt: esbuild version + epoch + tsconfig blob. */\n fingerprint: string;\n /** esbuild `target` (e.g. `\"node22\"` — must match the prod builder). */\n target: string;\n /** JSON string of `{ compilerOptions }` handed to esbuild as tsconfigRaw. */\n tsconfigRaw: string;\n /**\n * Debug-only: name cache files `<slug>.<hash>.js` and append a trailing\n * `// @source <path>` marker so entries are eyeball-identifiable. Off by\n * default (opaque `<hash>.js`). Cosmetic — never affects keys or lookup.\n */\n debugNames: boolean;\n};\n\nconst VERSION_QUERY = /\\?v=\\d+$/;\nconst TS_FILE = /\\.(ts|tsx|mts|cts)$/;\n\nlet transpile: TranspileInit;\nlet cache: TranspileCache;\n\n/**\n * Called once from the hook worker's `initialize()`. Wires the persisted\n * transpile cache and runs one opportunistic GC pass at boot — cheap, off\n * the hot path, single directory scan.\n */\nexport function configureTranspile(init: TranspileInit): void {\n transpile = init;\n cache = new TranspileCache(init.cacheDir);\n\n // Boot-time eviction so the cache can't grow unbounded across weeks of\n // dev. Bounds are generous; correctness never depends on GC (content\n // hashing already guarantees that) — this is purely disk hygiene.\n cache.gc({\n maxBytes: 256 * 1024 * 1024,\n maxAgeMs: 14 * 24 * 60 * 60 * 1000,\n });\n}\n\n/**\n * ESM loader `load()` hook.\n *\n * Owns the transpile for **every** TypeScript file — project `src/`,\n * `@warlock.js/*` framework source, and `warlock.config.ts` alike. There\n * is no tsx in the TypeScript path any more: we read the source, key it by\n * a content hash + options fingerprint, serve the cached JS on a hit, and\n * otherwise transform it with esbuild directly and persist. Non-TypeScript\n * URLs (npm `.js`/`.cjs`/`.mjs`, `node:` builtins, JSON) are not ours —\n * they fall through to the next loader (Node's default).\n *\n * The `?v=<N>` query drives Node's module identity (HMR) for `src/` files\n * and is **never** part of the cache key — the cache is keyed purely by\n * source content, so the two mechanisms are fully orthogonal. Framework\n * and config `.ts` carry no `?v` (no HMR) but are transpiled and cached\n * exactly the same way.\n *\n * The source map esbuild emits is inline base64 with `sourcefile` set to\n * the clean absolute `.ts` path, so V8 (run with source maps enabled)\n * reports stack frames at the original TypeScript location.\n *\n * @example\n * // load(\"file:///src/user.model.ts?v=3\") → esbuild transpile + cache\n * // load(\"file:///@warlock.js/core/src/x.ts\") → esbuild transpile + cache\n * // load(\"file:///node_modules/ms/index.js\") → nextLoad (Node default)\n */\nexport async function load(\n url: string,\n context: LoadContext,\n nextLoad: NextLoad,\n): Promise<LoadResult> {\n const cleanUrl = url.replace(VERSION_QUERY, \"\");\n\n // Not TypeScript → not ours. npm packages, node: builtins, JSON, etc.\n if (!TS_FILE.test(cleanUrl)) {\n return nextLoad(url, context);\n }\n\n const absolutePath = fileURLToPath(cleanUrl);\n const source = readFileSync(absolutePath, \"utf8\");\n const key = cacheKey(source, transpile.fingerprint);\n\n // Cosmetic filename label; undefined keeps opaque <hash>.js names.\n const label = transpile.debugNames ? sourceSlug(absolutePath) : undefined;\n\n const hit = cache.get(key, label);\n if (hit) {\n return { format: \"module\", source: hit.code, shortCircuit: true };\n }\n\n const loader = absolutePath.endsWith(\".tsx\") ? \"tsx\" : \"ts\";\n\n const result = transformSync(source, {\n loader,\n format: \"esm\",\n target: transpile.target,\n sourcefile: absolutePath,\n // Inline base64 map, self-contained (sourcesContent on by default), so\n // it survives the ?v=N URL with no extra resolution step.\n sourcemap: \"inline\",\n tsconfigRaw: transpile.tsconfigRaw,\n });\n\n // result.code already carries the inline //# sourceMappingURL. The\n // marker goes AFTER that line: a trailing comment can't shift earlier\n // generated lines, so the inline map (and therefore stack-frame line\n // numbers) stays exact. A leading marker would desync it by one line.\n const code = label ? `${result.code}\\n// @source ${absolutePath}\\n` : result.code;\n\n cache.put(key, { code, map: \"\" }, label);\n\n return { format: \"module\", source: code, shortCircuit: true };\n}\n"],"mappings":";;;;;;;AAyCA,MAAM,gBAAgB;AACtB,MAAM,UAAU;AAEhB,IAAI;AACJ,IAAI;;;;;;AAOJ,SAAgB,mBAAmB,MAA2B;CAC5D,YAAY;CACZ,QAAQ,IAAI,eAAe,KAAK,QAAQ;CAKxC,MAAM,GAAG;EACP,UAAU,MAAM,OAAO;EACvB,UAAU,MAAU,KAAK,KAAK;CAChC,CAAC;AACH;;;;;;;;;;;;;;;;;;;;;;;;;;;AA4BA,eAAsB,KACpB,KACA,SACA,UACqB;CACrB,MAAM,WAAW,IAAI,QAAQ,eAAe,EAAE;CAG9C,IAAI,CAAC,QAAQ,KAAK,QAAQ,GACxB,OAAO,SAAS,KAAK,OAAO;CAG9B,MAAM,eAAe,cAAc,QAAQ;CAC3C,MAAM,SAAS,aAAa,cAAc,MAAM;CAChD,MAAM,MAAM,SAAS,QAAQ,UAAU,WAAW;CAGlD,MAAM,QAAQ,UAAU,aAAa,WAAW,YAAY,IAAI;CAEhE,MAAM,MAAM,MAAM,IAAI,KAAK,KAAK;CAChC,IAAI,KACF,OAAO;EAAE,QAAQ;EAAU,QAAQ,IAAI;EAAM,cAAc;CAAK;CAKlE,MAAM,SAAS,cAAc,QAAQ;EACnC,QAHa,aAAa,SAAS,MAAM,IAAI,QAAQ;EAIrD,QAAQ;EACR,QAAQ,UAAU;EAClB,YAAY;EAGZ,WAAW;EACX,aAAa,UAAU;CACzB,CAAC;CAMD,MAAM,OAAO,QAAQ,GAAG,OAAO,KAAK,eAAe,aAAa,MAAM,OAAO;CAE7E,MAAM,IAAI,KAAK;EAAE;EAAM,KAAK;CAAG,GAAG,KAAK;CAEvC,OAAO;EAAE,QAAQ;EAAU,QAAQ;EAAM,cAAc;CAAK;AAC9D"}