docusaurus/lib/server/server.js

398 lines
12 KiB
JavaScript
Raw Normal View History

2017-07-07 13:28:29 -04:00
/**
* Copyright (c) 2017-present, Facebook, Inc.
* All rights reserved.
*
* This source code is licensed under the BSD-style license found in the
* LICENSE file in the root directory of this source tree. An additional grant
* of patent rights can be found in the PATENTS file in the same directory.
*/
2017-07-10 19:38:35 -04:00
function execute() {
const translation = require("./translation.js");
2017-07-07 13:28:29 -04:00
translation();
const CWD = process.cwd();
2017-07-10 19:38:35 -04:00
const express = require("express");
const React = require("react");
const request = require("request");
const renderToStaticMarkup = require("react-dom/server").renderToStaticMarkup;
const fs = require("fs-extra");
const os = require("os");
const path = require("path");
const readMetadata = require("./readMetadata.js");
const toSlug = require("../core/toSlug.js");
const mkdirp = require("mkdirp");
const glob = require("glob");
let siteConfig = require(CWD + "/siteConfig.js");
2017-07-07 13:28:29 -04:00
/**
* Removes a module from the cache
*/
function purgeCache(moduleName) {
// Traverse the cache looking for the files
// loaded by the specified module name
2017-07-10 19:38:35 -04:00
searchCache(moduleName, function(mod) {
2017-07-07 13:28:29 -04:00
delete require.cache[mod.id];
});
// Remove cached paths to the module.
Object.keys(module.constructor._pathCache).forEach(function(cacheKey) {
2017-07-10 19:38:35 -04:00
if (cacheKey.indexOf(moduleName) > 0) {
2017-07-07 13:28:29 -04:00
delete module.constructor._pathCache[cacheKey];
}
});
2017-07-10 19:38:35 -04:00
}
2017-07-07 13:28:29 -04:00
/**
* Traverses the cache to search for all the cached
* files of the specified module name
*/
function searchCache(moduleName, callback) {
// Resolve the module identified by the specified name
let mod = require.resolve(moduleName);
// Check if the module has been resolved and found within
// the cache
2017-07-10 19:38:35 -04:00
if (mod && (mod = require.cache[mod]) !== undefined) {
2017-07-07 13:28:29 -04:00
// Recursively go over the results
(function traverse(mod) {
// Go over each of the module's children and
// traverse them
2017-07-10 19:38:35 -04:00
mod.children.forEach(function(child) {
traverse(child);
2017-07-07 13:28:29 -04:00
});
// Call the specified callback providing the
// found cached module
callback(mod);
2017-07-10 19:38:35 -04:00
})(mod);
2017-07-07 13:28:29 -04:00
}
2017-07-10 19:38:35 -04:00
}
2017-07-07 13:28:29 -04:00
/****************************************************************************/
let Metadata;
let readCategories;
function reloadMetadataCategories() {
readMetadata.generateDocsMetadata();
2017-07-10 19:38:35 -04:00
purgeCache("../core/metadata.js");
Metadata = require("../core/metadata.js");
purgeCache("./readCategories.js");
readCategories = require("./readCategories.js");
2017-07-07 13:28:29 -04:00
let layouts = {};
for (let i = 0; i < Metadata.length; i++) {
let layout = Metadata[i].layout;
if (layouts[layout] !== true) {
layouts[layout] = true;
readCategories(layout);
}
}
}
/****************************************************************************/
2017-07-10 19:38:35 -04:00
const TABLE_OF_CONTENTS_TOKEN = "<AUTOGENERATED_TABLE_OF_CONTENTS>";
2017-07-07 13:28:29 -04:00
const insertTableOfContents = rawContent => {
const regexp = /\n###\s+(`.*`.*)\n/g;
let match;
const headers = [];
while ((match = regexp.exec(rawContent))) {
headers.push(match[1]);
}
const tableOfContents = headers
.map(header => ` - [${header}](#${toSlug(header)})`)
2017-07-10 19:38:35 -04:00
.join("\n");
2017-07-07 13:28:29 -04:00
return rawContent.replace(TABLE_OF_CONTENTS_TOKEN, tableOfContents);
};
/****************************************************************************/
2017-07-10 19:38:35 -04:00
console.log("server.js triggered...");
2017-07-07 13:28:29 -04:00
const port = 3000;
reloadMetadataCategories();
/* handle all requests for document pages */
2017-07-10 19:38:35 -04:00
const app = express().get(/docs\/[\s\S]*html$/, (req, res) => {
purgeCache(CWD + "/siteConfig.js");
siteConfig = require(CWD + "/siteConfig.js");
2017-07-07 13:28:29 -04:00
2017-07-10 19:38:35 -04:00
console.log(req.path);
2017-07-07 13:28:29 -04:00
2017-07-10 19:38:35 -04:00
reloadMetadataCategories();
let links = {};
for (let i = 0; i < Metadata.length; i++) {
const metadata = Metadata[i];
links[metadata.permalink] =
"docs/" + metadata.language + "/" + metadata.source;
}
let mdToHtml = {};
for (let i = 0; i < Metadata.length; i++) {
const metadata = Metadata[i];
mdToHtml["/docs/" + metadata.language + "/" + metadata.source] =
siteConfig.baseUrl + metadata.permalink;
}
2017-07-07 13:28:29 -04:00
2017-07-10 19:38:35 -04:00
let file = links[req.path.toString().replace(siteConfig.baseUrl, "")];
file = CWD + "/../" + file;
console.log(file);
const result = readMetadata.processMetadata(file);
2017-07-07 13:28:29 -04:00
2017-07-10 19:38:35 -04:00
const metadata = result.metadata;
const language = metadata.language;
let rawContent = result.rawContent;
2017-07-07 13:28:29 -04:00
2017-07-10 19:38:35 -04:00
/* generate table of contents if appropriate */
if (rawContent && rawContent.indexOf(TABLE_OF_CONTENTS_TOKEN) !== -1) {
rawContent = insertTableOfContents(rawContent);
}
2017-07-07 13:28:29 -04:00
2017-07-10 19:38:35 -04:00
/* replace any links to markdown files to their website html links */
Object.keys(mdToHtml).forEach(function(key, index) {
rawContent = rawContent.replace(new RegExp(key, "g"), mdToHtml[key]);
});
2017-07-07 13:28:29 -04:00
2017-07-10 19:38:35 -04:00
purgeCache("../core/DocsLayout.js");
const DocsLayout = require("../core/DocsLayout.js");
const docComp = (
<DocsLayout metadata={metadata} language={language} config={siteConfig}>
{rawContent}
</DocsLayout>
);
2017-07-07 13:28:29 -04:00
2017-07-10 19:38:35 -04:00
res.send(renderToStaticMarkup(docComp));
});
2017-07-07 13:28:29 -04:00
/* handle all requests for blog pages and posts */
app.get(/blog\/[\s\S]*html$/, (req, res) => {
2017-07-10 19:38:35 -04:00
purgeCache(CWD + "/siteConfig.js");
siteConfig = require(CWD + "/siteConfig.js");
2017-07-07 13:28:29 -04:00
2017-07-10 19:38:35 -04:00
if (fs.existsSync(__dirname + "../core/MetadataBlog.js")) {
purgeCache("../core/MetadataBlog.js");
fs.removeSync(__dirname + "../core/MetadataBlog.js");
2017-07-07 13:28:29 -04:00
}
readMetadata.generateBlogMetadata();
2017-07-10 19:38:35 -04:00
MetadataBlog = require("../core/MetadataBlog.js");
2017-07-07 13:28:29 -04:00
/* generate all of the blog pages */
2017-07-10 19:38:35 -04:00
purgeCache("../core/BlogPageLayout.js");
const BlogPageLayout = require("../core/BlogPageLayout.js");
2017-07-07 13:28:29 -04:00
const blogPages = {};
/* make blog pages with 10 posts per page */
const perPage = 10;
for (
let page = 0;
page < Math.ceil(MetadataBlog.length / perPage);
page++
) {
2017-07-10 19:38:35 -04:00
let language = "en";
const metadata = { page: page, perPage: perPage };
const blogPageComp = (
<BlogPageLayout
metadata={metadata}
language={language}
config={siteConfig}
/>
);
2017-07-07 13:28:29 -04:00
const str = renderToStaticMarkup(blogPageComp);
2017-07-10 19:38:35 -04:00
let path = (page > 0 ? "page" + (page + 1) : "") + "/index.html";
2017-07-07 13:28:29 -04:00
blogPages[path] = str;
}
2017-07-10 19:38:35 -04:00
let parts = req.path.toString().split("blog/");
2017-07-07 13:28:29 -04:00
// send corresponding blog page if appropriate
2017-07-10 19:38:35 -04:00
if (parts[1] === "index.html") {
res.send(blogPages["/index.html"]);
} else if (parts[1].endsWith("/index.html")) {
2017-07-07 13:28:29 -04:00
res.send(blogPages[parts[1]]);
2017-07-10 19:38:35 -04:00
} else if (parts[1].match(/page([0-9]+)/)) {
if (parts[1].endsWith("/")) {
res.send(blogPages[parts[1] + "index.html"]);
2017-07-07 13:28:29 -04:00
} else {
2017-07-10 19:38:35 -04:00
res.send(blogPages[parts[1] + "/index.html"]);
2017-07-07 13:28:29 -04:00
}
2017-07-10 19:38:35 -04:00
} else {
// else send corresponding blog post
2017-07-07 13:28:29 -04:00
let file = parts[1];
2017-07-10 19:38:35 -04:00
file = file.replace(/\.html$/, ".md");
file = file.replace(new RegExp("/", "g"), "-");
file = CWD + "/../blog/" + file;
2017-07-07 13:28:29 -04:00
2017-07-10 19:38:35 -04:00
const result = readMetadata.extractMetadata(
fs.readFileSync(file, { encoding: "utf8" })
);
2017-07-07 13:28:29 -04:00
const rawContent = result.rawContent;
const metadata = Object.assign(
2017-07-10 19:38:35 -04:00
{ path: req.path.toString().split("blog/")[1], content: rawContent },
2017-07-07 13:28:29 -04:00
result.metadata
);
metadata.id = metadata.title;
2017-07-10 19:38:35 -04:00
let language = "en";
purgeCache("../core/BlogPostLayout.js");
const BlogPostLayout = require("../core/BlogPostLayout.js");
const blogPostComp = (
<BlogPostLayout
metadata={metadata}
language={language}
config={siteConfig}
>
{rawContent}
</BlogPostLayout>
);
2017-07-07 13:28:29 -04:00
res.send(renderToStaticMarkup(blogPostComp));
}
});
/* handle all other main pages */
2017-07-10 19:38:35 -04:00
app.get("*.html", (req, res) => {
purgeCache(CWD + "/siteConfig.js");
siteConfig = require(CWD + "/siteConfig.js");
2017-07-07 13:28:29 -04:00
console.log(req.path);
/* look for user provided html file first */
2017-07-10 19:38:35 -04:00
let htmlFile = req.path.toString().replace(siteConfig.baseUrl, "");
htmlFile = CWD + "/pages/" + htmlFile;
if (
fs.existsSync(htmlFile) ||
fs.existsSync(
(htmlFile = htmlFile.replace(
path.basename(htmlFile),
"en/" + path.basename(htmlFile)
))
)
) {
res.send(fs.readFileSync(htmlFile, { encoding: "utf8" }));
2017-07-07 13:28:29 -04:00
return;
}
/* look for user provided react file either in specified path or in path for english files */
2017-07-10 19:38:35 -04:00
let file = req.path.toString().replace(/\.html$/, ".js");
file = file.replace(siteConfig.baseUrl, "");
let userFile = CWD + "/pages/" + file;
2017-07-07 13:28:29 -04:00
2017-07-10 19:38:35 -04:00
let language = "en";
2017-07-07 13:28:29 -04:00
const regexLang = /(.*)\/.*\.html$/;
const match = regexLang.exec(req.path);
2017-07-10 19:38:35 -04:00
const parts = match[1].split("/");
2017-07-07 13:28:29 -04:00
const enabledLangTags = [];
2017-07-10 19:38:35 -04:00
for (let i = 0; i < siteConfig["languages"].length; i++) {
enabledLangTags.push(siteConfig["languages"][i].tag);
2017-07-07 13:28:29 -04:00
}
for (let i = 0; i < parts.length; i++) {
if (enabledLangTags.indexOf(parts[i]) !== -1) {
language = parts[i];
}
}
2017-07-10 19:38:35 -04:00
if (
fs.existsSync(userFile) ||
fs.existsSync(
(userFile = userFile.replace(
path.basename(userFile),
"en/" + path.basename(userFile)
))
)
) {
2017-07-07 13:28:29 -04:00
/* copy into docusaurus so require paths work */
2017-07-10 19:38:35 -04:00
let parts = userFile.split("pages/");
let tempFile = __dirname + "/../pages/" + parts[1];
tempFile = tempFile.replace(
path.basename(file),
"temp" + path.basename(file)
);
mkdirp.sync(tempFile.replace(new RegExp("/[^/]*$"), ""));
2017-07-07 13:28:29 -04:00
fs.copySync(userFile, tempFile);
/* render into a string */
purgeCache(tempFile);
const ReactComp = require(tempFile);
2017-07-10 19:38:35 -04:00
purgeCache("../core/Site.js");
const Site = require("../core/Site.js");
const str = renderToStaticMarkup(
<Site language={language} config={siteConfig}>
<ReactComp language={language} />
</Site>
);
2017-07-07 13:28:29 -04:00
fs.removeSync(tempFile);
res.send(str);
2017-07-10 19:38:35 -04:00
} else {
2017-07-07 13:28:29 -04:00
console.log(req.path);
2017-07-10 19:38:35 -04:00
res.send("No file found");
2017-07-07 13:28:29 -04:00
}
});
/* generate the main.css file by concatenating user provided css to the end */
2017-07-10 19:38:35 -04:00
app.get(/main\.css$/, (req, res) => {
const mainCssPath =
__dirname +
"/../static/" +
req.path.toString().replace(siteConfig.baseUrl, "/");
let cssContent = fs.readFileSync(mainCssPath, { encoding: "utf8" });
2017-07-07 13:28:29 -04:00
2017-07-10 19:38:35 -04:00
let files = glob.sync(CWD + "/static/**/*.css");
2017-07-07 13:28:29 -04:00
files.forEach(file => {
2017-07-10 19:38:35 -04:00
cssContent =
cssContent + "\n" + fs.readFileSync(file, { encoding: "utf8" });
2017-07-07 13:28:29 -04:00
});
2017-07-10 19:38:35 -04:00
cssContent = cssContent
.toString()
.replace(
new RegExp("{primaryColor}", "g"),
siteConfig.colors.primaryColor
);
cssContent = cssContent.replace(
new RegExp("{secondaryColor}", "g"),
siteConfig.colors.secondaryColor
);
cssContent = cssContent.replace(
new RegExp("{prismColor}", "g"),
siteConfig.colors.prismColor
);
2017-07-07 13:28:29 -04:00
res.send(cssContent);
});
/* serve static content first from user folder then from docusaurus */
2017-07-10 19:38:35 -04:00
app.use(siteConfig.baseUrl, express.static(CWD + "/static"));
app.use(siteConfig.baseUrl, express.static(__dirname + "/../static"));
2017-07-07 13:28:29 -04:00
app.get(/\/[^\.]*\/?$/, (req, res) => {
2017-07-10 19:38:35 -04:00
if (req.path.toString().endsWith("/")) {
request.get(
"http://localhost:3000" + req.path + "index.html",
(err, response, body) => {
if (!err) {
res.send(body);
}
2017-07-07 13:28:29 -04:00
}
2017-07-10 19:38:35 -04:00
);
2017-07-07 13:28:29 -04:00
} else {
2017-07-10 19:38:35 -04:00
request.get(
"http://localhost:3000" + req.path + "/index.html",
(err, response, body) => {
if (!err) {
res.send(body);
}
2017-07-07 13:28:29 -04:00
}
2017-07-10 19:38:35 -04:00
);
2017-07-07 13:28:29 -04:00
}
});
app.listen(port);
2017-07-10 19:38:35 -04:00
console.log("listening on port: " + port);
2017-07-07 13:28:29 -04:00
}
module.exports = execute;