magic-string.umd.js 36 KB

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