@warlock.js/core 5.26.0 → 5.28.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (129) hide show
  1. package/CHANGELOG.md +30 -0
  2. package/esm/cli/commands/openapi-generator.action.mjs +43 -0
  3. package/esm/cli/commands/openapi-generator.action.mjs.map +1 -0
  4. package/esm/cli/commands/openapi-generator.command.mjs +44 -0
  5. package/esm/cli/commands/openapi-generator.command.mjs.map +1 -0
  6. package/esm/cli/commands/postman-generator.action.mjs +47 -0
  7. package/esm/cli/commands/postman-generator.action.mjs.map +1 -0
  8. package/esm/cli/commands/postman-generator.command.mjs +43 -0
  9. package/esm/cli/commands/postman-generator.command.mjs.map +1 -0
  10. package/esm/cli/framework-cli-commands.mjs +4 -0
  11. package/esm/cli/framework-cli-commands.mjs.map +1 -1
  12. package/esm/dev-server/build-development-openapi-document.mjs +36 -0
  13. package/esm/dev-server/build-development-openapi-document.mjs.map +1 -0
  14. package/esm/dev-server/collect-development-api-routes.mjs +27 -0
  15. package/esm/dev-server/collect-development-api-routes.mjs.map +1 -0
  16. package/esm/dev-server/dev-logger.mjs +9 -1
  17. package/esm/dev-server/dev-logger.mjs.map +1 -1
  18. package/esm/dev-server/development-server.mjs +6 -3
  19. package/esm/dev-server/development-server.mjs.map +1 -1
  20. package/esm/dev-server/files-orchestrator.mjs +17 -1
  21. package/esm/dev-server/files-orchestrator.mjs.map +1 -1
  22. package/esm/dev-server/model-resource-typings.mjs +246 -0
  23. package/esm/dev-server/model-resource-typings.mjs.map +1 -0
  24. package/esm/dev-server/type-generator.mjs +46 -2
  25. package/esm/dev-server/type-generator.mjs.map +1 -1
  26. package/esm/http/index.d.mts +2 -1
  27. package/esm/http/middleware/inject-request-context.d.mts.map +1 -1
  28. package/esm/http/middleware/inject-request-context.mjs +29 -3
  29. package/esm/http/middleware/inject-request-context.mjs.map +1 -1
  30. package/esm/http/serialized.d.mts +114 -0
  31. package/esm/http/serialized.d.mts.map +1 -0
  32. package/esm/index.d.mts +11 -3
  33. package/esm/index.mjs +6 -1
  34. package/esm/openapi/build-openapi-document.d.mts +17 -0
  35. package/esm/openapi/build-openapi-document.d.mts.map +1 -0
  36. package/esm/openapi/build-openapi-document.mjs +124 -0
  37. package/esm/openapi/build-openapi-document.mjs.map +1 -0
  38. package/esm/openapi/cast-schema.mjs +89 -0
  39. package/esm/openapi/cast-schema.mjs.map +1 -0
  40. package/esm/openapi/collect-openapi-document.mjs +40 -0
  41. package/esm/openapi/collect-openapi-document.mjs.map +1 -0
  42. package/esm/openapi/development-openapi-provider.d.mts +28 -0
  43. package/esm/openapi/development-openapi-provider.d.mts.map +1 -0
  44. package/esm/openapi/development-openapi-provider.mjs +35 -0
  45. package/esm/openapi/development-openapi-provider.mjs.map +1 -0
  46. package/esm/openapi/error-responses.mjs +67 -0
  47. package/esm/openapi/error-responses.mjs.map +1 -0
  48. package/esm/openapi/index.d.mts +6 -0
  49. package/esm/openapi/index.mjs +6 -0
  50. package/esm/openapi/openapi-child-output.mjs +57 -0
  51. package/esm/openapi/openapi-child-output.mjs.map +1 -0
  52. package/esm/openapi/openapi-protocol.mjs +30 -0
  53. package/esm/openapi/openapi-protocol.mjs.map +1 -0
  54. package/esm/openapi/paths.mjs +63 -0
  55. package/esm/openapi/paths.mjs.map +1 -0
  56. package/esm/openapi/postman/build-request-body.mjs +86 -0
  57. package/esm/openapi/postman/build-request-body.mjs.map +1 -0
  58. package/esm/openapi/postman/build-request-url.mjs +85 -0
  59. package/esm/openapi/postman/build-request-url.mjs.map +1 -0
  60. package/esm/openapi/postman/build-saved-responses.mjs +60 -0
  61. package/esm/openapi/postman/build-saved-responses.mjs.map +1 -0
  62. package/esm/openapi/postman/example-from-schema.d.mts +17 -0
  63. package/esm/openapi/postman/example-from-schema.d.mts.map +1 -0
  64. package/esm/openapi/postman/example-from-schema.mjs +92 -0
  65. package/esm/openapi/postman/example-from-schema.mjs.map +1 -0
  66. package/esm/openapi/postman/http-status-text.mjs +31 -0
  67. package/esm/openapi/postman/http-status-text.mjs.map +1 -0
  68. package/esm/openapi/postman/index.d.mts +3 -0
  69. package/esm/openapi/postman/openapi-to-postman-collection.d.mts +22 -0
  70. package/esm/openapi/postman/openapi-to-postman-collection.d.mts.map +1 -0
  71. package/esm/openapi/postman/openapi-to-postman-collection.mjs +109 -0
  72. package/esm/openapi/postman/openapi-to-postman-collection.mjs.map +1 -0
  73. package/esm/openapi/postman/postman-types.d.mts +119 -0
  74. package/esm/openapi/postman/postman-types.d.mts.map +1 -0
  75. package/esm/openapi/postman/resolve-operation-auth.mjs +51 -0
  76. package/esm/openapi/postman/resolve-operation-auth.mjs.map +1 -0
  77. package/esm/openapi/postman/schema-refs.d.mts +7 -0
  78. package/esm/openapi/postman/schema-refs.d.mts.map +1 -0
  79. package/esm/openapi/postman/schema-refs.mjs +41 -0
  80. package/esm/openapi/postman/schema-refs.mjs.map +1 -0
  81. package/esm/openapi/postman/uuid-v5.mjs +29 -0
  82. package/esm/openapi/postman/uuid-v5.mjs.map +1 -0
  83. package/esm/openapi/request-schemas.mjs +138 -0
  84. package/esm/openapi/request-schemas.mjs.map +1 -0
  85. package/esm/openapi/response-schemas.mjs +85 -0
  86. package/esm/openapi/response-schemas.mjs.map +1 -0
  87. package/esm/openapi/schema-registry.mjs +143 -0
  88. package/esm/openapi/schema-registry.mjs.map +1 -0
  89. package/esm/openapi/security.mjs +98 -0
  90. package/esm/openapi/security.mjs.map +1 -0
  91. package/esm/openapi/types.d.mts +119 -0
  92. package/esm/openapi/types.d.mts.map +1 -0
  93. package/esm/production/registration-child-runner.mjs +139 -0
  94. package/esm/production/registration-child-runner.mjs.map +1 -0
  95. package/esm/production/route-registration-child.mjs +30 -2
  96. package/esm/production/route-registration-child.mjs.map +1 -1
  97. package/esm/production/route-registration-snapshot.mjs +22 -119
  98. package/esm/production/route-registration-snapshot.mjs.map +1 -1
  99. package/esm/resource/define-resource.d.mts +44 -14
  100. package/esm/resource/define-resource.d.mts.map +1 -1
  101. package/esm/resource/define-resource.mjs +0 -40
  102. package/esm/resource/define-resource.mjs.map +1 -1
  103. package/esm/resource/index.d.mts +1 -1
  104. package/esm/resource/resource.d.mts +4 -4
  105. package/esm/resource/resource.d.mts.map +1 -1
  106. package/esm/resource/resource.mjs +2 -4
  107. package/esm/resource/resource.mjs.map +1 -1
  108. package/esm/resource/types.d.mts +89 -4
  109. package/esm/resource/types.d.mts.map +1 -1
  110. package/esm/router/index.d.mts +1 -1
  111. package/esm/router/named-api-routes-with-responses.mjs +59 -0
  112. package/esm/router/named-api-routes-with-responses.mjs.map +1 -0
  113. package/esm/router/response-schema-types.mjs +100 -0
  114. package/esm/router/response-schema-types.mjs.map +1 -0
  115. package/esm/router/router.d.mts +2 -2
  116. package/esm/router/router.d.mts.map +1 -1
  117. package/esm/router/router.mjs +38 -11
  118. package/esm/router/router.mjs.map +1 -1
  119. package/esm/router/types.d.mts +16 -1
  120. package/esm/router/types.d.mts.map +1 -1
  121. package/llms-full.txt +293 -5
  122. package/llms.txt +3 -2
  123. package/package.json +13 -13
  124. package/skills/README.md +3 -2
  125. package/skills/create-controller/SKILL.md +39 -2
  126. package/skills/define-resource/SKILL.md +100 -1
  127. package/skills/generate-openapi/SKILL.md +148 -0
  128. package/skills/index.md +3 -3
  129. package/skills/validate-input/SKILL.md +2 -2
