@devbookhq/sdk
Advanced tools
Comparing version 2.4.1 to 2.4.2
@@ -1,2 +0,2 @@ | ||
"use strict";Object.defineProperty(exports,"__esModule",{value:!0});var s=require("rpc-websocket-client");require("cross-fetch/polyfill");var i=require("openapi-typescript-fetch");function t(s,i,t,e){return new(t||(t=Promise))((function(o,n){function r(s){try{c(e.next(s))}catch(s){n(s)}}function l(s){try{c(e.throw(s))}catch(s){n(s)}}function c(s){var i;s.done?o(s.value):(i=s.value,i instanceof t?i:new t((function(s){s(i)}))).then(r,l)}c((e=e.apply(s,i||[])).next())}))}const e=i.Fetcher.for();function o(s){return new Promise((i=>setTimeout(i,s)))}e.configure({baseUrl:"https://ondevbook.com"});class n{constructor(s,i=!1){this.logID=s,this.isEnabled=i}id(){return"function"==typeof this.logID?this.logID():this.logID}log(...s){this.isEnabled&&console.log(`[36m[${this.id()}][0m`,...s)}error(...s){console.error(`[31m[${this.id()} ERROR][0m`,...s)}}const r=e.path("/sessions").method("post").create({api_key:!0}),l=e.path("/sessions/{sessionID}/refresh").method("post").create({api_key:!0});var c;exports.CodeSnippetExecState=void 0,(c=exports.CodeSnippetExecState||(exports.CodeSnippetExecState={})).Running="Running",c.Stopped="Stopped";var h;exports.OutType=void 0,(h=exports.OutType||(exports.OutType={})).Stdout="Stdout",h.Stderr="Stderr",exports.Session=class extends class{constructor(i){this.opts=i,this.isOpen=!1,this.rpc=new s.RpcWebSocketClient,this.subscribers=[],this.logger=new n("Session",i.debug),this.logger.log(`Session for code snippet "${i.id}" initialized`)}call(s,i){return t(this,void 0,void 0,(function*(){return this.rpc.call(s,i)}))}unsubscribe(s){return t(this,void 0,void 0,(function*(){const i=this.subscribers.find((i=>i.subscriptionID===s));i&&(yield this.call(`${i.method}_unsubscribe`,[null==i?void 0:i.subscriptionID]),this.subscribers=this.subscribers.filter((s=>s!==i)),this.logger.log(`Unsubscribed from "${i.method}"`))}))}subscribe(s,i,...e){return t(this,void 0,void 0,(function*(){const t=yield this.call(`${s}_subscribe`,e);if("string"!=typeof t)throw new Error(`Cannot subscribe to ${s} with params ${e}. Expected response to be a subscription ID, instead got ${JSON.stringify(t)}`);return this.subscribers.push({subscriptionID:t,handler:i,method:s}),this.logger.log(`Subscribed to "${s}_${e}" with id "${t}"`),t}))}getHostname(s){if(!this.session)return;const i=`${this.session.sessionID}-${this.session.clientID}.ondevbook.com`;return s?`${s}-${i}`:i}close(){var s,i,e;return t(this,void 0,void 0,(function*(){if(this.isOpen){this.logger.log("Closing",this.session),this.isOpen=!1,this.logger.log("Unsubscribing...");(yield Promise.allSettled(this.subscribers.map((s=>this.unsubscribe(s.subscriptionID))))).forEach((s=>{"rejected"===s.status&&this.logger.log(`Failed to unsubscribe: "${s.reason}"`)})),null===(s=this.rpc.ws)||void 0===s||s.close(),null===(e=null===(i=this.opts)||void 0===i?void 0:i.onClose)||void 0===e||e.call(i),this.logger.log("Disconected from the session")}}))}open(){return t(this,void 0,void 0,(function*(){if(this.isOpen||this.session)throw new Error("Session connect was already called");this.isOpen=!0;try{const s=yield r({codeSnippetID:this.opts.id,editEnabled:this.opts.editEnabled,api_key:this.opts.apiKey});this.session=s.data,this.logger.log("Aquired session:",this.session),this.refresh(this.session.sessionID)}catch(s){if(s instanceof r.Error){const i=s.getActualType();if(400===i.status)throw new Error(`Error creating session - (${i.status}) bad request: ${i.data.message}`);if(401===i.status)throw new Error(`Error creating session - (${i.status}) unauthenticated (you need to be authenticated to start an session with persistent edits): ${i.data.message}`);if(500===i.status)throw new Error(`Error creating session - (${i.status}) server error: ${i.data.message}`);throw s}}if(!this.session)throw new Error("Session is not defined");const s=this.getHostname(8010);if(!s)throw new Error("Cannot get session's hostname");const i=`wss://${s}/ws`;this.rpc.onError((s=>{this.logger.log("Error in WS session:",this.session,s)}));let e,n,l=!1;const c=new Promise(((s,i)=>{e=()=>{l||(l=!0,s())},n=()=>{l||(l=!0,i())}}));this.rpc.onOpen((()=>{this.logger.log("Connected to session:",this.session),null==e||e()})),this.rpc.onClose((s=>t(this,void 0,void 0,(function*(){var t,e,r,l;if(this.logger.log("Closing WS connection to session:",this.session,s),this.isOpen){null===(e=(t=this.opts).onDisconnect)||void 0===e||e.call(t),yield o(100),this.logger.log("Reconnecting to session:",this.session);try{yield this.rpc.connect(i),null===(l=(r=this.opts).onReconnect)||void 0===l||l.call(r),this.logger.log("Reconnected to session:",this.session)}catch(s){this.logger.log("Failed reconnecting to session:",this.session,s)}}else null==n||n()})))),this.rpc.onNotification.push(this.handleNotification.bind(this));try{this.logger.log("Connection to session:",this.session),yield this.rpc.connect(i)}catch(s){this.logger.log("Error connecting to session",this.session,s)}yield c}))}handleNotification(s){this.subscribers.filter((i=>{var t;return i.subscriptionID===(null===(t=s.params)||void 0===t?void 0:t.subscription)})).forEach((i=>{var t;return i.handler(null===(t=s.params)||void 0===t?void 0:t.result)}))}refresh(s){return t(this,void 0,void 0,(function*(){this.logger.log(`Started refreshing session "${s}"`);try{for(;;){if(!this.isOpen)return void this.logger.log("Cannot refresh session - it was closed",this.session);yield o(5e3);try{this.logger.log(`Refreshed session "${s}"`),yield l({sessionID:s,api_key:this.opts.apiKey})}catch(i){if(i instanceof l.Error){const t=i.getActualType();if(404===t.status)return void this.logger.error(`Error refreshing session - (${t.status}): ${t.data.message}`);this.logger.error(`Refreshing session "${s}" failed - (${t.status})`)}}}}finally{this.logger.log(`Stopped refreshing session "${s}"`),this.close()}}))}}{constructor(s){super(s),this.codeSnippetOpts=s.codeSnippet}get codeSnippet(){return this.isOpen&&this.session?this._codeSnippet:void 0}get terminal(){return this.isOpen&&this.session?this._terminal:void 0}get filesystem(){return this.isOpen&&this.session?this._filesystem:void 0}get process(){return this.isOpen&&this.session?this._process:void 0}open(){const s=Object.create(null,{open:{get:()=>super.open}});var i,e,o,n;return t(this,void 0,void 0,(function*(){yield s.open.call(this),yield Promise.all([(null===(i=this.codeSnippetOpts)||void 0===i?void 0:i.onStateChange)?this.subscribe("codeSnippet",this.codeSnippetOpts.onStateChange,"state"):Promise.resolve(),(null===(e=this.codeSnippetOpts)||void 0===e?void 0:e.onStderr)?this.subscribe("codeSnippet",this.codeSnippetOpts.onStderr,"stderr"):Promise.resolve(),(null===(o=this.codeSnippetOpts)||void 0===o?void 0:o.onStdout)?this.subscribe("codeSnippet",this.codeSnippetOpts.onStdout,"stdout"):Promise.resolve(),(null===(n=this.codeSnippetOpts)||void 0===n?void 0:n.onScanPorts)?this.subscribe("codeSnippet",this.codeSnippetOpts.onScanPorts,"scanOpenedPorts"):Promise.resolve()]),this._codeSnippet={run:(s,i={})=>t(this,void 0,void 0,(function*(){var t,e;const o=yield this.call("codeSnippet_run",[s,i]);return null===(e=null===(t=this.codeSnippetOpts)||void 0===t?void 0:t.onStateChange)||void 0===e||e.call(t,o),o})),stop:()=>t(this,void 0,void 0,(function*(){var s,i;const t=yield this.call("codeSnippet_stop");return null===(i=null===(s=this.codeSnippetOpts)||void 0===s?void 0:s.onStateChange)||void 0===i||i.call(s,t),t}))},this._filesystem={listAllFiles:s=>t(this,void 0,void 0,(function*(){return yield this.call("filesystem_listAllFiles",[s])})),removeFile:s=>t(this,void 0,void 0,(function*(){yield this.call("filesystem_removeFile",[s])})),writeFile:(s,i)=>t(this,void 0,void 0,(function*(){yield this.call("filesystem_writeFile",[s,i])})),readFile:s=>t(this,void 0,void 0,(function*(){return yield this.call("filesystem_readFile",[s])}))},this._terminal={killProcess:s=>t(this,void 0,void 0,(function*(){yield this.call("terminal_killProcess",[s])})),createSession:({onData:s,onChildProcessesChange:i,size:e,activeTerminalID:o})=>t(this,void 0,void 0,(function*(){try{const n=yield this.call("terminal_start",[o||"",e.cols,e.rows]);if("string"!=typeof n)throw new Error("Cannot initialize terminal");const[r,l]=yield Promise.all([this.subscribe("terminal",s,"onData",n),i?this.subscribe("terminal",i,"onChildProcessesChange",n):void 0]);return{terminalID:n,destroy:()=>t(this,void 0,void 0,(function*(){yield Promise.all([this.unsubscribe(r),l?this.unsubscribe(l):void 0,yield this.call("terminal_destroy",[n])])})),sendData:s=>t(this,void 0,void 0,(function*(){yield this.call("terminal_data",[n,s])})),resize:({cols:s,rows:i})=>t(this,void 0,void 0,(function*(){yield this.call("terminal_resize",[n,s,i])}))}}catch(s){throw this.logger.error(s),new Error("Error starting terminal session",s)}}))},this._process={start:({cmd:s,onStdout:i,onStderr:e,onExit:o,envVars:n={},rootdir:r="/"})=>t(this,void 0,void 0,(function*(){const l=function(s){let i="";const t="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789",e=t.length;for(let o=0;o<s;o++)i+=t.charAt(Math.floor(Math.random()*e));return i}(12);try{const[c,h,d]=yield Promise.all([o?this.subscribe("process",o,"onExit",l):void 0,i?this.subscribe("process",i,"onStdout",l):void 0,e?this.subscribe("process",e,"onStderr",l):void 0]);return yield this.call("process_start",[l,s,n,r]),{processID:l,kill:()=>t(this,void 0,void 0,(function*(){c&&(yield this.unsubscribe(c)),yield Promise.all([h?this.unsubscribe(h):void 0,d?this.unsubscribe(d):void 0,this.call("terminal_kill",[l])]),null==o||o()})),sendStdin:s=>t(this,void 0,void 0,(function*(){yield this.call("process_stdin",[l,s])}))}}catch(s){throw this.logger.error(s),new Error("Error starting process",s)}}))}}))}},exports.api=e; | ||
"use strict";Object.defineProperty(exports,"__esModule",{value:!0});var s=require("rpc-websocket-client");require("cross-fetch/polyfill");var i=require("openapi-typescript-fetch");function t(s,i,t,e){return new(t||(t=Promise))((function(o,n){function r(s){try{c(e.next(s))}catch(s){n(s)}}function l(s){try{c(e.throw(s))}catch(s){n(s)}}function c(s){var i;s.done?o(s.value):(i=s.value,i instanceof t?i:new t((function(s){s(i)}))).then(r,l)}c((e=e.apply(s,i||[])).next())}))}const e=i.Fetcher.for();function o(s){return new Promise((i=>setTimeout(i,s)))}e.configure({baseUrl:"https://ondevbook.com"});class n{constructor(s,i=!1){this.logID=s,this.isEnabled=i}id(){return"function"==typeof this.logID?this.logID():this.logID}log(...s){this.isEnabled&&console.log(`[36m[${this.id()}][0m`,...s)}error(...s){console.error(`[31m[${this.id()} ERROR][0m`,...s)}}const r=e.path("/sessions").method("post").create({api_key:!0}),l=e.path("/sessions/{sessionID}/refresh").method("post").create({api_key:!0});var c;exports.CodeSnippetExecState=void 0,(c=exports.CodeSnippetExecState||(exports.CodeSnippetExecState={})).Running="Running",c.Stopped="Stopped";var d;exports.OutType=void 0,(d=exports.OutType||(exports.OutType={})).Stdout="Stdout",d.Stderr="Stderr",exports.Session=class extends class{constructor(i){this.opts=i,this.isOpen=!1,this.rpc=new s.RpcWebSocketClient,this.subscribers=[],this.logger=new n("Session",i.debug),this.logger.log(`Session for code snippet "${i.id}" initialized`)}call(s,i){return t(this,void 0,void 0,(function*(){return this.rpc.call(s,i)}))}unsubscribe(s){return t(this,void 0,void 0,(function*(){const i=this.subscribers.find((i=>i.subscriptionID===s));i&&(yield this.call(`${i.method}_unsubscribe`,[null==i?void 0:i.subscriptionID]),this.subscribers=this.subscribers.filter((s=>s!==i)),this.logger.log(`Unsubscribed from "${i.method}"`))}))}subscribe(s,i,...e){return t(this,void 0,void 0,(function*(){const t=yield this.call(`${s}_subscribe`,e);if("string"!=typeof t)throw new Error(`Cannot subscribe to ${s} with params ${e}. Expected response to be a subscription ID, instead got ${JSON.stringify(t)}`);return this.subscribers.push({subscriptionID:t,handler:i,method:s}),this.logger.log(`Subscribed to "${s}_${e}" with id "${t}"`),t}))}getHostname(s){if(!this.session)return;const i=`${this.session.sessionID}-${this.session.clientID}.ondevbook.com`;return s?`${s}-${i}`:i}close(){var s,i,e;return t(this,void 0,void 0,(function*(){if(this.isOpen){this.logger.log("Closing",this.session),this.isOpen=!1,this.logger.log("Unsubscribing...");(yield Promise.allSettled(this.subscribers.map((s=>this.unsubscribe(s.subscriptionID))))).forEach((s=>{"rejected"===s.status&&this.logger.log(`Failed to unsubscribe: "${s.reason}"`)})),null===(s=this.rpc.ws)||void 0===s||s.close(),null===(e=null===(i=this.opts)||void 0===i?void 0:i.onClose)||void 0===e||e.call(i),this.logger.log("Disconected from the session")}}))}open(){return t(this,void 0,void 0,(function*(){if(this.isOpen||this.session)throw new Error("Session connect was already called");this.isOpen=!0;try{const s=yield r({codeSnippetID:this.opts.id,editEnabled:this.opts.editEnabled,api_key:this.opts.apiKey});this.session=s.data,this.logger.log("Aquired session:",this.session),this.refresh(this.session.sessionID)}catch(s){if(s instanceof r.Error){const i=s.getActualType();if(400===i.status)throw new Error(`Error creating session - (${i.status}) bad request: ${i.data.message}`);if(401===i.status)throw new Error(`Error creating session - (${i.status}) unauthenticated (you need to be authenticated to start an session with persistent edits): ${i.data.message}`);if(500===i.status)throw new Error(`Error creating session - (${i.status}) server error: ${i.data.message}`);throw s}}if(!this.session)throw new Error("Session is not defined");const s=this.getHostname(8010);if(!s)throw new Error("Cannot get session's hostname");const i=`wss://${s}/ws`;this.rpc.onError((s=>{this.logger.log("Error in WS session:",this.session,s)}));let e,n,l=!1;const c=new Promise(((s,i)=>{e=()=>{l||(l=!0,s())},n=()=>{l||(l=!0,i())}}));this.rpc.onOpen((()=>{this.logger.log("Connected to session:",this.session),null==e||e()})),this.rpc.onClose((s=>t(this,void 0,void 0,(function*(){var t,e,r,l;if(this.logger.log("Closing WS connection to session:",this.session,s),this.isOpen){null===(e=(t=this.opts).onDisconnect)||void 0===e||e.call(t),yield o(100),this.logger.log("Reconnecting to session:",this.session);try{yield this.rpc.connect(i),null===(l=(r=this.opts).onReconnect)||void 0===l||l.call(r),this.logger.log("Reconnected to session:",this.session)}catch(s){this.logger.log("Failed reconnecting to session:",this.session,s)}}else null==n||n()})))),this.rpc.onNotification.push(this.handleNotification.bind(this));try{this.logger.log("Connection to session:",this.session),yield this.rpc.connect(i)}catch(s){this.logger.log("Error connecting to session",this.session,s)}yield c}))}handleNotification(s){this.subscribers.filter((i=>{var t;return i.subscriptionID===(null===(t=s.params)||void 0===t?void 0:t.subscription)})).forEach((i=>{var t;return i.handler(null===(t=s.params)||void 0===t?void 0:t.result)}))}refresh(s){return t(this,void 0,void 0,(function*(){this.logger.log(`Started refreshing session "${s}"`);try{for(;;){if(!this.isOpen)return void this.logger.log("Cannot refresh session - it was closed",this.session);yield o(5e3);try{this.logger.log(`Refreshed session "${s}"`),yield l({sessionID:s,api_key:this.opts.apiKey})}catch(i){if(i instanceof l.Error){const t=i.getActualType();if(404===t.status)return void this.logger.error(`Error refreshing session - (${t.status}): ${t.data.message}`);this.logger.error(`Refreshing session "${s}" failed - (${t.status})`)}}}}finally{this.logger.log(`Stopped refreshing session "${s}"`),this.close()}}))}}{constructor(s){super(s),this.codeSnippetOpts=s.codeSnippet}open(){const s=Object.create(null,{open:{get:()=>super.open}});var i,e,o,n;return t(this,void 0,void 0,(function*(){yield s.open.call(this),yield Promise.all([(null===(i=this.codeSnippetOpts)||void 0===i?void 0:i.onStateChange)?this.subscribe("codeSnippet",this.codeSnippetOpts.onStateChange,"state"):Promise.resolve(),(null===(e=this.codeSnippetOpts)||void 0===e?void 0:e.onStderr)?this.subscribe("codeSnippet",this.codeSnippetOpts.onStderr,"stderr"):Promise.resolve(),(null===(o=this.codeSnippetOpts)||void 0===o?void 0:o.onStdout)?this.subscribe("codeSnippet",this.codeSnippetOpts.onStdout,"stdout"):Promise.resolve(),(null===(n=this.codeSnippetOpts)||void 0===n?void 0:n.onScanPorts)?this.subscribe("codeSnippet",this.codeSnippetOpts.onScanPorts,"scanOpenedPorts"):Promise.resolve()]),this.codeSnippet={run:(s,i={})=>t(this,void 0,void 0,(function*(){var t,e;const o=yield this.call("codeSnippet_run",[s,i]);return null===(e=null===(t=this.codeSnippetOpts)||void 0===t?void 0:t.onStateChange)||void 0===e||e.call(t,o),o})),stop:()=>t(this,void 0,void 0,(function*(){var s,i;const t=yield this.call("codeSnippet_stop");return null===(i=null===(s=this.codeSnippetOpts)||void 0===s?void 0:s.onStateChange)||void 0===i||i.call(s,t),t}))},this.filesystem={listAllFiles:s=>t(this,void 0,void 0,(function*(){return yield this.call("filesystem_listAllFiles",[s])})),removeFile:s=>t(this,void 0,void 0,(function*(){yield this.call("filesystem_removeFile",[s])})),writeFile:(s,i)=>t(this,void 0,void 0,(function*(){yield this.call("filesystem_writeFile",[s,i])})),readFile:s=>t(this,void 0,void 0,(function*(){return yield this.call("filesystem_readFile",[s])}))},this.terminal={killProcess:s=>t(this,void 0,void 0,(function*(){yield this.call("terminal_killProcess",[s])})),createSession:({onData:s,onChildProcessesChange:i,size:e,activeTerminalID:o})=>t(this,void 0,void 0,(function*(){const n=yield this.call("terminal_start",[o||"",e.cols,e.rows]);if("string"!=typeof n)throw new Error("Cannot initialize terminal");const[r,l]=yield Promise.all([this.subscribe("terminal",s,"onData",n),i?this.subscribe("terminal",i,"onChildProcessesChange",n):void 0]);return{terminalID:n,destroy:()=>t(this,void 0,void 0,(function*(){yield Promise.all([this.unsubscribe(r),l?this.unsubscribe(l):void 0,yield this.call("terminal_destroy",[n])])})),sendData:s=>t(this,void 0,void 0,(function*(){yield this.call("terminal_data",[n,s])})),resize:({cols:s,rows:i})=>t(this,void 0,void 0,(function*(){yield this.call("terminal_resize",[n,s,i])}))}}))},this.process={start:({cmd:s,onStdout:i,onStderr:e,onExit:o,envVars:n={},rootdir:r="/"})=>t(this,void 0,void 0,(function*(){const l=function(s){let i="";const t="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789",e=t.length;for(let o=0;o<s;o++)i+=t.charAt(Math.floor(Math.random()*e));return i}(12),[c,d,h]=yield Promise.all([o?this.subscribe("process",o,"onExit",l):void 0,i?this.subscribe("process",i,"onStdout",l):void 0,e?this.subscribe("process",e,"onStderr",l):void 0]);return yield this.call("process_start",[l,s,n,r]),{processID:l,kill:()=>t(this,void 0,void 0,(function*(){c&&(yield this.unsubscribe(c)),yield Promise.all([d?this.unsubscribe(d):void 0,h?this.unsubscribe(h):void 0,this.call("terminal_kill",[l])]),null==o||o()})),sendStdin:s=>t(this,void 0,void 0,(function*(){yield this.call("process_stdin",[l,s])}))}}))}}))}},exports.api=e; | ||
//# sourceMappingURL=index.js.map |
@@ -17,10 +17,6 @@ import SessionConnection, { SessionConnectionOpts } from './sessionConnection'; | ||
private readonly codeSnippetOpts?; | ||
private _codeSnippet?; | ||
private _terminal?; | ||
private _filesystem?; | ||
private _process?; | ||
get codeSnippet(): CodeSnippetManager | undefined; | ||
get terminal(): TerminalManager | undefined; | ||
get filesystem(): FilesystemManager | undefined; | ||
get process(): ProcessManager | undefined; | ||
codeSnippet?: CodeSnippetManager; | ||
terminal?: TerminalManager; | ||
filesystem?: FilesystemManager; | ||
process?: ProcessManager; | ||
constructor(opts: SessionOpts); | ||
@@ -27,0 +23,0 @@ open(): Promise<void>; |
@@ -1,2 +0,2 @@ | ||
import{RpcWebSocketClient as s}from"rpc-websocket-client";import"cross-fetch/polyfill";import{Fetcher as i}from"openapi-typescript-fetch";function t(s,i,t,e){return new(t||(t=Promise))((function(o,n){function r(s){try{c(e.next(s))}catch(s){n(s)}}function l(s){try{c(e.throw(s))}catch(s){n(s)}}function c(s){var i;s.done?o(s.value):(i=s.value,i instanceof t?i:new t((function(s){s(i)}))).then(r,l)}c((e=e.apply(s,i||[])).next())}))}const e=i.for();function o(s){return new Promise((i=>setTimeout(i,s)))}e.configure({baseUrl:"https://ondevbook.com"});class n{constructor(s,i=!1){this.logID=s,this.isEnabled=i}id(){return"function"==typeof this.logID?this.logID():this.logID}log(...s){this.isEnabled&&console.log(`[36m[${this.id()}][0m`,...s)}error(...s){console.error(`[31m[${this.id()} ERROR][0m`,...s)}}const r=e.path("/sessions").method("post").create({api_key:!0}),l=e.path("/sessions/{sessionID}/refresh").method("post").create({api_key:!0});var c;!function(s){s.Running="Running",s.Stopped="Stopped"}(c||(c={}));class h extends class{constructor(i){this.opts=i,this.isOpen=!1,this.rpc=new s,this.subscribers=[],this.logger=new n("Session",i.debug),this.logger.log(`Session for code snippet "${i.id}" initialized`)}call(s,i){return t(this,void 0,void 0,(function*(){return this.rpc.call(s,i)}))}unsubscribe(s){return t(this,void 0,void 0,(function*(){const i=this.subscribers.find((i=>i.subscriptionID===s));i&&(yield this.call(`${i.method}_unsubscribe`,[null==i?void 0:i.subscriptionID]),this.subscribers=this.subscribers.filter((s=>s!==i)),this.logger.log(`Unsubscribed from "${i.method}"`))}))}subscribe(s,i,...e){return t(this,void 0,void 0,(function*(){const t=yield this.call(`${s}_subscribe`,e);if("string"!=typeof t)throw new Error(`Cannot subscribe to ${s} with params ${e}. Expected response to be a subscription ID, instead got ${JSON.stringify(t)}`);return this.subscribers.push({subscriptionID:t,handler:i,method:s}),this.logger.log(`Subscribed to "${s}_${e}" with id "${t}"`),t}))}getHostname(s){if(!this.session)return;const i=`${this.session.sessionID}-${this.session.clientID}.ondevbook.com`;return s?`${s}-${i}`:i}close(){var s,i,e;return t(this,void 0,void 0,(function*(){if(this.isOpen){this.logger.log("Closing",this.session),this.isOpen=!1,this.logger.log("Unsubscribing...");(yield Promise.allSettled(this.subscribers.map((s=>this.unsubscribe(s.subscriptionID))))).forEach((s=>{"rejected"===s.status&&this.logger.log(`Failed to unsubscribe: "${s.reason}"`)})),null===(s=this.rpc.ws)||void 0===s||s.close(),null===(e=null===(i=this.opts)||void 0===i?void 0:i.onClose)||void 0===e||e.call(i),this.logger.log("Disconected from the session")}}))}open(){return t(this,void 0,void 0,(function*(){if(this.isOpen||this.session)throw new Error("Session connect was already called");this.isOpen=!0;try{const s=yield r({codeSnippetID:this.opts.id,editEnabled:this.opts.editEnabled,api_key:this.opts.apiKey});this.session=s.data,this.logger.log("Aquired session:",this.session),this.refresh(this.session.sessionID)}catch(s){if(s instanceof r.Error){const i=s.getActualType();if(400===i.status)throw new Error(`Error creating session - (${i.status}) bad request: ${i.data.message}`);if(401===i.status)throw new Error(`Error creating session - (${i.status}) unauthenticated (you need to be authenticated to start an session with persistent edits): ${i.data.message}`);if(500===i.status)throw new Error(`Error creating session - (${i.status}) server error: ${i.data.message}`);throw s}}if(!this.session)throw new Error("Session is not defined");const s=this.getHostname(8010);if(!s)throw new Error("Cannot get session's hostname");const i=`wss://${s}/ws`;this.rpc.onError((s=>{this.logger.log("Error in WS session:",this.session,s)}));let e,n,l=!1;const c=new Promise(((s,i)=>{e=()=>{l||(l=!0,s())},n=()=>{l||(l=!0,i())}}));this.rpc.onOpen((()=>{this.logger.log("Connected to session:",this.session),null==e||e()})),this.rpc.onClose((s=>t(this,void 0,void 0,(function*(){var t,e,r,l;if(this.logger.log("Closing WS connection to session:",this.session,s),this.isOpen){null===(e=(t=this.opts).onDisconnect)||void 0===e||e.call(t),yield o(100),this.logger.log("Reconnecting to session:",this.session);try{yield this.rpc.connect(i),null===(l=(r=this.opts).onReconnect)||void 0===l||l.call(r),this.logger.log("Reconnected to session:",this.session)}catch(s){this.logger.log("Failed reconnecting to session:",this.session,s)}}else null==n||n()})))),this.rpc.onNotification.push(this.handleNotification.bind(this));try{this.logger.log("Connection to session:",this.session),yield this.rpc.connect(i)}catch(s){this.logger.log("Error connecting to session",this.session,s)}yield c}))}handleNotification(s){this.subscribers.filter((i=>{var t;return i.subscriptionID===(null===(t=s.params)||void 0===t?void 0:t.subscription)})).forEach((i=>{var t;return i.handler(null===(t=s.params)||void 0===t?void 0:t.result)}))}refresh(s){return t(this,void 0,void 0,(function*(){this.logger.log(`Started refreshing session "${s}"`);try{for(;;){if(!this.isOpen)return void this.logger.log("Cannot refresh session - it was closed",this.session);yield o(5e3);try{this.logger.log(`Refreshed session "${s}"`),yield l({sessionID:s,api_key:this.opts.apiKey})}catch(i){if(i instanceof l.Error){const t=i.getActualType();if(404===t.status)return void this.logger.error(`Error refreshing session - (${t.status}): ${t.data.message}`);this.logger.error(`Refreshing session "${s}" failed - (${t.status})`)}}}}finally{this.logger.log(`Stopped refreshing session "${s}"`),this.close()}}))}}{constructor(s){super(s),this.codeSnippetOpts=s.codeSnippet}get codeSnippet(){return this.isOpen&&this.session?this._codeSnippet:void 0}get terminal(){return this.isOpen&&this.session?this._terminal:void 0}get filesystem(){return this.isOpen&&this.session?this._filesystem:void 0}get process(){return this.isOpen&&this.session?this._process:void 0}open(){const s=Object.create(null,{open:{get:()=>super.open}});var i,e,o,n;return t(this,void 0,void 0,(function*(){yield s.open.call(this),yield Promise.all([(null===(i=this.codeSnippetOpts)||void 0===i?void 0:i.onStateChange)?this.subscribe("codeSnippet",this.codeSnippetOpts.onStateChange,"state"):Promise.resolve(),(null===(e=this.codeSnippetOpts)||void 0===e?void 0:e.onStderr)?this.subscribe("codeSnippet",this.codeSnippetOpts.onStderr,"stderr"):Promise.resolve(),(null===(o=this.codeSnippetOpts)||void 0===o?void 0:o.onStdout)?this.subscribe("codeSnippet",this.codeSnippetOpts.onStdout,"stdout"):Promise.resolve(),(null===(n=this.codeSnippetOpts)||void 0===n?void 0:n.onScanPorts)?this.subscribe("codeSnippet",this.codeSnippetOpts.onScanPorts,"scanOpenedPorts"):Promise.resolve()]),this._codeSnippet={run:(s,i={})=>t(this,void 0,void 0,(function*(){var t,e;const o=yield this.call("codeSnippet_run",[s,i]);return null===(e=null===(t=this.codeSnippetOpts)||void 0===t?void 0:t.onStateChange)||void 0===e||e.call(t,o),o})),stop:()=>t(this,void 0,void 0,(function*(){var s,i;const t=yield this.call("codeSnippet_stop");return null===(i=null===(s=this.codeSnippetOpts)||void 0===s?void 0:s.onStateChange)||void 0===i||i.call(s,t),t}))},this._filesystem={listAllFiles:s=>t(this,void 0,void 0,(function*(){return yield this.call("filesystem_listAllFiles",[s])})),removeFile:s=>t(this,void 0,void 0,(function*(){yield this.call("filesystem_removeFile",[s])})),writeFile:(s,i)=>t(this,void 0,void 0,(function*(){yield this.call("filesystem_writeFile",[s,i])})),readFile:s=>t(this,void 0,void 0,(function*(){return yield this.call("filesystem_readFile",[s])}))},this._terminal={killProcess:s=>t(this,void 0,void 0,(function*(){yield this.call("terminal_killProcess",[s])})),createSession:({onData:s,onChildProcessesChange:i,size:e,activeTerminalID:o})=>t(this,void 0,void 0,(function*(){try{const n=yield this.call("terminal_start",[o||"",e.cols,e.rows]);if("string"!=typeof n)throw new Error("Cannot initialize terminal");const[r,l]=yield Promise.all([this.subscribe("terminal",s,"onData",n),i?this.subscribe("terminal",i,"onChildProcessesChange",n):void 0]);return{terminalID:n,destroy:()=>t(this,void 0,void 0,(function*(){yield Promise.all([this.unsubscribe(r),l?this.unsubscribe(l):void 0,yield this.call("terminal_destroy",[n])])})),sendData:s=>t(this,void 0,void 0,(function*(){yield this.call("terminal_data",[n,s])})),resize:({cols:s,rows:i})=>t(this,void 0,void 0,(function*(){yield this.call("terminal_resize",[n,s,i])}))}}catch(s){throw this.logger.error(s),new Error("Error starting terminal session",s)}}))},this._process={start:({cmd:s,onStdout:i,onStderr:e,onExit:o,envVars:n={},rootdir:r="/"})=>t(this,void 0,void 0,(function*(){const l=function(s){let i="";const t="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789",e=t.length;for(let o=0;o<s;o++)i+=t.charAt(Math.floor(Math.random()*e));return i}(12);try{const[c,h,d]=yield Promise.all([o?this.subscribe("process",o,"onExit",l):void 0,i?this.subscribe("process",i,"onStdout",l):void 0,e?this.subscribe("process",e,"onStderr",l):void 0]);return yield this.call("process_start",[l,s,n,r]),{processID:l,kill:()=>t(this,void 0,void 0,(function*(){c&&(yield this.unsubscribe(c)),yield Promise.all([h?this.unsubscribe(h):void 0,d?this.unsubscribe(d):void 0,this.call("terminal_kill",[l])]),null==o||o()})),sendStdin:s=>t(this,void 0,void 0,(function*(){yield this.call("process_stdin",[l,s])}))}}catch(s){throw this.logger.error(s),new Error("Error starting process",s)}}))}}))}}var d;!function(s){s.Stdout="Stdout",s.Stderr="Stderr"}(d||(d={}));export{c as CodeSnippetExecState,d as OutType,h as Session,e as api}; | ||
import{RpcWebSocketClient as s}from"rpc-websocket-client";import"cross-fetch/polyfill";import{Fetcher as i}from"openapi-typescript-fetch";function t(s,i,t,e){return new(t||(t=Promise))((function(o,n){function r(s){try{c(e.next(s))}catch(s){n(s)}}function l(s){try{c(e.throw(s))}catch(s){n(s)}}function c(s){var i;s.done?o(s.value):(i=s.value,i instanceof t?i:new t((function(s){s(i)}))).then(r,l)}c((e=e.apply(s,i||[])).next())}))}const e=i.for();function o(s){return new Promise((i=>setTimeout(i,s)))}e.configure({baseUrl:"https://ondevbook.com"});class n{constructor(s,i=!1){this.logID=s,this.isEnabled=i}id(){return"function"==typeof this.logID?this.logID():this.logID}log(...s){this.isEnabled&&console.log(`[36m[${this.id()}][0m`,...s)}error(...s){console.error(`[31m[${this.id()} ERROR][0m`,...s)}}const r=e.path("/sessions").method("post").create({api_key:!0}),l=e.path("/sessions/{sessionID}/refresh").method("post").create({api_key:!0});var c;!function(s){s.Running="Running",s.Stopped="Stopped"}(c||(c={}));class d extends class{constructor(i){this.opts=i,this.isOpen=!1,this.rpc=new s,this.subscribers=[],this.logger=new n("Session",i.debug),this.logger.log(`Session for code snippet "${i.id}" initialized`)}call(s,i){return t(this,void 0,void 0,(function*(){return this.rpc.call(s,i)}))}unsubscribe(s){return t(this,void 0,void 0,(function*(){const i=this.subscribers.find((i=>i.subscriptionID===s));i&&(yield this.call(`${i.method}_unsubscribe`,[null==i?void 0:i.subscriptionID]),this.subscribers=this.subscribers.filter((s=>s!==i)),this.logger.log(`Unsubscribed from "${i.method}"`))}))}subscribe(s,i,...e){return t(this,void 0,void 0,(function*(){const t=yield this.call(`${s}_subscribe`,e);if("string"!=typeof t)throw new Error(`Cannot subscribe to ${s} with params ${e}. Expected response to be a subscription ID, instead got ${JSON.stringify(t)}`);return this.subscribers.push({subscriptionID:t,handler:i,method:s}),this.logger.log(`Subscribed to "${s}_${e}" with id "${t}"`),t}))}getHostname(s){if(!this.session)return;const i=`${this.session.sessionID}-${this.session.clientID}.ondevbook.com`;return s?`${s}-${i}`:i}close(){var s,i,e;return t(this,void 0,void 0,(function*(){if(this.isOpen){this.logger.log("Closing",this.session),this.isOpen=!1,this.logger.log("Unsubscribing...");(yield Promise.allSettled(this.subscribers.map((s=>this.unsubscribe(s.subscriptionID))))).forEach((s=>{"rejected"===s.status&&this.logger.log(`Failed to unsubscribe: "${s.reason}"`)})),null===(s=this.rpc.ws)||void 0===s||s.close(),null===(e=null===(i=this.opts)||void 0===i?void 0:i.onClose)||void 0===e||e.call(i),this.logger.log("Disconected from the session")}}))}open(){return t(this,void 0,void 0,(function*(){if(this.isOpen||this.session)throw new Error("Session connect was already called");this.isOpen=!0;try{const s=yield r({codeSnippetID:this.opts.id,editEnabled:this.opts.editEnabled,api_key:this.opts.apiKey});this.session=s.data,this.logger.log("Aquired session:",this.session),this.refresh(this.session.sessionID)}catch(s){if(s instanceof r.Error){const i=s.getActualType();if(400===i.status)throw new Error(`Error creating session - (${i.status}) bad request: ${i.data.message}`);if(401===i.status)throw new Error(`Error creating session - (${i.status}) unauthenticated (you need to be authenticated to start an session with persistent edits): ${i.data.message}`);if(500===i.status)throw new Error(`Error creating session - (${i.status}) server error: ${i.data.message}`);throw s}}if(!this.session)throw new Error("Session is not defined");const s=this.getHostname(8010);if(!s)throw new Error("Cannot get session's hostname");const i=`wss://${s}/ws`;this.rpc.onError((s=>{this.logger.log("Error in WS session:",this.session,s)}));let e,n,l=!1;const c=new Promise(((s,i)=>{e=()=>{l||(l=!0,s())},n=()=>{l||(l=!0,i())}}));this.rpc.onOpen((()=>{this.logger.log("Connected to session:",this.session),null==e||e()})),this.rpc.onClose((s=>t(this,void 0,void 0,(function*(){var t,e,r,l;if(this.logger.log("Closing WS connection to session:",this.session,s),this.isOpen){null===(e=(t=this.opts).onDisconnect)||void 0===e||e.call(t),yield o(100),this.logger.log("Reconnecting to session:",this.session);try{yield this.rpc.connect(i),null===(l=(r=this.opts).onReconnect)||void 0===l||l.call(r),this.logger.log("Reconnected to session:",this.session)}catch(s){this.logger.log("Failed reconnecting to session:",this.session,s)}}else null==n||n()})))),this.rpc.onNotification.push(this.handleNotification.bind(this));try{this.logger.log("Connection to session:",this.session),yield this.rpc.connect(i)}catch(s){this.logger.log("Error connecting to session",this.session,s)}yield c}))}handleNotification(s){this.subscribers.filter((i=>{var t;return i.subscriptionID===(null===(t=s.params)||void 0===t?void 0:t.subscription)})).forEach((i=>{var t;return i.handler(null===(t=s.params)||void 0===t?void 0:t.result)}))}refresh(s){return t(this,void 0,void 0,(function*(){this.logger.log(`Started refreshing session "${s}"`);try{for(;;){if(!this.isOpen)return void this.logger.log("Cannot refresh session - it was closed",this.session);yield o(5e3);try{this.logger.log(`Refreshed session "${s}"`),yield l({sessionID:s,api_key:this.opts.apiKey})}catch(i){if(i instanceof l.Error){const t=i.getActualType();if(404===t.status)return void this.logger.error(`Error refreshing session - (${t.status}): ${t.data.message}`);this.logger.error(`Refreshing session "${s}" failed - (${t.status})`)}}}}finally{this.logger.log(`Stopped refreshing session "${s}"`),this.close()}}))}}{constructor(s){super(s),this.codeSnippetOpts=s.codeSnippet}open(){const s=Object.create(null,{open:{get:()=>super.open}});var i,e,o,n;return t(this,void 0,void 0,(function*(){yield s.open.call(this),yield Promise.all([(null===(i=this.codeSnippetOpts)||void 0===i?void 0:i.onStateChange)?this.subscribe("codeSnippet",this.codeSnippetOpts.onStateChange,"state"):Promise.resolve(),(null===(e=this.codeSnippetOpts)||void 0===e?void 0:e.onStderr)?this.subscribe("codeSnippet",this.codeSnippetOpts.onStderr,"stderr"):Promise.resolve(),(null===(o=this.codeSnippetOpts)||void 0===o?void 0:o.onStdout)?this.subscribe("codeSnippet",this.codeSnippetOpts.onStdout,"stdout"):Promise.resolve(),(null===(n=this.codeSnippetOpts)||void 0===n?void 0:n.onScanPorts)?this.subscribe("codeSnippet",this.codeSnippetOpts.onScanPorts,"scanOpenedPorts"):Promise.resolve()]),this.codeSnippet={run:(s,i={})=>t(this,void 0,void 0,(function*(){var t,e;const o=yield this.call("codeSnippet_run",[s,i]);return null===(e=null===(t=this.codeSnippetOpts)||void 0===t?void 0:t.onStateChange)||void 0===e||e.call(t,o),o})),stop:()=>t(this,void 0,void 0,(function*(){var s,i;const t=yield this.call("codeSnippet_stop");return null===(i=null===(s=this.codeSnippetOpts)||void 0===s?void 0:s.onStateChange)||void 0===i||i.call(s,t),t}))},this.filesystem={listAllFiles:s=>t(this,void 0,void 0,(function*(){return yield this.call("filesystem_listAllFiles",[s])})),removeFile:s=>t(this,void 0,void 0,(function*(){yield this.call("filesystem_removeFile",[s])})),writeFile:(s,i)=>t(this,void 0,void 0,(function*(){yield this.call("filesystem_writeFile",[s,i])})),readFile:s=>t(this,void 0,void 0,(function*(){return yield this.call("filesystem_readFile",[s])}))},this.terminal={killProcess:s=>t(this,void 0,void 0,(function*(){yield this.call("terminal_killProcess",[s])})),createSession:({onData:s,onChildProcessesChange:i,size:e,activeTerminalID:o})=>t(this,void 0,void 0,(function*(){const n=yield this.call("terminal_start",[o||"",e.cols,e.rows]);if("string"!=typeof n)throw new Error("Cannot initialize terminal");const[r,l]=yield Promise.all([this.subscribe("terminal",s,"onData",n),i?this.subscribe("terminal",i,"onChildProcessesChange",n):void 0]);return{terminalID:n,destroy:()=>t(this,void 0,void 0,(function*(){yield Promise.all([this.unsubscribe(r),l?this.unsubscribe(l):void 0,yield this.call("terminal_destroy",[n])])})),sendData:s=>t(this,void 0,void 0,(function*(){yield this.call("terminal_data",[n,s])})),resize:({cols:s,rows:i})=>t(this,void 0,void 0,(function*(){yield this.call("terminal_resize",[n,s,i])}))}}))},this.process={start:({cmd:s,onStdout:i,onStderr:e,onExit:o,envVars:n={},rootdir:r="/"})=>t(this,void 0,void 0,(function*(){const l=function(s){let i="";const t="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789",e=t.length;for(let o=0;o<s;o++)i+=t.charAt(Math.floor(Math.random()*e));return i}(12),[c,d,h]=yield Promise.all([o?this.subscribe("process",o,"onExit",l):void 0,i?this.subscribe("process",i,"onStdout",l):void 0,e?this.subscribe("process",e,"onStderr",l):void 0]);return yield this.call("process_start",[l,s,n,r]),{processID:l,kill:()=>t(this,void 0,void 0,(function*(){c&&(yield this.unsubscribe(c)),yield Promise.all([d?this.unsubscribe(d):void 0,h?this.unsubscribe(h):void 0,this.call("terminal_kill",[l])]),null==o||o()})),sendStdin:s=>t(this,void 0,void 0,(function*(){yield this.call("process_stdin",[l,s])}))}}))}}))}}var h;!function(s){s.Stdout="Stdout",s.Stderr="Stderr"}(h||(h={}));export{c as CodeSnippetExecState,h as OutType,d as Session,e as api}; | ||
//# sourceMappingURL=index.js.map |
@@ -17,10 +17,6 @@ import SessionConnection, { SessionConnectionOpts } from './sessionConnection'; | ||
private readonly codeSnippetOpts?; | ||
private _codeSnippet?; | ||
private _terminal?; | ||
private _filesystem?; | ||
private _process?; | ||
get codeSnippet(): CodeSnippetManager | undefined; | ||
get terminal(): TerminalManager | undefined; | ||
get filesystem(): FilesystemManager | undefined; | ||
get process(): ProcessManager | undefined; | ||
codeSnippet?: CodeSnippetManager; | ||
terminal?: TerminalManager; | ||
filesystem?: FilesystemManager; | ||
process?: ProcessManager; | ||
constructor(opts: SessionOpts); | ||
@@ -27,0 +23,0 @@ open(): Promise<void>; |
@@ -1,2 +0,2 @@ | ||
!function(s,i){"object"==typeof exports&&"undefined"!=typeof module?i(exports,require("rpc-websocket-client"),require("cross-fetch/polyfill"),require("openapi-typescript-fetch")):"function"==typeof define&&define.amd?define(["exports","rpc-websocket-client","cross-fetch/polyfill","openapi-typescript-fetch"],i):i((s="undefined"!=typeof globalThis?globalThis:s||self)["@devbookhq/sdk"]={},s.rpcWebsocketClient,null,s.openapiTypescriptFetch)}(this,(function(s,i,e,t){"use strict";function o(s,i,e,t){return new(e||(e=Promise))((function(o,n){function r(s){try{c(t.next(s))}catch(s){n(s)}}function l(s){try{c(t.throw(s))}catch(s){n(s)}}function c(s){var i;s.done?o(s.value):(i=s.value,i instanceof e?i:new e((function(s){s(i)}))).then(r,l)}c((t=t.apply(s,i||[])).next())}))}const n=t.Fetcher.for();function r(s){return new Promise((i=>setTimeout(i,s)))}n.configure({baseUrl:"https://ondevbook.com"});class l{constructor(s,i=!1){this.logID=s,this.isEnabled=i}id(){return"function"==typeof this.logID?this.logID():this.logID}log(...s){this.isEnabled&&console.log(`[36m[${this.id()}][0m`,...s)}error(...s){console.error(`[31m[${this.id()} ERROR][0m`,...s)}}const c=n.path("/sessions").method("post").create({api_key:!0}),h=n.path("/sessions/{sessionID}/refresh").method("post").create({api_key:!0});const d="codeSnippet";var a;s.CodeSnippetExecState=void 0,(a=s.CodeSnippetExecState||(s.CodeSnippetExecState={})).Running="Running",a.Stopped="Stopped";const u="terminal",p="process";var g;s.OutType=void 0,(g=s.OutType||(s.OutType={})).Stdout="Stdout",g.Stderr="Stderr",s.Session=class extends class{constructor(s){this.opts=s,this.isOpen=!1,this.rpc=new i.RpcWebSocketClient,this.subscribers=[],this.logger=new l("Session",s.debug),this.logger.log(`Session for code snippet "${s.id}" initialized`)}call(s,i){return o(this,void 0,void 0,(function*(){return this.rpc.call(s,i)}))}unsubscribe(s){return o(this,void 0,void 0,(function*(){const i=this.subscribers.find((i=>i.subscriptionID===s));i&&(yield this.call(`${i.method}_unsubscribe`,[null==i?void 0:i.subscriptionID]),this.subscribers=this.subscribers.filter((s=>s!==i)),this.logger.log(`Unsubscribed from "${i.method}"`))}))}subscribe(s,i,...e){return o(this,void 0,void 0,(function*(){const t=yield this.call(`${s}_subscribe`,e);if("string"!=typeof t)throw new Error(`Cannot subscribe to ${s} with params ${e}. Expected response to be a subscription ID, instead got ${JSON.stringify(t)}`);return this.subscribers.push({subscriptionID:t,handler:i,method:s}),this.logger.log(`Subscribed to "${s}_${e}" with id "${t}"`),t}))}getHostname(s){if(!this.session)return;const i=`${this.session.sessionID}-${this.session.clientID}.ondevbook.com`;return s?`${s}-${i}`:i}close(){var s,i,e;return o(this,void 0,void 0,(function*(){if(this.isOpen){this.logger.log("Closing",this.session),this.isOpen=!1,this.logger.log("Unsubscribing...");(yield Promise.allSettled(this.subscribers.map((s=>this.unsubscribe(s.subscriptionID))))).forEach((s=>{"rejected"===s.status&&this.logger.log(`Failed to unsubscribe: "${s.reason}"`)})),null===(s=this.rpc.ws)||void 0===s||s.close(),null===(e=null===(i=this.opts)||void 0===i?void 0:i.onClose)||void 0===e||e.call(i),this.logger.log("Disconected from the session")}}))}open(){return o(this,void 0,void 0,(function*(){if(this.isOpen||this.session)throw new Error("Session connect was already called");this.isOpen=!0;try{const s=yield c({codeSnippetID:this.opts.id,editEnabled:this.opts.editEnabled,api_key:this.opts.apiKey});this.session=s.data,this.logger.log("Aquired session:",this.session),this.refresh(this.session.sessionID)}catch(s){if(s instanceof c.Error){const i=s.getActualType();if(400===i.status)throw new Error(`Error creating session - (${i.status}) bad request: ${i.data.message}`);if(401===i.status)throw new Error(`Error creating session - (${i.status}) unauthenticated (you need to be authenticated to start an session with persistent edits): ${i.data.message}`);if(500===i.status)throw new Error(`Error creating session - (${i.status}) server error: ${i.data.message}`);throw s}}if(!this.session)throw new Error("Session is not defined");const s=this.getHostname(8010);if(!s)throw new Error("Cannot get session's hostname");const i=`wss://${s}/ws`;this.rpc.onError((s=>{this.logger.log("Error in WS session:",this.session,s)}));let e,t,n=!1;const l=new Promise(((s,i)=>{e=()=>{n||(n=!0,s())},t=()=>{n||(n=!0,i())}}));this.rpc.onOpen((()=>{this.logger.log("Connected to session:",this.session),null==e||e()})),this.rpc.onClose((s=>o(this,void 0,void 0,(function*(){var e,o,n,l;if(this.logger.log("Closing WS connection to session:",this.session,s),this.isOpen){null===(o=(e=this.opts).onDisconnect)||void 0===o||o.call(e),yield r(100),this.logger.log("Reconnecting to session:",this.session);try{yield this.rpc.connect(i),null===(l=(n=this.opts).onReconnect)||void 0===l||l.call(n),this.logger.log("Reconnected to session:",this.session)}catch(s){this.logger.log("Failed reconnecting to session:",this.session,s)}}else null==t||t()})))),this.rpc.onNotification.push(this.handleNotification.bind(this));try{this.logger.log("Connection to session:",this.session),yield this.rpc.connect(i)}catch(s){this.logger.log("Error connecting to session",this.session,s)}yield l}))}handleNotification(s){this.subscribers.filter((i=>{var e;return i.subscriptionID===(null===(e=s.params)||void 0===e?void 0:e.subscription)})).forEach((i=>{var e;return i.handler(null===(e=s.params)||void 0===e?void 0:e.result)}))}refresh(s){return o(this,void 0,void 0,(function*(){this.logger.log(`Started refreshing session "${s}"`);try{for(;;){if(!this.isOpen)return void this.logger.log("Cannot refresh session - it was closed",this.session);yield r(5e3);try{this.logger.log(`Refreshed session "${s}"`),yield h({sessionID:s,api_key:this.opts.apiKey})}catch(i){if(i instanceof h.Error){const e=i.getActualType();if(404===e.status)return void this.logger.error(`Error refreshing session - (${e.status}): ${e.data.message}`);this.logger.error(`Refreshing session "${s}" failed - (${e.status})`)}}}}finally{this.logger.log(`Stopped refreshing session "${s}"`),this.close()}}))}}{constructor(s){super(s),this.codeSnippetOpts=s.codeSnippet}get codeSnippet(){return this.isOpen&&this.session?this._codeSnippet:void 0}get terminal(){return this.isOpen&&this.session?this._terminal:void 0}get filesystem(){return this.isOpen&&this.session?this._filesystem:void 0}get process(){return this.isOpen&&this.session?this._process:void 0}open(){const s=Object.create(null,{open:{get:()=>super.open}});var i,e,t,n;return o(this,void 0,void 0,(function*(){yield s.open.call(this),yield Promise.all([(null===(i=this.codeSnippetOpts)||void 0===i?void 0:i.onStateChange)?this.subscribe(d,this.codeSnippetOpts.onStateChange,"state"):Promise.resolve(),(null===(e=this.codeSnippetOpts)||void 0===e?void 0:e.onStderr)?this.subscribe(d,this.codeSnippetOpts.onStderr,"stderr"):Promise.resolve(),(null===(t=this.codeSnippetOpts)||void 0===t?void 0:t.onStdout)?this.subscribe(d,this.codeSnippetOpts.onStdout,"stdout"):Promise.resolve(),(null===(n=this.codeSnippetOpts)||void 0===n?void 0:n.onScanPorts)?this.subscribe(d,this.codeSnippetOpts.onScanPorts,"scanOpenedPorts"):Promise.resolve()]),this._codeSnippet={run:(s,i={})=>o(this,void 0,void 0,(function*(){var e,t;const o=yield this.call("codeSnippet_run",[s,i]);return null===(t=null===(e=this.codeSnippetOpts)||void 0===e?void 0:e.onStateChange)||void 0===t||t.call(e,o),o})),stop:()=>o(this,void 0,void 0,(function*(){var s,i;const e=yield this.call("codeSnippet_stop");return null===(i=null===(s=this.codeSnippetOpts)||void 0===s?void 0:s.onStateChange)||void 0===i||i.call(s,e),e}))},this._filesystem={listAllFiles:s=>o(this,void 0,void 0,(function*(){return yield this.call("filesystem_listAllFiles",[s])})),removeFile:s=>o(this,void 0,void 0,(function*(){yield this.call("filesystem_removeFile",[s])})),writeFile:(s,i)=>o(this,void 0,void 0,(function*(){yield this.call("filesystem_writeFile",[s,i])})),readFile:s=>o(this,void 0,void 0,(function*(){return yield this.call("filesystem_readFile",[s])}))},this._terminal={killProcess:s=>o(this,void 0,void 0,(function*(){yield this.call("terminal_killProcess",[s])})),createSession:({onData:s,onChildProcessesChange:i,size:e,activeTerminalID:t})=>o(this,void 0,void 0,(function*(){try{const n=yield this.call("terminal_start",[t||"",e.cols,e.rows]);if("string"!=typeof n)throw new Error("Cannot initialize terminal");const[r,l]=yield Promise.all([this.subscribe(u,s,"onData",n),i?this.subscribe(u,i,"onChildProcessesChange",n):void 0]);return{terminalID:n,destroy:()=>o(this,void 0,void 0,(function*(){yield Promise.all([this.unsubscribe(r),l?this.unsubscribe(l):void 0,yield this.call("terminal_destroy",[n])])})),sendData:s=>o(this,void 0,void 0,(function*(){yield this.call("terminal_data",[n,s])})),resize:({cols:s,rows:i})=>o(this,void 0,void 0,(function*(){yield this.call("terminal_resize",[n,s,i])}))}}catch(s){throw this.logger.error(s),new Error("Error starting terminal session",s)}}))},this._process={start:({cmd:s,onStdout:i,onStderr:e,onExit:t,envVars:n={},rootdir:r="/"})=>o(this,void 0,void 0,(function*(){const l=function(s){let i="";const e="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789",t=e.length;for(let o=0;o<s;o++)i+=e.charAt(Math.floor(Math.random()*t));return i}(12);try{const[c,h,d]=yield Promise.all([t?this.subscribe(p,t,"onExit",l):void 0,i?this.subscribe(p,i,"onStdout",l):void 0,e?this.subscribe(p,e,"onStderr",l):void 0]);return yield this.call("process_start",[l,s,n,r]),{processID:l,kill:()=>o(this,void 0,void 0,(function*(){c&&(yield this.unsubscribe(c)),yield Promise.all([h?this.unsubscribe(h):void 0,d?this.unsubscribe(d):void 0,this.call("terminal_kill",[l])]),null==t||t()})),sendStdin:s=>o(this,void 0,void 0,(function*(){yield this.call("process_stdin",[l,s])}))}}catch(s){throw this.logger.error(s),new Error("Error starting process",s)}}))}}))}},s.api=n,Object.defineProperty(s,"__esModule",{value:!0})})); | ||
!function(s,i){"object"==typeof exports&&"undefined"!=typeof module?i(exports,require("rpc-websocket-client"),require("cross-fetch/polyfill"),require("openapi-typescript-fetch")):"function"==typeof define&&define.amd?define(["exports","rpc-websocket-client","cross-fetch/polyfill","openapi-typescript-fetch"],i):i((s="undefined"!=typeof globalThis?globalThis:s||self)["@devbookhq/sdk"]={},s.rpcWebsocketClient,null,s.openapiTypescriptFetch)}(this,(function(s,i,e,t){"use strict";function o(s,i,e,t){return new(e||(e=Promise))((function(o,n){function r(s){try{c(t.next(s))}catch(s){n(s)}}function l(s){try{c(t.throw(s))}catch(s){n(s)}}function c(s){var i;s.done?o(s.value):(i=s.value,i instanceof e?i:new e((function(s){s(i)}))).then(r,l)}c((t=t.apply(s,i||[])).next())}))}const n=t.Fetcher.for();function r(s){return new Promise((i=>setTimeout(i,s)))}n.configure({baseUrl:"https://ondevbook.com"});class l{constructor(s,i=!1){this.logID=s,this.isEnabled=i}id(){return"function"==typeof this.logID?this.logID():this.logID}log(...s){this.isEnabled&&console.log(`[36m[${this.id()}][0m`,...s)}error(...s){console.error(`[31m[${this.id()} ERROR][0m`,...s)}}const c=n.path("/sessions").method("post").create({api_key:!0}),d=n.path("/sessions/{sessionID}/refresh").method("post").create({api_key:!0});const h="codeSnippet";var a;s.CodeSnippetExecState=void 0,(a=s.CodeSnippetExecState||(s.CodeSnippetExecState={})).Running="Running",a.Stopped="Stopped";const u="terminal",p="process";var g;s.OutType=void 0,(g=s.OutType||(s.OutType={})).Stdout="Stdout",g.Stderr="Stderr",s.Session=class extends class{constructor(s){this.opts=s,this.isOpen=!1,this.rpc=new i.RpcWebSocketClient,this.subscribers=[],this.logger=new l("Session",s.debug),this.logger.log(`Session for code snippet "${s.id}" initialized`)}call(s,i){return o(this,void 0,void 0,(function*(){return this.rpc.call(s,i)}))}unsubscribe(s){return o(this,void 0,void 0,(function*(){const i=this.subscribers.find((i=>i.subscriptionID===s));i&&(yield this.call(`${i.method}_unsubscribe`,[null==i?void 0:i.subscriptionID]),this.subscribers=this.subscribers.filter((s=>s!==i)),this.logger.log(`Unsubscribed from "${i.method}"`))}))}subscribe(s,i,...e){return o(this,void 0,void 0,(function*(){const t=yield this.call(`${s}_subscribe`,e);if("string"!=typeof t)throw new Error(`Cannot subscribe to ${s} with params ${e}. Expected response to be a subscription ID, instead got ${JSON.stringify(t)}`);return this.subscribers.push({subscriptionID:t,handler:i,method:s}),this.logger.log(`Subscribed to "${s}_${e}" with id "${t}"`),t}))}getHostname(s){if(!this.session)return;const i=`${this.session.sessionID}-${this.session.clientID}.ondevbook.com`;return s?`${s}-${i}`:i}close(){var s,i,e;return o(this,void 0,void 0,(function*(){if(this.isOpen){this.logger.log("Closing",this.session),this.isOpen=!1,this.logger.log("Unsubscribing...");(yield Promise.allSettled(this.subscribers.map((s=>this.unsubscribe(s.subscriptionID))))).forEach((s=>{"rejected"===s.status&&this.logger.log(`Failed to unsubscribe: "${s.reason}"`)})),null===(s=this.rpc.ws)||void 0===s||s.close(),null===(e=null===(i=this.opts)||void 0===i?void 0:i.onClose)||void 0===e||e.call(i),this.logger.log("Disconected from the session")}}))}open(){return o(this,void 0,void 0,(function*(){if(this.isOpen||this.session)throw new Error("Session connect was already called");this.isOpen=!0;try{const s=yield c({codeSnippetID:this.opts.id,editEnabled:this.opts.editEnabled,api_key:this.opts.apiKey});this.session=s.data,this.logger.log("Aquired session:",this.session),this.refresh(this.session.sessionID)}catch(s){if(s instanceof c.Error){const i=s.getActualType();if(400===i.status)throw new Error(`Error creating session - (${i.status}) bad request: ${i.data.message}`);if(401===i.status)throw new Error(`Error creating session - (${i.status}) unauthenticated (you need to be authenticated to start an session with persistent edits): ${i.data.message}`);if(500===i.status)throw new Error(`Error creating session - (${i.status}) server error: ${i.data.message}`);throw s}}if(!this.session)throw new Error("Session is not defined");const s=this.getHostname(8010);if(!s)throw new Error("Cannot get session's hostname");const i=`wss://${s}/ws`;this.rpc.onError((s=>{this.logger.log("Error in WS session:",this.session,s)}));let e,t,n=!1;const l=new Promise(((s,i)=>{e=()=>{n||(n=!0,s())},t=()=>{n||(n=!0,i())}}));this.rpc.onOpen((()=>{this.logger.log("Connected to session:",this.session),null==e||e()})),this.rpc.onClose((s=>o(this,void 0,void 0,(function*(){var e,o,n,l;if(this.logger.log("Closing WS connection to session:",this.session,s),this.isOpen){null===(o=(e=this.opts).onDisconnect)||void 0===o||o.call(e),yield r(100),this.logger.log("Reconnecting to session:",this.session);try{yield this.rpc.connect(i),null===(l=(n=this.opts).onReconnect)||void 0===l||l.call(n),this.logger.log("Reconnected to session:",this.session)}catch(s){this.logger.log("Failed reconnecting to session:",this.session,s)}}else null==t||t()})))),this.rpc.onNotification.push(this.handleNotification.bind(this));try{this.logger.log("Connection to session:",this.session),yield this.rpc.connect(i)}catch(s){this.logger.log("Error connecting to session",this.session,s)}yield l}))}handleNotification(s){this.subscribers.filter((i=>{var e;return i.subscriptionID===(null===(e=s.params)||void 0===e?void 0:e.subscription)})).forEach((i=>{var e;return i.handler(null===(e=s.params)||void 0===e?void 0:e.result)}))}refresh(s){return o(this,void 0,void 0,(function*(){this.logger.log(`Started refreshing session "${s}"`);try{for(;;){if(!this.isOpen)return void this.logger.log("Cannot refresh session - it was closed",this.session);yield r(5e3);try{this.logger.log(`Refreshed session "${s}"`),yield d({sessionID:s,api_key:this.opts.apiKey})}catch(i){if(i instanceof d.Error){const e=i.getActualType();if(404===e.status)return void this.logger.error(`Error refreshing session - (${e.status}): ${e.data.message}`);this.logger.error(`Refreshing session "${s}" failed - (${e.status})`)}}}}finally{this.logger.log(`Stopped refreshing session "${s}"`),this.close()}}))}}{constructor(s){super(s),this.codeSnippetOpts=s.codeSnippet}open(){const s=Object.create(null,{open:{get:()=>super.open}});var i,e,t,n;return o(this,void 0,void 0,(function*(){yield s.open.call(this),yield Promise.all([(null===(i=this.codeSnippetOpts)||void 0===i?void 0:i.onStateChange)?this.subscribe(h,this.codeSnippetOpts.onStateChange,"state"):Promise.resolve(),(null===(e=this.codeSnippetOpts)||void 0===e?void 0:e.onStderr)?this.subscribe(h,this.codeSnippetOpts.onStderr,"stderr"):Promise.resolve(),(null===(t=this.codeSnippetOpts)||void 0===t?void 0:t.onStdout)?this.subscribe(h,this.codeSnippetOpts.onStdout,"stdout"):Promise.resolve(),(null===(n=this.codeSnippetOpts)||void 0===n?void 0:n.onScanPorts)?this.subscribe(h,this.codeSnippetOpts.onScanPorts,"scanOpenedPorts"):Promise.resolve()]),this.codeSnippet={run:(s,i={})=>o(this,void 0,void 0,(function*(){var e,t;const o=yield this.call("codeSnippet_run",[s,i]);return null===(t=null===(e=this.codeSnippetOpts)||void 0===e?void 0:e.onStateChange)||void 0===t||t.call(e,o),o})),stop:()=>o(this,void 0,void 0,(function*(){var s,i;const e=yield this.call("codeSnippet_stop");return null===(i=null===(s=this.codeSnippetOpts)||void 0===s?void 0:s.onStateChange)||void 0===i||i.call(s,e),e}))},this.filesystem={listAllFiles:s=>o(this,void 0,void 0,(function*(){return yield this.call("filesystem_listAllFiles",[s])})),removeFile:s=>o(this,void 0,void 0,(function*(){yield this.call("filesystem_removeFile",[s])})),writeFile:(s,i)=>o(this,void 0,void 0,(function*(){yield this.call("filesystem_writeFile",[s,i])})),readFile:s=>o(this,void 0,void 0,(function*(){return yield this.call("filesystem_readFile",[s])}))},this.terminal={killProcess:s=>o(this,void 0,void 0,(function*(){yield this.call("terminal_killProcess",[s])})),createSession:({onData:s,onChildProcessesChange:i,size:e,activeTerminalID:t})=>o(this,void 0,void 0,(function*(){const n=yield this.call("terminal_start",[t||"",e.cols,e.rows]);if("string"!=typeof n)throw new Error("Cannot initialize terminal");const[r,l]=yield Promise.all([this.subscribe(u,s,"onData",n),i?this.subscribe(u,i,"onChildProcessesChange",n):void 0]);return{terminalID:n,destroy:()=>o(this,void 0,void 0,(function*(){yield Promise.all([this.unsubscribe(r),l?this.unsubscribe(l):void 0,yield this.call("terminal_destroy",[n])])})),sendData:s=>o(this,void 0,void 0,(function*(){yield this.call("terminal_data",[n,s])})),resize:({cols:s,rows:i})=>o(this,void 0,void 0,(function*(){yield this.call("terminal_resize",[n,s,i])}))}}))},this.process={start:({cmd:s,onStdout:i,onStderr:e,onExit:t,envVars:n={},rootdir:r="/"})=>o(this,void 0,void 0,(function*(){const l=function(s){let i="";const e="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789",t=e.length;for(let o=0;o<s;o++)i+=e.charAt(Math.floor(Math.random()*t));return i}(12),[c,d,h]=yield Promise.all([t?this.subscribe(p,t,"onExit",l):void 0,i?this.subscribe(p,i,"onStdout",l):void 0,e?this.subscribe(p,e,"onStderr",l):void 0]);return yield this.call("process_start",[l,s,n,r]),{processID:l,kill:()=>o(this,void 0,void 0,(function*(){c&&(yield this.unsubscribe(c)),yield Promise.all([d?this.unsubscribe(d):void 0,h?this.unsubscribe(h):void 0,this.call("terminal_kill",[l])]),null==t||t()})),sendStdin:s=>o(this,void 0,void 0,(function*(){yield this.call("process_stdin",[l,s])}))}}))}}))}},s.api=n,Object.defineProperty(s,"__esModule",{value:!0})})); | ||
//# sourceMappingURL=index.js.map |
@@ -17,10 +17,6 @@ import SessionConnection, { SessionConnectionOpts } from './sessionConnection'; | ||
private readonly codeSnippetOpts?; | ||
private _codeSnippet?; | ||
private _terminal?; | ||
private _filesystem?; | ||
private _process?; | ||
get codeSnippet(): CodeSnippetManager | undefined; | ||
get terminal(): TerminalManager | undefined; | ||
get filesystem(): FilesystemManager | undefined; | ||
get process(): ProcessManager | undefined; | ||
codeSnippet?: CodeSnippetManager; | ||
terminal?: TerminalManager; | ||
filesystem?: FilesystemManager; | ||
process?: ProcessManager; | ||
constructor(opts: SessionOpts); | ||
@@ -27,0 +23,0 @@ open(): Promise<void>; |
{ | ||
"name": "@devbookhq/sdk", | ||
"version": "2.4.1", | ||
"version": "2.4.2", | ||
"description": "Devbook allows visitors of your docs to interact with and execute any code snippet or shell command in a private VM", | ||
@@ -5,0 +5,0 @@ "homepage": "https://usedevbook.com", |
@@ -42,23 +42,7 @@ import SessionConnection, { | ||
private _codeSnippet?: CodeSnippetManager | ||
private _terminal?: TerminalManager | ||
private _filesystem?: FilesystemManager | ||
private _process?: ProcessManager | ||
codeSnippet?: CodeSnippetManager | ||
terminal?: TerminalManager | ||
filesystem?: FilesystemManager | ||
process?: ProcessManager | ||
get codeSnippet() { | ||
return (this.isOpen && this.session) ? this._codeSnippet : undefined | ||
} | ||
get terminal() { | ||
return (this.isOpen && this.session) ? this._terminal : undefined | ||
} | ||
get filesystem() { | ||
return (this.isOpen && this.session) ? this._filesystem : undefined | ||
} | ||
get process() { | ||
return (this.isOpen && this.session) ? this._process : undefined | ||
} | ||
constructor(opts: SessionOpts) { | ||
@@ -88,3 +72,3 @@ super(opts) | ||
// Init CodeSnippet handler | ||
this._codeSnippet = { | ||
this.codeSnippet = { | ||
run: async (code, envVars = {}) => { | ||
@@ -103,6 +87,5 @@ const state = await this.call(`${codeSnippetMethod}_run`, [code, envVars]) as CodeSnippetExecState | ||
// Init Filesystem handler | ||
this._filesystem = { | ||
this.filesystem = { | ||
listAllFiles: async (path) => { | ||
const files = await this.call(`${filesystemMethod}_listAllFiles`, [path]) as FileInfo[] | ||
return files | ||
return await this.call(`${filesystemMethod}_listAllFiles`, [path]) as FileInfo[] | ||
}, | ||
@@ -116,4 +99,3 @@ removeFile: async (path) => { | ||
readFile: async (path) => { | ||
const content = await this.call(`${filesystemMethod}_readFile`, [path]) as string | ||
return content | ||
return await this.call(`${filesystemMethod}_readFile`, [path]) as string | ||
}, | ||
@@ -123,3 +105,3 @@ } | ||
// Init Terminal handler | ||
this._terminal = { | ||
this.terminal = { | ||
killProcess: async (pid) => { | ||
@@ -129,33 +111,30 @@ await this.call(`${terminalMethod}_killProcess`, [pid]) | ||
createSession: async ({ onData, onChildProcessesChange, size, activeTerminalID }) => { | ||
try { | ||
const terminalID = await this.call(`${terminalMethod}_start`, [activeTerminalID ? activeTerminalID : '', size.cols, size.rows]) | ||
if (typeof terminalID !== 'string') { | ||
throw new Error('Cannot initialize terminal') | ||
} | ||
const terminalID = await this.call(`${terminalMethod}_start`, [activeTerminalID ? activeTerminalID : '', size.cols, size.rows]) | ||
if (typeof terminalID !== 'string') { | ||
throw new Error('Cannot initialize terminal') | ||
} | ||
const [onDataSubscriptionID, onChildProcessesChangeSubscriptionID] = await Promise.all([ | ||
this.subscribe(terminalMethod, onData, 'onData', terminalID), | ||
onChildProcessesChange ? this.subscribe(terminalMethod, onChildProcessesChange, 'onChildProcessesChange', terminalID) : undefined, | ||
]) | ||
const [ | ||
onDataSubscriptionID, | ||
onChildProcessesChangeSubscriptionID, | ||
] = await Promise.all([ | ||
this.subscribe(terminalMethod, onData, 'onData', terminalID), | ||
onChildProcessesChange ? this.subscribe(terminalMethod, onChildProcessesChange, 'onChildProcessesChange', terminalID) : undefined, | ||
]) | ||
return { | ||
terminalID, | ||
destroy: async () => { | ||
await Promise.all([ | ||
this.unsubscribe(onDataSubscriptionID), | ||
onChildProcessesChangeSubscriptionID ? this.unsubscribe(onChildProcessesChangeSubscriptionID) : undefined, | ||
await this.call(`${terminalMethod}_destroy`, [terminalID]) | ||
]) | ||
}, | ||
sendData: async (data) => { | ||
await this.call(`${terminalMethod}_data`, [terminalID, data]) | ||
}, | ||
resize: async ({ cols, rows }) => { | ||
await this.call(`${terminalMethod}_resize`, [terminalID, cols, rows]) | ||
}, | ||
} | ||
// eslint-disable-next-line @typescript-eslint/no-explicit-any | ||
} catch (err: any) { | ||
this.logger.error(err) | ||
throw new Error('Error starting terminal session', err) | ||
return { | ||
terminalID, | ||
destroy: async () => { | ||
await Promise.all([ | ||
this.unsubscribe(onDataSubscriptionID), | ||
onChildProcessesChangeSubscriptionID ? this.unsubscribe(onChildProcessesChangeSubscriptionID) : undefined, | ||
await this.call(`${terminalMethod}_destroy`, [terminalID]) | ||
]) | ||
}, | ||
sendData: async (data) => { | ||
await this.call(`${terminalMethod}_data`, [terminalID, data]) | ||
}, | ||
resize: async ({ cols, rows }) => { | ||
await this.call(`${terminalMethod}_resize`, [terminalID, cols, rows]) | ||
}, | ||
} | ||
@@ -166,37 +145,35 @@ } | ||
// Init Process handler | ||
this._process = { | ||
this.process = { | ||
start: async ({ cmd, onStdout, onStderr, onExit, envVars = {}, rootdir = '/' }) => { | ||
// TODO: If the process or one of the subscriptions fails to register we are currently not unsubscribing from the others | ||
// We are generating process ID in the SDK because we need to subscribe to the process stdout/stderr before starting it. | ||
const processID = id(12) | ||
try { | ||
const [onExitSubscriptionID, onStdoutSubscriptionID, onStderrSubscriptionID] = await Promise.all([ | ||
onExit ? this.subscribe(processMethod, onExit, 'onExit', processID) : undefined, | ||
onStdout ? this.subscribe(processMethod, onStdout, 'onStdout', processID) : undefined, | ||
onStderr ? this.subscribe(processMethod, onStderr, 'onStderr', processID) : undefined, | ||
]) | ||
const [ | ||
onExitSubscriptionID, | ||
onStdoutSubscriptionID, | ||
onStderrSubscriptionID, | ||
] = await Promise.all([ | ||
onExit ? this.subscribe(processMethod, onExit, 'onExit', processID) : undefined, | ||
onStdout ? this.subscribe(processMethod, onStdout, 'onStdout', processID) : undefined, | ||
onStderr ? this.subscribe(processMethod, onStderr, 'onStderr', processID) : undefined, | ||
]) | ||
await this.call(`${processMethod}_start`, [processID, cmd, envVars, rootdir]) | ||
await this.call(`${processMethod}_start`, [processID, cmd, envVars, rootdir]) | ||
return { | ||
processID, | ||
kill: async () => { | ||
if (onExitSubscriptionID) await this.unsubscribe(onExitSubscriptionID) | ||
return { | ||
processID, | ||
kill: async () => { | ||
if (onExitSubscriptionID) await this.unsubscribe(onExitSubscriptionID) | ||
await Promise.all([ | ||
onStdoutSubscriptionID ? this.unsubscribe(onStdoutSubscriptionID) : undefined, | ||
onStderrSubscriptionID ? this.unsubscribe(onStderrSubscriptionID) : undefined, | ||
this.call(`${terminalMethod}_kill`, [processID]), | ||
]) | ||
await Promise.all([ | ||
onStdoutSubscriptionID ? this.unsubscribe(onStdoutSubscriptionID) : undefined, | ||
onStderrSubscriptionID ? this.unsubscribe(onStderrSubscriptionID) : undefined, | ||
this.call(`${terminalMethod}_kill`, [processID]), | ||
]) | ||
onExit?.() | ||
}, | ||
sendStdin: async (data) => { | ||
await this.call(`${processMethod}_stdin`, [processID, data]) | ||
}, | ||
} | ||
// eslint-disable-next-line @typescript-eslint/no-explicit-any | ||
} catch (err: any) { | ||
// TODO: If the process or one of the subscriptions fails to register we are currently not unsubscribing from the others | ||
this.logger.error(err) | ||
throw new Error('Error starting process', err) | ||
onExit?.() | ||
}, | ||
sendStdin: async (data) => { | ||
await this.call(`${processMethod}_stdin`, [processID, data]) | ||
}, | ||
} | ||
@@ -203,0 +180,0 @@ } |
Sorry, the diff of this file is not supported yet
Sorry, the diff of this file is not supported yet
Sorry, the diff of this file is not supported yet
207973
2422