@contrail/cli 3.6.0-alpha-8-alpha.252e3f3 → 3.6.0-alpha-8-alpha.c613d8e

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 (47) hide show
  1. package/README.md +31 -58
  2. package/dist/auth/login.js +8 -9
  3. package/dist/basecommand.js +2 -2
  4. package/dist/commands/app/getApiKey.js +2 -2
  5. package/dist/commands/entities/create.d.ts +1 -13
  6. package/dist/commands/entities/create.js +31 -98
  7. package/dist/commands/entities/create.spec.js +3 -32
  8. package/dist/commands/entities/delete.d.ts +2 -6
  9. package/dist/commands/entities/delete.js +53 -72
  10. package/dist/commands/entities/get.d.ts +0 -4
  11. package/dist/commands/entities/get.js +15 -66
  12. package/dist/commands/entities/update.d.ts +2 -15
  13. package/dist/commands/entities/update.js +44 -80
  14. package/dist/common.d.ts +0 -3
  15. package/dist/common.js +1 -18
  16. package/dist/helpers/entities/assortment-items.d.ts +2 -4
  17. package/dist/helpers/entities/assortment-items.js +1 -4
  18. package/dist/helpers/file-helpers.js +2 -2
  19. package/dist/helpers/propertySpecifications/propertySpecifications.d.ts +0 -8
  20. package/dist/helpers/propertySpecifications/propertySpecifications.js +9 -21
  21. package/dist/helpers/propertySpecifications/propertySpecifications.spec.js +10 -20
  22. package/dist/logger.js +1 -4
  23. package/node_modules/@contrail/entity-compare/package.json +6 -3
  24. package/node_modules/@contrail/loader/lib/common/conditional-columns.js +1 -1
  25. package/node_modules/@contrail/loader/lib/constants.d.ts +0 -8
  26. package/node_modules/@contrail/loader/lib/constants.js +1 -9
  27. package/node_modules/@contrail/loader/lib/entities-v2/linesheet-v2/item-processor.d.ts +0 -4
  28. package/node_modules/@contrail/loader/lib/entities-v2/linesheet-v2/item-processor.js +0 -57
  29. package/node_modules/@contrail/loader/lib/entities-v2/linesheet-v2/item-processor.spec.js +34 -492
  30. package/node_modules/@contrail/loader/lib/pipeline/validate.js +52 -2
  31. package/node_modules/@contrail/loader/lib/pipeline/validate.spec.js +85 -0
  32. package/node_modules/@contrail/loader/package.json +2 -2
  33. package/node_modules/@contrail/org-config-migration/node_modules/@contrail/sdk/lib/index.d.ts +0 -1
  34. package/node_modules/@contrail/org-config-migration/node_modules/@contrail/sdk/lib/index.js +0 -1
  35. package/node_modules/@contrail/org-config-migration/node_modules/@contrail/sdk/package.json +1 -1
  36. package/oclif.manifest.json +27 -99
  37. package/package.json +1 -1
  38. package/dist/commands/entities/grammar.spec.d.ts +0 -1
  39. package/dist/commands/entities/grammar.spec.js +0 -80
  40. package/dist/commands/entities/output.spec.d.ts +0 -1
  41. package/dist/commands/entities/output.spec.js +0 -72
  42. package/dist/logger.spec.d.ts +0 -1
  43. package/dist/logger.spec.js +0 -12
  44. package/node_modules/@contrail/org-config-migration/node_modules/@contrail/sdk/lib/image-search/image-search.d.ts +0 -34
  45. package/node_modules/@contrail/org-config-migration/node_modules/@contrail/sdk/lib/image-search/image-search.js +0 -42
  46. package/node_modules/@contrail/org-config-migration/node_modules/@contrail/sdk/lib/image-search/index.d.ts +0 -1
  47. package/node_modules/@contrail/org-config-migration/node_modules/@contrail/sdk/lib/image-search/index.js +0 -17
