@contrail/cli 3.6.0-alpha.f45f126 → 3.7.0-alpha.1c66a91

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 (105) hide show
  1. package/README.md +207 -3
  2. package/dist/api/types.d.ts +35 -0
  3. package/dist/api/types.js +49 -1
  4. package/dist/auth/login.d.ts +1 -1
  5. package/dist/auth/login.js +46 -29
  6. package/dist/auth/login.spec.js +31 -15
  7. package/dist/auth/sign-in-error.d.ts +7 -0
  8. package/dist/auth/sign-in-error.js +24 -0
  9. package/dist/auth/sign-in-error.spec.d.ts +1 -0
  10. package/dist/auth/sign-in-error.spec.js +22 -0
  11. package/dist/auth/sso.d.ts +5 -3
  12. package/dist/auth/sso.js +34 -18
  13. package/dist/auth/sso.spec.js +63 -10
  14. package/dist/basecommand.d.ts +3 -0
  15. package/dist/basecommand.js +10 -3
  16. package/dist/commands/app/getApiKey.js +2 -2
  17. package/dist/commands/app/publish.js +1 -1
  18. package/dist/commands/app/version/prerelease.d.ts +11 -0
  19. package/dist/commands/app/version/prerelease.js +32 -0
  20. package/dist/commands/entities/create.d.ts +49 -0
  21. package/dist/commands/entities/create.js +618 -0
  22. package/dist/commands/entities/create.spec.d.ts +1 -0
  23. package/dist/commands/entities/create.spec.js +581 -0
  24. package/dist/commands/entities/delete.d.ts +20 -0
  25. package/dist/commands/entities/delete.js +146 -0
  26. package/dist/commands/entities/get.d.ts +25 -0
  27. package/dist/commands/entities/get.js +298 -0
  28. package/dist/commands/entities/grammar.spec.d.ts +1 -0
  29. package/dist/commands/entities/grammar.spec.js +79 -0
  30. package/dist/commands/entities/output.spec.d.ts +1 -0
  31. package/dist/commands/entities/output.spec.js +72 -0
  32. package/dist/commands/entities/update.d.ts +32 -0
  33. package/dist/commands/entities/update.js +212 -0
  34. package/dist/commands/login.js +1 -1
  35. package/dist/commands/webhooks/delete.js +2 -3
  36. package/dist/common.d.ts +10 -1
  37. package/dist/common.js +37 -1
  38. package/dist/common.spec.d.ts +1 -0
  39. package/dist/common.spec.js +40 -0
  40. package/dist/helpers/app/app-config-validators.js +4 -4
  41. package/dist/helpers/app/app-config-validators.spec.js +36 -0
  42. package/dist/helpers/app/app-deployer.d.ts +1 -0
  43. package/dist/helpers/app/app-deployer.js +34 -0
  44. package/dist/helpers/app/upgrade-version.d.ts +3 -1
  45. package/dist/helpers/app/upgrade-version.js +7 -8
  46. package/dist/helpers/app/upgrade-version.spec.js +15 -0
  47. package/dist/helpers/config/config.d.ts +3 -3
  48. package/dist/helpers/config/config.js +3 -3
  49. package/dist/helpers/entities/assortment-items.d.ts +11 -0
  50. package/dist/helpers/entities/assortment-items.js +76 -0
  51. package/dist/helpers/entities/batchFetch.d.ts +11 -0
  52. package/dist/helpers/entities/batchFetch.js +50 -0
  53. package/dist/helpers/entities/index.d.ts +3 -0
  54. package/dist/helpers/entities/index.js +6 -0
  55. package/dist/helpers/entities/items.d.ts +6 -0
  56. package/dist/helpers/entities/items.js +60 -0
  57. package/dist/helpers/entities/items.spec.d.ts +1 -0
  58. package/dist/helpers/entities/items.spec.js +19 -0
  59. package/dist/helpers/entities/project-items.d.ts +2 -0
  60. package/dist/helpers/entities/project-items.js +44 -0
  61. package/dist/helpers/file-helpers.d.ts +1 -0
  62. package/dist/helpers/file-helpers.js +20 -3
  63. package/dist/helpers/propertySpecifications/dateRanges.d.ts +34 -0
  64. package/dist/helpers/propertySpecifications/dateRanges.js +91 -0
  65. package/dist/helpers/propertySpecifications/dateRanges.spec.d.ts +1 -0
  66. package/dist/helpers/propertySpecifications/dateRanges.spec.js +97 -0
  67. package/dist/helpers/propertySpecifications/propertySpecifications.d.ts +39 -0
  68. package/dist/helpers/propertySpecifications/propertySpecifications.js +102 -0
  69. package/dist/helpers/propertySpecifications/propertySpecifications.spec.d.ts +1 -0
  70. package/dist/helpers/propertySpecifications/propertySpecifications.spec.js +387 -0
  71. package/dist/helpers/propertySpecifications/propertyValues.d.ts +31 -0
  72. package/dist/helpers/propertySpecifications/propertyValues.js +132 -0
  73. package/dist/helpers/propertySpecifications/propertyValues.spec.d.ts +1 -0
  74. package/dist/helpers/propertySpecifications/propertyValues.spec.js +156 -0
  75. package/dist/logger.js +4 -1
  76. package/dist/logger.spec.d.ts +1 -0
  77. package/dist/logger.spec.js +12 -0
  78. package/node_modules/@contrail/entity-compare/package.json +6 -3
  79. package/node_modules/@contrail/loader/lib/common/conditional-columns.js +1 -1
  80. package/node_modules/@contrail/loader/lib/constants.d.ts +0 -8
  81. package/node_modules/@contrail/loader/lib/constants.js +1 -9
  82. package/node_modules/@contrail/loader/lib/entities-v2/linesheet-v2/item-processor.d.ts +0 -4
  83. package/node_modules/@contrail/loader/lib/entities-v2/linesheet-v2/item-processor.js +0 -57
  84. package/node_modules/@contrail/loader/lib/entities-v2/linesheet-v2/item-processor.spec.js +34 -492
  85. package/node_modules/@contrail/loader/lib/pipeline/validate.js +52 -2
  86. package/node_modules/@contrail/loader/lib/pipeline/validate.spec.js +85 -0
  87. package/node_modules/@contrail/loader/package.json +2 -2
  88. package/node_modules/@contrail/sdk/.github/workflows/publish-to-npm.yml +1 -4
  89. package/node_modules/@contrail/sdk/lib/auth/login.js +1 -1
  90. package/node_modules/@contrail/sdk/lib/config/config.d.ts +3 -0
  91. package/node_modules/@contrail/sdk/lib/config/config.js +13 -7
  92. package/node_modules/@contrail/sdk/lib/core/request.js +6 -2
  93. package/node_modules/@contrail/sdk/lib/entities/entities.client.d.ts +2 -0
  94. package/node_modules/@contrail/sdk/lib/entities/entities.client.js +3 -1
  95. package/node_modules/@contrail/sdk/lib/entities/entity.resource.registry.js +1 -0
  96. package/node_modules/@contrail/sdk/lib/image-search/image-search.d.ts +34 -0
  97. package/node_modules/@contrail/sdk/lib/image-search/image-search.js +42 -0
  98. package/node_modules/@contrail/sdk/lib/image-search/index.d.ts +1 -0
  99. package/node_modules/@contrail/sdk/lib/image-search/index.js +17 -0
  100. package/node_modules/@contrail/sdk/lib/index.d.ts +1 -0
  101. package/node_modules/@contrail/sdk/lib/index.js +1 -0
  102. package/node_modules/@contrail/sdk/package.json +1 -1
  103. package/node_modules/@contrail/sdk/scripts/replicate-bug.js +69 -0
  104. package/oclif.manifest.json +492 -2
  105. package/package.json +6 -12
