1
+ import type { Edit , Range , SgRoot } from '@codemod.com/jssg-types/main' ;
2
+ import type Js from '@codemod.com/jssg-types/langs/javascript' ;
3
+ import { getNodeRequireCalls } from '@nodejs/codemod-utils/ast-grep/require-call' ;
4
+ import { removeLines } from '@nodejs/codemod-utils/ast-grep/remove-lines' ;
5
+
6
+ export default function transform ( root : SgRoot < Js > ) : string | null {
7
+ const rootNode = root . root ( )
8
+ const edits : Edit [ ] = [ ] ;
9
+ const linesToRemove : Range [ ] = [ ] ;
10
+
11
+ // @ts -expect-error - ast-grep types are not fully compatible with JSSG types
12
+ const requireStatements = getNodeRequireCalls ( root , 'buffer' ) ;
13
+ const atobFunctionCalls = rootNode . findAll ( {
14
+ rule : {
15
+ pattern : `buffer.atob($ARG)`
16
+ }
17
+ } ) ;
18
+
19
+ // Remove all buffer require statements
20
+ for ( const statement of requireStatements ) {
21
+ linesToRemove . push ( statement . range ( ) ) ;
22
+ }
23
+
24
+ // Rewrite atob function calls
25
+ for ( const call of atobFunctionCalls ) {
26
+ const argMatch = call . getMatch ( "ARG" ) ;
27
+ if ( argMatch ) {
28
+ const arg = argMatch . text ( ) ;
29
+ const replacement = `Buffer.from(${ arg } , 'base64').toString('binary')` ;
30
+ edits . push ( call . replace ( replacement ) ) ;
31
+ }
32
+ }
33
+
34
+ const btoaFunctionCalls = rootNode . findAll ( {
35
+ rule : {
36
+ pattern : `buffer.btoa($ARG)`
37
+ }
38
+ } ) ;
39
+
40
+ // Rewrite btoa function calls
41
+ for ( const call of btoaFunctionCalls ) {
42
+ const argMatch = call . getMatch ( "ARG" ) ;
43
+ if ( argMatch ) {
44
+ const arg = argMatch . text ( ) ;
45
+ const replacement = `Buffer.from(${ arg } , 'binary').toString('base64')` ;
46
+ edits . push ( call . replace ( replacement ) ) ;
47
+ }
48
+ }
49
+
50
+ return removeLines ( rootNode . commitEdits ( edits ) , linesToRemove ) ;
51
+ }
0 commit comments