{"version":3,"names":["pkgJson","require","program","CommanderCommand","usage","version","enablePositionalOptions","handleError","err","logger","enable","opts","verbose","error","message","replace","stack","log","hasDebugMessages","info","chalk","dim","reset","process","exit","printExamples","examples","output","length","formattedUsage","map","example","desc","cyan","cmd","join","concat","bold","isDetachedCommand","command","detached","isAttachedCommand","attachCommand","config","commands","find","name","Error","option","action","handleAction","args","passedOptions","argv","Array","from","slice","func","description","addHelpText","opt","options","parse","val","default","run","platformName","setupAndRun","e","isCommandPassed","commandName","filter","arg","disable","setVerbose","includes","platform","scriptName","absolutePath","path","__dirname","childProcess","execFileSync","stdio","warn","red","loadConfig","projectCommands","Object","values","debug","CLIError","detachedCommands","push","bin","resolve"],"sources":["../src/index.ts"],"sourcesContent":["import loadConfig from '@react-native-community/cli-config';\nimport {CLIError, logger} from '@react-native-community/cli-tools';\nimport type {\n Command,\n Config,\n DetachedCommand,\n} from '@react-native-community/cli-types';\nimport chalk from 'chalk';\nimport childProcess from 'child_process';\nimport {Command as CommanderCommand} from 'commander';\nimport path from 'path';\nimport {detachedCommands, projectCommands} from './commands';\n\nconst pkgJson = require('../package.json');\n\nconst program = new CommanderCommand()\n .usage('[command] [options]')\n .version(pkgJson.version, '-v', 'Output the current version')\n .enablePositionalOptions();\n\nconst handleError = (err: Error) => {\n logger.enable();\n if (program.opts().verbose) {\n logger.error(err.message);\n } else {\n // Some error messages (esp. custom ones) might have `.` at the end already.\n const message = err.message.replace(/\\.$/, '');\n logger.error(`${message}.`);\n }\n if (err.stack) {\n logger.log(err.stack);\n }\n if (!program.opts().verbose && logger.hasDebugMessages()) {\n logger.info(\n chalk.dim(\n `Run CLI with ${chalk.reset('--verbose')} ${chalk.dim(\n 'flag for more details.',\n )}`,\n ),\n );\n }\n process.exit(1);\n};\n\nfunction printExamples(examples: Command['examples']) {\n let output: string[] = [];\n\n if (examples && examples.length > 0) {\n const formattedUsage = examples\n .map((example) => ` ${example.desc}: \\n ${chalk.cyan(example.cmd)}`)\n .join('\\n\\n');\n\n output = output.concat([chalk.bold('\\nExample usage:'), formattedUsage]);\n }\n\n return output.join('\\n').concat('\\n');\n}\n\n/**\n * Custom type assertion needed for the `makeCommand` conditional\n * types to be properly resolved.\n */\nfunction isDetachedCommand(\n command: Command,\n): command is DetachedCommand {\n return command.detached === true;\n}\n\nfunction isAttachedCommand(\n command: Command,\n): command is Command {\n return !isDetachedCommand(command);\n}\n\n/**\n * Attaches a new command onto global `commander` instance.\n *\n * Note that this function takes additional argument of `Config` type in case\n * passed `command` needs it for its execution.\n */\nfunction attachCommand>(\n command: C,\n config: C extends DetachedCommand ? Config | undefined : Config,\n): void {\n // commander@9.x will internally push commands into an array structure!\n // Commands with duplicate names (e.g. from config) must be reduced before\n // calling this function.\n // https://unpkg.com/browse/commander@9.4.1/lib/command.js#L1308\n if (program.commands.find((cmd) => cmd.name() === command.name)) {\n throw new Error(\n 'Invariant Violation: Attempted to override an already registered ' +\n `command: '${command.name}'. This is not supported by the underlying ` +\n 'library and will cause bugs. Ensure a command with this `name` is ' +\n 'only registered once.',\n );\n }\n\n const cmd = program\n .command(command.name)\n .option('--verbose', 'Increase logging verbosity')\n .action(async function handleAction(\n this: CommanderCommand,\n ...args: string[]\n ) {\n const passedOptions = this.opts();\n const argv = Array.from(args).slice(0, -1);\n\n try {\n if (isDetachedCommand(command)) {\n await command.func(argv, passedOptions, config);\n } else if (isAttachedCommand(command)) {\n await command.func(argv, config, passedOptions);\n } else {\n throw new Error('A command must be either attached or detached');\n }\n } catch (error) {\n handleError(error as Error);\n }\n });\n\n if (command.description) {\n cmd.description(command.description);\n }\n\n cmd.addHelpText('after', printExamples(command.examples));\n\n for (const opt of command.options || []) {\n cmd.option(\n opt.name,\n opt.description ?? '',\n opt.parse || ((val: any) => val),\n typeof opt.default === 'function' ? opt.default(config) : opt.default,\n );\n }\n}\n\n// Platform name is optional argument passed by out of tree platforms.\nasync function run(platformName?: string) {\n try {\n await setupAndRun(platformName);\n } catch (e) {\n handleError(e as Error);\n }\n}\n\nconst isCommandPassed = (commandName: string) => {\n return process.argv.filter((arg) => arg === commandName).length > 0;\n};\n\nasync function setupAndRun(platformName?: string) {\n // Commander is not available yet\n\n // when we run `config`, we don't want to output anything to the console. We\n // expect it to return valid JSON\n if (isCommandPassed('config')) {\n logger.disable();\n }\n\n logger.setVerbose(process.argv.includes('--verbose'));\n\n // We only have a setup script for UNIX envs currently\n if (process.platform !== 'win32') {\n const scriptName = 'setup_env.sh';\n const absolutePath = path.join(__dirname, '..', scriptName);\n\n try {\n childProcess.execFileSync(absolutePath, {stdio: 'pipe'});\n } catch (error) {\n logger.warn(\n `Failed to run environment setup script \"${scriptName}\"\\n\\n${chalk.red(\n error,\n )}`,\n );\n logger.info(\n `React Native CLI will continue to run if your local environment matches what React Native expects. If it does fail, check out \"${absolutePath}\" and adjust your environment to match it.`,\n );\n }\n }\n\n let config: Config | undefined;\n try {\n config = loadConfig();\n\n logger.enable();\n\n const commands: Record = {};\n\n // Reduce overridden commands before registering\n for (const command of [...projectCommands, ...config.commands]) {\n commands[command.name] = command;\n }\n\n for (const command of Object.values(commands)) {\n attachCommand(command, config);\n }\n } catch (error) {\n /**\n * When there is no `package.json` found, the CLI will enter `detached` mode and a subset\n * of commands will be available. That's why we don't throw on such kind of error.\n */\n if ((error as Error).message.includes(\"We couldn't find a package.json\")) {\n logger.debug((error as Error).message);\n logger.debug(\n 'Failed to load configuration of your project. Only a subset of commands will be available.',\n );\n } else {\n throw new CLIError(\n 'Failed to load configuration of your project.',\n error as any,\n );\n }\n } finally {\n for (const command of detachedCommands) {\n attachCommand(command, config);\n }\n }\n\n const argv = [...process.argv];\n\n // If out of tree platform specifices custom platform name, we need to pass it to argv array for the init command.\n if (isCommandPassed('init') && platformName) {\n argv.push('--platform-name', platformName);\n }\n\n program.parse(argv);\n}\n\nconst bin = require.resolve('./bin');\n\nexport {run, bin, loadConfig};\n"],"mappings":";;;;;;;;;;;;;AAAA;EAAA;EAAA;IAAA;EAAA;EAAA;AAAA;AACA;EA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