magic-string.es.mjs 35 KB

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