generate-helpers.js 1.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960
  1. import fs from "fs";
  2. import { join } from "path";
  3. import { URL, fileURLToPath } from "url";
  4. const HELPERS_FOLDER = new URL("../src/helpers", import.meta.url);
  5. const IGNORED_FILES = new Set(["package.json"]);
  6. export default async function generateAsserts() {
  7. let output = `/*
  8. * This file is auto-generated! Do not modify it directly.
  9. * To re-generate run 'make build'
  10. */
  11. import template from "@babel/template";
  12. `;
  13. for (const file of (await fs.promises.readdir(HELPERS_FOLDER)).sort()) {
  14. if (IGNORED_FILES.has(file)) continue;
  15. const [helperName] = file.split(".");
  16. const isValidId = isValidBindingIdentifier(helperName);
  17. const varName = isValidId ? helperName : `_${helperName}`;
  18. const fileContents = await fs.promises.readFile(
  19. join(fileURLToPath(HELPERS_FOLDER), file),
  20. "utf8"
  21. );
  22. const { minVersion } = fileContents.match(
  23. /^\s*\/\*\s*@minVersion\s+(?<minVersion>\S+)\s*\*\/\s*$/m
  24. ).groups;
  25. // TODO: We can minify the helpers in production
  26. const source = fileContents
  27. // Remove comments
  28. .replace(/\/\*[^]*?\*\/|\/\/.*/g, "")
  29. // Remove multiple newlines
  30. .replace(/\n{2,}/g, "\n");
  31. const intro = isValidId
  32. ? "export "
  33. : `export { ${varName} as ${helperName} }\n`;
  34. output += `\n${intro}const ${varName} = {
  35. minVersion: ${JSON.stringify(minVersion)},
  36. ast: () => template.program.ast(${JSON.stringify(source)})
  37. };\n`;
  38. }
  39. return output;
  40. }
  41. function isValidBindingIdentifier(name) {
  42. try {
  43. Function(`var ${name}`);
  44. return true;
  45. } catch {
  46. return false;
  47. }
  48. }