@forinda/kickjs 5.3.0 → 5.5.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 (122) hide show
  1. package/dist/{adapter-C1w_xt08.d.mts → adapter-0r2uRCD3.d.mts} +2 -2
  2. package/dist/{adapter-C1w_xt08.d.mts.map → adapter-0r2uRCD3.d.mts.map} +1 -1
  3. package/dist/app-module-CzlIIjO3.d.mts +92 -0
  4. package/dist/app-module-CzlIIjO3.d.mts.map +1 -0
  5. package/dist/{application-BTRI4aBd.d.mts → application-CaEYca9E.d.mts} +34 -7
  6. package/dist/application-CaEYca9E.d.mts.map +1 -0
  7. package/dist/application-Zt956jNS.mjs +12 -0
  8. package/dist/application-Zt956jNS.mjs.map +1 -0
  9. package/dist/bootstrap-CmFQq1ar.mjs +12 -0
  10. package/dist/{bootstrap-kPcmbbWe.mjs.map → bootstrap-CmFQq1ar.mjs.map} +1 -1
  11. package/dist/{bootstrap-B4YrBipl.d.mts → bootstrap-Db8k2-21.d.mts} +2 -2
  12. package/dist/{bootstrap-B4YrBipl.d.mts.map → bootstrap-Db8k2-21.d.mts.map} +1 -1
  13. package/dist/config/index.mjs +2 -4
  14. package/dist/config-DDz5LuWw.mjs +12 -0
  15. package/dist/{config-DxEREQmR.mjs.map → config-DDz5LuWw.mjs.map} +1 -1
  16. package/dist/container-DrioVLNv.mjs +12 -0
  17. package/dist/{container-SMnB5yeT.mjs.map → container-DrioVLNv.mjs.map} +1 -1
  18. package/dist/context-B4BeGq1B.mjs +12 -0
  19. package/dist/context-B4BeGq1B.mjs.map +1 -0
  20. package/dist/{context-Ymvv-85x.d.mts → context-BAdAV-zO.d.mts} +48 -11
  21. package/dist/context-BAdAV-zO.d.mts.map +1 -0
  22. package/dist/{context-decorator-Bca_BoRK.d.mts → context-decorator-BgdDd-6X.d.mts} +19 -4
  23. package/dist/{context-decorator-Bca_BoRK.d.mts.map → context-decorator-BgdDd-6X.d.mts.map} +1 -1
  24. package/dist/core/adapter.d.mts +1 -1
  25. package/dist/core/adapter.mjs +2 -2
  26. package/dist/core/app-module.d.mts +2 -2
  27. package/dist/core/app-module.mjs +2 -2
  28. package/dist/core/cache.mjs +2 -103
  29. package/dist/core/cache.mjs.map +1 -1
  30. package/dist/core/container.mjs +2 -3
  31. package/dist/core/cron.mjs +2 -32
  32. package/dist/core/cron.mjs.map +1 -1
  33. package/dist/core/decorators.mjs +2 -285
  34. package/dist/core/decorators.mjs.map +1 -1
  35. package/dist/core/errors.mjs +2 -110
  36. package/dist/core/errors.mjs.map +1 -1
  37. package/dist/core/interfaces.mjs +2 -53
  38. package/dist/core/interfaces.mjs.map +1 -1
  39. package/dist/core/logger.mjs +2 -207
  40. package/dist/core/logger.mjs.map +1 -1
  41. package/dist/core/path.mjs +2 -35
  42. package/dist/core/path.mjs.map +1 -1
  43. package/dist/core/plugin.d.mts +1 -1
  44. package/dist/core/plugin.mjs +2 -2
  45. package/dist/core/reactivity.mjs +2 -179
  46. package/dist/core/reactivity.mjs.map +1 -1
  47. package/dist/core-MvABl8Cl.mjs +13 -0
  48. package/dist/core-MvABl8Cl.mjs.map +1 -0
  49. package/dist/env-CObTuGZ3.mjs +12 -0
  50. package/dist/{env-C4Yr6nN8.mjs.map → env-CObTuGZ3.mjs.map} +1 -1
  51. package/dist/http/application.d.mts +1 -1
  52. package/dist/http/application.mjs +2 -3
  53. package/dist/http/bootstrap.d.mts +1 -1
  54. package/dist/http/bootstrap.mjs +2 -3
  55. package/dist/http/context.d.mts +2 -2
  56. package/dist/http/context.mjs +2 -3
  57. package/dist/http/middleware/cors.mjs +2 -73
  58. package/dist/http/middleware/cors.mjs.map +1 -1
  59. package/dist/http/middleware/csrf.mjs +2 -62
  60. package/dist/http/middleware/csrf.mjs.map +1 -1
  61. package/dist/http/middleware/error-handler.mjs +2 -54
  62. package/dist/http/middleware/error-handler.mjs.map +1 -1
  63. package/dist/http/middleware/helmet.mjs +2 -41
  64. package/dist/http/middleware/helmet.mjs.map +1 -1
  65. package/dist/http/middleware/rate-limit.mjs +2 -91
  66. package/dist/http/middleware/rate-limit.mjs.map +1 -1
  67. package/dist/http/middleware/request-id.mjs +2 -25
  68. package/dist/http/middleware/request-id.mjs.map +1 -1
  69. package/dist/http/middleware/request-logger.mjs +2 -39
  70. package/dist/http/middleware/request-logger.mjs.map +1 -1
  71. package/dist/http/middleware/session.mjs +2 -167
  72. package/dist/http/middleware/session.mjs.map +1 -1
  73. package/dist/http/middleware/spa.d.mts +1 -1
  74. package/dist/http/middleware/spa.mjs +2 -98
  75. package/dist/http/middleware/spa.mjs.map +1 -1
  76. package/dist/http/middleware/upload.mjs +2 -181
  77. package/dist/http/middleware/upload.mjs.map +1 -1
  78. package/dist/http/middleware/validate.mjs +2 -68
  79. package/dist/http/middleware/validate.mjs.map +1 -1
  80. package/dist/http/middleware/views.d.mts +1 -1
  81. package/dist/http/middleware/views.mjs +2 -56
  82. package/dist/http/middleware/views.mjs.map +1 -1
  83. package/dist/http/query/index.mjs +2 -3
  84. package/dist/http/router-builder.d.mts +1 -1
  85. package/dist/http/router-builder.mjs +2 -105
  86. package/dist/http/router-builder.mjs.map +1 -1
  87. package/dist/{index-DvZfBNIf.d.mts → index-D-Wb23e6.d.mts} +264 -86
  88. package/dist/index-D-Wb23e6.d.mts.map +1 -0
  89. package/dist/index.d.mts +12 -12
  90. package/dist/index.mjs +2 -171
  91. package/dist/index.mjs.map +1 -1
  92. package/dist/metadata-WTmSU6Sf.mjs +12 -0
  93. package/dist/{metadata-CdYaU-XM.mjs.map → metadata-WTmSU6Sf.mjs.map} +1 -1
  94. package/dist/{plugin-DF8Xfv9Z.d.mts → plugin-JMkG7soG.d.mts} +102 -8
  95. package/dist/plugin-JMkG7soG.d.mts.map +1 -0
  96. package/dist/query-BmO0aBf6.mjs +12 -0
  97. package/dist/{query-nAYUgagU.mjs.map → query-BmO0aBf6.mjs.map} +1 -1
  98. package/dist/{router-builder-C7sXk_FG.d.mts → router-builder-CaQ629tw.d.mts} +2 -2
  99. package/dist/{router-builder-C7sXk_FG.d.mts.map → router-builder-CaQ629tw.d.mts.map} +1 -1
  100. package/dist/{spa-e4FIS2RB.d.mts → spa-CreyQc4N.d.mts} +2 -2
  101. package/dist/{spa-e4FIS2RB.d.mts.map → spa-CreyQc4N.d.mts.map} +1 -1
  102. package/dist/{views-DkNp9JJs.d.mts → views-1e3jQr5C.d.mts} +4 -4
  103. package/dist/{views-DkNp9JJs.d.mts.map → views-1e3jQr5C.d.mts.map} +1 -1
  104. package/package.json +2 -2
  105. package/dist/app-module-D6zL_V5S.d.mts +0 -50
  106. package/dist/app-module-D6zL_V5S.d.mts.map +0 -1
  107. package/dist/application-BTRI4aBd.d.mts.map +0 -1
  108. package/dist/application-Cna_2gex.mjs +0 -574
  109. package/dist/application-Cna_2gex.mjs.map +0 -1
  110. package/dist/bootstrap-kPcmbbWe.mjs +0 -195
  111. package/dist/config-DxEREQmR.mjs +0 -135
  112. package/dist/container-SMnB5yeT.mjs +0 -897
  113. package/dist/context-B0B3WQft.mjs +0 -348
  114. package/dist/context-B0B3WQft.mjs.map +0 -1
  115. package/dist/context-Ymvv-85x.d.mts.map +0 -1
  116. package/dist/core--a4XflX7.mjs +0 -820
  117. package/dist/core--a4XflX7.mjs.map +0 -1
  118. package/dist/env-C4Yr6nN8.mjs +0 -137
  119. package/dist/index-DvZfBNIf.d.mts.map +0 -1
  120. package/dist/metadata-CdYaU-XM.mjs +0 -76
  121. package/dist/plugin-DF8Xfv9Z.d.mts.map +0 -1
  122. package/dist/query-nAYUgagU.mjs +0 -164
