"use strict";Object.defineProperty(exports, "__esModule", { value: true });exports.registerMissingPlatformEngines = exports.registerEngineExtension = exports.registerEngine = exports.registerAllPlatformEngines = exports.loadEngines = exports.loadEnginePluginDeps = exports.loadEnginePackageDeps = exports.hasEngineTask = exports.getRegisteredEngines = exports.getPlatformExtensions = exports.getEngineTask = exports.getEngineSubTasks = exports.getEngineRunnerByPlatform = exports.getEngineRunner = exports.generateEnvVars = exports.generateEngineTasks = exports.generateEngineExtensions = exports.configureEngines = void 0;
var _path = _interopRequireDefault(require("path"));
var _fileutils = require("../systemManager/fileutils");
var _npmUtils = require("../systemManager/npmUtils");
var _constants = require("../constants");
var _logger = require("../systemManager/logger");
var _common = require("../common");
var _resolve = require("../systemManager/resolve");
var _utils = require("../systemManager/utils");
var _configManager = require("../configManager");
var _pluginManager = require("../pluginManager");function _interopRequireDefault(obj) {return obj && obj.__esModule ? obj : { "default": obj };}function ownKeys(object, enumerableOnly) {var keys = Object.keys(object);if (Object.getOwnPropertySymbols) {var symbols = Object.getOwnPropertySymbols(object);enumerableOnly && (symbols = symbols.filter(function (sym) {return Object.getOwnPropertyDescriptor(object, sym).enumerable;})), keys.push.apply(keys, symbols);}return keys;}function _objectSpread(target) {for (var i = 1; i < arguments.length; i++) {var source = null != arguments[i] ? arguments[i] : {};i % 2 ? ownKeys(Object(source), !0).forEach(function (key) {_defineProperty(target, key, source[key]);}) : Object.getOwnPropertyDescriptors ? Object.defineProperties(target, Object.getOwnPropertyDescriptors(source)) : ownKeys(Object(source)).forEach(function (key) {Object.defineProperty(target, key, Object.getOwnPropertyDescriptor(source, key));});}return target;}function _defineProperty(obj, key, value) {if (key in obj) {Object.defineProperty(obj, key, { value: value, enumerable: true, configurable: true, writable: true });} else {obj[key] = value;}return obj;}function _toConsumableArray(arr) {return _arrayWithoutHoles(arr) || _iterableToArray(arr) || _unsupportedIterableToArray(arr) || _nonIterableSpread();}function _nonIterableSpread() {throw new TypeError("Invalid attempt to spread non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.");}function _unsupportedIterableToArray(o, minLen) {if (!o) return;if (typeof o === "string") return _arrayLikeToArray(o, minLen);var n = Object.prototype.toString.call(o).slice(8, -1);if (n === "Object" && o.constructor) n = o.constructor.name;if (n === "Map" || n === "Set") return Array.from(o);if (n === "Arguments" || /^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n)) return _arrayLikeToArray(o, minLen);}function _iterableToArray(iter) {if (typeof Symbol !== "undefined" && iter[Symbol.iterator] != null || iter["@@iterator"] != null) return Array.from(iter);}function _arrayWithoutHoles(arr) {if (Array.isArray(arr)) return _arrayLikeToArray(arr);}function _arrayLikeToArray(arr, len) {if (len == null || len > arr.length) len = arr.length;for (var i = 0, arr2 = new Array(len); i < len; i++) {arr2[i] = arr[i];}return arr2;}function asyncGeneratorStep(gen, resolve, reject, _next, _throw, key, arg) {try {var info = gen[key](arg);var value = info.value;} catch (error) {reject(error);return;}if (info.done) {resolve(value);} else {Promise.resolve(value).then(_next, _throw);}}function _asyncToGenerator(fn) {return function () {var self = this,args = arguments;return new Promise(function (resolve, reject) {var gen = fn.apply(self, args);function _next(value) {asyncGeneratorStep(gen, resolve, reject, _next, _throw, "next", value);}function _throw(err) {asyncGeneratorStep(gen, resolve, reject, _next, _throw, "throw", err);}_next(undefined);});};}

