@hubspot/local-dev-lib 0.0.2 → 0.0.4

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 (87) hide show
  1. package/config/CLIConfiguration.d.ts +55 -0
  2. package/config/CLIConfiguration.js +392 -0
  3. package/config/configFile.d.ts +21 -0
  4. package/config/configFile.js +109 -0
  5. package/config/configUtils.d.ts +24 -0
  6. package/config/configUtils.js +85 -0
  7. package/config/environment.d.ts +3 -0
  8. package/config/environment.js +64 -0
  9. package/constants/auth.d.ts +24 -0
  10. package/constants/auth.js +31 -0
  11. package/constants/config.d.ts +8 -0
  12. package/constants/config.js +12 -0
  13. package/constants/environments.d.ts +13 -0
  14. package/constants/environments.js +16 -0
  15. package/constants/extensions.d.ts +2 -0
  16. package/constants/extensions.js +23 -0
  17. package/constants/files.d.ts +5 -0
  18. package/constants/files.js +8 -0
  19. package/constants/github.d.ts +4 -0
  20. package/constants/github.js +7 -0
  21. package/constants/index.d.ts +16 -0
  22. package/constants/index.js +12 -0
  23. package/errors/HubSpotAuthError.d.ts +3 -0
  24. package/errors/HubSpotAuthError.js +6 -0
  25. package/errors/fileSystemErrors.d.ts +8 -0
  26. package/errors/fileSystemErrors.js +28 -0
  27. package/errors/standardErrors.d.ts +19 -0
  28. package/errors/standardErrors.js +67 -0
  29. package/http/requestOptions.d.ts +20 -0
  30. package/http/requestOptions.js +27 -0
  31. package/lib/archive.d.ts +7 -0
  32. package/lib/archive.js +111 -0
  33. package/lib/cms/handleFieldsJS.d.ts +32 -0
  34. package/lib/cms/handleFieldsJS.js +143 -0
  35. package/lib/cms/index.d.ts +10 -0
  36. package/lib/cms/index.js +13 -0
  37. package/lib/cms/modules.d.ts +24 -0
  38. package/lib/cms/modules.js +124 -0
  39. package/lib/cms/themes.d.ts +2 -0
  40. package/lib/cms/themes.js +34 -0
  41. package/lib/environment.d.ts +1 -0
  42. package/lib/environment.js +16 -0
  43. package/lib/fs.d.ts +4 -0
  44. package/lib/fs.js +71 -0
  45. package/lib/github.d.ts +17 -0
  46. package/lib/github.js +133 -0
  47. package/lib/gitignore.d.ts +1 -0
  48. package/lib/gitignore.js +76 -0
  49. package/lib/index.d.ts +11 -0
  50. package/lib/index.js +14 -0
  51. package/lib/path.d.ts +10 -0
  52. package/lib/path.js +84 -0
  53. package/lib/text.d.ts +1 -0
  54. package/lib/text.js +16 -0
  55. package/lib/urls.d.ts +2 -0
  56. package/lib/urls.js +20 -0
  57. package/package.json +8 -11
  58. package/types/Accounts.d.ts +50 -0
  59. package/types/Accounts.js +2 -0
  60. package/types/CLIOptions.d.ts +3 -0
  61. package/types/CLIOptions.js +2 -0
  62. package/types/Config.d.ts +10 -0
  63. package/types/Config.js +2 -0
  64. package/types/Error.d.ts +31 -0
  65. package/types/Error.js +2 -0
  66. package/types/Files.d.ts +8 -0
  67. package/types/Files.js +2 -0
  68. package/types/Github.d.ts +58 -0
  69. package/types/Github.js +2 -0
  70. package/types/LogCallbacks.d.ts +6 -0
  71. package/types/LogCallbacks.js +2 -0
  72. package/types/Modules.d.ts +5 -0
  73. package/types/Modules.js +2 -0
  74. package/types/Utils.d.ts +1 -0
  75. package/types/Utils.js +2 -0
  76. package/utils/escapeRegExp.d.ts +1 -0
  77. package/utils/escapeRegExp.js +7 -0
  78. package/utils/fieldsJS.d.ts +3 -0
  79. package/utils/fieldsJS.js +18 -0
  80. package/utils/git.d.ts +4 -0
  81. package/utils/git.js +40 -0
  82. package/utils/lang.d.ts +8 -0
  83. package/utils/lang.js +83 -0
  84. package/utils/logger.d.ts +10 -0
  85. package/utils/logger.js +22 -0
  86. package/utils/modules.d.ts +4 -0
  87. package/utils/modules.js +53 -0
