@hubspot/local-dev-lib 0.5.0-experimental.1 → 0.5.0-experimental.10

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.
package/config/index.d.ts CHANGED
@@ -4,6 +4,7 @@ import { CmsPublishMode } from '../types/Files';
4
4
  import { Environment } from '../types/Config';
5
5
  export declare function localConfigFileExists(): boolean;
6
6
  export declare function globalConfigFileExists(): boolean;
7
+ export declare function configFileExists(): boolean;
7
8
  export declare function getConfigFilePath(): string;
8
9
  export declare function getConfig(): HubSpotConfig;
9
10
  export declare function isConfigValid(): boolean;
@@ -15,7 +16,7 @@ export declare function getConfigAccountIfExists(identifier: number | string): H
15
16
  export declare function getConfigDefaultAccount(): HubSpotConfigAccount;
16
17
  export declare function getConfigDefaultAccountIfExists(): HubSpotConfigAccount | undefined;
17
18
  export declare function getAllConfigAccounts(): HubSpotConfigAccount[];
18
- export declare function getConfigAccountEnvironment(identifier?: number | string): Environment;
19
+ export declare function getConfigAccountEnvironment(identifier: number | string): Environment;
19
20
  export declare function addConfigAccount(accountToAdd: HubSpotConfigAccount): void;
20
21
  export declare function updateConfigAccount(updatedAccount: HubSpotConfigAccount): void;
21
22
  export declare function setConfigAccountAsDefault(identifier: number | string): void;
package/config/index.js CHANGED
@@ -3,7 +3,7 @@ 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.removeLocalStateFlag = exports.addLocalStateFlag = exports.hasLocalStateFlag = exports.isConfigFlagEnabled = exports.updateDefaultCmsPublishMode = exports.updateAutoOpenBrowser = exports.updateAllowAutoUpdates = exports.updateAllowUsageTracking = exports.updateHttpTimeout = exports.removeAccountFromConfig = exports.renameConfigAccount = exports.setConfigAccountAsDefault = exports.updateConfigAccount = exports.addConfigAccount = exports.getConfigAccountEnvironment = exports.getAllConfigAccounts = exports.getConfigDefaultAccountIfExists = exports.getConfigDefaultAccount = exports.getConfigAccountIfExists = exports.getConfigAccountByName = exports.getConfigAccountById = exports.deleteConfigFile = exports.createEmptyConfigFile = exports.isConfigValid = exports.getConfig = exports.getConfigFilePath = exports.globalConfigFileExists = exports.localConfigFileExists = void 0;
6
+ exports.removeLocalStateFlag = exports.addLocalStateFlag = exports.hasLocalStateFlag = exports.isConfigFlagEnabled = exports.updateDefaultCmsPublishMode = exports.updateAutoOpenBrowser = exports.updateAllowAutoUpdates = exports.updateAllowUsageTracking = exports.updateHttpTimeout = exports.removeAccountFromConfig = exports.renameConfigAccount = exports.setConfigAccountAsDefault = exports.updateConfigAccount = exports.addConfigAccount = exports.getConfigAccountEnvironment = exports.getAllConfigAccounts = exports.getConfigDefaultAccountIfExists = exports.getConfigDefaultAccount = exports.getConfigAccountIfExists = exports.getConfigAccountByName = exports.getConfigAccountById = exports.deleteConfigFile = exports.createEmptyConfigFile = exports.isConfigValid = exports.getConfig = exports.getConfigFilePath = exports.configFileExists = exports.globalConfigFileExists = exports.localConfigFileExists = void 0;
7
7
  const fs_extra_1 = __importDefault(require("fs-extra"));
8
8
  const config_1 = require("../constants/config");
9
9
  const logger_1 = require("../lib/logger");
@@ -19,12 +19,21 @@ function localConfigFileExists() {
19
19
  }
20
20
  exports.localConfigFileExists = localConfigFileExists;
21
21
  function globalConfigFileExists() {
22
- return fs_extra_1.default.existsSync((0, utils_1.getGlobalConfigFilePath)());
22
+ return (0, utils_1.doesConfigFileExistAtPath)((0, utils_1.getGlobalConfigFilePath)());
23
23
  }
24
24
  exports.globalConfigFileExists = globalConfigFileExists;
