@hubspot/local-dev-lib 0.2.3 → 0.3.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 (54) hide show
  1. package/api/sandboxHubs.d.ts +1 -1
  2. package/config/CLIConfiguration.d.ts +4 -4
  3. package/config/CLIConfiguration.js +42 -33
  4. package/config/configFile.js +5 -4
  5. package/config/configUtils.js +3 -2
  6. package/config/config_DEPRECATED.d.ts +2 -1
  7. package/config/config_DEPRECATED.js +23 -3
  8. package/config/environment.js +5 -4
  9. package/config/index.d.ts +2 -1
  10. package/config/index.js +8 -1
  11. package/constants/config.d.ts +7 -0
  12. package/constants/config.js +8 -1
  13. package/errors/apiErrors.d.ts +7 -2
  14. package/errors/apiErrors.js +12 -11
  15. package/errors/standardErrors.d.ts +1 -1
  16. package/http/index.d.ts +2 -4
  17. package/http/index.js +6 -7
  18. package/lang/en.json +10 -10
  19. package/lang/lang/en.json +10 -10
  20. package/lib/archive.d.ts +1 -3
  21. package/lib/archive.js +14 -16
  22. package/lib/cms/functions.d.ts +1 -3
  23. package/lib/cms/functions.js +25 -32
  24. package/lib/cms/handleFieldsJS.js +6 -5
  25. package/lib/cms/modules.d.ts +2 -3
  26. package/lib/cms/modules.js +16 -9
  27. package/lib/cms/templates.d.ts +1 -3
  28. package/lib/cms/templates.js +6 -7
  29. package/lib/cms/uploadFolder.d.ts +1 -3
  30. package/lib/cms/uploadFolder.js +14 -16
  31. package/lib/cms/watch.d.ts +1 -4
  32. package/lib/cms/watch.js +34 -47
  33. package/lib/fileManager.d.ts +2 -6
  34. package/lib/fileManager.js +31 -42
  35. package/lib/fileMapper.d.ts +2 -4
  36. package/lib/fileMapper.js +24 -35
  37. package/lib/github.d.ts +3 -4
  38. package/lib/github.js +35 -14
  39. package/lib/oauth.d.ts +1 -4
  40. package/lib/oauth.js +7 -9
  41. package/lib/personalAccessKey.js +19 -2
  42. package/lib/sandboxes.d.ts +1 -1
  43. package/lib/sandboxes.js +7 -8
  44. package/lib/trackUsage.js +5 -4
  45. package/models/OAuth2Manager.d.ts +16 -13
  46. package/models/OAuth2Manager.js +30 -38
  47. package/package.json +3 -2
  48. package/types/Accounts.d.ts +5 -0
  49. package/types/Sandbox.d.ts +13 -12
  50. package/utils/PortManagerServer.js +7 -7
  51. package/types/LogCallbacks.d.ts +0 -7
  52. package/types/LogCallbacks.js +0 -2
  53. package/utils/logger.d.ts +0 -5
  54. package/utils/logger.js +0 -23
package/lib/github.js CHANGED
@@ -3,20 +3,20 @@ 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.downloadGithubRepoContents = exports.cloneGithubRepo = exports.fetchReleaseData = exports.fetchFileFromRepository = void 0;
6
+ exports.listGithubRepoContents = exports.downloadGithubRepoContents = exports.cloneGithubRepo = exports.fetchReleaseData = exports.fetchFileFromRepository = void 0;
7
7
  const path_1 = __importDefault(require("path"));
8
8
  const fs_extra_1 = __importDefault(require("fs-extra"));
9
- const logger_1 = require("../utils/logger");
10
9
  const standardErrors_1 = require("../errors/standardErrors");
11
10
  const archive_1 = require("./archive");
11
+ const logger_1 = require("./logging/logger");
12
12
  const github_1 = require("../api/github");
13
+ const lang_1 = require("../utils/lang");
13
14
  const i18nKey = 'lib.github';
14
- const cloneGithubRepoCallbackKeys = ['success'];
15
15
  async function fetchFileFromRepository(repoPath, filePath, ref) {
16
16
  try {
17
- (0, logger_1.debug)(`${i18nKey}.fetchFileFromRepository.fetching`, {
17
+ logger_1.logger.debug((0, lang_1.i18n)(`${i18nKey}.fetchFileFromRepository.fetching`, {
18
18
  path: `${repoPath}/${ref}/${filePath}`,
19
- });
19
+ }));
20
20
  const { data } = await (0, github_1.fetchRepoFile)(repoPath, filePath, ref);
21
21
  return data;
22
22
  }
@@ -53,24 +53,23 @@ async function downloadGithubRepoZip(repoPath, isRelease = false, options = {})
53
53
  const releaseData = await fetchReleaseData(repoPath, tag);
54
54
  zipUrl = releaseData.zipball_url;
55
55
  const { name } = releaseData;
56
- (0, logger_1.debug)(`${i18nKey}.downloadGithubRepoZip.fetchingName`, { name });
56
+ logger_1.logger.debug((0, lang_1.i18n)(`${i18nKey}.downloadGithubRepoZip.fetchingName`, { name }));
57
57
  }
