magic-string.cjs.js 38 KB

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