25
+ function configFileExists() {
26
+ try {
27
+ return (0, utils_1.doesConfigFileExistAtPath)(getConfigFilePath());
28
+ }
29
+ catch (error) {
30
+ return false;
31
+ }
32
+ }
33
+ exports.configFileExists = configFileExists;
25
34
  function getConfigDefaultFilePath() {
26
35
  const globalConfigFilePath = (0, utils_1.getGlobalConfigFilePath)();
27
- if (fs_extra_1.default.existsSync(globalConfigFilePath)) {
36
+ if ((0, utils_1.doesConfigFileExistAtPath)(globalConfigFilePath)) {
28
37
  return globalConfigFilePath;
29
38
  }
30
39
  const localConfigFilePath = (0, utils_1.getLocalConfigFilePath)();
@@ -106,7 +115,15 @@ function createEmptyConfigFile(useGlobalConfig = false) {
106
115
  exports.createEmptyConfigFile = createEmptyConfigFile;
107
116
  function deleteConfigFile() {
108
117
  const pathToDelete = getConfigFilePath();
109
- fs_extra_1.default.unlinkSync(pathToDelete);
118
+ try {
119
+ fs_extra_1.default.unlinkSync(pathToDelete);
120
+ }
121
+ catch (error) {
122
+ const { message, type } = (0, utils_1.handleConfigFileSystemError)(error, pathToDelete);
123
+ throw new HubSpotConfigError_1.HubSpotConfigError(message, type, config_1.HUBSPOT_CONFIG_OPERATIONS.DELETE, {
124
+ cause: error,
125
+ });
126
+ }
110
127
  }
111
128
  exports.deleteConfigFile = deleteConfigFile;
112
129
  function getConfigAccountById(accountId) {
@@ -135,7 +152,9 @@ exports.getConfigAccountIfExists = getConfigAccountIfExists;
135
152
  function getConfigDefaultAccount() {
136
153
  const { accounts, defaultAccount } = getConfig();
137
154
  let defaultAccountToUse = defaultAccount;
138
- if (globalConfigFileExists()) {
155
+ const currentConfigPath = getConfigFilePath();
156
+ const globalConfigPath = (0, utils_1.getGlobalConfigFilePath)();
157
+ if (currentConfigPath === globalConfigPath && globalConfigFileExists()) {
139
158
  const defaultAccountOverrideAccountId = (0, defaultAccountOverride_1.getDefaultAccountOverrideAccountId)();
140
159
  defaultAccountToUse = defaultAccountOverrideAccountId || defaultAccount;
141
160
  }
@@ -154,7 +173,10 @@ exports.getConfigDefaultAccount = getConfigDefaultAccount;
154
173
  function getConfigDefaultAccountIfExists() {
155
174
  const { accounts, defaultAccount } = getConfig();
156
175
  let defaultAccountToUse = defaultAccount;
157
- if (globalConfigFileExists()) {
176
+ // Only check for default account override if we're using the global config
177
+ const currentConfigPath = getConfigFilePath();
178
+ const globalConfigPath = (0, utils_1.getGlobalConfigFilePath)();
179
+ if (currentConfigPath === globalConfigPath && globalConfigFileExists()) {
158
180
  const defaultAccountOverrideAccountId = (0, defaultAccountOverride_1.getDefaultAccountOverrideAccountId)();
159
181
  defaultAccountToUse = defaultAccountOverrideAccountId || defaultAccount;
160
182
  }
@@ -171,15 +193,14 @@ function getAllConfigAccounts() {
171
193
  }
172
194
  exports.getAllConfigAccounts = getAllConfigAccounts;
173
195
  function getConfigAccountEnvironment(identifier) {
174
- if (identifier) {
175
- const config = getConfig();
176
- const account = (0, utils_1.getConfigAccountByInferredIdentifier)(config.accounts, identifier);
177
- if (account) {
178
- return (0, environment_1.getValidEnv)(account.env);
179
- }
196
+ const config = getConfig();
197
+ const account = (0, utils_1.getConfigAccountByInferredIdentifier)(config.accounts, identifier);
198
+ if (!account) {
199
+ throw new HubSpotConfigError_1.HubSpotConfigError((0, lang_1.i18n)('config.getConfigAccountEnvironment.accountNotFound', {
200
+ identifier,
201
+ }), config_2.HUBSPOT_CONFIG_ERROR_TYPES.ACCOUNT_NOT_FOUND, config_1.HUBSPOT_CONFIG_OPERATIONS.READ);
180
202
  }
181
- const defaultAccount = getConfigDefaultAccount();
182
- return (0, environment_1.getValidEnv)(defaultAccount.env);
203
+ return (0, environment_1.getValidEnv)(account.env);
183
204
  }
184
205
  exports.getConfigAccountEnvironment = getConfigAccountEnvironment;
185
206
  function addConfigAccount(accountToAdd) {
package/config/state.d.ts CHANGED
@@ -1,3 +1,3 @@
1
- import { CLIState } from '../types/Config';
2
- export declare function getStateValue<K extends keyof CLIState>(key: K): CLIState[K];
3
- export declare function setStateValue<K extends keyof CLIState>(key: K, value: CLIState[K]): void;
1
+ import { HubSpotState } from '../types/Config';
2
+ export declare function getStateValue<K extends keyof HubSpotState>(key: K): HubSpotState[K];
3
+ export declare function setStateValue<K extends keyof HubSpotState>(key: K, value: HubSpotState[K]): void;
package/config/state.js CHANGED
@@ -29,9 +29,10 @@ const path = __importStar(require("path"));
29
29
  const lang_1 = require("../utils/lang");
30
30
  const config_1 = require("../constants/config");
31
31
  const logger_1 = require("../lib/logger");
32
+ const config_2 = require("../constants/config");
32
33
  const i18nKey = 'config.state';
33
34
  const DEFAULT_STATE = {
34
- mcpTotalToolCalls: 0,
35
+ [config_2.MCP_TOTAL_TOOL_CALLS_STATE]: 0,
35
36
  };
36
37
  function ensureCLIDirectory() {
37
38
  try {
@@ -46,19 +47,41 @@ function ensureCLIDirectory() {
46
47
  }));
47
48
  }
48
49
  }
50
+ function sanitizeAndMerge(parsed) {
51
+ if (!parsed || typeof parsed !== 'object' || Array.isArray(parsed)) {
52
+ return structuredClone(DEFAULT_STATE);
53
+ }
54
+ const state = parsed;
55
+ const result = structuredClone(DEFAULT_STATE);
56
+ for (const key in DEFAULT_STATE) {
57
+ const typedKey = key;
58
+ if (key in state &&
59
+ typeof state[typedKey] === typeof DEFAULT_STATE[typedKey]) {
60
+ result[typedKey] = state[typedKey];
61
+ }
62
+ // keys not in parsed file remain as DEFAULT values
63
+ }
64
+ return result;
65
+ }
49
66
  function getCurrentState() {
50
67
  try {
51
- if (fs.existsSync(config_1.STATE_FILE_PATH)) {
52
- const data = fs.readFileSync(config_1.STATE_FILE_PATH, 'utf-8');
53
- return JSON.parse(data);
68
+ if (!fs.existsSync(config_1.STATE_FILE_PATH)) {
69
+ return structuredClone(DEFAULT_STATE);
54
70
  }
71
+ const data = fs.readFileSync(config_1.STATE_FILE_PATH, 'utf-8');
72
+ if (!data?.trim()) {
73
+ logger_1.logger.debug((0, lang_1.i18n)(`${i18nKey}.getCurrentState.debug.emptyStateFile`));
74
+ return structuredClone(DEFAULT_STATE);
75
+ }
76
+ const parsed = JSON.parse(data);
77
+ return sanitizeAndMerge(parsed);
55
78
  }
56
79
  catch (error) {
57
- throw new Error((0, lang_1.i18n)(`${i18nKey}.getCurrentState.errors.errorReading`, {
80
+ logger_1.logger.debug((0, lang_1.i18n)(`${i18nKey}.getCurrentState.errors.errorReading`, {
58
81
  error: error instanceof Error ? error.message : String(error),
59
82
  }));
83
+ return structuredClone(DEFAULT_STATE);
60
84
  }
61
- return DEFAULT_STATE;
62
85
  }
63
86
  function getStateValue(key) {
64
87
  ensureCLIDirectory();
@@ -68,13 +91,7 @@ function getStateValue(key) {
68
91
  exports.getStateValue = getStateValue;
69
92
  function setStateValue(key, value) {
70
93
  ensureCLIDirectory();
71
- let currentState = DEFAULT_STATE;
72
- try {
73
- currentState = getCurrentState();
74
- }
75
- catch (error) {
76
- logger_1.logger.debug(error);
77
- }
94
+ const currentState = getCurrentState();
78
95
  const newState = { ...currentState, [key]: value };
79
96
  try {
80
97
  fs.writeFileSync(config_1.STATE_FILE_PATH, JSON.stringify(newState, null, 2), 'utf-8');
package/config/utils.d.ts CHANGED
@@ -1,5 +1,5 @@
1
1
  import { ACCOUNT_IDENTIFIERS } from '../constants/config';
2
- import { HubSpotConfig, DeprecatedHubSpotConfigFields } from '../types/Config';
2
+ import { HubSpotConfig, DeprecatedHubSpotConfigFields, HubSpotConfigErrorType } from '../types/Config';
3
3
  import { HubSpotConfigAccount, AccountType, TokenInfo } from '../types/Accounts';
4
4
  import { ValueOf } from '../types/Utils';
5
5
  export declare function getGlobalConfigFilePath(): string;
@@ -9,6 +9,7 @@ export declare function getConfigPathEnvironmentVariables(): {
9
9
  useEnvironmentConfig: boolean;
10
10
  configFilePathFromEnvironment: string | undefined;
11
11
  };
12
+ export declare function doesConfigFileExistAtPath(path: string): boolean;
12
13
  export declare function readConfigFile(configPath: string): string;
13
14
  export declare function removeUndefinedFieldsFromConfigAccount<T extends HubSpotConfigAccount | Partial<HubSpotConfigAccount> = HubSpotConfigAccount>(account: T): T;
14
15
  export declare function formatConfigForWrite(config: HubSpotConfig): {
@@ -72,3 +73,7 @@ export declare function getConfigAccountByIdentifier(accounts: Array<HubSpotConf
72
73
  export declare function getConfigAccountByInferredIdentifier(accounts: Array<HubSpotConfigAccount>, accountIdentifier: string | number): HubSpotConfigAccount | undefined;
73
74
  export declare function getConfigAccountIndexById(accounts: Array<HubSpotConfigAccount>, id: number): number;
74
75
  export declare function isConfigAccountValid(account: Partial<HubSpotConfigAccount>): boolean;
76
+ export declare function handleConfigFileSystemError(error: unknown, path: string): {
77
+ message?: string;
78
+ type: HubSpotConfigErrorType;
79
+ };
package/config/utils.js CHANGED
@@ -3,7 +3,7 @@ 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.isConfigAccountValid = exports.getConfigAccountIndexById = exports.getConfigAccountByInferredIdentifier = exports.getConfigAccountByIdentifier = exports.getAccountIdentifierAndType = exports.buildConfigFromEnvironment = exports.parseConfig = exports.normalizeParsedConfig = exports.writeConfigFile = exports.formatConfigForWrite = exports.removeUndefinedFieldsFromConfigAccount = exports.readConfigFile = exports.getConfigPathEnvironmentVariables = exports.getLocalConfigDefaultFilePath = exports.getLocalConfigFilePath = exports.getGlobalConfigFilePath = void 0;
6
+ exports.handleConfigFileSystemError = exports.isConfigAccountValid = exports.getConfigAccountIndexById = exports.getConfigAccountByInferredIdentifier = exports.getConfigAccountByIdentifier = exports.getAccountIdentifierAndType = exports.buildConfigFromEnvironment = exports.parseConfig = exports.normalizeParsedConfig = exports.writeConfigFile = exports.formatConfigForWrite = exports.removeUndefinedFieldsFromConfigAccount = exports.readConfigFile = exports.doesConfigFileExistAtPath = exports.getConfigPathEnvironmentVariables = exports.getLocalConfigDefaultFilePath = exports.getLocalConfigFilePath = exports.getGlobalConfigFilePath = void 0;
7
7
  const fs_extra_1 = __importDefault(require("fs-extra"));
8
8
  const js_yaml_1 = __importDefault(require("js-yaml"));
9
9
  const findup_sync_1 = __importDefault(require("findup-sync"));
@@ -24,7 +24,7 @@ function getLocalConfigFilePath() {
24
24
  return (0, findup_sync_1.default)([
25
25
  config_1.DEFAULT_HUBSPOT_CONFIG_YAML_FILE_NAME,
26
26
  config_1.DEFAULT_HUBSPOT_CONFIG_YAML_FILE_NAME.replace('.yml', '.yaml'),
27
- ]);
27
+ ], { cwd: (0, path_1.getCwd)() });
28
28
  }
29
29
  exports.getLocalConfigFilePath = getLocalConfigFilePath;
30
30
  function getLocalConfigDefaultFilePath() {
@@ -44,18 +44,24 @@ function getConfigPathEnvironmentVariables() {
44
44
  };
45
45
  }
46
46
  exports.getConfigPathEnvironmentVariables = getConfigPathEnvironmentVariables;
47
+ function doesConfigFileExistAtPath(path) {
48
+ try {
49
+ return fs_extra_1.default.existsSync(path);
50
+ }
51
+ catch (error) {
52
+ const { message, type } = handleConfigFileSystemError(error, path);
53
+ throw new HubSpotConfigError_1.HubSpotConfigError(message, type, config_1.HUBSPOT_CONFIG_OPERATIONS.READ, { cause: error });
54
+ }
55
+ }
56
+ exports.doesConfigFileExistAtPath = doesConfigFileExistAtPath;
47
57
  function readConfigFile(configPath) {
48
- let source = '';
49
58
  try {
50
- source = fs_extra_1.default.readFileSync(configPath).toString();
59
+ return fs_extra_1.default.readFileSync(configPath).toString();
51
60
  }
52
61
  catch (err) {
53
- throw new FileSystemError_1.FileSystemError({ cause: err }, {
54
- filepath: configPath,
55
- operation: 'read',
56
- });
62
+ const { message, type } = handleConfigFileSystemError(err, configPath);
63
+ throw new HubSpotConfigError_1.HubSpotConfigError(message, type, config_1.HUBSPOT_CONFIG_OPERATIONS.READ, { cause: err });
57
64
  }
58
- return source;
59
65
  }
60
66
  exports.readConfigFile = readConfigFile;
61
67
  function removeUndefinedFieldsFromConfigAccount(account) {
@@ -111,7 +117,7 @@ function formatConfigForWrite(config) {
111
117
  }
112
118
  exports.formatConfigForWrite = formatConfigForWrite;
113
119
  function writeConfigFile(config, configPath) {
114
- const source = js_yaml_1.default.dump(JSON.parse(JSON.stringify(formatConfigForWrite(config), null, 2)));
120
+ const source = js_yaml_1.default.dump(formatConfigForWrite(config));
115
121
  try {
116
122
  fs_extra_1.default.ensureFileSync(configPath);
117
123
  fs_extra_1.default.writeFileSync(configPath, source);
@@ -136,6 +142,9 @@ function getAccountType(sandboxAccountType) {
136
142
  return config_1.HUBSPOT_ACCOUNT_TYPES.STANDARD;
137
143
  }
138
144
  function normalizeParsedConfig(parsedConfig) {
145
+ if (!parsedConfig.portals && !parsedConfig.accounts) {
146
+ parsedConfig.accounts = [];
147
+ }
139
148
  if (parsedConfig.portals) {
140
149
  parsedConfig.accounts = parsedConfig.portals.map(account => {
141
150
  if (account.portalId) {
@@ -325,3 +334,19 @@ function isConfigAccountValid(account) {
325
334
  return valid;
326
335
  }
327
336
  exports.isConfigAccountValid = isConfigAccountValid;
337
+ function handleConfigFileSystemError(error, path) {
338
+ let message;
339
+ let type = config_1.HUBSPOT_CONFIG_ERROR_TYPES.UNKNOWN;
340
+ if (error instanceof Error && 'code' in error) {
341
+ if (error.code === 'ENOENT') {
342
+ message = (0, lang_1.i18n)('config.utils.handleConfigFileSystemError.configNotFoundError', { path });
343
+ type = config_1.HUBSPOT_CONFIG_ERROR_TYPES.CONFIG_NOT_FOUND;
344
+ }
345
+ else if (error.code === 'EACCES') {
346
+ message = (0, lang_1.i18n)('config.utils.handleConfigFileSystemError.insufficientPermissionsError', { path });
347
+ type = config_1.HUBSPOT_CONFIG_ERROR_TYPES.INSUFFICIENT_PERMISSIONS;
348
+ }
349
+ }
350
+ return { message, type };
351
+ }
352
+ exports.handleConfigFileSystemError = handleConfigFileSystemError;
@@ -18,6 +18,7 @@ export declare const ALLOW_AUTO_UPDATES = "allowAutoUpdates";
18
18
  export declare const DEFAULT_ACCOUNT = "defaultAccount";
19
19
  export declare const DEFAULT_PORTAL = "defaultPortal";
20
20
  export declare const MIN_HTTP_TIMEOUT = 3000;
21
+ export declare const MCP_TOTAL_TOOL_CALLS_STATE = "mcpTotalToolCalls";
21
22
  export declare const HUBSPOT_ACCOUNT_TYPES: {
22
23
  readonly DEVELOPMENT_SANDBOX: "DEVELOPMENT_SANDBOX";
23
24
  readonly DEVELOPER_TEST: "DEVELOPER_TEST";
@@ -58,14 +59,17 @@ export declare const ACCOUNT_IDENTIFIERS: {
58
59
  };
59
60
  export declare const HUBSPOT_CONFIG_ERROR_TYPES: {
60
61
  readonly CONFIG_NOT_FOUND: "CONFIG_NOT_FOUND";
62
+ readonly INSUFFICIENT_PERMISSIONS: "INSUFFICIENT_PERMISSIONS";
61
63
  readonly ACCOUNT_NOT_FOUND: "ACCOUNT_NOT_FOUND";
62
64
  readonly NO_DEFAULT_ACCOUNT: "NO_DEFAULT_ACCOUNT";
63
65
  readonly INVALID_ENVIRONMENT_VARIABLES: "ENVIRONMENT_VARIABLES";
64
66
  readonly YAML_PARSING: "YAML_PARSING";
65
67
  readonly INVALID_ACCOUNT: "INVALID_ACCOUNT";
66
68
  readonly INVALID_FIELD: "INVALID_FIELD";
69
+ readonly UNKNOWN: "UNKNOWN";
67
70
  };
68
71
  export declare const HUBSPOT_CONFIG_OPERATIONS: {
69
72
  readonly READ: "READ";
70
73
  readonly WRITE: "WRITE";
74
+ readonly DELETE: "DELETE";
71
75
  };
@@ -3,7 +3,7 @@ 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.HUBSPOT_CONFIG_OPERATIONS = exports.HUBSPOT_CONFIG_ERROR_TYPES = exports.ACCOUNT_IDENTIFIERS = exports.ENVIRONMENT_VARIABLES = exports.CONFIG_FLAGS = exports.HUBSPOT_ACCOUNT_TYPE_STRINGS = exports.HUBSPOT_ACCOUNT_TYPES = exports.MIN_HTTP_TIMEOUT = exports.DEFAULT_PORTAL = exports.DEFAULT_ACCOUNT = exports.ALLOW_AUTO_UPDATES = exports.AUTO_OPEN_BROWSER = exports.ALLOW_USAGE_TRACKING = exports.HTTP_USE_LOCALHOST = exports.ENV = exports.HTTP_TIMEOUT = exports.DEFAULT_CMS_PUBLISH_MODE = exports.DEFAULT_ACCOUNT_OVERRIDE_ERROR_ACCOUNT_NOT_FOUND = exports.DEFAULT_ACCOUNT_OVERRIDE_ERROR_INVALID_ID = exports.DEFAULT_ACCOUNT_OVERRIDE_FILE_NAME = exports.STATE_FILE_PATH = exports.GLOBAL_CONFIG_PATH = exports.HUBSPOT_STATE_FILE = exports.HUBSPOT_CONFIGURATION_FILE = exports.HUBSPOT_CONFIGURATION_FOLDER = exports.ARCHIVED_HUBSPOT_CONFIG_YAML_FILE_NAME = exports.DEFAULT_HUBSPOT_CONFIG_YAML_FILE_NAME = void 0;
6
+ exports.HUBSPOT_CONFIG_OPERATIONS = exports.HUBSPOT_CONFIG_ERROR_TYPES = exports.ACCOUNT_IDENTIFIERS = exports.ENVIRONMENT_VARIABLES = exports.CONFIG_FLAGS = exports.HUBSPOT_ACCOUNT_TYPE_STRINGS = exports.HUBSPOT_ACCOUNT_TYPES = exports.MCP_TOTAL_TOOL_CALLS_STATE = exports.MIN_HTTP_TIMEOUT = exports.DEFAULT_PORTAL = exports.DEFAULT_ACCOUNT = exports.ALLOW_AUTO_UPDATES = exports.AUTO_OPEN_BROWSER = exports.ALLOW_USAGE_TRACKING = exports.HTTP_USE_LOCALHOST = exports.ENV = exports.HTTP_TIMEOUT = exports.DEFAULT_CMS_PUBLISH_MODE = exports.DEFAULT_ACCOUNT_OVERRIDE_ERROR_ACCOUNT_NOT_FOUND = exports.DEFAULT_ACCOUNT_OVERRIDE_ERROR_INVALID_ID = exports.DEFAULT_ACCOUNT_OVERRIDE_FILE_NAME = exports.STATE_FILE_PATH = exports.GLOBAL_CONFIG_PATH = exports.HUBSPOT_STATE_FILE = exports.HUBSPOT_CONFIGURATION_FILE = exports.HUBSPOT_CONFIGURATION_FOLDER = exports.ARCHIVED_HUBSPOT_CONFIG_YAML_FILE_NAME = exports.DEFAULT_HUBSPOT_CONFIG_YAML_FILE_NAME = void 0;
7
7
  const lang_1 = require("../utils/lang");
8
8
  const path_1 = __importDefault(require("path"));
9
9
  const os_1 = __importDefault(require("os"));
@@ -27,6 +27,7 @@ exports.ALLOW_AUTO_UPDATES = 'allowAutoUpdates';
27
27
  exports.DEFAULT_ACCOUNT = 'defaultAccount';
28
28
  exports.DEFAULT_PORTAL = 'defaultPortal';
29
29
  exports.MIN_HTTP_TIMEOUT = 3000;
30
+ exports.MCP_TOTAL_TOOL_CALLS_STATE = 'mcpTotalToolCalls';
30
31
  exports.HUBSPOT_ACCOUNT_TYPES = {
31
32
  DEVELOPMENT_SANDBOX: 'DEVELOPMENT_SANDBOX',
32
33
  DEVELOPER_TEST: 'DEVELOPER_TEST',
@@ -67,14 +68,17 @@ exports.ACCOUNT_IDENTIFIERS = {
67
68
  };
68
69
  exports.HUBSPOT_CONFIG_ERROR_TYPES = {
69
70
  CONFIG_NOT_FOUND: 'CONFIG_NOT_FOUND',
71
+ INSUFFICIENT_PERMISSIONS: 'INSUFFICIENT_PERMISSIONS',
70
72
  ACCOUNT_NOT_FOUND: 'ACCOUNT_NOT_FOUND',
71
73
  NO_DEFAULT_ACCOUNT: 'NO_DEFAULT_ACCOUNT',
72
74
  INVALID_ENVIRONMENT_VARIABLES: 'ENVIRONMENT_VARIABLES',
73
75
  YAML_PARSING: 'YAML_PARSING',
74
76
  INVALID_ACCOUNT: 'INVALID_ACCOUNT',
75
77
  INVALID_FIELD: 'INVALID_FIELD',
78
+ UNKNOWN: 'UNKNOWN',
76
79
  };
77
80
  exports.HUBSPOT_CONFIG_OPERATIONS = {
78
81
  READ: 'READ',
79
82
  WRITE: 'WRITE',
83
+ DELETE: 'DELETE',
80
84
  };
package/http/index.js CHANGED
@@ -42,22 +42,29 @@ const HubSpotHttpError_1 = require("../models/HubSpotHttpError");
42
42
  const auth_1 = require("../constants/auth");
43
43
  const localDevAuth_1 = require("../api/localDevAuth");
44
44
  const util = __importStar(require("util"));
45
+ const trackUsage_1 = require("../lib/trackUsage");
45
46
  const i18nKey = 'http.index';
47
+ const IGNORE_URLS_NETWORK_DEBUG = [
48
+ localDevAuth_1.LOCALDEVAUTH_ACCESS_TOKEN_PATH,
49
+ trackUsage_1.CMS_CLI_USAGE_PATH,
50
+ trackUsage_1.VSCODE_USAGE_PATH,
51
+ ];
46
52
  function logRequest(response) {
47
53
  try {
48
- if (process.env.HUBSPOT_NETWORK_LOGGING) {
49
- if (response.config.url === localDevAuth_1.LOCALDEVAUTH_ACCESS_TOKEN_PATH) {
50
- // Don't log access tokens
51
- return;
52
- }
53
- logger_1.logger.debug(util.inspect({
54
- method: response.config.method,
55
- baseURL: response.config.baseURL,
56
- url: response.config.url,
57
- data: response.data,
58
- status: response.status,
59
- }, false, null, true));
54
+ if (!process.env.HUBSPOT_NETWORK_LOGGING) {
55
+ return;
56
+ }
57
+ if (response?.config?.url &&
58
+ IGNORE_URLS_NETWORK_DEBUG.includes(response.config.url)) {
59
+ return;
60
60
  }
61
+ logger_1.logger.debug(util.inspect({
62
+ method: response.config.method,
63
+ baseURL: response.config.baseURL,
64
+ url: response.config.url,
65
+ data: response.data,
66
+ status: response.status,
67
+ }, false, null, true));
61
68
  }
62
69
  catch (error) {
63
70
  // Ignore any errors that occur while logging the response
package/lang/en.json CHANGED
@@ -291,7 +291,14 @@
291
291
  "updateDefaultCmsPublishMode": {
292
292
  "invalidCmsPublishMode": "Error updating config default CMS publish mode: CMS publish can only be set to 'draft' or 'publish'"
293
293
  },
294
+ "getConfigAccountEnvironment": {
295
+ "accountNotFound": "Attempted to get environment for account with identifier {{ identifier }}, but that account was not found in config"
296
+ },
294
297
  "utils": {
298
+ "handleConfigFileSystemError": {
299
+ "configNotFoundError": "No config file found at {{ path }}.",
300
+ "insufficientPermissionsError": "Insufficient permissions to access config file at {{ path }}"
301
+ },
295
302
  "isConfigAccountValid": {
296
303
  "missingAccount": "Invalid config: at least one account in config is missing data",
297
304
  "missingAuthType": "Invalid config: account {{ accountId }} has no authType",
@@ -344,6 +351,9 @@
344
351
  }
345
352
  },
346
353
  "getCurrentState": {
354
+ "debug": {
355
+ "emptyStateFile": "State file is empty, using default state"
356
+ },
347
357
  "errors": {
348
358
  "errorReading": "Error reading CLI state, using defaults: {{ error }}"
349
359
  }
@@ -379,7 +389,7 @@
379
389
  }
380
390
  },
381
391
  "HubSpotConfigError": {
382
- "baseMessage": "An error occurred while {{ operation }} your HubSpot config {{ configType }}: {{ message }}"
392
+ "baseMessage": "An error occurred while {{ operation }} your HubSpot config {{ configType }}{{ message }}"
383
393
  }
384
394
  },
385
395
  "utils": {
@@ -121,10 +121,8 @@ async function authorizedScopesForPortalAndUser(accountId) {
121
121
  exports.authorizedScopesForPortalAndUser = authorizedScopesForPortalAndUser;
122
122
  async function updateConfigWithAccessToken(token, personalAccessKey, env, name, makeDefault = false) {
123
123
  const { portalId, accessToken, expiresAt, accountType } = token;
124
- const account = name
125
- ? (0, config_1.getConfigAccountByName)(name)
126
- : (0, config_1.getConfigDefaultAccount)();
127
- const accountEnv = env || account.env;
124
+ const account = (0, config_1.getConfigAccountIfExists)(portalId);
125
+ const accountEnv = env || account?.env || environments_1.ENVIRONMENTS.PROD;
128
126
  let parentAccountId;
129
127
  try {
130
128
  if (accountType === config_2.HUBSPOT_ACCOUNT_TYPES.STANDARD_SANDBOX ||
@@ -161,15 +159,21 @@ async function updateConfigWithAccessToken(token, personalAccessKey, env, name,
161
159
  accountId: portalId,
162
160
  accountType,
163
161
  personalAccessKey,
164
- name: name || account.name,
162
+ name: name || account?.name || token.hubName,
165
163
  authType: auth_1.PERSONAL_ACCESS_KEY_AUTH_METHOD.value,
166
164
  auth: { tokenInfo: { accessToken, expiresAt } },
167
165
  parentAccountId,
168
166
  env: accountEnv,
169
167
  };
170
- (0, config_1.updateConfigAccount)(updatedAccount);
171
- if (makeDefault && name) {
172
- (0, config_1.setConfigAccountAsDefault)(name);
168
+ // Add new account if it doesn't exist, otherwise update existing account
169
+ if (account) {
170
+ (0, config_1.updateConfigAccount)(updatedAccount);
171
+ }
172
+ else {
173
+ (0, config_1.addConfigAccount)(updatedAccount);
174
+ }
175
+ if (makeDefault) {
176
+ (0, config_1.setConfigAccountAsDefault)(updatedAccount.accountId);
173
177
  }
174
178
  return updatedAccount;
175
179
  }
@@ -7,11 +7,10 @@ exports.portManagerHasActiveServers = exports.deleteServerInstance = exports.get
7
7
  const axios_1 = __importDefault(require("axios"));
8
8
  const PortManagerServer_1 = require("../utils/PortManagerServer");
9
9
  const ports_1 = require("../constants/ports");
10
- const detectPort_1 = require("../utils/detectPort");
11
10
  const logger_1 = require("./logger");
12
11
  exports.BASE_URL = `http://localhost:${ports_1.PORT_MANAGER_SERVER_PORT}`;
13
12
  async function isPortManagerPortAvailable() {
14
- return ((await (0, detectPort_1.detectPort)(ports_1.PORT_MANAGER_SERVER_PORT)) === ports_1.PORT_MANAGER_SERVER_PORT);
13
+ return PortManagerServer_1.PortManagerServer.portAvailable();
15
14
  }
16
15
  exports.isPortManagerPortAvailable = isPortManagerPortAvailable;
17
16
  async function isPortManagerServerRunning() {
@@ -1 +1,3 @@
1
+ export declare const CMS_CLI_USAGE_PATH: string;
2
+ export declare const VSCODE_USAGE_PATH: string;
1
3
  export declare function trackUsage(eventName: string, eventClass: string, meta?: {}, accountId?: number): Promise<void>;
package/lib/trackUsage.js CHANGED
@@ -3,7 +3,7 @@ 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.trackUsage = void 0;
6
+ exports.trackUsage = exports.VSCODE_USAGE_PATH = exports.CMS_CLI_USAGE_PATH = void 0;
7
7
  const axios_1 = __importDefault(require("axios"));
8
8
  const getAxiosConfig_1 = require("../http/getAxiosConfig");
9
9
  const logger_1 = require("./logger");
@@ -13,6 +13,8 @@ const fileMapper_1 = require("../api/fileMapper");
13
13
  const lang_1 = require("../utils/lang");
14
14
  const environment_1 = require("./environment");
15
15
  const i18nKey = 'lib.trackUsage';
16
+ exports.CMS_CLI_USAGE_PATH = `${fileMapper_1.FILE_MAPPER_API_PATH}/cms-cli-usage`;
17
+ exports.VSCODE_USAGE_PATH = `${fileMapper_1.FILE_MAPPER_API_PATH}/vscode-extension-usage`;
16
18
  async function trackUsage(eventName, eventClass, meta = {}, accountId) {
17
19
  const usageEvent = {
18
20
  accountId,
@@ -24,18 +26,17 @@ async function trackUsage(eventName, eventClass, meta = {}, accountId) {
24
26
  VSCODE_EXTENSION_INTERACTION: 'vscode-extension-interaction',
25
27
  CLI_INTERACTION: 'cli-interaction',
26
28
  };
27
- let analyticsEndpoint;
29
+ let path = fileMapper_1.FILE_MAPPER_API_PATH;
28
30
  switch (eventName) {
29
31
  case EVENT_TYPES.CLI_INTERACTION:
30
- analyticsEndpoint = 'cms-cli-usage';
32
+ path = exports.CMS_CLI_USAGE_PATH;
31
33
  break;
32
34
  case EVENT_TYPES.VSCODE_EXTENSION_INTERACTION:
33
- analyticsEndpoint = 'vscode-extension-usage';
35
+ path = exports.VSCODE_USAGE_PATH;
34
36
  break;
35
37
  default:
36
38
  logger_1.logger.debug((0, lang_1.i18n)(`${i18nKey}.invalidEvent`, { eventName }));
37
39
  }
38
- const path = `${fileMapper_1.FILE_MAPPER_API_PATH}/${analyticsEndpoint}`;
39
40
  const account = accountId && (0, config_1.getConfigAccountById)(accountId);
40
41
  if (account && account.authType === 'personalaccesskey') {
41
42
  logger_1.logger.debug((0, lang_1.i18n)(`${i18nKey}.sendingEventAuthenticated`));
@@ -2,5 +2,5 @@ import { HubSpotConfigErrorType, HubSpotConfigOperation } from '../types/Config'
2
2
  export declare class HubSpotConfigError extends Error {
3
3
  type: HubSpotConfigErrorType;
4
4
  operation: HubSpotConfigOperation;
5
- constructor(message: string, type: HubSpotConfigErrorType, operation: HubSpotConfigOperation, options?: ErrorOptions);
5
+ constructor(message: string | undefined, type: HubSpotConfigErrorType, operation: HubSpotConfigOperation, options?: ErrorOptions);
6
6
  }
@@ -4,6 +4,11 @@ exports.HubSpotConfigError = void 0;
4
4
  const config_1 = require("../constants/config");
5
5
  const lang_1 = require("../utils/lang");
6
6
  const NAME = 'HubSpotConfigError';
7
+ const OPERATION_TEXT = {
8
+ [config_1.HUBSPOT_CONFIG_OPERATIONS.READ]: 'reading',
9
+ [config_1.HUBSPOT_CONFIG_OPERATIONS.WRITE]: 'writing to',
10
+ [config_1.HUBSPOT_CONFIG_OPERATIONS.DELETE]: 'deleting',
11
+ };
7
12
  function isEnvironmentError(type) {
8
13
  return type === config_1.HUBSPOT_CONFIG_ERROR_TYPES.INVALID_ENVIRONMENT_VARIABLES;
9
14
  }
@@ -14,10 +19,10 @@ class HubSpotConfigError extends Error {
14
19
  const configType = isEnvironmentError(type)
15
20
  ? 'environment variables'
16
21
  : 'file';
17
- const operationText = operation === config_1.HUBSPOT_CONFIG_OPERATIONS.WRITE ? 'writing to' : 'reading';
22
+ const operationText = OPERATION_TEXT[operation];
18
23
  const withBaseMessage = (0, lang_1.i18n)('models.HubSpotConfigError.baseMessage', {
19
24
  configType,
20
- message,
25
+ message: message ? `: ${message}` : '',
21
26
  operation: operationText,
22
27
  });
23
28
  super(withBaseMessage, options);
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@hubspot/local-dev-lib",
3
- "version": "0.5.0-experimental.1",
3
+ "version": "0.5.0-experimental.10",
4
4
  "description": "Provides library functionality for HubSpot local development tooling, including the HubSpot CLI",
5
5
  "repository": {
6
6
  "type": "git",
@@ -21,7 +21,6 @@
21
21
  "license": "Apache-2.0",
22
22
  "devDependencies": {
23
23
  "@hubspot/npm-scripts": "0.0.4",
24
- "@inquirer/prompts": "^7.0.1",
25
24
  "@types/content-disposition": "^0.5.5",
26
25
  "@types/cors": "^2.8.15",
27
26
  "@types/debounce": "^1.2.1",
package/types/Config.d.ts CHANGED
@@ -29,7 +29,7 @@ export type GitInclusionResult = {
29
29
  gitignoreFiles: Array<string>;
30
30
  };
31
31
  export type ConfigFlag = ValueOf<typeof CONFIG_FLAGS>;
32
- export type CLIState = {
32
+ export type HubSpotState = {
33
33
  mcpTotalToolCalls: number;
34
34
  };
35
35
  export type HubSpotConfigErrorType = ValueOf<typeof HUBSPOT_CONFIG_ERROR_TYPES>;
@@ -1,7 +1,7 @@
1
1
  /// <reference types="node" />
2
- import { Express, Request, Response } from 'express';
2
+ import { Express } from 'express';
3
3
  import { Server } from 'http';
4
- import { RequestPortsData, ServerPortMap } from '../types/PortManager';
4
+ import { ServerPortMap } from '../types/PortManager';
5
5
  export declare const HEALTH_CHECK_PATH = "/port-manager-health-check";
6
6
  export declare const SERVICE_HEALTHY = "OK";
7
7
  declare class _PortManagerServer {
@@ -10,19 +10,18 @@ declare class _PortManagerServer {
10
10
  serverPortMap: ServerPortMap;
11
11
  constructor();
12
12
  init(): Promise<void>;
13
- reset(): void;
14
- listen(): Promise<Server>;
15
- setupRoutes(): void;
16
- setPort(instanceId: string, port: number): void;
17
- deletePort(instanceId: string): void;
18
- send404(res: Response, instanceId: string): void;
19
- getServers: (req: Request, res: Response) => Promise<void>;
20
- getServerPortByInstanceId: (req: Request, res: Response) => void;
21
- assignPortsToServers: (req: Request<never, never, {
22
- portData: Array<RequestPortsData>;
23
- }>, res: Response) => Promise<void>;
24
- deleteServerInstance: (req: Request, res: Response) => void;
25
- closeServer: (req: Request, res: Response) => void;
13
+ private reset;
14
+ portAvailable(): Promise<boolean>;
15
+ private listen;
16
+ private setupRoutes;
17
+ private setPort;
18
+ private deletePort;
19
+ private send404;
20
+ private getServers;
21
+ private getServerPortByInstanceId;
22
+ private assignPortsToServers;
23
+ private deleteServerInstance;
24
+ private closeServer;
26
25
  }
27
26
  export declare const PortManagerServer: _PortManagerServer;
28
27
  export {};
@@ -8,7 +8,6 @@ const express_1 = __importDefault(require("express"));
8
8
  const cors_1 = __importDefault(require("cors"));
9
9
  const detectPort_1 = require("./detectPort");
10
10
  const ports_1 = require("../constants/ports");
11
- const errors_1 = require("../errors");
12
11
  const logger_1 = require("../lib/logger");
13
12
  const lang_1 = require("./lang");
14
13
  const i18nKey = 'utils.PortManagerServer';
@@ -22,6 +21,11 @@ class _PortManagerServer {
22
21
  this.serverPortMap = {};
23
22
  }
24
23
  async init() {
24
+ if (!(await this.portAvailable())) {
25
+ throw new Error((0, lang_1.i18n)(`${i18nKey}.errors.portInUse`, {
26
+ port: ports_1.PORT_MANAGER_SERVER_PORT,
27
+ }));
28
+ }
25
29
  if (this.app) {
26
30
  throw new Error((0, lang_1.i18n)(`${i18nKey}.errors.duplicateInstance`));
27
31
  }
@@ -29,24 +33,17 @@ class _PortManagerServer {
29
33
  this.app.use(express_1.default.json());
30
34
  this.app.use((0, cors_1.default)());
31
35
  this.setupRoutes();
32
- try {
33
- this.server = await this.listen();
34
- logger_1.logger.debug(this.server);
35
- }
36
- catch (e) {
37
- if ((0, errors_1.isSystemError)(e) && e.code === 'EADDRINUSE') {
38
- throw new Error((0, lang_1.i18n)(`${i18nKey}.errors.portInUse`, {
39
- port: ports_1.PORT_MANAGER_SERVER_PORT,
40
- }), { cause: e });
41
- }
42
- throw e;
43
- }
36
+ this.server = await this.listen();
37
+ logger_1.logger.debug(this.server);
44
38
  }
45
39
  reset() {
46
40
  this.app = undefined;
47
41
  this.server = undefined;
48
42
  this.serverPortMap = {};
49
43
  }
44
+ async portAvailable() {
45
+ return ((await (0, detectPort_1.detectPort)(ports_1.PORT_MANAGER_SERVER_PORT)) === ports_1.PORT_MANAGER_SERVER_PORT);
46
+ }
50
47
  listen() {
51
48
  return new Promise((resolve, reject) => {
52
49
  const server = this.app.listen(ports_1.PORT_MANAGER_SERVER_PORT, () => {