@@ -25,19 +25,31 @@ const files = process.argv.slice(2);
2525files . forEach ( filePath => {
2626 const lines = fs . readFileSync ( filePath , "utf8" ) . split ( / \r ? \n / gu) ;
2727 const typedefs = new Set ( ) ;
28-
29- const remainingLines = lines . filter ( line => {
30- if ( ! line . startsWith ( "/** @typedef {import" ) ) {
31- return true ;
32- }
33-
34- if ( typedefs . has ( line ) ) {
35- return false ;
28+ const importSources = new Set ( ) ;
29+ const outputLines = [ ] ;
30+
31+ for ( const line of lines ) {
32+ const match = line . match (
33+ / ^ (?< start > \/ \* \* \s * @ t y p e d e f \s + \{ ) i m p o r t \( " (?< importSource > .+ ?) " \) (?< end > .* ) / u,
34+ ) ;
35+ if ( ! match ) {
36+ // not a typedef, so just copy the line
37+ outputLines . push ( line ) ;
38+ } else if ( ! typedefs . has ( line ) ) {
39+ // we haven't seen this typedef before, so process it
40+ typedefs . add ( line ) ;
41+ const { start, importSource, end } = match . groups ;
42+ const importName = `$${ importSource . replace ( / \W / gu, "" ) } ` ;
43+ if ( ! importSources . has ( importSource ) ) {
44+ // we haven't seen this import before, so add an @import comment
45+ importSources . add ( importSource ) ;
46+ outputLines . push (
47+ `/** @import * as ${ importName } from "${ importSource } "; */` ,
48+ ) ;
49+ }
50+ outputLines . push ( `${ start } ${ importName } ${ end } ` ) ;
3651 }
52+ }
3753
38- typedefs . add ( line ) ;
39- return true ;
40- } ) ;
41-
42- fs . writeFileSync ( filePath , remainingLines . join ( "\n" ) , "utf8" ) ;
54+ fs . writeFileSync ( filePath , outputLines . join ( "\n" ) , "utf8" ) ;
4355} ) ;
0 commit comments