magic-string.cjs.js 34 KB

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