sourceBased.js 1.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051
  1. "use strict";
  2. Object.defineProperty(exports, "__esModule", { value: true });
  3. exports.overwriteSource = void 0;
  4. const basic_1 = require("./basic");
  5. function searchSource(s, ...args) {
  6. const source = args.length >= 2 ? args[0] : undefined;
  7. const sourceLoc = args.length >= 2 ? args[1] : args[0];
  8. let _offset = 0;
  9. let result;
  10. for (const segment of s) {
  11. if (typeof segment === 'string') {
  12. _offset += segment.length;
  13. continue;
  14. }
  15. if (segment[1] === source) {
  16. const segmentStart = typeof segment[2] === 'number' ? segment[2] : segment[2][0];
  17. const segmentEnd = typeof segment[2] === 'number' ? segment[2] + segment[0].length : segment[2][1];
  18. if (sourceLoc >= segmentStart && sourceLoc <= segmentEnd) {
  19. result = _offset + (sourceLoc - segmentStart);
  20. break;
  21. }
  22. }
  23. _offset += segment[0].length;
  24. }
  25. if (result === undefined) {
  26. throw new Error(`Source index not found, source: ${source}, index: ${sourceLoc}`);
  27. }
  28. return result;
  29. }
  30. function overwriteSource(s, ...args) {
  31. let loc;
  32. let newSegments;
  33. if (typeof args[0] === 'string') {
  34. const source = args[0];
  35. const sourceLoc = args[1];
  36. loc = typeof sourceLoc === 'number'
  37. ? searchSource(s, source, sourceLoc)
  38. : [searchSource(s, source, sourceLoc[0]), searchSource(s, source, sourceLoc[1])];
  39. newSegments = args.slice(2);
  40. }
  41. else {
  42. const sourceLoc = args[0];
  43. loc = typeof sourceLoc === 'number'
  44. ? searchSource(s, sourceLoc)
  45. : [searchSource(s, sourceLoc[0]), searchSource(s, sourceLoc[1])];
  46. newSegments = args.slice(1);
  47. }
  48. return (0, basic_1.overwrite)(s, loc, ...newSegments);
  49. }
  50. exports.overwriteSource = overwriteSource;
  51. //# sourceMappingURL=sourceBased.js.map