@redocly/cli 1.3.0 → 1.4.0

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 (63) hide show
  1. package/CHANGELOG.md +12 -0
  2. package/lib/__mocks__/@redocly/openapi-core.d.ts +1 -0
  3. package/lib/__mocks__/@redocly/openapi-core.js +4 -3
  4. package/lib/__mocks__/utils.d.ts +2 -0
  5. package/lib/__mocks__/utils.js +3 -1
  6. package/lib/__tests__/commands/build-docs.test.js +2 -2
  7. package/lib/__tests__/commands/bundle.test.js +7 -7
  8. package/lib/__tests__/commands/join.test.js +25 -18
  9. package/lib/__tests__/commands/lint.test.js +15 -15
  10. package/lib/__tests__/commands/push-region.test.js +2 -2
  11. package/lib/__tests__/commands/push.test.js +30 -30
  12. package/lib/__tests__/fetch-with-timeout.test.js +2 -2
  13. package/lib/__tests__/utils.test.js +63 -32
  14. package/lib/__tests__/wrapper.test.js +3 -3
  15. package/lib/assert-node-version.js +1 -1
  16. package/lib/commands/build-docs/index.js +9 -9
  17. package/lib/commands/build-docs/types.d.ts +2 -2
  18. package/lib/commands/build-docs/utils.js +10 -10
  19. package/lib/commands/bundle.d.ts +1 -1
  20. package/lib/commands/bundle.js +25 -25
  21. package/lib/commands/join.d.ts +1 -1
  22. package/lib/commands/join.js +49 -48
  23. package/lib/commands/lint.d.ts +1 -1
  24. package/lib/commands/lint.js +22 -22
  25. package/lib/commands/login.d.ts +1 -1
  26. package/lib/commands/login.js +3 -3
  27. package/lib/commands/preview-docs/index.d.ts +1 -1
  28. package/lib/commands/preview-docs/index.js +7 -7
  29. package/lib/commands/preview-docs/preview-server/hot.js +19 -2
  30. package/lib/commands/preview-docs/preview-server/preview-server.js +15 -14
  31. package/lib/commands/preview-docs/preview-server/server.d.ts +3 -1
  32. package/lib/commands/preview-docs/preview-server/server.js +2 -2
  33. package/lib/commands/push.d.ts +2 -2
  34. package/lib/commands/push.js +31 -31
  35. package/lib/commands/split/__tests__/index.test.js +9 -9
  36. package/lib/commands/split/index.d.ts +2 -2
  37. package/lib/commands/split/index.js +41 -40
  38. package/lib/commands/split/types.d.ts +2 -2
  39. package/lib/commands/split/types.js +2 -2
  40. package/lib/commands/stats.d.ts +1 -1
  41. package/lib/commands/stats.js +9 -9
  42. package/lib/fetch-with-timeout.js +5 -2
  43. package/lib/index.js +11 -12
  44. package/lib/types.d.ts +6 -6
  45. package/lib/update-version-notifier.js +18 -18
  46. package/lib/utils.d.ts +6 -3
  47. package/lib/utils.js +66 -38
  48. package/lib/wrapper.js +5 -5
  49. package/package.json +3 -3
  50. package/src/__mocks__/@redocly/openapi-core.ts +1 -0
  51. package/src/__mocks__/utils.ts +2 -0
  52. package/src/__tests__/commands/join.test.ts +37 -7
  53. package/src/__tests__/utils.test.ts +45 -1
  54. package/src/commands/join.ts +8 -3
  55. package/src/commands/preview-docs/preview-server/hot.js +19 -2
  56. package/src/commands/preview-docs/preview-server/preview-server.ts +6 -4
  57. package/src/commands/preview-docs/preview-server/server.ts +2 -2
  58. package/src/commands/split/__tests__/index.test.ts +14 -5
  59. package/src/commands/split/index.ts +25 -17
  60. package/src/fetch-with-timeout.ts +3 -0
  61. package/src/index.ts +0 -1
  62. package/src/utils.ts +40 -1
  63. package/tsconfig.tsbuildinfo +1 -1
