@navios/di-react 1.0.0-alpha.3 → 2.0.0-alpha.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/CHANGELOG.md +21 -0
- package/README.md +45 -665
- package/lib/{index.js → index.cjs} +249 -255
- package/lib/index.cjs.map +1 -0
- package/lib/{index.d.ts → index.d.cts} +94 -123
- package/lib/index.d.cts.map +1 -0
- package/lib/index.d.mts +93 -122
- package/lib/index.d.mts.map +1 -1
- package/lib/index.mjs +248 -255
- package/lib/index.mjs.map +1 -1
- package/package.json +32 -18
- package/coverage/base.css +0 -224
- package/coverage/block-navigation.js +0 -87
- package/coverage/clover.xml +0 -270
- package/coverage/coverage-final.json +0 -10
- package/coverage/favicon.png +0 -0
- package/coverage/hooks/index.html +0 -191
- package/coverage/hooks/use-container.mts.html +0 -268
- package/coverage/hooks/use-invalidate.mts.html +0 -208
- package/coverage/hooks/use-optional-service.mts.html +0 -910
- package/coverage/hooks/use-scope.mts.html +0 -346
- package/coverage/hooks/use-service.mts.html +0 -760
- package/coverage/hooks/use-suspense-service.mts.html +0 -784
- package/coverage/index.html +0 -131
- package/coverage/prettify.css +0 -1
- package/coverage/prettify.js +0 -2
- package/coverage/providers/container-provider.mts.html +0 -139
- package/coverage/providers/context.mts.html +0 -130
- package/coverage/providers/index.html +0 -146
- package/coverage/providers/scope-provider.mts.html +0 -355
- package/coverage/sort-arrow-sprite.png +0 -0
- package/coverage/sorter.js +0 -210
- package/lib/index.d.ts.map +0 -1
- package/lib/index.js.map +0 -1
- package/project.json +0 -61
- package/src/hooks/__tests__/use-container.spec.mts +0 -143
- package/src/hooks/__tests__/use-invalidate.spec.mts +0 -80
- package/src/hooks/__tests__/use-optional-service.spec.mts +0 -233
- package/src/hooks/__tests__/use-scope.spec.mts +0 -293
- package/src/hooks/__tests__/use-service.spec.mts +0 -212
- package/src/hooks/__tests__/use-suspense-service.spec.mts +0 -286
- package/src/hooks/index.mts +0 -14
- package/src/hooks/use-container.mts +0 -61
- package/src/hooks/use-invalidate.mts +0 -41
- package/src/hooks/use-optional-service.mts +0 -275
- package/src/hooks/use-scope.mts +0 -87
- package/src/hooks/use-service.mts +0 -225
- package/src/hooks/use-suspense-service.mts +0 -233
- package/src/index.mts +0 -8
- package/src/providers/__tests__/scope-provider.spec.mts +0 -366
- package/src/providers/container-provider.mts +0 -18
- package/src/providers/context.mts +0 -15
- package/src/providers/index.mts +0 -5
- package/src/providers/scope-provider.mts +0 -90
- package/src/types.mts +0 -21
- package/tsconfig.json +0 -13
- package/tsdown.config.mts +0 -14
- package/vitest.config.mts +0 -12
package/lib/index.mjs
CHANGED
|
@@ -1,7 +1,7 @@
|
|
|
1
|
-
import { createContext, useCallback, useContext, useEffect, useId, useReducer, useRef, useState, useSyncExternalStore } from "react";
|
|
1
|
+
import { createContext, useCallback, useContext, useEffect, useId, useMemo, useReducer, useRef, useState, useSyncExternalStore } from "react";
|
|
2
2
|
import { jsx } from "react/jsx-runtime";
|
|
3
|
-
|
|
4
|
-
|
|
3
|
+
import { DIError, DIErrorCode } from "@navios/di";
|
|
4
|
+
// src/container/context.mts
|
|
5
5
|
/**
|
|
6
6
|
* Context for the root Container.
|
|
7
7
|
* This is set by ContainerProvider and provides the base container.
|
|
@@ -12,18 +12,45 @@ const ContainerContext = createContext(null);
|
|
|
12
12
|
* This allows nested components to access request-scoped services.
|
|
13
13
|
*/
|
|
14
14
|
const ScopedContainerContext = createContext(null);
|
|
15
|
-
|
|
16
|
-
//#endregion
|
|
17
|
-
//#region src/providers/container-provider.mts
|
|
15
|
+
// src/container/container-provider.mts
|
|
18
16
|
function ContainerProvider({ container, children }) {
|
|
19
17
|
return jsx(ContainerContext.Provider, {
|
|
20
18
|
value: container,
|
|
21
19
|
children
|
|
22
20
|
});
|
|
23
21
|
}
|
|
24
|
-
|
|
25
|
-
|
|
26
|
-
|
|
22
|
+
// src/container/use-container.mts
|
|
23
|
+
/**
|
|
24
|
+
* Hook to get the current container (ScopedContainer if inside ScopeProvider, otherwise Container).
|
|
25
|
+
*
|
|
26
|
+
* This is the primary hook for accessing the DI container. It automatically
|
|
27
|
+
* returns the correct container based on context:
|
|
28
|
+
* - Inside a ScopeProvider: returns the ScopedContainer for request-scoped services
|
|
29
|
+
* - Outside a ScopeProvider: returns the root Container
|
|
30
|
+
*
|
|
31
|
+
* @returns The current container (ScopedContainer or Container)
|
|
32
|
+
*/
|
|
33
|
+
function useContainer() {
|
|
34
|
+
const scopedContainer = useContext(ScopedContainerContext);
|
|
35
|
+
const container = useContext(ContainerContext);
|
|
36
|
+
if (scopedContainer) return scopedContainer;
|
|
37
|
+
if (!container) throw new Error("useContainer must be used within a ContainerProvider");
|
|
38
|
+
return container;
|
|
39
|
+
}
|
|
40
|
+
/**
|
|
41
|
+
* Hook to get the root Container, regardless of whether we're inside a ScopeProvider.
|
|
42
|
+
*
|
|
43
|
+
* Use this when you need access to the root container specifically,
|
|
44
|
+
* for example to create new request scopes programmatically.
|
|
45
|
+
*
|
|
46
|
+
* @returns The root Container
|
|
47
|
+
*/
|
|
48
|
+
function useRootContainer() {
|
|
49
|
+
const container = useContext(ContainerContext);
|
|
50
|
+
if (!container) throw new Error("useRootContainer must be used within a ContainerProvider");
|
|
51
|
+
return container;
|
|
52
|
+
}
|
|
53
|
+
// src/scope/scope-provider.mts
|
|
27
54
|
/**
|
|
28
55
|
* ScopeProvider creates a new request scope for dependency injection.
|
|
29
56
|
*
|
|
@@ -52,57 +79,133 @@ function ScopeProvider({ scopeId, metadata, children }) {
|
|
|
52
79
|
const generatedId = useId();
|
|
53
80
|
const effectiveScopeId = scopeId ?? generatedId;
|
|
54
81
|
const scopedContainerRef = useRef(null);
|
|
55
|
-
|
|
56
|
-
|
|
57
|
-
|
|
82
|
+
const isMountedRef = useRef(false);
|
|
83
|
+
const isDisposedRef = useRef(false);
|
|
84
|
+
const [, rerender] = useReducer((count) => count + 1, 0);
|
|
85
|
+
const createScope = () => container.createScope({
|
|
86
|
+
...metadata,
|
|
87
|
+
scopeId: effectiveScopeId
|
|
88
|
+
});
|
|
89
|
+
const createScopeRef = useRef(createScope);
|
|
90
|
+
createScopeRef.current = createScope;
|
|
91
|
+
if (!scopedContainerRef.current) scopedContainerRef.current = createScope();
|
|
58
92
|
useEffect(() => {
|
|
59
|
-
|
|
93
|
+
isMountedRef.current = true;
|
|
94
|
+
if (isDisposedRef.current) {
|
|
95
|
+
isDisposedRef.current = false;
|
|
96
|
+
scopedContainerRef.current = createScopeRef.current();
|
|
97
|
+
rerender();
|
|
98
|
+
}
|
|
60
99
|
return () => {
|
|
61
|
-
|
|
100
|
+
isMountedRef.current = false;
|
|
101
|
+
queueMicrotask(() => {
|
|
102
|
+
if (isMountedRef.current || isDisposedRef.current) return;
|
|
103
|
+
isDisposedRef.current = true;
|
|
104
|
+
scopedContainerRef.current?.dispose();
|
|
105
|
+
});
|
|
62
106
|
};
|
|
63
107
|
}, []);
|
|
64
|
-
if (!scopedContainerRef.current) return null;
|
|
65
108
|
return jsx(ScopedContainerContext.Provider, {
|
|
66
109
|
value: scopedContainerRef.current,
|
|
67
110
|
children
|
|
68
111
|
});
|
|
69
112
|
}
|
|
70
|
-
|
|
71
|
-
//#endregion
|
|
72
|
-
//#region src/hooks/use-container.mts
|
|
113
|
+
// src/scope/use-scope.mts
|
|
73
114
|
/**
|
|
74
|
-
* Hook to get the current
|
|
115
|
+
* Hook to get the current scope ID.
|
|
116
|
+
* Returns null if not inside a ScopeProvider.
|
|
117
|
+
*/
|
|
118
|
+
function useScope() {
|
|
119
|
+
return useContext(ScopedContainerContext)?.getMetadata("scopeId") ?? null;
|
|
120
|
+
}
|
|
121
|
+
/**
|
|
122
|
+
* Hook to get the current scope ID, throwing if not inside a ScopeProvider.
|
|
123
|
+
* Use this when your component requires a scope to function correctly.
|
|
124
|
+
*/
|
|
125
|
+
function useScopeOrThrow() {
|
|
126
|
+
const scopeId = useScope();
|
|
127
|
+
if (scopeId === null) throw new Error("useScopeOrThrow must be used within a ScopeProvider. Wrap your component tree with <ScopeProvider> to create a request scope.");
|
|
128
|
+
return scopeId;
|
|
129
|
+
}
|
|
130
|
+
/**
|
|
131
|
+
* Hook to get the current ScopedContainer.
|
|
132
|
+
* Returns null if not inside a ScopeProvider.
|
|
75
133
|
*
|
|
76
|
-
*
|
|
77
|
-
* returns the correct container based on context:
|
|
78
|
-
* - Inside a ScopeProvider: returns the ScopedContainer for request-scoped services
|
|
79
|
-
* - Outside a ScopeProvider: returns the root Container
|
|
134
|
+
* Use this to access scope metadata or other ScopedContainer methods.
|
|
80
135
|
*
|
|
81
|
-
* @
|
|
136
|
+
* @example
|
|
137
|
+
* ```tsx
|
|
138
|
+
* function TableRow() {
|
|
139
|
+
* const scope = useScopedContainer()
|
|
140
|
+
* const rowData = scope?.getMetadata('rowData')
|
|
141
|
+
* // ...
|
|
142
|
+
* }
|
|
143
|
+
* ```
|
|
82
144
|
*/
|
|
83
|
-
function
|
|
84
|
-
|
|
85
|
-
const container = useContext(ContainerContext);
|
|
86
|
-
if (scopedContainer) return scopedContainer;
|
|
87
|
-
if (!container) throw new Error("useContainer must be used within a ContainerProvider");
|
|
88
|
-
return container;
|
|
145
|
+
function useScopedContainer() {
|
|
146
|
+
return useContext(ScopedContainerContext);
|
|
89
147
|
}
|
|
90
148
|
/**
|
|
91
|
-
* Hook to get the
|
|
149
|
+
* Hook to get the current ScopedContainer, throwing if not inside a ScopeProvider.
|
|
150
|
+
* Use this when your component requires a scope to function correctly.
|
|
151
|
+
*/
|
|
152
|
+
function useScopedContainerOrThrow() {
|
|
153
|
+
const scopedContainer = useScopedContainer();
|
|
154
|
+
if (scopedContainer === null) throw new Error("useScopedContainerOrThrow must be used within a ScopeProvider. Wrap your component tree with <ScopeProvider> to create a request scope.");
|
|
155
|
+
return scopedContainer;
|
|
156
|
+
}
|
|
157
|
+
/**
|
|
158
|
+
* Hook to get metadata from the current scope.
|
|
159
|
+
* Returns undefined if not inside a ScopeProvider or if the key doesn't exist.
|
|
92
160
|
*
|
|
93
|
-
*
|
|
94
|
-
*
|
|
161
|
+
* @example
|
|
162
|
+
* ```tsx
|
|
163
|
+
* // In parent component:
|
|
164
|
+
* <ScopeProvider metadata={{ userId: '123', theme: 'dark' }}>
|
|
165
|
+
* <ChildComponent />
|
|
166
|
+
* </ScopeProvider>
|
|
95
167
|
*
|
|
96
|
-
*
|
|
168
|
+
* // In child component:
|
|
169
|
+
* function ChildComponent() {
|
|
170
|
+
* const userId = useScopeMetadata<string>('userId')
|
|
171
|
+
* const theme = useScopeMetadata<'light' | 'dark'>('theme')
|
|
172
|
+
* // ...
|
|
173
|
+
* }
|
|
174
|
+
* ```
|
|
97
175
|
*/
|
|
98
|
-
function
|
|
99
|
-
|
|
100
|
-
if (!container) throw new Error("useRootContainer must be used within a ContainerProvider");
|
|
101
|
-
return container;
|
|
176
|
+
function useScopeMetadata(key) {
|
|
177
|
+
return useContext(ScopedContainerContext)?.getMetadata(key);
|
|
102
178
|
}
|
|
103
|
-
|
|
104
|
-
|
|
105
|
-
|
|
179
|
+
// src/service/args-key.mts
|
|
180
|
+
let nextId = 0;
|
|
181
|
+
const objectIds = /* @__PURE__ */ new WeakMap();
|
|
182
|
+
/** What the container compares by value, and JSON would leave out. */
|
|
183
|
+
function replacer(_key, value) {
|
|
184
|
+
if (typeof value === "bigint" || value instanceof RegExp) return { [typeof value]: String(value) };
|
|
185
|
+
if (value instanceof Map || value instanceof Set) return { [value.constructor.name]: Array.from(value) };
|
|
186
|
+
return value;
|
|
187
|
+
}
|
|
188
|
+
/**
|
|
189
|
+
* Key that identifies the args of a hook call. Args that serialize to the same
|
|
190
|
+
* JSON share a key, so an object literal written in the call, or a function in
|
|
191
|
+
* it, does not count as a change on every render.
|
|
192
|
+
*
|
|
193
|
+
* Args JSON cannot serialize, which contain themselves, are keyed by identity.
|
|
194
|
+
*/
|
|
195
|
+
function getArgsKey(args) {
|
|
196
|
+
try {
|
|
197
|
+
return JSON.stringify(args, replacer) ?? "";
|
|
198
|
+
} catch {
|
|
199
|
+
const object = args;
|
|
200
|
+
let id = objectIds.get(object);
|
|
201
|
+
if (id === void 0) {
|
|
202
|
+
id = ++nextId;
|
|
203
|
+
objectIds.set(object, id);
|
|
204
|
+
}
|
|
205
|
+
return `#${id}`;
|
|
206
|
+
}
|
|
207
|
+
}
|
|
208
|
+
// src/service/use-service.mts
|
|
106
209
|
function serviceReducer(state, action) {
|
|
107
210
|
switch (action.type) {
|
|
108
211
|
case "loading": return { status: "loading" };
|
|
@@ -120,53 +223,46 @@ function serviceReducer(state, action) {
|
|
|
120
223
|
}
|
|
121
224
|
function useService(token, args) {
|
|
122
225
|
const container = useContainer();
|
|
123
|
-
const
|
|
124
|
-
const
|
|
125
|
-
const
|
|
126
|
-
if (
|
|
127
|
-
|
|
128
|
-
|
|
226
|
+
const argsKey = getArgsKey(args);
|
|
227
|
+
const stableArgs = useMemo(() => args, [argsKey]);
|
|
228
|
+
const initialSyncRef = useRef(void 0);
|
|
229
|
+
if (initialSyncRef.current === void 0) {
|
|
230
|
+
const instance = container.peek(token, args);
|
|
231
|
+
initialSyncRef.current = instance === null ? null : {
|
|
232
|
+
container,
|
|
233
|
+
token,
|
|
234
|
+
argsKey,
|
|
235
|
+
instance
|
|
236
|
+
};
|
|
129
237
|
}
|
|
130
|
-
const
|
|
238
|
+
const initialState = initialSyncRef.current !== null ? {
|
|
131
239
|
status: "success",
|
|
132
|
-
data:
|
|
133
|
-
} : { status: "idle" }
|
|
134
|
-
const
|
|
240
|
+
data: initialSyncRef.current.instance
|
|
241
|
+
} : { status: "idle" };
|
|
242
|
+
const [state, dispatch] = useReducer(serviceReducer, initialState);
|
|
135
243
|
const [refetchCounter, setRefetchCounter] = useState(0);
|
|
136
|
-
{
|
|
137
|
-
const argsRef = useRef(args);
|
|
138
|
-
useEffect(() => {
|
|
139
|
-
if (argsRef.current !== args) {
|
|
140
|
-
if (JSON.stringify(argsRef.current) === JSON.stringify(args)) console.warn(`useService called with args that look the same but are different instances: ${JSON.stringify(argsRef.current)} !== ${JSON.stringify(args)}!
|
|
141
|
-
This is likely because you are using a value that is not memoized.
|
|
142
|
-
Please use a memoized value or use a different approach to pass the args.
|
|
143
|
-
Example:
|
|
144
|
-
const args = useMemo(() => ({ userId: '123' }), [])
|
|
145
|
-
return useService(UserToken, args)`);
|
|
146
|
-
argsRef.current = args;
|
|
147
|
-
}
|
|
148
|
-
}, [args]);
|
|
149
|
-
}
|
|
150
244
|
useEffect(() => {
|
|
151
|
-
const eventBus = rootContainer.getEventBus();
|
|
152
245
|
let unsubscribe;
|
|
153
246
|
let isMounted = true;
|
|
247
|
+
const subscribe = () => {
|
|
248
|
+
if (unsubscribe) return;
|
|
249
|
+
unsubscribe = container.onInvalidate(token, stableArgs, () => {
|
|
250
|
+
if (!isMounted) return;
|
|
251
|
+
dispatch({ type: "loading" });
|
|
252
|
+
queueMicrotask(() => {
|
|
253
|
+
if (isMounted) fetchAndSubscribe();
|
|
254
|
+
});
|
|
255
|
+
});
|
|
256
|
+
};
|
|
154
257
|
const fetchAndSubscribe = async () => {
|
|
155
258
|
try {
|
|
156
|
-
const instance = await container.get(token,
|
|
259
|
+
const instance = await container.get(token, stableArgs);
|
|
157
260
|
if (!isMounted) return;
|
|
158
|
-
const instanceName = container.calculateInstanceName(token, args);
|
|
159
|
-
if (instanceName) instanceNameRef.current = instanceName;
|
|
160
261
|
dispatch({
|
|
161
262
|
type: "success",
|
|
162
263
|
data: instance
|
|
163
264
|
});
|
|
164
|
-
|
|
165
|
-
if (isMounted) {
|
|
166
|
-
dispatch({ type: "loading" });
|
|
167
|
-
fetchAndSubscribe();
|
|
168
|
-
}
|
|
169
|
-
});
|
|
265
|
+
subscribe();
|
|
170
266
|
} catch (error) {
|
|
171
267
|
if (isMounted) dispatch({
|
|
172
268
|
type: "error",
|
|
@@ -174,18 +270,10 @@ Example:
|
|
|
174
270
|
});
|
|
175
271
|
}
|
|
176
272
|
};
|
|
177
|
-
|
|
178
|
-
|
|
179
|
-
|
|
180
|
-
|
|
181
|
-
unsubscribe = eventBus.on(instanceName, "destroy", () => {
|
|
182
|
-
if (isMounted) {
|
|
183
|
-
dispatch({ type: "loading" });
|
|
184
|
-
fetchAndSubscribe();
|
|
185
|
-
}
|
|
186
|
-
});
|
|
187
|
-
}
|
|
188
|
-
} else {
|
|
273
|
+
const initial = initialSyncRef.current;
|
|
274
|
+
if (initial != null && initial.container === container && initial.token === token && initial.argsKey === argsKey && refetchCounter === 0) subscribe();
|
|
275
|
+
else {
|
|
276
|
+
initialSyncRef.current = null;
|
|
189
277
|
dispatch({ type: "loading" });
|
|
190
278
|
fetchAndSubscribe();
|
|
191
279
|
}
|
|
@@ -195,9 +283,9 @@ Example:
|
|
|
195
283
|
};
|
|
196
284
|
}, [
|
|
197
285
|
container,
|
|
198
|
-
rootContainer,
|
|
199
286
|
token,
|
|
200
|
-
|
|
287
|
+
stableArgs,
|
|
288
|
+
argsKey,
|
|
201
289
|
refetchCounter
|
|
202
290
|
]);
|
|
203
291
|
const refetch = useCallback(() => {
|
|
@@ -212,18 +300,18 @@ Example:
|
|
|
212
300
|
refetch
|
|
213
301
|
};
|
|
214
302
|
}
|
|
215
|
-
|
|
216
|
-
//#endregion
|
|
217
|
-
//#region src/hooks/use-suspense-service.mts
|
|
303
|
+
// src/service/use-suspense-service.mts
|
|
218
304
|
const cacheMap = /* @__PURE__ */ new WeakMap();
|
|
219
|
-
function
|
|
220
|
-
|
|
221
|
-
|
|
222
|
-
|
|
223
|
-
|
|
305
|
+
function getCache(container, token) {
|
|
306
|
+
let byToken = cacheMap.get(container);
|
|
307
|
+
if (!byToken) {
|
|
308
|
+
byToken = /* @__PURE__ */ new WeakMap();
|
|
309
|
+
cacheMap.set(container, byToken);
|
|
310
|
+
}
|
|
311
|
+
let cache = byToken.get(token);
|
|
224
312
|
if (!cache) {
|
|
225
313
|
cache = /* @__PURE__ */ new Map();
|
|
226
|
-
|
|
314
|
+
byToken.set(token, cache);
|
|
227
315
|
}
|
|
228
316
|
return cache;
|
|
229
317
|
}
|
|
@@ -231,9 +319,9 @@ function getCache(container) {
|
|
|
231
319
|
* Sets up invalidation subscription for a cache entry if not already subscribed.
|
|
232
320
|
* When the service is destroyed, clears the cache and notifies subscribers.
|
|
233
321
|
*/
|
|
234
|
-
function setupInvalidationSubscription(entry,
|
|
235
|
-
if (entry.unsubscribe
|
|
236
|
-
entry.unsubscribe =
|
|
322
|
+
function setupInvalidationSubscription(entry, container, token, args) {
|
|
323
|
+
if (entry.unsubscribe) return;
|
|
324
|
+
entry.unsubscribe = container.onInvalidate(token, args, () => {
|
|
237
325
|
entry.result = void 0;
|
|
238
326
|
entry.error = void 0;
|
|
239
327
|
entry.status = "pending";
|
|
@@ -243,38 +331,21 @@ function setupInvalidationSubscription(entry, rootContainer) {
|
|
|
243
331
|
}
|
|
244
332
|
function useSuspenseService(token, args) {
|
|
245
333
|
const container = useContainer();
|
|
246
|
-
const
|
|
247
|
-
const
|
|
248
|
-
const cacheKey = getCacheKey(token, args);
|
|
334
|
+
const cache = getCache(container, token);
|
|
335
|
+
const cacheKey = getArgsKey(args);
|
|
249
336
|
const entryRef = useRef(null);
|
|
250
|
-
{
|
|
251
|
-
const argsRef = useRef(args);
|
|
252
|
-
useEffect(() => {
|
|
253
|
-
if (argsRef.current !== args) {
|
|
254
|
-
if (JSON.stringify(argsRef.current) === JSON.stringify(args)) console.warn(`useSuspenseService called with args that look the same but are different instances: ${JSON.stringify(argsRef.current)} !== ${JSON.stringify(args)}!
|
|
255
|
-
This is likely because you are using a value that is not memoized.
|
|
256
|
-
Please use a memoized value or use a different approach to pass the args.
|
|
257
|
-
Example:
|
|
258
|
-
const args = useMemo(() => ({ userId: '123' }), [])
|
|
259
|
-
return useSuspenseService(UserToken, args)`);
|
|
260
|
-
argsRef.current = args;
|
|
261
|
-
}
|
|
262
|
-
}, [args]);
|
|
263
|
-
}
|
|
264
337
|
if (!cache.has(cacheKey)) {
|
|
265
|
-
const syncInstance = container.
|
|
266
|
-
const
|
|
267
|
-
const entry$1 = {
|
|
338
|
+
const syncInstance = container.peek(token, args);
|
|
339
|
+
const entry = {
|
|
268
340
|
promise: null,
|
|
269
|
-
result: syncInstance
|
|
341
|
+
result: syncInstance !== null ? syncInstance : void 0,
|
|
270
342
|
error: void 0,
|
|
271
|
-
status: syncInstance ? "resolved" : "pending",
|
|
343
|
+
status: syncInstance !== null ? "resolved" : "pending",
|
|
272
344
|
version: 0,
|
|
273
345
|
subscribers: /* @__PURE__ */ new Set(),
|
|
274
|
-
instanceName,
|
|
275
346
|
unsubscribe: void 0
|
|
276
347
|
};
|
|
277
|
-
cache.set(cacheKey, entry
|
|
348
|
+
cache.set(cacheKey, entry);
|
|
278
349
|
}
|
|
279
350
|
const entry = cache.get(cacheKey);
|
|
280
351
|
entryRef.current = entry;
|
|
@@ -286,7 +357,7 @@ Example:
|
|
|
286
357
|
currentEntry.promise = container.get(token, args).then((instance) => {
|
|
287
358
|
currentEntry.result = instance;
|
|
288
359
|
currentEntry.status = "resolved";
|
|
289
|
-
setupInvalidationSubscription(currentEntry,
|
|
360
|
+
setupInvalidationSubscription(currentEntry, container, token, args);
|
|
290
361
|
currentEntry.subscribers.forEach((callback) => callback());
|
|
291
362
|
return instance;
|
|
292
363
|
}).catch((error) => {
|
|
@@ -297,7 +368,6 @@ Example:
|
|
|
297
368
|
return currentEntry.promise;
|
|
298
369
|
}, [
|
|
299
370
|
container,
|
|
300
|
-
rootContainer,
|
|
301
371
|
token,
|
|
302
372
|
args
|
|
303
373
|
]);
|
|
@@ -313,16 +383,19 @@ Example:
|
|
|
313
383
|
useSyncExternalStore(subscribe, getSnapshot, getSnapshot);
|
|
314
384
|
useEffect(() => {
|
|
315
385
|
const currentEntry = entryRef.current;
|
|
316
|
-
if (currentEntry && currentEntry.status === "resolved" &&
|
|
317
|
-
}, [
|
|
386
|
+
if (currentEntry && currentEntry.status === "resolved" && !currentEntry.unsubscribe) setupInvalidationSubscription(currentEntry, container, token, args);
|
|
387
|
+
}, [
|
|
388
|
+
container,
|
|
389
|
+
token,
|
|
390
|
+
args,
|
|
391
|
+
entry
|
|
392
|
+
]);
|
|
318
393
|
if (entry.status === "pending" && !entry.promise) fetchService();
|
|
319
394
|
if (entry.status === "pending") throw entry.promise;
|
|
320
395
|
if (entry.status === "rejected") throw entry.error;
|
|
321
396
|
return entry.result;
|
|
322
397
|
}
|
|
323
|
-
|
|
324
|
-
//#endregion
|
|
325
|
-
//#region src/hooks/use-optional-service.mts
|
|
398
|
+
// src/service/use-optional-service.mts
|
|
326
399
|
function optionalServiceReducer(state, action) {
|
|
327
400
|
switch (action.type) {
|
|
328
401
|
case "loading": return { status: "loading" };
|
|
@@ -366,87 +439,78 @@ function optionalServiceReducer(state, action) {
|
|
|
366
439
|
*/
|
|
367
440
|
function useOptionalService(token, args) {
|
|
368
441
|
const container = useContainer();
|
|
369
|
-
const
|
|
370
|
-
const
|
|
371
|
-
const
|
|
372
|
-
if (
|
|
442
|
+
const argsKey = getArgsKey(args);
|
|
443
|
+
const stableArgs = useMemo(() => args, [argsKey]);
|
|
444
|
+
const initialSyncRef = useRef(void 0);
|
|
445
|
+
if (initialSyncRef.current === void 0) {
|
|
446
|
+
let instance = null;
|
|
373
447
|
try {
|
|
374
|
-
|
|
448
|
+
instance = container.peek(token, args);
|
|
375
449
|
} catch {}
|
|
376
|
-
|
|
450
|
+
initialSyncRef.current = instance === null ? null : {
|
|
451
|
+
container,
|
|
452
|
+
token,
|
|
453
|
+
argsKey,
|
|
454
|
+
instance
|
|
455
|
+
};
|
|
377
456
|
}
|
|
378
|
-
const
|
|
457
|
+
const initialState = initialSyncRef.current !== null ? {
|
|
379
458
|
status: "success",
|
|
380
|
-
data:
|
|
381
|
-
} : { status: "idle" }
|
|
382
|
-
const
|
|
383
|
-
{
|
|
384
|
-
const argsRef = useRef(args);
|
|
385
|
-
useEffect(() => {
|
|
386
|
-
if (argsRef.current !== args) {
|
|
387
|
-
if (JSON.stringify(argsRef.current) === JSON.stringify(args)) console.warn(`useOptionalService called with args that look the same but are different instances: ${JSON.stringify(argsRef.current)} !== ${JSON.stringify(args)}!
|
|
388
|
-
This is likely because you are using a value that is not memoized.
|
|
389
|
-
Please use a memoized value or use a different approach to pass the args.
|
|
390
|
-
Example:
|
|
391
|
-
const args = useMemo(() => ({ userId: '123' }), [])
|
|
392
|
-
return useOptionalService(UserToken, args)`);
|
|
393
|
-
argsRef.current = args;
|
|
394
|
-
}
|
|
395
|
-
}, [args]);
|
|
396
|
-
}
|
|
459
|
+
data: initialSyncRef.current.instance
|
|
460
|
+
} : { status: "idle" };
|
|
461
|
+
const [state, dispatch] = useReducer(optionalServiceReducer, initialState);
|
|
397
462
|
const fetchService = useCallback(async () => {
|
|
398
463
|
dispatch({ type: "loading" });
|
|
399
464
|
try {
|
|
400
|
-
const instance = await container.get(token,
|
|
401
|
-
const instanceName = container.calculateInstanceName(token, args);
|
|
402
|
-
if (instanceName) instanceNameRef.current = instanceName;
|
|
465
|
+
const instance = await container.get(token, stableArgs);
|
|
403
466
|
dispatch({
|
|
404
467
|
type: "success",
|
|
405
468
|
data: instance
|
|
406
469
|
});
|
|
470
|
+
return true;
|
|
407
471
|
} catch (error) {
|
|
408
|
-
|
|
409
|
-
const errorMessage = err.message?.toLowerCase() ?? "";
|
|
410
|
-
if (errorMessage.includes("not found") || errorMessage.includes("not registered") || errorMessage.includes("no provider")) dispatch({ type: "not-found" });
|
|
472
|
+
if (error instanceof DIError && error.code === DIErrorCode.ProviderNotFound && !container.isRegistered(token)) dispatch({ type: "not-found" });
|
|
411
473
|
else dispatch({
|
|
412
474
|
type: "error",
|
|
413
|
-
error
|
|
475
|
+
error
|
|
414
476
|
});
|
|
477
|
+
return false;
|
|
415
478
|
}
|
|
416
479
|
}, [
|
|
417
480
|
container,
|
|
418
481
|
token,
|
|
419
|
-
|
|
482
|
+
stableArgs
|
|
420
483
|
]);
|
|
421
484
|
useEffect(() => {
|
|
422
|
-
const eventBus = rootContainer.getEventBus();
|
|
423
485
|
let unsubscribe;
|
|
424
|
-
|
|
425
|
-
|
|
426
|
-
if (
|
|
427
|
-
|
|
428
|
-
|
|
429
|
-
|
|
430
|
-
|
|
431
|
-
}
|
|
432
|
-
} else {
|
|
433
|
-
fetchService().then(() => {
|
|
434
|
-
if (instanceNameRef.current) unsubscribe = eventBus.on(instanceNameRef.current, "destroy", () => {
|
|
435
|
-
fetchService();
|
|
486
|
+
let isMounted = true;
|
|
487
|
+
const subscribe = () => {
|
|
488
|
+
if (unsubscribe || !isMounted) return;
|
|
489
|
+
unsubscribe = container.onInvalidate(token, stableArgs, () => {
|
|
490
|
+
dispatch({ type: "loading" });
|
|
491
|
+
queueMicrotask(() => {
|
|
492
|
+
if (isMounted) fetchService();
|
|
436
493
|
});
|
|
437
494
|
});
|
|
438
|
-
|
|
439
|
-
|
|
440
|
-
|
|
495
|
+
};
|
|
496
|
+
const initial = initialSyncRef.current;
|
|
497
|
+
if (initial != null && initial.container === container && initial.token === token && initial.argsKey === argsKey) subscribe();
|
|
498
|
+
else {
|
|
499
|
+
initialSyncRef.current = null;
|
|
500
|
+
fetchService().then((loaded) => {
|
|
501
|
+
if (loaded) subscribe();
|
|
502
|
+
});
|
|
441
503
|
}
|
|
442
504
|
return () => {
|
|
505
|
+
isMounted = false;
|
|
443
506
|
unsubscribe?.();
|
|
444
507
|
};
|
|
445
508
|
}, [
|
|
446
509
|
fetchService,
|
|
447
|
-
|
|
510
|
+
container,
|
|
448
511
|
token,
|
|
449
|
-
|
|
512
|
+
stableArgs,
|
|
513
|
+
argsKey
|
|
450
514
|
]);
|
|
451
515
|
return {
|
|
452
516
|
data: state.status === "success" ? state.data : void 0,
|
|
@@ -458,9 +522,7 @@ Example:
|
|
|
458
522
|
refetch: fetchService
|
|
459
523
|
};
|
|
460
524
|
}
|
|
461
|
-
|
|
462
|
-
//#endregion
|
|
463
|
-
//#region src/hooks/use-invalidate.mts
|
|
525
|
+
// src/service/use-invalidate-instance.mts
|
|
464
526
|
/**
|
|
465
527
|
* Hook that returns a function to invalidate a service instance directly.
|
|
466
528
|
*
|
|
@@ -494,75 +556,6 @@ function useInvalidateInstance() {
|
|
|
494
556
|
await container.invalidate(instance);
|
|
495
557
|
}, [container]);
|
|
496
558
|
}
|
|
497
|
-
|
|
498
|
-
//#endregion
|
|
499
|
-
//#region src/hooks/use-scope.mts
|
|
500
|
-
/**
|
|
501
|
-
* Hook to get the current scope ID.
|
|
502
|
-
* Returns null if not inside a ScopeProvider.
|
|
503
|
-
*/
|
|
504
|
-
function useScope() {
|
|
505
|
-
return useContext(ScopedContainerContext)?.getRequestId() ?? null;
|
|
506
|
-
}
|
|
507
|
-
/**
|
|
508
|
-
* Hook to get the current scope ID, throwing if not inside a ScopeProvider.
|
|
509
|
-
* Use this when your component requires a scope to function correctly.
|
|
510
|
-
*/
|
|
511
|
-
function useScopeOrThrow() {
|
|
512
|
-
const scopeId = useScope();
|
|
513
|
-
if (scopeId === null) throw new Error("useScopeOrThrow must be used within a ScopeProvider. Wrap your component tree with <ScopeProvider> to create a request scope.");
|
|
514
|
-
return scopeId;
|
|
515
|
-
}
|
|
516
|
-
/**
|
|
517
|
-
* Hook to get the current ScopedContainer.
|
|
518
|
-
* Returns null if not inside a ScopeProvider.
|
|
519
|
-
*
|
|
520
|
-
* Use this to access scope metadata or other ScopedContainer methods.
|
|
521
|
-
*
|
|
522
|
-
* @example
|
|
523
|
-
* ```tsx
|
|
524
|
-
* function TableRow() {
|
|
525
|
-
* const scope = useScopedContainer()
|
|
526
|
-
* const rowData = scope?.getMetadata('rowData')
|
|
527
|
-
* // ...
|
|
528
|
-
* }
|
|
529
|
-
* ```
|
|
530
|
-
*/
|
|
531
|
-
function useScopedContainer() {
|
|
532
|
-
return useContext(ScopedContainerContext);
|
|
533
|
-
}
|
|
534
|
-
/**
|
|
535
|
-
* Hook to get the current ScopedContainer, throwing if not inside a ScopeProvider.
|
|
536
|
-
* Use this when your component requires a scope to function correctly.
|
|
537
|
-
*/
|
|
538
|
-
function useScopedContainerOrThrow() {
|
|
539
|
-
const scopedContainer = useScopedContainer();
|
|
540
|
-
if (scopedContainer === null) throw new Error("useScopedContainerOrThrow must be used within a ScopeProvider. Wrap your component tree with <ScopeProvider> to create a request scope.");
|
|
541
|
-
return scopedContainer;
|
|
542
|
-
}
|
|
543
|
-
/**
|
|
544
|
-
* Hook to get metadata from the current scope.
|
|
545
|
-
* Returns undefined if not inside a ScopeProvider or if the key doesn't exist.
|
|
546
|
-
*
|
|
547
|
-
* @example
|
|
548
|
-
* ```tsx
|
|
549
|
-
* // In parent component:
|
|
550
|
-
* <ScopeProvider metadata={{ userId: '123', theme: 'dark' }}>
|
|
551
|
-
* <ChildComponent />
|
|
552
|
-
* </ScopeProvider>
|
|
553
|
-
*
|
|
554
|
-
* // In child component:
|
|
555
|
-
* function ChildComponent() {
|
|
556
|
-
* const userId = useScopeMetadata<string>('userId')
|
|
557
|
-
* const theme = useScopeMetadata<'light' | 'dark'>('theme')
|
|
558
|
-
* // ...
|
|
559
|
-
* }
|
|
560
|
-
* ```
|
|
561
|
-
*/
|
|
562
|
-
function useScopeMetadata(key) {
|
|
563
|
-
return useContext(ScopedContainerContext)?.getMetadata(key);
|
|
564
|
-
}
|
|
565
|
-
|
|
566
|
-
//#endregion
|
|
567
559
|
export { ContainerContext, ContainerProvider, ScopeProvider, ScopedContainerContext, useContainer, useInvalidateInstance, useOptionalService, useRootContainer, useScope, useScopeMetadata, useScopeOrThrow, useScopedContainer, useScopedContainerOrThrow, useService, useSuspenseService };
|
|
560
|
+
|
|
568
561
|
//# sourceMappingURL=index.mjs.map
|