@forinda/kickjs 2.0.1 → 2.2.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/README.md +63 -20
- package/dist/adapter-wuoBNkNs.d.mts +122 -0
- package/dist/adapter-wuoBNkNs.d.mts.map +1 -0
- package/dist/app-module-DOBmxARW.d.mts +40 -0
- package/dist/app-module-DOBmxARW.d.mts.map +1 -0
- package/dist/application-C5Q720a2.mjs +449 -0
- package/dist/application-C5Q720a2.mjs.map +1 -0
- package/dist/bootstrap-dEN6SjBl.mjs +205 -0
- package/dist/bootstrap-dEN6SjBl.mjs.map +1 -0
- package/dist/{core/cache.d.ts → cache-PufEhr0n.d.mts} +33 -31
- package/dist/cache-PufEhr0n.d.mts.map +1 -0
- package/dist/chunk-C9tIbwLT.mjs +15 -0
- package/dist/container-B7jFEbPE.mjs +496 -0
- package/dist/container-B7jFEbPE.mjs.map +1 -0
- package/dist/container-CcgV8eHL.d.mts +253 -0
- package/dist/container-CcgV8eHL.d.mts.map +1 -0
- package/dist/core/adapter.d.mts +3 -0
- package/dist/core/adapter.mjs +11 -0
- package/dist/core/app-module.d.mts +3 -0
- package/dist/core/app-module.mjs +11 -0
- package/dist/core/cache.d.mts +3 -0
- package/dist/core/cache.mjs +113 -0
- package/dist/core/cache.mjs.map +1 -0
- package/dist/core/container.d.mts +3 -0
- package/dist/core/container.mjs +12 -0
- package/dist/core/cron.d.mts +3 -0
- package/dist/core/cron.mjs +42 -0
- package/dist/core/cron.mjs.map +1 -0
- package/dist/core/decorators.d.mts +3 -0
- package/dist/core/decorators.mjs +219 -0
- package/dist/core/decorators.mjs.map +1 -0
- package/dist/core/errors.d.mts +3 -0
- package/dist/core/errors.mjs +97 -0
- package/dist/core/errors.mjs.map +1 -0
- package/dist/core/interfaces.d.mts +3 -0
- package/dist/core/interfaces.mjs +44 -0
- package/dist/core/interfaces.mjs.map +1 -0
- package/dist/core/logger.d.mts +3 -0
- package/dist/core/logger.mjs +217 -0
- package/dist/core/logger.mjs.map +1 -0
- package/dist/core/path.d.mts +3 -0
- package/dist/core/path.mjs +45 -0
- package/dist/core/path.mjs.map +1 -0
- package/dist/core/plugin.d.mts +3 -0
- package/dist/core/plugin.mjs +11 -0
- package/dist/core/reactivity.d.mts +3 -0
- package/dist/core/reactivity.mjs +189 -0
- package/dist/core/reactivity.mjs.map +1 -0
- package/dist/core-CMgIoRvg.mjs +121 -0
- package/dist/core-CMgIoRvg.mjs.map +1 -0
- package/dist/{core/cron.d.ts → cron-C29iHvHT.d.mts} +16 -14
- package/dist/cron-C29iHvHT.d.mts.map +1 -0
- package/dist/decorators-D3lBlmud.d.mts +204 -0
- package/dist/decorators-D3lBlmud.d.mts.map +1 -0
- package/dist/errors-BZUdxtjC.d.mts +68 -0
- package/dist/errors-BZUdxtjC.d.mts.map +1 -0
- package/dist/http/application.d.mts +220 -0
- package/dist/http/application.d.mts.map +1 -0
- package/dist/http/application.mjs +12 -0
- package/dist/http/bootstrap.d.mts +43 -0
- package/dist/http/bootstrap.d.mts.map +1 -0
- package/dist/http/bootstrap.mjs +12 -0
- package/dist/http/context.d.mts +190 -0
- package/dist/http/context.d.mts.map +1 -0
- package/dist/http/context.mjs +225 -0
- package/dist/http/context.mjs.map +1 -0
- package/dist/http/middleware/cors.d.mts +48 -0
- package/dist/http/middleware/cors.d.mts.map +1 -0
- package/dist/http/middleware/cors.mjs +83 -0
- package/dist/http/middleware/cors.mjs.map +1 -0
- package/dist/http/middleware/csrf.d.mts +52 -0
- package/dist/http/middleware/csrf.d.mts.map +1 -0
- package/dist/http/middleware/csrf.mjs +72 -0
- package/dist/http/middleware/csrf.mjs.map +1 -0
- package/dist/http/middleware/error-handler.d.mts +11 -0
- package/dist/http/middleware/error-handler.d.mts.map +1 -0
- package/dist/http/middleware/error-handler.mjs +52 -0
- package/dist/http/middleware/error-handler.mjs.map +1 -0
- package/dist/http/middleware/helmet.d.mts +41 -0
- package/dist/http/middleware/helmet.d.mts.map +1 -0
- package/dist/http/middleware/helmet.mjs +51 -0
- package/dist/http/middleware/helmet.mjs.map +1 -0
- package/dist/http/middleware/rate-limit.d.mts +56 -0
- package/dist/http/middleware/rate-limit.d.mts.map +1 -0
- package/dist/http/middleware/rate-limit.mjs +101 -0
- package/dist/http/middleware/rate-limit.mjs.map +1 -0
- package/dist/http/middleware/request-id.d.mts +10 -0
- package/dist/http/middleware/request-id.d.mts.map +1 -0
- package/dist/http/middleware/request-id.mjs +26 -0
- package/dist/http/middleware/request-id.mjs.map +1 -0
- package/dist/http/middleware/request-logger.d.mts +32 -0
- package/dist/http/middleware/request-logger.d.mts.map +1 -0
- package/dist/http/middleware/request-logger.mjs +49 -0
- package/dist/http/middleware/request-logger.mjs.map +1 -0
- package/dist/http/middleware/session.d.mts +67 -0
- package/dist/http/middleware/session.d.mts.map +1 -0
- package/dist/http/middleware/session.mjs +152 -0
- package/dist/http/middleware/session.mjs.map +1 -0
- package/dist/http/middleware/spa.d.mts +101 -0
- package/dist/http/middleware/spa.d.mts.map +1 -0
- package/dist/http/middleware/spa.mjs +108 -0
- package/dist/http/middleware/spa.mjs.map +1 -0
- package/dist/http/middleware/{upload.d.ts → upload.d.mts} +21 -17
- package/dist/http/middleware/upload.d.mts.map +1 -0
- package/dist/http/middleware/upload.mjs +191 -0
- package/dist/http/middleware/upload.mjs.map +1 -0
- package/dist/http/middleware/validate.d.mts +18 -0
- package/dist/http/middleware/validate.d.mts.map +1 -0
- package/dist/http/middleware/validate.mjs +62 -0
- package/dist/http/middleware/validate.mjs.map +1 -0
- package/dist/http/middleware/views.d.mts +62 -0
- package/dist/http/middleware/views.d.mts.map +1 -0
- package/dist/http/middleware/views.mjs +65 -0
- package/dist/http/middleware/views.mjs.map +1 -0
- package/dist/http/query/index.d.mts +3 -0
- package/dist/http/query/index.mjs +12 -0
- package/dist/http/{router-builder.d.ts → router-builder.d.mts} +9 -5
- package/dist/http/router-builder.d.mts.map +1 -0
- package/dist/http/router-builder.mjs +67 -0
- package/dist/http/router-builder.mjs.map +1 -0
- package/dist/index-4VM4dUJf.d.mts +107 -0
- package/dist/index-4VM4dUJf.d.mts.map +1 -0
- package/dist/index-rnK23QBD.d.mts +184 -0
- package/dist/index-rnK23QBD.d.mts.map +1 -0
- package/dist/index.d.mts +133 -0
- package/dist/index.d.mts.map +1 -0
- package/dist/index.mjs +126 -0
- package/dist/index.mjs.map +1 -0
- package/dist/interfaces-D5ohYl6D.d.mts +52 -0
- package/dist/interfaces-D5ohYl6D.d.mts.map +1 -0
- package/dist/logger-BLdfUF5b.d.mts +119 -0
- package/dist/logger-BLdfUF5b.d.mts.map +1 -0
- package/dist/metadata-BqXgNTOf.mjs +76 -0
- package/dist/metadata-BqXgNTOf.mjs.map +1 -0
- package/dist/{core/path.d.ts → path-Dq5V-i-x.d.mts} +7 -3
- package/dist/path-Dq5V-i-x.d.mts.map +1 -0
- package/dist/plugin-D20muJwC.d.mts +95 -0
- package/dist/plugin-D20muJwC.d.mts.map +1 -0
- package/dist/query-vljPDFaZ.mjs +164 -0
- package/dist/query-vljPDFaZ.mjs.map +1 -0
- package/dist/{core/reactivity.d.ts → reactivity-CMAQh0gi.d.mts} +21 -20
- package/dist/reactivity-CMAQh0gi.d.mts.map +1 -0
- package/package.json +73 -43
- package/dist/chunk-DVVP7zzD.js +0 -7
- package/dist/core/adapter.d.ts +0 -109
- package/dist/core/adapter.d.ts.map +0 -1
- package/dist/core/adapter.js +0 -0
- package/dist/core/app-module.d.ts +0 -28
- package/dist/core/app-module.d.ts.map +0 -1
- package/dist/core/app-module.js +0 -0
- package/dist/core/cache.d.ts.map +0 -1
- package/dist/core/cache.js +0 -57
- package/dist/core/container.d.ts +0 -63
- package/dist/core/container.d.ts.map +0 -1
- package/dist/core/container.js +0 -117
- package/dist/core/cron.d.ts.map +0 -1
- package/dist/core/cron.js +0 -22
- package/dist/core/decorators.d.ts +0 -153
- package/dist/core/decorators.d.ts.map +0 -1
- package/dist/core/decorators.js +0 -141
- package/dist/core/errors.d.ts +0 -64
- package/dist/core/errors.d.ts.map +0 -1
- package/dist/core/errors.js +0 -67
- package/dist/core/index.d.ts +0 -14
- package/dist/core/index.d.ts.map +0 -1
- package/dist/core/interfaces.d.ts +0 -44
- package/dist/core/interfaces.d.ts.map +0 -1
- package/dist/core/interfaces.js +0 -25
- package/dist/core/logger.d.ts +0 -43
- package/dist/core/logger.d.ts.map +0 -1
- package/dist/core/logger.js +0 -54
- package/dist/core/path.d.ts.map +0 -1
- package/dist/core/path.js +0 -12
- package/dist/core/plugin.d.ts +0 -90
- package/dist/core/plugin.d.ts.map +0 -1
- package/dist/core/plugin.js +0 -0
- package/dist/core/reactivity.d.ts.map +0 -1
- package/dist/core/reactivity.js +0 -101
- package/dist/core-B6Okew3W.js +0 -7
- package/dist/http/application.d.ts +0 -103
- package/dist/http/application.d.ts.map +0 -1
- package/dist/http/application.js +0 -167
- package/dist/http/bootstrap.d.ts +0 -22
- package/dist/http/bootstrap.d.ts.map +0 -1
- package/dist/http/bootstrap.js +0 -40
- package/dist/http/context.d.ts +0 -129
- package/dist/http/context.d.ts.map +0 -1
- package/dist/http/context.js +0 -115
- package/dist/http/index.d.ts +0 -16
- package/dist/http/index.d.ts.map +0 -1
- package/dist/http/middleware/cors.d.ts +0 -43
- package/dist/http/middleware/cors.d.ts.map +0 -1
- package/dist/http/middleware/cors.js +0 -31
- package/dist/http/middleware/csrf.d.ts +0 -47
- package/dist/http/middleware/csrf.d.ts.map +0 -1
- package/dist/http/middleware/csrf.js +0 -25
- package/dist/http/middleware/error-handler.d.ts +0 -6
- package/dist/http/middleware/error-handler.d.ts.map +0 -1
- package/dist/http/middleware/error-handler.js +0 -37
- package/dist/http/middleware/helmet.d.ts +0 -36
- package/dist/http/middleware/helmet.d.ts.map +0 -1
- package/dist/http/middleware/helmet.js +0 -20
- package/dist/http/middleware/rate-limit.d.ts +0 -51
- package/dist/http/middleware/rate-limit.d.ts.map +0 -1
- package/dist/http/middleware/rate-limit.js +0 -46
- package/dist/http/middleware/request-id.d.ts +0 -5
- package/dist/http/middleware/request-id.d.ts.map +0 -1
- package/dist/http/middleware/request-id.js +0 -12
- package/dist/http/middleware/request-logger.d.ts +0 -27
- package/dist/http/middleware/request-logger.d.ts.map +0 -1
- package/dist/http/middleware/request-logger.js +0 -16
- package/dist/http/middleware/session.d.ts +0 -62
- package/dist/http/middleware/session.d.ts.map +0 -1
- package/dist/http/middleware/session.js +0 -76
- package/dist/http/middleware/spa.d.ts +0 -93
- package/dist/http/middleware/spa.d.ts.map +0 -1
- package/dist/http/middleware/spa.js +0 -52
- package/dist/http/middleware/upload.d.ts.map +0 -1
- package/dist/http/middleware/upload.js +0 -119
- package/dist/http/middleware/validate.d.ts +0 -13
- package/dist/http/middleware/validate.d.ts.map +0 -1
- package/dist/http/middleware/validate.js +0 -45
- package/dist/http/middleware/views.d.ts +0 -56
- package/dist/http/middleware/views.d.ts.map +0 -1
- package/dist/http/middleware/views.js +0 -18
- package/dist/http/query/index.d.ts +0 -4
- package/dist/http/query/index.d.ts.map +0 -1
- package/dist/http/query/index.js +0 -10
- package/dist/http/query/parse-query.d.ts +0 -44
- package/dist/http/query/parse-query.d.ts.map +0 -1
- package/dist/http/query/types.d.ts +0 -100
- package/dist/http/query/types.d.ts.map +0 -1
- package/dist/http/router-builder.d.ts.map +0 -1
- package/dist/http/router-builder.js +0 -37
- package/dist/index.d.ts +0 -25
- package/dist/index.d.ts.map +0 -1
- package/dist/index.js +0 -103
- package/dist/query-Bym31XRp.js +0 -88
|
@@ -0,0 +1,219 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* @forinda/kickjs v2.2.0
|
|
3
|
+
*
|
|
4
|
+
* Copyright (c) Felix Orinda
|
|
5
|
+
*
|
|
6
|
+
* This source code is licensed under the MIT license found in the
|
|
7
|
+
* LICENSE file in the root directory of this source tree.
|
|
8
|
+
*
|
|
9
|
+
* @license MIT
|
|
10
|
+
*/
|
|
11
|
+
import { METADATA, Scope } from "./interfaces.mjs";
|
|
12
|
+
import { c as pushClassMeta, d as setInMetaMap, f as setInMetaRecord, l as pushMethodMeta, p as setMethodMeta, u as setClassMeta } from "../metadata-BqXgNTOf.mjs";
|
|
13
|
+
import { t as Container } from "../container-B7jFEbPE.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
|
+
* @param path - **Deprecated.** The path parameter is no longer used for routing.
|
|
76
|
+
* Route prefixes are defined by the module's `routes().path` — the single source
|
|
77
|
+
* of truth for where routes are mounted. This parameter will be removed in a
|
|
78
|
+
* future major version.
|
|
79
|
+
*/
|
|
80
|
+
function Controller(path) {
|
|
81
|
+
return (target) => {
|
|
82
|
+
setClassMeta(METADATA.CLASS_KIND, "controller", target);
|
|
83
|
+
registerInContainer(target, Scope.SINGLETON);
|
|
84
|
+
setClassMeta(METADATA.CONTROLLER_PATH, path || "/", target);
|
|
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
|
+
/**
|
|
100
|
+
* Constructor parameter injection with an explicit token.
|
|
101
|
+
*
|
|
102
|
+
* **Constructor parameters only** — does not work as a property decorator.
|
|
103
|
+
* For property injection with a token, use `@Autowired(token)` instead.
|
|
104
|
+
*/
|
|
105
|
+
function Inject(token) {
|
|
106
|
+
return (target, _propertyKey, parameterIndex) => {
|
|
107
|
+
setInMetaRecord(METADATA.INJECT, target, parameterIndex, token);
|
|
108
|
+
};
|
|
109
|
+
}
|
|
110
|
+
/**
|
|
111
|
+
* Inject an environment variable value. Evaluated lazily so the env
|
|
112
|
+
* is available at access time, not at decoration time.
|
|
113
|
+
*
|
|
114
|
+
* If no default is provided and the env var is missing, throws at access time
|
|
115
|
+
* to catch misconfiguration early instead of returning undefined.
|
|
116
|
+
*
|
|
117
|
+
* Uses metadata + instance getter to work correctly with `useDefineForClassFields`.
|
|
118
|
+
*
|
|
119
|
+
* Type-safety:
|
|
120
|
+
* - Without `kick typegen` run, any string key is accepted (back-compat).
|
|
121
|
+
* - After typegen, `KickEnv` is populated and unknown keys become a tsc
|
|
122
|
+
* error. The optional `defaultValue` is type-checked against the
|
|
123
|
+
* schema's inferred type for that key.
|
|
124
|
+
*/
|
|
125
|
+
function Value(envKey, defaultValue) {
|
|
126
|
+
return (target, propertyKey) => {
|
|
127
|
+
setInMetaMap(METADATA.VALUE, target, propertyKey, {
|
|
128
|
+
envKey,
|
|
129
|
+
defaultValue
|
|
130
|
+
});
|
|
131
|
+
};
|
|
132
|
+
}
|
|
133
|
+
function createRouteDecorator(method) {
|
|
134
|
+
return (path, validation) => {
|
|
135
|
+
return (target, propertyKey) => {
|
|
136
|
+
pushClassMeta(METADATA.ROUTES, target.constructor, {
|
|
137
|
+
method,
|
|
138
|
+
path: path || "/",
|
|
139
|
+
handlerName: propertyKey,
|
|
140
|
+
validation
|
|
141
|
+
});
|
|
142
|
+
};
|
|
143
|
+
};
|
|
144
|
+
}
|
|
145
|
+
const Get = createRouteDecorator("GET");
|
|
146
|
+
const Post = createRouteDecorator("POST");
|
|
147
|
+
const Put = createRouteDecorator("PUT");
|
|
148
|
+
const Delete = createRouteDecorator("DELETE");
|
|
149
|
+
const Patch = createRouteDecorator("PATCH");
|
|
150
|
+
/**
|
|
151
|
+
* Normalize a query params config to the string-based ApiQueryParamsConfig.
|
|
152
|
+
* Handles both string-based and column-object-based configs.
|
|
153
|
+
*/
|
|
154
|
+
function normalizeApiQueryParamsConfig(config) {
|
|
155
|
+
if ("columns" in config && config.columns && typeof config.columns === "object") return {
|
|
156
|
+
filterable: Object.keys(config.columns),
|
|
157
|
+
sortable: config.sortable ? Object.keys(config.sortable) : void 0,
|
|
158
|
+
searchable: config.searchColumns ? config.searchColumns.map((col) => col?.name ?? "").filter(Boolean) : void 0
|
|
159
|
+
};
|
|
160
|
+
return config;
|
|
161
|
+
}
|
|
162
|
+
/**
|
|
163
|
+
* Document the query parameters accepted by a GET endpoint.
|
|
164
|
+
* Used by SwaggerAdapter to generate `filter`, `sort`, `page`, `limit`, and `q` params
|
|
165
|
+
* in the OpenAPI spec, with descriptions listing the allowed fields.
|
|
166
|
+
*
|
|
167
|
+
* Accepts both string-based configs and column-object configs (e.g., DrizzleQueryParamsConfig).
|
|
168
|
+
*
|
|
169
|
+
* @example
|
|
170
|
+
* ```ts
|
|
171
|
+
* // String-based
|
|
172
|
+
* @ApiQueryParams({
|
|
173
|
+
* filterable: ['status', 'category', 'price'],
|
|
174
|
+
* sortable: ['name', 'createdAt', 'price'],
|
|
175
|
+
* searchable: ['name', 'description'],
|
|
176
|
+
* })
|
|
177
|
+
*
|
|
178
|
+
* // Column-object-based (Drizzle)
|
|
179
|
+
* @ApiQueryParams(TASK_QUERY_CONFIG)
|
|
180
|
+
* ```
|
|
181
|
+
*/
|
|
182
|
+
function ApiQueryParams(config) {
|
|
183
|
+
return (target, propertyKey) => {
|
|
184
|
+
const normalized = normalizeApiQueryParamsConfig(config);
|
|
185
|
+
setMethodMeta(METADATA.QUERY_PARAMS, normalized, target.constructor, propertyKey);
|
|
186
|
+
};
|
|
187
|
+
}
|
|
188
|
+
/** Attach middleware handlers to a class or method */
|
|
189
|
+
function Middleware(...handlers) {
|
|
190
|
+
return (target, propertyKey) => {
|
|
191
|
+
if (propertyKey) pushMethodMeta(METADATA.METHOD_MIDDLEWARES, target.constructor, propertyKey, ...handlers);
|
|
192
|
+
else pushClassMeta(METADATA.CLASS_MIDDLEWARES, target, ...handlers);
|
|
193
|
+
};
|
|
194
|
+
}
|
|
195
|
+
/** Configure file upload handling for a controller method */
|
|
196
|
+
function FileUpload(config) {
|
|
197
|
+
return (target, propertyKey) => {
|
|
198
|
+
setMethodMeta(METADATA.FILE_UPLOAD, config, target.constructor, propertyKey);
|
|
199
|
+
};
|
|
200
|
+
}
|
|
201
|
+
/** Add a static builder() method for fluent construction */
|
|
202
|
+
function Builder(target) {
|
|
203
|
+
setClassMeta(METADATA.BUILDER, true, target);
|
|
204
|
+
target.builder = function() {
|
|
205
|
+
const props = {};
|
|
206
|
+
const proxy = new Proxy({}, { get(_, key) {
|
|
207
|
+
if (key === "build") return () => Object.assign(new target(), props);
|
|
208
|
+
return (value) => {
|
|
209
|
+
props[key] = value;
|
|
210
|
+
return proxy;
|
|
211
|
+
};
|
|
212
|
+
} });
|
|
213
|
+
return proxy;
|
|
214
|
+
};
|
|
215
|
+
}
|
|
216
|
+
//#endregion
|
|
217
|
+
export { ApiQueryParams, Autowired, Builder, Component, Controller, Delete, FileUpload, Get, Inject, Injectable, Middleware, Patch, Post, PostConstruct, Put, Repository, Service, Value, normalizeApiQueryParamsConfig };
|
|
218
|
+
|
|
219
|
+
//# sourceMappingURL=decorators.mjs.map
|
|
@@ -0,0 +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 } from './container'\nimport {\n setClassMeta,\n setMethodMeta,\n getClassMeta,\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 * @param path - **Deprecated.** The path parameter is no longer used for routing.\n * Route prefixes are defined by the module's `routes().path` — the single source\n * of truth for where routes are mounted. This parameter will be removed in a\n * future major version.\n */\nexport function Controller(path?: string): ClassDecorator {\n return (target: any) => {\n setClassMeta(METADATA.CLASS_KIND, 'controller', target)\n registerInContainer(target, Scope.SINGLETON)\n setClassMeta(METADATA.CONTROLLER_PATH, path || '/', target)\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 */\nexport function Inject(token: any): 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// ── 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-http` for full type safety:\n *\n * ```ts\n * import type { MiddlewareHandler } from '@forinda/kickjs-core'\n * import type { RequestContext } from '@forinda/kickjs-http'\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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"}
|
|
@@ -0,0 +1,97 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* @forinda/kickjs v2.2.0
|
|
3
|
+
*
|
|
4
|
+
* Copyright (c) Felix Orinda
|
|
5
|
+
*
|
|
6
|
+
* This source code is licensed under the MIT license found in the
|
|
7
|
+
* LICENSE file in the root directory of this source tree.
|
|
8
|
+
*
|
|
9
|
+
* @license MIT
|
|
10
|
+
*/
|
|
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 and optional validation details.
|
|
51
|
+
* Provides static factory methods for common HTTP errors.
|
|
52
|
+
*/
|
|
53
|
+
var HttpException = class HttpException extends Error {
|
|
54
|
+
constructor(status, message, details) {
|
|
55
|
+
super(message);
|
|
56
|
+
this.status = status;
|
|
57
|
+
this.details = details;
|
|
58
|
+
this.name = "HttpException";
|
|
59
|
+
}
|
|
60
|
+
/** Create from a Zod error */
|
|
61
|
+
static fromZodError(error, message) {
|
|
62
|
+
const firstIssue = error.issues?.[0];
|
|
63
|
+
return new HttpException(HttpStatus.UNPROCESSABLE_ENTITY, message || firstIssue?.message || "Validation failed", [...(error.issues || []).map((issue) => ({
|
|
64
|
+
field: issue.path?.join(".") || "",
|
|
65
|
+
message: issue.message,
|
|
66
|
+
code: issue.code
|
|
67
|
+
}))]);
|
|
68
|
+
}
|
|
69
|
+
static badRequest(message = "Bad Request") {
|
|
70
|
+
return new HttpException(HttpStatus.BAD_REQUEST, message);
|
|
71
|
+
}
|
|
72
|
+
static unauthorized(message = "Unauthorized") {
|
|
73
|
+
return new HttpException(HttpStatus.UNAUTHORIZED, message);
|
|
74
|
+
}
|
|
75
|
+
static forbidden(message = "Forbidden") {
|
|
76
|
+
return new HttpException(HttpStatus.FORBIDDEN, message);
|
|
77
|
+
}
|
|
78
|
+
static notFound(message = "Not Found") {
|
|
79
|
+
return new HttpException(HttpStatus.NOT_FOUND, message);
|
|
80
|
+
}
|
|
81
|
+
static conflict(message = "Conflict") {
|
|
82
|
+
return new HttpException(HttpStatus.CONFLICT, message);
|
|
83
|
+
}
|
|
84
|
+
static unprocessable(message = "Unprocessable Entity", details) {
|
|
85
|
+
return new HttpException(HttpStatus.UNPROCESSABLE_ENTITY, message, details);
|
|
86
|
+
}
|
|
87
|
+
static tooManyRequests(message = "Too Many Requests") {
|
|
88
|
+
return new HttpException(HttpStatus.TOO_MANY_REQUESTS, message);
|
|
89
|
+
}
|
|
90
|
+
static internal(message = "Internal Server Error") {
|
|
91
|
+
return new HttpException(HttpStatus.INTERNAL_SERVER_ERROR, message);
|
|
92
|
+
}
|
|
93
|
+
};
|
|
94
|
+
//#endregion
|
|
95
|
+
export { HttpException, HttpStatus };
|
|
96
|
+
|
|
97
|
+
//# sourceMappingURL=errors.mjs.map
|
|
@@ -0,0 +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 */\nexport interface ValidationError {\n field: string\n message: string\n code?: string\n}\n\n/**\n * Typed HTTP exception with status code and optional validation details.\n * Provides static factory methods for common HTTP errors.\n */\nexport class HttpException extends Error {\n constructor(\n public readonly status: number,\n message: string,\n public readonly details?: ValidationError[],\n ) {\n super(message)\n this.name = 'HttpException'\n }\n\n /** Create from a Zod error */\n static fromZodError(error: any, message?: string): HttpException {\n const firstIssue = error.issues?.[0]\n return new HttpException(\n HttpStatus.UNPROCESSABLE_ENTITY,\n message || firstIssue?.message || 'Validation failed',\n [\n ...(error.issues || []).map((issue: any) => ({\n field: issue.path?.join('.') || '',\n message: issue.message,\n code: issue.code,\n })),\n ],\n )\n }\n\n static badRequest(message = 'Bad Request') {\n return new HttpException(HttpStatus.BAD_REQUEST, message)\n }\n static unauthorized(message = 'Unauthorized') {\n return new HttpException(HttpStatus.UNAUTHORIZED, message)\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 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') {\n return new HttpException(HttpStatus.TOO_MANY_REQUESTS, message)\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;;;;;AAeD,IAAa,gBAAb,MAAa,sBAAsB,MAAM;CACvC,YACE,QACA,SACA,SACA;AACA,QAAM,QAAQ;AAJE,OAAA,SAAA;AAEA,OAAA,UAAA;AAGhB,OAAK,OAAO;;;CAId,OAAO,aAAa,OAAY,SAAiC;EAC/D,MAAM,aAAa,MAAM,SAAS;AAClC,SAAO,IAAI,cACT,WAAW,sBACX,WAAW,YAAY,WAAW,qBAClC,CACE,IAAI,MAAM,UAAU,EAAE,EAAE,KAAK,WAAgB;GAC3C,OAAO,MAAM,MAAM,KAAK,IAAI,IAAI;GAChC,SAAS,MAAM;GACf,MAAM,MAAM;GACb,EAAE,CACJ,CACF;;CAGH,OAAO,WAAW,UAAU,eAAe;AACzC,SAAO,IAAI,cAAc,WAAW,aAAa,QAAQ;;CAE3D,OAAO,aAAa,UAAU,gBAAgB;AAC5C,SAAO,IAAI,cAAc,WAAW,cAAc,QAAQ;;CAE5D,OAAO,UAAU,UAAU,aAAa;AACtC,SAAO,IAAI,cAAc,WAAW,WAAW,QAAQ;;CAEzD,OAAO,SAAS,UAAU,aAAa;AACrC,SAAO,IAAI,cAAc,WAAW,WAAW,QAAQ;;CAEzD,OAAO,SAAS,UAAU,YAAY;AACpC,SAAO,IAAI,cAAc,WAAW,UAAU,QAAQ;;CAExD,OAAO,cAAc,UAAU,wBAAwB,SAA6B;AAClF,SAAO,IAAI,cAAc,WAAW,sBAAsB,SAAS,QAAQ;;CAE7E,OAAO,gBAAgB,UAAU,qBAAqB;AACpD,SAAO,IAAI,cAAc,WAAW,mBAAmB,QAAQ;;CAEjE,OAAO,SAAS,UAAU,yBAAyB;AACjD,SAAO,IAAI,cAAc,WAAW,uBAAuB,QAAQ"}
|
|
@@ -0,0 +1,3 @@
|
|
|
1
|
+
|
|
2
|
+
import { a as METADATA, c as Scope, i as Constructor, l as ServiceOptions, n as BuilderOf, o as MaybePromise, r as ClassKind, s as PostConstructStatus, t as Buildable } from "../interfaces-D5ohYl6D.mjs";
|
|
3
|
+
export { Buildable, BuilderOf, ClassKind, Constructor, METADATA, MaybePromise, PostConstructStatus, Scope, ServiceOptions };
|
|
@@ -0,0 +1,44 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* @forinda/kickjs v2.2.0
|
|
3
|
+
*
|
|
4
|
+
* Copyright (c) Felix Orinda
|
|
5
|
+
*
|
|
6
|
+
* This source code is licensed under the MIT license found in the
|
|
7
|
+
* LICENSE file in the root directory of this source tree.
|
|
8
|
+
*
|
|
9
|
+
* @license MIT
|
|
10
|
+
*/
|
|
11
|
+
import "reflect-metadata";
|
|
12
|
+
//#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
|
+
/** Symbol-based metadata keys for the DI system */
|
|
22
|
+
const METADATA = {
|
|
23
|
+
INJECTABLE: Symbol("kick:injectable"),
|
|
24
|
+
SCOPE: Symbol("kick:scope"),
|
|
25
|
+
CLASS_KIND: Symbol("kick:class-kind"),
|
|
26
|
+
AUTOWIRED: Symbol("kick:autowired"),
|
|
27
|
+
INJECT: Symbol("kick:inject"),
|
|
28
|
+
POST_CONSTRUCT: Symbol("kick:post_construct"),
|
|
29
|
+
BUILDER: Symbol("kick:builder"),
|
|
30
|
+
QUERY_PARAMS: Symbol("kick:query:params"),
|
|
31
|
+
CONTROLLER_PATH: Symbol("kick:controller:path"),
|
|
32
|
+
ROUTES: Symbol("kick:routes"),
|
|
33
|
+
CLASS_MIDDLEWARES: Symbol("kick:class:middlewares"),
|
|
34
|
+
METHOD_MIDDLEWARES: Symbol("kick:method:middlewares"),
|
|
35
|
+
FILE_UPLOAD: Symbol("kick:file:upload"),
|
|
36
|
+
VALUE: Symbol("kick:value"),
|
|
37
|
+
PARAM_TYPES: "design:paramtypes",
|
|
38
|
+
PROPERTY_TYPE: "design:type",
|
|
39
|
+
RETURN_TYPE: "design:returntype"
|
|
40
|
+
};
|
|
41
|
+
//#endregion
|
|
42
|
+
export { METADATA, Scope };
|
|
43
|
+
|
|
44
|
+
//# sourceMappingURL=interfaces.mjs.map
|
|
@@ -0,0 +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/** Symbol-based metadata keys for the DI system */\nexport const METADATA = {\n INJECTABLE: Symbol('kick:injectable'),\n SCOPE: Symbol('kick:scope'),\n CLASS_KIND: Symbol('kick:class-kind'),\n AUTOWIRED: Symbol('kick:autowired'),\n INJECT: Symbol('kick:inject'),\n POST_CONSTRUCT: Symbol('kick:post_construct'),\n BUILDER: Symbol('kick:builder'),\n QUERY_PARAMS: Symbol('kick:query:params'),\n CONTROLLER_PATH: Symbol('kick:controller:path'),\n ROUTES: Symbol('kick:routes'),\n CLASS_MIDDLEWARES: Symbol('kick:class:middlewares'),\n METHOD_MIDDLEWARES: Symbol('kick:method:middlewares'),\n FILE_UPLOAD: Symbol('kick:file:upload'),\n VALUE: Symbol('kick:value'),\n // TypeScript emit metadata keys\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;;AAsCD,MAAa,WAAW;CACtB,YAAY,OAAO,kBAAkB;CACrC,OAAO,OAAO,aAAa;CAC3B,YAAY,OAAO,kBAAkB;CACrC,WAAW,OAAO,iBAAiB;CACnC,QAAQ,OAAO,cAAc;CAC7B,gBAAgB,OAAO,sBAAsB;CAC7C,SAAS,OAAO,eAAe;CAC/B,cAAc,OAAO,oBAAoB;CACzC,iBAAiB,OAAO,uBAAuB;CAC/C,QAAQ,OAAO,cAAc;CAC7B,mBAAmB,OAAO,yBAAyB;CACnD,oBAAoB,OAAO,0BAA0B;CACrD,aAAa,OAAO,mBAAmB;CACvC,OAAO,OAAO,aAAa;CAE3B,aAAa;CACb,eAAe;CACf,aAAa;CACd"}
|
|
@@ -0,0 +1,217 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* @forinda/kickjs v2.2.0
|
|
3
|
+
*
|
|
4
|
+
* Copyright (c) Felix Orinda
|
|
5
|
+
*
|
|
6
|
+
* This source code is licensed under the MIT license found in the
|
|
7
|
+
* LICENSE file in the root directory of this source tree.
|
|
8
|
+
*
|
|
9
|
+
* @license MIT
|
|
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
|
+
this.provider.trace ? this.provider.trace(msg, ...args) : this.provider.debug(msg, ...args);
|
|
203
|
+
}
|
|
204
|
+
fatal(msg, ...args) {
|
|
205
|
+
this.provider.fatal ? this.provider.fatal(msg, ...args) : this.provider.error(msg, ...args);
|
|
206
|
+
}
|
|
207
|
+
};
|
|
208
|
+
/** Shorthand for Logger.for(name) */
|
|
209
|
+
function createLogger(name) {
|
|
210
|
+
return Logger.for(name);
|
|
211
|
+
}
|
|
212
|
+
/** @deprecated Use rootLogger instead */
|
|
213
|
+
const logger = rootLogger;
|
|
214
|
+
//#endregion
|
|
215
|
+
export { ConsoleLoggerProvider, Logger, createLogger, logger, rootLogger };
|
|
216
|
+
|
|
217
|
+
//# sourceMappingURL=logger.mjs.map
|