@fluixi/di 1.0.0-alpha.108 → 1.0.0-alpha.110

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.
@@ -0,0 +1,8 @@
1
+ // src/token.ts
2
+ function injectionToken(name, options) {
3
+ return { id: Symbol(name), name, factory: options?.factory, scope: options?.scope ?? "root" };
4
+ }
5
+
6
+ export {
7
+ injectionToken
8
+ };
@@ -0,0 +1,16 @@
1
+ // src/errors.ts
2
+ var InjectionError = class extends Error {
3
+ /**
4
+ * @param message - What went wrong, with the path rendered into it.
5
+ * @param path - The tokens being resolved, outermost first; the last one is the one that failed.
6
+ */
7
+ constructor(message, path) {
8
+ super(message);
9
+ this.path = path;
10
+ this.name = "InjectionError";
11
+ }
12
+ };
13
+
14
+ export {
15
+ InjectionError
16
+ };
@@ -0,0 +1,12 @@
1
+ import {
2
+ injectionToken
3
+ } from "./chunk-2GEQYTZE.mjs";
4
+
5
+ // src/tokens.ts
6
+ var DestroyRef = injectionToken("DestroyRef");
7
+ var INJECTOR = injectionToken("Injector");
8
+
9
+ export {
10
+ DestroyRef,
11
+ INJECTOR
12
+ };
@@ -0,0 +1,25 @@
1
+ // src/state.ts
2
+ function freshState() {
3
+ return {
4
+ platformProviders: [],
5
+ rootProviders: [],
6
+ platform: null,
7
+ clientRoot: null,
8
+ requestRoots: /* @__PURE__ */ new WeakMap(),
9
+ ownerInjectors: /* @__PURE__ */ new WeakMap(),
10
+ moduleScopes: /* @__PURE__ */ new WeakMap(),
11
+ overrides: /* @__PURE__ */ new Map(),
12
+ explicit: null,
13
+ path: []
14
+ };
15
+ }
16
+ var state = globalThis[/* @__PURE__ */ Symbol.for("fluixi.di")] ??= freshState();
17
+ function setModuleScope(provider, scope) {
18
+ state.moduleScopes.set(provider, scope);
19
+ }
20
+
21
+ export {
22
+ freshState,
23
+ state,
24
+ setModuleScope
25
+ };
@@ -0,0 +1,15 @@
1
+ var __typeError = (msg) => {
2
+ throw TypeError(msg);
3
+ };
4
+ var __accessCheck = (obj, member, msg) => member.has(obj) || __typeError("Cannot " + msg);
5
+ var __privateGet = (obj, member, getter) => (__accessCheck(obj, member, "read from private field"), getter ? getter.call(obj) : member.get(obj));
6
+ var __privateAdd = (obj, member, value) => member.has(obj) ? __typeError("Cannot add the same private member more than once") : member instanceof WeakSet ? member.add(obj) : member.set(obj, value);
7
+ var __privateSet = (obj, member, value, setter) => (__accessCheck(obj, member, "write to private field"), setter ? setter.call(obj, value) : member.set(obj, value), value);
8
+ var __privateMethod = (obj, member, method) => (__accessCheck(obj, member, "access private method"), method);
9
+
10
+ export {
11
+ __privateGet,
12
+ __privateAdd,
13
+ __privateSet,
14
+ __privateMethod
15
+ };
@@ -0,0 +1,113 @@
1
+ import {
2
+ Injector,
3
+ currentInjector,
4
+ nearestOwnerInjector,
5
+ rootInjector
6
+ } from "./chunk-NZ4DEJ6M.mjs";
7
+ import {
8
+ injectionToken
9
+ } from "./chunk-2GEQYTZE.mjs";
10
+ import {
11
+ state
12
+ } from "./chunk-E32UTSJA.mjs";
13
+
14
+ // src/initializers.ts
15
+ import { beforeFirstRender, renderStarted } from "@fluixi/dom";
16
+
17
+ // src/inject.ts
18
+ import { getRequestContext } from "@fluixi/dom";
19
+ import { getOwner, onCleanup } from "@fluixi/reactive/signal";
20
+ function inject(token, options) {
21
+ return currentInjector().get(token, options ?? {});
22
+ }
23
+ function provide(providers) {
24
+ const owner = getOwner();
25
+ if (!owner) {
26
+ throw new Error("[fluixi/di] provide() runs inside a component. Use provideRoot() for services of the whole app.");
27
+ }
28
+ let inj = state.ownerInjectors.get(owner);
29
+ if (!inj) {
30
+ const created = new Injector(nearestOwnerInjector(owner.parent) ?? rootInjector(), "owner");
31
+ state.ownerInjectors.set(owner, created);
32
+ onCleanup(() => created.dispose());
33
+ inj = created;
34
+ }
35
+ return inj.register(providers);
36
+ }
37
+ function provideRoot(providers) {
38
+ warnLateInitializers(providers);
39
+ state.rootProviders.push(...providers);
40
+ state.clientRoot?.register(providers);
41
+ const ctx = getRequestContext();
42
+ if (ctx) state.requestRoots.get(ctx)?.register(providers);
43
+ }
44
+ function providePlatform(providers) {
45
+ state.platformProviders.push(...providers);
46
+ state.platform?.register(providers);
47
+ }
48
+ function runInInjectionContext(injector, fn) {
49
+ const previous = state.explicit;
50
+ state.explicit = injector;
51
+ try {
52
+ return fn();
53
+ } finally {
54
+ state.explicit = previous;
55
+ }
56
+ }
57
+ function isInInjectionContext() {
58
+ return state.explicit !== null || getOwner() !== null || getRequestContext() !== void 0;
59
+ }
60
+ function assertInInjectionContext(name) {
61
+ if (!isInInjectionContext()) {
62
+ throw new Error(`[fluixi/di] ${name}() runs inside a component, a request or runInInjectionContext().`);
63
+ }
64
+ }
65
+ function getInjector() {
66
+ return currentInjector();
67
+ }
68
+ function createInjector(providers, parent) {
69
+ return new Injector(parent === void 0 ? rootInjector() : parent, "standalone").register(providers);
70
+ }
71
+
72
+ // src/initializers.ts
73
+ var APP_INITIALIZER = injectionToken("AppInitializer");
74
+ function provideAppInitializer(fn) {
75
+ return { provide: APP_INITIALIZER, useValue: fn, multi: true };
76
+ }
77
+ async function runAppInitializers(injector = rootInjector()) {
78
+ for (const run of injector.get(APP_INITIALIZER, { optional: true }) ?? []) await runInInjectionContext(injector, run);
79
+ }
80
+ beforeFirstRender(() => {
81
+ if (!state.rootProviders.some(isInitializer)) return;
82
+ return runAppInitializers();
83
+ });
84
+ var isInitializer = (p) => p.provide.id === APP_INITIALIZER.id;
85
+ function production() {
86
+ try {
87
+ return true;
88
+ } catch {
89
+ return false;
90
+ }
91
+ }
92
+ function warnLateInitializers(providers) {
93
+ if (!renderStarted() || !providers.some(isInitializer) || production()) return;
94
+ console.warn(
95
+ "[fluixi/di] provideAppInitializer() was registered after the app started rendering, so it did not run before this render, and in the browser it never runs. Register it in an app module (app.config.ts) or the entry."
96
+ );
97
+ }
98
+
99
+ export {
100
+ APP_INITIALIZER,
101
+ provideAppInitializer,
102
+ runAppInitializers,
103
+ warnLateInitializers,
104
+ inject,
105
+ provide,
106
+ provideRoot,
107
+ providePlatform,
108
+ runInInjectionContext,
109
+ isInInjectionContext,
110
+ assertInInjectionContext,
111
+ getInjector,
112
+ createInjector
113
+ };
@@ -0,0 +1,246 @@
1
+ import {
2
+ DestroyRef,
3
+ INJECTOR
4
+ } from "./chunk-6Y4QWQA7.mjs";
5
+ import {
6
+ InjectionError
7
+ } from "./chunk-5BUN4TXK.mjs";
8
+ import {
9
+ state
10
+ } from "./chunk-E32UTSJA.mjs";
11
+ import {
12
+ __privateAdd,
13
+ __privateGet,
14
+ __privateMethod,
15
+ __privateSet
16
+ } from "./chunk-I6KKUHEY.mjs";
17
+
18
+ // src/injector.ts
19
+ import { openReactiveScope, withReactiveScope } from "@fluixi/reactive/signal";
20
+
21
+ // src/hierarchy.ts
22
+ import { onRequestEnd, requestScope } from "@fluixi/dom";
23
+ import { getOwner } from "@fluixi/reactive/signal";
24
+ function platformInjector() {
25
+ return state.platform ??= new Injector(null, "platform").register(state.platformProviders);
26
+ }
27
+ function rootInjector() {
28
+ const scope = requestScope();
29
+ if (scope) {
30
+ let inj = state.requestRoots.get(scope);
31
+ if (!inj) {
32
+ const root = new Injector(platformInjector(), "root").register(state.rootProviders);
33
+ state.requestRoots.set(scope, root);
34
+ onRequestEnd(() => {
35
+ state.requestRoots.delete(scope);
36
+ root.dispose();
37
+ });
38
+ inj = root;
39
+ }
40
+ return inj;
41
+ }
42
+ return state.clientRoot ??= new Injector(platformInjector(), "root").register(state.rootProviders);
43
+ }
44
+ function nearestOwnerInjector(owner) {
45
+ let o = owner;
46
+ while (o) {
47
+ const inj = state.ownerInjectors.get(o);
48
+ if (inj) return inj;
49
+ o = o.parent;
50
+ }
51
+ return null;
52
+ }
53
+ function currentInjector() {
54
+ if (state.explicit) return state.explicit;
55
+ const owner = getOwner();
56
+ if (owner) return nearestOwnerInjector(owner) ?? rootInjector();
57
+ if (requestScope()) return rootInjector();
58
+ throw new Error(
59
+ "[fluixi/di] inject() called outside an injection context (after an await? in an event handler?). Inject during setup and keep the value, or keep the injector (getInjector()) and use runInInjectionContext()."
60
+ );
61
+ }
62
+
63
+ // src/injector.ts
64
+ var _records, _created, _hooks, _destroyed, _Injector_instances, home_fn, fromProvider_fn, build_fn, make_fn;
65
+ var Injector = class {
66
+ /**
67
+ * @param parent - Where a token this injector does not hold is looked for next; `null` for the
68
+ * top of a chain.
69
+ * @param kind - Where the injector sits in the hierarchy; see {@link InjectorKind}.
70
+ */
71
+ constructor(parent = null, kind = "standalone") {
72
+ this.parent = parent;
73
+ this.kind = kind;
74
+ __privateAdd(this, _Injector_instances);
75
+ __privateAdd(this, _records, /* @__PURE__ */ new Map());
76
+ __privateAdd(this, _created, []);
77
+ __privateAdd(this, _hooks, []);
78
+ __privateAdd(this, _destroyed, false);
79
+ const self = this;
80
+ this.destroyRef = {
81
+ onDestroy(fn) {
82
+ __privateGet(self, _hooks).push(fn);
83
+ return () => {
84
+ const i = __privateGet(self, _hooks).indexOf(fn);
85
+ if (i >= 0) __privateGet(self, _hooks).splice(i, 1);
86
+ };
87
+ },
88
+ get destroyed() {
89
+ return __privateGet(self, _destroyed);
90
+ }
91
+ };
92
+ }
93
+ /** Whether {@link Injector.dispose} has run. A disposed injector refuses every `get`. */
94
+ get destroyed() {
95
+ return __privateGet(this, _destroyed);
96
+ }
97
+ /**
98
+ * Add providers to this injector. A provider for a token already held replaces it, except
99
+ * `multi` providers, which extend the token's list. A provider whose token has a test override
100
+ * is replaced by the override.
101
+ *
102
+ * @param providers - The providers to add, in order.
103
+ * @returns This injector, for chaining.
104
+ */
105
+ register(providers) {
106
+ for (const given of providers) {
107
+ const p = state.overrides.get(given.provide.id) ?? given;
108
+ if (p.multi) {
109
+ const rec = __privateGet(this, _records).get(p.provide.id);
110
+ if (rec?.multi) {
111
+ rec.providers.push(p);
112
+ rec.built = false;
113
+ } else __privateGet(this, _records).set(p.provide.id, { multi: true, providers: [p], built: false, building: false, value: [] });
114
+ } else {
115
+ __privateGet(this, _records).set(p.provide.id, { multi: false, provider: p, built: false, building: false, value: void 0 });
116
+ }
117
+ }
118
+ return this;
119
+ }
120
+ get(token, options = {}) {
121
+ var _a, _b, _c;
122
+ if (__privateGet(this, _destroyed)) throw new InjectionError(`[fluixi/di] "${token.name}" requested from a disposed injector.`, [...state.path, token.name]);
123
+ if (token.id === INJECTOR.id) return this;
124
+ if (token.id === DestroyRef.id) return this.destroyRef;
125
+ let inj = options.skipSelf ? this.parent : this;
126
+ while (inj) {
127
+ const rec = __privateGet(inj, _records).get(token.id);
128
+ if (rec) return __privateMethod(_a = inj, _Injector_instances, build_fn).call(_a, token, rec);
129
+ if (options.self || options.host && inj.kind === "owner") break;
130
+ inj = inj.parent;
131
+ }
132
+ const override = state.overrides.get(token.id);
133
+ if (override && !options.self) return __privateMethod(_b = __privateMethod(this, _Injector_instances, home_fn).call(this, token.scope), _Injector_instances, fromProvider_fn).call(_b, token, override);
134
+ if (token.factory && !options.self && !options.host) {
135
+ return __privateMethod(_c = __privateMethod(this, _Injector_instances, home_fn).call(this, token.scope), _Injector_instances, fromProvider_fn).call(_c, token, { provide: token, useFactory: token.factory });
136
+ }
137
+ if (options.optional) return null;
138
+ const path = [...state.path, token.name];
139
+ throw new InjectionError(
140
+ `[fluixi/di] No provider for "${token.name}" (${path.join(" → ")}). Provide it in an app module, with provide() or provideRoot(), or give the token a { factory }.`,
141
+ path
142
+ );
143
+ }
144
+ /**
145
+ * Release this injector: run the hooks registered on its `DestroyRef`, latest first, then the
146
+ * `onDestroy()` method of every service it built, latest built first, then forget its
147
+ * providers. A hook or `onDestroy()` that throws is logged and the rest still run. Running it
148
+ * again does nothing.
149
+ *
150
+ * Component injectors are disposed when the component unmounts, request roots when the request
151
+ * ends; call it yourself only for injectors you created.
152
+ */
153
+ dispose() {
154
+ if (__privateGet(this, _destroyed)) return;
155
+ __privateSet(this, _destroyed, true);
156
+ const fail = (error) => console.error("[fluixi/di] a destroy hook threw:", error);
157
+ for (const hook of __privateGet(this, _hooks).splice(0).reverse()) {
158
+ try {
159
+ hook();
160
+ } catch (error) {
161
+ fail(error);
162
+ }
163
+ }
164
+ for (const value of __privateGet(this, _created).splice(0).reverse()) {
165
+ const service = value;
166
+ if (service && typeof service.onDestroy === "function") {
167
+ try {
168
+ service.onDestroy();
169
+ } catch (error) {
170
+ fail(error);
171
+ }
172
+ }
173
+ }
174
+ __privateGet(this, _records).clear();
175
+ }
176
+ };
177
+ _records = new WeakMap();
178
+ _created = new WeakMap();
179
+ _hooks = new WeakMap();
180
+ _destroyed = new WeakMap();
181
+ _Injector_instances = new WeakSet();
182
+ /** The injector a self-providing token builds in: the nearest root, or the platform. */
183
+ home_fn = function(scope) {
184
+ let inj = this;
185
+ if (scope === "platform") {
186
+ while (inj.parent) inj = inj.parent;
187
+ return inj.kind === "platform" ? inj : platformInjector();
188
+ }
189
+ let probe = this;
190
+ while (probe) {
191
+ if (probe.kind === "root") return probe;
192
+ probe = probe.parent;
193
+ }
194
+ while (inj.parent && inj.parent.kind !== "platform") inj = inj.parent;
195
+ return inj;
196
+ };
197
+ fromProvider_fn = function(token, provider) {
198
+ let rec = __privateGet(this, _records).get(token.id);
199
+ if (!rec) {
200
+ rec = { multi: false, provider, built: false, building: false, value: void 0 };
201
+ __privateGet(this, _records).set(token.id, rec);
202
+ }
203
+ return __privateMethod(this, _Injector_instances, build_fn).call(this, token, rec);
204
+ };
205
+ build_fn = function(token, rec) {
206
+ if (rec.built) return rec.value;
207
+ if (rec.building) {
208
+ const path = [...state.path, token.name];
209
+ throw new InjectionError(`[fluixi/di] Circular dependency: ${path.join(" → ")}.`, path);
210
+ }
211
+ rec.building = true;
212
+ state.path.push(token.name);
213
+ const previous = state.explicit;
214
+ state.explicit = this;
215
+ try {
216
+ if (rec.multi) {
217
+ rec.value = rec.providers.map((p) => __privateMethod(this, _Injector_instances, make_fn).call(this, token, p));
218
+ } else {
219
+ const module = state.moduleScopes.get(rec.provider);
220
+ rec.value = module ? withReactiveScope(module, () => __privateMethod(this, _Injector_instances, make_fn).call(this, token, rec.provider)) : __privateMethod(this, _Injector_instances, make_fn).call(this, token, rec.provider);
221
+ }
222
+ rec.built = true;
223
+ return rec.value;
224
+ } finally {
225
+ state.explicit = previous;
226
+ state.path.pop();
227
+ rec.building = false;
228
+ }
229
+ };
230
+ make_fn = function(token, p) {
231
+ if ("useValue" in p) return p.useValue;
232
+ if ("useExisting" in p) return this.get(p.useExisting);
233
+ const deps = (p.deps ?? []).map((d) => "token" in d ? this.get(d.token, d) : this.get(d));
234
+ const scope = openReactiveScope({ kind: "service", name: token.name, detail: "useClass" in p ? "useClass" : "useFactory" });
235
+ const value = withReactiveScope(scope, () => "useClass" in p ? new p.useClass(...deps) : p.useFactory(...deps));
236
+ __privateGet(this, _created).push(value);
237
+ return value;
238
+ };
239
+
240
+ export {
241
+ Injector,
242
+ platformInjector,
243
+ rootInjector,
244
+ nearestOwnerInjector,
245
+ currentInjector
246
+ };
package/dist/errors.mjs CHANGED
@@ -1,15 +1,7 @@
1
- // src/errors.ts
2
- var InjectionError = class extends Error {
3
- /**
4
- * @param message - What went wrong, with the path rendered into it.
5
- * @param path - The tokens being resolved, outermost first; the last one is the one that failed.
6
- */
7
- constructor(message, path) {
8
- super(message);
9
- this.path = path;
10
- this.name = "InjectionError";
11
- }
12
- };
1
+ import {
2
+ InjectionError
3
+ } from "./chunk-5BUN4TXK.mjs";
4
+ import "./chunk-I6KKUHEY.mjs";
13
5
  export {
14
6
  InjectionError
15
7
  };