var ENGINE_CORE = 'engine-core';

var registerEngine = /*#__PURE__*/function () {var _ref = _asyncToGenerator( /*#__PURE__*/regeneratorRuntime.mark(function _callee(c, engine, platform, engConfig) {return regeneratorRuntime.wrap(function _callee$(_context) {while (1) {switch (_context.prev = _context.next) {case 0:
            (0, _logger.logTask)("registerEngine:".concat(engine.config.id));
            c.runtime.enginesById[engine.config.id] = engine;
            engine.initializeRuntimeConfig(c);
            c.runtime.enginesByIndex.push(engine);
            if (engConfig !== null && engConfig !== void 0 && engConfig.packageName) {
              engine.rootPath = _resolvePkgPath(c, engConfig.packageName);
              engine.originalTemplatePlatformsDir = _path["default"].join(engine.rootPath, 'templates/platforms');
              engine.originalTemplateAssetsDir = _path["default"].join(engine.rootPath, 'templates/assets');
              engine.originalTemplatePlatformProjectDir = _path["default"].join(
              engine.originalTemplatePlatformsDir,
              engine.projectDirName);

            }
            _registerEnginePlatform(c, platform, engine);case 6:case "end":return _context.stop();}}}, _callee);}));return function registerEngine(_x, _x2, _x3, _x4) {return _ref.apply(this, arguments);};}();exports.registerEngine = registerEngine;


var _registerEnginePlatform = function _registerEnginePlatform(c, platform, engine) {
  if (platform) {
    c.runtime.enginesByPlatform[platform] = engine;
  }
};

var registerEngineExtension = function registerEngineExtension(ext, eExt) {var extras = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : [];
  var e1 = ext ? "".concat(ext, ".") : '';
  var e2 = eExt ? "".concat(eExt, ".") : '';
  var extArr;
  if (eExt) {
    extArr = ["".concat(
    e1).concat(e2, "jsx"), "".concat(e1, "jsx"), "".concat(e1).concat(e2, "js"), "".concat(e1, "js"), "".concat(
    e1).concat(e2, "tsx"), "".concat(e1, "tsx"), "".concat(e1).concat(e2, "ts"), "".concat(e1, "ts")].concat(_toConsumableArray(
    extras));

  } else {
    extArr = ["".concat(
    e1, "jsx"), "".concat(e1, "js"), "".concat(
    e1, "tsx"), "".concat(e1, "ts")].concat(_toConsumableArray(
    extras));

  }

  return extArr;
};exports.registerEngineExtension = registerEngineExtension;

var generateEngineExtensions = function generateEngineExtensions(exts, config) {
  var id = config.id,engineExtension = config.engineExtension;
  var extArr = _toConsumableArray(registerEngineExtension(id));
  exts.forEach(function (ext) {
    extArr = extArr.concat(registerEngineExtension(ext, engineExtension));
  });
  extArr = extArr.concat(registerEngineExtension(null, null, ['mjs', 'json', 'wasm']));
  return extArr;
};exports.generateEngineExtensions = generateEngineExtensions;

var generateEngineTasks = function generateEngineTasks(taskArr) {
  var tasks = {};
  taskArr.forEach(function (taskInstance) {
    tasks[taskInstance.task] = taskInstance;
  });
  return tasks;
};exports.generateEngineTasks = generateEngineTasks;

