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
// This val dynamically imports and executes another HTTP val, then injects error handling scripts.
// It uses dynamic imports for flexibility, but this approach has security implications if used with untrusted input.
// The error handling script allows for capturing and reporting various types of errors.
// Added a success message postMessage after 3 seconds of page load.
// Prefixed error types to the errorString for better error identification.
// Checks for minimum response size and presence of <html> tag.
export default async function main(req: Request): Promise<Response> {
const url = new URL(req.url);
const valName = url.searchParams.get("val");
if (!valName) {
return new Response("Val name not provided", { status: 400 });
}
try {
// Dynamically import the specified val
const module = await import(`https://esm.town/v/${valName}`);
const valFunction = module.default;
if (typeof valFunction !== "function") {
throw new Error("Imported val is not a function");
}
// Execute the imported val function
const response = await valFunction(req);
const originalHtml = await response.text();
if (!originalHtml.trim() || originalHtml.length < 50 || !/<html/i.test(originalHtml)) {
return createErrorResponse("Val returned invalid or empty response");
}
// Inject error handling script into the original HTML
const modifiedHtml = injectErrorHandlingScript(originalHtml);
return new Response(modifiedHtml, {
headers: { "Content-Type": "text/html" },
});
} catch (error) {
return createErrorResponse(error instanceof Error ? error.message : String(error));
}
}
function injectErrorHandlingScript(html: string): string {
const script = `
<script>
window.onerror = function(message, source, lineno, colno, error) {
window.parent.postMessage({ messageType: "valBrowserRuntimeError", errorString: "window.onerror: " + message }, "*");
};
window.addEventListener('unhandledrejection', function(event) {
window.parent.postMessage({ messageType: "valBrowserRuntimeError", errorString: "unhandledrejection: " + event.reason }, "*");
});
console.error = function(...args) {
window.parent.postMessage({ messageType: "valBrowserRuntimeError", errorString: "console.error: " + args.join(' ') }, "*");
};
window.addEventListener('load', function() {
setTimeout(function() {
window.parent.postMessage({ messageType: "success" }, "*");
}, 3000);
});
</script>
`;
return script + html;
}
function createErrorResponse(errorString: string): Response {
const errorHtml = `
<html>
<head>
<script>
window.parent.postMessage({ messageType: "valCallError", errorString: ${JSON.stringify(errorString)} }, "*");
</script>
</head>
<body></body>
</html>
`;
return new Response(errorHtml, {
headers: { "Content-Type": "text/html" },
});
}