58
58
  else {
59
59
  // If downloading a repository, manually construct the zip url. This url supports both branches and tags as refs
60
- (0, logger_1.debug)(`${i18nKey}.downloadGithubRepoZip.fetching`, { repoPath });
60
+ logger_1.logger.debug((0, lang_1.i18n)(`${i18nKey}.downloadGithubRepoZip.fetching`, { repoPath }));
61
61
  const ref = branch || tag;
62
62
  zipUrl = `https://api.github.com/repos/${repoPath}/zipball${ref ? `/${ref}` : ''}`;
63
63
  }
64
64
  const { data } = await (0, github_1.fetchRepoAsZip)(zipUrl);
65
- (0, logger_1.debug)(`${i18nKey}.downloadGithubRepoZip.completed`);
65
+ logger_1.logger.debug((0, lang_1.i18n)(`${i18nKey}.downloadGithubRepoZip.completed`));
66
66
  return data;
67
67
  }
68
68
  catch (err) {
69
69
  (0, standardErrors_1.throwErrorWithMessage)(`${i18nKey}.downloadGithubRepoZip.errors.fetchFail`, {}, err);
70
70
  }
71
71
  }
72
- async function cloneGithubRepo(repoPath, dest, options = {}, logCallbacks) {
73
- const logger = (0, logger_1.makeTypedLogger)(logCallbacks);
72
+ async function cloneGithubRepo(repoPath, dest, options = {}) {
74
73
  const { tag, isRelease, branch, sourceDir, type } = options;
75
74
  const zip = await downloadGithubRepoZip(repoPath, isRelease, {
76
75
  tag,
@@ -79,10 +78,10 @@ async function cloneGithubRepo(repoPath, dest, options = {}, logCallbacks) {
79
78
  const repoName = repoPath.split('/')[1];
80
79
  const success = await (0, archive_1.extractZipArchive)(zip, repoName, dest, { sourceDir });
81
80
  if (success) {
82
- logger('success', `${i18nKey}.cloneGithubRepo.success`, {
81
+ logger_1.logger.log((0, lang_1.i18n)(`${i18nKey}.cloneGithubRepo.success`, {
83
82
  type: type || '',
84
83
  dest,
85
- });
84
+ }));
86
85
  }
87
86
  return success;
88
87
  }
@@ -105,11 +104,11 @@ async function downloadGithubRepoContents(repoPath, contentPath, dest, ref, filt
105
104
  if (filter && !filter(contentPiecePath, downloadPath)) {
106
105
  return Promise.resolve();
107
106
  }
108
- (0, logger_1.debug)(`${i18nKey}.downloadGithubRepoContents.downloading`, {
107
+ logger_1.logger.debug((0, lang_1.i18n)(`${i18nKey}.downloadGithubRepoContents.downloading`, {
109
108
  contentPiecePath,
110
109
  downloadUrl: download_url,
111
110
  downloadPath,
112
- });
111
+ }));
113
112
  if (contentPieceType === 'dir') {
114
113
  const { data: innerDirContent } = await (0, github_1.fetchRepoContents)(repoPath, contentPiecePath, ref);
115
114
  await Promise.all(innerDirContent.map(downloadContent));
@@ -139,3 +138,25 @@ async function downloadGithubRepoContents(repoPath, contentPath, dest, ref, filt
139
138
  }
140
139
  }
141
140
  exports.downloadGithubRepoContents = downloadGithubRepoContents;
141
+ // Lists content from a public repository at the specified path
142
+ async function listGithubRepoContents(repoPath, contentPath, fileFilter) {
143
+ try {
144
+ const { data: contentsResp } = await (0, github_1.fetchRepoContents)(repoPath, contentPath);
145
+ const filteredFiles = fileFilter && fileFilter != undefined
146
+ ? contentsResp.filter(item => item.type === fileFilter)
147
+ : contentsResp;
148
+ return filteredFiles;
149
+ }
150
+ catch (e) {
151
+ const error = e;
152
+ if (error?.response?.data?.message) {
153
+ (0, standardErrors_1.throwErrorWithMessage)(`${i18nKey}.downloadGithubRepoContents.errors.fetchFail`, {
154
+ errorMessage: error.response.data.message,
155
+ });
156
+ }
157
+ else {
158
+ (0, standardErrors_1.throwError)(error);
159
+ }
160
+ }
161
+ }
162
+ exports.listGithubRepoContents = listGithubRepoContents;
package/lib/oauth.d.ts CHANGED
@@ -1,7 +1,4 @@
1
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
@@ -7,16 +7,15 @@ exports.addOauthToAccountConfig = exports.getOauthManager = void 0;
7
7
  const OAuth2Manager_1 = __importDefault(require("../models/OAuth2Manager"));
8
8
  const auth_1 = require("../constants/auth");
9
9
  const standardErrors_1 = require("../errors/standardErrors");
10
- const logger_1 = require("../utils/logger");
11
- const logger_2 = require("../utils/logger");
10
+ const logger_1 = require("./logging/logger");
12
11
  const getAccountIdentifier_1 = require("../utils/getAccountIdentifier");
13
12
  const config_1 = require("../config");
13
+ const lang_1 = require("../utils/lang");
14
14
  const i18nKey = 'lib.oauth';
15
- const addOauthToAccountConfigCallbackKeys = ['init', 'success'];
16
15
  const oauthManagers = new Map();
17
16
  function writeOauthTokenInfo(accountConfig) {
18
17
  const accountId = (0, getAccountIdentifier_1.getAccountIdentifier)(accountConfig);
19
- (0, logger_1.debug)(`${i18nKey}.writeTokenInfo`, { portalId: accountId || '' });
18
+ logger_1.logger.debug((0, lang_1.i18n)(`${i18nKey}.writeTokenInfo`, { portalId: accountId || '' }));
20
19
  (0, config_1.updateAccountConfig)(accountConfig);
21
20
  (0, config_1.writeConfig)();
22
21
  }
@@ -27,16 +26,15 @@ function getOauthManager(accountId, accountConfig) {
27
26
  return oauthManagers.get(accountId);
28
27
  }
29
28
  exports.getOauthManager = getOauthManager;
30
- function addOauthToAccountConfig(oauth, logCallbacks) {
31
- const logger = (0, logger_2.makeTypedLogger)(logCallbacks);
32
- logger('init', `${i18nKey}.addOauthToAccountConfig.init`);
29
+ function addOauthToAccountConfig(oauth) {
30
+ logger_1.logger.log((0, lang_1.i18n)(`${i18nKey}.addOauthToAccountConfig.init`));
33
31
  try {
34
32
  (0, config_1.updateAccountConfig)({
35
- ...oauth.toObj(),
33
+ ...oauth.account,
36
34
  authType: auth_1.AUTH_METHODS.oauth.value,
37
35
  });
38
36
  (0, config_1.writeConfig)();
39
- logger('success', `${i18nKey}.addOauthToAccountConfig.success`);
37
+ logger_1.logger.success((0, lang_1.i18n)(`${i18nKey}.addOauthToAccountConfig.success`));
40
38
  }
41
39
  catch (err) {
42
40
  (0, standardErrors_1.throwError)(err);
@@ -11,6 +11,7 @@ const standardErrors_1 = require("../errors/standardErrors");
11
11
  const localDevAuth_1 = require("../api/localDevAuth");
12
12
  const sandboxHubs_1 = require("../api/sandboxHubs");
13
13
  const config_1 = require("../config");
14
+ const config_2 = require("../constants/config");
14
15
  const i18nKey = 'lib.personalAccessKey';
15
16
  const refreshRequests = new Map();
16
17
  function getRefreshKey(personalAccessKey, expiration) {
@@ -101,11 +102,26 @@ async function updateConfigWithAccessToken(token, personalAccessKey, env, name,
101
102
  catch (err) {
102
103
  // Ignore error, returns 404 if account is not a sandbox
103
104
  }
105
+ let accountType = config_2.HUBSPOT_ACCOUNT_TYPES.STANDARD;
104
106
  let sandboxAccountType = null;
105
- let parentAccountId = null;
107
+ let parentAccountId;
106
108
  if (hubInfo) {
107
109
  if (hubInfo.type !== undefined) {
108
- sandboxAccountType = hubInfo.type === null ? 'STANDARD' : hubInfo.type;
110
+ const sandboxHubType = hubInfo.type ? hubInfo.type.toUpperCase() : null;
111
+ switch (sandboxHubType) {
112
+ case 'DEVELOPER':
113
+ accountType = config_2.HUBSPOT_ACCOUNT_TYPES.DEVELOPER_SANDBOX;
114
+ sandboxAccountType = 'DEVELOPER';
115
+ break;
116
+ case 'STANDARD':
117
+ accountType = config_2.HUBSPOT_ACCOUNT_TYPES.STANDARD_SANDBOX;
118
+ sandboxAccountType = 'STANDARD';
119
+ break;
120
+ default:
121
+ accountType = config_2.HUBSPOT_ACCOUNT_TYPES.STANDARD_SANDBOX;
122
+ sandboxAccountType = 'STANDARD';
123
+ break;
124
+ }
109
125
  }
110
126
  if (hubInfo.parentHubId) {
111
127
  parentAccountId = hubInfo.parentHubId;
@@ -113,6 +129,7 @@ async function updateConfigWithAccessToken(token, personalAccessKey, env, name,
113
129
  }
114
130
  const updatedConfig = (0, config_1.updateAccountConfig)({
115
131
  accountId: portalId,
132
+ accountType,
116
133
  personalAccessKey,
117
134
  name,
118
135
  authType: auth_1.PERSONAL_ACCESS_KEY_AUTH_METHOD.value,
@@ -1,5 +1,5 @@
1
1
  import { InitiateSyncResponse, Sandbox, SandboxType, SyncTask, Task, Usage } from '../types/Sandbox';
2
- export declare function createSandbox(accountId: number, name: string, type: string): Promise<{
2
+ export declare function createSandbox(accountId: number, name: string, type: 1 | 2): Promise<{
3
3
  name: string;
4
4
  sandbox: Sandbox;
5
5
  personalAccessKey: string;
package/lib/sandboxes.js CHANGED
@@ -3,8 +3,7 @@ Object.defineProperty(exports, "__esModule", { value: true });
3
3
  exports.fetchTypes = exports.fetchTaskStatus = exports.initiateSync = exports.getSandboxUsageLimits = exports.deleteSandbox = exports.createSandbox = void 0;
4
4
  const sandboxHubs_1 = require("../api/sandboxHubs");
5
5
  const sandboxSync_1 = require("../api/sandboxSync");
6
- const standardErrors_1 = require("../errors/standardErrors");
7
- const i18nKey = 'lib.sandboxes';
6
+ const apiErrors_1 = require("../errors/apiErrors");
8
7
  async function createSandbox(accountId, name, type) {
9
8
  try {
10
9
  const resp = await (0, sandboxHubs_1.createSandbox)(accountId, name, type);
@@ -14,7 +13,7 @@ async function createSandbox(accountId, name, type) {
14
13
  };
15
14
  }
16
15
  catch (err) {
17
- (0, standardErrors_1.throwErrorWithMessage)(`${i18nKey}.errors.createSandbox`, {}, err);
16
+ (0, apiErrors_1.throwApiError)(err);
18
17
  }
19
18
  }
20
19
  exports.createSandbox = createSandbox;
@@ -23,7 +22,7 @@ async function deleteSandbox(parentAccountId, sandboxAccountId) {
23
22
  await (0, sandboxHubs_1.deleteSandbox)(parentAccountId, sandboxAccountId);
24
23
  }
25
24
  catch (err) {
26
- (0, standardErrors_1.throwErrorWithMessage)(`${i18nKey}.errors.deleteSandbox`, {}, err);
25
+ (0, apiErrors_1.throwApiError)(err);
27
26
  }
28
27
  return {
29
28
  parentAccountId,
@@ -37,7 +36,7 @@ async function getSandboxUsageLimits(parentAccountId) {
37
36
  return resp && resp.usage;
38
37
  }
39
38
  catch (err) {
40
- (0, standardErrors_1.throwErrorWithMessage)(`${i18nKey}.errors.getSandboxUsageLimits`, {}, err);
39
+ (0, apiErrors_1.throwApiError)(err);
41
40
  }
42
41
  }
43
42
  exports.getSandboxUsageLimits = getSandboxUsageLimits;
@@ -46,7 +45,7 @@ async function initiateSync(fromHubId, toHubId, tasks, sandboxHubId) {
46
45
  return await (0, sandboxSync_1.initiateSync)(fromHubId, toHubId, tasks, sandboxHubId);
47
46
  }
48
47
  catch (err) {
49
- (0, standardErrors_1.throwErrorWithMessage)(`${i18nKey}.errors.initiateSync`, {}, err);
48
+ (0, apiErrors_1.throwApiError)(err);
50
49
  }
51
50
  }
52
51
  exports.initiateSync = initiateSync;
@@ -55,7 +54,7 @@ async function fetchTaskStatus(accountId, taskId) {
55
54
  return await (0, sandboxSync_1.fetchTaskStatus)(accountId, taskId);
56
55
  }
57
56
  catch (err) {
58
- (0, standardErrors_1.throwErrorWithMessage)(`${i18nKey}.errors.fetchTaskStatus`, {}, err);
57
+ (0, apiErrors_1.throwApiError)(err);
59
58
  }
60
59
  }
61
60
  exports.fetchTaskStatus = fetchTaskStatus;
@@ -65,7 +64,7 @@ async function fetchTypes(accountId, toHubId) {
65
64
  return resp && resp.results;
66
65
  }
67
66
  catch (err) {
68
- (0, standardErrors_1.throwErrorWithMessage)(`${i18nKey}.errors.fetchTypes`, {}, err);
67
+ (0, apiErrors_1.throwApiError)(err);
69
68
  }
70
69
  }
71
70
  exports.fetchTypes = fetchTypes;
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");
9
+ const logger_1 = require("./logging/logger");
10
10
  const http_1 = __importDefault(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,12 +32,12 @@ 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
+ logger_1.logger.debug((0, lang_1.i18n)(`${i18nKey}.sendingEventAuthenticated`));
40
41
  return http_1.default.post(accountId, {
41
42
  url: `${path}/authenticated`,
42
43
  data: usageEvent,
@@ -50,7 +51,7 @@ async function trackUsage(eventName, eventClass, meta = {}, accountId) {
50
51
  data: usageEvent,
51
52
  resolveWithFullResponse: true,
52
53
  });
53
- (0, logger_1.debug)(`${i18nKey}.sendingEventUnauthenticated`);
54
+ logger_1.logger.debug((0, lang_1.i18n)(`${i18nKey}.sendingEventUnauthenticated`));
54
55
  (0, axios_1.default)({ ...axiosConfig, method: 'post' });
55
56
  }
56
57
  exports.trackUsage = trackUsage;
@@ -1,4 +1,16 @@
1
- import { FlatAccountFields, OAuthAccount, TokenInfo } from '../types/Accounts';
1
+ import { FlatAccountFields, TokenInfo } from '../types/Accounts';
2
+ import { Environment } from '../types/Config';
3
+ type OAuth2ManagerAccountConfig = {
4
+ name?: string;
5
+ accountId?: number;
6
+ clientId?: string;
7
+ clientSecret?: string;
8
+ scopes?: Array<string>;
9
+ env?: Environment;
10
+ environment?: Environment;
11
+ tokenInfo?: TokenInfo;
12
+ authType?: 'oauth2';
13
+ };
2
14
  type WriteTokenInfoFunction = (tokenInfo: TokenInfo) => void;
3
15
  type RefreshTokenResponse = {
4
16
  refresh_token: string;
@@ -12,23 +24,14 @@ type ExchangeProof = {
12
24
  refresh_token?: string;
13
25
  };
14
26
  declare class OAuth2Manager {
15
- account: OAuthAccount;
16
- writeTokenInfo: WriteTokenInfoFunction;
27
+ account: OAuth2ManagerAccountConfig;
28
+ writeTokenInfo?: WriteTokenInfoFunction;
17
29
  refreshTokenRequest: Promise<RefreshTokenResponse> | null;
18
- constructor(account: OAuthAccount, writeTokenInfo: WriteTokenInfoFunction);
30
+ constructor(account: OAuth2ManagerAccountConfig, writeTokenInfo?: WriteTokenInfoFunction);
19
31
  accessToken(): Promise<string | undefined>;
20
32
  fetchAccessToken(exchangeProof: ExchangeProof): Promise<void>;
21
33
  exchangeForTokens(exchangeProof: ExchangeProof): Promise<void>;
22
34
  refreshAccessToken(): Promise<void>;
23
- toObj(): {
24
- env: import("../types/Config").Environment;
25
- clientSecret: string | undefined;
26
- clientId: string | undefined;
27
- scopes: string[] | undefined;
28
- tokenInfo: TokenInfo | undefined;
29
- name: string | undefined;
30
- accountId: number;
31
- };
32
35
  static fromConfig(accountConfig: FlatAccountFields, writeTokenInfo: WriteTokenInfoFunction): OAuth2Manager;
33
36
  }
34
37
  export default OAuth2Manager;
@@ -7,10 +7,11 @@ const axios_1 = __importDefault(require("axios"));
7
7
  const moment_1 = __importDefault(require("moment"));
8
8
  const urls_1 = require("../lib/urls");
9
9
  const environment_1 = require("../lib/environment");
10
- const logger_1 = require("../utils/logger");
10
+ const logger_1 = require("../lib/logging/logger");
11
11
  const getAccountIdentifier_1 = require("../utils/getAccountIdentifier");
12
12
  const auth_1 = require("../constants/auth");
13
13
  const standardErrors_1 = require("../errors/standardErrors");
14
+ const lang_1 = require("../utils/lang");
14
15
  const i18nKey = 'models.OAuth2Manager';
15
16
  class OAuth2Manager {
16
17
  account;
@@ -25,45 +26,47 @@ class OAuth2Manager {
25
26
  }
26
27
  }
27
28
  async accessToken() {
28
- if (!this.account.auth.tokenInfo?.refreshToken) {
29
+ if (!this.account.tokenInfo?.refreshToken) {
29
30
  (0, standardErrors_1.throwErrorWithMessage)(`${i18nKey}.errors.missingRefreshToken`, {
30
31
  accountId: (0, getAccountIdentifier_1.getAccountIdentifier)(this.account),
31
32
  });
32
33
  }
33
- if (!this.account.auth.tokenInfo?.accessToken ||
34
+ if (!this.account.tokenInfo?.accessToken ||
34
35
  (0, moment_1.default)()
35
36
  .add(5, 'minutes')
36
- .isAfter((0, moment_1.default)(this.account.auth?.tokenInfo.expiresAt))) {
37
+ .isAfter((0, moment_1.default)(new Date(this.account.tokenInfo.expiresAt || '')))) {
37
38
  await this.refreshAccessToken();
38
39
  }
39
- return this.account.auth?.tokenInfo.accessToken;
40
+ return this.account.tokenInfo.accessToken;
40
41
  }
41
42
  async fetchAccessToken(exchangeProof) {
42
- (0, logger_1.debug)(`${i18nKey}.fetchingAccessToken`, {
43
+ logger_1.logger.debug((0, lang_1.i18n)(`${i18nKey}.fetchingAccessToken`, {
43
44
  accountId: (0, getAccountIdentifier_1.getAccountIdentifier)(this.account),
44
- clientId: this.account.auth.clientId || '',
45
- });
45
+ clientId: this.account.clientId || '',
46
+ }));
46
47
  try {
47
- const { data } = await axios_1.default.post(`${(0, urls_1.getHubSpotApiOrigin)((0, environment_1.getValidEnv)(this.account.env))}/oauth/v1/token`, {
48
- form: exchangeProof,
49
- json: true,
48
+ const { data } = await (0, axios_1.default)({
49
+ url: `${(0, urls_1.getHubSpotApiOrigin)((0, environment_1.getValidEnv)(this.account.env))}/oauth/v1/token`,
50
+ method: 'post',
51
+ data: exchangeProof,
52
+ headers: { 'Content-Type': 'application/x-www-form-urlencoded' },
50
53
  });
51
54
  this.refreshTokenRequest = data;
52
55
  const { refresh_token: refreshToken, access_token: accessToken, expires_in: expiresIn, } = data;
53
- if (!this.account.auth.tokenInfo) {
54
- this.account.auth.tokenInfo = {};
56
+ if (!this.account.tokenInfo) {
57
+ this.account.tokenInfo = {};
55
58
  }
56
- this.account.auth.tokenInfo.refreshToken = refreshToken;
57
- this.account.auth.tokenInfo.accessToken = accessToken;
58
- this.account.auth.tokenInfo.expiresAt = (0, moment_1.default)()
59
+ this.account.tokenInfo.refreshToken = refreshToken;
60
+ this.account.tokenInfo.accessToken = accessToken;
61
+ this.account.tokenInfo.expiresAt = (0, moment_1.default)()
59
62
  .add(Math.round(parseInt(expiresIn) * 0.75), 'seconds')
60
63
  .toString();
61
64
  if (this.writeTokenInfo) {
62
- (0, logger_1.debug)(`${i18nKey}.updatingTokenInfo`, {
65
+ logger_1.logger.debug((0, lang_1.i18n)(`${i18nKey}.updatingTokenInfo`, {
63
66
  accountId: (0, getAccountIdentifier_1.getAccountIdentifier)(this.account),
64
- clientId: this.account.auth.clientId || '',
65
- });
66
- this.writeTokenInfo(this.account.auth.tokenInfo);
67
+ clientId: this.account.clientId || '',
68
+ }));
69
+ this.writeTokenInfo(this.account.tokenInfo);
67
70
  }
68
71
  this.refreshTokenRequest = null;
69
72
  }
@@ -75,10 +78,10 @@ class OAuth2Manager {
75
78
  async exchangeForTokens(exchangeProof) {
76
79
  try {
77
80
  if (this.refreshTokenRequest) {
78
- (0, logger_1.debug)(`${i18nKey}.refreshingAccessToken`, {
81
+ logger_1.logger.debug((0, lang_1.i18n)(`${i18nKey}.refreshingAccessToken`, {
79
82
  accountId: (0, getAccountIdentifier_1.getAccountIdentifier)(this.account),
80
- clientId: this.account.auth.clientId || '',
81
- });
83
+ clientId: this.account.clientId || '',
84
+ }));
82
85
  await this.refreshTokenRequest;
83
86
  }
84
87
  else {
@@ -100,28 +103,17 @@ class OAuth2Manager {
100
103
  async refreshAccessToken() {
101
104
  const refreshTokenProof = {
102
105
  grant_type: 'refresh_token',
103
- client_id: this.account.auth.clientId,
104
- client_secret: this.account.auth.clientSecret,
105
- refresh_token: this.account.auth.tokenInfo?.refreshToken,
106
+ client_id: this.account.clientId,
107
+ client_secret: this.account.clientSecret,
108
+ refresh_token: this.account.tokenInfo?.refreshToken,
106
109
  };
107
110
  await this.exchangeForTokens(refreshTokenProof);
108
111
  }
109
- toObj() {
110
- return {
111
- env: this.account.env,
112
- clientSecret: this.account.auth.clientSecret,
113
- clientId: this.account.auth.clientId,
114
- scopes: this.account.auth.scopes,
115
- tokenInfo: this.account.auth.tokenInfo,
116
- name: this.account.name,
117
- accountId: (0, getAccountIdentifier_1.getAccountIdentifier)(this.account),
118
- };
119
- }
120
112
  static fromConfig(accountConfig, writeTokenInfo) {
121
113
  return new OAuth2Manager({
122
114
  ...accountConfig,
123
115
  authType: auth_1.AUTH_METHODS.oauth.value,
124
- auth: accountConfig.auth || {},
116
+ ...(accountConfig.auth || {}),
125
117
  }, writeTokenInfo);
126
118
  }
127
119
  }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@hubspot/local-dev-lib",
3
- "version": "0.2.3",
3
+ "version": "0.3.0",
4
4
  "description": "Provides library functionality for HubSpot local development tooling, including the HubSpot CLI",
5
5
  "main": "lib/index.js",
6
6
  "repository": {
@@ -54,7 +54,8 @@
54
54
  "./http": "./http/index.js",
55
55
  "./config": "./config/index.js",
56
56
  "./constants/*": "./constants/*.js",
57
- "./logger": "./lib/logging/logger.js"
57
+ "./logger": "./lib/logging/logger.js",
58
+ "./models/*": "./models/*.js"
58
59
  },
59
60
  "dependencies": {
60
61
  "address": "^2.0.1",
@@ -1,9 +1,12 @@
1
+ import { HUBSPOT_ACCOUNT_TYPES } from '../constants/config';
1
2
  import { Mode } from './Files';
2
3
  import { Environment } from './Config';
4
+ import { ValueOf } from './Utils';
3
5
  export type AuthType = 'personalaccesskey' | 'apikey' | 'oauth2';
4
6
  export interface CLIAccount_NEW {
5
7
  name?: string;
6
8
  accountId: number;
9
+ accountType?: AccountType;
7
10
  defaultMode?: Mode;
8
11
  env: Environment;
9
12
  authType?: AuthType;
@@ -20,6 +23,7 @@ export interface CLIAccount_DEPRECATED {
20
23
  portalId?: number;
21
24
  defaultMode?: Mode;
22
25
  env: Environment;
26
+ accountType?: AccountType;
23
27
  authType?: AuthType;
24
28
  auth?: {
25
29
  tokenInfo?: TokenInfo;
@@ -30,6 +34,7 @@ export interface CLIAccount_DEPRECATED {
30
34
  personalAccessKey?: string;
31
35
  }
32
36
  export type CLIAccount = CLIAccount_NEW | CLIAccount_DEPRECATED;
37
+ export type AccountType = ValueOf<typeof HUBSPOT_ACCOUNT_TYPES>;
33
38
  export type TokenInfo = {
34
39
  accessToken?: string;
35
40
  expiresAt?: string;
@@ -6,9 +6,9 @@ type User = {
6
6
  userId: number;
7
7
  firstName: string;
8
8
  lastName: string;
9
- gdprDeleted: boolean;
10
- removed: boolean;
11
- deactivated: boolean;
9
+ gdprDeleted?: boolean;
10
+ removed?: boolean;
11
+ deactivated?: boolean;
12
12
  };
13
13
  type TaskError = {
14
14
  message: string;
@@ -80,15 +80,15 @@ export type Sandbox = {
80
80
  sandboxHubId: number;
81
81
  parentHubId: number;
82
82
  createdAt: string;
83
- updatedAt: string | null;
84
- archivedAt: string | null;
83
+ updatedAt?: string | null;
84
+ archivedAt?: string | null;
85
85
  type: string;
86
86
  archived: boolean;
87
87
  name: string;
88
88
  domain: string;
89
89
  createdByUser: User;
90
- updatedByUser: User | null;
91
- lastSync: {
90
+ updatedByUser?: User | null;
91
+ lastSync?: {
92
92
  id: string;
93
93
  parentHubId: number;
94
94
  sandboxHubId: number;
@@ -105,10 +105,10 @@ export type Sandbox = {
105
105
  completedAt: string;
106
106
  tasks: Array<Task>;
107
107
  };
108
- currentUserHasAccess: boolean | null;
109
- currentUserHasSuperAdminAccess: boolean | null;
110
- requestAccessFrom: User | null;
111
- superAdminsInSandbox: number | null;
108
+ currentUserHasAccess?: boolean;
109
+ currentUserHasSuperAdminAccess?: boolean;
110
+ requestAccessFrom?: User | null;
111
+ superAdminsInSandbox?: number;
112
112
  };
113
113
  export type SandboxResponse = {
114
114
  sandbox: Sandbox;
@@ -154,10 +154,11 @@ export type InitiateSyncResponse = {
154
154
  export type SandboxType = {
155
155
  name: string;
156
156
  dependsOn: Array<string>;
157
- pushToParentEnabled: boolean;
157
+ pushToProductionEnabled: boolean;
158
158
  isBeta: boolean;
159
159
  diffEnabled: boolean;
160
160
  groupType: string;
161
+ syncMandatory: boolean;
161
162
  };
162
163
  export type FetchTypesResponse = {
163
164
  results: Array<SandboxType>;
@@ -8,7 +8,7 @@ const cors_1 = __importDefault(require("cors"));
8
8
  const detectPort_1 = require("./detectPort");
9
9
  const ports_1 = require("../constants/ports");
10
10
  const standardErrors_1 = require("../errors/standardErrors");
11
- const logger_1 = require("./logger");
11
+ const logger_1 = require("../lib/logging/logger");
12
12
  const lang_1 = require("./lang");
13
13
  const i18nKey = 'utils.PortManagerServer';
14
14
  class PortManagerServer {
@@ -47,9 +47,9 @@ class PortManagerServer {
47
47
  listen() {
48
48
  return new Promise((resolve, reject) => {
49
49
  const server = this.app.listen(ports_1.PORT_MANAGER_SERVER_PORT, () => {
50
- (0, logger_1.debug)(`${i18nKey}.started`, {
50
+ logger_1.logger.debug((0, lang_1.i18n)(`${i18nKey}.started`, {
51
51
  port: ports_1.PORT_MANAGER_SERVER_PORT,
52
- });
52
+ }));
53
53
  resolve(server);
54
54
  }).on('error', (err) => {
55
55
  reject(err);
@@ -67,14 +67,14 @@ class PortManagerServer {
67
67
  this.app.post('/close', this.closeServer);
68
68
  }
69
69
  setPort(instanceId, port) {
70
- (0, logger_1.debug)(`${i18nKey}.setPort`, { instanceId, port });
70
+ logger_1.logger.debug((0, lang_1.i18n)(`${i18nKey}.setPort`, { instanceId, port }));
71
71
  this.serverPortMap[instanceId] = port;
72
72
  }
73
73
  deletePort(instanceId) {
74
- (0, logger_1.debug)(`${i18nKey}.deletedPort`, {
74
+ logger_1.logger.debug((0, lang_1.i18n)(`${i18nKey}.deletedPort`, {
75
75
  instanceId,
76
76
  port: this.serverPortMap[instanceId],
77
- });
77
+ }));
78
78
  delete this.serverPortMap[instanceId];
79
79
  }
80
80
  send404(res, instanceId) {
@@ -148,7 +148,7 @@ class PortManagerServer {
148
148
  };
149
149
  closeServer = (req, res) => {
150
150
  if (this.server) {
151
- (0, logger_1.debug)(`${i18nKey}.close`);
151
+ logger_1.logger.debug((0, lang_1.i18n)(`${i18nKey}.close`));
152
152
  res.sendStatus(200);
153
153
  this.server.close();
154
154
  this.reset();
@@ -1,7 +0,0 @@
1
- import { InterpolationData } from './Lang';
2
- export type LogCallbacks<T extends string> = {
3
- [key in T]?: (interpolationData?: InterpolationData) => void;
4
- };
5
- export type LogCallbacksArg<T extends readonly string[]> = {
6
- [key in T[number]]?: () => void;
7
- };
@@ -1,2 +0,0 @@
1
- "use strict";
2
- Object.defineProperty(exports, "__esModule", { value: true });