@contrail/cli 3.6.0-alpha-8-alpha.85a73d5 → 3.6.0-alpha-8-alpha.5ffe1e1
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.
- package/README.md +1 -1
- package/dist/commands/entities/create.d.ts +1 -2
- package/dist/commands/entities/create.js +10 -42
- package/dist/commands/entities/create.spec.js +0 -31
- package/dist/commands/entities/get.js +29 -9
- package/dist/commands/entities/update.js +50 -3
- package/dist/helpers/propertySpecifications/propertyValues.d.ts +31 -0
- package/dist/helpers/propertySpecifications/propertyValues.js +128 -0
- package/dist/helpers/propertySpecifications/propertyValues.spec.d.ts +1 -0
- package/dist/helpers/propertySpecifications/propertyValues.spec.js +148 -0
- package/oclif.manifest.json +1 -1
- package/package.json +1 -1
package/README.md
CHANGED
|
@@ -17,7 +17,7 @@ $ npm install -g @contrail/cli
|
|
|
17
17
|
$ contrail COMMAND
|
|
18
18
|
running command...
|
|
19
19
|
$ contrail (--version)
|
|
20
|
-
@contrail/cli/3.6.0-alpha-8-alpha.
|
|
20
|
+
@contrail/cli/3.6.0-alpha-8-alpha.5ffe1e1 linux-x64 node-v24.22.2
|
|
21
21
|
$ contrail --help [COMMAND]
|
|
22
22
|
USAGE
|
|
23
23
|
$ contrail COMMAND
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import { PropertyLevel
|
|
1
|
+
import { PropertyLevel } from '@contrail/types';
|
|
2
2
|
import { ColonDelimited, TypeProperty as ExtendedTypeProperty, TypeReferencesCacheByPath } from '../../api/types';
|
|
3
3
|
import { TypeWithProperties } from '../../api/types';
|
|
4
4
|
import { BaseCommand } from '../../basecommand';
|
|
@@ -42,7 +42,6 @@ export type WithId = {
|
|
|
42
42
|
export type ObjectReferenceCache = Map<string, WithId>;
|
|
43
43
|
type ObjectReferenceCachesByTypePath = Map<string, ObjectReferenceCache>;
|
|
44
44
|
export declare function pickRandomValueForProperty(property: ExtendedTypeProperty, objectReferencesCache: ObjectReferenceCachesByTypePath, typeReferencesCache: TypeReferencesCacheByPath): number | string | string[] | boolean | null;
|
|
45
|
-
export declare function castValueToPropertyType(value: string | number | string[] | number[], propertyType: PropertyType, propertySlug: string): any;
|
|
46
45
|
export declare function getReferencedObjectPaths(type: TypeWithProperties): ColonDelimited[];
|
|
47
46
|
export declare function buildObjectReferenceCache(entities: any[]): ObjectReferenceCache;
|
|
48
47
|
export declare function selectRandomObject(cache: ObjectReferenceCache): WithId;
|
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
"use strict";
|
|
2
2
|
Object.defineProperty(exports, "__esModule", { value: true });
|
|
3
|
-
exports.doesPropertyLevelMatchRole = exports.selectRandomObject = exports.buildObjectReferenceCache = exports.getReferencedObjectPaths = exports.
|
|
3
|
+
exports.doesPropertyLevelMatchRole = exports.selectRandomObject = exports.buildObjectReferenceCache = exports.getReferencedObjectPaths = exports.pickRandomValueForProperty = exports.pickRandomPropertyValues = exports.summarizeSettledCreates = void 0;
|
|
4
4
|
const tslib_1 = require("tslib");
|
|
5
5
|
const fs_1 = tslib_1.__importDefault(require("fs"));
|
|
6
6
|
const unique_names_generator_1 = require("unique-names-generator");
|
|
@@ -14,6 +14,7 @@ const common_1 = require("../../common");
|
|
|
14
14
|
const basecommand_1 = require("../../basecommand");
|
|
15
15
|
const sdk_1 = require("@contrail/sdk");
|
|
16
16
|
const entities_1 = require("../../helpers/entities");
|
|
17
|
+
const propertyValues_1 = require("../../helpers/propertySpecifications/propertyValues");
|
|
17
18
|
const propertySpecifications_1 = require("../../helpers/propertySpecifications/propertySpecifications");
|
|
18
19
|
const file_helpers_1 = require("../../helpers/file-helpers");
|
|
19
20
|
let IS_DRY_RUN = false;
|
|
@@ -233,6 +234,9 @@ class CreateEntity extends basecommand_1.BaseCommand {
|
|
|
233
234
|
this.error(`create takes no positional ids (got: ${strayTokens.join(' ')}); did you forget -- before property values?`);
|
|
234
235
|
}
|
|
235
236
|
const propertySpecBySlug = (0, propertySpecifications_1.parsePropertySpecificationsIntoMap)(specs);
|
|
237
|
+
if (Array.isArray(propertySpecBySlug.get('typePath'))) {
|
|
238
|
+
this.error('typePath takes a single value. Repeat the key only for multi-value properties.');
|
|
239
|
+
}
|
|
236
240
|
// Validate args
|
|
237
241
|
if (!entityTypePath) {
|
|
238
242
|
this.error('You must specify an entity type path.');
|
|
@@ -368,11 +372,11 @@ function createEntityWithPopulatedValues(type, typeReferencesCache, objectRefere
|
|
|
368
372
|
: {};
|
|
369
373
|
// Handle property specifications
|
|
370
374
|
for (const [propertySlug, specifiedValue] of propertySpecificationBySlug.entries()) {
|
|
371
|
-
const correspondingProperty = type.typeProperties.find((prop) => getPropertySlug(prop) === propertySlug);
|
|
375
|
+
const correspondingProperty = type.typeProperties.find((prop) => (0, propertyValues_1.getPropertySlug)(prop) === propertySlug);
|
|
372
376
|
if (specifiedValue === undefined) {
|
|
373
377
|
continue;
|
|
374
378
|
}
|
|
375
|
-
entity[propertySlug] = castValueToPropertyType(specifiedValue, correspondingProperty?.propertyType || types_1.PropertyType.String, propertySlug);
|
|
379
|
+
entity[propertySlug] = (0, propertyValues_1.castValueToPropertyType)(specifiedValue, correspondingProperty?.propertyType || types_1.PropertyType.String, propertySlug);
|
|
376
380
|
}
|
|
377
381
|
// Give Readbable IDs if specified
|
|
378
382
|
if (SHOULD_USE_READABLE_IDS) {
|
|
@@ -409,7 +413,7 @@ function pickRandomPropertyValues(type, objectReferencesCache, typeReferencesCac
|
|
|
409
413
|
// Validate property level
|
|
410
414
|
if (roles?.length && roles.every((r) => !doesPropertyLevelMatchRole(property.propertyLevel, r)))
|
|
411
415
|
continue;
|
|
412
|
-
if (suppliedSlugs?.has(getPropertySlug(property)))
|
|
416
|
+
if (suppliedSlugs?.has((0, propertyValues_1.getPropertySlug)(property)))
|
|
413
417
|
continue;
|
|
414
418
|
// Generate random value
|
|
415
419
|
if (property.propertyType === types_1.PropertyType.ObjectReference) {
|
|
@@ -417,10 +421,10 @@ function pickRandomPropertyValues(type, objectReferencesCache, typeReferencesCac
|
|
|
417
421
|
if (!cache || cache.size === 0) {
|
|
418
422
|
throw new Error(`No object references found for referencedTypePath: ${property.referencedTypePath}`);
|
|
419
423
|
}
|
|
420
|
-
entity[getPropertySlug(property)] = selectRandomObject(cache).id;
|
|
424
|
+
entity[(0, propertyValues_1.getPropertySlug)(property)] = selectRandomObject(cache).id;
|
|
421
425
|
}
|
|
422
426
|
else {
|
|
423
|
-
entity[getPropertySlug(property)] = pickRandomValueForProperty(property, objectReferencesCache, typeReferencesCache);
|
|
427
|
+
entity[(0, propertyValues_1.getPropertySlug)(property)] = pickRandomValueForProperty(property, objectReferencesCache, typeReferencesCache);
|
|
424
428
|
}
|
|
425
429
|
}
|
|
426
430
|
return entity;
|
|
@@ -513,37 +517,6 @@ function generateRandomReadableString() {
|
|
|
513
517
|
function generateRandomDateString() {
|
|
514
518
|
return new Date().toISOString();
|
|
515
519
|
}
|
|
516
|
-
function castValueToPropertyType(value, propertyType, propertySlug) {
|
|
517
|
-
if (Array.isArray(value) && propertyType !== types_1.PropertyType.MultiSelect) {
|
|
518
|
-
return value.map((element) => castValueToPropertyType(element, propertyType, propertySlug));
|
|
519
|
-
}
|
|
520
|
-
switch (propertyType) {
|
|
521
|
-
case types_1.PropertyType.Boolean:
|
|
522
|
-
return value.toString().toLowerCase() === 'true';
|
|
523
|
-
case types_1.PropertyType.Number:
|
|
524
|
-
const numValue = parseFloat(value.toString());
|
|
525
|
-
if (isNaN(numValue)) {
|
|
526
|
-
throw new Error(`Invalid number value: ${value}`);
|
|
527
|
-
}
|
|
528
|
-
return numValue;
|
|
529
|
-
case types_1.PropertyType.Date:
|
|
530
|
-
return new Date(value.toString()).toISOString();
|
|
531
|
-
case types_1.PropertyType.MultiSelect:
|
|
532
|
-
if (Array.isArray(value)) {
|
|
533
|
-
return value;
|
|
534
|
-
}
|
|
535
|
-
// the old comma syntax parses as one literal value; warn instead of guessing at a split
|
|
536
|
-
if (typeof value === 'string' && value.includes(',')) {
|
|
537
|
-
console.error(`${propertySlug} value "${value}" contains a comma and is treated as one literal value. To pass several values, repeat the key: ${propertySlug}=${value
|
|
538
|
-
.split(',')
|
|
539
|
-
.join(` ${propertySlug}=`)}`);
|
|
540
|
-
}
|
|
541
|
-
return [value];
|
|
542
|
-
default:
|
|
543
|
-
return value; // For string and other types, return as is
|
|
544
|
-
}
|
|
545
|
-
}
|
|
546
|
-
exports.castValueToPropertyType = castValueToPropertyType;
|
|
547
520
|
async function createEntity(entityName, entity, routing = {}) {
|
|
548
521
|
const client = new sdk_1.Entities();
|
|
549
522
|
const skipHydrateRelationships = SHOULD_SKIP_HYDRATE_RELATIONSHIPS;
|
|
@@ -619,11 +592,6 @@ function requiredValues(path, typeCache) {
|
|
|
619
592
|
return [{ slug: 'typeId', value: typeCache.get(path)?.id || '' }];
|
|
620
593
|
}
|
|
621
594
|
}
|
|
622
|
-
function getPropertySlug(property) {
|
|
623
|
-
return property.propertyType === types_1.PropertyType.ObjectReference
|
|
624
|
-
? `${property.slug}Id`
|
|
625
|
-
: property.slug;
|
|
626
|
-
}
|
|
627
595
|
function doesPropertyLevelMatchRole(propertyLevel, role) {
|
|
628
596
|
const isMatchingLevel = propertyLevel === role;
|
|
629
597
|
return (isMatchingLevel ||
|
|
@@ -514,37 +514,6 @@ describe('Entity Creation E2E Happy Path', () => {
|
|
|
514
514
|
});
|
|
515
515
|
});
|
|
516
516
|
});
|
|
517
|
-
describe('castValueToPropertyType array coercion', () => {
|
|
518
|
-
it('should coerce a single value on a multi-value property to a one-element array', () => {
|
|
519
|
-
expect((0, create_1.castValueToPropertyType)('option', types_1.PropertyType.MultiSelect, 'colors')).toEqual([
|
|
520
|
-
'option',
|
|
521
|
-
]);
|
|
522
|
-
});
|
|
523
|
-
it('should pass arrays through on multi-value properties', () => {
|
|
524
|
-
expect((0, create_1.castValueToPropertyType)(['option', 'family'], types_1.PropertyType.MultiSelect, 'colors')).toEqual(['option', 'family']);
|
|
525
|
-
});
|
|
526
|
-
it('should keep a comma value literal on a multi-value property and warn with the repeated-key form', () => {
|
|
527
|
-
const consoleError = jest.spyOn(console, 'error').mockImplementation(() => undefined);
|
|
528
|
-
expect((0, create_1.castValueToPropertyType)('option,family', types_1.PropertyType.MultiSelect, 'colors')).toEqual([
|
|
529
|
-
'option,family',
|
|
530
|
-
]);
|
|
531
|
-
expect(consoleError).toHaveBeenCalledWith(expect.stringContaining('colors=option colors=family'));
|
|
532
|
-
consoleError.mockRestore();
|
|
533
|
-
});
|
|
534
|
-
it('should cast each element of a repeated-key array on scalar property types', () => {
|
|
535
|
-
expect((0, create_1.castValueToPropertyType)(['1', '2'], types_1.PropertyType.Number, 'rank')).toEqual([1, 2]);
|
|
536
|
-
expect((0, create_1.castValueToPropertyType)(['true', 'false'], types_1.PropertyType.Boolean, 'isActive')).toEqual([
|
|
537
|
-
true,
|
|
538
|
-
false,
|
|
539
|
-
]);
|
|
540
|
-
});
|
|
541
|
-
it('should keep commas literal on string properties without warning', () => {
|
|
542
|
-
const consoleError = jest.spyOn(console, 'error').mockImplementation(() => undefined);
|
|
543
|
-
expect((0, create_1.castValueToPropertyType)('my,name', types_1.PropertyType.String, 'name')).toBe('my,name');
|
|
544
|
-
expect(consoleError).not.toHaveBeenCalled();
|
|
545
|
-
consoleError.mockRestore();
|
|
546
|
-
});
|
|
547
|
-
});
|
|
548
517
|
describe('pickRandomPropertyValues', () => {
|
|
549
518
|
const caches = [new Map(), new Map()];
|
|
550
519
|
const typeWith = (properties) => ({ typePath: 't', typeProperties: properties });
|
|
@@ -3,6 +3,8 @@ Object.defineProperty(exports, "__esModule", { value: true });
|
|
|
3
3
|
const tslib_1 = require("tslib");
|
|
4
4
|
const fs_1 = tslib_1.__importDefault(require("fs"));
|
|
5
5
|
const core_1 = require("@oclif/core");
|
|
6
|
+
const types_1 = require("../../api/types");
|
|
7
|
+
const propertyValues_1 = require("../../helpers/propertySpecifications/propertyValues");
|
|
6
8
|
const basecommand_1 = require("../../basecommand");
|
|
7
9
|
const sdk_1 = require("@contrail/sdk");
|
|
8
10
|
const login_1 = require("../../auth/login");
|
|
@@ -127,11 +129,12 @@ class GetEntity extends basecommand_1.BaseCommand {
|
|
|
127
129
|
.map((s) => s.trim())
|
|
128
130
|
.filter(Boolean)
|
|
129
131
|
: [];
|
|
132
|
+
const queryTypes = await resolveQueryTypes(entityName, propertySpecBySlug);
|
|
130
133
|
try {
|
|
131
134
|
// TODO: break the paginated and single-shot branches into their own functions.
|
|
132
135
|
if (SHOULD_USE_PAGINATED_FIND) {
|
|
133
136
|
const stream = streamPaginatedFind(entityName, {
|
|
134
|
-
criteria: convertPropertySpecIntoCriteria(propertySpecBySlug),
|
|
137
|
+
criteria: convertPropertySpecIntoCriteria(propertySpecBySlug, queryTypes),
|
|
135
138
|
skipHydrateRelationships,
|
|
136
139
|
skip,
|
|
137
140
|
suffix,
|
|
@@ -153,7 +156,7 @@ class GetEntity extends basecommand_1.BaseCommand {
|
|
|
153
156
|
console.error(`Output saved to ${outputFile}`);
|
|
154
157
|
}
|
|
155
158
|
else {
|
|
156
|
-
const response = await getEntitiesByName(entityName, propertySpecBySlug, {
|
|
159
|
+
const response = await getEntitiesByName(entityName, propertySpecBySlug, queryTypes, {
|
|
157
160
|
skipHydrateRelationships,
|
|
158
161
|
relations,
|
|
159
162
|
propertySlugs: propertySlugsArray,
|
|
@@ -183,10 +186,10 @@ class GetEntity extends basecommand_1.BaseCommand {
|
|
|
183
186
|
}
|
|
184
187
|
}
|
|
185
188
|
exports.default = GetEntity;
|
|
186
|
-
async function getEntitiesByName(entityName, propertySpec, options = {}) {
|
|
189
|
+
async function getEntitiesByName(entityName, propertySpec, typePropertySets, options = {}) {
|
|
187
190
|
const { propertySlugs, relations, skipHydrateRelationships, skip, suffix, apiVersion, take } = options;
|
|
188
191
|
const id = propertySpec?.get('id')?.toString() || undefined;
|
|
189
|
-
const criteria = convertPropertySpecIntoCriteria(propertySpec || new Map());
|
|
192
|
+
const criteria = convertPropertySpecIntoCriteria(propertySpec || new Map(), typePropertySets);
|
|
190
193
|
return find(entityName, {
|
|
191
194
|
id,
|
|
192
195
|
// a missing id returns null (no retries); the command turns it into a clean not-found error
|
|
@@ -201,15 +204,32 @@ async function getEntitiesByName(entityName, propertySpec, options = {}) {
|
|
|
201
204
|
take,
|
|
202
205
|
});
|
|
203
206
|
}
|
|
204
|
-
function convertPropertySpecIntoCriteria(propertySpec) {
|
|
205
|
-
const
|
|
207
|
+
function convertPropertySpecIntoCriteria(propertySpec, typePropertySets = []) {
|
|
208
|
+
const ranges = new Map();
|
|
209
|
+
const values = new Map();
|
|
206
210
|
propertySpec.forEach((value, slug) => {
|
|
207
|
-
|
|
208
|
-
|
|
209
|
-
|
|
211
|
+
((0, dateRanges_1.isDateRangeValue)(value) ? ranges : values).set(slug, value);
|
|
212
|
+
});
|
|
213
|
+
const criteria = (0, propertyValues_1.castCriteriaValues)(values, typePropertySets);
|
|
214
|
+
ranges.forEach((value, slug) => {
|
|
215
|
+
criteria[slug] = (0, dateRanges_1.convertDateRangeToJSURL)((0, dateRanges_1.parseDateRange)(value));
|
|
210
216
|
});
|
|
211
217
|
return criteria;
|
|
212
218
|
}
|
|
219
|
+
/**
|
|
220
|
+
* The types a query should be read against: the subtypes named by a typePath
|
|
221
|
+
* criterion if there is one, otherwise the entity's root type. A subtype
|
|
222
|
+
* carries its inherited properties, so one lookup per named path is enough.
|
|
223
|
+
*/
|
|
224
|
+
async function resolveQueryTypes(entityName, propertySpec) {
|
|
225
|
+
const specified = propertySpec.get('typePath');
|
|
226
|
+
const paths = specified === undefined ? [entityName] : [specified].flat().map(String);
|
|
227
|
+
const types = await Promise.all(paths.map((path) => (0, types_1.getTypeByPath)(path).catch(() => {
|
|
228
|
+
console.error(`Could not resolve type ${path}; criteria on it are read as written.`);
|
|
229
|
+
return undefined;
|
|
230
|
+
})));
|
|
231
|
+
return types.map((type) => type?.typeProperties);
|
|
232
|
+
}
|
|
213
233
|
async function find(entityName, options = {}) {
|
|
214
234
|
const client = new sdk_1.Entities();
|
|
215
235
|
const { criteria, id, ignore404, propertySlugs, skipHydrateRelationships, relations, skip, suffix, apiVersion, take, } = options;
|
|
@@ -10,6 +10,8 @@ const login_1 = require("../../auth/login");
|
|
|
10
10
|
const common_1 = require("../../common");
|
|
11
11
|
const propertySpecifications_1 = require("../../helpers/propertySpecifications/propertySpecifications");
|
|
12
12
|
const file_helpers_1 = require("../../helpers/file-helpers");
|
|
13
|
+
const propertyValues_1 = require("../../helpers/propertySpecifications/propertyValues");
|
|
14
|
+
const types_1 = require("../../api/types");
|
|
13
15
|
class UpdateEntity extends basecommand_1.BaseCommand {
|
|
14
16
|
static description = 'Update an entity';
|
|
15
17
|
static examples = [
|
|
@@ -88,12 +90,24 @@ class UpdateEntity extends basecommand_1.BaseCommand {
|
|
|
88
90
|
: positionalIds.map((id) => ({ id }));
|
|
89
91
|
const skipped = entitiesToUpdate.filter(({ id }) => !id).length;
|
|
90
92
|
const entitiesWithId = entitiesToUpdate.filter(({ id }) => id);
|
|
91
|
-
|
|
93
|
+
if (Array.isArray(propertySpec.get('typePath'))) {
|
|
94
|
+
this.error('typePath takes a single value. Repeat the key only for multi-value properties.');
|
|
95
|
+
}
|
|
96
|
+
// cast against each record's own subtype: the API converts numeric strings itself
|
|
97
|
+
// but rejects boolean ones, so an uncast isArchived=false comes back as a 400
|
|
98
|
+
const typePropertiesById = await resolvePropertiesByEntityId(entityName, entitiesWithId.map(({ id }) => id));
|
|
92
99
|
// JSON.stringify drops undefined keys, so an unset has to travel as an explicit null
|
|
93
|
-
const
|
|
100
|
+
const unsetValues = Object.fromEntries([...propertySpec.keys()]
|
|
101
|
+
.filter((slug) => propertySpec.get(slug) === undefined)
|
|
102
|
+
.map((slug) => [slug, null]));
|
|
103
|
+
const specifiedValues = new Map([...propertySpec.entries()].filter(([, value]) => value !== undefined));
|
|
94
104
|
async function updateEntity(entity) {
|
|
95
|
-
const newEntityState = { ...entity, ...fixedValues };
|
|
96
105
|
const id = entity.id;
|
|
106
|
+
const newEntityState = {
|
|
107
|
+
...entity,
|
|
108
|
+
...(0, propertyValues_1.castValuesToPropertyTypes)(specifiedValues, typePropertiesById.get(id)),
|
|
109
|
+
...unsetValues,
|
|
110
|
+
};
|
|
97
111
|
return isDryRun
|
|
98
112
|
? mockUpdateById(entityName, id, newEntityState, { skipHydrateRelationships })
|
|
99
113
|
: updateEntityById(entityName, id, newEntityState, {
|
|
@@ -121,6 +135,39 @@ class UpdateEntity extends basecommand_1.BaseCommand {
|
|
|
121
135
|
}
|
|
122
136
|
}
|
|
123
137
|
exports.default = UpdateEntity;
|
|
138
|
+
// The ids criterion travels in the URL, which the gateway rejects somewhere past
|
|
139
|
+
// 5k characters, so the lookup goes out in chunks.
|
|
140
|
+
const ID_LOOKUP_CHUNK_SIZE = 250;
|
|
141
|
+
async function resolvePropertiesByEntityId(entityName, ids) {
|
|
142
|
+
const rootType = await (0, types_1.getTypeByPath)(entityName).catch(() => undefined);
|
|
143
|
+
const typePathById = await fetchTypePathsByIds(entityName, ids);
|
|
144
|
+
const distinctPaths = [...new Set([...typePathById.values()])];
|
|
145
|
+
const propertiesByPath = new Map();
|
|
146
|
+
await Promise.all(distinctPaths.map(async (path) => {
|
|
147
|
+
const type = await (0, types_1.getTypeByPath)(path).catch(() => undefined);
|
|
148
|
+
propertiesByPath.set(path, type?.typeProperties ?? rootType?.typeProperties);
|
|
149
|
+
}));
|
|
150
|
+
// an id the lookup did not return falls back to the root type; the write reports its own 404
|
|
151
|
+
return new Map(ids.map((id) => [id, propertiesByPath.get(typePathById.get(id)) ?? rootType?.typeProperties]));
|
|
152
|
+
}
|
|
153
|
+
async function fetchTypePathsByIds(entityName, ids) {
|
|
154
|
+
const client = new sdk_1.Entities();
|
|
155
|
+
const chunks = [];
|
|
156
|
+
for (let i = 0; i < ids.length; i += ID_LOOKUP_CHUNK_SIZE) {
|
|
157
|
+
chunks.push(ids.slice(i, i + ID_LOOKUP_CHUNK_SIZE));
|
|
158
|
+
}
|
|
159
|
+
const pages = await Promise.all(chunks.map((chunk) => client
|
|
160
|
+
.get({
|
|
161
|
+
entityName,
|
|
162
|
+
criteria: { ids: chunk },
|
|
163
|
+
customParams: { propertySlugs: 'id,typePath' },
|
|
164
|
+
})
|
|
165
|
+
.catch(() => [])));
|
|
166
|
+
return new Map(pages
|
|
167
|
+
.flat()
|
|
168
|
+
.filter((entity) => entity?.id && entity?.typePath)
|
|
169
|
+
.map((entity) => [entity.id, entity.typePath]));
|
|
170
|
+
}
|
|
124
171
|
function summarizeSettledUpdates(inputs, settled, skipped) {
|
|
125
172
|
const updated = [];
|
|
126
173
|
const failed = [];
|
|
@@ -0,0 +1,31 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Turns parsed property specification values into the shapes the API expects.
|
|
3
|
+
*
|
|
4
|
+
* Writes cast only from a type definition and never guess, so a wrong value
|
|
5
|
+
* fails loudly rather than being silently rewritten. Reads fall back to the
|
|
6
|
+
* value's own shape for slugs no resolved type defines, because the alternative
|
|
7
|
+
* is a criterion that matches nothing and reports no error.
|
|
8
|
+
*/
|
|
9
|
+
import { PropertyType, TypeProperty } from '@contrail/types';
|
|
10
|
+
export declare function getPropertySlug(property: TypeProperty): string;
|
|
11
|
+
export declare function castValueToPropertyType(value: string | number | string[] | number[], propertyType: PropertyType, propertySlug: string): any;
|
|
12
|
+
/**
|
|
13
|
+
* Coerces a value from its own shape. Only used for reads, and only for slugs
|
|
14
|
+
* no resolved type defines.
|
|
15
|
+
*/
|
|
16
|
+
export declare function inferAndCastValue(value: any): any;
|
|
17
|
+
/**
|
|
18
|
+
* Builds the slug to property type lookup for one or more resolved types.
|
|
19
|
+
* Where two types define the same slug differently the first one given wins.
|
|
20
|
+
*/
|
|
21
|
+
export declare function buildPropertyTypeMap(typePropertySets: (TypeProperty[] | undefined)[]): Map<string, PropertyType>;
|
|
22
|
+
/**
|
|
23
|
+
* Casts values for a write. A slug the type does not define is written through
|
|
24
|
+
* unchanged, which is what happens for a property only a subtype declares.
|
|
25
|
+
*/
|
|
26
|
+
export declare function castValuesToPropertyTypes(valueBySlug: Map<string, any>, typeProperties?: TypeProperty[]): Record<string, any>;
|
|
27
|
+
/**
|
|
28
|
+
* Casts values for a read, falling back to the value's own shape so that a
|
|
29
|
+
* criterion on a slug the resolved types do not define still matches.
|
|
30
|
+
*/
|
|
31
|
+
export declare function castCriteriaValues(valueBySlug: Map<string, any>, typePropertySets?: (TypeProperty[] | undefined)[]): Record<string, any>;
|
|
@@ -0,0 +1,128 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
/**
|
|
3
|
+
* Turns parsed property specification values into the shapes the API expects.
|
|
4
|
+
*
|
|
5
|
+
* Writes cast only from a type definition and never guess, so a wrong value
|
|
6
|
+
* fails loudly rather than being silently rewritten. Reads fall back to the
|
|
7
|
+
* value's own shape for slugs no resolved type defines, because the alternative
|
|
8
|
+
* is a criterion that matches nothing and reports no error.
|
|
9
|
+
*/
|
|
10
|
+
Object.defineProperty(exports, "__esModule", { value: true });
|
|
11
|
+
exports.castCriteriaValues = exports.castValuesToPropertyTypes = exports.buildPropertyTypeMap = exports.inferAndCastValue = exports.castValueToPropertyType = exports.getPropertySlug = void 0;
|
|
12
|
+
const types_1 = require("@contrail/types");
|
|
13
|
+
// identifiers are always strings; coercing one would turn a numeric id into a number
|
|
14
|
+
const SLUGS_NEVER_CAST = new Set(['id', 'ids']);
|
|
15
|
+
const ISO_DATE = /^\d{4}-\d{2}-\d{2}(T\d{2}:\d{2}:\d{2}(\.\d+)?(Z|[+-]\d{2}:\d{2})?)?$/;
|
|
16
|
+
function getPropertySlug(property) {
|
|
17
|
+
return property.propertyType === types_1.PropertyType.ObjectReference
|
|
18
|
+
? `${property.slug}Id`
|
|
19
|
+
: property.slug;
|
|
20
|
+
}
|
|
21
|
+
exports.getPropertySlug = getPropertySlug;
|
|
22
|
+
function castValueToPropertyType(value, propertyType, propertySlug) {
|
|
23
|
+
if (Array.isArray(value) && propertyType !== types_1.PropertyType.MultiSelect) {
|
|
24
|
+
return value.map((element) => castValueToPropertyType(element, propertyType, propertySlug));
|
|
25
|
+
}
|
|
26
|
+
switch (propertyType) {
|
|
27
|
+
case types_1.PropertyType.Boolean:
|
|
28
|
+
return value.toString().toLowerCase() === 'true';
|
|
29
|
+
case types_1.PropertyType.Number:
|
|
30
|
+
case types_1.PropertyType.Currency:
|
|
31
|
+
case types_1.PropertyType.Percent:
|
|
32
|
+
case types_1.PropertyType.Rating:
|
|
33
|
+
case types_1.PropertyType.Sequence:
|
|
34
|
+
const numValue = parseFloat(value.toString());
|
|
35
|
+
if (isNaN(numValue)) {
|
|
36
|
+
throw new Error(`Invalid number value: ${value}`);
|
|
37
|
+
}
|
|
38
|
+
return numValue;
|
|
39
|
+
case types_1.PropertyType.Date:
|
|
40
|
+
return new Date(value.toString()).toISOString();
|
|
41
|
+
case types_1.PropertyType.MultiSelect:
|
|
42
|
+
if (Array.isArray(value)) {
|
|
43
|
+
return value;
|
|
44
|
+
}
|
|
45
|
+
// the old comma syntax parses as one literal value; warn instead of guessing at a split
|
|
46
|
+
if (typeof value === 'string' && value.includes(',')) {
|
|
47
|
+
console.error(`${propertySlug} value "${value}" contains a comma and is treated as one literal value. To pass several values, repeat the key: ${propertySlug}=${value
|
|
48
|
+
.split(',')
|
|
49
|
+
.join(` ${propertySlug}=`)}`);
|
|
50
|
+
}
|
|
51
|
+
return [value];
|
|
52
|
+
default:
|
|
53
|
+
return value; // For string and other types, return as is
|
|
54
|
+
}
|
|
55
|
+
}
|
|
56
|
+
exports.castValueToPropertyType = castValueToPropertyType;
|
|
57
|
+
/**
|
|
58
|
+
* Coerces a value from its own shape. Only used for reads, and only for slugs
|
|
59
|
+
* no resolved type defines.
|
|
60
|
+
*/
|
|
61
|
+
function inferAndCastValue(value) {
|
|
62
|
+
if (Array.isArray(value)) {
|
|
63
|
+
return value.map(inferAndCastValue);
|
|
64
|
+
}
|
|
65
|
+
if (typeof value !== 'string' || value === '') {
|
|
66
|
+
return value;
|
|
67
|
+
}
|
|
68
|
+
if (value === 'true')
|
|
69
|
+
return true;
|
|
70
|
+
if (value === 'false')
|
|
71
|
+
return false;
|
|
72
|
+
if (ISO_DATE.test(value) && !isNaN(new Date(value).getTime())) {
|
|
73
|
+
return new Date(value).toISOString();
|
|
74
|
+
}
|
|
75
|
+
// only coerce a number that survives the round trip, so 000000, 007 and 12.50 stay strings
|
|
76
|
+
const asNumber = Number(value);
|
|
77
|
+
return !isNaN(asNumber) && String(asNumber) === value ? asNumber : value;
|
|
78
|
+
}
|
|
79
|
+
exports.inferAndCastValue = inferAndCastValue;
|
|
80
|
+
/**
|
|
81
|
+
* Builds the slug to property type lookup for one or more resolved types.
|
|
82
|
+
* Where two types define the same slug differently the first one given wins.
|
|
83
|
+
*/
|
|
84
|
+
function buildPropertyTypeMap(typePropertySets) {
|
|
85
|
+
const propertyTypeBySlug = new Map();
|
|
86
|
+
for (const typeProperties of typePropertySets) {
|
|
87
|
+
for (const property of typeProperties ?? []) {
|
|
88
|
+
const slug = getPropertySlug(property);
|
|
89
|
+
if (!propertyTypeBySlug.has(slug)) {
|
|
90
|
+
propertyTypeBySlug.set(slug, property.propertyType);
|
|
91
|
+
}
|
|
92
|
+
}
|
|
93
|
+
}
|
|
94
|
+
return propertyTypeBySlug;
|
|
95
|
+
}
|
|
96
|
+
exports.buildPropertyTypeMap = buildPropertyTypeMap;
|
|
97
|
+
/**
|
|
98
|
+
* Casts values for a write. A slug the type does not define is written through
|
|
99
|
+
* unchanged, which is what happens for a property only a subtype declares.
|
|
100
|
+
*/
|
|
101
|
+
function castValuesToPropertyTypes(valueBySlug, typeProperties = []) {
|
|
102
|
+
const propertyTypeBySlug = buildPropertyTypeMap([typeProperties]);
|
|
103
|
+
return Object.fromEntries([...valueBySlug.entries()].map(([slug, value]) => [
|
|
104
|
+
slug,
|
|
105
|
+
SLUGS_NEVER_CAST.has(slug) || !propertyTypeBySlug.has(slug)
|
|
106
|
+
? value
|
|
107
|
+
: castValueToPropertyType(value, propertyTypeBySlug.get(slug), slug),
|
|
108
|
+
]));
|
|
109
|
+
}
|
|
110
|
+
exports.castValuesToPropertyTypes = castValuesToPropertyTypes;
|
|
111
|
+
/**
|
|
112
|
+
* Casts values for a read, falling back to the value's own shape so that a
|
|
113
|
+
* criterion on a slug the resolved types do not define still matches.
|
|
114
|
+
*/
|
|
115
|
+
function castCriteriaValues(valueBySlug, typePropertySets = []) {
|
|
116
|
+
const propertyTypeBySlug = buildPropertyTypeMap(typePropertySets);
|
|
117
|
+
return Object.fromEntries([...valueBySlug.entries()].map(([slug, value]) => {
|
|
118
|
+
if (SLUGS_NEVER_CAST.has(slug))
|
|
119
|
+
return [slug, value];
|
|
120
|
+
return [
|
|
121
|
+
slug,
|
|
122
|
+
propertyTypeBySlug.has(slug)
|
|
123
|
+
? castValueToPropertyType(value, propertyTypeBySlug.get(slug), slug)
|
|
124
|
+
: inferAndCastValue(value),
|
|
125
|
+
];
|
|
126
|
+
}));
|
|
127
|
+
}
|
|
128
|
+
exports.castCriteriaValues = castCriteriaValues;
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
export {};
|
|
@@ -0,0 +1,148 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
Object.defineProperty(exports, "__esModule", { value: true });
|
|
3
|
+
const types_1 = require("@contrail/types");
|
|
4
|
+
const propertyValues_1 = require("./propertyValues");
|
|
5
|
+
describe('castValueToPropertyType array coercion', () => {
|
|
6
|
+
it('should coerce a single value on a multi-value property to a one-element array', () => {
|
|
7
|
+
expect((0, propertyValues_1.castValueToPropertyType)('option', types_1.PropertyType.MultiSelect, 'colors')).toEqual([
|
|
8
|
+
'option',
|
|
9
|
+
]);
|
|
10
|
+
});
|
|
11
|
+
it('should pass arrays through on multi-value properties', () => {
|
|
12
|
+
expect((0, propertyValues_1.castValueToPropertyType)(['option', 'family'], types_1.PropertyType.MultiSelect, 'colors')).toEqual(['option', 'family']);
|
|
13
|
+
});
|
|
14
|
+
it('should keep a comma value literal on a multi-value property and warn with the repeated-key form', () => {
|
|
15
|
+
const consoleError = jest.spyOn(console, 'error').mockImplementation(() => undefined);
|
|
16
|
+
expect((0, propertyValues_1.castValueToPropertyType)('option,family', types_1.PropertyType.MultiSelect, 'colors')).toEqual([
|
|
17
|
+
'option,family',
|
|
18
|
+
]);
|
|
19
|
+
expect(consoleError).toHaveBeenCalledWith(expect.stringContaining('colors=option colors=family'));
|
|
20
|
+
consoleError.mockRestore();
|
|
21
|
+
});
|
|
22
|
+
it('should cast each element of a repeated-key array on scalar property types', () => {
|
|
23
|
+
expect((0, propertyValues_1.castValueToPropertyType)(['1', '2'], types_1.PropertyType.Number, 'rank')).toEqual([1, 2]);
|
|
24
|
+
expect((0, propertyValues_1.castValueToPropertyType)(['true', 'false'], types_1.PropertyType.Boolean, 'isActive')).toEqual([
|
|
25
|
+
true,
|
|
26
|
+
false,
|
|
27
|
+
]);
|
|
28
|
+
});
|
|
29
|
+
it('should keep commas literal on string properties without warning', () => {
|
|
30
|
+
const consoleError = jest.spyOn(console, 'error').mockImplementation(() => undefined);
|
|
31
|
+
expect((0, propertyValues_1.castValueToPropertyType)('my,name', types_1.PropertyType.String, 'name')).toBe('my,name');
|
|
32
|
+
expect(consoleError).not.toHaveBeenCalled();
|
|
33
|
+
consoleError.mockRestore();
|
|
34
|
+
});
|
|
35
|
+
});
|
|
36
|
+
describe('getPropertySlug', () => {
|
|
37
|
+
it('suffixes Id for an object reference', () => {
|
|
38
|
+
expect((0, propertyValues_1.getPropertySlug)({ slug: 'fabric', propertyType: types_1.PropertyType.ObjectReference })).toBe('fabricId');
|
|
39
|
+
});
|
|
40
|
+
it('leaves every other property type alone', () => {
|
|
41
|
+
expect((0, propertyValues_1.getPropertySlug)({ slug: 'name', propertyType: types_1.PropertyType.String })).toBe('name');
|
|
42
|
+
});
|
|
43
|
+
});
|
|
44
|
+
describe('castValuesToPropertyTypes', () => {
|
|
45
|
+
const typeProperties = [
|
|
46
|
+
{ slug: 'isArchived', propertyType: types_1.PropertyType.Boolean },
|
|
47
|
+
{ slug: 'rank', propertyType: types_1.PropertyType.Number },
|
|
48
|
+
{ slug: 'fabric', propertyType: types_1.PropertyType.ObjectReference },
|
|
49
|
+
];
|
|
50
|
+
it('casts each value using its property type', () => {
|
|
51
|
+
const result = (0, propertyValues_1.castValuesToPropertyTypes)(new Map([
|
|
52
|
+
['isArchived', 'false'],
|
|
53
|
+
['rank', '3'],
|
|
54
|
+
]), typeProperties);
|
|
55
|
+
expect(result).toEqual({ isArchived: false, rank: 3 });
|
|
56
|
+
});
|
|
57
|
+
it('matches an object reference by its suffixed slug', () => {
|
|
58
|
+
const result = (0, propertyValues_1.castValuesToPropertyTypes)(new Map([['fabricId', 'abc']]), typeProperties);
|
|
59
|
+
expect(result).toEqual({ fabricId: 'abc' });
|
|
60
|
+
});
|
|
61
|
+
it('writes a slug the type does not define through as a string', () => {
|
|
62
|
+
const result = (0, propertyValues_1.castValuesToPropertyTypes)(new Map([['unknown', 'false']]), typeProperties);
|
|
63
|
+
expect(result).toEqual({ unknown: 'false' });
|
|
64
|
+
});
|
|
65
|
+
it('treats a missing type as defining no properties', () => {
|
|
66
|
+
expect((0, propertyValues_1.castValuesToPropertyTypes)(new Map([['isArchived', 'true']]))).toEqual({
|
|
67
|
+
isArchived: 'true',
|
|
68
|
+
});
|
|
69
|
+
});
|
|
70
|
+
});
|
|
71
|
+
describe('inferAndCastValue', () => {
|
|
72
|
+
it('coerces a number only when it survives the round trip', () => {
|
|
73
|
+
expect((0, propertyValues_1.inferAndCastValue)('3650')).toBe(3650);
|
|
74
|
+
expect((0, propertyValues_1.inferAndCastValue)('12.5')).toBe(12.5);
|
|
75
|
+
expect((0, propertyValues_1.inferAndCastValue)('0')).toBe(0);
|
|
76
|
+
});
|
|
77
|
+
it('keeps numeric-looking strings that would not round trip', () => {
|
|
78
|
+
// hex=000000 appears in the create examples, and parseFloat would make it 0
|
|
79
|
+
expect((0, propertyValues_1.inferAndCastValue)('000000')).toBe('000000');
|
|
80
|
+
expect((0, propertyValues_1.inferAndCastValue)('007')).toBe('007');
|
|
81
|
+
expect((0, propertyValues_1.inferAndCastValue)('12.50')).toBe('12.50');
|
|
82
|
+
expect((0, propertyValues_1.inferAndCastValue)('1e5')).toBe('1e5');
|
|
83
|
+
});
|
|
84
|
+
it('coerces exact booleans only', () => {
|
|
85
|
+
expect((0, propertyValues_1.inferAndCastValue)('true')).toBe(true);
|
|
86
|
+
expect((0, propertyValues_1.inferAndCastValue)('false')).toBe(false);
|
|
87
|
+
expect((0, propertyValues_1.inferAndCastValue)('True')).toBe('True');
|
|
88
|
+
});
|
|
89
|
+
it('coerces ISO dates', () => {
|
|
90
|
+
expect((0, propertyValues_1.inferAndCastValue)('2025-09-15')).toBe('2025-09-15T00:00:00.000Z');
|
|
91
|
+
expect((0, propertyValues_1.inferAndCastValue)('not-a-date')).toBe('not-a-date');
|
|
92
|
+
});
|
|
93
|
+
it('maps over arrays and leaves non-strings alone', () => {
|
|
94
|
+
expect((0, propertyValues_1.inferAndCastValue)(['1', 'x'])).toEqual([1, 'x']);
|
|
95
|
+
expect((0, propertyValues_1.inferAndCastValue)(7)).toBe(7);
|
|
96
|
+
});
|
|
97
|
+
});
|
|
98
|
+
describe('buildPropertyTypeMap', () => {
|
|
99
|
+
it('gives the first type precedence for a conflicting slug', () => {
|
|
100
|
+
const first = [{ slug: 'matchingProperty2', propertyType: types_1.PropertyType.Number }];
|
|
101
|
+
const second = [{ slug: 'matchingProperty2', propertyType: types_1.PropertyType.String }];
|
|
102
|
+
expect((0, propertyValues_1.buildPropertyTypeMap)([first, second]).get('matchingProperty2')).toBe(types_1.PropertyType.Number);
|
|
103
|
+
expect((0, propertyValues_1.buildPropertyTypeMap)([second, first]).get('matchingProperty2')).toBe(types_1.PropertyType.String);
|
|
104
|
+
});
|
|
105
|
+
it('tolerates a type that could not be resolved', () => {
|
|
106
|
+
expect((0, propertyValues_1.buildPropertyTypeMap)([undefined]).size).toBe(0);
|
|
107
|
+
});
|
|
108
|
+
});
|
|
109
|
+
describe('castCriteriaValues', () => {
|
|
110
|
+
const typeProperties = [
|
|
111
|
+
{ slug: 'isArchived', propertyType: types_1.PropertyType.Boolean },
|
|
112
|
+
{ slug: 'optionSequence', propertyType: types_1.PropertyType.Sequence },
|
|
113
|
+
{ slug: 'hex', propertyType: types_1.PropertyType.String },
|
|
114
|
+
];
|
|
115
|
+
it('casts a defined slug from its property type', () => {
|
|
116
|
+
expect((0, propertyValues_1.castCriteriaValues)(new Map([['isArchived', 'false']]), [typeProperties])).toEqual({
|
|
117
|
+
isArchived: false,
|
|
118
|
+
});
|
|
119
|
+
});
|
|
120
|
+
it('casts the whole numeric family, not just Number', () => {
|
|
121
|
+
expect((0, propertyValues_1.castCriteriaValues)(new Map([['optionSequence', '3650']]), [typeProperties])).toEqual({
|
|
122
|
+
optionSequence: 3650,
|
|
123
|
+
});
|
|
124
|
+
});
|
|
125
|
+
it('leaves a defined string property alone', () => {
|
|
126
|
+
expect((0, propertyValues_1.castCriteriaValues)(new Map([['hex', '000000']]), [typeProperties])).toEqual({
|
|
127
|
+
hex: '000000',
|
|
128
|
+
});
|
|
129
|
+
});
|
|
130
|
+
it('falls back to the value shape for an undefined slug', () => {
|
|
131
|
+
expect((0, propertyValues_1.castCriteriaValues)(new Map([['unknown', 'true']]), [typeProperties])).toEqual({
|
|
132
|
+
unknown: true,
|
|
133
|
+
});
|
|
134
|
+
});
|
|
135
|
+
it('never coerces id or ids', () => {
|
|
136
|
+
expect((0, propertyValues_1.castCriteriaValues)(new Map([
|
|
137
|
+
['id', '12345'],
|
|
138
|
+
['ids', ['1', '2']],
|
|
139
|
+
]), [])).toEqual({ id: '12345', ids: ['1', '2'] });
|
|
140
|
+
});
|
|
141
|
+
});
|
|
142
|
+
describe('castValuesToPropertyTypes never guesses', () => {
|
|
143
|
+
it('writes an undefined slug through unchanged', () => {
|
|
144
|
+
expect((0, propertyValues_1.castValuesToPropertyTypes)(new Map([['unknown', 'true']]), [])).toEqual({
|
|
145
|
+
unknown: 'true',
|
|
146
|
+
});
|
|
147
|
+
});
|
|
148
|
+
});
|
package/oclif.manifest.json
CHANGED