Skip to content

Nx plugin crashes when nx:run-commands target has no options.cwd #1637

@liorp

Description

@liorp

Description

The Nx plugin crashes with TypeError [ERR_INVALID_ARG_TYPE] when a project.json contains nx:run-commands targets that don't specify options.cwd. This is the common case — most projects use nx:run-commands with just options.command.

Reproduction

knip version: 6.0.4

project.json:

{
  "name": "bff",
  "sourceRoot": "apps/bff/src",
  "projectType": "application",
  "targets": {
    "build": {
      "executor": "nx:run-commands",
      "options": {
        "command": "bun build apps/bff/src/index.ts --outdir apps/bff/dist --target bun"
      }
    },
    "serve": {
      "executor": "nx:run-commands",
      "options": {
        "command": "bun run apps/bff/src/index.ts"
      }
    }
  }
}

Run knip in a monorepo with this project.json.

Error

TypeError [ERR_INVALID_ARG_TYPE]: The "from" argument must be of type string. Received undefined
    at Object.relative (node:path:1357:5)
    at relative (knip/dist/util/path.js:18:25)
    at getDependenciesFromScript (knip/dist/binaries/bash-parser.js:140:72)
    at knip/dist/binaries/index.js:6:47
    at Array.flatMap (<anonymous>)
    at getInputsFromScripts (knip/dist/binaries/index.js:6:29)
    at Object.getInputsFromScripts (knip/dist/WorkspaceWorker.js:199:90)
    at knip/dist/plugins/nx/index.js:49:24
    at Array.flatMap (<anonymous>)
    at Object.resolveConfig (knip/dist/plugins/nx/index.js:40:10)

Root Cause

In dist/plugins/nx/index.js:48:

const cwd = target.options?.cwd ? join(options.cwd, target.options.cwd) : undefined;

When target.options.cwd is not set (which is the default for nx:run-commands), cwd becomes undefined. This is passed through getInputsFromScriptsgetDependenciesFromScript → and eventually into path.relative(options.cwd, ...) inside the bash parser's error handler at bash-parser.js:140, which crashes because options.cwd is undefined.

Fix

The fallback should be options.cwd (the project root) instead of undefined:

- const cwd = target.options?.cwd ? join(options.cwd, target.options.cwd) : undefined;
+ const cwd = target.options?.cwd ? join(options.cwd, target.options.cwd) : options.cwd;

This ensures the bash parser always has a valid cwd to resolve paths against, falling back to the workspace root when no explicit cwd is configured on the target.

Workaround

Using bun patch / patch-package to apply the one-line fix above.

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions