@redocly/cli 1.0.0 → 1.0.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (57) hide show
  1. package/CHANGELOG.md +8 -0
  2. package/lib/commands/build-docs/index.js +2 -4
  3. package/lib/commands/build-docs/utils.d.ts +1 -1
  4. package/lib/commands/build-docs/utils.js +3 -3
  5. package/package.json +2 -2
  6. package/src/__mocks__/@redocly/openapi-core.ts +80 -0
  7. package/src/__mocks__/documents.ts +63 -0
  8. package/src/__mocks__/fs.ts +6 -0
  9. package/src/__mocks__/perf_hooks.ts +3 -0
  10. package/src/__mocks__/redoc.ts +2 -0
  11. package/src/__mocks__/utils.ts +19 -0
  12. package/src/__tests__/commands/build-docs.test.ts +62 -0
  13. package/src/__tests__/commands/bundle.test.ts +150 -0
  14. package/src/__tests__/commands/join.test.ts +122 -0
  15. package/src/__tests__/commands/lint.test.ts +190 -0
  16. package/src/__tests__/commands/push-region.test.ts +58 -0
  17. package/src/__tests__/commands/push.test.ts +492 -0
  18. package/src/__tests__/fetch-with-timeout.test.ts +35 -0
  19. package/src/__tests__/fixtures/config.ts +21 -0
  20. package/src/__tests__/fixtures/openapi.json +0 -0
  21. package/src/__tests__/fixtures/openapi.yaml +0 -0
  22. package/src/__tests__/fixtures/redocly.yaml +0 -0
  23. package/src/__tests__/utils.test.ts +564 -0
  24. package/src/__tests__/wrapper.test.ts +57 -0
  25. package/src/assert-node-version.ts +8 -0
  26. package/src/commands/build-docs/index.ts +50 -0
  27. package/src/commands/build-docs/template.hbs +23 -0
  28. package/src/commands/build-docs/types.ts +24 -0
  29. package/src/commands/build-docs/utils.ts +110 -0
  30. package/src/commands/bundle.ts +177 -0
  31. package/src/commands/join.ts +811 -0
  32. package/src/commands/lint.ts +151 -0
  33. package/src/commands/login.ts +27 -0
  34. package/src/commands/preview-docs/index.ts +190 -0
  35. package/src/commands/preview-docs/preview-server/default.hbs +24 -0
  36. package/src/commands/preview-docs/preview-server/hot.js +42 -0
  37. package/src/commands/preview-docs/preview-server/oauth2-redirect.html +21 -0
  38. package/src/commands/preview-docs/preview-server/preview-server.ts +156 -0
  39. package/src/commands/preview-docs/preview-server/server.ts +91 -0
  40. package/src/commands/push.ts +441 -0
  41. package/src/commands/split/__tests__/fixtures/samples.json +61 -0
  42. package/src/commands/split/__tests__/fixtures/spec.json +70 -0
  43. package/src/commands/split/__tests__/fixtures/webhooks.json +85 -0
  44. package/src/commands/split/__tests__/index.test.ts +137 -0
  45. package/src/commands/split/index.ts +385 -0
  46. package/src/commands/split/types.ts +85 -0
  47. package/src/commands/stats.ts +119 -0
  48. package/src/custom.d.ts +1 -0
  49. package/src/fetch-with-timeout.ts +21 -0
  50. package/src/index.ts +484 -0
  51. package/src/js-utils.ts +17 -0
  52. package/src/types.ts +40 -0
  53. package/src/update-version-notifier.ts +106 -0
  54. package/src/utils.ts +590 -0
  55. package/src/wrapper.ts +42 -0
  56. package/tsconfig.json +9 -0
  57. package/tsconfig.tsbuildinfo +1 -0
