@forinda/kickjs 5.2.0 → 5.4.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.
- package/dist/application-mir5CSWO.mjs +12 -0
- package/dist/{application-Bw87drVl.mjs.map → application-mir5CSWO.mjs.map} +1 -1
- package/dist/bootstrap-B7j_-dOg.mjs +12 -0
- package/dist/{bootstrap-CsQ7LE-W.mjs.map → bootstrap-B7j_-dOg.mjs.map} +1 -1
- package/dist/config/index.d.mts +1 -1
- package/dist/config/index.mjs +2 -4
- package/dist/config-Dk5RVTnD.mjs +12 -0
- package/dist/{config-DKRN5fqC.mjs.map → config-Dk5RVTnD.mjs.map} +1 -1
- package/dist/container-DArhTDQQ.mjs +12 -0
- package/dist/{container-C0FlgLNH.mjs.map → container-DArhTDQQ.mjs.map} +1 -1
- package/dist/{context-Ymvv-85x.d.mts → context-BAdAV-zO.d.mts} +48 -11
- package/dist/context-BAdAV-zO.d.mts.map +1 -0
- package/dist/context-CIoXqpAX.mjs +12 -0
- package/dist/context-CIoXqpAX.mjs.map +1 -0
- package/dist/core/adapter.mjs +2 -2
- package/dist/core/app-module.mjs +2 -2
- package/dist/core/cache.mjs +2 -103
- package/dist/core/cache.mjs.map +1 -1
- package/dist/core/container.mjs +2 -3
- package/dist/core/cron.mjs +2 -32
- package/dist/core/cron.mjs.map +1 -1
- package/dist/core/decorators.d.mts +2 -2
- package/dist/core/decorators.mjs +2 -241
- package/dist/core/decorators.mjs.map +1 -1
- package/dist/core/errors.mjs +2 -110
- package/dist/core/errors.mjs.map +1 -1
- package/dist/core/interfaces.mjs +2 -53
- package/dist/core/interfaces.mjs.map +1 -1
- package/dist/core/logger.mjs +2 -207
- package/dist/core/logger.mjs.map +1 -1
- package/dist/core/path.mjs +2 -35
- package/dist/core/path.mjs.map +1 -1
- package/dist/core/plugin.mjs +2 -2
- package/dist/core/reactivity.mjs +2 -179
- package/dist/core/reactivity.mjs.map +1 -1
- package/dist/core-BQZyB8Wv.mjs +12 -0
- package/dist/{core-K0J8AH_4.mjs.map → core-BQZyB8Wv.mjs.map} +1 -1
- package/dist/{decorators-CRmHuzxz.d.mts → decorators-J5mC7D-6.d.mts} +44 -4
- package/dist/{decorators-CRmHuzxz.d.mts.map → decorators-J5mC7D-6.d.mts.map} +1 -1
- package/dist/env-BL0xOTyi.mjs +12 -0
- package/dist/{env-CDMCT10_.mjs.map → env-BL0xOTyi.mjs.map} +1 -1
- package/dist/http/application.mjs +2 -3
- package/dist/http/bootstrap.mjs +2 -3
- package/dist/http/context.d.mts +2 -2
- package/dist/http/context.mjs +2 -3
- package/dist/http/middleware/cors.mjs +2 -73
- package/dist/http/middleware/cors.mjs.map +1 -1
- package/dist/http/middleware/csrf.mjs +2 -62
- package/dist/http/middleware/csrf.mjs.map +1 -1
- package/dist/http/middleware/error-handler.mjs +2 -54
- package/dist/http/middleware/error-handler.mjs.map +1 -1
- package/dist/http/middleware/helmet.mjs +2 -41
- package/dist/http/middleware/helmet.mjs.map +1 -1
- package/dist/http/middleware/rate-limit.mjs +2 -91
- package/dist/http/middleware/rate-limit.mjs.map +1 -1
- package/dist/http/middleware/request-id.mjs +2 -25
- package/dist/http/middleware/request-id.mjs.map +1 -1
- package/dist/http/middleware/request-logger.mjs +2 -39
- package/dist/http/middleware/request-logger.mjs.map +1 -1
- package/dist/http/middleware/session.mjs +2 -167
- package/dist/http/middleware/session.mjs.map +1 -1
- package/dist/http/middleware/spa.mjs +2 -98
- package/dist/http/middleware/spa.mjs.map +1 -1
- package/dist/http/middleware/upload.d.mts +1 -1
- package/dist/http/middleware/upload.mjs +2 -181
- package/dist/http/middleware/upload.mjs.map +1 -1
- package/dist/http/middleware/validate.mjs +2 -68
- package/dist/http/middleware/validate.mjs.map +1 -1
- package/dist/http/middleware/views.d.mts +1 -1
- package/dist/http/middleware/views.mjs +2 -56
- package/dist/http/middleware/views.mjs.map +1 -1
- package/dist/http/query/index.mjs +2 -3
- package/dist/http/router-builder.mjs +2 -105
- package/dist/http/router-builder.mjs.map +1 -1
- package/dist/{index-DhNglXyS.d.mts → index-BbtF8kIr.d.mts} +2 -2
- package/dist/{index-DhNglXyS.d.mts.map → index-BbtF8kIr.d.mts.map} +1 -1
- package/dist/index.d.mts +6 -6
- package/dist/index.mjs +2 -171
- package/dist/index.mjs.map +1 -1
- package/dist/metadata-Dn6kNT82.mjs +12 -0
- package/dist/{metadata-DPLdmj1w.mjs.map → metadata-Dn6kNT82.mjs.map} +1 -1
- package/dist/query-B7n5isk_.mjs +12 -0
- package/dist/{query-CD0AMqxx.mjs.map → query-B7n5isk_.mjs.map} +1 -1
- package/dist/{upload-BM9uyR6Y.d.mts → upload-tGMrlhEB.d.mts} +2 -2
- package/dist/{upload-BM9uyR6Y.d.mts.map → upload-tGMrlhEB.d.mts.map} +1 -1
- package/dist/{views-DkNp9JJs.d.mts → views-oKRSw0Op.d.mts} +2 -2
- package/dist/{views-DkNp9JJs.d.mts.map → views-oKRSw0Op.d.mts.map} +1 -1
- package/package.json +1 -1
- package/dist/application-Bw87drVl.mjs +0 -574
- package/dist/bootstrap-CsQ7LE-W.mjs +0 -195
- package/dist/config-DKRN5fqC.mjs +0 -135
- package/dist/container-C0FlgLNH.mjs +0 -897
- package/dist/context-CDFiXWcV.mjs +0 -348
- package/dist/context-CDFiXWcV.mjs.map +0 -1
- package/dist/context-Ymvv-85x.d.mts.map +0 -1
- package/dist/core-K0J8AH_4.mjs +0 -820
- package/dist/env-CDMCT10_.mjs +0 -137
- package/dist/metadata-DPLdmj1w.mjs +0 -76
- package/dist/query-CD0AMqxx.mjs +0 -164
package/dist/core/cache.mjs
CHANGED
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
/**
|
|
2
|
-
* @forinda/kickjs v5.
|
|
2
|
+
* @forinda/kickjs v5.4.0
|
|
3
3
|
*
|
|
4
4
|
* Copyright (c) Felix Orinda
|
|
5
5
|
*
|
|
@@ -8,106 +8,5 @@
|
|
|
8
8
|
*
|
|
9
9
|
* @license MIT
|
|
10
10
|
*/
|
|
11
|
-
import
|
|
12
|
-
//#region src/core/cache.ts
|
|
13
|
-
const CACHEABLE_META = "kick/cacheable";
|
|
14
|
-
/**
|
|
15
|
-
* Default in-memory cache provider using a Map.
|
|
16
|
-
* Suitable for development and single-instance deployments.
|
|
17
|
-
* For multi-instance or production, use a Redis-backed provider.
|
|
18
|
-
*/
|
|
19
|
-
var MemoryCacheProvider = class {
|
|
20
|
-
store = /* @__PURE__ */ new Map();
|
|
21
|
-
async get(key) {
|
|
22
|
-
const entry = this.store.get(key);
|
|
23
|
-
if (!entry) return null;
|
|
24
|
-
if (entry.expiresAt <= Date.now()) {
|
|
25
|
-
this.store.delete(key);
|
|
26
|
-
return null;
|
|
27
|
-
}
|
|
28
|
-
return entry.data;
|
|
29
|
-
}
|
|
30
|
-
async set(key, value, ttlMs) {
|
|
31
|
-
this.store.set(key, {
|
|
32
|
-
data: value,
|
|
33
|
-
expiresAt: Date.now() + ttlMs
|
|
34
|
-
});
|
|
35
|
-
}
|
|
36
|
-
async del(key) {
|
|
37
|
-
this.store.delete(key);
|
|
38
|
-
}
|
|
39
|
-
async delByPrefix(prefix) {
|
|
40
|
-
for (const key of this.store.keys()) if (key.startsWith(prefix)) this.store.delete(key);
|
|
41
|
-
}
|
|
42
|
-
async shutdown() {
|
|
43
|
-
this.store.clear();
|
|
44
|
-
}
|
|
45
|
-
};
|
|
46
|
-
let _cacheProvider = new MemoryCacheProvider();
|
|
47
|
-
/**
|
|
48
|
-
* Set the global cache provider used by @Cacheable and @CacheEvict.
|
|
49
|
-
* Call this before bootstrapping your app.
|
|
50
|
-
*
|
|
51
|
-
* @example
|
|
52
|
-
* ```ts
|
|
53
|
-
* import { setCacheProvider } from '@forinda/kickjs'
|
|
54
|
-
* import { RedisCacheProvider } from './redis-cache'
|
|
55
|
-
*
|
|
56
|
-
* setCacheProvider(new RedisCacheProvider(redisClient))
|
|
57
|
-
* ```
|
|
58
|
-
*/
|
|
59
|
-
function setCacheProvider(provider) {
|
|
60
|
-
_cacheProvider = provider;
|
|
61
|
-
}
|
|
62
|
-
/** Get the current cache provider */
|
|
63
|
-
function getCacheProvider() {
|
|
64
|
-
return _cacheProvider;
|
|
65
|
-
}
|
|
66
|
-
/**
|
|
67
|
-
* Cache the return value of a method for the specified TTL.
|
|
68
|
-
* Uses the globally registered CacheProvider (default: MemoryCacheProvider).
|
|
69
|
-
*
|
|
70
|
-
* Call `setCacheProvider()` to use Redis or any custom backend.
|
|
71
|
-
*
|
|
72
|
-
* @param ttl - Time-to-live in seconds (default: 60)
|
|
73
|
-
* @param options.key - Custom cache key prefix
|
|
74
|
-
*/
|
|
75
|
-
function Cacheable(ttl, options) {
|
|
76
|
-
return (_target, propertyKey, descriptor) => {
|
|
77
|
-
const original = descriptor.value;
|
|
78
|
-
const cacheTtl = (ttl ?? 60) * 1e3;
|
|
79
|
-
const keyPrefix = options?.key ?? String(propertyKey);
|
|
80
|
-
descriptor.value = async function(...args) {
|
|
81
|
-
const cacheKey = `${keyPrefix}:${JSON.stringify(args)}`;
|
|
82
|
-
const provider = getCacheProvider();
|
|
83
|
-
const cached = await provider.get(cacheKey);
|
|
84
|
-
if (cached !== null) return cached;
|
|
85
|
-
const result = await original.apply(this, args);
|
|
86
|
-
await provider.set(cacheKey, result, cacheTtl);
|
|
87
|
-
return result;
|
|
88
|
-
};
|
|
89
|
-
return descriptor;
|
|
90
|
-
};
|
|
91
|
-
}
|
|
92
|
-
/**
|
|
93
|
-
* Evict cached values matching a key prefix after the method executes.
|
|
94
|
-
* Works with any CacheProvider that implements `delByPrefix`.
|
|
95
|
-
*
|
|
96
|
-
* @param key - Cache key prefix to evict (matches the @Cacheable key)
|
|
97
|
-
*/
|
|
98
|
-
function CacheEvict(key) {
|
|
99
|
-
return (_target, _propertyKey, descriptor) => {
|
|
100
|
-
const original = descriptor.value;
|
|
101
|
-
descriptor.value = async function(...args) {
|
|
102
|
-
const result = await original.apply(this, args);
|
|
103
|
-
const provider = getCacheProvider();
|
|
104
|
-
if (provider.delByPrefix) await provider.delByPrefix(key);
|
|
105
|
-
return result;
|
|
106
|
-
};
|
|
107
|
-
return descriptor;
|
|
108
|
-
};
|
|
109
|
-
}
|
|
110
|
-
//#endregion
|
|
111
|
-
export { CACHEABLE_META, CacheEvict, Cacheable, MemoryCacheProvider, getCacheProvider, setCacheProvider };
|
|
112
|
-
|
|
11
|
+
import"reflect-metadata";const CACHEABLE_META=`kick/cacheable`;var MemoryCacheProvider=class{store=new Map;async get(key){let entry=this.store.get(key);return entry?entry.expiresAt<=Date.now()?(this.store.delete(key),null):entry.data:null}async set(key,value,ttlMs){this.store.set(key,{data:value,expiresAt:Date.now()+ttlMs})}async del(key){this.store.delete(key)}async delByPrefix(prefix){for(let key of this.store.keys())key.startsWith(prefix)&&this.store.delete(key)}async shutdown(){this.store.clear()}};let _cacheProvider=new MemoryCacheProvider;function setCacheProvider(provider){_cacheProvider=provider}function getCacheProvider(){return _cacheProvider}function Cacheable(ttl,options){return(_target,propertyKey,descriptor)=>{let original=descriptor.value,cacheTtl=(ttl??60)*1e3,keyPrefix=options?.key??String(propertyKey);return descriptor.value=async function(...args){let cacheKey=`${keyPrefix}:${JSON.stringify(args)}`,provider=getCacheProvider(),cached=await provider.get(cacheKey);if(cached!==null)return cached;let result=await original.apply(this,args);return await provider.set(cacheKey,result,cacheTtl),result},descriptor}}function CacheEvict(key){return(_target,_propertyKey,descriptor)=>{let original=descriptor.value;return descriptor.value=async function(...args){let result=await original.apply(this,args),provider=getCacheProvider();return provider.delByPrefix&&await provider.delByPrefix(key),result},descriptor}}export{CACHEABLE_META,CacheEvict,Cacheable,MemoryCacheProvider,getCacheProvider,setCacheProvider};
|
|
113
12
|
//# sourceMappingURL=cache.mjs.map
|
package/dist/core/cache.mjs.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"cache.mjs","names":[],"sources":["../../src/core/cache.ts"],"sourcesContent":["import 'reflect-metadata'\n\n// String metadata key (post-Symbol migration). Slash-delimited\n// `kick/cacheable` so it can't collide with adopter metadata keys.\nconst CACHEABLE_META = 'kick/cacheable'\n\n// ── CacheProvider Interface ─────────────────────────────────────────────\n\n/**\n * Abstract cache backend. Implement this interface to use Redis, Memcached,\n * or any other cache store with @Cacheable and @CacheEvict.\n *\n * @example\n * ```ts\n * class RedisCacheProvider implements CacheProvider {\n * private client: RedisClient\n * constructor(client: RedisClient) { this.client = client }\n * async get(key: string) {\n * const val = await this.client.get(key)\n * return val ? JSON.parse(val) : null\n * }\n * async set(key: string, value: any, ttlMs: number) {\n * await this.client.set(key, JSON.stringify(value), 'PX', ttlMs)\n * }\n * async del(key: string) { await this.client.del(key) }\n * async delByPrefix(prefix: string) {\n * const keys = await this.client.keys(prefix + '*')\n * if (keys.length) await this.client.del(...keys)\n * }\n * }\n * ```\n */\nexport interface CacheProvider {\n /** Retrieve a cached value. Return null if not found or expired. */\n get(key: string): Promise<any | null>\n /** Store a value with a TTL in milliseconds. */\n set(key: string, value: any, ttlMs: number): Promise<void>\n /** Delete a specific cache key. */\n del(key: string): Promise<void>\n /** Delete all keys matching a prefix. Used by @CacheEvict. */\n delByPrefix?(prefix: string): Promise<void>\n /** Optional cleanup on shutdown. */\n shutdown?(): Promise<void>\n}\n\n// ── Built-in Memory Provider ────────────────────────────────────────────\n\n/**\n * Default in-memory cache provider using a Map.\n * Suitable for development and single-instance deployments.\n * For multi-instance or production, use a Redis-backed provider.\n */\nexport class MemoryCacheProvider implements CacheProvider {\n private store = new Map<string, { data: any; expiresAt: number }>()\n\n async get(key: string): Promise<any | null> {\n const entry = this.store.get(key)\n if (!entry) return null\n if (entry.expiresAt <= Date.now()) {\n this.store.delete(key)\n return null\n }\n return entry.data\n }\n\n async set(key: string, value: any, ttlMs: number): Promise<void> {\n this.store.set(key, { data: value, expiresAt: Date.now() + ttlMs })\n }\n\n async del(key: string): Promise<void> {\n this.store.delete(key)\n }\n\n async delByPrefix(prefix: string): Promise<void> {\n for (const key of this.store.keys()) {\n if (key.startsWith(prefix)) {\n this.store.delete(key)\n }\n }\n }\n\n async shutdown(): Promise<void> {\n this.store.clear()\n }\n}\n\n// ── Global Cache Registry ───────────────────────────────────────────────\n\nlet _cacheProvider: CacheProvider = new MemoryCacheProvider()\n\n/**\n * Set the global cache provider used by @Cacheable and @CacheEvict.\n * Call this before bootstrapping your app.\n *\n * @example\n * ```ts\n * import { setCacheProvider } from '@forinda/kickjs'\n * import { RedisCacheProvider } from './redis-cache'\n *\n * setCacheProvider(new RedisCacheProvider(redisClient))\n * ```\n */\nexport function setCacheProvider(provider: CacheProvider): void {\n _cacheProvider = provider\n}\n\n/** Get the current cache provider */\nexport function getCacheProvider(): CacheProvider {\n return _cacheProvider\n}\n\n// ── Cache Options ───────────────────────────────────────────────────────\n\nexport interface CacheOptions {\n /** Time-to-live in seconds (default: 60) */\n ttl?: number\n /** Cache key prefix (default: ClassName.methodName) */\n key?: string\n}\n\n// ── @Cacheable Decorator ────────────────────────────────────────────────\n\n/**\n * Cache the return value of a method for the specified TTL.\n * Uses the globally registered CacheProvider (default: MemoryCacheProvider).\n *\n * Call `setCacheProvider()` to use Redis or any custom backend.\n *\n * @param ttl - Time-to-live in seconds (default: 60)\n * @param options.key - Custom cache key prefix\n */\nexport function Cacheable(ttl?: number, options?: { key?: string }): MethodDecorator {\n return (_target, propertyKey, descriptor: PropertyDescriptor) => {\n const original = descriptor.value\n const cacheTtl = (ttl ?? 60) * 1000\n const keyPrefix = options?.key ?? String(propertyKey)\n\n descriptor.value = async function (...args: any[]) {\n const cacheKey = `${keyPrefix}:${JSON.stringify(args)}`\n const provider = getCacheProvider()\n\n const cached = await provider.get(cacheKey)\n if (cached !== null) {\n return cached\n }\n\n const result = await original.apply(this, args)\n await provider.set(cacheKey, result, cacheTtl)\n return result\n }\n\n return descriptor\n }\n}\n\n// ── @CacheEvict Decorator ───────────────────────────────────────────────\n\n/**\n * Evict cached values matching a key prefix after the method executes.\n * Works with any CacheProvider that implements `delByPrefix`.\n *\n * @param key - Cache key prefix to evict (matches the @Cacheable key)\n */\nexport function CacheEvict(key: string): MethodDecorator {\n return (_target, _propertyKey, descriptor: PropertyDescriptor) => {\n const original = descriptor.value\n\n descriptor.value = async function (...args: any[]) {\n const result = await original.apply(this, args)\n const provider = getCacheProvider()\n if (provider.delByPrefix) {\n await provider.delByPrefix(key)\n }\n return result\n }\n\n return descriptor\n }\n}\n\nexport { CACHEABLE_META }\n"],"mappings":"
|
|
1
|
+
{"version":3,"file":"cache.mjs","names":[],"sources":["../../src/core/cache.ts"],"sourcesContent":["import 'reflect-metadata'\n\n// String metadata key (post-Symbol migration). Slash-delimited\n// `kick/cacheable` so it can't collide with adopter metadata keys.\nconst CACHEABLE_META = 'kick/cacheable'\n\n// ── CacheProvider Interface ─────────────────────────────────────────────\n\n/**\n * Abstract cache backend. Implement this interface to use Redis, Memcached,\n * or any other cache store with @Cacheable and @CacheEvict.\n *\n * @example\n * ```ts\n * class RedisCacheProvider implements CacheProvider {\n * private client: RedisClient\n * constructor(client: RedisClient) { this.client = client }\n * async get(key: string) {\n * const val = await this.client.get(key)\n * return val ? JSON.parse(val) : null\n * }\n * async set(key: string, value: any, ttlMs: number) {\n * await this.client.set(key, JSON.stringify(value), 'PX', ttlMs)\n * }\n * async del(key: string) { await this.client.del(key) }\n * async delByPrefix(prefix: string) {\n * const keys = await this.client.keys(prefix + '*')\n * if (keys.length) await this.client.del(...keys)\n * }\n * }\n * ```\n */\nexport interface CacheProvider {\n /** Retrieve a cached value. Return null if not found or expired. */\n get(key: string): Promise<any | null>\n /** Store a value with a TTL in milliseconds. */\n set(key: string, value: any, ttlMs: number): Promise<void>\n /** Delete a specific cache key. */\n del(key: string): Promise<void>\n /** Delete all keys matching a prefix. Used by @CacheEvict. */\n delByPrefix?(prefix: string): Promise<void>\n /** Optional cleanup on shutdown. */\n shutdown?(): Promise<void>\n}\n\n// ── Built-in Memory Provider ────────────────────────────────────────────\n\n/**\n * Default in-memory cache provider using a Map.\n * Suitable for development and single-instance deployments.\n * For multi-instance or production, use a Redis-backed provider.\n */\nexport class MemoryCacheProvider implements CacheProvider {\n private store = new Map<string, { data: any; expiresAt: number }>()\n\n async get(key: string): Promise<any | null> {\n const entry = this.store.get(key)\n if (!entry) return null\n if (entry.expiresAt <= Date.now()) {\n this.store.delete(key)\n return null\n }\n return entry.data\n }\n\n async set(key: string, value: any, ttlMs: number): Promise<void> {\n this.store.set(key, { data: value, expiresAt: Date.now() + ttlMs })\n }\n\n async del(key: string): Promise<void> {\n this.store.delete(key)\n }\n\n async delByPrefix(prefix: string): Promise<void> {\n for (const key of this.store.keys()) {\n if (key.startsWith(prefix)) {\n this.store.delete(key)\n }\n }\n }\n\n async shutdown(): Promise<void> {\n this.store.clear()\n }\n}\n\n// ── Global Cache Registry ───────────────────────────────────────────────\n\nlet _cacheProvider: CacheProvider = new MemoryCacheProvider()\n\n/**\n * Set the global cache provider used by @Cacheable and @CacheEvict.\n * Call this before bootstrapping your app.\n *\n * @example\n * ```ts\n * import { setCacheProvider } from '@forinda/kickjs'\n * import { RedisCacheProvider } from './redis-cache'\n *\n * setCacheProvider(new RedisCacheProvider(redisClient))\n * ```\n */\nexport function setCacheProvider(provider: CacheProvider): void {\n _cacheProvider = provider\n}\n\n/** Get the current cache provider */\nexport function getCacheProvider(): CacheProvider {\n return _cacheProvider\n}\n\n// ── Cache Options ───────────────────────────────────────────────────────\n\nexport interface CacheOptions {\n /** Time-to-live in seconds (default: 60) */\n ttl?: number\n /** Cache key prefix (default: ClassName.methodName) */\n key?: string\n}\n\n// ── @Cacheable Decorator ────────────────────────────────────────────────\n\n/**\n * Cache the return value of a method for the specified TTL.\n * Uses the globally registered CacheProvider (default: MemoryCacheProvider).\n *\n * Call `setCacheProvider()` to use Redis or any custom backend.\n *\n * @param ttl - Time-to-live in seconds (default: 60)\n * @param options.key - Custom cache key prefix\n */\nexport function Cacheable(ttl?: number, options?: { key?: string }): MethodDecorator {\n return (_target, propertyKey, descriptor: PropertyDescriptor) => {\n const original = descriptor.value\n const cacheTtl = (ttl ?? 60) * 1000\n const keyPrefix = options?.key ?? String(propertyKey)\n\n descriptor.value = async function (...args: any[]) {\n const cacheKey = `${keyPrefix}:${JSON.stringify(args)}`\n const provider = getCacheProvider()\n\n const cached = await provider.get(cacheKey)\n if (cached !== null) {\n return cached\n }\n\n const result = await original.apply(this, args)\n await provider.set(cacheKey, result, cacheTtl)\n return result\n }\n\n return descriptor\n }\n}\n\n// ── @CacheEvict Decorator ───────────────────────────────────────────────\n\n/**\n * Evict cached values matching a key prefix after the method executes.\n * Works with any CacheProvider that implements `delByPrefix`.\n *\n * @param key - Cache key prefix to evict (matches the @Cacheable key)\n */\nexport function CacheEvict(key: string): MethodDecorator {\n return (_target, _propertyKey, descriptor: PropertyDescriptor) => {\n const original = descriptor.value\n\n descriptor.value = async function (...args: any[]) {\n const result = await original.apply(this, args)\n const provider = getCacheProvider()\n if (provider.delByPrefix) {\n await provider.delByPrefix(key)\n }\n return result\n }\n\n return descriptor\n }\n}\n\nexport { CACHEABLE_META }\n"],"mappings":";;;;;;;;;;yBAIA,MAAM,eAAiB,iBAgDvB,IAAa,oBAAb,KAA0D,CACxD,MAAgB,IAAI,IAEpB,MAAM,IAAI,IAAkC,CAC1C,IAAM,MAAQ,KAAK,MAAM,IAAI,IAAI,CAMjC,OALK,MACD,MAAM,WAAa,KAAK,KAAK,EAC/B,KAAK,MAAM,OAAO,IAAI,CACf,MAEF,MAAM,KALM,KAQrB,MAAM,IAAI,IAAa,MAAY,MAA8B,CAC/D,KAAK,MAAM,IAAI,IAAK,CAAE,KAAM,MAAO,UAAW,KAAK,KAAK,CAAG,MAAO,CAAC,CAGrE,MAAM,IAAI,IAA4B,CACpC,KAAK,MAAM,OAAO,IAAI,CAGxB,MAAM,YAAY,OAA+B,CAC/C,IAAK,IAAM,OAAO,KAAK,MAAM,MAAM,CAC7B,IAAI,WAAW,OAAO,EACxB,KAAK,MAAM,OAAO,IAAI,CAK5B,MAAM,UAA0B,CAC9B,KAAK,MAAM,OAAO,GAMtB,IAAI,eAAgC,IAAI,oBAcxC,SAAgB,iBAAiB,SAA+B,CAC9D,eAAiB,SAInB,SAAgB,kBAAkC,CAChD,OAAO,eAuBT,SAAgB,UAAU,IAAc,QAA6C,CACnF,OAAQ,QAAS,YAAa,aAAmC,CAC/D,IAAM,SAAW,WAAW,MACtB,UAAY,KAAO,IAAM,IACzB,UAAY,SAAS,KAAO,OAAO,YAAY,CAgBrD,MAdA,YAAW,MAAQ,eAAgB,GAAG,KAAa,CACjD,IAAM,SAAW,GAAG,UAAU,GAAG,KAAK,UAAU,KAAK,GAC/C,SAAW,kBAAkB,CAE7B,OAAS,MAAM,SAAS,IAAI,SAAS,CAC3C,GAAI,SAAW,KACb,OAAO,OAGT,IAAM,OAAS,MAAM,SAAS,MAAM,KAAM,KAAK,CAE/C,OADA,MAAM,SAAS,IAAI,SAAU,OAAQ,SAAS,CACvC,QAGF,YAYX,SAAgB,WAAW,IAA8B,CACvD,OAAQ,QAAS,aAAc,aAAmC,CAChE,IAAM,SAAW,WAAW,MAW5B,MATA,YAAW,MAAQ,eAAgB,GAAG,KAAa,CACjD,IAAM,OAAS,MAAM,SAAS,MAAM,KAAM,KAAK,CACzC,SAAW,kBAAkB,CAInC,OAHI,SAAS,aACX,MAAM,SAAS,YAAY,IAAI,CAE1B,QAGF"}
|
package/dist/core/container.mjs
CHANGED
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
/**
|
|
2
|
-
* @forinda/kickjs v5.
|
|
2
|
+
* @forinda/kickjs v5.4.0
|
|
3
3
|
*
|
|
4
4
|
* Copyright (c) Felix Orinda
|
|
5
5
|
*
|
|
@@ -8,5 +8,4 @@
|
|
|
8
8
|
*
|
|
9
9
|
* @license MIT
|
|
10
10
|
*/
|
|
11
|
-
import
|
|
12
|
-
export { Container, tokenName };
|
|
11
|
+
import{n as tokenName,t as Container}from"../container-DArhTDQQ.mjs";export{Container,tokenName};
|
package/dist/core/cron.mjs
CHANGED
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
/**
|
|
2
|
-
* @forinda/kickjs v5.
|
|
2
|
+
* @forinda/kickjs v5.4.0
|
|
3
3
|
*
|
|
4
4
|
* Copyright (c) Felix Orinda
|
|
5
5
|
*
|
|
@@ -8,35 +8,5 @@
|
|
|
8
8
|
*
|
|
9
9
|
* @license MIT
|
|
10
10
|
*/
|
|
11
|
-
import
|
|
12
|
-
//#region src/core/cron.ts
|
|
13
|
-
const CRON_META = "kick/cron";
|
|
14
|
-
/**
|
|
15
|
-
* Schedule a method to run on a cron expression.
|
|
16
|
-
* Requires a CronAdapter to be registered in bootstrap().
|
|
17
|
-
*
|
|
18
|
-
* @param expression - Standard 5-part cron: minute hour day month weekday.
|
|
19
|
-
* Use forward-slash for intervals (e.g. every 5 min, every 2 hours).
|
|
20
|
-
* @param options.description - Human-readable label for logging
|
|
21
|
-
* @param options.timezone - IANA timezone (e.g. 'America/New_York', 'UTC')
|
|
22
|
-
* @param options.runOnInit - Run immediately on startup before first scheduled tick
|
|
23
|
-
*/
|
|
24
|
-
function Cron(expression, options) {
|
|
25
|
-
return (target, propertyKey) => {
|
|
26
|
-
pushClassMeta(CRON_META, target.constructor, {
|
|
27
|
-
expression,
|
|
28
|
-
handlerName: propertyKey,
|
|
29
|
-
description: options?.description,
|
|
30
|
-
timezone: options?.timezone,
|
|
31
|
-
runOnInit: options?.runOnInit
|
|
32
|
-
});
|
|
33
|
-
};
|
|
34
|
-
}
|
|
35
|
-
/** Read cron jobs registered on a class */
|
|
36
|
-
function getCronJobs(target) {
|
|
37
|
-
return getClassMeta(CRON_META, target, []);
|
|
38
|
-
}
|
|
39
|
-
//#endregion
|
|
40
|
-
export { CRON_META, Cron, getCronJobs };
|
|
41
|
-
|
|
11
|
+
import{c as pushClassMeta,t as getClassMeta}from"../metadata-Dn6kNT82.mjs";const CRON_META=`kick/cron`;function Cron(expression,options){return(target,propertyKey)=>{pushClassMeta(CRON_META,target.constructor,{expression,handlerName:propertyKey,description:options?.description,timezone:options?.timezone,runOnInit:options?.runOnInit})}}function getCronJobs(target){return getClassMeta(CRON_META,target,[])}export{CRON_META,Cron,getCronJobs};
|
|
42
12
|
//# sourceMappingURL=cron.mjs.map
|
package/dist/core/cron.mjs.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"cron.mjs","names":[],"sources":["../../src/core/cron.ts"],"sourcesContent":["import { pushClassMeta, getClassMeta } from './metadata'\n\n// String metadata key (post-Symbol migration). Slash-delimited\n// `kick/cron` so it can't collide with adopter metadata keys.\nconst CRON_META = 'kick/cron'\n\nexport interface CronJobMeta {\n expression: string\n handlerName: string\n description?: string\n timezone?: string\n runOnInit?: boolean\n}\n\n// Cron format: minute hour day month weekday\n// Examples:\n// '* * * * *' - every minute\n// '0 * * * *' - every hour\n// '0 0 * * *' - daily at midnight\n// '0 9 * * MON-FRI' - weekdays at 9am\n// '0 0 1 * *' - first of each month\n\n/**\n * Schedule a method to run on a cron expression.\n * Requires a CronAdapter to be registered in bootstrap().\n *\n * @param expression - Standard 5-part cron: minute hour day month weekday.\n * Use forward-slash for intervals (e.g. every 5 min, every 2 hours).\n * @param options.description - Human-readable label for logging\n * @param options.timezone - IANA timezone (e.g. 'America/New_York', 'UTC')\n * @param options.runOnInit - Run immediately on startup before first scheduled tick\n */\nexport function Cron(\n expression: string,\n options?: { description?: string; timezone?: string; runOnInit?: boolean },\n): MethodDecorator {\n return (target, propertyKey) => {\n pushClassMeta<CronJobMeta>(CRON_META, target.constructor, {\n expression,\n handlerName: propertyKey as string,\n description: options?.description,\n timezone: options?.timezone,\n runOnInit: options?.runOnInit,\n })\n }\n}\n\n/** Read cron jobs registered on a class */\nexport function getCronJobs(target: any): CronJobMeta[] {\n return getClassMeta<CronJobMeta[]>(CRON_META, target, [])\n}\n\nexport { CRON_META }\n"],"mappings":"
|
|
1
|
+
{"version":3,"file":"cron.mjs","names":[],"sources":["../../src/core/cron.ts"],"sourcesContent":["import { pushClassMeta, getClassMeta } from './metadata'\n\n// String metadata key (post-Symbol migration). Slash-delimited\n// `kick/cron` so it can't collide with adopter metadata keys.\nconst CRON_META = 'kick/cron'\n\nexport interface CronJobMeta {\n expression: string\n handlerName: string\n description?: string\n timezone?: string\n runOnInit?: boolean\n}\n\n// Cron format: minute hour day month weekday\n// Examples:\n// '* * * * *' - every minute\n// '0 * * * *' - every hour\n// '0 0 * * *' - daily at midnight\n// '0 9 * * MON-FRI' - weekdays at 9am\n// '0 0 1 * *' - first of each month\n\n/**\n * Schedule a method to run on a cron expression.\n * Requires a CronAdapter to be registered in bootstrap().\n *\n * @param expression - Standard 5-part cron: minute hour day month weekday.\n * Use forward-slash for intervals (e.g. every 5 min, every 2 hours).\n * @param options.description - Human-readable label for logging\n * @param options.timezone - IANA timezone (e.g. 'America/New_York', 'UTC')\n * @param options.runOnInit - Run immediately on startup before first scheduled tick\n */\nexport function Cron(\n expression: string,\n options?: { description?: string; timezone?: string; runOnInit?: boolean },\n): MethodDecorator {\n return (target, propertyKey) => {\n pushClassMeta<CronJobMeta>(CRON_META, target.constructor, {\n expression,\n handlerName: propertyKey as string,\n description: options?.description,\n timezone: options?.timezone,\n runOnInit: options?.runOnInit,\n })\n }\n}\n\n/** Read cron jobs registered on a class */\nexport function getCronJobs(target: any): CronJobMeta[] {\n return getClassMeta<CronJobMeta[]>(CRON_META, target, [])\n}\n\nexport { CRON_META }\n"],"mappings":";;;;;;;;;;2EAIA,MAAM,UAAY,YA4BlB,SAAgB,KACd,WACA,QACiB,CACjB,OAAQ,OAAQ,cAAgB,CAC9B,cAA2B,UAAW,OAAO,YAAa,CACxD,WACA,YAAa,YACb,YAAa,SAAS,YACtB,SAAU,SAAS,SACnB,UAAW,SAAS,UACrB,CAAC,EAKN,SAAgB,YAAY,OAA4B,CACtD,OAAO,aAA4B,UAAW,OAAQ,EAAE,CAAC"}
|
|
@@ -1,3 +1,3 @@
|
|
|
1
1
|
|
|
2
|
-
import { A as normalizeApiQueryParamsConfig, C as Post, D as RouteDefinition, E as Repository, O as Service, S as Patch, T as Put, _ as Get, a as Autowired, b as Middleware, c as ColumnApiQueryParamsConfig, d as Delete, f as Env, g as FileUploadConfig, h as FileUpload, i as AssetKey, k as Value, l as Component, m as FileTypeFilter, n as ApiQueryParamsConfig, o as BaseUploadOptions, p as EnvKey, r as Asset, s as Builder, t as ApiQueryParams, u as Controller, v as Inject, w as PostConstruct, x as MiddlewareHandler, y as Injectable } from "../decorators-
|
|
3
|
-
export { ApiQueryParams, ApiQueryParamsConfig, Asset, AssetKey, Autowired, BaseUploadOptions, Builder, ColumnApiQueryParamsConfig, Component, Controller, Delete, Env, EnvKey, FileTypeFilter, FileUpload, FileUploadConfig, Get, Inject, Injectable, Middleware, MiddlewareHandler, Patch, Post, PostConstruct, Put, Repository, RouteDefinition, Service, Value, normalizeApiQueryParamsConfig };
|
|
2
|
+
import { A as normalizeApiQueryParamsConfig, C as Post, D as RouteDefinition, E as Repository, O as Service, S as Patch, T as Put, _ as Get, a as Autowired, b as Middleware, c as ColumnApiQueryParamsConfig, d as Delete, f as Env, g as FileUploadConfig, h as FileUpload, i as AssetKey, j as withBuilder, k as Value, l as Component, m as FileTypeFilter, n as ApiQueryParamsConfig, o as BaseUploadOptions, p as EnvKey, r as Asset, s as Builder, t as ApiQueryParams, u as Controller, v as Inject, w as PostConstruct, x as MiddlewareHandler, y as Injectable } from "../decorators-J5mC7D-6.mjs";
|
|
3
|
+
export { ApiQueryParams, ApiQueryParamsConfig, Asset, AssetKey, Autowired, BaseUploadOptions, Builder, ColumnApiQueryParamsConfig, Component, Controller, Delete, Env, EnvKey, FileTypeFilter, FileUpload, FileUploadConfig, Get, Inject, Injectable, Middleware, MiddlewareHandler, Patch, Post, PostConstruct, Put, Repository, RouteDefinition, Service, Value, normalizeApiQueryParamsConfig, withBuilder };
|
package/dist/core/decorators.mjs
CHANGED
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
/**
|
|
2
|
-
* @forinda/kickjs v5.
|
|
2
|
+
* @forinda/kickjs v5.4.0
|
|
3
3
|
*
|
|
4
4
|
* Copyright (c) Felix Orinda
|
|
5
5
|
*
|
|
@@ -8,244 +8,5 @@
|
|
|
8
8
|
*
|
|
9
9
|
* @license MIT
|
|
10
10
|
*/
|
|
11
|
-
import
|
|
12
|
-
import { METADATA, Scope } from "./interfaces.mjs";
|
|
13
|
-
import { c as pushClassMeta, d as setInMetaMap, f as setInMetaRecord, l as pushMethodMeta, p as setMethodMeta, u as setClassMeta } from "../metadata-DPLdmj1w.mjs";
|
|
14
|
-
import "reflect-metadata";
|
|
15
|
-
//#region src/core/decorators.ts
|
|
16
|
-
const pendingRegistrations = [];
|
|
17
|
-
const allRegistrations = /* @__PURE__ */ new Map();
|
|
18
|
-
let containerRef = null;
|
|
19
|
-
function flushPending(container) {
|
|
20
|
-
containerRef = container;
|
|
21
|
-
for (const { target, scope } of pendingRegistrations) if (!container.has(target)) container.register(target, target, scope);
|
|
22
|
-
pendingRegistrations.length = 0;
|
|
23
|
-
}
|
|
24
|
-
Container._onReady = flushPending;
|
|
25
|
-
Container._onReset = (container) => {
|
|
26
|
-
containerRef = container;
|
|
27
|
-
for (const [, { target, scope }] of allRegistrations) if (!container.has(target)) container.register(target, target, scope);
|
|
28
|
-
};
|
|
29
|
-
function registerInContainer(target, scope) {
|
|
30
|
-
setClassMeta(METADATA.INJECTABLE, true, target);
|
|
31
|
-
setClassMeta(METADATA.SCOPE, scope, target);
|
|
32
|
-
const name = target.name || String(target);
|
|
33
|
-
allRegistrations.set(name, {
|
|
34
|
-
target,
|
|
35
|
-
scope
|
|
36
|
-
});
|
|
37
|
-
if (containerRef) {
|
|
38
|
-
if (!containerRef.has(target)) containerRef.register(target, target, scope);
|
|
39
|
-
} else pendingRegistrations.push({
|
|
40
|
-
target,
|
|
41
|
-
scope
|
|
42
|
-
});
|
|
43
|
-
}
|
|
44
|
-
/** Mark a class as injectable with lifecycle scope */
|
|
45
|
-
function Injectable(options) {
|
|
46
|
-
return (target) => {
|
|
47
|
-
setClassMeta(METADATA.CLASS_KIND, "injectable", target);
|
|
48
|
-
registerInContainer(target, options?.scope ?? Scope.SINGLETON);
|
|
49
|
-
};
|
|
50
|
-
}
|
|
51
|
-
/** Mark a class as a service (semantic alias for Injectable) */
|
|
52
|
-
function Service(options) {
|
|
53
|
-
return (target) => {
|
|
54
|
-
setClassMeta(METADATA.CLASS_KIND, "service", target);
|
|
55
|
-
registerInContainer(target, options?.scope ?? Scope.SINGLETON);
|
|
56
|
-
};
|
|
57
|
-
}
|
|
58
|
-
/** Mark a class as a generic managed component */
|
|
59
|
-
function Component(options) {
|
|
60
|
-
return (target) => {
|
|
61
|
-
setClassMeta(METADATA.CLASS_KIND, "component", target);
|
|
62
|
-
registerInContainer(target, options?.scope ?? Scope.SINGLETON);
|
|
63
|
-
};
|
|
64
|
-
}
|
|
65
|
-
/** Mark a class as a repository */
|
|
66
|
-
function Repository(options) {
|
|
67
|
-
return (target) => {
|
|
68
|
-
setClassMeta(METADATA.CLASS_KIND, "repository", target);
|
|
69
|
-
registerInContainer(target, options?.scope ?? Scope.SINGLETON);
|
|
70
|
-
};
|
|
71
|
-
}
|
|
72
|
-
/**
|
|
73
|
-
* Mark a class as an HTTP controller and register it in the DI container.
|
|
74
|
-
*
|
|
75
|
-
* Route prefixes are defined by the module's `routes().path` — the single
|
|
76
|
-
* source of truth for where routes mount. The legacy
|
|
77
|
-
* `@Controller('/path')` parameter was removed in v4; if your code
|
|
78
|
-
* still passes a string, see `docs/guide/migration-v3-to-v4.md` for
|
|
79
|
-
* the rename map.
|
|
80
|
-
*/
|
|
81
|
-
function Controller() {
|
|
82
|
-
return (target) => {
|
|
83
|
-
setClassMeta(METADATA.CLASS_KIND, "controller", target);
|
|
84
|
-
registerInContainer(target, Scope.SINGLETON);
|
|
85
|
-
};
|
|
86
|
-
}
|
|
87
|
-
/** Mark a method as a lifecycle hook called after instantiation */
|
|
88
|
-
function PostConstruct() {
|
|
89
|
-
return (target, propertyKey) => {
|
|
90
|
-
setClassMeta(METADATA.POST_CONSTRUCT, propertyKey, target);
|
|
91
|
-
};
|
|
92
|
-
}
|
|
93
|
-
/** Property injection — resolved lazily from the container */
|
|
94
|
-
function Autowired(token) {
|
|
95
|
-
return (target, propertyKey) => {
|
|
96
|
-
setInMetaMap(METADATA.AUTOWIRED, target, propertyKey, token);
|
|
97
|
-
};
|
|
98
|
-
}
|
|
99
|
-
function Inject(token) {
|
|
100
|
-
return (target, _propertyKey, parameterIndex) => {
|
|
101
|
-
setInMetaRecord(METADATA.INJECT, target, parameterIndex, token);
|
|
102
|
-
};
|
|
103
|
-
}
|
|
104
|
-
/**
|
|
105
|
-
* Inject an environment variable value. Evaluated lazily so the env
|
|
106
|
-
* is available at access time, not at decoration time.
|
|
107
|
-
*
|
|
108
|
-
* If no default is provided and the env var is missing, throws at access time
|
|
109
|
-
* to catch misconfiguration early instead of returning undefined.
|
|
110
|
-
*
|
|
111
|
-
* Uses metadata + instance getter to work correctly with `useDefineForClassFields`.
|
|
112
|
-
*
|
|
113
|
-
* Type-safety:
|
|
114
|
-
* - Without `kick typegen` run, any string key is accepted (back-compat).
|
|
115
|
-
* - After typegen, `KickEnv` is populated and unknown keys become a tsc
|
|
116
|
-
* error. The optional `defaultValue` is type-checked against the
|
|
117
|
-
* schema's inferred type for that key.
|
|
118
|
-
*/
|
|
119
|
-
function Value(envKey, defaultValue) {
|
|
120
|
-
return (target, propertyKey) => {
|
|
121
|
-
setInMetaMap(METADATA.VALUE, target, propertyKey, {
|
|
122
|
-
envKey,
|
|
123
|
-
defaultValue
|
|
124
|
-
});
|
|
125
|
-
};
|
|
126
|
-
}
|
|
127
|
-
/**
|
|
128
|
-
* Inject the resolved file-system path for a typed asset. Mirrors
|
|
129
|
-
* `@Value`'s lazy-getter pattern — the asset is resolved on every
|
|
130
|
-
* property access, NOT at class instantiation, so:
|
|
131
|
-
*
|
|
132
|
-
* - Tests can swap fixtures + clear the cache without re-instantiating
|
|
133
|
-
* the consuming class.
|
|
134
|
-
* - The first access cost is paid once per process (the manifest cache
|
|
135
|
-
* in `core/assets.ts` makes subsequent calls cheap).
|
|
136
|
-
*
|
|
137
|
-
* Type-safety:
|
|
138
|
-
*
|
|
139
|
-
* - Without typegen, any string key is accepted (back-compat — same
|
|
140
|
-
* trick as `@Value`).
|
|
141
|
-
* - After typegen, `KickAssets` is populated and `AssetKey` is a
|
|
142
|
-
* union of every flattened `<namespace>/<key>` path. Unknown keys
|
|
143
|
-
* become a TS error.
|
|
144
|
-
*
|
|
145
|
-
* @example
|
|
146
|
-
* ```ts
|
|
147
|
-
* import { Service, Asset } from '@forinda/kickjs'
|
|
148
|
-
*
|
|
149
|
-
* `@Service()`
|
|
150
|
-
* class MailService {
|
|
151
|
-
* `@Asset('mails/welcome')`
|
|
152
|
-
* private welcomeTemplate!: string
|
|
153
|
-
*
|
|
154
|
-
* send(user: User) {
|
|
155
|
-
* return ejs.renderFile(this.welcomeTemplate, { user })
|
|
156
|
-
* }
|
|
157
|
-
* }
|
|
158
|
-
* ```
|
|
159
|
-
*/
|
|
160
|
-
function Asset(assetKey) {
|
|
161
|
-
return (target, propertyKey) => {
|
|
162
|
-
setInMetaMap(METADATA.ASSET, target, propertyKey, { assetKey });
|
|
163
|
-
};
|
|
164
|
-
}
|
|
165
|
-
function createRouteDecorator(method) {
|
|
166
|
-
return (path, validation) => {
|
|
167
|
-
return (target, propertyKey) => {
|
|
168
|
-
pushClassMeta(METADATA.ROUTES, target.constructor, {
|
|
169
|
-
method,
|
|
170
|
-
path: path || "/",
|
|
171
|
-
handlerName: propertyKey,
|
|
172
|
-
validation
|
|
173
|
-
});
|
|
174
|
-
};
|
|
175
|
-
};
|
|
176
|
-
}
|
|
177
|
-
const Get = createRouteDecorator("GET");
|
|
178
|
-
const Post = createRouteDecorator("POST");
|
|
179
|
-
const Put = createRouteDecorator("PUT");
|
|
180
|
-
const Delete = createRouteDecorator("DELETE");
|
|
181
|
-
const Patch = createRouteDecorator("PATCH");
|
|
182
|
-
/**
|
|
183
|
-
* Normalize a query params config to the string-based ApiQueryParamsConfig.
|
|
184
|
-
* Handles both string-based and column-object-based configs.
|
|
185
|
-
*/
|
|
186
|
-
function normalizeApiQueryParamsConfig(config) {
|
|
187
|
-
if ("columns" in config && config.columns && typeof config.columns === "object") return {
|
|
188
|
-
filterable: Object.keys(config.columns),
|
|
189
|
-
sortable: config.sortable ? Object.keys(config.sortable) : void 0,
|
|
190
|
-
searchable: config.searchColumns ? config.searchColumns.map((col) => col?.name ?? "").filter(Boolean) : void 0
|
|
191
|
-
};
|
|
192
|
-
return config;
|
|
193
|
-
}
|
|
194
|
-
/**
|
|
195
|
-
* Document the query parameters accepted by a GET endpoint.
|
|
196
|
-
* Used by SwaggerAdapter to generate `filter`, `sort`, `page`, `limit`, and `q` params
|
|
197
|
-
* in the OpenAPI spec, with descriptions listing the allowed fields.
|
|
198
|
-
*
|
|
199
|
-
* Accepts both string-based configs and column-object configs (e.g., DrizzleQueryParamsConfig).
|
|
200
|
-
*
|
|
201
|
-
* @example
|
|
202
|
-
* ```ts
|
|
203
|
-
* // String-based
|
|
204
|
-
* @ApiQueryParams({
|
|
205
|
-
* filterable: ['status', 'category', 'price'],
|
|
206
|
-
* sortable: ['name', 'createdAt', 'price'],
|
|
207
|
-
* searchable: ['name', 'description'],
|
|
208
|
-
* })
|
|
209
|
-
*
|
|
210
|
-
* // Column-object-based (Drizzle)
|
|
211
|
-
* @ApiQueryParams(TASK_QUERY_CONFIG)
|
|
212
|
-
* ```
|
|
213
|
-
*/
|
|
214
|
-
function ApiQueryParams(config) {
|
|
215
|
-
return (target, propertyKey) => {
|
|
216
|
-
const normalized = normalizeApiQueryParamsConfig(config);
|
|
217
|
-
setMethodMeta(METADATA.QUERY_PARAMS, normalized, target.constructor, propertyKey);
|
|
218
|
-
};
|
|
219
|
-
}
|
|
220
|
-
/** Attach middleware handlers to a class or method */
|
|
221
|
-
function Middleware(...handlers) {
|
|
222
|
-
return (target, propertyKey) => {
|
|
223
|
-
if (propertyKey) pushMethodMeta(METADATA.METHOD_MIDDLEWARES, target.constructor, propertyKey, ...handlers);
|
|
224
|
-
else pushClassMeta(METADATA.CLASS_MIDDLEWARES, target, ...handlers);
|
|
225
|
-
};
|
|
226
|
-
}
|
|
227
|
-
/** Configure file upload handling for a controller method */
|
|
228
|
-
function FileUpload(config) {
|
|
229
|
-
return (target, propertyKey) => {
|
|
230
|
-
setMethodMeta(METADATA.FILE_UPLOAD, config, target.constructor, propertyKey);
|
|
231
|
-
};
|
|
232
|
-
}
|
|
233
|
-
/** Add a static builder() method for fluent construction */
|
|
234
|
-
function Builder(target) {
|
|
235
|
-
setClassMeta(METADATA.BUILDER, true, target);
|
|
236
|
-
target.builder = function() {
|
|
237
|
-
const props = {};
|
|
238
|
-
const proxy = new Proxy({}, { get(_, key) {
|
|
239
|
-
if (key === "build") return () => Object.assign(new target(), props);
|
|
240
|
-
return (value) => {
|
|
241
|
-
props[key] = value;
|
|
242
|
-
return proxy;
|
|
243
|
-
};
|
|
244
|
-
} });
|
|
245
|
-
return proxy;
|
|
246
|
-
};
|
|
247
|
-
}
|
|
248
|
-
//#endregion
|
|
249
|
-
export { ApiQueryParams, Asset, Autowired, Builder, Component, Controller, Delete, FileUpload, Get, Inject, Injectable, Middleware, Patch, Post, PostConstruct, Put, Repository, Service, Value, normalizeApiQueryParamsConfig };
|
|
250
|
-
|
|
11
|
+
import{t as Container}from"../container-DArhTDQQ.mjs";import{METADATA,Scope}from"./interfaces.mjs";import{c as pushClassMeta,d as setInMetaMap,f as setInMetaRecord,l as pushMethodMeta,p as setMethodMeta,u as setClassMeta}from"../metadata-Dn6kNT82.mjs";import"reflect-metadata";const pendingRegistrations=[],allRegistrations=new Map;let containerRef=null;function flushPending(container){containerRef=container;for(let{target,scope}of pendingRegistrations)container.has(target)||container.register(target,target,scope);pendingRegistrations.length=0}Container._onReady=flushPending,Container._onReset=container=>{containerRef=container;for(let[,{target,scope}]of allRegistrations)container.has(target)||container.register(target,target,scope)};function registerInContainer(target,scope){setClassMeta(METADATA.INJECTABLE,!0,target),setClassMeta(METADATA.SCOPE,scope,target);let name=target.name||String(target);allRegistrations.set(name,{target,scope}),containerRef?containerRef.has(target)||containerRef.register(target,target,scope):pendingRegistrations.push({target,scope})}function Injectable(options){return target=>{setClassMeta(METADATA.CLASS_KIND,`injectable`,target),registerInContainer(target,options?.scope??Scope.SINGLETON)}}function Service(options){return target=>{setClassMeta(METADATA.CLASS_KIND,`service`,target),registerInContainer(target,options?.scope??Scope.SINGLETON)}}function Component(options){return target=>{setClassMeta(METADATA.CLASS_KIND,`component`,target),registerInContainer(target,options?.scope??Scope.SINGLETON)}}function Repository(options){return target=>{setClassMeta(METADATA.CLASS_KIND,`repository`,target),registerInContainer(target,options?.scope??Scope.SINGLETON)}}function Controller(){return target=>{setClassMeta(METADATA.CLASS_KIND,`controller`,target),registerInContainer(target,Scope.SINGLETON)}}function PostConstruct(){return(target,propertyKey)=>{setClassMeta(METADATA.POST_CONSTRUCT,propertyKey,target)}}function Autowired(token){return(target,propertyKey)=>{setInMetaMap(METADATA.AUTOWIRED,target,propertyKey,token)}}function Inject(token){return(target,_propertyKey,parameterIndex)=>{setInMetaRecord(METADATA.INJECT,target,parameterIndex,token)}}function Value(envKey,defaultValue){return(target,propertyKey)=>{setInMetaMap(METADATA.VALUE,target,propertyKey,{envKey,defaultValue})}}function Asset(assetKey){return(target,propertyKey)=>{setInMetaMap(METADATA.ASSET,target,propertyKey,{assetKey})}}function createRouteDecorator(method){return(path,validation)=>(target,propertyKey)=>{pushClassMeta(METADATA.ROUTES,target.constructor,{method,path:path||`/`,handlerName:propertyKey,validation})}}const Get=createRouteDecorator(`GET`),Post=createRouteDecorator(`POST`),Put=createRouteDecorator(`PUT`),Delete=createRouteDecorator(`DELETE`),Patch=createRouteDecorator(`PATCH`);function normalizeApiQueryParamsConfig(config){return`columns`in config&&config.columns&&typeof config.columns==`object`?{filterable:Object.keys(config.columns),sortable:config.sortable?Object.keys(config.sortable):void 0,searchable:config.searchColumns?config.searchColumns.map(col=>col?.name??``).filter(Boolean):void 0}:config}function ApiQueryParams(config){return(target,propertyKey)=>{let normalized=normalizeApiQueryParamsConfig(config);setMethodMeta(METADATA.QUERY_PARAMS,normalized,target.constructor,propertyKey)}}function Middleware(...handlers){return(target,propertyKey)=>{propertyKey?pushMethodMeta(METADATA.METHOD_MIDDLEWARES,target.constructor,propertyKey,...handlers):pushClassMeta(METADATA.CLASS_MIDDLEWARES,target,...handlers)}}function FileUpload(config){return(target,propertyKey)=>{setMethodMeta(METADATA.FILE_UPLOAD,config,target.constructor,propertyKey)}}function attachBuilder(target){setClassMeta(METADATA.BUILDER,!0,target),target.builder=function(){let props={},proxy=new Proxy({},{get(_,key){return key===`build`?()=>Object.assign(new target,props):value=>(props[key]=value,proxy)}});return proxy}}function Builder(target){attachBuilder(target)}function withBuilder(ctor){return attachBuilder(ctor),ctor}export{ApiQueryParams,Asset,Autowired,Builder,Component,Controller,Delete,FileUpload,Get,Inject,Injectable,Middleware,Patch,Post,PostConstruct,Put,Repository,Service,Value,normalizeApiQueryParamsConfig,withBuilder};
|
|
251
12
|
//# sourceMappingURL=decorators.mjs.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"decorators.mjs","names":[],"sources":["../../src/core/decorators.ts"],"sourcesContent":["import 'reflect-metadata'\nimport { METADATA, Scope, 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\n/** Add a static builder() method for fluent construction */\nexport function Builder(target: any): void {\n setClassMeta(METADATA.BUILDER, true, target)\n\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"],"mappings":"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"}
|
|
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<InstanceType<C>> }\n}\n"],"mappings":"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"}
|