@navios/di-react 2.0.0-alpha.0 → 2.0.0-alpha.1
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 +27 -2
- package/lib/index.cjs +189 -192
- package/lib/index.cjs.map +1 -1
- package/lib/index.d.cts +88 -40
- package/lib/index.d.cts.map +1 -1
- package/lib/index.d.mts +88 -40
- package/lib/index.d.mts.map +1 -1
- package/lib/index.mjs +189 -192
- package/lib/index.mjs.map +1 -1
- package/package.json +3 -3
package/lib/index.mjs.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"index.mjs","names":[],"sources":["../src/container/context.mts","../src/container/container-provider.mts","../src/container/use-container.mts","../src/scope/scope-provider.mts","../src/scope/use-scope.mts","../src/service/args-key.mts","../src/service/use-service.mts","../src/service/use-suspense-service.mts","../src/service/use-optional-service.mts","../src/service/use-invalidate-instance.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 { jsx } from 'react/jsx-runtime'\n\nimport type { Container } from '@navios/di'\nimport type { ReactNode } from 'react'\n\nimport { ContainerContext } from './context.mjs'\n\nexport interface ContainerProviderProps {\n container: Container\n children: ReactNode\n}\n\nexport function ContainerProvider({ container, children }: ContainerProviderProps) {\n return jsx(ContainerContext.Provider, { value: container, children })\n}\n","import { useContext } from 'react'\n\nimport type { Container, ScopedContainer } from '@navios/di'\n\nimport { ContainerContext, ScopedContainerContext } from './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(): Container | ScopedContainer {\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","import { useContext, useEffect, useId, useReducer, useRef } from 'react'\nimport { jsx } from 'react/jsx-runtime'\n\nimport type { ScopedContainer } from '@navios/di'\nimport type { ReactNode } from 'react'\n\nimport { ContainerContext, ScopedContainerContext } from '../container/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 scope.\n * The key `scopeId` is reserved: it always holds the effective scope ID.\n * Can be used to pass data like user info, request headers, etc.\n */\n metadata?: Record<string, unknown>\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({ scopeId, metadata, children }: 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 // True between an effect setup and its cleanup.\n const isMountedRef = useRef(false)\n // True once the scope in the ref has been disposed.\n const isDisposedRef = useRef(false)\n const [, rerender] = useReducer((count: number) => count + 1, 0)\n\n // DI scopes have no ids, so the effective scope id lives in the scope's\n // metadata under `scopeId`.\n const createScope = () => container.createScope({ ...metadata, scopeId: effectiveScopeId })\n const createScopeRef = useRef(createScope)\n createScopeRef.current = createScope\n\n // Create the ScopedContainer once per mounted provider.\n // The ref keeps it stable across re-renders.\n if (!scopedContainerRef.current) {\n scopedContainerRef.current = createScope()\n }\n\n useEffect(() => {\n isMountedRef.current = true\n // React re-ran the effect after the scope was disposed (an `<Activity>`\n // shown again): the old scope is gone for good, so start a new one.\n if (isDisposedRef.current) {\n isDisposedRef.current = false\n scopedContainerRef.current = createScopeRef.current()\n rerender()\n }\n return () => {\n isMountedRef.current = false\n // Disposal waits one microtask. StrictMode's simulated unmount is\n // followed by a re-mount in the same commit, which sets the flag again\n // and keeps the scope; a real unmount leaves it unset.\n queueMicrotask(() => {\n if (isMountedRef.current || isDisposedRef.current) {\n return\n }\n isDisposedRef.current = true\n void scopedContainerRef.current?.dispose()\n })\n }\n }, [])\n\n return jsx(ScopedContainerContext.Provider, {\n value: scopedContainerRef.current,\n children,\n })\n}\n","import { useContext } from 'react'\n\nimport type { ScopedContainer } from '@navios/di'\n\nimport { ScopedContainerContext } from '../container/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?.getMetadata('scopeId') as string | undefined) ?? 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","let nextId = 0\nconst objectIds = new WeakMap<object, number>()\n\n/** What the container compares by value, and JSON would leave out. */\nfunction replacer(_key: string, value: unknown): unknown {\n if (typeof value === 'bigint' || value instanceof RegExp) {\n return { [typeof value]: String(value) }\n }\n if (value instanceof Map || value instanceof Set) {\n return { [value.constructor.name]: Array.from(value as Iterable<unknown>) }\n }\n return value\n}\n\n/**\n * Key that identifies the args of a hook call. Args that serialize to the same\n * JSON share a key, so an object literal written in the call, or a function in\n * it, does not count as a change on every render.\n *\n * Args JSON cannot serialize, which contain themselves, are keyed by identity.\n */\nexport function getArgsKey(args: unknown): string {\n try {\n return JSON.stringify(args, replacer) ?? ''\n } catch {\n const object = args as object\n let id = objectIds.get(object)\n if (id === undefined) {\n id = ++nextId\n objectIds.set(object, id)\n }\n return `#${id}`\n }\n}\n","import { useCallback, useEffect, useMemo, useReducer, useRef, useState } from 'react'\n\nimport type {\n AnyInjectableType,\n BoundInjectionToken,\n ClassType,\n FactoryInjectionToken,\n InferInput,\n InjectionToken,\n MissingArgsError,\n ResolvedInstance,\n StandardSchemaV1,\n} from '@navios/di'\n\nimport { useContainer } from '../container/use-container.mjs'\n\nimport { getArgsKey } from './args-key.mjs'\n\nimport type { InitialSync } from './initial-sync.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>(state: ServiceState<T>, action: ServiceAction<T>): 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>(token: T): UseServiceResult<ResolvedInstance<T>>\n\n// #2 Token with required Schema\nexport function useService<T, S extends StandardSchemaV1>(\n token: InjectionToken<T, S>,\n args: InferInput<S>,\n): UseServiceResult<T>\n\n// #3 Token with optional Schema\nexport function useService<T, S extends StandardSchemaV1, R extends boolean>(\n token: InjectionToken<T, S, R>,\n): R extends false ? UseServiceResult<T> : MissingArgsError<S>\n\n// #4 Token with no Schema\nexport function useService<T>(token: InjectionToken<T, unknown>): UseServiceResult<T>\n\nexport function useService<T>(token: BoundInjectionToken<T, any>): UseServiceResult<T>\n\nexport function useService<T>(token: FactoryInjectionToken<T, any>): 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\n // Args that serialize the same are the same args: an object literal in the\n // call must not restart the hook on every render.\n const argsKey = getArgsKey(args)\n // oxlint-disable-next-line react-hooks/exhaustive-deps\n const stableArgs = useMemo(() => args, [argsKey])\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 // The ref remembers what it was read for, so the shortcut is only taken for\n // that container, token and args.\n const initialSyncRef = useRef<InitialSync | null | undefined>(undefined)\n\n if (initialSyncRef.current === undefined) {\n const instance = container.peek(token as InjectionToken<any, any>, args)\n initialSyncRef.current = instance === null ? null : { container, token, argsKey, instance }\n }\n\n const initialState: ServiceState<any> =\n initialSyncRef.current !== null\n ? { status: 'success', data: initialSyncRef.current.instance }\n : { status: 'idle' }\n\n const [state, dispatch] = useReducer(serviceReducer, initialState)\n const [refetchCounter, setRefetchCounter] = useState(0)\n\n // Subscribe to invalidation events\n useEffect(() => {\n let unsubscribe: (() => void) | undefined\n let isMounted = true\n\n // The container routes the listener to the store that owns the instance\n // (the root store for singletons, the scope's store for request-scoped).\n const subscribe = () => {\n if (unsubscribe) return\n unsubscribe = container.onInvalidate(token, stableArgs, () => {\n // Re-fetch when the service is invalidated\n if (!isMounted) return\n dispatch({ type: 'loading' })\n // Listeners run once the invalidation has finished, so resolving here\n // builds the service once. The microtask only keeps the resolution out\n // of the container's notification loop.\n queueMicrotask(() => {\n if (isMounted) {\n void fetchAndSubscribe()\n }\n })\n })\n }\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 stableArgs as any,\n )\n\n if (!isMounted) return\n\n dispatch({ type: 'success', data: instance })\n\n // Set up subscription after we have the instance\n subscribe()\n } catch (error) {\n if (isMounted) {\n dispatch({ type: 'error', error: error as Error })\n }\n }\n }\n\n // If the instance read during the first render is still the one asked\n // for, just set up the subscription. Otherwise, fetch async.\n const initial = initialSyncRef.current\n if (\n initial != null &&\n initial.container === container &&\n initial.token === token &&\n initial.argsKey === argsKey &&\n refetchCounter === 0\n ) {\n subscribe()\n } else {\n initialSyncRef.current = null\n dispatch({ type: 'loading' })\n void fetchAndSubscribe()\n }\n\n return () => {\n isMounted = false\n unsubscribe?.()\n }\n }, [container, token, stableArgs, argsKey, 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 { useCallback, useEffect, useRef, useSyncExternalStore } from 'react'\n\nimport type {\n BoundInjectionToken,\n ClassType,\n Container,\n FactoryInjectionToken,\n InferInput,\n InjectionToken,\n MissingArgsError,\n ResolvedInstance,\n ScopedContainer,\n StandardSchemaV1,\n} from '@navios/di'\n\nimport { useContainer } from '../container/use-container.mjs'\n\nimport { getArgsKey } from './args-key.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 unsubscribe: (() => void) | undefined\n}\n\ntype AnyContainer = Container | ScopedContainer\ntype AnyToken =\n | ClassType\n | InjectionToken<any, any>\n | BoundInjectionToken<any, any>\n | FactoryInjectionToken<any, any>\n\n// Global cache for service instances: container -> token object -> args key.\n// Tokens have no ids, so the token object itself (class, token, or the\n// Bound/Factory wrapper) is the identity.\nconst cacheMap = new WeakMap<object, WeakMap<object, Map<string, CacheEntry<any>>>>()\n\nfunction getCache(container: object, token: object): Map<string, CacheEntry<any>> {\n let byToken = cacheMap.get(container)\n if (!byToken) {\n byToken = new WeakMap()\n cacheMap.set(container, byToken)\n }\n let cache = byToken.get(token)\n if (!cache) {\n cache = new Map()\n byToken.set(token, 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 container: AnyContainer,\n token: AnyToken,\n args: unknown,\n): void {\n if (entry.unsubscribe) return\n\n entry.unsubscribe = container.onInvalidate(token, args, () => {\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>(token: T): ResolvedInstance<T>\n\n// #2 Token with required Schema\nexport function useSuspenseService<T, S extends StandardSchemaV1>(\n token: InjectionToken<T, S>,\n args: InferInput<S>,\n): T\n\n// #3 Token with optional Schema\nexport function useSuspenseService<T, S extends StandardSchemaV1, R extends boolean>(\n token: InjectionToken<T, S, R>,\n): R extends false ? T : MissingArgsError<S>\n\n// #4 Token with no Schema\nexport function useSuspenseService<T>(token: InjectionToken<T, unknown>): 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 cache = getCache(container, token)\n const cacheKey = getArgsKey(args)\n const entryRef = useRef<CacheEntry<any> | null>(null)\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.peek(token as InjectionToken<any, any>, args)\n\n const entry: CacheEntry<any> = {\n promise: null,\n result: syncInstance !== null ? syncInstance : undefined,\n error: undefined,\n status: syncInstance !== null ? 'resolved' : 'pending',\n version: 0,\n subscribers: new Set(),\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\n // Subscribe to invalidation events if not already subscribed\n setupInvalidationSubscription(currentEntry, container, token, args)\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, 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 (currentEntry && currentEntry.status === 'resolved' && !currentEntry.unsubscribe) {\n setupInvalidationSubscription(currentEntry, container, token, args)\n }\n }, [container, token, args, 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 { DIError, DIErrorCode } from '@navios/di'\nimport { useCallback, useEffect, useMemo, useReducer, useRef } from 'react'\n\nimport type {\n AnyInjectableType,\n BoundInjectionToken,\n ClassType,\n FactoryInjectionToken,\n InferInput,\n InjectionToken,\n MissingArgsError,\n ResolvedInstance,\n StandardSchemaV1,\n} from '@navios/di'\n\nimport { useContainer } from '../container/use-container.mjs'\n\nimport { getArgsKey } from './args-key.mjs'\n\nimport type { InitialSync } from './initial-sync.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<ResolvedInstance<T>>\n\n// #2 Token with required Schema\nexport function useOptionalService<T, S extends StandardSchemaV1>(\n token: InjectionToken<T, S>,\n args: InferInput<S>,\n): UseOptionalServiceResult<T>\n\n// #3 Token with optional Schema\nexport function useOptionalService<T, S extends StandardSchemaV1, R extends boolean>(\n token: InjectionToken<T, S, R>,\n): R extends false ? UseOptionalServiceResult<T> : MissingArgsError<S>\n\n// #4 Token with no Schema\nexport function useOptionalService<T>(\n token: InjectionToken<T, unknown>,\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\n // Args that serialize the same are the same args: an object literal in the\n // call must not restart the hook on every render.\n const argsKey = getArgsKey(args)\n // oxlint-disable-next-line react-hooks/exhaustive-deps\n const stableArgs = useMemo(() => args, [argsKey])\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 // The ref remembers what it was read for, so the shortcut is only taken for\n // that container, token and args.\n const initialSyncRef = useRef<InitialSync | null | undefined>(undefined)\n\n if (initialSyncRef.current === undefined) {\n let instance: unknown = null\n try {\n instance = container.peek(token as InjectionToken<any, any>, args)\n } catch {\n // Service not registered, leave as null\n }\n initialSyncRef.current = instance === null ? null : { container, token, argsKey, instance }\n }\n\n const initialState: OptionalServiceState<any> =\n initialSyncRef.current !== null\n ? { status: 'success', data: initialSyncRef.current.instance }\n : { status: 'idle' }\n\n const [state, dispatch] = useReducer(optionalServiceReducer, initialState)\n\n // Resolves to true when the service was loaded\n const fetchService = useCallback(async (): Promise<boolean> => {\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 stableArgs as any,\n )\n dispatch({ type: 'success', data: instance })\n return true\n } catch (error) {\n if (\n error instanceof DIError &&\n error.code === DIErrorCode.ProviderNotFound &&\n // It may be something the service depends on.\n !container.isRegistered(token)\n ) {\n dispatch({ type: 'not-found' })\n } else {\n dispatch({ type: 'error', error: error as Error })\n }\n return false\n }\n }, [container, token, stableArgs])\n\n // Subscribe to invalidation events\n useEffect(() => {\n let unsubscribe: (() => void) | undefined\n let isMounted = true\n\n const subscribe = () => {\n if (unsubscribe || !isMounted) return\n unsubscribe = container.onInvalidate(token, stableArgs, () => {\n // Re-fetch when the service is invalidated\n dispatch({ type: 'loading' })\n // Listeners run once the invalidation has finished, so resolving here\n // builds the service once. The microtask only keeps the resolution out\n // of the container's notification loop.\n queueMicrotask(() => {\n if (isMounted) {\n void fetchService()\n }\n })\n })\n }\n\n // If the instance read during the first render is still the one asked\n // for, just set up the subscription. Otherwise, fetch async.\n const initial = initialSyncRef.current\n if (\n initial != null &&\n initial.container === container &&\n initial.token === token &&\n initial.argsKey === argsKey\n ) {\n subscribe()\n } else {\n initialSyncRef.current = null\n void fetchService().then((loaded) => {\n if (loaded) {\n subscribe()\n }\n })\n }\n\n return () => {\n isMounted = false\n unsubscribe?.()\n }\n }, [fetchService, container, token, stableArgs, argsKey])\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 { useCallback } from 'react'\n\nimport { useContainer } from '../container/use-container.mjs'\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"],"mappings":";;;;;;;;AAQA,MAAa,mBAAmB,cAAgC,IAAI;;;;;AAMpE,MAAa,yBAAyB,cAAsC,IAAI;;ACFhF,SAAgB,kBAAkB,EAAE,WAAW,YAAoC;CACjF,OAAO,IAAI,iBAAiB,UAAU;EAAE,OAAO;EAAW;CAAS,CAAC;AACtE;;;;;;;;;;;;ACEA,SAAgB,eAA4C;CAC1D,MAAM,kBAAkB,WAAW,sBAAsB;CACzD,MAAM,YAAY,WAAW,gBAAgB;CAG7C,IAAI,iBACF,OAAO;CAGT,IAAI,CAAC,WACH,MAAM,IAAI,MAAM,sDAAsD;CAGxE,OAAO;AACT;;;;;;;;;AAUA,SAAgB,mBAA8B;CAC5C,MAAM,YAAY,WAAW,gBAAgB;CAE7C,IAAI,CAAC,WACH,MAAM,IAAI,MAAM,0DAA0D;CAG5E,OAAO;AACT;;;;;;;;;;;;;;;;;;;;;;;;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I;EACJ,IAAI,YAAY;EAEhB,MAAM,kBAAkB;GACtB,IAAI,eAAe,CAAC,WAAW;GAC/B,cAAc,UAAU,aAAa,OAAO,kBAAkB;IAE5D,SAAS,EAAE,MAAM,UAAU,CAAC;IAI5B,qBAAqB;KACnB,IAAI,WACG,aAAa;IAEtB,CAAC;GACH,CAAC;EACH;EAIA,MAAM,UAAU,eAAe;EAC/B,IACE,WAAW,QACX,QAAQ,cAAc,aACtB,QAAQ,UAAU,SAClB,QAAQ,YAAY,SAEpB,UAAU;OACL;GACL,eAAe,UAAU;GACpB,aAAa,CAAC,CAAC,MAAM,WAAW;IACnC,IAAI,QACF,UAAU;GAEd,CAAC;EACH;EAEA,aAAa;GACX,YAAY;GACZ,cAAc;EAChB;CACF,GAAG;EAAC;EAAc;EAAW;EAAO;EAAY;CAAO,CAAC;CAExD,OAAO;EACL,MAAM,MAAM,WAAW,YAAY,MAAM,OAAO,KAAA;EAChD,OAAO,MAAM,WAAW,UAAU,MAAM,QAAQ,KAAA;EAChD,WAAW,MAAM,WAAW;EAC5B,WAAW,MAAM,WAAW;EAC5B,YAAY,MAAM,WAAW;EAC7B,SAAS,MAAM,WAAW;EAC1B,SAAS;CACX;AACF;;;;;;;;;;;;;;;;;;;;;;;;;;;;;ACvOA,SAAgB,wBAA8D;CAC5E,MAAM,YAAY,aAAa;CAE/B,OAAO,YACL,OAAO,aAAsB;EAC3B,MAAM,UAAU,WAAW,QAAQ;CACrC,GACA,CAAC,SAAS,CACZ;AACF"}
|
|
1
|
+
{"version":3,"file":"index.mjs","names":[],"sources":["../src/container/context.mts","../src/container/container-provider.mts","../src/container/use-container.mts","../src/scope/scope-provider.mts","../src/scope/use-scope.mts","../src/service/args-key.mts","../src/service/use-resolved-service.mts","../src/service/use-service.mts","../src/service/use-suspense-service.mts","../src/service/use-optional-service.mts","../src/service/use-invalidate-instance.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 { jsx } from 'react/jsx-runtime'\n\nimport type { Container } from '@navios/di'\nimport type { ReactNode } from 'react'\n\nimport { ContainerContext } from './context.mjs'\n\nexport interface ContainerProviderProps {\n container: Container\n children: ReactNode\n}\n\nexport function ContainerProvider({ container, children }: ContainerProviderProps) {\n return jsx(ContainerContext.Provider, { value: container, children })\n}\n","import { useContext } from 'react'\n\nimport type { Container, ScopedContainer } from '@navios/di'\n\nimport { ContainerContext, ScopedContainerContext } from './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(): Container | ScopedContainer {\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","import { useContext, useEffect, useId, useReducer, useRef } from 'react'\nimport { jsx } from 'react/jsx-runtime'\n\nimport type { ScopedContainer } from '@navios/di'\nimport type { ReactNode } from 'react'\n\nimport { ContainerContext, ScopedContainerContext } from '../container/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 scope.\n * The key `scopeId` is reserved: it always holds the effective scope ID.\n * Can be used to pass data like user info, request headers, etc.\n */\n metadata?: Record<string, unknown>\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({ scopeId, metadata, children }: 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 // True between an effect setup and its cleanup.\n const isMountedRef = useRef(false)\n // True once the scope in the ref has been disposed.\n const isDisposedRef = useRef(false)\n const [, rerender] = useReducer((count: number) => count + 1, 0)\n\n // DI scopes have no ids, so the effective scope id lives in the scope's\n // metadata under `scopeId`.\n const createScope = () => container.createScope({ ...metadata, scopeId: effectiveScopeId })\n const createScopeRef = useRef(createScope)\n createScopeRef.current = createScope\n\n // Create the ScopedContainer once per mounted provider.\n // The ref keeps it stable across re-renders.\n if (!scopedContainerRef.current) {\n scopedContainerRef.current = createScope()\n }\n\n useEffect(() => {\n isMountedRef.current = true\n // React re-ran the effect after the scope was disposed (an `<Activity>`\n // shown again): the old scope is gone for good, so start a new one.\n if (isDisposedRef.current) {\n isDisposedRef.current = false\n scopedContainerRef.current = createScopeRef.current()\n rerender()\n }\n return () => {\n isMountedRef.current = false\n // Disposal waits one microtask. StrictMode's simulated unmount is\n // followed by a re-mount in the same commit, which sets the flag again\n // and keeps the scope; a real unmount leaves it unset.\n queueMicrotask(() => {\n if (isMountedRef.current || isDisposedRef.current) {\n return\n }\n isDisposedRef.current = true\n void scopedContainerRef.current?.dispose()\n })\n }\n }, [])\n\n return jsx(ScopedContainerContext.Provider, {\n value: scopedContainerRef.current,\n children,\n })\n}\n","import { useContext } from 'react'\n\nimport type { ScopedContainer } from '@navios/di'\n\nimport { ScopedContainerContext } from '../container/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?.getMetadata('scopeId') as string | undefined) ?? 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","let nextId = 0\nconst objectIds = new WeakMap<object, number>()\n\n/** What the container compares by value, and JSON would leave out. */\nfunction replacer(_key: string, value: unknown): unknown {\n if (typeof value === 'bigint' || value instanceof RegExp) {\n return { [typeof value]: String(value) }\n }\n if (value instanceof Map || value instanceof Set) {\n return { [value.constructor.name]: Array.from(value as Iterable<unknown>) }\n }\n return value\n}\n\n/**\n * Key that identifies the args of a hook call. Args that serialize to the same\n * JSON share a key, so an object literal written in the call, or a function in\n * it, does not count as a change on every render.\n *\n * Args JSON cannot serialize, which contain themselves, are keyed by identity.\n */\nexport function getArgsKey(args: unknown): string {\n try {\n return JSON.stringify(args, replacer) ?? ''\n } catch {\n const object = args as object\n let id = objectIds.get(object)\n if (id === undefined) {\n id = ++nextId\n objectIds.set(object, id)\n }\n return `#${id}`\n }\n}\n","import { DIError, DIErrorCode } from '@navios/di'\nimport { useCallback, useEffect, useMemo, useRef, useState } from 'react'\n\nimport type { AnyInjectableType, Container, InjectionToken, ScopedContainer } from '@navios/di'\n\nimport { useContainer } from '../container/use-container.mjs'\n\nimport { getArgsKey } from './args-key.mjs'\n\nimport type { AnyServiceToken, UseServiceResult } from './types.mjs'\n\nexport type ResolvedServiceState<T> =\n | { status: 'loading' }\n | { status: 'success'; data: T }\n | { status: 'not-found' }\n | { status: 'error'; error: Error }\n\n// One object each, so setting a state the hook is already in does not render.\nconst LOADING: ResolvedServiceState<never> = { status: 'loading' }\nconst NOT_FOUND: ResolvedServiceState<never> = { status: 'not-found' }\n\n/**\n * The instance read synchronously during the first render, with the\n * container, token and args it was read for.\n */\ninterface InitialSync {\n container: object\n token: object\n argsKey: string\n instance: unknown\n}\n\ninterface ResolvedService<T> {\n state: ResolvedServiceState<T>\n refetch: () => void\n}\n\n/** Whether `error` says that `token` itself has no provider. */\nfunction isMissingProvider(\n container: Container | ScopedContainer,\n token: AnyServiceToken,\n error: unknown,\n): boolean {\n return (\n error instanceof DIError &&\n error.code === DIErrorCode.ProviderNotFound &&\n // It may be something the service depends on.\n !container.isRegistered(token)\n )\n}\n\n/** What the container holds for `token` and `args` now, or `null`. */\nfunction peekInstance(\n container: Container | ScopedContainer,\n token: AnyServiceToken,\n args: unknown,\n): unknown {\n try {\n return container.peek(token as InjectionToken<any, any>, args)\n } catch {\n // A token the container cannot read, an alias cycle or args that contain\n // themselves. The resolution in the effect reports the error.\n return null\n }\n}\n\n/**\n * Resolution behind `useService` and `useOptionalService`. With `optional`,\n * a token without a provider ends in `not-found` instead of `error`.\n */\nexport function useResolvedService(\n token: AnyServiceToken,\n args: unknown,\n { optional }: { optional: boolean },\n): ResolvedService<any> {\n // useContainer returns ScopedContainer if inside ScopeProvider, otherwise Container\n // This automatically handles request-scoped services correctly\n const container = useContainer()\n\n // Args that serialize the same are the same args: an object literal in the\n // call must not restart the hook on every render.\n const argsKey = getArgsKey(args)\n // oxlint-disable-next-line react-hooks/exhaustive-deps\n const stableArgs = useMemo(() => args, [argsKey])\n\n // An instance the container already holds is returned by the first render,\n // without a loading state. The ref remembers what it was read for, so the\n // shortcut is only taken for that container, token and args.\n const initialSyncRef = useRef<InitialSync | null | undefined>(undefined)\n\n if (initialSyncRef.current === undefined) {\n const instance = peekInstance(container, token, args)\n initialSyncRef.current = instance === null ? null : { container, token, argsKey, instance }\n }\n\n const [state, setState] = useState<ResolvedServiceState<any>>(() =>\n initialSyncRef.current ? { status: 'success', data: initialSyncRef.current.instance } : LOADING,\n )\n const [refetchCount, setRefetchCount] = useState(0)\n\n useEffect(() => {\n // False once the container, token or args change, refetch is called or\n // the component unmounts: a resolution started by this run is then stale.\n let isCurrent = true\n let unsubscribe: (() => void) | undefined\n // The resolution whose result counts: the one started last, unless the\n // instance was invalidated since.\n let latest = 0\n\n // The container routes the listener to the store that owns the instance\n // (the root store for singletons, the scope's store for request-scoped).\n const subscribe = () => {\n if (unsubscribe) return\n unsubscribe = container.onInvalidate(token, stableArgs, () => {\n if (!isCurrent) return\n // What a resolution in flight is about to return may be the instance\n // that is gone.\n latest++\n setState(LOADING)\n // Listeners run once the invalidation has finished, so resolving here\n // builds the service once. The microtask only keeps the resolution out\n // of the container's notification loop.\n queueMicrotask(() => {\n if (isCurrent) {\n void resolve()\n }\n })\n })\n }\n\n const resolve = async () => {\n const run = ++latest\n try {\n // Before the instance is asked for: an invalidation between its\n // resolution and a subscription made afterwards would be missed.\n subscribe()\n } catch {\n // The resolution reports what is wrong with the token.\n }\n try {\n const instance = await container.get(\n // @ts-expect-error - token is valid\n token as AnyInjectableType,\n stableArgs as any,\n )\n if (!isCurrent || run !== latest) return\n setState({ status: 'success', data: instance })\n subscribe()\n } catch (error) {\n if (!isCurrent || run !== latest) return\n setState(\n optional && isMissingProvider(container, token, error)\n ? NOT_FOUND\n : { status: 'error', error: error as Error },\n )\n }\n }\n\n // If the instance read during the first render is still the one asked\n // for, just set up the subscription. Otherwise, resolve. So too when it\n // was destroyed between that render and this effect, which no listener\n // was there to see.\n const initial = initialSyncRef.current\n if (\n initial &&\n initial.container === container &&\n initial.token === token &&\n initial.argsKey === argsKey &&\n refetchCount === 0\n ) {\n subscribe()\n if (peekInstance(container, token, stableArgs) !== initial.instance) {\n initialSyncRef.current = null\n setState(LOADING)\n void resolve()\n }\n } else {\n initialSyncRef.current = null\n setState(LOADING)\n void resolve()\n }\n\n return () => {\n isCurrent = false\n unsubscribe?.()\n }\n }, [container, token, stableArgs, argsKey, refetchCount, optional])\n\n const refetch = useCallback(() => {\n setRefetchCount((count) => count + 1)\n }, [])\n\n return { state, refetch }\n}\n\n/** The result object of `useService` for a state. */\nexport function serviceResult<T>(\n state: ResolvedServiceState<T>,\n refetch: () => void,\n): UseServiceResult<T> {\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 { serviceResult, useResolvedService } from './use-resolved-service.mjs'\n\nimport type { AnyServiceToken, ServiceHook, UseServiceResult } from './types.mjs'\n\n/**\n * Hook to load a service from the DI container, with its loading and error\n * state. Resolves again when the instance is invalidated.\n *\n * @example\n * ```tsx\n * function UserCard() {\n * const { data: users, error } = useService(UserService)\n *\n * if (error) return <p>{error.message}</p>\n * if (!users) return <p>Loading…</p>\n *\n * return <UserList users={users} />\n * }\n * ```\n */\nexport const useService = function useService(\n token: AnyServiceToken,\n args?: unknown,\n): UseServiceResult<any> {\n const { state, refetch } = useResolvedService(token, args, { optional: false })\n return serviceResult(state, refetch)\n} as ServiceHook<'service'>\n","import { useCallback, useSyncExternalStore } from 'react'\n\nimport type { Container, InjectionToken, ScopedContainer } from '@navios/di'\n\nimport { useContainer } from '../container/use-container.mjs'\n\nimport { getArgsKey } from './args-key.mjs'\n\nimport type { AnyServiceToken, ServiceHook } from './types.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 unsubscribe: (() => void) | undefined\n // The timer after which a rejected entry leaves the cache\n eviction: ReturnType<typeof setTimeout> | undefined\n // The timer after which an entry no component shows leaves the cache\n release: ReturnType<typeof setTimeout> | undefined\n // How many renders read the entry\n renders: number\n}\n\ntype AnyContainer = Container | ScopedContainer\ntype Cache = Map<string, CacheEntry<any>>\n\n// Global cache for service instances: container -> token object -> args key.\n// Tokens have no ids, so the token object itself (class, token, or the\n// Bound/Factory wrapper) is the identity.\nconst cacheMap = new WeakMap<object, WeakMap<object, Cache>>()\n\nfunction getCache(container: object, token: object): Cache {\n let byToken = cacheMap.get(container)\n if (!byToken) {\n byToken = new WeakMap()\n cacheMap.set(container, byToken)\n }\n let cache = byToken.get(token)\n if (!cache) {\n cache = new Map()\n byToken.set(token, cache)\n }\n return cache\n}\n\n/**\n * The cache entry for `key`, created on first use. An instance the container\n * already holds makes it resolved, so the first render does not suspend. The\n * entry listens for the invalidation of that instance from the start: an\n * effect would subscribe after the render, and miss one in between.\n */\nfunction getEntry(\n cache: Cache,\n key: string,\n container: AnyContainer,\n token: AnyServiceToken,\n args: unknown,\n): CacheEntry<any> {\n let entry = cache.get(key)\n if (!entry) {\n const syncInstance = container.peek(token as InjectionToken<any, any>, args)\n entry = {\n promise: null,\n result: syncInstance !== null ? syncInstance : undefined,\n error: undefined,\n status: syncInstance !== null ? 'resolved' : 'pending',\n version: 0,\n subscribers: new Set(),\n unsubscribe: undefined,\n eviction: undefined,\n release: undefined,\n renders: 0,\n }\n cache.set(key, entry)\n if (syncInstance !== null) {\n setupInvalidationSubscription(entry, container, token, args)\n }\n }\n return entry\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 container: AnyContainer,\n token: AnyServiceToken,\n args: unknown,\n): void {\n if (entry.unsubscribe) return\n\n entry.unsubscribe = container.onInvalidate(token, args, () => {\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\nfunction fetchService(\n entry: CacheEntry<any>,\n container: AnyContainer,\n token: AnyServiceToken,\n args: unknown,\n): void {\n entry.status = 'pending'\n entry.version++ // Increment version to signal change to useSyncExternalStore\n entry.promise = (container.get as any)(token, args)\n .then((instance: unknown) => {\n entry.result = instance\n entry.status = 'resolved'\n\n // Subscribe to invalidation events if not already subscribed\n setupInvalidationSubscription(entry, container, token, args)\n\n // Notify subscribers\n entry.subscribers.forEach((callback) => callback())\n return instance\n })\n .catch((error: Error) => {\n entry.error = error\n entry.status = 'rejected'\n throw error\n })\n}\n\n/**\n * Drops a rejected entry two timer turns after the last render that threw its\n * error. Every render until then throws the error again: React renders a\n * failed component a second time before it shows the error boundary, and when\n * the first of those renders used up its time slice, the second one runs in a\n * later task. That task is queued before the second timer is, so it still\n * finds the entry; with one turn it found the cache empty and resolved the\n * service again. The next render after that, such as the one of an error\n * boundary reset, resolves the service again.\n */\nfunction evictAfterRender(cache: Cache, key: string, entry: CacheEntry<any>): void {\n clearTimeout(entry.eviction)\n entry.eviction = setTimeout(() => {\n entry.eviction = setTimeout(() => {\n if (cache.get(key) === entry && entry.status === 'rejected') {\n cache.delete(key)\n entry.unsubscribe?.()\n }\n }, 0)\n }, 0)\n}\n\n/**\n * Drops a resolved entry, and its invalidation listener, one timer turn after\n * its last subscriber left, unless a component subscribed or rendered with it\n * in the meantime. A component that shows the service later reads the instance\n * from the container again.\n */\nfunction releaseWhenUnused(cache: Cache, key: string, entry: CacheEntry<any>): void {\n clearTimeout(entry.release)\n const renders = entry.renders\n entry.release = setTimeout(() => {\n if (\n cache.get(key) === entry &&\n entry.status === 'resolved' &&\n entry.subscribers.size === 0 &&\n entry.renders === renders\n ) {\n cache.delete(key)\n entry.unsubscribe?.()\n entry.unsubscribe = undefined\n }\n }, 0)\n}\n\n/**\n * Hook that returns a service from the DI container and suspends while it is\n * resolved. A failed resolution is thrown to the nearest error boundary.\n * Resolves again, suspending, when the instance is invalidated.\n */\nexport const useSuspenseService = function useSuspenseService(\n token: AnyServiceToken,\n args?: unknown,\n): any {\n // useContainer returns ScopedContainer if inside ScopeProvider, otherwise Container\n const container = useContainer()\n const cache = getCache(container, token)\n const cacheKey = getArgsKey(args)\n const entry = getEntry(cache, cacheKey, container, token, args)\n entry.renders++\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 if (entry.subscribers.size === 0) {\n releaseWhenUnused(cache, cacheKey, entry)\n }\n }\n },\n [cache, cacheKey, 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 // Start fetching if not already\n if (entry.status === 'pending' && !entry.promise) {\n fetchService(entry, container, token, args)\n }\n\n // Suspense behavior\n if (entry.status === 'pending') {\n throw entry.promise\n }\n\n if (entry.status === 'rejected') {\n // A later render tries again\n evictAfterRender(cache, cacheKey, entry)\n throw entry.error\n }\n\n return entry.result\n} as ServiceHook<'suspense'>\n","import { serviceResult, useResolvedService } from './use-resolved-service.mjs'\n\nimport type { AnyServiceToken, ServiceHook, UseOptionalServiceResult } from './types.mjs'\n\n/**\n * Hook to optionally load a service from the DI container.\n *\n * Unlike useService, a token without a provider is not an error: the hook\n * returns `isNotFound: true` instead.\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 const useOptionalService = function useOptionalService(\n token: AnyServiceToken,\n args?: unknown,\n): UseOptionalServiceResult<any> {\n const { state, refetch } = useResolvedService(token, args, { optional: true })\n return { ...serviceResult(state, refetch), isNotFound: state.status === 'not-found' }\n} as ServiceHook<'optional'>\n","import { useCallback } from 'react'\n\nimport { useContainer } from '../container/use-container.mjs'\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"],"mappings":";;;;;;;;AAQA,MAAa,mBAAmB,cAAgC,IAAI;;;;;AAMpE,MAAa,yBAAyB,cAAsC,IAAI;;ACFhF,SAAgB,kBAAkB,EAAE,WAAW,YAAoC;CACjF,OAAO,IAAI,iBAAiB,UAAU;EAAE,OAAO;EAAW;CAAS,CAAC;AACtE;;;;;;;;;;;;ACEA,SAAgB,eAA4C;CAC1D,MAAM,kBAAkB,WAAW,sBAAsB;CACzD,MAAM,YAAY,WAAW,gBAAgB;CAG7C,IAAI,iBACF,OAAO;CAGT,IAAI,CAAC,WACH,MAAM,IAAI,MAAM,sDAAsD;CAGxE,OAAO;AACT;;;;;;;;;AAUA,SAAgB,mBAA8B;CAC5C,MAAM,YAAY,WAAW,gBAAgB;CAE7C,IAAI,CAAC,WACH,MAAM,IAAI,MAAM,0DAA0D;CAG5E,OAAO;AACT;;;;;;;;;;;;;;;;;;;;;;;;ACHA,SAAgB,cAAc,EAAE,SAAS,UAAU,YAAgC;CACjF,MAAM,YAAY,WAAW,gBAAgB;CAC7C,IAAI,CAAC,WACH,MAAM,IAAI,MAAM,uDAAuD;CAGzE,MAAM,cAAc,MAAM;CAC1B,MAAM,mBAAmB,WAAW;CACpC,MAAM,qBAAqB,OAA+B,IAAI;CAE9D,MAAM,eAAe,OAAO,KAAK;CAEjC,MAAM,gBAAgB,OAAO,KAAK;CAClC,MAAM,GAAG,YAAY,YAAY,UA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
4
|
"license": "MIT",
|
|
5
5
|
"author": {
|
|
6
6
|
"name": "Oleksandr Hanzha",
|
|
@@ -41,7 +41,7 @@
|
|
|
41
41
|
"publish:next": "yarn npm publish --access public --tag next"
|
|
42
42
|
},
|
|
43
43
|
"devDependencies": {
|
|
44
|
-
"@navios/di": "^2.0.0-alpha.
|
|
44
|
+
"@navios/di": "^2.0.0-alpha.1",
|
|
45
45
|
"@testing-library/dom": "^10.4.2",
|
|
46
46
|
"@testing-library/react": "^16.3.3",
|
|
47
47
|
"@types/react": "^19.3.0",
|
|
@@ -52,7 +52,7 @@
|
|
|
52
52
|
"zod": "^4.6.7"
|
|
53
53
|
},
|
|
54
54
|
"peerDependencies": {
|
|
55
|
-
"@navios/di": "2.0.0-alpha.
|
|
55
|
+
"@navios/di": "2.0.0-alpha.1",
|
|
56
56
|
"react": "^18.0.0 || ^19.0.0"
|
|
57
57
|
}
|
|
58
58
|
}
|