getbox 1.3.1 → 2.0.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.d.mts CHANGED
@@ -1,8 +1,9 @@
1
1
  //#region src/index.d.ts
2
2
  /**
3
- * A type that can be resolved by a {@link Box}. Either an object with an
4
- * `init(box: Box)` method, a class with a `static init(box: Box)` method
5
- * that returns an instance, or a class with a no-argument constructor.
3
+ * A type that can be resolved by a {@link Box}. Either a class with a
4
+ * `static init` function that returns an instance, a class with a
5
+ * no-argument constructor, or a function-based constructor created by
6
+ * {@link factory}, {@link computed}, or {@link constant}.
6
7
  */
7
8
  type Constructor<T> = {
8
9
  init(box: Box): T;
@@ -30,22 +31,28 @@ type ConstructorInstanceType<T> = T extends {
30
31
  */
31
32
  declare function factory<T>(init: (box: Box) => T): Constructor<T>;
32
33
  /**
33
- * Creates a {@link Constructor} from a factory function whose result is never cached.
34
- * The factory is called on every resolution, always returning a fresh value
35
- * even when retrieved via {@link Box.get}.
34
+ * Creates a {@link Constructor} that computes a value from the box without caching the result.
36
35
  *
37
36
  * @example
38
37
  * ```ts
39
- * const RequestId = transient(() => crypto.randomUUID());
40
- * const id1 = box.get(RequestId);
41
- * const id2 = box.get(RequestId);
42
- * console.log(id1 === id2); // false
38
+ * class Config {
39
+ * baseUrl = "https://example.com";
40
+ * }
41
+ *
42
+ * const RequestContext = computed((box) => ({
43
+ * baseUrl: box.get(Config).baseUrl,
44
+ * timestamp: Date.now(),
45
+ * }));
46
+ *
47
+ * const ctx1 = box.get(RequestContext);
48
+ * const ctx2 = box.get(RequestContext);
49
+ * console.log(ctx1 === ctx2); // false
43
50
  * ```
44
51
  */
45
- declare function transient<T>(init: (box: Box) => T): Constructor<T>;
52
+ declare function computed<T>(init: (box: Box) => T): Constructor<T>;
46
53
  /**
47
54
  * Creates a {@link Constructor} that always resolves to the given constant value.
48
- * Constant values are never cached since they are already fixed.
55
+ * Constant values are already fixed and do not need caching.
49
56
  *
50
57
  * @example
51
58
  * ```ts
@@ -58,10 +65,9 @@ declare function constant<const T>(value: T): Constructor<T>;
58
65
  * Dependency injection container that resolves and caches instances from
59
66
  * a {@link Constructor}.
60
67
  *
61
- * A constructor is an object with an `init(box: Box)` method,
62
- * a class with a `static init(box: Box)` method, or a class with a
63
- * no-argument constructor. The {@link factory} and {@link constant} helpers
64
- * create constructors from functions and values respectively.
68
+ * A constructor is a class with a `static init` function, a class with a
69
+ * no-argument constructor, or a function-based constructor created by
70
+ * {@link factory}, {@link computed}, or {@link constant}.
65
71
  *
66
72
  * @example
67
73
  * ```ts
@@ -71,9 +77,7 @@ declare function constant<const T>(value: T): Constructor<T>;
71
77
  *
72
78
  * class UserService {
73
79
  * constructor(private db: Database) {}
74
- * static init(box: Box) {
75
- * return new UserService(box.get(Database));
76
- * }
80
+ * static init = Box.init(UserService).get(Database);
77
81
  * }
78
82
  *
79
83
  * const box = new Box();
@@ -81,35 +85,27 @@ declare function constant<const T>(value: T): Constructor<T>;
81
85
  * const db = box.get(Database);
82
86
  *
83
87
  * console.log(service.db === db); // true (cached)
84
- * console.log(box.new(Database) === db); // false (transient)
85
88
  * ```
86
89
  */
87
90
  declare class Box {
88
- private cache;
91
+ protected cache: Map<Constructor<any>, any>;
89
92
  /**
90
- * Creates a new (transient) instance without caching. Useful for instances
91
- * that should not be shared.
93
+ * Creates a new instance without caching.
94
+ * Accepts a single constructor, an array of constructors, or an object map of constructors.
92
95
  */
93
96
  new<T extends Constructor<any>>(constructor: T): ConstructorInstanceType<T>;
97
+ new<const T extends Constructor<any>[]>(constructors: T): { [K in keyof T]: ConstructorInstanceType<T[K]> };
98
+ new<T extends Record<string, Constructor<any>>>(constructors: T): { [K in keyof T]: ConstructorInstanceType<T[K]> };
94
99
  /**
95
100
  * Resolves an instance from the cache, or creates and caches a new one.
96
101
  * Subsequent calls with the same constructor return the cached instance.
102
+ * Accepts a single constructor, an array of constructors, or an object map of constructors.
97
103
  */
98
104
  get<T extends Constructor<any>>(constructor: T): ConstructorInstanceType<T>;
99
- /** Resolves multiple constructors at once. */
100
- readonly all: BoxAll;
101
- /**
102
- * Returns a {@link Construct} builder for creating class instances by
103
- * resolving constructors for each constructor parameter.
104
- *
105
- * Intended to be used inside a class's `static init` method. The instance
106
- * returned by the builder is never cached itself, but can be cached when
107
- * the class is retrieved via {@link Box.get} or kept transient via {@link Box.new}.
108
- */
109
- for<T extends ClassConstructor<any>>(constructor: T): Construct<T>;
105
+ get<const T extends Constructor<any>[]>(constructors: T): { [K in keyof T]: ConstructorInstanceType<T[K]> };
106
+ get<T extends Record<string, Constructor<any>>>(constructors: T): { [K in keyof T]: ConstructorInstanceType<T[K]> };
110
107
  /**
111
- * Returns a {@link StaticConstruct} builder for defining a `static init` method.
112
- * The result can be assigned directly to `static init`.
108
+ * Returns a `static init` function builder.
113
109
  *
114
110
  * @example
115
111
  * ```ts
@@ -119,7 +115,7 @@ declare class Box {
119
115
  * }
120
116
  * ```
121
117
  */
122
- static init<T extends ClassConstructor<any>>(constructor: T): StaticConstruct<T>;
118
+ static init<T extends ClassConstructor<any>>(constructor: T): StaticInit<T>;
123
119
  /**
124
120
  * Registers a mock value in the box's cache for a given constructor.
125
121
  * Useful for replacing dependencies in tests.
@@ -128,88 +124,31 @@ declare class Box {
128
124
  /**
129
125
  * Removes the instance from the box's cache for a given constructor.
130
126
  * Removes all instances if no constructor is provided.
131
- */
132
- static clear<T>(box: Box, constructor?: Constructor<T>): void;
133
- }
134
- /** Resolves multiple constructors at once from a {@link Box}. */
135
- declare class BoxAll {
136
- private box;
137
- constructor(box: Box);
138
- /**
139
- * Resolves each constructor as a cached instance via {@link Box.get}.
140
- * Accepts an array or object of constructors and returns instances in the same shape.
141
- */
142
- get<const T extends Constructor<any>[]>(constructors: T): { [K in keyof T]: ConstructorInstanceType<T[K]> };
143
- get<T extends Record<string, Constructor<any>>>(constructors: T): { [K in keyof T]: ConstructorInstanceType<T[K]> };
144
- /**
145
- * Resolves each constructor as a new transient instance via {@link Box.new}.
146
- * Accepts an array or object of constructors and returns instances in the same shape.
147
- */
148
- new<const T extends Constructor<any>[]>(constructors: T): { [K in keyof T]: ConstructorInstanceType<T[K]> };
149
- new<T extends Record<string, Constructor<any>>>(constructors: T): { [K in keyof T]: ConstructorInstanceType<T[K]> };
150
- }
151
- /** Builder for creating class instances with constructor dependencies resolved from a {@link Box}. */
152
- declare class Construct<T extends ClassConstructor<any>> {
153
- private box;
154
- private construct;
155
- constructor(box: Box, construct: T);
156
- /**
157
- * Resolves each dependency as a new transient instance via {@link Box.new},
158
- * meaning dependencies are not cached or shared.
159
- *
160
- * The returned instance is cached or transient depending on whether the
161
- * class is retrieved via {@link Box.get} or {@link Box.new}.
162
127
  *
163
- * @example
164
- * ```ts
165
- * class UserService {
166
- * constructor(private db: Database, private logger: Logger) {}
167
- * static init(box: Box) {
168
- * return box.for(UserService).new(Database, LoggerFactory);
169
- * }
170
- * }
171
- * ```
128
+ * Returns true if an instance existed and has been removed from the box's cache.
172
129
  */
173
- new(...args: ClassConstructorArgs<T>): InstanceType<T>;
174
- /**
175
- * Resolves each dependency as a cached instance via {@link Box.get},
176
- * meaning dependencies are shared across the box.
177
- *
178
- * The returned instance is cached or transient depending on whether the
179
- * class is retrieved via {@link Box.get} or {@link Box.new}.
180
- *
181
- * @example
182
- * ```ts
183
- * class UserService {
184
- * constructor(private db: Database, private logger: Logger) {}
185
- * static init(box: Box) {
186
- * return box.for(UserService).get(Database, LoggerFactory);
187
- * }
188
- * }
189
- * ```
190
- */
191
- get(...args: ClassConstructorArgs<T>): InstanceType<T>;
130
+ static clear<T>(box: Box, constructor?: Constructor<T>): boolean;
192
131
  }
193
132
  /**
194
133
  * Builder for creating a `static init` function with constructor dependencies
195
134
  * resolved from a {@link Box}.
196
135
  */
197
- declare class StaticConstruct<T extends ClassConstructor<any>> {
136
+ declare class StaticInit<T extends ClassConstructor<any>> {
198
137
  private construct;
199
138
  constructor(construct: T);
200
139
  /**
201
- * Resolves each dependency as a new transient instance via {@link Box.new},
140
+ * Resolves each dependency as a new instance via {@link Box.new},
202
141
  * meaning dependencies are not cached or shared.
203
142
  * Returns a function compatible with `static init` that can be assigned directly.
204
143
  *
205
- * The returned instance is cached or transient depending on whether the
144
+ * The returned instance is cached or new depending on whether the
206
145
  * class is retrieved via {@link Box.get} or {@link Box.new}.
207
146
  *
208
147
  * @example
209
148
  * ```ts
210
149
  * class UserService {
211
150
  * constructor(private db: Database, private logger: Logger) {}
212
- * static init = Box.init(UserService).get(Database, LoggerFactory);
151
+ * static init = Box.init(UserService).new(Database, LoggerFactory);
213
152
  * }
214
153
  * ```
215
154
  */
@@ -219,7 +158,7 @@ declare class StaticConstruct<T extends ClassConstructor<any>> {
219
158
  * meaning dependencies are shared across the box.
220
159
  * Returns a function compatible with `static init` that can be assigned directly.
221
160
  *
222
- * The returned instance is cached or transient depending on whether the
161
+ * The returned instance is cached or new depending on whether the
223
162
  * class is retrieved via {@link Box.get} or {@link Box.new}.
224
163
  *
225
164
  * @example
@@ -239,4 +178,4 @@ type ClassConstructor<T> = {
239
178
  /** Maps each constructor parameter to its corresponding {@link Constructor} type. */
240
179
  type ClassConstructorArgs<T extends ClassConstructor<any>, Args = ConstructorParameters<T>> = { [K in keyof Args]: Constructor<Args[K]> };
241
180
  //#endregion
242
- export { Box, Construct, Constructor, ConstructorInstanceType, StaticConstruct, constant, factory, transient };
181
+ export { Box, Constructor, ConstructorInstanceType, StaticInit, computed, constant, factory };
package/dist/index.mjs CHANGED
@@ -1,4 +1,6 @@
1
1
  //#region src/index.ts
2
+ const cacheSymbol = Symbol("Box.cache");
3
+ const isClass = (fn) => fn.prototype !== void 0 && Function.prototype.toString.call(fn).startsWith("class");
2
4
  /**
3
5
  * Creates a {@link Constructor} from a factory function.
4
6
  * The factory receives the box as an argument, allowing it to resolve other dependencies.
@@ -13,31 +15,36 @@
13
15
  * ```
14
16
  */
15
17
  function factory(init) {
16
- return { init };
18
+ return {
19
+ [cacheSymbol]: true,
20
+ init
21
+ };
17
22
  }
18
- const noCacheSymbol = Symbol("Box.noCache");
19
23
  /**
20
- * Creates a {@link Constructor} from a factory function whose result is never cached.
21
- * The factory is called on every resolution, always returning a fresh value
22
- * even when retrieved via {@link Box.get}.
24
+ * Creates a {@link Constructor} that computes a value from the box without caching the result.
23
25
  *
24
26
  * @example
25
27
  * ```ts
26
- * const RequestId = transient(() => crypto.randomUUID());
27
- * const id1 = box.get(RequestId);
28
- * const id2 = box.get(RequestId);
29
- * console.log(id1 === id2); // false
28
+ * class Config {
29
+ * baseUrl = "https://example.com";
30
+ * }
31
+ *
32
+ * const RequestContext = computed((box) => ({
33
+ * baseUrl: box.get(Config).baseUrl,
34
+ * timestamp: Date.now(),
35
+ * }));
36
+ *
37
+ * const ctx1 = box.get(RequestContext);
38
+ * const ctx2 = box.get(RequestContext);
39
+ * console.log(ctx1 === ctx2); // false
30
40
  * ```
31
41
  */
32
- function transient(init) {
33
- return {
34
- init,
35
- [noCacheSymbol]: true
36
- };
42
+ function computed(init) {
43
+ return { init };
37
44
  }
38
45
  /**
39
46
  * Creates a {@link Constructor} that always resolves to the given constant value.
40
- * Constant values are never cached since they are already fixed.
47
+ * Constant values are already fixed and do not need caching.
41
48
  *
42
49
  * @example
43
50
  * ```ts
@@ -46,19 +53,15 @@ function transient(init) {
46
53
  * ```
47
54
  */
48
55
  function constant(value) {
49
- return {
50
- init: () => value,
51
- [noCacheSymbol]: true
52
- };
56
+ return { init: () => value };
53
57
  }
54
58
  /**
55
59
  * Dependency injection container that resolves and caches instances from
56
60
  * a {@link Constructor}.
57
61
  *
58
- * A constructor is an object with an `init(box: Box)` method,
59
- * a class with a `static init(box: Box)` method, or a class with a
60
- * no-argument constructor. The {@link factory} and {@link constant} helpers
61
- * create constructors from functions and values respectively.
62
+ * A constructor is a class with a `static init` function, a class with a
63
+ * no-argument constructor, or a function-based constructor created by
64
+ * {@link factory}, {@link computed}, or {@link constant}.
62
65
  *
63
66
  * @example
64
67
  * ```ts
@@ -68,9 +71,7 @@ function constant(value) {
68
71
  *
69
72
  * class UserService {
70
73
  * constructor(private db: Database) {}
71
- * static init(box: Box) {
72
- * return new UserService(box.get(Database));
73
- * }
74
+ * static init = Box.init(UserService).get(Database);
74
75
  * }
75
76
  *
76
77
  * const box = new Box();
@@ -78,44 +79,38 @@ function constant(value) {
78
79
  * const db = box.get(Database);
79
80
  *
80
81
  * console.log(service.db === db); // true (cached)
81
- * console.log(box.new(Database) === db); // false (transient)
82
82
  * ```
83
83
  */
84
84
  var Box = class {
85
85
  cache = /* @__PURE__ */ new Map();
86
- /**
87
- * Creates a new (transient) instance without caching. Useful for instances
88
- * that should not be shared.
89
- */
90
- new(constructor) {
91
- return "init" in constructor ? constructor.init(this) : new constructor();
92
- }
93
- /**
94
- * Resolves an instance from the cache, or creates and caches a new one.
95
- * Subsequent calls with the same constructor return the cached instance.
96
- */
97
- get(constructor) {
98
- if (this.cache.has(constructor)) return this.cache.get(constructor);
99
- const value = this.new(constructor);
100
- if (!(noCacheSymbol in constructor && constructor[noCacheSymbol])) this.cache.set(constructor, value);
101
- return value;
86
+ new(arg) {
87
+ if (Array.isArray(arg)) return arg.map((c) => this.new(c));
88
+ if (typeof arg === "function") return "init" in arg ? arg.init(this) : new arg();
89
+ if ("init" in arg && !isClass(arg.init)) return arg.init(this);
90
+ const result = {};
91
+ for (const [key, constructor] of Object.entries(arg)) result[key] = this.new(constructor);
92
+ return result;
102
93
  }
103
- /** Resolves multiple constructors at once. */
104
- all = new BoxAll(this);
105
- /**
106
- * Returns a {@link Construct} builder for creating class instances by
107
- * resolving constructors for each constructor parameter.
108
- *
109
- * Intended to be used inside a class's `static init` method. The instance
110
- * returned by the builder is never cached itself, but can be cached when
111
- * the class is retrieved via {@link Box.get} or kept transient via {@link Box.new}.
112
- */
113
- for(constructor) {
114
- return new Construct(this, constructor);
94
+ get(arg) {
95
+ if (Array.isArray(arg)) return arg.map((c) => this.get(c));
96
+ if (typeof arg === "function") {
97
+ if (this.cache.has(arg)) return this.cache.get(arg);
98
+ const value = "init" in arg ? arg.init(this) : new arg();
99
+ this.cache.set(arg, value);
100
+ return value;
101
+ }
102
+ if ("init" in arg && !isClass(arg.init)) {
103
+ if (this.cache.has(arg)) return this.cache.get(arg);
104
+ const value = arg.init(this);
105
+ if (cacheSymbol in arg) this.cache.set(arg, value);
106
+ return value;
107
+ }
108
+ const result = {};
109
+ for (const [key, constructor] of Object.entries(arg)) result[key] = this.get(constructor);
110
+ return result;
115
111
  }
116
112
  /**
117
- * Returns a {@link StaticConstruct} builder for defining a `static init` method.
118
- * The result can be assigned directly to `static init`.
113
+ * Returns a `static init` function builder.
119
114
  *
120
115
  * @example
121
116
  * ```ts
@@ -126,7 +121,7 @@ var Box = class {
126
121
  * ```
127
122
  */
128
123
  static init(constructor) {
129
- return new StaticConstruct(constructor);
124
+ return new StaticInit(constructor);
130
125
  }
131
126
  /**
132
127
  * Registers a mock value in the box's cache for a given constructor.
@@ -138,107 +133,45 @@ var Box = class {
138
133
  /**
139
134
  * Removes the instance from the box's cache for a given constructor.
140
135
  * Removes all instances if no constructor is provided.
141
- */
142
- static clear(box, constructor) {
143
- if (!constructor) return box.cache.clear();
144
- box.cache.delete(constructor);
145
- }
146
- };
147
- /** Resolves multiple constructors at once from a {@link Box}. */
148
- var BoxAll = class {
149
- constructor(box) {
150
- this.box = box;
151
- }
152
- get(constructors) {
153
- if (Array.isArray(constructors)) return constructors.map((c) => this.box.get(c));
154
- const result = {};
155
- for (const [key, constructor] of Object.entries(constructors)) result[key] = this.box.get(constructor);
156
- return result;
157
- }
158
- new(constructors) {
159
- if (Array.isArray(constructors)) return constructors.map((c) => this.box.new(c));
160
- const result = {};
161
- for (const [key, constructor] of Object.entries(constructors)) result[key] = this.box.new(constructor);
162
- return result;
163
- }
164
- };
165
- /** Builder for creating class instances with constructor dependencies resolved from a {@link Box}. */
166
- var Construct = class {
167
- constructor(box, construct) {
168
- this.box = box;
169
- this.construct = construct;
170
- }
171
- /**
172
- * Resolves each dependency as a new transient instance via {@link Box.new},
173
- * meaning dependencies are not cached or shared.
174
- *
175
- * The returned instance is cached or transient depending on whether the
176
- * class is retrieved via {@link Box.get} or {@link Box.new}.
177
- *
178
- * @example
179
- * ```ts
180
- * class UserService {
181
- * constructor(private db: Database, private logger: Logger) {}
182
- * static init(box: Box) {
183
- * return box.for(UserService).new(Database, LoggerFactory);
184
- * }
185
- * }
186
- * ```
187
- */
188
- new(...args) {
189
- const instances = args.map((arg) => this.box.new(arg));
190
- return new this.construct(...instances);
191
- }
192
- /**
193
- * Resolves each dependency as a cached instance via {@link Box.get},
194
- * meaning dependencies are shared across the box.
195
- *
196
- * The returned instance is cached or transient depending on whether the
197
- * class is retrieved via {@link Box.get} or {@link Box.new}.
198
136
  *
199
- * @example
200
- * ```ts
201
- * class UserService {
202
- * constructor(private db: Database, private logger: Logger) {}
203
- * static init(box: Box) {
204
- * return box.for(UserService).get(Database, LoggerFactory);
205
- * }
206
- * }
207
- * ```
137
+ * Returns true if an instance existed and has been removed from the box's cache.
208
138
  */
209
- get(...args) {
210
- const instances = args.map((arg) => this.box.get(arg));
211
- return new this.construct(...instances);
139
+ static clear(box, constructor) {
140
+ if (!constructor) {
141
+ const size = box.cache.size;
142
+ box.cache.clear();
143
+ return size > 0;
144
+ }
145
+ return box.cache.delete(constructor);
212
146
  }
213
147
  };
214
148
  /**
215
149
  * Builder for creating a `static init` function with constructor dependencies
216
150
  * resolved from a {@link Box}.
217
151
  */
218
- var StaticConstruct = class {
152
+ var StaticInit = class {
219
153
  constructor(construct) {
220
154
  this.construct = construct;
221
155
  }
222
156
  /**
223
- * Resolves each dependency as a new transient instance via {@link Box.new},
157
+ * Resolves each dependency as a new instance via {@link Box.new},
224
158
  * meaning dependencies are not cached or shared.
225
159
  * Returns a function compatible with `static init` that can be assigned directly.
226
160
  *
227
- * The returned instance is cached or transient depending on whether the
161
+ * The returned instance is cached or new depending on whether the
228
162
  * class is retrieved via {@link Box.get} or {@link Box.new}.
229
163
  *
230
164
  * @example
231
165
  * ```ts
232
166
  * class UserService {
233
167
  * constructor(private db: Database, private logger: Logger) {}
234
- * static init = Box.init(UserService).get(Database, LoggerFactory);
168
+ * static init = Box.init(UserService).new(Database, LoggerFactory);
235
169
  * }
236
170
  * ```
237
171
  */
238
172
  new(...args) {
239
173
  return (box) => {
240
- const instances = args.map((arg) => box.new(arg));
241
- return new this.construct(...instances);
174
+ return new this.construct(...box.new(args));
242
175
  };
243
176
  }
244
177
  /**
@@ -246,7 +179,7 @@ var StaticConstruct = class {
246
179
  * meaning dependencies are shared across the box.
247
180
  * Returns a function compatible with `static init` that can be assigned directly.
248
181
  *
249
- * The returned instance is cached or transient depending on whether the
182
+ * The returned instance is cached or new depending on whether the
250
183
  * class is retrieved via {@link Box.get} or {@link Box.new}.
251
184
  *
252
185
  * @example
@@ -259,11 +192,10 @@ var StaticConstruct = class {
259
192
  */
260
193
  get(...args) {
261
194
  return (box) => {
262
- const instances = args.map((arg) => box.get(arg));
263
- return new this.construct(...instances);
195
+ return new this.construct(...box.get(args));
264
196
  };
265
197
  }
266
198
  };
267
199
 
268
200
  //#endregion
269
- export { Box, Construct, StaticConstruct, constant, factory, transient };
201
+ export { Box, StaticInit, computed, constant, factory };
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "getbox",
3
- "version": "1.3.1",
3
+ "version": "2.0.0",
4
4
  "description": "Lightweight dependency injection for TypeScript",
5
5
  "private": false,
6
6
  "main": "./dist/index.cjs",