-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmod.ts
75 lines (61 loc) · 1.7 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
73
74
75
import { existsSync } from 'https://deno.land/std@0.197.0/fs/mod.ts';
const MODULE_REGEX = /^(?:(?!\.).)*$/;
export default () => {
const externalsCode: Record<string, Uint8Array> = {};
const bundleExternal = (path: string) => {
try {
const command = new Deno.Command(Deno.execPath(), {
args: ['bundle', path],
});
const { stdout } = command.outputSync();
externalsCode[path] = stdout;
return true;
} catch (e) {
console.error(`Error getting "${path}": ${e.message}`);
return false;
}
};
const onResolveHttp = args => {
const ok = bundleExternal(args.path);
if (!ok) return null;
return {
path: args.path,
namespace: 'deno-loader',
};
};
const onResolveModuleMap = args => {
const [_currentPath, ...nextPath] = args.path.split('/');
const currentPath = _currentPath + (nextPath.length ? '/' : '');
if (currentPath.match(MODULE_REGEX)) {
const cwd = Deno.cwd();
const denoPath = `${cwd}/deno.json`;
if (!existsSync(denoPath)) {
console.error(`deno.json not found in "${cwd}"`);
return null;
}
const denoJson = JSON.parse(Deno.readTextFileSync(denoPath));
const path = denoJson.imports[currentPath] + nextPath?.join('/');
if (!bundleExternal(path)) return null;
return {
path: path,
namespace: 'deno-loader',
};
}
return null;
};
const onLoad = args => {
return {
contents: externalsCode[args.path],
loader: 'js',
};
};
const setup = build => {
build.onResolve({ filter: /^https?:\/\// }, onResolveHttp);
build.onResolve({ filter: /. */ }, onResolveModuleMap);
build.onLoad({ filter: /.*/, namespace: 'deno-loader' }, onLoad);
};
return {
name: 'deno-loader',
setup,
};
};