@@ -26,18 +26,19 @@ function handleJoin(argv, config, packageVersion) {
26
26
  return __awaiter(this, void 0, void 0, function* () {
27
27
  const startedAt = perf_hooks_1.performance.now();
28
28
  if (argv.apis.length < 2) {
29
- return utils_1.exitWithError(`At least 2 apis should be provided. \n\n`);
29
+ return (0, utils_1.exitWithError)(`At least 2 apis should be provided. \n\n`);
30
30
  }
31
- 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.yaml', } = argv;
31
+ const fileExtension = (0, utils_1.getAndValidateFileExtension)(argv.output || argv.apis[0]);
32
+ 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;
32
33
  const usedTagsOptions = [
33
34
  prefixTagsWithFilename && 'prefix-tags-with-filename',
34
35
  prefixTagsWithInfoProp && 'prefix-tags-with-info-prop',
35
36
  withoutXTagGroups && 'without-x-tag-groups',
36
37
  ].filter(Boolean);
37
38
  if (usedTagsOptions.length > 1) {
38
- return utils_1.exitWithError(`You use ${colorette_1.yellow(usedTagsOptions.join(', '))} together.\nPlease choose only one! \n\n`);
39
+ return (0, utils_1.exitWithError)(`You use ${(0, colorette_1.yellow)(usedTagsOptions.join(', '))} together.\nPlease choose only one! \n\n`);
39
40
  }
40
- const apis = yield utils_1.getFallbackApisOrExit(argv.apis, config);
41
+ const apis = yield (0, utils_1.getFallbackApisOrExit)(argv.apis, config);
41
42
  const externalRefResolver = new openapi_core_1.BaseResolver(config.resolve);
42
43
  const documents = yield Promise.all(apis.map(({ path }) => externalRefResolver.resolveDocument(null, path, true)));
43
44
  if (!argv.decorate) {
@@ -56,37 +57,37 @@ function handleJoin(argv, config, packageVersion) {
56
57
  ]);
57
58
  config.styleguide.skipPreprocessors(Array.from(preprocessors));
58
59
  }
59
- const bundleResults = yield Promise.all(documents.map((document) => openapi_core_1.bundleDocument({
60
+ const bundleResults = yield Promise.all(documents.map((document) => (0, openapi_core_1.bundleDocument)({
60
61
  document,
61
62
  config: config.styleguide,
62
63
  externalRefResolver: new openapi_core_1.BaseResolver(config.resolve),
63
64
  }).catch((e) => {
64
- utils_1.exitWithError(`${e.message}: ${colorette_1.blue(document.source.absoluteRef)}`);
65
+ (0, utils_1.exitWithError)(`${e.message}: ${(0, colorette_1.blue)(document.source.absoluteRef)}`);
65
66
  })));
66
67
  for (const { problems, bundle: document } of bundleResults) {
67
- const fileTotals = openapi_core_1.getTotals(problems);
68
+ const fileTotals = (0, openapi_core_1.getTotals)(problems);
68
69
  if (fileTotals.errors) {
69
- openapi_core_1.formatProblems(problems, {
70
+ (0, openapi_core_1.formatProblems)(problems, {
70
71
  totals: fileTotals,
71
72
  version: document.parsed.version,
72
73
  });
73
- utils_1.exitWithError(`❌ Errors encountered while bundling ${colorette_1.blue(document.source.absoluteRef)}: join will not proceed.\n`);
74
+ (0, utils_1.exitWithError)(`❌ Errors encountered while bundling ${(0, colorette_1.blue)(document.source.absoluteRef)}: join will not proceed.\n`);
74
75
  }
75
76
  }
76
77
  let oasVersion = null;
77
78
  for (const document of documents) {
78
79
  try {
79
- const version = openapi_core_1.detectSpec(document.parsed);
80
+ const version = (0, openapi_core_1.detectSpec)(document.parsed);
80
81
  if (version !== openapi_core_1.SpecVersion.OAS3_0 && version !== openapi_core_1.SpecVersion.OAS3_1) {
81
- return utils_1.exitWithError(`Only OpenAPI 3.0 and OpenAPI 3.1 are supported: ${colorette_1.blue(document.source.absoluteRef)} \n\n`);
82
+ return (0, utils_1.exitWithError)(`Only OpenAPI 3.0 and OpenAPI 3.1 are supported: ${(0, colorette_1.blue)(document.source.absoluteRef)} \n\n`);
82
83
  }
83
84
  oasVersion = oasVersion !== null && oasVersion !== void 0 ? oasVersion : version;
84
85
  if (oasVersion !== version) {
85
- return utils_1.exitWithError(`All APIs must use the same OpenAPI version: ${colorette_1.blue(document.source.absoluteRef)} \n\n`);
86
+ return (0, utils_1.exitWithError)(`All APIs must use the same OpenAPI version: ${(0, colorette_1.blue)(document.source.absoluteRef)} \n\n`);
86
87
  }
87
88
  }
88
89
  catch (e) {
89
- return utils_1.exitWithError(`${e.message}: ${colorette_1.blue(document.source.absoluteRef)}`);
90
+ return (0, utils_1.exitWithError)(`${e.message}: ${(0, colorette_1.blue)(document.source.absoluteRef)}`);
90
91
  }
91
92
  }
92
93
  if (argv.lint) {
@@ -112,7 +113,7 @@ function handleJoin(argv, config, packageVersion) {
112
113
  : getInfoPrefix(info, prefixTagsWithInfoProp, 'tags');
113
114
  const componentsPrefix = getInfoPrefix(info, prefixComponentsWithInfoProp, COMPONENTS);
114
115
  if (openapi.hasOwnProperty('x-tagGroups')) {
115
- process.stderr.write(colorette_1.yellow(`warning: x-tagGroups at ${colorette_1.blue(api)} will be skipped \n`));
116
+ process.stderr.write((0, colorette_1.yellow)(`warning: x-tagGroups at ${(0, colorette_1.blue)(api)} will be skipped \n`));
116
117
  }
117
118
  const context = {
118
119
  api,
@@ -138,10 +139,10 @@ function handleJoin(argv, config, packageVersion) {
138
139
  iteratePotentialConflicts(potentialConflicts, withoutXTagGroups);
139
140
  const noRefs = true;
140
141
  if (potentialConflictsTotal) {
141
- return utils_1.exitWithError(`Please fix conflicts before running ${colorette_1.yellow('join')}.`);
142
+ return (0, utils_1.exitWithError)(`Please fix conflicts before running ${(0, colorette_1.yellow)('join')}.`);
142
143
  }
143
- utils_1.writeYaml(utils_1.sortTopLevelKeysForOas(joinedDef), specFilename, noRefs);
144
- utils_1.printExecutionTime('join', startedAt, specFilename);
144
+ (0, utils_1.writeToFileByExtension)((0, utils_1.sortTopLevelKeysForOas)(joinedDef), specFilename, noRefs);
145
+ (0, utils_1.printExecutionTime)('join', startedAt, specFilename);
145
146
  function populateTags({ api, apiFilename, tags, potentialConflicts, tagsPrefix, componentsPrefix, }) {
146
147
  if (!joinedDef.hasOwnProperty(Tags)) {
147
148
  joinedDef[Tags] = [];
@@ -237,7 +238,7 @@ function handleJoin(argv, config, packageVersion) {
237
238
  const { externalDocs } = openapi;
238
239
  if (externalDocs) {
239
240
  if (joinedDef.hasOwnProperty('externalDocs')) {
240
- process.stderr.write(colorette_1.yellow(`warning: skip externalDocs from ${colorette_1.blue(path.basename(api))} \n`));
241
+ process.stderr.write((0, colorette_1.yellow)(`warning: skip externalDocs from ${(0, colorette_1.blue)(path.basename(api))} \n`));
241
242
  return;
242
243
  }
243
244
  joinedDef['externalDocs'] = externalDocs;
@@ -245,12 +246,12 @@ function handleJoin(argv, config, packageVersion) {
245
246
  }
246
247
  function collectPaths(openapi, { apiFilename, api, potentialConflicts, tagsPrefix, componentsPrefix }) {
247
248
  const { paths } = openapi;
248
- const operationsSet = new Set(js_utils_1.keysOf(types_1.OPENAPI3_METHOD));
249
+ const operationsSet = new Set((0, js_utils_1.keysOf)(types_1.OPENAPI3_METHOD));
249
250
  if (paths) {
250
251
  if (!joinedDef.hasOwnProperty('paths')) {
251
252
  joinedDef['paths'] = {};
252
253
  }
253
- for (const path of js_utils_1.keysOf(paths)) {
254
+ for (const path of (0, js_utils_1.keysOf)(paths)) {
254
255
  if (!joinedDef.paths.hasOwnProperty(path)) {
255
256
  joinedDef.paths[path] = {};
256
257
  }
@@ -258,7 +259,7 @@ function handleJoin(argv, config, packageVersion) {
258
259
  potentialConflicts.paths[path] = {};
259
260
  }
260
261
  const pathItem = paths[path];
261
- for (const field of js_utils_1.keysOf(pathItem)) {
262
+ for (const field of (0, js_utils_1.keysOf)(pathItem)) {
262
263
  if (operationsSet.has(field)) {
263
264
  collectPathOperation(pathItem, path, field);
264
265
  }
@@ -278,7 +279,7 @@ function handleJoin(argv, config, packageVersion) {
278
279
  const fieldValue = pathItem[field];
279
280
  if (joinedDef.paths[path].hasOwnProperty(field) &&
280
281
  joinedDef.paths[path][field] !== fieldValue) {
281
- process.stderr.write(colorette_1.yellow(`warning: different ${field} values in ${path}\n`));
282
+ process.stderr.write((0, colorette_1.yellow)(`warning: different ${field} values in ${path}\n`));
282
283
  return;
283
284
  }
284
285
  joinedDef.paths[path][field] = fieldValue;
@@ -295,7 +296,7 @@ function handleJoin(argv, config, packageVersion) {
295
296
  for (const pathServer of joinedDef.paths[path].servers) {
296
297
  if (pathServer.url === server.url) {
297
298
  if (!isServersEqual(pathServer, server)) {
298
- utils_1.exitWithError(`Different server values for (${server.url}) in ${path}`);
299
+ (0, utils_1.exitWithError)(`Different server values for (${server.url}) in ${path}`);
299
300
  }
300
301
  isFoundServer = true;
301
302
  }
@@ -317,16 +318,16 @@ function handleJoin(argv, config, packageVersion) {
317
318
  for (const pathParameter of joinedDef.paths[path]
318
319
  .parameters) {
319
320
  // Compare $ref only if both are reference objects
320
- if (openapi_core_1.isRef(pathParameter) && openapi_core_1.isRef(parameter)) {
321
+ if ((0, openapi_core_1.isRef)(pathParameter) && (0, openapi_core_1.isRef)(parameter)) {
321
322
  if (pathParameter['$ref'] === parameter['$ref']) {
322
323
  isFoundParameter = true;
323
324
  }
324
325
  }
325
326
  // Compare properties only if both are reference objects
326
- if (!openapi_core_1.isRef(pathParameter) && !openapi_core_1.isRef(parameter)) {
327
+ if (!(0, openapi_core_1.isRef)(pathParameter) && !(0, openapi_core_1.isRef)(parameter)) {
327
328
  if (pathParameter.name === parameter.name && pathParameter.in === parameter.in) {
328
329
  if (!isEqual(pathParameter.schema, parameter.schema)) {
329
- utils_1.exitWithError(`Different parameter schemas for (${parameter.name}) in ${path}`);
330
+ (0, utils_1.exitWithError)(`Different parameter schemas for (${parameter.name}) in ${path}`);
330
331
  }
331
332
  isFoundParameter = true;
332
333
  }
@@ -457,9 +458,9 @@ function handleJoin(argv, config, packageVersion) {
457
458
  const openapi = firstApi.parsed;
458
459
  const componentsPrefix = getInfoPrefix(openapi.info, prefixComponentsWithInfoProp, COMPONENTS);
459
460
  if (!openapi.openapi)
460
- utils_1.exitWithError('Version of specification is not found in. \n');
461
+ (0, utils_1.exitWithError)('Version of specification is not found in. \n');
461
462
  if (!openapi.info)
462
- utils_1.exitWithError('Info section is not found in specification. \n');
463
+ (0, utils_1.exitWithError)('Info section is not found in specification. \n');
463
464
  if ((_a = openapi.info) === null || _a === void 0 ? void 0 : _a.description) {
464
465
  openapi.info.description = addComponentsPrefix(openapi.info.description, componentsPrefix);
465
466
  }
@@ -491,7 +492,7 @@ function iteratePotentialConflicts(potentialConflicts, withoutXTagGroups) {
491
492
  for (const [_, conflict] of Object.entries(conflicts)) {
492
493
  if (validateComponentsDifference(conflict[1])) {
493
494
  conflict[1] = conflict[1].map((c) => Object.keys(c)[0]);
494
- showConflicts(colorette_1.green(group) + ' => ' + key, [conflict]);
495
+ showConflicts((0, colorette_1.green)(group) + ' => ' + key, [conflict]);
495
496
  potentialConflictsTotal += 1;
496
497
  }
497
498
  }
@@ -502,7 +503,7 @@ function iteratePotentialConflicts(potentialConflicts, withoutXTagGroups) {
502
503
  }
503
504
  else {
504
505
  potentialConflictsTotal += conflicts.length;
505
- showConflicts(colorette_1.green(group) + ' => ' + key, conflicts);
506
+ showConflicts((0, colorette_1.green)(group) + ' => ' + key, conflicts);
506
507
  }
507
508
  }
508
509
  if (group === 'tags' && !withoutXTagGroups) {
@@ -514,15 +515,15 @@ function iteratePotentialConflicts(potentialConflicts, withoutXTagGroups) {
514
515
  }
515
516
  function duplicateTagDescriptionWarning(conflicts) {
516
517
  const tagsKeys = conflicts.map(([tagName]) => `\`${tagName}\``);
517
- const joinString = colorette_1.yellow(', ');
518
- process.stderr.write(colorette_1.yellow(`\nwarning: ${tagsKeys.length} conflict(s) on the ${colorette_1.red(tagsKeys.join(joinString))} tags description.\n`));
518
+ const joinString = (0, colorette_1.yellow)(', ');
519
+ process.stderr.write((0, colorette_1.yellow)(`\nwarning: ${tagsKeys.length} conflict(s) on the ${(0, colorette_1.red)(tagsKeys.join(joinString))} tags description.\n`));
519
520
  }
520
521
  function prefixTagSuggestion(conflictsLength) {
521
- process.stderr.write(colorette_1.green(`\n${conflictsLength} conflict(s) on tags.\nSuggestion: please use ${colorette_1.blue('prefix-tags-with-filename')}, ${colorette_1.blue('prefix-tags-with-info-prop')} or ${colorette_1.blue('without-x-tag-groups')} to prevent naming conflicts.\n\n`));
522
+ process.stderr.write((0, colorette_1.green)(`\n${conflictsLength} conflict(s) on tags.\nSuggestion: please use ${(0, colorette_1.blue)('prefix-tags-with-filename')}, ${(0, colorette_1.blue)('prefix-tags-with-info-prop')} or ${(0, colorette_1.blue)('without-x-tag-groups')} to prevent naming conflicts.\n\n`));
522
523
  }
523
524
  function showConflicts(key, conflicts) {
524
525
  for (const [path, files] of conflicts) {
525
- process.stderr.write(colorette_1.yellow(`Conflict on ${key} : ${colorette_1.red(path)} in files: ${colorette_1.blue(files)} \n`));
526
+ process.stderr.write((0, colorette_1.yellow)(`Conflict on ${key} : ${(0, colorette_1.red)(path)} in files: ${(0, colorette_1.blue)(files)} \n`));
526
527
  }
527
528
  }
528
529
  function filterConflicts(entities) {
@@ -555,30 +556,30 @@ function getInfoPrefix(info, prefixArg, type) {
555
556
  if (!prefixArg)
556
557
  return '';
557
558
  if (!info)
558
- utils_1.exitWithError('Info section is not found in specification. \n');
559
+ (0, utils_1.exitWithError)('Info section is not found in specification. \n');
559
560
  if (!info[prefixArg])
560
- utils_1.exitWithError(`${colorette_1.yellow(`prefix-${type}-with-info-prop`)} argument value is not found in info section. \n`);
561
- if (!js_utils_1.isString(info[prefixArg]))
562
- utils_1.exitWithError(`${colorette_1.yellow(`prefix-${type}-with-info-prop`)} argument value should be string. \n\n`);
561
+ (0, utils_1.exitWithError)(`${(0, colorette_1.yellow)(`prefix-${type}-with-info-prop`)} argument value is not found in info section. \n`);
562
+ if (!(0, js_utils_1.isString)(info[prefixArg]))
563
+ (0, utils_1.exitWithError)(`${(0, colorette_1.yellow)(`prefix-${type}-with-info-prop`)} argument value should be string. \n\n`);
563
564
  if (info[prefixArg].length > 50)
564
- utils_1.exitWithError(`${colorette_1.yellow(`prefix-${type}-with-info-prop`)} argument value length should not exceed 50 characters. \n\n`);
565
+ (0, utils_1.exitWithError)(`${(0, colorette_1.yellow)(`prefix-${type}-with-info-prop`)} argument value length should not exceed 50 characters. \n\n`);
565
566
  return info[prefixArg];
566
567
  }
567
568
  function validateApi(document, config, externalRefResolver, packageVersion) {
568
569
  return __awaiter(this, void 0, void 0, function* () {
569
570
  try {
570
- const results = yield openapi_core_1.lintDocument({ document, config, externalRefResolver });
571
- const fileTotals = openapi_core_1.getTotals(results);
572
- openapi_core_1.formatProblems(results, { format: 'stylish', totals: fileTotals, version: packageVersion });
573
- utils_1.printLintTotals(fileTotals, 2);
571
+ const results = yield (0, openapi_core_1.lintDocument)({ document, config, externalRefResolver });
572
+ const fileTotals = (0, openapi_core_1.getTotals)(results);
573
+ (0, openapi_core_1.formatProblems)(results, { format: 'stylish', totals: fileTotals, version: packageVersion });
574
+ (0, utils_1.printLintTotals)(fileTotals, 2);
574
575
  }
575
576
  catch (err) {
576
- utils_1.handleError(err, document.parsed);
577
+ (0, utils_1.handleError)(err, document.parsed);
577
578
  }
578
579
  });
579
580
  }
580
581
  function crawl(object, visitor) {
581
- if (!js_utils_1.isObject(object))
582
+ if (!(0, js_utils_1.isObject)(object))
582
583
  return;
583
584
  for (const key of Object.keys(object)) {
584
585
  visitor(object, key);
@@ -587,16 +588,16 @@ function crawl(object, visitor) {
587
588
  }
588
589
  function replace$Refs(obj, componentsPrefix) {
589
590
  crawl(obj, (node) => {
590
- if (node.$ref && js_utils_1.isString(node.$ref) && node.$ref.startsWith(`#/${COMPONENTS}/`)) {
591
+ if (node.$ref && (0, js_utils_1.isString)(node.$ref) && node.$ref.startsWith(`#/${COMPONENTS}/`)) {
591
592
  const name = path.basename(node.$ref);
592
593
  node.$ref = node.$ref.replace(name, componentsPrefix + '_' + name);
593
594
  }
594
595
  else if (node.discriminator &&
595
596
  node.discriminator.mapping &&
596
- js_utils_1.isObject(node.discriminator.mapping)) {
597
+ (0, js_utils_1.isObject)(node.discriminator.mapping)) {
597
598
  const { mapping } = node.discriminator;
598
599
  for (const name of Object.keys(mapping)) {
599
- if (js_utils_1.isString(mapping[name]) && mapping[name].startsWith(`#/${COMPONENTS}/`)) {
600
+ if ((0, js_utils_1.isString)(mapping[name]) && mapping[name].startsWith(`#/${COMPONENTS}/`)) {
600
601
  mapping[name] = mapping[name]
601
602
  .split('/')
602
603
  .map((name, i, arr) => {
@@ -1,7 +1,7 @@
1
1
  import { Config } from '@redocly/openapi-core';
2
2
  import type { OutputFormat, RawConfig, RuleSeverity } from '@redocly/openapi-core';
3
3
  import type { CommandOptions, Skips } from '../types';
4
- export declare type LintOptions = {
4
+ export type LintOptions = {
5
5
  apis?: string[];
6
6
  'max-problems': number;
7
7
  extends?: string[];
@@ -17,9 +17,9 @@ const colorette_1 = require("colorette");
17
17
  const perf_hooks_1 = require("perf_hooks");
18
18
  function handleLint(argv, config, version) {
19
19
  return __awaiter(this, void 0, void 0, function* () {
20
- const apis = yield utils_1.getFallbackApisOrExit(argv.apis, config);
20
+ const apis = yield (0, utils_1.getFallbackApisOrExit)(argv.apis, config);
21
21
  if (!apis.length) {
22
- utils_1.exitWithError('No APIs were provided');
22
+ (0, utils_1.exitWithError)('No APIs were provided');
23
23
  }
24
24
  if (argv['generate-ignore-file']) {
25
25
  config.styleguide.ignore = {}; // clear ignore
@@ -30,20 +30,20 @@ function handleLint(argv, config, version) {
30
30
  for (const { path, alias } of apis) {
31
31
  try {
32
32
  const startedAt = perf_hooks_1.performance.now();
33
- const resolvedConfig = openapi_core_1.getMergedConfig(config, alias);
33
+ const resolvedConfig = (0, openapi_core_1.getMergedConfig)(config, alias);
34
34
  const { styleguide } = resolvedConfig;
35
- utils_1.checkIfRulesetExist(styleguide.rules);
35
+ (0, utils_1.checkIfRulesetExist)(styleguide.rules);
36
36
  styleguide.skipRules(argv['skip-rule']);
37
37
  styleguide.skipPreprocessors(argv['skip-preprocessor']);
38
38
  if (styleguide.recommendedFallback) {
39
- process.stderr.write(`No configurations were provided -- using built in ${colorette_1.blue('recommended')} configuration by default.\n\n`);
39
+ process.stderr.write(`No configurations were provided -- using built in ${(0, colorette_1.blue)('recommended')} configuration by default.\n\n`);
40
40
  }
41
- process.stderr.write(colorette_1.gray(`validating ${path.replace(process.cwd(), '')}...\n`));
42
- const results = yield openapi_core_1.lint({
41
+ process.stderr.write((0, colorette_1.gray)(`validating ${path.replace(process.cwd(), '')}...\n`));
42
+ const results = yield (0, openapi_core_1.lint)({
43
43
  ref: path,
44
44
  config: resolvedConfig,
45
45
  });
46
- const fileTotals = openapi_core_1.getTotals(results);
46
+ const fileTotals = (0, openapi_core_1.getTotals)(results);
47
47
  totals.errors += fileTotals.errors;
48
48
  totals.warnings += fileTotals.warnings;
49
49
  totals.ignored += fileTotals.ignored;
@@ -54,28 +54,28 @@ function handleLint(argv, config, version) {
54
54
  }
55
55
  }
56
56
  else {
57
- openapi_core_1.formatProblems(results, {
57
+ (0, openapi_core_1.formatProblems)(results, {
58
58
  format: argv.format,
59
59
  maxProblems: argv['max-problems'],
60
60
  totals: fileTotals,
61
61
  version,
62
62
  });
63
63
  }
64
- const elapsed = utils_1.getExecutionTime(startedAt);
65
- process.stderr.write(colorette_1.gray(`${path.replace(process.cwd(), '')}: validated in ${elapsed}\n\n`));
64
+ const elapsed = (0, utils_1.getExecutionTime)(startedAt);
65
+ process.stderr.write((0, colorette_1.gray)(`${path.replace(process.cwd(), '')}: validated in ${elapsed}\n\n`));
66
66
  }
67
67
  catch (e) {
68
- utils_1.handleError(e, path);
68
+ (0, utils_1.handleError)(e, path);
69
69
  }
70
70
  }
71
71
  if (argv['generate-ignore-file']) {
72
72
  config.styleguide.saveIgnore();
73
- process.stderr.write(`Generated ignore file with ${totalIgnored} ${utils_1.pluralize('problem', totalIgnored)}.\n\n`);
73
+ process.stderr.write(`Generated ignore file with ${totalIgnored} ${(0, utils_1.pluralize)('problem', totalIgnored)}.\n\n`);
74
74
  }
75
75
  else {
76
- utils_1.printLintTotals(totals, apis.length);
76
+ (0, utils_1.printLintTotals)(totals, apis.length);
77
77
  }
78
- utils_1.printUnusedWarnings(config.styleguide);
78
+ (0, utils_1.printUnusedWarnings)(config.styleguide);
79
79
  if (!(totals.errors === 0 || argv['generate-ignore-file'])) {
80
80
  throw new Error('Lint failed.');
81
81
  }
@@ -91,21 +91,21 @@ function lintConfigCallback(argv, version) {
91
91
  return;
92
92
  }
93
93
  return (config) => __awaiter(this, void 0, void 0, function* () {
94
- const configPath = openapi_core_1.findConfig(argv.config) || '';
95
- const stringYaml = openapi_core_1.stringifyYaml(config);
96
- const configContent = openapi_core_1.makeDocumentFromString(stringYaml, configPath);
97
- const problems = yield openapi_core_1.lintConfig({
94
+ const configPath = (0, openapi_core_1.findConfig)(argv.config) || '';
95
+ const stringYaml = (0, openapi_core_1.stringifyYaml)(config);
96
+ const configContent = (0, openapi_core_1.makeDocumentFromString)(stringYaml, configPath);
97
+ const problems = yield (0, openapi_core_1.lintConfig)({
98
98
  document: configContent,
99
99
  severity: (argv['lint-config'] || 'warn'),
100
100
  });
101
- const fileTotals = openapi_core_1.getTotals(problems);
102
- openapi_core_1.formatProblems(problems, {
101
+ const fileTotals = (0, openapi_core_1.getTotals)(problems);
102
+ (0, openapi_core_1.formatProblems)(problems, {
103
103
  format: argv.format,
104
104
  maxProblems: argv['max-problems'],
105
105
  totals: fileTotals,
106
106
  version,
107
107
  });
108
- utils_1.printConfigLintTotals(fileTotals);
108
+ (0, utils_1.printConfigLintTotals)(fileTotals);
109
109
  if (fileTotals.errors > 0) {
110
110
  throw new config_1.ConfigValidationError();
111
111
  }
@@ -1,6 +1,6 @@
1
1
  import { Region, Config } from '@redocly/openapi-core';
2
2
  export declare function promptClientToken(domain: string): Promise<string>;
3
- export declare type LoginOptions = {
3
+ export type LoginOptions = {
4
4
  verbose?: boolean;
5
5
  region?: Region;
6
6
  config?: string;
@@ -14,7 +14,7 @@ const openapi_core_1 = require("@redocly/openapi-core");
14
14
  const colorette_1 = require("colorette");
15
15
  const utils_1 = require("../utils");
16
16
  function promptClientToken(domain) {
17
- return utils_1.promptUser(colorette_1.green(`\n 🔑 Copy your API key from ${colorette_1.blue(`https://app.${domain}/profile`)} and paste it below`), true);
17
+ return (0, utils_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);
18
18
  }
19
19
  exports.promptClientToken = promptClientToken;
20
20
  function handleLogin(argv, config) {
@@ -22,9 +22,9 @@ function handleLogin(argv, config) {
22
22
  const region = argv.region || config.region;
23
23
  const client = new openapi_core_1.RedoclyClient(region);
24
24
  const clientToken = yield promptClientToken(client.domain);
25
- process.stdout.write(colorette_1.gray('\n Logging in...\n'));
25
+ process.stdout.write((0, colorette_1.gray)('\n Logging in...\n'));
26
26
  yield client.login(clientToken, argv.verbose);
27
- process.stdout.write(colorette_1.green(' Authorization confirmed. ✅\n\n'));
27
+ process.stdout.write((0, colorette_1.green)(' Authorization confirmed. ✅\n\n'));
28
28
  });
29
29
  }
30
30
  exports.handleLogin = handleLogin;
@@ -1,6 +1,6 @@
1
1
  import { Config } from '@redocly/openapi-core';
2
2
  import type { Skips } from '../../types';
3
- export declare type PreviewDocsOptions = {
3
+ export type PreviewDocsOptions = {
4
4
  port: number;
5
5
  host: string;
6
6
  'use-community-edition'?: boolean;
@@ -20,7 +20,7 @@ function previewDocs(argv, configFromFile) {
20
20
  let isAuthorizedWithRedocly = false;
21
21
  let redocOptions = {};
22
22
  let config = yield reloadConfig(configFromFile);
23
- const apis = yield utils_1.getFallbackApisOrExit(argv.api ? [argv.api] : [], config);
23
+ const apis = yield (0, utils_1.getFallbackApisOrExit)(argv.api ? [argv.api] : [], config);
24
24
  const api = apis[0];
25
25
  let cachedBundle;
26
26
  const deps = new Set();
@@ -33,7 +33,7 @@ function previewDocs(argv, configFromFile) {
33
33
  return __awaiter(this, void 0, void 0, function* () {
34
34
  process.stdout.write('\nBundling...\n\n');
35
35
  try {
36
- const { bundle: openapiBundle, problems, fileDependencies, } = yield openapi_core_1.bundle({
36
+ const { bundle: openapiBundle, problems, fileDependencies, } = yield (0, openapi_core_1.bundle)({
37
37
  ref: api.path,
38
38
  config,
39
39
  });
@@ -42,7 +42,7 @@ function previewDocs(argv, configFromFile) {
42
42
  watcher.add([...fileDependencies]);
43
43
  deps.clear();
44
44
  fileDependencies.forEach(deps.add, deps);
45
- const fileTotals = openapi_core_1.getTotals(problems);
45
+ const fileTotals = (0, openapi_core_1.getTotals)(problems);
46
46
  if (fileTotals.errors === 0) {
47
47
  process.stdout.write(fileTotals.errors === 0
48
48
  ? `Created a bundle for ${api.alias || api.path} ${fileTotals.warnings > 0 ? 'with warnings' : 'successfully'}\n`
@@ -51,7 +51,7 @@ function previewDocs(argv, configFromFile) {
51
51
  return openapiBundle.parsed;
52
52
  }
53
53
  catch (e) {
54
- utils_1.handleError(e, api.path);
54
+ (0, utils_1.handleError)(e, api.path);
55
55
  }
56
56
  });
57
57
  }
@@ -62,7 +62,7 @@ function previewDocs(argv, configFromFile) {
62
62
  if (!isAuthorized) {
63
63
  process.stderr.write(`Using Redoc community edition.\nLogin with redocly ${colorette.blue('login')} or use an enterprise license key to preview with the premium docs.\n\n`);
64
64
  }
65
- const hotClients = yield preview_server_1.default(argv.port, argv.host, {
65
+ const hotClients = yield (0, preview_server_1.default)(argv.port, argv.host, {
66
66
  getBundle,
67
67
  getOptions: () => redocOptions,
68
68
  useRedocPro: isAuthorized && !redocOptions.useCommunityEdition,
@@ -97,7 +97,7 @@ function previewDocs(argv, configFromFile) {
97
97
  return __awaiter(this, void 0, void 0, function* () {
98
98
  if (!config) {
99
99
  try {
100
- config = (yield utils_1.loadConfigAndHandleErrors({ configPath: argv.config }));
100
+ config = (yield (0, utils_1.loadConfigAndHandleErrors)({ configPath: argv.config }));
101
101
  }
102
102
  catch (err) {
103
103
  config = new openapi_core_1.Config({ apis: {}, styleguide: {} });
@@ -105,7 +105,7 @@ function previewDocs(argv, configFromFile) {
105
105
  }
106
106
  const redoclyClient = new openapi_core_1.RedoclyClient();
107
107
  isAuthorizedWithRedocly = yield redoclyClient.isAuthorizedWithRedocly();
108
- const resolvedConfig = openapi_core_1.getMergedConfig(config, argv.api);
108
+ const resolvedConfig = (0, openapi_core_1.getMergedConfig)(config, argv.api);
109
109
  const { styleguide } = resolvedConfig;
110
110
  styleguide.skipPreprocessors(argv['skip-preprocessor']);
111
111
  styleguide.skipDecorators(argv['skip-decorator']);
@@ -1,13 +1,29 @@
1
1
  (function run() {
2
2
  const Socket = window.SimpleWebsocket;
3
3
  const port = window.__OPENAPI_CLI_WS_PORT;
4
+ const host = window.__OPENAPI_CLI_WS_HOST;
4
5
 
5
6
  let socket;
6
7
 
7
8
  reconnect();
8
9
 
10
+ function getFormattedHost() {
11
+ // Use localhost when bound to all interfaces
12
+ if (host === '::' || host === '0.0.0.0') {
13
+ return 'localhost';
14
+ }
15
+
16
+ // Other IPv6 addresses must be wrapped in brackets
17
+ if (host.includes('::')) {
18
+ return `[${host}]`;
19
+ }
20
+
21
+ // Otherwise return as-is
22
+ return host;
23
+ }
24
+
9
25
  function reconnect() {
10
- socket = new Socket(`ws://127.0.0.1:${port}`);
26
+ socket = new Socket(`ws://${getFormattedHost()}:${port}`);
11
27
  socket.on('connect', () => {
12
28
  socket.send('{"type": "ping"}');
13
29
  });
@@ -29,13 +45,14 @@
29
45
 
30
46
  socket.on('close', () => {
31
47
  socket.destroy();
32
- console.log('Connection lost, trying to reconnect in 4s');
48
+ console.log('[hot] Connection lost, trying to reconnect in 4s');
33
49
  setTimeout(() => {
34
50
  reconnect();
35
51
  }, 4000);
36
52
  });
37
53
 
38
54
  socket.on('error', () => {
55
+ console.log('[hot] Error connecting to hot reloading server');
39
56
  socket.destroy();
40
57
  });
41
58
  }
@@ -16,18 +16,19 @@ const fs_1 = require("fs");
16
16
  const path = require("path");
17
17
  const server_1 = require("./server");
18
18
  const utils_1 = require("../../../utils");
19
- function getPageHTML(htmlTemplate, redocOptions = {}, useRedocPro, wsPort) {
20
- let templateSrc = fs_1.readFileSync(htmlTemplate, 'utf-8');
19
+ function getPageHTML(htmlTemplate, redocOptions = {}, useRedocPro, wsPort, host) {
20
+ let templateSrc = (0, fs_1.readFileSync)(htmlTemplate, 'utf-8');
21
21
  // fix template for backward compatibility
22
22
  templateSrc = templateSrc
23
23
  .replace(/{?{{redocHead}}}?/, '{{{redocHead}}}')
24
24
  .replace('{{redocBody}}', '{{{redocHTML}}}');
25
- const template = handlebars_1.compile(templateSrc);
25
+ const template = (0, handlebars_1.compile)(templateSrc);
26
26
  return template({
27
27
  redocHead: `
28
28
  <script>
29
29
  window.__REDOC_EXPORT = '${useRedocPro ? 'RedoclyReferenceDocs' : 'Redoc'}';
30
30
  window.__OPENAPI_CLI_WS_PORT = ${wsPort};
31
+ window.__OPENAPI_CLI_WS_HOST = "${host}";
31
32
  </script>
32
33
  <script src="/simplewebsocket.min.js"></script>
33
34
  <script src="/hot.js"></script>
@@ -54,14 +55,14 @@ function startPreviewServer(port, host, { getBundle, getOptions, useRedocPro, })
54
55
  console.time(colorette.dim(`GET ${request.url}`));
55
56
  const { htmlTemplate } = getOptions() || {};
56
57
  if (((_a = request.url) === null || _a === void 0 ? void 0 : _a.endsWith('/')) || path.extname(request.url) === '') {
57
- server_1.respondWithGzip(getPageHTML(htmlTemplate || defaultTemplate, getOptions(), useRedocPro, wsPort), request, response, {
58
+ (0, server_1.respondWithGzip)(getPageHTML(htmlTemplate || defaultTemplate, getOptions(), useRedocPro, wsPort, host), request, response, {
58
59
  'Content-Type': 'text/html',
59
60
  });
60
61
  }
61
62
  else if (request.url === '/openapi.json') {
62
63
  const bundle = yield getBundle();
63
64
  if (bundle === undefined) {
64
- server_1.respondWithGzip(JSON.stringify({
65
+ (0, server_1.respondWithGzip)(JSON.stringify({
65
66
  openapi: '3.0.0',
66
67
  info: {
67
68
  description: '<code> Failed to generate bundle: check out console output for more details </code>',
@@ -72,7 +73,7 @@ function startPreviewServer(port, host, { getBundle, getOptions, useRedocPro, })
72
73
  });
73
74
  }
74
75
  else {
75
- server_1.respondWithGzip(JSON.stringify(bundle), request, response, {
76
+ (0, server_1.respondWithGzip)(JSON.stringify(bundle), request, response, {
76
77
  'Content-Type': 'application/json',
77
78
  });
78
79
  }
@@ -89,8 +90,8 @@ function startPreviewServer(port, host, { getBundle, getOptions, useRedocPro, })
89
90
  if (!filePath) {
90
91
  const basePath = htmlTemplate ? path.dirname(htmlTemplate) : process.cwd();
91
92
  filePath = path.resolve(basePath, `.${request.url}`);
92
- if (!utils_1.isSubdir(basePath, filePath)) {
93
- server_1.respondWithGzip('404 Not Found', request, response, { 'Content-Type': 'text/html' }, 404);
93
+ if (!(0, utils_1.isSubdir)(basePath, filePath)) {
94
+ (0, server_1.respondWithGzip)('404 Not Found', request, response, { 'Content-Type': 'text/html' }, 404);
94
95
  console.timeEnd(colorette.dim(`GET ${request.url}`));
95
96
  return;
96
97
  }
@@ -98,27 +99,27 @@ function startPreviewServer(port, host, { getBundle, getOptions, useRedocPro, })
98
99
  const extname = String(path.extname(filePath)).toLowerCase();
99
100
  const contentType = server_1.mimeTypes[extname] || 'application/octet-stream';
100
101
  try {
101
- server_1.respondWithGzip(yield fs_1.promises.readFile(filePath), request, response, {
102
+ (0, server_1.respondWithGzip)(yield fs_1.promises.readFile(filePath), request, response, {
102
103
  'Content-Type': contentType,
103
104
  });
104
105
  }
105
106
  catch (e) {
106
107
  if (e.code === 'ENOENT') {
107
- server_1.respondWithGzip('404 Not Found', request, response, { 'Content-Type': 'text/html' }, 404);
108
+ (0, server_1.respondWithGzip)('404 Not Found', request, response, { 'Content-Type': 'text/html' }, 404);
108
109
  }
109
110
  else {
110
- server_1.respondWithGzip(`Something went wrong: ${e.code || e.message}...\n`, request, response, {}, 500);
111
+ (0, server_1.respondWithGzip)(`Something went wrong: ${e.code || e.message}...\n`, request, response, {}, 500);
111
112
  }
112
113
  }
113
114
  }
114
115
  console.timeEnd(colorette.dim(`GET ${request.url}`));
115
116
  });
116
- const wsPort = yield get_port_please_1.getPort({ portRange: [32201, 32301] });
117
- const server = server_1.startHttpServer(port, host, handler);
117
+ const wsPort = yield (0, get_port_please_1.getPort)({ port: 32201, portRange: [32201, 32301], host });
118
+ const server = (0, server_1.startHttpServer)(port, host, handler);
118
119
  server.on('listening', () => {
119
120
  process.stdout.write(`\n 🔎 Preview server running at ${colorette.blue(`http://${host}:${port}\n`)}`);
120
121
  });
121
- return server_1.startWsServer(wsPort);
122
+ return (0, server_1.startWsServer)(wsPort, host);
122
123
  });
123
124
  }
124
125
  exports.default = startPreviewServer;