@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
|
@@ -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,53 +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.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
245
|
(0, react.useEffect)(() => {
|
|
151
|
-
const eventBus = rootContainer.getEventBus();
|
|
152
246
|
let unsubscribe;
|
|
153
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
|
+
};
|
|
154
258
|
const fetchAndSubscribe = async () => {
|
|
155
259
|
try {
|
|
156
|
-
const instance = await container.get(token,
|
|
260
|
+
const instance = await container.get(token, stableArgs);
|
|
157
261
|
if (!isMounted) return;
|
|
158
|
-
const instanceName = container.calculateInstanceName(token, args);
|
|
159
|
-
if (instanceName) instanceNameRef.current = instanceName;
|
|
160
262
|
dispatch({
|
|
161
263
|
type: "success",
|
|
162
264
|
data: instance
|
|
163
265
|
});
|
|
164
|
-
|
|
165
|
-
if (isMounted) {
|
|
166
|
-
dispatch({ type: "loading" });
|
|
167
|
-
fetchAndSubscribe();
|
|
168
|
-
}
|
|
169
|
-
});
|
|
266
|
+
subscribe();
|
|
170
267
|
} catch (error) {
|
|
171
268
|
if (isMounted) dispatch({
|
|
172
269
|
type: "error",
|
|
@@ -174,18 +271,10 @@ Example:
|
|
|
174
271
|
});
|
|
175
272
|
}
|
|
176
273
|
};
|
|
177
|
-
|
|
178
|
-
|
|
179
|
-
|
|
180
|
-
|
|
181
|
-
unsubscribe = eventBus.on(instanceName, "destroy", () => {
|
|
182
|
-
if (isMounted) {
|
|
183
|
-
dispatch({ type: "loading" });
|
|
184
|
-
fetchAndSubscribe();
|
|
185
|
-
}
|
|
186
|
-
});
|
|
187
|
-
}
|
|
188
|
-
} 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;
|
|
189
278
|
dispatch({ type: "loading" });
|
|
190
279
|
fetchAndSubscribe();
|
|
191
280
|
}
|
|
@@ -195,9 +284,9 @@ Example:
|
|
|
195
284
|
};
|
|
196
285
|
}, [
|
|
197
286
|
container,
|
|
198
|
-
rootContainer,
|
|
199
287
|
token,
|
|
200
|
-
|
|
288
|
+
stableArgs,
|
|
289
|
+
argsKey,
|
|
201
290
|
refetchCounter
|
|
202
291
|
]);
|
|
203
292
|
const refetch = (0, react.useCallback)(() => {
|
|
@@ -212,18 +301,18 @@ Example:
|
|
|
212
301
|
refetch
|
|
213
302
|
};
|
|
214
303
|
}
|
|
215
|
-
|
|
216
|
-
//#endregion
|
|
217
|
-
//#region src/hooks/use-suspense-service.mts
|
|
304
|
+
// src/service/use-suspense-service.mts
|
|
218
305
|
const cacheMap = /* @__PURE__ */ new WeakMap();
|
|
219
|
-
function
|
|
220
|
-
|
|
221
|
-
|
|
222
|
-
|
|
223
|
-
|
|
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);
|
|
224
313
|
if (!cache) {
|
|
225
314
|
cache = /* @__PURE__ */ new Map();
|
|
226
|
-
|
|
315
|
+
byToken.set(token, cache);
|
|
227
316
|
}
|
|
228
317
|
return cache;
|
|
229
318
|
}
|
|
@@ -231,9 +320,9 @@ function getCache(container) {
|
|
|
231
320
|
* Sets up invalidation subscription for a cache entry if not already subscribed.
|
|
232
321
|
* When the service is destroyed, clears the cache and notifies subscribers.
|
|
233
322
|
*/
|
|
234
|
-
function setupInvalidationSubscription(entry,
|
|
235
|
-
if (entry.unsubscribe
|
|
236
|
-
entry.unsubscribe =
|
|
323
|
+
function setupInvalidationSubscription(entry, container, token, args) {
|
|
324
|
+
if (entry.unsubscribe) return;
|
|
325
|
+
entry.unsubscribe = container.onInvalidate(token, args, () => {
|
|
237
326
|
entry.result = void 0;
|
|
238
327
|
entry.error = void 0;
|
|
239
328
|
entry.status = "pending";
|
|
@@ -243,38 +332,21 @@ function setupInvalidationSubscription(entry, rootContainer) {
|
|
|
243
332
|
}
|
|
244
333
|
function useSuspenseService(token, args) {
|
|
245
334
|
const container = useContainer();
|
|
246
|
-
const
|
|
247
|
-
const
|
|
248
|
-
const cacheKey = getCacheKey(token, args);
|
|
335
|
+
const cache = getCache(container, token);
|
|
336
|
+
const cacheKey = getArgsKey(args);
|
|
249
337
|
const entryRef = (0, react.useRef)(null);
|
|
250
|
-
if (process.env.NODE_ENV === "development") {
|
|
251
|
-
const argsRef = (0, react.useRef)(args);
|
|
252
|
-
(0, react.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
338
|
if (!cache.has(cacheKey)) {
|
|
265
|
-
const syncInstance = container.
|
|
266
|
-
const
|
|
267
|
-
const entry$1 = {
|
|
339
|
+
const syncInstance = container.peek(token, args);
|
|
340
|
+
const entry = {
|
|
268
341
|
promise: null,
|
|
269
|
-
result: syncInstance
|
|
342
|
+
result: syncInstance !== null ? syncInstance : void 0,
|
|
270
343
|
error: void 0,
|
|
271
|
-
status: syncInstance ? "resolved" : "pending",
|
|
344
|
+
status: syncInstance !== null ? "resolved" : "pending",
|
|
272
345
|
version: 0,
|
|
273
346
|
subscribers: /* @__PURE__ */ new Set(),
|
|
274
|
-
instanceName,
|
|
275
347
|
unsubscribe: void 0
|
|
276
348
|
};
|
|
277
|
-
cache.set(cacheKey, entry
|
|
349
|
+
cache.set(cacheKey, entry);
|
|
278
350
|
}
|
|
279
351
|
const entry = cache.get(cacheKey);
|
|
280
352
|
entryRef.current = entry;
|
|
@@ -286,7 +358,7 @@ Example:
|
|
|
286
358
|
currentEntry.promise = container.get(token, args).then((instance) => {
|
|
287
359
|
currentEntry.result = instance;
|
|
288
360
|
currentEntry.status = "resolved";
|
|
289
|
-
setupInvalidationSubscription(currentEntry,
|
|
361
|
+
setupInvalidationSubscription(currentEntry, container, token, args);
|
|
290
362
|
currentEntry.subscribers.forEach((callback) => callback());
|
|
291
363
|
return instance;
|
|
292
364
|
}).catch((error) => {
|
|
@@ -297,7 +369,6 @@ Example:
|
|
|
297
369
|
return currentEntry.promise;
|
|
298
370
|
}, [
|
|
299
371
|
container,
|
|
300
|
-
rootContainer,
|
|
301
372
|
token,
|
|
302
373
|
args
|
|
303
374
|
]);
|
|
@@ -313,16 +384,19 @@ Example:
|
|
|
313
384
|
(0, react.useSyncExternalStore)(subscribe, getSnapshot, getSnapshot);
|
|
314
385
|
(0, react.useEffect)(() => {
|
|
315
386
|
const currentEntry = entryRef.current;
|
|
316
|
-
if (currentEntry && currentEntry.status === "resolved" &&
|
|
317
|
-
}, [
|
|
387
|
+
if (currentEntry && currentEntry.status === "resolved" && !currentEntry.unsubscribe) setupInvalidationSubscription(currentEntry, container, token, args);
|
|
388
|
+
}, [
|
|
389
|
+
container,
|
|
390
|
+
token,
|
|
391
|
+
args,
|
|
392
|
+
entry
|
|
393
|
+
]);
|
|
318
394
|
if (entry.status === "pending" && !entry.promise) fetchService();
|
|
319
395
|
if (entry.status === "pending") throw entry.promise;
|
|
320
396
|
if (entry.status === "rejected") throw entry.error;
|
|
321
397
|
return entry.result;
|
|
322
398
|
}
|
|
323
|
-
|
|
324
|
-
//#endregion
|
|
325
|
-
//#region src/hooks/use-optional-service.mts
|
|
399
|
+
// src/service/use-optional-service.mts
|
|
326
400
|
function optionalServiceReducer(state, action) {
|
|
327
401
|
switch (action.type) {
|
|
328
402
|
case "loading": return { status: "loading" };
|
|
@@ -366,87 +440,78 @@ function optionalServiceReducer(state, action) {
|
|
|
366
440
|
*/
|
|
367
441
|
function useOptionalService(token, args) {
|
|
368
442
|
const container = useContainer();
|
|
369
|
-
const
|
|
370
|
-
const
|
|
371
|
-
const
|
|
372
|
-
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;
|
|
373
448
|
try {
|
|
374
|
-
|
|
449
|
+
instance = container.peek(token, args);
|
|
375
450
|
} catch {}
|
|
376
|
-
|
|
451
|
+
initialSyncRef.current = instance === null ? null : {
|
|
452
|
+
container,
|
|
453
|
+
token,
|
|
454
|
+
argsKey,
|
|
455
|
+
instance
|
|
456
|
+
};
|
|
377
457
|
}
|
|
378
|
-
const
|
|
458
|
+
const initialState = initialSyncRef.current !== null ? {
|
|
379
459
|
status: "success",
|
|
380
|
-
data:
|
|
381
|
-
} : { status: "idle" }
|
|
382
|
-
const
|
|
383
|
-
if (process.env.NODE_ENV === "development") {
|
|
384
|
-
const argsRef = (0, react.useRef)(args);
|
|
385
|
-
(0, react.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
|
-
}
|
|
460
|
+
data: initialSyncRef.current.instance
|
|
461
|
+
} : { status: "idle" };
|
|
462
|
+
const [state, dispatch] = (0, react.useReducer)(optionalServiceReducer, initialState);
|
|
397
463
|
const fetchService = (0, react.useCallback)(async () => {
|
|
398
464
|
dispatch({ type: "loading" });
|
|
399
465
|
try {
|
|
400
|
-
const instance = await container.get(token,
|
|
401
|
-
const instanceName = container.calculateInstanceName(token, args);
|
|
402
|
-
if (instanceName) instanceNameRef.current = instanceName;
|
|
466
|
+
const instance = await container.get(token, stableArgs);
|
|
403
467
|
dispatch({
|
|
404
468
|
type: "success",
|
|
405
469
|
data: instance
|
|
406
470
|
});
|
|
471
|
+
return true;
|
|
407
472
|
} 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" });
|
|
473
|
+
if (error instanceof _navios_di.DIError && error.code === _navios_di.DIErrorCode.ProviderNotFound && !container.isRegistered(token)) dispatch({ type: "not-found" });
|
|
411
474
|
else dispatch({
|
|
412
475
|
type: "error",
|
|
413
|
-
error
|
|
476
|
+
error
|
|
414
477
|
});
|
|
478
|
+
return false;
|
|
415
479
|
}
|
|
416
480
|
}, [
|
|
417
481
|
container,
|
|
418
482
|
token,
|
|
419
|
-
|
|
483
|
+
stableArgs
|
|
420
484
|
]);
|
|
421
485
|
(0, react.useEffect)(() => {
|
|
422
|
-
const eventBus = rootContainer.getEventBus();
|
|
423
486
|
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();
|
|
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();
|
|
436
494
|
});
|
|
437
495
|
});
|
|
438
|
-
|
|
439
|
-
|
|
440
|
-
|
|
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
|
+
});
|
|
441
504
|
}
|
|
442
505
|
return () => {
|
|
506
|
+
isMounted = false;
|
|
443
507
|
unsubscribe?.();
|
|
444
508
|
};
|
|
445
509
|
}, [
|
|
446
510
|
fetchService,
|
|
447
|
-
|
|
511
|
+
container,
|
|
448
512
|
token,
|
|
449
|
-
|
|
513
|
+
stableArgs,
|
|
514
|
+
argsKey
|
|
450
515
|
]);
|
|
451
516
|
return {
|
|
452
517
|
data: state.status === "success" ? state.data : void 0,
|
|
@@ -458,9 +523,7 @@ Example:
|
|
|
458
523
|
refetch: fetchService
|
|
459
524
|
};
|
|
460
525
|
}
|
|
461
|
-
|
|
462
|
-
//#endregion
|
|
463
|
-
//#region src/hooks/use-invalidate.mts
|
|
526
|
+
// src/service/use-invalidate-instance.mts
|
|
464
527
|
/**
|
|
465
528
|
* Hook that returns a function to invalidate a service instance directly.
|
|
466
529
|
*
|
|
@@ -494,76 +557,6 @@ function useInvalidateInstance() {
|
|
|
494
557
|
await container.invalidate(instance);
|
|
495
558
|
}, [container]);
|
|
496
559
|
}
|
|
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 (0, react.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 (0, react.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 (0, react.useContext)(ScopedContainerContext)?.getMetadata(key);
|
|
564
|
-
}
|
|
565
|
-
|
|
566
|
-
//#endregion
|
|
567
560
|
exports.ContainerContext = ContainerContext;
|
|
568
561
|
exports.ContainerProvider = ContainerProvider;
|
|
569
562
|
exports.ScopeProvider = ScopeProvider;
|
|
@@ -579,4 +572,5 @@ exports.useScopedContainer = useScopedContainer;
|
|
|
579
572
|
exports.useScopedContainerOrThrow = useScopedContainerOrThrow;
|
|
580
573
|
exports.useService = useService;
|
|
581
574
|
exports.useSuspenseService = useSuspenseService;
|
|
582
|
-
|
|
575
|
+
|
|
576
|
+
//# sourceMappingURL=index.cjs.map
|