@@ -15,6 +15,37 @@ if (typeof window !== 'undefined' && typeof window.btoa === 'function') {
15
15
btoa = ( str ) => Buffer . from ( str , 'utf-8' ) . toString ( 'base64' ) ;
16
16
}
17
17
18
+ class SourceMap {
19
+ version = 3 ;
20
+
21
+ /** @type {string[] } */
22
+ names = [ ] ;
23
+
24
+ /**
25
+ * @param {[number, number, number, number][][] } mappings
26
+ * @param {PrintOptions } opts
27
+ */
28
+ constructor ( mappings , opts ) {
29
+ this . sources = [ opts . sourceMapSource || null ] ;
30
+ this . sourcesContent = [ opts . sourceMapContent || null ] ;
31
+ this . mappings = opts . sourceMapEncodeMappings === false ? mappings : encode ( mappings ) ;
32
+ }
33
+
34
+ /**
35
+ * Returns a JSON representation suitable for saving as a `*.map` file
36
+ */
37
+ toString ( ) {
38
+ return JSON . stringify ( this ) ;
39
+ }
40
+
41
+ /**
42
+ * Returns a base64-encoded JSON representation suitable for inlining at the bottom of a file with `//# sourceMappingURL={...}`
43
+ */
44
+ toUrl ( ) {
45
+ return 'data:application/json;charset=utf-8;base64,' + btoa ( this . toString ( ) ) ;
46
+ }
47
+ }
48
+
18
49
/**
19
50
* @template {BaseNode} [T=BaseNode]
20
51
* @param {{ type: string, [key: string]: any } } node
@@ -113,35 +144,14 @@ export function print(node, visitors, opts = {}) {
113
144
114
145
mappings . push ( current_line ) ;
115
146
116
- const map = {
117
- version : 3 ,
118
- /** @type {string[] } */
119
- names : [ ] ,
120
- sources : [ opts . sourceMapSource || null ] ,
121
- sourcesContent : [ opts . sourceMapContent || null ] ,
122
- mappings :
123
- opts . sourceMapEncodeMappings == undefined || opts . sourceMapEncodeMappings
124
- ? encode ( mappings )
125
- : mappings
126
- } ;
127
-
128
- Object . defineProperties ( map , {
129
- toString : {
130
- enumerable : false ,
131
- value : function toString ( ) {
132
- return JSON . stringify ( this ) ;
133
- }
134
- } ,
135
- toUrl : {
136
- enumerable : false ,
137
- value : function toUrl ( ) {
138
- return 'data:application/json;charset=utf-8;base64,' + btoa ( this . toString ( ) ) ;
139
- }
140
- }
141
- } ) ;
147
+ /** @type {SourceMap } */
148
+ let map ;
142
149
143
150
return {
144
151
code,
145
- map
152
+ // create sourcemap lazily in case we don't need it
153
+ get map ( ) {
154
+ return ( map ??= new SourceMap ( mappings , opts ) ) ;
155
+ }
146
156
} ;
147
157
}
0 commit comments