-
Notifications
You must be signed in to change notification settings - Fork 22
Expand file tree
/
Copy pathdeno-build.mjs
More file actions
81 lines (66 loc) · 2.85 KB
/
deno-build.mjs
File metadata and controls
81 lines (66 loc) · 2.85 KB
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
// source from: https://github.com/colinhacks/zod/blob/main/deno-build.mjs
// Although this script generates code for use in Deno, this script itself is// written for Node so that contributors do not need to install Deno to build.
// @ts-check
import {
mkdirSync,
readdirSync,
readFileSync,
statSync,
writeFileSync,
} from "fs";
import { dirname } from "path";
// Node's path.join() normalize explicitly-relative paths like "./index.ts" to
// paths like "index.ts" which don't work as relative ES imports, so we do this.
const join = (/** @type string[] */ ...parts) =>
parts.join("/").replace(/\/\//g, "/");
// const targetFilesReg = /(?<!\.spec)\.ts$/
const projectRoot = process.cwd();
const nodeSrcRoot = join(projectRoot, "src");
const denoLibRoot = join(projectRoot, "dist");
const walkAndBuild = (/** @type string */ dir) => {
for (const entry of readdirSync(join(nodeSrcRoot, dir), {
withFileTypes: true,
encoding: "utf-8",
})) {
if (entry.isDirectory()) {
walkAndBuild(join(dir, entry.name));
} else if (entry.isFile() && entry.name.endsWith(".ts")) {
const nodePath = join(nodeSrcRoot, dir, entry.name);
const denoPath = join(denoLibRoot, dir, entry.name);
// skip those files
if (/\.spec\.ts$/.test(nodePath)) {
// console.log(`Skipping ${nodePath}`);
continue;
}
const nodeSource = readFileSync(nodePath, { encoding: "utf-8" });
const denoSource = nodeSource.replace(
/^(?:import|export)[\s\S]*?from\s*['"]([^'"]*)['"];?$/gm,
(line, target) => {
const targetNodePath = join(dirname(nodePath), target);
const targetNodePathIfFile = targetNodePath + ".ts";
const targetNodePathIfDir = join(targetNodePath, "index.ts");
if (/\.ts$/.test(targetNodePath)) {
return line
}
try {
if (statSync(targetNodePathIfFile)?.isFile()) {
return line.replace(target, target + ".ts");
}
if (statSync(targetNodePathIfDir)?.isFile()) {
return line.replace(target, join(target, "index.ts"));
}
} catch (error) {
if (error?.code !== "ENOENT") {
throw error;
}
}
// console.warn(`Skipping non-resolvable import:\n ${line}`);
return line;
}
);
mkdirSync(dirname(denoPath), { recursive: true });
writeFileSync(denoPath, denoSource, { encoding: "utf-8" });
}
}
};
walkAndBuild("");