@contrail/cli 3.6.0-alpha-8-alpha.c613d8e → 3.6.0-alpha-8-alpha.2ba81bf

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.
@@ -1,41 +1,48 @@
1
1
  "use strict";
2
2
  Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.summarizeSettledUpdates = void 0;
3
4
  const tslib_1 = require("tslib");
4
5
  const p_limit_1 = tslib_1.__importDefault(require("p-limit"));
5
6
  const core_1 = require("@oclif/core");
6
7
  const basecommand_1 = require("../../basecommand");
7
8
  const sdk_1 = require("@contrail/sdk");
8
9
  const login_1 = require("../../auth/login");
10
+ const common_1 = require("../../common");
9
11
  const propertySpecifications_1 = require("../../helpers/propertySpecifications/propertySpecifications");
10
12
  const file_helpers_1 = require("../../helpers/file-helpers");
11
13
  class UpdateEntity extends basecommand_1.BaseCommand {
12
- static description = '(BETA) Update an entity';
14
+ static description = 'Update an entity';
13
15
  static examples = [
14
16
  'contrail entities update color 123 -- name=obsidian hex=000000',
17
+ 'contrail entities update item id1 id2 id3 -- status=archived # apply the same change to several entities',
15
18
  'contrail entities update color 123 -- description= notes=\'""\' # Unset description, set notes to empty string',
16
19
  ];
17
20
  static flags = {
18
21
  ...basecommand_1.BaseCommand.baseFlags,
19
22
  skipHydrateRelationships: core_1.Flags.boolean({
20
- char: 's',
23
+ char: 'S',
21
24
  description: 'Skip hydrating relationships when updating the entity',
22
25
  required: false,
23
26
  default: false,
24
27
  }),
25
28
  dryRun: core_1.Flags.boolean({
26
29
  char: 'd',
27
- description: 'If true, does not create the entity but simulates the creation',
30
+ description: 'If true, does not update the entities but simulates the update',
28
31
  required: false,
29
32
  default: false,
30
33
  }),
31
34
  inputFile: core_1.Flags.string({
32
35
  char: 'i',
33
- description: 'File containing properties to update the entity (optional)',
36
+ description: 'A file with a JSON array of {id, ...} objects; each object is one entity to update.',
34
37
  required: false,
35
38
  }),
36
- force: core_1.Flags.boolean({
37
- char: 'F',
38
- description: 'Force update without validation. Internal use only',
39
+ suffix: core_1.Flags.string({
40
+ description: 'Append a sub-route to the entity endpoint (e.g. --suffix=synchronous targets /<entities>/synchronous)',
41
+ required: false,
42
+ }),
43
+ apiVersion: core_1.Flags.string({
44
+ description: 'Api-Version header to send; selects the V1 or V2 variant of the endpoint',
45
+ options: ['1', '2'],
39
46
  required: false,
40
47
  }),
41
48
  };
@@ -44,33 +51,40 @@ class UpdateEntity extends basecommand_1.BaseCommand {
44
51
  description: 'The name of the entity type to update',
45
52
  required: true,
46
53
  }),
47
- id: core_1.Args.string({
48
- description: 'The unique identifier of the entity',
54
+ ids: core_1.Args.string({
55
+ description: 'One or more entity ids to update',
49
56
  required: false,
50
57
  }),
51
58
  };
52
59
  static strict = false;
60
+ async init() {
61
+ (0, common_1.routeConsoleLogToStderr)();
62
+ await super.init();
63
+ }
53
64
  async run() {
54
- this.log('🚨 This command is in BETA and may change or be removed at any time.');
55
65
  await (0, login_1.authUser)();
56
66
  const { args, argv } = await this.parse(UpdateEntity);
57
- const { id: specifiedId, entityName } = args;
58
- const { dryRun: isDryRun, inputFile: inputFilename, skipHydrateRelationships, force, } = this.flags;
59
- const propertySpecArgs = argv.slice(1, argv.length).filter(propertySpecifications_1.isValidPropertySpecification);
60
- const propertySpec = (0, propertySpecifications_1.parsePropertySpecificationsIntoMap)(propertySpecArgs);
61
- if (inputFilename && specifiedId) {
62
- throw new Error('You cannot use --input and --id together. Please specify one or the other.');
67
+ const { entityName } = args;
68
+ const { dryRun: isDryRun, inputFile: inputFilename, skipHydrateRelationships, suffix, apiVersion, } = this.flags;
69
+ const { ids: positionalIds, specs } = (0, propertySpecifications_1.partitionIdsAndSpecs)(argv.slice(1));
70
+ const propertySpec = (0, propertySpecifications_1.parsePropertySpecificationsIntoMap)(specs);
71
+ if (propertySpec.has('id') || propertySpec.has('ids')) {
72
+ this.error('The -- payload is values to write. Pass ids positionally: contrail entities update <typePath> <ID...> -- slug=value');
73
+ }
74
+ if (inputFilename && positionalIds.length > 0) {
75
+ this.error('You cannot use --inputFile and positional ids together. Please specify one or the other.');
76
+ }
77
+ if (!inputFilename && positionalIds.length === 0) {
78
+ this.error('You must provide one or more ids or an input file (-i) of entities to update.');
79
+ }
80
+ if (positionalIds.length > 0 && propertySpec.size === 0) {
81
+ this.error('Nothing to update: pass values to write after --, e.g. -- name=jet');
63
82
  }
64
83
  const entitiesToUpdate = inputFilename
65
84
  ? (0, file_helpers_1.parseFileAsJsonArray)(inputFilename)
66
- : [{ id: specifiedId }];
67
- const results = {
68
- idsSuccessfullyUpdated: new Set(),
69
- idsFailedToUpdate: new Set(),
70
- numEntriesSkipped: entitiesToUpdate.filter(({ id }) => !id).length,
71
- };
85
+ : positionalIds.map((id) => ({ id }));
86
+ const skipped = entitiesToUpdate.filter(({ id }) => !id).length;
72
87
  const entitiesWithId = entitiesToUpdate.filter(({ id }) => id);
73
- propertySpec.delete('id'); // Remove 'id' from the property spec if it exists
74
88
  // will be applied to all entities
75
89
  const fixedValues = [...propertySpec.entries()].reduce((acc, [key, value]) => {
76
90
  acc[key] = value;
@@ -79,39 +93,61 @@ class UpdateEntity extends basecommand_1.BaseCommand {
79
93
  async function updateEntity(entity) {
80
94
  const newEntityState = { ...entity, ...fixedValues };
81
95
  const id = entity.id;
82
- const promise = isDryRun
96
+ return isDryRun
83
97
  ? mockUpdateById(entityName, id, newEntityState, { skipHydrateRelationships })
84
- : updateEntityById(entityName, id, newEntityState, { skipHydrateRelationships, force });
85
- promise
86
- .catch(() => {
87
- results.idsFailedToUpdate.add(id);
88
- })
89
- .then(() => {
90
- results.idsSuccessfullyUpdated.add(id);
91
- });
92
- return promise;
98
+ : updateEntityById(entityName, id, newEntityState, {
99
+ skipHydrateRelationships,
100
+ suffix,
101
+ apiVersion: apiVersion,
102
+ });
93
103
  }
94
104
  try {
95
105
  const limit = (0, p_limit_1.default)(20);
96
- const responses = await Promise.all(entitiesWithId.map((entity) => limit(() => updateEntity(entity))));
97
- const messagePrefix = isDryRun
98
- ? 'Dry run. Update skipped. Changes would be:'
99
- : 'Entity updated successfully:';
100
- this.log(`${messagePrefix}\n\n${JSON.stringify(responses, null, 2)}`);
101
- this.log(`\nIDs successfully updated: ${Array.from(results.idsSuccessfullyUpdated).join(', ')}`);
102
- this.log(`IDs failed to update: ${Array.from(results.idsFailedToUpdate).join(', ')}`);
103
- this.log(`Number of entries skipped due to missing IDs: ${results.numEntriesSkipped}`);
106
+ const settled = await Promise.allSettled(entitiesWithId.map((entity) => limit(() => updateEntity(entity))));
107
+ const summary = summarizeSettledUpdates(entitiesWithId, settled, skipped);
108
+ if (isDryRun) {
109
+ console.error('Dry run. Update skipped. Changes would be:');
110
+ }
111
+ this.log(JSON.stringify(summary, null, 2));
112
+ if (summary.failed.length > 0) {
113
+ console.error(`${summary.failed.length} of ${entitiesWithId.length} updates failed.`);
114
+ process.exitCode = 1;
115
+ }
104
116
  }
105
117
  catch (e) {
106
- this.error(`Error fetching entity: ${e.message}`);
118
+ this.error(`Error updating entities: ${e.message}`);
107
119
  }
108
120
  }
109
121
  }
110
122
  exports.default = UpdateEntity;
123
+ function summarizeSettledUpdates(inputs, settled, skipped) {
124
+ const updated = [];
125
+ const failed = [];
126
+ settled.forEach((result, index) => {
127
+ if (result.status === 'fulfilled') {
128
+ updated.push(result.value);
129
+ }
130
+ else {
131
+ failed.push({
132
+ id: inputs[index].id,
133
+ error: (0, common_1.sdkErrorMessage)(result.reason),
134
+ });
135
+ }
136
+ });
137
+ return { updated, failed, skipped };
138
+ }
139
+ exports.summarizeSettledUpdates = summarizeSettledUpdates;
111
140
  async function updateEntityById(entityName, id, changes, options = {}) {
112
141
  const client = new sdk_1.Entities();
113
- const { skipHydrateRelationships, force } = options;
114
- return client.update({ entityName, id, object: changes, skipHydrateRelationships });
142
+ const { skipHydrateRelationships, suffix, apiVersion } = options;
143
+ return client.update({
144
+ entityName,
145
+ id,
146
+ object: changes,
147
+ skipHydrateRelationships,
148
+ suffix,
149
+ apiVersion,
150
+ });
115
151
  }
116
152
  async function mockUpdateById(entityName, id, changes, options = {}) {
117
153
  const client = new sdk_1.Entities();
package/dist/common.d.ts CHANGED
@@ -2,3 +2,6 @@
2
2
  export declare function getSeparatorByPlatform(): string;
3
3
  export declare function delay(ms: number): Promise<NodeJS.Timeout>;
4
4
  export declare function removeSlash(string: string): string;
5
+ export declare function routeConsoleLogToStderr(): void;
6
+ export declare function sdkErrorMessage(reason: any): string;
7
+ export declare const promptOnStderr: any;
package/dist/common.js CHANGED
@@ -1,6 +1,8 @@
1
1
  "use strict";
2
2
  Object.defineProperty(exports, "__esModule", { value: true });
3
- exports.removeSlash = exports.delay = exports.getSeparatorByPlatform = void 0;
3
+ exports.promptOnStderr = exports.sdkErrorMessage = exports.routeConsoleLogToStderr = exports.removeSlash = exports.delay = exports.getSeparatorByPlatform = void 0;
4
+ const tslib_1 = require("tslib");
5
+ const inquirer_1 = tslib_1.__importDefault(require("inquirer"));
4
6
  function getSeparatorByPlatform() {
5
7
  const isWin = process.platform === 'win32';
6
8
  const separator = isWin ? '\\' : '/';
@@ -16,3 +18,18 @@ function removeSlash(string) {
16
18
  return string.replace(re, '-');
17
19
  }
18
20
  exports.removeSlash = removeSlash;
21
+ // The SDK and auth flow print request logs and token messages via bare
22
+ // console.log. A command whose stdout is a data contract must route those to
23
+ // stderr before any of that code runs.
24
+ function routeConsoleLogToStderr() {
25
+ console.log = (...args) => console.error(...args);
26
+ }
27
+ exports.routeConsoleLogToStderr = routeConsoleLogToStderr;
28
+ // SDK errors can carry an empty message with the response body in details
29
+ function sdkErrorMessage(reason) {
30
+ return reason?.message || reason?.details || String(reason);
31
+ }
32
+ exports.sdkErrorMessage = sdkErrorMessage;
33
+ // inquirer renders prompt UI to its output stream directly, bypassing the
34
+ // console.log redirect; stdout must stay data-only
35
+ exports.promptOnStderr = inquirer_1.default.createPromptModule({ output: process.stderr });
@@ -1,10 +1,12 @@
1
1
  import { Item } from '@contrail/entity-types';
2
+ import { API_VERSION } from '@contrail/sdk';
2
3
  export declare function throwIfInvalidAssortmentId(assortmentId: string): Promise<void>;
3
4
  export declare function createAssortmentItem(assortmentItem: {
4
5
  assortmentId: string;
5
6
  itemId: string;
6
7
  [key: string]: any;
7
- }, { skipHydrateRelationships }?: {
8
- skipHydrateRelationships: boolean;
8
+ }, options?: {
9
+ skipHydrateRelationships?: boolean;
10
+ apiVersion?: API_VERSION;
9
11
  }): Promise<any>;
10
12
  export declare function findItemsNotInAssortment(assortmentId: string, count?: number): Promise<Item[]>;
@@ -15,15 +15,17 @@ async function doesAssortmentExistById(id) {
15
15
  const assortment = await client.get({ entityName: 'assortment', id });
16
16
  return !!assortment;
17
17
  }
18
- async function createAssortmentItem(assortmentItem, { skipHydrateRelationships } = { skipHydrateRelationships: false }) {
18
+ async function createAssortmentItem(assortmentItem, options = {}) {
19
19
  const client = new sdk_1.Entities();
20
20
  const { assortmentId, itemId } = assortmentItem;
21
+ const { skipHydrateRelationships = false, apiVersion } = options;
21
22
  // add item to assortment
22
23
  await client.create({
23
24
  entityName: 'assortment',
24
25
  id: assortmentId,
25
26
  relation: 'items',
26
27
  object: { itemIds: [itemId] },
28
+ apiVersion,
27
29
  });
28
30
  // Update assortment item with properties
29
31
  const updated = await client.update({
@@ -31,6 +33,7 @@ async function createAssortmentItem(assortmentItem, { skipHydrateRelationships }
31
33
  id: `${assortmentId}:${itemId}`,
32
34
  object: assortmentItem,
33
35
  skipHydrateRelationships,
36
+ apiVersion,
34
37
  });
35
38
  return updated;
36
39
  }
@@ -3,8 +3,8 @@ Object.defineProperty(exports, "__esModule", { value: true });
3
3
  exports.loadData = exports.saveData = exports.parseFileAsJsonArray = exports.parseCSVData = exports.safeFileOverwrite = void 0;
4
4
  const tslib_1 = require("tslib");
5
5
  const path = tslib_1.__importStar(require("path"));
6
+ const common_1 = require("../common");
6
7
  const fs_1 = tslib_1.__importDefault(require("fs"));
7
- const inquirer_1 = tslib_1.__importDefault(require("inquirer"));
8
8
  const js_yaml_1 = tslib_1.__importDefault(require("js-yaml"));
9
9
  const logger_1 = tslib_1.__importDefault(require("../logger"));
10
10
  const sync_1 = require("csv-parse/sync");
@@ -15,7 +15,7 @@ async function safeFileOverwrite(fileLocation, overwrite) {
15
15
  logger_1.default.info(`overwriting ${fileLocation}`);
16
16
  return true;
17
17
  }
18
- const answers = await inquirer_1.default.prompt([
18
+ const answers = await (0, common_1.promptOnStderr)([
19
19
  {
20
20
  type: 'confirm',
21
21
  name: 'shouldOverwrite',
@@ -29,4 +29,12 @@ export type PropertySpecificationBySlug = Map<string, string | number | string[]
29
29
  export type PropertySpecificationString = `${string}=${string}`;
30
30
  export declare function parsePropertySpecification(spec: PropertySpecificationString): PropertySpecification;
31
31
  export declare function parsePropertySpecificationsIntoMap(propertySpecifications: PropertySpecificationString[]): PropertySpecificationBySlug;
32
+ /**
33
+ * Splits command argv tokens (after the typePath) into positional ids and
34
+ * property specifications.
35
+ */
36
+ export declare function partitionIdsAndSpecs(tokens: string[]): {
37
+ ids: string[];
38
+ specs: PropertySpecificationString[];
39
+ };
32
40
  export declare function isValidPropertySpecification(maybeSpec: string): maybeSpec is PropertySpecificationString;
@@ -23,7 +23,7 @@
23
23
  * contrail entities get loader-processes -- createdOn=2025-09-15..2025-09-16
24
24
  */
25
25
  Object.defineProperty(exports, "__esModule", { value: true });
26
- exports.isValidPropertySpecification = exports.parsePropertySpecificationsIntoMap = exports.parsePropertySpecification = void 0;
26
+ exports.isValidPropertySpecification = exports.partitionIdsAndSpecs = exports.parsePropertySpecificationsIntoMap = exports.parsePropertySpecification = void 0;
27
27
  const dateRanges_1 = require("./dateRanges");
28
28
  // Special tokens for empty strings
29
29
  const DOUBLE_QUOTED_EMPTY = '""';
@@ -64,16 +64,17 @@ function parsePropertySpecificationsIntoMap(propertySpecifications) {
64
64
  continue;
65
65
  }
66
66
  const { slug, value } = parsePropertySpecification(spec);
67
- if (slug === 'roles' && value !== undefined) {
68
- // Special handling for roles, which can be an array (only if value is not undefined)
69
- const rolesArray = value.split(',').map((role) => role.trim());
70
- propertySpecBySlug.set(slug, rolesArray);
71
- continue;
72
- }
73
67
  if (slug === 'ids' && value !== undefined) {
74
- // Special handling for ids, which can be an array (only if value is not undefined)
68
+ // ids is the one comma-split exception: it is a list of ids by definition
69
+ // and ids never contain commas.
75
70
  const idsArray = value.split(',').map((id) => id.trim());
76
- propertySpecBySlug.set(slug, idsArray);
71
+ const existingIds = propertySpecBySlug.get(slug);
72
+ propertySpecBySlug.set(slug, Array.isArray(existingIds) ? [...existingIds, ...idsArray] : idsArray);
73
+ continue;
74
+ }
75
+ const existing = propertySpecBySlug.get(slug);
76
+ if (propertySpecBySlug.has(slug) && existing !== undefined && value !== undefined) {
77
+ propertySpecBySlug.set(slug, Array.isArray(existing) ? [...existing, value] : [existing, value]);
77
78
  continue;
78
79
  }
79
80
  propertySpecBySlug.set(slug, value);
@@ -81,6 +82,17 @@ function parsePropertySpecificationsIntoMap(propertySpecifications) {
81
82
  return propertySpecBySlug;
82
83
  }
83
84
  exports.parsePropertySpecificationsIntoMap = parsePropertySpecificationsIntoMap;
85
+ /**
86
+ * Splits command argv tokens (after the typePath) into positional ids and
87
+ * property specifications.
88
+ */
89
+ function partitionIdsAndSpecs(tokens) {
90
+ return {
91
+ ids: tokens.filter((token) => !token.includes('=')),
92
+ specs: tokens.filter(isValidPropertySpecification),
93
+ };
94
+ }
95
+ exports.partitionIdsAndSpecs = partitionIdsAndSpecs;
84
96
  function isValidPropertySpecification(maybeSpec) {
85
97
  try {
86
98
  if ((0, dateRanges_1.isDateRangeSpecification)(maybeSpec)) {
@@ -142,12 +142,17 @@ describe('parsePropertySpecificationsIntoMap', () => {
142
142
  expect(result.get('url')).toBe('https://example.com');
143
143
  expect(result.size).toBe(3);
144
144
  });
145
- it('should handle duplicate slugs by overwriting with last value', () => {
145
+ it('should accumulate repeated keys into an array', () => {
146
146
  const specs = ['name=first', 'name=second', 'name=third'];
147
147
  const result = (0, propertySpecifications_1.parsePropertySpecificationsIntoMap)(specs);
148
- expect(result.get('name')).toBe('third');
148
+ expect(result.get('name')).toEqual(['first', 'second', 'third']);
149
149
  expect(result.size).toBe(1);
150
150
  });
151
+ it('should keep a single value scalar', () => {
152
+ const specs = ['status=archived'];
153
+ const result = (0, propertySpecifications_1.parsePropertySpecificationsIntoMap)(specs);
154
+ expect(result.get('status')).toBe('archived');
155
+ });
151
156
  it('should handle property specifications with empty values', () => {
152
157
  const specs = ['name=john', 'description=', 'notes=""'];
153
158
  const result = (0, propertySpecifications_1.parsePropertySpecificationsIntoMap)(specs);
@@ -163,21 +168,21 @@ describe('parsePropertySpecificationsIntoMap', () => {
163
168
  ];
164
169
  expect(() => (0, propertySpecifications_1.parsePropertySpecificationsIntoMap)(specs)).toThrow('Invalid property specification: invalid');
165
170
  });
166
- it('should handle roles as comma-separated array', () => {
167
- const specs = ['roles=option,family', 'name=Test'];
171
+ it('should build roles arrays from repeated keys, with commas literal', () => {
172
+ const specs = ['roles=option', 'roles=family', 'name=Test'];
168
173
  const result = (0, propertySpecifications_1.parsePropertySpecificationsIntoMap)(specs);
169
174
  expect(result.get('roles')).toEqual(['option', 'family']);
170
175
  expect(result.get('name')).toBe('Test');
171
176
  });
172
- it('should handle roles as single value', () => {
173
- const specs = ['roles=option'];
177
+ it('should treat a comma in a roles value as literal', () => {
178
+ const specs = ['roles=option,family'];
174
179
  const result = (0, propertySpecifications_1.parsePropertySpecificationsIntoMap)(specs);
175
- expect(result.get('roles')).toEqual(['option']);
180
+ expect(result.get('roles')).toBe('option,family');
176
181
  });
177
- it('should trim whitespace in roles array', () => {
178
- const specs = ['roles=option, family, variant'];
182
+ it('should keep commas literal in ordinary values', () => {
183
+ const specs = ['name=my,name'];
179
184
  const result = (0, propertySpecifications_1.parsePropertySpecificationsIntoMap)(specs);
180
- expect(result.get('roles')).toEqual(['option', 'family', 'variant']);
185
+ expect(result.get('name')).toBe('my,name');
181
186
  });
182
187
  it('should handle ids as comma-separated array', () => {
183
188
  const specs = ['ids=1,2,3', 'name=Test'];
@@ -185,6 +190,11 @@ describe('parsePropertySpecificationsIntoMap', () => {
185
190
  expect(result.get('ids')).toEqual(['1', '2', '3']);
186
191
  expect(result.get('name')).toBe('Test');
187
192
  });
193
+ it('should accumulate repeated ids keys', () => {
194
+ const specs = ['ids=1,2', 'ids=3'];
195
+ const result = (0, propertySpecifications_1.parsePropertySpecificationsIntoMap)(specs);
196
+ expect(result.get('ids')).toEqual(['1', '2', '3']);
197
+ });
188
198
  it('should handle ids as single value', () => {
189
199
  const specs = ['ids=123'];
190
200
  const result = (0, propertySpecifications_1.parsePropertySpecificationsIntoMap)(specs);
package/dist/logger.js CHANGED
@@ -12,7 +12,10 @@ class Logger {
12
12
  debug: 'blue',
13
13
  };
14
14
  constructor() {
15
- const transport = new winston_1.transports.Console();
15
+ // All log output goes to stderr so stdout carries only command output (JSON)
16
+ const transport = new winston_1.transports.Console({
17
+ stderrLevels: ['error', 'warn', 'info', 'debug'],
18
+ });
16
19
  winston_1.default.addColors(this.colors);
17
20
  this.logger = (0, winston_1.createLogger)({
18
21
  level: 'info',
@@ -0,0 +1 @@
1
+ export {};
@@ -0,0 +1,12 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ const tslib_1 = require("tslib");
4
+ const logger_1 = tslib_1.__importDefault(require("./logger"));
5
+ describe('logger', () => {
6
+ it('should write every log level to stderr so stdout carries only command output', () => {
7
+ const consoleTransport = logger_1.default.transports[0];
8
+ for (const level of ['error', 'warn', 'info', 'debug']) {
9
+ expect(consoleTransport.stderrLevels[level]).toBe(true);
10
+ }
11
+ });
12
+ });