@redocly/cli 1.0.0-beta.96

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 (79) hide show
  1. package/README.md +39 -0
  2. package/bin/cli.js +3 -0
  3. package/lib/__mocks__/utils.d.ts +17 -0
  4. package/lib/__mocks__/utils.js +14 -0
  5. package/lib/__tests__/commands/bundle.test.d.ts +1 -0
  6. package/lib/__tests__/commands/bundle.test.js +92 -0
  7. package/lib/__tests__/commands/push-region.test.d.ts +1 -0
  8. package/lib/__tests__/commands/push-region.test.js +55 -0
  9. package/lib/__tests__/commands/push.test.d.ts +1 -0
  10. package/lib/__tests__/commands/push.test.js +153 -0
  11. package/lib/__tests__/utils.test.d.ts +1 -0
  12. package/lib/__tests__/utils.test.js +41 -0
  13. package/lib/assert-node-version.d.ts +1 -0
  14. package/lib/assert-node-version.js +10 -0
  15. package/lib/commands/bundle.d.ts +19 -0
  16. package/lib/commands/bundle.js +128 -0
  17. package/lib/commands/join.d.ts +7 -0
  18. package/lib/commands/join.js +421 -0
  19. package/lib/commands/lint.d.ts +11 -0
  20. package/lib/commands/lint.js +80 -0
  21. package/lib/commands/login.d.ts +6 -0
  22. package/lib/commands/login.js +28 -0
  23. package/lib/commands/preview-docs/index.d.ts +12 -0
  24. package/lib/commands/preview-docs/index.js +141 -0
  25. package/lib/commands/preview-docs/preview-server/default.hbs +24 -0
  26. package/lib/commands/preview-docs/preview-server/hot.js +42 -0
  27. package/lib/commands/preview-docs/preview-server/oauth2-redirect.html +21 -0
  28. package/lib/commands/preview-docs/preview-server/preview-server.d.ts +5 -0
  29. package/lib/commands/preview-docs/preview-server/preview-server.js +120 -0
  30. package/lib/commands/preview-docs/preview-server/server.d.ts +23 -0
  31. package/lib/commands/preview-docs/preview-server/server.js +85 -0
  32. package/lib/commands/push.d.ts +25 -0
  33. package/lib/commands/push.js +247 -0
  34. package/lib/commands/split/__tests__/index.test.d.ts +1 -0
  35. package/lib/commands/split/__tests__/index.test.js +70 -0
  36. package/lib/commands/split/index.d.ts +8 -0
  37. package/lib/commands/split/index.js +279 -0
  38. package/lib/commands/split/types.d.ts +37 -0
  39. package/lib/commands/split/types.js +52 -0
  40. package/lib/commands/stats.d.ts +5 -0
  41. package/lib/commands/stats.js +92 -0
  42. package/lib/index.d.ts +2 -0
  43. package/lib/index.js +269 -0
  44. package/lib/js-utils.d.ts +3 -0
  45. package/lib/js-utils.js +16 -0
  46. package/lib/types.d.ts +13 -0
  47. package/lib/types.js +5 -0
  48. package/lib/utils.d.ts +28 -0
  49. package/lib/utils.js +260 -0
  50. package/package.json +54 -0
  51. package/src/__mocks__/utils.ts +11 -0
  52. package/src/__tests__/commands/bundle.test.ts +120 -0
  53. package/src/__tests__/commands/push-region.test.ts +51 -0
  54. package/src/__tests__/commands/push.test.ts +156 -0
  55. package/src/__tests__/utils.test.ts +50 -0
  56. package/src/assert-node-version.ts +8 -0
  57. package/src/commands/bundle.ts +178 -0
  58. package/src/commands/join.ts +488 -0
  59. package/src/commands/lint.ts +110 -0
  60. package/src/commands/login.ts +19 -0
  61. package/src/commands/preview-docs/index.ts +188 -0
  62. package/src/commands/preview-docs/preview-server/default.hbs +24 -0
  63. package/src/commands/preview-docs/preview-server/hot.js +42 -0
  64. package/src/commands/preview-docs/preview-server/oauth2-redirect.html +21 -0
  65. package/src/commands/preview-docs/preview-server/preview-server.ts +150 -0
  66. package/src/commands/preview-docs/preview-server/server.ts +91 -0
  67. package/src/commands/push.ts +355 -0
  68. package/src/commands/split/__tests__/fixtures/spec.json +70 -0
  69. package/src/commands/split/__tests__/fixtures/webhooks.json +88 -0
  70. package/src/commands/split/__tests__/index.test.ts +96 -0
  71. package/src/commands/split/index.ts +349 -0
  72. package/src/commands/split/types.ts +73 -0
  73. package/src/commands/stats.ts +115 -0
  74. package/src/index.ts +311 -0
  75. package/src/js-utils.ts +12 -0
  76. package/src/types.ts +13 -0
  77. package/src/utils.ts +300 -0
  78. package/tsconfig.json +9 -0
  79. package/tsconfig.tsbuildinfo +1 -0
