@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.
Files changed (58) hide show
  1. package/CHANGELOG.md +21 -0
  2. package/README.md +45 -665
  3. package/lib/{index.js → index.cjs} +249 -255
  4. package/lib/index.cjs.map +1 -0
  5. package/lib/{index.d.ts → index.d.cts} +94 -123
  6. package/lib/index.d.cts.map +1 -0
  7. package/lib/index.d.mts +93 -122
  8. package/lib/index.d.mts.map +1 -1
  9. package/lib/index.mjs +248 -255
  10. package/lib/index.mjs.map +1 -1
  11. package/package.json +32 -18
  12. package/coverage/base.css +0 -224
  13. package/coverage/block-navigation.js +0 -87
  14. package/coverage/clover.xml +0 -270
  15. package/coverage/coverage-final.json +0 -10
  16. package/coverage/favicon.png +0 -0
  17. package/coverage/hooks/index.html +0 -191
  18. package/coverage/hooks/use-container.mts.html +0 -268
  19. package/coverage/hooks/use-invalidate.mts.html +0 -208
  20. package/coverage/hooks/use-optional-service.mts.html +0 -910
  21. package/coverage/hooks/use-scope.mts.html +0 -346
  22. package/coverage/hooks/use-service.mts.html +0 -760
  23. package/coverage/hooks/use-suspense-service.mts.html +0 -784
  24. package/coverage/index.html +0 -131
  25. package/coverage/prettify.css +0 -1
  26. package/coverage/prettify.js +0 -2
  27. package/coverage/providers/container-provider.mts.html +0 -139
  28. package/coverage/providers/context.mts.html +0 -130
  29. package/coverage/providers/index.html +0 -146
  30. package/coverage/providers/scope-provider.mts.html +0 -355
  31. package/coverage/sort-arrow-sprite.png +0 -0
  32. package/coverage/sorter.js +0 -210
  33. package/lib/index.d.ts.map +0 -1
  34. package/lib/index.js.map +0 -1
  35. package/project.json +0 -61
  36. package/src/hooks/__tests__/use-container.spec.mts +0 -143
  37. package/src/hooks/__tests__/use-invalidate.spec.mts +0 -80
  38. package/src/hooks/__tests__/use-optional-service.spec.mts +0 -233
  39. package/src/hooks/__tests__/use-scope.spec.mts +0 -293
  40. package/src/hooks/__tests__/use-service.spec.mts +0 -212
  41. package/src/hooks/__tests__/use-suspense-service.spec.mts +0 -286
  42. package/src/hooks/index.mts +0 -14
  43. package/src/hooks/use-container.mts +0 -61
  44. package/src/hooks/use-invalidate.mts +0 -41
  45. package/src/hooks/use-optional-service.mts +0 -275
  46. package/src/hooks/use-scope.mts +0 -87
  47. package/src/hooks/use-service.mts +0 -225
  48. package/src/hooks/use-suspense-service.mts +0 -233
  49. package/src/index.mts +0 -8
  50. package/src/providers/__tests__/scope-provider.spec.mts +0 -366
  51. package/src/providers/container-provider.mts +0 -18
  52. package/src/providers/context.mts +0 -15
  53. package/src/providers/index.mts +0 -5
  54. package/src/providers/scope-provider.mts +0 -90
  55. package/src/types.mts +0 -21
  56. package/tsconfig.json +0 -13
  57. package/tsdown.config.mts +0 -14
  58. package/vitest.config.mts +0 -12
