@grasplabs/grasp
Version:
TypeScript SDK for browser automation and secure command execution in highly available and scalable cloud browser environments
76 lines • 2.68 kB
JavaScript
"use strict";
var __importDefault = (this && this.__importDefault) || function (mod) {
return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.GraspSession = void 0;
const filesystem_service_1 = require("../services/filesystem.service");
const browser_1 = require("./browser");
const terminal_service_1 = require("../services/terminal.service");
const code_runner_1 = require("./code-runner");
const server_1 = require("./server");
const ws_1 = __importDefault(require("ws"));
const promises_1 = require("timers/promises");
// TODO 后续拆分
class GraspSession {
constructor(connection) {
this.connection = connection;
this.isClosed = false;
this.browser = new browser_1.GraspBrowser(this.connection, this);
this.codeRunner = new code_runner_1.CodeRunner(this);
function createTerminal(connection) {
const { id } = connection;
const server = server_1.servers[id];
return new terminal_service_1.TerminalService(server.sandbox, connection);
}
this.terminal = createTerminal(this.connection);
function createFiles(connection) {
const { id } = connection;
const server = server_1.servers[id];
return new filesystem_service_1.FileSystemService(server.sandbox, connection);
}
this.files = createFiles(this.connection);
// console.log('create session...');
this.ws = new ws_1.default(this.connection.wsUrl);
this.ws.on('open', () => {
if (!this.isClosed) {
this.keepAlive();
}
else {
this.ws.close();
}
});
}
async keepAlive() {
const ws = this.ws;
await (0, promises_1.setTimeout)(10000);
if (ws.readyState === ws_1.default.OPEN) {
ws.ping();
}
ws.once('pong', () => {
this.keepAlive();
});
}
isRunning() {
const { id } = this.connection;
const server = server_1.servers[id];
return server.sandbox.getStatus() === 'running';
}
get id() {
return this.connection.id;
}
getHost(port) {
const { id } = this.connection;
const server = server_1.servers[id];
return server.sandbox.getSandboxHost(port);
}
async close() {
if (this.ws.readyState === ws_1.default.OPEN) {
this.ws.close();
}
this.isClosed = true;
server_1.servers[this.id].cleanup();
}
}
exports.GraspSession = GraspSession;
//# sourceMappingURL=session.js.map