@contrail/cli 3.6.0-alpha.eec506e → 3.6.0

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 (91) hide show
  1. package/README.md +182 -26
  2. package/dist/api/types.d.ts +35 -0
  3. package/dist/api/types.js +49 -1
  4. package/dist/auth/login.d.ts +0 -4
  5. package/dist/auth/login.js +52 -115
  6. package/dist/auth/login.spec.js +0 -100
  7. package/dist/basecommand.js +2 -2
  8. package/dist/commands/app/getApiKey.js +2 -2
  9. package/dist/commands/entities/create.d.ts +49 -0
  10. package/dist/commands/entities/create.js +618 -0
  11. package/dist/commands/entities/create.spec.js +581 -0
  12. package/dist/commands/entities/delete.d.ts +20 -0
  13. package/dist/commands/entities/delete.js +146 -0
  14. package/dist/commands/entities/get.d.ts +25 -0
  15. package/dist/commands/entities/get.js +298 -0
  16. package/dist/commands/entities/grammar.spec.d.ts +1 -0
  17. package/dist/commands/entities/grammar.spec.js +79 -0
  18. package/dist/commands/entities/output.spec.d.ts +1 -0
  19. package/dist/commands/entities/output.spec.js +72 -0
  20. package/dist/commands/entities/update.d.ts +32 -0
  21. package/dist/commands/entities/update.js +212 -0
  22. package/dist/commands/webhooks/delete.js +2 -3
  23. package/dist/common.d.ts +10 -1
  24. package/dist/common.js +37 -1
  25. package/dist/common.spec.d.ts +1 -0
  26. package/dist/common.spec.js +40 -0
  27. package/dist/helpers/config/config.d.ts +3 -3
  28. package/dist/helpers/config/config.js +3 -3
  29. package/dist/helpers/entities/assortment-items.d.ts +11 -0
  30. package/dist/helpers/entities/assortment-items.js +76 -0
  31. package/dist/helpers/entities/batchFetch.d.ts +11 -0
  32. package/dist/helpers/entities/batchFetch.js +50 -0
  33. package/dist/helpers/entities/index.d.ts +3 -0
  34. package/dist/helpers/entities/index.js +6 -0
  35. package/dist/helpers/entities/items.d.ts +6 -0
  36. package/dist/helpers/entities/items.js +60 -0
  37. package/dist/helpers/entities/items.spec.d.ts +1 -0
  38. package/dist/helpers/entities/items.spec.js +19 -0
  39. package/dist/helpers/entities/project-items.d.ts +2 -0
  40. package/dist/helpers/entities/project-items.js +44 -0
  41. package/dist/helpers/file-helpers.d.ts +1 -0
  42. package/dist/helpers/file-helpers.js +20 -3
  43. package/dist/helpers/propertySpecifications/dateRanges.d.ts +34 -0
  44. package/dist/helpers/propertySpecifications/dateRanges.js +91 -0
  45. package/dist/helpers/propertySpecifications/dateRanges.spec.d.ts +1 -0
  46. package/dist/helpers/propertySpecifications/dateRanges.spec.js +97 -0
  47. package/dist/helpers/propertySpecifications/propertySpecifications.d.ts +39 -0
  48. package/dist/helpers/propertySpecifications/propertySpecifications.js +102 -0
  49. package/dist/helpers/propertySpecifications/propertySpecifications.spec.d.ts +1 -0
  50. package/dist/helpers/propertySpecifications/propertySpecifications.spec.js +387 -0
  51. package/dist/helpers/propertySpecifications/propertyValues.d.ts +31 -0
  52. package/dist/helpers/propertySpecifications/propertyValues.js +132 -0
  53. package/dist/helpers/propertySpecifications/propertyValues.spec.d.ts +1 -0
  54. package/dist/helpers/propertySpecifications/propertyValues.spec.js +156 -0
  55. package/dist/logger.js +4 -1
  56. package/dist/logger.spec.d.ts +1 -0
  57. package/dist/logger.spec.js +12 -0
  58. package/node_modules/@contrail/entity-compare/package.json +6 -3
  59. package/node_modules/@contrail/loader/lib/common/conditional-columns.js +1 -1
  60. package/node_modules/@contrail/loader/lib/constants.d.ts +0 -8
  61. package/node_modules/@contrail/loader/lib/constants.js +1 -9
  62. package/node_modules/@contrail/loader/lib/entities-v2/linesheet-v2/item-processor.d.ts +0 -4
  63. package/node_modules/@contrail/loader/lib/entities-v2/linesheet-v2/item-processor.js +0 -57
  64. package/node_modules/@contrail/loader/lib/entities-v2/linesheet-v2/item-processor.spec.js +34 -492
  65. package/node_modules/@contrail/loader/lib/pipeline/validate.js +52 -2
  66. package/node_modules/@contrail/loader/lib/pipeline/validate.spec.js +85 -0
  67. package/node_modules/@contrail/loader/package.json +2 -2
  68. package/node_modules/@contrail/sdk/.github/workflows/publish-to-npm.yml +1 -4
  69. package/node_modules/@contrail/sdk/lib/auth/login.js +1 -1
  70. package/node_modules/@contrail/sdk/lib/config/config.d.ts +3 -0
  71. package/node_modules/@contrail/sdk/lib/config/config.js +13 -7
  72. package/node_modules/@contrail/sdk/lib/core/request.js +6 -2
  73. package/node_modules/@contrail/sdk/lib/entities/entities.client.d.ts +2 -0
  74. package/node_modules/@contrail/sdk/lib/entities/entities.client.js +3 -1
  75. package/node_modules/@contrail/sdk/lib/entities/entity.resource.registry.js +1 -0
  76. package/node_modules/@contrail/sdk/lib/image-search/image-search.d.ts +34 -0
  77. package/node_modules/@contrail/sdk/lib/image-search/image-search.js +42 -0
  78. package/node_modules/@contrail/sdk/lib/image-search/index.d.ts +1 -0
  79. package/node_modules/@contrail/sdk/lib/image-search/index.js +17 -0
  80. package/node_modules/@contrail/sdk/lib/index.d.ts +1 -0
  81. package/node_modules/@contrail/sdk/lib/index.js +1 -0
  82. package/node_modules/@contrail/sdk/package.json +1 -1
  83. package/node_modules/@contrail/sdk/scripts/replicate-bug.js +69 -0
  84. package/oclif.manifest.json +449 -50
  85. package/package.json +6 -12
  86. package/dist/auth/sso.d.ts +0 -36
  87. package/dist/auth/sso.js +0 -174
  88. package/dist/auth/sso.spec.js +0 -148
  89. package/dist/commands/login.d.ts +0 -12
  90. package/dist/commands/login.js +0 -25
  91. /package/dist/{auth/sso.spec.d.ts → commands/entities/create.spec.d.ts} +0 -0
