@navios/di-react 1.0.0-alpha.3 → 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.
Files changed (60) hide show
  1. package/CHANGELOG.md +47 -1
  2. package/README.md +45 -665
  3. package/lib/index.cjs +573 -0
  4. package/lib/index.cjs.map +1 -0
  5. package/lib/index.d.cts +262 -0
  6. package/lib/index.d.cts.map +1 -0
  7. package/lib/index.d.mts +159 -140
  8. package/lib/index.d.mts.map +1 -1
  9. package/lib/index.mjs +371 -381
  10. package/lib/index.mjs.map +1 -1
  11. package/package.json +32 -18
  12. package/coverage/base.css +0 -224
  13. package/coverage/block-navigation.js +0 -87
  14. package/coverage/clover.xml +0 -270
  15. package/coverage/coverage-final.json +0 -10
  16. package/coverage/favicon.png +0 -0
  17. package/coverage/hooks/index.html +0 -191
  18. package/coverage/hooks/use-container.mts.html +0 -268
  19. package/coverage/hooks/use-invalidate.mts.html +0 -208
  20. package/coverage/hooks/use-optional-service.mts.html +0 -910
  21. package/coverage/hooks/use-scope.mts.html +0 -346
  22. package/coverage/hooks/use-service.mts.html +0 -760
  23. package/coverage/hooks/use-suspense-service.mts.html +0 -784
  24. package/coverage/index.html +0 -131
  25. package/coverage/prettify.css +0 -1
  26. package/coverage/prettify.js +0 -2
  27. package/coverage/providers/container-provider.mts.html +0 -139
  28. package/coverage/providers/context.mts.html +0 -130
  29. package/coverage/providers/index.html +0 -146
  30. package/coverage/providers/scope-provider.mts.html +0 -355
  31. package/coverage/sort-arrow-sprite.png +0 -0
  32. package/coverage/sorter.js +0 -210
  33. package/lib/index.d.ts +0 -243
  34. package/lib/index.d.ts.map +0 -1
  35. package/lib/index.js +0 -582
  36. package/lib/index.js.map +0 -1
  37. package/project.json +0 -61
  38. package/src/hooks/__tests__/use-container.spec.mts +0 -143
  39. package/src/hooks/__tests__/use-invalidate.spec.mts +0 -80
  40. package/src/hooks/__tests__/use-optional-service.spec.mts +0 -233
  41. package/src/hooks/__tests__/use-scope.spec.mts +0 -293
  42. package/src/hooks/__tests__/use-service.spec.mts +0 -212
  43. package/src/hooks/__tests__/use-suspense-service.spec.mts +0 -286
  44. package/src/hooks/index.mts +0 -14
  45. package/src/hooks/use-container.mts +0 -61
  46. package/src/hooks/use-invalidate.mts +0 -41
  47. package/src/hooks/use-optional-service.mts +0 -275
  48. package/src/hooks/use-scope.mts +0 -87
  49. package/src/hooks/use-service.mts +0 -225
  50. package/src/hooks/use-suspense-service.mts +0 -233
  51. package/src/index.mts +0 -8
  52. package/src/providers/__tests__/scope-provider.spec.mts +0 -366
  53. package/src/providers/container-provider.mts +0 -18
  54. package/src/providers/context.mts +0 -15
  55. package/src/providers/index.mts +0 -5
  56. package/src/providers/scope-provider.mts +0 -90
  57. package/src/types.mts +0 -21
  58. package/tsconfig.json +0 -13
  59. package/tsdown.config.mts +0 -14
  60. package/vitest.config.mts +0 -12