@@ -261,14 +261,14 @@ function platformInjector() {
261
261
  return state.platform ??= new Injector(null, "platform").register(state.platformProviders);
262
262
  }
263
263
  function rootInjector() {
264
- const ctx = (0, import_dom.getRequestContext)();
265
- if (ctx) {
266
- let inj = state.requestRoots.get(ctx);
264
+ const scope = (0, import_dom.requestScope)();
265
+ if (scope) {
266
+ let inj = state.requestRoots.get(scope);
267
267
  if (!inj) {
268
268
  const root = new Injector(platformInjector(), "root").register(state.rootProviders);
269
- state.requestRoots.set(ctx, root);
269
+ state.requestRoots.set(scope, root);
270
270
  (0, import_dom.onRequestEnd)(() => {
271
- state.requestRoots.delete(ctx);
271
+ state.requestRoots.delete(scope);
272
272
  root.dispose();
273
273
  });
274
274
  inj = root;
@@ -287,5 +287,11 @@ function nearestOwnerInjector(owner) {
287
287
  return null;
288
288
  }
289
289
  function currentInjector() {
290
- return state.explicit ?? nearestOwnerInjector((0, import_signal2.getOwner)()) ?? rootInjector();
290
+ if (state.explicit) return state.explicit;
291
+ const owner = (0, import_signal2.getOwner)();
292
+ if (owner) return nearestOwnerInjector(owner) ?? rootInjector();
293
+ if ((0, import_dom.requestScope)()) return rootInjector();
294
+ throw new Error(
295
+ "[fluixi/di] inject() called outside an injection context (after an await? in an event handler?). Inject during setup and keep the value, or keep the injector (getInjector()) and use runInInjectionContext()."
296
+ );
291
297
  }
@@ -2,8 +2,9 @@ import { Injector } from './injector.js';
2
2
  /** The process-wide injector: `providePlatform` services and `scope: 'platform'` tokens. */
3
3
  export declare function platformInjector(): Injector;
4
4
  /**
5
- * The root injector: one per request during a server render (disposed when the request ends),
6
- * one per app in the browser.
5
+ * The root injector: one per request on the server (disposed when the request ends), one per
6
+ * app in the browser. Keyed by the request scope rather than a render's context, so middleware
7
+ * and the page, route or function behind it get the same instances.
7
8
  */
8
9
  export declare function rootInjector(): Injector;
9
10
  export declare function nearestOwnerInjector(owner: any): Injector | null;
@@ -1 +1 @@
1
- {"version":3,"file":"hierarchy.d.ts","sourceRoot":"","sources":["../src/hierarchy.ts"],"names":[],"mappings":"AAOA,OAAO,EAAE,QAAQ,EAAE,MAAM,eAAe,CAAC;AAGzC,4FAA4F;AAC5F,wBAAgB,gBAAgB,IAAI,QAAQ,CAE3C;AAED;;;GAGG;AACH,wBAAgB,YAAY,IAAI,QAAQ,CAgBvC;AAED,wBAAgB,oBAAoB,CAAC,KAAK,EAAE,GAAG,GAAG,QAAQ,GAAG,IAAI,CAQhE;AAED,wBAAgB,eAAe,IAAI,QAAQ,CAE1C"}
1
+ {"version":3,"file":"hierarchy.d.ts","sourceRoot":"","sources":["../src/hierarchy.ts"],"names":[],"mappings":"AAOA,OAAO,EAAE,QAAQ,EAAE,MAAM,eAAe,CAAC;AAGzC,4FAA4F;AAC5F,wBAAgB,gBAAgB,IAAI,QAAQ,CAE3C;AAED;;;;GAIG;AACH,wBAAgB,YAAY,IAAI,QAAQ,CAgBvC;AAED,wBAAgB,oBAAoB,CAAC,KAAK,EAAE,GAAG,GAAG,QAAQ,GAAG,IAAI,CAQhE;AAED,wBAAgB,eAAe,IAAI,QAAQ,CAa1C"}
package/dist/hierarchy.js CHANGED
@@ -3,7 +3,7 @@
3
3
  * server, disposed when the request ends; one per app in the browser), and the component
4
4
  * injectors `provide()` attaches to the reactive owner tree.
5
5
  */
6
- import { getRequestContext, onRequestEnd } from '@fluixi/dom';
6
+ import { onRequestEnd, requestScope } from '@fluixi/dom';
7
7
  import { getOwner } from '@fluixi/reactive/signal';
8
8
  import { Injector } from './injector.js';
9
9
  import { state } from './state.js';
@@ -12,18 +12,19 @@ export function platformInjector() {
12
12
  return (state.platform ??= new Injector(null, 'platform').register(state.platformProviders));
13
13
  }
14
14
  /**
15
- * The root injector: one per request during a server render (disposed when the request ends),
16
- * one per app in the browser.
15
+ * The root injector: one per request on the server (disposed when the request ends), one per
16
+ * app in the browser. Keyed by the request scope rather than a render's context, so middleware
17
+ * and the page, route or function behind it get the same instances.
17
18
  */
18
19
  export function rootInjector() {
19
- const ctx = getRequestContext();
20
- if (ctx) {
21
- let inj = state.requestRoots.get(ctx);
20
+ const scope = requestScope();
21
+ if (scope) {
22
+ let inj = state.requestRoots.get(scope);
22
23
  if (!inj) {
23
24
  const root = new Injector(platformInjector(), 'root').register(state.rootProviders);
24
- state.requestRoots.set(ctx, root);
25
+ state.requestRoots.set(scope, root);
25
26
  onRequestEnd(() => {
26
- state.requestRoots.delete(ctx);
27
+ state.requestRoots.delete(scope);
27
28
  root.dispose();
28
29
  });
29
30
  inj = root;
@@ -43,5 +44,17 @@ export function nearestOwnerInjector(owner) {
43
44
  return null;
44
45
  }
45
46
  export function currentInjector() {
46
- return state.explicit ?? nearestOwnerInjector(getOwner()) ?? rootInjector();
47
+ if (state.explicit)
48
+ return state.explicit;
49
+ const owner = getOwner();
50
+ if (owner)
51
+ return nearestOwnerInjector(owner) ?? rootInjector();
52
+ // A server request is a context of its own: its root is the request's.
53
+ if (requestScope())
54
+ return rootInjector();
55
+ // No component, request or explicit injector: after an `await`, in an event handler, at
56
+ // module load. Falling back to the root here returned its instance in place of the one a
57
+ // component provided, with no sign of it.
58
+ throw new Error('[fluixi/di] inject() called outside an injection context (after an await? in an event handler?). ' +
59
+ 'Inject during setup and keep the value, or keep the injector (getInjector()) and use runInInjectionContext().');
47
60
  }