@forinda/kickjs 10.8.0 → 10.9.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 (140) hide show
  1. package/dist/{adapter-B0Q8PzQ3.d.mts → adapter-DLjn8q0c.d.mts} +2 -2
  2. package/dist/{adapter-B0Q8PzQ3.d.mts.map → adapter-DLjn8q0c.d.mts.map} +1 -1
  3. package/dist/{application-CWPS2sst.mjs → application-2cqnmnMR.mjs} +4 -4
  4. package/dist/{application-CWPS2sst.mjs.map → application-2cqnmnMR.mjs.map} +1 -1
  5. package/dist/{application-BND5VDje.d.mts → application-w0Xnc35j.d.mts} +15 -8
  6. package/dist/{application-BND5VDje.d.mts.map → application-w0Xnc35j.d.mts.map} +1 -1
  7. package/dist/{background-D8VpVDrH.mjs → background-X_AU4qmI.mjs} +3 -3
  8. package/dist/{background-D8VpVDrH.mjs.map → background-X_AU4qmI.mjs.map} +1 -1
  9. package/dist/{body-policy-DAoHt4Cr.mjs → body-policy-BkjZt30w.mjs} +2 -2
  10. package/dist/{body-policy-DAoHt4Cr.mjs.map → body-policy-BkjZt30w.mjs.map} +1 -1
  11. package/dist/{bootstrap-BpRQ1_KV.mjs → bootstrap-CF5TB3dt.mjs} +3 -3
  12. package/dist/{bootstrap-BpRQ1_KV.mjs.map → bootstrap-CF5TB3dt.mjs.map} +1 -1
  13. package/dist/{bounded-counters-BMHzTpuZ.mjs → bounded-counters-BdHZ2tZ9.mjs} +2 -2
  14. package/dist/{bounded-counters-BMHzTpuZ.mjs.map → bounded-counters-BdHZ2tZ9.mjs.map} +1 -1
  15. package/dist/{client-ip-COnqHbaF.mjs → client-ip-Db1WMxl6.mjs} +2 -2
  16. package/dist/{client-ip-COnqHbaF.mjs.map → client-ip-Db1WMxl6.mjs.map} +1 -1
  17. package/dist/config/index.mjs +2 -2
  18. package/dist/{config-Cq6_Qr4r.mjs → config-DeWWBNz5.mjs} +3 -3
  19. package/dist/{config-Cq6_Qr4r.mjs.map → config-DeWWBNz5.mjs.map} +1 -1
  20. package/dist/{context-CX0TLa4H.mjs → context-CfGBpRlD.mjs} +3 -3
  21. package/dist/{context-CX0TLa4H.mjs.map → context-CfGBpRlD.mjs.map} +1 -1
  22. package/dist/{context-errors-Chi6ESHh.mjs → context-errors-QfmGMX4-.mjs} +2 -2
  23. package/dist/{context-errors-Chi6ESHh.mjs.map → context-errors-QfmGMX4-.mjs.map} +1 -1
  24. package/dist/{contributor-runner-Da7v9Whk.mjs → contributor-runner-DmHsL9iD.mjs} +3 -3
  25. package/dist/{contributor-runner-Da7v9Whk.mjs.map → contributor-runner-DmHsL9iD.mjs.map} +1 -1
  26. package/dist/core/adapter.d.mts +1 -1
  27. package/dist/core/adapter.mjs +1 -1
  28. package/dist/core/app-module.mjs +1 -1
  29. package/dist/core/cache.mjs +1 -1
  30. package/dist/core/container.mjs +2 -2
  31. package/dist/core/cron.mjs +2 -2
  32. package/dist/core/decorators.mjs +2 -2
  33. package/dist/core/errors.mjs +1 -1
  34. package/dist/core/interfaces.mjs +1 -1
  35. package/dist/core/logger.mjs +1 -1
  36. package/dist/core/path.mjs +1 -1
  37. package/dist/core/plugin.d.mts +1 -1
  38. package/dist/core/plugin.mjs +1 -1
  39. package/dist/core/reactivity.mjs +2 -2
  40. package/dist/{core-CiwDroJ7.mjs → core-DaYy5tKw.mjs} +3 -3
  41. package/dist/{core-CiwDroJ7.mjs.map → core-DaYy5tKw.mjs.map} +1 -1
  42. package/dist/{decorate-DdzHOAA1.mjs → decorate-8MLQUvoW.mjs} +3 -3
  43. package/dist/{decorate-DdzHOAA1.mjs.map → decorate-8MLQUvoW.mjs.map} +1 -1
  44. package/dist/{define-adapter-DJnPaqbo.mjs → define-adapter-By20TI53.mjs} +2 -2
  45. package/dist/{define-adapter-DJnPaqbo.mjs.map → define-adapter-By20TI53.mjs.map} +1 -1
  46. package/dist/{di-hooks-rXw3zCor.mjs → di-hooks-CGr13ce2.mjs} +6 -4
  47. package/dist/{di-hooks-rXw3zCor.mjs.map → di-hooks-CGr13ce2.mjs.map} +1 -1
  48. package/dist/{disposables-Cpde_0BE.mjs → disposables-V3Xlgvgk.mjs} +1 -1
  49. package/dist/{error-handler-C1I8a4wY.d.mts → error-handler-BrihKETE.d.mts} +2 -2
  50. package/dist/{error-handler-C1I8a4wY.d.mts.map → error-handler-BrihKETE.d.mts.map} +1 -1
  51. package/dist/{express-fiMFHEPO.mjs → express-CZHu70JR.mjs} +3 -3
  52. package/dist/{express-fiMFHEPO.mjs.map → express-CZHu70JR.mjs.map} +1 -1
  53. package/dist/{express-lazy-DxQzDeza.mjs → express-lazy-BixrSsYx.mjs} +3 -3
  54. package/dist/{express-lazy-DxQzDeza.mjs.map → express-lazy-BixrSsYx.mjs.map} +1 -1
  55. package/dist/{handler-D5QS_90y.mjs → handler-DFZIsJH1.mjs} +3 -3
  56. package/dist/{handler-D5QS_90y.mjs.map → handler-DFZIsJH1.mjs.map} +1 -1
  57. package/dist/{host-D7vw6t1i.mjs → host-CJdqJGsr.mjs} +2 -2
  58. package/dist/{host-D7vw6t1i.mjs.map → host-CJdqJGsr.mjs.map} +1 -1
  59. package/dist/http/application.d.mts +1 -1
  60. package/dist/http/application.mjs +2 -2
  61. package/dist/http/bootstrap.d.mts +1 -1
  62. package/dist/http/bootstrap.mjs +2 -2
  63. package/dist/http/context.d.mts +1 -1
  64. package/dist/http/context.mjs +2 -2
  65. package/dist/http/middleware/allowed-hosts.mjs +2 -2
  66. package/dist/http/middleware/breach-padding.mjs +1 -1
  67. package/dist/http/middleware/cors.mjs +1 -1
  68. package/dist/http/middleware/csrf.mjs +2 -2
  69. package/dist/http/middleware/error-handler.d.mts +1 -1
  70. package/dist/http/middleware/error-handler.mjs +2 -2
  71. package/dist/http/middleware/helmet.mjs +1 -1
  72. package/dist/http/middleware/rate-limit.mjs +2 -2
  73. package/dist/http/middleware/request-id.mjs +1 -1
  74. package/dist/http/middleware/request-logger.mjs +2 -2
  75. package/dist/http/middleware/session.mjs +2 -2
  76. package/dist/http/middleware/spa.d.mts +1 -1
  77. package/dist/http/middleware/spa.mjs +2 -2
  78. package/dist/http/middleware/upload.d.mts +2 -2
  79. package/dist/http/middleware/upload.mjs +2 -2
  80. package/dist/http/middleware/validate.mjs +1 -1
  81. package/dist/http/middleware/views.d.mts +1 -1
  82. package/dist/http/middleware/views.mjs +2 -2
  83. package/dist/http/query/index.mjs +2 -2
  84. package/dist/http/router-builder.d.mts +1 -1
  85. package/dist/http/router-builder.mjs +2 -2
  86. package/dist/http/runtimes/express.d.mts +2 -2
  87. package/dist/http/runtimes/express.mjs +2 -2
  88. package/dist/http/runtimes/fastify.d.mts +1 -1
  89. package/dist/http/runtimes/fastify.mjs +2 -2
  90. package/dist/http/runtimes/h3-web.mjs +1 -1
  91. package/dist/http/runtimes/h3.d.mts +1 -1
  92. package/dist/http/runtimes/h3.mjs +2 -2
  93. package/dist/index.d.mts +6 -6
  94. package/dist/index.mjs +2 -2
  95. package/dist/{is-production-C7DJ7c5k.mjs → is-production-CMJW948J.mjs} +2 -2
  96. package/dist/{is-production-C7DJ7c5k.mjs.map → is-production-CMJW948J.mjs.map} +1 -1
  97. package/dist/{jobs-Bdqz5n21.mjs → jobs-d2j_7_9R.mjs} +3 -3
  98. package/dist/{jobs-Bdqz5n21.mjs.map → jobs-d2j_7_9R.mjs.map} +1 -1
  99. package/dist/{kv-stores-CISRYh_H.d.mts → kv-stores-DJBnGQsJ.d.mts} +2 -2
  100. package/dist/{kv-stores-CISRYh_H.d.mts.map → kv-stores-DJBnGQsJ.d.mts.map} +1 -1
  101. package/dist/{kv-stores-BM5Fcds2.mjs → kv-stores-u0V_K-2O.mjs} +3 -3
  102. package/dist/{kv-stores-BM5Fcds2.mjs.map → kv-stores-u0V_K-2O.mjs.map} +1 -1
  103. package/dist/{lazy-serve-static-D2pf9ODr.mjs → lazy-serve-static-kB1m23xS.mjs} +3 -3
  104. package/dist/{lazy-serve-static-D2pf9ODr.mjs.map → lazy-serve-static-kB1m23xS.mjs.map} +1 -1
  105. package/dist/{metadata-Ck5f9CNm.mjs → metadata-c1TNXrm_.mjs} +1 -1
  106. package/dist/{observers-BV435fEL.mjs → observers-vX5EpqCX.mjs} +2 -2
  107. package/dist/{observers-BV435fEL.mjs.map → observers-vX5EpqCX.mjs.map} +1 -1
  108. package/dist/{precompressed-DPESwDxf.mjs → precompressed-DIkilvFq.mjs} +2 -2
  109. package/dist/{precompressed-DPESwDxf.mjs.map → precompressed-DIkilvFq.mjs.map} +1 -1
  110. package/dist/{query-Bs9mU4bx.mjs → query-BIGYogvJ.mjs} +2 -2
  111. package/dist/{query-Bs9mU4bx.mjs.map → query-BIGYogvJ.mjs.map} +1 -1
  112. package/dist/{reply-BmNC0SFg.mjs → reply-CtSYYFK5.mjs} +2 -2
  113. package/dist/{reply-BmNC0SFg.mjs.map → reply-CtSYYFK5.mjs.map} +1 -1
  114. package/dist/{request-scope-DFf8XH5R.mjs → request-scope-B1GH3d99.mjs} +3 -3
  115. package/dist/{request-scope-DFf8XH5R.mjs.map → request-scope-B1GH3d99.mjs.map} +1 -1
  116. package/dist/{respond-DbgwV87J.mjs → respond-D8cMACHW.mjs} +2 -2
  117. package/dist/{respond-DbgwV87J.mjs.map → respond-D8cMACHW.mjs.map} +1 -1
  118. package/dist/{rolldown-runtime-BIVYCGx6.mjs → rolldown-runtime-CSRdE5Vk.mjs} +1 -1
  119. package/dist/{route-flag-Dm1NxMbJ.mjs → route-flag-Ce2FkkeT.mjs} +3 -3
  120. package/dist/{route-flag-Dm1NxMbJ.mjs.map → route-flag-Ce2FkkeT.mjs.map} +1 -1
  121. package/dist/{route-policy-CdBgPlft.mjs → route-policy-BRcI3gmZ.mjs} +2 -2
  122. package/dist/{route-policy-CdBgPlft.mjs.map → route-policy-BRcI3gmZ.mjs.map} +1 -1
  123. package/dist/{router-builder-BM9t-xGP.mjs → router-builder-BgxacQbc.mjs} +3 -3
  124. package/dist/{router-builder-BM9t-xGP.mjs.map → router-builder-BgxacQbc.mjs.map} +1 -1
  125. package/dist/{router-builder-CwPowg4s.d.mts → router-builder-CPJHwoL1.d.mts} +2 -2
  126. package/dist/{router-builder-CwPowg4s.d.mts.map → router-builder-CPJHwoL1.d.mts.map} +1 -1
  127. package/dist/{settings-CPQhWD12.mjs → settings-hE0ewJKF.mjs} +3 -3
  128. package/dist/{settings-CPQhWD12.mjs.map → settings-hE0ewJKF.mjs.map} +1 -1
  129. package/dist/{token-tL_r-ZPP.mjs → token-DNQnEuMJ.mjs} +1 -1
  130. package/dist/{upload-DDDboa_F.d.mts → upload-DtQ1pdQw.d.mts} +2 -2
  131. package/dist/{upload-DDDboa_F.d.mts.map → upload-DtQ1pdQw.d.mts.map} +1 -1
  132. package/dist/{upload-config-DCm8AFEW.mjs → upload-config-ikC1nZgF.mjs} +2 -2
  133. package/dist/{upload-config-DCm8AFEW.mjs.map → upload-config-ikC1nZgF.mjs.map} +1 -1
  134. package/dist/{url-for-DAVOWiQ_.mjs → url-for-Bh43Ax1C.mjs} +3 -3
  135. package/dist/{url-for-DAVOWiQ_.mjs.map → url-for-Bh43Ax1C.mjs.map} +1 -1
  136. package/dist/{web-crypto-BMaKs6M0.mjs → web-crypto-Dx8Nmh16.mjs} +2 -2
  137. package/dist/{web-crypto-BMaKs6M0.mjs.map → web-crypto-Dx8Nmh16.mjs.map} +1 -1
  138. package/dist/web.d.mts +2 -2
  139. package/dist/web.mjs +2 -2
  140. package/package.json +10 -10
