@navios/di-react 1.0.0-alpha.3 → 2.0.0-alpha.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +21 -0
- package/README.md +45 -665
- package/lib/{index.js → index.cjs} +249 -255
- package/lib/index.cjs.map +1 -0
- package/lib/{index.d.ts → index.d.cts} +94 -123
- package/lib/index.d.cts.map +1 -0
- package/lib/index.d.mts +93 -122
- package/lib/index.d.mts.map +1 -1
- package/lib/index.mjs +248 -255
- package/lib/index.mjs.map +1 -1
- package/package.json +32 -18
- package/coverage/base.css +0 -224
- package/coverage/block-navigation.js +0 -87
- package/coverage/clover.xml +0 -270
- package/coverage/coverage-final.json +0 -10
- package/coverage/favicon.png +0 -0
- package/coverage/hooks/index.html +0 -191
- package/coverage/hooks/use-container.mts.html +0 -268
- package/coverage/hooks/use-invalidate.mts.html +0 -208
- package/coverage/hooks/use-optional-service.mts.html +0 -910
- package/coverage/hooks/use-scope.mts.html +0 -346
- package/coverage/hooks/use-service.mts.html +0 -760
- package/coverage/hooks/use-suspense-service.mts.html +0 -784
- package/coverage/index.html +0 -131
- package/coverage/prettify.css +0 -1
- package/coverage/prettify.js +0 -2
- package/coverage/providers/container-provider.mts.html +0 -139
- package/coverage/providers/context.mts.html +0 -130
- package/coverage/providers/index.html +0 -146
- package/coverage/providers/scope-provider.mts.html +0 -355
- package/coverage/sort-arrow-sprite.png +0 -0
- package/coverage/sorter.js +0 -210
- package/lib/index.d.ts.map +0 -1
- package/lib/index.js.map +0 -1
- package/project.json +0 -61
- package/src/hooks/__tests__/use-container.spec.mts +0 -143
- package/src/hooks/__tests__/use-invalidate.spec.mts +0 -80
- package/src/hooks/__tests__/use-optional-service.spec.mts +0 -233
- package/src/hooks/__tests__/use-scope.spec.mts +0 -293
- package/src/hooks/__tests__/use-service.spec.mts +0 -212
- package/src/hooks/__tests__/use-suspense-service.spec.mts +0 -286
- package/src/hooks/index.mts +0 -14
- package/src/hooks/use-container.mts +0 -61
- package/src/hooks/use-invalidate.mts +0 -41
- package/src/hooks/use-optional-service.mts +0 -275
- package/src/hooks/use-scope.mts +0 -87
- package/src/hooks/use-service.mts +0 -225
- package/src/hooks/use-suspense-service.mts +0 -233
- package/src/index.mts +0 -8
- package/src/providers/__tests__/scope-provider.spec.mts +0 -366
- package/src/providers/container-provider.mts +0 -18
- package/src/providers/context.mts +0 -15
- package/src/providers/index.mts +0 -5
- package/src/providers/scope-provider.mts +0 -90
- package/src/types.mts +0 -21
- package/tsconfig.json +0 -13
- package/tsdown.config.mts +0 -14
- package/vitest.config.mts +0 -12
package/lib/index.mjs.map
CHANGED
|
@@ -1 +1 @@
|
|
|
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 { ScopedContainer } from '@navios/di'\nimport type { ReactNode } from 'react'\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 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 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 )\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, ScopedContainer } from '@navios/di'\n\nimport { useContext } from 'react'\n\nimport {\n ContainerContext,\n ScopedContainerContext,\n} 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(): 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\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\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.warn(`useService called with args that look the same but are different instances: ${JSON.stringify(argsRef.current)} !== ${JSON.stringify(args)}!\nThis is likely because you are using a value that is not memoized.\nPlease use a memoized value or use a different approach to pass the args.\nExample:\n const args = useMemo(() => ({ userId: '123' }), [])\n return useService(UserToken, args)`)\n }\n argsRef.current = args\n }\n }, [args])\n }\n\n // Subscribe to invalidation events\n useEffect(() => {\n const eventBus = rootContainer.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 = container.calculateInstanceName(token, args)\n if (instanceName) {\n instanceNameRef.current = instanceName\n }\n\n dispatch({ type: 'success', data: instance })\n\n // Set up subscription after we have the instance\n if (instanceName) {\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 }\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 = container.calculateInstanceName(token, args)\n if (instanceName) {\n instanceNameRef.current = instanceName\n unsubscribe = eventBus.on(instanceName, 'destroy', () => {\n if (isMounted) {\n dispatch({ type: 'loading' })\n void fetchAndSubscribe()\n }\n })\n }\n } else {\n dispatch({ type: 'loading' })\n void fetchAndSubscribe()\n }\n\n return () => {\n isMounted = false\n unsubscribe?.()\n }\n }, [container, rootContainer, 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 BoundInjectionToken,\n ClassType,\n Container,\n Factorable,\n FactoryInjectionToken,\n InjectionToken,\n InjectionTokenSchemaType,\n} from '@navios/di'\nimport type { z, ZodType } from 'zod/v4'\n\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 rootContainer: Container,\n): void {\n if (entry.unsubscribe || !entry.instanceName) return\n\n const eventBus = rootContainer.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 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.warn(`useSuspenseService called with args that look the same but are different instances: ${JSON.stringify(argsRef.current)} !== ${JSON.stringify(args)}!\nThis is likely because you are using a value that is not memoized.\nPlease use a memoized value or use a different approach to pass the args.\nExample:\n const args = useMemo(() => ({ userId: '123' }), [])\n return useSuspenseService(UserToken, args)`)\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 instanceName = container.calculateInstanceName(token, args)\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,\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, rootContainer)\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, rootContainer, 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, rootContainer)\n }\n }, [rootContainer, 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\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.warn(`useOptionalService called with args that look the same but are different instances: ${JSON.stringify(argsRef.current)} !== ${JSON.stringify(args)}!\nThis is likely because you are using a value that is not memoized.\nPlease use a memoized value or use a different approach to pass the args.\nExample:\n const args = useMemo(() => ({ userId: '123' }), [])\n return useOptionalService(UserToken, args)`)\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 // Get instance name for event subscription\n const instanceName = container.calculateInstanceName(token, args)\n if (instanceName) {\n instanceNameRef.current = instanceName\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, token, args])\n\n // Subscribe to invalidation events\n useEffect(() => {\n const eventBus = rootContainer.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 const instanceName = container.calculateInstanceName(token, args)\n if (instanceName) {\n instanceNameRef.current = instanceName\n unsubscribe = eventBus.on(instanceName, 'destroy', () => {\n // Re-fetch when the service is invalidated\n void fetchService()\n })\n }\n } else {\n void fetchService().then(() => {\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 return () => {\n unsubscribe?.()\n }\n }\n\n return () => {\n unsubscribe?.()\n }\n }, [fetchService, rootContainer, 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 { useCallback } from 'react'\n\nimport { useContainer } from './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","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;A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|
|
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;;;;;;;;;;;;;;;;;;;;;;;;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,UAAkB,QAAQ,GAAG,CAAC;CAI/D,MAAM,oBAAoB,UAAU,YAAY;EAAE,GAAG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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"}
|
package/package.json
CHANGED
|
@@ -1,23 +1,25 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@navios/di-react",
|
|
3
|
-
"version": "
|
|
3
|
+
"version": "2.0.0-alpha.0",
|
|
4
|
+
"license": "MIT",
|
|
4
5
|
"author": {
|
|
5
6
|
"name": "Oleksandr Hanzha",
|
|
6
7
|
"email": "alex@granted.name"
|
|
7
8
|
},
|
|
8
9
|
"repository": {
|
|
9
|
-
"directory": "packages/di-react",
|
|
10
10
|
"type": "git",
|
|
11
|
-
"url": "https://github.com/
|
|
12
|
-
|
|
13
|
-
"license": "MIT",
|
|
14
|
-
"peerDependencies": {
|
|
15
|
-
"@navios/di": "^1.0.0",
|
|
16
|
-
"react": "^18.0.0 || ^19.0.0"
|
|
11
|
+
"url": "https://github.com/navios-org/navios.git",
|
|
12
|
+
"directory": "packages/di-react"
|
|
17
13
|
},
|
|
18
|
-
"
|
|
14
|
+
"files": [
|
|
15
|
+
"lib",
|
|
16
|
+
"README.md",
|
|
17
|
+
"CHANGELOG.md",
|
|
18
|
+
"LICENSE"
|
|
19
|
+
],
|
|
19
20
|
"main": "./lib/index.cjs",
|
|
20
21
|
"module": "./lib/index.mjs",
|
|
22
|
+
"typings": "./lib/index.d.mts",
|
|
21
23
|
"exports": {
|
|
22
24
|
".": {
|
|
23
25
|
"import": {
|
|
@@ -30,15 +32,27 @@
|
|
|
30
32
|
}
|
|
31
33
|
}
|
|
32
34
|
},
|
|
35
|
+
"scripts": {
|
|
36
|
+
"check": "tsc -b",
|
|
37
|
+
"lint": "yarn run -T oxlint --fix && yarn run -T oxfmt",
|
|
38
|
+
"test:ci": "vitest run",
|
|
39
|
+
"build": "tsdown",
|
|
40
|
+
"publish": "node ../../scripts/assert-stable-version.mjs && yarn npm publish --access public",
|
|
41
|
+
"publish:next": "yarn npm publish --access public --tag next"
|
|
42
|
+
},
|
|
33
43
|
"devDependencies": {
|
|
34
|
-
"@navios/di": "^
|
|
35
|
-
"@testing-library/dom": "^10.4.
|
|
36
|
-
"@testing-library/react": "^16.3.
|
|
37
|
-
"@types/react": "^19.
|
|
38
|
-
"jsdom": "^
|
|
39
|
-
"react": "^19.
|
|
40
|
-
"react-dom": "^19.
|
|
41
|
-
"typescript": "^
|
|
42
|
-
"zod": "^4.
|
|
44
|
+
"@navios/di": "^2.0.0-alpha.0",
|
|
45
|
+
"@testing-library/dom": "^10.4.2",
|
|
46
|
+
"@testing-library/react": "^16.3.3",
|
|
47
|
+
"@types/react": "^19.3.0",
|
|
48
|
+
"jsdom": "^31.0.1",
|
|
49
|
+
"react": "^19.3.1",
|
|
50
|
+
"react-dom": "^19.3.1",
|
|
51
|
+
"typescript": "^7.0.2",
|
|
52
|
+
"zod": "^4.6.7"
|
|
53
|
+
},
|
|
54
|
+
"peerDependencies": {
|
|
55
|
+
"@navios/di": "2.0.0-alpha.0",
|
|
56
|
+
"react": "^18.0.0 || ^19.0.0"
|
|
43
57
|
}
|
|
44
58
|
}
|
package/coverage/base.css
DELETED
|
@@ -1,224 +0,0 @@
|
|
|
1
|
-
body, html {
|
|
2
|
-
margin:0; padding: 0;
|
|
3
|
-
height: 100%;
|
|
4
|
-
}
|
|
5
|
-
body {
|
|
6
|
-
font-family: Helvetica Neue, Helvetica, Arial;
|
|
7
|
-
font-size: 14px;
|
|
8
|
-
color:#333;
|
|
9
|
-
}
|
|
10
|
-
.small { font-size: 12px; }
|
|
11
|
-
*, *:after, *:before {
|
|
12
|
-
-webkit-box-sizing:border-box;
|
|
13
|
-
-moz-box-sizing:border-box;
|
|
14
|
-
box-sizing:border-box;
|
|
15
|
-
}
|
|
16
|
-
h1 { font-size: 20px; margin: 0;}
|
|
17
|
-
h2 { font-size: 14px; }
|
|
18
|
-
pre {
|
|
19
|
-
font: 12px/1.4 Consolas, "Liberation Mono", Menlo, Courier, monospace;
|
|
20
|
-
margin: 0;
|
|
21
|
-
padding: 0;
|
|
22
|
-
-moz-tab-size: 2;
|
|
23
|
-
-o-tab-size: 2;
|
|
24
|
-
tab-size: 2;
|
|
25
|
-
}
|
|
26
|
-
a { color:#0074D9; text-decoration:none; }
|
|
27
|
-
a:hover { text-decoration:underline; }
|
|
28
|
-
.strong { font-weight: bold; }
|
|
29
|
-
.space-top1 { padding: 10px 0 0 0; }
|
|
30
|
-
.pad2y { padding: 20px 0; }
|
|
31
|
-
.pad1y { padding: 10px 0; }
|
|
32
|
-
.pad2x { padding: 0 20px; }
|
|
33
|
-
.pad2 { padding: 20px; }
|
|
34
|
-
.pad1 { padding: 10px; }
|
|
35
|
-
.space-left2 { padding-left:55px; }
|
|
36
|
-
.space-right2 { padding-right:20px; }
|
|
37
|
-
.center { text-align:center; }
|
|
38
|
-
.clearfix { display:block; }
|
|
39
|
-
.clearfix:after {
|
|
40
|
-
content:'';
|
|
41
|
-
display:block;
|
|
42
|
-
height:0;
|
|
43
|
-
clear:both;
|
|
44
|
-
visibility:hidden;
|
|
45
|
-
}
|
|
46
|
-
.fl { float: left; }
|
|
47
|
-
@media only screen and (max-width:640px) {
|
|
48
|
-
.col3 { width:100%; max-width:100%; }
|
|
49
|
-
.hide-mobile { display:none!important; }
|
|
50
|
-
}
|
|
51
|
-
|
|
52
|
-
.quiet {
|
|
53
|
-
color: #7f7f7f;
|
|
54
|
-
color: rgba(0,0,0,0.5);
|
|
55
|
-
}
|
|
56
|
-
.quiet a { opacity: 0.7; }
|
|
57
|
-
|
|
58
|
-
.fraction {
|
|
59
|
-
font-family: Consolas, 'Liberation Mono', Menlo, Courier, monospace;
|
|
60
|
-
font-size: 10px;
|
|
61
|
-
color: #555;
|
|
62
|
-
background: #E8E8E8;
|
|
63
|
-
padding: 4px 5px;
|
|
64
|
-
border-radius: 3px;
|
|
65
|
-
vertical-align: middle;
|
|
66
|
-
}
|
|
67
|
-
|
|
68
|
-
div.path a:link, div.path a:visited { color: #333; }
|
|
69
|
-
table.coverage {
|
|
70
|
-
border-collapse: collapse;
|
|
71
|
-
margin: 10px 0 0 0;
|
|
72
|
-
padding: 0;
|
|
73
|
-
}
|
|
74
|
-
|
|
75
|
-
table.coverage td {
|
|
76
|
-
margin: 0;
|
|
77
|
-
padding: 0;
|
|
78
|
-
vertical-align: top;
|
|
79
|
-
}
|
|
80
|
-
table.coverage td.line-count {
|
|
81
|
-
text-align: right;
|
|
82
|
-
padding: 0 5px 0 20px;
|
|
83
|
-
}
|
|
84
|
-
table.coverage td.line-coverage {
|
|
85
|
-
text-align: right;
|
|
86
|
-
padding-right: 10px;
|
|
87
|
-
min-width:20px;
|
|
88
|
-
}
|
|
89
|
-
|
|
90
|
-
table.coverage td span.cline-any {
|
|
91
|
-
display: inline-block;
|
|
92
|
-
padding: 0 5px;
|
|
93
|
-
width: 100%;
|
|
94
|
-
}
|
|
95
|
-
.missing-if-branch {
|
|
96
|
-
display: inline-block;
|
|
97
|
-
margin-right: 5px;
|
|
98
|
-
border-radius: 3px;
|
|
99
|
-
position: relative;
|
|
100
|
-
padding: 0 4px;
|
|
101
|
-
background: #333;
|
|
102
|
-
color: yellow;
|
|
103
|
-
}
|
|
104
|
-
|
|
105
|
-
.skip-if-branch {
|
|
106
|
-
display: none;
|
|
107
|
-
margin-right: 10px;
|
|
108
|
-
position: relative;
|
|
109
|
-
padding: 0 4px;
|
|
110
|
-
background: #ccc;
|
|
111
|
-
color: white;
|
|
112
|
-
}
|
|
113
|
-
.missing-if-branch .typ, .skip-if-branch .typ {
|
|
114
|
-
color: inherit !important;
|
|
115
|
-
}
|
|
116
|
-
.coverage-summary {
|
|
117
|
-
border-collapse: collapse;
|
|
118
|
-
width: 100%;
|
|
119
|
-
}
|
|
120
|
-
.coverage-summary tr { border-bottom: 1px solid #bbb; }
|
|
121
|
-
.keyline-all { border: 1px solid #ddd; }
|
|
122
|
-
.coverage-summary td, .coverage-summary th { padding: 10px; }
|
|
123
|
-
.coverage-summary tbody { border: 1px solid #bbb; }
|
|
124
|
-
.coverage-summary td { border-right: 1px solid #bbb; }
|
|
125
|
-
.coverage-summary td:last-child { border-right: none; }
|
|
126
|
-
.coverage-summary th {
|
|
127
|
-
text-align: left;
|
|
128
|
-
font-weight: normal;
|
|
129
|
-
white-space: nowrap;
|
|
130
|
-
}
|
|
131
|
-
.coverage-summary th.file { border-right: none !important; }
|
|
132
|
-
.coverage-summary th.pct { }
|
|
133
|
-
.coverage-summary th.pic,
|
|
134
|
-
.coverage-summary th.abs,
|
|
135
|
-
.coverage-summary td.pct,
|
|
136
|
-
.coverage-summary td.abs { text-align: right; }
|
|
137
|
-
.coverage-summary td.file { white-space: nowrap; }
|
|
138
|
-
.coverage-summary td.pic { min-width: 120px !important; }
|
|
139
|
-
.coverage-summary tfoot td { }
|
|
140
|
-
|
|
141
|
-
.coverage-summary .sorter {
|
|
142
|
-
height: 10px;
|
|
143
|
-
width: 7px;
|
|
144
|
-
display: inline-block;
|
|
145
|
-
margin-left: 0.5em;
|
|
146
|
-
background: url(sort-arrow-sprite.png) no-repeat scroll 0 0 transparent;
|
|
147
|
-
}
|
|
148
|
-
.coverage-summary .sorted .sorter {
|
|
149
|
-
background-position: 0 -20px;
|
|
150
|
-
}
|
|
151
|
-
.coverage-summary .sorted-desc .sorter {
|
|
152
|
-
background-position: 0 -10px;
|
|
153
|
-
}
|
|
154
|
-
.status-line { height: 10px; }
|
|
155
|
-
/* yellow */
|
|
156
|
-
.cbranch-no { background: yellow !important; color: #111; }
|
|
157
|
-
/* dark red */
|
|
158
|
-
.red.solid, .status-line.low, .low .cover-fill { background:#C21F39 }
|
|
159
|
-
.low .chart { border:1px solid #C21F39 }
|
|
160
|
-
.highlighted,
|
|
161
|
-
.highlighted .cstat-no, .highlighted .fstat-no, .highlighted .cbranch-no{
|
|
162
|
-
background: #C21F39 !important;
|
|
163
|
-
}
|
|
164
|
-
/* medium red */
|
|
165
|
-
.cstat-no, .fstat-no, .cbranch-no, .cbranch-no { background:#F6C6CE }
|
|
166
|
-
/* light red */
|
|
167
|
-
.low, .cline-no { background:#FCE1E5 }
|
|
168
|
-
/* light green */
|
|
169
|
-
.high, .cline-yes { background:rgb(230,245,208) }
|
|
170
|
-
/* medium green */
|
|
171
|
-
.cstat-yes { background:rgb(161,215,106) }
|
|
172
|
-
/* dark green */
|
|
173
|
-
.status-line.high, .high .cover-fill { background:rgb(77,146,33) }
|
|
174
|
-
.high .chart { border:1px solid rgb(77,146,33) }
|
|
175
|
-
/* dark yellow (gold) */
|
|
176
|
-
.status-line.medium, .medium .cover-fill { background: #f9cd0b; }
|
|
177
|
-
.medium .chart { border:1px solid #f9cd0b; }
|
|
178
|
-
/* light yellow */
|
|
179
|
-
.medium { background: #fff4c2; }
|
|
180
|
-
|
|
181
|
-
.cstat-skip { background: #ddd; color: #111; }
|
|
182
|
-
.fstat-skip { background: #ddd; color: #111 !important; }
|
|
183
|
-
.cbranch-skip { background: #ddd !important; color: #111; }
|
|
184
|
-
|
|
185
|
-
span.cline-neutral { background: #eaeaea; }
|
|
186
|
-
|
|
187
|
-
.coverage-summary td.empty {
|
|
188
|
-
opacity: .5;
|
|
189
|
-
padding-top: 4px;
|
|
190
|
-
padding-bottom: 4px;
|
|
191
|
-
line-height: 1;
|
|
192
|
-
color: #888;
|
|
193
|
-
}
|
|
194
|
-
|
|
195
|
-
.cover-fill, .cover-empty {
|
|
196
|
-
display:inline-block;
|
|
197
|
-
height: 12px;
|
|
198
|
-
}
|
|
199
|
-
.chart {
|
|
200
|
-
line-height: 0;
|
|
201
|
-
}
|
|
202
|
-
.cover-empty {
|
|
203
|
-
background: white;
|
|
204
|
-
}
|
|
205
|
-
.cover-full {
|
|
206
|
-
border-right: none !important;
|
|
207
|
-
}
|
|
208
|
-
pre.prettyprint {
|
|
209
|
-
border: none !important;
|
|
210
|
-
padding: 0 !important;
|
|
211
|
-
margin: 0 !important;
|
|
212
|
-
}
|
|
213
|
-
.com { color: #999 !important; }
|
|
214
|
-
.ignore-none { color: #999; font-weight: normal; }
|
|
215
|
-
|
|
216
|
-
.wrapper {
|
|
217
|
-
min-height: 100%;
|
|
218
|
-
height: auto !important;
|
|
219
|
-
height: 100%;
|
|
220
|
-
margin: 0 auto -48px;
|
|
221
|
-
}
|
|
222
|
-
.footer, .push {
|
|
223
|
-
height: 48px;
|
|
224
|
-
}
|
|
@@ -1,87 +0,0 @@
|
|
|
1
|
-
/* eslint-disable */
|
|
2
|
-
var jumpToCode = (function init() {
|
|
3
|
-
// Classes of code we would like to highlight in the file view
|
|
4
|
-
var missingCoverageClasses = ['.cbranch-no', '.cstat-no', '.fstat-no'];
|
|
5
|
-
|
|
6
|
-
// Elements to highlight in the file listing view
|
|
7
|
-
var fileListingElements = ['td.pct.low'];
|
|
8
|
-
|
|
9
|
-
// We don't want to select elements that are direct descendants of another match
|
|
10
|
-
var notSelector = ':not(' + missingCoverageClasses.join('):not(') + ') > '; // becomes `:not(a):not(b) > `
|
|
11
|
-
|
|
12
|
-
// Selector that finds elements on the page to which we can jump
|
|
13
|
-
var selector =
|
|
14
|
-
fileListingElements.join(', ') +
|
|
15
|
-
', ' +
|
|
16
|
-
notSelector +
|
|
17
|
-
missingCoverageClasses.join(', ' + notSelector); // becomes `:not(a):not(b) > a, :not(a):not(b) > b`
|
|
18
|
-
|
|
19
|
-
// The NodeList of matching elements
|
|
20
|
-
var missingCoverageElements = document.querySelectorAll(selector);
|
|
21
|
-
|
|
22
|
-
var currentIndex;
|
|
23
|
-
|
|
24
|
-
function toggleClass(index) {
|
|
25
|
-
missingCoverageElements
|
|
26
|
-
.item(currentIndex)
|
|
27
|
-
.classList.remove('highlighted');
|
|
28
|
-
missingCoverageElements.item(index).classList.add('highlighted');
|
|
29
|
-
}
|
|
30
|
-
|
|
31
|
-
function makeCurrent(index) {
|
|
32
|
-
toggleClass(index);
|
|
33
|
-
currentIndex = index;
|
|
34
|
-
missingCoverageElements.item(index).scrollIntoView({
|
|
35
|
-
behavior: 'smooth',
|
|
36
|
-
block: 'center',
|
|
37
|
-
inline: 'center'
|
|
38
|
-
});
|
|
39
|
-
}
|
|
40
|
-
|
|
41
|
-
function goToPrevious() {
|
|
42
|
-
var nextIndex = 0;
|
|
43
|
-
if (typeof currentIndex !== 'number' || currentIndex === 0) {
|
|
44
|
-
nextIndex = missingCoverageElements.length - 1;
|
|
45
|
-
} else if (missingCoverageElements.length > 1) {
|
|
46
|
-
nextIndex = currentIndex - 1;
|
|
47
|
-
}
|
|
48
|
-
|
|
49
|
-
makeCurrent(nextIndex);
|
|
50
|
-
}
|
|
51
|
-
|
|
52
|
-
function goToNext() {
|
|
53
|
-
var nextIndex = 0;
|
|
54
|
-
|
|
55
|
-
if (
|
|
56
|
-
typeof currentIndex === 'number' &&
|
|
57
|
-
currentIndex < missingCoverageElements.length - 1
|
|
58
|
-
) {
|
|
59
|
-
nextIndex = currentIndex + 1;
|
|
60
|
-
}
|
|
61
|
-
|
|
62
|
-
makeCurrent(nextIndex);
|
|
63
|
-
}
|
|
64
|
-
|
|
65
|
-
return function jump(event) {
|
|
66
|
-
if (
|
|
67
|
-
document.getElementById('fileSearch') === document.activeElement &&
|
|
68
|
-
document.activeElement != null
|
|
69
|
-
) {
|
|
70
|
-
// if we're currently focused on the search input, we don't want to navigate
|
|
71
|
-
return;
|
|
72
|
-
}
|
|
73
|
-
|
|
74
|
-
switch (event.which) {
|
|
75
|
-
case 78: // n
|
|
76
|
-
case 74: // j
|
|
77
|
-
goToNext();
|
|
78
|
-
break;
|
|
79
|
-
case 66: // b
|
|
80
|
-
case 75: // k
|
|
81
|
-
case 80: // p
|
|
82
|
-
goToPrevious();
|
|
83
|
-
break;
|
|
84
|
-
}
|
|
85
|
-
};
|
|
86
|
-
})();
|
|
87
|
-
window.addEventListener('keydown', jumpToCode);
|