-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathimports.js
139 lines (88 loc) · 4.02 KB
/
imports.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
let Websockets = []
const ws = require('ws')
class WebSocketImport {
constructor() {
this._exports = null
this.wasmImports = {
WebSocket: {
sendPointer: (id, event, pointer) => {
if (!Websockets[id]) return
Websockets[id]['pointers'][this._exports.__getString(event).toLowerCase().trim()] = this._exports.table.get(pointer)
},
initWS: (address) => {
Websockets.push({
pointers: {
message: null,
error: null,
listening: null,
connect: null,
close: null
},
socket: new ws(this._exports.__getString(address)),
cache: [],
ready: false
})
let id = Websockets.length - 1
let socket = Websockets[id]
// Handle messages before ready (b/c closures) :P
socket.socket.on('open', () => {
socket.ready = true
for (const message of socket.cache) {
socket.socket.send(message)
}
})
socket.socket.on('message', (data, info) => {
const func = socket.pointers['message']
if (typeof func === 'function') func(this._exports.__newString(data))
})
socket.socket.on('listening', () => {
const func = socket.pointers['listening']
if (typeof func === 'function') func()
})
socket.socket.on('close', () => {
const func = socket.pointers['close']
if (typeof func === 'function') func()
})
socket.socket.on('error', (err) => {
const func = socket.pointers['error']
if (typeof func === 'function') func(this._exports.__getString(err))
})
socket.socket.on('connect', () => {
const func = socket.pointers['connect']
if (typeof func === 'function') func()
})
return id
},
sendWS: (id, message) => {
if (Websockets[id].ready === false) {
Websockets[id].cache.push(this._exports.__getArray(message))
return
}
Websockets[id]['socket'].send(this._exports.__getArray(message))
return
},
closeWS: (id, number) => {
Websockets[id]['socket'].close(number)
}
},
}
}
get wasmExports() {
return this._exports
}
set wasmExports(e) {
this._exports = e
this._exports.__getString = e.__getString
this._exports.__newString = e.__newString
this._exports.__newArray = e.__newArray
this._exports.__getArray = e.__getArray
}
getFn(fnIndex) {
if (!this.wasmExports)
throw new Error(
'Make sure you set .wasmExports after instantiating the Wasm module but before running the Wasm module.',
)
return this.table.get(fnIndex)
}
}
module.exports = WebSocketImport