@@ -0,0 +1,55 @@
1
+ import { CLIConfig } from '../types/Config';
2
+ import { CLIAccount, FlatAccountFields, OauthTokenInfo } from '../types/Accounts';
3
+ import { CLIOptions } from '../types/CLIOptions';
4
+ import { LogCallbacksArg } from '../types/LogCallbacks';
5
+ declare const validateLogCallbackKeys: readonly ["noConfig", "noConfigAccounts", "emptyAccountConfig", "noAccountId", "duplicateAccountIds", "duplicateAccountNames", "nameContainsSpaces"];
6
+ declare class CLIConfiguration {
7
+ options: CLIOptions;
8
+ useEnvConfig: boolean;
9
+ config: CLIConfig | null;
10
+ constructor();
11
+ init(options?: CLIOptions): void;
12
+ load(): CLIConfig | null;
13
+ configIsEmpty(): boolean;
14
+ delete(): void;
15
+ write(updatedConfig?: CLIConfig): CLIConfig | null;
16
+ validate(logCallbacks?: LogCallbacksArg<typeof validateLogCallbackKeys>): boolean;
17
+ getAccount(nameOrId: string | number | undefined): CLIAccount | null;
18
+ getAccountId(nameOrId: string | number): number | null;
19
+ getDefaultAccount(): string | number | null;
20
+ getResolvedDefaultAccountForCWD(nameOrId: string | number): CLIAccount | null;
21
+ getConfigAccountIndex(accountId: number): number;
22
+ isAccountInConfig(nameOrId: string | number): boolean;
23
+ getAndLoadConfigIfNeeded(options?: CLIOptions): CLIConfig;
24
+ getEnv(nameOrId?: string | number): string;
25
+ /**
26
+ * @throws {Error}
27
+ */
28
+ updateAccount(updatedAccountFields: FlatAccountFields<OauthTokenInfo>, writeUpdate?: boolean): CLIAccount | null;
29
+ /**
30
+ * @throws {Error}
31
+ */
32
+ updateDefaultAccount(defaultAccount: string | number): CLIConfig | null;
33
+ /**
34
+ * @throws {Error}
35
+ */
36
+ renameAccount(currentName: string, newName: string): void;
37
+ /**
38
+ * @throws {Error}
39
+ */
40
+ removeAccountFromConfig(nameOrId: string | number): boolean;
41
+ /**
42
+ * @throws {Error}
43
+ */
44
+ updateDefaultMode(defaultMode: string): CLIConfig | null;
45
+ /**
46
+ * @throws {Error}
47
+ */
48
+ updateHttpTimeout(timeout: string): CLIConfig | null;
49
+ /**
50
+ * @throws {Error}
51
+ */
52
+ updateAllowUsageTracking(isEnabled: boolean): CLIConfig | null;
53
+ }
54
+ declare const _default: CLIConfiguration;
55
+ export default _default;
@@ -0,0 +1,392 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ const logger_1 = require("../utils/logger");
4
+ const standardErrors_1 = require("../errors/standardErrors");
5
+ const environment_1 = require("./environment");
6
+ const configFile_1 = require("./configFile");
7
+ const text_1 = require("../lib/text");
8
+ const constants_1 = require("../constants");
9
+ const auth_1 = require("../constants/auth");
10
+ const config_1 = require("../constants/config");
11
+ const i18nKey = 'config.cliConfiguration';
12
+ const validateLogCallbackKeys = [
13
+ 'noConfig',
14
+ 'noConfigAccounts',
15
+ 'emptyAccountConfig',
16
+ 'noAccountId',
17
+ 'duplicateAccountIds',
18
+ 'duplicateAccountNames',
19
+ 'nameContainsSpaces',
20
+ ];
21
+ class CLIConfiguration {
22
+ options;
23
+ useEnvConfig;
24
+ config;
25
+ constructor() {
26
+ this.options = {};
27
+ this.useEnvConfig = false;
28
+ this.config = null;
29
+ }
30
+ init(options = {}) {
31
+ this.options = options;
32
+ this.load();
33
+ }
34
+ load() {
35
+ if (this.options.useEnv) {
36
+ const configFromEnv = (0, environment_1.loadConfigFromEnvironment)();
37
+ if (configFromEnv) {
38
+ (0, logger_1.debug)(`${i18nKey}.load.configFromEnv`, {
39
+ accountId: configFromEnv.accounts[0].accountId,
40
+ });
41
+ this.useEnvConfig = true;
42
+ this.config = configFromEnv;
43
+ }
44
+ }
45
+ else {
46
+ const configFromFile = (0, configFile_1.loadConfigFromFile)();
47
+ (0, logger_1.debug)(`${i18nKey}.load.configFromFile`);
48
+ if (!configFromFile) {
49
+ (0, logger_1.debug)(`${i18nKey}.load.empty`);
50
+ this.config = { accounts: [] };
51
+ }
52
+ this.useEnvConfig = false;
53
+ this.config = configFromFile;
54
+ }
55
+ return this.config;
56
+ }
57
+ configIsEmpty() {
58
+ if (!(0, configFile_1.configFileExists)() || (0, configFile_1.configFileIsBlank)()) {
59
+ return true;
60
+ }
61
+ else {
62
+ this.load();
63
+ if (!!this.config &&
64
+ Object.keys(this.config).length === 1 &&
65
+ !!this.config.accounts) {
66
+ return true;
67
+ }
68
+ }
69
+ return false;
70
+ }
71
+ delete() {
72
+ if (!this.useEnvConfig && this.configIsEmpty()) {
73
+ (0, configFile_1.deleteConfigFile)();
74
+ this.config = null;
75
+ }
76
+ }
77
+ write(updatedConfig) {
78
+ if (!this.useEnvConfig) {
79
+ if (updatedConfig) {
80
+ this.config = updatedConfig;
81
+ }
82
+ if (this.config) {
83
+ (0, configFile_1.writeConfigToFile)(this.config);
84
+ }
85
+ }
86
+ return this.config;
87
+ }
88
+ validate(logCallbacks) {
89
+ const validateLogger = (0, logger_1.makeTypedLogger)(logCallbacks, 'config.cliConfiguration.validate');
90
+ if (!this.config) {
91
+ validateLogger('noConfig');
92
+ return false;
93
+ }
94
+ if (!Array.isArray(this.config.accounts)) {
95
+ validateLogger('noConfigAccounts');
96
+ return false;
97
+ }
98
+ const accountIdsMap = {};
99
+ const accountNamesMap = {};
100
+ return this.config.accounts.every(accountConfig => {
101
+ if (!accountConfig) {
102
+ validateLogger('emptyAccountConfig');
103
+ return false;
104
+ }
105
+ if (!accountConfig.accountId) {
106
+ validateLogger('noAccountId');
107
+ return false;
108
+ }
109
+ if (accountIdsMap[accountConfig.accountId]) {
110
+ validateLogger('duplicateAccountIds', {
111
+ accountId: accountConfig.accountId,
112
+ });
113
+ return false;
114
+ }
115
+ if (accountConfig.name) {
116
+ if (accountNamesMap[accountConfig.name]) {
117
+ validateLogger('duplicateAccountNames', {
118
+ accountName: accountConfig.name,
119
+ });
120
+ return false;
121
+ }
122
+ if (/\s+/.test(accountConfig.name)) {
123
+ validateLogger('nameContainsSpaces', {
124
+ accountName: accountConfig.name,
125
+ });
126
+ return false;
127
+ }
128
+ accountNamesMap[accountConfig.name] = true;
129
+ }
130
+ accountIdsMap[accountConfig.accountId] = true;
131
+ return true;
132
+ });
133
+ }
134
+ getAccount(nameOrId) {
135
+ let name = null;
136
+ let accountId = null;
137
+ if (!this.config) {
138
+ return null;
139
+ }
140
+ const nameOrIdToCheck = nameOrId ? nameOrId : this.getDefaultAccount();
141
+ if (!nameOrIdToCheck) {
142
+ return null;
143
+ }
144
+ if (typeof nameOrIdToCheck === 'number') {
145
+ accountId = nameOrIdToCheck;
146
+ }
147
+ else if (/^\d+$/.test(nameOrIdToCheck)) {
148
+ accountId = parseInt(nameOrIdToCheck, 10);
149
+ }
150
+ else {
151
+ name = nameOrIdToCheck;
152
+ }
153
+ if (name) {
154
+ return this.config.accounts.find(a => a.name === name) || null;
155
+ }
156
+ else if (accountId) {
157
+ return this.config.accounts.find(a => accountId === a.accountId) || null;
158
+ }
159
+ return null;
160
+ }
161
+ getAccountId(nameOrId) {
162
+ const account = this.getAccount(nameOrId);
163
+ return account ? account.accountId : null;
164
+ }
165
+ getDefaultAccount() {
166
+ return this.config && this.config.defaultAccount
167
+ ? this.config.defaultAccount
168
+ : null;
169
+ }
170
+ // TODO a util that returns the account to use, respecting the values set in
171
+ // "defaultAccountOverrides"
172
+ // Example "defaultAccountOverrides":
173
+ // - /src/brodgers/customer-project-1: customer-account1
174
+ // - /src/brodgers/customer-project-2: customer-account2
175
+ // "/src/brodgers/customer-project-1" is the path to the project dir
176
+ // "customer-account1" is the name of the account to use as the default for the specified dir
177
+ // These defaults take precedence over the standard default account specified in the config
178
+ getResolvedDefaultAccountForCWD(nameOrId) {
179
+ return this.getAccount(nameOrId);
180
+ }
181
+ getConfigAccountIndex(accountId) {
182
+ return this.config
183
+ ? this.config.accounts.findIndex(account => account.accountId === accountId)
184
+ : -1;
185
+ }
186
+ isAccountInConfig(nameOrId) {
187
+ return (!!this.config && this.config.accounts && !!this.getAccountId(nameOrId));
188
+ }
189
+ getAndLoadConfigIfNeeded(options) {
190
+ if (!this.config) {
191
+ this.init(options);
192
+ }
193
+ return this.config;
194
+ }
195
+ getEnv(nameOrId) {
196
+ const accountConfig = this.getAccount(nameOrId);
197
+ if (accountConfig && accountConfig.accountId && accountConfig.env) {
198
+ return accountConfig.env;
199
+ }
200
+ if (this.config && this.config.env) {
201
+ return this.config.env;
202
+ }
203
+ return constants_1.ENVIRONMENTS.PROD;
204
+ }
205
+ /*
206
+ * Config Update Utils
207
+ */
208
+ /**
209
+ * @throws {Error}
210
+ */
211
+ updateAccount(updatedAccountFields, writeUpdate = true) {
212
+ const { accountId, apiKey, authType, clientId, clientSecret, defaultMode, env, name, parentAccountId, personalAccessKey, sandboxAccountType, scopes, tokenInfo, } = updatedAccountFields;
213
+ if (!accountId) {
214
+ (0, standardErrors_1.throwErrorWithMessage)(`${i18nKey}.updateAccount`);
215
+ }
216
+ if (!this.config) {
217
+ (0, logger_1.debug)(`${i18nKey}.updateAccount.noConfigToUpdate`);
218
+ return null;
219
+ }
220
+ const currentAccountConfig = this.getAccount(accountId);
221
+ let auth;
222
+ if (clientId || clientSecret || scopes || tokenInfo) {
223
+ auth = {
224
+ ...(currentAccountConfig ? currentAccountConfig.auth : {}),
225
+ clientId,
226
+ clientSecret,
227
+ scopes,
228
+ tokenInfo,
229
+ };
230
+ }
231
+ const nextAccountConfig = {
232
+ ...(currentAccountConfig ? currentAccountConfig : {}),
233
+ };
234
+ // Allow everything except for 'undefined' values to override the existing values
235
+ function safelyApplyUpdates(fieldName,
236
+ // eslint-disable-next-line @typescript-eslint/no-explicit-any
237
+ newValue) {
238
+ if (typeof newValue !== 'undefined') {
239
+ nextAccountConfig[fieldName] = newValue;
240
+ }
241
+ }
242
+ const updatedEnv = (0, environment_1.getValidEnv)(env || (currentAccountConfig && currentAccountConfig.env), false);
243
+ const updatedDefaultMode = defaultMode &&
244
+ defaultMode.toLowerCase();
245
+ safelyApplyUpdates('name', name);
246
+ safelyApplyUpdates('env', updatedEnv);
247
+ safelyApplyUpdates('accountId', accountId);
248
+ safelyApplyUpdates('authType', authType);
249
+ safelyApplyUpdates('auth', auth);
250
+ if (nextAccountConfig.authType === auth_1.API_KEY_AUTH_METHOD.value) {
251
+ safelyApplyUpdates('apiKey', apiKey);
252
+ }
253
+ if (typeof updatedDefaultMode !== 'undefined') {
254
+ // eslint-disable-next-line @typescript-eslint/no-explicit-any
255
+ safelyApplyUpdates('defaultMode', config_1.DEFAULT_MODES[updatedDefaultMode]);
256
+ }
257
+ safelyApplyUpdates('personalAccessKey', personalAccessKey);
258
+ safelyApplyUpdates('sandboxAccountType', sandboxAccountType);
259
+ safelyApplyUpdates('parentAccountId', parentAccountId);
260
+ const completedAccountConfig = nextAccountConfig;
261
+ if (currentAccountConfig) {
262
+ (0, logger_1.debug)(`${i18nKey}.updateAccount.updating`, {
263
+ accountId,
264
+ });
265
+ const index = this.getConfigAccountIndex(accountId);
266
+ this.config.accounts[index] = completedAccountConfig;
267
+ (0, logger_1.debug)(`${i18nKey}.updateAccount.addingConfigEntry`, {
268
+ accountId,
269
+ });
270
+ if (this.config.accounts) {
271
+ this.config.accounts.push(completedAccountConfig);
272
+ }
273
+ else {
274
+ this.config.accounts = [completedAccountConfig];
275
+ }
276
+ }
277
+ if (writeUpdate) {
278
+ this.write();
279
+ }
280
+ return completedAccountConfig;
281
+ }
282
+ /**
283
+ * @throws {Error}
284
+ */
285
+ updateDefaultAccount(defaultAccount) {
286
+ if (!this.config) {
287
+ (0, standardErrors_1.throwErrorWithMessage)(`${i18nKey}.noConfigLoaded`);
288
+ }
289
+ if (!defaultAccount ||
290
+ (typeof defaultAccount !== 'number' && typeof defaultAccount !== 'string')) {
291
+ (0, standardErrors_1.throwErrorWithMessage)(`${i18nKey}.updateDefaultAccount`);
292
+ }
293
+ this.config.defaultAccount = defaultAccount;
294
+ return this.write();
295
+ }
296
+ /**
297
+ * @throws {Error}
298
+ */
299
+ renameAccount(currentName, newName) {
300
+ if (!this.config) {
301
+ (0, standardErrors_1.throwErrorWithMessage)(`${i18nKey}.noConfigLoaded`);
302
+ }
303
+ const accountId = this.getAccountId(currentName);
304
+ let accountConfigToRename = null;
305
+ if (accountId) {
306
+ accountConfigToRename = this.getAccount(accountId);
307
+ }
308
+ if (!accountConfigToRename) {
309
+ (0, standardErrors_1.throwErrorWithMessage)(`${i18nKey}.renameAccount`, { currentName });
310
+ }
311
+ if (accountId) {
312
+ this.updateAccount({ accountId, name: newName });
313
+ }
314
+ if (accountConfigToRename.name === this.getDefaultAccount()) {
315
+ this.updateDefaultAccount(newName);
316
+ }
317
+ }
318
+ /**
319
+ * @throws {Error}
320
+ */
321
+ removeAccountFromConfig(nameOrId) {
322
+ if (!this.config) {
323
+ (0, standardErrors_1.throwErrorWithMessage)(`${i18nKey}.noConfigLoaded`);
324
+ }
325
+ const accountId = this.getAccountId(nameOrId);
326
+ if (!accountId) {
327
+ (0, standardErrors_1.throwErrorWithMessage)(`${i18nKey}.removeAccountFromConfig`, { nameOrId });
328
+ }
329
+ let removedAccountIsDefault = false;
330
+ const accountConfig = this.getAccount(accountId);
331
+ if (accountConfig) {
332
+ (0, logger_1.debug)(`${i18nKey}.removeAccountFromConfig`, { accountId });
333
+ const index = this.getConfigAccountIndex(accountId);
334
+ this.config.accounts.splice(index, 1);
335
+ if (this.getDefaultAccount() === accountConfig.name) {
336
+ removedAccountIsDefault = true;
337
+ }
338
+ this.write();
339
+ }
340
+ return removedAccountIsDefault;
341
+ }
342
+ /**
343
+ * @throws {Error}
344
+ */
345
+ updateDefaultMode(defaultMode) {
346
+ if (!this.config) {
347
+ (0, standardErrors_1.throwErrorWithMessage)(`${i18nKey}.noConfigLoaded`);
348
+ }
349
+ const ALL_MODES = Object.values(config_1.DEFAULT_MODES);
350
+ if (!defaultMode || !ALL_MODES.find(m => m === defaultMode)) {
351
+ (0, standardErrors_1.throwErrorWithMessage)(`${i18nKey}.updateDefaultMode`, {
352
+ defaultMode,
353
+ validModes: (0, text_1.commaSeparatedValues)(ALL_MODES),
354
+ });
355
+ }
356
+ this.config.defaultMode = defaultMode;
357
+ return this.write();
358
+ }
359
+ /**
360
+ * @throws {Error}
361
+ */
362
+ updateHttpTimeout(timeout) {
363
+ if (!this.config) {
364
+ (0, standardErrors_1.throwErrorWithMessage)(`${i18nKey}.noConfigLoaded`);
365
+ }
366
+ const parsedTimeout = parseInt(timeout);
367
+ if (isNaN(parsedTimeout) || parsedTimeout < config_1.MIN_HTTP_TIMEOUT) {
368
+ (0, standardErrors_1.throwErrorWithMessage)(`${i18nKey}.updateHttpTimeout`, {
369
+ timeout,
370
+ minTimeout: config_1.MIN_HTTP_TIMEOUT,
371
+ });
372
+ }
373
+ this.config.httpTimeout = parsedTimeout;
374
+ return this.write();
375
+ }
376
+ /**
377
+ * @throws {Error}
378
+ */
379
+ updateAllowUsageTracking(isEnabled) {
380
+ if (!this.config) {
381
+ (0, standardErrors_1.throwErrorWithMessage)(`${i18nKey}.noConfigLoaded`);
382
+ }
383
+ if (typeof isEnabled !== 'boolean') {
384
+ (0, standardErrors_1.throwErrorWithMessage)(`${i18nKey}.updateAllowUsageTracking`, {
385
+ isEnabled: `${isEnabled}`,
386
+ });
387
+ }
388
+ this.config.allowUsageTracking = isEnabled;
389
+ return this.write();
390
+ }
391
+ }
392
+ exports.default = new CLIConfiguration();
@@ -0,0 +1,21 @@
1
+ import { CLIConfig } from '../types/Config';
2
+ export declare function getConfigFilePath(): string;
3
+ export declare function configFileExists(): boolean;
4
+ export declare function configFileIsBlank(): boolean;
5
+ export declare function deleteConfigFile(): void;
6
+ /**
7
+ * @throws {Error}
8
+ */
9
+ export declare function readConfigFile(configPath: string): string;
10
+ /**
11
+ * @throws {Error}
12
+ */
13
+ export declare function parseConfig(configSource: string): CLIConfig;
14
+ /**
15
+ * @throws {Error}
16
+ */
17
+ export declare function loadConfigFromFile(): CLIConfig | null;
18
+ /**
19
+ * @throws {Error}
20
+ */
21
+ export declare function writeConfigToFile(config: CLIConfig): void;
@@ -0,0 +1,109 @@
1
+ "use strict";
2
+ var __importDefault = (this && this.__importDefault) || function (mod) {
3
+ return (mod && mod.__esModule) ? mod : { "default": mod };
4
+ };
5
+ Object.defineProperty(exports, "__esModule", { value: true });
6
+ exports.writeConfigToFile = exports.loadConfigFromFile = exports.parseConfig = exports.readConfigFile = exports.deleteConfigFile = exports.configFileIsBlank = exports.configFileExists = exports.getConfigFilePath = void 0;
7
+ const fs_extra_1 = __importDefault(require("fs-extra"));
8
+ const path_1 = __importDefault(require("path"));
9
+ const os_1 = __importDefault(require("os"));
10
+ const js_yaml_1 = __importDefault(require("js-yaml"));
11
+ const logger_1 = require("../utils/logger");
12
+ const fileSystemErrors_1 = require("../errors/fileSystemErrors");
13
+ const standardErrors_1 = require("../errors/standardErrors");
14
+ const constants_1 = require("../constants");
15
+ const configUtils_1 = require("./configUtils");
16
+ const i18nKey = 'config.configFile';
17
+ function getConfigFilePath() {
18
+ return path_1.default.join(os_1.default.homedir(), constants_1.HUBSPOT_CONFIGURATION_FOLDER, constants_1.HUBSPOT_CONFIGURATION_FILE);
19
+ }
20
+ exports.getConfigFilePath = getConfigFilePath;
21
+ function configFileExists() {
22
+ const configPath = getConfigFilePath();
23
+ return !!configPath && fs_extra_1.default.existsSync(configPath);
24
+ }
25
+ exports.configFileExists = configFileExists;
26
+ function configFileIsBlank() {
27
+ const configPath = getConfigFilePath();
28
+ return !!configPath && fs_extra_1.default.readFileSync(configPath).length === 0;
29
+ }
30
+ exports.configFileIsBlank = configFileIsBlank;
31
+ function deleteConfigFile() {
32
+ const configPath = getConfigFilePath();
33
+ fs_extra_1.default.unlinkSync(configPath);
34
+ }
35
+ exports.deleteConfigFile = deleteConfigFile;
36
+ /**
37
+ * @throws {Error}
38
+ */
39
+ function readConfigFile(configPath) {
40
+ let source = '';
41
+ try {
42
+ source = fs_extra_1.default.readFileSync(configPath).toString();
43
+ }
44
+ catch (err) {
45
+ (0, logger_1.debug)(`${i18nKey}.errorReading`, { configPath });
46
+ (0, fileSystemErrors_1.throwFileSystemError)(err, {
47
+ filepath: configPath,
48
+ read: true,
49
+ });
50
+ }
51
+ return source;
52
+ }
53
+ exports.readConfigFile = readConfigFile;
54
+ /**
55
+ * @throws {Error}
56
+ */
57
+ function parseConfig(configSource) {
58
+ let parsed;
59
+ try {
60
+ parsed = js_yaml_1.default.load(configSource);
61
+ }
62
+ catch (err) {
63
+ (0, standardErrors_1.throwErrorWithMessage)(`${i18nKey}.parsing`, {}, err);
64
+ }
65
+ return parsed;
66
+ }
67
+ exports.parseConfig = parseConfig;
68
+ /**
69
+ * @throws {Error}
70
+ */
71
+ function loadConfigFromFile() {
72
+ const configPath = getConfigFilePath();
73
+ if (configPath) {
74
+ const source = readConfigFile(configPath);
75
+ if (!source) {
76
+ return null;
77
+ }
78
+ return parseConfig(source);
79
+ }
80
+ // TODO: Maybe use log callbacks here
81
+ (0, logger_1.debug)(`${i18nKey}.errorLoading`, { configPath });
82
+ return null;
83
+ }
84
+ exports.loadConfigFromFile = loadConfigFromFile;
85
+ /**
86
+ * @throws {Error}
87
+ */
88
+ function writeConfigToFile(config) {
89
+ let source;
90
+ try {
91
+ source = js_yaml_1.default.dump(JSON.parse(JSON.stringify((0, configUtils_1.getOrderedConfig)(config), null, 2)));
92
+ }
93
+ catch (err) {
94
+ (0, standardErrors_1.throwError)(err);
95
+ }
96
+ const configPath = getConfigFilePath();
97
+ try {
98
+ fs_extra_1.default.ensureFileSync(configPath);
99
+ fs_extra_1.default.writeFileSync(configPath, source);
100
+ (0, logger_1.debug)(`${i18nKey}.writeSuccess`, { configPath });
101
+ }
102
+ catch (err) {
103
+ (0, fileSystemErrors_1.throwFileSystemError)(err, {
104
+ filepath: configPath,
105
+ write: true,
106
+ });
107
+ }
108
+ }
109
+ exports.writeConfigToFile = writeConfigToFile;
@@ -0,0 +1,24 @@
1
+ import { CLIConfig } from '../types/Config';
2
+ import { AuthType, CLIAccount } from '../types/Accounts';
3
+ export declare function getOrderedAccount(unorderedAccount: CLIAccount): CLIAccount;
4
+ export declare function getOrderedConfig(unorderedConfig: CLIConfig): CLIConfig;
5
+ type PersonalAccessKeyOptions = {
6
+ accountId: number;
7
+ personalAccessKey: string;
8
+ env: string;
9
+ };
10
+ type OAuthOptions = {
11
+ accountId: number;
12
+ clientId: string;
13
+ clientSecret: string;
14
+ refreshToken: string;
15
+ scopes: Array<string>;
16
+ env: string;
17
+ };
18
+ type APIKeyOptions = {
19
+ accountId: number;
20
+ apiKey: string;
21
+ env: string;
22
+ };
23
+ export declare function generateConfig(type: AuthType, options: PersonalAccessKeyOptions | OAuthOptions | APIKeyOptions): CLIConfig | null;
24
+ export {};
@@ -0,0 +1,85 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.generateConfig = exports.getOrderedConfig = exports.getOrderedAccount = void 0;
4
+ const logger_1 = require("../utils/logger");
5
+ const auth_1 = require("../constants/auth");
6
+ function getOrderedAccount(unorderedAccount) {
7
+ const { name, accountId, env, authType, ...rest } = unorderedAccount;
8
+ return {
9
+ name,
10
+ accountId,
11
+ env,
12
+ authType,
13
+ ...rest,
14
+ };
15
+ }
16
+ exports.getOrderedAccount = getOrderedAccount;
17
+ function getOrderedConfig(unorderedConfig) {
18
+ const { defaultAccount, defaultMode, httpTimeout, allowUsageTracking, accounts, ...rest } = unorderedConfig;
19
+ return {
20
+ ...(defaultAccount && { defaultAccount }),
21
+ defaultMode,
22
+ httpTimeout,
23
+ allowUsageTracking,
24
+ ...rest,
25
+ accounts: accounts.map(getOrderedAccount),
26
+ };
27
+ }
28
+ exports.getOrderedConfig = getOrderedConfig;
29
+ function generatePersonalAccessKeyAccountConfig({ accountId, personalAccessKey, env, }) {
30
+ return {
31
+ authType: auth_1.PERSONAL_ACCESS_KEY_AUTH_METHOD.value,
32
+ accountId,
33
+ personalAccessKey,
34
+ env,
35
+ };
36
+ }
37
+ function generateOauthAccountConfig({ accountId, clientId, clientSecret, refreshToken, scopes, env, }) {
38
+ return {
39
+ authType: auth_1.OAUTH_AUTH_METHOD.value,
40
+ accountId,
41
+ auth: {
42
+ clientId,
43
+ clientSecret,
44
+ scopes,
45
+ tokenInfo: {
46
+ refreshToken,
47
+ },
48
+ },
49
+ env,
50
+ };
51
+ }
52
+ function generateApiKeyAccountConfig({ accountId, apiKey, env, }) {
53
+ return {
54
+ authType: auth_1.API_KEY_AUTH_METHOD.value,
55
+ accountId,
56
+ apiKey,
57
+ env,
58
+ };
59
+ }
60
+ function generateConfig(type, options) {
61
+ if (!options) {
62
+ return null;
63
+ }
64
+ const config = { accounts: [] };
65
+ let configAccount;
66
+ switch (type) {
67
+ case auth_1.API_KEY_AUTH_METHOD.value:
68
+ configAccount = generateApiKeyAccountConfig(options);
69
+ break;
70
+ case auth_1.PERSONAL_ACCESS_KEY_AUTH_METHOD.value:
71
+ configAccount = generatePersonalAccessKeyAccountConfig(options);
72
+ break;
73
+ case auth_1.OAUTH_AUTH_METHOD.value:
74
+ configAccount = generateOauthAccountConfig(options);
75
+ break;
76
+ default:
77
+ (0, logger_1.debug)('config.configUtils.unknownType', { type });
78
+ return null;
79
+ }
80
+ if (configAccount) {
81
+ config.accounts.push(configAccount);
82
+ }
83
+ return config;
84
+ }
85
+ exports.generateConfig = generateConfig;
@@ -0,0 +1,3 @@
1
+ import { CLIConfig } from '../types/Config';
2
+ export declare function getValidEnv(env?: string | null, useProdDefault?: boolean): string | undefined;
3
+ export declare function loadConfigFromEnvironment(): CLIConfig | null;