| 16 | const preactImportRegex = /import\s*{\s*([\w\s,]+)\s*}\s*from\s*'preact'\s*;?/; |
| 17 | |
| 18 | function walk(dir) { |
| 19 | const files = fs.readdirSync(dir); |
| 20 | files.forEach(file => { |
| 21 | const filePath = path.join(dir, file); |
| 22 | const stat = fs.lstatSync(filePath); |
| 23 | if (stat.isDirectory()) { |
| 24 | walk(filePath); |
| 25 | } else { |
| 26 | if (filePath.endsWith('.d.ts')) { |
| 27 | const content = fs.readFileSync(filePath, 'utf8'); |
| 28 | const capture = preactImportRegex.exec(content); |
| 29 | if (capture) { |
| 30 | const groups = capture[1].split(',').map(s => s.trim()); |
| 31 | |
| 32 | // This generates a shim snippet to replace the type imports from preact |
| 33 | // It generates a snippet based on the capture groups of preactImportRegex. |
| 34 | // |
| 35 | // Example: |
| 36 | // |
| 37 | // import type { ComponentChildren, VNode } from 'preact'; |
| 38 | // becomes |
| 39 | // type ComponentChildren: any; |
| 40 | // type VNode: any; |
| 41 | const snippet = groups.reduce((acc, curr) => { |
| 42 | const searchableValue = curr.includes(' as ') ? curr.split(' as ')[1] : curr; |
| 43 | |
| 44 | // look to see if imported as value, then we have to use declare const |
| 45 | if (content.includes(`typeof ${searchableValue}`)) { |
| 46 | return `${acc}declare const ${searchableValue}: any;\n`; |
| 47 | } |
| 48 | |
| 49 | // look to see if generic type like Foo<T> |
| 50 | if (content.includes(`${searchableValue}<`)) { |
| 51 | return `${acc}type ${searchableValue}<T> = any;\n`; |
| 52 | } |
| 53 | |
| 54 | // otherwise we can just leave as type |
| 55 | return `${acc}type ${searchableValue} = any;\n`; |
| 56 | }, ''); |
| 57 | |
| 58 | // we then can remove the import from preact |
| 59 | const newContent = content.replace(preactImportRegex, '// replaced import from preact'); |
| 60 | |
| 61 | // and write the new content to the file |
| 62 | fs.writeFileSync(filePath, snippet + newContent, 'utf8'); |
| 63 | } |
| 64 | } |
| 65 | } |
| 66 | }); |
| 67 | } |
| 68 | |
| 69 | function run() { |
| 70 | // recurse through build/npm/types-ts3.8 directory |