From 5d3aec41551fbc76c3bd2cd1be57678bdfaff5a7 Mon Sep 17 00:00:00 2001 From: Joe Yeager Date: Wed, 15 Jan 2025 10:23:37 -0800 Subject: [PATCH 1/6] chore: Add a debugging command (#1340) --- package.json | 1 + 1 file changed, 1 insertion(+) diff --git a/package.json b/package.json index 06cc0c486..d27048d5a 100644 --- a/package.json +++ b/package.json @@ -72,6 +72,7 @@ "circular-deps": "yarn madge --circular .", "release": "yarn ts-node ./scripts/release.ts release", "hs": "yarn build && node ./dist/bin/hs", + "hs-debug": "yarn build && NODE_DEBUG=http* node --inspect-brk ./dist/bin/hs", "update-ldl": "yarn add --exact @hubspot/local-dev-lib@latest" }, "lint-staged": { From e8f353fb91845835b716447eaa2949c71ae7e629 Mon Sep 17 00:00:00 2001 From: ruslanhubspot <165080640+ruslanhubspot@users.noreply.github.com> Date: Wed, 15 Jan 2025 16:34:39 -0500 Subject: [PATCH 2/6] Update hs upload --clean flag description (#1343) --- lang/en.lyaml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/lang/en.lyaml b/lang/en.lyaml index 0b4f5c7e4..10a8691b0 100644 --- a/lang/en.lyaml +++ b/lang/en.lyaml @@ -972,7 +972,7 @@ en: convertFields: describe: "If true, converts any javascript fields files contained in module folder or project root." clean: - describe: "Will cause upload to delete files in your HubSpot account that are not found locally." + describe: "Will delete the destination directory and its contents before uploading. This will also clear the global content associated with any global partial templates and modules." force: describe: "Skips confirmation prompts when doing a clean upload." previewUrl: "To preview this theme, visit: {{ previewUrl }}" From c045dfbcdd8d2f67dd27dbb3e27b152d3e35e9b5 Mon Sep 17 00:00:00 2001 From: Camden Phalen Date: Thu, 16 Jan 2025 10:59:22 -0500 Subject: [PATCH 3/6] Convert lib/serverlessLogs and lib/buildAccount to TS (#1337) --- commands/logs.ts | 8 +- commands/sandbox/create.ts | 12 +- lang/en.lyaml | 2 +- lib/__tests__/serverlessLogs.test.ts | 48 ++--- lib/buildAccount.ts | 256 ++++++++++++++----------- lib/localDev.ts | 31 +-- lib/prompts/personalAccessKeyPrompt.ts | 2 +- lib/sandboxes.ts | 2 +- lib/serverlessLogs.ts | 98 +++++----- lib/ui/serverlessFunctionLogs.ts | 59 +++--- package.json | 2 +- yarn.lock | 8 +- 12 files changed, 265 insertions(+), 263 deletions(-) diff --git a/commands/logs.ts b/commands/logs.ts index 3570a1416..c6e86375e 100644 --- a/commands/logs.ts +++ b/commands/logs.ts @@ -61,13 +61,7 @@ const endpointLog = async (accountId, functionPath, options) => { } }; - await tailLogs({ - accountId, - compact, - tailCall, - fetchLatest, - name: functionPath, - }); + await tailLogs(accountId, functionPath, fetchLatest, tailCall, compact); } else if (latest) { try { const { data } = await getLatestFunctionLog(accountId, functionPath); diff --git a/commands/sandbox/create.ts b/commands/sandbox/create.ts index 33dbb1314..d05ef2b77 100644 --- a/commands/sandbox/create.ts +++ b/commands/sandbox/create.ts @@ -28,7 +28,7 @@ const { HUBSPOT_ACCOUNT_TYPES, HUBSPOT_ACCOUNT_TYPE_STRINGS, } = require('@hubspot/local-dev-lib/constants/config'); -const { buildNewAccount } = require('../../lib/buildAccount'); +const { buildSandbox } = require('../../lib/buildAccount'); const { hubspotAccountNamePrompt, } = require('../../lib/prompts/accountNamePrompt'); @@ -130,13 +130,13 @@ exports.handler = async options => { } try { - const { result } = await buildNewAccount({ - name: sandboxName, - accountType: sandboxType, + const result = await buildSandbox( + sandboxName, accountConfig, + sandboxType, env, - force, - }); + force + ); const sandboxAccountConfig = getAccountConfig(result.sandbox.sandboxHubId); // For v1 sandboxes, keep sync here. Once we migrate to v2, this will be handled by BE automatically diff --git a/lang/en.lyaml b/lang/en.lyaml index 10a8691b0..db54c51ef 100644 --- a/lang/en.lyaml +++ b/lang/en.lyaml @@ -1499,7 +1499,7 @@ en: missingScopeError: "Couldn't execute the {{ request }} because the access key for {{ accountName }} is missing required scopes. To update scopes, run {{ authCommand }}. Then deactivate the existing key and generate a new one that includes the missing scopes." serverless: verifyAccessKeyAndUserAccess: - fetchScopeDataError: "Error verifying access of scopeGroup {{ scopeGroup }}: {{ error }}" + fetchScopeDataError: "Error verifying access of scopeGroup {{ scopeGroup }}:" portalMissingScope: "Your account does not have access to this action. Talk to an account admin to request it." userMissingScope: "You don't have access to this action. Ask an account admin to change your permissions in Users & Teams settings." genericMissingScope: "Your access key does not allow this action. Please generate a new access key by running `hs auth personalaccesskey`." diff --git a/lib/__tests__/serverlessLogs.test.ts b/lib/__tests__/serverlessLogs.test.ts index 1cb92dd66..195787f82 100644 --- a/lib/__tests__/serverlessLogs.test.ts +++ b/lib/__tests__/serverlessLogs.test.ts @@ -12,16 +12,10 @@ const ACCOUNT_ID = 123; describe('lib/serverlessLogs', () => { describe('tailLogs()', () => { let stdinMock; - let spinnies; beforeEach(() => { jest.spyOn(process, 'exit').mockImplementation(() => {}); stdinMock = mockStdIn.stdin(); - spinnies = { - succeed: jest.fn(), - fail: jest.fn(), - stopAll: jest.fn(), - }; }); afterEach(() => { @@ -33,14 +27,16 @@ describe('lib/serverlessLogs', () => { const compact = false; const fetchLatest = jest.fn(() => { return Promise.resolve({ - id: '1234', - executionTime: 510, - log: 'Log message', - error: null, - status: 'SUCCESS', - createdAt: 1620232011451, - memory: '70/128 MB', - duration: '53.40 ms', + data: { + id: '1234', + executionTime: 510, + log: 'Log message', + error: null, + status: 'SUCCESS', + createdAt: 1620232011451, + memory: '70/128 MB', + duration: '53.40 ms', + }, }); }); const tailCall = jest.fn(() => { @@ -54,13 +50,7 @@ describe('lib/serverlessLogs', () => { }); }); - await tailLogs({ - accountId: ACCOUNT_ID, - compact, - spinnies, - fetchLatest, - tailCall, - }); + await tailLogs(ACCOUNT_ID, 'name', fetchLatest, tailCall, compact); jest.runOnlyPendingTimers(); expect(fetchLatest).toHaveBeenCalled(); @@ -116,13 +106,7 @@ describe('lib/serverlessLogs', () => { Promise.resolve({ data: latestLogResponse }) ); - await tailLogs({ - accountId: ACCOUNT_ID, - compact, - spinnies, - fetchLatest, - tailCall, - }); + await tailLogs(ACCOUNT_ID, 'name', fetchLatest, tailCall, compact); jest.runOnlyPendingTimers(); expect(outputLogs).toHaveBeenCalledWith( latestLogResponse, @@ -148,13 +132,7 @@ describe('lib/serverlessLogs', () => { ) ); - await tailLogs({ - accountId: ACCOUNT_ID, - compact, - spinnies, - fetchLatest, - tailCall, - }); + await tailLogs(ACCOUNT_ID, 'name', fetchLatest, tailCall, compact); jest.runOnlyPendingTimers(); expect(tailCall).toHaveBeenCalledTimes(2); }); diff --git a/lib/buildAccount.ts b/lib/buildAccount.ts index e6e236678..91f421bea 100644 --- a/lib/buildAccount.ts +++ b/lib/buildAccount.ts @@ -1,47 +1,39 @@ -// @ts-nocheck -const { +import { getAccessToken, updateConfigWithAccessToken, -} = require('@hubspot/local-dev-lib/personalAccessKey'); -const { - personalAccessKeyPrompt, -} = require('./prompts/personalAccessKeyPrompt'); -const { +} from '@hubspot/local-dev-lib/personalAccessKey'; +import { accountNameExistsInConfig, updateAccountConfig, writeConfig, getAccountId, -} = require('@hubspot/local-dev-lib/config'); -const { - getAccountIdentifier, -} = require('@hubspot/local-dev-lib/config/getAccountIdentifier'); -const { logger } = require('@hubspot/local-dev-lib/logger'); -const { i18n } = require('./lang'); -const { cliAccountNamePrompt } = require('./prompts/accountNamePrompt'); -const SpinniesManager = require('./ui/SpinniesManager'); -const { debugError, logError } = require('./errorHandlers/index'); -const { - createDeveloperTestAccount, -} = require('@hubspot/local-dev-lib/api/developerTestAccounts'); -const { - HUBSPOT_ACCOUNT_TYPES, -} = require('@hubspot/local-dev-lib/constants/config'); -const { createSandbox } = require('@hubspot/local-dev-lib/api/sandboxHubs'); -const { - SANDBOX_API_TYPE_MAP, - handleSandboxCreateError, -} = require('./sandboxes'); -const { - handleDeveloperTestAccountCreateError, -} = require('./developerTestAccounts'); - -async function saveAccountToConfig({ - env, - personalAccessKey, - accountName, - accountId, - force = false, -}) { +} from '@hubspot/local-dev-lib/config'; +import { getAccountIdentifier } from '@hubspot/local-dev-lib/config/getAccountIdentifier'; +import { logger } from '@hubspot/local-dev-lib/logger'; +import { createDeveloperTestAccount } from '@hubspot/local-dev-lib/api/developerTestAccounts'; +import { HUBSPOT_ACCOUNT_TYPES } from '@hubspot/local-dev-lib/constants/config'; +import { createSandbox } from '@hubspot/local-dev-lib/api/sandboxHubs'; +import { Environment } from '@hubspot/local-dev-lib/types/Config'; + +import { personalAccessKeyPrompt } from './prompts/personalAccessKeyPrompt'; +import { i18n } from './lang'; +import { cliAccountNamePrompt } from './prompts/accountNamePrompt'; +import SpinniesManager from './ui/SpinniesManager'; +import { debugError, logError } from './errorHandlers/index'; + +import { SANDBOX_API_TYPE_MAP, handleSandboxCreateError } from './sandboxes'; +import { handleDeveloperTestAccountCreateError } from './developerTestAccounts'; +import { CLIAccount } from '@hubspot/local-dev-lib/types/Accounts'; +import { DeveloperTestAccount } from '@hubspot/local-dev-lib/types/developerTestAccounts'; +import { SandboxResponse } from '@hubspot/local-dev-lib/types/Sandbox'; + +export async function saveAccountToConfig( + accountId: number | undefined, + accountName: string, + env: Environment, + personalAccessKey?: string, + force = false +): Promise { if (!personalAccessKey) { const configData = await personalAccessKeyPrompt({ env, @@ -57,8 +49,8 @@ async function saveAccountToConfig({ env ); - let validName = updatedConfig.name; - if (!updatedConfig.name) { + let validName = updatedConfig?.name || ''; + if (!updatedConfig?.name) { const nameForConfig = accountName.toLowerCase().split(' ').join('-'); validName = nameForConfig; const invalidAccountName = accountNameExistsInConfig(nameForConfig); @@ -83,8 +75,8 @@ async function saveAccountToConfig({ updateAccountConfig({ ...updatedConfig, - environment: updatedConfig.env, - tokenInfo: updatedConfig.auth.tokenInfo, + env: updatedConfig?.env, + tokenInfo: updatedConfig?.auth?.tokenInfo, name: validName, }); writeConfig(); @@ -93,105 +85,145 @@ async function saveAccountToConfig({ return validName; } -async function buildNewAccount({ - name, - accountType, - accountConfig, - env, - portalLimit, // Used only for developer test accounts - force = false, -}) { +export async function buildDeveloperTestAccount( + name: string, + accountConfig: CLIAccount, + env: Environment, + portalLimit: number +): Promise { + const i18nKey = 'lib.developerTestAccount.create.loading'; + + const id = getAccountIdentifier(accountConfig); + const accountId = getAccountId(id); + + if (!accountId) { + throw new Error(i18n(`${i18nKey}.fail`)); + } + SpinniesManager.init({ succeedColor: 'white', }); + + logger.log(''); + SpinniesManager.add('buildDeveloperTestAccount', { + text: i18n(`${i18nKey}.add`, { + accountName: name, + }), + }); + + let developerTestAccount: DeveloperTestAccount; + + try { + const { data } = await createDeveloperTestAccount(accountId, name); + + developerTestAccount = data; + + SpinniesManager.succeed('buildDeveloperTestAccount', { + text: i18n(`${i18nKey}.succeed`, { + accountName: name, + accountId: developerTestAccount.id, + }), + }); + } catch (e) { + debugError(e); + + SpinniesManager.fail('buildDeveloperTestAccount', { + text: i18n(`${i18nKey}.fail`, { + accountName: name, + }), + }); + + handleDeveloperTestAccountCreateError(e, accountId, env, portalLimit); + } + + try { + await saveAccountToConfig(accountId, name, env); + } catch (err) { + logError(err); + throw err; + } + + return developerTestAccount; +} + +type SandboxType = + | typeof HUBSPOT_ACCOUNT_TYPES.STANDARD_SANDBOX + | typeof HUBSPOT_ACCOUNT_TYPES.DEVELOPMENT_SANDBOX; + +type SandboxAccount = SandboxResponse & { + name: string; +}; + +export async function buildSandbox( + name: string, + accountConfig: CLIAccount, + sandboxType: SandboxType, + env: Environment, + force = false +): Promise { + let i18nKey: string; + if (sandboxType === HUBSPOT_ACCOUNT_TYPES.STANDARD_SANDBOX) { + i18nKey = 'lib.sandbox.create.loading.standard'; + } else { + i18nKey = 'lib.sandbox.create.loading.developer'; + } + const id = getAccountIdentifier(accountConfig); const accountId = getAccountId(id); - const isSandbox = - accountType === HUBSPOT_ACCOUNT_TYPES.STANDARD_SANDBOX || - accountType === HUBSPOT_ACCOUNT_TYPES.DEVELOPMENT_SANDBOX; - const isDeveloperTestAccount = - accountType === HUBSPOT_ACCOUNT_TYPES.DEVELOPER_TEST; - - let result; - let spinniesI18nKey; - if (isSandbox) { - if (accountType === HUBSPOT_ACCOUNT_TYPES.STANDARD_SANDBOX) { - spinniesI18nKey = 'lib.sandbox.create.loading.standard'; - } - if (accountType === HUBSPOT_ACCOUNT_TYPES.DEVELOPMENT_SANDBOX) { - spinniesI18nKey = 'lib.sandbox.create.loading.developer'; - } - } else if (isDeveloperTestAccount) { - spinniesI18nKey = 'lib.developerTestAccount.create.loading'; + + if (!accountId) { + throw new Error(i18n(`${i18nKey}.fail`)); } + SpinniesManager.init({ + succeedColor: 'white', + }); + logger.log(''); - SpinniesManager.add('buildNewAccount', { - text: i18n(`${spinniesI18nKey}.add`, { + SpinniesManager.add('buildSandbox', { + text: i18n(`${i18nKey}.add`, { accountName: name, }), }); - let resultAccountId; + let sandbox: SandboxAccount; + try { - if (isSandbox) { - const sandboxApiType = SANDBOX_API_TYPE_MAP[accountType]; // API expects sandbox type as 1 or 2. - - const { data } = await createSandbox(accountId, name, sandboxApiType); - result = { name, ...data }; - resultAccountId = result.sandbox.sandboxHubId; - } else if (isDeveloperTestAccount) { - const { data } = await createDeveloperTestAccount(accountId, name); - result = data; - resultAccountId = result.id; - } + const sandboxApiType = SANDBOX_API_TYPE_MAP[sandboxType]; + + const { data } = await createSandbox(accountId, name, sandboxApiType); + sandbox = { name, ...data }; - SpinniesManager.succeed('buildNewAccount', { - text: i18n(`${spinniesI18nKey}.succeed`, { + SpinniesManager.succeed('buildSandbox', { + text: i18n(`${i18nKey}.succeed`, { accountName: name, - accountId: resultAccountId, + accountId: sandbox.sandbox.sandboxHubId, }), }); - } catch (err) { - debugError(err); + } catch (e) { + debugError(e); - SpinniesManager.fail('buildNewAccount', { - text: i18n(`${spinniesI18nKey}.fail`, { + SpinniesManager.fail('buildSandbox', { + text: i18n(`${i18nKey}.fail`, { accountName: name, }), }); - if (isSandbox) { - handleSandboxCreateError(err, env, name, accountId); - } - if (isDeveloperTestAccount) { - handleDeveloperTestAccountCreateError(err, env, accountId, portalLimit); - } + handleSandboxCreateError(e, env, name, accountId); } - let configAccountName; - try { - // Response contains PAK, save to config here - configAccountName = await saveAccountToConfig({ + await saveAccountToConfig( + accountId, + name, env, - personalAccessKey: result.personalAccessKey, - accountName: name, - accountId: resultAccountId, - force, - }); + sandbox.personalAccessKey, + force + ); } catch (err) { logError(err); throw err; } - return { - configAccountName, - result, - }; + return sandbox; } - -module.exports = { - buildNewAccount, - saveAccountToConfig, -}; diff --git a/lib/localDev.ts b/lib/localDev.ts index 20d5b02b9..886e185ca 100644 --- a/lib/localDev.ts +++ b/lib/localDev.ts @@ -49,7 +49,11 @@ const { logError, ApiErrorContext } = require('./errorHandlers/index'); const { PERSONAL_ACCESS_KEY_AUTH_METHOD, } = require('@hubspot/local-dev-lib/constants/auth'); -const { buildNewAccount, saveAccountToConfig } = require('./buildAccount'); +const { + buildSandbox, + buildDeveloperTestAccount, + saveAccountToConfig, +} = require('./buildAccount'); const { hubspotAccountNamePrompt } = require('./prompts/accountNamePrompt'); const i18nKey = 'lib.localDev'; @@ -208,12 +212,12 @@ const createSandboxForLocalDev = async (accountId, accountConfig, env) => { accountId ); - const { result } = await buildNewAccount({ + const result = await buildSandbox( name, - accountType: HUBSPOT_ACCOUNT_TYPES.DEVELOPMENT_SANDBOX, accountConfig, - env, - }); + HUBSPOT_ACCOUNT_TYPES.DEVELOPMENT_SANDBOX, + env + ); const targetAccountId = result.sandbox.sandboxHubId; @@ -286,13 +290,12 @@ const createDeveloperTestAccountForLocalDev = async ( accountId ); - const { result } = await buildNewAccount({ + const result = await buildDeveloperTestAccount( name, - accountType: HUBSPOT_ACCOUNT_TYPES.DEVELOPER_TEST, accountConfig, env, - portalLimit: maxTestPortals, - }); + maxTestPortals + ); return result.id; } catch (err) { @@ -319,11 +322,11 @@ const useExistingDevTestAccount = async (env, account) => { logger.log(''); process.exit(EXIT_CODES.SUCCESS); } - const devTestAcctConfigName = await saveAccountToConfig({ - env, - accountName: account.accountName, - accountId: account.id, - }); + const devTestAcctConfigName = await saveAccountToConfig( + account.id, + account.accountName, + env + ); logger.success( i18n(`lib.developerTestAccount.create.success.configFileUpdated`, { accountName: devTestAcctConfigName, diff --git a/lib/prompts/personalAccessKeyPrompt.ts b/lib/prompts/personalAccessKeyPrompt.ts index dd15dc6ef..51c43436a 100644 --- a/lib/prompts/personalAccessKeyPrompt.ts +++ b/lib/prompts/personalAccessKeyPrompt.ts @@ -49,7 +49,7 @@ export async function personalAccessKeyPrompt({ account, }: { env: string; - account?: string; + account?: number; }): Promise { const websiteOrigin = getHubSpotWebsiteOrigin(env); let url = `${websiteOrigin}/l/personal-access-key`; diff --git a/lib/sandboxes.ts b/lib/sandboxes.ts index feb561dd8..b4a25698a 100644 --- a/lib/sandboxes.ts +++ b/lib/sandboxes.ts @@ -186,7 +186,7 @@ export function handleSandboxCreateError( env: Environment, name: string, accountId: number -) { +): never { if (isMissingScopeError(err)) { logger.error( i18n(`${i18nKey}.create.failure.scopes.message`, { diff --git a/lib/serverlessLogs.ts b/lib/serverlessLogs.ts index c716d7ece..476d4f4de 100644 --- a/lib/serverlessLogs.ts +++ b/lib/serverlessLogs.ts @@ -1,37 +1,41 @@ -// @ts-nocheck -const https = require('https'); -const SpinniesManager = require('./ui/SpinniesManager'); -const { handleExit, handleKeypress } = require('./process'); -const chalk = require('chalk'); -const { logger } = require('@hubspot/local-dev-lib/logger'); -const { outputLogs } = require('./ui/serverlessFunctionLogs'); -const { logError, ApiErrorContext } = require('./errorHandlers/index'); - -const { EXIT_CODES } = require('./enums/exitCodes'); -const { +import https from 'https'; +import chalk from 'chalk'; +import { logger } from '@hubspot/local-dev-lib/logger'; +import { isHubSpotHttpError, isMissingScopeError, -} = require('@hubspot/local-dev-lib/errors/index'); -const { +} from '@hubspot/local-dev-lib/errors/index'; +import { SCOPE_GROUPS, PERSONAL_ACCESS_KEY_AUTH_METHOD, -} = require('@hubspot/local-dev-lib/constants/auth'); -const { getAccountConfig } = require('@hubspot/local-dev-lib/config'); -const { fetchScopeData } = require('@hubspot/local-dev-lib/api/localDevAuth'); -const { i18n } = require('./lang'); +} from '@hubspot/local-dev-lib/constants/auth'; +import { getAccountConfig } from '@hubspot/local-dev-lib/config'; +import { fetchScopeData } from '@hubspot/local-dev-lib/api/localDevAuth'; + +import { outputLogs } from './ui/serverlessFunctionLogs'; +import { logError, ApiErrorContext } from './errorHandlers/index'; +import SpinniesManager from './ui/SpinniesManager'; +import { handleExit, handleKeypress } from './process'; +import { EXIT_CODES } from './enums/exitCodes'; +import { i18n } from './lang'; +import { HubSpotPromise } from '@hubspot/local-dev-lib/types/Http'; +import { + FunctionLog, + GetFunctionLogsResponse, +} from '@hubspot/local-dev-lib/types/Functions'; const TAIL_DELAY = 5000; -const base64EncodeString = valueToEncode => { +function base64EncodeString(valueToEncode: string): string { if (typeof valueToEncode !== 'string') { return valueToEncode; } const stringBuffer = Buffer.from(valueToEncode); return encodeURIComponent(stringBuffer.toString('base64')); -}; +} -const handleUserInput = () => { +function handleUserInput(): void { const onTerminate = async () => { SpinniesManager.remove('tailLogs'); SpinniesManager.remove('stopMessage'); @@ -44,10 +48,18 @@ const handleUserInput = () => { onTerminate(); } }); -}; +} -async function verifyAccessKeyAndUserAccess(accountId, scopeGroup) { +async function verifyAccessKeyAndUserAccess( + accountId: number, + scopeGroup: string +): Promise { const accountConfig = getAccountConfig(accountId); + + if (!accountConfig) { + return; + } + // TODO[JOE]: Update this i18n key const i18nKey = 'lib.serverless'; const { authType } = accountConfig; @@ -57,14 +69,15 @@ async function verifyAccessKeyAndUserAccess(accountId, scopeGroup) { let scopesData; try { - scopesData = await fetchScopeData(accountId, scopeGroup); + const resp = await fetchScopeData(accountId, scopeGroup); + scopesData = resp.data; } catch (e) { logger.debug( i18n(`${i18nKey}.verifyAccessKeyAndUserAccess.fetchScopeDataError`, { scopeGroup, - error: e, }) ); + logger.debug(e); return; } const { portalScopesInGroup, userScopesInGroup } = scopesData; @@ -87,14 +100,14 @@ async function verifyAccessKeyAndUserAccess(accountId, scopeGroup) { } } -const tailLogs = async ({ - accountId, - compact, - fetchLatest, - tailCall, - name, -}) => { - let initialAfter; +export async function tailLogs( + accountId: number, + name: string, + fetchLatest: () => HubSpotPromise, + tailCall: (after?: string) => HubSpotPromise, + compact = false +): Promise { + let initialAfter = ''; try { const { data: latestLog } = await fetchLatest(); @@ -113,9 +126,9 @@ const tailLogs = async ({ } } - const tail = async after => { - let latestLog; - let nextAfter; + async function tail(after?: string): Promise { + let latestLog: GetFunctionLogsResponse; + let nextAfter: string; try { const { data } = await tailCall(after); latestLog = data; @@ -141,7 +154,7 @@ const tailLogs = async ({ setTimeout(async () => { await tail(nextAfter); }, TAIL_DELAY); - }; + } SpinniesManager.init(); @@ -156,14 +169,14 @@ const tailLogs = async ({ handleUserInput(); await tail(initialAfter); -}; +} -const outputBuildLog = async buildLogUrl => { +export async function outputBuildLog(buildLogUrl: string): Promise { if (!buildLogUrl) { logger.debug( 'Unable to display build output. No build log URL was provided.' ); - return; + return ''; } return new Promise(resolve => { @@ -191,9 +204,4 @@ const outputBuildLog = async buildLogUrl => { resolve(''); } }); -}; - -module.exports = { - outputBuildLog, - tailLogs, -}; +} diff --git a/lib/ui/serverlessFunctionLogs.ts b/lib/ui/serverlessFunctionLogs.ts index 66108eab3..f75a56a16 100644 --- a/lib/ui/serverlessFunctionLogs.ts +++ b/lib/ui/serverlessFunctionLogs.ts @@ -2,11 +2,15 @@ import moment from 'moment'; import chalk from 'chalk'; import { logger, Styles } from '@hubspot/local-dev-lib/logger'; import { i18n } from '../lang'; +import { + FunctionLog, + GetFunctionLogsResponse, +} from '@hubspot/local-dev-lib/types/Functions'; const i18nKey = 'lib.ui.serverlessFunctionLogs'; const SEPARATOR = ' - '; -const LOG_STATUS_COLORS = { +const LOG_STATUS_COLORS: { [key: string]: (status: string) => string } = { SUCCESS: Styles.success, ERROR: Styles.error, UNHANDLED_ERROR: Styles.error, @@ -15,22 +19,6 @@ const LOG_STATUS_COLORS = { type LogStatus = keyof typeof LOG_STATUS_COLORS; -type Log = { - status: LogStatus; - createdAt: string; - executionTime: number; - log?: string; - error?: { - type: string; - message: string; - stackTrace?: string[]; - }; -}; - -type LogsResponse = { - results?: Log[]; -}; - type Options = { compact?: boolean; insertions?: { @@ -38,22 +26,22 @@ type Options = { }; }; -function errorHandler(log: Log, options: Options): string { +function errorHandler(log: FunctionLog, options: Options): string { return `${formatLogHeader(log, options)}${formatError(log, options)}`; } const logHandler: { - [key in LogStatus]: (log: Log, options: Options) => string; + [key in LogStatus]: (log: FunctionLog, options: Options) => string; } = { ERROR: errorHandler, UNHANDLED_ERROR: errorHandler, HANDLED_ERROR: errorHandler, - SUCCESS: (log: Log, options: Options): string => { + SUCCESS: (log: FunctionLog, options: Options): string => { return `${formatLogHeader(log, options)}${formatSuccess(log, options)}`; }, }; -function formatSuccess(log: Log, options: Options): string { +function formatSuccess(log: FunctionLog, options: Options): string { if (!log.log || options.compact) { return ''; } @@ -61,7 +49,7 @@ function formatSuccess(log: Log, options: Options): string { return `\n${log.log}`; } -function formatError(log: Log, options: Options): string { +function formatError(log: FunctionLog, options: Options): string { if (!log.error || options.compact) { return ''; } @@ -69,7 +57,7 @@ function formatError(log: Log, options: Options): string { return `${log.error.type}: ${log.error.message}\n${formatStackTrace(log)}`; } -function formatLogHeader(log: Log, options: Options): string { +function formatLogHeader(log: FunctionLog, options: Options): string { const color = LOG_STATUS_COLORS[log.status]; const headerInsertion = options && options.insertions && options.insertions.header; @@ -79,7 +67,7 @@ function formatLogHeader(log: Log, options: Options): string { }${SEPARATOR}${formatExecutionTime(log)}`; } -function formatStackTrace(log: Log): string { +function formatStackTrace(log: FunctionLog): string { const stackTrace = log.error?.stackTrace || []; return stackTrace .map(trace => { @@ -88,15 +76,15 @@ function formatStackTrace(log: Log): string { .join(''); } -function formatTimestamp(log: Log): string { +function formatTimestamp(log: FunctionLog): string { return `${chalk.whiteBright(moment(log.createdAt).toISOString())}`; } -function formatExecutionTime(log: Log): string { +function formatExecutionTime(log: FunctionLog): string { return `${chalk.whiteBright('Execution Time:')} ${log.executionTime}ms`; } -function processLog(log: Log, options: Options): string | void { +function processLog(log: FunctionLog, options: Options): string | void { try { return logHandler[log.status](log, options); } catch (e) { @@ -109,8 +97,8 @@ function processLog(log: Log, options: Options): string | void { } function isLogsResponse( - logsResp: LogsResponse | Log -): logsResp is LogsResponse { + logsResp: GetFunctionLogsResponse | FunctionLog +): logsResp is GetFunctionLogsResponse { return ( logsResp && 'results' in logsResp && @@ -120,7 +108,7 @@ function isLogsResponse( } function processLogs( - logsResp: LogsResponse | Log, + logsResp: GetFunctionLogsResponse | FunctionLog, options: Options ): string | void { const isLogsResp = isLogsResponse(logsResp); @@ -134,13 +122,12 @@ function processLogs( }) .join('\n'); } - return processLog(logsResp as Log, options); + return processLog(logsResp, options); } -function outputLogs(logsResp: LogsResponse | Log, options: Options): void { +export function outputLogs( + logsResp: GetFunctionLogsResponse | FunctionLog, + options: Options +): void { logger.log(processLogs(logsResp, options)); } - -module.exports = { - outputLogs, -}; diff --git a/package.json b/package.json index d27048d5a..ab7d82683 100644 --- a/package.json +++ b/package.json @@ -5,7 +5,7 @@ "license": "Apache-2.0", "repository": "https://github.com/HubSpot/hubspot-cli", "dependencies": { - "@hubspot/local-dev-lib": "3.1.1", + "@hubspot/local-dev-lib": "3.1.2", "@hubspot/serverless-dev-runtime": "7.0.1", "@hubspot/theme-preview-dev-server": "0.0.10", "@hubspot/ui-extensions-dev-server": "0.8.40", diff --git a/yarn.lock b/yarn.lock index 065849c51..564d14de1 100644 --- a/yarn.lock +++ b/yarn.lock @@ -1446,10 +1446,10 @@ semver "^6.3.0" unixify "^1.0.0" -"@hubspot/local-dev-lib@3.1.1": - version "3.1.1" - resolved "https://registry.yarnpkg.com/@hubspot/local-dev-lib/-/local-dev-lib-3.1.1.tgz#b67646d7a7b399cebc5d74f62c389c13554e950c" - integrity sha512-/SIKBuC3ORkKMXityS6tCz2sNU7OY96slJtLM0CxRlKDCiwEGb08Lf0Ruf1PMBJnAu8iHbw/6SprefFEHEQOpw== +"@hubspot/local-dev-lib@3.1.2": + version "3.1.2" + resolved "https://registry.yarnpkg.com/@hubspot/local-dev-lib/-/local-dev-lib-3.1.2.tgz#9af9f8ca5cf9aba912cb9c5f9acf51e760604465" + integrity sha512-vn9pyKs/2NW86GWhTlp9VyDcpKUUUEWQgHwQpq57Luz9IWwCFAmFaTzSggmttTnqJRAmqwMIN8DHUKeMEJqquA== dependencies: address "^2.0.1" axios "^1.3.5" From 40afea24034986bb32eaf23c63450b2974525ffe Mon Sep 17 00:00:00 2001 From: Jessica Sines Date: Thu, 16 Jan 2025 11:40:41 -0500 Subject: [PATCH 4/6] Adjust `hs upload --clean` warning prompt language (#1344) --- lang/en.lyaml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/lang/en.lyaml b/lang/en.lyaml index db54c51ef..8ff856c77 100644 --- a/lang/en.lyaml +++ b/lang/en.lyaml @@ -987,7 +987,7 @@ en: uploading: "Uploading files from \"{{ src }}\" to \"{{ dest }}\" in the Design Manager of account {{ accountId }}" notUploaded: "There was an error processing \"{{ src }}\". The file has not been uploaded." cleaning: "Removing \"{{ filePath }}\" from account {{ accountId }} and uploading local..." - confirmCleanUpload: "You are about to remove any remote files in \"{{ filePath }}\" on HubSpot account {{ accountId }} that don't exist locally. Are you sure you want to do this?" + confirmCleanUpload: "You are about to delete the directory \"{{ filePath }}\" and its contents on HubSpot account {{ accountId }} before uploading. This will also clear the global content associated with any global partial templates and modules. Are you sure you want to do this?" watch: describe: "Watch a directory on your computer for changes and upload the changed files to the HubSpot CMS." errors: From 0b2d449c4a20487d9944b61c7488765ac7b77260 Mon Sep 17 00:00:00 2001 From: Branden Rodgers Date: Fri, 17 Jan 2025 16:00:46 -0500 Subject: [PATCH 5/6] chore: Remove CLI getAccountId util (#1331) --- commands/account/remove.ts | 12 +++------ commands/account/use.ts | 10 +++---- commands/auth.ts | 4 +-- .../project/__tests__/installDeps.test.ts | 5 +--- commands/project/installDeps.ts | 6 ++--- commands/sandbox/delete.ts | 18 +++++-------- lib/__tests__/commonOpts.test.ts | 4 --- lib/__tests__/validation.test.ts | 6 +++-- lib/commonOpts.ts | 26 +++++-------------- lib/validation.ts | 24 +++++++++-------- 10 files changed, 42 insertions(+), 73 deletions(-) diff --git a/commands/account/remove.ts b/commands/account/remove.ts index b0a11533f..a82ef6f03 100644 --- a/commands/account/remove.ts +++ b/commands/account/remove.ts @@ -6,7 +6,7 @@ const { getConfigPath, deleteAccount, getConfigDefaultAccount, - getAccountId: getAccountIdFromConfig, + getAccountId, updateDefaultAccount, } = require('@hubspot/local-dev-lib/config'); @@ -23,7 +23,7 @@ exports.handler = async options => { const { account } = options; let accountToRemove = account; - if (accountToRemove && !getAccountIdFromConfig(accountToRemove)) { + if (accountToRemove && !getAccountId(accountToRemove)) { logger.error( i18n(`${i18nKey}.errors.accountNotFound`, { specifiedAccount: accountToRemove, @@ -32,17 +32,13 @@ exports.handler = async options => { ); } - if (!accountToRemove || !getAccountIdFromConfig(accountToRemove)) { + if (!accountToRemove || !getAccountId(accountToRemove)) { accountToRemove = await selectAccountFromConfig( i18n(`${i18nKey}.prompts.selectAccountToRemove`) ); } - trackCommandUsage( - 'accounts-remove', - null, - getAccountIdFromConfig(accountToRemove) - ); + trackCommandUsage('accounts-remove', null, getAccountId(accountToRemove)); const currentDefaultAccount = getConfigDefaultAccount(); diff --git a/commands/account/use.ts b/commands/account/use.ts index df2ec0594..e4cb208ab 100644 --- a/commands/account/use.ts +++ b/commands/account/use.ts @@ -3,7 +3,7 @@ const { logger } = require('@hubspot/local-dev-lib/logger'); const { getConfigPath, updateDefaultAccount, - getAccountId: getAccountIdFromConfig, + getAccountId, } = require('@hubspot/local-dev-lib/config'); const { trackCommandUsage } = require('../../lib/usageTracking'); @@ -20,7 +20,7 @@ exports.handler = async options => { if (!newDefaultAccount) { newDefaultAccount = await selectAccountFromConfig(); - } else if (!getAccountIdFromConfig(newDefaultAccount)) { + } else if (!getAccountId(newDefaultAccount)) { logger.error( i18n(`${i18nKey}.errors.accountNotFound`, { specifiedAccount: newDefaultAccount, @@ -30,11 +30,7 @@ exports.handler = async options => { newDefaultAccount = await selectAccountFromConfig(); } - trackCommandUsage( - 'accounts-use', - null, - getAccountIdFromConfig(newDefaultAccount) - ); + trackCommandUsage('accounts-use', null, getAccountId(newDefaultAccount)); updateDefaultAccount(newDefaultAccount); diff --git a/commands/auth.ts b/commands/auth.ts index b0d26e1d5..89aafc2d0 100644 --- a/commands/auth.ts +++ b/commands/auth.ts @@ -22,6 +22,7 @@ const { getConfigPath, loadConfig, getConfigDefaultAccount, + getAccountId, } = require('@hubspot/local-dev-lib/config'); const { commaSeparatedValues, @@ -39,7 +40,6 @@ const { const { addConfigOptions, setLogLevel, - getAccountId, addTestingOptions, addGlobalOptions, } = require('../lib/commonOpts'); @@ -197,7 +197,7 @@ exports.handler = async options => { 'accountsListCommand', ]); - const accountId = getAccountId({ account: accountName }); + const accountId = getAccountId(accountName); await trackAuthAction('auth', authType, TRACKING_STATUS.COMPLETE, accountId); process.exit(EXIT_CODES.SUCCESS); diff --git a/commands/project/__tests__/installDeps.test.ts b/commands/project/__tests__/installDeps.test.ts index d4c7bc901..3d0135e9a 100644 --- a/commands/project/__tests__/installDeps.test.ts +++ b/commands/project/__tests__/installDeps.test.ts @@ -5,7 +5,6 @@ const { logger } = require('@hubspot/local-dev-lib/logger'); const { getProjectConfig } = require('../../../lib/projects'); const { EXIT_CODES } = require('../../../lib/enums/exitCodes'); const { trackCommandUsage } = require('../../../lib/usageTracking'); -const { getAccountId } = require('../../../lib/commonOpts'); const { installPackages, getProjectPackageJsonLocations, @@ -56,10 +55,8 @@ describe('commands/project/installDeps', () => { it('should track the command usage', async () => { const accountId = 999999; - getAccountId.mockReturnValue(accountId); - await installDepsCommand.handler({}); + await installDepsCommand.handler({ derivedAccountId: accountId }); - expect(getAccountId).toHaveBeenCalledTimes(1); expect(trackCommandUsage).toHaveBeenCalledTimes(1); expect(trackCommandUsage).toHaveBeenCalledWith( 'project-install-deps', diff --git a/commands/project/installDeps.ts b/commands/project/installDeps.ts index c85b2102c..987d80fce 100644 --- a/commands/project/installDeps.ts +++ b/commands/project/installDeps.ts @@ -10,7 +10,6 @@ const { promptUser } = require('../../lib/prompts/promptUtils'); const path = require('path'); const { i18n } = require('../../lib/lang'); const { trackCommandUsage } = require('../../lib/usageTracking'); -const { getAccountId } = require('../../lib/commonOpts'); const { uiBetaTag } = require('../../lib/ui'); const i18nKey = `commands.project.subcommands.installDeps`; @@ -19,10 +18,9 @@ exports.command = 'install-deps [packages..]'; exports.describe = uiBetaTag(i18n(`${i18nKey}.help.describe`), false); exports.handler = async options => { - const { packages } = options || {}; + const { derivedAccountId, packages } = options || {}; try { - const accountId = getAccountId(options); - trackCommandUsage('project-install-deps', null, accountId); + trackCommandUsage('project-install-deps', null, derivedAccountId); const projectConfig = await getProjectConfig(); if (!projectConfig || !projectConfig.projectDir) { diff --git a/commands/sandbox/delete.ts b/commands/sandbox/delete.ts index 290acd49d..5be8826c2 100644 --- a/commands/sandbox/delete.ts +++ b/commands/sandbox/delete.ts @@ -3,7 +3,6 @@ const { addAccountOptions, addConfigOptions, addUseEnvironmentOptions, - getAccountId, addTestingOptions, } = require('../../lib/commonOpts'); const { logger } = require('@hubspot/local-dev-lib/logger'); @@ -17,7 +16,7 @@ const { getEnv, removeSandboxAccountFromConfig, updateDefaultAccount, - getConfigDefaultAccount, + getAccountId, getConfigAccounts, } = require('@hubspot/local-dev-lib/config'); const { @@ -61,11 +60,10 @@ exports.handler = async options => { } } - const sandboxAccountId = getAccountId({ - account: providedAccountId || accountPrompt.account, - }); - const isDefaultAccount = - sandboxAccountId === getAccountId(getConfigDefaultAccount()); + const sandboxAccountId = getAccountId( + providedAccountId || accountPrompt.account + ); + const isDefaultAccount = sandboxAccountId === getAccountId(); const baseUrl = getHubSpotWebsiteOrigin( getValidEnv(getEnv(sandboxAccountId)) @@ -79,9 +77,7 @@ exports.handler = async options => { parentAccountId = portal.parentAccountId; } else if (!force) { const parentAccountPrompt = await deleteSandboxPrompt(true); - parentAccountId = getAccountId({ - account: parentAccountPrompt.account, - }); + parentAccountId = getAccountId(parentAccountPrompt.account); } else { logger.error(i18n(`${i18nKey}.failure.noParentAccount`)); process.exit(EXIT_CODES.ERROR); @@ -94,7 +90,7 @@ exports.handler = async options => { getEnv(sandboxAccountId) === 'qa' ? '--qa' : '' } --account=${parentAccountId}`; - if (parentAccountId && !getAccountId({ account: parentAccountId })) { + if (parentAccountId && !getAccountId(parentAccountId)) { logger.log(''); logger.error( i18n(`${i18nKey}.failure.noParentPortalAvailable`, { diff --git a/lib/__tests__/commonOpts.test.ts b/lib/__tests__/commonOpts.test.ts index 1354c0ec5..f2292d1f7 100644 --- a/lib/__tests__/commonOpts.test.ts +++ b/lib/__tests__/commonOpts.test.ts @@ -5,7 +5,6 @@ const { } = require('@hubspot/local-dev-lib/constants/files'); const { getAndLoadConfigIfNeeded, - getAccountId, getAccountConfig, loadConfigFromEnvironment, } = require('@hubspot/local-dev-lib/config'); @@ -40,7 +39,6 @@ describe('lib/commonOpts', () => { afterEach(() => { getAndLoadConfigIfNeeded.mockReset(); - getAccountId.mockReset(); getAccountConfig.mockReset(); loadConfigFromEnvironment.mockReset(); }); @@ -68,7 +66,6 @@ describe('lib/commonOpts', () => { getAndLoadConfigIfNeeded.mockReturnValue( configWithDefaultCmsPublishMode ); - getAccountId.mockReturnValue(accounts.DEV); getAccountConfig.mockReturnValue(devAccountConfig); loadConfigFromEnvironment.mockReturnValue(undefined); expect(getCmsPublishMode({ account: accounts.DEV })).toBe( @@ -81,7 +78,6 @@ describe('lib/commonOpts', () => { getAndLoadConfigIfNeeded.mockReturnValue( configWithDefaultCmsPublishMode ); - getAccountId.mockReturnValue(accounts.PROD); getAccountConfig.mockReturnValue(prodAccountConfig); loadConfigFromEnvironment.mockReturnValue(undefined); expect(getCmsPublishMode({ account: accounts.PROD })).toBe( diff --git a/lib/__tests__/validation.test.ts b/lib/__tests__/validation.test.ts index ba44922a6..25e302e52 100644 --- a/lib/__tests__/validation.test.ts +++ b/lib/__tests__/validation.test.ts @@ -1,10 +1,12 @@ // @ts-nocheck -const { getAccountConfig } = require('@hubspot/local-dev-lib/config'); +const { + getAccountId, + getAccountConfig, +} = require('@hubspot/local-dev-lib/config'); const { getOauthManager } = require('@hubspot/local-dev-lib/oauth'); const { accessTokenForPersonalAccessKey, } = require('@hubspot/local-dev-lib/personalAccessKey'); -const { getAccountId } = require('../commonOpts'); const { validateAccount } = require('../validation'); jest.mock('@hubspot/local-dev-lib/config'); diff --git a/lib/commonOpts.ts b/lib/commonOpts.ts index c2d37d152..5a6794924 100644 --- a/lib/commonOpts.ts +++ b/lib/commonOpts.ts @@ -8,7 +8,6 @@ import { } from '@hubspot/local-dev-lib/constants/files'; import { CmsPublishMode } from '@hubspot/local-dev-lib/types/Files'; import { - getAccountId as getAccountIdFromConfig, getAccountConfig, getAndLoadConfigIfNeeded, } from '@hubspot/local-dev-lib/config'; @@ -102,23 +101,11 @@ export function getCommandName(argv: Arguments<{ _?: string[] }>): string { return (argv && argv._ && argv._[0]) || ''; } -/** - * Obtains accountId using supplied --account flag or from environment variables - */ -export function getAccountId( - options: Arguments<{ account?: number | string }> -): number | null { - const { account } = options || {}; - - if (options?.useEnv && process.env.HUBSPOT_ACCOUNT_ID) { - return parseInt(process.env.HUBSPOT_ACCOUNT_ID, 10); - } - - return getAccountIdFromConfig(account); -} - export function getCmsPublishMode( - options: Arguments<{ cmsPublishMode?: CmsPublishMode }> + options: Arguments<{ + cmsPublishMode?: CmsPublishMode; + derivedAccountId?: number; + }> ): CmsPublishMode { // 1. --cmsPublishMode const { cmsPublishMode } = options; @@ -126,9 +113,8 @@ export function getCmsPublishMode( return cmsPublishMode.toLowerCase() as CmsPublishMode; } // 2. config[account].defaultCmsPublishMode - const accountId = getAccountId(options); - if (accountId) { - const accountConfig = getAccountConfig(accountId); + if (options.derivedAccountId) { + const accountConfig = getAccountConfig(options.derivedAccountId); if (accountConfig && accountConfig.defaultCmsPublishMode) { return accountConfig.defaultCmsPublishMode; } diff --git a/lib/validation.ts b/lib/validation.ts index 859ebde44..6269f8c75 100644 --- a/lib/validation.ts +++ b/lib/validation.ts @@ -13,6 +13,7 @@ import { commaSeparatedValues } from '@hubspot/local-dev-lib/text'; import { getConfigPath, getAccountConfig, + getAccountId, loadConfigFromEnvironment, } from '@hubspot/local-dev-lib/config'; import { getOauthManager } from '@hubspot/local-dev-lib/oauth'; @@ -22,23 +23,24 @@ import { getCwd, getExt, } from '@hubspot/local-dev-lib/path'; -import { getAccountId, getCmsPublishMode } from './commonOpts'; +import { getCmsPublishMode } from './commonOpts'; import { logError } from './errorHandlers/index'; export async function validateAccount( - options: Arguments<{ account?: string; accountId?: string }> + options: Arguments<{ + account?: string; + accountId?: string; + derivedAccountId?: number; + providedAccountId?: string; + }> ): Promise { - const accountId = getAccountId(options); - const { accountId: accountIdOption, account: accountOption } = options; + const { derivedAccountId, providedAccountId } = options; + const accountId = getAccountId(derivedAccountId); if (!accountId) { - if (accountOption) { + if (providedAccountId) { logger.error( - `The account "${accountOption}" could not be found in the config` - ); - } else if (accountIdOption) { - logger.error( - `The account "${accountIdOption}" could not be found in the config` + `The account "${providedAccountId}" could not be found in the config` ); } else { logger.error( @@ -48,7 +50,7 @@ export async function validateAccount( return false; } - if (accountOption && loadConfigFromEnvironment()) { + if (providedAccountId && loadConfigFromEnvironment()) { throw new Error( 'Cannot specify an account when environment variables are supplied. Please unset the environment variables or do not use the "--account" flag.' ); From 565ad321592a818e1698f54ea676e767bba0c698 Mon Sep 17 00:00:00 2001 From: Camden Phalen Date: Fri, 17 Jan 2025 16:42:16 -0500 Subject: [PATCH 6/6] Convert localDev and LocalDevManager to TS (#1339) --- commands/project/upload.ts | 8 +- commands/project/watch.ts | 8 +- lang/en.lyaml | 3 + lib/LocalDevManager.ts | 278 ++++++++++++------- lib/localDev.ts | 274 ++++++++++-------- lib/projects/buildAndDeploy.ts | 8 +- lib/projects/structure.ts | 27 ++ lib/projects/upload.ts | 19 +- lib/prompts/installPublicAppPrompt.ts | 2 +- lib/prompts/projectDevTargetAccountPrompt.ts | 4 +- types/Projects.ts | 11 +- 11 files changed, 401 insertions(+), 241 deletions(-) diff --git a/commands/project/upload.ts b/commands/project/upload.ts index 343e93d52..0e6432d09 100644 --- a/commands/project/upload.ts +++ b/commands/project/upload.ts @@ -48,7 +48,7 @@ exports.handler = async options => { }); try { - const result = await handleProjectUpload( + const { result, uploadError } = await handleProjectUpload( derivedAccountId, projectConfig, projectDir, @@ -56,9 +56,9 @@ exports.handler = async options => { message ); - if (result.uploadError) { + if (uploadError) { if ( - isSpecifiedError(result.uploadError, { + isSpecifiedError(uploadError, { subCategory: PROJECT_ERROR_TYPES.PROJECT_LOCKED, }) ) { @@ -67,7 +67,7 @@ exports.handler = async options => { logger.log(); } else { logError( - result.uploadError, + uploadError, new ApiErrorContext({ accountId: derivedAccountId, request: 'project upload', diff --git a/commands/project/watch.ts b/commands/project/watch.ts index ceac52615..db969c6fd 100644 --- a/commands/project/watch.ts +++ b/commands/project/watch.ts @@ -113,16 +113,16 @@ exports.handler = async options => { // Upload all files if no build exists for this project yet if (initialUpload || hasNoBuilds) { - const result = await handleProjectUpload( + const { uploadError } = await handleProjectUpload( derivedAccountId, projectConfig, projectDir, startWatching ); - if (result.uploadError) { + if (uploadError) { if ( - isSpecifiedError(result.uploadError, { + isSpecifiedError(uploadError, { subCategory: PROJECT_ERROR_TYPES.PROJECT_LOCKED, }) ) { @@ -131,7 +131,7 @@ exports.handler = async options => { logger.log(); } else { logError( - result.uploadError, + uploadError, new ApiErrorContext({ accountId: derivedAccountId, request: 'project upload', diff --git a/lang/en.lyaml b/lang/en.lyaml index 8ff856c77..fd4f17732 100644 --- a/lang/en.lyaml +++ b/lang/en.lyaml @@ -1075,6 +1075,7 @@ en: fileChangeError: "Failed to notify local dev server of file change: {{ message }}" localDev: confirmDefaultAccountIsTarget: + configError: "An error occurred while reading the default account from your config. Run {{ authCommand }} to re-auth this account" declineDefaultAccountExplanation: "To develop on a different account, run {{ useCommand }} to change your default account, then re-run {{ devCommand }}." checkIfDefaultAccountIsSupported: publicApp: "This project contains a public app. Local development of public apps is only supported on developer accounts and developer test accounts. Change your default account using {{ useCommand }}, or link a new account with {{ authCommand }}." @@ -1095,6 +1096,7 @@ en: createInitialBuildForNewProject: initialUploadMessage: "HubSpot Local Dev Server Startup" projectLockedError: "Your project is locked. This may mean that another user is running the {{#bold}}`hs project watch`{{/bold}} command for this project. If this is you, unlock the project in Projects UI." + genericError: "An error occurred while creating the initial build for this project. Run {{ uploadCommand }} to try again." checkIfParentAccountIsAuthed: notAuthedError: "To develop this project locally, run {{ authCommand }} to authenticate the App Developer Account {{ accountId }} associated with {{ accountIdentifier }}." projects: @@ -1421,6 +1423,7 @@ en: invalidUser: "Couldn't create {{#bold}}{{ accountName }}{{/bold}} because your account has been removed from {{#bold}}{{ parentAccountName }}{{/bold}} or your permission set doesn't allow you to create the sandbox. To update your permissions, contact a super admin in {{#bold}}{{ parentAccountName }}{{/bold}}." 403Gating: "Couldn't create {{#bold}}{{ accountName }}{{/bold}} because {{#bold}}{{ parentAccountName }}{{/bold}} does not have access to development sandboxes. To opt in to the CRM Development Beta and use development sandboxes, visit https://app.hubspot.com/l/product-updates/in-beta?update=13899236." usageLimitsFetch: "Unable to fetch sandbox usage limits. Please try again." + generic: "An error occurred while creating a new sandbox. Please try again." limit: developer: one: "{{#bold}}{{ accountName }}{{/bold}} reached the limit of {{ limit }} development sandbox. diff --git a/lib/LocalDevManager.ts b/lib/LocalDevManager.ts index 18af42151..6de661f95 100644 --- a/lib/LocalDevManager.ts +++ b/lib/LocalDevManager.ts @@ -1,40 +1,47 @@ -// @ts-nocheck -const path = require('path'); -const chokidar = require('chokidar'); -const chalk = require('chalk'); -const { i18n } = require('./lang'); -const { handleKeypress } = require('./process'); -const { logger } = require('@hubspot/local-dev-lib/logger'); -const { - fetchAppInstallationData, -} = require('@hubspot/local-dev-lib/api/localDevAuth'); -const { +import path from 'path'; +import chokidar, { FSWatcher } from 'chokidar'; +import chalk from 'chalk'; +import { logger } from '@hubspot/local-dev-lib/logger'; +import { fetchAppInstallationData } from '@hubspot/local-dev-lib/api/localDevAuth'; +import { fetchPublicAppsForPortal, fetchPublicAppProductionInstallCounts, -} = require('@hubspot/local-dev-lib/api/appsDev'); -const { +} from '@hubspot/local-dev-lib/api/appsDev'; +import { getAccountId, getConfigDefaultAccount, -} = require('@hubspot/local-dev-lib/config'); -const { PROJECT_CONFIG_FILE } = require('./constants'); -const SpinniesManager = require('./ui/SpinniesManager'); -const DevServerManager = require('./DevServerManager'); -const { EXIT_CODES } = require('./enums/exitCodes'); -const { getProjectDetailUrl } = require('./projects/urls'); -const { getAccountHomeUrl } = require('./localDev'); -const { CONFIG_FILES, getAppCardConfigs } = require('./projects/structure'); -const { ComponentTypes } = require('../types/Projects'); -const { +} from '@hubspot/local-dev-lib/config'; +import { Build } from '@hubspot/local-dev-lib/types/Build'; +import { PublicApp } from '@hubspot/local-dev-lib/types/Apps'; +import { Environment } from '@hubspot/local-dev-lib/types/Config'; + +import { PROJECT_CONFIG_FILE } from './constants'; +import SpinniesManager from './ui/SpinniesManager'; +import DevServerManager from './DevServerManager'; +import { EXIT_CODES } from './enums/exitCodes'; +import { getProjectDetailUrl } from './projects/urls'; +import { getAccountHomeUrl } from './localDev'; +import { + componentIsApp, + componentIsPublicApp, + CONFIG_FILES, + getAppCardConfigs, + getComponentUid, +} from './projects/structure'; +import { Component, ComponentTypes, ProjectConfig } from '../types/Projects'; +import { UI_COLORS, uiCommandReference, uiAccountDescription, uiBetaTag, uiLink, uiLine, -} = require('./ui'); -const { logError } = require('./errorHandlers/index'); -const { installPublicAppPrompt } = require('./prompts/installPublicAppPrompt'); -const { confirmPrompt } = require('./prompts/promptUtils'); +} from './ui'; +import { logError } from './errorHandlers/index'; +import { installPublicAppPrompt } from './prompts/installPublicAppPrompt'; +import { confirmPrompt } from './prompts/promptUtils'; +import { i18n } from './lang'; +import { handleKeypress } from './process'; const WATCH_EVENTS = { add: 'add', @@ -45,11 +52,42 @@ const WATCH_EVENTS = { const i18nKey = 'lib.LocalDevManager'; +type LocalDevManagerConstructorOptions = { + targetAccountId: number; + parentAccountId: number; + projectConfig: ProjectConfig; + projectDir: string; + projectId: number; + debug?: boolean; + deployedBuild: Build; + isGithubLinked: boolean; + runnableComponents: Component[]; + env: Environment; +}; + class LocalDevManager { - constructor(options) { + targetAccountId: number; + targetProjectAccountId: number; + projectConfig: ProjectConfig; + projectDir: string; + projectId: number; + debug: boolean; + deployedBuild: Build; + isGithubLinked: boolean; + watcher: FSWatcher | null; + uploadWarnings: { [key: string]: boolean }; + runnableComponents: Component[]; + activeApp: Component | null; + activePublicAppData: PublicApp | null; + env: Environment; + publicAppActiveInstalls: number | null; + projectSourceDir: string; + mostRecentUploadWarning: string | null; + + constructor(options: LocalDevManagerConstructorOptions) { this.targetAccountId = options.targetAccountId; // The account that the project exists in. This is not always the targetAccountId - this.targetProjectAccountId = options.parentAccountId || options.accountId; + this.targetProjectAccountId = options.parentAccountId; this.projectConfig = options.projectConfig; this.projectDir = options.projectDir; @@ -64,6 +102,7 @@ class LocalDevManager { this.activePublicAppData = null; this.env = options.env; this.publicAppActiveInstalls = null; + this.mostRecentUploadWarning = null; this.projectSourceDir = path.join( this.projectDir, @@ -76,7 +115,7 @@ class LocalDevManager { } } - async setActiveApp(appUid) { + async setActiveApp(appUid?: string): Promise { if (!appUid) { logger.error( i18n(`${i18nKey}.missingUid`, { @@ -85,11 +124,12 @@ class LocalDevManager { ); process.exit(EXIT_CODES.ERROR); } - this.activeApp = this.runnableComponents.find(component => { - return component.config.uid === appUid; - }); + this.activeApp = + this.runnableComponents.find(component => { + return getComponentUid(component) === appUid; + }) || null; - if (this.activeApp.type === ComponentTypes.PublicApp) { + if (componentIsPublicApp(this.activeApp)) { try { await this.setActivePublicAppData(); await this.checkActivePublicAppInstalls(); @@ -100,7 +140,7 @@ class LocalDevManager { } } - async setActivePublicAppData() { + async setActivePublicAppData(): Promise { if (!this.activeApp) { return; } @@ -110,10 +150,13 @@ class LocalDevManager { } = await fetchPublicAppsForPortal(this.targetProjectAccountId); const activePublicAppData = portalPublicApps.find( - ({ sourceId }) => sourceId === this.activeApp.config.uid + ({ sourceId }) => sourceId === getComponentUid(this.activeApp) ); - // TODO: Update to account for new API with { data } + if (!activePublicAppData) { + return; + } + const { data: { uniquePortalInstallCount }, } = await fetchPublicAppProductionInstallCounts( @@ -125,7 +168,7 @@ class LocalDevManager { this.publicAppActiveInstalls = uniquePortalInstallCount; } - async checkActivePublicAppInstalls() { + async checkActivePublicAppInstalls(): Promise { if ( !this.activePublicAppData || !this.publicAppActiveInstalls || @@ -156,7 +199,7 @@ class LocalDevManager { } } - async start() { + async start(): Promise { SpinniesManager.stopAll(); SpinniesManager.init(); @@ -205,11 +248,11 @@ class LocalDevManager { getProjectDetailUrl( this.projectConfig.name, this.targetProjectAccountId - ) + ) || '' ) ); - if (this.activeApp.type === ComponentTypes.PublicApp) { + if (this.activeApp?.type === ComponentTypes.PublicApp) { logger.log( uiLink( i18n(`${i18nKey}.viewTestAccountLink`), @@ -237,7 +280,7 @@ class LocalDevManager { this.compareLocalProjectToDeployed(); } - async stop(showProgress = true) { + async stop(showProgress = true): Promise { if (showProgress) { SpinniesManager.add('cleanupMessage', { text: i18n(`${i18nKey}.exitingStart`), @@ -264,22 +307,20 @@ class LocalDevManager { process.exit(EXIT_CODES.SUCCESS); } - async getActiveAppInstallationData() { - const { data } = await fetchAppInstallationData( + async checkPublicAppInstallation(): Promise { + if (!componentIsPublicApp(this.activeApp) || !this.activePublicAppData) { + return; + } + + const { + data: { isInstalledWithScopeGroups, previouslyAuthorizedScopeGroups }, + } = await fetchAppInstallationData( this.targetAccountId, this.projectId, this.activeApp.config.uid, this.activeApp.config.auth.requiredScopes, this.activeApp.config.auth.optionalScopes ); - - return data; - } - - async checkPublicAppInstallation() { - const { isInstalledWithScopeGroups, previouslyAuthorizedScopeGroups } = - await this.getActiveAppInstallationData(); - const isReinstall = previouslyAuthorizedScopeGroups.length > 0; if (!isInstalledWithScopeGroups) { @@ -294,7 +335,7 @@ class LocalDevManager { } } - updateKeypressListeners() { + updateKeypressListeners(): void { handleKeypress(async key => { if ((key.ctrl && key.name === 'c') || key.name === 'q') { this.stop(); @@ -302,8 +343,8 @@ class LocalDevManager { }); } - getUploadCommand() { - const currentDefaultAccount = getConfigDefaultAccount(); + getUploadCommand(): string { + const currentDefaultAccount = getConfigDefaultAccount() || undefined; return this.targetProjectAccountId !== getAccountId(currentDefaultAccount) ? uiCommandReference( @@ -312,11 +353,15 @@ class LocalDevManager { : uiCommandReference('hs project upload'); } - logUploadWarning(reason) { - let warning = reason; - if (!reason) { + logUploadWarning(reason?: string): void { + let warning: string; + + if (reason) { + warning = reason; + } else { warning = - this.activeApp.type === ComponentTypes.PublicApp && + componentIsPublicApp(this.activeApp) && + this.publicAppActiveInstalls && this.publicAppActiveInstalls > 0 ? i18n(`${i18nKey}.uploadWarning.defaultPublicAppWarning`, { installCount: this.publicAppActiveInstalls, @@ -356,10 +401,29 @@ class LocalDevManager { } } - monitorConsoleOutput() { + monitorConsoleOutput(): void { const originalStdoutWrite = process.stdout.write.bind(process.stdout); - process.stdout.write = function (chunk, encoding, callback) { + type StdoutCallback = (err?: Error) => void; + + // Need to provide both overloads for process.stdout.write to satisfy TS + function customStdoutWrite( + this: LocalDevManager, + buffer: Uint8Array | string, + cb?: StdoutCallback + ): boolean; + function customStdoutWrite( + this: LocalDevManager, + str: Uint8Array | string, + encoding?: BufferEncoding, + cb?: StdoutCallback + ): boolean; + function customStdoutWrite( + this: LocalDevManager, + chunk: Uint8Array | string, + encoding?: BufferEncoding | StdoutCallback, + callback?: StdoutCallback + ) { // Reset the most recently logged warning if ( this.mostRecentUploadWarning && @@ -368,42 +432,51 @@ class LocalDevManager { delete this.uploadWarnings[this.mostRecentUploadWarning]; } + if (typeof encoding === 'function') { + return originalStdoutWrite(chunk, callback); + } return originalStdoutWrite(chunk, encoding, callback); - }.bind(this); + } + + customStdoutWrite.bind(this); + + process.stdout.write = customStdoutWrite; } - compareLocalProjectToDeployed() { + compareLocalProjectToDeployed(): void { const deployedComponentNames = this.deployedBuild.subbuildStatuses.map( subbuildStatus => subbuildStatus.buildName ); - const missingComponents = []; - - this.runnableComponents.forEach(({ type, config, path }) => { - if (Object.values(ComponentTypes).includes(type)) { - const cardConfigs = getAppCardConfigs(config, path); + const missingComponents: string[] = []; - if (!deployedComponentNames.includes(config.name)) { - missingComponents.push( - `${i18n(`${i18nKey}.uploadWarning.appLabel`)} ${config.name}` - ); - } + this.runnableComponents + .filter(componentIsApp) + .forEach(({ type, config, path }) => { + if (Object.values(ComponentTypes).includes(type)) { + const cardConfigs = getAppCardConfigs(config, path); - cardConfigs.forEach(cardConfig => { - if ( - cardConfig.data && - cardConfig.data.title && - !deployedComponentNames.includes(cardConfig.data.title) - ) { + if (!deployedComponentNames.includes(config.name)) { missingComponents.push( - `${i18n(`${i18nKey}.uploadWarning.uiExtensionLabel`)} ${ - cardConfig.data.title - }` + `${i18n(`${i18nKey}.uploadWarning.appLabel`)} ${config.name}` ); } - }); - } - }); + + cardConfigs.forEach(cardConfig => { + if ( + cardConfig.data && + cardConfig.data.title && + !deployedComponentNames.includes(cardConfig.data.title) + ) { + missingComponents.push( + `${i18n(`${i18nKey}.uploadWarning.uiExtensionLabel`)} ${ + cardConfig.data.title + }` + ); + } + }); + } + }); if (missingComponents.length) { this.logUploadWarning( @@ -414,7 +487,7 @@ class LocalDevManager { } } - startWatching() { + startWatching(): void { this.watcher = chokidar.watch(this.projectDir, { ignoreInitial: true, }); @@ -446,11 +519,15 @@ class LocalDevManager { }); } - async stopWatching() { - await this.watcher.close(); + async stopWatching(): Promise { + await this.watcher?.close(); } - handleWatchEvent(filePath, event, configPaths) { + handleWatchEvent( + filePath: string, + event: string, + configPaths: string[] + ): void { if (configPaths.includes(filePath)) { this.logUploadWarning(); } else { @@ -458,7 +535,7 @@ class LocalDevManager { } } - async devServerSetup() { + async devServerSetup(): Promise { try { await DevServerManager.setup({ components: this.runnableComponents, @@ -472,13 +549,15 @@ class LocalDevManager { logger.error(e); } logger.error( - i18n(`${i18nKey}.devServer.setupError`, { message: e.message }) + i18n(`${i18nKey}.devServer.setupError`, { + message: e instanceof Error ? e.message : '', + }) ); return false; } } - async devServerStart() { + async devServerStart(): Promise { try { await DevServerManager.start({ accountId: this.targetAccountId, @@ -489,13 +568,15 @@ class LocalDevManager { logger.error(e); } logger.error( - i18n(`${i18nKey}.devServer.startError`, { message: e.message }) + i18n(`${i18nKey}.devServer.startError`, { + message: e instanceof Error ? e.message : '', + }) ); process.exit(EXIT_CODES.ERROR); } } - devServerFileChange(filePath, event) { + devServerFileChange(filePath: string, event: string): void { try { DevServerManager.fileChange({ filePath, event }); } catch (e) { @@ -504,13 +585,13 @@ class LocalDevManager { } logger.error( i18n(`${i18nKey}.devServer.fileChangeError`, { - message: e.message, + message: e instanceof Error ? e.message : '', }) ); } } - async devServerCleanup() { + async devServerCleanup(): Promise { try { await DevServerManager.cleanup(); return true; @@ -519,11 +600,14 @@ class LocalDevManager { logger.error(e); } logger.error( - i18n(`${i18nKey}.devServer.cleanupError`, { message: e.message }) + i18n(`${i18nKey}.devServer.cleanupError`, { + message: e instanceof Error ? e.message : '', + }) ); return false; } } } +export default LocalDevManager; module.exports = LocalDevManager; diff --git a/lib/localDev.ts b/lib/localDev.ts index 886e185ca..76fe50088 100644 --- a/lib/localDev.ts +++ b/lib/localDev.ts @@ -1,66 +1,77 @@ -// @ts-nocheck -const { logger } = require('@hubspot/local-dev-lib/logger'); -const { +import { logger } from '@hubspot/local-dev-lib/logger'; +import { HUBSPOT_ACCOUNT_TYPES, HUBSPOT_ACCOUNT_TYPE_STRINGS, -} = require('@hubspot/local-dev-lib/constants/config'); -const { +} from '@hubspot/local-dev-lib/constants/config'; +import { isMissingScopeError, isSpecifiedError, -} = require('@hubspot/local-dev-lib/errors/index'); -const { getHubSpotWebsiteOrigin } = require('@hubspot/local-dev-lib/urls'); -const { getAccountConfig, getEnv } = require('@hubspot/local-dev-lib/config'); -const { createProject } = require('@hubspot/local-dev-lib/api/projects'); -const { - ENVIRONMENTS, -} = require('@hubspot/local-dev-lib/constants/environments'); -const { +} from '@hubspot/local-dev-lib/errors/index'; +import { getHubSpotWebsiteOrigin } from '@hubspot/local-dev-lib/urls'; +import { getAccountConfig, getEnv } from '@hubspot/local-dev-lib/config'; +import { createProject } from '@hubspot/local-dev-lib/api/projects'; +import { ENVIRONMENTS } from '@hubspot/local-dev-lib/constants/environments'; +import { PERSONAL_ACCESS_KEY_AUTH_METHOD } from '@hubspot/local-dev-lib/constants/auth'; +import { getAccountIdentifier } from '@hubspot/local-dev-lib/config/getAccountIdentifier'; +import { CLIAccount } from '@hubspot/local-dev-lib/types/Accounts'; +import { Environment } from '@hubspot/local-dev-lib/types/Config'; +import { DeveloperTestAccount } from '@hubspot/local-dev-lib/types/developerTestAccounts'; +import { Project } from '@hubspot/local-dev-lib/types/Project'; + +import { confirmDefaultAccountPrompt, selectSandboxTargetAccountPrompt, selectDeveloperTestTargetAccountPrompt, confirmUseExistingDeveloperTestAccountPrompt, -} = require('./prompts/projectDevTargetAccountPrompt'); -const { confirmPrompt } = require('./prompts/promptUtils'); -const { - validateSandboxUsageLimits, - getAvailableSyncTypes, -} = require('./sandboxes'); -const { syncSandbox } = require('./sandboxSync'); -const { - validateDevTestAccountUsageLimits, -} = require('./developerTestAccounts'); -const { uiCommandReference, uiLine, uiAccountDescription } = require('./ui'); -const SpinniesManager = require('./ui/SpinniesManager'); -const { i18n } = require('./lang'); -const { EXIT_CODES } = require('./enums/exitCodes'); -const { trackCommandMetadataUsage } = require('./usageTracking'); -const { - isAppDeveloperAccount, - isDeveloperTestAccount, -} = require('./accountTypes'); -const { handleProjectUpload } = require('./projects/upload'); -const { pollProjectBuildAndDeploy } = require('./projects/buildAndDeploy'); -const { +} from './prompts/projectDevTargetAccountPrompt'; +import { confirmPrompt } from './prompts/promptUtils'; +import { validateSandboxUsageLimits, getAvailableSyncTypes } from './sandboxes'; +import { syncSandbox } from './sandboxSync'; +import { validateDevTestAccountUsageLimits } from './developerTestAccounts'; +import { uiCommandReference, uiLine, uiAccountDescription } from './ui'; +import SpinniesManager from './ui/SpinniesManager'; +import { i18n } from './lang'; +import { EXIT_CODES } from './enums/exitCodes'; +import { trackCommandMetadataUsage } from './usageTracking'; +import { isAppDeveloperAccount, isDeveloperTestAccount } from './accountTypes'; +import { handleProjectUpload } from './projects/upload'; +import { pollProjectBuildAndDeploy } from './projects/buildAndDeploy'; +import { PROJECT_ERROR_TYPES, PROJECT_BUILD_TEXT, PROJECT_DEPLOY_TEXT, -} = require('./constants'); -const { logError, ApiErrorContext } = require('./errorHandlers/index'); -const { - PERSONAL_ACCESS_KEY_AUTH_METHOD, -} = require('@hubspot/local-dev-lib/constants/auth'); -const { +} from './constants'; +import { logError, ApiErrorContext } from './errorHandlers/index'; +import { buildSandbox, buildDeveloperTestAccount, saveAccountToConfig, -} = require('./buildAccount'); -const { hubspotAccountNamePrompt } = require('./prompts/accountNamePrompt'); +} from './buildAccount'; +import { hubspotAccountNamePrompt } from './prompts/accountNamePrompt'; +import { + ProjectConfig, + ProjectPollResult, + ProjectSubtask, +} from '../types/Projects'; +import { FileResult } from 'tmp'; +import { Build } from '@hubspot/local-dev-lib/types/Build'; const i18nKey = 'lib.localDev'; // If the user passed in the --account flag, confirm they want to use that account as // their target account, otherwise exit -const confirmDefaultAccountIsTarget = async accountConfig => { +export async function confirmDefaultAccountIsTarget( + accountConfig: CLIAccount +): Promise { + if (!accountConfig.name || !accountConfig.accountType) { + logger.error( + i18n(`${i18nKey}.confirmDefaultAccountIsTarget.configError`, { + authCommand: uiCommandReference('hs auth'), + }) + ); + process.exit(EXIT_CODES.ERROR); + } + logger.log(); const useDefaultAccount = await confirmDefaultAccountPrompt( accountConfig.name, @@ -79,10 +90,13 @@ const confirmDefaultAccountIsTarget = async accountConfig => { ); process.exit(EXIT_CODES.SUCCESS); } -}; +} // Confirm the default account is supported for the type of apps being developed -const checkIfDefaultAccountIsSupported = (accountConfig, hasPublicApps) => { +export function checkIfDefaultAccountIsSupported( + accountConfig: CLIAccount, + hasPublicApps: boolean +): void { if ( hasPublicApps && !( @@ -106,14 +120,19 @@ const checkIfDefaultAccountIsSupported = (accountConfig, hasPublicApps) => { ); process.exit(EXIT_CODES.SUCCESS); } -}; +} -const checkIfParentAccountIsAuthed = accountConfig => { - if (!getAccountConfig(accountConfig.parentAccountId)) { +export function checkIfParentAccountIsAuthed(accountConfig: CLIAccount): void { + if ( + !accountConfig.parentAccountId || + !getAccountConfig(accountConfig.parentAccountId) + ) { logger.error( i18n(`${i18nKey}.checkIfParentAccountIsAuthed.notAuthedError`, { - accountId: accountConfig.parentAccountId, - accountIdentifier: uiAccountDescription(accountConfig.portalId), + accountId: accountConfig.parentAccountId || '', + accountIdentifier: uiAccountDescription( + getAccountIdentifier(accountConfig) + ), authCommand: uiCommandReference( `hs auth --account=${accountConfig.parentAccountId}` ), @@ -121,10 +140,13 @@ const checkIfParentAccountIsAuthed = accountConfig => { ); process.exit(EXIT_CODES.SUCCESS); } -}; +} // Confirm the default account is a developer account if developing public apps -const checkIfAccountFlagIsSupported = (accountConfig, hasPublicApps) => { +export function checkIfAccountFlagIsSupported( + accountConfig: CLIAccount, + hasPublicApps: boolean +): void { if (hasPublicApps) { if (!isDeveloperTestAccount(accountConfig)) { logger.error( @@ -144,14 +166,14 @@ const checkIfAccountFlagIsSupported = (accountConfig, hasPublicApps) => { ); process.exit(EXIT_CODES.SUCCESS); } -}; +} // If the user isn't using the recommended account type, prompt them to use or create one -const suggestRecommendedNestedAccount = async ( - accounts, - accountConfig, - hasPublicApps -) => { +export async function suggestRecommendedNestedAccount( + accounts: CLIAccount[], + accountConfig: CLIAccount, + hasPublicApps: boolean +) { logger.log(); uiLine(); if (hasPublicApps) { @@ -170,11 +192,15 @@ const suggestRecommendedNestedAccount = async ( ? selectDeveloperTestTargetAccountPrompt : selectSandboxTargetAccountPrompt; - return targetAccountPrompt(accounts, accountConfig, hasPublicApps); -}; + return targetAccountPrompt(accounts, accountConfig); +} // Create a new sandbox and return its accountId -const createSandboxForLocalDev = async (accountId, accountConfig, env) => { +export async function createSandboxForLocalDev( + accountId: number, + accountConfig: CLIAccount, + env: Environment +): Promise { try { await validateSandboxUsageLimits( accountConfig, @@ -222,6 +248,12 @@ const createSandboxForLocalDev = async (accountId, accountConfig, env) => { const targetAccountId = result.sandbox.sandboxHubId; const sandboxAccountConfig = getAccountConfig(result.sandbox.sandboxHubId); + + if (!sandboxAccountConfig) { + logger.error(i18n('lib.sandbox.create.failure.generic')); + process.exit(EXIT_CODES.ERROR); + } + const syncTasks = await getAvailableSyncTypes( accountConfig, sandboxAccountConfig @@ -239,14 +271,14 @@ const createSandboxForLocalDev = async (accountId, accountConfig, env) => { logError(err); process.exit(EXIT_CODES.ERROR); } -}; +} // Create a developer test account and return its accountId -const createDeveloperTestAccountForLocalDev = async ( - accountId, - accountConfig, - env -) => { +export async function createDeveloperTestAccountForLocalDev( + accountId: number, + accountConfig: CLIAccount, + env: Environment +): Promise { let currentPortalCount = 0; let maxTestPortals = 10; try { @@ -302,10 +334,13 @@ const createDeveloperTestAccountForLocalDev = async ( logError(err); process.exit(EXIT_CODES.ERROR); } -}; +} // Prompt user to confirm usage of an existing developer test account that is not currently in the config -const useExistingDevTestAccount = async (env, account) => { +export async function useExistingDevTestAccount( + env: Environment, + account: DeveloperTestAccount +): Promise { const useExistingDevTestAcct = await confirmUseExistingDeveloperTestAccountPrompt(account); if (!useExistingDevTestAcct) { @@ -333,15 +368,15 @@ const useExistingDevTestAccount = async (env, account) => { authType: PERSONAL_ACCESS_KEY_AUTH_METHOD.name, }) ); -}; +} // Prompt the user to create a new project if one doesn't exist on their target account -const createNewProjectForLocalDev = async ( - projectConfig, - targetAccountId, - shouldCreateWithoutConfirmation, - hasPublicApps -) => { +export async function createNewProjectForLocalDev( + projectConfig: ProjectConfig, + targetAccountId: number, + shouldCreateWithoutConfirmation: boolean, + hasPublicApps: boolean +): Promise { // Create the project without prompting if this is a newly created sandbox let shouldCreateProject = shouldCreateWithoutConfirmation; @@ -404,26 +439,51 @@ const createNewProjectForLocalDev = async ( ); process.exit(EXIT_CODES.SUCCESS); } -}; +} + +function projectUploadCallback( + accountId: number, + projectConfig: ProjectConfig, + tempFile: FileResult, + buildId?: number +): Promise { + if (!buildId) { + logger.error( + i18n(`${i18nKey}.createInitialBuildForNewProject.initialUploadMessage`, { + uploadCommand: uiCommandReference('hs project upload'), + }) + ); + process.exit(EXIT_CODES.ERROR); + } -// Create an initial build if the project was newly created in the account -// Return the newly deployed build -const createInitialBuildForNewProject = async ( - projectConfig, - projectDir, - targetAccountId -) => { - const initialUploadResult = await handleProjectUpload( - targetAccountId, + return pollProjectBuildAndDeploy( + accountId, projectConfig, - projectDir, - (...args) => pollProjectBuildAndDeploy(...args, true), - i18n(`${i18nKey}.createInitialBuildForNewProject.initialUploadMessage`) + tempFile, + buildId, + true ); +} + +// Create an initial build if the project was newly created in the account +// Return the newly deployed build +export async function createInitialBuildForNewProject( + projectConfig: ProjectConfig, + projectDir: string, + targetAccountId: number +): Promise { + const { result: initialUploadResult, uploadError } = + await handleProjectUpload( + targetAccountId, + projectConfig, + projectDir, + projectUploadCallback, + i18n(`${i18nKey}.createInitialBuildForNewProject.initialUploadMessage`) + ); - if (initialUploadResult.uploadError) { + if (uploadError) { if ( - isSpecifiedError(initialUploadResult.uploadError, { + isSpecifiedError(uploadError, { subCategory: PROJECT_ERROR_TYPES.PROJECT_LOCKED, }) ) { @@ -434,7 +494,7 @@ const createInitialBuildForNewProject = async ( logger.log(); } else { logError( - initialUploadResult.uploadError, + uploadError, new ApiErrorContext({ accountId: targetAccountId, projectName: projectConfig.name, @@ -444,13 +504,13 @@ const createInitialBuildForNewProject = async ( process.exit(EXIT_CODES.ERROR); } - if (!initialUploadResult.succeeded) { - let subTasks = []; + if (!initialUploadResult?.succeeded) { + let subTasks: ProjectSubtask[] = []; - if (initialUploadResult.buildResult.status === 'FAILURE') { + if (initialUploadResult?.buildResult.status === 'FAILURE') { subTasks = initialUploadResult.buildResult[PROJECT_BUILD_TEXT.SUBTASK_KEY]; - } else if (initialUploadResult.deployResult.status === 'FAILURE') { + } else if (initialUploadResult?.deployResult?.status === 'FAILURE') { subTasks = initialUploadResult.deployResult[PROJECT_DEPLOY_TEXT.SUBTASK_KEY]; } @@ -467,25 +527,11 @@ const createInitialBuildForNewProject = async ( } return initialUploadResult.buildResult; -}; +} -const getAccountHomeUrl = accountId => { +export function getAccountHomeUrl(accountId: number): string { const baseUrl = getHubSpotWebsiteOrigin( getEnv(accountId) === 'qa' ? ENVIRONMENTS.QA : ENVIRONMENTS.PROD ); return `${baseUrl}/home?portalId=${accountId}`; -}; - -module.exports = { - confirmDefaultAccountIsTarget, - checkIfDefaultAccountIsSupported, - checkIfAccountFlagIsSupported, - suggestRecommendedNestedAccount, - createSandboxForLocalDev, - createDeveloperTestAccountForLocalDev, - useExistingDevTestAccount, - createNewProjectForLocalDev, - createInitialBuildForNewProject, - getAccountHomeUrl, - checkIfParentAccountIsAuthed, -}; +} diff --git a/lib/projects/buildAndDeploy.ts b/lib/projects/buildAndDeploy.ts index 1a1960f7f..83f2c5d63 100644 --- a/lib/projects/buildAndDeploy.ts +++ b/lib/projects/buildAndDeploy.ts @@ -36,6 +36,7 @@ import { ProjectTask, ProjectSubtask, ProjectPollStatusFunctionText, + ProjectPollResult, } from '../../types/Projects'; const i18nKey = 'lib.projectBuildAndDeploy'; @@ -453,13 +454,6 @@ export const pollDeployStatus = makePollTaskStatusFunc({ }, }); -type ProjectPollResult = { - succeeded: boolean; - buildId: number; - buildResult: Build; - deployResult: Deploy | null; -}; - export async function displayWarnLogs( accountId: number, projectName: string, diff --git a/lib/projects/structure.ts b/lib/projects/structure.ts index d6ad0a903..1f4b2f55c 100644 --- a/lib/projects/structure.ts +++ b/lib/projects/structure.ts @@ -149,3 +149,30 @@ export function getProjectComponentTypes(components: Array): { components.forEach(({ type }) => (projectContents[type] = true)); return projectContents; } + +export function getComponentUid(component?: Component | null): string | null { + if (!component) { + return null; + } else if ('uid' in component.config) { + return component.config.uid; + } else { + return component.config.data.uid; + } +} + +export function componentIsApp( + component?: Component | null +): component is Component< + PublicAppComponentConfig | PrivateAppComponentConfig +> { + return ( + component?.type === ComponentTypes.PublicApp || + component?.type === ComponentTypes.PrivateApp + ); +} + +export function componentIsPublicApp( + component?: Component | null +): component is Component { + return component?.type === ComponentTypes.PublicApp; +} diff --git a/lib/projects/upload.ts b/lib/projects/upload.ts index 98068259d..b3ff5ff1e 100644 --- a/lib/projects/upload.ts +++ b/lib/projects/upload.ts @@ -80,19 +80,20 @@ type ProjectUploadCallbackFunction = ( projectConfig: ProjectConfig, tempFile: FileResult, buildId?: number -) => Promise; +) => Promise; -type ProjectUploadDefaultResult = { +type ProjectUploadResult = { + result?: T; uploadError?: unknown; }; -export async function handleProjectUpload( +export async function handleProjectUpload( accountId: number, projectConfig: ProjectConfig, projectDir: string, callbackFunc: ProjectUploadCallbackFunction, uploadMessage: string -) { +): Promise> { const srcDir = path.resolve(projectDir, projectConfig.srcDir); const filenames = fs.readdirSync(srcDir); @@ -116,10 +117,8 @@ export async function handleProjectUpload( const output = fs.createWriteStream(tempFile.name); const archive = archiver('zip'); - const result = new Promise(resolve => + const result = new Promise>(resolve => output.on('close', async function () { - let uploadResult: ProjectUploadDefaultResult | T | undefined; - logger.debug( i18n(`${i18nKey}.handleProjectUpload.compressed`, { byteCount: archive.pointer(), @@ -136,16 +135,16 @@ export async function handleProjectUpload( if (error) { console.log(error); - uploadResult = { uploadError: error }; + resolve({ uploadError: error }); } else if (callbackFunc) { - uploadResult = await callbackFunc( + const uploadResult = await callbackFunc( accountId, projectConfig, tempFile, buildId ); + resolve({ result: uploadResult }); } - resolve(uploadResult || {}); }) ); diff --git a/lib/prompts/installPublicAppPrompt.ts b/lib/prompts/installPublicAppPrompt.ts index 56f6759af..33e5a527b 100644 --- a/lib/prompts/installPublicAppPrompt.ts +++ b/lib/prompts/installPublicAppPrompt.ts @@ -10,7 +10,7 @@ const i18nKey = 'lib.prompts.installPublicAppPrompt'; export async function installPublicAppPrompt( env: string, targetAccountId: number, - clientId: number, + clientId: string, scopes: string[], redirectUrls: string[], isReinstall = false diff --git a/lib/prompts/projectDevTargetAccountPrompt.ts b/lib/prompts/projectDevTargetAccountPrompt.ts index 8be678aa2..b89774159 100644 --- a/lib/prompts/projectDevTargetAccountPrompt.ts +++ b/lib/prompts/projectDevTargetAccountPrompt.ts @@ -11,7 +11,7 @@ import { import { getAccountIdentifier } from '@hubspot/local-dev-lib/config/getAccountIdentifier'; import { logger } from '@hubspot/local-dev-lib/logger'; import { fetchDeveloperTestAccounts } from '@hubspot/local-dev-lib/api/developerTestAccounts'; -import { CLIAccount, AccountType } from '@hubspot/local-dev-lib/types/Accounts'; +import { CLIAccount } from '@hubspot/local-dev-lib/types/Accounts'; import { Usage } from '@hubspot/local-dev-lib/types/Sandbox'; import { DeveloperTestAccount, @@ -214,7 +214,7 @@ async function selectTargetAccountPrompt( export async function confirmDefaultAccountPrompt( accountName: string, - accountType: AccountType + accountType: string ): Promise { const { useDefaultAccount } = await promptUser<{ useDefaultAccount: boolean; diff --git a/types/Projects.ts b/types/Projects.ts index 0d7b9ac25..3a3606efb 100644 --- a/types/Projects.ts +++ b/types/Projects.ts @@ -50,6 +50,13 @@ export type ProjectTemplateRepoConfig = { components?: ComponentTemplate[]; }; +export type ProjectPollResult = { + succeeded: boolean; + buildId: number; + buildResult: Build; + deployResult: Deploy | null; +}; + export type PrivateAppComponentConfig = { name: string; description: string; @@ -114,9 +121,9 @@ export enum ComponentTypes { HublTheme = 'hubl-theme', } -export type Component = { +export type Component = { type: ComponentTypes; - config: GenericComponentConfig; + config: T; runnable: boolean; path: string; };