-
Notifications
You must be signed in to change notification settings - Fork 0
/
esbuild.ts
169 lines (149 loc) · 5.16 KB
/
esbuild.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
import { z } from "zod";
import { Tool } from "openai-function-calling-tools";
import * as esbuild from "esbuild-wasm";
import axios from "axios";
import localForage from "localforage";
const fileCache = localForage.createInstance({
name: "fileCache",
});
export const unpkgFetchPlugin = (
inputCode: string | undefined,
entryPoint: string
): esbuild.Plugin => {
return {
name: "unpkg-fetch-plugin",
setup(build: esbuild.PluginBuild) {
//match entrypoint
if (entryPoint === "index.ts") {
build.onLoad({ filter: /(^index\.ts$)/ }, () => {
return {
loader: "tsx",
contents: inputCode,
};
});
} else {
build.onLoad({ filter: /(^index\.js$)/ }, () => {
return {
loader: "jsx",
contents: inputCode,
};
});
}
build.onLoad({ filter: /.*/ }, async (args: esbuild.OnLoadArgs) => {
const cacheResult = await fileCache.getItem<esbuild.OnLoadResult>(
args.path
);
if (cacheResult) {
return cacheResult;
}
return null;
});
//match css file
build.onLoad({ filter: /.css$/ }, async (args: esbuild.OnLoadArgs) => {
const { data, request } = await axios.get(args.path);
const escapedData = data
.replace(/\n/g, "")
.replace(/"/g, '\\"')
.replace(/'/g, "\\'");
const contents = `const style = document.createElement("style");
style.innerText = '${escapedData}';
document.head.appendChild(style);`;
const result: esbuild.OnLoadResult = {
loader: "jsx",
contents,
//specify the place where the content was found
resolveDir: new URL("./", request.responseURL).pathname,
};
//store response in cache
await fileCache.setItem(args.path, result);
return result;
});
//=================================================
build.onLoad({ filter: /.*/ }, async (args: esbuild.OnLoadArgs) => {
console.log(`...fetching ${args.path}`);
const { data, request } = await axios.get(args.path);
const result: esbuild.OnLoadResult = {
loader: "jsx",
contents: data,
//specify the place where the content was found
resolveDir: new URL("./", request.responseURL).pathname,
};
//store response in cache
await fileCache.setItem(args.path, result);
console.log("end of fetching");
return result;
});
},
};
};
export const unpkgPathPlugin = (): esbuild.Plugin => {
return {
name: "unpkg-path-plugin",
setup(build: esbuild.PluginBuild) {
//
build.onResolve({ filter: /.*/ }, (args) => {
if (args.kind === "entry-point") {
return { path: args.path, namespace: "a" };
}
return undefined;
});
//match relative path in a module "./" or "../"
build.onResolve({ filter: /^\.+\// }, (args: esbuild.OnResolveArgs) => {
return {
namespace: "a",
path: new URL(args.path, `https://unpkg.com${args.resolveDir}/`).href,
};
});
//match main file in a module
build.onResolve({ filter: /.*/ }, async (args: esbuild.OnResolveArgs) => {
return {
namespace: "a",
path: `https://unpkg.com/${args.path}`,
};
});
},
};
};
// Define the version of esbuild-wasm to use
const ESBUILD_WASM_VERSION = "0.14.54";
function createEsbuilder() {
const paramsSchema = z.object({
rawCode: z.string(),
entryPoint: z.string()
});
const name = "esbuilder";
const description = "Compiles JavaScript, TypeScript, JSX, or TSX code within a chat interface using esbuild-wasm. Accepts raw code as input and sets the filename dynamically based on code type (i.e., 'index.js' for JavaScript, 'index.ts' for TypeScript, 'index.jsx' for JSX and 'index.tsx' for TSX). The compiler presents a compiled output, facilitating real-time code execution and analysis in a chatbot environment.";
const execute = async (params: z.infer<typeof paramsSchema>) => {
const { rawCode, entryPoint } = params;
try {
// Initialize esbuild-wasm if it hasn't been initialized
await esbuild.initialize({
worker: true,
wasmURL: `https://unpkg.com/esbuild-wasm@${ESBUILD_WASM_VERSION}/esbuild.wasm`
});
} catch (err) {
console.log(err);
}
try {
// Compile the code using esbuild-wasm
const result = await esbuild.build({
entryPoints: [entryPoint],
bundle: true,
write: false,
minify: true,
outdir: "/",
plugins: [unpkgPathPlugin(), unpkgFetchPlugin(rawCode, entryPoint)],
metafile: true,
allowOverwrite: true
});
return result.outputFiles[0].text;
} catch (error: unknown) {
if (error instanceof Error) {
return `Compilation failed: ${error.message}`;
}
return `Compilation failed with unknown error: ${error}`;
}
};
return new Tool<typeof paramsSchema, z.ZodType<any, any>>(paramsSchema, name, description, execute).tool;
}
export { createEsbuilder };