@forinda/kickjs 3.2.0 → 4.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 (187) hide show
  1. package/README.md +13 -212
  2. package/dist/{adapter-DLEHb0K6.d.mts → adapter-BNw2pGbg.d.mts} +117 -7
  3. package/dist/adapter-BNw2pGbg.d.mts.map +1 -0
  4. package/dist/{app-module-ERR9jhow.d.mts → app-module-CO0ksPCm.d.mts} +3 -3
  5. package/dist/{app-module-ERR9jhow.d.mts.map → app-module-CO0ksPCm.d.mts.map} +1 -1
  6. package/dist/{application-x8CXLOlv.mjs → application-Ce4DQN6m.mjs} +28 -9
  7. package/dist/application-Ce4DQN6m.mjs.map +1 -0
  8. package/dist/application-Czwm7Gty.d.mts +302 -0
  9. package/dist/application-Czwm7Gty.d.mts.map +1 -0
  10. package/dist/{bootstrap-CYnxozL_.mjs → bootstrap-CB7bJeJG.mjs} +6 -6
  11. package/dist/{bootstrap-CYnxozL_.mjs.map → bootstrap-CB7bJeJG.mjs.map} +1 -1
  12. package/dist/bootstrap-NxFRaNTh.d.mts +28 -0
  13. package/dist/bootstrap-NxFRaNTh.d.mts.map +1 -0
  14. package/dist/{cache-V91BNTIM.d.mts → cache-BStrqXSZ.d.mts} +2 -2
  15. package/dist/{cache-V91BNTIM.d.mts.map → cache-BStrqXSZ.d.mts.map} +1 -1
  16. package/dist/config/index.d.mts +1 -1
  17. package/dist/config/index.mjs +3 -3
  18. package/dist/{config-aWxKLk4A.mjs → config-wZ_TgBfs.mjs} +4 -4
  19. package/dist/{config-aWxKLk4A.mjs.map → config-wZ_TgBfs.mjs.map} +1 -1
  20. package/dist/{container-fIS1uLx-.d.mts → container-CnWDsxi-.d.mts} +9 -7
  21. package/dist/container-CnWDsxi-.d.mts.map +1 -0
  22. package/dist/{container-Dnk43k54.mjs → container-DYYSu58w.mjs} +313 -9
  23. package/dist/container-DYYSu58w.mjs.map +1 -0
  24. package/dist/{context-OktlOQBQ.mjs → context-BAGzqT7-.mjs} +33 -41
  25. package/dist/context-BAGzqT7-.mjs.map +1 -0
  26. package/dist/context-Ymvv-85x.d.mts +260 -0
  27. package/dist/context-Ymvv-85x.d.mts.map +1 -0
  28. package/dist/{context-decorator-GA8-hDLe.d.mts → context-decorator-B5v3VQCN.d.mts} +4 -4
  29. package/dist/{context-decorator-GA8-hDLe.d.mts.map → context-decorator-B5v3VQCN.d.mts.map} +1 -1
  30. package/dist/core/adapter.d.mts +1 -1
  31. package/dist/core/adapter.mjs +1 -1
  32. package/dist/core/app-module.d.mts +1 -1
  33. package/dist/core/app-module.mjs +1 -1
  34. package/dist/core/cache.d.mts +1 -1
  35. package/dist/core/cache.mjs +2 -2
  36. package/dist/core/cache.mjs.map +1 -1
  37. package/dist/core/container.d.mts +1 -1
  38. package/dist/core/container.mjs +2 -2
  39. package/dist/core/cron.d.mts +1 -1
  40. package/dist/core/cron.mjs +2 -2
  41. package/dist/core/decorators.d.mts +2 -2
  42. package/dist/core/decorators.mjs +48 -16
  43. package/dist/core/decorators.mjs.map +1 -1
  44. package/dist/core/errors.d.mts +1 -1
  45. package/dist/core/errors.mjs +1 -1
  46. package/dist/core/interfaces.d.mts +1 -1
  47. package/dist/core/interfaces.mjs +35 -18
  48. package/dist/core/interfaces.mjs.map +1 -1
  49. package/dist/core/logger.d.mts +2 -2
  50. package/dist/core/logger.mjs +2 -4
  51. package/dist/core/logger.mjs.map +1 -1
  52. package/dist/core/path.d.mts +1 -1
  53. package/dist/core/path.mjs +1 -1
  54. package/dist/core/plugin.d.mts +1 -1
  55. package/dist/core/plugin.mjs +1 -1
  56. package/dist/core/reactivity.d.mts +1 -1
  57. package/dist/core/reactivity.mjs +1 -1
  58. package/dist/{core-DANnH5-e.mjs → core-DBcoqPHM.mjs} +282 -8
  59. package/dist/core-DBcoqPHM.mjs.map +1 -0
  60. package/dist/cors-BfgqfLPd.d.mts +48 -0
  61. package/dist/cors-BfgqfLPd.d.mts.map +1 -0
  62. package/dist/{cron-CfsPdi7R.d.mts → cron-7zqvsmMI.d.mts} +1 -1
  63. package/dist/{cron-CfsPdi7R.d.mts.map → cron-7zqvsmMI.d.mts.map} +1 -1
  64. package/dist/csrf-DiK9zept.d.mts +52 -0
  65. package/dist/csrf-DiK9zept.d.mts.map +1 -0
  66. package/dist/{decorators-H42oPg0m.d.mts → decorators-BMvaLliz.d.mts} +147 -12
  67. package/dist/decorators-BMvaLliz.d.mts.map +1 -0
  68. package/dist/{env-Cs8Wt8A_.mjs → env-CdH5-dM_.mjs} +3 -4
  69. package/dist/{env-Cs8Wt8A_.mjs.map → env-CdH5-dM_.mjs.map} +1 -1
  70. package/dist/error-handler-Xud_3Lah.d.mts +20 -0
  71. package/dist/error-handler-Xud_3Lah.d.mts.map +1 -0
  72. package/dist/{errors-D_CWI7Bl.d.mts → errors-uaHCeXRz.d.mts} +1 -1
  73. package/dist/{errors-D_CWI7Bl.d.mts.map → errors-uaHCeXRz.d.mts.map} +1 -1
  74. package/dist/{execution-context-Dl2CKqSo.d.mts → execution-context-DKnt61pY.d.mts} +1 -1
  75. package/dist/{execution-context-Dl2CKqSo.d.mts.map → execution-context-DKnt61pY.d.mts.map} +1 -1
  76. package/dist/helmet-CaMbjzBG.d.mts +41 -0
  77. package/dist/helmet-CaMbjzBG.d.mts.map +1 -0
  78. package/dist/http/application.d.mts +2 -293
  79. package/dist/http/application.mjs +2 -2
  80. package/dist/http/bootstrap.d.mts +2 -27
  81. package/dist/http/bootstrap.mjs +2 -2
  82. package/dist/http/context.d.mts +3 -251
  83. package/dist/http/context.mjs +2 -2
  84. package/dist/http/middleware/cors.d.mts +2 -47
  85. package/dist/http/middleware/cors.mjs +1 -1
  86. package/dist/http/middleware/csrf.d.mts +2 -51
  87. package/dist/http/middleware/csrf.mjs +2 -2
  88. package/dist/http/middleware/csrf.mjs.map +1 -1
  89. package/dist/http/middleware/error-handler.d.mts +2 -19
  90. package/dist/http/middleware/error-handler.mjs +2 -2
  91. package/dist/http/middleware/helmet.d.mts +2 -40
  92. package/dist/http/middleware/helmet.mjs +1 -1
  93. package/dist/http/middleware/rate-limit.d.mts +2 -55
  94. package/dist/http/middleware/rate-limit.mjs +2 -2
  95. package/dist/http/middleware/rate-limit.mjs.map +1 -1
  96. package/dist/http/middleware/request-id.d.mts +2 -9
  97. package/dist/http/middleware/request-id.mjs +12 -3
  98. package/dist/http/middleware/request-id.mjs.map +1 -1
  99. package/dist/http/middleware/request-logger.d.mts +2 -31
  100. package/dist/http/middleware/request-logger.mjs +2 -2
  101. package/dist/http/middleware/session.d.mts +2 -69
  102. package/dist/http/middleware/session.mjs +1 -1
  103. package/dist/http/middleware/spa.d.mts +2 -100
  104. package/dist/http/middleware/spa.mjs +5 -5
  105. package/dist/http/middleware/spa.mjs.map +1 -1
  106. package/dist/http/middleware/upload.d.mts +2 -78
  107. package/dist/http/middleware/upload.mjs +1 -1
  108. package/dist/http/middleware/validate.d.mts +2 -22
  109. package/dist/http/middleware/validate.mjs +2 -2
  110. package/dist/http/middleware/views.d.mts +2 -61
  111. package/dist/http/middleware/views.mjs +16 -15
  112. package/dist/http/middleware/views.mjs.map +1 -1
  113. package/dist/http/query/index.d.mts +1 -1
  114. package/dist/http/query/index.mjs +2 -2
  115. package/dist/http/router-builder.d.mts +2 -32
  116. package/dist/http/router-builder.mjs +10 -14
  117. package/dist/http/router-builder.mjs.map +1 -1
  118. package/dist/{index-RNK41JPE.d.mts → index-B9cyOQAe.d.mts} +1 -1
  119. package/dist/{index-RNK41JPE.d.mts.map → index-B9cyOQAe.d.mts.map} +1 -1
  120. package/dist/{index-Cf-MGrqT.d.mts → index-D-qhXg9M.d.mts} +3 -3
  121. package/dist/{index-Cf-MGrqT.d.mts.map → index-D-qhXg9M.d.mts.map} +1 -1
  122. package/dist/{index-BQM9pJrV.d.mts → index-DQyWtyp0.d.mts} +241 -5
  123. package/dist/index-DQyWtyp0.d.mts.map +1 -0
  124. package/dist/index.d.mts +34 -152
  125. package/dist/index.mjs +14 -14
  126. package/dist/interfaces-B50n7dwl.d.mts +71 -0
  127. package/dist/{interfaces-CwcdqfNq.d.mts.map → interfaces-B50n7dwl.d.mts.map} +1 -1
  128. package/dist/{logger-GK8yT0BD.d.mts → logger-CLVRZf2N.d.mts} +2 -4
  129. package/dist/{logger-GK8yT0BD.d.mts.map → logger-CLVRZf2N.d.mts.map} +1 -1
  130. package/dist/{metadata-BFuoSEX6.mjs → metadata-VQM9wChy.mjs} +2 -2
  131. package/dist/{metadata-BFuoSEX6.mjs.map → metadata-VQM9wChy.mjs.map} +1 -1
  132. package/dist/{path-Bj3vZMUY.d.mts → path-Diviu6hv.d.mts} +1 -1
  133. package/dist/path-Diviu6hv.d.mts.map +1 -0
  134. package/dist/{plugin-3rKA0Loy.d.mts → plugin-WdrDgNzk.d.mts} +45 -7
  135. package/dist/plugin-WdrDgNzk.d.mts.map +1 -0
  136. package/dist/{query-BcYEjYyX.mjs → query-DJMxdx5r.mjs} +2 -2
  137. package/dist/{query-BcYEjYyX.mjs.map → query-DJMxdx5r.mjs.map} +1 -1
  138. package/dist/rate-limit-DUwoICtI.d.mts +56 -0
  139. package/dist/rate-limit-DUwoICtI.d.mts.map +1 -0
  140. package/dist/{reactivity-CczHu3R-.d.mts → reactivity-CfJceo4H.d.mts} +1 -1
  141. package/dist/{reactivity-CczHu3R-.d.mts.map → reactivity-CfJceo4H.d.mts.map} +1 -1
  142. package/dist/request-id-BgglvZHN.d.mts +19 -0
  143. package/dist/request-id-BgglvZHN.d.mts.map +1 -0
  144. package/dist/request-logger-CWHbAzTE.d.mts +32 -0
  145. package/dist/request-logger-CWHbAzTE.d.mts.map +1 -0
  146. package/dist/router-builder-C799BAf0.d.mts +31 -0
  147. package/dist/router-builder-C799BAf0.d.mts.map +1 -0
  148. package/dist/session-N0hActOO.d.mts +70 -0
  149. package/dist/session-N0hActOO.d.mts.map +1 -0
  150. package/dist/spa-CrFR2_cz.d.mts +101 -0
  151. package/dist/spa-CrFR2_cz.d.mts.map +1 -0
  152. package/dist/upload-BueOnnLw.d.mts +79 -0
  153. package/dist/upload-BueOnnLw.d.mts.map +1 -0
  154. package/dist/validate-HwAyWTwH.d.mts +23 -0
  155. package/dist/validate-HwAyWTwH.d.mts.map +1 -0
  156. package/dist/views-DhQSXV2P.d.mts +176 -0
  157. package/dist/views-DhQSXV2P.d.mts.map +1 -0
  158. package/package.json +6 -9
  159. package/dist/adapter-DLEHb0K6.d.mts.map +0 -1
  160. package/dist/application-x8CXLOlv.mjs.map +0 -1
  161. package/dist/chunk-Bt-rz0Tp.mjs +0 -15
  162. package/dist/container-Dnk43k54.mjs.map +0 -1
  163. package/dist/container-fIS1uLx-.d.mts.map +0 -1
  164. package/dist/context-OktlOQBQ.mjs.map +0 -1
  165. package/dist/core-DANnH5-e.mjs.map +0 -1
  166. package/dist/decorators-H42oPg0m.d.mts.map +0 -1
  167. package/dist/http/application.d.mts.map +0 -1
  168. package/dist/http/bootstrap.d.mts.map +0 -1
  169. package/dist/http/context.d.mts.map +0 -1
  170. package/dist/http/middleware/cors.d.mts.map +0 -1
  171. package/dist/http/middleware/csrf.d.mts.map +0 -1
  172. package/dist/http/middleware/error-handler.d.mts.map +0 -1
  173. package/dist/http/middleware/helmet.d.mts.map +0 -1
  174. package/dist/http/middleware/rate-limit.d.mts.map +0 -1
  175. package/dist/http/middleware/request-id.d.mts.map +0 -1
  176. package/dist/http/middleware/request-logger.d.mts.map +0 -1
  177. package/dist/http/middleware/session.d.mts.map +0 -1
  178. package/dist/http/middleware/spa.d.mts.map +0 -1
  179. package/dist/http/middleware/upload.d.mts.map +0 -1
  180. package/dist/http/middleware/validate.d.mts.map +0 -1
  181. package/dist/http/middleware/views.d.mts.map +0 -1
  182. package/dist/http/router-builder.d.mts.map +0 -1
  183. package/dist/index-BQM9pJrV.d.mts.map +0 -1
  184. package/dist/index.d.mts.map +0 -1
  185. package/dist/interfaces-CwcdqfNq.d.mts +0 -54
  186. package/dist/path-Bj3vZMUY.d.mts.map +0 -1
  187. package/dist/plugin-3rKA0Loy.d.mts.map +0 -1
