UNPKG

@graphql-hive/cli

Version:

A CLI util to manage and control your GraphQL Hive

168 lines • 6.27 kB
"use strict"; Object.defineProperty(exports, "__esModule", { value: true }); const tslib_1 = require("tslib"); const node_fs_1 = require("node:fs"); const node_process_1 = require("node:process"); const core_1 = require("@oclif/core"); const errors_1 = require("@oclif/core/lib/parser/errors"); const config_1 = require("./helpers/config"); const errors_2 = require("./helpers/errors"); const graphql_request_1 = require("./helpers/graphql-request"); const texture_1 = require("./helpers/texture/texture"); class BaseCommand extends core_1.Command { constructor() { super(...arguments); this.logger = { info: (...args) => this.logInfo(...args), error: (...args) => this.logFailure(...args), debug: (...args) => this.logDebug(...args), }; } get userConfig() { if (!this._userConfig) { throw new Error('User config is not initialized'); } return this._userConfig; } async init() { await super.init(); this._userConfig = new config_1.Config({ // eslint-disable-next-line no-process-env filepath: process.env.HIVE_CONFIG, rootDir: process.cwd(), }); const { args, flags } = await this.parse({ flags: this.ctor.flags, baseFlags: super.ctor.baseFlags, args: this.ctor.args, strict: this.ctor.strict, }); this.flags = flags; this.args = args; } /** Every failure is reported with a CLI error code. */ async catch(error) { if (error instanceof errors_2.HiveCLIError || error instanceof core_1.Errors.ExitError) { return super.catch(error); } if (error instanceof errors_1.CLIParseError) { return super.catch(new errors_2.InvalidInputError(error)); } return super.catch(new errors_2.UnexpectedError(error)); } logSuccess(...args) { this.log(texture_1.Texture.success(...args)); } logFailure(...args) { this.logToStderr(texture_1.Texture.failure(...args)); } logInfo(...args) { this.log(texture_1.Texture.info(...args)); } logWarning(...args) { this.log(texture_1.Texture.warning(...args)); } logDebug(...args) { if (this.flags.debug) { this.logInfo(...args); } } maybe({ key, env, args, }) { if (args[key] != null) { return args[key]; } // eslint-disable-next-line no-process-env if (env && process.env[env]) { // eslint-disable-next-line no-process-env return process.env[env]; } return undefined; } /** * Get a value from arguments or flags first, then from env variables, * then fallback to config. * Throw when there's no value. * * @param key * @param args all arguments or flags * @param defaultValue default value * @param description description of the flag in case of no value * @param env an env var name */ ensure({ key, args, legacyFlagName, defaultValue, env: envName, description, }) { let value; if (args[key] != null) { value = args[key]; } else if (legacyFlagName && args[legacyFlagName] != null) { value = args[legacyFlagName]; } else if (envName && node_process_1.env[envName] !== undefined) { value = node_process_1.env[envName]; } else { const configValue = this._userConfig.get(key); if (configValue != null) { value = configValue; } else if (defaultValue) { value = defaultValue; } } if (value === null || value === void 0 ? void 0 : value.length) { return value; } throw new errors_2.MissingArgumentsError([String(key), description]); } registryApi(registry, token) { var _a; const flagHeaders = Object.fromEntries(((_a = this.flags['registry.header']) !== null && _a !== void 0 ? _a : []).map(header => { const separatorIndex = header.indexOf('='); if (separatorIndex <= 0) { throw new errors_2.InvalidHeaderError(header, 'Name=Value'); } return [header.slice(0, separatorIndex), header.slice(separatorIndex + 1)]; })); const requestHeaders = Object.assign(Object.assign(Object.assign({}, this.userConfig.get('registry.headers')), flagHeaders), { Authorization: `Bearer ${token}`, 'graphql-client-name': 'Hive CLI', 'graphql-client-version': this.config.version }); return (0, graphql_request_1.graphqlRequest)({ endpoint: registry, additionalHeaders: requestHeaders, version: this.config.version, logger: this.logger, isHiveRegistry: true, }); } async require(flags) { if (flags.require && flags.require.length > 0) { await Promise.all(flags.require.map(mod => Promise.resolve(`${require.resolve(mod, { paths: [process.cwd()] })}`).then(s => tslib_1.__importStar(require(s))))); } } readJSON(file) { // If we can't parse it, we can try to load it from FS const exists = (0, node_fs_1.existsSync)(file); if (!exists) { throw new errors_2.FileMissingError(file, 'Please specify a path to an existing file, or a string with valid JSON'); } try { const fileContent = (0, node_fs_1.readFileSync)(file, 'utf-8'); JSON.parse(fileContent); return fileContent; } catch (e) { this.logFailure(e); throw new errors_2.InvalidFileContentsError(file, 'JSON'); } } } BaseCommand.baseFlags = { debug: core_1.Flags.boolean({ default: false, summary: 'Whether debug output for HTTP calls and similar should be enabled.', }), 'registry.header': core_1.Flags.string({ description: 'HTTP header to add to registry requests (in Name=Value format)', multiple: true, }), }; exports.default = BaseCommand; //# sourceMappingURL=base-command.js.map