@theokit/di 0.1.0 → 0.2.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.js CHANGED
@@ -47,6 +47,17 @@ var AsyncProviderInSyncResolveError = class extends Error {
47
47
  super(`Provider for token ${describeToken(token)} is async (factory returned a Promise). Use container.resolveAsync() instead of container.resolve().`), this.token = token;
48
48
  }
49
49
  };
50
+ var AsyncPostConstructInSyncResolveError = class extends Error {
51
+ static {
52
+ __name(this, "AsyncPostConstructInSyncResolveError");
53
+ }
54
+ className;
55
+ methodName;
56
+ name = "AsyncPostConstructInSyncResolveError";
57
+ constructor(className, methodName) {
58
+ 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;
59
+ }
60
+ };
50
61
  var ScopeViolationError = class extends Error {
51
62
  static {
52
63
  __name(this, "ScopeViolationError");
@@ -188,7 +199,47 @@ var METADATA_KEYS = {
188
199
  /** Set<number> from `@Optional()` parameter decorators. */
189
200
  OPTIONAL_FLAGS: "usetheo:di:optional",
190
201
  /** TS-emitted constructor parameter types (requires `emitDecoratorMetadata`). */
191
- DESIGN_PARAMTYPES: "design:paramtypes"
202
+ DESIGN_PARAMTYPES: "design:paramtypes",
203
+ /** Map<number, string> from `@Qualifier(name)` parameter decorators. */
204
+ QUALIFIER_NAMES: "usetheo:di:qualifier-names",
205
+ /** boolean from `@Primary` class decorator. */
206
+ PRIMARY: "usetheo:di:primary",
207
+ /** string | symbol from `@PostConstruct` method decorator. */
208
+ POST_CONSTRUCT: "usetheo:di:post-construct",
209
+ /** string | symbol from `@PreDestroy` method decorator. */
210
+ PRE_DESTROY: "usetheo:di:pre-destroy",
211
+ /** Map<string|symbol, SandboxOptions> from `@UseSandbox()` property decorator. */
212
+ SANDBOX: "usetheo:di:sandbox",
213
+ /** Map<string|symbol, SubAgentSpec> from `@SubAgent()` property decorator. */
214
+ SUBAGENT: "usetheo:di:subagent",
215
+ /** Map<string|symbol, SquadMetadata> from `@Squad()` property decorator. */
216
+ SQUAD: "usetheo:di:squad",
217
+ /** Map<string|symbol, StepMetadata> from `@Step()` method decorator. */
218
+ STEP: "usetheo:di:step",
219
+ /** Map<string|symbol, HitlMetadata> from `@Hitl()` method decorator. */
220
+ HITL: "usetheo:di:hitl",
221
+ /** AutoSummarizeConfig from `@AutoSummarize()` class decorator. */
222
+ AUTO_SUMMARIZE: "usetheo:di:auto-summarize",
223
+ /** Map<string|symbol, ToolOptions> from `@Tool()` property decorator. */
224
+ TOOL: "usetheo:di:tool",
225
+ /** WorkflowOptions from `@Workflow()` class decorator. */
226
+ WORKFLOW: "usetheo:di:workflow",
227
+ /** EvalOptions from `@Eval()` class decorator. */
228
+ EVAL: "usetheo:di:eval",
229
+ /** Map<string|symbol, CronMetadata> from `@Cron()` method decorator. */
230
+ CRON: "usetheo:di:cron",
231
+ /** Map<string|symbol, SubscriptionOptions> from `@Subscription()` property decorator. */
232
+ SUBSCRIPTION: "usetheo:di:subscription",
233
+ /** AuthOptions from `@Auth()` class decorator. */
234
+ AUTH: "usetheo:di:auth",
235
+ /** Map<string|symbol, RetrieverOptions> from `@Retriever()` property decorator. */
236
+ RETRIEVER: "usetheo:di:retriever",
237
+ /** Map<string|symbol, RerankerOptions> from `@Reranker()` property decorator. */
238
+ RERANKER: "usetheo:di:reranker",
239
+ /** Map<string|symbol, TextSplitterOptions> from `@TextSplitter()` property decorator. */
240
+ TEXT_SPLITTER: "usetheo:di:text-splitter",
241
+ /** Map<string|symbol, MemoryScopeOptions> from `@MemoryScopeDecorator()` property decorator. */
242
+ MEMORY_SCOPE: "usetheo:di:memory-scope"
192
243
  };
193
244
  function hasReflectMetadata() {
194
245
  return typeof Reflect !== "undefined" && typeof Reflect.getMetadata === "function";
@@ -227,6 +278,21 @@ function isInjectable(target) {
227
278
  return readInjectableMetadata(target) !== void 0;
228
279
  }
229
280
  __name(isInjectable, "isInjectable");
281
+ function readPostConstruct(target) {
282
+ return readLifecycleHook(target, METADATA_KEYS.POST_CONSTRUCT);
283
+ }
284
+ __name(readPostConstruct, "readPostConstruct");
285
+ function readPreDestroy(target) {
286
+ return readLifecycleHook(target, METADATA_KEYS.PRE_DESTROY);
287
+ }
288
+ __name(readPreDestroy, "readPreDestroy");
289
+ function readLifecycleHook(target, key) {
290
+ if (!hasReflectMetadata()) return void 0;
291
+ const out = Reflect.getMetadata(key, target);
292
+ if (typeof out === "string" || typeof out === "symbol") return out;
293
+ return void 0;
294
+ }
295
+ __name(readLifecycleHook, "readLifecycleHook");
230
296
  var PRIMITIVE_WRAPPERS = /* @__PURE__ */ new Set([
231
297
  Number,
232
298
  String,
@@ -357,6 +423,11 @@ var Scope = {
357
423
  };
358
424
 
359
425
  // src/container.ts
426
+ var ASYNC_CONTEXT = /* @__PURE__ */ Symbol("theokit.di.asyncContext");
427
+ function isAsyncContext(ctx) {
428
+ return ctx[ASYNC_CONTEXT] === true;
429
+ }
430
+ __name(isAsyncContext, "isAsyncContext");
360
431
  var Container = class {
361
432
  static {
362
433
  __name(this, "Container");
@@ -382,7 +453,7 @@ var Container = class {
382
453
  * - A full Provider (useClass / useFactory / useValue / useExisting)
383
454
  * - A bare class (shorthand expands to ClassProvider { provide: X, useClass: X })
384
455
  *
385
- * Per v1.1 EC-1, ClassProvider validation runs via `validateClassProvider()`
456
+ * ClassProvider validation runs via `validateClassProvider()`
386
457
  * regardless of which API path was used.
387
458
  */
388
459
  register(providerOrClass) {
@@ -402,9 +473,9 @@ var Container = class {
402
473
  * modules. Walks imports BFS, registers every provider, validates
403
474
  * exports.
404
475
  *
405
- * Per v1.1 EC-4: undecorated class throws `InvalidModuleError`.
406
- * Per v1.2 EC-R2-5: respects the freeze-after-first-resolve guarantee
407
- * (each child `register()` checks `assertNotFrozen`).
476
+ * An undecorated class throws `InvalidModuleError`. Respects the
477
+ * freeze-after-first-resolve guarantee — each child `register()` checks
478
+ * `assertNotFrozen`.
408
479
  */
409
480
  registerModule(moduleClass) {
410
481
  this.assertNotDisposed();
@@ -441,7 +512,7 @@ var Container = class {
441
512
  * providers resolved within `callback` (or any async continuation) share
442
513
  * a single per-request cache.
443
514
  *
444
- * v1.1 EC-3: try/finally guarantees REQUEST-scoped instances are disposed
515
+ * try/finally guarantees REQUEST-scoped instances are disposed
445
516
  * even if the callback throws.
446
517
  */
447
518
  async runInRequest(callback) {
@@ -459,7 +530,7 @@ var Container = class {
459
530
  /**
460
531
  * Debug helper — returns a snapshot of the dependency graph.
461
532
  *
462
- * Per ADR D7: detects cycles in unused providers too (resolve-time
533
+ * Detects cycles in unused providers too (resolve-time
463
534
  * detection only fires for resolves that actually traverse the cycle).
464
535
  * Use this proactively in tests / dev mode to surface latent cycles.
465
536
  */
@@ -560,7 +631,7 @@ var Container = class {
560
631
  }
561
632
  }
562
633
  /**
563
- * v1.1 EC-1: shared by both declarative providers: [] AND imperative
634
+ * Shared by both declarative providers: [] AND imperative
564
635
  * register() — every class provider must have @Injectable().
565
636
  */
566
637
  validateClassProvider(provider) {
@@ -575,7 +646,7 @@ var Container = class {
575
646
  if (this.disposed) throw new ContainerDisposedError();
576
647
  }
577
648
  /**
578
- * v1.2 EC-R2-5: container freezes on first resolve. Late registrations
649
+ * The container freezes on first resolve. Late registrations
579
650
  * require explicit `allowDynamicRegistration: true` (testing escape hatch).
580
651
  */
581
652
  assertNotFrozen(token) {
@@ -606,7 +677,8 @@ var Container = class {
606
677
  token: provider.provide,
607
678
  scope,
608
679
  factory: /* @__PURE__ */ __name((ctx) => this.constructClassWithAsyncFallback(target, ctx), "factory"),
609
- classTarget: target
680
+ classTarget: target,
681
+ containerOwned: true
610
682
  };
611
683
  }
612
684
  fromFactoryProvider(provider) {
@@ -621,7 +693,8 @@ var Container = class {
621
693
  }
622
694
  return Promise.all(injectTokens.map((dep) => ctx.resolveAsync(dep))).then((asyncArgs) => provider.useFactory(...asyncArgs));
623
695
  }, "factory"),
624
- injectTokens
696
+ injectTokens,
697
+ containerOwned: true
625
698
  };
626
699
  }
627
700
  /**
@@ -652,7 +725,8 @@ var Container = class {
652
725
  return {
653
726
  token: provider.provide,
654
727
  scope: Scope.SINGLETON,
655
- factory: /* @__PURE__ */ __name(() => provider.useValue, "factory")
728
+ factory: /* @__PURE__ */ __name(() => provider.useValue, "factory"),
729
+ containerOwned: false
656
730
  };
657
731
  }
658
732
  fromExistingProvider(provider) {
@@ -660,15 +734,16 @@ var Container = class {
660
734
  token: provider.provide,
661
735
  scope: Scope.SINGLETON,
662
736
  factory: /* @__PURE__ */ __name((ctx) => ctx.resolve(provider.useExisting), "factory"),
663
- aliasTarget: provider.useExisting
737
+ aliasTarget: provider.useExisting,
738
+ containerOwned: false
664
739
  };
665
740
  }
666
741
  /**
667
742
  * Resolve constructor params + build instance. Tries sync first; if any
668
743
  * dep is async, falls back to awaiting via `resolveAsync`.
669
744
  *
670
- * Refactored via Extract Method (ADR D422): orchestrates 3 helpers:
671
- * - validateMetadata: EC-12 detect emitDecoratorMetadata off
745
+ * Refactored via Extract Method: orchestrates 3 helpers:
746
+ * - validateMetadata: detect emitDecoratorMetadata off
672
747
  * - tryResolveSync: sync resolution loop with AsyncProvider bailout
673
748
  * - resolveAllAsync: Promise.all fallback when any dep is async
674
749
  */
@@ -682,12 +757,13 @@ var Container = class {
682
757
  this.validateMetadata(target, paramTypes);
683
758
  const syncResult = this.tryResolveSync(target, paramTypes, injectTokens, optionalFlags, ctx);
684
759
  if ("args" in syncResult) {
685
- return new target(...syncResult.args);
760
+ const instance = new target(...syncResult.args);
761
+ return isAsyncContext(ctx) ? runPostConstructAsync(target, instance) : runPostConstructSync(target, instance);
686
762
  }
687
- return this.resolveAllAsync(target, paramTypes, injectTokens, optionalFlags, ctx);
763
+ return this.resolveAllAsync(target, paramTypes, injectTokens, optionalFlags, ctx).then((instance) => runPostConstructAsync(target, instance));
688
764
  }
689
765
  /**
690
- * EC-12 detection: zero paramTypes for a class that declares a non-empty
766
+ * Detection: zero paramTypes for a class that declares a non-empty
691
767
  * constructor strongly suggests emitDecoratorMetadata is off.
692
768
  */
693
769
  validateMetadata(target, paramTypes) {
@@ -794,14 +870,14 @@ var Container = class {
794
870
  this.storeInCache(token, value, registration.scope);
795
871
  value.then((resolved) => {
796
872
  this.storeInCache(token, resolved, registration.scope);
797
- this.trackInstance(resolved, registration.scope);
873
+ this.trackInstance(resolved, registration);
798
874
  }, () => {
799
875
  this.deleteFromCache(token, registration.scope);
800
876
  });
801
877
  throw new AsyncProviderInSyncResolveError(token);
802
878
  }
803
879
  this.storeInCache(token, value, registration.scope);
804
- this.trackInstance(value, registration.scope);
880
+ this.trackInstance(value, registration);
805
881
  return value;
806
882
  }
807
883
  // ─────────────────────────────────────────────────────────────────────
@@ -834,14 +910,14 @@ var Container = class {
834
910
  this.storeInCache(token, result, registration.scope);
835
911
  result.then((value) => {
836
912
  this.storeInCache(token, value, registration.scope);
837
- this.trackInstance(value, registration.scope);
913
+ this.trackInstance(value, registration);
838
914
  }, () => {
839
915
  this.deleteFromCache(token, registration.scope);
840
916
  });
841
917
  return result;
842
918
  }
843
919
  this.storeInCache(token, result, registration.scope);
844
- this.trackInstance(result, registration.scope);
920
+ this.trackInstance(result, registration);
845
921
  return result;
846
922
  }
847
923
  // ─────────────────────────────────────────────────────────────────────
@@ -876,8 +952,18 @@ var Container = class {
876
952
  store?.cache.delete(token);
877
953
  }
878
954
  }
879
- trackInstance(value, scope) {
880
- if (!isDisposable(value)) return;
955
+ /**
956
+ * Record an instance for teardown, when this container is the one that should tear it down.
957
+ *
958
+ * Two questions, in this order. Does the container OWN it — see `containerOwned`; a value the
959
+ * caller handed in and an instance reached through an alias are both refused here. And does it
960
+ * have any teardown at all: a class whose only teardown is `@PreDestroy` has no `dispose()`, so
961
+ * testing `isDisposable` alone would silently skip it.
962
+ */
963
+ trackInstance(value, registration) {
964
+ if (!registration.containerOwned) return;
965
+ const { scope } = registration;
966
+ if (!isDisposable(value) && !hasPreDestroy(value)) return;
881
967
  if (scope === Scope.SINGLETON) {
882
968
  this.singletonInstances.push(value);
883
969
  return;
@@ -903,11 +989,14 @@ var Container = class {
903
989
  };
904
990
  }
905
991
  createContextAsync(path) {
906
- return {
992
+ const ctx = {
907
993
  path,
908
994
  resolve: /* @__PURE__ */ __name((t) => this.resolveInContext(t, this.createContext(path)), "resolve"),
909
995
  resolveAsync: /* @__PURE__ */ __name((t) => this.resolveAsyncInContext(t, this.createContextAsync(path)), "resolveAsync")
910
996
  };
997
+ return Object.assign(ctx, {
998
+ [ASYNC_CONTEXT]: true
999
+ });
911
1000
  }
912
1001
  // ─────────────────────────────────────────────────────────────────────
913
1002
  // Internal: disposal
@@ -918,10 +1007,11 @@ var Container = class {
918
1007
  const instance = instances[i];
919
1008
  if (instance === void 0) continue;
920
1009
  try {
1010
+ await callPreDestroy(instance);
921
1011
  const asAsync = instance[Symbol.asyncDispose];
922
1012
  if (typeof asAsync === "function") {
923
1013
  await asAsync.call(instance);
924
- } else {
1014
+ } else if (isDisposable(instance)) {
925
1015
  await instance.dispose();
926
1016
  }
927
1017
  } catch (err) {
@@ -942,6 +1032,49 @@ function isDisposable(value) {
942
1032
  return false;
943
1033
  }
944
1034
  __name(isDisposable, "isDisposable");
1035
+ function callPostConstruct(target, instance) {
1036
+ const hook = readPostConstruct(target);
1037
+ if (hook === void 0) return void 0;
1038
+ const method = instance[hook];
1039
+ if (typeof method !== "function") return void 0;
1040
+ return method.call(instance);
1041
+ }
1042
+ __name(callPostConstruct, "callPostConstruct");
1043
+ function runPostConstructSync(target, instance) {
1044
+ const returned = callPostConstruct(target, instance);
1045
+ if (isThenable(returned)) {
1046
+ throw new AsyncPostConstructInSyncResolveError(target.name, String(readPostConstruct(target)));
1047
+ }
1048
+ return instance;
1049
+ }
1050
+ __name(runPostConstructSync, "runPostConstructSync");
1051
+ async function runPostConstructAsync(target, instance) {
1052
+ const returned = callPostConstruct(target, instance);
1053
+ if (isThenable(returned)) await returned;
1054
+ return instance;
1055
+ }
1056
+ __name(runPostConstructAsync, "runPostConstructAsync");
1057
+ async function callPreDestroy(instance) {
1058
+ const ctor = instance.constructor;
1059
+ if (typeof ctor !== "function") return;
1060
+ const hook = readPreDestroy(ctor);
1061
+ if (hook === void 0) return;
1062
+ const method = instance[hook];
1063
+ if (typeof method !== "function") return;
1064
+ await method.call(instance);
1065
+ }
1066
+ __name(callPreDestroy, "callPreDestroy");
1067
+ function hasPreDestroy(value) {
1068
+ if (value === null || typeof value !== "object") return false;
1069
+ const ctor = value.constructor;
1070
+ if (typeof ctor !== "function") return false;
1071
+ return readPreDestroy(ctor) !== void 0;
1072
+ }
1073
+ __name(hasPreDestroy, "hasPreDestroy");
1074
+ function isThenable(value) {
1075
+ return value !== null && (typeof value === "object" || typeof value === "function") && typeof value.then === "function";
1076
+ }
1077
+ __name(isThenable, "isThenable");
945
1078
 
946
1079
  // src/decorators/inject.ts
947
1080
  function Inject(token) {
@@ -965,6 +1098,16 @@ function Injectable(options = {}) {
965
1098
  }
966
1099
  __name(Injectable, "Injectable");
967
1100
 
1101
+ // src/decorators/lifecycle.ts
1102
+ function PostConstruct(target, propertyKey) {
1103
+ Reflect.defineMetadata(METADATA_KEYS.POST_CONSTRUCT, propertyKey, target.constructor);
1104
+ }
1105
+ __name(PostConstruct, "PostConstruct");
1106
+ function PreDestroy(target, propertyKey) {
1107
+ Reflect.defineMetadata(METADATA_KEYS.PRE_DESTROY, propertyKey, target.constructor);
1108
+ }
1109
+ __name(PreDestroy, "PreDestroy");
1110
+
968
1111
  // src/decorators/optional.ts
969
1112
  function Optional() {
970
1113
  return (target, _propertyKey, parameterIndex) => {
@@ -976,6 +1119,22 @@ function Optional() {
976
1119
  }
977
1120
  __name(Optional, "Optional");
978
1121
 
979
- export { AsyncProviderInSyncResolveError, Container, ContainerDisposedError, ContainerFrozenError, CyclicDependencyError, CyclicModuleImportError, Inject, Injectable, InvalidExportError, InvalidModuleError, MissingInjectableError, Module, Optional, ReflectMetadataMissingError, Scope, ScopeViolationError, TokenNotFoundError, describeToken };
1122
+ // src/decorators/primary.ts
1123
+ function Primary(target) {
1124
+ Reflect.defineMetadata(METADATA_KEYS.PRIMARY, true, target);
1125
+ }
1126
+ __name(Primary, "Primary");
1127
+
1128
+ // src/decorators/qualifier.ts
1129
+ function Qualifier(name) {
1130
+ return (target, _propertyKey, parameterIndex) => {
1131
+ const existing = Reflect.getMetadata(METADATA_KEYS.QUALIFIER_NAMES, target) ?? /* @__PURE__ */ new Map();
1132
+ existing.set(parameterIndex, name);
1133
+ Reflect.defineMetadata(METADATA_KEYS.QUALIFIER_NAMES, existing, target);
1134
+ };
1135
+ }
1136
+ __name(Qualifier, "Qualifier");
1137
+
1138
+ 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, describeToken };
980
1139
  //# sourceMappingURL=index.js.map
981
1140
  //# sourceMappingURL=index.js.map