This repository has been archived by the owner on Jan 11, 2023. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 0
/
ssmd.js
619 lines (561 loc) · 18.2 KB
/
ssmd.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
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
'use strict';
const fs = require('fs');
const marked = require('marked');
const uploader = require('./uploader')
const args = require('args');
const _ = require('underscore');
const hljs = require('highlight.js');
let singleModule = '_single';
class Page {
constructor(parent) {
this.parent = parent;
this.path = [];
this.children = [];
this.name = "";
this.markdown = "";
}
dump(depth) {
for (let p of this.children.filter(c => c.children.length == 0)) {
let s = " ".repeat(depth);
s += p.name;
console.log(s);
}
for (let p of this.children.filter(c => c.children.length != 0)) {
let s = " ".repeat(depth);
s += "[" + p.name + "]";
console.log(s);
p.dump(depth + 1);
}
}
id() {
return this.path.concat(this.name).join('-');
}
localUrl() {
return this.path.concat(this.name + ".html").join('/');
}
// If this node has an 'index.md' child, then return that child. Otherwise, return null.
indexChild() {
for (let p of this.children) {
if (p.isIndex())
return p;
}
return null;
}
// If a page has a child called 'index', then copy it's contents up into the parent,
// and delete that child. This makes further processing simpler.
promoteIndex() {
for (let i = 0; i < this.children.length; i++) {
let c = this.children[i];
c.promoteIndex();
if (c.isIndex()) {
if (this.markdown != "")
throw "Page " + this.name + " already has content. Promoting 'index' up into it would destroy content";
this.markdown = c.markdown;
this.children.splice(i, 1);
i--;
}
}
}
isIndex() {
return this.name === 'index';
}
makeJSONPageTree() {
let tree = {};
let make = (page) => {
let node = {
id: page.id(),
path: page.localUrl(),
name: page.name,
hasContent: page.markdown != "",
};
node.children = [];
for (let c of page.children)
node.children.push(make(c));
return node;
};
return make(this);
}
}
class PageBuilder {
constructor(ownDir) {
this.ownDir = ownDir;
this.frame = fs.readFileSync(this.ownDir + "/templates/frame.html", { encoding: "utf-8" });
this.page = fs.readFileSync(this.ownDir + "/templates/page.html", { encoding: "utf-8" });
this.indexJS = fs.readFileSync(this.ownDir + "/templates/frame.js", { encoding: "utf-8" });
this.frameCSS = null;
this.pageCSS = null;
}
// themes/base/common.css + themes/base/<file>.css [+ themes/<themeName>/common.css] [+ themes/<themeName>/<file>.css]
mergeCSS(themeName, file) {
let merged = fs.readFileSync(this.ownDir + "/themes/base/common.css", { encoding: "utf-8" });
merged += fs.readFileSync(this.ownDir + "/themes/base/" + file + ".css", { encoding: "utf-8" });
try {
merged += fs.readFileSync(this.ownDir + "/themes/" + themeName + "/common.css", { encoding: "utf-8" });
} catch (e) {
// it's fine for a theme to exclude a common.css file
}
try {
merged += fs.readFileSync(this.ownDir + "/themes/" + themeName + "/" + file + ".css", { encoding: "utf-8" });
} catch (e) {
// it's fine for a theme to exclude customizing a file
}
return merged;
}
readTheme(themeName, highlightTheme) {
this.frameCSS = this.mergeCSS(themeName, 'frame');
this.pageCSS = this.mergeCSS(themeName, 'page');
this.pageCSS += "\n" + fs.readFileSync("node_modules/highlight.js/styles/" + highlightTheme + ".css", { encoding: "utf-8" });
}
makePage(content) {
let s = this.page.replace("/*PAGE_CSS*/", this.pageCSS);
s = s.replace("<!-- PAGE BODY -->", content);
return s;
}
firstPage(page) {
if (page.hasContent)
return page;
if (!page.children)
return null;
for (let c of page.children) {
let p = this.firstPage(c);
if (p)
return p;
}
return null;
}
// Create index.html, which is the outer page that the user navigates to.
// The content lives inside an iframe, inside index.html
makeIndexFrame(mergedManifestFile) {
let indent = ' '.repeat(4);
let makeHTML = (p, depth) => {
let self = "";
let indentDepth = indent.repeat(depth + 1);
let hasChildren = p.children && p.children.length != 0;
if (p.hasContent) {
let classes = 'indexItem';
if (hasChildren)
classes += " liNone";
self += indentDepth + `<div id='doc-${p.id}' x-path='${p.path}' x-id='${p.id}' class='${classes}'>`;
if (hasChildren)
self += `<div id='openclose-${p.id}' class='liBox' onclick='togglePageOpen("${p.id}")'></div>`;
else
self += `<div class='liBox'></div>`;
self += `<div class='liLabel' onclick='navigateToPage("${p.path}", "${p.id}")'>${_.escape(p.name)}</div>` +
`</div>\n`;
} else if (p.name !== "") {
// This is just a category node, without any content. So this might be something like "API", or "Reference".
self += indentDepth + `<div id='doc-${p.id}' x-path='${p.path}' x-id='${p.id}' class='indexItem'>` +
`<div id='openclose-${p.id}' class='liBox' onclick='togglePageOpen("${p.id}")'></div>` +
`<div class='liLabel'>${_.escape(p.name)}</div>` +
`</div>\n`;
}
if (hasChildren) {
let style = "";
if (depth == 0) {
style += "margin-left:0;"; // remove unnecessary padding from top-level <div> element
} else {
style += "";
}
let classes = "indexList";
if (depth >= 1)
classes += " hidden";
self += indentDepth + `<div id='children-${p.id}' class='${classes}' style='${style}'>\n`;
for (let c of p.children)
self += makeHTML(c, depth + 1);
self += indentDepth + '</div>\n';
}
return self;
}
let tree = JSON.parse(fs.readFileSync(mergedManifestFile, { encoding: "utf-8" }));
normalizeTree(tree);
//let frameGlobals = {
// s3bucket: deployParams.s3bucket || '',
// s3root: deployParams.s3root || '',
//};
//let frameGlobalsStr = "window.ssmd = " + JSON.stringify(frameGlobals) + ";";
let frameGlobalsStr = "window.ssmd = {};";
let listHTML = makeHTML(tree, 0);
//list = "<ul>\n" + list + "</ul>\n";
let frame = this.frame;
frame = frame.replace("<!-- INDEX -->", listHTML);
frame = frame.replace("INITIAL_PAGE", this.firstPage(tree).path);
frame = frame.replace("/*FRAME_CSS*/", this.frameCSS);
frame = frame.replace("/*FRAME_SCRIPT_GLOBALS*/", frameGlobalsStr);
frame = frame.replace("/*FRAME_SCRIPT*/", this.indexJS);
frame = frame.replace("/*PAGE_TREE*/", "var pageTree = " + JSON.stringify(tree, null, 3) + ";");
return frame;
}
}
// ensure that all nodes have the properties that we expect
function normalizeTree(node) {
if (node.children === undefined)
node.children = [];
for (let c of node.children)
normalizeTree(c);
}
function loadTreeOfMarkdownFiles(parentPage, parentPath, parentPathRootIndex, dir) {
let myPath = parentPath;
if (dir != "") {
// This is the usual case. The only case where dir = "" is for the root object
myPath = parentPath.concat(dir);
}
let root = new Page(parentPage);
root.name = dir;
root.path = parentPath.slice(parentPathRootIndex); // slice off the first part, which is the root 'content' directory
for (var f of fs.readdirSync(myPath.join("/"))) {
let st = fs.statSync(myPath.concat(f).join("/"));
if (st.isDirectory()) {
root.children.push(loadTreeOfMarkdownFiles(root, myPath, parentPathRootIndex, f));
} else if (st.isFile()) {
if (f.match(/\.md$/)) {
let p = new Page(root);
p.name = f.substr(0, f.length - 3);
p.markdown = fs.readFileSync(myPath.concat(f).join("/"), { encoding: "utf-8" });
p.path = myPath.slice(parentPathRootIndex);
root.children.push(p);
}
}
}
root.promoteIndex();
return root;
}
function childByID(node, id) {
if (!node.children)
return null;
for (let c of node.children) {
if (c.id == id)
return c;
}
return null;
}
function mergeNode(dst, src) {
for (let key of Object.keys(src)) {
if (key == 'children')
continue;
if (dst[key] === undefined || dst[key] === null || dst[key] === '')
dst[key] = src[key];
}
}
// merge srcRoot into dstRoot
function mergeTree(dstRoot, srcRoot) {
mergeNode(dstRoot, srcRoot);
if (srcRoot.children) {
for (let srcChild of srcRoot.children) {
let dstChild = childByID(dstRoot, srcChild.id);
if (!dstChild) {
dstChild = {};
if (dstRoot.children === undefined)
dstRoot.children = [];
dstRoot.children.push(dstChild);
}
mergeTree(dstChild, srcChild);
}
}
}
function createMergedManifest(mergedFilename, tmpDir, newManifestFile) {
let docs = {};
let tmpManifestDir = tmpDir + "/manifest";
for (var f of fs.readdirSync(tmpManifestDir)) {
let fname = tmpManifestDir + "/" + f;
let st = fs.statSync(fname);
if (st.isFile() && f.match(/\.json$/))
docs[fname] = JSON.parse(fs.readFileSync(fname, { encoding: "utf-8" }));
}
docs[newManifestFile] = JSON.parse(fs.readFileSync(newManifestFile, { encoding: "utf-8" }));
// sort manifests, so that we always get the same order, regardless of the filesystem.
let manifestNames = Object.keys(docs);
manifestNames.sort();
let merged = {};
for (let mft of manifestNames)
mergeTree(merged, docs[mft]);
fs.writeFileSync(mergedFilename, JSON.stringify(merged, null, 3));
}
function rmdirRecursive(dir, depth) {
if (!fs.existsSync(dir))
return;
for (let f of fs.readdirSync(dir)) {
let full = dir + "/" + f;
let st = fs.statSync(full);
if (st.isFile()) {
fs.unlinkSync(full);
} else {
rmdirRecursive(full, depth + 1);
}
}
try {
fs.rmdirSync(dir);
} catch (e) {
// Ignore at level 0, so that from inside Docker, we can ignore the deletion of the
// 'dist' directory, which will often be a mounted volumne that cannot be deleted.
if (depth === 0)
console.log(`Failed to delete directory ${dir} - ignoring`);
else
throw e;
}
}
function isAPIDoc(page) {
return page.name.match(/API/);
}
// Detect if this is an HTTP API page, and make some tweaks to improve the appearance of the page
function preprocessAPIDocs(options, page, md, addTitle) {
if (addTitle) {
let title = (page.parent ? page.parent.name : "") + " API";
md = "# " + title + "\n" + md;
}
let t = "";
for (let line of md.split("\n")) {
// This matches:
// # GET /my/api
// # POST /my/api
// # POST|PATCH /my/api
// # POST,PATCH /my/api
// # POST/PATCH /my/api
// # POST\PATCH /my/api
let m = line.match(/^#\s((?:GET|HEAD|POST|PUT|DELETE|CONNECT|OPTIONS|TRACE|PATCH)(?:\||\/|\\|,)?)+\s(.+)/)
if (m) {
t += "#".repeat(options.apiHeaderLevel) + " $-API-$ `" + m[1] + "` " + m[2] + "\n";
} else {
t += line + "\n";
}
}
return t;
}
function highlight(code, lang, callback) {
let h = null;
if (lang) {
h = hljs.highlight(lang, code, true, null);
} else {
h = hljs.highlightAuto(code, null);
if (!(h.language === "json" || h.language === "xml")) {
// Only format JSON and XML automatically.
// Auto-detect for other languages is too weak, and causes too many false positives.
return code;
}
}
return h.value;
}
function writeTreeRecursive(renderer, options, outDir, pageBuilder, page) {
if (page.markdown != "") {
let filename = outDir.concat(page.name + ".html").join("/");
let markedOptions = {
renderer: renderer,
highlight: highlight,
};
page.markdown = page.markdown.trim();
let md = page.markdown;
let titleMatch = md.match(/# ./);
let hasTitle = titleMatch && titleMatch.index === 0;
let isAPI = isAPIDoc(page);
if (isAPI)
md = preprocessAPIDocs(options, page, md, options.autoTitles && !hasTitle);
else if (options.autoTitles && !hasTitle)
md = "# " + page.name + "\n" + md;
let html = pageBuilder.makePage(marked(md, markedOptions));
fs.writeFileSync(filename, html);
}
if (page.children.length != 0) {
if (page.name != "")
fs.mkdirSync(outDir.concat(page.name).join("/"));
for (var c of page.children)
writeTreeRecursive(renderer, options, outDir.concat(page.name), pageBuilder, c);
}
}
function mkdirRobust(dir) {
// sometimes the mkdir fails on Windows. This loop seems to work around the issue
let attempts = 10;
for (let i = 0; i < attempts; i++) {
try {
fs.mkdirSync(dir);
break;
} catch (e) {
if (e.code === 'EEXIST')
break;
if (i == attempts - 1)
throw e;
}
}
}
function manifestFilename(outDir, moduleName) {
return outDir + "/manifest/" + moduleName + ".json";
}
// The 'escape' function is copied from the marked sources
function escape(html, encode) {
if (encode) {
if (escape.escapeTest.test(html)) {
return html.replace(escape.escapeReplace, function (ch) { return escape.replacements[ch]; });
}
} else {
if (escape.escapeTestNoEncode.test(html)) {
return html.replace(escape.escapeReplaceNoEncode, function (ch) { return escape.replacements[ch]; });
}
}
return html;
}
escape.escapeTest = /[&<>"']/;
escape.escapeReplace = /[&<>"']/g;
escape.replacements = {
'&': '&',
'<': '<',
'>': '>',
'"': '"',
"'": '''
};
escape.escapeTestNoEncode = /[<>"']|&(?!#?\w+;)/;
escape.escapeReplaceNoEncode = /[<>"']|&(?!#?\w+;)/g;
function writeTree(outDir, options, moduleName, deployParams, pageBuilder, root) {
let renderer = new marked.Renderer();
renderer.link = (href, title, text) => {
// Since our content lives inside an iframe, we always want to open a new tab if the user clicks on
// a link that comes from a markdown file.
return `<a href="${href}" target="_blank">${text}</a>`;
};
renderer.heading = (text, level, raw, slugger) => {
if (level === options.apiHeaderLevel && text.match(/^\$-API-\$/)) {
return `<h${level} class='api'>${text.substr(8)}</h${level}>`;
}
return `<h${level}>${text}</h${level}>`;
};
// This is a fork of the 'code' function from the marked sources
renderer.code = function (code, lang, escaped) {
if (code.indexOf("Busy") == 0) {
let d = 123;
}
if (this.options.highlight) {
var out = this.options.highlight(code, lang);
if (out != null && out !== code) {
escaped = true;
code = out;
}
}
if (!lang) {
return '<pre class="hljs"><code>'
+ (escaped ? code : escape(code, true))
+ '</code></pre>';
}
// We apply class=hljs on <pre> so that the background color applies to the entire thing
return '<pre class="hljs"><code class="'
+ this.options.langPrefix
+ escape(lang, true)
+ '">'
+ (escaped ? code : escape(code, true))
+ '</code></pre>\n';
}.bind(renderer);
writeTreeRecursive(renderer, options, [outDir], pageBuilder, root);
}
args.option('s3id', 'S3 Access ID (eg TJE2PBV7N48MJ8AZPG6N)');
args.option('s3key', 'S3 Secret Key (eg fvjR8bGy95E4eu77Q7BUh9ai2vkA7uqmxTii64ZF) ');
args.option('s3bucket', 'S3 Bucket Name (eg docs.example.com)');
args.option('s3root', 'S3 Root directory inside bucket (eg /docs)', '');
args.option('module', 'Name of this module, if this is a multi-repo document store', singleModule);
args.option('dryrun', 'Do not actually upload', false);
args.option('content', 'Content directory', '');
args.option('theme', 'Theme', 'muted');
args.option('highlight', 'Highlight.js theme', 'github-gist');
args.option('output', 'Output directory', 'dist');
// flags are the options from 'args', eg {content: '/docs'}
async function run(flags) {
if (flags.content === undefined || flags.content == '')
throw "You must specify the 'content' directory";
// Set defaults, for the case where we're not launched from the command line
if (flags.s3root === undefined)
flags.s3root = '';
if (flags.module === undefined)
flags.module = singleModule;
if (flags.dryrun === undefined)
flags.dryrun = false;
if (flags.theme === undefined)
flags.theme = 'muted';
if (flags.highlight === undefined)
flags.highlight = 'github-gist';
if (flags.output === undefined)
flags.output = 'dist';
let ownDir = __dirname;
// Ensure s3root has the form "foo/bar/" (always trailing slash, never leading slash)
let s3root = flags.s3root;
if (s3root.length != 0 && s3root[0] == '/')
s3root = s3root.substr(1);
if (s3root.length != 0 && s3root[s3root.length - 1] != '/')
s3root += '/';
flags.s3root = s3root;
let deployParams = {
s3bucket: flags.s3bucket,
s3root: s3root,
};
let dist = flags.output;
let tmp = 'ssmd_tmp';
rmdirRecursive(dist, 0);
rmdirRecursive(tmp, 0);
mkdirRobust(dist);
mkdirRobust(tmp);
mkdirRobust(dist + '/manifest');
mkdirRobust(tmp + '/manifest');
let up = null;
if (flags.s3id && flags.s3key && flags.s3bucket) {
up = new uploader({
s3: {
accessKeyId: flags.s3id,
secretAccessKey: flags.s3key,
bucket: flags.s3bucket,
bucketRoot: s3root,
},
dist: dist,
moduleName: flags.module,
});
}
let root = loadTreeOfMarkdownFiles(null, [flags.content], 1, ""); // a root index of 1 skips "content"
// Write our content into dist
let pageBuilder = new PageBuilder(ownDir);
pageBuilder.readTheme(flags.theme, flags.highlight);
let options = {
autoTitles: true,
apiHeaderLevel: 2,
};
writeTree(dist, options, flags.module, deployParams, pageBuilder, root);
// Produce the merged manifest
let merged = '';
if (up && flags.module != singleModule) {
try {
// Write the manifest for this repo into /manifest/<module>.json
// We need this on disk, so that it will get included with the upload, so that other
// builders will incorporate it if/when they perform a manifest merge.
let local = manifestFilename(dist, flags.module);
merged = dist + '/manifest/_merged.json';
fs.writeFileSync(local, JSON.stringify(root.makeJSONPageTree(), null, 3));
await up.downloadAllManifests(tmp);
createMergedManifest(merged, tmp, local);
console.log("Downloaded merged manifest");
} catch (err) {
console.error(err);
}
} else {
// just do single manifest, because we're either operating offline, or this is not a multi-module doc store
merged = manifestFilename(dist, singleModule);
fs.writeFileSync(merged, JSON.stringify(root.makeJSONPageTree(), null, 3));
}
console.info("Generated content in 'dist'");
// create index.html
fs.writeFileSync(dist + "/index.html", pageBuilder.makeIndexFrame(merged));
if (up) {
if (!flags.dryrun) {
console.info("Uploading...");
up.upload();
}
} else {
console.info("No S3 details provided; skipping upload");
console.info("You can preview the site in " + dist + "/index.html");
}
}
if (require.main === module) {
const flags = args.parse(process.argv);
run(flags).catch((err) => { console.error(err) });
} else {
let ssmd = {
run,
mergeTree, // exposed for unit tests
};
if (typeof module !== 'undefined' && typeof exports === 'object') {
module.exports = ssmd;
} else if (typeof define === 'function' && define.amd) {
define(function () { return ssmd; });
}
}