@@ -1,5 +1,5 @@
1
1
  /**
2
- * @forinda/kickjs v10.8.0
2
+ * @forinda/kickjs v10.9.0
3
3
  *
4
4
  * Copyright (c) Felix Orinda
5
5
  *
@@ -8,4 +8,4 @@
8
8
  *
9
9
  * @license MIT
10
10
  */
11
- import{a as getEnv,c as reloadEnv,l as resetEnvCache,n as baseEnvSchema,o as loadEnv,r as defineEnv,s as loadEnvFromSchema,u as withEnv}from"../decorate-DdzHOAA1.mjs";import{n as createConfigService,t as ConfigService}from"../config-Cq6_Qr4r.mjs";export{ConfigService,baseEnvSchema,createConfigService,defineEnv,getEnv,loadEnv,loadEnvFromSchema,reloadEnv,resetEnvCache,withEnv};
11
+ import{a as getEnv,c as reloadEnv,l as resetEnvCache,n as baseEnvSchema,o as loadEnv,r as defineEnv,s as loadEnvFromSchema,u as withEnv}from"../decorate-8MLQUvoW.mjs";import{n as createConfigService,t as ConfigService}from"../config-DeWWBNz5.mjs";export{ConfigService,baseEnvSchema,createConfigService,defineEnv,getEnv,loadEnv,loadEnvFromSchema,reloadEnv,resetEnvCache,withEnv};
@@ -1,5 +1,5 @@
1
1
  /**
2
- * @forinda/kickjs v10.8.0
2
+ * @forinda/kickjs v10.9.0
3
3
  *
4
4
  * Copyright (c) Felix Orinda
5
5
  *
@@ -8,5 +8,5 @@
8
8
  *
9
9
  * @license MIT
10
10
  */
