parse-ast-index.mjs 2.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960
  1. import { l as locate, n as error, s as logParseError, t as augmentCodeLocation, u as getCodeFrame } from "./shared/logs-D80CXhvg.mjs";
  2. import { n as parseSync, t as parse } from "./shared/parse-BywQARUG.mjs";
  3. //#region src/parse-ast-index.ts
  4. function wrap(result, filename, sourceText) {
  5. if (result.errors.length > 0) return normalizeParseError(filename, sourceText, result.errors);
  6. return result.program;
  7. }
  8. function normalizeParseError(filename, sourceText, errors) {
  9. let message = `Parse failed with ${errors.length} error${errors.length < 2 ? "" : "s"}:\n`;
  10. const pos = errors[0]?.labels?.[0]?.start;
  11. for (let i = 0; i < errors.length; i++) {
  12. if (i >= 5) {
  13. message += "\n...";
  14. break;
  15. }
  16. const e = errors[i];
  17. message += e.message + "\n" + e.labels.map((label) => {
  18. const location = locate(sourceText, label.start, { offsetLine: 1 });
  19. if (!location) return;
  20. return getCodeFrame(sourceText, location.line, location.column);
  21. }).filter(Boolean).join("\n");
  22. }
  23. const log = logParseError(message, filename, pos);
  24. if (pos !== void 0 && filename) augmentCodeLocation(log, pos, sourceText, filename);
  25. return error(log);
  26. }
  27. const defaultParserOptions = {
  28. lang: "js",
  29. preserveParens: false
  30. };
  31. /**
  32. * Parse code synchronously and return the AST.
  33. *
  34. * This function is similar to Rollup's `parseAst` function.
  35. * Prefer using {@linkcode parseSync} instead of this function as it has more information in the return value.
  36. *
  37. * @category Utilities
  38. */
  39. function parseAst(sourceText, options, filename) {
  40. return wrap(parseSync(filename ?? "file.js", sourceText, {
  41. ...defaultParserOptions,
  42. ...options
  43. }), filename, sourceText);
  44. }
  45. /**
  46. * Parse code asynchronously and return the AST.
  47. *
  48. * This function is similar to Rollup's `parseAstAsync` function.
  49. * Prefer using {@linkcode parseAsync} instead of this function as it has more information in the return value.
  50. *
  51. * @category Utilities
  52. */
  53. async function parseAstAsync(sourceText, options, filename) {
  54. return wrap(await parse(filename ?? "file.js", sourceText, {
  55. ...defaultParserOptions,
  56. ...options
  57. }), filename, sourceText);
  58. }
  59. //#endregion
  60. export { parseAst, parseAstAsync };