var configureEngines = /*#__PURE__*/function () {var _ref2 = _asyncToGenerator( /*#__PURE__*/regeneratorRuntime.mark(function _callee2(c) {var engines, devDependencies, needsPackageUpdate;return regeneratorRuntime.wrap(function _callee2$(_context2) {while (1) {switch (_context2.prev = _context2.next) {case 0:
            (0, _logger.logTask)('configureEngines');if (!
            c.runtime.isWrapper) {_context2.next = 3;break;}return _context2.abrupt("return", true);case 3:
            engines = c.files.project.config.engines;
            devDependencies = c.files.project["package"].devDependencies;
            needsPackageUpdate = false;
            if (engines && !c.runtime.skipPackageUpdate && !c.program.skipDependencyCheck && !c.program.skipRnvCheck) {
              Object.keys(engines).forEach(function (k) {var _c$buildConfig$engine, _c$buildConfig$engine2;
                var engVer = (_c$buildConfig$engine = c.buildConfig.engineTemplates) === null || _c$buildConfig$engine === void 0 ? void 0 : (_c$buildConfig$engine2 = _c$buildConfig$engine[k]) === null || _c$buildConfig$engine2 === void 0 ? void 0 : _c$buildConfig$engine2.version;
                if (engVer) {
                  if (devDependencies[k]) {
                    if (devDependencies[k] !== engVer) {
                      needsPackageUpdate = true;
                      (0, _logger.logInfo)("Updating missing engine ".concat(k, " ").concat(
                      (0, _logger.chalk)().red(devDependencies[k]), "=>").concat((0, _logger.chalk)().green(engVer), " to package.json"));
                      devDependencies[k] = engVer;
                    }
                  } else {
                    needsPackageUpdate = true;
                    (0, _logger.logInfo)("Adding missing engine ".concat(k, "@").concat(engVer, " to package.json"));
                    devDependencies[k] = engVer;
                  }
                }
              });
              if (needsPackageUpdate) {
                (0, _fileutils.writeFileSync)(c.paths.project["package"], c.files.project["package"]);
              }
            }return _context2.abrupt("return",
            true);case 8:case "end":return _context2.stop();}}}, _callee2);}));return function configureEngines(_x5) {return _ref2.apply(this, arguments);};}();exports.configureEngines = configureEngines;


var registerMissingPlatformEngines = /*#__PURE__*/function () {var _ref3 = _asyncToGenerator( /*#__PURE__*/regeneratorRuntime.mark(function _callee3(c, taskInstance) {var _taskInstance$platfor;var registerEngineList;return regeneratorRuntime.wrap(function _callee3$(_context3) {while (1) {switch (_context3.prev = _context3.next) {case 0:
            (0, _logger.logTask)('registerMissingPlatformEngines');if (!(
            !taskInstance || !taskInstance.isGlobalScope && (taskInstance === null || taskInstance === void 0 ? void 0 : (_taskInstance$platfor = taskInstance.platforms) === null || _taskInstance$platfor === void 0 ? void 0 : _taskInstance$platfor.length) === 0)) {_context3.next = 7;break;}
            registerEngineList = [];
            c.buildConfig.defaults.supportedPlatforms.forEach(function (platform) {
              registerEngineList.push(
              _registerPlatformEngine(c, platform));

            });if (!

            registerEngineList.length) {_context3.next = 7;break;}_context3.next = 7;return (
              Promise.all(registerEngineList));case 7:return _context3.abrupt("return",



            true);case 8:case "end":return _context3.stop();}}}, _callee3);}));return function registerMissingPlatformEngines(_x6, _x7) {return _ref3.apply(this, arguments);};}();exports.registerMissingPlatformEngines = registerMissingPlatformEngines;


var registerAllPlatformEngines = /*#__PURE__*/function () {var _ref4 = _asyncToGenerator( /*#__PURE__*/regeneratorRuntime.mark(function _callee4(c) {var _c$buildConfig, _c$buildConfig$defaul, _c$buildConfig$defaul2;var registerEngineList;return regeneratorRuntime.wrap(function _callee4$(_context4) {while (1) {switch (_context4.prev = _context4.next) {case 0:
            (0, _logger.logTask)('registerAllPlatformEngines');if ((_c$buildConfig =
            c.buildConfig) !== null && _c$buildConfig !== void 0 && (_c$buildConfig$defaul = _c$buildConfig.defaults) !== null && _c$buildConfig$defaul !== void 0 && (_c$buildConfig$defaul2 = _c$buildConfig$defaul.supportedPlatforms) !== null && _c$buildConfig$defaul2 !== void 0 && _c$buildConfig$defaul2.forEach) {_context4.next = 4;break;}
            c.runtime.hasAllEnginesRegistered = true;return _context4.abrupt("return",
            true);case 4:

            registerEngineList = [];
            c.buildConfig.defaults.supportedPlatforms.forEach(function (platform) {
              registerEngineList.push(
              _registerPlatformEngine(c, platform));

            });if (!

            registerEngineList.length) {_context4.next = 9;break;}_context4.next = 9;return (
              Promise.all(registerEngineList));case 9:

            c.runtime.hasAllEnginesRegistered = true;return _context4.abrupt("return",
            true);case 11:case "end":return _context4.stop();}}}, _callee4);}));return function registerAllPlatformEngines(_x8) {return _ref4.apply(this, arguments);};}();exports.registerAllPlatformEngines = registerAllPlatformEngines;