11
- import{Service}from"./core/decorators.mjs";import{c as reloadEnv,o as loadEnv,t as __decorate}from"./decorate-DdzHOAA1.mjs";let ConfigService=class{get env(){return loadEnv()}get(key,fallback){return this.env[key]??fallback}getAll(){return Object.freeze({...this.env})}reload(){reloadEnv(),loadEnv()}isProduction(){return this.env.NODE_ENV===`production`}isDevelopment(){return this.env.NODE_ENV===`development`}isTest(){return this.env.NODE_ENV===`test`}};ConfigService=__decorate([Service()],ConfigService);function createConfigService(schema){let SchemaConfigService=class{get env(){return loadEnv(schema)}get(key,fallback){return this.env[key]??fallback}getAll(){return Object.freeze({...this.env})}reload(){reloadEnv(),loadEnv(schema)}isProduction(){return this.env.NODE_ENV===`production`}isDevelopment(){return this.env.NODE_ENV===`development`}isTest(){return this.env.NODE_ENV===`test`}};return SchemaConfigService=__decorate([Service()],SchemaConfigService),SchemaConfigService}export{createConfigService as n,ConfigService as t};
12
- //# sourceMappingURL=config-Cq6_Qr4r.mjs.map
11
+ import{Service}from"./core/decorators.mjs";import{c as reloadEnv,o as loadEnv,t as __decorate}from"./decorate-8MLQUvoW.mjs";let ConfigService=class{get env(){return loadEnv()}get(key,fallback){return this.env[key]??fallback}getAll(){return Object.freeze({...this.env})}reload(){reloadEnv(),loadEnv()}isProduction(){return this.env.NODE_ENV===`production`}isDevelopment(){return this.env.NODE_ENV===`development`}isTest(){return this.env.NODE_ENV===`test`}};ConfigService=__decorate([Service()],ConfigService);function createConfigService(schema){let SchemaConfigService=class{get env(){return loadEnv(schema)}get(key,fallback){return this.env[key]??fallback}getAll(){return Object.freeze({...this.env})}reload(){reloadEnv(),loadEnv(schema)}isProduction(){return this.env.NODE_ENV===`production`}isDevelopment(){return this.env.NODE_ENV===`development`}isTest(){return this.env.NODE_ENV===`test`}};return SchemaConfigService=__decorate([Service()],SchemaConfigService),SchemaConfigService}export{createConfigService as n,ConfigService as t};
12
+ //# sourceMappingURL=config-DeWWBNz5.mjs.map
@@ -1 +1 @@
1
- {"version":3,"file":"config-Cq6_Qr4r.mjs","names":[],"sources":["../src/config/config-service.ts"],"sourcesContent":["import type { z } from 'zod'\nimport { Service } from '../core/decorators'\nimport type { EnvKey } from '../core/decorators'\nimport { loadEnv, reloadEnv } from './env'\n\n/**\n * Constraint that locks the `key` argument to known `EnvKey` literals\n * once `kick typegen` has populated `KickEnv`. Mirrors the same trick\n * used by the `@Value` decorator: when `EnvKey` resolves to `never`\n * (no schema yet), accept any string for back-compat; once typegen\n * has run, require a known key.\n */\ntype ConfigKey<K extends string> = [EnvKey] extends [never] ? K : K & EnvKey\n\n/**\n * Resolve the return type for a `ConfigService.get(key)` call. When\n * `KickEnv` is populated and the key is a known one, returns the\n * schema-inferred type. Otherwise falls back to the caller-provided\n * generic `T` (default `any`) so existing call sites keep working.\n */\ntype ConfigValue<K extends string, T> = K extends EnvKey ? KickEnv[K] : T\n\n/**\n * Injectable service for accessing typed environment configuration.\n *\n * Once `kick typegen` has run against your `src/env.ts`, both `get()`\n * and `getAll()` are fully typed against the schema with **no extra\n * setup** — you just inject `ConfigService` and call it:\n *\n * ```ts\n * @Service()\n * class DatabaseService {\n * @Autowired() private readonly config!: ConfigService\n *\n * connect() {\n * const url = this.config.get('DATABASE_URL') // typed string\n * const port = this.config.get('PORT') // typed number\n * // const bad = this.config.get('NOPE') // tsc error\n * }\n * }\n * ```\n *\n * Without typegen the previous `<T = any>` generic still works, so\n * legacy code calling `config.get<string>('DATABASE_URL')` keeps\n * compiling.\n */\n@Service()\nexport class ConfigService {\n /**\n * Read the current parsed env on every access. We deliberately do **not**\n * snapshot in the constructor: if `ConfigService` is instantiated before\n * the user's `defineEnv()` schema has been registered (e.g. DI wires it\n * eagerly, or HMR's `reloadEnv()` cleared the cache between rebuilds),\n * an eager snapshot would freeze the base shape and never see the\n * extended values — even though `@Value()` (which reads lazily through\n * `Container.envResolver`) would resolve them correctly.\n *\n * `loadEnv()` is sticky: once an extended schema has been parsed it\n * keeps returning that schema's values, so this getter is cheap (one\n * cached lookup) and always consistent with `@Value`.\n */\n private get env(): Record<string, any> {\n return loadEnv() as Record<string, any>\n }\n\n /**\n * Get an env variable by key.\n *\n * - When `kick typegen` has run, `key` is constrained to known\n * `KickEnv` keys and the return type is inferred from the schema.\n * - When `KickEnv` is empty (no typegen run yet), any string is\n * accepted and `T` falls back to the explicit generic for\n * back-compat.\n */\n get<K extends string, T = any>(key: ConfigKey<K>): ConfigValue<K, T>\n /** With a fallback, returned when the value is unset (`undefined` or `null`). */\n get<K extends string, T = any>(\n key: ConfigKey<K>,\n fallback: NonNullable<ConfigValue<K, T>>,\n ): NonNullable<ConfigValue<K, T>>\n get(key: string, fallback?: unknown): unknown {\n return this.env[key] ?? fallback\n }\n\n /**\n * Get all env config as a readonly object. When `KickEnv` is\n * populated by typegen, returns `Readonly<KickEnv>` so the caller\n * gets autocomplete on every key.\n */\n getAll(): [EnvKey] extends [never] ? Readonly<Record<string, any>> : Readonly<KickEnv> {\n return Object.freeze({ ...this.env }) as any\n }\n\n /** Reload env from .env file (for HMR / file-watch scenarios) */\n reload(): void {\n reloadEnv()\n // Touch loadEnv() so the resolver + cache are repopulated immediately.\n loadEnv()\n }\n\n isProduction(): boolean {\n return this.env.NODE_ENV === 'production'\n }\n\n isDevelopment(): boolean {\n return this.env.NODE_ENV === 'development'\n }\n\n isTest(): boolean {\n return this.env.NODE_ENV === 'test'\n }\n}\n\n/**\n * Typed config service interface — provides autocomplete for env keys.\n * Use with `createConfigService()` for full type safety.\n */\nexport interface TypedConfigService<TEnv extends Record<string, any>> {\n get<K extends string & keyof TEnv>(key: K): TEnv[K]\n get<K extends string & keyof TEnv>(key: K, fallback: NonNullable<TEnv[K]>): NonNullable<TEnv[K]>\n getAll(): Readonly<TEnv>\n reload(): void\n isProduction(): boolean\n isDevelopment(): boolean\n isTest(): boolean\n}\n\n/**\n * Create a typed ConfigService class bound to a specific Zod env schema.\n * The returned class is DI-injectable via `@Service()` and provides\n * fully typed `get()` with key autocomplete.\n *\n * @example\n * ```ts\n * const envSchema = defineEnv((base) =>\n * base.extend({\n * DATABASE_URL: z.string().url(),\n * JWT_SECRET: z.string().min(32),\n * })\n * )\n *\n * // Create a typed, injectable config service\n * export const AppConfigService = createConfigService(envSchema)\n * export type AppConfigService = InstanceType<typeof AppConfigService>\n *\n * // In a controller or service — inject it:\n * @Controller()\n * class UserController {\n * constructor(@Inject(AppConfigService) private config: AppConfigService) {\n * const dbUrl = config.get('DATABASE_URL') // string — autocompletes!\n * const bad = config.get('NOPE') // TS error\n * }\n * }\n * ```\n */\nexport function createConfigService<T extends z.ZodObject<any>>(schema: T) {\n type TEnv = z.infer<T>\n\n @Service()\n class SchemaConfigService implements TypedConfigService<TEnv> {\n /** See note on `ConfigService.env` — same eager-snapshot hazard. */\n private get env(): TEnv {\n return loadEnv(schema)\n }\n\n get<K extends string & keyof TEnv>(key: K): TEnv[K]\n get<K extends string & keyof TEnv>(key: K, fallback: NonNullable<TEnv[K]>): NonNullable<TEnv[K]>\n get(key: string, fallback?: unknown): unknown {\n return (this.env as Record<string, unknown>)[key] ?? fallback\n }\n\n getAll(): Readonly<TEnv> {\n return Object.freeze({ ...this.env })\n }\n\n reload(): void {\n reloadEnv()\n loadEnv(schema)\n }\n\n isProduction(): boolean {\n return this.env.NODE_ENV === 'production'\n }\n\n isDevelopment(): boolean {\n return this.env.NODE_ENV === 'development'\n }\n\n isTest(): boolean {\n return this.env.NODE_ENV === 'test'\n }\n }\n\n return SchemaConfigService as {\n new (): TypedConfigService<TEnv>\n }\n}\n"],"mappings":";;;;;;;;;;4HA+CO,IAAM,cAAN,KAAoB,CAczB,IAAY,KAA2B,CACrC,OAAO,QAAQ,CACjB,CAiBA,IAAI,IAAa,SAA6B,CAC5C,OAAO,KAAK,IAAI,MAAQ,QAC1B,CAOA,QAAuF,CACrF,OAAO,OAAO,OAAO,CAAE,GAAG,KAAK,GAAI,CAAC,CACtC,CAGA,QAAe,CACb,UAAU,EAEV,QAAQ,CACV,CAEA,cAAwB,CACtB,OAAO,KAAK,IAAI,WAAa,YAC/B,CAEA,eAAyB,CACvB,OAAO,KAAK,IAAI,WAAa,aAC/B,CAEA,QAAkB,CAChB,OAAO,KAAK,IAAI,WAAa,MAC/B,CACF,EAjEC,cAAA,WAAA,CAAA,QAAQ,CAAA,EAAA,aAAA,EA6GT,SAAgB,oBAAgD,OAAW,CAGzE,IACM,oBADN,KAC8D,CAE5D,IAAY,KAAY,CACtB,OAAO,QAAQ,MAAM,CACvB,CAIA,IAAI,IAAa,SAA6B,CAC5C,OAAQ,KAAK,IAAgC,MAAQ,QACvD,CAEA,QAAyB,CACvB,OAAO,OAAO,OAAO,CAAE,GAAG,KAAK,GAAI,CAAC,CACtC,CAEA,QAAe,CACb,UAAU,EACV,QAAQ,MAAM,CAChB,CAEA,cAAwB,CACtB,OAAO,KAAK,IAAI,WAAa,YAC/B,CAEA,eAAyB,CACvB,OAAO,KAAK,IAAI,WAAa,aAC/B,CAEA,QAAkB,CAChB,OAAO,KAAK,IAAI,WAAa,MAC/B,CACF,EAEA,MAnCC,qBAAA,WAAA,CAAA,QAAQ,CAAA,EAAA,mBAAA,EAmCF,mBAGT"}
1
+ {"version":3,"file":"config-DeWWBNz5.mjs","names":[],"sources":["../src/config/config-service.ts"],"sourcesContent":["import type { z } from 'zod'\nimport { Service } from '../core/decorators'\nimport type { EnvKey } from '../core/decorators'\nimport { loadEnv, reloadEnv } from './env'\n\n/**\n * Constraint that locks the `key` argument to known `EnvKey` literals\n * once `kick typegen` has populated `KickEnv`. Mirrors the same trick\n * used by the `@Value` decorator: when `EnvKey` resolves to `never`\n * (no schema yet), accept any string for back-compat; once typegen\n * has run, require a known key.\n */\ntype ConfigKey<K extends string> = [EnvKey] extends [never] ? K : K & EnvKey\n\n/**\n * Resolve the return type for a `ConfigService.get(key)` call. When\n * `KickEnv` is populated and the key is a known one, returns the\n * schema-inferred type. Otherwise falls back to the caller-provided\n * generic `T` (default `any`) so existing call sites keep working.\n */\ntype ConfigValue<K extends string, T> = K extends EnvKey ? KickEnv[K] : T\n\n/**\n * Injectable service for accessing typed environment configuration.\n *\n * Once `kick typegen` has run against your `src/env.ts`, both `get()`\n * and `getAll()` are fully typed against the schema with **no extra\n * setup** — you just inject `ConfigService` and call it:\n *\n * ```ts\n * @Service()\n * class DatabaseService {\n * @Autowired() private readonly config!: ConfigService\n *\n * connect() {\n * const url = this.config.get('DATABASE_URL') // typed string\n * const port = this.config.get('PORT') // typed number\n * // const bad = this.config.get('NOPE') // tsc error\n * }\n * }\n * ```\n *\n * Without typegen the previous `<T = any>` generic still works, so\n * legacy code calling `config.get<string>('DATABASE_URL')` keeps\n * compiling.\n */\n@Service()\nexport class ConfigService {\n /**\n * Read the current parsed env on every access. We deliberately do **not**\n * snapshot in the constructor: if `ConfigService` is instantiated before\n * the user's `defineEnv()` schema has been registered (e.g. DI wires it\n * eagerly, or HMR's `reloadEnv()` cleared the cache between rebuilds),\n * an eager snapshot would freeze the base shape and never see the\n * extended values — even though `@Value()` (which reads lazily through\n * `Container.envResolver`) would resolve them correctly.\n *\n * `loadEnv()` is sticky: once an extended schema has been parsed it\n * keeps returning that schema's values, so this getter is cheap (one\n * cached lookup) and always consistent with `@Value`.\n */\n private get env(): Record<string, any> {\n return loadEnv() as Record<string, any>\n }\n\n /**\n * Get an env variable by key.\n *\n * - When `kick typegen` has run, `key` is constrained to known\n * `KickEnv` keys and the return type is inferred from the schema.\n * - When `KickEnv` is empty (no typegen run yet), any string is\n * accepted and `T` falls back to the explicit generic for\n * back-compat.\n */\n get<K extends string, T = any>(key: ConfigKey<K>): ConfigValue<K, T>\n /** With a fallback, returned when the value is unset (`undefined` or `null`). */\n get<K extends string, T = any>(\n key: ConfigKey<K>,\n fallback: NonNullable<ConfigValue<K, T>>,\n ): NonNullable<ConfigValue<K, T>>\n get(key: string, fallback?: unknown): unknown {\n return this.env[key] ?? fallback\n }\n\n /**\n * Get all env config as a readonly object. When `KickEnv` is\n * populated by typegen, returns `Readonly<KickEnv>` so the caller\n * gets autocomplete on every key.\n */\n getAll(): [EnvKey] extends [never] ? Readonly<Record<string, any>> : Readonly<KickEnv> {\n return Object.freeze({ ...this.env }) as any\n }\n\n /** Reload env from .env file (for HMR / file-watch scenarios) */\n reload(): void {\n reloadEnv()\n // Touch loadEnv() so the resolver + cache are repopulated immediately.\n loadEnv()\n }\n\n isProduction(): boolean {\n return this.env.NODE_ENV === 'production'\n }\n\n isDevelopment(): boolean {\n return this.env.NODE_ENV === 'development'\n }\n\n isTest(): boolean {\n return this.env.NODE_ENV === 'test'\n }\n}\n\n/**\n * Typed config service interface — provides autocomplete for env keys.\n * Use with `createConfigService()` for full type safety.\n */\nexport interface TypedConfigService<TEnv extends Record<string, any>> {\n get<K extends string & keyof TEnv>(key: K): TEnv[K]\n get<K extends string & keyof TEnv>(key: K, fallback: NonNullable<TEnv[K]>): NonNullable<TEnv[K]>\n getAll(): Readonly<TEnv>\n reload(): void\n isProduction(): boolean\n isDevelopment(): boolean\n isTest(): boolean\n}\n\n/**\n * Create a typed ConfigService class bound to a specific Zod env schema.\n * The returned class is DI-injectable via `@Service()` and provides\n * fully typed `get()` with key autocomplete.\n *\n * @example\n * ```ts\n * const envSchema = defineEnv((base) =>\n * base.extend({\n * DATABASE_URL: z.string().url(),\n * JWT_SECRET: z.string().min(32),\n * })\n * )\n *\n * // Create a typed, injectable config service\n * export const AppConfigService = createConfigService(envSchema)\n * export type AppConfigService = InstanceType<typeof AppConfigService>\n *\n * // In a controller or service — inject it:\n * @Controller()\n * class UserController {\n * constructor(@Inject(AppConfigService) private config: AppConfigService) {\n * const dbUrl = config.get('DATABASE_URL') // string — autocompletes!\n * const bad = config.get('NOPE') // TS error\n * }\n * }\n * ```\n */\nexport function createConfigService<T extends z.ZodObject<any>>(schema: T) {\n type TEnv = z.infer<T>\n\n @Service()\n class SchemaConfigService implements TypedConfigService<TEnv> {\n /** See note on `ConfigService.env` — same eager-snapshot hazard. */\n private get env(): TEnv {\n return loadEnv(schema)\n }\n\n get<K extends string & keyof TEnv>(key: K): TEnv[K]\n get<K extends string & keyof TEnv>(key: K, fallback: NonNullable<TEnv[K]>): NonNullable<TEnv[K]>\n get(key: string, fallback?: unknown): unknown {\n return (this.env as Record<string, unknown>)[key] ?? fallback\n }\n\n getAll(): Readonly<TEnv> {\n return Object.freeze({ ...this.env })\n }\n\n reload(): void {\n reloadEnv()\n loadEnv(schema)\n }\n\n isProduction(): boolean {\n return this.env.NODE_ENV === 'production'\n }\n\n isDevelopment(): boolean {\n return this.env.NODE_ENV === 'development'\n }\n\n isTest(): boolean {\n return this.env.NODE_ENV === 'test'\n }\n }\n\n return SchemaConfigService as {\n new (): TypedConfigService<TEnv>\n }\n}\n"],"mappings":";;;;;;;;;;4HA+CO,IAAM,cAAN,KAAoB,CAczB,IAAY,KAA2B,CACrC,OAAO,QAAQ,CACjB,CAiBA,IAAI,IAAa,SAA6B,CAC5C,OAAO,KAAK,IAAI,MAAQ,QAC1B,CAOA,QAAuF,CACrF,OAAO,OAAO,OAAO,CAAE,GAAG,KAAK,GAAI,CAAC,CACtC,CAGA,QAAe,CACb,UAAU,EAEV,QAAQ,CACV,CAEA,cAAwB,CACtB,OAAO,KAAK,IAAI,WAAa,YAC/B,CAEA,eAAyB,CACvB,OAAO,KAAK,IAAI,WAAa,aAC/B,CAEA,QAAkB,CAChB,OAAO,KAAK,IAAI,WAAa,MAC/B,CACF,EAjEC,cAAA,WAAA,CAAA,QAAQ,CAAA,EAAA,aAAA,EA6GT,SAAgB,oBAAgD,OAAW,CAGzE,IACM,oBADN,KAC8D,CAE5D,IAAY,KAAY,CACtB,OAAO,QAAQ,MAAM,CACvB,CAIA,IAAI,IAAa,SAA6B,CAC5C,OAAQ,KAAK,IAAgC,MAAQ,QACvD,CAEA,QAAyB,CACvB,OAAO,OAAO,OAAO,CAAE,GAAG,KAAK,GAAI,CAAC,CACtC,CAEA,QAAe,CACb,UAAU,EACV,QAAQ,MAAM,CAChB,CAEA,cAAwB,CACtB,OAAO,KAAK,IAAI,WAAa,YAC/B,CAEA,eAAyB,CACvB,OAAO,KAAK,IAAI,WAAa,aAC/B,CAEA,QAAkB,CAChB,OAAO,KAAK,IAAI,WAAa,MAC/B,CACF,EAEA,MAnCC,qBAAA,WAAA,CAAA,QAAQ,CAAA,EAAA,mBAAA,EAmCF,mBAGT"}
@@ -1,5 +1,5 @@
1
1
  /**
2
- * @forinda/kickjs v10.8.0
2
+ * @forinda/kickjs v10.9.0
3
3
  *
4
4
  * Copyright (c) Felix Orinda
5
5
  *
@@ -8,5 +8,5 @@
8
8
  *
9
9
  * @license MIT
10
10
  */
