@fgv/ts-res 5.0.0-21 → 5.0.0-23

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 (197) hide show
  1. package/README.md +794 -137
  2. package/dist/ts-res.d.ts +506 -33
  3. package/lib/packlets/common/convert.d.ts +10 -0
  4. package/lib/packlets/common/convert.js +11 -1
  5. package/lib/packlets/common/resources.d.ts +40 -1
  6. package/lib/packlets/common/validate/regularExpressions.d.ts +4 -0
  7. package/lib/packlets/common/validate/regularExpressions.js +5 -1
  8. package/lib/packlets/common/validate/resources.d.ts +35 -1
  9. package/lib/packlets/common/validate/resources.js +54 -0
  10. package/lib/packlets/config/convert.js +1 -1
  11. package/lib/packlets/config/json.d.ts +1 -1
  12. package/lib/packlets/qualifier-types/config/convert.d.ts +22 -1
  13. package/lib/packlets/qualifier-types/config/convert.js +67 -2
  14. package/lib/packlets/qualifier-types/config/json.d.ts +11 -2
  15. package/lib/packlets/qualifier-types/helpers.d.ts +1 -2
  16. package/lib/packlets/qualifier-types/languageQualifierType.d.ts +27 -1
  17. package/lib/packlets/qualifier-types/languageQualifierType.js +75 -0
  18. package/lib/packlets/qualifier-types/literalQualifierType.d.ts +30 -4
  19. package/lib/packlets/qualifier-types/literalQualifierType.js +77 -0
  20. package/lib/packlets/qualifier-types/literalValueHierarchy.d.ts +6 -10
  21. package/lib/packlets/qualifier-types/literalValueHierarchy.js +10 -0
  22. package/lib/packlets/qualifier-types/qualifierType.d.ts +28 -0
  23. package/lib/packlets/qualifier-types/territoryQualifierType.d.ts +28 -4
  24. package/lib/packlets/qualifier-types/territoryQualifierType.js +77 -0
  25. package/lib/packlets/resource-json/compiled/convert.js +2 -1
  26. package/lib/packlets/resource-json/compiled/json.d.ts +6 -2
  27. package/lib/packlets/resource-types/config/convert.js +3 -1
  28. package/lib/packlets/resource-types/config/json.d.ts +2 -0
  29. package/lib/packlets/resource-types/jsonResourceType.d.ts +10 -6
  30. package/lib/packlets/resource-types/jsonResourceType.js +7 -10
  31. package/lib/packlets/resource-types/resourceType.d.ts +20 -8
  32. package/lib/packlets/resource-types/resourceType.js +20 -16
  33. package/lib/packlets/resources/candidateValue.d.ts +92 -0
  34. package/lib/packlets/resources/candidateValue.js +128 -0
  35. package/lib/packlets/resources/candidateValueCollector.d.ts +55 -0
  36. package/lib/packlets/resources/candidateValueCollector.js +96 -0
  37. package/lib/packlets/resources/index.d.ts +2 -0
  38. package/lib/packlets/resources/index.js +2 -0
  39. package/lib/packlets/resources/resource.js +2 -2
  40. package/lib/packlets/resources/resourceBuilder.d.ts +6 -0
  41. package/lib/packlets/resources/resourceBuilder.js +3 -1
  42. package/lib/packlets/resources/resourceCandidate.d.ts +10 -1
  43. package/lib/packlets/resources/resourceCandidate.js +11 -5
  44. package/lib/packlets/resources/resourceManagerBuilder.d.ts +7 -0
  45. package/lib/packlets/resources/resourceManagerBuilder.js +13 -6
  46. package/lib/packlets/runtime/compiledResourceCollection.d.ts +20 -8
  47. package/lib/packlets/runtime/compiledResourceCollection.js +25 -4
  48. package/lib/packlets/runtime/resource-tree/common.d.ts +1 -1
  49. package/lib/packlets/runtime/resourceResolver.d.ts +39 -1
  50. package/lib/packlets/runtime/resourceResolver.js +45 -28
  51. package/lib/test/unit/qualifier-types/testQualifierType.d.ts +4 -0
  52. package/lib/test/unit/qualifier-types/testQualifierType.js +24 -0
  53. package/lib/test/unit/resource-types/derivedResourceType.test.d.ts +2 -0
  54. package/lib/test/unit/resource-types/testDerivedResourceType.d.ts +79 -0
  55. package/lib/test/unit/resource-types/testDerivedResourceType.js +113 -0
  56. package/lib/test/unit/resources/candidateValue.test.d.ts +2 -0
  57. package/lib/test/unit/resources/candidateValueCollector.test.d.ts +2 -0
  58. package/lib/test/unit/runtime/resourceResolver.coverage.test.d.ts +2 -0
  59. package/lib/test/unit/runtime/resourceResolver.newFeatures.test.d.ts +2 -0
  60. package/package.json +7 -7
  61. package/src/index.ts +0 -75
  62. package/src/packlets/bundle/bundleBuilder.ts +0 -159
  63. package/src/packlets/bundle/bundleLoader.ts +0 -157
  64. package/src/packlets/bundle/bundleNormalizer.ts +0 -173
  65. package/src/packlets/bundle/bundleUtils.ts +0 -142
  66. package/src/packlets/bundle/convert.ts +0 -87
  67. package/src/packlets/bundle/index.ts +0 -52
  68. package/src/packlets/bundle/model.ts +0 -138
  69. package/src/packlets/common/conditions.ts +0 -226
  70. package/src/packlets/common/convert.ts +0 -184
  71. package/src/packlets/common/helpers/conditions.ts +0 -84
  72. package/src/packlets/common/helpers/context.ts +0 -88
  73. package/src/packlets/common/helpers/index.ts +0 -26
  74. package/src/packlets/common/helpers/qualifierDefaultValues.ts +0 -91
  75. package/src/packlets/common/helpers/resources.ts +0 -96
  76. package/src/packlets/common/index.ts +0 -30
  77. package/src/packlets/common/resources.ts +0 -78
  78. package/src/packlets/common/validate/conditions.ts +0 -595
  79. package/src/packlets/common/validate/index.ts +0 -27
  80. package/src/packlets/common/validate/regularExpressions.ts +0 -92
  81. package/src/packlets/common/validate/resources.ts +0 -170
  82. package/src/packlets/conditions/condition.ts +0 -351
  83. package/src/packlets/conditions/conditionCollector.ts +0 -103
  84. package/src/packlets/conditions/conditionDecls.ts +0 -50
  85. package/src/packlets/conditions/conditionSet.ts +0 -318
  86. package/src/packlets/conditions/conditionSetCollector.ts +0 -127
  87. package/src/packlets/conditions/conditionSetDecls.ts +0 -41
  88. package/src/packlets/conditions/conditionToken.ts +0 -180
  89. package/src/packlets/conditions/convert/conditionSetDecls.ts +0 -72
  90. package/src/packlets/conditions/convert/decls.ts +0 -95
  91. package/src/packlets/conditions/convert/index.ts +0 -24
  92. package/src/packlets/conditions/index.ts +0 -33
  93. package/src/packlets/config/common.ts +0 -107
  94. package/src/packlets/config/configInitFactory.ts +0 -142
  95. package/src/packlets/config/convert.ts +0 -61
  96. package/src/packlets/config/index.ts +0 -30
  97. package/src/packlets/config/json.ts +0 -43
  98. package/src/packlets/config/predefined/default.ts +0 -150
  99. package/src/packlets/config/predefined/extended.ts +0 -198
  100. package/src/packlets/config/predefined/index.ts +0 -26
  101. package/src/packlets/config/systemConfiguration.ts +0 -217
  102. package/src/packlets/context/contextDecls.ts +0 -76
  103. package/src/packlets/context/contextToken.ts +0 -252
  104. package/src/packlets/context/convert/decls.ts +0 -126
  105. package/src/packlets/context/convert/index.ts +0 -23
  106. package/src/packlets/context/index.ts +0 -27
  107. package/src/packlets/decisions/abstractDecision.ts +0 -87
  108. package/src/packlets/decisions/abstractDecisionCollector.ts +0 -122
  109. package/src/packlets/decisions/candidate.ts +0 -101
  110. package/src/packlets/decisions/common.ts +0 -37
  111. package/src/packlets/decisions/concreteDecision.ts +0 -157
  112. package/src/packlets/decisions/decision.ts +0 -172
  113. package/src/packlets/decisions/index.ts +0 -28
  114. package/src/packlets/import/fsItem.ts +0 -212
  115. package/src/packlets/import/importContext.ts +0 -183
  116. package/src/packlets/import/importManager.ts +0 -187
  117. package/src/packlets/import/importable.ts +0 -107
  118. package/src/packlets/import/importers/collectionImporter.ts +0 -153
  119. package/src/packlets/import/importers/fsItemImporter.ts +0 -154
  120. package/src/packlets/import/importers/importer.ts +0 -58
  121. package/src/packlets/import/importers/index.ts +0 -27
  122. package/src/packlets/import/importers/jsonImporter.ts +0 -133
  123. package/src/packlets/import/importers/pathImporter.ts +0 -134
  124. package/src/packlets/import/index.ts +0 -29
  125. package/src/packlets/qualifier-types/config/convert.ts +0 -108
  126. package/src/packlets/qualifier-types/config/index.ts +0 -27
  127. package/src/packlets/qualifier-types/config/json.ts +0 -126
  128. package/src/packlets/qualifier-types/convert.ts +0 -77
  129. package/src/packlets/qualifier-types/helpers.ts +0 -94
  130. package/src/packlets/qualifier-types/index.ts +0 -34
  131. package/src/packlets/qualifier-types/languageQualifierType.ts +0 -143
  132. package/src/packlets/qualifier-types/literalQualifierType.ts +0 -244
  133. package/src/packlets/qualifier-types/literalValueHierarchy.ts +0 -332
  134. package/src/packlets/qualifier-types/qualifierType.ts +0 -360
  135. package/src/packlets/qualifier-types/qualifierTypeCollector.ts +0 -102
  136. package/src/packlets/qualifier-types/territoryQualifierType.ts +0 -255
  137. package/src/packlets/qualifiers/convert/decls.ts +0 -90
  138. package/src/packlets/qualifiers/convert/index.ts +0 -24
  139. package/src/packlets/qualifiers/convert/qualifier.ts +0 -55
  140. package/src/packlets/qualifiers/index.ts +0 -31
  141. package/src/packlets/qualifiers/qualifier.ts +0 -169
  142. package/src/packlets/qualifiers/qualifierCollector.ts +0 -194
  143. package/src/packlets/qualifiers/qualifierDecl.ts +0 -80
  144. package/src/packlets/qualifiers/qualifierDefaultValueDecls.ts +0 -57
  145. package/src/packlets/qualifiers/qualifierDefaultValueToken.ts +0 -230
  146. package/src/packlets/resource-json/compiled/common.ts +0 -35
  147. package/src/packlets/resource-json/compiled/convert.ts +0 -143
  148. package/src/packlets/resource-json/compiled/index.ts +0 -27
  149. package/src/packlets/resource-json/compiled/json.ts +0 -239
  150. package/src/packlets/resource-json/convert.ts +0 -236
  151. package/src/packlets/resource-json/helpers.ts +0 -284
  152. package/src/packlets/resource-json/index.ts +0 -33
  153. package/src/packlets/resource-json/json.ts +0 -295
  154. package/src/packlets/resource-json/normalized.ts +0 -211
  155. package/src/packlets/resource-json/resourceDeclCollection.ts +0 -117
  156. package/src/packlets/resource-json/resourceDeclContainer.ts +0 -48
  157. package/src/packlets/resource-json/resourceDeclTree.ts +0 -116
  158. package/src/packlets/resource-types/config/convert.ts +0 -36
  159. package/src/packlets/resource-types/config/index.ts +0 -27
  160. package/src/packlets/resource-types/config/json.ts +0 -30
  161. package/src/packlets/resource-types/helpers.ts +0 -44
  162. package/src/packlets/resource-types/index.ts +0 -30
  163. package/src/packlets/resource-types/jsonResourceType.ts +0 -104
  164. package/src/packlets/resource-types/resourceType.ts +0 -259
  165. package/src/packlets/resource-types/resourceTypeCollector.ts +0 -79
  166. package/src/packlets/resources/candidateReducer.ts +0 -331
  167. package/src/packlets/resources/common.ts +0 -114
  168. package/src/packlets/resources/index.ts +0 -28
  169. package/src/packlets/resources/resource.ts +0 -307
  170. package/src/packlets/resources/resourceBuilder.ts +0 -269
  171. package/src/packlets/resources/resourceCandidate.ts +0 -333
  172. package/src/packlets/resources/resourceManagerBuilder.ts +0 -1169
  173. package/src/packlets/runtime/cacheListener.ts +0 -113
  174. package/src/packlets/runtime/cacheMetrics.ts +0 -206
  175. package/src/packlets/runtime/compiledResourceCollection.ts +0 -607
  176. package/src/packlets/runtime/conditionSetResolutionResult.ts +0 -160
  177. package/src/packlets/runtime/context/contextQualifierProvider.ts +0 -117
  178. package/src/packlets/runtime/context/contextQualifierProviderValidator.ts +0 -281
  179. package/src/packlets/runtime/context/index.ts +0 -26
  180. package/src/packlets/runtime/context/simpleContextQualifierProvider.ts +0 -225
  181. package/src/packlets/runtime/context/validatingSimpleContextQualifierProvider.ts +0 -96
  182. package/src/packlets/runtime/iResourceManager.ts +0 -130
  183. package/src/packlets/runtime/index.ts +0 -35
  184. package/src/packlets/runtime/resource-tree/common.ts +0 -126
  185. package/src/packlets/runtime/resource-tree/index.ts +0 -26
  186. package/src/packlets/runtime/resource-tree/readOnlyResourceTree.ts +0 -342
  187. package/src/packlets/runtime/resource-tree/resourceTreeChildren.ts +0 -125
  188. package/src/packlets/runtime/resource-tree/resourceTreeChildrenValidator.ts +0 -187
  189. package/src/packlets/runtime/resourceResolver.ts +0 -626
  190. package/src/packlets/runtime/validate.ts +0 -63
  191. package/src/packlets/zip-archive/convert.ts +0 -121
  192. package/src/packlets/zip-archive/index.ts +0 -76
  193. package/src/packlets/zip-archive/json.ts +0 -91
  194. package/src/packlets/zip-archive/types.ts +0 -140
  195. package/src/packlets/zip-archive/zipArchiveCreator.ts +0 -229
  196. package/src/packlets/zip-archive/zipArchiveFormat.ts +0 -158
  197. package/src/packlets/zip-archive/zipArchiveLoader.ts +0 -370
