55517a25d13497a8beaf1448c0cf3aeb4babf272b40aae3f4915cd03c994f2c4c6db7eb504b340f9bd8e5f65110dc849772994ade0e14395a9e1818faa3f7a 33 KB

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