@@ -4,17 +4,13 @@ export default class DeleteEntity extends BaseCommand {
4
4
  static examples: string[];
5
5
  static flags: {
6
6
  dryRun: import("@oclif/core/lib/interfaces").BooleanFlag<boolean>;
7
- inputFile: import("@oclif/core/lib/interfaces").OptionFlag<string, import("@oclif/core/lib/interfaces/parser").CustomOptions>;
8
- suffix: import("@oclif/core/lib/interfaces").OptionFlag<string, import("@oclif/core/lib/interfaces/parser").CustomOptions>;
9
- apiVersion: import("@oclif/core/lib/interfaces").OptionFlag<string, import("@oclif/core/lib/interfaces/parser").CustomOptions>;
7
+ input: import("@oclif/core/lib/interfaces").OptionFlag<string, import("@oclif/core/lib/interfaces/parser").CustomOptions>;
8
+ id: import("@oclif/core/lib/interfaces").OptionFlag<string, import("@oclif/core/lib/interfaces/parser").CustomOptions>;
10
9
  alwaysConfirmEnv: import("@oclif/core/lib/interfaces").OptionFlag<string, import("@oclif/core/lib/interfaces/parser").CustomOptions>;
11
10
  logLevel: import("@oclif/core/lib/interfaces").OptionFlag<string, import("@oclif/core/lib/interfaces/parser").CustomOptions>;
12
11
  };
13
12
  static args: {
14
13
  entityName: import("@oclif/core/lib/interfaces/parser").Arg<string, Record<string, unknown>>;
15
- ids: import("@oclif/core/lib/interfaces/parser").Arg<string, Record<string, unknown>>;
16
14
  };
17
- static strict: boolean;
18
- init(): Promise<void>;
19
15
  run(): Promise<void>;
20
16
  }
@@ -6,37 +6,27 @@ const p_limit_1 = tslib_1.__importDefault(require("p-limit"));
6
6
  const basecommand_1 = require("../../basecommand");
7
7
  const sdk_1 = require("@contrail/sdk");
8
8
  const login_1 = require("../../auth/login");
9
- const common_1 = require("../../common");
10
9
  const file_helpers_1 = require("../../helpers/file-helpers");
11
10
  let IS_DRY_RUN = false;
