UNPKG

typedoc-better-json

Version:

Transforms typedoc's json output to a format that is better for creating custom documentation website

513 lines (500 loc) 16.6 kB
"use strict"; var __defProp = Object.defineProperty; var __getOwnPropDesc = Object.getOwnPropertyDescriptor; var __getOwnPropNames = Object.getOwnPropertyNames; var __hasOwnProp = Object.prototype.hasOwnProperty; var __export = (target, all) => { for (var name in all) __defProp(target, name, { get: all[name], enumerable: true }); }; var __copyProps = (to, from, except, desc) => { if (from && typeof from === "object" || typeof from === "function") { for (let key of __getOwnPropNames(from)) if (!__hasOwnProp.call(to, key) && key !== except) __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable }); } return to; }; var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod); var __async = (__this, __arguments, generator) => { return new Promise((resolve, reject) => { var fulfilled = (value) => { try { step(generator.next(value)); } catch (e) { reject(e); } }; var rejected = (value) => { try { step(generator.throw(value)); } catch (e) { reject(e); } }; var step = (x) => x.done ? resolve(x.value) : Promise.resolve(x.value).then(fulfilled, rejected); step((generator = generator.apply(__this, __arguments)).next()); }); }; // src/index.ts var src_exports = {}; __export(src_exports, { transform: () => transform }); module.exports = __toCommonJS(src_exports); // src/utils/getReadableType.ts function getReadableType(typeObj) { var _a; switch (typeObj.type) { case "intrinsic": { return typeObj.name; } case "reflection": { if (typeObj.declaration.children) { return `{ ${(_a = typeObj.declaration.children) == null ? void 0 : _a.map((child) => { if (child.type) { return `${createValidKey(child.name)}: ${getReadableType( child.type )}`; } return ""; }).join(", ")} }`; } else if (typeObj.declaration.signatures) { return typeObj.declaration.signatures.map(readableFunctionSignature).join(" | "); } return `{}`; } case "reference": { if (typeObj.typeArguments) { return `${typeObj.name}<${typeObj.typeArguments.map(getReadableType).join(", ")}>`; } return typeObj.name; } case "union": { return typeObj.types.map((t) => `(${getReadableType(t)})`).join(" | "); } case "literal": { if (typeof typeObj.value === "string") { return `"${typeObj.value}"`; } return typeObj.value + ""; } case "array": { const type = getReadableType(typeObj.elementType); if (type.length > 50) { return `Array<${type}>`; } return `${type}[]`; } case "conditional": { return `${getReadableType(typeObj.checkType)} extends ${getReadableType( typeObj.extendsType )} ? ${getReadableType(typeObj.trueType)} : ${getReadableType( typeObj.falseType )}`; } case "indexedAccess": { return `${getReadableType(typeObj.objectType)}[${getReadableType( typeObj.indexType )}]`; } case "intersection": { return typeObj.types.map((t) => `${getReadableType(t)}`).join(" & "); } case "mapped": { return `{[${typeObj.parameter} in ${getReadableType( typeObj.parameterType )}] : ${getReadableType(typeObj.templateType)}}`; } case "tuple": { if (typeObj.elements) { return `[${typeObj.elements.map(getReadableType).join(", ")}]`; } return `[]`; } case "query": { return `typeof ${getReadableType(typeObj.queryType)}`; } case "typeOperator": { return `${typeObj.operator} ${getReadableType(typeObj.target)}`; } case "templateLiteral": { return "`" + typeObj.head + typeObj.tail.map((t) => `\${${getReadableType(t[0])}}` + t[1]).join("") + "`"; } case "inferred": { return `infer ${typeObj.name}`; } case "rest": { return `...(${getReadableType(typeObj.elementType)})`; } case "unknown": { return typeObj.name; } case "predicate": { if (typeObj.targetType) { return `${typeObj.name} is (${getReadableType(typeObj.targetType)})`; } throw new Error("Failed to get readable type of type 'predicate' "); } case "namedTupleMember": { return `${typeObj.name}: ${getReadableType(typeObj.element)}`; } case "optional": { return `${getReadableType(typeObj.elementType)}?`; } default: { throw new Error("Failed to create a readable type for type"); } } } function readableFunctionSignature(signature) { var _a; const parameters = ((_a = signature.parameters) == null ? void 0 : _a.map((p) => p.type ? `${p.name} : ${getReadableType(p.type)}` : p.name).join(", ")) || ""; const returnType = signature.type ? ` => ${getReadableType(signature.type)}` : ""; return `((${parameters})${returnType})`; } function createValidKey(str) { if (str.includes(" ") || str.includes("-")) { return `"${str}"`; } return str; } // src/utils/markdown.ts var import_mdast_util_from_markdown = require("mdast-util-from-markdown"); function simplifyNode(node) { delete node.position; if ("children" in node) { node.children.forEach(simplifyNode); } return node; } function parseMarkdown(markdown) { const tree = (0, import_mdast_util_from_markdown.fromMarkdown)(markdown, {}); tree.children.forEach(simplifyNode); return tree.children; } // src/nodes/summary.ts function getSummaryDoc(summary) { if (!summary) return void 0; return summary.map((s) => parseMarkdown(s.text)).flat(); } // src/nodes/function.ts function getFunctionDoc(data) { var _a, _b, _c; return { kind: "function", name: data.name, signatures: (_a = data.signatures) == null ? void 0 : _a.map(getFunctionSignatureDoc), source: (_c = (_b = data.sources) == null ? void 0 : _b[0]) == null ? void 0 : _c.url }; } function getFunctionSignatureDoc(signature) { var _a, _b, _c, _d, _e, _f, _g, _h; const output = { summary: getSummaryDoc((_a = signature.comment) == null ? void 0 : _a.summary), parameters: (_b = signature.parameters) == null ? void 0 : _b.map((param) => { var _a2; const arg = { name: param.name, type: param.type ? getReadableType(param.type) : void 0, summary: getSummaryDoc((_a2 = param.comment) == null ? void 0 : _a2.summary), flags: Object.keys(param.flags).length > 0 ? param.flags : void 0 }; return arg; }), typeParameters: (_c = signature.typeParameter) == null ? void 0 : _c.map((param) => { const typeParam = { name: param.name, extendsType: param.type ? getReadableType(param.type) : void 0 }; return typeParam; }), blockTags: (_e = (_d = signature.comment) == null ? void 0 : _d.blockTags) == null ? void 0 : _e.filter( (w) => w.tag !== "@returns" ), returns: { type: signature.type ? getReadableType(signature.type) : void 0, summary: getSummaryDoc( (_h = (_g = (_f = signature.comment) == null ? void 0 : _f.blockTags) == null ? void 0 : _g.find((tag) => tag.tag === "@returns")) == null ? void 0 : _h.content ) } }; return output; } // src/utils/isComponentType.ts function isComponentType(data) { var _a; return data.signatures && data.signatures[0] && ((_a = data.signatures[0].type) == null ? void 0 : _a.type) === "reference" && data.signatures[0].type.name && isComponentName(data.signatures[0].type.name) && (data.signatures[0].type.name === "ReactNode" || data.signatures[0].type.name === "Element"); } function isComponentName(str) { const firstChar = str[0]; if (firstChar && firstChar === firstChar.toUpperCase()) { return true; } return false; } // src/nodes/interface.ts function getInterfaceDoc(data) { var _a, _b, _c; return { kind: "type", name: data.name, summary: getSummaryDoc((_a = data.comment) == null ? void 0 : _a.summary), source: (_c = (_b = data.sources) == null ? void 0 : _b[0]) == null ? void 0 : _c.url, type: data.type ? getReadableType(data.type) : void 0, typeDeclaration: getDeclaration(data.type) }; } function getDeclaration(typeObj) { var _a; if ((typeObj == null ? void 0 : typeObj.type) !== "reflection") { return void 0; } return (_a = typeObj.declaration.children) == null ? void 0 : _a.map((child) => { var _a2; if (!child.type) { throw new Error(`No type found for type declaration ${child.name}`); } const output = { name: child.name, type: getReadableType(child.type), summary: getSummaryDoc((_a2 = child.comment) == null ? void 0 : _a2.summary) }; return output; }); } // src/nodes/enum.ts function getEnumDoc(data) { var _a, _b, _c; return { kind: "enum", name: data.name, summary: getSummaryDoc((_a = data.comment) == null ? void 0 : _a.summary), source: (_c = (_b = data.sources) == null ? void 0 : _b[0]) == null ? void 0 : _c.url, members: getMembers(data) }; } function getMembers(data) { if (!data.children) { throw new Error(`Failed to get members for enum ${data.name}`); } const output = data.children.map((child) => { var _a; if (!child.type) { throw new Error(`No type found for enum member ${child.name}`); } return { name: child.name, value: getReadableType(child.type), summary: getSummaryDoc((_a = child.comment) == null ? void 0 : _a.summary) }; }); return output; } // src/nodes/variable.ts function getVariableDoc(data) { var _a, _b, _c; return { kind: "variable", name: data.name, summary: getSummaryDoc((_a = data.comment) == null ? void 0 : _a.summary), source: (_c = (_b = data.sources) == null ? void 0 : _b[0]) == null ? void 0 : _c.url, type: data.type ? getReadableType(data.type) : void 0, typeDeclaration: data.type ? getDeclaration2(data.type) : void 0, flags: Object.keys(data.flags).length > 0 ? data.flags : void 0 }; } function getDeclaration2(typeObj) { var _a; if (typeObj.type === "reflection") { return (_a = typeObj.declaration.children) == null ? void 0 : _a.map((child) => { var _a2, _b; if (child.signatures) { const output = getFunctionDoc(child); return output; } if (((_a2 = child.type) == null ? void 0 : _a2.type) === "reflection" && child.type.declaration.signatures) { const output = getFunctionDoc( child.type.declaration ); output.name = child.name; return output; } if (child.type) { const output = { name: child.name, type: getReadableType(child.type), summary: getSummaryDoc((_b = child.comment) == null ? void 0 : _b.summary) }; return output; } throw new Error(`Unknown type declaration node ${child.name}`); }); } if (typeObj.type === "array") { return getDeclaration2(typeObj.elementType); } } // src/nodes/accessor.ts function getAccessorDoc(data) { var _a, _b, _c, _d, _e, _f, _g, _h; return { kind: "accessor", name: data.name, source: (_b = (_a = data.sources) == null ? void 0 : _a[0]) == null ? void 0 : _b.url, summary: getSummaryDoc((_c = data.comment) == null ? void 0 : _c.summary), returns: data.getSignature ? { type: data.getSignature.type ? getReadableType(data.getSignature.type) : void 0, summary: getSummaryDoc( (_f = (_e = (_d = data.getSignature.comment) == null ? void 0 : _d.blockTags) == null ? void 0 : _e.find( (tag) => tag.tag === "@returns" )) == null ? void 0 : _f.content ) } : void 0, blockTags: (_h = (_g = data.comment) == null ? void 0 : _g.blockTags) == null ? void 0 : _h.filter((w) => w.tag !== "@returns"), flags: Object.keys(data.flags).length > 0 ? data.flags : void 0 }; } // src/nodes/class.ts var groupMappings = { Constructors: "constructors", Properties: "properties", Methods: "methods", Accessors: "accessors" }; function getClassDoc(data) { var _a, _b, _c, _d, _e, _f, _g; const methods = []; const properties = []; const constructors = []; const accessors = []; const childrenMap = {}; (_a = data.children) == null ? void 0 : _a.forEach((child) => { childrenMap[child.id] = child; }); (_b = data.groups) == null ? void 0 : _b.forEach((group) => { var _a2; const title = group.title; if (group.title in groupMappings) { (_a2 = group.children) == null ? void 0 : _a2.forEach((childId) => { const childData = childrenMap[childId]; if (!childData) { throw new Error(`Failed to resolve child id ${childId}`); } switch (groupMappings[title]) { case "methods": { methods.push(getFunctionDoc(childData)); break; } case "properties": { properties.push(getVariableDoc(childData)); break; } case "constructors": { constructors.push(getFunctionDoc(childData)); break; } case "accessors": { accessors.push(getAccessorDoc(childData)); break; } } }); } else { throw new Error(`Unknown group in class ${group.title}`); } }); if (constructors.length > 1) { throw new Error(`Found more than 1 constructors on ${data.name} Class`); } const output = { kind: "class", name: data.name, source: (_d = (_c = data.sources) == null ? void 0 : _c[0]) == null ? void 0 : _d.url, summary: getSummaryDoc((_e = data.comment) == null ? void 0 : _e.summary), blockTags: (_f = data.comment) == null ? void 0 : _f.blockTags, constructor: constructors[0], methods: methods.length > 0 ? methods : void 0, properties: properties.length > 0 ? properties : void 0, accessors: accessors.length > 0 ? accessors : void 0, implements: (_g = data.implementedTypes) == null ? void 0 : _g.map((t) => getReadableType(t)) }; return output; } // src/transform.ts var groupNameMap = { Interfaces: "types", "Type Aliases": "types", Variables: "variables", Functions: "functions", Classes: "classes", Enumerations: "enums" }; function transform(inputData) { var _a, _b; const functions = []; const hooks = []; const components = []; const types = []; const variables = []; const enums = []; const classes = []; const childrenMap = {}; (_a = inputData.children) == null ? void 0 : _a.forEach((child) => { childrenMap[child.id] = child; }); (_b = inputData.groups) == null ? void 0 : _b.forEach((group) => { var _a2; if (group.title in groupNameMap) { const mappedTitle = groupNameMap[group.title]; (_a2 = group.children) == null ? void 0 : _a2.map((childId) => __async(this, null, function* () { const childData = childrenMap[childId]; if (!childData) { throw new Error(`Failed to resolve child id ${childId}`); } switch (mappedTitle) { case "functions": { if (childData.name.startsWith("use")) { hooks.push(getFunctionDoc(childData)); } else if (isComponentType(childData)) { components.push(getFunctionDoc(childData)); } else { functions.push(getFunctionDoc(childData)); } break; } case "types": { types.push(getInterfaceDoc(childData)); break; } case "variables": { variables.push(getVariableDoc(childData)); break; } case "classes": { classes.push(getClassDoc(childData)); break; } case "enums": { enums.push(getEnumDoc(childData)); } } })); } }); const output = { functions: functions.length > 0 ? functions : void 0, hooks: hooks.length > 0 ? hooks : void 0, variables: variables.length > 0 ? variables : void 0, types: types.length > 0 ? types : void 0, components: components.length > 0 ? components : void 0, enums: enums.length > 0 ? enums : void 0, classes: classes.length > 0 ? classes : void 0 }; return output; } // Annotate the CommonJS export names for ESM import in node: 0 && (module.exports = { transform });