generate-helpers.js 1.9 KB

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