Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
49 changes: 49 additions & 0 deletions packages/nuxi/src/commands/module/_utils.ts
Original file line number Diff line number Diff line change
@@ -1,7 +1,19 @@
import type { PackageManager } from 'nypm'
import type { PackageJson } from 'pkg-types'

import { existsSync } from 'node:fs'

import { confirm, isCancel } from '@clack/prompts'
import { parseINI } from 'confbox'
import { colors } from 'consola/utils'
import { $fetch } from 'ofetch'
import { resolve } from 'pathe'
import { satisfies } from 'semver'

import { logger } from '../../utils/logger'
import { relativeToProcess } from '../../utils/paths'
import { cwdArgs, logLevelArgs } from '../_shared'

export const categories = [
'Analytics',
'CMS',
Expand Down Expand Up @@ -136,3 +148,40 @@ export function getRegistryFromContent(content: string, scope: string | null) {
return null
}
}

export function getProjectDependencies(projectPkg: PackageJson): Set<string> {
return new Set([
...Object.keys(projectPkg.dependencies || {}),
...Object.keys(projectPkg.devDependencies || {}),
])
}

/**
* Warn and prompt to continue when the project has no `nuxt` dependency.
* Returns `false` if the user declines or cancels.
*/
export async function ensureNuxtDependency(cwd: string, projectPkg: PackageJson): Promise<boolean> {
if (projectPkg.dependencies?.nuxt || projectPkg.devDependencies?.nuxt) {
return true
}

logger.warn(`No ${colors.cyan('nuxt')} dependency detected in ${colors.cyan(relativeToProcess(cwd))}.`)

const shouldContinue = await confirm({
message: `Do you want to continue anyway?`,
initialValue: false,
})

return !isCancel(shouldContinue) && shouldContinue === true
}

export function isPnpmWorkspace(packageManager: PackageManager | undefined, cwd: string): boolean {
return packageManager?.name === 'pnpm' && existsSync(resolve(cwd, 'pnpm-workspace.yaml'))
}

/** Forward `cwd` and log-level args to a chained command invocation. */
export function forwardCommandArgs(args: Record<string, unknown>): string[] {
return Object.entries(args)
.filter(([k]) => k in cwdArgs || k in logLevelArgs)
.map(([k, v]) => `--${k}=${v}`)
Comment on lines +183 to +186

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

⚠️ Potential issue | 🟡 Minor | ⚡ Quick win

Avoid forwarding undefined/null option values in chained args.

forwardCommandArgs currently serializes absent values into flags like --logLevel=undefined, which can leak invalid values into runCommand(...) invocations.

Suggested patch
 export function forwardCommandArgs(args: Record<string, unknown>): string[] {
   return Object.entries(args)
-    .filter(([k]) => k in cwdArgs || k in logLevelArgs)
-    .map(([k, v]) => `--${k}=${v}`)
+    .filter(([k, v]) =>
+      (Object.prototype.hasOwnProperty.call(cwdArgs, k)
+        || Object.prototype.hasOwnProperty.call(logLevelArgs, k))
+      && v !== undefined
+      && v !== null,
+    )
+    .map(([k, v]) => `--${k}=${String(v)}`)
 }
🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@packages/nuxi/src/commands/module/_utils.ts` around lines 183 - 186, The
forwardCommandArgs function currently serializes undefined and null values into
command flags like --logLevel=undefined, which is invalid. Add an additional
filter condition in the chain to exclude entries where the value (v) is
undefined or null before the map operation that formats the arguments as
strings. This ensures only valid option values are forwarded to runCommand
invocations.

}
28 changes: 6 additions & 22 deletions packages/nuxi/src/commands/module/add.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,6 @@ import type { PackageJson } from 'pkg-types'

import type { NuxtModule } from './_utils'
import * as fs from 'node:fs'
import { existsSync } from 'node:fs'
import { homedir } from 'node:os'
import { join } from 'node:path'
import process from 'node:process'
Expand All @@ -21,12 +20,11 @@ import { joinURL } from 'ufo'

import { runCommand } from '../../run'
import { logger } from '../../utils/logger'
import { relativeToProcess } from '../../utils/paths'
import { getNuxtVersion } from '../../utils/versions'
import { cwdArgs, logLevelArgs } from '../_shared'
import prepareCommand from '../prepare'
import { selectModulesAutocomplete } from './_autocomplete'
import { checkNuxtCompatibility, fetchModules, getRegistryFromContent } from './_utils'
import { checkNuxtCompatibility, ensureNuxtDependency, fetchModules, forwardCommandArgs, getProjectDependencies, getRegistryFromContent, isPnpmWorkspace } from './_utils'

const PROTOCOL_RE = /^https?:\/\//
const TRAILING_SLASH_RE = /\/$/
Expand Down Expand Up @@ -76,17 +74,8 @@ export default defineCommand({
let modules = ctx.args._.map(e => e.trim()).filter(Boolean)
const projectPkg = await readPackageJSON(cwd).catch(() => ({} as PackageJson))

if (!projectPkg.dependencies?.nuxt && !projectPkg.devDependencies?.nuxt) {
logger.warn(`No ${colors.cyan('nuxt')} dependency detected in ${colors.cyan(relativeToProcess(cwd))}.`)

const shouldContinue = await confirm({
message: `Do you want to continue anyway?`,
initialValue: false,
})

if (isCancel(shouldContinue) || shouldContinue !== true) {
process.exit(1)
}
if (!await ensureNuxtDependency(cwd, projectPkg)) {
process.exit(1)
}

// If no modules specified, show interactive search
Expand Down Expand Up @@ -137,9 +126,7 @@ export default defineCommand({

// Run prepare command if install is not skipped
if (!ctx.args.skipInstall) {
const args = Object.entries(ctx.args).filter(([k]) => k in cwdArgs || k in logLevelArgs).map(([k, v]) => `--${k}=${v}`)

await runCommand(prepareCommand, args)
await runCommand(prepareCommand, forwardCommandArgs(ctx.args))
}
},
})
Expand All @@ -151,10 +138,7 @@ async function addModules(modules: ResolvedModule[], { skipInstall = false, skip
const installedModules: ResolvedModule[] = []
const notInstalledModules: ResolvedModule[] = []

const dependencies = new Set([
...Object.keys(projectPkg.dependencies || {}),
...Object.keys(projectPkg.devDependencies || {}),
])
const dependencies = getProjectDependencies(projectPkg)

for (const module of modules) {
if (dependencies.has(module.pkgName)) {
Expand Down Expand Up @@ -186,7 +170,7 @@ async function addModules(modules: ResolvedModule[], { skipInstall = false, skip
dev: isDev,
installPeerDependencies: true,
packageManager,
workspace: packageManager?.name === 'pnpm' && existsSync(resolve(cwd, 'pnpm-workspace.yaml')),
workspace: isPnpmWorkspace(packageManager, cwd),
}).then(() => true).catch(
async (error) => {
logger.error(String(error))
Expand Down
1 change: 1 addition & 0 deletions packages/nuxi/src/commands/module/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,7 @@ export default defineCommand({
args: {},
subCommands: {
add: () => import('./add').then(r => r.default || r),
remove: () => import('./remove').then(r => r.default || r),
search: () => import('./search').then(r => r.default || r),
},
})
Loading
Loading