storybook/code/ui/manager/scripts/generate-exports-file.ts
2022-11-29 18:36:32 +01:00

72 lines
1.7 KiB
TypeScript

/* eslint-disable no-console */
import fs from 'fs-extra';
import path from 'path';
import { dedent } from 'ts-dedent';
import { ESLint } from '../../../../scripts/node_modules/eslint';
import { values } from '../src/globals/runtime';
const location = path.join(__dirname, '..', 'src', 'globals', 'exports.ts');
let attempts = 0;
function removeDefault(input: string) {
return input !== 'default';
}
const wait = (ms: number) => new Promise((resolve) => setTimeout(resolve, ms));
async function generate(text: string) {
console.log('Linting...');
const eslint = new ESLint({
cwd: path.join(__dirname, '..'),
fix: true,
});
const output = await eslint.lintText(text, { filePath: location });
console.log('Writing...');
await fs.writeFile(location, output[0].output);
}
const run = async () => {
const data = Object.entries(values).reduce<Record<string, string[]>>((acc, [key, value]) => {
acc[key] = Object.keys(value).filter(removeDefault);
return acc;
}, {});
console.log('Generating...');
const text = dedent`
// this file is generated by generate-exports-file.ts
// this is done to prevent runtime dependencies from making it's way into the build/start script of the manager
// the manager builder needs to know which dependencies are 'globalized' in the ui
export default ${JSON.stringify(data, null, 2)} as const;`;
await fs.ensureFile(location);
const tryGenerate = async () => {
attempts += 1;
await generate(text).catch(async (e) => {
if (attempts > 5) {
throw e;
}
console.log('Retrying...');
await wait(1000);
await tryGenerate();
});
};
await tryGenerate();
console.log('Done!');
};
run().catch((e) => {
console.error(e);
process.exitCode = 1;
});