Compare commits

..

2 Commits

Author SHA1 Message Date
acd677bff5 Fix display bugs in the console. 2024-06-12 06:05:12 -04:00
7307a6c2ee Add E2B. 2024-06-11 10:48:34 -04:00
12 changed files with 453 additions and 407 deletions

View File

@ -0,0 +1,19 @@
# e2b template build --name "terminal"
# Use a Debian-based base image
FROM ubuntu:22.04
# Install dependencies and customize sandbox
RUN apt update \
&& apt install -y sudo
# Install xterm
RUN apt update \
&& apt install -y xterm
RUN apt update \
&& apt install -y tmux screen
# Clean up
RUN apt clean \
&& rm -rf /var/lib/apt/lists/*

View File

@ -0,0 +1,14 @@
# This is a config for E2B sandbox template.
# You can use 'template_id' (ne8xtb57tq5xw9vwhdyc) or 'template_name (terminal) from this config to spawn a sandbox:
# Python SDK
# from e2b import Sandbox
# sandbox = Sandbox(template='terminal')
# JS SDK
# import { Sandbox } from 'e2b'
# const sandbox = await Sandbox.create({ template: 'terminal' })
dockerfile = "e2b.Dockerfile"
template_name = "terminal"
template_id = "ne8xtb57tq5xw9vwhdyc"

View File

@ -110,17 +110,12 @@ export default {
const body = await request.json() const body = await request.json()
const { type, name, userId, visibility } = initSchema.parse(body) const { type, name, userId, visibility } = initSchema.parse(body)
const userSandboxes = await db const allSandboxes = await db.select().from(sandbox).all()
.select() if (allSandboxes.length >= 8) {
.from(sandbox) return new Response("You reached the maximum # of sandboxes.", {
.where(eq(sandbox.userId, userId)) status: 400,
.all(); })
}
if (userSandboxes.length >= 8) {
return new Response("You reached the maximum # of sandboxes.", {
status: 400,
});
}
const sb = await db const sb = await db
.insert(sandbox) .insert(sandbox)

View File

@ -31,8 +31,8 @@ export const sandbox = sqliteTable("sandbox", {
createdAt: integer("createdAt", { mode: "timestamp_ms" }), createdAt: integer("createdAt", { mode: "timestamp_ms" }),
userId: text("user_id") userId: text("user_id")
.notNull() .notNull()
.references(() => user.id, { onDelete: "cascade" }), .references(() => user.id),
}); });
export type Sandbox = typeof sandbox.$inferSelect; export type Sandbox = typeof sandbox.$inferSelect;

View File

@ -9,11 +9,12 @@
"version": "1.0.0", "version": "1.0.0",
"license": "ISC", "license": "ISC",
"dependencies": { "dependencies": {
"@e2b/code-interpreter": "^0.0.7",
"concurrently": "^8.2.2", "concurrently": "^8.2.2",
"cors": "^2.8.5", "cors": "^2.8.5",
"dotenv": "^16.4.5", "dotenv": "^16.4.5",
"e2b": "^0.16.1",
"express": "^4.19.2", "express": "^4.19.2",
"node-pty": "^1.0.0",
"rate-limiter-flexible": "^5.0.3", "rate-limiter-flexible": "^5.0.3",
"socket.io": "^4.7.5", "socket.io": "^4.7.5",
"zod": "^3.22.4" "zod": "^3.22.4"
@ -50,6 +51,39 @@
"node": ">=12" "node": ">=12"
} }
}, },
"node_modules/@e2b/code-interpreter": {
"version": "0.0.7",
"resolved": "https://registry.npmjs.org/@e2b/code-interpreter/-/code-interpreter-0.0.7.tgz",
"integrity": "sha512-e8nAY4zXU2b9nKthqq/pCPlTVD7f01dtzCtvabWmhlx7Wq+AUln14Q1Wf+uRVJXHkwS9BDv2CupdZpUChsjoCA==",
"dependencies": {
"e2b": "^0.16.1",
"isomorphic-ws": "^5.0.0",
"ws": "^8.15.1"
},
"engines": {
"node": ">=18"
}
},
"node_modules/@e2b/code-interpreter/node_modules/ws": {
"version": "8.17.0",
"resolved": "https://registry.npmjs.org/ws/-/ws-8.17.0.tgz",
"integrity": "sha512-uJq6108EgZMAl20KagGkzCKfMEjxmKvZHG7Tlq0Z6nOky7YF7aq4mOx6xK8TJ/i1LeK4Qus7INktacctDgY8Ow==",
"engines": {
"node": ">=10.0.0"
},
"peerDependencies": {
"bufferutil": "^4.0.1",
"utf-8-validate": ">=5.0.2"
},
"peerDependenciesMeta": {
"bufferutil": {
"optional": true
},
"utf-8-validate": {
"optional": true
}
}
},
"node_modules/@jridgewell/resolve-uri": { "node_modules/@jridgewell/resolve-uri": {
"version": "3.1.2", "version": "3.1.2",
"resolved": "https://registry.npmjs.org/@jridgewell/resolve-uri/-/resolve-uri-3.1.2.tgz", "resolved": "https://registry.npmjs.org/@jridgewell/resolve-uri/-/resolve-uri-3.1.2.tgz",
@ -1247,6 +1281,11 @@
"resolved": "https://registry.npmjs.org/ms/-/ms-2.0.0.tgz", "resolved": "https://registry.npmjs.org/ms/-/ms-2.0.0.tgz",
"integrity": "sha512-Tpp60P6IUJDTuOq/5Z8cdskzJujfwqfOTkrwIwj7IRISpnkJnT6SyJ4PCPnGMoFjC9ddhal5KVIYtAt97ix05A==" "integrity": "sha512-Tpp60P6IUJDTuOq/5Z8cdskzJujfwqfOTkrwIwj7IRISpnkJnT6SyJ4PCPnGMoFjC9ddhal5KVIYtAt97ix05A=="
}, },
"node_modules/nan": {
"version": "2.19.0",
"resolved": "https://registry.npmjs.org/nan/-/nan-2.19.0.tgz",
"integrity": "sha512-nO1xXxfh/RWNxfd/XPfbIfFk5vgLsAxUR9y5O0cHMJu/AW9U95JLXqthYHjEp+8gQ5p96K9jUp8nbVOxCdRbtw=="
},
"node_modules/negotiator": { "node_modules/negotiator": {
"version": "0.6.3", "version": "0.6.3",
"resolved": "https://registry.npmjs.org/negotiator/-/negotiator-0.6.3.tgz", "resolved": "https://registry.npmjs.org/negotiator/-/negotiator-0.6.3.tgz",
@ -1266,6 +1305,15 @@
"node-gyp-build-test": "build-test.js" "node-gyp-build-test": "build-test.js"
} }
}, },
"node_modules/node-pty": {
"version": "1.0.0",
"resolved": "https://registry.npmjs.org/node-pty/-/node-pty-1.0.0.tgz",
"integrity": "sha512-wtBMWWS7dFZm/VgqElrTvtfMq4GzJ6+edFI0Y0zyzygUSZMgZdraDUMUhCIvkjhJjme15qWmbyJbtAx4ot4uZA==",
"hasInstallScript": true,
"dependencies": {
"nan": "^2.17.0"
}
},
"node_modules/nodemon": { "node_modules/nodemon": {
"version": "3.1.0", "version": "3.1.0",
"resolved": "https://registry.npmjs.org/nodemon/-/nodemon-3.1.0.tgz", "resolved": "https://registry.npmjs.org/nodemon/-/nodemon-3.1.0.tgz",

View File

@ -11,11 +11,12 @@
"author": "", "author": "",
"license": "ISC", "license": "ISC",
"dependencies": { "dependencies": {
"@e2b/code-interpreter": "^0.0.7",
"concurrently": "^8.2.2", "concurrently": "^8.2.2",
"cors": "^2.8.5", "cors": "^2.8.5",
"dotenv": "^16.4.5", "dotenv": "^16.4.5",
"e2b": "^0.16.1",
"express": "^4.19.2", "express": "^4.19.2",
"node-pty": "^1.0.0",
"rate-limiter-flexible": "^5.0.3", "rate-limiter-flexible": "^5.0.3",
"socket.io": "^4.7.5", "socket.io": "^4.7.5",
"zod": "^3.22.4" "zod": "^3.22.4"

View File

@ -1,177 +0,0 @@
import * as dotenv from "dotenv";
import {
R2FileBody,
R2Files,
Sandbox,
TFile,
TFileData,
TFolder,
} from "./types";
dotenv.config();
export const getSandboxFiles = async (id: string) => {
const res = await fetch(
`${process.env.STORAGE_WORKER_URL}/api?sandboxId=${id}`,
{
headers: {
Authorization: `${process.env.WORKERS_KEY}`,
},
}
);
const data: R2Files = await res.json();
const paths = data.objects.map((obj) => obj.key);
const processedFiles = await processFiles(paths, id);
return processedFiles;
};
export const getFolder = async (folderId: string) => {
const res = await fetch(
`${process.env.STORAGE_WORKER_URL}/api?folderId=${folderId}`,
{
headers: {
Authorization: `${process.env.WORKERS_KEY}`,
},
}
);
const data: R2Files = await res.json();
return data.objects.map((obj) => obj.key);
};
const processFiles = async (paths: string[], id: string) => {
const root: TFolder = { id: "/", type: "folder", name: "/", children: [] };
const fileData: TFileData[] = [];
paths.forEach((path) => {
const allParts = path.split("/");
if (allParts[1] !== id) {
return;
}
const parts = allParts.slice(2);
let current: TFolder = root;
for (let i = 0; i < parts.length; i++) {
const part = parts[i];
const isFile = i === parts.length - 1 && part.includes(".");
const existing = current.children.find((child) => child.name === part);
if (existing) {
if (!isFile) {
current = existing as TFolder;
}
} else {
if (isFile) {
const file: TFile = { id: path, type: "file", name: part };
current.children.push(file);
fileData.push({ id: path, data: "" });
} else {
const folder: TFolder = {
// id: path, // todo: wrong id. for example, folder "src" ID is: projects/a7vgttfqbgy403ratp7du3ln/src/App.css
id: `projects/${id}/${parts.slice(0, i + 1).join("/")}`,
type: "folder",
name: part,
children: [],
};
current.children.push(folder);
current = folder;
}
}
}
});
await Promise.all(
fileData.map(async (file) => {
const data = await fetchFileContent(file.id);
file.data = data;
})
);
return {
files: root.children,
fileData,
};
};
const fetchFileContent = async (fileId: string): Promise<string> => {
try {
const fileRes = await fetch(
`${process.env.STORAGE_WORKER_URL}/api?fileId=${fileId}`,
{
headers: {
Authorization: `${process.env.WORKERS_KEY}`,
},
}
);
return await fileRes.text();
} catch (error) {
console.error("ERROR fetching file:", error);
return "";
}
};
export const createFile = async (fileId: string) => {
const res = await fetch(`${process.env.STORAGE_WORKER_URL}/api`, {
method: "POST",
headers: {
"Content-Type": "application/json",
Authorization: `${process.env.WORKERS_KEY}`,
},
body: JSON.stringify({ fileId }),
});
return res.ok;
};
export const renameFile = async (
fileId: string,
newFileId: string,
data: string
) => {
const res = await fetch(`${process.env.STORAGE_WORKER_URL}/api/rename`, {
method: "POST",
headers: {
"Content-Type": "application/json",
Authorization: `${process.env.WORKERS_KEY}`,
},
body: JSON.stringify({ fileId, newFileId, data }),
});
return res.ok;
};
export const saveFile = async (fileId: string, data: string) => {
const res = await fetch(`${process.env.STORAGE_WORKER_URL}/api/save`, {
method: "POST",
headers: {
"Content-Type": "application/json",
Authorization: `${process.env.WORKERS_KEY}`,
},
body: JSON.stringify({ fileId, data }),
});
return res.ok;
};
export const deleteFile = async (fileId: string) => {
const res = await fetch(`${process.env.STORAGE_WORKER_URL}/api`, {
method: "DELETE",
headers: {
"Content-Type": "application/json",
Authorization: `${process.env.WORKERS_KEY}`,
},
body: JSON.stringify({ fileId }),
});
return res.ok;
};
export const getProjectSize = async (id: string) => {
const res = await fetch(
`${process.env.STORAGE_WORKER_URL}/api/size?sandboxId=${id}`,
{
headers: {
Authorization: `${process.env.WORKERS_KEY}`,
},
}
);
return (await res.json()).size;
};

View File

@ -1,3 +1,4 @@
import fs from "fs";
import os from "os"; import os from "os";
import path from "path"; import path from "path";
import cors from "cors"; import cors from "cors";
@ -16,9 +17,8 @@ import {
getSandboxFiles, getSandboxFiles,
renameFile, renameFile,
saveFile, saveFile,
} from "./fileoperations"; } from "./utils";
import { LockManager } from "./utils"; import { Sandbox, Process, ProcessMessage } from "e2b";
import { Sandbox, Terminal, FilesystemManager } from "e2b";
import { import {
MAX_BODY_SIZE, MAX_BODY_SIZE,
createFileRL, createFileRL,
@ -43,17 +43,14 @@ const io = new Server(httpServer, {
let inactivityTimeout: NodeJS.Timeout | null = null; let inactivityTimeout: NodeJS.Timeout | null = null;
let isOwnerConnected = false; let isOwnerConnected = false;
const containers: Record<string, Sandbox> = {}; const terminals: {
const connections: Record<string, number> = {}; [id: string]: Process;
const terminals: Record<string, Terminal> = {}; } = {};
const containers: {
[id: string]: Sandbox;
} = {};
const dirName = "/home/user"; const dirName = path.join(__dirname, "..");
const moveFile = async (filesystem: FilesystemManager, filePath: string, newFilePath: string) => {
const fileContents = await filesystem.readBytes(filePath)
await filesystem.writeBytes(newFilePath, fileContents);
await filesystem.remove(filePath);
}
io.use(async (socket, next) => { io.use(async (socket, next) => {
const handshakeSchema = z.object({ const handshakeSchema = z.object({
@ -106,6 +103,30 @@ io.use(async (socket, next) => {
next(); next();
}); });
class LockManager {
private locks: { [key: string]: Promise<any> };
constructor() {
this.locks = {};
}
async acquireLock<T>(key: string, task: () => Promise<T>): Promise<T> {
if (!this.locks[key]) {
this.locks[key] = new Promise<T>(async (resolve, reject) => {
try {
const result = await task();
resolve(result);
} catch (error) {
reject(error);
} finally {
delete this.locks[key];
}
});
}
return await this.locks[key];
}
}
const lockManager = new LockManager(); const lockManager = new LockManager();
io.on("connection", async (socket) => { io.on("connection", async (socket) => {
@ -119,7 +140,6 @@ io.on("connection", async (socket) => {
if (data.isOwner) { if (data.isOwner) {
isOwnerConnected = true; isOwnerConnected = true;
connections[data.sandboxId] = (connections[data.sandboxId] ?? 0) + 1;
} else { } else {
if (!isOwnerConnected) { if (!isOwnerConnected) {
socket.emit("disableAccess", "The sandbox owner is not connected."); socket.emit("disableAccess", "The sandbox owner is not connected.");
@ -128,31 +148,23 @@ io.on("connection", async (socket) => {
} }
await lockManager.acquireLock(data.sandboxId, async () => { await lockManager.acquireLock(data.sandboxId, async () => {
try { if (!containers[data.sandboxId]) {
if (!containers[data.sandboxId]) { console.log("Creating container ", data.sandboxId);
containers[data.sandboxId] = await Sandbox.create(); containers[data.sandboxId] = await Sandbox.create({
console.log("Created container ", data.sandboxId); template: "terminal",
io.emit("previewURL", "https://" + containers[data.sandboxId].getHostname(5173)); });
} console.log("Created.");
} catch (error) {
console.error("Error creating container ", data.sandboxId, error);
} }
}); });
// Change the owner of the project directory to user
const fixPermissions = async () => {
await containers[data.sandboxId].process.startAndWait(
`sudo chown -R user "${path.join(dirName, "projects", data.sandboxId)}"`
);
}
const sandboxFiles = await getSandboxFiles(data.sandboxId); const sandboxFiles = await getSandboxFiles(data.sandboxId);
sandboxFiles.fileData.forEach(async (file) => { sandboxFiles.fileData.forEach((file) => {
const filePath = path.join(dirName, file.id); const filePath = path.join(dirName, file.id);
await containers[data.sandboxId].filesystem.makeDir(path.dirname(filePath)); fs.mkdirSync(path.dirname(filePath), { recursive: true });
await containers[data.sandboxId].filesystem.write(filePath, file.data); fs.writeFile(filePath, file.data, function (err) {
if (err) throw err;
});
}); });
fixPermissions();
socket.emit("loaded", sandboxFiles.files); socket.emit("loaded", sandboxFiles.files);
@ -185,8 +197,9 @@ io.on("connection", async (socket) => {
if (!file) return; if (!file) return;
file.data = body; file.data = body;
await containers[data.sandboxId].filesystem.write(path.join(dirName, file.id), body); fs.writeFile(path.join(dirName, file.id), body, function (err) {
fixPermissions(); if (err) throw err;
});
await saveFile(fileId, body); await saveFile(fileId, body);
} catch (e) { } catch (e) {
io.emit("rateLimit", "Rate limited: file saving. Please slow down."); io.emit("rateLimit", "Rate limited: file saving. Please slow down.");
@ -200,12 +213,13 @@ io.on("connection", async (socket) => {
const parts = fileId.split("/"); const parts = fileId.split("/");
const newFileId = folderId + "/" + parts.pop(); const newFileId = folderId + "/" + parts.pop();
await moveFile( fs.rename(
containers[data.sandboxId].filesystem,
path.join(dirName, fileId), path.join(dirName, fileId),
path.join(dirName, newFileId) path.join(dirName, newFileId),
) function (err) {
fixPermissions(); if (err) throw err;
}
);
file.id = newFileId; file.id = newFileId;
@ -231,8 +245,9 @@ io.on("connection", async (socket) => {
const id = `projects/${data.sandboxId}/${name}`; const id = `projects/${data.sandboxId}/${name}`;
await containers[data.sandboxId].filesystem.write(path.join(dirName, id), ""); fs.writeFile(path.join(dirName, id), "", function (err) {
fixPermissions(); if (err) throw err;
});
sandboxFiles.files.push({ sandboxFiles.files.push({
id, id,
@ -259,7 +274,9 @@ io.on("connection", async (socket) => {
const id = `projects/${data.sandboxId}/${name}`; const id = `projects/${data.sandboxId}/${name}`;
await containers[data.sandboxId].filesystem.makeDir(path.join(dirName, id)); fs.mkdir(path.join(dirName, id), { recursive: true }, function (err) {
if (err) throw err;
});
callback(); callback();
} catch (e) { } catch (e) {
@ -279,13 +296,13 @@ io.on("connection", async (socket) => {
const newFileId = const newFileId =
parts.slice(0, parts.length - 1).join("/") + "/" + newName; parts.slice(0, parts.length - 1).join("/") + "/" + newName;
fs.rename(
await moveFile(
containers[data.sandboxId].filesystem,
path.join(dirName, fileId), path.join(dirName, fileId),
path.join(dirName, newFileId) path.join(dirName, newFileId),
) function (err) {
fixPermissions(); if (err) throw err;
}
);
await renameFile(fileId, newFileId, file.data); await renameFile(fileId, newFileId, file.data);
} catch (e) { } catch (e) {
io.emit("rateLimit", "Rate limited: file renaming. Please slow down."); io.emit("rateLimit", "Rate limited: file renaming. Please slow down.");
@ -299,7 +316,9 @@ io.on("connection", async (socket) => {
const file = sandboxFiles.fileData.find((f) => f.id === fileId); const file = sandboxFiles.fileData.find((f) => f.id === fileId);
if (!file) return; if (!file) return;
await containers[data.sandboxId].filesystem.remove(path.join(dirName, fileId)); fs.unlink(path.join(dirName, fileId), function (err) {
if (err) throw err;
});
sandboxFiles.fileData = sandboxFiles.fileData.filter( sandboxFiles.fileData = sandboxFiles.fileData.filter(
(f) => f.id !== fileId (f) => f.id !== fileId
); );
@ -322,7 +341,9 @@ io.on("connection", async (socket) => {
await Promise.all( await Promise.all(
files.map(async (file) => { files.map(async (file) => {
await containers[data.sandboxId].filesystem.remove(path.join(dirName, file)); fs.unlink(path.join(dirName, file), function (err) {
if (err) throw err;
});
sandboxFiles.fileData = sandboxFiles.fileData.filter( sandboxFiles.fileData = sandboxFiles.fileData.filter(
(f) => f.id !== file (f) => f.id !== file
@ -337,35 +358,56 @@ io.on("connection", async (socket) => {
callback(newFiles.files); callback(newFiles.files);
}); });
function toBackslashNotation(input: string) {
return input
.replace(/\\/g, "\\\\") // Escape backslashes
.replace(/\n/g, "\\n") // Escape newlines
.replace(/\r/g, "\\r") // Escape carriage returns
.replace(/\t/g, "\\t") // Escape tabs
.replace(/"/g, '\\"') // Escape double quotes
.replace(/'/g, "\\'") // Escape single quotes
.replace(/\f/g, "\\f") // Escape form feeds
.replace(/\b/g, "\\b") // Escape backspaces
.replace(/\v/g, "\\v") // Escape vertical tabs
.replace(/\0/g, "\\0") // Escape null characters
.replace(/\a/g, "\\a") // Escape alert (bell)
.replace(/\e/g, "\\e"); // Escape escape
}
socket.on("createTerminal", async (id: string, callback) => { socket.on("createTerminal", async (id: string, callback) => {
if (terminals[id] || Object.keys(terminals).length >= 4) { if (terminals[id] || Object.keys(terminals).length >= 4) {
return; return;
} }
const onData = (data: ProcessMessage) => {
console.log("process", toBackslashNotation(data.toString()));
io.emit("terminalResponse", {
id,
data: data.toString() + "\r\n",
});
};
await lockManager.acquireLock(data.sandboxId, async () => { await lockManager.acquireLock(data.sandboxId, async () => {
try { console.log("Creating terminal", id);
terminals[id] = await containers[data.sandboxId].terminal.start({ terminals[id] = await containers[data.sandboxId].process.start({
onData: (data: string) => { cmd: 'TERM=xterm script -c "screen" /dev/null', // xterm vt100
io.emit("terminalResponse", { id, data }); onStdout: onData,
}, onStderr: onData,
size: { cols: 80, rows: 20 }, onExit: (code) => console.log("exit :(", code),
onExit: () => console.log("Terminal exited", id), });
}); await terminals[id].sendStdin("clear\r\n");
await terminals[id].sendData(`cd "${path.join(dirName, "projects", data.sandboxId)}"\r`) await terminals[id].sendStdin("export PS1='user> '\r\n");
await terminals[id].sendData("export PS1='user> '\rclear\r"); await terminals[id].sendStdin("clear\r\n");
console.log("Created terminal", id); console.log("Created terminal", id);
} catch (error) {
console.error("Error creating terminal ", id, error);
}
}); });
callback(); callback();
}); });
socket.on("resizeTerminal", (dimensions: { cols: number; rows: number }) => { socket.on("resizeTerminal", (dimensions: { cols: number; rows: number }) => {
Object.values(terminals).forEach((t) => { /*Object.values(terminals).forEach((t) => {
t.resize(dimensions); t.terminal.resize(dimensions.cols, dimensions.rows);
}); });*/
}); });
socket.on("terminalData", (id: string, data: string) => { socket.on("terminalData", (id: string, data: string) => {
@ -374,7 +416,8 @@ io.on("connection", async (socket) => {
} }
try { try {
terminals[id].sendData(data); console.log(`Writing ${toBackslashNotation(data)} to ${id}`);
terminals[id].sendStdin(data);
} catch (e) { } catch (e) {
console.log("Error writing to terminal", e); console.log("Error writing to terminal", e);
} }
@ -438,26 +481,18 @@ io.on("connection", async (socket) => {
socket.on("disconnect", async () => { socket.on("disconnect", async () => {
if (data.isOwner) { if (data.isOwner) {
connections[data.sandboxId]--; Object.entries(terminals).forEach((t) => {
} const terminal = t[1];
terminal.kill();
if (data.isOwner && connections[data.sandboxId] <= 0) { delete terminals[t[0]];
await Promise.all( });
Object.entries(terminals).map(async ([key, terminal]) => {
await terminal.kill();
delete terminals[key];
})
);
await lockManager.acquireLock(data.sandboxId, async () => { await lockManager.acquireLock(data.sandboxId, async () => {
try { if (containers[data.sandboxId]) {
if (containers[data.sandboxId]) { console.log("Closing container", data.sandboxId);
await containers[data.sandboxId].close(); await containers[data.sandboxId].close();
delete containers[data.sandboxId]; delete containers[data.sandboxId];
console.log("Closed container", data.sandboxId); console.log("Closed");
}
} catch (error) {
console.error("Error closing container ", data.sandboxId, error);
} }
}); });

View File

@ -1,23 +1,177 @@
export class LockManager { import * as dotenv from "dotenv";
private locks: { [key: string]: Promise<any> }; import {
R2FileBody,
R2Files,
Sandbox,
TFile,
TFileData,
TFolder,
} from "./types";
constructor() { dotenv.config();
this.locks = {};
}
async acquireLock<T>(key: string, task: () => Promise<T>): Promise<T> { export const getSandboxFiles = async (id: string) => {
if (!this.locks[key]) { const res = await fetch(
this.locks[key] = new Promise<T>(async (resolve, reject) => { `${process.env.STORAGE_WORKER_URL}/api?sandboxId=${id}`,
try { {
const result = await task(); headers: {
resolve(result); Authorization: `${process.env.WORKERS_KEY}`,
} catch (error) { },
reject(error);
} finally {
delete this.locks[key];
}
});
} }
return await this.locks[key]; );
const data: R2Files = await res.json();
const paths = data.objects.map((obj) => obj.key);
const processedFiles = await processFiles(paths, id);
return processedFiles;
};
export const getFolder = async (folderId: string) => {
const res = await fetch(
`${process.env.STORAGE_WORKER_URL}/api?folderId=${folderId}`,
{
headers: {
Authorization: `${process.env.WORKERS_KEY}`,
},
}
);
const data: R2Files = await res.json();
return data.objects.map((obj) => obj.key);
};
const processFiles = async (paths: string[], id: string) => {
const root: TFolder = { id: "/", type: "folder", name: "/", children: [] };
const fileData: TFileData[] = [];
paths.forEach((path) => {
const allParts = path.split("/");
if (allParts[1] !== id) {
return;
}
const parts = allParts.slice(2);
let current: TFolder = root;
for (let i = 0; i < parts.length; i++) {
const part = parts[i];
const isFile = i === parts.length - 1 && part.includes(".");
const existing = current.children.find((child) => child.name === part);
if (existing) {
if (!isFile) {
current = existing as TFolder;
}
} else {
if (isFile) {
const file: TFile = { id: path, type: "file", name: part };
current.children.push(file);
fileData.push({ id: path, data: "" });
} else {
const folder: TFolder = {
// id: path, // todo: wrong id. for example, folder "src" ID is: projects/a7vgttfqbgy403ratp7du3ln/src/App.css
id: `projects/${id}/${parts.slice(0, i + 1).join("/")}`,
type: "folder",
name: part,
children: [],
};
current.children.push(folder);
current = folder;
}
}
}
});
await Promise.all(
fileData.map(async (file) => {
const data = await fetchFileContent(file.id);
file.data = data;
})
);
return {
files: root.children,
fileData,
};
};
const fetchFileContent = async (fileId: string): Promise<string> => {
try {
const fileRes = await fetch(
`${process.env.STORAGE_WORKER_URL}/api?fileId=${fileId}`,
{
headers: {
Authorization: `${process.env.WORKERS_KEY}`,
},
}
);
return await fileRes.text();
} catch (error) {
console.error("ERROR fetching file:", error);
return "";
} }
} };
export const createFile = async (fileId: string) => {
const res = await fetch(`${process.env.STORAGE_WORKER_URL}/api`, {
method: "POST",
headers: {
"Content-Type": "application/json",
Authorization: `${process.env.WORKERS_KEY}`,
},
body: JSON.stringify({ fileId }),
});
return res.ok;
};
export const renameFile = async (
fileId: string,
newFileId: string,
data: string
) => {
const res = await fetch(`${process.env.STORAGE_WORKER_URL}/api/rename`, {
method: "POST",
headers: {
"Content-Type": "application/json",
Authorization: `${process.env.WORKERS_KEY}`,
},
body: JSON.stringify({ fileId, newFileId, data }),
});
return res.ok;
};
export const saveFile = async (fileId: string, data: string) => {
const res = await fetch(`${process.env.STORAGE_WORKER_URL}/api/save`, {
method: "POST",
headers: {
"Content-Type": "application/json",
Authorization: `${process.env.WORKERS_KEY}`,
},
body: JSON.stringify({ fileId, data }),
});
return res.ok;
};
export const deleteFile = async (fileId: string) => {
const res = await fetch(`${process.env.STORAGE_WORKER_URL}/api`, {
method: "DELETE",
headers: {
"Content-Type": "application/json",
Authorization: `${process.env.WORKERS_KEY}`,
},
body: JSON.stringify({ fileId }),
});
return res.ok;
};
export const getProjectSize = async (id: string) => {
const res = await fetch(
`${process.env.STORAGE_WORKER_URL}/api/size?sandboxId=${id}`,
{
headers: {
Authorization: `${process.env.WORKERS_KEY}`,
},
}
);
return (await res.json()).size;
};

View File

@ -1,9 +1,9 @@
"use client" "use client"
import { SetStateAction, useCallback, useEffect, useRef, useState } from "react" import { useEffect, useRef, useState } from "react"
import monaco from "monaco-editor" import monaco from "monaco-editor"
import Editor, { BeforeMount, OnMount } from "@monaco-editor/react" import Editor, { BeforeMount, OnMount } from "@monaco-editor/react"
import { Socket, io } from "socket.io-client" import { io } from "socket.io-client"
import { toast } from "sonner" import { toast } from "sonner"
import { useClerk } from "@clerk/nextjs" import { useClerk } from "@clerk/nextjs"
@ -23,7 +23,7 @@ import Tab from "../ui/tab"
import Sidebar from "./sidebar" import Sidebar from "./sidebar"
import GenerateInput from "./generate" import GenerateInput from "./generate"
import { Sandbox, User, TFile, TFolder, TTab } from "@/lib/types" import { Sandbox, User, TFile, TFolder, TTab } from "@/lib/types"
import { addNew, processFileType, validateName, debounce } from "@/lib/utils" import { addNew, processFileType, validateName } from "@/lib/utils"
import { Cursors } from "./live/cursors" import { Cursors } from "./live/cursors"
import { Terminal } from "@xterm/xterm" import { Terminal } from "@xterm/xterm"
import DisableAccessModal from "./live/disableModal" import DisableAccessModal from "./live/disableModal"
@ -41,16 +41,12 @@ export default function CodeEditor({
sandboxData: Sandbox sandboxData: Sandbox
reactDefinitionFile: string reactDefinitionFile: string
}) { }) {
const socketRef = useRef<Socket | null>(null); const socket = io(
`http://localhost:${process.env.NEXT_PUBLIC_SERVER_PORT}?userId=${userData.id}&sandboxId=${sandboxData.id}`,
// Initialize socket connection if it doesn't exist {
if (!socketRef.current) { timeout: 2000,
socketRef.current = io( }
`http://localhost:${process.env.NEXT_PUBLIC_SERVER_PORT}?userId=${userData.id}&sandboxId=${sandboxData.id}`, )
{
timeout: 2000,
}
);}
const [isPreviewCollapsed, setIsPreviewCollapsed] = useState(true) const [isPreviewCollapsed, setIsPreviewCollapsed] = useState(true)
const [disableAccess, setDisableAccess] = useState({ const [disableAccess, setDisableAccess] = useState({
@ -94,9 +90,6 @@ export default function CodeEditor({
}[] }[]
>([]) >([])
// Preview state
const [previewURL, setPreviewURL] = useState<string>("");
const isOwner = sandboxData.userId === userData.id const isOwner = sandboxData.userId === userData.id
const clerk = useClerk() const clerk = useClerk()
@ -297,33 +290,26 @@ export default function CodeEditor({
}, [decorations.options]) }, [decorations.options])
// Save file keybinding logic effect // Save file keybinding logic effect
const debouncedSaveData = useCallback(
debounce((value: string | undefined, activeFileId: string | undefined) => {
setTabs((prev) =>
prev.map((tab) =>
tab.id === activeFileId ? { ...tab, saved: true } : tab
)
);
console.log(`Saving file...${activeFileId}`);
console.log(`Saving file...${value}`);
socketRef.current?.emit("saveFile", activeFileId, value);
}, Number(process.env.FILE_SAVE_DEBOUNCE_DELAY)||1000),
[socketRef]
);
useEffect(() => { useEffect(() => {
const down = (e: KeyboardEvent) => { const down = (e: KeyboardEvent) => {
if (e.key === "s" && (e.metaKey || e.ctrlKey)) { if (e.key === "s" && (e.metaKey || e.ctrlKey)) {
e.preventDefault(); e.preventDefault()
debouncedSaveData(editorRef?.getValue(), activeFileId);
setTabs((prev) =>
prev.map((tab) =>
tab.id === activeFileId ? { ...tab, saved: true } : tab
)
)
socket.emit("saveFile", activeFileId, editorRef?.getValue())
} }
}; }
document.addEventListener("keydown", down); document.addEventListener("keydown", down)
return () => { return () => {
document.removeEventListener("keydown", down); document.removeEventListener("keydown", down)
}; }
}, [activeFileId, tabs, debouncedSaveData]); }, [tabs, activeFileId])
// Liveblocks live collaboration setup effect // Liveblocks live collaboration setup effect
useEffect(() => { useEffect(() => {
@ -372,10 +358,10 @@ export default function CodeEditor({
// Connection/disconnection effect // Connection/disconnection effect
useEffect(() => { useEffect(() => {
socketRef.current?.connect() socket.connect()
return () => { return () => {
socketRef.current?.disconnect() socket.disconnect()
} }
}, []) }, [])
@ -410,22 +396,20 @@ export default function CodeEditor({
}) })
} }
socketRef.current?.on("connect", onConnect) socket.on("connect", onConnect)
socketRef.current?.on("disconnect", onDisconnect) socket.on("disconnect", onDisconnect)
socketRef.current?.on("loaded", onLoadedEvent) socket.on("loaded", onLoadedEvent)
socketRef.current?.on("rateLimit", onRateLimit) socket.on("rateLimit", onRateLimit)
socketRef.current?.on("terminalResponse", onTerminalResponse) socket.on("terminalResponse", onTerminalResponse)
socketRef.current?.on("disableAccess", onDisableAccess) socket.on("disableAccess", onDisableAccess)
socketRef.current?.on("previewURL", setPreviewURL)
return () => { return () => {
socketRef.current?.off("connect", onConnect) socket.off("connect", onConnect)
socketRef.current?.off("disconnect", onDisconnect) socket.off("disconnect", onDisconnect)
socketRef.current?.off("loaded", onLoadedEvent) socket.off("loaded", onLoadedEvent)
socketRef.current?.off("rateLimit", onRateLimit) socket.off("rateLimit", onRateLimit)
socketRef.current?.off("terminalResponse", onTerminalResponse) socket.off("terminalResponse", onTerminalResponse)
socketRef.current?.off("disableAccess", onDisableAccess) socket.off("disableAccess", onDisableAccess)
socketRef.current?.off("previewURL", setPreviewURL)
} }
// }, []); // }, []);
}, [terminals]) }, [terminals])
@ -433,44 +417,31 @@ export default function CodeEditor({
// Helper functions for tabs: // Helper functions for tabs:
// Select file and load content // Select file and load content
const selectFile = (tab: TTab) => {
if (tab.id === activeFileId) return
// Initialize debounced function once setGenerate((prev) => {
const fileCache = useRef(new Map()); return {
...prev,
show: false,
}
})
const exists = tabs.find((t) => t.id === tab.id)
// Debounced function to get file content
const debouncedGetFile = useCallback(
debounce((tabId, callback) => {
socketRef.current?.emit('getFile', tabId, callback);
}, 300), // 300ms debounce delay, adjust as needed
[]
);
const selectFile = useCallback((tab: TTab) => {
if (tab.id === activeFileId) return;
setGenerate((prev) => ({ ...prev, show: false }));
const exists = tabs.find((t) => t.id === tab.id);
setTabs((prev) => { setTabs((prev) => {
if (exists) { if (exists) {
setActiveFileId(exists.id); setActiveFileId(exists.id)
return prev; return prev
} }
return [...prev, tab]; return [...prev, tab]
}); })
if (fileCache.current.has(tab.id)) { socket.emit("getFile", tab.id, (response: string) => {
setActiveFileContent(fileCache.current.get(tab.id)); setActiveFileContent(response)
} else { })
debouncedGetFile(tab.id, (response: SetStateAction<string>) => { setEditorLanguage(processFileType(tab.name))
fileCache.current.set(tab.id, response); setActiveFileId(tab.id)
setActiveFileContent(response); }
});
}
setEditorLanguage(processFileType(tab.name));
setActiveFileId(tab.id);
}, [activeFileId, tabs, debouncedGetFile]);
// Close tab and remove from tabs // Close tab and remove from tabs
const closeTab = (id: string) => { const closeTab = (id: string) => {
@ -544,7 +515,7 @@ export default function CodeEditor({
return false return false
} }
socketRef.current?.emit("renameFile", id, newName) socket.emit("renameFile", id, newName)
setTabs((prev) => setTabs((prev) =>
prev.map((tab) => (tab.id === id ? { ...tab, name: newName } : tab)) prev.map((tab) => (tab.id === id ? { ...tab, name: newName } : tab))
) )
@ -553,7 +524,7 @@ export default function CodeEditor({
} }
const handleDeleteFile = (file: TFile) => { const handleDeleteFile = (file: TFile) => {
socketRef.current?.emit("deleteFile", file.id, (response: (TFolder | TFile)[]) => { socket.emit("deleteFile", file.id, (response: (TFolder | TFile)[]) => {
setFiles(response) setFiles(response)
}) })
closeTab(file.id) closeTab(file.id)
@ -563,11 +534,11 @@ export default function CodeEditor({
setDeletingFolderId(folder.id) setDeletingFolderId(folder.id)
console.log("deleting folder", folder.id) console.log("deleting folder", folder.id)
socketRef.current?.emit("getFolder", folder.id, (response: string[]) => socket.emit("getFolder", folder.id, (response: string[]) =>
closeTabs(response) closeTabs(response)
) )
socketRef.current?.emit("deleteFolder", folder.id, (response: (TFolder | TFile)[]) => { socket.emit("deleteFolder", folder.id, (response: (TFolder | TFile)[]) => {
setFiles(response) setFiles(response)
setDeletingFolderId("") setDeletingFolderId("")
}) })
@ -594,7 +565,7 @@ export default function CodeEditor({
{generate.show && ai ? ( {generate.show && ai ? (
<GenerateInput <GenerateInput
user={userData} user={userData}
socket={socketRef.current} socket={socket}
width={generate.width - 90} width={generate.width - 90}
data={{ data={{
fileName: tabs.find((t) => t.id === activeFileId)?.name ?? "", fileName: tabs.find((t) => t.id === activeFileId)?.name ?? "",
@ -654,7 +625,7 @@ export default function CodeEditor({
handleRename={handleRename} handleRename={handleRename}
handleDeleteFile={handleDeleteFile} handleDeleteFile={handleDeleteFile}
handleDeleteFolder={handleDeleteFolder} handleDeleteFolder={handleDeleteFolder}
socket={socketRef.current} socket={socket}
setFiles={setFiles} setFiles={setFiles}
addNew={(name, type) => addNew(name, type, setFiles, sandboxData)} addNew={(name, type) => addNew(name, type, setFiles, sandboxData)}
deletingFolderId={deletingFolderId} deletingFolderId={deletingFolderId}
@ -774,7 +745,6 @@ export default function CodeEditor({
previewPanelRef.current?.expand() previewPanelRef.current?.expand()
setIsPreviewCollapsed(false) setIsPreviewCollapsed(false)
}} }}
src={previewURL}
/> />
</ResizablePanel> </ResizablePanel>
<ResizableHandle /> <ResizableHandle />
@ -787,7 +757,7 @@ export default function CodeEditor({
<Terminals <Terminals
terminals={terminals} terminals={terminals}
setTerminals={setTerminals} setTerminals={setTerminals}
socket={socketRef.current} socket={socket}
/> />
) : ( ) : (
<div className="w-full h-full flex items-center justify-center text-lg font-medium text-muted-foreground/50 select-none"> <div className="w-full h-full flex items-center justify-center text-lg font-medium text-muted-foreground/50 select-none">
@ -802,4 +772,3 @@ export default function CodeEditor({
</> </>
) )
} }

View File

@ -15,11 +15,9 @@ import { toast } from "sonner"
export default function PreviewWindow({ export default function PreviewWindow({
collapsed, collapsed,
open, open,
src
}: { }: {
collapsed: boolean collapsed: boolean
open: () => void open: () => void
src: string
}) { }) {
const ref = useRef<HTMLIFrameElement>(null) const ref = useRef<HTMLIFrameElement>(null)
const [iframeKey, setIframeKey] = useState(0) const [iframeKey, setIframeKey] = useState(0)
@ -47,7 +45,7 @@ export default function PreviewWindow({
<PreviewButton <PreviewButton
onClick={() => { onClick={() => {
navigator.clipboard.writeText(src) navigator.clipboard.writeText(`http://localhost:5173`)
toast.info("Copied preview link to clipboard") toast.info("Copied preview link to clipboard")
}} }}
> >
@ -75,7 +73,7 @@ export default function PreviewWindow({
ref={ref} ref={ref}
width={"100%"} width={"100%"}
height={"100%"} height={"100%"}
src={src} src={`http://localhost:5173`}
/> />
</div> </div>
)} )}

View File

@ -61,13 +61,3 @@ export function addNew(
]) ])
} }
} }
export function debounce<T extends (...args: any[]) => void>(func: T, wait: number): T {
let timeout: NodeJS.Timeout | null = null;
return function (...args: Parameters<T>) {
if (timeout) {
clearTimeout(timeout);
}
timeout = setTimeout(() => func(...args), wait);
} as T;
}