@equinor/fusion-framework-module-context 8.0.2 → 9.0.0-next.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.
Files changed (123) hide show
  1. package/CHANGELOG.md +82 -0
  2. package/README.md +78 -2
  3. package/dist/esm/ContextModuleConfig.js +2 -0
  4. package/dist/esm/ContextModuleConfig.js.map +1 -0
  5. package/dist/esm/ContextModuleConfigurator.interface.js +2 -0
  6. package/dist/esm/ContextModuleConfigurator.interface.js.map +1 -0
  7. package/dist/esm/ContextModuleConfigurator.js +211 -0
  8. package/dist/esm/ContextModuleConfigurator.js.map +1 -0
  9. package/dist/esm/ContextProvider.js +1 -1
  10. package/dist/esm/ContextProvider.js.map +1 -1
  11. package/dist/esm/__tests__/ContextModuleConfigurator.test.js +282 -0
  12. package/dist/esm/__tests__/ContextModuleConfigurator.test.js.map +1 -0
  13. package/dist/esm/__tests__/mock/context-mock.test.js +101 -0
  14. package/dist/esm/__tests__/mock/context-mock.test.js.map +1 -0
  15. package/dist/esm/__tests__/mock/create-context-item-factory.test.js +45 -0
  16. package/dist/esm/__tests__/mock/create-context-item-factory.test.js.map +1 -0
  17. package/dist/esm/__tests__/mock/create-context-items.test.js +46 -0
  18. package/dist/esm/__tests__/mock/create-context-items.test.js.map +1 -0
  19. package/dist/esm/index.js +1 -1
  20. package/dist/esm/index.js.map +1 -1
  21. package/dist/esm/mock/ContextMockConfigurator.js +206 -0
  22. package/dist/esm/mock/ContextMockConfigurator.js.map +1 -0
  23. package/dist/esm/mock/fixtures/create-context-item-factory.js +50 -0
  24. package/dist/esm/mock/fixtures/create-context-item-factory.js.map +1 -0
  25. package/dist/esm/mock/fixtures/create-context-items.js +53 -0
  26. package/dist/esm/mock/fixtures/create-context-items.js.map +1 -0
  27. package/dist/esm/mock/fixtures/index.js +22 -0
  28. package/dist/esm/mock/fixtures/index.js.map +1 -0
  29. package/dist/esm/mock/fixtures/string-to-seed.js +15 -0
  30. package/dist/esm/mock/fixtures/string-to-seed.js.map +1 -0
  31. package/dist/esm/mock/index.js +31 -0
  32. package/dist/esm/mock/index.js.map +1 -0
  33. package/dist/esm/mock/module.js +41 -0
  34. package/dist/esm/mock/module.js.map +1 -0
  35. package/dist/esm/module.js +35 -6
  36. package/dist/esm/module.js.map +1 -1
  37. package/dist/esm/{get-context-selector.js → selectors/get-context-selector.js} +1 -4
  38. package/dist/esm/selectors/get-context-selector.js.map +1 -0
  39. package/dist/esm/selectors/index.js +13 -0
  40. package/dist/esm/selectors/index.js.map +1 -0
  41. package/dist/esm/{query-context-selector.js → selectors/query-context-selector.js} +1 -1
  42. package/dist/esm/selectors/query-context-selector.js.map +1 -0
  43. package/dist/esm/{related-context-selector.js → selectors/related-context-selector.js} +1 -1
  44. package/dist/esm/selectors/related-context-selector.js.map +1 -0
  45. package/dist/esm/utils/enable-context.js +1 -1
  46. package/dist/esm/utils/enable-context.js.map +1 -1
  47. package/dist/esm/utils/index.js +2 -0
  48. package/dist/esm/utils/index.js.map +1 -1
  49. package/dist/esm/utils/parse-context-item.js.map +1 -0
  50. package/dist/esm/utils/resolve-initial-context.js +16 -7
  51. package/dist/esm/utils/resolve-initial-context.js.map +1 -1
  52. package/dist/esm/version.js +1 -1
  53. package/dist/esm/version.js.map +1 -1
  54. package/dist/tsconfig.tsbuildinfo +1 -1
  55. package/dist/types/{configurator.d.ts → ContextModuleConfig.d.ts} +4 -64
  56. package/dist/types/ContextModuleConfigurator.d.ts +97 -0
  57. package/dist/types/{ContextConfigBuilder.d.ts → ContextModuleConfigurator.interface.d.ts} +27 -47
  58. package/dist/types/ContextProvider.d.ts +1 -1
  59. package/dist/types/__tests__/ContextModuleConfigurator.test.d.ts +1 -0
  60. package/dist/types/__tests__/mock/context-mock.test.d.ts +1 -0
  61. package/dist/types/__tests__/mock/create-context-item-factory.test.d.ts +1 -0
  62. package/dist/types/__tests__/mock/create-context-items.test.d.ts +1 -0
  63. package/dist/types/index.d.ts +3 -1
  64. package/dist/types/mock/ContextMockConfigurator.d.ts +155 -0
  65. package/dist/types/mock/fixtures/create-context-item-factory.d.ts +40 -0
  66. package/dist/types/mock/fixtures/create-context-items.d.ts +59 -0
  67. package/dist/types/mock/fixtures/index.d.ts +21 -0
  68. package/dist/types/mock/fixtures/string-to-seed.d.ts +12 -0
  69. package/dist/types/mock/index.d.ts +30 -0
  70. package/dist/types/mock/module.d.ts +38 -0
  71. package/dist/types/module.d.ts +5 -3
  72. package/dist/types/{get-context-selector.d.ts → selectors/get-context-selector.d.ts} +1 -3
  73. package/dist/types/selectors/index.d.ts +12 -0
  74. package/dist/types/{query-context-selector.d.ts → selectors/query-context-selector.d.ts} +1 -1
  75. package/dist/types/{related-context-selector.d.ts → selectors/related-context-selector.d.ts} +1 -1
  76. package/dist/types/utils/enable-context.d.ts +4 -5
  77. package/dist/types/utils/index.d.ts +2 -0
  78. package/dist/types/{parse-context-item.d.ts → utils/parse-context-item.d.ts} +1 -1
  79. package/dist/types/utils/resolve-initial-context.d.ts +7 -4
  80. package/dist/types/version.d.ts +1 -1
  81. package/docs/data-model.md +134 -0
  82. package/docs/lifecycle.md +163 -0
  83. package/docs/recipes.md +89 -0
  84. package/package.json +36 -8
  85. package/src/ContextModuleConfig.ts +147 -0
  86. package/src/ContextModuleConfigurator.interface.ts +145 -0
  87. package/src/ContextModuleConfigurator.ts +295 -0
  88. package/src/ContextProvider.ts +1 -2
  89. package/src/__tests__/ContextModuleConfigurator.test.ts +412 -0
  90. package/src/__tests__/mock/context-mock.test.ts +137 -0
  91. package/src/__tests__/mock/create-context-item-factory.test.ts +60 -0
  92. package/src/__tests__/mock/create-context-items.test.ts +58 -0
  93. package/src/index.ts +3 -5
  94. package/src/mock/ContextMockConfigurator.ts +244 -0
  95. package/src/mock/fixtures/create-context-item-factory.ts +62 -0
  96. package/src/mock/fixtures/create-context-items.ts +80 -0
  97. package/src/mock/fixtures/index.ts +28 -0
  98. package/src/mock/fixtures/string-to-seed.ts +18 -0
  99. package/src/mock/index.ts +33 -0
  100. package/src/mock/module.ts +54 -0
  101. package/src/module.ts +45 -17
  102. package/src/{get-context-selector.ts → selectors/get-context-selector.ts} +2 -6
  103. package/src/selectors/index.ts +12 -0
  104. package/src/{query-context-selector.ts → selectors/query-context-selector.ts} +2 -2
  105. package/src/{related-context-selector.ts → selectors/related-context-selector.ts} +2 -2
  106. package/src/utils/enable-context.ts +6 -10
  107. package/src/utils/index.ts +2 -0
  108. package/src/{parse-context-item.ts → utils/parse-context-item.ts} +1 -1
  109. package/src/utils/resolve-initial-context.ts +26 -8
  110. package/src/version.ts +1 -1
  111. package/tsconfig.json +6 -0
  112. package/vitest.config.ts +11 -0
  113. package/dist/esm/ContextConfigBuilder.js +0 -175
  114. package/dist/esm/ContextConfigBuilder.js.map +0 -1
  115. package/dist/esm/configurator.js +0 -99
  116. package/dist/esm/configurator.js.map +0 -1
  117. package/dist/esm/get-context-selector.js.map +0 -1
  118. package/dist/esm/parse-context-item.js.map +0 -1
  119. package/dist/esm/query-context-selector.js.map +0 -1
  120. package/dist/esm/related-context-selector.js.map +0 -1
  121. package/src/ContextConfigBuilder.ts +0 -258
  122. package/src/configurator.ts +0 -295
  123. /package/dist/esm/{parse-context-item.js → utils/parse-context-item.js} +0 -0
