magic-string.cjs.js 36 KB

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