magic-string.umd.js 41 KB

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