'use strict'; var util = require('util'); var path = require('path'); var cp = require('child_process'); var os = require('os'); var fs = require('fs'); var semver = require('semver'); var typedoc = require('typedoc'); var markdown = require('extra-markdown-text'); var javascript = require('extra-javascript-text'); var jsdoc = require('extra-jsdoc-text'); var kleur = require('kleur'); var url = require('url'); var rest = require('@octokit/rest'); function _interopNamespaceDefault(e) { var n = Object.create(null); if (e) { Object.keys(e).forEach(function (k) { if (k !== 'default') { var d = Object.getOwnPropertyDescriptor(e, k); Object.defineProperty(n, k, d.get ? d : { enumerable: true, get: function () { return e[k]; } }); } }); } n.default = e; return Object.freeze(n); } var util__namespace = /*#__PURE__*/_interopNamespaceDefault(util); var path__namespace = /*#__PURE__*/_interopNamespaceDefault(path); var cp__namespace = /*#__PURE__*/_interopNamespaceDefault(cp); var os__namespace = /*#__PURE__*/_interopNamespaceDefault(os); var fs__namespace = /*#__PURE__*/_interopNamespaceDefault(fs); var semver__namespace = /*#__PURE__*/_interopNamespaceDefault(semver); var typedoc__namespace = /*#__PURE__*/_interopNamespaceDefault(typedoc); var markdown__namespace = /*#__PURE__*/_interopNamespaceDefault(markdown); var javascript__namespace = /*#__PURE__*/_interopNamespaceDefault(javascript); var jsdoc__namespace = /*#__PURE__*/_interopNamespaceDefault(jsdoc); function kebabCase(x, sep = "-") { var rdelta = /([^A-Z])([A-Z])|(\D)(\d)/g; var rtrim = /^[^a-zA-Z0-9\.]+|[^a-zA-Z0-9\.]+$/g; var rsep = /[^a-zA-Z0-9\.]+/g; x = x.replace(rdelta, `$1$3${sep}$2$4`); x = x.replace(rsep, sep); x = x.replace(rtrim, ""); return x.toLowerCase(); } function wrapText(x, cols = 0) { var a = "", cols = cols || x.length; for (var i = 0; i < x.length; i += cols) a += x.substring(i, i + cols) + "\n"; return a.substring(0, a.length - 1); } function indentText(x, pre = "") { return x.split("\n").map(l => pre + l).join("\n").replace(/[ \t]+\n/g, "\n"); } function filename(pth) { var f = path__namespace.basename(pth); return f.replace(/\..*/, ""); } function symbolname(pth) { return filename(pth).replace(/[^\w$]+/g, "_"); } function keywordname(pth) { return kebabCase(filename(pth)).replace(/\W+/g, "-"); } function fixup(x) { x = x || ""; x = typeof x !== "string" ? util__namespace.inspect(x) : x; return x.replace(/^\w+:/, (m) => kleur.bold(m)); } function error(x) { console.error(kleur.red(fixup(x))); } function warn(x) { console.warn(kleur.yellow(fixup(x))); } function log(x) { console.log(kleur.cyan(fixup(x))); } function info(x) { console.info(kleur.grey(fixup(x))); } function exec(cmd, options) { var o = Object.assign({ stdio: [0, 1, 2] }, options); if (!o.commandHide) info(`$ ${cmd}`); var a = cp__namespace.execSync(cmd, o); if (!o.commandHide) info(); return a; } function execStr(cmd, options) { info(`$ ${cmd}`); var o = Object.assign({ encoding: "utf8" }, options); var a = cp__namespace.execSync(cmd, o).toString().trim(); info(); return a; } function readFileText(pth) { var txt = fs__namespace.readFileSync(pth, "utf8"); return txt.replace(/\r?\n/g, "\n"); } function writeFileText(pth, txt) { var txt = txt.replace(/\r?\n/g, os__namespace.EOL); fs__namespace.writeFileSync(pth, txt); } function readJson(pth) { return JSON.parse(readFileText(pth)); } function writeJson(pth, val) { writeFileText(pth, JSON.stringify(val, null, 2) + "\n"); } function readDocument(pth) { var data = fs__namespace.existsSync(pth) ? fs__namespace.readFileSync(pth) : null; return { path: pth, data }; } function writeDocument(doc) { if (doc.data != null) fs__namespace.writeFileSync(doc.path, doc.data); else if (fs__namespace.existsSync(doc.path)) fs__namespace.unlinkSync(doc.path); } function gitRemoteUrl() { return execStr(`git config --get remote.origin.url`); } function gitCommitPush(msg = "", options = null) { var o = Object.assign({ commit: "", push: "" }, options); if (msg) o.commit += ` -m "${msg}"`; else o.commit += ` --amend --no-edit`; if (!msg) o.push += ` -f`; exec(`git add .`, o); exec(`git commit${o.commit}`, o); exec(`git push${o.push}`, o); } function gitSetupBranch(branch, options = null) { var o = Object.assign({}, options); log(`Creating ${branch} branch ...`); exec(`git checkout --orphan ${branch}`, o); exec(`git rm -rf .`, o); exec(`git clean -fxd`, o); exec(`touch ${o.file || "index.html"}`, o); var co = Object.assign({ push: ` --set-upstream origin ${branch}` }, options); gitCommitPush("initial commit", co); } function addBanner(txt) { txt = txt.trim(); if (txt.length === 0) return ""; if (/^\/\/[^\n]*$|^\/\*[\s\S]*?\*\/$/.test(txt)) return `${txt}\n`; if (txt.includes("\n")) return `/**\n${txt}\n*/\n`; return `/** ${txt} */\n`; } function bundleEnvArgs(env) { var a = ""; if (!env) return a; for (var k in env) a += ` --environment ${k}:${env[k]}`; return a; } function bundleScript(src, options) { var o = Object.assign({}, options); if (src) src = src.replace(/\.ts$/, ".js"); var cfg = o.config || "rollup.config.js"; var inp = src ? `-i "${src}"` : ""; var env = bundleEnvArgs(o.env); exec(`rollup -c "${cfg}" ${inp} ${env}`); } function webifyScript(src, dst, options) { var o = Object.assign({}, options); var cjs = !o.format || /c?js/i.test(o.format); var tfm = o.format === "esm" ? "-t babelify" : ""; var sym = o.symbol ? `-s "${o.symbol}"` : ""; if (cjs) exec(`browserify "${src}" ${tfm} -o "${src}.1" ${sym}`); else exec(`cp "${src}" "${src}.1"`); exec(`terser "${src}.1" -o "${src}.2" -c -m`); var txt = readFileText(`${src}.2`); writeFileText(dst, addBanner(o.banner || "") + txt); exec(`rm -f "${src}.1"`); exec(`rm -f "${src}.2"`); } function jsdocifyScript(src, dst, fm) { var txt = readFileText(src); txt = javascript__namespace.replaceJsdocSymbols(txt, (full, txt, name, kind, isExported, isDefault) => { var a = fm(Object.assign(jsdoc__namespace.parse(txt), { name, kind, isExported, isDefault })); return a ? full.replace(txt, jsdoc__namespace.stringify(a)) : full; }); writeFileText(dst, txt); } function parseGithubUrl(url$1) { var p = new url.URL(url$1).pathname; p = p.replace(/^\/|^.*?:/, ""); p = p.replace(/^git+|\.git$/, ""); var [owner, repo] = p.split("/"); return { owner, repo }; } function githubTopics(ks) { return ks.map(keywordname).filter(k => k.length <= 35).slice(0, 20); } async function updateGithubRepoDetails(options = null) { var E = process.env; var m = readMetadata("."); var u = parseGithubUrl(m.repository.url); var o = Object.assign({}, options); var owner = o.owner || u.owner; var repo = o.repo || u.repo; var description = o.description || m.description; var homepage = o.homepage || `https://www.npmjs.com/package/${m.name}`; var topics = githubTopics(o.topics || m.keywords); var octokit = new rest.Octokit({ auth: o.auth || E.GITHUB_TOKEN }); info("Updating GitHub details:\n"); info(`Description: ${description}`); info(`Website: ${homepage}`); info(`Topics: ${(topics || []).join(", ")}`); await octokit.repos.update({ owner, repo, description, homepage }); await octokit.repos.replaceAllTopics({ owner, repo, names: topics }); } function readMetadata(dir = ".") { var pth = path__namespace.join(dir, "package.json"); return readJson(pth); } function writeMetadata(dir, val) { var pth = path__namespace.join(dir, "package.json"); writeJson(pth, val); } function registry(dir = ".") { var cwd = dir; return execStr(`npm config get registry`, { cwd }); } function setRegistry(dir, url) { var pth = path__namespace.join(dir, ".npmrc"); var txt = fs__namespace.existsSync(pth) ? readFileText(pth) : ""; var has = /^registry\s*=/.test(txt); if (has) txt = txt.replace(/^registry\s*=.*$/gm, `registry=${url}`); else txt = txt + `\nregistry=${url}`; writeFileText(pth, txt.trim() + "\n"); } function latestVersion(name) { return execStr(`npm view ${name} version`); } function nextUnpublishedVersion(name, ver) { var u = latestVersion(name); var d = semver__namespace.diff(u, ver); if (d === "major" || d === "minor") return ver; if (semver__namespace.lt(u, ver)) return ver; return semver__namespace.inc(u, "patch"); } function publish(dir = ".") { var cwd = dir; exec(`npm publish`, { cwd }); } function publishGithub(dir, owner) { var err = null; var _package = readDocument(path__namespace.join(dir, "package.json")); var _npmrc = readDocument(path__namespace.join(dir, ".npmrc")); var m = readMetadata(dir); var pkg = m.name.replace("@", "").replace("/", "--"); m.name = `@${owner}/${pkg}`; writeMetadata(dir, m); setRegistry(dir, `https://npm.pkg.github.com/${owner}`); try { publish(dir); } catch (e) { err = e; } writeDocument(_npmrc); writeDocument(_package); if (err) throw err; } function generateDocs(src, out = ".docs") { exec(`typedoc --plugin extra-typedoc-theme "${src}" --out "${out}"`); } function publishDocs(dir = ".docs") { var url = gitRemoteUrl(); var cwd = fs__namespace.mkdtempSync(path__namespace.join(os__namespace.tmpdir(), dir)); exec(`git clone ${url} "${cwd}"`); try { exec(`git checkout gh-pages`, { cwd }); } catch (e) { gitSetupBranch("gh-pages", { cwd }); } exec(`rm -rf "${cwd}"/*`); exec(`mv "${dir}"/* "${cwd}"/`); gitCommitPush("", { cwd }); exec(`rm -rf ${cwd}`); } function docsRefer(docs, r) { if (!r.target) return r; return docsRefer(docs, docs.getReflectionById(r.target)); } function docsName(r) { return r.name; } function docsLocation(r) { var [s] = r.sources || []; return s == null ? null : s.fileName + ":" + s.line.toString().padStart(6, "0"); } function docsFlags(r) { return r.flags; } function docsKind(r) { return typedoc.ReflectionKind[r.kind]; } function docsFindSignatures(r) { if (r.signatures) return r.signatures; if (r.declaration) return docsFindSignatures(r.declaration); if (r.type) return docsFindSignatures(r.type); return []; } function docsFindComment(r, sig = 0) { if (r == null) return null; if (r.comment) return r.comment; return docsFindComment(docsFindSignatures(r)[sig]); } function docsChildCount(r) { return r.children ? r.children.length : 0; } function docsParameterCount(r) { return r.parameters ? r.parameters.length : 0; } function docsSignatureCount(r) { return docsFindSignatures(r).length; } function docsType(r, sig = 0) { if (r == null) return null; if (r.type) return r.type.toString(); if (/class|interface|type/i.test(typedoc.ReflectionKind[r.kind])) return r.name; return docsType(docsFindSignatures(r)[sig]); } function contentText(ps) { var a = ""; for (var p of ps) a += p.text; return a; } function docsDescription(r, sig = 0) { var c = docsFindComment(r, sig); if (c == null || c.summary == null) return null; return contentText(c.summary).trim(); } function docsReturns(r, sig = 0) { var c = docsFindComment(r, sig); if (c == null) return null; var t = c.getTag("@returns"); if (t == null) return null; return contentText(t.content); } function docsDetails(r) { var s = r.children || r.parameters || docsFindSignatures(r); return { name: docsName(r), location: docsLocation(r), flags: docsFlags(r), kind: docsKind(r), type: docsType(r), description: docsDescription(r), children: s ? s.map(docsDetails) : null, returns: docsReturns(r), }; } function docsReferDetails(docs, r) { var s = docsRefer(docs, r); if (s === r) return docsDetails(r); var kind = `${docsKind(r)}/${docsKind(s)}`; return Object.assign(docsDetails(s), docsDetails(r), { kind }); } function loadDocs(entryPoints) { entryPoints = entryPoints || ["src/index.ts"]; var app = new typedoc__namespace.Application(); app.options.addReader(new typedoc__namespace.TSConfigReader()); app.options.addReader(new typedoc__namespace.TypeDocReader()); app.bootstrap({ entryPoints }); return app.convert(); } function wikiText(txt, short = false) { txt = txt.replace(/\{@\w+\s+(.*?)\}/g, "`$1`"); if (short) txt = txt.replace(/([\?\!\.])\s[\s\S]*/, "$1").replace(/\s*\n\s*/, " "); return txt.trim(); } function wikiDescription(txt, cols = 0) { if (!txt) return ""; return wrapText(wikiText(txt), cols).split("\n").map(l => `// ${l}`).join("\n") + "\n"; } function wikiFlagsPrefix(d) { var a = "", f = d.flags; if (f.isAbstract) a += "abstract "; if (f.isReadonly) a += "readonly "; if (f.isStatic) a += "static "; return a; } function wikiVariable(d, e, o) { var text = wikiDescription(e === null || e === void 0 ? void 0 : e.description, o === null || o === void 0 ? void 0 : o.wrapText), f = d.flags; var code = wikiFlagsPrefix(d) + (f.isConst ? "const" : "var") + " "; code += d.name + ((o === null || o === void 0 ? void 0 : o.withType) ? ": " + d.type : "") + "\n"; return text + code; } function wikiProperty(d, e, o) { var text = wikiDescription(e === null || e === void 0 ? void 0 : e.description, o === null || o === void 0 ? void 0 : o.wrapText); var code = wikiFlagsPrefix(d) + d.name + ((o === null || o === void 0 ? void 0 : o.withType) ? ": " + d.type : "") + ",\n"; return text + code; } function wikiInterface(d, e, o) { var text = wikiDescription(e === null || e === void 0 ? void 0 : e.description, o === null || o === void 0 ? void 0 : o.wrapText); var code = `interface ${d.name} {\n`; for (var c of d.children || []) code += indentText(wikiProperty(c, c, o), " "); code += "}\n"; return text + code; } function wikiParameter(d, e, o) { var a = "", f = d.flags; if (f.isReadonly) a += "readonly "; if (f.isRest) a += "..."; a += d.name; if (f.isOptional && !f.isRest) a += "?"; if (o === null || o === void 0 ? void 0 : o.withType) a += ": " + d.type; return a; } function wikiCallSignature(d, e, o) { var text = wikiDescription(e === null || e === void 0 ? void 0 : e.description, o === null || o === void 0 ? void 0 : o.wrapText); var code = wikiFlagsPrefix(d) + `function ${d.name}(`, children = d.children || []; for (var c of children) code += wikiParameter(c, c, o) + ", "; code = code.endsWith("(") ? code : code.substring(0, code.length - 2); code += ")" + ((o === null || o === void 0 ? void 0 : o.withType) ? ": " + d.type : "") + "\n"; var gap = Math.max(...children.map(p => p.name.length)) + 2; var desc = children.map(p => `// ${(p.name + ":").padEnd(gap, " ")}${p.description}`).join("\n") + "\n"; return text + code + desc; } function wikiFunction(d, e, o) { var children = d.children || [], c1 = e == null && children.length === 1; var code = children.map(c => wikiCallSignature(c, c1 ? null : c, o)).join("\n\n").trim() + "\n"; return code; } function wikiTypeAlias(d, e, o) { var text = wikiDescription(e === null || e === void 0 ? void 0 : e.description, o === null || o === void 0 ? void 0 : o.wrapText); var code = `type ${d.name} = ${d.type}\n`; return text + code; } function wikiClass(d, e, o) { var text = wikiDescription(e === null || e === void 0 ? void 0 : e.description, o === null || o === void 0 ? void 0 : o.wrapText); var code = wikiFlagsPrefix(d) + `class ${d.name} {\n`; for (var c of d.children || []) code += indentText(wikiCodeReference(c, o), " ") + "\n"; code += "}\n"; return text + code; } function wikiCodeReference(d, o) { var e = (o === null || o === void 0 ? void 0 : o.withDescription) ? d : null; switch (d.kind) { case "Variable": return wikiVariable(d, e, o); case "Interface": return wikiInterface(d, e, o); case "Function": return wikiFunction(d, e, o); case "Type alias": return wikiTypeAlias(d, e, o); case "Class": return wikiClass(d, e, o); default: return "ERROR: UNKNOWN KIND!\n"; } } function wikiCodeExample(d, o) { var repo = (o === null || o === void 0 ? void 0 : o.repo) || "repo"; var name = (o === null || o === void 0 ? void 0 : o.prefix) ? `${o === null || o === void 0 ? void 0 : o.prefix}.${d.name}` : d.name; var code = `const {${name}} = require('${repo}');\n\n\n`; var text = `// Example for ${d.name}\n`; var out = "// → OUTPUT\n"; return code + text + out; } function wikiMarkdown(d, o) { var owner = (o === null || o === void 0 ? void 0 : o.owner) || "owner"; var repo = (o === null || o === void 0 ? void 0 : o.repo) || "repo"; var name = (o === null || o === void 0 ? void 0 : o.prefix) ? `${o.prefix}.${d.name}` : d.name; return `${d.description}\n\n` + `> Alternatives: [${name}].
\n` + `> Similar: [${name}].\n\n` + `
\n\n` + "```javascript\n" + wikiCodeReference(d, o) + "```\n\n
\n\n" + "```javascript\n" + wikiCodeExample(d, o) + "```\n\n" + "
\n" + "
\n\n\n" + `## References\n\n` + `- [Example](https://www.example.com/)\n\n\n` + `[${name}]: https://github.com/${owner}/${repo}/wiki/${name}\n`; } function linkReferenceDocs(d, o) { var owner = (o === null || o === void 0 ? void 0 : o.owner) || "owner"; var repo = (o === null || o === void 0 ? void 0 : o.repo) || "repo"; var root = `https://${owner}.github.io/${repo}`; var pred = (o === null || o === void 0 ? void 0 : o.prefix) ? `${o.prefix}.` : ""; var prem = (o === null || o === void 0 ? void 0 : o.prefix) ? `modules/${o.prefix}.html` : "modules.html"; switch (d.kind) { case "Interface": return `[${d.name}]: ${root}/interfaces/` + `${pred}${d.name}.html`; case "Type alias": return `[${d.name}]: ${root}/types/` + `${pred}${d.name}.html`; case "Class": return `[${d.name}]: ${root}/classes/` + `${pred}${d.name}.html`; case "Function": return `[${d.name}]: ${root}/functions/` + `${pred}${d.name}.html`; case "Variable": return `[${d.name}]: ${root}/variables/` + `${pred}${d.name}.html`; default: return `[${d.name}]: ${root}/${prem}#${d.name}`; } } function linkReferenceWiki(d, o) { var owner = (o === null || o === void 0 ? void 0 : o.owner) || "owner"; var repo = (o === null || o === void 0 ? void 0 : o.repo) || "repo"; var name = (o === null || o === void 0 ? void 0 : o.prefix) ? `${o.prefix}.${d.name}` : d.name; return `[${d.name}]: https://github.com/${owner}/${repo}/wiki/${name}`; } function linkReference(d, o) { if (o === null || o === void 0 ? void 0 : o.useWiki) return linkReferenceWiki(d, o); return linkReferenceDocs(d, o); } function wikiUpdateIndex(txt, dm, fn) { return markdown__namespace.replaceTables(txt, (full, rows) => { if (rows.length < 1 || rows[0].length < 2) return full; rows = rows.map(r => [r[0].trim(), r[1].trim()]); if (!/property/i.test(rows[0][0])) return full; if (!/description/i.test(rows[0][1])) return full; var rmap = new Map(rows.map((r, i) => [r[0], i])); for (var d of dm.values()) { var dsc = fn ? fn(d) : d.description || " "; if (!dsc) continue; var key = `[${d.name}]`; var val = wikiText(dsc, true).trim(); if (!rmap.has(key)) rows.push([key, val]); else rows[rmap.get(key)][1] = val; } var top = "| " + rows[0].join(" | ") + " |\n"; var mid = "| " + rows[0].map(_ => ` ---- `).join(" | ") + " |\n"; var bot = rows.slice(1).map(r => "| " + r.join(" | ") + " |\n").join(""); return top + mid + bot; }); } function wikiUpdateLinkReferences(txt, dm, o) { txt = markdown__namespace.replaceLinkReferences(txt, (full, name) => { if (!dm.has(name)) return full; return linkReference(dm.get(name), o); }); var lset = new Set(markdown__namespace.links(txt).filter(x => !x.url).map(x => x.reference || x.name)); var rset = new Set(markdown__namespace.linkReferences(txt).map(x => x.name)); for (var l of lset) { if (rset.has(l)) continue; if (!dm.has(l)) continue; txt += linkReference(dm.get(l), o) + "\n"; } return txt; } function wikiUpdateDescription(txt, d) { return txt.replace(/[\s\S]+?\n\n/, `${d.description}\n\n`); } function wikiUpdateCodeReference(txt, d, o) { return txt.replace(/(```javascript\n)[\s\S]+?(```\n\n)/, `$1${wikiCodeReference(d, o)}$2`); } exports.addBanner = addBanner; exports.bundleScript = bundleScript; exports.docsChildCount = docsChildCount; exports.docsDescription = docsDescription; exports.docsDetails = docsDetails; exports.docsFlags = docsFlags; exports.docsKind = docsKind; exports.docsLocation = docsLocation; exports.docsName = docsName; exports.docsParameterCount = docsParameterCount; exports.docsRefer = docsRefer; exports.docsReferDetails = docsReferDetails; exports.docsReturns = docsReturns; exports.docsSignatureCount = docsSignatureCount; exports.docsType = docsType; exports.error = error; exports.exec = exec; exports.execStr = execStr; exports.generateDocs = generateDocs; exports.gitCommitPush = gitCommitPush; exports.gitSetupBranch = gitSetupBranch; exports.info = info; exports.jsdocifyScript = jsdocifyScript; exports.keywordname = keywordname; exports.latestVersion = latestVersion; exports.loadDocs = loadDocs; exports.log = log; exports.nextUnpublishedVersion = nextUnpublishedVersion; exports.parseGithubUrl = parseGithubUrl; exports.publish = publish; exports.publishDocs = publishDocs; exports.publishGithub = publishGithub; exports.readDocument = readDocument; exports.readFileText = readFileText; exports.readJson = readJson; exports.readMetadata = readMetadata; exports.registry = registry; exports.setRegistry = setRegistry; exports.symbolname = symbolname; exports.updateGithubRepoDetails = updateGithubRepoDetails; exports.warn = warn; exports.webifyScript = webifyScript; exports.wikiCodeExample = wikiCodeExample; exports.wikiCodeReference = wikiCodeReference; exports.wikiMarkdown = wikiMarkdown; exports.wikiUpdateCodeReference = wikiUpdateCodeReference; exports.wikiUpdateDescription = wikiUpdateDescription; exports.wikiUpdateIndex = wikiUpdateIndex; exports.wikiUpdateLinkReferences = wikiUpdateLinkReferences; exports.writeDocument = writeDocument; exports.writeFileText = writeFileText; exports.writeJson = writeJson; exports.writeMetadata = writeMetadata;