UNPKG

1.98 kBJavaScriptView Raw
1// @ts-check
2const fs = require('fs')
3const path = require('path')
4const chalk = require('chalk')
5const { parse } = require('@babel/parser')
6const MagicString = require('magic-string').default
7const tempDir = path.resolve(__dirname, '../temp/node')
8const typesDir = path.resolve(__dirname, '../types')
9
10// walk through the temp dts dir, find all import/export of types/*
11// and rewrite them into relative imports - so that api-extractor actually
12// includes them in the rolled-up final d.ts file.
13walkDir(tempDir)
14console.log(chalk.green.bold(`patched types/* imports`))
15
16function slash(p) {
17 return p.replace(/\\/g, '/')
18}
19
20/**
21 * @param {string} dir
22 */
23function walkDir(dir) {
24 const files = fs.readdirSync(dir)
25 for (const file of files) {
26 const resolved = path.resolve(dir, file)
27 const isDir = fs.statSync(resolved).isDirectory()
28 if (isDir) {
29 walkDir(resolved)
30 } else {
31 rewriteFile(resolved)
32 }
33 }
34}
35
36/**
37 * @param {string} file
38 */
39function rewriteFile(file) {
40 const content = fs.readFileSync(file, 'utf-8')
41 const str = new MagicString(content)
42 let ast
43 try {
44 ast = parse(content, {
45 sourceType: 'module',
46 plugins: ['typescript', 'classProperties']
47 })
48 } catch (e) {
49 console.log(chalk.red(`failed to parse ${file}`))
50 throw e
51 }
52 for (const statement of ast.program.body) {
53 if (
54 (statement.type === 'ImportDeclaration' ||
55 statement.type === 'ExportNamedDeclaration' ||
56 statement.type === 'ExportAllDeclaration') &&
57 statement.source &&
58 statement.source.value.startsWith('types/')
59 ) {
60 const source = statement.source
61 const absoluteTypePath = path.resolve(typesDir, source.value.slice(6))
62 const relativeTypePath = slash(
63 path.relative(path.dirname(file), absoluteTypePath)
64 )
65 // @ts-ignore
66 str.overwrite(source.start, source.end, JSON.stringify(relativeTypePath))
67 }
68 }
69 fs.writeFileSync(file, str.toString())
70}