@warlock.js/core 4.16.0 → 5.0.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 (180) hide show
  1. package/CHANGELOG.md +13 -0
  2. package/bin/warlock.js +154 -1
  3. package/esm/application/application.d.mts +65 -1
  4. package/esm/application/application.d.mts.map +1 -1
  5. package/esm/application/application.mjs +62 -0
  6. package/esm/application/application.mjs.map +1 -1
  7. package/esm/application/index.d.mts +1 -1
  8. package/esm/cli/cli-commands.manager.mjs +60 -10
  9. package/esm/cli/cli-commands.manager.mjs.map +1 -1
  10. package/esm/cli/commands/dev-server.command.mjs +1 -0
  11. package/esm/cli/commands/dev-server.command.mjs.map +1 -1
  12. package/esm/cli/commands/doctor/checks/handler-signature.check.mjs +40 -0
  13. package/esm/cli/commands/doctor/checks/handler-signature.check.mjs.map +1 -0
  14. package/esm/cli/commands/doctor/checks/index.mjs +4 -2
  15. package/esm/cli/commands/doctor/checks/index.mjs.map +1 -1
  16. package/esm/commands/cli-command.d.mts +1 -1
  17. package/esm/commands/cli-command.d.mts.map +1 -1
  18. package/esm/commands/cli-command.mjs.map +1 -1
  19. package/esm/commands/types.d.mts +10 -2
  20. package/esm/commands/types.d.mts.map +1 -1
  21. package/esm/config/config-handlers.d.mts +1 -2
  22. package/esm/config/config-handlers.d.mts.map +1 -1
  23. package/esm/config/config-handlers.mjs +3 -2
  24. package/esm/config/config-handlers.mjs.map +1 -1
  25. package/esm/config/locale-configuration.mjs +29 -0
  26. package/esm/config/locale-configuration.mjs.map +1 -0
  27. package/esm/connectors/assert-no-reserved-connector-names.d.mts +7 -0
  28. package/esm/connectors/assert-no-reserved-connector-names.d.mts.map +1 -0
  29. package/esm/connectors/assert-no-reserved-connector-names.mjs +44 -0
  30. package/esm/connectors/assert-no-reserved-connector-names.mjs.map +1 -0
  31. package/esm/connectors/assert-unique-connector-names.d.mts +7 -0
  32. package/esm/connectors/assert-unique-connector-names.d.mts.map +1 -0
  33. package/esm/connectors/assert-unique-connector-names.mjs +20 -0
  34. package/esm/connectors/assert-unique-connector-names.mjs.map +1 -0
  35. package/esm/connectors/connectors-manager.d.mts +38 -0
  36. package/esm/connectors/connectors-manager.d.mts.map +1 -1
  37. package/esm/connectors/connectors-manager.mjs +45 -12
  38. package/esm/connectors/connectors-manager.mjs.map +1 -1
  39. package/esm/connectors/describe-server-address.mjs +75 -0
  40. package/esm/connectors/describe-server-address.mjs.map +1 -0
  41. package/esm/connectors/http-connector.d.mts.map +1 -1
  42. package/esm/connectors/http-connector.mjs +6 -3
  43. package/esm/connectors/http-connector.mjs.map +1 -1
  44. package/esm/connectors/index.d.mts +4 -1
  45. package/esm/connectors/index.mjs +4 -1
  46. package/esm/connectors/register-configured-connectors.d.mts +14 -0
  47. package/esm/connectors/register-configured-connectors.d.mts.map +1 -0
  48. package/esm/connectors/register-configured-connectors.mjs +99 -0
  49. package/esm/connectors/register-configured-connectors.mjs.map +1 -0
  50. package/esm/connectors/socket-connector.d.mts.map +1 -1
  51. package/esm/connectors/socket-connector.mjs +4 -1
  52. package/esm/connectors/socket-connector.mjs.map +1 -1
  53. package/esm/connectors/types.d.mts +76 -1
  54. package/esm/connectors/types.d.mts.map +1 -1
  55. package/esm/connectors/types.mjs.map +1 -1
  56. package/esm/database/models/database-log/database-log.d.mts +50 -2
  57. package/esm/database/models/database-log/database-log.d.mts.map +1 -1
  58. package/esm/database/utils.d.mts +2 -2
  59. package/esm/database/utils.d.mts.map +1 -1
  60. package/esm/dev-server/development-server.mjs +1 -0
  61. package/esm/dev-server/development-server.mjs.map +1 -1
  62. package/esm/dev-server/layer-executor.mjs +2 -1
  63. package/esm/dev-server/layer-executor.mjs.map +1 -1
  64. package/esm/dev-server/read-config-ast.mjs +48 -0
  65. package/esm/dev-server/read-config-ast.mjs.map +1 -0
  66. package/esm/dev-server/run-typings-generation.mjs +18 -0
  67. package/esm/dev-server/run-typings-generation.mjs.map +1 -0
  68. package/esm/dev-server/type-generator.mjs +30 -39
  69. package/esm/dev-server/type-generator.mjs.map +1 -1
  70. package/esm/generations/add-command.action.mjs +169 -1
  71. package/esm/generations/add-command.action.mjs.map +1 -1
  72. package/esm/generations/stubs.mjs +93 -1
  73. package/esm/generations/stubs.mjs.map +1 -1
  74. package/esm/http/context/request-context.d.mts +14 -3
  75. package/esm/http/context/request-context.d.mts.map +1 -1
  76. package/esm/http/context/request-context.mjs +11 -1
  77. package/esm/http/context/request-context.mjs.map +1 -1
  78. package/esm/http/context/request-memo.d.mts +21 -0
  79. package/esm/http/context/request-memo.d.mts.map +1 -0
  80. package/esm/http/context/request-memo.mjs +48 -0
  81. package/esm/http/context/request-memo.mjs.map +1 -0
  82. package/esm/http/database/RequestLog.d.mts +164 -2
  83. package/esm/http/database/RequestLog.d.mts.map +1 -1
  84. package/esm/http/index.d.mts +6 -5
  85. package/esm/http/index.mjs +2 -1
  86. package/esm/http/middleware/cache-response-middleware.d.mts +2 -2
  87. package/esm/http/middleware/cache-response-middleware.d.mts.map +1 -1
  88. package/esm/http/middleware/cache-response-middleware.mjs +1 -1
  89. package/esm/http/middleware/cache-response-middleware.mjs.map +1 -1
  90. package/esm/http/middleware/concurrency-limit.middleware.mjs +1 -1
  91. package/esm/http/middleware/concurrency-limit.middleware.mjs.map +1 -1
  92. package/esm/http/middleware/idempotency.middleware.mjs +1 -1
  93. package/esm/http/middleware/idempotency.middleware.mjs.map +1 -1
  94. package/esm/http/middleware/index.d.mts +1 -1
  95. package/esm/http/middleware/index.mjs +1 -1
  96. package/esm/http/middleware/inject-request-context.d.mts +1 -8
  97. package/esm/http/middleware/inject-request-context.d.mts.map +1 -1
  98. package/esm/http/middleware/inject-request-context.mjs +9 -22
  99. package/esm/http/middleware/inject-request-context.mjs.map +1 -1
  100. package/esm/http/middleware/ip-filter.middleware.mjs +1 -1
  101. package/esm/http/middleware/ip-filter.middleware.mjs.map +1 -1
  102. package/esm/http/middleware/maintenance.middleware.mjs +1 -1
  103. package/esm/http/middleware/maintenance.middleware.mjs.map +1 -1
  104. package/esm/http/middleware/max-body-size.middleware.mjs +1 -1
  105. package/esm/http/middleware/max-body-size.middleware.mjs.map +1 -1
  106. package/esm/http/middleware/rate-limit.middleware.mjs +1 -1
  107. package/esm/http/middleware/rate-limit.middleware.mjs.map +1 -1
  108. package/esm/http/middleware/utils/idempotency-key.d.mts +0 -14
  109. package/esm/http/middleware/utils/idempotency-key.d.mts.map +1 -1
  110. package/esm/http/middleware/utils/idempotency-key.mjs +19 -1
  111. package/esm/http/middleware/utils/idempotency-key.mjs.map +1 -1
  112. package/esm/http/request.d.mts +119 -30
  113. package/esm/http/request.d.mts.map +1 -1
  114. package/esm/http/request.mjs +98 -25
  115. package/esm/http/request.mjs.map +1 -1
  116. package/esm/http/response.mjs +1 -1
  117. package/esm/http/response.mjs.map +1 -1
  118. package/esm/http/types.d.mts +36 -1
  119. package/esm/http/types.d.mts.map +1 -1
  120. package/esm/http/uploaded-file.d.mts +51 -19
  121. package/esm/http/uploaded-file.d.mts.map +1 -1
  122. package/esm/http/uploaded-file.mjs +36 -8
  123. package/esm/http/uploaded-file.mjs.map +1 -1
  124. package/esm/index.d.mts +17 -9
  125. package/esm/index.mjs +10 -4
  126. package/esm/production/build-contributions.mjs +115 -0
  127. package/esm/production/build-contributions.mjs.map +1 -0
  128. package/esm/production/production-builder.mjs +97 -2
  129. package/esm/production/production-builder.mjs.map +1 -1
  130. package/esm/production/resolve-build-config.d.mts +25 -0
  131. package/esm/production/resolve-build-config.d.mts.map +1 -0
  132. package/esm/production/resolve-build-config.mjs +43 -1
  133. package/esm/production/resolve-build-config.mjs.map +1 -1
  134. package/esm/repositories/adapters/cascade/cascade-query-builder.d.mts +1 -1
  135. package/esm/repositories/adapters/cascade/filter-applicator.mjs +20 -9
  136. package/esm/repositories/adapters/cascade/filter-applicator.mjs.map +1 -1
  137. package/esm/restful/restful.d.mts +29 -8
  138. package/esm/restful/restful.d.mts.map +1 -1
  139. package/esm/restful/restful.mjs +31 -13
  140. package/esm/restful/restful.mjs.map +1 -1
  141. package/esm/router/describe-route-for-log.mjs +29 -0
  142. package/esm/router/describe-route-for-log.mjs.map +1 -0
  143. package/esm/router/index.d.mts +3 -1
  144. package/esm/router/index.mjs +2 -0
  145. package/esm/router/log-request-lifecycle.mjs +38 -0
  146. package/esm/router/log-request-lifecycle.mjs.map +1 -0
  147. package/esm/router/positional-handler-diagnostics.d.mts +90 -0
  148. package/esm/router/positional-handler-diagnostics.d.mts.map +1 -0
  149. package/esm/router/positional-handler-diagnostics.mjs +247 -0
  150. package/esm/router/positional-handler-diagnostics.mjs.map +1 -0
  151. package/esm/router/route-registry.d.mts +34 -0
  152. package/esm/router/route-registry.d.mts.map +1 -0
  153. package/esm/router/router.d.mts.map +1 -1
  154. package/esm/router/router.mjs +87 -63
  155. package/esm/router/router.mjs.map +1 -1
  156. package/esm/router/types.d.mts +23 -5
  157. package/esm/router/types.d.mts.map +1 -1
  158. package/esm/storage/storage.d.mts.map +1 -1
  159. package/esm/storage/storage.mjs +1 -1
  160. package/esm/storage/storage.mjs.map +1 -1
  161. package/esm/storage/utils/safe-fetch.d.mts +11 -1
  162. package/esm/storage/utils/safe-fetch.d.mts.map +1 -1
  163. package/esm/storage/utils/safe-fetch.mjs +51 -4
  164. package/esm/storage/utils/safe-fetch.mjs.map +1 -1
  165. package/esm/tests/vitest-setup.mjs +1 -1
  166. package/esm/utils/load-environment.mjs +33 -2
  167. package/esm/utils/load-environment.mjs.map +1 -1
  168. package/esm/utils/types.d.mts +4 -0
  169. package/esm/utils/types.d.mts.map +1 -1
  170. package/esm/validation/validateAll.mjs +4 -1
  171. package/esm/validation/validateAll.mjs.map +1 -1
  172. package/esm/validation/validators/file-validator.d.mts +25 -1
  173. package/esm/validation/validators/file-validator.d.mts.map +1 -1
  174. package/esm/warlock-config/index.mjs +1 -1
  175. package/esm/warlock-config/normalize-build-config.mjs.map +1 -1
  176. package/esm/warlock-config/types.d.mts +36 -2
  177. package/esm/warlock-config/types.d.mts.map +1 -1
  178. package/package.json +15 -12
  179. package/skills/request-memo/SKILL.md +142 -0
  180. package/skills/use-request-locals/SKILL.md +144 -0
