@hubspot/local-dev-lib 0.2.2 → 0.2.3-experimental.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 (187) hide show
  1. package/LICENSE +12 -0
  2. package/README.md +17 -0
  3. package/api/appsDev.d.ts +6 -0
  4. package/api/appsDev.js +29 -0
  5. package/api/customObjects.d.ts +8 -7
  6. package/api/customObjects.js +13 -16
  7. package/api/designManager.d.ts +4 -13
  8. package/api/designManager.js +6 -9
  9. package/api/developerTestAccounts.d.ts +7 -0
  10. package/api/developerTestAccounts.js +48 -0
  11. package/api/fileManager.d.ts +5 -4
  12. package/api/fileManager.js +11 -11
  13. package/api/fileMapper.d.ts +8 -7
  14. package/api/fileMapper.js +17 -17
  15. package/api/fileTransport.d.ts +4 -0
  16. package/api/fileTransport.js +39 -0
  17. package/api/functions.d.ts +7 -4
  18. package/api/functions.js +22 -11
  19. package/api/github.d.ts +7 -9
  20. package/api/github.js +31 -13
  21. package/api/hubdb.d.ts +11 -10
  22. package/api/hubdb.js +28 -22
  23. package/api/lighthouseScore.d.ts +4 -4
  24. package/api/lighthouseScore.js +9 -12
  25. package/api/localDevAuth.d.ts +8 -16
  26. package/api/localDevAuth.js +34 -13
  27. package/api/marketplaceValidation.d.ts +4 -4
  28. package/api/marketplaceValidation.js +8 -11
  29. package/api/projects.d.ts +31 -24
  30. package/api/projects.js +164 -44
  31. package/api/sandboxHubs.d.ts +6 -4
  32. package/api/sandboxHubs.js +10 -11
  33. package/api/sandboxSync.d.ts +4 -4
  34. package/api/sandboxSync.js +4 -13
  35. package/api/secrets.d.ts +6 -8
  36. package/api/secrets.js +9 -12
  37. package/api/validateHubl.d.ts +2 -1
  38. package/api/validateHubl.js +3 -6
  39. package/config/CLIConfiguration.d.ts +15 -11
  40. package/config/CLIConfiguration.js +175 -90
  41. package/config/configFile.js +12 -18
  42. package/config/configUtils.d.ts +2 -21
  43. package/config/configUtils.js +5 -4
  44. package/config/config_DEPRECATED.d.ts +6 -8
  45. package/config/config_DEPRECATED.js +79 -25
  46. package/config/environment.js +5 -4
  47. package/config/getAccountIdentifier.d.ts +2 -0
  48. package/config/getAccountIdentifier.js +15 -0
  49. package/config/index.d.ts +14 -8
  50. package/config/index.js +108 -57
  51. package/constants/config.d.ts +18 -1
  52. package/constants/config.js +20 -3
  53. package/constants/environments.d.ts +1 -0
  54. package/constants/environments.js +1 -0
  55. package/constants/extensions.d.ts +2 -0
  56. package/constants/extensions.js +3 -1
  57. package/constants/files.d.ts +2 -2
  58. package/constants/files.js +3 -3
  59. package/errors/errors_DEPRECATED.d.ts +1 -5
  60. package/errors/errors_DEPRECATED.js +2 -2
  61. package/errors/index.d.ts +18 -0
  62. package/errors/index.js +63 -0
  63. package/http/addQueryParams.d.ts +2 -0
  64. package/http/addQueryParams.js +14 -0
  65. package/http/getAxiosConfig.d.ts +6 -3
  66. package/http/getAxiosConfig.js +51 -7
  67. package/http/index.d.ts +11 -12
  68. package/http/index.js +35 -41
  69. package/http/unauthed.d.ts +14 -0
  70. package/http/unauthed.js +38 -0
  71. package/lang/en.json +378 -386
  72. package/lib/archive.d.ts +2 -8
  73. package/lib/archive.js +34 -30
  74. package/lib/cms/functions.d.ts +7 -12
  75. package/lib/cms/functions.js +49 -51
  76. package/lib/cms/handleFieldsJS.js +16 -14
  77. package/lib/cms/modules.d.ts +4 -15
  78. package/lib/cms/modules.js +81 -78
  79. package/lib/cms/processFieldsJs.js +10 -33
  80. package/lib/cms/templates.d.ts +43 -3
  81. package/lib/cms/templates.js +53 -11
  82. package/lib/cms/uploadFolder.d.ts +3 -14
  83. package/lib/cms/uploadFolder.js +58 -42
  84. package/lib/cms/validate.js +1 -1
  85. package/lib/cms/watch.d.ts +2 -18
  86. package/lib/cms/watch.js +63 -68
  87. package/lib/customObjects.js +4 -15
  88. package/lib/fileManager.d.ts +2 -6
  89. package/lib/fileManager.js +54 -65
  90. package/lib/fileMapper.d.ts +4 -15
  91. package/lib/fileMapper.js +67 -88
  92. package/lib/fs.d.ts +1 -1
  93. package/lib/fs.js +10 -6
  94. package/lib/github.d.ts +12 -14
  95. package/lib/github.js +70 -35
  96. package/lib/gitignore.d.ts +2 -0
  97. package/lib/gitignore.js +21 -4
  98. package/lib/hubdb.d.ts +3 -2
  99. package/lib/hubdb.js +11 -9
  100. package/{utils → lib}/notify.js +2 -2
  101. package/lib/oauth.d.ts +2 -5
  102. package/lib/oauth.js +14 -25
  103. package/lib/path.d.ts +3 -0
  104. package/lib/path.js +46 -1
  105. package/lib/personalAccessKey.d.ts +8 -11
  106. package/lib/personalAccessKey.js +75 -38
  107. package/lib/portManager.d.ts +3 -5
  108. package/lib/portManager.js +18 -6
  109. package/lib/trackUsage.js +18 -11
  110. package/lib/urls.js +5 -1
  111. package/models/FileSystemError.d.ts +6 -0
  112. package/models/FileSystemError.js +47 -0
  113. package/models/HubSpotHttpError.d.ts +24 -0
  114. package/models/HubSpotHttpError.js +197 -0
  115. package/models/OAuth2Manager.d.ts +5 -27
  116. package/models/OAuth2Manager.js +41 -64
  117. package/package.json +34 -35
  118. package/types/Accounts.d.ts +103 -3
  119. package/types/Apps.d.ts +77 -0
  120. package/types/Archive.d.ts +9 -0
  121. package/types/Archive.js +2 -0
  122. package/types/Build.d.ts +4 -2
  123. package/types/ComponentStructure.d.ts +30 -10
  124. package/types/Config.d.ts +19 -2
  125. package/types/Deploy.d.ts +3 -2
  126. package/types/DesignManager.d.ts +10 -0
  127. package/types/DesignManager.js +2 -0
  128. package/types/Error.d.ts +9 -5
  129. package/types/FieldsJS.d.ts +1 -0
  130. package/types/FieldsJS.js +2 -0
  131. package/types/FileManager.d.ts +1 -1
  132. package/types/Files.d.ts +43 -4
  133. package/types/Functions.d.ts +52 -0
  134. package/types/Github.d.ts +13 -0
  135. package/types/Http.d.ts +12 -11
  136. package/types/Hubdb.d.ts +9 -0
  137. package/types/MarketplaceValidation.d.ts +7 -3
  138. package/types/Migration.d.ts +28 -0
  139. package/types/Migration.js +10 -0
  140. package/types/Modules.d.ts +11 -0
  141. package/types/PortManager.d.ts +7 -0
  142. package/types/Project.d.ts +30 -0
  143. package/types/ProjectLog.d.ts +9 -0
  144. package/types/ProjectLog.js +2 -0
  145. package/types/Sandbox.d.ts +37 -47
  146. package/types/Schemas.d.ts +56 -0
  147. package/types/Secrets.d.ts +3 -0
  148. package/types/Secrets.js +2 -0
  149. package/types/developerTestAccounts.d.ts +13 -0
  150. package/types/developerTestAccounts.js +2 -0
  151. package/utils/PortManagerServer.d.ts +6 -7
  152. package/utils/PortManagerServer.js +22 -16
  153. package/utils/{getAccountIdentifier.d.ts → accounts.d.ts} +0 -6
  154. package/utils/{getAccountIdentifier.js → accounts.js} +1 -13
  155. package/utils/cms/fieldsJS.d.ts +1 -2
  156. package/utils/cms/modules.js +2 -2
  157. package/utils/detectPort.js +3 -3
  158. package/utils/git.d.ts +1 -7
  159. package/utils/git.js +2 -18
  160. package/errors/apiErrors.d.ts +0 -19
  161. package/errors/apiErrors.js +0 -179
  162. package/errors/fileSystemErrors.d.ts +0 -5
  163. package/errors/fileSystemErrors.js +0 -31
  164. package/errors/standardErrors.d.ts +0 -27
  165. package/errors/standardErrors.js +0 -59
  166. package/lang/lang/en.json +0 -401
  167. package/lib/logging/git.d.ts +0 -2
  168. package/lib/logging/git.js +0 -54
  169. package/lib/logging/logs.d.ts +0 -22
  170. package/lib/logging/logs.js +0 -86
  171. package/lib/logging/table.d.ts +0 -3
  172. package/lib/logging/table.js +0 -47
  173. package/lib/sandboxes.d.ts +0 -14
  174. package/lib/sandboxes.js +0 -71
  175. package/models/HubSpotAuthError.d.ts +0 -12
  176. package/models/HubSpotAuthError.js +0 -20
  177. package/types/LogCallbacks.d.ts +0 -7
  178. package/utils/logger.d.ts +0 -5
  179. package/utils/logger.js +0 -23
  180. package/utils/objectUtils.d.ts +0 -8
  181. package/utils/objectUtils.js +0 -33
  182. /package/{utils → lib}/escapeRegExp.d.ts +0 -0
  183. /package/{utils → lib}/escapeRegExp.js +0 -0
  184. /package/lib/{logging/logger.d.ts → logger.d.ts} +0 -0
  185. /package/lib/{logging/logger.js → logger.js} +0 -0
  186. /package/{utils → lib}/notify.d.ts +0 -0
  187. /package/types/{LogCallbacks.js → Apps.js} +0 -0
