magic-string.es.mjs 34 KB

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