var loadEnginePluginDeps = /*#__PURE__*/function () {var _ref5 = _asyncToGenerator( /*#__PURE__*/regeneratorRuntime.mark(function _callee5(c, engineConfigs) {var addedPlugins;return regeneratorRuntime.wrap(function _callee5$(_context5) {while (1) {switch (_context5.prev = _context5.next) {case 0:
            (0, _logger.logTask)('loadEnginePluginDeps');
            // Check engine dependencies
            addedPlugins = [];
            engineConfigs.forEach(function (ecf) {
              var engineConfig = (0, _fileutils.readObjectSync)(ecf.configPath);

              if (engineConfig !== null && engineConfig !== void 0 && engineConfig.plugins) {
                var projectPlugins = c.files.project.config.plugins;
                Object.keys(engineConfig === null || engineConfig === void 0 ? void 0 : engineConfig.plugins).forEach(function (k) {
                  if (!projectPlugins[k]) {
                    (0, _logger.logInfo)("Engine ".concat(ecf.key, " requires plugin ").concat(k, ". ADDING...DONE"));
                    projectPlugins[k] = engineConfig === null || engineConfig === void 0 ? void 0 : engineConfig.plugins[k];
                    addedPlugins.push(k);
                  }
                });
                if (addedPlugins.length > 0) {
                  (0, _configManager.writeRenativeConfigFile)(c, c.paths.project.config, c.files.project.config);
                }
                //
              }
            });return _context5.abrupt("return",
            addedPlugins.length);case 4:case "end":return _context5.stop();}}}, _callee5);}));return function loadEnginePluginDeps(_x9, _x10) {return _ref5.apply(this, arguments);};}();exports.loadEnginePluginDeps = loadEnginePluginDeps;


