1 |
|
2 |
|
3 |
|
4 |
|
5 | "use strict";
|
6 |
|
7 | const Source = require("./Source");
|
8 | const RawSource = require("./RawSource");
|
9 | const { SourceNode } = require("source-map");
|
10 | const { getSourceAndMap, getMap } = require("./helpers");
|
11 |
|
12 | const REPLACE_REGEX = /\n(?=.|\s)/g;
|
13 |
|
14 | class PrefixSource extends Source {
|
15 | constructor(prefix, source) {
|
16 | super();
|
17 | this._source =
|
18 | typeof source === "string" || Buffer.isBuffer(source)
|
19 | ? new RawSource(source, true)
|
20 | : source;
|
21 | this._prefix = prefix;
|
22 | }
|
23 |
|
24 | getPrefix() {
|
25 | return this._prefix;
|
26 | }
|
27 |
|
28 | original() {
|
29 | return this._source;
|
30 | }
|
31 |
|
32 | source() {
|
33 | const node = this._source.source();
|
34 | const prefix = this._prefix;
|
35 | return prefix + node.replace(REPLACE_REGEX, "\n" + prefix);
|
36 | }
|
37 |
|
38 |
|
39 |
|
40 | map(options) {
|
41 | return getMap(this, options);
|
42 | }
|
43 |
|
44 | sourceAndMap(options) {
|
45 | return getSourceAndMap(this, options);
|
46 | }
|
47 |
|
48 | node(options) {
|
49 | const node = this._source.node(options);
|
50 | const prefix = this._prefix;
|
51 | const output = [];
|
52 | const result = new SourceNode();
|
53 | node.walkSourceContents(function (source, content) {
|
54 | result.setSourceContent(source, content);
|
55 | });
|
56 | let needPrefix = true;
|
57 | node.walk(function (chunk, mapping) {
|
58 | const parts = chunk.split(/(\n)/);
|
59 | for (let i = 0; i < parts.length; i += 2) {
|
60 | const nl = i + 1 < parts.length;
|
61 | const part = parts[i] + (nl ? "\n" : "");
|
62 | if (part) {
|
63 | if (needPrefix) {
|
64 | output.push(prefix);
|
65 | }
|
66 | output.push(
|
67 | new SourceNode(
|
68 | mapping.line,
|
69 | mapping.column,
|
70 | mapping.source,
|
71 | part,
|
72 | mapping.name
|
73 | )
|
74 | );
|
75 | needPrefix = nl;
|
76 | }
|
77 | }
|
78 | });
|
79 | result.add(output);
|
80 | return result;
|
81 | }
|
82 |
|
83 | listMap(options) {
|
84 | const prefix = this._prefix;
|
85 | const map = this._source.listMap(options);
|
86 | let prefixNextLine = true;
|
87 | return map.mapGeneratedCode(function (code) {
|
88 | let updatedCode = code.replace(REPLACE_REGEX, "\n" + prefix);
|
89 | if (prefixNextLine) updatedCode = prefix + updatedCode;
|
90 | prefixNextLine = code.charCodeAt(code.length - 1) === 10;
|
91 | return updatedCode;
|
92 | });
|
93 | }
|
94 |
|
95 | updateHash(hash) {
|
96 | hash.update("PrefixSource");
|
97 | this._source.updateHash(hash);
|
98 | hash.update(this._prefix);
|
99 | }
|
100 | }
|
101 |
|
102 | module.exports = PrefixSource;
|