@equinor/fusion-framework-module-context 6.0.7-next.0 → 7.0.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 (37) hide show
  1. package/CHANGELOG.md +30 -5
  2. package/README.md +33 -0
  3. package/dist/esm/ContextConfigBuilder.js +70 -2
  4. package/dist/esm/ContextConfigBuilder.js.map +1 -1
  5. package/dist/esm/ContextProvider.js +207 -2
  6. package/dist/esm/ContextProvider.js.map +1 -1
  7. package/dist/esm/client/ContextClient.js +65 -1
  8. package/dist/esm/client/ContextClient.js.map +1 -1
  9. package/dist/esm/configurator.js +3 -5
  10. package/dist/esm/configurator.js.map +1 -1
  11. package/dist/esm/errors.js +12 -1
  12. package/dist/esm/errors.js.map +1 -1
  13. package/dist/esm/module.js +21 -0
  14. package/dist/esm/module.js.map +1 -1
  15. package/dist/esm/utils/enable-context.js +19 -3
  16. package/dist/esm/utils/enable-context.js.map +1 -1
  17. package/dist/esm/version.js +1 -1
  18. package/dist/esm/version.js.map +1 -1
  19. package/dist/tsconfig.tsbuildinfo +1 -1
  20. package/dist/types/ContextConfigBuilder.d.ts +70 -0
  21. package/dist/types/ContextProvider.d.ts +347 -6
  22. package/dist/types/client/ContextClient.d.ts +65 -1
  23. package/dist/types/errors.d.ts +12 -1
  24. package/dist/types/module.d.ts +31 -0
  25. package/dist/types/types.d.ts +33 -0
  26. package/dist/types/utils/enable-context.d.ts +18 -2
  27. package/dist/types/version.d.ts +1 -1
  28. package/package.json +7 -7
  29. package/src/ContextConfigBuilder.ts +70 -4
  30. package/src/ContextProvider.ts +353 -10
  31. package/src/client/ContextClient.ts +66 -2
  32. package/src/configurator.ts +4 -5
  33. package/src/errors.ts +12 -1
  34. package/src/module.ts +31 -0
  35. package/src/types.ts +33 -0
  36. package/src/utils/enable-context.ts +19 -3
  37. package/src/version.ts +1 -1
@@ -4,17 +4,75 @@ import type { GetContextParameters } from './client/ContextClient';
4
4
  import type { ContextModuleConfig, ContextModuleConfigurator, IContextModuleConfigurator } from './configurator';
5
5
  import type { ContextItem, QueryContextParameters, RelatedContextParameters } from './types';
6
6
  export type ContextConfigBuilderCallback = <TDeps extends Array<AnyModule> = []>(builder: ContextConfigBuilder<TDeps, ModuleInitializerArgs<IContextModuleConfigurator, TDeps>>) => void | Promise<void>;
