socket-function 0.21.0 → 0.23.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/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "socket-function",
3
- "version": "0.21.0",
3
+ "version": "0.23.0",
4
4
  "main": "index.js",
5
5
  "license": "MIT",
6
6
  "note1": "note on node-forge fork, see https://github.com/digitalbazaar/forge/issues/744 for details",
@@ -1,3 +1,4 @@
1
+ import debugbreak from "debugbreak";
1
2
  import * as dgram from "dgram";
2
3
  import os from "os";
3
4
 
@@ -14,6 +15,7 @@ export async function forwardPort(config: {
14
15
  if (!localObj) throw new Error("Could not find the local address / gateway");
15
16
 
16
17
  const { internalIP, gatewayIP } = localObj;
18
+ console.log(`Local IP: ${internalIP}, Gateway IP: ${gatewayIP}`);
17
19
  let gateway = await discoverGateway(internalIP);
18
20
  let controlURLs = await getControlPaths(gateway);
19
21
  let controlPort = Number(new URL(gateway).port);
@@ -27,29 +29,70 @@ export async function forwardPort(config: {
27
29
  controlPath: controlURL,
28
30
  internalIP,
29
31
  });
32
+ console.log(`Port mapping created on ${gatewayIP}:${externalPort} -> ${internalIP}:${internalPort}`);
30
33
  return;
31
34
  } catch (e) {
32
- console.error(e);
35
+ console.error(`Failed to create port mapping using controlURL ${controlURL}`, e);
33
36
  }
34
37
  }
35
38
  console.error("Failed to create port mapping, could not find controlURL");
36
39
  }
37
40
 
