1:   2:   3:   4:   5:   6:   7:   8:   9:  10:  11:  12:  13:  14:  15:  16:  17:  18:  19:  20:  21:  22:  23:  24:  25:  26:  27:  28:  29:  30:  31:  32:  33:  34:  35:  36:  37:  38:  39:  40:  41:  42:  43:  44:  45:  46:  47:  48:  49:  50:  51:  52:  53:  54:  55:  56:  57:  58:  59:  60:  61:  62:  63:  64:  65:  66:  67:  68:  69:  70:  71:  72:  73:  74:  75:  76:  77:  78:  79:  80:  81:  82:  83:  84:  85:  86:  87:  88:  89:  90:  91:  92:  93:  94:  95:  96:  97:  98:  99: 100: 101: 102: 103: 104: 105: 106: 107: 108: 109: 110: 111: 112: 113: 114: 115: 116: 117: 118: 119: 120: 121: 122: 123: 124: 125: 126: 127: 128: 129: 130: 131: 132: 133: 134: 135: 136: 137: 138: 139: 140: 141: 142: 143: 144: 145: 146: 147: 148: 149: 150: 151: 152: 153: 154: 155: 156: 157: 158: 159: 160: 161: 162: 163: 164: 165: 166: 167: 168: 169: 170: 171: 172: 173: 174: 175: 176: 177: 178: 179: 180: 181: 182: 183: 184: 185: 186: 187: 188: 189: 190: 191: 192: 193: 194: 195: 196: 197: 198: 199: 200: 201: 202: 203: 204: 205: 206: 207: 208: 209: 210: 211: 212: 213: 214: 215: 216: 217: 218: 219: 220: 221: 222: 223: 224: 225: 226: 227: 228: 229: 230: 231: 232: 233: 234: 235: 236: 237: 238: 239: 240: 241: 242: 243: 244: 245: 246: 247: 248: 249: 250: 251: 252: 253: 254: 255: 256: 257: 258: 259: 260: 261: 262: 263: 264: 265: 266: 267: 268: 269: 270: 271: 272: 273: 274: 275: 276: 277: 278: 279: 280: 281: 282: 283: 284: 285: 286: 
<?php
    declare(strict_types=1);
    /**
     *  +------------------------------------------------------------+
     *  | apnscp                                                     |
     *  +------------------------------------------------------------+
     *  | Copyright (c) Apis Networks                                |
     *  +------------------------------------------------------------+
     *  | Licensed under Artistic License 2.0                        |
     *  +------------------------------------------------------------+
     *  | Author: Matt Saladna (msaladna@apisnetworks.com)           |
     *  +------------------------------------------------------------+
     */

    use Opcenter\Versioning;

    /**
     * Manage and install Node versions
     *
     * @package core
     */
    class Node_Module extends Module_Skeleton
    {
        const NVM_LOCATION = FILESYSTEM_SHARED . '/node/nvm/nvm-exec';

        protected $exportedFunctions = [
            '*' => PRIVILEGE_SITE | PRIVILEGE_USER
        ];

        /**
         * void __construct(void)
         *
         * @ignore
         */
        public function __construct()
        {
            if (!platform_is('6.5')) {
                $this->exportedFunctions = [];
            }
            parent::__construct();
        }

        /**
         * Execute Node within the scope of a version
         *
         * @param null|string $version
         * @param string      $command
         * @param array       $args optional command arguments
         * @return array process output from pman_run
         */
        public function do(?string $version, string $command, ...$args): array
        {
            if ($version === 'lts') {
                $version = '--lts';
            } else if ($version) {
                $version = escapeshellarg($version);
            }
            $ret = $this->exec('exec --silent ' . $version, $command, ...$args);

            return $ret;
        }

        /**
         * nvm wrapper
         *
         * @param null|string $name
         * @param null|string $command
         * @param array       $args optional args
         * @return array
         */
        private function exec(?string $name, string $command = null, ...$args): array
        {
            $ret = $this->pman_run('/bin/bash -ic -- ' . escapeshellarg("nvm ${name} ${command}"),
                $args,
                [
                    'PATH'     => '/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin' . PATH_SEPARATOR . '~/node_modules/.bin',
                    'BASH_ENV' => '/dev/null'
                ]
            );

            return $ret;
        }

        /**
         * Remove an installed Node
         *
         * @param string $version
         * @return bool
         */
        public function uninstall(string $version): bool
        {
            if ($version === 'lts') {
                $version = '--lts';
            }
            $ret = $this->exec('uninstall', $version);
            if (!$ret['success']) {
                return error('failed to uninstall Node %s: %s',
                    $version,
                    coalesce($ret['stderr'], $ret['stdout'])
                );
            }

            return true;
        }

        /**
         * Assign Node version to directory
         *
         * Resolves symbolic names to version number
         *
         * @param string $version
         * @param string $path
         * @return bool
         */
        public function make_default(string $version, string $path = '~'): bool
        {
            $path .= '/.nvmrc';
            if ($version === 'lts') {
                $version = 'lts/*';
            }

            return $this->file_put_file_contents($path, $this->resolveVersion($version), true);
        }

        /**
         * Get Node version for a path
         *
         * @param string $path
         * @return string|null
         */
        public function get_default(string $path): ?string
        {
            $path .= '/.nvmrc';
            if (!$this->file_exists($path)) {
                return null;
            }

            return $this->file_get_file_contents($path);
        }

        /**
         * Resolve Node alias to version number
         *
         * @param string $version
         * @return null|string
         */
        protected function resolveVersion(string $version): ?string
        {
            if ($version === 'lts') {
                $version = 'lts/*';
            }
            $ret = $this->exec('ls', '%s', $version);
            if ($ret['success']) {
                return trim(preg_replace('/^\S+\s+|\bv(?=\d)|\s+\*$/', '', $ret['output']));
            }

            return null;
        }

        /**
         * Get installed LTS version for account
         *
         * @param string $alias Node release alias (argon, boron, carbon, dubnium, etc)
         * @return null|string
         */
        public function lts_version(string $alias = '*'): ?string
        {
            return $this->resolveVersion('lts/' . $alias);
        }

        /**
         * Install Node
         *
         * @param string $version
         * @return bool
         */
        public function install(string $version): bool
        {
            if ($version === 'lts') {
                $version = '--lts';
            }
            $ret = $this->exec('install', $version);
            if (!$ret['success']) {
                return error('failed to install Node %s, error: %s',
                    $version,
                    coalesce($ret['stderr'], $ret['stdout'])
                );
            }

            return true;
        }

        /**
         * Node version is installed
         *
         * @param string $version
         * @return bool
         */
        public function installed(string $version): bool
        {
            if ($version === 'lts') {
                return $this->lts_installed();
            }
            $nodes = $this->list();
            foreach ($nodes as $alias => $localVersion) {
                if ($alias === $version) {
                    return true;
                }

                if ($version === $localVersion ||
                    (false !== strpos($localVersion, '.') && Versioning::compare($version, $localVersion, '=')))
                {
                    return true;
                }
            }
            return false;
        }

        /**
         * Latest LTS is installed
         *
         * @return bool
         */
        public function lts_installed(): bool
        {
            $versions = $this->list();
            $lts = $versions['lts/*'] ?? null;

            return array_has($versions, $lts);
        }

        /**
         * List installed Nodes
         *
         * @return array
         */
        public function list(): array
        {
            // 3 = no nodes installed
            $ret = $this->exec('ls');
            if (!$ret['success']) {
                if ($ret['return'] !== 3) {
                    error('failed to query nodes - is nvm installed? error: %s', $ret['error']);
                }

                return [];
            }
            if (preg_match_all(\Regex::NVM_NODES, $ret['output'], $versions, PREG_SET_ORDER)) {
                $nodes = array_combine(array_column($versions, 'alias'), array_column($versions, 'version'));
                if (isset($nodes['->'])) {
                    $nodes['active'] = $nodes['->'];
                    unset($nodes['->']);
                }

                return $nodes;
            }

            return [];
        }

        public function get_available(): array
        {
            $cache = \Cache_Super_Global::spawn();
            $key = 'node.rem';
            if (false !== ($res = $cache->get($key))) {
                return $res;
            }
            $ret = $this->exec('ls-remote');
            if (!$ret['success']) {
                error('failed to query remote Node versions: %s', coalesce($ret['stderr'], $ret['stdout']));

                return [];
            }

            if (!preg_match_all('/\s*v(?<version>\S*)\s*(?:\((?:Latest )?LTS: (\S*)\))?/', $ret['stdout'], $versions,
                PREG_SET_ORDER)) {
                warn('failed to discover any Nodes');

                return [];
            }
            $versions = array_column($versions, 'version');
            $cache->set($key, $versions);

            return $versions;
        }
    }