@forinda/kickjs 10.2.0 → 10.3.1
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-6fjmVVc2.d.mts +2324 -0
- package/dist/adapter-6fjmVVc2.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-BuUWvaqp.d.mts +1985 -0
- package/dist/application-BuUWvaqp.d.mts.map +1 -0
- package/dist/{application-Ch5jT4fj.mjs → application-CYCvctQx.mjs} +3 -3
- package/dist/{application-Ch5jT4fj.mjs.map → application-CYCvctQx.mjs.map} +1 -1
- package/dist/bootstrap-CfaYHbmd.mjs +12 -0
- package/dist/{bootstrap-D56HIq1N.mjs.map → bootstrap-CfaYHbmd.mjs.map} +1 -1
- package/dist/{bounded-counters-B9dzk5o_.mjs → bounded-counters-BcA0f0bV.mjs} +2 -2
- package/dist/{bounded-counters-B9dzk5o_.mjs.map → bounded-counters-BcA0f0bV.mjs.map} +1 -1
- package/dist/{client-ip-lYnBU2PR.mjs → client-ip-BpauuVN_.mjs} +2 -2
- package/dist/{client-ip-lYnBU2PR.mjs.map → client-ip-BpauuVN_.mjs.map} +1 -1
- package/dist/config/index.d.mts +1 -1
- package/dist/config/index.mjs +2 -2
- package/dist/{config-BfImCyaG.mjs → config-DgMxtfcW.mjs} +3 -3
- package/dist/{config-BfImCyaG.mjs.map → config-DgMxtfcW.mjs.map} +1 -1
- package/dist/container-4iJdDkRH.d.mts +3 -0
- package/dist/{context-C6iKf9hN.mjs → context-DJvuLfrx.mjs} +3 -3
- package/dist/{context-C6iKf9hN.mjs.map → context-DJvuLfrx.mjs.map} +1 -1
- package/dist/{context-errors-6psUheqc.mjs → context-errors-BGIOYMV5.mjs} +2 -2
- package/dist/{context-errors-6psUheqc.mjs.map → context-errors-BGIOYMV5.mjs.map} +1 -1
- package/dist/{contributor-runner-Bn-ipSS5.mjs → contributor-runner-CJn1gZ8h.mjs} +3 -3
- package/dist/{contributor-runner-Bn-ipSS5.mjs.map → contributor-runner-CJn1gZ8h.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-YE-k8IrU.mjs +12 -0
- package/dist/{core-CFXpwc7m.mjs.map → core-YE-k8IrU.mjs.map} +1 -1
- package/dist/{csrf-C3RRSCMs.mjs → csrf-C6Em76kH.mjs} +3 -3
- package/dist/{csrf-C3RRSCMs.mjs.map → csrf-C6Em76kH.mjs.map} +1 -1
- package/dist/{csrf-Cy1meSpf.d.mts → csrf-ahBjt1ay.d.mts} +2 -2
- package/dist/{csrf-Cy1meSpf.d.mts.map → csrf-ahBjt1ay.d.mts.map} +1 -1
- package/dist/decorate-CaEYam5J.mjs +13 -0
- package/dist/{decorate-DkxaoRo5.mjs.map → decorate-CaEYam5J.mjs.map} +1 -1
- package/dist/{decorators-DaQUNXOn.d.mts → decorators-deGmthGc.d.mts} +3 -199
- package/dist/decorators-deGmthGc.d.mts.map +1 -0
- package/dist/{define-adapter-BRJ6lXkV.mjs → define-adapter-C6H-I1og.mjs} +2 -2
- package/dist/{define-adapter-BRJ6lXkV.mjs.map → define-adapter-C6H-I1og.mjs.map} +1 -1
- package/dist/di-hooks-BE0IOQk-.mjs +132 -0
- package/dist/di-hooks-BE0IOQk-.mjs.map +1 -0
- package/dist/disposables-Cste73oY.mjs +11 -0
- package/dist/error-handler-C6JJJct_.d.mts +63 -0
- package/dist/error-handler-C6JJJct_.d.mts.map +1 -0
- package/dist/{handler-Dl_1fGxE.mjs → handler-DUyRCpPw.mjs} +3 -3
- package/dist/{handler-Dl_1fGxE.mjs.map → handler-DUyRCpPw.mjs.map} +1 -1
- package/dist/{host-DTQ5pZgg.mjs → host-fc-YQZnN.mjs} +2 -2
- package/dist/{host-DTQ5pZgg.mjs.map → host-fc-YQZnN.mjs.map} +1 -1
- package/dist/http/application.d.mts +1 -1
- 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 +2 -2
- package/dist/http/middleware/error-handler.d.mts +1 -1
- package/dist/http/middleware/error-handler.mjs +2 -2
- 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 -3
- package/dist/http/middleware/upload.mjs.map +1 -1
- package/dist/http/middleware/validate.mjs +1 -1
- package/dist/http/middleware/views.d.mts +2 -2
- package/dist/http/middleware/views.mjs +2 -2
- package/dist/http/middleware/views.mjs.map +1 -1
- 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.d.mts.map +1 -1
- package/dist/http/runtimes/fastify.mjs +3 -3
- package/dist/http/runtimes/fastify.mjs.map +1 -1
- package/dist/http/runtimes/h3-web.mjs +1 -1
- package/dist/http/runtimes/h3.d.mts +5 -4
- package/dist/http/runtimes/h3.d.mts.map +1 -1
- package/dist/http/runtimes/h3.mjs +2 -2
- package/dist/http/runtimes/h3.mjs.map +1 -1
- package/dist/{index-CuiWSnZL.d.mts → index-Dms8LzHG.d.mts} +3 -3
- package/dist/{index-CuiWSnZL.d.mts.map → index-Dms8LzHG.d.mts.map} +1 -1
- package/dist/index.d.mts +17 -11
- package/dist/index.mjs +3 -3
- 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-tnFh6NCj.mjs → is-production-0lB5MU1j.mjs} +2 -2
- package/dist/{is-production-tnFh6NCj.mjs.map → is-production-0lB5MU1j.mjs.map} +1 -1
- package/dist/jobs-DWi_Lwbe.mjs +12 -0
- package/dist/{jobs-lLcPhIqq.mjs.map → jobs-DWi_Lwbe.mjs.map} +1 -1
- package/dist/kv-stores-BGXPKv15.d.mts +366 -0
- package/dist/kv-stores-BGXPKv15.d.mts.map +1 -0
- package/dist/{kv-stores-_wz4DEiw.mjs → kv-stores-BGXeNEDK.mjs} +3 -3
- package/dist/{kv-stores-_wz4DEiw.mjs.map → kv-stores-BGXeNEDK.mjs.map} +1 -1
- package/dist/lazy-serve-static-Barg3__1.mjs +12 -0
- package/dist/lazy-serve-static-Barg3__1.mjs.map +1 -0
- package/dist/metadata-CnL9sQFa.mjs +11 -0
- package/dist/{observers-IGga6yut.mjs → observers-BNMQ7VLb.mjs} +2 -2
- package/dist/{observers-IGga6yut.mjs.map → observers-BNMQ7VLb.mjs.map} +1 -1
- package/dist/{query-AnbWMCd6.mjs → query-mXPZYtQw.mjs} +2 -2
- package/dist/{query-AnbWMCd6.mjs.map → query-mXPZYtQw.mjs.map} +1 -1
- package/dist/{reply-DjysdCPI.mjs → reply-CMRk-Jp3.mjs} +3 -3
- package/dist/{reply-DjysdCPI.mjs.map → reply-CMRk-Jp3.mjs.map} +1 -1
- package/dist/{respond-vPZlRnZR.mjs → respond-gPELdOSi.mjs} +2 -2
- package/dist/{respond-vPZlRnZR.mjs.map → respond-gPELdOSi.mjs.map} +1 -1
- package/dist/{route-flag-BjRpxryx.mjs → route-flag-8Pi83-uw.mjs} +3 -3
- package/dist/{route-flag-BjRpxryx.mjs.map → route-flag-8Pi83-uw.mjs.map} +1 -1
- package/dist/{route-policy-Pffte5M1.mjs → route-policy-0LAfSzo-.mjs} +2 -2
- package/dist/{route-policy-Pffte5M1.mjs.map → route-policy-0LAfSzo-.mjs.map} +1 -1
- package/dist/router-builder-D0SDqFTr.mjs +12 -0
- package/dist/{router-builder-CrWKq6O2.mjs.map → router-builder-D0SDqFTr.mjs.map} +1 -1
- package/dist/router-builder-obSpg-Ub.d.mts +56 -0
- package/dist/router-builder-obSpg-Ub.d.mts.map +1 -0
- package/dist/settings-BW5gVm6c.mjs +14 -0
- package/dist/{settings-CFtEAQUs.mjs.map → settings-BW5gVm6c.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/token-D6jfTQLA.d.mts +3 -0
- package/dist/token-Q2c8xwJE.mjs +11 -0
- package/dist/upload-CyBSlnH_.d.mts +104 -0
- package/dist/upload-CyBSlnH_.d.mts.map +1 -0
- package/dist/{upload-config-DLgt4l7F.mjs → upload-config-D22qKth8.mjs} +2 -2
- package/dist/{upload-config-DLgt4l7F.mjs.map → upload-config-D22qKth8.mjs.map} +1 -1
- package/dist/url-for-UZ5kJjsG.mjs +12 -0
- package/dist/{url-for-Cyh7pJCb.mjs.map → url-for-UZ5kJjsG.mjs.map} +1 -1
- package/dist/web.d.mts +5 -4
- package/dist/web.d.mts.map +1 -1
- package/dist/web.mjs +2 -2
- package/dist/web.mjs.map +1 -1
- package/package.json +6 -1
- package/dist/adapter-C5I5e_-i.d.mts +0 -4866
- package/dist/adapter-C5I5e_-i.d.mts.map +0 -1
- package/dist/app-module-Ftz6m7SO.d.mts.map +0 -1
- package/dist/bootstrap-D56HIq1N.mjs +0 -12
- package/dist/container-C2aTj8Cb.mjs +0 -132
- package/dist/container-C2aTj8Cb.mjs.map +0 -1
- package/dist/container-Dpvd66Yt.d.mts +0 -298
- package/dist/container-Dpvd66Yt.d.mts.map +0 -1
- package/dist/core-CFXpwc7m.mjs +0 -12
- package/dist/decorate-DkxaoRo5.mjs +0 -13
- package/dist/decorators-DaQUNXOn.d.mts.map +0 -1
- package/dist/disposables-5nFqc1aC.mjs +0 -12
- package/dist/disposables-5nFqc1aC.mjs.map +0 -1
- package/dist/interfaces-C1hCSoLD.d.mts +0 -75
- package/dist/interfaces-C1hCSoLD.d.mts.map +0 -1
- package/dist/jobs-lLcPhIqq.mjs +0 -12
- package/dist/metadata-Tc6jhIBi.mjs +0 -12
- package/dist/metadata-Tc6jhIBi.mjs.map +0 -1
- package/dist/router-builder-CrWKq6O2.mjs +0 -12
- package/dist/settings-CFtEAQUs.mjs +0 -14
- package/dist/url-for-Cyh7pJCb.mjs +0 -12
|
@@ -1,298 +0,0 @@
|
|
|
1
|
-
|
|
2
|
-
import { c as Scope, i as Constructor, r as ClassKind, s as PostConstructStatus } from "./interfaces-C1hCSoLD.mjs";
|
|
3
|
-
import "reflect-metadata";
|
|
4
|
-
//#region src/core/token.d.ts
|
|
5
|
-
/**
|
|
6
|
-
* Collision-safe injection tokens with phantom type parameters.
|
|
7
|
-
*
|
|
8
|
-
* `createToken<T>(name)` is the recommended way to declare any DI token
|
|
9
|
-
* that isn't a class. Each call returns a unique frozen object — even if
|
|
10
|
-
* two files write `createToken<X>('Logger')`, they produce two distinct
|
|
11
|
-
* references that the container treats as different tokens. Collisions
|
|
12
|
-
* become impossible by construction, not by convention.
|
|
13
|
-
*
|
|
14
|
-
* The phantom type parameter `T` lets `container.resolve(token)` infer
|
|
15
|
-
* the correct return type without any codegen.
|
|
16
|
-
*
|
|
17
|
-
* ## Hardening layers
|
|
18
|
-
*
|
|
19
|
-
* KickJS has four DI token kinds, listed from safest to riskiest:
|
|
20
|
-
*
|
|
21
|
-
* 1. **Class identity** — `container.resolve(UserService)`. Reference
|
|
22
|
-
* equality, never collides. Type-safe via `Constructor<T>` overload.
|
|
23
|
-
* 2. **`createToken<T>(name)`** — frozen object identity, never collides.
|
|
24
|
-
* Type-safe via the `InjectionToken<T>` overload.
|
|
25
|
-
* 3. **Symbol** — `Symbol('foo')` is unique per call but `Symbol.for('foo')`
|
|
26
|
-
* is interned and CAN collide. Discouraged.
|
|
27
|
-
* 4. **Raw string `@Inject('foo')`** — high collision risk, untyped.
|
|
28
|
-
* Reserved for legacy code and runtime-computed token names.
|
|
29
|
-
*
|
|
30
|
-
* Prefer (1) and (2). Use (4) only when you have to.
|
|
31
|
-
*
|
|
32
|
-
* @example
|
|
33
|
-
* ```ts
|
|
34
|
-
* // src/tokens.ts
|
|
35
|
-
* export const DATABASE_URL = createToken<string>('config.database.url')
|
|
36
|
-
* export const FEATURE_FLAGS = createToken<FeatureFlags>('app.features')
|
|
37
|
-
*
|
|
38
|
-
* // bootstrap
|
|
39
|
-
* container.registerInstance(DATABASE_URL, process.env.DATABASE_URL!)
|
|
40
|
-
*
|
|
41
|
-
* // anywhere else
|
|
42
|
-
* const url = container.resolve(DATABASE_URL) // typed as `string`
|
|
43
|
-
* ```
|
|
44
|
-
*
|
|
45
|
-
* @module @forinda/kickjs/core/token
|
|
46
|
-
*/
|
|
47
|
-
/**
|
|
48
|
-
* Symbol marker stamped on every InjectionToken so the container can
|
|
49
|
-
* detect them at runtime regardless of which package created them.
|
|
50
|
-
*
|
|
51
|
-
* Uses `Symbol.for()` so cross-package isolation (different copies of
|
|
52
|
-
* `@forinda/kickjs` loaded under different module identities) still
|
|
53
|
-
* shares the same marker.
|
|
54
|
-
*/
|
|
55
|
-
declare const INJECTION_TOKEN: unique symbol;
|
|
56
|
-
/**
|
|
57
|
-
* A type-safe DI token. Each `createToken()` call returns a unique frozen
|
|
58
|
-
* object identified by reference, not by the `name` string. Two
|
|
59
|
-
* `createToken<X>('foo')` calls in different files produce two distinct
|
|
60
|
-
* tokens that the container treats independently.
|
|
61
|
-
*
|
|
62
|
-
* The phantom `_type` parameter is never assigned at runtime — it exists
|
|
63
|
-
* solely to thread the type through `container.resolve(token)`.
|
|
64
|
-
*/
|
|
65
|
-
interface InjectionToken<T> {
|
|
66
|
-
readonly [INJECTION_TOKEN]: true;
|
|
67
|
-
/** Descriptive name used in error messages, logs, and devtools */
|
|
68
|
-
readonly name: string;
|
|
69
|
-
/** Phantom — never assigned at runtime */
|
|
70
|
-
readonly _type?: T;
|
|
71
|
-
}
|
|
72
|
-
/**
|
|
73
|
-
* Create a collision-safe injection token.
|
|
74
|
-
*
|
|
75
|
-
* The returned token is a frozen object identified by reference, not by
|
|
76
|
-
* the `name` string. The `name` is used only for error messages, logs,
|
|
77
|
-
* and debugging.
|
|
78
|
-
*/
|
|
79
|
-
declare function createToken<T>(name: string): InjectionToken<T>;
|
|
80
|
-
/** Type guard — returns `true` if `value` is an InjectionToken */
|
|
81
|
-
declare function isInjectionToken(value: unknown): value is InjectionToken<unknown>;
|
|
82
|
-
//#endregion
|
|
83
|
-
//#region src/core/container.d.ts
|
|
84
|
-
/** Format a token for display in error messages */
|
|
85
|
-
declare function tokenName(token: any): string;
|
|
86
|
-
/** A single container change event */
|
|
87
|
-
interface ContainerChangeEvent {
|
|
88
|
-
token: string;
|
|
89
|
-
event: 'registered' | 'resolved' | 'invalidated';
|
|
90
|
-
kind?: ClassKind;
|
|
91
|
-
timestamp: number;
|
|
92
|
-
}
|
|
93
|
-
/** Listener that receives batched change events */
|
|
94
|
-
type ContainerChangeListener = (changes: ContainerChangeEvent[]) => void;
|
|
95
|
-
/**
|
|
96
|
-
* Type-safe registry of string DI tokens. Augmented by `kick typegen` —
|
|
97
|
-
* the generated `.kickjs/types/registry.d.ts` adds entries like:
|
|
98
|
-
*
|
|
99
|
-
* ```ts
|
|
100
|
-
* declare module '@forinda/kickjs' {
|
|
101
|
-
* interface KickJsRegistry {
|
|
102
|
-
* UserService: import('../../src/modules/users/user.service').UserService
|
|
103
|
-
* }
|
|
104
|
-
* }
|
|
105
|
-
* ```
|
|
106
|
-
*
|
|
107
|
-
* Once typegen has run, `container.resolve('UserService')` returns the
|
|
108
|
-
* correct type instead of `any`. Class-token resolution
|
|
109
|
-
* (`container.resolve(UserService)`) is already type-safe via the
|
|
110
|
-
* `Constructor<T>` overload and does not need typegen.
|
|
111
|
-
*/
|
|
112
|
-
interface KickJsRegistry {}
|
|
113
|
-
/**
|
|
114
|
-
* Inversion-of-Control (IoC) container that manages dependency registration,
|
|
115
|
-
* resolution, and lifecycle. Implements the Singleton pattern so all parts of
|
|
116
|
-
* the application share a single container instance.
|
|
117
|
-
*
|
|
118
|
-
* Supports constructor injection, property injection (@Autowired),
|
|
119
|
-
* factory registrations, and lifecycle hooks (@PostConstruct).
|
|
120
|
-
*
|
|
121
|
-
* Persistent state (DB connections, Redis, etc.) is stored on globalThis so
|
|
122
|
-
* it survives both Container.reset() and Vite module re-evaluation.
|
|
123
|
-
*/
|
|
124
|
-
declare class Container {
|
|
125
|
-
private static instance;
|
|
126
|
-
private registrations;
|
|
127
|
-
private resolving;
|
|
128
|
-
private changeListeners;
|
|
129
|
-
private pendingChanges;
|
|
130
|
-
private notifyTimer;
|
|
131
|
-
private static readonly DEBOUNCE_MS;
|
|
132
|
-
/** Callback set by the decorators module to flush pending registrations */
|
|
133
|
-
static _onReady: ((container: Container) => void) | null;
|
|
134
|
-
/** Callback invoked on reset so decorators can update their container reference */
|
|
135
|
-
static _onReset: ((container: Container) => void) | null;
|
|
136
|
-
/**
|
|
137
|
-
* Seeds a NEWLY CREATED container with the decorator registrations, without
|
|
138
|
-
* adopting it as the global one. `_onReset` does both; an isolated container
|
|
139
|
-
* must only have the first half, or it would capture every subsequent
|
|
140
|
-
* decorator registration in the process.
|
|
141
|
-
*/
|
|
142
|
-
static _onCreate: ((container: Container) => void) | null;
|
|
143
|
-
/**
|
|
144
|
-
* Environment resolver for @Value decorator. Set by the unified
|
|
145
|
-
* `@forinda/kickjs` config layer to return Zod-validated, type-coerced
|
|
146
|
-
* env values instead of raw process.env strings.
|
|
147
|
-
*/
|
|
148
|
-
static _envResolver: ((key: string) => any) | null;
|
|
149
|
-
/**
|
|
150
|
-
* Request store provider for REQUEST-scoped DI. Set by the HTTP layer
|
|
151
|
-
* inside `@forinda/kickjs` to return the current request's
|
|
152
|
-
* AsyncLocalStorage store. Returns { instances: Map, values: Map } or
|
|
153
|
-
* null if outside a request.
|
|
154
|
-
*/
|
|
155
|
-
/**
|
|
156
|
-
* Whether this container is the global singleton.
|
|
157
|
-
*
|
|
158
|
-
* The persistent store exists to carry the GLOBAL container's registrations
|
|
159
|
-
* across HMR and module re-evaluation. An isolated container is per-test and
|
|
160
|
-
* must neither write to it — a `registerInstance` override was replayed into
|
|
161
|
-
* every later `Container.reset()` — nor read from it, which would pull global
|
|
162
|
-
* state into a container created to be free of it.
|
|
163
|
-
*/
|
|
164
|
-
private isGlobal;
|
|
165
|
-
static _requestStoreProvider: (() => {
|
|
166
|
-
instances: Map<any, any>;
|
|
167
|
-
values: Map<any, any>;
|
|
168
|
-
} | null) | null;
|
|
169
|
-
static getInstance(): Container;
|
|
170
|
-
/**
|
|
171
|
-
* Resets the container by replacing the singleton with a fresh instance.
|
|
172
|
-
* Persistent registrations (DB, Redis, etc.) are replayed from globalThis
|
|
173
|
-
* so they survive both reset() and Vite module re-evaluation.
|
|
174
|
-
*/
|
|
175
|
-
static reset(): void;
|
|
176
|
-
/**
|
|
177
|
-
* Create an isolated container instance (not the global singleton).
|
|
178
|
-
* Useful for concurrent tests that must not share DI state.
|
|
179
|
-
*
|
|
180
|
-
* @example
|
|
181
|
-
* ```ts
|
|
182
|
-
* const container = Container.create()
|
|
183
|
-
* container.register(UserService, UserService)
|
|
184
|
-
* const svc = container.resolve(UserService)
|
|
185
|
-
* ```
|
|
186
|
-
*/
|
|
187
|
-
static create(): Container;
|
|
188
|
-
/** Register a class constructor under the given token */
|
|
189
|
-
register(token: any, target: Constructor, scope?: Scope): void;
|
|
190
|
-
/** Register a factory function under the given token */
|
|
191
|
-
registerFactory(token: any, factory: () => any, scope?: Scope): void;
|
|
192
|
-
/** Register a pre-constructed singleton instance */
|
|
193
|
-
registerInstance(token: any, instance: any): void;
|
|
194
|
-
/** Check if a binding exists for the given token */
|
|
195
|
-
has(token: any): boolean;
|
|
196
|
-
/** Return a snapshot of all registered tokens with their scope and instantiation status */
|
|
197
|
-
getRegistrations(): Array<{
|
|
198
|
-
token: string;
|
|
199
|
-
scope: string;
|
|
200
|
-
kind: ClassKind;
|
|
201
|
-
instantiated: boolean;
|
|
202
|
-
resolveCount: number;
|
|
203
|
-
lastResolvedAt?: number;
|
|
204
|
-
firstResolvedAt?: number;
|
|
205
|
-
resolveDurationMs?: number;
|
|
206
|
-
postConstructStatus: PostConstructStatus;
|
|
207
|
-
dependencies: string[];
|
|
208
|
-
}>;
|
|
209
|
-
/**
|
|
210
|
-
* Resolve a dependency by its token.
|
|
211
|
-
*
|
|
212
|
-
* Four overloads, in order of preference:
|
|
213
|
-
* - **`InjectionToken<T>`** (from `createToken<T>(name)`) → returns `T`.
|
|
214
|
-
* Collision-safe by construction; no codegen required.
|
|
215
|
-
* - **Class constructor** → returns an instance of that class. Always
|
|
216
|
-
* type-safe; no codegen required.
|
|
217
|
-
* - **String token in `KickJsRegistry`** (populated by `kick typegen`) →
|
|
218
|
-
* returns the augmented type.
|
|
219
|
-
* - **Anything else** → returns `any`. Use this only for legacy code or
|
|
220
|
-
* string tokens that haven't been registered with typegen yet.
|
|
221
|
-
*/
|
|
222
|
-
resolve<T>(token: InjectionToken<T>): T;
|
|
223
|
-
resolve<T>(token: Constructor<T>): T;
|
|
224
|
-
resolve<K extends keyof KickJsRegistry & string>(token: K): KickJsRegistry[K];
|
|
225
|
-
resolve<T = any>(token: any): T;
|
|
226
|
-
/** Lifecycle hook called during Application.setup() after module registration */
|
|
227
|
-
bootstrap(): void;
|
|
228
|
-
/**
|
|
229
|
-
* Subscribe to container changes. Returns an unsubscribe function.
|
|
230
|
-
*
|
|
231
|
-
* Changes are batched (50ms debounce) so bulk operations like
|
|
232
|
-
* `kick g module` creating 10+ files emit ONE batch, not 10 events.
|
|
233
|
-
*
|
|
234
|
-
* Any adapter can subscribe:
|
|
235
|
-
* - SwaggerAdapter: re-build spec when controllers change
|
|
236
|
-
* - DevToolsAdapter: push SSE events to dashboard
|
|
237
|
-
* - WsAdapter: re-discover namespaces when controllers change
|
|
238
|
-
* - OtelAdapter: emit tracing spans for DI resolution
|
|
239
|
-
* - Custom user adapters
|
|
240
|
-
*
|
|
241
|
-
* @example
|
|
242
|
-
* ```ts
|
|
243
|
-
* const unsub = container.onChange((changes) => {
|
|
244
|
-
* for (const c of changes) {
|
|
245
|
-
* console.log(`${c.event}: ${c.token} (${c.kind})`)
|
|
246
|
-
* }
|
|
247
|
-
* })
|
|
248
|
-
* // later:
|
|
249
|
-
* unsub()
|
|
250
|
-
* ```
|
|
251
|
-
*/
|
|
252
|
-
onChange(callback: ContainerChangeListener): () => void;
|
|
253
|
-
/**
|
|
254
|
-
* Invalidate a specific registration. Clears the cached instance so the
|
|
255
|
-
* next resolve() creates a fresh one. Also invalidates dependents
|
|
256
|
-
* (anything that injected this token) by walking the dependency graph.
|
|
257
|
-
*
|
|
258
|
-
* Called by the Vite HMR plugin when a module file changes.
|
|
259
|
-
* Skips persistent registrations (DB connections, etc.).
|
|
260
|
-
*/
|
|
261
|
-
invalidate(token: any): void;
|
|
262
|
-
/**
|
|
263
|
-
* Batch-emit a change event (debounced, flushed after 50ms of quiet).
|
|
264
|
-
* Takes the RAW token — `tokenName()` is only computed after the
|
|
265
|
-
* zero-listener guard, so the hot cached-singleton resolve path never pays
|
|
266
|
-
* the name derivation when nobody is watching (the production default).
|
|
267
|
-
*/
|
|
268
|
-
private emit;
|
|
269
|
-
/** Flush pending change events immediately (useful in tests) */
|
|
270
|
-
flushChanges(): void;
|
|
271
|
-
/**
|
|
272
|
-
* Build the one-time instantiation plan for a registration. Runs on the
|
|
273
|
-
* FIRST createInstance for the class — the metadata it reads is immutable
|
|
274
|
-
* after class definition, so every later create (REQUEST scope: every
|
|
275
|
-
* request) skips all Reflect reads and re-derivation.
|
|
276
|
-
*
|
|
277
|
-
* Scope validation (SINGLETON must not ctor-inject REQUEST) lives here
|
|
278
|
-
* too: it's a static property of the (parent, dep) registration pair, so
|
|
279
|
-
* checking it once at plan build is equivalent to the old per-create loop.
|
|
280
|
-
*/
|
|
281
|
-
private buildPlan;
|
|
282
|
-
private createInstance;
|
|
283
|
-
/**
|
|
284
|
-
* Extract every dependency token name a class declares — both
|
|
285
|
-
* constructor params (`@Inject` + emitted `design:paramtypes`) and
|
|
286
|
-
* `@Autowired` properties (read lazily at injection time, but
|
|
287
|
-
* captured here so devtools surfaces a complete dependency graph).
|
|
288
|
-
*
|
|
289
|
-
* Without the property branch, classes that rely entirely on
|
|
290
|
-
* `@Autowired` show `dependencies: []` in the introspection panel
|
|
291
|
-
* even though they have real DI deps — see /_debug topology.
|
|
292
|
-
*/
|
|
293
|
-
private extractDependencies;
|
|
294
|
-
private injectProperties;
|
|
295
|
-
}
|
|
296
|
-
//#endregion
|
|
297
|
-
export { tokenName as a, createToken as c, KickJsRegistry as i, isInjectionToken as l, ContainerChangeEvent as n, INJECTION_TOKEN as o, ContainerChangeListener as r, InjectionToken as s, Container as t };
|
|
298
|
-
//# sourceMappingURL=container-Dpvd66Yt.d.mts.map
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"file":"container-Dpvd66Yt.d.mts","names":[],"sources":["../src/core/token.ts","../src/core/container.ts"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;cAmDa;;;;;;;;;;UAWI,eAAe;YACpB;;WAED;;WAEA,QAAQ;;;;;;;;;iBAUH,YAAY,GAAG,eAAe,eAAe;;iBAQ7C,iBAAiB,iBAAiB,SAAS;;;;iBCL3C,UAAU;;UAqBT;EACf;EACA;EACA,OAAO;EACP;;;KAIU,2BAA2B,SAAS;;;;;;;;;;;;;;;;;;UAmB/B;;;;;;;;;;;;cA+BJ;iBACI;UACP;UACA;UAGA;UACA;UACA;0BACgB;;SAGjB,YAAY,WAAW;;SAEvB,YAAY,WAAW;;;;;;;SAQvB,aAAa,WAAW;;;;;;SAMxB,gBAAgB;;;;;;;;;;;;;;;;UAgBf;SAED;IACM,WAAW;IAAe,QAAQ;;SAGxC,eAAe;;;;;;SAkBf;;;;;;;;;;;;SAsDA,UAAU;;EAYjB,SAAS,YAAY,QAAQ,aAAa,QAAO;;EAcjD,gBAAgB,YAAY,oBAAoB,QAAO;;EAiDvD,iBAAiB,YAAY;;EAiC7B,IAAI;;EAKJ,oBAAoB;IAClB;IACA;IACA,MAAM;IACN;IACA;IACA;IACA;IACA;IACA,qBAAqB;IACrB;;;;;;;;;;;;;;;EAmCF,QAAQ,GAAG,OAAO,eAAe,KAAK;EACtC,QAAQ,GAAG,OAAO,YAAY,KAAK;EACnC,QAAQ,gBAAgB,yBAAyB,OAAO,IAAI,eAAe;EAC3E,QAAQ,SAAS,aAAa;;EAmH9B;;;;;;;;;;;;;;;;;;;;;;;;;EA+BA,SAAS,UAAU;;;;;;;;;EAanB,WAAW;;;;;;;UA8BH;;EA6CR;;;;;;;;;;;UA0BQ;UA4FA;;;;;;;;;;;UAwDA;UAuBA"}
|
package/dist/core-CFXpwc7m.mjs
DELETED
|
@@ -1,12 +0,0 @@
|
|
|
1
|
-
/**
|
|
2
|
-
* @forinda/kickjs v10.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{d as __require}from"./decorate-DkxaoRo5.mjs";import{METADATA}from"./core/interfaces.mjs";import{i as createToken,p as _setAssetResolver}from"./container-C2aTj8Cb.mjs";import"./core/logger.mjs";import{c as pushClassMeta,l as pushMethodMeta}from"./metadata-Tc6jhIBi.mjs";import"./core/decorators.mjs";import"./core/cron.mjs";import"./jobs-lLcPhIqq.mjs";import"./core/cache.mjs";import{n as assertFlagTest}from"./route-flag-BjRpxryx.mjs";import"./contributor-runner-Bn-ipSS5.mjs";import{t as isProduction}from"./is-production-tnFh6NCj.mjs";import"reflect-metadata";import{existsSync,readFileSync,readdirSync}from"node:fs";import{isAbsolute,join,resolve,sep}from"node:path";function defineContextDecoratorImpl(spec){if(typeof spec!=`object`||!spec)throw TypeError(`defineContextDecorator: spec must be an object literal. See architecture.md §20.4 for the spec shape.`);if(typeof spec.key!=`string`||spec.key.length===0){let got=typeof spec.key==`string`?`""`:typeof spec.key;throw TypeError(`defineContextDecorator: spec.key must be a non-empty string (got ${got}). Pick a name that matches a key declared on \`ContextMeta\` (or one of the framework keys).`)}if(typeof spec.resolve!=`function`)throw TypeError(`defineContextDecorator(${spec.key}): spec.resolve is required and must be a function (got ${typeof spec.resolve}). Each contributor needs a resolver that produces the value to write into ctx.set(${JSON.stringify(spec.key)}, …).`);if(spec.onError!==void 0&&typeof spec.onError!=`function`)throw TypeError(`defineContextDecorator(${spec.key}): spec.onError must be a function when provided (got ${typeof spec.onError}).`);if(spec.dependsOn!==void 0&&!Array.isArray(spec.dependsOn))throw TypeError(`defineContextDecorator(${spec.key}): spec.dependsOn must be an array when provided (got ${typeof spec.dependsOn}).`);if(spec.requiredParams!==void 0&&!Array.isArray(spec.requiredParams))throw TypeError(`defineContextDecorator(${spec.key}): spec.requiredParams must be an array when provided (got ${typeof spec.requiredParams}).`);if(Array.isArray(spec.requiredParams)&&spec.requiredParams.some(p=>typeof p!=`string`||p.length===0))throw TypeError(`defineContextDecorator(${spec.key}): spec.requiredParams entries must be non-empty strings.`);if(Array.isArray(spec.dependsOn)&&spec.dependsOn.some(dep=>typeof dep!=`string`||dep.length===0))throw TypeError(`defineContextDecorator(${spec.key}): spec.dependsOn entries must be non-empty strings.`);let definedAt=(/* @__PURE__ */ Error()).stack,defaults=Object.freeze({...spec.paramDefaults??{}}),sharedDeps=Object.freeze({...spec.deps??{}}),sharedDependsOn=Object.freeze([...spec.dependsOn??[]]),sharedOptional=spec.optional??!1,buildRegistration=params=>{let frozenParams=Object.freeze({...params}),onError=spec.onError?(err,ctx)=>spec.onError(err,ctx,frozenParams):void 0;return spec.skipWhen!==void 0&&assertFlagTest(spec.skipWhen,`contributor '${spec.key}' skipWhen`),spec.onlyWhen!==void 0&&assertFlagTest(spec.onlyWhen,`contributor '${spec.key}' onlyWhen`),Object.freeze({key:spec.key,deps:sharedDeps,dependsOn:sharedDependsOn,optional:sharedOptional,skipWhen:spec.skipWhen,onlyWhen:spec.onlyWhen,beforeValidation:spec.beforeValidation===!0,onError,resolve:(ctx,deps)=>spec.resolve(ctx,deps,frozenParams),definedAt})},defaultRegistration=buildRegistration({...defaults}),isDecoratorCall=args=>args.length===0?!1:args.length>=2||typeof args[0]==`function`,applyAsDecorator=(registration,target,propertyKey)=>{if(propertyKey===void 0)pushClassMeta(METADATA.CLASS_CONTRIBUTORS,target,registration);else{let constructor=target.constructor;pushMethodMeta(METADATA.METHOD_CONTRIBUTORS,constructor,String(propertyKey),registration)}},isPlainObject=value=>{let proto=Object.getPrototypeOf(value);return proto===Object.prototype||proto===null},mergeParams=override=>{if(override===void 0)return{...defaults};if(typeof override!=`object`||!override||Array.isArray(override)||!isPlainObject(override)){let got=override===null?`null`:Array.isArray(override)?`array`:typeof override==`object`?`instance of ${override.constructor?.name??`unknown class`}`:typeof override;throw TypeError(`defineContextDecorator(${spec.key}): factory call requires a plain object literal, got ${got}. Class instances and built-ins (Map, Date, etc) silently spread to empty objects — call the decorator with a spread object literal instead, e.g. \`MyDecorator({ ...someInstance })\`.`)}return{...defaults,...override}},sharedRequiredParams=Object.freeze([...spec.requiredParams??[]]),assertRequiredParams=(params,usage)=>{if(sharedRequiredParams.length===0)return;let missing=sharedRequiredParams.filter(name=>params[name]===void 0);if(missing.length!==0)throw TypeError(`defineContextDecorator(${spec.key}): ${usage} is missing required param(s) ${missing.map(m=>`'${m}'`).join(`, `)}. Supply them at the call site — e.g. \`@${spec.key}({ ${missing[0]}: … })\` — or add a default in \`paramDefaults\` if one is genuinely correct for every route.`)};function decoratorOrFactory(...args){if(isDecoratorCall(args)){let[target,propertyKey]=args;assertRequiredParams({...defaults},"bare `@decorator` usage"),applyAsDecorator(defaultRegistration,target,propertyKey);return}let params=mergeParams(args[0]);assertRequiredParams(params,`factory call`);let registration=buildRegistration(params);return(target,propertyKey)=>{applyAsDecorator(registration,target,propertyKey)}}Object.defineProperty(decoratorOrFactory,"name",{value:`ContextDecorator(${spec.key})`,writable:!1,enumerable:!1,configurable:!0});let decorator=Object.assign(decoratorOrFactory,{with:params=>{let merged=mergeParams(params);return assertRequiredParams(merged,"`.with()`"),{registration:buildRegistration(merged)}}});return Object.defineProperty(decorator,"registration",{get(){return assertRequiredParams({...defaults},"`.registration`"),defaultRegistration},enumerable:!0,configurable:!1}),Object.freeze(decorator)}const defineContextDecorator=Object.freeze(Object.assign(defineContextDecoratorImpl,{withParams:()=>spec=>defineContextDecoratorImpl(spec)}));function groupAssetKeys(namespace,paths,opts={}){let strategy=opts.strategy??`auto`;if(strategy===`with-extension`)return{pairs:paths.map(rel=>({rel,key:`${namespace}/${rel}`})),collisionGroupsResolved:0};if(strategy===`strip`)return{pairs:paths.map(rel=>({rel,key:`${namespace}/${stripExt(rel)}`})),collisionGroupsResolved:0};let groups=/* @__PURE__ */ new Map;for(let rel of paths){let strippedKey=`${namespace}/${stripExt(rel)}`,arr=groups.get(strippedKey);arr?arr.push(rel):groups.set(strippedKey,[rel])}let collisionGroupsResolved=0,keyByRel=/* @__PURE__ */ new Map;for(let[strippedKey,rels]of groups)if(rels.length===1)keyByRel.set(rels[0],strippedKey);else{collisionGroupsResolved+=1;for(let rel of rels)keyByRel.set(rel,`${namespace}/${rel}`)}return{pairs:paths.map(rel=>({rel,key:keyByRel.get(rel)??`${namespace}/${rel}`})),collisionGroupsResolved}}function stripExt(path){let lastSlash=path.lastIndexOf(`/`),filename=lastSlash>=0?path.slice(lastSlash+1):path,lastDot=filename.lastIndexOf(`.`);return lastDot<=0?path:(lastSlash>=0?path.slice(0,lastSlash+1):``)+filename.slice(0,lastDot)}const ASSET_MANIFEST_VERSION=1,ASSETS=createToken(`kick/assets/Map`);var UnknownAssetError=class extends Error{namespace;key;constructor(namespace,key){super(`Unknown asset '${namespace}/${key}'. Make sure the namespace exists in kick.config.ts assetMap and that the file is present in the source directory.`),this.name=`UnknownAssetError`,this.namespace=namespace,this.key=key}};let manifestCache;function toPosixPath(p){return p.replaceAll(`\\`,`/`)}function resolveAsset(namespace,key){let resolved=loadManifest();if(!resolved)throw new UnknownAssetError(namespace,key);let entry=resolved.manifest.entries[`${namespace}/${key}`];if(!entry)throw new UnknownAssetError(namespace,key);return toPosixPath(isAbsolute(entry)?entry:resolve(resolved.root,entry))}function clearAssetCache(){manifestCache=void 0}function loadManifest(){return isProduction()?(manifestCache===void 0&&(manifestCache=discoverManifest()),manifestCache):discoverManifest()}function discoverManifest(){let envRoot=process.env.KICK_ASSETS_ROOT;if(envRoot){let fromEnv=readBuiltManifest(envRoot);if(fromEnv)return fromEnv}let cwd=process.cwd(),config=loadConfigSync(cwd);if(!isProduction()){let fresh=synthesiseDevManifest(cwd,config);if(fresh)return fresh}let configOutDir=config?.build?.outDir;if(configOutDir&&!STANDARD_OUT_DIRS.includes(configOutDir)){let found=readBuiltManifest(resolve(cwd,configOutDir));if(found)return found}for(let candidate of STANDARD_OUT_DIRS){let found=readBuiltManifest(join(cwd,candidate));if(found)return found}return synthesiseDevManifest(cwd,config)}const STANDARD_OUT_DIRS=[`dist`,`build`,`out`];function readBuiltManifest(dir){let path=join(dir,`.kickjs-assets.json`);if(!existsSync(path))return null;try{let raw=readFileSync(path,`utf-8`),parsed=JSON.parse(raw);return parsed.version!==1||!parsed.entries||typeof parsed.entries!=`object`?null:{manifest:parsed,root:resolve(dir)}}catch{return null}}function synthesiseDevManifest(cwd,preloadedConfig){let config=preloadedConfig===void 0?loadConfigSync(cwd):preloadedConfig;if(!config?.assetMap)return null;let entries={};for(let[namespace,entry]of Object.entries(config.assetMap)){if(!entry||typeof entry.src!=`string`)continue;let srcAbs=resolve(cwd,entry.src);if(!existsSync(srcAbs))continue;let collected=[];walkSync(srcAbs,srcAbs,(relPath,absPath)=>{(!entry.glob||matchesGlobLite(relPath,entry.glob,namespace))&&collected.push({rel:relPath,abs:absPath})}),collected.sort((a,b)=>a.rel.localeCompare(b.rel));let{pairs,collisionGroupsResolved}=groupAssetKeys(namespace,collected.map(c=>c.rel),{strategy:entry.keys??`auto`}),absByRel=new Map(collected.map(c=>[c.rel,c.abs]));for(let{rel,key}of pairs){let abs=absByRel.get(rel);abs&&(entries[key]=abs)}collisionGroupsResolved>0&&!isProduction()&&console.log(`[kickjs/assets] '${namespace}': ${collisionGroupsResolved} basename collision(s) auto-resolved by keeping extensions (set assetMap.${namespace}.keys to 'strip' or 'with-extension' to override).`)}return{manifest:{version:1,entries},root:cwd}}const warnedGlobs=/* @__PURE__ */ new Set;function matchesGlobLite(relPath,pattern,namespace){if(pattern===`**/*`||pattern===`**`)return!0;let singleExt=/^\*\*\/\*\.(\w+)$/.exec(pattern);if(singleExt)return relPath.endsWith(`.${singleExt[1]}`);let braceExt=/^\*\*\/\*\.\{([^}]+)\}$/.exec(pattern);if(braceExt)return braceExt[1].split(`,`).map(e=>e.trim()).some(ext=>relPath.endsWith(`.${ext}`));let tag=`${namespace}::${pattern}`;return warnedGlobs.has(tag)||(warnedGlobs.add(tag),console.warn(`[kickjs/assets] Dev-mode glob '${pattern}' on '${namespace}' isn't recognised by the lite matcher. Falling back to '**/*'. Run 'kick build:assets' to use the full glob engine.`)),!0}function walkSync(root,dir,onFile){let entries;try{entries=readdirSync(dir,{withFileTypes:!0})}catch{return}for(let entry of entries){if(entry.name===`node_modules`||entry.name.startsWith(`.`))continue;let full=join(dir,entry.name);entry.isDirectory()?walkSync(root,full,onFile):entry.isFile()&&onFile(full.slice(root.length+1).split(sep).join(`/`),full)}}function loadConfigSync(cwd){let jsonPath=join(cwd,`kick.config.json`);if(existsSync(jsonPath))try{return JSON.parse(readFileSync(jsonPath,`utf-8`))}catch{return null}for(let filename of[`kick.config.cjs`,`kick.config.js`]){let path=join(cwd,filename);if(existsSync(path))try{let{createRequire}=__require(`node:module`),mod=createRequire(join(cwd,`package.json`))(path);return mod.default??mod??null}catch{continue}}let snapshotPath=join(cwd,`.kickjs`,`kick.config.json`);if(existsSync(snapshotPath))try{return JSON.parse(readFileSync(snapshotPath,`utf-8`))}catch{return null}return null}const PROMISE_DETECTION_KEYS=/* @__PURE__ */ new Set([`then`]),PASSTHROUGH_KEYS=/* @__PURE__ */ new Set([`toString`,`valueOf`,`constructor`,`prototype`,`name`,`length`,`asymmetricMatch`,`nodeType`,Symbol.toPrimitive,Symbol.toStringTag,Symbol.iterator,Symbol.asyncIterator]);function createNamespaceProxy(parts){return new Proxy(function(){},{apply(){if(parts.length<2)throw new UnknownAssetError(parts[0]??``,``);let[namespace,...rest]=parts;return resolveAsset(namespace,rest.join(`/`))},get(t,prop){if(!PROMISE_DETECTION_KEYS.has(prop)){if(PASSTHROUGH_KEYS.has(prop))return Reflect.get(t,prop);if(typeof prop!=`symbol`)return createNamespaceProxy([...parts,prop])}}})}function createAssetProxy(){return new Proxy({},{get(t,prop){if(!PROMISE_DETECTION_KEYS.has(prop)){if(PASSTHROUGH_KEYS.has(prop))return Reflect.get(t,prop);if(typeof prop!=`symbol`)return createNamespaceProxy([prop])}}})}const assets=createAssetProxy();function useAssets(){return assets}_setAssetResolver(resolveAsset);export{clearAssetCache as a,groupAssetKeys as c,assets as i,stripExt as l,ASSET_MANIFEST_VERSION as n,resolveAsset as o,UnknownAssetError as r,useAssets as s,ASSETS as t,defineContextDecorator as u};
|
|
12
|
-
//# sourceMappingURL=core-CFXpwc7m.mjs.map
|
|
@@ -1,13 +0,0 @@
|
|
|
1
|
-
/**
|
|
2
|
-
* @forinda/kickjs v10.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{t as Container}from"./container-C2aTj8Cb.mjs";import{r as describeSchemaVars,t as _useSecretFileReader}from"./settings-CFtEAQUs.mjs";import{createRequire}from"node:module";import{existsSync,readFileSync}from"node:fs";import{resolve}from"node:path";import{detectSchema}from"@forinda/kickjs-schema";var __require=/* @__PURE__ */ createRequire(import.meta.url);let _zod;function getZod(){if(_zod)return _zod;try{_zod=__require(`zod`)}catch{throw Error("@forinda/kickjs: the 'zod' peer dependency is required for baseEnvSchema / defineEnv / loadEnv but is not installed. Install it (`pnpm add zod`), or define your env with a non-Zod schema and call loadEnvFromSchema() instead — @forinda/kickjs-schema supports Valibot, Yup, and any Standard Schema validator without zod.")}return _zod}function isTestRun(){return process.env.NODE_ENV===`test`||!!process.env.VITEST}function envMode(){return isTestRun()?`test`:process.env.NODE_ENV??`development`}const GENERIC_ENV_FILES=[`.env.local`,`.env`];function resolveEnvFiles(){let explicit=process.env.KICKJS_ENV_FILE;if(explicit===`off`||explicit===`none`)return null;if(explicit)return explicit.split(`,`).map(f=>f.trim()).filter(Boolean);let exists=f=>existsSync(resolve(process.cwd(),f)),mode=envMode(),modeFiles=[`.env.${mode}.local`,`.env.${mode}`],found=(mode===`test`&&modeFiles.some(exists)?modeFiles:[...modeFiles,...GENERIC_ENV_FILES]).filter(exists);return found.length>0?found:null}let warnedTestBackfill=!1;function appliedKeys(before,parsed){return Object.keys(parsed).filter(k=>process.env[k]!==before[k])}function tryLoadDotenv(override=!1){let files=resolveEnvFiles();if(files)try{let dotenv=__require(`dotenv`),path=override?files.toReversed():files,usedGeneric=files.some(f=>GENERIC_ENV_FILES.includes(f)),mayWarn=!warnedTestBackfill&&isTestRun()&&usedGeneric,before=mayWarn?{...process.env}:void 0,result=dotenv.config({path,override,quiet:!0});if(mayWarn&&result.parsed){let applied=appliedKeys(before,result.parsed);applied.length>0&&(warnedTestBackfill=!0,console.warn(`[kickjs] test run took ${applied.length} env var(s) from ${files.join(`, `)} (${applied.slice(0,5).join(`, `)}${applied.length>5?`, …`:``}). Create a .env.test to isolate the suite, or set KICKJS_ENV_FILE=off.`))}}catch{}}tryLoadDotenv();function buildBaseEnvSchema(){let z=getZod();return z.object({PORT:z.coerce.number().default(3e3),NODE_ENV:z.enum([`development`,`production`,`test`]).default(`development`),LOG_LEVEL:z.string().default(`info`)})}let _baseEnvSchema;function getBaseEnvSchema(){return _baseEnvSchema||=buildBaseEnvSchema(),_baseEnvSchema}const baseEnvSchema=new Proxy({},{get(_t,prop){let real=getBaseEnvSchema(),value=real[prop];return typeof value==`function`?value.bind(real):value},has(_t,prop){return prop in getBaseEnvSchema()}});let cachedEnv=null,envOverlay=null;function overlaid(env){return envOverlay?{...env,...envOverlay}:env}function resolveEnvKey(key){return envOverlay&&key in envOverlay?envOverlay[key]:cachedEnv?.[key]}let cachedSchema=null;function defineEnv(extend){let base=getBaseEnvSchema(),userSchema=extend(base);return base.extend(userSchema.shape)}function loadEnv(schema){let s=schema??cachedSchema??getBaseEnvSchema();return cachedEnv&&cachedSchema===s?overlaid(cachedEnv):(cachedSchema=s,describingConfig()?{}:(cachedEnv=s.parse(withSecretFiles(process.env,Object.keys(s.shape??{}))),Container._envResolver=resolveEnvKey,overlaid(cachedEnv)))}function getEnv(key,fallback){return isZodObject(fallback)?(warnedSchemaArg||(warnedSchemaArg=!0,process.emitWarning(`getEnv(key, schema) is deprecated: register the schema once with loadEnv(envSchema); the second argument is now a fallback value.`,`DeprecationWarning`)),loadEnv(fallback)[key]):loadEnv()[key]??fallback}let warnedSchemaArg=!1;function isZodObject(value){return typeof value==`object`&&!!value&&typeof value.safeParse==`function`&&`shape`in value}async function withEnv(overrides,fn){loadEnv();let previous=envOverlay;envOverlay={...previous,...overrides};try{return await fn()}finally{envOverlay=previous}}function reloadEnv(){tryLoadDotenv(!0),cachedEnv=null,cachedSchema&&(typeof cachedSchema.parse==`function`?loadEnv(cachedSchema):loadEnvFromSchema(cachedSchema))}function resetEnvCache(){cachedEnv=null,cachedSchema=null,warnedTestBackfill=!1,Container._envResolver=null}function loadEnvFromSchema(schema){if(describingConfig())return cachedSchema=schema,{};let wrapped=detectSchema(schema),declared=Object.keys(wrapped.toJsonSchema?.()?.properties??{}),result=wrapped.safeParse(withSecretFiles(process.env,declared));if(!result.success){let details=result.issues.map(i=>` ${i.path.join(`.`)||`(root)`}: ${i.message}`).join(`
|
|
12
|
-
`);throw Error(`Environment validation failed:\n${details}`)}return cachedEnv=result.data,cachedSchema=schema,Container._envResolver=resolveEnvKey,overlaid(result.data)}function withSecretFiles(env,keys){let out;for(let key of keys){let path=env[`${key}_FILE`];if(!path)continue;if(env[key]!==void 0&&env[key]!==``)throw Error(`Environment: set either ${key} or ${key}_FILE, not both`);let value;try{value=readFileSync(path,`utf8`)}catch(err){throw Error(`Environment: ${key}_FILE points at ${path}, which could not be read (${err.code??`error`})`,{cause:err})}out??={...env},out[key]=value.replace(/\r?\n$/,``)}return out??env}_useSecretFileReader(withSecretFiles);const DESCRIBE_CONFIG=Symbol.for(`kickjs.config.describe`);function describingConfig(){return globalThis[DESCRIBE_CONFIG]===!0}function describeEnvSchema(){return describeSchemaVars(cachedSchema??getBaseEnvSchema())}function __decorate(decorators,target,key,desc){var c=arguments.length,r=c<3?target:desc===null?desc=Object.getOwnPropertyDescriptor(target,key):desc,d;if(typeof Reflect==`object`&&typeof Reflect.decorate==`function`)r=Reflect.decorate(decorators,target,key,desc);else for(var i=decorators.length-1;i>=0;i--)(d=decorators[i])&&(r=(c<3?d(r):c>3?d(target,key,r):d(target,key))||r);return c>3&&r&&Object.defineProperty(target,key,r),r}export{getEnv as a,reloadEnv as c,__require as d,describeEnvSchema as i,resetEnvCache as l,baseEnvSchema as n,loadEnv as o,defineEnv as r,loadEnvFromSchema as s,__decorate as t,withEnv as u};
|
|
13
|
-
//# sourceMappingURL=decorate-DkxaoRo5.mjs.map
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"file":"decorators-DaQUNXOn.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;;;;iBCrTb,WAAW,UAAU,iBAAiB;;iBAQtC,QAAQ,UAAU,iBAAiB;;iBAQnC,UAAU,UAAU,iBAAiB;;iBAQrC,WAAW,UAAU,iBAAiB;;;;;;;;;;iBAgBtC,cAAc;;iBAUd,iBAAiB;;;;;;;;;;;;;;;;;;iBAuBjB,cAAc;;;;;;;;;UAgBb;;GAEd,gBAAgB;;GAEhB,gBAAgB,0CAA0C;;;;;;;;;;;;;;;;;;;;iBA2C7C,UAAU,gBAAgB,yBACxC,OAAO,IACN;iBACa,UAAU,kBAAkB;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;iBAyC5B,OAAO,gBAAgB,yBACrC,OAAO,IACN;iBACa,OAAO,kBAAkB;;;;;;;;;;;;QAsBjC;YAEI;;;KAIA,eAAe;;;;;;;;;;;;;;;;KAiBf,IAAI,UAAU,SAAS,UAAU,QAAQ;;;;;;;;;;;;KAahD,SAAS,qBAAqB,0BAA0B,IAAI,IAAI;;;;;;;;;;;;;;;;iBAiBrD,MAAM,kBACpB,QAAQ,SAAS,IACjB,eAAe,UAAU,SAAS,QAAQ,eACzC;;;;;;;;;;;;KAqBE,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;;;;;;;;;;;;;;;;KAwBS,kBAAkB,eAAe,KAAK,MAAM,4BAA4B;;iBAGpE,cAAc,UAAU,sBAAsB,iBAAiB;;;;;KAqBnE,8BAA8B,kBAAkB;;;;;UAM3C;;EAEf;;;;;;EAMA,eAAe;;EAEf,gBAAgB;;UAGD,yBAAyB;EACxC;;EAEA;;EAEA;;;iBAIc,WAAW,QAAQ,mBAAmB;;;;;;;;;;;;;;;;;;;;;;;iBAoDtC,QAAQ;;;;;;;;;;;;;;;;;iBAoBR,YAAY,kBAAkB,qBAC5C,MAAM,IACL;EAAM,WAAW,UAAU,aAAa"}
|
|
@@ -1,12 +0,0 @@
|
|
|
1
|
-
/**
|
|
2
|
-
* @forinda/kickjs v10.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
|
-
const disposables=/* @__PURE__ */ new Set;function registerDisposable(fn){return disposables.add(fn),()=>disposables.delete(fn)}function drainDisposables(){let pending=[...disposables];return disposables.clear(),pending}async function runDisposables(list){await Promise.allSettled(list.map(async fn=>fn()))}async function disposeAll(){await runDisposables(drainDisposables())}export{runDisposables as i,drainDisposables as n,registerDisposable as r,disposeAll as t};
|
|
12
|
-
//# sourceMappingURL=disposables-5nFqc1aC.mjs.map
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"file":"disposables-5nFqc1aC.mjs","names":[],"sources":["../src/core/disposables.ts"],"sourcesContent":["/**\n * Registry for framework-owned resources that hold timers or other handles\n * outside the adapter/plugin lifecycle — e.g. the in-memory session and\n * rate-limit stores' cleanup intervals. `Application.shutdown()` drains it so\n * startup and shutdown stay symmetric even for resources created lazily by\n * middleware factories.\n *\n * Intervals are `.unref()`'d so they never wedge process exit — this registry\n * exists for IN-PROCESS teardown (test suites, HMR, multi-app hosts) where\n * each un-disposed store would otherwise leak a live interval + backing Map\n * per app instance.\n */\n\nexport type Disposable = () => void | Promise<void>\n\nconst disposables = new Set<Disposable>()\n\n/** Register a cleanup callback. Returns an unregister function. */\nexport function registerDisposable(fn: Disposable): () => void {\n disposables.add(fn)\n return () => disposables.delete(fn)\n}\n\n/**\n * Remove and return all currently registered disposables WITHOUT running\n * them. Used by HMR rebuild to snapshot the outgoing app's resources before\n * `setup()` registers the incoming app's — so the stale set can be disposed\n * on success, or restored on failure, without touching the new one.\n */\nexport function drainDisposables(): Disposable[] {\n const pending = [...disposables]\n disposables.clear()\n return pending\n}\n\n/**\n * Run a list of disposables. Errors — including SYNCHRONOUS throws — are\n * swallowed per-entry: the `async` callback converts a sync throw into a\n * rejection that `allSettled` absorbs, so one bad disposable can't abort\n * the rest (a bare `Promise.resolve(fn())` would let the throw escape the\n * `.map()` before `allSettled` ever ran).\n */\nexport async function runDisposables(list: Disposable[]): Promise<void> {\n await Promise.allSettled(list.map(async (fn) => fn()))\n}\n\n/** Run and clear all registered disposables. Errors are swallowed per-entry. */\nexport async function disposeAll(): Promise<void> {\n await runDisposables(drainDisposables())\n}\n"],"mappings":";;;;;;;;;;AAeA,MAAM,4BAAc,IAAI,IAGxB,SAAgB,mBAAmB,GAA4B,CAE7D,OADA,YAAY,IAAI,EAAE,MACL,YAAY,OAAO,EAAE,CACpC,CAQA,SAAgB,kBAAiC,CAC/C,IAAM,QAAU,CAAC,GAAG,WAAW,EAE/B,OADA,YAAY,MAAM,EACX,OACT,CASA,eAAsB,eAAe,KAAmC,CACtE,MAAM,QAAQ,WAAW,KAAK,IAAI,KAAO,KAAO,GAAG,CAAC,CAAC,CACvD,CAGA,eAAsB,YAA4B,CAChD,MAAM,eAAe,iBAAiB,CAAC,CACzC"}
|
|
@@ -1,75 +0,0 @@
|
|
|
1
|
-
|
|
2
|
-
import "reflect-metadata";
|
|
3
|
-
//#region src/core/interfaces.d.ts
|
|
4
|
-
/** Lifecycle scope for DI registrations */
|
|
5
|
-
declare enum Scope {
|
|
6
|
-
SINGLETON = "singleton",
|
|
7
|
-
TRANSIENT = "transient",
|
|
8
|
-
/** One instance per HTTP request, cached in AsyncLocalStorage. Throws outside request context. */
|
|
9
|
-
REQUEST = "request"
|
|
10
|
-
}
|
|
11
|
-
/** Generic constructor type */
|
|
12
|
-
type Constructor<T = any> = new (...args: any[]) => T;
|
|
13
|
-
/** A value that may or may not be wrapped in a Promise */
|
|
14
|
-
type MaybePromise<T = void> = T | Promise<T>;
|
|
15
|
-
/** Options for @Service, @Repository, @Component decorators */
|
|
16
|
-
interface ServiceOptions {
|
|
17
|
-
scope?: Scope;
|
|
18
|
-
}
|
|
19
|
-
/** Fluent builder type */
|
|
20
|
-
type BuilderOf<T> = { [K in keyof T as T[K] extends Function ? never : K]-?: (value: T[K]) => BuilderOf<T>; } & {
|
|
21
|
-
build(): T;
|
|
22
|
-
};
|
|
23
|
-
/** Class with static builder() method */
|
|
24
|
-
interface Buildable<T> {
|
|
25
|
-
builder(): BuilderOf<T>;
|
|
26
|
-
}
|
|
27
|
-
/** Decorator class kind for devtools introspection */
|
|
28
|
-
type ClassKind = 'service' | 'controller' | 'repository' | 'component' | 'injectable' | 'factory' | 'instance' | 'unknown';
|
|
29
|
-
/** PostConstruct lifecycle status */
|
|
30
|
-
type PostConstructStatus = 'pending' | 'completed' | 'failed' | 'skipped';
|
|
31
|
-
/**
|
|
32
|
-
* String metadata keys for the DI system + decorator subsystem. Every
|
|
33
|
-
* key starts with the `kick:` prefix; the suffix is a short identifier
|
|
34
|
-
* that may itself contain `:`, `-`, or `_` separators (historical —
|
|
35
|
-
* keys grew alongside the framework). The §22 v4 convention is "no
|
|
36
|
-
* Symbols", not "use a strict naming scheme" — Symbols don't survive
|
|
37
|
-
* JSON serialisation, can't be addressed by string from worker
|
|
38
|
-
* threads, and don't show up in DevTools snapshots.
|
|
39
|
-
*
|
|
40
|
-
* `reflect-metadata` accepts both Symbol and string keys identically,
|
|
41
|
-
* so the consumer-side change is internal — references go through the
|
|
42
|
-
* `METADATA` enum's named members (e.g. `METADATA.INJECT`), not the
|
|
43
|
-
* underlying string.
|
|
44
|
-
*
|
|
45
|
-
* The `design:*` entries match what TypeScript's
|
|
46
|
-
* `emitDecoratorMetadata` writes; those names are fixed by the
|
|
47
|
-
* compiler + must stay as-is.
|
|
48
|
-
*/
|
|
49
|
-
declare const METADATA: {
|
|
50
|
-
readonly INJECTABLE: 'kick:injectable';
|
|
51
|
-
readonly SCOPE: 'kick:scope';
|
|
52
|
-
readonly CLASS_KIND: 'kick:class-kind';
|
|
53
|
-
readonly AUTOWIRED: 'kick:autowired';
|
|
54
|
-
readonly INJECT: 'kick:inject';
|
|
55
|
-
readonly POST_CONSTRUCT: 'kick:post_construct';
|
|
56
|
-
readonly PRE_DESTROY: 'kick:pre_destroy';
|
|
57
|
-
readonly BUILDER: 'kick:builder';
|
|
58
|
-
readonly QUERY_PARAMS: 'kick:query:params';
|
|
59
|
-
readonly ROUTES: 'kick:routes';
|
|
60
|
-
readonly CLASS_MIDDLEWARES: 'kick:class:middlewares';
|
|
61
|
-
readonly METHOD_MIDDLEWARES: 'kick:method:middlewares';
|
|
62
|
-
readonly CLASS_CONTRIBUTORS: 'kick:class:contributors';
|
|
63
|
-
readonly METHOD_CONTRIBUTORS: 'kick:method:contributors';
|
|
64
|
-
readonly CLASS_FLAGS: 'kick:class:flags';
|
|
65
|
-
readonly METHOD_FLAGS: 'kick:method:flags';
|
|
66
|
-
readonly FILE_UPLOAD: 'kick:file:upload';
|
|
67
|
-
readonly VALUE: 'kick:value';
|
|
68
|
-
readonly ASSET: 'kick:asset';
|
|
69
|
-
readonly PARAM_TYPES: 'design:paramtypes';
|
|
70
|
-
readonly PROPERTY_TYPE: 'design:type';
|
|
71
|
-
readonly RETURN_TYPE: 'design:returntype';
|
|
72
|
-
};
|
|
73
|
-
//#endregion
|
|
74
|
-
export { METADATA as a, Scope as c, Constructor as i, ServiceOptions as l, BuilderOf as n, MaybePromise as o, ClassKind as r, PostConstructStatus as s, Buildable as t };
|
|
75
|
-
//# sourceMappingURL=interfaces-C1hCSoLD.d.mts.map
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"file":"interfaces-C1hCSoLD.d.mts","names":[],"sources":["../src/core/interfaces.ts"],"mappings":";;;;aAGY;EACV;EACA;;EAEA;;;KAIU,YAAY,mBAAmB,gBAAgB;;KAG/C,aAAa,YAAY,IAAI,QAAQ;;UAGhC;EACf,QAAQ;;;KAIE,UAAU,QACnB,WAAW,KAAK,EAAE,WAAW,mBAAmB,OAAO,OAAO,EAAE,OAAO,UAAU;EAC9E,SAAS;;;UAGE,UAAU;EACzB,WAAW,UAAU;;;KAIX;;KAWA;;;;;;;;;;;;;;;;;;;cAoBC;WACX;WACA;WACA;WACA;WACA;WACA;WACA;WACA;WACA;WACA;WACA;WACA;WACA;WACA;WACA;WACA;WACA;WACA;WACA;WAEA;WACA;WACA"}
|
package/dist/jobs-lLcPhIqq.mjs
DELETED
|
@@ -1,12 +0,0 @@
|
|
|
1
|
-
/**
|
|
2
|
-
* @forinda/kickjs v10.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{i as createToken}from"./container-C2aTj8Cb.mjs";import{createLogger}from"./core/logger.mjs";import{c as pushClassMeta,n as getClassMetaOrUndefined,t as getClassMeta,u as setClassMeta}from"./metadata-Tc6jhIBi.mjs";import{Service}from"./core/decorators.mjs";import{r as reportError}from"./observers-IGga6yut.mjs";const log=createLogger(`KickJobs`),JOB_META={JOB:`kick/queue/job`,PROCESS:`kick/queue/process`},jobClasses=/* @__PURE__ */ new Map;function Job(queue){return target=>{Service()(target),setClassMeta(JOB_META.JOB,queue,target),jobClasses.set(target.name,target)}}function Process(jobName){return(target,propertyKey)=>{pushClassMeta(JOB_META.PROCESS,target.constructor,{handlerName:propertyKey,jobName})}}function listJobHandlers(container){let handlers=[];for(let target of jobClasses.values()){if(!container.has(target))continue;let queue=getClassMetaOrUndefined(JOB_META.JOB,target);if(queue===void 0)continue;let processes=getClassMeta(JOB_META.PROCESS,target,[]);processes.length===0&&log.warn(`@Job('${queue}') class ${target.name} has no @Process methods`);for(let process of processes)handlers.push({...process,queue,target})}return handlers}function listJobQueues(container){return[...new Set(listJobHandlers(container).map(h=>h.queue))]}var NoJobHandlerError=class extends Error{queue;jobName;constructor(queue,jobName){super(`No @Process handler for job "${jobName}" on queue "${queue}"`),this.queue=queue,this.jobName=jobName,this.name=`NoJobHandlerError`}};async function runJob(container,queue,job,report={}){let handlers=listJobHandlers(container).filter(h=>h.queue===queue),handler=handlers.find(h=>h.jobName===job.name)??handlers.find(h=>h.jobName===void 0);try{if(!handler)throw new NoJobHandlerError(queue,job.name);let instance=container.resolve(handler.target);return await withJobContext(job,()=>instance[handler.handlerName](job))()}catch(err){throw log.error({err},`Job ${queue}/${job.name} failed`),reportError(err,{source:`job`,context:{queue,job:job.name,id:job.id,...report}}),err}}const JOB_CONTEXT_FIELD=`__kickContext`,jobContextCarriers=/* @__PURE__ */ new Map;function registerJobContext(carrier){jobContextCarriers.set(carrier.key,carrier)}const isPlainObject=v=>!!v&&typeof v==`object`&&Object.getPrototypeOf(v)===Object.prototype;function stampJobContext(data){if(!isPlainObject(data))return data;let{[JOB_CONTEXT_FIELD]:_untrusted,...rest}=data,context={};for(let[key,carrier]of jobContextCarriers){let value=carrier.capture();value!==void 0&&(context[key]=value)}return Object.keys(context).length>0?{...rest,[JOB_CONTEXT_FIELD]:context}:rest}function withJobContext(job,run){let data=job.data;if(!isPlainObject(data)||!(`__kickContext`in data))return run;let context=data[JOB_CONTEXT_FIELD];if(delete data[JOB_CONTEXT_FIELD],!isPlainObject(context))return run;let wrapped=run;for(let[key,value]of Object.entries(context)){let carrier=jobContextCarriers.get(key);if(!carrier)continue;let inner=wrapped;wrapped=()=>carrier.restore(value,inner)}return wrapped}const JOB_DISPATCHER=createToken(`kick/jobs/Dispatcher`);export{NoJobHandlerError as a,listJobQueues as c,stampJobContext as d,Job as i,registerJobContext as l,JOB_DISPATCHER as n,Process as o,JOB_META as r,listJobHandlers as s,JOB_CONTEXT_FIELD as t,runJob as u};
|
|
12
|
-
//# sourceMappingURL=jobs-lLcPhIqq.mjs.map
|
|
@@ -1,12 +0,0 @@
|
|
|
1
|
-
/**
|
|
2
|
-
* @forinda/kickjs v10.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";function setClassMeta(key,value,target){Reflect.defineMetadata(key,value,target)}function setMethodMeta(key,value,target,method){Reflect.defineMetadata(key,value,target,method)}function getClassMeta(key,target,fallback){return Reflect.getMetadata(key,target)??fallback}function getMethodMeta(key,target,method,fallback){return Reflect.getMetadata(key,target,method)??fallback}function hasClassMeta(key,target){return Reflect.hasMetadata(key,target)}function getClassMetaOrUndefined(key,target){return Reflect.getMetadata(key,target)}function getMethodMetaOrUndefined(key,target,method){return Reflect.getMetadata(key,target,method)}function pushClassMeta(key,target,...items){let existing=Reflect.getOwnMetadata(key,target)??[];Reflect.defineMetadata(key,[...existing,...items],target)}function pushMethodMeta(key,target,method,...items){let existing=Reflect.getOwnMetadata(key,target,method)??[];Reflect.defineMetadata(key,[...existing,...items],target,method)}function setInMetaMap(key,target,mapKey,mapValue){let inherited=Reflect.getOwnMetadata(key,target),map=inherited?new Map(inherited):/* @__PURE__ */ new Map;map.set(mapKey,mapValue),Reflect.defineMetadata(key,map,target)}function getMetaMap(key,target){return Reflect.getMetadata(key,target)??/* @__PURE__ */ new Map}function setInMetaRecord(key,target,recKey,recValue){let inherited=Reflect.getOwnMetadata(key,target),rec=inherited?{...inherited}:{};rec[recKey]=recValue,Reflect.defineMetadata(key,rec,target)}function getMetaRecord(key,target){return Reflect.getMetadata(key,target)??{}}export{getMethodMeta as a,pushClassMeta as c,setInMetaMap as d,setInMetaRecord as f,getMetaRecord as i,pushMethodMeta as l,getClassMetaOrUndefined as n,getMethodMetaOrUndefined as o,setMethodMeta as p,getMetaMap as r,hasClassMeta as s,getClassMeta as t,setClassMeta as u};
|
|
12
|
-
//# sourceMappingURL=metadata-Tc6jhIBi.mjs.map
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"file":"metadata-Tc6jhIBi.mjs","names":[],"sources":["../src/core/metadata.ts"],"sourcesContent":["import 'reflect-metadata'\nimport type { InjectionToken } from './token'\n\n/**\n * Typed utilities for reflect-metadata operations.\n *\n * Replaces scattered Reflect.defineMetadata/getMetadata calls with a single\n * source of truth. If we later move to Stage 3 decorators or a WeakMap-based\n * store, only this file changes — all 24+ consumer files stay untouched.\n *\n * Keys may be symbols, strings, or `InjectionToken<T>` objects produced by\n * `createToken()`. Using `createToken` is the preferred pattern because the\n * token's phantom type flows through the helpers, enabling type-safe reads.\n */\n\ntype MetaKey = symbol | string | InjectionToken<unknown>\n\n// ── Setters ─────────────────────────────────────────────────────\n\n/** Set metadata on a class (or prototype for property decorators) */\nexport function setClassMeta<T>(key: MetaKey, value: T, target: object): void {\n Reflect.defineMetadata(key, value, target)\n}\n\n/** Set metadata on a specific method */\nexport function setMethodMeta<T>(key: MetaKey, value: T, target: object, method: string): void {\n Reflect.defineMetadata(key, value, target, method)\n}\n\n// ── Getters ─────────────────────────────────────────────────────\n\n/** Get metadata from a class, returning `fallback` if not set */\nexport function getClassMeta<T>(key: MetaKey, target: object, fallback: T): T {\n return (Reflect.getMetadata(key, target) as T) ?? fallback\n}\n\n/** Get metadata from a specific method, returning `fallback` if not set */\nexport function getMethodMeta<T>(key: MetaKey, target: object, method: string, fallback: T): T {\n return (Reflect.getMetadata(key, target, method) as T) ?? fallback\n}\n\n/** Check if metadata exists on a class */\nexport function hasClassMeta(key: MetaKey, target: object): boolean {\n return Reflect.hasMetadata(key, target)\n}\n\n/** Get metadata from a class with no default (returns undefined if absent) */\nexport function getClassMetaOrUndefined<T>(key: MetaKey, target: object): T | undefined {\n return Reflect.getMetadata(key, target) as T | undefined\n}\n\n/** Get metadata from a method with no default (returns undefined if absent) */\nexport function getMethodMetaOrUndefined<T>(\n key: MetaKey,\n target: object,\n method: string,\n): T | undefined {\n return Reflect.getMetadata(key, target, method) as T | undefined\n}\n\n// ── Accumulate: Arrays ──────────────────────────────────────────\n\n/** Append items to an array stored in class metadata */\nexport function pushClassMeta<T>(key: MetaKey, target: object, ...items: T[]): void {\n const existing: T[] = Reflect.getOwnMetadata(key, target) ?? []\n Reflect.defineMetadata(key, [...existing, ...items], target)\n}\n\n/** Append items to an array stored in method metadata */\nexport function pushMethodMeta<T>(\n key: MetaKey,\n target: object,\n method: string,\n ...items: T[]\n): void {\n const existing: T[] = Reflect.getOwnMetadata(key, target, method) ?? []\n Reflect.defineMetadata(key, [...existing, ...items], target, method)\n}\n\n// ── Accumulate: Maps ────────────────────────────────────────────\n\n/** Set a key/value in a Map stored in class metadata */\nexport function setInMetaMap<K, V>(key: MetaKey, target: object, mapKey: K, mapValue: V): void {\n const inherited: Map<K, V> | undefined = Reflect.getOwnMetadata(key, target)\n const map = inherited ? new Map(inherited) : new Map<K, V>()\n map.set(mapKey, mapValue)\n Reflect.defineMetadata(key, map, target)\n}\n\n/** Get a Map from class metadata (returns empty Map if absent) */\nexport function getMetaMap<K, V>(key: MetaKey, target: object): Map<K, V> {\n return Reflect.getMetadata(key, target) ?? new Map()\n}\n\n// ── Accumulate: Records ─────────────────────────────────────────\n\n/** Set a key/value in a Record stored in class metadata */\nexport function setInMetaRecord<V>(\n key: MetaKey,\n target: object,\n recKey: string | number,\n recValue: V,\n): void {\n const inherited: Record<string | number, V> | undefined = Reflect.getOwnMetadata(key, target)\n const rec = inherited ? { ...inherited } : {}\n rec[recKey] = recValue\n Reflect.defineMetadata(key, rec, target)\n}\n\n/** Get a Record from class metadata (returns empty object if absent) */\nexport function getMetaRecord<V>(key: MetaKey, target: object): Record<string | number, V> {\n return Reflect.getMetadata(key, target) ?? {}\n}\n"],"mappings":";;;;;;;;;;yBAoBA,SAAgB,aAAgB,IAAc,MAAU,OAAsB,CAC5E,QAAQ,eAAe,IAAK,MAAO,MAAM,CAC3C,CAGA,SAAgB,cAAiB,IAAc,MAAU,OAAgB,OAAsB,CAC7F,QAAQ,eAAe,IAAK,MAAO,OAAQ,MAAM,CACnD,CAKA,SAAgB,aAAgB,IAAc,OAAgB,SAAgB,CAC5E,OAAQ,QAAQ,YAAY,IAAK,MAAM,GAAW,QACpD,CAGA,SAAgB,cAAiB,IAAc,OAAgB,OAAgB,SAAgB,CAC7F,OAAQ,QAAQ,YAAY,IAAK,OAAQ,MAAM,GAAW,QAC5D,CAGA,SAAgB,aAAa,IAAc,OAAyB,CAClE,OAAO,QAAQ,YAAY,IAAK,MAAM,CACxC,CAGA,SAAgB,wBAA2B,IAAc,OAA+B,CACtF,OAAO,QAAQ,YAAY,IAAK,MAAM,CACxC,CAGA,SAAgB,yBACd,IACA,OACA,OACe,CACf,OAAO,QAAQ,YAAY,IAAK,OAAQ,MAAM,CAChD,CAKA,SAAgB,cAAiB,IAAc,OAAgB,GAAG,MAAkB,CAClF,IAAM,SAAgB,QAAQ,eAAe,IAAK,MAAM,GAAK,CAAC,EAC9D,QAAQ,eAAe,IAAK,CAAC,GAAG,SAAU,GAAG,KAAK,EAAG,MAAM,CAC7D,CAGA,SAAgB,eACd,IACA,OACA,OACA,GAAG,MACG,CACN,IAAM,SAAgB,QAAQ,eAAe,IAAK,OAAQ,MAAM,GAAK,CAAC,EACtE,QAAQ,eAAe,IAAK,CAAC,GAAG,SAAU,GAAG,KAAK,EAAG,OAAQ,MAAM,CACrE,CAKA,SAAgB,aAAmB,IAAc,OAAgB,OAAW,SAAmB,CAC7F,IAAM,UAAmC,QAAQ,eAAe,IAAK,MAAM,EACrE,IAAM,UAAY,IAAI,IAAI,SAAS,kBAAI,IAAI,IACjD,IAAI,IAAI,OAAQ,QAAQ,EACxB,QAAQ,eAAe,IAAK,IAAK,MAAM,CACzC,CAGA,SAAgB,WAAiB,IAAc,OAA2B,CACxE,OAAO,QAAQ,YAAY,IAAK,MAAM,mBAAK,IAAI,GACjD,CAKA,SAAgB,gBACd,IACA,OACA,OACA,SACM,CACN,IAAM,UAAoD,QAAQ,eAAe,IAAK,MAAM,EACtF,IAAM,UAAY,CAAE,GAAG,SAAU,EAAI,CAAC,EAC5C,IAAI,QAAU,SACd,QAAQ,eAAe,IAAK,IAAK,MAAM,CACzC,CAGA,SAAgB,cAAiB,IAAc,OAA4C,CACzF,OAAO,QAAQ,YAAY,IAAK,MAAM,GAAK,CAAC,CAC9C"}
|
|
@@ -1,12 +0,0 @@
|
|
|
1
|
-
/**
|
|
2
|
-
* @forinda/kickjs v10.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}from"./core/interfaces.mjs";import{o as duplicateRouteError,t as Container}from"./container-C2aTj8Cb.mjs";import{a as getMethodMeta,o as getMethodMetaOrUndefined,t as getClassMeta}from"./metadata-Tc6jhIBi.mjs";import{a as getMethodFlagDeclarations,c as registerMountFlags,i as getClassFlagDeclarations,l as resolveRouteFlags,u as toFlagDeclarations}from"./route-flag-BjRpxryx.mjs";import{i as MissingContributorError,n as DuplicateContributorError,t as ContributorCycleError}from"./context-errors-6psUheqc.mjs";import{t as runContributors}from"./contributor-runner-Bn-ipSS5.mjs";const PRECEDENCE_ORDER=[`method`,`class`,`module`,`adapter`,`global`];function buildPipeline(sources,options={}){let route=options.route,bySource=/* @__PURE__ */ new Map;for(let src of PRECEDENCE_ORDER)bySource.set(src,[]);for(let entry of sources)bySource.get(entry.source).push(entry);let winners=/* @__PURE__ */ new Map;for(let src of PRECEDENCE_ORDER){let rows=bySource.get(src),keysAtThisLevel=/* @__PURE__ */ new Map;for(let row of rows){let key=row.registration.key,existing=keysAtThisLevel.get(key)??[];existing.push(row),keysAtThisLevel.set(key,existing)}for(let[key,rowsForKey]of keysAtThisLevel){if(rowsForKey.length>1){let labels=rowsForKey.map((r,i)=>r.label??`${src}#${i}`);throw new DuplicateContributorError(key,labels)}winners.has(key)||winners.set(key,rowsForKey[0])}}let survivors=[...winners.values()].map(r=>r.registration),allKeys=new Set(survivors.map(r=>r.key));for(let reg of survivors)for(let dep of reg.dependsOn)if(!allKeys.has(dep))throw new MissingContributorError(dep,reg.key,route,reg.definedAt);let sorted=topoSort(survivors,route);return Object.freeze({contributors:Object.freeze(sorted),keys:allKeys})}function splitBeforeValidation(pipeline,route){let early=pipeline.contributors.filter(reg=>reg.beforeValidation);if(early.length===0)return{early:null,late:pipeline};let earlyKeys=new Set(early.map(reg=>reg.key));for(let reg of early){let lateDep=reg.dependsOn.find(dep=>!earlyKeys.has(dep));if(lateDep!==void 0)throw Error(`Contributor '${reg.key}'${route?` on ${route}`:``} sets beforeValidation but depends on '${lateDep}', which runs after validation. Set beforeValidation on '${lateDep}' too, or remove it from '${reg.key}'.`)}let late=pipeline.contributors.filter(reg=>!reg.beforeValidation);return{early:Object.freeze({contributors:Object.freeze(early),keys:earlyKeys}),late:late.length===0?null:Object.freeze({contributors:Object.freeze(late),keys:new Set(late.map(reg=>reg.key))})}}function topoSort(registrations,route){let indegree=/* @__PURE__ */ new Map,dependents=/* @__PURE__ */ new Map,byKey=/* @__PURE__ */ new Map;for(let reg of registrations)indegree.set(reg.key,reg.dependsOn.length),byKey.set(reg.key,reg);for(let reg of registrations)for(let dep of reg.dependsOn){let list=dependents.get(dep)??[];list.push(reg),dependents.set(dep,list)}let queue=[];for(let reg of registrations)indegree.get(reg.key)===0&&queue.push(reg);let sorted=[];for(;queue.length>0;){let node=queue.shift();sorted.push(node);for(let dependent of dependents.get(node.key)??[]){let next=(indegree.get(dependent.key)??0)-1;indegree.set(dependent.key,next),next===0&&queue.push(dependent)}}if(sorted.length!==registrations.length){let remaining=registrations.filter(r=>(indegree.get(r.key)??0)>0);throw new ContributorCycleError(reconstructCycle(remaining,byKey),route)}return sorted}function reconstructCycle(residual,byKey){let residualKeys=new Set(residual.map(r=>r.key)),start=residual[0].key,path=[start],seen=/* @__PURE__ */ new Set([start]),cursor=start;for(;;){let nextDep=byKey.get(cursor).dependsOn.find(d=>residualKeys.has(d));if(nextDep===void 0)break;if(seen.has(nextDep)){let cycleStart=path.indexOf(nextDep);return[...path.slice(cycleStart),nextDep]}path.push(nextDep),seen.add(nextDep),cursor=nextDep}return path}let _externalContributorSources=[];function _setExternalContributorSources(sources){_externalContributorSources=sources}function assertRouteUnique(registry,method,fullPath,owner){let key=`${method.toUpperCase()} ${fullPath.replace(/:[^/]+/g,`:*`)}`,prior=registry.get(key);if(prior!==void 0)throw duplicateRouteError(method.toUpperCase(),fullPath,owner,prior);registry.set(key,owner)}function buildRouteTable(controllerClass,options={}){let container=Container.getInstance(),externalSources=options.externalSources??_externalContributorSources,routes=getClassMeta(METADATA.ROUTES,controllerClass,[]),classMiddlewares=getClassMeta(METADATA.CLASS_MIDDLEWARES,controllerClass,[]),classContributors=getClassMeta(METADATA.CLASS_CONTRIBUTORS,controllerClass,[]),classFlagDeclarations=getClassFlagDeclarations(controllerClass),mountFlagDeclarations=toFlagDeclarations(options.mountFlags,`${controllerClass?.name??`controller`} mount flags`);registerMountFlags(controllerClass,mountFlagDeclarations);let entries=[];for(let route of routes){let method=route.method.toUpperCase(),fullPath=route.path||`/`,methodMiddlewares=getMethodMeta(METADATA.METHOD_MIDDLEWARES,controllerClass,route.handlerName,[]),fileUploadConfig=getMethodMetaOrUndefined(METADATA.FILE_UPLOAD,controllerClass,route.handlerName),methodContributors=getMethodMeta(METADATA.METHOD_CONTRIBUTORS,controllerClass,route.handlerName,[]),flags=resolveRouteFlags(classFlagDeclarations,getMethodFlagDeclarations(controllerClass,route.handlerName),mountFlagDeclarations),contributorRunner=null,earlyContributorRunner=null,contributors;if(classContributors.length>0||methodContributors.length>0||externalSources.length>0){let sources=[...methodContributors.map((registration,i)=>({source:`method`,registration,label:`${controllerClass.name}.${String(route.handlerName)}#${i}(${registration.key})`})),...classContributors.map((registration,i)=>({source:`class`,registration,label:`${controllerClass.name}.@class#${i}(${registration.key})`})),...externalSources],routeLabel=`${method} ${fullPath}`,pipeline=buildPipeline(sources,{route:routeLabel});contributors=describePipeline(pipeline.contributors,sources);let{early,late}=splitBeforeValidation(pipeline,routeLabel);early&&(earlyContributorRunner=ctx=>runContributors({pipeline:early,ctx,container,flags})),late&&(contributorRunner=ctx=>runContributors({pipeline:late,ctx,container,flags}))}let handler=ctx=>container.resolve(controllerClass)[route.handlerName](ctx);entries.push({method,path:fullPath,middlewares:[...classMiddlewares,...methodMiddlewares],contributorRunner,earlyContributorRunner,handler,meta:{controller:controllerClass,handlerName:route.handlerName,validation:route.validation,upload:fileUploadConfig,flags,...contributors?{contributors}:{}}})}return entries}function describePipeline(ordered,sources){let bySource=new Map(sources.map(s=>[s.registration,s]));return[...ordered.filter(r=>r.beforeValidation===!0),...ordered.filter(r=>r.beforeValidation!==!0)].map(registration=>{let winner=bySource.get(registration),described={key:registration.key,source:winner?.source??`global`,dependsOn:registration.dependsOn,beforeValidation:registration.beforeValidation===!0,overrides:sources.filter(s=>s.registration!==registration&&s.registration.key===registration.key).map(s=>s.label?{source:s.source,label:s.label}:{source:s.source})};return winner?.label&&(described.label=winner.label),described})}export{buildPipeline as i,assertRouteUnique as n,buildRouteTable as r,_setExternalContributorSources as t};
|
|
12
|
-
//# sourceMappingURL=router-builder-CrWKq6O2.mjs.map
|
|
@@ -1,14 +0,0 @@
|
|
|
1
|
-
/**
|
|
2
|
-
* @forinda/kickjs v10.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{r as INJECTION_TOKEN,t as Container}from"./container-C2aTj8Cb.mjs";import{detectSchema}from"@forinda/kickjs-schema";let readSecretFiles;function _useSecretFileReader(reader){readSecretFiles=reader}const PROVIDED=Symbol.for(`kickjs.settings.provided`);function isProvided(decl){return decl[PROVIDED]===!0}const envSegment=key=>key.replace(/([a-z0-9])([A-Z])/g,`$1_$2`).toUpperCase();function leavesOf(shape,prefix,path=[],required=!0){if(shape.properties){let own=new Set(shape.required??[]),parentRequired=required&&shape.default===void 0;return Object.entries(shape.properties).flatMap(([key,child])=>leavesOf(child,prefix,[...path,key],parentRequired&&own.has(key)))}let types=Array.isArray(shape.type)?shape.type:[shape.type];return[{path,env:[prefix,...path.map(envSegment)].join(`_`),list:types.includes(`array`),required:required&&shape.default===void 0,...shape.default===void 0?{}:{default:shape.default},...shape.description?{description:shape.description}:{}}]}const toConfigVar=leaf=>({name:leaf.env,required:leaf.required,list:leaf.list,...leaf.default===void 0?{}:{default:leaf.default},...leaf.description?{description:leaf.description}:{}});function describeSchemaVars(schema){let shape=detectSchema(schema).toJsonSchema(),required=new Set(shape.required??[]);return Object.entries(shape.properties??{}).map(([key,child])=>{let described=toConfigVar(leavesOf(child,``,[key],required.has(key))[0]);return described.name=key,described})}function originsOf(vars,env=process.env){let has=name=>env[name]!==void 0&&env[name]!==``;return vars.map(v=>{let origin=`unset`;return has(v.name)?origin=`env`:readSecretFiles&&has(`${v.name}_FILE`)?origin=`file`:v.default!==void 0&&(origin=`default`),{name:v.name,origin}})}const cached=/* @__PURE__ */ new WeakMap;function defineSettings(prefix,schema){return createSection(prefix,schema)}function createSection(prefix,schema){if(!/^[A-Z][A-Z0-9_]*$/.test(prefix))throw Error(`defineSettings: prefix '${prefix}' must be UPPER_SNAKE_CASE, e.g. 'DB'`);let wrapped=detectSchema(schema),shape=wrapped.toJsonSchema();if(!shape.properties)throw Error(`defineSettings('${prefix}'): the schema must be an object whose keys can be read (Zod, Valibot or Yup) — a bare Standard Schema has no shape to map to env names.`);let leaves=leavesOf(shape,prefix),seenEnv=/* @__PURE__ */ new Map;for(let leaf of leaves){let path=leaf.path.join(`.`),other=seenEnv.get(leaf.env);if(other!==void 0)throw Error(`defineSettings('${prefix}'): '${other}' and '${path}' both read ${leaf.env} — rename one`);seenEnv.set(leaf.env,path)}let envNames=leaves.map(leaf=>leaf.env),byPath=new Map(leaves.map(leaf=>[leaf.path.join(`.`),leaf.env])),load=(env=process.env)=>{let source=readSecretFiles?readSecretFiles(env,envNames):env,input={};for(let leaf of leaves){let raw=source[leaf.env];if(raw===void 0)continue;let target=input;for(let key of leaf.path.slice(0,-1))target=target[key]??={};target[leaf.path.at(-1)]=leaf.list?raw.split(`,`).map(item=>item.trim()).filter(Boolean):raw}return validate(input)},validate=input=>{let result=wrapped.safeParse(input);if(result.success)return result.data;let problems=result.issues.map(issue=>{let key=issue.path.join(`.`);return` ${byPath.get(key)??[prefix,...issue.path.map(p=>envSegment(String(p)))].join(`_`)}: ${issue.message}`});throw Error(`Settings '${prefix}' are invalid:\n${problems.join(`
|
|
12
|
-
`)}`)},scopes=/* @__PURE__ */ new Map,settings=Object.freeze({[INJECTION_TOKEN]:!0,name:`Settings(${prefix})`,prefix,envNames,load,parse:value=>validate(value),provide:value=>Object.freeze({[PROVIDED]:!0,section:settings,value}),describe:()=>leaves.map(toConfigVar),get:()=>{let container=Container.getInstance();return container.has(settings)?container.resolve(settings):(cached.has(settings)||cached.set(settings,load()),cached.get(settings))},scoped:name=>{let scopePrefix=`${name}_${prefix}`,scoped=scopes.get(scopePrefix);return scoped||(scoped=createSection(scopePrefix,schema),scopes.set(scopePrefix,scoped)),scoped}});return settings}function loadSettings(declarations,env=process.env,byPrefix=/* @__PURE__ */ new Map,providedBefore=/* @__PURE__ */ new Map){let values=/* @__PURE__ */ new Map,failures=[],provided=/* @__PURE__ */ new Map,sections=[];for(let decl of declarations)if(isProvided(decl)){let earlier=provided.has(decl.section)?provided:providedBefore;if(earlier.has(decl.section)&&earlier.get(decl.section)!==decl.value){failures.push(`Settings '${decl.section.prefix}' are provided twice with different values.`);continue}provided.set(decl.section,decl.value),sections.push(decl.section)}else sections.push(decl);for(let section of sections){if(values.has(section))continue;let other=byPrefix.get(section.prefix);if(other!==section||provided.has(section)&&!providedBefore.has(section)){if(other&&other!==section)failures.push(`Two different settings sections use the prefix '${section.prefix}'.`);else{byPrefix.set(section.prefix,section);try{let value=provided.has(section)?section.parse(provided.get(section)):section.load(env);values.set(section,value),provided.has(section)&&providedBefore.set(section,provided.get(section)),cached.set(section,value)}catch(err){failures.push(err.message)}}}}if(failures.length>0)throw Error(failures.join(`
|
|
13
|
-
`));return values}export{originsOf as a,loadSettings as i,defineSettings as n,describeSchemaVars as r,_useSecretFileReader as t};
|
|
14
|
-
//# sourceMappingURL=settings-CFtEAQUs.mjs.map
|
|
@@ -1,12 +0,0 @@
|
|
|
1
|
-
/**
|
|
2
|
-
* @forinda/kickjs v10.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{i as createToken}from"./container-C2aTj8Cb.mjs";var MutableModuleRegistry=class{entries=[];mount(module){this.entries.push(module)}};const ROUTE_URLS=createToken(`kick/Http/routeUrls`);var RouteUrls=class{paths=/* @__PURE__ */ new Map;add(name,path){this.paths.has(name)||this.paths.set(name,path)}urlFor(name,...args){let[params,query]=args;return this.build(name,params,query)}build(name,params,query){let pattern=this.paths.get(name);if(pattern===void 0)throw Error(`urlFor: no route named '${name}' — expected 'Controller.method'`);let path=pattern.replace(/:([A-Za-z0-9_]+)/g,(_,key)=>{let value=params?.[key];if(value==null||value===``)throw Error(`urlFor('${name}'): missing param '${key}' for '${pattern}'`);return encodeURIComponent(String(value))});if(!query)return path;let search=new URLSearchParams;for(let[key,value]of Object.entries(query))for(let v of Array.isArray(value)?value:[value])search.append(key,String(v));let qs=search.toString();return qs?`${path}?${qs}`:path}};export{RouteUrls as n,MutableModuleRegistry as r,ROUTE_URLS as t};
|
|
12
|
-
//# sourceMappingURL=url-for-Cyh7pJCb.mjs.map
|