forked from openai/openai-node
-
Notifications
You must be signed in to change notification settings - Fork 0
/
denoify.ts
229 lines (212 loc) · 7 KB
/
denoify.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
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
import path from 'path';
import * as tm from 'ts-morph';
import { name as pkgName } from '../package.json';
import fs from 'fs';
const rootDir = path.resolve(__dirname, '..');
const denoDir = path.join(rootDir, 'deno');
const tsConfigFilePath = path.join(rootDir, 'tsconfig.deno.json');
async function denoify() {
const project = new tm.Project({ tsConfigFilePath });
for (const file of project.getSourceFiles()) {
if (!file.getFilePath().startsWith(denoDir + '/')) continue;
let addedBuffer = false,
addedProcess = false;
file.forEachDescendant((node) => {
switch (node.getKind()) {
case tm.ts.SyntaxKind.ExportDeclaration: {
const decl: tm.ExportDeclaration = node as any;
if (decl.isTypeOnly()) return;
for (const named of decl.getNamedExports()) {
// Convert `export { Foo } from './foo.ts'`
// to `export { type Foo } from './foo.ts'`
// if `./foo.ts` only exports types for `Foo`
if (!named.isTypeOnly() && !hasValueDeclarations(named)) {
named.replaceWithText(`type ${named.getText()}`);
}
}
break;
}
case tm.ts.SyntaxKind.ImportEqualsDeclaration: {
const decl: tm.ImportEqualsDeclaration = node as any;
if (decl.isTypeOnly()) return;
const ref = decl.getModuleReference();
if (!hasValueDeclarations(ref)) {
const params = isBuiltinType(ref.getType()) ? [] : ref.getType().getTypeArguments();
if (params.length) {
const paramsStr = params.map((p: tm.TypeParameter) => p.getText()).join(', ');
const bindingsStr = params
.map((p: tm.TypeParameter) => p.getSymbol()?.getName() || p.getText())
.join(', ');
decl.replaceWithText(
`export type ${decl.getName()}<${paramsStr}> = ${ref.getText()}<${bindingsStr}>`,
);
} else {
decl.replaceWithText(`export type ${decl.getName()} = ${ref.getText()}`);
}
}
break;
}
case tm.ts.SyntaxKind.Identifier: {
const id = node as tm.Identifier;
if (!addedBuffer && id.getText() === 'Buffer') {
addedBuffer = true;
file?.addVariableStatement({
declarations: [
{
name: 'Buffer',
type: 'any',
},
],
hasDeclareKeyword: true,
});
file?.addTypeAlias({
name: 'Buffer',
type: 'any',
});
}
if (!addedProcess && id.getText() === 'process') {
addedProcess = true;
file?.addVariableStatement({
declarations: [
{
name: 'process',
type: 'any',
},
],
hasDeclareKeyword: true,
});
}
}
}
});
}
await project.save();
for (const file of project.getSourceFiles()) {
if (!file.getFilePath().startsWith(denoDir + '/')) continue;
for (const decl of [...file.getImportDeclarations(), ...file.getExportDeclarations()]) {
const moduleSpecifier = decl.getModuleSpecifier();
if (!moduleSpecifier) continue;
let specifier = moduleSpecifier.getLiteralValue().replace(/^node:/, '');
if (!specifier || specifier.startsWith('http')) continue;
if (nodeStdModules.has(specifier)) {
// convert node builtins to deno.land/std
specifier = `https://deno.land/[email protected]/node/${specifier}.ts`;
} else if (specifier.startsWith(pkgName + '/')) {
// convert self-referencing module specifiers to relative paths
specifier = file.getRelativePathAsModuleSpecifierTo(denoDir + specifier.substring(pkgName.length));
} else if (specifier === 'qs') {
decl.replaceWithText(`import { qs } from "https://deno.land/x/[email protected]/mod.ts"`);
continue;
} else if (!decl.isModuleSpecifierRelative()) {
specifier = `npm:${specifier}`;
}
if (specifier.startsWith('./') || specifier.startsWith('../')) {
// there may be CJS directory module specifiers that implicitly resolve
// to /index.ts. Add an explicit /index.ts to the end
const sourceFile = decl.getModuleSpecifierSourceFile();
if (sourceFile && /\/index\.ts$/.test(sourceFile.getFilePath()) && !/\/mod\.ts$/.test(specifier)) {
if (/\/index(\.ts)?$/.test(specifier)) {
specifier = specifier.replace(/\/index(\.ts)?$/, '/mod.ts');
} else {
specifier += '/mod.ts';
}
}
// add explicit .ts file extensions to relative module specifiers
specifier = specifier.replace(/(\.[^./]*)?$/, '.ts');
}
moduleSpecifier.replaceWithText(JSON.stringify(specifier));
}
}
await project.save();
await Promise.all(
project.getSourceFiles().map(async (f) => {
const filePath = f.getFilePath();
if (filePath.endsWith('index.ts')) {
const newPath = filePath.replace(/index\.ts$/, 'mod.ts');
await fs.promises.rename(filePath, newPath);
}
}),
);
}
const nodeStdModules = new Set([
'assert',
'assertion_error',
'async_hooks',
'buffer',
'child_process',
'cluster',
'console',
'constants',
'crypto',
'dgram',
'diagnostics_channel',
'dns',
'domain',
'events',
'fs',
'global',
'http',
'http2',
'https',
'inspector',
'module_all',
'module_esm',
'module',
'net',
'os',
'path',
'perf_hooks',
'process',
'punycode',
'querystring',
'readline',
'repl',
'stream',
'string_decoder',
'sys',
'timers',
'tls',
'tty',
'upstream_modules',
'url',
'util',
'v8',
'vm',
'wasi',
'worker_threads',
'zlib',
]);
const typeDeclarationKinds = new Set([
tm.ts.SyntaxKind.InterfaceDeclaration,
tm.ts.SyntaxKind.ModuleDeclaration,
tm.ts.SyntaxKind.TypeAliasDeclaration,
]);
const builtinTypeNames = new Set(['Array', 'Set', 'Map', 'Record', 'Promise']);
function isBuiltinType(type: tm.Type): boolean {
const symbol = type.getSymbol();
return (
symbol != null &&
builtinTypeNames.has(symbol.getName()) &&
symbol.getDeclarations().some((d) => d.getSourceFile().getFilePath().includes('node_modules/typescript'))
);
}
function hasValueDeclarations(nodes?: tm.Node): boolean;
function hasValueDeclarations(nodes?: tm.Node[]): boolean;
function hasValueDeclarations(nodes?: tm.Node | tm.Node[]): boolean {
if (nodes && !Array.isArray(nodes)) {
return (
!isBuiltinType(nodes.getType()) && hasValueDeclarations(nodes.getType().getSymbol()?.getDeclarations())
);
}
return nodes ?
nodes.some((n) => {
const parent = n.getParent();
return (
!typeDeclarationKinds.has(n.getKind()) &&
// sometimes the node will be the right hand side of a type alias
(!parent || !typeDeclarationKinds.has(parent.getKind()))
);
})
: false;
}
denoify();