@@ -1,5 +1,5 @@
1
1
  /**
2
- * @forinda/kickjs v3.2.0
2
+ * @forinda/kickjs v4.0.0
3
3
  *
4
4
  * Copyright (c) Felix Orinda
5
5
  *
@@ -10,8 +10,14 @@
10
10
  */
11
11
  import { METADATA, Scope } from "./core/interfaces.mjs";
12
12
  import { createLogger } from "./core/logger.mjs";
13
- import { i as getMetaRecord, n as getClassMetaOrUndefined, o as getMethodMetaOrUndefined, r as getMetaMap, t as getClassMeta } from "./metadata-BFuoSEX6.mjs";
13
+ import { i as getMetaRecord, n as getClassMetaOrUndefined, o as getMethodMetaOrUndefined, r as getMetaMap, t as getClassMeta } from "./metadata-VQM9wChy.mjs";
14
+ import { createRequire } from "node:module";
14
15
  import "reflect-metadata";
16
+ import { existsSync, readFileSync, readdirSync } from "node:fs";
17
+ import { extname, isAbsolute, join, resolve, sep } from "node:path";
18
+ //#region \0rolldown/runtime.js
19
+ var __require = /* @__PURE__ */ createRequire(import.meta.url);
20
+ //#endregion
15
21
  //#region src/core/token.ts
