'use strict';
Error.stackTraceLimit = Infinity;
const acquit = require('acquit');
const fs = require('fs');
const fsextra = require('fs-extra');
const path = require('path');
const pug = require('pug');
const pkg = require('../package.json');
const transform = require('acquit-require');
const childProcess = require('child_process');
// using "__dirname" and ".." to have a consistent CWD, this script should not be runnable, even when not being in the root of the project
// also a consistent root path so that it is easy to change later when the script should be moved
const cwd = path.resolve(__dirname, '..');
// support custom heading ids
// see https://www.markdownguide.org/extended-syntax/#heading-ids
// Example:
// # Some Header {#custom-id}
const CustomIdRegex = /{#([a-zA-Z0-9_-]+)}(?: *)$/;
const isMain = require.main === module;
let jobs = [];
try {
jobs = require('../docs/data/jobs.json');
} catch {}
let opencollectiveSponsors = [];
try {
opencollectiveSponsors = require('../docs/data/opencollective.json');
} catch {}
require('acquit-ignore')();
const markdown = require('marked');
const highlight = require('highlight.js');
const { promisify } = require('util');
markdown.use({
renderer: {
heading: function({ tokens, depth }) {
let raw = this.parser.parseInline(tokens);
let slug;
const idMatch = CustomIdRegex.exec(raw);
// use custom header id if available, otherwise fallback to default slugger
if (idMatch) {
slug = idMatch[1];
raw = raw.replace(CustomIdRegex, '');
} else {
slug = createSlug(raw.trim());
}
return `
${highlight.highlight(text, { language: lang }).value}`;
}
}
});
const testPath = path.resolve(cwd, 'test');
/** additional test files to scan, relative to `test/` */
const additionalTestFiles = [
'geojson.test.js',
'schema.alias.test.js'
];
/** ignored files from `test/docs/` */
const ignoredTestFiles = [
// ignored because acquit does not like "for await"
'asyncIterator.test.js'
];
/**
* Load all test file contents with acquit
* @returns {Object[]} acquit ast array
*/
function getTests() {
const testDocs = path.resolve(testPath, 'docs');
const filesToScan = [
...additionalTestFiles.map(v => path.join(testPath, v)),
...fs.readdirSync(testDocs).filter(v => !ignoredTestFiles.includes(v)).map(v => path.join(testDocs, v))
];
const retArray = [];
for (const file of filesToScan) {
try {
retArray.push(acquit.parse(fs.readFileSync(file).toString()));
} catch (err) {
// add a file path to a acquit error, for better debugging
err.filePath = file;
throw err;
}
}
return retArray.flat();
}
function deleteAllHtmlFiles() {
try {
console.log('Delete', path.join(versionObj.versionedPath, 'index.html'));
fs.unlinkSync(path.join(versionObj.versionedPath, 'index.html'));
} catch (err) {
if (err.code !== 'ENOENT') {
throw err;
}
}
const foldersToClean = [
path.join('.', versionObj.versionedPath, 'docs'),
path.join('.', versionObj.versionedPath, 'docs', 'tutorials'),
path.join('.', versionObj.versionedPath, 'docs', 'typescript'),
path.join('.', versionObj.versionedPath, 'docs', 'api'),
path.join('.', versionObj.versionedPath, 'docs', 'source', '_docs'),
'./tmp'
];
for (const folder of foldersToClean) {
let files = [];
try {
files = fs.readdirSync(folder);
} catch (err) {
if (err.code === 'ENOENT') {
continue;
}
}
for (const file of files) {
if (file.endsWith('.html')) {
console.log('Delete', path.join(folder, file));
fs.unlinkSync(path.join(folder, file));
}
}
}
}
function moveDocsToTemp() {
console.log('Moving docs to tmp dir...');
if (!versionObj.versionedPath) {
throw new Error('Cannot move unversioned deploy to /tmp');
}
try {
fs.rmSync('./tmp', { recursive: true });
} catch (err) {
if (err.code !== 'ENOENT') {
throw err;
}
}
const folder = versionObj.versionedPath.replace(/^\//, '');
const directory = fs.readdirSync(folder);
for (const file of directory) {
fsextra.moveSync(`${folder}/${file}`, `./tmp/${file}`);
}
}
/**
* Array of array of semver numbers, sorted with highest number first
* @example
* [[1,2,3], [0,1,2]]
* @type {number[][]}
*/
let filteredTags = [];
/**
* Parse a given semver version string to a number array
* @param {string} str The string to parse
* @returns number array or undefined
*/
function parseVersion(str) {
// there is no ending "$", because of "rc"-like versions
const versionReg = /^v?(\d+)\.(\d+)\.(\d+)/i;
const match = versionReg.exec(str);
if (match) {
const parsed = [parseInt(match[1]), parseInt(match[2]), parseInt(match[3])];
// fallback just in case some number did not parse
if (Number.isNaN(parsed[0]) || Number.isNaN(parsed[1]) || Number.isNaN(parsed[2])) {
console.log(`some version was matched but did not parse to int! "${str}"`);
return undefined;
}
return parsed;
}
// special case, to not log a warning
if (str === 'test') {
return undefined;
}
console.log(`Failed to parse version! got: ${str}`);
return undefined;
}
/**
* Get versions from git tags and put them into {@link filteredTags}
*/
function getVersions() {
// get all tags from git
// "trim" is used to remove the ending new-line
const res = childProcess.execSync('git tag').toString().trim();
filteredTags = res.split('\n')
// map all gotten tags if they match the regular expression
.map(parseVersion)
// filter out all null / undefined / falsy values
.filter(v => !!v)
// sort tags with latest (highest) first
.sort((a, b) => {
if (a[0] === b[0]) {
if (a[1] === b[1]) {
return b[2] - a[2];
}
return b[1] - a[1];
}
return b[0] - a[0];
});
if (filteredTags.length === 0) {
console.error('no tags found!');
filteredTags.push([0, 0, 0]);
}
}
/**
* Stringify a semver number array
* @param {number[]} arr The array to stringify
* @param {boolean} dotX If "true", return "5.X" instead of "5.5.5"
* @returns
*/
function stringifySemverNumber(arr, dotX) {
if (dotX) {
return `${arr[0]}.x`;
}
return `${arr[0]}.${arr[1]}.${arr[2]}`;
}
/**
* Get the latest version available
* @returns {Version}
*/
function getLatestVersion() {
return { listed: stringifySemverNumber(filteredTags[0]), path: '' };
}
/**
* Get the latest version for the provided major version
* @param {number} version major version to search for
* @returns {Version}
*/
function getLatestVersionOf(version) {
let foundVersion = filteredTags.find(v => v[0] === version);
// fallback to "0" in case a version cannot be found
if (!foundVersion) {
console.error(`Could not find a version for major "${version}"`);
foundVersion = [0, 0, 0];
}
return { listed: stringifySemverNumber(foundVersion), path: stringifySemverNumber(foundVersion, true) };
}
/**
* Try to get the current version on the checked-out branch
* @returns {Version}
*/
function getCurrentVersion() {
let versionToUse = pkg.version;
// i dont think this will ever happen, but just in case
if (!pkg.version) {
console.log('no version from package?');
versionToUse = getLatestVersion();
}
return { listed: versionToUse, path: stringifySemverNumber(parseVersion(versionToUse), true) };
}
// execute function to get all tags from git
getVersions();
/**
* @typedef {Object} Version
* @property {string} listed The string it is displayed as
* @property {string} path The path to use for the actual url
*/
/**
* Object for all version information
* @property {Version} currentVersion The current version this branch is built for
* @property {string} latestVersion The latest version available across the repository
* @property {Version[]} pastVersions The latest versions of past major versions to include as selectable
* @property {boolean} versionedDeploy Indicates wheter to build for a version or as latest (no prefix)
* @property {string} versionedPath The path to use for versioned deploy (empty string when "versionedDeploy" is false)
*/
const versionObj = (() => {
const base = {
currentVersion: getCurrentVersion(),
latestVersion: getLatestVersion(),
pastVersions: [
getLatestVersionOf(8),
getLatestVersionOf(7),
getLatestVersionOf(6)
]
};
const versionedDeploy = process.env.DOCS_DEPLOY ? !(base.currentVersion.listed === base.latestVersion.listed) : false;
const versionedPath = versionedDeploy ? `/docs/${base.currentVersion.path}` : '';
return {
...base,
versionedDeploy,
versionedPath
};
})();
// Create api dir if it doesn't already exist
try {
fs.mkdirSync(path.join(cwd, './docs/api'));
} catch {}
const docsFilemap = require('../docs/source/index');
const files = Object.keys(docsFilemap.fileMap);
// api explicitly imported for specific file loading
const apiReq = require('../docs/source/api');
const wrapMarkdown = (md, baseLayout, versionedPath) => `
extends ${baseLayout}
append style
link(rel="stylesheet", href="${versionedPath}/docs/css/inlinecpc.css")
script(type="text/javascript" src="${versionedPath}/docs/js/native.js")
block content