@dronedeploy/rocos-js-sdk 3.0.1-alpha.1 → 3.0.1-alpha.2
Sign up to get free protection for your applications and to get access to all the features.
- package/helpers/websandbox/frame/frame.source.js +1 -1
- package/helpers/websandbox/frame/worker/manager.d.ts +1 -3
- package/helpers/websandbox/frame/worker/manager.js +20 -18
- package/helpers/websandbox/frame/worker/manager.spec.d.ts +4 -0
- package/helpers/websandbox/frame/worker/manager.spec.js +121 -0
- package/package.json +1 -1
@@ -1,5 +1,5 @@
|
|
1
1
|
// Auto-generated file
|
2
2
|
/* eslint-disable */
|
3
3
|
import __WORKER_SOURCE__ from './worker/worker.source';
|
4
|
-
const source = `(()=>{"use strict";var e={880:(e,t)=>{var s;Object.defineProperty(t,"__esModule",{value:!0}),function(e){e.RESPONSE="response",e.MESSAGE="message"}(s||(s={}));const r={allowedSenderOrigin:void 0,debugMode:!1};t.default=class{constructor(e,t,s,i,o={}){this.callbacks=new Map,this.serviceMethods=new Map,this.name=e,this.options={...r,...o},this.log("Created connection w/ allowedOrigin:",this.options.allowedSenderOrigin),this.serviceMethods=new Map(Object.entries(s));const[n]=crypto.getRandomValues(new Uint32Array(1));this.incrementalID=n,this.postMessageInternal=t,i((e=>this.onMessageListener(e)))}callRemoteMethod(e,...t){return this.log("Calling Remote Method",{name:e,args:t}),new Promise(((r,i)=>{const o=this.registerCallback(r,i);this.postMessage({callId:o,type:s.MESSAGE,methodName:e,arguments:t})}))}onMessageListener(e){this.log("Received message",e);const{data:t}=e,{allowedSenderOrigin:r}=this.options;switch(r&&e.origin!==r&&console.warn(\`Received message from invalid origin: \${e.origin}\`),t.type){case s.RESPONSE:return void this.popCallback(t.callId,t.success,t.result);case s.MESSAGE:this.callLocalMethod(t.methodName,t.arguments).then((e=>this.responseOtherSide(t.callId,e))).catch((e=>this.responseOtherSide(t.callId,e,!1)))}}async callLocalMethod(e,t){this.log("calling local method",e,t);const s=this.serviceMethods.get(e);if(!s)throw new Error(\`service method \${e} not found\`);return s(...t)}responseOtherSide(e,t,r=!0){this.log("responding to remote call",{id:e,result:t,success:r});const i=t=>{this.postMessage({callId:e,type:s.RESPONSE,success:r,result:t})};try{i(t)}catch(e){e instanceof DOMException&&i(JSON.parse(JSON.stringify(t)))}}registerCallback(e,t){const s=(++this.incrementalID).toString();return this.log("registering callback for id",s),this.callbacks.set(s,{success:e,failure:t}),s}popCallback(e,t,s){this.log("calling callback for id",e,{success:t,result:s});const r=this.callbacks.get(e);t?r?.success(s):r?.failure(s),this.callbacks.delete(e)}postMessage(e,t="*"){this.log("sending message",{data:e,targetOrigin:t}),this.postMessageInternal(e,t)}log(...e){this.options.debugMode&&console.debug(\`[\${this.name}]\`,...e)}}},306:function(e,t,s){var r=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0});const i=r(s(880)),o=r(s(54)),n=new class{constructor(){const e=!!window?.debugMode;this.connection=new i.default("FRAME",window.parent.postMessage.bind(window.parent),{startTask:this.runCode.bind(this)},(e=>{window.addEventListener("message",e)}),{debugMode:e}),this.connection.callRemoteMethod("iframeInitialised"),this.workerManager=new o.default}async runCode(e){return this.workerManager.execute(e)}};t.default=n},54:function(e,t,s){var r=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0});const i=r(s(420));t.default=i.default},420:(e,t)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.default=class{constructor(){this.worker=this.createWorker()}async execute(e){const t={...e,contextVariable:e.contextVariable??"ctx"},s=this.runTask(t),r=this.
|
4
|
+
const source = `(()=>{"use strict";var e={880:(e,t)=>{var s;Object.defineProperty(t,"__esModule",{value:!0}),function(e){e.RESPONSE="response",e.MESSAGE="message"}(s||(s={}));const r={allowedSenderOrigin:void 0,debugMode:!1};t.default=class{constructor(e,t,s,i,o={}){this.callbacks=new Map,this.serviceMethods=new Map,this.name=e,this.options={...r,...o},this.log("Created connection w/ allowedOrigin:",this.options.allowedSenderOrigin),this.serviceMethods=new Map(Object.entries(s));const[n]=crypto.getRandomValues(new Uint32Array(1));this.incrementalID=n,this.postMessageInternal=t,i((e=>this.onMessageListener(e)))}callRemoteMethod(e,...t){return this.log("Calling Remote Method",{name:e,args:t}),new Promise(((r,i)=>{const o=this.registerCallback(r,i);this.postMessage({callId:o,type:s.MESSAGE,methodName:e,arguments:t})}))}onMessageListener(e){this.log("Received message",e);const{data:t}=e,{allowedSenderOrigin:r}=this.options;switch(r&&e.origin!==r&&console.warn(\`Received message from invalid origin: \${e.origin}\`),t.type){case s.RESPONSE:return void this.popCallback(t.callId,t.success,t.result);case s.MESSAGE:this.callLocalMethod(t.methodName,t.arguments).then((e=>this.responseOtherSide(t.callId,e))).catch((e=>this.responseOtherSide(t.callId,e,!1)))}}async callLocalMethod(e,t){this.log("calling local method",e,t);const s=this.serviceMethods.get(e);if(!s)throw new Error(\`service method \${e} not found\`);return s(...t)}responseOtherSide(e,t,r=!0){this.log("responding to remote call",{id:e,result:t,success:r});const i=t=>{this.postMessage({callId:e,type:s.RESPONSE,success:r,result:t})};try{i(t)}catch(e){e instanceof DOMException&&i(JSON.parse(JSON.stringify(t)))}}registerCallback(e,t){const s=(++this.incrementalID).toString();return this.log("registering callback for id",s),this.callbacks.set(s,{success:e,failure:t}),s}popCallback(e,t,s){this.log("calling callback for id",e,{success:t,result:s});const r=this.callbacks.get(e);t?r?.success(s):r?.failure(s),this.callbacks.delete(e)}postMessage(e,t="*"){this.log("sending message",{data:e,targetOrigin:t}),this.postMessageInternal(e,t)}log(...e){this.options.debugMode&&console.debug(\`[\${this.name}]\`,...e)}}},306:function(e,t,s){var r=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0});const i=r(s(880)),o=r(s(54)),n=new class{constructor(){const e=!!window?.debugMode;this.connection=new i.default("FRAME",window.parent.postMessage.bind(window.parent),{startTask:this.runCode.bind(this)},(e=>{window.addEventListener("message",e)}),{debugMode:e}),this.connection.callRemoteMethod("iframeInitialised"),this.workerManager=new o.default}async runCode(e){return this.workerManager.execute(e)}};t.default=n},54:function(e,t,s){var r=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0});const i=r(s(420));t.default=i.default},420:(e,t)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.default=class{constructor(){this.messageListeners=new Map,this.worker=this.createWorker()}async execute(e){const t={...e,contextVariable:e.contextVariable??"ctx"},s=this.runTask(t);let r;const i=new Promise(((t,s)=>{r=setTimeout((()=>{console.warn("sandbox level timeout exceeded, destroying and rebuilding"),this.terminate(),s(new Error("maximum execution time exceeded"))}),e.timeout)}));return Promise.race([s,i]).finally((()=>{this.removeMessageListener(e.id),clearTimeout(r)}))}terminate(){for(const e of this.messageListeners.values())this.worker.removeEventListener("message",e);this.worker.terminate(),this.worker=this.createWorker()}runTask(e){return new Promise(((t,s)=>{const r=r=>{const{data:i}=r;i.id===e.id&&(i.success?t(i.result):s(i.result))};this.messageListeners.set(e.id,r),this.worker.addEventListener("message",r),this.worker.postMessage(e)}))}createWorker(){const e=URL.createObjectURL(new Blob(["${__WORKER_SOURCE__.replace(/(['`"$])/g, '\\$1')}"],{type:"application/javascript"}));return new Worker(e)}removeMessageListener(e){const t=this.messageListeners.get(e);t&&this.worker.removeEventListener("message",t)}}}},t={};!function s(r){var i=t[r];if(void 0!==i)return i.exports;var o=t[r]={exports:{}};return e[r].call(o.exports,o,o.exports,s),o.exports}(306)})();`;
|
5
5
|
export default source;
|
@@ -1,13 +1,11 @@
|
|
1
1
|
import { Task } from '../../types';
|
2
2
|
export default class Manager {
|
3
3
|
private worker;
|
4
|
-
private
|
4
|
+
private messageListeners;
|
5
5
|
constructor();
|
6
6
|
execute(task: Task): Promise<unknown>;
|
7
7
|
terminate(): void;
|
8
8
|
private runTask;
|
9
|
-
private timeout;
|
10
|
-
private stopTimer;
|
11
9
|
private createWorker;
|
12
10
|
private removeMessageListener;
|
13
11
|
}
|
@@ -2,6 +2,7 @@
|
|
2
2
|
const WORKER_SOURCE = '__WORKER_SOURCE__';
|
3
3
|
export default class Manager {
|
4
4
|
constructor() {
|
5
|
+
this.messageListeners = new Map();
|
5
6
|
this.worker = this.createWorker();
|
6
7
|
}
|
7
8
|
async execute(task) {
|
@@ -10,13 +11,22 @@ export default class Manager {
|
|
10
11
|
contextVariable: task.contextVariable ?? 'ctx',
|
11
12
|
};
|
12
13
|
const result = this.runTask(workerTask);
|
13
|
-
|
14
|
+
let timerId;
|
15
|
+
const timeout = new Promise((_, reject) => {
|
16
|
+
timerId = setTimeout(() => {
|
17
|
+
this.terminate();
|
18
|
+
reject(new Error('maximum execution time exceeded'));
|
19
|
+
}, task.timeout);
|
20
|
+
});
|
14
21
|
return Promise.race([result, timeout]).finally(() => {
|
15
|
-
this.removeMessageListener();
|
22
|
+
this.removeMessageListener(task.id);
|
23
|
+
clearTimeout(timerId);
|
16
24
|
});
|
17
25
|
}
|
18
26
|
terminate() {
|
19
|
-
this.
|
27
|
+
for (const listener of this.messageListeners.values()) {
|
28
|
+
this.worker.removeEventListener('message', listener);
|
29
|
+
}
|
20
30
|
this.worker.terminate();
|
21
31
|
this.worker = this.createWorker();
|
22
32
|
}
|
@@ -25,7 +35,6 @@ export default class Manager {
|
|
25
35
|
const listener = (event) => {
|
26
36
|
const { data } = event;
|
27
37
|
if (data.id === task.id) {
|
28
|
-
this.stopTimer();
|
29
38
|
if (data.success) {
|
30
39
|
resolve(data.result);
|
31
40
|
}
|
@@ -34,27 +43,20 @@ export default class Manager {
|
|
34
43
|
}
|
35
44
|
}
|
36
45
|
};
|
46
|
+
this.messageListeners.set(task.id, listener);
|
37
47
|
this.worker.addEventListener('message', listener);
|
38
|
-
this.removeMessageListener = () => this.worker.removeEventListener('message', listener);
|
39
48
|
this.worker.postMessage(task);
|
40
49
|
});
|
41
50
|
}
|
42
|
-
timeout(timeoutMs) {
|
43
|
-
return new Promise((_, reject) => {
|
44
|
-
this.timerId = window.setTimeout(() => {
|
45
|
-
this.terminate();
|
46
|
-
reject(new Error('maximum execution time exceeded'));
|
47
|
-
}, timeoutMs);
|
48
|
-
});
|
49
|
-
}
|
50
|
-
stopTimer() {
|
51
|
-
clearTimeout(this.timerId);
|
52
|
-
}
|
53
51
|
createWorker() {
|
54
52
|
const blob = URL.createObjectURL(new Blob([WORKER_SOURCE], { type: 'application/javascript' }));
|
55
53
|
return new Worker(blob);
|
56
54
|
}
|
57
|
-
removeMessageListener() {
|
58
|
-
|
55
|
+
removeMessageListener(id) {
|
56
|
+
const listener = this.messageListeners.get(id);
|
57
|
+
if (!listener) {
|
58
|
+
return;
|
59
|
+
}
|
60
|
+
this.worker.removeEventListener('message', listener);
|
59
61
|
}
|
60
62
|
}
|
@@ -0,0 +1,121 @@
|
|
1
|
+
/**
|
2
|
+
* @jest-environment jsdom
|
3
|
+
*/
|
4
|
+
import WorkerManager from './manager';
|
5
|
+
const WorkerMocks = {
|
6
|
+
postMessage: jest.fn(),
|
7
|
+
terminate: jest.fn(),
|
8
|
+
addEventListener: jest.fn(),
|
9
|
+
removeEventListener: jest.fn(),
|
10
|
+
onerror: jest.fn(),
|
11
|
+
onmessage: jest.fn(),
|
12
|
+
onmessageerror: jest.fn(),
|
13
|
+
dispatchEvent: jest.fn(),
|
14
|
+
clearAllMocks() {
|
15
|
+
this.postMessage.mockClear();
|
16
|
+
this.terminate.mockClear();
|
17
|
+
this.addEventListener.mockClear();
|
18
|
+
this.removeEventListener.mockClear();
|
19
|
+
this.onerror.mockClear();
|
20
|
+
this.onmessage.mockClear();
|
21
|
+
this.onmessageerror.mockClear();
|
22
|
+
this.dispatchEvent.mockClear();
|
23
|
+
},
|
24
|
+
};
|
25
|
+
class MockWorkerClass {
|
26
|
+
constructor() {
|
27
|
+
this.postMessage = WorkerMocks.postMessage;
|
28
|
+
this.terminate = WorkerMocks.terminate;
|
29
|
+
this.addEventListener = WorkerMocks.addEventListener;
|
30
|
+
this.removeEventListener = WorkerMocks.removeEventListener;
|
31
|
+
this.onerror = WorkerMocks.onerror;
|
32
|
+
this.onmessage = WorkerMocks.onmessage;
|
33
|
+
this.onmessageerror = WorkerMocks.onmessageerror;
|
34
|
+
this.dispatchEvent = WorkerMocks.dispatchEvent;
|
35
|
+
}
|
36
|
+
}
|
37
|
+
Object.defineProperty(window, 'Worker', {
|
38
|
+
value: MockWorkerClass,
|
39
|
+
writable: true,
|
40
|
+
});
|
41
|
+
Object.defineProperty(window, 'URL', {
|
42
|
+
value: {
|
43
|
+
createObjectURL: jest.fn(),
|
44
|
+
},
|
45
|
+
});
|
46
|
+
const task = {
|
47
|
+
id: 'test',
|
48
|
+
code: '1',
|
49
|
+
timeout: 1000,
|
50
|
+
};
|
51
|
+
const response = {
|
52
|
+
data: {
|
53
|
+
id: 'test',
|
54
|
+
success: true,
|
55
|
+
result: 'test',
|
56
|
+
},
|
57
|
+
};
|
58
|
+
describe('WorkerManager', () => {
|
59
|
+
beforeEach(() => {
|
60
|
+
WorkerMocks.clearAllMocks();
|
61
|
+
});
|
62
|
+
it('should send a task to the worker', async () => {
|
63
|
+
const listeners = [];
|
64
|
+
WorkerMocks.addEventListener.mockImplementation((_, listener) => {
|
65
|
+
listeners.push(listener);
|
66
|
+
});
|
67
|
+
WorkerMocks.postMessage.mockImplementation((msg) => {
|
68
|
+
listeners.forEach((listener) => {
|
69
|
+
listener(response);
|
70
|
+
});
|
71
|
+
});
|
72
|
+
const manager = new WorkerManager();
|
73
|
+
const result = await manager.execute(task);
|
74
|
+
expect(result).toEqual('test');
|
75
|
+
});
|
76
|
+
it('should handle listener for a single task', async () => {
|
77
|
+
const listeners = [];
|
78
|
+
WorkerMocks.addEventListener.mockImplementation((_, listener) => {
|
79
|
+
listeners.push(listener);
|
80
|
+
});
|
81
|
+
WorkerMocks.removeEventListener.mockImplementation((_, listener) => {
|
82
|
+
const index = listeners.indexOf(listener);
|
83
|
+
listeners.splice(index, 1);
|
84
|
+
});
|
85
|
+
const manager = new WorkerManager();
|
86
|
+
expect(listeners.length).toEqual(0);
|
87
|
+
const result = manager.execute(task);
|
88
|
+
expect(listeners.length).toEqual(1);
|
89
|
+
listeners[0](response);
|
90
|
+
await result;
|
91
|
+
expect(listeners.length).toEqual(0);
|
92
|
+
});
|
93
|
+
it('should handle listener for multiple simultaneous task', async () => {
|
94
|
+
const listeners = [];
|
95
|
+
WorkerMocks.addEventListener.mockImplementation((_, listener) => {
|
96
|
+
listeners.push(listener);
|
97
|
+
});
|
98
|
+
WorkerMocks.removeEventListener.mockImplementation((_, listener) => {
|
99
|
+
const index = listeners.indexOf(listener);
|
100
|
+
listeners.splice(index, 1);
|
101
|
+
});
|
102
|
+
const manager = new WorkerManager();
|
103
|
+
expect(listeners.length).toEqual(0);
|
104
|
+
const result1 = manager.execute(task);
|
105
|
+
const result2 = manager.execute(task);
|
106
|
+
expect(listeners.length).toEqual(2);
|
107
|
+
const result3 = manager.execute(task);
|
108
|
+
expect(listeners.length).toEqual(3);
|
109
|
+
const [listener1, listener2, listener3] = listeners;
|
110
|
+
listener1(response);
|
111
|
+
await result1;
|
112
|
+
expect(listeners.length).toEqual(2);
|
113
|
+
listener3(response);
|
114
|
+
await result3;
|
115
|
+
expect(listeners.length).toEqual(1);
|
116
|
+
listener2(response);
|
117
|
+
await result2;
|
118
|
+
expect(listeners.length).toEqual(0);
|
119
|
+
expect(WorkerMocks.removeEventListener).toHaveBeenCalledTimes(3);
|
120
|
+
});
|
121
|
+
});
|