@forinda/kickjs 5.3.0 → 5.4.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (90) hide show
  1. package/dist/application-mir5CSWO.mjs +12 -0
  2. package/dist/{application-Cna_2gex.mjs.map → application-mir5CSWO.mjs.map} +1 -1
  3. package/dist/bootstrap-B7j_-dOg.mjs +12 -0
  4. package/dist/{bootstrap-kPcmbbWe.mjs.map → bootstrap-B7j_-dOg.mjs.map} +1 -1
  5. package/dist/config/index.mjs +2 -4
  6. package/dist/config-Dk5RVTnD.mjs +12 -0
  7. package/dist/{config-DxEREQmR.mjs.map → config-Dk5RVTnD.mjs.map} +1 -1
  8. package/dist/container-DArhTDQQ.mjs +12 -0
  9. package/dist/{container-SMnB5yeT.mjs.map → container-DArhTDQQ.mjs.map} +1 -1
  10. package/dist/{context-Ymvv-85x.d.mts → context-BAdAV-zO.d.mts} +48 -11
  11. package/dist/context-BAdAV-zO.d.mts.map +1 -0
  12. package/dist/context-CIoXqpAX.mjs +12 -0
  13. package/dist/context-CIoXqpAX.mjs.map +1 -0
  14. package/dist/core/adapter.mjs +2 -2
  15. package/dist/core/app-module.mjs +2 -2
  16. package/dist/core/cache.mjs +2 -103
  17. package/dist/core/cache.mjs.map +1 -1
  18. package/dist/core/container.mjs +2 -3
  19. package/dist/core/cron.mjs +2 -32
  20. package/dist/core/cron.mjs.map +1 -1
  21. package/dist/core/decorators.mjs +2 -285
  22. package/dist/core/decorators.mjs.map +1 -1
  23. package/dist/core/errors.mjs +2 -110
  24. package/dist/core/errors.mjs.map +1 -1
  25. package/dist/core/interfaces.mjs +2 -53
  26. package/dist/core/interfaces.mjs.map +1 -1
  27. package/dist/core/logger.mjs +2 -207
  28. package/dist/core/logger.mjs.map +1 -1
  29. package/dist/core/path.mjs +2 -35
  30. package/dist/core/path.mjs.map +1 -1
  31. package/dist/core/plugin.mjs +2 -2
  32. package/dist/core/reactivity.mjs +2 -179
  33. package/dist/core/reactivity.mjs.map +1 -1
  34. package/dist/core-BQZyB8Wv.mjs +12 -0
  35. package/dist/{core--a4XflX7.mjs.map → core-BQZyB8Wv.mjs.map} +1 -1
  36. package/dist/env-BL0xOTyi.mjs +12 -0
  37. package/dist/{env-C4Yr6nN8.mjs.map → env-BL0xOTyi.mjs.map} +1 -1
  38. package/dist/http/application.mjs +2 -3
  39. package/dist/http/bootstrap.mjs +2 -3
  40. package/dist/http/context.d.mts +2 -2
  41. package/dist/http/context.mjs +2 -3
  42. package/dist/http/middleware/cors.mjs +2 -73
  43. package/dist/http/middleware/cors.mjs.map +1 -1
  44. package/dist/http/middleware/csrf.mjs +2 -62
  45. package/dist/http/middleware/csrf.mjs.map +1 -1
  46. package/dist/http/middleware/error-handler.mjs +2 -54
  47. package/dist/http/middleware/error-handler.mjs.map +1 -1
  48. package/dist/http/middleware/helmet.mjs +2 -41
  49. package/dist/http/middleware/helmet.mjs.map +1 -1
  50. package/dist/http/middleware/rate-limit.mjs +2 -91
  51. package/dist/http/middleware/rate-limit.mjs.map +1 -1
  52. package/dist/http/middleware/request-id.mjs +2 -25
  53. package/dist/http/middleware/request-id.mjs.map +1 -1
  54. package/dist/http/middleware/request-logger.mjs +2 -39
  55. package/dist/http/middleware/request-logger.mjs.map +1 -1
  56. package/dist/http/middleware/session.mjs +2 -167
  57. package/dist/http/middleware/session.mjs.map +1 -1
  58. package/dist/http/middleware/spa.mjs +2 -98
  59. package/dist/http/middleware/spa.mjs.map +1 -1
  60. package/dist/http/middleware/upload.mjs +2 -181
  61. package/dist/http/middleware/upload.mjs.map +1 -1
  62. package/dist/http/middleware/validate.mjs +2 -68
  63. package/dist/http/middleware/validate.mjs.map +1 -1
  64. package/dist/http/middleware/views.d.mts +1 -1
  65. package/dist/http/middleware/views.mjs +2 -56
  66. package/dist/http/middleware/views.mjs.map +1 -1
  67. package/dist/http/query/index.mjs +2 -3
  68. package/dist/http/router-builder.mjs +2 -105
  69. package/dist/http/router-builder.mjs.map +1 -1
  70. package/dist/index.d.mts +3 -3
  71. package/dist/index.mjs +2 -171
  72. package/dist/index.mjs.map +1 -1
  73. package/dist/metadata-Dn6kNT82.mjs +12 -0
  74. package/dist/{metadata-CdYaU-XM.mjs.map → metadata-Dn6kNT82.mjs.map} +1 -1
  75. package/dist/query-B7n5isk_.mjs +12 -0
  76. package/dist/{query-nAYUgagU.mjs.map → query-B7n5isk_.mjs.map} +1 -1
  77. package/dist/{views-DkNp9JJs.d.mts → views-oKRSw0Op.d.mts} +2 -2
  78. package/dist/{views-DkNp9JJs.d.mts.map → views-oKRSw0Op.d.mts.map} +1 -1
  79. package/package.json +1 -1
  80. package/dist/application-Cna_2gex.mjs +0 -574
  81. package/dist/bootstrap-kPcmbbWe.mjs +0 -195
  82. package/dist/config-DxEREQmR.mjs +0 -135
  83. package/dist/container-SMnB5yeT.mjs +0 -897
  84. package/dist/context-B0B3WQft.mjs +0 -348
  85. package/dist/context-B0B3WQft.mjs.map +0 -1
  86. package/dist/context-Ymvv-85x.d.mts.map +0 -1
  87. package/dist/core--a4XflX7.mjs +0 -820
  88. package/dist/env-C4Yr6nN8.mjs +0 -137
  89. package/dist/metadata-CdYaU-XM.mjs +0 -76
  90. package/dist/query-nAYUgagU.mjs +0 -164
