magic-string.es.mjs 37 KB

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