@navios/di-react 0.1.1 → 0.2.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 +609 -28
- package/lib/index.d.mts +297 -18
- package/lib/index.d.mts.map +1 -0
- package/lib/index.d.ts +297 -18
- package/lib/index.d.ts.map +1 -0
- package/lib/index.js +536 -335
- package/lib/index.js.map +1 -1
- package/lib/index.mjs +533 -334
- package/lib/index.mjs.map +1 -1
- package/package.json +3 -3
- package/project.json +2 -2
- package/src/hooks/__tests__/use-service.spec.mts +1 -1
- package/src/hooks/index.mts +8 -2
- package/src/hooks/use-container.mts +47 -2
- package/src/hooks/use-invalidate.mts +3 -3
- package/src/hooks/use-optional-service.mts +59 -34
- package/src/hooks/use-scope.mts +66 -5
- package/src/hooks/use-service.mts +44 -18
- package/src/hooks/use-suspense-service.mts +48 -29
- package/src/providers/__tests__/scope-provider.spec.mts +84 -1
- package/src/providers/context.mts +11 -1
- package/src/providers/index.mts +2 -2
- package/src/providers/scope-provider.mts +34 -22
- package/{tsup.config.mts → tsdown.config.mts} +4 -3
- package/lib/_tsup-dts-rollup.d.mts +0 -304
- package/lib/_tsup-dts-rollup.d.ts +0 -304
package/lib/index.mjs.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../src/providers/context.mts","../src/providers/container-provider.mts","../src/hooks/use-container.mts","../src/providers/scope-provider.mts","../src/hooks/use-service.mts","../src/hooks/use-suspense-service.mts","../src/hooks/use-optional-service.mts","../src/hooks/use-invalidate.mts","../src/hooks/use-scope.mts"],"names":["createContext","jsx","useContext","useRef","useEffect","entry","useCallback","useReducer"],"mappings":";;;;AAIO,IAAM,gBAAA,GAAmB,cAAgC,IAAI;ACQ7D,SAAS,iBAAA,CAAkB;AAAA,EAChC,SAAA;AAAA,EACA;AACF,CAAA,EAA2B;AACzB,EAAA,OAAO,IAAI,gBAAA,CAAiB,QAAA,EAAU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AA;AAChC;AAMO,SAAS,eAAA,GAA0B;AACxC,EAAA,MAAM,QAAQ,QAAA,EAAS;AACvB,EAAA,IAAI,UAAU,IAAA,EAAM;AAClB,IAAA,MAAM,IAAI,KAAA;AAAA,MACR;AAAA,KAEF;AAAA,EACF;AACA,EAAA,OAAO,KAAA;AACT","file":"index.mjs","sourcesContent":["import { createContext } from 'react'\n\nimport type { Container } from '@navios/di'\n\nexport const ContainerContext = createContext<Container | null>(null)\n","import type { Container } from '@navios/di'\nimport type { ReactNode } from 'react'\n\nimport { jsx } from 'react/jsx-runtime'\n\nimport { ContainerContext } from './context.mjs'\n\nexport interface ContainerProviderProps {\n container: Container\n children: ReactNode\n}\n\nexport function ContainerProvider({\n container,\n children,\n}: ContainerProviderProps) {\n return jsx(ContainerContext.Provider, { value: container, children })\n}\n","import { useContext } from 'react'\n\nimport { ContainerContext } from '../providers/context.mjs'\n\nexport function useContainer() {\n const container = useContext(ContainerContext)\n\n if (!container) {\n throw new Error('useContainer must be used within a ContainerProvider')\n }\n\n return container\n}\n","import type { ReactNode } from 'react'\n\nimport { createContext, useEffect, useId, useRef } from 'react'\nimport { jsx } from 'react/jsx-runtime'\n\nimport { useContainer } from '../hooks/use-container.mjs'\n\n/**\n * Context for the current scope ID.\n * This allows nested components to access the current request scope.\n */\nexport const ScopeContext = createContext<string | null>(null)\n\nexport interface ScopeProviderProps {\n /**\n * Optional explicit scope ID. If not provided, a unique ID will be generated.\n * Useful when you need to reference the scope externally.\n */\n scopeId?: string\n /**\n * Optional metadata to attach to the request context.\n * Can be used to pass data like user info, request headers, etc.\n */\n metadata?: Record<string, unknown>\n /**\n * Priority for service resolution. Higher priority scopes take precedence.\n * @default 100\n */\n priority?: number\n children: ReactNode\n}\n\n/**\n * ScopeProvider creates a new request scope for dependency injection.\n *\n * Services with `scope: 'Request'` will be instantiated once per ScopeProvider\n * and shared among all components within that provider.\n *\n * This is useful for:\n * - Table rows that need isolated state\n * - Modal dialogs with their own service instances\n * - Multi-tenant scenarios\n * - Any case where you need isolated service instances\n *\n * @example\n * ```tsx\n * // Each row gets its own RowStateService instance\n * {rows.map(row => (\n * <ScopeProvider key={row.id} scopeId={row.id}>\n * <TableRow data={row} />\n * </ScopeProvider>\n * ))}\n * ```\n */\nexport function ScopeProvider({\n scopeId,\n metadata,\n priority = 100,\n children,\n}: ScopeProviderProps) {\n const container = useContainer()\n const generatedId = useId()\n const effectiveScopeId = scopeId ?? generatedId\n const isInitializedRef = useRef(false)\n\n // Begin request context on first render only\n // We use a ref to track initialization to handle React StrictMode double-renders\n if (!isInitializedRef.current) {\n // Check if context already exists (e.g., from StrictMode double render)\n const existingContexts = container.getServiceLocator().getRequestContexts()\n if (!existingContexts.has(effectiveScopeId)) {\n container.beginRequest(effectiveScopeId, metadata, priority)\n }\n isInitializedRef.current = true\n }\n\n // End request context on unmount\n useEffect(() => {\n return () => {\n void container.endRequest(effectiveScopeId)\n }\n }, [container, effectiveScopeId])\n\n return jsx(ScopeContext.Provider, { value: effectiveScopeId, children })\n}\n","import type {\n AnyInjectableType,\n BoundInjectionToken,\n ClassType,\n Factorable,\n FactoryInjectionToken,\n InjectionToken,\n InjectionTokenSchemaType,\n} from '@navios/di'\nimport type { z, ZodType } from 'zod/v4'\n\nimport { useCallback, useContext, useEffect, useReducer, useRef, useState } from 'react'\n\nimport type { Join, UnionToArray } from '../types.mjs'\n\nimport { ScopeContext } from '../providers/scope-provider.mjs'\nimport { useContainer } from './use-container.mjs'\n\ntype ServiceState<T> =\n | { status: 'idle' }\n | { status: 'loading' }\n | { status: 'success'; data: T }\n | { status: 'error'; error: Error }\n\ntype ServiceAction<T> =\n | { type: 'loading' }\n | { type: 'success'; data: T }\n | { type: 'error'; error: Error }\n | { type: 'reset' }\n\nfunction serviceReducer<T>(\n state: ServiceState<T>,\n action: ServiceAction<T>,\n): ServiceState<T> {\n switch (action.type) {\n case 'loading':\n return { status: 'loading' }\n case 'success':\n return { status: 'success', data: action.data }\n case 'error':\n return { status: 'error', error: action.error }\n case 'reset':\n return { status: 'idle' }\n default:\n return state\n }\n}\n\nexport interface UseServiceResult<T> {\n data: T | undefined\n error: Error | undefined\n isLoading: boolean\n isSuccess: boolean\n isError: boolean\n refetch: () => void\n}\n\n// #1 Simple class\nexport function useService<T extends ClassType>(\n token: T,\n): UseServiceResult<\n InstanceType<T> extends Factorable<infer R> ? R : InstanceType<T>\n>\n\n// #2 Token with required Schema\nexport function useService<T, S extends InjectionTokenSchemaType>(\n token: InjectionToken<T, S>,\n args: z.input<S>,\n): UseServiceResult<T>\n\n// #3 Token with optional Schema\nexport function useService<\n T,\n S extends InjectionTokenSchemaType,\n R extends boolean,\n>(\n token: InjectionToken<T, S, R>,\n): R extends false\n ? UseServiceResult<T>\n : S extends ZodType<infer Type>\n ? `Error: Your token requires args: ${Join<UnionToArray<keyof Type>, ', '>}`\n : 'Error: Your token requires args'\n\n// #4 Token with no Schema\nexport function useService<T>(\n token: InjectionToken<T, undefined>,\n): UseServiceResult<T>\n\nexport function useService<T>(\n token: BoundInjectionToken<T, any>,\n): UseServiceResult<T>\n\nexport function useService<T>(\n token: FactoryInjectionToken<T, any>,\n): UseServiceResult<T>\n\nexport function useService(\n token:\n | ClassType\n | InjectionToken<any, any>\n | BoundInjectionToken<any, any>\n | FactoryInjectionToken<any, any>,\n args?: unknown,\n): UseServiceResult<any> {\n const container = useContainer()\n const serviceLocator = container.getServiceLocator()\n const scopeId = useContext(ScopeContext)\n const [state, dispatch] = useReducer(serviceReducer, { status: 'idle' })\n const instanceNameRef = useRef<string | null>(null)\n const [refetchCounter, setRefetchCounter] = useState(0)\n\n if (process.env.NODE_ENV === 'development') {\n const argsRef = useRef<unknown>(args)\n useEffect(() => {\n if (argsRef.current !== args) {\n if (JSON.stringify(argsRef.current) === JSON.stringify(args)) {\n console.log(`WARNING: useService called with args that look the same but are different instances: ${JSON.stringify(argsRef.current)} !== ${JSON.stringify(args)}!\n This is likely because you are using not memoized value that is not stable.\n Please use a memoized value or use a different approach to pass the args.\n Example:\n const args = useMemo(() => ({ userId: '123' }), [])\n return useService(UserToken, args)\n `)\n }\n argsRef.current = args\n }\n }, [args])\n }\n\n // Subscribe to invalidation events\n useEffect(() => {\n const eventBus = serviceLocator.getEventBus()\n let unsubscribe: (() => void) | undefined\n let isMounted = true\n\n // Fetch the service and set up subscription\n const fetchAndSubscribe = async () => {\n try {\n // Set the correct request context before getting the instance\n // This ensures request-scoped services are resolved in the correct scope\n if (scopeId) {\n const requestContexts = serviceLocator.getRequestContexts()\n if (requestContexts.has(scopeId)) {\n container.setCurrentRequestContext(scopeId)\n }\n }\n\n const instance = await container.get(\n // @ts-expect-error - token is valid\n token as AnyInjectableType,\n args as any,\n )\n\n if (!isMounted) return\n\n // Get instance name for event subscription\n const instanceName = serviceLocator.getInstanceIdentifier(\n token as AnyInjectableType,\n args,\n )\n instanceNameRef.current = instanceName\n\n dispatch({ type: 'success', data: instance })\n\n // Set up subscription after we have the instance\n unsubscribe = eventBus.on(instanceName, 'destroy', () => {\n // Re-fetch when the service is invalidated\n if (isMounted) {\n dispatch({ type: 'loading' })\n void fetchAndSubscribe()\n }\n })\n } catch (error) {\n if (isMounted) {\n dispatch({ type: 'error', error: error as Error })\n }\n }\n }\n\n dispatch({ type: 'loading' })\n void fetchAndSubscribe()\n\n return () => {\n isMounted = false\n unsubscribe?.()\n }\n }, [container, serviceLocator, token, args, scopeId, refetchCounter])\n\n const refetch = useCallback(() => {\n setRefetchCounter((c) => c + 1)\n }, [])\n\n return {\n data: state.status === 'success' ? state.data : undefined,\n error: state.status === 'error' ? state.error : undefined,\n isLoading: state.status === 'loading',\n isSuccess: state.status === 'success',\n isError: state.status === 'error',\n refetch,\n }\n}\n","import type {\n AnyInjectableType,\n BoundInjectionToken,\n ClassType,\n Factorable,\n FactoryInjectionToken,\n InjectionToken,\n InjectionTokenSchemaType,\n} from '@navios/di'\nimport type { z, ZodType } from 'zod/v4'\n\nimport { useCallback, useEffect, useRef, useSyncExternalStore } from 'react'\n\nimport type { Join, UnionToArray } from '../types.mjs'\n\nimport { useContainer } from './use-container.mjs'\n\n// Cache entry for suspense\ninterface CacheEntry<T> {\n promise: Promise<T> | null\n result: T | undefined\n error: Error | undefined\n status: 'pending' | 'resolved' | 'rejected'\n version: number // Increment on each fetch to track changes\n subscribers: Set<() => void>\n instanceName: string | null\n unsubscribe: (() => void) | undefined\n}\n\n// Global cache for service instances (per container + token + args combination)\nconst cacheMap = new WeakMap<object, Map<string, CacheEntry<any>>>()\n\nfunction getCacheKey(token: any, args: unknown): string {\n const tokenId =\n typeof token === 'function'\n ? token.name\n : token.id || token.token?.id || String(token)\n return `${tokenId}:${JSON.stringify(args ?? null)}`\n}\n\nfunction getCache(container: object): Map<string, CacheEntry<any>> {\n let cache = cacheMap.get(container)\n if (!cache) {\n cache = new Map()\n cacheMap.set(container, cache)\n }\n return cache\n}\n\n// #1 Simple class\nexport function useSuspenseService<T extends ClassType>(\n token: T,\n): InstanceType<T> extends Factorable<infer R> ? R : InstanceType<T>\n\n// #2 Token with required Schema\nexport function useSuspenseService<T, S extends InjectionTokenSchemaType>(\n token: InjectionToken<T, S>,\n args: z.input<S>,\n): T\n\n// #3 Token with optional Schema\nexport function useSuspenseService<\n T,\n S extends InjectionTokenSchemaType,\n R extends boolean,\n>(\n token: InjectionToken<T, S, R>,\n): R extends false\n ? T\n : S extends ZodType<infer Type>\n ? `Error: Your token requires args: ${Join<UnionToArray<keyof Type>, ', '>}`\n : 'Error: Your token requires args'\n\n// #4 Token with no Schema\nexport function useSuspenseService<T>(token: InjectionToken<T, undefined>): T\n\nexport function useSuspenseService<T>(token: BoundInjectionToken<T, any>): T\n\nexport function useSuspenseService<T>(token: FactoryInjectionToken<T, any>): T\n\nexport function useSuspenseService(\n token:\n | ClassType\n | InjectionToken<any, any>\n | BoundInjectionToken<any, any>\n | FactoryInjectionToken<any, any>,\n args?: unknown,\n): any {\n const container = useContainer()\n const serviceLocator = container.getServiceLocator()\n const cache = getCache(container)\n const cacheKey = getCacheKey(token, args)\n const entryRef = useRef<CacheEntry<any> | null>(null)\n if (process.env.NODE_ENV === 'development') {\n const argsRef = useRef<unknown>(args)\n useEffect(() => {\n if (argsRef.current !== args) {\n if (JSON.stringify(argsRef.current) === JSON.stringify(args)) {\n console.log(`WARNING: useService called with args that look the same but are different instances: ${JSON.stringify(argsRef.current)} !== ${JSON.stringify(args)}!\n This is likely because you are using not memoized value that is not stable.\n Please use a memoized value or use a different approach to pass the args.\n Example:\n const args = useMemo(() => ({ userId: '123' }), [])\n return useService(UserToken, args)\n `)\n }\n argsRef.current = args\n }\n }, [args])\n }\n\n // Initialize or get cache entry\n if (!cache.has(cacheKey)) {\n const entry: CacheEntry<any> = {\n promise: null,\n result: undefined,\n error: undefined,\n status: 'pending',\n version: 0,\n subscribers: new Set(),\n instanceName: null,\n unsubscribe: undefined,\n }\n cache.set(cacheKey, entry)\n }\n\n const entry = cache.get(cacheKey)!\n entryRef.current = entry\n\n // Function to fetch the service\n const fetchService = useCallback(() => {\n const currentEntry = entryRef.current\n if (!currentEntry) return\n\n currentEntry.status = 'pending'\n currentEntry.version++ // Increment version to signal change to useSyncExternalStore\n currentEntry.promise = (container.get as any)(token, args)\n .then((instance: any) => {\n currentEntry.result = instance\n currentEntry.status = 'resolved'\n currentEntry.instanceName = serviceLocator.getInstanceIdentifier(\n token as AnyInjectableType,\n args,\n )\n\n // Subscribe to invalidation events if not already subscribed\n if (!currentEntry.unsubscribe && currentEntry.instanceName) {\n const eventBus = serviceLocator.getEventBus()\n currentEntry.unsubscribe = eventBus.on(\n currentEntry.instanceName,\n 'destroy',\n () => {\n // Clear cache and notify subscribers to re-fetch\n currentEntry.result = undefined\n currentEntry.error = undefined\n currentEntry.status = 'pending'\n currentEntry.promise = null\n // Notify all subscribers\n currentEntry.subscribers.forEach((callback) => callback())\n },\n )\n }\n\n // Notify subscribers\n currentEntry.subscribers.forEach((callback) => callback())\n return instance\n })\n .catch((error: Error) => {\n currentEntry.error = error\n currentEntry.status = 'rejected'\n throw error\n })\n\n return currentEntry.promise\n }, [container, serviceLocator, token, args])\n\n // Subscribe to cache changes\n const subscribe = useCallback(\n (callback: () => void) => {\n entry.subscribers.add(callback)\n return () => {\n entry.subscribers.delete(callback)\n }\n },\n [entry],\n )\n\n // Get snapshot of current state - include version to detect invalidation\n const getSnapshot = useCallback(() => {\n return `${entry.status}:${entry.version}`\n }, [entry])\n\n // Use sync external store to track cache state\n useSyncExternalStore(subscribe, getSnapshot, getSnapshot)\n\n // Cleanup subscription on unmount\n useEffect(() => {\n return () => {\n // // If there are no subscribers, unsubscribe and delete the cache entry\n // if (entry.subscribers.size === 0) {\n // entry.unsubscribe?.()\n // cache.delete(cacheKey)\n // }\n }\n }, [])\n\n // Start fetching if not already\n if (entry.status === 'pending' && !entry.promise) {\n fetchService()\n }\n\n // Suspense behavior\n if (entry.status === 'pending') {\n throw entry.promise\n }\n\n if (entry.status === 'rejected') {\n throw entry.error\n }\n\n return entry.result\n}\n","import type {\n AnyInjectableType,\n BoundInjectionToken,\n ClassType,\n Factorable,\n FactoryInjectionToken,\n InjectionToken,\n InjectionTokenSchemaType,\n} from '@navios/di'\nimport type { z, ZodType } from 'zod/v4'\n\nimport { useCallback, useEffect, useReducer, useRef } from 'react'\n\nimport type { Join, UnionToArray } from '../types.mjs'\n\nimport { useContainer } from './use-container.mjs'\n\ntype OptionalServiceState<T> =\n | { status: 'idle' }\n | { status: 'loading' }\n | { status: 'success'; data: T }\n | { status: 'not-found' }\n | { status: 'error'; error: Error }\n\ntype OptionalServiceAction<T> =\n | { type: 'loading' }\n | { type: 'success'; data: T }\n | { type: 'not-found' }\n | { type: 'error'; error: Error }\n | { type: 'reset' }\n\nfunction optionalServiceReducer<T>(\n state: OptionalServiceState<T>,\n action: OptionalServiceAction<T>,\n): OptionalServiceState<T> {\n switch (action.type) {\n case 'loading':\n return { status: 'loading' }\n case 'success':\n return { status: 'success', data: action.data }\n case 'not-found':\n return { status: 'not-found' }\n case 'error':\n return { status: 'error', error: action.error }\n case 'reset':\n return { status: 'idle' }\n default:\n return state\n }\n}\n\nexport interface UseOptionalServiceResult<T> {\n /**\n * The service instance if found and loaded successfully, otherwise undefined.\n */\n data: T | undefined\n /**\n * Error that occurred during loading (excludes \"not found\" which is not an error).\n */\n error: Error | undefined\n /**\n * True while the service is being loaded.\n */\n isLoading: boolean\n /**\n * True if the service was loaded successfully.\n */\n isSuccess: boolean\n /**\n * True if the service was not found (not registered in the container).\n */\n isNotFound: boolean\n /**\n * True if an error occurred during loading.\n */\n isError: boolean\n /**\n * Function to manually re-fetch the service.\n */\n refetch: () => void\n}\n\n// #1 Simple class\nexport function useOptionalService<T extends ClassType>(\n token: T,\n): UseOptionalServiceResult<\n InstanceType<T> extends Factorable<infer R> ? R : InstanceType<T>\n>\n\n// #2 Token with required Schema\nexport function useOptionalService<T, S extends InjectionTokenSchemaType>(\n token: InjectionToken<T, S>,\n args: z.input<S>,\n): UseOptionalServiceResult<T>\n\n// #3 Token with optional Schema\nexport function useOptionalService<\n T,\n S extends InjectionTokenSchemaType,\n R extends boolean,\n>(\n token: InjectionToken<T, S, R>,\n): R extends false\n ? UseOptionalServiceResult<T>\n : S extends ZodType<infer Type>\n ? `Error: Your token requires args: ${Join<UnionToArray<keyof Type>, ', '>}`\n : 'Error: Your token requires args'\n\n// #4 Token with no Schema\nexport function useOptionalService<T>(\n token: InjectionToken<T, undefined>,\n): UseOptionalServiceResult<T>\n\nexport function useOptionalService<T>(\n token: BoundInjectionToken<T, any>,\n): UseOptionalServiceResult<T>\n\nexport function useOptionalService<T>(\n token: FactoryInjectionToken<T, any>,\n): UseOptionalServiceResult<T>\n\n/**\n * Hook to optionally load a service from the DI container.\n *\n * Unlike useService, this hook does NOT throw an error if the service is not registered.\n * Instead, it returns `isNotFound: true` when the service doesn't exist.\n *\n * This is useful for:\n * - Optional dependencies that may or may not be configured\n * - Feature flags where a service might not be available\n * - Plugins or extensions that are conditionally registered\n *\n * @example\n * ```tsx\n * function Analytics() {\n * const { data: analytics, isNotFound } = useOptionalService(AnalyticsService)\n *\n * if (isNotFound) {\n * // Analytics service not configured, skip tracking\n * return null\n * }\n *\n * return <AnalyticsTracker service={analytics} />\n * }\n * ```\n */\nexport function useOptionalService(\n token:\n | ClassType\n | InjectionToken<any, any>\n | BoundInjectionToken<any, any>\n | FactoryInjectionToken<any, any>,\n args?: unknown,\n): UseOptionalServiceResult<any> {\n const container = useContainer()\n const serviceLocator = container.getServiceLocator()\n const [state, dispatch] = useReducer(optionalServiceReducer, { status: 'idle' })\n const instanceNameRef = useRef<string | null>(null)\n\n if (process.env.NODE_ENV === 'development') {\n const argsRef = useRef<unknown>(args)\n useEffect(() => {\n if (argsRef.current !== args) {\n if (JSON.stringify(argsRef.current) === JSON.stringify(args)) {\n console.log(`WARNING: useOptionalService called with args that look the same but are different instances: ${JSON.stringify(argsRef.current)} !== ${JSON.stringify(args)}!\n This is likely because you are using not memoized value that is not stable.\n Please use a memoized value or use a different approach to pass the args.\n Example:\n const args = useMemo(() => ({ userId: '123' }), [])\n return useOptionalService(UserToken, args)\n `)\n }\n argsRef.current = args\n }\n }, [args])\n }\n\n const fetchService = useCallback(async () => {\n dispatch({ type: 'loading' })\n try {\n const [error, instance] = await serviceLocator.getInstance(\n token as AnyInjectableType,\n args as any,\n )\n\n if (error) {\n // Check if error is a \"not found\" type error\n const errorMessage = error.message?.toLowerCase() ?? ''\n if (\n errorMessage.includes('not found') ||\n errorMessage.includes('not registered') ||\n errorMessage.includes('no provider')\n ) {\n dispatch({ type: 'not-found' })\n } else {\n dispatch({ type: 'error', error: error as Error })\n }\n return\n }\n\n // Get instance name for event subscription\n instanceNameRef.current = serviceLocator.getInstanceIdentifier(\n token as AnyInjectableType,\n args,\n )\n dispatch({ type: 'success', data: instance })\n } catch (error) {\n // Caught exceptions are treated as errors\n const err = error as Error\n const errorMessage = err.message?.toLowerCase() ?? ''\n if (\n errorMessage.includes('not found') ||\n errorMessage.includes('not registered') ||\n errorMessage.includes('no provider')\n ) {\n dispatch({ type: 'not-found' })\n } else {\n dispatch({ type: 'error', error: err })\n }\n }\n }, [serviceLocator, token, args])\n\n // Subscribe to invalidation events\n useEffect(() => {\n const eventBus = serviceLocator.getEventBus()\n let unsubscribe: (() => void) | undefined\n\n // Fetch the service\n void fetchService()\n\n // Set up subscription after we have the instance name\n const setupSubscription = () => {\n if (instanceNameRef.current) {\n unsubscribe = eventBus.on(instanceNameRef.current, 'destroy', () => {\n // Re-fetch when the service is invalidated\n void fetchService()\n })\n }\n }\n\n // Wait a tick for the instance name to be set\n const timeoutId = setTimeout(setupSubscription, 10)\n\n return () => {\n clearTimeout(timeoutId)\n unsubscribe?.()\n }\n }, [fetchService, serviceLocator])\n\n return {\n data: state.status === 'success' ? state.data : undefined,\n error: state.status === 'error' ? state.error : undefined,\n isLoading: state.status === 'loading',\n isSuccess: state.status === 'success',\n isNotFound: state.status === 'not-found',\n isError: state.status === 'error',\n refetch: fetchService,\n }\n}\n","import type {\n BoundInjectionToken,\n ClassType,\n FactoryInjectionToken,\n InjectionToken,\n InjectionTokenSchemaType,\n} from '@navios/di'\n\nimport { useCallback } from 'react'\n\nimport { useContainer } from './use-container.mjs'\n\ntype InvalidatableToken =\n | ClassType\n | InjectionToken<any, any>\n | BoundInjectionToken<any, any>\n | FactoryInjectionToken<any, any>\n\n/**\n * Hook that returns a function to invalidate a service by its token.\n *\n * When called, this will:\n * 1. Destroy the current service instance\n * 2. Trigger re-fetch in all components using useService/useSuspenseService for that token\n *\n * @example\n * ```tsx\n * function UserProfile() {\n * const { data: user } = useService(UserService)\n * const invalidateUser = useInvalidate(UserService)\n *\n * const handleRefresh = () => {\n * invalidateUser() // All components using UserService will re-fetch\n * }\n *\n * return (\n * <div>\n * <span>{user?.name}</span>\n * <button onClick={handleRefresh}>Refresh</button>\n * </div>\n * )\n * }\n * ```\n */\nexport function useInvalidate<T extends InvalidatableToken>(\n token: T,\n): () => Promise<void>\n\n/**\n * Hook that returns a function to invalidate a service by its token with args.\n *\n * @example\n * ```tsx\n * function UserProfile({ userId }: { userId: string }) {\n * const args = useMemo(() => ({ userId }), [userId])\n * const { data: user } = useService(UserToken, args)\n * const invalidateUser = useInvalidate(UserToken, args)\n *\n * return (\n * <div>\n * <span>{user?.name}</span>\n * <button onClick={() => invalidateUser()}>Refresh</button>\n * </div>\n * )\n * }\n * ```\n */\nexport function useInvalidate<T, S extends InjectionTokenSchemaType>(\n token: InjectionToken<T, S>,\n args: S extends undefined ? never : unknown,\n): () => Promise<void>\n\nexport function useInvalidate(\n token: InvalidatableToken,\n args?: unknown,\n): () => Promise<void> {\n const container = useContainer()\n const serviceLocator = container.getServiceLocator()\n\n return useCallback(async () => {\n const instanceName = serviceLocator.getInstanceIdentifier(token, args)\n await serviceLocator.invalidate(instanceName)\n }, [serviceLocator, token, args])\n}\n\n/**\n * Hook that returns a function to invalidate a service instance directly.\n *\n * This is useful when you have the service instance and want to invalidate it\n * without knowing its token.\n *\n * @example\n * ```tsx\n * function UserProfile() {\n * const { data: user } = useService(UserService)\n * const invalidateInstance = useInvalidateInstance()\n *\n * const handleRefresh = () => {\n * if (user) {\n * invalidateInstance(user)\n * }\n * }\n *\n * return (\n * <div>\n * <span>{user?.name}</span>\n * <button onClick={handleRefresh}>Refresh</button>\n * </div>\n * )\n * }\n * ```\n */\nexport function useInvalidateInstance(): (instance: unknown) => Promise<void> {\n const container = useContainer()\n\n return useCallback(\n async (instance: unknown) => {\n await container.invalidate(instance)\n },\n [container],\n )\n}\n","import { useContext } from 'react'\n\nimport { ScopeContext } from '../providers/scope-provider.mjs'\n\n/**\n * Hook to get the current scope ID.\n * Returns null if not inside a ScopeProvider.\n */\nexport function useScope(): string | null {\n return useContext(ScopeContext)\n}\n\n/**\n * Hook to get the current scope ID, throwing if not inside a ScopeProvider.\n * Use this when your component requires a scope to function correctly.\n */\nexport function useScopeOrThrow(): string {\n const scope = useScope()\n if (scope === null) {\n throw new Error(\n 'useScopeOrThrow must be used within a ScopeProvider. ' +\n 'Wrap your component tree with <ScopeProvider> to create a request scope.',\n )\n }\n return scope\n}\n"]}
|
|
1
|
+
{"version":3,"file":"index.mjs","names":["unsubscribe: (() => void) | undefined","entry: CacheEntry<any>","entry","unsubscribe: (() => void) | undefined"],"sources":["../src/providers/context.mts","../src/providers/container-provider.mts","../src/providers/scope-provider.mts","../src/hooks/use-container.mts","../src/hooks/use-service.mts","../src/hooks/use-suspense-service.mts","../src/hooks/use-optional-service.mts","../src/hooks/use-invalidate.mts","../src/hooks/use-scope.mts"],"sourcesContent":["import { createContext } from 'react'\n\nimport type { Container, ScopedContainer } from '@navios/di'\n\n/**\n * Context for the root Container.\n * This is set by ContainerProvider and provides the base container.\n */\nexport const ContainerContext = createContext<Container | null>(null)\n\n/**\n * Context for the current ScopedContainer (if inside a ScopeProvider).\n * This allows nested components to access request-scoped services.\n */\nexport const ScopedContainerContext = createContext<ScopedContainer | null>(null)\n","import type { Container } from '@navios/di'\nimport type { ReactNode } from 'react'\n\nimport { jsx } from 'react/jsx-runtime'\n\nimport { ContainerContext } from './context.mjs'\n\nexport interface ContainerProviderProps {\n container: Container\n children: ReactNode\n}\n\nexport function ContainerProvider({\n container,\n children,\n}: ContainerProviderProps) {\n return jsx(ContainerContext.Provider, { value: container, children })\n}\n","import type { ReactNode } from 'react'\nimport type { ScopedContainer } from '@navios/di'\n\nimport { useContext, useEffect, useId, useRef } from 'react'\nimport { jsx } from 'react/jsx-runtime'\n\nimport { ContainerContext, ScopedContainerContext } from './context.mjs'\n\nexport interface ScopeProviderProps {\n /**\n * Optional explicit scope ID. If not provided, a unique ID will be generated.\n * Useful when you need to reference the scope externally.\n */\n scopeId?: string\n /**\n * Optional metadata to attach to the request context.\n * Can be used to pass data like user info, request headers, etc.\n */\n metadata?: Record<string, unknown>\n /**\n * Priority for service resolution. Higher priority scopes take precedence.\n * @default 100\n */\n priority?: number\n children: ReactNode\n}\n\n/**\n * ScopeProvider creates a new request scope for dependency injection.\n *\n * Services with `scope: 'Request'` will be instantiated once per ScopeProvider\n * and shared among all components within that provider.\n *\n * This is useful for:\n * - Table rows that need isolated state\n * - Modal dialogs with their own service instances\n * - Multi-tenant scenarios\n * - Any case where you need isolated service instances\n *\n * @example\n * ```tsx\n * // Each row gets its own RowStateService instance\n * {rows.map(row => (\n * <ScopeProvider key={row.id} scopeId={row.id} metadata={{ rowData: row }}>\n * <TableRow />\n * </ScopeProvider>\n * ))}\n * ```\n */\nexport function ScopeProvider({\n scopeId,\n metadata,\n priority = 100,\n children,\n}: ScopeProviderProps) {\n const container = useContext(ContainerContext)\n if (!container) {\n throw new Error('ScopeProvider must be used within a ContainerProvider')\n }\n\n const generatedId = useId()\n const effectiveScopeId = scopeId ?? generatedId\n const scopedContainerRef = useRef<ScopedContainer | null>(null)\n\n // Create ScopedContainer on first render only\n // We use a ref to track initialization to handle React StrictMode double-renders\n if (!scopedContainerRef.current) {\n // Check if this request ID already exists (e.g., from StrictMode double render)\n if (!container.hasActiveRequest(effectiveScopeId)) {\n scopedContainerRef.current = container.beginRequest(\n effectiveScopeId,\n metadata,\n priority,\n )\n }\n }\n\n // End request context on unmount\n useEffect(() => {\n const scopedContainer = scopedContainerRef.current\n return () => {\n if (scopedContainer) {\n void scopedContainer.endRequest()\n }\n }\n }, [])\n\n // If we don't have a scoped container (shouldn't happen normally), don't render\n if (!scopedContainerRef.current) {\n return null\n }\n\n return jsx(ScopedContainerContext.Provider, {\n value: scopedContainerRef.current,\n children,\n })\n}\n","import type { Container, IContainer, ScopedContainer } from '@navios/di'\n\nimport { useContext } from 'react'\n\nimport { ContainerContext, ScopedContainerContext } from '../providers/context.mjs'\n\n/**\n * Hook to get the current container (ScopedContainer if inside ScopeProvider, otherwise Container).\n *\n * This is the primary hook for accessing the DI container. It automatically\n * returns the correct container based on context:\n * - Inside a ScopeProvider: returns the ScopedContainer for request-scoped services\n * - Outside a ScopeProvider: returns the root Container\n *\n * @returns The current container (ScopedContainer or Container)\n */\nexport function useContainer(): IContainer {\n const scopedContainer = useContext(ScopedContainerContext)\n const container = useContext(ContainerContext)\n\n // Prefer scoped container if available (we're inside a ScopeProvider)\n if (scopedContainer) {\n return scopedContainer\n }\n\n if (!container) {\n throw new Error('useContainer must be used within a ContainerProvider')\n }\n\n return container\n}\n\n/**\n * Hook to get the root Container, regardless of whether we're inside a ScopeProvider.\n *\n * Use this when you need access to the root container specifically,\n * for example to create new request scopes programmatically.\n *\n * @returns The root Container\n */\nexport function useRootContainer(): Container {\n const container = useContext(ContainerContext)\n\n if (!container) {\n throw new Error('useRootContainer must be used within a ContainerProvider')\n }\n\n return container\n}\n\n/**\n * Hook to get the current ScopedContainer if inside a ScopeProvider.\n *\n * @returns The ScopedContainer or null if not inside a ScopeProvider\n */\nexport function useScopedContainer(): ScopedContainer | null {\n return useContext(ScopedContainerContext)\n}\n","import type {\n AnyInjectableType,\n BoundInjectionToken,\n ClassType,\n Factorable,\n FactoryInjectionToken,\n InjectionToken,\n InjectionTokenSchemaType,\n} from '@navios/di'\nimport type { z, ZodType } from 'zod/v4'\n\nimport { useCallback, useEffect, useReducer, useRef, useState } from 'react'\n\nimport type { Join, UnionToArray } from '../types.mjs'\n\nimport { useContainer, useRootContainer } from './use-container.mjs'\n\ntype ServiceState<T> =\n | { status: 'idle' }\n | { status: 'loading' }\n | { status: 'success'; data: T }\n | { status: 'error'; error: Error }\n\ntype ServiceAction<T> =\n | { type: 'loading' }\n | { type: 'success'; data: T }\n | { type: 'error'; error: Error }\n | { type: 'reset' }\n\nfunction serviceReducer<T>(\n state: ServiceState<T>,\n action: ServiceAction<T>,\n): ServiceState<T> {\n switch (action.type) {\n case 'loading':\n return { status: 'loading' }\n case 'success':\n return { status: 'success', data: action.data }\n case 'error':\n return { status: 'error', error: action.error }\n case 'reset':\n return { status: 'idle' }\n default:\n return state\n }\n}\n\nexport interface UseServiceResult<T> {\n data: T | undefined\n error: Error | undefined\n isLoading: boolean\n isSuccess: boolean\n isError: boolean\n refetch: () => void\n}\n\n// #1 Simple class\nexport function useService<T extends ClassType>(\n token: T,\n): UseServiceResult<\n InstanceType<T> extends Factorable<infer R> ? R : InstanceType<T>\n>\n\n// #2 Token with required Schema\nexport function useService<T, S extends InjectionTokenSchemaType>(\n token: InjectionToken<T, S>,\n args: z.input<S>,\n): UseServiceResult<T>\n\n// #3 Token with optional Schema\nexport function useService<\n T,\n S extends InjectionTokenSchemaType,\n R extends boolean,\n>(\n token: InjectionToken<T, S, R>,\n): R extends false\n ? UseServiceResult<T>\n : S extends ZodType<infer Type>\n ? `Error: Your token requires args: ${Join<UnionToArray<keyof Type>, ', '>}`\n : 'Error: Your token requires args'\n\n// #4 Token with no Schema\nexport function useService<T>(\n token: InjectionToken<T, undefined>,\n): UseServiceResult<T>\n\nexport function useService<T>(\n token: BoundInjectionToken<T, any>,\n): UseServiceResult<T>\n\nexport function useService<T>(\n token: FactoryInjectionToken<T, any>,\n): UseServiceResult<T>\n\nexport function useService(\n token:\n | ClassType\n | InjectionToken<any, any>\n | BoundInjectionToken<any, any>\n | FactoryInjectionToken<any, any>,\n args?: unknown,\n): UseServiceResult<any> {\n // useContainer returns ScopedContainer if inside ScopeProvider, otherwise Container\n // This automatically handles request-scoped services correctly\n const container = useContainer()\n const rootContainer = useRootContainer()\n const serviceLocator = rootContainer.getServiceLocator()\n\n // Try to get the instance synchronously first for better performance\n // This avoids the async loading state when the instance is already cached\n // We use a ref to track this so it doesn't cause effect re-runs\n const initialSyncInstanceRef = useRef<any>(undefined)\n const isFirstRenderRef = useRef(true)\n\n if (isFirstRenderRef.current) {\n initialSyncInstanceRef.current = container.tryGetSync(token, args)\n isFirstRenderRef.current = false\n }\n\n const initialState: ServiceState<any> = initialSyncInstanceRef.current\n ? { status: 'success', data: initialSyncInstanceRef.current }\n : { status: 'idle' }\n\n const [state, dispatch] = useReducer(serviceReducer, initialState)\n const instanceNameRef = useRef<string | null>(null)\n const [refetchCounter, setRefetchCounter] = useState(0)\n\n if (process.env.NODE_ENV === 'development') {\n const argsRef = useRef<unknown>(args)\n useEffect(() => {\n if (argsRef.current !== args) {\n if (JSON.stringify(argsRef.current) === JSON.stringify(args)) {\n console.log(`WARNING: useService called with args that look the same but are different instances: ${JSON.stringify(argsRef.current)} !== ${JSON.stringify(args)}!\n This is likely because you are using not memoized value that is not stable.\n Please use a memoized value or use a different approach to pass the args.\n Example:\n const args = useMemo(() => ({ userId: '123' }), [])\n return useService(UserToken, args)\n `)\n }\n argsRef.current = args\n }\n }, [args])\n }\n\n // Subscribe to invalidation events\n useEffect(() => {\n const eventBus = serviceLocator.getEventBus()\n let unsubscribe: (() => void) | undefined\n let isMounted = true\n\n // Fetch the service and set up subscription\n const fetchAndSubscribe = async () => {\n try {\n // The container (either ScopedContainer or Container) handles resolution correctly\n const instance = await container.get(\n // @ts-expect-error - token is valid\n token as AnyInjectableType,\n args as any,\n )\n\n if (!isMounted) return\n\n // Get instance name for event subscription\n const instanceName = serviceLocator.getInstanceIdentifier(\n token as AnyInjectableType,\n args,\n )\n instanceNameRef.current = instanceName\n\n dispatch({ type: 'success', data: instance })\n\n // Set up subscription after we have the instance\n unsubscribe = eventBus.on(instanceName, 'destroy', () => {\n // Re-fetch when the service is invalidated\n if (isMounted) {\n dispatch({ type: 'loading' })\n void fetchAndSubscribe()\n }\n })\n } catch (error) {\n if (isMounted) {\n dispatch({ type: 'error', error: error as Error })\n }\n }\n }\n\n // If we already have a sync instance from initial render, just set up subscription\n // Otherwise, fetch async\n const syncInstance = initialSyncInstanceRef.current\n if (syncInstance && refetchCounter === 0) {\n const instanceName = serviceLocator.getInstanceIdentifier(\n token as AnyInjectableType,\n args,\n )\n instanceNameRef.current = instanceName\n unsubscribe = eventBus.on(instanceName, 'destroy', () => {\n if (isMounted) {\n dispatch({ type: 'loading' })\n void fetchAndSubscribe()\n }\n })\n } else {\n dispatch({ type: 'loading' })\n void fetchAndSubscribe()\n }\n\n return () => {\n isMounted = false\n unsubscribe?.()\n }\n }, [container, serviceLocator, token, args, refetchCounter])\n\n const refetch = useCallback(() => {\n setRefetchCounter((c) => c + 1)\n }, [])\n\n return {\n data: state.status === 'success' ? state.data : undefined,\n error: state.status === 'error' ? state.error : undefined,\n isLoading: state.status === 'loading',\n isSuccess: state.status === 'success',\n isError: state.status === 'error',\n refetch,\n }\n}\n","import type {\n AnyInjectableType,\n BoundInjectionToken,\n ClassType,\n Factorable,\n FactoryInjectionToken,\n InjectionToken,\n InjectionTokenSchemaType,\n} from '@navios/di'\nimport type { z, ZodType } from 'zod/v4'\n\nimport { useCallback, useEffect, useRef, useSyncExternalStore } from 'react'\n\nimport type { Join, UnionToArray } from '../types.mjs'\n\nimport { useContainer, useRootContainer } from './use-container.mjs'\n\n// Cache entry for suspense\ninterface CacheEntry<T> {\n promise: Promise<T> | null\n result: T | undefined\n error: Error | undefined\n status: 'pending' | 'resolved' | 'rejected'\n version: number // Increment on each fetch to track changes\n subscribers: Set<() => void>\n instanceName: string | null\n unsubscribe: (() => void) | undefined\n}\n\n// Global cache for service instances (per container + token + args combination)\nconst cacheMap = new WeakMap<object, Map<string, CacheEntry<any>>>()\n\nfunction getCacheKey(token: any, args: unknown): string {\n const tokenId =\n typeof token === 'function'\n ? token.name\n : token.id || token.token?.id || String(token)\n return `${tokenId}:${JSON.stringify(args ?? null)}`\n}\n\nfunction getCache(container: object): Map<string, CacheEntry<any>> {\n let cache = cacheMap.get(container)\n if (!cache) {\n cache = new Map()\n cacheMap.set(container, cache)\n }\n return cache\n}\n\n/**\n * Sets up invalidation subscription for a cache entry if not already subscribed.\n * When the service is destroyed, clears the cache and notifies subscribers.\n */\nfunction setupInvalidationSubscription(\n entry: CacheEntry<any>,\n serviceLocator: ReturnType<\n import('@navios/di').Container['getServiceLocator']\n >,\n): void {\n if (entry.unsubscribe || !entry.instanceName) return\n\n const eventBus = serviceLocator.getEventBus()\n entry.unsubscribe = eventBus.on(entry.instanceName, 'destroy', () => {\n // Clear cache and notify subscribers to re-fetch\n entry.result = undefined\n entry.error = undefined\n entry.status = 'pending'\n entry.promise = null\n // Notify all subscribers\n entry.subscribers.forEach((callback) => callback())\n })\n}\n\n// #1 Simple class\nexport function useSuspenseService<T extends ClassType>(\n token: T,\n): InstanceType<T> extends Factorable<infer R> ? R : InstanceType<T>\n\n// #2 Token with required Schema\nexport function useSuspenseService<T, S extends InjectionTokenSchemaType>(\n token: InjectionToken<T, S>,\n args: z.input<S>,\n): T\n\n// #3 Token with optional Schema\nexport function useSuspenseService<\n T,\n S extends InjectionTokenSchemaType,\n R extends boolean,\n>(\n token: InjectionToken<T, S, R>,\n): R extends false\n ? T\n : S extends ZodType<infer Type>\n ? `Error: Your token requires args: ${Join<UnionToArray<keyof Type>, ', '>}`\n : 'Error: Your token requires args'\n\n// #4 Token with no Schema\nexport function useSuspenseService<T>(token: InjectionToken<T, undefined>): T\n\nexport function useSuspenseService<T>(token: BoundInjectionToken<T, any>): T\n\nexport function useSuspenseService<T>(token: FactoryInjectionToken<T, any>): T\n\nexport function useSuspenseService(\n token:\n | ClassType\n | InjectionToken<any, any>\n | BoundInjectionToken<any, any>\n | FactoryInjectionToken<any, any>,\n args?: unknown,\n): any {\n // useContainer returns ScopedContainer if inside ScopeProvider, otherwise Container\n const container = useContainer()\n const rootContainer = useRootContainer()\n const serviceLocator = rootContainer.getServiceLocator()\n const cache = getCache(container)\n const cacheKey = getCacheKey(token, args)\n const entryRef = useRef<CacheEntry<any> | null>(null)\n if (process.env.NODE_ENV === 'development') {\n const argsRef = useRef<unknown>(args)\n useEffect(() => {\n if (argsRef.current !== args) {\n if (JSON.stringify(argsRef.current) === JSON.stringify(args)) {\n console.log(`WARNING: useService called with args that look the same but are different instances: ${JSON.stringify(argsRef.current)} !== ${JSON.stringify(args)}!\n This is likely because you are using not memoized value that is not stable.\n Please use a memoized value or use a different approach to pass the args.\n Example:\n const args = useMemo(() => ({ userId: '123' }), [])\n return useService(UserToken, args)\n `)\n }\n argsRef.current = args\n }\n }, [args])\n }\n\n // Initialize or get cache entry\n if (!cache.has(cacheKey)) {\n // Try to get the instance synchronously first for better performance\n // This avoids suspense when the instance is already cached\n const syncInstance = container.tryGetSync(token, args)\n\n const entry: CacheEntry<any> = {\n promise: null,\n result: syncInstance ?? undefined,\n error: undefined,\n status: syncInstance ? 'resolved' : 'pending',\n version: 0,\n subscribers: new Set(),\n instanceName: syncInstance\n ? serviceLocator.getInstanceIdentifier(token as AnyInjectableType, args)\n : null,\n unsubscribe: undefined,\n }\n cache.set(cacheKey, entry)\n }\n\n const entry = cache.get(cacheKey)!\n entryRef.current = entry\n\n // Function to fetch the service\n const fetchService = useCallback(() => {\n const currentEntry = entryRef.current\n if (!currentEntry) return\n\n currentEntry.status = 'pending'\n currentEntry.version++ // Increment version to signal change to useSyncExternalStore\n currentEntry.promise = (container.get as any)(token, args)\n .then((instance: any) => {\n currentEntry.result = instance\n currentEntry.status = 'resolved'\n currentEntry.instanceName = serviceLocator.getInstanceIdentifier(\n token as AnyInjectableType,\n args,\n )\n\n // Subscribe to invalidation events if not already subscribed\n setupInvalidationSubscription(currentEntry, serviceLocator)\n\n // Notify subscribers\n currentEntry.subscribers.forEach((callback) => callback())\n return instance\n })\n .catch((error: Error) => {\n currentEntry.error = error\n currentEntry.status = 'rejected'\n throw error\n })\n\n return currentEntry.promise\n }, [container, serviceLocator, token, args])\n\n // Subscribe to cache changes\n const subscribe = useCallback(\n (callback: () => void) => {\n entry.subscribers.add(callback)\n return () => {\n entry.subscribers.delete(callback)\n }\n },\n [entry],\n )\n\n // Get snapshot of current state - include version to detect invalidation\n const getSnapshot = useCallback(() => {\n return `${entry.status}:${entry.version}`\n }, [entry])\n\n // Use sync external store to track cache state\n useSyncExternalStore(subscribe, getSnapshot, getSnapshot)\n\n // Set up subscription for sync instances that don't have one yet\n useEffect(() => {\n const currentEntry = entryRef.current\n if (\n currentEntry &&\n currentEntry.status === 'resolved' &&\n currentEntry.instanceName &&\n !currentEntry.unsubscribe\n ) {\n setupInvalidationSubscription(currentEntry, serviceLocator)\n }\n }, [serviceLocator, entry])\n\n // Start fetching if not already\n if (entry.status === 'pending' && !entry.promise) {\n fetchService()\n }\n\n // Suspense behavior\n if (entry.status === 'pending') {\n throw entry.promise\n }\n\n if (entry.status === 'rejected') {\n throw entry.error\n }\n\n return entry.result\n}\n","import type {\n AnyInjectableType,\n BoundInjectionToken,\n ClassType,\n Factorable,\n FactoryInjectionToken,\n InjectionToken,\n InjectionTokenSchemaType,\n} from '@navios/di'\nimport type { z, ZodType } from 'zod/v4'\n\nimport { useCallback, useEffect, useReducer, useRef } from 'react'\n\nimport type { Join, UnionToArray } from '../types.mjs'\n\nimport { useContainer, useRootContainer } from './use-container.mjs'\n\ntype OptionalServiceState<T> =\n | { status: 'idle' }\n | { status: 'loading' }\n | { status: 'success'; data: T }\n | { status: 'not-found' }\n | { status: 'error'; error: Error }\n\ntype OptionalServiceAction<T> =\n | { type: 'loading' }\n | { type: 'success'; data: T }\n | { type: 'not-found' }\n | { type: 'error'; error: Error }\n | { type: 'reset' }\n\nfunction optionalServiceReducer<T>(\n state: OptionalServiceState<T>,\n action: OptionalServiceAction<T>,\n): OptionalServiceState<T> {\n switch (action.type) {\n case 'loading':\n return { status: 'loading' }\n case 'success':\n return { status: 'success', data: action.data }\n case 'not-found':\n return { status: 'not-found' }\n case 'error':\n return { status: 'error', error: action.error }\n case 'reset':\n return { status: 'idle' }\n default:\n return state\n }\n}\n\nexport interface UseOptionalServiceResult<T> {\n /**\n * The service instance if found and loaded successfully, otherwise undefined.\n */\n data: T | undefined\n /**\n * Error that occurred during loading (excludes \"not found\" which is not an error).\n */\n error: Error | undefined\n /**\n * True while the service is being loaded.\n */\n isLoading: boolean\n /**\n * True if the service was loaded successfully.\n */\n isSuccess: boolean\n /**\n * True if the service was not found (not registered in the container).\n */\n isNotFound: boolean\n /**\n * True if an error occurred during loading.\n */\n isError: boolean\n /**\n * Function to manually re-fetch the service.\n */\n refetch: () => void\n}\n\n// #1 Simple class\nexport function useOptionalService<T extends ClassType>(\n token: T,\n): UseOptionalServiceResult<\n InstanceType<T> extends Factorable<infer R> ? R : InstanceType<T>\n>\n\n// #2 Token with required Schema\nexport function useOptionalService<T, S extends InjectionTokenSchemaType>(\n token: InjectionToken<T, S>,\n args: z.input<S>,\n): UseOptionalServiceResult<T>\n\n// #3 Token with optional Schema\nexport function useOptionalService<\n T,\n S extends InjectionTokenSchemaType,\n R extends boolean,\n>(\n token: InjectionToken<T, S, R>,\n): R extends false\n ? UseOptionalServiceResult<T>\n : S extends ZodType<infer Type>\n ? `Error: Your token requires args: ${Join<UnionToArray<keyof Type>, ', '>}`\n : 'Error: Your token requires args'\n\n// #4 Token with no Schema\nexport function useOptionalService<T>(\n token: InjectionToken<T, undefined>,\n): UseOptionalServiceResult<T>\n\nexport function useOptionalService<T>(\n token: BoundInjectionToken<T, any>,\n): UseOptionalServiceResult<T>\n\nexport function useOptionalService<T>(\n token: FactoryInjectionToken<T, any>,\n): UseOptionalServiceResult<T>\n\n/**\n * Hook to optionally load a service from the DI container.\n *\n * Unlike useService, this hook does NOT throw an error if the service is not registered.\n * Instead, it returns `isNotFound: true` when the service doesn't exist.\n *\n * This is useful for:\n * - Optional dependencies that may or may not be configured\n * - Feature flags where a service might not be available\n * - Plugins or extensions that are conditionally registered\n *\n * @example\n * ```tsx\n * function Analytics() {\n * const { data: analytics, isNotFound } = useOptionalService(AnalyticsService)\n *\n * if (isNotFound) {\n * // Analytics service not configured, skip tracking\n * return null\n * }\n *\n * return <AnalyticsTracker service={analytics} />\n * }\n * ```\n */\nexport function useOptionalService(\n token:\n | ClassType\n | InjectionToken<any, any>\n | BoundInjectionToken<any, any>\n | FactoryInjectionToken<any, any>,\n args?: unknown,\n): UseOptionalServiceResult<any> {\n // useContainer returns ScopedContainer if inside ScopeProvider, otherwise Container\n const container = useContainer()\n const rootContainer = useRootContainer()\n const serviceLocator = rootContainer.getServiceLocator()\n\n // Try to get the instance synchronously first for better performance\n // This avoids the async loading state when the instance is already cached\n // We use a ref to track this so it doesn't cause effect re-runs\n const initialSyncInstanceRef = useRef<any>(undefined)\n const isFirstRenderRef = useRef(true)\n\n if (isFirstRenderRef.current) {\n try {\n initialSyncInstanceRef.current = container.tryGetSync(token, args)\n } catch {\n // Service not registered, leave as undefined\n }\n isFirstRenderRef.current = false\n }\n\n const initialState: OptionalServiceState<any> = initialSyncInstanceRef.current\n ? { status: 'success', data: initialSyncInstanceRef.current }\n : { status: 'idle' }\n\n const [state, dispatch] = useReducer(optionalServiceReducer, initialState)\n const instanceNameRef = useRef<string | null>(null)\n\n if (process.env.NODE_ENV === 'development') {\n const argsRef = useRef<unknown>(args)\n useEffect(() => {\n if (argsRef.current !== args) {\n if (JSON.stringify(argsRef.current) === JSON.stringify(args)) {\n console.log(`WARNING: useOptionalService called with args that look the same but are different instances: ${JSON.stringify(argsRef.current)} !== ${JSON.stringify(args)}!\n This is likely because you are using not memoized value that is not stable.\n Please use a memoized value or use a different approach to pass the args.\n Example:\n const args = useMemo(() => ({ userId: '123' }), [])\n return useOptionalService(UserToken, args)\n `)\n }\n argsRef.current = args\n }\n }, [args])\n }\n\n const fetchService = useCallback(async () => {\n dispatch({ type: 'loading' })\n try {\n // Use the container (ScopedContainer or Container) for resolution\n const instance = await container.get(\n // @ts-expect-error - token is valid\n token as AnyInjectableType,\n args as any,\n )\n\n // Get instance name for event subscription\n instanceNameRef.current = serviceLocator.getInstanceIdentifier(\n token as AnyInjectableType,\n args,\n )\n dispatch({ type: 'success', data: instance })\n } catch (error) {\n // Caught exceptions are treated as errors\n const err = error as Error\n const errorMessage = err.message?.toLowerCase() ?? ''\n if (\n errorMessage.includes('not found') ||\n errorMessage.includes('not registered') ||\n errorMessage.includes('no provider')\n ) {\n dispatch({ type: 'not-found' })\n } else {\n dispatch({ type: 'error', error: err })\n }\n }\n }, [container, serviceLocator, token, args])\n\n // Subscribe to invalidation events\n useEffect(() => {\n const eventBus = serviceLocator.getEventBus()\n let unsubscribe: (() => void) | undefined\n\n // If we already have a sync instance from initial render, just set up subscription\n // Otherwise, fetch async\n const syncInstance = initialSyncInstanceRef.current\n if (syncInstance) {\n instanceNameRef.current = serviceLocator.getInstanceIdentifier(\n token as AnyInjectableType,\n args,\n )\n unsubscribe = eventBus.on(instanceNameRef.current, 'destroy', () => {\n void fetchService()\n })\n } else {\n void fetchService()\n\n // Set up subscription after we have the instance name\n const setupSubscription = () => {\n if (instanceNameRef.current) {\n unsubscribe = eventBus.on(instanceNameRef.current, 'destroy', () => {\n // Re-fetch when the service is invalidated\n void fetchService()\n })\n }\n }\n\n // Wait a tick for the instance name to be set\n const timeoutId = setTimeout(setupSubscription, 10)\n\n return () => {\n clearTimeout(timeoutId)\n unsubscribe?.()\n }\n }\n\n return () => {\n unsubscribe?.()\n }\n }, [fetchService, serviceLocator, token, args])\n\n return {\n data: state.status === 'success' ? state.data : undefined,\n error: state.status === 'error' ? state.error : undefined,\n isLoading: state.status === 'loading',\n isSuccess: state.status === 'success',\n isNotFound: state.status === 'not-found',\n isError: state.status === 'error',\n refetch: fetchService,\n }\n}\n","import type {\n BoundInjectionToken,\n ClassType,\n FactoryInjectionToken,\n InjectionToken,\n InjectionTokenSchemaType,\n} from '@navios/di'\n\nimport { useCallback } from 'react'\n\nimport { useContainer, useRootContainer } from './use-container.mjs'\n\ntype InvalidatableToken =\n | ClassType\n | InjectionToken<any, any>\n | BoundInjectionToken<any, any>\n | FactoryInjectionToken<any, any>\n\n/**\n * Hook that returns a function to invalidate a service by its token.\n *\n * When called, this will:\n * 1. Destroy the current service instance\n * 2. Trigger re-fetch in all components using useService/useSuspenseService for that token\n *\n * @example\n * ```tsx\n * function UserProfile() {\n * const { data: user } = useService(UserService)\n * const invalidateUser = useInvalidate(UserService)\n *\n * const handleRefresh = () => {\n * invalidateUser() // All components using UserService will re-fetch\n * }\n *\n * return (\n * <div>\n * <span>{user?.name}</span>\n * <button onClick={handleRefresh}>Refresh</button>\n * </div>\n * )\n * }\n * ```\n */\nexport function useInvalidate<T extends InvalidatableToken>(\n token: T,\n): () => Promise<void>\n\n/**\n * Hook that returns a function to invalidate a service by its token with args.\n *\n * @example\n * ```tsx\n * function UserProfile({ userId }: { userId: string }) {\n * const args = useMemo(() => ({ userId }), [userId])\n * const { data: user } = useService(UserToken, args)\n * const invalidateUser = useInvalidate(UserToken, args)\n *\n * return (\n * <div>\n * <span>{user?.name}</span>\n * <button onClick={() => invalidateUser()}>Refresh</button>\n * </div>\n * )\n * }\n * ```\n */\nexport function useInvalidate<T, S extends InjectionTokenSchemaType>(\n token: InjectionToken<T, S>,\n args: S extends undefined ? never : unknown,\n): () => Promise<void>\n\nexport function useInvalidate(\n token: InvalidatableToken,\n args?: unknown,\n): () => Promise<void> {\n const rootContainer = useRootContainer()\n const serviceLocator = rootContainer.getServiceLocator()\n\n return useCallback(async () => {\n const instanceName = serviceLocator.getInstanceIdentifier(token, args)\n await serviceLocator.invalidate(instanceName)\n }, [serviceLocator, token, args])\n}\n\n/**\n * Hook that returns a function to invalidate a service instance directly.\n *\n * This is useful when you have the service instance and want to invalidate it\n * without knowing its token.\n *\n * @example\n * ```tsx\n * function UserProfile() {\n * const { data: user } = useService(UserService)\n * const invalidateInstance = useInvalidateInstance()\n *\n * const handleRefresh = () => {\n * if (user) {\n * invalidateInstance(user)\n * }\n * }\n *\n * return (\n * <div>\n * <span>{user?.name}</span>\n * <button onClick={handleRefresh}>Refresh</button>\n * </div>\n * )\n * }\n * ```\n */\nexport function useInvalidateInstance(): (instance: unknown) => Promise<void> {\n const container = useContainer()\n\n return useCallback(\n async (instance: unknown) => {\n await container.invalidate(instance)\n },\n [container],\n )\n}\n","import type { ScopedContainer } from '@navios/di'\n\nimport { useContext } from 'react'\n\nimport { ScopedContainerContext } from '../providers/context.mjs'\n\n/**\n * Hook to get the current scope ID.\n * Returns null if not inside a ScopeProvider.\n */\nexport function useScope(): string | null {\n const scopedContainer = useContext(ScopedContainerContext)\n return scopedContainer?.getRequestId() ?? null\n}\n\n/**\n * Hook to get the current scope ID, throwing if not inside a ScopeProvider.\n * Use this when your component requires a scope to function correctly.\n */\nexport function useScopeOrThrow(): string {\n const scopeId = useScope()\n if (scopeId === null) {\n throw new Error(\n 'useScopeOrThrow must be used within a ScopeProvider. ' +\n 'Wrap your component tree with <ScopeProvider> to create a request scope.',\n )\n }\n return scopeId\n}\n\n/**\n * Hook to get the current ScopedContainer.\n * Returns null if not inside a ScopeProvider.\n *\n * Use this to access scope metadata or other ScopedContainer methods.\n *\n * @example\n * ```tsx\n * function TableRow() {\n * const scope = useScopedContainer()\n * const rowData = scope?.getMetadata('rowData')\n * // ...\n * }\n * ```\n */\nexport function useScopedContainer(): ScopedContainer | null {\n return useContext(ScopedContainerContext)\n}\n\n/**\n * Hook to get the current ScopedContainer, throwing if not inside a ScopeProvider.\n * Use this when your component requires a scope to function correctly.\n */\nexport function useScopedContainerOrThrow(): ScopedContainer {\n const scopedContainer = useScopedContainer()\n if (scopedContainer === null) {\n throw new Error(\n 'useScopedContainerOrThrow must be used within a ScopeProvider. ' +\n 'Wrap your component tree with <ScopeProvider> to create a request scope.',\n )\n }\n return scopedContainer\n}\n\n/**\n * Hook to get metadata from the current scope.\n * Returns undefined if not inside a ScopeProvider or if the key doesn't exist.\n *\n * @example\n * ```tsx\n * // In parent component:\n * <ScopeProvider metadata={{ userId: '123', theme: 'dark' }}>\n * <ChildComponent />\n * </ScopeProvider>\n *\n * // In child component:\n * function ChildComponent() {\n * const userId = useScopeMetadata<string>('userId')\n * const theme = useScopeMetadata<'light' | 'dark'>('theme')\n * // ...\n * }\n * ```\n */\nexport function useScopeMetadata<T = unknown>(key: string): T | undefined {\n const scopedContainer = useContext(ScopedContainerContext)\n return scopedContainer?.getMetadata(key) as T | undefined\n}\n"],"mappings":";;;;;;;;AAQA,MAAa,mBAAmB,cAAgC,KAAK;;;;;AAMrE,MAAa,yBAAyB,cAAsC,KAAK;;;;ACFjF,SAAgB,kBAAkB,EAChC,WACA,YACyB;AACzB,QAAO,IAAI,iBAAiB,UAAU;EAAE,OAAO;EAAW;EAAU,CAAC;;;;;;;;;;;;;;;;;;;;;;;;;;;ACiCvE,SA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5C,KAAI,oBAAoB,KACtB,OAAM,IAAI,MACR,0IAED;AAEH,QAAO;;;;;;;;;;;;;;;;;;;;;AAsBT,SAAgB,iBAA8B,KAA4B;AAExE,QADwB,WAAW,uBAAuB,EAClC,YAAY,IAAI"}
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@navios/di-react",
|
|
3
|
-
"version": "0.
|
|
3
|
+
"version": "0.2.0",
|
|
4
4
|
"author": {
|
|
5
5
|
"name": "Oleksandr Hanzha",
|
|
6
6
|
"email": "alex@granted.name"
|
|
@@ -12,7 +12,7 @@
|
|
|
12
12
|
},
|
|
13
13
|
"license": "MIT",
|
|
14
14
|
"peerDependencies": {
|
|
15
|
-
"@navios/di": "^0.
|
|
15
|
+
"@navios/di": "^0.6.0",
|
|
16
16
|
"react": "^18.0.0 || ^19.0.0"
|
|
17
17
|
},
|
|
18
18
|
"typings": "./lib/index.d.mts",
|
|
@@ -31,7 +31,7 @@
|
|
|
31
31
|
}
|
|
32
32
|
},
|
|
33
33
|
"devDependencies": {
|
|
34
|
-
"@navios/di": "^0.
|
|
34
|
+
"@navios/di": "^0.6.0",
|
|
35
35
|
"@testing-library/dom": "^10.4.1",
|
|
36
36
|
"@testing-library/react": "^16.3.0",
|
|
37
37
|
"@types/react": "^19.2.7",
|
package/project.json
CHANGED
|
@@ -33,11 +33,11 @@
|
|
|
33
33
|
},
|
|
34
34
|
"build": {
|
|
35
35
|
"executor": "nx:run-commands",
|
|
36
|
-
"inputs": ["projectSources"],
|
|
36
|
+
"inputs": ["projectSources", "{projectRoot}/tsdown.config.mts"],
|
|
37
37
|
"outputs": ["{projectRoot}/lib"],
|
|
38
38
|
"dependsOn": ["check", "test:ci", "lint"],
|
|
39
39
|
"options": {
|
|
40
|
-
"command": "
|
|
40
|
+
"command": "tsdown",
|
|
41
41
|
"cwd": "packages/di-react"
|
|
42
42
|
}
|
|
43
43
|
},
|
|
@@ -71,7 +71,7 @@ describe('useService', () => {
|
|
|
71
71
|
expect(result.current.isError).toBe(true)
|
|
72
72
|
})
|
|
73
73
|
|
|
74
|
-
expect(result.current.error?.message).
|
|
74
|
+
expect(result.current.error?.message).toContain(
|
|
75
75
|
'Service initialization failed',
|
|
76
76
|
)
|
|
77
77
|
expect(result.current.data).toBeUndefined()
|
package/src/hooks/index.mts
CHANGED
|
@@ -1,8 +1,14 @@
|
|
|
1
|
-
export { useContainer } from './use-container.mjs'
|
|
1
|
+
export { useContainer, useRootContainer } from './use-container.mjs'
|
|
2
2
|
export { useService } from './use-service.mjs'
|
|
3
3
|
export type { UseServiceResult } from './use-service.mjs'
|
|
4
4
|
export { useSuspenseService } from './use-suspense-service.mjs'
|
|
5
5
|
export { useOptionalService } from './use-optional-service.mjs'
|
|
6
6
|
export type { UseOptionalServiceResult } from './use-optional-service.mjs'
|
|
7
7
|
export { useInvalidate, useInvalidateInstance } from './use-invalidate.mjs'
|
|
8
|
-
export {
|
|
8
|
+
export {
|
|
9
|
+
useScope,
|
|
10
|
+
useScopeOrThrow,
|
|
11
|
+
useScopedContainer,
|
|
12
|
+
useScopedContainerOrThrow,
|
|
13
|
+
useScopeMetadata,
|
|
14
|
+
} from './use-scope.mjs'
|
|
@@ -1,13 +1,58 @@
|
|
|
1
|
+
import type { Container, IContainer, ScopedContainer } from '@navios/di'
|
|
2
|
+
|
|
1
3
|
import { useContext } from 'react'
|
|
2
4
|
|
|
3
|
-
import { ContainerContext } from '../providers/context.mjs'
|
|
5
|
+
import { ContainerContext, ScopedContainerContext } from '../providers/context.mjs'
|
|
4
6
|
|
|
5
|
-
|
|
7
|
+
/**
|
|
8
|
+
* Hook to get the current container (ScopedContainer if inside ScopeProvider, otherwise Container).
|
|
9
|
+
*
|
|
10
|
+
* This is the primary hook for accessing the DI container. It automatically
|
|
11
|
+
* returns the correct container based on context:
|
|
12
|
+
* - Inside a ScopeProvider: returns the ScopedContainer for request-scoped services
|
|
13
|
+
* - Outside a ScopeProvider: returns the root Container
|
|
14
|
+
*
|
|
15
|
+
* @returns The current container (ScopedContainer or Container)
|
|
16
|
+
*/
|
|
17
|
+
export function useContainer(): IContainer {
|
|
18
|
+
const scopedContainer = useContext(ScopedContainerContext)
|
|
6
19
|
const container = useContext(ContainerContext)
|
|
7
20
|
|
|
21
|
+
// Prefer scoped container if available (we're inside a ScopeProvider)
|
|
22
|
+
if (scopedContainer) {
|
|
23
|
+
return scopedContainer
|
|
24
|
+
}
|
|
25
|
+
|
|
8
26
|
if (!container) {
|
|
9
27
|
throw new Error('useContainer must be used within a ContainerProvider')
|
|
10
28
|
}
|
|
11
29
|
|
|
12
30
|
return container
|
|
13
31
|
}
|
|
32
|
+
|
|
33
|
+
/**
|
|
34
|
+
* Hook to get the root Container, regardless of whether we're inside a ScopeProvider.
|
|
35
|
+
*
|
|
36
|
+
* Use this when you need access to the root container specifically,
|
|
37
|
+
* for example to create new request scopes programmatically.
|
|
38
|
+
*
|
|
39
|
+
* @returns The root Container
|
|
40
|
+
*/
|
|
41
|
+
export function useRootContainer(): Container {
|
|
42
|
+
const container = useContext(ContainerContext)
|
|
43
|
+
|
|
44
|
+
if (!container) {
|
|
45
|
+
throw new Error('useRootContainer must be used within a ContainerProvider')
|
|
46
|
+
}
|
|
47
|
+
|
|
48
|
+
return container
|
|
49
|
+
}
|
|
50
|
+
|
|
51
|
+
/**
|
|
52
|
+
* Hook to get the current ScopedContainer if inside a ScopeProvider.
|
|
53
|
+
*
|
|
54
|
+
* @returns The ScopedContainer or null if not inside a ScopeProvider
|
|
55
|
+
*/
|
|
56
|
+
export function useScopedContainer(): ScopedContainer | null {
|
|
57
|
+
return useContext(ScopedContainerContext)
|
|
58
|
+
}
|
|
@@ -8,7 +8,7 @@ import type {
|
|
|
8
8
|
|
|
9
9
|
import { useCallback } from 'react'
|
|
10
10
|
|
|
11
|
-
import { useContainer } from './use-container.mjs'
|
|
11
|
+
import { useContainer, useRootContainer } from './use-container.mjs'
|
|
12
12
|
|
|
13
13
|
type InvalidatableToken =
|
|
14
14
|
| ClassType
|
|
@@ -74,8 +74,8 @@ export function useInvalidate(
|
|
|
74
74
|
token: InvalidatableToken,
|
|
75
75
|
args?: unknown,
|
|
76
76
|
): () => Promise<void> {
|
|
77
|
-
const
|
|
78
|
-
const serviceLocator =
|
|
77
|
+
const rootContainer = useRootContainer()
|
|
78
|
+
const serviceLocator = rootContainer.getServiceLocator()
|
|
79
79
|
|
|
80
80
|
return useCallback(async () => {
|
|
81
81
|
const instanceName = serviceLocator.getInstanceIdentifier(token, args)
|
|
@@ -13,7 +13,7 @@ import { useCallback, useEffect, useReducer, useRef } from 'react'
|
|
|
13
13
|
|
|
14
14
|
import type { Join, UnionToArray } from '../types.mjs'
|
|
15
15
|
|
|
16
|
-
import { useContainer } from './use-container.mjs'
|
|
16
|
+
import { useContainer, useRootContainer } from './use-container.mjs'
|
|
17
17
|
|
|
18
18
|
type OptionalServiceState<T> =
|
|
19
19
|
| { status: 'idle' }
|
|
@@ -152,9 +152,31 @@ export function useOptionalService(
|
|
|
152
152
|
| FactoryInjectionToken<any, any>,
|
|
153
153
|
args?: unknown,
|
|
154
154
|
): UseOptionalServiceResult<any> {
|
|
155
|
+
// useContainer returns ScopedContainer if inside ScopeProvider, otherwise Container
|
|
155
156
|
const container = useContainer()
|
|
156
|
-
const
|
|
157
|
-
const
|
|
157
|
+
const rootContainer = useRootContainer()
|
|
158
|
+
const serviceLocator = rootContainer.getServiceLocator()
|
|
159
|
+
|
|
160
|
+
// Try to get the instance synchronously first for better performance
|
|
161
|
+
// This avoids the async loading state when the instance is already cached
|
|
162
|
+
// We use a ref to track this so it doesn't cause effect re-runs
|
|
163
|
+
const initialSyncInstanceRef = useRef<any>(undefined)
|
|
164
|
+
const isFirstRenderRef = useRef(true)
|
|
165
|
+
|
|
166
|
+
if (isFirstRenderRef.current) {
|
|
167
|
+
try {
|
|
168
|
+
initialSyncInstanceRef.current = container.tryGetSync(token, args)
|
|
169
|
+
} catch {
|
|
170
|
+
// Service not registered, leave as undefined
|
|
171
|
+
}
|
|
172
|
+
isFirstRenderRef.current = false
|
|
173
|
+
}
|
|
174
|
+
|
|
175
|
+
const initialState: OptionalServiceState<any> = initialSyncInstanceRef.current
|
|
176
|
+
? { status: 'success', data: initialSyncInstanceRef.current }
|
|
177
|
+
: { status: 'idle' }
|
|
178
|
+
|
|
179
|
+
const [state, dispatch] = useReducer(optionalServiceReducer, initialState)
|
|
158
180
|
const instanceNameRef = useRef<string | null>(null)
|
|
159
181
|
|
|
160
182
|
if (process.env.NODE_ENV === 'development') {
|
|
@@ -178,26 +200,13 @@ export function useOptionalService(
|
|
|
178
200
|
const fetchService = useCallback(async () => {
|
|
179
201
|
dispatch({ type: 'loading' })
|
|
180
202
|
try {
|
|
181
|
-
|
|
203
|
+
// Use the container (ScopedContainer or Container) for resolution
|
|
204
|
+
const instance = await container.get(
|
|
205
|
+
// @ts-expect-error - token is valid
|
|
182
206
|
token as AnyInjectableType,
|
|
183
207
|
args as any,
|
|
184
208
|
)
|
|
185
209
|
|
|
186
|
-
if (error) {
|
|
187
|
-
// Check if error is a "not found" type error
|
|
188
|
-
const errorMessage = error.message?.toLowerCase() ?? ''
|
|
189
|
-
if (
|
|
190
|
-
errorMessage.includes('not found') ||
|
|
191
|
-
errorMessage.includes('not registered') ||
|
|
192
|
-
errorMessage.includes('no provider')
|
|
193
|
-
) {
|
|
194
|
-
dispatch({ type: 'not-found' })
|
|
195
|
-
} else {
|
|
196
|
-
dispatch({ type: 'error', error: error as Error })
|
|
197
|
-
}
|
|
198
|
-
return
|
|
199
|
-
}
|
|
200
|
-
|
|
201
210
|
// Get instance name for event subscription
|
|
202
211
|
instanceNameRef.current = serviceLocator.getInstanceIdentifier(
|
|
203
212
|
token as AnyInjectableType,
|
|
@@ -218,34 +227,50 @@ export function useOptionalService(
|
|
|
218
227
|
dispatch({ type: 'error', error: err })
|
|
219
228
|
}
|
|
220
229
|
}
|
|
221
|
-
}, [serviceLocator, token, args])
|
|
230
|
+
}, [container, serviceLocator, token, args])
|
|
222
231
|
|
|
223
232
|
// Subscribe to invalidation events
|
|
224
233
|
useEffect(() => {
|
|
225
234
|
const eventBus = serviceLocator.getEventBus()
|
|
226
235
|
let unsubscribe: (() => void) | undefined
|
|
227
236
|
|
|
228
|
-
//
|
|
229
|
-
|
|
237
|
+
// If we already have a sync instance from initial render, just set up subscription
|
|
238
|
+
// Otherwise, fetch async
|
|
239
|
+
const syncInstance = initialSyncInstanceRef.current
|
|
240
|
+
if (syncInstance) {
|
|
241
|
+
instanceNameRef.current = serviceLocator.getInstanceIdentifier(
|
|
242
|
+
token as AnyInjectableType,
|
|
243
|
+
args,
|
|
244
|
+
)
|
|
245
|
+
unsubscribe = eventBus.on(instanceNameRef.current, 'destroy', () => {
|
|
246
|
+
void fetchService()
|
|
247
|
+
})
|
|
248
|
+
} else {
|
|
249
|
+
void fetchService()
|
|
230
250
|
|
|
231
|
-
|
|
232
|
-
|
|
233
|
-
|
|
234
|
-
|
|
235
|
-
|
|
236
|
-
|
|
237
|
-
|
|
251
|
+
// Set up subscription after we have the instance name
|
|
252
|
+
const setupSubscription = () => {
|
|
253
|
+
if (instanceNameRef.current) {
|
|
254
|
+
unsubscribe = eventBus.on(instanceNameRef.current, 'destroy', () => {
|
|
255
|
+
// Re-fetch when the service is invalidated
|
|
256
|
+
void fetchService()
|
|
257
|
+
})
|
|
258
|
+
}
|
|
238
259
|
}
|
|
239
|
-
}
|
|
240
260
|
|
|
241
|
-
|
|
242
|
-
|
|
261
|
+
// Wait a tick for the instance name to be set
|
|
262
|
+
const timeoutId = setTimeout(setupSubscription, 10)
|
|
263
|
+
|
|
264
|
+
return () => {
|
|
265
|
+
clearTimeout(timeoutId)
|
|
266
|
+
unsubscribe?.()
|
|
267
|
+
}
|
|
268
|
+
}
|
|
243
269
|
|
|
244
270
|
return () => {
|
|
245
|
-
clearTimeout(timeoutId)
|
|
246
271
|
unsubscribe?.()
|
|
247
272
|
}
|
|
248
|
-
}, [fetchService, serviceLocator])
|
|
273
|
+
}, [fetchService, serviceLocator, token, args])
|
|
249
274
|
|
|
250
275
|
return {
|
|
251
276
|
data: state.status === 'success' ? state.data : undefined,
|
package/src/hooks/use-scope.mts
CHANGED
|
@@ -1,13 +1,16 @@
|
|
|
1
|
+
import type { ScopedContainer } from '@navios/di'
|
|
2
|
+
|
|
1
3
|
import { useContext } from 'react'
|
|
2
4
|
|
|
3
|
-
import {
|
|
5
|
+
import { ScopedContainerContext } from '../providers/context.mjs'
|
|
4
6
|
|
|
5
7
|
/**
|
|
6
8
|
* Hook to get the current scope ID.
|
|
7
9
|
* Returns null if not inside a ScopeProvider.
|
|
8
10
|
*/
|
|
9
11
|
export function useScope(): string | null {
|
|
10
|
-
|
|
12
|
+
const scopedContainer = useContext(ScopedContainerContext)
|
|
13
|
+
return scopedContainer?.getRequestId() ?? null
|
|
11
14
|
}
|
|
12
15
|
|
|
13
16
|
/**
|
|
@@ -15,12 +18,70 @@ export function useScope(): string | null {
|
|
|
15
18
|
* Use this when your component requires a scope to function correctly.
|
|
16
19
|
*/
|
|
17
20
|
export function useScopeOrThrow(): string {
|
|
18
|
-
const
|
|
19
|
-
if (
|
|
21
|
+
const scopeId = useScope()
|
|
22
|
+
if (scopeId === null) {
|
|
20
23
|
throw new Error(
|
|
21
24
|
'useScopeOrThrow must be used within a ScopeProvider. ' +
|
|
22
25
|
'Wrap your component tree with <ScopeProvider> to create a request scope.',
|
|
23
26
|
)
|
|
24
27
|
}
|
|
25
|
-
return
|
|
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
|
|
26
87
|
}
|