magic-string.es.mjs 35 KB

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