@fgv/ts-res 5.0.1-0 → 5.0.1-2

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 (39) hide show
  1. package/dist/ts-res.d.ts +212 -1
  2. package/lib/packlets/common/helpers/resources.d.ts +1 -1
  3. package/lib/packlets/common/helpers/resources.js +3 -2
  4. package/lib/packlets/common/resources.d.ts +4 -0
  5. package/lib/packlets/common/validate/conditions.js +14 -14
  6. package/lib/packlets/common/validate/resources.js +7 -7
  7. package/lib/packlets/conditions/conditionSet.js +1 -1
  8. package/lib/packlets/config/common.js +1 -0
  9. package/lib/packlets/config/configInitFactory.js +1 -0
  10. package/lib/packlets/config/systemConfiguration.js +1 -0
  11. package/lib/packlets/context/convert/decls.js +1 -1
  12. package/lib/packlets/import/importers/collectionImporter.js +1 -1
  13. package/lib/packlets/import/importers/jsonImporter.js +1 -1
  14. package/lib/packlets/qualifier-types/helpers.js +5 -4
  15. package/lib/packlets/qualifier-types/literalQualifierType.js +1 -1
  16. package/lib/packlets/qualifier-types/literalValueHierarchy.js +7 -6
  17. package/lib/packlets/qualifier-types/qualifierType.js +1 -0
  18. package/lib/packlets/qualifier-types/territoryQualifierType.js +1 -1
  19. package/lib/packlets/resource-json/helpers.js +4 -0
  20. package/lib/packlets/resource-types/helpers.js +1 -0
  21. package/lib/packlets/resource-types/resourceType.js +1 -0
  22. package/lib/packlets/resources/candidateValue.js +1 -0
  23. package/lib/packlets/resources/candidateValueCollector.js +4 -2
  24. package/lib/packlets/resources/deltaGenerator.d.ts +189 -0
  25. package/lib/packlets/resources/deltaGenerator.js +342 -0
  26. package/lib/packlets/resources/index.d.ts +1 -0
  27. package/lib/packlets/resources/index.js +1 -0
  28. package/lib/packlets/resources/resourceBuilder.js +4 -0
  29. package/lib/packlets/resources/resourceManagerBuilder.d.ts +4 -0
  30. package/lib/packlets/resources/resourceManagerBuilder.js +12 -0
  31. package/lib/packlets/runtime/compiledResourceCollection.d.ts +4 -0
  32. package/lib/packlets/runtime/compiledResourceCollection.js +7 -0
  33. package/lib/packlets/runtime/context/simpleContextQualifierProvider.js +4 -3
  34. package/lib/packlets/runtime/iResourceManager.d.ts +4 -0
  35. package/lib/packlets/runtime/resource-tree/resourceTreeChildren.js +3 -0
  36. package/lib/packlets/runtime/resourceResolver.d.ts +5 -1
  37. package/lib/packlets/runtime/resourceResolver.js +8 -4
  38. package/lib/packlets/runtime/resourceTreeResolver.js +2 -0
  39. package/package.json +7 -7
@@ -78,6 +78,7 @@ class QualifierType {
78
78
  if (this.isValidConditionValue(conditionValue) && this.isValidContextValue(contextValue)) {
79
79
  return this._matchOne(conditionValue, contextValue, 'matches') !== common_1.NoMatch;
80
80
  }
81
+ /* c8 ignore next 2 - functional code tested but coverage intermittently missed */
81
82
  return false;
82
83
  }
83
84
  /**
@@ -230,7 +230,7 @@ class TerritoryQualifierType extends qualifierType_1.QualifierType {
230
230
  const normalized = value.toUpperCase();
231
231
  return TerritoryQualifierType.isValidTerritoryConditionValue(normalized, acceptLowercase)
232
232
  ? (0, ts_utils_1.succeed)(normalized)
233
- : (0, ts_utils_1.fail)(`${value}: not a valid territory code`);
233
+ : (0, ts_utils_1.fail)(`${value}: invalid territory code`);
234
234
  }
235
235
  }
236
236
  exports.TerritoryQualifierType = TerritoryQualifierType;
@@ -112,6 +112,7 @@ function mergeLooseCandidate(candidate, baseName, baseConditions) {
112
112
  if (!Json.isLooseResourceCandidateDecl(candidate) && !baseName) {
113
113
  return (0, ts_utils_1.fail)('id is required in mergeLooseCandidate');
114
114
  }
115
+ /* c8 ignore next 7 - functional code tested but coverage intermittently missed */
115
116
  return common_1.Helpers.joinResourceIds(baseName, candidateId).onSuccess((id) => {
116
117
  var _a;
117
118
  /* c8 ignore next 1 - defense in depth */
@@ -157,6 +158,7 @@ function mergeImporterCandidate(candidate, baseName, baseConditions) {
157
158
  });
158
159
  }