var loadEnginePackageDeps = /*#__PURE__*/function () {var _ref6 = _asyncToGenerator( /*#__PURE__*/regeneratorRuntime.mark(function _callee6(c, engineConfigs) {var addedDeps;return regeneratorRuntime.wrap(function _callee6$(_context6) {while (1) {switch (_context6.prev = _context6.next) {case 0:
            (0, _logger.logTask)('loadEnginePackageDeps');
            // Check engine dependencies
            addedDeps = [];
            engineConfigs.forEach(function (ecf) {
              var engineConfig = (0, _fileutils.readObjectSync)(ecf.configPath);
              c.buildConfig.defaults.supportedPlatforms.forEach(function (platform) {var _engineConfig$platfor, _engineConfig$platfor2;
                var npm = engineConfig === null || engineConfig === void 0 ? void 0 : (_engineConfig$platfor = engineConfig.platforms) === null || _engineConfig$platfor === void 0 ? void 0 : (_engineConfig$platfor2 = _engineConfig$platfor[platform]) === null || _engineConfig$platfor2 === void 0 ? void 0 : _engineConfig$platfor2.npm;
                if (npm) {
                  if (npm.devDependencies) {
                    var deps = c.files.project["package"].devDependencies || {};
                    Object.keys(npm.devDependencies).forEach(function (k) {
                      if (!deps[k]) {
                        (0, _logger.logInfo)("Engine ".concat(ecf.key, " requires npm devDependency ").concat(
                        k, " for platform ").concat(platform, ". ADDING...DONE"));
                        deps[k] = npm === null || npm === void 0 ? void 0 : npm.devDependencies[k];
                        addedDeps.push(k);
                      }
                    });
                    c.files.project["package"].devDependencies = deps;
                  }
                  if (npm.dependencies) {
                    var _deps = c.files.project["package"].dependencies || {};
                    Object.keys(npm.dependencies).forEach(function (k) {
                      if (!_deps[k]) {
                        (0, _logger.logInfo)("Engine ".concat(ecf.key, " requires npm dependency ").concat(
                        k, " for platform ").concat(platform, ". ADDING...DONE"));
                        _deps[k] = npm === null || npm === void 0 ? void 0 : npm.dependencies[k];
                        addedDeps.push(k);
                      }
                    });
                    c.files.project["package"].dependencies = _deps;
                  }
                  if (npm.optionalDependencies) {
                    var _deps2 = c.files.project["package"].optionalDependencies || {};
                    Object.keys(npm.optionalDependencies).forEach(function (k) {
                      if (!_deps2[k]) {
                        (0, _logger.logInfo)("Engine ".concat(ecf.key, " requires npm optionalDependency ").concat(
                        k, " for platform ").concat(platform, ". ADDING...DONE"));
                        _deps2[k] = npm === null || npm === void 0 ? void 0 : npm.optionalDependencies[k];
                        addedDeps.push(k);
                      }
                    });
                    c.files.project["package"].optionalDependencies = _deps2;
                  }

                  if (addedDeps.length > 0) {
                    (0, _fileutils.writeFileSync)(c.paths.project["package"], c.files.project["package"]);
                  }
                  //
                }
              });
            });
            // if (addedDeps.length > 0) {
            //     await installPackageDependencies(c);
            // }
            return _context6.abrupt("return", addedDeps.length);case 4:case "end":return _context6.stop();}}}, _callee6);}));return function loadEnginePackageDeps(_x11, _x12) {return _ref6.apply(this, arguments);};}();exports.loadEnginePackageDeps = loadEnginePackageDeps;


