@redocly/cli 1.25.15 → 1.26.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.
package/CHANGELOG.md CHANGED
@@ -1,5 +1,26 @@
1
1
  # @redocly/cli
2
2
 
3
+ ## 1.26.1
4
+
5
+ ### Patch Changes
6
+
7
+ - Fixed an issue where an API alias's root path might be resolved incorrectly for configuration files located outside the root folder.
8
+ - Updated @redocly/openapi-core to v1.26.1.
9
+
10
+ ## 1.26.0
11
+
12
+ ### Minor Changes
13
+
14
+ - Introduced the `struct` rule and deprecated the `spec` rule.
15
+ Added the `spec` ruleset, which enforces compliance with the specifications.
16
+
17
+ ### Patch Changes
18
+
19
+ - Fixed an issue where the CLI would fail to run on Windows due to a breaking change in the Node.js API.
20
+ - Fixed an issue where `join` would throw an error when a glob pattern was provided.
21
+ - Updated `sourceDescriptions` to enforce a valid type field, ensuring compliance with the Arazzo specification.
22
+ - Updated @redocly/openapi-core to v1.26.0.
23
+
3
24
  ## 1.25.15
4
25
 
5
26
  ### Patch Changes
@@ -13,7 +13,29 @@ describe('handleJoin', () => {
13
13
  colloreteYellowMock.mockImplementation((string) => string);
14
14
  it('should call exitWithError because only one entrypoint', async () => {
15
15
  await (0, join_1.handleJoin)({ argv: { apis: ['first.yaml'] }, config: {}, version: 'cli-version' });
16
- expect(miscellaneous_1.exitWithError).toHaveBeenCalledWith(`At least 2 apis should be provided.`);
16
+ expect(miscellaneous_1.exitWithError).toHaveBeenCalledWith(`At least 2 APIs should be provided.`);
17
+ });
18
+ it('should call exitWithError if glob expands to less than 2 APIs', async () => {
19
+ miscellaneous_1.getFallbackApisOrExit.mockResolvedValueOnce([{ path: 'first.yaml' }]);
20
+ await (0, join_1.handleJoin)({
21
+ argv: { apis: ['*.yaml'] },
22
+ config: {},
23
+ version: 'cli-version',
24
+ });
25
+ expect(miscellaneous_1.exitWithError).toHaveBeenCalledWith(`At least 2 APIs should be provided.`);
26
+ });
27
+ it('should proceed if glob expands to 2 or more APIs', async () => {
28
+ openapi_core_1.detectSpec.mockReturnValue('oas3_1');
29
+ miscellaneous_1.getFallbackApisOrExit.mockResolvedValueOnce([
30
+ { path: 'first.yaml' },
31
+ { path: 'second.yaml' },
32
+ ]);
33
+ await (0, join_1.handleJoin)({
34
+ argv: { apis: ['*.yaml'] },
35
+ config: config_1.ConfigFixture,
36
+ version: 'cli-version',
37
+ });
38
+ expect(miscellaneous_1.exitWithError).not.toHaveBeenCalled();
17
39
  });
18
40
  it('should call exitWithError because passed all 3 options for tags', async () => {
19
41
  await (0, join_1.handleJoin)({
@@ -41,6 +63,7 @@ describe('handleJoin', () => {
41
63
  expect(miscellaneous_1.exitWithError).toHaveBeenCalledWith(`You use prefix-tags-with-filename, without-x-tag-groups together.\nPlease choose only one!`);
42
64
  });
43
65
  it('should call exitWithError because Only OpenAPI 3.0 and OpenAPI 3.1 are supported', async () => {
66
+ openapi_core_1.detectSpec.mockReturnValueOnce('oas2_0');
44
67
  await (0, join_1.handleJoin)({
45
68
  argv: {
46
69
  apis: ['first.yaml', 'second.yaml'],
@@ -1,6 +1,7 @@
1
1
  "use strict";
2
2
  Object.defineProperty(exports, "__esModule", { value: true });
3
3
  const miscellaneous_1 = require("../utils/miscellaneous");
4
+ const platform_1 = require("../utils/platform");
4
5
  const openapi_core_1 = require("@redocly/openapi-core");
5
6
  const colorette_1 = require("colorette");
6
7
  const fs_1 = require("fs");
@@ -407,7 +408,7 @@ describe('checkIfRulesetExist', () => {
407
408
  oas3_1: {},
408
409
  async2: {},
409
410
  async3: {},
410
- arazzo: {},
411
+ arazzo1: {},
411
412
  };
412
413
  expect(() => (0, miscellaneous_1.checkIfRulesetExist)(rules)).toThrowError('⚠️ No rules were configured. Learn how to configure rules: https://redocly.com/docs/cli/rules/');
413
414
  });
@@ -530,3 +531,63 @@ describe('writeToFileByExtension', () => {
530
531
  expect(process.stderr.write).toHaveBeenCalledWith(`test data`);
531
532
  });
532
533
  });
534
+ describe('runtime platform', () => {
535
+ describe('sanitizePath', () => {
536
+ test.each([
537
+ ['C:\\Program Files\\App', 'C:\\Program Files\\App'],
538
+ ['/usr/local/bin/app', '/usr/local/bin/app'],
539
+ ['invalid|path?name*', 'invalidpathname'],
540
+ ['', ''],
541
+ ['<>:"|?*', ':'],
542
+ ['C:/Program Files\\App', 'C:/Program Files\\App'],
543
+ ['path\nname\r', 'pathname'],
544
+ ['/usr/local; rm -rf /', '/usr/local rm -rf /'],
545
+ ['C:\\data&& dir', 'C:\\data dir'],
546
+ ])('should sanitize path %s to %s', (input, expected) => {
547
+ expect((0, platform_1.sanitizePath)(input)).toBe(expected);
548
+ });
549
+ });
550
+ describe('sanitizeLocale', () => {
551
+ test.each([
552
+ ['en-US', 'en-US'],
553
+ ['fr_FR', 'fr_FR'],
554
+ ['en<>US', 'enUS'],
555
+ ['fr@FR', 'fr@FR'],
556
+ ['en_US@#$%', 'en_US@'],
557
+ [' en-US ', 'en-US'],
558
+ ['', ''],
559
+ ])('should sanitize locale %s to %s', (input, expected) => {
560
+ expect((0, platform_1.sanitizeLocale)(input)).toBe(expected);
561
+ });
562
+ });
563
+ describe('getPlatformSpawnArgs', () => {
564
+ const originalPlatform = process.platform;
565
+ afterEach(() => {
566
+ Object.defineProperty(process, 'platform', {
567
+ value: originalPlatform,
568
+ });
569
+ });
570
+ it('should return args for Windows platform', () => {
571
+ Object.defineProperty(process, 'platform', {
572
+ value: 'win32',
573
+ });
574
+ const result = (0, platform_1.getPlatformSpawnArgs)();
575
+ expect(result).toEqual({
576
+ npxExecutableName: 'npx.cmd',
577
+ sanitize: expect.any(Function),
578
+ shell: true,
579
+ });
580
+ });
581
+ it('should return args for non-Windows platform', () => {
582
+ Object.defineProperty(process, 'platform', {
583
+ value: 'linux',
584
+ });
585
+ const result = (0, platform_1.getPlatformSpawnArgs)();
586
+ expect(result).toEqual({
587
+ npxExecutableName: 'npx',
588
+ sanitize: expect.any(Function),
589
+ shell: false,
590
+ });
591
+ });
592
+ });
593
+ });
@@ -1,6 +1,7 @@
1
1
  "use strict";
2
2
  Object.defineProperty(exports, "__esModule", { value: true });
3
3
  exports.handleBundle = handleBundle;
4
+ const path_1 = require("path");
4
5
  const perf_hooks_1 = require("perf_hooks");
5
6
  const colorette_1 = require("colorette");
6
7
  const fs_1 = require("fs");
@@ -20,7 +21,7 @@ async function handleBundle({ argv, config, version, collectSpecData, }) {
20
21
  const { styleguide } = resolvedConfig;
21
22
  styleguide.skipPreprocessors(argv['skip-preprocessor']);
22
23
  styleguide.skipDecorators(argv['skip-decorator']);
23
- process.stderr.write((0, colorette_1.gray)(`bundling ${path}...\n`));
24
+ process.stderr.write((0, colorette_1.gray)(`bundling ${(0, path_1.relative)(process.cwd(), path)}...\n`));
24
25
  const { bundle: result, problems, ...meta } = await (0, openapi_core_1.bundle)({
25
26
  config: resolvedConfig,
26
27
  ref: path,
@@ -66,14 +67,14 @@ async function handleBundle({ argv, config, version, collectSpecData, }) {
66
67
  const elapsed = (0, miscellaneous_1.getExecutionTime)(startedAt);
67
68
  if (fileTotals.errors > 0) {
68
69
  if (argv.force) {
69
- process.stderr.write(`❓ Created a bundle for ${(0, colorette_1.blue)(path)} at ${(0, colorette_1.blue)(outputFile || 'stdout')} with errors ${(0, colorette_1.green)(elapsed)}.\n${(0, colorette_1.yellow)('Errors ignored because of --force')}.\n`);
70
+ process.stderr.write(`❓ Created a bundle for ${(0, colorette_1.blue)((0, path_1.relative)(process.cwd(), path))} at ${(0, colorette_1.blue)(outputFile || 'stdout')} with errors ${(0, colorette_1.green)(elapsed)}.\n${(0, colorette_1.yellow)('Errors ignored because of --force')}.\n`);
70
71
  }
71
72
  else {
72
- process.stderr.write(`❌ Errors encountered while bundling ${(0, colorette_1.blue)(path)}: bundle not created (use --force to ignore errors).\n`);
73
+ process.stderr.write(`❌ Errors encountered while bundling ${(0, colorette_1.blue)((0, path_1.relative)(process.cwd(), path))}: bundle not created (use --force to ignore errors).\n`);
73
74
  }
74
75
  }
75
76
  else {
76
- process.stderr.write(`📦 Created a bundle for ${(0, colorette_1.blue)(path)} at ${(0, colorette_1.blue)(outputFile || 'stdout')} ${(0, colorette_1.green)(elapsed)}.\n`);
77
+ process.stderr.write(`📦 Created a bundle for ${(0, colorette_1.blue)((0, path_1.relative)(process.cwd(), path))} at ${(0, colorette_1.blue)(outputFile || 'stdout')} ${(0, colorette_1.green)(elapsed)}.\n`);
77
78
  }
78
79
  const removedCount = meta.visitorsData?.['remove-unused-components']?.removedCount;
79
80
  if (removedCount) {
@@ -2,17 +2,27 @@
2
2
  Object.defineProperty(exports, "__esModule", { value: true });
3
3
  exports.handleEject = void 0;
4
4
  const child_process_1 = require("child_process");
5
+ const platform_1 = require("../utils/platform");
5
6
  const handleEject = async ({ argv }) => {
6
7
  process.stdout.write(`\nLaunching eject using NPX.\n\n`);
7
- const npxExecutableName = process.platform === 'win32' ? 'npx.cmd' : 'npx';
8
- (0, child_process_1.spawn)(npxExecutableName, [
8
+ const { npxExecutableName, sanitize, shell } = (0, platform_1.getPlatformSpawnArgs)();
9
+ const path = sanitize(argv.path, platform_1.sanitizePath);
10
+ const projectDir = sanitize(argv['project-dir'], platform_1.sanitizePath);
11
+ const child = (0, child_process_1.spawn)(npxExecutableName, [
9
12
  '-y',
10
13
  '@redocly/realm',
11
14
  'eject',
12
15
  `${argv.type}`,
13
- `${argv.path ?? ''}`,
14
- `-d=${argv['project-dir']}`,
16
+ path,
17
+ `-d=${projectDir}`,
15
18
  argv.force ? `--force=${argv.force}` : '',
16
- ], { stdio: 'inherit' });
19
+ ], {
20
+ stdio: 'inherit',
21
+ shell,
22
+ });
23
+ child.on('error', (error) => {
24
+ process.stderr.write(`Eject launch failed: ${error.message}`);
25
+ throw new Error('Eject launch failed.');
26
+ });
17
27
  };
18
28
  exports.handleEject = handleEject;
@@ -15,11 +15,7 @@ const xTagGroups = 'x-tagGroups';
15
15
  let potentialConflictsTotal = 0;
16
16
  async function handleJoin({ argv, config, version: packageVersion, }) {
17
17
  const startedAt = perf_hooks_1.performance.now();
18
- if (argv.apis.length < 2) {
19
- return (0, miscellaneous_1.exitWithError)(`At least 2 apis should be provided.`);
20
- }
21
- const fileExtension = (0, miscellaneous_1.getAndValidateFileExtension)(argv.output || argv.apis[0]);
22
- const { 'prefix-components-with-info-prop': prefixComponentsWithInfoProp, 'prefix-tags-with-filename': prefixTagsWithFilename, 'prefix-tags-with-info-prop': prefixTagsWithInfoProp, 'without-x-tag-groups': withoutXTagGroups, output: specFilename = `openapi.${fileExtension}`, } = argv;
18
+ const { 'prefix-components-with-info-prop': prefixComponentsWithInfoProp, 'prefix-tags-with-filename': prefixTagsWithFilename, 'prefix-tags-with-info-prop': prefixTagsWithInfoProp, 'without-x-tag-groups': withoutXTagGroups, output, } = argv;
23
19
  const usedTagsOptions = [
24
20
  prefixTagsWithFilename && 'prefix-tags-with-filename',
25
21
  prefixTagsWithInfoProp && 'prefix-tags-with-info-prop',
@@ -29,6 +25,11 @@ async function handleJoin({ argv, config, version: packageVersion, }) {
29
25
  return (0, miscellaneous_1.exitWithError)(`You use ${(0, colorette_1.yellow)(usedTagsOptions.join(', '))} together.\nPlease choose only one!`);
30
26
  }
31
27
  const apis = await (0, miscellaneous_1.getFallbackApisOrExit)(argv.apis, config);
28
+ if (apis.length < 2) {
29
+ return (0, miscellaneous_1.exitWithError)(`At least 2 APIs should be provided.`);
30
+ }
31
+ const fileExtension = (0, miscellaneous_1.getAndValidateFileExtension)(output || apis[0].path);
32
+ const specFilename = output || `openapi.${fileExtension}`;
32
33
  const externalRefResolver = new openapi_core_1.BaseResolver(config.resolve);
33
34
  const documents = await Promise.all(apis.map(({ path }) => externalRefResolver.resolveDocument(null, path, true)));
34
35
  const decorators = new Set([
@@ -2,6 +2,7 @@
2
2
  Object.defineProperty(exports, "__esModule", { value: true });
3
3
  exports.handleLint = handleLint;
4
4
  exports.lintConfigCallback = lintConfigCallback;
5
+ const path_1 = require("path");
5
6
  const colorette_1 = require("colorette");
6
7
  const perf_hooks_1 = require("perf_hooks");
7
8
  const openapi_core_1 = require("@redocly/openapi-core");
@@ -31,7 +32,7 @@ async function handleLint({ argv, config, version, collectSpecData, }) {
31
32
  if (styleguide.recommendedFallback) {
32
33
  process.stderr.write(`No configurations were provided -- using built in ${(0, colorette_1.blue)('recommended')} configuration by default.\n\n`);
33
34
  }
34
- process.stderr.write((0, colorette_1.gray)(`validating ${path.replace(process.cwd(), '')}...\n`));
35
+ process.stderr.write((0, colorette_1.gray)(`validating ${(0, path_1.relative)(process.cwd(), path)}...\n`));
35
36
  const results = await (0, openapi_core_1.lint)({
36
37
  ref: path,
37
38
  config: resolvedConfig,
@@ -56,7 +57,7 @@ async function handleLint({ argv, config, version, collectSpecData, }) {
56
57
  });
57
58
  }
58
59
  const elapsed = (0, miscellaneous_1.getExecutionTime)(startedAt);
59
- process.stderr.write((0, colorette_1.gray)(`${path.replace(process.cwd(), '')}: validated in ${elapsed}\n\n`));
60
+ process.stderr.write((0, colorette_1.gray)(`${(0, path_1.relative)(process.cwd(), path)}: validated in ${elapsed}\n\n`));
60
61
  }
61
62
  catch (e) {
62
63
  (0, miscellaneous_1.handleError)(e, path);
@@ -9,10 +9,15 @@ function promptClientToken(domain) {
9
9
  return (0, miscellaneous_1.promptUser)((0, colorette_1.green)(`\n 🔑 Copy your API key from ${(0, colorette_1.blue)(`https://app.${domain}/profile`)} and paste it below`), true);
10
10
  }
11
11
  async function handleLogin({ argv, config }) {
12
- const region = argv.region || config.region;
13
- const client = new openapi_core_1.RedoclyClient(region);
14
- const clientToken = await promptClientToken(client.domain);
15
- process.stdout.write((0, colorette_1.gray)('\n Logging in...\n'));
16
- await client.login(clientToken, argv.verbose);
17
- process.stdout.write((0, colorette_1.green)(' Authorization confirmed. ✅\n\n'));
12
+ try {
13
+ const region = argv.region || config.region;
14
+ const client = new openapi_core_1.RedoclyClient(region);
15
+ const clientToken = await promptClientToken(client.domain);
16
+ process.stdout.write((0, colorette_1.gray)('\n Logging in...\n'));
17
+ await client.login(clientToken, argv.verbose);
18
+ process.stdout.write((0, colorette_1.green)(' Authorization confirmed. ✅\n\n'));
19
+ }
20
+ catch (err) {
21
+ (0, miscellaneous_1.exitWithError)(' ' + err?.message);
22
+ }
18
23
  }
@@ -5,6 +5,7 @@ const path = require("path");
5
5
  const fs_1 = require("fs");
6
6
  const child_process_1 = require("child_process");
7
7
  const constants_1 = require("./constants");
8
+ const platform_1 = require("../../utils/platform");
8
9
  const previewProject = async ({ argv }) => {
9
10
  const { plan, port } = argv;
10
11
  const projectDir = argv['project-dir'];
@@ -16,10 +17,15 @@ const previewProject = async ({ argv }) => {
16
17
  const productName = constants_1.PRODUCT_NAMES[product];
17
18
  const packageName = constants_1.PRODUCT_PACKAGES[product];
18
19
  process.stdout.write(`\nLaunching preview of ${productName} ${plan} using NPX.\n\n`);
19
- const npxExecutableName = process.platform === 'win32' ? 'npx.cmd' : 'npx';
20
- (0, child_process_1.spawn)(npxExecutableName, ['-y', packageName, 'preview', `--plan=${plan}`, `--port=${port || 4000}`], {
20
+ const { npxExecutableName, shell } = (0, platform_1.getPlatformSpawnArgs)();
21
+ const child = (0, child_process_1.spawn)(npxExecutableName, ['-y', packageName, 'preview', `--plan=${plan}`, `--port=${port || 4000}`], {
21
22
  stdio: 'inherit',
22
23
  cwd: projectDir,
24
+ shell,
25
+ });
26
+ child.on('error', (error) => {
27
+ process.stderr.write(`Project preview launch failed: ${error.message}`);
28
+ throw new Error(`Project preview launch failed.`);
23
29
  });
24
30
  };
25
31
  exports.previewProject = previewProject;
@@ -2,9 +2,19 @@
2
2
  Object.defineProperty(exports, "__esModule", { value: true });
3
3
  exports.handleTranslations = void 0;
4
4
  const child_process_1 = require("child_process");
5
+ const platform_1 = require("../utils/platform");
5
6
  const handleTranslations = async ({ argv }) => {
6
7
  process.stdout.write(`\nLaunching translate using NPX.\n\n`);
7
- const npxExecutableName = process.platform === 'win32' ? 'npx.cmd' : 'npx';
8
- (0, child_process_1.spawn)(npxExecutableName, ['-y', '@redocly/realm', 'translate', argv.locale, `-d=${argv['project-dir']}`], { stdio: 'inherit' });
8
+ const { npxExecutableName, sanitize, shell } = (0, platform_1.getPlatformSpawnArgs)();
9
+ const projectDir = sanitize(argv['project-dir'], platform_1.sanitizePath);
10
+ const locale = sanitize(argv.locale, platform_1.sanitizeLocale);
11
+ const child = (0, child_process_1.spawn)(npxExecutableName, ['-y', '@redocly/realm', 'translate', locale, `-d=${projectDir}`], {
12
+ stdio: 'inherit',
13
+ shell,
14
+ });
15
+ child.on('error', (error) => {
16
+ process.stderr.write(`Translate launch failed: ${error.message}`);
17
+ throw new Error(`Translate launch failed.`);
18
+ });
9
19
  };
10
20
  exports.handleTranslations = handleTranslations;
@@ -84,9 +84,11 @@ function getAliasOrPath(config, aliasOrPath) {
84
84
  const aliasApi = config.apis[aliasOrPath];
85
85
  return aliasApi
86
86
  ? {
87
- path: aliasApi.root,
87
+ path: (0, path_1.isAbsolute)(aliasApi.root)
88
+ ? aliasApi.root
89
+ : (0, path_1.resolve)(getConfigDirectory(config), aliasApi.root),
88
90
  alias: aliasOrPath,
89
- output: aliasApi.output,
91
+ output: aliasApi.output && (0, path_1.resolve)(getConfigDirectory(config), aliasApi.output),
90
92
  }
91
93
  : {
92
94
  path: aliasOrPath,
@@ -427,7 +429,7 @@ function checkIfRulesetExist(rules) {
427
429
  ...rules.oas3_1,
428
430
  ...rules.async2,
429
431
  ...rules.async3,
430
- ...rules.arazzo,
432
+ ...rules.arazzo1,
431
433
  };
432
434
  if ((0, utils_1.isEmptyObject)(ruleset)) {
433
435
  exitWithError('⚠️ No rules were configured. Learn how to configure rules: https://redocly.com/docs/cli/rules/');
@@ -0,0 +1,16 @@
1
+ /**
2
+ * Sanitizes the input path by removing invalid characters.
3
+ */
4
+ export declare const sanitizePath: (input: string) => string;
5
+ /**
6
+ * Sanitizes the input locale (ex. en-US) by removing invalid characters.
7
+ */
8
+ export declare const sanitizeLocale: (input: string) => string;
9
+ /**
10
+ * Retrieves platform-specific arguments and utilities.
11
+ */
12
+ export declare function getPlatformSpawnArgs(): {
13
+ npxExecutableName: string;
14
+ sanitize: (input: string | undefined, sanitizer: (input: string) => string) => string;
15
+ shell: boolean;
16
+ };
@@ -0,0 +1,34 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.sanitizeLocale = exports.sanitizePath = void 0;
4
+ exports.getPlatformSpawnArgs = getPlatformSpawnArgs;
5
+ /**
6
+ * Sanitizes the input path by removing invalid characters.
7
+ */
8
+ const sanitizePath = (input) => {
9
+ return input.replace(/[^a-zA-Z0-9 ._\-:\\/@]/g, '');
10
+ };
11
+ exports.sanitizePath = sanitizePath;
12
+ /**
13
+ * Sanitizes the input locale (ex. en-US) by removing invalid characters.
14
+ */
15
+ const sanitizeLocale = (input) => {
16
+ return input.replace(/[^a-zA-Z0-9@._-]/g, '');
17
+ };
18
+ exports.sanitizeLocale = sanitizeLocale;
19
+ /**
20
+ * Retrieves platform-specific arguments and utilities.
21
+ */
22
+ function getPlatformSpawnArgs() {
23
+ const isWindowsPlatform = process.platform === 'win32';
24
+ const npxExecutableName = isWindowsPlatform ? 'npx.cmd' : 'npx';
25
+ const sanitizeIfWindows = (input, sanitizer) => {
26
+ if (isWindowsPlatform && input) {
27
+ return sanitizer(input);
28
+ }
29
+ else {
30
+ return input || '';
31
+ }
32
+ };
33
+ return { npxExecutableName, sanitize: sanitizeIfWindows, shell: isWindowsPlatform };
34
+ }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@redocly/cli",
3
- "version": "1.25.15",
3
+ "version": "1.26.1",
4
4
  "description": "",
5
5
  "license": "MIT",
6
6
  "bin": {
@@ -36,7 +36,7 @@
36
36
  "Roman Hotsiy <roman@redocly.com> (https://redocly.com/)"
37
37
  ],
38
38
  "dependencies": {
39
- "@redocly/openapi-core": "1.25.15",
39
+ "@redocly/openapi-core": "1.26.1",
40
40
  "abort-controller": "^3.0.0",
41
41
  "chokidar": "^3.5.1",
42
42
  "colorette": "^1.2.0",
@@ -1,7 +1,11 @@
1
1
  import { yellow } from 'colorette';
2
2
  import { detectSpec } from '@redocly/openapi-core';
3
3
  import { handleJoin } from '../../commands/join';
4
- import { exitWithError, writeToFileByExtension } from '../../utils/miscellaneous';
4
+ import {
5
+ exitWithError,
6
+ getFallbackApisOrExit,
7
+ writeToFileByExtension,
8
+ } from '../../utils/miscellaneous';
5
9
  import { loadConfig } from '../../__mocks__/@redocly/openapi-core';
6
10
  import { ConfigFixture } from '../fixtures/config';
7
11
 
@@ -15,7 +19,35 @@ describe('handleJoin', () => {
15
19
 
16
20
  it('should call exitWithError because only one entrypoint', async () => {
17
21
  await handleJoin({ argv: { apis: ['first.yaml'] }, config: {} as any, version: 'cli-version' });
18
- expect(exitWithError).toHaveBeenCalledWith(`At least 2 apis should be provided.`);
22
+ expect(exitWithError).toHaveBeenCalledWith(`At least 2 APIs should be provided.`);
23
+ });
24
+
25
+ it('should call exitWithError if glob expands to less than 2 APIs', async () => {
26
+ (getFallbackApisOrExit as jest.Mock).mockResolvedValueOnce([{ path: 'first.yaml' }]);
27
+
28
+ await handleJoin({
29
+ argv: { apis: ['*.yaml'] },
30
+ config: {} as any,
31
+ version: 'cli-version',
32
+ });
33
+
34
+ expect(exitWithError).toHaveBeenCalledWith(`At least 2 APIs should be provided.`);
35
+ });
36
+
37
+ it('should proceed if glob expands to 2 or more APIs', async () => {
38
+ (detectSpec as jest.Mock).mockReturnValue('oas3_1');
39
+ (getFallbackApisOrExit as jest.Mock).mockResolvedValueOnce([
40
+ { path: 'first.yaml' },
41
+ { path: 'second.yaml' },
42
+ ]);
43
+
44
+ await handleJoin({
45
+ argv: { apis: ['*.yaml'] },
46
+ config: ConfigFixture as any,
47
+ version: 'cli-version',
48
+ });
49
+
50
+ expect(exitWithError).not.toHaveBeenCalled();
19
51
  });
20
52
 
21
53
  it('should call exitWithError because passed all 3 options for tags', async () => {
@@ -52,6 +84,7 @@ describe('handleJoin', () => {
52
84
  });
53
85
 
54
86
  it('should call exitWithError because Only OpenAPI 3.0 and OpenAPI 3.1 are supported', async () => {
87
+ (detectSpec as jest.Mock).mockReturnValueOnce('oas2_0');
55
88
  await handleJoin({
56
89
  argv: {
57
90
  apis: ['first.yaml', 'second.yaml'],
@@ -15,6 +15,7 @@ import {
15
15
  getAndValidateFileExtension,
16
16
  writeToFileByExtension,
17
17
  } from '../utils/miscellaneous';
18
+ import { sanitizeLocale, sanitizePath, getPlatformSpawnArgs } from '../utils/platform';
18
19
  import {
19
20
  ResolvedApi,
20
21
  Totals,
@@ -500,7 +501,7 @@ describe('checkIfRulesetExist', () => {
500
501
  oas3_1: {},
501
502
  async2: {},
502
503
  async3: {},
503
- arazzo: {},
504
+ arazzo1: {},
504
505
  };
505
506
  expect(() => checkIfRulesetExist(rules)).toThrowError(
506
507
  '⚠️ No rules were configured. Learn how to configure rules: https://redocly.com/docs/cli/rules/'
@@ -641,3 +642,73 @@ describe('writeToFileByExtension', () => {
641
642
  expect(process.stderr.write).toHaveBeenCalledWith(`test data`);
642
643
  });
643
644
  });
645
+
646
+ describe('runtime platform', () => {
647
+ describe('sanitizePath', () => {
648
+ test.each([
649
+ ['C:\\Program Files\\App', 'C:\\Program Files\\App'],
650
+ ['/usr/local/bin/app', '/usr/local/bin/app'],
651
+ ['invalid|path?name*', 'invalidpathname'],
652
+ ['', ''],
653
+ ['<>:"|?*', ':'],
654
+ ['C:/Program Files\\App', 'C:/Program Files\\App'],
655
+ ['path\nname\r', 'pathname'],
656
+ ['/usr/local; rm -rf /', '/usr/local rm -rf /'],
657
+ ['C:\\data&& dir', 'C:\\data dir'],
658
+ ])('should sanitize path %s to %s', (input, expected) => {
659
+ expect(sanitizePath(input)).toBe(expected);
660
+ });
661
+ });
662
+
663
+ describe('sanitizeLocale', () => {
664
+ test.each([
665
+ ['en-US', 'en-US'],
666
+ ['fr_FR', 'fr_FR'],
667
+ ['en<>US', 'enUS'],
668
+ ['fr@FR', 'fr@FR'],
669
+ ['en_US@#$%', 'en_US@'],
670
+ [' en-US ', 'en-US'],
671
+ ['', ''],
672
+ ])('should sanitize locale %s to %s', (input, expected) => {
673
+ expect(sanitizeLocale(input)).toBe(expected);
674
+ });
675
+ });
676
+
677
+ describe('getPlatformSpawnArgs', () => {
678
+ const originalPlatform = process.platform;
679
+
680
+ afterEach(() => {
681
+ Object.defineProperty(process, 'platform', {
682
+ value: originalPlatform,
683
+ });
684
+ });
685
+
686
+ it('should return args for Windows platform', () => {
687
+ Object.defineProperty(process, 'platform', {
688
+ value: 'win32',
689
+ });
690
+
691
+ const result = getPlatformSpawnArgs();
692
+
693
+ expect(result).toEqual({
694
+ npxExecutableName: 'npx.cmd',
695
+ sanitize: expect.any(Function),
696
+ shell: true,
697
+ });
698
+ });
699
+
700
+ it('should return args for non-Windows platform', () => {
701
+ Object.defineProperty(process, 'platform', {
702
+ value: 'linux',
703
+ });
704
+
705
+ const result = getPlatformSpawnArgs();
706
+
707
+ expect(result).toEqual({
708
+ npxExecutableName: 'npx',
709
+ sanitize: expect.any(Function),
710
+ shell: false,
711
+ });
712
+ });
713
+ });
714
+ });
@@ -1,3 +1,4 @@
1
+ import { relative } from 'path';
1
2
  import { performance } from 'perf_hooks';
2
3
  import { blue, gray, green, yellow } from 'colorette';
3
4
  import { writeFileSync } from 'fs';
@@ -54,7 +55,7 @@ export async function handleBundle({
54
55
  styleguide.skipPreprocessors(argv['skip-preprocessor']);
55
56
  styleguide.skipDecorators(argv['skip-decorator']);
56
57
 
57
- process.stderr.write(gray(`bundling ${path}...\n`));
58
+ process.stderr.write(gray(`bundling ${relative(process.cwd(), path)}...\n`));
58
59
 
59
60
  const {
60
61
  bundle: result,
@@ -117,22 +118,22 @@ export async function handleBundle({
117
118
  if (fileTotals.errors > 0) {
118
119
  if (argv.force) {
119
120
  process.stderr.write(
120
- `❓ Created a bundle for ${blue(path)} at ${blue(
121
+ `❓ Created a bundle for ${blue(relative(process.cwd(), path))} at ${blue(
121
122
  outputFile || 'stdout'
122
123
  )} with errors ${green(elapsed)}.\n${yellow('Errors ignored because of --force')}.\n`
123
124
  );
124
125
  } else {
125
126
  process.stderr.write(
126
127
  `❌ Errors encountered while bundling ${blue(
127
- path
128
+ relative(process.cwd(), path)
128
129
  )}: bundle not created (use --force to ignore errors).\n`
129
130
  );
130
131
  }
131
132
  } else {
132
133
  process.stderr.write(
133
- `📦 Created a bundle for ${blue(path)} at ${blue(outputFile || 'stdout')} ${green(
134
- elapsed
135
- )}.\n`
134
+ `📦 Created a bundle for ${blue(relative(process.cwd(), path))} at ${blue(
135
+ outputFile || 'stdout'
136
+ )} ${green(elapsed)}.\n`
136
137
  );
137
138
  }
138
139