hsync 0.12.0 → 0.14.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/connection.js CHANGED
@@ -1,12 +1,13 @@
1
- const fetch = require('isomorphic-fetch');
2
1
  const EventEmitter = require('events').EventEmitter;
3
2
  const b64id = require('b64id');
4
3
  const debug = require('debug')('hsync:info');
5
4
  const debugVerbose = require('debug')('hsync:verbose');
6
5
  const debugError = require('debug')('hsync:error');
7
- const { createRPCPeer, createServerReplyPeer } = require('./lib/rpc');
6
+ const { getRPCPeer, createServerPeer } = require('./lib/rpc');
8
7
  const { createWebHandler, setNet: webSetNet } = require('./lib/web-handler');
9
- const { createSocketListenHandler, setNet: listenSetNet } = require('./lib/socket-listen-handler');
8
+ const { createSocketListenHandler, setNet: listenSetNet, receiveRelayData } = require('./lib/socket-listen-handler');
9
+ const { createSocketRelayHandler, setNet: relaySetNet, receiveListenerData, connectSocket } = require('./lib/socket-relay-handler');
10
+ const fetch = require('./lib/fetch');
10
11
 
11
12
  debug.color = 3;
12
13
  debugVerbose.color = 2;
@@ -17,6 +18,7 @@ let mqtt;
17
18
  function setNet(netImpl) {
18
19
  webSetNet(netImpl);
19
20
  listenSetNet(netImpl);
21
+ relaySetNet(netImpl);
20
22
  }
21
23
 