@@ -1,3 +1,6 @@
1
+ import { ResolvedBuildConfig } from "../production/resolve-build-config.mjs";
2
+ import { BuildOptions } from "esbuild";
3
+
1
4
  //#region ../core/src/connectors/types.d.ts
2
5
  /**
3
6
  * Connector Interface
@@ -48,7 +51,79 @@ interface Connector {
48
51
  * @returns true if connector should restart
49
52
  */
50
53
  shouldRestart(changedFiles: string[]): boolean;
54
+ /**
55
+ * What this connector contributes to `warlock build`.
56
+ *
57
+ * Read STATICALLY from `warlock.config.ts > connectors` — `warlock build`
58
+ * never calls `boot()`/`start()`, so nothing here may assume a running
59
+ * connector. The same `connectors` key drives both halves of a connector's
60
+ * life — build-time contribution and runtime boot; see
61
+ * {@link ConnectorBuildContribution}.
62
+ */
63
+ readonly build?: ConnectorBuildContribution;
51
64
  }
65
+ /**
66
+ * What a build contribution is handed. Everything it needs to write files
67
+ * and shape the bundle, and nothing that would let it reach the runtime.
68
+ */
69
+ type ConnectorBuildContext = {
70
+ /** Absolute path to `.warlock/production` — deleted after the build */productionDir: string; /** Absolute path to the application root (where `package.json` lives) */
71
+ appRoot: string; /** The build config after framework defaults and user overrides */
72
+ options: ResolvedBuildConfig;
73
+ };
74
+ /**
75
+ * The esbuild options a contributor may patch.
76
+ *
77
+ * Deliberately a narrow `Pick`, not `Partial<BuildOptions>`: `entryPoints`,
78
+ * `tsconfig` and `tsconfigRaw` stay forbidden here for the same reason they
79
+ * are forbidden in the user's `build` block — they re-compile every file in
80
+ * the bundle, workspace packages included (see `ForbiddenBuildOptionError`).
81
+ * A contributor reaching them would reintroduce the failure the user-level
82
+ * guard exists to prevent.
83
+ */
84
+ type ConnectorEsbuildPatch = Pick<BuildOptions, "jsx" | "jsxImportSource" | "define" | "external" | "loader">;
85
+ /**
86
+ * What `generate` may hand back to the builder.
87
+ */
88
+ type ConnectorBuildGenerateResult = {
89
+ /**
90
+ * Lines appended verbatim to section 4 of the generated entry, AFTER the
91
+ * `./routes` import — page registration must see the routes app code
92
+ * collected, mirroring dev's ordering.
93
+ *
94
+ * @example ['await import("./pages");']
95
+ */
96
+ entryImports?: string[]; /** Merged into the esbuild call: defaults < this patch < user `build` */
97
+ esbuild?: ConnectorEsbuildPatch;
98
+ };
99
+ /**
100
+ * A connector's build-time half: two hooks, both awaited, drained in
101
+ * `connectors` array order. A hook that throws fails the build.
102
+ *
103
+ * **This type is closed on purpose**: exactly these two optional function properties and ZERO data-bearing
104
+ * fields. There is deliberately no property where a Vite/babel plugin
105
+ * instance, an alias map or a compiled pipeline could live, so
106
+ * `build: { plugins: [...] }` is a type error rather than something a
107
+ * reviewer has to catch. Anything heavy must be constructed INSIDE a hook,
108
+ * after that hook dynamically imports it — that is what keeps a connector's
109
+ * static import graph out of the runtime closure. The drain mirrors this at
110
+ * read time by rejecting unknown enumerable keys (`assertClosedContribution`):
111
+ * the type narrows, the runtime asserts.
112
+ */
113
+ type ConnectorBuildContribution = {
114
+ /**
115
+ * Write files into `ctx.productionDir` and/or patch the bundle.
116
+ *
117
+ * Runs after the generated-imports check and before esbuild bundles.
118
+ */
119
+ generate?(context: ConnectorBuildContext): Promise<ConnectorBuildGenerateResult | void> | ConnectorBuildGenerateResult | void;
120
+ /**
121
+ * Produce artifacts esbuild does not — e.g. a client bundle.
122
+ *
123
+ * Runs after esbuild and before `.warlock/production` is removed.
124
+ */
125
+ emit?(context: ConnectorBuildContext): Promise<void> | void;
126
+ };
52
127
  type ConnectorName = "logger" | "mailer" | "http" | "database" | "cache" | "storage" | "herald" | "socket" | "notifications" | "access" | "ai" | (string & {});
