generate-helpers.js 1.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263
  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. if (file.startsWith(".")) continue; // ignore e.g. vim swap files
  16. const [helperName] = file.split(".");
  17. const isValidId = isValidBindingIdentifier(helperName);
  18. const varName = isValidId ? helperName : `_${helperName}`;
  19. const filePath = join(fileURLToPath(HELPERS_FOLDER), file);
  20. const fileContents = await fs.promises.readFile(filePath, "utf8");
  21. const minVersionMatch = fileContents.match(
  22. /^\s*\/\*\s*@minVersion\s+(?<minVersion>\S+)\s*\*\/\s*$/m
  23. );
  24. if (!minVersionMatch) {
  25. throw new Error(`@minVersion number missing in ${filePath}`);
  26. }
  27. const { minVersion } = minVersionMatch.groups;
  28. // TODO: We can minify the helpers in production
  29. const source = fileContents
  30. // Remove comments
  31. .replace(/\/\*[^]*?\*\/|\/\/.*/g, "")
  32. // Remove multiple newlines
  33. .replace(/\n{2,}/g, "\n");
  34. const intro = isValidId
  35. ? "export "
  36. : `export { ${varName} as ${helperName} }\n`;
  37. output += `\n${intro}const ${varName} = {
  38. minVersion: ${JSON.stringify(minVersion)},
  39. ast: () => template.program.ast(${JSON.stringify(source)})
  40. };\n`;
  41. }
  42. return output;
  43. }
  44. function isValidBindingIdentifier(name) {
  45. try {
  46. Function(`var ${name}`);
  47. return true;
  48. } catch {
  49. return false;
  50. }
  51. }