38
41
  function getLocalInterfaceAddress(): { internalIP: string; gatewayIP: string; } | undefined {
39
- const interfaces = os.networkInterfaces() as any;
40
- for (const name of Object.keys(interfaces)) {
41
- for (const iface of interfaces[name]) {
42
- if (iface.family === "IPv4" && !iface.internal) {
43
- // TOOD: Correctly resolve the cidr?
44
- let gatewayIP = iface.cidr.split(".").slice(0, 3).join(".") + ".1";
45
- // TOOD: We try discovery on all gateways, so we can know for sure which one it is
46
- // (and maybe even port forward all gateway, if multiple respond?)
47
- if (gatewayIP.startsWith("10.0.0") || gatewayIP.startsWith("10.0.1") || gatewayIP.startsWith("192.168.0")) {
48
- return { internalIP: iface.address, gatewayIP };
42
+ let looksLikeRouter = (ip: string) => ip.startsWith("10.0.0") || ip.startsWith("10.0.1") || ip.startsWith("192.168.0");
43
+
44
+ // On windows, run `ipconfig` and parse the output
45
+ // Otherwise, ifconfig
46
+ if (os.platform() === "win32") {
47
+ let output = require("child_process").execSync("ipconfig").toString();
48
+ let sections = output.split("\r\n\r\n");
49
+
50
+ for (let section of sections) {
51
+ if (section.includes("IPv4 Address")) {
52
+ let ipv4Match = section.match(/IPv4 Address[.\s]*: ([\d.]+)/);
53
+ let gatewayMatch = section.match(/Default Gateway[.\s]*: ([\d.]+)/);
54
+
55
+ if (ipv4Match && gatewayMatch && looksLikeRouter(gatewayMatch[1])) {
56
+ return {
57
+ internalIP: ipv4Match[1],
58
+ gatewayIP: gatewayMatch[1]
59
+ };
49
60
  }
50
61
  }
51
62
  }
63
+ } else {
64
+ // For Unix-like systems (Linux, macOS)
65
+ // Try to get gateway from route command first
66
+ let routeOutput = require("child_process").execSync("route -n").toString();
67
+ let gatewayMatch = routeOutput.match(/0\.0\.0\.0\s+(\d+\.\d+\.\d+\.\d+)/);
68
+
69
+ if (!gatewayMatch) {
70
+ // Fallback for macOS
71
+ routeOutput = require("child_process").execSync("netstat -nr").toString();
72
+ gatewayMatch = routeOutput.match(/default\s+(\d+\.\d+\.\d+\.\d+)/);
73
+ }
74
+
75
+ if (gatewayMatch && looksLikeRouter(gatewayMatch[1])) {
76
+ // Now get the internal IP from ifconfig/ip addr
77
+ let ipCommand = os.platform() === "darwin" ? "ifconfig" : "ip addr";
78
+ let ipOutput = require("child_process").execSync(ipCommand).toString();
79
+
80
+ let ipMatch;
81
+ if (os.platform() === "darwin") {
82
+ ipMatch = ipOutput.match(/inet ((?!127\.0\.0\.1)\d+\.\d+\.\d+\.\d+)/);
83
+ } else {
84
+ ipMatch = ipOutput.match(/inet ((?!127\.0\.0\.1)\d+\.\d+\.\d+\.\d+)\/\d+/);
85
+ }
86
+
87
+ if (ipMatch) {
88
+ return {
89
+ internalIP: ipMatch[1],
90
+ gatewayIP: gatewayMatch[1]
91
+ };
92
+ }
93
+ }
52
94
  }
95
+
53
96
  return undefined;
54
97
  }
55
98
 
package/src/misc.ts CHANGED
@@ -205,47 +205,48 @@ export function throttleFunction<Args extends any[]>(
205
205
  let nextAllowedCall = 0;
206
206
  let pendingArgs: { args: Args; promiseObj: PromiseObj<void> } | undefined = undefined;
207
207
  function doCall(args: Args, promiseObj: PromiseObj<void>) {
208
- nextAllowedCall = Number.POSITIVE_INFINITY;
209
208
  try {
210
209
  let result = fnc(...args);
211
210
  promiseObj.resolve(result);
212
211
  if (result instanceof Promise) {
213
- result.finally(() => {
214
- afterCall(Date.now() + delay);
215
- }).catch(e => console.error(e));
212
+ // NOTE: The caller should handle the promise. If not, they probably
213
+ // want the unresolved promise rejection, so they can handle it properly.
214
+ void result.finally(() => {
215
+ nextAllowedCall = Date.now() + delay;
216
+ runNextCall();
217
+ });
216
218
  } else {
217
- afterCall(Date.now() + delay);
219
+ nextAllowedCall = Date.now() + delay;
220
+ runNextCall();
218
221
  }
219
222
  } catch (e: any) {
220
- debugger;
221
223
  promiseObj.reject(e);
222
- afterCall(Date.now() + delay);
224
+ nextAllowedCall = Date.now() + delay;
225
+ runNextCall();
223
226
  }
224
227
  }
225
- function afterCall(setNextAllowedCall: number | undefined, time = Date.now()) {
226
-
227
- // NOTE: Ignore error, we really shouldn't have any here
228
- if (setNextAllowedCall) {
229
- nextAllowedCall = setNextAllowedCall;
230
- } else {
231
- if (nextAllowedCall === Number.POSITIVE_INFINITY) return;
232
- }
228
+ function runNextCall() {
229
+ if (nextAllowedCall === Number.POSITIVE_INFINITY) return;
233
230
  if (!pendingArgs) return;
231
+ let time = Date.now();
234
232
  if (time > nextAllowedCall) {
235
- let args = pendingArgs;
236
- pendingArgs = undefined;
233
+ // Set nextAllowedCall to infinity, to prevent new calls from running
234
+ // until doCall finishes.
235
+ nextAllowedCall = Number.POSITIVE_INFINITY;
237
236
  // Delay, so we don't turn a series of sequential calls to a series of nested calls
238
237
  // (which will cause a stack overflow)
239
- nextAllowedCall = Number.POSITIVE_INFINITY;
240
- setImmediate(() => doCall(args.args, args.promiseObj));
241
- } else {
242
238
  setTimeout(() => {
243
- if (pendingArgs) {
244
- let args = pendingArgs;
245
- pendingArgs = undefined;
246
- doCall(args.args, args.promiseObj);
239
+ let args = pendingArgs;
240
+ pendingArgs = undefined;
241
+ if (!args) {
242
+ nextAllowedCall = 0;
243
+ console.warn(`Impossible, pendingArgs was reset when we shouldn't have even been in a call`);
244
+ return;
247
245
  }
248
- }, nextAllowedCall - time);
246
+ doCall(args.args, args.promiseObj);
247
+ }, 0);
248
+ } else {
249
+ setTimeout(runNextCall, nextAllowedCall - time);
249
250
  }
250
251
  }
251
252
  return function (...args: Args): Promise<void> {
@@ -253,16 +254,9 @@ export function throttleFunction<Args extends any[]>(
253
254
  pendingArgs.args = args;
254
255
  return pendingArgs.promiseObj.promise;
255
256
  }
256
- let time = Date.now();
257
- if (time > nextAllowedCall) {
258
- let promise = promiseObj();
259
- doCall(args, promise);
260
- return promise.promise;
261
- } else {
262
- pendingArgs = { args, promiseObj: promiseObj() };
263
- afterCall(undefined, time);
264
- return pendingArgs.promiseObj.promise;
265
- }
257
+ pendingArgs = { args, promiseObj: promiseObj() };
258
+ runNextCall();
259
+ return pendingArgs.promiseObj.promise;
266
260
  };
267
261
  }
268
262