-
-
Notifications
You must be signed in to change notification settings - Fork 1.1k
/
index.ts
62 lines (56 loc) · 2 KB
/
index.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
import fs from 'node:fs';
import path from 'node:path';
import type { CommonOptions, ConfigFile, GenerationOptions, OutputFileOptions } from './types';
import { isValidUrl, prettify } from './utils';
export type { ConfigFile } from './types';
export async function generateEndpoints(options: GenerationOptions): Promise<string | void> {
const schemaLocation = options.schemaFile;
const schemaAbsPath = isValidUrl(options.schemaFile)
? options.schemaFile
: path.resolve(process.cwd(), schemaLocation);
const sourceCode = await enforceOazapftsTsVersion(async () => {
const { generateApi } = await import('./generate');
return generateApi(schemaAbsPath, options);
});
const { outputFile } = options;
if (outputFile) {
fs.writeFileSync(path.resolve(process.cwd(), outputFile), await prettify(outputFile, sourceCode));
} else {
return await prettify(null, sourceCode);
}
}
export function parseConfig(fullConfig: ConfigFile) {
const outFiles: (CommonOptions & OutputFileOptions)[] = [];
if ('outputFiles' in fullConfig) {
const { outputFiles, ...commonConfig } = fullConfig;
for (const [outputFile, specificConfig] of Object.entries(outputFiles)) {
outFiles.push({
...commonConfig,
...specificConfig,
outputFile,
});
}
} else {
outFiles.push(fullConfig);
}
return outFiles;
}
/**
* Enforces `oazapfts` to use the same TypeScript version as this module itself uses.
* That should prevent enums from running out of sync if both libraries use different TS versions.
*/
function enforceOazapftsTsVersion<T>(cb: () => T): T {
const ozTsPath = require.resolve('typescript', { paths: [require.resolve('oazapfts')] });
const tsPath = require.resolve('typescript');
const originalEntry = require.cache[ozTsPath];
try {
require.cache[ozTsPath] = require.cache[tsPath];
return cb();
} finally {
if (originalEntry) {
require.cache[ozTsPath] = originalEntry;
} else {
delete require.cache[ozTsPath];
}
}
}