@@ -0,0 +1,146 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ const tslib_1 = require("tslib");
4
+ const core_1 = require("@oclif/core");
5
+ const p_limit_1 = tslib_1.__importDefault(require("p-limit"));
6
+ const basecommand_1 = require("../../basecommand");
7
+ const sdk_1 = require("@contrail/sdk");
8
+ const login_1 = require("../../auth/login");
9
+ const common_1 = require("../../common");
10
+ const file_helpers_1 = require("../../helpers/file-helpers");
11
+ let IS_DRY_RUN = false;
12
+ 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
+ ];
19
+ static flags = {
20
+ ...basecommand_1.BaseCommand.baseFlags,
21
+ dryRun: core_1.Flags.boolean({
22
+ char: 'd',
23
+ description: 'If true, does not delete the entities but simulates the deletion',
24
+ required: false,
25
+ default: false,
26
+ }),
27
+ inputFile: core_1.Flags.string({
28
+ 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.",
30
+ required: false,
31
+ multiple: false,
32
+ }),
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'],
40
+ required: false,
41
+ }),
42
+ };
43
+ static args = {
44
+ entityName: core_1.Args.string({
45
+ description: 'The name of the entity type to delete (type paths are not supported)',
46
+ required: true,
47
+ }),
48
+ ids: core_1.Args.string({
49
+ description: 'One or more entity ids to delete',
50
+ required: false,
51
+ }),
52
+ };
53
+ static strict = false;
54
+ async init() {
55
+ (0, common_1.routeConsoleLogToStderr)();
56
+ await super.init();
57
+ }
58
+ async run() {
59
+ await (0, login_1.authUser)();
60
+ const { args, flags, argv } = await this.parse(DeleteEntity);
61
+ const { entityName } = args;
62
+ const idParsedAsFlag = (0, common_1.findIdParsedAsFlag)(process.argv, 'il');
63
+ if (idParsedAsFlag) {
64
+ this.error(`${idParsedAsFlag} starts with a hyphen, so it is read as flags rather than an id. Pass it after -- instead, or use an input file (-i).`);
65
+ }
66
+ const { inputFile: inputFilename, suffix, apiVersion } = flags;
67
+ if (flags.dryRun) {
68
+ IS_DRY_RUN = true;
69
+ console.error('Running in dry run mode. No entities will be deleted.');
70
+ }
71
+ if (entityName.includes(':')) {
72
+ this.error(`delete takes an entity name, not a type path. Use: contrail entities delete ${entityName.split(':')[0]} <ID...>`);
73
+ }
74
+ const tokens = argv.slice(1);
75
+ const valueTokens = tokens.filter((token) => token.includes('='));
76
+ if (valueTokens.length > 0) {
77
+ this.error(`delete takes no -- values (got: ${valueTokens.join(' ')}); pass ids positionally or use an input file (-i).`);
78
+ }
79
+ const positionalIds = tokens;
80
+ if (inputFilename && positionalIds.length > 0) {
81
+ this.error('You cannot use --inputFile and positional ids together. Please specify one or the other.');
82
+ }
83
+ if (!inputFilename && positionalIds.length === 0) {
84
+ this.error('You must provide one or more ids or an input file (-i) of entities to delete.');
85
+ }
86
+ const jsonInput = inputFilename ? (0, file_helpers_1.parseFileAsJsonArray)(inputFilename) : undefined;
87
+ // the file may hold bare ids or {id, ...} rows; delete only ever needs the id
88
+ const idsFromFile = jsonInput?.map((row) => (typeof row === 'string' ? row : row?.id));
89
+ const idsFromFileWithValue = idsFromFile?.filter(Boolean);
90
+ if (jsonInput && idsFromFileWithValue.length < jsonInput.length) {
91
+ console.error(`${jsonInput.length - idsFromFileWithValue.length} row(s) without an id were skipped.`);
92
+ }
93
+ const ids = idsFromFileWithValue ?? positionalIds;
94
+ try {
95
+ const response = await deleteEntityByIds(entityName, ids, {
96
+ suffix,
97
+ apiVersion: apiVersion,
98
+ });
99
+ if (IS_DRY_RUN) {
100
+ console.error('simulated deletion of entities:');
101
+ }
102
+ else {
103
+ console.error('deleted entities:');
104
+ }
105
+ this.log(JSON.stringify(response, null, 2));
106
+ if (response.failed.length > 0) {
107
+ console.error(`${response.failed.length} of ${ids.length} deletes failed.`);
108
+ process.exitCode = 1;
109
+ }
110
+ }
111
+ catch (e) {
112
+ this.error(`Error deleting entities: ${e.message}`);
113
+ }
114
+ }
115
+ }
116
+ exports.default = DeleteEntity;
117
+ async function deleteEntityByIds(entityName, ids, routing = {}) {
118
+ const deletedIds = [];
119
+ const notFoundIds = [];
120
+ const failed = [];
121
+ const limit = (0, p_limit_1.default)(10);
122
+ const deletePromises = ids.map((id) => limit(() => deleteEntityById(entityName, id, routing).then((entity) => {
123
+ if (!entity) {
124
+ notFoundIds.push(id);
125
+ return;
126
+ }
127
+ deletedIds.push(id);
128
+ }, (error) => {
129
+ if (error.message?.includes('not found')) {
130
+ notFoundIds.push(id);
131
+ }
132
+ else {
133
+ failed.push({ id, error: (0, common_1.sdkErrorMessage)(error) });
134
+ }
135
+ })));
136
+ await Promise.all(deletePromises);
137
+ return { deletedIds, notFoundIds, failed };
138
+ }
139
+ async function deleteEntityById(entityName, id, routing = {}) {
140
+ const client = new sdk_1.Entities();
141
+ if (IS_DRY_RUN) {
142
+ return client.get({ entityName, id, ignore404: true });
143
+ }
144
+ const { suffix, apiVersion } = routing;
145
+ return client.delete({ entityName, id, ignore404: true, suffix, apiVersion });
146
+ }
@@ -0,0 +1,25 @@
1
+ import { BaseCommand } from '../../basecommand';
2
+ export default class GetEntity extends BaseCommand {
3
+ static description: string;
4
+ static examples: string[];
5
+ static flags: {
6
+ outputFile: import("@oclif/core/lib/interfaces").OptionFlag<string, import("@oclif/core/lib/interfaces/parser").CustomOptions>;
7
+ propertySlugs: import("@oclif/core/lib/interfaces").OptionFlag<string, import("@oclif/core/lib/interfaces/parser").CustomOptions>;
8
+ paginated: import("@oclif/core/lib/interfaces").BooleanFlag<boolean>;
9
+ skip: import("@oclif/core/lib/interfaces").OptionFlag<number, import("@oclif/core/lib/interfaces/parser").CustomOptions>;
10
+ skipHydrateRelationships: import("@oclif/core/lib/interfaces").BooleanFlag<boolean>;
11
+ take: import("@oclif/core/lib/interfaces").OptionFlag<number, import("@oclif/core/lib/interfaces/parser").CustomOptions>;
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
+ alwaysConfirmEnv: import("@oclif/core/lib/interfaces").OptionFlag<string, import("@oclif/core/lib/interfaces/parser").CustomOptions>;
16
+ logLevel: import("@oclif/core/lib/interfaces").OptionFlag<string, import("@oclif/core/lib/interfaces/parser").CustomOptions>;
17
+ };
18
+ static args: {
19
+ entityName: 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
+ };
22
+ static strict: boolean;
23
+ init(): Promise<void>;
24
+ run(): Promise<void>;
25
+ }
@@ -0,0 +1,298 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ const tslib_1 = require("tslib");
4
+ const fs_1 = tslib_1.__importDefault(require("fs"));
5
+ const core_1 = require("@oclif/core");
6
+ const types_1 = require("@contrail/types");
7
+ const types_2 = require("../../api/types");
8
+ const propertyValues_1 = require("../../helpers/propertySpecifications/propertyValues");
9
+ const basecommand_1 = require("../../basecommand");
10
+ const sdk_1 = require("@contrail/sdk");
11
+ const login_1 = require("../../auth/login");
12
+ const common_1 = require("../../common");
13
+ const dateRanges_1 = require("../../helpers/propertySpecifications/dateRanges");
14
+ const propertySpecifications_1 = require("../../helpers/propertySpecifications/propertySpecifications");
15
+ const batchFetch_1 = require("../../helpers/entities/batchFetch");
16
+ let SHOULD_USE_PAGINATED_FIND = false;
17
+ let MAX_NUMBER_OF_ENTITIES_TO_FETCH = undefined;
18
+ class GetEntity extends basecommand_1.BaseCommand {
19
+ static description = 'Get an entity';
20
+ static examples = [
21
+ 'contrail entities get color 123',
22
+ 'contrail entities get color id1 id2 id3',
23
+ 'contrail entities get color -- id=123',
24
+ 'contrail entities get loader-process -- createdOn=2026-09-01..2026-09-11',
25
+ 'contrail entities get loader-process -- createdOn=2026-09-05..',
26
+ 'contrail entities get loader-process -- createdOn=..2026-09-05',
27
+ ];
28
+ static flags = {
29
+ ...basecommand_1.BaseCommand.baseFlags,
30
+ outputFile: core_1.Flags.string({
31
+ char: 'o',
32
+ description: 'File to save the output (optional)',
33
+ required: false,
34
+ }),
35
+ propertySlugs: core_1.Flags.string({
36
+ char: 'p',
37
+ description: 'Comma-separated list of property slugs to include in the output. Only some entity types support this; the rest return full records.',
38
+ required: false,
39
+ }),
40
+ paginated: core_1.Flags.boolean({
41
+ char: 'P',
42
+ description: 'If true, fetches all entities in a paginated manner',
43
+ required: false,
44
+ default: false,
45
+ }),
46
+ skip: core_1.Flags.integer({
47
+ char: 's',
48
+ description: 'Number of entities to skip',
49
+ required: false,
50
+ }),
51
+ skipHydrateRelationships: core_1.Flags.boolean({
52
+ char: 'S',
53
+ description: 'Skip hydrating relationships when fetching the entity',
54
+ required: false,
55
+ default: false,
56
+ }),
57
+ take: core_1.Flags.integer({
58
+ char: 't',
59
+ description: 'Number of entities to fetch in a single request (default is 100)',
60
+ required: false,
61
+ default: MAX_NUMBER_OF_ENTITIES_TO_FETCH,
62
+ }),
63
+ relations: core_1.Flags.string({
64
+ char: 'r',
65
+ description: 'Comma-separated list of relations to include in the output',
66
+ required: false,
67
+ }),
68
+ suffix: core_1.Flags.string({
69
+ description: 'Append a sub-route to the entity endpoint (e.g. --suffix=synchronous targets /<entities>/synchronous)',
70
+ required: false,
71
+ }),
72
+ apiVersion: core_1.Flags.string({
73
+ description: 'Api-Version header to send; selects the V1 or V2 variant of the endpoint',
74
+ options: ['1', '2'],
75
+ required: false,
76
+ }),
77
+ };
78
+ static args = {
79
+ entityName: core_1.Args.string({
80
+ description: 'The name of the entity type to fetch (type paths are not supported)',
81
+ required: true,
82
+ }),
83
+ ids: core_1.Args.string({
84
+ description: 'One or more entity ids; shorthand for the id/ids criteria',
85
+ required: false,
86
+ }),
87
+ };
88
+ static strict = false;
89
+ async init() {
90
+ (0, common_1.routeConsoleLogToStderr)();
91
+ await super.init();
92
+ }
93
+ async run() {
94
+ await (0, login_1.authUser)();
95
+ const { args, flags, argv } = await this.parse(GetEntity);
96
+ const { entityName } = args;
97
+ const idParsedAsFlag = (0, common_1.findIdParsedAsFlag)(process.argv, 'loprst');
98
+ if (idParsedAsFlag) {
99
+ this.error(`${idParsedAsFlag} starts with a hyphen, so it is read as flags rather than an id. Pass it after -- instead, or use an input file (-i).`);
100
+ }
101
+ if (entityName.includes(':')) {
102
+ this.error(`get takes an entity name, not a type path. Use: contrail entities get ${entityName.split(':')[0]} [ID...]`);
103
+ }
104
+ const { outputFile, paginated: shouldUsePaginatedFind, propertySlugs, relations: relationString, skip, skipHydrateRelationships, suffix, apiVersion, take, } = flags;
105
+ SHOULD_USE_PAGINATED_FIND = shouldUsePaginatedFind;
106
+ MAX_NUMBER_OF_ENTITIES_TO_FETCH = take;
107
+ if (MAX_NUMBER_OF_ENTITIES_TO_FETCH)
108
+ console.error(`Will limit output to ${MAX_NUMBER_OF_ENTITIES_TO_FETCH} entities.`);
109
+ const { ids: positionalIds, specs } = (0, propertySpecifications_1.partitionIdsAndSpecs)(argv.slice(1));
110
+ const propertySpecBySlug = (0, propertySpecifications_1.parsePropertySpecificationsIntoMap)(specs);
111
+ if (positionalIds.length > 0) {
112
+ if (propertySpecBySlug.has('id') || propertySpecBySlug.has('ids')) {
113
+ this.error('Pass ids positionally or as -- id=/ids= criteria, not both.');
114
+ }
115
+ if (propertySpecBySlug.size > 0) {
116
+ this.error('Positional ids cannot be combined with other -- criteria. Use -- ids= alongside the other criteria instead.');
117
+ }
118
+ if (positionalIds.length === 1) {
119
+ propertySpecBySlug.set('id', positionalIds[0]);
120
+ }
121
+ else {
122
+ propertySpecBySlug.set('ids', positionalIds);
123
+ }
124
+ }
125
+ const relations = relationString
126
+ ? relationString
127
+ .split(',')
128
+ .map((r) => r.trim())
129
+ .filter(Boolean)
130
+ : [];
131
+ const propertySlugsArray = propertySlugs
132
+ ? propertySlugs
133
+ .split(',')
134
+ .map((s) => s.trim())
135
+ .filter(Boolean)
136
+ : [];
137
+ const queryTypes = await resolveQueryTypes(entityName, propertySpecBySlug);
138
+ try {
139
+ // TODO: break the paginated and single-shot branches into their own functions.
140
+ if (SHOULD_USE_PAGINATED_FIND) {
141
+ const stream = streamPaginatedFind(entityName, {
142
+ criteria: convertPropertySpecIntoCriteria(propertySpecBySlug, queryTypes),
143
+ skipHydrateRelationships,
144
+ skip,
145
+ suffix,
146
+ apiVersion: apiVersion,
147
+ relations,
148
+ propertySlugs: propertySlugsArray,
149
+ });
150
+ const writer = outputFile ? fs_1.default.createWriteStream(outputFile) : process.stdout;
151
+ writer.write('[\n');
152
+ let first = true;
153
+ for await (const entity of stream) {
154
+ if (!first)
155
+ writer.write(',\n');
156
+ writer.write(JSON.stringify(entity, null, 2));
157
+ first = false;
158
+ }
159
+ writer.write('\n]\n');
160
+ if (outputFile)
161
+ console.error(`Output saved to ${outputFile}`);
162
+ }
163
+ else {
164
+ const response = await getEntitiesByName(entityName, propertySpecBySlug, queryTypes, {
165
+ skipHydrateRelationships,
166
+ relations,
167
+ propertySlugs: propertySlugsArray,
168
+ skip,
169
+ suffix,
170
+ apiVersion: apiVersion,
171
+ take,
172
+ });
173
+ if (response === null) {
174
+ this.error(`Entity not found: ${propertySpecBySlug.get('id')}`, { exit: 1 });
175
+ }
176
+ if (outputFile) {
177
+ fs_1.default.writeFileSync(outputFile, JSON.stringify(response, null, 2));
178
+ console.error(`Output saved to ${outputFile}`);
179
+ }
180
+ else {
181
+ this.log(JSON.stringify(response, null, 2));
182
+ }
183
+ }
184
+ }
185
+ catch (e) {
186
+ if (e.message?.startsWith('Entity not found:')) {
187
+ throw e;
188
+ }
189
+ this.error(`Error fetching entity: ${e.message}`);
190
+ }
191
+ }
192
+ }
193
+ exports.default = GetEntity;
194
+ async function getEntitiesByName(entityName, propertySpec, typePropertySets, options = {}) {
195
+ const { propertySlugs, relations, skipHydrateRelationships, skip, suffix, apiVersion, take } = options;
196
+ const id = propertySpec?.get('id')?.toString() || undefined;
197
+ const criteria = convertPropertySpecIntoCriteria(propertySpec || new Map(), typePropertySets);
198
+ return find(entityName, {
199
+ id,
200
+ // a missing id returns null (no retries); the command turns it into a clean not-found error
201
+ ignore404: id !== undefined,
202
+ skipHydrateRelationships,
203
+ relations,
204
+ propertySlugs,
205
+ criteria,
206
+ skip,
207
+ suffix,
208
+ apiVersion,
209
+ take,
210
+ });
211
+ }
212
+ function convertPropertySpecIntoCriteria(propertySpec, typePropertySets = []) {
213
+ const propertyTypeBySlug = (0, propertyValues_1.buildPropertyTypeMap)(typePropertySets);
214
+ const ranges = new Map();
215
+ const values = new Map();
216
+ propertySpec.forEach((value, slug) => {
217
+ const looksLikeRange = typeof value === 'string' && value.includes('..');
218
+ const isDateProperty = propertyTypeBySlug.get(slug) === types_1.PropertyType.Date;
219
+ const isRange = looksLikeRange && (isDateProperty || (0, dateRanges_1.isDateRangeValue)(value));
220
+ (isRange ? ranges : values).set(slug, value);
221
+ });
222
+ const criteria = (0, propertyValues_1.castCriteriaValues)(values, typePropertySets);
223
+ ranges.forEach((value, slug) => {
224
+ criteria[slug] = (0, dateRanges_1.convertDateRangeToJSURL)((0, dateRanges_1.parseDateRange)(value));
225
+ });
226
+ return criteria;
227
+ }
228
+ /**
229
+ * The types a query should be read against: the subtypes named by a typePath
230
+ * criterion if there is one, otherwise the entity's root type. A subtype
231
+ * carries its inherited properties, so one lookup per named path is enough.
232
+ */
233
+ async function resolveQueryTypes(entityName, propertySpec) {
234
+ const specified = propertySpec.get('typePath');
235
+ const paths = specified === undefined ? [entityName] : [specified].flat().map(String);
236
+ const types = await Promise.all(paths.map((path) => (0, types_2.getTypeByPath)(path).catch(() => {
237
+ console.error(`Could not resolve type ${path}; criteria on it are read as written.`);
238
+ return undefined;
239
+ })));
240
+ return types.map((type) => type?.typeProperties);
241
+ }
242
+ async function find(entityName, options = {}) {
243
+ const client = new sdk_1.Entities();
244
+ const { criteria, id, ignore404, propertySlugs, skipHydrateRelationships, relations, skip, suffix, apiVersion, take, } = options;
245
+ const queryOptions = {
246
+ entityName,
247
+ ignore404,
248
+ skipHydrateRelationships,
249
+ relations,
250
+ skip,
251
+ suffix,
252
+ apiVersion,
253
+ take,
254
+ };
255
+ if (propertySlugs && propertySlugs.length > 0) {
256
+ queryOptions.customParams = { propertySlugs: propertySlugs.join(',') };
257
+ }
258
+ const payload = id ? { id, ...queryOptions } : { criteria, ...queryOptions };
259
+ // a suffix names a specific sub-route and an id names one entity; both always go
260
+ // through the plain client (batch-fetch only understands criteria)
261
+ if ((0, batchFetch_1.canBatchFetchEntity)(entityName) && !suffix && !id) {
262
+ return (0, batchFetch_1.batchFetch)(entityName, { ...payload, propertySlugs });
263
+ }
264
+ else {
265
+ return client.get(payload);
266
+ }
267
+ }
268
+ async function* streamPaginatedFind(entityName, options = {}) {
269
+ const client = new sdk_1.Entities();
270
+ let nextPageKey = undefined;
271
+ let count = 0;
272
+ while (true) {
273
+ const opts = {
274
+ ...options,
275
+ entityName,
276
+ // paginated reads require the V2 response shape unless overridden
277
+ apiVersion: options.apiVersion ?? sdk_1.API_VERSION.V2,
278
+ nextPageKey,
279
+ };
280
+ if (options.propertySlugs?.length > 0) {
281
+ opts.customParams = {
282
+ propertySlugs: options.propertySlugs.join(','),
283
+ };
284
+ }
285
+ const response = await client.get(opts);
286
+ nextPageKey = response.nextPageKey;
287
+ const results = response.results || [];
288
+ for (const result of results) {
289
+ yield result;
290
+ count++;
291
+ if (MAX_NUMBER_OF_ENTITIES_TO_FETCH && count >= MAX_NUMBER_OF_ENTITIES_TO_FETCH)
292
+ return;
293
+ }
294
+ console.error(`Fetched ${count} entities`);
295
+ if (!nextPageKey || results.length === 0)
296
+ return;
297
+ }
298
+ }
@@ -0,0 +1 @@
1
+ export {};
@@ -0,0 +1,79 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ const tslib_1 = require("tslib");
4
+ const create_1 = tslib_1.__importDefault(require("./create"));
5
+ const get_1 = tslib_1.__importDefault(require("./get"));
6
+ const update_1 = tslib_1.__importDefault(require("./update"));
7
+ const delete_1 = tslib_1.__importDefault(require("./delete"));
8
+ const propertySpecifications_1 = require("../../helpers/propertySpecifications/propertySpecifications");
9
+ describe('entities command grammar: entities <verb> <typePath> [ID...]', () => {
10
+ describe('partitionIdsAndSpecs', () => {
11
+ it('should treat tokens without an equals sign as ids', () => {
12
+ const { ids, specs } = (0, propertySpecifications_1.partitionIdsAndSpecs)(['id1', 'id2', 'id3']);
13
+ expect(ids).toEqual(['id1', 'id2', 'id3']);
14
+ expect(specs).toEqual([]);
15
+ });
16
+ it('should treat slug=value tokens as property specifications', () => {
17
+ const { ids, specs } = (0, propertySpecifications_1.partitionIdsAndSpecs)(['name=jet', 'hex=000000']);
18
+ expect(ids).toEqual([]);
19
+ expect(specs).toEqual(['name=jet', 'hex=000000']);
20
+ });
21
+ it('should split mixed tokens preserving order within each group', () => {
22
+ const { ids, specs } = (0, propertySpecifications_1.partitionIdsAndSpecs)(['id1', 'name=jet', 'id2', 'status=archived']);
23
+ expect(ids).toEqual(['id1', 'id2']);
24
+ expect(specs).toEqual(['name=jet', 'status=archived']);
25
+ });
26
+ it('should reject malformed specs rather than discard them', () => {
27
+ expect(() => (0, propertySpecifications_1.partitionIdsAndSpecs)(['=value'])).toThrow('Invalid property specification');
28
+ expect(() => (0, propertySpecifications_1.partitionIdsAndSpecs)(['id1', '=value'])).toThrow('=value');
29
+ });
30
+ it('should handle empty input', () => {
31
+ const { ids, specs } = (0, propertySpecifications_1.partitionIdsAndSpecs)([]);
32
+ expect(ids).toEqual([]);
33
+ expect(specs).toEqual([]);
34
+ });
35
+ });
36
+ describe('positional id arguments', () => {
37
+ it('should accept variadic positional ids on get', () => {
38
+ expect(get_1.default.strict).toBe(false);
39
+ expect(get_1.default.args.ids).toBeDefined();
40
+ });
41
+ it('should accept variadic positional ids on update with no single id arg', () => {
42
+ expect(update_1.default.strict).toBe(false);
43
+ expect(update_1.default.args.ids).toBeDefined();
44
+ expect(update_1.default.args.id).toBeUndefined();
45
+ });
46
+ it('should accept variadic positional ids on delete with no --id flag', () => {
47
+ expect(delete_1.default.strict).toBe(false);
48
+ expect(delete_1.default.args.ids).toBeDefined();
49
+ expect(delete_1.default.flags.id).toBeUndefined();
50
+ });
51
+ });
52
+ describe('flag alignment across verbs', () => {
53
+ it('should name the input file -i, --inputFile on every verb that accepts one', () => {
54
+ expect(create_1.default.flags.inputFile.char).toBe('i');
55
+ expect(update_1.default.flags.inputFile.char).toBe('i');
56
+ expect(delete_1.default.flags.inputFile.char).toBe('i');
57
+ expect(delete_1.default.flags.input).toBeUndefined();
58
+ });
59
+ it('should map skipHydrateRelationships to -S on every verb', () => {
60
+ expect(create_1.default.flags.skipHydrateRelationships.char).toBe('S');
61
+ expect(get_1.default.flags.skipHydrateRelationships.char).toBe('S');
62
+ expect(update_1.default.flags.skipHydrateRelationships.char).toBe('S');
63
+ });
64
+ it('should keep -s for --skip on get', () => {
65
+ expect(get_1.default.flags.skip.char).toBe('s');
66
+ });
67
+ it('should expose --suffix on every verb to reach entity sub-routes', () => {
68
+ expect(create_1.default.flags.suffix).toBeDefined();
69
+ expect(get_1.default.flags.suffix).toBeDefined();
70
+ expect(update_1.default.flags.suffix).toBeDefined();
71
+ expect(delete_1.default.flags.suffix).toBeDefined();
72
+ });
73
+ it('should expose --apiVersion on every verb, constrained to 1 or 2', () => {
74
+ for (const command of [create_1.default, get_1.default, update_1.default, delete_1.default]) {
75
+ expect(command.flags.apiVersion.options).toEqual(['1', '2']);
76
+ }
77
+ });
78
+ });
79
+ });
@@ -0,0 +1 @@
1
+ export {};
@@ -0,0 +1,72 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ const create_1 = require("./create");
4
+ const update_1 = require("./update");
5
+ const fulfilled = (value) => ({ status: 'fulfilled', value });
6
+ const rejected = (message) => ({
7
+ status: 'rejected',
8
+ reason: new Error(message),
9
+ });
10
+ describe('mutation output summaries', () => {
11
+ describe('summarizeSettledCreates', () => {
12
+ it('should put every fulfilled result under created', () => {
13
+ const inputs = [{ name: 'a' }, { name: 'b' }];
14
+ const summary = (0, create_1.summarizeSettledCreates)(inputs, [
15
+ fulfilled({ id: '1', name: 'a' }),
16
+ fulfilled({ id: '2', name: 'b' }),
17
+ ]);
18
+ expect(summary.created).toEqual([
19
+ { id: '1', name: 'a' },
20
+ { id: '2', name: 'b' },
21
+ ]);
22
+ expect(summary.failed).toEqual([]);
23
+ });
24
+ it('should pair each failed input with its error so it can be retried as-is', () => {
25
+ const inputs = [{ itemId: 'itm-1' }, { itemId: 'itm-41x' }, { itemId: 'itm-3' }];
26
+ const summary = (0, create_1.summarizeSettledCreates)(inputs, [
27
+ fulfilled({ id: 'ai-1' }),
28
+ rejected('Item with ID itm-41x does not exist'),
29
+ fulfilled({ id: 'ai-3' }),
30
+ ]);
31
+ expect(summary.created).toEqual([{ id: 'ai-1' }, { id: 'ai-3' }]);
32
+ expect(summary.failed).toEqual([
33
+ { input: { itemId: 'itm-41x' }, error: 'Item with ID itm-41x does not exist' },
34
+ ]);
35
+ });
36
+ it('should fall back to details when the SDK error message is empty', () => {
37
+ const sdkError = Object.assign(new Error(''), {
38
+ details: '{"message":"Assortment not found.","statusCode":404}',
39
+ });
40
+ const summary = (0, create_1.summarizeSettledCreates)([{ assortmentId: 'bogus' }], [{ status: 'rejected', reason: sdkError }]);
41
+ expect(summary.failed[0].error).toBe('{"message":"Assortment not found.","statusCode":404}');
42
+ });
43
+ it('should stringify reasons that are not Errors', () => {
44
+ const summary = (0, create_1.summarizeSettledCreates)([{ name: 'a' }], [{ status: 'rejected', reason: 'boom' }]);
45
+ expect(summary.failed).toEqual([{ input: { name: 'a' }, error: 'boom' }]);
46
+ });
47
+ it('should handle empty input', () => {
48
+ expect((0, create_1.summarizeSettledCreates)([], [])).toEqual({ created: [], failed: [] });
49
+ });
50
+ });
51
+ describe('summarizeSettledUpdates', () => {
52
+ it('should report updated, failed, and skipped without stopping on failures', () => {
53
+ const inputs = [{ id: 'id1' }, { id: 'id2' }, { id: 'id3' }];
54
+ const summary = (0, update_1.summarizeSettledUpdates)(inputs, [
55
+ fulfilled({ id: 'id1', status: 'archived' }),
56
+ rejected('Entity not found.'),
57
+ fulfilled({ id: 'id3', status: 'archived' }),
58
+ ], 2);
59
+ expect(summary.updated).toEqual([
60
+ { id: 'id1', status: 'archived' },
61
+ { id: 'id3', status: 'archived' },
62
+ ]);
63
+ expect(summary.failed).toEqual([{ id: 'id2', error: 'Entity not found.' }]);
64
+ expect(summary.skipped).toBe(2);
65
+ });
66
+ it('should not report a failed id as updated', () => {
67
+ const summary = (0, update_1.summarizeSettledUpdates)([{ id: 'id1' }], [rejected('boom')], 0);
68
+ expect(summary.updated).toEqual([]);
69
+ expect(summary.failed).toEqual([{ id: 'id1', error: 'boom' }]);
70
+ });
71
+ });
72
+ });
@@ -0,0 +1,32 @@
1
+ import { BaseCommand } from '../../basecommand';
2
+ export default class UpdateEntity extends BaseCommand {
3
+ static description: string;
4
+ static examples: string[];
5
+ static flags: {
6
+ skipHydrateRelationships: import("@oclif/core/lib/interfaces").BooleanFlag<boolean>;
7
+ dryRun: import("@oclif/core/lib/interfaces").BooleanFlag<boolean>;
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>;
11
+ alwaysConfirmEnv: import("@oclif/core/lib/interfaces").OptionFlag<string, import("@oclif/core/lib/interfaces/parser").CustomOptions>;
12
+ logLevel: import("@oclif/core/lib/interfaces").OptionFlag<string, import("@oclif/core/lib/interfaces/parser").CustomOptions>;
13
+ };
14
+ static args: {
15
+ 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>>;
17
+ };
18
+ static strict: boolean;
19
+ init(): Promise<void>;
20
+ run(): Promise<void>;
21
+ }
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;