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