@@ -0,0 +1,141 @@
1
+ "use strict";
2
+ var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
3
+ function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
4
+ return new (P || (P = Promise))(function (resolve, reject) {
5
+ function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
6
+ function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
7
+ function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
8
+ step((generator = generator.apply(thisArg, _arguments || [])).next());
9
+ });
10
+ };
11
+ Object.defineProperty(exports, "__esModule", { value: true });
12
+ exports.debounce = exports.previewDocs = void 0;
13
+ const colorette = require("colorette");
14
+ const chockidar = require("chokidar");
15
+ const openapi_core_1 = require("@redocly/openapi-core");
16
+ const utils_1 = require("../../utils");
17
+ const preview_server_1 = require("./preview-server/preview-server");
18
+ function previewDocs(argv) {
19
+ return __awaiter(this, void 0, void 0, function* () {
20
+ let isAuthorizedWithRedocly = false;
21
+ let redocOptions = {};
22
+ let config = yield reloadConfig();
23
+ const entrypoints = yield utils_1.getFallbackEntryPointsOrExit(argv.entrypoint ? [argv.entrypoint] : [], config);
24
+ const entrypoint = entrypoints[0];
25
+ let cachedBundle;
26
+ const deps = new Set();
27
+ function getBundle() {
28
+ return __awaiter(this, void 0, void 0, function* () {
29
+ return cachedBundle;
30
+ });
31
+ }
32
+ function updateBundle() {
33
+ return __awaiter(this, void 0, void 0, function* () {
34
+ process.stdout.write('\nBundling...\n\n');
35
+ try {
36
+ const { bundle: openapiBundle, problems, fileDependencies, } = yield openapi_core_1.bundle({
37
+ ref: entrypoint.path,
38
+ config,
39
+ });
40
+ const removed = [...deps].filter((x) => !fileDependencies.has(x));
41
+ watcher.unwatch(removed);
42
+ watcher.add([...fileDependencies]);
43
+ deps.clear();
44
+ fileDependencies.forEach(deps.add, deps);
45
+ const fileTotals = openapi_core_1.getTotals(problems);
46
+ if (fileTotals.errors === 0) {
47
+ process.stdout.write(fileTotals.errors === 0
48
+ ? `Created a bundle for ${entrypoint.alias || entrypoint.path} ${fileTotals.warnings > 0 ? 'with warnings' : 'successfully'}\n`
49
+ : colorette.yellow(`Created a bundle for ${entrypoint.alias || entrypoint.path} with errors. Docs may be broken or not accurate\n`));
50
+ }
51
+ return openapiBundle.parsed;
52
+ }
53
+ catch (e) {
54
+ handleError(e, entrypoint.path);
55
+ }
56
+ });
57
+ }
58
+ setImmediate(() => {
59
+ cachedBundle = updateBundle();
60
+ }); // initial cache
61
+ const isAuthorized = isAuthorizedWithRedocly || redocOptions.licenseKey;
62
+ if (!isAuthorized) {
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
+ }
65
+ const hotClients = yield preview_server_1.default(argv.port, argv.host, {
66
+ getBundle,
67
+ getOptions: () => redocOptions,
68
+ useRedocPro: isAuthorized && !redocOptions.useCommunityEdition,
69
+ });
70
+ const watchPaths = [entrypoint.path, config.configFile].filter((e) => !!e);
71
+ const watcher = chockidar.watch(watchPaths, {
72
+ disableGlobbing: true,
73
+ ignoreInitial: true,
74
+ });
75
+ const debouncedUpdatedBundle = debounce(() => __awaiter(this, void 0, void 0, function* () {
76
+ cachedBundle = updateBundle();
77
+ yield cachedBundle;
78
+ hotClients.broadcast('{"type": "reload", "bundle": true}');
79
+ }), 2000);
80
+ const changeHandler = (type, file) => __awaiter(this, void 0, void 0, function* () {
81
+ process.stdout.write(`${colorette.green('watch')} ${type} ${colorette.blue(file)}\n`);
82
+ if (file === config.configFile) {
83
+ config = yield reloadConfig();
84
+ hotClients.broadcast(JSON.stringify({ type: 'reload' }));
85
+ return;
86
+ }
87
+ debouncedUpdatedBundle();
88
+ });
89
+ watcher.on('change', changeHandler.bind(undefined, 'changed'));
90
+ watcher.on('add', changeHandler.bind(undefined, 'added'));
91
+ watcher.on('unlink', changeHandler.bind(undefined, 'removed'));
92
+ watcher.on('ready', () => {
93
+ process.stdout.write(`\n 👀 Watching ${colorette.blue(entrypoint.path)} and all related resources for changes\n\n`);
94
+ });
95
+ function reloadConfig() {
96
+ return __awaiter(this, void 0, void 0, function* () {
97
+ let config = yield openapi_core_1.loadConfig(argv.config);
98
+ const redoclyClient = new openapi_core_1.RedoclyClient();
99
+ isAuthorizedWithRedocly = yield redoclyClient.isAuthorizedWithRedocly();
100
+ const resolvedConfig = openapi_core_1.getMergedConfig(config, argv.entrypoint);
101
+ resolvedConfig.lint.skipRules(argv['skip-rule']);
102
+ resolvedConfig.lint.skipPreprocessors(argv['skip-preprocessor']);
103
+ resolvedConfig.lint.skipDecorators(argv['skip-decorator']);
104
+ const referenceDocs = resolvedConfig['features.openapi'];
105
+ redocOptions = Object.assign(Object.assign({}, referenceDocs), { useCommunityEdition: argv['use-community-edition'] || referenceDocs.useCommunityEdition, licenseKey: process.env.REDOCLY_LICENSE_KEY || referenceDocs.licenseKey });
106
+ return resolvedConfig;
107
+ });
108
+ }
109
+ });
110
+ }
111
+ exports.previewDocs = previewDocs;
112
+ function debounce(func, wait, immediate) {
113
+ let timeout;
114
+ return function executedFunction(...args) {
115
+ // @ts-ignore
116
+ const context = this;
117
+ const later = () => {
118
+ timeout = null;
119
+ if (!immediate)
120
+ func.apply(context, args);
121
+ };
122
+ const callNow = immediate && !timeout;
123
+ if (timeout)
124
+ clearTimeout(timeout);
125
+ timeout = setTimeout(later, wait);
126
+ if (callNow)
127
+ func.apply(context, args);
128
+ };
129
+ }
130
+ exports.debounce = debounce;
131
+ function handleError(e, ref) {
132
+ if (e instanceof openapi_core_1.ResolveError) {
133
+ process.stderr.write(`Failed to resolve entrypoint definition at ${ref}:\n\n - ${e.message}.\n\n`);
134
+ }
135
+ else if (e instanceof openapi_core_1.YamlParseError) {
136
+ process.stderr.write(`Failed to parse entrypoint definition at ${ref}:\n\n - ${e.message}.\n\n`);
137
+ }
138
+ else {
139
+ process.stderr.write(`Something went wrong when processing ${ref}:\n\n - ${e.message}.\n\n`);
140
+ }
141
+ }
@@ -0,0 +1,24 @@
1
+
2
+ <!DOCTYPE html>
3
+ <html>
4
+
5
+ <head>
6
+ <meta charset="utf8" />
7
+ <title>{{title}}</title>
8
+ <!-- needed for adaptive design -->
9
+ <meta name="viewport" content="width=device-width, initial-scale=1">
10
+ <style>
11
+ body {
12
+ padding: 0;
13
+ margin: 0;
14
+ }
15
+ </style>
16
+ {{{redocHead}}}
17
+ <link href="https://fonts.googleapis.com/css?family=Montserrat:300,400,700|Roboto:300,400,700" rel="stylesheet">
18
+ </head>
19
+
20
+ <body>
21
+ {{{redocHTML}}}
22
+ </body>
23
+
24
+ </html>
@@ -0,0 +1,42 @@
1
+ (function run() {
2
+ const Socket = window.SimpleWebsocket;
3
+ const port = window.__OPENAPI_CLI_WS_PORT;
4
+
5
+ let socket;
6
+
7
+ reconnect();
8
+
9
+ function reconnect() {
10
+ socket = new Socket(`ws://127.0.0.1:${port}`);
11
+ socket.on('connect', () => {
12
+ socket.send('{"type": "ping"}');
13
+ });
14
+
15
+ socket.on('data', (data) => {
16
+ const message = JSON.parse(data);
17
+ switch (message.type) {
18
+ case 'pong':
19
+ console.log('[hot] hot reloading connected');
20
+ break;
21
+ case 'reload':
22
+ console.log('[hot] full page reload');
23
+ window.location.reload();
24
+ break;
25
+ default:
26
+ console.log(`[hot] ${message.type} received`);
27
+ }
28
+ });
29
+
30
+ socket.on('close', () => {
31
+ socket.destroy();
32
+ console.log('Connection lost, trying to reconnect in 4s');
33
+ setTimeout(() => {
34
+ reconnect();
35
+ }, 4000);
36
+ });
37
+
38
+ socket.on('error', () => {
39
+ socket.destroy();
40
+ });
41
+ }
42
+ })();
@@ -0,0 +1,21 @@
1
+ <!DOCTYPE html>
2
+ <html lang="en">
3
+ <head>
4
+ <meta charset="utf-8" />
5
+ <meta name="viewport" content="width=device-width,initial-scale=1,shrink-to-fit=no" />
6
+ <title>Redocly Reference Docs: OAuth2 Redirect</title>
7
+ <style>
8
+ .user-info {
9
+ margin: 150px auto auto;
10
+ width: 50%;
11
+ background-color: whitesmoke;
12
+ padding: 20px;
13
+ text-align: center;
14
+ }
15
+ </style>
16
+ </head>
17
+ <body>
18
+ <script src="https://cdn.jsdelivr.net/npm/@redocly/reference-docs@latest/dist/oauth2-redirect.js"></script>
19
+ <noscript>You need to enable JavaScript to run this app.</noscript>
20
+ </body>
21
+ </html>
@@ -0,0 +1,5 @@
1
+ export default function startPreviewServer(port: number, host: string, { getBundle, getOptions, useRedocPro, }: {
2
+ getBundle: Function;
3
+ getOptions: Function;
4
+ useRedocPro: boolean;
5
+ }): Promise<any>;
@@ -0,0 +1,120 @@
1
+ "use strict";
2
+ var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
3
+ function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
4
+ return new (P || (P = Promise))(function (resolve, reject) {
5
+ function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
6
+ function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
7
+ function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
8
+ step((generator = generator.apply(thisArg, _arguments || [])).next());
9
+ });
10
+ };
11
+ Object.defineProperty(exports, "__esModule", { value: true });
12
+ const handlebars_1 = require("handlebars");
13
+ const colorette = require("colorette");
14
+ const portfinder = require("portfinder");
15
+ const fs_1 = require("fs");
16
+ const path = require("path");
17
+ const server_1 = require("./server");
18
+ const utils_1 = require("../../../utils");
19
+ function getPageHTML(htmlTemplate, redocOptions = {}, useRedocPro, wsPort) {
20
+ let templateSrc = fs_1.readFileSync(htmlTemplate, 'utf-8');
21
+ // fix template for backward compatibility
22
+ templateSrc = templateSrc
23
+ .replace(/{?{{redocHead}}}?/, '{{{redocHead}}}')
24
+ .replace('{{redocBody}}', '{{{redocHTML}}}');
25
+ const template = handlebars_1.compile(templateSrc);
26
+ return template({
27
+ redocHead: `
28
+ <script>
29
+ window.__REDOC_EXPORT = '${useRedocPro ? 'RedoclyReferenceDocs' : 'Redoc'}';
30
+ window.__OPENAPI_CLI_WS_PORT = ${wsPort};
31
+ </script>
32
+ <script src="/simplewebsocket.min.js"></script>
33
+ <script src="/hot.js"></script>
34
+ <script src="${useRedocPro
35
+ ? 'https://cdn.jsdelivr.net/npm/@redocly/reference-docs@latest/dist/redocly-reference-docs.min.js'
36
+ : 'https://cdn.jsdelivr.net/npm/redoc@latest/bundles/redoc.standalone.js'}"></script>
37
+ `,
38
+ redocHTML: `
39
+ <div id="redoc"></div>
40
+ <script>
41
+ var container = document.getElementById('redoc');
42
+ ${useRedocPro
43
+ ? "window[window.__REDOC_EXPORT].setPublicPath('https://cdn.jsdelivr.net/npm/@redocly/reference-docs@latest/dist/');"
44
+ : ''}
45
+ window[window.__REDOC_EXPORT].init("/openapi.json", ${JSON.stringify(redocOptions)}, container)
46
+ </script>`,
47
+ });
48
+ }
49
+ function startPreviewServer(port, host, { getBundle, getOptions, useRedocPro, }) {
50
+ return __awaiter(this, void 0, void 0, function* () {
51
+ const defaultTemplate = path.join(__dirname, 'default.hbs');
52
+ const handler = (request, response) => __awaiter(this, void 0, void 0, function* () {
53
+ var _a;
54
+ console.time(colorette.dim(`GET ${request.url}`));
55
+ const { htmlTemplate } = getOptions() || {};
56
+ 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
+ 'Content-Type': 'text/html',
59
+ });
60
+ }
61
+ else if (request.url === '/openapi.json') {
62
+ const bundle = yield getBundle();
63
+ if (bundle === undefined) {
64
+ server_1.respondWithGzip(JSON.stringify({
65
+ openapi: '3.0.0',
66
+ info: {
67
+ description: '<code> Failed to generate bundle: check out console output for more details </code>',
68
+ },
69
+ paths: {},
70
+ }), request, response, {
71
+ 'Content-Type': 'application/json',
72
+ });
73
+ }
74
+ else {
75
+ server_1.respondWithGzip(JSON.stringify(bundle), request, response, {
76
+ 'Content-Type': 'application/json',
77
+ });
78
+ }
79
+ }
80
+ else {
81
+ const filePath =
82
+ // @ts-ignore
83
+ {
84
+ '/hot.js': path.join(__dirname, 'hot.js'),
85
+ '/oauth2-redirect.html': path.join(__dirname, 'oauth2-redirect.html'),
86
+ '/simplewebsocket.min.js': require.resolve('simple-websocket/simplewebsocket.min.js'),
87
+ }[request.url || ''] ||
88
+ path.resolve(htmlTemplate ? path.dirname(htmlTemplate) : process.cwd(), `.${request.url}`);
89
+ if (!utils_1.isSubdir(process.cwd(), filePath)) {
90
+ server_1.respondWithGzip('404 Not Found', request, response, { 'Content-Type': 'text/html' }, 404);
91
+ console.timeEnd(colorette.dim(`GET ${request.url}`));
92
+ return;
93
+ }
94
+ const extname = String(path.extname(filePath)).toLowerCase();
95
+ const contentType = server_1.mimeTypes[extname] || 'application/octet-stream';
96
+ try {
97
+ server_1.respondWithGzip(yield fs_1.promises.readFile(filePath), request, response, {
98
+ 'Content-Type': contentType,
99
+ });
100
+ }
101
+ catch (e) {
102
+ if (e.code === 'ENOENT') {
103
+ server_1.respondWithGzip('404 Not Found', request, response, { 'Content-Type': 'text/html' }, 404);
104
+ }
105
+ else {
106
+ server_1.respondWithGzip(`Something went wrong: ${e.code || e.message}...\n`, request, response, {}, 500);
107
+ }
108
+ }
109
+ }
110
+ console.timeEnd(colorette.dim(`GET ${request.url}`));
111
+ });
112
+ let wsPort = yield portfinder.getPortPromise({ port: 32201 });
113
+ const server = server_1.startHttpServer(port, host, handler);
114
+ server.on('listening', () => {
115
+ process.stdout.write(`\n 🔎 Preview server running at ${colorette.blue(`http://${host}:${port}\n`)}`);
116
+ });
117
+ return server_1.startWsServer(wsPort);
118
+ });
119
+ }
120
+ exports.default = startPreviewServer;
@@ -0,0 +1,23 @@
1
+ /// <reference types="node" />
2
+ import * as http from 'http';
3
+ import { ReadStream } from 'fs';
4
+ export declare const mimeTypes: {
5
+ '.html': string;
6
+ '.js': string;
7
+ '.css': string;
8
+ '.json': string;
9
+ '.png': string;
10
+ '.jpg': string;
11
+ '.gif': string;
12
+ '.svg': string;
13
+ '.wav': string;
14
+ '.mp4': string;
15
+ '.woff': string;
16
+ '.ttf': string;
17
+ '.eot': string;
18
+ '.otf': string;
19
+ '.wasm': string;
20
+ };
21
+ export declare function respondWithGzip(contents: string | Buffer | ReadStream, request: http.IncomingMessage, response: http.ServerResponse, headers?: {}, code?: number): void;
22
+ export declare function startHttpServer(port: number, host: string, handler: http.RequestListener): http.Server;
23
+ export declare function startWsServer(port: number): any;
@@ -0,0 +1,85 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.startWsServer = exports.startHttpServer = exports.respondWithGzip = exports.mimeTypes = void 0;
4
+ const http = require("http");
5
+ const zlib = require("zlib");
6
+ const SocketServer = require('simple-websocket/server.js');
7
+ exports.mimeTypes = {
8
+ '.html': 'text/html',
9
+ '.js': 'text/javascript',
10
+ '.css': 'text/css',
11
+ '.json': 'application/json',
12
+ '.png': 'image/png',
13
+ '.jpg': 'image/jpg',
14
+ '.gif': 'image/gif',
15
+ '.svg': 'image/svg+xml',
16
+ '.wav': 'audio/wav',
17
+ '.mp4': 'video/mp4',
18
+ '.woff': 'application/font-woff',
19
+ '.ttf': 'application/font-ttf',
20
+ '.eot': 'application/vnd.ms-fontobject',
21
+ '.otf': 'application/font-otf',
22
+ '.wasm': 'application/wasm',
23
+ };
24
+ // credits: https://stackoverflow.com/a/9238214/1749888
25
+ function respondWithGzip(contents, request, response, headers = {}, code = 200) {
26
+ let compressedStream;
27
+ const acceptEncoding = request.headers['accept-encoding'] || '';
28
+ if (acceptEncoding.match(/\bdeflate\b/)) {
29
+ response.writeHead(code, Object.assign(Object.assign({}, headers), { 'content-encoding': 'deflate' }));
30
+ compressedStream = zlib.createDeflate();
31
+ }
32
+ else if (acceptEncoding.match(/\bgzip\b/)) {
33
+ response.writeHead(code, Object.assign(Object.assign({}, headers), { 'content-encoding': 'gzip' }));
34
+ compressedStream = zlib.createGzip();
35
+ }
36
+ else {
37
+ response.writeHead(code, headers);
38
+ if (typeof contents === 'string' || Buffer.isBuffer(contents)) {
39
+ response.write(contents);
40
+ response.end();
41
+ }
42
+ else if (response !== undefined) {
43
+ contents.pipe(response);
44
+ }
45
+ return;
46
+ }
47
+ if (typeof contents === 'string' || Buffer.isBuffer(contents)) {
48
+ compressedStream.write(contents);
49
+ compressedStream.pipe(response);
50
+ compressedStream.end();
51
+ }
52
+ else {
53
+ contents.pipe(compressedStream).pipe(response);
54
+ }
55
+ }
56
+ exports.respondWithGzip = respondWithGzip;
57
+ function startHttpServer(port, host, handler) {
58
+ return http.createServer(handler).listen(port, host);
59
+ }
60
+ exports.startHttpServer = startHttpServer;
61
+ function startWsServer(port) {
62
+ const socketServer = new SocketServer({ port, clientTracking: true });
63
+ socketServer.on('connection', (socket) => {
64
+ socket.on('data', (data) => {
65
+ const message = JSON.parse(data);
66
+ switch (message.type) {
67
+ case 'ping':
68
+ socket.send('{"type": "pong"}');
69
+ break;
70
+ default:
71
+ // nope
72
+ }
73
+ });
74
+ });
75
+ socketServer.broadcast = (message) => {
76
+ socketServer._server.clients.forEach((client) => {
77
+ if (client.readyState === 1) {
78
+ // OPEN
79
+ client.send(message);
80
+ }
81
+ });
82
+ };
83
+ return socketServer;
84
+ }
85
+ exports.startWsServer = startWsServer;
@@ -0,0 +1,25 @@
1
+ import { Config, Region } from '@redocly/openapi-core';
2
+ declare type PushArgs = {
3
+ entrypoint?: string;
4
+ destination?: string;
5
+ branchName?: string;
6
+ upsert?: boolean;
7
+ 'run-id'?: string;
8
+ region?: Region;
9
+ 'skip-decorator'?: string[];
10
+ };
11
+ export declare function handlePush(argv: PushArgs): Promise<void>;
12
+ export declare function getDestinationProps(destination: string | undefined, organization: string | undefined): (string | undefined)[];
13
+ declare type BarePushArgs = Omit<PushArgs, 'entrypoint' | 'destination' | 'branchName'> & {
14
+ maybeEntrypointOrAliasOrDestination?: string;
15
+ maybeDestination?: string;
16
+ maybeBranchName?: string;
17
+ branch?: string;
18
+ };
19
+ export declare const transformPush: (callback: typeof handlePush) => ({ maybeEntrypointOrAliasOrDestination, maybeDestination, maybeBranchName, branch, ...rest }: BarePushArgs) => Promise<void>;
20
+ export declare function getApiEntrypoint({ name, version, config: { apis }, }: {
21
+ name: string;
22
+ version: string;
23
+ config: Config;
24
+ }): string;
25
+ export {};