var loadEngines = /*#__PURE__*/function () {var _ref7 = _asyncToGenerator( /*#__PURE__*/regeneratorRuntime.mark(function _callee7(c, failOnMissingDeps) {var _c$buildConfig2;var engines, enginesToInstall, readyEngines, engineConfigs, plugDepsCount, pkgDepsCount;return regeneratorRuntime.wrap(function _callee7$(_context7) {while (1) {switch (_context7.prev = _context7.next) {case 0:
            (0, _logger.logTask)('loadEngines');
            engines = (_c$buildConfig2 = c.buildConfig) === null || _c$buildConfig2 === void 0 ? void 0 : _c$buildConfig2.engines;
            // c.runtime.engineConfigs = {};
            enginesToInstall = [];
            readyEngines = [];
            engineConfigs = [];if (!
            engines) {_context7.next = 34;break;}
            Object.keys(engines).forEach(function (k) {
              var engineRootPath = (0, _resolve.doResolve)(k);
              var configPath = engineRootPath ? _path["default"].join(engineRootPath, 'renative.engine.json') : null;
              if (!configPath || !(0, _fileutils.fsExistsSync)(configPath)) {
                var engVer = (0, _utils.getScopedVersion)(c, k, engines[k], 'engineTemplates');
                if (engVer) {
                  enginesToInstall.push({
                    key: k,
                    version: engVer,
                    engineRootPath: engineRootPath });

                }
              } else {
                readyEngines.push(k);
                engineConfigs.push({
                  key: k,
                  engineRootPath: engineRootPath,
                  configPath: configPath });

              }
            });if (!


            enginesToInstall.length) {_context7.next = 17;break;}if (!
            failOnMissingDeps) {_context7.next = 10;break;}return _context7.abrupt("return",
            Promise.reject("Failed to load some engines:\n".concat(
            enginesToInstall.map(function (v) {return "> ".concat(v.key, "@").concat(v.version, " path: ").concat(v.engineRootPath);}).join('\n'))));case 10:

            (0, _logger.logInfo)("Some engines not installed in your project:\n".concat(
            enginesToInstall.map(function (v) {return "> ".concat(v.key, "@").concat(v.version);}).join('\n'), "\n ADDING TO PACKAGE.JSON...DONE"));_context7.next = 13;return (


              (0, _npmUtils.checkAndCreateProjectPackage)(c));case 13:
            enginesToInstall.forEach(function (v) {
              c.files.project["package"].devDependencies[v.key] = v.version;
              (0, _fileutils.writeFileSync)(c.paths.project["package"], c.files.project["package"]);
            });_context7.next = 16;return (
              (0, _npmUtils.installPackageDependencies)(c));case 16:return _context7.abrupt("return",
            loadEngines(c, true));case 17:if (

            c.runtime.isWrapper) {_context7.next = 31;break;}_context7.next = 20;return (
              loadEnginePluginDeps(c, engineConfigs));case 20:plugDepsCount = _context7.sent;_context7.next = 23;return (
              loadEnginePackageDeps(c, engineConfigs));case 23:pkgDepsCount = _context7.sent;if (!(

            plugDepsCount + pkgDepsCount > 0)) {_context7.next = 31;break;}
            c.runtime._skipPluginScopeWarnings = true;_context7.next = 28;return (
              (0, _pluginManager.configurePlugins)(c, true));case 28: // TODO: This is too early as scoped plugin have not been installed
            c.runtime._skipPluginScopeWarnings = false;_context7.next = 31;return (
              (0, _npmUtils.installPackageDependencies)(c));case 31:




            // All engines ready to be registered
            _registerPlatformEngine(c, c.platform);_context7.next = 40;break;case 34:if (!
            c.files.project.config) {_context7.next = 40;break;}
            (0, _logger.logInfo)('Engine configs missing in your renative.json. FIXING...DONE');
            c.files.project.config.engines = {
              '@rnv/engine-rn': 'source:rnv',
              '@rnv/engine-rn-web': 'source:rnv',
              '@rnv/engine-rn-next': 'source:rnv',
              '@rnv/engine-rn-electron': 'source:rnv',
              '@rnv/engine-lightning': 'source:rnv',
              '@rnv/engine-rn-macos': 'source:rnv' };

            // TODO: use parseRenativeConfigs instead
            c.buildConfig.engines = c.files.project.config.engines;

            (0, _fileutils.writeFileSync)(c.paths.project.config, c.files.project.config);return _context7.abrupt("return",
            loadEngines(c));case 40:return _context7.abrupt("return",

            true);case 41:case "end":return _context7.stop();}}}, _callee7);}));return function loadEngines(_x13, _x14) {return _ref7.apply(this, arguments);};}();exports.loadEngines = loadEngines;


var _getMergedEngineConfigs = function _getMergedEngineConfigs(c) {var _c$buildConfig3, _c$buildConfig4;
  var engines = (_c$buildConfig3 = c.buildConfig) === null || _c$buildConfig3 === void 0 ? void 0 : _c$buildConfig3.engines;
  var engineTemplates = (_c$buildConfig4 = c.buildConfig) === null || _c$buildConfig4 === void 0 ? void 0 : _c$buildConfig4.engineTemplates;
  var mergedEngineConfigs = {};
  Object.keys(engineTemplates).forEach(function (packageName) {
    mergedEngineConfigs[packageName] = _objectSpread({
      packageName: packageName },
    engineTemplates[packageName]);

  });

  var engineTemplatesKeys = Object.keys(engineTemplates);
  if (engines) {
    Object.keys(engines).forEach(function (enginePackageName) {
      var engineVal = engines[enginePackageName];
      if (engineVal === 'source:rnv') {
        if (!engineTemplatesKeys.includes(enginePackageName)) {
          (0, _logger.logWarning)("Engine ".concat(enginePackageName, " not found in default engineTemplates"));
        }
      } else {
        mergedEngineConfigs[enginePackageName] = engineVal;
      }
    });
  }
  return mergedEngineConfigs;
};

var _getEngineConfigByPlatform = function _getEngineConfigByPlatform(c, platform) {
  var mergedEngineConfigs = _getMergedEngineConfigs(c);
  var engineId = c.program.engine || (0, _common.getConfigProp)(c, platform, 'engine');
  var selectedEngineConfig;
  Object.values(mergedEngineConfigs).forEach(function (engineConfig) {
    if (engineConfig.id === engineId) {
      selectedEngineConfig = engineConfig;
    }
  });

  return selectedEngineConfig;
};

