chunk-magic-string.56b2b543.mjs 34 KB

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