Debian Codegraph @

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

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