@@ -1 +1 @@
1
- {"version":3,"file":"decorators.mjs","names":[],"sources":["../../src/core/decorators.ts"],"sourcesContent":["import 'reflect-metadata'\nimport { METADATA, Scope, type BuilderOf, type ServiceOptions } from './interfaces'\nimport { Container, type KickJsRegistry } from './container'\nimport {\n setClassMeta,\n setMethodMeta,\n pushClassMeta,\n pushMethodMeta,\n setInMetaMap,\n setInMetaRecord,\n} from './metadata'\n\n// ── Decorator Registration System ───────────────────────────────────────\n// Decorators execute at class-definition time (module load). The Container\n// may not exist yet when the first decorator fires. We queue registrations\n// and flush them on first Container.getInstance() call.\n//\n// `allRegistrations` is a persistent registry that survives Container.reset().\n// On reset (HMR), all previously decorated classes are re-registered on the\n// fresh container. This ensures @Service, @Controller, @Repository, etc.\n// all survive HMR without manual re-registration.\n\ntype PendingRegistration = { target: any; scope: Scope }\nconst pendingRegistrations: PendingRegistration[] = []\n// Keyed by class name to prevent memory leaks during HMR — new class with\n// the same name replaces the old entry instead of accumulating references.\nconst allRegistrations = new Map<string, { target: any; scope: Scope }>()\nlet containerRef: any = null\n\nfunction flushPending(container: any): void {\n containerRef = container\n for (const { target, scope } of pendingRegistrations) {\n if (!container.has(target)) {\n container.register(target, target, scope)\n }\n }\n pendingRegistrations.length = 0\n}\n\n// Wire up synchronously — Container._onReady is called on first getInstance()\nContainer._onReady = flushPending\n\n// On Container.reset(), update containerRef and replay ALL decorator\n// registrations on the fresh container. This handles HMR where the container\n// is wiped but not all decorated modules are re-evaluated.\nContainer._onReset = (container: any) => {\n containerRef = container\n for (const [, { target, scope }] of allRegistrations) {\n if (!container.has(target)) {\n container.register(target, target, scope)\n }\n }\n}\n\n// ── Class Decorators ────────────────────────────────────────────────────\n\nfunction registerInContainer(target: any, scope: Scope): void {\n setClassMeta(METADATA.INJECTABLE, true, target)\n setClassMeta(METADATA.SCOPE, scope, target)\n\n // Track in persistent registry — survives Container.reset() for HMR replay.\n // Keyed by name so HMR class re-creation replaces the old entry.\n const name = target.name || String(target)\n allRegistrations.set(name, { target, scope })\n\n if (containerRef) {\n // Container already initialized — register immediately\n if (!containerRef.has(target)) {\n containerRef.register(target, target, scope)\n }\n } else {\n // Container not ready yet — queue for later\n pendingRegistrations.push({ target, scope })\n }\n}\n\n/** Mark a class as injectable with lifecycle scope */\nexport function Injectable(options?: ServiceOptions): ClassDecorator {\n return (target: any) => {\n setClassMeta(METADATA.CLASS_KIND, 'injectable', target)\n registerInContainer(target, options?.scope ?? Scope.SINGLETON)\n }\n}\n\n/** Mark a class as a service (semantic alias for Injectable) */\nexport function Service(options?: ServiceOptions): ClassDecorator {\n return (target: any) => {\n setClassMeta(METADATA.CLASS_KIND, 'service', target)\n registerInContainer(target, options?.scope ?? Scope.SINGLETON)\n }\n}\n\n/** Mark a class as a generic managed component */\nexport function Component(options?: ServiceOptions): ClassDecorator {\n return (target: any) => {\n setClassMeta(METADATA.CLASS_KIND, 'component', target)\n registerInContainer(target, options?.scope ?? Scope.SINGLETON)\n }\n}\n\n/** Mark a class as a repository */\nexport function Repository(options?: ServiceOptions): ClassDecorator {\n return (target: any) => {\n setClassMeta(METADATA.CLASS_KIND, 'repository', target)\n registerInContainer(target, options?.scope ?? Scope.SINGLETON)\n }\n}\n\n/**\n * Mark a class as an HTTP controller and register it in the DI container.\n *\n * Route prefixes are defined by the module's `routes().path` — the single\n * source of truth for where routes mount. The legacy\n * `@Controller('/path')` parameter was removed in v4; if your code\n * still passes a string, see `docs/guide/migration-v3-to-v4.md` for\n * the rename map.\n */\nexport function Controller(): ClassDecorator {\n return (target: any) => {\n setClassMeta(METADATA.CLASS_KIND, 'controller', target)\n registerInContainer(target, Scope.SINGLETON)\n }\n}\n\n// ── Method Decorators ───────────────────────────────────────────────────\n\n/** Mark a method as a lifecycle hook called after instantiation */\nexport function PostConstruct(): MethodDecorator {\n return (target, propertyKey) => {\n setClassMeta(METADATA.POST_CONSTRUCT, propertyKey, target)\n }\n}\n\n// ── Property Decorators ─────────────────────────────────────────────────\n\n/** Property injection — resolved lazily from the container */\nexport function Autowired(token?: any): PropertyDecorator {\n return (target, propertyKey) => {\n setInMetaMap(METADATA.AUTOWIRED, target, propertyKey as string, token)\n }\n}\n\n/**\n * Constructor parameter injection with an explicit token.\n *\n * **Constructor parameters only** — does not work as a property decorator.\n * For property injection with a token, use `@Autowired(token)` instead.\n *\n * ## Typed string-literal overload (architecture.md §22.4 #3)\n *\n * When called with a string literal that matches a key of the\n * augmented `KickJsRegistry`, TypeScript narrows the parameter type\n * to the registered type. Typo'd literals become compile errors\n * (the string isn't `keyof KickJsRegistry`). Class identities and\n * `InjectionToken<T>` keep working unchanged via the second overload.\n *\n * @example\n * ```ts\n * import { Service, Inject } from '@forinda/kickjs'\n * import type { PrismaClient } from '@prisma/client'\n *\n * `@Service()`\n * class UserRepo {\n * constructor(@Inject('kick/prisma/Client') private db: PrismaClient) {}\n * }\n * ```\n *\n * After `kick typegen` populates `.kickjs/types/registry.d.ts` the\n * literal autocompletes from the registry, and a typo\n * (`@Inject('kick/prisma/Cleint')`) becomes a TS2345 error.\n */\nexport function Inject<K extends keyof KickJsRegistry & string>(token: K): ParameterDecorator\nexport function Inject(token: unknown): ParameterDecorator\nexport function Inject(token: unknown): ParameterDecorator {\n return (target, _propertyKey, parameterIndex) => {\n setInMetaRecord(METADATA.INJECT, target as object, parameterIndex, token)\n }\n}\n\n/**\n * Global ambient registry of typed environment variables, populated by\n * `kick typegen` from the project's env schema (typically\n * `src/env.ts`'s `export default defineEnv(...)`).\n *\n * Empty by default — declarations come from `.kickjs/types/env.ts`\n * generated alongside the rest of the typegen output. Once populated,\n * `@Value('PORT')` autocompletes the key, type-checks the default\n * value, and `process.env.PORT` is also typed via the parallel\n * `NodeJS.ProcessEnv` augmentation in the same generated file.\n */\ndeclare global {\n // eslint-disable-next-line @typescript-eslint/no-empty-object-type\n interface KickEnv {}\n}\n\n/** A string key known to the typed env registry (`never` until typegen runs) */\nexport type EnvKey = keyof KickEnv & string\n\n/**\n * Look up the type of a typed env entry.\n *\n * Decorators can't propagate the property type from the key, so users\n * still need to write the property's type — but `Env<K>` lets them\n * derive it from `KickEnv` instead of duplicating the schema:\n *\n * ```ts\n * @Service()\n * class MyService {\n * @Value('PORT')\n * private port!: Env<'PORT'> // → number, narrowed from KickEnv['PORT']\n * }\n * ```\n */\nexport type Env<K extends EnvKey = EnvKey> = KickEnv[K]\n\n/**\n * Constraint that allows any string when the typed env registry is\n * empty (no `kick typegen` has run yet, so existing code with raw\n * string keys keeps working) but locks the argument down to known\n * `EnvKey` literals once the registry is populated.\n *\n * Implementation: when `EnvKey` is `never`, the conditional resolves\n * to the user's `K`, accepting anything. Once typegen has populated\n * `KickEnv`, `EnvKey` becomes a real union and the conditional forces\n * `K` to be assignable to it.\n */\ntype ValueKey<K extends string> = [EnvKey] extends [never] ? K : K & EnvKey\n\n/**\n * Inject an environment variable value. Evaluated lazily so the env\n * is available at access time, not at decoration time.\n *\n * If no default is provided and the env var is missing, throws at access time\n * to catch misconfiguration early instead of returning undefined.\n *\n * Uses metadata + instance getter to work correctly with `useDefineForClassFields`.\n *\n * Type-safety:\n * - Without `kick typegen` run, any string key is accepted (back-compat).\n * - After typegen, `KickEnv` is populated and unknown keys become a tsc\n * error. The optional `defaultValue` is type-checked against the\n * schema's inferred type for that key.\n */\nexport function Value<K extends string>(\n envKey: ValueKey<K>,\n defaultValue?: K extends EnvKey ? KickEnv[K] : unknown,\n): PropertyDecorator {\n return (target, propertyKey) => {\n setInMetaMap(METADATA.VALUE, target, propertyKey as string, { envKey, defaultValue })\n }\n}\n\n// ── @Asset — typed asset path injection (assets-plan.md PR 3+) ─────────\n\nimport type { KickAssets } from './assets'\n\n/**\n * Flatten the nested `KickAssets` augmentation (typegen-emitted in\n * PR 4) into a string-literal union of dot/slash-joined paths.\n *\n * `interface KickAssets { mails: { welcome: () => string; orders: {\n * confirmation: () => string } } }` becomes\n * `'mails/welcome' | 'mails/orders/confirmation'`.\n *\n * Returns `never` when `KickAssets` is empty (no typegen has run yet)\n * so `AssetKeyArg` falls through to accept any string.\n */\ntype FlattenAssets<T, Prefix extends string = ''> = {\n [K in keyof T & string]: T[K] extends () => string\n ? `${Prefix}${K}`\n : T[K] extends Record<string, unknown>\n ? FlattenAssets<T[K], `${Prefix}${K}/`>\n : never\n}[keyof T & string]\n\n/** Flat union of every known `<namespace>/<key>` path. */\nexport type AssetKey = FlattenAssets<KickAssets>\n\n/**\n * Constraint mirroring `ValueKey<K>` — accepts any string when\n * `AssetKey` is `never` (back-compat for adopters who haven't run\n * `kick typegen` yet) but locks the argument to known literals once\n * the typegen-augmented `KickAssets` interface is populated.\n */\ntype AssetKeyArg<K extends string> = [AssetKey] extends [never] ? K : K & AssetKey\n\n/**\n * Inject the resolved file-system path for a typed asset. Mirrors\n * `@Value`'s lazy-getter pattern — the asset is resolved on every\n * property access, NOT at class instantiation, so:\n *\n * - Tests can swap fixtures + clear the cache without re-instantiating\n * the consuming class.\n * - The first access cost is paid once per process (the manifest cache\n * in `core/assets.ts` makes subsequent calls cheap).\n *\n * Type-safety:\n *\n * - Without typegen, any string key is accepted (back-compat — same\n * trick as `@Value`).\n * - After typegen, `KickAssets` is populated and `AssetKey` is a\n * union of every flattened `<namespace>/<key>` path. Unknown keys\n * become a TS error.\n *\n * @example\n * ```ts\n * import { Service, Asset } from '@forinda/kickjs'\n *\n * `@Service()`\n * class MailService {\n * `@Asset('mails/welcome')`\n * private welcomeTemplate!: string\n *\n * send(user: User) {\n * return ejs.renderFile(this.welcomeTemplate, { user })\n * }\n * }\n * ```\n */\nexport function Asset<K extends string>(assetKey: AssetKeyArg<K>): PropertyDecorator {\n return (target, propertyKey) => {\n setInMetaMap(METADATA.ASSET, target, propertyKey as string, { assetKey })\n }\n}\n\n// ── HTTP Route Decorators ───────────────────────────────────────────────\n\nexport interface RouteDefinition {\n method: string\n path: string\n handlerName: string\n validation?: {\n /** JSON Schema object for validating the request body */\n body?: any\n /** JSON Schema object for validating query parameters */\n query?: any\n /** JSON Schema object for validating URL params */\n params?: any\n /** Schema name in OpenAPI components/schemas for the request body. Auto-generated from handler name if omitted. */\n name?: string\n }\n}\n\nfunction createRouteDecorator(method: string) {\n return (path?: string, validation?: RouteDefinition['validation']): MethodDecorator => {\n return (target, propertyKey) => {\n pushClassMeta<RouteDefinition>(METADATA.ROUTES, target.constructor, {\n method,\n path: path || '/',\n handlerName: propertyKey as string,\n validation,\n })\n }\n }\n}\n\nexport const Get = createRouteDecorator('GET')\nexport const Post = createRouteDecorator('POST')\nexport const Put = createRouteDecorator('PUT')\nexport const Delete = createRouteDecorator('DELETE')\nexport const Patch = createRouteDecorator('PATCH')\n\n// ── Query Params Decorator ─────────────────────────────────────────────\n\nexport interface ApiQueryParamsConfig {\n /** Fields that can be used in filter queries (e.g., `?filter=status:eq:active`) */\n filterable?: string[]\n /** Fields that can be used in sort queries (e.g., `?sort=createdAt:desc`) */\n sortable?: string[]\n /** Fields that are searched with the `?q=` parameter */\n searchable?: string[]\n}\n\n/**\n * Column-object-based query params config (e.g., from DrizzleQueryParamsConfig).\n * `Object.keys()` is used to derive field names for OpenAPI docs.\n */\nexport interface ColumnApiQueryParamsConfig {\n columns: Record<string, any>\n sortable?: Record<string, any>\n searchColumns?: any[]\n [key: string]: any\n}\n\n/**\n * Normalize a query params config to the string-based ApiQueryParamsConfig.\n * Handles both string-based and column-object-based configs.\n */\nexport function normalizeApiQueryParamsConfig(\n config: ApiQueryParamsConfig | ColumnApiQueryParamsConfig,\n): ApiQueryParamsConfig {\n if ('columns' in config && config.columns && typeof config.columns === 'object') {\n return {\n filterable: Object.keys(config.columns),\n sortable: config.sortable ? Object.keys(config.sortable) : undefined,\n searchable: config.searchColumns\n ? config.searchColumns.map((col: any) => col?.name ?? '').filter(Boolean)\n : undefined,\n }\n }\n return config as ApiQueryParamsConfig\n}\n\n/**\n * Document the query parameters accepted by a GET endpoint.\n * Used by SwaggerAdapter to generate `filter`, `sort`, `page`, `limit`, and `q` params\n * in the OpenAPI spec, with descriptions listing the allowed fields.\n *\n * Accepts both string-based configs and column-object configs (e.g., DrizzleQueryParamsConfig).\n *\n * @example\n * ```ts\n * // String-based\n * @ApiQueryParams({\n * filterable: ['status', 'category', 'price'],\n * sortable: ['name', 'createdAt', 'price'],\n * searchable: ['name', 'description'],\n * })\n *\n * // Column-object-based (Drizzle)\n * @ApiQueryParams(TASK_QUERY_CONFIG)\n * ```\n */\nexport function ApiQueryParams(\n config: ApiQueryParamsConfig | ColumnApiQueryParamsConfig,\n): MethodDecorator {\n return (target, propertyKey) => {\n const normalized = normalizeApiQueryParamsConfig(config)\n setMethodMeta(METADATA.QUERY_PARAMS, normalized, target.constructor, propertyKey as string)\n }\n}\n\n// ── Middleware Decorators ───────────────────────────────────────────────\n\n/**\n * Middleware handler function.\n * Generic `TCtx` defaults to `any` — import `RequestContext` from\n * `@forinda/kickjs` for full type safety:\n *\n * ```ts\n * import type { MiddlewareHandler } from '@forinda/kickjs'\n * import type { RequestContext } from '@forinda/kickjs'\n *\n * const auth: MiddlewareHandler<RequestContext> = (ctx, next) => {\n * ctx.body // fully typed\n * next()\n * }\n * ```\n */\nexport type MiddlewareHandler<TCtx = any> = (ctx: TCtx, next: () => void) => void | Promise<void>\n\n/** Attach middleware handlers to a class or method */\nexport function Middleware(...handlers: MiddlewareHandler[]): ClassDecorator & MethodDecorator {\n return (target: any, propertyKey?: string | symbol) => {\n if (propertyKey) {\n pushMethodMeta(\n METADATA.METHOD_MIDDLEWARES,\n target.constructor,\n propertyKey as string,\n ...handlers,\n )\n } else {\n pushClassMeta(METADATA.CLASS_MIDDLEWARES, target, ...handlers)\n }\n }\n}\n\n// ── File Upload Decorator ───────────────────────────────────────────────\n\n/**\n * File filter — accepts short extensions ('jpg'), full MIME types ('image/jpeg'),\n * wildcards ('image/*'), or a function `(mimetype, filename) => boolean` for full control.\n */\nexport type FileTypeFilter = string[] | ((mimetype: string, filename: string) => boolean)\n\n/**\n * Shared upload options used by both the `@FileUpload` decorator and the\n * `upload.single()` / `upload.array()` / `upload.none()` middleware.\n */\nexport interface BaseUploadOptions {\n /** Max file size in bytes (default: 5MB) */\n maxSize?: number\n /**\n * Allowed file types:\n * - **string[]** — short extensions ('jpg'), full MIME types ('image/jpeg'), or wildcards ('image/*')\n * - **function** — `(mimetype, filename) => boolean` for full control\n */\n allowedTypes?: FileTypeFilter\n /** Extend the built-in extension-to-MIME map */\n customMimeMap?: Record<string, string>\n}\n\nexport interface FileUploadConfig extends BaseUploadOptions {\n mode: 'single' | 'array' | 'none'\n /** Form field name (default: 'file') */\n fieldName?: string\n /** Max files for array mode (default: 10) */\n maxCount?: number\n}\n\n/** Configure file upload handling for a controller method */\nexport function FileUpload(config: FileUploadConfig): MethodDecorator {\n return (target, propertyKey) => {\n setMethodMeta(METADATA.FILE_UPLOAD, config, target.constructor, propertyKey as string)\n }\n}\n\n// ── Builder Decorator ───────────────────────────────────────────────────\n\nfunction attachBuilder(target: any): void {\n setClassMeta(METADATA.BUILDER, true, target)\n target.builder = function () {\n const props: Record<string, any> = {}\n const proxy: any = new Proxy(\n {},\n {\n get(_, key) {\n if (key === 'build') {\n return () => Object.assign(new target(), props)\n }\n return (value: any) => {\n props[key as string] = value\n return proxy\n }\n },\n },\n )\n return proxy\n }\n}\n\n/**\n * Add a static `builder()` method for fluent construction.\n *\n * Legacy decorators cannot widen the class type, so by default the\n * caller sees the unmodified shape. Opt into typing by adding a single\n * `declare static` line:\n *\n * ```ts\n * @Builder\n * class UserDto {\n * name!: string\n * email!: string\n * declare static readonly builder: () => BuilderOf<UserDto>\n * }\n * ```\n *\n * `readonly` keeps SonarQube's `typescript:S1444` quiet — the runtime\n * assigns `target.builder` once at decoration time and never again.\n *\n * If you'd rather not write the `declare`, use `withBuilder()` instead —\n * same runtime, types inferred automatically.\n */\nexport function Builder(target: any): void {\n attachBuilder(target)\n}\n\n/**\n * Factory variant of `@Builder`. Wraps the class with the same runtime\n * and returns it intersected with `{ builder(): BuilderOf<T> }` so the\n * static is fully typed without any `declare` boilerplate.\n *\n * ```ts\n * class UserDtoBase {\n * name!: string\n * email!: string\n * }\n * export const UserDto = withBuilder(UserDtoBase)\n * export type UserDto = InstanceType<typeof UserDto>\n *\n * UserDto.builder().name('Alice').email('a@b.com').build() // fully typed\n * ```\n */\nexport function withBuilder<C extends new (...args: any[]) => any>(\n ctor: C,\n): C & { builder(): BuilderOf<InstanceType<C>> } {\n attachBuilder(ctor)\n return ctor as C & { builder(): BuilderOf<Instance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"version":3,"file":"decorators.mjs","names":[],"sources":["../../src/core/decorators.ts"],"sourcesContent":["import 'reflect-metadata'\nimport { METADATA, Scope, type BuilderOf, type ServiceOptions } from './interfaces'\nimport { Container, type KickJsRegistry } from './container'\nimport {\n setClassMeta,\n setMethodMeta,\n pushClassMeta,\n pushMethodMeta,\n setInMetaMap,\n setInMetaRecord,\n} from './metadata'\n\n// ── Decorator Registration System ───────────────────────────────────────\n// Decorators execute at class-definition time (module load). The Container\n// may not exist yet when the first decorator fires. We queue registrations\n// and flush them on first Container.getInstance() call.\n//\n// `allRegistrations` is a persistent registry that survives Container.reset().\n// On reset (HMR), all previously decorated classes are re-registered on the\n// fresh container. This ensures @Service, @Controller, @Repository, etc.\n// all survive HMR without manual re-registration.\n\ntype PendingRegistration = { target: any; scope: Scope }\nconst pendingRegistrations: PendingRegistration[] = []\n// Keyed by class name to prevent memory leaks during HMR — new class with\n// the same name replaces the old entry instead of accumulating references.\nconst allRegistrations = new Map<string, { target: any; scope: Scope }>()\nlet containerRef: any = null\n\nfunction flushPending(container: any): void {\n containerRef = container\n for (const { target, scope } of pendingRegistrations) {\n if (!container.has(target)) {\n container.register(target, target, scope)\n }\n }\n pendingRegistrations.length = 0\n}\n\n// Wire up synchronously — Container._onReady is called on first getInstance()\nContainer._onReady = flushPending\n\n// On Container.reset(), update containerRef and replay ALL decorator\n// registrations on the fresh container. This handles HMR where the container\n// is wiped but not all decorated modules are re-evaluated.\nContainer._onReset = (container: any) => {\n containerRef = container\n for (const [, { target, scope }] of allRegistrations) {\n if (!container.has(target)) {\n container.register(target, target, scope)\n }\n }\n}\n\n// ── Class Decorators ────────────────────────────────────────────────────\n\nfunction registerInContainer(target: any, scope: Scope): void {\n setClassMeta(METADATA.INJECTABLE, true, target)\n setClassMeta(METADATA.SCOPE, scope, target)\n\n // Track in persistent registry — survives Container.reset() for HMR replay.\n // Keyed by name so HMR class re-creation replaces the old entry.\n const name = target.name || String(target)\n allRegistrations.set(name, { target, scope })\n\n if (containerRef) {\n // Container already initialized — register immediately\n if (!containerRef.has(target)) {\n containerRef.register(target, target, scope)\n }\n } else {\n // Container not ready yet — queue for later\n pendingRegistrations.push({ target, scope })\n }\n}\n\n/** Mark a class as injectable with lifecycle scope */\nexport function Injectable(options?: ServiceOptions): ClassDecorator {\n return (target: any) => {\n setClassMeta(METADATA.CLASS_KIND, 'injectable', target)\n registerInContainer(target, options?.scope ?? Scope.SINGLETON)\n }\n}\n\n/** Mark a class as a service (semantic alias for Injectable) */\nexport function Service(options?: ServiceOptions): ClassDecorator {\n return (target: any) => {\n setClassMeta(METADATA.CLASS_KIND, 'service', target)\n registerInContainer(target, options?.scope ?? Scope.SINGLETON)\n }\n}\n\n/** Mark a class as a generic managed component */\nexport function Component(options?: ServiceOptions): ClassDecorator {\n return (target: any) => {\n setClassMeta(METADATA.CLASS_KIND, 'component', target)\n registerInContainer(target, options?.scope ?? Scope.SINGLETON)\n }\n}\n\n/** Mark a class as a repository */\nexport function Repository(options?: ServiceOptions): ClassDecorator {\n return (target: any) => {\n setClassMeta(METADATA.CLASS_KIND, 'repository', target)\n registerInContainer(target, options?.scope ?? Scope.SINGLETON)\n }\n}\n\n/**\n * Mark a class as an HTTP controller and register it in the DI container.\n *\n * Route prefixes are defined by the module's `routes().path` — the single\n * source of truth for where routes mount. The legacy\n * `@Controller('/path')` parameter was removed in v4; if your code\n * still passes a string, see `docs/guide/migration-v3-to-v4.md` for\n * the rename map.\n */\nexport function Controller(): ClassDecorator {\n return (target: any) => {\n setClassMeta(METADATA.CLASS_KIND, 'controller', target)\n registerInContainer(target, Scope.SINGLETON)\n }\n}\n\n// ── Method Decorators ───────────────────────────────────────────────────\n\n/** Mark a method as a lifecycle hook called after instantiation */\nexport function PostConstruct(): MethodDecorator {\n return (target, propertyKey) => {\n setClassMeta(METADATA.POST_CONSTRUCT, propertyKey, target)\n }\n}\n\n// ── Property Decorators ─────────────────────────────────────────────────\n\n/** Property injection — resolved lazily from the container */\nexport function Autowired(token?: any): PropertyDecorator {\n return (target, propertyKey) => {\n setInMetaMap(METADATA.AUTOWIRED, target, propertyKey as string, token)\n }\n}\n\n/**\n * Constructor parameter injection with an explicit token.\n *\n * **Constructor parameters only** — does not work as a property decorator.\n * For property injection with a token, use `@Autowired(token)` instead.\n *\n * ## Typed string-literal overload (architecture.md §22.4 #3)\n *\n * When called with a string literal that matches a key of the\n * augmented `KickJsRegistry`, TypeScript narrows the parameter type\n * to the registered type. Typo'd literals become compile errors\n * (the string isn't `keyof KickJsRegistry`). Class identities and\n * `InjectionToken<T>` keep working unchanged via the second overload.\n *\n * @example\n * ```ts\n * import { Service, Inject } from '@forinda/kickjs'\n * import type { PrismaClient } from '@prisma/client'\n *\n * `@Service()`\n * class UserRepo {\n * constructor(@Inject('kick/prisma/Client') private db: PrismaClient) {}\n * }\n * ```\n *\n * After `kick typegen` populates `.kickjs/types/registry.d.ts` the\n * literal autocompletes from the registry, and a typo\n * (`@Inject('kick/prisma/Cleint')`) becomes a TS2345 error.\n */\nexport function Inject<K extends keyof KickJsRegistry & string>(token: K): ParameterDecorator\nexport function Inject(token: unknown): ParameterDecorator\nexport function Inject(token: unknown): ParameterDecorator {\n return (target, _propertyKey, parameterIndex) => {\n setInMetaRecord(METADATA.INJECT, target as object, parameterIndex, token)\n }\n}\n\n/**\n * Global ambient registry of typed environment variables, populated by\n * `kick typegen` from the project's env schema (typically\n * `src/env.ts`'s `export default defineEnv(...)`).\n *\n * Empty by default — declarations come from `.kickjs/types/env.ts`\n * generated alongside the rest of the typegen output. Once populated,\n * `@Value('PORT')` autocompletes the key, type-checks the default\n * value, and `process.env.PORT` is also typed via the parallel\n * `NodeJS.ProcessEnv` augmentation in the same generated file.\n */\ndeclare global {\n // eslint-disable-next-line @typescript-eslint/no-empty-object-type\n interface KickEnv {}\n}\n\n/** A string key known to the typed env registry (`never` until typegen runs) */\nexport type EnvKey = keyof KickEnv & string\n\n/**\n * Look up the type of a typed env entry.\n *\n * Decorators can't propagate the property type from the key, so users\n * still need to write the property's type — but `Env<K>` lets them\n * derive it from `KickEnv` instead of duplicating the schema:\n *\n * ```ts\n * @Service()\n * class MyService {\n * @Value('PORT')\n * private port!: Env<'PORT'> // → number, narrowed from KickEnv['PORT']\n * }\n * ```\n */\nexport type Env<K extends EnvKey = EnvKey> = KickEnv[K]\n\n/**\n * Constraint that allows any string when the typed env registry is\n * empty (no `kick typegen` has run yet, so existing code with raw\n * string keys keeps working) but locks the argument down to known\n * `EnvKey` literals once the registry is populated.\n *\n * Implementation: when `EnvKey` is `never`, the conditional resolves\n * to the user's `K`, accepting anything. Once typegen has populated\n * `KickEnv`, `EnvKey` becomes a real union and the conditional forces\n * `K` to be assignable to it.\n */\ntype ValueKey<K extends string> = [EnvKey] extends [never] ? K : K & EnvKey\n\n/**\n * Inject an environment variable value. Evaluated lazily so the env\n * is available at access time, not at decoration time.\n *\n * If no default is provided and the env var is missing, throws at access time\n * to catch misconfiguration early instead of returning undefined.\n *\n * Uses metadata + instance getter to work correctly with `useDefineForClassFields`.\n *\n * Type-safety:\n * - Without `kick typegen` run, any string key is accepted (back-compat).\n * - After typegen, `KickEnv` is populated and unknown keys become a tsc\n * error. The optional `defaultValue` is type-checked against the\n * schema's inferred type for that key.\n */\nexport function Value<K extends string>(\n envKey: ValueKey<K>,\n defaultValue?: K extends EnvKey ? KickEnv[K] : unknown,\n): PropertyDecorator {\n return (target, propertyKey) => {\n setInMetaMap(METADATA.VALUE, target, propertyKey as string, { envKey, defaultValue })\n }\n}\n\n// ── @Asset — typed asset path injection (assets-plan.md PR 3+) ─────────\n\nimport type { KickAssets } from './assets'\n\n/**\n * Flatten the nested `KickAssets` augmentation (typegen-emitted in\n * PR 4) into a string-literal union of dot/slash-joined paths.\n *\n * `interface KickAssets { mails: { welcome: () => string; orders: {\n * confirmation: () => string } } }` becomes\n * `'mails/welcome' | 'mails/orders/confirmation'`.\n *\n * Returns `never` when `KickAssets` is empty (no typegen has run yet)\n * so `AssetKeyArg` falls through to accept any string.\n */\ntype FlattenAssets<T, Prefix extends string = ''> = {\n [K in keyof T & string]: T[K] extends () => string\n ? `${Prefix}${K}`\n : T[K] extends Record<string, unknown>\n ? FlattenAssets<T[K], `${Prefix}${K}/`>\n : never\n}[keyof T & string]\n\n/** Flat union of every known `<namespace>/<key>` path. */\nexport type AssetKey = FlattenAssets<KickAssets>\n\n/**\n * Constraint mirroring `ValueKey<K>` — accepts any string when\n * `AssetKey` is `never` (back-compat for adopters who haven't run\n * `kick typegen` yet) but locks the argument to known literals once\n * the typegen-augmented `KickAssets` interface is populated.\n */\ntype AssetKeyArg<K extends string> = [AssetKey] extends [never] ? K : K & AssetKey\n\n/**\n * Inject the resolved file-system path for a typed asset. Mirrors\n * `@Value`'s lazy-getter pattern — the asset is resolved on every\n * property access, NOT at class instantiation, so:\n *\n * - Tests can swap fixtures + clear the cache without re-instantiating\n * the consuming class.\n * - The first access cost is paid once per process (the manifest cache\n * in `core/assets.ts` makes subsequent calls cheap).\n *\n * Type-safety:\n *\n * - Without typegen, any string key is accepted (back-compat — same\n * trick as `@Value`).\n * - After typegen, `KickAssets` is populated and `AssetKey` is a\n * union of every flattened `<namespace>/<key>` path. Unknown keys\n * become a TS error.\n *\n * @example\n * ```ts\n * import { Service, Asset } from '@forinda/kickjs'\n *\n * `@Service()`\n * class MailService {\n * `@Asset('mails/welcome')`\n * private welcomeTemplate!: string\n *\n * send(user: User) {\n * return ejs.renderFile(this.welcomeTemplate, { user })\n * }\n * }\n * ```\n */\nexport function Asset<K extends string>(assetKey: AssetKeyArg<K>): PropertyDecorator {\n return (target, propertyKey) => {\n setInMetaMap(METADATA.ASSET, target, propertyKey as string, { assetKey })\n }\n}\n\n// ── HTTP Route Decorators ───────────────────────────────────────────────\n\nexport interface RouteDefinition {\n method: string\n path: string\n handlerName: string\n validation?: {\n /** JSON Schema object for validating the request body */\n body?: any\n /** JSON Schema object for validating query parameters */\n query?: any\n /** JSON Schema object for validating URL params */\n params?: any\n /** Schema name in OpenAPI components/schemas for the request body. Auto-generated from handler name if omitted. */\n name?: string\n }\n}\n\nfunction createRouteDecorator(method: string) {\n return (path?: string, validation?: RouteDefinition['validation']): MethodDecorator => {\n return (target, propertyKey) => {\n pushClassMeta<RouteDefinition>(METADATA.ROUTES, target.constructor, {\n method,\n path: path || '/',\n handlerName: propertyKey as string,\n validation,\n })\n }\n }\n}\n\nexport const Get = createRouteDecorator('GET')\nexport const Post = createRouteDecorator('POST')\nexport const Put = createRouteDecorator('PUT')\nexport const Delete = createRouteDecorator('DELETE')\nexport const Patch = createRouteDecorator('PATCH')\n\n// ── Query Params Decorator ─────────────────────────────────────────────\n\nexport interface ApiQueryParamsConfig {\n /** Fields that can be used in filter queries (e.g., `?filter=status:eq:active`) */\n filterable?: string[]\n /** Fields that can be used in sort queries (e.g., `?sort=createdAt:desc`) */\n sortable?: string[]\n /** Fields that are searched with the `?q=` parameter */\n searchable?: string[]\n}\n\n/**\n * Column-object-based query params config (e.g., from DrizzleQueryParamsConfig).\n * `Object.keys()` is used to derive field names for OpenAPI docs.\n */\nexport interface ColumnApiQueryParamsConfig {\n columns: Record<string, any>\n sortable?: Record<string, any>\n searchColumns?: any[]\n [key: string]: any\n}\n\n/**\n * Normalize a query params config to the string-based ApiQueryParamsConfig.\n * Handles both string-based and column-object-based configs.\n */\nexport function normalizeApiQueryParamsConfig(\n config: ApiQueryParamsConfig | ColumnApiQueryParamsConfig,\n): ApiQueryParamsConfig {\n if ('columns' in config && config.columns && typeof config.columns === 'object') {\n return {\n filterable: Object.keys(config.columns),\n sortable: config.sortable ? Object.keys(config.sortable) : undefined,\n searchable: config.searchColumns\n ? config.searchColumns.map((col: any) => col?.name ?? '').filter(Boolean)\n : undefined,\n }\n }\n return config as ApiQueryParamsConfig\n}\n\n/**\n * Document the query parameters accepted by a GET endpoint.\n * Used by SwaggerAdapter to generate `filter`, `sort`, `page`, `limit`, and `q` params\n * in the OpenAPI spec, with descriptions listing the allowed fields.\n *\n * Accepts both string-based configs and column-object configs (e.g., DrizzleQueryParamsConfig).\n *\n * @example\n * ```ts\n * // String-based\n * @ApiQueryParams({\n * filterable: ['status', 'category', 'price'],\n * sortable: ['name', 'createdAt', 'price'],\n * searchable: ['name', 'description'],\n * })\n *\n * // Column-object-based (Drizzle)\n * @ApiQueryParams(TASK_QUERY_CONFIG)\n * ```\n */\nexport function ApiQueryParams(\n config: ApiQueryParamsConfig | ColumnApiQueryParamsConfig,\n): MethodDecorator {\n return (target, propertyKey) => {\n const normalized = normalizeApiQueryParamsConfig(config)\n setMethodMeta(METADATA.QUERY_PARAMS, normalized, target.constructor, propertyKey as string)\n }\n}\n\n// ── Middleware Decorators ───────────────────────────────────────────────\n\n/**\n * Middleware handler function.\n * Generic `TCtx` defaults to `any` — import `RequestContext` from\n * `@forinda/kickjs` for full type safety:\n *\n * ```ts\n * import type { MiddlewareHandler } from '@forinda/kickjs'\n * import type { RequestContext } from '@forinda/kickjs'\n *\n * const auth: MiddlewareHandler<RequestContext> = (ctx, next) => {\n * ctx.body // fully typed\n * next()\n * }\n * ```\n */\nexport type MiddlewareHandler<TCtx = any> = (ctx: TCtx, next: () => void) => void | Promise<void>\n\n/** Attach middleware handlers to a class or method */\nexport function Middleware(...handlers: MiddlewareHandler[]): ClassDecorator & MethodDecorator {\n return (target: any, propertyKey?: string | symbol) => {\n if (propertyKey) {\n pushMethodMeta(\n METADATA.METHOD_MIDDLEWARES,\n target.constructor,\n propertyKey as string,\n ...handlers,\n )\n } else {\n pushClassMeta(METADATA.CLASS_MIDDLEWARES, target, ...handlers)\n }\n }\n}\n\n// ── File Upload Decorator ───────────────────────────────────────────────\n\n/**\n * File filter — accepts short extensions ('jpg'), full MIME types ('image/jpeg'),\n * wildcards ('image/*'), or a function `(mimetype, filename) => boolean` for full control.\n */\nexport type FileTypeFilter = string[] | ((mimetype: string, filename: string) => boolean)\n\n/**\n * Shared upload options used by both the `@FileUpload` decorator and the\n * `upload.single()` / `upload.array()` / `upload.none()` middleware.\n */\nexport interface BaseUploadOptions {\n /** Max file size in bytes (default: 5MB) */\n maxSize?: number\n /**\n * Allowed file types:\n * - **string[]** — short extensions ('jpg'), full MIME types ('image/jpeg'), or wildcards ('image/*')\n * - **function** — `(mimetype, filename) => boolean` for full control\n */\n allowedTypes?: FileTypeFilter\n /** Extend the built-in extension-to-MIME map */\n customMimeMap?: Record<string, string>\n}\n\nexport interface FileUploadConfig extends BaseUploadOptions {\n mode: 'single' | 'array' | 'none'\n /** Form field name (default: 'file') */\n fieldName?: string\n /** Max files for array mode (default: 10) */\n maxCount?: number\n}\n\n/** Configure file upload handling for a controller method */\nexport function FileUpload(config: FileUploadConfig): MethodDecorator {\n return (target, propertyKey) => {\n setMethodMeta(METADATA.FILE_UPLOAD, config, target.constructor, propertyKey as string)\n }\n}\n\n// ── Builder Decorator ───────────────────────────────────────────────────\n\nfunction attachBuilder(target: any): void {\n setClassMeta(METADATA.BUILDER, true, target)\n target.builder = function () {\n const props: Record<string, any> = {}\n const proxy: any = new Proxy(\n {},\n {\n get(_, key) {\n if (key === 'build') {\n return () => Object.assign(new target(), props)\n }\n return (value: any) => {\n props[key as string] = value\n return proxy\n }\n },\n },\n )\n return proxy\n }\n}\n\n/**\n * Add a static `builder()` method for fluent construction.\n *\n * Legacy decorators cannot widen the class type, so by default the\n * caller sees the unmodified shape. Opt into typing by adding a single\n * `declare static` line:\n *\n * ```ts\n * @Builder\n * class UserDto {\n * name!: string\n * email!: string\n * declare static readonly builder: () => BuilderOf<UserDto>\n * }\n * ```\n *\n * `readonly` keeps SonarQube's `typescript:S1444` quiet — the runtime\n * assigns `target.builder` once at decoration time and never again.\n *\n * If you'd rather not write the `declare`, use `withBuilder()` instead —\n * same runtime, types inferred automatically.\n */\nexport function Builder(target: any): void {\n attachBuilder(target)\n}\n\n/**\n * Factory variant of `@Builder`. Wraps the class with the same runtime\n * and returns it intersected with `{ builder(): BuilderOf<T> }` so the\n * static is fully typed without any `declare` boilerplate.\n *\n * ```ts\n * class UserDtoBase {\n * name!: string\n * email!: string\n * }\n * export const UserDto = withBuilder(UserDtoBase)\n * export type UserDto = InstanceType<typeof UserDto>\n *\n * UserDto.builder().name('Alice').email('a@b.com').build() // fully typed\n * ```\n */\nexport function withBuilder<C extends new (...args: any[]) => any>(\n ctor: C,\n): C & { builder(): BuilderOf<InstanceType<C>> } {\n attachBuilder(ctor)\n return ctor as C & { builder(): BuilderOf<InstanceType<C>> }\n}\n"],"mappings":";;;;;;;;;;+QAuBA,MAAM,qBAA8C,EAAE,CAGhD,iBAAmB,IAAI,IAC7B,IAAI,aAAoB,KAExB,SAAS,aAAa,UAAsB,CAC1C,aAAe,UACf,IAAK,GAAM,CAAE,OAAQ,SAAW,qBACzB,UAAU,IAAI,OAAO,EACxB,UAAU,SAAS,OAAQ,OAAQ,MAAM,CAG7C,qBAAqB,OAAS,EAIhC,UAAU,SAAW,aAKrB,UAAU,SAAY,WAAmB,CACvC,aAAe,UACf,IAAK,GAAM,EAAG,CAAE,OAAQ,UAAY,iBAC7B,UAAU,IAAI,OAAO,EACxB,UAAU,SAAS,OAAQ,OAAQ,MAAM,EAO/C,SAAS,oBAAoB,OAAa,MAAoB,CAC5D,aAAa,SAAS,WAAY,GAAM,OAAO,CAC/C,aAAa,SAAS,MAAO,MAAO,OAAO,CAI3C,IAAM,KAAO,OAAO,MAAQ,OAAO,OAAO,CAC1C,iBAAiB,IAAI,KAAM,CAAE,OAAQ,MAAO,CAAC,CAEzC,aAEG,aAAa,IAAI,OAAO,EAC3B,aAAa,SAAS,OAAQ,OAAQ,MAAM,CAI9C,qBAAqB,KAAK,CAAE,OAAQ,MAAO,CAAC,CAKhD,SAAgB,WAAW,QAA0C,CACnE,MAAQ,SAAgB,CACtB,aAAa,SAAS,WAAY,aAAc,OAAO,CACvD,oBAAoB,OAAQ,SAAS,OAAA,YAAyB,EAKlE,SAAgB,QAAQ,QAA0C,CAChE,MAAQ,SAAgB,CACtB,aAAa,SAAS,WAAY,UAAW,OAAO,CACpD,oBAAoB,OAAQ,SAAS,OAAA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
  */
11
- //#region src/core/errors.ts
12
- /**
13
- * Standard HTTP status codes as a const enum.
14
- * Use instead of raw numbers for readability and type safety.
15
- *
16
- * @example
17
- * ```ts
18
- * throw new HttpException(HttpStatus.NOT_FOUND, 'User not found')
19
- * ctx.res.status(HttpStatus.CREATED).json(data)
20
- * ```
21
- */
22
- const HttpStatus = {
23
- OK: 200,
24
- CREATED: 201,
25
- ACCEPTED: 202,
26
- NO_CONTENT: 204,
27
- MOVED_PERMANENTLY: 301,
28
- FOUND: 302,
29
- NOT_MODIFIED: 304,
30
- TEMPORARY_REDIRECT: 307,
31
- PERMANENT_REDIRECT: 308,
32
- BAD_REQUEST: 400,
33
- UNAUTHORIZED: 401,
34
- PAYMENT_REQUIRED: 402,
35
- FORBIDDEN: 403,
36
- NOT_FOUND: 404,
37
- METHOD_NOT_ALLOWED: 405,
38
- NOT_ACCEPTABLE: 406,
39
- CONFLICT: 409,
40
- GONE: 410,
41
- UNPROCESSABLE_ENTITY: 422,
42
- TOO_MANY_REQUESTS: 429,
43
- INTERNAL_SERVER_ERROR: 500,
44
- NOT_IMPLEMENTED: 501,
45
- BAD_GATEWAY: 502,
46
- SERVICE_UNAVAILABLE: 503,
47
- GATEWAY_TIMEOUT: 504
48
- };
49
- /**
50
- * Typed HTTP exception with status code, free-form details, and optional
51
- * response headers. Provides static factory methods for common HTTP errors.
52
- *
53
- * `details` is intentionally typed as `unknown` — it serializes straight into
54
- * the response body's `errors` field, so any JSON-compatible shape works
55
- * (string, object, array of mixed values, ValidationError[]).
56
- *
57
- * `headers` are merged into the response by the global error handler so
58
- * spec-mandated headers (Retry-After, WWW-Authenticate, Allow, Location)
59
- * stay on the exception, not on ad-hoc try/catch chains.
60
- */
61
- var HttpException = class HttpException extends Error {
62
- constructor(status, message, details, headers) {
63
- super(message);
64
- this.status = status;
65
- this.details = details;
66
- this.headers = headers;
67
- this.name = "HttpException";
68
- }
69
- /** Return a new exception with `headers` shallow-merged onto this one. */
70
- withHeaders(headers) {
71
- return new HttpException(this.status, this.message, this.details, {
72
- ...this.headers,
73
- ...headers
74
- });
75
- }
76
- /** Create from a Zod error */
77
- static fromZodError(error, message) {
78
- const firstIssue = error.issues?.[0];
79
- const details = (error.issues || []).map((issue) => ({
80
- field: issue.path?.join(".") || "",
81
- message: issue.message,
82
- code: issue.code
83
- }));
84
- return new HttpException(HttpStatus.UNPROCESSABLE_ENTITY, message || firstIssue?.message || "Validation failed", details);
85
- }
86
- static badRequest(message = "Bad Request") {
87
- return new HttpException(HttpStatus.BAD_REQUEST, message);
88
- }
89
- static unauthorized(message = "Unauthorized", wwwAuthenticate) {
90
- return new HttpException(HttpStatus.UNAUTHORIZED, message, void 0, wwwAuthenticate ? { "WWW-Authenticate": wwwAuthenticate } : void 0);
91
- }
92
- static forbidden(message = "Forbidden") {
93
- return new HttpException(HttpStatus.FORBIDDEN, message);
94
- }
95
- static notFound(message = "Not Found") {
96
- return new HttpException(HttpStatus.NOT_FOUND, message);
97
- }
98
- static methodNotAllowed(allowedMethods, message = "Method Not Allowed") {
99
- return new HttpException(HttpStatus.METHOD_NOT_ALLOWED, message, void 0, { Allow: allowedMethods.join(", ") });
100
- }
101
- static conflict(message = "Conflict") {
102
- return new HttpException(HttpStatus.CONFLICT, message);
103
- }
104
- static unprocessable(message = "Unprocessable Entity", details) {
105
- return new HttpException(HttpStatus.UNPROCESSABLE_ENTITY, message, details);
106
- }
107
- static tooManyRequests(message = "Too Many Requests", retryAfterSeconds) {
108
- return new HttpException(HttpStatus.TOO_MANY_REQUESTS, message, void 0, retryAfterSeconds !== void 0 ? { "Retry-After": String(retryAfterSeconds) } : void 0);
109
- }
110
- static serviceUnavailable(message = "Service Unavailable", retryAfterSeconds) {
111
- return new HttpException(HttpStatus.SERVICE_UNAVAILABLE, message, void 0, retryAfterSeconds !== void 0 ? { "Retry-After": String(retryAfterSeconds) } : void 0);
112
- }
113
- static internal(message = "Internal Server Error") {
114
- return new HttpException(HttpStatus.INTERNAL_SERVER_ERROR, message);
115
- }
116
- };
117
- //#endregion
118
- export { HttpException, HttpStatus };
119
-
11
+ const HttpStatus={OK:200,CREATED:201,ACCEPTED:202,NO_CONTENT:204,MOVED_PERMANENTLY:301,FOUND:302,NOT_MODIFIED:304,TEMPORARY_REDIRECT:307,PERMANENT_REDIRECT:308,BAD_REQUEST:400,UNAUTHORIZED:401,PAYMENT_REQUIRED:402,FORBIDDEN:403,NOT_FOUND:404,METHOD_NOT_ALLOWED:405,NOT_ACCEPTABLE:406,CONFLICT:409,GONE:410,UNPROCESSABLE_ENTITY:422,TOO_MANY_REQUESTS:429,INTERNAL_SERVER_ERROR:500,NOT_IMPLEMENTED:501,BAD_GATEWAY:502,SERVICE_UNAVAILABLE:503,GATEWAY_TIMEOUT:504};var HttpException=class HttpException extends Error{constructor(status,message,details,headers){super(message),this.status=status,this.details=details,this.headers=headers,this.name=`HttpException`}withHeaders(headers){return new HttpException(this.status,this.message,this.details,{...this.headers,...headers})}static fromZodError(error,message){let firstIssue=error.issues?.[0],details=(error.issues||[]).map(issue=>({field:issue.path?.join(`.`)||``,message:issue.message,code:issue.code}));return new HttpException(HttpStatus.UNPROCESSABLE_ENTITY,message||firstIssue?.message||`Validation failed`,details)}static badRequest(message=`Bad Request`){return new HttpException(HttpStatus.BAD_REQUEST,message)}static unauthorized(message=`Unauthorized`,wwwAuthenticate){return new HttpException(HttpStatus.UNAUTHORIZED,message,void 0,wwwAuthenticate?{"WWW-Authenticate":wwwAuthenticate}:void 0)}static forbidden(message=`Forbidden`){return new HttpException(HttpStatus.FORBIDDEN,message)}static notFound(message=`Not Found`){return new HttpException(HttpStatus.NOT_FOUND,message)}static methodNotAllowed(allowedMethods,message=`Method Not Allowed`){return new HttpException(HttpStatus.METHOD_NOT_ALLOWED,message,void 0,{Allow:allowedMethods.join(`, `)})}static conflict(message=`Conflict`){return new HttpException(HttpStatus.CONFLICT,message)}static unprocessable(message=`Unprocessable Entity`,details){return new HttpException(HttpStatus.UNPROCESSABLE_ENTITY,message,details)}static tooManyRequests(message=`Too Many Requests`,retryAfterSeconds){return new HttpException(HttpStatus.TOO_MANY_REQUESTS,message,void 0,retryAfterSeconds===void 0?void 0:{"Retry-After":String(retryAfterSeconds)})}static serviceUnavailable(message=`Service Unavailable`,retryAfterSeconds){return new HttpException(HttpStatus.SERVICE_UNAVAILABLE,message,void 0,retryAfterSeconds===void 0?void 0:{"Retry-After":String(retryAfterSeconds)})}static internal(message=`Internal Server Error`){return new HttpException(HttpStatus.INTERNAL_SERVER_ERROR,message)}};export{HttpException,HttpStatus};
120
12
  //# sourceMappingURL=errors.mjs.map
@@ -1 +1 @@
1
- {"version":3,"file":"errors.mjs","names":[],"sources":["../../src/core/errors.ts"],"sourcesContent":["/**\n * Standard HTTP status codes as a const enum.\n * Use instead of raw numbers for readability and type safety.\n *\n * @example\n * ```ts\n * throw new HttpException(HttpStatus.NOT_FOUND, 'User not found')\n * ctx.res.status(HttpStatus.CREATED).json(data)\n * ```\n */\nexport const HttpStatus = {\n // 2xx Success\n OK: 200,\n CREATED: 201,\n ACCEPTED: 202,\n NO_CONTENT: 204,\n\n // 3xx Redirection\n MOVED_PERMANENTLY: 301,\n FOUND: 302,\n NOT_MODIFIED: 304,\n TEMPORARY_REDIRECT: 307,\n PERMANENT_REDIRECT: 308,\n\n // 4xx Client Errors\n BAD_REQUEST: 400,\n UNAUTHORIZED: 401,\n PAYMENT_REQUIRED: 402,\n FORBIDDEN: 403,\n NOT_FOUND: 404,\n METHOD_NOT_ALLOWED: 405,\n NOT_ACCEPTABLE: 406,\n CONFLICT: 409,\n GONE: 410,\n UNPROCESSABLE_ENTITY: 422,\n TOO_MANY_REQUESTS: 429,\n\n // 5xx Server Errors\n INTERNAL_SERVER_ERROR: 500,\n NOT_IMPLEMENTED: 501,\n BAD_GATEWAY: 502,\n SERVICE_UNAVAILABLE: 503,\n GATEWAY_TIMEOUT: 504,\n} as const\n\nexport type HttpStatusCode = (typeof HttpStatus)[keyof typeof HttpStatus]\n\n/** Validation error detail — shape used by `unprocessable()` and `fromZodError()`. */\nexport interface ValidationError {\n field: string\n message: string\n code?: string\n}\n\n/**\n * Typed HTTP exception with status code, free-form details, and optional\n * response headers. Provides static factory methods for common HTTP errors.\n *\n * `details` is intentionally typed as `unknown` — it serializes straight into\n * the response body's `errors` field, so any JSON-compatible shape works\n * (string, object, array of mixed values, ValidationError[]).\n *\n * `headers` are merged into the response by the global error handler so\n * spec-mandated headers (Retry-After, WWW-Authenticate, Allow, Location)\n * stay on the exception, not on ad-hoc try/catch chains.\n */\nexport class HttpException extends Error {\n constructor(\n public readonly status: number,\n message: string,\n public readonly details?: unknown,\n public readonly headers?: Record<string, string>,\n ) {\n super(message)\n this.name = 'HttpException'\n }\n\n /** Return a new exception with `headers` shallow-merged onto this one. */\n withHeaders(headers: Record<string, string>): HttpException {\n return new HttpException(this.status, this.message, this.details, {\n ...this.headers,\n ...headers,\n })\n }\n\n /** Create from a Zod error */\n static fromZodError(error: any, message?: string): HttpException {\n const firstIssue = error.issues?.[0]\n const details: ValidationError[] = (error.issues || []).map((issue: any) => ({\n field: issue.path?.join('.') || '',\n message: issue.message,\n code: issue.code,\n }))\n return new HttpException(\n HttpStatus.UNPROCESSABLE_ENTITY,\n message || firstIssue?.message || 'Validation failed',\n details,\n )\n }\n\n static badRequest(message = 'Bad Request') {\n return new HttpException(HttpStatus.BAD_REQUEST, message)\n }\n static unauthorized(message = 'Unauthorized', wwwAuthenticate?: string) {\n return new HttpException(\n HttpStatus.UNAUTHORIZED,\n message,\n undefined,\n wwwAuthenticate ? { 'WWW-Authenticate': wwwAuthenticate } : undefined,\n )\n }\n static forbidden(message = 'Forbidden') {\n return new HttpException(HttpStatus.FORBIDDEN, message)\n }\n static notFound(message = 'Not Found') {\n return new HttpException(HttpStatus.NOT_FOUND, message)\n }\n static methodNotAllowed(allowedMethods: string[], message = 'Method Not Allowed') {\n return new HttpException(HttpStatus.METHOD_NOT_ALLOWED, message, undefined, {\n Allow: allowedMethods.join(', '),\n })\n }\n static conflict(message = 'Conflict') {\n return new HttpException(HttpStatus.CONFLICT, message)\n }\n static unprocessable(message = 'Unprocessable Entity', details?: ValidationError[]) {\n return new HttpException(HttpStatus.UNPROCESSABLE_ENTITY, message, details)\n }\n static tooManyRequests(message = 'Too Many Requests', retryAfterSeconds?: number) {\n return new HttpException(\n HttpStatus.TOO_MANY_REQUESTS,\n message,\n undefined,\n retryAfterSeconds !== undefined ? { 'Retry-After': String(retryAfterSeconds) } : undefined,\n )\n }\n static serviceUnavailable(message = 'Service Unavailable', retryAfterSeconds?: number) {\n return new HttpException(\n HttpStatus.SERVICE_UNAVAILABLE,\n message,\n undefined,\n retryAfterSeconds !== undefined ? { 'Retry-After': String(retryAfterSeconds) } : undefined,\n )\n }\n static internal(message = 'Internal Server Error') {\n return new HttpException(HttpStatus.INTERNAL_SERVER_ERROR, message)\n }\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;AAUA,MAAa,aAAa;CAExB,IAAI;CACJ,SAAS;CACT,UAAU;CACV,YAAY;CAGZ,mBAAmB;CACnB,OAAO;CACP,cAAc;CACd,oBAAoB;CACpB,oBAAoB;CAGpB,aAAa;CACb,cAAc;CACd,kBAAkB;CAClB,WAAW;CACX,WAAW;CACX,oBAAoB;CACpB,gBAAgB;CAChB,UAAU;CACV,MAAM;CACN,sBAAsB;CACtB,mBAAmB;CAGnB,uBAAuB;CACvB,iBAAiB;CACjB,aAAa;CACb,qBAAqB;CACrB,iBAAiB;CAClB;;;;;;;;;;;;;AAuBD,IAAa,gBAAb,MAAa,sBAAsB,MAAM;CACvC,YACE,QACA,SACA,SACA,SACA;AACA,QAAM,QAAQ;AALE,OAAA,SAAA;AAEA,OAAA,UAAA;AACA,OAAA,UAAA;AAGhB,OAAK,OAAO;;;CAId,YAAY,SAAgD;AAC1D,SAAO,IAAI,cAAc,KAAK,QAAQ,KAAK,SAAS,KAAK,SAAS;GAChE,GAAG,KAAK;GACR,GAAG;GACJ,CAAC;;;CAIJ,OAAO,aAAa,O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AO,kBAAkB,EAAE,GAAG,KAAA,EAClF;;CAEH,OAAO,SAAS,UAAU,yBAAyB;AACjD,SAAO,IAAI,cAAc,WAAW,uBAAuB,QAAQ"}
1
+ {"version":3,"file":"errors.mjs","names":[],"sources":["../../src/core/errors.ts"],"sourcesContent":["/**\n * Standard HTTP status codes as a const enum.\n * Use instead of raw numbers for readability and type safety.\n *\n * @example\n * ```ts\n * throw new HttpException(HttpStatus.NOT_FOUND, 'User not found')\n * ctx.res.status(HttpStatus.CREATED).json(data)\n * ```\n */\nexport const HttpStatus = {\n // 2xx Success\n OK: 200,\n CREATED: 201,\n ACCEPTED: 202,\n NO_CONTENT: 204,\n\n // 3xx Redirection\n MOVED_PERMANENTLY: 301,\n FOUND: 302,\n NOT_MODIFIED: 304,\n TEMPORARY_REDIRECT: 307,\n PERMANENT_REDIRECT: 308,\n\n // 4xx Client Errors\n BAD_REQUEST: 400,\n UNAUTHORIZED: 401,\n PAYMENT_REQUIRED: 402,\n FORBIDDEN: 403,\n NOT_FOUND: 404,\n METHOD_NOT_ALLOWED: 405,\n NOT_ACCEPTABLE: 406,\n CONFLICT: 409,\n GONE: 410,\n UNPROCESSABLE_ENTITY: 422,\n TOO_MANY_REQUESTS: 429,\n\n // 5xx Server Errors\n INTERNAL_SERVER_ERROR: 500,\n NOT_IMPLEMENTED: 501,\n BAD_GATEWAY: 502,\n SERVICE_UNAVAILABLE: 503,\n GATEWAY_TIMEOUT: 504,\n} as const\n\nexport type HttpStatusCode = (typeof HttpStatus)[keyof typeof HttpStatus]\n\n/** Validation error detail — shape used by `unprocessable()` and `fromZodError()`. */\nexport interface ValidationError {\n field: string\n message: string\n code?: string\n}\n\n/**\n * Typed HTTP exception with status code, free-form details, and optional\n * response headers. Provides static factory methods for common HTTP errors.\n *\n * `details` is intentionally typed as `unknown` — it serializes straight into\n * the response body's `errors` field, so any JSON-compatible shape works\n * (string, object, array of mixed values, ValidationError[]).\n *\n * `headers` are merged into the response by the global error handler so\n * spec-mandated headers (Retry-After, WWW-Authenticate, Allow, Location)\n * stay on the exception, not on ad-hoc try/catch chains.\n */\nexport class HttpException extends Error {\n constructor(\n public readonly status: number,\n message: string,\n public readonly details?: unknown,\n public readonly headers?: Record<string, string>,\n ) {\n super(message)\n this.name = 'HttpException'\n }\n\n /** Return a new exception with `headers` shallow-merged onto this one. */\n withHeaders(headers: Record<string, string>): HttpException {\n return new HttpException(this.status, this.message, this.details, {\n ...this.headers,\n ...headers,\n })\n }\n\n /** Create from a Zod error */\n static fromZodError(error: any, message?: string): HttpException {\n const firstIssue = error.issues?.[0]\n const details: ValidationError[] = (error.issues || []).map((issue: any) => ({\n field: issue.path?.join('.') || '',\n message: issue.message,\n code: issue.code,\n }))\n return new HttpException(\n HttpStatus.UNPROCESSABLE_ENTITY,\n message || firstIssue?.message || 'Validation failed',\n details,\n )\n }\n\n static badRequest(message = 'Bad Request') {\n return new HttpException(HttpStatus.BAD_REQUEST, message)\n }\n static unauthorized(message = 'Unauthorized', wwwAuthenticate?: string) {\n return new HttpException(\n HttpStatus.UNAUTHORIZED,\n message,\n undefined,\n wwwAuthenticate ? { 'WWW-Authenticate': wwwAuthenticate } : undefined,\n )\n }\n static forbidden(message = 'Forbidden') {\n return new HttpException(HttpStatus.FORBIDDEN, message)\n }\n static notFound(message = 'Not Found') {\n return new HttpException(HttpStatus.NOT_FOUND, message)\n }\n static methodNotAllowed(allowedMethods: string[], message = 'Method Not Allowed') {\n return new HttpException(HttpStatus.METHOD_NOT_ALLOWED, message, undefined, {\n Allow: allowedMethods.join(', '),\n })\n }\n static conflict(message = 'Conflict') {\n return new HttpException(HttpStatus.CONFLICT, message)\n }\n static unprocessable(message = 'Unprocessable Entity', details?: ValidationError[]) {\n return new HttpException(HttpStatus.UNPROCESSABLE_ENTITY, message, details)\n }\n static tooManyRequests(message = 'Too Many Requests', retryAfterSeconds?: number) {\n return new HttpException(\n HttpStatus.TOO_MANY_REQUESTS,\n message,\n undefined,\n retryAfterSeconds !== undefined ? { 'Retry-After': String(retryAfterSeconds) } : undefined,\n )\n }\n static serviceUnavailable(message = 'Service Unavailable', retryAfterSeconds?: number) {\n return new HttpException(\n HttpStatus.SERVICE_UNAVAILABLE,\n message,\n undefined,\n retryAfterSeconds !== undefined ? { 'Retry-After': String(retryAfterSeconds) } : undefined,\n )\n }\n static internal(message = 'Internal Server Error') {\n return new HttpException(HttpStatus.INTERNAL_SERVER_ERROR, message)\n }\n}\n"],"mappings":";;;;;;;;;;AAUA,MAAa,WAAa,CAExB,GAAI,IACJ,QAAS,IACT,SAAU,IACV,WAAY,IAGZ,kBAAmB,IACnB,MAAO,IACP,aAAc,IACd,mBAAoB,IACpB,mBAAoB,IAGpB,YAAa,IACb,aAAc,IACd,iBAAkB,IAClB,UAAW,IACX,UAAW,IACX,mBAAoB,IACpB,eAAgB,IAChB,SAAU,IACV,KAAM,IACN,qBAAsB,IACtB,kBAAmB,IAGnB,sBAAuB,IACvB,gBAAiB,IACjB,YAAa,IACb,oBAAqB,IACrB,gBAAiB,IAClB,CAuBD,IAAa,cAAb,MAAa,sBAAsB,KAAM,CACvC,YACE,OACA,QACA,QACA,QACA,CACA,MAAM,QAAQ,CALE,KAAA,OAAA,OAEA,KAAA,QAAA,QACA,KAAA,QAAA,QAGhB,KAAK,KAAO,gBAId,YAAY,QAAgD,CAC1D,OAAO,IAAI,cAAc,KAAK,OAAQ,KAAK,QAAS,KAAK,QAAS,CAChE,GAAG,KAAK,QACR,GAAG,QACJ,CAAC,CAIJ,OAAO,aAAa,MAAY,QAAiC,CAC/D,IAAM,WAAa,MAAM,SAAS,GAC5B,SAA8B,MAAM,QAAU,EAAE,EAAE,IAAK,QAAgB,CAC3E,MAAO,MAAM,MAAM,KAAK,IAAI,EAAI,GAChC,QAAS,MAAM,QACf,KAAM,MAAM,KACb,EAAE,CACH,OAAO,IAAI,cACT,WAAW,qBACX,SAAW,YAAY,SAAW,oBAClC,QACD,CAGH,OAAO,WAAW,QAAU,cAAe,CACzC,OAAO,IAAI,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- //#region src/core/interfaces.ts
13
- /** Lifecycle scope for DI registrations */
14
- let Scope = /* @__PURE__ */ function(Scope) {
15
- Scope["SINGLETON"] = "singleton";
16
- Scope["TRANSIENT"] = "transient";
17
- /** One instance per HTTP request, cached in AsyncLocalStorage. Throws outside request context. */
18
- Scope["REQUEST"] = "request";
19
- return Scope;
20
- }({});
21
- /**
22
- * String metadata keys for the DI system + decorator subsystem. Every
23
- * key starts with the `kick:` prefix; the suffix is a short identifier
24
- * that may itself contain `:`, `-`, or `_` separators (historical —
25
- * keys grew alongside the framework). The §22 v4 convention is "no
26
- * Symbols", not "use a strict naming scheme" — Symbols don't survive
27
- * JSON serialisation, can't be addressed by string from worker
28
- * threads, and don't show up in DevTools snapshots.
29
- *
30
- * `reflect-metadata` accepts both Symbol and string keys identically,
31
- * so the consumer-side change is internal — references go through the
32
- * `METADATA` enum's named members (e.g. `METADATA.INJECT`), not the
33
- * underlying string.
34
- *
35
- * The `design:*` entries match what TypeScript's
36
- * `emitDecoratorMetadata` writes; those names are fixed by the
37
- * compiler + must stay as-is.
38
- */
39
- const METADATA = {
40
- INJECTABLE: "kick:injectable",
41
- SCOPE: "kick:scope",
42
- CLASS_KIND: "kick:class-kind",
43
- AUTOWIRED: "kick:autowired",
44
- INJECT: "kick:inject",
45
- POST_CONSTRUCT: "kick:post_construct",
46
- BUILDER: "kick:builder",
47
- QUERY_PARAMS: "kick:query:params",
48
- ROUTES: "kick:routes",
49
- CLASS_MIDDLEWARES: "kick:class:middlewares",
50
- METHOD_MIDDLEWARES: "kick:method:middlewares",
51
- CLASS_CONTRIBUTORS: "kick:class:contributors",
52
- METHOD_CONTRIBUTORS: "kick:method:contributors",
53
- FILE_UPLOAD: "kick:file:upload",
54
- VALUE: "kick:value",
55
- ASSET: "kick:asset",
56
- PARAM_TYPES: "design:paramtypes",
57
- PROPERTY_TYPE: "design:type",
58
- RETURN_TYPE: "design:returntype"
59
- };
60
- //#endregion
61
- export { METADATA, Scope };
62
-
11
+ import"reflect-metadata";let Scope=function(Scope){return Scope.SINGLETON=`singleton`,Scope.TRANSIENT=`transient`,Scope.REQUEST=`request`,Scope}({});const METADATA={INJECTABLE:`kick:injectable`,SCOPE:`kick:scope`,CLASS_KIND:`kick:class-kind`,AUTOWIRED:`kick:autowired`,INJECT:`kick:inject`,POST_CONSTRUCT:`kick:post_construct`,BUILDER:`kick:builder`,QUERY_PARAMS:`kick:query:params`,ROUTES:`kick:routes`,CLASS_MIDDLEWARES:`kick:class:middlewares`,METHOD_MIDDLEWARES:`kick:method:middlewares`,CLASS_CONTRIBUTORS:`kick:class:contributors`,METHOD_CONTRIBUTORS:`kick:method:contributors`,FILE_UPLOAD:`kick:file:upload`,VALUE:`kick:value`,ASSET:`kick:asset`,PARAM_TYPES:`design:paramtypes`,PROPERTY_TYPE:`design:type`,RETURN_TYPE:`design:returntype`};export{METADATA,Scope};
63
12
  //# sourceMappingURL=interfaces.mjs.map
@@ -1 +1 @@
1
- {"version":3,"file":"interfaces.mjs","names":[],"sources":["../../src/core/interfaces.ts"],"sourcesContent":["import 'reflect-metadata'\n\n/** Lifecycle scope for DI registrations */\nexport enum Scope {\n SINGLETON = 'singleton',\n TRANSIENT = 'transient',\n /** One instance per HTTP request, cached in AsyncLocalStorage. Throws outside request context. */\n REQUEST = 'request',\n}\n\n/** Generic constructor type */\nexport type Constructor<T = any> = new (...args: any[]) => T\n\n/** A value that may or may not be wrapped in a Promise */\nexport type MaybePromise<T = void> = T | Promise<T>\n\n/** Options for @Service, @Repository, @Component decorators */\nexport interface ServiceOptions {\n scope?: Scope\n}\n\n/** Fluent builder type */\nexport type BuilderOf<T> = {\n [K in keyof T as T[K] extends Function ? never : K]-?: (value: T[K]) => BuilderOf<T>\n} & { build(): T }\n\n/** Class with static builder() method */\nexport interface Buildable<T> {\n builder(): BuilderOf<T>\n}\n\n/** Decorator class kind for devtools introspection */\nexport type ClassKind =\n | 'service'\n | 'controller'\n | 'repository'\n | 'component'\n | 'injectable'\n | 'factory'\n | 'instance'\n | 'unknown'\n\n/** PostConstruct lifecycle status */\nexport type PostConstructStatus = 'pending' | 'completed' | 'failed' | 'skipped'\n\n/**\n * String metadata keys for the DI system + decorator subsystem. Every\n * key starts with the `kick:` prefix; the suffix is a short identifier\n * that may itself contain `:`, `-`, or `_` separators (historical —\n * keys grew alongside the framework). The §22 v4 convention is \"no\n * Symbols\", not \"use a strict naming scheme\" — Symbols don't survive\n * JSON serialisation, can't be addressed by string from worker\n * threads, and don't show up in DevTools snapshots.\n *\n * `reflect-metadata` accepts both Symbol and string keys identically,\n * so the consumer-side change is internal — references go through the\n * `METADATA` enum's named members (e.g. `METADATA.INJECT`), not the\n * underlying string.\n *\n * The `design:*` entries match what TypeScript's\n * `emitDecoratorMetadata` writes; those names are fixed by the\n * compiler + must stay as-is.\n */\nexport const METADATA = {\n INJECTABLE: 'kick:injectable',\n SCOPE: 'kick:scope',\n CLASS_KIND: 'kick:class-kind',\n AUTOWIRED: 'kick:autowired',\n INJECT: 'kick:inject',\n POST_CONSTRUCT: 'kick:post_construct',\n BUILDER: 'kick:builder',\n QUERY_PARAMS: 'kick:query:params',\n ROUTES: 'kick:routes',\n CLASS_MIDDLEWARES: 'kick:class:middlewares',\n METHOD_MIDDLEWARES: 'kick:method:middlewares',\n CLASS_CONTRIBUTORS: 'kick:class:contributors',\n METHOD_CONTRIBUTORS: 'kick:method:contributors',\n FILE_UPLOAD: 'kick:file:upload',\n VALUE: 'kick:value',\n ASSET: 'kick:asset',\n // TypeScript emit metadata keys — fixed by the compiler.\n PARAM_TYPES: 'design:paramtypes',\n PROPERTY_TYPE: 'design:type',\n RETURN_TYPE: 'design:returntype',\n} as const\n"],"mappings":";;;;;;;;;;;;;AAGA,IAAY,QAAL,yBAAA,OAAA;AACL,OAAA,eAAA;AACA,OAAA,eAAA;;AAEA,OAAA,aAAA;;KACD;;;;;;;;;;;;;;;;;;;AAuDD,MAAa,WAAW;CACtB,YAAY;CACZ,OAAO;CACP,YAAY;CACZ,WAAW;CACX,QAAQ;CACR,gBAAgB;CAChB,SAAS;CACT,cAAc;CACd,QAAQ;CACR,mBAAmB;CACnB,oBAAoB;CACpB,oBAAoB;CACpB,qBAAqB;CACrB,aAAa;CACb,OAAO;CACP,OAAO;CAEP,aAAa;CACb,eAAe;CACf,aAAa;CACd"}
1
+ {"version":3,"file":"interfaces.mjs","names":[],"sources":["../../src/core/interfaces.ts"],"sourcesContent":["import 'reflect-metadata'\n\n/** Lifecycle scope for DI registrations */\nexport enum Scope {\n SINGLETON = 'singleton',\n TRANSIENT = 'transient',\n /** One instance per HTTP request, cached in AsyncLocalStorage. Throws outside request context. */\n REQUEST = 'request',\n}\n\n/** Generic constructor type */\nexport type Constructor<T = any> = new (...args: any[]) => T\n\n/** A value that may or may not be wrapped in a Promise */\nexport type MaybePromise<T = void> = T | Promise<T>\n\n/** Options for @Service, @Repository, @Component decorators */\nexport interface ServiceOptions {\n scope?: Scope\n}\n\n/** Fluent builder type */\nexport type BuilderOf<T> = {\n [K in keyof T as T[K] extends Function ? never : K]-?: (value: T[K]) => BuilderOf<T>\n} & { build(): T }\n\n/** Class with static builder() method */\nexport interface Buildable<T> {\n builder(): BuilderOf<T>\n}\n\n/** Decorator class kind for devtools introspection */\nexport type ClassKind =\n | 'service'\n | 'controller'\n | 'repository'\n | 'component'\n | 'injectable'\n | 'factory'\n | 'instance'\n | 'unknown'\n\n/** PostConstruct lifecycle status */\nexport type PostConstructStatus = 'pending' | 'completed' | 'failed' | 'skipped'\n\n/**\n * String metadata keys for the DI system + decorator subsystem. Every\n * key starts with the `kick:` prefix; the suffix is a short identifier\n * that may itself contain `:`, `-`, or `_` separators (historical —\n * keys grew alongside the framework). The §22 v4 convention is \"no\n * Symbols\", not \"use a strict naming scheme\" — Symbols don't survive\n * JSON serialisation, can't be addressed by string from worker\n * threads, and don't show up in DevTools snapshots.\n *\n * `reflect-metadata` accepts both Symbol and string keys identically,\n * so the consumer-side change is internal — references go through the\n * `METADATA` enum's named members (e.g. `METADATA.INJECT`), not the\n * underlying string.\n *\n * The `design:*` entries match what TypeScript's\n * `emitDecoratorMetadata` writes; those names are fixed by the\n * compiler + must stay as-is.\n */\nexport const METADATA = {\n INJECTABLE: 'kick:injectable',\n SCOPE: 'kick:scope',\n CLASS_KIND: 'kick:class-kind',\n AUTOWIRED: 'kick:autowired',\n INJECT: 'kick:inject',\n POST_CONSTRUCT: 'kick:post_construct',\n BUILDER: 'kick:builder',\n QUERY_PARAMS: 'kick:query:params',\n ROUTES: 'kick:routes',\n CLASS_MIDDLEWARES: 'kick:class:middlewares',\n METHOD_MIDDLEWARES: 'kick:method:middlewares',\n CLASS_CONTRIBUTORS: 'kick:class:contributors',\n METHOD_CONTRIBUTORS: 'kick:method:contributors',\n FILE_UPLOAD: 'kick:file:upload',\n VALUE: 'kick:value',\n ASSET: 'kick:asset',\n // TypeScript emit metadata keys — fixed by the compiler.\n PARAM_TYPES: 'design:paramtypes',\n PROPERTY_TYPE: 'design:type',\n RETURN_TYPE: 'design:returntype',\n} as const\n"],"mappings":";;;;;;;;;;yBAGA,IAAY,MAAL,SAAA,MAAA,OACL,OAAA,UAAA,YACA,MAAA,UAAA,YAEA,MAAA,QAAA,oBACD,CAuDD,MAAa,SAAW,CACtB,WAAY,kBACZ,MAAO,aACP,WAAY,kBACZ,UAAW,iBACX,OAAQ,cACR,eAAgB,sBAChB,QAAS,eACT,aAAc,oBACd,OAAQ,cACR,kBAAmB,yBACnB,mBAAoB,0BACpB,mBAAoB,0BACpB,oBAAqB,2BACrB,YAAa,mBACb,MAAO,aACP,MAAO,aAEP,YAAa,oBACb,cAAe,cACf,YAAa,oBACd"}
@@ -1,5 +1,5 @@
1
1
  /**
2
- * @forinda/kickjs v5.3.0
2
+ * @forinda/kickjs v5.5.0
3
3
  *
4
4
  * Copyright (c) Felix Orinda
5
5
  *
@@ -8,210 +8,5 @@
8
8
  *
9
9
  * @license MIT
10
10
  */
11
- import pino from "pino";
12
- //#region src/core/logger.ts
13
- const isDev = process.env.NODE_ENV !== "production";
14
- /** Root pino logger instance */
15
- const rootLogger = pino({
16
- level: process.env.LOG_LEVEL || "info",
17
- ...isDev ? { transport: {
18
- target: "pino-pretty",
19
- options: {
20
- colorize: true,
21
- translateTime: "SYS:HH:MM:ss.l",
22
- singleLine: true,
23
- ignore: "pid,hostname,component",
24
- messageFormat: "{if component}[{component}] {end}{msg}"
25
- }
26
- } } : {}
27
- });
28
- /** Default provider that delegates to the root pino instance */
29
- var PinoLoggerProvider = class PinoLoggerProvider {
30
- log;
31
- constructor(pinoInstance) {
32
- this.log = pinoInstance ?? rootLogger;
33
- }
34
- info(msg, ...args) {
35
- this.log.info(msg, ...args);
36
- }
37
- warn(msg, ...args) {
38
- this.log.warn(msg, ...args);
39
- }
40
- error(msg, ...args) {
41
- this.log.error(msg, ...args);
42
- }
43
- debug(msg, ...args) {
44
- this.log.debug(msg, ...args);
45
- }
46
- trace(msg, ...args) {
47
- this.log.trace(msg, ...args);
48
- }
49
- fatal(msg, ...args) {
50
- this.log.fatal(msg, ...args);
51
- }
52
- child(bindings) {
53
- return new PinoLoggerProvider(this.log.child(bindings));
54
- }
55
- };
56
- /**
57
- * Built-in fallback provider that uses `console.*` methods.
58
- * Useful for environments where pino is unavailable or undesired.
59
- */
60
- var ConsoleLoggerProvider = class ConsoleLoggerProvider {
61
- prefix;
62
- constructor(prefix) {
63
- this.prefix = prefix ?? "";
64
- }
65
- fmt(msg) {
66
- return this.prefix ? `[${this.prefix}] ${msg}` : msg;
67
- }
68
- info(msg, ...args) {
69
- console.log(this.fmt(msg), ...args);
70
- }
71
- warn(msg, ...args) {
72
- console.warn(this.fmt(msg), ...args);
73
- }
74
- error(msg, ...args) {
75
- console.error(this.fmt(msg), ...args);
76
- }
77
- debug(msg, ...args) {
78
- console.debug(this.fmt(msg), ...args);
79
- }
80
- trace(msg, ...args) {
81
- console.trace(this.fmt(msg), ...args);
82
- }
83
- fatal(msg, ...args) {
84
- console.error(this.fmt(msg), ...args);
85
- }
86
- child(bindings) {
87
- return new ConsoleLoggerProvider(bindings.component);
88
- }
89
- };
90
- let activeProvider = new PinoLoggerProvider();
91
- /** Cache of named loggers to avoid creating duplicates */
92
- const loggerCache = /* @__PURE__ */ new Map();
93
- /**
94
- * Named logger with component context.
95
- *
96
- * @example
97
- * ```ts
98
- * // Static factory — preferred
99
- * const log = Logger.for('UserService')
100
- * log.info('User created')
101
- * // Output: [UserService] User created
102
- *
103
- * // Shorthand function
104
- * const log = createLogger('OrderService')
105
- *
106
- * // Pluggable backend
107
- * Logger.setProvider(new ConsoleLoggerProvider())
108
- *
109
- * // Injectable — auto-named from class
110
- * class MyService {
111
- * @Autowired() private logger!: Logger
112
- * // or inject a named one:
113
- * private log = Logger.for('MyService')
114
- * }
115
- * ```
116
- */
117
- var Logger = class Logger {
118
- _provider;
119
- _providerVersion;
120
- _name;
121
- /**
122
- * Optional context provider for request-scoped log enrichment.
123
- * Set by the HTTP package to inject requestId from AsyncLocalStorage.
124
- * Returns extra fields to merge into every log call, or null if outside a request.
125
- */
126
- static _contextProvider = null;
127
- /** Incremented on every setProvider/resetProvider so instances know to refresh */
128
- static _providerVersion = 0;
129
- constructor(name) {
130
- this._name = name;
131
- this._providerVersion = Logger._providerVersion;
132
- this._provider = name ? activeProvider.child({ component: name }) : activeProvider;
133
- }
134
- /** Re-derive the provider if setProvider() was called since construction/last access */
135
- get provider() {
136
- if (this._providerVersion !== Logger._providerVersion) {
137
- this._providerVersion = Logger._providerVersion;
138
- this._provider = this._name ? activeProvider.child({ component: this._name }) : activeProvider;
139
- }
140
- return this._provider;
141
- }
142
- /**
143
- * Replace the logging backend for **all** Logger instances created after
144
- * this call. Clears the logger cache so subsequent `Logger.for()` calls
145
- * pick up the new provider.
146
- *
147
- * @example
148
- * ```ts
149
- * Logger.setProvider(new ConsoleLoggerProvider())
150
- * ```
151
- */
152
- static setProvider(provider) {
153
- activeProvider = provider;
154
- Logger._providerVersion++;
155
- loggerCache.clear();
156
- }
157
- /** Return the currently active provider (useful for testing) */
158
- static getProvider() {
159
- return activeProvider;
160
- }
161
- /**
162
- * Reset the provider back to the default pino-based implementation.
163
- * Primarily intended for test teardown.
164
- */
165
- static resetProvider() {
166
- activeProvider = new PinoLoggerProvider();
167
- Logger._providerVersion++;
168
- loggerCache.clear();
169
- }
170
- /** Create or retrieve a cached named logger */
171
- static for(name) {
172
- let cached = loggerCache.get(name);
173
- if (!cached) {
174
- cached = new Logger(name);
175
- loggerCache.set(name, cached);
176
- }
177
- return cached;
178
- }
179
- /** Create a child logger with a sub-component name */
180
- child(name) {
181
- return new Logger(name);
182
- }
183
- /** Get request context (requestId, etc.) if inside a request */
184
- ctx() {
185
- return Logger._contextProvider?.() ?? void 0;
186
- }
187
- info(msg, ...args) {
188
- this.provider.info(msg, ...args);
189
- }
190
- warn(msg, ...args) {
191
- this.provider.warn(msg, ...args);
192
- }
193
- error(msgOrObj, msg, ...args) {
194
- if (typeof msgOrObj === "string") this.provider.error(msgOrObj);
195
- else if (msg) this.provider.error(msg, ...args);
196
- else this.provider.error(String(msgOrObj));
197
- }
198
- debug(msg, ...args) {
199
- this.provider.debug(msg, ...args);
200
- }
201
- trace(msg, ...args) {
202
- if (this.provider.trace) this.provider.trace(msg, ...args);
203
- else this.provider.debug(msg, ...args);
204
- }
205
- fatal(msg, ...args) {
206
- if (this.provider.fatal) this.provider.fatal(msg, ...args);
207
- else this.provider.error(msg, ...args);
208
- }
209
- };
210
- /** Shorthand for Logger.for(name) */
211
- function createLogger(name) {
212
- return Logger.for(name);
213
- }
214
- //#endregion
215
- export { ConsoleLoggerProvider, Logger, createLogger, rootLogger };
216
-
11
+ import pino from"pino";const isDev=process.env.NODE_ENV!==`production`,rootLogger=pino({level:process.env.LOG_LEVEL||`info`,...isDev?{transport:{target:`pino-pretty`,options:{colorize:!0,translateTime:`SYS:HH:MM:ss.l`,singleLine:!0,ignore:`pid,hostname,component`,messageFormat:`{if component}[{component}] {end}{msg}`}}}:{}});var PinoLoggerProvider=class PinoLoggerProvider{log;constructor(pinoInstance){this.log=pinoInstance??rootLogger}info(msg,...args){this.log.info(msg,...args)}warn(msg,...args){this.log.warn(msg,...args)}error(msg,...args){this.log.error(msg,...args)}debug(msg,...args){this.log.debug(msg,...args)}trace(msg,...args){this.log.trace(msg,...args)}fatal(msg,...args){this.log.fatal(msg,...args)}child(bindings){return new PinoLoggerProvider(this.log.child(bindings))}},ConsoleLoggerProvider=class ConsoleLoggerProvider{prefix;constructor(prefix){this.prefix=prefix??``}fmt(msg){return this.prefix?`[${this.prefix}] ${msg}`:msg}info(msg,...args){console.log(this.fmt(msg),...args)}warn(msg,...args){console.warn(this.fmt(msg),...args)}error(msg,...args){console.error(this.fmt(msg),...args)}debug(msg,...args){console.debug(this.fmt(msg),...args)}trace(msg,...args){console.trace(this.fmt(msg),...args)}fatal(msg,...args){console.error(this.fmt(msg),...args)}child(bindings){return new ConsoleLoggerProvider(bindings.component)}};let activeProvider=new PinoLoggerProvider;const loggerCache=new Map;var Logger=class Logger{_provider;_providerVersion;_name;static _contextProvider=null;static _providerVersion=0;constructor(name){this._name=name,this._providerVersion=Logger._providerVersion,this._provider=name?activeProvider.child({component:name}):activeProvider}get provider(){return this._providerVersion!==Logger._providerVersion&&(this._providerVersion=Logger._providerVersion,this._provider=this._name?activeProvider.child({component:this._name}):activeProvider),this._provider}static setProvider(provider){activeProvider=provider,Logger._providerVersion++,loggerCache.clear()}static getProvider(){return activeProvider}static resetProvider(){activeProvider=new PinoLoggerProvider,Logger._providerVersion++,loggerCache.clear()}static for(name){let cached=loggerCache.get(name);return cached||(cached=new Logger(name),loggerCache.set(name,cached)),cached}child(name){return new Logger(name)}ctx(){return Logger._contextProvider?.()??void 0}info(msg,...args){this.provider.info(msg,...args)}warn(msg,...args){this.provider.warn(msg,...args)}error(msgOrObj,msg,...args){typeof msgOrObj==`string`?this.provider.error(msgOrObj):msg?this.provider.error(msg,...args):this.provider.error(String(msgOrObj))}debug(msg,...args){this.provider.debug(msg,...args)}trace(msg,...args){this.provider.trace?this.provider.trace(msg,...args):this.provider.debug(msg,...args)}fatal(msg,...args){this.provider.fatal?this.provider.fatal(msg,...args):this.provider.error(msg,...args)}};function createLogger(name){return Logger.for(name)}export{ConsoleLoggerProvider,Logger,createLogger,rootLogger};
217
12
  //# sourceMappingURL=logger.mjs.map