Compare commits
16 Commits
fix-multip
...
fix-editor
Author | SHA1 | Date | |
---|---|---|---|
44f803ffaf | |||
d9ce147e09 | |||
398139ec36 | |||
bd6284df8f | |||
c262fb2a31 | |||
ed709210e3 | |||
97c8598717 | |||
9ec59bc781 | |||
687416e6e9 | |||
006c5cea66 | |||
869ae6c148 | |||
7353e88567 | |||
a0fb905a04 | |||
0df074924f | |||
e5b320d1c5 | |||
b561f1e962 |
@ -29,7 +29,9 @@ npm run dev
|
|||||||
|
|
||||||
### Backend
|
### Backend
|
||||||
|
|
||||||
The backend consists of a primary Express and Socket.io server, and 3 Cloudflare Workers microservices for the D1 database, R2 storage, and Workers AI. The D1 database also contains a [service binding](https://developers.cloudflare.com/workers/runtime-apis/bindings/service-bindings/) to the R2 storage worker.
|
The backend consists of a primary Express and Socket.io server, and 3 Cloudflare Workers microservices for the D1 database, R2 storage, and Workers AI. The D1 database also contains a [service binding](https://developers.cloudflare.com/workers/runtime-apis/bindings/service-bindings/) to the R2 storage worker. Each open sandbox instantiates a secure Linux sandboxes on E2B, which is used for the terminal and live preview.
|
||||||
|
|
||||||
|
You will need to make an account on [E2B](https://e2b.dev/) to get an API key.
|
||||||
|
|
||||||
#### Socket.io server
|
#### Socket.io server
|
||||||
|
|
||||||
@ -181,3 +183,4 @@ It should be in the form `category(scope or module): message` in your commit mes
|
|||||||
- [Express](https://expressjs.com/)
|
- [Express](https://expressjs.com/)
|
||||||
- [Socket.io](https://socket.io/)
|
- [Socket.io](https://socket.io/)
|
||||||
- [Drizzle ORM](https://orm.drizzle.team/)
|
- [Drizzle ORM](https://orm.drizzle.team/)
|
||||||
|
- [E2B](https://e2b.dev/)
|
||||||
|
@ -1,197 +1,168 @@
|
|||||||
{
|
{
|
||||||
"version": "5",
|
"version": "5",
|
||||||
"dialect": "sqlite",
|
"dialect": "sqlite",
|
||||||
"id": "70e3d022-aed8-4464-9063-c92113b4ebe2",
|
"id": "6570ba20-a672-400c-8147-7ba533784918",
|
||||||
"prevId": "00000000-0000-0000-0000-000000000000",
|
"prevId": "00000000-0000-0000-0000-000000000000",
|
||||||
"tables": {
|
"tables": {
|
||||||
"sandbox": {
|
"sandbox": {
|
||||||
"name": "sandbox",
|
"name": "sandbox",
|
||||||
"columns": {
|
"columns": {
|
||||||
"id": {
|
"id": {
|
||||||
"name": "id",
|
"name": "id",
|
||||||
"type": "text",
|
"type": "text",
|
||||||
"primaryKey": true,
|
"primaryKey": true,
|
||||||
"notNull": true,
|
"notNull": true,
|
||||||
"autoincrement": false
|
"autoincrement": false
|
||||||
},
|
|
||||||
"name": {
|
|
||||||
"name": "name",
|
|
||||||
"type": "text",
|
|
||||||
"primaryKey": false,
|
|
||||||
"notNull": true,
|
|
||||||
"autoincrement": false
|
|
||||||
},
|
|
||||||
"type": {
|
|
||||||
"name": "type",
|
|
||||||
"type": "text",
|
|
||||||
"primaryKey": false,
|
|
||||||
"notNull": true,
|
|
||||||
"autoincrement": false
|
|
||||||
},
|
|
||||||
"visibility": {
|
|
||||||
"name": "visibility",
|
|
||||||
"type": "text",
|
|
||||||
"primaryKey": false,
|
|
||||||
"notNull": false,
|
|
||||||
"autoincrement": false
|
|
||||||
},
|
|
||||||
"createdAt": {
|
|
||||||
"name": "createdAt",
|
|
||||||
"type": "integer",
|
|
||||||
"primaryKey": false,
|
|
||||||
"notNull": false,
|
|
||||||
"autoincrement": false
|
|
||||||
},
|
|
||||||
"user_id": {
|
|
||||||
"name": "user_id",
|
|
||||||
"type": "text",
|
|
||||||
"primaryKey": false,
|
|
||||||
"notNull": true,
|
|
||||||
"autoincrement": false
|
|
||||||
}
|
|
||||||
},
|
},
|
||||||
"indexes": {
|
"name": {
|
||||||
"sandbox_id_unique": {
|
"name": "name",
|
||||||
"name": "sandbox_id_unique",
|
"type": "text",
|
||||||
"columns": [
|
"primaryKey": false,
|
||||||
"id"
|
"notNull": true,
|
||||||
],
|
"autoincrement": false
|
||||||
"isUnique": true
|
|
||||||
}
|
|
||||||
},
|
},
|
||||||
"foreignKeys": {
|
"type": {
|
||||||
"sandbox_user_id_user_id_fk": {
|
"name": "type",
|
||||||
"name": "sandbox_user_id_user_id_fk",
|
"type": "text",
|
||||||
"tableFrom": "sandbox",
|
"primaryKey": false,
|
||||||
"tableTo": "user",
|
"notNull": true,
|
||||||
"columnsFrom": [
|
"autoincrement": false
|
||||||
"user_id"
|
|
||||||
],
|
|
||||||
"columnsTo": [
|
|
||||||
"id"
|
|
||||||
],
|
|
||||||
"onDelete": "no action",
|
|
||||||
"onUpdate": "no action"
|
|
||||||
}
|
|
||||||
},
|
},
|
||||||
"compositePrimaryKeys": {},
|
"visibility": {
|
||||||
"uniqueConstraints": {}
|
"name": "visibility",
|
||||||
|
"type": "text",
|
||||||
|
"primaryKey": false,
|
||||||
|
"notNull": false,
|
||||||
|
"autoincrement": false
|
||||||
|
},
|
||||||
|
"user_id": {
|
||||||
|
"name": "user_id",
|
||||||
|
"type": "text",
|
||||||
|
"primaryKey": false,
|
||||||
|
"notNull": true,
|
||||||
|
"autoincrement": false
|
||||||
|
}
|
||||||
},
|
},
|
||||||
"user": {
|
"indexes": {
|
||||||
"name": "user",
|
"sandbox_id_unique": {
|
||||||
"columns": {
|
"name": "sandbox_id_unique",
|
||||||
"id": {
|
"columns": [
|
||||||
"name": "id",
|
"id"
|
||||||
"type": "text",
|
],
|
||||||
"primaryKey": true,
|
"isUnique": true
|
||||||
"notNull": true,
|
}
|
||||||
"autoincrement": false
|
|
||||||
},
|
|
||||||
"name": {
|
|
||||||
"name": "name",
|
|
||||||
"type": "text",
|
|
||||||
"primaryKey": false,
|
|
||||||
"notNull": true,
|
|
||||||
"autoincrement": false
|
|
||||||
},
|
|
||||||
"email": {
|
|
||||||
"name": "email",
|
|
||||||
"type": "text",
|
|
||||||
"primaryKey": false,
|
|
||||||
"notNull": true,
|
|
||||||
"autoincrement": false
|
|
||||||
},
|
|
||||||
"image": {
|
|
||||||
"name": "image",
|
|
||||||
"type": "text",
|
|
||||||
"primaryKey": false,
|
|
||||||
"notNull": false,
|
|
||||||
"autoincrement": false
|
|
||||||
},
|
|
||||||
"generations": {
|
|
||||||
"name": "generations",
|
|
||||||
"type": "integer",
|
|
||||||
"primaryKey": false,
|
|
||||||
"notNull": false,
|
|
||||||
"autoincrement": false,
|
|
||||||
"default": 0
|
|
||||||
}
|
|
||||||
},
|
|
||||||
"indexes": {
|
|
||||||
"user_id_unique": {
|
|
||||||
"name": "user_id_unique",
|
|
||||||
"columns": [
|
|
||||||
"id"
|
|
||||||
],
|
|
||||||
"isUnique": true
|
|
||||||
}
|
|
||||||
},
|
|
||||||
"foreignKeys": {},
|
|
||||||
"compositePrimaryKeys": {},
|
|
||||||
"uniqueConstraints": {}
|
|
||||||
},
|
},
|
||||||
"users_to_sandboxes": {
|
"foreignKeys": {
|
||||||
"name": "users_to_sandboxes",
|
"sandbox_user_id_user_id_fk": {
|
||||||
"columns": {
|
"name": "sandbox_user_id_user_id_fk",
|
||||||
"userId": {
|
"tableFrom": "sandbox",
|
||||||
"name": "userId",
|
"tableTo": "user",
|
||||||
"type": "text",
|
"columnsFrom": [
|
||||||
"primaryKey": false,
|
"user_id"
|
||||||
"notNull": true,
|
],
|
||||||
"autoincrement": false
|
"columnsTo": [
|
||||||
},
|
"id"
|
||||||
"sandboxId": {
|
],
|
||||||
"name": "sandboxId",
|
"onDelete": "no action",
|
||||||
"type": "text",
|
"onUpdate": "no action"
|
||||||
"primaryKey": false,
|
}
|
||||||
"notNull": true,
|
},
|
||||||
"autoincrement": false
|
"compositePrimaryKeys": {},
|
||||||
},
|
"uniqueConstraints": {}
|
||||||
"sharedOn": {
|
|
||||||
"name": "sharedOn",
|
|
||||||
"type": "integer",
|
|
||||||
"primaryKey": false,
|
|
||||||
"notNull": false,
|
|
||||||
"autoincrement": false
|
|
||||||
}
|
|
||||||
},
|
|
||||||
"indexes": {},
|
|
||||||
"foreignKeys": {
|
|
||||||
"users_to_sandboxes_userId_user_id_fk": {
|
|
||||||
"name": "users_to_sandboxes_userId_user_id_fk",
|
|
||||||
"tableFrom": "users_to_sandboxes",
|
|
||||||
"tableTo": "user",
|
|
||||||
"columnsFrom": [
|
|
||||||
"userId"
|
|
||||||
],
|
|
||||||
"columnsTo": [
|
|
||||||
"id"
|
|
||||||
],
|
|
||||||
"onDelete": "no action",
|
|
||||||
"onUpdate": "no action"
|
|
||||||
},
|
|
||||||
"users_to_sandboxes_sandboxId_sandbox_id_fk": {
|
|
||||||
"name": "users_to_sandboxes_sandboxId_sandbox_id_fk",
|
|
||||||
"tableFrom": "users_to_sandboxes",
|
|
||||||
"tableTo": "sandbox",
|
|
||||||
"columnsFrom": [
|
|
||||||
"sandboxId"
|
|
||||||
],
|
|
||||||
"columnsTo": [
|
|
||||||
"id"
|
|
||||||
],
|
|
||||||
"onDelete": "no action",
|
|
||||||
"onUpdate": "no action"
|
|
||||||
}
|
|
||||||
},
|
|
||||||
"compositePrimaryKeys": {},
|
|
||||||
"uniqueConstraints": {}
|
|
||||||
}
|
|
||||||
},
|
},
|
||||||
"enums": {},
|
"user": {
|
||||||
"_meta": {
|
"name": "user",
|
||||||
"schemas": {},
|
"columns": {
|
||||||
"tables": {},
|
"id": {
|
||||||
"columns": {}
|
"name": "id",
|
||||||
|
"type": "text",
|
||||||
|
"primaryKey": true,
|
||||||
|
"notNull": true,
|
||||||
|
"autoincrement": false
|
||||||
|
},
|
||||||
|
"name": {
|
||||||
|
"name": "name",
|
||||||
|
"type": "text",
|
||||||
|
"primaryKey": false,
|
||||||
|
"notNull": true,
|
||||||
|
"autoincrement": false
|
||||||
|
},
|
||||||
|
"email": {
|
||||||
|
"name": "email",
|
||||||
|
"type": "text",
|
||||||
|
"primaryKey": false,
|
||||||
|
"notNull": true,
|
||||||
|
"autoincrement": false
|
||||||
|
}
|
||||||
|
},
|
||||||
|
"indexes": {
|
||||||
|
"user_id_unique": {
|
||||||
|
"name": "user_id_unique",
|
||||||
|
"columns": [
|
||||||
|
"id"
|
||||||
|
],
|
||||||
|
"isUnique": true
|
||||||
|
}
|
||||||
|
},
|
||||||
|
"foreignKeys": {},
|
||||||
|
"compositePrimaryKeys": {},
|
||||||
|
"uniqueConstraints": {}
|
||||||
|
},
|
||||||
|
"users_to_sandboxes": {
|
||||||
|
"name": "users_to_sandboxes",
|
||||||
|
"columns": {
|
||||||
|
"userId": {
|
||||||
|
"name": "userId",
|
||||||
|
"type": "text",
|
||||||
|
"primaryKey": false,
|
||||||
|
"notNull": true,
|
||||||
|
"autoincrement": false
|
||||||
|
},
|
||||||
|
"sandboxId": {
|
||||||
|
"name": "sandboxId",
|
||||||
|
"type": "text",
|
||||||
|
"primaryKey": false,
|
||||||
|
"notNull": true,
|
||||||
|
"autoincrement": false
|
||||||
|
}
|
||||||
|
},
|
||||||
|
"indexes": {},
|
||||||
|
"foreignKeys": {
|
||||||
|
"users_to_sandboxes_userId_user_id_fk": {
|
||||||
|
"name": "users_to_sandboxes_userId_user_id_fk",
|
||||||
|
"tableFrom": "users_to_sandboxes",
|
||||||
|
"tableTo": "user",
|
||||||
|
"columnsFrom": [
|
||||||
|
"userId"
|
||||||
|
],
|
||||||
|
"columnsTo": [
|
||||||
|
"id"
|
||||||
|
],
|
||||||
|
"onDelete": "no action",
|
||||||
|
"onUpdate": "no action"
|
||||||
|
},
|
||||||
|
"users_to_sandboxes_sandboxId_sandbox_id_fk": {
|
||||||
|
"name": "users_to_sandboxes_sandboxId_sandbox_id_fk",
|
||||||
|
"tableFrom": "users_to_sandboxes",
|
||||||
|
"tableTo": "sandbox",
|
||||||
|
"columnsFrom": [
|
||||||
|
"sandboxId"
|
||||||
|
],
|
||||||
|
"columnsTo": [
|
||||||
|
"id"
|
||||||
|
],
|
||||||
|
"onDelete": "no action",
|
||||||
|
"onUpdate": "no action"
|
||||||
|
}
|
||||||
|
},
|
||||||
|
"compositePrimaryKeys": {},
|
||||||
|
"uniqueConstraints": {}
|
||||||
}
|
}
|
||||||
}
|
},
|
||||||
|
"enums": {},
|
||||||
|
"_meta": {
|
||||||
|
"schemas": {},
|
||||||
|
"tables": {},
|
||||||
|
"columns": {}
|
||||||
|
}
|
||||||
|
}
|
175
backend/database/drizzle/meta/0001_snapshot.json
Normal file
175
backend/database/drizzle/meta/0001_snapshot.json
Normal file
@ -0,0 +1,175 @@
|
|||||||
|
{
|
||||||
|
"version": "5",
|
||||||
|
"dialect": "sqlite",
|
||||||
|
"id": "9f64104a-4954-40c0-8155-17755ea0a243",
|
||||||
|
"prevId": "6570ba20-a672-400c-8147-7ba533784918",
|
||||||
|
"tables": {
|
||||||
|
"sandbox": {
|
||||||
|
"name": "sandbox",
|
||||||
|
"columns": {
|
||||||
|
"id": {
|
||||||
|
"name": "id",
|
||||||
|
"type": "text",
|
||||||
|
"primaryKey": true,
|
||||||
|
"notNull": true,
|
||||||
|
"autoincrement": false
|
||||||
|
},
|
||||||
|
"name": {
|
||||||
|
"name": "name",
|
||||||
|
"type": "text",
|
||||||
|
"primaryKey": false,
|
||||||
|
"notNull": true,
|
||||||
|
"autoincrement": false
|
||||||
|
},
|
||||||
|
"type": {
|
||||||
|
"name": "type",
|
||||||
|
"type": "text",
|
||||||
|
"primaryKey": false,
|
||||||
|
"notNull": true,
|
||||||
|
"autoincrement": false
|
||||||
|
},
|
||||||
|
"visibility": {
|
||||||
|
"name": "visibility",
|
||||||
|
"type": "text",
|
||||||
|
"primaryKey": false,
|
||||||
|
"notNull": false,
|
||||||
|
"autoincrement": false
|
||||||
|
},
|
||||||
|
"user_id": {
|
||||||
|
"name": "user_id",
|
||||||
|
"type": "text",
|
||||||
|
"primaryKey": false,
|
||||||
|
"notNull": true,
|
||||||
|
"autoincrement": false
|
||||||
|
}
|
||||||
|
},
|
||||||
|
"indexes": {
|
||||||
|
"sandbox_id_unique": {
|
||||||
|
"name": "sandbox_id_unique",
|
||||||
|
"columns": [
|
||||||
|
"id"
|
||||||
|
],
|
||||||
|
"isUnique": true
|
||||||
|
}
|
||||||
|
},
|
||||||
|
"foreignKeys": {
|
||||||
|
"sandbox_user_id_user_id_fk": {
|
||||||
|
"name": "sandbox_user_id_user_id_fk",
|
||||||
|
"tableFrom": "sandbox",
|
||||||
|
"tableTo": "user",
|
||||||
|
"columnsFrom": [
|
||||||
|
"user_id"
|
||||||
|
],
|
||||||
|
"columnsTo": [
|
||||||
|
"id"
|
||||||
|
],
|
||||||
|
"onDelete": "no action",
|
||||||
|
"onUpdate": "no action"
|
||||||
|
}
|
||||||
|
},
|
||||||
|
"compositePrimaryKeys": {},
|
||||||
|
"uniqueConstraints": {}
|
||||||
|
},
|
||||||
|
"user": {
|
||||||
|
"name": "user",
|
||||||
|
"columns": {
|
||||||
|
"id": {
|
||||||
|
"name": "id",
|
||||||
|
"type": "text",
|
||||||
|
"primaryKey": true,
|
||||||
|
"notNull": true,
|
||||||
|
"autoincrement": false
|
||||||
|
},
|
||||||
|
"name": {
|
||||||
|
"name": "name",
|
||||||
|
"type": "text",
|
||||||
|
"primaryKey": false,
|
||||||
|
"notNull": true,
|
||||||
|
"autoincrement": false
|
||||||
|
},
|
||||||
|
"email": {
|
||||||
|
"name": "email",
|
||||||
|
"type": "text",
|
||||||
|
"primaryKey": false,
|
||||||
|
"notNull": true,
|
||||||
|
"autoincrement": false
|
||||||
|
},
|
||||||
|
"image": {
|
||||||
|
"name": "image",
|
||||||
|
"type": "text",
|
||||||
|
"primaryKey": false,
|
||||||
|
"notNull": false,
|
||||||
|
"autoincrement": false
|
||||||
|
}
|
||||||
|
},
|
||||||
|
"indexes": {
|
||||||
|
"user_id_unique": {
|
||||||
|
"name": "user_id_unique",
|
||||||
|
"columns": [
|
||||||
|
"id"
|
||||||
|
],
|
||||||
|
"isUnique": true
|
||||||
|
}
|
||||||
|
},
|
||||||
|
"foreignKeys": {},
|
||||||
|
"compositePrimaryKeys": {},
|
||||||
|
"uniqueConstraints": {}
|
||||||
|
},
|
||||||
|
"users_to_sandboxes": {
|
||||||
|
"name": "users_to_sandboxes",
|
||||||
|
"columns": {
|
||||||
|
"userId": {
|
||||||
|
"name": "userId",
|
||||||
|
"type": "text",
|
||||||
|
"primaryKey": false,
|
||||||
|
"notNull": true,
|
||||||
|
"autoincrement": false
|
||||||
|
},
|
||||||
|
"sandboxId": {
|
||||||
|
"name": "sandboxId",
|
||||||
|
"type": "text",
|
||||||
|
"primaryKey": false,
|
||||||
|
"notNull": true,
|
||||||
|
"autoincrement": false
|
||||||
|
}
|
||||||
|
},
|
||||||
|
"indexes": {},
|
||||||
|
"foreignKeys": {
|
||||||
|
"users_to_sandboxes_userId_user_id_fk": {
|
||||||
|
"name": "users_to_sandboxes_userId_user_id_fk",
|
||||||
|
"tableFrom": "users_to_sandboxes",
|
||||||
|
"tableTo": "user",
|
||||||
|
"columnsFrom": [
|
||||||
|
"userId"
|
||||||
|
],
|
||||||
|
"columnsTo": [
|
||||||
|
"id"
|
||||||
|
],
|
||||||
|
"onDelete": "no action",
|
||||||
|
"onUpdate": "no action"
|
||||||
|
},
|
||||||
|
"users_to_sandboxes_sandboxId_sandbox_id_fk": {
|
||||||
|
"name": "users_to_sandboxes_sandboxId_sandbox_id_fk",
|
||||||
|
"tableFrom": "users_to_sandboxes",
|
||||||
|
"tableTo": "sandbox",
|
||||||
|
"columnsFrom": [
|
||||||
|
"sandboxId"
|
||||||
|
],
|
||||||
|
"columnsTo": [
|
||||||
|
"id"
|
||||||
|
],
|
||||||
|
"onDelete": "no action",
|
||||||
|
"onUpdate": "no action"
|
||||||
|
}
|
||||||
|
},
|
||||||
|
"compositePrimaryKeys": {},
|
||||||
|
"uniqueConstraints": {}
|
||||||
|
}
|
||||||
|
},
|
||||||
|
"enums": {},
|
||||||
|
"_meta": {
|
||||||
|
"schemas": {},
|
||||||
|
"tables": {},
|
||||||
|
"columns": {}
|
||||||
|
}
|
||||||
|
}
|
168
backend/database/drizzle/meta/0002_snapshot.json
Normal file
168
backend/database/drizzle/meta/0002_snapshot.json
Normal file
@ -0,0 +1,168 @@
|
|||||||
|
{
|
||||||
|
"version": "5",
|
||||||
|
"dialect": "sqlite",
|
||||||
|
"id": "5baf10d6-7697-42ba-a11a-ee4c7bd7e91e",
|
||||||
|
"prevId": "9f64104a-4954-40c0-8155-17755ea0a243",
|
||||||
|
"tables": {
|
||||||
|
"sandbox": {
|
||||||
|
"name": "sandbox",
|
||||||
|
"columns": {
|
||||||
|
"id": {
|
||||||
|
"name": "id",
|
||||||
|
"type": "text",
|
||||||
|
"primaryKey": true,
|
||||||
|
"notNull": true,
|
||||||
|
"autoincrement": false
|
||||||
|
},
|
||||||
|
"name": {
|
||||||
|
"name": "name",
|
||||||
|
"type": "text",
|
||||||
|
"primaryKey": false,
|
||||||
|
"notNull": true,
|
||||||
|
"autoincrement": false
|
||||||
|
},
|
||||||
|
"type": {
|
||||||
|
"name": "type",
|
||||||
|
"type": "text",
|
||||||
|
"primaryKey": false,
|
||||||
|
"notNull": true,
|
||||||
|
"autoincrement": false
|
||||||
|
},
|
||||||
|
"visibility": {
|
||||||
|
"name": "visibility",
|
||||||
|
"type": "text",
|
||||||
|
"primaryKey": false,
|
||||||
|
"notNull": false,
|
||||||
|
"autoincrement": false
|
||||||
|
},
|
||||||
|
"user_id": {
|
||||||
|
"name": "user_id",
|
||||||
|
"type": "text",
|
||||||
|
"primaryKey": false,
|
||||||
|
"notNull": true,
|
||||||
|
"autoincrement": false
|
||||||
|
}
|
||||||
|
},
|
||||||
|
"indexes": {
|
||||||
|
"sandbox_id_unique": {
|
||||||
|
"name": "sandbox_id_unique",
|
||||||
|
"columns": [
|
||||||
|
"id"
|
||||||
|
],
|
||||||
|
"isUnique": true
|
||||||
|
}
|
||||||
|
},
|
||||||
|
"foreignKeys": {
|
||||||
|
"sandbox_user_id_user_id_fk": {
|
||||||
|
"name": "sandbox_user_id_user_id_fk",
|
||||||
|
"tableFrom": "sandbox",
|
||||||
|
"tableTo": "user",
|
||||||
|
"columnsFrom": [
|
||||||
|
"user_id"
|
||||||
|
],
|
||||||
|
"columnsTo": [
|
||||||
|
"id"
|
||||||
|
],
|
||||||
|
"onDelete": "no action",
|
||||||
|
"onUpdate": "no action"
|
||||||
|
}
|
||||||
|
},
|
||||||
|
"compositePrimaryKeys": {},
|
||||||
|
"uniqueConstraints": {}
|
||||||
|
},
|
||||||
|
"user": {
|
||||||
|
"name": "user",
|
||||||
|
"columns": {
|
||||||
|
"id": {
|
||||||
|
"name": "id",
|
||||||
|
"type": "text",
|
||||||
|
"primaryKey": true,
|
||||||
|
"notNull": true,
|
||||||
|
"autoincrement": false
|
||||||
|
},
|
||||||
|
"name": {
|
||||||
|
"name": "name",
|
||||||
|
"type": "text",
|
||||||
|
"primaryKey": false,
|
||||||
|
"notNull": true,
|
||||||
|
"autoincrement": false
|
||||||
|
},
|
||||||
|
"email": {
|
||||||
|
"name": "email",
|
||||||
|
"type": "text",
|
||||||
|
"primaryKey": false,
|
||||||
|
"notNull": true,
|
||||||
|
"autoincrement": false
|
||||||
|
}
|
||||||
|
},
|
||||||
|
"indexes": {
|
||||||
|
"user_id_unique": {
|
||||||
|
"name": "user_id_unique",
|
||||||
|
"columns": [
|
||||||
|
"id"
|
||||||
|
],
|
||||||
|
"isUnique": true
|
||||||
|
}
|
||||||
|
},
|
||||||
|
"foreignKeys": {},
|
||||||
|
"compositePrimaryKeys": {},
|
||||||
|
"uniqueConstraints": {}
|
||||||
|
},
|
||||||
|
"users_to_sandboxes": {
|
||||||
|
"name": "users_to_sandboxes",
|
||||||
|
"columns": {
|
||||||
|
"userId": {
|
||||||
|
"name": "userId",
|
||||||
|
"type": "text",
|
||||||
|
"primaryKey": false,
|
||||||
|
"notNull": true,
|
||||||
|
"autoincrement": false
|
||||||
|
},
|
||||||
|
"sandboxId": {
|
||||||
|
"name": "sandboxId",
|
||||||
|
"type": "text",
|
||||||
|
"primaryKey": false,
|
||||||
|
"notNull": true,
|
||||||
|
"autoincrement": false
|
||||||
|
}
|
||||||
|
},
|
||||||
|
"indexes": {},
|
||||||
|
"foreignKeys": {
|
||||||
|
"users_to_sandboxes_userId_user_id_fk": {
|
||||||
|
"name": "users_to_sandboxes_userId_user_id_fk",
|
||||||
|
"tableFrom": "users_to_sandboxes",
|
||||||
|
"tableTo": "user",
|
||||||
|
"columnsFrom": [
|
||||||
|
"userId"
|
||||||
|
],
|
||||||
|
"columnsTo": [
|
||||||
|
"id"
|
||||||
|
],
|
||||||
|
"onDelete": "no action",
|
||||||
|
"onUpdate": "no action"
|
||||||
|
},
|
||||||
|
"users_to_sandboxes_sandboxId_sandbox_id_fk": {
|
||||||
|
"name": "users_to_sandboxes_sandboxId_sandbox_id_fk",
|
||||||
|
"tableFrom": "users_to_sandboxes",
|
||||||
|
"tableTo": "sandbox",
|
||||||
|
"columnsFrom": [
|
||||||
|
"sandboxId"
|
||||||
|
],
|
||||||
|
"columnsTo": [
|
||||||
|
"id"
|
||||||
|
],
|
||||||
|
"onDelete": "no action",
|
||||||
|
"onUpdate": "no action"
|
||||||
|
}
|
||||||
|
},
|
||||||
|
"compositePrimaryKeys": {},
|
||||||
|
"uniqueConstraints": {}
|
||||||
|
}
|
||||||
|
},
|
||||||
|
"enums": {},
|
||||||
|
"_meta": {
|
||||||
|
"schemas": {},
|
||||||
|
"tables": {},
|
||||||
|
"columns": {}
|
||||||
|
}
|
||||||
|
}
|
175
backend/database/drizzle/meta/0003_snapshot.json
Normal file
175
backend/database/drizzle/meta/0003_snapshot.json
Normal file
@ -0,0 +1,175 @@
|
|||||||
|
{
|
||||||
|
"version": "5",
|
||||||
|
"dialect": "sqlite",
|
||||||
|
"id": "37e38b82-1494-4818-8c26-b9024cce3fa9",
|
||||||
|
"prevId": "5baf10d6-7697-42ba-a11a-ee4c7bd7e91e",
|
||||||
|
"tables": {
|
||||||
|
"sandbox": {
|
||||||
|
"name": "sandbox",
|
||||||
|
"columns": {
|
||||||
|
"id": {
|
||||||
|
"name": "id",
|
||||||
|
"type": "text",
|
||||||
|
"primaryKey": true,
|
||||||
|
"notNull": true,
|
||||||
|
"autoincrement": false
|
||||||
|
},
|
||||||
|
"name": {
|
||||||
|
"name": "name",
|
||||||
|
"type": "text",
|
||||||
|
"primaryKey": false,
|
||||||
|
"notNull": true,
|
||||||
|
"autoincrement": false
|
||||||
|
},
|
||||||
|
"type": {
|
||||||
|
"name": "type",
|
||||||
|
"type": "text",
|
||||||
|
"primaryKey": false,
|
||||||
|
"notNull": true,
|
||||||
|
"autoincrement": false
|
||||||
|
},
|
||||||
|
"visibility": {
|
||||||
|
"name": "visibility",
|
||||||
|
"type": "text",
|
||||||
|
"primaryKey": false,
|
||||||
|
"notNull": false,
|
||||||
|
"autoincrement": false
|
||||||
|
},
|
||||||
|
"user_id": {
|
||||||
|
"name": "user_id",
|
||||||
|
"type": "text",
|
||||||
|
"primaryKey": false,
|
||||||
|
"notNull": true,
|
||||||
|
"autoincrement": false
|
||||||
|
}
|
||||||
|
},
|
||||||
|
"indexes": {
|
||||||
|
"sandbox_id_unique": {
|
||||||
|
"name": "sandbox_id_unique",
|
||||||
|
"columns": [
|
||||||
|
"id"
|
||||||
|
],
|
||||||
|
"isUnique": true
|
||||||
|
}
|
||||||
|
},
|
||||||
|
"foreignKeys": {
|
||||||
|
"sandbox_user_id_user_id_fk": {
|
||||||
|
"name": "sandbox_user_id_user_id_fk",
|
||||||
|
"tableFrom": "sandbox",
|
||||||
|
"tableTo": "user",
|
||||||
|
"columnsFrom": [
|
||||||
|
"user_id"
|
||||||
|
],
|
||||||
|
"columnsTo": [
|
||||||
|
"id"
|
||||||
|
],
|
||||||
|
"onDelete": "no action",
|
||||||
|
"onUpdate": "no action"
|
||||||
|
}
|
||||||
|
},
|
||||||
|
"compositePrimaryKeys": {},
|
||||||
|
"uniqueConstraints": {}
|
||||||
|
},
|
||||||
|
"user": {
|
||||||
|
"name": "user",
|
||||||
|
"columns": {
|
||||||
|
"id": {
|
||||||
|
"name": "id",
|
||||||
|
"type": "text",
|
||||||
|
"primaryKey": true,
|
||||||
|
"notNull": true,
|
||||||
|
"autoincrement": false
|
||||||
|
},
|
||||||
|
"name": {
|
||||||
|
"name": "name",
|
||||||
|
"type": "text",
|
||||||
|
"primaryKey": false,
|
||||||
|
"notNull": true,
|
||||||
|
"autoincrement": false
|
||||||
|
},
|
||||||
|
"email": {
|
||||||
|
"name": "email",
|
||||||
|
"type": "text",
|
||||||
|
"primaryKey": false,
|
||||||
|
"notNull": true,
|
||||||
|
"autoincrement": false
|
||||||
|
},
|
||||||
|
"image": {
|
||||||
|
"name": "image",
|
||||||
|
"type": "text",
|
||||||
|
"primaryKey": false,
|
||||||
|
"notNull": false,
|
||||||
|
"autoincrement": false
|
||||||
|
}
|
||||||
|
},
|
||||||
|
"indexes": {
|
||||||
|
"user_id_unique": {
|
||||||
|
"name": "user_id_unique",
|
||||||
|
"columns": [
|
||||||
|
"id"
|
||||||
|
],
|
||||||
|
"isUnique": true
|
||||||
|
}
|
||||||
|
},
|
||||||
|
"foreignKeys": {},
|
||||||
|
"compositePrimaryKeys": {},
|
||||||
|
"uniqueConstraints": {}
|
||||||
|
},
|
||||||
|
"users_to_sandboxes": {
|
||||||
|
"name": "users_to_sandboxes",
|
||||||
|
"columns": {
|
||||||
|
"userId": {
|
||||||
|
"name": "userId",
|
||||||
|
"type": "text",
|
||||||
|
"primaryKey": false,
|
||||||
|
"notNull": true,
|
||||||
|
"autoincrement": false
|
||||||
|
},
|
||||||
|
"sandboxId": {
|
||||||
|
"name": "sandboxId",
|
||||||
|
"type": "text",
|
||||||
|
"primaryKey": false,
|
||||||
|
"notNull": true,
|
||||||
|
"autoincrement": false
|
||||||
|
}
|
||||||
|
},
|
||||||
|
"indexes": {},
|
||||||
|
"foreignKeys": {
|
||||||
|
"users_to_sandboxes_userId_user_id_fk": {
|
||||||
|
"name": "users_to_sandboxes_userId_user_id_fk",
|
||||||
|
"tableFrom": "users_to_sandboxes",
|
||||||
|
"tableTo": "user",
|
||||||
|
"columnsFrom": [
|
||||||
|
"userId"
|
||||||
|
],
|
||||||
|
"columnsTo": [
|
||||||
|
"id"
|
||||||
|
],
|
||||||
|
"onDelete": "no action",
|
||||||
|
"onUpdate": "no action"
|
||||||
|
},
|
||||||
|
"users_to_sandboxes_sandboxId_sandbox_id_fk": {
|
||||||
|
"name": "users_to_sandboxes_sandboxId_sandbox_id_fk",
|
||||||
|
"tableFrom": "users_to_sandboxes",
|
||||||
|
"tableTo": "sandbox",
|
||||||
|
"columnsFrom": [
|
||||||
|
"sandboxId"
|
||||||
|
],
|
||||||
|
"columnsTo": [
|
||||||
|
"id"
|
||||||
|
],
|
||||||
|
"onDelete": "no action",
|
||||||
|
"onUpdate": "no action"
|
||||||
|
}
|
||||||
|
},
|
||||||
|
"compositePrimaryKeys": {},
|
||||||
|
"uniqueConstraints": {}
|
||||||
|
}
|
||||||
|
},
|
||||||
|
"enums": {},
|
||||||
|
"_meta": {
|
||||||
|
"schemas": {},
|
||||||
|
"tables": {},
|
||||||
|
"columns": {}
|
||||||
|
}
|
||||||
|
}
|
@ -1,13 +1,55 @@
|
|||||||
{
|
{
|
||||||
"version": "5",
|
"version": "5",
|
||||||
"dialect": "sqlite",
|
"dialect": "sqlite",
|
||||||
"entries": [
|
"entries": [
|
||||||
{
|
{
|
||||||
"idx": 0,
|
"idx": 0,
|
||||||
"version": "5",
|
"version": "5",
|
||||||
"when": 1718032216030,
|
"when": 1714540200800,
|
||||||
"tag": "0000_melodic_the_captain",
|
"tag": "0000_big_rogue",
|
||||||
"breakpoints": true
|
"breakpoints": true
|
||||||
}
|
},
|
||||||
]
|
{
|
||||||
}
|
"idx": 1,
|
||||||
|
"version": "5",
|
||||||
|
"when": 1714541190588,
|
||||||
|
"tag": "0001_empty_black_knight",
|
||||||
|
"breakpoints": true
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"idx": 2,
|
||||||
|
"version": "5",
|
||||||
|
"when": 1714541209173,
|
||||||
|
"tag": "0002_sour_ego",
|
||||||
|
"breakpoints": true
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"idx": 3,
|
||||||
|
"version": "5",
|
||||||
|
"when": 1714541233589,
|
||||||
|
"tag": "0003_pale_overlord",
|
||||||
|
"breakpoints": true
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"idx": 4,
|
||||||
|
"version": "5",
|
||||||
|
"when": 1714565073180,
|
||||||
|
"tag": "0004_cuddly_wolf_cub",
|
||||||
|
"breakpoints": true
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"idx": 5,
|
||||||
|
"version": "5",
|
||||||
|
"when": 1714950365718,
|
||||||
|
"tag": "0005_last_the_twelve",
|
||||||
|
"breakpoints": true
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"idx": 6,
|
||||||
|
"version": "5",
|
||||||
|
"when": 1716432225404,
|
||||||
|
"tag": "0006_lively_mattie_franklin",
|
||||||
|
"breakpoints": true
|
||||||
|
}
|
||||||
|
]
|
||||||
|
}
|
@ -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,
|
||||||
})
|
})
|
||||||
|
@ -31,7 +31,7 @@ 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;
|
||||||
|
@ -5,3 +5,4 @@ PORT=4000
|
|||||||
WORKERS_KEY=
|
WORKERS_KEY=
|
||||||
DATABASE_WORKER_URL=
|
DATABASE_WORKER_URL=
|
||||||
STORAGE_WORKER_URL=
|
STORAGE_WORKER_URL=
|
||||||
|
E2B_API_KEY=
|
131
backend/server/package-lock.json
generated
131
backend/server/package-lock.json
generated
@ -12,8 +12,8 @@
|
|||||||
"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"
|
||||||
@ -369,6 +369,19 @@
|
|||||||
"node": ">=8"
|
"node": ">=8"
|
||||||
}
|
}
|
||||||
},
|
},
|
||||||
|
"node_modules/bufferutil": {
|
||||||
|
"version": "4.0.8",
|
||||||
|
"resolved": "https://registry.npmjs.org/bufferutil/-/bufferutil-4.0.8.tgz",
|
||||||
|
"integrity": "sha512-4T53u4PdgsXqKaIctwF8ifXlRTTmEPJ8iEPWFdGZvcf7sbwYo6FKFEX9eNNAnzFZ7EzJAQ3CJeOtCRA4rDp7Pw==",
|
||||||
|
"hasInstallScript": true,
|
||||||
|
"optional": true,
|
||||||
|
"dependencies": {
|
||||||
|
"node-gyp-build": "^4.3.0"
|
||||||
|
},
|
||||||
|
"engines": {
|
||||||
|
"node": ">=6.14.2"
|
||||||
|
}
|
||||||
|
},
|
||||||
"node_modules/bytes": {
|
"node_modules/bytes": {
|
||||||
"version": "3.1.2",
|
"version": "3.1.2",
|
||||||
"resolved": "https://registry.npmjs.org/bytes/-/bytes-3.1.2.tgz",
|
"resolved": "https://registry.npmjs.org/bytes/-/bytes-3.1.2.tgz",
|
||||||
@ -662,6 +675,59 @@
|
|||||||
"url": "https://dotenvx.com"
|
"url": "https://dotenvx.com"
|
||||||
}
|
}
|
||||||
},
|
},
|
||||||
|
"node_modules/e2b": {
|
||||||
|
"version": "0.16.1",
|
||||||
|
"resolved": "https://registry.npmjs.org/e2b/-/e2b-0.16.1.tgz",
|
||||||
|
"integrity": "sha512-2L1R/REEB+EezD4Q4MmcXXNATjvCYov2lv/69+PY6V95+wl1PZblIMTYAe7USxX6P6sqANxNs+kXqZr6RvXkSw==",
|
||||||
|
"dependencies": {
|
||||||
|
"isomorphic-ws": "^5.0.0",
|
||||||
|
"normalize-path": "^3.0.0",
|
||||||
|
"openapi-typescript-fetch": "^1.1.3",
|
||||||
|
"path-browserify": "^1.0.1",
|
||||||
|
"platform": "^1.3.6",
|
||||||
|
"ws": "^8.15.1"
|
||||||
|
},
|
||||||
|
"engines": {
|
||||||
|
"node": ">=18"
|
||||||
|
},
|
||||||
|
"optionalDependencies": {
|
||||||
|
"bufferutil": "^4.0.8",
|
||||||
|
"utf-8-validate": "^6.0.3"
|
||||||
|
}
|
||||||
|
},
|
||||||
|
"node_modules/e2b/node_modules/utf-8-validate": {
|
||||||
|
"version": "6.0.4",
|
||||||
|
"resolved": "https://registry.npmjs.org/utf-8-validate/-/utf-8-validate-6.0.4.tgz",
|
||||||
|
"integrity": "sha512-xu9GQDeFp+eZ6LnCywXN/zBancWvOpUMzgjLPSjy4BRHSmTelvn2E0DG0o1sTiw5hkCKBHo8rwSKncfRfv2EEQ==",
|
||||||
|
"hasInstallScript": true,
|
||||||
|
"optional": true,
|
||||||
|
"dependencies": {
|
||||||
|
"node-gyp-build": "^4.3.0"
|
||||||
|
},
|
||||||
|
"engines": {
|
||||||
|
"node": ">=6.14.2"
|
||||||
|
}
|
||||||
|
},
|
||||||
|
"node_modules/e2b/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/ee-first": {
|
"node_modules/ee-first": {
|
||||||
"version": "1.1.1",
|
"version": "1.1.1",
|
||||||
"resolved": "https://registry.npmjs.org/ee-first/-/ee-first-1.1.1.tgz",
|
"resolved": "https://registry.npmjs.org/ee-first/-/ee-first-1.1.1.tgz",
|
||||||
@ -1082,6 +1148,14 @@
|
|||||||
"node": ">=0.12.0"
|
"node": ">=0.12.0"
|
||||||
}
|
}
|
||||||
},
|
},
|
||||||
|
"node_modules/isomorphic-ws": {
|
||||||
|
"version": "5.0.0",
|
||||||
|
"resolved": "https://registry.npmjs.org/isomorphic-ws/-/isomorphic-ws-5.0.0.tgz",
|
||||||
|
"integrity": "sha512-muId7Zzn9ywDsyXgTIafTry2sV3nySZeUDe6YedVd1Hvuuep5AsIlqK+XefWpYTyJG5e503F2xIuT2lcU6rCSw==",
|
||||||
|
"peerDependencies": {
|
||||||
|
"ws": "*"
|
||||||
|
}
|
||||||
|
},
|
||||||
"node_modules/lodash": {
|
"node_modules/lodash": {
|
||||||
"version": "4.17.21",
|
"version": "4.17.21",
|
||||||
"resolved": "https://registry.npmjs.org/lodash/-/lodash-4.17.21.tgz",
|
"resolved": "https://registry.npmjs.org/lodash/-/lodash-4.17.21.tgz",
|
||||||
@ -1173,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",
|
||||||
@ -1186,13 +1255,15 @@
|
|||||||
"node": ">= 0.6"
|
"node": ">= 0.6"
|
||||||
}
|
}
|
||||||
},
|
},
|
||||||
"node_modules/node-pty": {
|
"node_modules/node-gyp-build": {
|
||||||
"version": "1.0.0",
|
"version": "4.8.1",
|
||||||
"resolved": "https://registry.npmjs.org/node-pty/-/node-pty-1.0.0.tgz",
|
"resolved": "https://registry.npmjs.org/node-gyp-build/-/node-gyp-build-4.8.1.tgz",
|
||||||
"integrity": "sha512-wtBMWWS7dFZm/VgqElrTvtfMq4GzJ6+edFI0Y0zyzygUSZMgZdraDUMUhCIvkjhJjme15qWmbyJbtAx4ot4uZA==",
|
"integrity": "sha512-OSs33Z9yWr148JZcbZd5WiAXhh/n9z8TxQcdMhIOlpN9AhWpLfvVFO73+m77bBABQMaY9XSvIa+qk0jlI7Gcaw==",
|
||||||
"hasInstallScript": true,
|
"optional": true,
|
||||||
"dependencies": {
|
"bin": {
|
||||||
"nan": "^2.17.0"
|
"node-gyp-build": "bin.js",
|
||||||
|
"node-gyp-build-optional": "optional.js",
|
||||||
|
"node-gyp-build-test": "build-test.js"
|
||||||
}
|
}
|
||||||
},
|
},
|
||||||
"node_modules/nodemon": {
|
"node_modules/nodemon": {
|
||||||
@ -1265,7 +1336,6 @@
|
|||||||
"version": "3.0.0",
|
"version": "3.0.0",
|
||||||
"resolved": "https://registry.npmjs.org/normalize-path/-/normalize-path-3.0.0.tgz",
|
"resolved": "https://registry.npmjs.org/normalize-path/-/normalize-path-3.0.0.tgz",
|
||||||
"integrity": "sha512-6eZs5Ls3WtCisHWp9S2GUy8dqkpGi4BVSz3GaqiE6ezub0512ESztXUwUB6C6IKbQkY2Pnb/mD4WYojCRwcwLA==",
|
"integrity": "sha512-6eZs5Ls3WtCisHWp9S2GUy8dqkpGi4BVSz3GaqiE6ezub0512ESztXUwUB6C6IKbQkY2Pnb/mD4WYojCRwcwLA==",
|
||||||
"dev": true,
|
|
||||||
"engines": {
|
"engines": {
|
||||||
"node": ">=0.10.0"
|
"node": ">=0.10.0"
|
||||||
}
|
}
|
||||||
@ -1297,6 +1367,15 @@
|
|||||||
"node": ">= 0.8"
|
"node": ">= 0.8"
|
||||||
}
|
}
|
||||||
},
|
},
|
||||||
|
"node_modules/openapi-typescript-fetch": {
|
||||||
|
"version": "1.1.3",
|
||||||
|
"resolved": "https://registry.npmjs.org/openapi-typescript-fetch/-/openapi-typescript-fetch-1.1.3.tgz",
|
||||||
|
"integrity": "sha512-smLZPck4OkKMNExcw8jMgrMOGgVGx2N/s6DbKL2ftNl77g5HfoGpZGFy79RBzU/EkaO0OZpwBnslfdBfh7ZcWg==",
|
||||||
|
"engines": {
|
||||||
|
"node": ">= 12.0.0",
|
||||||
|
"npm": ">= 7.0.0"
|
||||||
|
}
|
||||||
|
},
|
||||||
"node_modules/parseurl": {
|
"node_modules/parseurl": {
|
||||||
"version": "1.3.3",
|
"version": "1.3.3",
|
||||||
"resolved": "https://registry.npmjs.org/parseurl/-/parseurl-1.3.3.tgz",
|
"resolved": "https://registry.npmjs.org/parseurl/-/parseurl-1.3.3.tgz",
|
||||||
@ -1305,6 +1384,11 @@
|
|||||||
"node": ">= 0.8"
|
"node": ">= 0.8"
|
||||||
}
|
}
|
||||||
},
|
},
|
||||||
|
"node_modules/path-browserify": {
|
||||||
|
"version": "1.0.1",
|
||||||
|
"resolved": "https://registry.npmjs.org/path-browserify/-/path-browserify-1.0.1.tgz",
|
||||||
|
"integrity": "sha512-b7uo2UCUOYZcnF/3ID0lulOJi/bafxa1xPe7ZPsammBSpjSWQkjNxlt635YGS2MiR9GjvuXCtz2emr3jbsz98g=="
|
||||||
|
},
|
||||||
"node_modules/path-to-regexp": {
|
"node_modules/path-to-regexp": {
|
||||||
"version": "0.1.7",
|
"version": "0.1.7",
|
||||||
"resolved": "https://registry.npmjs.org/path-to-regexp/-/path-to-regexp-0.1.7.tgz",
|
"resolved": "https://registry.npmjs.org/path-to-regexp/-/path-to-regexp-0.1.7.tgz",
|
||||||
@ -1322,6 +1406,11 @@
|
|||||||
"url": "https://github.com/sponsors/jonschlinkert"
|
"url": "https://github.com/sponsors/jonschlinkert"
|
||||||
}
|
}
|
||||||
},
|
},
|
||||||
|
"node_modules/platform": {
|
||||||
|
"version": "1.3.6",
|
||||||
|
"resolved": "https://registry.npmjs.org/platform/-/platform-1.3.6.tgz",
|
||||||
|
"integrity": "sha512-fnWVljUchTro6RiCFvCXBbNhJc2NijN7oIQxbwsyL0buWJPG85v81ehlHI9fXrJsMNgTofEoWIQeClKpgxFLrg=="
|
||||||
|
},
|
||||||
"node_modules/proxy-addr": {
|
"node_modules/proxy-addr": {
|
||||||
"version": "2.0.7",
|
"version": "2.0.7",
|
||||||
"resolved": "https://registry.npmjs.org/proxy-addr/-/proxy-addr-2.0.7.tgz",
|
"resolved": "https://registry.npmjs.org/proxy-addr/-/proxy-addr-2.0.7.tgz",
|
||||||
@ -1835,6 +1924,20 @@
|
|||||||
"node": ">= 0.8"
|
"node": ">= 0.8"
|
||||||
}
|
}
|
||||||
},
|
},
|
||||||
|
"node_modules/utf-8-validate": {
|
||||||
|
"version": "5.0.10",
|
||||||
|
"resolved": "https://registry.npmjs.org/utf-8-validate/-/utf-8-validate-5.0.10.tgz",
|
||||||
|
"integrity": "sha512-Z6czzLq4u8fPOyx7TU6X3dvUZVvoJmxSQ+IcrlmagKhilxlhZgxPK6C5Jqbkw1IDUmFTM+cz9QDnnLTwDz/2gQ==",
|
||||||
|
"hasInstallScript": true,
|
||||||
|
"optional": true,
|
||||||
|
"peer": true,
|
||||||
|
"dependencies": {
|
||||||
|
"node-gyp-build": "^4.3.0"
|
||||||
|
},
|
||||||
|
"engines": {
|
||||||
|
"node": ">=6.14.2"
|
||||||
|
}
|
||||||
|
},
|
||||||
"node_modules/utils-merge": {
|
"node_modules/utils-merge": {
|
||||||
"version": "1.0.1",
|
"version": "1.0.1",
|
||||||
"resolved": "https://registry.npmjs.org/utils-merge/-/utils-merge-1.0.1.tgz",
|
"resolved": "https://registry.npmjs.org/utils-merge/-/utils-merge-1.0.1.tgz",
|
||||||
|
@ -14,8 +14,8 @@
|
|||||||
"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 { IDisposable, IPty, spawn } from "node-pty";
|
import { LockManager } from "./utils";
|
||||||
|
import { Sandbox, Terminal, FilesystemManager } from "e2b";
|
||||||
import {
|
import {
|
||||||
MAX_BODY_SIZE,
|
MAX_BODY_SIZE,
|
||||||
createFileRL,
|
createFileRL,
|
||||||
@ -43,11 +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]: { terminal: IPty; onData: IDisposable; onExit: IDisposable };
|
const connections: Record<string, number> = {};
|
||||||
} = {};
|
const terminals: Record<string, Terminal> = {};
|
||||||
|
|
||||||
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({
|
||||||
@ -100,364 +110,490 @@ io.use(async (socket, next) => {
|
|||||||
next();
|
next();
|
||||||
});
|
});
|
||||||
|
|
||||||
|
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;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
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);
|
|
||||||
});
|
|
||||||
|
|
||||||
socket.on("createTerminal", (id: string, callback) => {
|
|
||||||
if (terminals[id] || Object.keys(terminals).length >= 4) {
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
|
|
||||||
const pty = spawn(os.platform() === "win32" ? "cmd.exe" : "bash", [], {
|
|
||||||
name: "xterm",
|
|
||||||
cols: 100,
|
|
||||||
cwd: path.join(dirName, "projects", data.sandboxId),
|
|
||||||
});
|
|
||||||
|
|
||||||
const onData = pty.onData((data) => {
|
|
||||||
io.emit("terminalResponse", {
|
|
||||||
id,
|
|
||||||
data,
|
|
||||||
});
|
|
||||||
});
|
|
||||||
|
|
||||||
const onExit = pty.onExit((code) => console.log("exit :(", code));
|
|
||||||
|
|
||||||
pty.write("export PS1='\\u > '\r");
|
|
||||||
pty.write("clear\r");
|
|
||||||
|
|
||||||
terminals[id] = {
|
|
||||||
terminal: pty,
|
|
||||||
onData,
|
|
||||||
onExit,
|
|
||||||
};
|
};
|
||||||
|
|
||||||
callback();
|
|
||||||
});
|
|
||||||
|
|
||||||
socket.on("resizeTerminal", (dimensions: { cols: number; rows: number }) => {
|
|
||||||
Object.values(terminals).forEach((t) => {
|
|
||||||
t.terminal.resize(dimensions.cols, dimensions.rows);
|
|
||||||
});
|
|
||||||
});
|
|
||||||
|
|
||||||
socket.on("terminalData", (id: string, data: string) => {
|
|
||||||
if (!terminals[id]) {
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
|
|
||||||
try {
|
|
||||||
terminals[id].terminal.write(data);
|
|
||||||
} catch (e) {
|
|
||||||
console.log("Error writing to terminal", e);
|
|
||||||
}
|
|
||||||
});
|
|
||||||
|
|
||||||
socket.on("closeTerminal", (id: string, callback) => {
|
|
||||||
if (!terminals[id]) {
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
|
|
||||||
terminals[id].onData.dispose();
|
|
||||||
terminals[id].onExit.dispose();
|
|
||||||
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 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 });
|
|
||||||
}
|
|
||||||
);
|
|
||||||
|
|
||||||
socket.on("disconnect", async () => {
|
|
||||||
if (data.isOwner) {
|
if (data.isOwner) {
|
||||||
Object.entries(terminals).forEach((t) => {
|
isOwnerConnected = true;
|
||||||
const { terminal, onData, onExit } = t[1];
|
connections[data.sandboxId] = (connections[data.sandboxId] ?? 0) + 1;
|
||||||
onData.dispose();
|
} else {
|
||||||
onExit.dispose();
|
if (!isOwnerConnected) {
|
||||||
delete terminals[t[0]];
|
socket.emit("disableAccess", "The sandbox owner is not connected.");
|
||||||
});
|
return;
|
||||||
|
}
|
||||||
socket.broadcast.emit(
|
|
||||||
"disableAccess",
|
|
||||||
"The sandbox owner has disconnected."
|
|
||||||
);
|
|
||||||
}
|
}
|
||||||
|
|
||||||
// const sockets = await io.fetchSockets();
|
await lockManager.acquireLock(data.sandboxId, async () => {
|
||||||
// if (inactivityTimeout) {
|
try {
|
||||||
// clearTimeout(inactivityTimeout);
|
if (!containers[data.sandboxId]) {
|
||||||
// }
|
containers[data.sandboxId] = await Sandbox.create();
|
||||||
// if (sockets.length === 0) {
|
console.log("Created container ", data.sandboxId);
|
||||||
// console.log("STARTING TIMER");
|
io.emit(
|
||||||
// inactivityTimeout = setTimeout(() => {
|
"previewURL",
|
||||||
// io.fetchSockets().then(async (sockets) => {
|
"https://" + containers[data.sandboxId].getHostname(5173)
|
||||||
// if (sockets.length === 0) {
|
);
|
||||||
// console.log("Server stopped", res);
|
}
|
||||||
// }
|
} catch (e: any) {
|
||||||
// });
|
console.error(`Error creating container ${data.sandboxId}:`, e);
|
||||||
// }, 20000);
|
io.emit("error", `Error: container creation. ${e.message ?? e}`);
|
||||||
// } else {
|
}
|
||||||
// console.log("number of sockets", sockets.length);
|
});
|
||||||
// }
|
|
||||||
});
|
// 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);
|
||||||
|
sandboxFiles.fileData.forEach(async (file) => {
|
||||||
|
const filePath = path.join(dirName, file.id);
|
||||||
|
await containers[data.sandboxId].filesystem.makeDir(
|
||||||
|
path.dirname(filePath)
|
||||||
|
);
|
||||||
|
await containers[data.sandboxId].filesystem.write(filePath, file.data);
|
||||||
|
});
|
||||||
|
fixPermissions();
|
||||||
|
|
||||||
|
socket.emit("loaded", sandboxFiles.files);
|
||||||
|
|
||||||
|
socket.on("getFile", (fileId: string, callback) => {
|
||||||
|
console.log(fileId);
|
||||||
|
try {
|
||||||
|
const file = sandboxFiles.fileData.find((f) => f.id === fileId);
|
||||||
|
if (!file) return;
|
||||||
|
|
||||||
|
callback(file.data);
|
||||||
|
} catch (e: any) {
|
||||||
|
console.error("Error getting file:", e);
|
||||||
|
io.emit("error", `Error: get file. ${e.message ?? e}`);
|
||||||
|
}
|
||||||
|
});
|
||||||
|
|
||||||
|
socket.on("getFolder", async (folderId: string, callback) => {
|
||||||
|
try {
|
||||||
|
const files = await getFolder(folderId);
|
||||||
|
callback(files);
|
||||||
|
} catch (e: any) {
|
||||||
|
console.error("Error getting folder:", e);
|
||||||
|
io.emit("error", `Error: get folder. ${e.message ?? e}`);
|
||||||
|
}
|
||||||
|
});
|
||||||
|
|
||||||
|
// todo: send diffs + debounce for efficiency
|
||||||
|
socket.on("saveFile", async (fileId: string, body: string) => {
|
||||||
|
try {
|
||||||
|
if (Buffer.byteLength(body, "utf-8") > MAX_BODY_SIZE) {
|
||||||
|
socket.emit(
|
||||||
|
"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;
|
||||||
|
}
|
||||||
|
|
||||||
|
const file = sandboxFiles.fileData.find((f) => f.id === fileId);
|
||||||
|
if (!file) return;
|
||||||
|
file.data = body;
|
||||||
|
|
||||||
|
await containers[data.sandboxId].filesystem.write(
|
||||||
|
path.join(dirName, file.id),
|
||||||
|
body
|
||||||
|
);
|
||||||
|
fixPermissions();
|
||||||
|
} catch (e: any) {
|
||||||
|
console.error("Error saving file:", e);
|
||||||
|
io.emit("error", `Error: file saving. ${e.message ?? e}`);
|
||||||
|
}
|
||||||
|
});
|
||||||
|
|
||||||
|
socket.on(
|
||||||
|
"moveFile",
|
||||||
|
async (fileId: string, folderId: string, callback) => {
|
||||||
|
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;
|
}
|
||||||
};
|
}
|
@ -6,6 +6,7 @@ import { ThemeProvider } from "@/components/layout/themeProvider"
|
|||||||
import { ClerkProvider } from "@clerk/nextjs"
|
import { ClerkProvider } from "@clerk/nextjs"
|
||||||
import { Toaster } from "@/components/ui/sonner"
|
import { Toaster } from "@/components/ui/sonner"
|
||||||
import { Analytics } from "@vercel/analytics/react"
|
import { Analytics } from "@vercel/analytics/react"
|
||||||
|
import { TerminalProvider } from '@/context/TerminalContext';
|
||||||
|
|
||||||
export const metadata: Metadata = {
|
export const metadata: Metadata = {
|
||||||
title: "Sandbox",
|
title: "Sandbox",
|
||||||
@ -27,7 +28,9 @@ export default function RootLayout({
|
|||||||
forcedTheme="dark"
|
forcedTheme="dark"
|
||||||
disableTransitionOnChange
|
disableTransitionOnChange
|
||||||
>
|
>
|
||||||
|
<TerminalProvider>
|
||||||
{children}
|
{children}
|
||||||
|
</TerminalProvider>
|
||||||
<Analytics />
|
<Analytics />
|
||||||
<Toaster position="bottom-left" richColors />
|
<Toaster position="bottom-left" richColors />
|
||||||
</ThemeProvider>
|
</ThemeProvider>
|
||||||
|
@ -46,7 +46,7 @@ export default function CodeEditor({
|
|||||||
// Initialize socket connection if it doesn't exist
|
// Initialize socket connection if it doesn't exist
|
||||||
if (!socketRef.current) {
|
if (!socketRef.current) {
|
||||||
socketRef.current = io(
|
socketRef.current = io(
|
||||||
`http://localhost:${process.env.NEXT_PUBLIC_SERVER_PORT}?userId=${userData.id}&sandboxId=${sandboxData.id}`,
|
`${window.location.protocol}//${window.location.hostname}:${process.env.NEXT_PUBLIC_SERVER_PORT}?userId=${userData.id}&sandboxId=${sandboxData.id}`,
|
||||||
{
|
{
|
||||||
timeout: 2000,
|
timeout: 2000,
|
||||||
}
|
}
|
||||||
@ -94,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()
|
||||||
|
|
||||||
@ -322,50 +325,90 @@ export default function CodeEditor({
|
|||||||
};
|
};
|
||||||
}, [activeFileId, tabs, debouncedSaveData]);
|
}, [activeFileId, tabs, debouncedSaveData]);
|
||||||
|
|
||||||
// Liveblocks live collaboration setup effect
|
// Liveblocks live collaboration setup effect
|
||||||
|
|
||||||
|
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>());
|
||||||
|
|
||||||
useEffect(() => {
|
useEffect(() => {
|
||||||
const tab = tabs.find((t) => t.id === activeFileId)
|
const tab = tabs.find((t) => t.id === activeFileId);
|
||||||
const model = editorRef?.getModel()
|
const model = editorRef?.getModel();
|
||||||
|
|
||||||
|
if (!editorRef || !tab || !model) return;
|
||||||
|
|
||||||
|
let providerData: ProviderData;
|
||||||
|
|
||||||
|
if (!providersMap.current.has(tab.id)) {
|
||||||
|
const yDoc = new Y.Doc();
|
||||||
|
const yText = yDoc.getText(tab.id);
|
||||||
|
const yProvider = new LiveblocksProvider(room, yDoc);
|
||||||
|
|
||||||
if (!editorRef || !tab || !model) return
|
const onSync = (isSynced: boolean) => {
|
||||||
|
if (isSynced) {
|
||||||
const yDoc = new Y.Doc()
|
const text = yText.toString()
|
||||||
const yText = yDoc.getText(tab.id)
|
if (text === "") {
|
||||||
const yProvider: any = new LiveblocksProvider(room, yDoc)
|
if (activeFileContent) {
|
||||||
|
yText.insert(0, activeFileContent)
|
||||||
const onSync = (isSynced: boolean) => {
|
} else {
|
||||||
if (isSynced) {
|
setTimeout(() => {
|
||||||
const text = yText.toString()
|
yText.insert(0, editorRef.getValue())
|
||||||
if (text === "") {
|
}, 0)
|
||||||
if (activeFileContent) {
|
}
|
||||||
yText.insert(0, activeFileContent)
|
|
||||||
} else {
|
|
||||||
setTimeout(() => {
|
|
||||||
yText.insert(0, editorRef.getValue())
|
|
||||||
}, 0)
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
yProvider.on("sync", onSync);
|
||||||
|
|
||||||
|
providerData = { provider: yProvider, yDoc, yText, onSync };
|
||||||
|
providersMap.current.set(tab.id, providerData);
|
||||||
|
} else {
|
||||||
|
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;
|
||||||
|
}
|
||||||
|
};
|
||||||
|
}, [editorRef, room, activeFileContent, activeFileId, tabs]);
|
||||||
|
|
||||||
|
// 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(() => {
|
||||||
@ -388,7 +431,7 @@ export default function CodeEditor({
|
|||||||
setFiles(files)
|
setFiles(files)
|
||||||
}
|
}
|
||||||
|
|
||||||
const onRateLimit = (message: string) => {
|
const onError = (message: string) => {
|
||||||
toast.error(message)
|
toast.error(message)
|
||||||
}
|
}
|
||||||
|
|
||||||
@ -410,17 +453,19 @@ export default function CodeEditor({
|
|||||||
socketRef.current?.on("connect", onConnect)
|
socketRef.current?.on("connect", onConnect)
|
||||||
socketRef.current?.on("disconnect", onDisconnect)
|
socketRef.current?.on("disconnect", onDisconnect)
|
||||||
socketRef.current?.on("loaded", onLoadedEvent)
|
socketRef.current?.on("loaded", onLoadedEvent)
|
||||||
socketRef.current?.on("rateLimit", onRateLimit)
|
socketRef.current?.on("error", onError)
|
||||||
socketRef.current?.on("terminalResponse", onTerminalResponse)
|
socketRef.current?.on("terminalResponse", onTerminalResponse)
|
||||||
socketRef.current?.on("disableAccess", onDisableAccess)
|
socketRef.current?.on("disableAccess", onDisableAccess)
|
||||||
|
socketRef.current?.on("previewURL", setPreviewURL)
|
||||||
|
|
||||||
return () => {
|
return () => {
|
||||||
socketRef.current?.off("connect", onConnect)
|
socketRef.current?.off("connect", onConnect)
|
||||||
socketRef.current?.off("disconnect", onDisconnect)
|
socketRef.current?.off("disconnect", onDisconnect)
|
||||||
socketRef.current?.off("loaded", onLoadedEvent)
|
socketRef.current?.off("loaded", onLoadedEvent)
|
||||||
socketRef.current?.off("rateLimit", onRateLimit)
|
socketRef.current?.off("error", onError)
|
||||||
socketRef.current?.off("terminalResponse", onTerminalResponse)
|
socketRef.current?.off("terminalResponse", onTerminalResponse)
|
||||||
socketRef.current?.off("disableAccess", onDisableAccess)
|
socketRef.current?.off("disableAccess", onDisableAccess)
|
||||||
|
socketRef.current?.off("previewURL", setPreviewURL)
|
||||||
}
|
}
|
||||||
// }, []);
|
// }, []);
|
||||||
}, [terminals])
|
}, [terminals])
|
||||||
@ -445,23 +490,29 @@ export default function CodeEditor({
|
|||||||
|
|
||||||
setGenerate((prev) => ({ ...prev, show: false }));
|
setGenerate((prev) => ({ ...prev, show: false }));
|
||||||
|
|
||||||
const exists = tabs.find((t) => t.id === tab.id);
|
//editor windows fix
|
||||||
setTabs((prev) => {
|
function updateTabs(){
|
||||||
if (exists) {
|
const exists = tabs.find((t) => t.id === tab.id);
|
||||||
setActiveFileId(exists.id);
|
setTabs((prev) => {
|
||||||
return prev;
|
if (exists) {
|
||||||
}
|
setActiveFileId(exists.id);
|
||||||
return [...prev, tab];
|
return prev;
|
||||||
});
|
}
|
||||||
|
return [...prev, tab];
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
if (fileCache.current.has(tab.id)) {
|
if (fileCache.current.has(tab.id)) {
|
||||||
setActiveFileContent(fileCache.current.get(tab.id));
|
setActiveFileContent(fileCache.current.get(tab.id));
|
||||||
|
updateTabs();
|
||||||
} else {
|
} else {
|
||||||
debouncedGetFile(tab.id, (response: SetStateAction<string>) => {
|
debouncedGetFile(tab.id, (response: SetStateAction<string>) => {
|
||||||
fileCache.current.set(tab.id, response);
|
fileCache.current.set(tab.id, response);
|
||||||
setActiveFileContent(response);
|
setActiveFileContent(response);
|
||||||
|
updateTabs();
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
|
|
||||||
setEditorLanguage(processFileType(tab.name));
|
setEditorLanguage(processFileType(tab.name));
|
||||||
setActiveFileId(tab.id);
|
setActiveFileId(tab.id);
|
||||||
}, [activeFileId, tabs, debouncedGetFile]);
|
}, [activeFileId, tabs, debouncedGetFile]);
|
||||||
@ -768,6 +819,7 @@ export default function CodeEditor({
|
|||||||
previewPanelRef.current?.expand()
|
previewPanelRef.current?.expand()
|
||||||
setIsPreviewCollapsed(false)
|
setIsPreviewCollapsed(false)
|
||||||
}}
|
}}
|
||||||
|
src={previewURL}
|
||||||
/>
|
/>
|
||||||
</ResizablePanel>
|
</ResizablePanel>
|
||||||
<ResizableHandle />
|
<ResizableHandle />
|
||||||
@ -777,11 +829,7 @@ export default function CodeEditor({
|
|||||||
className="p-2 flex flex-col"
|
className="p-2 flex flex-col"
|
||||||
>
|
>
|
||||||
{isOwner ? (
|
{isOwner ? (
|
||||||
<Terminals
|
<Terminals/>
|
||||||
terminals={terminals}
|
|
||||||
setTerminals={setTerminals}
|
|
||||||
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">
|
||||||
<TerminalSquare className="w-4 h-4 mr-2" />
|
<TerminalSquare className="w-4 h-4 mr-2" />
|
||||||
|
@ -2,7 +2,7 @@
|
|||||||
|
|
||||||
import Image from "next/image";
|
import Image from "next/image";
|
||||||
import Logo from "@/assets/logo.svg";
|
import Logo from "@/assets/logo.svg";
|
||||||
import { Pencil, Users } from "lucide-react";
|
import { Pencil, Users, Play, StopCircle } from "lucide-react";
|
||||||
import Link from "next/link";
|
import Link from "next/link";
|
||||||
import { Sandbox, User } from "@/lib/types";
|
import { Sandbox, User } from "@/lib/types";
|
||||||
import UserButton from "@/components/ui/userButton";
|
import UserButton from "@/components/ui/userButton";
|
||||||
@ -11,23 +11,30 @@ import { useState } from "react";
|
|||||||
import EditSandboxModal from "./edit";
|
import EditSandboxModal from "./edit";
|
||||||
import ShareSandboxModal from "./share";
|
import ShareSandboxModal from "./share";
|
||||||
import { Avatars } from "../live/avatars";
|
import { Avatars } from "../live/avatars";
|
||||||
|
import RunButtonModal from "./run";
|
||||||
|
import { Terminal } from "@xterm/xterm";
|
||||||
|
import { Socket } from "socket.io-client";
|
||||||
|
import Terminals from "../terminals";
|
||||||
|
|
||||||
export default function Navbar({
|
export default function Navbar({
|
||||||
userData,
|
userData,
|
||||||
sandboxData,
|
sandboxData,
|
||||||
shared,
|
shared,
|
||||||
|
socket,
|
||||||
}: {
|
}: {
|
||||||
userData: User;
|
userData: User;
|
||||||
sandboxData: Sandbox;
|
sandboxData: Sandbox;
|
||||||
shared: {
|
shared: { id: string; name: string }[];
|
||||||
id: string;
|
socket: Socket;
|
||||||
name: string;
|
|
||||||
}[];
|
|
||||||
}) {
|
}) {
|
||||||
const [isEditOpen, setIsEditOpen] = useState(false);
|
const [isEditOpen, setIsEditOpen] = useState(false);
|
||||||
const [isShareOpen, setIsShareOpen] = useState(false);
|
const [isShareOpen, setIsShareOpen] = useState(false);
|
||||||
|
const [isRunning, setIsRunning] = useState(false);
|
||||||
|
const [terminals, setTerminals] = useState<{ id: string; terminal: Terminal | null }[]>([]);
|
||||||
|
const [activeTerminalId, setActiveTerminalId] = useState("");
|
||||||
|
const [creatingTerminal, setCreatingTerminal] = useState(false);
|
||||||
|
|
||||||
const isOwner = sandboxData.userId === userData.id;
|
const isOwner = sandboxData.userId === userData.id;;
|
||||||
|
|
||||||
return (
|
return (
|
||||||
<>
|
<>
|
||||||
@ -62,6 +69,10 @@ export default function Navbar({
|
|||||||
) : null}
|
) : null}
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
|
<RunButtonModal
|
||||||
|
isRunning={isRunning}
|
||||||
|
setIsRunning={setIsRunning}
|
||||||
|
/>
|
||||||
<div className="flex items-center h-full space-x-4">
|
<div className="flex items-center h-full space-x-4">
|
||||||
<Avatars />
|
<Avatars />
|
||||||
|
|
||||||
|
60
frontend/components/editor/navbar/run.tsx
Normal file
60
frontend/components/editor/navbar/run.tsx
Normal file
@ -0,0 +1,60 @@
|
|||||||
|
"use client";
|
||||||
|
|
||||||
|
import { Play, StopCircle } from "lucide-react";
|
||||||
|
import { Button } from "@/components/ui/button";
|
||||||
|
import { useTerminal } from "@/context/TerminalContext";
|
||||||
|
import { closeTerminal } from "@/lib/terminal";
|
||||||
|
|
||||||
|
export default function RunButtonModal({
|
||||||
|
isRunning,
|
||||||
|
setIsRunning,
|
||||||
|
}: {
|
||||||
|
isRunning: boolean;
|
||||||
|
setIsRunning: (running: boolean) => void;
|
||||||
|
}) {
|
||||||
|
const { createNewTerminal, terminals, setTerminals, socket, setActiveTerminalId } = useTerminal();
|
||||||
|
|
||||||
|
const handleRun = () => {
|
||||||
|
if (isRunning) {
|
||||||
|
console.log('Stopping sandbox...');
|
||||||
|
console.log('Closing Terminal');
|
||||||
|
console.log('Closing Preview Window');
|
||||||
|
|
||||||
|
// Close all terminals if needed
|
||||||
|
terminals.forEach(term => {
|
||||||
|
if (term.terminal) {
|
||||||
|
// Assuming you have a closeTerminal function similar to createTerminal
|
||||||
|
closeTerminal({
|
||||||
|
term,
|
||||||
|
terminals,
|
||||||
|
setTerminals,
|
||||||
|
setActiveTerminalId,
|
||||||
|
setClosingTerminal: () => { },
|
||||||
|
socket: socket!,
|
||||||
|
activeTerminalId: term.id,
|
||||||
|
});
|
||||||
|
}
|
||||||
|
});
|
||||||
|
} else {
|
||||||
|
console.log('Running sandbox...');
|
||||||
|
console.log('Opening Terminal');
|
||||||
|
console.log('Opening Preview Window');
|
||||||
|
|
||||||
|
if (terminals.length < 4) {
|
||||||
|
createNewTerminal();
|
||||||
|
} else {
|
||||||
|
console.error('Maximum number of terminals reached.');
|
||||||
|
}
|
||||||
|
}
|
||||||
|
setIsRunning(!isRunning);
|
||||||
|
};
|
||||||
|
|
||||||
|
return (
|
||||||
|
<>
|
||||||
|
<Button variant="outline" onClick={handleRun}>
|
||||||
|
{isRunning ? <StopCircle className="w-4 h-4 mr-2" /> : <Play className="w-4 h-4 mr-2" />}
|
||||||
|
{isRunning ? 'Stop' : 'Run'}
|
||||||
|
</Button>
|
||||||
|
</>
|
||||||
|
);
|
||||||
|
}
|
@ -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>
|
||||||
)}
|
)}
|
||||||
|
@ -2,30 +2,16 @@
|
|||||||
|
|
||||||
import { Button } from "@/components/ui/button";
|
import { Button } from "@/components/ui/button";
|
||||||
import Tab from "@/components/ui/tab";
|
import Tab from "@/components/ui/tab";
|
||||||
import { closeTerminal, createTerminal } from "@/lib/terminal";
|
import { closeTerminal } from "@/lib/terminal";
|
||||||
import { Terminal } from "@xterm/xterm";
|
import { Terminal } from "@xterm/xterm";
|
||||||
import { Loader2, Plus, SquareTerminal, TerminalSquare } from "lucide-react";
|
import { Loader2, Plus, SquareTerminal, TerminalSquare } from "lucide-react";
|
||||||
import { Socket } from "socket.io-client";
|
|
||||||
import { toast } from "sonner";
|
import { toast } from "sonner";
|
||||||
import EditorTerminal from "./terminal";
|
import EditorTerminal from "./terminal";
|
||||||
import { useState } from "react";
|
import { useState } from "react";
|
||||||
|
import { useTerminal } from "@/context/TerminalContext";
|
||||||
|
|
||||||
export default function Terminals({
|
export default function Terminals() {
|
||||||
terminals,
|
const { terminals, setTerminals, socket, createNewTerminal } = useTerminal();
|
||||||
setTerminals,
|
|
||||||
socket,
|
|
||||||
}: {
|
|
||||||
terminals: { id: string; terminal: Terminal | null }[];
|
|
||||||
setTerminals: React.Dispatch<
|
|
||||||
React.SetStateAction<
|
|
||||||
{
|
|
||||||
id: string;
|
|
||||||
terminal: Terminal | null;
|
|
||||||
}[]
|
|
||||||
>
|
|
||||||
>;
|
|
||||||
socket: Socket;
|
|
||||||
}) {
|
|
||||||
const [activeTerminalId, setActiveTerminalId] = useState("");
|
const [activeTerminalId, setActiveTerminalId] = useState("");
|
||||||
const [creatingTerminal, setCreatingTerminal] = useState(false);
|
const [creatingTerminal, setCreatingTerminal] = useState(false);
|
||||||
const [closingTerminal, setClosingTerminal] = useState("");
|
const [closingTerminal, setClosingTerminal] = useState("");
|
||||||
@ -46,7 +32,7 @@ export default function Terminals({
|
|||||||
setTerminals,
|
setTerminals,
|
||||||
setActiveTerminalId,
|
setActiveTerminalId,
|
||||||
setClosingTerminal,
|
setClosingTerminal,
|
||||||
socket,
|
socket: socket!,
|
||||||
activeTerminalId,
|
activeTerminalId,
|
||||||
})
|
})
|
||||||
}
|
}
|
||||||
@ -64,12 +50,7 @@ export default function Terminals({
|
|||||||
toast.error("You reached the maximum # of terminals.");
|
toast.error("You reached the maximum # of terminals.");
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
createTerminal({
|
createNewTerminal();
|
||||||
setTerminals,
|
|
||||||
setActiveTerminalId,
|
|
||||||
setCreatingTerminal,
|
|
||||||
socket,
|
|
||||||
});
|
|
||||||
}}
|
}}
|
||||||
size="smIcon"
|
size="smIcon"
|
||||||
variant={"secondary"}
|
variant={"secondary"}
|
||||||
|
99
frontend/context/TerminalContext.tsx
Normal file
99
frontend/context/TerminalContext.tsx
Normal file
@ -0,0 +1,99 @@
|
|||||||
|
"use client";
|
||||||
|
|
||||||
|
import React, { createContext, useContext, useState, useEffect } from 'react';
|
||||||
|
import { io, Socket } from 'socket.io-client';
|
||||||
|
import { Terminal } from '@xterm/xterm';
|
||||||
|
import { createId } from '@paralleldrive/cuid2';
|
||||||
|
import { createTerminal as createTerminalHelper, closeTerminal as closeTerminalHelper } from '@/lib/terminal'; // Adjust the import path as necessary
|
||||||
|
|
||||||
|
interface TerminalContextType {
|
||||||
|
socket: Socket | null;
|
||||||
|
terminals: { id: string; terminal: Terminal | null }[];
|
||||||
|
setTerminals: React.Dispatch<React.SetStateAction<{ id: string; terminal: Terminal | null }[]>>;
|
||||||
|
activeTerminalId: string;
|
||||||
|
setActiveTerminalId: React.Dispatch<React.SetStateAction<string>>;
|
||||||
|
creatingTerminal: boolean;
|
||||||
|
setCreatingTerminal: React.Dispatch<React.SetStateAction<boolean>>;
|
||||||
|
createNewTerminal: () => void;
|
||||||
|
closeTerminal: (id: string) => void;
|
||||||
|
}
|
||||||
|
|
||||||
|
const TerminalContext = createContext<TerminalContextType | undefined>(undefined);
|
||||||
|
|
||||||
|
export const TerminalProvider: React.FC<{ children: React.ReactNode }> = ({ children }) => {
|
||||||
|
const [socket, setSocket] = useState<Socket | null>(null);
|
||||||
|
const [terminals, setTerminals] = useState<{ id: string; terminal: Terminal | null }[]>([]);
|
||||||
|
const [activeTerminalId, setActiveTerminalId] = useState<string>('');
|
||||||
|
const [creatingTerminal, setCreatingTerminal] = useState<boolean>(false);
|
||||||
|
|
||||||
|
useEffect(() => {
|
||||||
|
// Replace with your server URL
|
||||||
|
const socketIo = io(process.env.NEXT_PUBLIC_API_URL || 'http://localhost:3001');
|
||||||
|
setSocket(socketIo);
|
||||||
|
|
||||||
|
// Log socket events
|
||||||
|
socketIo.on('connect', () => {
|
||||||
|
console.log('Socket connected:', socketIo.id);
|
||||||
|
});
|
||||||
|
|
||||||
|
socketIo.on('disconnect', () => {
|
||||||
|
console.log('Socket disconnected');
|
||||||
|
});
|
||||||
|
|
||||||
|
return () => {
|
||||||
|
socketIo.disconnect();
|
||||||
|
};
|
||||||
|
}, []);
|
||||||
|
|
||||||
|
const createNewTerminal = () => {
|
||||||
|
if (socket) {
|
||||||
|
createTerminalHelper({
|
||||||
|
setTerminals,
|
||||||
|
setActiveTerminalId,
|
||||||
|
setCreatingTerminal,
|
||||||
|
socket,
|
||||||
|
});
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
|
const closeTerminal = (id: string) => {
|
||||||
|
const terminalToClose = terminals.find(term => term.id === id);
|
||||||
|
if (terminalToClose && socket) {
|
||||||
|
closeTerminalHelper({
|
||||||
|
term: terminalToClose,
|
||||||
|
terminals,
|
||||||
|
setTerminals,
|
||||||
|
setActiveTerminalId,
|
||||||
|
setClosingTerminal: () => {}, // Implement if needed
|
||||||
|
socket,
|
||||||
|
activeTerminalId,
|
||||||
|
});
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
|
const value = {
|
||||||
|
socket,
|
||||||
|
terminals,
|
||||||
|
setTerminals,
|
||||||
|
activeTerminalId,
|
||||||
|
setActiveTerminalId,
|
||||||
|
creatingTerminal,
|
||||||
|
setCreatingTerminal,
|
||||||
|
createNewTerminal,
|
||||||
|
closeTerminal,
|
||||||
|
};
|
||||||
|
|
||||||
|
return (
|
||||||
|
<TerminalContext.Provider value={value}>
|
||||||
|
{children}
|
||||||
|
</TerminalContext.Provider>
|
||||||
|
);
|
||||||
|
};
|
||||||
|
|
||||||
|
export const useTerminal = (): TerminalContextType => {
|
||||||
|
const context = useContext(TerminalContext);
|
||||||
|
if (!context) {
|
||||||
|
throw new Error('useTerminal must be used within a TerminalProvider');
|
||||||
|
}
|
||||||
|
return context;
|
||||||
|
};
|
Reference in New Issue
Block a user