@@ -0,0 +1,262 @@
1
+ import { BoundInjectionToken, ClassType, Container, FactoryInjectionToken, InferInput, InjectionToken, MissingArgsError, ResolvedInstance, ScopedContainer, StandardSchemaV1 } from "@navios/di";
2
+ import { ReactNode } from "react";
3
+ /**
4
+ * Context for the root Container.
5
+ * This is set by ContainerProvider and provides the base container.
6
+ */
7
+ export declare const ContainerContext: import("react").Context<Container | null>;
8
+ /**
9
+ * Context for the current ScopedContainer (if inside a ScopeProvider).
10
+ * This allows nested components to access request-scoped services.
11
+ */
12
+ export declare const ScopedContainerContext: import("react").Context<ScopedContainer | null>;
13
+ interface ContainerProviderProps {
14
+ container: Container;
15
+ children: ReactNode;
16
+ }
17
+ export declare function ContainerProvider({ container, children }: ContainerProviderProps): import("react").ReactElement<unknown, string | import("react").JSXElementConstructor<any>>;
18
+ /**
19
+ * Hook to get the current container (ScopedContainer if inside ScopeProvider, otherwise Container).
20
+ *
21
+ * This is the primary hook for accessing the DI container. It automatically
22
+ * returns the correct container based on context:
23
+ * - Inside a ScopeProvider: returns the ScopedContainer for request-scoped services
24
+ * - Outside a ScopeProvider: returns the root Container
25
+ *
26
+ * @returns The current container (ScopedContainer or Container)
27
+ */
28
+ export declare function useContainer(): Container | ScopedContainer;
29
+ /**
30
+ * Hook to get the root Container, regardless of whether we're inside a ScopeProvider.
31
+ *
32
+ * Use this when you need access to the root container specifically,
33
+ * for example to create new request scopes programmatically.
34
+ *
35
+ * @returns The root Container
36
+ */
37
+ export declare function useRootContainer(): Container;
38
+ interface ScopeProviderProps {
39
+ /**
40
+ * Optional explicit scope ID. If not provided, a unique ID will be generated.
41
+ * Useful when you need to reference the scope externally.
42
+ */
43
+ scopeId?: string;
44
+ /**
45
+ * Optional metadata to attach to the scope.
46
+ * The key `scopeId` is reserved: it always holds the effective scope ID.
47
+ * Can be used to pass data like user info, request headers, etc.
48
+ */
49
+ metadata?: Record<string, unknown>;
50
+ children: ReactNode;
51
+ }
52
+ /**
53
+ * ScopeProvider creates a new request scope for dependency injection.
54
+ *
55
+ * Services with `scope: 'Request'` will be instantiated once per ScopeProvider
56
+ * and shared among all components within that provider.
57
+ *
58
+ * This is useful for:
59
+ * - Table rows that need isolated state
60
+ * - Modal dialogs with their own service instances
61
+ * - Multi-tenant scenarios
62
+ * - Any case where you need isolated service instances
63
+ *
64
+ * @example
65
+ * ```tsx
66
+ * // Each row gets its own RowStateService instance
67
+ * {rows.map(row => (
68
+ * <ScopeProvider key={row.id} scopeId={row.id} metadata={{ rowData: row }}>
69
+ * <TableRow />
70
+ * </ScopeProvider>
71
+ * ))}
72
+ * ```
73
+ */
74
+ export declare function ScopeProvider({ scopeId, metadata, children }: ScopeProviderProps): import("react").ReactElement<unknown, string | import("react").JSXElementConstructor<any>>;
75
+ /**
76
+ * Hook to get the current scope ID.
77
+ * Returns null if not inside a ScopeProvider.
78
+ */
79
+ export declare function useScope(): string | null;
80
+ /**
81
+ * Hook to get the current scope ID, throwing if not inside a ScopeProvider.
82
+ * Use this when your component requires a scope to function correctly.
83
+ */
84
+ export declare function useScopeOrThrow(): string;
85
+ /**
86
+ * Hook to get the current ScopedContainer.
87
+ * Returns null if not inside a ScopeProvider.
88
+ *
89
+ * Use this to access scope metadata or other ScopedContainer methods.
90
+ *
91
+ * @example
92
+ * ```tsx
93
+ * function TableRow() {
94
+ * const scope = useScopedContainer()
95
+ * const rowData = scope?.getMetadata('rowData')
96
+ * // ...
97
+ * }
98
+ * ```
99
+ */
100
+ export declare function useScopedContainer(): ScopedContainer | null;
101
+ /**
102
+ * Hook to get the current ScopedContainer, throwing if not inside a ScopeProvider.
103
+ * Use this when your component requires a scope to function correctly.
104
+ */
105
+ export declare function useScopedContainerOrThrow(): ScopedContainer;
106
+ /**
107
+ * Hook to get metadata from the current scope.
108
+ * Returns undefined if not inside a ScopeProvider or if the key doesn't exist.
109
+ *
110
+ * @example
111
+ * ```tsx
112
+ * // In parent component:
113
+ * <ScopeProvider metadata={{ userId: '123', theme: 'dark' }}>
114
+ * <ChildComponent />
115
+ * </ScopeProvider>
116
+ *
117
+ * // In child component:
118
+ * function ChildComponent() {
119
+ * const userId = useScopeMetadata<string>('userId')
120
+ * const theme = useScopeMetadata<'light' | 'dark'>('theme')
121
+ * // ...
122
+ * }
123
+ * ```
124
+ */
125
+ export declare function useScopeMetadata<T = unknown>(key: string): T | undefined;
126
+ interface UseServiceResult<T> {
127
+ /**
128
+ * The instance once it is resolved, otherwise undefined.
129
+ */
130
+ data: T | undefined;
131
+ /**
132
+ * What the container rejected with, normally a `DIError`.
133
+ */
134
+ error: Error | undefined;
135
+ /**
136
+ * True while a resolution is in progress, including on the first render
137
+ * when the container does not hold the instance yet.
138
+ */
139
+ isLoading: boolean;
140
+ /**
141
+ * True when `data` is set.
142
+ */
143
+ isSuccess: boolean;
144
+ /**
145
+ * True when `error` is set.
146
+ */
147
+ isError: boolean;
148
+ /**
149
+ * Resolves the service again. Returns the existing instance when there is
150
+ * one, so its use is retrying after an error.
151
+ */
152
+ refetch: () => void;
153
+ }
154
+ interface UseOptionalServiceResult<T> extends UseServiceResult<T> {
155
+ /**
156
+ * What the container rejected with, except a missing provider for the token
157
+ * itself, which is reported by `isNotFound`.
158
+ */
159
+ error: Error | undefined;
160
+ /**
161
+ * True when the token has no provider in the container.
162
+ */
163
+ isNotFound: boolean;
164
+ }
165
+ /** What each service hook returns for an instance of type `T`. */
166
+ interface ServiceHookResults<T> {
167
+ service: UseServiceResult<T>;
168
+ optional: UseOptionalServiceResult<T>;
169
+ suspense: T;
170
+ }
171
+ /**
172
+ * The overloads of a service hook: `ServiceHook<'service'>` is `useService`,
173
+ * `ServiceHook<'optional'>` is `useOptionalService` and
174
+ * `ServiceHook<'suspense'>` is `useSuspenseService`.
175
+ */
176
+ interface ServiceHook<K extends keyof ServiceHookResults<unknown>> {
177
+ <T extends ClassType>(token: T): ServiceHookResults<ResolvedInstance<T>>[K];
178
+ <T, S extends StandardSchemaV1>(token: InjectionToken<T, S>, args: InferInput<S>): ServiceHookResults<T>[K];
179
+ <T, S extends StandardSchemaV1, R extends boolean>(token: InjectionToken<T, S, R>): R extends false ? ServiceHookResults<T>[K] : MissingArgsError<S>;
180
+ <T>(token: InjectionToken<T, unknown>): ServiceHookResults<T>[K];
181
+ <T>(token: BoundInjectionToken<T, any>): ServiceHookResults<T>[K];
182
+ <T>(token: FactoryInjectionToken<T, any>): ServiceHookResults<T>[K];
183
+ }
184
+ /**
185
+ * Hook to load a service from the DI container, with its loading and error
186
+ * state. Resolves again when the instance is invalidated.
187
+ *
188
+ * @example
189
+ * ```tsx
190
+ * function UserCard() {
191
+ * const { data: users, error } = useService(UserService)
192
+ *
193
+ * if (error) return <p>{error.message}</p>
194
+ * if (!users) return <p>Loading…</p>
195
+ *
196
+ * return <UserList users={users} />
197
+ * }
198
+ * ```
199
+ */
200
+ export declare const useService: ServiceHook<'service'>;
201
+ /**
202
+ * Hook that returns a service from the DI container and suspends while it is
203
+ * resolved. A failed resolution is thrown to the nearest error boundary.
204
+ * Resolves again, suspending, when the instance is invalidated.
205
+ */
206
+ export declare const useSuspenseService: ServiceHook<'suspense'>;
207
+ /**
208
+ * Hook to optionally load a service from the DI container.
209
+ *
210
+ * Unlike useService, a token without a provider is not an error: the hook
211
+ * returns `isNotFound: true` instead.
212
+ *
213
+ * This is useful for:
214
+ * - Optional dependencies that may or may not be configured
215
+ * - Feature flags where a service might not be available
216
+ * - Plugins or extensions that are conditionally registered
217
+ *
218
+ * @example
219
+ * ```tsx
220
+ * function Analytics() {
221
+ * const { data: analytics, isNotFound } = useOptionalService(AnalyticsService)
222
+ *
223
+ * if (isNotFound) {
224
+ * // Analytics service not configured, skip tracking
225
+ * return null
226
+ * }
227
+ *
228
+ * return <AnalyticsTracker service={analytics} />
229
+ * }
230
+ * ```
231
+ */
232
+ export declare const useOptionalService: ServiceHook<'optional'>;
233
+ /**
234
+ * Hook that returns a function to invalidate a service instance directly.
235
+ *
236
+ * This is useful when you have the service instance and want to invalidate it
237
+ * without knowing its token.
238
+ *
239
+ * @example
240
+ * ```tsx
241
+ * function UserProfile() {
242
+ * const { data: user } = useService(UserService)
243
+ * const invalidateInstance = useInvalidateInstance()
244
+ *
245
+ * const handleRefresh = () => {
246
+ * if (user) {
247
+ * invalidateInstance(user)
248
+ * }
249
+ * }
250
+ *
251
+ * return (
252
+ * <div>
253
+ * <span>{user?.name}</span>
254
+ * <button onClick={handleRefresh}>Refresh</button>
255
+ * </div>
256
+ * )
257
+ * }
258
+ * ```
259
+ */
260
+ export declare function useInvalidateInstance(): (instance: unknown) => Promise<void>;
261
+ export type { ContainerProviderProps, ScopeProviderProps, ServiceHook, ServiceHookResults, UseOptionalServiceResult, UseServiceResult };
262
+ //# sourceMappingURL=index.d.cts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"index.d.cts","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/types.mts","../src/service/use-service.mts","../src/service/use-suspense-service.mts","../src/service/use-optional-service.mts","../src/service/use-invalidate-instance.mts"],"mappings":";;;;;;qBAQa,kCAAgB,QAAA;;;;;qBAMhB,wCAAsB,QAAA;UCPlB;EACf,WAAW;EACX,UAAU;;wBAGI,oBAAoB,WAAW,YAAY,yCAAsB,+CAAA;;;;;;;;;;;wBCIjE,gBAAgB,YAAY;;;;;;;;;wBAwB5B,oBAAoB;UChCnB;;;;;EAKf;;;;;;EAMA,WAAW;EACX,UAAU;;;;;;;;;;;;;;;;;;;;;;;;wBAyBI,gBAAgB,SAAS,UAAU,YAAY,qCAAkB,+CAAA;;;;;wBCnCjE;;;;;wBASA;;;;;;;;;;;;;;;;wBA0BA,sBAAsB;;;;;wBAQtB,6BAA6B;;;;;;;;;;;;;;;;;;;;wBA8B7B,iBAAiB,aAAa,cAAc;UCjE3C,iBAAiB;;;;EAIhC,MAAM;;;;EAIN,OAAO;;;;;EAKP;;;;EAIA;;;;EAIA;;;;;EAKA;;UAGe,yBAAyB,WAAW,iBAAiB;;;;;EAKpE,OAAO;;;;EAIP;;;UAIe,mBAAmB;EAClC,SAAS,iBAAiB;EAC1B,UAAU,yBAAyB;EACnC,UAAU;;;;;;;UAQK,YAAY,gBAAgB;GAE1C,UAAU,WAAW,OAAO,IAAI,mBAAmB,iBAAiB,IAAI;GAExE,GAAG,UAAU,kBACZ,OAAO,eAAe,GAAG,IACzB,MAAM,WAAW,KAChB,mBAAmB,GAAG;GAExB,GAAG,UAAU,kBAAkB,mBAC9B,OAAO,eAAe,GAAG,GAAG,KAC3B,kBAAkB,mBAAmB,GAAG,KAAK,iBAAiB;GAEhE,GAAG,OAAO,eAAe,cAAc,mBAAmB,GAAG;GAC7D,GAAG,OAAO,oBAAoB,UAAU,mBAAmB,GAAG;GAC9D,GAAG,OAAO,sBAAsB,UAAU,mBAAmB,GAAG;;;;;;;;;;;;;;;;;;qBClEtD,YAMR;;;;;;qBC+JQ,oBAkDR;;;;;;;;;;;;;;;;;;;;;;;;;;qBC9MQ,oBAMR;;;;;;;;;;;;;;;;;;;;;;;;;;;;wBCJW,0BAA0B,sBAAsB"}
package/lib/index.d.mts CHANGED
@@ -1,31 +1,40 @@
1
- import * as react1 from "react";
1
+ import { BoundInjectionToken, ClassType, Container, FactoryInjectionToken, InferInput, InjectionToken, MissingArgsError, ResolvedInstance, ScopedContainer, StandardSchemaV1 } from "@navios/di";
2
2
  import { ReactNode } from "react";