159
160
  else {
161
+ /* c8 ignore next 5 - functional code tested but coverage intermittently missed */
160
162
  /* c8 ignore next 1 - defense in depth */
161
163
  const conditions = [...(baseConditions !== null && baseConditions !== void 0 ? baseConditions : []), ...((_a = candidate.conditions) !== null && _a !== void 0 ? _a : [])];
162
164
  return (0, ts_utils_1.succeed)(Object.assign(Object.assign({}, candidate), { conditions }));
@@ -189,6 +191,7 @@ function mergeLooseResource(resource, baseName, baseConditions) {
189
191
  if (!baseName && !Json.isLooseResourceDecl(resource)) {
190
192
  return (0, ts_utils_1.fail)('id is required in mergeLooseResource');
191
193
  }
194
+ /* c8 ignore next 10 - functional code tested but coverage intermittently missed */
192
195
  return common_1.Helpers.joinResourceIds(baseName, resourceId).onSuccess((id) => {
193
196
  var _a;
194
197
  return (0, ts_utils_1.mapResults)(
@@ -249,6 +252,7 @@ function mergeImporterResource(resource, baseName, baseConditions) {
249
252
  });
250
253
  }
251
254
  else {
255
+ /* c8 ignore next 8 - functional code tested but coverage intermittently missed */
252
256
  return (0, ts_utils_1.mapResults)(
253
257
  /* c8 ignore next 1 - defense in depth */
254
258
  ((_a = resource.candidates) !== null && _a !== void 0 ? _a : []).map((candidate) => mergeChildCandidate(candidate, baseConditions))).onSuccess((candidates) => {
@@ -39,6 +39,7 @@ function createResourceTypeFromConfig(config) {
39
39
  .convert(config.name)
40
40
  .onSuccess((key) => jsonResourceType_1.JsonResourceType.create({ key }));
41
41
  }
42
+ /* c8 ignore next 2 - functional code tested but coverage intermittently missed */
42
43
  return (0, ts_utils_1.fail)(`${config.typeName}: Unknown resource type.`);
43
44
  }
44
45
  //# sourceMappingURL=helpers.js.map
@@ -51,6 +51,7 @@ class ResourceType {
51
51
  index: index !== undefined ? common_1.Validate.toResourceTypeIndex(index).orThrow() : undefined,
52
52
  indexConverter: common_1.Convert.resourceTypeIndex
53
53
  });
54
+ /* c8 ignore next 1 - defense in depth */
54
55
  this._template = template !== null && template !== void 0 ? template : {};
55
56
  }
56
57
  /**
@@ -90,6 +90,7 @@ class CandidateValue {
90
90
  */
91
91
  constructor(params) {
92
92
  var _a;
93
+ /* c8 ignore next 1 - defense in depth */
93
94
  const normalizer = (_a = params.normalizer) !== null && _a !== void 0 ? _a : new ts_utils_1.Hash.Crc32Normalizer();
94
95
  // Normalize the JSON value
95
96
  const normalizedResult = normalizer.normalize(params.json);
@@ -38,7 +38,7 @@ class CandidateValueCollector extends ts_utils_1.ValidatingCollector {
38
38
  * @param params - Parameters to create the collector.
39
39
  * @internal
40
40
  */
41
- constructor(params = {}) {
41
+ constructor(params) {
42
42
  var _a, _b;
43
43
  super({
44
44
  converters: new ts_utils_1.Collections.KeyValueConverters({
@@ -46,7 +46,9 @@ class CandidateValueCollector extends ts_utils_1.ValidatingCollector {
46
46
  value: (from) => this._toCandidateValue(from)
47
47
  })
48
48
  });
49
- this.normalizer = (_a = params === null || params === void 0 ? void 0 : params.normalizer) !== null && _a !== void 0 ? _a : new ts_utils_1.Hash.Crc32Normalizer();
49
+ /* c8 ignore next 3 - defense in depth */
50
+ params = params !== null && params !== void 0 ? params : {};
51
+ this.normalizer = (_a = params.normalizer) !== null && _a !== void 0 ? _a : new ts_utils_1.Hash.Crc32Normalizer();
50
52
  (_b = params.candidateValues) === null || _b === void 0 ? void 0 : _b.forEach((candidateValue) => this.validating.add(candidateValue));
51
53
  }
52
54
  /**
@@ -0,0 +1,189 @@
1
+ import { Logging, Result } from '@fgv/ts-utils';
2
+ import { IResourceResolver } from '../common';
3
+ import { ResourceManagerBuilder } from './resourceManagerBuilder';
4
+ import * as Context from '../context';
5
+ /**
6
+ * Interface for parameters to create a {@link Resources.DeltaGenerator | DeltaGenerator}.
7
+ * @public
8
+ */
9
+ export interface IDeltaGeneratorParams {
10
+ /**
11
+ * The baseline resource resolver to compare against.
12
+ */
13
+ baselineResolver: IResourceResolver;
14
+ /**
15
+ * The delta resource resolver containing changes.
16
+ */
17
+ deltaResolver: IResourceResolver;
18
+ /**
19
+ * The resource manager to clone and update.
20
+ */
21
+ resourceManager: ResourceManagerBuilder;
22
+ /**
23
+ * Optional logger for status and error reporting.
24
+ */
25
+ logger?: Logging.ILogger;
26
+ }
27
+ /**
28
+ * Interface for options controlling delta generation behavior.
29
+ * @public
30
+ */
31
+ export interface IDeltaGeneratorOptions {
32
+ /**
33
+ * Context to use when resolving resources. If not provided, uses empty context.
34
+ */
35
+ context?: Context.IContextDecl;
36
+ /**
37
+ * Array of specific resource IDs to include in delta generation.
38
+ * If not provided, generates deltas for all resources in the delta resolver.
39
+ */
40
+ resourceIds?: ReadonlyArray<string>;
41
+ /**
42
+ * Whether to skip resources that haven't changed. Default: true.
43
+ */
44
+ skipUnchanged?: boolean;
45
+ }
46
+ /**
47
+ * Class for generating resource deltas between baseline and delta resolvers.
48
+ * Creates partial/augment candidates for updated resources and full/replace candidates for new resources.
49
+ * Uses Diff.jsonThreeWayDiff for efficient delta computation.
50
+ * @public
51
+ */
52
+ export declare class DeltaGenerator {
53
+ /**
54
+ * The baseline resource resolver to compare against.
55
+ * @internal
56
+ */
57
+ private readonly _baselineResolver;
58
+ /**
59
+ * The delta resource resolver containing changes.
60
+ * @internal
61
+ */
62
+ private readonly _deltaResolver;
63
+ /**
64
+ * The resource manager to clone and update.
65
+ * @internal
66
+ */
67
+ private readonly _resourceManager;
68
+ /**
69
+ * Logger for status and error reporting.
70
+ * @internal
71
+ */
72
+ private readonly _logger;
73
+ /**
74
+ * Constructor for a {@link Resources.DeltaGenerator | DeltaGenerator} object.
75
+ * @param params - Parameters to create a new {@link Resources.DeltaGenerator | DeltaGenerator}.
76
+ * @internal
77
+ */
78
+ protected constructor(params: IDeltaGeneratorParams);
79
+ /**
80
+ * Creates a new {@link Resources.DeltaGenerator | DeltaGenerator} object.
81
+ * @param params - Parameters to create a new {@link Resources.DeltaGenerator | DeltaGenerator}.
82
+ * @returns `Success` with the new {@link Resources.DeltaGenerator | DeltaGenerator} object if successful,
83
+ * or `Failure` with an error message if not.
84
+ * @public
85
+ */
86
+ static create(params: IDeltaGeneratorParams): Result<DeltaGenerator>;
87
+ /**
88
+ * Generates deltas between baseline and delta resolvers.
89
+ * Creates a cloned resource manager with partial/augment candidates for updates
90
+ * and full/replace candidates for new resources.
91
+ *
92
+ * @param options - Options controlling delta generation behavior.
93
+ * @returns `Success` with the updated resource manager if successful,
94
+ * or `Failure` with an error message if not.
95
+ * @public
96
+ */
97
+ generate(options?: IDeltaGeneratorOptions): Result<ResourceManagerBuilder>;
98
+ /**
99
+ * Validates the provided context declaration.
100
+ * @param context - The context declaration to validate.
101
+ * @returns `Success` with the validated context if successful, `Failure` otherwise.
102
+ * @internal
103
+ */
104
+ private _validateContext;
105
+ /**
106
+ * Enumerates target resource IDs for delta generation.
107
+ * If specific resource IDs are provided, uses those. Otherwise, discovers all resources
108
+ * from both the baseline resource manager and the delta resolver to ensure comprehensive
109
+ * coverage of all potential resources.
110
+ *
111
+ * @param requestedIds - Optional array of specific resource IDs to target.
112
+ * @param context - The validated context to use for resource discovery.
113
+ * @returns `Success` with array of resource IDs if successful, `Failure` otherwise.
114
+ * @internal
115
+ */
116
+ private _enumerateTargetResources;
117
+ /**
118
+ * Discovers all unique resource IDs from both baseline and delta resolvers.
119
+ * Creates a union of resource IDs from the baseline resource manager and delta resolver
120
+ * to ensure comprehensive coverage of all resources.
121
+ *
122
+ * @returns `Success` with array of unique resource IDs if successful, `Failure` otherwise.
123
+ * @internal
124
+ */
125
+ private _discoverAllResourceIds;
126
+ /**
127
+ * Creates a clone of the resource manager for delta operations.
128
+ * @returns `Success` with the cloned resource manager if successful, `Failure` otherwise.
129
+ * @internal
130
+ */
131
+ private _cloneResourceManager;
132
+ /**
133
+ * Generates deltas for the specified resources and adds them to the cloned manager.
134
+ *
135
+ * @param clonedManager - The cloned resource manager to update.
136
+ * @param resourceIds - Array of resource IDs to process.
137
+ * @param context - The context to use for resource resolution.
138
+ * @param skipUnchanged - Whether to skip resources that haven't changed.
139
+ * @returns `Success` with the updated manager if successful, `Failure` otherwise.
140
+ * @internal
141
+ */
142
+ private _generateDeltas;
143
+ /**
144
+ * Generates a delta for a single resource and adds appropriate candidates to the manager.
145
+ *
146
+ * @param manager - The resource manager to update.
147
+ * @param resourceId - The resource ID to process.
148
+ * @param context - The context to use for resource resolution.
149
+ * @param skipUnchanged - Whether to skip resources that haven't changed.
150
+ * @returns `Success` with the resource delta result if successful, `Failure` otherwise.
151
+ * @internal
152
+ */
153
+ private _generateResourceDelta;
154
+ /**
155
+ * Checks if two JSON values are identical.
156
+ * @param value1 - First value to compare.
157
+ * @param value2 - Second value to compare.
158
+ * @returns True if values are identical, false otherwise.
159
+ * @internal
160
+ */
161
+ private _areValuesIdentical;
162
+ /**
163
+ * Creates a new resource candidate for a newly discovered resource.
164
+ * Uses full/replace merge method since this is a completely new resource.
165
+ *
166
+ * @param manager - The resource manager to update.
167
+ * @param resourceId - The resource ID for the new resource.
168
+ * @param value - The resolved value for the new resource.
169
+ * @param context - The context used for resolution.
170
+ * @returns `Success` if the candidate was added successfully, `Failure` otherwise.
171
+ * @internal
172
+ */
173
+ private _createNewResourceCandidate;
174
+ /**
175
+ * Creates a delta candidate for an updated resource.
176
+ * Computes the difference between baseline and delta values and creates
177
+ * a partial/augment candidate with only the changed properties.
178
+ *
179
+ * @param manager - The resource manager to update.
180
+ * @param resourceId - The resource ID for the updated resource.
181
+ * @param baselineValue - The baseline resolved value.
182
+ * @param deltaValue - The delta resolved value.
183
+ * @param context - The context used for resolution.
184
+ * @returns `Success` if the candidate was added successfully, `Failure` otherwise.
185
+ * @internal
186
+ */
187
+ private _createDeltaCandidate;
188
+ }
189
+ //# sourceMappingURL=deltaGenerator.d.ts.map
@@ -0,0 +1,342 @@
1
+ "use strict";
2
+ /*
3
+ * Copyright (c) 2025 Erik Fortune
4
+ *
5
+ * Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ * of this software and associated documentation files (the "Software"), to deal
7
+ * in the Software without restriction, including without limitation the rights
8
+ * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ * copies of the Software, and to permit persons to whom the Software is
10
+ * furnished to do so, subject to the following conditions:
11
+ *
12
+ * The above copyright notice and this permission notice shall be included in all
13
+ * copies or substantial portions of the Software.
14
+ *
15
+ * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ * SOFTWARE.
22
+ */
23
+ Object.defineProperty(exports, "__esModule", { value: true });
24
+ exports.DeltaGenerator = void 0;
25
+ const ts_utils_1 = require("@fgv/ts-utils");
26
+ const ts_json_base_1 = require("@fgv/ts-json-base");
27
+ const ts_json_1 = require("@fgv/ts-json");
28
+ /**
29
+ * Class for generating resource deltas between baseline and delta resolvers.
30
+ * Creates partial/augment candidates for updated resources and full/replace candidates for new resources.
31
+ * Uses Diff.jsonThreeWayDiff for efficient delta computation.
32
+ * @public
33
+ */
34
+ class DeltaGenerator {
35
+ /**
36
+ * Constructor for a {@link Resources.DeltaGenerator | DeltaGenerator} object.
37
+ * @param params - Parameters to create a new {@link Resources.DeltaGenerator | DeltaGenerator}.
38
+ * @internal
39
+ */
40
+ constructor(params) {
41
+ var _a;
42
+ this._baselineResolver = params.baselineResolver;
43
+ this._deltaResolver = params.deltaResolver;
44
+ this._resourceManager = params.resourceManager;
45
+ this._logger = (_a = params.logger) !== null && _a !== void 0 ? _a : new ts_utils_1.Logging.NoOpLogger();
46
+ }
47
+ /**
48
+ * Creates a new {@link Resources.DeltaGenerator | DeltaGenerator} object.
49
+ * @param params - Parameters to create a new {@link Resources.DeltaGenerator | DeltaGenerator}.
50
+ * @returns `Success` with the new {@link Resources.DeltaGenerator | DeltaGenerator} object if successful,
51
+ * or `Failure` with an error message if not.
52
+ * @public
53
+ */
54
+ static create(params) {
55
+ return (0, ts_utils_1.captureResult)(() => new DeltaGenerator(params));
56
+ }
57
+ /**
58
+ * Generates deltas between baseline and delta resolvers.
59
+ * Creates a cloned resource manager with partial/augment candidates for updates
60
+ * and full/replace candidates for new resources.
61
+ *
62
+ * @param options - Options controlling delta generation behavior.
63
+ * @returns `Success` with the updated resource manager if successful,
64
+ * or `Failure` with an error message if not.
65
+ * @public
66
+ */
67
+ generate(options) {
68
+ var _a, _b;
69
+ this._logger.info('Starting delta generation');
70
+ const context = (_a = options === null || options === void 0 ? void 0 : options.context) !== null && _a !== void 0 ? _a : {};
71
+ const skipUnchanged = (_b = options === null || options === void 0 ? void 0 : options.skipUnchanged) !== null && _b !== void 0 ? _b : true;
72
+ return this._validateContext(context)
73
+ .onSuccess((validatedContext) => this._enumerateTargetResources(options === null || options === void 0 ? void 0 : options.resourceIds, validatedContext))
74
+ .onSuccess((resourceIds) => {
75
+ return this._cloneResourceManager()
76
+ .onSuccess((clonedManager) => this._generateDeltas(clonedManager, resourceIds, context, skipUnchanged))
77
+ .onSuccess((manager) => {
78
+ this._logger.info(`Delta generation completed successfully with ${manager.size} resources`);
79
+ return (0, ts_utils_1.succeed)(manager);
80
+ });
81
+ });
82
+ }
83
+ /**
84
+ * Validates the provided context declaration.
85
+ * @param context - The context declaration to validate.
86
+ * @returns `Success` with the validated context if successful, `Failure` otherwise.
87
+ * @internal
88
+ */
89
+ _validateContext(context) {
90
+ return this._resourceManager.validateContext(context);
91
+ }
92
+ /**
93
+ * Enumerates target resource IDs for delta generation.
94
+ * If specific resource IDs are provided, uses those. Otherwise, discovers all resources
95
+ * from both the baseline resource manager and the delta resolver to ensure comprehensive
96
+ * coverage of all potential resources.
97
+ *
98
+ * @param requestedIds - Optional array of specific resource IDs to target.
99
+ * @param context - The validated context to use for resource discovery.
100
+ * @returns `Success` with array of resource IDs if successful, `Failure` otherwise.
101
+ * @internal
102
+ */
103
+ _enumerateTargetResources(requestedIds, context) {
104
+ /* c8 ignore next 20 - functional code tested but coverage intermittently missed */
105
+ if (requestedIds && requestedIds.length > 0) {
106
+ this._logger.info(`Using ${requestedIds.length} specified resource IDs`);
107
+ // Validate the requested IDs
108
+ const validatedIds = [];
109
+ const errors = new ts_utils_1.MessageAggregator();
110
+ for (const id of requestedIds) {
111
+ const validationResult = this._resourceManager.getBuiltResource(id);
112
+ if (validationResult.isSuccess()) {
113
+ validatedIds.push(id);
114
+ }
115
+ else {
116
+ errors.addMessage(`Invalid resource ID "${id}": ${validationResult.message}`);
117
+ }
118
+ }
119
+ if (errors.hasMessages) {
120
+ return (0, ts_utils_1.fail)(errors.toString());
121
+ }
122
+ return (0, ts_utils_1.succeed)(validatedIds);
123
+ }
124
+ // Discover resources from both baseline and delta resolvers to ensure comprehensive coverage
125
+ this._logger.info('Discovering resources from both baseline and delta resolvers');
126
+ return this._discoverAllResourceIds().onSuccess((allResourceIds) => {
127
+ this._logger.info(`Discovered ${allResourceIds.length} unique resources across both resolvers`);
128
+ return (0, ts_utils_1.succeed)(allResourceIds);
129
+ });
130
+ }
131
+ /**
132
+ * Discovers all unique resource IDs from both baseline and delta resolvers.
133
+ * Creates a union of resource IDs from the baseline resource manager and delta resolver
134
+ * to ensure comprehensive coverage of all resources.
135
+ *
136
+ * @returns `Success` with array of unique resource IDs if successful, `Failure` otherwise.
137
+ * @internal
138
+ */
139
+ _discoverAllResourceIds() {
140
+ // Get resource IDs from baseline resource manager
141
+ return this._resourceManager.getAllBuiltResources().onSuccess((baselineResources) => {
142
+ const baselineResourceIds = baselineResources.map((r) => r.id);
143
+ this._logger.detail(`Found ${baselineResourceIds.length} resources in baseline`);
144
+ // Get resource IDs from delta resolver using the public interface
145
+ const deltaResourceIds = this._deltaResolver.resourceIds;
146
+ this._logger.detail(`Found ${deltaResourceIds.length} resources in delta`);
147
+ // Create a union of resource IDs from both sources
148
+ const allResourceIds = new Set();
149
+ // Add baseline resource IDs
150
+ baselineResourceIds.forEach((id) => {
151
+ allResourceIds.add(id);
152
+ });
153
+ // Add delta resource IDs
154
+ deltaResourceIds.forEach((id) => {
155
+ allResourceIds.add(id);
156
+ });
157
+ const uniqueResourceIds = Array.from(allResourceIds);
158
+ this._logger.detail(`Created union of ${uniqueResourceIds.length} unique resource IDs`);
159
+ return (0, ts_utils_1.succeed)(uniqueResourceIds);
160
+ });
161
+ }
162
+ /**
163
+ * Creates a clone of the resource manager for delta operations.
164
+ * @returns `Success` with the cloned resource manager if successful, `Failure` otherwise.
165
+ * @internal
166
+ */
167
+ _cloneResourceManager() {
168
+ this._logger.info('Cloning resource manager');
169
+ return this._resourceManager.clone();
170
+ }
171
+ /**
172
+ * Generates deltas for the specified resources and adds them to the cloned manager.
173
+ *
174
+ * @param clonedManager - The cloned resource manager to update.
175
+ * @param resourceIds - Array of resource IDs to process.
176
+ * @param context - The context to use for resource resolution.
177
+ * @param skipUnchanged - Whether to skip resources that haven't changed.
178
+ * @returns `Success` with the updated manager if successful, `Failure` otherwise.
179
+ * @internal
180
+ */
181
+ _generateDeltas(clonedManager, resourceIds, context, skipUnchanged) {
182
+ this._logger.info(`Generating deltas for ${resourceIds.length} resources`);
183
+ const errors = new ts_utils_1.MessageAggregator();
184
+ let processedCount = 0;
185
+ let changedCount = 0;
186
+ let newCount = 0;
187
+ let skippedCount = 0;
188
+ for (const resourceId of resourceIds) {
189
+ this._logger.detail(`Processing resource: ${resourceId}`);
190
+ const result = this._generateResourceDelta(clonedManager, resourceId, context, skipUnchanged);
191
+ /* c8 ignore next 3 - functional code tested but coverage intermittently missed */
192
+ if (result.isFailure()) {
193
+ errors.addMessage(`${resourceId}: ${result.message}`);
194
+ continue;
195
+ }
196
+ processedCount++;
197
+ // Track statistics based on result
198
+ const deltaResult = result.value;
199
+ if (deltaResult.type === 'skipped') {
200
+ skippedCount++;
201
+ }
202
+ else if (deltaResult.type === 'new') {
203
+ newCount++;
204
+ }
205
+ else {
206
+ changedCount++;
207
+ }
208
+ }
209
+ this._logger.info(`Processed ${processedCount} resources: ${changedCount} updated, ${newCount} new, ${skippedCount} skipped`);
210
+ /* c8 ignore next 2 - functional code tested but coverage intermittently missed */
211
+ if (errors.hasMessages) {
212
+ return (0, ts_utils_1.fail)(`Delta generation failed with errors:\n${errors.toString()}`);
213
+ }
214
+ return (0, ts_utils_1.succeed)(clonedManager);
215
+ }
216
+ /**
217
+ * Generates a delta for a single resource and adds appropriate candidates to the manager.
218
+ *
219
+ * @param manager - The resource manager to update.
220
+ * @param resourceId - The resource ID to process.
221
+ * @param context - The context to use for resource resolution.
222
+ * @param skipUnchanged - Whether to skip resources that haven't changed.
223
+ * @returns `Success` with the resource delta result if successful, `Failure` otherwise.
224
+ * @internal
225
+ */
226
+ _generateResourceDelta(manager, resourceId, context, skipUnchanged) {
227
+ // Resolve values from both resolvers
228
+ const baselineResult = this._baselineResolver.resolveComposedResourceValue(resourceId);
229
+ const deltaResult = this._deltaResolver.resolveComposedResourceValue(resourceId);
230
+ const baselineExists = baselineResult.isSuccess();
231
+ const deltaExists = deltaResult.isSuccess();
232
+ if (deltaExists && !baselineExists) {
233
+ // New resource - exists in delta but not in baseline
234
+ this._logger.detail(`${resourceId}: New resource detected (exists in delta only)`);
235
+ return this._createNewResourceCandidate(manager, resourceId, deltaResult.value, context).onSuccess(() => (0, ts_utils_1.succeed)({ type: 'new', resourceId }));
236
+ }
237
+ if (baselineExists && !deltaExists) {
238
+ // Baseline-only resource - exists in baseline but not in delta (potential deletion)
239
+ // For now, skip these resources since delete merge method is not yet implemented
240
+ // TODO: When 'delete' merge method is available, create deletion candidates here
241
+ this._logger.detail(`${resourceId}: Baseline-only resource detected, skipping (delete merge method not yet implemented)`);
242
+ return (0, ts_utils_1.succeed)({ type: 'skipped', resourceId });
243
+ }
244
+ /* c8 ignore next 4 - defense in depth should not happen in practice */
245
+ if (!baselineExists && !deltaExists) {
246
+ // Resource doesn't exist in either resolver - this shouldn't happen due to enumeration logic
247
+ return (0, ts_utils_1.fail)(`Resource ${resourceId} not found in either baseline or delta resolvers`);
248
+ }
249
+ // Both resolvers have the resource - check for changes
250
+ // At this point, both results are successful so values are guaranteed to exist
251
+ const baselineValue = baselineResult.value; // Safe: baselineExists is true
252
+ const deltaValue = deltaResult.value; // Safe: deltaExists is true
253
+ // Check if values are identical
254
+ if (skipUnchanged && this._areValuesIdentical(baselineValue, deltaValue)) {
255
+ this._logger.detail(`${resourceId}: No changes detected, skipping`);
256
+ return (0, ts_utils_1.succeed)({ type: 'skipped', resourceId });
257
+ }
258
+ // Updated resource - compute delta and create partial/augment candidate
259
+ this._logger.detail(`${resourceId}: Changes detected, computing delta`);
260
+ return this._createDeltaCandidate(manager, resourceId, baselineValue, deltaValue, context).onSuccess(() => (0, ts_utils_1.succeed)({ type: 'updated', resourceId }));
261
+ }
262
+ /**
263
+ * Checks if two JSON values are identical.
264
+ * @param value1 - First value to compare.
265
+ * @param value2 - Second value to compare.
266
+ * @returns True if values are identical, false otherwise.
267
+ * @internal
268
+ */
269
+ _areValuesIdentical(value1, value2) {
270
+ return JSON.stringify(value1) === JSON.stringify(value2);
271
+ }
272
+ /**
273
+ * Creates a new resource candidate for a newly discovered resource.
274
+ * Uses full/replace merge method since this is a completely new resource.
275
+ *
276
+ * @param manager - The resource manager to update.
277
+ * @param resourceId - The resource ID for the new resource.
278
+ * @param value - The resolved value for the new resource.
279
+ * @param context - The context used for resolution.
280
+ * @returns `Success` if the candidate was added successfully, `Failure` otherwise.
281
+ * @internal
282
+ */
283
+ _createNewResourceCandidate(manager, resourceId, value, context) {
284
+ /* c8 ignore next 2 - functional code tested but coverage intermittently missed */
285
+ if (!(0, ts_json_base_1.isJsonObject)(value)) {
286
+ return (0, ts_utils_1.fail)(`Resource value must be a JSON object, got ${typeof value}`);
287
+ }
288
+ const candidateDecl = {
289
+ id: resourceId,
290
+ json: value,
291
+ conditions: Object.keys(context).length > 0 ? context : undefined,
292
+ isPartial: false,
293
+ mergeMethod: 'replace',
294
+ resourceTypeName: 'json' // Use 'json' resource type for new JSON resources
295
+ };
296
+ return manager.addLooseCandidate(candidateDecl).asResult.onSuccess(() => (0, ts_utils_1.succeed)(undefined));
297
+ }
298
+ /**
299
+ * Creates a delta candidate for an updated resource.
300
+ * Computes the difference between baseline and delta values and creates
301
+ * a partial/augment candidate with only the changed properties.
302
+ *
303
+ * @param manager - The resource manager to update.
304
+ * @param resourceId - The resource ID for the updated resource.
305
+ * @param baselineValue - The baseline resolved value.
306
+ * @param deltaValue - The delta resolved value.
307
+ * @param context - The context used for resolution.
308
+ * @returns `Success` if the candidate was added successfully, `Failure` otherwise.
309
+ * @internal
310
+ */
311
+ _createDeltaCandidate(manager, resourceId, baselineValue, deltaValue, context) {
312
+ // Compute three-way diff to get only the changed properties
313
+ return ts_json_1.Diff.jsonThreeWayDiff(baselineValue, deltaValue).onSuccess((diff) => {
314
+ if (diff.identical) {
315
+ // This shouldn't happen if we checked for identity earlier, but be defensive
316
+ this._logger.warn(`${resourceId}: Diff reports identical values, skipping`);
317
+ return (0, ts_utils_1.succeed)(undefined);
318
+ }
319
+ // Use onlyInB (second object) which contains new/changed properties
320
+ const deltaChanges = diff.onlyInB;
321
+ /* c8 ignore next 2 - functional code tested but coverage intermittently missed */
322
+ if (!(0, ts_json_base_1.isJsonObject)(deltaChanges)) {
323
+ return (0, ts_utils_1.fail)(`Delta changes must be a JSON object, got ${typeof deltaChanges}`);
324
+ }
325
+ // TODO: Handle deletions using 'augment' merge method with null values
326
+ // Note: The 'delete' merge type is not yet implemented in ts-res, so we use 'augment'
327
+ // with null values for deletion semantics (as used in ts-res-ui-components).
328
+ // When the 'delete' merge type is available, this should be updated to use it.
329
+ const candidateDecl = {
330
+ id: resourceId,
331
+ json: deltaChanges,
332
+ conditions: Object.keys(context).length > 0 ? context : undefined,
333
+ isPartial: true,
334
+ mergeMethod: 'augment',
335
+ resourceTypeName: undefined // Will be inferred by the manager
336
+ };
337
+ return manager.addLooseCandidate(candidateDecl).asResult.onSuccess(() => (0, ts_utils_1.succeed)(undefined));
338
+ });
339
+ }
340
+ }
341
+ exports.DeltaGenerator = DeltaGenerator;
342
+ //# sourceMappingURL=deltaGenerator.js.map
@@ -1,6 +1,7 @@
1
1
  export * from './candidateReducer';
2
2
  export * from './candidateValue';
3
3
  export * from './candidateValueCollector';
4
+ export * from './deltaGenerator';
4
5
  export * from './resourceCandidate';
5
6
  export * from './resource';
6
7
  export * from './resourceBuilder';
@@ -38,6 +38,7 @@ Object.defineProperty(exports, "__esModule", { value: true });
38
38
  __exportStar(require("./candidateReducer"), exports);
39
39
  __exportStar(require("./candidateValue"), exports);
40
40
  __exportStar(require("./candidateValueCollector"), exports);
41
+ __exportStar(require("./deltaGenerator"), exports);
41
42
  __exportStar(require("./resourceCandidate"), exports);
42
43
  __exportStar(require("./resource"), exports);
43
44
  __exportStar(require("./resourceBuilder"), exports);