-
Notifications
You must be signed in to change notification settings - Fork 0
/
mod.ts
72 lines (63 loc) · 1.77 KB
/
mod.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
import {
bundle as denoBundle,
transpile,
} from "https://deno.land/x/[email protected]/mod.ts";
import { resolve } from "https://deno.land/[email protected]/path/mod.ts";
export async function bundle(
entry: string,
importMap?: string,
): Promise<string> {
const imap = getImportMap(importMap);
const files = await transpile(entry, {
importMap: imap,
});
await Promise.all(
Object.keys(files).map(async (path) => {
if (!isBucket(files.get(path) as string)) return;
const content = await getSource(path);
files.set(path, content);
}),
);
const fileContent = await denoBundle(entry, {
compilerOptions: {
sourceMap: false,
},
async load(url: string) {
return await Promise.resolve({
kind: "module",
specifier: url,
content: files.get(url) as string,
});
},
importMap: imap,
});
const code = fileContent.code;
const lastIndex = code.lastIndexOf("//# sourceMappingURL");
return lastIndex ? code.slice(0, lastIndex) : code;
}
function isBucket(content: string): boolean {
const str = content.slice(0, 20);
return str.includes("is-deno-bucket");
}
async function getSource(path: string): Promise<string> {
const data = await import(path);
return `export default ${JSON.stringify(data.default)}`;
}
function getImportMap(path?: string) {
if (!path) {
const json = resolve("deno.json");
if (existsSync(json)) return JSON.parse(Deno.readTextFileSync(json));
const jsonc = resolve("deno.jsonc");
if (existsSync(jsonc)) return JSON.parse(Deno.readTextFileSync(jsonc));
return;
}
return JSON.parse(Deno.readTextFileSync(resolve(path)));
}
function existsSync(path: string): boolean {
try {
Deno.statSync(path);
} catch (e) {
return !e;
}
return true;
}