Debian Codegraph @

debian/build_modules/rollup-plugin-dts/dist/rollup-plugin-dts.mjs

raw
1 import * as path from 'path';
2 import ts from 'typescript';
3 import { createRequire } from 'module';
4 import MagicString from 'magic-string';
5
6 const dts = ".d.ts";
7 const formatHost = {
8 getCurrentDirectory: () => ts.sys.getCurrentDirectory(),
9 getNewLine: () => ts.sys.newLine,
10 getCanonicalFileName: ts.sys.useCaseSensitiveFileNames ? (f) => f : (f) => f.toLowerCase(),
11 };
12 const DEFAULT_OPTIONS = {
13 // Ensure ".d.ts" modules are generated
14 declaration: true,
15 // Skip ".js" generation
16 noEmit: false,
17 emitDeclarationOnly: true,
18 // Skip code generation when error occurs
19 noEmitOnError: true,
20 // Avoid extra work
21 checkJs: false,
22 declarationMap: false,
23 skipLibCheck: true,
24 // Ensure TS2742 errors are visible
25 preserveSymlinks: true,
26 // Ensure we can parse the latest code
27 target: ts.ScriptTarget.ESNext,
28 };
29 function getCompilerOptions(input, overrideOptions) {
30 const compilerOptions = { ...DEFAULT_OPTIONS, ...overrideOptions };
31 let dirName = path.dirname(input);
32 let dtsFiles = [];
33 const configPath = ts.findConfigFile(dirName, ts.sys.fileExists);
34 if (!configPath) {
35 return { dtsFiles, dirName, compilerOptions };
36 }
37 dirName = path.dirname(configPath);
38 const { config, error } = ts.readConfigFile(configPath, ts.sys.readFile);
39 if (error) {
40 console.error(ts.formatDiagnostic(error, formatHost));
41 return { dtsFiles, dirName, compilerOptions };
42 }
43 const { fileNames, options, errors } = ts.parseJsonConfigFileContent(config, ts.sys, dirName);
44 dtsFiles = fileNames.filter((name) => name.endsWith(dts));
45 if (errors.length) {
46 console.error(ts.formatDiagnostics(errors, formatHost));
47 return { dtsFiles, dirName, compilerOptions };
48 }
49 return {
50 dtsFiles,
51 dirName,
52 compilerOptions: {
53 ...options,
54 ...compilerOptions,
55 },
56 };
57 }
58 function createProgram$1(fileName, overrideOptions) {
59 const { dtsFiles, compilerOptions } = getCompilerOptions(fileName, overrideOptions);
60 return ts.createProgram([fileName].concat(Array.from(dtsFiles)), compilerOptions, ts.createCompilerHost(compilerOptions, true));
61 }
62 function createPrograms(input, overrideOptions) {
63 const programs = [];
64 let inputs = [];
65 let dtsFiles = new Set();
66 let dirName = "";
67 let compilerOptions = {};
68 for (let main of input) {
69 if (main.endsWith(dts)) {
70 continue;
71 }
72 main = path.resolve(main);
73 const options = getCompilerOptions(main, overrideOptions);
74 options.dtsFiles.forEach(dtsFiles.add, dtsFiles);
75 if (!inputs.length) {
76 inputs.push(main);
77 ({ dirName, compilerOptions } = options);
78 continue;
79 }
80 if (options.dirName === dirName) {
81 inputs.push(main);
82 }
83 else {
84 const host = ts.createCompilerHost(compilerOptions, true);
85 const program = ts.createProgram(inputs.concat(Array.from(dtsFiles)), compilerOptions, host);
86 programs.push(program);
87 inputs = [main];
88 ({ dirName, compilerOptions } = options);
89 }
90 }
91 if (inputs.length) {
92 const host = ts.createCompilerHost(compilerOptions, true);
93 const program = ts.createProgram(inputs.concat(Array.from(dtsFiles)), compilerOptions, host);
94 programs.push(program);
95 }
96 return programs;
97 }
98
99 function getCodeFrame() {
100 let codeFrameColumns = undefined;
101 try {
102 ({ codeFrameColumns } = require("@babel/code-frame"));
103 return codeFrameColumns;
104 }
105 catch {
106 try {
107 const esmRequire = createRequire(import.meta.url);
108 ({ codeFrameColumns } = esmRequire("@babel/code-frame"));
109 return codeFrameColumns;
110 }
111 catch { }
112 }
113 return undefined;
114 }
115 function getLocation(node) {
116 const sourceFile = node.getSourceFile();
117 const start = sourceFile.getLineAndCharacterOfPosition(node.getStart());
118 const end = sourceFile.getLineAndCharacterOfPosition(node.getEnd());
119 return {
120 start: { line: start.line + 1, column: start.character + 1 },
121 end: { line: end.line + 1, column: end.character + 1 },
122 };
123 }
124 function frameNode(node) {
125 const codeFrame = getCodeFrame();
126 const sourceFile = node.getSourceFile();
127 const code = sourceFile.getFullText();
128 const location = getLocation(node);
129 if (codeFrame) {
130 return ("\n" +
131 codeFrame(code, location, {
132 highlightCode: true,
133 }));
134 }
135 else {
136 return `\n${location.start.line}:${location.start.column}: \`${node.getFullText().trim()}\``;
137 }
138 }
139 class UnsupportedSyntaxError extends Error {
140 constructor(node, message = "Syntax not yet supported") {
141 super(`${message}\n${frameNode(node)}`);
142 }
143 }
144
145 class NamespaceFixer {
146 constructor(sourceFile) {
147 this.sourceFile = sourceFile;
148 }
149 findNamespaces() {
150 const namespaces = [];
151 const items = {};
152 for (const node of this.sourceFile.statements) {
153 const location = {
154 start: node.getStart(),
155 end: node.getEnd(),
156 };
157 // Well, this is a big hack:
158 // For some global `namespace` and `module` declarations, we generate
159 // some fake IIFE code, so rollup can correctly scan its scope.
160 // However, rollup will then insert bogus semicolons,
161 // these `EmptyStatement`s, which are a syntax error and we want to
162 // remove them. Well, we do that here…
163 if (ts.isEmptyStatement(node)) {
164 namespaces.unshift({
165 name: "",
166 exports: [],
167 location,
168 });
169 continue;
170 }
171 // When generating multiple chunks, rollup links those via import
172 // statements, obviously. But rollup uses full filenames with typescript extension,
173 // which typescript does not like. So make sure to change those to javascript extension here.
174 // `.d.ts` -> `.js`
175 // `.d.cts` -> `.cjs`
176 // `.d.mts` -> `.mjs`
177 if ((ts.isImportDeclaration(node) || ts.isExportDeclaration(node)) &&
178 node.moduleSpecifier &&
179 ts.isStringLiteral(node.moduleSpecifier)) {
180 let { text } = node.moduleSpecifier;
181 if (text.startsWith(".") && (text.endsWith(".d.ts") || text.endsWith(".d.cts") || text.endsWith(".d.mts"))) {
182 let start = node.moduleSpecifier.getStart() + 1; // +1 to account for the quote
183 let end = node.moduleSpecifier.getEnd() - 1; // -1 to account for the quote
184 namespaces.unshift({
185 name: "",
186 exports: [],
187 location: {
188 start,
189 end,
190 },
191 textBeforeCodeAfter: text
192 .replace(/\.d\.ts$/, ".js")
193 .replace(/\.d\.cts$/, ".cjs")
194 .replace(/\.d\.mts$/, ".mjs"),
195 });
196 }
197 }
198 // Remove redundant `{ Foo as Foo }` exports from a namespace which we
199 // added in pre-processing to fix up broken renaming
200 if (ts.isModuleDeclaration(node) && node.body && ts.isModuleBlock(node.body)) {
201 for (const stmt of node.body.statements) {
202 if (ts.isExportDeclaration(stmt) && stmt.exportClause) {
203 if (ts.isNamespaceExport(stmt.exportClause)) {
204 continue;
205 }
206 for (const decl of stmt.exportClause.elements) {
207 if (decl.propertyName && decl.propertyName.getText() == decl.name.getText()) {
208 namespaces.unshift({
209 name: "",
210 exports: [],
211 location: {
212 start: decl.propertyName.getEnd(),
213 end: decl.name.getEnd(),
214 },
215 });
216 }
217 }
218 }
219 }
220 }
221 if (ts.isClassDeclaration(node)) {
222 items[node.name.getText()] = { type: "class", generics: node.typeParameters };
223 }
224 else if (ts.isFunctionDeclaration(node)) {
225 // a function has generics, but these don’t need to be specified explicitly,
226 // since functions are treated as values.
227 items[node.name.getText()] = { type: "function" };
228 }
229 else if (ts.isInterfaceDeclaration(node)) {
230 items[node.name.getText()] = { type: "interface", generics: node.typeParameters };
231 }
232 else if (ts.isTypeAliasDeclaration(node)) {
233 items[node.name.getText()] = { type: "type", generics: node.typeParameters };
234 }
235 else if (ts.isModuleDeclaration(node) && ts.isIdentifier(node.name)) {
236 items[node.name.getText()] = { type: "namespace" };
237 }
238 else if (ts.isEnumDeclaration(node)) {
239 items[node.name.getText()] = { type: "enum" };
240 }
241 if (!ts.isVariableStatement(node)) {
242 continue;
243 }
244 const { declarations } = node.declarationList;
245 if (declarations.length !== 1) {
246 continue;
247 }
248 const decl = declarations[0];
249 const name = decl.name.getText();
250 if (!decl.initializer || !ts.isCallExpression(decl.initializer)) {
251 items[name] = { type: "var" };
252 continue;
253 }
254 const obj = decl.initializer.arguments[0];
255 if (!decl.initializer.expression.getFullText().includes("/*#__PURE__*/Object.freeze") ||
256 !ts.isObjectLiteralExpression(obj)) {
257 continue;
258 }
259 const exports = [];
260 for (const prop of obj.properties) {
261 if (!ts.isPropertyAssignment(prop) ||
262 !(ts.isIdentifier(prop.name) || ts.isStringLiteral(prop.name)) ||
263 (prop.name.text !== "__proto__" && !ts.isIdentifier(prop.initializer))) {
264 throw new UnsupportedSyntaxError(prop, "Expected a property assignment");
265 }
266 if (prop.name.text === "__proto__") {
267 continue;
268 }
269 exports.push({
270 exportedName: prop.name.text,
271 localName: prop.initializer.getText(),
272 });
273 }
274 // sort in reverse order, since we will do string manipulation
275 namespaces.unshift({
276 name,
277 exports,
278 location,
279 });
280 }
281 return { namespaces, itemTypes: items };
282 }
283 fix() {
284 var _a;
285 let code = this.sourceFile.getFullText();
286 const { namespaces, itemTypes } = this.findNamespaces();
287 for (const ns of namespaces) {
288 const codeAfter = code.slice(ns.location.end);
289 code = code.slice(0, ns.location.start);
290 for (const { exportedName, localName } of ns.exports) {
291 if (exportedName === localName) {
292 const { type, generics } = itemTypes[localName] || {};
293 if (type === "interface" || type === "type") {
294 // an interface is just a type
295 const typeParams = renderTypeParams(generics);
296 code += `type ${ns.name}_${exportedName}${typeParams.in} = ${localName}${typeParams.out};\n`;
297 }
298 else if (type === "enum" || type === "class") {
299 // enums and classes are both types and values
300 const typeParams = renderTypeParams(generics);
301 code += `type ${ns.name}_${exportedName}${typeParams.in} = ${localName}${typeParams.out};\n`;
302 code += `declare const ${ns.name}_${exportedName}: typeof ${localName};\n`;
303 }
304 else {
305 // functions and vars are just values
306 code += `declare const ${ns.name}_${exportedName}: typeof ${localName};\n`;
307 }
308 }
309 }
310 if (ns.name) {
311 code += `declare namespace ${ns.name} {\n`;
312 code += ` export {\n`;
313 for (const { exportedName, localName } of ns.exports) {
314 if (exportedName === localName) {
315 code += ` ${ns.name}_${exportedName} as ${exportedName},\n`;
316 }
317 else {
318 code += ` ${localName} as ${exportedName},\n`;
319 }
320 }
321 code += ` };\n`;
322 code += `}`;
323 }
324 code += (_a = ns.textBeforeCodeAfter) !== null && _a !== void 0 ? _a : "";
325 code += codeAfter;
326 }
327 return code;
328 }
329 }
330 function renderTypeParams(typeParameters) {
331 if (!typeParameters || !typeParameters.length) {
332 return { in: "", out: "" };
333 }
334 return {
335 in: `<${typeParameters.map((param) => param.getText()).join(", ")}>`,
336 out: `<${typeParameters.map((param) => param.name.getText()).join(", ")}>`,
337 };
338 }
339
340 let IDs = 1;
341 /**
342 * Create a new `Program` for the given `node`:
343 */
344 function createProgram(node) {
345 return withStartEnd({
346 type: "Program",
347 sourceType: "module",
348 body: [],
349 }, { start: node.getFullStart(), end: node.getEnd() });
350 }
351 /**
352 * Creates a reference to `id`:
353 * `_ = ${id}`
354 */
355 function createReference(id) {
356 return {
357 type: "AssignmentPattern",
358 left: {
359 type: "Identifier",
360 name: String(IDs++),
361 },
362 right: id,
363 };
364 }
365 function createIdentifier(node) {
366 return withStartEnd({
367 type: "Identifier",
368 name: node.getText(),
369 }, node);
370 }
371 /**
372 * Create a new Scope which is always included
373 * `(function (_ = MARKER) {})()`
374 */
375 function createIIFE(range) {
376 const fn = withStartEnd({
377 type: "FunctionExpression",
378 id: null,
379 params: [],
380 body: { type: "BlockStatement", body: [] },
381 }, range);
382 const iife = withStartEnd({
383 type: "ExpressionStatement",
384 expression: {
385 type: "CallExpression",
386 callee: { type: "Identifier", name: String(IDs++) },
387 arguments: [fn],
388 optional: false,
389 },
390 }, range);
391 return { fn, iife };
392 }
393 /**
394 * Create a new Declaration and Scope for `id`:
395 * `function ${id}(_ = MARKER) {}`
396 */
397 function createDeclaration(id, range) {
398 return withStartEnd({
399 type: "FunctionDeclaration",
400 id: withStartEnd({
401 type: "Identifier",
402 name: ts.idText(id),
403 }, id),
404 params: [],
405 body: { type: "BlockStatement", body: [] },
406 }, range);
407 }
408 function convertExpression(node) {
409 if (ts.isLiteralExpression(node)) {
410 return { type: "Literal", value: node.text };
411 }
412 if (ts.isPropertyAccessExpression(node)) {
413 if (ts.isPrivateIdentifier(node.name)) {
414 throw new UnsupportedSyntaxError(node.name);
415 }
416 return withStartEnd({
417 type: "MemberExpression",
418 computed: false,
419 optional: false,
420 object: convertExpression(node.expression),
421 property: convertExpression(node.name),
422 }, {
423 start: node.expression.getStart(),
424 end: node.name.getEnd(),
425 });
426 }
427 if (ts.isIdentifier(node)) {
428 return createIdentifier(node);
429 }
430 else if (node.kind == ts.SyntaxKind.NullKeyword) {
431 return { type: "Literal", value: null };
432 }
433 else {
434 throw new UnsupportedSyntaxError(node);
435 }
436 }
437 function withStartEnd(esNode, nodeOrRange) {
438 let range = "start" in nodeOrRange ? nodeOrRange : { start: nodeOrRange.getStart(), end: nodeOrRange.getEnd() };
439 return Object.assign(esNode, range);
440 }
441 function matchesModifier(node, flags) {
442 const nodeFlags = ts.getCombinedModifierFlags(node);
443 return (nodeFlags & flags) === flags;
444 }
445
446 /**
447 * The pre-process step has the following goals:
448 * - [x] Fixes the "modifiers", removing any `export` modifier and adding any
449 * missing `declare` modifier.
450 * - [x] Splitting compound `VariableStatement` into its parts.
451 * - [x] Moving declarations for the same "name" to be next to each other.
452 * - [x] Removing any triple-slash directives and recording them.
453 * - [x] Create a synthetic name for any nameless "export default".
454 * - [x] Resolve inline `import()` statements and generate top-level imports for
455 * them.
456 * - [x] Generate a separate `export {}` statement for any item which had its
457 * modifiers rewritten.
458 * - [ ] Duplicate the identifiers of a namespace `export`, so that renaming does
459 * not break it
460 */
461 function preProcess({ sourceFile }) {
462 const code = new MagicString(sourceFile.getFullText());
463 /** All the names that are declared in the `SourceFile`. */
464 const declaredNames = new Set();
465 /** All the names that are exported. */
466 const exportedNames = new Set();
467 /** The name of the default export. */
468 let defaultExport = "";
469 /** Inlined exports from `fileId` -> <synthetic name>. */
470 const inlineImports = new Map();
471 /** The ranges that each name covers, for re-ordering. */
472 const nameRanges = new Map();
473 /**
474 * Pass 1:
475 *
476 * - Remove statements that we can’t handle.
477 * - Collect a `Set` of all the declared names.
478 * - Collect a `Set` of all the exported names.
479 * - Maybe collect the name of the default export if present.
480 * - Fix the modifiers of all the items.
481 * - Collect the ranges of each named statement.
482 * - Duplicate the identifiers of a namespace `export`, so that renaming does
483 * not break it
484 */
485 for (const node of sourceFile.statements) {
486 if (ts.isEmptyStatement(node)) {
487 code.remove(node.getStart(), node.getEnd());
488 continue;
489 }
490 if (ts.isEnumDeclaration(node) ||
491 ts.isFunctionDeclaration(node) ||
492 ts.isInterfaceDeclaration(node) ||
493 ts.isClassDeclaration(node) ||
494 ts.isTypeAliasDeclaration(node) ||
495 ts.isModuleDeclaration(node)) {
496 // collect the declared name
497 if (node.name) {
498 const name = node.name.getText();
499 declaredNames.add(name);
500 // collect the exported name, maybe as `default`.
501 if (matchesModifier(node, ts.ModifierFlags.ExportDefault)) {
502 defaultExport = name;
503 }
504 else if (matchesModifier(node, ts.ModifierFlags.Export)) {
505 exportedNames.add(name);
506 }
507 if (!(node.flags & ts.NodeFlags.GlobalAugmentation)) {
508 pushNamedNode(name, [getStart(node), getEnd(node)]);
509 }
510 }
511 // duplicate exports of namespaces
512 if (ts.isModuleDeclaration(node)) {
513 duplicateExports(code, node);
514 }
515 fixModifiers(code, node);
516 }
517 else if (ts.isVariableStatement(node)) {
518 const { declarations } = node.declarationList;
519 // collect all the names, also check if they are exported
520 const isExport = matchesModifier(node, ts.ModifierFlags.Export);
521 for (const decl of node.declarationList.declarations) {
522 if (ts.isIdentifier(decl.name)) {
523 const name = decl.name.getText();
524 declaredNames.add(name);
525 if (isExport) {
526 exportedNames.add(name);
527 }
528 }
529 }
530 fixModifiers(code, node);
531 // collect the ranges for re-ordering
532 if (declarations.length == 1) {
533 const decl = declarations[0];
534 if (ts.isIdentifier(decl.name)) {
535 pushNamedNode(decl.name.getText(), [getStart(node), getEnd(node)]);
536 }
537 }
538 else {
539 // we do reordering after splitting
540 const decls = declarations.slice();
541 const first = decls.shift();
542 pushNamedNode(first.name.getText(), [getStart(node), first.getEnd()]);
543 for (const decl of decls) {
544 if (ts.isIdentifier(decl.name)) {
545 pushNamedNode(decl.name.getText(), [decl.getFullStart(), decl.getEnd()]);
546 }
547 }
548 }
549 // split the variable declaration into different statements
550 const { flags } = node.declarationList;
551 const type = flags & ts.NodeFlags.Let ? "let" : flags & ts.NodeFlags.Const ? "const" : "var";
552 const prefix = `declare ${type} `;
553 const list = node.declarationList
554 .getChildren()
555 .find((c) => c.kind === ts.SyntaxKind.SyntaxList)
556 .getChildren();
557 let commaPos = 0;
558 for (const node of list) {
559 if (node.kind === ts.SyntaxKind.CommaToken) {
560 commaPos = node.getStart();
561 code.remove(commaPos, node.getEnd());
562 }
563 else if (commaPos) {
564 code.appendLeft(commaPos, ";\n");
565 const start = node.getFullStart();
566 const slice = code.slice(start, node.getStart());
567 let whitespace = slice.length - slice.trimStart().length;
568 if (whitespace) {
569 code.overwrite(start, start + whitespace, prefix);
570 }
571 else {
572 code.appendLeft(start, prefix);
573 }
574 }
575 }
576 }
577 }
578 /**
579 * Pass 2:
580 *
581 * Now that we have a Set of all the declared names, we can use that to
582 * generate and de-conflict names for the following steps:
583 *
584 * - Resolve all the inline imports.
585 * - Give any name-less `default export` a name.
586 */
587 for (const node of sourceFile.statements) {
588 // recursively check inline imports
589 checkInlineImport(node);
590 if (!matchesModifier(node, ts.ModifierFlags.ExportDefault)) {
591 continue;
592 }
593 // only function and class can be default exported, and be missing a name
594 if (ts.isFunctionDeclaration(node) || ts.isClassDeclaration(node)) {
595 if (node.name) {
596 continue;
597 }
598 if (!defaultExport) {
599 defaultExport = uniqName("export_default");
600 }
601 const children = node.getChildren();
602 const idx = children.findIndex((node) => node.kind === ts.SyntaxKind.ClassKeyword || node.kind === ts.SyntaxKind.FunctionKeyword);
603 const token = children[idx];
604 const nextToken = children[idx + 1];
605 const isPunctuation = nextToken.kind >= ts.SyntaxKind.FirstPunctuation && nextToken.kind <= ts.SyntaxKind.LastPunctuation;
606 if (isPunctuation) {
607 code.appendLeft(nextToken.getStart(), defaultExport);
608 }
609 else {
610 code.appendRight(token.getEnd(), ` ${defaultExport}`);
611 }
612 }
613 }
614 // and re-order all the name ranges to be contiguous
615 for (const ranges of nameRanges.values()) {
616 // we have to move all the nodes in front of the *last* one, which is a bit
617 // unintuitive but is a workaround for:
618 // https://github.com/Rich-Harris/magic-string/issues/180
619 const last = ranges.pop();
620 const start = last[0];
621 for (const node of ranges) {
622 code.move(node[0], node[1], start);
623 }
624 }
625 // render all the inline imports, and all the exports
626 if (defaultExport) {
627 code.append(`\nexport default ${defaultExport};\n`);
628 }
629 if (exportedNames.size) {
630 code.append(`\nexport { ${[...exportedNames].join(", ")} };\n`);
631 }
632 for (const [fileId, importName] of inlineImports.entries()) {
633 code.prepend(`import * as ${importName} from "${fileId}";\n`);
634 }
635 const lineStarts = sourceFile.getLineStarts();
636 // and collect/remove all the typeReferenceDirectives
637 const typeReferences = new Set();
638 for (const ref of sourceFile.typeReferenceDirectives) {
639 typeReferences.add(ref.fileName);
640 const { line } = sourceFile.getLineAndCharacterOfPosition(ref.pos);
641 const start = lineStarts[line];
642 let end = sourceFile.getLineEndOfPosition(ref.pos);
643 if (code.slice(end, end + 1) == "\n") {
644 end += 1;
645 }
646 code.remove(start, end);
647 }
648 // and collect/remove all the fileReferenceDirectives
649 const fileReferences = new Set();
650 for (const ref of sourceFile.referencedFiles) {
651 fileReferences.add(ref.fileName);
652 const { line } = sourceFile.getLineAndCharacterOfPosition(ref.pos);
653 const start = lineStarts[line];
654 let end = sourceFile.getLineEndOfPosition(ref.pos);
655 if (code.slice(end, end + 1) == "\n") {
656 end += 1;
657 }
658 code.remove(start, end);
659 }
660 return {
661 code,
662 typeReferences,
663 fileReferences,
664 };
665 function checkInlineImport(node) {
666 ts.forEachChild(node, checkInlineImport);
667 if (ts.isImportTypeNode(node)) {
668 if (!ts.isLiteralTypeNode(node.argument) || !ts.isStringLiteral(node.argument.literal)) {
669 throw new UnsupportedSyntaxError(node, "inline imports should have a literal argument");
670 }
671 const fileId = node.argument.literal.text;
672 const children = node.getChildren();
673 const start = children.find((t) => t.kind === ts.SyntaxKind.ImportKeyword).getStart();
674 let end = node.getEnd();
675 const token = children.find((t) => t.kind === ts.SyntaxKind.DotToken || t.kind === ts.SyntaxKind.LessThanToken);
676 if (token) {
677 end = token.getStart();
678 }
679 const importName = createNamespaceImport(fileId);
680 code.overwrite(start, end, importName);
681 }
682 }
683 function createNamespaceImport(fileId) {
684 let importName = inlineImports.get(fileId);
685 if (!importName) {
686 importName = uniqName(fileId.replace(/[^a-zA-Z0-9_$]/g, () => "_"));
687 inlineImports.set(fileId, importName);
688 }
689 return importName;
690 }
691 function uniqName(hint) {
692 let name = hint;
693 while (declaredNames.has(name)) {
694 name = `_${name}`;
695 }
696 declaredNames.add(name);
697 return name;
698 }
699 function pushNamedNode(name, range) {
700 let nodes = nameRanges.get(name);
701 if (!nodes) {
702 nodes = [range];
703 nameRanges.set(name, nodes);
704 }
705 else {
706 const last = nodes[nodes.length - 1];
707 if (last[1] === range[0]) {
708 last[1] = range[1];
709 }
710 else {
711 nodes.push(range);
712 }
713 }
714 }
715 }
716 function fixModifiers(code, node) {
717 var _a;
718 // remove the `export` and `default` modifier, add a `declare` if its missing.
719 let hasDeclare = false;
720 const needsDeclare = ts.isClassDeclaration(node) ||
721 ts.isFunctionDeclaration(node) ||
722 ts.isModuleDeclaration(node) ||
723 ts.isVariableStatement(node);
724 for (const mod of (_a = node.modifiers) !== null && _a !== void 0 ? _a : []) {
725 switch (mod.kind) {
726 case ts.SyntaxKind.ExportKeyword: // fall through
727 case ts.SyntaxKind.DefaultKeyword:
728 // TODO: be careful about that `+ 1`
729 code.remove(mod.getStart(), mod.getEnd() + 1);
730 break;
731 case ts.SyntaxKind.DeclareKeyword:
732 hasDeclare = true;
733 }
734 }
735 if (needsDeclare && !hasDeclare) {
736 code.appendRight(node.getStart(), "declare ");
737 }
738 }
739 function duplicateExports(code, module) {
740 if (!module.body || !ts.isModuleBlock(module.body)) {
741 return;
742 }
743 for (const node of module.body.statements) {
744 if (ts.isExportDeclaration(node) && node.exportClause) {
745 if (ts.isNamespaceExport(node.exportClause)) {
746 continue;
747 }
748 for (const decl of node.exportClause.elements) {
749 if (!decl.propertyName) {
750 code.appendLeft(decl.name.getEnd(), ` as ${decl.name.getText()}`);
751 }
752 }
753 }
754 }
755 }
756 function getStart(node) {
757 const start = node.getFullStart();
758 return start + (newlineAt(node, start) ? 1 : 0);
759 }
760 function getEnd(node) {
761 const end = node.getEnd();
762 return end + (newlineAt(node, end) ? 1 : 0);
763 }
764 function newlineAt(node, idx) {
765 return node.getSourceFile().getFullText()[idx] == "\n";
766 }
767
768 const IGNORE_TYPENODES = new Set([
769 ts.SyntaxKind.LiteralType,
770 ts.SyntaxKind.VoidKeyword,
771 ts.SyntaxKind.UnknownKeyword,
772 ts.SyntaxKind.AnyKeyword,
773 ts.SyntaxKind.BooleanKeyword,
774 ts.SyntaxKind.NumberKeyword,
775 ts.SyntaxKind.StringKeyword,
776 ts.SyntaxKind.ObjectKeyword,
777 ts.SyntaxKind.NullKeyword,
778 ts.SyntaxKind.UndefinedKeyword,
779 ts.SyntaxKind.SymbolKeyword,
780 ts.SyntaxKind.NeverKeyword,
781 ts.SyntaxKind.ThisKeyword,
782 ts.SyntaxKind.ThisType,
783 ts.SyntaxKind.BigIntKeyword,
784 ]);
785 class DeclarationScope {
786 constructor({ id, range }) {
787 /**
788 * As we walk the AST, we need to keep track of type variable bindings that
789 * shadow the outer identifiers. To achieve this, we keep a stack of scopes,
790 * represented as Sets of variable names.
791 */
792 this.scopes = [];
793 if (id) {
794 this.declaration = createDeclaration(id, range);
795 }
796 else {
797 const { iife, fn } = createIIFE(range);
798 this.iife = iife;
799 this.declaration = fn;
800 }
801 }
802 pushScope() {
803 this.scopes.push(new Set());
804 }
805 popScope(n = 1) {
806 for (let i = 0; i < n; i++) {
807 this.scopes.pop();
808 }
809 }
810 pushTypeVariable(id) {
811 var _a;
812 const name = id.getText();
813 (_a = this.scopes[this.scopes.length - 1]) === null || _a === void 0 ? void 0 : _a.add(name);
814 }
815 pushRaw(expr) {
816 this.declaration.params.push(expr);
817 }
818 pushReference(id) {
819 let name;
820 // We convert references from TS AST to ESTree
821 // to hand them off to rollup.
822 // This means we have to check the left-most identifier inside our scope
823 // tree and avoid to create the reference in that case
824 if (id.type === "Identifier") {
825 name = id.name;
826 }
827 else if (id.type === "MemberExpression") {
828 if (id.object.type === "Identifier") {
829 name = id.object.name;
830 }
831 }
832 if (name) {
833 for (const scope of this.scopes) {
834 if (scope.has(name)) {
835 return;
836 }
837 }
838 }
839 this.pushRaw(createReference(id));
840 }
841 pushIdentifierReference(id) {
842 this.pushReference(createIdentifier(id));
843 }
844 convertEntityName(node) {
845 if (ts.isIdentifier(node)) {
846 return createIdentifier(node);
847 }
848 return withStartEnd({
849 type: "MemberExpression",
850 computed: false,
851 optional: false,
852 object: this.convertEntityName(node.left),
853 property: createIdentifier(node.right),
854 }, node);
855 }
856 convertPropertyAccess(node) {
857 // hm, we only care about property access expressions here…
858 if (!ts.isIdentifier(node.expression) && !ts.isPropertyAccessExpression(node.expression)) {
859 throw new UnsupportedSyntaxError(node.expression);
860 }
861 if (ts.isPrivateIdentifier(node.name)) {
862 throw new UnsupportedSyntaxError(node.name);
863 }
864 let object = ts.isIdentifier(node.expression)
865 ? createIdentifier(node.expression)
866 : this.convertPropertyAccess(node.expression);
867 return withStartEnd({
868 type: "MemberExpression",
869 computed: false,
870 optional: false,
871 object,
872 property: createIdentifier(node.name),
873 }, node);
874 }
875 convertComputedPropertyName(node) {
876 if (!node.name || !ts.isComputedPropertyName(node.name)) {
877 return;
878 }
879 const { expression } = node.name;
880 if (ts.isLiteralExpression(expression) || ts.isPrefixUnaryExpression(expression)) {
881 return;
882 }
883 if (ts.isIdentifier(expression)) {
884 return this.pushReference(createIdentifier(expression));
885 }
886 if (ts.isPropertyAccessExpression(expression)) {
887 return this.pushReference(this.convertPropertyAccess(expression));
888 }
889 throw new UnsupportedSyntaxError(expression);
890 }
891 convertParametersAndType(node) {
892 this.convertComputedPropertyName(node);
893 const typeVariables = this.convertTypeParameters(node.typeParameters);
894 for (const param of node.parameters) {
895 this.convertTypeNode(param.type);
896 }
897 this.convertTypeNode(node.type);
898 this.popScope(typeVariables);
899 }
900 convertHeritageClauses(node) {
901 for (const heritage of node.heritageClauses || []) {
902 for (const type of heritage.types) {
903 this.pushReference(convertExpression(type.expression));
904 this.convertTypeArguments(type);
905 }
906 }
907 }
908 convertTypeArguments(node) {
909 if (!node.typeArguments) {
910 return;
911 }
912 for (const arg of node.typeArguments) {
913 this.convertTypeNode(arg);
914 }
915 }
916 convertMembers(members) {
917 for (const node of members) {
918 if (ts.isPropertyDeclaration(node) || ts.isPropertySignature(node) || ts.isIndexSignatureDeclaration(node)) {
919 this.convertComputedPropertyName(node);
920 this.convertTypeNode(node.type);
921 continue;
922 }
923 if (ts.isMethodDeclaration(node) ||
924 ts.isMethodSignature(node) ||
925 ts.isConstructorDeclaration(node) ||
926 ts.isConstructSignatureDeclaration(node) ||
927 ts.isCallSignatureDeclaration(node) ||
928 ts.isGetAccessorDeclaration(node) ||
929 ts.isSetAccessorDeclaration(node)) {
930 this.convertParametersAndType(node);
931 }
932 else {
933 throw new UnsupportedSyntaxError(node);
934 }
935 }
936 }
937 convertTypeParameters(params) {
938 if (!params) {
939 return 0;
940 }
941 for (const node of params) {
942 this.convertTypeNode(node.constraint);
943 this.convertTypeNode(node.default);
944 this.pushScope();
945 this.pushTypeVariable(node.name);
946 }
947 return params.length;
948 }
949 convertTypeNode(node) {
950 if (!node) {
951 return;
952 }
953 if (IGNORE_TYPENODES.has(node.kind)) {
954 return;
955 }
956 if (ts.isTypeReferenceNode(node)) {
957 this.pushReference(this.convertEntityName(node.typeName));
958 this.convertTypeArguments(node);
959 return;
960 }
961 if (ts.isTypeLiteralNode(node)) {
962 return this.convertMembers(node.members);
963 }
964 if (ts.isArrayTypeNode(node)) {
965 return this.convertTypeNode(node.elementType);
966 }
967 if (ts.isTupleTypeNode(node)) {
968 for (const type of node.elements) {
969 this.convertTypeNode(type);
970 }
971 return;
972 }
973 if (ts.isNamedTupleMember(node) ||
974 ts.isParenthesizedTypeNode(node) ||
975 ts.isTypeOperatorNode(node) ||
976 ts.isTypePredicateNode(node)) {
977 return this.convertTypeNode(node.type);
978 }
979 if (ts.isUnionTypeNode(node) || ts.isIntersectionTypeNode(node)) {
980 for (const type of node.types) {
981 this.convertTypeNode(type);
982 }
983 return;
984 }
985 if (ts.isMappedTypeNode(node)) {
986 const { typeParameter, type, nameType } = node;
987 this.convertTypeNode(typeParameter.constraint);
988 this.pushScope();
989 this.pushTypeVariable(typeParameter.name);
990 this.convertTypeNode(type);
991 if (nameType) {
992 this.convertTypeNode(nameType);
993 }
994 this.popScope();
995 return;
996 }
997 if (ts.isConditionalTypeNode(node)) {
998 this.convertTypeNode(node.checkType);
999 this.pushScope();
1000 this.convertTypeNode(node.extendsType);
1001 this.convertTypeNode(node.trueType);
1002 this.convertTypeNode(node.falseType);
1003 this.popScope();
1004 return;
1005 }
1006 if (ts.isIndexedAccessTypeNode(node)) {
1007 this.convertTypeNode(node.objectType);
1008 this.convertTypeNode(node.indexType);
1009 return;
1010 }
1011 if (ts.isFunctionOrConstructorTypeNode(node)) {
1012 this.convertParametersAndType(node);
1013 return;
1014 }
1015 if (ts.isTypeQueryNode(node)) {
1016 this.pushReference(this.convertEntityName(node.exprName));
1017 return;
1018 }
1019 if (ts.isRestTypeNode(node)) {
1020 this.convertTypeNode(node.type);
1021 return;
1022 }
1023 if (ts.isOptionalTypeNode(node)) {
1024 this.convertTypeNode(node.type);
1025 return;
1026 }
1027 if (ts.isTemplateLiteralTypeNode(node)) {
1028 for (const span of node.templateSpans) {
1029 this.convertTypeNode(span.type);
1030 }
1031 return;
1032 }
1033 if (ts.isInferTypeNode(node)) {
1034 const { typeParameter } = node;
1035 this.convertTypeNode(typeParameter.constraint);
1036 this.pushTypeVariable(typeParameter.name);
1037 return;
1038 }
1039 else {
1040 throw new UnsupportedSyntaxError(node);
1041 }
1042 }
1043 convertNamespace(node, relaxedModuleBlock = false) {
1044 this.pushScope();
1045 if (relaxedModuleBlock && node.body && ts.isModuleDeclaration(node.body)) {
1046 this.convertNamespace(node.body, true);
1047 return;
1048 }
1049 if (!node.body || !ts.isModuleBlock(node.body)) {
1050 throw new UnsupportedSyntaxError(node, `namespace must have a "ModuleBlock" body.`);
1051 }
1052 const { statements } = node.body;
1053 // first, hoist all the declarations for correct shadowing
1054 for (const stmt of statements) {
1055 if (ts.isEnumDeclaration(stmt) ||
1056 ts.isFunctionDeclaration(stmt) ||
1057 ts.isClassDeclaration(stmt) ||
1058 ts.isInterfaceDeclaration(stmt) ||
1059 ts.isTypeAliasDeclaration(stmt) ||
1060 ts.isModuleDeclaration(stmt)) {
1061 if (stmt.name && ts.isIdentifier(stmt.name)) {
1062 this.pushTypeVariable(stmt.name);
1063 }
1064 else {
1065 throw new UnsupportedSyntaxError(stmt, `non-Identifier name not supported`);
1066 }
1067 continue;
1068 }
1069 if (ts.isVariableStatement(stmt)) {
1070 for (const decl of stmt.declarationList.declarations) {
1071 if (ts.isIdentifier(decl.name)) {
1072 this.pushTypeVariable(decl.name);
1073 }
1074 else {
1075 throw new UnsupportedSyntaxError(decl, `non-Identifier name not supported`);
1076 }
1077 }
1078 continue;
1079 }
1080 if (ts.isExportDeclaration(stmt)) ;
1081 else {
1082 throw new UnsupportedSyntaxError(stmt, `namespace child (hoisting) not supported yet`);
1083 }
1084 }
1085 // and then walk all the children like normal…
1086 for (const stmt of statements) {
1087 if (ts.isVariableStatement(stmt)) {
1088 for (const decl of stmt.declarationList.declarations) {
1089 if (decl.type) {
1090 this.convertTypeNode(decl.type);
1091 }
1092 }
1093 continue;
1094 }
1095 if (ts.isFunctionDeclaration(stmt)) {
1096 this.convertParametersAndType(stmt);
1097 continue;
1098 }
1099 if (ts.isInterfaceDeclaration(stmt) || ts.isClassDeclaration(stmt)) {
1100 const typeVariables = this.convertTypeParameters(stmt.typeParameters);
1101 this.convertHeritageClauses(stmt);
1102 this.convertMembers(stmt.members);
1103 this.popScope(typeVariables);
1104 continue;
1105 }
1106 if (ts.isTypeAliasDeclaration(stmt)) {
1107 const typeVariables = this.convertTypeParameters(stmt.typeParameters);
1108 this.convertTypeNode(stmt.type);
1109 this.popScope(typeVariables);
1110 continue;
1111 }
1112 if (ts.isModuleDeclaration(stmt)) {
1113 this.convertNamespace(stmt, relaxedModuleBlock);
1114 continue;
1115 }
1116 if (ts.isEnumDeclaration(stmt)) {
1117 // noop
1118 continue;
1119 }
1120 if (ts.isExportDeclaration(stmt)) {
1121 if (stmt.exportClause) {
1122 if (ts.isNamespaceExport(stmt.exportClause)) {
1123 throw new UnsupportedSyntaxError(stmt.exportClause);
1124 }
1125 for (const decl of stmt.exportClause.elements) {
1126 const id = decl.propertyName || decl.name;
1127 this.pushIdentifierReference(id);
1128 }
1129 }
1130 }
1131 else {
1132 throw new UnsupportedSyntaxError(stmt, `namespace child (walking) not supported yet`);
1133 }
1134 }
1135 this.popScope();
1136 }
1137 }
1138
1139 function convert({ sourceFile }) {
1140 const transformer = new Transformer(sourceFile);
1141 return transformer.transform();
1142 }
1143 class Transformer {
1144 constructor(sourceFile) {
1145 this.sourceFile = sourceFile;
1146 this.declarations = new Map();
1147 this.ast = createProgram(sourceFile);
1148 for (const stmt of sourceFile.statements) {
1149 this.convertStatement(stmt);
1150 }
1151 }
1152 transform() {
1153 return {
1154 ast: this.ast,
1155 };
1156 }
1157 pushStatement(node) {
1158 this.ast.body.push(node);
1159 }
1160 createDeclaration(node, id) {
1161 const range = { start: node.getFullStart(), end: node.getEnd() };
1162 if (!id) {
1163 const scope = new DeclarationScope({ range });
1164 this.pushStatement(scope.iife);
1165 return scope;
1166 }
1167 const name = id.getText();
1168 // We have re-ordered and grouped declarations in `reorderStatements`,
1169 // so we can assume same-name statements are next to each other, so we just
1170 // bump the `end` range.
1171 const scope = new DeclarationScope({ id, range });
1172 const existingScope = this.declarations.get(name);
1173 if (existingScope) {
1174 existingScope.pushIdentifierReference(id);
1175 existingScope.declaration.end = range.end;
1176 // we possibly have other declarations, such as an ExportDeclaration in
1177 // between, which should also be updated to the correct start/end.
1178 let selfIdx = this.ast.body.findIndex((node) => node == existingScope.declaration);
1179 for (let i = selfIdx + 1; i < this.ast.body.length; i++) {
1180 const decl = this.ast.body[i];
1181 decl.start = decl.end = range.end;
1182 }
1183 }
1184 else {
1185 this.pushStatement(scope.declaration);
1186 this.declarations.set(name, scope);
1187 }
1188 return existingScope || scope;
1189 }
1190 convertStatement(node) {
1191 if (ts.isEnumDeclaration(node)) {
1192 return this.convertEnumDeclaration(node);
1193 }
1194 if (ts.isFunctionDeclaration(node)) {
1195 return this.convertFunctionDeclaration(node);
1196 }
1197 if (ts.isInterfaceDeclaration(node) || ts.isClassDeclaration(node)) {
1198 return this.convertClassOrInterfaceDeclaration(node);
1199 }
1200 if (ts.isTypeAliasDeclaration(node)) {
1201 return this.convertTypeAliasDeclaration(node);
1202 }
1203 if (ts.isVariableStatement(node)) {
1204 return this.convertVariableStatement(node);
1205 }
1206 if (ts.isExportDeclaration(node) || ts.isExportAssignment(node)) {
1207 return this.convertExportDeclaration(node);
1208 }
1209 if (ts.isModuleDeclaration(node)) {
1210 return this.convertNamespaceDeclaration(node);
1211 }
1212 if (node.kind == ts.SyntaxKind.NamespaceExportDeclaration) {
1213 // just ignore `export as namespace FOO` statements…
1214 return this.removeStatement(node);
1215 }
1216 if (ts.isImportDeclaration(node) || ts.isImportEqualsDeclaration(node)) {
1217 return this.convertImportDeclaration(node);
1218 }
1219 else {
1220 throw new UnsupportedSyntaxError(node);
1221 }
1222 }
1223 removeStatement(node) {
1224 this.pushStatement(withStartEnd({
1225 type: "ExpressionStatement",
1226 expression: { type: "Literal", value: "pls remove me" },
1227 }, node));
1228 }
1229 convertNamespaceDeclaration(node) {
1230 // we want to keep `declare global` augmentations, and we want to
1231 // pull in all the things referenced inside.
1232 // so for this case, we need to figure out some way so that rollup does
1233 // the right thing and not rename these…
1234 const isGlobalAugmentation = node.flags & ts.NodeFlags.GlobalAugmentation;
1235 if (isGlobalAugmentation || !ts.isIdentifier(node.name)) {
1236 const scope = this.createDeclaration(node);
1237 scope.convertNamespace(node, true);
1238 return;
1239 }
1240 const scope = this.createDeclaration(node, node.name);
1241 scope.pushIdentifierReference(node.name);
1242 scope.convertNamespace(node);
1243 }
1244 convertEnumDeclaration(node) {
1245 const scope = this.createDeclaration(node, node.name);
1246 scope.pushIdentifierReference(node.name);
1247 }
1248 convertFunctionDeclaration(node) {
1249 if (!node.name) {
1250 throw new UnsupportedSyntaxError(node, `FunctionDeclaration should have a name`);
1251 }
1252 const scope = this.createDeclaration(node, node.name);
1253 scope.pushIdentifierReference(node.name);
1254 scope.convertParametersAndType(node);
1255 }
1256 convertClassOrInterfaceDeclaration(node) {
1257 if (!node.name) {
1258 throw new UnsupportedSyntaxError(node, `ClassDeclaration / InterfaceDeclaration should have a name`);
1259 }
1260 const scope = this.createDeclaration(node, node.name);
1261 const typeVariables = scope.convertTypeParameters(node.typeParameters);
1262 scope.convertHeritageClauses(node);
1263 scope.convertMembers(node.members);
1264 scope.popScope(typeVariables);
1265 }
1266 convertTypeAliasDeclaration(node) {
1267 const scope = this.createDeclaration(node, node.name);
1268 const typeVariables = scope.convertTypeParameters(node.typeParameters);
1269 scope.convertTypeNode(node.type);
1270 scope.popScope(typeVariables);
1271 }
1272 convertVariableStatement(node) {
1273 const { declarations } = node.declarationList;
1274 if (declarations.length !== 1) {
1275 throw new UnsupportedSyntaxError(node, `VariableStatement with more than one declaration not yet supported`);
1276 }
1277 for (const decl of declarations) {
1278 if (!ts.isIdentifier(decl.name)) {
1279 throw new UnsupportedSyntaxError(node, `VariableDeclaration must have a name`);
1280 }
1281 const scope = this.createDeclaration(node, decl.name);
1282 scope.convertTypeNode(decl.type);
1283 }
1284 }
1285 convertExportDeclaration(node) {
1286 if (ts.isExportAssignment(node)) {
1287 this.pushStatement(withStartEnd({
1288 type: "ExportDefaultDeclaration",
1289 declaration: convertExpression(node.expression),
1290 }, node));
1291 return;
1292 }
1293 const source = node.moduleSpecifier ? convertExpression(node.moduleSpecifier) : undefined;
1294 if (!node.exportClause) {
1295 // export * from './other'
1296 this.pushStatement(withStartEnd({
1297 type: "ExportAllDeclaration",
1298 source,
1299 exported: null,
1300 }, node));
1301 }
1302 else if (ts.isNamespaceExport(node.exportClause)) {
1303 // export * as name from './other'
1304 this.pushStatement(withStartEnd({
1305 type: "ExportAllDeclaration",
1306 source,
1307 exported: createIdentifier(node.exportClause.name),
1308 }, node));
1309 }
1310 else {
1311 // export { name } from './other'
1312 const specifiers = [];
1313 for (const elem of node.exportClause.elements) {
1314 specifiers.push(this.convertExportSpecifier(elem));
1315 }
1316 this.pushStatement(withStartEnd({
1317 type: "ExportNamedDeclaration",
1318 declaration: null,
1319 specifiers,
1320 source,
1321 }, node));
1322 }
1323 }
1324 convertImportDeclaration(node) {
1325 if (ts.isImportEqualsDeclaration(node)) {
1326 // assume its like `import default`
1327 if (!ts.isExternalModuleReference(node.moduleReference)) {
1328 throw new UnsupportedSyntaxError(node, "ImportEquals should have a literal source.");
1329 }
1330 this.pushStatement(withStartEnd({
1331 type: "ImportDeclaration",
1332 specifiers: [
1333 {
1334 type: "ImportDefaultSpecifier",
1335 local: createIdentifier(node.name),
1336 },
1337 ],
1338 source: convertExpression(node.moduleReference.expression),
1339 }, node));
1340 return;
1341 }
1342 const source = convertExpression(node.moduleSpecifier);
1343 const specifiers = node.importClause && node.importClause.namedBindings
1344 ? this.convertNamedImportBindings(node.importClause.namedBindings)
1345 : [];
1346 if (node.importClause && node.importClause.name) {
1347 specifiers.push({
1348 type: "ImportDefaultSpecifier",
1349 local: createIdentifier(node.importClause.name),
1350 });
1351 }
1352 this.pushStatement(withStartEnd({
1353 type: "ImportDeclaration",
1354 specifiers,
1355 source,
1356 }, node));
1357 }
1358 convertNamedImportBindings(node) {
1359 if (ts.isNamedImports(node)) {
1360 return node.elements.map((el) => {
1361 const local = createIdentifier(el.name);
1362 const imported = el.propertyName ? createIdentifier(el.propertyName) : local;
1363 return {
1364 type: "ImportSpecifier",
1365 local,
1366 imported,
1367 };
1368 });
1369 }
1370 return [
1371 {
1372 type: "ImportNamespaceSpecifier",
1373 local: createIdentifier(node.name),
1374 },
1375 ];
1376 }
1377 convertExportSpecifier(node) {
1378 const exported = createIdentifier(node.name);
1379 return {
1380 type: "ExportSpecifier",
1381 exported: exported,
1382 local: node.propertyName ? createIdentifier(node.propertyName) : exported,
1383 };
1384 }
1385 }
1386
1387 function parse(fileName, code) {
1388 return ts.createSourceFile(fileName, code, ts.ScriptTarget.Latest, true);
1389 }
1390 /**
1391 * This is the *transform* part of `rollup-plugin-dts`.
1392 *
1393 * It sets a few input and output options, and otherwise is the core part of the
1394 * plugin responsible for bundling `.d.ts` files.
1395 *
1396 * That itself is a multi-step process:
1397 *
1398 * 1. The plugin has a preprocessing step that moves code around and cleans it
1399 * up a bit, so that later steps can work with it easier. See `preprocess.ts`.
1400 * 2. It then converts the TypeScript AST into a ESTree-like AST that rollup
1401 * understands. See `Transformer.ts`.
1402 * 3. After rollup is finished, the plugin will postprocess the output in a
1403 * `renderChunk` hook. As rollup usually outputs javascript, it can output
1404 * some code that is invalid in the context of a `.d.ts` file. In particular,
1405 * the postprocess convert any javascript code that was created for namespace
1406 * exports into TypeScript namespaces. See `NamespaceFixer.ts`.
1407 */
1408 const transform = () => {
1409 const allTypeReferences = new Map();
1410 const allFileReferences = new Map();
1411 return {
1412 name: "dts-transform",
1413 options(options) {
1414 const { onwarn } = options;
1415 return {
1416 ...options,
1417 onwarn(warning, warn) {
1418 if (warning.code != "CIRCULAR_DEPENDENCY") {
1419 if (onwarn) {
1420 onwarn(warning, warn);
1421 }
1422 else {
1423 warn(warning);
1424 }
1425 }
1426 },
1427 treeshake: {
1428 moduleSideEffects: "no-external",
1429 propertyReadSideEffects: true,
1430 unknownGlobalSideEffects: false,
1431 },
1432 };
1433 },
1434 outputOptions(options) {
1435 return {
1436 ...options,
1437 chunkFileNames: options.chunkFileNames || "[name]-[hash].d.ts",
1438 entryFileNames: options.entryFileNames || "[name].d.ts",
1439 format: "es",
1440 exports: "named",
1441 compact: false,
1442 freeze: true,
1443 interop: false,
1444 namespaceToStringTag: false,
1445 strict: false,
1446 };
1447 },
1448 transform(code, fileName) {
1449 let sourceFile = parse(fileName, code);
1450 const preprocessed = preProcess({ sourceFile });
1451 // `sourceFile.fileName` here uses forward slashes
1452 allTypeReferences.set(sourceFile.fileName, preprocessed.typeReferences);
1453 allFileReferences.set(sourceFile.fileName, preprocessed.fileReferences);
1454 code = preprocessed.code.toString();
1455 sourceFile = parse(fileName, code);
1456 const converted = convert({ sourceFile });
1457 if (process.env.DTS_DUMP_AST) {
1458 console.log(fileName);
1459 console.log(code);
1460 console.log(JSON.stringify(converted.ast.body, undefined, 2));
1461 }
1462 return { code, ast: converted.ast, map: preprocessed.code.generateMap() };
1463 },
1464 renderChunk(code, chunk, options) {
1465 const source = parse(chunk.fileName, code);
1466 const fixer = new NamespaceFixer(source);
1467 const typeReferences = new Set();
1468 const fileReferences = new Set();
1469 for (const fileName of Object.keys(chunk.modules)) {
1470 for (const ref of allTypeReferences.get(fileName.split("\\").join("/")) || []) {
1471 typeReferences.add(ref);
1472 }
1473 for (const ref of allFileReferences.get(fileName.split("\\").join("/")) || []) {
1474 if (ref.startsWith('.')) {
1475 // Need absolute path of the target file here
1476 const absolutePathToOriginal = path.join(path.dirname(fileName), ref);
1477 const chunkFolder = (options.file && path.dirname(options.file)) || (chunk.facadeModuleId && path.dirname(chunk.facadeModuleId)) || ".";
1478 let targetRelPath = path.relative(chunkFolder, absolutePathToOriginal).split("\\").join("/");
1479 if (targetRelPath[0] !== ".") {
1480 targetRelPath = "./" + targetRelPath;
1481 }
1482 fileReferences.add(targetRelPath);
1483 }
1484 else {
1485 fileReferences.add(ref);
1486 }
1487 }
1488 }
1489 code = writeBlock(Array.from(fileReferences, (ref) => `/// <reference path="${ref}" />`));
1490 code += writeBlock(Array.from(typeReferences, (ref) => `/// <reference types="${ref}" />`));
1491 code += fixer.fix();
1492 return { code, map: { mappings: "" } };
1493 },
1494 };
1495 };
1496 function writeBlock(codes) {
1497 if (codes.length) {
1498 return codes.join("\n") + "\n";
1499 }
1500 return "";
1501 }
1502
1503 const tsx = /\.(t|j)sx?$/;
1504 const plugin = (options = {}) => {
1505 const transformPlugin = transform();
1506 const { respectExternal = false, compilerOptions = {} } = options;
1507 // There exists one Program object per entry point,
1508 // except when all entry points are ".d.ts" modules.
1509 let programs = [];
1510 function getModule(fileName) {
1511 let source;
1512 let program;
1513 // Create any `ts.SourceFile` objects on-demand for ".d.ts" modules,
1514 // but only when there are zero ".ts" entry points.
1515 if (!programs.length && fileName.endsWith(dts)) {
1516 source = true;
1517 }
1518 else {
1519 // Rollup doesn't tell you the entry point of each module in the bundle,
1520 // so we need to ask every TypeScript program for the given filename.
1521 program = programs.find((p) => (source = p.getSourceFile(fileName)));
1522 if (!program && ts.sys.fileExists(fileName)) {
1523 programs.push((program = createProgram$1(fileName, compilerOptions)));
1524 source = program.getSourceFile(fileName);
1525 }
1526 }
1527 return { source, program };
1528 }
1529 return {
1530 name: "dts",
1531 options(options) {
1532 let { input = [] } = options;
1533 if (!Array.isArray(input)) {
1534 input = typeof input === "string" ? [input] : Object.values(input);
1535 }
1536 else if (input.length > 1) {
1537 // when dealing with multiple unnamed inputs, transform the inputs into
1538 // an explicit object, which strips the file extension
1539 options.input = {};
1540 for (const filename of input) {
1541 let name = filename.replace(/((\.d)?\.(t|j)sx?)$/, "");
1542 if (path.isAbsolute(filename)) {
1543 name = path.basename(name);
1544 }
1545 else {
1546 name = path.normalize(name);
1547 }
1548 options.input[name] = filename;
1549 }
1550 }
1551 programs = createPrograms(Object.values(input), compilerOptions);
1552 return transformPlugin.options.call(this, options);
1553 },
1554 outputOptions: transformPlugin.outputOptions,
1555 transform(code, id) {
1556 const transformFile = (source, id) => {
1557 if (typeof source === "object") {
1558 code = source.getFullText();
1559 }
1560 return transformPlugin.transform.call(this, code, id);
1561 };
1562 if (!tsx.test(id)) {
1563 return null;
1564 }
1565 if (id.endsWith(dts)) {
1566 const { source } = getModule(id);
1567 return source ? transformFile(source, id) : null;
1568 }
1569 // Always try ".d.ts" before ".tsx?"
1570 const declarationId = id.replace(tsx, dts);
1571 let module = getModule(declarationId);
1572 if (module.source) {
1573 return transformFile(module.source, declarationId);
1574 }
1575 // Generate in-memory ".d.ts" modules from ".tsx?" modules!
1576 module = getModule(id);
1577 if (typeof module.source != "object" || !module.program) {
1578 return null;
1579 }
1580 let generated;
1581 const { emitSkipped, diagnostics } = module.program.emit(module.source, (_, declarationText) => {
1582 code = declarationText;
1583 generated = transformFile(true, declarationId);
1584 }, undefined, // cancellationToken
1585 true);
1586 if (emitSkipped) {
1587 const errors = diagnostics.filter((diag) => diag.category === ts.DiagnosticCategory.Error);
1588 if (errors.length) {
1589 console.error(ts.formatDiagnostics(errors, formatHost));
1590 this.error("Failed to compile. Check the logs above.");
1591 }
1592 }
1593 return generated;
1594 },
1595 resolveId(source, importer) {
1596 if (!importer) {
1597 return;
1598 }
1599 // normalize directory separators to forward slashes, as apparently typescript expects that?
1600 importer = importer.split("\\").join("/");
1601 // resolve this via typescript
1602 const { resolvedModule } = ts.nodeModuleNameResolver(source, importer, compilerOptions, ts.sys);
1603 if (!resolvedModule) {
1604 return;
1605 }
1606 if (!respectExternal && resolvedModule.isExternalLibraryImport) {
1607 // here, we define everything that comes from `node_modules` as `external`.
1608 return { id: source, external: true };
1609 }
1610 else {
1611 // using `path.resolve` here converts paths back to the system specific separators
1612 return { id: path.resolve(resolvedModule.resolvedFileName) };
1613 }
1614 },
1615 renderChunk: transformPlugin.renderChunk,
1616 };
1617 };
1618
1619 export { plugin as default };