redoc/cli/index.ts

277 lines
7.6 KiB
TypeScript
Raw Normal View History

2018-03-13 17:56:38 +03:00
#!/usr/bin/env node
import * as React from 'react';
import { renderToString } from 'react-dom/server';
import { ServerStyleSheet } from 'styled-components';
import { createServer, ServerResponse, ServerRequest } from 'http';
import * as zlib from 'zlib';
import { join, dirname } from 'path';
2018-03-20 12:00:45 +03:00
import { compile } from 'handlebars';
2018-03-13 17:56:38 +03:00
// @ts-ignore
import { Redoc, loadAndBundleSpec, createStore } from 'redoc';
2018-03-13 17:56:38 +03:00
import { createReadStream, writeFileSync, ReadStream, readFileSync, watch, existsSync } from 'fs';
import * as yargs from 'yargs';
type Options = {
ssr?: boolean;
watch?: boolean;
cdn?: boolean;
output?: string;
2018-03-20 11:21:05 +03:00
title?: string;
2018-03-20 12:00:45 +03:00
templateFileName?: string;
2018-03-13 17:56:38 +03:00
};
const BUNDLES_DIR = dirname(require.resolve('redoc'));
2018-03-13 17:56:38 +03:00
yargs
.command(
'serve [spec]',
'start the server',
yargs => {
yargs.positional('spec', {
describe: 'path or URL to your spec',
});
yargs.option('s', {
alias: 'ssr',
describe: 'Enable server-side rendering',
type: 'boolean',
});
yargs.option('p', {
alias: 'port',
type: 'number',
default: 8080,
});
yargs.option('w', {
alias: 'watch',
type: 'boolean',
});
2018-03-14 09:24:45 +03:00
yargs.demandOption('spec');
return yargs;
2018-03-13 17:56:38 +03:00
},
async argv => {
try {
2018-03-20 12:00:45 +03:00
await serve(argv.port, argv.spec, {
ssr: argv.ssr,
watch: argv.watch,
templateFileName: argv.template,
});
2018-03-13 17:56:38 +03:00
} catch (e) {
console.log(e.stack);
2018-03-13 17:56:38 +03:00
}
},
)
.command(
'bundle [spec]',
'bundle spec into zero-dependency HTML-file',
yargs => {
yargs.positional('spec', {
describe: 'path or URL to your spec',
});
yargs.option('o', {
describe: 'Output file',
alias: 'output',
type: 'number',
default: 'redoc-static.html',
});
2018-03-20 11:21:05 +03:00
yargs.options('title', {
describe: 'Page Title',
type: 'string',
default: 'ReDoc documentation',
});
2018-03-13 17:56:38 +03:00
yargs.option('cdn', {
describe: 'Do not include ReDoc source code into html page, use link to CDN instead',
type: 'boolean',
default: false,
});
2018-03-14 09:24:45 +03:00
yargs.demandOption('spec');
return yargs;
2018-03-13 17:56:38 +03:00
},
async argv => {
try {
2018-03-20 12:00:45 +03:00
await bundle(argv.spec, {
ssr: true,
output: argv.o,
cdn: argv.cdn,
title: argv.title,
templateFileName: argv.template,
});
2018-03-13 17:56:38 +03:00
} catch (e) {
console.log(e.message);
}
},
2018-03-14 09:24:45 +03:00
)
2018-03-20 12:00:45 +03:00
.options('t', {
alias: 'template',
describe: 'Path to handlebars page template, see https://git.io/vxZ3V for the example ',
type: 'string',
})
2018-03-14 09:24:45 +03:00
.demandCommand().argv;
2018-03-13 17:56:38 +03:00
async function serve(port: number, pathToSpec: string, options: Options = {}) {
let spec = await loadAndBundleSpec(pathToSpec);
let pageHTML = await getPageHTML(spec, pathToSpec, options);
const server = createServer((request, response) => {
console.time('GET ' + request.url);
if (request.url === '/redoc.standalone.js') {
respondWithGzip(
createReadStream(join(BUNDLES_DIR, 'redoc.standalone.js'), 'utf8'),
request,
response,
{
'Content-Type': 'application/javascript',
},
);
2018-03-13 17:56:38 +03:00
} else if (request.url === '/') {
respondWithGzip(pageHTML, request, response);
} else if (request.url === '/spec.json') {
const specStr = JSON.stringify(spec, null, 2);
respondWithGzip(specStr, request, response, {
'Content-Type': 'application/json',
});
} else {
response.writeHead(404);
response.write('Not found');
response.end();
}
console.timeEnd('GET ' + request.url);
});
console.log();
server.listen(port, () => console.log(`Server started: http://127.0.0.1:${port}`));
if (options.watch && existsSync(pathToSpec)) {
watch(
pathToSpec,
debounce(async (event, filename) => {
if (event === 'change' || (event === 'rename' && existsSync(filename))) {
console.log(`${pathToSpec} changed, updating docs`);
try {
spec = await loadAndBundleSpec(pathToSpec);
pageHTML = await getPageHTML(spec, pathToSpec, options);
console.log('Updated successfully');
} catch (e) {
console.error('Error while updating: ', e.message);
}
}
}, 2200),
);
console.log(`👀 Watching ${pathToSpec} for changes...`);
}
}
async function bundle(pathToSpec, options: Options = {}) {
const start = Date.now();
2018-03-13 17:56:38 +03:00
const spec = await loadAndBundleSpec(pathToSpec);
const pageHTML = await getPageHTML(spec, pathToSpec, { ...options, ssr: true });
2018-03-13 17:56:38 +03:00
writeFileSync(options.output!, pageHTML);
const sizeInKiB = Math.ceil(Buffer.byteLength(pageHTML) / 1024);
const time = Date.now() - start;
console.log(
`\n🎉 bundled successfully in: ${options.output!} (${sizeInKiB} KiB) [⏱ ${time / 1000}s]`,
);
2018-03-13 17:56:38 +03:00
}
2018-03-20 12:00:45 +03:00
async function getPageHTML(
spec: any,
pathToSpec: string,
{ ssr, cdn, title, templateFileName }: Options,
) {
2018-03-13 17:56:38 +03:00
let html, css, state;
let redocStandaloneSrc;
if (ssr) {
console.log('Prerendering docs');
const store = await createStore(spec, pathToSpec);
2018-03-13 17:56:38 +03:00
const sheet = new ServerStyleSheet();
html = renderToString(sheet.collectStyles(React.createElement(Redoc, { store })));
css = sheet.getStyleTags();
state = await store.toJS();
if (!cdn) {
redocStandaloneSrc = readFileSync(join(BUNDLES_DIR, 'redoc.standalone.js'));
2018-03-13 17:56:38 +03:00
}
}
2018-03-20 12:00:45 +03:00
templateFileName = templateFileName ? templateFileName : join(__dirname, './template.hbs');
const template = compile(readFileSync(templateFileName).toString());
console.log(readFileSync(templateFileName).toString());
debugger;
return template({
redocHTML: `
<script>
${(ssr && `const __redoc_state = ${JSON.stringify(state)};`) || ''}
2018-03-13 17:56:38 +03:00
document.addEventListener('DOMContentLoaded', function() {
var container = document.getElementById('redoc');
2018-03-20 12:00:45 +03:00
Redoc.${ssr ? 'hydrate(__redoc_state, container);' : 'init("spec.json", {}, container)'};
2018-03-13 17:56:38 +03:00
});
2018-03-20 12:00:45 +03:00
</script>
<div id="redoc">${(ssr && html) || ''}</div>`,
redocHead: ssr
? (cdn
? '<script src="https://unpkg.com/redoc@next/bundles/redoc.standalone.js"></script>'
: `<script>${redocStandaloneSrc}</script>`) + css
: '<script src="redoc.standalone.js"></script>',
title: title,
});
2018-03-13 17:56:38 +03:00
}
// credits: https://stackoverflow.com/a/9238214/1749888
function respondWithGzip(
contents: string | ReadStream,
request: ServerRequest,
response: ServerResponse,
headers = {},
) {
let compressedStream;
const acceptEncoding = (request.headers['accept-encoding'] as string) || '';
if (acceptEncoding.match(/\bdeflate\b/)) {
response.writeHead(200, { ...headers, 'content-encoding': 'deflate' });
compressedStream = zlib.createDeflate();
} else if (acceptEncoding.match(/\bgzip\b/)) {
response.writeHead(200, { ...headers, 'content-encoding': 'gzip' });
compressedStream = zlib.createGzip();
} else {
response.writeHead(200, headers);
if (typeof contents === 'string') {
response.write(contents);
response.end();
} else {
contents.pipe(response);
}
return;
}
if (typeof contents === 'string') {
compressedStream.write(contents);
compressedStream.pipe(response);
compressedStream.end();
return;
} else {
contents.pipe(compressedStream).pipe(response);
}
}
function debounce(callback: Function, time: number) {
let interval;
return (...args) => {
clearTimeout(interval);
interval = setTimeout(() => {
interval = null;
callback(...args);
}, time);
};
}