Compare commits
15 Commits
e2b-test
...
fix-editor
Author | SHA1 | Date | |
---|---|---|---|
7dd67f72d8 | |||
5bf264b807 | |||
6f6926a621 | |||
c262fb2a31 | |||
ed709210e3 | |||
97c8598717 | |||
9ec59bc781 | |||
687416e6e9 | |||
006c5cea66 | |||
869ae6c148 | |||
7353e88567 | |||
a0fb905a04 | |||
0df074924f | |||
e5b320d1c5 | |||
b561f1e962 |
@ -1,19 +0,0 @@
|
|||||||
# 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/*
|
|
@ -1,14 +0,0 @@
|
|||||||
# 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"
|
|
@ -110,8 +110,13 @@ 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 allSandboxes = await db.select().from(sandbox).all()
|
const userSandboxes = await db
|
||||||
if (allSandboxes.length >= 8) {
|
.select()
|
||||||
|
.from(sandbox)
|
||||||
|
.where(eq(sandbox.userId, userId))
|
||||||
|
.all()
|
||||||
|
|
||||||
|
if (userSandboxes.length >= 8) {
|
||||||
return new Response("You reached the maximum # of sandboxes.", {
|
return new Response("You reached the maximum # of sandboxes.", {
|
||||||
status: 400,
|
status: 400,
|
||||||
})
|
})
|
||||||
|
50
backend/server/package-lock.json
generated
50
backend/server/package-lock.json
generated
@ -9,12 +9,11 @@
|
|||||||
"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"
|
||||||
@ -51,39 +50,6 @@
|
|||||||
"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",
|
||||||
@ -1281,11 +1247,6 @@
|
|||||||
"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",
|
||||||
@ -1305,15 +1266,6 @@
|
|||||||
"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",
|
||||||
|
@ -11,12 +11,11 @@
|
|||||||
"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"
|
||||||
|
177
backend/server/src/fileoperations.ts
Normal file
177
backend/server/src/fileoperations.ts
Normal file
@ -0,0 +1,177 @@
|
|||||||
|
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;
|
||||||
|
};
|
@ -1,4 +1,3 @@
|
|||||||
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";
|
||||||
@ -17,8 +16,9 @@ import {
|
|||||||
getSandboxFiles,
|
getSandboxFiles,
|
||||||
renameFile,
|
renameFile,
|
||||||
saveFile,
|
saveFile,
|
||||||
} from "./utils";
|
} from "./fileoperations";
|
||||||
import { Sandbox, Process, ProcessMessage } from "e2b";
|
import { LockManager } from "./utils";
|
||||||
|
import { Sandbox, Terminal, FilesystemManager } from "e2b";
|
||||||
import {
|
import {
|
||||||
MAX_BODY_SIZE,
|
MAX_BODY_SIZE,
|
||||||
createFileRL,
|
createFileRL,
|
||||||
@ -43,14 +43,21 @@ const io = new Server(httpServer, {
|
|||||||
let inactivityTimeout: NodeJS.Timeout | null = null;
|
let inactivityTimeout: NodeJS.Timeout | null = null;
|
||||||
let isOwnerConnected = false;
|
let isOwnerConnected = false;
|
||||||
|
|
||||||
const terminals: {
|
const containers: Record<string, Sandbox> = {};
|
||||||
[id: string]: Process;
|
const connections: Record<string, number> = {};
|
||||||
} = {};
|
const terminals: Record<string, Terminal> = {};
|
||||||
const containers: {
|
|
||||||
[id: string]: Sandbox;
|
|
||||||
} = {};
|
|
||||||
|
|
||||||
const dirName = path.join(__dirname, "..");
|
const dirName = "/home/user";
|
||||||
|
|
||||||
|
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({
|
||||||
@ -103,422 +110,490 @@ 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) => {
|
||||||
if (inactivityTimeout) clearTimeout(inactivityTimeout);
|
try {
|
||||||
|
if (inactivityTimeout) clearTimeout(inactivityTimeout);
|
||||||
|
|
||||||
const data = socket.data as {
|
const data = socket.data as {
|
||||||
userId: string;
|
userId: string;
|
||||||
sandboxId: string;
|
sandboxId: string;
|
||||||
isOwner: boolean;
|
isOwner: boolean;
|
||||||
};
|
|
||||||
|
|
||||||
if (data.isOwner) {
|
|
||||||
isOwnerConnected = true;
|
|
||||||
} else {
|
|
||||||
if (!isOwnerConnected) {
|
|
||||||
socket.emit("disableAccess", "The sandbox owner is not connected.");
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
await lockManager.acquireLock(data.sandboxId, async () => {
|
|
||||||
if (!containers[data.sandboxId]) {
|
|
||||||
console.log("Creating container ", data.sandboxId);
|
|
||||||
containers[data.sandboxId] = await Sandbox.create({
|
|
||||||
template: "terminal",
|
|
||||||
});
|
|
||||||
console.log("Created.");
|
|
||||||
}
|
|
||||||
});
|
|
||||||
|
|
||||||
const sandboxFiles = await getSandboxFiles(data.sandboxId);
|
|
||||||
sandboxFiles.fileData.forEach((file) => {
|
|
||||||
const filePath = path.join(dirName, file.id);
|
|
||||||
fs.mkdirSync(path.dirname(filePath), { recursive: true });
|
|
||||||
fs.writeFile(filePath, file.data, function (err) {
|
|
||||||
if (err) throw err;
|
|
||||||
});
|
|
||||||
});
|
|
||||||
|
|
||||||
socket.emit("loaded", sandboxFiles.files);
|
|
||||||
|
|
||||||
socket.on("getFile", (fileId: string, callback) => {
|
|
||||||
const file = sandboxFiles.fileData.find((f) => f.id === fileId);
|
|
||||||
if (!file) return;
|
|
||||||
|
|
||||||
callback(file.data);
|
|
||||||
});
|
|
||||||
|
|
||||||
socket.on("getFolder", async (folderId: string, callback) => {
|
|
||||||
const files = await getFolder(folderId);
|
|
||||||
callback(files);
|
|
||||||
});
|
|
||||||
|
|
||||||
// todo: send diffs + debounce for efficiency
|
|
||||||
socket.on("saveFile", async (fileId: string, body: string) => {
|
|
||||||
try {
|
|
||||||
await saveFileRL.consume(data.userId, 1);
|
|
||||||
|
|
||||||
if (Buffer.byteLength(body, "utf-8") > MAX_BODY_SIZE) {
|
|
||||||
socket.emit(
|
|
||||||
"rateLimit",
|
|
||||||
"Rate limited: file size too large. Please reduce the file size."
|
|
||||||
);
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
|
|
||||||
const file = sandboxFiles.fileData.find((f) => f.id === fileId);
|
|
||||||
if (!file) return;
|
|
||||||
file.data = body;
|
|
||||||
|
|
||||||
fs.writeFile(path.join(dirName, file.id), body, function (err) {
|
|
||||||
if (err) throw err;
|
|
||||||
});
|
|
||||||
await saveFile(fileId, body);
|
|
||||||
} catch (e) {
|
|
||||||
io.emit("rateLimit", "Rate limited: file saving. Please slow down.");
|
|
||||||
}
|
|
||||||
});
|
|
||||||
|
|
||||||
socket.on("moveFile", async (fileId: string, folderId: string, callback) => {
|
|
||||||
const file = sandboxFiles.fileData.find((f) => f.id === fileId);
|
|
||||||
if (!file) return;
|
|
||||||
|
|
||||||
const parts = fileId.split("/");
|
|
||||||
const newFileId = folderId + "/" + parts.pop();
|
|
||||||
|
|
||||||
fs.rename(
|
|
||||||
path.join(dirName, fileId),
|
|
||||||
path.join(dirName, newFileId),
|
|
||||||
function (err) {
|
|
||||||
if (err) throw err;
|
|
||||||
}
|
|
||||||
);
|
|
||||||
|
|
||||||
file.id = newFileId;
|
|
||||||
|
|
||||||
await renameFile(fileId, newFileId, file.data);
|
|
||||||
const newFiles = await getSandboxFiles(data.sandboxId);
|
|
||||||
|
|
||||||
callback(newFiles.files);
|
|
||||||
});
|
|
||||||
|
|
||||||
socket.on("createFile", async (name: string, callback) => {
|
|
||||||
try {
|
|
||||||
const size: number = await getProjectSize(data.sandboxId);
|
|
||||||
// limit is 200mb
|
|
||||||
if (size > 200 * 1024 * 1024) {
|
|
||||||
io.emit(
|
|
||||||
"rateLimit",
|
|
||||||
"Rate limited: project size exceeded. Please delete some files."
|
|
||||||
);
|
|
||||||
callback({ success: false });
|
|
||||||
}
|
|
||||||
|
|
||||||
await createFileRL.consume(data.userId, 1);
|
|
||||||
|
|
||||||
const id = `projects/${data.sandboxId}/${name}`;
|
|
||||||
|
|
||||||
fs.writeFile(path.join(dirName, id), "", function (err) {
|
|
||||||
if (err) throw err;
|
|
||||||
});
|
|
||||||
|
|
||||||
sandboxFiles.files.push({
|
|
||||||
id,
|
|
||||||
name,
|
|
||||||
type: "file",
|
|
||||||
});
|
|
||||||
|
|
||||||
sandboxFiles.fileData.push({
|
|
||||||
id,
|
|
||||||
data: "",
|
|
||||||
});
|
|
||||||
|
|
||||||
await createFile(id);
|
|
||||||
|
|
||||||
callback({ success: true });
|
|
||||||
} catch (e) {
|
|
||||||
io.emit("rateLimit", "Rate limited: file creation. Please slow down.");
|
|
||||||
}
|
|
||||||
});
|
|
||||||
|
|
||||||
socket.on("createFolder", async (name: string, callback) => {
|
|
||||||
try {
|
|
||||||
await createFolderRL.consume(data.userId, 1);
|
|
||||||
|
|
||||||
const id = `projects/${data.sandboxId}/${name}`;
|
|
||||||
|
|
||||||
fs.mkdir(path.join(dirName, id), { recursive: true }, function (err) {
|
|
||||||
if (err) throw err;
|
|
||||||
});
|
|
||||||
|
|
||||||
callback();
|
|
||||||
} catch (e) {
|
|
||||||
io.emit("rateLimit", "Rate limited: folder creation. Please slow down.");
|
|
||||||
}
|
|
||||||
});
|
|
||||||
|
|
||||||
socket.on("renameFile", async (fileId: string, newName: string) => {
|
|
||||||
try {
|
|
||||||
await renameFileRL.consume(data.userId, 1);
|
|
||||||
|
|
||||||
const file = sandboxFiles.fileData.find((f) => f.id === fileId);
|
|
||||||
if (!file) return;
|
|
||||||
file.id = newName;
|
|
||||||
|
|
||||||
const parts = fileId.split("/");
|
|
||||||
const newFileId =
|
|
||||||
parts.slice(0, parts.length - 1).join("/") + "/" + newName;
|
|
||||||
|
|
||||||
fs.rename(
|
|
||||||
path.join(dirName, fileId),
|
|
||||||
path.join(dirName, newFileId),
|
|
||||||
function (err) {
|
|
||||||
if (err) throw err;
|
|
||||||
}
|
|
||||||
);
|
|
||||||
await renameFile(fileId, newFileId, file.data);
|
|
||||||
} catch (e) {
|
|
||||||
io.emit("rateLimit", "Rate limited: file renaming. Please slow down.");
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
});
|
|
||||||
|
|
||||||
socket.on("deleteFile", async (fileId: string, callback) => {
|
|
||||||
try {
|
|
||||||
await deleteFileRL.consume(data.userId, 1);
|
|
||||||
const file = sandboxFiles.fileData.find((f) => f.id === fileId);
|
|
||||||
if (!file) return;
|
|
||||||
|
|
||||||
fs.unlink(path.join(dirName, fileId), function (err) {
|
|
||||||
if (err) throw err;
|
|
||||||
});
|
|
||||||
sandboxFiles.fileData = sandboxFiles.fileData.filter(
|
|
||||||
(f) => f.id !== fileId
|
|
||||||
);
|
|
||||||
|
|
||||||
await deleteFile(fileId);
|
|
||||||
|
|
||||||
const newFiles = await getSandboxFiles(data.sandboxId);
|
|
||||||
callback(newFiles.files);
|
|
||||||
} catch (e) {
|
|
||||||
io.emit("rateLimit", "Rate limited: file deletion. Please slow down.");
|
|
||||||
}
|
|
||||||
});
|
|
||||||
|
|
||||||
// todo
|
|
||||||
// socket.on("renameFolder", async (folderId: string, newName: string) => {
|
|
||||||
// });
|
|
||||||
|
|
||||||
socket.on("deleteFolder", async (folderId: string, callback) => {
|
|
||||||
const files = await getFolder(folderId);
|
|
||||||
|
|
||||||
await Promise.all(
|
|
||||||
files.map(async (file) => {
|
|
||||||
fs.unlink(path.join(dirName, file), function (err) {
|
|
||||||
if (err) throw err;
|
|
||||||
});
|
|
||||||
|
|
||||||
sandboxFiles.fileData = sandboxFiles.fileData.filter(
|
|
||||||
(f) => f.id !== file
|
|
||||||
);
|
|
||||||
|
|
||||||
await deleteFile(file);
|
|
||||||
})
|
|
||||||
);
|
|
||||||
|
|
||||||
const newFiles = await getSandboxFiles(data.sandboxId);
|
|
||||||
|
|
||||||
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) => {
|
|
||||||
if (terminals[id] || Object.keys(terminals).length >= 4) {
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
|
|
||||||
const onData = (data: ProcessMessage) => {
|
|
||||||
console.log("process", toBackslashNotation(data.toString()));
|
|
||||||
io.emit("terminalResponse", {
|
|
||||||
id,
|
|
||||||
data: data.toString() + "\r\n",
|
|
||||||
});
|
|
||||||
};
|
};
|
||||||
|
|
||||||
|
if (data.isOwner) {
|
||||||
|
isOwnerConnected = true;
|
||||||
|
connections[data.sandboxId] = (connections[data.sandboxId] ?? 0) + 1;
|
||||||
|
} else {
|
||||||
|
if (!isOwnerConnected) {
|
||||||
|
socket.emit("disableAccess", "The sandbox owner is not connected.");
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
await lockManager.acquireLock(data.sandboxId, async () => {
|
await lockManager.acquireLock(data.sandboxId, async () => {
|
||||||
console.log("Creating terminal", id);
|
try {
|
||||||
terminals[id] = await containers[data.sandboxId].process.start({
|
if (!containers[data.sandboxId]) {
|
||||||
cmd: 'TERM=xterm script -c "screen" /dev/null', // xterm vt100
|
containers[data.sandboxId] = await Sandbox.create();
|
||||||
onStdout: onData,
|
console.log("Created container ", data.sandboxId);
|
||||||
onStderr: onData,
|
io.emit(
|
||||||
onExit: (code) => console.log("exit :(", code),
|
"previewURL",
|
||||||
});
|
"https://" + containers[data.sandboxId].getHostname(5173)
|
||||||
await terminals[id].sendStdin("clear\r\n");
|
);
|
||||||
await terminals[id].sendStdin("export PS1='user> '\r\n");
|
}
|
||||||
await terminals[id].sendStdin("clear\r\n");
|
} catch (e: any) {
|
||||||
console.log("Created terminal", id);
|
console.error(`Error creating container ${data.sandboxId}:`, e);
|
||||||
|
io.emit("error", `Error: container creation. ${e.message ?? e}`);
|
||||||
|
}
|
||||||
});
|
});
|
||||||
|
|
||||||
callback();
|
// Change the owner of the project directory to user
|
||||||
});
|
const fixPermissions = async () => {
|
||||||
|
await containers[data.sandboxId].process.startAndWait(
|
||||||
socket.on("resizeTerminal", (dimensions: { cols: number; rows: number }) => {
|
`sudo chown -R user "${path.join(dirName, "projects", data.sandboxId)}"`
|
||||||
/*Object.values(terminals).forEach((t) => {
|
|
||||||
t.terminal.resize(dimensions.cols, dimensions.rows);
|
|
||||||
});*/
|
|
||||||
});
|
|
||||||
|
|
||||||
socket.on("terminalData", (id: string, data: string) => {
|
|
||||||
if (!terminals[id]) {
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
|
|
||||||
try {
|
|
||||||
console.log(`Writing ${toBackslashNotation(data)} to ${id}`);
|
|
||||||
terminals[id].sendStdin(data);
|
|
||||||
} catch (e) {
|
|
||||||
console.log("Error writing to terminal", e);
|
|
||||||
}
|
|
||||||
});
|
|
||||||
|
|
||||||
socket.on("closeTerminal", async (id: string, callback) => {
|
|
||||||
if (!terminals[id]) {
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
|
|
||||||
await terminals[id].kill();
|
|
||||||
delete terminals[id];
|
|
||||||
|
|
||||||
callback();
|
|
||||||
});
|
|
||||||
|
|
||||||
socket.on(
|
|
||||||
"generateCode",
|
|
||||||
async (
|
|
||||||
fileName: string,
|
|
||||||
code: string,
|
|
||||||
line: number,
|
|
||||||
instructions: string,
|
|
||||||
callback
|
|
||||||
) => {
|
|
||||||
const fetchPromise = fetch(
|
|
||||||
`${process.env.DATABASE_WORKER_URL}/api/sandbox/generate`,
|
|
||||||
{
|
|
||||||
method: "POST",
|
|
||||||
headers: {
|
|
||||||
"Content-Type": "application/json",
|
|
||||||
Authorization: `${process.env.WORKERS_KEY}`,
|
|
||||||
},
|
|
||||||
body: JSON.stringify({
|
|
||||||
userId: data.userId,
|
|
||||||
}),
|
|
||||||
}
|
|
||||||
);
|
);
|
||||||
|
};
|
||||||
|
|
||||||
// Generate code from cloudflare workers AI
|
const sandboxFiles = await getSandboxFiles(data.sandboxId);
|
||||||
const generateCodePromise = fetch(
|
sandboxFiles.fileData.forEach(async (file) => {
|
||||||
`${process.env.AI_WORKER_URL}/api?fileName=${fileName}&code=${code}&line=${line}&instructions=${instructions}`,
|
const filePath = path.join(dirName, file.id);
|
||||||
{
|
await containers[data.sandboxId].filesystem.makeDir(
|
||||||
headers: {
|
path.dirname(filePath)
|
||||||
"Content-Type": "application/json",
|
|
||||||
Authorization: `${process.env.CF_AI_KEY}`,
|
|
||||||
},
|
|
||||||
}
|
|
||||||
);
|
);
|
||||||
|
await containers[data.sandboxId].filesystem.write(filePath, file.data);
|
||||||
|
});
|
||||||
|
fixPermissions();
|
||||||
|
|
||||||
const [fetchResponse, generateCodeResponse] = await Promise.all([
|
socket.emit("loaded", sandboxFiles.files);
|
||||||
fetchPromise,
|
|
||||||
generateCodePromise,
|
|
||||||
]);
|
|
||||||
|
|
||||||
const json = await generateCodeResponse.json();
|
socket.on("getFile", (fileId: string, callback) => {
|
||||||
|
console.log(fileId);
|
||||||
|
try {
|
||||||
|
const file = sandboxFiles.fileData.find((f) => f.id === fileId);
|
||||||
|
if (!file) return;
|
||||||
|
|
||||||
callback({ response: json.response, success: true });
|
callback(file.data);
|
||||||
}
|
} catch (e: any) {
|
||||||
);
|
console.error("Error getting file:", e);
|
||||||
|
io.emit("error", `Error: get file. ${e.message ?? e}`);
|
||||||
|
}
|
||||||
|
});
|
||||||
|
|
||||||
socket.on("disconnect", async () => {
|
socket.on("getFolder", async (folderId: string, callback) => {
|
||||||
if (data.isOwner) {
|
try {
|
||||||
Object.entries(terminals).forEach((t) => {
|
const files = await getFolder(folderId);
|
||||||
const terminal = t[1];
|
callback(files);
|
||||||
terminal.kill();
|
} catch (e: any) {
|
||||||
delete terminals[t[0]];
|
console.error("Error getting folder:", e);
|
||||||
});
|
io.emit("error", `Error: get folder. ${e.message ?? e}`);
|
||||||
|
}
|
||||||
|
});
|
||||||
|
|
||||||
await lockManager.acquireLock(data.sandboxId, async () => {
|
// todo: send diffs + debounce for efficiency
|
||||||
if (containers[data.sandboxId]) {
|
socket.on("saveFile", async (fileId: string, body: string) => {
|
||||||
console.log("Closing container", data.sandboxId);
|
try {
|
||||||
await containers[data.sandboxId].close();
|
if (Buffer.byteLength(body, "utf-8") > MAX_BODY_SIZE) {
|
||||||
delete containers[data.sandboxId];
|
socket.emit(
|
||||||
console.log("Closed");
|
"error",
|
||||||
|
"Error: file size too large. Please reduce the file size."
|
||||||
|
);
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
try {
|
||||||
|
await saveFileRL.consume(data.userId, 1);
|
||||||
|
await saveFile(fileId, body);
|
||||||
|
} catch (e) {
|
||||||
|
io.emit("error", "Rate limited: file saving. Please slow down.");
|
||||||
|
return;
|
||||||
}
|
}
|
||||||
});
|
|
||||||
|
|
||||||
socket.broadcast.emit(
|
const file = sandboxFiles.fileData.find((f) => f.id === fileId);
|
||||||
"disableAccess",
|
if (!file) return;
|
||||||
"The sandbox owner has disconnected."
|
file.data = body;
|
||||||
);
|
|
||||||
}
|
|
||||||
|
|
||||||
// const sockets = await io.fetchSockets();
|
await containers[data.sandboxId].filesystem.write(
|
||||||
// if (inactivityTimeout) {
|
path.join(dirName, file.id),
|
||||||
// clearTimeout(inactivityTimeout);
|
body
|
||||||
// }
|
);
|
||||||
// if (sockets.length === 0) {
|
fixPermissions();
|
||||||
// console.log("STARTING TIMER");
|
} catch (e: any) {
|
||||||
// inactivityTimeout = setTimeout(() => {
|
console.error("Error saving file:", e);
|
||||||
// io.fetchSockets().then(async (sockets) => {
|
io.emit("error", `Error: file saving. ${e.message ?? e}`);
|
||||||
// if (sockets.length === 0) {
|
}
|
||||||
// console.log("Server stopped", res);
|
});
|
||||||
// }
|
|
||||||
// });
|
socket.on(
|
||||||
// }, 20000);
|
"moveFile",
|
||||||
// } else {
|
async (fileId: string, folderId: string, callback) => {
|
||||||
// console.log("number of sockets", sockets.length);
|
try {
|
||||||
// }
|
const file = sandboxFiles.fileData.find((f) => f.id === fileId);
|
||||||
});
|
if (!file) return;
|
||||||
|
|
||||||
|
const parts = fileId.split("/");
|
||||||
|
const newFileId = folderId + "/" + parts.pop();
|
||||||
|
|
||||||
|
await moveFile(
|
||||||
|
containers[data.sandboxId].filesystem,
|
||||||
|
path.join(dirName, fileId),
|
||||||
|
path.join(dirName, newFileId)
|
||||||
|
);
|
||||||
|
fixPermissions();
|
||||||
|
|
||||||
|
file.id = newFileId;
|
||||||
|
|
||||||
|
await renameFile(fileId, newFileId, file.data);
|
||||||
|
const newFiles = await getSandboxFiles(data.sandboxId);
|
||||||
|
callback(newFiles.files);
|
||||||
|
} catch (e: any) {
|
||||||
|
console.error("Error moving file:", e);
|
||||||
|
io.emit("error", `Error: file moving. ${e.message ?? e}`);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
);
|
||||||
|
|
||||||
|
socket.on("createFile", async (name: string, callback) => {
|
||||||
|
try {
|
||||||
|
const size: number = await getProjectSize(data.sandboxId);
|
||||||
|
// limit is 200mb
|
||||||
|
if (size > 200 * 1024 * 1024) {
|
||||||
|
io.emit(
|
||||||
|
"error",
|
||||||
|
"Rate limited: project size exceeded. Please delete some files."
|
||||||
|
);
|
||||||
|
callback({ success: false });
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
try {
|
||||||
|
await createFileRL.consume(data.userId, 1);
|
||||||
|
} catch (e) {
|
||||||
|
io.emit("error", "Rate limited: file creation. Please slow down.");
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
const id = `projects/${data.sandboxId}/${name}`;
|
||||||
|
|
||||||
|
await containers[data.sandboxId].filesystem.write(
|
||||||
|
path.join(dirName, id),
|
||||||
|
""
|
||||||
|
);
|
||||||
|
fixPermissions();
|
||||||
|
|
||||||
|
sandboxFiles.files.push({
|
||||||
|
id,
|
||||||
|
name,
|
||||||
|
type: "file",
|
||||||
|
});
|
||||||
|
|
||||||
|
sandboxFiles.fileData.push({
|
||||||
|
id,
|
||||||
|
data: "",
|
||||||
|
});
|
||||||
|
|
||||||
|
await createFile(id);
|
||||||
|
|
||||||
|
callback({ success: true });
|
||||||
|
} catch (e: any) {
|
||||||
|
console.error("Error creating file:", e);
|
||||||
|
io.emit("error", `Error: file creation. ${e.message ?? e}`);
|
||||||
|
}
|
||||||
|
});
|
||||||
|
|
||||||
|
socket.on("createFolder", async (name: string, callback) => {
|
||||||
|
try {
|
||||||
|
try {
|
||||||
|
await createFolderRL.consume(data.userId, 1);
|
||||||
|
} catch (e) {
|
||||||
|
io.emit("error", "Rate limited: folder creation. Please slow down.");
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
const id = `projects/${data.sandboxId}/${name}`;
|
||||||
|
|
||||||
|
await containers[data.sandboxId].filesystem.makeDir(
|
||||||
|
path.join(dirName, id)
|
||||||
|
);
|
||||||
|
|
||||||
|
callback();
|
||||||
|
} catch (e: any) {
|
||||||
|
console.error("Error creating folder:", e);
|
||||||
|
io.emit("error", `Error: folder creation. ${e.message ?? e}`);
|
||||||
|
}
|
||||||
|
});
|
||||||
|
|
||||||
|
socket.on("renameFile", async (fileId: string, newName: string) => {
|
||||||
|
try {
|
||||||
|
try {
|
||||||
|
await renameFileRL.consume(data.userId, 1);
|
||||||
|
} catch (e) {
|
||||||
|
io.emit("error", "Rate limited: file renaming. Please slow down.");
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
const file = sandboxFiles.fileData.find((f) => f.id === fileId);
|
||||||
|
if (!file) return;
|
||||||
|
file.id = newName;
|
||||||
|
|
||||||
|
const parts = fileId.split("/");
|
||||||
|
const newFileId =
|
||||||
|
parts.slice(0, parts.length - 1).join("/") + "/" + newName;
|
||||||
|
|
||||||
|
await moveFile(
|
||||||
|
containers[data.sandboxId].filesystem,
|
||||||
|
path.join(dirName, fileId),
|
||||||
|
path.join(dirName, newFileId)
|
||||||
|
);
|
||||||
|
fixPermissions();
|
||||||
|
await renameFile(fileId, newFileId, file.data);
|
||||||
|
} catch (e: any) {
|
||||||
|
console.error("Error renaming folder:", e);
|
||||||
|
io.emit("error", `Error: folder renaming. ${e.message ?? e}`);
|
||||||
|
}
|
||||||
|
});
|
||||||
|
|
||||||
|
socket.on("deleteFile", async (fileId: string, callback) => {
|
||||||
|
try {
|
||||||
|
try {
|
||||||
|
await deleteFileRL.consume(data.userId, 1);
|
||||||
|
} catch (e) {
|
||||||
|
io.emit("error", "Rate limited: file deletion. Please slow down.");
|
||||||
|
}
|
||||||
|
|
||||||
|
const file = sandboxFiles.fileData.find((f) => f.id === fileId);
|
||||||
|
if (!file) return;
|
||||||
|
|
||||||
|
await containers[data.sandboxId].filesystem.remove(
|
||||||
|
path.join(dirName, fileId)
|
||||||
|
);
|
||||||
|
sandboxFiles.fileData = sandboxFiles.fileData.filter(
|
||||||
|
(f) => f.id !== fileId
|
||||||
|
);
|
||||||
|
|
||||||
|
await deleteFile(fileId);
|
||||||
|
|
||||||
|
const newFiles = await getSandboxFiles(data.sandboxId);
|
||||||
|
callback(newFiles.files);
|
||||||
|
} catch (e: any) {
|
||||||
|
console.error("Error deleting file:", e);
|
||||||
|
io.emit("error", `Error: file deletion. ${e.message ?? e}`);
|
||||||
|
}
|
||||||
|
});
|
||||||
|
|
||||||
|
// todo
|
||||||
|
// socket.on("renameFolder", async (folderId: string, newName: string) => {
|
||||||
|
// });
|
||||||
|
|
||||||
|
socket.on("deleteFolder", async (folderId: string, callback) => {
|
||||||
|
try {
|
||||||
|
const files = await getFolder(folderId);
|
||||||
|
|
||||||
|
await Promise.all(
|
||||||
|
files.map(async (file) => {
|
||||||
|
await containers[data.sandboxId].filesystem.remove(
|
||||||
|
path.join(dirName, file)
|
||||||
|
);
|
||||||
|
|
||||||
|
sandboxFiles.fileData = sandboxFiles.fileData.filter(
|
||||||
|
(f) => f.id !== file
|
||||||
|
);
|
||||||
|
|
||||||
|
await deleteFile(file);
|
||||||
|
})
|
||||||
|
);
|
||||||
|
|
||||||
|
const newFiles = await getSandboxFiles(data.sandboxId);
|
||||||
|
|
||||||
|
callback(newFiles.files);
|
||||||
|
} catch (e: any) {
|
||||||
|
console.error("Error deleting folder:", e);
|
||||||
|
io.emit("error", `Error: folder deletion. ${e.message ?? e}`);
|
||||||
|
}
|
||||||
|
});
|
||||||
|
|
||||||
|
socket.on("createTerminal", async (id: string, callback) => {
|
||||||
|
try {
|
||||||
|
if (terminals[id] || Object.keys(terminals).length >= 4) {
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
await lockManager.acquireLock(data.sandboxId, async () => {
|
||||||
|
try {
|
||||||
|
terminals[id] = await containers[data.sandboxId].terminal.start({
|
||||||
|
onData: (data: string) => {
|
||||||
|
io.emit("terminalResponse", { id, data });
|
||||||
|
},
|
||||||
|
size: { cols: 80, rows: 20 },
|
||||||
|
onExit: () => console.log("Terminal exited", id),
|
||||||
|
});
|
||||||
|
await terminals[id].sendData(
|
||||||
|
`cd "${path.join(dirName, "projects", data.sandboxId)}"\r`
|
||||||
|
);
|
||||||
|
await terminals[id].sendData("export PS1='user> '\rclear\r");
|
||||||
|
console.log("Created terminal", id);
|
||||||
|
} catch (e: any) {
|
||||||
|
console.error(`Error creating terminal ${id}:`, e);
|
||||||
|
io.emit("error", `Error: terminal creation. ${e.message ?? e}`);
|
||||||
|
}
|
||||||
|
});
|
||||||
|
|
||||||
|
callback();
|
||||||
|
} catch (e: any) {
|
||||||
|
console.error(`Error creating terminal ${id}:`, e);
|
||||||
|
io.emit("error", `Error: terminal creation. ${e.message ?? e}`);
|
||||||
|
}
|
||||||
|
});
|
||||||
|
|
||||||
|
socket.on(
|
||||||
|
"resizeTerminal",
|
||||||
|
(dimensions: { cols: number; rows: number }) => {
|
||||||
|
try {
|
||||||
|
Object.values(terminals).forEach((t) => {
|
||||||
|
t.resize(dimensions);
|
||||||
|
});
|
||||||
|
} catch (e: any) {
|
||||||
|
console.error("Error resizing terminal:", e);
|
||||||
|
io.emit("error", `Error: terminal resizing. ${e.message ?? e}`);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
);
|
||||||
|
|
||||||
|
socket.on("terminalData", (id: string, data: string) => {
|
||||||
|
try {
|
||||||
|
if (!terminals[id]) {
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
terminals[id].sendData(data);
|
||||||
|
} catch (e: any) {
|
||||||
|
console.error("Error writing to terminal:", e);
|
||||||
|
io.emit("error", `Error: writing to terminal. ${e.message ?? e}`);
|
||||||
|
}
|
||||||
|
});
|
||||||
|
|
||||||
|
socket.on("closeTerminal", async (id: string, callback) => {
|
||||||
|
try {
|
||||||
|
if (!terminals[id]) {
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
await terminals[id].kill();
|
||||||
|
delete terminals[id];
|
||||||
|
|
||||||
|
callback();
|
||||||
|
} catch (e: any) {
|
||||||
|
console.error("Error closing terminal:", e);
|
||||||
|
io.emit("error", `Error: closing terminal. ${e.message ?? e}`);
|
||||||
|
}
|
||||||
|
});
|
||||||
|
|
||||||
|
socket.on(
|
||||||
|
"generateCode",
|
||||||
|
async (
|
||||||
|
fileName: string,
|
||||||
|
code: string,
|
||||||
|
line: number,
|
||||||
|
instructions: string,
|
||||||
|
callback
|
||||||
|
) => {
|
||||||
|
try {
|
||||||
|
const fetchPromise = fetch(
|
||||||
|
`${process.env.DATABASE_WORKER_URL}/api/sandbox/generate`,
|
||||||
|
{
|
||||||
|
method: "POST",
|
||||||
|
headers: {
|
||||||
|
"Content-Type": "application/json",
|
||||||
|
Authorization: `${process.env.WORKERS_KEY}`,
|
||||||
|
},
|
||||||
|
body: JSON.stringify({
|
||||||
|
userId: data.userId,
|
||||||
|
}),
|
||||||
|
}
|
||||||
|
);
|
||||||
|
|
||||||
|
// Generate code from cloudflare workers AI
|
||||||
|
const generateCodePromise = fetch(
|
||||||
|
`${process.env.AI_WORKER_URL}/api?fileName=${fileName}&code=${code}&line=${line}&instructions=${instructions}`,
|
||||||
|
{
|
||||||
|
headers: {
|
||||||
|
"Content-Type": "application/json",
|
||||||
|
Authorization: `${process.env.CF_AI_KEY}`,
|
||||||
|
},
|
||||||
|
}
|
||||||
|
);
|
||||||
|
|
||||||
|
const [fetchResponse, generateCodeResponse] = await Promise.all([
|
||||||
|
fetchPromise,
|
||||||
|
generateCodePromise,
|
||||||
|
]);
|
||||||
|
|
||||||
|
const json = await generateCodeResponse.json();
|
||||||
|
|
||||||
|
callback({ response: json.response, success: true });
|
||||||
|
} catch (e: any) {
|
||||||
|
console.error("Error generating code:", e);
|
||||||
|
io.emit("error", `Error: code generation. ${e.message ?? e}`);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
);
|
||||||
|
|
||||||
|
socket.on("disconnect", async () => {
|
||||||
|
try {
|
||||||
|
if (data.isOwner) {
|
||||||
|
connections[data.sandboxId]--;
|
||||||
|
}
|
||||||
|
|
||||||
|
if (data.isOwner && connections[data.sandboxId] <= 0) {
|
||||||
|
await Promise.all(
|
||||||
|
Object.entries(terminals).map(async ([key, terminal]) => {
|
||||||
|
await terminal.kill();
|
||||||
|
delete terminals[key];
|
||||||
|
})
|
||||||
|
);
|
||||||
|
|
||||||
|
await lockManager.acquireLock(data.sandboxId, async () => {
|
||||||
|
try {
|
||||||
|
if (containers[data.sandboxId]) {
|
||||||
|
await containers[data.sandboxId].close();
|
||||||
|
delete containers[data.sandboxId];
|
||||||
|
console.log("Closed container", data.sandboxId);
|
||||||
|
}
|
||||||
|
} catch (error) {
|
||||||
|
console.error("Error closing container ", data.sandboxId, error);
|
||||||
|
}
|
||||||
|
});
|
||||||
|
|
||||||
|
socket.broadcast.emit(
|
||||||
|
"disableAccess",
|
||||||
|
"The sandbox owner has disconnected."
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
// const sockets = await io.fetchSockets();
|
||||||
|
// if (inactivityTimeout) {
|
||||||
|
// clearTimeout(inactivityTimeout);
|
||||||
|
// }
|
||||||
|
// if (sockets.length === 0) {
|
||||||
|
// console.log("STARTING TIMER");
|
||||||
|
// inactivityTimeout = setTimeout(() => {
|
||||||
|
// io.fetchSockets().then(async (sockets) => {
|
||||||
|
// if (sockets.length === 0) {
|
||||||
|
// console.log("Server stopped", res);
|
||||||
|
// }
|
||||||
|
// });
|
||||||
|
// }, 20000);
|
||||||
|
// } else {
|
||||||
|
// console.log("number of sockets", sockets.length);
|
||||||
|
// }
|
||||||
|
} catch (e: any) {
|
||||||
|
console.log("Error disconnecting:", e);
|
||||||
|
io.emit("error", `Error: disconnecting. ${e.message ?? e}`);
|
||||||
|
}
|
||||||
|
});
|
||||||
|
} catch (e: any) {
|
||||||
|
console.error("Error connecting:", e);
|
||||||
|
io.emit("error", `Error: connection. ${e.message ?? e}`);
|
||||||
|
}
|
||||||
});
|
});
|
||||||
|
|
||||||
httpServer.listen(port, () => {
|
httpServer.listen(port, () => {
|
||||||
|
@ -1,177 +1,23 @@
|
|||||||
import * as dotenv from "dotenv";
|
export class LockManager {
|
||||||
import {
|
private locks: { [key: string]: Promise<any> };
|
||||||
R2FileBody,
|
|
||||||
R2Files,
|
|
||||||
Sandbox,
|
|
||||||
TFile,
|
|
||||||
TFileData,
|
|
||||||
TFolder,
|
|
||||||
} from "./types";
|
|
||||||
|
|
||||||
dotenv.config();
|
constructor() {
|
||||||
|
this.locks = {};
|
||||||
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) => {
|
async acquireLock<T>(key: string, task: () => Promise<T>): Promise<T> {
|
||||||
const res = await fetch(`${process.env.STORAGE_WORKER_URL}/api`, {
|
if (!this.locks[key]) {
|
||||||
method: "POST",
|
this.locks[key] = new Promise<T>(async (resolve, reject) => {
|
||||||
headers: {
|
try {
|
||||||
"Content-Type": "application/json",
|
const result = await task();
|
||||||
Authorization: `${process.env.WORKERS_KEY}`,
|
resolve(result);
|
||||||
},
|
} catch (error) {
|
||||||
body: JSON.stringify({ fileId }),
|
reject(error);
|
||||||
});
|
} finally {
|
||||||
return res.ok;
|
delete this.locks[key];
|
||||||
};
|
}
|
||||||
|
});
|
||||||
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 this.locks[key];
|
||||||
return (await res.json()).size;
|
}
|
||||||
};
|
}
|
@ -1,9 +1,9 @@
|
|||||||
"use client"
|
"use client"
|
||||||
|
|
||||||
import { useEffect, useRef, useState } from "react"
|
import { SetStateAction, useCallback, 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 { io } from "socket.io-client"
|
import { Socket, 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 } from "@/lib/utils"
|
import { addNew, processFileType, validateName, debounce } 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,12 +41,16 @@ export default function CodeEditor({
|
|||||||
sandboxData: Sandbox
|
sandboxData: Sandbox
|
||||||
reactDefinitionFile: string
|
reactDefinitionFile: string
|
||||||
}) {
|
}) {
|
||||||
const socket = io(
|
const socketRef = useRef<Socket | null>(null);
|
||||||
`http://localhost:${process.env.NEXT_PUBLIC_SERVER_PORT}?userId=${userData.id}&sandboxId=${sandboxData.id}`,
|
|
||||||
{
|
// Initialize socket connection if it doesn't exist
|
||||||
timeout: 2000,
|
if (!socketRef.current) {
|
||||||
}
|
socketRef.current = io(
|
||||||
)
|
`${window.location.protocol}//${window.location.hostname}:${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({
|
||||||
@ -90,6 +94,9 @@ 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()
|
||||||
|
|
||||||
@ -98,6 +105,16 @@ export default function CodeEditor({
|
|||||||
const [provider, setProvider] = useState<TypedLiveblocksProvider>()
|
const [provider, setProvider] = useState<TypedLiveblocksProvider>()
|
||||||
const userInfo = useSelf((me) => me.info)
|
const userInfo = useSelf((me) => me.info)
|
||||||
|
|
||||||
|
// Liveblocks providers map to prevent reinitializing providers
|
||||||
|
type ProviderData = {
|
||||||
|
provider: LiveblocksProvider<never, never, never, never>;
|
||||||
|
yDoc: Y.Doc;
|
||||||
|
yText: Y.Text;
|
||||||
|
binding?: MonacoBinding;
|
||||||
|
onSync: (isSynced: boolean) => void;
|
||||||
|
};
|
||||||
|
const providersMap = useRef(new Map<string, ProviderData>());
|
||||||
|
|
||||||
// Refs for libraries / features
|
// Refs for libraries / features
|
||||||
const editorContainerRef = useRef<HTMLDivElement>(null)
|
const editorContainerRef = useRef<HTMLDivElement>(null)
|
||||||
const monacoRef = useRef<typeof monaco | null>(null)
|
const monacoRef = useRef<typeof monaco | null>(null)
|
||||||
@ -290,26 +307,33 @@ 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);
|
||||||
}
|
};
|
||||||
}, [tabs, activeFileId])
|
}, [activeFileId, tabs, debouncedSaveData]);
|
||||||
|
|
||||||
// Liveblocks live collaboration setup effect
|
// Liveblocks live collaboration setup effect
|
||||||
useEffect(() => {
|
useEffect(() => {
|
||||||
@ -318,50 +342,84 @@ export default function CodeEditor({
|
|||||||
|
|
||||||
if (!editorRef || !tab || !model) return
|
if (!editorRef || !tab || !model) return
|
||||||
|
|
||||||
const yDoc = new Y.Doc()
|
let providerData: ProviderData;
|
||||||
const yText = yDoc.getText(tab.id)
|
|
||||||
const yProvider: any = new LiveblocksProvider(room, yDoc)
|
|
||||||
|
|
||||||
const onSync = (isSynced: boolean) => {
|
// When a file is opened for the first time, create a new provider and store in providersMap.
|
||||||
if (isSynced) {
|
if (!providersMap.current.has(tab.id)) {
|
||||||
const text = yText.toString()
|
const yDoc = new Y.Doc();
|
||||||
if (text === "") {
|
const yText = yDoc.getText(tab.id);
|
||||||
if (activeFileContent) {
|
const yProvider = new LiveblocksProvider(room, yDoc);
|
||||||
yText.insert(0, activeFileContent)
|
|
||||||
} else {
|
// Inserts the file content into the editor once when the tab is changed.
|
||||||
setTimeout(() => {
|
const onSync = (isSynced: boolean) => {
|
||||||
yText.insert(0, editorRef.getValue())
|
if (isSynced) {
|
||||||
}, 0)
|
const text = yText.toString()
|
||||||
|
if (text === "") {
|
||||||
|
if (activeFileContent) {
|
||||||
|
yText.insert(0, activeFileContent)
|
||||||
|
} else {
|
||||||
|
setTimeout(() => {
|
||||||
|
yText.insert(0, editorRef.getValue())
|
||||||
|
}, 0)
|
||||||
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
yProvider.on("sync", onSync)
|
||||||
|
|
||||||
|
// Save the provider to the map.
|
||||||
|
providerData = { provider: yProvider, yDoc, yText, onSync };
|
||||||
|
providersMap.current.set(tab.id, providerData);
|
||||||
|
|
||||||
|
} else {
|
||||||
|
// When a tab is opened that has been open before, reuse the existing provider.
|
||||||
|
providerData = providersMap.current.get(tab.id)!;
|
||||||
}
|
}
|
||||||
|
|
||||||
yProvider.on("sync", onSync)
|
|
||||||
|
|
||||||
setProvider(yProvider)
|
|
||||||
|
|
||||||
const binding = new MonacoBinding(
|
const binding = new MonacoBinding(
|
||||||
yText,
|
providerData.yText,
|
||||||
model,
|
model,
|
||||||
new Set([editorRef]),
|
new Set([editorRef]),
|
||||||
yProvider.awareness as Awareness
|
providerData.provider.awareness as unknown as Awareness
|
||||||
)
|
);
|
||||||
|
|
||||||
|
providerData.binding = binding;
|
||||||
|
|
||||||
|
setProvider(providerData.provider);
|
||||||
|
|
||||||
return () => {
|
return () => {
|
||||||
yDoc.destroy()
|
// Cleanup logic
|
||||||
yProvider.destroy()
|
if (binding) {
|
||||||
binding.destroy()
|
binding.destroy();
|
||||||
yProvider.off("sync", onSync)
|
}
|
||||||
}
|
if (providerData.binding) {
|
||||||
}, [editorRef, room, activeFileContent])
|
providerData.binding = undefined;
|
||||||
|
}
|
||||||
|
};
|
||||||
|
}, [room, activeFileContent]);
|
||||||
|
|
||||||
|
// Added this effect to clean up when the component unmounts
|
||||||
|
useEffect(() => {
|
||||||
|
return () => {
|
||||||
|
// Clean up all providers when the component unmounts
|
||||||
|
providersMap.current.forEach((data) => {
|
||||||
|
if (data.binding) {
|
||||||
|
data.binding.destroy();
|
||||||
|
}
|
||||||
|
data.provider.disconnect();
|
||||||
|
data.yDoc.destroy();
|
||||||
|
});
|
||||||
|
providersMap.current.clear();
|
||||||
|
};
|
||||||
|
}, []);
|
||||||
|
|
||||||
// Connection/disconnection effect
|
// Connection/disconnection effect
|
||||||
useEffect(() => {
|
useEffect(() => {
|
||||||
socket.connect()
|
socketRef.current?.connect()
|
||||||
|
|
||||||
return () => {
|
return () => {
|
||||||
socket.disconnect()
|
socketRef.current?.disconnect()
|
||||||
}
|
}
|
||||||
}, [])
|
}, [])
|
||||||
|
|
||||||
@ -377,7 +435,7 @@ export default function CodeEditor({
|
|||||||
setFiles(files)
|
setFiles(files)
|
||||||
}
|
}
|
||||||
|
|
||||||
const onRateLimit = (message: string) => {
|
const onError = (message: string) => {
|
||||||
toast.error(message)
|
toast.error(message)
|
||||||
}
|
}
|
||||||
|
|
||||||
@ -396,20 +454,22 @@ export default function CodeEditor({
|
|||||||
})
|
})
|
||||||
}
|
}
|
||||||
|
|
||||||
socket.on("connect", onConnect)
|
socketRef.current?.on("connect", onConnect)
|
||||||
socket.on("disconnect", onDisconnect)
|
socketRef.current?.on("disconnect", onDisconnect)
|
||||||
socket.on("loaded", onLoadedEvent)
|
socketRef.current?.on("loaded", onLoadedEvent)
|
||||||
socket.on("rateLimit", onRateLimit)
|
socketRef.current?.on("error", onError)
|
||||||
socket.on("terminalResponse", onTerminalResponse)
|
socketRef.current?.on("terminalResponse", onTerminalResponse)
|
||||||
socket.on("disableAccess", onDisableAccess)
|
socketRef.current?.on("disableAccess", onDisableAccess)
|
||||||
|
socketRef.current?.on("previewURL", setPreviewURL)
|
||||||
|
|
||||||
return () => {
|
return () => {
|
||||||
socket.off("connect", onConnect)
|
socketRef.current?.off("connect", onConnect)
|
||||||
socket.off("disconnect", onDisconnect)
|
socketRef.current?.off("disconnect", onDisconnect)
|
||||||
socket.off("loaded", onLoadedEvent)
|
socketRef.current?.off("loaded", onLoadedEvent)
|
||||||
socket.off("rateLimit", onRateLimit)
|
socketRef.current?.off("error", onError)
|
||||||
socket.off("terminalResponse", onTerminalResponse)
|
socketRef.current?.off("terminalResponse", onTerminalResponse)
|
||||||
socket.off("disableAccess", onDisableAccess)
|
socketRef.current?.off("disableAccess", onDisableAccess)
|
||||||
|
socketRef.current?.off("previewURL", setPreviewURL)
|
||||||
}
|
}
|
||||||
// }, []);
|
// }, []);
|
||||||
}, [terminals])
|
}, [terminals])
|
||||||
@ -417,31 +477,44 @@ 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
|
|
||||||
|
|
||||||
setGenerate((prev) => {
|
// Initialize debounced function once
|
||||||
return {
|
const fileCache = useRef(new Map());
|
||||||
...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];
|
||||||
})
|
});
|
||||||
|
|
||||||
socket.emit("getFile", tab.id, (response: string) => {
|
if (fileCache.current.has(tab.id)) {
|
||||||
setActiveFileContent(response)
|
setActiveFileContent(fileCache.current.get(tab.id));
|
||||||
})
|
} else {
|
||||||
setEditorLanguage(processFileType(tab.name))
|
debouncedGetFile(tab.id, (response: SetStateAction<string>) => {
|
||||||
setActiveFileId(tab.id)
|
fileCache.current.set(tab.id, response);
|
||||||
}
|
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) => {
|
||||||
@ -515,7 +588,7 @@ export default function CodeEditor({
|
|||||||
return false
|
return false
|
||||||
}
|
}
|
||||||
|
|
||||||
socket.emit("renameFile", id, newName)
|
socketRef.current?.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))
|
||||||
)
|
)
|
||||||
@ -524,7 +597,7 @@ export default function CodeEditor({
|
|||||||
}
|
}
|
||||||
|
|
||||||
const handleDeleteFile = (file: TFile) => {
|
const handleDeleteFile = (file: TFile) => {
|
||||||
socket.emit("deleteFile", file.id, (response: (TFolder | TFile)[]) => {
|
socketRef.current?.emit("deleteFile", file.id, (response: (TFolder | TFile)[]) => {
|
||||||
setFiles(response)
|
setFiles(response)
|
||||||
})
|
})
|
||||||
closeTab(file.id)
|
closeTab(file.id)
|
||||||
@ -534,11 +607,11 @@ export default function CodeEditor({
|
|||||||
setDeletingFolderId(folder.id)
|
setDeletingFolderId(folder.id)
|
||||||
console.log("deleting folder", folder.id)
|
console.log("deleting folder", folder.id)
|
||||||
|
|
||||||
socket.emit("getFolder", folder.id, (response: string[]) =>
|
socketRef.current?.emit("getFolder", folder.id, (response: string[]) =>
|
||||||
closeTabs(response)
|
closeTabs(response)
|
||||||
)
|
)
|
||||||
|
|
||||||
socket.emit("deleteFolder", folder.id, (response: (TFolder | TFile)[]) => {
|
socketRef.current?.emit("deleteFolder", folder.id, (response: (TFolder | TFile)[]) => {
|
||||||
setFiles(response)
|
setFiles(response)
|
||||||
setDeletingFolderId("")
|
setDeletingFolderId("")
|
||||||
})
|
})
|
||||||
@ -565,7 +638,7 @@ export default function CodeEditor({
|
|||||||
{generate.show && ai ? (
|
{generate.show && ai ? (
|
||||||
<GenerateInput
|
<GenerateInput
|
||||||
user={userData}
|
user={userData}
|
||||||
socket={socket}
|
socket={socketRef.current}
|
||||||
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 ?? "",
|
||||||
@ -625,7 +698,7 @@ export default function CodeEditor({
|
|||||||
handleRename={handleRename}
|
handleRename={handleRename}
|
||||||
handleDeleteFile={handleDeleteFile}
|
handleDeleteFile={handleDeleteFile}
|
||||||
handleDeleteFolder={handleDeleteFolder}
|
handleDeleteFolder={handleDeleteFolder}
|
||||||
socket={socket}
|
socket={socketRef.current}
|
||||||
setFiles={setFiles}
|
setFiles={setFiles}
|
||||||
addNew={(name, type) => addNew(name, type, setFiles, sandboxData)}
|
addNew={(name, type) => addNew(name, type, setFiles, sandboxData)}
|
||||||
deletingFolderId={deletingFolderId}
|
deletingFolderId={deletingFolderId}
|
||||||
@ -745,6 +818,7 @@ export default function CodeEditor({
|
|||||||
previewPanelRef.current?.expand()
|
previewPanelRef.current?.expand()
|
||||||
setIsPreviewCollapsed(false)
|
setIsPreviewCollapsed(false)
|
||||||
}}
|
}}
|
||||||
|
src={previewURL}
|
||||||
/>
|
/>
|
||||||
</ResizablePanel>
|
</ResizablePanel>
|
||||||
<ResizableHandle />
|
<ResizableHandle />
|
||||||
@ -757,7 +831,7 @@ export default function CodeEditor({
|
|||||||
<Terminals
|
<Terminals
|
||||||
terminals={terminals}
|
terminals={terminals}
|
||||||
setTerminals={setTerminals}
|
setTerminals={setTerminals}
|
||||||
socket={socket}
|
socket={socketRef.current}
|
||||||
/>
|
/>
|
||||||
) : (
|
) : (
|
||||||
<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">
|
||||||
@ -772,3 +846,4 @@ export default function CodeEditor({
|
|||||||
</>
|
</>
|
||||||
)
|
)
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@ -15,9 +15,11 @@ 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)
|
||||||
@ -45,7 +47,7 @@ export default function PreviewWindow({
|
|||||||
|
|
||||||
<PreviewButton
|
<PreviewButton
|
||||||
onClick={() => {
|
onClick={() => {
|
||||||
navigator.clipboard.writeText(`http://localhost:5173`)
|
navigator.clipboard.writeText(src)
|
||||||
toast.info("Copied preview link to clipboard")
|
toast.info("Copied preview link to clipboard")
|
||||||
}}
|
}}
|
||||||
>
|
>
|
||||||
@ -73,7 +75,7 @@ export default function PreviewWindow({
|
|||||||
ref={ref}
|
ref={ref}
|
||||||
width={"100%"}
|
width={"100%"}
|
||||||
height={"100%"}
|
height={"100%"}
|
||||||
src={`http://localhost:5173`}
|
src={src}
|
||||||
/>
|
/>
|
||||||
</div>
|
</div>
|
||||||
)}
|
)}
|
||||||
|
@ -61,3 +61,13 @@ 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;
|
||||||
|
}
|
Reference in New Issue
Block a user