-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathextract-types.mjs
36 lines (30 loc) · 1.21 KB
/
extract-types.mjs
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
import fs from 'node:fs';
import path from 'node:path';
/**
* This is used to extract the type declarations from the openai Node.js
* package. Doing this allows it to be a devDependency instead of a dependency,
* which greatly reduces the size of the final bundle.
*/
function extractTypes(srcDir, destDir) {
if (!fs.existsSync(destDir)) {
fs.mkdirSync(destDir, { recursive: true });
}
const entries = fs.readdirSync(srcDir, { withFileTypes: true });
for (const entry of entries) {
const srcPath = path.join(srcDir, entry.name);
const destPath = path.join(destDir, entry.name);
if (entry.isDirectory()) {
extractTypes(srcPath, destPath);
} else if (entry.isFile() && entry.name.endsWith('.d.ts')) {
const depth = Math.max(0, destPath.split('/').length - 2);
const relativePath = depth > 0 ? '../'.repeat(depth) : './';
// OpenAI has some absolute package imports, so switch them to use relative imports.
const content = fs
.readFileSync(srcPath, 'utf8')
.replaceAll(/'openai\/([^'.]*)'/g, `'${relativePath}$1.js'`);
fs.writeFileSync(destPath, content);
console.log(destPath);
}
}
}
extractTypes('node_modules/openai', 'openai-types');