@warlock.js/core 5.5.0 → 5.6.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.
- package/CHANGELOG.md +14 -0
- package/esm/application/app.d.mts.map +1 -1
- package/esm/application/app.mjs +7 -1
- package/esm/application/app.mjs.map +1 -1
- package/esm/cli/cli-commands.utils.mjs.map +1 -1
- package/esm/cli/commands/doctor/checks/optional-peers.check.mjs.map +1 -1
- package/esm/cli/commands/doctor/checks/release-hygiene.check.mjs.map +1 -1
- package/esm/cli/commands/generate/generators/column-dsl-parser.mjs.map +1 -1
- package/esm/cli/commands/generate/generators/migration.generator.mjs.map +1 -1
- package/esm/cli/commands/routes/format-routes-table.mjs.map +1 -1
- package/esm/cli/commands/routes/route-row.mjs.map +1 -1
- package/esm/cli/commands/routes.command.mjs.map +1 -1
- package/esm/cli/framework-cli-commands.mjs.map +1 -1
- package/esm/config/locale-configuration.mjs +11 -1
- package/esm/config/locale-configuration.mjs.map +1 -1
- package/esm/container/container-instance-registry.mjs +40 -0
- package/esm/container/container-instance-registry.mjs.map +1 -0
- package/esm/container/index.d.mts +11 -0
- package/esm/container/index.d.mts.map +1 -1
- package/esm/container/index.mjs +11 -0
- package/esm/container/index.mjs.map +1 -1
- package/esm/database/drop-tables-action.mjs.map +1 -1
- package/esm/database/migrate-action.mjs.map +1 -1
- package/esm/database/seed-command-action.mjs.map +1 -1
- package/esm/dev-server/dependency-graph.d.mts.map +1 -1
- package/esm/dev-server/dependency-graph.mjs.map +1 -1
- package/esm/dev-server/dev-logger.mjs.map +1 -1
- package/esm/dev-server/file-event-handler.mjs.map +1 -1
- package/esm/dev-server/layer-executor.mjs.map +1 -1
- package/esm/dev-server/loader/build-transpile-init.mjs.map +1 -1
- package/esm/dev-server/loader/load-hook.mjs.map +1 -1
- package/esm/dev-server/loader/register-loader.mjs.map +1 -1
- package/esm/dev-server/loader/resolve-hook.mjs.map +1 -1
- package/esm/dev-server/loader/transpile-cache.mjs.map +1 -1
- package/esm/dev-server/module-loader.mjs.map +1 -1
- package/esm/dev-server/parse-imports.mjs.map +1 -1
- package/esm/dev-server/type-generator.mjs.map +1 -1
- package/esm/dev-server/types.d.mts.map +1 -1
- package/esm/dev-server/utils.mjs.map +1 -1
- package/esm/errors/container-key-missing-error.mjs +28 -0
- package/esm/errors/container-key-missing-error.mjs.map +1 -0
- package/esm/errors/unknown-locale-error.mjs +28 -0
- package/esm/errors/unknown-locale-error.mjs.map +1 -0
- package/esm/generations/add-command.action.mjs.map +1 -1
- package/esm/generations/features/access.feature.mjs.map +1 -1
- package/esm/generations/features/ai-anthropic.feature.mjs.map +1 -1
- package/esm/generations/features/ai-bedrock.feature.mjs.map +1 -1
- package/esm/generations/features/ai-google.feature.mjs.map +1 -1
- package/esm/generations/features/ai-ollama.feature.mjs.map +1 -1
- package/esm/generations/features/ai-openai.feature.mjs.map +1 -1
- package/esm/generations/features/ai-panoptic.feature.mjs.map +1 -1
- package/esm/generations/features/ai-tools.feature.mjs.map +1 -1
- package/esm/generations/features/ai-workspace.feature.mjs.map +1 -1
- package/esm/generations/features/ai.feature.mjs.map +1 -1
- package/esm/generations/features/herald.feature.mjs.map +1 -1
- package/esm/generations/features/notifications.feature.mjs.map +1 -1
- package/esm/generations/features/scheduler.feature.mjs.map +1 -1
- package/esm/generations/features/shared/patch-tsconfig-include.mjs.map +1 -1
- package/esm/generations/features/tailwind.feature.mjs.map +1 -1
- package/esm/generations/features/types.mjs.map +1 -1
- package/esm/generations/features/web.feature.mjs.map +1 -1
- package/esm/http/context/request-memo.mjs.map +1 -1
- package/esm/http/middleware/cache-response-middleware.d.mts.map +1 -1
- package/esm/http/middleware/cache-response-middleware.mjs.map +1 -1
- package/esm/http/middleware/concurrency-limit.middleware.mjs.map +1 -1
- package/esm/http/middleware/idempotency.middleware.d.mts.map +1 -1
- package/esm/http/middleware/idempotency.middleware.mjs.map +1 -1
- package/esm/http/middleware/maintenance.middleware.mjs.map +1 -1
- package/esm/http/middleware/max-body-size.middleware.mjs.map +1 -1
- package/esm/http/middleware/rate-limit.middleware.mjs.map +1 -1
- package/esm/http/port-preflight.d.mts.map +1 -1
- package/esm/http/port-preflight.mjs.map +1 -1
- package/esm/http/request.d.mts.map +1 -1
- package/esm/http/request.mjs +2 -2
- package/esm/http/request.mjs.map +1 -1
- package/esm/http/response.d.mts +38 -0
- package/esm/http/response.d.mts.map +1 -1
- package/esm/http/response.mjs +47 -0
- package/esm/http/response.mjs.map +1 -1
- package/esm/http/server.d.mts.map +1 -1
- package/esm/http/server.mjs.map +1 -1
- package/esm/http/types.d.mts.map +1 -1
- package/esm/image/image.d.mts.map +1 -1
- package/esm/image/image.mjs.map +1 -1
- package/esm/mail/send-mail.mjs.map +1 -1
- package/esm/production/build-contributions.mjs.map +1 -1
- package/esm/production/bundle-framework-dependencies.mjs +152 -0
- package/esm/production/bundle-framework-dependencies.mjs.map +1 -0
- package/esm/production/production-builder.mjs +30 -3
- package/esm/production/production-builder.mjs.map +1 -1
- package/esm/production/production-supervisor.mjs.map +1 -1
- package/esm/production/tsconfig-path-aliases.mjs +99 -0
- package/esm/production/tsconfig-path-aliases.mjs.map +1 -0
- package/esm/react/index.d.mts.map +1 -1
- package/esm/react/index.mjs.map +1 -1
- package/esm/repositories/contracts/query-builder.contract.d.mts.map +1 -1
- package/esm/repositories/contracts/types.d.mts.map +1 -1
- package/esm/resource/resource-field-builder.d.mts.map +1 -1
- package/esm/resource/resource-field-builder.mjs.map +1 -1
- package/esm/resource/types.d.mts.map +1 -1
- package/esm/router/router.d.mts.map +1 -1
- package/esm/router/router.mjs +1 -2
- package/esm/router/router.mjs.map +1 -1
- package/esm/router/types.d.mts.map +1 -1
- package/esm/storage/drivers/cloud-driver.d.mts.map +1 -1
- package/esm/storage/drivers/cloud-driver.mjs.map +1 -1
- package/esm/storage/scoped-storage.d.mts.map +1 -1
- package/esm/storage/scoped-storage.mjs.map +1 -1
- package/esm/storage/storage.d.mts.map +1 -1
- package/esm/storage/storage.mjs.map +1 -1
- package/esm/storage/types.d.mts.map +1 -1
- package/esm/storage/utils/contain-path.mjs.map +1 -1
- package/esm/storage/utils/safe-fetch.d.mts.map +1 -1
- package/esm/storage/utils/safe-fetch.mjs.map +1 -1
- package/esm/tests/start-http-development-server.d.mts.map +1 -1
- package/esm/tests/start-http-development-server.mjs.map +1 -1
- package/esm/tests/test-lifecycle-state.mjs.map +1 -1
- package/esm/tests/test-setup-timeout.mjs.map +1 -1
- package/esm/tests/vitest-setup.d.mts.map +1 -1
- package/esm/tests/vitest-setup.mjs.map +1 -1
- package/esm/use-cases/use-cases-registry.d.mts.map +1 -1
- package/esm/use-cases/use-cases-registry.mjs.map +1 -1
- package/esm/utils/app-log.mjs.map +1 -1
- package/esm/utils/queue.mjs.map +1 -1
- package/esm/utils/sleep.mjs.map +1 -1
- package/esm/validation/plugins/database-plugin.mjs.map +1 -1
- 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":";;;;;;;;;;;;;;;;;;;;;;;;;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,IAAI,kBAAkB,WAAW,GAAG;EAClC,QAAQ,IAAI,OAAO,KAAK,2CAA2C,CAAC;EACpE;CACF;CAGA,KAAK,MAAM,aAAa,mBAAmB;EACzC,MAAM,aAAa,MAAM,UAAU,UAAU,CAAC,CAAC,OAAO,uBAAuB;EAC7E,MAAM,YAAY,UAAU,YACxB,MAAM,UAAU,SAAS,CAAC,CAAC,OAAO,uBAAuB,IACzD;EAGJ,QAAQ,IAAI,KAAK,OAAO,MAAM,GAAG,EAAE,GAAG,OAAO,WAAW,UAAU,IAAI,GAAG;EAGzE,QAAQ,IAAI,OAAO,OAAO,KAAK,WAAW,EAAE,GAAG,OAAO,MAAM,U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IA,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,IAAI,kBAAkB,WAAW,GAAG;EAClC,QAAQ,IAAI,OAAO,KAAK,2CAA2C,CAAC;EACpE;CACF;CAGA,KAAK,MAAM,aAAa,mBAAmB;EACzC,MAAM,aAAa,MAAM,UAAU,UAAU,CAAC,CAAC,OAAO,uBAAuB;EAC7E,MAAM,YAAY,UAAU,YACxB,MAAM,UAAU,SAAS,CAAC,CAAC,OAAO,uBAAuB,IACzD;EAGJ,QAAQ,IAAI,KAAK,OAAO,MAAM,GAAG,EAAE,GAAG,OAAO,WAAW,UAAU,IAAI,GAAG;EAGzE,QAAQ,IAAI,OAAO,OAAO,KAAK,WAAW,EAAE,GAAG,OAAO,MAAM,UAAU,GAAG;EAGzE,IAAI,WACF,QAAQ,IAAI,OAAO,OAAO,KAAK,UAAU,EAAE,IAAI,OAAO,OAAO,SAAS,GAAG;EAG3E,QAAQ,IAAI,EAAE;CAChB;AACF;;;;;;;;AASA,SAAS,uBAAuB,QAAiC;CAC/D,IAAI,OAAO,SAAS,eAAe;EACjC,QAAQ,I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e;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
|
|
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;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,OAA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../../../../../../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;;;;
|
|
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;;;;EAoGD,QAAA"}
|
|
@@ -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,c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,IAAI,OAAO,IAAI,iEAAiE,CAAC;EACzF,QAAQ,IAAI,OAAO,IAAI,yDAAyD,CAAC;EACjF,QAAQ,IAAI,EAAE;CAChB;;;;CAKA,AAAO,WAAW;EAChB,IAAI,oBAAoB;EACxB,IAAI,kBAAkB;EACtB,IAAI,gBAAgB;EACpB,IAAI,mBAAmB;EACvB,IAAI,oBAAoB;EAExB,KAAK,MAAM,CAAC,MAAM,SAAS,KAAK,cAAc;GAC5C,qBAAqB,KAAK;GAC1B,IAAI,KAAK,OAAO,iBAAiB;IAC/B,kBAAkB,KAAK;IACvB,oBAAoB;GACtB;EACF;EAEA,KAAK,MAAM,CAAC,MAAM,SAAS,KAAK,YAC9B,IAAI,KAAK,OAAO,eAAe;GAC7B,gBAAgB,KAAK;GACrB,mBAAmB;EACrB;EAGF,OAAO;GACL,YAAY,KAAK,aAAa;GAC9B;GACA,wBAAwB,oBAAoB,KAAK,aAAa,QAAQ;GACtE;GACA;GACA;GACA;EACF;CACF;AACF;;;;;;AAOA,SAAS,cAAc,OAAmD;CACxE,MAAM,QAAQ,MAAM,MAAM,GAAG,EAAE;CAC/B,IAAI,MAAM,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 if (this.isEdgeTypeOnly(from, to)) {\r\n return false;\r\n }\r\n }\r\n\r\n return true;\r\n }\r\n\r\n /**\r\n * Display circular dependency warnings in a formatted, user-friendly way\r\n * Shows each cycle with visual tree structure and helpful recommendations\r\n */\r\n private displayCircularDependencyWarnings(cycles: string[][]): void {\r\n const colors = {\r\n yellow: (text: string) => `\\x1b[33m${text}\\x1b[0m`,\r\n cyan: (text: string) => `\\x1b[36m${text}\\x1b[0m`,\r\n dim: (text: string) => `\\x1b[2m${text}\\x1b[0m`,\r\n bold: (text: string) => `\\x1b[1m${text}\\x1b[0m`,\r\n green: (text: string) => `\\x1b[32m${text}\\x1b[0m`,\r\n };\r\n\r\n console.log(\"\");\r\n console.log(colors.yellow(\"⚠️ Circular Dependencies Detected\"));\r\n console.log(colors.dim(\"━\".repeat(60)));\r\n console.log(\"\");\r\n console.log(\r\n colors.dim(\r\n `Found ${colors.bold(cycles.length.toString())} circular dependency chain${cycles.length > 1 ? \"s\" : \"\"}`,\r\n ),\r\n );\r\n console.log(\"\");\r\n\r\n cycles.forEach((cycle, index) => {\r\n console.log(colors.cyan(` ${index + 1}. Cycle with ${cycle.length - 1} files:`));\r\n console.log(\"\");\r\n\r\n // Display the cycle chain\r\n cycle.forEach((file, fileIndex) => {\r\n const isLast = fileIndex === cycle.length - 1;\r\n const arrow = isLast ? colors.dim(\" └─→ \") : colors.dim(\" ├─→ \");\r\n const fileName = file.split(\"/\").pop() || file;\r\n const filePath = colors.dim(file.replace(fileName, \"\"));\r\n\r\n if (isLast) {\r\n // Last item is the same as first (completes the cycle)\r\n console.log(\r\n arrow + colors.yellow(`${filePath}${colors.bold(fileName)} (cycle completes)`),\r\n );\r\n } else {\r\n console.log(arrow + filePath + colors.bold(fileName));\r\n }\r\n });\r\n\r\n console.log(\"\");\r\n });\r\n\r\n console.log(colors.dim(\"━\".repeat(60)));\r\n console.log(colors.yellow(\"💡 How to Fix:\"));\r\n console.log(\"\");\r\n\r\n const exampleCycle = cycles[0];\r\n const fileA = exampleCycle[0]?.split(\"/\").pop() || \"fileA.ts\";\r\n const fileB = exampleCycle[1]?.split(\"/\").pop() || \"fileB.ts\";\r\n const stripExt = (file: string) => file.replace(/\\.tsx?$/, \"\");\r\n\r\n const kind = classifyCycle(exampleCycle);\r\n\r\n if (kind === \"resource\" || kind === \"model\") {\r\n // Cascade's `lazy()` is purpose-built for circular relations between\r\n // resources and models — recommend it first, not as a footnote.\r\n console.log(colors.green(` ✨ Use lazy() for the back-reference`));\r\n console.log(\r\n colors.dim(\r\n ` ${kind === \"resource\" ? \"Resources\" : \"Models\"} that reference each other should declare`,\r\n ),\r\n );\r\n console.log(colors.dim(` one side with lazy() so the import resolves at access time:`));\r\n console.log(\"\");\r\n console.log(colors.dim(` import { lazy } from \"@warlock.js/cascade\";`));\r\n console.log(colors.dim(` // inside ${fileB}:`));\r\n console.log(\r\n colors.dim(\r\n ` other: lazy(() => ${kind === \"resource\" ? \"OtherResource\" : \"OtherModel\"})`,\r\n ),\r\n );\r\n console.log(\"\");\r\n } else {\r\n // Generic cycle — dynamic import is the most common reliable fix.\r\n console.log(colors.green(` ✨ Convert one edge to a dynamic import`));\r\n console.log(colors.dim(` In ${fileB}, change:`));\r\n console.log(colors.dim(` import { SomeClass } from \"./${stripExt(fileA)}\";`));\r\n console.log(colors.dim(` To:`));\r\n console.log(colors.dim(` const { SomeClass } = await import(\"./${stripExt(fileA)}\");`));\r\n console.log(\"\");\r\n }\r\n\r\n console.log(colors.dim(\" Other options:\"));\r\n console.log(colors.dim(\" • Extract the shared symbols into a third file both can import.\"));\r\n console.log(\r\n colors.dim(\" • Pass the dependency as a constructor/function parameter instead.\"),\r\n );\r\n console.log(\"\");\r\n\r\n console.log(colors.dim(\"━\".repeat(60)));\r\n console.log(colors.dim(\" Circular dependencies can cause HMR issues and hard-to-debug\"));\r\n console.log(colors.dim(\" initialization order problems. Consider refactoring.\"));\r\n console.log(\"\");\r\n }\r\n\r\n /**\r\n * Get statistics about the dependency graph\r\n */\r\n public getStats() {\r\n let totalDependencies = 0;\r\n let maxDependencies = 0;\r\n let maxDependents = 0;\r\n let mostDependedFile = \"\";\r\n let mostDependingFile = \"\";\r\n\r\n for (const [file, deps] of this.dependencies) {\r\n totalDependencies += deps.size;\r\n if (deps.size > maxDependencies) {\r\n maxDependencies = deps.size;\r\n mostDependingFile = file;\r\n }\r\n }\r\n\r\n for (const [file, deps] of this.dependents) {\r\n if (deps.size > maxDependents) {\r\n maxDependents = deps.size;\r\n mostDependedFile = file;\r\n }\r\n }\r\n\r\n return {\r\n totalFiles: this.dependencies.size,\r\n totalDependencies,\r\n avgDependenciesPerFile: totalDependencies / this.dependencies.size || 0,\r\n maxDependencies,\r\n maxDependents,\r\n mostDependingFile,\r\n mostDependedFile,\r\n };\r\n }\r\n}\r\n\r\n/**\r\n * Pick the most useful \"fix-it\" hint for a cycle by inspecting the file\r\n * extensions involved. Cascade resources/models have a first-class fix\r\n * (`lazy()`); generic cycles just want a dynamic import.\r\n */\r\nfunction classifyCycle(cycle: string[]): \"resource\" | \"model\" | \"generic\" {\r\n const files = cycle.slice(0, -1); // last entry repeats the first\r\n if (files.every((file) => file.endsWith(\".resource.ts\") || file.endsWith(\".resource.tsx\"))) {\r\n return \"resource\";\r\n }\r\n if (files.every((file) => file.endsWith(\".model.ts\") || file.endsWith(\".model.tsx\"))) {\r\n return \"model\";\r\n }\r\n return \"generic\";\r\n}\r\n"],"mappings":";;;;;;;;;;;AAYA,IAAa,kBAAb,MAA6B;;sCAMJ,IAAI,IAAkD;oCAOxD,IAAI,IAAyB;eAMD;;;;;CAKjD,AAAO,MAAM,OAAiC;EAC5C,KAAK,QAAQ;EAEb,KAAK,aAAa,MAAM;EACxB,KAAK,WAAW,MAAM;EAEtB,KAAK,MAAM,CAAC,cAAc,gBAAgB,OAAO;GAC/C,IAAI,CAAC,KAAK,aAAa,IAAI,YAAY,GACrC,KAAK,aAAa,IAAI,8BAAc,IAAI,IAAI,CAAC;GAG/C,IAAI,CAAC,KAAK,WAAW,IAAI,YAAY,GACnC,KAAK,WAAW,IAAI,8BAAc,IAAI,IAAI,CAAC;GAG7C,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,CA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A;GACA;GACA;EACF;CACF;AACF;;;;;;AAOA,SAAS,cAAc,OAAmD;CACxE,MAAM,QAAQ,MAAM,MAAM,GAAG,EAAE;CAC/B,IAAI,MAAM,OAAO,SAAS,KAAK,SAAS,cAAc,KAAK,KAAK,SAAS,eAAe,CAAC,GACvF,OAAO;CAET,IAAI,MAAM,OAAO,SAAS,KAAK,SAAS,WAAW,KAAK,KAAK,SAAS,YAAY,CAAC,GACjF,OAAO;CAET,OAAO;AACT"}
|
|
@@ -1 +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,
|
|
1
|
+
{"version":3,"file":"dev-logger.mjs","names":[],"sources":["../../../../../../../core/src/dev-server/dev-logger.ts"],"sourcesContent":["import { colors } from \"@mongez/copper\";\nimport dayjs from \"dayjs\";\nimport { Path } from \"../utils/normalized-path\";\n\n/**\n * Dev server logger — Vite-style formatting helpers.\n */\n\nfunction timestamp(): string {\n return colors.dim(`${dayjs().format(\"HH:mm:ss A\")}`);\n}\n\nexport function devLog(message: string) {\n console.log(`${timestamp()} ${message}`);\n}\n\nexport function devLogSuccess(message: string) {\n console.log(`${timestamp()} ${colors.green(\"✓\")} ${colors.green(message)}`);\n}\n\n/**\n * Colourise a stack trace so the eye lands on *your* code.\n *\n * - Error header (`ReferenceError: x is not defined`) → bold red.\n * - Frames in project `src/` → highlighted: a green `›` pointer, yellow\n * function name, cyan relative path, dim `:line:col`. These are almost\n * always where the bug is.\n * - Framework (`@warlock.js`), `node_modules`, and `node:` internal frames\n * → dimmed and relativised. Still there for context, just out of the way.\n *\n * Source maps are enabled in dev, so the paths/lines here are already the\n * original `.ts` locations — this only changes how they're painted.\n */\nexport function formatErrorStack(stack: string): string {\n const frame = /^(\\s*)at (.+?) \\((.+):(\\d+):(\\d+)\\)$/;\n const bareFrame = /^(\\s*)at (.+):(\\d+):(\\d+)$/;\n let headerDone = false;\n\n return stack\n .split(\"\\n\")\n .map((line) => {\n const withFn = line.match(frame);\n const bare = line.match(bareFrame);\n\n if (!withFn && !bare) {\n // Header line(s) before the first frame.\n const painted = headerDone ? colors.dim(line) : colors.bold(colors.red(line));\n return painted;\n }\n\n headerDone = true;\n\n const fn = withFn ? withFn[2] : \"\";\n const file = withFn ? withFn[3] : bare![2];\n const lineNo = withFn ? withFn[4] : bare![3];\n const col = withFn ? withFn[5] : bare![4];\n\n const isNodeInternal = file.startsWith(\"node:\");\n const isDep = file.includes(\"node_modules\");\n const isFramework = /[\\\\/]@warlock\\.js[\\\\/]/.test(file);\n const isUserCode = !isNodeInternal && !isDep && !isFramework;\n\n const rel = isNodeInternal ? file : Path.toRelative(file);\n const loc = `:${lineNo}:${col}`;\n\n if (isUserCode) {\n return (\n ` ${colors.green(\"›\")} ${colors.dim(\"at\")} ` +\n `${colors.yellow(fn || \"<anonymous>\")} ` +\n `${colors.cyan(rel)}${colors.dim(loc)}`\n );\n }\n\n const label = fn ? `at ${fn} ${rel}${loc}` : `at ${rel}${loc}`;\n return ` ${colors.dim(label)}`;\n })\n .join(\"\\n\");\n}\n\nexport function devLogError(message: string, error?: any) {\n console.log(`${timestamp()} ${colors.red(\"✗\")} ${colors.red(message)}`);\n if (error?.stack) console.log(formatErrorStack(error.stack));\n}\n\nexport function devLogWarn(message: string) {\n console.log(`${timestamp()} ${colors.yellow(\"⚠\")} ${colors.yellow(message)}`);\n}\n\nexport function devLogInfo(message: string) {\n console.log(`${timestamp()} ${colors.cyan(message)}`);\n}\n\nexport function devLogDim(message: string) {\n console.log(`${timestamp()} ${colors.dim(message)}`);\n}\n\nexport function devLogHMR(file: string, dependents?: number) {\n const relativePath = Path.toRelative(file);\n const depInfo = dependents\n ? colors.dim(` +${dependents} module${dependents > 1 ? \"s\" : \"\"}`)\n : \"\";\n console.log(\n `${timestamp()} 🔥 ${colors.green(\"hmr update\")} ${colors.dim(relativePath)}${depInfo}`,\n );\n}\n\nexport function devLogConfig(file: string, connectors?: string[]) {\n const relativePath = Path.toRelative(file);\n const connectorInfo =\n connectors && connectors.length > 0 ? colors.dim(` → restarting ${connectors.join(\", \")}`) : \"\";\n console.log(\n `${timestamp()} ${colors.cyan(\"config reload\")} ${colors.dim(relativePath)}${connectorInfo}`,\n );\n}\n\nexport function devLogReady(message: string) {\n console.log(`\\n${timestamp()} ${colors.green(\"➜\")} ${colors.bold(message)}`);\n}\n\nexport function devLogSection(title: string) {\n console.log(`\\n${timestamp()} ${colors.bold(colors.cyan(title))}`);\n}\n\n/**\n * Format ERR_MODULE_NOT_FOUND so the displayed paths are relative to the\n * project root. The loader hook keeps source paths in the URL so we only\n * need to strip the absolute prefix — no cache-path translation any more.\n */\nexport function formatModuleNotFoundError(error: Error, suggestions?: string[]): string {\n const match = error.message.match(/Cannot find module '([^']+)' imported from '([^']+)'/);\n if (!match) return error.message;\n\n const [, modulePath, importerPath] = match;\n const lines: string[] = [\n \"\",\n `${colors.red(\"❌ MODULE NOT FOUND\")}`,\n \"\",\n `${colors.dim(\"Cannot find:\")} ${colors.cyan(Path.toRelative(modulePath))}`,\n \"\",\n `${colors.dim(\"Imported by:\")}`,\n ` ${colors.yellow(\"→\")} ${colors.white(Path.toRelative(importerPath))}`,\n ];\n\n if (suggestions && suggestions.length > 0) {\n lines.push(\"\");\n lines.push(`${colors.dim(\"Did you mean?\")}`);\n suggestions.forEach((s) => lines.push(` ${colors.cyan(\"→\")} ${colors.green(s)}`));\n }\n\n lines.push(\"\");\n return lines.join(\"\\n\");\n}\n\n/** @deprecated alias retained for older callers. Use `devLog` directly. */\nexport const devServeLog = devLog;\n"],"mappings":";;;;;;;;AAQA,SAAS,YAAoB;CAC3B,OAAO,OAAO,IAAI,GAAG,MAAM,CAAC,CAAC,OAAO,YAAY,GAAG;AACrD;AAEA,SAAgB,OAAO,SAAiB;CACtC,QAAQ,IAAI,GAAG,UAAU,EAAE,GAAG,SAAS;AACzC;AAEA,SAAgB,cAAc,SAAiB;CAC7C,QAAQ,IAAI,GAAG,UAAU,EAAE,GAAG,OAAO,MAAM,GAAG,EAAE,GAAG,OAAO,MAAM,OAAO,GAAG;AAC5E;;;;;;;;;;;;;;AAeA,SAAgB,iBAAiB,OAAuB;CACtD,MAAM,QAAQ;CACd,MAAM,YAAY;CAClB,IAAI,aAAa;CAEjB,OAAO,MACJ,MAAM,IAAI,CAAC,CACX,KAAK,SAAS;EACb,MAAM,SAAS,KAAK,MAAM,KAAK;EAC/B,MAAM,OA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M,KAAK,IAAI;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,QAAQ,OAAO,cAAc;EACrD,MAAM,cAAc,QAAQ,
|
|
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,KAA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AM,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"}
|
|
@@ -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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AK,aAAa,aAAa,IAAI;EAC3E,KAAK,MAAM,QAAQ,gBAAgB,MAAM,KAAK,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
|
+
{"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,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AAO,IAAI;GAC/B,YAAY,KAAK,KAAK,YAAY;EACpC;EAIA,KAAK,MAAM,QAAQ,iBAAiB,MAAM,KAAK,aAAa,aAAa,IAAI;EAC7E,KAAK,MAAM,QAAQ,eAAe,MAAM,KAAK,aAAa,aAAa,IAAI;EAC3E,KAAK,MAAM,QAAQ,gBAAgB,MAAM,KAAK,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(
|
|
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
|
|
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"}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"register-loader.mjs","names":[],"sources":["../../../../../../../../core/src/dev-server/loader/register-loader.ts"],"sourcesContent":["import { putFileAsync } from \"@warlock.js/fs\";\nimport { build, type Plugin } from \"esbuild\";\nimport { register } from \"node:module\";\nimport path from \"node:path\";\nimport { fileURLToPath, pathToFileURL } from \"node:url\";\nimport { type MessagePort, MessageChannel } from \"node:worker_threads\";\nimport type { TranspileInit } from \"./load-hook.js\";\n\n/**\n * Rewrite the hook bundle's remaining npm imports to absolute paths resolved\n * from **core's own** location.\n *\n * The bundle is written into the consuming app's `.warlock/` directory, so a\n * bare `import \"esbuild\"` in it resolves starting from the *app*, walking up\n * the app's `node_modules`. `esbuild` and `get-tsconfig` are core's\n * dependencies, not the app's — under npm/yarn's flat hoisting they happen to\n * be reachable anyway, but under pnpm's strict layout they are not, and the\n * dev server dies with `ERR_MODULE_NOT_FOUND` for a package the app never\n * imported. That is a phantom dependency baked into generated code.\n *\n * Bundling them in instead is not an option for `esbuild`: its JS API is a\n * thin wrapper that spawns a platform-specific native binary, so inlining the\n * JavaScript would not remove the need for the package on disk. Resolving to\n * an absolute `file://` URL at generation time does — the generated file then\n * points straight at the copy core itself is using, whatever the installer's\n * layout.\n */\nexport const resolveExternalsFromCore: Plugin = {\n name: \"warlock-resolve-externals-from-core\",\n setup(build) {\n // The filter is deliberately loose — anything not starting `.` or `/` —\n // so the guards below carry the real logic.\n build.onResolve({ filter: /^[^./]/ }, args => {\n // The entry point comes through here too, and on Windows its absolute\n // path (\"D:\\\\…\") is not `.` or `/`. Marking it external fails the build.\n if (args.kind === \"entry-point\" || path.isAbsolute(args.path)) {\n return null;\n }\n\n if (args.path.startsWith(\"node:\")) {\n return { external: true };\n }\n\n try {\n return { path: import.meta.resolve(args.path), external: true };\n } catch {\n // Unresolvable from here — leave it bare and let Node try, which is\n // exactly the previous behaviour rather than a hard failure.\n return { external: true };\n }\n });\n },\n};\n\n/**\n * Bundle, write, and register the ESM loader hook.\n *\n * **Why bundle?**\n * `module.register()` runs the hook file in a fresh Node.js worker thread that\n * has no tsx hook of its own. The hook source is TypeScript, so we must produce\n * a plain ESM bundle before registering. esbuild inline-bundles all three hook\n * modules (`hook-thread`, `resolve-hook`, `load-hook`, `version-registry`)\n * into a single `.mjs` file written to `.warlock/`. External npm packages\n * (`esbuild`, `node:*`) are kept external — the hook thread can resolve those\n * from `node_modules` normally.\n *\n * **Why a file and not a `data:` URL?**\n * Some Node versions have issues resolving `import.meta.url` inside `data:`\n * modules. A real file under `.warlock/` is simpler and debuggable.\n *\n * **Timing**\n * Called from `FilesOrchestrator.init()` before any user `src/` module is\n * dynamically imported. `module.register()` takes effect for all subsequent\n * `import()` calls, which is exactly the window we need.\n *\n * @param transpile - Transpile-cache config to ship into the hook worker,\n * or `null` to keep the hook in tsx-passthrough mode.\n *\n * @returns The main-thread side of the MessageChannel. Callers post\n * `{ type: \"bump\", absolutePath }` messages on it to invalidate modules.\n *\n * @example\n * const port = await registerLoader(transpileInit);\n * // Later, when a file changes:\n * port.postMessage({ type: \"bump\", absolutePath: \"/abs/path/to/user.model.ts\" });\n */\nexport async function registerLoader(
|
|
1
|
+
{"version":3,"file":"register-loader.mjs","names":[],"sources":["../../../../../../../../core/src/dev-server/loader/register-loader.ts"],"sourcesContent":["import { putFileAsync } from \"@warlock.js/fs\";\nimport { build, type Plugin } from \"esbuild\";\nimport { register } from \"node:module\";\nimport path from \"node:path\";\nimport { fileURLToPath, pathToFileURL } from \"node:url\";\nimport { type MessagePort, MessageChannel } from \"node:worker_threads\";\nimport type { TranspileInit } from \"./load-hook.js\";\n\n/**\n * Rewrite the hook bundle's remaining npm imports to absolute paths resolved\n * from **core's own** location.\n *\n * The bundle is written into the consuming app's `.warlock/` directory, so a\n * bare `import \"esbuild\"` in it resolves starting from the *app*, walking up\n * the app's `node_modules`. `esbuild` and `get-tsconfig` are core's\n * dependencies, not the app's — under npm/yarn's flat hoisting they happen to\n * be reachable anyway, but under pnpm's strict layout they are not, and the\n * dev server dies with `ERR_MODULE_NOT_FOUND` for a package the app never\n * imported. That is a phantom dependency baked into generated code.\n *\n * Bundling them in instead is not an option for `esbuild`: its JS API is a\n * thin wrapper that spawns a platform-specific native binary, so inlining the\n * JavaScript would not remove the need for the package on disk. Resolving to\n * an absolute `file://` URL at generation time does — the generated file then\n * points straight at the copy core itself is using, whatever the installer's\n * layout.\n */\nexport const resolveExternalsFromCore: Plugin = {\n name: \"warlock-resolve-externals-from-core\",\n setup(build) {\n // The filter is deliberately loose — anything not starting `.` or `/` —\n // so the guards below carry the real logic.\n build.onResolve({ filter: /^[^./]/ }, (args) => {\n // The entry point comes through here too, and on Windows its absolute\n // path (\"D:\\\\…\") is not `.` or `/`. Marking it external fails the build.\n if (args.kind === \"entry-point\" || path.isAbsolute(args.path)) {\n return null;\n }\n\n if (args.path.startsWith(\"node:\")) {\n return { external: true };\n }\n\n try {\n return { path: import.meta.resolve(args.path), external: true };\n } catch {\n // Unresolvable from here — leave it bare and let Node try, which is\n // exactly the previous behaviour rather than a hard failure.\n return { external: true };\n }\n });\n },\n};\n\n/**\n * Bundle, write, and register the ESM loader hook.\n *\n * **Why bundle?**\n * `module.register()` runs the hook file in a fresh Node.js worker thread that\n * has no tsx hook of its own. The hook source is TypeScript, so we must produce\n * a plain ESM bundle before registering. esbuild inline-bundles all three hook\n * modules (`hook-thread`, `resolve-hook`, `load-hook`, `version-registry`)\n * into a single `.mjs` file written to `.warlock/`. External npm packages\n * (`esbuild`, `node:*`) are kept external — the hook thread can resolve those\n * from `node_modules` normally.\n *\n * **Why a file and not a `data:` URL?**\n * Some Node versions have issues resolving `import.meta.url` inside `data:`\n * modules. A real file under `.warlock/` is simpler and debuggable.\n *\n * **Timing**\n * Called from `FilesOrchestrator.init()` before any user `src/` module is\n * dynamically imported. `module.register()` takes effect for all subsequent\n * `import()` calls, which is exactly the window we need.\n *\n * @param transpile - Transpile-cache config to ship into the hook worker,\n * or `null` to keep the hook in tsx-passthrough mode.\n *\n * @returns The main-thread side of the MessageChannel. Callers post\n * `{ type: \"bump\", absolutePath }` messages on it to invalidate modules.\n *\n * @example\n * const port = await registerLoader(transpileInit);\n * // Later, when a file changes:\n * port.postMessage({ type: \"bump\", absolutePath: \"/abs/path/to/user.model.ts\" });\n */\nexport async function registerLoader(transpile: TranspileInit): Promise<MessagePort> {\n const { port1, port2 } = new MessageChannel();\n\n // hook-thread is a sibling module, so it shares THIS file's extension:\n // `.ts` when core runs from source (tsx), `.mjs` when published.\n const selfPath = fileURLToPath(import.meta.url);\n const hookThreadPath = path.join(path.dirname(selfPath), `hook-thread${path.extname(selfPath)}`);\n\n const bundleResult = await build({\n entryPoints: [hookThreadPath],\n bundle: true,\n format: \"esm\",\n write: false,\n platform: \"node\",\n target: \"node20\",\n // npm packages and Node built-ins stay external, but the plugin rewrites\n // each remaining npm specifier to an absolute path resolved from core's\n // own install — see `resolveExternalsFromCore` for why bare imports break\n // under pnpm's strict layout.\n packages: \"external\",\n plugins: [resolveExternalsFromCore],\n });\n\n const bundledCode = bundleResult.outputFiles[0].text;\n // Caller (filesOrchestrator.init) guarantees .warlock/ exists before this runs.\n const hookBundlePath = path.join(process.cwd(), \".warlock\", \"loader-hook.mjs\");\n await putFileAsync(hookBundlePath, bundledCode);\n\n const srcRoot = path.join(process.cwd(), \"src\");\n\n // No tsx registration: our hook owns resolution (own-resolver) and the\n // transpile of every `.ts`/`.tsx` (esbuild, in the load hook). The chain\n // is simply [our hook] → [Node default] for non-TS (npm/.js, node:).\n // In this monorepo tsx is still the *launcher* (`tsx start.ts`) so its\n // loader is present anyway, but it is never consulted for TypeScript —\n // our hook short-circuits first. A released `node bin/warlock.js` has no\n // tsx at all and relies entirely on this hook.\n\n register(pathToFileURL(hookBundlePath).href, import.meta.url, {\n data: { port: port2, srcRoot, transpile },\n transferList: [port2],\n });\n\n return port1;\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;AA2BA,MAAa,2BAAmC;CAC9C,MAAM;CACN,MAAM,OAAO;EAGX,MAAM,UAAU,EAAE,QAAQ,SAAS,IAAI,SAAS;GAG9C,IAAI,KAAK,SAAS,iBAAiB,KAAK,WAAW,KAAK,IAAI,GAC1D,OAAO;GAGT,IAAI,KAAK,KAAK,WAAW,OAAO,GAC9B,OAAO,EAAE,UAAU,KAAK;GAG1B,IAAI;IACF,OAAO;KAAE,MAAM,OAAO,KAAK,QAAQ,KAAK,IAAI;KAAG,UAAU;IAAK;GAChE,QAAQ;IAGN,OAAO,EAAE,UAAU,KAAK;GAC1B;EACF,CAAC;CACH;AACF;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAkCA,eAAsB,eAAe,WAAgD;CACnF,MAAM,EAAE,OAAO,UAAU,IAAI,eAAe;CAI5C,MAAM,WAAW,cAAc,OAAO,KAAK,GAAG;CAkB9C,MAAM,eAAc,MAfO,MAAM;EAC/B,aAAa,CAHQ,KAAK,KAAK,KAAK,QAAQ,QAAQ,GAAG,cAAc,KAAK,QAAQ,QAAQ,GAG/D,CAAC;EAC5B,QAAQ;EACR,QAAQ;EACR,OAAO;EACP,UAAU;EACV,QAAQ;EAKR,UAAU;EACV,SAAS,CAAC,wBAAwB;CACpC,CAAC,EAE+B,CAAC,YAAY,EAAE,CAAC;CAEhD,MAAM,iBAAiB,KAAK,KAAK,QAAQ,IAAI,GAAG,YAAY,iBAAiB;CAC7E,MAAM,aAAa,gBAAgB,WAAW;CAE9C,MAAM,UAAU,KAAK,KAAK,QAAQ,IAAI,GAAG,KAAK;CAU9C,SAAS,cAAc,cAAc,CAAC,CAAC,MAAM,OAAO,KAAK,KAAK;EAC5D,MAAM;GAAE,MAAM;GAAO;GAAS;EAAU;EACxC,cAAc,CAAC,KAAK;CACtB,CAAC;CAED,OAAO;AACT"}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"resolve-hook.mjs","names":[],"sources":["../../../../../../../../core/src/dev-server/loader/resolve-hook.ts"],"sourcesContent":["import { getTsconfig, resolvePathAlias } from \"get-tsconfig\";\nimport { existsSync } from \"node:fs\";\nimport { fileURLToPath, pathToFileURL } from \"node:url\";\nimport { ownResolve, type PathsMatcher } from \"./own-resolver.js\";\nimport { captureResolution } from \"./resolve-capture.js\";\nimport { getVersion } from \"./version-registry.js\";\n\n/**\n * The `file://` URL prefix for the project's `src/` root, set once during\n * `initialize()`. Used to identify which resolved URLs belong to user code.\n */\nlet srcRootUrl = \"\";\n\n/**\n * Configure the source root used by the resolve hook.\n * Must be called from `initialize()` before any imports are resolved.\n *\n * @param srcRoot - Absolute filesystem path to the project `src/` directory.\n */\nexport function setSrcRoot(srcRoot: string): void {\n srcRootUrl = pathToFileURL(srcRoot).href + \"/\";\n}\n\n/** Lazily-built tsconfig `paths` matcher (worker has no startup hook). */\nlet pathsMatcher: PathsMatcher | null = null;\nlet pathsMatcherBuilt = false;\n\nfunction getPathsMatcher(): PathsMatcher | null {\n if (pathsMatcherBuilt) return pathsMatcher;\n pathsMatcherBuilt = true;\n const tsconfig = getTsconfig(process.cwd());\n // get-tsconfig v5 renamed the curried `createPathsMatcher(t)(spec)` to a direct\n // `resolvePathAlias(t, spec)`. Wrap it to keep the PathsMatcher closure shape.\n pathsMatcher = tsconfig ? (specifier: string) => resolvePathAlias(tsconfig, specifier) : null;\n return pathsMatcher;\n}\n\ntype ResolveContext = {\n parentURL?: string;\n conditions?: string[];\n importAttributes?: Record<string, string>;\n};\n\ntype ResolveResult = {\n url: string;\n format?: string;\n shortCircuit?: boolean;\n};\n\ntype NextResolve = (specifier: string, context?: ResolveContext) => Promise<ResolveResult>;\n\n/**\n * ESM loader `resolve()` hook.\n *\n * The framework's own resolver (`ownResolve`) handles tsconfig `paths`,\n * aliases, and TS extension/`index` probing. Specifiers it doesn't own\n * (bare npm, `node:`, `file:`) fall through to `nextResolve` (Node\n * default). After resolution, stamps a `?v=<N>` version token onto any\n * `.ts` / `.tsx` file that lives under the configured `src/` root.\n *\n * The version token is the cache-bust mechanism: when a file changes the main\n * thread bumps its counter, the next `import()` produces a new URL, Node sees\n * a cache miss, and loads fresh content — native ESM cycles are preserved\n * because static imports remain static throughout.\n *\n * **parentURL cleaning**: the resolved URL carries `?v=N` as a suffix. If a\n * module loaded this way statically imports a relative sibling, Node uses that\n * `?v=N` URL as the `parentURL` for the next `resolve()` call. Passing it\n * unmodified to `nextResolve()` causes tsx to produce paths like\n * `some-sibling.ts?v=0` (the query leaks into URL joining). We strip `?v=N`\n * from `parentURL` before forwarding to prevent this.\n *\n * @example\n * // First import of user.model.ts → ?v=0\n * // File watcher bumps → next import → ?v=1 → fresh module\n */\nexport async function resolve(\n specifier: string,\n context: ResolveContext,\n nextResolve: NextResolve,\n): Promise<ResolveResult> {\n const cleanContext
|
|
1
|
+
{"version":3,"file":"resolve-hook.mjs","names":[],"sources":["../../../../../../../../core/src/dev-server/loader/resolve-hook.ts"],"sourcesContent":["import { getTsconfig, resolvePathAlias } from \"get-tsconfig\";\nimport { existsSync } from \"node:fs\";\nimport { fileURLToPath, pathToFileURL } from \"node:url\";\nimport { ownResolve, type PathsMatcher } from \"./own-resolver.js\";\nimport { captureResolution } from \"./resolve-capture.js\";\nimport { getVersion } from \"./version-registry.js\";\n\n/**\n * The `file://` URL prefix for the project's `src/` root, set once during\n * `initialize()`. Used to identify which resolved URLs belong to user code.\n */\nlet srcRootUrl = \"\";\n\n/**\n * Configure the source root used by the resolve hook.\n * Must be called from `initialize()` before any imports are resolved.\n *\n * @param srcRoot - Absolute filesystem path to the project `src/` directory.\n */\nexport function setSrcRoot(srcRoot: string): void {\n srcRootUrl = pathToFileURL(srcRoot).href + \"/\";\n}\n\n/** Lazily-built tsconfig `paths` matcher (worker has no startup hook). */\nlet pathsMatcher: PathsMatcher | null = null;\nlet pathsMatcherBuilt = false;\n\nfunction getPathsMatcher(): PathsMatcher | null {\n if (pathsMatcherBuilt) return pathsMatcher;\n pathsMatcherBuilt = true;\n const tsconfig = getTsconfig(process.cwd());\n // get-tsconfig v5 renamed the curried `createPathsMatcher(t)(spec)` to a direct\n // `resolvePathAlias(t, spec)`. Wrap it to keep the PathsMatcher closure shape.\n pathsMatcher = tsconfig ? (specifier: string) => resolvePathAlias(tsconfig, specifier) : null;\n return pathsMatcher;\n}\n\ntype ResolveContext = {\n parentURL?: string;\n conditions?: string[];\n importAttributes?: Record<string, string>;\n};\n\ntype ResolveResult = {\n url: string;\n format?: string;\n shortCircuit?: boolean;\n};\n\ntype NextResolve = (specifier: string, context?: ResolveContext) => Promise<ResolveResult>;\n\n/**\n * ESM loader `resolve()` hook.\n *\n * The framework's own resolver (`ownResolve`) handles tsconfig `paths`,\n * aliases, and TS extension/`index` probing. Specifiers it doesn't own\n * (bare npm, `node:`, `file:`) fall through to `nextResolve` (Node\n * default). After resolution, stamps a `?v=<N>` version token onto any\n * `.ts` / `.tsx` file that lives under the configured `src/` root.\n *\n * The version token is the cache-bust mechanism: when a file changes the main\n * thread bumps its counter, the next `import()` produces a new URL, Node sees\n * a cache miss, and loads fresh content — native ESM cycles are preserved\n * because static imports remain static throughout.\n *\n * **parentURL cleaning**: the resolved URL carries `?v=N` as a suffix. If a\n * module loaded this way statically imports a relative sibling, Node uses that\n * `?v=N` URL as the `parentURL` for the next `resolve()` call. Passing it\n * unmodified to `nextResolve()` causes tsx to produce paths like\n * `some-sibling.ts?v=0` (the query leaks into URL joining). We strip `?v=N`\n * from `parentURL` before forwarding to prevent this.\n *\n * @example\n * // First import of user.model.ts → ?v=0\n * // File watcher bumps → next import → ?v=1 → fresh module\n */\nexport async function resolve(\n specifier: string,\n context: ResolveContext,\n nextResolve: NextResolve,\n): Promise<ResolveResult> {\n const cleanContext = context.parentURL?.includes(\"?v=\")\n ? { ...context, parentURL: context.parentURL.replace(/\\?v=\\d+$/, \"\") }\n : context;\n\n // The framework's own resolver owns tsconfig `paths` + TS\n // extension/index probing. Anything it returns `null` for (bare npm,\n // `node:`, `file:`) falls through to Node default via `nextResolve`.\n const owned = ownResolve(specifier, cleanContext.parentURL, getPathsMatcher(), existsSync);\n // When we produced the URL ourselves we did NOT call nextResolve, so the\n // result must short-circuit the loader chain or Node throws\n // ERR_LOADER_CHAIN_INCOMPLETE (e.g. for @warlock.js/* .ts that resolve\n // outside the project src root and hit the early return below).\n const result: ResolveResult = owned\n ? { url: owned, shortCircuit: true }\n : await nextResolve(specifier, cleanContext);\n\n const { url } = result;\n\n // Ground-truth recorder (no-op unless WARLOCK_RESOLVE_CAPTURE is set):\n // logs the answer for this (specifier, parentURL) so the Phase B\n // resolver can be proven to reproduce tsx exactly.\n captureResolution({\n specifier,\n parentURL: cleanContext.parentURL,\n url,\n format: result.format,\n });\n\n const cleanUrl = url.replace(/\\?v=\\d+$/, \"\");\n\n if (\n !cleanUrl.startsWith(srcRootUrl) ||\n (!cleanUrl.endsWith(\".ts\") && !cleanUrl.endsWith(\".tsx\"))\n ) {\n return result;\n }\n\n const absolutePath = fileURLToPath(cleanUrl);\n const version = getVersion(absolutePath);\n\n // Spread the full result from nextResolve (preserves `format` and any other\n // fields tsx sets) and only override `url`. Dropping `format` would cause\n // tsx's load hook to see an undefined format and fall through to Node's\n // default loader, which rejects unknown extensions like .tsx.\n return { ...result, url: `${cleanUrl}?v=${version}`, shortCircuit: true };\n}\n"],"mappings":";;;;;;;;;;;;AAWA,IAAI,aAAa;;;;;;;AAQjB,SAAgB,WAAW,SAAuB;CAChD,aAAa,cAAc,OAAO,CAAC,CAAC,OAAO;AAC7C;;AAGA,IAAI,eAAoC;AACxC,IAAI,oBAAoB;AAExB,SAAS,kBAAuC;CAC9C,IAAI,mBAAmB,OAAO;CAC9B,oBAAoB;CACpB,MAAM,WAAW,YAAY,QAAQ,IAAI,CAAC;CAG1C,eAAe,YAAY,cAAsB,iBAAiB,UAAU,SAAS,IAAI;CACzF,OAAO;AACT;;;;;;;;;;;;;;;;;;;;;;;;;;AAyCA,eAAsB,QACpB,WACA,SACA,aACwB;CACxB,MAAM,eAAe,QAAQ,WAAW,SAAS,KAAK,IAClD;EAAE,GAAG;EAAS,WAAW,QAAQ,UAAU,QAAQ,YAAY,EAAE;CAAE,IACnE;CAKJ,MAAM,QAAQ,WAAW,WAAW,aAAa,WAAW,gBAAgB,GAAG,UAAU;CAKzF,MAAM,SAAwB,QAC1B;EAAE,KAAK;EAAO,cAAc;CAAK,IACjC,MAAM,YAAY,WAAW,YAAY;CAE7C,MAAM,EAAE,QAAQ;CAKhB,kBAAkB;EAChB;EACA,WAAW,aAAa;EACxB;EACA,QAAQ,OAAO;CACjB,CAAC;CAED,MAAM,WAAW,IAAI,QAAQ,YAAY,EAAE;CAE3C,IACE,CAAC,SAAS,WAAW,UAAU,KAC9B,CAAC,SAAS,SAAS,KAAK,KAAK,CAAC,SAAS,SAAS,MAAM,GAEvD,OAAO;CAIT,MAAM,UAAU,WADK,cAAc,QACG,CAAC;CAMvC,OAAO;EAAE,GAAG;EAAQ,KAAK,GAAG,SAAS,KAAK;EAAW,cAAc;CAAK;AAC1E"}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"transpile-cache.mjs","names":[],"sources":["../../../../../../../../core/src/dev-server/loader/transpile-cache.ts"],"sourcesContent":["/**\n * Persisted transpile cache.\n *\n * Keyed by a hash of *source content* plus a transform-options fingerprint.\n * Same source + same options → same key → same output, always. Changed\n * content → different key → fresh transpile. There is no path-keyed entry\n * anywhere, so the old \"stack trace points at a mangled cache filename\" bug\n * class is structurally impossible — the on-disk filename is opaque and the\n * source identity lives only inside the source map.\n *\n * This module is pure and hook-agnostic on purpose: it knows how to read,\n * write and evict cache entries given a key, nothing about the ESM loader,\n * `?v=N` versioning, or esbuild. Phase 2 wires it into the load hook.\n *\n * @example\n * const fp = computeFingerprint({\n * esbuildVersion: esbuild.version,\n * cacheEpoch: CACHE_EPOCH,\n * compilerOptions,\n * });\n * const key = cacheKey(sourceText, fp);\n * const hit = cache.get(key);\n * if (!hit) cache.put(key, { code, map });\n */\n\nimport { createHash, randomUUID } from \"node:crypto\";\nimport {\n mkdirSync,\n readdirSync,\n readFileSync,\n renameSync,\n rmSync,\n statSync,\n writeFileSync,\n} from \"node:fs\";\nimport path from \"node:path\";\n\n/**\n * A cached transpile result: the emitted JS and its source map (raw JSON\n * string, exactly as esbuild produced it). Either may be empty for code\n * that produced no map.\n */\nexport type TranspileEntry = {\n code: string;\n map: string;\n};\n\n/**\n * Inputs that change transpiled output for identical source text. Bumping\n * any of these must invalidate every entry — that is achieved structurally\n * by folding them into the key, not by sweeping the cache.\n */\nexport type FingerprintParts = {\n /** `esbuild.version` — a transform-engine upgrade can change output. */\n esbuildVersion: string;\n /**\n * Monotonic cache-format epoch owned by the framework. Bump it whenever\n * the cache contract (entry shape, map handling, key derivation) changes\n * so old entries are guaranteed to miss after a framework upgrade.\n */\n cacheEpoch: number;\n /**\n * The resolved tsconfig `compilerOptions` blob, hashed wholesale rather\n * than cherry-picking fields — safer against tsconfig drift (a new option\n * that affects output can't silently serve stale code).\n */\n compilerOptions: unknown;\n};\n\n/**\n * Current cache-format epoch. Bump on any change to {@link TranspileEntry}\n * shape, the storage layout, or how the loader consumes entries.\n */\nexport const CACHE_EPOCH = 1;\n\n/**\n * Stable JSON stringify — object keys sorted recursively so semantically\n * equal option blobs always produce the same fingerprint regardless of key\n * insertion order.\n */\nfunction stableStringify(value: unknown): string {\n if (value === null || typeof value !== \"object\") {\n return JSON.stringify(value) ?? \"null\";\n }\n\n if (Array.isArray(value)) {\n return `[${value.map(stableStringify).join(\",\")}]`;\n }\n\n const entries = Object.keys(value as Record<string, unknown>)\n .sort()\n .map(key => {\n const child = stableStringify((value as Record<string, unknown>)[key]);\n return `${JSON.stringify(key)}:${child}`;\n });\n\n return `{${entries.join(\",\")}}`;\n}\n\n/**\n * Fold every output-affecting input into one short hex fingerprint that\n * becomes part of every cache key.\n */\nexport function computeFingerprint(parts: FingerprintParts): string {\n const canonical = stableStringify({\n esbuildVersion: parts.esbuildVersion,\n cacheEpoch: parts.cacheEpoch,\n compilerOptions: parts.compilerOptions,\n });\n\n return createHash(\"sha256\").update(canonical).digest(\"hex\").slice(0, 16);\n}\n\n/**\n * Derive the cache key for a source file. The NUL separator makes\n * `sourceText` and `fingerprint` unambiguous (no concatenation collision).\n */\nexport function cacheKey(sourceText: string, fingerprint: string): string {\n return createHash(\"sha256\")\n .update(sourceText)\n .update(\"\\0\")\n .update(fingerprint)\n .digest(\"hex\");\n}\n\n/** Options for {@link TranspileCache.gc}. */\nexport type GcOptions = {\n /** Evict least-recently-modified entries once total size exceeds this. */\n maxBytes?: number;\n /** Evict entries whose mtime is older than this many milliseconds. */\n maxAgeMs?: number;\n};\n\ntype CacheFileInfo = {\n codePath: string;\n mapPath: string;\n size: number;\n mtimeMs: number;\n};\n\n/**\n * Content-hash-addressed transpile cache stored on disk.\n *\n * Layout: `<cacheDir>/<first2-of-key>/<key>.js` plus a sibling `.js.map`.\n * Sharding by the first two hex chars keeps any single directory small on\n * large projects. GC metadata is derived from filesystem mtime so there is\n * no second source of truth (no sidecar index to keep consistent).\n */\nexport class TranspileCache {\n public constructor(private readonly cacheDir: string) {}\n\n private shardDir(key: string): string {\n return path.join(this.cacheDir, key.slice(0, 2));\n }\n\n /**\n * `label` is an optional human-readable prefix (e.g. a path slug). It is\n * cosmetic only — the content `key` is still what makes the name unique,\n * so the same `(key, label)` pair must be passed to `get` and `put`.\n */\n private fileName(key: string, label: string | undefined, ext: string): string {\n return label ? `${label}.${key}${ext}` : `${key}${ext}`;\n }\n\n private codePath(key: string, label?: string): string {\n return path.join(this.shardDir(key), this.fileName(key, label, \".js\"));\n }\n\n private mapPath(key: string, label?: string): string {\n return path.join(this.shardDir(key), this.fileName(key, label, \".js.map\"));\n }\n\n /**\n * Return the cached entry for `key`, or `null` on a miss. Synchronous on\n * purpose: this sits on the module-load hot path and must not pay an\n * event-loop hop per import.\n */\n public get(key: string, label?: string): TranspileEntry | null {\n try {\n const code = readFileSync(this.codePath(key, label), \"utf8\");\n let map = \"\";\n try {\n map = readFileSync(this.mapPath(key, label), \"utf8\");\n } catch {\n // A code entry with no map is valid (e.g. map-less transform).\n }\n return { code, map };\n } catch {\n return null;\n }\n }\n\n /**\n * Store an entry for `key`. Written atomically (temp file + rename) so a\n * concurrent {@link get} never observes a half-written module.\n */\n public put(key: string, entry: TranspileEntry, label?: string): void {\n const shard = this.shardDir(key);\n mkdirSync(shard, { recursive: true });\n\n this.atomicWrite(this.codePath(key, label), entry.code);\n if (entry.map) {\n this.atomicWrite(this.mapPath(key, label), entry.map);\n }\n }\n\n private atomicWrite(filePath: string, content: string): void {\n const tempPath = `${filePath}.${process.pid}.${randomUUID()}.tmp`;\n try {\n writeFileSync(tempPath, content);\n renameSync(tempPath, filePath);\n } catch (error) {\n // Windows can report EPERM/EACCES when another loader process wins the\n // rename to this content-addressed destination. The winner's file is a\n // valid commit only when it contains the exact bytes we meant to store;\n // otherwise preserve the original error instead of accepting corruption.\n const code = (error as NodeJS.ErrnoException).code;\n const mayBeConcurrentCommit =\n code === \"EEXIST\" || code === \"EPERM\" || code === \"EACCES\";\n\n if (!mayBeConcurrentCommit || !this.hasCommittedContent(filePath, content)) {\n throw error;\n }\n } finally {\n try {\n rmSync(tempPath, { force: true });\n } catch {\n // Best effort: a cleanup failure must not mask the rename result.\n }\n }\n }\n\n private hasCommittedContent(filePath: string, content: string): boolean {\n try {\n return readFileSync(filePath, \"utf8\") === content;\n } catch {\n return false;\n }\n }\n\n /**\n * Opportunistic eviction. Cheap, runs at boot (not on the hot path).\n * Removes age-expired entries first, then trims to the size budget by\n * evicting least-recently-modified entries. Both bounds are optional;\n * with neither set this is a no-op.\n */\n public gc(options: GcOptions = {}): void {\n const { maxBytes, maxAgeMs } = options;\n if (maxBytes === undefined && maxAgeMs === undefined) return;\n\n const files = this.scan();\n const now = Date.now();\n\n let live = files;\n\n if (maxAgeMs !== undefined) {\n live = [];\n for (const file of files) {\n if (now - file.mtimeMs > maxAgeMs) {\n this.evict(file);\n } else {\n live.push(file);\n }\n }\n }\n\n if (maxBytes !== undefined) {\n let total = live.reduce((sum, file) => sum + file.size, 0);\n if (total > maxBytes) {\n // Oldest first — least-recently-modified is the eviction order.\n live.sort((a, b) => a.mtimeMs - b.mtimeMs);\n for (const file of live) {\n if (total <= maxBytes) break;\n total -= file.size;\n this.evict(file);\n }\n }\n }\n }\n\n private scan(): CacheFileInfo[] {\n const result: CacheFileInfo[] = [];\n\n let shards: string[];\n try {\n shards = readdirSync(this.cacheDir);\n } catch {\n return result;\n }\n\n for (const shard of shards) {\n const shardPath = path.join(this.cacheDir, shard);\n let entries: string[];\n try {\n entries = readdirSync(shardPath);\n } catch {\n continue;\n }\n\n for (const entry of entries) {\n if (!entry.endsWith(\".js\")) continue;\n const codePath = path.join(shardPath, entry);\n try {\n const stat = statSync(codePath);\n const mapPath = `${codePath}.map`;\n let mapSize = 0;\n try {\n mapSize = statSync(mapPath).size;\n } catch {\n // no map sidecar — fine\n }\n result.push({\n codePath,\n mapPath,\n size: stat.size + mapSize,\n mtimeMs: stat.mtimeMs,\n });\n } catch {\n // entry vanished mid-scan — skip\n }\n }\n }\n\n return result;\n }\n\n private evict(file: CacheFileInfo): void {\n try {\n rmSync(file.codePath, { force: true });\n } catch {\n // best effort\n }\n try {\n rmSync(file.mapPath, { force: true });\n } catch {\n // best effort\n }\n }\n\n /** Remove the entire cache directory (used by `--fresh`). */\n public clear(): void {\n try {\n rmSync(this.cacheDir, { recursive: true, force: true });\n } catch {\n // best effort\n }\n }\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAgFA,SAAS,gBAAgB,OAAwB;CAC/C,IAAI,UAAU,QAAQ,OAAO,UAAU,UACrC,OAAO,KAAK,UAAU,KAAK,KAAK;CAGlC,IAAI,MAAM,QAAQ,KAAK,GACrB,OAAO,IAAI,MAAM,IAAI,eAAe,CAAC,CAAC,KAAK,GAAG,EAAE;CAUlD,OAAO,IAPS,OAAO,KAAK,KAAgC,CAAC,CAC1D,KAAK,CAAC,CACN,KAAI,QAAO;EACV,MAAM,QAAQ,gBAAiB,MAAkC,IAAI;EACrE,OAAO,GAAG,KAAK,UAAU,GAAG,EAAE,GAAG;CACnC,CAEe,CAAC,CAAC,KAAK,GAAG,EAAE;AAC/B;;;;;AAMA,SAAgB,mBAAmB,OAAiC;CAClE,MAAM,YAAY,gBAAgB;EAChC,gBAAgB,MAAM;EACtB,YAAY,MAAM;EAClB,iBAAiB,MAAM;CACzB,CAAC;CAED,OAAO,WAAW,QAAQ,CAAC,CAAC,OAAO,SAAS,CAAC,CAAC,OAAO,KAAK,CAAC,CAAC,MAAM,GAAG,EAAE;AACzE;;;;;AAMA,SAAgB,SAAS,YAAoB,aAA6B;CACxE,OAAO,WAAW,QAAQ,CAAC,CACxB,OAAO,UAAU,C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Q;GAC1B,MAAM,YAAY,KAAK,KAAK,KAAK,UAAU,KAAK;GAChD,IAAI;GACJ,IAAI;IACF,UAAU,YAAY,SAAS;GACjC,QAAQ;IACN;GACF;GAEA,KAAK,MAAM,SAAS,SAAS;IAC3B,IAAI,CAAC,MAAM,SAAS,KAAK,GAAG;IAC5B,MAAM,WAAW,KAAK,KAAK,WAAW,KAAK;IAC3C,IAAI;KACF,MAAM,OAAO,SAAS,QAAQ;KAC9B,MAAM,UAAU,GAAG,SAAS;KAC5B,IAAI,UAAU;KACd,IAAI;MACF,UAAU,SAAS,OAAO,CAAC,CAAC;KAC9B,QAAQ,CAER;KACA,OAAO,KAAK;MACV;MACA;MACA,MAAM,KAAK,OAAO;MAClB,SAAS,KAAK;KAChB,CAAC;IACH,QAAQ,CAER;GACF;EACF;EAEA,OAAO;CACT;CAEA,AAAQ,MAAM,MAA2B;EACvC,IAAI;GACF,OAAO,KAAK,UAAU,EAAE,OAAO,KAAK,CAAC;EACvC,QAAQ,CAER;EACA,IAAI;GACF,OAAO,KAAK,SAAS,EAAE,OAAO,KAAK,CAAC;EACtC,QAAQ,CAER;CACF;;CAGA,AAAO,QAAc;EACnB,IAAI;GACF,OAAO,KAAK,UAAU;IAAE,WAAW;IAAM,OAAO;GAAK,CAAC;EACxD,QAAQ,CAER;CACF;AACF"}
|
|
1
|
+
{"version":3,"file":"transpile-cache.mjs","names":[],"sources":["../../../../../../../../core/src/dev-server/loader/transpile-cache.ts"],"sourcesContent":["/**\n * Persisted transpile cache.\n *\n * Keyed by a hash of *source content* plus a transform-options fingerprint.\n * Same source + same options → same key → same output, always. Changed\n * content → different key → fresh transpile. There is no path-keyed entry\n * anywhere, so the old \"stack trace points at a mangled cache filename\" bug\n * class is structurally impossible — the on-disk filename is opaque and the\n * source identity lives only inside the source map.\n *\n * This module is pure and hook-agnostic on purpose: it knows how to read,\n * write and evict cache entries given a key, nothing about the ESM loader,\n * `?v=N` versioning, or esbuild. Phase 2 wires it into the load hook.\n *\n * @example\n * const fp = computeFingerprint({\n * esbuildVersion: esbuild.version,\n * cacheEpoch: CACHE_EPOCH,\n * compilerOptions,\n * });\n * const key = cacheKey(sourceText, fp);\n * const hit = cache.get(key);\n * if (!hit) cache.put(key, { code, map });\n */\n\nimport { createHash, randomUUID } from \"node:crypto\";\nimport {\n mkdirSync,\n readdirSync,\n readFileSync,\n renameSync,\n rmSync,\n statSync,\n writeFileSync,\n} from \"node:fs\";\nimport path from \"node:path\";\n\n/**\n * A cached transpile result: the emitted JS and its source map (raw JSON\n * string, exactly as esbuild produced it). Either may be empty for code\n * that produced no map.\n */\nexport type TranspileEntry = {\n code: string;\n map: string;\n};\n\n/**\n * Inputs that change transpiled output for identical source text. Bumping\n * any of these must invalidate every entry — that is achieved structurally\n * by folding them into the key, not by sweeping the cache.\n */\nexport type FingerprintParts = {\n /** `esbuild.version` — a transform-engine upgrade can change output. */\n esbuildVersion: string;\n /**\n * Monotonic cache-format epoch owned by the framework. Bump it whenever\n * the cache contract (entry shape, map handling, key derivation) changes\n * so old entries are guaranteed to miss after a framework upgrade.\n */\n cacheEpoch: number;\n /**\n * The resolved tsconfig `compilerOptions` blob, hashed wholesale rather\n * than cherry-picking fields — safer against tsconfig drift (a new option\n * that affects output can't silently serve stale code).\n */\n compilerOptions: unknown;\n};\n\n/**\n * Current cache-format epoch. Bump on any change to {@link TranspileEntry}\n * shape, the storage layout, or how the loader consumes entries.\n */\nexport const CACHE_EPOCH = 1;\n\n/**\n * Stable JSON stringify — object keys sorted recursively so semantically\n * equal option blobs always produce the same fingerprint regardless of key\n * insertion order.\n */\nfunction stableStringify(value: unknown): string {\n if (value === null || typeof value !== \"object\") {\n return JSON.stringify(value) ?? \"null\";\n }\n\n if (Array.isArray(value)) {\n return `[${value.map(stableStringify).join(\",\")}]`;\n }\n\n const entries = Object.keys(value as Record<string, unknown>)\n .sort()\n .map((key) => {\n const child = stableStringify((value as Record<string, unknown>)[key]);\n return `${JSON.stringify(key)}:${child}`;\n });\n\n return `{${entries.join(\",\")}}`;\n}\n\n/**\n * Fold every output-affecting input into one short hex fingerprint that\n * becomes part of every cache key.\n */\nexport function computeFingerprint(parts: FingerprintParts): string {\n const canonical = stableStringify({\n esbuildVersion: parts.esbuildVersion,\n cacheEpoch: parts.cacheEpoch,\n compilerOptions: parts.compilerOptions,\n });\n\n return createHash(\"sha256\").update(canonical).digest(\"hex\").slice(0, 16);\n}\n\n/**\n * Derive the cache key for a source file. The NUL separator makes\n * `sourceText` and `fingerprint` unambiguous (no concatenation collision).\n */\nexport function cacheKey(sourceText: string, fingerprint: string): string {\n return createHash(\"sha256\").update(sourceText).update(\"\\0\").update(fingerprint).digest(\"hex\");\n}\n\n/** Options for {@link TranspileCache.gc}. */\nexport type GcOptions = {\n /** Evict least-recently-modified entries once total size exceeds this. */\n maxBytes?: number;\n /** Evict entries whose mtime is older than this many milliseconds. */\n maxAgeMs?: number;\n};\n\ntype CacheFileInfo = {\n codePath: string;\n mapPath: string;\n size: number;\n mtimeMs: number;\n};\n\n/**\n * Content-hash-addressed transpile cache stored on disk.\n *\n * Layout: `<cacheDir>/<first2-of-key>/<key>.js` plus a sibling `.js.map`.\n * Sharding by the first two hex chars keeps any single directory small on\n * large projects. GC metadata is derived from filesystem mtime so there is\n * no second source of truth (no sidecar index to keep consistent).\n */\nexport class TranspileCache {\n public constructor(private readonly cacheDir: string) {}\n\n private shardDir(key: string): string {\n return path.join(this.cacheDir, key.slice(0, 2));\n }\n\n /**\n * `label` is an optional human-readable prefix (e.g. a path slug). It is\n * cosmetic only — the content `key` is still what makes the name unique,\n * so the same `(key, label)` pair must be passed to `get` and `put`.\n */\n private fileName(key: string, label: string | undefined, ext: string): string {\n return label ? `${label}.${key}${ext}` : `${key}${ext}`;\n }\n\n private codePath(key: string, label?: string): string {\n return path.join(this.shardDir(key), this.fileName(key, label, \".js\"));\n }\n\n private mapPath(key: string, label?: string): string {\n return path.join(this.shardDir(key), this.fileName(key, label, \".js.map\"));\n }\n\n /**\n * Return the cached entry for `key`, or `null` on a miss. Synchronous on\n * purpose: this sits on the module-load hot path and must not pay an\n * event-loop hop per import.\n */\n public get(key: string, label?: string): TranspileEntry | null {\n try {\n const code = readFileSync(this.codePath(key, label), \"utf8\");\n let map = \"\";\n try {\n map = readFileSync(this.mapPath(key, label), \"utf8\");\n } catch {\n // A code entry with no map is valid (e.g. map-less transform).\n }\n return { code, map };\n } catch {\n return null;\n }\n }\n\n /**\n * Store an entry for `key`. Written atomically (temp file + rename) so a\n * concurrent {@link get} never observes a half-written module.\n */\n public put(key: string, entry: TranspileEntry, label?: string): void {\n const shard = this.shardDir(key);\n mkdirSync(shard, { recursive: true });\n\n this.atomicWrite(this.codePath(key, label), entry.code);\n if (entry.map) {\n this.atomicWrite(this.mapPath(key, label), entry.map);\n }\n }\n\n private atomicWrite(filePath: string, content: string): void {\n const tempPath = `${filePath}.${process.pid}.${randomUUID()}.tmp`;\n try {\n writeFileSync(tempPath, content);\n renameSync(tempPath, filePath);\n } catch (error) {\n // Windows can report EPERM/EACCES when another loader process wins the\n // rename to this content-addressed destination. The winner's file is a\n // valid commit only when it contains the exact bytes we meant to store;\n // otherwise preserve the original error instead of accepting corruption.\n const code = (error as NodeJS.ErrnoException).code;\n const mayBeConcurrentCommit = code === \"EEXIST\" || code === \"EPERM\" || code === \"EACCES\";\n\n if (!mayBeConcurrentCommit || !this.hasCommittedContent(filePath, content)) {\n throw error;\n }\n } finally {\n try {\n rmSync(tempPath, { force: true });\n } catch {\n // Best effort: a cleanup failure must not mask the rename result.\n }\n }\n }\n\n private hasCommittedContent(filePath: string, content: string): boolean {\n try {\n return readFileSync(filePath, \"utf8\") === content;\n } catch {\n return false;\n }\n }\n\n /**\n * Opportunistic eviction. Cheap, runs at boot (not on the hot path).\n * Removes age-expired entries first, then trims to the size budget by\n * evicting least-recently-modified entries. Both bounds are optional;\n * with neither set this is a no-op.\n */\n public gc(options: GcOptions = {}): void {\n const { maxBytes, maxAgeMs } = options;\n if (maxBytes === undefined && maxAgeMs === undefined) return;\n\n const files = this.scan();\n const now = Date.now();\n\n let live = files;\n\n if (maxAgeMs !== undefined) {\n live = [];\n for (const file of files) {\n if (now - file.mtimeMs > maxAgeMs) {\n this.evict(file);\n } else {\n live.push(file);\n }\n }\n }\n\n if (maxBytes !== undefined) {\n let total = live.reduce((sum, file) => sum + file.size, 0);\n if (total > maxBytes) {\n // Oldest first — least-recently-modified is the eviction order.\n live.sort((a, b) => a.mtimeMs - b.mtimeMs);\n for (const file of live) {\n if (total <= maxBytes) break;\n total -= file.size;\n this.evict(file);\n }\n }\n }\n }\n\n private scan(): CacheFileInfo[] {\n const result: CacheFileInfo[] = [];\n\n let shards: string[];\n try {\n shards = readdirSync(this.cacheDir);\n } catch {\n return result;\n }\n\n for (const shard of shards) {\n const shardPath = path.join(this.cacheDir, shard);\n let entries: string[];\n try {\n entries = readdirSync(shardPath);\n } catch {\n continue;\n }\n\n for (const entry of entries) {\n if (!entry.endsWith(\".js\")) continue;\n const codePath = path.join(shardPath, entry);\n try {\n const stat = statSync(codePath);\n const mapPath = `${codePath}.map`;\n let mapSize = 0;\n try {\n mapSize = statSync(mapPath).size;\n } catch {\n // no map sidecar — fine\n }\n result.push({\n codePath,\n mapPath,\n size: stat.size + mapSize,\n mtimeMs: stat.mtimeMs,\n });\n } catch {\n // entry vanished mid-scan — skip\n }\n }\n }\n\n return result;\n }\n\n private evict(file: CacheFileInfo): void {\n try {\n rmSync(file.codePath, { force: true });\n } catch {\n // best effort\n }\n try {\n rmSync(file.mapPath, { force: true });\n } catch {\n // best effort\n }\n }\n\n /** Remove the entire cache directory (used by `--fresh`). */\n public clear(): void {\n try {\n rmSync(this.cacheDir, { recursive: true, force: true });\n } catch {\n // best effort\n }\n }\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAgFA,SAAS,gBAAgB,OAAwB;CAC/C,IAAI,UAAU,QAAQ,OAAO,UAAU,UACrC,OAAO,KAAK,UAAU,KAAK,KAAK;C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