12
11
  class DeleteEntity extends basecommand_1.BaseCommand {
13
- static description = 'Delete entities by id';
14
- static examples = [
15
- 'contrail entities delete color 123',
16
- 'contrail entities delete color id1 id2 id3',
17
- 'contrail entities delete item -i ids.json',
18
- ];
12
+ static description = '(BETA) Delete an entity';
13
+ static examples = ['contrail entities delete color 123'];
19
14
  static flags = {
20
15
  ...basecommand_1.BaseCommand.baseFlags,
21
16
  dryRun: core_1.Flags.boolean({
22
17
  char: 'd',
23
- description: 'If true, does not delete the entities but simulates the deletion',
18
+ description: 'If true, does not delete the entity but simulates the deletion',
24
19
  required: false,
25
20
  default: false,
26
21
  }),
27
- inputFile: core_1.Flags.string({
22
+ input: core_1.Flags.string({
28
23
  char: 'i',
29
- description: "A file with a JSON array of objects; only each object's id is used. Deletes every entity in the file.",
24
+ description: 'A JSON array of objects where each object is one entity to create. Cannot be used with --count. Unless --precise is specified, any missing values will be populated with random values.',
30
25
  required: false,
31
26
  multiple: false,
32
27
  }),
33
- suffix: core_1.Flags.string({
34
- description: 'Append a sub-route to the entity endpoint (e.g. --suffix=synchronous targets /<entities>/synchronous)',
35
- required: false,
36
- }),
37
- apiVersion: core_1.Flags.string({
38
- description: 'Api-Version header to send; selects the V1 or V2 variant of the endpoint',
39
- options: ['1', '2'],
28
+ id: core_1.Flags.string({
29
+ description: 'The unique identifier of the entity',
40
30
  required: false,
41
31
  }),
42
32
  };
@@ -45,93 +35,84 @@ class DeleteEntity extends basecommand_1.BaseCommand {
45
35
  description: 'The name of the entity type to delete',
46
36
  required: true,
47
37
  }),
48
- ids: core_1.Args.string({
49
- description: 'One or more entity ids to delete',
50
- required: false,
51
- }),
52
38
  };
53
- static strict = false;
54
- async init() {
55
- (0, common_1.routeConsoleLogToStderr)();
56
- await super.init();
57
- }
58
39
  async run() {
40
+ this.log('🚨 This command is in BETA and may change or be removed at any time.');
59
41
  await (0, login_1.authUser)();
60
- const { args, flags, argv } = await this.parse(DeleteEntity);
42
+ const { args, flags } = await this.parse(DeleteEntity);
61
43
  const { entityName } = args;
62
- const { inputFile: inputFilename, suffix, apiVersion } = flags;
44
+ const { id, input: inputFilename } = flags;
63
45
  if (flags.dryRun) {
64
46
  IS_DRY_RUN = true;
65
- console.error('Running in dry run mode. No entities will be deleted.');
66
- }
67
- const tokens = argv.slice(1);
68
- const valueTokens = tokens.filter((token) => token.includes('='));
69
- if (valueTokens.length > 0) {
70
- this.error(`delete takes no -- values (got: ${valueTokens.join(' ')}); pass ids positionally or use an input file (-i).`);
71
- }
72
- const positionalIds = tokens;
73
- if (inputFilename && positionalIds.length > 0) {
74
- this.error('You cannot use --inputFile and positional ids together. Please specify one or the other.');
75
- }
76
- if (!inputFilename && positionalIds.length === 0) {
77
- this.error('You must provide one or more ids or an input file (-i) of entities to delete.');
47
+ this.log('Running in dry run mode. No entities will be deleted.');
78
48
  }
79
49
  const jsonInput = inputFilename ? (0, file_helpers_1.parseFileAsJsonArray)(inputFilename) : undefined;
80
- const rowsWithId = jsonInput?.filter((item) => item.id);
81
- if (jsonInput && rowsWithId.length < jsonInput.length) {
82
- console.error(`${jsonInput.length - rowsWithId.length} row(s) without an id were skipped.`);
50
+ if (!jsonInput && !id) {
51
+ this.error('You must provide either an ID or a JSON input file with entities to delete.');
83
52
  }
84
- const ids = rowsWithId ? rowsWithId.map((item) => item.id) : positionalIds;
53
+ const ids = jsonInput ? jsonInput.map((item) => item.id) : [id];
85
54
  try {
86
- const response = await deleteEntityByIds(entityName, ids, {
87
- suffix,
88
- apiVersion: apiVersion,
89
- });
55
+ const response = await deleteEntityByIds(entityName, ids);
90
56
  if (IS_DRY_RUN) {
91
- console.error('simulated deletion of entities:');
57
+ this.log('simulated deletion of entities:');
92
58
  }
93
59
  else {
94
- console.error('deleted entities:');
60
+ this.log('deleted entities:');
95
61
  }
96
62
  this.log(JSON.stringify(response, null, 2));
97
- if (response.failed.length > 0) {
98
- console.error(`${response.failed.length} of ${ids.length} deletes failed.`);
99
- process.exitCode = 1;
100
- }
101
63
  }
102
64
  catch (e) {
103
- this.error(`Error deleting entities: ${e.message}`);
65
+ this.error(`Error fetching entity: ${e.message}`);
104
66
  }
105
67
  }
106
68
  }
107
69
  exports.default = DeleteEntity;
108
- async function deleteEntityByIds(entityName, ids, routing = {}) {
109
- const deletedIds = [];
110
- const notFoundIds = [];
111
- const failed = [];
70
+ async function deleteEntityByIds(entityName, ids) {
71
+ const idsDeleted = new Set();
72
+ const idsNotFound = new Set();
73
+ const idsErrored = new Set();
112
74
  const limit = (0, p_limit_1.default)(10);
113
- const deletePromises = ids.map((id) => limit(() => deleteEntityById(entityName, id, routing).then((entity) => {
75
+ const deletePromises = ids.map((id) => limit(() => deleteEntityById(entityName, id).then((entity) => {
114
76
  if (!entity) {
115
- notFoundIds.push(id);
116
- return;
77
+ idsNotFound.add(id);
78
+ return null;
117
79
  }
118
- deletedIds.push(id);
80
+ idsDeleted.add(id);
81
+ return entity;
119
82
  }, (error) => {
120
- if (error.message?.includes('not found')) {
121
- notFoundIds.push(id);
83
+ if (error.message.includes('not found')) {
84
+ idsNotFound.add(id);
122
85
  }
123
86
  else {
124
- failed.push({ id, error: (0, common_1.sdkErrorMessage)(error) });
87
+ idsErrored.add(id);
125
88
  }
89
+ return null;
126
90
  })));
127
91
  await Promise.all(deletePromises);
128
- return { deletedIds, notFoundIds, failed };
92
+ return {
93
+ idsDeleted: Array.from(idsDeleted),
94
+ idsNotFound: Array.from(idsNotFound),
95
+ idsErrored: Array.from(idsErrored),
96
+ };
129
97
  }
130
- async function deleteEntityById(entityName, id, routing = {}) {
98
+ async function deleteEntityById(entityName, id) {
131
99
  const client = new sdk_1.Entities();
132
100
  if (IS_DRY_RUN) {
133
- return client.get({ entityName, id, ignore404: true });
101
+ return client.get({ entityName, id, ignore404: true }).catch(throwIfNot404);
134
102
  }
135
- const { suffix, apiVersion } = routing;
136
- return client.delete({ entityName, id, ignore404: true, suffix, apiVersion });
103
+ return client.delete({ entityName, id, ignore404: true }).catch(throwIfNot404);
104
+ }
105
+ function throwIfNot404(e) {
106
+ const { statusCode } = parseSDKErrorMessage(e);
107
+ if (statusCode === 404) {
108
+ return null;
109
+ }
110
+ throw e;
111
+ }
112
+ function parseSDKErrorMessage(e) {
113
+ const parsed = JSON.parse(e.details);
114
+ return {
115
+ statusCode: parsed.statusCode,
116
+ message: parsed.message,
117
+ };
137
118
  }
@@ -10,16 +10,12 @@ export default class GetEntity extends BaseCommand {
10
10
  skipHydrateRelationships: import("@oclif/core/lib/interfaces").BooleanFlag<boolean>;
11
11
  take: import("@oclif/core/lib/interfaces").OptionFlag<number, import("@oclif/core/lib/interfaces/parser").CustomOptions>;
12
12
  relations: import("@oclif/core/lib/interfaces").OptionFlag<string, import("@oclif/core/lib/interfaces/parser").CustomOptions>;
13
- suffix: import("@oclif/core/lib/interfaces").OptionFlag<string, import("@oclif/core/lib/interfaces/parser").CustomOptions>;
14
- apiVersion: import("@oclif/core/lib/interfaces").OptionFlag<string, import("@oclif/core/lib/interfaces/parser").CustomOptions>;
15
13
  alwaysConfirmEnv: import("@oclif/core/lib/interfaces").OptionFlag<string, import("@oclif/core/lib/interfaces/parser").CustomOptions>;
16
14
  logLevel: import("@oclif/core/lib/interfaces").OptionFlag<string, import("@oclif/core/lib/interfaces/parser").CustomOptions>;
17
15
  };
18
16
  static args: {
19
17
  typePath: import("@oclif/core/lib/interfaces/parser").Arg<string, Record<string, unknown>>;
20
- ids: import("@oclif/core/lib/interfaces/parser").Arg<string, Record<string, unknown>>;
21
18
  };
22
19
  static strict: boolean;
23
- init(): Promise<void>;
24
20
  run(): Promise<void>;
25
21
  }
@@ -6,17 +6,14 @@ const core_1 = require("@oclif/core");
6
6
  const basecommand_1 = require("../../basecommand");
7
7
  const sdk_1 = require("@contrail/sdk");
8
8
  const login_1 = require("../../auth/login");
9
- const common_1 = require("../../common");
10
9
  const types_1 = require("../../api/types");
11
10
  const propertySpecifications_1 = require("../../helpers/propertySpecifications/propertySpecifications");
12
11
  const batchFetch_1 = require("../../helpers/entities/batchFetch");
13
12
  let SHOULD_USE_PAGINATED_FIND = false;
14
13
  let MAX_NUMBER_OF_ENTITIES_TO_FETCH = undefined;
15
14
  class GetEntity extends basecommand_1.BaseCommand {
16
- static description = 'Get an entity';
15
+ static description = '(BETA) Get an entity';
17
16
  static examples = [
18
- 'contrail entities get color 123',
19
- 'contrail entities get color id1 id2 id3',
20
17
  'contrail entities get color -- id=123',
21
18
  'contrail entities get loader-processes -- createdOn=2025-09-15..2025-09-16',
22
19
  'contrail entities get orders -- updatedAt=2025-09-15T04:00:00Z..',
@@ -62,56 +59,28 @@ class GetEntity extends basecommand_1.BaseCommand {
62
59
  description: 'Comma-separated list of relations to include in the output',
63
60
  required: false,
64
61
  }),
65
- suffix: core_1.Flags.string({
66
- description: 'Append a sub-route to the entity endpoint (e.g. --suffix=synchronous targets /<entities>/synchronous)',
67
- required: false,
68
- }),
69
- apiVersion: core_1.Flags.string({
70
- description: 'Api-Version header to send; selects the V1 or V2 variant of the endpoint',
71
- options: ['1', '2'],
72
- required: false,
73
- }),
74
62
  };
75
63
  static args = {
76
64
  typePath: core_1.Args.string({
77
65
  description: 'The name of the entity type to fetch',
78
66
  required: true,
79
67
  }),
80
- ids: core_1.Args.string({
81
- description: 'One or more entity ids; shorthand for the id/ids criteria',
82
- required: false,
83
- }),
84
68
  };
85
69
  static strict = false;
86
- async init() {
87
- (0, common_1.routeConsoleLogToStderr)();
88
- await super.init();
89
- }
90
70
  async run() {
71
+ this.log('🚨 This command is in BETA and may change or be removed at any time.');
91
72
  await (0, login_1.authUser)();
92
73
  const { args, flags, argv } = await this.parse(GetEntity);
93
74
  const { typePath } = args;
94
- const { outputFile, paginated: shouldUsePaginatedFind, propertySlugs, relations: relationString, skip, skipHydrateRelationships, suffix, apiVersion, take, } = flags;
75
+ const { outputFile, paginated: shouldUsePaginatedFind, propertySlugs, relations: relationString, skip, skipHydrateRelationships, take, } = flags;
95
76
  SHOULD_USE_PAGINATED_FIND = shouldUsePaginatedFind;
96
77
  MAX_NUMBER_OF_ENTITIES_TO_FETCH = take;
97
78
  if (MAX_NUMBER_OF_ENTITIES_TO_FETCH)
98
- console.error(`Will limit output to ${MAX_NUMBER_OF_ENTITIES_TO_FETCH} entities.`);
99
- const { ids: positionalIds, specs } = (0, propertySpecifications_1.partitionIdsAndSpecs)(argv.slice(1));
100
- const propertySpecBySlug = (0, propertySpecifications_1.parsePropertySpecificationsIntoMap)(specs);
101
- if (positionalIds.length > 0) {
102
- if (propertySpecBySlug.has('id') || propertySpecBySlug.has('ids')) {
103
- this.error('Pass ids positionally or as -- id=/ids= criteria, not both.');
104
- }
105
- if (propertySpecBySlug.size > 0) {
106
- this.error('Positional ids cannot be combined with other -- criteria. Use -- ids= alongside the other criteria instead.');
107
- }
108
- if (positionalIds.length === 1) {
109
- propertySpecBySlug.set('id', positionalIds[0]);
110
- }
111
- else {
112
- propertySpecBySlug.set('ids', positionalIds);
113
- }
114
- }
79
+ console.log(`Will limit output to ${MAX_NUMBER_OF_ENTITIES_TO_FETCH} entities.`);
80
+ const propertySpecificationArgs = argv
81
+ .slice(1, argv.length)
82
+ .filter(propertySpecifications_1.isValidPropertySpecification);
83
+ const propertySpecBySlug = (0, propertySpecifications_1.parsePropertySpecificationsIntoMap)(propertySpecificationArgs);
115
84
  const relations = relationString
116
85
  ? relationString
117
86
  .split(',')
@@ -132,8 +101,6 @@ class GetEntity extends basecommand_1.BaseCommand {
132
101
  criteria: convertPropertySpecIntoCriteria(propertySpecBySlug),
133
102
  skipHydrateRelationships,
134
103
  skip,
135
- suffix,
136
- apiVersion: apiVersion,
137
104
  relations,
138
105
  propertySlugs: propertySlugsArray,
139
106
  });
@@ -148,7 +115,7 @@ class GetEntity extends basecommand_1.BaseCommand {
148
115
  }
149
116
  writer.write('\n]\n');
150
117
  if (outputFile)
151
- console.error(`Output saved to ${outputFile}`);
118
+ this.log(`Output saved to ${outputFile}`);
152
119
  }
153
120
  else {
154
121
  const response = await getEntityByTypePath(typePath, propertySpecBySlug, {
@@ -156,16 +123,11 @@ class GetEntity extends basecommand_1.BaseCommand {
156
123
  relations,
157
124
  propertySlugs: propertySlugsArray,
158
125
  skip,
159
- suffix,
160
- apiVersion: apiVersion,
161
126
  take,
162
127
  });
163
- if (response === null) {
164
- this.error(`Entity not found: ${propertySpecBySlug.get('id')}`, { exit: 1 });
165
- }
166
128
  if (outputFile) {
167
129
  fs_1.default.writeFileSync(outputFile, JSON.stringify(response, null, 2));
168
- console.error(`Output saved to ${outputFile}`);
130
+ this.log(`Output saved to ${outputFile}`);
169
131
  }
170
132
  else {
171
133
  this.log(JSON.stringify(response, null, 2));
@@ -173,16 +135,13 @@ class GetEntity extends basecommand_1.BaseCommand {
173
135
  }
174
136
  }
175
137
  catch (e) {
176
- if (e.message?.startsWith('Entity not found:')) {
177
- throw e;
178
- }
179
138
  this.error(`Error fetching entity: ${e.message}`);
180
139
  }
181
140
  }
182
141
  }
183
142
  exports.default = GetEntity;
184
143
  async function getEntityByTypePath(typePath, propertySpec, options = {}) {
185
- const { propertySlugs, relations, skipHydrateRelationships, skip, suffix, apiVersion, take } = options;
144
+ const { propertySlugs, relations, skipHydrateRelationships, skip, take } = options;
186
145
  const id = propertySpec?.get('id')?.toString() || undefined;
187
146
  const criteria = convertPropertySpecIntoCriteria(propertySpec || new Map());
188
147
  const { root: entityName } = (0, types_1.parseTypePath)(typePath);
@@ -191,15 +150,11 @@ async function getEntityByTypePath(typePath, propertySpec, options = {}) {
191
150
  }
192
151
  return find(entityName, {
193
152
  id,
194
- // a missing id returns null (no retries); the command turns it into a clean not-found error
195
- ignore404: id !== undefined,
196
153
  skipHydrateRelationships,
197
154
  relations,
198
155
  propertySlugs,
199
156
  criteria,
200
157
  skip,
201
- suffix,
202
- apiVersion,
203
158
  take,
204
159
  });
205
160
  }
@@ -212,24 +167,19 @@ function convertPropertySpecIntoCriteria(propertySpec) {
212
167
  }
213
168
  async function find(entityName, options = {}) {
214
169
  const client = new sdk_1.Entities();
215
- const { criteria, id, ignore404, propertySlugs, skipHydrateRelationships, relations, skip, suffix, apiVersion, take, } = options;
170
+ const { criteria, id, propertySlugs, skipHydrateRelationships, relations, skip, take } = options;
216
171
  const queryOptions = {
217
172
  entityName,
218
- ignore404,
219
173
  skipHydrateRelationships,
220
174
  relations,
221
175
  skip,
222
- suffix,
223
- apiVersion,
224
176
  take,
225
177
  };
226
178
  if (propertySlugs && propertySlugs.length > 0) {
227
179
  queryOptions.customParams = { propertySlugs: propertySlugs.join(',') };
228
180
  }
229
181
  const payload = id ? { id, ...queryOptions } : { criteria, ...queryOptions };
230
- // a suffix names a specific sub-route and an id names one entity; both always go
231
- // through the plain client (batch-fetch only understands criteria)
232
- if ((0, batchFetch_1.canBatchFetchEntity)(entityName) && !suffix && !id) {
182
+ if ((0, batchFetch_1.canBatchFetchEntity)(entityName)) {
233
183
  return (0, batchFetch_1.batchFetch)(entityName, payload);
234
184
  }
235
185
  else {
@@ -245,8 +195,7 @@ async function* streamPaginatedFind(typePath, options = {}) {
245
195
  const opts = {
246
196
  ...options,
247
197
  entityName,
248
- // paginated reads require the V2 response shape unless overridden
249
- apiVersion: options.apiVersion ?? sdk_1.API_VERSION.V2,
198
+ apiVersion: sdk_1.API_VERSION.V2,
250
199
  nextPageKey,
251
200
  };
252
201
  if (options.propertySlugs?.length > 0) {
@@ -263,7 +212,7 @@ async function* streamPaginatedFind(typePath, options = {}) {
263
212
  if (MAX_NUMBER_OF_ENTITIES_TO_FETCH && count >= MAX_NUMBER_OF_ENTITIES_TO_FETCH)
264
213
  return;
265
214
  }
266
- console.error(`Fetched ${count} entities`);
215
+ console.log(`Fetched ${count} entities`);
267
216
  if (!nextPageKey || results.length === 0)
268
217
  return;
269
218
  }
@@ -6,27 +6,14 @@ export default class UpdateEntity extends BaseCommand {
6
6
  skipHydrateRelationships: import("@oclif/core/lib/interfaces").BooleanFlag<boolean>;
7
7
  dryRun: import("@oclif/core/lib/interfaces").BooleanFlag<boolean>;
8
8
  inputFile: import("@oclif/core/lib/interfaces").OptionFlag<string, import("@oclif/core/lib/interfaces/parser").CustomOptions>;
9
- suffix: import("@oclif/core/lib/interfaces").OptionFlag<string, import("@oclif/core/lib/interfaces/parser").CustomOptions>;
10
- apiVersion: import("@oclif/core/lib/interfaces").OptionFlag<string, import("@oclif/core/lib/interfaces/parser").CustomOptions>;
9
+ force: import("@oclif/core/lib/interfaces").BooleanFlag<boolean>;
11
10
  alwaysConfirmEnv: import("@oclif/core/lib/interfaces").OptionFlag<string, import("@oclif/core/lib/interfaces/parser").CustomOptions>;
12
11
  logLevel: import("@oclif/core/lib/interfaces").OptionFlag<string, import("@oclif/core/lib/interfaces/parser").CustomOptions>;
13
12
  };
14
13
  static args: {
15
14
  entityName: import("@oclif/core/lib/interfaces/parser").Arg<string, Record<string, unknown>>;
16
- ids: import("@oclif/core/lib/interfaces/parser").Arg<string, Record<string, unknown>>;
15
+ id: import("@oclif/core/lib/interfaces/parser").Arg<string, Record<string, unknown>>;
17
16
  };
18
17
  static strict: boolean;
19
- init(): Promise<void>;
20
18
  run(): Promise<void>;
21
19
  }
22
- export type UpdateSummary = {
23
- updated: any[];
24
- failed: {
25
- id: string;
26
- error: string;
27
- }[];
28
- skipped: number;
29
- };
30
- export declare function summarizeSettledUpdates(inputs: {
31
- id: string;
32
- }[], settled: PromiseSettledResult<any>[], skipped: number): UpdateSummary;
@@ -1,48 +1,41 @@
1
1
  "use strict";
2
2
  Object.defineProperty(exports, "__esModule", { value: true });
3
- exports.summarizeSettledUpdates = void 0;
4
3
  const tslib_1 = require("tslib");
5
4
  const p_limit_1 = tslib_1.__importDefault(require("p-limit"));
6
5
  const core_1 = require("@oclif/core");
7
6
  const basecommand_1 = require("../../basecommand");
8
7
  const sdk_1 = require("@contrail/sdk");
9
8
  const login_1 = require("../../auth/login");
10
- const common_1 = require("../../common");
11
9
  const propertySpecifications_1 = require("../../helpers/propertySpecifications/propertySpecifications");
12
10
  const file_helpers_1 = require("../../helpers/file-helpers");
13
11
  class UpdateEntity extends basecommand_1.BaseCommand {
14
- static description = 'Update an entity';
12
+ static description = '(BETA) Update an entity';
15
13
  static examples = [
16
14
  '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',
18
15
  'contrail entities update color 123 -- description= notes=\'""\' # Unset description, set notes to empty string',
19
16
  ];
20
17
  static flags = {
21
18
  ...basecommand_1.BaseCommand.baseFlags,
22
19
  skipHydrateRelationships: core_1.Flags.boolean({
23
- char: 'S',
20
+ char: 's',
24
21
  description: 'Skip hydrating relationships when updating the entity',
25
22
  required: false,
26
23
  default: false,
27
24
  }),
28
25
  dryRun: core_1.Flags.boolean({
29
26
  char: 'd',
30
- description: 'If true, does not update the entities but simulates the update',
27
+ description: 'If true, does not create the entity but simulates the creation',
31
28
  required: false,
32
29
  default: false,
33
30
  }),
34
31
  inputFile: core_1.Flags.string({
35
32
  char: 'i',
36
- description: 'A file with a JSON array of {id, ...} objects; each object is one entity to update.',
33
+ description: 'File containing properties to update the entity (optional)',
37
34
  required: false,
38
35
  }),
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'],
36
+ force: core_1.Flags.boolean({
37
+ char: 'F',
38
+ description: 'Force update without validation. Internal use only',
46
39
  required: false,
47
40
  }),
48
41
  };
@@ -51,40 +44,33 @@ class UpdateEntity extends basecommand_1.BaseCommand {
51
44
  description: 'The name of the entity type to update',
52
45
  required: true,
53
46
  }),
54
- ids: core_1.Args.string({
55
- description: 'One or more entity ids to update',
47
+ id: core_1.Args.string({
48
+ description: 'The unique identifier of the entity',
56
49
  required: false,
57
50
  }),
58
51
  };
59
52
  static strict = false;
60
- async init() {
61
- (0, common_1.routeConsoleLogToStderr)();
62
- await super.init();
63
- }
64
53
  async run() {
54
+ this.log('🚨 This command is in BETA and may change or be removed at any time.');
65
55
  await (0, login_1.authUser)();
66
56
  const { args, argv } = await this.parse(UpdateEntity);
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');
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.');
82
63
  }
83
64
  const entitiesToUpdate = inputFilename
84
65
  ? (0, file_helpers_1.parseFileAsJsonArray)(inputFilename)
85
- : positionalIds.map((id) => ({ id }));
86
- const skipped = entitiesToUpdate.filter(({ id }) => !id).length;
66
+ : [{ id: specifiedId }];
67
+ const results = {
68
+ idsSuccessfullyUpdated: new Set(),
69
+ idsFailedToUpdate: new Set(),
70
+ numEntriesSkipped: entitiesToUpdate.filter(({ id }) => !id).length,
71
+ };
87
72
  const entitiesWithId = entitiesToUpdate.filter(({ id }) => id);
73
+ propertySpec.delete('id'); // Remove 'id' from the property spec if it exists
88
74
  // will be applied to all entities
89
75
  const fixedValues = [...propertySpec.entries()].reduce((acc, [key, value]) => {
90
76
  acc[key] = value;
@@ -93,61 +79,39 @@ class UpdateEntity extends basecommand_1.BaseCommand {
93
79
  async function updateEntity(entity) {
94
80
  const newEntityState = { ...entity, ...fixedValues };
95
81
  const id = entity.id;
96
- return isDryRun
82
+ const promise = isDryRun
97
83
  ? mockUpdateById(entityName, id, newEntityState, { skipHydrateRelationships })
98
- : updateEntityById(entityName, id, newEntityState, {
99
- skipHydrateRelationships,
100
- suffix,
101
- apiVersion: apiVersion,
102
- });
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;
103
93
  }
104
94
  try {
105
95
  const limit = (0, p_limit_1.default)(20);
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
- }
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}`);
116
104
  }
117
105
  catch (e) {
118
- this.error(`Error updating entities: ${e.message}`);
106
+ this.error(`Error fetching entity: ${e.message}`);
119
107
  }
120
108
  }
121
109
  }
122
110
  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;
140
111
  async function updateEntityById(entityName, id, changes, options = {}) {
141
112
  const client = new sdk_1.Entities();
142
- const { skipHydrateRelationships, suffix, apiVersion } = options;
143
- return client.update({
144
- entityName,
145
- id,
146
- object: changes,
147
- skipHydrateRelationships,
148
- suffix,
149
- apiVersion,
150
- });
113
+ const { skipHydrateRelationships, force } = options;
114
+ return client.update({ entityName, id, object: changes, skipHydrateRelationships });
151
115
  }
152
116
  async function mockUpdateById(entityName, id, changes, options = {}) {
153
117
  const client = new sdk_1.Entities();