@@ -1 +1 @@
1
- {"version":3,"file":"files-orchestrator.mjs","names":[],"sources":["../../../../../../../core/src/dev-server/files-orchestrator.ts"],"sourcesContent":["import { colors } from \"@mongez/copper\";\nimport { init } from \"es-module-lexer\";\nimport { fileURLToPath } from \"node:url\";\nimport type { MessagePort } from \"node:worker_threads\";\nimport { warlockConfigManager } from \"../warlock-config/warlock-config.manager\";\nimport { DependencyGraph } from \"./dependency-graph\";\nimport { devLogDim, devLogSuccess } from \"./dev-logger\";\nimport { FileEventHandler } from \"./file-event-handler\";\nimport { FileManager } from \"./file-manager\";\nimport { FileOperations } from \"./file-operations\";\nimport { FilesWatcher, createIgnoredMatcher } from \"./files-watcher\";\nimport { FILE_PROCESSING_BATCH_SIZE } from \"./flags\";\nimport { EslintHealthChecker } from \"./health-checker/checkers/eslint-health-checker\";\nimport { TypescriptHealthChecker } from \"./health-checker/checkers/typescript-health-checker\";\nimport type { FileHealthCheckerContract } from \"./health-checker/file-health-checker.contract\";\nimport { FilesHealthcareManager } from \"./health-checker/files-healthcare.manager\";\nimport { buildTranspileInit } from \"./loader/build-transpile-init.js\";\nimport { registerLoader } from \"./loader/register-loader.js\";\nimport { ManifestManager } from \"./manifest-manager\";\nimport { ModuleLoader } from \"./module-loader\";\nimport { packageJsonManager } from \"./package-json-manager\";\nimport { Path } from \"../utils/normalized-path\";\nimport { SpecialFilesCollector } from \"./special-files-collector\";\nimport { tsconfigManager } from \"./tsconfig-manager\";\nimport { ensureWarlockDirectory, getFilesFromDirectory } from \"./utils\";\n\n/**\n * Register a cleanup callback that fires before the current module is\n * unloaded by HMR. Stack-inspects the caller so user code doesn't need to\n * thread the FileManager through.\n */\nexport function onCleanup(callback: () => any) {\n if (globalThis.__currentModuleFile) {\n globalThis.__currentModuleFile.addCleanup(callback);\n return;\n }\n\n const stack = new Error().stack;\n const callerLine = stack?.split(\"\\n\")[2];\n const match = callerLine?.match(/\\((.+?):\\d+:\\d+\\)/) || callerLine?.match(/at (.+?):\\d+:\\d+/);\n const rawCaller = match?.[1];\n\n // Loaded modules report `file:///…?v=N`; turn that back into a plain path.\n const callerFile = rawCaller?.startsWith(\"file://\")\n ? fileURLToPath(rawCaller.replace(/\\?.*$/, \"\"))\n : rawCaller;\n\n if (!callerFile) return;\n const fileManager = filesOrchestrator.files.get(Path.toRelative(callerFile));\n fileManager?.addCleanup(callback);\n}\n\n/**\n * Top-level coordinator for the dev server's file system.\n *\n * Owns: file discovery, the dependency graph, the manifest, the special-files\n * index, the file watcher, and the lifecycle of the ESM loader hook (which\n * provides cache-busting via `?v=N` version tokens).\n */\nexport class FilesOrchestrator {\n public readonly filesWatcher = new FilesWatcher();\n public readonly files = new Map<string, FileManager>();\n private readonly manifest = new ManifestManager(this.files);\n private readonly dependencyGraph = new DependencyGraph();\n private readonly healthCheckerManager = new FilesHealthcareManager(this.files);\n public readonly specialFilesCollector = new SpecialFilesCollector();\n public readonly moduleLoader = new ModuleLoader(this.specialFilesCollector);\n public readonly fileOperations: FileOperations;\n private readonly eventHandler: FileEventHandler;\n\n /** Main-thread end of the MessageChannel to the loader hook worker. */\n private loaderPort: MessagePort | null = null;\n\n /** Resolve callbacks for pending `flushVersionBumps()` calls. */\n private readonly pendingFlushes: Array<() => void> = [];\n\n public isInitialized = false;\n\n public constructor() {\n this.fileOperations = new FileOperations(\n this.files,\n this.dependencyGraph,\n this.manifest,\n this.specialFilesCollector,\n );\n\n this.eventHandler = new FileEventHandler(\n this.fileOperations,\n this.manifest,\n this.dependencyGraph,\n this.files,\n );\n }\n\n public async add(relativePath: string): Promise<FileManager> {\n return this.fileOperations.addFile(relativePath);\n }\n\n public async load<T>(relativePath: string, type = \"other\") {\n // Guarantee the ESM loader hook is registered before we import anything.\n // `load()` is the dynamic-import entrypoint, so it is the one place that\n // must satisfy `init()`'s documented precondition (\"Must be called before\n // any user src/ module is dynamically imported\") on its own — it cannot\n // assume a caller ran `init()` first.\n //\n // The CLI command-resolution path proves why: `cliCommandsLoader.load()`\n // imports a project command module during command *lookup* (before the\n // command's own `execute()` runs), whereas `loadPreloaders()` only calls\n // `init()` from *inside* `execute()`. So a `warlock <command>` whose\n // command file imports an `app/*` alias or a `.ts` sibling was imported\n // with no hook registered and died on `ERR_MODULE_NOT_FOUND` (f9d8f99f).\n //\n // `init()` is idempotent (guarded by `isInitialized`), so this is a no-op\n // on the dev-server path, which already calls it explicitly at startup.\n await this.init();\n\n const fileManager = await this.add(relativePath);\n return this.moduleLoader.loadModule<T>(fileManager, fileManager.type || type);\n }\n\n public getDependencyGraph(): DependencyGraph {\n return this.dependencyGraph;\n }\n\n public getInvalidationChain(file: string): string[] {\n return this.dependencyGraph.getInvalidationChain(file);\n }\n\n public getFiles(): Map<string, FileManager> {\n return this.files;\n }\n\n public getHealthCheckerManager(): FilesHealthcareManager {\n return this.healthCheckerManager;\n }\n\n /**\n * Initialise managers and register the ESM loader hook. Must be called\n * before any user `src/` module is dynamically imported.\n */\n public async init() {\n if (this.isInitialized) return;\n this.isInitialized = true;\n\n await init;\n await Promise.all([tsconfigManager.init(), packageJsonManager.init()]);\n\n // The loader hook writes itself into .warlock/, so ensure the dir exists.\n await ensureWarlockDirectory();\n\n const devServerConfig = await warlockConfigManager.lazyGet(\"devServer\");\n const transpileInit = buildTranspileInit(\n tsconfigManager.tsconfig?.compilerOptions,\n devServerConfig?.transpileCacheDebug === true,\n );\n\n this.loaderPort = await registerLoader(transpileInit);\n\n this.loaderPort.on(\"message\", (msg: { type: string }) => {\n if (msg.type === \"sync-ack\") {\n this.pendingFlushes.shift()?.();\n }\n });\n }\n\n /**\n * Tell the hook worker a file changed. The next `import()` of it will get\n * a fresh `?v=N` URL → Node cache miss → fresh content.\n */\n public bumpVersion(absolutePath: string): void {\n this.loaderPort?.postMessage({ type: \"bump\", absolutePath });\n }\n\n /**\n * Wait until the hook worker has processed every pending bump.\n *\n * `postMessage` is async — without this, a follow-up `import()` may\n * resolve before the worker increments the counter and Node will return\n * the cached old module.\n */\n public flushVersionBumps(): Promise<void> {\n if (!this.loaderPort) return Promise.resolve();\n\n return new Promise<void>((resolve) => {\n this.pendingFlushes.push(resolve);\n this.loaderPort!.postMessage({ type: \"sync\" });\n });\n }\n\n /**\n * Discover files on disk, reconcile against the manifest, build the dep\n * graph, and persist the new manifest. Idempotent.\n */\n public async initializeAll() {\n const [filesInFilesystem, manifestExists] = await Promise.all([\n this.getAllFilesFromFilesystem(),\n this.manifest.init(),\n ]);\n\n if (!manifestExists) {\n await this.processFiles(filesInFilesystem);\n } else {\n await this.reconcileFiles(filesInFilesystem);\n }\n\n this.dependencyGraph.build(this.files);\n this.fileOperations.updateFileDependents();\n this.fileOperations.syncFilesToManifest();\n await this.manifest.save();\n }\n\n public async checkHealth(files: { added: string[]; changed: string[]; deleted: string[] }) {\n const filesToCheck = [...files.added, ...files.changed]\n .map((file) => this.files.get(Path.toRelative(file)))\n .filter((file): file is FileManager => !!file);\n\n const filesToDelete = files.deleted\n .map((file) => this.files.get(Path.toRelative(file)))\n .filter((file): file is FileManager => !!file);\n\n await this.healthCheckerManager.onFileChanges(filesToCheck);\n this.healthCheckerManager.removeFiles(filesToDelete);\n this.healthCheckerManager.checkFiles(filesToCheck);\n }\n\n public async startCheckingHealth(healthCheckers?: FileHealthCheckerContract[]): Promise<void> {\n devLogDim(\"Started File Health Checks in the background.\");\n\n const checkers = healthCheckers ?? [new TypescriptHealthChecker(), new EslintHealthChecker()];\n await this.healthCheckerManager.setHealthCheckers(checkers).initialize();\n await this.healthCheckerManager.validateAllFiles();\n }\n\n /**\n * Glob the src directory, returning relative paths.\n */\n public async getAllFilesFromFilesystem(): Promise<string[]> {\n const absolutePaths = await getFilesFromDirectory();\n return absolutePaths.map((absPath) => Path.toRelative(absPath));\n }\n\n /**\n * Process every file from scratch — used when no manifest exists.\n */\n private async processFiles(filePaths: string[]) {\n devLogDim(`processing ${filePaths.length} files...`);\n await runInBatches(filePaths, FILE_PROCESSING_BATCH_SIZE, async (relativePath) => {\n const fileManager = new FileManager(\n Path.toAbsolute(relativePath),\n this.files,\n this.fileOperations,\n );\n this.files.set(relativePath, fileManager);\n await fileManager.process();\n });\n devLogSuccess(`processed ${filePaths.length} files`);\n }\n\n private async reconcileFiles(filesInFilesystem: string[]) {\n const filesInManifest = new Set(this.manifest.getAllFilePaths());\n const filesInFilesystemSet = new Set(filesInFilesystem);\n\n const newFiles = filesInFilesystem.filter((f) => !filesInManifest.has(f));\n const deletedFiles = Array.from(filesInManifest).filter((f) => !filesInFilesystemSet.has(f));\n const existingFiles = filesInFilesystem.filter((f) => filesInManifest.has(f));\n\n if (newFiles.length > 0 || deletedFiles.length > 0) {\n devLogDim(\n `reconciling: ${colors.green(newFiles.length)} new, ${colors.red(deletedFiles.length)} deleted, ${colors.blue(existingFiles.length)} existing`,\n );\n }\n\n await this.processFiles(newFiles);\n\n for (const relativePath of deletedFiles) {\n this.manifest.removeFile(relativePath);\n this.files.delete(relativePath);\n }\n\n await runInBatches(existingFiles, FILE_PROCESSING_BATCH_SIZE, async (relativePath) => {\n const fileManager = new FileManager(\n Path.toAbsolute(relativePath),\n this.files,\n this.fileOperations,\n );\n this.files.set(relativePath, fileManager);\n await fileManager.init(this.manifest.getFile(relativePath));\n });\n }\n\n public async watchFiles() {\n devLogSuccess(\"watching for file changes (not serving yet)\");\n\n this.filesWatcher.onFileChange((p, settleMs) => this.eventHandler.handleFileChange(p, settleMs));\n this.filesWatcher.onFileAdd((p, settleMs) => this.eventHandler.handleFileAdd(p, settleMs));\n this.filesWatcher.onFileDelete((p, settleMs) => this.eventHandler.handleFileDelete(p, settleMs));\n\n const watchConfig = warlockConfigManager.get(\"devServer\")?.watch;\n if (watchConfig?.include?.length) {\n this.eventHandler.setIncludeMatcher(createIgnoredMatcher(watchConfig.include));\n }\n\n await this.filesWatcher.watch(watchConfig);\n }\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\nexport const filesOrchestrator = new FilesOrchestrator();\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AA2DA,IAAa,oBAAb,MAA+B;CAmB7B,AAAO,cAAc;sBAlBU,IAAI,aAAa;+BACxB,IAAI,IAAyB;kBACzB,IAAI,gBAAgB,KAAK,KAAK;yBACvB,IAAI,gBAAgB;8BACf,IAAI,uBAAuB,KAAK,KAAK;+BACrC,IAAI,sBAAsB;sBACnC,IAAI,aAAa,KAAK,qBAAqB;oBAKjC;wBAGY,CAAC;uBAE/B;EAGrB,KAAK,iBAAiB,IAAI,eACxB,KA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EAE3D,KAAK,aAAa,cAAc,GAAG,aAAa,KAAK,aAAa,iBAAiB,GAAG,QAAQ,CAAC;EAC/F,KAAK,aAAa,WAAW,GAAG,aAAa,KAAK,aAAa,cAAc,GAAG,QAAQ,CAAC;EACzF,KAAK,aAAa,cAAc,GAAG,aAAa,KAAK,aAAa,iBAAiB,GAAG,QAAQ,CAAC;EAE/F,MAAM,cAAc,qBAAqB,IAAI,WAAW,CAAC,EAAE;EAC3D,IAAI,aAAa,SAAS,QACxB,KAAK,aAAa,kBAAkB,qBAAqB,YAAY,OAAO,CAAC;EAG/E,MAAM,KAAK,aAAa,MAAM,WAAW;CAC3C;AACF;AAEA,eAAe,aACb,OACA,MACA,IACe;CACf,IAAI,MAAM,WAAW,GAAG;CACxB,KAAK,IAAI,IAAI,GAAG,IAAI,MAAM,QAAQ,KAAK,MACrC,MAAM,QAAQ,IAAI,MAAM,MAAM,GAAG,IAAI,IAAI,CAAC,CAAC,IAAI,EAAE,CAAC;AAEtD;AAEA,MAAa,oBAAoB,IAAI,kBAAkB"}
1
+ {"version":3,"file":"files-orchestrator.mjs","names":[],"sources":["../../../../../../../core/src/dev-server/files-orchestrator.ts"],"sourcesContent":["import { colors } from \"@mongez/copper\";\nimport { init } from \"es-module-lexer\";\nimport { fileURLToPath } from \"node:url\";\nimport type { MessagePort } from \"node:worker_threads\";\nimport { warlockConfigManager } from \"../warlock-config/warlock-config.manager\";\nimport { DependencyGraph } from \"./dependency-graph\";\nimport { devLogDim, devLogSuccess } from \"./dev-logger\";\nimport { FileEventHandler } from \"./file-event-handler\";\nimport { FileManager } from \"./file-manager\";\nimport { FileOperations } from \"./file-operations\";\nimport { FilesWatcher, createIgnoredMatcher } from \"./files-watcher\";\nimport { FILE_PROCESSING_BATCH_SIZE } from \"./flags\";\nimport { EslintHealthChecker } from \"./health-checker/checkers/eslint-health-checker\";\nimport { TypescriptHealthChecker } from \"./health-checker/checkers/typescript-health-checker\";\nimport type { FileHealthCheckerContract } from \"./health-checker/file-health-checker.contract\";\nimport { FilesHealthcareManager } from \"./health-checker/files-healthcare.manager\";\nimport { buildTranspileInit } from \"./loader/build-transpile-init.js\";\nimport { registerLoader } from \"./loader/register-loader.js\";\nimport { ManifestManager } from \"./manifest-manager\";\nimport { ModuleLoader } from \"./module-loader\";\nimport { packageJsonManager } from \"./package-json-manager\";\nimport { Path } from \"../utils/normalized-path\";\nimport { SpecialFilesCollector } from \"./special-files-collector\";\nimport { tsconfigManager } from \"./tsconfig-manager\";\nimport { ensureWarlockDirectory, getFilesFromDirectory } from \"./utils\";\n\n/**\n * Register a cleanup callback that fires before the current module is\n * unloaded by HMR. Stack-inspects the caller so user code doesn't need to\n * thread the FileManager through.\n */\nexport function onCleanup(callback: () => any) {\n if (globalThis.__currentModuleFile) {\n globalThis.__currentModuleFile.addCleanup(callback);\n return;\n }\n\n const stack = new Error().stack;\n const callerLine = stack?.split(\"\\n\")[2];\n const match = callerLine?.match(/\\((.+?):\\d+:\\d+\\)/) || callerLine?.match(/at (.+?):\\d+:\\d+/);\n const rawCaller = match?.[1];\n\n // Loaded modules report `file:///…?v=N`; turn that back into a plain path.\n const callerFile = rawCaller?.startsWith(\"file://\")\n ? fileURLToPath(rawCaller.replace(/\\?.*$/, \"\"))\n : rawCaller;\n\n if (!callerFile) return;\n const fileManager = filesOrchestrator.files.get(Path.toRelative(callerFile));\n fileManager?.addCleanup(callback);\n}\n\n/**\n * Top-level coordinator for the dev server's file system.\n *\n * Owns: file discovery, the dependency graph, the manifest, the special-files\n * index, the file watcher, and the lifecycle of the ESM loader hook (which\n * provides cache-busting via `?v=N` version tokens).\n */\nexport class FilesOrchestrator {\n public readonly filesWatcher = new FilesWatcher();\n public readonly files = new Map<string, FileManager>();\n private readonly manifest = new ManifestManager(this.files);\n private readonly dependencyGraph = new DependencyGraph();\n private readonly healthCheckerManager = new FilesHealthcareManager(this.files);\n public readonly specialFilesCollector = new SpecialFilesCollector();\n public readonly moduleLoader = new ModuleLoader(this.specialFilesCollector);\n public readonly fileOperations: FileOperations;\n private readonly eventHandler: FileEventHandler;\n\n /** Main-thread end of the MessageChannel to the loader hook worker. */\n private loaderPort: MessagePort | null = null;\n\n /** Resolve callbacks for pending `flushVersionBumps()` calls. */\n private readonly pendingFlushes: Array<() => void> = [];\n\n public isInitialized = false;\n\n public constructor() {\n this.fileOperations = new FileOperations(\n this.files,\n this.dependencyGraph,\n this.manifest,\n this.specialFilesCollector,\n );\n\n this.eventHandler = new FileEventHandler(\n this.fileOperations,\n this.manifest,\n this.dependencyGraph,\n this.files,\n );\n }\n\n public async add(relativePath: string): Promise<FileManager> {\n return this.fileOperations.addFile(relativePath);\n }\n\n public async load<T>(relativePath: string, type = \"other\") {\n // Guarantee the ESM loader hook is registered before we import anything.\n // `load()` is the dynamic-import entrypoint, so it is the one place that\n // must satisfy `init()`'s documented precondition (\"Must be called before\n // any user src/ module is dynamically imported\") on its own — it cannot\n // assume a caller ran `init()` first.\n //\n // The CLI command-resolution path proves why: `cliCommandsLoader.load()`\n // imports a project command module during command *lookup* (before the\n // command's own `execute()` runs), whereas `loadPreloaders()` only calls\n // `init()` from *inside* `execute()`. So a `warlock <command>` whose\n // command file imports an `app/*` alias or a `.ts` sibling was imported\n // with no hook registered and died on `ERR_MODULE_NOT_FOUND` (f9d8f99f).\n //\n // `init()` is idempotent (guarded by `isInitialized`), so this is a no-op\n // on the dev-server path, which already calls it explicitly at startup.\n await this.init();\n\n const fileManager = await this.add(relativePath);\n return this.moduleLoader.loadModule<T>(fileManager, fileManager.type || type);\n }\n\n public getDependencyGraph(): DependencyGraph {\n return this.dependencyGraph;\n }\n\n public getInvalidationChain(file: string): string[] {\n return this.dependencyGraph.getInvalidationChain(file);\n }\n\n public getFiles(): Map<string, FileManager> {\n return this.files;\n }\n\n public getHealthCheckerManager(): FilesHealthcareManager {\n return this.healthCheckerManager;\n }\n\n /**\n * Initialise managers and register the ESM loader hook. Must be called\n * before any user `src/` module is dynamically imported.\n */\n public async init() {\n if (this.isInitialized) return;\n this.isInitialized = true;\n\n await init;\n await Promise.all([tsconfigManager.init(), packageJsonManager.init()]);\n\n // The loader hook writes itself into .warlock/, so ensure the dir exists.\n await ensureWarlockDirectory();\n\n const devServerConfig = await warlockConfigManager.lazyGet(\"devServer\");\n const transpileInit = buildTranspileInit(\n tsconfigManager.tsconfig?.compilerOptions,\n devServerConfig?.transpileCacheDebug === true,\n );\n\n this.loaderPort = await registerLoader(transpileInit);\n\n this.loaderPort.on(\"message\", (msg: { type: string }) => {\n if (msg.type === \"sync-ack\") {\n this.pendingFlushes.shift()?.();\n }\n });\n }\n\n /**\n * Tell the hook worker a file changed. The next `import()` of it will get\n * a fresh `?v=N` URL → Node cache miss → fresh content.\n */\n public bumpVersion(absolutePath: string): void {\n this.loaderPort?.postMessage({ type: \"bump\", absolutePath });\n }\n\n /**\n * Wait until the hook worker has processed every pending bump.\n *\n * `postMessage` is async — without this, a follow-up `import()` may\n * resolve before the worker increments the counter and Node will return\n * the cached old module.\n */\n public flushVersionBumps(): Promise<void> {\n if (!this.loaderPort) return Promise.resolve();\n\n return new Promise<void>((resolve) => {\n this.pendingFlushes.push(resolve);\n this.loaderPort!.postMessage({ type: \"sync\" });\n });\n }\n\n /**\n * Discover files on disk, reconcile against the manifest, build the dep\n * graph, and persist the new manifest. Idempotent.\n */\n public async initializeAll() {\n const [filesInFilesystem, manifestExists] = await Promise.all([\n this.getAllFilesFromFilesystem(),\n this.manifest.init(),\n ]);\n\n if (!manifestExists) {\n await this.processFiles(filesInFilesystem);\n } else {\n await this.reconcileFiles(filesInFilesystem);\n }\n\n this.dependencyGraph.build(this.files);\n this.fileOperations.updateFileDependents();\n this.fileOperations.syncFilesToManifest();\n await this.manifest.save();\n }\n\n public async checkHealth(files: { added: string[]; changed: string[]; deleted: string[] }) {\n const filesToCheck = [...files.added, ...files.changed]\n .map((file) => this.files.get(Path.toRelative(file)))\n .filter((file): file is FileManager => !!file);\n\n const filesToDelete = files.deleted\n .map((file) => this.files.get(Path.toRelative(file)))\n .filter((file): file is FileManager => !!file);\n\n await this.healthCheckerManager.onFileChanges(filesToCheck);\n this.healthCheckerManager.removeFiles(filesToDelete);\n this.healthCheckerManager.checkFiles(filesToCheck);\n }\n\n public async startCheckingHealth(healthCheckers?: FileHealthCheckerContract[]): Promise<void> {\n devLogDim(\"Started File Health Checks in the background.\");\n\n const checkers = healthCheckers ?? [new TypescriptHealthChecker(), new EslintHealthChecker()];\n await this.healthCheckerManager.setHealthCheckers(checkers).initialize();\n await this.healthCheckerManager.validateAllFiles();\n }\n\n /**\n * Glob the src directory, returning relative paths.\n */\n public async getAllFilesFromFilesystem(): Promise<string[]> {\n const absolutePaths = await getFilesFromDirectory();\n return absolutePaths.map((absPath) => Path.toRelative(absPath));\n }\n\n /**\n * Process every file from scratch — used when no manifest exists.\n */\n private async processFiles(filePaths: string[]) {\n devLogDim(`processing ${filePaths.length} files...`);\n await runInBatches(filePaths, FILE_PROCESSING_BATCH_SIZE, async (relativePath) => {\n const fileManager = new FileManager(\n Path.toAbsolute(relativePath),\n this.files,\n this.fileOperations,\n );\n this.files.set(relativePath, fileManager);\n await fileManager.process();\n });\n devLogSuccess(`processed ${filePaths.length} files`);\n }\n\n private async reconcileFiles(filesInFilesystem: string[]) {\n const filesInManifest = new Set(this.manifest.getAllFilePaths());\n const filesInFilesystemSet = new Set(filesInFilesystem);\n\n const newFiles = filesInFilesystem.filter((f) => !filesInManifest.has(f));\n const deletedFiles = Array.from(filesInManifest).filter((f) => !filesInFilesystemSet.has(f));\n const existingFiles = filesInFilesystem.filter((f) => filesInManifest.has(f));\n\n if (newFiles.length > 0 || deletedFiles.length > 0) {\n devLogDim(\n `reconciling: ${colors.green(newFiles.length)} new, ${colors.red(deletedFiles.length)} deleted, ${colors.blue(existingFiles.length)} existing`,\n );\n }\n\n await this.processFiles(newFiles);\n\n for (const relativePath of deletedFiles) {\n this.manifest.removeFile(relativePath);\n this.files.delete(relativePath);\n }\n\n await runInBatches(existingFiles, FILE_PROCESSING_BATCH_SIZE, async (relativePath) => {\n const fileManager = new FileManager(\n Path.toAbsolute(relativePath),\n this.files,\n this.fileOperations,\n );\n this.files.set(relativePath, fileManager);\n await fileManager.init(this.manifest.getFile(relativePath));\n });\n }\n\n public async watchFiles() {\n devLogSuccess(\"watching for file changes (not serving yet)\");\n\n this.filesWatcher.onFileChange((p, settleMs) => this.eventHandler.handleFileChange(p, settleMs));\n this.filesWatcher.onFileAdd((p, settleMs) => this.eventHandler.handleFileAdd(p, settleMs));\n this.filesWatcher.onFileDelete((p, settleMs) => this.eventHandler.handleFileDelete(p, settleMs));\n\n const watchConfig = warlockConfigManager.get(\"devServer\")?.watch;\n if (watchConfig?.include?.length) {\n this.eventHandler.setIncludeMatcher(createIgnoredMatcher(watchConfig.include));\n }\n\n await this.filesWatcher.watch(watchConfig);\n }\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\nexport const filesOrchestrator = new FilesOrchestrator();\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AA+BA,SAAgB,UAAU,UAAqB;CAC7C,IAAI,WAAW,qBAAqB;EAClC,WAAW,oBAAoB,WAAW,QAAQ;EAClD;CACF;CAGA,MAAM,8BADQ,IAAI,MAAM,EAAC,CAAC,OACA,MAAM,IAAI,CAAC,CAAC;CAEtC,MAAM,aADQ,YAAY,MAAM,mBAAmB,KAAK,YAAY,MAAM,kBAAkB,EACrE,GAAG;CAG1B,MAAM,aAAa,WAAW,WAAW,SAAS,IAC9C,cAAc,UAAU,QAAQ,SAAS,EAAE,CAAC,IAC5C;CAEJ,IAAI,CAAC,YAAY;CAEjB,AADoB,kBAAkB,MAAM,IAAI,KAAK,WAAW,UAAU,CAChE,CAAC,EAAE,WAAW,QAAQ;AAClC;;;;;;;;AASA,IAAa,oBAAb,MAA+B;CAmB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;EAEA,MAAM,aAAa,oBAA2C,OAAO,iBAAiB;GACpF,MAAM,cAAc,IAAI,YACtB,KAAK,WAAW,YAAY,GAC5B,KAAK,OACL,KAAK,cACP;GACA,KAAK,MAAM,IAAI,cAAc,WAAW;GACxC,MAAM,YAAY,KAAK,KAAK,SAAS,QAAQ,YAAY,CAAC;EAC5D,CAAC;CACH;CAEA,MAAa,aAAa;EACxB,cAAc,6CAA6C;EAE3D,KAAK,aAAa,cAAc,GAAG,aAAa,KAAK,aAAa,iBAAiB,GAAG,QAAQ,CAAC;EAC/F,KAAK,aAAa,WAAW,GAAG,aAAa,KAAK,aAAa,cAAc,GAAG,QAAQ,CAAC;EACzF,KAAK,aAAa,cAAc,GAAG,aAAa,KAAK,aAAa,iBAAiB,GAAG,QAAQ,CAAC;EAE/F,MAAM,cAAc,qBAAqB,IAAI,WAAW,CAAC,EAAE;EAC3D,IAAI,aAAa,SAAS,QACxB,KAAK,aAAa,kBAAkB,qBAAqB,YAAY,OAAO,CAAC;EAG/E,MAAM,KAAK,aAAa,MAAM,WAAW;CAC3C;AACF;AAEA,eAAe,aACb,OACA,MACA,IACe;CACf,IAAI,MAAM,WAAW,GAAG;CACxB,KAAK,IAAI,IAAI,GAAG,IAAI,MAAM,QAAQ,KAAK,MACrC,MAAM,QAAQ,IAAI,MAAM,MAAM,GAAG,IAAI,IAAI,CAAC,CAAC,IAAI,EAAE,CAAC;AAEtD;AAEA,MAAa,oBAAoB,IAAI,kBAAkB"}
@@ -0,0 +1,246 @@
1
+ import { dirname, isAbsolute, relative } from "node:path";
2
+ import { mkdir, readFile, rename, rm, writeFile } from "node:fs/promises";
3
+ import ts from "typescript";
4
+
5
+ //#region ../core/src/dev-server/model-resource-typings.ts
6
+ const IDENTIFIER = /^[A-Za-z_$][A-Za-z0-9_$]*$/;
7
+ function hasModifier(node, kind) {
8
+ return ts.canHaveModifiers(node) && (ts.getModifiers(node)?.some((m) => m.kind === kind) ?? false);
9
+ }
10
+ function unwrapParentheses(expression) {
11
+ let current = expression;
12
+ while (ts.isParenthesizedExpression(current)) current = current.expression;
13
+ return current;
14
+ }
15
+ /** Top-level names this file declares, and the names each is exported under. */
16
+ function readLocalDeclarations(sourceFile) {
17
+ const declared = /* @__PURE__ */ new Set();
18
+ const exportNames = /* @__PURE__ */ new Map();
19
+ const addExport = (local, exported) => {
20
+ const names = exportNames.get(local) ?? [];
21
+ names.push(exported);
22
+ exportNames.set(local, names);
23
+ };
24
+ for (const statement of sourceFile.statements) {
25
+ const exported = hasModifier(statement, ts.SyntaxKind.ExportKeyword);
26
+ const isDefault = hasModifier(statement, ts.SyntaxKind.DefaultKeyword);
27
+ if ((ts.isClassDeclaration(statement) || ts.isFunctionDeclaration(statement) || ts.isEnumDeclaration(statement)) && statement.name) {
28
+ declared.add(statement.name.text);
29
+ if (exported) addExport(statement.name.text, isDefault ? "default" : statement.name.text);
30
+ continue;
31
+ }
32
+ if (ts.isVariableStatement(statement)) {
33
+ for (const declaration of statement.declarationList.declarations) {
34
+ if (!ts.isIdentifier(declaration.name)) continue;
35
+ declared.add(declaration.name.text);
36
+ if (exported) addExport(declaration.name.text, declaration.name.text);
37
+ }
38
+ continue;
39
+ }
40
+ if (ts.isExportDeclaration(statement) && !statement.moduleSpecifier && !statement.isTypeOnly && statement.exportClause && ts.isNamedExports(statement.exportClause)) {
41
+ for (const element of statement.exportClause.elements) {
42
+ if (element.isTypeOnly) continue;
43
+ addExport((element.propertyName ?? element.name).text, element.name.text);
44
+ }
45
+ continue;
46
+ }
47
+ if (ts.isExportAssignment(statement) && !statement.isExportEquals && ts.isIdentifier(statement.expression)) addExport(statement.expression.text, "default");
48
+ }
49
+ return {
50
+ declared,
51
+ exportNames
52
+ };
53
+ }
54
+ /** Prefer a named export over `default`; among named exports, the first sorted. */
55
+ function pickExportName(names) {
56
+ if (!names || names.length === 0) return void 0;
57
+ return names.filter((name) => name !== "default").sort()[0] ?? "default";
58
+ }
59
+ function readImportBindings(sourceFile) {
60
+ const bindings = /* @__PURE__ */ new Map();
61
+ for (const statement of sourceFile.statements) {
62
+ if (!ts.isImportDeclaration(statement) || !ts.isStringLiteral(statement.moduleSpecifier)) continue;
63
+ const clause = statement.importClause;
64
+ const specifier = statement.moduleSpecifier.text;
65
+ if (!clause) continue;
66
+ if (clause.name) bindings.set(clause.name.text, {
67
+ specifier,
68
+ exportName: "default"
69
+ });
70
+ if (clause.namedBindings && ts.isNamedImports(clause.namedBindings)) for (const element of clause.namedBindings.elements) bindings.set(element.name.text, {
71
+ specifier,
72
+ exportName: (element.propertyName ?? element.name).text
73
+ });
74
+ }
75
+ return bindings;
76
+ }
77
+ /** The identifier a class assigns to `static resource`, when it is a bare identifier. */
78
+ function readStaticResourceReference(member) {
79
+ if (!ts.isPropertyDeclaration(member)) return void 0;
80
+ if (!hasModifier(member, ts.SyntaxKind.StaticKeyword)) return void 0;
81
+ if (hasModifier(member, ts.SyntaxKind.DeclareKeyword)) return void 0;
82
+ if (!((ts.isIdentifier(member.name) || ts.isStringLiteral(member.name)) && member.name.text === "resource")) return void 0;
83
+ if (!member.initializer) return void 0;
84
+ const initializer = unwrapParentheses(member.initializer);
85
+ return ts.isIdentifier(initializer) ? { name: initializer.text } : "computed";
86
+ }
87
+ /**
88
+ * Read every model class of one file that declares `static resource = <Identifier>`
89
+ * and resolve it to a model export plus a resource export. Pure: the only
90
+ * outside knowledge is the injected {@link ExtractModelResourcesInput.resolveImport}.
91
+ */
92
+ function extractModelResourceEntries(input) {
93
+ const result = {
94
+ entries: [],
95
+ skipped: []
96
+ };
97
+ if (!input.source.includes("resource")) return result;
98
+ const sourceFile = ts.createSourceFile(input.absolutePath, input.source, ts.ScriptTarget.ESNext, false, input.absolutePath.endsWith("x") ? ts.ScriptKind.TSX : ts.ScriptKind.TS);
99
+ const { declared, exportNames } = readLocalDeclarations(sourceFile);
100
+ const imports = readImportBindings(sourceFile);
101
+ for (const statement of sourceFile.statements) {
102
+ if (!ts.isClassDeclaration(statement) || !statement.name) continue;
103
+ const className = statement.name.text;
104
+ let reference;
105
+ for (const member of statement.members) reference = readStaticResourceReference(member) ?? reference;
106
+ if (reference === void 0) continue;
107
+ const skip = (reason) => {
108
+ result.skipped.push({
109
+ className,
110
+ modelFile: input.absolutePath,
111
+ reason
112
+ });
113
+ };
114
+ if (reference === "computed") {
115
+ skip("`static resource` is not a plain identifier");
116
+ continue;
117
+ }
118
+ if (statement.typeParameters?.some((parameter) => parameter.default === void 0)) {
119
+ skip("the model class is generic");
120
+ continue;
121
+ }
122
+ const modelExport = pickExportName(exportNames.get(className));
123
+ if (modelExport === void 0) {
124
+ skip("the model class is not exported");
125
+ continue;
126
+ }
127
+ if (modelExport !== "default" && !IDENTIFIER.test(modelExport)) {
128
+ skip("the model export name is not an identifier");
129
+ continue;
130
+ }
131
+ const binding = imports.get(reference.name);
132
+ let resourceFile;
133
+ let resourceExport;
134
+ if (binding) {
135
+ resourceFile = input.resolveImport(binding.specifier);
136
+ resourceExport = binding.exportName;
137
+ } else if (declared.has(reference.name)) {
138
+ resourceFile = input.absolutePath;
139
+ resourceExport = pickExportName(exportNames.get(reference.name));
140
+ }
141
+ if (resourceFile === void 0 || resourceExport === void 0) {
142
+ skip(`\`${reference.name}\` cannot be resolved to an exported module member`);
143
+ continue;
144
+ }
145
+ if (resourceExport !== "default" && !IDENTIFIER.test(resourceExport)) {
146
+ skip("the resource export name is not an identifier");
147
+ continue;
148
+ }
149
+ result.entries.push({
150
+ className,
151
+ modelFile: input.absolutePath,
152
+ modelExport,
153
+ resourceFile,
154
+ resourceExport
155
+ });
156
+ }
157
+ return result;
158
+ }
159
+ /** Module specifier, relative to the typings directory, without a TypeScript extension. */
160
+ function toTypeImportSpecifier(typingsDirectory, absoluteFile) {
161
+ const path = relative(typingsDirectory, absoluteFile).replaceAll("\\", "/");
162
+ if (isAbsolute(path)) return void 0;
163
+ const withoutExtension = path.replace(/\.(?:d\.)?(?:ts|tsx|mts|cts)$/, "");
164
+ return withoutExtension.startsWith(".") ? withoutExtension : `./${withoutExtension}`;
165
+ }
166
+ /**
167
+ * Registry keys: the class name, suffixed `_2`, `_3`, ... when several model
168
+ * files declare the same class name. Order is by class name, then by file path,
169
+ * so the same set of models always yields the same keys and the same text.
170
+ */
171
+ function assignRegistryKeys(entries) {
172
+ const sorted = [...entries].sort((a, b) => a.className.localeCompare(b.className, "en") || a.modelFile.localeCompare(b.modelFile, "en") || a.modelExport.localeCompare(b.modelExport, "en"));
173
+ const taken = /* @__PURE__ */ new Set();
174
+ const counts = /* @__PURE__ */ new Map();
175
+ return sorted.map((entry) => {
176
+ let count = (counts.get(entry.className) ?? 0) + 1;
177
+ let key = count === 1 ? entry.className : `${entry.className}_${count}`;
178
+ while (taken.has(key)) {
179
+ count += 1;
180
+ key = `${entry.className}_${count}`;
181
+ }
182
+ counts.set(entry.className, count);
183
+ taken.add(key);
184
+ return {
185
+ key,
186
+ entry
187
+ };
188
+ });
189
+ }
190
+ /**
191
+ * Text of the generated declaration file.
192
+ *
193
+ * @param entries Every resolved model, in any order.
194
+ * @param typingsDirectory Absolute directory the file is written to; import
195
+ * specifiers are relative to it.
196
+ */
197
+ function renderModelResourceRegistry(entries, typingsDirectory) {
198
+ const lines = [];
199
+ for (const { key, entry } of assignRegistryKeys(entries)) {
200
+ const modelPath = toTypeImportSpecifier(typingsDirectory, entry.modelFile);
201
+ const resourcePath = toTypeImportSpecifier(typingsDirectory, entry.resourceFile);
202
+ if (modelPath === void 0 || resourcePath === void 0) continue;
203
+ const model = `import(${JSON.stringify(modelPath)}).${entry.modelExport}`;
204
+ const resource = `typeof import(${JSON.stringify(resourcePath)}).${entry.resourceExport}`;
205
+ lines.push(` ${JSON.stringify(key)}: { model: ${model}; resource: ${resource} };`);
206
+ }
207
+ return `// Auto-generated by Warlock.js - DO NOT EDIT
208
+ // One entry per model class that declares \`static resource = <Resource>\`, so
209
+ // \`Serialized<Model>\` resolves to the resource output. Models whose resource
210
+ // cannot be resolved statically are left out.
211
+
212
+ import "@warlock.js/core";
213
+
214
+ declare module "@warlock.js/core" {
215
+ interface ModelResourceRegistry {
216
+ ${lines.join("\n")}
217
+ }
218
+ }
219
+ `;
220
+ }
221
+ /**
222
+ * Write `content` to `filePath` through a temporary sibling and a rename, so a
223
+ * reader (the editor's TypeScript server) never sees a half-written file, and
224
+ * skip the write entirely when the file already holds exactly this text.
225
+ *
226
+ * @returns `true` when the file was written.
227
+ */
228
+ async function writeFileIfChanged(filePath, content) {
229
+ try {
230
+ if (await readFile(filePath, "utf-8") === content) return false;
231
+ } catch {}
232
+ await mkdir(dirname(filePath), { recursive: true });
233
+ const temporaryPath = `${filePath}.${process.pid}.tmp`;
234
+ try {
235
+ await writeFile(temporaryPath, content, "utf-8");
236
+ await rename(temporaryPath, filePath);
237
+ } catch (error) {
238
+ await rm(temporaryPath, { force: true });
239
+ throw error;
240
+ }
241
+ return true;
242
+ }
243
+
244
+ //#endregion
245
+ export { extractModelResourceEntries, renderModelResourceRegistry, writeFileIfChanged };
246
+ //# sourceMappingURL=model-resource-typings.mjs.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"model-resource-typings.mjs","names":[],"sources":["../../../../../../../core/src/dev-server/model-resource-typings.ts"],"sourcesContent":["import { mkdir, readFile, rename, rm, writeFile } from \"node:fs/promises\";\nimport { dirname, isAbsolute, relative } from \"node:path\";\nimport ts from \"typescript\";\n\n/**\n * Static `ModelResourceRegistry` generation.\n *\n * `Serialized<User>` can only resolve a model to its resource output through an\n * entry in the augmentable `ModelResourceRegistry` (see `http/serialized.ts`).\n * This module derives those entries from source: a model class that declares\n * `static resource = UserResource` produces\n *\n * ```ts\n * \"User\": { model: import(\"<model file>\").User; resource: typeof import(\"<resource file>\").UserResource };\n * ```\n *\n * Everything here is syntactic. It reads one `ts.createSourceFile` AST per model\n * file, follows the identifier through that file's own imports, and never\n * imports or executes application code (`read-config-ast.ts` explains why a\n * type checker is not an option). Anything it cannot prove from the AST alone\n * (a computed expression, `lazy(...)`, a namespace import, a class that is not\n * exported) is skipped, and nothing is recorded for it: a guessed entry would\n * make `Serialized` lie, which is worse than the raw-data type it falls back to.\n */\n\n/** One model class whose resource could be resolved statically. */\nexport type ModelResourceEntry = {\n /** The model class name (the registry key before de-duplication). */\n className: string;\n /** Absolute path of the model file. */\n modelFile: string;\n /** How the model file exports the class: its export name, or `\"default\"`. */\n modelExport: string;\n /** Absolute path of the module that exports the resource. */\n resourceFile: string;\n /** How that module exports the resource: its export name, or `\"default\"`. */\n resourceExport: string;\n};\n\n/** A model that declares `static resource` but could not be resolved. */\nexport type SkippedModelResource = {\n className: string;\n modelFile: string;\n reason: string;\n};\n\nexport type ModelResourceExtraction = {\n entries: ModelResourceEntry[];\n skipped: SkippedModelResource[];\n};\n\nexport type ExtractModelResourcesInput = {\n /** Source text of the model file. */\n source: string;\n /** Absolute path of the model file. */\n absolutePath: string;\n /**\n * Resolve an import specifier of the model file (relative or tsconfig alias) to\n * an absolute file path, or `undefined` when it does not point at app source.\n */\n resolveImport: (specifier: string) => string | undefined;\n};\n\ntype ImportBinding = { specifier: string; exportName: string };\n\nconst IDENTIFIER = /^[A-Za-z_$][A-Za-z0-9_$]*$/;\n\nfunction hasModifier(node: ts.Node, kind: ts.SyntaxKind): boolean {\n return ts.canHaveModifiers(node) && (ts.getModifiers(node)?.some((m) => m.kind === kind) ?? false);\n}\n\nfunction unwrapParentheses(expression: ts.Expression): ts.Expression {\n let current = expression;\n\n while (ts.isParenthesizedExpression(current)) {\n current = current.expression;\n }\n\n return current;\n}\n\n/** Top-level names this file declares, and the names each is exported under. */\nfunction readLocalDeclarations(sourceFile: ts.SourceFile): {\n declared: Set<string>;\n exportNames: Map<string, string[]>;\n} {\n const declared = new Set<string>();\n const exportNames = new Map<string, string[]>();\n\n const addExport = (local: string, exported: string): void => {\n const names = exportNames.get(local) ?? [];\n\n names.push(exported);\n exportNames.set(local, names);\n };\n\n for (const statement of sourceFile.statements) {\n const exported = hasModifier(statement, ts.SyntaxKind.ExportKeyword);\n const isDefault = hasModifier(statement, ts.SyntaxKind.DefaultKeyword);\n\n if (\n (ts.isClassDeclaration(statement) ||\n ts.isFunctionDeclaration(statement) ||\n ts.isEnumDeclaration(statement)) &&\n statement.name\n ) {\n declared.add(statement.name.text);\n\n if (exported) {\n addExport(statement.name.text, isDefault ? \"default\" : statement.name.text);\n }\n\n continue;\n }\n\n if (ts.isVariableStatement(statement)) {\n for (const declaration of statement.declarationList.declarations) {\n if (!ts.isIdentifier(declaration.name)) continue;\n\n declared.add(declaration.name.text);\n\n if (exported) {\n addExport(declaration.name.text, declaration.name.text);\n }\n }\n\n continue;\n }\n\n // `export { A, B as C }` (local form only; a `from` clause re-exports a foreign name).\n if (\n ts.isExportDeclaration(statement) &&\n !statement.moduleSpecifier &&\n !statement.isTypeOnly &&\n statement.exportClause &&\n ts.isNamedExports(statement.exportClause)\n ) {\n for (const element of statement.exportClause.elements) {\n if (element.isTypeOnly) continue;\n\n addExport((element.propertyName ?? element.name).text, element.name.text);\n }\n\n continue;\n }\n\n // `export default UserResource;`\n if (\n ts.isExportAssignment(statement) &&\n !statement.isExportEquals &&\n ts.isIdentifier(statement.expression)\n ) {\n addExport(statement.expression.text, \"default\");\n }\n }\n\n return { declared, exportNames };\n}\n\n/** Prefer a named export over `default`; among named exports, the first sorted. */\nfunction pickExportName(names: readonly string[] | undefined): string | undefined {\n if (!names || names.length === 0) return undefined;\n\n const named = names.filter((name) => name !== \"default\").sort();\n\n return named[0] ?? \"default\";\n}\n\nfunction readImportBindings(sourceFile: ts.SourceFile): Map<string, ImportBinding> {\n const bindings = new Map<string, ImportBinding>();\n\n for (const statement of sourceFile.statements) {\n if (!ts.isImportDeclaration(statement) || !ts.isStringLiteral(statement.moduleSpecifier)) {\n continue;\n }\n\n const clause = statement.importClause;\n const specifier = statement.moduleSpecifier.text;\n\n if (!clause) continue;\n\n if (clause.name) {\n bindings.set(clause.name.text, { specifier, exportName: \"default\" });\n }\n\n // A namespace import (`import * as ns`) cannot be the bare identifier a\n // `static resource = X` reads, so it never becomes a binding.\n if (clause.namedBindings && ts.isNamedImports(clause.namedBindings)) {\n for (const element of clause.namedBindings.elements) {\n bindings.set(element.name.text, {\n specifier,\n exportName: (element.propertyName ?? element.name).text,\n });\n }\n }\n }\n\n return bindings;\n}\n\n/** The identifier a class assigns to `static resource`, when it is a bare identifier. */\nfunction readStaticResourceReference(\n member: ts.ClassElement,\n): { name: string } | \"computed\" | undefined {\n if (!ts.isPropertyDeclaration(member)) return undefined;\n if (!hasModifier(member, ts.SyntaxKind.StaticKeyword)) return undefined;\n if (hasModifier(member, ts.SyntaxKind.DeclareKeyword)) return undefined;\n\n const isResourceName =\n (ts.isIdentifier(member.name) || ts.isStringLiteral(member.name)) &&\n member.name.text === \"resource\";\n\n if (!isResourceName) return undefined;\n if (!member.initializer) return undefined;\n\n const initializer = unwrapParentheses(member.initializer);\n\n return ts.isIdentifier(initializer) ? { name: initializer.text } : \"computed\";\n}\n\n/**\n * Read every model class of one file that declares `static resource = <Identifier>`\n * and resolve it to a model export plus a resource export. Pure: the only\n * outside knowledge is the injected {@link ExtractModelResourcesInput.resolveImport}.\n */\nexport function extractModelResourceEntries(\n input: ExtractModelResourcesInput,\n): ModelResourceExtraction {\n const result: ModelResourceExtraction = { entries: [], skipped: [] };\n\n // Cheap exit: most model files declare no resource.\n if (!input.source.includes(\"resource\")) return result;\n\n const sourceFile = ts.createSourceFile(\n input.absolutePath,\n input.source,\n ts.ScriptTarget.ESNext,\n /* setParentNodes */ false,\n input.absolutePath.endsWith(\"x\") ? ts.ScriptKind.TSX : ts.ScriptKind.TS,\n );\n\n const { declared, exportNames } = readLocalDeclarations(sourceFile);\n const imports = readImportBindings(sourceFile);\n\n for (const statement of sourceFile.statements) {\n if (!ts.isClassDeclaration(statement) || !statement.name) continue;\n\n const className = statement.name.text;\n\n let reference: { name: string } | \"computed\" | undefined;\n\n for (const member of statement.members) {\n reference = readStaticResourceReference(member) ?? reference;\n }\n\n if (reference === undefined) continue;\n\n const skip = (reason: string): void => {\n result.skipped.push({ className, modelFile: input.absolutePath, reason });\n };\n\n if (reference === \"computed\") {\n skip(\"`static resource` is not a plain identifier\");\n continue;\n }\n\n const requiresTypeArguments = statement.typeParameters?.some(\n (parameter) => parameter.default === undefined,\n );\n\n if (requiresTypeArguments) {\n skip(\"the model class is generic\");\n continue;\n }\n\n const modelExport = pickExportName(exportNames.get(className));\n\n if (modelExport === undefined) {\n skip(\"the model class is not exported\");\n continue;\n }\n\n if (modelExport !== \"default\" && !IDENTIFIER.test(modelExport)) {\n skip(\"the model export name is not an identifier\");\n continue;\n }\n\n const binding = imports.get(reference.name);\n\n let resourceFile: string | undefined;\n let resourceExport: string | undefined;\n\n if (binding) {\n resourceFile = input.resolveImport(binding.specifier);\n resourceExport = binding.exportName;\n } else if (declared.has(reference.name)) {\n resourceFile = input.absolutePath;\n resourceExport = pickExportName(exportNames.get(reference.name));\n }\n\n if (resourceFile === undefined || resourceExport === undefined) {\n skip(`\\`${reference.name}\\` cannot be resolved to an exported module member`);\n continue;\n }\n\n if (resourceExport !== \"default\" && !IDENTIFIER.test(resourceExport)) {\n skip(\"the resource export name is not an identifier\");\n continue;\n }\n\n result.entries.push({\n className,\n modelFile: input.absolutePath,\n modelExport,\n resourceFile,\n resourceExport,\n });\n }\n\n return result;\n}\n\n/** Module specifier, relative to the typings directory, without a TypeScript extension. */\nfunction toTypeImportSpecifier(typingsDirectory: string, absoluteFile: string): string | undefined {\n const path = relative(typingsDirectory, absoluteFile).replaceAll(\"\\\\\", \"/\");\n\n // A different drive (Windows) has no relative form; do not emit a guess.\n if (isAbsolute(path)) return undefined;\n\n const withoutExtension = path.replace(/\\.(?:d\\.)?(?:ts|tsx|mts|cts)$/, \"\");\n\n return withoutExtension.startsWith(\".\") ? withoutExtension : `./${withoutExtension}`;\n}\n\n/**\n * Registry keys: the class name, suffixed `_2`, `_3`, ... when several model\n * files declare the same class name. Order is by class name, then by file path,\n * so the same set of models always yields the same keys and the same text.\n */\nexport function assignRegistryKeys(\n entries: readonly ModelResourceEntry[],\n): Array<{ key: string; entry: ModelResourceEntry }> {\n const sorted = [...entries].sort(\n (a, b) =>\n a.className.localeCompare(b.className, \"en\") ||\n a.modelFile.localeCompare(b.modelFile, \"en\") ||\n a.modelExport.localeCompare(b.modelExport, \"en\"),\n );\n\n const taken = new Set<string>();\n const counts = new Map<string, number>();\n\n return sorted.map((entry) => {\n let count = (counts.get(entry.className) ?? 0) + 1;\n let key = count === 1 ? entry.className : `${entry.className}_${count}`;\n\n while (taken.has(key)) {\n count += 1;\n key = `${entry.className}_${count}`;\n }\n\n counts.set(entry.className, count);\n taken.add(key);\n\n return { key, entry };\n });\n}\n\n/**\n * Text of the generated declaration file.\n *\n * @param entries Every resolved model, in any order.\n * @param typingsDirectory Absolute directory the file is written to; import\n * specifiers are relative to it.\n */\nexport function renderModelResourceRegistry(\n entries: readonly ModelResourceEntry[],\n typingsDirectory: string,\n): string {\n const lines: string[] = [];\n\n for (const { key, entry } of assignRegistryKeys(entries)) {\n const modelPath = toTypeImportSpecifier(typingsDirectory, entry.modelFile);\n const resourcePath = toTypeImportSpecifier(typingsDirectory, entry.resourceFile);\n\n if (modelPath === undefined || resourcePath === undefined) continue;\n\n const model = `import(${JSON.stringify(modelPath)}).${entry.modelExport}`;\n const resource = `typeof import(${JSON.stringify(resourcePath)}).${entry.resourceExport}`;\n\n lines.push(` ${JSON.stringify(key)}: { model: ${model}; resource: ${resource} };`);\n }\n\n return `// Auto-generated by Warlock.js - DO NOT EDIT\n// One entry per model class that declares \\`static resource = <Resource>\\`, so\n// \\`Serialized<Model>\\` resolves to the resource output. Models whose resource\n// cannot be resolved statically are left out.\n\nimport \"@warlock.js/core\";\n\ndeclare module \"@warlock.js/core\" {\n interface ModelResourceRegistry {\n${lines.join(\"\\n\")}\n }\n}\n`;\n}\n\n/**\n * Write `content` to `filePath` through a temporary sibling and a rename, so a\n * reader (the editor's TypeScript server) never sees a half-written file, and\n * skip the write entirely when the file already holds exactly this text.\n *\n * @returns `true` when the file was written.\n */\nexport async function writeFileIfChanged(filePath: string, content: string): Promise<boolean> {\n try {\n if ((await readFile(filePath, \"utf-8\")) === content) return false;\n } catch {\n // Missing file: write it.\n }\n\n await mkdir(dirname(filePath), { recursive: true });\n\n const temporaryPath = `${filePath}.${process.pid}.tmp`;\n\n try {\n await writeFile(temporaryPath, content, \"utf-8\");\n await rename(temporaryPath, filePath);\n } catch (error) {\n await rm(temporaryPath, { force: true });\n\n throw error;\n }\n\n return true;\n}\n"],"mappings":";;;;;AAiEA,MAAM,aAAa;AAEnB,SAAS,YAAY,MAAe,MAA8B;CAChE,OAAO,GAAG,iBAAiB,IAAI,MAAM,GAAG,aAAa,IAAI,CAAC,EAAE,MAAM,MAAM,EAAE,SAAS,IAAI,KAAK;AAC9F;AAEA,SAAS,kBAAkB,YAA0C;CACnE,IAAI,UAAU;CAEd,OAAO,GAAG,0BAA0B,OAAO,GACzC,UAAU,QAAQ;CAGpB,OAAO;AACT;;AAGA,SAAS,sBAAsB,YAG7B;CACA,MAAM,2BAAW,IAAI,IAAY;CACjC,MAAM,8BAAc,IAAI,IAAsB;CAE9C,MAAM,aAAa,OAAe,aAA2B;EAC3D,MAAM,QAAQ,YAAY,IAAI,KAAK,KAAK,CAAC;EAEzC,MAAM,KAAK,QAAQ;EACnB,YAAY,IAAI,OAAO,KAAK;CAC9B;CAEA,KAAK,MAAM,aAAa,WAAW,YAAY;EAC7C,MAAM,WAAW,YAAY,WAAW,GAAG,WAAW,aAAa;EACnE,MAAM,YAAY,YAAY,WAAW,GAAG,WAAW,cAAc;EAErE,KACG,GAAG,mBAAmB,SAAS,KAC9B,GAAG,sBAAsB,SAAS,KAClC,GAAG,kBAAkB,SAAS,MAChC,UAAU,MACV;GACA,SAAS,IAAI,UAAU,KAAK,IAAI;GAEhC,IAAI,UACF,UAAU,UAAU,KAAK,MAAM,YAAY,YAAY,UAAU,KAAK,IAAI;GAG5E;EACF;EAEA,IAAI,GAAG,oBAAoB,SAAS,GAAG;GACrC,KAAK,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AO,SAAS,OAAO;CAC9D,QAAQ,CAER;CAEA,MAAM,MAAM,QAAQ,QAAQ,GAAG,EAAE,WAAW,KAAK,CAAC;CAElD,MAAM,gBAAgB,GAAG,SAAS,GAAG,QAAQ,IAAI;CAEjD,IAAI;EACF,MAAM,UAAU,eAAe,SAAS,OAAO;EAC/C,MAAM,OAAO,eAAe,QAAQ;CACtC,SAAS,OAAO;EACd,MAAM,GAAG,eAAe,EAAE,OAAO,KAAK,CAAC;EAEvC,MAAM;CACR;CAEA,OAAO;AACT"}
@@ -3,13 +3,15 @@ import { warlockPath } from "../utils/paths.mjs";
3
3
  import "../utils/index.mjs";
4
4
  import { parseLocaleDictionary } from "../localization/parse-locale-dictionary.mjs";
5
5
  import "../localization/index.mjs";
6
- import { devLogError, devLogInfo, devLogSuccess, devServeLog } from "./dev-logger.mjs";
6
+ import { devLogDim, devLogError, devLogInfo, devLogSuccess, devServeLog } from "./dev-logger.mjs";
7
+ import { parseImports } from "./parse-imports.mjs";
7
8
  import { getFilesFromDirectory } from "./utils.mjs";
8
9
  import { extractTranslationKeys } from "./extract-translation-keys.mjs";
9
10
  import { filesOrchestrator } from "./files-orchestrator.mjs";
10
11
  import { readConfigAst } from "./read-config-ast.mjs";
11
12
  import { runTypingsGeneration } from "./run-typings-generation.mjs";
12
13
  import { isModuleLocaleDictionaryPath, isTranslationRegisteringSource } from "./translation-keys-sources.mjs";
14
+ import { extractModelResourceEntries, renderModelResourceRegistry, writeFileIfChanged } from "./model-resource-typings.mjs";
13
15
  import { join, resolve } from "path";
14
16
  import { ensureDirectoryAsync } from "@warlock.js/fs";
15
17
  import { constants } from "fs";
@@ -58,6 +60,7 @@ var TypeGenerator = class {
58
60
  this.manifest = null;
59
61
  this.configCache = /* @__PURE__ */ new Map();
60
62
  this.translationSourceFiles = /* @__PURE__ */ new Set();
63
+ this.modelResourceSourceFiles = /* @__PURE__ */ new Set();
61
64
  }
62
65
  /**
63
66
  * Generate all framework type definitions
@@ -83,6 +86,7 @@ var TypeGenerator = class {
83
86
  await this.reconcile();
84
87
  }
85
88
  await this.generateTranslationTypes();
89
+ await this.generateModelResourceTypes();
86
90
  await this.saveManifest();
87
91
  }
88
92
  /**
@@ -278,6 +282,42 @@ ${Array.from(keys).sort().map((key) => ` ${JSON.stringify(key)}: true;`).join
278
282
  await writeFile(join(this.outputDir, "translations.d.ts"), content, "utf-8");
279
283
  devLogSuccess(`Generated translation types: ${keys.size} keys`);
280
284
  }
285
+ /**
286
+ * Generate `model-resources.d.ts`: the `ModelResourceRegistry` augmentation
287
+ * behind `Serialized<Model>`.
288
+ *
289
+ * Reads every discovered model file (`*.model.ts`) and records the ones that
290
+ * declare `static resource = <Identifier>`. Static AST read only, no app
291
+ * module is imported; see `model-resource-typings.ts` for what is skipped.
292
+ * The file is rewritten only when its text changes.
293
+ */
294
+ async generateModelResourceTypes() {
295
+ try {
296
+ const entries = [];
297
+ const sourceFiles = /* @__PURE__ */ new Set();
298
+ const skippedModels = [];
299
+ for (const [path, fileManager] of filesOrchestrator.getFiles()) {
300
+ if (fileManager.type !== "model" || !fileManager.source.includes("resource")) continue;
301
+ const imports = await parseImports(fileManager.source, fileManager.absolutePath);
302
+ const extraction = extractModelResourceEntries({
303
+ source: fileManager.source,
304
+ absolutePath: fileManager.absolutePath,
305
+ resolveImport: (specifier) => imports.get(specifier)?.absolutePath
306
+ });
307
+ if (extraction.entries.length > 0) sourceFiles.add(path);
308
+ for (const entry of extraction.entries) {
309
+ entries.push(entry);
310
+ sourceFiles.add(Path.toRelative(entry.resourceFile));
311
+ }
312
+ for (const skipped of extraction.skipped) skippedModels.push(`${skipped.className} (${skipped.reason})`);
313
+ }
314
+ this.modelResourceSourceFiles = sourceFiles;
315
+ if (await writeFileIfChanged(join(this.outputDir, "model-resources.d.ts"), renderModelResourceRegistry(entries, this.outputDir))) devLogSuccess(`Generated model resource types: ${entries.length} models`);
316
+ if (skippedModels.length > 0) devLogDim(`Model resources not typed (not statically resolvable): ${skippedModels.join(", ")}`);
317
+ } catch (error) {
318
+ devServeLog(`⚠️ Failed to generate model resource types: ${error}`);
319
+ }
320
+ }
281
321
  isLocalesFile(path) {
282
322
  return Path.normalize(path).includes("/utils/locales.");
283
323
  }
@@ -535,12 +575,16 @@ ${allKeys.map((key) => ` "${key}": true;`).join("\n")}
535
575
  */
536
576
  async executeTypingsGenerator(upcomingFiles) {
537
577
  const files = filesOrchestrator.getFiles();
538
- if (!(Array.from(this.translationSourceFiles).some((path) => !files.has(path)) || Array.from(new Set(upcomingFiles)).some((file) => {
578
+ const aKnownTranslationSourceVanished = Array.from(this.translationSourceFiles).some((path) => !files.has(path));
579
+ const aKnownModelResourceSourceVanished = Array.from(this.modelResourceSourceFiles).some((path) => !files.has(path));
580
+ if (!(aKnownTranslationSourceVanished || aKnownModelResourceSourceVanished || Array.from(new Set(upcomingFiles)).some((file) => {
539
581
  const normalizedPath = Path.normalize(file);
540
582
  if (normalizedPath.includes("src/config/")) return true;
541
583
  if (isRouteLocalesJsonPath(normalizedPath)) return true;
542
584
  if (isModuleLocaleDictionaryPath(normalizedPath)) return true;
543
585
  if (this.translationSourceFiles.has(normalizedPath)) return true;
586
+ if (this.modelResourceSourceFiles.has(normalizedPath)) return true;
587
+ if (files.get(normalizedPath)?.type === "model") return true;
544
588
  const fileManager = files.get(normalizedPath);
545
589
  return fileManager !== void 0 && isTranslationRegisteringSource(normalizedPath, fileManager.source);
546
590
  }))) return;