@theokit/di 0.1.1 → 0.2.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/index.js CHANGED
@@ -14,6 +14,11 @@ function describeToken(token) {
14
14
  return "<unknown token>";
15
15
  }
16
16
  __name(describeToken, "describeToken");
17
+ function describeClassName(target, fallback) {
18
+ const name = target?.name;
19
+ return typeof name === "string" && name.length > 0 ? name : fallback;
20
+ }
21
+ __name(describeClassName, "describeClassName");
17
22
  var TokenNotFoundError = class extends Error {
18
23
  static {
19
24
  __name(this, "TokenNotFoundError");
@@ -47,6 +52,17 @@ var AsyncProviderInSyncResolveError = class extends Error {
47
52
  super(`Provider for token ${describeToken(token)} is async (factory returned a Promise). Use container.resolveAsync() instead of container.resolve().`), this.token = token;
48
53
  }
49
54
  };
55
+ var AsyncPostConstructInSyncResolveError = class extends Error {
56
+ static {
57
+ __name(this, "AsyncPostConstructInSyncResolveError");
58
+ }
59
+ className;
60
+ methodName;
61
+ name = "AsyncPostConstructInSyncResolveError";
62
+ constructor(className, methodName) {
63
+ super(`@PostConstruct ${className}.${methodName}() returned a Promise, and container.resolve() cannot await it. Use container.resolveAsync() instead, or make ${methodName}() synchronous.`), this.className = className, this.methodName = methodName;
64
+ }
65
+ };
50
66
  var ScopeViolationError = class extends Error {
51
67
  static {
52
68
  __name(this, "ScopeViolationError");
@@ -64,7 +80,7 @@ var MissingInjectableError = class extends Error {
64
80
  target;
65
81
  name = "MissingInjectableError";
66
82
  constructor(target) {
67
- super(`Class ${target.name ?? "<anonymous>"} has no @Injectable() decorator. Add @Injectable() above the class declaration before registering it.`), this.target = target;
83
+ super(`Class ${describeClassName(target, "<anonymous>")} has no @Injectable() decorator. Add @Injectable() above the class declaration before registering it.`), this.target = target;
68
84
  }
69
85
  };
70
86
  var ContainerDisposedError = class extends Error {
@@ -107,14 +123,15 @@ function findCycles(snapshot) {
107
123
  const cycles = [];
108
124
  const seenCycles = /* @__PURE__ */ new Set();
109
125
  const visited = /* @__PURE__ */ new Set();
126
+ const tokenIds = /* @__PURE__ */ new Map();
110
127
  for (const node of snapshot.nodes) {
111
128
  if (visited.has(node.token)) continue;
112
- iterativeDfs(node.token, adjacency, visited, cycles, seenCycles);
129
+ iterativeDfs(node.token, adjacency, visited, cycles, seenCycles, tokenIds);
113
130
  }
114
131
  return cycles;
115
132
  }
116
133
  __name(findCycles, "findCycles");
117
- function iterativeDfs(root, adjacency, visited, out, seenCycles) {
134
+ function iterativeDfs(root, adjacency, visited, out, seenCycles, tokenIds) {
118
135
  const stack = [];
119
136
  const onPath = /* @__PURE__ */ new Set();
120
137
  const pathOrder = [];
@@ -147,7 +164,7 @@ function iterativeDfs(root, adjacency, visited, out, seenCycles) {
147
164
  ...pathOrder.slice(cycleStart),
148
165
  neighbor
149
166
  ];
150
- const key = canonicalCycleKey(cycle);
167
+ const key = canonicalCycleKey(cycle, tokenIds);
151
168
  if (!seenCycles.has(key)) {
152
169
  seenCycles.add(key);
153
170
  out.push(cycle);
@@ -158,26 +175,27 @@ function iterativeDfs(root, adjacency, visited, out, seenCycles) {
158
175
  }
159
176
  }
160
177
  __name(iterativeDfs, "iterativeDfs");
161
- function canonicalCycleKey(cycle) {
162
- const strs = cycle.map(stringifyToken);
178
+ function canonicalCycleKey(cycle, tokenIds) {
179
+ const ids = cycle.map((token) => {
180
+ let id = tokenIds.get(token);
181
+ if (id === void 0) {
182
+ id = tokenIds.size;
183
+ tokenIds.set(token, id);
184
+ }
185
+ return id;
186
+ });
163
187
  let minIndex = 0;
164
- for (let i = 1; i < strs.length; i += 1) {
165
- if (strs[i] < strs[minIndex]) {
188
+ for (let i = 1; i < ids.length; i += 1) {
189
+ if (ids[i] < ids[minIndex]) {
166
190
  minIndex = i;
167
191
  }
168
192
  }
169
193
  return [
170
- ...strs.slice(minIndex),
171
- ...strs.slice(0, minIndex)
194
+ ...ids.slice(minIndex),
195
+ ...ids.slice(0, minIndex)
172
196
  ].join("\u2192");
173
197
  }
174
198
  __name(canonicalCycleKey, "canonicalCycleKey");
175
- function stringifyToken(token) {
176
- if (typeof token === "string") return `s:${token}`;
177
- if (typeof token === "function") return `c:${token.name ?? "<anon>"}`;
178
- return "u:<unknown>";
179
- }
180
- __name(stringifyToken, "stringifyToken");
181
199
 
182
200
  // src/internal/metadata.ts
183
201
  var METADATA_KEYS = {
@@ -205,7 +223,7 @@ var METADATA_KEYS = {
205
223
  SQUAD: "usetheo:di:squad",
206
224
  /** Map<string|symbol, StepMetadata> from `@Step()` method decorator. */
207
225
  STEP: "usetheo:di:step",
208
- /** HitlOptions from `@Hitl()` method decorator. */
226
+ /** Map<string|symbol, HitlMetadata> from `@Hitl()` method decorator. */
209
227
  HITL: "usetheo:di:hitl",
210
228
  /** AutoSummarizeConfig from `@AutoSummarize()` class decorator. */
211
229
  AUTO_SUMMARIZE: "usetheo:di:auto-summarize",
@@ -215,7 +233,7 @@ var METADATA_KEYS = {
215
233
  WORKFLOW: "usetheo:di:workflow",
216
234
  /** EvalOptions from `@Eval()` class decorator. */
217
235
  EVAL: "usetheo:di:eval",
218
- /** CronMetadata from `@Cron()` method decorator. */
236
+ /** Map<string|symbol, CronMetadata> from `@Cron()` method decorator. */
219
237
  CRON: "usetheo:di:cron",
220
238
  /** Map<string|symbol, SubscriptionOptions> from `@Subscription()` property decorator. */
221
239
  SUBSCRIPTION: "usetheo:di:subscription",
@@ -267,6 +285,21 @@ function isInjectable(target) {
267
285
  return readInjectableMetadata(target) !== void 0;
268
286
  }
269
287
  __name(isInjectable, "isInjectable");
288
+ function readPostConstruct(target) {
289
+ return readLifecycleHook(target, METADATA_KEYS.POST_CONSTRUCT);
290
+ }
291
+ __name(readPostConstruct, "readPostConstruct");
292
+ function readPreDestroy(target) {
293
+ return readLifecycleHook(target, METADATA_KEYS.PRE_DESTROY);
294
+ }
295
+ __name(readPreDestroy, "readPreDestroy");
296
+ function readLifecycleHook(target, key) {
297
+ if (!hasReflectMetadata()) return void 0;
298
+ const out = Reflect.getMetadata(key, target);
299
+ if (typeof out === "string" || typeof out === "symbol") return out;
300
+ return void 0;
301
+ }
302
+ __name(readLifecycleHook, "readLifecycleHook");
270
303
  var PRIMITIVE_WRAPPERS = /* @__PURE__ */ new Set([
271
304
  Number,
272
305
  String,
@@ -307,7 +340,7 @@ var InvalidModuleError = class extends Error {
307
340
  target;
308
341
  name = "InvalidModuleError";
309
342
  constructor(target) {
310
- super(`Class ${target.name ?? "<anonymous>"} has no @Module() decorator. Add @Module({ providers: [...], imports: [...], exports: [...] }) above the class declaration.`), this.target = target;
343
+ super(`Class ${describeClassName(target, "<anonymous>")} has no @Module() decorator. Add @Module({ providers: [...], imports: [...], exports: [...] }) above the class declaration.`), this.target = target;
311
344
  }
312
345
  };
313
346
  var InvalidExportError = class extends Error {
@@ -397,6 +430,11 @@ var Scope = {
397
430
  };
398
431
 
399
432
  // src/container.ts
433
+ var ASYNC_CONTEXT = /* @__PURE__ */ Symbol("theokit.di.asyncContext");
434
+ function isAsyncContext(ctx) {
435
+ return ctx[ASYNC_CONTEXT] === true;
436
+ }
437
+ __name(isAsyncContext, "isAsyncContext");
400
438
  var Container = class {
401
439
  static {
402
440
  __name(this, "Container");
@@ -422,7 +460,7 @@ var Container = class {
422
460
  * - A full Provider (useClass / useFactory / useValue / useExisting)
423
461
  * - A bare class (shorthand expands to ClassProvider { provide: X, useClass: X })
424
462
  *
425
- * Per v1.1 EC-1, ClassProvider validation runs via `validateClassProvider()`
463
+ * ClassProvider validation runs via `validateClassProvider()`
426
464
  * regardless of which API path was used.
427
465
  */
428
466
  register(providerOrClass) {
@@ -442,9 +480,9 @@ var Container = class {
442
480
  * modules. Walks imports BFS, registers every provider, validates
443
481
  * exports.
444
482
  *
445
- * Per v1.1 EC-4: undecorated class throws `InvalidModuleError`.
446
- * Per v1.2 EC-R2-5: respects the freeze-after-first-resolve guarantee
447
- * (each child `register()` checks `assertNotFrozen`).
483
+ * An undecorated class throws `InvalidModuleError`. Respects the
484
+ * freeze-after-first-resolve guarantee — each child `register()` checks
485
+ * `assertNotFrozen`.
448
486
  */
449
487
  registerModule(moduleClass) {
450
488
  this.assertNotDisposed();
@@ -481,7 +519,7 @@ var Container = class {
481
519
  * providers resolved within `callback` (or any async continuation) share
482
520
  * a single per-request cache.
483
521
  *
484
- * v1.1 EC-3: try/finally guarantees REQUEST-scoped instances are disposed
522
+ * try/finally guarantees REQUEST-scoped instances are disposed
485
523
  * even if the callback throws.
486
524
  */
487
525
  async runInRequest(callback) {
@@ -499,7 +537,7 @@ var Container = class {
499
537
  /**
500
538
  * Debug helper — returns a snapshot of the dependency graph.
501
539
  *
502
- * Per ADR D7: detects cycles in unused providers too (resolve-time
540
+ * Detects cycles in unused providers too (resolve-time
503
541
  * detection only fires for resolves that actually traverse the cycle).
504
542
  * Use this proactively in tests / dev mode to surface latent cycles.
505
543
  */
@@ -600,7 +638,7 @@ var Container = class {
600
638
  }
601
639
  }
602
640
  /**
603
- * v1.1 EC-1: shared by both declarative providers: [] AND imperative
641
+ * Shared by both declarative providers: [] AND imperative
604
642
  * register() — every class provider must have @Injectable().
605
643
  */
606
644
  validateClassProvider(provider) {
@@ -615,7 +653,7 @@ var Container = class {
615
653
  if (this.disposed) throw new ContainerDisposedError();
616
654
  }
617
655
  /**
618
- * v1.2 EC-R2-5: container freezes on first resolve. Late registrations
656
+ * The container freezes on first resolve. Late registrations
619
657
  * require explicit `allowDynamicRegistration: true` (testing escape hatch).
620
658
  */
621
659
  assertNotFrozen(token) {
@@ -646,7 +684,8 @@ var Container = class {
646
684
  token: provider.provide,
647
685
  scope,
648
686
  factory: /* @__PURE__ */ __name((ctx) => this.constructClassWithAsyncFallback(target, ctx), "factory"),
649
- classTarget: target
687
+ classTarget: target,
688
+ containerOwned: true
650
689
  };
651
690
  }
652
691
  fromFactoryProvider(provider) {
@@ -661,7 +700,8 @@ var Container = class {
661
700
  }
662
701
  return Promise.all(injectTokens.map((dep) => ctx.resolveAsync(dep))).then((asyncArgs) => provider.useFactory(...asyncArgs));
663
702
  }, "factory"),
664
- injectTokens
703
+ injectTokens,
704
+ containerOwned: true
665
705
  };
666
706
  }
667
707
  /**
@@ -692,7 +732,8 @@ var Container = class {
692
732
  return {
693
733
  token: provider.provide,
694
734
  scope: Scope.SINGLETON,
695
- factory: /* @__PURE__ */ __name(() => provider.useValue, "factory")
735
+ factory: /* @__PURE__ */ __name(() => provider.useValue, "factory"),
736
+ containerOwned: false
696
737
  };
697
738
  }
698
739
  fromExistingProvider(provider) {
@@ -700,15 +741,16 @@ var Container = class {
700
741
  token: provider.provide,
701
742
  scope: Scope.SINGLETON,
702
743
  factory: /* @__PURE__ */ __name((ctx) => ctx.resolve(provider.useExisting), "factory"),
703
- aliasTarget: provider.useExisting
744
+ aliasTarget: provider.useExisting,
745
+ containerOwned: false
704
746
  };
705
747
  }
706
748
  /**
707
749
  * Resolve constructor params + build instance. Tries sync first; if any
708
750
  * dep is async, falls back to awaiting via `resolveAsync`.
709
751
  *
710
- * Refactored via Extract Method (ADR D422): orchestrates 3 helpers:
711
- * - validateMetadata: EC-12 detect emitDecoratorMetadata off
752
+ * Refactored via Extract Method: orchestrates 3 helpers:
753
+ * - validateMetadata: detect emitDecoratorMetadata off
712
754
  * - tryResolveSync: sync resolution loop with AsyncProvider bailout
713
755
  * - resolveAllAsync: Promise.all fallback when any dep is async
714
756
  */
@@ -722,12 +764,13 @@ var Container = class {
722
764
  this.validateMetadata(target, paramTypes);
723
765
  const syncResult = this.tryResolveSync(target, paramTypes, injectTokens, optionalFlags, ctx);
724
766
  if ("args" in syncResult) {
725
- return new target(...syncResult.args);
767
+ const instance = new target(...syncResult.args);
768
+ return isAsyncContext(ctx) ? runPostConstructAsync(target, instance) : runPostConstructSync(target, instance);
726
769
  }
727
- return this.resolveAllAsync(target, paramTypes, injectTokens, optionalFlags, ctx);
770
+ return this.resolveAllAsync(target, paramTypes, injectTokens, optionalFlags, ctx).then((instance) => runPostConstructAsync(target, instance));
728
771
  }
729
772
  /**
730
- * EC-12 detection: zero paramTypes for a class that declares a non-empty
773
+ * Detection: zero paramTypes for a class that declares a non-empty
731
774
  * constructor strongly suggests emitDecoratorMetadata is off.
732
775
  */
733
776
  validateMetadata(target, paramTypes) {
@@ -742,7 +785,7 @@ var Container = class {
742
785
  */
743
786
  handlePrimitiveParam(target, paramType, index, isOptional) {
744
787
  if (isOptional) return void 0;
745
- throw new TypeError(`Class ${target.name} has a primitive/interface constructor parameter at index ${index} (emitted as ${paramType.name ?? "<unknown>"}). Primitives and interfaces cannot be auto-resolved \u2014 use \`@Inject('SOME_STRING_TOKEN')\` to provide an explicit token.`);
788
+ throw new TypeError(`Class ${target.name} has a primitive/interface constructor parameter at index ${index} (emitted as ${describeClassName(paramType, "<unknown>")}). Primitives and interfaces cannot be auto-resolved \u2014 use \`@Inject('SOME_STRING_TOKEN')\` to provide an explicit token.`);
746
789
  }
747
790
  /**
748
791
  * Attempt sync resolution. Returns `{ args }` on success, `{ needsAsync: true }`
@@ -834,14 +877,14 @@ var Container = class {
834
877
  this.storeInCache(token, value, registration.scope);
835
878
  value.then((resolved) => {
836
879
  this.storeInCache(token, resolved, registration.scope);
837
- this.trackInstance(resolved, registration.scope);
880
+ this.trackInstance(resolved, registration);
838
881
  }, () => {
839
882
  this.deleteFromCache(token, registration.scope);
840
883
  });
841
884
  throw new AsyncProviderInSyncResolveError(token);
842
885
  }
843
886
  this.storeInCache(token, value, registration.scope);
844
- this.trackInstance(value, registration.scope);
887
+ this.trackInstance(value, registration);
845
888
  return value;
846
889
  }
847
890
  // ─────────────────────────────────────────────────────────────────────
@@ -874,14 +917,14 @@ var Container = class {
874
917
  this.storeInCache(token, result, registration.scope);
875
918
  result.then((value) => {
876
919
  this.storeInCache(token, value, registration.scope);
877
- this.trackInstance(value, registration.scope);
920
+ this.trackInstance(value, registration);
878
921
  }, () => {
879
922
  this.deleteFromCache(token, registration.scope);
880
923
  });
881
924
  return result;
882
925
  }
883
926
  this.storeInCache(token, result, registration.scope);
884
- this.trackInstance(result, registration.scope);
927
+ this.trackInstance(result, registration);
885
928
  return result;
886
929
  }
887
930
  // ─────────────────────────────────────────────────────────────────────
@@ -916,8 +959,18 @@ var Container = class {
916
959
  store?.cache.delete(token);
917
960
  }
918
961
  }
919
- trackInstance(value, scope) {
920
- if (!isDisposable(value)) return;
962
+ /**
963
+ * Record an instance for teardown, when this container is the one that should tear it down.
964
+ *
965
+ * Two questions, in this order. Does the container OWN it — see `containerOwned`; a value the
966
+ * caller handed in and an instance reached through an alias are both refused here. And does it
967
+ * have any teardown at all: a class whose only teardown is `@PreDestroy` has no `dispose()`, so
968
+ * testing `isDisposable` alone would silently skip it.
969
+ */
970
+ trackInstance(value, registration) {
971
+ if (!registration.containerOwned) return;
972
+ const { scope } = registration;
973
+ if (!isDisposable(value) && !hasPreDestroy(value)) return;
921
974
  if (scope === Scope.SINGLETON) {
922
975
  this.singletonInstances.push(value);
923
976
  return;
@@ -943,11 +996,14 @@ var Container = class {
943
996
  };
944
997
  }
945
998
  createContextAsync(path) {
946
- return {
999
+ const ctx = {
947
1000
  path,
948
1001
  resolve: /* @__PURE__ */ __name((t) => this.resolveInContext(t, this.createContext(path)), "resolve"),
949
1002
  resolveAsync: /* @__PURE__ */ __name((t) => this.resolveAsyncInContext(t, this.createContextAsync(path)), "resolveAsync")
950
1003
  };
1004
+ return Object.assign(ctx, {
1005
+ [ASYNC_CONTEXT]: true
1006
+ });
951
1007
  }
952
1008
  // ─────────────────────────────────────────────────────────────────────
953
1009
  // Internal: disposal
@@ -958,10 +1014,11 @@ var Container = class {
958
1014
  const instance = instances[i];
959
1015
  if (instance === void 0) continue;
960
1016
  try {
1017
+ await callPreDestroy(instance);
961
1018
  const asAsync = instance[Symbol.asyncDispose];
962
1019
  if (typeof asAsync === "function") {
963
1020
  await asAsync.call(instance);
964
- } else {
1021
+ } else if (isDisposable(instance)) {
965
1022
  await instance.dispose();
966
1023
  }
967
1024
  } catch (err) {
@@ -982,6 +1039,49 @@ function isDisposable(value) {
982
1039
  return false;
983
1040
  }
984
1041
  __name(isDisposable, "isDisposable");
1042
+ function callPostConstruct(target, instance) {
1043
+ const hook = readPostConstruct(target);
1044
+ if (hook === void 0) return void 0;
1045
+ const method = instance[hook];
1046
+ if (typeof method !== "function") return void 0;
1047
+ return method.call(instance);
1048
+ }
1049
+ __name(callPostConstruct, "callPostConstruct");
1050
+ function runPostConstructSync(target, instance) {
1051
+ const returned = callPostConstruct(target, instance);
1052
+ if (isThenable(returned)) {
1053
+ throw new AsyncPostConstructInSyncResolveError(target.name, String(readPostConstruct(target)));
1054
+ }
1055
+ return instance;
1056
+ }
1057
+ __name(runPostConstructSync, "runPostConstructSync");
1058
+ async function runPostConstructAsync(target, instance) {
1059
+ const returned = callPostConstruct(target, instance);
1060
+ if (isThenable(returned)) await returned;
1061
+ return instance;
1062
+ }
1063
+ __name(runPostConstructAsync, "runPostConstructAsync");
1064
+ async function callPreDestroy(instance) {
1065
+ const ctor = instance.constructor;
1066
+ if (typeof ctor !== "function") return;
1067
+ const hook = readPreDestroy(ctor);
1068
+ if (hook === void 0) return;
1069
+ const method = instance[hook];
1070
+ if (typeof method !== "function") return;
1071
+ await method.call(instance);
1072
+ }
1073
+ __name(callPreDestroy, "callPreDestroy");
1074
+ function hasPreDestroy(value) {
1075
+ if (value === null || typeof value !== "object") return false;
1076
+ const ctor = value.constructor;
1077
+ if (typeof ctor !== "function") return false;
1078
+ return readPreDestroy(ctor) !== void 0;
1079
+ }
1080
+ __name(hasPreDestroy, "hasPreDestroy");
1081
+ function isThenable(value) {
1082
+ return value !== null && (typeof value === "object" || typeof value === "function") && typeof value.then === "function";
1083
+ }
1084
+ __name(isThenable, "isThenable");
985
1085
 
986
1086
  // src/decorators/inject.ts
987
1087
  function Inject(token) {
@@ -1042,6 +1142,6 @@ function Qualifier(name) {
1042
1142
  }
1043
1143
  __name(Qualifier, "Qualifier");
1044
1144
 
1045
- export { AsyncProviderInSyncResolveError, Container, ContainerDisposedError, ContainerFrozenError, CyclicDependencyError, CyclicModuleImportError, Inject, Injectable, InvalidExportError, InvalidModuleError, METADATA_KEYS, MissingInjectableError, Module, Optional, PostConstruct, PreDestroy, Primary, Qualifier, ReflectMetadataMissingError, Scope, ScopeViolationError, TokenNotFoundError, describeToken };
1145
+ export { AsyncPostConstructInSyncResolveError, AsyncProviderInSyncResolveError, Container, ContainerDisposedError, ContainerFrozenError, CyclicDependencyError, CyclicModuleImportError, Inject, Injectable, InvalidExportError, InvalidModuleError, METADATA_KEYS, MissingInjectableError, Module, Optional, PostConstruct, PreDestroy, Primary, Qualifier, ReflectMetadataMissingError, Scope, ScopeViolationError, TokenNotFoundError, describeClassName, describeToken };
1046
1146
  //# sourceMappingURL=index.js.map
1047
1147
  //# sourceMappingURL=index.js.map