forked from OAI/OpenAPI-Specification
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmd2html.js
326 lines (284 loc) · 11.3 KB
/
md2html.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
/* ReSpec supports markdown formatting, but this shows up on the page before being rendered
Hence we render the markdown to HTML ourselves, this gives us
complete control over formatting and syntax highlighting */
'use strict';
/**
@author Mike Ralphson <[email protected]>
**/
const fs = require('fs');
const path = require('path');
const url = require('url');
const util = require('util');
const hljs = require('highlight.js');
const cheerio = require('cheerio');
let argv = require('yargs')
.boolean('respec')
.alias('r','respec')
.describe('respec','Output in respec format')
.default('respec',true)
.string('maintainers')
.alias('m','maintainers')
.describe('maintainers','path to MAINTAINERS.md')
.require(1)
.argv;
const abstract = 'What is the OpenAPI Specification?';
let maintainers = [];
let emeritus = [];
const md = require('markdown-it')({
html: true,
linkify: true,
typographer: true,
highlight: function (str, lang) {
if (lang && hljs.getLanguage(lang)) { // && !argv.respec) {
try {
return '<pre class="nohighlight"><code>' +
hljs.highlight(str, { language: lang }).value +
'</code></pre>';
} catch (__) { }
}
return '<pre class="highlight '+lang+'"><code>' + md.utils.escapeHtml(str) + '</code></pre>';
}
});
function preface(title,options) {
const respec = {
specStatus: "base",
editors: maintainers,
formerEditors: emeritus,
publishDate: options.publishDate,
subtitle: 'Version '+options.subtitle,
processVersion: 2017,
edDraftURI: "https://github.com/OAI/OpenAPI-Specification/",
github: {
repoURL: "https://github.com/OAI/OpenAPI-Specification/",
branch: "master"
},
shortName: "OAS",
noTOC: false,
lint: false,
additionalCopyrightHolders: "the Linux Foundation",
includePermalinks: true
};
let preface = `<!DOCTYPE html><html lang="en"><head><meta charset="UTF-8"><title>${md.utils.escapeHtml(title)}</title>`;
// SEO
preface += '<meta name="description" content="The OpenAPI Specification (OAS) defines a standard, programming language-agnostic interface description for HTTP APIs.">';
preface += '<link rel="canonical" href="https://spec.openapis.org/oas/latest.html" />';
if (options.respec) {
preface += '<script src="../js/respec-oai.js" class="remove"></script>';
preface += `<script class="remove">var respecConfig = ${JSON.stringify(respec)};</script>`;
try {
preface += fs.readFileSync('./analytics/google.html','utf8');
}
catch (ex) {}
preface += '</head><body>';
preface += '<style>';
preface += '#respec-ui { visibility: hidden; }';
preface += 'h1,h2,h3 { color: #629b34; }';
preface += 'a[href] { color: #45512c; }'; // third OAI colour is #8ad000
preface += 'body:not(.toc-inline) #toc h2 { color: #45512c; }';
preface += 'table { display: block; width: 100%; overflow: auto; }';
preface += 'table th { font-weight: 600; }';
preface += 'table th, table td { padding: 6px 13px; border: 1px solid #dfe2e5; }';
preface += 'table tr { background-color: #fff; border-top: 1px solid #c6cbd1; }';
preface += 'table tr:nth-child(2n) { background-color: #f6f8fa; }';
preface += 'pre { background-color: #f6f8fa !important; }';
preface += fs.readFileSync(path.resolve(__dirname,'gist.css'),'utf8').split('\n').join(' ');
preface += '</style>';
preface += `<h1 id="title">${title.split('|')[0]}</h1>`;
preface += `<section id="abstract" title="${abstract}">`;
preface += 'The OpenAPI Specification (OAS) defines a standard, programming language-agnostic interface description for HTTP APIs, which allows both humans and computers to discover and understand the capabilities of a service without requiring access to source code, additional documentation, or inspection of network traffic. When properly defined via OpenAPI, a consumer can understand and interact with the remote service with a minimal amount of implementation logic. Similar to what interface descriptions have done for lower-level programming, the OpenAPI Specification removes guesswork in calling a service.';
preface += '</section>';
preface += '<section class="notoc" id="sotd">';
preface += '<h2>Status of This Document</h2>';
preface += 'The source-of-truth for the specification is the GitHub markdown file referenced above.';
preface += '</section>';
}
else {
preface += '</head><body>';
}
return preface;
}
function doMaintainers() {
let m = fs.readFileSync(argv.maintainers,'utf8');
let h = md.render(m);
let $ = cheerio.load(h);
let u = $('ul').first();
$(u).children('li').each(function(e){
let t = $(this).text().split('@')[0];
maintainers.push({name:t});
});
if ($("ul").length < 2) return;
u = $("ul").last();
$(u).children('li').each(function(e){
let t = $(this).text().split('@')[0];
emeritus.push({name:t});
});
}
function getPublishDate(m) {
let result = new Date();
let h = md.render(m);
let $ = cheerio.load(h);
$('table').each(function(i,table){
const h = $(table).find('th');
const headers = [];
$(h).each(function(i,header){
headers.push($(header).text());
});
if (headers.length >= 2 && headers[0] === 'Version' && headers[1] === 'Date') {
let c = $(table).find('tr').find('td');
let v = $(c[0]).text();
let d = $(c[1]).text();
argv.subtitle = v;
if (d !== 'TBA') result = new Date(d);
}
});
return result;
}
if (argv.maintainers) {
doMaintainers();
}
let s = fs.readFileSync(argv._[0],'utf8');
if (argv.respec) {
argv.publishDate = getPublishDate(s);
}
let lines = s.split('\r').join().split('\n');
let prevHeading = 0;
let lastIndent = 0;
let inTOC = false;
let inDefs = false;
let inCodeBlock = false;
let bsFix = true;
let indents = [0];
// process the markdown
for (let l in lines) {
let line = lines[l];
let linkTarget;
if (line.startsWith('## Table of Contents')) inTOC = true;
if (line.startsWith('<!-- /TOC')) inTOC = false;
if (inTOC) line = '';
if (line.startsWith('## Definitions')) {
inDefs = true;
bsFix = false;
}
else if (line.startsWith('## ')) inDefs = false;
if (line.startsWith('```')) {
inCodeBlock = !inCodeBlock;
line += '\n'; // fixes formatting of first line of syntax-highlighted blocks
}
if (!inCodeBlock && line.startsWith('#')) {
let indent = 0;
while (line[indent] === '#') indent++;
let originalIndent = indent;
let prevIndent = indents[indents.length-1]; // peek
let delta = indent-prevIndent;
if (!argv.respec) {
if (delta===0) indent = lastIndent
else if (delta<0) indent = lastIndent-1
else if (delta>0) indent = lastIndent+1;
}
if (indent < 0) {
indent = 1;
}
if (argv.respec && (indent > 1)) {
indent--;
}
let newIndent = indent;
if (!argv.respec && (indent <= 2) && bsFix) {
newIndent++;
}
if (line.indexOf('<a name=')>=0) {
let comp = line.split('</a>');
let title = comp[1];
if (inDefs) title = '<dfn>'+title+'</dfn>';
let link = comp[0].split('<a ')[1].replace('name=','id=');
const anchor = link.split("'").join('"').split('"')[1];
line = '#'.repeat(newIndent)+' <span>'+title+'</span>';
linkTarget = '<a id="'+anchor+'"></a>';
}
else {
let title = line.split('# ')[1];
if (inDefs) title = '<dfn>'+title+'</dfn>';
line = ('#'.repeat(newIndent)+' '+title);
}
if (delta>0) indents.push(originalIndent);
if (delta<0) {
let d = Math.abs(delta);
while (d>0) {
indents.pop();
d--;
}
}
lastIndent = indent;
}
if (line.indexOf('"></a>')>=0) {
line = line.replace(' name=',' id=');
line = line.replace('"></a>','"> </a>');
}
line = line.split('\\|').join('|'); // was ¦
if (!inCodeBlock) {
// minor fixups to get RFC links to work properly
if (line.indexOf('RFC [')>=0) {
line = line.replace('RFC [','[RFC');
}
line = line.replace('[Authorization header as defined in ','Authorization header as defined in [');
if (line.indexOf('[RFC')>=0) {
line = line.replace(/\[RFC ?([0-9]{1,5})\]/g,function(match,group1){
console.warn('Fixing RFC reference',match,group1);
return '[[!RFC'+group1+']]';
});
}
line = line.replace('http://tools.ietf.org','https://tools.ietf.org');
if (line.indexOf('xml2rfc.ietf.org')>0) {
line = line.replace('https://xml2rfc.ietf.org/public/rfc/html/rfc','https://tools.ietf.org/html/rfc');
line = line.replace('.html','');
}
line = line.replace(/\]\]\(https:\/\/tools.ietf.org\/html\/rfc[0-9]{1,5}\/?(\#.*?)?\)/g,function(match,group1){
//return (group1 ? group1 : '')+']]';
return ']]';
});
}
// minor fixup to get bibliography link to work
//if (line.indexOf('[ABNF]')>=0) {
// line = line.replace('[ABNF]','[Augmented Backus-Naur Form]');
//}
if (!inCodeBlock && line.indexOf('](../') >= 0) {
const regExp = /\((\.\.[^)]+)\)/g;
line = line.replace(regExp,function(match,group1){
console.warn('Fixing relative link',group1,line);
return '('+url.resolve('https://github.com/OAI/OpenAPI-Specification/tree/master/versions/foo',group1)+')';
});
}
if (!inCodeBlock && argv.respec && line.startsWith('#')) {
let heading = 0;
while (line[heading] === '#') heading++;
let delta = heading-prevHeading;
if (delta>0) delta = 1;
//if (delta<0) delta = -1;
if (Math.abs(delta)>1) console.warn(delta,line);
let prefix = '';
let newSection = '<section>';
if (line.includes('Appendix')) {
newSection = '<section class="appendix">';
}
// heading level delta is either 0 or is +1/-1, or we're in respec mode
/* respec insists on <section>...</section> breaks around headings */
if (delta === 0) {
prefix = '</section>'+newSection;
}
else if (delta > 0) {
prefix = newSection.repeat(delta);
}
else {
prefix = '</section>'+('</section>').repeat(Math.abs(delta))+newSection;
}
prevHeading = heading;
line = prefix+md.render(line);
}
lines[l] = (linkTarget ? linkTarget : '') + line;
}
s = preface(`OpenAPI Specification v${argv.subtitle} | Introduction, Definitions, & More`,argv)+'\n\n'+lines.join('\n');
let out = md.render(s);
out = out.replace(/\[([RGB])\]/g,function(match,group1){
console.warn('Fixing',match,group1);
return '['+group1+']';
});
console.log(out);