3
- import { BoundInjectionToken, ClassType, Container, Factorable, FactoryInjectionToken, InjectionToken, InjectionTokenSchemaType, ScopedContainer } from "@navios/di";
4
- import { ZodType, z } from "zod/v4";
5
-
6
- //#region src/providers/context.d.mts
7
3
  /**
8
4
  * Context for the root Container.
9
5
  * This is set by ContainerProvider and provides the base container.
10
6
  */
11
- declare const ContainerContext: react1.Context<Container | null>;
7
+ export declare const ContainerContext: import("react").Context<Container | null>;
12
8
  /**
13
9
  * Context for the current ScopedContainer (if inside a ScopeProvider).
14
10
  * This allows nested components to access request-scoped services.
15
11
  */
16
- declare const ScopedContainerContext: react1.Context<ScopedContainer | null>;
17
- //#endregion
18
- //#region src/providers/container-provider.d.mts
12
+ export declare const ScopedContainerContext: import("react").Context<ScopedContainer | null>;
19
13
  interface ContainerProviderProps {
20
14
  container: Container;
21
15
  children: ReactNode;
22
16
  }
23
- declare function ContainerProvider({
24
- container,
25
- children
26
- }: ContainerProviderProps): react1.ReactElement<unknown, string | react1.JSXElementConstructor<any>>;
27
- //#endregion
28
- //#region src/providers/scope-provider.d.mts
17
+ export declare function ContainerProvider({ container, children }: ContainerProviderProps): import("react").ReactElement<unknown, string | import("react").JSXElementConstructor<any>>;
18
+ /**
19
+ * Hook to get the current container (ScopedContainer if inside ScopeProvider, otherwise Container).
20
+ *
21
+ * This is the primary hook for accessing the DI container. It automatically
22
+ * returns the correct container based on context:
23
+ * - Inside a ScopeProvider: returns the ScopedContainer for request-scoped services
24
+ * - Outside a ScopeProvider: returns the root Container
25
+ *
26
+ * @returns The current container (ScopedContainer or Container)
27
+ */
28
+ export declare function useContainer(): Container | ScopedContainer;
29
+ /**
30
+ * Hook to get the root Container, regardless of whether we're inside a ScopeProvider.
31
+ *
32
+ * Use this when you need access to the root container specifically,
33
+ * for example to create new request scopes programmatically.
34
+ *
35
+ * @returns The root Container
36
+ */
37
+ export declare function useRootContainer(): Container;
29
38
  interface ScopeProviderProps {
30
39
  /**
31
40
  * Optional explicit scope ID. If not provided, a unique ID will be generated.
@@ -33,7 +42,8 @@ interface ScopeProviderProps {
33
42
  */
34
43
  scopeId?: string;
35
44
  /**
36
- * Optional metadata to attach to the request context.
45
+ * Optional metadata to attach to the scope.
46
+ * The key `scopeId` is reserved: it always holds the effective scope ID.
37
47
  * Can be used to pass data like user info, request headers, etc.
38
48
  */
39
49
  metadata?: Record<string, unknown>;
@@ -61,183 +71,192 @@ interface ScopeProviderProps {
61
71
  * ))}
