From 1effaf012dba9bc50d1cf6a2e4c074af0c2f8942 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Kh=E1=BA=A3i?= Date: Sun, 14 Apr 2024 03:36:31 +0700 Subject: [PATCH] refactor(cli): return type annotations (#7920) --- cli/cli-utils/src/getConfig.ts | 4 +- cli/cli-utils/src/index.ts | 2 +- cli/cli-utils/src/packageIsInstallable.ts | 2 +- cli/cli-utils/src/readDepNameCompletions.ts | 2 +- cli/cli-utils/src/recursiveSummary.ts | 2 +- cli/cli-utils/src/style.ts | 5 ++- cli/default-reporter/src/reportError.ts | 44 ++++++++++--------- .../src/reporterForClient/pkgsDiff.ts | 9 +++- .../reportBigTarballsProgress.ts | 2 +- .../src/reporterForClient/reportContext.ts | 2 +- .../reporterForClient/reportDeprecations.ts | 2 +- .../reporterForClient/reportExecutionTime.ts | 2 +- .../src/reporterForClient/reportHooks.ts | 2 +- .../reporterForClient/reportInstallChecks.ts | 4 +- .../reportLifecycleScripts.ts | 28 ++++++------ .../src/reporterForClient/reportMisc.ts | 9 +++- .../reportPeerDependencyIssues.ts | 2 +- .../src/reporterForClient/reportProgress.ts | 20 ++++++--- .../reporterForClient/reportRequestRetry.ts | 2 +- .../src/reporterForClient/reportScope.ts | 2 +- .../reportSkippedOptionalDependencies.ts | 2 +- .../src/reporterForClient/reportStats.ts | 10 ++--- .../src/reporterForClient/reportSummary.ts | 4 +- .../reporterForClient/reportUpdateCheck.ts | 8 ++-- .../reporterForClient/utils/formatPrefix.ts | 4 +- .../src/reporterForClient/utils/formatWarn.ts | 2 +- .../src/reporterForClient/utils/zooming.ts | 2 +- cli/default-reporter/src/reporterForServer.ts | 4 +- cli/parse-cli-args/src/index.ts | 17 ++++--- 29 files changed, 113 insertions(+), 87 deletions(-) diff --git a/cli/cli-utils/src/getConfig.ts b/cli/cli-utils/src/getConfig.ts index 520aa3050b..c089c16717 100644 --- a/cli/cli-utils/src/getConfig.ts +++ b/cli/cli-utils/src/getConfig.ts @@ -1,5 +1,5 @@ import { packageManager } from '@pnpm/cli-meta' -import { getConfig as _getConfig, type CliOptions } from '@pnpm/config' +import { getConfig as _getConfig, type CliOptions, type Config } from '@pnpm/config' import { formatWarn } from '@pnpm/default-reporter' export async function getConfig ( @@ -11,7 +11,7 @@ export async function getConfig ( workspaceDir: string | undefined checkUnknownSetting?: boolean } -) { +): Promise { const { config, warnings } = await _getConfig({ cliOptions, globalDirShouldAllowWrite: opts.globalDirShouldAllowWrite, diff --git a/cli/cli-utils/src/index.ts b/cli/cli-utils/src/index.ts index c214d7e57b..ba952ca211 100644 --- a/cli/cli-utils/src/index.ts +++ b/cli/cli-utils/src/index.ts @@ -7,7 +7,7 @@ export * from './readProjectManifest' export * from './recursiveSummary' export * from './style' -export const docsUrl = (cmd: string) => { +export function docsUrl (cmd: string): string { const [pnpmMajorVersion] = packageManager.version.split('.') return `https://pnpm.io/${pnpmMajorVersion}.x/cli/${cmd}` } diff --git a/cli/cli-utils/src/packageIsInstallable.ts b/cli/cli-utils/src/packageIsInstallable.ts index e85f6f0b6f..4c29bd5992 100644 --- a/cli/cli-utils/src/packageIsInstallable.ts +++ b/cli/cli-utils/src/packageIsInstallable.ts @@ -19,7 +19,7 @@ export function packageIsInstallable ( nodeVersion?: string supportedArchitectures?: SupportedArchitectures } -) { +): void { const pnpmVersion = packageManager.name === 'pnpm' ? packageManager.version : undefined diff --git a/cli/cli-utils/src/readDepNameCompletions.ts b/cli/cli-utils/src/readDepNameCompletions.ts index d07a2d846f..21cb56f41f 100644 --- a/cli/cli-utils/src/readDepNameCompletions.ts +++ b/cli/cli-utils/src/readDepNameCompletions.ts @@ -1,7 +1,7 @@ import { getAllDependenciesFromManifest } from '@pnpm/manifest-utils' import { readProjectManifest } from '@pnpm/read-project-manifest' -export async function readDepNameCompletions (dir?: string) { +export async function readDepNameCompletions (dir?: string): Promise> { const { manifest } = await readProjectManifest(dir ?? process.cwd()) return Object.keys( getAllDependenciesFromManifest(manifest) diff --git a/cli/cli-utils/src/recursiveSummary.ts b/cli/cli-utils/src/recursiveSummary.ts index e6dcaf61f0..612077c3b1 100644 --- a/cli/cli-utils/src/recursiveSummary.ts +++ b/cli/cli-utils/src/recursiveSummary.ts @@ -25,7 +25,7 @@ class RecursiveFailError extends PnpmError { } } -export function throwOnCommandFail (command: string, recursiveSummary: RecursiveSummary) { +export function throwOnCommandFail (command: string, recursiveSummary: RecursiveSummary): void { const failures = Object.values(recursiveSummary).filter(({ status }) => status === 'failure') as ActionFailure[] if (failures.length > 0) { throw new RecursiveFailError(command, recursiveSummary, failures) diff --git a/cli/cli-utils/src/style.ts b/cli/cli-utils/src/style.ts index 494c536b4c..3cde356083 100644 --- a/cli/cli-utils/src/style.ts +++ b/cli/cli-utils/src/style.ts @@ -24,7 +24,8 @@ export const TABLE_OPTIONS = { columns: {}, } +type BorderKey = keyof typeof TABLE_OPTIONS['border'] + for (const [key, value] of Object.entries(TABLE_OPTIONS.border)) { - // @ts-expect-error - TABLE_OPTIONS.border[key] = chalk.grey(value) + TABLE_OPTIONS.border[key as BorderKey] = chalk.grey(value) } diff --git a/cli/default-reporter/src/reportError.ts b/cli/default-reporter/src/reportError.ts index e0193d3987..7b4eb5f771 100644 --- a/cli/default-reporter/src/reportError.ts +++ b/cli/default-reporter/src/reportError.ts @@ -19,7 +19,7 @@ StackTracey.maxColumnWidths = { const highlight = chalk.yellow const colorPath = chalk.gray -export function reportError (logObj: Log, config?: Config, peerDependencyRules?: PeerDependencyRules) { +export function reportError (logObj: Log, config?: Config, peerDependencyRules?: PeerDependencyRules): string | null { const errorInfo = getErrorInfo(logObj, config, peerDependencyRules) if (!errorInfo) return null let output = formatErrorSummary(errorInfo.title, (logObj as LogObjWithPossibleError).err?.code) @@ -44,10 +44,12 @@ export function reportError (logObj: Log, config?: Config, peerDependencyRules?: } } -function getErrorInfo (logObj: Log, config?: Config, peerDependencyRules?: PeerDependencyRules): { +interface ErrorInfo { title: string body?: string -} | null { +} + +function getErrorInfo (logObj: Log, config?: Config, peerDependencyRules?: PeerDependencyRules): ErrorInfo | null { if (logObj['err']) { const err = logObj['err'] as (PnpmError & { stack: object }) switch (err.code) { @@ -135,7 +137,7 @@ function reportUnexpectedStore ( expectedStorePath: string modulesDir: string } -) { +): ErrorInfo { return { title: err.message, body: `The dependencies at "${msg.modulesDir}" are currently linked from the store at "${msg.expectedStorePath}". @@ -156,7 +158,7 @@ function reportUnexpectedVirtualStoreDir ( expected: string modulesDir: string } -) { +): ErrorInfo { return { title: err.message, body: `The dependencies at "${msg.modulesDir}" are currently symlinked from the virtual store directory at "${msg.expected}". @@ -174,7 +176,7 @@ function reportStoreBreakingChange (msg: { storePath: string relatedIssue?: number relatedPR?: number -}) { +}): ErrorInfo { let output = `Store path: ${colorPath(msg.storePath)} Run "pnpm install" to recreate node_modules.` @@ -195,7 +197,7 @@ function reportModulesBreakingChange (msg: { modulesPath: string relatedIssue?: number relatedPR?: number -}) { +}): ErrorInfo { let output = `node_modules path: ${colorPath(msg.modulesPath)} Run ${highlight('pnpm install')} to recreate node_modules.` @@ -214,7 +216,7 @@ Run ${highlight('pnpm install')} to recreate node_modules.` function formatRelatedSources (msg: { relatedIssue?: number relatedPR?: number -}) { +}): string { let output = '' if (!msg.relatedIssue && !msg.relatedPR) return output @@ -232,7 +234,7 @@ function formatRelatedSources (msg: { return output } -function formatGenericError (errorMessage: string, stack: object) { +function formatGenericError (errorMessage: string, stack: object): ErrorInfo { if (stack) { let prettyStack: string | undefined try { @@ -250,11 +252,11 @@ function formatGenericError (errorMessage: string, stack: object) { return { title: errorMessage } } -function formatErrorSummary (message: string, code?: string) { +function formatErrorSummary (message: string, code?: string): string { return `${chalk.bgRed.black(`\u2009${code ?? 'ERROR'}\u2009`)} ${chalk.red(message)}` } -function reportModifiedDependency (msg: { modified: string[] }) { +function reportModifiedDependency (msg: { modified: string[] }): ErrorInfo { return { title: 'Packages in the store have been mutated', body: `These packages are modified: @@ -264,14 +266,14 @@ You can run ${highlight('pnpm install --force')} to refetch the modified package } } -function reportLockfileBreakingChange (err: Error, msg: object) { +function reportLockfileBreakingChange (err: Error, msg: object): ErrorInfo { return { title: err.message, body: `Run with the ${highlight('--force')} parameter to recreate the lockfile.`, } } -function formatRecursiveCommandSummary (msg: { failures: Array, passes: number }) { +function formatRecursiveCommandSummary (msg: { failures: Array, passes: number }): ErrorInfo { const output = EOL + `Summary: ${chalk.red(`${msg.failures.length} fails`)}, ${msg.passes} passes` + EOL + EOL + msg.failures.map(({ message, prefix }) => { return prefix + ':' + EOL + formatErrorSummary(message) @@ -282,7 +284,7 @@ function formatRecursiveCommandSummary (msg: { failures: Array `hint: ${hint}`).join('\n')} } } -function getHasMissingPeers (issuesByProjects: PeerDependencyIssuesByProjects) { +function getHasMissingPeers (issuesByProjects: PeerDependencyIssuesByProjects): boolean { return Object.values(issuesByProjects) .some((issues) => Object.values(issues.missing).flat().some(({ optional }) => !optional)) } -function reportDedupeCheckIssuesError (err: Error, msg: { dedupeCheckIssues: DedupeCheckIssues }) { +function reportDedupeCheckIssuesError (err: Error, msg: { dedupeCheckIssues: DedupeCheckIssues }): ErrorInfo { return { title: err.message, body: `\ diff --git a/cli/default-reporter/src/reporterForClient/pkgsDiff.ts b/cli/default-reporter/src/reporterForClient/pkgsDiff.ts index 23a9d583e4..9daeb53c50 100644 --- a/cli/default-reporter/src/reporterForClient/pkgsDiff.ts +++ b/cli/default-reporter/src/reporterForClient/pkgsDiff.ts @@ -27,6 +27,13 @@ export const propertyByDependencyType = { prod: 'dependencies', } +export interface PkgsDiff { + dev: Map + nodeModulesOnly: Map + optional: Map + prod: Map +} + export function getPkgsDiff ( log$: { deprecation: Rx.Observable @@ -37,7 +44,7 @@ export function getPkgsDiff ( opts: { prefix: string } -) { +): Rx.Observable { const deprecationSet$ = log$.deprecation .pipe( filter((log) => log.prefix === opts.prefix), diff --git a/cli/default-reporter/src/reporterForClient/reportBigTarballsProgress.ts b/cli/default-reporter/src/reporterForClient/reportBigTarballsProgress.ts index bb08cf2ff0..b369f95463 100644 --- a/cli/default-reporter/src/reporterForClient/reportBigTarballsProgress.ts +++ b/cli/default-reporter/src/reporterForClient/reportBigTarballsProgress.ts @@ -17,7 +17,7 @@ export function reportBigTarballProgress ( log$: { fetchingProgress: Rx.Observable } -) { +): Rx.Observable> { return log$.fetchingProgress.pipe( filter((log: FetchingProgressLog) => log.status === 'started' && typeof log.size === 'number' && log.size >= BIG_TARBALL_SIZE && diff --git a/cli/default-reporter/src/reporterForClient/reportContext.ts b/cli/default-reporter/src/reporterForClient/reportContext.ts index c826eed002..1649f837f6 100644 --- a/cli/default-reporter/src/reporterForClient/reportContext.ts +++ b/cli/default-reporter/src/reporterForClient/reportContext.ts @@ -10,7 +10,7 @@ export function reportContext ( packageImportMethod: Rx.Observable }, opts: { cwd: string } -) { +): Rx.Observable> { return Rx.combineLatest( log$.context.pipe(take(1)), log$.packageImportMethod.pipe(take(1)) diff --git a/cli/default-reporter/src/reporterForClient/reportDeprecations.ts b/cli/default-reporter/src/reporterForClient/reportDeprecations.ts index 0c29f00296..a7932f8d30 100644 --- a/cli/default-reporter/src/reporterForClient/reportDeprecations.ts +++ b/cli/default-reporter/src/reporterForClient/reportDeprecations.ts @@ -14,7 +14,7 @@ export function reportDeprecations ( cwd: string isRecursive: boolean } -) { +): Rx.Observable> { const [deprecatedDirectDeps$, deprecatedSubdeps$] = Rx.partition(log$.deprecation, (log) => log.depth === 0) const resolutionDone$ = log$.stage.pipe( filter((log) => log.stage === 'resolution_done') diff --git a/cli/default-reporter/src/reporterForClient/reportExecutionTime.ts b/cli/default-reporter/src/reporterForClient/reportExecutionTime.ts index 7ccc2594a2..63d12d90d7 100644 --- a/cli/default-reporter/src/reporterForClient/reportExecutionTime.ts +++ b/cli/default-reporter/src/reporterForClient/reportExecutionTime.ts @@ -5,7 +5,7 @@ import { map, take } from 'rxjs/operators' export function reportExecutionTime ( executionTime$: Rx.Observable -) { +): Rx.Observable> { return executionTime$.pipe( take(1), map((log) => { diff --git a/cli/default-reporter/src/reporterForClient/reportHooks.ts b/cli/default-reporter/src/reporterForClient/reportHooks.ts index 323d8a5597..25778de075 100644 --- a/cli/default-reporter/src/reporterForClient/reportHooks.ts +++ b/cli/default-reporter/src/reporterForClient/reportHooks.ts @@ -10,7 +10,7 @@ export function reportHooks ( cwd: string isRecursive: boolean } -) { +): Rx.Observable> { return hook$.pipe( map((log) => Rx.of({ msg: autozoom( diff --git a/cli/default-reporter/src/reporterForClient/reportInstallChecks.ts b/cli/default-reporter/src/reporterForClient/reportInstallChecks.ts index 39fdc67e1a..99cd3330da 100644 --- a/cli/default-reporter/src/reporterForClient/reportInstallChecks.ts +++ b/cli/default-reporter/src/reporterForClient/reportInstallChecks.ts @@ -9,7 +9,7 @@ export function reportInstallChecks ( opts: { cwd: string } -) { +): Rx.Observable> { return installCheck$.pipe( map((log) => formatInstallCheck(opts.cwd, log)), filter(Boolean), @@ -23,7 +23,7 @@ function formatInstallCheck ( opts?: { zoomOutCurrent: boolean } -) { +): string | undefined { const zoomOutCurrent = opts?.zoomOutCurrent ?? false switch (logObj.code) { case 'EBADPLATFORM': diff --git a/cli/default-reporter/src/reporterForClient/reportLifecycleScripts.ts b/cli/default-reporter/src/reporterForClient/reportLifecycleScripts.ts index e11440c6db..cf3731ffe5 100644 --- a/cli/default-reporter/src/reporterForClient/reportLifecycleScripts.ts +++ b/cli/default-reporter/src/reporterForClient/reportLifecycleScripts.ts @@ -32,7 +32,7 @@ export function reportLifecycleScripts ( cwd: string width: number } -) { +): Rx.Observable> { // When the reporter is not append-only, the length of output is limited // in order to reduce flickering if (opts.appendOnly) { @@ -95,7 +95,7 @@ export function reportLifecycleScripts ( return Rx.from(lifecyclePushStream) } -function toNano (time: [number, number]) { +function toNano (time: [number, number]): number { return (time[0] + (time[1] / 1e9)) * 1e3 } @@ -114,7 +114,7 @@ function renderCollapsedScriptOutput ( exit: boolean maxWidth: number } -) { +): string { if (!messageCache.label) { messageCache.label = highlightLastFolder(formatPrefixNoTrim(opts.cwd, log.wd)) if (log.wd.includes(TMP_DIR_IN_STORE)) { @@ -150,7 +150,7 @@ function renderScriptOutput ( exit: boolean maxWidth: number } -) { +): string { updateMessageCache(log, messageCache, opts) if (opts.exit && log['exitCode'] !== 0) { return [ @@ -188,7 +188,7 @@ function updateMessageCache ( exit: boolean maxWidth: number } -) { +): void { if (log['script']) { const prefix = `${formatPrefix(opts.cwd, log.wd)} ${hlValue(log.stage)}` const maxLineWidth = opts.maxWidth - prefix.length - 2 + ANSI_ESCAPES_LENGTH_OF_PREFIX @@ -205,18 +205,18 @@ function updateMessageCache ( } } -function formatIndentedStatus (status: string) { +function formatIndentedStatus (status: string): string { return `${chalk.magentaBright('└─')} ${status}` } -function highlightLastFolder (p: string) { +function highlightLastFolder (p: string): string { const lastSlash = p.lastIndexOf('/') + 1 return `${chalk.gray(p.slice(0, lastSlash))}${p.slice(lastSlash)}` } const ANSI_ESCAPES_LENGTH_OF_PREFIX = hlValue(' ').length - 1 -function createStreamLifecycleOutput (cwd: string, hideLifecyclePrefix: boolean) { +function createStreamLifecycleOutput (cwd: string, hideLifecyclePrefix: boolean): (logObj: LifecycleLog) => string { currentColor = 0 const colorByPrefix: ColorByPkg = new Map() return streamLifecycleOutput.bind(null, colorByPrefix, cwd, hideLifecyclePrefix) @@ -227,7 +227,7 @@ function streamLifecycleOutput ( cwd: string, hideLifecyclePrefix: boolean, logObj: LifecycleLog -) { +): string { const prefix = formatLifecycleScriptPrefix(colorByPkg, cwd, logObj.wd, logObj.stage) if (typeof logObj['exitCode'] === 'number') { if (logObj['exitCode'] === 0) { @@ -243,7 +243,7 @@ function streamLifecycleOutput ( return hideLifecyclePrefix ? line : `${prefix}: ${line}` } -function formatIndentedOutput (maxWidth: number, logObj: LifecycleLog) { +function formatIndentedOutput (maxWidth: number, logObj: LifecycleLog): string { return `${chalk.magentaBright('│')} ${formatLine(maxWidth - 2, logObj)}` } @@ -252,7 +252,7 @@ function formatLifecycleScriptPrefix ( cwd: string, wd: string, stage: string -) { +): string { if (!colorByPkg.has(wd)) { const colorName = colorWheel[currentColor % NUM_COLORS] colorByPkg.set(wd, chalk[colorName]) @@ -263,7 +263,7 @@ function formatLifecycleScriptPrefix ( return `${color(formatPrefix(cwd, wd))} ${hlValue(stage)}` } -function formatLine (maxWidth: number, logObj: LifecycleLog) { +function formatLine (maxWidth: number, logObj: LifecycleLog): string { const line = cutLine(logObj['line'], maxWidth) // TODO: strip only the non-color/style ansi escape codes @@ -273,12 +273,12 @@ function formatLine (maxWidth: number, logObj: LifecycleLog) { return line } -function cutLine (line: string, maxLength: number) { +function cutLine (line: string, maxLength: number): string { if (!line) return '' // This actually should never happen but it is better to be safe return cliTruncate(line, maxLength) } -function aggregateOutput (source: Rx.Observable) { +function aggregateOutput (source: Rx.Observable): Rx.Observable { return source.pipe( // The '\0' is a null character which delimits these strings. This works since JS doesn't use // null-terminated strings. diff --git a/cli/default-reporter/src/reporterForClient/reportMisc.ts b/cli/default-reporter/src/reporterForClient/reportMisc.ts index 67eb8bc637..1ae0e8f5eb 100644 --- a/cli/default-reporter/src/reporterForClient/reportMisc.ts +++ b/cli/default-reporter/src/reporterForClient/reportMisc.ts @@ -33,7 +33,7 @@ export function reportMisc ( zoomOutCurrent: boolean peerDependencyRules?: PeerDependencyRules } -) { +): Rx.Observable> { const maxLogLevel = LOG_LEVEL_NUMBER[opts.logLevel ?? 'info'] ?? LOG_LEVEL_NUMBER['info'] const reportWarning = makeWarningReporter(opts) return Rx.merge(log$.registry, log$.other).pipe( @@ -61,6 +61,11 @@ export function reportMisc ( ) } +type WarningReporter = (obj: { + prefix: string + message: string +}) => Rx.Observable<{ msg: string }> + // Sometimes, when installing new dependencies that rely on many peer dependencies, // or when running installation on a huge monorepo, there will be hundreds or thousands of warnings. // Printing many messages to the terminal is expensive and reduces speed, @@ -71,7 +76,7 @@ function makeWarningReporter ( cwd: string zoomOutCurrent: boolean } -) { +): WarningReporter { let warningsCounter = 0 let collapsedWarnings: Rx.Subject<{ msg: string }> return (obj: { prefix: string, message: string }) => { diff --git a/cli/default-reporter/src/reporterForClient/reportPeerDependencyIssues.ts b/cli/default-reporter/src/reporterForClient/reportPeerDependencyIssues.ts index 10d0d7c7d8..ae67d23592 100644 --- a/cli/default-reporter/src/reporterForClient/reportPeerDependencyIssues.ts +++ b/cli/default-reporter/src/reporterForClient/reportPeerDependencyIssues.ts @@ -10,7 +10,7 @@ export function reportPeerDependencyIssues ( peerDependencyIssues: Rx.Observable }, peerDependencyRules?: PeerDependencyRules -) { +): Rx.Observable> { return log$.peerDependencyIssues.pipe( take(1), map((log) => { diff --git a/cli/default-reporter/src/reporterForClient/reportProgress.ts b/cli/default-reporter/src/reporterForClient/reportProgress.ts index 9a462d15d5..19b4cbdd59 100644 --- a/cli/default-reporter/src/reporterForClient/reportProgress.ts +++ b/cli/default-reporter/src/reporterForClient/reportProgress.ts @@ -17,6 +17,12 @@ interface ModulesInstallProgress { requirer: string } +export interface StatusMessage { + msg: string + fixed: boolean + done?: boolean +} + export function reportProgress ( log$: { progress: Rx.Observable @@ -29,7 +35,7 @@ export function reportProgress ( hideAddedPkgsProgress?: boolean hideProgressPrefix?: boolean } -) { +): Rx.Observable> { const progressOutput = throttledProgressOutput.bind(null, opts) return getModulesInstallProgress$(log$.stage, log$.progress).pipe( @@ -42,7 +48,7 @@ export function reportProgress ( return output$ } return output$.pipe( - map((msg: any) => { // eslint-disable-line @typescript-eslint/no-explicit-any + map((msg) => { msg['msg'] = zoomOut(opts.cwd, requirer, msg['msg']) return msg }) @@ -59,7 +65,7 @@ function throttledProgressOutput ( }, importingDone$: Rx.Observable, progress$: Rx.Observable -) { +): Rx.Observable { if (opts.throttle != null) { progress$ = progress$.pipe(opts.throttle) } @@ -107,7 +113,7 @@ function getModulesInstallProgress$ ( return Rx.from(modulesInstallProgressPushStream) } -function stage$ToImportingDone$ (stage$: Rx.Observable) { +function stage$ToImportingDone$ (stage$: Rx.Observable): Rx.Observable { return stage$ .pipe( filter((log: StageLog) => log.stage === 'importing_done'), @@ -117,7 +123,7 @@ function stage$ToImportingDone$ (stage$: Rx.Observable) { ) } -function getProgressStatsPushStreamByRequirer (progress$: Rx.Observable) { +function getProgressStatsPushStreamByRequirer (progress$: Rx.Observable): { [requirer: string]: Rx.Subject } { const progressStatsPushStreamByRequirer: { [requirer: string]: Rx.Subject } = {} @@ -157,7 +163,7 @@ function getProgressStatsPushStreamByRequirer (progress$: Rx.Observable -) { +): Rx.Observable> { return requestRetry$.pipe( map((log) => { const retriesLeft = log.maxRetries - log.attempt + 1 diff --git a/cli/default-reporter/src/reporterForClient/reportScope.ts b/cli/default-reporter/src/reporterForClient/reportScope.ts index 324f0bfed7..817bfdf1b3 100644 --- a/cli/default-reporter/src/reporterForClient/reportScope.ts +++ b/cli/default-reporter/src/reporterForClient/reportScope.ts @@ -20,7 +20,7 @@ export function reportScope ( isRecursive: boolean cmd: string } -) { +): Rx.Observable> { if (!COMMANDS_THAT_REPORT_SCOPE.has(opts.cmd)) { return Rx.NEVER } diff --git a/cli/default-reporter/src/reporterForClient/reportSkippedOptionalDependencies.ts b/cli/default-reporter/src/reporterForClient/reportSkippedOptionalDependencies.ts index bf1890e88f..7820a4279e 100644 --- a/cli/default-reporter/src/reporterForClient/reportSkippedOptionalDependencies.ts +++ b/cli/default-reporter/src/reporterForClient/reportSkippedOptionalDependencies.ts @@ -7,7 +7,7 @@ export function reportSkippedOptionalDependencies ( opts: { cwd: string } -) { +): Rx.Observable> { return skippedOptionalDependency$.pipe( filter((log) => Boolean(log['prefix'] === opts.cwd && log.parents && log.parents.length === 0)), map((log) => Rx.of({ diff --git a/cli/default-reporter/src/reporterForClient/reportStats.ts b/cli/default-reporter/src/reporterForClient/reportStats.ts index 6c7145fd04..25b03993aa 100644 --- a/cli/default-reporter/src/reporterForClient/reportStats.ts +++ b/cli/default-reporter/src/reporterForClient/reportStats.ts @@ -22,7 +22,7 @@ export function reportStats ( width: number hideProgressPrefix?: boolean } -) { +): Array>> { if (opts.hideProgressPrefix) { return [statsForCurrentPackage(log$.stats, { cmd: opts.cmd, @@ -59,7 +59,7 @@ function statsForCurrentPackage ( cmd: string width: number } -) { +): Rx.Observable> { return stats$.pipe( take((opts.cmd === 'install' || opts.cmd === 'install-test' || opts.cmd === 'add' || opts.cmd === 'update' || opts.cmd === 'dlx') ? 2 : 1), reduce((acc, log) => { @@ -98,7 +98,7 @@ function statsForNotCurrentPackage ( currentPrefix: string width: number } -) { +): Rx.Observable> { const stats = {} const cookedStats$ = ( opts.cmd !== 'remove' @@ -146,7 +146,7 @@ function statsForNotCurrentPackage ( ) } -function padStep (s: string, step: number) { +function padStep (s: string, step: number): string { const sLength = stringLength(s) const placeholderLength = Math.ceil(sLength / step) * step if (sLength < placeholderLength) { @@ -160,7 +160,7 @@ function roundStats (stat: number): number { return Math.max(1, Math.round(stat / 10)) } -function printPlusesAndMinuses (maxWidth: number, added: number, removed: number) { +function printPlusesAndMinuses (maxWidth: number, added: number, removed: number): string { if (maxWidth === 0) return '' const changes = added + removed let addedChars: number diff --git a/cli/default-reporter/src/reporterForClient/reportSummary.ts b/cli/default-reporter/src/reporterForClient/reportSummary.ts index 35c945229b..9e76237dc5 100644 --- a/cli/default-reporter/src/reporterForClient/reportSummary.ts +++ b/cli/default-reporter/src/reporterForClient/reportSummary.ts @@ -41,7 +41,7 @@ export function reportSummary ( filterPkgsDiff?: FilterPkgsDiff pnpmConfig?: Config } -) { +): Rx.Observable> { const pkgsDiff$ = getPkgsDiff(log$, { prefix: opts.cwd }) const summaryLog$ = log$.summary.pipe(take(1)) @@ -96,7 +96,7 @@ function printDiffs ( }, pkgsDiff: PackageDiff[], depType: string -) { +): string { // Sorts by alphabet then by removed/added // + ava 0.10.0 // - chalk 1.0.0 diff --git a/cli/default-reporter/src/reporterForClient/reportUpdateCheck.ts b/cli/default-reporter/src/reporterForClient/reportUpdateCheck.ts index 8dae969ba1..7e685d5de1 100644 --- a/cli/default-reporter/src/reporterForClient/reportUpdateCheck.ts +++ b/cli/default-reporter/src/reporterForClient/reportUpdateCheck.ts @@ -8,7 +8,7 @@ import semver from 'semver' export function reportUpdateCheck (log$: Rx.Observable, opts: { env: NodeJS.ProcessEnv process: NodeJS.Process -}) { +}): Rx.Observable> { return log$.pipe( take(1), filter((log) => semver.gt(log.latestVersion, log.currentVersion)), @@ -44,7 +44,7 @@ interface UpdateMessageOptions { latestVersion: string } -function renderUpdateMessage (opts: UpdateMessageOptions) { +function renderUpdateMessage (opts: UpdateMessageOptions): string { if (opts.currentPkgIsExecutable && opts.env.PNPM_HOME) { return 'Run a script from: https://pnpm.io/installation' } @@ -52,7 +52,7 @@ function renderUpdateMessage (opts: UpdateMessageOptions) { return `Run "${chalk.magenta(updateCommand)}" to update.` } -function renderUpdateCommand (opts: UpdateMessageOptions) { +function renderUpdateCommand (opts: UpdateMessageOptions): string { if (opts.env.COREPACK_ROOT) { return `corepack prepare pnpm@${opts.latestVersion} --activate` } @@ -60,6 +60,6 @@ function renderUpdateCommand (opts: UpdateMessageOptions) { return `pnpm add -g ${pkgName}` } -function detectIfCurrentPkgIsExecutable (process: NodeJS.Process) { +function detectIfCurrentPkgIsExecutable (process: NodeJS.Process): boolean { return process['pkg'] != null } diff --git a/cli/default-reporter/src/reporterForClient/utils/formatPrefix.ts b/cli/default-reporter/src/reporterForClient/utils/formatPrefix.ts index cc10c2e2a5..f1ef15b145 100644 --- a/cli/default-reporter/src/reporterForClient/utils/formatPrefix.ts +++ b/cli/default-reporter/src/reporterForClient/utils/formatPrefix.ts @@ -2,7 +2,7 @@ import path from 'path' import normalize from 'normalize-path' import { PREFIX_MAX_LENGTH } from '../outputConstants' -export function formatPrefix (cwd: string, prefix: string) { +export function formatPrefix (cwd: string, prefix: string): string { prefix = formatPrefixNoTrim(cwd, prefix) if (prefix.length <= PREFIX_MAX_LENGTH) { @@ -20,6 +20,6 @@ export function formatPrefix (cwd: string, prefix: string) { return `...${shortPrefix.slice(separatorLocation)}` } -export function formatPrefixNoTrim (cwd: string, prefix: string) { +export function formatPrefixNoTrim (cwd: string, prefix: string): string { return normalize(path.relative(cwd, prefix) || '.') } diff --git a/cli/default-reporter/src/reporterForClient/utils/formatWarn.ts b/cli/default-reporter/src/reporterForClient/utils/formatWarn.ts index 913d19eead..6ce6c1be35 100644 --- a/cli/default-reporter/src/reporterForClient/utils/formatWarn.ts +++ b/cli/default-reporter/src/reporterForClient/utils/formatWarn.ts @@ -1,6 +1,6 @@ import chalk from 'chalk' -export function formatWarn (message: string) { +export function formatWarn (message: string): string { // The \u2009 is the "thin space" unicode character // It is used instead of ' ' because chalk (as of version 2.1.0) // trims whitespace at the beginning diff --git a/cli/default-reporter/src/reporterForClient/utils/zooming.ts b/cli/default-reporter/src/reporterForClient/utils/zooming.ts index 9cc7352e8e..52a492de8d 100644 --- a/cli/default-reporter/src/reporterForClient/utils/zooming.ts +++ b/cli/default-reporter/src/reporterForClient/utils/zooming.ts @@ -9,7 +9,7 @@ export function autozoom ( opts: { zoomOutCurrent: boolean } -) { +): string { if (!logPrefix || !opts.zoomOutCurrent && currentPrefix === logPrefix) { return line } diff --git a/cli/default-reporter/src/reporterForServer.ts b/cli/default-reporter/src/reporterForServer.ts index cc4fce6c69..b2ad97c718 100644 --- a/cli/default-reporter/src/reporterForServer.ts +++ b/cli/default-reporter/src/reporterForServer.ts @@ -7,7 +7,7 @@ import { reportError } from './reportError' export function reporterForServer ( log$: Rx.Observable, config?: Config -) { +): Rx.Subscription { return log$.subscribe({ complete: () => undefined, error: () => undefined, @@ -32,7 +32,7 @@ export function reporterForServer ( }) } -function formatWarn (message: string) { +function formatWarn (message: string): string { // The \u2009 is the "thin space" unicode character // It is used instead of ' ' because chalk (as of version 2.1.0) // trims whitespace at the beginning diff --git a/cli/parse-cli-args/src/index.ts b/cli/parse-cli-args/src/index.ts index 206a63c3a8..d301d05958 100644 --- a/cli/parse-cli-args/src/index.ts +++ b/cli/parse-cli-args/src/index.ts @@ -64,7 +64,7 @@ export async function parseCliArgs ( return getParsedArgsForHelp() } - function getParsedArgsForHelp () { + function getParsedArgsForHelp (): ParsedCliArgs { return { argv: noptExploratoryResults.argv, cmd: 'help', @@ -80,7 +80,7 @@ export async function parseCliArgs ( ...opts.getTypesByCommandName(commandName), } as any // eslint-disable-line @typescript-eslint/no-explicit-any - function getCommandName (args: string[]) { + function getCommandName (args: string[]): string { if (recursiveCommandUsed) { args = args.slice(1) } @@ -90,7 +90,7 @@ export async function parseCliArgs ( return 'add' } - function getEscapeArgsWithSpecialCaseForRun () { + function getEscapeArgsWithSpecialCaseForRun (): string[] | undefined { if (cmd !== 'run') { return opts.escapeArgs } @@ -184,7 +184,12 @@ export async function parseCliArgs ( const CUSTOM_OPTION_PREFIX = 'config.' -function normalizeOptions (options: Record, knownOptions: Set) { +interface NormalizeOptionsResult { + options: Record + unknownOptions: Map +} + +function normalizeOptions (options: Record, knownOptions: Set): NormalizeOptionsResult { const standardOptionNames = [] const normalizedOptions: Record = {} for (const [optionName, optionValue] of Object.entries(options)) { @@ -199,7 +204,7 @@ function normalizeOptions (options: Record, knownOptions: Set) { +function getUnknownOptions (usedOptions: string[], knownOptions: Set): Map { const unknownOptions = new Map() const closestMatches = getClosestOptionMatches.bind(null, Array.from(knownOptions)) for (const usedOption of usedOptions) { @@ -210,7 +215,7 @@ function getUnknownOptions (usedOptions: string[], knownOptions: Set) { return unknownOptions } -function getClosestOptionMatches (knownOptions: string[], option: string) { +function getClosestOptionMatches (knownOptions: string[], option: string): string[] { return didYouMean(option, knownOptions, { returnType: ReturnTypeEnums.ALL_CLOSEST_MATCHES, })