@@ -1,820 +0,0 @@
1
- /**
2
- * @forinda/kickjs v5.3.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 "./container-SMnB5yeT.mjs";
12
- import { METADATA } from "./core/interfaces.mjs";
13
- import "./core/logger.mjs";
14
- import { c as pushClassMeta, l as pushMethodMeta } from "./metadata-CdYaU-XM.mjs";
15
- import "./core/decorators.mjs";
16
- import "./core/cron.mjs";
17
- import "./core/cache.mjs";
18
- import "reflect-metadata";
19
- //#region src/core/circuit-breaker.ts
20
- /**
21
- * Error thrown when the circuit is open and calls are being rejected.
22
- */
23
- var CircuitOpenError = class extends Error {
24
- constructor(breakerName) {
25
- super(`Circuit breaker "${breakerName}" is open — request rejected`);
26
- this.breakerName = breakerName;
27
- this.name = "CircuitOpenError";
28
- }
29
- };
30
- var CircuitBreaker = class {
31
- state = "closed";
32
- failures = 0;
33
- successes = 0;
34
- halfOpenAttempts = 0;
35
- lastFailure;
36
- openedAt;
37
- failureThreshold;
38
- resetTimeout;
39
- halfOpenMax;
40
- constructor(name, options) {
41
- this.name = name;
42
- this.failureThreshold = options.failureThreshold;
43
- this.resetTimeout = options.resetTimeout;
44
- this.halfOpenMax = options.halfOpenMax ?? 1;
45
- }
46
- /**
47
- * Execute an async function through the circuit breaker.
48
- * Throws `CircuitOpenError` if the circuit is open.
49
- */
50
- async execute(fn) {
51
- this.maybeTransitionToHalfOpen();
52
- if (this.state === "open") throw new CircuitOpenError(this.name);
53
- if (this.state === "half_open" && this.halfOpenAttempts >= this.halfOpenMax) throw new CircuitOpenError(this.name);
54
- if (this.state === "half_open") this.halfOpenAttempts++;
55
- try {
56
- const result = await fn();
57
- this.onSuccess();
58
- return result;
59
- } catch (error) {
60
- this.onFailure();
61
- throw error;
62
- }
63
- }
64
- /** Returns the current circuit state. */
65
- getState() {
66
- this.maybeTransitionToHalfOpen();
67
- return this.state;
68
- }
69
- /** Returns current statistics. */
70
- getStats() {
71
- this.maybeTransitionToHalfOpen();
72
- return {
73
- failures: this.failures,
74
- successes: this.successes,
75
- state: this.state,
76
- ...this.lastFailure ? { lastFailure: this.lastFailure } : {}
77
- };
78
- }
79
- /** Manually reset the circuit breaker to CLOSED state. */
80
- reset() {
81
- this.state = "closed";
82
- this.failures = 0;
83
- this.successes = 0;
84
- this.halfOpenAttempts = 0;
85
- this.lastFailure = void 0;
86
- this.openedAt = void 0;
87
- }
88
- onSuccess() {
89
- if (this.state === "half_open") {
90
- this.state = "closed";
91
- this.failures = 0;
92
- this.halfOpenAttempts = 0;
93
- this.openedAt = void 0;
94
- }
95
- this.successes++;
96
- }
97
- onFailure() {
98
- this.failures++;
99
- this.lastFailure = /* @__PURE__ */ new Date();
100
- if (this.state === "half_open") {
101
- this.state = "open";
102
- this.openedAt = Date.now();
103
- this.halfOpenAttempts = 0;
104
- } else if (this.state === "closed" && this.failures >= this.failureThreshold) {
105
- this.state = "open";
106
- this.openedAt = Date.now();
107
- }
108
- }
109
- maybeTransitionToHalfOpen() {
110
- if (this.state === "open" && this.openedAt != null) {
111
- if (Date.now() - this.openedAt >= this.resetTimeout) {
112
- this.state = "half_open";
113
- this.halfOpenAttempts = 0;
114
- }
115
- }
116
- }
117
- };
118
- //#endregion
119
- //#region src/core/context-decorator.ts
120
- /**
121
- * Define a typed context contributor.
122
- *
123
- * The returned function works as a method or class decorator:
124
- *
125
- * ```ts
126
- * const LoadTenant = defineContextDecorator({
127
- * key: 'tenant',
128
- * deps: { tenants: TenantsRepo },
129
- * resolve: (ctx, { tenants }) => tenants.findByHost(ctx.requestId),
130
- * })
131
- *
132
- * @LoadTenant
133
- * @Get('/me')
134
- * me(ctx: RequestContext) {
135
- * ctx.get('tenant') // typed via ContextMeta
136
- * }
137
- * ```
138
- *
139
- * For non-decorator registration (module/adapter/bootstrap), pass
140
- * `LoadTenant.registration` into the appropriate contributors list.
141
- *
142
- * **No runtime behaviour is wired in Phase 1.** This factory only writes
143
- * metadata; the topo-sort, runner, and HTTP integration land in later
144
- * phases. See `architecture.md` §20 for the full pipeline plan.
145
- */
146
- function defineContextDecorator(spec) {
147
- const defaults = Object.freeze({ ...spec.paramDefaults ?? {} });
148
- const sharedDeps = Object.freeze({ ...spec.deps ?? {} });
149
- const sharedDependsOn = Object.freeze([...spec.dependsOn ?? []]);
150
- const sharedOptional = spec.optional ?? false;
151
- /**
152
- * Build a frozen registration that closes over a specific
153
- * resolved-params object. The runner sees a normal
154
- * `(ctx, deps) => value` registration — params are baked into the
155
- * closure, invisible to the pipeline.
156
- */
157
- const buildRegistration = (params) => {
158
- const frozenParams = Object.freeze({ ...params });
159
- const onError = spec.onError ? (err, ctx) => spec.onError(err, ctx, frozenParams) : void 0;
160
- const resolve = (ctx, deps) => spec.resolve(ctx, deps, frozenParams);
161
- return Object.freeze({
162
- key: spec.key,
163
- deps: sharedDeps,
164
- dependsOn: sharedDependsOn,
165
- optional: sharedOptional,
166
- onError,
167
- resolve
168
- });
169
- };
170
- const defaultRegistration = buildRegistration({ ...defaults });
171
- /**
172
- * Decide whether the decorator was called as a decorator
173
- * (`@Foo` / `@Foo(target, key)`) or as a factory
174
- * (`@Foo()` / `@Foo({...})`).
175
- *
176
- * - Class decorator: `(target)` where target is a constructor function.
177
- * - Method decorator: `(target, propertyKey, descriptor?)` where
178
- * target is a prototype object and propertyKey is a string/symbol.
179
- * - Factory (defaults): `()` — adopter wrote `@Foo()` (rare; usually
180
- * they write the bare `@Foo`). Returns a decorator using
181
- * `paramDefaults`.
182
- * - Factory (params): `(params)` where params is a plain object.
183
- *
184
- * The legacy decorators that ship with KickJS (`@Get('/path')`,
185
- * `@Cron('* * * *')`, etc.) use the same heuristic, so adopters
186
- * already know to pass plain object literals as factory args.
187
- */
188
- const isDecoratorCall = (args) => {
189
- if (args.length === 0) return false;
190
- if (args.length >= 2) return true;
191
- if (typeof args[0] === "function") return true;
192
- return false;
193
- };
194
- const applyAsDecorator = (registration, target, propertyKey) => {
195
- if (propertyKey === void 0) pushClassMeta(METADATA.CLASS_CONTRIBUTORS, target, registration);
196
- else {
197
- const constructor = target.constructor;
198
- pushMethodMeta(METADATA.METHOD_CONTRIBUTORS, constructor, String(propertyKey), registration);
199
- }
200
- };
201
- /**
202
- * `true` for `{...}` and `Object.create(null)`. Rejects every
203
- * built-in subclass (Map / Set / Date / Error / RegExp / Promise),
204
- * adopter classes, and arrays.
205
- */
206
- const isPlainObject = (value) => {
207
- const proto = Object.getPrototypeOf(value);
208
- return proto === Object.prototype || proto === null;
209
- };
210
- /**
211
- * Merge call-site `Partial<P>` over `paramDefaults`. Strict guard:
212
- * accepts only **plain object literals** (or `Object.create(null)`).
213
- * Reject everything else with a descriptive `TypeError`.
214
- *
215
- * Why strict? Object spread copies enumerable own properties only.
216
- * `{ ...new Date() }` and `{ ...new Map([...])}` both produce `{}`
217
- * — the params silently drop. Catching this at the boundary
218
- * surfaces the mistake instead of routing the request with empty
219
- * config. Adopters who genuinely need a class-instance shape can
220
- * destructure it themselves: `Foo({ ...new MyParams() })`.
221
- */
222
- const mergeParams = (override) => {
223
- if (override === void 0) return { ...defaults };
224
- if (override === null || typeof override !== "object" || Array.isArray(override) || !isPlainObject(override)) {
225
- const got = override === null ? "null" : Array.isArray(override) ? "array" : typeof override === "object" ? `instance of ${override.constructor?.name ?? "unknown class"}` : typeof override;
226
- throw new 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 })\`.`);
227
- }
228
- return {
229
- ...defaults,
230
- ...override
231
- };
232
- };
233
- function decoratorOrFactory(...args) {
234
- if (isDecoratorCall(args)) {
235
- const [target, propertyKey] = args;
236
- applyAsDecorator(defaultRegistration, target, propertyKey);
237
- return;
238
- }
239
- const registration = buildRegistration(mergeParams(args[0]));
240
- return (target, propertyKey) => {
241
- applyAsDecorator(registration, target, propertyKey);
242
- };
243
- }
244
- Object.defineProperty(decoratorOrFactory, "registration", {
245
- value: defaultRegistration,
246
- writable: false,
247
- enumerable: true,
248
- configurable: false
249
- });
250
- Object.defineProperty(decoratorOrFactory, "with", {
251
- value: (params) => ({ registration: buildRegistration(mergeParams(params)) }),
252
- writable: false,
253
- enumerable: true,
254
- configurable: false
255
- });
256
- return decoratorOrFactory;
257
- }
258
- //#endregion
259
- //#region src/core/context-errors.ts
260
- /**
261
- * Errors thrown by the Context Contributor pipeline.
262
- *
263
- * All three are startup-time errors raised during pipeline build (topo-sort
264
- * + validation), not per-request — a misconfigured app fails to boot rather
265
- * than fails a request. Per the locked design in `architecture.md` §20.4,
266
- * the pipeline is validated once when each route is mounted and the
267
- * resolved order is cached on the route.
268
- */
269
- /**
270
- * A contributor declared `dependsOn: ['<key>']` but no other contributor
271
- * (at any precedence level) produces that key for the same route.
272
- *
273
- * @example
274
- * ```text
275
- * MissingContributorError: Missing context contributor 'tenant' required by 'project' on route GET /projects/:id
276
- * ```
277
- */
278
- var MissingContributorError = class extends Error {
279
- key;
280
- dependent;
281
- route;
282
- constructor(key, dependent, route) {
283
- const where = route ? ` on route ${route}` : "";
284
- super(`Missing context contributor '${key}' required by '${dependent}'${where}`);
285
- this.name = "MissingContributorError";
286
- this.key = key;
287
- this.dependent = dependent;
288
- this.route = route;
289
- }
290
- };
291
- /**
292
- * Topo-sort detected a cycle in `dependsOn` declarations. The `cycle` field
293
- * lists the keys in the order they form the loop, with the first key
294
- * repeated at the end so the path reads naturally.
295
- *
296
- * @example
297
- * ```text
298
- * ContributorCycleError: Cycle in context contributors on route GET /projects/:id: tenant → project → tenant
299
- * ```
300
- */
301
- var ContributorCycleError = class extends Error {
302
- cycle;
303
- route;
304
- constructor(cycle, route) {
305
- const where = route ? ` on route ${route}` : "";
306
- super(`Cycle in context contributors${where}: ${cycle.join(" → ")}`);
307
- this.name = "ContributorCycleError";
308
- this.cycle = Object.freeze([...cycle]);
309
- this.route = route;
310
- }
311
- };
312
- /**
313
- * Two contributors at the same precedence level both produce the same key
314
- * for the same route. Precedence resolution (method > class > module >
315
- * adapter > global, per architecture.md §20.4) silently drops
316
- * lower-precedence duplicates; this error fires only when ties occur
317
- * within a single level — e.g., two method-level decorators declaring
318
- * `key: 'tenant'`.
319
- *
320
- * `sources` is best-effort identifying labels for each conflicting
321
- * registration (typically the decorator's call site or registering
322
- * module/adapter name).
323
- *
324
- * @example
325
- * ```text
326
- * DuplicateContributorError: Duplicate context contributor for key 'tenant' at the same precedence level. Sources: LoadTenantFromHeader, LoadTenantFromSubdomain
327
- * ```
328
- */
329
- var DuplicateContributorError = class extends Error {
330
- key;
331
- sources;
332
- constructor(key, sources) {
333
- super(`Duplicate context contributor for key '${key}' at the same precedence level. Sources: ${sources.join(", ")}`);
334
- this.name = "DuplicateContributorError";
335
- this.key = key;
336
- this.sources = Object.freeze([...sources]);
337
- }
338
- };
339
- //#endregion
340
- //#region src/core/contributor-pipeline.ts
341
- /** Precedence-ranked source list. Index = precedence; method (0) wins ties. */
342
- const PRECEDENCE_ORDER = [
343
- "method",
344
- "class",
345
- "module",
346
- "adapter",
347
- "global"
348
- ];
349
- /**
350
- * Build, validate, and topo-sort a contributor pipeline.
351
- *
352
- * Pipeline:
353
- *
354
- * 1. Group sources by precedence (method > class > module > adapter > global).
355
- * 2. Within each precedence level, two contributors with the same `key`
356
- * raise {@link DuplicateContributorError}.
357
- * 3. Across levels, the highest-precedence contributor wins each key
358
- * (lower-precedence duplicates are silently dropped — that is the
359
- * documented override mechanism, not an error).
360
- * 4. Every key referenced by `dependsOn` must be produced by the
361
- * surviving set, otherwise {@link MissingContributorError}.
362
- * 5. Kahn's algorithm topo-sorts the survivors. Any nodes left after
363
- * the queue drains form a cycle → {@link ContributorCycleError}
364
- * with a reconstructed path.
365
- *
366
- * Pure function — no DI, no I/O. Safe to call once at startup per
367
- * route and cache the result.
368
- */
369
- function buildPipeline(sources, options = {}) {
370
- const route = options.route;
371
- const bySource = /* @__PURE__ */ new Map();
372
- for (const src of PRECEDENCE_ORDER) bySource.set(src, []);
373
- for (const entry of sources) bySource.get(entry.source).push(entry);
374
- const winners = /* @__PURE__ */ new Map();
375
- for (const src of PRECEDENCE_ORDER) {
376
- const rows = bySource.get(src);
377
- const keysAtThisLevel = /* @__PURE__ */ new Map();
378
- for (const row of rows) {
379
- const key = row.registration.key;
380
- const existing = keysAtThisLevel.get(key) ?? [];
381
- existing.push(row);
382
- keysAtThisLevel.set(key, existing);
383
- }
384
- for (const [key, rowsForKey] of keysAtThisLevel) {
385
- if (rowsForKey.length > 1) throw new DuplicateContributorError(key, rowsForKey.map((r, i) => r.label ?? `${src}#${i}`));
386
- if (!winners.has(key)) winners.set(key, rowsForKey[0]);
387
- }
388
- }
389
- const survivors = [...winners.values()].map((r) => r.registration);
390
- const allKeys = new Set(survivors.map((r) => r.key));
391
- for (const reg of survivors) for (const dep of reg.dependsOn) if (!allKeys.has(dep)) throw new MissingContributorError(dep, reg.key, route);
392
- const sorted = topoSort(survivors, route);
393
- return Object.freeze({
394
- contributors: Object.freeze(sorted),
395
- keys: allKeys
396
- });
397
- }
398
- /**
399
- * Kahn's algorithm with deterministic ordering on ties.
400
- *
401
- * Nodes with no remaining incoming edges enter the queue in input
402
- * order. Cycles surface as nodes still present after the queue
403
- * drains; we reconstruct one cycle path for diagnostics.
404
- */
405
- function topoSort(registrations, route) {
406
- const indegree = /* @__PURE__ */ new Map();
407
- const dependents = /* @__PURE__ */ new Map();
408
- const byKey = /* @__PURE__ */ new Map();
409
- for (const reg of registrations) {
410
- indegree.set(reg.key, reg.dependsOn.length);
411
- byKey.set(reg.key, reg);
412
- }
413
- for (const reg of registrations) for (const dep of reg.dependsOn) {
414
- const list = dependents.get(dep) ?? [];
415
- list.push(reg);
416
- dependents.set(dep, list);
417
- }
418
- const queue = [];
419
- for (const reg of registrations) if (indegree.get(reg.key) === 0) queue.push(reg);
420
- const sorted = [];
421
- while (queue.length > 0) {
422
- const node = queue.shift();
423
- sorted.push(node);
424
- for (const dependent of dependents.get(node.key) ?? []) {
425
- const next = (indegree.get(dependent.key) ?? 0) - 1;
426
- indegree.set(dependent.key, next);
427
- if (next === 0) queue.push(dependent);
428
- }
429
- }
430
- if (sorted.length !== registrations.length) throw new ContributorCycleError(reconstructCycle$1(registrations.filter((r) => (indegree.get(r.key) ?? 0) > 0), byKey), route);
431
- return sorted;
432
- }
433
- /**
434
- * Reconstruct one cycle path from the residual graph.
435
- *
436
- * Walks from any remaining node, following its first dependency that's
437
- * still in the residual set, until we revisit a node. The path returned
438
- * starts and ends with the same key so the message reads naturally:
439
- * `tenant → project → tenant`.
440
- */
441
- function reconstructCycle$1(residual, byKey) {
442
- const residualKeys = new Set(residual.map((r) => r.key));
443
- const start = residual[0].key;
444
- const path = [start];
445
- const seen = new Set([start]);
446
- let cursor = start;
447
- while (true) {
448
- const nextDep = byKey.get(cursor).dependsOn.find((d) => residualKeys.has(d));
449
- if (nextDep === void 0) break;
450
- if (seen.has(nextDep)) {
451
- const cycleStart = path.indexOf(nextDep);
452
- return [...path.slice(cycleStart), nextDep];
453
- }
454
- path.push(nextDep);
455
- seen.add(nextDep);
456
- cursor = nextDep;
457
- }
458
- return path;
459
- }
460
- //#endregion
461
- //#region src/core/contributor-runner.ts
462
- /**
463
- * Execute a built {@link ContributorPipeline} against an {@link ExecutionContext}.
464
- *
465
- * Sequential — one contributor at a time, in the topo order chosen at
466
- * pipeline-build time. Per `architecture.md` §20.10, V1 does not run
467
- * contributors in parallel even within the same topo level; that is a
468
- * V2 follow-up gated on profiling.
469
- *
470
- * ## Error matrix (architecture.md §20.9)
471
- *
472
- * | resolve outcome | optional | onError defined | runner behaviour |
473
- * |-----------------|----------|-----------------|--------------------------------------------------|
474
- * | throws | true | — | skip; `ctx.get(key)` remains undefined |
475
- * | throws | false | yes | call hook; returned value (if any) stored |
476
- * | throws | false | no | propagate the original error |
477
- * | hook throws | — | yes | propagate the new error |
478
- * | hook returns | — | yes | undefined/void → skip; value → `ctx.set(key, v)` |
479
- * | resolves | — | — | `ctx.set(key, value)` |
480
- *
481
- * Container.resolve() throwing while building `deps` is treated as a
482
- * resolve-side throw and flows through the same matrix — adopters who
483
- * need different behaviour for missing-DI vs. data-lookup failures can
484
- * wrap the container access inside their own `resolve()`.
485
- */
486
- async function runContributors(options) {
487
- const { pipeline, ctx, container } = options;
488
- for (const reg of pipeline.contributors) await runOne(reg, ctx, container);
489
- }
490
- async function runOne(reg, ctx, container) {
491
- let value;
492
- try {
493
- const deps = resolveDeps(reg, container);
494
- value = await reg.resolve(ctx, deps);
495
- } catch (err) {
496
- if (reg.optional) return;
497
- if (reg.onError) {
498
- const replacement = await reg.onError(err, ctx);
499
- if (replacement === void 0) return;
500
- ctx.set(reg.key, replacement);
501
- return;
502
- }
503
- throw err;
504
- }
505
- ctx.set(reg.key, value);
506
- }
507
- /**
508
- * Resolve a contributor's declared dependencies through the container,
509
- * preserving the property names from the spec so `resolve(ctx, deps)`
510
- * receives exactly the shape the user wrote.
511
- *
512
- * Empty `deps` produces an empty object — `resolve()` always sees an
513
- * object, never `undefined`.
514
- */
515
- function resolveDeps(reg, container) {
516
- const out = {};
517
- for (const [key, token] of Object.entries(reg.deps)) out[key] = container.resolve(token);
518
- return out;
519
- }
520
- //#endregion
521
- //#region src/core/mount-sort.ts
522
- /**
523
- * Two items in the same mount set declared the same `name`. Plugin/adapter
524
- * names must be unique so `dependsOn` references resolve unambiguously.
525
- */
526
- var DuplicateMountNameError = class extends Error {
527
- kind;
528
- mountName;
529
- constructor(kind, mountName) {
530
- super(`Duplicate ${kind} name '${mountName}' — every ${kind} must declare a unique name`);
531
- this.name = "DuplicateMountNameError";
532
- this.kind = kind;
533
- this.mountName = mountName;
534
- }
535
- };
536
- /**
537
- * A `dependsOn` entry references a plugin/adapter that isn't in the
538
- * current set. The dependency might not be installed, might be misspelled,
539
- * or might live in a different mount set (plugin referencing an adapter,
540
- * or vice versa — they sort independently).
541
- */
542
- var MissingMountDepError = class extends Error {
543
- kind;
544
- missing;
545
- dependent;
546
- constructor(kind, missing, dependent) {
547
- super(`Missing ${kind} dependency '${missing}' required by '${dependent}' — is the ${kind} installed and named correctly?`);
548
- this.name = "MissingMountDepError";
549
- this.kind = kind;
550
- this.missing = missing;
551
- this.dependent = dependent;
552
- }
553
- };
554
- /**
555
- * The `dependsOn` declarations form a cycle. Boot fails so the cycle
556
- * can't poison live traffic. The `cycle` field reports one path through
557
- * the offending nodes for diagnostics — formatted `A → B → C → A`.
558
- */
559
- var MountCycleError = class extends Error {
560
- kind;
561
- cycle;
562
- constructor(kind, cycle) {
563
- super(`Cycle in ${kind} dependsOn declarations: ${cycle.join(" → ")}`);
564
- this.name = "MountCycleError";
565
- this.kind = kind;
566
- this.cycle = Object.freeze([...cycle]);
567
- }
568
- };
569
- /**
570
- * Topologically sort `items` so every item with `dependsOn: ['X']` mounts
571
- * after `X`. Items without `dependsOn` keep their input order via Kahn's
572
- * algorithm with a FIFO queue seeded in input order — preserves the
573
- * historical "plugins/adapters mount in declaration order" behaviour for
574
- * any set that doesn't use `dependsOn`.
575
- *
576
- * @param items - mountable items, e.g. plugins or adapters
577
- * @param kind - 'plugin' | 'adapter', used in error messages
578
- * @returns a new array in valid mount order
579
- * @throws {DuplicateMountNameError} two items share a name
580
- * @throws {MissingMountDepError} a `dependsOn` references an unknown name
581
- * @throws {MountCycleError} the dep graph contains a cycle
582
- */
583
- function mountSort(items, kind) {
584
- const byName = /* @__PURE__ */ new Map();
585
- for (const item of items) {
586
- if (byName.has(item.name)) throw new DuplicateMountNameError(kind, item.name);
587
- byName.set(item.name, item);
588
- }
589
- const indegree = /* @__PURE__ */ new Map();
590
- const dependents = /* @__PURE__ */ new Map();
591
- for (const item of items) indegree.set(item.name, item.dependsOn?.length ?? 0);
592
- for (const item of items) for (const dep of item.dependsOn ?? []) {
593
- if (!byName.has(dep)) throw new MissingMountDepError(kind, dep, item.name);
594
- const list = dependents.get(dep) ?? [];
595
- list.push(item);
596
- dependents.set(dep, list);
597
- }
598
- const queue = [];
599
- for (const item of items) if (indegree.get(item.name) === 0) queue.push(item);
600
- const sorted = [];
601
- while (queue.length > 0) {
602
- const node = queue.shift();
603
- sorted.push(node);
604
- for (const dependent of dependents.get(node.name) ?? []) {
605
- const next = (indegree.get(dependent.name) ?? 0) - 1;
606
- indegree.set(dependent.name, next);
607
- if (next === 0) queue.push(dependent);
608
- }
609
- }
610
- if (sorted.length !== items.length) throw new MountCycleError(kind, reconstructCycle(items.filter((it) => (indegree.get(it.name) ?? 0) > 0), byName));
611
- return sorted;
612
- }
613
- /**
614
- * Walk the residual graph to find one cycle path for diagnostics.
615
- * Starts from the first remaining node and follows the first dep that's
616
- * still in the residual set until we revisit a node. Returns a path
617
- * starting and ending with the same name so the message reads naturally
618
- * (`A → B → C → A`).
619
- */
620
- function reconstructCycle(residual, byName) {
621
- const residualNames = new Set(residual.map((r) => r.name));
622
- const start = residual[0].name;
623
- const path = [start];
624
- const seen = new Set([start]);
625
- let cursor = start;
626
- while (true) {
627
- const nextDep = byName.get(cursor).dependsOn?.find((d) => residualNames.has(d));
628
- if (nextDep === void 0) break;
629
- if (seen.has(nextDep)) {
630
- const cycleStart = path.indexOf(nextDep);
631
- return [...path.slice(cycleStart), nextDep];
632
- }
633
- path.push(nextDep);
634
- seen.add(nextDep);
635
- cursor = nextDep;
636
- }
637
- return path;
638
- }
639
- //#endregion
640
- //#region src/core/define-plugin.ts
641
- const mergeConfig$1 = (defaults = {}, overrides = {}) => ({
642
- ...defaults,
643
- ...overrides
644
- });
645
- const composeName$1 = (base, scope) => `${base}:${scope}`;
646
- /**
647
- * Build a {@link KickPlugin} factory from a typed definition. See
648
- * `architecture.md` §21.2.2 for the design rationale.
649
- *
650
- * @example
651
- * ```ts
652
- * const FlagsPlugin = definePlugin<FlagsConfig>({
653
- * name: 'FlagsPlugin',
654
- * defaults: { defaultTtl: 60_000 },
655
- * build(config) {
656
- * return {
657
- * register(container) {
658
- * container.registerInstance(FLAGS, makeProvider(config))
659
- * },
660
- * }
661
- * },
662
- * })
663
- *
664
- * bootstrap({ plugins: [FlagsPlugin({ provider: launchDarkly })] })
665
- * ```
666
- */
667
- function definePlugin(options) {
668
- const buildSync = (instanceName, scoped, overrides) => {
669
- const config = mergeConfig$1(options.defaults, overrides);
670
- const built = options.build(config, {
671
- name: instanceName,
672
- scoped
673
- });
674
- built.name = instanceName;
675
- return built;
676
- };
677
- const buildAsync = (instanceName, opts) => {
678
- let inner;
679
- const ensureInner = async (container) => {
680
- if (inner) return inner;
681
- const deps = (opts.inject ?? []).map((tok) => container.resolve(tok));
682
- inner = buildSync(instanceName, false, await opts.useFactory(...deps));
683
- return inner;
684
- };
685
- return {
686
- name: instanceName,
687
- async onReady(container) {
688
- const built = await ensureInner(container);
689
- built.register?.(container);
690
- await built.onReady?.(container);
691
- },
692
- async shutdown() {
693
- await inner?.shutdown?.();
694
- }
695
- };
696
- };
697
- const factory = ((config) => buildSync(options.name, false, config));
698
- factory.scoped = (scopeName, config) => buildSync(composeName$1(options.name, scopeName), true, config);
699
- factory.async = (opts) => buildAsync(options.name, opts);
700
- Object.defineProperty(factory, "definition", { value: Object.freeze({ ...options }) });
701
- return factory;
702
- }
703
- //#endregion
704
- //#region src/core/define-adapter.ts
705
- const mergeConfig = (defaults = {}, overrides = {}) => ({
706
- ...defaults,
707
- ...overrides
708
- });
709
- const composeName = (base, scope) => `${base}:${scope}`;
710
- /**
711
- * Build an {@link AppAdapter} factory from a typed definition. See
712
- * `architecture.md` §21.3.4 for migration guidance — most first-party
713
- * adapter packages collapse to a single `defineAdapter()` call after this
714
- * lands.
715
- *
716
- * @example
717
- * ```ts
718
- * const TenantAdapter = defineAdapter<TenantConfig>({
719
- * name: 'TenantAdapter',
720
- * defaults: { strategy: 'header', required: true },
721
- * build: (config) => ({
722
- * middleware: () => [tenantResolverMiddleware(config)],
723
- * beforeStart: ({ container }) => registerTenantFactory(container, config),
724
- * }),
725
- * })
726
- *
727
- * bootstrap({
728
- * adapters: [
729
- * TenantAdapter({ strategy: 'subdomain' }),
730
- * TenantAdapter.scoped('shard-eu', { headerName: 'x-eu-tenant' }),
731
- * ],
732
- * })
733
- * ```
734
- */
735
- function defineAdapter(options) {
736
- const buildSync = (instanceName, scoped, overrides) => {
737
- const config = mergeConfig(options.defaults, overrides);
738
- const built = options.build(config, {
739
- name: instanceName,
740
- scoped
741
- });
742
- built.name = instanceName;
743
- return built;
744
- };
745
- const buildAsync = (instanceName, opts) => {
746
- let inner;
747
- return {
748
- name: instanceName,
749
- async beforeStart(ctx) {
750
- const deps = (opts.inject ?? []).map((tok) => ctx.container.resolve(tok));
751
- inner = buildSync(instanceName, false, await opts.useFactory(...deps));
752
- await inner.beforeStart?.(ctx);
753
- },
754
- async afterStart(ctx) {
755
- await inner?.afterStart?.(ctx);
756
- },
757
- async shutdown() {
758
- await inner?.shutdown?.();
759
- },
760
- async onHealthCheck() {
761
- return await inner?.onHealthCheck?.() ?? {
762
- name: instanceName,
763
- status: "up"
764
- };
765
- }
766
- };
767
- };
768
- const factory = ((config) => buildSync(options.name, false, config));
769
- factory.scoped = (scopeName, config) => buildSync(composeName(options.name, scopeName), true, config);
770
- factory.async = (opts) => buildAsync(options.name, opts);
771
- Object.defineProperty(factory, "definition", { value: Object.freeze({ ...options }) });
772
- return factory;
773
- }
774
- //#endregion
775
- //#region src/core/augmentation.ts
776
- /**
777
- * Advertise an augmentable interface so `kick typegen` can list it in
778
- * `.kickjs/types/augmentations.d.ts` for project-wide discovery.
779
- *
780
- * **This function is a runtime AND type-level no-op.** It does NOT
781
- * augment the interface for TypeScript. The actual augmentation is
782
- * the `declare module` block — `defineAugmentation` only adds an
783
- * entry to the typegen catalogue so other contributors / adopters
784
- * can find the interface and know its expected shape.
785
- *
786
- * Both calls are needed:
787
- *
788
- * ```ts
789
- * import { defineAugmentation } from '@forinda/kickjs'
790
- *
791
- * // (1) The actual TS augmentation — what `ctx.get('tenant')` reads.
792
- * declare module '@forinda/kickjs' {
793
- * interface ContextMeta {
794
- * tenant: { id: string; name: string }
795
- * }
796
- * }
797
- *
798
- * // (2) Catalogue entry — what `kick typegen` lists in
799
- * // `.kickjs/types/augmentations.d.ts` for browseability.
800
- * defineAugmentation('ContextMeta', {
801
- * description: 'Tenant resolved from x-tenant-id by TenantAdapter',
802
- * example: `{
803
- * tenant: {
804
- * id: string
805
- * name: string
806
- * plan: 'free' | 'pro' | 'enterprise'
807
- * featureFlags: Record<string, boolean>
808
- * }
809
- * }`,
810
- * })
811
- * ```
812
- *
813
- * Skip `defineAugmentation` if you don't care about the catalogue — the
814
- * `declare module` block alone is enough for runtime + type behaviour.
815
- */
816
- function defineAugmentation(name, meta) {}
817
- //#endregion
818
- export { MissingMountDepError as a, runContributors as c, DuplicateContributorError as d, MissingContributorError as f, CircuitOpenError as h, DuplicateMountNameError as i, buildPipeline as l, CircuitBreaker as m, defineAdapter as n, MountCycleError as o, defineContextDecorator as p, definePlugin as r, mountSort as s, defineAugmentation as t, ContributorCycleError as u };
819
-
820
- //# sourceMappingURL=core--a4XflX7.mjs.map