# Setup Node.js environment: NVM (preferred), system/fallback Node, NPM global bin, and Yarn _setup_node() { _add_to_path() { [ -d "$1" ] || return 0 case ":$PATH:" in *":$1:"*) ;; *) PATH="$1:$PATH"; export PATH ;; esac } _nvm_active=0 # 1. Check for NVM and prefer NVM node version if [ -z "$NVM_DIR" ]; then if [ -d "$HOME/.nvm" ]; then export NVM_DIR="$HOME/.nvm" elif [ -d "${XDG_CONFIG_HOME:-$HOME/.config}/nvm" ]; then export NVM_DIR="${XDG_CONFIG_HOME:-$HOME/.config}/nvm" elif [ -d "/opt/homebrew/opt/nvm" ]; then export NVM_DIR="/opt/homebrew/opt/nvm" fi fi if [ -n "$NVM_DIR" ] && [ -d "$NVM_DIR" ]; then [ -s "$NVM_DIR/nvm.sh" ] && \. "$NVM_DIR/nvm.sh" [ -s "$NVM_DIR/bash_completion" ] && \. "$NVM_DIR/bash_completion" if command -v nvm >/dev/null 2>&1 || type nvm >/dev/null 2>&1; then nvm use --silent 2>/dev/null || nvm use --silent default 2>/dev/null || nvm use --silent node 2>/dev/null fi if [ -n "$NVM_BIN" ] && [ -d "$NVM_BIN" ]; then _nvm_active=1 fi fi # 2. If NVM is not available or has no active node, fallback to system/global node installs if [ "$_nvm_active" -eq 0 ]; then if ! command -v node >/dev/null 2>&1; then for _node_dir in \ /opt/homebrew/opt/node/bin \ /opt/homebrew/bin \ /usr/local/bin \ /usr/bin \ /usr/local/nodejs/bin \ /usr/local/node/bin \ "$HOME/.local/bin" do if [ -x "$_node_dir/node" ]; then _add_to_path "$_node_dir" break fi done fi fi # 3. Setup NPM global binaries (for system node or custom npm prefix) if [ "$_nvm_active" -eq 0 ] && command -v npm >/dev/null 2>&1; then _npm_prefix="$(npm config get prefix 2>/dev/null || npm prefix -g 2>/dev/null)" if [ -n "$_npm_prefix" ] && [ -d "$_npm_prefix/bin" ]; then _add_to_path "$_npm_prefix/bin" fi unset _npm_prefix elif [ -d "$HOME/.npm-global/bin" ]; then _add_to_path "$HOME/.npm-global/bin" fi # 4. Setup Yarn global bin if yarn is available if command -v yarn >/dev/null 2>&1; then _yarn_bin="$(yarn global bin 2>/dev/null)" if [ -n "$_yarn_bin" ] && [ -d "$_yarn_bin" ]; then _add_to_path "$_yarn_bin" fi unset _yarn_bin fi # 5. Guarantee NVM active node takes precedence over any global node in PATH if [ "$_nvm_active" -eq 1 ] && [ -n "$NVM_BIN" ] && [ -d "$NVM_BIN" ]; then _clean_path=":$PATH:" _clean_path="${_clean_path//:$NVM_BIN:/:}" _clean_path="${_clean_path#:}" _clean_path="${_clean_path%:}" PATH="$NVM_BIN:$_clean_path" export PATH unset _clean_path fi unset _nvm_active } _setup_node unset -f _setup_node _add_to_path