-
Notifications
You must be signed in to change notification settings - Fork 112
/
Copy pathbase-command.ts
316 lines (278 loc) · 8.75 KB
/
base-command.ts
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
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
import { existsSync, readFileSync } from 'node:fs';
import { env } from 'node:process';
import { print } from 'graphql';
import type { ExecutionResult } from 'graphql';
import { http } from '@graphql-hive/core';
import type { TypedDocumentNode } from '@graphql-typed-document-node/core';
import { Command, Flags, Interfaces } from '@oclif/core';
import { Config, GetConfigurationValueType, ValidConfigurationKeys } from './helpers/config';
import {
APIError,
FileMissingError,
HTTPError,
InvalidFileContentsError,
InvalidRegistryTokenError,
isAggregateError,
MissingArgumentsError,
NetworkError,
} from './helpers/errors';
import { Texture } from './helpers/texture/texture';
export type Flags<T extends typeof Command> = Interfaces.InferredFlags<
(typeof BaseCommand)['baseFlags'] & T['flags']
>;
export type Args<T extends typeof Command> = Interfaces.InferredArgs<T['args']>;
type OmitNever<T> = { [K in keyof T as T[K] extends never ? never : K]: T[K] };
export default abstract class BaseCommand<T extends typeof Command> extends Command {
protected _userConfig: Config | undefined;
static baseFlags = {
debug: Flags.boolean({
default: false,
summary: 'Whether debug output for HTTP calls and similar should be enabled.',
}),
};
protected flags!: Flags<T>;
protected args!: Args<T>;
protected get userConfig(): Config {
if (!this._userConfig) {
throw new Error('User config is not initialized');
}
return this._userConfig!;
}
public async init(): Promise<void> {
await super.init();
this._userConfig = new 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 as typeof BaseCommand).baseFlags,
args: this.ctor.args,
strict: this.ctor.strict,
});
this.flags = flags as Flags<T>;
this.args = args as Args<T>;
}
logSuccess(...args: any[]) {
this.log(Texture.success(...args));
}
logFailure(...args: any[]) {
this.logToStderr(Texture.failure(...args));
}
logInfo(...args: any[]) {
this.log(Texture.info(...args));
}
logWarning(...args: any[]) {
this.log(Texture.warning(...args));
}
maybe<TArgs extends Record<string, any>, TKey extends keyof TArgs>({
key,
env,
args,
}: {
key: TKey;
env: string;
args: TArgs;
}) {
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<
TKey extends ValidConfigurationKeys,
TArgs extends {
[key in TKey]: GetConfigurationValueType<TKey>;
},
>({
key,
args,
legacyFlagName,
defaultValue,
env: envName,
description,
}: {
args: TArgs;
key: TKey;
/** By default we try to match config names with flag names, but for legacy compatibility we need to provide the old flag name. */
legacyFlagName?: keyof OmitNever<{
// Symbol.asyncIterator to discriminate against any lol
[TArgKey in keyof TArgs]: typeof Symbol.asyncIterator extends TArgs[TArgKey]
? never
: string extends TArgs[TArgKey]
? TArgKey
: never;
}>;
defaultValue?: TArgs[keyof TArgs] | null;
description: string;
env?: string;
}): NonNullable<GetConfigurationValueType<TKey>> | never {
let value: GetConfigurationValueType<TKey>;
if (args[key] != null) {
value = args[key];
} else if (legacyFlagName && (args as any)[legacyFlagName] != null) {
value = args[legacyFlagName] as NonNullable<GetConfigurationValueType<TKey>>;
} else if (envName && env[envName] !== undefined) {
value = env[envName] as TArgs[keyof TArgs] as NonNullable<GetConfigurationValueType<TKey>>;
} else {
const configValue = this._userConfig!.get(key) as NonNullable<
GetConfigurationValueType<TKey>
>;
if (configValue !== undefined) {
value = configValue;
} else if (defaultValue) {
value = defaultValue;
}
}
if (value?.length) {
return value;
}
throw new MissingArgumentsError([String(key), description]);
}
cleanRequestId(requestId?: string | null) {
return requestId ? requestId.split(',')[0].trim() : undefined;
}
registryApi(registry: string, token: string) {
const requestHeaders = {
Authorization: `Bearer ${token}`,
'graphql-client-name': 'Hive CLI',
'graphql-client-version': this.config.version,
};
return this.graphql(registry, requestHeaders);
}
graphql(endpoint: string, additionalHeaders: Record<string, string> = {}) {
const requestHeaders = {
'Content-Type': 'application/json',
Accept: 'application/json',
'User-Agent': `hive-cli/${this.config.version}`,
...additionalHeaders,
};
const isDebug = this.flags.debug;
return {
request: async <TResult, TVariables>(
args: {
operation: TypedDocumentNode<TResult, TVariables>;
/** timeout in milliseconds */
timeout?: number;
} & (TVariables extends Record<string, never>
? {
variables?: never;
}
: {
variables: TVariables;
}),
): Promise<TResult> => {
let response: Response;
try {
response = await http.post(
endpoint,
JSON.stringify({
query: typeof args.operation === 'string' ? args.operation : print(args.operation),
variables: args.variables,
}),
{
logger: {
info: (...args) => {
if (isDebug) {
this.logInfo(...args);
}
},
error: (...args) => {
// Allow retrying requests without noise
if (isDebug) {
this.logWarning(...args);
}
},
},
headers: requestHeaders,
timeout: args.timeout,
},
);
} catch (e: any) {
const sourceError = e?.cause ?? e;
if (isAggregateError(sourceError)) {
throw new NetworkError(sourceError.errors[0]?.message);
} else {
throw new NetworkError(sourceError);
}
}
if (!response.ok) {
throw new HTTPError(
endpoint,
response.status,
response.statusText ?? 'Invalid status code for HTTP call',
);
}
let jsonData;
try {
jsonData = (await response.json()) as ExecutionResult<TResult>;
} catch (err) {
const contentType = response?.headers?.get('content-type');
throw new APIError(
`Response from graphql was not valid JSON.${contentType ? ` Received "content-type": "${contentType}".` : ''}`,
this.cleanRequestId(response?.headers?.get('x-request-id')),
);
}
if (jsonData.errors && jsonData.errors.length > 0) {
if (jsonData.errors[0].message === 'Invalid token provided') {
throw new InvalidRegistryTokenError();
}
if (isDebug) {
this.logFailure(jsonData.errors);
}
throw new APIError(
jsonData.errors.map(e => e.message).join('\n'),
this.cleanRequestId(response?.headers?.get('x-request-id')),
);
}
return jsonData.data!;
},
};
}
async require<
TFlags extends {
require: string[];
[key: string]: any;
},
>(flags: TFlags) {
if (flags.require && flags.require.length > 0) {
await Promise.all(
flags.require.map(mod => import(require.resolve(mod, { paths: [process.cwd()] }))),
);
}
}
readJSON(file: string): string {
// If we can't parse it, we can try to load it from FS
const exists = existsSync(file);
if (!exists) {
throw new FileMissingError(
file,
'Please specify a path to an existing file, or a string with valid JSON',
);
}
try {
const fileContent = readFileSync(file, 'utf-8');
JSON.parse(fileContent);
return fileContent;
} catch (e) {
throw new InvalidFileContentsError(file, 'JSON');
}
}
}