62
72
  * ```
63
73
  */
64
- declare function ScopeProvider({
65
- scopeId,
66
- metadata,
67
- children
68
- }: ScopeProviderProps): react1.ReactElement<unknown, string | react1.JSXElementConstructor<any>> | null;
69
- //#endregion
70
- //#region src/hooks/use-container.d.mts
74
+ export declare function ScopeProvider({ scopeId, metadata, children }: ScopeProviderProps): import("react").ReactElement<unknown, string | import("react").JSXElementConstructor<any>>;
71
75
  /**
72
- * Hook to get the current container (ScopedContainer if inside ScopeProvider, otherwise Container).
76
+ * Hook to get the current scope ID.
77
+ * Returns null if not inside a ScopeProvider.
78
+ */
79
+ export declare function useScope(): string | null;
80
+ /**
81
+ * Hook to get the current scope ID, throwing if not inside a ScopeProvider.
82
+ * Use this when your component requires a scope to function correctly.
83
+ */
84
+ export declare function useScopeOrThrow(): string;
85
+ /**
86
+ * Hook to get the current ScopedContainer.
87
+ * Returns null if not inside a ScopeProvider.
73
88
  *
74
- * This is the primary hook for accessing the DI container. It automatically
75
- * returns the correct container based on context:
76
- * - Inside a ScopeProvider: returns the ScopedContainer for request-scoped services
77
- * - Outside a ScopeProvider: returns the root Container
89
+ * Use this to access scope metadata or other ScopedContainer methods.
78
90
  *
79
- * @returns The current container (ScopedContainer or Container)
91
+ * @example
92
+ * ```tsx
93
+ * function TableRow() {
94
+ * const scope = useScopedContainer()
95
+ * const rowData = scope?.getMetadata('rowData')
96
+ * // ...
97
+ * }
98
+ * ```
80
99
  */
81
- declare function useContainer(): Container | ScopedContainer;
100
+ export declare function useScopedContainer(): ScopedContainer | null;
82
101
  /**
83
- * Hook to get the root Container, regardless of whether we're inside a ScopeProvider.
102
+ * Hook to get the current ScopedContainer, throwing if not inside a ScopeProvider.
103
+ * Use this when your component requires a scope to function correctly.
104
+ */
105
+ export declare function useScopedContainerOrThrow(): ScopedContainer;
106
+ /**
107
+ * Hook to get metadata from the current scope.
108
+ * Returns undefined if not inside a ScopeProvider or if the key doesn't exist.
84
109
  *
85
- * Use this when you need access to the root container specifically,
86
- * for example to create new request scopes programmatically.
110
+ * @example
111
+ * ```tsx
112
+ * // In parent component:
113
+ * <ScopeProvider metadata={{ userId: '123', theme: 'dark' }}>
114
+ * <ChildComponent />
115
+ * </ScopeProvider>
87
116
  *