@@ -1,626 +0,0 @@
1
- /*
2
- * Copyright (c) 2025 Erik Fortune
3
- *
4
- * Permission is hereby granted, free of charge, to any person obtaining a copy
5
- * of this software and associated documentation files (the "Software"), to deal
6
- * in the Software without restriction, including without limitation the rights
7
- * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
8
- * copies of the Software, and to permit persons to whom the Software is
9
- * furnished to do so, subject to the following conditions:
10
- *
11
- * The above copyright notice and this permission notice shall be included in all
12
- * copies or substantial portions of the Software.
13
- *
14
- * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
15
- * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
16
- * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
17
- * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
18
- * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
19
- * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
20
- * SOFTWARE.
21
- */
22
-
23
- import { Result, captureResult, fail, succeed } from '@fgv/ts-utils';
24
- import { JsonValue, JsonObject, isJsonObject } from '@fgv/ts-json-base';
25
- import { JsonEditor } from '@fgv/ts-json';
26
- import { NoMatch } from '../common';
27
- import { Condition, ConditionSet } from '../conditions';
28
- import { AbstractDecision } from '../decisions';
29
- import { ReadOnlyQualifierTypeCollector } from '../qualifier-types';
30
- import { IContextQualifierProvider } from './context';
31
- import { IResourceManager, IResource, IResourceCandidate } from './iResourceManager';
32
- import {
33
- ConditionMatchType,
34
- ConditionSetResolutionResult,
35
- IConditionMatchResult
36
- } from './conditionSetResolutionResult';
37
- import { IResourceResolverCacheListener } from './cacheListener';
38
-
39
- /**
40
- * Represents the cached result of resolving a decision.
41
- * Contains either a failure indicator or a list of instance indices for matching condition sets,
42
- * ordered by condition set priority.
43
- * @public
44
- */
45
- export type DecisionResolutionResult =
46
- | { success: false }
47
- | { success: true; instanceIndices: ReadonlyArray<number>; defaultInstanceIndices: ReadonlyArray<number> };
48
-
49
- /**
50
- * Options for configuring a {@link Runtime.ResourceResolver | ResourceResolver}.
51
- * @public
52
- */
53
- export interface IResourceResolverOptions {
54
- /**
55
- * Controls whether null values in resource composition should suppress properties
56
- * instead of setting them to null. When true, properties with null values from
57
- * higher-priority partial candidates will be omitted from the final composed resource.
58
- * @defaultValue false
59
- */
60
- suppressNullAsDelete?: boolean;
61
- }
62
-
63
- /**
64
- * Parameters for creating a {@link Runtime.ResourceResolver | ResourceResolver}.
65
- * @public
66
- */
67
- export interface IResourceResolverCreateParams {
68
- /**
69
- * The {@link Runtime.IResourceManager | resource manager} that defines the resources available
70
- * and provides access to qualifiers and conditions.
71
- */
72
- resourceManager: IResourceManager;
73
-
74
- /**
75
- * The {@link QualifierTypes.ReadOnlyQualifierTypeCollector | readonly qualifier type collector}
76
- * that provides qualifier implementations for condition evaluation.
77
- */
78
- qualifierTypes: ReadOnlyQualifierTypeCollector;
79
-
80
- /**
81
- * The {@link Runtime.Context.IContextQualifierProvider | context qualifier provider} that resolves
82
- * qualifier values for the current context.
83
- */
84
- contextQualifierProvider: IContextQualifierProvider;
85
-
86
- /**
87
- * An optional listener for {@link Runtime.ResourceResolver | ResourceResolver} cache activity.
88
- */
89
- listener?: IResourceResolverCacheListener;
90
-
91
- /**
92
- * Optional configuration options for the {@link Runtime.ResourceResolver | ResourceResolver}.
93
- */
94
- options?: IResourceResolverOptions;
95
- }
96
-
97
- /**
98
- * High-performance runtime resource resolver with O(1) condition caching.
99
- * Resolves resources for a given context by evaluating conditions against qualifier values
100
- * and caching results for optimal performance.
101
- * @public
102
- */
103
- export class ResourceResolver {
104
- /**
105
- * The resource manager that defines available resources and provides condition access.
106
- */
107
- public readonly resourceManager: IResourceManager;
108
-
109
- /**
110
- * The readonly qualifier type collector that provides qualifier implementations.
111
- */
112
- public readonly qualifierTypes: ReadOnlyQualifierTypeCollector;
113
-
114
- /**
115
- * The context qualifier provider that resolves qualifier values.
116
- */
117
- public readonly contextQualifierProvider: IContextQualifierProvider;
118
-
119
- /**
120
- * The configuration options for this resource resolver.
121
- */
122
- public readonly options: IResourceResolverOptions;
123
-
124
- /**
125
- * The cache array for resolved conditions, indexed by condition index for O(1) lookup.
126
- * Each entry stores the resolved {@link Runtime.IConditionMatchResult | condition match result} for
127
- * the corresponding condition.
128
- */
129
- public get conditionCache(): ReadonlyArray<IConditionMatchResult | undefined> {
130
- return this._conditionCache;
131
- }
132
-
133
- /**
134
- * The cache array for resolved condition sets, indexed by condition set index for O(1) lookup.
135
- * Each entry stores the resolved ConditionSetResolutionResult for the corresponding condition set.
136
- */
137
- public get conditionSetCache(): ReadonlyArray<ConditionSetResolutionResult | undefined> {
138
- return this._conditionSetCache;
139
- }
140
-
141
- /**
142
- * The cache array for resolved decisions, indexed by decision index for O(1) lookup.
143
- * Each entry stores the resolved DecisionResolutionResult for the corresponding decision.
144
- */
145
- public get decisionCache(): ReadonlyArray<DecisionResolutionResult | undefined> {
146
- return this._decisionCache;
147
- }
148
-
149
- /**
150
- * Cache array for resolved conditions, indexed by condition index for O(1) lookup.
151
- * Each entry stores the resolved QualifierMatchScore for the corresponding condition.
152
- */
153
- private readonly _conditionCache: Array<IConditionMatchResult | undefined>;
154
-
155
- /**
156
- * Cache array for resolved condition sets, indexed by condition set index for O(1) lookup.
157
- * Each entry stores the resolved ConditionSetResolutionResult for the corresponding condition set.
158
- */
159
- private readonly _conditionSetCache: Array<ConditionSetResolutionResult | undefined>;
160
-
161
- /**
162
- * Cache array for resolved decisions, indexed by decision index for O(1) lookup.
163
- * Each entry stores the resolved DecisionResolutionResult for the corresponding decision.
164
- */
165
- private readonly _decisionCache: Array<DecisionResolutionResult | undefined>;
166
-
167
- /**
168
- * The listener for {@link Runtime.ResourceResolver | ResourceResolver} cache activity.
169
- */
170
- private readonly _listener?: IResourceResolverCacheListener;
171
-
172
- /**
173
- * Constructor for a {@link Runtime.ResourceResolver | ResourceResolver} object.
174
- * @param params - {@link Runtime.IResourceResolverCreateParams | Parameters} used to create the resolver.
175
- */
176
- protected constructor(params: IResourceResolverCreateParams) {
177
- this.resourceManager = params.resourceManager;
178
- this.qualifierTypes = params.qualifierTypes;
179
- this.contextQualifierProvider = params.contextQualifierProvider;
180
- this.options = {
181
- suppressNullAsDelete: params.options?.suppressNullAsDelete ?? false
182
- };
183
-
184
- // Initialize condition cache array with size matching the condition collector
185
- const conditionCollectorSize = this.resourceManager.conditions.size;
186
- this._conditionCache = new Array<IConditionMatchResult | undefined>(conditionCollectorSize);
187
-
188
- // Initialize condition set cache array with size matching the condition set collector
189
- const conditionSetCollectorSize = this.resourceManager.conditionSets.size;
190
- this._conditionSetCache = new Array<ConditionSetResolutionResult | undefined>(conditionSetCollectorSize);
191
-
192
- // Initialize decision cache array with size matching the decision collector
193
- const decisionCollectorSize = this.resourceManager.decisions.size;
194
- this._decisionCache = new Array<DecisionResolutionResult | undefined>(decisionCollectorSize);
195
-
196
- this._listener = params.listener;
197
- }
198
-
199
- /**
200
- * Creates a new {@link Runtime.ResourceResolver | ResourceResolver} object.
201
- * @param params - {@link Runtime.IResourceResolverCreateParams | Parameters} used to create the resolver.
202
- * @returns `Success` with the new {@link Runtime.ResourceResolver | ResourceResolver} object if successful,
203
- * or `Failure` with an error message if not.
204
- * @public
205
- */
206
- public static create(params: IResourceResolverCreateParams): Result<ResourceResolver> {
207
- return captureResult(() => new ResourceResolver(params));
208
- }
209
-
210
- /**
211
- * Resolves a condition by evaluating it against the current context.
212
- * Uses O(1) caching based on the condition's globally unique sequential index.
213
- * @param condition - The {@link Conditions.Condition | condition} to resolve.
214
- * @returns `Success` with the {@link QualifierMatchScore | match score} if successful,
215
- * or `Failure` with an error message if the condition cannot be resolved.
216
- * @public
217
- */
218
- public resolveCondition(condition: Condition): Result<IConditionMatchResult> {
219
- // Get the condition's index for cache lookup
220
- const conditionIndex = condition.index;
221
- if (conditionIndex === undefined) {
222
- return fail(`Condition "${condition.key}" does not have a valid index`);
223
- }
224
-
225
- // Check cache first for O(1) lookup
226
- const cachedResult = this._conditionCache[conditionIndex];
227
- if (cachedResult !== undefined) {
228
- this._listener?.onCacheHit('condition', conditionIndex);
229
- return succeed(cachedResult);
230
- }
231
-
232
- // Resolve the condition by getting qualifier value and evaluating with qualifier type
233
- const score = this.contextQualifierProvider
234
- .get(condition.qualifier)
235
- .onSuccess((qualifierValue) => {
236
- // Evaluate the condition using the qualifier type's matching logic
237
- return succeed(condition.qualifier.type.matches(condition.value, qualifierValue, condition.operator));
238
- })
239
- .onFailure((err) => {
240
- this._listener?.onContextError(condition.qualifier.name, err);
241
- return fail(err);
242
- })
243
- .orDefault(NoMatch);
244
-
245
- const priority = condition.priority;
246
- const scoreAsDefault = condition.scoreAsDefault ?? NoMatch;
247
- const matchResult: IConditionMatchResult =
248
- score > NoMatch
249
- ? { score, priority, matchType: 'match' }
250
- : scoreAsDefault > NoMatch
251
- ? { score: scoreAsDefault, priority, matchType: 'matchAsDefault' }
252
- : { score: NoMatch, priority, matchType: 'noMatch' };
253
-
254
- // Cache the resolved value for future O(1) lookup
255
- this._conditionCache[conditionIndex] = matchResult;
256
- this._listener?.onCacheMiss('condition', conditionIndex);
257
-
258
- return succeed(matchResult);
259
- }
260
-
261
- /**
262
- * Resolves a condition set by evaluating all its constituent conditions against the current context.
263
- * Uses O(1) caching based on the condition set's globally unique sequential index.
264
- * @param conditionSet - The {@link Conditions.ConditionSet | condition set} to resolve.
265
- * @returns `Success` with the {@link Runtime.ConditionSetResolutionResult | resolution result} if successful,
266
- * or `Failure` with an error message if the condition set cannot be resolved.
267
- * @public
268
- */
269
- public resolveConditionSet(conditionSet: ConditionSet): Result<ConditionSetResolutionResult> {
270
- // Get the condition set's index for cache lookup
271
- const conditionSetIndex = conditionSet.index;
272
- if (conditionSetIndex === undefined) {
273
- return fail(`ConditionSet "${conditionSet.key}" does not have a valid index`);
274
- }
275
-
276
- // Check cache first for O(1) lookup
277
- const cachedResult = this._conditionSetCache[conditionSetIndex];
278
- if (cachedResult !== undefined) {
279
- this._listener?.onCacheHit('conditionSet', conditionSetIndex);
280
- return succeed(cachedResult);
281
- }
282
-
283
- // Resolve all conditions in the condition set
284
- const conditions: Array<IConditionMatchResult> = [];
285
- let matchType: ConditionMatchType = 'match';
286
-
287
- for (const condition of conditionSet.conditions) {
288
- const { value: conditionResult, message: conditionMessage } = this.resolveCondition(condition);
289
-
290
- /* c8 ignore next 4 - defensive coding: extreme internal error scenario not reachable in normal operation */
291
- if (conditionMessage !== undefined) {
292
- this._listener?.onCacheError('conditionSet', conditionSetIndex);
293
- return fail(`Failed to resolve condition "${condition.key}": ${conditionMessage}`);
294
- }
295
-
296
- conditions.push(conditionResult);
297
-
298
- if (conditionResult.matchType === 'noMatch') {
299
- // Cache the failure result
300
- return ConditionSetResolutionResult.create('noMatch', conditions)
301
- .onSuccess((result) => {
302
- this._conditionSetCache[conditionSetIndex] = result;
303
- this._listener?.onCacheMiss('conditionSet', conditionSetIndex);
304
- return succeed(result);
305
- })
306
- .onFailure((err) => {
307
- /* c8 ignore next 4 - defensive coding: extreme internal error scenario not reachable in normal operation */
308
- this._conditionSetCache[conditionSetIndex] = undefined;
309
- this._listener?.onCacheError('conditionSet', conditionSetIndex);
310
- return fail(`${conditionSetIndex}: error creating condition set resolution result: ${err}`);
311
- });
312
- }
313
-
314
- if (conditionResult.matchType === 'matchAsDefault') {
315
- matchType = 'matchAsDefault';
316
- }
317
- }
318
-
319
- // Cache the successful result
320
- return ConditionSetResolutionResult.create(matchType, conditions)
321
- .onSuccess((result) => {
322
- this._conditionSetCache[conditionSetIndex] = result;
323
- this._listener?.onCacheMiss('conditionSet', conditionSetIndex);
324
- return succeed(result);
325
- })
326
- .onFailure((err) => {
327
- /* c8 ignore next 4 - defensive coding: extreme internal error scenario not reachable in normal operation */
328
- this._conditionSetCache[conditionSetIndex] = undefined;
329
- this._listener?.onCacheError('conditionSet', conditionSetIndex);
330
- return fail(`${conditionSetIndex}: error creating condition set resolution result: ${err}`);
331
- });
332
- }
333
-
334
- /**
335
- * Resolves a decision by evaluating all its constituent condition sets against the current context.
336
- * Uses O(1) caching based on the decision's globally unique sequential index.
337
- * @param decision - The {@link Decisions.AbstractDecision | abstract decision} to resolve.
338
- * @returns `Success` with the {@link Runtime.DecisionResolutionResult | resolution result} if successful,
339
- * or `Failure` with an error message if the decision cannot be resolved.
340
- * @public
341
- */
342
- public resolveDecision(decision: AbstractDecision): Result<DecisionResolutionResult> {
343
- // Get the decision's index for cache lookup
344
- const decisionIndex = decision.index;
345
- if (decisionIndex === undefined) {
346
- return fail(`Decision "${decision.key}" does not have a valid index`);
347
- }
348
-
349
- // Check cache first for O(1) lookup
350
- const cachedResult = this._decisionCache[decisionIndex];
351
- if (cachedResult !== undefined) {
352
- this._listener?.onCacheHit('decision', decisionIndex);
353
- return succeed(cachedResult);
354
- }
355
-
356
- // Resolve all condition sets in the decision
357
- const matchingInstanceResults: Array<{ index: number; result: ConditionSetResolutionResult }> = [];
358
- const matchingDefaultInstanceResults: Array<{ index: number; result: ConditionSetResolutionResult }> = [];
359
-
360
- for (let instanceIndex = 0; instanceIndex < decision.candidates.length; instanceIndex++) {
361
- const candidate = decision.candidates[instanceIndex];
362
- const conditionSetResult = this.resolveConditionSet(candidate.conditionSet);
363
-
364
- /* c8 ignore next 4 - defensive coding: extreme internal error scenario not reachable in normal operation */
365
- if (conditionSetResult.isFailure()) {
366
- this._listener?.onCacheError('decision', decisionIndex);
367
- return fail(`${decision.key}: Failed to resolve condition set": ${conditionSetResult.message}`);
368
- }
369
-
370
- const resolution = conditionSetResult.value;
371
-
372
- // Only include condition sets that match
373
- if (resolution.matchType === 'match') {
374
- matchingInstanceResults.push({
375
- index: instanceIndex,
376
- result: resolution
377
- });
378
- } else if (resolution.matchType === 'matchAsDefault') {
379
- matchingDefaultInstanceResults.push({
380
- index: instanceIndex,
381
- result: resolution
382
- });
383
- }
384
- // If condition set doesn't match, we simply skip it and continue (don't fail the decision)
385
- }
386
-
387
- // Sort by condition set resolution priority using the proper comparison logic
388
- matchingInstanceResults.sort((a, b) => ConditionSetResolutionResult.compare(a.result, b.result));
389
- matchingDefaultInstanceResults.sort((a, b) => ConditionSetResolutionResult.compare(a.result, b.result));
390
-
391
- // Extract just the instance indices in priority order
392
- const instanceIndices = matchingInstanceResults.map((item) => item.index);
393
- const defaultInstanceIndices = matchingDefaultInstanceResults.map((item) => item.index);
394
-
395
- // Cache the successful result
396
- const successResult: DecisionResolutionResult = {
397
- success: true,
398
- instanceIndices,
399
- defaultInstanceIndices
400
- };
401
- this._decisionCache[decisionIndex] = successResult;
402
- this._listener?.onCacheMiss('decision', decisionIndex);
403
-
404
- return succeed(successResult);
405
- }
406
-
407
- /**
408
- * Resolves a resource by finding the best matching candidate.
409
- * Uses the resource's associated decision to determine the best match based on the current context.
410
- * @param resource - The {@link Resources.Resource | resource} to resolve.
411
- * @returns `Success` with the best matching candidate if successful,
412
- * or `Failure` with an error message if no candidates match or resolution fails.
413
- * @public
414
- */
415
- public resolveResource(resource: IResource): Result<IResourceCandidate> {
416
- // Get the abstract decision from the resource's concrete decision
417
- const abstractDecision = resource.decision.baseDecision;
418
-
419
- // Resolve the decision to get candidate indices in priority order
420
- const decisionResult = this.resolveDecision(abstractDecision);
421
- /* c8 ignore next 3 - defense in depth almost impossible to hit */
422
- if (decisionResult.isFailure()) {
423
- return fail(`Failed to resolve decision for resource "${resource.id}": ${decisionResult.message}`);
424
- }
425
-
426
- const resolution = decisionResult.value;
427
-
428
- // Check if any candidates matched (regular or default)
429
- if (
430
- !resolution.success ||
431
- (resolution.instanceIndices.length === 0 && resolution.defaultInstanceIndices.length === 0)
432
- ) {
433
- return fail(`No matching candidates found for resource "${resource.id}"`);
434
- }
435
-
436
- // Prefer regular matches over default matches
437
- const candidateIndex =
438
- resolution.instanceIndices.length > 0
439
- ? resolution.instanceIndices[0] // Best regular match
440
- : resolution.defaultInstanceIndices[0]; // Best default match
441
-
442
- if (candidateIndex >= resource.candidates.length) {
443
- return fail(`Invalid candidate index ${candidateIndex} for resource "${resource.id}"`);
444
- }
445
-
446
- const bestCandidate = resource.candidates[candidateIndex];
447
- return succeed(bestCandidate);
448
- }
449
-
450
- /**
451
- * Resolves all matching resource candidates in priority order.
452
- * Uses the resource's associated decision to determine all matching candidates based on the current context.
453
- * @param resource - The {@link Resources.Resource | resource} to resolve.
454
- * @returns `Success` with an array of all matching candidates in priority order if successful,
455
- * or `Failure` with an error message if no candidates match or resolution fails.
456
- * @public
457
- */
458
- public resolveAllResourceCandidates(resource: IResource): Result<ReadonlyArray<IResourceCandidate>> {
459
- // Get the abstract decision from the resource's concrete decision
460
- const abstractDecision = resource.decision.baseDecision;
461
-
462
- // Resolve the decision to get candidate indices in priority order
463
- const decisionResult = this.resolveDecision(abstractDecision);
464
- /* c8 ignore next 3 - defense in depth almost impossible to hit */
465
- if (decisionResult.isFailure()) {
466
- return fail(`Failed to resolve decision for resource "${resource.id}": ${decisionResult.message}`);
467
- }
468
-
469
- const resolution = decisionResult.value;
470
-
471
- // Check if any candidates matched (regular or default)
472
- if (
473
- !resolution.success ||
474
- (resolution.instanceIndices.length === 0 && resolution.defaultInstanceIndices.length === 0)
475
- ) {
476
- return fail(`No matching candidates found for resource "${resource.id}"`);
477
- }
478
-
479
- // Get all matching candidates: regular matches first, then default matches
480
- const candidates: IResourceCandidate[] = [];
481
-
482
- // Add all regular matches first (already sorted by priority)
483
- for (const candidateIndex of resolution.instanceIndices) {
484
- if (candidateIndex >= resource.candidates.length) {
485
- return fail(`Invalid candidate index ${candidateIndex} for resource "${resource.id}"`);
486
- }
487
- const candidate = resource.candidates[candidateIndex];
488
- candidates.push(candidate);
489
- }
490
-
491
- // Add all default matches after regular matches (already sorted by priority)
492
- for (const candidateIndex of resolution.defaultInstanceIndices) {
493
- /* c8 ignore next 3 - defensive coding: extreme internal error scenario not reachable in normal operation */
494
- if (candidateIndex >= resource.candidates.length) {
495
- return fail(`Invalid candidate index ${candidateIndex} for resource "${resource.id}"`);
496
- }
497
- const candidate = resource.candidates[candidateIndex];
498
- candidates.push(candidate);
499
- }
500
-
501
- return succeed(candidates);
502
- }
503
-
504
- /**
505
- * Resolves a resource to a composed value by merging matching candidates according to their merge methods.
506
- * Starting from the highest priority candidates, finds the first "full" candidate and merges all higher
507
- * priority "partial" candidates into it in ascending order of priority.
508
- * @param resource - The {@link Resources.Resource | resource} to resolve.
509
- * @returns `Success` with the composed JsonValue if successful,
510
- * or `Failure` with an error message if no candidates match or resolution fails.
511
- * @public
512
- */
513
- public resolveComposedResourceValue(resource: IResource): Result<JsonValue> {
514
- return this.resolveAllResourceCandidates(resource).onSuccess((candidates) => {
515
- /* c8 ignore next 3 - defense in depth should never occur */
516
- if (candidates.length === 0) {
517
- return fail(`${resource.id}: No matching candidates found.`);
518
- }
519
-
520
- // Find the first full candidate and collect all partial candidates above it
521
- let fullCandidateIndex = -1;
522
- const partialCandidates: IResourceCandidate[] = [];
523
-
524
- for (let i = 0; i < candidates.length; i++) {
525
- const candidate = candidates[i];
526
- if (!candidate.isPartial) {
527
- // Found the first full candidate
528
- fullCandidateIndex = i;
529
- break;
530
- } else {
531
- // Collect partial candidates (these are in ascending priority order)
532
- partialCandidates.unshift(candidate);
533
- }
534
- }
535
-
536
- // If no full candidate found, use the last candidate as the base
537
- const baseCandidateIndex = fullCandidateIndex >= 0 ? fullCandidateIndex : candidates.length - 1;
538
- const baseCandidate = candidates[baseCandidateIndex];
539
-
540
- // If there are no partial candidates to merge, but null-as-delete is enabled,
541
- // still process through JsonEditor to handle null properties in the base candidate
542
- if (partialCandidates.length === 0) {
543
- if (this.options.suppressNullAsDelete || !isJsonObject(baseCandidate.json)) {
544
- return succeed(baseCandidate.json);
545
- }
546
-
547
- // Process single candidate through JsonEditor to apply null-as-delete
548
- const editor = JsonEditor.create({
549
- merge: {
550
- arrayMergeBehavior: 'replace',
551
- nullAsDelete: true
552
- }
553
- }).orThrow(); // Should never fail with valid options
554
-
555
- return editor
556
- .mergeObjectsInPlace({}, [baseCandidate.json])
557
- .withErrorFormat((err) => `${resource.id}: Composition failed: ${err}`);
558
- }
559
-
560
- const allCandidates = [
561
- baseCandidate.json,
562
- ...partialCandidates.map((candidate) => candidate.json)
563
- ].filter((v): v is JsonObject => isJsonObject(v));
564
-
565
- /* c8 ignore next 3 - defensive check: non-object values in resource candidates should be prevented at validation time */
566
- if (allCandidates.length !== partialCandidates.length + 1) {
567
- return fail(`${resource.id}: Unable to compose non-object candidate values.`);
568
- }
569
-
570
- // Create JsonEditor with array replacement behavior and null-as-delete for resource composition
571
- const editor = JsonEditor.create({
572
- merge: {
573
- arrayMergeBehavior: 'replace',
574
- nullAsDelete: !this.options.suppressNullAsDelete
575
- }
576
- }).orThrow(); // Should never fail with valid options
577
-
578
- return editor
579
- .mergeObjectsInPlace({}, allCandidates)
580
- .withErrorFormat((err) => `${resource.id}: Composition failed: ${err}`);
581
- });
582
- }
583
-
584
- /**
585
- * Clears all caches (condition, condition set, and decision), forcing all cached items
586
- * to be re-evaluated on next access. This should be called when the context changes and cached
587
- * results are no longer valid.
588
- * @public
589
- */
590
- public clearConditionCache(): void {
591
- this._conditionCache.fill(undefined);
592
- this._conditionSetCache.fill(undefined);
593
- this._decisionCache.fill(undefined);
594
-
595
- this._listener?.onCacheClear('condition');
596
- this._listener?.onCacheClear('conditionSet');
597
- this._listener?.onCacheClear('decision');
598
- }
599
-
600
- /**
601
- * Gets the current size of the condition cache array.
602
- * @returns The size of the condition cache array.
603
- * @public
604
- */
605
- public get conditionCacheSize(): number {
606
- return this._conditionCache.length;
607
- }
608
-
609
- /**
610
- * Gets the current size of the condition set cache array.
611
- * @returns The size of the condition set cache array.
612
- * @public
613
- */
614
- public get conditionSetCacheSize(): number {
615
- return this._conditionSetCache.length;
616
- }
617
-
618
- /**
619
- * Gets the current size of the decision cache array.
620
- * @returns The size of the decision cache array.
621
- * @public
622
- */
623
- public get decisionCacheSize(): number {
624
- return this._decisionCache.length;
625
- }
626
- }
@@ -1,63 +0,0 @@
1
- /*
2
- * Copyright (c) 2025 Erik Fortune
3
- *
4
- * Permission is hereby granted, free of charge, to any person obtaining a copy
5
- * of this software and associated documentation files (the "Software"), to deal
6
- * in the Software without restriction, including without limitation the rights
7
- * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
8
- * copies of the Software, and to permit persons to whom the Software is
9
- * furnished to do so, subject to the following conditions:
10
- *
11
- * The above copyright notice and this permission notice shall be included in all
12
- * copies or substantial portions of the Software.
13
- *
14
- * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
15
- * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
16
- * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
17
- * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
18
- * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
19
- * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
20
- * SOFTWARE.
21
- */
22
-
23
- import { Validators, Validator } from '@fgv/ts-utils';
24
- import { Validators as JsonValidators } from '@fgv/ts-json-base';
25
- import { Validate, ResourceId } from '../common';
26
- import { ResourceType } from '../resource-types';
27
- import { ConcreteDecision } from '../decisions';
28
- import { IResource, IResourceCandidate } from './iResourceManager';
29
-
30
- /**
31
- * Validates an {@link Runtime.IResourceCandidate | IResourceCandidate} object.
32
- * @public
33
- */
34
- export const resourceCandidate: Validator<IResourceCandidate, unknown> =
35
- Validators.object<IResourceCandidate>({
36
- json: JsonValidators.jsonObject,
37
- isPartial: Validators.boolean,
38
- mergeMethod: Validators.isA(
39
- 'resource value merge method',
40
- (v): v is 'augment' | 'delete' | 'replace' => v === 'augment' || v === 'delete' || v === 'replace'
41
- )
42
- });
43
-
44
- /**
45
- * Validates an {@link Runtime.IResource | IResource} object.
46
- * @public
47
- */
48
- export const resource: Validator<IResource, unknown> = Validators.object<IResource>({
49
- id: Validators.isA(
50
- 'ResourceId',
51
- (v): v is ResourceId => typeof v === 'string' && Validate.isValidResourceId(v)
52
- ),
53
- name: Validators.isA(
54
- 'ResourceName',
55
- (v): v is string => typeof v === 'string' && Validate.isValidResourceName(v)
56
- ),
57
- resourceType: Validators.isA('ResourceType instance', (v): v is ResourceType => v instanceof ResourceType),
58
- decision: Validators.isA(
59
- 'ConcreteDecision instance',
60
- (v): v is ConcreteDecision => v instanceof ConcreteDecision
61
- ),
62
- candidates: Validators.arrayOf(resourceCandidate)
63
- });