@@ -1,258 +0,0 @@
1
- import type {
2
- AnyModule,
3
- ModuleInitializerArgs,
4
- Modules,
5
- ModuleType,
6
- } from '@equinor/fusion-framework-module';
7
-
8
- import type { QueryCtorOptions, QueryFn } from '@equinor/fusion-query';
9
-
10
- import type { GetContextParameters } from './client/ContextClient';
11
-
12
- import type {
13
- ContextModuleConfig,
14
- ContextModuleConfigurator,
15
- IContextModuleConfigurator,
16
- } from './configurator';
17
-
18
- import type { ContextItem, QueryContextParameters, RelatedContextParameters } from './types';
19
-
20
- /**
21
- * Callback passed to {@link IContextModuleConfigurator.addConfigBuilder}.
22
- *
23
- * Receives a {@link ContextConfigBuilder} and may use its setter methods
24
- * to populate the context module configuration. The callback may be async.
25
- *
26
- * @typeParam TDeps - Module dependency array inferred from the configurator.
27
- */
28
- export type ContextConfigBuilderCallback = <TDeps extends Array<AnyModule> = []>(
29
- builder: ContextConfigBuilder<TDeps, ModuleInitializerArgs<IContextModuleConfigurator, TDeps>>,
30
- ) => void | Promise<void>;
31
-
32
- /**
33
- * A builder class for configuring and customizing context module behavior within the Fusion Framework.
34
- *
35
- * `ContextConfigBuilder` provides a fluent API for setting up various aspects of context management,
36
- * including context type, filtering, parent context connection, parameter resolution, validation,
37
- * path extraction/generation, and client configuration for fetching context items.
38
- *
39
- * @typeParam TModules - An array of modules that extend `AnyModule`. Defaults to an empty array.
40
- * @typeParam TInit - The initializer arguments for the module, extending `ModuleInitializerArgs`.
41
- *
42
- * @example
43
- * ```typescript
44
- * const builder = new ContextConfigBuilder(init);
45
- * builder.setContextType(['ProjectMaster']);
46
- * builder.setContextFilter(items => items.filter(ctx => ctx.isActive));
47
- * builder.setContextClient({ get: fetchContextItem, query: fetchContextItems });
48
- * ```
49
- *
50
- * @remarks
51
- * - Use the provided setter methods to customize context behavior as needed.
52
- * - The builder pattern allows chaining configuration methods for clarity and convenience.
53
- * - The `requireInstance` method enables asynchronous retrieval of module instances by name.
54
- *
55
- * @todo(#5120) - this should extend the BaseConfigBuilder
56
- *
57
- * @see ContextModuleConfig
58
- * @see ModuleInitializerArgs
59
- */
60
- export class ContextConfigBuilder<
61
- TModules extends Array<AnyModule> = [],
62
- // biome-ignore lint/suspicious/noExplicitAny: `ModuleInitializerArgs<any, any>` widens the constraint to accept initializer args for any configurator/module set \u2014 `unknown` breaks assignability of the concrete default type argument
63
- TInit extends ModuleInitializerArgs<any, any> = ModuleInitializerArgs<
64
- ContextModuleConfigurator,
65
- TModules
66
- >,
67
- > {
68
- #init: TInit;
69
- /**
70
- * Creates a new `ContextConfigBuilder`.
71
- * @param init - Module initializer arguments used to resolve module instances.
72
- * @param config - The partial context module config to build upon.
73
- */
74
- constructor(
75
- init: TInit,
76
- public config: Partial<ContextModuleConfig> = {},
77
- ) {
78
- this.#init = init;
79
- }
80
-
81
- /**
82
- * Requires a module instance by its registered key.
83
- * @param module - The key of the module to resolve.
84
- * @returns A promise that resolves to the requested module instance.
85
- */
86
- requireInstance<TKey extends string = Extract<keyof Modules, string>>(
87
- module: TKey,
88
- ): Promise<ModuleType<Modules[TKey]>>;
89
-
90
- /**
91
- * Requires a module instance by name.
92
- * @param module - The name of the module to resolve.
93
- * @returns A promise that resolves to the requested module instance.
94
- */
95
- requireInstance<T>(module: string): Promise<T>;
96
-
97
- /**
98
- * Requires a module instance by key or name.
99
- * @param module - The key or name of the module to resolve.
100
- * @returns A promise that resolves to the requested module instance.
101
- */
102
- requireInstance(
103
- module: string,
104
- // biome-ignore lint/suspicious/noExplicitAny: implementation signature must satisfy both overloads above (`Promise<ModuleType<...>>` and `Promise<T>`); `unknown` is not assignable to the generic `Promise<T>` overload
105
- ): Promise<any> {
106
- return this.#init.requireInstance(module);
107
- }
108
-
109
- /**
110
- * Sets the context type for the current configuration.
111
- *
112
- * @param type - The context type to assign, as defined by `ContextModuleConfig['contextType']`.
113
- */
114
- setContextType(type: ContextModuleConfig['contextType']) {
115
- this.config.contextType = type;
116
- }
117
-
118
- /**
119
- * Sets the context filter function for the configuration.
120
- *
121
- * @param filter - A function that determines whether a context should be included, as defined by `ContextModuleConfig['contextFilter']`.
122
- */
123
- setContextFilter(filter: ContextModuleConfig['contextFilter']) {
124
- this.config.contextFilter = filter;
125
- }
126
-
127
- /**
128
- * Sets the function or configuration used to connect to a parent context.
129
- *
130
- * @param connect - The function or configuration that defines how to connect to the parent context.
131
- */
132
- connectParentContext(connect: ContextModuleConfig['connectParentContext']) {
133
- this.config.connectParentContext = connect;
134
- }
135
-
136
- /**
137
- * Sets the function used to provide context parameters for the module configuration.
138
- *
139
- * @param fn - A function conforming to the `contextParameterFn` type defined in `ContextModuleConfig`.
140
- */
141
- setContextParameterFn(fn: ContextModuleConfig['contextParameterFn']) {
142
- this.config.contextParameterFn = fn;
143
- }
144
-
145
- /**
146
- * Sets the function used to validate the context within the configuration.
147
- *
148
- * @param fn - A function that implements the `validateContext` signature from `ContextModuleConfig`.
149
- */
150
- setValidateContext(fn: ContextModuleConfig['validateContext']) {
151
- this.config.validateContext = fn;
152
- }
153
-
154
- /**
155
- * Sets the function used to resolve the context for the module configuration.
156
- *
157
- * @param fn - A function that defines how the context should be resolved, conforming to the `resolveContext` type from `ContextModuleConfig`.
158
- */
159
- setResolveContext(fn: ContextModuleConfig['resolveContext']) {
160
- this.config.resolveContext = fn;
161
- }
162
-
163
- /**
164
- * Sets the function responsible for extracting the context ID from a given path.
165
- *
166
- * @param fn - A function that defines how to extract the context ID from a path.
167
- * This function should match the type defined in `ContextModuleConfig['extractContextIdFromPath']`.
168
- */
169
- setContextPathExtractor(fn: ContextModuleConfig['extractContextIdFromPath']) {
170
- this.config.extractContextIdFromPath = fn;
171
- }
172
-
173
- /**
174
- * Sets the function responsible for generating a path from the context.
175
- *
176
- * @param fn - A function that takes a context and generates a corresponding path.
177
- */
178
- setContextPathGenerator(fn: ContextModuleConfig['generatePathFromContext']) {
179
- this.config.generatePathFromContext = fn;
180
- }
181
-
182
- /**
183
- * Sets the function used to resolve the initial context during module post-initialization.
184
- *
185
- * @param fn - A function that returns an observable input emitting the initial context item.
186
- * The default resolver extracts a context ID from the navigation path, falling
187
- * back to the parent provider's current context.
188
- */
189
- setResolveInitialContext(fn: ContextModuleConfig['resolveInitialContext']) {
190
- this.config.resolveInitialContext = fn;
191
- }
192
-
193
- /**
194
- * Sets the context client configuration for fetching context items.
195
- *
196
- * This method allows you to provide custom query functions or query constructor options
197
- * for retrieving single context items (`get`), querying multiple context items (`query`),
198
- * and optionally fetching related context items (`related`). Each query can be provided
199
- * as either a function or a configuration object. The expiration time for cached results
200
- * can also be specified.
201
- *
202
- * @param client - An object containing the query functions or options for `get`, `query`, and optionally `related` context items.
203
- * @param expire - Optional. The expiration time (in milliseconds) for cached query results. Defaults to 1 minute.
204
- */
205
- setContextClient(
206
- client: {
207
- get:
208
- | QueryFn<ContextItem, GetContextParameters>
209
- | QueryCtorOptions<ContextItem, GetContextParameters>;
210
- query:
211
- | QueryFn<ContextItem[], QueryContextParameters>
212
- | QueryCtorOptions<ContextItem[], QueryContextParameters>;
213
- related?:
214
- | QueryFn<ContextItem[], RelatedContextParameters>
215
- | QueryCtorOptions<ContextItem[], RelatedContextParameters>;
216
- },
217
- expire = 1 * 60 * 1000,
218
- ): void {
219
- const clientConfig: ContextModuleConfig['client'] = {
220
- get:
221
- typeof client.get === 'function'
222
- ? {
223
- key: ({ id }) => id,
224
- client: {
225
- fn: client.get,
226
- },
227
- expire,
228
- }
229
- : client.get,
230
- query:
231
- typeof client.query === 'function'
232
- ? {
233
- // TODO(#5118) - might cast to checksum
234
- key: (args) => JSON.stringify(args),
235
- client: {
236
- fn: client.query,
237
- },
238
- expire,
239
- }
240
- : client.query,
241
- };
242
- this.config.client = clientConfig;
243
- // only override the related-context client config if one was provided
244
- if (client.related) {
245
- clientConfig.related =
246
- typeof client.related === 'function'
247
- ? {
248
- // TODO(#5118) - might cast to checksum
249
- key: (args) => JSON.stringify(args),
250
- client: {
251
- fn: client.related,
252
- },
253
- expire,
254
- }
255
- : client.related;
256
- }
257
- }
258
- }
@@ -1,295 +0,0 @@
1
- import type { ObservableInput } from 'rxjs';
2
-
3
- import type {
4
- AnyModuleInstance,
5
- ModuleInitializerArgs,
6
- ModuleInstance,
7
- ModulesInstanceType,
8
- } from '@equinor/fusion-framework-module';
9
- import type { ServicesModule, IApiProvider } from '@equinor/fusion-framework-module-services';
10
- import type { NavigationModule } from '@equinor/fusion-framework-module-navigation';
11
- import {
12
- getContextSelector,
13
- queryContextSelector,
14
- relatedContextSelector,
15
- } from './get-context-selector';
16
- import type { QueryCtorOptions } from '@equinor/fusion-query';
17
- import type {
18
- ContextFilterFn,
19
- ContextItem,
20
- QueryContextParameters,
21
- RelatedContextParameters,
22
- } from './types';
23
- import type { GetContextParameters } from './client/ContextClient';
24
- import { ContextConfigBuilder, type ContextConfigBuilderCallback } from './ContextConfigBuilder';
25
- import type { IContextProvider } from './ContextProvider';
26
- import resolveInitialContext from './utils/resolve-initial-context';
27
-
28
- /**
29
- * Resolved configuration for the context module.
30
- *
31
- * Holds query clients, type filters, parent-connection settings, and
32
- * optional callbacks for validation, resolution, and path integration.
33
- * Produced by {@link ContextModuleConfigurator.createConfig} after all
34
- * {@link ContextConfigBuilder} callbacks have run.
35
- *
36
- * @see ContextConfigBuilder — fluent API for populating this config.
37
- * @see ContextProvider — runtime consumer of this config.
38
- */
39
- export interface ContextModuleConfig {
40
- /**
41
- * Query client options used to fetch, search, and resolve related context items.
42
- *
43
- * - `get` — retrieves a single context item by ID.
44
- * - `query` — searches context items by text and optional type filter.
45
- * - `related` — fetches context items related to a given item (used during resolution).
46
- */
47
- client: {
48
- get: QueryCtorOptions<ContextItem, GetContextParameters>;
49
- query: QueryCtorOptions<ContextItem[], QueryContextParameters>;
50
- related?: QueryCtorOptions<ContextItem[], RelatedContextParameters>;
51
- };
52
-
53
- /**
54
- * Allowed context type IDs (e.g. `['ProjectMaster', 'Facility']`).
55
- *
56
- * When set, {@link ContextProvider.validateContext} only accepts items
57
- * whose `type.id` matches one of these values (case-insensitive).
58
- */
59
- contextType?: string[];
60
-
61
- /**
62
- * Optional post-query filter applied to the result set returned by
63
- * {@link ContextProvider.queryContext}.
64
- */
65
- contextFilter?: ContextFilterFn;
66
-
67
- /**
68
- * Whether to connect the context module to a parent context module.
69
- *
70
- * When `true` (the default), the provider subscribes to the parent's
71
- * `currentContext$` and mirrors changes into its own state.
72
- *
73
- * @defaultValue `true`
74
- */
75
- connectParentContext?: boolean;
76
-
77
- /**
78
- * When `true`, skips resolving an initial context from the path or parent
79
- * during module post-initialization.
80
- */
81
- skipInitialContext?: boolean;
82
-
83
- /**
84
- * Extracts a context ID from a URL path segment.
85
- *
86
- * Used during initial context resolution and deep-link support.
87
- * If not provided, the default GUID-based extractor is used.
88
- *
89
- * @param path - The URL path to inspect.
90
- * @returns The extracted context ID, or `undefined` if none is found.
91
- */
92
- extractContextIdFromPath?: (path: string) => string | undefined;
93
-
94
- /**
95
- * Generates a URL path that embeds the given context item's ID.
96
- *
97
- * Used by navigation integrations to update the browser URL when
98
- * the context changes.
99
- *
100
- * @param context - The active context item.
101
- * @param path - The current URL path.
102
- * @returns The updated path, or `undefined` to leave it unchanged.
103
- */
104
- generatePathFromContext?: (context: ContextItem, path: string) => string | undefined;
105
-
106
- /**
107
- * Transforms a user search string and the configured context type into
108
- * the query parameters sent to the context API.
109
- *
110
- * Override this to customise how free-text searches are mapped to the
111
- * backend query contract.
112
- */
113
- contextParameterFn?: (args: {
114
- search: string;
115
- type: ContextModuleConfig['contextType'];
116
- }) => string | QueryContextParameters;
117
-
118
- /**
119
- * Custom context resolution strategy.
120
- *
121
- * Called with `this` bound to the {@link IContextProvider} when a context
122
- * item fails validation and the caller requests resolution.
123
- *
124
- * @param item - The context item to resolve, or `null`.
125
- * @returns An observable emitting the resolved context item.
126
- */
127
- resolveContext?: (
128
- this: IContextProvider,
129
- item: ContextItem | null,
130
- ) => ReturnType<IContextProvider['resolveContext']>;
131
-
132
- /**
133
- * Custom context validation strategy.
134
- *
135
- * Called with `this` bound to the {@link IContextProvider} to decide
136
- * whether a candidate context item is acceptable.
137
- *
138
- * @param item - The context item to validate, or `null`.
139
- * @returns `true` if the item is valid.
140
- */
141
- validateContext?: (
142
- this: IContextProvider,
143
- item: ContextItem | null,
144
- ) => ReturnType<IContextProvider['validateContext']>;
145
-
146
- /**
147
- * Resolves the initial context during module post-initialization.
148
- *
149
- * The default implementation tries to extract a context ID from the
150
- * current navigation path, falling back to the parent provider's context.
151
- *
152
- * @param args - Module reference and instance map.
153
- * @returns An observable input emitting the initial context item, or void.
154
- */
155
- resolveInitialContext?: (args: {
156
- // biome-ignore lint/suspicious/noExplicitAny: `AnyModuleInstance | any` intentionally widens to accept any module instance shape for `ref`
157
- ref?: AnyModuleInstance | any;
158
- modules: ModuleInstance;
159
- // biome-ignore lint/suspicious/noConfusingVoidType: `void` here relies on TypeScript's special-cased "void-returning callback accepts any return value" behavior — `undefined` would break assignability of resolver functions that only conditionally emit a `ContextItem`
160
- }) => ObservableInput<ContextItem | void>;
161
- }
162
-
163
- /**
164
- * Public configurator contract for the context module.
165
- *
166
- * Consumers call {@link addConfigBuilder} to register one or more
167
- * {@link ContextConfigBuilderCallback} functions that will run during
168
- * module initialization to populate the {@link ContextModuleConfig}.
169
- */
170
- export interface IContextModuleConfigurator {
171
- /**
172
- * Registers a configuration callback that receives a {@link ContextConfigBuilder}.
173
- *
174
- * Multiple builders can be added; they execute sequentially and merge
175
- * their results into a single {@link ContextModuleConfig}.
176
- *
177
- * @param init - Builder callback invoked during module initialization.
178
- */
179
- addConfigBuilder: (init: ContextConfigBuilderCallback) => void;
180
- }
181
-
182
- /**
183
- * Default implementation of {@link IContextModuleConfigurator}.
184
- *
185
- * Collects {@link ContextConfigBuilderCallback} registrations and, when
186
- * {@link createConfig} is called, runs them in order against a
187
- * {@link ContextConfigBuilder} to produce the final {@link ContextModuleConfig}.
188
- *
189
- * If no custom client is configured, the configurator falls back to
190
- * creating one from the {@link ServicesModule} API provider.
191
- */
192
- export class ContextModuleConfigurator implements IContextModuleConfigurator {
193
- /** Default cache TTL (in ms) for context query results. */
194
- defaultExpireTime = 1 * 60 * 1000;
195
-
196
- #configBuilders: Array<ContextConfigBuilderCallback> = [];
197
-
198
- /** @inheritdoc */
199
- addConfigBuilder(init: ContextConfigBuilderCallback): void {
200
- this.#configBuilders.push(init);
201
- }
202
-
203
- /**
204
- * Resolves the services API provider, preferring the local module
205
- * instance and falling back to the parent module.
206
- *
207
- * @param init - Module initializer arguments.
208
- * @returns The resolved API provider.
209
- * @throws Error if no services module is available.
210
- */
211
- protected async _getServiceProvider(
212
- init: ModuleInitializerArgs<IContextModuleConfigurator, [ServicesModule]>,
213
- ): Promise<IApiProvider> {
214
- // prefer the local services module instance if available
215
- if (init.hasModule('services')) {
216
- return init.requireInstance('services');
217
- }
218
- const parentServiceModule = (init.ref as ModulesInstanceType<[ServicesModule]>)?.services;
219
- // fall back to the parent module's services instance
220
- if (!parentServiceModule) {
221
- throw Error('no service services provider configures [ServicesModule]');
222
- }
223
- return parentServiceModule;
224
- }
225
-
226
- /**
227
- * Runs all registered config builders and produces the final
228
- * {@link ContextModuleConfig}.
229
- *
230
- * If no `resolveInitialContext` was set, the default path + parent
231
- * resolver is used. If no `client` was set, one is created from the
232
- * {@link ServicesModule} API provider.
233
- *
234
- * @param init - Module initializer arguments including dependency instances.
235
- * @returns The fully resolved context module configuration.
236
- */
237
- public async createConfig(
238
- init: ModuleInitializerArgs<IContextModuleConfigurator, [ServicesModule, NavigationModule]>,
239
- ): Promise<ContextModuleConfig> {
240
- // run each registered config builder in sequence, merging results into the accumulated config
241
- const config = await this.#configBuilders.reduce(
242
- async (cur, cb) => {
243
- // biome-ignore lint/suspicious/noExplicitAny: builder generics are erased here — `unknown` breaks assignability of the concrete `ContextConfigBuilder` instance passed to consumer callbacks
244
- const builder = new ContextConfigBuilder<any, any>(init, await cur);
245
- await Promise.resolve(cb(builder));
246
- // Merge this builder's config into the accumulator for the next iteration.
247
- return Object.assign(cur, builder.config);
248
- },
249
- Promise.resolve({} as Partial<ContextModuleConfig>),
250
- );
251
-
252
- config.resolveInitialContext ??= resolveInitialContext();
253
-
254
- // TODO(#5119) - make less lazy
255
- config.client ??= await (async (): Promise<ContextModuleConfig['client']> => {
256
- const apiProvider = await this._getServiceProvider(init);
257
- const contextClient = await apiProvider.createContextClient('json$');
258
- return {
259
- get: {
260
- client: {
261
- fn: (args) => contextClient.get('v1', args, { selector: getContextSelector }),
262
- },
263
- key: ({ id }) => id,
264
- expire: this.defaultExpireTime,
265
- },
266
- query: {
267
- client: {
268
- fn: (query) => contextClient.query('v1', { query }, { selector: queryContextSelector }),
269
- },
270
- // TODO(#5118) - might cast to checksum
271
- key: (args) => JSON.stringify(args),
272
- expire: this.defaultExpireTime,
273
- },
274
- related: {
275
- client: {
276
- fn: (args) => {
277
- return contextClient.related(
278
- 'v1',
279
- { id: args.item.id, query: { filter: args.filter } },
280
- { selector: relatedContextSelector },
281
- );
282
- },
283
- },
284
- // TODO(#5118) - might cast to checksum
285
- key: (args) => JSON.stringify(args),
286
- expire: this.defaultExpireTime,
287
- },
288
- };
289
- })();
290
-
291
- return config as ContextModuleConfig;
292
- }
293
- }
294
-
295
- export default ContextModuleConfigurator;