magic-string.umd.js 41 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639
  1. (function (global, factory) {
  2. typeof exports === 'object' && typeof module !== 'undefined' ? module.exports = factory() :
  3. typeof define === 'function' && define.amd ? define(factory) :
  4. (global = typeof globalThis !== 'undefined' ? globalThis : global || self, global.MagicString = factory());
  5. })(this, (function () { 'use strict';
  6. class BitSet {
  7. constructor(arg) {
  8. this.bits = arg instanceof BitSet ? arg.bits.slice() : [];
  9. }
  10. add(n) {
  11. this.bits[n >> 5] |= 1 << (n & 31);
  12. }
  13. has(n) {
  14. return !!(this.bits[n >> 5] & (1 << (n & 31)));
  15. }
  16. }
  17. class Chunk {
  18. constructor(start, end, content) {
  19. this.start = start;
  20. this.end = end;
  21. this.original = content;
  22. this.intro = '';
  23. this.outro = '';
  24. this.content = content;
  25. this.storeName = false;
  26. this.edited = false;
  27. {
  28. this.previous = null;
  29. this.next = null;
  30. }
  31. }
  32. appendLeft(content) {
  33. this.outro += content;
  34. }
  35. appendRight(content) {
  36. this.intro = this.intro + content;
  37. }
  38. clone() {
  39. const chunk = new Chunk(this.start, this.end, this.original);
  40. chunk.intro = this.intro;
  41. chunk.outro = this.outro;
  42. chunk.content = this.content;
  43. chunk.storeName = this.storeName;
  44. chunk.edited = this.edited;
  45. return chunk;
  46. }
  47. contains(index) {
  48. return this.start < index && index < this.end;
  49. }
  50. eachNext(fn) {
  51. let chunk = this;
  52. while (chunk) {
  53. fn(chunk);
  54. chunk = chunk.next;
  55. }
  56. }
  57. eachPrevious(fn) {
  58. let chunk = this;
  59. while (chunk) {
  60. fn(chunk);
  61. chunk = chunk.previous;
  62. }
  63. }
  64. edit(content, storeName, contentOnly) {
  65. this.content = content;
  66. if (!contentOnly) {
  67. this.intro = '';
  68. this.outro = '';
  69. }
  70. this.storeName = storeName;
  71. this.edited = true;
  72. return this;
  73. }
  74. prependLeft(content) {
  75. this.outro = content + this.outro;
  76. }
  77. prependRight(content) {
  78. this.intro = content + this.intro;
  79. }
  80. reset() {
  81. this.intro = '';
  82. this.outro = '';
  83. if (this.edited) {
  84. this.content = this.original;
  85. this.storeName = false;
  86. this.edited = false;
  87. }
  88. }
  89. split(index) {
  90. const sliceIndex = index - this.start;
  91. const originalBefore = this.original.slice(0, sliceIndex);
  92. const originalAfter = this.original.slice(sliceIndex);
  93. this.original = originalBefore;
  94. const newChunk = new Chunk(index, this.end, originalAfter);
  95. newChunk.outro = this.outro;
  96. this.outro = '';
  97. this.end = index;
  98. if (this.edited) {
  99. // after split we should save the edit content record into the correct chunk
  100. // to make sure sourcemap correct
  101. // For example:
  102. // ' test'.trim()
  103. // split -> ' ' + 'test'
  104. // ✔️ edit -> '' + 'test'
  105. // ✖️ edit -> 'test' + ''
  106. // TODO is this block necessary?...
  107. newChunk.edit('', false);
  108. this.content = '';
  109. } else {
  110. this.content = originalBefore;
  111. }
  112. newChunk.next = this.next;
  113. if (newChunk.next) newChunk.next.previous = newChunk;
  114. newChunk.previous = this;
  115. this.next = newChunk;
  116. return newChunk;
  117. }
  118. toString() {
  119. return this.intro + this.content + this.outro;
  120. }
  121. trimEnd(rx) {
  122. this.outro = this.outro.replace(rx, '');
  123. if (this.outro.length) return true;
  124. const trimmed = this.content.replace(rx, '');
  125. if (trimmed.length) {
  126. if (trimmed !== this.content) {
  127. this.split(this.start + trimmed.length).edit('', undefined, true);
  128. if (this.edited) {
  129. // save the change, if it has been edited
  130. this.edit(trimmed, this.storeName, true);
  131. }
  132. }
  133. return true;
  134. } else {
  135. this.edit('', undefined, true);
  136. this.intro = this.intro.replace(rx, '');
  137. if (this.intro.length) return true;
  138. }
  139. }
  140. trimStart(rx) {
  141. this.intro = this.intro.replace(rx, '');
  142. if (this.intro.length) return true;
  143. const trimmed = this.content.replace(rx, '');
  144. if (trimmed.length) {
  145. if (trimmed !== this.content) {
  146. const newChunk = this.split(this.end - trimmed.length);
  147. if (this.edited) {
  148. // save the change, if it has been edited
  149. newChunk.edit(trimmed, this.storeName, true);
  150. }
  151. this.edit('', undefined, true);
  152. }
  153. return true;
  154. } else {
  155. this.edit('', undefined, true);
  156. this.outro = this.outro.replace(rx, '');
  157. if (this.outro.length) return true;
  158. }
  159. }
  160. }
  161. const comma = ','.charCodeAt(0);
  162. const semicolon = ';'.charCodeAt(0);
  163. const chars = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/';
  164. const intToChar = new Uint8Array(64); // 64 possible chars.
  165. const charToInt = new Uint8Array(128); // z is 122 in ASCII
  166. for (let i = 0; i < chars.length; i++) {
  167. const c = chars.charCodeAt(i);
  168. intToChar[i] = c;
  169. charToInt[c] = i;
  170. }
  171. // Provide a fallback for older environments.
  172. const td = typeof TextDecoder !== 'undefined'
  173. ? /* #__PURE__ */ new TextDecoder()
  174. : typeof Buffer !== 'undefined'
  175. ? {
  176. decode(buf) {
  177. const out = Buffer.from(buf.buffer, buf.byteOffset, buf.byteLength);
  178. return out.toString();
  179. },
  180. }
  181. : {
  182. decode(buf) {
  183. let out = '';
  184. for (let i = 0; i < buf.length; i++) {
  185. out += String.fromCharCode(buf[i]);
  186. }
  187. return out;
  188. },
  189. };
  190. function encode(decoded) {
  191. const state = new Int32Array(5);
  192. const bufLength = 1024 * 16;
  193. const subLength = bufLength - 36;
  194. const buf = new Uint8Array(bufLength);
  195. const sub = buf.subarray(0, subLength);
  196. let pos = 0;
  197. let out = '';
  198. for (let i = 0; i < decoded.length; i++) {
  199. const line = decoded[i];
  200. if (i > 0) {
  201. if (pos === bufLength) {
  202. out += td.decode(buf);
  203. pos = 0;
  204. }
  205. buf[pos++] = semicolon;
  206. }
  207. if (line.length === 0)
  208. continue;
  209. state[0] = 0;
  210. for (let j = 0; j < line.length; j++) {
  211. const segment = line[j];
  212. // We can push up to 5 ints, each int can take at most 7 chars, and we
  213. // may push a comma.
  214. if (pos > subLength) {
  215. out += td.decode(sub);
  216. buf.copyWithin(0, subLength, pos);
  217. pos -= subLength;
  218. }
  219. if (j > 0)
  220. buf[pos++] = comma;
  221. pos = encodeInteger(buf, pos, state, segment, 0); // genColumn
  222. if (segment.length === 1)
  223. continue;
  224. pos = encodeInteger(buf, pos, state, segment, 1); // sourcesIndex
  225. pos = encodeInteger(buf, pos, state, segment, 2); // sourceLine
  226. pos = encodeInteger(buf, pos, state, segment, 3); // sourceColumn
  227. if (segment.length === 4)
  228. continue;
  229. pos = encodeInteger(buf, pos, state, segment, 4); // namesIndex
  230. }
  231. }
  232. return out + td.decode(buf.subarray(0, pos));
  233. }
  234. function encodeInteger(buf, pos, state, segment, j) {
  235. const next = segment[j];
  236. let num = next - state[j];
  237. state[j] = next;
  238. num = num < 0 ? (-num << 1) | 1 : num << 1;
  239. do {
  240. let clamped = num & 0b011111;
  241. num >>>= 5;
  242. if (num > 0)
  243. clamped |= 0b100000;
  244. buf[pos++] = intToChar[clamped];
  245. } while (num > 0);
  246. return pos;
  247. }
  248. function getBtoa() {
  249. if (typeof globalThis !== 'undefined' && typeof globalThis.btoa === 'function') {
  250. return (str) => globalThis.btoa(unescape(encodeURIComponent(str)));
  251. } else if (typeof Buffer === 'function') {
  252. return (str) => Buffer.from(str, 'utf-8').toString('base64');
  253. } else {
  254. return () => {
  255. throw new Error('Unsupported environment: `window.btoa` or `Buffer` should be supported.');
  256. };
  257. }
  258. }
  259. const btoa = /*#__PURE__*/ getBtoa();
  260. class SourceMap {
  261. constructor(properties) {
  262. this.version = 3;
  263. this.file = properties.file;
  264. this.sources = properties.sources;
  265. this.sourcesContent = properties.sourcesContent;
  266. this.names = properties.names;
  267. this.mappings = encode(properties.mappings);
  268. if (typeof properties.x_google_ignoreList !== 'undefined') {
  269. this.x_google_ignoreList = properties.x_google_ignoreList;
  270. }
  271. }
  272. toString() {
  273. return JSON.stringify(this);
  274. }
  275. toUrl() {
  276. return 'data:application/json;charset=utf-8;base64,' + btoa(this.toString());
  277. }
  278. }
  279. function guessIndent(code) {
  280. const lines = code.split('\n');
  281. const tabbed = lines.filter((line) => /^\t+/.test(line));
  282. const spaced = lines.filter((line) => /^ {2,}/.test(line));
  283. if (tabbed.length === 0 && spaced.length === 0) {
  284. return null;
  285. }
  286. // More lines tabbed than spaced? Assume tabs, and
  287. // default to tabs in the case of a tie (or nothing
  288. // to go on)
  289. if (tabbed.length >= spaced.length) {
  290. return '\t';
  291. }
  292. // Otherwise, we need to guess the multiple
  293. const min = spaced.reduce((previous, current) => {
  294. const numSpaces = /^ +/.exec(current)[0].length;
  295. return Math.min(numSpaces, previous);
  296. }, Infinity);
  297. return new Array(min + 1).join(' ');
  298. }
  299. function getRelativePath(from, to) {
  300. const fromParts = from.split(/[/\\]/);
  301. const toParts = to.split(/[/\\]/);
  302. fromParts.pop(); // get dirname
  303. while (fromParts[0] === toParts[0]) {
  304. fromParts.shift();
  305. toParts.shift();
  306. }
  307. if (fromParts.length) {
  308. let i = fromParts.length;
  309. while (i--) fromParts[i] = '..';
  310. }
  311. return fromParts.concat(toParts).join('/');
  312. }
  313. const toString = Object.prototype.toString;
  314. function isObject(thing) {
  315. return toString.call(thing) === '[object Object]';
  316. }
  317. function getLocator(source) {
  318. const originalLines = source.split('\n');
  319. const lineOffsets = [];
  320. for (let i = 0, pos = 0; i < originalLines.length; i++) {
  321. lineOffsets.push(pos);
  322. pos += originalLines[i].length + 1;
  323. }
  324. return function locate(index) {
  325. let i = 0;
  326. let j = lineOffsets.length;
  327. while (i < j) {
  328. const m = (i + j) >> 1;
  329. if (index < lineOffsets[m]) {
  330. j = m;
  331. } else {
  332. i = m + 1;
  333. }
  334. }
  335. const line = i - 1;
  336. const column = index - lineOffsets[line];
  337. return { line, column };
  338. };
  339. }
  340. const wordRegex = /\w/;
  341. class Mappings {
  342. constructor(hires) {
  343. this.hires = hires;
  344. this.generatedCodeLine = 0;
  345. this.generatedCodeColumn = 0;
  346. this.raw = [];
  347. this.rawSegments = this.raw[this.generatedCodeLine] = [];
  348. this.pending = null;
  349. }
  350. addEdit(sourceIndex, content, loc, nameIndex) {
  351. if (content.length) {
  352. const contentLengthMinusOne = content.length - 1;
  353. let contentLineEnd = content.indexOf('\n', 0);
  354. let previousContentLineEnd = -1;
  355. // Loop through each line in the content and add a segment, but stop if the last line is empty,
  356. // else code afterwards would fill one line too many
  357. while (contentLineEnd >= 0 && contentLengthMinusOne > contentLineEnd) {
  358. const segment = [this.generatedCodeColumn, sourceIndex, loc.line, loc.column];
  359. if (nameIndex >= 0) {
  360. segment.push(nameIndex);
  361. }
  362. this.rawSegments.push(segment);
  363. this.generatedCodeLine += 1;
  364. this.raw[this.generatedCodeLine] = this.rawSegments = [];
  365. this.generatedCodeColumn = 0;
  366. previousContentLineEnd = contentLineEnd;
  367. contentLineEnd = content.indexOf('\n', contentLineEnd + 1);
  368. }
  369. const segment = [this.generatedCodeColumn, sourceIndex, loc.line, loc.column];
  370. if (nameIndex >= 0) {
  371. segment.push(nameIndex);
  372. }
  373. this.rawSegments.push(segment);
  374. this.advance(content.slice(previousContentLineEnd + 1));
  375. } else if (this.pending) {
  376. this.rawSegments.push(this.pending);
  377. this.advance(content);
  378. }
  379. this.pending = null;
  380. }
  381. addUneditedChunk(sourceIndex, chunk, original, loc, sourcemapLocations) {
  382. let originalCharIndex = chunk.start;
  383. let first = true;
  384. // when iterating each char, check if it's in a word boundary
  385. let charInHiresBoundary = false;
  386. while (originalCharIndex < chunk.end) {
  387. if (this.hires || first || sourcemapLocations.has(originalCharIndex)) {
  388. const segment = [this.generatedCodeColumn, sourceIndex, loc.line, loc.column];
  389. if (this.hires === 'boundary') {
  390. // in hires "boundary", group segments per word boundary than per char
  391. if (wordRegex.test(original[originalCharIndex])) {
  392. // for first char in the boundary found, start the boundary by pushing a segment
  393. if (!charInHiresBoundary) {
  394. this.rawSegments.push(segment);
  395. charInHiresBoundary = true;
  396. }
  397. } else {
  398. // for non-word char, end the boundary by pushing a segment
  399. this.rawSegments.push(segment);
  400. charInHiresBoundary = false;
  401. }
  402. } else {
  403. this.rawSegments.push(segment);
  404. }
  405. }
  406. if (original[originalCharIndex] === '\n') {
  407. loc.line += 1;
  408. loc.column = 0;
  409. this.generatedCodeLine += 1;
  410. this.raw[this.generatedCodeLine] = this.rawSegments = [];
  411. this.generatedCodeColumn = 0;
  412. first = true;
  413. } else {
  414. loc.column += 1;
  415. this.generatedCodeColumn += 1;
  416. first = false;
  417. }
  418. originalCharIndex += 1;
  419. }
  420. this.pending = null;
  421. }
  422. advance(str) {
  423. if (!str) return;
  424. const lines = str.split('\n');
  425. if (lines.length > 1) {
  426. for (let i = 0; i < lines.length - 1; i++) {
  427. this.generatedCodeLine++;
  428. this.raw[this.generatedCodeLine] = this.rawSegments = [];
  429. }
  430. this.generatedCodeColumn = 0;
  431. }
  432. this.generatedCodeColumn += lines[lines.length - 1].length;
  433. }
  434. }
  435. const n = '\n';
  436. const warned = {
  437. insertLeft: false,
  438. insertRight: false,
  439. storeName: false,
  440. };
  441. class MagicString {
  442. constructor(string, options = {}) {
  443. const chunk = new Chunk(0, string.length, string);
  444. Object.defineProperties(this, {
  445. original: { writable: true, value: string },
  446. outro: { writable: true, value: '' },
  447. intro: { writable: true, value: '' },
  448. firstChunk: { writable: true, value: chunk },
  449. lastChunk: { writable: true, value: chunk },
  450. lastSearchedChunk: { writable: true, value: chunk },
  451. byStart: { writable: true, value: {} },
  452. byEnd: { writable: true, value: {} },
  453. filename: { writable: true, value: options.filename },
  454. indentExclusionRanges: { writable: true, value: options.indentExclusionRanges },
  455. sourcemapLocations: { writable: true, value: new BitSet() },
  456. storedNames: { writable: true, value: {} },
  457. indentStr: { writable: true, value: undefined },
  458. ignoreList: { writable: true, value: options.ignoreList },
  459. });
  460. this.byStart[0] = chunk;
  461. this.byEnd[string.length] = chunk;
  462. }
  463. addSourcemapLocation(char) {
  464. this.sourcemapLocations.add(char);
  465. }
  466. append(content) {
  467. if (typeof content !== 'string') throw new TypeError('outro content must be a string');
  468. this.outro += content;
  469. return this;
  470. }
  471. appendLeft(index, content) {
  472. if (typeof content !== 'string') throw new TypeError('inserted content must be a string');
  473. this._split(index);
  474. const chunk = this.byEnd[index];
  475. if (chunk) {
  476. chunk.appendLeft(content);
  477. } else {
  478. this.intro += content;
  479. }
  480. return this;
  481. }
  482. appendRight(index, content) {
  483. if (typeof content !== 'string') throw new TypeError('inserted content must be a string');
  484. this._split(index);
  485. const chunk = this.byStart[index];
  486. if (chunk) {
  487. chunk.appendRight(content);
  488. } else {
  489. this.outro += content;
  490. }
  491. return this;
  492. }
  493. clone() {
  494. const cloned = new MagicString(this.original, { filename: this.filename });
  495. let originalChunk = this.firstChunk;
  496. let clonedChunk = (cloned.firstChunk = cloned.lastSearchedChunk = originalChunk.clone());
  497. while (originalChunk) {
  498. cloned.byStart[clonedChunk.start] = clonedChunk;
  499. cloned.byEnd[clonedChunk.end] = clonedChunk;
  500. const nextOriginalChunk = originalChunk.next;
  501. const nextClonedChunk = nextOriginalChunk && nextOriginalChunk.clone();
  502. if (nextClonedChunk) {
  503. clonedChunk.next = nextClonedChunk;
  504. nextClonedChunk.previous = clonedChunk;
  505. clonedChunk = nextClonedChunk;
  506. }
  507. originalChunk = nextOriginalChunk;
  508. }
  509. cloned.lastChunk = clonedChunk;
  510. if (this.indentExclusionRanges) {
  511. cloned.indentExclusionRanges = this.indentExclusionRanges.slice();
  512. }
  513. cloned.sourcemapLocations = new BitSet(this.sourcemapLocations);
  514. cloned.intro = this.intro;
  515. cloned.outro = this.outro;
  516. return cloned;
  517. }
  518. generateDecodedMap(options) {
  519. options = options || {};
  520. const sourceIndex = 0;
  521. const names = Object.keys(this.storedNames);
  522. const mappings = new Mappings(options.hires);
  523. const locate = getLocator(this.original);
  524. if (this.intro) {
  525. mappings.advance(this.intro);
  526. }
  527. this.firstChunk.eachNext((chunk) => {
  528. const loc = locate(chunk.start);
  529. if (chunk.intro.length) mappings.advance(chunk.intro);
  530. if (chunk.edited) {
  531. mappings.addEdit(
  532. sourceIndex,
  533. chunk.content,
  534. loc,
  535. chunk.storeName ? names.indexOf(chunk.original) : -1,
  536. );
  537. } else {
  538. mappings.addUneditedChunk(sourceIndex, chunk, this.original, loc, this.sourcemapLocations);
  539. }
  540. if (chunk.outro.length) mappings.advance(chunk.outro);
  541. });
  542. return {
  543. file: options.file ? options.file.split(/[/\\]/).pop() : undefined,
  544. sources: [
  545. options.source ? getRelativePath(options.file || '', options.source) : options.file || '',
  546. ],
  547. sourcesContent: options.includeContent ? [this.original] : undefined,
  548. names,
  549. mappings: mappings.raw,
  550. x_google_ignoreList: this.ignoreList ? [sourceIndex] : undefined,
  551. };
  552. }
  553. generateMap(options) {
  554. return new SourceMap(this.generateDecodedMap(options));
  555. }
  556. _ensureindentStr() {
  557. if (this.indentStr === undefined) {
  558. this.indentStr = guessIndent(this.original);
  559. }
  560. }
  561. _getRawIndentString() {
  562. this._ensureindentStr();
  563. return this.indentStr;
  564. }
  565. getIndentString() {
  566. this._ensureindentStr();
  567. return this.indentStr === null ? '\t' : this.indentStr;
  568. }
  569. indent(indentStr, options) {
  570. const pattern = /^[^\r\n]/gm;
  571. if (isObject(indentStr)) {
  572. options = indentStr;
  573. indentStr = undefined;
  574. }
  575. if (indentStr === undefined) {
  576. this._ensureindentStr();
  577. indentStr = this.indentStr || '\t';
  578. }
  579. if (indentStr === '') return this; // noop
  580. options = options || {};
  581. // Process exclusion ranges
  582. const isExcluded = {};
  583. if (options.exclude) {
  584. const exclusions =
  585. typeof options.exclude[0] === 'number' ? [options.exclude] : options.exclude;
  586. exclusions.forEach((exclusion) => {
  587. for (let i = exclusion[0]; i < exclusion[1]; i += 1) {
  588. isExcluded[i] = true;
  589. }
  590. });
  591. }
  592. let shouldIndentNextCharacter = options.indentStart !== false;
  593. const replacer = (match) => {
  594. if (shouldIndentNextCharacter) return `${indentStr}${match}`;
  595. shouldIndentNextCharacter = true;
  596. return match;
  597. };
  598. this.intro = this.intro.replace(pattern, replacer);
  599. let charIndex = 0;
  600. let chunk = this.firstChunk;
  601. while (chunk) {
  602. const end = chunk.end;
  603. if (chunk.edited) {
  604. if (!isExcluded[charIndex]) {
  605. chunk.content = chunk.content.replace(pattern, replacer);
  606. if (chunk.content.length) {
  607. shouldIndentNextCharacter = chunk.content[chunk.content.length - 1] === '\n';
  608. }
  609. }
  610. } else {
  611. charIndex = chunk.start;
  612. while (charIndex < end) {
  613. if (!isExcluded[charIndex]) {
  614. const char = this.original[charIndex];
  615. if (char === '\n') {
  616. shouldIndentNextCharacter = true;
  617. } else if (char !== '\r' && shouldIndentNextCharacter) {
  618. shouldIndentNextCharacter = false;
  619. if (charIndex === chunk.start) {
  620. chunk.prependRight(indentStr);
  621. } else {
  622. this._splitChunk(chunk, charIndex);
  623. chunk = chunk.next;
  624. chunk.prependRight(indentStr);
  625. }
  626. }
  627. }
  628. charIndex += 1;
  629. }
  630. }
  631. charIndex = chunk.end;
  632. chunk = chunk.next;
  633. }
  634. this.outro = this.outro.replace(pattern, replacer);
  635. return this;
  636. }
  637. insert() {
  638. throw new Error(
  639. 'magicString.insert(...) is deprecated. Use prependRight(...) or appendLeft(...)',
  640. );
  641. }
  642. insertLeft(index, content) {
  643. if (!warned.insertLeft) {
  644. console.warn(
  645. 'magicString.insertLeft(...) is deprecated. Use magicString.appendLeft(...) instead',
  646. ); // eslint-disable-line no-console
  647. warned.insertLeft = true;
  648. }
  649. return this.appendLeft(index, content);
  650. }
  651. insertRight(index, content) {
  652. if (!warned.insertRight) {
  653. console.warn(
  654. 'magicString.insertRight(...) is deprecated. Use magicString.prependRight(...) instead',
  655. ); // eslint-disable-line no-console
  656. warned.insertRight = true;
  657. }
  658. return this.prependRight(index, content);
  659. }
  660. move(start, end, index) {
  661. if (index >= start && index <= end) throw new Error('Cannot move a selection inside itself');
  662. this._split(start);
  663. this._split(end);
  664. this._split(index);
  665. const first = this.byStart[start];
  666. const last = this.byEnd[end];
  667. const oldLeft = first.previous;
  668. const oldRight = last.next;
  669. const newRight = this.byStart[index];
  670. if (!newRight && last === this.lastChunk) return this;
  671. const newLeft = newRight ? newRight.previous : this.lastChunk;
  672. if (oldLeft) oldLeft.next = oldRight;
  673. if (oldRight) oldRight.previous = oldLeft;
  674. if (newLeft) newLeft.next = first;
  675. if (newRight) newRight.previous = last;
  676. if (!first.previous) this.firstChunk = last.next;
  677. if (!last.next) {
  678. this.lastChunk = first.previous;
  679. this.lastChunk.next = null;
  680. }
  681. first.previous = newLeft;
  682. last.next = newRight || null;
  683. if (!newLeft) this.firstChunk = first;
  684. if (!newRight) this.lastChunk = last;
  685. return this;
  686. }
  687. overwrite(start, end, content, options) {
  688. options = options || {};
  689. return this.update(start, end, content, { ...options, overwrite: !options.contentOnly });
  690. }
  691. update(start, end, content, options) {
  692. if (typeof content !== 'string') throw new TypeError('replacement content must be a string');
  693. while (start < 0) start += this.original.length;
  694. while (end < 0) end += this.original.length;
  695. if (end > this.original.length) throw new Error('end is out of bounds');
  696. if (start === end)
  697. throw new Error(
  698. 'Cannot overwrite a zero-length range – use appendLeft or prependRight instead',
  699. );
  700. this._split(start);
  701. this._split(end);
  702. if (options === true) {
  703. if (!warned.storeName) {
  704. console.warn(
  705. 'The final argument to magicString.overwrite(...) should be an options object. See https://github.com/rich-harris/magic-string',
  706. ); // eslint-disable-line no-console
  707. warned.storeName = true;
  708. }
  709. options = { storeName: true };
  710. }
  711. const storeName = options !== undefined ? options.storeName : false;
  712. const overwrite = options !== undefined ? options.overwrite : false;
  713. if (storeName) {
  714. const original = this.original.slice(start, end);
  715. Object.defineProperty(this.storedNames, original, {
  716. writable: true,
  717. value: true,
  718. enumerable: true,
  719. });
  720. }
  721. const first = this.byStart[start];
  722. const last = this.byEnd[end];
  723. if (first) {
  724. let chunk = first;
  725. while (chunk !== last) {
  726. if (chunk.next !== this.byStart[chunk.end]) {
  727. throw new Error('Cannot overwrite across a split point');
  728. }
  729. chunk = chunk.next;
  730. chunk.edit('', false);
  731. }
  732. first.edit(content, storeName, !overwrite);
  733. } else {
  734. // must be inserting at the end
  735. const newChunk = new Chunk(start, end, '').edit(content, storeName);
  736. // TODO last chunk in the array may not be the last chunk, if it's moved...
  737. last.next = newChunk;
  738. newChunk.previous = last;
  739. }
  740. return this;
  741. }
  742. prepend(content) {
  743. if (typeof content !== 'string') throw new TypeError('outro content must be a string');
  744. this.intro = content + this.intro;
  745. return this;
  746. }
  747. prependLeft(index, content) {
  748. if (typeof content !== 'string') throw new TypeError('inserted content must be a string');
  749. this._split(index);
  750. const chunk = this.byEnd[index];
  751. if (chunk) {
  752. chunk.prependLeft(content);
  753. } else {
  754. this.intro = content + this.intro;
  755. }
  756. return this;
  757. }
  758. prependRight(index, content) {
  759. if (typeof content !== 'string') throw new TypeError('inserted content must be a string');
  760. this._split(index);
  761. const chunk = this.byStart[index];
  762. if (chunk) {
  763. chunk.prependRight(content);
  764. } else {
  765. this.outro = content + this.outro;
  766. }
  767. return this;
  768. }
  769. remove(start, end) {
  770. while (start < 0) start += this.original.length;
  771. while (end < 0) end += this.original.length;
  772. if (start === end) return this;
  773. if (start < 0 || end > this.original.length) throw new Error('Character is out of bounds');
  774. if (start > end) throw new Error('end must be greater than start');
  775. this._split(start);
  776. this._split(end);
  777. let chunk = this.byStart[start];
  778. while (chunk) {
  779. chunk.intro = '';
  780. chunk.outro = '';
  781. chunk.edit('');
  782. chunk = end > chunk.end ? this.byStart[chunk.end] : null;
  783. }
  784. return this;
  785. }
  786. reset(start, end) {
  787. while (start < 0) start += this.original.length;
  788. while (end < 0) end += this.original.length;
  789. if (start === end) return this;
  790. if (start < 0 || end > this.original.length) throw new Error('Character is out of bounds');
  791. if (start > end) throw new Error('end must be greater than start');
  792. this._split(start);
  793. this._split(end);
  794. let chunk = this.byStart[start];
  795. while (chunk) {
  796. chunk.reset();
  797. chunk = end > chunk.end ? this.byStart[chunk.end] : null;
  798. }
  799. return this;
  800. }
  801. lastChar() {
  802. if (this.outro.length) return this.outro[this.outro.length - 1];
  803. let chunk = this.lastChunk;
  804. do {
  805. if (chunk.outro.length) return chunk.outro[chunk.outro.length - 1];
  806. if (chunk.content.length) return chunk.content[chunk.content.length - 1];
  807. if (chunk.intro.length) return chunk.intro[chunk.intro.length - 1];
  808. } while ((chunk = chunk.previous));
  809. if (this.intro.length) return this.intro[this.intro.length - 1];
  810. return '';
  811. }
  812. lastLine() {
  813. let lineIndex = this.outro.lastIndexOf(n);
  814. if (lineIndex !== -1) return this.outro.substr(lineIndex + 1);
  815. let lineStr = this.outro;
  816. let chunk = this.lastChunk;
  817. do {
  818. if (chunk.outro.length > 0) {
  819. lineIndex = chunk.outro.lastIndexOf(n);
  820. if (lineIndex !== -1) return chunk.outro.substr(lineIndex + 1) + lineStr;
  821. lineStr = chunk.outro + lineStr;
  822. }
  823. if (chunk.content.length > 0) {
  824. lineIndex = chunk.content.lastIndexOf(n);
  825. if (lineIndex !== -1) return chunk.content.substr(lineIndex + 1) + lineStr;
  826. lineStr = chunk.content + lineStr;
  827. }
  828. if (chunk.intro.length > 0) {
  829. lineIndex = chunk.intro.lastIndexOf(n);
  830. if (lineIndex !== -1) return chunk.intro.substr(lineIndex + 1) + lineStr;
  831. lineStr = chunk.intro + lineStr;
  832. }
  833. } while ((chunk = chunk.previous));
  834. lineIndex = this.intro.lastIndexOf(n);
  835. if (lineIndex !== -1) return this.intro.substr(lineIndex + 1) + lineStr;
  836. return this.intro + lineStr;
  837. }
  838. slice(start = 0, end = this.original.length) {
  839. while (start < 0) start += this.original.length;
  840. while (end < 0) end += this.original.length;
  841. let result = '';
  842. // find start chunk
  843. let chunk = this.firstChunk;
  844. while (chunk && (chunk.start > start || chunk.end <= start)) {
  845. // found end chunk before start
  846. if (chunk.start < end && chunk.end >= end) {
  847. return result;
  848. }
  849. chunk = chunk.next;
  850. }
  851. if (chunk && chunk.edited && chunk.start !== start)
  852. throw new Error(`Cannot use replaced character ${start} as slice start anchor.`);
  853. const startChunk = chunk;
  854. while (chunk) {
  855. if (chunk.intro && (startChunk !== chunk || chunk.start === start)) {
  856. result += chunk.intro;
  857. }
  858. const containsEnd = chunk.start < end && chunk.end >= end;
  859. if (containsEnd && chunk.edited && chunk.end !== end)
  860. throw new Error(`Cannot use replaced character ${end} as slice end anchor.`);
  861. const sliceStart = startChunk === chunk ? start - chunk.start : 0;
  862. const sliceEnd = containsEnd ? chunk.content.length + end - chunk.end : chunk.content.length;
  863. result += chunk.content.slice(sliceStart, sliceEnd);
  864. if (chunk.outro && (!containsEnd || chunk.end === end)) {
  865. result += chunk.outro;
  866. }
  867. if (containsEnd) {
  868. break;
  869. }
  870. chunk = chunk.next;
  871. }
  872. return result;
  873. }
  874. // TODO deprecate this? not really very useful
  875. snip(start, end) {
  876. const clone = this.clone();
  877. clone.remove(0, start);
  878. clone.remove(end, clone.original.length);
  879. return clone;
  880. }
  881. _split(index) {
  882. if (this.byStart[index] || this.byEnd[index]) return;
  883. let chunk = this.lastSearchedChunk;
  884. const searchForward = index > chunk.end;
  885. while (chunk) {
  886. if (chunk.contains(index)) return this._splitChunk(chunk, index);
  887. chunk = searchForward ? this.byStart[chunk.end] : this.byEnd[chunk.start];
  888. }
  889. }
  890. _splitChunk(chunk, index) {
  891. if (chunk.edited && chunk.content.length) {
  892. // zero-length edited chunks are a special case (overlapping replacements)
  893. const loc = getLocator(this.original)(index);
  894. throw new Error(
  895. `Cannot split a chunk that has already been edited (${loc.line}:${loc.column} – "${chunk.original}")`,
  896. );
  897. }
  898. const newChunk = chunk.split(index);
  899. this.byEnd[index] = chunk;
  900. this.byStart[index] = newChunk;
  901. this.byEnd[newChunk.end] = newChunk;
  902. if (chunk === this.lastChunk) this.lastChunk = newChunk;
  903. this.lastSearchedChunk = chunk;
  904. return true;
  905. }
  906. toString() {
  907. let str = this.intro;
  908. let chunk = this.firstChunk;
  909. while (chunk) {
  910. str += chunk.toString();
  911. chunk = chunk.next;
  912. }
  913. return str + this.outro;
  914. }
  915. isEmpty() {
  916. let chunk = this.firstChunk;
  917. do {
  918. if (
  919. (chunk.intro.length && chunk.intro.trim()) ||
  920. (chunk.content.length && chunk.content.trim()) ||
  921. (chunk.outro.length && chunk.outro.trim())
  922. )
  923. return false;
  924. } while ((chunk = chunk.next));
  925. return true;
  926. }
  927. length() {
  928. let chunk = this.firstChunk;
  929. let length = 0;
  930. do {
  931. length += chunk.intro.length + chunk.content.length + chunk.outro.length;
  932. } while ((chunk = chunk.next));
  933. return length;
  934. }
  935. trimLines() {
  936. return this.trim('[\\r\\n]');
  937. }
  938. trim(charType) {
  939. return this.trimStart(charType).trimEnd(charType);
  940. }
  941. trimEndAborted(charType) {
  942. const rx = new RegExp((charType || '\\s') + '+$');
  943. this.outro = this.outro.replace(rx, '');
  944. if (this.outro.length) return true;
  945. let chunk = this.lastChunk;
  946. do {
  947. const end = chunk.end;
  948. const aborted = chunk.trimEnd(rx);
  949. // if chunk was trimmed, we have a new lastChunk
  950. if (chunk.end !== end) {
  951. if (this.lastChunk === chunk) {
  952. this.lastChunk = chunk.next;
  953. }
  954. this.byEnd[chunk.end] = chunk;
  955. this.byStart[chunk.next.start] = chunk.next;
  956. this.byEnd[chunk.next.end] = chunk.next;
  957. }
  958. if (aborted) return true;
  959. chunk = chunk.previous;
  960. } while (chunk);
  961. return false;
  962. }
  963. trimEnd(charType) {
  964. this.trimEndAborted(charType);
  965. return this;
  966. }
  967. trimStartAborted(charType) {
  968. const rx = new RegExp('^' + (charType || '\\s') + '+');
  969. this.intro = this.intro.replace(rx, '');
  970. if (this.intro.length) return true;
  971. let chunk = this.firstChunk;
  972. do {
  973. const end = chunk.end;
  974. const aborted = chunk.trimStart(rx);
  975. if (chunk.end !== end) {
  976. // special case...
  977. if (chunk === this.lastChunk) this.lastChunk = chunk.next;
  978. this.byEnd[chunk.end] = chunk;
  979. this.byStart[chunk.next.start] = chunk.next;
  980. this.byEnd[chunk.next.end] = chunk.next;
  981. }
  982. if (aborted) return true;
  983. chunk = chunk.next;
  984. } while (chunk);
  985. return false;
  986. }
  987. trimStart(charType) {
  988. this.trimStartAborted(charType);
  989. return this;
  990. }
  991. hasChanged() {
  992. return this.original !== this.toString();
  993. }
  994. _replaceRegexp(searchValue, replacement) {
  995. function getReplacement(match, str) {
  996. if (typeof replacement === 'string') {
  997. return replacement.replace(/\$(\$|&|\d+)/g, (_, i) => {
  998. // https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/replace#specifying_a_string_as_a_parameter
  999. if (i === '$') return '$';
  1000. if (i === '&') return match[0];
  1001. const num = +i;
  1002. if (num < match.length) return match[+i];
  1003. return `$${i}`;
  1004. });
  1005. } else {
  1006. return replacement(...match, match.index, str, match.groups);
  1007. }
  1008. }
  1009. function matchAll(re, str) {
  1010. let match;
  1011. const matches = [];
  1012. while ((match = re.exec(str))) {
  1013. matches.push(match);
  1014. }
  1015. return matches;
  1016. }
  1017. if (searchValue.global) {
  1018. const matches = matchAll(searchValue, this.original);
  1019. matches.forEach((match) => {
  1020. if (match.index != null) {
  1021. const replacement = getReplacement(match, this.original);
  1022. if (replacement !== match[0]) {
  1023. this.overwrite(
  1024. match.index,
  1025. match.index + match[0].length,
  1026. replacement
  1027. );
  1028. }
  1029. }
  1030. });
  1031. } else {
  1032. const match = this.original.match(searchValue);
  1033. if (match && match.index != null) {
  1034. const replacement = getReplacement(match, this.original);
  1035. if (replacement !== match[0]) {
  1036. this.overwrite(
  1037. match.index,
  1038. match.index + match[0].length,
  1039. replacement
  1040. );
  1041. }
  1042. }
  1043. }
  1044. return this;
  1045. }
  1046. _replaceString(string, replacement) {
  1047. const { original } = this;
  1048. const index = original.indexOf(string);
  1049. if (index !== -1) {
  1050. this.overwrite(index, index + string.length, replacement);
  1051. }
  1052. return this;
  1053. }
  1054. replace(searchValue, replacement) {
  1055. if (typeof searchValue === 'string') {
  1056. return this._replaceString(searchValue, replacement);
  1057. }
  1058. return this._replaceRegexp(searchValue, replacement);
  1059. }
  1060. _replaceAllString(string, replacement) {
  1061. const { original } = this;
  1062. const stringLength = string.length;
  1063. for (
  1064. let index = original.indexOf(string);
  1065. index !== -1;
  1066. index = original.indexOf(string, index + stringLength)
  1067. ) {
  1068. const previous = original.slice(index, index + stringLength);
  1069. if (previous !== replacement)
  1070. this.overwrite(index, index + stringLength, replacement);
  1071. }
  1072. return this;
  1073. }
  1074. replaceAll(searchValue, replacement) {
  1075. if (typeof searchValue === 'string') {
  1076. return this._replaceAllString(searchValue, replacement);
  1077. }
  1078. if (!searchValue.global) {
  1079. throw new TypeError(
  1080. 'MagicString.prototype.replaceAll called with a non-global RegExp argument',
  1081. );
  1082. }
  1083. return this._replaceRegexp(searchValue, replacement);
  1084. }
  1085. }
  1086. const hasOwnProp = Object.prototype.hasOwnProperty;
  1087. class Bundle {
  1088. constructor(options = {}) {
  1089. this.intro = options.intro || '';
  1090. this.separator = options.separator !== undefined ? options.separator : '\n';
  1091. this.sources = [];
  1092. this.uniqueSources = [];
  1093. this.uniqueSourceIndexByFilename = {};
  1094. }
  1095. addSource(source) {
  1096. if (source instanceof MagicString) {
  1097. return this.addSource({
  1098. content: source,
  1099. filename: source.filename,
  1100. separator: this.separator,
  1101. });
  1102. }
  1103. if (!isObject(source) || !source.content) {
  1104. throw new Error(
  1105. 'bundle.addSource() takes an object with a `content` property, which should be an instance of MagicString, and an optional `filename`',
  1106. );
  1107. }
  1108. ['filename', 'ignoreList', 'indentExclusionRanges', 'separator'].forEach((option) => {
  1109. if (!hasOwnProp.call(source, option)) source[option] = source.content[option];
  1110. });
  1111. if (source.separator === undefined) {
  1112. // TODO there's a bunch of this sort of thing, needs cleaning up
  1113. source.separator = this.separator;
  1114. }
  1115. if (source.filename) {
  1116. if (!hasOwnProp.call(this.uniqueSourceIndexByFilename, source.filename)) {
  1117. this.uniqueSourceIndexByFilename[source.filename] = this.uniqueSources.length;
  1118. this.uniqueSources.push({ filename: source.filename, content: source.content.original });
  1119. } else {
  1120. const uniqueSource = this.uniqueSources[this.uniqueSourceIndexByFilename[source.filename]];
  1121. if (source.content.original !== uniqueSource.content) {
  1122. throw new Error(`Illegal source: same filename (${source.filename}), different contents`);
  1123. }
  1124. }
  1125. }
  1126. this.sources.push(source);
  1127. return this;
  1128. }
  1129. append(str, options) {
  1130. this.addSource({
  1131. content: new MagicString(str),
  1132. separator: (options && options.separator) || '',
  1133. });
  1134. return this;
  1135. }
  1136. clone() {
  1137. const bundle = new Bundle({
  1138. intro: this.intro,
  1139. separator: this.separator,
  1140. });
  1141. this.sources.forEach((source) => {
  1142. bundle.addSource({
  1143. filename: source.filename,
  1144. content: source.content.clone(),
  1145. separator: source.separator,
  1146. });
  1147. });
  1148. return bundle;
  1149. }
  1150. generateDecodedMap(options = {}) {
  1151. const names = [];
  1152. let x_google_ignoreList = undefined;
  1153. this.sources.forEach((source) => {
  1154. Object.keys(source.content.storedNames).forEach((name) => {
  1155. if (!~names.indexOf(name)) names.push(name);
  1156. });
  1157. });
  1158. const mappings = new Mappings(options.hires);
  1159. if (this.intro) {
  1160. mappings.advance(this.intro);
  1161. }
  1162. this.sources.forEach((source, i) => {
  1163. if (i > 0) {
  1164. mappings.advance(this.separator);
  1165. }
  1166. const sourceIndex = source.filename ? this.uniqueSourceIndexByFilename[source.filename] : -1;
  1167. const magicString = source.content;
  1168. const locate = getLocator(magicString.original);
  1169. if (magicString.intro) {
  1170. mappings.advance(magicString.intro);
  1171. }
  1172. magicString.firstChunk.eachNext((chunk) => {
  1173. const loc = locate(chunk.start);
  1174. if (chunk.intro.length) mappings.advance(chunk.intro);
  1175. if (source.filename) {
  1176. if (chunk.edited) {
  1177. mappings.addEdit(
  1178. sourceIndex,
  1179. chunk.content,
  1180. loc,
  1181. chunk.storeName ? names.indexOf(chunk.original) : -1,
  1182. );
  1183. } else {
  1184. mappings.addUneditedChunk(
  1185. sourceIndex,
  1186. chunk,
  1187. magicString.original,
  1188. loc,
  1189. magicString.sourcemapLocations,
  1190. );
  1191. }
  1192. } else {
  1193. mappings.advance(chunk.content);
  1194. }
  1195. if (chunk.outro.length) mappings.advance(chunk.outro);
  1196. });
  1197. if (magicString.outro) {
  1198. mappings.advance(magicString.outro);
  1199. }
  1200. if (source.ignoreList && sourceIndex !== -1) {
  1201. if (x_google_ignoreList === undefined) {
  1202. x_google_ignoreList = [];
  1203. }
  1204. x_google_ignoreList.push(sourceIndex);
  1205. }
  1206. });
  1207. return {
  1208. file: options.file ? options.file.split(/[/\\]/).pop() : undefined,
  1209. sources: this.uniqueSources.map((source) => {
  1210. return options.file ? getRelativePath(options.file, source.filename) : source.filename;
  1211. }),
  1212. sourcesContent: this.uniqueSources.map((source) => {
  1213. return options.includeContent ? source.content : null;
  1214. }),
  1215. names,
  1216. mappings: mappings.raw,
  1217. x_google_ignoreList,
  1218. };
  1219. }
  1220. generateMap(options) {
  1221. return new SourceMap(this.generateDecodedMap(options));
  1222. }
  1223. getIndentString() {
  1224. const indentStringCounts = {};
  1225. this.sources.forEach((source) => {
  1226. const indentStr = source.content._getRawIndentString();
  1227. if (indentStr === null) return;
  1228. if (!indentStringCounts[indentStr]) indentStringCounts[indentStr] = 0;
  1229. indentStringCounts[indentStr] += 1;
  1230. });
  1231. return (
  1232. Object.keys(indentStringCounts).sort((a, b) => {
  1233. return indentStringCounts[a] - indentStringCounts[b];
  1234. })[0] || '\t'
  1235. );
  1236. }
  1237. indent(indentStr) {
  1238. if (!arguments.length) {
  1239. indentStr = this.getIndentString();
  1240. }
  1241. if (indentStr === '') return this; // noop
  1242. let trailingNewline = !this.intro || this.intro.slice(-1) === '\n';
  1243. this.sources.forEach((source, i) => {
  1244. const separator = source.separator !== undefined ? source.separator : this.separator;
  1245. const indentStart = trailingNewline || (i > 0 && /\r?\n$/.test(separator));
  1246. source.content.indent(indentStr, {
  1247. exclude: source.indentExclusionRanges,
  1248. indentStart, //: trailingNewline || /\r?\n$/.test( separator ) //true///\r?\n/.test( separator )
  1249. });
  1250. trailingNewline = source.content.lastChar() === '\n';
  1251. });
  1252. if (this.intro) {
  1253. this.intro =
  1254. indentStr +
  1255. this.intro.replace(/^[^\n]/gm, (match, index) => {
  1256. return index > 0 ? indentStr + match : match;
  1257. });
  1258. }
  1259. return this;
  1260. }
  1261. prepend(str) {
  1262. this.intro = str + this.intro;
  1263. return this;
  1264. }
  1265. toString() {
  1266. const body = this.sources
  1267. .map((source, i) => {
  1268. const separator = source.separator !== undefined ? source.separator : this.separator;
  1269. const str = (i > 0 ? separator : '') + source.content.toString();
  1270. return str;
  1271. })
  1272. .join('');
  1273. return this.intro + body;
  1274. }
  1275. isEmpty() {
  1276. if (this.intro.length && this.intro.trim()) return false;
  1277. if (this.sources.some((source) => !source.content.isEmpty())) return false;
  1278. return true;
  1279. }
  1280. length() {
  1281. return this.sources.reduce(
  1282. (length, source) => length + source.content.length(),
  1283. this.intro.length,
  1284. );
  1285. }
  1286. trimLines() {
  1287. return this.trim('[\\r\\n]');
  1288. }
  1289. trim(charType) {
  1290. return this.trimStart(charType).trimEnd(charType);
  1291. }
  1292. trimStart(charType) {
  1293. const rx = new RegExp('^' + (charType || '\\s') + '+');
  1294. this.intro = this.intro.replace(rx, '');
  1295. if (!this.intro) {
  1296. let source;
  1297. let i = 0;
  1298. do {
  1299. source = this.sources[i++];
  1300. if (!source) {
  1301. break;
  1302. }
  1303. } while (!source.content.trimStartAborted(charType));
  1304. }
  1305. return this;
  1306. }
  1307. trimEnd(charType) {
  1308. const rx = new RegExp((charType || '\\s') + '+$');
  1309. let source;
  1310. let i = this.sources.length - 1;
  1311. do {
  1312. source = this.sources[i--];
  1313. if (!source) {
  1314. this.intro = this.intro.replace(rx, '');
  1315. break;
  1316. }
  1317. } while (!source.content.trimEndAborted(charType));
  1318. return this;
  1319. }
  1320. }
  1321. MagicString.Bundle = Bundle;
  1322. MagicString.SourceMap = SourceMap;
  1323. MagicString.default = MagicString; // work around TypeScript bug https://github.com/Rich-Harris/magic-string/pull/121
  1324. return MagicString;
  1325. }));
  1326. //# sourceMappingURL=magic-string.umd.js.map