16
22
  /**
17
23
  * Collision-safe injection tokens with phantom type parameters.
@@ -82,6 +88,288 @@ function isInjectionToken(value) {
82
88
  return typeof value === "object" && value !== null && value[INJECTION_TOKEN] === true;
83
89
  }
84
90
  //#endregion
91
+ //#region src/core/assets.ts
92
+ /**
93
+ * Asset manager runtime (assets-plan.md PR 3).
94
+ *
95
+ * Three accessor surfaces over one resolver engine:
96
+ *
97
+ * - `assets.x.y()` — Proxy ambient, autocomplete-friendly default.
98
+ * - `useAssets()` — hook returning the same Proxy; mockable per-call.
99
+ * - `resolveAsset(ns, k)` — string resolver for dynamic dispatch.
100
+ *
101
+ * Resolution path:
102
+ *
103
+ * 1. Load the build-time manifest (`<outDir>/.kickjs-assets.json`)
104
+ * when present. Manifest existence = "we're running from a built
105
+ * dist". Fast path; mapped paths returned verbatim.
106
+ * 2. Otherwise (dev / test) walk the assetMap src directories from
107
+ * `kick.config.{json,js,cjs}` and synthesise the same manifest
108
+ * shape in memory. First call pays the walk cost; subsequent
109
+ * calls hit the cache.
110
+ * 3. `KICK_ASSETS_ROOT` env var overrides everything — the resolver
111
+ * treats the path as the manifest directory and skips discovery.
112
+ *
113
+ * @module @forinda/kickjs/core/assets
114
+ */
115
+ const ASSET_MANIFEST_VERSION = 1;
116
+ /**
117
+ * DI token for the `assets` Proxy. Adopter code that wants to
118
+ * receive assets via constructor injection registers via
119
+ * `container.registerInstance(ASSETS, useAssets())` in `bootstrap()`
120
+ * and injects with `@Inject(ASSETS)`.
121
+ */
122
+ const ASSETS = createToken("kick/assets/Map");
123
+ var UnknownAssetError = class extends Error {
124
+ namespace;
125
+ key;
126
+ constructor(namespace, key) {
127
+ super(`Unknown asset '${namespace}/${key}'. Make sure the namespace exists in kick.config.ts assetMap and that the file is present in the source directory.`);
128
+ this.name = "UnknownAssetError";
129
+ this.namespace = namespace;
130
+ this.key = key;
131
+ }
132
+ };
133
+ let manifestCache = void 0;
134
+ function resolveAsset(namespace, key) {
135
+ const resolved = loadManifest();
136
+ if (!resolved) throw new UnknownAssetError(namespace, key);
137
+ const entry = resolved.manifest.entries[`${namespace}/${key}`];
138
+ if (!entry) throw new UnknownAssetError(namespace, key);
139
+ return isAbsolute(entry) ? entry : resolve(resolved.root, entry);
140
+ }
141
+ /** Reset the manifest cache. Tests use this; production code shouldn't need it. */
142
+ function clearAssetCache() {
143
+ manifestCache = void 0;
144
+ }
145
+ function loadManifest() {
146
+ if (manifestCache !== void 0) return manifestCache;
147
+ manifestCache = discoverManifest();
148
+ return manifestCache;
149
+ }
150
+ function discoverManifest() {
151
+ const envRoot = process.env.KICK_ASSETS_ROOT;
152
+ if (envRoot) {
153
+ const fromEnv = readBuiltManifest(envRoot);
154
+ if (fromEnv) return fromEnv;
155
+ }
156
+ const cwd = process.cwd();
157
+ const config = loadConfigSync(cwd);
158
+ const configOutDir = config?.build?.outDir;
159
+ if (configOutDir && !STANDARD_OUT_DIRS.includes(configOutDir)) {
160
+ const found = readBuiltManifest(resolve(cwd, configOutDir));
161
+ if (found) return found;
162
+ }
163
+ for (const candidate of STANDARD_OUT_DIRS) {
164
+ const found = readBuiltManifest(join(cwd, candidate));
165
+ if (found) return found;
166
+ }
167
+ return synthesiseDevManifest(cwd, config);
168
+ }
169
+ const STANDARD_OUT_DIRS = [
170
+ "dist",
171
+ "build",
172
+ "out"
173
+ ];
174
+ function readBuiltManifest(dir) {
175
+ const path = join(dir, ".kickjs-assets.json");
176
+ if (!existsSync(path)) return null;
177
+ try {
178
+ const raw = readFileSync(path, "utf-8");
179
+ const parsed = JSON.parse(raw);
180
+ if (parsed.version !== 1) return null;
181
+ if (!parsed.entries || typeof parsed.entries !== "object") return null;
182
+ return {
183
+ manifest: parsed,
184
+ root: resolve(dir)
185
+ };
186
+ } catch {
187
+ return null;
188
+ }
189
+ }
190
+ function synthesiseDevManifest(cwd, preloadedConfig) {
191
+ const config = preloadedConfig === void 0 ? loadConfigSync(cwd) : preloadedConfig;
192
+ if (!config?.assetMap) return null;
193
+ const entries = {};
194
+ const keyOwners = /* @__PURE__ */ new Map();
195
+ for (const [namespace, entry] of Object.entries(config.assetMap)) {
196
+ if (!entry || typeof entry.src !== "string") continue;
197
+ const srcAbs = resolve(cwd, entry.src);
198
+ if (!existsSync(srcAbs)) continue;
199
+ walkSync(srcAbs, srcAbs, (relPath, absPath) => {
200
+ if (entry.glob && !matchesGlobLite(relPath, entry.glob, namespace)) return;
201
+ const logicalKey = `${namespace}/${stripExt(relPath)}`;
202
+ const previous = keyOwners.get(logicalKey);
203
+ if (previous && previous !== relPath) console.warn(`[kickjs/assets] Dev collision in '${namespace}': '${previous}' and '${relPath}' both flatten to key '${logicalKey}'. Resolved to '${relPath}'. Rename one of them or filter via assetMap.${namespace}.glob.`);
204
+ keyOwners.set(logicalKey, relPath);
205
+ entries[logicalKey] = absPath;
206
+ });
207
+ }
208
+ return {
209
+ manifest: {
210
+ version: 1,
211
+ entries
212
+ },
213
+ root: cwd
214
+ };
215
+ }
216
+ const warnedGlobs = /* @__PURE__ */ new Set();
217
+ /**
218
+ * Tiny glob matcher used only by dev manifest synthesis. Covers the
219
+ * common assetMap glob patterns (`**\/*`, `**\/*.ext`,
220
+ * `**\/*.{a,b}`). Anything exotic prints a one-time warning + falls
221
+ * through to `**\/*` semantics rather than silently dropping files.
222
+ *
223
+ * The build pipeline (`packages/cli/src/asset-manager/build.ts`) uses
224
+ * the full `glob` package; adopters who hit the dev-mode warning
225
+ * should run `kick build:assets` to produce a real manifest.
226
+ */
227
+ function matchesGlobLite(relPath, pattern, namespace) {
228
+ if (pattern === "**/*" || pattern === "**") return true;
229
+ const singleExt = /^\*\*\/\*\.(\w+)$/.exec(pattern);
230
+ if (singleExt) return relPath.endsWith(`.${singleExt[1]}`);
231
+ const braceExt = /^\*\*\/\*\.\{([^}]+)\}$/.exec(pattern);
232
+ if (braceExt) return braceExt[1].split(",").map((e) => e.trim()).some((ext) => relPath.endsWith(`.${ext}`));
233
+ const tag = `${namespace}::${pattern}`;
234
+ if (!warnedGlobs.has(tag)) {
235
+ warnedGlobs.add(tag);
236
+ console.warn(`[kickjs/assets] Dev-mode glob '${pattern}' on '${namespace}' isn't recognised by the lite matcher. Falling back to '**/*'. Run 'kick build:assets' to use the full glob engine.`);
237
+ }
238
+ return true;
239
+ }
240
+ function walkSync(root, dir, onFile) {
241
+ let entries;
242
+ try {
243
+ entries = readdirSync(dir, { withFileTypes: true });
244
+ } catch {
245
+ return;
246
+ }
247
+ for (const entry of entries) {
248
+ if (entry.name === "node_modules" || entry.name.startsWith(".")) continue;
249
+ const full = join(dir, entry.name);
250
+ if (entry.isDirectory()) walkSync(root, full, onFile);
251
+ else if (entry.isFile()) onFile(full.slice(root.length + 1).split(sep).join("/"), full);
252
+ }
253
+ }
254
+ function stripExt(path) {
255
+ const ext = extname(path);
256
+ return ext ? path.slice(0, -ext.length) : path;
257
+ }
258
+ /**
259
+ * Sync `kick.config.{json,cjs,js}` loader for dev manifest
260
+ * synthesis. Avoids dynamic `import()` (would force every assets
261
+ * lookup to be async). TypeScript configs (`kick.config.ts`) are
262
+ * skipped here — adopters who use them should run `kick build:assets`
263
+ * to produce a real manifest the resolver can read.
264
+ */
265
+ function loadConfigSync(cwd) {
266
+ const jsonPath = join(cwd, "kick.config.json");
267
+ if (existsSync(jsonPath)) try {
268
+ return JSON.parse(readFileSync(jsonPath, "utf-8"));
269
+ } catch {
270
+ return null;
271
+ }
272
+ for (const filename of ["kick.config.cjs", "kick.config.js"]) {
273
+ const path = join(cwd, filename);
274
+ if (!existsSync(path)) continue;
275
+ try {
276
+ const { createRequire } = __require("node:module");
277
+ const mod = createRequire(join(cwd, "package.json"))(path);
278
+ return mod.default ?? mod ?? null;
279
+ } catch {
280
+ continue;
281
+ }
282
+ }
283
+ return null;
284
+ }
285
+ /**
286
+ * Keys we MUST return `undefined` for: returning anything truthy
287
+ * here causes Promise resolution to treat the Proxy as a thenable
288
+ * and `await` it (resolving to whatever `then.call(...)` produces).
289
+ * Two-element list deliberately — every other coercion-related key
290
+ * goes through {@link PASSTHROUGH_KEYS} below so `String(assets)`,
291
+ * template literals, and `util.inspect` keep working.
292
+ */
293
+ const PROMISE_DETECTION_KEYS = new Set(["then"]);
294
+ /**
295
+ * Keys we let fall through to the proxy target (a function-shaped
296
+ * object). The default `Object.prototype` implementations of
297
+ * `toString` / `valueOf` etc. are correct for these — returning
298
+ * `undefined` here would break `String(assets)` and template
299
+ * literals (`${assets}`) because `Symbol.toPrimitive` falling through
300
+ * to a missing `toString` throws. Adopters that hit `assets.toString`
301
+ * get `'function () {}'` back, which is fine — the contract is
302
+ * "asset access returns paths"; everything else is incidental.
303
+ */
304
+ const PASSTHROUGH_KEYS = new Set([
305
+ "toString",
306
+ "valueOf",
307
+ "constructor",
308
+ "prototype",
309
+ "name",
310
+ "length",
311
+ "asymmetricMatch",
312
+ "nodeType",
313
+ Symbol.toPrimitive,
314
+ Symbol.toStringTag,
315
+ Symbol.iterator,
316
+ Symbol.asyncIterator
317
+ ]);
318
+ function createNamespaceProxy(parts) {
319
+ const target = function() {};
320
+ return new Proxy(target, {
321
+ apply() {
322
+ if (parts.length < 2) throw new UnknownAssetError(parts[0] ?? "", "");
323
+ const [namespace, ...rest] = parts;
324
+ return resolveAsset(namespace, rest.join("/"));
325
+ },
326
+ get(t, prop) {
327
+ if (PROMISE_DETECTION_KEYS.has(prop)) return void 0;
328
+ if (PASSTHROUGH_KEYS.has(prop)) return Reflect.get(t, prop);
329
+ if (typeof prop === "symbol") return void 0;
330
+ return createNamespaceProxy([...parts, prop]);
331
+ }
332
+ });
333
+ }
334
+ function createAssetProxy() {
335
+ return new Proxy({}, { get(t, prop) {
336
+ if (PROMISE_DETECTION_KEYS.has(prop)) return void 0;
337
+ if (PASSTHROUGH_KEYS.has(prop)) return Reflect.get(t, prop);
338
+ if (typeof prop === "symbol") return void 0;
339
+ return createNamespaceProxy([prop]);
340
+ } });
341
+ }
342
+ /**
343
+ * Variant A — the ambient Proxy. Default accessor for static call
344
+ * sites where the namespace + key are literals known at compile time.
345
+ *
346
+ * @example
347
+ * ```ts
348
+ * import { assets } from '@forinda/kickjs'
349
+ * const path = assets.mails.welcome()
350
+ * ```
351
+ */
352
+ const assets = createAssetProxy();
353
+ /**
354
+ * Variant B — the hook accessor. Returns the same Proxy as `assets`;
355
+ * factory shape exists for testability + DI. Mock via
356
+ * `vi.mock('@forinda/kickjs', () => ({ useAssets: () => fakeAssets }))`.
357
+ *
358
+ * @example
359
+ * ```ts
360
+ * import { useAssets } from '@forinda/kickjs'
361
+ * class MailService {
362
+ * private assets = useAssets()
363
+ * send(name: string) {
364
+ * return ejs.renderFile(this.assets.mails[name](), {})
365
+ * }
366
+ * }
367
+ * ```
368
+ */
369
+ function useAssets() {
370
+ return assets;
371
+ }
372
+ //#endregion
85
373
  //#region src/core/container.ts
86
374
  const log = createLogger("Container");
87
375
  /** Create a Registration with observability defaults */
@@ -132,14 +420,16 @@ var Container = class Container {
132
420
  /** Callback invoked on reset so decorators can update their container reference */
133
421
  static _onReset = null;
134
422
  /**
135
- * Environment resolver for @Value decorator. Set by @forinda/kickjs-config
136
- * to return Zod-validated, type-coerced env values instead of raw process.env strings.
423
+ * Environment resolver for @Value decorator. Set by the unified
424
+ * `@forinda/kickjs` config layer to return Zod-validated, type-coerced
425
+ * env values instead of raw process.env strings.
137
426
  */
138
427
  static _envResolver = null;
139
428
  /**
140
- * Request store provider for REQUEST-scoped DI. Set by @forinda/kickjs-http
141
- * to return the current request's AsyncLocalStorage store.
142
- * Returns { instances: Map, values: Map } or null if outside a request.
429
+ * Request store provider for REQUEST-scoped DI. Set by the HTTP layer
430
+ * inside `@forinda/kickjs` to return the current request's
431
+ * AsyncLocalStorage store. Returns { instances: Map, values: Map } or
432
+ * null if outside a request.
143
433
  */
144
434
  static _requestStoreProvider = null;
145
435
  static getInstance() {
@@ -488,9 +778,23 @@ var Container = class Container {
488
778
  enumerable: true,
489
779
  configurable: true
490
780
  });
781
+ const assetProps = getMetaMap(METADATA.ASSET, target.prototype);
782
+ if (assetProps.size > 0) for (const [prop, config] of assetProps) {
783
+ const slashIdx = config.assetKey.indexOf("/");
784
+ if (slashIdx === -1) throw new Error(`@Asset('${config.assetKey}'): asset key must include a '/' separator (e.g. 'mails/welcome').`);
785
+ const namespace = config.assetKey.slice(0, slashIdx);
786
+ const key = config.assetKey.slice(slashIdx + 1);
787
+ Object.defineProperty(instance, prop, {
788
+ get() {
789
+ return resolveAsset(namespace, key);
790
+ },
791
+ enumerable: true,
792
+ configurable: true
793
+ });
794
+ }
491
795
  }
