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