@@ -0,0 +1,564 @@
1
+ import {
2
+ getFallbackApisOrExit,
3
+ isSubdir,
4
+ pathToFilename,
5
+ printConfigLintTotals,
6
+ langToExt,
7
+ checkIfRulesetExist,
8
+ handleError,
9
+ CircularJSONNotSupportedError,
10
+ sortTopLevelKeysForOas,
11
+ cleanColors,
12
+ HandledError,
13
+ cleanArgs,
14
+ cleanRawInput,
15
+ } from '../utils';
16
+ import {
17
+ ResolvedApi,
18
+ Totals,
19
+ isAbsoluteUrl,
20
+ ResolveError,
21
+ YamlParseError,
22
+ } from '@redocly/openapi-core';
23
+ import { blue, red, yellow } from 'colorette';
24
+ import { existsSync, statSync } from 'fs';
25
+ import * as path from 'path';
26
+ import * as process from 'process';
27
+
28
+ jest.mock('os');
29
+ jest.mock('colorette');
30
+
31
+ jest.mock('fs');
32
+
33
+ describe('isSubdir', () => {
34
+ it('can correctly determine if subdir', () => {
35
+ (
36
+ [
37
+ ['/foo', '/foo', false],
38
+ ['/foo', '/bar', false],
39
+ ['/foo', '/foobar', false],
40
+ ['/foo', '/foo/bar', true],
41
+ ['/foo', '/foo/../bar', false],
42
+ ['/foo', '/foo/./bar', true],
43
+ ['/bar/../foo', '/foo/bar', true],
44
+ ['/foo', './bar', false],
45
+ ['/foo', '/foo/..bar', true],
46
+ ] as [string, string, boolean][]
47
+ ).forEach(([parent, child, expectRes]) => {
48
+ expect(isSubdir(parent, child)).toBe(expectRes);
49
+ });
50
+ });
51
+
52
+ it('can correctly determine if subdir for windows-based paths', () => {
53
+ const os = require('os');
54
+ os.platform.mockImplementation(() => 'win32');
55
+
56
+ (
57
+ [
58
+ ['C:/Foo', 'C:/Foo/Bar', true],
59
+ ['C:\\Foo', 'C:\\Bar', false],
60
+ ['C:\\Foo', 'D:\\Foo\\Bar', false],
61
+ ] as [string, string, boolean][]
62
+ ).forEach(([parent, child, expectRes]) => {
63
+ expect(isSubdir(parent, child)).toBe(expectRes);
64
+ });
65
+ });
66
+
67
+ afterEach(() => {
68
+ jest.resetModules();
69
+ });
70
+ });
71
+
72
+ describe('pathToFilename', () => {
73
+ it('should use correct path separator', () => {
74
+ const processedPath = pathToFilename('/user/createWithList', '_');
75
+ expect(processedPath).toEqual('user_createWithList');
76
+ });
77
+ });
78
+
79
+ describe('getFallbackApisOrExit', () => {
80
+ it('should find alias by filename', async () => {
81
+ (existsSync as jest.Mock<any, any>).mockImplementationOnce(() => true);
82
+ const entry = await getFallbackApisOrExit(['./test.yaml'], {
83
+ apis: {
84
+ main: {
85
+ root: 'test.yaml',
86
+ },
87
+ },
88
+ } as any);
89
+ expect(entry).toEqual([{ path: './test.yaml', alias: 'main' }]);
90
+ });
91
+ });
92
+
93
+ describe('printConfigLintTotals', () => {
94
+ const totalProblemsMock: Totals = {
95
+ errors: 1,
96
+ warnings: 0,
97
+ ignored: 0,
98
+ };
99
+
100
+ const redColoretteMocks = red as jest.Mock<any, any>;
101
+ const yellowColoretteMocks = yellow as jest.Mock<any, any>;
102
+
103
+ beforeEach(() => {
104
+ yellowColoretteMocks.mockImplementation((text: string) => text);
105
+ redColoretteMocks.mockImplementation((text: string) => text);
106
+ jest.spyOn(process.stderr, 'write').mockImplementation(() => true);
107
+ });
108
+
109
+ it('should print errors if such exist', () => {
110
+ printConfigLintTotals(totalProblemsMock);
111
+ expect(process.stderr.write).toHaveBeenCalledWith('āŒ Your config has 1 error.\n');
112
+ expect(redColoretteMocks).toHaveBeenCalledWith('āŒ Your config has 1 error.\n');
113
+ });
114
+
115
+ it('should print warnign and error', () => {
116
+ printConfigLintTotals({ ...totalProblemsMock, warnings: 2 });
117
+ expect(process.stderr.write).toHaveBeenCalledWith(
118
+ 'āŒ Your config has 1 error and 2 warnings.\n'
119
+ );
120
+ expect(redColoretteMocks).toHaveBeenCalledWith('āŒ Your config has 1 error and 2 warnings.\n');
121
+ });
122
+
123
+ it('should print warnign if no error', () => {
124
+ printConfigLintTotals({ ...totalProblemsMock, errors: 0, warnings: 2 });
125
+ expect(process.stderr.write).toHaveBeenCalledWith('You have 2 warnings.\n');
126
+ expect(yellowColoretteMocks).toHaveBeenCalledWith('You have 2 warnings.\n');
127
+ });
128
+
129
+ it('should print nothing if no error and no warnings', () => {
130
+ const result = printConfigLintTotals({ ...totalProblemsMock, errors: 0 });
131
+ expect(result).toBeUndefined();
132
+ expect(process.stderr.write).toHaveBeenCalledTimes(0);
133
+ expect(yellowColoretteMocks).toHaveBeenCalledTimes(0);
134
+ expect(redColoretteMocks).toHaveBeenCalledTimes(0);
135
+ });
136
+ });
137
+
138
+ describe('getFallbackApisOrExit', () => {
139
+ const redColoretteMocks = red as jest.Mock<any, any>;
140
+ const yellowColoretteMocks = yellow as jest.Mock<any, any>;
141
+
142
+ const apis: Record<string, ResolvedApi> = {
143
+ main: {
144
+ root: 'someFile.yaml',
145
+ styleguide: {},
146
+ },
147
+ };
148
+
149
+ const config = { apis };
150
+
151
+ beforeEach(() => {
152
+ yellowColoretteMocks.mockImplementation((text: string) => text);
153
+ redColoretteMocks.mockImplementation((text: string) => text);
154
+ jest.spyOn(process.stderr, 'write').mockImplementation(() => true);
155
+ jest.spyOn(process, 'exit').mockImplementation();
156
+ });
157
+ afterEach(() => {
158
+ jest.clearAllMocks();
159
+ });
160
+
161
+ it('should exit with error because no path provided', async () => {
162
+ const apisConfig = {
163
+ apis: {},
164
+ };
165
+ expect.assertions(1);
166
+ try {
167
+ await getFallbackApisOrExit([''], apisConfig);
168
+ } catch (e) {
169
+ expect(e.message).toEqual('Path cannot be empty.');
170
+ }
171
+ });
172
+
173
+ it('should error if file from config do not exist', async () => {
174
+ (existsSync as jest.Mock<any, any>).mockImplementationOnce(() => false);
175
+ expect.assertions(3);
176
+ try {
177
+ await getFallbackApisOrExit(undefined, config);
178
+ } catch (e) {
179
+ expect(process.stderr.write).toHaveBeenCalledWith(
180
+ '\nsomeFile.yaml does not exist or is invalid.\n\n'
181
+ );
182
+ expect(process.stderr.write).toHaveBeenCalledWith('Please provide a valid path.\n\n');
183
+ expect(e.message).toEqual('Please provide a valid path.');
184
+ }
185
+ });
186
+
187
+ it('should return valid array with results if such file exist', async () => {
188
+ (existsSync as jest.Mock<any, any>).mockImplementationOnce(() => true);
189
+ jest.spyOn(path, 'resolve').mockImplementationOnce((_, path) => path);
190
+
191
+ const result = await getFallbackApisOrExit(undefined, config);
192
+ expect(process.stderr.write).toHaveBeenCalledTimes(0);
193
+ expect(process.exit).toHaveBeenCalledTimes(0);
194
+ expect(result).toStrictEqual([
195
+ {
196
+ alias: 'main',
197
+ path: 'someFile.yaml',
198
+ },
199
+ ]);
200
+ });
201
+
202
+ it('should exit with error in case if invalid path provided as args', async () => {
203
+ const apisConfig = {
204
+ apis: {},
205
+ };
206
+ (existsSync as jest.Mock<any, any>).mockImplementationOnce(() => false);
207
+ expect.assertions(3);
208
+
209
+ try {
210
+ await getFallbackApisOrExit(['someFile.yaml'], apisConfig);
211
+ } catch (e) {
212
+ expect(process.stderr.write).toHaveBeenCalledWith(
213
+ '\nsomeFile.yaml does not exist or is invalid.\n\n'
214
+ );
215
+ expect(process.stderr.write).toHaveBeenCalledWith('Please provide a valid path.\n\n');
216
+ expect(e.message).toEqual('Please provide a valid path.');
217
+ }
218
+ });
219
+
220
+ it('should exit with error in case if invalid 2 path provided as args', async () => {
221
+ const apisConfig = {
222
+ apis: {},
223
+ };
224
+ (existsSync as jest.Mock<any, any>).mockImplementationOnce(() => false);
225
+ expect.assertions(3);
226
+ try {
227
+ await getFallbackApisOrExit(['someFile.yaml', 'someFile2.yaml'], apisConfig);
228
+ } catch (e) {
229
+ expect(process.stderr.write).toHaveBeenCalledWith(
230
+ '\nsomeFile.yaml does not exist or is invalid.\n\n'
231
+ );
232
+ expect(process.stderr.write).toHaveBeenCalledWith('Please provide a valid path.\n\n');
233
+ expect(e.message).toEqual('Please provide a valid path.');
234
+ }
235
+ });
236
+
237
+ it('should exit with error if only one file exist ', async () => {
238
+ const apisStub = {
239
+ ...apis,
240
+ notExist: {
241
+ root: 'notExist.yaml',
242
+ styleguide: {},
243
+ },
244
+ };
245
+ const configStub = { apis: apisStub };
246
+
247
+ const existSyncMock = (existsSync as jest.Mock<any, any>).mockImplementation((path) =>
248
+ path.endsWith('someFile.yaml')
249
+ );
250
+
251
+ expect.assertions(4);
252
+
253
+ try {
254
+ await getFallbackApisOrExit(undefined, configStub);
255
+ } catch (e) {
256
+ expect(process.stderr.write).toHaveBeenCalledWith(
257
+ '\nnotExist.yaml does not exist or is invalid.\n\n'
258
+ );
259
+ expect(process.stderr.write).toHaveBeenCalledWith('Please provide a valid path.\n\n');
260
+ expect(process.stderr.write).toHaveBeenCalledTimes(2);
261
+ expect(e.message).toEqual('Please provide a valid path.');
262
+ }
263
+ existSyncMock.mockClear();
264
+ });
265
+
266
+ it('should work ok if it is url passed', async () => {
267
+ (existsSync as jest.Mock<any, any>).mockImplementationOnce(() => false);
268
+ (isAbsoluteUrl as jest.Mock<any, any>).mockImplementation(() => true);
269
+ const apisConfig = {
270
+ apis: {
271
+ main: {
272
+ root: 'https://someLinkt/petstore.yaml?main',
273
+ styleguide: {},
274
+ },
275
+ },
276
+ };
277
+
278
+ const result = await getFallbackApisOrExit(undefined, apisConfig);
279
+
280
+ expect(process.stderr.write).toHaveBeenCalledTimes(0);
281
+ expect(result).toStrictEqual([
282
+ {
283
+ alias: 'main',
284
+ path: 'https://someLinkt/petstore.yaml?main',
285
+ },
286
+ ]);
287
+ });
288
+ });
289
+
290
+ describe('langToExt', () => {
291
+ it.each([
292
+ ['php', '.php'],
293
+ ['c#', '.cs'],
294
+ ['shell', '.sh'],
295
+ ['curl', '.sh'],
296
+ ['bash', '.sh'],
297
+ ['javascript', '.js'],
298
+ ['js', '.js'],
299
+ ['python', '.py'],
300
+ ])('should infer file extension from lang - %s', (lang, expected) => {
301
+ expect(langToExt(lang)).toBe(expected);
302
+ });
303
+
304
+ it('should ignore case when inferring file extension', () => {
305
+ expect(langToExt('JavaScript')).toBe('.js');
306
+ });
307
+ });
308
+
309
+ describe('sorTopLevelKeysForOas', () => {
310
+ it('should sort oas3 top level keys', () => {
311
+ const openApi = {
312
+ openapi: '3.0.0',
313
+ components: {},
314
+ security: [],
315
+ tags: [],
316
+ servers: [],
317
+ paths: {},
318
+ info: {},
319
+ externalDocs: {},
320
+ webhooks: [],
321
+ 'x-webhooks': [],
322
+ jsonSchemaDialect: '',
323
+ } as any;
324
+ const orderedKeys = [
325
+ 'openapi',
326
+ 'info',
327
+ 'jsonSchemaDialect',
328
+ 'servers',
329
+ 'security',
330
+ 'tags',
331
+ 'externalDocs',
332
+ 'paths',
333
+ 'webhooks',
334
+ 'x-webhooks',
335
+ 'components',
336
+ ];
337
+ const result = sortTopLevelKeysForOas(openApi);
338
+
339
+ Object.keys(result).forEach((key, index) => {
340
+ expect(key).toEqual(orderedKeys[index]);
341
+ });
342
+ });
343
+
344
+ it('should sort oas2 top level keys', () => {
345
+ const openApi = {
346
+ swagger: '2.0.0',
347
+ security: [],
348
+ tags: [],
349
+ paths: {},
350
+ info: {},
351
+ externalDocs: {},
352
+ host: '',
353
+ basePath: '',
354
+ securityDefinitions: [],
355
+ schemes: [],
356
+ consumes: [],
357
+ parameters: [],
358
+ produces: [],
359
+ definitions: [],
360
+ responses: [],
361
+ } as any;
362
+ const orderedKeys = [
363
+ 'swagger',
364
+ 'info',
365
+ 'host',
366
+ 'basePath',
367
+ 'schemes',
368
+ 'consumes',
369
+ 'produces',
370
+ 'security',
371
+ 'tags',
372
+ 'externalDocs',
373
+ 'paths',
374
+ 'definitions',
375
+ 'parameters',
376
+ 'responses',
377
+ 'securityDefinitions',
378
+ ];
379
+ const result = sortTopLevelKeysForOas(openApi);
380
+
381
+ Object.keys(result).forEach((key, index) => {
382
+ expect(key).toEqual(orderedKeys[index]);
383
+ });
384
+ });
385
+ });
386
+
387
+ describe('handleErrors', () => {
388
+ const ref = 'openapi/test.yaml';
389
+
390
+ const redColoretteMocks = red as jest.Mock<any, any>;
391
+ const blueColoretteMocks = blue as jest.Mock<any, any>;
392
+
393
+ beforeEach(() => {
394
+ jest.spyOn(process.stderr, 'write').mockImplementation(() => true);
395
+ jest.spyOn(process, 'exit').mockImplementation((code) => code as never);
396
+ redColoretteMocks.mockImplementation((text) => text);
397
+ blueColoretteMocks.mockImplementation((text) => text);
398
+ });
399
+
400
+ afterEach(() => {
401
+ jest.clearAllMocks();
402
+ });
403
+
404
+ it('should handle ResolveError', () => {
405
+ const resolveError = new ResolveError(new Error('File not found'));
406
+ expect(() => handleError(resolveError, ref)).toThrowError(HandledError);
407
+ expect(redColoretteMocks).toHaveBeenCalledTimes(1);
408
+ expect(process.stderr.write).toHaveBeenCalledWith(
409
+ `Failed to resolve api definition at openapi/test.yaml:\n\n - File not found.\n\n`
410
+ );
411
+ });
412
+
413
+ it('should handle YamlParseError', () => {
414
+ const yamlParseError = new YamlParseError(new Error('Invalid yaml'), {} as any);
415
+ expect(() => handleError(yamlParseError, ref)).toThrowError(HandledError);
416
+ expect(redColoretteMocks).toHaveBeenCalledTimes(1);
417
+ expect(process.stderr.write).toHaveBeenCalledWith(
418
+ `Failed to parse api definition at openapi/test.yaml:\n\n - Invalid yaml.\n\n`
419
+ );
420
+ });
421
+
422
+ it('should handle CircularJSONNotSupportedError', () => {
423
+ const circularError = new CircularJSONNotSupportedError(new Error('Circular json'));
424
+ expect(() => handleError(circularError, ref)).toThrowError(HandledError);
425
+ expect(process.stderr.write).toHaveBeenCalledWith(
426
+ `Detected circular reference which can't be converted to JSON.\n` +
427
+ `Try to use ${blue('yaml')} output or remove ${blue('--dereferenced')}.\n\n`
428
+ );
429
+ });
430
+
431
+ it('should handle SyntaxError', () => {
432
+ const testError = new SyntaxError('Unexpected identifier');
433
+ testError.stack = 'test stack';
434
+ expect(() => handleError(testError, ref)).toThrowError(HandledError);
435
+ expect(process.stderr.write).toHaveBeenCalledWith(
436
+ 'Syntax error: Unexpected identifier test stack\n\n'
437
+ );
438
+ });
439
+
440
+ it('should throw unknown error', () => {
441
+ const testError = new Error('Test error');
442
+ expect(() => handleError(testError, ref)).toThrowError(HandledError);
443
+ expect(process.stderr.write).toHaveBeenCalledWith(
444
+ `Something went wrong when processing openapi/test.yaml:\n\n - Test error.\n\n`
445
+ );
446
+ });
447
+ });
448
+
449
+ describe('checkIfRulesetExist', () => {
450
+ beforeEach(() => {
451
+ jest.spyOn(process, 'exit').mockImplementation((code?: number) => code as never);
452
+ });
453
+
454
+ afterEach(() => {
455
+ jest.clearAllMocks();
456
+ });
457
+
458
+ it('should throw an error if rules are not provided', () => {
459
+ const rules = {
460
+ oas2: {},
461
+ oas3_0: {},
462
+ oas3_1: {},
463
+ };
464
+ expect(() => checkIfRulesetExist(rules)).toThrowError(
465
+ 'āš ļø No rules were configured. Learn how to configure rules: https://redocly.com/docs/cli/rules/'
466
+ );
467
+ });
468
+
469
+ it('should not throw an error if rules are provided', () => {
470
+ const rules = {
471
+ oas2: { 'operation-4xx-response': 'error' },
472
+ oas3_0: {},
473
+ oas3_1: {},
474
+ } as any;
475
+ checkIfRulesetExist(rules);
476
+ });
477
+ });
478
+
479
+ describe('cleanColors', () => {
480
+ it('should remove colors from string', () => {
481
+ const stringWithColors = `String for ${red('test')}`;
482
+ const result = cleanColors(stringWithColors);
483
+
484
+ expect(result).not.toMatch(/\x1b\[\d+m/g);
485
+ });
486
+ });
487
+
488
+ describe('cleanArgs', () => {
489
+ beforeEach(() => {
490
+ // @ts-ignore
491
+ isAbsoluteUrl = jest.requireActual('@redocly/openapi-core').isAbsoluteUrl;
492
+ // @ts-ignore
493
+ existsSync = (value) => jest.requireActual('fs').existsSync(path.resolve(__dirname, value));
494
+ // @ts-ignore
495
+ statSync = (value) => jest.requireActual('fs').statSync(path.resolve(__dirname, value));
496
+ });
497
+ afterEach(() => {
498
+ jest.clearAllMocks();
499
+ });
500
+ it('should remove potentially sensitive data from args', () => {
501
+ const testArgs = {
502
+ config: './fixtures/redocly.yaml',
503
+ apis: ['main@v1', 'fixtures/openapi.yaml', 'http://some.url/openapi.yaml'],
504
+ format: 'codeframe',
505
+ };
506
+ expect(cleanArgs(testArgs)).toEqual({
507
+ config: 'file-yaml',
508
+ apis: ['api-name@api-version', 'file-yaml', 'http://url'],
509
+ format: 'codeframe',
510
+ });
511
+ });
512
+ it('should remove potentially sensitive data from a push destination', () => {
513
+ const testArgs = {
514
+ destination: '@org/name@version',
515
+ };
516
+ expect(cleanArgs(testArgs)).toEqual({
517
+ destination: '@organization/api-name@api-version',
518
+ });
519
+ });
520
+ });
521
+
522
+ describe('cleanRawInput', () => {
523
+ beforeEach(() => {
524
+ // @ts-ignore
525
+ isAbsoluteUrl = jest.requireActual('@redocly/openapi-core').isAbsoluteUrl;
526
+ // @ts-ignore
527
+ existsSync = (value) => jest.requireActual('fs').existsSync(path.resolve(__dirname, value));
528
+ // @ts-ignore
529
+ statSync = (value) => jest.requireActual('fs').statSync(path.resolve(__dirname, value));
530
+ });
531
+ afterEach(() => {
532
+ jest.clearAllMocks();
533
+ });
534
+ it('should remove potentially sensitive data from raw CLI input', () => {
535
+ const rawInput = [
536
+ 'redocly',
537
+ 'bundle',
538
+ 'api-name@api-version',
539
+ './fixtures/openapi.yaml',
540
+ 'http://some.url/openapi.yaml',
541
+ '--config=fixtures/redocly.yaml',
542
+ '--output',
543
+ 'fixtures',
544
+ ];
545
+ expect(cleanRawInput(rawInput)).toEqual(
546
+ 'redocly bundle api-name@api-version file-yaml http://url --config=file-yaml --output folder'
547
+ );
548
+ });
549
+ it('should preserve safe data from raw CLI input', () => {
550
+ const rawInput = [
551
+ 'redocly',
552
+ 'lint',
553
+ './fixtures/openapi.json',
554
+ '--format',
555
+ 'stylish',
556
+ '--extends=minimal',
557
+ '--skip-rule',
558
+ 'operation-4xx-response',
559
+ ];
560
+ expect(cleanRawInput(rawInput)).toEqual(
561
+ 'redocly lint file-json --format stylish --extends=minimal --skip-rule operation-4xx-response'
562
+ );
563
+ });
564
+ });
@@ -0,0 +1,57 @@
1
+ import { loadConfigAndHandleErrors, sendTelemetry } from '../utils';
2
+ import * as process from 'process';
3
+ import { commandWrapper } from '../wrapper';
4
+ import { handleLint } from '../commands/lint';
5
+ import { Arguments } from 'yargs';
6
+ import { handlePush, PushOptions } from '../commands/push';
7
+
8
+ jest.mock('node-fetch');
9
+ jest.mock('../utils', () => ({
10
+ sendTelemetry: jest.fn(),
11
+ loadConfigAndHandleErrors: jest.fn(),
12
+ }));
13
+ jest.mock('../commands/lint', () => ({
14
+ handleLint: jest.fn(),
15
+ lintConfigCallback: jest.fn(),
16
+ }));
17
+
18
+ describe('commandWrapper', () => {
19
+ it('should send telemetry if there is "telemetry: on" in the config', async () => {
20
+ (loadConfigAndHandleErrors as jest.Mock).mockImplementation(() => {
21
+ return { telemetry: 'on', styleguide: { recommendedFallback: true } };
22
+ });
23
+ process.env.REDOCLY_TELEMETRY = 'on';
24
+
25
+ const wrappedHandler = commandWrapper(handleLint);
26
+ await wrappedHandler({} as any);
27
+ expect(handleLint).toHaveBeenCalledTimes(1);
28
+ expect(sendTelemetry).toHaveBeenCalledTimes(1);
29
+ expect(sendTelemetry).toHaveBeenCalledWith({}, 0, false);
30
+ });
31
+
32
+ it('should NOT send telemetry if there is "telemetry: off" in the config', async () => {
33
+ (loadConfigAndHandleErrors as jest.Mock).mockImplementation(() => {
34
+ return { telemetry: 'off', styleguide: { recommendedFallback: true } };
35
+ });
36
+ process.env.REDOCLY_TELEMETRY = 'on';
37
+
38
+ const wrappedHandler = commandWrapper(handleLint);
39
+ await wrappedHandler({} as any);
40
+ expect(handleLint).toHaveBeenCalledTimes(1);
41
+
42
+ expect(sendTelemetry).toHaveBeenCalledTimes(0);
43
+ });
44
+
45
+ it('should pass files from arguments to config', async () => {
46
+ const filesToPush = ['test1.yaml', 'test2.yaml'];
47
+
48
+ const loadConfigMock = loadConfigAndHandleErrors as jest.Mock<any, any>;
49
+
50
+ const argv = {
51
+ files: filesToPush,
52
+ } as Arguments<PushOptions>;
53
+
54
+ await commandWrapper(handlePush)(argv);
55
+ expect(loadConfigMock).toHaveBeenCalledWith(expect.objectContaining({ files: filesToPush }));
56
+ });
57
+ });
@@ -0,0 +1,8 @@
1
+ import * as path from 'path';
2
+ import { exitWithError } from './utils';
3
+
4
+ try {
5
+ require('assert-node-version')(path.join(__dirname, '../'));
6
+ } catch (err) {
7
+ exitWithError(err.message);
8
+ }
@@ -0,0 +1,50 @@
1
+ import { loadAndBundleSpec } from 'redoc';
2
+ import { dirname, resolve } from 'path';
3
+ import { writeFileSync, mkdirSync } from 'fs';
4
+ import { performance } from 'perf_hooks';
5
+
6
+ import { getObjectOrJSON, getPageHTML } from './utils';
7
+ import type { BuildDocsArgv } from './types';
8
+ import { Config, getMergedConfig, isAbsoluteUrl } from '@redocly/openapi-core';
9
+ import { exitWithError, getExecutionTime, getFallbackApisOrExit } from '../../utils';
10
+
11
+ export const handlerBuildCommand = async (argv: BuildDocsArgv, configFromFile: Config) => {
12
+ const startedAt = performance.now();
13
+
14
+ const config = getMergedConfig(configFromFile, argv.api);
15
+
16
+ const apis = await getFallbackApisOrExit(argv.api ? [argv.api] : [], config);
17
+ const { path: pathToApi } = apis[0];
18
+
19
+ const options = {
20
+ output: argv.o,
21
+ title: argv.title,
22
+ disableGoogleFont: argv.disableGoogleFont,
23
+ templateFileName: argv.template,
24
+ templateOptions: argv.templateOptions || {},
25
+ redocOptions: getObjectOrJSON(argv.theme?.openapi, config),
26
+ };
27
+
28
+ const redocCurrentVersion = require('../../../package.json').dependencies.redoc.substring(1); // remove ~
29
+
30
+ try {
31
+ const elapsed = getExecutionTime(startedAt);
32
+
33
+ const api = await loadAndBundleSpec(isAbsoluteUrl(pathToApi) ? pathToApi : resolve(pathToApi));
34
+ const pageHTML = await getPageHTML(
35
+ api,
36
+ pathToApi,
37
+ { ...options, redocCurrentVersion },
38
+ argv.config
39
+ );
40
+
41
+ mkdirSync(dirname(options.output), { recursive: true });
42
+ writeFileSync(options.output, pageHTML);
43
+ const sizeInKiB = Math.ceil(Buffer.byteLength(pageHTML) / 1024);
44
+ process.stdout.write(
45
+ `\nšŸŽ‰ bundled successfully in: ${options.output} (${sizeInKiB} KiB) [ā± ${elapsed}].\n`
46
+ );
47
+ } catch (e) {
48
+ exitWithError(e);
49
+ }
50
+ };
@@ -0,0 +1,23 @@
1
+ <!DOCTYPE html>
2
+ <html>
3
+
4
+ <head>
5
+ <meta charset="utf8" />
6
+ <title>{{title}}</title>
7
+ <!-- needed for adaptive design -->
8
+ <meta name="viewport" content="width=device-width, initial-scale=1">
9
+ <style>
10
+ body {
11
+ padding: 0;
12
+ margin: 0;
13
+ }
14
+ </style>
15
+ {{{redocHead}}}
16
+ {{#unless disableGoogleFont}}<link href="https://fonts.googleapis.com/css?family=Montserrat:300,400,700|Roboto:300,400,700" rel="stylesheet">{{/unless}}
17
+ </head>
18
+
19
+ <body>
20
+ {{{redocHTML}}}
21
+ </body>
22
+
23
+ </html>