magic-string.cjs.js 35 KB

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