7
+ /**
8
+ * A builder class for configuring and customizing context module behavior within the Fusion Framework.
9
+ *
10
+ * `ContextConfigBuilder` provides a fluent API for setting up various aspects of context management,
11
+ * including context type, filtering, parent context connection, parameter resolution, validation,
12
+ * path extraction/generation, and client configuration for fetching context items.
13
+ *
14
+ * @typeParam TModules - An array of modules that extend `AnyModule`. Defaults to an empty array.
15
+ * @typeParam TInit - The initializer arguments for the module, extending `ModuleInitializerArgs`.
16
+ *
17
+ * @example
18
+ * ```typescript
19
+ * const builder = new ContextConfigBuilder(init);
20
+ * builder.setContextType(['ProjectMaster']);
21
+ * builder.setContextFilter(items => items.filter(ctx => ctx.isActive));
22
+ * builder.setContextClient({ get: fetchContextItem, query: fetchContextItems });
23
+ * ```
24
+ *
25
+ * @remarks
26
+ * - Use the provided setter methods to customize context behavior as needed.
27
+ * - The builder pattern allows chaining configuration methods for clarity and convenience.
28
+ * - The `requireInstance` method enables asynchronous retrieval of module instances by name.
29
+ *
30
+ * @todo - this should extend the BaseConfigBuilder
31
+ *
32
+ * @see ContextModuleConfig
33
+ * @see ModuleInitializerArgs
34
+ */
7
35
  export declare class ContextConfigBuilder<TModules extends Array<AnyModule> = [], TInit extends ModuleInitializerArgs<any, any> = ModuleInitializerArgs<ContextModuleConfigurator, TModules>> {
8
36
  #private;
9
37
  config: Partial<ContextModuleConfig>;
10
38
  constructor(init: TInit, config?: Partial<ContextModuleConfig>);
11
39
  requireInstance<TKey extends string = Extract<keyof Modules, string>>(module: TKey): Promise<ModuleType<Modules[TKey]>>;
12
40
  requireInstance<T>(module: string): Promise<T>;
41
+ /**
42
+ * Sets the context type for the current configuration.
43
+ *
44
+ * @param type - The context type to assign, as defined by `ContextModuleConfig['contextType']`.
45
+ */
13
46
  setContextType(type: ContextModuleConfig['contextType']): void;
47
+ /**
48
+ * Sets the context filter function for the configuration.
49
+ *
50
+ * @param filter - A function that determines whether a context should be included, as defined by `ContextModuleConfig['contextFilter']`.
51
+ */
14
52
  setContextFilter(filter: ContextModuleConfig['contextFilter']): void;
53
+ /**
54
+ * Sets the function or configuration used to connect to a parent context.
55
+ *
56
+ * @param connect - The function or configuration that defines how to connect to the parent context.
57
+ */
15
58
  connectParentContext(connect: ContextModuleConfig['connectParentContext']): void;
59
+ /**
60
+ * Sets the function used to provide context parameters for the module configuration.
61
+ *
62
+ * @param fn - A function conforming to the `contextParameterFn` type defined in `ContextModuleConfig`.
63
+ */
16
64
  setContextParameterFn(fn: ContextModuleConfig['contextParameterFn']): void;
65
+ /**
66
+ * Sets the function used to validate the context within the configuration.
67
+ *
68
+ * @param fn - A function that implements the `validateContext` signature from `ContextModuleConfig`.
69
+ */
17
70
  setValidateContext(fn: ContextModuleConfig['validateContext']): void;
71
+ /**
72
+ * Sets the function used to resolve the context for the module configuration.
73
+ *
74
+ * @param fn - A function that defines how the context should be resolved, conforming to the `resolveContext` type from `ContextModuleConfig`.
75
+ */
18
76
  setResolveContext(fn: ContextModuleConfig['resolveContext']): void;
19
77
  /**
20
78
  * Sets the function responsible for extracting the context ID from a given path.
@@ -30,6 +88,18 @@ export declare class ContextConfigBuilder<TModules extends Array<AnyModule> = []
30
88
  */
31
89
  setContextPathGenerator(fn: ContextModuleConfig['generatePathFromContext']): void;
32
90
  setResolveInitialContext(fn: ContextModuleConfig['resolveInitialContext']): void;
91
+ /**
92
+ * Sets the context client configuration for fetching context items.
93
+ *
94
+ * This method allows you to provide custom query functions or query constructor options
95
+ * for retrieving single context items (`get`), querying multiple context items (`query`),
96
+ * and optionally fetching related context items (`related`). Each query can be provided
97
+ * as either a function or a configuration object. The expiration time for cached results
98
+ * can also be specified.
99
+ *
100
+ * @param client - An object containing the query functions or options for `get`, `query`, and optionally `related` context items.
101
+ * @param expire - Optional. The expiration time (in milliseconds) for cached query results. Defaults to 1 minute.
102
+ */
33
103
  setContextClient(client: {
34
104
  get: QueryFn<ContextItem, GetContextParameters> | QueryCtorOptions<ContextItem, GetContextParameters>;
35
105
  query: QueryFn<ContextItem[], QueryContextParameters> | QueryCtorOptions<ContextItem[], QueryContextParameters>;
@@ -6,79 +6,200 @@ import type { ModuleType } from '@equinor/fusion-framework-module';
6
6
  import type { EventModule, FrameworkEvent, FrameworkEventInit } from '@equinor/fusion-framework-module-event';
7
7
  import Query from '@equinor/fusion-query';
8
8
  /**
9
- * WARNING: this is an initial out cast.
10
- * api clients will most probably not be exposed in future!
11
- */
12
- /**
13
- * Represents a context provider that manages the current context and provides methods for querying and manipulating context items.
9
+ * Interface representing a provider for managing and interacting with context items within an application.
10
+ *
11
+ * The `IContextProvider` interface defines a contract for querying, validating, resolving, and managing the current context state.
12
+ * It supports both synchronous and asynchronous operations, as well as observable streams for reactive programming.
13
+ * This interface is intended to be implemented by modules that encapsulate context-related logic, such as user, tenant, or environment context.
14
+ *
15
+ * ## Core Responsibilities
16
+ * - **Querying Contexts:** Search and retrieve context items based on search criteria, both as observables and promises.
17
+ * - **Current Context Management:** Get, set, and clear the current context, with support for validation and resolution.
18
+ * - **Context Resolution:** Resolve context items to their full representation, synchronously or asynchronously.
19
+ * - **Related Contexts:** Retrieve related context items based on specific parameters.
20
+ * - **Path Utilities:** Extract context IDs from paths and generate paths from context items, supporting deep linking and routing.
21
+ * - **Reactive State:** Expose the current context as an observable stream for reactive UI updates.
22
+ *
23
+ * ## Usage Example
24
+ * ```ts
25
+ * const provider: IContextProvider = ...;
26
+ * provider.currentContext$.subscribe(ctx => {
27
+ * // React to context changes
28
+ * });
29
+ * const items = await provider.queryContextAsync('search-term');
30
+ * ```
31
+ *
32
+ * ## Notes
33
+ * - Some members are marked as **DANGER** and are intended for advanced or internal use only.
34
+ * - Implementations should ensure thread safety and consistency of the current context state.
35
+ * - Optional methods for path extraction and generation enable integration with routing systems.
36
+ *
37
+ * @template T - The shape of the context item data.
14
38
  */
15
39
  export interface IContextProvider {
16
40
  /** DANGER */
17
41
  readonly contextClient: ContextClient;
18
42
  /** DANGER */
19
43
  readonly queryClient: Query<ContextItem[], QueryContextParameters>;
44
+ /**
45
+ * Observable stream emitting the current context item.
46
+ *
47
+ * - Emits `undefined` if the context has not been initialized.
48
+ * - Emits `null` when the current context is cleared.
49
+ * - Emits a `ContextItem` when a valid context is set.
50
+ *
51
+ * @example
52
+ * ```ts
53
+ * portal.context.currentContext$.subscribe(context => {
54
+ * if (context) {
55
+ * console.log('Current context:', context);
56
+ * } else if (context === null) {
57
+ * console.log('Current context cleared');
58
+ * }
59
+ * });
60
+ * ```
61
+ */
20
62
  readonly currentContext$: Observable<ContextItem | null | undefined>;
21
- currentContext: ContextItem | null | undefined;
63
+ /**
64
+ * Snapshot of the current context item.
65
+ *
66
+ * @remarks
67
+ * This property provides the current context item as a snapshot.
68
+ * It may be `null` or `undefined` if no context is set or if the context is not initialized.
69
+ * It is intended for synchronous access to the current context state.
70
+ *
71
+ * __Use {@link currentContext$} instead of this property to get the current context as an observable stream.__
72
+ */
73
+ readonly currentContext: ContextItem | null | undefined;
22
74
  /**
23
75
  * Queries the context items based on the provided search string.
76
+ *
77
+ * @example
78
+ * ```ts
79
+ * portal.context.queryContext('search-term').subscribe(contextItems => {
80
+ * console.log('Queried context items:', contextItems);
81
+ * });
82
+ * ```
83
+ *
24
84
  * @param search The search string.
25
85
  * @returns An observable that emits an array of context items.
26
86
  */
27
87
  queryContext(search: string): Observable<Array<ContextItem>>;
28
88
  /**
29
89
  * Queries the context items asynchronously based on the provided search string.
90
+ *
91
+ * @example
92
+ * ```ts
93
+ * portal.context.queryContextAsync('search-term').then(contextItems => {
94
+ * console.log('Queried context items:', contextItems);
95
+ * });
96
+ * ```
97
+ *
30
98
  * @param search The search string.
31
99
  * @returns A promise that resolves to an array of context items.
32
100
  */
33
101
  queryContextAsync(search: string): Promise<Array<ContextItem>>;
34
102
  /**
35
103
  * Validates the given context item.
104
+ * This method is used to check if the context item meets the criteria defined in the provider's configuration.
105
+ *
106
+ * @example
107
+ * ```ts
108
+ * const currentContext = portal.context.currentContext;
109
+ * if(app.context.validateContext(currentContext)) {
110
+ * // the application can safely use the context item
111
+ * } else {
112
+ * // the context item is not valid, handle accordingly
113
+ * }
114
+ * ```
115
+ *
116
+ * @remarks
117
+ * This method will use the configured validation function to check if the context item is valid.
118
+ *
36
119
  * @param item The context item to validate.
37
120
  * @returns A boolean indicating whether the context item is valid or not.
38
121
  */
39
122
  validateContext(item: ContextItem<Record<string, unknown>>): boolean;
40
123
  /**
41
124
  * Resolves the context item as a stream.
125
+ *
126
+ * This method will try to resolve the context item based on the current context.
127
+ * This is useful when transferring context items between different parts of the application.
128
+ *
129
+ * @remarks
130
+ * A normal implementation of this method will first validate the context item and if it is not valid,
131
+ * it will use the {@link relatedContexts} method to find related context items.
132
+ *
133
+ * @example
134
+ * ```ts
135
+ * app.context.resolveContext(portal.context.currentContext).subscribe({
136
+ * next: (resolvedContext) => {
137
+ * // the application can safely use the resolved context item
138
+ * },
139
+ * error: (err) => {
140
+ * // handle error during context resolution
141
+ * },
142
+ * complete: () => {
143
+ * // context resolution completed
144
+ * }
145
+ * });
146
+ * ```
147
+ *
42
148
  * @param current The current context item.
43
149
  * @returns An observable that emits the resolved context item.
44
150
  */
45
151
  resolveContext: (current: ContextItem) => Observable<ContextItem>;
46
152
  /**
47
153
  * Resolves the context item asynchronously.
154
+ *
155
+ * @see {@link resolveContext} for more details.
156
+ *
48
157
  * @param current The current context item.
49
158
  * @returns A promise that resolves to the resolved context item.
50
159
  */
51
160
  resolveContextAsync: (current: ContextItem) => Promise<ContextItem>;
52
161
  /**
53
162
  * Retrieves the related context items based on the provided parameters.
163
+ *
54
164
  * @param args The parameters for retrieving related context items.
55
165
  * @returns An observable that emits an array of related context items.
56
166
  */
57
167
  relatedContexts: (args: RelatedContextParameters) => Observable<Array<ContextItem<Record<string, unknown>>>>;
58
168
  /**
59
169
  * Retrieves the related context items asynchronously based on the provided parameters.
170
+ *
171
+ * @see {@link relatedContexts}
172
+ *
60
173
  * @param args The parameters for retrieving related context items.
61
174
  * @returns A promise that resolves to an array of related context items.
62
175
  */
63
176
  relatedContextsAsync: (args: RelatedContextParameters) => Promise<Array<ContextItem<Record<string, unknown>>>>;
64
177
  /**
65
178
  * Clears the current context.
179
+ * This method will set the current context to `null`.
66
180
  */
67
181
  clearCurrentContext: VoidFunction;
68
182
  /**
69
183
  * Sets the current context item by its ID.
184
+ *
70
185
  * @param id The ID of the context item.
71
186
  * @returns An observable that emits the current context item.
72
187
  */
73
188
  setCurrentContextById(id: string): Observable<ContextItem<Record<string, unknown>>>;
74
189
  /**
75
190
  * Sets the current context item by its ID asynchronously.
191
+ *
192
+ * @see {@link setCurrentContextById}
193
+ *
76
194
  * @param id The ID of the context item.
77
195
  * @returns A promise that resolves to the current context item.
78
196
  */
79
197
  setCurrentContextByIdAsync(id: string): Promise<ContextItem<Record<string, unknown>>>;
80
198
  /**
81
199
  * Sets the current context item.
200
+ *
201
+ * Optionally validates and resolves the context item based on the provided settings.
202
+ *
82
203
  * @param context The context item to set as the current context.
83
204
  * @param opt Optional settings for the operation.
84
205
  * @param opt.validate Specifies whether to validate the context item. Default is `true`.
@@ -91,6 +212,9 @@ export interface IContextProvider {
91
212
  }): Observable<ContextItem<Record<string, unknown>> | null>;
92
213
  /**
93
214
  * Sets the current context item asynchronously.
215
+ *
216
+ * @see {@link setCurrentContext}
217
+ *
94
218
  * @param context The context item to set as the current context.
95
219
  * @param opt Optional settings for the operation.
96
220
  * @param opt.validate Specifies whether to validate the context item. Default is `true`.
@@ -104,19 +228,65 @@ export interface IContextProvider {
104
228
  /**
105
229
  * Method for extracting context id from a path.
106
230
  *
231
+ * @remarks
232
+ * This method extracts the context ID from a given path using the extraction method
233
+ * provided to the provider via the configuration. If no extraction method is configured,
234
+ * it returns undefined.
235
+ *
107
236
  * @param path path to resolve context from
108
237
  * @returns the resolved context item id
238
+ *
239
+ * @example
240
+ * ```ts
241
+ * // configured with extracting id from path like '/context/:id'
242
+ * provider.extractContextIdFromPath('/context/1234'); // returns '1234'
243
+ * ```
109
244
  */
110
245
  extractContextIdFromPath?: (path: string) => string | undefined;
111
246
  /**
112
247
  * Method for generating path from a context item.
113
248
  *
249
+ * @remarks
250
+ * This method generates a path for the context item using the generation method
251
+ * provided to the provider via the configuration. If no generation method is configured,
252
+ * it returns undefined.
253
+ *
114
254
  * @param context context item to generate path from
115
255
  * @param path current path
116
256
  * @returns path for the context item
117
257
  */
118
258
  generatePathFromContext?: (context: ContextItem, path: string) => string | undefined;
119
259
  }
260
+ /**
261
+ * Provides context management functionality, including querying, setting, validating, and resolving context items.
262
+ *
263
+ * The `ContextProvider` class acts as a central service for handling context state, supporting asynchronous operations,
264
+ * event-driven updates, and integration with parent/child context providers. It manages a queue for context changes,
265
+ * supports validation and resolution logic, and can interact with related context items.
266
+ *
267
+ * Key Features:
268
+ * - Maintains the current context and exposes it as both an observable and a property.
269
+ * - Allows querying for context items based on search criteria and filters.
270
+ * - Supports setting the current context by ID or by context item, with optional validation and resolution.
271
+ * - Handles context changes asynchronously, queuing tasks and supporting cancellation.
272
+ * - Integrates with an event module to dispatch and listen for context-related events.
273
+ * - Supports connecting to a parent context provider to synchronize context state.
274
+ * - Provides methods for resolving related contexts and validating context items.
275
+ * - Manages subscriptions and ensures proper resource cleanup via `dispose`.
276
+ *
277
+ * @template T The type of context item managed by the provider.
278
+ *
279
+ * @remarks
280
+ * - Some methods and properties are marked as deprecated and may be removed in future versions.
281
+ * - Event integration is optional and depends on the presence of an event module.
282
+ * - The provider is designed to be extensible and can be configured via the `ContextModuleConfig`.
283
+ *
284
+ * @example
285
+ * ```typescript
286
+ * const provider = new ContextProvider({ config: myConfig, event: myEventModule });
287
+ * provider.setCurrentContextById('context-id').subscribe(...);
288
+ * ```
289
+ */
120
290
  export declare class ContextProvider implements IContextProvider {
121
291
  #private;
122
292
  get contextClient(): ContextClient;
@@ -131,10 +301,50 @@ export declare class ContextProvider implements IContextProvider {
131
301
  /** @deprecated use ContextProvider.connectParentContext */
132
302
  parentContext?: IContextProvider;
133
303
  });
304
+ /**
305
+ * Connects this context provider to a parent context provider, subscribing to changes in the parent's context.
306
+ *
307
+ * When the parent context changes, this method will:
308
+ * - Optionally skip the first emitted value from the parent (if `opt.skipFirst` is true).
309
+ * - Only update the current context if the context ID has changed.
310
+ * - Dispatch an `onParentContextChanged` event before updating, allowing for cancellation.
311
+ * - Set the current context with validation and resolution, handling errors gracefully.
312
+ *
313
+ * The subscription is automatically managed and will be cleaned up with the provider.
314
+ *
315
+ * @param provider - The parent context provider to connect to.
316
+ * @param opt - Optional settings.
317
+ * @param opt.skipFirst - If true, skips the first emitted value from the parent context.
318
+ * @returns A `Subscription` object representing the connection to the parent context.
319
+ */
134
320
  connectParentContext(provider: IContextProvider, opt?: {
135
321
  skipFirst: boolean;
136
322
  }): Subscription;
323
+ /**
324
+ * Sets the current context by resolving a context item using the provided ID.
325
+ *
326
+ * This method attempts to resolve a context item by its unique identifier,
327
+ * filters out any invalid or undefined items, and then sets the current context
328
+ * using the resolved item. The operation is performed as an Observable stream,
329
+ * allowing subscribers to react to the context change or handle errors.
330
+ *
331
+ * @param id - The unique identifier of the context item to resolve and set as current.
332
+ * @returns An Observable that emits the resolved and set {@link ContextItem}.
333
+ * Emits an error if the context cannot be resolved or set.
334
+ */
137
335
  setCurrentContextById(id: string): Observable<ContextItem<Record<string, unknown>>>;
336
+ /**
337
+ * Asynchronously sets the current context by its unique identifier and returns a promise
338
+ * that resolves to the corresponding `ContextItem`.
339
+ *
340
+ * This method wraps the observable returned by `setCurrentContextById` into a promise,
341
+ * allowing for async/await usage.
342
+ *
343
+ * @see {@link setCurrentContextById} for more details.
344
+ *
345
+ * @param id - The unique identifier of the context to set as current.
346
+ * @returns A promise that resolves to the `ContextItem` associated with the given ID.
347
+ */
138
348
  setCurrentContextByIdAsync(id: string): Promise<ContextItem<Record<string, unknown>>>;
139
349
  /**
140
350
  * Setting context is a complex operation, and might not happen immediately.
@@ -151,22 +361,153 @@ export declare class ContextProvider implements IContextProvider {
151
361
  validate?: boolean;
152
362
  resolve?: boolean;
153
363
  }): Observable<T>;
364
+ /**
365
+ * Sets the current context, optionally validating and resolving it.
366
+ *
367
+ * This method emits the provided context as an observable. If the context is the same as the current one,
368
+ * it emits and completes immediately. If validation is requested and fails, it either emits an error or,
369
+ * if resolution is enabled, attempts to resolve the context before setting it. The method dispatches various
370
+ * events to notify listeners about validation failures, resolution steps, and context changes, allowing
371
+ * cancellation at several stages.
372
+ *
373
+ * ### Step-by-step process:
374
+ * 1. **Check if the context is the same as the current one:**
375
+ * - If so, emit the context and complete the observable immediately.
376
+ * 2. **Validate the context (if requested):**
377
+ * - If validation fails and resolution is not enabled:
378
+ * - Dispatch the `onSetContextValidationFailed` event.
379
+ * - Emit an error and complete.
380
+ * - If validation fails but resolution is enabled:
381
+ * - Dispatch the `onSetContextResolve` event (cancelable).
382
+ * - If canceled, throw an error and abort.
383
+ * - Attempt to resolve the context using `resolveContext`.
384
+ * - Dispatch the `onSetContextResolved` event (cancelable) after resolution.
385
+ * - If canceled, throw an error and abort.
386
+ * - Recursively call `_setCurrentContext` with the resolved context (without validation/resolution).
387
+ * 3. **If validation passes or not requested:**
388
+ * - Dispatch the `onCurrentContextChange` event (cancelable).
389
+ * - If canceled, throw an error and abort.
390
+ * - Emit the context and complete the observable.
391
+ *
392
+ * @protected
393
+ * @typeParam T - The type of the context item, which extends `ContextItem<Record<string, unknown>>` or can be `null`.
394
+ * @param context - The new context to set.
395
+ * @param opt - Optional settings:
396
+ * - `validate`: Whether to validate the context before setting.
397
+ * - `resolve`: Whether to attempt to resolve the context if validation fails.
398
+ * @returns An `Observable<T>` that emits the context when set, or errors if validation or resolution fails.
399
+ * @fires onSetContextValidationFailed - When context validation fails and resolution is not enabled.
400
+ * @fires onSetContextResolve - Before attempting to resolve the context.
401
+ * @fires onSetContextResolved - After the context has been resolved.
402
+ * @fires onCurrentContextChange - Before changing the current context.
403
+ * @throws Error if validation fails and resolution is not enabled, or if any event handler cancels the operation.
404
+ */
154
405
  protected _setCurrentContext<T extends ContextItem<Record<string, unknown>> | null>(context: T, opt?: {
155
406
  validate?: boolean;
156
407
  resolve?: boolean;
157
408
  }): Observable<T>;
409
+ /**
410
+ * Asynchronously sets the current context and returns a promise that resolves with the provided context.
411
+ *
412
+ * @see {@link setCurrentContext} for more details.
413
+ *
414
+ * @typeParam T - The type of the context item, which extends `ContextItem<Record<string, unknown>>` or can be `null`.
415
+ * @param context - The context item to set as the current context, or `null` to clear it.
416
+ * @param opt - Optional settings for context handling.
417
+ * @param opt.validate - If `true`, validates the context before setting it.
418
+ * @param opt.resolve - If `true`, resolves any dependencies or references in the context before setting it.
419
+ * @returns A promise that resolves with the context item that was set.
420
+ */
158
421
  setCurrentContextAsync<T extends ContextItem<Record<string, unknown>> | null>(context: T, opt?: {
159
422
  validate?: boolean;
160
423
  resolve?: boolean;
161
424
  }): Promise<T>;
425
+ /**
426
+ * Queries the context for items matching the provided search string.
427
+ *
428
+ * This method constructs query parameters using the given search term and the current context type,
429
+ * then executes the query using the internal query client. If a context filter is defined, it is applied
430
+ * to the results before emitting them. Errors thrown by the query client of type `QueryClientError` will
431
+ * have their underlying cause re-thrown.
432
+ *
433
+ * @param search - The search string to filter context items.
434
+ * @returns An Observable that emits an array of `ContextItem` objects matching the search criteria.
435
+ */
162
436
  queryContext(search: string): Observable<Array<ContextItem>>;
437
+ /**
438
+ * Asynchronously queries the context for items matching the provided search string.
439
+ *
440
+ * @see {@link queryContext} for more details.
441
+ *
442
+ * @param search - The search string used to filter context items.
443
+ * @returns A promise that resolves to an array of `ContextItem` objects matching the search criteria.
444
+ */
163
445
  queryContextAsync(search: string): Promise<Array<ContextItem>>;
446
+ /**
447
+ * Validates whether the provided context item matches one of the allowed context types.
448
+ *
449
+ * @param item - The context item to validate, containing a type with an `id` property.
450
+ * @returns `true` if the context type is not set or if the item's type ID matches one of the allowed types (case-insensitive); otherwise, `false`.
451
+ */
164
452
  validateContext(item: ContextItem<Record<string, unknown>>): boolean;
453
+ /**
454
+ * Resolves a context item by fetching related context items of the same type as configured in the provider.
455
+ *
456
+ * This method:
457
+ * - Requests related context items matching the provider's context type.
458
+ * - Filters out invalid context items using `validateContext`.
459
+ * - Selects the first valid context item, throwing an error if none are found.
460
+ * - Logs a warning if multiple valid context items are found.
461
+ * - Returns the resolved context item as an observable.
462
+ *
463
+ * @param item - The context item for which to resolve related context.
464
+ * @returns An observable emitting the resolved context item.
465
+ * @throws Error if no valid related context item is found.
466
+ */
165
467
  resolveContext(item: ContextItem<Record<string, unknown>>): Observable<ContextItem<Record<string, unknown>>>;
468
+ /**
469
+ * Asynchronously resolves the provided context item.
470
+ *
471
+ * @see {@link resolveContext} for more details.
472
+ *
473
+ * @param item - The context item to resolve.
474
+ * @returns A promise that resolves to the resolved context item.
475
+ */
166
476
  resolveContextAsync(item: ContextItem<Record<string, unknown>>): Promise<ContextItem<Record<string, unknown>>>;
477
+ /**
478
+ * Retrieves related context items based on the provided parameters.
479
+ *
480
+ * This method queries the related context client to fetch an array of context items
481
+ * that are related to the specified parameters. If the related context client is not
482
+ * available, it returns an observable that emits an error.
483
+ *
484
+ * @param args - The parameters used to query for related context items.
485
+ * @returns An Observable that emits an array of related context items.
486
+ * @throws Error if no related context client is defined or if the query fails.
487
+ */
167
488
  relatedContexts(args: RelatedContextParameters): Observable<Array<ContextItem<Record<string, unknown>>>>;
489
+ /**
490
+ * Asynchronously retrieves an array of related context items based on the provided parameters.
491
+ *
492
+ * @see {@link relatedContexts} for more details.
493
+ *
494
+ * @param args - The parameters used to determine which related contexts to retrieve.
495
+ * @returns A promise that resolves to an array of `ContextItem` objects containing generic records.
496
+ */
168
497
  relatedContextsAsync(args: RelatedContextParameters): Promise<Array<ContextItem<Record<string, unknown>>>>;
498
+ /**
499
+ * Clears the current context by setting it to null.
500
+ *
501
+ * This method is typically used to reset or remove the active context,
502
+ * ensuring that subsequent operations do not reference any previous context state.
503
+ */
169
504
  clearCurrentContext(): void;
505
+ /**
506
+ * Disposes of resources held by the context provider.
507
+ *
508
+ * Unsubscribes from all active subscriptions and disposes of the context client,
509
+ * ensuring that any allocated resources are properly released.
510
+ */
170
511
  dispose(): void;
171
512
  }
172
513
  export default ContextProvider;
@@ -5,19 +5,83 @@ export type GetContextParameters = {
5
5
  id: string;
6
6
  };
7
7
  /**
8
- * @todo - add documentation
8
+ * `ContextClient` is an observable client for managing and retrieving context items.
9
+ *
10
+ * This class extends `Observable<ContextItem | null | undefined>`, allowing consumers to subscribe to context changes.
11
+ * It encapsulates a `Query` instance for fetching context items by ID and maintains the current context state using a `BehaviorSubject`.
12
+ *
13
+ * ### Features
14
+ * - Exposes the current context synchronously and as an observable stream.
15
+ * - Provides methods to set the current context by ID or item, resolving and updating as needed.
16
+ * - Supports asynchronous context resolution with optional await behavior.
17
+ * - Handles errors during context resolution, unwrapping nested causes.
18
+ * - Implements a `dispose` method to clean up internal subscriptions.
19
+ *
20
+ * @template ContextItem The type of the context item managed by the client.
21
+ * @extends Observable<ContextItem | null | undefined>
22
+ *
9
23
  * @todo - should this have `undefined` as a valid value?
24
+ *
25
+ * @example
26
+ * ```typescript
27
+ * const client = new ContextClient(options);
28
+ * client.setCurrentContext('context-id');
29
+ * client.currentContext$.subscribe(ctx => { ... });
30
+ * ```
10
31
  */
11
32
  export declare class ContextClient extends Observable<ContextItem | null | undefined> {
12
33
  #private;
34
+ /**
35
+ * Gets the current context item.
36
+ *
37
+ * @returns The current {@link ContextItem}, or `null` if no context is set, or `undefined` if the context has not been initialized.
38
+ */
13
39
  get currentContext(): ContextItem | null | undefined;
40
+ /**
41
+ * An observable stream that emits the current context item.
42
+ *
43
+ * @remarks
44
+ * This observable emits the current `ContextItem` whenever it changes.
45
+ * It can emit `null` or `undefined` if there is no current context.
46
+ *
47
+ * @returns Observable that emits the current `ContextItem`, `null`, or `undefined`.
48
+ */
14
49
  get currentContext$(): Observable<ContextItem | null | undefined>;
50
+ /**
51
+ * Gets the query client for retrieving a specific `ContextItem` by its ID.
52
+ *
53
+ * @returns A `Query` instance configured to fetch a `ContextItem` using an object containing an `id` property.
54
+ */
15
55
  get client(): Query<ContextItem, {
16
56
  id: string;
17
57
  }>;
18
58
  constructor(options: QueryCtorOptions<ContextItem, GetContextParameters>);
59
+ /**
60
+ * Sets the current context based on the provided identifier or context item.
61
+ *
62
+ * If a string identifier is provided, attempts to resolve the corresponding context asynchronously.
63
+ * If a `ContextItem` or `null` is provided, updates the current context only if it differs from the existing one.
64
+ *
65
+ * @param idOrItem - The context identifier (string), a `ContextItem`, or `null`. If omitted, the current context may be cleared.
66
+ */
19
67
  setCurrentContext(idOrItem?: string | ContextItem | null): void;
68
+ /**
69
+ * Resolves a context item by its unique identifier.
70
+ *
71
+ * @param id - The unique identifier of the context item to resolve.
72
+ * @returns An Observable that emits the resolved {@link ContextItem}.
73
+ * @throws Rethrows the underlying error cause if present, otherwise throws the original error.
74
+ */
20
75
  resolveContext(id: string): Observable<ContextItem>;
76
+ /**
77
+ * Resolves a context item asynchronously by its ID.
78
+ *
79
+ * @param id - The unique identifier of the context item to resolve.
80
+ * @param opt - Optional settings for resolution.
81
+ * @param opt.awaitResolve - If true, waits for the observable to complete and returns the last emitted value;
82
+ * otherwise, returns the first emitted value.
83
+ * @returns A promise that resolves to the requested {@link ContextItem}.
84
+ */
21
85
  resolveContextAsync(id: string, opt?: {
22
86
  awaitResolve: boolean;
23
87
  }): Promise<ContextItem>;