var _resolvePkgPath = function _resolvePkgPath(c, packageName) {
  if (_constants.IS_LINKED) {
    // In the instances of running linked rnv instead of installed one load local packages
    try {
      var pkgPathLocal = require.resolve(packageName, { paths: [_path["default"].join(_constants.RNV_HOME_DIR, '..')] });
      pkgPathLocal = pkgPathLocal.replace('/dist/index.js', '').replace('\\dist\\index.js', '');
      return pkgPathLocal;
    } catch (_unused) {
      (0, _logger.logInfo)("Running local rnv but did not find linked ".concat(packageName, ". moving on..."));
    }
  }
  var pkgPath = _path["default"].join(c.paths.project.dir, 'node_modules', packageName);
  if ((0, _fileutils.fsExistsSync)(pkgPath)) {
    return pkgPath;
  }
  var monoRoot = (0, _common.getConfigProp)(c, c.platform, 'monoRoot');
  pkgPath = _path["default"].join(c.paths.project.dir, monoRoot || '../..', 'node_modules', packageName);
  if ((0, _fileutils.fsExistsSync)(pkgPath)) {
    return pkgPath;
  }
  pkgPath = require.resolve(packageName);

  return pkgPath;
};


var _registerPlatformEngine = function _registerPlatformEngine(c, platform) {
  // Only register active platform engine to be faster
  if (platform === true || !platform) return;
  var selectedEngineConfig = _getEngineConfigByPlatform(c, platform);
  if (selectedEngineConfig) {
    var existingEngine = c.runtime.enginesById[selectedEngineConfig.id];
    if (!existingEngine) {var _require;
      // if (IS_LINKED) {
      //     // In the instances of running linked rnv instead of installed one load local packages
      //     const pth = require.resolve(selectedEngineConfig.packageName, { paths: [path.join(RNV_HOME_DIR, '..')] });
      //     registerEngine(c, require(
      //         pth
      //     )?.default, platform, selectedEngineConfig);
      // } else {
      //     registerEngine(c, require(
      //         _resolvePkgPath(c, selectedEngineConfig.packageName)
      //     )?.default,
      //     platform, selectedEngineConfig);
      // }
      registerEngine(c, (_require = require(
      _resolvePkgPath(c, selectedEngineConfig.packageName))) === null || _require === void 0 ? void 0 : _require["default"],

      platform, selectedEngineConfig);
    } else {
      _registerEnginePlatform(c, platform, existingEngine);
    }
  } else if (platform !== true && platform) {
    (0, _logger.logWarning)("Could not find suitable engine for platform ".concat(platform, "\nMaybe you forgot to define platforms.").concat(
    platform, ".engine in your renative.json?"));
  }
};

var generateEnvVars = function generateEnvVars(c, moduleConfig, nextConfig) {
  var isMonorepo = (0, _common.getConfigProp)(c, c.platform, 'isMonorepo');
  var monoRoot = (0, _common.getConfigProp)(c, c.platform, 'monoRoot');

  return {
    RNV_EXTENSIONS: getPlatformExtensions(c),
    RNV_MODULE_PATHS: (moduleConfig === null || moduleConfig === void 0 ? void 0 : moduleConfig.modulePaths) || [],
    RNV_MODULE_ALIASES: (moduleConfig === null || moduleConfig === void 0 ? void 0 : moduleConfig.moduleAliasesArray) || [],
    RNV_NEXT_TRANSPILE_MODULES: nextConfig,
    RNV_PROJECT_ROOT: c.paths.project.dir,
    RNV_APP_BUILD_DIR: (0, _common.getAppFolder)(c),
    RNV_IS_MONOREPO: isMonorepo,
    RNV_MONO_ROOT: c.runtime.isWrapper || isMonorepo ? _path["default"].join(c.paths.project.dir, monoRoot || '../..') : c.paths.project.dir,
    RNV_ENGINE: c.runtime.engine.config.id,
    RNV_IS_NATIVE_TV: [_constants.TVOS, _constants.ANDROID_TV, _constants.FIRE_TV].includes(c.platform) };

};exports.generateEnvVars = generateEnvVars;