11
- import{HttpException,normalizeProblem}from"./core/errors.mjs";import{t as ROUTE_SLOT}from"./route-flag-Dm1NxMbJ.mjs";import{r as MissingContextValueError}from"./context-errors-Chi6ESHh.mjs";import{t as isProduction}from"./is-production-C7DJ7c5k.mjs";import{i as waitUntil,s as requestStore}from"./background-D8VpVDrH.mjs";import{t as resolveClientIp}from"./client-ip-COnqHbaF.mjs";import{a as parseQuery}from"./query-Bs9mU4bx.mjs";function header(headers,name){let value=headers[name];return Array.isArray(value)?value.join(`, `):value}function normalizeEtag(etag){if(/^(W\/)?".*"$/.test(etag))return etag;let weak=etag.startsWith(`W/`),bare=(weak?etag.slice(2):etag).replaceAll(`"`,``);return`${weak?`W/`:``}"${bare}"`}const opaque=tag=>tag.replace(/^W\//,``),isWeak=tag=>tag.startsWith(`W/`);function tagsOf(value){return value.match(/\*|(?:W\/)?"[^"]*"/g)??[]}function dateOf(value){if(!value)return;let ms=Date.parse(value);return Number.isNaN(ms)?void 0:ms}const seconds=date=>Math.floor(date.getTime()/1e3)*1e3;function evaluatePreconditions(method,headers,validators){let etag=validators.etag===void 0?void 0:normalizeEtag(validators.etag),modified=validators.lastModified?seconds(validators.lastModified):void 0,safe=method===`GET`||method===`HEAD`,ifMatch=header(headers,`if-match`);if(ifMatch!==void 0){let tags=tagsOf(ifMatch);if(!(tags.includes(`*`)||etag!==void 0&&!isWeak(etag)&&tags.some(t=>!isWeak(t)&&t===etag)))return 412}else{let since=dateOf(header(headers,`if-unmodified-since`));if(since!==void 0&&modified!==void 0&&modified>since)return 412}let ifNoneMatch=header(headers,`if-none-match`);if(ifNoneMatch!==void 0){let tags=tagsOf(ifNoneMatch);return tags.includes(`*`)||etag!==void 0&&tags.some(t=>opaque(t)===opaque(etag))?safe?304:412:200}if(safe){let since=dateOf(header(headers,`if-modified-since`));if(since!==void 0&&modified!==void 0&&modified<=since)return 304}return 200}function publishMatchedRoute(req,entry){let route=matchedRoutes.get(entry);route||(route=Object.freeze({method:entry.method,path:entry.path,controller:entry.meta.controller,handlerName:entry.meta.handlerName,flags:entry.meta.flags??EMPTY_FLAGS,pattern:entry.meta.pattern??entry.path,urls:entry.urls}),matchedRoutes.set(entry,route)),req[ROUTE_SLOT]=route}const matchedRoutes=/* @__PURE__ */ new WeakMap,EMPTY_FLAGS=/* @__PURE__ */ new Map;function isBigIntJsonError(err){return err instanceof TypeError&&/BigInt/.test(err.message)}function stringifyJson(data){try{return JSON.stringify(data)}catch(err){if(!isBigIntJsonError(err))throw err;return JSON.stringify(data,(_key,value)=>typeof value==`bigint`?value.toString():value)}}function sortSignature(sort){return sort.map(s=>`${s.field}:${s.direction}`).join(`,`)}function isPrimitive(value){return value===null||[`string`,`number`,`boolean`].includes(typeof value)}function encodeCursor(position,signature){let bytes=new TextEncoder().encode(JSON.stringify({v:position,s:signature})),binary=``;for(let byte of bytes)binary+=String.fromCharCode(byte);return btoa(binary).replace(/\+/g,`-`).replace(/\//g,`_`).replace(/=+$/,``)}function decodeCursor(raw,signature,keys){let invalid=()=>HttpException.badRequest(`Invalid pagination cursor`);if(typeof raw!=`string`||!/^[A-Za-z0-9_-]+$/.test(raw))throw invalid();let parsed;try{let binary=atob(raw.replace(/-/g,`+`).replace(/_/g,`/`)),bytes=Uint8Array.from(binary,c=>c.charCodeAt(0));parsed=JSON.parse(new TextDecoder(`utf-8`,{fatal:!0}).decode(bytes))}catch{throw invalid()}if(typeof parsed!=`object`||!parsed)throw invalid();let{v,s}=parsed;if(typeof v!=`object`||!v||Array.isArray(v)||!Object.values(v).every(isPrimitive)||keys&&(Object.keys(v).length!==keys.length||!keys.every(k=>Object.hasOwn(v,k))))throw invalid();if(s!==signature)throw HttpException.badRequest(`Pagination cursor was issued for a different sort`);return v}function pageLink(rawUrl,key,value){let url=parseUrl(rawUrl),kept=url.search.slice(1).split(`&`).filter(part=>part!==``&&paramName(part)!==key);return value!==null&&kept.push(`${key}=${encodeURIComponent(value)}`),kept.length?`${url.pathname}?${kept.join(`&`)}`:url.pathname}function selfLink(rawUrl){let url=parseUrl(rawUrl);return url.pathname+url.search}function parseUrl(rawUrl){let url=new URL(rawUrl,`http://localhost`);return url.pathname=url.pathname.replace(/^\/+/,`/`),url}function paramName(part){let name=part.split(`=`,1)[0].replace(/\+/g,` `);try{return decodeURIComponent(name)}catch{return name}}const signalControllerKey=Symbol.for(`kickjs.requestContext.signalController`),readOnlyProxyCacheKey=Symbol.for(`kickjs.requestContext.readOnlyProxyCache`);function isPlainObjectOrArray(v){if(typeof v!=`object`||!v)return!1;if(Array.isArray(v))return!0;let proto=Object.getPrototypeOf(v);return proto===Object.prototype||proto===null}function makeReadOnlyProxy(target,req,label){if(isProduction()||!isPlainObjectOrArray(target))return target;let reqObj=req,cache=reqObj[readOnlyProxyCacheKey];cache||(cache=/* @__PURE__ */ new WeakMap,reqObj[readOnlyProxyCacheKey]=cache);let targetObj=target,cached=cache.get(targetObj);if(cached)return cached;let warnWrite=(verb,prop)=>{console.warn(`[kickjs] Attempted to ${verb} \`ctx.${label}.${String(prop)}\` — request data is read-only. Stash computed values via \`ctx.set('key', value)\` or a Context Contributor, or reach \`ctx.req.${label}\` if you genuinely need the raw mutable handle.`)},proxy=new Proxy(targetObj,{get(t,prop,receiver){let value=Reflect.get(t,prop,receiver);return isPlainObjectOrArray(value)?makeReadOnlyProxy(value,req,`${label}.${String(prop)}`):value},set(_t,prop){return warnWrite(`assign`,prop),!0},deleteProperty(_t,prop){return warnWrite(`delete`,prop),!0},defineProperty(_t,prop){return warnWrite(`Object.defineProperty on`,prop),!0}});return cache.set(targetObj,proxy),proxy}var RequestContext=class{req;res;next;_response;get route(){return this.req?.[ROUTE_SLOT]}constructor(req,res,next,responseDriver){this.req=req,this.res=res,this.next=next,this._response=responseDriver??res}_qsMemo;_problem;metadataReadOnly(){return requestStore.getStore()?.values??null}metadataForWrite(){let store=requestStore.getStore();if(store)return store.values;throw 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() }, () => ...).`)}get body(){return makeReadOnlyProxy(this.req.body,this.req,`body`)}get params(){return makeReadOnlyProxy(this.req.params,this.req,`params`)}get query(){return makeReadOnlyProxy(this.req.query,this.req,`query`)}get headers(){return makeReadOnlyProxy(this.req.headers,this.req,`headers`)}get requestId(){return this.req.requestId??this.req.headers[`x-request-id`]}get signal(){let req=this.req,cached=req[signalControllerKey];if(cached)return cached.signal;let ctrl=new AbortController;req[signalControllerKey]=ctrl;let abort=()=>ctrl.abort(`request closed`);return this.req.once(`close`,abort),this._response.once(`close`,abort),ctrl.signal}get session(){return this.req.session}get user(){return this.metadataReadOnly()?.get(`user`)??this.req.user}get tenantId(){return this.user?.tenantId}get roles(){let u=this.user;return u?.tenantRoles??u?.roles??[]}qs(fieldConfig,options){let memo=this._qsMemo;if(memo&&memo.config===fieldConfig&&memo.options===options)return memo.result;let effective={...options,onReject:options?.onReject??(rejection=>{let id=this.requestId?`[${this.requestId}] `:``;console.warn(`${id}query ${rejection.kind} '${rejection.field}' rejected (${rejection.reason})`)})},result=parseQuery(this.req.query,fieldConfig,effective);return this._qsMemo={config:fieldConfig,options,result},result}get file(){let f=this.req.file;return f?makeReadOnlyProxy(f,this.req,`file`):void 0}get files(){let f=this.req.files;if(Array.isArray(f))return makeReadOnlyProxy(f,this.req,`files`)}get(key){return this.metadataReadOnly()?.get(key)}require(key){let value=this.metadataReadOnly()?.get(key);if(value===void 0)throw new MissingContextValueError(key,this.routeLabel());return value}routeLabel(){let req=this.req,method=typeof req?.method==`string`?req.method:void 0,url=typeof req?.url==`string`?req.url:void 0;return method&&url?`${method} ${url}`:method??url}set(key,value){this.metadataForWrite().set(key,value)}setHeader(name,value){return this._response.setHeader(name,value),this}json(data,status=200){return this.sendJson(status,data)}created(data){return this.sendJson(201,data)}sendJson(status,data){try{return this._response.status(status).json(data)}catch(err){if(!isBigIntJsonError(err)||this._response.headersSent)throw err;return this._response.status(status).json(JSON.parse(stringifyJson(data)))}}noContent(){return this._response.status(204).end()}urlFor(name,...args){let urls=this.route?.urls;if(!urls)throw Error(`ctx.urlFor() is only available inside a matched route`);let[params,query]=args;return urls.build(name,params,query)}conditional(validators){validators.etag!==void 0&&this.setHeader(`ETag`,normalizeEtag(validators.etag)),validators.lastModified&&this.setHeader(`Last-Modified`,validators.lastModified.toUTCString());let outcome=evaluatePreconditions(String(this.req.method??`GET`).toUpperCase(),this.headers,validators);return outcome===304?(this._response.status(304).end(),!0):outcome===412&&(this.sendProblem({status:412,detail:`The resource changed since the version this request is based on.`}),!0)}notFound(message=`Not Found`){return this._response.status(404).json({message})}badRequest(message){return this._response.status(400).json({message})}get problem(){if(this._problem)return this._problem;let send=input=>this.sendProblem(input);return send.badRequest=(input={})=>this.sendProblem({status:400,...input}),send.unauthorized=(input={})=>this.sendProblem({status:401,...input}),send.forbidden=(input={})=>this.sendProblem({status:403,...input}),send.notFound=(input={})=>this.sendProblem({status:404,...input}),send.conflict=(input={})=>this.sendProblem({status:409,...input}),send.unprocessable=(input={})=>this.sendProblem({status:422,...input}),send.tooManyRequests=(input={})=>this.sendProblem({status:429,...input}),send.internal=(input={})=>this.sendProblem({status:500,...input}),send.validation=(issues,input={})=>{let errors=(issues||[]).map(issue=>({field:issue.path?.join?.(`.`)??``,message:issue.message??``,code:issue.code}));return this.sendProblem({status:422,detail:issues?.[0]?.message,...input,errors})},this._problem=send,this._problem}sendProblem(input){let body=normalizeProblem(input);return this._response.setHeader(`Content-Type`,`application/problem+json`),this._response.status(body.status).json(body)}get ip(){return resolveClientIp(this.req)}redirect(url,status=302){return this._response.status(status).setHeader(`location`,url),this._response.end()}html(content,status=200){return this._response.status(status).type(`text/html; charset=utf-8`).send(content)}send(body,options={}){return this._response.status(options.status??200).type(options.type??`text/plain; charset=utf-8`).send(body)}download(buffer,filename,contentType=`application/octet-stream`){return this._response.setHeader(`Content-Disposition`,contentDisposition(filename)),this._response.setHeader(`Content-Type`,contentType),this._response.send(buffer)}render(template,data={}){return this._response.render(template,data)}async paginate(fetcher,fieldConfig){let parsed=this.qs(fieldConfig),{data,total}=await fetcher(parsed),{page,limit}=parsed.pagination,totalPages=Math.ceil(total/limit)||1,response={data,meta:{page,limit,total,totalPages,hasNext:page<totalPages,hasPrev:page>1},links:{self:selfLink(this.requestUrl()),next:page<totalPages?pageLink(this.requestUrl(),`page`,page+1):null,prev:page>1?pageLink(this.requestUrl(),`page`,page-1):null}};return this.json(response),response}async paginateCursor(fetcher,fieldConfig,options){let{pagination,...parsed}=this.qs(fieldConfig),{limit}=pagination,idField=options?.idField??`id`,signature=sortSignature(parsed.sort),keys=options?.cursorKey?void 0:[.../* @__PURE__ */ new Set([...parsed.sort.map(s=>s.field),idField])],raw=this.req.query?.cursor,cursor=raw===void 0||raw===``?null:decodeCursor(raw,signature,keys),rows=await fetcher({...parsed,cursor,limit}),hasNext=rows.length>limit,data=hasNext?rows.slice(0,limit):rows,last=data.at(-1),nextCursor=null;hasNext&&last!==void 0&&(nextCursor=encodeCursor(cursorValues(last,keys??[],options?.cursorKey),signature));let url=this.requestUrl(),response={data,meta:{limit,hasNext,nextCursor},links:{self:selfLink(url),next:nextCursor?pageLink(url,`cursor`,nextCursor):null}};return this.json(response),response}requestUrl(){let req=this.req;return typeof req.originalUrl==`string`?req.originalUrl:typeof req.url==`string`?req.url:`/`}async sendResponse(response){let headers={};response.headers.forEach((value,name)=>{name!==`set-cookie`&&(headers[name]=value)});let cookies=response.headers.getSetCookie();if(cookies.length>0&&(headers[`set-cookie`]=cookies),!response.body){this._response.status(response.status);for(let[name,value]of Object.entries(headers))this._response.setHeader(name,value);this._response.send(``);return}this._response.writeHead(response.status,headers),this._response.flushHeaders();let reader=response.body.getReader(),stop=()=>{reader.cancel().catch(()=>{})};this.signal.addEventListener(`abort`,stop,{once:!0});try{for(;;){let{done,value}=await reader.read();if(done)break;this._response.write(Buffer.from(value))===!1&&!this.signal.aborted&&await new Promise(resolve=>{let resume=()=>{this.signal.removeEventListener(`abort`,resume),resolve()};this._response.once(`drain`,resume),this.signal.addEventListener(`abort`,resume,{once:!0})})}}finally{this.signal.removeEventListener(`abort`,stop),this._response.end()}}waitUntil(promise){waitUntil(promise)}sse(){this._response.writeHead(200,{"Content-Type":`text/event-stream`,"Cache-Control":`no-cache, no-transform`,Connection:`keep-alive`,"X-Accel-Buffering":`no`}),this._response.flushHeaders();let closeCallbacks=[];return this.req.on(`close`,()=>{for(let cb of closeCallbacks)cb()}),{send:(data,event,id)=>{id&&this._response.write(`id: ${id}\n`),event&&this._response.write(`event: ${event}\n`),this._response.write(`data: ${JSON.stringify(data)}\n\n`)},comment:text=>{this._response.write(`: ${text}\n\n`)},onClose:fn=>{closeCallbacks.push(fn)},close:()=>{this._response.end()}}}};function contentDisposition(filename){return`attachment; filename="${filename.replace(/[^\x20-\x7e]|["\\]/g,`_`)}"; filename*=UTF-8''${encodeURIComponent(filename).replace(/['()*]/g,c=>`%${c.charCodeAt(0).toString(16).toUpperCase()}`)}`}function cursorValues(row,keys,cursorKey){if(cursorKey)return cursorKey(row);let values={};for(let key of keys){let value=row[key];if(value===void 0)throw Error(`paginateCursor: row has no '${key}' — return the sort fields and the id field on every row, or pass options.cursorKey / options.idField`);values[key]=value instanceof Date?value.toISOString():typeof value==`bigint`?value.toString():value}return values}export{evaluatePreconditions as a,stringifyJson as i,contentDisposition as n,publishMatchedRoute as r,RequestContext as t};
12
- //# sourceMappingURL=context-CX0TLa4H.mjs.map
11
+ import{HttpException,normalizeProblem}from"./core/errors.mjs";import{t as ROUTE_SLOT}from"./route-flag-Ce2FkkeT.mjs";import{r as MissingContextValueError}from"./context-errors-QfmGMX4-.mjs";import{t as isProduction}from"./is-production-CMJW948J.mjs";import{i as waitUntil,s as requestStore}from"./background-X_AU4qmI.mjs";import{t as resolveClientIp}from"./client-ip-Db1WMxl6.mjs";import{a as parseQuery}from"./query-BIGYogvJ.mjs";function header(headers,name){let value=headers[name];return Array.isArray(value)?value.join(`, `):value}function normalizeEtag(etag){if(/^(W\/)?".*"$/.test(etag))return etag;let weak=etag.startsWith(`W/`),bare=(weak?etag.slice(2):etag).replaceAll(`"`,``);return`${weak?`W/`:``}"${bare}"`}const opaque=tag=>tag.replace(/^W\//,``),isWeak=tag=>tag.startsWith(`W/`);function tagsOf(value){return value.match(/\*|(?:W\/)?"[^"]*"/g)??[]}function dateOf(value){if(!value)return;let ms=Date.parse(value);return Number.isNaN(ms)?void 0:ms}const seconds=date=>Math.floor(date.getTime()/1e3)*1e3;function evaluatePreconditions(method,headers,validators){let etag=validators.etag===void 0?void 0:normalizeEtag(validators.etag),modified=validators.lastModified?seconds(validators.lastModified):void 0,safe=method===`GET`||method===`HEAD`,ifMatch=header(headers,`if-match`);if(ifMatch!==void 0){let tags=tagsOf(ifMatch);if(!(tags.includes(`*`)||etag!==void 0&&!isWeak(etag)&&tags.some(t=>!isWeak(t)&&t===etag)))return 412}else{let since=dateOf(header(headers,`if-unmodified-since`));if(since!==void 0&&modified!==void 0&&modified>since)return 412}let ifNoneMatch=header(headers,`if-none-match`);if(ifNoneMatch!==void 0){let tags=tagsOf(ifNoneMatch);return tags.includes(`*`)||etag!==void 0&&tags.some(t=>opaque(t)===opaque(etag))?safe?304:412:200}if(safe){let since=dateOf(header(headers,`if-modified-since`));if(since!==void 0&&modified!==void 0&&modified<=since)return 304}return 200}function publishMatchedRoute(req,entry){let route=matchedRoutes.get(entry);route||(route=Object.freeze({method:entry.method,path:entry.path,controller:entry.meta.controller,handlerName:entry.meta.handlerName,flags:entry.meta.flags??EMPTY_FLAGS,pattern:entry.meta.pattern??entry.path,urls:entry.urls}),matchedRoutes.set(entry,route)),req[ROUTE_SLOT]=route}const matchedRoutes=/* @__PURE__ */ new WeakMap,EMPTY_FLAGS=/* @__PURE__ */ new Map;function isBigIntJsonError(err){return err instanceof TypeError&&/BigInt/.test(err.message)}function stringifyJson(data){try{return JSON.stringify(data)}catch(err){if(!isBigIntJsonError(err))throw err;return JSON.stringify(data,(_key,value)=>typeof value==`bigint`?value.toString():value)}}function sortSignature(sort){return sort.map(s=>`${s.field}:${s.direction}`).join(`,`)}function isPrimitive(value){return value===null||[`string`,`number`,`boolean`].includes(typeof value)}function encodeCursor(position,signature){let bytes=new TextEncoder().encode(JSON.stringify({v:position,s:signature})),binary=``;for(let byte of bytes)binary+=String.fromCharCode(byte);return btoa(binary).replace(/\+/g,`-`).replace(/\//g,`_`).replace(/=+$/,``)}function decodeCursor(raw,signature,keys){let invalid=()=>HttpException.badRequest(`Invalid pagination cursor`);if(typeof raw!=`string`||!/^[A-Za-z0-9_-]+$/.test(raw))throw invalid();let parsed;try{let binary=atob(raw.replace(/-/g,`+`).replace(/_/g,`/`)),bytes=Uint8Array.from(binary,c=>c.charCodeAt(0));parsed=JSON.parse(new TextDecoder(`utf-8`,{fatal:!0}).decode(bytes))}catch{throw invalid()}if(typeof parsed!=`object`||!parsed)throw invalid();let{v,s}=parsed;if(typeof v!=`object`||!v||Array.isArray(v)||!Object.values(v).every(isPrimitive)||keys&&(Object.keys(v).length!==keys.length||!keys.every(k=>Object.hasOwn(v,k))))throw invalid();if(s!==signature)throw HttpException.badRequest(`Pagination cursor was issued for a different sort`);return v}function pageLink(rawUrl,key,value){let url=parseUrl(rawUrl),kept=url.search.slice(1).split(`&`).filter(part=>part!==``&&paramName(part)!==key);return value!==null&&kept.push(`${key}=${encodeURIComponent(value)}`),kept.length?`${url.pathname}?${kept.join(`&`)}`:url.pathname}function selfLink(rawUrl){let url=parseUrl(rawUrl);return url.pathname+url.search}function parseUrl(rawUrl){let url=new URL(rawUrl,`http://localhost`);return url.pathname=url.pathname.replace(/^\/+/,`/`),url}function paramName(part){let name=part.split(`=`,1)[0].replace(/\+/g,` `);try{return decodeURIComponent(name)}catch{return name}}const signalControllerKey=Symbol.for(`kickjs.requestContext.signalController`),readOnlyProxyCacheKey=Symbol.for(`kickjs.requestContext.readOnlyProxyCache`);function isPlainObjectOrArray(v){if(typeof v!=`object`||!v)return!1;if(Array.isArray(v))return!0;let proto=Object.getPrototypeOf(v);return proto===Object.prototype||proto===null}function makeReadOnlyProxy(target,req,label){if(isProduction()||!isPlainObjectOrArray(target))return target;let reqObj=req,cache=reqObj[readOnlyProxyCacheKey];cache||(cache=/* @__PURE__ */ new WeakMap,reqObj[readOnlyProxyCacheKey]=cache);let targetObj=target,cached=cache.get(targetObj);if(cached)return cached;let warnWrite=(verb,prop)=>{console.warn(`[kickjs] Attempted to ${verb} \`ctx.${label}.${String(prop)}\` — request data is read-only. Stash computed values via \`ctx.set('key', value)\` or a Context Contributor, or reach \`ctx.req.${label}\` if you genuinely need the raw mutable handle.`)},proxy=new Proxy(targetObj,{get(t,prop,receiver){let value=Reflect.get(t,prop,receiver);return isPlainObjectOrArray(value)?makeReadOnlyProxy(value,req,`${label}.${String(prop)}`):value},set(_t,prop){return warnWrite(`assign`,prop),!0},deleteProperty(_t,prop){return warnWrite(`delete`,prop),!0},defineProperty(_t,prop){return warnWrite(`Object.defineProperty on`,prop),!0}});return cache.set(targetObj,proxy),proxy}var RequestContext=class{req;res;next;_response;get route(){return this.req?.[ROUTE_SLOT]}constructor(req,res,next,responseDriver){this.req=req,this.res=res,this.next=next,this._response=responseDriver??res}_qsMemo;_problem;metadataReadOnly(){return requestStore.getStore()?.values??null}metadataForWrite(){let store=requestStore.getStore();if(store)return store.values;throw 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() }, () => ...).`)}get body(){return makeReadOnlyProxy(this.req.body,this.req,`body`)}get params(){return makeReadOnlyProxy(this.req.params,this.req,`params`)}get query(){return makeReadOnlyProxy(this.req.query,this.req,`query`)}get headers(){return makeReadOnlyProxy(this.req.headers,this.req,`headers`)}get requestId(){return this.req.requestId??this.req.headers[`x-request-id`]}get signal(){let req=this.req,cached=req[signalControllerKey];if(cached)return cached.signal;let ctrl=new AbortController;req[signalControllerKey]=ctrl;let abort=()=>ctrl.abort(`request closed`);return this.req.once(`close`,abort),this._response.once(`close`,abort),ctrl.signal}get session(){return this.req.session}get user(){return this.metadataReadOnly()?.get(`user`)??this.req.user}get tenantId(){return this.user?.tenantId}get roles(){let u=this.user;return u?.tenantRoles??u?.roles??[]}qs(fieldConfig,options){let memo=this._qsMemo;if(memo&&memo.config===fieldConfig&&memo.options===options)return memo.result;let effective={...options,onReject:options?.onReject??(rejection=>{let id=this.requestId?`[${this.requestId}] `:``;console.warn(`${id}query ${rejection.kind} '${rejection.field}' rejected (${rejection.reason})`)})},result=parseQuery(this.req.query,fieldConfig,effective);return this._qsMemo={config:fieldConfig,options,result},result}get file(){let f=this.req.file;return f?makeReadOnlyProxy(f,this.req,`file`):void 0}get files(){let f=this.req.files;if(Array.isArray(f))return makeReadOnlyProxy(f,this.req,`files`)}get(key){return this.metadataReadOnly()?.get(key)}require(key){let value=this.metadataReadOnly()?.get(key);if(value===void 0)throw new MissingContextValueError(key,this.routeLabel());return value}routeLabel(){let req=this.req,method=typeof req?.method==`string`?req.method:void 0,url=typeof req?.url==`string`?req.url:void 0;return method&&url?`${method} ${url}`:method??url}set(key,value){this.metadataForWrite().set(key,value)}setHeader(name,value){return this._response.setHeader(name,value),this}json(data,status=200){return this.sendJson(status,data)}created(data){return this.sendJson(201,data)}sendJson(status,data){try{return this._response.status(status).json(data)}catch(err){if(!isBigIntJsonError(err)||this._response.headersSent)throw err;return this._response.status(status).json(JSON.parse(stringifyJson(data)))}}noContent(){return this._response.status(204).end()}urlFor(name,...args){let urls=this.route?.urls;if(!urls)throw Error(`ctx.urlFor() is only available inside a matched route`);let[params,query]=args;return urls.build(name,params,query)}conditional(validators){validators.etag!==void 0&&this.setHeader(`ETag`,normalizeEtag(validators.etag)),validators.lastModified&&this.setHeader(`Last-Modified`,validators.lastModified.toUTCString());let outcome=evaluatePreconditions(String(this.req.method??`GET`).toUpperCase(),this.headers,validators);return outcome===304?(this._response.status(304).end(),!0):outcome===412&&(this.sendProblem({status:412,detail:`The resource changed since the version this request is based on.`}),!0)}notFound(message=`Not Found`){return this._response.status(404).json({message})}badRequest(message){return this._response.status(400).json({message})}get problem(){if(this._problem)return this._problem;let send=input=>this.sendProblem(input);return send.badRequest=(input={})=>this.sendProblem({status:400,...input}),send.unauthorized=(input={})=>this.sendProblem({status:401,...input}),send.forbidden=(input={})=>this.sendProblem({status:403,...input}),send.notFound=(input={})=>this.sendProblem({status:404,...input}),send.conflict=(input={})=>this.sendProblem({status:409,...input}),send.unprocessable=(input={})=>this.sendProblem({status:422,...input}),send.tooManyRequests=(input={})=>this.sendProblem({status:429,...input}),send.internal=(input={})=>this.sendProblem({status:500,...input}),send.validation=(issues,input={})=>{let errors=(issues||[]).map(issue=>({field:issue.path?.join?.(`.`)??``,message:issue.message??``,code:issue.code}));return this.sendProblem({status:422,detail:issues?.[0]?.message,...input,errors})},this._problem=send,this._problem}sendProblem(input){let body=normalizeProblem(input);return this._response.setHeader(`Content-Type`,`application/problem+json`),this._response.status(body.status).json(body)}get ip(){return resolveClientIp(this.req)}redirect(url,status=302){return this._response.status(status).setHeader(`location`,url),this._response.end()}html(content,status=200){return this._response.status(status).type(`text/html; charset=utf-8`).send(content)}send(body,options={}){return this._response.status(options.status??200).type(options.type??`text/plain; charset=utf-8`).send(body)}download(buffer,filename,contentType=`application/octet-stream`){return this._response.setHeader(`Content-Disposition`,contentDisposition(filename)),this._response.setHeader(`Content-Type`,contentType),this._response.send(buffer)}render(template,data={}){return this._response.render(template,data)}async paginate(fetcher,fieldConfig){let parsed=this.qs(fieldConfig),{data,total}=await fetcher(parsed),{page,limit}=parsed.pagination,totalPages=Math.ceil(total/limit)||1,response={data,meta:{page,limit,total,totalPages,hasNext:page<totalPages,hasPrev:page>1},links:{self:selfLink(this.requestUrl()),next:page<totalPages?pageLink(this.requestUrl(),`page`,page+1):null,prev:page>1?pageLink(this.requestUrl(),`page`,page-1):null}};return this.json(response),response}async paginateCursor(fetcher,fieldConfig,options){let{pagination,...parsed}=this.qs(fieldConfig),{limit}=pagination,idField=options?.idField??`id`,signature=sortSignature(parsed.sort),keys=options?.cursorKey?void 0:[.../* @__PURE__ */ new Set([...parsed.sort.map(s=>s.field),idField])],raw=this.req.query?.cursor,cursor=raw===void 0||raw===``?null:decodeCursor(raw,signature,keys),rows=await fetcher({...parsed,cursor,limit}),hasNext=rows.length>limit,data=hasNext?rows.slice(0,limit):rows,last=data.at(-1),nextCursor=null;hasNext&&last!==void 0&&(nextCursor=encodeCursor(cursorValues(last,keys??[],options?.cursorKey),signature));let url=this.requestUrl(),response={data,meta:{limit,hasNext,nextCursor},links:{self:selfLink(url),next:nextCursor?pageLink(url,`cursor`,nextCursor):null}};return this.json(response),response}requestUrl(){let req=this.req;return typeof req.originalUrl==`string`?req.originalUrl:typeof req.url==`string`?req.url:`/`}async sendResponse(response){let headers={};response.headers.forEach((value,name)=>{name!==`set-cookie`&&(headers[name]=value)});let cookies=response.headers.getSetCookie();if(cookies.length>0&&(headers[`set-cookie`]=cookies),!response.body){this._response.status(response.status);for(let[name,value]of Object.entries(headers))this._response.setHeader(name,value);this._response.send(``);return}this._response.writeHead(response.status,headers),this._response.flushHeaders();let reader=response.body.getReader(),stop=()=>{reader.cancel().catch(()=>{})};this.signal.addEventListener(`abort`,stop,{once:!0});try{for(;;){let{done,value}=await reader.read();if(done)break;this._response.write(Buffer.from(value))===!1&&!this.signal.aborted&&await new Promise(resolve=>{let resume=()=>{this.signal.removeEventListener(`abort`,resume),resolve()};this._response.once(`drain`,resume),this.signal.addEventListener(`abort`,resume,{once:!0})})}}finally{this.signal.removeEventListener(`abort`,stop),this._response.end()}}waitUntil(promise){waitUntil(promise)}sse(){this._response.writeHead(200,{"Content-Type":`text/event-stream`,"Cache-Control":`no-cache, no-transform`,Connection:`keep-alive`,"X-Accel-Buffering":`no`}),this._response.flushHeaders();let closeCallbacks=[];return this.req.on(`close`,()=>{for(let cb of closeCallbacks)cb()}),{send:(data,event,id)=>{id&&this._response.write(`id: ${id}\n`),event&&this._response.write(`event: ${event}\n`),this._response.write(`data: ${JSON.stringify(data)}\n\n`)},comment:text=>{this._response.write(`: ${text}\n\n`)},onClose:fn=>{closeCallbacks.push(fn)},close:()=>{this._response.end()}}}};function contentDisposition(filename){return`attachment; filename="${filename.replace(/[^\x20-\x7e]|["\\]/g,`_`)}"; filename*=UTF-8''${encodeURIComponent(filename).replace(/['()*]/g,c=>`%${c.charCodeAt(0).toString(16).toUpperCase()}`)}`}function cursorValues(row,keys,cursorKey){if(cursorKey)return cursorKey(row);let values={};for(let key of keys){let value=row[key];if(value===void 0)throw Error(`paginateCursor: row has no '${key}' — return the sort fields and the id field on every row, or pass options.cursorKey / options.idField`);values[key]=value instanceof Date?value.toISOString():typeof value==`bigint`?value.toString():value}return values}export{evaluatePreconditions as a,stringifyJson as i,contentDisposition as n,publishMatchedRoute as r,RequestContext as t};
12
+ //# sourceMappingURL=context-CfGBpRlD.mjs.map