@hubspot/cli 8.17.0-beta.0 → 8.17.0-beta.1

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.
@@ -4,6 +4,8 @@ export type ProjectDownloadArgs = CommonArgs & ConfigArgs & AccountArgs & Enviro
4
4
  project?: string;
5
5
  dest?: string;
6
6
  build?: number;
7
+ force?: boolean;
8
+ keepLocalFiles?: boolean;
7
9
  };
8
10
  declare const projectDownloadCommand: YargsCommandModule<unknown, ProjectDownloadArgs>;
9
11
  export default projectDownloadCommand;
@@ -1,10 +1,9 @@
1
- import path from 'path';
2
- import { getCwd, sanitizeFileName } from '@hubspot/local-dev-lib/path';
3
- import { extractZipArchive } from '@hubspot/local-dev-lib/archive';
4
1
  import { downloadProject, fetchProjectBuilds, } from '@hubspot/local-dev-lib/api/projects';
5
2
  import { logError, ApiErrorContext } from '../../lib/errorHandlers/index.js';
6
3
  import { isPromptExitError } from '../../lib/errors/PromptExitError.js';
7
- import { getIsInProject } from '../../lib/projects/config.js';
4
+ import { confirmPrompt } from '../../lib/prompts/promptUtils.js';
5
+ import { archiveDestExists, moveSourceToProjectArchive, } from '../../lib/projects/archive.js';
6
+ import { describeArchiveLocation, extractBuild, getDisplayPath, getLocalProject, handleArchivedSource, resolveDownloadDestination, } from '../../lib/projects/download.js';
8
7
  import { downloadProjectPrompt } from '../../lib/prompts/downloadProjectPrompt.js';
9
8
  import { commands } from '../../lang/en.js';
10
9
  import { uiLogger } from '../../lib/ui/logger.js';
@@ -15,15 +14,14 @@ import { ProjectDownloadSchema, } from '../../lib/jsonOutput/projectDownload.js'
15
14
  const command = 'download';
16
15
  const describe = commands.project.download.describe;