88
- * @returns The root Container
117
+ * // In child component:
118
+ * function ChildComponent() {
119
+ * const userId = useScopeMetadata<string>('userId')
120
+ * const theme = useScopeMetadata<'light' | 'dark'>('theme')
121
+ * // ...
122
+ * }
123
+ * ```
89
124
  */
90
- declare function useRootContainer(): Container;
91
- //#endregion
92
- //#region src/types.d.mts
93
- type UnionToArray<T> = UnionToArrayImpl<T, never>;
94
- type UnionToArrayImpl<T, L extends any[]> = T extends any ? UnionToArrayImpl<Exclude<T, T>, [...L, T]> : L;
95
- type Join<T extends any[], Delimiter extends string> = T extends [] ? '' : T extends [infer First extends string | number | symbol] ? First extends string | number ? `${First}` : never : T extends [infer First extends string | number | symbol, ...infer Rest extends any[]] ? First extends string | number ? `${First}${Delimiter}${Join<Rest, Delimiter>}` : never : '';
96
- //#endregion
97
- //#region src/hooks/use-service.d.mts
125
+ export declare function useScopeMetadata<T = unknown>(key: string): T | undefined;
98
126
  interface UseServiceResult<T> {
99
- data: T | undefined;
100
- error: Error | undefined;
101
- isLoading: boolean;
102
- isSuccess: boolean;
103
- isError: boolean;
104
- refetch: () => void;
105
- }
106
- declare function useService<T extends ClassType>(token: T): UseServiceResult<InstanceType<T> extends Factorable<infer R> ? R : InstanceType<T>>;
107
- declare function useService<T, S extends InjectionTokenSchemaType>(token: InjectionToken<T, S>, args: z.input<S>): UseServiceResult<T>;
108
- declare function useService<T, S extends InjectionTokenSchemaType, R extends boolean>(token: InjectionToken<T, S, R>): R extends false ? UseServiceResult<T> : S extends ZodType<infer Type> ? `Error: Your token requires args: ${Join<UnionToArray<keyof Type>, ', '>}` : 'Error: Your token requires args';
109
- declare function useService<T>(token: InjectionToken<T, undefined>): UseServiceResult<T>;
110
- declare function useService<T>(token: BoundInjectionToken<T, any>): UseServiceResult<T>;
111
- declare function useService<T>(token: FactoryInjectionToken<T, any>): UseServiceResult<T>;
112
- //#endregion
113
- //#region src/hooks/use-suspense-service.d.mts
114
- declare function useSuspenseService<T extends ClassType>(token: T): InstanceType<T> extends Factorable<infer R> ? R : InstanceType<T>;
115
- declare function useSuspenseService<T, S extends InjectionTokenSchemaType>(token: InjectionToken<T, S>, args: z.input<S>): T;
116
- declare function useSuspenseService<T, S extends InjectionTokenSchemaType, R extends boolean>(token: InjectionToken<T, S, R>): R extends false ? T : S extends ZodType<infer Type> ? `Error: Your token requires args: ${Join<UnionToArray<keyof Type>, ', '>}` : 'Error: Your token requires args';
117
- declare function useSuspenseService<T>(token: InjectionToken<T, undefined>): T;
118
- declare function useSuspenseService<T>(token: BoundInjectionToken<T, any>): T;
119
- declare function useSuspenseService<T>(token: FactoryInjectionToken<T, any>): T;
120
- //#endregion
121
- //#region src/hooks/use-optional-service.d.mts
122
- interface UseOptionalServiceResult<T> {
123
127
  /**
124
- * The service instance if found and loaded successfully, otherwise undefined.
128
+ * The instance once it is resolved, otherwise undefined.
125
129
  */
126
130
  data: T | undefined;
127
131
  /**
128
- * Error that occurred during loading (excludes "not found" which is not an error).
132
+ * What the container rejected with, normally a `DIError`.
129
133
  */
130
134
  error: Error | undefined;
131
135
  /**
132
- * True while the service is being loaded.
136
+ * True while a resolution is in progress, including on the first render
137
+ * when the container does not hold the instance yet.
133
138
  */
134
139
  isLoading: boolean;
135
140
  /**
136
- * True if the service was loaded successfully.
141
+ * True when `data` is set.
137
142
  */
138
143
  isSuccess: boolean;
139
144
  /**
140
- * True if the service was not found (not registered in the container).
141
- */
142
- isNotFound: boolean;
143
- /**
144
- * True if an error occurred during loading.
145
+ * True when `error` is set.
145
146
  */
146
147
  isError: boolean;
147
148
  /**
148
- * Function to manually re-fetch the service.
149
+ * Resolves the service again. Returns the existing instance when there is
150
+ * one, so its use is retrying after an error.
149
151
  */
150
152
  refetch: () => void;
151
153
  }
152
- declare function useOptionalService<T extends ClassType>(token: T): UseOptionalServiceResult<InstanceType<T> extends Factorable<infer R> ? R : InstanceType<T>>;
153
- declare function useOptionalService<T, S extends InjectionTokenSchemaType>(token: InjectionToken<T, S>, args: z.input<S>): UseOptionalServiceResult<T>;
154
- declare function useOptionalService<T, S extends InjectionTokenSchemaType, R extends boolean>(token: InjectionToken<T, S, R>): R extends false ? UseOptionalServiceResult<T> : S extends ZodType<infer Type> ? `Error: Your token requires args: ${Join<UnionToArray<keyof Type>, ', '>}` : 'Error: Your token requires args';
155
- declare function useOptionalService<T>(token: InjectionToken<T, undefined>): UseOptionalServiceResult<T>;
156
- declare function useOptionalService<T>(token: BoundInjectionToken<T, any>): UseOptionalServiceResult<T>;
157
- declare function useOptionalService<T>(token: FactoryInjectionToken<T, any>): UseOptionalServiceResult<T>;
158
- //#endregion
159
- //#region src/hooks/use-invalidate.d.mts
154
+ interface UseOptionalServiceResult<T> extends UseServiceResult<T> {
155
+ /**
156
+ * What the container rejected with, except a missing provider for the token
157
+ * itself, which is reported by `isNotFound`.
158
+ */
159
+ error: Error | undefined;
160
+ /**
161
+ * True when the token has no provider in the container.
162
+ */
163
+ isNotFound: boolean;
164
+ }
165
+ /** What each service hook returns for an instance of type `T`. */
166
+ interface ServiceHookResults<T> {
167
+ service: UseServiceResult<T>;
168
+ optional: UseOptionalServiceResult<T>;
169
+ suspense: T;
170
+ }
160
171
  /**
161
- * Hook that returns a function to invalidate a service instance directly.
162
- *
163
- * This is useful when you have the service instance and want to invalidate it
164
- * without knowing its token.
172
+ * The overloads of a service hook: `ServiceHook<'service'>` is `useService`,
173
+ * `ServiceHook<'optional'>` is `useOptionalService` and
174
+ * `ServiceHook<'suspense'>` is `useSuspenseService`.
175
+ */
176
+ interface ServiceHook<K extends keyof ServiceHookResults<unknown>> {
177
+ <T extends ClassType>(token: T): ServiceHookResults<ResolvedInstance<T>>[K];
178
+ <T, S extends StandardSchemaV1>(token: InjectionToken<T, S>, args: InferInput<S>): ServiceHookResults<T>[K];
179
+ <T, S extends StandardSchemaV1, R extends boolean>(token: InjectionToken<T, S, R>): R extends false ? ServiceHookResults<T>[K] : MissingArgsError<S>;
180
+ <T>(token: InjectionToken<T, unknown>): ServiceHookResults<T>[K];
181
+ <T>(token: BoundInjectionToken<T, any>): ServiceHookResults<T>[K];
182
+ <T>(token: FactoryInjectionToken<T, any>): ServiceHookResults<T>[K];
183
+ }
184
+ /**
185
+ * Hook to load a service from the DI container, with its loading and error
186
+ * state. Resolves again when the instance is invalidated.
165
187
  *
166
188
  * @example
167
189
  * ```tsx