package/lib/hubdb.js CHANGED
@@ -9,11 +9,11 @@ const fs_extra_1 = __importDefault(require("fs-extra"));
9
9
  const prettier_1 = __importDefault(require("prettier"));
10
10
  const hubdb_1 = require("../api/hubdb");
11
11
  const path_2 = require("./path");
12
- const standardErrors_1 = require("../errors/standardErrors");
12
+ const lang_1 = require("../utils/lang");
13
13
  const i18nKey = 'lib.hubdb';
14
14
  function validateJsonPath(src) {
15
15
  if (path_1.default.extname(src) !== '.json') {
16
- (0, standardErrors_1.throwErrorWithMessage)(`${i18nKey}.errors.invalidJsonPath`);
16
+ throw new Error((0, lang_1.i18n)(`${i18nKey}.errors.invalidJsonPath`));
17
17
  }
18
18
  }
19
19
  function validateJsonFile(src) {
@@ -22,10 +22,12 @@ function validateJsonFile(src) {
22
22
  stats = fs_extra_1.default.statSync(src);
23
23
  }
24
24
  catch (err) {
25
- (0, standardErrors_1.throwErrorWithMessage)(`${i18nKey}.errors.invalidJsonFile`, { src }, err);
25
+ throw new Error((0, lang_1.i18n)(`${i18nKey}.errors.invalidJsonFile`, { src }), {
26
+ cause: err,
27
+ });
26
28
  }
27
29
  if (!stats.isFile()) {
28
- (0, standardErrors_1.throwErrorWithMessage)(`${i18nKey}.errors.invalidJsonFile`, { src });
30
+ throw new Error((0, lang_1.i18n)(`${i18nKey}.errors.invalidJsonFile`, { src }));
29
31
  }
30
32
  validateJsonPath(src);
31
33
  }