17
16
  async function handler(args) {
18
- const { dest, build, derivedAccountId, exit, addJsonOutput } = args;
19
- const isInProjectDir = getIsInProject();
20
- if (isInProjectDir) {
21
- uiLogger.error(commands.project.download.warnings.cannotDownloadWithinProject);
22
- return exit(EXIT_CODES.ERROR);
23
- }
17
+ const { project: projectArg, dest, build, force, keepLocalFiles, derivedAccountId, formatOutputAsJson, exit, addJsonOutput, } = args;
24
18
  let buildNumberToDownload = build;
25
19
  try {
26
- const { project: projectName } = await downloadProjectPrompt(args);
20
+ const localProject = getLocalProject();
21
+ const { project: projectName } = await downloadProjectPrompt({
22
+ ...args,
23
+ project: projectArg || localProject?.projectName,
24
+ });
27
25
  if (!buildNumberToDownload) {
28
26
  const { data: projectBuildsResult } = await fetchProjectBuilds(derivedAccountId, projectName);
29
27
  const { results: projectBuilds } = projectBuildsResult;
@@ -36,16 +34,46 @@ async function handler(args) {
36
34
  uiLogger.error(commands.project.download.errors.noBuildIdToDownload);
37
35
  return exit(EXIT_CODES.ERROR);
38
36
  }
39
- const sanitizedProjectName = sanitizeFileName(projectName);
40
- const absoluteDestPath = dest
41
- ? path.resolve(getCwd(), dest, sanitizedProjectName)
42
- : path.resolve(getCwd(), sanitizedProjectName);
37
+ const { absoluteDestPath, archivePlan } = resolveDownloadDestination({
38
+ projectName,
39
+ dest,
40
+ localProject,
41
+ });
42
+ if (archivePlan && archiveDestExists(archivePlan.archiveDest)) {
43
+ uiLogger.error(commands.project.download.errors.archiveAlreadyExists(getDisplayPath(archivePlan.archiveDest)));
44
+ return exit(EXIT_CODES.ERROR);
45
+ }
46
+ if (archivePlan && !force && !formatOutputAsJson) {
47
+ uiLogger.warn(commands.project.download.warnings.sourceWillBeArchived(describeArchiveLocation(archivePlan)));
48
+ uiLogger.log('');
49
+ const confirmed = await confirmPrompt(commands.project.download.prompts.confirmDownload(buildNumberToDownload, projectName), { defaultAnswer: false });
50
+ if (!confirmed) {
51
+ uiLogger.log(commands.project.download.logs.downloadCancelled);
52
+ return exit(EXIT_CODES.SUCCESS);
53
+ }
54
+ }
43
55
  const { data: zippedProject } = await downloadProject(derivedAccountId, projectName, buildNumberToDownload);
44
- await extractZipArchive(zippedProject, sanitizeFileName(projectName), path.resolve(absoluteDestPath));
56
+ if (archivePlan) {
57
+ moveSourceToProjectArchive(archivePlan.projectDir, archivePlan.srcDir);
58
+ }
59
+ await extractBuild({
60
+ zippedProject,
61
+ projectName,
62
+ absoluteDestPath,
63
+ archivePlan,
64
+ });
65
+ if (archivePlan) {
66
+ await handleArchivedSource({
67
+ archivePlan,
68
+ keepLocalFiles,
69
+ canPrompt: !force && !formatOutputAsJson,
70
+ });
71
+ }
45
72
  addJsonOutput({
46
73
  projectName,
47
74
  buildId: buildNumberToDownload,
48
75
  dest: absoluteDestPath,
76
+ archiveDest: archivePlan?.archiveDest,
49
77
  });
50
78
  uiLogger.log(commands.project.download.logs.downloadSucceeded(buildNumberToDownload, projectName));
51
79
  return exit(EXIT_CODES.SUCCESS);
@@ -76,12 +104,24 @@ function projectDownloadBuilder(yargs) {
76
104
  alias: ['build-id'],
77
105
  type: 'number',
78
106
  },
107
+ force: {
108
+ describe: commands.project.download.options.force.describe,
109
+ type: 'boolean',
110
+ },
111
+ 'keep-local-files': {
112
+ describe: commands.project.download.options.keepLocalFiles.describe,
113
+ type: 'boolean',
114
+ },
79
115
  });
80
116
  yargs.example([
81
117
  [
82
118
  '$0 project download --project=myProject --dest=myProjectFolder',
83
119
  commands.project.download.examples.default,
84
120
  ],
121
+ [
122
+ '$0 project download --build=3',
123
+ commands.project.download.examples.currentProject,
124
+ ],
85
125
  [
86
126
  '$0 project download --project=myProject --json',
87
127
  commands.project.download.examples.json,
package/lang/en.d.ts CHANGED
@@ -2012,24 +2012,43 @@ export declare const commands: {
2012
2012
  describe: string;
2013
2013
  examples: {
2014
2014
  default: string;
2015
+ currentProject: string;
2015
2016
  json: string;
2016
2017
  };
2017
2018
  logs: {
2018
2019
  downloadCancelled: string;
2019
2020
  downloadSucceeded: (buildId: number, projectName: string) => string;
2021
+ filesOnlyInArchive: (files: string[], hiddenCount: number, diffFilePath?: string) => string;
2022
+ filesCopiedBack: (copiedCount: number, srcPath: string) => string;
2023
+ sourceContentsArchived: (archiveLocation: string) => string;
2020
2024
  };
2021
2025
  errors: {
2022
2026
  downloadFailed: string;
2023
2027
  projectNotFound: (projectName: string, accountId: string) => string;
2024
2028
  noBuildIdToDownload: string;
2029
+ restoreFailed: (archiveDest: string) => string;
2030
+ archiveAlreadyExists: (archiveDest: string) => string;
2025
2031
  };
2026
2032
  warnings: {
2027
- cannotDownloadWithinProject: string;
2033
+ filesNotCopiedBack: (failedCount: number) => string;
2034
+ sourceWillBeArchived: (archiveLocation: string) => string;
2035
+ sourceRestored: string;
2036
+ };
2037
+ archiveLocation: (archivePath: string) => string;
2038
+ prompts: {
2039
+ confirmCopyFilesBack: (fileCount: number) => string;
2040
+ confirmDownload: (buildId: number, projectName: string) => string;
2028
2041
  };
2029
2042
  options: {
2030
2043
  build: {
2031
2044
  describe: string;
2032
2045
  };
2046
+ force: {
2047
+ describe: string;
2048
+ };
2049
+ keepLocalFiles: {
2050
+ describe: string;
2051
+ };
2033
2052
  project: {
2034
2053
  describe: string;
2035
2054
  };
@@ -3639,6 +3658,12 @@ export declare const lib: {
3639
3658
  generateSafeFilenameDifferentiator: {
3640
3659
  failedToCheckFiles: string;
3641
3660
  };
3661
+ archive: {
3662
+ errors: {
3663
+ archiveNotFound: (archiveDest: string) => string;
3664
+ srcDirInsideArchive: (srcDir: string) => string;
3665
+ };
3666
+ };
3642
3667
  validateProjectConfig: {
3643
3668
  configNotFound: string;
3644
3669
  };
@@ -4481,6 +4506,7 @@ export declare const lib: {
4481
4506
  oauth2AccessTokenNotFound: (accountId: number) => string;
4482
4507
  personalAccessKeyMissing: (accountId: number) => string;
4483
4508
  personalAccessKeyTokenRetrievalFailed: (accountId: number) => string;
4509
+ accessTokenMissing: (accountId: number) => string;
4484
4510
  authConfigurationMissing: (accountId: number) => string;
4485
4511
  availableCMSModes: (modes: string) => string;
4486
4512
  invalidCmsPublishMode: (cmsPublishMode: string, modesMessage: string) => string;
package/lang/en.js CHANGED
@@ -2030,26 +2030,54 @@ export const commands = {
2030
2030
  describe: 'Download your project files from HubSpot.',
2031
2031
  examples: {
2032
2032
  default: 'Download the project myProject into myProjectFolder folder',
2033
+ currentProject: 'Download build 3 of the current project into the current project directory',
2033
2034
  json: 'Output the download result as JSON for scripting',
2034
2035
  },
2035
2036
  logs: {
2036
2037
  downloadCancelled: 'Cancelling project download',
2037
2038
  downloadSucceeded: (buildId, projectName) => `Downloaded build "${buildId}" from project "${projectName}"`,
2039
+ filesOnlyInArchive: (files, hiddenCount, diffFilePath) => [
2040
+ 'These files existed locally but are not in the downloaded build. They are available in the archive directory:',
2041
+ ...files.map(file => `${indent(2)}- ${file}`),
2042
+ ...(hiddenCount > 0
2043
+ ? [`${indent(2)}...and ${hiddenCount} more`]
2044
+ : []),
2045
+ ...(hiddenCount > 0 && diffFilePath
2046
+ ? [`\nThe full list can be viewed in ${chalk.bold(diffFilePath)}`]
2047
+ : []),
2048
+ ].join('\n'),
2049
+ filesCopiedBack: (copiedCount, srcPath) => `Copied ${copiedCount} ${copiedCount === 1 ? 'file' : 'files'} back to ${chalk.bold(srcPath)}`,
2050
+ sourceContentsArchived: (archiveLocation) => `The previous contents of your project have been moved to ${archiveLocation}. Once you have reviewed them, you can safely delete that directory.`,
2038
2051
  },
2039
2052
  errors: {
2040
2053
  downloadFailed: 'Something went wrong downloading the project',
2041
2054
  projectNotFound: (projectName, accountId) => `Your project ${chalk.bold(projectName)} could not be found in ${accountId}`,
2042
2055
  noBuildIdToDownload: 'No build ID available for download',
2056
+ restoreFailed: (archiveDest) => `Extracting the downloaded build failed, and your original project files could not be restored automatically. They are in ${chalk.bold(archiveDest)}.`,
2057
+ archiveAlreadyExists: (archiveDest) => `Cannot download into the current project because ${chalk.bold(archiveDest)} already exists. Delete or rename it and run the command again.`,
2043
2058
  },
2044
2059
  warnings: {
2045
- cannotDownloadWithinProject: 'Cancelling project download. Please run the command again outside the context of an existing project.',
2060
+ filesNotCopiedBack: (failedCount) => `${failedCount} ${failedCount === 1 ? 'file' : 'files'} could not be copied back. ${failedCount === 1 ? 'It is' : 'They are'} still available in the archive directory.`,
2061
+ sourceWillBeArchived: (archiveLocation) => `Your current project source files will be moved to ${archiveLocation}.\nBack up any local changes in this project before you continue.`,
2062
+ sourceRestored: 'Extracting the downloaded build failed. Your original project files have been restored. The archive directory was left in place and can be deleted.',
2063
+ },
2064
+ archiveLocation: (archivePath) => `the archive directory in your project root (${chalk.bold(archivePath)})`,
2065
+ prompts: {
2066
+ confirmCopyFilesBack: (fileCount) => `[--keep-local-files] Copy ${fileCount === 1 ? 'this file' : `these ${fileCount} files`} back into your project source directory?`,
2067
+ confirmDownload: (buildId, projectName) => `[--force] Download build "${buildId}" of project "${projectName}"?`,
2046
2068
  },
2047
2069
  options: {
2048
2070
  build: {
2049
- describe: 'The build to download',
2071
+ describe: 'The build to download (defaults to the latest build)',
2072
+ },
2073
+ force: {
2074
+ describe: 'Skip the confirmation prompt before archiving your source',
2075
+ },
2076
+ keepLocalFiles: {
2077
+ describe: 'Copy local files missing from the build back into the source directory without prompting (--no-keep-local-files skips)',
2050
2078
  },
2051
2079
  project: {
2052
- describe: 'The name of the project to download',
2080
+ describe: 'The name of the project to download (defaults to the current project)',
2053
2081
  },
2054
2082
  dest: {
2055
2083
  describe: 'Destination folder for the project',
@@ -3772,6 +3800,12 @@ export const lib = {
3772
3800
  generateSafeFilenameDifferentiator: {
3773
3801
  failedToCheckFiles: 'Failed to check files for filename differentiator. Falling back to timestamp.',
3774
3802
  },
3803
+ archive: {
3804
+ errors: {
3805
+ archiveNotFound: (archiveDest) => `Archive directory not found: ${archiveDest}`,
3806
+ srcDirInsideArchive: (srcDir) => `The source directory "${srcDir}" cannot be the archive directory or inside it`,
3807
+ },
3808
+ },
3775
3809
  validateProjectConfig: {
3776
3810
  configNotFound: `Unable to locate a project configuration file. Try running again from a project directory, or run ${uiCommandReference('hs project create')} to create a new project.`,
3777
3811
  },
@@ -4251,9 +4285,9 @@ export const lib = {
4251
4285
  },
4252
4286
  },
4253
4287
  downloadProjectPrompt: {
4254
- selectProject: 'Select a project to download:',
4288
+ selectProject: '[--project] Select a project to download:',
4255
4289
  errors: {
4256
- projectNotFound: (projectName, accountId) => `Your project ${projectName} could not be found in ${accountId}. Please select a valid project:`,
4290
+ projectNotFound: (projectName, accountId) => `[--project] Your project ${projectName} could not be found in ${uiAccountDescription(accountId)}. Please select a valid project:`,
4257
4291
  accountIdRequired: 'An account ID is required to download a project.',
4258
4292
  },
4259
4293
  },
@@ -4614,6 +4648,7 @@ export const lib = {
4614
4648
  oauth2AccessTokenNotFound: (accountId) => `The OAuth2 access token could not be found for accountId ${uiAccountDescription(accountId)}`,
4615
4649
  personalAccessKeyMissing: (accountId) => `The account "${uiAccountDescription(accountId)}" is configured to use a access key for authentication and is missing a "personalAccessKey" in the configuration file`,
4616
4650
  personalAccessKeyTokenRetrievalFailed: (accountId) => `An OAuth2 access token for account "${uiAccountDescription(accountId)} could not be retrieved using the "personalAccessKey" provided`,
4651
+ accessTokenMissing: (accountId) => `The account "${uiAccountDescription(accountId)}" is configured to use an access token for authentication and is missing an access token`,
4617
4652
  authConfigurationMissing: (accountId) => `The accountId ${uiAccountDescription(accountId)} is missing authentication configuration`,
4618
4653
  availableCMSModes: (modes) => `Available CMS publish modes are: ${modes}`,
4619
4654
  invalidCmsPublishMode: (cmsPublishMode, modesMessage) => `The CMS publish mode "${cmsPublishMode}" is invalid. ${modesMessage}`,
@@ -11,11 +11,11 @@ import { downloadProject, fetchProjectComponentsMetadata, } from '@hubspot/local
11
11
  import { Separator } from '@inquirer/prompts';
12
12
  import { confirmPrompt, inputPrompt, listPrompt, } from '../prompts/promptUtils.js';
13
13
  import { uiAccountDescription, uiCommandReference, uiLine, uiLink, } from '../ui/index.js';
14
+ import { archiveProjectSource } from '../projects/archive.js';
14
15
  import { ensureProjectExists } from '../projects/ensureProjectExists.js';
15
16
  import SpinniesManager from '../ui/SpinniesManager.js';
16
17
  import { DEFAULT_POLLING_STATUS_LOOKUP, poll } from '../polling.js';
17
18
  import { checkMigrationStatusV2, CLI_UNMIGRATABLE_REASONS, continueAppMigration, initializeAppMigration, isMigrationStatus, listAppsForMigration, } from '../../api/migrate.js';
18
- import fs from 'fs';
19
19
  import { lib } from '../../lang/en.js';
20
20
  import { hasUnfiedAppsAccess } from '../hasFeature.js';
21
21
  import { getProjectBuildDetailUrl, getProjectDetailUrl, } from '../projects/urls.js';
@@ -311,11 +311,8 @@ export async function downloadProjectFiles(derivedAccountId, projectName, buildI
311
311
  const { projectDir } = projectConfig;
312
312
  absoluteDestPath = projectDir;
313
313
  const { srcDir } = projectConfig.projectConfig;
314
- const archiveDest = srcDir === '.'
315
- ? path.join(path.dirname(projectDir), `${path.basename(projectDir)}-archive`)
316
- : path.join(projectDir, 'archive');
317
314
  // Move the existing source directory to archive
318
- fs.renameSync(path.join(projectDir, srcDir), archiveDest);
315
+ const archiveDest = archiveProjectSource(projectDir, srcDir);
319
316
  uiLogger.info(lib.migrate.sourceContentsMoved(archiveDest));
320
317
  }
321
318
  else {
@@ -3,5 +3,6 @@ export declare const ProjectDownloadSchema: z.ZodObject<{
3
3
  projectName: z.ZodString;
4
4
  buildId: z.ZodNumber;
5
5
  dest: z.ZodString;
6
+ archiveDest: z.ZodOptional<z.ZodString>;
6
7
  }, z.core.$strip>;
7
8
  export type ProjectDownloadJsonOutput = z.infer<typeof ProjectDownloadSchema>;
@@ -3,4 +3,5 @@ export const ProjectDownloadSchema = z.object({
3
3
  projectName: z.string(),
4
4
  buildId: z.number(),
5
5
  dest: z.string(),
6
+ archiveDest: z.string().optional(),
6
7
  });
@@ -0,0 +1,8 @@
1
+ export declare const ARCHIVE_DIR_NAME = "archive";
2
+ export declare const ROOT_SRC_DIR = ".";
3
+ export declare function getArchiveDest(projectDir: string, srcDir: string): string;
4
+ export declare function archiveDestExists(archiveDest: string): boolean;
5
+ export declare function archiveProjectSource(projectDir: string, srcDir: string): string;
6
+ export declare function getProjectArchiveDest(projectDir: string): string;
7
+ export declare function moveSourceToProjectArchive(projectDir: string, srcDir: string): string;
8
+ export declare function restoreSourceFromProjectArchive(projectDir: string, srcDir: string): void;
@@ -0,0 +1,104 @@
1
+ import fs from 'fs';
2
+ import path from 'path';
3
+ import { lib } from '../../lang/en.js';
4
+ export const ARCHIVE_DIR_NAME = 'archive';
5
+ export const ROOT_SRC_DIR = '.';
6
+ const ROOT_ENTRIES_KEPT_IN_PLACE = new Set([
7
+ '.git',
8
+ 'node_modules',
9
+ 'dist',
10
+ 'hsproject.json',
11
+ ]);
12
+ export function getArchiveDest(projectDir, srcDir) {
13
+ if (srcDir === ROOT_SRC_DIR) {
14
+ return path.join(path.dirname(projectDir), `${path.basename(projectDir)}-${ARCHIVE_DIR_NAME}`);
15
+ }
16
+ return path.join(projectDir, ARCHIVE_DIR_NAME);
17
+ }
18
+ export function archiveDestExists(archiveDest) {
19
+ return fs.existsSync(archiveDest);
20
+ }
21
+ export function archiveProjectSource(projectDir, srcDir) {
22
+ const archiveDest = getArchiveDest(projectDir, srcDir);
23
+ fs.renameSync(path.join(projectDir, srcDir), archiveDest);
24
+ return archiveDest;
25
+ }
26
+ export function getProjectArchiveDest(projectDir) {
27
+ return path.join(projectDir, ARCHIVE_DIR_NAME);
28
+ }
29
+ function assertSrcDirOutsideArchive(projectDir, srcDir) {
30
+ const archiveDest = path.resolve(getProjectArchiveDest(projectDir));
31
+ const srcPath = path.resolve(projectDir, srcDir);
32
+ const isInsideArchive = srcPath === archiveDest || srcPath.startsWith(archiveDest + path.sep);
33
+ if (isInsideArchive) {
34
+ throw new Error(lib.projects.archive.errors.srcDirInsideArchive(srcDir));
35
+ }
36
+ }
37
+ function assertArchiveExists(archiveDest) {
38
+ if (!fs.existsSync(archiveDest)) {
39
+ throw new Error(lib.projects.archive.errors.archiveNotFound(archiveDest));
40
+ }
41
+ }
42
+ function getMovableRootEntries(projectDir) {
43
+ return fs
44
+ .readdirSync(projectDir)
45
+ .filter(name => name !== ARCHIVE_DIR_NAME && !ROOT_ENTRIES_KEPT_IN_PLACE.has(name));
46
+ }
47
+ function moveEntries(names, fromDir, toDir) {
48
+ const moved = [];
49
+ try {
50
+ names.forEach(name => {
51
+ fs.renameSync(path.join(fromDir, name), path.join(toDir, name));
52
+ moved.push(name);
53
+ });
54
+ }
55
+ catch (error) {
56
+ moved.forEach(name => {
57
+ fs.renameSync(path.join(toDir, name), path.join(fromDir, name));
58
+ });
59
+ throw error;
60
+ }
61
+ return moved;
62
+ }
63
+ function archiveRootEntries(projectDir, archiveDest) {
64
+ fs.mkdirSync(archiveDest);
65
+ try {
66
+ moveEntries(getMovableRootEntries(projectDir), projectDir, archiveDest);
67
+ }
68
+ catch (error) {
69
+ fs.rmdirSync(archiveDest);
70
+ throw error;
71
+ }
72
+ }
73
+ export function moveSourceToProjectArchive(projectDir, srcDir) {
74
+ assertSrcDirOutsideArchive(projectDir, srcDir);
75
+ const archiveDest = getProjectArchiveDest(projectDir);
76
+ if (srcDir === ROOT_SRC_DIR) {
77
+ archiveRootEntries(projectDir, archiveDest);
78
+ return archiveDest;
79
+ }
80
+ fs.renameSync(path.join(projectDir, srcDir), archiveDest);
81
+ return archiveDest;
82
+ }
83
+ function restoreRootEntries(projectDir, archiveDest) {
84
+ getMovableRootEntries(projectDir).forEach(name => {
85
+ fs.rmSync(path.join(projectDir, name), { recursive: true, force: true });
86
+ });
87
+ fs.readdirSync(archiveDest).forEach(name => {
88
+ fs.cpSync(path.join(archiveDest, name), path.join(projectDir, name), {
89
+ recursive: true,
90
+ });
91
+ });
92
+ }
93
+ export function restoreSourceFromProjectArchive(projectDir, srcDir) {
94
+ const archiveDest = getProjectArchiveDest(projectDir);
95
+ assertArchiveExists(archiveDest);
96
+ assertSrcDirOutsideArchive(projectDir, srcDir);
97
+ if (srcDir === ROOT_SRC_DIR) {
98
+ restoreRootEntries(projectDir, archiveDest);
99
+ return;
100
+ }
101
+ const srcPath = path.join(projectDir, srcDir);
102
+ fs.rmSync(srcPath, { recursive: true, force: true });
103
+ fs.cpSync(archiveDest, srcPath, { recursive: true });
104
+ }
@@ -0,0 +1,12 @@
1
+ export declare function getFilesOnlyInArchive(projectDir: string, srcDir: string): Promise<string[]>;
2
+ export declare function writeArchiveDiffFile(archiveDest: string, files: string[]): string;
3
+ type FailedFileCopy = {
4
+ file: string;
5
+ error: unknown;
6
+ };
7
+ type CopyArchivedFilesResult = {
8
+ copiedCount: number;
9
+ failures: FailedFileCopy[];
10
+ };
11
+ export declare function copyArchivedFilesToSource(projectDir: string, srcDir: string, files: string[]): CopyArchivedFilesResult;
12
+ export {};
@@ -0,0 +1,68 @@
1
+ import fs from 'fs';
2
+ import path from 'path';
3
+ import { ARCHIVE_DIR_NAME, ROOT_SRC_DIR, getProjectArchiveDest, } from './archive.js';
4
+ const DIFF_FILE_NAME = 'diff.json';
5
+ const IGNORED_DIR_NAMES = new Set(['node_modules', 'dist', '.git']);
6
+ function toPosixPath(filePath) {
7
+ return filePath.split(path.sep).join('/');
8
+ }
9
+ function isIgnoredDir(entry, { rootDir, currentDir, ignoredRootEntry }) {
10
+ const isIgnoredRootEntry = currentDir === rootDir && entry.name === ignoredRootEntry;
11
+ return isIgnoredRootEntry || IGNORED_DIR_NAMES.has(entry.name);
12
+ }
13
+ async function listEntryFiles(options, entry) {
14
+ const { rootDir, currentDir = rootDir } = options;
15
+ const entryPath = path.join(currentDir, entry.name);
16
+ if (entry.isDirectory() && !isIgnoredDir(entry, { ...options, currentDir })) {
17
+ return listFiles({ ...options, currentDir: entryPath });
18
+ }
19
+ if (entry.isFile()) {
20
+ return [toPosixPath(path.relative(rootDir, entryPath))];
21
+ }
22
+ return [];
23
+ }
24
+ async function listFiles(options) {
25
+ const { rootDir, currentDir = rootDir } = options;
26
+ if (!fs.existsSync(currentDir)) {
27
+ return [];
28
+ }
29
+ const entries = await fs.promises.readdir(currentDir, {
30
+ withFileTypes: true,
31
+ });
32
+ const nestedFiles = await Promise.all(entries.map(entry => listEntryFiles({ ...options, currentDir }, entry)));
33
+ return nestedFiles.flat();
34
+ }
35
+ export async function getFilesOnlyInArchive(projectDir, srcDir) {
36
+ const archiveFiles = await listFiles({
37
+ rootDir: getProjectArchiveDest(projectDir),
38
+ });
39
+ const downloadedFiles = new Set(await listFiles({
40
+ rootDir: path.join(projectDir, srcDir),
41
+ ignoredRootEntry: srcDir === ROOT_SRC_DIR ? ARCHIVE_DIR_NAME : undefined,
42
+ }));
43
+ return archiveFiles.filter(file => !downloadedFiles.has(file)).sort();
44
+ }
45
+ export function writeArchiveDiffFile(archiveDest, files) {
46
+ const diffFilePath = path.join(archiveDest, DIFF_FILE_NAME);
47
+ fs.writeFileSync(diffFilePath, `${JSON.stringify(files, null, 2)}\n`);
48
+ return diffFilePath;
49
+ }
50
+ function copyArchivedFile(archiveDest, srcPath, file) {
51
+ const destination = path.join(srcPath, file);
52
+ fs.mkdirSync(path.dirname(destination), { recursive: true });
53
+ fs.copyFileSync(path.join(archiveDest, file), destination, fs.constants.COPYFILE_EXCL);
54
+ }
55
+ export function copyArchivedFilesToSource(projectDir, srcDir, files) {
56
+ const archiveDest = getProjectArchiveDest(projectDir);
57
+ const srcPath = path.join(projectDir, srcDir);
58
+ const failures = [];
59
+ files.forEach(file => {
60
+ try {
61
+ copyArchivedFile(archiveDest, srcPath, file);
62
+ }
63
+ catch (error) {
64
+ failures.push({ file, error });
65
+ }
66
+ });
67
+ return { copiedCount: files.length - failures.length, failures };
68
+ }
@@ -1,6 +1,6 @@
1
1
  import fs from 'fs-extra';
2
2
  import path from 'path';
3
- import findup from 'findup-sync';
3
+ import { findup } from '@hubspot/local-dev-lib/findup';
4
4
  import { getAbsoluteFilePath, getCwd } from '@hubspot/local-dev-lib/path';
5
5
  import { parseProjectConfig, ProjectConfigValidationError, } from '@hubspot/project-parsing-lib/projects';
6
6
  import { PROJECT_CONFIG_FILE } from '../constants.js';
@@ -0,0 +1,37 @@
1
+ export type LocalProject = {
2
+ projectName: string;
3
+ projectDir: string;
4
+ srcDir: string;
5
+ };
6
+ export type ArchivePlan = {
7
+ projectDir: string;
8
+ srcDir: string;
9
+ archiveDest: string;
10
+ };
11
+ type DownloadDestination = {
12
+ absoluteDestPath: string;
13
+ archivePlan?: ArchivePlan;
14
+ };
15
+ type ResolveDownloadDestinationOptions = {
16
+ projectName: string;
17
+ dest?: string;
18
+ localProject?: LocalProject;
19
+ };
20
+ export declare function getLocalProject(): LocalProject | undefined;
21
+ export declare function resolveDownloadDestination({ projectName, dest, localProject, }: ResolveDownloadDestinationOptions): DownloadDestination;
22
+ export declare function getDisplayPath(absolutePath: string): string;
23
+ export declare function describeArchiveLocation({ archiveDest }: ArchivePlan): string;
24
+ type HandleArchivedSourceOptions = {
25
+ archivePlan: ArchivePlan;
26
+ keepLocalFiles?: boolean;
27
+ canPrompt: boolean;
28
+ };
29
+ export declare function handleArchivedSource({ archivePlan, keepLocalFiles, canPrompt, }: HandleArchivedSourceOptions): Promise<void>;
30
+ type ExtractBuildOptions = {
31
+ zippedProject: Buffer;
32
+ projectName: string;
33
+ absoluteDestPath: string;
34
+ archivePlan?: ArchivePlan;
35
+ };
36
+ export declare function extractBuild({ zippedProject, projectName, absoluteDestPath, archivePlan, }: ExtractBuildOptions): Promise<void>;
37
+ export {};
@@ -0,0 +1,123 @@
1
+ import path from 'path';
2
+ import { getCwd, sanitizeFileName } from '@hubspot/local-dev-lib/path';
3
+ import { extractZipArchive } from '@hubspot/local-dev-lib/archive';
4
+ import { commands } from '../../lang/en.js';
5
+ import { debugError } from '../errorHandlers/index.js';
6
+ import { confirmPrompt } from '../prompts/promptUtils.js';
7
+ import { uiLogger } from '../ui/logger.js';
8
+ import { getIsInProject, getProjectConfig } from './config.js';
9
+ import { getProjectArchiveDest, restoreSourceFromProjectArchive, } from './archive.js';
10
+ import { copyArchivedFilesToSource, getFilesOnlyInArchive, writeArchiveDiffFile, } from './archiveDiff.js';
11
+ const MAX_LISTED_ARCHIVE_ONLY_FILES = 25;
12
+ export function getLocalProject() {
13
+ if (!getIsInProject()) {
14
+ return undefined;
15
+ }
16
+ const { projectConfig, projectDir } = getProjectConfig();
17
+ return {
18
+ projectName: projectConfig.name,
19
+ projectDir,
20
+ srcDir: projectConfig.srcDir,
21
+ };
22
+ }
23
+ export function resolveDownloadDestination({ projectName, dest, localProject, }) {
24
+ if (localProject && !dest && localProject.projectName === projectName) {
25
+ const { projectDir, srcDir } = localProject;
26
+ return {
27
+ absoluteDestPath: projectDir,
28
+ archivePlan: {
29
+ projectDir,
30
+ srcDir,
31
+ archiveDest: getProjectArchiveDest(projectDir),
32
+ },
33
+ };
34
+ }
35
+ const sanitizedProjectName = sanitizeFileName(projectName);
36
+ const absoluteDestPath = dest
37
+ ? path.resolve(getCwd(), dest, sanitizedProjectName)
38
+ : path.resolve(getCwd(), sanitizedProjectName);
39
+ return { absoluteDestPath };
40
+ }
41
+ export function getDisplayPath(absolutePath) {
42
+ return path.relative(getCwd(), absolutePath) || '.';
43
+ }
44
+ export function describeArchiveLocation({ archiveDest }) {
45
+ return commands.project.download.archiveLocation(getDisplayPath(archiveDest));
46
+ }
47
+ function restoreArchivedSource({ projectDir, srcDir, archiveDest, }) {
48
+ try {
49
+ restoreSourceFromProjectArchive(projectDir, srcDir);
50
+ uiLogger.warn(commands.project.download.warnings.sourceRestored);
51
+ }
52
+ catch (error) {
53
+ debugError(error);
54
+ uiLogger.error(commands.project.download.errors.restoreFailed(getDisplayPath(archiveDest)));
55
+ }
56
+ }
57
+ function tryWriteArchiveDiffFile(archiveDest, files) {
58
+ try {
59
+ return writeArchiveDiffFile(archiveDest, files);
60
+ }
61
+ catch (error) {
62
+ debugError(error);
63
+ return undefined;
64
+ }
65
+ }
66
+ async function logFilesOnlyInArchive({ projectDir, srcDir, archiveDest, }) {
67
+ let files;
68
+ try {
69
+ files = await getFilesOnlyInArchive(projectDir, srcDir);
70
+ }
71
+ catch (error) {
72
+ debugError(error);
73
+ return [];
74
+ }
75
+ if (files.length === 0) {
76
+ return [];
77
+ }
78
+ const diffFilePath = tryWriteArchiveDiffFile(archiveDest, files);
79
+ uiLogger.log('');
80
+ uiLogger.log(commands.project.download.logs.filesOnlyInArchive(files.slice(0, MAX_LISTED_ARCHIVE_ONLY_FILES), Math.max(files.length - MAX_LISTED_ARCHIVE_ONLY_FILES, 0), diffFilePath ? getDisplayPath(diffFilePath) : undefined));
81
+ return files;
82
+ }
83
+ async function shouldCopyFilesBack({ files, keepLocalFiles, canPrompt, }) {
84
+ if (keepLocalFiles !== undefined) {
85
+ return keepLocalFiles;
86
+ }
87
+ if (!canPrompt) {
88
+ return false;
89
+ }
90
+ uiLogger.log('');
91
+ return confirmPrompt(commands.project.download.prompts.confirmCopyFilesBack(files.length));
92
+ }
93
+ async function copyFilesBack(options) {
94
+ const { archivePlan, files } = options;
95
+ if (files.length === 0 || !(await shouldCopyFilesBack(options))) {
96
+ return;
97
+ }
98
+ const { projectDir, srcDir } = archivePlan;
99
+ const { copiedCount, failures } = copyArchivedFilesToSource(projectDir, srcDir, files);
100
+ failures.forEach(({ error }) => debugError(error));
101
+ if (copiedCount > 0) {
102
+ uiLogger.success(commands.project.download.logs.filesCopiedBack(copiedCount, getDisplayPath(path.join(projectDir, srcDir))));
103
+ }
104
+ if (failures.length > 0) {
105
+ uiLogger.warn(commands.project.download.warnings.filesNotCopiedBack(failures.length));
106
+ }
107
+ }
108
+ export async function handleArchivedSource({ archivePlan, keepLocalFiles, canPrompt, }) {
109
+ uiLogger.info(commands.project.download.logs.sourceContentsArchived(describeArchiveLocation(archivePlan)));
110
+ const files = await logFilesOnlyInArchive(archivePlan);
111
+ await copyFilesBack({ archivePlan, files, keepLocalFiles, canPrompt });
112
+ }
113
+ export async function extractBuild({ zippedProject, projectName, absoluteDestPath, archivePlan, }) {
114
+ try {
115
+ await extractZipArchive(zippedProject, sanitizeFileName(projectName), absoluteDestPath);
116
+ }
117
+ catch (error) {
118
+ if (archivePlan) {
119
+ restoreArchivedSource(archivePlan);
120
+ }
121
+ throw error;
122
+ }
123
+ }
@@ -7,6 +7,7 @@ const WATCH_EVENTS = {
7
7
  unlink: 'unlink',
8
8
  unlinkDir: 'unlinkDir',
9
9
  };
10
+ const IGNORED_DIRECTORIES = ['dist', 'node_modules'];
10
11
  class LocalDevWatcher {
11
12
  localDevProcess;
12
13
  watcher;
@@ -23,7 +24,7 @@ class LocalDevWatcher {
23
24
  start() {
24
25
  this.watcher = chokidar.watch(this.localDevProcess.projectDir, {
25
26
  ignoreInitial: true,
26
- ignored: ['**/dist', '**/node_modules'],
27
+ ignored: filePath => IGNORED_DIRECTORIES.includes(path.basename(filePath)),
27
28
  });
28
29
  const configPaths = Object.values(this.localDevProcess.projectNodes).map(component => component.localDev.componentConfigPath);
29
30
  const projectConfigPath = path.join(this.localDevProcess.projectDir, PROJECT_CONFIG_FILE);
package/lib/validation.js CHANGED
@@ -2,11 +2,12 @@ import * as fs from 'fs';
2
2
  import * as path from 'path';
3
3
  import { uiLogger } from '../lib/ui/logger.js';
4
4
  import { CMS_PUBLISH_MODE } from '@hubspot/local-dev-lib/constants/files';
5
- import { API_KEY_AUTH_METHOD, OAUTH_AUTH_METHOD, PERSONAL_ACCESS_KEY_AUTH_METHOD, } from '@hubspot/local-dev-lib/constants/auth';
5
+ import { ACCESS_TOKEN_AUTH_METHOD, API_KEY_AUTH_METHOD, OAUTH_AUTH_METHOD, PERSONAL_ACCESS_KEY_AUTH_METHOD, } from '@hubspot/local-dev-lib/constants/auth';
6
6
  import { commaSeparatedValues } from '@hubspot/local-dev-lib/text';
7
7
  import { getConfigFilePath, getConfigAccountById, } from '@hubspot/local-dev-lib/config';
8
8
  import { getOauthManager } from '@hubspot/local-dev-lib/oauth';
9
9
  import { accessTokenForPersonalAccessKey } from '@hubspot/local-dev-lib/personalAccessKey';
10
+ import { accessTokenForInjectedAccessToken } from '@hubspot/local-dev-lib/accessToken';
10
11
  import { getAbsoluteFilePath, getCwd, getExt, } from '@hubspot/local-dev-lib/path';
11
12
  import { ENVIRONMENT_VARIABLES } from '@hubspot/local-dev-lib/constants/config';
12
13
  import { getCmsPublishMode } from './commonOpts.js';
@@ -39,6 +40,7 @@ export async function validateAccount(options) {
39
40
  PERSONAL_ACCESS_KEY_AUTH_METHOD,
40
41
  OAUTH_AUTH_METHOD,
41
42
  API_KEY_AUTH_METHOD,
43
+ ACCESS_TOKEN_AUTH_METHOD,
42
44
  ].map(method => method.value))));
43
45
  }
44
46
  if (authType === 'oauth2') {
@@ -84,6 +86,19 @@ export async function validateAccount(options) {
84
86
  return false;
85
87
  }
86
88
  }
89
+ else if (authType === ACCESS_TOKEN_AUTH_METHOD.value) {
90
+ if (!accountConfig.auth.tokenInfo.accessToken) {
91
+ uiLogger.error(lib.validation.accessTokenMissing(accountId));
92
+ return false;
93
+ }
94
+ try {
95
+ accessTokenForInjectedAccessToken(accountId);
96
+ }
97
+ catch (e) {
98
+ logError(e);
99
+ return false;
100
+ }
101
+ }
87
102
  else if (!accountConfig.apiKey) {
88
103
  uiLogger.error(lib.validation.authConfigurationMissing(accountId));
89
104
  return false;
@@ -10,8 +10,8 @@ declare const inputSchemaZodObject: z.ZodObject<{
10
10
  buildId: z.ZodNumber;
11
11
  logLevel: z.ZodOptional<z.ZodEnum<{
12
12
  ERROR: "ERROR";
13
- WARN: "WARN";
14
13
  ALL: "ALL";
14
+ WARN: "WARN";
15
15
  INFO: "INFO";
16
16
  }>>;
17
17
  }, z.core.$strip>;
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@hubspot/cli",
3
- "version": "8.17.0-beta.0",
3
+ "version": "8.17.0-beta.1",
4
4
  "description": "The official CLI for developing on HubSpot",
5
5
  "license": "Apache-2.0",
6
6
  "repository": "https://github.com/HubSpot/hubspot-cli",
@@ -10,18 +10,17 @@
10
10
  "!**/__tests__/**"
11
11
  ],
12
12
  "dependencies": {
13
- "@hubspot/local-dev-lib": "5.13.0",
14
- "@hubspot/project-parsing-lib": "0.23.6",
13
+ "@hubspot/local-dev-lib": "5.14.0",
14
+ "@hubspot/project-parsing-lib": "0.23.7",
15
15
  "@hubspot/ui-extensions-dev-server": "2.2.2",
16
16
  "@inquirer/prompts": "7.10.1",
17
17
  "@modelcontextprotocol/sdk": "1.32.1",
18
18
  "archiver": "7.0.1",
19
19
  "chalk": "5.6.2",
20
- "chokidar": "3.6.0",
20
+ "chokidar": "4.0.3",
21
21
  "cli-cursor": "3.1.0",
22
22
  "cli-progress": "3.12.0",
23
23
  "express": "4.22.3",
24
- "findup-sync": "4.0.0",
25
24
  "fs-extra": "8.1.0",
26
25
  "ink": "6.8.0",
27
26
  "ink-spinner": "5.0.0",
@@ -47,7 +46,6 @@
47
46
  "@types/archiver": "^6.0.3",
48
47
  "@types/cli-progress": "^3.11.6",
49
48
  "@types/express": "^5.0.0",
50
- "@types/findup-sync": "^4.0.5",
51
49
  "@types/fs-extra": "^11.0.4",
52
50
  "@types/js-yaml": "^4.0.9",
53
51
  "@types/node": "^24.1.0",