@@ -1,87 +0,0 @@
1
- import type { ScopedContainer } from '@navios/di'
2
-
3
- import { useContext } from 'react'
4
-
5
- import { ScopedContainerContext } from '../providers/context.mjs'
6
-
7
- /**
8
- * Hook to get the current scope ID.
9
- * Returns null if not inside a ScopeProvider.
10
- */
11
- export function useScope(): string | null {
12
- const scopedContainer = useContext(ScopedContainerContext)
13
- return scopedContainer?.getRequestId() ?? null
14
- }
15
-
16
- /**
17
- * Hook to get the current scope ID, throwing if not inside a ScopeProvider.
18
- * Use this when your component requires a scope to function correctly.
19
- */
20
- export function useScopeOrThrow(): string {
21
- const scopeId = useScope()
22
- if (scopeId === null) {
23
- throw new Error(
24
- 'useScopeOrThrow must be used within a ScopeProvider. ' +
25
- 'Wrap your component tree with <ScopeProvider> to create a request scope.',
26
- )
27
- }
28
- return scopeId
29
- }
30
-
31
- /**
32
- * Hook to get the current ScopedContainer.
33
- * Returns null if not inside a ScopeProvider.
34
- *
35
- * Use this to access scope metadata or other ScopedContainer methods.
36
- *
37
- * @example
38
- * ```tsx
39
- * function TableRow() {
40
- * const scope = useScopedContainer()
41
- * const rowData = scope?.getMetadata('rowData')
42
- * // ...
43
- * }
44
- * ```
45
- */
46
- export function useScopedContainer(): ScopedContainer | null {
47
- return useContext(ScopedContainerContext)
48
- }
49
-
50
- /**
51
- * Hook to get the current ScopedContainer, throwing if not inside a ScopeProvider.
52
- * Use this when your component requires a scope to function correctly.
53
- */
54
- export function useScopedContainerOrThrow(): ScopedContainer {
55
- const scopedContainer = useScopedContainer()
56
- if (scopedContainer === null) {
57
- throw new Error(
58
- 'useScopedContainerOrThrow must be used within a ScopeProvider. ' +
59
- 'Wrap your component tree with <ScopeProvider> to create a request scope.',
60
- )
61
- }
62
- return scopedContainer
63
- }
64
-
65
- /**
66
- * Hook to get metadata from the current scope.
67
- * Returns undefined if not inside a ScopeProvider or if the key doesn't exist.
68
- *
69
- * @example
70
- * ```tsx
71
- * // In parent component:
72
- * <ScopeProvider metadata={{ userId: '123', theme: 'dark' }}>
73
- * <ChildComponent />
74
- * </ScopeProvider>
75
- *
76
- * // In child component:
77
- * function ChildComponent() {
78
- * const userId = useScopeMetadata<string>('userId')
79
- * const theme = useScopeMetadata<'light' | 'dark'>('theme')
80
- * // ...
81
- * }
82
- * ```
83
- */
84
- export function useScopeMetadata<T = unknown>(key: string): T | undefined {
85
- const scopedContainer = useContext(ScopedContainerContext)
86
- return scopedContainer?.getMetadata(key) as T | undefined
87
- }
@@ -1,225 +0,0 @@
1
- import type {
2
- AnyInjectableType,
3
- BoundInjectionToken,
4
- ClassType,
5
- Factorable,
6
- FactoryInjectionToken,
7
- InjectionToken,
8
- InjectionTokenSchemaType,
9
- } from '@navios/di'
10
- import type { z, ZodType } from 'zod/v4'
11
-
12
- import { useCallback, useEffect, useReducer, useRef, useState } from 'react'
13
-
14
- import type { Join, UnionToArray } from '../types.mjs'
15
-
16
- import { useContainer, useRootContainer } from './use-container.mjs'
17
-
18
- type ServiceState<T> =
19
- | { status: 'idle' }
20
- | { status: 'loading' }
21
- | { status: 'success'; data: T }
22
- | { status: 'error'; error: Error }
23
-
24
- type ServiceAction<T> =
25
- | { type: 'loading' }
26
- | { type: 'success'; data: T }
27
- | { type: 'error'; error: Error }
28
- | { type: 'reset' }
29
-
30
- function serviceReducer<T>(
31
- state: ServiceState<T>,
32
- action: ServiceAction<T>,
33
- ): ServiceState<T> {
34
- switch (action.type) {
35
- case 'loading':
36
- return { status: 'loading' }
37
- case 'success':
38
- return { status: 'success', data: action.data }
39
- case 'error':
40
- return { status: 'error', error: action.error }
41
- case 'reset':
42
- return { status: 'idle' }
43
- default:
44
- return state
45
- }
46
- }
47
-
48
- export interface UseServiceResult<T> {
49
- data: T | undefined
50
- error: Error | undefined
51
- isLoading: boolean
52
- isSuccess: boolean
53
- isError: boolean
54
- refetch: () => void
55
- }
56
-
57
- // #1 Simple class
58
- export function useService<T extends ClassType>(
59
- token: T,
60
- ): UseServiceResult<
61
- InstanceType<T> extends Factorable<infer R> ? R : InstanceType<T>
62
- >
63
-
64
- // #2 Token with required Schema
65
- export function useService<T, S extends InjectionTokenSchemaType>(
66
- token: InjectionToken<T, S>,
67
- args: z.input<S>,
68
- ): UseServiceResult<T>
69
-
70
- // #3 Token with optional Schema
71
- export function useService<
72
- T,
73
- S extends InjectionTokenSchemaType,
74
- R extends boolean,
75
- >(
76
- token: InjectionToken<T, S, R>,
77
- ): R extends false
78
- ? UseServiceResult<T>
79
- : S extends ZodType<infer Type>
80
- ? `Error: Your token requires args: ${Join<UnionToArray<keyof Type>, ', '>}`
81
- : 'Error: Your token requires args'
82
-
83
- // #4 Token with no Schema
84
- export function useService<T>(
85
- token: InjectionToken<T, undefined>,
86
- ): UseServiceResult<T>
87
-
88
- export function useService<T>(
89
- token: BoundInjectionToken<T, any>,
90
- ): UseServiceResult<T>
91
-
92
- export function useService<T>(
93
- token: FactoryInjectionToken<T, any>,
94
- ): UseServiceResult<T>
95
-
96
- export function useService(
97
- token:
98
- | ClassType
99
- | InjectionToken<any, any>
100
- | BoundInjectionToken<any, any>
101
- | FactoryInjectionToken<any, any>,
102
- args?: unknown,
103
- ): UseServiceResult<any> {
104
- // useContainer returns ScopedContainer if inside ScopeProvider, otherwise Container
105
- // This automatically handles request-scoped services correctly
106
- const container = useContainer()
107
- const rootContainer = useRootContainer()
108
-
109
- // Try to get the instance synchronously first for better performance
110
- // This avoids the async loading state when the instance is already cached
111
- // We use a ref to track this so it doesn't cause effect re-runs
112
- const initialSyncInstanceRef = useRef<any>(undefined)
113
- const isFirstRenderRef = useRef(true)
114
-
115
- if (isFirstRenderRef.current) {
116
- initialSyncInstanceRef.current = container.tryGetSync(token, args)
117
- isFirstRenderRef.current = false
118
- }
119
-
120
- const initialState: ServiceState<any> = initialSyncInstanceRef.current
121
- ? { status: 'success', data: initialSyncInstanceRef.current }
122
- : { status: 'idle' }
123
-
124
- const [state, dispatch] = useReducer(serviceReducer, initialState)
125
- const instanceNameRef = useRef<string | null>(null)
126
- const [refetchCounter, setRefetchCounter] = useState(0)
127
-
128
- if (process.env.NODE_ENV === 'development') {
129
- const argsRef = useRef<unknown>(args)
130
- useEffect(() => {
131
- if (argsRef.current !== args) {
132
- if (JSON.stringify(argsRef.current) === JSON.stringify(args)) {
133
- console.warn(`useService called with args that look the same but are different instances: ${JSON.stringify(argsRef.current)} !== ${JSON.stringify(args)}!
134
- This is likely because you are using a value that is not memoized.
135
- Please use a memoized value or use a different approach to pass the args.
136
- Example:
137
- const args = useMemo(() => ({ userId: '123' }), [])
138
- return useService(UserToken, args)`)
139
- }
140
- argsRef.current = args
141
- }
142
- }, [args])
143
- }
144
-
145
- // Subscribe to invalidation events
146
- useEffect(() => {
147
- const eventBus = rootContainer.getEventBus()
148
- let unsubscribe: (() => void) | undefined
149
- let isMounted = true
150
-
151
- // Fetch the service and set up subscription
152
- const fetchAndSubscribe = async () => {
153
- try {
154
- // The container (either ScopedContainer or Container) handles resolution correctly
155
- const instance = await container.get(
156
- // @ts-expect-error - token is valid
157
- token as AnyInjectableType,
158
- args as any,
159
- )
160
-
161
- if (!isMounted) return
162
-
163
- // Get instance name for event subscription
164
- const instanceName = container.calculateInstanceName(token, args)
165
- if (instanceName) {
166
- instanceNameRef.current = instanceName
167
- }
168
-
169
- dispatch({ type: 'success', data: instance })
170
-
171
- // Set up subscription after we have the instance
172
- if (instanceName) {
173
- unsubscribe = eventBus.on(instanceName, 'destroy', () => {
174
- // Re-fetch when the service is invalidated
175
- if (isMounted) {
176
- dispatch({ type: 'loading' })
177
- void fetchAndSubscribe()
178
- }
179
- })
180
- }
181
- } catch (error) {
182
- if (isMounted) {
183
- dispatch({ type: 'error', error: error as Error })
184
- }
185
- }
186
- }
187
-
188
- // If we already have a sync instance from initial render, just set up subscription
189
- // Otherwise, fetch async
190
- const syncInstance = initialSyncInstanceRef.current
191
- if (syncInstance && refetchCounter === 0) {
192
- const instanceName = container.calculateInstanceName(token, args)
193
- if (instanceName) {
194
- instanceNameRef.current = instanceName
195
- unsubscribe = eventBus.on(instanceName, 'destroy', () => {
196
- if (isMounted) {
197
- dispatch({ type: 'loading' })
198
- void fetchAndSubscribe()
199
- }
200
- })
201
- }
202
- } else {
203
- dispatch({ type: 'loading' })
204
- void fetchAndSubscribe()
205
- }
206
-
207
- return () => {
208
- isMounted = false
209
- unsubscribe?.()
210
- }
211
- }, [container, rootContainer, token, args, refetchCounter])
212
-
213
- const refetch = useCallback(() => {
214
- setRefetchCounter((c) => c + 1)
215
- }, [])
216
-
217
- return {
218
- data: state.status === 'success' ? state.data : undefined,
219
- error: state.status === 'error' ? state.error : undefined,
220
- isLoading: state.status === 'loading',
221
- isSuccess: state.status === 'success',
222
- isError: state.status === 'error',
223
- refetch,
224
- }
225
- }
@@ -1,233 +0,0 @@
1
- import type {
2
- BoundInjectionToken,
3
- ClassType,
4
- Container,
5
- Factorable,
6
- FactoryInjectionToken,
7
- InjectionToken,
8
- InjectionTokenSchemaType,
9
- } from '@navios/di'
10
- import type { z, ZodType } from 'zod/v4'
11
-
12
-
13
- import { useCallback, useEffect, useRef, useSyncExternalStore } from 'react'
14
-
15
- import type { Join, UnionToArray } from '../types.mjs'
16
-
17
- import { useContainer, useRootContainer } from './use-container.mjs'
18
-
19
- // Cache entry for suspense
20
- interface CacheEntry<T> {
21
- promise: Promise<T> | null
22
- result: T | undefined
23
- error: Error | undefined
24
- status: 'pending' | 'resolved' | 'rejected'
25
- version: number // Increment on each fetch to track changes
26
- subscribers: Set<() => void>
27
- instanceName: string | null
28
- unsubscribe: (() => void) | undefined
29
- }
30
-
31
- // Global cache for service instances (per container + token + args combination)
32
- const cacheMap = new WeakMap<object, Map<string, CacheEntry<any>>>()
33
-
34
- function getCacheKey(token: any, args: unknown): string {
35
- const tokenId =
36
- typeof token === 'function'
37
- ? token.name
38
- : token.id || token.token?.id || String(token)
39
- return `${tokenId}:${JSON.stringify(args ?? null)}`
40
- }
41
-
42
- function getCache(container: object): Map<string, CacheEntry<any>> {
43
- let cache = cacheMap.get(container)
44
- if (!cache) {
45
- cache = new Map()
46
- cacheMap.set(container, cache)
47
- }
48
- return cache
49
- }
50
-
51
- /**
52
- * Sets up invalidation subscription for a cache entry if not already subscribed.
53
- * When the service is destroyed, clears the cache and notifies subscribers.
54
- */
55
- function setupInvalidationSubscription(
56
- entry: CacheEntry<any>,
57
- rootContainer: Container,
58
- ): void {
59
- if (entry.unsubscribe || !entry.instanceName) return
60
-
61
- const eventBus = rootContainer.getEventBus()
62
- entry.unsubscribe = eventBus.on(entry.instanceName, 'destroy', () => {
63
- // Clear cache and notify subscribers to re-fetch
64
- entry.result = undefined
65
- entry.error = undefined
66
- entry.status = 'pending'
67
- entry.promise = null
68
- // Notify all subscribers
69
- entry.subscribers.forEach((callback) => callback())
70
- })
71
- }
72
-
73
- // #1 Simple class
74
- export function useSuspenseService<T extends ClassType>(
75
- token: T,
76
- ): InstanceType<T> extends Factorable<infer R> ? R : InstanceType<T>
77
-
78
- // #2 Token with required Schema
79
- export function useSuspenseService<T, S extends InjectionTokenSchemaType>(
80
- token: InjectionToken<T, S>,
81
- args: z.input<S>,
82
- ): T
83
-
84
- // #3 Token with optional Schema
85
- export function useSuspenseService<
86
- T,
87
- S extends InjectionTokenSchemaType,
88
- R extends boolean,
89
- >(
90
- token: InjectionToken<T, S, R>,
91
- ): R extends false
92
- ? T
93
- : S extends ZodType<infer Type>
94
- ? `Error: Your token requires args: ${Join<UnionToArray<keyof Type>, ', '>}`
95
- : 'Error: Your token requires args'
96
-
97
- // #4 Token with no Schema
98
- export function useSuspenseService<T>(token: InjectionToken<T, undefined>): T
99
-
100
- export function useSuspenseService<T>(token: BoundInjectionToken<T, any>): T
101
-
102
- export function useSuspenseService<T>(token: FactoryInjectionToken<T, any>): T
103
-
104
- export function useSuspenseService(
105
- token:
106
- | ClassType
107
- | InjectionToken<any, any>
108
- | BoundInjectionToken<any, any>
109
- | FactoryInjectionToken<any, any>,
110
- args?: unknown,
111
- ): any {
112
- // useContainer returns ScopedContainer if inside ScopeProvider, otherwise Container
113
- const container = useContainer()
114
- const rootContainer = useRootContainer()
115
- const cache = getCache(container)
116
- const cacheKey = getCacheKey(token, args)
117
- const entryRef = useRef<CacheEntry<any> | null>(null)
118
- if (process.env.NODE_ENV === 'development') {
119
- const argsRef = useRef<unknown>(args)
120
- useEffect(() => {
121
- if (argsRef.current !== args) {
122
- if (JSON.stringify(argsRef.current) === JSON.stringify(args)) {
123
- console.warn(`useSuspenseService called with args that look the same but are different instances: ${JSON.stringify(argsRef.current)} !== ${JSON.stringify(args)}!
124
- This is likely because you are using a value that is not memoized.
125
- Please use a memoized value or use a different approach to pass the args.
126
- Example:
127
- const args = useMemo(() => ({ userId: '123' }), [])
128
- return useSuspenseService(UserToken, args)`)
129
- }
130
- argsRef.current = args
131
- }
132
- }, [args])
133
- }
134
-
135
- // Initialize or get cache entry
136
- if (!cache.has(cacheKey)) {
137
- // Try to get the instance synchronously first for better performance
138
- // This avoids suspense when the instance is already cached
139
- const syncInstance = container.tryGetSync(token, args)
140
-
141
- const instanceName = container.calculateInstanceName(token, args)
142
- const entry: CacheEntry<any> = {
143
- promise: null,
144
- result: syncInstance ?? undefined,
145
- error: undefined,
146
- status: syncInstance ? 'resolved' : 'pending',
147
- version: 0,
148
- subscribers: new Set(),
149
- instanceName,
150
- unsubscribe: undefined,
151
- }
152
- cache.set(cacheKey, entry)
153
- }
154
-
155
- const entry = cache.get(cacheKey)!
156
- entryRef.current = entry
157
-
158
- // Function to fetch the service
159
- const fetchService = useCallback(() => {
160
- const currentEntry = entryRef.current
161
- if (!currentEntry) return
162
-
163
- currentEntry.status = 'pending'
164
- currentEntry.version++ // Increment version to signal change to useSyncExternalStore
165
- currentEntry.promise = (container.get as any)(token, args)
166
- .then((instance: any) => {
167
- currentEntry.result = instance
168
- currentEntry.status = 'resolved'
169
-
170
- // Subscribe to invalidation events if not already subscribed
171
- setupInvalidationSubscription(currentEntry, rootContainer)
172
-
173
- // Notify subscribers
174
- currentEntry.subscribers.forEach((callback) => callback())
175
- return instance
176
- })
177
- .catch((error: Error) => {
178
- currentEntry.error = error
179
- currentEntry.status = 'rejected'
180
- throw error
181
- })
182
-
183
- return currentEntry.promise
184
- }, [container, rootContainer, token, args])
185
-
186
- // Subscribe to cache changes
187
- const subscribe = useCallback(
188
- (callback: () => void) => {
189
- entry.subscribers.add(callback)
190
- return () => {
191
- entry.subscribers.delete(callback)
192
- }
193
- },
194
- [entry],
195
- )
196
-
197
- // Get snapshot of current state - include version to detect invalidation
198
- const getSnapshot = useCallback(() => {
199
- return `${entry.status}:${entry.version}`
200
- }, [entry])
201
-
202
- // Use sync external store to track cache state
203
- useSyncExternalStore(subscribe, getSnapshot, getSnapshot)
204
-
205
- // Set up subscription for sync instances that don't have one yet
206
- useEffect(() => {
207
- const currentEntry = entryRef.current
208
- if (
209
- currentEntry &&
210
- currentEntry.status === 'resolved' &&
211
- currentEntry.instanceName &&
212
- !currentEntry.unsubscribe
213
- ) {
214
- setupInvalidationSubscription(currentEntry, rootContainer)
215
- }
216
- }, [rootContainer, entry])
217
-
218
- // Start fetching if not already
219
- if (entry.status === 'pending' && !entry.promise) {
220
- fetchService()
221
- }
222
-
223
- // Suspense behavior
224
- if (entry.status === 'pending') {
225
- throw entry.promise
226
- }
227
-
228
- if (entry.status === 'rejected') {
229
- throw entry.error
230
- }
231
-
232
- return entry.result
233
- }
package/src/index.mts DELETED
@@ -1,8 +0,0 @@
1
- // Providers
2
- export * from './providers/index.mjs'
3
-
4
- // Hooks
5
- export * from './hooks/index.mjs'
6
-
7
- // Types
8
- export * from './types.mjs'