| 57 | return { |
| 58 | name: 'patch-types', |
| 59 | renderChunk(code, chunk) { |
| 60 | const s = new MagicString(code) |
| 61 | const ast = parse(code, { |
| 62 | plugins: ['typescript'], |
| 63 | sourceType: 'module', |
| 64 | }) |
| 65 | |
| 66 | /** |
| 67 | * @param {import('@babel/types').VariableDeclarator | import('@babel/types').TSTypeAliasDeclaration | import('@babel/types').TSInterfaceDeclaration | import('@babel/types').TSDeclareFunction | import('@babel/types').TSInterfaceDeclaration | import('@babel/types').TSEnumDeclaration | import('@babel/types').ClassDeclaration} node |
| 68 | * @param {import('@babel/types').VariableDeclaration} [parentDecl] |
| 69 | */ |
| 70 | function processDeclaration(node, parentDecl) { |
| 71 | if (!node.id) { |
| 72 | return |
| 73 | } |
| 74 | assert(node.id.type === 'Identifier') |
| 75 | const name = node.id.name |
| 76 | if (name.startsWith('_')) { |
| 77 | return |
| 78 | } |
| 79 | shouldRemoveExport.add(name) |
| 80 | if (isExported.has(name)) { |
| 81 | const start = (parentDecl || node).start |
| 82 | assert(typeof start === 'number') |
| 83 | s.prependLeft(start, `export `) |
| 84 | } |
| 85 | } |
| 86 | |
| 87 | const isExported = new Set() |
| 88 | const shouldRemoveExport = new Set() |
| 89 | |
| 90 | // pass 0: check all exported types |
| 91 | for (const node of ast.program.body) { |
| 92 | if (node.type === 'ExportNamedDeclaration' && !node.source) { |
| 93 | for (let i = 0; i < node.specifiers.length; i++) { |
| 94 | const spec = node.specifiers[i] |
| 95 | if (spec.type === 'ExportSpecifier') { |
| 96 | isExported.add(spec.local.name) |
| 97 | } |
| 98 | } |
| 99 | } |
| 100 | } |
| 101 | |
| 102 | // pass 1: add exports |
| 103 | for (const node of ast.program.body) { |
| 104 | if (node.type === 'VariableDeclaration') { |
| 105 | processDeclaration(node.declarations[0], node) |
| 106 | if (node.declarations.length > 1) { |
| 107 | assert(typeof node.start === 'number') |
| 108 | assert(typeof node.end === 'number') |
| 109 | throw new Error( |
| 110 | `unhandled declare const with more than one declarators:\n${code.slice( |
| 111 | node.start, |
| 112 | node.end, |
| 113 | )}`, |
| 114 | ) |
| 115 | } |
| 116 | } else if ( |