@@ -42,7 +44,7 @@ async function addRowsToHubDbTable(accountId, tableId, rows = []) {
42
44
  if (rowsToUpdate.length > 0) {
43
45
  await (0, hubdb_1.createRows)(accountId, tableId, rowsToUpdate);
44
46
  }
45
- const { rowCount } = await (0, hubdb_1.publishTable)(accountId, tableId);
47
+ const { data: { rowCount }, } = await (0, hubdb_1.publishTable)(accountId, tableId);
46
48
  return {
47
49
  tableId,
48
50
  rowCount,
@@ -53,7 +55,7 @@ async function createHubDbTable(accountId, src) {
53
55
  validateJsonFile(src);
54
56
  const table = fs_extra_1.default.readJsonSync(src);
55
57
  const { rows, ...schema } = table;
56
- const { id } = await (0, hubdb_1.createTable)(accountId, schema);
58
+ const { data: { id }, } = await (0, hubdb_1.createTable)(accountId, schema);
57
59
  return addRowsToHubDbTable(accountId, id, rows);
58
60
  }
59
61
  exports.createHubDbTable = createHubDbTable;
@@ -96,15 +98,15 @@ async function fetchAllRows(accountId, tableId) {
96
98
  let rows = [];
97
99
  let after = null;
98
100
  do {
99
- const response = await (0, hubdb_1.fetchRows)(accountId, tableId, after ? { after } : undefined);
100
- const { paging, results } = response;
101
+ const axiosResponse = await (0, hubdb_1.fetchRows)(accountId, tableId, after ? { after } : undefined);
102
+ const { paging, results } = axiosResponse.data;
101
103
  rows = rows.concat(results);
102
104
  after = paging && paging.next ? paging.next.after : null;
103
105
  } while (after !== null);
104
106
  return rows;
105
107
  }
106
108
  async function downloadHubDbTable(accountId, tableId, dest) {
107
- const table = await (0, hubdb_1.fetchTable)(accountId, tableId);
109
+ const { data: table } = await (0, hubdb_1.fetchTable)(accountId, tableId);
108
110
  dest = path_1.default.resolve((0, path_2.getCwd)(), dest || `${table.name}.hubdb.json`);
109
111
  if (fs_extra_1.default.pathExistsSync(dest)) {
110
112
  validateJsonFile(dest);
@@ -7,7 +7,7 @@ exports.triggerNotify = void 0;
7
7
  const fs_1 = __importDefault(require("fs"));
8
8
  const moment_1 = __importDefault(require("moment"));
9
9
  const debounce_1 = __importDefault(require("debounce"));
10
- const standardErrors_1 = require("../errors/standardErrors");
10
+ const lang_1 = require("../utils/lang");
11
11
  const i18nKey = 'utils.notify';
12
12
  const notifyQueue = [];
13
13
  const notifyPromises = [];
@@ -37,7 +37,7 @@ function notifyFilePath(filePathToNotify, outputToWrite) {
37
37
  fs_1.default.appendFileSync(filePathToNotify, outputToWrite);
38
38
  }
39
39
  catch (e) {
40
- (0, standardErrors_1.throwErrorWithMessage)(`${i18nKey}.errors.filePath`, { filePath: filePathToNotify }, e);
40
+ throw new Error((0, lang_1.i18n)(`${i18nKey}.errors.filePath`, { filePath: filePathToNotify }), { cause: e });
41
41
  }
42
42
  }
43
43
  }
package/lib/oauth.d.ts CHANGED
@@ -1,7 +1,4 @@
1
- import OAuth2Manager from '../models/OAuth2Manager';
1
+ import { OAuth2Manager } from '../models/OAuth2Manager';
2
2
  import { FlatAccountFields } from '../types/Accounts';
3
- import { LogCallbacksArg } from '../types/LogCallbacks';
4
- declare const addOauthToAccountConfigCallbackKeys: readonly ["init", "success"];
5
3
  export declare function getOauthManager(accountId: number, accountConfig: FlatAccountFields): OAuth2Manager | undefined;
6
- export declare function addOauthToAccountConfig(oauth: OAuth2Manager, logCallbacks: LogCallbacksArg<typeof addOauthToAccountConfigCallbackKeys>): void;
7
- export {};
4
+ export declare function addOauthToAccountConfig(oauth: OAuth2Manager): void;
package/lib/oauth.js CHANGED
@@ -1,45 +1,34 @@
1
1
  "use strict";
2
- var __importDefault = (this && this.__importDefault) || function (mod) {
3
- return (mod && mod.__esModule) ? mod : { "default": mod };
4
- };
5
2
  Object.defineProperty(exports, "__esModule", { value: true });
6
3
  exports.addOauthToAccountConfig = exports.getOauthManager = void 0;
7
- const OAuth2Manager_1 = __importDefault(require("../models/OAuth2Manager"));
4
+ const OAuth2Manager_1 = require("../models/OAuth2Manager");
8
5
  const auth_1 = require("../constants/auth");
9
- const standardErrors_1 = require("../errors/standardErrors");
10
- const logger_1 = require("../utils/logger");
11
- const logger_2 = require("../utils/logger");
12
- const getAccountIdentifier_1 = require("../utils/getAccountIdentifier");
6
+ const logger_1 = require("./logger");
7
+ const getAccountIdentifier_1 = require("../config/getAccountIdentifier");
13
8
  const config_1 = require("../config");
9
+ const lang_1 = require("../utils/lang");
14
10
  const i18nKey = 'lib.oauth';
15
- const addOauthToAccountConfigCallbackKeys = ['init', 'success'];
16
11
  const oauthManagers = new Map();
17
12
  function writeOauthTokenInfo(accountConfig) {
18
13
  const accountId = (0, getAccountIdentifier_1.getAccountIdentifier)(accountConfig);
19
- (0, logger_1.debug)(`${i18nKey}.writeTokenInfo`, { portalId: accountId || '' });
14
+ logger_1.logger.debug((0, lang_1.i18n)(`${i18nKey}.writeTokenInfo`, { portalId: accountId || '' }));
20
15
  (0, config_1.updateAccountConfig)(accountConfig);
21
16
  (0, config_1.writeConfig)();
22
17
  }
23
18
  function getOauthManager(accountId, accountConfig) {
24
19
  if (!oauthManagers.has(accountId)) {
25
- oauthManagers.set(accountId, OAuth2Manager_1.default.fromConfig(accountConfig, () => writeOauthTokenInfo(accountConfig)));
20
+ oauthManagers.set(accountId, OAuth2Manager_1.OAuth2Manager.fromConfig(accountConfig, () => writeOauthTokenInfo(accountConfig)));
26
21
  }
27
22
  return oauthManagers.get(accountId);
28
23
  }
29
24
  exports.getOauthManager = getOauthManager;
30
- function addOauthToAccountConfig(oauth, logCallbacks) {
31
- const logger = (0, logger_2.makeTypedLogger)(logCallbacks);
32
- logger('init', `${i18nKey}.addOauthToAccountConfig.init`);
33
- try {
34
- (0, config_1.updateAccountConfig)({
35
- ...oauth.toObj(),
36
- authType: auth_1.AUTH_METHODS.oauth.value,
37
- });
38
- (0, config_1.writeConfig)();
39
- logger('success', `${i18nKey}.addOauthToAccountConfig.success`);
40
- }
41
- catch (err) {
42
- (0, standardErrors_1.throwError)(err);
43
- }
25
+ function addOauthToAccountConfig(oauth) {
26
+ logger_1.logger.log((0, lang_1.i18n)(`${i18nKey}.addOauthToAccountConfig.init`));
27
+ (0, config_1.updateAccountConfig)({
28
+ ...oauth.account,
29
+ authType: auth_1.AUTH_METHODS.oauth.value,
30
+ });
31
+ (0, config_1.writeConfig)();
32
+ logger_1.logger.success((0, lang_1.i18n)(`${i18nKey}.addOauthToAccountConfig.success`));
44
33
  }
45
34
  exports.addOauthToAccountConfig = addOauthToAccountConfig;
package/lib/path.d.ts CHANGED
@@ -9,3 +9,6 @@ export declare function getExt(filepath: string): string;
9
9
  export declare function getAllowedExtensions(allowList?: Array<string>): Set<string>;
10
10
  export declare function isAllowedExtension(filepath: string, allowList?: Array<string>): boolean;
11
11
  export declare function getAbsoluteFilePath(_path: string): string;
12
+ export declare function sanitizeFileName(fileName: string): string;
13
+ export declare function isValidPath(_path: string): boolean;
14
+ export declare function untildify(pathWithTilde: string): string;
package/lib/path.js CHANGED
@@ -3,10 +3,11 @@ var __importDefault = (this && this.__importDefault) || function (mod) {
3
3
  return (mod && mod.__esModule) ? mod : { "default": mod };
4
4
  };
5
5
  Object.defineProperty(exports, "__esModule", { value: true });
6
- exports.getAbsoluteFilePath = exports.isAllowedExtension = exports.getAllowedExtensions = exports.getExt = exports.getCwd = exports.splitHubSpotPath = exports.splitLocalPath = exports.convertToLocalFileSystemPath = exports.convertToUnixPath = void 0;
6
+ exports.untildify = exports.isValidPath = exports.sanitizeFileName = exports.getAbsoluteFilePath = exports.isAllowedExtension = exports.getAllowedExtensions = exports.getExt = exports.getCwd = exports.splitHubSpotPath = exports.splitLocalPath = exports.convertToLocalFileSystemPath = exports.convertToUnixPath = void 0;
7
7
  const path_1 = __importDefault(require("path"));
8
8
  const unixify_1 = __importDefault(require("unixify"));
9
9
  const extensions_1 = require("../constants/extensions");
10
+ const os_1 = __importDefault(require("os"));
10
11
  function convertToUnixPath(_path) {
11
12
  return (0, unixify_1.default)(path_1.default.normalize(_path));
12
13
  }
@@ -87,3 +88,47 @@ function getAbsoluteFilePath(_path) {
87
88
  return path_1.default.resolve(getCwd(), _path);
88
89
  }
89
90
  exports.getAbsoluteFilePath = getAbsoluteFilePath;
91
+ // Reserved names (Windows specific)
92
+ const reservedNames = /^(CON|PRN|AUX|NUL|COM[1-9]|LPT[1-9])$/i;
93
+ // Based on the node-sanitize-filename package: https://github.com/parshap/node-sanitize-filename/blob/master/index.js
94
+ function sanitizeFileName(fileName) {
95
+ // Windows invalid/control characters
96
+ // eslint-disable-next-line no-control-regex
97
+ const invalidChars = /[<>:"/|?*\x00-\x1F]/g;
98
+ //Replace invalid characters with dash
99
+ let sanitizedFileName = fileName.replace(invalidChars, '-');
100
+ // Removes trailing periods and spaces for Windows
101
+ sanitizedFileName = sanitizedFileName.replace(/[. ]+$/, '');
102
+ //Reserved names check for Windows
103
+ if (reservedNames.test(sanitizedFileName)) {
104
+ sanitizedFileName = `-${sanitizedFileName}`;
105
+ }
106
+ return sanitizedFileName;
107
+ }
108
+ exports.sanitizeFileName = sanitizeFileName;
109
+ // Based on the node-sanitize-filename package: https://github.com/parshap/node-sanitize-filename/blob/master/index.js
110
+ function isValidPath(_path) {
111
+ // Invalid characters excluding forward slash
112
+ // eslint-disable-next-line no-control-regex
113
+ const invalidChars = /[<>:"|?*\x00-\x1F]/;
114
+ const baseName = path_1.default.basename(_path);
115
+ if (invalidChars.test(baseName)) {
116
+ return false;
117
+ }
118
+ if (reservedNames.test(baseName)) {
119
+ return false;
120
+ }
121
+ return true;
122
+ }
123
+ exports.isValidPath = isValidPath;
124
+ // Based on the untildify package: https://github.com/sindresorhus/untildify/blob/main/index.js
125
+ function untildify(pathWithTilde) {
126
+ const homeDirectory = os_1.default.homedir();
127
+ if (typeof pathWithTilde !== 'string') {
128
+ throw new TypeError(`Expected a string, got ${typeof pathWithTilde}`);
129
+ }
130
+ return homeDirectory
131
+ ? pathWithTilde.replace(/^~(?=$|\/|\\)/, homeDirectory)
132
+ : pathWithTilde;
133
+ }
134
+ exports.untildify = untildify;
@@ -1,14 +1,11 @@
1
- import { CLIAccount } from '../types/Accounts';
1
+ import { CLIAccount, ScopeGroupAuthorization } from '../types/Accounts';
2
2
  import { Environment } from '../types/Config';
3
- type AccessToken = {
4
- portalId: number;
5
- accessToken: string;
6
- expiresAt: string;
7
- scopeGroups: Array<string>;
8
- encodedOAuthRefreshToken: string;
9
- hubName: string;
10
- };
3
+ import { AccessToken } from '../types/Accounts';
11
4
  export declare function getAccessToken(personalAccessKey: string, env?: Environment, accountId?: number): Promise<AccessToken>;
12
- export declare function accessTokenForPersonalAccessKey(accountId: number): Promise<string | undefined>;
5
+ export declare function accessTokenForPersonalAccessKey(accountId: number, forceRefresh?: boolean): Promise<string | undefined>;
6
+ export declare function enabledFeaturesForPersonalAccessKey(accountId: number): Promise<{
7
+ [key: string]: number;
8
+ } | undefined>;
9
+ export declare function scopesOnAccessToken(accountId: number): Promise<Array<string>>;
10
+ export declare function authorizedScopesForPortalAndUser(accountId: number): Promise<Array<ScopeGroupAuthorization>>;
13
11
  export declare function updateConfigWithAccessToken(token: AccessToken, personalAccessKey: string, env?: Environment, name?: string, makeDefault?: boolean): Promise<CLIAccount | null>;
14
- export {};
@@ -3,45 +3,42 @@ var __importDefault = (this && this.__importDefault) || function (mod) {
3
3
  return (mod && mod.__esModule) ? mod : { "default": mod };
4
4
  };
5
5
  Object.defineProperty(exports, "__esModule", { value: true });
6
- exports.updateConfigWithAccessToken = exports.accessTokenForPersonalAccessKey = exports.getAccessToken = void 0;
6
+ exports.updateConfigWithAccessToken = exports.authorizedScopesForPortalAndUser = exports.scopesOnAccessToken = exports.enabledFeaturesForPersonalAccessKey = exports.accessTokenForPersonalAccessKey = exports.getAccessToken = void 0;
7
7
  const moment_1 = __importDefault(require("moment"));
8
8
  const environments_1 = require("../constants/environments");
9
9
  const auth_1 = require("../constants/auth");
10
- const standardErrors_1 = require("../errors/standardErrors");
11
10
  const localDevAuth_1 = require("../api/localDevAuth");
12
11
  const sandboxHubs_1 = require("../api/sandboxHubs");
13
12
  const config_1 = require("../config");
13
+ const config_2 = require("../constants/config");
14
+ const developerTestAccounts_1 = require("../api/developerTestAccounts");
15
+ const logger_1 = require("./logger");
16
+ const CLIConfiguration_1 = require("../config/CLIConfiguration");
17
+ const lang_1 = require("../utils/lang");
18
+ const errors_1 = require("../errors");
14
19
  const i18nKey = 'lib.personalAccessKey';
15
20
  const refreshRequests = new Map();
16
21
  function getRefreshKey(personalAccessKey, expiration) {
17
22
  return `${personalAccessKey}-${expiration || 'fresh'}`;
18
23
  }
19
24
  async function getAccessToken(personalAccessKey, env = environments_1.ENVIRONMENTS.PROD, accountId) {
20
- let response;
21
- try {
22
- response = await (0, localDevAuth_1.fetchAccessToken)(personalAccessKey, env, accountId);
23
- }
24
- catch (e) {
25
- const error = e;
26
- if (error.response) {
27
- (0, standardErrors_1.throwAuthErrorWithMessage)(`${i18nKey}.errors.invalidPersonalAccessKey`, { errorMessage: error.response.data.message || '' }, error);
28
- }
29
- else {
30
- (0, standardErrors_1.throwError)(e);
31
- }
32
- }
25
+ const axiosResponse = await (0, localDevAuth_1.fetchAccessToken)(personalAccessKey, env, accountId);
26
+ const response = axiosResponse.data;
33
27
  return {
34
28
  portalId: response.hubId,
35
29
  accessToken: response.oauthAccessToken,
36
30
  expiresAt: (0, moment_1.default)(response.expiresAtMillis).toISOString(),
37
31
  scopeGroups: response.scopeGroups,
32
+ enabledFeatures: response.enabledFeatures,
38
33
  encodedOAuthRefreshToken: response.encodedOAuthRefreshToken,
39
34
  hubName: response.hubName,
35
+ accountType: response.accountType,
40
36
  };
41
37
  }
42
38
  exports.getAccessToken = getAccessToken;
43
39
  async function refreshAccessToken(personalAccessKey, env = environments_1.ENVIRONMENTS.PROD, accountId) {
44
- const { accessToken, expiresAt } = await getAccessToken(personalAccessKey, env, accountId);
40
+ const accessTokenResponse = await getAccessToken(personalAccessKey, env, accountId);
41
+ const { accessToken, expiresAt } = accessTokenResponse;
45
42
  const config = (0, config_1.getAccountConfig)(accountId);
46
43
  (0, config_1.updateAccountConfig)({
47
44
  env,
@@ -53,20 +50,20 @@ async function refreshAccessToken(personalAccessKey, env = environments_1.ENVIRO
53
50
  },
54
51
  });
55
52
  (0, config_1.writeConfig)();
56
- return accessToken;
53
+ return accessTokenResponse;
57
54
  }
58
55
  async function getNewAccessToken(accountId, personalAccessKey, expiresAt, env) {
59
56
  const key = getRefreshKey(personalAccessKey, expiresAt);
60
57
  if (refreshRequests.has(key)) {
61
58
  return refreshRequests.get(key);
62
59
  }
63
- let accessToken;
60
+ let accessTokenResponse;
64
61
  try {
65
62
  const refreshAccessPromise = refreshAccessToken(personalAccessKey, env, accountId);
66
63
  if (key) {
67
64
  refreshRequests.set(key, refreshAccessPromise);
68
65
  }
69
- accessToken = await refreshAccessPromise;
66
+ accessTokenResponse = await refreshAccessPromise;
70
67
  }
71
68
  catch (e) {
72
69
  if (key) {
@@ -74,57 +71,97 @@ async function getNewAccessToken(accountId, personalAccessKey, expiresAt, env) {
74
71
  }
75
72
  throw e;
76
73
  }
77
- return accessToken;
74
+ return accessTokenResponse;
75
+ }
76
+ async function getNewAccessTokenByAccountId(accountId) {
77
+ const account = (0, config_1.getAccountConfig)(accountId);
78
+ if (!account) {
79
+ throw new Error((0, lang_1.i18n)(`${i18nKey}.errors.accountNotFound`, { accountId }));
80
+ }
81
+ const { auth, personalAccessKey, env } = account;
82
+ const accessTokenResponse = await getNewAccessToken(accountId, personalAccessKey, auth?.tokenInfo?.expiresAt, env);
83
+ return accessTokenResponse;
78
84
  }
79
- async function accessTokenForPersonalAccessKey(accountId) {
85
+ async function accessTokenForPersonalAccessKey(accountId, forceRefresh = false) {
80
86
  const account = (0, config_1.getAccountConfig)(accountId);
81
87
  if (!account) {
82
- (0, standardErrors_1.throwErrorWithMessage)(`${i18nKey}.errors.accountNotFound`, { accountId });
88
+ throw new Error((0, lang_1.i18n)(`${i18nKey}.errors.accountNotFound`, { accountId }));
83
89
  }
84
90
  const { auth, personalAccessKey, env } = account;
85
91
  const authTokenInfo = auth && auth.tokenInfo;
86
92
  const authDataExists = authTokenInfo && auth?.tokenInfo?.accessToken;
87
93
  if (!authDataExists ||
94
+ forceRefresh ||
88
95
  (0, moment_1.default)().add(5, 'minutes').isAfter((0, moment_1.default)(authTokenInfo.expiresAt))) {
89
- return getNewAccessToken(accountId, personalAccessKey, authTokenInfo && authTokenInfo.expiresAt, env);
96
+ return getNewAccessToken(accountId, personalAccessKey, authTokenInfo && authTokenInfo.expiresAt, env).then(tokenInfo => tokenInfo.accessToken);
90
97
  }
91
98
  return auth?.tokenInfo?.accessToken;
92
99
  }
93
100
  exports.accessTokenForPersonalAccessKey = accessTokenForPersonalAccessKey;
101
+ async function enabledFeaturesForPersonalAccessKey(accountId) {
102
+ const accessTokenResponse = await getNewAccessTokenByAccountId(accountId);
103
+ return accessTokenResponse?.enabledFeatures;
104
+ }
105
+ exports.enabledFeaturesForPersonalAccessKey = enabledFeaturesForPersonalAccessKey;
106
+ async function scopesOnAccessToken(accountId) {
107
+ return (await getNewAccessTokenByAccountId(accountId)).scopeGroups;
108
+ }
109
+ exports.scopesOnAccessToken = scopesOnAccessToken;
110
+ async function authorizedScopesForPortalAndUser(accountId) {
111
+ return (await (0, localDevAuth_1.fetchScopeAuthorizationData)(accountId)).data.results;
112
+ }
113
+ exports.authorizedScopesForPortalAndUser = authorizedScopesForPortalAndUser;
94
114
  async function updateConfigWithAccessToken(token, personalAccessKey, env, name, makeDefault = false) {
95
- const { portalId, accessToken, expiresAt } = token;
115
+ const { portalId, accessToken, expiresAt, accountType } = token;
96
116
  const accountEnv = env || (0, config_1.getEnv)(name);
97
- let hubInfo;
117
+ let parentAccountId;
98
118
  try {
99
- hubInfo = await (0, sandboxHubs_1.fetchSandboxHubData)(accessToken, portalId, accountEnv);
119
+ if (accountType === config_2.HUBSPOT_ACCOUNT_TYPES.STANDARD_SANDBOX ||
120
+ accountType === config_2.HUBSPOT_ACCOUNT_TYPES.DEVELOPMENT_SANDBOX) {
121
+ const { data: sandboxDataResponse } = await (0, sandboxHubs_1.fetchSandboxHubData)(accessToken, portalId, accountEnv);
122
+ if (sandboxDataResponse.parentHubId) {
123
+ parentAccountId = sandboxDataResponse.parentHubId;
124
+ }
125
+ }
100
126
  }
101
127
  catch (err) {
102
- // Ignore error, returns 404 if account is not a sandbox
128
+ // Log error but do not throw
129
+ if ((0, errors_1.isHubSpotHttpError)(err)) {
130
+ logger_1.logger.debug(err.message);
131
+ }
132
+ logger_1.logger.debug(err);
103
133
  }
104
- let sandboxAccountType = null;
105
- let parentAccountId = null;
106
- if (hubInfo) {
107
- if (hubInfo.type !== undefined) {
108
- sandboxAccountType = hubInfo.type === null ? 'STANDARD' : hubInfo.type;
134
+ try {
135
+ if (accountType === config_2.HUBSPOT_ACCOUNT_TYPES.DEVELOPER_TEST) {
136
+ const { data: developerTestAccountResponse } = await (0, developerTestAccounts_1.fetchDeveloperTestAccountData)(accessToken, portalId, accountEnv);
137
+ if (developerTestAccountResponse) {
138
+ parentAccountId = developerTestAccountResponse.parentPortalId;
139
+ }
109
140
  }
110
- if (hubInfo.parentHubId) {
111
- parentAccountId = hubInfo.parentHubId;
141
+ }
142
+ catch (err) {
143
+ // Log error but do not throw
144
+ if ((0, errors_1.isHubSpotHttpError)(err)) {
145
+ logger_1.logger.debug(err.message);
112
146
  }
147
+ logger_1.logger.debug(err);
113
148
  }
114
- const updatedConfig = (0, config_1.updateAccountConfig)({
149
+ const updatedAccount = (0, config_1.updateAccountConfig)({
115
150
  accountId: portalId,
151
+ accountType,
116
152
  personalAccessKey,
117
153
  name,
118
154
  authType: auth_1.PERSONAL_ACCESS_KEY_AUTH_METHOD.value,
119
155
  tokenInfo: { accessToken, expiresAt },
120
- sandboxAccountType,
121
156
  parentAccountId,
122
157
  env: accountEnv,
123
158
  });
124
- (0, config_1.writeConfig)();
159
+ if (!CLIConfiguration_1.CLIConfiguration.isActive()) {
160
+ (0, config_1.writeConfig)();
161
+ }
125
162
  if (makeDefault && name) {
126
163
  (0, config_1.updateDefaultAccount)(name);
127
164
  }
128
- return updatedConfig;
165
+ return updatedAccount;
129
166
  }
130
167
  exports.updateConfigWithAccessToken = updateConfigWithAccessToken;
@@ -1,13 +1,11 @@
1
+ import { RequestPortsData } from '../types/PortManager';
1
2
  export declare const BASE_URL: string;
3
+ export declare function isPortManagerPortAvailable(): Promise<boolean>;
4
+ export declare function isPortManagerServerRunning(): Promise<boolean>;
2
5
  export declare function startPortManagerServer(): Promise<void>;
3
6
  export declare function stopPortManagerServer(): Promise<void>;
4
- type RequestPortsData = {
5
- instanceId: string;
6
- port?: number;
7
- };
8
7
  export declare function requestPorts(portData: Array<RequestPortsData>): Promise<{
9
8
  [instanceId: string]: number;
10
9
  }>;
11
10
  export declare function deleteServerInstance(serverInstanceId: string): Promise<void>;
12
11
  export declare function portManagerHasActiveServers(): Promise<boolean>;
13
- export {};
@@ -3,20 +3,32 @@ var __importDefault = (this && this.__importDefault) || function (mod) {
3
3
  return (mod && mod.__esModule) ? mod : { "default": mod };
4
4
  };
5
5
  Object.defineProperty(exports, "__esModule", { value: true });
6
- exports.portManagerHasActiveServers = exports.deleteServerInstance = exports.requestPorts = exports.stopPortManagerServer = exports.startPortManagerServer = exports.BASE_URL = void 0;
6
+ exports.portManagerHasActiveServers = exports.deleteServerInstance = exports.requestPorts = exports.stopPortManagerServer = exports.startPortManagerServer = exports.isPortManagerServerRunning = exports.isPortManagerPortAvailable = exports.BASE_URL = void 0;
7
7
  const axios_1 = __importDefault(require("axios"));
8
- const PortManagerServer_1 = __importDefault(require("../utils/PortManagerServer"));
9
- const detectPort_1 = require("../utils/detectPort");
8
+ const PortManagerServer_1 = require("../utils/PortManagerServer");
10
9
  const ports_1 = require("../constants/ports");
10
+ const detectPort_1 = require("../utils/detectPort");
11
+ const logger_1 = require("./logger");
11
12
  exports.BASE_URL = `http://localhost:${ports_1.PORT_MANAGER_SERVER_PORT}`;
13
+ async function isPortManagerPortAvailable() {
14
+ return ((await (0, detectPort_1.detectPort)(ports_1.PORT_MANAGER_SERVER_PORT)) === ports_1.PORT_MANAGER_SERVER_PORT);
15
+ }
16
+ exports.isPortManagerPortAvailable = isPortManagerPortAvailable;
12
17
  async function isPortManagerServerRunning() {
13
- const port = await (0, detectPort_1.detectPort)(ports_1.PORT_MANAGER_SERVER_PORT);
14
- return port !== ports_1.PORT_MANAGER_SERVER_PORT;
18
+ try {
19
+ const { data } = await axios_1.default.get(`${exports.BASE_URL}${PortManagerServer_1.HEALTH_CHECK_PATH}`);
20
+ return data.status === PortManagerServer_1.SERVICE_HEALTHY;
21
+ }
22
+ catch (e) {
23
+ logger_1.logger.debug(e);
24
+ return false;
25
+ }
15
26
  }
27
+ exports.isPortManagerServerRunning = isPortManagerServerRunning;
16
28
  async function startPortManagerServer() {
17
29
  const isRunning = await isPortManagerServerRunning();
18
30
  if (!isRunning) {
19
- await PortManagerServer_1.default.init();
31
+ await PortManagerServer_1.PortManagerServer.init();
20
32
  }
21
33
  }
22
34
  exports.startPortManagerServer = startPortManagerServer;
package/lib/trackUsage.js CHANGED
@@ -6,10 +6,11 @@ Object.defineProperty(exports, "__esModule", { value: true });
6
6
  exports.trackUsage = void 0;
7
7
  const axios_1 = __importDefault(require("axios"));
8
8
  const getAxiosConfig_1 = require("../http/getAxiosConfig");
9
- const logger_1 = require("../utils/logger");
10
- const http_1 = __importDefault(require("../http"));
9
+ const logger_1 = require("./logger");
10
+ const http_1 = require("../http");
11
11
  const config_1 = require("../config");
12
12
  const fileMapper_1 = require("../api/fileMapper");
13
+ const lang_1 = require("../utils/lang");
13
14
  const i18nKey = 'lib.trackUsage';
14
15
  async function trackUsage(eventName, eventClass, meta = {}, accountId) {
15
16
  const usageEvent = {
@@ -31,17 +32,23 @@ async function trackUsage(eventName, eventClass, meta = {}, accountId) {
31
32
  analyticsEndpoint = 'vscode-extension-usage';
32
33
  break;
33
34
  default:
34
- (0, logger_1.debug)(`${i18nKey}.invalidEvent`, { eventName });
35
+ logger_1.logger.debug((0, lang_1.i18n)(`${i18nKey}.invalidEvent`, { eventName }));
35
36
  }
36
37
  const path = `${fileMapper_1.FILE_MAPPER_API_PATH}/${analyticsEndpoint}`;
37
38
  const accountConfig = accountId && (0, config_1.getAccountConfig)(accountId);
38
39
  if (accountConfig && accountConfig.authType === 'personalaccesskey') {
39
- (0, logger_1.debug)(`${i18nKey}.sendingEventAuthenticated`);
40
- return http_1.default.post(accountId, {
41
- url: `${path}/authenticated`,
42
- data: usageEvent,
43
- resolveWithFullResponse: true,
44
- });
40
+ logger_1.logger.debug((0, lang_1.i18n)(`${i18nKey}.sendingEventAuthenticated`));
41
+ try {
42
+ await http_1.http.post(accountId, {
43
+ url: `${path}/authenticated`,
44
+ data: usageEvent,
45
+ resolveWithFullResponse: true,
46
+ });
47
+ return;
48
+ }
49
+ catch (e) {
50
+ logger_1.logger.debug((0, lang_1.i18n)(`${i18nKey}.retryingEventUnauthenticated`));
51
+ }
45
52
  }
46
53
  const env = (0, config_1.getEnv)(accountId);
47
54
  const axiosConfig = (0, getAxiosConfig_1.getAxiosConfig)({
@@ -50,7 +57,7 @@ async function trackUsage(eventName, eventClass, meta = {}, accountId) {
50
57
  data: usageEvent,
51
58
  resolveWithFullResponse: true,
52
59
  });
53
- (0, logger_1.debug)(`${i18nKey}.sendingEventUnauthenticated`);
54
- (0, axios_1.default)({ ...axiosConfig, method: 'post' });
60
+ logger_1.logger.debug((0, lang_1.i18n)(`${i18nKey}.sendingEventUnauthenticated`));
61
+ return (0, axios_1.default)({ ...axiosConfig, method: 'post' });
55
62
  }
56
63
  exports.trackUsage = trackUsage;
package/lib/urls.js CHANGED
@@ -11,7 +11,11 @@ function getEnvUrlString(env) {
11
11
  const getHubSpotWebsiteOrigin = (env) => `https://app.hubspot${getEnvUrlString(env)}.com`;
12
12
  exports.getHubSpotWebsiteOrigin = getHubSpotWebsiteOrigin;
13
13
  function getHubSpotApiOrigin(env, useLocalHost) {
14
- let domain = process.env.HUBAPI_DOMAIN_OVERRIDE;
14
+ let domain;
15
+ const domainOverride = process.env.HUBAPI_DOMAIN_OVERRIDE;
16
+ if (domainOverride && typeof domainOverride === 'string') {
17
+ domain = `${domainOverride}${getEnvUrlString(env)}`;
18
+ }
15
19
  if (!domain || typeof domain !== 'string') {
16
20
  domain = `${useLocalHost ? 'local' : 'api'}.hubapi${getEnvUrlString(env)}`;
17
21
  }
@@ -0,0 +1,6 @@
1
+ import { FileSystemErrorContext } from '../types/Error';
2
+ export declare class FileSystemError extends Error {
3
+ private context;
4
+ constructor(options?: ErrorOptions, context?: FileSystemErrorContext);
5
+ toString(): string;
6
+ }
@@ -0,0 +1,47 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.FileSystemError = void 0;
4
+ const lang_1 = require("../utils/lang");
5
+ const errors_1 = require("../errors");
6
+ const i18nKey = 'errors.fileSystemErrors';
7
+ class FileSystemError extends Error {
8
+ context;
9
+ constructor(options, context) {
10
+ super('', options);
11
+ this.name = 'FileSystemError';
12
+ this.context = context;
13
+ if (context) {
14
+ let fileAction = '';
15
+ if (context.operation === 'read') {
16
+ fileAction = (0, lang_1.i18n)(`${i18nKey}.readAction`);
17
+ }
18
+ else if (context.operation === 'write') {
19
+ fileAction = (0, lang_1.i18n)(`${i18nKey}.writeAction`);
20
+ }
21
+ else {
22
+ fileAction = (0, lang_1.i18n)(`${i18nKey}.otherAction`);
23
+ }
24
+ const filepath = context.filepath
25
+ ? `"${context.filepath}"`
26
+ : (0, lang_1.i18n)(`${i18nKey}.unknownFilepath`);
27
+ const messages = [
28
+ (0, lang_1.i18n)(`${i18nKey}.baseMessage`, { fileAction, filepath }),
29
+ ];
30
+ // Many `fs` errors will be `SystemError`s
31
+ if ((0, errors_1.isSystemError)(options?.cause)) {
32
+ messages.push((0, lang_1.i18n)(`${i18nKey}.baseMessage`, {
33
+ errorMessage: options?.cause?.message || '',
34
+ }));
35
+ }
36
+ this.message = messages.join(' ');
37
+ }
38
+ }
39
+ toString() {
40
+ let baseString = `${this.name}: ${this.message}`;
41
+ if (this.context) {
42
+ baseString = `${baseString} context: ${this.context}`;
43
+ }
44
+ return baseString;
45
+ }
46
+ }
47
+ exports.FileSystemError = FileSystemError;