53
128
  /**
54
129
  * When a connector boots relative to user code (main, routes, events).
@@ -80,5 +155,5 @@ declare enum ConnectorPriority {
80
155
  AI = 10
81
156
  }
82
157
  //#endregion
83
- export { Connector, ConnectorLifecyclePhase, ConnectorName, ConnectorPriority };
158
+ export { Connector, ConnectorBuildContext, ConnectorBuildContribution, ConnectorBuildGenerateResult, ConnectorEsbuildPatch, ConnectorLifecyclePhase, ConnectorName, ConnectorPriority };
84
159
  //# sourceMappingURL=types.d.mts.map
@@ -1 +1 @@
1
- {"version":3,"file":"types.d.mts","names":[],"sources":["../../../../../../../core/src/connectors/types.ts"],"mappings":";;AAIA;;;UAAiB,SAAA;EAgBU;;;EAAA,SAZhB,IAAA,EAAM,aAAA;EAyCH;;;;EAAA,SAnCH,QAAA;EAAA;;;;EAAA,SAMA,cAAA,EAAgB,uBAAA;EAWV;;;EANf,QAAA;EAkBW;;;;EAZX,IAAA,WAAe,OAAA;EAyBqB;AAAA;AAGtC;;EAtBE,KAAA,IAAS,OAAA;EAsBc;AAAA;AAuBzB;;EAvCE,OAAA,IAAW,OAAA;EAwCX;AACI;AAMN;;EAzCE,QAAA,IAAY,OAAA;EAyCe;;;;;EAlC3B,aAAA,CAAc,YAAA;AAAA;AAAA,KAGJ,aAAA;;;;;;AA0CR;;;;aAnBQ,uBAAA;EACV,KAAA;EACA,IAAI;AAAA;;;;aAMM,iBAAA;EACV,MAAA;EACA,MAAA;EACA,QAAA;EACA,YAAA;EACA,KAAA;EACA,IAAA;EACA,OAAA;EACA,MAAA;EACA,aAAA;EACA,MAAA;EACA,EAAA;AAAA"}
1
+ {"version":3,"file":"types.d.mts","names":[],"sources":["../../../../../../../core/src/connectors/types.ts"],"mappings":";;;;;;AAOA;;UAAiB,SAAA;EAIA;;;EAAA,SAAN,IAAA,EAAM,aAAA;EAmCJ;;;;EAAA,SA7BF,QAAA;EANA;;;;EAAA,SAYA,cAAA,EAAgB,uBAAA;EAKzB;;;EAAA,QAAA;EAYS;;;;EANT,IAAA,WAAe,OAAA;EAyBf;;;;EAnBA,KAAA,IAAS,OAAA;EA8BkC;AAO7C;;;EA/BE,OAAA,IAAW,OAAA;EAiCX;;;;EA3BA,QAAA,IAAY,OAAA;EA+BgB;AAa9B;;;;EArCE,aAAA,CAAc,YAAA;EA6CJ;;;;;;;;AAUqB;EAVrB,SAlCD,KAAA,GAAQ,0BAAA;AAAA;;;;;KAOP,qBAAA;EAqEK,uEAnEf,aAAA,UAmE8C;EAjE9C,OAAA,UAwDA;EAtDA,OAAA,EAAS,mBAAmB;AAAA;;;;;;;;;AA+DkB;AAGhD;KArDY,qBAAA,GAAwB,IAAI,CACtC,YAAA;;;AAoDuB;KA7Cb,4BAAA;EAoEuB;;;AAE7B;AAMN;;;EApEE,YAAA,aAqEA;EAnEA,OAAA,GAAU,qBAAqB;AAAA;;;;;;;;;;AA6E7B;;;;;KA5DQ,0BAAA;;;;;;EAMV,QAAA,EACE,OAAA,EAAS,qBAAA,GACR,OAAA,CAAQ,4BAAA,WAAuC,4BAAA;;;;;;EAOlD,IAAA,EAAM,OAAA,EAAS,qBAAA,GAAwB,OAAA;AAAA;AAAA,KAG7B,aAAA;;;;;;;;;;aAuBA,uBAAA;EACV,KAAA;EACA,IAAI;AAAA;;;;aAMM,iBAAA;EACV,MAAA;EACA,MAAA;EACA,QAAA;EACA,YAAA;EACA,KAAA;EACA,IAAA;EACA,OAAA;EACA,MAAA;EACA,aAAA;EACA,MAAA;EACA,EAAA;AAAA"}
@@ -1 +1 @@
1
- {"version":3,"file":"types.mjs","names":[],"sources":["../../../../../../../core/src/connectors/types.ts"],"sourcesContent":["/**\n * Connector Interface\n * All service connectors (Database, HTTP, Cache, etc.) must implement this interface\n */\nexport interface Connector {\n /**\n * Unique name of the connector\n */\n readonly name: ConnectorName;\n\n /**\n * Priority for initialization order\n * Lower numbers initialize first (e.g., Database: 1, HTTP: 3)\n */\n readonly priority: number;\n\n /**\n * Phase the connector boots in, relative to user code.\n * See `ConnectorLifecyclePhase` for semantics.\n */\n readonly lifecyclePhase: ConnectorLifecyclePhase;\n\n /**\n * Whether the connector is currently active/connected\n */\n isActive(): boolean;\n\n /**\n * Boot the connector\n * Called during server startup before starting the connector\n */\n boot(): void | Promise<void>;\n\n /**\n * Initialize the connector\n * Called during server startup\n */\n start(): Promise<void>;\n\n /**\n * Restart the connector\n * Called when watched files change\n */\n restart(): Promise<void>;\n\n /**\n * Gracefully shutdown the connector\n * Called during server shutdown\n */\n shutdown(): Promise<void>;\n\n /**\n * Determine if this connector needs restart based on changed files\n * @param changedFiles Array of relative file paths that changed\n * @returns true if connector should restart\n */\n shouldRestart(changedFiles: string[]): boolean;\n}\n\nexport type ConnectorName =\n | \"logger\"\n | \"mailer\"\n | \"http\"\n | \"database\"\n | \"cache\"\n | \"storage\"\n | \"herald\"\n | \"socket\"\n | \"notifications\"\n | \"access\"\n | \"ai\"\n | (string & {});\n\n/**\n * When a connector boots relative to user code (main, routes, events).\n *\n * - `Early`: before user code is imported. For services user code\n * needs at import time (database, cache, logger, storage, mailer).\n * - `Late`: after user code is imported. For services that bind to\n * things user code registered (http scans the router; socket\n * depends on http's instance).\n */\nexport enum ConnectorLifecyclePhase {\n Early = \"early\",\n Late = \"late\",\n}\n\n/**\n * Connector priority constants\n */\nexport enum ConnectorPriority {\n LOGGER = 0,\n MAILER = 1,\n DATABASE = 2,\n COMMUNICATOR = 3,\n CACHE = 4,\n HTTP = 5,\n STORAGE = 6,\n SOCKET = 7,\n NOTIFICATIONS = 8,\n ACCESS = 9,\n AI = 10,\n}\n"],"mappings":";;;;;;;;;;AAkFA,IAAY,0BAAL;CACL;CACA;;AACF;;;;AAKA,IAAY,oBAAL;CACL;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;;AACF"}
1
+ {"version":3,"file":"types.mjs","names":[],"sources":["../../../../../../../core/src/connectors/types.ts"],"sourcesContent":["import type { BuildOptions } from \"esbuild\";\nimport type { ResolvedBuildConfig } from \"../production/resolve-build-config\";\n\n/**\n * Connector Interface\n * All service connectors (Database, HTTP, Cache, etc.) must implement this interface\n */\nexport interface Connector {\n /**\n * Unique name of the connector\n */\n readonly name: ConnectorName;\n\n /**\n * Priority for initialization order\n * Lower numbers initialize first (e.g., Database: 1, HTTP: 3)\n */\n readonly priority: number;\n\n /**\n * Phase the connector boots in, relative to user code.\n * See `ConnectorLifecyclePhase` for semantics.\n */\n readonly lifecyclePhase: ConnectorLifecyclePhase;\n\n /**\n * Whether the connector is currently active/connected\n */\n isActive(): boolean;\n\n /**\n * Boot the connector\n * Called during server startup before starting the connector\n */\n boot(): void | Promise<void>;\n\n /**\n * Initialize the connector\n * Called during server startup\n */\n start(): Promise<void>;\n\n /**\n * Restart the connector\n * Called when watched files change\n */\n restart(): Promise<void>;\n\n /**\n * Gracefully shutdown the connector\n * Called during server shutdown\n */\n shutdown(): Promise<void>;\n\n /**\n * Determine if this connector needs restart based on changed files\n * @param changedFiles Array of relative file paths that changed\n * @returns true if connector should restart\n */\n shouldRestart(changedFiles: string[]): boolean;\n\n /**\n * What this connector contributes to `warlock build`.\n *\n * Read STATICALLY from `warlock.config.ts > connectors` — `warlock build`\n * never calls `boot()`/`start()`, so nothing here may assume a running\n * connector. The same `connectors` key drives both halves of a connector's\n * life — build-time contribution and runtime boot; see\n * {@link ConnectorBuildContribution}.\n */\n readonly build?: ConnectorBuildContribution;\n}\n\n/**\n * What a build contribution is handed. Everything it needs to write files\n * and shape the bundle, and nothing that would let it reach the runtime.\n */\nexport type ConnectorBuildContext = {\n /** Absolute path to `.warlock/production` — deleted after the build */\n productionDir: string;\n /** Absolute path to the application root (where `package.json` lives) */\n appRoot: string;\n /** The build config after framework defaults and user overrides */\n options: ResolvedBuildConfig;\n};\n\n/**\n * The esbuild options a contributor may patch.\n *\n * Deliberately a narrow `Pick`, not `Partial<BuildOptions>`: `entryPoints`,\n * `tsconfig` and `tsconfigRaw` stay forbidden here for the same reason they\n * are forbidden in the user's `build` block — they re-compile every file in\n * the bundle, workspace packages included (see `ForbiddenBuildOptionError`).\n * A contributor reaching them would reintroduce the failure the user-level\n * guard exists to prevent.\n */\nexport type ConnectorEsbuildPatch = Pick<\n BuildOptions,\n \"jsx\" | \"jsxImportSource\" | \"define\" | \"external\" | \"loader\"\n>;\n\n/**\n * What `generate` may hand back to the builder.\n */\nexport type ConnectorBuildGenerateResult = {\n /**\n * Lines appended verbatim to section 4 of the generated entry, AFTER the\n * `./routes` import — page registration must see the routes app code\n * collected, mirroring dev's ordering.\n *\n * @example ['await import(\"./pages\");']\n */\n entryImports?: string[];\n /** Merged into the esbuild call: defaults < this patch < user `build` */\n esbuild?: ConnectorEsbuildPatch;\n};\n\n/**\n * A connector's build-time half: two hooks, both awaited, drained in\n * `connectors` array order. A hook that throws fails the build.\n *\n * **This type is closed on purpose**: exactly these two optional function properties and ZERO data-bearing\n * fields. There is deliberately no property where a Vite/babel plugin\n * instance, an alias map or a compiled pipeline could live, so\n * `build: { plugins: [...] }` is a type error rather than something a\n * reviewer has to catch. Anything heavy must be constructed INSIDE a hook,\n * after that hook dynamically imports it — that is what keeps a connector's\n * static import graph out of the runtime closure. The drain mirrors this at\n * read time by rejecting unknown enumerable keys (`assertClosedContribution`):\n * the type narrows, the runtime asserts.\n */\nexport type ConnectorBuildContribution = {\n /**\n * Write files into `ctx.productionDir` and/or patch the bundle.\n *\n * Runs after the generated-imports check and before esbuild bundles.\n */\n generate?(\n context: ConnectorBuildContext,\n ): Promise<ConnectorBuildGenerateResult | void> | ConnectorBuildGenerateResult | void;\n\n /**\n * Produce artifacts esbuild does not — e.g. a client bundle.\n *\n * Runs after esbuild and before `.warlock/production` is removed.\n */\n emit?(context: ConnectorBuildContext): Promise<void> | void;\n};\n\nexport type ConnectorName =\n | \"logger\"\n | \"mailer\"\n | \"http\"\n | \"database\"\n | \"cache\"\n | \"storage\"\n | \"herald\"\n | \"socket\"\n | \"notifications\"\n | \"access\"\n | \"ai\"\n | (string & {});\n\n/**\n * When a connector boots relative to user code (main, routes, events).\n *\n * - `Early`: before user code is imported. For services user code\n * needs at import time (database, cache, logger, storage, mailer).\n * - `Late`: after user code is imported. For services that bind to\n * things user code registered (http scans the router; socket\n * depends on http's instance).\n */\nexport enum ConnectorLifecyclePhase {\n Early = \"early\",\n Late = \"late\",\n}\n\n/**\n * Connector priority constants\n */\nexport enum ConnectorPriority {\n LOGGER = 0,\n MAILER = 1,\n DATABASE = 2,\n COMMUNICATOR = 3,\n CACHE = 4,\n HTTP = 5,\n STORAGE = 6,\n SOCKET = 7,\n NOTIFICATIONS = 8,\n ACCESS = 9,\n AI = 10,\n}\n"],"mappings":";;;;;;;;;;AA4KA,IAAY,0BAAL;CACL;CACA;;AACF;;;;AAKA,IAAY,oBAAL;CACL;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;;AACF"}
@@ -2,7 +2,31 @@ import { Infer } from "@warlock.js/seal";
2
2
  import { Model } from "@warlock.js/cascade";
3
3
 
4
4
  //#region ../core/src/database/models/database-log/database-log.d.ts
5
- declare const schema: any;
5
+ declare const schema: import("@warlock.js/seal").ObjectValidator<{
6
+ module: import("@warlock.js/seal").StringValidator & import("@warlock.js/seal").StandardSchemaV1<string, string>;
7
+ action: import("@warlock.js/seal").StringValidator & import("@warlock.js/seal").StandardSchemaV1<string, string>;
8
+ message: import("@warlock.js/seal").StringValidator & import("@warlock.js/seal").StandardSchemaV1<string, string>;
9
+ trace: import("@warlock.js/seal").RecordValidator & {
10
+ valueValidator: import("@warlock.js/seal").AnyValidator & import("@warlock.js/seal").StandardSchemaV1<any, any>;
11
+ } & import("@warlock.js/seal").StandardSchemaV1<Record<string, any>, Record<string, any>>;
12
+ level: import("@warlock.js/seal").StringValidator & import("@warlock.js/seal").StandardSchemaV1<string, string>;
13
+ }> & import("@warlock.js/seal").StandardSchemaV1<import("@warlock.js/seal").InferInputObjectShape<{
14
+ module: import("@warlock.js/seal").StringValidator & import("@warlock.js/seal").StandardSchemaV1<string, string>;
15
+ action: import("@warlock.js/seal").StringValidator & import("@warlock.js/seal").StandardSchemaV1<string, string>;
16
+ message: import("@warlock.js/seal").StringValidator & import("@warlock.js/seal").StandardSchemaV1<string, string>;
17
+ trace: import("@warlock.js/seal").RecordValidator & {
18
+ valueValidator: import("@warlock.js/seal").AnyValidator & import("@warlock.js/seal").StandardSchemaV1<any, any>;
19
+ } & import("@warlock.js/seal").StandardSchemaV1<Record<string, any>, Record<string, any>>;
20
+ level: import("@warlock.js/seal").StringValidator & import("@warlock.js/seal").StandardSchemaV1<string, string>;
21
+ }>, import("@warlock.js/seal").InferInputObjectShape<{
22
+ module: import("@warlock.js/seal").StringValidator & import("@warlock.js/seal").StandardSchemaV1<string, string>;
23
+ action: import("@warlock.js/seal").StringValidator & import("@warlock.js/seal").StandardSchemaV1<string, string>;
24
+ message: import("@warlock.js/seal").StringValidator & import("@warlock.js/seal").StandardSchemaV1<string, string>;
25
+ trace: import("@warlock.js/seal").RecordValidator & {
26
+ valueValidator: import("@warlock.js/seal").AnyValidator & import("@warlock.js/seal").StandardSchemaV1<any, any>;
27
+ } & import("@warlock.js/seal").StandardSchemaV1<Record<string, any>, Record<string, any>>;
28
+ level: import("@warlock.js/seal").StringValidator & import("@warlock.js/seal").StandardSchemaV1<string, string>;
29
+ }>>;
6
30
  type LogSchema = Infer.Output<typeof schema>;
