|
| 1 | +/** |
| 2 | + * WARNING: this is a very, very rudimentary d.ts bundler; it only works |
| 3 | + * in the TS project thanks to our history using namespaces, which has |
| 4 | + * prevented us from duplicating names across files, and allows us to |
| 5 | + * bundle as namespaces again, even though the project is modules. |
| 6 | + */ |
| 7 | + |
| 8 | +import * as assert from "assert"; |
| 9 | +import * as fs from "fs"; |
| 10 | +import * as path from "path"; |
| 11 | +import * as minimist from "minimist"; |
| 12 | +import * as ts from "../lib/typescript"; |
| 13 | + |
| 14 | +const dotDts = ".d.ts"; |
| 15 | + |
| 16 | +const options = minimist(process.argv.slice(2), { |
| 17 | + string: ["project", "entrypoint", "output"], |
| 18 | +}); |
| 19 | + |
| 20 | +const entrypoint = options.entrypoint; |
| 21 | +const output = options.output; |
| 22 | + |
| 23 | +assert(typeof entrypoint === "string" && entrypoint); |
| 24 | +assert(typeof output === "string" && output); |
| 25 | +assert(output.endsWith(dotDts)); |
| 26 | + |
| 27 | +const internalOutput = output.substring(0, output.length - dotDts.length) + ".internal" + dotDts; |
| 28 | + |
| 29 | +console.log(`Bundling ${entrypoint} to ${output} and ${internalOutput}`); |
| 30 | + |
| 31 | +const newLineKind = ts.NewLineKind.LineFeed; |
| 32 | +const newLine = newLineKind === ts.NewLineKind.LineFeed ? "\n" : "\r\n"; |
| 33 | + |
| 34 | +function isDeclarationStatement(node: ts.Node): node is ts.DeclarationStatement { |
| 35 | + return (ts as any).isDeclarationStatement(node); |
| 36 | +} |
| 37 | + |
| 38 | +function isInternalDeclaration(node: ts.Node): boolean { |
| 39 | + return (ts as any).isInternalDeclaration(node, node.getSourceFile()); |
| 40 | +} |
| 41 | + |
| 42 | +function getParentVariableStatement(node: ts.VariableDeclaration): ts.VariableStatement { |
| 43 | + const declarationList = node.parent as ts.VariableDeclarationList; |
| 44 | + assert(ts.isVariableDeclarationList(declarationList), `expected VariableDeclarationList at ${nodeToLocation(node)}`); |
| 45 | + assert(declarationList.declarations.length === 1, `expected VariableDeclarationList of length 1 at ${nodeToLocation(node)}`); |
| 46 | + const variableStatement = declarationList.parent; |
| 47 | + assert(ts.isVariableStatement(variableStatement), `expected VariableStatement at ${nodeToLocation(node)}`); |
| 48 | + return variableStatement; |
| 49 | +} |
| 50 | + |
| 51 | +function getDeclarationStatement(node: ts.Declaration): ts.Statement | undefined { |
| 52 | + if (ts.isVariableDeclaration(node)) { |
| 53 | + return getParentVariableStatement(node); |
| 54 | + } |
| 55 | + else if (isDeclarationStatement(node)) { |
| 56 | + return node; |
| 57 | + } |
| 58 | + return undefined; |
| 59 | +} |
| 60 | + |
| 61 | +const nullTransformationContext: ts.TransformationContext = (ts as any).nullTransformationContext; |
| 62 | + |
| 63 | +const program = ts.createProgram([entrypoint], { target: ts.ScriptTarget.ES5 }); |
| 64 | + |
| 65 | +const typeChecker = program.getTypeChecker(); |
| 66 | + |
| 67 | +const sourceFile = program.getSourceFile(entrypoint); |
| 68 | +assert(sourceFile); |
| 69 | +const moduleSymbol = typeChecker.getSymbolAtLocation(sourceFile); |
| 70 | +assert(moduleSymbol); |
| 71 | + |
| 72 | +const printer = ts.createPrinter({ newLine: newLineKind }); |
| 73 | + |
| 74 | + |
| 75 | +const publicLines: string[] = []; |
| 76 | +const internalLines: string[] = []; |
| 77 | + |
| 78 | +const indent = " "; |
| 79 | +let currentIndent = ""; |
| 80 | + |
| 81 | +function increaseIndent() { |
| 82 | + currentIndent += indent; |
| 83 | +} |
| 84 | + |
| 85 | +function decreaseIndent() { |
| 86 | + currentIndent = currentIndent.slice(indent.length); |
| 87 | +} |
| 88 | + |
| 89 | +enum WriteTarget { |
| 90 | + Public = 1 << 0, |
| 91 | + Internal = 1 << 1, |
| 92 | + Both = Public | Internal, |
| 93 | +} |
| 94 | + |
| 95 | +function write(s: string, target: WriteTarget) { |
| 96 | + if (!target) { |
| 97 | + return; |
| 98 | + } |
| 99 | + |
| 100 | + const toPush = !s ? [""] : s.split(/\r?\n/).filter(line => line).map(line => (currentIndent + line).trimEnd()); |
| 101 | + |
| 102 | + if (target & WriteTarget.Public) { |
| 103 | + publicLines.push(...toPush); |
| 104 | + } |
| 105 | + if (target & WriteTarget.Internal) { |
| 106 | + internalLines.push(...toPush); |
| 107 | + } |
| 108 | +} |
| 109 | + |
| 110 | +function writeNode(node: ts.Node, sourceFile: ts.SourceFile, target: WriteTarget) { |
| 111 | + write(printer.printNode(ts.EmitHint.Unspecified, node, sourceFile), target); |
| 112 | +} |
| 113 | + |
| 114 | +const containsPublicAPICache = new Map<ts.Symbol, boolean>(); |
| 115 | + |
| 116 | +function containsPublicAPI(symbol: ts.Symbol): boolean { |
| 117 | + const cached = containsPublicAPICache.get(symbol); |
| 118 | + if (cached !== undefined) { |
| 119 | + return cached; |
| 120 | + } |
| 121 | + |
| 122 | + const result = containsPublicAPIWorker(); |
| 123 | + containsPublicAPICache.set(symbol, result); |
| 124 | + return result; |
| 125 | + |
| 126 | + function containsPublicAPIWorker(): boolean { |
| 127 | + if (!symbol.declarations?.length) { |
| 128 | + return false; |
| 129 | + } |
| 130 | + |
| 131 | + if (symbol.flags & ts.SymbolFlags.Alias) { |
| 132 | + const resolved = typeChecker.getAliasedSymbol(symbol); |
| 133 | + return containsPublicAPI(resolved); |
| 134 | + } |
| 135 | + |
| 136 | + // Namespace barrel; actual namespaces are checked below. |
| 137 | + if (symbol.flags & ts.SymbolFlags.ValueModule && symbol.valueDeclaration?.kind === ts.SyntaxKind.SourceFile) { |
| 138 | + for (const me of typeChecker.getExportsOfModule(symbol)) { |
| 139 | + if (containsPublicAPI(me)) { |
| 140 | + return true; |
| 141 | + } |
| 142 | + } |
| 143 | + return false; |
| 144 | + } |
| 145 | + |
| 146 | + for (const decl of symbol.declarations) { |
| 147 | + const statement = getDeclarationStatement(decl); |
| 148 | + if (statement && !isInternalDeclaration(statement)) { |
| 149 | + return true; |
| 150 | + } |
| 151 | + } |
| 152 | + |
| 153 | + return false; |
| 154 | + } |
| 155 | +} |
| 156 | + |
| 157 | +function nodeToLocation(decl: ts.Node): string { |
| 158 | + const sourceFile = decl.getSourceFile(); |
| 159 | + const lc = sourceFile.getLineAndCharacterOfPosition(decl.pos); |
| 160 | + return `${sourceFile.fileName}:${lc.line}:${lc.character}`; |
| 161 | +} |
| 162 | + |
| 163 | +function removeDeclareConstExport(node: ts.Node): ts.Node | undefined { |
| 164 | + switch (node.kind) { |
| 165 | + case ts.SyntaxKind.DeclareKeyword: // No need to emit this in d.ts files. |
| 166 | + case ts.SyntaxKind.ConstKeyword: // Remove const from const enums. |
| 167 | + case ts.SyntaxKind.ExportKeyword: // No export modifier; we are already in the namespace. |
| 168 | + return undefined; |
| 169 | + } |
| 170 | + return node; |
| 171 | +} |
| 172 | + |
| 173 | +function emitAsNamespace(name: string, moduleSymbol: ts.Symbol) { |
| 174 | + assert(moduleSymbol.flags & ts.SymbolFlags.ValueModule); |
| 175 | + |
| 176 | + const target = containsPublicAPI(moduleSymbol) ? WriteTarget.Both : WriteTarget.Internal; |
| 177 | + |
| 178 | + if (name === "ts") { |
| 179 | + // We will write `export = ts` at the end. |
| 180 | + write(`declare namespace ${name} {`, target); |
| 181 | + } |
| 182 | + else { |
| 183 | + // No export modifier; we are already in the namespace. |
| 184 | + write(`namespace ${name} {`, target); |
| 185 | + } |
| 186 | + increaseIndent(); |
| 187 | + |
| 188 | + const moduleExports = typeChecker.getExportsOfModule(moduleSymbol); |
| 189 | + for (const me of moduleExports) { |
| 190 | + assert(me.declarations?.length); |
| 191 | + |
| 192 | + if (me.flags & ts.SymbolFlags.Alias) { |
| 193 | + const resolved = typeChecker.getAliasedSymbol(me); |
| 194 | + emitAsNamespace(me.name, resolved); |
| 195 | + continue; |
| 196 | + } |
| 197 | + |
| 198 | + for (const decl of me.declarations) { |
| 199 | + const statement = getDeclarationStatement(decl); |
| 200 | + const sourceFile = decl.getSourceFile(); |
| 201 | + |
| 202 | + if (!statement) { |
| 203 | + throw new Error(`Unhandled declaration for ${me.name} at ${nodeToLocation(decl)}`); |
| 204 | + } |
| 205 | + |
| 206 | + const isInternal = isInternalDeclaration(statement); |
| 207 | + if (!isInternal) { |
| 208 | + const publicStatement = ts.visitEachChild(statement, (node) => { |
| 209 | + // No @internal comments in the public API. |
| 210 | + if (isInternalDeclaration(node)) { |
| 211 | + return undefined; |
| 212 | + } |
| 213 | + return removeDeclareConstExport(node); |
| 214 | + }, nullTransformationContext); |
| 215 | + |
| 216 | + writeNode(publicStatement, sourceFile, WriteTarget.Public); |
| 217 | + } |
| 218 | + |
| 219 | + const internalStatement = ts.visitEachChild(statement, removeDeclareConstExport, nullTransformationContext); |
| 220 | + |
| 221 | + writeNode(internalStatement, sourceFile, WriteTarget.Internal); |
| 222 | + } |
| 223 | + } |
| 224 | + |
| 225 | + decreaseIndent(); |
| 226 | + write(`}`, target); |
| 227 | +} |
| 228 | + |
| 229 | +emitAsNamespace("ts", moduleSymbol); |
| 230 | + |
| 231 | +write("export = ts;", WriteTarget.Both); |
| 232 | + |
| 233 | +const copyrightNotice = fs.readFileSync(path.join(__dirname, "..", "CopyrightNotice.txt"), "utf-8"); |
| 234 | +const publicContents = copyrightNotice + publicLines.join(newLine); |
| 235 | +const internalContents = copyrightNotice + internalLines.join(newLine); |
| 236 | + |
| 237 | +if (publicContents.includes("@internal")) { |
| 238 | + console.error("Output includes untrimmed @internal nodes!"); |
| 239 | +} |
| 240 | + |
| 241 | +fs.writeFileSync(output, publicContents); |
| 242 | +fs.writeFileSync(internalOutput, internalContents); |
0 commit comments