22
24
  function setMqtt(mqttImpl) {
@@ -37,16 +39,7 @@ async function createHsync(config) {
37
39
  let dynamicTimeout;
38
40
 
39
41
  if (dynamicHost) {
40
- const options = {
41
- headers: {
42
- 'Content-Type': 'application/json',
43
- },
44
- method: 'POST',
45
- body: '{}',
46
- };
47
- const resp = await fetch(`${dynamicHost}/${hsyncBase}/dyn`, options);
48
- const result = await resp.json();
49
- // console.log('resutl', result);
42
+ const result = await fetch.post(`${dynamicHost}/${hsyncBase}/dyn`, {});
50
43
  if (dynamicHost.toLowerCase().startsWith('https')) {
51
44
  hsyncServer = `wss://${result.url}`;
52
45
  } else {
@@ -58,13 +51,14 @@ async function createHsync(config) {
58
51
 
59
52
  const hsyncClient = {};
60
53
  hsyncClient.config = config;
61
- const peers = {};
54
+ // const peers = {};
62
55
  const socketListeners = {};
56
+ const socketRelays= {};
63
57
  const events = new EventEmitter();
64
58
 
65
59
  hsyncClient.on = events.on;
66
60
  hsyncClient.emit = events.emit;
67
- hsyncClient.peers = peers;
61
+ // hsyncClient.peers = peers;
68
62
 
69
63
  let lastConnect;
70
64
  const connectURL = `${hsyncServer}${hsyncServer.endsWith('/') ? '' : '/'}${hsyncBase}`;
@@ -114,16 +108,21 @@ async function createHsync(config) {
114
108
  } catch (e) {
115
109
  debugError('error parsing json message');
116
110
  }
117
- } else if (action === 'ssrpc') {
118
- const peer = createServerReplyPeer({requestId: from, hsyncClient, methods: serverReplyMethods});
111
+ } else if (action === 'rpc') {
112
+ const peer = getRPCPeer({hostName: from, temporary: true, hsyncClient});
113
+ // const peer = getPeer({hostName: from, temporary: true});
119
114
  peer.transport.receiveData(message.toString());
120
115
  }
121
- else if (action === 'rpc') {
122
- const peer = getPeer({hostName: from, temporary: true});
123
- peer.transport.receiveData(message.toString());
116
+ else if (!action && (segment3 === 'srpc')) {
117
+ hsyncClient.serverPeer.transport.receiveData(message.toString());
124
118
  }
125
119
  else if (action === 'socketData') {
126
- events.emit('socketData', from, segment5, message);
120
+ // events.emit('socketData', from, segment5, message);
121
+ receiveSocketData(segment5, message);
122
+ }
123
+ else if (action === 'relayData') {
124
+ // events.emit('socketData', from, segment5, message);
125
+ receiveRelayData(segment5, message);
127
126
  }
128
127
  else if (action === 'socketClose') {
129
128
  events.emit('socketClose', from, segment5);
@@ -132,17 +131,17 @@ async function createHsync(config) {
132
131
 
133
132
  });
134
133
 
135
- function getPeer({hostName, temporary, timeout = 10000}) {
136
- let peer = peers[host];
137
- if (!peer) {
138
- peer = createRPCPeer({hostName, hsyncClient, timeout, methods: peerMethods});
139
- if (temporary) {
140
- peer.rpcTemporary = true;
141
- }
142
- peers[host] = peer;
143
- }
144
- return peer;
145
- }
134
+ // function getPeer({hostName, temporary, timeout = 10000}) {
135
+ // let peer = peers[hostName];
136
+ // if (!peer) {
137
+ // peer = createRPCPeer({hostName, hsyncClient, timeout, methods: peerMethods});
138
+ // if (temporary) {
139
+ // peer.rpcTemporary = true;
140
+ // }
141
+ // peers[host] = peer;
142
+ // }
143
+ // return peer;
144
+ // }
146
145
 
147
146
  function sendJson(host, json) {
148
147
  if (!host || !json) {
@@ -192,6 +191,12 @@ async function createHsync(config) {
192
191
  });
193
192
  }
194
193
 
194
+ function getSocketRelays () {
195
+ return Object.keys(socketRelays).map((id) => {
196
+ return { info: socketRelays[id].info, id };
197
+ });
198
+ }
199
+
195
200
  function addSocketListener (port, hostName, targetPort, targetHost = 'localhost') {
196
201
  const handler = createSocketListenHandler({port, hostName, targetPort, targetHost, hsyncClient});
197
202
  const id = b64id.generateId();
@@ -199,34 +204,77 @@ async function createHsync(config) {
199
204
  return getSocketListeners();
200
205
  }
201
206
 
207
+ function addSocketRelay(port, hostName, targetPort, targetHost = 'localhost') {
208
+ const handler = createSocketRelayHandler({port, hostName, targetPort, targetHost, hsyncClient});
209
+ const id = b64id.generateId();
210
+ socketRelays[id] = {handler, info: {port, hostName, targetPort, targetHost}, id};
211
+ debug('relay added', port);
212
+ return getSocketRelays();
213
+ }
214
+
202
215
  const serverReplyMethods = {
203
216
  ping: (greeting) => {
204
217
  return `${greeting} back atcha from client. ${Date.now()}`;
205
218
  },
206
219
  addSocketListener,
207
220
  getSocketListeners,
221
+ getSocketRelays,
222
+ addSocketRelay,
223
+ peerRpc: async (requestInfo) => {
224
+ requestInfo.hsyncClient = hsyncClient;
225
+ const { msg } = requestInfo;
226
+ debug('peerRpc handler', requestInfo.fromHost, msg);
227
+ const reply = {id: msg.id};
228
+ try {
229
+ if (!peerMethods[msg.method]) {
230
+ const notFoundError = new Error('method not found');
231
+ notFoundError.code = -32601;
232
+ throw notFoundError;
233
+ }
234
+ const result = await peerMethods[msg.method](requestInfo, ...msg.params);
235
+ reply.result = result;
236
+ return result;
237
+ } catch (e) {
238
+ debug('peer rpc error', e, msg);
239
+ msg.error = {
240
+ code: e.code || 500,
241
+ message: e.toString(),
242
+ };
243
+ return msg;
244
+ }
245
+ }
208
246
  };
209
247
 
210
248
  const peerMethods = {
211
249
  ping: (host, greeting) => {
250
+ debug('ping called', host, greeting);
212
251
  return `${greeting} back atcha, ${host}.`;
213
252
  },
253
+ connectSocket,
254
+ receiveListenerData,
255
+ receiveRelayData,
214
256
  };
215
257
 
258
+ hsyncClient.serverPeer = createServerPeer(hsyncClient, serverReplyMethods);
259
+
260
+ hsyncClient.hsyncBase = hsyncBase;
216
261
  hsyncClient.sendJson = sendJson;
217
262
  hsyncClient.endClient = endClient;
218
263
  hsyncClient.serverReplyMethods = serverReplyMethods;
219
- hsyncClient.getPeer = getPeer;
264
+ hsyncClient.getRPCPeer = getRPCPeer;
220
265
  hsyncClient.peerMethods = peerMethods;
221
266
  hsyncClient.hsyncSecret = hsyncSecret;
222
267
  hsyncClient.hsyncServer = hsyncServer;
223
268
  hsyncClient.dynamicTimeout = dynamicTimeout;
224
- if (hsyncServer.toLowerCase().startsWith('wss://')) {
225
- hsyncClient.webUrl = `https://${myHostName}`;
269
+ const { host, protocol } = new URL(hsyncServer);
270
+ debug('url', host, protocol);
271
+ if (protocol === 'wss:') {
272
+ hsyncClient.webUrl = `https://${host}`;
226
273
  } else {
227
- hsyncClient.webUrl = `https://${myHostName}`;
274
+ hsyncClient.webUrl = `http://${host}`;
228
275
  }
229
276
  hsyncClient.webAdmin = `${hsyncClient.webUrl}/${hsyncBase}/admin`;
277
+ hsyncClient.webBase = `${hsyncClient.webUrl}/${hsyncBase}`;
230
278
  hsyncClient.port = port;
231
279
 
232
280
  return hsyncClient;
package/dist/hsync.js CHANGED
@@ -25,7 +25,7 @@ eval("let process = __webpack_require__.g.process || {env: {}};\n\nconst baseCon
25
25
  \***********************/
26
26
  /***/ ((module, __unused_webpack_exports, __webpack_require__) => {
27
27
 
28
- eval("const fetch = __webpack_require__(/*! isomorphic-fetch */ \"./node_modules/isomorphic-fetch/fetch-npm-browserify.js\");\nconst EventEmitter = (__webpack_require__(/*! events */ \"./node_modules/events/events.js\").EventEmitter);\nconst b64id = __webpack_require__(/*! b64id */ \"./node_modules/b64id/index.js\");\nconst debug = __webpack_require__(/*! debug */ \"./node_modules/debug/src/browser.js\")('hsync:info');\nconst debugVerbose = __webpack_require__(/*! debug */ \"./node_modules/debug/src/browser.js\")('hsync:verbose');\nconst debugError = __webpack_require__(/*! debug */ \"./node_modules/debug/src/browser.js\")('hsync:error');\nconst { createRPCPeer, createServerReplyPeer } = __webpack_require__(/*! ./lib/rpc */ \"./lib/rpc.js\");\nconst { createWebHandler, setNet: webSetNet } = __webpack_require__(/*! ./lib/web-handler */ \"./lib/web-handler.js\");\nconst { createSocketListenHandler, setNet: listenSetNet } = __webpack_require__(/*! ./lib/socket-listen-handler */ \"./lib/socket-listen-handler.js\");\n\ndebug.color = 3;\ndebugVerbose.color = 2;\ndebugError.color = 1;\n\nlet mqtt;\n\nfunction setNet(netImpl) {\n webSetNet(netImpl);\n listenSetNet(netImpl);\n}\n\nfunction setMqtt(mqttImpl) {\n mqtt = mqttImpl;\n}\n\nasync function createHsync(config) {\n let {\n hsyncServer,\n hsyncSecret,\n localHost,\n port,\n hsyncBase,\n keepalive,\n dynamicHost,\n } = config;\n\n let dynamicTimeout;\n\n if (dynamicHost) {\n const options = {\n headers: {\n 'Content-Type': 'application/json',\n },\n method: 'POST',\n body: '{}',\n };\n const resp = await fetch(`${dynamicHost}/${hsyncBase}/dyn`, options);\n const result = await resp.json();\n // console.log('resutl', result);\n if (dynamicHost.toLowerCase().startsWith('https')) {\n hsyncServer = `wss://${result.url}`;\n } else {\n hsyncServer = `ws://${result.url}`;\n }\n hsyncSecret = result.secret;\n dynamicTimeout = result.timeout;\n }\n\n const hsyncClient = {};\n hsyncClient.config = config;\n const peers = {};\n const socketListeners = {};\n const events = new EventEmitter();\n \n hsyncClient.on = events.on;\n hsyncClient.emit = events.emit;\n hsyncClient.peers = peers;\n \n let lastConnect;\n const connectURL = `${hsyncServer}${hsyncServer.endsWith('/') ? '' : '/'}${hsyncBase}`;\n const myHostName = (new URL(connectURL)).hostname;\n hsyncClient.myHostName = myHostName;\n \n debug('connecting to', connectURL, '…' );\n const mqConn = mqtt.connect(connectURL, { password: hsyncSecret, username: myHostName, keepalive });\n mqConn.myHostName = myHostName;\n hsyncClient.mqConn = mqConn;\n\n const webHandler = config.webHandler || createWebHandler({myHostName, localHost, port, mqConn});\n hsyncClient.webHandler = webHandler;\n\n mqConn.on('connect', () => {\n const now = Date.now();\n debug('connected to', myHostName, lastConnect ? (now - lastConnect) : '', lastConnect ? 'since last connect' : '');\n lastConnect = now;\n hsyncClient.emit('connected', config);\n });\n\n mqConn.on('error', (error) => {\n debugError('error on mqConn', myHostName, error.code, error);\n if ((error.code === 4) || (error.code === 5)) {\n debug('ending');\n mqConn.end();\n }\n });\n\n mqConn.on('message', (topic, message) => {\n if (!topic) {\n return;\n }\n // message is Buffer\n const [name, hostName, segment3, action, segment5] = topic.split('/');\n debugVerbose('\\n↓ MQTT' , topic);\n if (name === 'web') {\n webHandler.handleWebRequest(hostName, segment3, action, message);\n return;\n } else if (name === 'msg') {\n const from = segment3;\n if (action === 'json') {\n try {\n const msg = JSON.parse(message.toString());\n msg.from = from;\n hsyncClient.emit('json', msg);\n } catch (e) {\n debugError('error parsing json message');\n }\n } else if (action === 'ssrpc') {\n const peer = createServerReplyPeer({requestId: from, hsyncClient, methods: serverReplyMethods});\n peer.transport.receiveData(message.toString());\n }\n else if (action === 'rpc') {\n const peer = getPeer({hostName: from, temporary: true});\n peer.transport.receiveData(message.toString());\n }\n else if (action === 'socketData') {\n events.emit('socketData', from, segment5, message);\n }\n else if (action === 'socketClose') {\n events.emit('socketClose', from, segment5);\n }\n }\n\n });\n\n function getPeer({hostName, temporary, timeout = 10000}) {\n let peer = peers[host];\n if (!peer) {\n peer = createRPCPeer({hostName, hsyncClient, timeout, methods: peerMethods});\n if (temporary) {\n peer.rpcTemporary = true;\n }\n peers[host] = peer;\n }\n return peer;\n }\n\n function sendJson(host, json) {\n if (!host || !json) {\n return;\n }\n\n if (host === myHostName) {\n debugError('cannot send message to self', host);\n }\n\n if (typeof json === 'object') {\n json = JSON.stringify(json);\n } else if (typeof json === 'string') {\n try {\n json = JSON.stringify(JSON.parse(json));\n } catch(e) {\n debugError('not well formed json or object', e);\n return;\n }\n } else {\n return;\n }\n mqConn.publish(`msg/${host}/${myHostName}/json`, json);\n }\n\n function endClient(force, callback) {\n if (force) {\n mqConn.end(force);\n if (webHandler.end) {\n webHandler.end();\n }\n return;\n }\n mqConn.end(force, (a, b) => {\n if (webHandler.end) {\n webHandler.end();\n }\n if (callback) {\n callback(a, b);\n }\n })\n }\n\n function getSocketListeners () {\n return Object.keys(socketListeners).map((id) => {\n return { info: socketListeners[id].info, id };\n });\n }\n\n function addSocketListener (port, hostName, targetPort, targetHost = 'localhost') {\n const handler = createSocketListenHandler({port, hostName, targetPort, targetHost, hsyncClient});\n const id = b64id.generateId();\n socketListeners[id] = {handler, info: {port, hostName, targetPort, targetHost}, id};\n return getSocketListeners();\n }\n\n const serverReplyMethods = {\n ping: (greeting) => {\n return `${greeting} back atcha from client. ${Date.now()}`;\n },\n addSocketListener,\n getSocketListeners,\n };\n\n const peerMethods = {\n ping: (host, greeting) => {\n return `${greeting} back atcha, ${host}.`;\n },\n };\n\n hsyncClient.sendJson = sendJson;\n hsyncClient.endClient = endClient;\n hsyncClient.serverReplyMethods = serverReplyMethods;\n hsyncClient.getPeer = getPeer;\n hsyncClient.peerMethods = peerMethods;\n hsyncClient.hsyncSecret = hsyncSecret;\n hsyncClient.hsyncServer = hsyncServer;\n hsyncClient.dynamicTimeout = dynamicTimeout;\n if (hsyncServer.toLowerCase().startsWith('wss://')) {\n hsyncClient.webUrl = `https://${myHostName}`;\n } else {\n hsyncClient.webUrl = `https://${myHostName}`;\n }\n hsyncClient.webAdmin = `${hsyncClient.webUrl}/${hsyncBase}/admin`;\n hsyncClient.port = port;\n\n return hsyncClient;\n}\n\nmodule.exports = {\n createHsync,\n setNet,\n setMqtt,\n};\n\n\n//# sourceURL=webpack://hsync/./connection.js?");
28
+ eval("const EventEmitter = (__webpack_require__(/*! events */ \"./node_modules/events/events.js\").EventEmitter);\nconst b64id = __webpack_require__(/*! b64id */ \"./node_modules/b64id/index.js\");\nconst debug = __webpack_require__(/*! debug */ \"./node_modules/debug/src/browser.js\")('hsync:info');\nconst debugVerbose = __webpack_require__(/*! debug */ \"./node_modules/debug/src/browser.js\")('hsync:verbose');\nconst debugError = __webpack_require__(/*! debug */ \"./node_modules/debug/src/browser.js\")('hsync:error');\nconst { getRPCPeer, createServerPeer } = __webpack_require__(/*! ./lib/rpc */ \"./lib/rpc.js\");\nconst { createWebHandler, setNet: webSetNet } = __webpack_require__(/*! ./lib/web-handler */ \"./lib/web-handler.js\");\nconst { createSocketListenHandler, setNet: listenSetNet, receiveRelayData } = __webpack_require__(/*! ./lib/socket-listen-handler */ \"./lib/socket-listen-handler.js\");\nconst { createSocketRelayHandler, setNet: relaySetNet, receiveListenerData, connectSocket } = __webpack_require__(/*! ./lib/socket-relay-handler */ \"./lib/socket-relay-handler.js\");\nconst fetch = __webpack_require__(/*! ./lib/fetch */ \"./lib/fetch.js\");\n\ndebug.color = 3;\ndebugVerbose.color = 2;\ndebugError.color = 1;\n\nlet mqtt;\n\nfunction setNet(netImpl) {\n webSetNet(netImpl);\n listenSetNet(netImpl);\n relaySetNet(netImpl);\n}\n\nfunction setMqtt(mqttImpl) {\n mqtt = mqttImpl;\n}\n\nasync function createHsync(config) {\n let {\n hsyncServer,\n hsyncSecret,\n localHost,\n port,\n hsyncBase,\n keepalive,\n dynamicHost,\n } = config;\n\n let dynamicTimeout;\n\n if (dynamicHost) {\n const result = await fetch.post(`${dynamicHost}/${hsyncBase}/dyn`, {});\n if (dynamicHost.toLowerCase().startsWith('https')) {\n hsyncServer = `wss://${result.url}`;\n } else {\n hsyncServer = `ws://${result.url}`;\n }\n hsyncSecret = result.secret;\n dynamicTimeout = result.timeout;\n }\n\n const hsyncClient = {};\n hsyncClient.config = config;\n // const peers = {};\n const socketListeners = {};\n const socketRelays= {};\n const events = new EventEmitter();\n \n hsyncClient.on = events.on;\n hsyncClient.emit = events.emit;\n // hsyncClient.peers = peers;\n \n let lastConnect;\n const connectURL = `${hsyncServer}${hsyncServer.endsWith('/') ? '' : '/'}${hsyncBase}`;\n const myHostName = (new URL(connectURL)).hostname;\n hsyncClient.myHostName = myHostName;\n \n debug('connecting to', connectURL, '…' );\n const mqConn = mqtt.connect(connectURL, { password: hsyncSecret, username: myHostName, keepalive });\n mqConn.myHostName = myHostName;\n hsyncClient.mqConn = mqConn;\n\n const webHandler = config.webHandler || createWebHandler({myHostName, localHost, port, mqConn});\n hsyncClient.webHandler = webHandler;\n\n mqConn.on('connect', () => {\n const now = Date.now();\n debug('connected to', myHostName, lastConnect ? (now - lastConnect) : '', lastConnect ? 'since last connect' : '');\n lastConnect = now;\n hsyncClient.emit('connected', config);\n });\n\n mqConn.on('error', (error) => {\n debugError('error on mqConn', myHostName, error.code, error);\n if ((error.code === 4) || (error.code === 5)) {\n debug('ending');\n mqConn.end();\n }\n });\n\n mqConn.on('message', (topic, message) => {\n if (!topic) {\n return;\n }\n // message is Buffer\n const [name, hostName, segment3, action, segment5] = topic.split('/');\n debugVerbose('\\n↓ MQTT' , topic);\n if (name === 'web') {\n webHandler.handleWebRequest(hostName, segment3, action, message);\n return;\n } else if (name === 'msg') {\n const from = segment3;\n if (action === 'json') {\n try {\n const msg = JSON.parse(message.toString());\n msg.from = from;\n hsyncClient.emit('json', msg);\n } catch (e) {\n debugError('error parsing json message');\n }\n } else if (action === 'rpc') {\n const peer = getRPCPeer({hostName: from, temporary: true, hsyncClient});\n // const peer = getPeer({hostName: from, temporary: true});\n peer.transport.receiveData(message.toString());\n }\n else if (!action && (segment3 === 'srpc')) {\n hsyncClient.serverPeer.transport.receiveData(message.toString());\n }\n else if (action === 'socketData') {\n // events.emit('socketData', from, segment5, message);\n receiveSocketData(segment5, message);\n }\n else if (action === 'relayData') {\n // events.emit('socketData', from, segment5, message);\n receiveRelayData(segment5, message);\n }\n else if (action === 'socketClose') {\n events.emit('socketClose', from, segment5);\n }\n }\n\n });\n\n // function getPeer({hostName, temporary, timeout = 10000}) {\n // let peer = peers[hostName];\n // if (!peer) {\n // peer = createRPCPeer({hostName, hsyncClient, timeout, methods: peerMethods});\n // if (temporary) {\n // peer.rpcTemporary = true;\n // }\n // peers[host] = peer;\n // }\n // return peer;\n // }\n\n function sendJson(host, json) {\n if (!host || !json) {\n return;\n }\n\n if (host === myHostName) {\n debugError('cannot send message to self', host);\n }\n\n if (typeof json === 'object') {\n json = JSON.stringify(json);\n } else if (typeof json === 'string') {\n try {\n json = JSON.stringify(JSON.parse(json));\n } catch(e) {\n debugError('not well formed json or object', e);\n return;\n }\n } else {\n return;\n }\n mqConn.publish(`msg/${host}/${myHostName}/json`, json);\n }\n\n function endClient(force, callback) {\n if (force) {\n mqConn.end(force);\n if (webHandler.end) {\n webHandler.end();\n }\n return;\n }\n mqConn.end(force, (a, b) => {\n if (webHandler.end) {\n webHandler.end();\n }\n if (callback) {\n callback(a, b);\n }\n })\n }\n\n function getSocketListeners () {\n return Object.keys(socketListeners).map((id) => {\n return { info: socketListeners[id].info, id };\n });\n }\n\n function getSocketRelays () {\n return Object.keys(socketRelays).map((id) => {\n return { info: socketRelays[id].info, id };\n });\n }\n\n function addSocketListener (port, hostName, targetPort, targetHost = 'localhost') {\n const handler = createSocketListenHandler({port, hostName, targetPort, targetHost, hsyncClient});\n const id = b64id.generateId();\n socketListeners[id] = {handler, info: {port, hostName, targetPort, targetHost}, id};\n return getSocketListeners();\n }\n\n function addSocketRelay(port, hostName, targetPort, targetHost = 'localhost') {\n const handler = createSocketRelayHandler({port, hostName, targetPort, targetHost, hsyncClient});\n const id = b64id.generateId();\n socketRelays[id] = {handler, info: {port, hostName, targetPort, targetHost}, id};\n debug('relay added', port);\n return getSocketRelays();\n }\n\n const serverReplyMethods = {\n ping: (greeting) => {\n return `${greeting} back atcha from client. ${Date.now()}`;\n },\n addSocketListener,\n getSocketListeners,\n getSocketRelays,\n addSocketRelay,\n peerRpc: async (requestInfo) => {\n requestInfo.hsyncClient = hsyncClient;\n const { msg } = requestInfo;\n debug('peerRpc handler', requestInfo.fromHost, msg);\n const reply = {id: msg.id};\n try {\n if (!peerMethods[msg.method]) {\n const notFoundError = new Error('method not found');\n notFoundError.code = -32601;\n throw notFoundError;\n }\n const result = await peerMethods[msg.method](requestInfo, ...msg.params);\n reply.result = result;\n return result;\n } catch (e) {\n debug('peer rpc error', e, msg);\n msg.error = {\n code: e.code || 500,\n message: e.toString(),\n };\n return msg;\n }\n }\n };\n\n const peerMethods = {\n ping: (host, greeting) => {\n debug('ping called', host, greeting);\n return `${greeting} back atcha, ${host}.`;\n },\n connectSocket,\n receiveListenerData,\n receiveRelayData,\n };\n\n hsyncClient.serverPeer = createServerPeer(hsyncClient, serverReplyMethods);\n\n hsyncClient.hsyncBase = hsyncBase;\n hsyncClient.sendJson = sendJson;\n hsyncClient.endClient = endClient;\n hsyncClient.serverReplyMethods = serverReplyMethods;\n hsyncClient.getRPCPeer = getRPCPeer;\n hsyncClient.peerMethods = peerMethods;\n hsyncClient.hsyncSecret = hsyncSecret;\n hsyncClient.hsyncServer = hsyncServer;\n hsyncClient.dynamicTimeout = dynamicTimeout;\n const { host, protocol } = new URL(hsyncServer);\n debug('url', host, protocol);\n if (protocol === 'wss:') {\n hsyncClient.webUrl = `https://${host}`;\n } else {\n hsyncClient.webUrl = `http://${host}`;\n }\n hsyncClient.webAdmin = `${hsyncClient.webUrl}/${hsyncBase}/admin`;\n hsyncClient.webBase = `${hsyncClient.webUrl}/${hsyncBase}`;\n hsyncClient.port = port;\n\n return hsyncClient;\n}\n\nmodule.exports = {\n createHsync,\n setNet,\n setMqtt,\n};\n\n\n//# sourceURL=webpack://hsync/./connection.js?");
29
29
 
30
30
  /***/ }),
31
31
 
@@ -35,7 +35,17 @@ eval("const fetch = __webpack_require__(/*! isomorphic-fetch */ \"./node_modules
35
35
  \**********************/
36
36
  /***/ ((module, __unused_webpack_exports, __webpack_require__) => {
37
37
 
38
- eval("const mqtt = __webpack_require__(/*! precompiled-mqtt */ \"./node_modules/precompiled-mqtt/dist/mqtt.browser.js\");\nconst buffer = __webpack_require__(/*! buffer */ \"./node_modules/buffer/index.js\");\nconst net = __webpack_require__(/*! net-web */ \"./node_modules/net-web/net-web.js\");\nconst { createHsync, setNet, setMqtt } = __webpack_require__(/*! ./connection */ \"./connection.js\");\nconst config = __webpack_require__(/*! ./config */ \"./config.js\");\n\n// TODO need to make this work with web/service workers\nwindow.Buffer = buffer.Buffer;\n\nsetNet(net);\nsetMqtt(mqtt);\n\nasync function dynamicConnect(dynamicHost, useLocalStorage) {\n let con;\n if (useLocalStorage) {\n const localConfigStr = localStorage.getItem('hsyncConfig');\n if (localConfigStr) {\n const localConfig = JSON.parse(localConfigStr);\n if ((Date.now() - localConfig.created) < (localConfig.timeout * 0.66)) {\n config.hsyncSecret = localConfig.hsyncSecret;\n config.hsyncServer = localConfig.hsyncServer;\n }\n }\n \n if (!config.hsyncSecret) {\n config.dynamicHost = dynamicHost || config.defaultDynamicHost;\n }\n \n con = await createHsync(config);\n \n if (config.dynamicHost) {\n const storeConfig = {\n hsyncSecret: con.hsyncSecret,\n hsyncServer: con.hsyncServer,\n timeout: con.dynamicTimeout,\n created: Date.now(),\n };\n localStorage.setItem('hsyncConfig', JSON.stringify(storeConfig));\n }\n\n return con;\n }\n\n config.dynamicHost = dynamicHost || config.defaultDynamicHost;\n con = await createHsync(config);\n\n return con;\n \n}\n\n\nconst hsync = globalThis.hsync || {\n createConnection: createHsync,\n dynamicConnect,\n net,\n config,\n};\nglobalThis.hsync = hsync;\n\nmodule.exports = hsync;\n\n\n//# sourceURL=webpack://hsync/./hsync-web.js?");
38
+ eval("const mqtt = __webpack_require__(/*! precompiled-mqtt */ \"./node_modules/precompiled-mqtt/dist/mqtt.browser.js\");\nconst buffer = __webpack_require__(/*! buffer */ \"./node_modules/buffer/index.js\");\nconst net = __webpack_require__(/*! net-web */ \"./node_modules/net-web/net-web.js\");\nconst { createHsync, setNet, setMqtt } = __webpack_require__(/*! ./connection */ \"./connection.js\");\nconst config = __webpack_require__(/*! ./config */ \"./config.js\");\n\n// TODO need to make this work with web/service workers\nwindow.Buffer = buffer.Buffer;\n\nsetNet(net);\nsetMqtt(mqtt);\n\nasync function dynamicConnect(dynamicHost, useLocalStorage) {\n let con;\n if (useLocalStorage) {\n const localConfigStr = localStorage.getItem('hsyncConfig');\n if (localConfigStr) {\n const localConfig = JSON.parse(localConfigStr);\n if ((Date.now() - localConfig.created) < (localConfig.timeout * 0.66)) {\n config.hsyncSecret = localConfig.hsyncSecret;\n config.hsyncServer = localConfig.hsyncServer;\n } else {\n localStorage.removeItem('hsyncConfig');\n }\n }\n \n if (!config.hsyncSecret) {\n config.dynamicHost = dynamicHost || config.defaultDynamicHost;\n }\n \n con = await createHsync(config);\n \n if (config.dynamicHost) {\n const storeConfig = {\n hsyncSecret: con.hsyncSecret,\n hsyncServer: con.hsyncServer,\n timeout: con.dynamicTimeout,\n created: Date.now(),\n };\n localStorage.setItem('hsyncConfig', JSON.stringify(storeConfig));\n }\n\n return con;\n }\n\n config.dynamicHost = dynamicHost || config.defaultDynamicHost;\n con = await createHsync(config);\n\n return con;\n \n}\n\nfunction createConnection(configObj = {}) {\n const fullConfig = {...config, ...configObj};\n return createHsync(fullConfig);\n}\n\n\nconst hsync = globalThis.hsync || {\n createConnection,\n dynamicConnect,\n net,\n config,\n};\nglobalThis.hsync = hsync;\n\nmodule.exports = hsync;\n\n\n//# sourceURL=webpack://hsync/./hsync-web.js?");
39
+
40
+ /***/ }),
41
+
42
+ /***/ "./lib/fetch.js":
43
+ /*!**********************!*\
44
+ !*** ./lib/fetch.js ***!
45
+ \**********************/
46
+ /***/ ((module, __unused_webpack_exports, __webpack_require__) => {
47
+
48
+ eval("const fetch = __webpack_require__(/*! isomorphic-fetch */ \"./node_modules/isomorphic-fetch/fetch-npm-browserify.js\");\n\nfunction getContent(res) {\n const contentType = res.headers.get('content-type');\n if (contentType.startsWith('application/json')) {\n return res.json();\n }\n if (contentType.startsWith('text')) {\n return res.text();\n }\n return res.blob();\n}\n\nfunction handledFetch(path, options) {\n return fetch(path, options)\n .then((res) => {\n if (res.status >= 400) {\n const err = new Error('Bad response from server');\n err.status = res.status;\n return getContent(res)\n .then((content) => {\n err.content = content;\n throw err;\n });\n }\n return res;\n });\n}\n\nfunction apiFetch(path, options = {}) {\n let qs = '';\n if (typeof options.body === 'object') {\n options.body = JSON.stringify(options.body);\n }\n if (options.query) {\n if (Object.keys(options.query).length) {\n qs = `?${(new URLSearchParams(options.query)).toString()}`;\n }\n }\n Object.assign(options, { credentials: 'include' });\n options.headers = {\n 'Content-Type': 'application/json',\n ...options.headers,\n };\n return handledFetch(`${path}${qs}`, options)\n .then(getContent);\n}\n\napiFetch.post = (path, body) => {\n return apiFetch(path, { method: 'POST', body });\n};\n\napiFetch.put = (path, body) => {\n return apiFetch(path, { method: 'PUT', body });\n};\n\napiFetch.del = (path, body = {}) => {\n return apiFetch(path, { method: 'DELETE', body });\n};\n\nmodule.exports = apiFetch;\n\n\n//# sourceURL=webpack://hsync/./lib/fetch.js?");
39
49
 
40
50
  /***/ }),
41
51
 
@@ -45,7 +55,7 @@ eval("const mqtt = __webpack_require__(/*! precompiled-mqtt */ \"./node_modules/
45
55
  \********************/
46
56
  /***/ ((module, __unused_webpack_exports, __webpack_require__) => {
47
57
 
48
- eval("const rawr = __webpack_require__(/*! rawr */ \"./node_modules/rawr/index.js\");\nconst b64id = __webpack_require__(/*! b64id */ \"./node_modules/b64id/index.js\");\nconst debug = __webpack_require__(/*! debug */ \"./node_modules/debug/src/browser.js\")('hsync:rpc');\nconst EventEmitter = (__webpack_require__(/*! events */ \"./node_modules/events/events.js\").EventEmitter);\n\nfunction createRPCPeer({ hostName, hsyncClient, timeout = 10000, methods = {} }) {\n if (!hostName) {\n throw new Error('No hostname specified');\n }\n if (hostName === hsyncClient.username) {\n throw new Error('Peer must be a different host');\n }\n const transport = new EventEmitter();\n transport.send = (msg) => {\n if(typeof msg === 'object') {\n msg = JSON.stringify(msg);\n }\n const topic = `msg/${hostName}/${hsyncClient.username}/rpc`;\n debug('↑ peer rpc reply', msg);\n hsyncClient.mqConn.publish(topic, Buffer.from(msg));\n };\n transport.receiveData = (msg) => {\n debug('↓ peer rpc', msg);\n if(msg) {\n msg = JSON.parse(msg);\n }\n if (Array.isArray(msg.params)) {\n msg.params.unshift(hostName);\n }\n transport.emit('rpc', msg);\n };\n\n const peer = rawr({transport, methods: Object.assign({}, methods), timeout});\n return peer;\n \n}\n\nfunction createServerReplyPeer({ requestId, hsyncClient, methods = {}}) {\n\n const transport = new EventEmitter();\n transport.send = (msg) => {\n if(typeof msg === 'object') {\n msg = JSON.stringify(msg);\n }\n const topic = `ssrpc/${hsyncClient.myHostName}/${requestId}`;\n debug('↑ server rpc reply', msg);\n hsyncClient.mqConn.publish(topic, Buffer.from(msg));\n };\n transport.receiveData = (msg) => {\n debug('↓ server rpc', msg);\n if(msg) {\n msg = JSON.parse(msg);\n }\n transport.emit('rpc', msg);\n };\n\n const peer = rawr({transport, methods});\n return peer;\n}\n\nmodule.exports = {\n createRPCPeer,\n createServerReplyPeer,\n};\n\n//# sourceURL=webpack://hsync/./lib/rpc.js?");
58
+ eval("const rawr = __webpack_require__(/*! rawr */ \"./node_modules/rawr/index.js\");\nconst b64id = __webpack_require__(/*! b64id */ \"./node_modules/b64id/index.js\");\nconst debug = __webpack_require__(/*! debug */ \"./node_modules/debug/src/browser.js\")('hsync:rpc');\nconst EventEmitter = (__webpack_require__(/*! events */ \"./node_modules/events/events.js\").EventEmitter);\n// const { peerMethods } = require('./peer-methods');\nconst fetch = __webpack_require__(/*! ./fetch */ \"./lib/fetch.js\");\n\nconst peers = {};\n\nfunction getRPCPeer({hostName, temporary, timeout = 10000, hsyncClient}) {\n let peer = peers[hostName];\n if (!peer) {\n debug('creating peer', hostName);\n peer = createRPCPeer({hostName, hsyncClient, timeout, methods: hsyncClient.peerMethods});\n if (temporary) {\n peer.rpcTemporary = true;\n }\n peers[hostName] = peer;\n }\n return peer;\n}\n\n\nfunction createRPCPeer({ hostName, hsyncClient, timeout = 10000, methods = {} }) {\n if (!hostName) {\n throw new Error('No hostname specified');\n }\n if (hostName === hsyncClient.myHostName) {\n throw new Error('Peer must be a different host');\n }\n const myAuth = b64id.generateId();\n const transport = new EventEmitter();\n transport.send = async (msg) => {\n const fullMsg = {\n msg,\n myAuth,\n toHost: hostName,\n fromHost: hsyncClient.webUrl,\n };\n // const toSend = JSON.stringify(fullMsg);\n const topic = `rpc/${hsyncClient.myHostName}`;\n debug('↑ peer rpc', `${hostName}/_hs/rpc`, msg);\n // hsyncClient.mqConn.publish(topic, Buffer.from(toSend));\n try {\n const result = await fetch.post(`${hostName}/_hs/rpc`, fullMsg);\n transport.receiveData({id: msg.id, result, jsonrpc: msg.jsonrpc});\n } catch(e) {\n debug(e);\n transport.receiveData({id: msg.id, error: e, method: msg.method, jsonrpc: msg.jsonrpc});\n }\n \n };\n transport.receiveData = (msg) => {\n debug('↓ peer rpc', msg);\n if(typeof msg === 'string') {\n msg = JSON.parse(msg);\n }\n if (Array.isArray(msg.params)) {\n msg.params.unshift(hostName);\n }\n transport.emit('rpc', msg);\n };\n\n const peer = rawr({transport, methods: Object.assign({}, methods), timeout, idGenerator: b64id.generateId});\n peer.myAuth = myAuth;\n return peer;\n \n}\n\nfunction createServerPeer(hsyncClient, methods) {\n const transport = new EventEmitter();\n transport.send = (msg) => {\n if(typeof msg === 'object') {\n msg = JSON.stringify(msg);\n }\n const topic = `srpc/${hsyncClient.myHostName}`;\n debug('↑ server rpc request', msg);\n hsyncClient.mqConn.publish(topic, Buffer.from(msg));\n };\n transport.receiveData = (msg) => {\n debug('↓ server rpc reply', msg);\n if(msg) {\n msg = JSON.parse(msg);\n }\n transport.emit('rpc', msg);\n };\n const peer = rawr({transport, methods, timeout: 5000});\n return peer;\n}\n\nmodule.exports = {\n createRPCPeer,\n createServerPeer,\n getRPCPeer,\n};\n\n//# sourceURL=webpack://hsync/./lib/rpc.js?");
49
59
 
50
60
  /***/ }),
51
61
 
@@ -55,7 +65,17 @@ eval("const rawr = __webpack_require__(/*! rawr */ \"./node_modules/rawr/index.j
55
65
  \**************************************/
56
66
  /***/ ((module, __unused_webpack_exports, __webpack_require__) => {
57
67
 
58
- eval("const debug = __webpack_require__(/*! debug */ \"./node_modules/debug/src/browser.js\")('hsync:listener');\nconst debugError = __webpack_require__(/*! debug */ \"./node_modules/debug/src/browser.js\")('hsync:error');\n\nconst { createRPCPeer } = __webpack_require__(/*! ./rpc */ \"./lib/rpc.js\");\n\ndebugError.color = 1;\nlet net;\n\nfunction setNet(netImpl) {\n net = netImpl;\n}\n\nfunction createSocketListenHandler({hostName, port, targetPort, targetHost, hsyncClient}) {\n debug('creating handler', hostName, port, targetPort, targetHost);\n\n const sockets = {};\n \n const peer = createRPCPeer({hostName, hsyncClient});\n\n debug('peer crated');\n \n const socketServer = net.createServer(async (socket) => {\n\n socket.socketId = b64id.generateId();\n sockets[socket.socketId] = socket;\n socket.peerConnected = false;\n const pubTopic = `msg/${hostName}/${hsyncClient.username}/socketData/${socket.socketId}`;\n const closeTopic = `msg/${hostName}/${hsyncClient.username}/socketClose/${socket.socketId}`;\n const dataQueue = [];\n\n function sendData(data) {\n hsyncClient.mqConn.publish(pubTopic, data);\n }\n\n socket.on('data', async (data) => {\n if (!socket.peerConnected) {\n dataQueue.push(data);\n return;\n }\n sendData(data);\n });\n \n socket.on('close', () => {\n\n if (sockets[socket.socketId]) {\n delete sockets[socket.socketId];\n }\n hsyncClient.mqConn.publish(closeTopic, '');\n });\n \n socket.on('error', (error) => {\n debug('socket error', hostName, socket.socketId, error);\n if (sockets[socket.socketId]) {\n delete sockets[socket.socketId];\n }\n hsyncClient.mqConn.publish(closeTopic, '');\n });\n \n try {\n await peer.methods.connectSocket(targetPort, targetHost);\n dataQueue.forEach(sendData);\n } catch (e) {\n debugError('cant connect remotely', hostName, targetPort, e);\n if (sockets[socket.socketId]) {\n delete sockets[socket.socketId];\n }\n socket.end();\n }\n \n });\n\n socketServer.listen(port);\n\n\n function end() {\n const sockKeys = Object.keys(sockets);\n sockKeys.forEach((sk) => {\n try {\n sockets[sk].end();\n delete sockets[sk];\n }\n catch(e) {\n debug('error closing socket', e);\n }\n });\n }\n\n return {\n socketServer,\n sockets,\n end,\n };\n}\n\nmodule.exports = {\n createSocketListenHandler,\n setNet,\n};\n\n//# sourceURL=webpack://hsync/./lib/socket-listen-handler.js?");
68
+ eval("const b64id = __webpack_require__(/*! b64id */ \"./node_modules/b64id/index.js\");\nconst debug = __webpack_require__(/*! debug */ \"./node_modules/debug/src/browser.js\")('hsync:listener');\nconst debugError = __webpack_require__(/*! debug */ \"./node_modules/debug/src/browser.js\")('hsync:error');\n// const { getRTCPeer } = require('./data-channel');\n\nconst { getRPCPeer } = __webpack_require__(/*! ./rpc */ \"./lib/rpc.js\");\n\nlet net;\n\nfunction setNet(netImpl) {\n net = netImpl;\n}\n\n\ndebugError.color = 1;\n\nconst sockets = {};\n\n// function receiveRelayData(socketId, data) {\n// if (sockets[socketId]) {\n// debug('receiveRelayData', socketId, data.length);\n// sockets[socketId].write(data);\n// }\n// }\n\nfunction receiveRelayData(requestInfo, { socketId, data }) {\n debug('receiveRelayData', socketId, data, 'sockets', Object.keys(sockets));\n if (!sockets[socketId]) {\n throw new Error('listener has no matching socket for relay: ' + socketId);\n }\n let dataBuffer = data;\n if (typeof dataBuffer === 'string') {\n dataBuffer = Buffer.from(dataBuffer, 'base64');\n }\n sockets[socketId].write(dataBuffer);\n return 'ok';\n}\n\nfunction createSocketListenHandler({hostName, port, targetPort, targetHost, hsyncClient}) {\n debug('creating handler', hostName, port, targetPort, targetHost);\n \n const rpcPeer = getRPCPeer({hostName, hsyncClient});\n\n debug('peer crated');\n\n const socketServer = net.createServer(async (socket) => {\n\n socket.socketId = b64id.generateId();\n sockets[socket.socketId] = socket;\n debug('connected to local listener', port, socket.socketId);\n socket.peerConnected = false;\n const pubTopic = `msg/${hostName}/${hsyncClient.myHostName}/socketData/${socket.socketId}`;\n const closeTopic = `msg/${hostName}/${hsyncClient.myHostName}/socketClose/${socket.socketId}`;\n const dataQueue = [];\n\n async function sendData(data) {\n debug('sending data', hostName, data.length);\n // const p = getRTCPeer(hostName, hsyncClient);\n // if (p.connected) {\n // p.send(`socketData/${socket.socketId}`, data);\n // return;\n // }\n // hsyncClient.mqConn.publish(pubTopic, data);\n const result = await rpcPeer.methods.receiveListenerData({\n socketId: socket.socketId,\n data: Buffer.from(data).toString('base64'),\n });\n debug('sendData from Listener', result);\n }\n\n socket.on('data', async (data) => {\n debug('socket data', data?.length);\n // if (!socket.peerConnected) {\n // dataQueue.push(data);\n // return;\n // }\n sendData(data);\n });\n \n socket.on('close', () => {\n debug('listener socket closed', port, socket.socketId);\n if (sockets[socket.socketId]) {\n delete sockets[socket.socketId];\n }\n // hsyncClient.mqConn.publish(closeTopic, '');\n });\n \n socket.on('error', (error) => {\n debug('socket error', hostName, socket.socketId, error);\n if (sockets[socket.socketId]) {\n delete sockets[socket.socketId];\n }\n // hsyncClient.mqConn.publish(closeTopic, '');\n });\n \n try {\n debug('connecting remotely', socket.socketId, targetPort);\n const result = await rpcPeer.methods.connectSocket({socketId: socket.socketId, port: targetPort});\n debug('connect result', result);\n socket.peerConnected = true;\n dataQueue.forEach(sendData);\n // const p = getRTCPeer(hostName, hsyncClient);\n // if (p.pc) {\n // p.createDC();\n // }\n \n } catch (e) {\n debugError('cant connect remotely', hostName, targetPort, e);\n if (sockets[socket.socketId]) {\n delete sockets[socket.socketId];\n }\n socket.end();\n }\n \n\n });\n\n socketServer.listen(port);\n\n\n function end() {\n const sockKeys = Object.keys(sockets);\n sockKeys.forEach((sk) => {\n try {\n sockets[sk].end();\n delete sockets[sk];\n }\n catch(e) {\n debug('error closing socket', e);\n }\n });\n }\n\n return {\n socketServer,\n sockets,\n end,\n };\n}\n\nmodule.exports = { \n createSocketListenHandler,\n receiveRelayData,\n setNet,\n};\n\n//# sourceURL=webpack://hsync/./lib/socket-listen-handler.js?");
69
+
70
+ /***/ }),
71
+
72
+ /***/ "./lib/socket-relay-handler.js":
73
+ /*!*************************************!*\
74
+ !*** ./lib/socket-relay-handler.js ***!
75
+ \*************************************/
76
+ /***/ ((module, __unused_webpack_exports, __webpack_require__) => {
77
+
78
+ eval("const b64id = __webpack_require__(/*! b64id */ \"./node_modules/b64id/index.js\");\nconst debug = __webpack_require__(/*! debug */ \"./node_modules/debug/src/browser.js\")('hsync:relay');\nconst debugError = __webpack_require__(/*! debug */ \"./node_modules/debug/src/browser.js\")('hsync:error');\n// const { getRTCPeer } = require('./data-channel');\nconst { getRPCPeer } = __webpack_require__(/*! ./rpc */ \"./lib/rpc.js\");\n\ndebugError.color = 1;\n\nlet net;\n\nfunction setNet(netImpl) {\n net = netImpl;\n}\n\n\nconst relays = {};\nconst sockets = {};\n\nfunction receiveListenerData(requestInfo, { socketId, data }) {\n debug('receiveListenerData', socketId, data, 'sockets', Object.keys(sockets));\n if (!sockets[socketId]) {\n throw new Error('relay has no matching socket for listener : ' + socketId);\n }\n let dataBuffer = data;\n if (typeof dataBuffer === 'string') {\n dataBuffer = Buffer.from(dataBuffer, 'base64');\n }\n sockets[socketId].write(dataBuffer);\n return 'ok';\n}\n\nfunction connectSocket({ hsyncClient, fromHost }, {port, socketId}) {\n const relay = relays['p' + port];\n debug('connect relay', port, socketId);\n if (!relay) {\n throw new Error('no relay found for port: ' + port);\n }\n const rpcPeer = getRPCPeer({hostName: fromHost, hsyncClient});\n // const relayDataTopic = `msg/${hostName}/${hsyncClient.myHostName}/relayData/${socketId}`;\n return new Promise((resolve, reject) => {\n const socket = new net.Socket();\n socket.socketId = socketId;\n sockets[socketId] = socket;\n socket.connect(relay.targetPort, relay.targetHost, () => {\n debug(`CONNECTED TO LOCAL SERVER`, socket.socketId, socket.hostName);\n resolve({socketId, targetHost: relay.targetHost, targetPort: relay.targetPort});\n });\n\n socket.on('data', async (data) => {\n debug(`data in ${socket.socketId}`, relay.targetPort, relay.targetHost, data.length);\n const result = await rpcPeer.methods.receiveRelayData({\n socketId,\n data: Buffer.from(data).toString('base64'),\n });\n // const p = getRTCPeer(hostName, hsyncClient);\n // if (p.connected) {\n // p.send(`relayData/${socketId}`, data);\n // return;\n // }\n // hsyncClient.mqConn.publish(relayDataTopic, data);\n });\n socket.on('close', () => {\n debug(`LOCAL CONNECTION CLOSED`, socket.socketId, targetHost, targetPort);\n delete sockets[socket.socketId];\n });\n\n socket.on('error', (e) => {\n debugError(`LOCAL CONNECTION ERROR`, socket.socketId, targetHost, targetPort, e);\n delete sockets[socket.socketId];\n reject(e);\n });\n \n });\n\n}\n\n// function receiveSocketData(socketId, data) {\n// if (sockets[socketId]) {\n// debug('receiveSocketData', socketId, data.length);\n// sockets[socketId].write(data);\n// return 'ok';\n// }\n\n// throw new Error('socket not found: ' + socketId);\n// }\n\nfunction createSocketRelayHandler({hostName, port, targetPort, targetHost, hsyncClient}) {\n debug('creating relay', hostName, port, targetPort, targetHost);\n relays['p' + port] = {\n hostName,\n port,\n targetPort,\n targetHost,\n };\n}\n\nmodule.exports = {\n createSocketRelayHandler,\n connectSocket,\n // receiveSocketData,\n setNet,\n receiveListenerData,\n};\n\n//# sourceURL=webpack://hsync/./lib/socket-relay-handler.js?");
59
79
 
60
80
  /***/ }),
61
81