7
31
  declare class DatabaseLogModel extends Model<LogSchema> {
8
32
  /**
@@ -12,7 +36,31 @@ declare class DatabaseLogModel extends Model<LogSchema> {
12
36
  /**
13
37
  * {@inheritdoc}
14
38
  */
15
- static schema: any;
39
+ static schema: import("@warlock.js/seal").ObjectValidator<{
40
+ module: import("@warlock.js/seal").StringValidator & import("@warlock.js/seal").StandardSchemaV1<string, string>;
41
+ action: import("@warlock.js/seal").StringValidator & import("@warlock.js/seal").StandardSchemaV1<string, string>;
42
+ message: import("@warlock.js/seal").StringValidator & import("@warlock.js/seal").StandardSchemaV1<string, string>;
43
+ trace: import("@warlock.js/seal").RecordValidator & {
44
+ valueValidator: import("@warlock.js/seal").AnyValidator & import("@warlock.js/seal").StandardSchemaV1<any, any>;
45
+ } & import("@warlock.js/seal").StandardSchemaV1<Record<string, any>, Record<string, any>>;
46
+ level: import("@warlock.js/seal").StringValidator & import("@warlock.js/seal").StandardSchemaV1<string, string>;
47
+ }> & import("@warlock.js/seal").StandardSchemaV1<import("@warlock.js/seal").InferInputObjectShape<{
48
+ module: import("@warlock.js/seal").StringValidator & import("@warlock.js/seal").StandardSchemaV1<string, string>;
49
+ action: import("@warlock.js/seal").StringValidator & import("@warlock.js/seal").StandardSchemaV1<string, string>;
50
+ message: import("@warlock.js/seal").StringValidator & import("@warlock.js/seal").StandardSchemaV1<string, string>;
51
+ trace: import("@warlock.js/seal").RecordValidator & {
52
+ valueValidator: import("@warlock.js/seal").AnyValidator & import("@warlock.js/seal").StandardSchemaV1<any, any>;
53
+ } & import("@warlock.js/seal").StandardSchemaV1<Record<string, any>, Record<string, any>>;
54
+ level: import("@warlock.js/seal").StringValidator & import("@warlock.js/seal").StandardSchemaV1<string, string>;
55
+ }>, import("@warlock.js/seal").InferInputObjectShape<{
56
+ module: import("@warlock.js/seal").StringValidator & import("@warlock.js/seal").StandardSchemaV1<string, string>;
57
+ action: import("@warlock.js/seal").StringValidator & import("@warlock.js/seal").StandardSchemaV1<string, string>;
58
+ message: import("@warlock.js/seal").StringValidator & import("@warlock.js/seal").StandardSchemaV1<string, string>;
59
+ trace: import("@warlock.js/seal").RecordValidator & {
60
+ valueValidator: import("@warlock.js/seal").AnyValidator & import("@warlock.js/seal").StandardSchemaV1<any, any>;
61
+ } & import("@warlock.js/seal").StandardSchemaV1<Record<string, any>, Record<string, any>>;
62
+ level: import("@warlock.js/seal").StringValidator & import("@warlock.js/seal").StandardSchemaV1<string, string>;
63
+ }>>;
16
64
  }
17
65
  //#endregion
18
66
  export { DatabaseLogModel };
@@ -1 +1 @@
1
- {"version":3,"file":"database-log.d.mts","names":[],"sources":["../../../../../../../../../core/src/database/models/database-log/database-log.ts"],"mappings":";;;;cAGM,MAAA;AAAA,KAQD,SAAA,GAAY,KAAA,CAAM,MAAM,QAAQ,MAAA;AAAA,cAExB,gBAAA,SAAyB,KAAK,CAAC,SAAA;EAJ1C;;;EAAA,OAQc,KAAA;EANX;;;EAAA,OAWW,MAAA;AAAA"}
1
+ {"version":3,"file":"database-log.d.mts","names":[],"sources":["../../../../../../../../../core/src/database/models/database-log/database-log.ts"],"mappings":";;;;cAGM,MAAA,6BAAM,eAAA;;;;;;;;;;;;;;;;;;;;;;;;;KAQP,SAAA,GAAY,KAAA,CAAM,MAAM,QAAQ,MAAA;AAAA,cAExB,gBAAA,SAAyB,KAAA,CAAM,SAAA;;;;SAI5B,KAAA;;;;SAKA,MAAA,6BAAM,eAAA"}
@@ -1,11 +1,11 @@
1
- import { SchemaContext } from "@warlock.js/seal";
1
+ import { ComputedCallback, SchemaContext } from "@warlock.js/seal";
2
2
  import { Model } from "@warlock.js/cascade";
3
3
 
4
4
  //#region ../core/src/database/utils.d.ts
5
5
  /**
6
6
  * Hash password on saving if password changes
7
7
  */
8
- declare const useHashedPassword: () => any;
8
+ declare const useHashedPassword: () => import("@warlock.js/seal").TransformerCallback;
9
9
  type ComputedCallbackModel = (data: any, model: Model, context: SchemaContext) => any | Promise<any>;
