Skip to content
File

Blob: samples/repl-server/worker.js

javascript42 lines
1// Copyright (c) 2017-2023 Cloudflare, Inc.
2// Licensed under the Apache 2.0 license found in the LICENSE file or at:
3// https://opensource.org/licenses/Apache-2.0
4 
5import { default as UnsafeEval } from "workerd:unsafe-eval";
6import { default as util } from "node:util";
7 
8// https://stackoverflow.com/questions/67322922/context-preserving-eval
9var __EVAL = s => UnsafeEval.eval(`void (__EVAL = ${__EVAL.toString()}); ${s}`);
10 
11async function evaluate(expr) {
12 try {
13 const result = await __EVAL(expr);
14 return result;
15 } catch (err) {
16 return err;
17 }
18}
19 
20globalThis.consoleLogBuf = "";
21 
22export default {
23 async fetch(req, env) {
24 const {cmd} = await req.json();
25 
26 globalThis.env = env;
27 
28 globalThis.console.log = (...args) => {
29 const line = args.map(a => util.inspect(a, {colors: true})).join(" ");
30 consoleLogBuf += line + "\n";
31 };
32 
33 const res = await evaluate(cmd);
34 
35 const response = consoleLogBuf + util.inspect(res, {colors: true});
36 
37 globalThis.consoleLogBuf = "";
38 
39 return new Response(response);
40 }
41};