@forinda/kickjs 10.3.0 → 10.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/adapter-BZ1WzN1z.d.mts +2354 -0
- package/dist/adapter-BZ1WzN1z.d.mts.map +1 -0
- package/dist/{app-module-Ftz6m7SO.d.mts → app-module-Cuu-Ma_E.d.mts} +5 -4
- package/dist/app-module-Cuu-Ma_E.d.mts.map +1 -0
- package/dist/{application-B2e5XYHm.mjs → application-Bs30gJF1.mjs} +4 -4
- package/dist/application-Bs30gJF1.mjs.map +1 -0
- package/dist/application-D5Iiy7rt.d.mts +1996 -0
- package/dist/application-D5Iiy7rt.d.mts.map +1 -0
- package/dist/bootstrap-B_sGJNSz.mjs +12 -0
- package/dist/{bootstrap-BmALF-1Y.mjs.map → bootstrap-B_sGJNSz.mjs.map} +1 -1
- package/dist/{bounded-counters-aA3iI_Ei.mjs → bounded-counters-DS-IbDW9.mjs} +2 -2
- package/dist/{bounded-counters-aA3iI_Ei.mjs.map → bounded-counters-DS-IbDW9.mjs.map} +1 -1
- package/dist/{client-ip-D2dsx8RG.mjs → client-ip-BLkoQTIR.mjs} +2 -2
- package/dist/{client-ip-D2dsx8RG.mjs.map → client-ip-BLkoQTIR.mjs.map} +1 -1
- package/dist/config/index.d.mts +1 -1
- package/dist/config/index.mjs +2 -2
- package/dist/{config-B77LTW_E.mjs → config-B6EeAw4P.mjs} +3 -3
- package/dist/{config-B77LTW_E.mjs.map → config-B6EeAw4P.mjs.map} +1 -1
- package/dist/container-4iJdDkRH.d.mts +3 -0
- package/dist/context-CRJzl_Mj.mjs +12 -0
- package/dist/context-CRJzl_Mj.mjs.map +1 -0
- package/dist/{context-errors-CPqYYhl0.mjs → context-errors-CR5NCXfl.mjs} +2 -2
- package/dist/{context-errors-CPqYYhl0.mjs.map → context-errors-CR5NCXfl.mjs.map} +1 -1
- package/dist/{contributor-runner-Cl5yZZy1.mjs → contributor-runner--ofCRZ0d.mjs} +3 -3
- package/dist/{contributor-runner-Cl5yZZy1.mjs.map → contributor-runner--ofCRZ0d.mjs.map} +1 -1
- package/dist/core/adapter.d.mts +1 -1
- package/dist/core/adapter.mjs +1 -1
- package/dist/core/app-module.d.mts +1 -1
- package/dist/core/app-module.mjs +1 -1
- package/dist/core/cache.mjs +1 -1
- package/dist/core/container.d.mts +2 -2
- package/dist/core/container.mjs +2 -2
- package/dist/core/cron.mjs +2 -2
- package/dist/core/decorators.d.mts +2 -2
- package/dist/core/decorators.mjs +2 -2
- package/dist/core/decorators.mjs.map +1 -1
- package/dist/core/errors.mjs +1 -1
- package/dist/core/interfaces.d.mts +2 -2
- package/dist/core/interfaces.mjs +2 -2
- package/dist/core/interfaces.mjs.map +1 -1
- package/dist/core/logger.mjs +1 -1
- package/dist/core/path.mjs +1 -1
- package/dist/core/plugin.d.mts +1 -1
- package/dist/core/plugin.mjs +1 -1
- package/dist/core/reactivity.mjs +1 -1
- package/dist/core-CsMDdzNE.mjs +12 -0
- package/dist/{core-D1AV-Tvd.mjs.map → core-CsMDdzNE.mjs.map} +1 -1
- package/dist/{csrf-Cy1meSpf.d.mts → csrf-BDAZK2mm.d.mts} +2 -2
- package/dist/{csrf-Cy1meSpf.d.mts.map → csrf-BDAZK2mm.d.mts.map} +1 -1
- package/dist/decorate-CLeX6hbL.mjs +13 -0
- package/dist/{decorate-BiXL-9e9.mjs.map → decorate-CLeX6hbL.mjs.map} +1 -1
- package/dist/{decorators-DaQUNXOn.d.mts → decorators-Dvy0JZ5L.d.mts} +8 -200
- package/dist/decorators-Dvy0JZ5L.d.mts.map +1 -0
- package/dist/{define-adapter-D22SDe0U.mjs → define-adapter-RbKRSG3i.mjs} +2 -2
- package/dist/{define-adapter-D22SDe0U.mjs.map → define-adapter-RbKRSG3i.mjs.map} +1 -1
- package/dist/di-hooks-CiNaIu12.mjs +132 -0
- package/dist/di-hooks-CiNaIu12.mjs.map +1 -0
- package/dist/disposables-DYTkgNiG.mjs +11 -0
- package/dist/error-handler-CbP7hKdJ.d.mts +63 -0
- package/dist/error-handler-CbP7hKdJ.d.mts.map +1 -0
- package/dist/{handler-gW_h2miq.mjs → handler-Cw4mr3ls.mjs} +3 -3
- package/dist/{handler-gW_h2miq.mjs.map → handler-Cw4mr3ls.mjs.map} +1 -1
- package/dist/{host-D__uZPyz.mjs → host-H7CIkHNB.mjs} +2 -2
- package/dist/{host-D__uZPyz.mjs.map → host-H7CIkHNB.mjs.map} +1 -1
- package/dist/http/application.d.mts +2 -2
- package/dist/http/application.mjs +2 -2
- package/dist/http/bootstrap.d.mts +1 -1
- package/dist/http/bootstrap.mjs +2 -2
- package/dist/http/context.d.mts +2 -2
- package/dist/http/context.mjs +2 -2
- package/dist/http/middleware/allowed-hosts.mjs +2 -2
- package/dist/http/middleware/breach-padding.mjs +1 -1
- package/dist/http/middleware/cors.mjs +1 -1
- package/dist/http/middleware/csrf.d.mts +1 -1
- package/dist/http/middleware/csrf.mjs +3 -2
- package/dist/http/middleware/csrf.mjs.map +1 -0
- package/dist/http/middleware/error-handler.d.mts +1 -1
- package/dist/http/middleware/error-handler.mjs +2 -2
- package/dist/http/middleware/error-handler.mjs.map +1 -1
- package/dist/http/middleware/helmet.mjs +1 -1
- package/dist/http/middleware/rate-limit.mjs +2 -2
- package/dist/http/middleware/request-id.mjs +1 -1
- package/dist/http/middleware/request-logger.mjs +2 -2
- package/dist/http/middleware/session.mjs +2 -2
- package/dist/http/middleware/spa.d.mts +1 -1
- package/dist/http/middleware/spa.mjs +2 -2
- package/dist/http/middleware/upload.d.mts +1 -1
- package/dist/http/middleware/upload.mjs +2 -2
- package/dist/http/middleware/validate.mjs +1 -1
- package/dist/http/middleware/views.d.mts +1 -1
- package/dist/http/middleware/views.mjs +2 -2
- package/dist/http/query/index.d.mts +2 -2
- package/dist/http/query/index.mjs +2 -2
- package/dist/http/router-builder.d.mts +1 -1
- package/dist/http/router-builder.mjs +2 -2
- package/dist/http/runtimes/fastify.d.mts +1 -1
- package/dist/http/runtimes/fastify.mjs +2 -2
- package/dist/http/runtimes/h3-web.mjs +1 -1
- package/dist/http/runtimes/h3.d.mts +1 -1
- package/dist/http/runtimes/h3.mjs +2 -2
- package/dist/{index-CuiWSnZL.d.mts → index-B4aOLoId.d.mts} +4 -4
- package/dist/{index-CuiWSnZL.d.mts.map → index-B4aOLoId.d.mts.map} +1 -1
- package/dist/{index-BfT5KZ-M.d.mts → index-Blgka75E.d.mts} +63 -4
- package/dist/index-Blgka75E.d.mts.map +1 -0
- package/dist/index.d.mts +17 -11
- package/dist/index.mjs +4 -4
- package/dist/index.mjs.map +1 -1
- package/dist/interfaces-C6LHcYsg.d.mts +34 -0
- package/dist/interfaces-C6LHcYsg.d.mts.map +1 -0
- package/dist/is-production-BTroGhp5.mjs +12 -0
- package/dist/is-production-BTroGhp5.mjs.map +1 -0
- package/dist/jobs-xqoMmdr4.mjs +12 -0
- package/dist/{jobs-s4__kZLr.mjs.map → jobs-xqoMmdr4.mjs.map} +1 -1
- package/dist/{kv-stores-Cjel_Dkc.mjs → kv-stores-0-6blGzh.mjs} +3 -3
- package/dist/{kv-stores-Cjel_Dkc.mjs.map → kv-stores-0-6blGzh.mjs.map} +1 -1
- package/dist/kv-stores-DXFBEYYu.d.mts +390 -0
- package/dist/kv-stores-DXFBEYYu.d.mts.map +1 -0
- package/dist/{lazy-serve-static-w94Xs3wQ.mjs → lazy-serve-static-D94xvah5.mjs} +2 -2
- package/dist/{lazy-serve-static-w94Xs3wQ.mjs.map → lazy-serve-static-D94xvah5.mjs.map} +1 -1
- package/dist/metadata-Bm65Y-5O.mjs +11 -0
- package/dist/{observers-boPE9XGi.mjs → observers-BAXkwMx0.mjs} +2 -2
- package/dist/{observers-boPE9XGi.mjs.map → observers-BAXkwMx0.mjs.map} +1 -1
- package/dist/query-CGyw7vNi.mjs +12 -0
- package/dist/query-CGyw7vNi.mjs.map +1 -0
- package/dist/{reply-CYY_CzRf.mjs → reply-tlUaowib.mjs} +3 -3
- package/dist/{reply-CYY_CzRf.mjs.map → reply-tlUaowib.mjs.map} +1 -1
- package/dist/{respond-Dc18G0X7.mjs → respond-BOlh-baJ.mjs} +2 -2
- package/dist/{respond-Dc18G0X7.mjs.map → respond-BOlh-baJ.mjs.map} +1 -1
- package/dist/{route-flag-BOQZs2Wn.mjs → route-flag-BPSq2JCs.mjs} +3 -3
- package/dist/{route-flag-BOQZs2Wn.mjs.map → route-flag-BPSq2JCs.mjs.map} +1 -1
- package/dist/{route-policy-B8c6QfiU.mjs → route-policy-DDszB6dQ.mjs} +2 -2
- package/dist/{route-policy-B8c6QfiU.mjs.map → route-policy-DDszB6dQ.mjs.map} +1 -1
- package/dist/router-builder-BewIsj7V.d.mts +56 -0
- package/dist/router-builder-BewIsj7V.d.mts.map +1 -0
- package/dist/router-builder-DoaDAmK8.mjs +12 -0
- package/dist/{router-builder-DoWOIGmG.mjs.map → router-builder-DoaDAmK8.mjs.map} +1 -1
- package/dist/{settings-C8VKewNS.d.mts → settings-BnE75hnr.d.mts} +2 -2
- package/dist/{settings-C8VKewNS.d.mts.map → settings-BnE75hnr.d.mts.map} +1 -1
- package/dist/settings-CRkMOwcz.mjs +14 -0
- package/dist/{settings-DcytOCC6.mjs.map → settings-CRkMOwcz.mjs.map} +1 -1
- package/dist/token-2CJq89za.mjs +11 -0
- package/dist/token-D6jfTQLA.d.mts +3 -0
- package/dist/upload-DkT2p1gd.d.mts +104 -0
- package/dist/upload-DkT2p1gd.d.mts.map +1 -0
- package/dist/{upload-config-CzxbJALL.mjs → upload-config-Be7w0Dfx.mjs} +2 -2
- package/dist/{upload-config-CzxbJALL.mjs.map → upload-config-Be7w0Dfx.mjs.map} +1 -1
- package/dist/url-for-EQsmb3yi.mjs +12 -0
- package/dist/url-for-EQsmb3yi.mjs.map +1 -0
- package/dist/web-crypto-G-m6c6w2.mjs +12 -0
- package/dist/web-crypto-G-m6c6w2.mjs.map +1 -0
- package/dist/web.d.mts +6 -5
- package/dist/web.d.mts.map +1 -1
- package/dist/web.mjs +2 -2
- package/dist/web.mjs.map +1 -1
- package/package.json +2 -1
- package/dist/adapter-BYdxuKiM.d.mts +0 -4916
- package/dist/adapter-BYdxuKiM.d.mts.map +0 -1
- package/dist/app-module-Ftz6m7SO.d.mts.map +0 -1
- package/dist/application-B2e5XYHm.mjs.map +0 -1
- package/dist/bootstrap-BmALF-1Y.mjs +0 -12
- package/dist/container-Dpvd66Yt.d.mts +0 -298
- package/dist/container-Dpvd66Yt.d.mts.map +0 -1
- package/dist/container-mvaAYThX.mjs +0 -132
- package/dist/container-mvaAYThX.mjs.map +0 -1
- package/dist/context-GbQnJB-L.mjs +0 -12
- package/dist/context-GbQnJB-L.mjs.map +0 -1
- package/dist/core-D1AV-Tvd.mjs +0 -12
- package/dist/csrf-D3prC4FK.mjs +0 -12
- package/dist/csrf-D3prC4FK.mjs.map +0 -1
- package/dist/decorate-BiXL-9e9.mjs +0 -13
- package/dist/decorators-DaQUNXOn.d.mts.map +0 -1
- package/dist/disposables-CJD_gWlA.mjs +0 -12
- package/dist/disposables-CJD_gWlA.mjs.map +0 -1
- package/dist/index-BfT5KZ-M.d.mts.map +0 -1
- package/dist/interfaces-C1hCSoLD.d.mts +0 -75
- package/dist/interfaces-C1hCSoLD.d.mts.map +0 -1
- package/dist/is-production-Dbm13WNL.mjs +0 -12
- package/dist/is-production-Dbm13WNL.mjs.map +0 -1
- package/dist/jobs-s4__kZLr.mjs +0 -12
- package/dist/metadata-C2GK_17k.mjs +0 -12
- package/dist/metadata-C2GK_17k.mjs.map +0 -1
- package/dist/query-DjTeF1d4.mjs +0 -12
- package/dist/query-DjTeF1d4.mjs.map +0 -1
- package/dist/router-builder-DoWOIGmG.mjs +0 -12
- package/dist/settings-DcytOCC6.mjs +0 -14
- package/dist/url-for-DGSrVfdD.mjs +0 -12
- package/dist/url-for-DGSrVfdD.mjs.map +0 -1
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
|
|
2
|
-
import {
|
|
3
|
-
import { l as ServiceOptions, n as BuilderOf } from "./interfaces-C1hCSoLD.mjs";
|
|
2
|
+
import { n as InjectionToken } from "./token-D6jfTQLA.mjs";
|
|
4
3
|
import "reflect-metadata";
|
|
4
|
+
import { Autowired, Builder, Component, Env, EnvKey, Inject, Injectable, PostConstruct, PreDestroy, PropertyOrParameterDecorator, Repository, Service, Value, withBuilder } from "@forinda/kickjs-di";
|
|
5
5
|
//#region src/core/assets.d.ts
|
|
6
6
|
declare const ASSET_MANIFEST_VERSION: 1;
|
|
7
7
|
/**
|
|
@@ -57,14 +57,6 @@ declare const assets: KickAssets;
|
|
|
57
57
|
declare function useAssets(): KickAssets;
|
|
58
58
|
//#endregion
|
|
59
59
|
//#region src/core/decorators.d.ts
|
|
60
|
-
/** Mark a class as injectable with lifecycle scope */
|
|
61
|
-
declare function Injectable(options?: ServiceOptions): ClassDecorator;
|
|
62
|
-
/** Mark a class as a service (semantic alias for Injectable) */
|
|
63
|
-
declare function Service(options?: ServiceOptions): ClassDecorator;
|
|
64
|
-
/** Mark a class as a generic managed component */
|
|
65
|
-
declare function Component(options?: ServiceOptions): ClassDecorator;
|
|
66
|
-
/** Mark a class as a repository */
|
|
67
|
-
declare function Repository(options?: ServiceOptions): ClassDecorator;
|
|
68
60
|
/**
|
|
69
61
|
* Mark a class as an HTTP controller and register it in the DI container.
|
|
70
62
|
*
|
|
@@ -75,152 +67,6 @@ declare function Repository(options?: ServiceOptions): ClassDecorator;
|
|
|
75
67
|
* the rename map.
|
|
76
68
|
*/
|
|
77
69
|
declare function Controller(): ClassDecorator;
|
|
78
|
-
/** Mark a method as a lifecycle hook called after instantiation */
|
|
79
|
-
declare function PostConstruct(): MethodDecorator;
|
|
80
|
-
/**
|
|
81
|
-
* Mark a method as a teardown hook — the counterpart to {@link PostConstruct}.
|
|
82
|
-
*
|
|
83
|
-
* For REQUEST-scoped services it runs when the request's scope closes
|
|
84
|
-
* (response finished or aborted): release per-request resources there
|
|
85
|
-
* (transactions, handles, subscriptions). May be async; errors are logged
|
|
86
|
-
* and swallowed so one failing hook can't break request completion.
|
|
87
|
-
*
|
|
88
|
-
* It does NOT run on a SINGLETON — the default scope — because nothing closes
|
|
89
|
-
* a singleton's scope. Unlike {@link PostConstruct}, which does run for
|
|
90
|
-
* singletons, so the pair is not symmetric. Applying it to a singleton logs a
|
|
91
|
-
* warning naming the class rather than failing silently.
|
|
92
|
-
*
|
|
93
|
-
* For application-lifetime resources (a connection pool, a timer, a socket
|
|
94
|
-
* server) use an adapter's `shutdown()` hook, which the framework runs on a
|
|
95
|
-
* real shutdown AND on every HMR reload, time-boxed and concurrent.
|
|
96
|
-
*/
|
|
97
|
-
declare function PreDestroy(): MethodDecorator;
|
|
98
|
-
/**
|
|
99
|
-
* A decorator that's valid as either a property decorator OR a
|
|
100
|
-
* constructor-parameter decorator. forinda/kick-js#235 §2 — `@Autowired`
|
|
101
|
-
* and `@Inject` previously diverged at the type level (property-only
|
|
102
|
-
* vs parameter-only) and adopters who picked the wrong name for the
|
|
103
|
-
* position got a cryptic TS1240 error. Both names now accept either
|
|
104
|
-
* position and route to the correct metadata bucket at runtime.
|
|
105
|
-
*/
|
|
106
|
-
interface PropertyOrParameterDecorator {
|
|
107
|
-
/** Property decorator form — `@Autowired(TOKEN) private foo!: Foo`. */
|
|
108
|
-
(target: object, propertyKey: string | symbol): void;
|
|
109
|
-
/** Constructor-parameter form — `constructor(@Inject(TOKEN) foo: Foo) {}`. */
|
|
110
|
-
(target: object, propertyKey: string | symbol | undefined, parameterIndex: number): void;
|
|
111
|
-
}
|
|
112
|
-
/**
|
|
113
|
-
* Inject a dependency. Works in two positions:
|
|
114
|
-
*
|
|
115
|
-
* - **Property decorator** — `@Autowired(TOKEN) private repo!: UserRepo`.
|
|
116
|
-
* Resolved lazily from the container the first time the property is
|
|
117
|
-
* read.
|
|
118
|
-
* - **Constructor parameter decorator** — `constructor(@Autowired(TOKEN) repo: UserRepo) {}`.
|
|
119
|
-
* Resolved at instantiation; injected into the ctor call.
|
|
120
|
-
*
|
|
121
|
-
* `@Inject` is the same function under another name — they share
|
|
122
|
-
* runtime + types so the two names are interchangeable. Pick whichever
|
|
123
|
-
* reads better at the call site.
|
|
124
|
-
*
|
|
125
|
-
* Like `@Inject`, the typed string-literal overload narrows the token
|
|
126
|
-
* to a key of the augmented `KickJsRegistry`. After `kick typegen`
|
|
127
|
-
* populates the registry, `@Autowired('kick/prisma/Client')` auto-
|
|
128
|
-
* completes the key and typo'd literals become TS2345 errors.
|
|
129
|
-
*/
|
|
130
|
-
declare function Autowired<K extends keyof KickJsRegistry & string>(token: K): PropertyOrParameterDecorator;
|
|
131
|
-
declare function Autowired(token?: unknown): PropertyOrParameterDecorator;
|
|
132
|
-
/**
|
|
133
|
-
* Inject a dependency by token. Same shape as {@link Autowired} —
|
|
134
|
-
* works as either a property decorator or a constructor-parameter
|
|
135
|
-
* decorator. Pick whichever name reads better at the call site.
|
|
136
|
-
*
|
|
137
|
-
* ## Typed string-literal overload
|
|
138
|
-
*
|
|
139
|
-
* When called with a string literal that matches a key of the
|
|
140
|
-
* augmented `KickJsRegistry`, TypeScript narrows the parameter type
|
|
141
|
-
* to the registered type. Typo'd literals become compile errors
|
|
142
|
-
* (the string isn't `keyof KickJsRegistry`). Class identities and
|
|
143
|
-
* `InjectionToken<T>` keep working unchanged via the second overload.
|
|
144
|
-
*
|
|
145
|
-
* @example
|
|
146
|
-
* ```ts
|
|
147
|
-
* import { Service, Inject } from '@forinda/kickjs'
|
|
148
|
-
* import type { PrismaClient } from '@prisma/client'
|
|
149
|
-
*
|
|
150
|
-
* `@Service()`
|
|
151
|
-
* class UserRepo {
|
|
152
|
-
* constructor(@Inject('kick/prisma/Client') private db: PrismaClient) {}
|
|
153
|
-
* // OR property form, same decorator:
|
|
154
|
-
* @Inject('kick/prisma/Client') private db2!: PrismaClient
|
|
155
|
-
* }
|
|
156
|
-
* ```
|
|
157
|
-
*
|
|
158
|
-
* After `kick typegen` runs, the literal autocompletes from the
|
|
159
|
-
* registry and a typo (`@Inject('kick/prisma/Cleint')`) becomes a
|
|
160
|
-
* TS2345 error.
|
|
161
|
-
*/
|
|
162
|
-
declare function Inject<K extends keyof KickJsRegistry & string>(token: K): PropertyOrParameterDecorator;
|
|
163
|
-
declare function Inject(token?: unknown): PropertyOrParameterDecorator;
|
|
164
|
-
/**
|
|
165
|
-
* Global ambient registry of typed environment variables, populated by
|
|
166
|
-
* `kick typegen` from the project's env schema (typically
|
|
167
|
-
* `src/env.ts`'s `export default defineEnv(...)`).
|
|
168
|
-
*
|
|
169
|
-
* Empty by default — declarations come from `.kickjs/types/env.ts`
|
|
170
|
-
* generated alongside the rest of the typegen output. Once populated,
|
|
171
|
-
* `@Value('PORT')` autocompletes the key, type-checks the default
|
|
172
|
-
* value, and `process.env.PORT` is also typed via the parallel
|
|
173
|
-
* `NodeJS.ProcessEnv` augmentation in the same generated file.
|
|
174
|
-
*/
|
|
175
|
-
declare global {
|
|
176
|
-
interface KickEnv {}
|
|
177
|
-
}
|
|
178
|
-
/** A string key known to the typed env registry (`never` until typegen runs) */
|
|
179
|
-
type EnvKey = keyof KickEnv & string;
|
|
180
|
-
/**
|
|
181
|
-
* Look up the type of a typed env entry.
|
|
182
|
-
*
|
|
183
|
-
* Decorators can't propagate the property type from the key, so users
|
|
184
|
-
* still need to write the property's type — but `Env<K>` lets them
|
|
185
|
-
* derive it from `KickEnv` instead of duplicating the schema:
|
|
186
|
-
*
|
|
187
|
-
* ```ts
|
|
188
|
-
* @Service()
|
|
189
|
-
* class MyService {
|
|
190
|
-
* @Value('PORT')
|
|
191
|
-
* private port!: Env<'PORT'> // → number, narrowed from KickEnv['PORT']
|
|
192
|
-
* }
|
|
193
|
-
* ```
|
|
194
|
-
*/
|
|
195
|
-
type Env<K extends EnvKey = EnvKey> = KickEnv[K];
|
|
196
|
-
/**
|
|
197
|
-
* Constraint that allows any string when the typed env registry is
|
|
198
|
-
* empty (no `kick typegen` has run yet, so existing code with raw
|
|
199
|
-
* string keys keeps working) but locks the argument down to known
|
|
200
|
-
* `EnvKey` literals once the registry is populated.
|
|
201
|
-
*
|
|
202
|
-
* Implementation: when `EnvKey` is `never`, the conditional resolves
|
|
203
|
-
* to the user's `K`, accepting anything. Once typegen has populated
|
|
204
|
-
* `KickEnv`, `EnvKey` becomes a real union and the conditional forces
|
|
205
|
-
* `K` to be assignable to it.
|
|
206
|
-
*/
|
|
207
|
-
type ValueKey<K extends string> = [EnvKey] extends [never] ? K : K & EnvKey;
|
|
208
|
-
/**
|
|
209
|
-
* Inject an environment variable value. Evaluated lazily so the env
|
|
210
|
-
* is available at access time, not at decoration time.
|
|
211
|
-
*
|
|
212
|
-
* If no default is provided and the env var is missing, throws at access time
|
|
213
|
-
* to catch misconfiguration early instead of returning undefined.
|
|
214
|
-
*
|
|
215
|
-
* Uses metadata + instance getter to work correctly with `useDefineForClassFields`.
|
|
216
|
-
*
|
|
217
|
-
* Type-safety:
|
|
218
|
-
* - Without `kick typegen` run, any string key is accepted (back-compat).
|
|
219
|
-
* - After typegen, `KickEnv` is populated and unknown keys become a tsc
|
|
220
|
-
* error. The optional `defaultValue` is type-checked against the
|
|
221
|
-
* schema's inferred type for that key.
|
|
222
|
-
*/
|
|
223
|
-
declare function Value<K extends string>(envKey: ValueKey<K>, defaultValue?: K extends EnvKey ? KickEnv[K] : unknown): PropertyDecorator;
|
|
224
70
|
/**
|
|
225
71
|
* Flatten the nested `KickAssets` augmentation (typegen-emitted in
|
|
226
72
|
* PR 4) into a string-literal union of dot/slash-joined paths.
|
|
@@ -361,8 +207,12 @@ declare function ApiQueryParams(config: ApiQueryParamsConfig | ColumnApiQueryPar
|
|
|
361
207
|
* next()
|
|
362
208
|
* }
|
|
363
209
|
* ```
|
|
210
|
+
*
|
|
211
|
+
* A guard stops the request by writing a response and not calling `next()`.
|
|
212
|
+
* Whatever it returns is ignored, so `if (!user) return ctx.problem.unauthorized()`
|
|
213
|
+
* — the idiom handlers use — type-checks here too.
|
|
364
214
|
*/
|
|
365
|
-
type MiddlewareHandler<TCtx = any> = (ctx: TCtx, next: () => void) =>
|
|
215
|
+
type MiddlewareHandler<TCtx = any> = (ctx: TCtx, next: () => void) => unknown;
|
|
366
216
|
/** Attach middleware handlers to a class or method */
|
|
367
217
|
declare function Middleware(...handlers: MiddlewareHandler[]): ClassDecorator & MethodDecorator;
|
|
368
218
|
/**
|
|
@@ -395,48 +245,6 @@ interface FileUploadConfig extends BaseUploadOptions {
|
|
|
395
245
|
}
|
|
396
246
|
/** Configure file upload handling for a controller method */
|
|
397
247
|
declare function FileUpload(config: FileUploadConfig): MethodDecorator;
|
|
398
|
-
/**
|
|
399
|
-
* Add a static `builder()` method for fluent construction.
|
|
400
|
-
*
|
|
401
|
-
* Legacy decorators cannot widen the class type, so by default the
|
|
402
|
-
* caller sees the unmodified shape. Opt into typing by adding a single
|
|
403
|
-
* `declare static` line:
|
|
404
|
-
*
|
|
405
|
-
* ```ts
|
|
406
|
-
* @Builder
|
|
407
|
-
* class UserDto {
|
|
408
|
-
* name!: string
|
|
409
|
-
* email!: string
|
|
410
|
-
* declare static readonly builder: () => BuilderOf<UserDto>
|
|
411
|
-
* }
|
|
412
|
-
* ```
|
|
413
|
-
*
|
|
414
|
-
* `readonly` keeps SonarQube's `typescript:S1444` quiet — the runtime
|
|
415
|
-
* assigns `target.builder` once at decoration time and never again.
|
|
416
|
-
*
|
|
417
|
-
* If you'd rather not write the `declare`, use `withBuilder()` instead —
|
|
418
|
-
* same runtime, types inferred automatically.
|
|
419
|
-
*/
|
|
420
|
-
declare function Builder(target: any): void;
|
|
421
|
-
/**
|
|
422
|
-
* Factory variant of `@Builder`. Wraps the class with the same runtime
|
|
423
|
-
* and returns it intersected with `{ builder(): BuilderOf<T> }` so the
|
|
424
|
-
* static is fully typed without any `declare` boilerplate.
|
|
425
|
-
*
|
|
426
|
-
* ```ts
|
|
427
|
-
* class UserDtoBase {
|
|
428
|
-
* name!: string
|
|
429
|
-
* email!: string
|
|
430
|
-
* }
|
|
431
|
-
* export const UserDto = withBuilder(UserDtoBase)
|
|
432
|
-
* export type UserDto = InstanceType<typeof UserDto>
|
|
433
|
-
*
|
|
434
|
-
* UserDto.builder().name('Alice').email('a@b.com').build() // fully typed
|
|
435
|
-
* ```
|
|
436
|
-
*/
|
|
437
|
-
declare function withBuilder<C extends new (...args: any[]) => any>(ctor: C): C & {
|
|
438
|
-
builder(): BuilderOf<InstanceType<C>>;
|
|
439
|
-
};
|
|
440
248
|
//#endregion
|
|
441
249
|
export { Service as A, resolveAsset as B, Post as C, Put as D, PropertyOrParameterDecorator as E, ASSET_MANIFEST_VERSION as F, KickAssets as I, UnknownAssetError as L, normalizeApiQueryParamsConfig as M, withBuilder as N, Repository as O, ASSETS as P, assets as R, Patch as S, PreDestroy as T, useAssets as V, Get as _, Autowired as a, Middleware as b, ColumnApiQueryParamsConfig as c, Delete as d, Env as f, FileUploadConfig as g, FileUpload as h, AssetKey as i, Value as j, RouteDefinition as k, Component as l, FileTypeFilter as m, ApiQueryParamsConfig as n, BaseUploadOptions as o, EnvKey as p, Asset as r, Builder as s, ApiQueryParams as t, Controller as u, Inject as v, PostConstruct as w, MiddlewareHandler as x, Injectable as y, clearAssetCache as z };
|
|
442
|
-
//# sourceMappingURL=decorators-
|
|
250
|
+
//# sourceMappingURL=decorators-Dvy0JZ5L.d.mts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"decorators-Dvy0JZ5L.d.mts","names":[],"sources":["../src/core/assets.ts","../src/core/decorators.ts"],"mappings":";;;;;cA8Ba;;;;;;;;UAmBI;;;;;;;cAQJ,QAAQ,eAAe;cAEvB,0BAA0B;WAC5B;WACA;EACT,YAAY,mBAAmB;;iBAmCjB,aAAa,mBAAmB;;iBAchC;;;;;;;;;;;cA6TH,QAAQ;;;;;;;;;;;;;;;;;iBAkBL,aAAa;;;;;;;;;;;;iBCtZb,cAAc;;;;;;;;;;;;KAsBzB,cAAc,GAAG,iCACnB,WAAW,aAAa,EAAE,+BACpB,SAAS,MACZ,EAAE,WAAW,0BACX,cAAc,EAAE,OAAO,SAAS,uBAEhC;;KAGI,WAAW,cAAc;;;;;;;KAQhC,YAAY,qBAAqB,4BAA4B,IAAI,IAAI;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;iBAmC1D,MAAM,kBAAkB,UAAU,YAAY,KAAK;UAQlD;EACf;EACA;EACA;EACA;;IAEE;;IAEA;;IAEA;;;;;;;IAOA;;IAEA;;;cAiBS,MAAG,eAZO,aAAe,kCAAgC;cAazD,OAAI,eAbM,aAAe,kCAAgC;cAczD,MAAG,eAdO,aAAe,kCAAgC;cAezD,SAAM,eAfI,aAAe,kCAAgC;cAgBzD,QAAK,eAhBK,aAAe,kCAAgC;UAoBrD;;EAEf;;EAEA;;EAEA;;;;;;UAOe;EACf,SAAS;EACT,WAAW;EACX;GACC;;;;;;iBAOa,8BACd,QAAQ,uBAAuB,6BAC9B;;;;;;;;;;;;;;;;;;;;;iBAiCa,eACd,QAAQ,uBAAuB,6BAC9B;;;;;;;;;;;;;;;;;;;;KA4BS,kBAAkB,eAAe,KAAK,MAAM;;iBAGxC,cAAc,UAAU,sBAAsB,iBAAiB;;;;;KAqBnE,8BAA8B,kBAAkB;;;;;UAM3C;;EAEf;;;;;;EAMA,eAAe;;EAEf,gBAAgB;;UAGD,yBAAyB;EACxC;;EAEA;;EAEA;;;iBAIc,WAAW,QAAQ,mBAAmB"}
|
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
/**
|
|
2
|
-
* @forinda/kickjs v10.
|
|
2
|
+
* @forinda/kickjs v10.4.0
|
|
3
3
|
*
|
|
4
4
|
* Copyright (c) Felix Orinda
|
|
5
5
|
*
|
|
@@ -9,4 +9,4 @@
|
|
|
9
9
|
* @license MIT
|
|
10
10
|
*/
|
|
11
11
|
const mergeConfig=(defaults={},overrides={})=>({...defaults,...overrides}),composeName=(base,scope)=>`${base}:${scope}`;function defineAdapter(options){let buildSync=(instanceName,scoped,overrides)=>{let config=mergeConfig(options.defaults,overrides),built=options.build(config,{name:instanceName,scoped});return built.name=instanceName,built},buildAsync=(instanceName,opts)=>{let inner;return{name:instanceName,async beforeStart(ctx){let deps=(opts.inject??[]).map(tok=>ctx.container.resolve(tok)),config=await opts.useFactory(...deps);inner=buildSync(instanceName,!1,config),await inner.beforeStart?.(ctx)},async afterStart(ctx){await inner?.afterStart?.(ctx)},async shutdown(){await inner?.shutdown?.()},async onHealthCheck(){return await inner?.onHealthCheck?.()??{name:instanceName,status:`up`}}}},factory=(config=>buildSync(options.name,!1,config));return factory.scoped=(scopeName,config)=>buildSync(composeName(options.name,scopeName),!0,config),factory.async=opts=>buildAsync(options.name,opts),Object.defineProperty(factory,"definition",{value:Object.freeze({...options})}),factory}export{defineAdapter as t};
|
|
12
|
-
//# sourceMappingURL=define-adapter-
|
|
12
|
+
//# sourceMappingURL=define-adapter-RbKRSG3i.mjs.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"define-adapter-
|
|
1
|
+
{"version":3,"file":"define-adapter-RbKRSG3i.mjs","names":[],"sources":["../src/core/define-adapter.ts"],"sourcesContent":["import type { AppAdapter, AdapterContext } from './adapter'\nimport type { BuildContext } from './define-plugin'\n\n/**\n * Options passed to {@link defineAdapter}. Mirrors {@link DefinePluginOptions}\n * exactly — see `architecture.md` §21.3.4 for the definePlugin/defineAdapter\n * symmetry rationale.\n *\n * The optional `TExtra` generic lets an adapter ship public methods\n * beyond the standard {@link AppAdapter} contract — they're preserved\n * on the returned adapter instance so external callers (tests, peer\n * adapters) can invoke them directly. See `OtelAdapter.applyRedaction`\n * for the canonical use case.\n */\nexport interface DefineAdapterOptions<TConfig, TExtra = unknown> {\n /**\n * Stable identity used for logging, `dependsOn` lookups, and `.scoped()`\n * namespacing. Required for adapters that participate in `dependsOn`\n * sort — error messages reference adapters by name.\n */\n name: string\n version?: string\n requires?: { kickjs?: string }\n defaults?: Partial<TConfig>\n build(config: TConfig, ctx: BuildContext): Omit<AppAdapter, 'name'> & TExtra\n}\n\n/**\n * Async-config form of an adapter. Identical shape to `PluginAsyncOptions`\n * but resolved during `beforeStart` (the earliest async hook in\n * `AppAdapter`) — meaning `middleware()` and `contributors()` from the inner\n * adapter are **not** picked up. Use the bare/`.scoped()` form when you need\n * those.\n */\nexport interface AdapterAsyncOptions<TConfig> {\n inject?: ReadonlyArray<unknown>\n useFactory(...deps: any[]): TConfig | Promise<TConfig>\n}\n\n/**\n * Factory returned by {@link defineAdapter}. Same surface as\n * {@link PluginFactory} (call / `.scoped()` / `.async()`) so adopters learn\n * one mental model for both primitives. Returned instances carry both\n * the standard {@link AppAdapter} contract and any `TExtra` extension\n * methods the `build` function exposed.\n */\nexport interface AdapterFactory<TConfig, TExtra = unknown> {\n (config?: Partial<TConfig>): AppAdapter & TExtra\n scoped(scopeName: string, config?: Partial<TConfig>): AppAdapter & TExtra\n async(opts: AdapterAsyncOptions<TConfig>): AppAdapter\n readonly definition: Readonly<DefineAdapterOptions<TConfig, TExtra>>\n}\n\nconst mergeConfig = <TConfig>(\n defaults: Partial<TConfig> = {},\n overrides: Partial<TConfig> = {},\n): TConfig => ({ ...defaults, ...overrides }) as TConfig\n\nconst composeName = (base: string, scope: string): string => `${base}:${scope}`\n\n/**\n * Build an {@link AppAdapter} factory from a typed definition. See\n * `architecture.md` §21.3.4 for migration guidance — most first-party\n * adapter packages collapse to a single `defineAdapter()` call after this\n * lands.\n *\n * @example\n * ```ts\n * const TenantAdapter = defineAdapter<TenantConfig>({\n * name: 'TenantAdapter',\n * defaults: { strategy: 'header', required: true },\n * build: (config) => ({\n * middleware: () => [tenantResolverMiddleware(config)],\n * beforeStart: ({ container }) => registerTenantFactory(container, config),\n * }),\n * })\n *\n * bootstrap({\n * adapters: [\n * TenantAdapter({ strategy: 'subdomain' }),\n * TenantAdapter.scoped('shard-eu', { headerName: 'x-eu-tenant' }),\n * ],\n * })\n * ```\n */\nexport function defineAdapter<TConfig = Record<string, unknown>, TExtra = unknown>(\n options: DefineAdapterOptions<TConfig, TExtra>,\n): AdapterFactory<TConfig, TExtra> {\n const buildSync = (\n instanceName: string,\n scoped: boolean,\n overrides?: Partial<TConfig>,\n ): AppAdapter & TExtra => {\n const config = mergeConfig(options.defaults, overrides)\n // Mutate `name` on the build result instead of spreading — spread\n // strips prototype methods when `build()` returns a class instance.\n // Extension methods declared by the build function (`TExtra`) survive\n // the mutation since they're own properties on the build result.\n const built = options.build(config, { name: instanceName, scoped }) as AppAdapter & TExtra\n ;(built as AppAdapter).name = instanceName\n return built\n }\n\n const buildAsync = (instanceName: string, opts: AdapterAsyncOptions<TConfig>): AppAdapter => {\n let inner: AppAdapter | undefined\n\n return {\n name: instanceName,\n async beforeStart(ctx: AdapterContext) {\n const deps = (opts.inject ?? []).map((tok) => ctx.container.resolve(tok as never))\n const config = await opts.useFactory(...deps)\n inner = buildSync(instanceName, false, config as Partial<TConfig>)\n await inner.beforeStart?.(ctx)\n },\n async afterStart(ctx: AdapterContext) {\n await inner?.afterStart?.(ctx)\n },\n async shutdown() {\n await inner?.shutdown?.()\n },\n async onHealthCheck() {\n return (await inner?.onHealthCheck?.()) ?? { name: instanceName, status: 'up' }\n },\n }\n }\n\n const factory = ((config?: Partial<TConfig>) =>\n buildSync(options.name, false, config)) as AdapterFactory<TConfig, TExtra>\n\n factory.scoped = (scopeName: string, config?: Partial<TConfig>) =>\n buildSync(composeName(options.name, scopeName), true, config)\n\n factory.async = (opts: AdapterAsyncOptions<TConfig>) => buildAsync(options.name, opts)\n\n Object.defineProperty(factory, 'definition', { value: Object.freeze({ ...options }) })\n\n return factory\n}\n"],"mappings":";;;;;;;;;;AAqDA,MAAM,aACJ,SAA6B,CAAC,EAC9B,UAA8B,CAAC,KAClB,CAAE,GAAG,SAAU,GAAG,SAAU,GAErC,aAAe,KAAc,QAA0B,GAAG,KAAK,GAAG,QA2BxE,SAAgB,cACd,QACiC,CACjC,IAAM,WACJ,aACA,OACA,YACwB,CACxB,IAAM,OAAS,YAAY,QAAQ,SAAU,SAAS,EAKhD,MAAQ,QAAQ,MAAM,OAAQ,CAAE,KAAM,aAAc,MAAO,CAAC,EAElE,MADC,OAAsB,KAAO,aACvB,KACT,EAEM,YAAc,aAAsB,OAAmD,CAC3F,IAAI,MAEJ,MAAO,CACL,KAAM,aACN,MAAM,YAAY,IAAqB,CACrC,IAAM,MAAQ,KAAK,QAAU,CAAC,EAAA,CAAG,IAAK,KAAQ,IAAI,UAAU,QAAQ,GAAY,CAAC,EAC3E,OAAS,MAAM,KAAK,WAAW,GAAG,IAAI,EAC5C,MAAQ,UAAU,aAAc,GAAO,MAA0B,EACjE,MAAM,MAAM,cAAc,GAAG,CAC/B,EACA,MAAM,WAAW,IAAqB,CACpC,MAAM,OAAO,aAAa,GAAG,CAC/B,EACA,MAAM,UAAW,CACf,MAAM,OAAO,WAAW,CAC1B,EACA,MAAM,eAAgB,CACpB,OAAQ,MAAM,OAAO,gBAAgB,GAAM,CAAE,KAAM,aAAc,OAAQ,IAAK,CAChF,CACF,CACF,EAEM,SAAY,QAChB,UAAU,QAAQ,KAAM,GAAO,MAAM,GASvC,MAPA,SAAQ,QAAU,UAAmB,SACnC,UAAU,YAAY,QAAQ,KAAM,SAAS,EAAG,GAAM,MAAM,EAE9D,QAAQ,MAAS,MAAuC,WAAW,QAAQ,KAAM,IAAI,EAErF,OAAO,eAAe,QAAS,aAAc,CAAE,MAAO,OAAO,OAAO,CAAE,GAAG,OAAQ,CAAC,CAAE,CAAC,EAE9E,OACT"}
|
|
@@ -0,0 +1,132 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* @forinda/kickjs v10.4.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}from"./core/interfaces.mjs";import{createLogger}from"./core/logger.mjs";import{Container}from"@forinda/kickjs-di";let impl=null;function _setAssetResolver(fn){impl=fn}function resolveAssetViaSlot(namespace,key){if(!impl)throw Error(`@Asset('${namespace}/${key}'): the asset manager is not loaded. Import it (any import from '@forinda/kickjs' loads it) — note @Asset reads from the filesystem and is not supported on edge runtimes.`);return impl(namespace,key)}var KickError=class extends Error{code;summary;cause;fix;docsUrl;context;constructor(init){super(formatKickError(init,{color:!1})),this.name=`KickError`,this.code=init.code,this.summary=init.summary,init.cause!==void 0&&(this.cause=init.cause),init.fix!==void 0&&(this.fix=init.fix),init.docsUrl!==void 0&&(this.docsUrl=init.docsUrl),init.context!==void 0&&(this.context=init.context)}};function ansiEnabled(){return process.env.NO_COLOR?!1:process.env.FORCE_COLOR?!0:process.stderr?.isTTY===!0}function paint(text,code,enabled){return enabled?`[${code}m${text}[0m`:text}const c={red:(s,enabled)=>paint(s,`31`,enabled),bold:(s,enabled)=>paint(s,`1`,enabled),dim:(s,enabled)=>paint(s,`2`,enabled),cyan:(s,enabled)=>paint(s,`36`,enabled),blue:(s,enabled)=>paint(s,`34`,enabled),underline:(s,enabled)=>paint(s,`4`,enabled)};function formatKickError(err,options={}){let color=options.color??ansiEnabled(),lines=[],code=c.bold(c.red(err.code,color),color);if(lines.push(`${code}: ${err.summary}`),err.cause){lines.push(``,` ${c.bold(c.dim(`Cause:`,color),color)}`);for(let line of err.cause.split(`
|
|
12
|
+
`))lines.push(` ${highlightInline(line,color)}`)}if(err.fix){lines.push(``,` ${c.bold(c.dim(`Fix:`,color),color)}`);for(let line of err.fix.split(`
|
|
13
|
+
`))lines.push(` ${highlightInline(line,color)}`)}return err.docsUrl&&(lines.push(``,` ${c.bold(c.dim(`Docs:`,color),color)}`),lines.push(` ${c.underline(c.blue(err.docsUrl,color),color)}`)),lines.join(`
|
|
14
|
+
`)}function highlightInline(line,color){return color?line.replace(/`([^`]+)`/g,(_,inner)=>`\`${c.cyan(inner,!0)}\``):line}const DOCS_BASE=`https://kickjs.app`;function noProviderError(tokenName){return new KickError({code:`KICK001`,summary:`No provider for ${tokenName}`,cause:`\`${tokenName}\` was requested from the DI container but no binding is registered.
|
|
15
|
+
This usually means one of:
|
|
16
|
+
• The class is decorated with @Service() / @Repository() / @Controller(),
|
|
17
|
+
but its enclosing module isn't passed to bootstrap({ modules: [...] }).
|
|
18
|
+
• The class isn't decorated at all (decorators register the binding).
|
|
19
|
+
• You're injecting a token (created with createToken()) that nothing
|
|
20
|
+
provides — add a Container.register(TOKEN, ...) call or a module that
|
|
21
|
+
binds it.`,fix:`If \`${tokenName}\` lives in a module, add the module to bootstrap:
|
|
22
|
+
|
|
23
|
+
bootstrap({
|
|
24
|
+
modules: [
|
|
25
|
+
UsersModule, // add this
|
|
26
|
+
OtherModule,
|
|
27
|
+
],
|
|
28
|
+
})
|
|
29
|
+
|
|
30
|
+
If it's a custom token, register it explicitly:
|
|
31
|
+
|
|
32
|
+
const TENANT_REPO = createToken<TenantRepo>('TENANT_REPO')
|
|
33
|
+
Container.getInstance().register(TENANT_REPO, { useClass: PrismaTenantRepo })`,docsUrl:`${DOCS_BASE}/guide/dependency-injection#registering-services`,context:{token:tokenName}})}function requestScopeMiddlewareMissingError(tokenName){return new KickError({code:`KICK002`,summary:`Cannot resolve REQUEST-scoped "${tokenName}" — request scope middleware not mounted`,cause:`\`${tokenName}\` has \`scope: Scope.REQUEST\` but no AsyncLocalStorage frame is wired.
|
|
34
|
+
The framework's request-scope middleware sets up that frame; without it,
|
|
35
|
+
REQUEST-scoped resolutions have nowhere to cache the per-request instance.`,fix:`Add \`requestScopeMiddleware()\` to your global middleware pipeline,
|
|
36
|
+
or let the framework auto-mount it by using \`contextStore: 'auto'\`
|
|
37
|
+
(the default — only check this if you set it to 'manual' explicitly):
|
|
38
|
+
|
|
39
|
+
bootstrap({
|
|
40
|
+
modules,
|
|
41
|
+
// contextStore: 'auto', // default; no need to set
|
|
42
|
+
})
|
|
43
|
+
|
|
44
|
+
If you set \`contextStore: 'manual'\` deliberately (rare), you own the
|
|
45
|
+
ALS wrapping — call \`requestStore.run({...}, () => ...)\` around the
|
|
46
|
+
code that resolves the binding.`,docsUrl:`${DOCS_BASE}/guide/dependency-injection#scopes`,context:{token:tokenName}})}function requestScopeOutsideRequestError(tokenName){return new KickError({code:`KICK003`,summary:`Cannot resolve REQUEST-scoped "${tokenName}" outside an HTTP request`,cause:`\`${tokenName}\` has \`scope: Scope.REQUEST\` and was resolved outside
|
|
47
|
+
any HTTP request context. The request-scope middleware is wired, but
|
|
48
|
+
the call happened before a request started (e.g. in a top-level
|
|
49
|
+
import, a constructor, a cron job, a test without setup).`,fix:`If the caller is request-scoped (controller, request-scoped service),
|
|
50
|
+
make sure the call happens inside the request lifecycle, not at module
|
|
51
|
+
load time.
|
|
52
|
+
|
|
53
|
+
In tests, wrap setup in an ALS frame manually:
|
|
54
|
+
|
|
55
|
+
import { requestStore } from '@forinda/kickjs'
|
|
56
|
+
|
|
57
|
+
requestStore.run(
|
|
58
|
+
{ requestId: 'test', instances: new Map(), values: new Map() },
|
|
59
|
+
() => {
|
|
60
|
+
const svc = container.resolve(MyRequestScopedService)
|
|
61
|
+
// ...
|
|
62
|
+
},
|
|
63
|
+
)
|
|
64
|
+
|
|
65
|
+
If the caller is a SINGLETON, change \`${tokenName}\` to TRANSIENT or
|
|
66
|
+
SINGLETON scope, or inject a factory instead of the instance directly.`,docsUrl:`${DOCS_BASE}/guide/dependency-injection#scopes`,context:{token:tokenName}})}function envValueMissingError(envKey){return new KickError({code:`KICK004`,summary:`@Value('${envKey}'): environment variable not set and no default provided`,cause:`\`@Value('${envKey}')\` resolved but the env var isn't present and the
|
|
67
|
+
decorator didn't declare a default. Possible reasons:
|
|
68
|
+
• The variable is genuinely missing from your environment / .env file.
|
|
69
|
+
• Your \`src/env.ts\` calls \`loadEnv(envSchema)\` but \`src/index.ts\`
|
|
70
|
+
doesn't import \`./env\` before \`bootstrap()\`. Without that import
|
|
71
|
+
the schema never runs and ConfigService stays empty — \`@Value\`
|
|
72
|
+
only finds the var via the \`process.env\` fallback.`,fix:`Either set the variable in your shell / .env file:
|
|
73
|
+
|
|
74
|
+
${envKey}=...
|
|
75
|
+
|
|
76
|
+
Or add a default at the decorator:
|
|
77
|
+
|
|
78
|
+
@Value('${envKey}', { default: 'fallback' })
|
|
79
|
+
private value!: string
|
|
80
|
+
|
|
81
|
+
If you're using a schema, make sure \`src/env.ts\` is imported from
|
|
82
|
+
\`src/index.ts\` BEFORE bootstrap runs:
|
|
83
|
+
|
|
84
|
+
// src/index.ts
|
|
85
|
+
import 'reflect-metadata'
|
|
86
|
+
import './env' // ← this line is required
|
|
87
|
+
import { bootstrap } from '@forinda/kickjs'
|
|
88
|
+
// ...`,docsUrl:`${DOCS_BASE}/guide/configuration#wiring-the-schema-at-startup`,context:{envKey}})}function moduleRouteMissingControllerError(mountPath){return new KickError({code:`KICK005`,summary:`Module route at ${mountPath} requires either 'controller' or 'router'`,cause:`A module's \`routes()\` returned an entry for \`${mountPath}\` but didn't
|
|
89
|
+
specify how to build the router. The framework needs either a decorated
|
|
90
|
+
controller class (it calls \`buildRoutes()\` internally) or a hand-built
|
|
91
|
+
Express Router.`,fix:`Pass \`controller:\` for the common case:
|
|
92
|
+
|
|
93
|
+
routes() {
|
|
94
|
+
return {
|
|
95
|
+
path: '${mountPath}',
|
|
96
|
+
controller: UsersController,
|
|
97
|
+
}
|
|
98
|
+
}
|
|
99
|
+
|
|
100
|
+
Or pass \`router:\` for full control:
|
|
101
|
+
|
|
102
|
+
routes() {
|
|
103
|
+
return {
|
|
104
|
+
path: '${mountPath}',
|
|
105
|
+
router: myExpressRouter,
|
|
106
|
+
}
|
|
107
|
+
}`,docsUrl:`${DOCS_BASE}/guide/modules`,context:{mountPath}})}function duplicateRouteError(method,path,owner,prior){return new KickError({code:`KICK006`,summary:`Duplicate route: ${method} ${path} is registered twice`,cause:`\`${owner}\` registers \`${method} ${path}\`, but that verb + path is
|
|
108
|
+
already claimed by \`${prior}\`. Only one handler can win at dispatch
|
|
109
|
+
time, and which one depends on the engine — while \`kick typegen\` and
|
|
110
|
+
the typed client may describe the other. Param names are ignored when
|
|
111
|
+
comparing (\`/:id\` and \`/:taskId\` are the same route).`,fix:`Change one of the two paths, remove the duplicate handler, or mount
|
|
112
|
+
the second controller under a different module path / version:
|
|
113
|
+
|
|
114
|
+
routes() {
|
|
115
|
+
return { path: '/tasks', controller: TasksController, version: 2 }
|
|
116
|
+
}`,docsUrl:`${DOCS_BASE}/guide/modules`,context:{method,path,owner,prior}})}function http2UnsupportedRuntimeError(runtime){return new KickError({code:`KICK007`,summary:`The ${runtime} runtime cannot serve HTTP/2`,cause:`\`bootstrap({ server: { http2: true } })\` asks for an HTTP/2 server, but the
|
|
117
|
+
\`${runtime}\` runtime does not support Node's HTTP/2 compatibility layer —
|
|
118
|
+
requests would hang instead of being answered.`,fix:`Pick one:
|
|
119
|
+
• Switch to a runtime that serves HTTP/2:
|
|
120
|
+
bootstrap({ runtime: fastifyRuntime(), server: { tls, http2: true } })
|
|
121
|
+
(or h3Runtime()).
|
|
122
|
+
• Drop \`http2\` and keep HTTPS over HTTP/1.1: server: { tls }.
|
|
123
|
+
• Terminate HTTP/2 at your proxy / load balancer and serve HTTP/1.1 to it.`,docsUrl:`${DOCS_BASE}/guide/http-runtimes#https-and-http-2`,context:{runtime}})}function http2RequiresTlsError(){return new KickError({code:`KICK008`,summary:`server.http2 requires server.tls`,cause:"`bootstrap({ server: { http2: true } })` was set without `tls`. Browsers only\nnegotiate HTTP/2 over TLS, and KickJS does not serve cleartext HTTP/2 (h2c).",fix:`Pass the certificate and key alongside http2:
|
|
124
|
+
|
|
125
|
+
server: {
|
|
126
|
+
tls: { key: readFileSync('key.pem'), cert: readFileSync('cert.pem') },
|
|
127
|
+
http2: true,
|
|
128
|
+
}
|
|
129
|
+
|
|
130
|
+
Or remove \`http2\` if TLS is terminated in front of the app.`,docsUrl:`${DOCS_BASE}/guide/http-runtimes#https-and-http-2`})}function tlsCredentialsError(problem){return new KickError({code:`KICK009`,summary:`server.tls is not usable: ${problem}`,cause:`\`bootstrap({ server: { tls } })\` was given TLS options the server cannot use:
|
|
131
|
+
${problem}. Node would start anyway and fail every TLS handshake.`,fix:"Give the server an identity:\n • `key` and `cert` together (PEM, matching each other), or\n • `pfx` (with `passphrase` if it is encrypted), or\n • `SNICallback` / `pskCallback` for per-host or PSK setups.\n\n server: { tls: { key: readFileSync('key.pem'), cert: readFileSync('cert.pem') } }",docsUrl:`${DOCS_BASE}/guide/http-runtimes#https-and-http-2`,context:{problem}})}const CATALOGUE={KICK001:noProviderError,KICK002:requestScopeMiddlewareMissingError,KICK003:requestScopeOutsideRequestError,KICK004:envValueMissingError};Container._error=(code,subject)=>CATALOGUE[code](subject),Container._logger=createLogger(`Container`),Container._propertyInjectors.set(METADATA.ASSET,({assetKey})=>{let slash=assetKey.indexOf(`/`);if(slash===-1)throw Error(`@Asset('${assetKey}'): asset key must include a '/' separator (e.g. 'mails/welcome').`);let namespace=assetKey.slice(0,slash),key=assetKey.slice(slash+1);return()=>resolveAssetViaSlot(namespace,key)});export{tlsCredentialsError as a,_setAssetResolver as c,moduleRouteMissingControllerError as i,http2RequiresTlsError as n,KickError as o,http2UnsupportedRuntimeError as r,formatKickError as s,duplicateRouteError as t};
|
|
132
|
+
//# sourceMappingURL=di-hooks-CiNaIu12.mjs.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"di-hooks-CiNaIu12.mjs","names":[],"sources":["../src/core/asset-resolver-slot.ts","../src/core/kick-error.ts","../src/core/kick-errors.ts","../src/core/di-hooks.ts"],"sourcesContent":["/**\n * Indirection slot between the DI container's `@Asset` property injection\n * and the asset manager. The container must NOT import `./assets` directly —\n * its eager `node:fs`/`node:path` imports would poison the edge-safe\n * `@forinda/kickjs/web` entry graph (every graph includes the container).\n *\n * `./assets` registers the real resolver at module scope, so any node app\n * that imports the asset manager (the core barrel does) gets full `@Asset`\n * behavior; an edge bundle that never imports it gets a clear error on\n * first `@Asset` property access instead of a broken bundle.\n */\n\ntype AssetResolver = (namespace: string, key: string) => unknown\n\nlet impl: AssetResolver | null = null\n\n/** Called by `./assets` at module scope to install the real resolver. */\nexport function _setAssetResolver(fn: AssetResolver): void {\n impl = fn\n}\n\n/** Resolve an asset through the slot — throws when no asset manager is loaded. */\nexport function resolveAssetViaSlot(namespace: string, key: string): unknown {\n if (!impl) {\n throw new Error(\n `@Asset('${namespace}/${key}'): the asset manager is not loaded. ` +\n \"Import it (any import from '@forinda/kickjs' loads it) — note @Asset \" +\n 'reads from the filesystem and is not supported on edge runtimes.',\n )\n }\n return impl(namespace, key)\n}\n","/**\n * Structured framework error with code, cause, and actionable fix hint.\n *\n * The goal is \"the developer who hits this knows what to do next.\" A\n * cryptic `Error('No binding found for: UserService')` becomes a\n * multi-line explanation pointing at the likely cause, the exact code\n * change to apply, and a docs link.\n *\n * `.message` carries the full multi-line plain-text body so Node's\n * default `Error.toString()` and unhandled-exception printing still\n * surface the helpful version. Call {@link formatKickError} to render a\n * colorized version for terminals.\n *\n * Per-error factories live in `kick-errors.ts` — those are the public\n * entry points framework code uses. `KickError` is exported so adopters\n * can build their own structured errors using the same shape.\n */\nexport interface KickErrorInit {\n /** Short stable identifier (e.g. `KICK001`, `NO_PROVIDER`). */\n code: string\n /** One-line headline. */\n summary: string\n /** Multi-line explanation of why this happened. */\n cause?: string\n /** Multi-line actionable fix — show exact code if possible. */\n fix?: string\n /** Absolute URL to the docs page that covers this error. */\n docsUrl?: string\n /** Arbitrary structured fields for log consumers / debug tooling. */\n context?: Record<string, unknown>\n}\n\nexport class KickError extends Error {\n public readonly code: string\n public readonly summary: string\n public readonly cause?: string\n public readonly fix?: string\n public readonly docsUrl?: string\n public readonly context?: Record<string, unknown>\n\n constructor(init: KickErrorInit) {\n super(formatKickError(init, { color: false }))\n this.name = 'KickError'\n this.code = init.code\n this.summary = init.summary\n if (init.cause !== undefined) this.cause = init.cause\n if (init.fix !== undefined) this.fix = init.fix\n if (init.docsUrl !== undefined) this.docsUrl = init.docsUrl\n if (init.context !== undefined) this.context = init.context\n }\n}\n\n// ── ANSI colour helpers ────────────────────────────────────────────────\n\n/**\n * `true` when the runtime can render ANSI escape codes on stderr.\n * Honors `NO_COLOR` (https://no-color.org) and `FORCE_COLOR`.\n */\nfunction ansiEnabled(): boolean {\n if (process.env.NO_COLOR) return false\n if (process.env.FORCE_COLOR) return true\n // Node sets `isTTY` on the writable streams when stdout/stderr is a\n // terminal. KickError output goes to stderr conceptually (it's an\n // error), so we follow that stream's affordances.\n return process.stderr?.isTTY === true\n}\n\n// Use the Unicode-escape form (`\u001b`) rather than the hex-escape (`\\x1b`)\n// for the ANSI ESC byte — both produce the same character, but oxlint's\n// `no-control-character` rule flags the hex form as \"unexpected control\n// character in string literal\". Functionally identical, lint-clean.\nconst ESC = '\u001b['\nconst RESET = `${ESC}0m`\n\nfunction paint(text: string, code: string, enabled: boolean): string {\n return enabled ? `${ESC}${code}m${text}${RESET}` : text\n}\n\nconst c = {\n red: (s: string, enabled: boolean) => paint(s, '31', enabled),\n bold: (s: string, enabled: boolean) => paint(s, '1', enabled),\n dim: (s: string, enabled: boolean) => paint(s, '2', enabled),\n cyan: (s: string, enabled: boolean) => paint(s, '36', enabled),\n blue: (s: string, enabled: boolean) => paint(s, '34', enabled),\n underline: (s: string, enabled: boolean) => paint(s, '4', enabled),\n}\n\n// ── Formatter ─────────────────────────────────────────────────────────\n\nexport interface FormatKickErrorOptions {\n /**\n * Render ANSI colour codes. Defaults to TTY detection (`NO_COLOR` /\n * `FORCE_COLOR` env vars honoured). Pass `false` for log files,\n * structured loggers, or HTTP response bodies.\n */\n color?: boolean\n}\n\n/**\n * Render a {@link KickErrorInit} (or {@link KickError} instance) into a\n * multi-line human-readable string. Identical layout regardless of\n * colour — the colour flag only toggles ANSI codes.\n */\nexport function formatKickError(\n err: KickErrorInit | KickError,\n options: FormatKickErrorOptions = {},\n): string {\n const color = options.color ?? ansiEnabled()\n const lines: string[] = []\n\n // Headline: `KICK001: No provider for UserService`\n const code = c.bold(c.red(err.code, color), color)\n lines.push(`${code}: ${err.summary}`)\n\n if (err.cause) {\n lines.push('', ` ${c.bold(c.dim('Cause:', color), color)}`)\n for (const line of err.cause.split('\\n')) {\n lines.push(` ${highlightInline(line, color)}`)\n }\n }\n\n if (err.fix) {\n lines.push('', ` ${c.bold(c.dim('Fix:', color), color)}`)\n for (const line of err.fix.split('\\n')) {\n lines.push(` ${highlightInline(line, color)}`)\n }\n }\n\n if (err.docsUrl) {\n lines.push('', ` ${c.bold(c.dim('Docs:', color), color)}`)\n lines.push(` ${c.underline(c.blue(err.docsUrl, color), color)}`)\n }\n\n return lines.join('\\n')\n}\n\n/**\n * Highlight inline `code spans` in a line of cause/fix text. Anything\n * between backticks gets cyan when colour is enabled; backticks stay\n * in the output so the plain-text rendering still distinguishes\n * literals.\n */\nfunction highlightInline(line: string, color: boolean): string {\n if (!color) return line\n return line.replace(/`([^`]+)`/g, (_, inner: string) => `\\`${c.cyan(inner, true)}\\``)\n}\n","/**\n * Catalog of framework errors with structured cause + fix hints.\n *\n * Each factory function returns a {@link KickError} with a stable\n * `code` (KICK001, KICK002, …), a human-readable summary, an\n * explanation of the likely cause, an actionable fix, and a docs URL.\n *\n * Adding a new error: pick the next free code, add the factory below,\n * call it from the framework site that used to throw a bare `Error`.\n * Keep the public function name descriptive — `noProviderError`,\n * `envValueMissingError` — so call sites grep cleanly.\n *\n * Codes are stable. Reordering or renumbering breaks adopters whose\n * tools key on `err.code`.\n */\nimport { KickError } from './kick-error'\n\nconst DOCS_BASE = 'https://kickjs.app'\n\n// ── DI container ──────────────────────────────────────────────────────\n\n/**\n * KICK001 — No provider registered for a token.\n *\n * Thrown by `Container.resolve()` when no binding can be found for the\n * requested token. The most common cause is forgetting to add the\n * enclosing module to `bootstrap({ modules })`.\n */\nexport function noProviderError(tokenName: string): KickError {\n return new KickError({\n code: 'KICK001',\n summary: `No provider for ${tokenName}`,\n cause: `\\`${tokenName}\\` was requested from the DI container but no binding is registered.\nThis usually means one of:\n • The class is decorated with @Service() / @Repository() / @Controller(),\n but its enclosing module isn't passed to bootstrap({ modules: [...] }).\n • The class isn't decorated at all (decorators register the binding).\n • You're injecting a token (created with createToken()) that nothing\n provides — add a Container.register(TOKEN, ...) call or a module that\n binds it.`,\n fix: `If \\`${tokenName}\\` lives in a module, add the module to bootstrap:\n\n bootstrap({\n modules: [\n UsersModule, // add this\n OtherModule,\n ],\n })\n\nIf it's a custom token, register it explicitly:\n\n const TENANT_REPO = createToken<TenantRepo>('TENANT_REPO')\n Container.getInstance().register(TENANT_REPO, { useClass: PrismaTenantRepo })`,\n docsUrl: `${DOCS_BASE}/guide/dependency-injection#registering-services`,\n context: { token: tokenName },\n })\n}\n\n/**\n * KICK002 — REQUEST-scoped binding resolved without a request store\n * provider configured.\n */\nexport function requestScopeMiddlewareMissingError(tokenName: string): KickError {\n return new KickError({\n code: 'KICK002',\n summary: `Cannot resolve REQUEST-scoped \"${tokenName}\" — request scope middleware not mounted`,\n cause: `\\`${tokenName}\\` has \\`scope: Scope.REQUEST\\` but no AsyncLocalStorage frame is wired.\nThe framework's request-scope middleware sets up that frame; without it,\nREQUEST-scoped resolutions have nowhere to cache the per-request instance.`,\n fix: `Add \\`requestScopeMiddleware()\\` to your global middleware pipeline,\nor let the framework auto-mount it by using \\`contextStore: 'auto'\\`\n(the default — only check this if you set it to 'manual' explicitly):\n\n bootstrap({\n modules,\n // contextStore: 'auto', // default; no need to set\n })\n\nIf you set \\`contextStore: 'manual'\\` deliberately (rare), you own the\nALS wrapping — call \\`requestStore.run({...}, () => ...)\\` around the\ncode that resolves the binding.`,\n docsUrl: `${DOCS_BASE}/guide/dependency-injection#scopes`,\n context: { token: tokenName },\n })\n}\n\n/**\n * KICK003 — REQUEST-scoped binding resolved outside any HTTP request\n * context (no ALS store active).\n */\nexport function requestScopeOutsideRequestError(tokenName: string): KickError {\n return new KickError({\n code: 'KICK003',\n summary: `Cannot resolve REQUEST-scoped \"${tokenName}\" outside an HTTP request`,\n cause: `\\`${tokenName}\\` has \\`scope: Scope.REQUEST\\` and was resolved outside\nany HTTP request context. The request-scope middleware is wired, but\nthe call happened before a request started (e.g. in a top-level\nimport, a constructor, a cron job, a test without setup).`,\n fix: `If the caller is request-scoped (controller, request-scoped service),\nmake sure the call happens inside the request lifecycle, not at module\nload time.\n\nIn tests, wrap setup in an ALS frame manually:\n\n import { requestStore } from '@forinda/kickjs'\n\n requestStore.run(\n { requestId: 'test', instances: new Map(), values: new Map() },\n () => {\n const svc = container.resolve(MyRequestScopedService)\n // ...\n },\n )\n\nIf the caller is a SINGLETON, change \\`${tokenName}\\` to TRANSIENT or\nSINGLETON scope, or inject a factory instead of the instance directly.`,\n docsUrl: `${DOCS_BASE}/guide/dependency-injection#scopes`,\n context: { token: tokenName },\n })\n}\n\n// ── Config / env wiring ───────────────────────────────────────────────\n\n/**\n * KICK004 — `@Value('X')` resolved but the env var isn't set and no\n * default was provided.\n *\n * This is the canonical \"you forgot to wire env\" symptom — surfaces\n * when ConfigService can't find the key. The fix usually involves\n * either setting the env var or wiring `loadEnv(envSchema)` at startup.\n */\nexport function envValueMissingError(envKey: string): KickError {\n return new KickError({\n code: 'KICK004',\n summary: `@Value('${envKey}'): environment variable not set and no default provided`,\n cause: `\\`@Value('${envKey}')\\` resolved but the env var isn't present and the\ndecorator didn't declare a default. Possible reasons:\n • The variable is genuinely missing from your environment / .env file.\n • Your \\`src/env.ts\\` calls \\`loadEnv(envSchema)\\` but \\`src/index.ts\\`\n doesn't import \\`./env\\` before \\`bootstrap()\\`. Without that import\n the schema never runs and ConfigService stays empty — \\`@Value\\`\n only finds the var via the \\`process.env\\` fallback.`,\n fix: `Either set the variable in your shell / .env file:\n\n ${envKey}=...\n\nOr add a default at the decorator:\n\n @Value('${envKey}', { default: 'fallback' })\n private value!: string\n\nIf you're using a schema, make sure \\`src/env.ts\\` is imported from\n\\`src/index.ts\\` BEFORE bootstrap runs:\n\n // src/index.ts\n import 'reflect-metadata'\n import './env' // ← this line is required\n import { bootstrap } from '@forinda/kickjs'\n // ...`,\n docsUrl: `${DOCS_BASE}/guide/configuration#wiring-the-schema-at-startup`,\n context: { envKey },\n })\n}\n\n// ── Module setup ──────────────────────────────────────────────────────\n\n/**\n * KICK005 — A module's `routes()` return value declares a mount path\n * but provides neither a `controller` class nor a pre-built `router`.\n */\nexport function moduleRouteMissingControllerError(mountPath: string): KickError {\n return new KickError({\n code: 'KICK005',\n summary: `Module route at ${mountPath} requires either 'controller' or 'router'`,\n cause: `A module's \\`routes()\\` returned an entry for \\`${mountPath}\\` but didn't\nspecify how to build the router. The framework needs either a decorated\ncontroller class (it calls \\`buildRoutes()\\` internally) or a hand-built\nExpress Router.`,\n fix: `Pass \\`controller:\\` for the common case:\n\n routes() {\n return {\n path: '${mountPath}',\n controller: UsersController,\n }\n }\n\nOr pass \\`router:\\` for full control:\n\n routes() {\n return {\n path: '${mountPath}',\n router: myExpressRouter,\n }\n }`,\n docsUrl: `${DOCS_BASE}/guide/modules`,\n context: { mountPath },\n })\n}\n\n/**\n * KICK006 — Two handlers claim the same HTTP verb + mounted path. The\n * engine would silently dispatch one of them (Express/h3: first wins,\n * Fastify: its own throw), while typegen and the typed client may\n * describe the other — so this fails at boot instead.\n */\nexport function duplicateRouteError(\n method: string,\n path: string,\n owner: string,\n prior: string,\n): KickError {\n return new KickError({\n code: 'KICK006',\n summary: `Duplicate route: ${method} ${path} is registered twice`,\n cause: `\\`${owner}\\` registers \\`${method} ${path}\\`, but that verb + path is\nalready claimed by \\`${prior}\\`. Only one handler can win at dispatch\ntime, and which one depends on the engine — while \\`kick typegen\\` and\nthe typed client may describe the other. Param names are ignored when\ncomparing (\\`/:id\\` and \\`/:taskId\\` are the same route).`,\n fix: `Change one of the two paths, remove the duplicate handler, or mount\nthe second controller under a different module path / version:\n\n routes() {\n return { path: '/tasks', controller: TasksController, version: 2 }\n }`,\n docsUrl: `${DOCS_BASE}/guide/modules`,\n context: { method, path, owner, prior },\n })\n}\n\n// ── Server ────────────────────────────────────────────────────────────\n\n/**\n * KICK007 — `server.http2` on a runtime that cannot serve HTTP/2. Express 5\n * does not run on Node's HTTP/2 compatibility layer (requests hang and it\n * throws internally), so this fails at boot rather than on the first request.\n */\nexport function http2UnsupportedRuntimeError(runtime: string): KickError {\n return new KickError({\n code: 'KICK007',\n summary: `The ${runtime} runtime cannot serve HTTP/2`,\n cause: `\\`bootstrap({ server: { http2: true } })\\` asks for an HTTP/2 server, but the\n\\`${runtime}\\` runtime does not support Node's HTTP/2 compatibility layer —\nrequests would hang instead of being answered.`,\n fix: `Pick one:\n • Switch to a runtime that serves HTTP/2:\n bootstrap({ runtime: fastifyRuntime(), server: { tls, http2: true } })\n (or h3Runtime()).\n • Drop \\`http2\\` and keep HTTPS over HTTP/1.1: server: { tls }.\n • Terminate HTTP/2 at your proxy / load balancer and serve HTTP/1.1 to it.`,\n docsUrl: `${DOCS_BASE}/guide/http-runtimes#https-and-http-2`,\n context: { runtime },\n })\n}\n\n/**\n * KICK008 — `server.http2` without `server.tls`. Browsers only speak HTTP/2\n * over TLS; cleartext HTTP/2 (h2c) is not offered.\n */\nexport function http2RequiresTlsError(): KickError {\n return new KickError({\n code: 'KICK008',\n summary: 'server.http2 requires server.tls',\n cause: `\\`bootstrap({ server: { http2: true } })\\` was set without \\`tls\\`. Browsers only\nnegotiate HTTP/2 over TLS, and KickJS does not serve cleartext HTTP/2 (h2c).`,\n fix: `Pass the certificate and key alongside http2:\n\n server: {\n tls: { key: readFileSync('key.pem'), cert: readFileSync('cert.pem') },\n http2: true,\n }\n\nOr remove \\`http2\\` if TLS is terminated in front of the app.`,\n docsUrl: `${DOCS_BASE}/guide/http-runtimes#https-and-http-2`,\n })\n}\n\n/**\n * KICK009 — `server.tls` cannot identify the server. Node starts an HTTPS /\n * HTTP/2 server without a certificate (or with a key that does not match it)\n * and then fails every TLS handshake, so this is checked at boot instead.\n */\nexport function tlsCredentialsError(problem: string): KickError {\n return new KickError({\n code: 'KICK009',\n summary: `server.tls is not usable: ${problem}`,\n cause: `\\`bootstrap({ server: { tls } })\\` was given TLS options the server cannot use:\n${problem}. Node would start anyway and fail every TLS handshake.`,\n fix: `Give the server an identity:\n • \\`key\\` and \\`cert\\` together (PEM, matching each other), or\n • \\`pfx\\` (with \\`passphrase\\` if it is encrypted), or\n • \\`SNICallback\\` / \\`pskCallback\\` for per-host or PSK setups.\n\n server: { tls: { key: readFileSync('key.pem'), cert: readFileSync('cert.pem') } }`,\n docsUrl: `${DOCS_BASE}/guide/http-runtimes#https-and-http-2`,\n context: { problem },\n })\n}\n","/**\n * Connects the DI core (`@forinda/kickjs-di`) to\n * the framework: catalogued errors, the logger, and `@Asset` injection.\n * Imported by `./container` and `./decorators`, so every kickjs entry that\n * reaches the container installs them.\n */\nimport { Container, type DiErrorCode } from '@forinda/kickjs-di'\n// Slot indirection, NOT `./assets` — that module's eager node:fs import\n// would poison the edge-safe web entry graph (see asset-resolver-slot.ts).\nimport { resolveAssetViaSlot } from './asset-resolver-slot'\nimport { METADATA } from './interfaces'\nimport {\n envValueMissingError,\n noProviderError,\n requestScopeMiddlewareMissingError,\n requestScopeOutsideRequestError,\n} from './kick-errors'\nimport { createLogger } from './logger'\n\nconst CATALOGUE: Record<DiErrorCode, (subject: string) => Error> = {\n KICK001: noProviderError,\n KICK002: requestScopeMiddlewareMissingError,\n KICK003: requestScopeOutsideRequestError,\n KICK004: envValueMissingError,\n}\n\nContainer._error = (code, subject) => CATALOGUE[code](subject)\nContainer._logger = createLogger('Container')\nContainer._propertyInjectors.set(METADATA.ASSET, ({ assetKey }: { assetKey: string }) => {\n const slash = assetKey.indexOf('/')\n if (slash === -1) {\n throw new Error(\n `@Asset('${assetKey}'): asset key must include a '/' separator (e.g. 'mails/welcome').`,\n )\n }\n const namespace = assetKey.slice(0, slash)\n const key = assetKey.slice(slash + 1)\n return () => resolveAssetViaSlot(namespace, key)\n})\n"],"mappings":"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"}
|
|
@@ -0,0 +1,11 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* @forinda/kickjs v10.4.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
|
+
export{runDisposables as i,drainDisposables as n,registerDisposable as r,disposeAll as t}from"@forinda/kickjs-di";
|
|
@@ -0,0 +1,63 @@
|
|
|
1
|
+
|
|
2
|
+
import { C as RuntimeResponse } from "./adapter-BZ1WzN1z.mjs";
|
|
3
|
+
//#region src/http/middleware/error-handler.d.ts
|
|
4
|
+
/**
|
|
5
|
+
* The slice of the request this handler reads, spelled from node's
|
|
6
|
+
* `IncomingMessage` rather than Express's `Request`.
|
|
7
|
+
*
|
|
8
|
+
* Fastify and h3 hand the error handler `request.raw` — a plain
|
|
9
|
+
* `IncomingMessage` — so anything Express-only is `undefined` there. This is
|
|
10
|
+
* the default handler for EVERY runtime, so it must not assume Express.
|
|
11
|
+
*/
|
|
12
|
+
interface ErrorRequest {
|
|
13
|
+
method?: string;
|
|
14
|
+
url?: string;
|
|
15
|
+
/** Express-only; absent on the raw node request the other runtimes pass. */
|
|
16
|
+
originalUrl?: string;
|
|
17
|
+
headers: Record<string, string | string[] | undefined>;
|
|
18
|
+
}
|
|
19
|
+
/** A mounted route, as the catch-all needs to see it. */
|
|
20
|
+
interface MountedRoute {
|
|
21
|
+
method: string;
|
|
22
|
+
/** Full path as mounted, `:param` segments included. */
|
|
23
|
+
path: string;
|
|
24
|
+
}
|
|
25
|
+
/**
|
|
26
|
+
* Catch-all for unmatched routes.
|
|
27
|
+
*
|
|
28
|
+
* Answers RFC 9457 problem details, like every other error the framework
|
|
29
|
+
* produces — the catch-all was the one path still emitting a bare
|
|
30
|
+
* `{ message }`, so a client parsing `application/problem+json` had to special
|
|
31
|
+
* case it.
|
|
32
|
+
*
|
|
33
|
+
* Distinguishes a path that does not exist from a path that does not accept
|
|
34
|
+
* this method. `DELETE /things/1` where only `GET` is mounted is a **405** with
|
|
35
|
+
* an `Allow` header, not a 404: the resource is there, the verb is not, and
|
|
36
|
+
* 404 tells a client to stop looking for something that exists. Requires the
|
|
37
|
+
* mounted route table, so an app that does not pass one keeps answering 404.
|
|
38
|
+
*/
|
|
39
|
+
declare function notFoundHandler(routes?: readonly MountedRoute[]): (req: ErrorRequest, res: RuntimeResponse, _next: () => void) => RuntimeResponse;
|
|
40
|
+
/**
|
|
41
|
+
* Global error handler.
|
|
42
|
+
*
|
|
43
|
+
* Default behavior strips error `details` from the response in production
|
|
44
|
+
* (any `NODE_ENV` but `development` / `test`, unset included) so internal
|
|
45
|
+
* context (DB errors, custom payloads) does not leak to clients. A 422's
|
|
46
|
+
* per-field `{ field, message }` list is kept — field names and messages are
|
|
47
|
+
* what a form shows — with every other member dropped. Apps that want a
|
|
48
|
+
* different policy pass their own `onError` to `bootstrap()`.
|
|
49
|
+
*
|
|
50
|
+
* Unexpected 500s carry `requestId` in every environment (the correlation
|
|
51
|
+
* handle back to the log line) and, outside production, the error summary
|
|
52
|
+
* plus stack. Production bodies stay opaque.
|
|
53
|
+
*
|
|
54
|
+
* {@link ProblemException} and plain {@link HttpException} both emit
|
|
55
|
+
* `application/problem+json` per RFC 9457. `ProblemException` carries a
|
|
56
|
+
* caller-supplied `type` / `title` / extensions; an `HttpException`'s message
|
|
57
|
+
* becomes `detail`, with `title` and `type` defaulted from the status. One
|
|
58
|
+
* shape, so a client never has to branch on which one the app threw.
|
|
59
|
+
*/
|
|
60
|
+
declare function errorHandler(): (err: any, req: ErrorRequest, res: RuntimeResponse, _next: () => void) => RuntimeResponse | undefined;
|
|
61
|
+
//#endregion
|
|
62
|
+
export { errorHandler as n, notFoundHandler as r, MountedRoute as t };
|
|
63
|
+
//# sourceMappingURL=error-handler-CbP7hKdJ.d.mts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"error-handler-CbP7hKdJ.d.mts","names":[],"sources":["../src/http/middleware/error-handler.ts"],"mappings":";;;;;;;;;;;UAUU;EACR;EACA;;EAEA;EACA,SAAS;;;UAWM;EACf;;EAEA;;;;;;;;;;;;;;;;iBAiCc,gBAAgB,kBAAiB,kBAAmB,KAMrD,cAAY,KAAO,iBAAe,sBAAmB;;;;;;;;;;;;;;;;;;;;;iBAuDpD,iBAAY,UACV,KAAO,cAAY,KAAO,iBAAe,sBAAmB"}
|
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
/**
|
|
2
|
-
* @forinda/kickjs v10.
|
|
2
|
+
* @forinda/kickjs v10.4.0
|
|
3
3
|
*
|
|
4
4
|
* Copyright (c) Felix Orinda
|
|
5
5
|
*
|
|
@@ -8,5 +8,5 @@
|
|
|
8
8
|
*
|
|
9
9
|
* @license MIT
|
|
10
10
|
*/
|
|
11
|
-
import{HttpException}from"./core/errors.mjs";import{_ as unsupportedMediaTypeError,f as classifyMediaType,h as readBodyText,m as parseForm,n as applyHandlerResult,o as createRequestStore,p as parseByteSize,s as disposeRequestStore}from"./reply-
|
|
12
|
-
//# sourceMappingURL=handler-
|
|
11
|
+
import{HttpException}from"./core/errors.mjs";import{_ as unsupportedMediaTypeError,f as classifyMediaType,h as readBodyText,m as parseForm,n as applyHandlerResult,o as createRequestStore,p as parseByteSize,s as disposeRequestStore}from"./reply-tlUaowib.mjs";import{f as requestStore,i as stringifyJson,r as publishMatchedRoute,t as RequestContext}from"./context-CRJzl_Mj.mjs";import{errorHandler,notFoundHandler}from"./http/middleware/error-handler.mjs";import{validate}from"./http/middleware/validate.mjs";import{t as applyUploadConfig}from"./upload-config-Be7w0Dfx.mjs";var WebRequestShim=class{method;url;headers;body;params={};query={};requestId;file;files;signal;constructor(request,url){this.method=request.method,this.url=url.pathname+url.search,this.signal=request.signal;let headers={};request.headers.forEach((value,key)=>{headers[key]=value}),this.headers=headers;let query={};for(let key of url.searchParams.keys()){let all=url.searchParams.getAll(key);query[key]=all.length>1?all:all[0]}this.query=query}once(event,listener){return event===`close`&&this.signal.addEventListener(`abort`,listener,{once:!0}),this}on(event,listener){return this.once(event,listener)}};const encoder=new TextEncoder;function toBytes(chunk){return chunk instanceof Uint8Array?chunk:encoder.encode(String(chunk))}const utf8=new TextEncoder;var WebResponseDriver=class{signal;ready;settled=!1;_status=200;headers=new Headers;_headersSent=!1;writer;resolveReady;constructor(signal){this.signal=signal,this.ready=new Promise(resolve=>{this.resolveReady=resolve})}status(code){return this._status=code,this}json(data){return this.headers.has(`content-type`)||this.headers.set(`content-type`,`application/json; charset=utf-8`),this.finish(stringifyJson(data))}send(data){return typeof data==`object`&&data&&!(data instanceof Uint8Array)?this.json(data):this.finish(data)}type(contentType){return this.headers.set(`content-type`,contentType),this}getHeader(name){if(name.toLowerCase()===`set-cookie`){let cookies=this.headers.getSetCookie();return cookies.length>0?cookies:void 0}return this.headers.get(name)??void 0}setHeader(name,value){if(Array.isArray(value)){this.headers.delete(name);for(let v of value)this.headers.append(name,String(v))}else this.headers.set(name,String(value));return this}render(){throw Error(`ctx.render() is not supported on the web runtime (no view engine).`)}writeHead(statusCode,headers){if(this._status=statusCode,headers)for(let[name,value]of Object.entries(headers))this.setHeader(name,value);return this.startStream(),this}flushHeaders(){return this.startStream(),this}write(chunk){return this.startStream(),this.writer.write(toBytes(chunk)).catch(()=>{}),!0}end(data){return this.writer?(data!==void 0&&this.write(data),this.writer.close().catch(()=>{}),this.writer=void 0,this):this.finish(data)}once(event,listener){return event===`close`&&this.signal&&this.signal.addEventListener(`abort`,listener,{once:!0}),this}get headersSent(){return this._headersSent}finish(body){if(this.settled)return this;this.settled=!0,this._headersSent=!0;let bodyAllowed=this._status!==204&&this._status!==304;if(bodyAllowed&&body!=null&&!this.headers.has(`content-length`)){let length=typeof body==`string`?utf8.encode(body).byteLength:body.byteLength;this.headers.set(`content-length`,String(length))}return this.resolveReady(new Response(bodyAllowed?body??null:null,{status:this._status,headers:this.headers})),this}startStream(){if(this.writer||this.settled)return;let{readable,writable}=new TransformStream;this.writer=writable.getWriter(),this.settled=!0,this._headersSent=!0,this.signal?.addEventListener(`abort`,()=>{this.writer?.abort().catch(()=>{}),this.writer=void 0},{once:!0}),this.resolveReady(new Response(readable,{status:this._status,headers:this.headers}))}};const NOOP_NEXT=()=>{},BODY_METHODS=/* @__PURE__ */ new Set([`POST`,`PUT`,`PATCH`,`DELETE`]),builtInError=errorHandler(),builtInNotFound=notFoundHandler();function decodeParams(params){let decoded={};for(let key in params){let value=params[key];decoded[key]=value.includes(`%`)?decodeURIComponent(value):value}return decoded}function readThrough(shim,carry){return new Proxy(shim,{get(target,prop,receiver){let own=Reflect.get(target,prop,receiver);return own===void 0?Reflect.get(carry,prop,carry):own},has(target,prop){return Reflect.has(target,prop)||Reflect.has(carry,prop)}})}function compileWebRoute(entry,hooks,options={}){let bodyLimit=options.bodyLimit??parseByteSize(`1mb`),validator=entry.meta.validation?validate(entry.meta.validation,{validationError:entry.validationError}):void 0,upload=entry.meta.upload&&entry.meta.upload.mode!==`none`?entry.meta.upload:null;return async({request,url,params,carry})=>{let shim=new WebRequestShim(request,url),req=carry?readThrough(shim,carry):shim,bodyError;try{req.params=decodeParams(params)}catch{req.params=params,bodyError=HttpException.badRequest(`Malformed URL parameter`)}if(upload){let form=await request.formData().catch(()=>void 0);if(form){let rawParts=[],fields={};for(let[name,value]of form.entries())typeof value==`string`?fields[name]=value:rawParts.push({fieldname:name,filename:value.name??``,mimetype:value.type||`application/octet-stream`,buffer:typeof Buffer==`function`?Buffer.from(await value.arrayBuffer()):new Uint8Array(await value.arrayBuffer())});let{file,files}=applyUploadConfig(rawParts,entry.meta.upload);req.file=file,req.files=files,req.body=fields}}else if(BODY_METHODS.has(request.method)){let raw=``;try{raw=await readBodyText(request,bodyLimit)}catch(err){err instanceof HttpException&&(bodyError=err)}let kind=classifyMediaType(req.headers[`content-type`]);if(raw!==``&&kind===`unsupported`)bodyError=unsupportedMediaTypeError(req.headers[`content-type`]);else if(raw!==``&&kind!==`multipart`){if(kind===`json`)try{req.body=JSON.parse(raw)}catch(err){bodyError=HttpException.badRequest(err instanceof Error?err.message:`Request body could not be parsed`)}else req.body=kind===`urlencoded`?parseForm(raw):raw}}let store=createRequestStore(req.requestId||req.headers[`x-request-id`]);req.requestId=store.requestId;let driver=new WebResponseDriver(request.signal);driver.setHeader(`x-request-id`,store.requestId),publishMatchedRoute(req,entry),carry&&publishMatchedRoute(carry,entry);let pipeline=requestStore.run(store,async()=>{if(bodyError)throw bodyError;let ctx=new RequestContext(req,driver,NOOP_NEXT,driver);if(entry.earlyContributorRunner&&(await entry.earlyContributorRunner(ctx),driver.settled))return;validator&&await new Promise((resolve,reject)=>{validator(req,void 0,err=>err?reject(err):resolve())});for(let mw of entry.middlewares){let advanced=!1;if(await new Promise((resolve,reject)=>{Promise.resolve(mw(ctx,err=>{advanced=!0,err?reject(err):resolve()})).catch(reject)}),!advanced||driver.settled)return}if(entry.contributorRunner&&await entry.contributorRunner(ctx),driver.settled)return;let result=await entry.handler(ctx);driver.settled||await applyHandlerResult(ctx,result)});try{try{await Promise.race([pipeline,driver.ready])}catch(err){driver.settled||(hooks?.onError&&await hooks.onError(err,req,driver),driver.settled||await builtInError(err,req,driver,NOOP_NEXT))}return driver.settled||builtInNotFound(req,driver,NOOP_NEXT),await driver.ready}finally{Promise.resolve(pipeline).catch(()=>{}).then(()=>disposeRequestStore(store))}}}export{WebResponseDriver as i,readThrough as n,WebRequestShim as r,compileWebRoute as t};
|
|
12
|
+
//# sourceMappingURL=handler-Cw4mr3ls.mjs.map
|