var getPlatformExtensions = function getPlatformExtensions(c) {var excludeServer = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : false;var addDotPrefix = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : false;
  var engine = c.runtime.engine;
  var output;
  var platforms = engine.platforms;

  if (addDotPrefix) {
    output = platforms[c.platform].extenstions.map(function (v) {return ".".concat(v);}).filter(function (ext) {return !excludeServer || !ext.includes('server.');});
  } else {
    output = platforms[c.platform].extenstions.filter(function (ext) {return !excludeServer || !ext.includes('server.');});
  }
  return output;
};exports.getPlatformExtensions = getPlatformExtensions;

var getEngineRunnerByPlatform = function getEngineRunnerByPlatform(c, platform, ignoreMissingError) {
  var selectedEngine = c.runtime.enginesByPlatform[platform];
  if (!selectedEngine && !ignoreMissingError) {
    (0, _logger.logDebug)("ERROR: Engine for platform: ".concat(platform, " does not exists or is not registered ").concat(new Error()));
    // logRaw(new Error());
  }
  return selectedEngine;
};exports.getEngineRunnerByPlatform = getEngineRunnerByPlatform;

var getEngineTask = function getEngineTask(task, tasks, customTasks) {
  var customTask = customTasks === null || customTasks === void 0 ? void 0 : customTasks[task];
  if (customTask) return customTask;
  var tsk;
  var taskCleaned = task.split(' ')[0];
  tsk = tasks[task];
  if (!tsk) {
    tsk = tasks[taskCleaned];
  }
  return tsk;
};exports.getEngineTask = getEngineTask;

var hasEngineTask = function hasEngineTask(task, tasks, isProjectScope) {var _getEngineTask;return (
    isProjectScope ? !!getEngineTask(task, tasks) : (_getEngineTask = getEngineTask(task, tasks)) === null || _getEngineTask === void 0 ? void 0 : _getEngineTask.isGlobalScope);};exports.hasEngineTask = hasEngineTask;

var getEngineSubTasks = function getEngineSubTasks(task, tasks, exactMatch) {return Object.values(tasks).filter(function (v) {return exactMatch ? v.task.split(' ')[0] === task : v.task.startsWith(task);});};exports.getEngineSubTasks = getEngineSubTasks;

var getEngineRunner = function getEngineRunner(c, task, customTasks) {var failOnMissingEngine = arguments.length > 3 && arguments[3] !== undefined ? arguments[3] : true;
  if (customTasks !== null && customTasks !== void 0 && customTasks[task]) {
    return c.runtime.enginesById[ENGINE_CORE];
  }

  var configExists = c.paths.project.configExists;
  var engine = c.runtime.enginesByPlatform[c.platform];
  if (!engine) {
    engine = c.runtime.enginesById['engine-core'];
  }
  if (!engine) {
    if (hasEngineTask(task, c.runtime.enginesById[ENGINE_CORE].tasks, configExists)) {
      return c.runtime.enginesById[ENGINE_CORE];
    }
    if (failOnMissingEngine) {
      throw new Error("Cound not find active engine for platform ".concat(c.platform, ". Available engines:\n        ").concat(
      c.runtime.enginesByIndex.map(function (v) {return v.config.id;}).join(', ')));
    }
    return null;
  }
  if (hasEngineTask(task, engine.tasks, configExists)) return engine;
  if (hasEngineTask(task, c.runtime.enginesById[ENGINE_CORE].tasks, configExists)) {
    return c.runtime.enginesById[ENGINE_CORE];
  }
  if (failOnMissingEngine) throw new Error("Cound not find suitable executor for task ".concat((0, _logger.chalk)().white(task)));
  return null;
};exports.getEngineRunner = getEngineRunner;

var getRegisteredEngines = function getRegisteredEngines(c) {return c.runtime.enginesByIndex;};exports.getRegisteredEngines = getRegisteredEngines;
//# sourceMappingURL=index.js.map