magic-string.cjs.js 33 KB

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