168
- * function UserProfile() {
169
- * const { data: user } = useService(UserService)
170
- * const invalidateInstance = useInvalidateInstance()
190
+ * function UserCard() {
191
+ * const { data: users, error } = useService(UserService)
171
192
  *
172
- * const handleRefresh = () => {
173
- * if (user) {
174
- * invalidateInstance(user)
175
- * }
176
- * }
193
+ * if (error) return <p>{error.message}</p>
194
+ * if (!users) return <p>Loading…</p>
177
195
  *
178
- * return (
179
- * <div>
180
- * <span>{user?.name}</span>
181
- * <button onClick={handleRefresh}>Refresh</button>
182
- * </div>
183
- * )
196
+ * return <UserList users={users} />
184
197
  * }
185
198
  * ```
186
199
  */
187
- declare function useInvalidateInstance(): (instance: unknown) => Promise<void>;
188
- //#endregion
189
- //#region src/hooks/use-scope.d.mts
200
+ export declare const useService: ServiceHook<'service'>;
190
201
  /**
191
- * Hook to get the current scope ID.
192
- * Returns null if not inside a ScopeProvider.
202
+ * Hook that returns a service from the DI container and suspends while it is
203
+ * resolved. A failed resolution is thrown to the nearest error boundary.
204
+ * Resolves again, suspending, when the instance is invalidated.
193
205
  */
194
- declare function useScope(): string | null;
206
+ export declare const useSuspenseService: ServiceHook<'suspense'>;
195
207
  /**
196
- * Hook to get the current scope ID, throwing if not inside a ScopeProvider.
197
- * Use this when your component requires a scope to function correctly.
198
- */
199
- declare function useScopeOrThrow(): string;
200
- /**
201
- * Hook to get the current ScopedContainer.
202
- * Returns null if not inside a ScopeProvider.
208
+ * Hook to optionally load a service from the DI container.
203
209
  *
204
- * Use this to access scope metadata or other ScopedContainer methods.
210
+ * Unlike useService, a token without a provider is not an error: the hook
211
+ * returns `isNotFound: true` instead.
212
+ *
213
+ * This is useful for:
214
+ * - Optional dependencies that may or may not be configured
215
+ * - Feature flags where a service might not be available
216
+ * - Plugins or extensions that are conditionally registered
205
217
  *
206
218
  * @example
207
219
  * ```tsx
208
- * function TableRow() {
209
- * const scope = useScopedContainer()
210
- * const rowData = scope?.getMetadata('rowData')
211
- * // ...
220
+ * function Analytics() {
221
+ * const { data: analytics, isNotFound } = useOptionalService(AnalyticsService)
222
+ *
223
+ * if (isNotFound) {
224
+ * // Analytics service not configured, skip tracking
225
+ * return null
226
+ * }
227
+ *
228
+ * return <AnalyticsTracker service={analytics} />
212
229
  * }
213
230
  * ```
214
231
  */
215
- declare function useScopedContainer(): ScopedContainer | null;
232
+ export declare const useOptionalService: ServiceHook<'optional'>;
216
233
  /**
217
- * Hook to get the current ScopedContainer, throwing if not inside a ScopeProvider.
218
- * Use this when your component requires a scope to function correctly.
219
- */
220
- declare function useScopedContainerOrThrow(): ScopedContainer;
221
- /**
222
- * Hook to get metadata from the current scope.
223
- * Returns undefined if not inside a ScopeProvider or if the key doesn't exist.
234
+ * Hook that returns a function to invalidate a service instance directly.
235
+ *
236
+ * This is useful when you have the service instance and want to invalidate it
237
+ * without knowing its token.
224
238
  *
225
239
  * @example
226
240
  * ```tsx
227
- * // In parent component:
228
- * <ScopeProvider metadata={{ userId: '123', theme: 'dark' }}>
229
- * <ChildComponent />
230
- * </ScopeProvider>
241
+ * function UserProfile() {
242
+ * const { data: user } = useService(UserService)
243
+ * const invalidateInstance = useInvalidateInstance()
231
244
  *
232
- * // In child component:
233
- * function ChildComponent() {
234
- * const userId = useScopeMetadata<string>('userId')
235
- * const theme = useScopeMetadata<'light' | 'dark'>('theme')
236
- * // ...
245
+ * const handleRefresh = () => {
246
+ * if (user) {
247
+ * invalidateInstance(user)
248
+ * }
249
+ * }
250
+ *
251
+ * return (
252
+ * <div>
253
+ * <span>{user?.name}</span>
254
+ * <button onClick={handleRefresh}>Refresh</button>
255
+ * </div>
256
+ * )
237
257
  * }
238
258
  * ```
239
259
  */
240
- declare function useScopeMetadata<T = unknown>(key: string): T | undefined;
241
- //#endregion
242
- export { ContainerContext, ContainerProvider, type ContainerProviderProps, Join, ScopeProvider, type ScopeProviderProps, ScopedContainerContext, UnionToArray, type UseOptionalServiceResult, type UseServiceResult, useContainer, useInvalidateInstance, useOptionalService, useRootContainer, useScope, useScopeMetadata, useScopeOrThrow, useScopedContainer, useScopedContainerOrThrow, useService, useSuspenseService };
260
+ export declare function useInvalidateInstance(): (instance: unknown) => Promise<void>;
261
+ export type { ContainerProviderProps, ScopeProviderProps, ServiceHook, ServiceHookResults, UseOptionalServiceResult, UseServiceResult };
243
262
  //# sourceMappingURL=index.d.mts.map