Skip to content

Commit 9e57d7c

Browse files
committed
tidy up sourcemap stuff, make lazy, improve type safety
1 parent 26164c3 commit 9e57d7c

File tree

1 file changed

+37
-27
lines changed

1 file changed

+37
-27
lines changed

src/index.js

Lines changed: 37 additions & 27 deletions
Original file line numberDiff line numberDiff line change
@@ -15,6 +15,37 @@ if (typeof window !== 'undefined' && typeof window.btoa === 'function') {
1515
btoa = (str) => Buffer.from(str, 'utf-8').toString('base64');
1616
}
1717

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+
1849
/**
1950
* @template {BaseNode} [T=BaseNode]
2051
* @param {{ type: string, [key: string]: any }} node
@@ -113,35 +144,14 @@ export function print(node, visitors, opts = {}) {
113144

114145
mappings.push(current_line);
115146

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;
142149

143150
return {
144151
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+
}
146156
};
147157
}

0 commit comments

Comments
 (0)