492
796
  };
493
797
  //#endregion
494
- export { isInjectionToken as a, createToken as i, tokenName as n, INJECTION_TOKEN as r, Container as t };
798
+ export { UnknownAssetError as a, resolveAsset as c, createToken as d, isInjectionToken as f, ASSET_MANIFEST_VERSION as i, useAssets as l, tokenName as n, assets as o, __require as p, ASSETS as r, clearAssetCache as s, Container as t, INJECTION_TOKEN as u };
495
799
 
496
- //# sourceMappingURL=container-Dnk43k54.mjs.map
800
+ //# sourceMappingURL=container-DYYSu58w.mjs.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"container-DYYSu58w.mjs","names":[],"sources":["../src/core/token.ts","../src/core/assets.ts","../src/core/container.ts"],"sourcesContent":["/**\n * Collision-safe injection tokens with phantom type parameters.\n *\n * `createToken<T>(name)` is the recommended way to declare any DI token\n * that isn't a class. Each call returns a unique frozen object — even if\n * two files write `createToken<X>('Logger')`, they produce two distinct\n * references that the container treats as different tokens. Collisions\n * become impossible by construction, not by convention.\n *\n * The phantom type parameter `T` lets `container.resolve(token)` infer\n * the correct return type without any codegen.\n *\n * ## Hardening layers\n *\n * KickJS has four DI token kinds, listed from safest to riskiest:\n *\n * 1. **Class identity** — `container.resolve(UserService)`. Reference\n * equality, never collides. Type-safe via `Constructor<T>` overload.\n * 2. **`createToken<T>(name)`** — frozen object identity, never collides.\n * Type-safe via the `InjectionToken<T>` overload.\n * 3. **Symbol** — `Symbol('foo')` is unique per call but `Symbol.for('foo')`\n * is interned and CAN collide. Discouraged.\n * 4. **Raw string `@Inject('foo')`** — high collision risk, untyped.\n * Reserved for legacy code and runtime-computed token names.\n *\n * Prefer (1) and (2). Use (4) only when you have to.\n *\n * @example\n * ```ts\n * // src/tokens.ts\n * export const DATABASE_URL = createToken<string>('config.database.url')\n * export const FEATURE_FLAGS = createToken<FeatureFlags>('app.features')\n *\n * // bootstrap\n * container.registerInstance(DATABASE_URL, process.env.DATABASE_URL!)\n *\n * // anywhere else\n * const url = container.resolve(DATABASE_URL) // typed as `string`\n * ```\n *\n * @module @forinda/kickjs/core/token\n */\n\n/**\n * Symbol marker stamped on every InjectionToken so the container can\n * detect them at runtime regardless of which package created them.\n *\n * Uses `Symbol.for()` so cross-package isolation (different copies of\n * `@forinda/kickjs` loaded under different module identities) still\n * shares the same marker.\n */\nexport const INJECTION_TOKEN: unique symbol = Symbol.for('@kickjs/InjectionToken') as never\n\n/**\n * A type-safe DI token. Each `createToken()` call returns a unique frozen\n * object identified by reference, not by the `name` string. Two\n * `createToken<X>('foo')` calls in different files produce two distinct\n * tokens that the container treats independently.\n *\n * The phantom `_type` parameter is never assigned at runtime — it exists\n * solely to thread the type through `container.resolve(token)`.\n */\nexport interface InjectionToken<T> {\n readonly [INJECTION_TOKEN]: true\n /** Descriptive name used in error messages, logs, and devtools */\n readonly name: string\n /** Phantom — never assigned at runtime */\n readonly _type?: T\n}\n\n/**\n * Create a collision-safe injection token.\n *\n * The returned token is a frozen object identified by reference, not by\n * the `name` string. The `name` is used only for error messages, logs,\n * and debugging.\n */\nexport function createToken<T>(name: string): InjectionToken<T> {\n return Object.freeze({\n [INJECTION_TOKEN]: true as const,\n name,\n })\n}\n\n/** Type guard — returns `true` if `value` is an InjectionToken */\nexport function isInjectionToken(value: unknown): value is InjectionToken<unknown> {\n return (\n typeof value === 'object' &&\n value !== null &&\n (value as Record<symbol, unknown>)[INJECTION_TOKEN] === true\n )\n}\n","/**\n * Asset manager runtime (assets-plan.md PR 3).\n *\n * Three accessor surfaces over one resolver engine:\n *\n * - `assets.x.y()` — Proxy ambient, autocomplete-friendly default.\n * - `useAssets()` — hook returning the same Proxy; mockable per-call.\n * - `resolveAsset(ns, k)` — string resolver for dynamic dispatch.\n *\n * Resolution path:\n *\n * 1. Load the build-time manifest (`<outDir>/.kickjs-assets.json`)\n * when present. Manifest existence = \"we're running from a built\n * dist\". Fast path; mapped paths returned verbatim.\n * 2. Otherwise (dev / test) walk the assetMap src directories from\n * `kick.config.{json,js,cjs}` and synthesise the same manifest\n * shape in memory. First call pays the walk cost; subsequent\n * calls hit the cache.\n * 3. `KICK_ASSETS_ROOT` env var overrides everything — the resolver\n * treats the path as the manifest directory and skips discovery.\n *\n * @module @forinda/kickjs/core/assets\n */\n\nimport { existsSync, readFileSync, readdirSync } from 'node:fs'\nimport { extname, isAbsolute, join, resolve, sep } from 'node:path'\nimport { createToken, type InjectionToken } from './token'\n\nexport const ASSET_MANIFEST_VERSION = 1 as const\n\ninterface AssetManifest {\n version: typeof ASSET_MANIFEST_VERSION\n entries: Record<string, string>\n}\n\ninterface ResolvedManifest {\n manifest: AssetManifest\n root: string\n}\n\n/**\n * Augmentable interface — `kick typegen` (assets-plan.md PR 4) emits\n * a `declare global` augmentation listing every namespace + key for\n * the project's `assetMap`. Adopters who haven't run typegen yet\n * still get a runtime-correct Proxy; only typed autocomplete waits\n * on the augmentation.\n */\nexport interface KickAssets {}\n\n/**\n * DI token for the `assets` Proxy. Adopter code that wants to\n * receive assets via constructor injection registers via\n * `container.registerInstance(ASSETS, useAssets())` in `bootstrap()`\n * and injects with `@Inject(ASSETS)`.\n */\nexport const ASSETS: InjectionToken<KickAssets> = createToken<KickAssets>('kick/assets/Map')\n\nexport class UnknownAssetError extends Error {\n readonly namespace: string\n readonly key: string\n constructor(namespace: string, key: string) {\n super(\n `Unknown asset '${namespace}/${key}'. ` +\n `Make sure the namespace exists in kick.config.ts assetMap and that the file is present in the source directory.`,\n )\n this.name = 'UnknownAssetError'\n this.namespace = namespace\n this.key = key\n }\n}\n\nlet manifestCache: ResolvedManifest | null | undefined = undefined\n\nexport function resolveAsset(namespace: string, key: string): string {\n const resolved = loadManifest()\n if (!resolved) {\n throw new UnknownAssetError(namespace, key)\n }\n const entry = resolved.manifest.entries[`${namespace}/${key}`]\n if (!entry) {\n throw new UnknownAssetError(namespace, key)\n }\n return isAbsolute(entry) ? entry : resolve(resolved.root, entry)\n}\n\n/** Reset the manifest cache. Tests use this; production code shouldn't need it. */\nexport function clearAssetCache(): void {\n manifestCache = undefined\n}\n\nfunction loadManifest(): ResolvedManifest | null {\n if (manifestCache !== undefined) return manifestCache\n manifestCache = discoverManifest()\n return manifestCache\n}\n\nfunction discoverManifest(): ResolvedManifest | null {\n const envRoot = process.env.KICK_ASSETS_ROOT\n if (envRoot) {\n const fromEnv = readBuiltManifest(envRoot)\n if (fromEnv) return fromEnv\n }\n\n const cwd = process.cwd()\n\n // Honour `kick.config.build.outDir` BEFORE the standard probe list\n // so adopters with non-default Vite outputs (e.g. `output/`,\n // `target/`, anything else) don't have to set KICK_ASSETS_ROOT\n // every time. Cached config load — same loader the dev fallback\n // uses. Skip when outDir matches one of the standard candidates;\n // it'd be probed redundantly otherwise.\n const config = loadConfigSync(cwd)\n const configOutDir = config?.build?.outDir\n if (configOutDir && !(STANDARD_OUT_DIRS as readonly string[]).includes(configOutDir)) {\n const found = readBuiltManifest(resolve(cwd, configOutDir))\n if (found) return found\n }\n\n for (const candidate of STANDARD_OUT_DIRS) {\n const found = readBuiltManifest(join(cwd, candidate))\n if (found) return found\n }\n\n return synthesiseDevManifest(cwd, config)\n}\n\nconst STANDARD_OUT_DIRS = ['dist', 'build', 'out'] as const\n\nfunction readBuiltManifest(dir: string): ResolvedManifest | null {\n const path = join(dir, '.kickjs-assets.json')\n if (!existsSync(path)) return null\n try {\n const raw = readFileSync(path, 'utf-8')\n const parsed = JSON.parse(raw) as Partial<AssetManifest>\n if (parsed.version !== ASSET_MANIFEST_VERSION) return null\n if (!parsed.entries || typeof parsed.entries !== 'object') return null\n return { manifest: parsed as AssetManifest, root: resolve(dir) }\n } catch {\n return null\n }\n}\n\ninterface AssetMapConfigShape {\n assetMap?: Record<string, { src: string; dest?: string; glob?: string }>\n build?: { outDir?: string }\n}\n\nfunction synthesiseDevManifest(\n cwd: string,\n preloadedConfig?: AssetMapConfigShape | null,\n): ResolvedManifest | null {\n const config = preloadedConfig === undefined ? loadConfigSync(cwd) : preloadedConfig\n if (!config?.assetMap) return null\n\n const entries: Record<string, string> = {}\n // Per-namespace owner tracker — same collision semantics as the\n // build pipeline (last-write-wins by walk order, warn on collision).\n // Walk order is filesystem-dependent in dev so the \"winner\" isn't\n // strictly alphabetical, but the warning still surfaces the conflict\n // so adopters can fix it before shipping.\n const keyOwners = new Map<string, string>()\n for (const [namespace, entry] of Object.entries(config.assetMap)) {\n if (!entry || typeof entry.src !== 'string') continue\n const srcAbs = resolve(cwd, entry.src)\n if (!existsSync(srcAbs)) continue\n walkSync(srcAbs, srcAbs, (relPath, absPath) => {\n if (entry.glob && !matchesGlobLite(relPath, entry.glob, namespace)) return\n const logicalKey = `${namespace}/${stripExt(relPath)}`\n const previous = keyOwners.get(logicalKey)\n if (previous && previous !== relPath) {\n console.warn(\n `[kickjs/assets] Dev collision in '${namespace}': '${previous}' and '${relPath}' both flatten to key '${logicalKey}'. ` +\n `Resolved to '${relPath}'. Rename one of them or filter via assetMap.${namespace}.glob.`,\n )\n }\n keyOwners.set(logicalKey, relPath)\n entries[logicalKey] = absPath\n })\n }\n\n return { manifest: { version: ASSET_MANIFEST_VERSION, entries }, root: cwd }\n}\n\nconst warnedGlobs = new Set<string>()\n\n/**\n * Tiny glob matcher used only by dev manifest synthesis. Covers the\n * common assetMap glob patterns (`**\\/*`, `**\\/*.ext`,\n * `**\\/*.{a,b}`). Anything exotic prints a one-time warning + falls\n * through to `**\\/*` semantics rather than silently dropping files.\n *\n * The build pipeline (`packages/cli/src/asset-manager/build.ts`) uses\n * the full `glob` package; adopters who hit the dev-mode warning\n * should run `kick build:assets` to produce a real manifest.\n */\nfunction matchesGlobLite(relPath: string, pattern: string, namespace: string): boolean {\n if (pattern === '**/*' || pattern === '**') return true\n const singleExt = /^\\*\\*\\/\\*\\.(\\w+)$/.exec(pattern)\n if (singleExt) return relPath.endsWith(`.${singleExt[1]}`)\n const braceExt = /^\\*\\*\\/\\*\\.\\{([^}]+)\\}$/.exec(pattern)\n if (braceExt) {\n const exts = braceExt[1].split(',').map((e) => e.trim())\n return exts.some((ext) => relPath.endsWith(`.${ext}`))\n }\n const tag = `${namespace}::${pattern}`\n if (!warnedGlobs.has(tag)) {\n warnedGlobs.add(tag)\n console.warn(\n `[kickjs/assets] Dev-mode glob '${pattern}' on '${namespace}' isn't recognised by the lite matcher. ` +\n `Falling back to '**/*'. Run 'kick build:assets' to use the full glob engine.`,\n )\n }\n return true\n}\n\nfunction walkSync(root: string, dir: string, onFile: (rel: string, abs: string) => void): void {\n let entries\n try {\n entries = readdirSync(dir, { withFileTypes: true })\n } catch {\n return\n }\n for (const entry of entries) {\n if (entry.name === 'node_modules' || entry.name.startsWith('.')) continue\n const full = join(dir, entry.name)\n if (entry.isDirectory()) {\n walkSync(root, full, onFile)\n } else if (entry.isFile()) {\n const rel = full\n .slice(root.length + 1)\n .split(sep)\n .join('/')\n onFile(rel, full)\n }\n }\n}\n\nfunction stripExt(path: string): string {\n const ext = extname(path)\n return ext ? path.slice(0, -ext.length) : path\n}\n\n/**\n * Sync `kick.config.{json,cjs,js}` loader for dev manifest\n * synthesis. Avoids dynamic `import()` (would force every assets\n * lookup to be async). TypeScript configs (`kick.config.ts`) are\n * skipped here — adopters who use them should run `kick build:assets`\n * to produce a real manifest the resolver can read.\n */\nfunction loadConfigSync(cwd: string): AssetMapConfigShape | null {\n const jsonPath = join(cwd, 'kick.config.json')\n if (existsSync(jsonPath)) {\n try {\n return JSON.parse(readFileSync(jsonPath, 'utf-8')) as AssetMapConfigShape\n } catch {\n return null\n }\n }\n for (const filename of ['kick.config.cjs', 'kick.config.js']) {\n const path = join(cwd, filename)\n if (!existsSync(path)) continue\n try {\n // eslint-disable-next-line @typescript-eslint/no-require-imports\n const { createRequire } = require('node:module') as typeof import('node:module')\n const req = createRequire(join(cwd, 'package.json'))\n const mod = req(path) as { default?: AssetMapConfigShape } & AssetMapConfigShape\n return mod.default ?? mod ?? null\n } catch {\n continue\n }\n }\n return null\n}\n\n/**\n * Keys we MUST return `undefined` for: returning anything truthy\n * here causes Promise resolution to treat the Proxy as a thenable\n * and `await` it (resolving to whatever `then.call(...)` produces).\n * Two-element list deliberately — every other coercion-related key\n * goes through {@link PASSTHROUGH_KEYS} below so `String(assets)`,\n * template literals, and `util.inspect` keep working.\n */\nconst PROMISE_DETECTION_KEYS: ReadonlySet<string | symbol> = new Set<string | symbol>(['then'])\n\n/**\n * Keys we let fall through to the proxy target (a function-shaped\n * object). The default `Object.prototype` implementations of\n * `toString` / `valueOf` etc. are correct for these — returning\n * `undefined` here would break `String(assets)` and template\n * literals (`${assets}`) because `Symbol.toPrimitive` falling through\n * to a missing `toString` throws. Adopters that hit `assets.toString`\n * get `'function () {}'` back, which is fine — the contract is\n * \"asset access returns paths\"; everything else is incidental.\n */\nconst PASSTHROUGH_KEYS: ReadonlySet<string | symbol> = new Set<string | symbol>([\n 'toString',\n 'valueOf',\n 'constructor',\n 'prototype',\n 'name',\n 'length',\n 'asymmetricMatch',\n 'nodeType',\n Symbol.toPrimitive,\n Symbol.toStringTag,\n Symbol.iterator,\n Symbol.asyncIterator,\n])\n\nfunction createNamespaceProxy(parts: readonly string[]): unknown {\n const target = function () {} as unknown as Record<string, unknown>\n return new Proxy(target, {\n apply() {\n if (parts.length < 2) {\n throw new UnknownAssetError(parts[0] ?? '', '')\n }\n const [namespace, ...rest] = parts\n return resolveAsset(namespace, rest.join('/'))\n },\n get(t, prop) {\n if (PROMISE_DETECTION_KEYS.has(prop)) return undefined\n if (PASSTHROUGH_KEYS.has(prop)) return Reflect.get(t, prop)\n if (typeof prop === 'symbol') return undefined\n return createNamespaceProxy([...parts, prop])\n },\n })\n}\n\nfunction createAssetProxy(): KickAssets {\n return new Proxy({} as Record<string, unknown>, {\n get(t, prop) {\n if (PROMISE_DETECTION_KEYS.has(prop)) return undefined\n if (PASSTHROUGH_KEYS.has(prop)) return Reflect.get(t, prop)\n if (typeof prop === 'symbol') return undefined\n return createNamespaceProxy([prop])\n },\n }) as unknown as KickAssets\n}\n\n/**\n * Variant A — the ambient Proxy. Default accessor for static call\n * sites where the namespace + key are literals known at compile time.\n *\n * @example\n * ```ts\n * import { assets } from '@forinda/kickjs'\n * const path = assets.mails.welcome()\n * ```\n */\nexport const assets: KickAssets = createAssetProxy()\n\n/**\n * Variant B — the hook accessor. Returns the same Proxy as `assets`;\n * factory shape exists for testability + DI. Mock via\n * `vi.mock('@forinda/kickjs', () => ({ useAssets: () => fakeAssets }))`.\n *\n * @example\n * ```ts\n * import { useAssets } from '@forinda/kickjs'\n * class MailService {\n * private assets = useAssets()\n * send(name: string) {\n * return ejs.renderFile(this.assets.mails[name](), {})\n * }\n * }\n * ```\n */\nexport function useAssets(): KickAssets {\n return assets\n}\n","import 'reflect-metadata'\nimport {\n Constructor,\n Scope,\n METADATA,\n type ClassKind,\n type PostConstructStatus,\n} from './interfaces'\nimport { resolveAsset } from './assets'\nimport { createLogger } from './logger'\nimport {\n getClassMeta,\n getClassMetaOrUndefined,\n getMetaMap,\n getMetaRecord,\n getMethodMetaOrUndefined,\n} from './metadata'\nimport { isInjectionToken, type InjectionToken } from './token'\n\nconst log = createLogger('Container')\n\n/** Internal registration entry that tracks how a dependency should be resolved */\ninterface Registration {\n target: Constructor\n scope: Scope\n instance?: any\n factory?: () => any\n // Observability fields\n kind: ClassKind\n resolveCount: number\n lastResolvedAt?: number\n firstResolvedAt?: number\n resolveDurationMs?: number\n postConstructStatus: PostConstructStatus\n dependencies: string[]\n}\n\n/** Create a Registration with observability defaults */\nfunction createReg(\n fields: Partial<Registration> & Pick<Registration, 'target' | 'scope'>,\n): Registration {\n return {\n kind: 'unknown',\n resolveCount: 0,\n postConstructStatus: 'skipped',\n dependencies: [],\n ...fields,\n }\n}\n\n/** Format a token for display in error messages */\nexport function tokenName(token: any): string {\n if (typeof token === 'symbol') return token.toString()\n if (isInjectionToken(token)) return token.name\n return token?.name || String(token)\n}\n\n// ── Persistent Store ────────────────────────────────────────────────────\n// globalThis-based storage that survives BOTH Container.reset() AND Vite's\n// ssrLoadModule() re-evaluation. When Vite re-evaluates a module, the\n// Container class gets a new identity (new statics). But globalThis persists.\n//\n// This is how DB connections, Redis clients, WsAdapter instances, and any\n// other stateful bindings survive HMR without being dropped.\n//\n// Pattern from: React Router (globalThis for state), Vinxi (globalThis.app)\n\n// ── Change Event System ─────────────────────────────────────────────────\n// Batched (50ms debounce) so `kick g module` creating 10+ files emits ONE\n// notification, not 10. Any adapter can subscribe: Swagger, DevTools, WS, etc.\n\n/** A single container change event */\nexport interface ContainerChangeEvent {\n token: string\n event: 'registered' | 'resolved' | 'invalidated'\n kind?: ClassKind\n timestamp: number\n}\n\n/** Listener that receives batched change events */\nexport type ContainerChangeListener = (changes: ContainerChangeEvent[]) => void\n\n/**\n * Type-safe registry of string DI tokens. Augmented by `kick typegen` —\n * the generated `.kickjs/types/registry.d.ts` adds entries like:\n *\n * ```ts\n * declare module '@forinda/kickjs' {\n * interface KickJsRegistry {\n * UserService: import('../../src/modules/users/user.service').UserService\n * }\n * }\n * ```\n *\n * Once typegen has run, `container.resolve('UserService')` returns the\n * correct type instead of `any`. Class-token resolution\n * (`container.resolve(UserService)`) is already type-safe via the\n * `Constructor<T>` overload and does not need typegen.\n */\nexport interface KickJsRegistry {}\n\ninterface PersistentStore {\n factories: Array<{ token: any; factory: () => any; scope: Scope }>\n instances: Array<{ token: any; instance: any }>\n /** Resolved instances keyed by string name — survives class identity changes */\n resolvedInstances: Map<string, any>\n}\n\nfunction getPersistentStore(): PersistentStore {\n if (!(globalThis as any).__kickjs_persistent) {\n ;(globalThis as any).__kickjs_persistent = {\n factories: [],\n instances: [],\n resolvedInstances: new Map(),\n } satisfies PersistentStore\n }\n return (globalThis as any).__kickjs_persistent\n}\n\n/**\n * Inversion-of-Control (IoC) container that manages dependency registration,\n * resolution, and lifecycle. Implements the Singleton pattern so all parts of\n * the application share a single container instance.\n *\n * Supports constructor injection, property injection (@Autowired),\n * factory registrations, and lifecycle hooks (@PostConstruct).\n *\n * Persistent state (DB connections, Redis, etc.) is stored on globalThis so\n * it survives both Container.reset() and Vite module re-evaluation.\n */\nexport class Container {\n private static instance: Container\n private registrations = new Map<any, Registration>()\n private resolving = new Set<any>()\n\n // ── Reactive change tracking ──────────────────────────────────────\n private changeListeners = new Set<ContainerChangeListener>()\n private pendingChanges: ContainerChangeEvent[] = []\n private notifyTimer: ReturnType<typeof setTimeout> | null = null\n private static readonly DEBOUNCE_MS = 50\n\n /** Callback set by the decorators module to flush pending registrations */\n static _onReady: ((container: Container) => void) | null = null\n /** Callback invoked on reset so decorators can update their container reference */\n static _onReset: ((container: Container) => void) | null = null\n /**\n * Environment resolver for @Value decorator. Set by the unified\n * `@forinda/kickjs` config layer to return Zod-validated, type-coerced\n * env values instead of raw process.env strings.\n */\n static _envResolver: ((key: string) => any) | null = null\n /**\n * Request store provider for REQUEST-scoped DI. Set by the HTTP layer\n * inside `@forinda/kickjs` to return the current request's\n * AsyncLocalStorage store. Returns { instances: Map, values: Map } or\n * null if outside a request.\n */\n static _requestStoreProvider:\n | (() => { instances: Map<any, any>; values: Map<any, any> } | null)\n | null = null\n\n static getInstance(): Container {\n if (!Container.instance) {\n Container.instance = new Container()\n }\n // Flush any decorator registrations that queued before the container existed\n if (Container._onReady) {\n Container._onReady(Container.instance)\n Container._onReady = null\n }\n return Container.instance\n }\n\n /**\n * Resets the container by replacing the singleton with a fresh instance.\n * Persistent registrations (DB, Redis, etc.) are replayed from globalThis\n * so they survive both reset() and Vite module re-evaluation.\n */\n static reset(): void {\n Container.instance = new Container()\n // Notify decorators so they update their container reference\n Container._onReset?.(Container.instance)\n // Replay persistent registrations from globalThis store\n const store = getPersistentStore()\n for (const { token, factory, scope } of store.factories) {\n if (!Container.instance.has(token)) {\n // Check if we have a previously resolved instance for this token\n const name = tokenName(token)\n const existing = store.resolvedInstances.get(name)\n Container.instance.registrations.set(\n token,\n createReg({\n target: Object as any,\n scope,\n factory,\n kind: 'factory',\n instance: existing, // Reuse resolved instance if available\n resolveCount: existing ? 1 : 0,\n postConstructStatus: existing ? 'completed' : 'skipped',\n }),\n )\n }\n }\n for (const { token, instance } of store.instances) {\n if (!Container.instance.has(token)) {\n Container.instance.registrations.set(\n token,\n createReg({\n target: instance.constructor,\n scope: Scope.SINGLETON,\n instance,\n kind: 'instance',\n postConstructStatus: 'completed',\n resolveCount: 1,\n }),\n )\n }\n }\n }\n\n /**\n * Create an isolated container instance (not the global singleton).\n * Useful for concurrent tests that must not share DI state.\n *\n * @example\n * ```ts\n * const container = Container.create()\n * container.register(UserService, UserService)\n * const svc = container.resolve(UserService)\n * ```\n */\n static create(): Container {\n return new Container()\n }\n\n /** Register a class constructor under the given token */\n register(token: any, target: Constructor, scope: Scope = Scope.SINGLETON): void {\n const kind = getClassMeta<ClassKind>(METADATA.CLASS_KIND, target, 'unknown')\n const dependencies = this.extractDependencies(target)\n const reg = createReg({ target, scope, kind, dependencies })\n this.registrations.set(token, reg)\n // Store a name-based fallback so HMR class re-creation (new identity)\n // can still resolve by the original class name.\n if (typeof token === 'function' && token.name) {\n this.registrations.set(`__hmr__${token.name}`, reg)\n }\n this.emit(tokenName(token), 'registered', kind)\n }\n\n /** Register a factory function under the given token */\n registerFactory(token: any, factory: () => any, scope: Scope = Scope.SINGLETON): void {\n const store = getPersistentStore()\n const name = tokenName(token)\n // Check if we already have a resolved instance from a previous HMR cycle.\n // Only reuse if the factory hasn't changed (same reference). When a new\n // factory is provided (e.g. swapping implementations), clear the stale\n // instance so the new factory runs on next resolve.\n const existingEntry = store.factories.find((r) => tokenName(r.token) === name)\n const factoryUnchanged = existingEntry?.factory === factory\n const existingInstance = factoryUnchanged ? store.resolvedInstances.get(name) : undefined\n\n // Clear stale resolved instance when factory changes\n if (!factoryUnchanged) {\n store.resolvedInstances.delete(name)\n }\n\n this.registrations.set(\n token,\n createReg({\n target: Object as any,\n scope,\n factory,\n kind: 'factory',\n instance: existingInstance,\n resolveCount: existingInstance ? 1 : 0,\n postConstructStatus: existingInstance ? 'completed' : 'skipped',\n }),\n )\n // Track in globalThis for persistence across HMR + module re-evaluation\n const idx = store.factories.findIndex((r) => tokenName(r.token) === name)\n if (idx >= 0) {\n store.factories[idx] = { token, factory, scope }\n } else {\n store.factories.push({ token, factory, scope })\n }\n this.emit(name, 'registered', 'factory')\n }\n\n /** Register a pre-constructed singleton instance */\n registerInstance(token: any, instance: any): void {\n const store = getPersistentStore()\n const name = tokenName(token)\n\n this.registrations.set(\n token,\n createReg({\n target: instance.constructor,\n scope: Scope.SINGLETON,\n instance,\n kind: 'instance',\n postConstructStatus: 'completed',\n resolveCount: 1,\n firstResolvedAt: Date.now(),\n lastResolvedAt: Date.now(),\n }),\n )\n // Track in globalThis for persistence across HMR + module re-evaluation\n store.resolvedInstances.set(name, instance)\n const idx = store.instances.findIndex((r) => tokenName(r.token) === name)\n if (idx >= 0) {\n store.instances[idx] = { token, instance }\n } else {\n store.instances.push({ token, instance })\n }\n this.emit(name, 'registered', 'instance')\n }\n\n /** Check if a binding exists for the given token */\n has(token: any): boolean {\n return this.registrations.has(token)\n }\n\n /** Return a snapshot of all registered tokens with their scope and instantiation status */\n getRegistrations(): Array<{\n token: string\n scope: string\n kind: ClassKind\n instantiated: boolean\n resolveCount: number\n lastResolvedAt?: number\n firstResolvedAt?: number\n resolveDurationMs?: number\n postConstructStatus: PostConstructStatus\n dependencies: string[]\n }> {\n const entries: Array<ReturnType<Container['getRegistrations']>[number]> = []\n for (const [token, reg] of this.registrations) {\n entries.push({\n token: tokenName(token),\n scope: reg.scope,\n kind: reg.kind,\n // Singletons check cached instance; transients check resolveCount\n instantiated:\n reg.scope === Scope.SINGLETON ? reg.instance !== undefined : reg.resolveCount > 0,\n resolveCount: reg.resolveCount,\n lastResolvedAt: reg.lastResolvedAt,\n firstResolvedAt: reg.firstResolvedAt,\n resolveDurationMs: reg.resolveDurationMs,\n postConstructStatus: reg.postConstructStatus,\n dependencies: reg.dependencies,\n })\n }\n return entries\n }\n\n /**\n * Resolve a dependency by its token.\n *\n * Four overloads, in order of preference:\n * - **`InjectionToken<T>`** (from `createToken<T>(name)`) → returns `T`.\n * Collision-safe by construction; no codegen required.\n * - **Class constructor** → returns an instance of that class. Always\n * type-safe; no codegen required.\n * - **String token in `KickJsRegistry`** (populated by `kick typegen`) →\n * returns the augmented type.\n * - **Anything else** → returns `any`. Use this only for legacy code or\n * string tokens that haven't been registered with typegen yet.\n */\n resolve<T>(token: InjectionToken<T>): T\n resolve<T>(token: Constructor<T>): T\n resolve<K extends keyof KickJsRegistry & string>(token: K): KickJsRegistry[K]\n resolve<T = any>(token: any): T\n resolve<T = any>(token: any): T {\n let reg = this.registrations.get(token)\n // HMR fallback: when Vite re-evaluates a module, decorated classes get new\n // identity. Try resolving by class name if the primary token lookup fails.\n if (!reg && typeof token === 'function' && token.name) {\n reg = this.registrations.get(`__hmr__${token.name}`)\n }\n if (!reg) {\n throw new Error(`No binding found for: ${tokenName(token)}`)\n }\n\n if (reg.scope === Scope.SINGLETON && reg.instance !== undefined) {\n reg.resolveCount++\n reg.lastResolvedAt = Date.now()\n return reg.instance\n }\n\n // REQUEST scope: one instance per HTTP request, cached in AsyncLocalStorage\n if (reg.scope === Scope.REQUEST) {\n if (!Container._requestStoreProvider) {\n throw new Error(\n `Cannot resolve REQUEST-scoped \"${tokenName(token)}\": no request store provider configured. ` +\n `Ensure requestScopeMiddleware() is in your middleware pipeline.`,\n )\n }\n const store = Container._requestStoreProvider()\n if (!store) {\n throw new Error(\n `Cannot resolve REQUEST-scoped \"${tokenName(token)}\" outside an HTTP request context.`,\n )\n }\n // Check for pre-registered request values (user, tenant, etc.)\n if (store.values.has(token)) {\n reg.resolveCount++\n reg.lastResolvedAt = Date.now()\n return store.values.get(token) as T\n }\n // Check per-request instance cache\n if (store.instances.has(token)) {\n reg.resolveCount++\n reg.lastResolvedAt = Date.now()\n return store.instances.get(token) as T\n }\n // Create instance and cache for this request only\n const start = performance.now()\n const instance = this.createInstance(reg)\n reg.resolveDurationMs = performance.now() - start\n reg.resolveCount++\n reg.lastResolvedAt = Date.now()\n if (!reg.firstResolvedAt) reg.firstResolvedAt = Date.now()\n store.instances.set(token, instance)\n return instance as T\n }\n\n if (reg.factory) {\n const start = performance.now()\n const instance = reg.factory()\n reg.resolveDurationMs = performance.now() - start\n reg.resolveCount++\n reg.lastResolvedAt = Date.now()\n if (!reg.firstResolvedAt) reg.firstResolvedAt = Date.now()\n if (reg.scope === Scope.SINGLETON) {\n reg.instance = instance\n // Persist resolved factory instances so they survive module re-evaluation\n getPersistentStore().resolvedInstances.set(tokenName(token), instance)\n }\n return instance\n }\n\n if (this.resolving.has(token)) {\n const chain = [...this.resolving].map(tokenName)\n chain.push(tokenName(token))\n throw new Error(`Circular dependency detected: ${chain.join(' -> ')}`)\n }\n this.resolving.add(token)\n\n try {\n const start = performance.now()\n const instance = this.createInstance(reg)\n reg.resolveDurationMs = performance.now() - start\n reg.resolveCount++\n reg.lastResolvedAt = Date.now()\n if (!reg.firstResolvedAt) reg.firstResolvedAt = Date.now()\n if (reg.scope === Scope.SINGLETON) {\n reg.instance = instance\n }\n return instance\n } finally {\n this.resolving.delete(token)\n }\n }\n\n /** Lifecycle hook called during Application.setup() after module registration */\n bootstrap(): void {\n // Reserved for future use — adapters and modules register via\n // container.register(), registerFactory(), and registerInstance().\n }\n\n // ── Reactive Change API ─────────────────────────────────────────────\n\n /**\n * Subscribe to container changes. Returns an unsubscribe function.\n *\n * Changes are batched (50ms debounce) so bulk operations like\n * `kick g module` creating 10+ files emit ONE batch, not 10 events.\n *\n * Any adapter can subscribe:\n * - SwaggerAdapter: re-build spec when controllers change\n * - DevToolsAdapter: push SSE events to dashboard\n * - WsAdapter: re-discover namespaces when controllers change\n * - OtelAdapter: emit tracing spans for DI resolution\n * - Custom user adapters\n *\n * @example\n * ```ts\n * const unsub = container.onChange((changes) => {\n * for (const c of changes) {\n * console.log(`${c.event}: ${c.token} (${c.kind})`)\n * }\n * })\n * // later:\n * unsub()\n * ```\n */\n onChange(callback: ContainerChangeListener): () => void {\n this.changeListeners.add(callback)\n return () => this.changeListeners.delete(callback)\n }\n\n /**\n * Invalidate a specific registration. Clears the cached instance so the\n * next resolve() creates a fresh one. Also invalidates dependents\n * (anything that injected this token) by walking the dependency graph.\n *\n * Called by the Vite HMR plugin when a module file changes.\n * Skips persistent registrations (DB connections, etc.).\n */\n invalidate(token: any): void {\n const name = tokenName(token)\n // Try both the token itself and the HMR fallback name\n const reg = this.registrations.get(token) ?? this.registrations.get(`__hmr__${name}`)\n if (!reg) return\n\n // Don't invalidate persistent registrations (DB, Redis, etc.)\n const store = getPersistentStore()\n if (store.resolvedInstances.has(name)) return\n\n // Clear cached instance — next resolve() will re-create\n reg.instance = undefined\n reg.resolveCount = 0\n reg.postConstructStatus = 'skipped'\n this.emit(name, 'invalidated', reg.kind)\n\n // Walk dependency graph — invalidate anything that injected this token\n for (const [depToken, depReg] of this.registrations) {\n if (depReg.dependencies.includes(name)) {\n this.invalidate(depToken)\n }\n }\n }\n\n /** Batch-emit a change event (debounced, flushed after 50ms of quiet) */\n private emit(token: string, event: ContainerChangeEvent['event'], kind?: ClassKind): void {\n this.pendingChanges.push({ token, event, kind, timestamp: Date.now() })\n\n if (this.notifyTimer) clearTimeout(this.notifyTimer)\n this.notifyTimer = setTimeout(() => {\n const batch = this.pendingChanges.splice(0)\n if (batch.length === 0) return\n for (const listener of this.changeListeners) {\n try {\n listener(batch)\n } catch {\n // Don't let one broken listener break others\n }\n }\n }, Container.DEBOUNCE_MS)\n }\n\n /** Flush pending change events immediately (useful in tests) */\n flushChanges(): void {\n if (this.notifyTimer) {\n clearTimeout(this.notifyTimer)\n this.notifyTimer = null\n }\n const batch = this.pendingChanges.splice(0)\n if (batch.length === 0) return\n for (const listener of this.changeListeners) {\n try {\n listener(batch)\n } catch {\n // Don't let one broken listener break others\n }\n }\n }\n\n private createInstance(reg: Registration): any {\n const paramTypes = getClassMeta<Constructor[]>(METADATA.PARAM_TYPES, reg.target, [])\n\n const args = paramTypes.map((paramType, index) => {\n // Check for @Inject token override on constructor parameter\n const injectTokens = getMetaRecord<any>(METADATA.INJECT, reg.target)\n const token = injectTokens[index] || paramType\n // Scope validation: SINGLETON cannot inject REQUEST-scoped dependencies\n if (reg.scope === Scope.SINGLETON) {\n const depReg = this.registrations.get(token)\n if (depReg && depReg.scope === Scope.REQUEST) {\n throw new Error(\n `Cannot inject REQUEST-scoped \"${tokenName(token)}\" into SINGLETON \"${tokenName(reg.target)}\". ` +\n `Singletons outlive requests. Use TRANSIENT or REQUEST scope for the parent.`,\n )\n }\n }\n return this.resolve(token)\n })\n\n const instance = new reg.target(...args)\n\n // Property injection via @Autowired\n this.injectProperties(instance, reg.target)\n\n // @PostConstruct lifecycle hook\n const postConstruct = getClassMetaOrUndefined<string | symbol>(\n METADATA.POST_CONSTRUCT,\n reg.target.prototype,\n )\n if (postConstruct && typeof instance[postConstruct] === 'function') {\n try {\n const result = instance[postConstruct]()\n if (result && typeof result.then === 'function') {\n reg.postConstructStatus = 'pending'\n ;(result as Promise<void>)\n .then(() => {\n reg.postConstructStatus = 'completed'\n })\n .catch(() => {\n reg.postConstructStatus = 'failed'\n })\n log.warn(\n `@PostConstruct on ${tokenName(reg.target)}.${String(postConstruct)}() returned a Promise ` +\n `but the container is synchronous. The async operation will not be awaited.`,\n )\n } else {\n reg.postConstructStatus = 'completed'\n }\n } catch (err) {\n reg.postConstructStatus = 'failed'\n log.error(\n err,\n `@PostConstruct on ${tokenName(reg.target)}.${String(postConstruct)}() threw an error`,\n )\n }\n }\n\n return instance\n }\n\n /** Extract dependency token names from constructor metadata */\n private extractDependencies(target: Constructor): string[] {\n const paramTypes = getClassMeta<Constructor[]>(METADATA.PARAM_TYPES, target, [])\n const injectTokens = getMetaRecord<any>(METADATA.INJECT, target)\n return paramTypes.map((type, index) => {\n const token = injectTokens[index] || type\n return tokenName(token)\n })\n }\n\n private injectProperties(instance: any, target: Constructor): void {\n // @Autowired — lazy DI property injection\n const autowiredProps = getMetaMap<string, any>(METADATA.AUTOWIRED, target.prototype)\n\n for (const [prop, token] of autowiredProps) {\n const resolvedToken =\n token || getMethodMetaOrUndefined(METADATA.PROPERTY_TYPE, target.prototype, prop)\n if (resolvedToken) {\n Object.defineProperty(instance, prop, {\n get: () => this.resolve(resolvedToken),\n enumerable: true,\n configurable: true,\n })\n }\n }\n\n // @Value — lazy environment variable injection\n const valueProps = getMetaMap<string, { envKey: string; defaultValue?: any }>(\n METADATA.VALUE,\n target.prototype,\n )\n\n for (const [prop, config] of valueProps) {\n Object.defineProperty(instance, prop, {\n get() {\n // Use the registered env resolver if available (wired by the\n // config layer in @forinda/kickjs). Returns Zod-validated,\n // type-coerced values (e.g. PORT as number).\n if (Container._envResolver) {\n const val = Container._envResolver(config.envKey)\n if (val !== undefined) return val\n }\n\n // Fallback to raw process.env for apps that haven't called loadEnv()\n const val = process.env[config.envKey]\n if (val !== undefined) return val\n if (config.defaultValue !== undefined) return config.defaultValue\n throw new Error(\n `@Value('${config.envKey}'): Environment variable \"${config.envKey}\" is not set and no default was provided.`,\n )\n },\n enumerable: true,\n configurable: true,\n })\n }\n\n // @Asset — lazy asset path injection (assets-plan.md). Same lazy-\n // getter pattern as @Value: resolve on every property access via\n // the asset manager's cached resolver, not at class instantiation.\n // Splits the key on the FIRST '/' so `mails/orders/confirmation`\n // becomes namespace=`mails` + key=`orders/confirmation`.\n const assetProps = getMetaMap<string, { assetKey: string }>(METADATA.ASSET, target.prototype)\n\n if (assetProps.size > 0) {\n for (const [prop, config] of assetProps) {\n const slashIdx = config.assetKey.indexOf('/')\n if (slashIdx === -1) {\n throw new Error(\n `@Asset('${config.assetKey}'): asset key must include a '/' separator (e.g. 'mails/welcome').`,\n )\n }\n const namespace = config.assetKey.slice(0, slashIdx)\n const key = config.assetKey.slice(slashIdx + 1)\n Object.defineProperty(instance, prop, {\n get() {\n return resolveAsset(namespace, key)\n },\n enumerable: true,\n configurable: true,\n })\n }\n }\n }\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAmDA,MAAa,kBAAiC,OAAO,IAAI,yBAAyB;;;;;;;;AA0BlF,SAAgB,YAAe,MAAiC;AAC9D,QAAO,OAAO,OAAO;GAClB,kBAAkB;EACnB;EACD,CAAC;;;AAIJ,SAAgB,iBAAiB,OAAkD;AACjF,QACE,OAAO,UAAU,YACjB,UAAU,QACT,MAAkC,qBAAqB;;;;;;;;;;;;;;;;;;;;;;;;;;;AC7D5D,MAAa,yBAAyB;;;;;;;AA2BtC,MA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C3B,QAAO,eAAe,UAAU,MAAM;GACpC,MAAM;AAIJ,QAAI,UAAU,cAAc;KAC1B,MAAM,MAAM,UAAU,aAAa,OAAO,OAAO;AACjD,SAAI,QAAQ,KAAA,EAAW,QAAO;;IAIhC,MAAM,MAAM,QAAQ,IAAI,OAAO;AAC/B,QAAI,QAAQ,KAAA,EAAW,QAAO;AAC9B,QAAI,OAAO,iBAAiB,KAAA,EAAW,QAAO,OAAO;AACrD,UAAM,IAAI,MACR,WAAW,OAAO,OAAO,4BAA4B,OAAO,OAAO,2CACpE;;GAEH,YAAY;GACZ,cAAc;GACf,CAAC;EAQJ,MAAM,aAAa,WAAyC,SAAS,OAAO,OAAO,UAAU;AAE7F,MAAI,WAAW,OAAO,EACpB,MAAK,MAAM,CAAC,MAAM,WAAW,YAAY;GACvC,MAAM,WAAW,OAAO,SAAS,QAAQ,IAAI;AAC7C,OAAI,aAAa,GACf,OAAM,IAAI,MACR,WAAW,OAAO,SAAS,oEAC5B;GAEH,MAAM,YAAY,OAAO,SAAS,MAAM,GAAG,SAAS;GACpD,MAAM,MAAM,OAAO,SAAS,MAAM,WAAW,EAAE;AAC/C,UAAO,eAAe,UAAU,MAAM;IACpC,MAAM;AACJ,YAAO,aAAa,WAAW,IAAI;;IAErC,YAAY;IACZ,cAAc;IACf,CAAC"}
@@ -1,5 +1,5 @@
1
1
  /**
2
- * @forinda/kickjs v3.2.0
2
+ * @forinda/kickjs v4.0.0
3
3
  *
4
4
  * Copyright (c) Felix Orinda
5
5
  *
@@ -8,8 +8,7 @@
8
8
  *
9
9
  * @license MIT
10
10
  */
