parse-ast-index.mjs 2.1 KB

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