@@ -0,0 +1,212 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.summarizeSettledUpdates = void 0;
4
+ const tslib_1 = require("tslib");
5
+ const p_limit_1 = tslib_1.__importDefault(require("p-limit"));
6
+ const core_1 = require("@oclif/core");
7
+ const basecommand_1 = require("../../basecommand");
8
+ const sdk_1 = require("@contrail/sdk");
9
+ const login_1 = require("../../auth/login");
10
+ const common_1 = require("../../common");
11
+ const propertySpecifications_1 = require("../../helpers/propertySpecifications/propertySpecifications");
12
+ const file_helpers_1 = require("../../helpers/file-helpers");
13
+ const propertyValues_1 = require("../../helpers/propertySpecifications/propertyValues");
14
+ const types_1 = require("../../api/types");
15
+ class UpdateEntity extends basecommand_1.BaseCommand {
16
+ static description = 'Update an entity';
17
+ static examples = [
18
+ 'contrail entities update color 123 -- name=obsidian hex=000000',
19
+ 'contrail entities update item id1 id2 id3 -- colorName=obsidian # apply the same change to several entities',
20
+ 'contrail entities update color 123 -- federatedId= name=\'""\' # Unset federatedId, set name to empty string',
21
+ ];
22
+ static flags = {
23
+ ...basecommand_1.BaseCommand.baseFlags,
24
+ skipHydrateRelationships: core_1.Flags.boolean({
25
+ char: 'S',
26
+ description: 'Skip hydrating relationships when updating the entity',
27
+ required: false,
28
+ default: false,
29
+ }),
30
+ dryRun: core_1.Flags.boolean({
31
+ char: 'd',
32
+ description: 'If true, does not update the entities but simulates the update',
33
+ required: false,
34
+ default: false,
35
+ }),
36
+ inputFile: core_1.Flags.string({
37
+ char: 'i',
38
+ description: 'A file with a JSON array of {id, ...} objects; each object is one entity to update.',
39
+ required: false,
40
+ }),
41
+ suffix: core_1.Flags.string({
42
+ description: 'Append a sub-route to the entity endpoint (e.g. --suffix=synchronous targets /<entities>/synchronous)',
43
+ required: false,
44
+ }),
45
+ apiVersion: core_1.Flags.string({
46
+ description: 'Api-Version header to send; selects the V1 or V2 variant of the endpoint',
47
+ options: ['1', '2'],
48
+ required: false,
49
+ }),
50
+ };
51
+ static args = {
52
+ entityName: core_1.Args.string({
53
+ description: 'The name of the entity type to update (type paths are not supported)',
54
+ required: true,
55
+ }),
56
+ ids: core_1.Args.string({
57
+ description: 'One or more entity ids to update',
58
+ required: false,
59
+ }),
60
+ };
61
+ static strict = false;
62
+ async init() {
63
+ (0, common_1.routeConsoleLogToStderr)();
64
+ await super.init();
65
+ }
66
+ async run() {
67
+ await (0, login_1.authUser)();
68
+ const { args, argv } = await this.parse(UpdateEntity);
69
+ const { entityName } = args;
70
+ const idParsedAsFlag = (0, common_1.findIdParsedAsFlag)(process.argv, 'il');
71
+ if (idParsedAsFlag) {
72
+ 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).`);
73
+ }
74
+ const { dryRun: isDryRun, inputFile: inputFilename, skipHydrateRelationships, suffix, apiVersion, } = this.flags;
75
+ if (entityName.includes(':')) {
76
+ this.error(`update takes an entity name, not a type path. Use: contrail entities update ${entityName.split(':')[0]} <ID...>`);
77
+ }
78
+ const { ids: positionalIds, specs } = (0, propertySpecifications_1.partitionIdsAndSpecs)(argv.slice(1));
79
+ const propertySpec = (0, propertySpecifications_1.parsePropertySpecificationsIntoMap)(specs);
80
+ if (propertySpec.has('id') || propertySpec.has('ids')) {
81
+ this.error('The -- payload is values to write. Pass ids positionally: contrail entities update <entityName> <ID...> -- slug=value');
82
+ }
83
+ if (inputFilename && positionalIds.length > 0) {
84
+ this.error('You cannot use --inputFile and positional ids together. Please specify one or the other.');
85
+ }
86
+ if (!inputFilename && positionalIds.length === 0) {
87
+ this.error('You must provide one or more ids or an input file (-i) of entities to update.');
88
+ }
89
+ if (positionalIds.length > 0 && propertySpec.size === 0) {
90
+ this.error('Nothing to update: pass values to write after --, e.g. -- name=jet');
91
+ }
92
+ const entitiesToUpdate = inputFilename
93
+ ? (0, file_helpers_1.parseFileAsJsonArray)(inputFilename)
94
+ : positionalIds.map((id) => ({ id }));
95
+ const skipped = entitiesToUpdate.filter(({ id }) => !id).length;
96
+ const entitiesWithId = entitiesToUpdate.filter(({ id }) => id);
97
+ if (Array.isArray(propertySpec.get('typePath'))) {
98
+ this.error('typePath takes a single value. Repeat the key only for multi-value properties.');
99
+ }
100
+ // cast against each record's own subtype: the API converts numeric strings itself
101
+ // but rejects boolean ones, so an uncast isArchived=false comes back as a 400
102
+ const typePropertiesById = await resolvePropertiesByEntityId(entityName, entitiesWithId.map(({ id }) => id));
103
+ // JSON.stringify drops undefined keys, so an unset has to travel as an explicit null
104
+ const unsetValues = Object.fromEntries([...propertySpec.keys()]
105
+ .filter((slug) => propertySpec.get(slug) === undefined)
106
+ .map((slug) => [slug, null]));
107
+ const specifiedValues = new Map([...propertySpec.entries()].filter(([, value]) => value !== undefined));
108
+ async function updateEntity(entity) {
109
+ const id = entity.id;
110
+ const newEntityState = {
111
+ ...entity,
112
+ ...(0, propertyValues_1.castValuesToPropertyTypes)(specifiedValues, typePropertiesById.get(id)),
113
+ ...unsetValues,
114
+ };
115
+ return isDryRun
116
+ ? mockUpdateById(entityName, id, newEntityState, { skipHydrateRelationships })
117
+ : updateEntityById(entityName, id, newEntityState, {
118
+ skipHydrateRelationships,
119
+ suffix,
120
+ apiVersion: apiVersion,
121
+ });
122
+ }
123
+ try {
124
+ const limit = (0, p_limit_1.default)(20);
125
+ const settled = await Promise.allSettled(entitiesWithId.map((entity) => limit(() => updateEntity(entity))));
126
+ const summary = summarizeSettledUpdates(entitiesWithId, settled, skipped);
127
+ if (isDryRun) {
128
+ console.error('Dry run. Update skipped. Changes would be:');
129
+ }
130
+ this.log(JSON.stringify(summary, null, 2));
131
+ if (summary.failed.length > 0) {
132
+ console.error(`${summary.failed.length} of ${entitiesWithId.length} updates failed.`);
133
+ process.exitCode = 1;
134
+ }
135
+ }
136
+ catch (e) {
137
+ this.error(`Error updating entities: ${e.message}`);
138
+ }
139
+ }
140
+ }
141
+ exports.default = UpdateEntity;
142
+ // The ids criterion travels in the URL, which the gateway rejects somewhere past
143
+ // 5k characters, so the lookup goes out in chunks.
144
+ const ID_LOOKUP_CHUNK_SIZE = 250;
145
+ async function resolvePropertiesByEntityId(entityName, ids) {
146
+ const rootType = await (0, types_1.getTypeByPath)(entityName).catch(() => undefined);
147
+ const typePathById = await fetchTypePathsByIds(entityName, ids);
148
+ const distinctPaths = [...new Set([...typePathById.values()])];
149
+ const propertiesByPath = new Map();
150
+ await Promise.all(distinctPaths.map(async (path) => {
151
+ const type = await (0, types_1.getTypeByPath)(path).catch(() => undefined);
152
+ propertiesByPath.set(path, type?.typeProperties ?? rootType?.typeProperties);
153
+ }));
154
+ // an id the lookup did not return falls back to the root type; the write reports its own 404
155
+ return new Map(ids.map((id) => [id, propertiesByPath.get(typePathById.get(id)) ?? rootType?.typeProperties]));
156
+ }
157
+ async function fetchTypePathsByIds(entityName, ids) {
158
+ const client = new sdk_1.Entities();
159
+ const chunks = [];
160
+ for (let i = 0; i < ids.length; i += ID_LOOKUP_CHUNK_SIZE) {
161
+ chunks.push(ids.slice(i, i + ID_LOOKUP_CHUNK_SIZE));
162
+ }
163
+ const pages = await Promise.all(chunks.map((chunk) => client
164
+ .get({
165
+ entityName,
166
+ criteria: { ids: chunk },
167
+ customParams: { propertySlugs: 'id,typePath' },
168
+ })
169
+ .catch(() => [])));
170
+ return new Map(pages
171
+ .flat()
172
+ .filter((entity) => entity?.id && entity?.typePath)
173
+ .map((entity) => [entity.id, entity.typePath]));
174
+ }
175
+ function summarizeSettledUpdates(inputs, settled, skipped) {
176
+ const updated = [];
177
+ const failed = [];
178
+ settled.forEach((result, index) => {
179
+ if (result.status === 'fulfilled') {
180
+ updated.push(result.value);
181
+ }
182
+ else {
183
+ failed.push({
184
+ id: inputs[index].id,
185
+ error: (0, common_1.sdkErrorMessage)(result.reason),
186
+ });
187
+ }
188
+ });
189
+ return { updated, failed, skipped };
190
+ }
191
+ exports.summarizeSettledUpdates = summarizeSettledUpdates;
192
+ async function updateEntityById(entityName, id, changes, options = {}) {
193
+ const client = new sdk_1.Entities();
194
+ const { skipHydrateRelationships, suffix, apiVersion } = options;
195
+ return client.update({
196
+ entityName,
197
+ id,
198
+ object: changes,
199
+ skipHydrateRelationships,
200
+ suffix,
201
+ apiVersion,
202
+ });
203
+ }
204
+ async function mockUpdateById(entityName, id, changes, options = {}) {
205
+ const client = new sdk_1.Entities();
206
+ const { skipHydrateRelationships } = options;
207
+ const entity = await client.get({ entityName, id, skipHydrateRelationships });
208
+ if (!entity) {
209
+ return null;
210
+ }
211
+ return { ...entity, ...changes };
212
+ }
@@ -6,7 +6,6 @@ const login_1 = require("../../auth/login");
6
6
  const webhooks_1 = require("../../api/webhooks");
7
7
  const inquirer_1 = tslib_1.__importDefault(require("inquirer"));
8
8
  const basecommand_1 = require("../../basecommand");
9
- const logger_1 = tslib_1.__importDefault(require("../../logger"));
10
9
  class DeleteWebhooks extends basecommand_1.BaseCommand {
11
10
  static description = 'Delete an existing webhook. To delete a single webhook, pass its ID. To delete multiple webhooks, do not pass a value for the ID, and select multiple using the interactive selector';
12
11
  static examples = [
@@ -43,10 +42,10 @@ class DeleteWebhooks extends basecommand_1.BaseCommand {
43
42
  }
44
43
  }
45
44
  if (this.flags.json) {
46
- logger_1.default.info(JSON.stringify(deletedWebhooks, null, 2));
45
+ this.log(JSON.stringify(deletedWebhooks, null, 2));
47
46
  }
48
47
  else {
49
- logger_1.default.info(deletedWebhooks.map((x) => x.id).join('\n'));
48
+ this.log(deletedWebhooks.map((x) => x.id).join('\n'));
50
49
  }
51
50
  }
52
51
  }
package/dist/common.d.ts CHANGED
@@ -1,4 +1,13 @@
1
1
  /// <reference types="node" />
2
2
  export declare function getSeparatorByPlatform(): string;
3
3
  export declare function delay(ms: number): Promise<NodeJS.Timeout>;
4
- export declare function removeSlash(string: any): string;
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;
8
+ /**
9
+ * An id beginning with a hyphen is consumed as flags before a command sees it,
10
+ * which can silently switch on a boolean flag and shift the remaining arguments.
11
+ * Platform ids are long enough to tell apart from a cluster of short flags.
12
+ */
13
+ export declare function findIdParsedAsFlag(argv: string[], shortFlagsTakingValues?: string): string | undefined;
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.findIdParsedAsFlag = 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,37 @@ 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 });
36
+ /**
37
+ * An id beginning with a hyphen is consumed as flags before a command sees it,
38
+ * which can silently switch on a boolean flag and shift the remaining arguments.
39
+ * Platform ids are long enough to tell apart from a cluster of short flags.
40
+ */
41
+ function findIdParsedAsFlag(argv, shortFlagsTakingValues = '') {
42
+ const separator = argv.indexOf('--');
43
+ const beforeSeparator = separator === -1 ? argv : argv.slice(0, separator);
44
+ return beforeSeparator.find((token) => {
45
+ // a long flag could never have been a short-flag cluster, and oclif rejects
46
+ // an unknown one itself
47
+ if (token.startsWith('--') || !/^-[A-Za-z0-9_-]{8,}$/.test(token)) {
48
+ return false;
49
+ }
50
+ // oclif reads -rvalue as a flag with an attached value
51
+ return !shortFlagsTakingValues.includes(token[1]);
52
+ });
53
+ }
54
+ exports.findIdParsedAsFlag = findIdParsedAsFlag;
@@ -0,0 +1 @@
1
+ export {};
@@ -0,0 +1,40 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ const common_1 = require("./common");
4
+ describe('findIdParsedAsFlag', () => {
5
+ const GET_SHORT_FLAGS_WITH_VALUES = 'loprst';
6
+ it('should find an id that a short flag cluster would swallow', () => {
7
+ expect((0, common_1.findIdParsedAsFlag)(['delete', 'item', '-d3YBdV-d8PXI88U'])).toBe('-d3YBdV-d8PXI88U');
8
+ });
9
+ it('should ignore long flags, whatever their length', () => {
10
+ const longFlags = [
11
+ '--paginated',
12
+ '--inputFile',
13
+ '--outputFile',
14
+ '--relations',
15
+ '--propertySlugs',
16
+ '--skipHydrateRelationships',
17
+ '--alwaysConfirmEnv',
18
+ '--apiVersion',
19
+ '--logLevel',
20
+ '--dryRun',
21
+ '--suffix',
22
+ ];
23
+ longFlags.forEach((flag) => {
24
+ expect((0, common_1.findIdParsedAsFlag)(['get', 'color', flag])).toBeUndefined();
25
+ });
26
+ });
27
+ it('should ignore a short flag carrying an attached value', () => {
28
+ expect((0, common_1.findIdParsedAsFlag)(['get', 'color', '-rprojectItems'], GET_SHORT_FLAGS_WITH_VALUES)).toBeUndefined();
29
+ expect((0, common_1.findIdParsedAsFlag)(['get', 'color', '-ooutput12345'], GET_SHORT_FLAGS_WITH_VALUES)).toBeUndefined();
30
+ });
31
+ it('should still flag an id whose first character is not a value-taking flag', () => {
32
+ expect((0, common_1.findIdParsedAsFlag)(['get', 'color', '-d3YBdV-d8PX'], GET_SHORT_FLAGS_WITH_VALUES)).toBe('-d3YBdV-d8PX');
33
+ });
34
+ it('should ignore everything after the -- separator', () => {
35
+ expect((0, common_1.findIdParsedAsFlag)(['get', 'color', '--', '-nJkS_UQjgRHrENJ'])).toBeUndefined();
36
+ });
37
+ it('should ignore short flag clusters and ordinary arguments', () => {
38
+ expect((0, common_1.findIdParsedAsFlag)(['get', 'color', '-dS', '-t', '5', 'someId'])).toBeUndefined();
39
+ });
40
+ });
@@ -9,10 +9,10 @@ export declare function readVibeIQConfig(): Promise<any>;
9
9
  export declare function writeVibeIQConfig(config: any): Promise<void>;
10
10
  export declare function storeVibeIQConfig(incomingConfig: any): Promise<void>;
11
11
  export declare function createConfig(fileName: any): Promise<void>;
12
- export declare function writeConfig(config: any, configName?: string): Promise<void>;
12
+ export declare function writeConfig(config: any, configName?: string | null): Promise<void>;
13
13
  export declare function getConfig(): Promise<any>;
14
- export declare function storeConfig(incomingConfig: any, configName?: string, merge?: boolean): Promise<void>;
14
+ export declare function storeConfig(incomingConfig: any, configName?: string | null, merge?: boolean): Promise<void>;
15
15
  export declare function getConfigFiles(): Promise<any>;
16
16
  export declare function getConfigContent(fileName: string): Promise<any>;
17
- export declare function validateEnvironments(envName?: any): Promise<any>;
17
+ export declare function validateEnvironments(envName?: string | null): Promise<any>;
18
18
  export declare function checkTelemetry(cliVersion: string): Promise<void>;
@@ -46,13 +46,13 @@ exports.initializeVibeIQConfig = initializeVibeIQConfig;
46
46
  async function readVibeIQConfig() {
47
47
  let fileContent;
48
48
  try {
49
- fileContent = await (await node_fs_1.promises.readFile(configFileLocation)).toString();
49
+ fileContent = (await node_fs_1.promises.readFile(configFileLocation)).toString();
50
50
  }
51
51
  catch {
52
52
  logger_1.default.debug(`failed to open config file (${configFileLocation}) for reading.`);
53
53
  logger_1.default.debug('trying to initialize config file');
54
54
  await initializeVibeIQConfig();
55
- fileContent = await (await node_fs_1.promises.readFile(configFileLocation)).toString();
55
+ fileContent = (await node_fs_1.promises.readFile(configFileLocation)).toString();
56
56
  }
57
57
  try {
58
58
  return JSON.parse(fileContent);
@@ -165,7 +165,7 @@ async function getConfigContent(fileName) {
165
165
  return JSON.parse(fileContent);
166
166
  }
167
167
  catch (error) {
168
- logger_1.default.error(`Failed to open/parse config file (${fileName}) might be malformed or not found.`);
168
+ logger_1.default.error(`Failed to open/parse config file (${fileName}) might be malformed or not found. Path: ${configFilePath}, error: ${error}`);
169
169
  }
170
170
  }
171
171
  exports.getConfigContent = getConfigContent;
@@ -0,0 +1,11 @@
1
+ import { Item } from '@contrail/entity-types';
2
+ import { API_VERSION } from '@contrail/sdk';
3
+ export declare function createAssortmentItem(assortmentItem: {
4
+ assortmentId: string;
5
+ itemId: string;
6
+ [key: string]: any;
7
+ }, options?: {
8
+ skipHydrateRelationships?: boolean;
9
+ apiVersion?: API_VERSION;
10
+ }): Promise<any>;
11
+ export declare function findItemsNotInAssortment(assortmentId: string, count?: number): Promise<Item[]>;
@@ -0,0 +1,76 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.findItemsNotInAssortment = exports.createAssortmentItem = void 0;
4
+ const sdk_1 = require("@contrail/sdk");
5
+ const batchFetch_1 = require("./batchFetch");
6
+ const items_1 = require("./items");
7
+ async function createAssortmentItem(assortmentItem, options = {}) {
8
+ const client = new sdk_1.Entities();
9
+ const { assortmentId, itemId } = assortmentItem;
10
+ const { skipHydrateRelationships = false, apiVersion } = options;
11
+ // add item to assortment
12
+ await client.create({
13
+ entityName: 'assortment',
14
+ id: assortmentId,
15
+ relation: 'items',
16
+ object: { itemIds: [itemId] },
17
+ apiVersion,
18
+ });
19
+ // Update assortment item with properties
20
+ const updated = await client.update({
21
+ entityName: 'assortment-item',
22
+ id: `${assortmentId}:${itemId}`,
23
+ object: assortmentItem,
24
+ skipHydrateRelationships,
25
+ apiVersion,
26
+ });
27
+ return updated;
28
+ }
29
+ exports.createAssortmentItem = createAssortmentItem;
30
+ // Methods to find an item not in the assortment
31
+ const ASSORTMENT_ITEMS_CACHE_BY_ASSORTMENT_ID = new Map();
32
+ const ASSORTMENT_ITEMS_CACHE_BY_ITEM_ID = new Map();
33
+ async function cacheAssortmentItemsByAssortmentId(assortmentId) {
34
+ if (!assortmentId) {
35
+ throw new Error('Assortment ID is required to cache assortment items');
36
+ }
37
+ if (ASSORTMENT_ITEMS_CACHE_BY_ASSORTMENT_ID.has(assortmentId)) {
38
+ return; // Already cached
39
+ }
40
+ const assortmentItems = await (0, batchFetch_1.batchFetch)('assortment-item', {
41
+ criteria: { assortmentId },
42
+ propertySlugs: ['id', 'assortmentId', 'itemId'],
43
+ });
44
+ ASSORTMENT_ITEMS_CACHE_BY_ASSORTMENT_ID.set(assortmentId, assortmentItems);
45
+ assortmentItems.forEach((item) => {
46
+ if (!ASSORTMENT_ITEMS_CACHE_BY_ITEM_ID.has(item.itemId)) {
47
+ ASSORTMENT_ITEMS_CACHE_BY_ITEM_ID.set(item.itemId, []);
48
+ }
49
+ ASSORTMENT_ITEMS_CACHE_BY_ITEM_ID.get(item.itemId).push(item);
50
+ });
51
+ }
52
+ async function getAssortmentItemsByAssortmentId(assortmentId) {
53
+ if (!assortmentId) {
54
+ throw new Error('Assortment ID is required to get assortment items');
55
+ }
56
+ await cacheAssortmentItemsByAssortmentId(assortmentId);
57
+ const assortmentItems = ASSORTMENT_ITEMS_CACHE_BY_ASSORTMENT_ID.get(assortmentId);
58
+ if (!assortmentItems) {
59
+ throw new Error(`No assortment items found for assortment ID ${assortmentId}`);
60
+ }
61
+ return assortmentItems;
62
+ }
63
+ async function findItemsNotInAssortment(assortmentId, count) {
64
+ if (!assortmentId) {
65
+ throw new Error('Assortment ID is required to find items not in assortment');
66
+ }
67
+ const assortmentItemsInAssortment = await getAssortmentItemsByAssortmentId(assortmentId);
68
+ const items = await (0, items_1.getManyItems)(count + assortmentItemsInAssortment.length);
69
+ const assortmentItemIds = new Set(assortmentItemsInAssortment.map((ai) => ai.itemId));
70
+ const itemsNotInAssortment = items.filter((item) => !assortmentItemIds.has(item.id));
71
+ if (itemsNotInAssortment.length === 0) {
72
+ throw new Error(`All items are already in assortment ${assortmentId}`);
73
+ }
74
+ return itemsNotInAssortment.sort((a, b) => a.id.localeCompare(b.id)); // sorting ensures consistent order of response
75
+ }
76
+ exports.findItemsNotInAssortment = findItemsNotInAssortment;
@@ -0,0 +1,11 @@
1
+ import { AssortmentItem, ProjectItem } from '@contrail/entity-types';
2
+ import { EntitiesClientGetOptions } from '@contrail/sdk';
3
+ export declare function canBatchFetchEntity(entityName: string): entityName is keyof BatchFetchableEntityMap;
4
+ export interface BatchFetchableEntityMap {
5
+ 'project-item': ProjectItem;
6
+ 'assortment-item': AssortmentItem;
7
+ }
8
+ export type BatchFetchOptions = EntitiesClientGetOptions & {
9
+ propertySlugs?: string[];
10
+ };
11
+ export declare function batchFetch<K extends keyof BatchFetchableEntityMap>(entityName: K, options: BatchFetchOptions): Promise<BatchFetchableEntityMap[K][]>;
@@ -0,0 +1,50 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.batchFetch = exports.canBatchFetchEntity = void 0;
4
+ const sdk_1 = require("@contrail/sdk");
5
+ const util_1 = require("@contrail/util");
6
+ // Maps entity names to their types for batch fetching.
7
+ // This allows for type-safe batch fetching of entities
8
+ // such that the Type returned always matches the entity name.
9
+ const BATCH_FETCHABLE_ENTITIES = ['assortment-item', 'project-item'];
10
+ function canBatchFetchEntity(entityName) {
11
+ return BATCH_FETCHABLE_ENTITIES.includes(entityName);
12
+ }
13
+ exports.canBatchFetchEntity = canBatchFetchEntity;
14
+ async function batchFetch(entityName, options) {
15
+ const response = await requestBatchFetch(entityName, options);
16
+ return parseBatchFetchResponse(response);
17
+ }
18
+ exports.batchFetch = batchFetch;
19
+ async function requestBatchFetch(entityName, options) {
20
+ const client = new sdk_1.Entities();
21
+ // NOTE: There is probably a helper somewhere else that manages this conversion
22
+ const optionsClone = { ...options };
23
+ if (optionsClone.criteria) {
24
+ optionsClone.where = optionsClone.criteria;
25
+ }
26
+ delete optionsClone.customParams;
27
+ return client.create({
28
+ entityName: entityName,
29
+ suffix: 'batch-fetch',
30
+ object: optionsClone,
31
+ });
32
+ }
33
+ async function parseBatchFetchResponse(response) {
34
+ if ('results' in response) {
35
+ return response.results;
36
+ }
37
+ else if ('resultsCompressedString' in response) {
38
+ const compressedString = response.resultsCompressedString;
39
+ const jsonData = (0, util_1.decompressFromString)(compressedString);
40
+ return jsonData;
41
+ }
42
+ else if ('resultsDownloadUrl' in response) {
43
+ const downloadUrl = response.resultsDownloadUrl;
44
+ const data = await fetch(downloadUrl).then((res) => res.json());
45
+ return data;
46
+ }
47
+ else {
48
+ throw new Error('Invalid batch fetch response format');
49
+ }
50
+ }
@@ -0,0 +1,3 @@
1
+ export * from './assortment-items';
2
+ export * from './items';
3
+ export * from './project-items';
@@ -0,0 +1,6 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ const tslib_1 = require("tslib");
4
+ tslib_1.__exportStar(require("./assortment-items"), exports);
5
+ tslib_1.__exportStar(require("./items"), exports);
6
+ tslib_1.__exportStar(require("./project-items"), exports);
@@ -0,0 +1,6 @@
1
+ import { Item } from '@contrail/entity-types';
2
+ export type SparseItem = Pick<Item, 'id' | 'itemFamilyId' | 'roles' | 'name'>;
3
+ export declare function getManyItems(maxCount?: number): Promise<SparseItem[]>;
4
+ export declare function getItemFamilies(count: number): Promise<SparseItem[] | undefined>;
5
+ export declare const Roles: readonly ["option", "family"];
6
+ export type Role = (typeof Roles)[number];
@@ -0,0 +1,60 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.Roles = exports.getItemFamilies = exports.getManyItems = void 0;
4
+ const sdk_1 = require("@contrail/sdk");
5
+ const ITEM_FETCH_CEILING = 10000;
6
+ async function getManyItems(maxCount) {
7
+ const client = new sdk_1.Entities();
8
+ const limit = maxCount ?? ITEM_FETCH_CEILING;
9
+ const items = [];
10
+ let nextPageKey = undefined;
11
+ while (true) {
12
+ const response = await client.get({
13
+ entityName: 'item',
14
+ apiVersion: sdk_1.API_VERSION.V2,
15
+ nextPageKey,
16
+ });
17
+ nextPageKey = response.nextPageKey;
18
+ if (response.results.length === 0) {
19
+ break;
20
+ }
21
+ items.push(...response.results);
22
+ if (!nextPageKey) {
23
+ break; // an absent cursor restarts pagination from page one
24
+ }
25
+ if (items.length >= limit) {
26
+ if (maxCount === undefined) {
27
+ console.warn(`Reached maximum item limit of ${limit}. Some items may not be included.`);
28
+ }
29
+ break;
30
+ }
31
+ }
32
+ return items;
33
+ }
34
+ exports.getManyItems = getManyItems;
35
+ async function getItemFamilies(count) {
36
+ return getItems({ roles: ['family'] }, count);
37
+ }
38
+ exports.getItemFamilies = getItemFamilies;
39
+ exports.Roles = ['option', 'family'];
40
+ async function getItems(criteria, count = 100) {
41
+ const client = new sdk_1.Entities();
42
+ const items = [];
43
+ let nextPageKey = undefined;
44
+ do {
45
+ const response = await client.get({
46
+ entityName: 'item',
47
+ criteria,
48
+ nextPageKey,
49
+ apiVersion: sdk_1.API_VERSION.V2,
50
+ });
51
+ nextPageKey = response.nextPageKey;
52
+ if (response.results.length === 0) {
53
+ break;
54
+ }
55
+ const numItemsCanBeAdded = count - items.length;
56
+ const itemsToAdd = response.results.slice(0, numItemsCanBeAdded);
57
+ items.push(...itemsToAdd);
58
+ } while (nextPageKey && items.length < count);
59
+ return items;
60
+ }
@@ -0,0 +1 @@
1
+ export {};
@@ -0,0 +1,19 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ const items_1 = require("./items");
4
+ const mockGet = jest.fn();
5
+ jest.mock('@contrail/sdk', () => ({
6
+ Entities: jest.fn().mockImplementation(() => ({ get: (...args) => mockGet(...args) })),
7
+ API_VERSION: { V2: '2' },
8
+ }));
9
+ describe('getManyItems', () => {
10
+ beforeEach(() => jest.clearAllMocks());
11
+ it('should stop on the last page rather than refetching the first', async () => {
12
+ mockGet.mockImplementation(async ({ nextPageKey }) => nextPageKey === 'page-2'
13
+ ? { results: [{ id: 'b' }], nextPageKey: undefined }
14
+ : { results: [{ id: 'a' }], nextPageKey: 'page-2' });
15
+ const items = await (0, items_1.getManyItems)(10);
16
+ expect(mockGet).toHaveBeenCalledTimes(2);
17
+ expect(items.map((item) => item.id)).toEqual(['a', 'b']);
18
+ });
19
+ });
@@ -0,0 +1,2 @@
1
+ import { Item } from '@contrail/entity-types';
2
+ export declare function findItemsNotInProject(projectId: string): Promise<Item[]>;