11
- import { Logger } from "./core/logger.mjs";
12
- import { i as parseQuery } from "./query-BcYEjYyX.mjs";
11
+ import { i as parseQuery } from "./query-DJMxdx5r.mjs";
13
12
  import { AsyncLocalStorage } from "node:async_hooks";
14
13
  //#region src/http/request-store.ts
15
14
  /** AsyncLocalStorage instance shared across the framework */
@@ -25,20 +24,6 @@ function getRequestStore() {
25
24
  }
26
25
  //#endregion
27
26
  //#region src/http/context.ts
28
- const log = Logger.for("RequestContext");
29
- /**
30
- * One-time non-production warning when {@link RequestContext} falls back to
31
- * `req.__ctxMeta` because no AsyncLocalStorage frame is active. This is the
32
- * back-compat path for ad-hoc context construction (mostly tests). The
33
- * fallback is deprecated and will be removed in the next major.
34
- */
35
- let warnedAboutCtxMetaFallback = false;
36
- function warnCtxMetaFallbackOnce() {
37
- if (warnedAboutCtxMetaFallback) return;
38
- warnedAboutCtxMetaFallback = true;
39
- if (process.env.NODE_ENV === "production") return;
40
- log.warn("RequestContext.metadata fell back to req.__ctxMeta because no AsyncLocalStorage frame was active. Mount requestScopeMiddleware() before constructing RequestContext to use the unified ALS-backed store. The req.__ctxMeta path is deprecated and will be removed in the next major.");
41
- }
42
27
  /**
43
28
  * Unified request/response abstraction passed to every controller method.
44
29
  * Shields handlers from raw Express objects and provides convenience methods.
@@ -54,27 +39,35 @@ var RequestContext = class {
54
39
  this.next = next;
55
40
  }
56
41
  /**
57
- * Per-request metadata map shared across all RequestContext instances
58
- * for the same request.
42
+ * Read-side accessor for the per-request metadata map.
59
43
  *
60
- * Backed by `requestStore.getStore()?.values` (the AsyncLocalStorage
61
- * map shared with the Context Contributor pipeline) when an ALS frame
62
- * is active — the canonical, supported path.
44
+ * Returns the AsyncLocalStorage map (`requestStore.getStore().values`)
45
+ * shared with the Context Contributor pipeline when an ALS frame is
46
+ * active. Returns `null` outside any frame — read-side callers
47
+ * (`ctx.get`, `ctx.user`, `ctx.tenantId`, `ctx.roles`) treat that as
48
+ * "no metadata" and fall through to their `req.*` defaults. Reads
49
+ * never throw because outside an ALS frame nobody could have written
50
+ * via `ctx.set` anyway, so an empty answer is the truthful one.
51
+ */
52
+ metadataReadOnly() {
53
+ return requestStore.getStore()?.values ?? null;
54
+ }
55
+ /**
56
+ * Write-side accessor for the per-request metadata map.
63
57
  *
64
- * Falls back to a lazily-attached `req.__ctxMeta` Map for ad-hoc
65
- * construction outside any frame — typically test code that builds a
66
- * RequestContext directly without mounting `requestScopeMiddleware()`.
67
- * That fallback path is **deprecated** and will be removed in the next
68
- * major; a one-time non-production warning fires the first time it is
69
- * hit so adopters can migrate to ALS-backed contexts.
58
+ * Returns the same map as {@link metadataReadOnly} when an ALS frame
59
+ * is active. Throws otherwise — writing to a fallback map outside
60
+ * the ALS frame would silently lose data because other call sites
61
+ * (downstream contributors, request-logger, etc.) read from the
62
+ * canonical store and would never see it. Mount
63
+ * `requestScopeMiddleware()` (Application does this for you in
64
+ * `'auto'` mode) or wrap your test setup in
65
+ * `requestStore.run({...}, () => …)` to fix.
70
66
  */