10
10
  /**
11
11
  * Generate computed value based on other fields
@@ -1 +1 @@
1
- {"version":3,"file":"utils.d.mts","names":[],"sources":["../../../../../../../core/src/database/utils.ts"],"mappings":";;;;;;AASA;cAAa,iBAAA;AAAA,KASR,qBAAA,IACH,IAAA,OACA,KAAA,EAAO,KAAA,EACP,OAAA,EAAS,aAAA,WACA,OAAA;;AANP;AAAC;iBAWW,gBAAA,CAAiB,QAAA,EAAU,qBAAA,GAAqB,gBAAA;;;;iBAWhD,eAAA,CAAgB,KAAA,WAAiB,KAAA,0BAAuC,gBAAA"}
1
+ {"version":3,"file":"utils.d.mts","names":[],"sources":["../../../../../../../core/src/database/utils.ts"],"mappings":";;;;;;AASA;cAAa,iBAAA,mCAAiB,mBAO1B;AAAA,KAEC,qBAAA,IACH,IAAA,OACA,KAAA,EAAO,KAAA,EACP,OAAA,EAAS,aAAA,WACA,OAAA;;AANP;AAAC;iBAWW,gBAAA,CAAiB,QAAA,EAAU,qBAAA,GAAqB,gBAAA;;;;iBAWhD,eAAA,CAAgB,KAAA,WAAiB,KAAA,0BAAuC,gBAAA"}
@@ -41,6 +41,7 @@ var DevelopmentServer = class {
41
41
  this.setupEventListeners();
42
42
  await this.autoDiscoverFiles();
43
43
  await filesOrchestrator.moduleLoader.loadAll();
44
+ await Application.runStartupValidators();
44
45
  await connectorsManager.startPhase("late");
45
46
  this.layerExecutor = new LayerExecutor(filesOrchestrator.getDependencyGraph(), filesOrchestrator.specialFilesCollector, filesOrchestrator.moduleLoader, (absolutePath) => filesOrchestrator.bumpVersion(absolutePath), () => filesOrchestrator.flushVersionBumps());
46
47
  this.running = true;
@@ -1 +1 @@
1
- {"version":3,"file":"development-server.mjs","names":[],"sources":["../../../../../../../core/src/dev-server/development-server.ts"],"sourcesContent":["import { colors } from \"@mongez/copper\";\r\nimport events from \"@mongez/events\";\r\nimport { fileExistsAsync, unlinkAsync } from \"@warlock.js/fs\";\r\nimport { Application } from \"../application\";\r\nimport { connectorsManager } from \"../connectors/connectors-manager\";\r\nimport { ConnectorLifecyclePhase } from \"../connectors/types\";\r\nimport { warlockConfigManager } from \"../warlock-config\";\r\nimport { devLogInfo, devLogReady, devLogSection, devLogWarn, devServeLog } from \"./dev-logger\";\r\nimport { filesOrchestrator } from \"./files-orchestrator\";\r\nimport { MANIFEST_PATH } from \"./flags\";\r\nimport { LayerExecutor } from \"./layer-executor\";\r\nimport { restartDevServer } from \"./restart-dev-server\";\r\nimport { devServerShortcuts } from \"./shortcuts\";\r\nimport type { StartDevServerOptions } from \"./start-development-server\";\r\nimport { typeGenerator } from \"./type-generator\";\r\n\r\ntype Batch = { added: string[]; changed: string[]; deleted: string[] };\r\n\r\n/**\r\n * Top-level coordinator for `warlock dev`. Wires the file orchestrator, the\r\n * connectors, and the layer executor together, and listens for the watcher's\r\n * batched events to drive HMR.\r\n */\r\nexport class DevelopmentServer {\r\n private layerExecutor?: LayerExecutor;\r\n private running = false;\r\n private readonly options: StartDevServerOptions;\r\n\r\n public constructor(options: StartDevServerOptions = {}) {\r\n this.options = options;\r\n devLogSection(\"Starting Development Server...\");\r\n }\r\n\r\n public async start(): Promise<void> {\r\n try {\r\n const startedAt = performance.now();\r\n\r\n // --fresh deletes the manifest so reconciliation re-parses every file\r\n // from disk. Transpile caching is owned by the loader hook (in-memory).\r\n if (this.options.fresh && (await fileExistsAsync(MANIFEST_PATH))) {\r\n await unlinkAsync(MANIFEST_PATH);\r\n devServeLog(colors.cyanBright(\"Cleared manifest (--fresh)\"));\r\n }\r\n\r\n await filesOrchestrator.init();\r\n await filesOrchestrator.initializeAll();\r\n await filesOrchestrator.watchFiles();\r\n\r\n filesOrchestrator.specialFilesCollector.collect(filesOrchestrator.getFiles());\r\n\r\n this.setupEventListeners();\r\n\r\n // Decorator-driven registries (models, etc.) must be populated before\r\n // routes/services can resolve symbols by name.\r\n await this.autoDiscoverFiles();\r\n\r\n await filesOrchestrator.moduleLoader.loadAll();\r\n\r\n // Late-phase connectors (http, socket) bind after app code has\r\n // registered routes/listeners.\r\n await connectorsManager.startPhase(ConnectorLifecyclePhase.Late);\r\n\r\n this.layerExecutor = new LayerExecutor(\r\n filesOrchestrator.getDependencyGraph(),\r\n filesOrchestrator.specialFilesCollector,\r\n filesOrchestrator.moduleLoader,\r\n (absolutePath) => filesOrchestrator.bumpVersion(absolutePath),\r\n () => filesOrchestrator.flushVersionBumps(),\r\n );\r\n\r\n this.running = true;\r\n\r\n const duration = performance.now() - startedAt;\r\n devLogReady(`Development Server is ready in ${colors.greenBright(parseDuration(duration))}`);\r\n\r\n // App modules are loaded and both connector phases are active — signal a\r\n // complete boot so `Application.onceBooted(...)` listeners fire.\r\n Application.markBooted({\r\n environment: Application.environment,\r\n runtimeStrategy: Application.runtimeStrategy,\r\n bootDurationMs: duration,\r\n });\r\n\r\n // Precedence: explicit CLI option > devServer.* config > default.\r\n const devServerConfig = await warlockConfigManager.get(\"devServer\");\r\n const generateTypings =\r\n this.options.generateTypings ?? devServerConfig?.generateTypings ?? true;\r\n const healthCheckers = this.options.healthCheckers ?? devServerConfig?.healthCheckers ?? true;\r\n\r\n if (generateTypings) typeGenerator.executeGenerateAllCommand();\r\n\r\n if (healthCheckers) {\r\n filesOrchestrator.startCheckingHealth(healthCheckers === true ? undefined : healthCheckers);\r\n }\r\n } catch (error) {\r\n devServeLog(colors.redBright(`Failed to start Development Server: ${error}`));\r\n await this.shutdown();\r\n throw error;\r\n }\r\n }\r\n\r\n /**\r\n * Eagerly import files whose decorators populate global registries so any\r\n * symbol-by-name resolution later in boot finds them.\r\n */\r\n private async autoDiscoverFiles(): Promise<void> {\r\n const discoveryTypes = [\"model\"] as const;\r\n for (const file of filesOrchestrator.files.values()) {\r\n if (file.type && (discoveryTypes as readonly string[]).includes(file.type)) {\r\n await filesOrchestrator.moduleLoader.loadModule(file, file.type);\r\n }\r\n }\r\n }\r\n\r\n private setupEventListeners(): void {\r\n events.on(\"dev-server:batch-complete\", (batch: Batch) => this.handleBatchComplete(batch));\r\n }\r\n\r\n private async handleBatchComplete(batch: Batch): Promise<void> {\r\n if (!this.running || !this.layerExecutor) return;\r\n\r\n // warlock.config.ts holds settings read at boot (CLI commands, build\r\n // options, watch patterns, scheduled jobs) and .env feeds every config\r\n // that reads it. Neither can be hot-reloaded without leaving running\r\n // services configured with stale values, so the only honest response is\r\n // a full restart.\r\n const restartTrigger = this.findRestartTrigger(batch);\r\n\r\n if (restartTrigger) {\r\n // On success this never comes back — the process exits and the\r\n // supervisor replaces it. Reaching the next line means the restart was\r\n // declined by config or wasn't possible, so we fall through and still\r\n // hot-reload whatever ordinary code shared the batch.\r\n await this.restartForConfigChange(restartTrigger);\r\n }\r\n\r\n // No-op saves (an editor that fsyncs without a content write) are already\r\n // filtered upstream by the file hash in FileEventHandler, so batch.changed\r\n // only contains genuinely-changed paths by the time it reaches here.\r\n\r\n const total = batch.added.length + batch.changed.length + batch.deleted.length;\r\n if (total === 0) return;\r\n\r\n // Boot-time files still ride along in `changed` when a restart was\r\n // declined (`restartOnConfigChange: false`) or wasn't possible — they are\r\n // never hot-reloaded, so keep them out of the reload set either way.\r\n const codeFiles = [...batch.added, ...batch.changed].filter(\r\n (p) => !isEnvPath(p) && p !== \"warlock.config.ts\",\r\n );\r\n\r\n try {\r\n await this.layerExecutor.executeBatchReload(\r\n codeFiles,\r\n filesOrchestrator.getFiles(),\r\n batch.deleted,\r\n batch.changed,\r\n );\r\n\r\n typeGenerator.executeTypingsGenerator([...batch.added, ...batch.changed]);\r\n\r\n filesOrchestrator.checkHealth(batch);\r\n } catch (error) {\r\n devServeLog(colors.redBright(`Failed to execute batch reload: ${error}`));\r\n }\r\n }\r\n\r\n /**\r\n * The boot-time file in this batch that can only be applied by restarting,\r\n * or `undefined` when the batch is ordinary application code.\r\n */\r\n private findRestartTrigger(batch: Batch): string | undefined {\r\n if (batch.changed.includes(\"warlock.config.ts\")) {\r\n return \"warlock.config.ts\";\r\n }\r\n\r\n return [...batch.added, ...batch.changed].find(isEnvPath);\r\n }\r\n\r\n /**\r\n * Restart so a changed boot-time file actually takes effect.\r\n *\r\n * Opt out with `devServer.restartOnConfigChange: false` and the old\r\n * behaviour returns: a warning telling you to restart yourself. If the\r\n * restart can't be performed at all (no supervisor, a shutdown that threw),\r\n * `restartDevServer` reports it and we fall back to the same warning rather\r\n * than leaving the server running against config it isn't using.\r\n */\r\n private async restartForConfigChange(file: string): Promise<void> {\r\n const devServerConfig = await warlockConfigManager.get(\"devServer\");\r\n\r\n if (devServerConfig?.restartOnConfigChange === false) {\r\n devLogWarn(`${file} changed — restart the dev server to apply.`);\r\n return;\r\n }\r\n\r\n devLogInfo(`${file} changed — restarting to apply.`);\r\n\r\n const restarted = await restartDevServer(this);\r\n\r\n if (!restarted) {\r\n devLogWarn(`${file} changed — restart the dev server to apply.`);\r\n }\r\n }\r\n\r\n public async shutdown(): Promise<void> {\r\n // Always hand the terminal back, even on a repeat/no-op shutdown — a\r\n // process that exits while stdin is still in raw mode leaves the user's\r\n // shell without line editing or Ctrl+C.\r\n devServerShortcuts.release();\r\n\r\n if (!this.running) return;\r\n devServeLog(colors.redBright(\"Shutting down Development Server...\"));\r\n this.running = false;\r\n await connectorsManager.shutdown();\r\n devServeLog(colors.greenBright(\"Development Server stopped\"));\r\n }\r\n\r\n public isRunning(): boolean {\r\n return this.running;\r\n }\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\nfunction parseDuration(ms: number): string {\r\n if (ms < 1000) return `${ms.toFixed(2)}ms`;\r\n if (ms > 60_000) return `${(ms / 60_000).toFixed(2)}m`;\r\n return `${(ms / 1000).toFixed(2)}s`;\r\n}\r\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;AAuBA,IAAa,oBAAb,MAA+B;CAK7B,AAAO,YAAY,UAAiC,CAAC,GAAG;iBAHtC;EAIhB,KAAK,UAAU;EACf,cAAc,gCAAgC;CAChD;CAEA,MAAa,QAAuB;EAClC,IAAI;GACF,MAAM,YAAY,YAAY,IAAI;GAIlC,IAAI,KAAK,QAAQ,SAAU,MAAM,gBAAgB,aAAa,GAAI;IAChE,MAAM,YAAY,aAAa;IAC/B,YAAY,OAAO,WAAW,4BAA4B,CAAC;GAC7D;GAEA,MAAM,kBAAkB,KAAK;GAC7B,MAAM,kBAAkB,cAAc;GACtC,MAAM,kBAAkB,WAAW;GAEnC,kBAAkB,sBAAsB,QAAQ,kBAAkB,SAAS,CAAC;GAE5E,KAAK,oBAAoB;GAIzB,MAAM,KAAK,kBAAkB;GAE7B,MAAM,kBAAkB,aAAa,QAAQ;GAI7C,MAAM,kBAAkB,iBAAuC;GAE/D,KAAK,gBAAgB,IAAI,cACvB,kBAAkB,mBAAmB,GACrC,kBAAkB,uBAClB,kBAAkB,eACjB,iBAAiB,kBAAkB,YAAY,YAAY,SACtD,kBAAkB,kBAAkB,CAC5C;GAEA,KAAK,UAAU;GAEf,MAAM,WAAW,YAAY,IAAI,IAAI;GACrC,YAAY,kCAAkC,OAAO,YAAY,cAAc,QAAQ,C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js","names":[],"sources":["../../../../../../../core/src/dev-server/development-server.ts"],"sourcesContent":["import { colors } from \"@mongez/copper\";\r\nimport events from \"@mongez/events\";\r\nimport { fileExistsAsync, unlinkAsync } from \"@warlock.js/fs\";\r\nimport { Application } from \"../application\";\r\nimport { connectorsManager } from \"../connectors/connectors-manager\";\r\nimport { ConnectorLifecyclePhase } from \"../connectors/types\";\r\nimport { warlockConfigManager } from \"../warlock-config\";\r\nimport { devLogInfo, devLogReady, devLogSection, devLogWarn, devServeLog } from \"./dev-logger\";\r\nimport { filesOrchestrator } from \"./files-orchestrator\";\r\nimport { MANIFEST_PATH } from \"./flags\";\r\nimport { LayerExecutor } from \"./layer-executor\";\r\nimport { restartDevServer } from \"./restart-dev-server\";\r\nimport { devServerShortcuts } from \"./shortcuts\";\r\nimport type { StartDevServerOptions } from \"./start-development-server\";\r\nimport { typeGenerator } from \"./type-generator\";\r\n\r\ntype Batch = { added: string[]; changed: string[]; deleted: string[] };\r\n\r\n/**\r\n * Top-level coordinator for `warlock dev`. Wires the file orchestrator, the\r\n * connectors, and the layer executor together, and listens for the watcher's\r\n * batched events to drive HMR.\r\n */\r\nexport class DevelopmentServer {\r\n private layerExecutor?: LayerExecutor;\r\n private running = false;\r\n private readonly options: StartDevServerOptions;\r\n\r\n public constructor(options: StartDevServerOptions = {}) {\r\n this.options = options;\r\n devLogSection(\"Starting Development Server...\");\r\n }\r\n\r\n public async start(): Promise<void> {\r\n try {\r\n const startedAt = performance.now();\r\n\r\n // --fresh deletes the manifest so reconciliation re-parses every file\r\n // from disk. Transpile caching is owned by the loader hook (in-memory).\r\n if (this.options.fresh && (await fileExistsAsync(MANIFEST_PATH))) {\r\n await unlinkAsync(MANIFEST_PATH);\r\n devServeLog(colors.cyanBright(\"Cleared manifest (--fresh)\"));\r\n }\r\n\r\n await filesOrchestrator.init();\r\n await filesOrchestrator.initializeAll();\r\n await filesOrchestrator.watchFiles();\r\n\r\n filesOrchestrator.specialFilesCollector.collect(filesOrchestrator.getFiles());\r\n\r\n this.setupEventListeners();\r\n\r\n // Decorator-driven registries (models, etc.) must be populated before\r\n // routes/services can resolve symbols by name.\r\n await this.autoDiscoverFiles();\r\n\r\n await filesOrchestrator.moduleLoader.loadAll();\r\n\r\n // A rejecting validator (Application.onValidateBoot) must abort boot\r\n // before late-phase connectors bind a port — this is what makes the\r\n // hook actually prevent serving instead of merely being defined.\r\n await Application.runStartupValidators();\r\n\r\n // Late-phase connectors (http, socket) bind after app code has\r\n // registered routes/listeners.\r\n await connectorsManager.startPhase(ConnectorLifecyclePhase.Late);\r\n\r\n this.layerExecutor = new LayerExecutor(\r\n filesOrchestrator.getDependencyGraph(),\r\n filesOrchestrator.specialFilesCollector,\r\n filesOrchestrator.moduleLoader,\r\n (absolutePath) => filesOrchestrator.bumpVersion(absolutePath),\r\n () => filesOrchestrator.flushVersionBumps(),\r\n );\r\n\r\n this.running = true;\r\n\r\n const duration = performance.now() - startedAt;\r\n devLogReady(`Development Server is ready in ${colors.greenBright(parseDuration(duration))}`);\r\n\r\n // App modules are loaded and both connector phases are active — signal a\r\n // complete boot so `Application.onceBooted(...)` listeners fire.\r\n Application.markBooted({\r\n environment: Application.environment,\r\n runtimeStrategy: Application.runtimeStrategy,\r\n bootDurationMs: duration,\r\n });\r\n\r\n // Precedence: explicit CLI option > devServer.* config > default.\r\n const devServerConfig = await warlockConfigManager.get(\"devServer\");\r\n const generateTypings =\r\n this.options.generateTypings ?? devServerConfig?.generateTypings ?? true;\r\n const healthCheckers = this.options.healthCheckers ?? devServerConfig?.healthCheckers ?? true;\r\n\r\n if (generateTypings) typeGenerator.executeGenerateAllCommand();\r\n\r\n if (healthCheckers) {\r\n filesOrchestrator.startCheckingHealth(healthCheckers === true ? undefined : healthCheckers);\r\n }\r\n } catch (error) {\r\n devServeLog(colors.redBright(`Failed to start Development Server: ${error}`));\r\n await this.shutdown();\r\n throw error;\r\n }\r\n }\r\n\r\n /**\r\n * Eagerly import files whose decorators populate global registries so any\r\n * symbol-by-name resolution later in boot finds them.\r\n */\r\n private async autoDiscoverFiles(): Promise<void> {\r\n const discoveryTypes = [\"model\"] as const;\r\n for (const file of filesOrchestrator.files.values()) {\r\n if (file.type && (discoveryTypes as readonly string[]).includes(file.type)) {\r\n await filesOrchestrator.moduleLoader.loadModule(file, file.type);\r\n }\r\n }\r\n }\r\n\r\n private setupEventListeners(): void {\r\n events.on(\"dev-server:batch-complete\", (batch: Batch) => this.handleBatchComplete(batch));\r\n }\r\n\r\n private async handleBatchComplete(batch: Batch): Promise<void> {\r\n if (!this.running || !this.layerExecutor) return;\r\n\r\n // warlock.config.ts holds settings read at boot (CLI commands, build\r\n // options, watch patterns, scheduled jobs) and .env feeds every config\r\n // that reads it. Neither can be hot-reloaded without leaving running\r\n // services configured with stale values, so the only honest response is\r\n // a full restart.\r\n const restartTrigger = this.findRestartTrigger(batch);\r\n\r\n if (restartTrigger) {\r\n // On success this never comes back — the process exits and the\r\n // supervisor replaces it. Reaching the next line means the restart was\r\n // declined by config or wasn't possible, so we fall through and still\r\n // hot-reload whatever ordinary code shared the batch.\r\n await this.restartForConfigChange(restartTrigger);\r\n }\r\n\r\n // No-op saves (an editor that fsyncs without a content write) are already\r\n // filtered upstream by the file hash in FileEventHandler, so batch.changed\r\n // only contains genuinely-changed paths by the time it reaches here.\r\n\r\n const total = batch.added.length + batch.changed.length + batch.deleted.length;\r\n if (total === 0) return;\r\n\r\n // Boot-time files still ride along in `changed` when a restart was\r\n // declined (`restartOnConfigChange: false`) or wasn't possible — they are\r\n // never hot-reloaded, so keep them out of the reload set either way.\r\n const codeFiles = [...batch.added, ...batch.changed].filter(\r\n (p) => !isEnvPath(p) && p !== \"warlock.config.ts\",\r\n );\r\n\r\n try {\r\n await this.layerExecutor.executeBatchReload(\r\n codeFiles,\r\n filesOrchestrator.getFiles(),\r\n batch.deleted,\r\n batch.changed,\r\n );\r\n\r\n typeGenerator.executeTypingsGenerator([...batch.added, ...batch.changed]);\r\n\r\n filesOrchestrator.checkHealth(batch);\r\n } catch (error) {\r\n devServeLog(colors.redBright(`Failed to execute batch reload: ${error}`));\r\n }\r\n }\r\n\r\n /**\r\n * The boot-time file in this batch that can only be applied by restarting,\r\n * or `undefined` when the batch is ordinary application code.\r\n */\r\n private findRestartTrigger(batch: Batch): string | undefined {\r\n if (batch.changed.includes(\"warlock.config.ts\")) {\r\n return \"warlock.config.ts\";\r\n }\r\n\r\n return [...batch.added, ...batch.changed].find(isEnvPath);\r\n }\r\n\r\n /**\r\n * Restart so a changed boot-time file actually takes effect.\r\n *\r\n * Opt out with `devServer.restartOnConfigChange: false` and the old\r\n * behaviour returns: a warning telling you to restart yourself. If the\r\n * restart can't be performed at all (no supervisor, a shutdown that threw),\r\n * `restartDevServer` reports it and we fall back to the same warning rather\r\n * than leaving the server running against config it isn't using.\r\n */\r\n private async restartForConfigChange(file: string): Promise<void> {\r\n const devServerConfig = await warlockConfigManager.get(\"devServer\");\r\n\r\n if (devServerConfig?.restartOnConfigChange === false) {\r\n devLogWarn(`${file} changed — restart the dev server to apply.`);\r\n return;\r\n }\r\n\r\n devLogInfo(`${file} changed — restarting to apply.`);\r\n\r\n const restarted = await restartDevServer(this);\r\n\r\n if (!restarted) {\r\n devLogWarn(`${file} changed — restart the dev server to apply.`);\r\n }\r\n }\r\n\r\n public async shutdown(): Promise<void> {\r\n // Always hand the terminal back, even on a repeat/no-op shutdown — a\r\n // process that exits while stdin is still in raw mode leaves the user's\r\n // shell without line editing or Ctrl+C.\r\n devServerShortcuts.release();\r\n\r\n if (!this.running) return;\r\n devServeLog(colors.redBright(\"Shutting down Development Server...\"));\r\n this.running = false;\r\n await connectorsManager.shutdown();\r\n devServeLog(colors.greenBright(\"Development Server stopped\"));\r\n }\r\n\r\n public isRunning(): boolean {\r\n return this.running;\r\n }\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\nfunction parse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BAAmB,GAC5C,OAAO;EAGT,OAAO,CAAC,GAAG,MAAM,OAAO,GAAG,MAAM,OAAO,CAAC,CAAC,KAAK,SAAS;CAC1D;;;;;;;;;;CAWA,MAAc,uBAAuB,MAA6B;EAGhE,KAAI,MAF0B,qBAAqB,IAAI,WAAW,EAE/C,EAAE,0BAA0B,OAAO;GACpD,WAAW,GAAG,KAAK,4CAA4C;GAC/D;EACF;EAEA,WAAW,GAAG,KAAK,gCAAgC;EAInD,IAAI,CAAC,MAFmB,iBAAiB,IAAI,GAG3C,WAAW,GAAG,KAAK,4CAA4C;CAEnE;CAEA,MAAa,WAA0B;EAIrC,mBAAmB,QAAQ;EAE3B,IAAI,CAAC,KAAK,SAAS;EACnB,YAAY,OAAO,UAAU,qCAAqC,CAAC;EACnE,KAAK,UAAU;EACf,MAAM,kBAAkB,SAAS;EACjC,YAAY,OAAO,YAAY,4BAA4B,CAAC;CAC9D;CAEA,AAAO,YAAqB;EAC1B,OAAO,KAAK;CACd;AACF;AAGA,SAAS,UAAU,MAAuB;CACxC,MAAM,WAAW,KAAK,MAAM,GAAG,CAAC,CAAC,IAAI,KAAK;CAC1C,OAAO,aAAa,UAAU,SAAS,WAAW,OAAO;AAC3D;AAEA,SAAS,cAAc,IAAoB;CACzC,IAAI,KAAK,KAAM,OAAO,GAAG,GAAG,QAAQ,CAAC,EAAE;CACvC,IAAI,KAAK,KAAQ,OAAO,IAAI,KAAK,IAAM,CAAE,QAAQ,CAAC,EAAE;CACpD,OAAO,IAAI,KAAK,IAAI,CAAE,QAAQ,CAAC,EAAE;AACnC"}
@@ -1,3 +1,4 @@
1
+ import { environmentLoaderOptions } from "../utils/load-environment.mjs";
1
2
  import { connectorsManager } from "../connectors/connectors-manager.mjs";
2
3
  import { devLogHMR } from "./dev-logger.mjs";
3
4
  import { configManager } from "../config/config-manager.mjs";
@@ -69,7 +70,7 @@ var LayerExecutor = class {
69
70
  */
70
71
  async reloadAffectedModules(chain, filesMap) {
71
72
  const isEnvAffected = chain.some(isEnvPath);
72
- if (isEnvAffected) await loadEnv();
73
+ if (isEnvAffected) await loadEnv(void 0, environmentLoaderOptions);
73
74
  const isAffected = (file) => isFileAffected(file, chain);
74
75
  const affectedModels = chain.map((path) => filesMap.get(path)).filter((file) => !!file && file.type === "model");
75
76
  for (const file of affectedModels) await this.moduleLoader.loadModule(file, "model");
@@ -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\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(configPaths);\r\n return;\r\n }\r\n\r\n if (changedPaths.length === 0) return;\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([...changedPaths, ...affectedConfigPaths]);\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 if (isEnvAffected) await loadEnv();\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":";;;;;;;;;;;;;;AAiBA,IAAa,gBAAb,MAA2B;CACzB,AAAO,YACL,AAAiB,iBACjB,AAAiB,uBACjB,AAAiB,cACjB,AAAiB,aACjB,AAAiB,mBACjB;EALiB;EACA;EACA;EACA;EACA;CAChB;;;;;;;;;CAUH,MAAa,mBACX,cACA,UACA,cACA,iBACe;EACf,MAAM,mBAAmB,mBAAmB,CAAC,EAAC,CAAE,KAAK,SAAS;EAE9D,IAAI,aAAa,WAAW,KAAK,aAAa,WAAW,KAAK,CAAC,iBAC7D;EAIF,KAAK,MAAM,QAAQ,cAAc;GAC/B,MAAM,OAAO,SAAS,IAAI,IAAI;GAC9B,IAAI,MAAM,KAAK,aAAa,qBAAqB,IAAI;EACvD;EAGA,IAAI,aAAa,WAAW,KAAK,iBAAiB;GAChD,MAAM,cAAc,MAAM,KAAK,sBAA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AK,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(configPaths);\r\n return;\r\n }\r\n\r\n if (changedPaths.length === 0) return;\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([...changedPaths, ...affectedConfigPaths]);\r\n }\r\n\r\n private async restartAffectedConnectors(affectedFiles: string[]): Promise<void> {\r\n const toRestart = connectorsManager\r\n .list()\r\n .filter(connector => connector.shouldRestart(affectedFiles));\r\n\r\n for (const connector of toRestart) {\r\n await connector.restart();\r\n }\r\n }\r\n\r\n /**\r\n * Re-import every special file whose path or dependency-set intersects the\r\n * invalidation chain. Returns the relative paths of any config files that\r\n * reloaded so the caller can pass them to the connector-restart pass.\r\n */\r\n private async reloadAffectedModules(\r\n chain: string[],\r\n filesMap: Map<string, FileManager>,\r\n ): Promise<string[]> {\r\n const isEnvAffected = chain.some(isEnvPath);\r\n // Same precedence policy as the boot-time load: an exported variable is not\r\n // demoted to the file's value just because the file was touched.\r\n if (isEnvAffected) await loadEnv(undefined, environmentLoaderOptions);\r\n\r\n const isAffected = (file: FileManager) => isFileAffected(file, chain);\r\n\r\n // Models self-register via the @RegisterModel decorator and rely on the\r\n // module-loader's registerCleanup() to attach Model.$cleanup (which\r\n // unregisters them on the next reload). That only happens inside\r\n // loadModule(), which models hit exactly once — at boot, via\r\n // autoDiscoverFiles. During HMR they're otherwise re-imported\r\n // *transitively* through routes, which never re-runs registerCleanup, so\r\n // after the first reload the cleanup list is empty and the registration\r\n // leaks (\"Model X is already registered\" on every subsequent edit).\r\n //\r\n // Re-importing changed model files through loadModule here re-attaches\r\n // $cleanup every cycle. It runs before the route pass so the decorator\r\n // registers once; the transitive route import then hits the cached ?v=N\r\n // and does not double-register.\r\n const affectedModels = chain\r\n .map(path => filesMap.get(path))\r\n .filter((file): file is FileManager => !!file && file.type === \"model\");\r\n\r\n for (const file of affectedModels) {\r\n await this.moduleLoader.loadModule(file, \"model\");\r\n }\r\n\r\n const collector = this.specialFilesCollector;\r\n const affectedConfigs = collector\r\n .getFilesByType(\"config\")\r\n .filter(file => (isEnvAffected ? true : isAffected(file)));\r\n const affectedMains = collector.getFilesByType(\"main\").filter(isAffected);\r\n const affectedRoutes = collector.getFilesByType(\"route\").filter(isAffected);\r\n const affectedEvents = collector.getFilesByType(\"event\").filter(isAffected);\r\n const affectedLocales = collector.getFilesByType(\"locale\").filter(isAffected);\r\n\r\n const hasSpecialFiles =\r\n affectedConfigs.length > 0 ||\r\n affectedMains.length > 0 ||\r\n affectedRoutes.length > 0 ||\r\n affectedEvents.length > 0 ||\r\n affectedLocales.length > 0;\r\n\r\n // No entry points touched: reloading internal files alone is wasted work\r\n // because the hook will re-import them on next access anyway. But the\r\n // dep chain's last hop is usually the user-facing edge — give it a kick.\r\n if (!hasSpecialFiles) {\r\n const tail = filesMap.get(chain[chain.length - 1]);\r\n if (tail) await this.moduleLoader.reloadModule(tail);\r\n return [];\r\n }\r\n\r\n const configPaths: string[] = [];\r\n for (const file of affectedConfigs) {\r\n await configManager.reload(file);\r\n configPaths.push(file.relativePath);\r\n }\r\n\r\n // Order matters: locales first (translations used by main), main before\r\n // routes (registers state routes consume), events between (listeners).\r\n for (const file of affectedLocales) await this.moduleLoader.reloadModule(file);\r\n for (const file of affectedMains) await this.moduleLoader.reloadModule(file);\r\n for (const file of affectedEvents) await this.moduleLoader.reloadModule(file);\r\n for (const file of affectedRoutes) await this.moduleLoader.reloadModule(file);\r\n\r\n return configPaths;\r\n }\r\n}\r\n\r\nfunction isEnvPath(path: string): boolean {\r\n const basename = path.split(\"/\").pop() ?? path;\r\n return basename === \".env\" || basename.startsWith(\".env.\");\r\n}\r\n\r\n/**\r\n * A file is \"affected\" if it itself is in the chain or imports something in it.\r\n */\r\nfunction isFileAffected(file: FileManager, chain: string[]): boolean {\r\n if (chain.includes(file.relativePath)) return true;\r\n for (const dep of file.dependencies) {\r\n if (chain.includes(dep)) return true;\r\n }\r\n return false;\r\n}\r\n"],"mappings":";;;;;;;;;;;;;;;AAkBA,IAAa,gBAAb,MAA2B;CACzB,AAAO,YACL,AAAiB,iBACjB,AAAiB,uBACjB,AAAiB,cACjB,AAAiB,aACjB,AAAiB,mBACjB;EALiB;EACA;EACA;EACA;EACA;CAChB;;;;;;;;;CAUH,MAAa,mBACX,cACA,UACA,cACA,iBACe;EACf,MAAM,mBAAmB,mBAAmB,CAAC,EAAC,CAAE,KAAK,SAAS;EAE9D,IAAI,aAAa,WAAW,KAAK,aAAa,WAAW,KAAK,CAAC,iBAC7D;EAIF,KAAK,MAAM,QAAQ,cAAc;GAC/B,MAAM,OAAO,SAAS,IAAI,IAAI;GAC9B,IAAI,MAAM,KAAK,aAAa,qBAAqB,IAAI;EACvD;EAGA,IAAI,aAAa,WAAW,KAAK,iBAAiB;GAChD,MAAM,cAAc,MAAM,KAAK,sBAAsB,CAAC,MAAM,GAAG,QAAQ;GACvE,MAAM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B,IAAI,MAAM,SAAS,GAAG,GAAG,OAAO;CAElC,OAAO;AACT"}
@@ -0,0 +1,48 @@
1
+ import { readFile } from "node:fs/promises";
2
+ import ts from "typescript";
3
+
4
+ //#region ../core/src/dev-server/read-config-ast.ts
5
+ /**
6
+ * Parse one config file into an AST.
7
+ *
8
+ * ## Why this is not `ts.createProgram`
9
+ *
10
+ * It was. The typings generator built a whole TypeScript **Program** for each
11
+ * config file just to call `program.getSourceFile(path)` on it. A Warlock
12
+ * config imports `@warlock.js/core`, which in this monorepo resolves to
13
+ * TypeScript **source**, so every one of those Programs resolved and parsed the
14
+ * entire dependency graph behind it.
15
+ *
16
+ * Measured on the reference app's six configs, 2026-08-24:
17
+ *
18
+ * ```
19
+ * ts.createProgram 82,996.00 ms 2,908 source files per program
20
+ * ts.createSourceFile 5.12 ms
21
+ * ratio 16,212x
22
+ * ```
23
+ *
24
+ * And all of it was discarded. `getTypeChecker()` is never called anywhere in
25
+ * the generator — every question it asks of the AST is syntactic
26
+ * (`isImportDeclaration`, `isTypeAliasDeclaration`, `isVariableDeclaration`,
27
+ * `isObjectLiteralExpression`). Resolving 2,908 files to answer a syntactic
28
+ * question is 2,908 files of work thrown away.
29
+ *
30
+ * A previous pass had already noticed the cost and halved it, from two Programs
31
+ * per file to one — an optimisation inside a premise that did not need to hold.
32
+ *
33
+ * **If a future change here needs a type checker, it needs a Program too, and
34
+ * the cost comes back.** That is the one reason to reconsider this file.
35
+ */
36
+ async function readConfigAst(filePath) {
37
+ let contents;
38
+ try {
39
+ contents = await readFile(filePath, "utf-8");
40
+ } catch {
41
+ return;
42
+ }
43
+ return ts.createSourceFile(filePath, contents, ts.ScriptTarget.ESNext, true);
44
+ }
45
+
46
+ //#endregion
47
+ export { readConfigAst };
48
+ //# sourceMappingURL=read-config-ast.mjs.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"read-config-ast.mjs","names":[],"sources":["../../../../../../../core/src/dev-server/read-config-ast.ts"],"sourcesContent":["/**\n * Parse one config file into an AST.\n *\n * ## Why this is not `ts.createProgram`\n *\n * It was. The typings generator built a whole TypeScript **Program** for each\n * config file just to call `program.getSourceFile(path)` on it. A Warlock\n * config imports `@warlock.js/core`, which in this monorepo resolves to\n * TypeScript **source**, so every one of those Programs resolved and parsed the\n * entire dependency graph behind it.\n *\n * Measured on the reference app's six configs, 2026-08-24:\n *\n * ```\n * ts.createProgram 82,996.00 ms 2,908 source files per program\n * ts.createSourceFile 5.12 ms\n * ratio 16,212x\n * ```\n *\n * And all of it was discarded. `getTypeChecker()` is never called anywhere in\n * the generator — every question it asks of the AST is syntactic\n * (`isImportDeclaration`, `isTypeAliasDeclaration`, `isVariableDeclaration`,\n * `isObjectLiteralExpression`). Resolving 2,908 files to answer a syntactic\n * question is 2,908 files of work thrown away.\n *\n * A previous pass had already noticed the cost and halved it, from two Programs\n * per file to one — an optimisation inside a premise that did not need to hold.\n *\n * **If a future change here needs a type checker, it needs a Program too, and\n * the cost comes back.** That is the one reason to reconsider this file.\n */\n\nimport { readFile } from \"node:fs/promises\";\nimport ts from \"typescript\";\n\nexport async function readConfigAst(filePath: string): Promise<ts.SourceFile | undefined> {\n let contents: string;\n\n try {\n contents = await readFile(filePath, \"utf-8\");\n } catch {\n // Callers already treat a missing config as \"nothing to generate\"; a throw\n // here would turn an absent optional file into a failed generation.\n return undefined;\n }\n\n return ts.createSourceFile(\n filePath,\n contents,\n ts.ScriptTarget.ESNext,\n // The generator's visitors read `node.parent`, which the Program-backed\n // source files provided for free.\n /* setParentNodes */ true,\n );\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAmCA,eAAsB,cAAc,UAAsD;CACxF,IAAI;CAEJ,IAAI;EACF,WAAW,MAAM,SAAS,UAAU,OAAO;CAC7C,QAAQ;EAGN;CACF;CAEA,OAAO,GAAG,iBACR,UACA,UACA,GAAG,aAAa,QAGK,IACvB;AACF"}
@@ -0,0 +1,18 @@
1
+ //#region ../core/src/dev-server/run-typings-generation.ts
2
+ function describeCause(thrown) {
3
+ if (thrown instanceof Error) return thrown.message;
4
+ return String(thrown);
5
+ }
6
+ async function runTypingsGeneration(ports) {
7
+ ports.info("Checking for types generation");
8
+ try {
9
+ await ports.generate();
10
+ ports.success("Types generated successfully");
11
+ } catch (thrown) {
12
+ ports.error(`Failed to generate types: ${describeCause(thrown)}`);
13
+ }
14
+ }
15
+
16
+ //#endregion
17
+ export { runTypingsGeneration };
18
+ //# sourceMappingURL=run-typings-generation.mjs.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"run-typings-generation.mjs","names":[],"sources":["../../../../../../../core/src/dev-server/run-typings-generation.ts"],"sourcesContent":["/**\n * Run type generation, in this process.\n *\n * ## Why this is not a spawn\n *\n * It used to be. `type-generator.ts` ran `npx warlock generate.typings`, which\n * resolves to `core/bin/warlock.js` → `import \"../esm/cli/start.mjs\"`. This\n * monorepo consumes packages as TypeScript **source**, so there is no `esm/`\n * directory: every dev boot printed `✗ Failed to generate types`, and an\n * `ERR_MODULE_NOT_FOUND` stack rode along inside an otherwise green core suite.\n *\n * Spawning was the mistake underneath the broken path. The CLI command it\n * launched does two things — add the config files to the orchestrator, then\n * call `typeGenerator.generateAll()` — and the dev server has **already**\n * initialised that orchestrator with those files at boot. So it paid for a\n * second Node process to rediscover state it was holding, in order to call a\n * method that lives in the same module it was calling from.\n *\n * Launching a binary through `npx` is separately prohibited in this workspace:\n * resolve and invoke directly.\n *\n * ## Why a failure here is not fatal\n *\n * Generated typings are editor autocomplete. A dev server that refused to boot\n * because it could not write them would be a worse defect than the one this\n * replaces, so this never throws — but it does say **why**, which the old\n * `Failed to generate types` did not. A failure message that names no cause\n * sends the reader hunting, which is most of what the old line achieved.\n */\n\nexport type TypingsGenerationPorts = {\n /** `typeGenerator.generateAll()` in production; a fake in tests. */\n generate(): Promise<void>;\n info(message: string): void;\n success(message: string): void;\n error(message: string): void;\n};\n\nfunction describeCause(thrown: unknown): string {\n if (thrown instanceof Error) return thrown.message;\n\n return String(thrown);\n}\n\nexport async function runTypingsGeneration(ports: TypingsGenerationPorts): Promise<void> {\n ports.info(\"Checking for types generation\");\n\n try {\n await ports.generate();\n\n ports.success(\"Types generated successfully\");\n } catch (thrown) {\n ports.error(`Failed to generate types: ${describeCause(thrown)}`);\n }\n}\n"],"mappings":";AAsCA,SAAS,cAAc,QAAyB;CAC9C,IAAI,kBAAkB,OAAO,OAAO,OAAO;CAE3C,OAAO,OAAO,MAAM;AACtB;AAEA,eAAsB,qBAAqB,OAA8C;CACvF,MAAM,KAAK,+BAA+B;CAE1C,IAAI;EACF,MAAM,MAAM,SAAS;EAErB,MAAM,QAAQ,8BAA8B;CAC9C,SAAS,QAAQ;EACf,MAAM,MAAM,6BAA6B,cAAc,MAAM,GAAG;CAClE;AACF"}
@@ -3,13 +3,13 @@ import { warlockPath } from "../utils/paths.mjs";
3
3
  import "../utils/index.mjs";
4
4
  import { devLogError, devLogInfo, devLogSuccess, devServeLog } from "./dev-logger.mjs";
5
5
  import { filesOrchestrator } from "./files-orchestrator.mjs";
6
- import { env } from "@mongez/dotenv";
6
+ import { readConfigAst } from "./read-config-ast.mjs";
7
+ import { runTypingsGeneration } from "./run-typings-generation.mjs";
7
8
  import { join, resolve } from "path";
8
9
  import { ensureDirectoryAsync } from "@warlock.js/fs";
9
10
  import { constants } from "fs";
10
11
  import { access, readFile, writeFile } from "fs/promises";
11
12
  import ts from "typescript";
12
- import { spawn } from "child_process";
13
13
 
14
14
  //#region ../core/src/dev-server/type-generator.ts
15
15
  /**
@@ -269,9 +269,10 @@ ${allKeys.map((key) => ` "${key}": true;`).join("\n")}
269
269
  /**
270
270
  * Extract BOTH type info AND keys in a single pass
271
271
  *
272
- * This is optimized to create ts.createProgram() only ONCE per file
273
- * instead of twice (once for type extraction, once for keys).
274
- * This reduces parsing time by ~50%.
272
+ * One parse serves both extractions. It used to be one whole TypeScript
273
+ * Program per file halved from two by an earlier pass, which optimised
274
+ * inside a premise that did not need to hold. `read-config-ast.ts` has the
275
+ * numbers.
275
276
  *
276
277
  * @param configPath Absolute path to the config file
277
278
  * @param configName Config name (e.g., "auth", "notifications")
@@ -283,11 +284,7 @@ ${allKeys.map((key) => ` "${key}": true;`).join("\n")}
283
284
  importSource: null,
284
285
  keys: []
285
286
  };
286
- const sourceFile = ts.createProgram([configPath], {
287
- target: ts.ScriptTarget.ESNext,
288
- module: ts.ModuleKind.ESNext,
289
- moduleResolution: ts.ModuleResolutionKind.NodeJs
290
- }).getSourceFile(configPath);
287
+ const sourceFile = await readConfigAst(configPath);
291
288
  if (!sourceFile) return {
292
289
  typeName: null,
293
290
  importSource: null,
@@ -355,11 +352,7 @@ ${allKeys.map((key) => ` "${key}": true;`).join("\n")}
355
352
  devServeLog(`⚠️ Storage config not found: ${absolutePath}`);
356
353
  return [];
357
354
  }
358
- const sourceFile = ts.createProgram([absolutePath], {
359
- target: ts.ScriptTarget.ESNext,
360
- module: ts.ModuleKind.ESNext,
361
- moduleResolution: ts.ModuleResolutionKind.NodeJs
362
- }).getSourceFile(absolutePath);
355
+ const sourceFile = await readConfigAst(absolutePath);
363
356
  if (!sourceFile) {
364
357
  devServeLog(`⚠️ Could not parse storage config: ${absolutePath}`);
365
358
  return [];
@@ -411,36 +404,34 @@ ${allKeys.map((key) => ` "${key}": true;`).join("\n")}
411
404
  }
412
405
  }
413
406
  /**
414
- * Execute generateAll command using spawn
407
+ * The ports `runTypingsGeneration` needs, bound to this instance and this
408
+ * package's dev logger.
409
+ */
410
+ get typingsGenerationPorts() {
411
+ return {
412
+ generate: () => this.generateAll(),
413
+ info: (message) => devLogInfo(message),
414
+ success: (message) => devLogSuccess(message),
415
+ error: (message) => devLogError(message)
416
+ };
417
+ }
418
+ /**
419
+ * Generate every config's typings.
420
+ *
421
+ * Runs IN THIS PROCESS. It used to spawn `npx warlock generate.typings`,
422
+ * which could not resolve in a source checkout — see
423
+ * `run-typings-generation.ts` for the whole story.
415
424
  */
416
425
  async executeGenerateAllCommand() {
417
- devLogInfo("Checking for types generation");
418
- const isDevServeCore = env("DEV_SERVER_CORE");
419
- spawn(isDevServeCore ? "yarn" : "npx", [isDevServeCore ? "cli" : "warlock", "generate.typings"], {
420
- stdio: "inherit",
421
- cwd: process.cwd(),
422
- shell: true
423
- }).on("exit", (code) => {
424
- if (code === 0) devLogSuccess("Types generated successfully");
425
- else devLogError("Failed to generate types");
426
- });
426
+ await runTypingsGeneration(this.typingsGenerationPorts);
427
427
  }
428
428
  /**
429
- * Execute a typings generator for the given files
429
+ * Regenerate typings after a batch reload but only when the batch actually
430
+ * touched a config file, since nothing else contributes to them.
430
431
  */
431
432
  async executeTypingsGenerator(upcomingFiles) {
432
- const configFilesOnly = Array.from(new Set(upcomingFiles)).filter((file) => Path.normalize(file).includes("src/config/"));
433
- if (configFilesOnly.length === 0) return;
434
- configFilesOnly.map((file) => "./" + Path.toRelative(file));
435
- const isDevServeCore = env("DEV_SERVER_CORE");
436
- spawn(isDevServeCore ? "yarn" : "npx", [isDevServeCore ? "cli" : "warlock", "generate.typings"], {
437
- stdio: "inherit",
438
- cwd: process.cwd(),
439
- shell: true
440
- }).on("exit", (code) => {
441
- if (code === 0) devLogSuccess("Types generated successfully");
442
- else devLogError("Failed to generate types");
443
- });
433
+ if (!Array.from(new Set(upcomingFiles)).some((file) => Path.normalize(file).includes("src/config/"))) return;
434
+ await runTypingsGeneration(this.typingsGenerationPorts);
444
435
  }
445
436
  };
446
437
  /**