magic-string.cjs.js 37 KB

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