71
- get metadata() {
67
+ metadataForWrite() {
72
68
  const store = requestStore.getStore();
73
69
  if (store) return store.values;
74
- warnCtxMetaFallbackOnce();
75
- const r = this.req;
76
- if (!r.__ctxMeta) r.__ctxMeta = /* @__PURE__ */ new Map();
77
- return r.__ctxMeta;
70
+ throw new Error("RequestContext.set called outside an AsyncLocalStorage frame. Mount requestScopeMiddleware() before constructing RequestContext, or wrap test setup in requestStore.run({ requestId, instances: new Map(), values: new Map() }, () => ...).");
78
71
  }
79
72
  get body() {
80
73
  return this.req.body;
@@ -115,7 +108,7 @@ var RequestContext = class {
115
108
  * ```
116
109
  */
117
110
  get user() {
118
- return this.metadata.get("user") ?? this.req.user;
111
+ return this.metadataReadOnly()?.get("user") ?? this.req.user;
119
112
  }
120
113
  /**
121
114
  * Tenant identifier for multi-tenant apps. Reads `user.tenantId` —
@@ -181,16 +174,15 @@ var RequestContext = class {
181
174
  * `ctx.get<MyType>('custom')`.
182
175
  */
183
176
  get(key) {
184
- return this.metadata.get(key);
177
+ return this.metadataReadOnly()?.get(key);
185
178
  }
186
179
  /**
187
- * Write a value to the per-request metadata store.
188
- *
189
- * When `ContextMeta` has been augmented with a matching key, the value
190
- * type is checked at compile time.
180
+ * Write a value to the per-request metadata store. Throws when no
181
+ * AsyncLocalStorage frame is active — see {@link metadataForWrite}
182
+ * for why a silent fallback is the wrong default.
191
183
  */
192
184
  set(key, value) {
193
- this.metadata.set(key, value);
185
+ this.metadataForWrite().set(key, value);
194
186
  }
195
187
  json(data, status = 200) {
196
188
  return this.res.status(status).json(data);
@@ -324,4 +316,4 @@ var RequestContext = class {
324
316
  //#endregion
325
317
  export { getRequestStore as n, requestStore as r, RequestContext as t };
326
318
 
327
- //# sourceMappingURL=context-OktlOQBQ.mjs.map
319
+ //# sourceMappingURL=context-BAGzqT7-.mjs.map