magic-string.cjs.js 33 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298
  1. 'use strict';
  2. var sourcemapCodec = require('sourcemap-codec');
  3. var Chunk = function Chunk(start, end, content) {
  4. this.start = start;
  5. this.end = end;
  6. this.original = content;
  7. this.intro = '';
  8. this.outro = '';
  9. this.content = content;
  10. this.storeName = false;
  11. this.edited = false;
  12. // we make these non-enumerable, for sanity while debugging
  13. Object.defineProperties(this, {
  14. previous: { writable: true, value: null },
  15. next: { writable: true, value: null }
  16. });
  17. };
  18. Chunk.prototype.appendLeft = function appendLeft (content) {
  19. this.outro += content;
  20. };
  21. Chunk.prototype.appendRight = function appendRight (content) {
  22. this.intro = this.intro + content;
  23. };
  24. Chunk.prototype.clone = function clone () {
  25. var chunk = new Chunk(this.start, this.end, this.original);
  26. chunk.intro = this.intro;
  27. chunk.outro = this.outro;
  28. chunk.content = this.content;
  29. chunk.storeName = this.storeName;
  30. chunk.edited = this.edited;
  31. return chunk;
  32. };
  33. Chunk.prototype.contains = function contains (index) {
  34. return this.start < index && index < this.end;
  35. };
  36. Chunk.prototype.eachNext = function eachNext (fn) {
  37. var chunk = this;
  38. while (chunk) {
  39. fn(chunk);
  40. chunk = chunk.next;
  41. }
  42. };
  43. Chunk.prototype.eachPrevious = function eachPrevious (fn) {
  44. var chunk = this;
  45. while (chunk) {
  46. fn(chunk);
  47. chunk = chunk.previous;
  48. }
  49. };
  50. Chunk.prototype.edit = function edit (content, storeName, contentOnly) {
  51. this.content = content;
  52. if (!contentOnly) {
  53. this.intro = '';
  54. this.outro = '';
  55. }
  56. this.storeName = storeName;
  57. this.edited = true;
  58. return this;
  59. };
  60. Chunk.prototype.prependLeft = function prependLeft (content) {
  61. this.outro = content + this.outro;
  62. };
  63. Chunk.prototype.prependRight = function prependRight (content) {
  64. this.intro = content + this.intro;
  65. };
  66. Chunk.prototype.split = function split (index) {
  67. var sliceIndex = index - this.start;
  68. var originalBefore = this.original.slice(0, sliceIndex);
  69. var originalAfter = this.original.slice(sliceIndex);
  70. this.original = originalBefore;
  71. var newChunk = new Chunk(index, this.end, originalAfter);
  72. newChunk.outro = this.outro;
  73. this.outro = '';
  74. this.end = index;
  75. if (this.edited) {
  76. // TODO is this block necessary?...
  77. newChunk.edit('', false);
  78. this.content = '';
  79. } else {
  80. this.content = originalBefore;
  81. }
  82. newChunk.next = this.next;
  83. if (newChunk.next) { newChunk.next.previous = newChunk; }
  84. newChunk.previous = this;
  85. this.next = newChunk;
  86. return newChunk;
  87. };
  88. Chunk.prototype.toString = function toString () {
  89. return this.intro + this.content + this.outro;
  90. };
  91. Chunk.prototype.trimEnd = function trimEnd (rx) {
  92. this.outro = this.outro.replace(rx, '');
  93. if (this.outro.length) { return true; }
  94. var trimmed = this.content.replace(rx, '');
  95. if (trimmed.length) {
  96. if (trimmed !== this.content) {
  97. this.split(this.start + trimmed.length).edit('', undefined, true);
  98. }
  99. return true;
  100. } else {
  101. this.edit('', undefined, true);
  102. this.intro = this.intro.replace(rx, '');
  103. if (this.intro.length) { return true; }
  104. }
  105. };
  106. Chunk.prototype.trimStart = function trimStart (rx) {
  107. this.intro = this.intro.replace(rx, '');
  108. if (this.intro.length) { return true; }
  109. var trimmed = this.content.replace(rx, '');
  110. if (trimmed.length) {
  111. if (trimmed !== this.content) {
  112. this.split(this.end - trimmed.length);
  113. this.edit('', undefined, true);
  114. }
  115. return true;
  116. } else {
  117. this.edit('', undefined, true);
  118. this.outro = this.outro.replace(rx, '');
  119. if (this.outro.length) { return true; }
  120. }
  121. };
  122. var btoa = function () {
  123. throw new Error('Unsupported environment: `window.btoa` or `Buffer` should be supported.');
  124. };
  125. if (typeof window !== 'undefined' && typeof window.btoa === 'function') {
  126. btoa = function (str) { return window.btoa(unescape(encodeURIComponent(str))); };
  127. } else if (typeof Buffer === 'function') {
  128. btoa = function (str) { return Buffer.from(str, 'utf-8').toString('base64'); };
  129. }
  130. var SourceMap = function SourceMap(properties) {
  131. this.version = 3;
  132. this.file = properties.file;
  133. this.sources = properties.sources;
  134. this.sourcesContent = properties.sourcesContent;
  135. this.names = properties.names;
  136. this.mappings = sourcemapCodec.encode(properties.mappings);
  137. };
  138. SourceMap.prototype.toString = function toString () {
  139. return JSON.stringify(this);
  140. };
  141. SourceMap.prototype.toUrl = function toUrl () {
  142. return 'data:application/json;charset=utf-8;base64,' + btoa(this.toString());
  143. };
  144. function guessIndent(code) {
  145. var lines = code.split('\n');
  146. var tabbed = lines.filter(function (line) { return /^\t+/.test(line); });
  147. var spaced = lines.filter(function (line) { return /^ {2,}/.test(line); });
  148. if (tabbed.length === 0 && spaced.length === 0) {
  149. return null;
  150. }
  151. // More lines tabbed than spaced? Assume tabs, and
  152. // default to tabs in the case of a tie (or nothing
  153. // to go on)
  154. if (tabbed.length >= spaced.length) {
  155. return '\t';
  156. }
  157. // Otherwise, we need to guess the multiple
  158. var min = spaced.reduce(function (previous, current) {
  159. var numSpaces = /^ +/.exec(current)[0].length;
  160. return Math.min(numSpaces, previous);
  161. }, Infinity);
  162. return new Array(min + 1).join(' ');
  163. }
  164. function getRelativePath(from, to) {
  165. var fromParts = from.split(/[/\\]/);
  166. var toParts = to.split(/[/\\]/);
  167. fromParts.pop(); // get dirname
  168. while (fromParts[0] === toParts[0]) {
  169. fromParts.shift();
  170. toParts.shift();
  171. }
  172. if (fromParts.length) {
  173. var i = fromParts.length;
  174. while (i--) { fromParts[i] = '..'; }
  175. }
  176. return fromParts.concat(toParts).join('/');
  177. }
  178. var toString = Object.prototype.toString;
  179. function isObject(thing) {
  180. return toString.call(thing) === '[object Object]';
  181. }
  182. function getLocator(source) {
  183. var originalLines = source.split('\n');
  184. var lineOffsets = [];
  185. for (var i = 0, pos = 0; i < originalLines.length; i++) {
  186. lineOffsets.push(pos);
  187. pos += originalLines[i].length + 1;
  188. }
  189. return function locate(index) {
  190. var i = 0;
  191. var j = lineOffsets.length;
  192. while (i < j) {
  193. var m = (i + j) >> 1;
  194. if (index < lineOffsets[m]) {
  195. j = m;
  196. } else {
  197. i = m + 1;
  198. }
  199. }
  200. var line = i - 1;
  201. var column = index - lineOffsets[line];
  202. return { line: line, column: column };
  203. };
  204. }
  205. var Mappings = function Mappings(hires) {
  206. this.hires = hires;
  207. this.generatedCodeLine = 0;
  208. this.generatedCodeColumn = 0;
  209. this.raw = [];
  210. this.rawSegments = this.raw[this.generatedCodeLine] = [];
  211. this.pending = null;
  212. };
  213. Mappings.prototype.addEdit = function addEdit (sourceIndex, content, loc, nameIndex) {
  214. if (content.length) {
  215. var segment = [this.generatedCodeColumn, sourceIndex, loc.line, loc.column];
  216. if (nameIndex >= 0) {
  217. segment.push(nameIndex);
  218. }
  219. this.rawSegments.push(segment);
  220. } else if (this.pending) {
  221. this.rawSegments.push(this.pending);
  222. }
  223. this.advance(content);
  224. this.pending = null;
  225. };
  226. Mappings.prototype.addUneditedChunk = function addUneditedChunk (sourceIndex, chunk, original, loc, sourcemapLocations) {
  227. var originalCharIndex = chunk.start;
  228. var first = true;
  229. while (originalCharIndex < chunk.end) {
  230. if (this.hires || first || sourcemapLocations[originalCharIndex]) {
  231. this.rawSegments.push([this.generatedCodeColumn, sourceIndex, loc.line, loc.column]);
  232. }
  233. if (original[originalCharIndex] === '\n') {
  234. loc.line += 1;
  235. loc.column = 0;
  236. this.generatedCodeLine += 1;
  237. this.raw[this.generatedCodeLine] = this.rawSegments = [];
  238. this.generatedCodeColumn = 0;
  239. } else {
  240. loc.column += 1;
  241. this.generatedCodeColumn += 1;
  242. }
  243. originalCharIndex += 1;
  244. first = false;
  245. }
  246. this.pending = [this.generatedCodeColumn, sourceIndex, loc.line, loc.column];
  247. };
  248. Mappings.prototype.advance = function advance (str) {
  249. if (!str) { return; }
  250. var lines = str.split('\n');
  251. if (lines.length > 1) {
  252. for (var i = 0; i < lines.length - 1; i++) {
  253. this.generatedCodeLine++;
  254. this.raw[this.generatedCodeLine] = this.rawSegments = [];
  255. }
  256. this.generatedCodeColumn = 0;
  257. }
  258. this.generatedCodeColumn += lines[lines.length - 1].length;
  259. };
  260. var n = '\n';
  261. var warned = {
  262. insertLeft: false,
  263. insertRight: false,
  264. storeName: false
  265. };
  266. var MagicString = function MagicString(string, options) {
  267. if ( options === void 0 ) options = {};
  268. var chunk = new Chunk(0, string.length, string);
  269. Object.defineProperties(this, {
  270. original: { writable: true, value: string },
  271. outro: { writable: true, value: '' },
  272. intro: { writable: true, value: '' },
  273. firstChunk: { writable: true, value: chunk },
  274. lastChunk: { writable: true, value: chunk },
  275. lastSearchedChunk: { writable: true, value: chunk },
  276. byStart: { writable: true, value: {} },
  277. byEnd: { writable: true, value: {} },
  278. filename: { writable: true, value: options.filename },
  279. indentExclusionRanges: { writable: true, value: options.indentExclusionRanges },
  280. sourcemapLocations: { writable: true, value: {} },
  281. storedNames: { writable: true, value: {} },
  282. indentStr: { writable: true, value: guessIndent(string) }
  283. });
  284. this.byStart[0] = chunk;
  285. this.byEnd[string.length] = chunk;
  286. };
  287. MagicString.prototype.addSourcemapLocation = function addSourcemapLocation (char) {
  288. this.sourcemapLocations[char] = true;
  289. };
  290. MagicString.prototype.append = function append (content) {
  291. if (typeof content !== 'string') { throw new TypeError('outro content must be a string'); }
  292. this.outro += content;
  293. return this;
  294. };
  295. MagicString.prototype.appendLeft = function appendLeft (index, content) {
  296. if (typeof content !== 'string') { throw new TypeError('inserted content must be a string'); }
  297. this._split(index);
  298. var chunk = this.byEnd[index];
  299. if (chunk) {
  300. chunk.appendLeft(content);
  301. } else {
  302. this.intro += content;
  303. }
  304. return this;
  305. };
  306. MagicString.prototype.appendRight = function appendRight (index, content) {
  307. if (typeof content !== 'string') { throw new TypeError('inserted content must be a string'); }
  308. this._split(index);
  309. var chunk = this.byStart[index];
  310. if (chunk) {
  311. chunk.appendRight(content);
  312. } else {
  313. this.outro += content;
  314. }
  315. return this;
  316. };
  317. MagicString.prototype.clone = function clone () {
  318. var cloned = new MagicString(this.original, { filename: this.filename });
  319. var originalChunk = this.firstChunk;
  320. var clonedChunk = (cloned.firstChunk = cloned.lastSearchedChunk = originalChunk.clone());
  321. while (originalChunk) {
  322. cloned.byStart[clonedChunk.start] = clonedChunk;
  323. cloned.byEnd[clonedChunk.end] = clonedChunk;
  324. var nextOriginalChunk = originalChunk.next;
  325. var nextClonedChunk = nextOriginalChunk && nextOriginalChunk.clone();
  326. if (nextClonedChunk) {
  327. clonedChunk.next = nextClonedChunk;
  328. nextClonedChunk.previous = clonedChunk;
  329. clonedChunk = nextClonedChunk;
  330. }
  331. originalChunk = nextOriginalChunk;
  332. }
  333. cloned.lastChunk = clonedChunk;
  334. if (this.indentExclusionRanges) {
  335. cloned.indentExclusionRanges = this.indentExclusionRanges.slice();
  336. }
  337. Object.keys(this.sourcemapLocations).forEach(function (loc) {
  338. cloned.sourcemapLocations[loc] = true;
  339. });
  340. return cloned;
  341. };
  342. MagicString.prototype.generateDecodedMap = function generateDecodedMap (options) {
  343. var this$1 = this;
  344. options = options || {};
  345. var sourceIndex = 0;
  346. var names = Object.keys(this.storedNames);
  347. var mappings = new Mappings(options.hires);
  348. var locate = getLocator(this.original);
  349. if (this.intro) {
  350. mappings.advance(this.intro);
  351. }
  352. this.firstChunk.eachNext(function (chunk) {
  353. var loc = locate(chunk.start);
  354. if (chunk.intro.length) { mappings.advance(chunk.intro); }
  355. if (chunk.edited) {
  356. mappings.addEdit(
  357. sourceIndex,
  358. chunk.content,
  359. loc,
  360. chunk.storeName ? names.indexOf(chunk.original) : -1
  361. );
  362. } else {
  363. mappings.addUneditedChunk(sourceIndex, chunk, this$1.original, loc, this$1.sourcemapLocations);
  364. }
  365. if (chunk.outro.length) { mappings.advance(chunk.outro); }
  366. });
  367. return {
  368. file: options.file ? options.file.split(/[/\\]/).pop() : null,
  369. sources: [options.source ? getRelativePath(options.file || '', options.source) : null],
  370. sourcesContent: options.includeContent ? [this.original] : [null],
  371. names: names,
  372. mappings: mappings.raw
  373. };
  374. };
  375. MagicString.prototype.generateMap = function generateMap (options) {
  376. return new SourceMap(this.generateDecodedMap(options));
  377. };
  378. MagicString.prototype.getIndentString = function getIndentString () {
  379. return this.indentStr === null ? '\t' : this.indentStr;
  380. };
  381. MagicString.prototype.indent = function indent (indentStr, options) {
  382. var pattern = /^[^\r\n]/gm;
  383. if (isObject(indentStr)) {
  384. options = indentStr;
  385. indentStr = undefined;
  386. }
  387. indentStr = indentStr !== undefined ? indentStr : this.indentStr || '\t';
  388. if (indentStr === '') { return this; } // noop
  389. options = options || {};
  390. // Process exclusion ranges
  391. var isExcluded = {};
  392. if (options.exclude) {
  393. var exclusions =
  394. typeof options.exclude[0] === 'number' ? [options.exclude] : options.exclude;
  395. exclusions.forEach(function (exclusion) {
  396. for (var i = exclusion[0]; i < exclusion[1]; i += 1) {
  397. isExcluded[i] = true;
  398. }
  399. });
  400. }
  401. var shouldIndentNextCharacter = options.indentStart !== false;
  402. var replacer = function (match) {
  403. if (shouldIndentNextCharacter) { return ("" + indentStr + match); }
  404. shouldIndentNextCharacter = true;
  405. return match;
  406. };
  407. this.intro = this.intro.replace(pattern, replacer);
  408. var charIndex = 0;
  409. var chunk = this.firstChunk;
  410. while (chunk) {
  411. var end = chunk.end;
  412. if (chunk.edited) {
  413. if (!isExcluded[charIndex]) {
  414. chunk.content = chunk.content.replace(pattern, replacer);
  415. if (chunk.content.length) {
  416. shouldIndentNextCharacter = chunk.content[chunk.content.length - 1] === '\n';
  417. }
  418. }
  419. } else {
  420. charIndex = chunk.start;
  421. while (charIndex < end) {
  422. if (!isExcluded[charIndex]) {
  423. var char = this.original[charIndex];
  424. if (char === '\n') {
  425. shouldIndentNextCharacter = true;
  426. } else if (char !== '\r' && shouldIndentNextCharacter) {
  427. shouldIndentNextCharacter = false;
  428. if (charIndex === chunk.start) {
  429. chunk.prependRight(indentStr);
  430. } else {
  431. this._splitChunk(chunk, charIndex);
  432. chunk = chunk.next;
  433. chunk.prependRight(indentStr);
  434. }
  435. }
  436. }
  437. charIndex += 1;
  438. }
  439. }
  440. charIndex = chunk.end;
  441. chunk = chunk.next;
  442. }
  443. this.outro = this.outro.replace(pattern, replacer);
  444. return this;
  445. };
  446. MagicString.prototype.insert = function insert () {
  447. throw new Error('magicString.insert(...) is deprecated. Use prependRight(...) or appendLeft(...)');
  448. };
  449. MagicString.prototype.insertLeft = function insertLeft (index, content) {
  450. if (!warned.insertLeft) {
  451. console.warn('magicString.insertLeft(...) is deprecated. Use magicString.appendLeft(...) instead'); // eslint-disable-line no-console
  452. warned.insertLeft = true;
  453. }
  454. return this.appendLeft(index, content);
  455. };
  456. MagicString.prototype.insertRight = function insertRight (index, content) {
  457. if (!warned.insertRight) {
  458. console.warn('magicString.insertRight(...) is deprecated. Use magicString.prependRight(...) instead'); // eslint-disable-line no-console
  459. warned.insertRight = true;
  460. }
  461. return this.prependRight(index, content);
  462. };
  463. MagicString.prototype.move = function move (start, end, index) {
  464. if (index >= start && index <= end) { throw new Error('Cannot move a selection inside itself'); }
  465. this._split(start);
  466. this._split(end);
  467. this._split(index);
  468. var first = this.byStart[start];
  469. var last = this.byEnd[end];
  470. var oldLeft = first.previous;
  471. var oldRight = last.next;
  472. var newRight = this.byStart[index];
  473. if (!newRight && last === this.lastChunk) { return this; }
  474. var newLeft = newRight ? newRight.previous : this.lastChunk;
  475. if (oldLeft) { oldLeft.next = oldRight; }
  476. if (oldRight) { oldRight.previous = oldLeft; }
  477. if (newLeft) { newLeft.next = first; }
  478. if (newRight) { newRight.previous = last; }
  479. if (!first.previous) { this.firstChunk = last.next; }
  480. if (!last.next) {
  481. this.lastChunk = first.previous;
  482. this.lastChunk.next = null;
  483. }
  484. first.previous = newLeft;
  485. last.next = newRight || null;
  486. if (!newLeft) { this.firstChunk = first; }
  487. if (!newRight) { this.lastChunk = last; }
  488. return this;
  489. };
  490. MagicString.prototype.overwrite = function overwrite (start, end, content, options) {
  491. if (typeof content !== 'string') { throw new TypeError('replacement content must be a string'); }
  492. while (start < 0) { start += this.original.length; }
  493. while (end < 0) { end += this.original.length; }
  494. if (end > this.original.length) { throw new Error('end is out of bounds'); }
  495. if (start === end)
  496. { throw new Error('Cannot overwrite a zero-length range – use appendLeft or prependRight instead'); }
  497. this._split(start);
  498. this._split(end);
  499. if (options === true) {
  500. if (!warned.storeName) {
  501. console.warn('The final argument to magicString.overwrite(...) should be an options object. See https://github.com/rich-harris/magic-string'); // eslint-disable-line no-console
  502. warned.storeName = true;
  503. }
  504. options = { storeName: true };
  505. }
  506. var storeName = options !== undefined ? options.storeName : false;
  507. var contentOnly = options !== undefined ? options.contentOnly : false;
  508. if (storeName) {
  509. var original = this.original.slice(start, end);
  510. this.storedNames[original] = true;
  511. }
  512. var first = this.byStart[start];
  513. var last = this.byEnd[end];
  514. if (first) {
  515. if (end > first.end && first.next !== this.byStart[first.end]) {
  516. throw new Error('Cannot overwrite across a split point');
  517. }
  518. first.edit(content, storeName, contentOnly);
  519. if (first !== last) {
  520. var chunk = first.next;
  521. while (chunk !== last) {
  522. chunk.edit('', false);
  523. chunk = chunk.next;
  524. }
  525. chunk.edit('', false);
  526. }
  527. } else {
  528. // must be inserting at the end
  529. var newChunk = new Chunk(start, end, '').edit(content, storeName);
  530. // TODO last chunk in the array may not be the last chunk, if it's moved...
  531. last.next = newChunk;
  532. newChunk.previous = last;
  533. }
  534. return this;
  535. };
  536. MagicString.prototype.prepend = function prepend (content) {
  537. if (typeof content !== 'string') { throw new TypeError('outro content must be a string'); }
  538. this.intro = content + this.intro;
  539. return this;
  540. };
  541. MagicString.prototype.prependLeft = function prependLeft (index, content) {
  542. if (typeof content !== 'string') { throw new TypeError('inserted content must be a string'); }
  543. this._split(index);
  544. var chunk = this.byEnd[index];
  545. if (chunk) {
  546. chunk.prependLeft(content);
  547. } else {
  548. this.intro = content + this.intro;
  549. }
  550. return this;
  551. };
  552. MagicString.prototype.prependRight = function prependRight (index, content) {
  553. if (typeof content !== 'string') { throw new TypeError('inserted content must be a string'); }
  554. this._split(index);
  555. var chunk = this.byStart[index];
  556. if (chunk) {
  557. chunk.prependRight(content);
  558. } else {
  559. this.outro = content + this.outro;
  560. }
  561. return this;
  562. };
  563. MagicString.prototype.remove = function remove (start, end) {
  564. while (start < 0) { start += this.original.length; }
  565. while (end < 0) { end += this.original.length; }
  566. if (start === end) { return this; }
  567. if (start < 0 || end > this.original.length) { throw new Error('Character is out of bounds'); }
  568. if (start > end) { throw new Error('end must be greater than start'); }
  569. this._split(start);
  570. this._split(end);
  571. var chunk = this.byStart[start];
  572. while (chunk) {
  573. chunk.intro = '';
  574. chunk.outro = '';
  575. chunk.edit('');
  576. chunk = end > chunk.end ? this.byStart[chunk.end] : null;
  577. }
  578. return this;
  579. };
  580. MagicString.prototype.lastChar = function lastChar () {
  581. if (this.outro.length)
  582. { return this.outro[this.outro.length - 1]; }
  583. var chunk = this.lastChunk;
  584. do {
  585. if (chunk.outro.length)
  586. { return chunk.outro[chunk.outro.length - 1]; }
  587. if (chunk.content.length)
  588. { return chunk.content[chunk.content.length - 1]; }
  589. if (chunk.intro.length)
  590. { return chunk.intro[chunk.intro.length - 1]; }
  591. } while (chunk = chunk.previous);
  592. if (this.intro.length)
  593. { return this.intro[this.intro.length - 1]; }
  594. return '';
  595. };
  596. MagicString.prototype.lastLine = function lastLine () {
  597. var lineIndex = this.outro.lastIndexOf(n);
  598. if (lineIndex !== -1)
  599. { return this.outro.substr(lineIndex + 1); }
  600. var lineStr = this.outro;
  601. var chunk = this.lastChunk;
  602. do {
  603. if (chunk.outro.length > 0) {
  604. lineIndex = chunk.outro.lastIndexOf(n);
  605. if (lineIndex !== -1)
  606. { return chunk.outro.substr(lineIndex + 1) + lineStr; }
  607. lineStr = chunk.outro + lineStr;
  608. }
  609. if (chunk.content.length > 0) {
  610. lineIndex = chunk.content.lastIndexOf(n);
  611. if (lineIndex !== -1)
  612. { return chunk.content.substr(lineIndex + 1) + lineStr; }
  613. lineStr = chunk.content + lineStr;
  614. }
  615. if (chunk.intro.length > 0) {
  616. lineIndex = chunk.intro.lastIndexOf(n);
  617. if (lineIndex !== -1)
  618. { return chunk.intro.substr(lineIndex + 1) + lineStr; }
  619. lineStr = chunk.intro + lineStr;
  620. }
  621. } while (chunk = chunk.previous);
  622. lineIndex = this.intro.lastIndexOf(n);
  623. if (lineIndex !== -1)
  624. { return this.intro.substr(lineIndex + 1) + lineStr; }
  625. return this.intro + lineStr;
  626. };
  627. MagicString.prototype.slice = function slice (start, end) {
  628. if ( start === void 0 ) start = 0;
  629. if ( end === void 0 ) end = this.original.length;
  630. while (start < 0) { start += this.original.length; }
  631. while (end < 0) { end += this.original.length; }
  632. var result = '';
  633. // find start chunk
  634. var chunk = this.firstChunk;
  635. while (chunk && (chunk.start > start || chunk.end <= start)) {
  636. // found end chunk before start
  637. if (chunk.start < end && chunk.end >= end) {
  638. return result;
  639. }
  640. chunk = chunk.next;
  641. }
  642. if (chunk && chunk.edited && chunk.start !== start)
  643. { throw new Error(("Cannot use replaced character " + start + " as slice start anchor.")); }
  644. var startChunk = chunk;
  645. while (chunk) {
  646. if (chunk.intro && (startChunk !== chunk || chunk.start === start)) {
  647. result += chunk.intro;
  648. }
  649. var containsEnd = chunk.start < end && chunk.end >= end;
  650. if (containsEnd && chunk.edited && chunk.end !== end)
  651. { throw new Error(("Cannot use replaced character " + end + " as slice end anchor.")); }
  652. var sliceStart = startChunk === chunk ? start - chunk.start : 0;
  653. var sliceEnd = containsEnd ? chunk.content.length + end - chunk.end : chunk.content.length;
  654. result += chunk.content.slice(sliceStart, sliceEnd);
  655. if (chunk.outro && (!containsEnd || chunk.end === end)) {
  656. result += chunk.outro;
  657. }
  658. if (containsEnd) {
  659. break;
  660. }
  661. chunk = chunk.next;
  662. }
  663. return result;
  664. };
  665. // TODO deprecate this? not really very useful
  666. MagicString.prototype.snip = function snip (start, end) {
  667. var clone = this.clone();
  668. clone.remove(0, start);
  669. clone.remove(end, clone.original.length);
  670. return clone;
  671. };
  672. MagicString.prototype._split = function _split (index) {
  673. if (this.byStart[index] || this.byEnd[index]) { return; }
  674. var chunk = this.lastSearchedChunk;
  675. var searchForward = index > chunk.end;
  676. while (chunk) {
  677. if (chunk.contains(index)) { return this._splitChunk(chunk, index); }
  678. chunk = searchForward ? this.byStart[chunk.end] : this.byEnd[chunk.start];
  679. }
  680. };
  681. MagicString.prototype._splitChunk = function _splitChunk (chunk, index) {
  682. if (chunk.edited && chunk.content.length) {
  683. // zero-length edited chunks are a special case (overlapping replacements)
  684. var loc = getLocator(this.original)(index);
  685. throw new Error(
  686. ("Cannot split a chunk that has already been edited (" + (loc.line) + ":" + (loc.column) + " – \"" + (chunk.original) + "\")")
  687. );
  688. }
  689. var newChunk = chunk.split(index);
  690. this.byEnd[index] = chunk;
  691. this.byStart[index] = newChunk;
  692. this.byEnd[newChunk.end] = newChunk;
  693. if (chunk === this.lastChunk) { this.lastChunk = newChunk; }
  694. this.lastSearchedChunk = chunk;
  695. return true;
  696. };
  697. MagicString.prototype.toString = function toString () {
  698. var str = this.intro;
  699. var chunk = this.firstChunk;
  700. while (chunk) {
  701. str += chunk.toString();
  702. chunk = chunk.next;
  703. }
  704. return str + this.outro;
  705. };
  706. MagicString.prototype.isEmpty = function isEmpty () {
  707. var chunk = this.firstChunk;
  708. do {
  709. if (chunk.intro.length && chunk.intro.trim() ||
  710. chunk.content.length && chunk.content.trim() ||
  711. chunk.outro.length && chunk.outro.trim())
  712. { return false; }
  713. } while (chunk = chunk.next);
  714. return true;
  715. };
  716. MagicString.prototype.length = function length () {
  717. var chunk = this.firstChunk;
  718. var length = 0;
  719. do {
  720. length += chunk.intro.length + chunk.content.length + chunk.outro.length;
  721. } while (chunk = chunk.next);
  722. return length;
  723. };
  724. MagicString.prototype.trimLines = function trimLines () {
  725. return this.trim('[\\r\\n]');
  726. };
  727. MagicString.prototype.trim = function trim (charType) {
  728. return this.trimStart(charType).trimEnd(charType);
  729. };
  730. MagicString.prototype.trimEndAborted = function trimEndAborted (charType) {
  731. var rx = new RegExp((charType || '\\s') + '+$');
  732. this.outro = this.outro.replace(rx, '');
  733. if (this.outro.length) { return true; }
  734. var chunk = this.lastChunk;
  735. do {
  736. var end = chunk.end;
  737. var aborted = chunk.trimEnd(rx);
  738. // if chunk was trimmed, we have a new lastChunk
  739. if (chunk.end !== end) {
  740. if (this.lastChunk === chunk) {
  741. this.lastChunk = chunk.next;
  742. }
  743. this.byEnd[chunk.end] = chunk;
  744. this.byStart[chunk.next.start] = chunk.next;
  745. this.byEnd[chunk.next.end] = chunk.next;
  746. }
  747. if (aborted) { return true; }
  748. chunk = chunk.previous;
  749. } while (chunk);
  750. return false;
  751. };
  752. MagicString.prototype.trimEnd = function trimEnd (charType) {
  753. this.trimEndAborted(charType);
  754. return this;
  755. };
  756. MagicString.prototype.trimStartAborted = function trimStartAborted (charType) {
  757. var rx = new RegExp('^' + (charType || '\\s') + '+');
  758. this.intro = this.intro.replace(rx, '');
  759. if (this.intro.length) { return true; }
  760. var chunk = this.firstChunk;
  761. do {
  762. var end = chunk.end;
  763. var aborted = chunk.trimStart(rx);
  764. if (chunk.end !== end) {
  765. // special case...
  766. if (chunk === this.lastChunk) { this.lastChunk = chunk.next; }
  767. this.byEnd[chunk.end] = chunk;
  768. this.byStart[chunk.next.start] = chunk.next;
  769. this.byEnd[chunk.next.end] = chunk.next;
  770. }
  771. if (aborted) { return true; }
  772. chunk = chunk.next;
  773. } while (chunk);
  774. return false;
  775. };
  776. MagicString.prototype.trimStart = function trimStart (charType) {
  777. this.trimStartAborted(charType);
  778. return this;
  779. };
  780. var hasOwnProp = Object.prototype.hasOwnProperty;
  781. var Bundle = function Bundle(options) {
  782. if ( options === void 0 ) options = {};
  783. this.intro = options.intro || '';
  784. this.separator = options.separator !== undefined ? options.separator : '\n';
  785. this.sources = [];
  786. this.uniqueSources = [];
  787. this.uniqueSourceIndexByFilename = {};
  788. };
  789. Bundle.prototype.addSource = function addSource (source) {
  790. if (source instanceof MagicString) {
  791. return this.addSource({
  792. content: source,
  793. filename: source.filename,
  794. separator: this.separator
  795. });
  796. }
  797. if (!isObject(source) || !source.content) {
  798. throw new Error('bundle.addSource() takes an object with a `content` property, which should be an instance of MagicString, and an optional `filename`');
  799. }
  800. ['filename', 'indentExclusionRanges', 'separator'].forEach(function (option) {
  801. if (!hasOwnProp.call(source, option)) { source[option] = source.content[option]; }
  802. });
  803. if (source.separator === undefined) {
  804. // TODO there's a bunch of this sort of thing, needs cleaning up
  805. source.separator = this.separator;
  806. }
  807. if (source.filename) {
  808. if (!hasOwnProp.call(this.uniqueSourceIndexByFilename, source.filename)) {
  809. this.uniqueSourceIndexByFilename[source.filename] = this.uniqueSources.length;
  810. this.uniqueSources.push({ filename: source.filename, content: source.content.original });
  811. } else {
  812. var uniqueSource = this.uniqueSources[this.uniqueSourceIndexByFilename[source.filename]];
  813. if (source.content.original !== uniqueSource.content) {
  814. throw new Error(("Illegal source: same filename (" + (source.filename) + "), different contents"));
  815. }
  816. }
  817. }
  818. this.sources.push(source);
  819. return this;
  820. };
  821. Bundle.prototype.append = function append (str, options) {
  822. this.addSource({
  823. content: new MagicString(str),
  824. separator: (options && options.separator) || ''
  825. });
  826. return this;
  827. };
  828. Bundle.prototype.clone = function clone () {
  829. var bundle = new Bundle({
  830. intro: this.intro,
  831. separator: this.separator
  832. });
  833. this.sources.forEach(function (source) {
  834. bundle.addSource({
  835. filename: source.filename,
  836. content: source.content.clone(),
  837. separator: source.separator
  838. });
  839. });
  840. return bundle;
  841. };
  842. Bundle.prototype.generateDecodedMap = function generateDecodedMap (options) {
  843. var this$1 = this;
  844. if ( options === void 0 ) options = {};
  845. var names = [];
  846. this.sources.forEach(function (source) {
  847. Object.keys(source.content.storedNames).forEach(function (name) {
  848. if (!~names.indexOf(name)) { names.push(name); }
  849. });
  850. });
  851. var mappings = new Mappings(options.hires);
  852. if (this.intro) {
  853. mappings.advance(this.intro);
  854. }
  855. this.sources.forEach(function (source, i) {
  856. if (i > 0) {
  857. mappings.advance(this$1.separator);
  858. }
  859. var sourceIndex = source.filename ? this$1.uniqueSourceIndexByFilename[source.filename] : -1;
  860. var magicString = source.content;
  861. var locate = getLocator(magicString.original);
  862. if (magicString.intro) {
  863. mappings.advance(magicString.intro);
  864. }
  865. magicString.firstChunk.eachNext(function (chunk) {
  866. var loc = locate(chunk.start);
  867. if (chunk.intro.length) { mappings.advance(chunk.intro); }
  868. if (source.filename) {
  869. if (chunk.edited) {
  870. mappings.addEdit(
  871. sourceIndex,
  872. chunk.content,
  873. loc,
  874. chunk.storeName ? names.indexOf(chunk.original) : -1
  875. );
  876. } else {
  877. mappings.addUneditedChunk(
  878. sourceIndex,
  879. chunk,
  880. magicString.original,
  881. loc,
  882. magicString.sourcemapLocations
  883. );
  884. }
  885. } else {
  886. mappings.advance(chunk.content);
  887. }
  888. if (chunk.outro.length) { mappings.advance(chunk.outro); }
  889. });
  890. if (magicString.outro) {
  891. mappings.advance(magicString.outro);
  892. }
  893. });
  894. return {
  895. file: options.file ? options.file.split(/[/\\]/).pop() : null,
  896. sources: this.uniqueSources.map(function (source) {
  897. return options.file ? getRelativePath(options.file, source.filename) : source.filename;
  898. }),
  899. sourcesContent: this.uniqueSources.map(function (source) {
  900. return options.includeContent ? source.content : null;
  901. }),
  902. names: names,
  903. mappings: mappings.raw
  904. };
  905. };
  906. Bundle.prototype.generateMap = function generateMap (options) {
  907. return new SourceMap(this.generateDecodedMap(options));
  908. };
  909. Bundle.prototype.getIndentString = function getIndentString () {
  910. var indentStringCounts = {};
  911. this.sources.forEach(function (source) {
  912. var indentStr = source.content.indentStr;
  913. if (indentStr === null) { return; }
  914. if (!indentStringCounts[indentStr]) { indentStringCounts[indentStr] = 0; }
  915. indentStringCounts[indentStr] += 1;
  916. });
  917. return (
  918. Object.keys(indentStringCounts).sort(function (a, b) {
  919. return indentStringCounts[a] - indentStringCounts[b];
  920. })[0] || '\t'
  921. );
  922. };
  923. Bundle.prototype.indent = function indent (indentStr) {
  924. var this$1 = this;
  925. if (!arguments.length) {
  926. indentStr = this.getIndentString();
  927. }
  928. if (indentStr === '') { return this; } // noop
  929. var trailingNewline = !this.intro || this.intro.slice(-1) === '\n';
  930. this.sources.forEach(function (source, i) {
  931. var separator = source.separator !== undefined ? source.separator : this$1.separator;
  932. var indentStart = trailingNewline || (i > 0 && /\r?\n$/.test(separator));
  933. source.content.indent(indentStr, {
  934. exclude: source.indentExclusionRanges,
  935. indentStart: indentStart //: trailingNewline || /\r?\n$/.test( separator ) //true///\r?\n/.test( separator )
  936. });
  937. trailingNewline = source.content.lastChar() === '\n';
  938. });
  939. if (this.intro) {
  940. this.intro =
  941. indentStr +
  942. this.intro.replace(/^[^\n]/gm, function (match, index) {
  943. return index > 0 ? indentStr + match : match;
  944. });
  945. }
  946. return this;
  947. };
  948. Bundle.prototype.prepend = function prepend (str) {
  949. this.intro = str + this.intro;
  950. return this;
  951. };
  952. Bundle.prototype.toString = function toString () {
  953. var this$1 = this;
  954. var body = this.sources
  955. .map(function (source, i) {
  956. var separator = source.separator !== undefined ? source.separator : this$1.separator;
  957. var str = (i > 0 ? separator : '') + source.content.toString();
  958. return str;
  959. })
  960. .join('');
  961. return this.intro + body;
  962. };
  963. Bundle.prototype.isEmpty = function isEmpty () {
  964. if (this.intro.length && this.intro.trim())
  965. { return false; }
  966. if (this.sources.some(function (source) { return !source.content.isEmpty(); }))
  967. { return false; }
  968. return true;
  969. };
  970. Bundle.prototype.length = function length () {
  971. return this.sources.reduce(function (length, source) { return length + source.content.length(); }, this.intro.length);
  972. };
  973. Bundle.prototype.trimLines = function trimLines () {
  974. return this.trim('[\\r\\n]');
  975. };
  976. Bundle.prototype.trim = function trim (charType) {
  977. return this.trimStart(charType).trimEnd(charType);
  978. };
  979. Bundle.prototype.trimStart = function trimStart (charType) {
  980. var rx = new RegExp('^' + (charType || '\\s') + '+');
  981. this.intro = this.intro.replace(rx, '');
  982. if (!this.intro) {
  983. var source;
  984. var i = 0;
  985. do {
  986. source = this.sources[i++];
  987. if (!source) {
  988. break;
  989. }
  990. } while (!source.content.trimStartAborted(charType));
  991. }
  992. return this;
  993. };
  994. Bundle.prototype.trimEnd = function trimEnd (charType) {
  995. var rx = new RegExp((charType || '\\s') + '+$');
  996. var source;
  997. var i = this.sources.length - 1;
  998. do {
  999. source = this.sources[i--];
  1000. if (!source) {
  1001. this.intro = this.intro.replace(rx, '');
  1002. break;
  1003. }
  1004. } while (!source.content.trimEndAborted(charType));
  1005. return this;
  1006. };
  1007. MagicString.Bundle = Bundle;
  1008. MagicString.default = MagicString; // work around TypeScript bug https://github.com/Rich-Harris/magic-string/pull/121
  1009. module.exports = MagicString;
  1010. //# sourceMappingURL=magic-string.cjs.js.map