@webvpn/dgram 0.0.1 → 0.2.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.
Files changed (91) hide show
  1. package/build/index.cjs +2235 -2327
  2. package/build/index.cjs.map +1 -1
  3. package/build/index.d.ts +5 -184
  4. package/build/index.js +10094 -2664
  5. package/build/index.js.map +1 -1
  6. package/package.json +4 -6
  7. package/src/index.ts +5 -698
  8. package/vite-plugin-node-stdlib-browser.cjs +61 -61
  9. package/vite.config.ts +29 -29
  10. package/build/index.mjs +0 -3252
  11. package/build/index.mjs.map +0 -1
  12. package/build/test.d.ts +0 -1
  13. package/build/utils.d.ts +0 -13
  14. package/index.html +0 -11
  15. package/src/chrome-dgram.js +0 -503
  16. package/src/flatbuffers/client-packet-type.ts +0 -40
  17. package/src/flatbuffers/client-packet.ts +0 -162
  18. package/src/flatbuffers/client-tcpserver-close.ts +0 -93
  19. package/src/flatbuffers/client-tcpserver-get-connections.ts +0 -93
  20. package/src/flatbuffers/client-tcpserver-listen.ts +0 -211
  21. package/src/flatbuffers/client-tcpserver.ts +0 -159
  22. package/src/flatbuffers/client-tcpsocket-connect.ts +0 -253
  23. package/src/flatbuffers/client-tcpsocket-destroy-soon.ts +0 -75
  24. package/src/flatbuffers/client-tcpsocket-destroy.ts +0 -93
  25. package/src/flatbuffers/client-tcpsocket-end.ts +0 -93
  26. package/src/flatbuffers/client-tcpsocket-pause.ts +0 -75
  27. package/src/flatbuffers/client-tcpsocket-reset-and-destroy.ts +0 -75
  28. package/src/flatbuffers/client-tcpsocket-resume.ts +0 -75
  29. package/src/flatbuffers/client-tcpsocket-set-encoding.ts +0 -93
  30. package/src/flatbuffers/client-tcpsocket-set-keep-alive.ts +0 -103
  31. package/src/flatbuffers/client-tcpsocket-set-no-delay.ts +0 -89
  32. package/src/flatbuffers/client-tcpsocket-set-timeout.ts +0 -107
  33. package/src/flatbuffers/client-tcpsocket-write.ts +0 -147
  34. package/src/flatbuffers/client-tcpsocket.ts +0 -89
  35. package/src/flatbuffers/client-udpsocket-add-membership.ts +0 -110
  36. package/src/flatbuffers/client-udpsocket-add-source-specific-membership.ts +0 -127
  37. package/src/flatbuffers/client-udpsocket-bind.ts +0 -138
  38. package/src/flatbuffers/client-udpsocket-close.ts +0 -93
  39. package/src/flatbuffers/client-udpsocket-disconnect.ts +0 -75
  40. package/src/flatbuffers/client-udpsocket-drop-membership.ts +0 -110
  41. package/src/flatbuffers/client-udpsocket-drop-source-specific-membership.ts +0 -127
  42. package/src/flatbuffers/client-udpsocket-send.ts +0 -189
  43. package/src/flatbuffers/client-udpsocket-set-broadcast.ts +0 -89
  44. package/src/flatbuffers/client-udpsocket-set-multicast-interface.ts +0 -93
  45. package/src/flatbuffers/client-udpsocket-set-multicast-loopback.ts +0 -89
  46. package/src/flatbuffers/client-udpsocket-set-multicast-ttl.ts +0 -89
  47. package/src/flatbuffers/client-udpsocket-set-recv-buffer-size.ts +0 -89
  48. package/src/flatbuffers/client-udpsocket-set-send-buffer-size.ts +0 -89
  49. package/src/flatbuffers/client-udpsocket-set-ttl.ts +0 -89
  50. package/src/flatbuffers/client-udpsocket.ts +0 -149
  51. package/src/flatbuffers/packet-handshake-type.ts +0 -9
  52. package/src/flatbuffers/packet.ts +0 -210
  53. package/src/flatbuffers/schema.ts +0 -75
  54. package/src/flatbuffers/server-packet-type.ts +0 -38
  55. package/src/flatbuffers/server-packet.ts +0 -158
  56. package/src/flatbuffers/server-tcpserver-callback-close.ts +0 -93
  57. package/src/flatbuffers/server-tcpserver-callback-get-connections.ts +0 -124
  58. package/src/flatbuffers/server-tcpserver-callback-listen.ts +0 -141
  59. package/src/flatbuffers/server-tcpserver-event-close.ts +0 -75
  60. package/src/flatbuffers/server-tcpserver-event-drop.ts +0 -75
  61. package/src/flatbuffers/server-tcpserver-event-error.ts +0 -75
  62. package/src/flatbuffers/server-tcpserver-event-listening.ts +0 -124
  63. package/src/flatbuffers/server-tcpsocket-callback-connect.ts +0 -189
  64. package/src/flatbuffers/server-tcpsocket-callback-end.ts +0 -93
  65. package/src/flatbuffers/server-tcpsocket-callback-set-timeout.ts +0 -93
  66. package/src/flatbuffers/server-tcpsocket-callback-write.ts +0 -93
  67. package/src/flatbuffers/server-tcpsocket-event-close.ts +0 -89
  68. package/src/flatbuffers/server-tcpsocket-event-connect.ts +0 -172
  69. package/src/flatbuffers/server-tcpsocket-event-connection-attempt-failed.ts +0 -138
  70. package/src/flatbuffers/server-tcpsocket-event-connection-attempt-timeout.ts +0 -121
  71. package/src/flatbuffers/server-tcpsocket-event-connection-attempt.ts +0 -121
  72. package/src/flatbuffers/server-tcpsocket-event-data.ts +0 -113
  73. package/src/flatbuffers/server-tcpsocket-event-drain.ts +0 -75
  74. package/src/flatbuffers/server-tcpsocket-event-end.ts +0 -75
  75. package/src/flatbuffers/server-tcpsocket-event-error.ts +0 -93
  76. package/src/flatbuffers/server-tcpsocket-event-lookup.ts +0 -141
  77. package/src/flatbuffers/server-tcpsocket-event-ready.ts +0 -75
  78. package/src/flatbuffers/server-tcpsocket-event-timeout.ts +0 -75
  79. package/src/flatbuffers/server-udpsocket-callback-bind.ts +0 -141
  80. package/src/flatbuffers/server-udpsocket-callback-close.ts +0 -93
  81. package/src/flatbuffers/server-udpsocket-callback-connect.ts +0 -141
  82. package/src/flatbuffers/server-udpsocket-callback-send.ts +0 -93
  83. package/src/flatbuffers/server-udpsocket-event-close.ts +0 -75
  84. package/src/flatbuffers/server-udpsocket-event-connect.ts +0 -75
  85. package/src/flatbuffers/server-udpsocket-event-error.ts +0 -93
  86. package/src/flatbuffers/server-udpsocket-event-listening.ts +0 -124
  87. package/src/flatbuffers/server-udpsocket-event-message.ts +0 -175
  88. package/src/net.js +0 -2442
  89. package/src/test.ts +0 -34
  90. package/src/types.ts +0 -16
  91. package/src/utils.ts +0 -45
package/build/index.cjs CHANGED
@@ -2,20 +2,281 @@
2
2
 
3
3
  Object.defineProperties(exports, { __esModule: { value: true }, [Symbol.toStringTag]: { value: 'Module' } });
4
4
 
5
+ const p = [];
6
+ for (let e = 0; e < 256; ++e)
7
+ p.push((e + 256).toString(16).slice(1));
8
+ function N(e, t = 0) {
9
+ return (p[e[t + 0]] + p[e[t + 1]] + p[e[t + 2]] + p[e[t + 3]] + "-" + p[e[t + 4]] + p[e[t + 5]] + "-" + p[e[t + 6]] + p[e[t + 7]] + "-" + p[e[t + 8]] + p[e[t + 9]] + "-" + p[e[t + 10]] + p[e[t + 11]] + p[e[t + 12]] + p[e[t + 13]] + p[e[t + 14]] + p[e[t + 15]]).toLowerCase();
10
+ }
11
+ let _$1;
12
+ const D$1 = new Uint8Array(16);
13
+ function z$1() {
14
+ if (!_$1) {
15
+ if (typeof crypto > "u" || !crypto.getRandomValues)
16
+ throw new Error("crypto.getRandomValues() not supported. See https://github.com/uuidjs/uuid#getrandomvalues-not-supported");
17
+ _$1 = crypto.getRandomValues.bind(crypto);
18
+ }
19
+ return _$1(D$1);
20
+ }
21
+ const Y = typeof crypto < "u" && crypto.randomUUID && crypto.randomUUID.bind(crypto), j = { randomUUID: Y };
22
+ function V(e, t, r) {
23
+ if (j.randomUUID && !t && !e)
24
+ return j.randomUUID();
25
+ e = e || {};
26
+ const o = e.random || (e.rng || z$1)();
27
+ return o[6] = o[6] & 15 | 64, o[8] = o[8] & 63 | 128, N(o);
28
+ }
29
+ const E$1 = "__OSRA__", G = "__OSRA_DEFAULT_KEY__", w$1 = "__OSRA_PROXY__", x = (e) => !!(globalThis.SharedArrayBuffer && e instanceof globalThis.SharedArrayBuffer), B = (e) => globalThis.ArrayBuffer && e instanceof globalThis.ArrayBuffer || globalThis.MessagePort && e instanceof globalThis.MessagePort || globalThis.ReadableStream && e instanceof globalThis.ReadableStream || globalThis.WritableStream && e instanceof globalThis.WritableStream || globalThis.TransformStream && e instanceof globalThis.TransformStream ? !0 : !!(globalThis.ImageBitmap && e instanceof globalThis.ImageBitmap), M$1 = (e) => {
30
+ const t = [], r = (o) => x(o) ? void 0 : B(o) ? t.push(o) : Array.isArray(o) ? o.map(r) : o && typeof o == "object" ? Object.values(o).map(r) : void 0;
31
+ return r(e), t;
32
+ }, K$1 = (e, t) => {
33
+ const r = "portId" in e ? e.portId : void 0, o = "port" in e ? e.port : r ? t.addIncomingProxiedMessagePort(r) : void 0;
34
+ if (!o) throw new Error("No ports received for proxied function");
35
+ const c = (...n) => new Promise((i, f) => {
36
+ const { port1: g, port2: l } = new MessageChannel(), m = y([l, n], t), A = M$1(m), S = (h) => {
37
+ const b = R$2(h.data, t);
38
+ if (!(b instanceof Promise)) throw new Error("Proxied function did not return a promise");
39
+ b.then(i).catch(f).finally(() => g.close());
40
+ };
41
+ g.addEventListener("message", S, { once: !0 }), g.start(), o.postMessage(m, { transfer: A });
42
+ });
43
+ return r && t.finalizationRegistry.register(c, Number(r.split("/")[1])), c;
44
+ }, W = (e, t) => {
45
+ const r = t.envCheck.supportsPorts && "port" in e ? e.port : "portId" in e ? t.addIncomingProxiedMessagePort(e.portId) : void 0;
46
+ if (!r) throw new Error("No ports received for proxied message port");
47
+ return r;
48
+ }, X = (e, t) => new Error(e.message, { cause: e.stack }), H = (e, t) => new Promise((r, o) => {
49
+ const c = "port" in e ? e.port : "portId" in e ? t.addIncomingProxiedMessagePort(e.portId) : void 0;
50
+ if (!c) throw new Error("No ports received for proxied promise");
51
+ const n = async (i) => {
52
+ const f = await R$2(i.data, t);
53
+ f instanceof Error ? o(f) : r(f), c.close();
54
+ };
55
+ c.addEventListener("message", n, { once: !0 }), c.start();
56
+ }), R$2 = (e, t) => O(
57
+ e,
58
+ (r) => !!(r && typeof r == "object" && w$1 in r && r[w$1]),
59
+ (r) => {
60
+ if (r.type === "function")
61
+ return K$1(r, t);
62
+ if (r.type === "error")
63
+ return X(r);
64
+ if (r.type === "messagePort")
65
+ return W(r, t);
66
+ if (r.type === "promise")
67
+ return H(r, t);
68
+ throw new Error(`Unknown incoming proxied type: ${e}`);
69
+ }
70
+ ), q = (e, t) => ({
71
+ [w$1]: !0,
72
+ type: "error",
73
+ message: e.message,
74
+ stack: e.stack
75
+ }), F = (e, t) => ({
76
+ [w$1]: !0,
77
+ type: "messagePort",
78
+ ...t.envCheck.supportsPorts ? { port: e } : { portId: t.addOutgoingProxiedMessagePort(e) }
79
+ }), J = (e, t) => {
80
+ const { port1: r, port2: o } = new MessageChannel(), c = (n) => {
81
+ const i = y(n, t), f = M$1(i);
82
+ r.postMessage(i, { transfer: f }), r.close();
83
+ };
84
+ return e.then(c).catch(c), {
85
+ [w$1]: !0,
86
+ type: "promise",
87
+ port: y(o, t)
88
+ };
89
+ }, Q = (e, t) => {
90
+ const { port1: r, port2: o } = new MessageChannel();
91
+ return r.addEventListener("message", async (c) => {
92
+ const [n, i] = R$2(c.data, t), f = (async () => e(...i))(), g = y(f, t), l = M$1(g);
93
+ n.postMessage(g, { transfer: l }), n.close();
94
+ }), r.start(), {
95
+ [w$1]: !0,
96
+ type: "function",
97
+ port: y(o, t)
98
+ };
99
+ }, y = (e, t) => O(
100
+ e,
101
+ (r) => typeof r == "function" || r instanceof Error || r instanceof MessagePort || r instanceof Promise,
102
+ (r) => {
103
+ if (typeof r == "function")
104
+ return Q(r, t);
105
+ if (r instanceof Error)
106
+ return q(r);
107
+ if (r instanceof MessagePort)
108
+ return F(r, t);
109
+ if (r instanceof Promise)
110
+ return J(r, t);
111
+ throw new Error(`Unknown outgoing proxied type: ${r}`);
112
+ }
113
+ ), O = (e, t, r) => x(e) || B(e) ? e : t(e) ? r(e) : Array.isArray(e) ? e.map((o) => O(o, t, r)) : e && typeof e == "object" ? Object.fromEntries(
114
+ Object.entries(e).map(([o, c]) => [
115
+ o,
116
+ O(c, t, r)
117
+ ])
118
+ ) : e, Z = () => {
119
+ let e = 0;
120
+ const t = /* @__PURE__ */ new Set();
121
+ return {
122
+ alloc: () => {
123
+ if (t.size > 0) {
124
+ const r = t.values().next().value;
125
+ if (r === void 0)
126
+ throw new Error("Tried to allocate number from freedUnused but result was undefined");
127
+ return t.delete(r), r;
128
+ }
129
+ return e++, e;
130
+ },
131
+ free: (r) => {
132
+ t.add(r);
133
+ }
134
+ };
135
+ }, v = ({ numberAllocator: e }) => {
136
+ const t = /* @__PURE__ */ new Map();
137
+ return {
138
+ alloc: (n) => {
139
+ const i = e.alloc();
140
+ return t.set(i, n), i;
141
+ },
142
+ get: (n) => t.get(n),
143
+ free: (n) => {
144
+ t.delete(n), e.free(n);
145
+ }
146
+ };
147
+ }, ee = async (e, {
148
+ remote: t,
149
+ local: r,
150
+ key: o = G,
151
+ origin: c = "*"
152
+ }) => {
153
+ const n = V();
154
+ let i;
155
+ const f = new FinalizationRegistry((s) => {
156
+ const a = l.get(s);
157
+ if (!a) throw new Error(`Osra received a port-closed message with an invalid portId "${s}".`);
158
+ a(), l.free(s);
159
+ }), g = Z(), l = v({ numberAllocator: g }), m = /* @__PURE__ */ new Map(), A = (s) => {
160
+ const { port1: a, port2: d } = new MessageChannel();
161
+ return m.set(s, a), d;
162
+ }, S = (s) => {
163
+ const a = l.alloc(() => {
164
+ s.close();
165
+ });
166
+ return s.addEventListener("message", async (d) => {
167
+ T(
168
+ {
169
+ [E$1]: !0,
170
+ key: o,
171
+ type: "message",
172
+ portId: `${n}/${a}`,
173
+ data: y(d.data, h())
174
+ },
175
+ []
176
+ );
177
+ }), s.addEventListener("close", () => {
178
+ g.free(a), T(
179
+ {
180
+ [E$1]: !0,
181
+ key: o,
182
+ type: "port-closed",
183
+ portId: `${n}/${a}`
184
+ },
185
+ []
186
+ );
187
+ }), `${n}/${a}`;
188
+ }, h = () => {
189
+ if (!i) throw new Error("Osra context was accessed before the ready message was received.");
190
+ return {
191
+ addIncomingProxiedMessagePort: A,
192
+ addOutgoingProxiedMessagePort: S,
193
+ envCheck: i,
194
+ finalizationRegistry: f
195
+ };
196
+ };
197
+ let b;
198
+ const L = new Promise((s, a) => {
199
+ b = s;
200
+ }), U = () => {
201
+ const s = new ArrayBuffer(1), { port1: a } = new MessageChannel();
202
+ T(
203
+ {
204
+ [E$1]: !0,
205
+ key: o,
206
+ type: "ready",
207
+ envCheck: { buffer: s, port: a }
208
+ },
209
+ [s, a]
210
+ );
211
+ };
212
+ let C = !1;
213
+ const $ = async (s) => {
214
+ if (!s.data || typeof s.data != "object" || !s.data[E$1] || s.data.key !== o) return;
215
+ const { type: a } = s.data;
216
+ if (a === "ready" && !C) {
217
+ C = !0, i = {
218
+ uuid: n,
219
+ supportsPorts: s.data.envCheck.port instanceof MessagePort,
220
+ jsonOnly: s.data.envCheck.buffer instanceof ArrayBuffer
221
+ }, U();
222
+ const d = y(e, h()), u = M$1(d);
223
+ T(
224
+ {
225
+ [E$1]: !0,
226
+ key: o,
227
+ type: "init",
228
+ data: d
229
+ },
230
+ u
231
+ );
232
+ return;
233
+ }
234
+ if (!C || !i) throw new Error("Osra received a message before the ready message.");
235
+ if (a === "init") {
236
+ b(
237
+ R$2(
238
+ s.data.data,
239
+ h()
240
+ )
241
+ );
242
+ return;
243
+ }
244
+ if (a === "message") {
245
+ const { portId: d, data: u } = s.data, I = m.get(d);
246
+ if (!I) throw new Error(`Osra received a message with portId set to "${d}" but no port was found.`);
247
+ I.postMessage(u);
248
+ } else if (a === "port-closed") {
249
+ const { portId: d } = s.data, [u, I] = d.split("/"), k = Number(I);
250
+ if (!k) throw new Error(`Osra received a port-closed message with an invalid portId "${d}".`);
251
+ if (u !== n && u !== i.uuid) throw new Error(`Osra received a port-closed message with an invalid portId's uuid "${d}".`);
252
+ if (u === n) {
253
+ const P = l.get(k);
254
+ if (!P) throw new Error(`Osra received a port-closed message with an invalid portId "${d}".`);
255
+ P();
256
+ } else if (u === i.uuid) {
257
+ const P = m.get(d);
258
+ if (!P) throw new Error(`Osra received a message with portId set to "${d}" but no port was found.`);
259
+ P.close(), m.delete(d);
260
+ }
261
+ }
262
+ }, T = typeof t == "function" ? t : (s, a = []) => t.postMessage(s, { targetOrigin: c, transfer: a });
263
+ return typeof r == "function" ? r($) : r.addEventListener("message", $), U(), L;
264
+ };
265
+
5
266
  var commonjsGlobal = typeof globalThis !== 'undefined' ? globalThis : typeof window !== 'undefined' ? window : typeof global !== 'undefined' ? global : typeof self !== 'undefined' ? self : {};
6
267
 
7
268
  var events = {exports: {}};
8
269
 
9
- var R = typeof Reflect === 'object' ? Reflect : null;
10
- var ReflectApply = R && typeof R.apply === 'function'
11
- ? R.apply
270
+ var R$1 = typeof Reflect === 'object' ? Reflect : null;
271
+ var ReflectApply = R$1 && typeof R$1.apply === 'function'
272
+ ? R$1.apply
12
273
  : function ReflectApply(target, receiver, args) {
13
274
  return Function.prototype.apply.call(target, receiver, args);
14
275
  };
15
276
 
16
277
  var ReflectOwnKeys;
17
- if (R && typeof R.ownKeys === 'function') {
18
- ReflectOwnKeys = R.ownKeys;
278
+ if (R$1 && typeof R$1.ownKeys === 'function') {
279
+ ReflectOwnKeys = R$1.ownKeys;
19
280
  } else if (Object.getOwnPropertySymbols) {
20
281
  ReflectOwnKeys = function ReflectOwnKeys(target) {
21
282
  return Object.getOwnPropertyNames(target)
@@ -8388,2398 +8649,2045 @@ Stream.prototype.pipe = function(dest, options) {
8388
8649
  return dest;
8389
8650
  };
8390
8651
 
8391
- var decoder;
8392
- try {
8393
- decoder = new TextDecoder();
8394
- } catch(error) {}
8395
- var src;
8396
- var srcEnd;
8397
- var position$1 = 0;
8398
- var currentUnpackr = {};
8399
- var currentStructures;
8400
- var srcString;
8401
- var srcStringStart = 0;
8402
- var srcStringEnd = 0;
8403
- var bundledStrings$1;
8404
- var referenceMap;
8405
- var currentExtensions = [];
8406
- var dataView;
8407
- var defaultOptions = {
8408
- useRecords: false,
8409
- mapsAsObjects: true
8410
- };
8411
- class C1Type {}
8412
- const C1 = new C1Type();
8413
- C1.name = 'MessagePack 0xC1';
8414
- var sequentialMode = false;
8415
- var inlineObjectReadThreshold = 2;
8416
- var readStruct;
8417
- // no-eval build
8418
- try {
8419
- new Function('');
8420
- } catch(error) {
8421
- // if eval variants are not supported, do not create inline object readers ever
8422
- inlineObjectReadThreshold = Infinity;
8423
- }
8652
+ var ipAddress = {};
8424
8653
 
8425
- class Unpackr {
8426
- constructor(options) {
8427
- if (options) {
8428
- if (options.useRecords === false && options.mapsAsObjects === undefined)
8429
- options.mapsAsObjects = true;
8430
- if (options.sequential && options.trusted !== false) {
8431
- options.trusted = true;
8432
- if (!options.structures && options.useRecords != false) {
8433
- options.structures = [];
8434
- if (!options.maxSharedStructures)
8435
- options.maxSharedStructures = 0;
8436
- }
8437
- }
8438
- if (options.structures)
8439
- options.structures.sharedLength = options.structures.length;
8440
- else if (options.getStructures) {
8441
- (options.structures = []).uninitialized = true; // this is what we use to denote an uninitialized structures
8442
- options.structures.sharedLength = 0;
8443
- }
8444
- if (options.int64AsNumber) {
8445
- options.int64AsType = 'number';
8446
- }
8447
- }
8448
- Object.assign(this, options);
8449
- }
8450
- unpack(source, options) {
8451
- if (src) {
8452
- // re-entrant execution, save the state and restore it after we do this unpack
8453
- return saveState(() => {
8454
- clearSource();
8455
- return this ? this.unpack(source, options) : Unpackr.prototype.unpack.call(defaultOptions, source, options)
8456
- })
8457
- }
8458
- if (!source.buffer && source.constructor === ArrayBuffer)
8459
- source = typeof Buffer !== 'undefined' ? Buffer.from(source) : new Uint8Array(source);
8460
- if (typeof options === 'object') {
8461
- srcEnd = options.end || source.length;
8462
- position$1 = options.start || 0;
8463
- } else {
8464
- position$1 = 0;
8465
- srcEnd = options > -1 ? options : source.length;
8466
- }
8467
- srcStringEnd = 0;
8468
- srcString = null;
8469
- bundledStrings$1 = null;
8470
- src = source;
8471
- // this provides cached access to the data view for a buffer if it is getting reused, which is a recommend
8472
- // technique for getting data from a database where it can be copied into an existing buffer instead of creating
8473
- // new ones
8474
- try {
8475
- dataView = source.dataView || (source.dataView = new DataView(source.buffer, source.byteOffset, source.byteLength));
8476
- } catch(error) {
8477
- // if it doesn't have a buffer, maybe it is the wrong type of object
8478
- src = null;
8479
- if (source instanceof Uint8Array)
8480
- throw error
8481
- throw new Error('Source must be a Uint8Array or Buffer but was a ' + ((source && typeof source == 'object') ? source.constructor.name : typeof source))
8482
- }
8483
- if (this instanceof Unpackr) {
8484
- currentUnpackr = this;
8485
- if (this.structures) {
8486
- currentStructures = this.structures;
8487
- return checkedRead(options)
8488
- } else if (!currentStructures || currentStructures.length > 0) {
8489
- currentStructures = [];
8490
- }
8491
- } else {
8492
- currentUnpackr = defaultOptions;
8493
- if (!currentStructures || currentStructures.length > 0)
8494
- currentStructures = [];
8495
- }
8496
- return checkedRead(options)
8497
- }
8498
- unpackMultiple(source, forEach) {
8499
- let values, lastPosition = 0;
8500
- try {
8501
- sequentialMode = true;
8502
- let size = source.length;
8503
- let value = this ? this.unpack(source, size) : defaultUnpackr.unpack(source, size);
8504
- if (forEach) {
8505
- if (forEach(value, lastPosition, position$1) === false) return;
8506
- while(position$1 < size) {
8507
- lastPosition = position$1;
8508
- if (forEach(checkedRead(), lastPosition, position$1) === false) {
8509
- return
8510
- }
8511
- }
8512
- }
8513
- else {
8514
- values = [ value ];
8515
- while(position$1 < size) {
8516
- lastPosition = position$1;
8517
- values.push(checkedRead());
8518
- }
8519
- return values
8520
- }
8521
- } catch(error) {
8522
- error.lastPosition = lastPosition;
8523
- error.values = values;
8524
- throw error
8525
- } finally {
8526
- sequentialMode = false;
8527
- clearSource();
8528
- }
8529
- }
8530
- _mergeStructures(loadedStructures, existingStructures) {
8531
- loadedStructures = loadedStructures || [];
8532
- if (Object.isFrozen(loadedStructures))
8533
- loadedStructures = loadedStructures.map(structure => structure.slice(0));
8534
- for (let i = 0, l = loadedStructures.length; i < l; i++) {
8535
- let structure = loadedStructures[i];
8536
- if (structure) {
8537
- structure.isShared = true;
8538
- if (i >= 32)
8539
- structure.highByte = (i - 32) >> 5;
8540
- }
8541
- }
8542
- loadedStructures.sharedLength = loadedStructures.length;
8543
- for (let id in existingStructures || []) {
8544
- if (id >= 0) {
8545
- let structure = loadedStructures[id];
8546
- let existing = existingStructures[id];
8547
- if (existing) {
8548
- if (structure)
8549
- (loadedStructures.restoreStructures || (loadedStructures.restoreStructures = []))[id] = structure;
8550
- loadedStructures[id] = existing;
8551
- }
8552
- }
8553
- }
8554
- return this.structures = loadedStructures
8555
- }
8556
- decode(source, options) {
8557
- return this.unpack(source, options)
8558
- }
8654
+ var ipv4 = {};
8655
+
8656
+ var common$2 = {};
8657
+
8658
+ Object.defineProperty(common$2, "__esModule", { value: true });
8659
+ common$2.isInSubnet = isInSubnet;
8660
+ common$2.isCorrect = isCorrect;
8661
+ common$2.numberToPaddedHex = numberToPaddedHex;
8662
+ common$2.stringToPaddedHex = stringToPaddedHex;
8663
+ common$2.testBit = testBit;
8664
+ function isInSubnet(address) {
8665
+ if (this.subnetMask < address.subnetMask) {
8666
+ return false;
8667
+ }
8668
+ if (this.mask(address.subnetMask) === address.mask()) {
8669
+ return true;
8670
+ }
8671
+ return false;
8559
8672
  }
8560
- function checkedRead(options) {
8561
- try {
8562
- if (!currentUnpackr.trusted && !sequentialMode) {
8563
- let sharedLength = currentStructures.sharedLength || 0;
8564
- if (sharedLength < currentStructures.length)
8565
- currentStructures.length = sharedLength;
8566
- }
8567
- let result;
8568
- if (currentUnpackr.randomAccessStructure && src[position$1] < 0x40 && src[position$1] >= 0x20 && readStruct) {
8569
- result = readStruct(src, position$1, srcEnd, currentUnpackr);
8570
- src = null; // dispose of this so that recursive unpack calls don't save state
8571
- if (!(options && options.lazy) && result)
8572
- result = result.toJSON();
8573
- position$1 = srcEnd;
8574
- } else
8575
- result = read();
8576
- if (bundledStrings$1) { // bundled strings to skip past
8577
- position$1 = bundledStrings$1.postBundlePosition;
8578
- bundledStrings$1 = null;
8579
- }
8580
- if (sequentialMode)
8581
- // we only need to restore the structures if there was an error, but if we completed a read,
8582
- // we can clear this out and keep the structures we read
8583
- currentStructures.restoreStructures = null;
8584
-
8585
- if (position$1 == srcEnd) {
8586
- // finished reading this source, cleanup references
8587
- if (currentStructures && currentStructures.restoreStructures)
8588
- restoreStructures();
8589
- currentStructures = null;
8590
- src = null;
8591
- if (referenceMap)
8592
- referenceMap = null;
8593
- } else if (position$1 > srcEnd) {
8594
- // over read
8595
- throw new Error('Unexpected end of MessagePack data')
8596
- } else if (!sequentialMode) {
8597
- let jsonView;
8598
- try {
8599
- jsonView = JSON.stringify(result, (_, value) => typeof value === "bigint" ? `${value}n` : value).slice(0, 100);
8600
- } catch(error) {
8601
- jsonView = '(JSON view not available ' + error + ')';
8602
- }
8603
- throw new Error('Data read, but end of buffer not reached ' + jsonView)
8604
- }
8605
- // else more to read, but we are reading sequentially, so don't clear source yet
8606
- return result
8607
- } catch(error) {
8608
- if (currentStructures && currentStructures.restoreStructures)
8609
- restoreStructures();
8610
- clearSource();
8611
- if (error instanceof RangeError || error.message.startsWith('Unexpected end of buffer') || position$1 > srcEnd) {
8612
- error.incomplete = true;
8613
- }
8614
- throw error
8615
- }
8673
+ function isCorrect(defaultBits) {
8674
+ return function () {
8675
+ if (this.addressMinusSuffix !== this.correctForm()) {
8676
+ return false;
8677
+ }
8678
+ if (this.subnetMask === defaultBits && !this.parsedSubnet) {
8679
+ return true;
8680
+ }
8681
+ return this.parsedSubnet === String(this.subnetMask);
8682
+ };
8616
8683
  }
8617
-
8618
- function restoreStructures() {
8619
- for (let id in currentStructures.restoreStructures) {
8620
- currentStructures[id] = currentStructures.restoreStructures[id];
8621
- }
8622
- currentStructures.restoreStructures = null;
8684
+ function numberToPaddedHex(number) {
8685
+ return number.toString(16).padStart(2, '0');
8623
8686
  }
8624
-
8625
- function read() {
8626
- let token = src[position$1++];
8627
- if (token < 0xa0) {
8628
- if (token < 0x80) {
8629
- if (token < 0x40)
8630
- return token
8631
- else {
8632
- let structure = currentStructures[token & 0x3f] ||
8633
- currentUnpackr.getStructures && loadStructures()[token & 0x3f];
8634
- if (structure) {
8635
- if (!structure.read) {
8636
- structure.read = createStructureReader(structure, token & 0x3f);
8637
- }
8638
- return structure.read()
8639
- } else
8640
- return token
8641
- }
8642
- } else if (token < 0x90) {
8643
- // map
8644
- token -= 0x80;
8645
- if (currentUnpackr.mapsAsObjects) {
8646
- let object = {};
8647
- for (let i = 0; i < token; i++) {
8648
- let key = readKey();
8649
- if (key === '__proto__')
8650
- key = '__proto_';
8651
- object[key] = read();
8652
- }
8653
- return object
8654
- } else {
8655
- let map = new Map();
8656
- for (let i = 0; i < token; i++) {
8657
- map.set(read(), read());
8658
- }
8659
- return map
8660
- }
8661
- } else {
8662
- token -= 0x90;
8663
- let array = new Array(token);
8664
- for (let i = 0; i < token; i++) {
8665
- array[i] = read();
8666
- }
8667
- if (currentUnpackr.freezeData)
8668
- return Object.freeze(array)
8669
- return array
8670
- }
8671
- } else if (token < 0xc0) {
8672
- // fixstr
8673
- let length = token - 0xa0;
8674
- if (srcStringEnd >= position$1) {
8675
- return srcString.slice(position$1 - srcStringStart, (position$1 += length) - srcStringStart)
8676
- }
8677
- if (srcStringEnd == 0 && srcEnd < 140) {
8678
- // for small blocks, avoiding the overhead of the extract call is helpful
8679
- let string = length < 16 ? shortStringInJS(length) : longStringInJS(length);
8680
- if (string != null)
8681
- return string
8682
- }
8683
- return readFixedString(length)
8684
- } else {
8685
- let value;
8686
- switch (token) {
8687
- case 0xc0: return null
8688
- case 0xc1:
8689
- if (bundledStrings$1) {
8690
- value = read(); // followed by the length of the string in characters (not bytes!)
8691
- if (value > 0)
8692
- return bundledStrings$1[1].slice(bundledStrings$1.position1, bundledStrings$1.position1 += value)
8693
- else
8694
- return bundledStrings$1[0].slice(bundledStrings$1.position0, bundledStrings$1.position0 -= value)
8695
- }
8696
- return C1; // "never-used", return special object to denote that
8697
- case 0xc2: return false
8698
- case 0xc3: return true
8699
- case 0xc4:
8700
- // bin 8
8701
- value = src[position$1++];
8702
- if (value === undefined)
8703
- throw new Error('Unexpected end of buffer')
8704
- return readBin(value)
8705
- case 0xc5:
8706
- // bin 16
8707
- value = dataView.getUint16(position$1);
8708
- position$1 += 2;
8709
- return readBin(value)
8710
- case 0xc6:
8711
- // bin 32
8712
- value = dataView.getUint32(position$1);
8713
- position$1 += 4;
8714
- return readBin(value)
8715
- case 0xc7:
8716
- // ext 8
8717
- return readExt(src[position$1++])
8718
- case 0xc8:
8719
- // ext 16
8720
- value = dataView.getUint16(position$1);
8721
- position$1 += 2;
8722
- return readExt(value)
8723
- case 0xc9:
8724
- // ext 32
8725
- value = dataView.getUint32(position$1);
8726
- position$1 += 4;
8727
- return readExt(value)
8728
- case 0xca:
8729
- value = dataView.getFloat32(position$1);
8730
- if (currentUnpackr.useFloat32 > 2) {
8731
- // this does rounding of numbers that were encoded in 32-bit float to nearest significant decimal digit that could be preserved
8732
- let multiplier = mult10[((src[position$1] & 0x7f) << 1) | (src[position$1 + 1] >> 7)];
8733
- position$1 += 4;
8734
- return ((multiplier * value + (value > 0 ? 0.5 : -0.5)) >> 0) / multiplier
8735
- }
8736
- position$1 += 4;
8737
- return value
8738
- case 0xcb:
8739
- value = dataView.getFloat64(position$1);
8740
- position$1 += 8;
8741
- return value
8742
- // uint handlers
8743
- case 0xcc:
8744
- return src[position$1++]
8745
- case 0xcd:
8746
- value = dataView.getUint16(position$1);
8747
- position$1 += 2;
8748
- return value
8749
- case 0xce:
8750
- value = dataView.getUint32(position$1);
8751
- position$1 += 4;
8752
- return value
8753
- case 0xcf:
8754
- if (currentUnpackr.int64AsType === 'number') {
8755
- value = dataView.getUint32(position$1) * 0x100000000;
8756
- value += dataView.getUint32(position$1 + 4);
8757
- } else if (currentUnpackr.int64AsType === 'string') {
8758
- value = dataView.getBigUint64(position$1).toString();
8759
- } else if (currentUnpackr.int64AsType === 'auto') {
8760
- value = dataView.getBigUint64(position$1);
8761
- if (value<=BigInt(2)<<BigInt(52)) value=Number(value);
8762
- } else
8763
- value = dataView.getBigUint64(position$1);
8764
- position$1 += 8;
8765
- return value
8766
-
8767
- // int handlers
8768
- case 0xd0:
8769
- return dataView.getInt8(position$1++)
8770
- case 0xd1:
8771
- value = dataView.getInt16(position$1);
8772
- position$1 += 2;
8773
- return value
8774
- case 0xd2:
8775
- value = dataView.getInt32(position$1);
8776
- position$1 += 4;
8777
- return value
8778
- case 0xd3:
8779
- if (currentUnpackr.int64AsType === 'number') {
8780
- value = dataView.getInt32(position$1) * 0x100000000;
8781
- value += dataView.getUint32(position$1 + 4);
8782
- } else if (currentUnpackr.int64AsType === 'string') {
8783
- value = dataView.getBigInt64(position$1).toString();
8784
- } else if (currentUnpackr.int64AsType === 'auto') {
8785
- value = dataView.getBigInt64(position$1);
8786
- if (value>=BigInt(-2)<<BigInt(52)&&value<=BigInt(2)<<BigInt(52)) value=Number(value);
8787
- } else
8788
- value = dataView.getBigInt64(position$1);
8789
- position$1 += 8;
8790
- return value
8791
-
8792
- case 0xd4:
8793
- // fixext 1
8794
- value = src[position$1++];
8795
- if (value == 0x72) {
8796
- return recordDefinition(src[position$1++] & 0x3f)
8797
- } else {
8798
- let extension = currentExtensions[value];
8799
- if (extension) {
8800
- if (extension.read) {
8801
- position$1++; // skip filler byte
8802
- return extension.read(read())
8803
- } else if (extension.noBuffer) {
8804
- position$1++; // skip filler byte
8805
- return extension()
8806
- } else
8807
- return extension(src.subarray(position$1, ++position$1))
8808
- } else
8809
- throw new Error('Unknown extension ' + value)
8810
- }
8811
- case 0xd5:
8812
- // fixext 2
8813
- value = src[position$1];
8814
- if (value == 0x72) {
8815
- position$1++;
8816
- return recordDefinition(src[position$1++] & 0x3f, src[position$1++])
8817
- } else
8818
- return readExt(2)
8819
- case 0xd6:
8820
- // fixext 4
8821
- return readExt(4)
8822
- case 0xd7:
8823
- // fixext 8
8824
- return readExt(8)
8825
- case 0xd8:
8826
- // fixext 16
8827
- return readExt(16)
8828
- case 0xd9:
8829
- // str 8
8830
- value = src[position$1++];
8831
- if (srcStringEnd >= position$1) {
8832
- return srcString.slice(position$1 - srcStringStart, (position$1 += value) - srcStringStart)
8833
- }
8834
- return readString8(value)
8835
- case 0xda:
8836
- // str 16
8837
- value = dataView.getUint16(position$1);
8838
- position$1 += 2;
8839
- if (srcStringEnd >= position$1) {
8840
- return srcString.slice(position$1 - srcStringStart, (position$1 += value) - srcStringStart)
8841
- }
8842
- return readString16(value)
8843
- case 0xdb:
8844
- // str 32
8845
- value = dataView.getUint32(position$1);
8846
- position$1 += 4;
8847
- if (srcStringEnd >= position$1) {
8848
- return srcString.slice(position$1 - srcStringStart, (position$1 += value) - srcStringStart)
8849
- }
8850
- return readString32(value)
8851
- case 0xdc:
8852
- // array 16
8853
- value = dataView.getUint16(position$1);
8854
- position$1 += 2;
8855
- return readArray(value)
8856
- case 0xdd:
8857
- // array 32
8858
- value = dataView.getUint32(position$1);
8859
- position$1 += 4;
8860
- return readArray(value)
8861
- case 0xde:
8862
- // map 16
8863
- value = dataView.getUint16(position$1);
8864
- position$1 += 2;
8865
- return readMap(value)
8866
- case 0xdf:
8867
- // map 32
8868
- value = dataView.getUint32(position$1);
8869
- position$1 += 4;
8870
- return readMap(value)
8871
- default: // negative int
8872
- if (token >= 0xe0)
8873
- return token - 0x100
8874
- if (token === undefined) {
8875
- let error = new Error('Unexpected end of MessagePack data');
8876
- error.incomplete = true;
8877
- throw error
8878
- }
8879
- throw new Error('Unknown MessagePack token ' + token)
8880
-
8881
- }
8882
- }
8687
+ function stringToPaddedHex(numberString) {
8688
+ return numberToPaddedHex(parseInt(numberString, 10));
8883
8689
  }
8884
- const validName = /^[a-zA-Z_$][a-zA-Z\d_$]*$/;
8885
- function createStructureReader(structure, firstId) {
8886
- function readObject() {
8887
- // This initial function is quick to instantiate, but runs slower. After several iterations pay the cost to build the faster function
8888
- if (readObject.count++ > inlineObjectReadThreshold) {
8889
- let readObject = structure.read = (new Function('r', 'return function(){return ' + (currentUnpackr.freezeData ? 'Object.freeze' : '') +
8890
- '({' + structure.map(key => key === '__proto__' ? '__proto_:r()' : validName.test(key) ? key + ':r()' : ('[' + JSON.stringify(key) + ']:r()')).join(',') + '})}'))(read);
8891
- if (structure.highByte === 0)
8892
- structure.read = createSecondByteReader(firstId, structure.read);
8893
- return readObject() // second byte is already read, if there is one so immediately read object
8894
- }
8895
- let object = {};
8896
- for (let i = 0, l = structure.length; i < l; i++) {
8897
- let key = structure[i];
8898
- if (key === '__proto__')
8899
- key = '__proto_';
8900
- object[key] = read();
8901
- }
8902
- if (currentUnpackr.freezeData)
8903
- return Object.freeze(object);
8904
- return object
8905
- }
8906
- readObject.count = 0;
8907
- if (structure.highByte === 0) {
8908
- return createSecondByteReader(firstId, readObject)
8909
- }
8910
- return readObject
8690
+ /**
8691
+ * @param binaryValue Binary representation of a value (e.g. `10`)
8692
+ * @param position Byte position, where 0 is the least significant bit
8693
+ */
8694
+ function testBit(binaryValue, position) {
8695
+ const { length } = binaryValue;
8696
+ if (position > length) {
8697
+ return false;
8698
+ }
8699
+ const positionInString = length - position;
8700
+ return binaryValue.substring(positionInString, positionInString + 1) === '1';
8911
8701
  }
8912
8702
 
8913
- const createSecondByteReader = (firstId, read0) => {
8914
- return function() {
8915
- let highByte = src[position$1++];
8916
- if (highByte === 0)
8917
- return read0()
8918
- let id = firstId < 32 ? -(firstId + (highByte << 5)) : firstId + (highByte << 5);
8919
- let structure = currentStructures[id] || loadStructures()[id];
8920
- if (!structure) {
8921
- throw new Error('Record id is not defined for ' + id)
8922
- }
8923
- if (!structure.read)
8924
- structure.read = createStructureReader(structure, firstId);
8925
- return structure.read()
8926
- }
8927
- };
8703
+ var constants$2 = {};
8928
8704
 
8929
- function loadStructures() {
8930
- let loadedStructures = saveState(() => {
8931
- // save the state in case getStructures modifies our buffer
8932
- src = null;
8933
- return currentUnpackr.getStructures()
8934
- });
8935
- return currentStructures = currentUnpackr._mergeStructures(loadedStructures, currentStructures)
8936
- }
8705
+ Object.defineProperty(constants$2, "__esModule", { value: true });
8706
+ constants$2.RE_SUBNET_STRING = constants$2.RE_ADDRESS = constants$2.GROUPS = constants$2.BITS = void 0;
8707
+ constants$2.BITS = 32;
8708
+ constants$2.GROUPS = 4;
8709
+ constants$2.RE_ADDRESS = /^(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)$/g;
8710
+ constants$2.RE_SUBNET_STRING = /\/\d{1,2}$/;
8937
8711
 
8938
- var readFixedString = readStringJS;
8939
- var readString8 = readStringJS;
8940
- var readString16 = readStringJS;
8941
- var readString32 = readStringJS;
8942
- function readStringJS(length) {
8943
- let result;
8944
- if (length < 16) {
8945
- if (result = shortStringInJS(length))
8946
- return result
8947
- }
8948
- if (length > 64 && decoder)
8949
- return decoder.decode(src.subarray(position$1, position$1 += length))
8950
- const end = position$1 + length;
8951
- const units = [];
8952
- result = '';
8953
- while (position$1 < end) {
8954
- const byte1 = src[position$1++];
8955
- if ((byte1 & 0x80) === 0) {
8956
- // 1 byte
8957
- units.push(byte1);
8958
- } else if ((byte1 & 0xe0) === 0xc0) {
8959
- // 2 bytes
8960
- const byte2 = src[position$1++] & 0x3f;
8961
- units.push(((byte1 & 0x1f) << 6) | byte2);
8962
- } else if ((byte1 & 0xf0) === 0xe0) {
8963
- // 3 bytes
8964
- const byte2 = src[position$1++] & 0x3f;
8965
- const byte3 = src[position$1++] & 0x3f;
8966
- units.push(((byte1 & 0x1f) << 12) | (byte2 << 6) | byte3);
8967
- } else if ((byte1 & 0xf8) === 0xf0) {
8968
- // 4 bytes
8969
- const byte2 = src[position$1++] & 0x3f;
8970
- const byte3 = src[position$1++] & 0x3f;
8971
- const byte4 = src[position$1++] & 0x3f;
8972
- let unit = ((byte1 & 0x07) << 0x12) | (byte2 << 0x0c) | (byte3 << 0x06) | byte4;
8973
- if (unit > 0xffff) {
8974
- unit -= 0x10000;
8975
- units.push(((unit >>> 10) & 0x3ff) | 0xd800);
8976
- unit = 0xdc00 | (unit & 0x3ff);
8977
- }
8978
- units.push(unit);
8979
- } else {
8980
- units.push(byte1);
8981
- }
8712
+ var addressError = {};
8982
8713
 
8983
- if (units.length >= 0x1000) {
8984
- result += fromCharCode.apply(String, units);
8985
- units.length = 0;
8986
- }
8987
- }
8714
+ Object.defineProperty(addressError, "__esModule", { value: true });
8715
+ addressError.AddressError = void 0;
8716
+ class AddressError extends Error {
8717
+ constructor(message, parseMessage) {
8718
+ super(message);
8719
+ this.name = 'AddressError';
8720
+ this.parseMessage = parseMessage;
8721
+ }
8722
+ }
8723
+ addressError.AddressError = AddressError;
8724
+
8725
+ /* eslint-disable no-param-reassign */
8726
+ var __createBinding$2 = (commonjsGlobal && commonjsGlobal.__createBinding) || (Object.create ? (function(o, m, k, k2) {
8727
+ if (k2 === undefined) k2 = k;
8728
+ var desc = Object.getOwnPropertyDescriptor(m, k);
8729
+ if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
8730
+ desc = { enumerable: true, get: function() { return m[k]; } };
8731
+ }
8732
+ Object.defineProperty(o, k2, desc);
8733
+ }) : (function(o, m, k, k2) {
8734
+ if (k2 === undefined) k2 = k;
8735
+ o[k2] = m[k];
8736
+ }));
8737
+ var __setModuleDefault$2 = (commonjsGlobal && commonjsGlobal.__setModuleDefault) || (Object.create ? (function(o, v) {
8738
+ Object.defineProperty(o, "default", { enumerable: true, value: v });
8739
+ }) : function(o, v) {
8740
+ o["default"] = v;
8741
+ });
8742
+ var __importStar$2 = (commonjsGlobal && commonjsGlobal.__importStar) || function (mod) {
8743
+ if (mod && mod.__esModule) return mod;
8744
+ var result = {};
8745
+ if (mod != null) for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding$2(result, mod, k);
8746
+ __setModuleDefault$2(result, mod);
8747
+ return result;
8748
+ };
8749
+ Object.defineProperty(ipv4, "__esModule", { value: true });
8750
+ ipv4.Address4 = void 0;
8751
+ const common$1 = __importStar$2(common$2);
8752
+ const constants$1 = __importStar$2(constants$2);
8753
+ const address_error_1$1 = addressError;
8754
+ /**
8755
+ * Represents an IPv4 address
8756
+ * @class Address4
8757
+ * @param {string} address - An IPv4 address string
8758
+ */
8759
+ class Address4 {
8760
+ constructor(address) {
8761
+ this.groups = constants$1.GROUPS;
8762
+ this.parsedAddress = [];
8763
+ this.parsedSubnet = '';
8764
+ this.subnet = '/32';
8765
+ this.subnetMask = 32;
8766
+ this.v4 = true;
8767
+ /**
8768
+ * Returns true if the address is correct, false otherwise
8769
+ * @memberof Address4
8770
+ * @instance
8771
+ * @returns {Boolean}
8772
+ */
8773
+ this.isCorrect = common$1.isCorrect(constants$1.BITS);
8774
+ /**
8775
+ * Returns true if the given address is in the subnet of the current address
8776
+ * @memberof Address4
8777
+ * @instance
8778
+ * @returns {boolean}
8779
+ */
8780
+ this.isInSubnet = common$1.isInSubnet;
8781
+ this.address = address;
8782
+ const subnet = constants$1.RE_SUBNET_STRING.exec(address);
8783
+ if (subnet) {
8784
+ this.parsedSubnet = subnet[0].replace('/', '');
8785
+ this.subnetMask = parseInt(this.parsedSubnet, 10);
8786
+ this.subnet = `/${this.subnetMask}`;
8787
+ if (this.subnetMask < 0 || this.subnetMask > constants$1.BITS) {
8788
+ throw new address_error_1$1.AddressError('Invalid subnet mask.');
8789
+ }
8790
+ address = address.replace(constants$1.RE_SUBNET_STRING, '');
8791
+ }
8792
+ this.addressMinusSuffix = address;
8793
+ this.parsedAddress = this.parse(address);
8794
+ }
8795
+ static isValid(address) {
8796
+ try {
8797
+ // eslint-disable-next-line no-new
8798
+ new Address4(address);
8799
+ return true;
8800
+ }
8801
+ catch (e) {
8802
+ return false;
8803
+ }
8804
+ }
8805
+ /*
8806
+ * Parses a v4 address
8807
+ */
8808
+ parse(address) {
8809
+ const groups = address.split('.');
8810
+ if (!address.match(constants$1.RE_ADDRESS)) {
8811
+ throw new address_error_1$1.AddressError('Invalid IPv4 address.');
8812
+ }
8813
+ return groups;
8814
+ }
8815
+ /**
8816
+ * Returns the correct form of an address
8817
+ * @memberof Address4
8818
+ * @instance
8819
+ * @returns {String}
8820
+ */
8821
+ correctForm() {
8822
+ return this.parsedAddress.map((part) => parseInt(part, 10)).join('.');
8823
+ }
8824
+ /**
8825
+ * Converts a hex string to an IPv4 address object
8826
+ * @memberof Address4
8827
+ * @static
8828
+ * @param {string} hex - a hex string to convert
8829
+ * @returns {Address4}
8830
+ */
8831
+ static fromHex(hex) {
8832
+ const padded = hex.replace(/:/g, '').padStart(8, '0');
8833
+ const groups = [];
8834
+ let i;
8835
+ for (i = 0; i < 8; i += 2) {
8836
+ const h = padded.slice(i, i + 2);
8837
+ groups.push(parseInt(h, 16));
8838
+ }
8839
+ return new Address4(groups.join('.'));
8840
+ }
8841
+ /**
8842
+ * Converts an integer into a IPv4 address object
8843
+ * @memberof Address4
8844
+ * @static
8845
+ * @param {integer} integer - a number to convert
8846
+ * @returns {Address4}
8847
+ */
8848
+ static fromInteger(integer) {
8849
+ return Address4.fromHex(integer.toString(16));
8850
+ }
8851
+ /**
8852
+ * Return an address from in-addr.arpa form
8853
+ * @memberof Address4
8854
+ * @static
8855
+ * @param {string} arpaFormAddress - an 'in-addr.arpa' form ipv4 address
8856
+ * @returns {Adress4}
8857
+ * @example
8858
+ * var address = Address4.fromArpa(42.2.0.192.in-addr.arpa.)
8859
+ * address.correctForm(); // '192.0.2.42'
8860
+ */
8861
+ static fromArpa(arpaFormAddress) {
8862
+ // remove ending ".in-addr.arpa." or just "."
8863
+ const leader = arpaFormAddress.replace(/(\.in-addr\.arpa)?\.$/, '');
8864
+ const address = leader.split('.').reverse().join('.');
8865
+ return new Address4(address);
8866
+ }
8867
+ /**
8868
+ * Converts an IPv4 address object to a hex string
8869
+ * @memberof Address4
8870
+ * @instance
8871
+ * @returns {String}
8872
+ */
8873
+ toHex() {
8874
+ return this.parsedAddress.map((part) => common$1.stringToPaddedHex(part)).join(':');
8875
+ }
8876
+ /**
8877
+ * Converts an IPv4 address object to an array of bytes
8878
+ * @memberof Address4
8879
+ * @instance
8880
+ * @returns {Array}
8881
+ */
8882
+ toArray() {
8883
+ return this.parsedAddress.map((part) => parseInt(part, 10));
8884
+ }
8885
+ /**
8886
+ * Converts an IPv4 address object to an IPv6 address group
8887
+ * @memberof Address4
8888
+ * @instance
8889
+ * @returns {String}
8890
+ */
8891
+ toGroup6() {
8892
+ const output = [];
8893
+ let i;
8894
+ for (i = 0; i < constants$1.GROUPS; i += 2) {
8895
+ output.push(`${common$1.stringToPaddedHex(this.parsedAddress[i])}${common$1.stringToPaddedHex(this.parsedAddress[i + 1])}`);
8896
+ }
8897
+ return output.join(':');
8898
+ }
8899
+ /**
8900
+ * Returns the address as a `bigint`
8901
+ * @memberof Address4
8902
+ * @instance
8903
+ * @returns {bigint}
8904
+ */
8905
+ bigInt() {
8906
+ return BigInt(`0x${this.parsedAddress.map((n) => common$1.stringToPaddedHex(n)).join('')}`);
8907
+ }
8908
+ /**
8909
+ * Helper function getting start address.
8910
+ * @memberof Address4
8911
+ * @instance
8912
+ * @returns {bigint}
8913
+ */
8914
+ _startAddress() {
8915
+ return BigInt(`0b${this.mask() + '0'.repeat(constants$1.BITS - this.subnetMask)}`);
8916
+ }
8917
+ /**
8918
+ * The first address in the range given by this address' subnet.
8919
+ * Often referred to as the Network Address.
8920
+ * @memberof Address4
8921
+ * @instance
8922
+ * @returns {Address4}
8923
+ */
8924
+ startAddress() {
8925
+ return Address4.fromBigInt(this._startAddress());
8926
+ }
8927
+ /**
8928
+ * The first host address in the range given by this address's subnet ie
8929
+ * the first address after the Network Address
8930
+ * @memberof Address4
8931
+ * @instance
8932
+ * @returns {Address4}
8933
+ */
8934
+ startAddressExclusive() {
8935
+ const adjust = BigInt('1');
8936
+ return Address4.fromBigInt(this._startAddress() + adjust);
8937
+ }
8938
+ /**
8939
+ * Helper function getting end address.
8940
+ * @memberof Address4
8941
+ * @instance
8942
+ * @returns {bigint}
8943
+ */
8944
+ _endAddress() {
8945
+ return BigInt(`0b${this.mask() + '1'.repeat(constants$1.BITS - this.subnetMask)}`);
8946
+ }
8947
+ /**
8948
+ * The last address in the range given by this address' subnet
8949
+ * Often referred to as the Broadcast
8950
+ * @memberof Address4
8951
+ * @instance
8952
+ * @returns {Address4}
8953
+ */
8954
+ endAddress() {
8955
+ return Address4.fromBigInt(this._endAddress());
8956
+ }
8957
+ /**
8958
+ * The last host address in the range given by this address's subnet ie
8959
+ * the last address prior to the Broadcast Address
8960
+ * @memberof Address4
8961
+ * @instance
8962
+ * @returns {Address4}
8963
+ */
8964
+ endAddressExclusive() {
8965
+ const adjust = BigInt('1');
8966
+ return Address4.fromBigInt(this._endAddress() - adjust);
8967
+ }
8968
+ /**
8969
+ * Converts a BigInt to a v4 address object
8970
+ * @memberof Address4
8971
+ * @static
8972
+ * @param {bigint} bigInt - a BigInt to convert
8973
+ * @returns {Address4}
8974
+ */
8975
+ static fromBigInt(bigInt) {
8976
+ return Address4.fromHex(bigInt.toString(16));
8977
+ }
8978
+ /**
8979
+ * Returns the first n bits of the address, defaulting to the
8980
+ * subnet mask
8981
+ * @memberof Address4
8982
+ * @instance
8983
+ * @returns {String}
8984
+ */
8985
+ mask(mask) {
8986
+ if (mask === undefined) {
8987
+ mask = this.subnetMask;
8988
+ }
8989
+ return this.getBitsBase2(0, mask);
8990
+ }
8991
+ /**
8992
+ * Returns the bits in the given range as a base-2 string
8993
+ * @memberof Address4
8994
+ * @instance
8995
+ * @returns {string}
8996
+ */
8997
+ getBitsBase2(start, end) {
8998
+ return this.binaryZeroPad().slice(start, end);
8999
+ }
9000
+ /**
9001
+ * Return the reversed ip6.arpa form of the address
9002
+ * @memberof Address4
9003
+ * @param {Object} options
9004
+ * @param {boolean} options.omitSuffix - omit the "in-addr.arpa" suffix
9005
+ * @instance
9006
+ * @returns {String}
9007
+ */
9008
+ reverseForm(options) {
9009
+ if (!options) {
9010
+ options = {};
9011
+ }
9012
+ const reversed = this.correctForm().split('.').reverse().join('.');
9013
+ if (options.omitSuffix) {
9014
+ return reversed;
9015
+ }
9016
+ return `${reversed}.in-addr.arpa.`;
9017
+ }
9018
+ /**
9019
+ * Returns true if the given address is a multicast address
9020
+ * @memberof Address4
9021
+ * @instance
9022
+ * @returns {boolean}
9023
+ */
9024
+ isMulticast() {
9025
+ return this.isInSubnet(new Address4('224.0.0.0/4'));
9026
+ }
9027
+ /**
9028
+ * Returns a zero-padded base-2 string representation of the address
9029
+ * @memberof Address4
9030
+ * @instance
9031
+ * @returns {string}
9032
+ */
9033
+ binaryZeroPad() {
9034
+ return this.bigInt().toString(2).padStart(constants$1.BITS, '0');
9035
+ }
9036
+ /**
9037
+ * Groups an IPv4 address for inclusion at the end of an IPv6 address
9038
+ * @returns {String}
9039
+ */
9040
+ groupForV6() {
9041
+ const segments = this.parsedAddress;
9042
+ return this.address.replace(constants$1.RE_ADDRESS, `<span class="hover-group group-v4 group-6">${segments
9043
+ .slice(0, 2)
9044
+ .join('.')}</span>.<span class="hover-group group-v4 group-7">${segments
9045
+ .slice(2, 4)
9046
+ .join('.')}</span>`);
9047
+ }
9048
+ }
9049
+ ipv4.Address4 = Address4;
8988
9050
 
8989
- if (units.length > 0) {
8990
- result += fromCharCode.apply(String, units);
8991
- }
9051
+ var ipv6 = {};
8992
9052
 
8993
- return result
8994
- }
9053
+ var constants = {};
8995
9054
 
8996
- function readArray(length) {
8997
- let array = new Array(length);
8998
- for (let i = 0; i < length; i++) {
8999
- array[i] = read();
9000
- }
9001
- if (currentUnpackr.freezeData)
9002
- return Object.freeze(array)
9003
- return array
9055
+ Object.defineProperty(constants, "__esModule", { value: true });
9056
+ constants.RE_URL_WITH_PORT = constants.RE_URL = constants.RE_ZONE_STRING = constants.RE_SUBNET_STRING = constants.RE_BAD_ADDRESS = constants.RE_BAD_CHARACTERS = constants.TYPES = constants.SCOPES = constants.GROUPS = constants.BITS = void 0;
9057
+ constants.BITS = 128;
9058
+ constants.GROUPS = 8;
9059
+ /**
9060
+ * Represents IPv6 address scopes
9061
+ * @memberof Address6
9062
+ * @static
9063
+ */
9064
+ constants.SCOPES = {
9065
+ 0: 'Reserved',
9066
+ 1: 'Interface local',
9067
+ 2: 'Link local',
9068
+ 4: 'Admin local',
9069
+ 5: 'Site local',
9070
+ 8: 'Organization local',
9071
+ 14: 'Global',
9072
+ 15: 'Reserved',
9073
+ };
9074
+ /**
9075
+ * Represents IPv6 address types
9076
+ * @memberof Address6
9077
+ * @static
9078
+ */
9079
+ constants.TYPES = {
9080
+ 'ff01::1/128': 'Multicast (All nodes on this interface)',
9081
+ 'ff01::2/128': 'Multicast (All routers on this interface)',
9082
+ 'ff02::1/128': 'Multicast (All nodes on this link)',
9083
+ 'ff02::2/128': 'Multicast (All routers on this link)',
9084
+ 'ff05::2/128': 'Multicast (All routers in this site)',
9085
+ 'ff02::5/128': 'Multicast (OSPFv3 AllSPF routers)',
9086
+ 'ff02::6/128': 'Multicast (OSPFv3 AllDR routers)',
9087
+ 'ff02::9/128': 'Multicast (RIP routers)',
9088
+ 'ff02::a/128': 'Multicast (EIGRP routers)',
9089
+ 'ff02::d/128': 'Multicast (PIM routers)',
9090
+ 'ff02::16/128': 'Multicast (MLDv2 reports)',
9091
+ 'ff01::fb/128': 'Multicast (mDNSv6)',
9092
+ 'ff02::fb/128': 'Multicast (mDNSv6)',
9093
+ 'ff05::fb/128': 'Multicast (mDNSv6)',
9094
+ 'ff02::1:2/128': 'Multicast (All DHCP servers and relay agents on this link)',
9095
+ 'ff05::1:2/128': 'Multicast (All DHCP servers and relay agents in this site)',
9096
+ 'ff02::1:3/128': 'Multicast (All DHCP servers on this link)',
9097
+ 'ff05::1:3/128': 'Multicast (All DHCP servers in this site)',
9098
+ '::/128': 'Unspecified',
9099
+ '::1/128': 'Loopback',
9100
+ 'ff00::/8': 'Multicast',
9101
+ 'fe80::/10': 'Link-local unicast',
9102
+ };
9103
+ /**
9104
+ * A regular expression that matches bad characters in an IPv6 address
9105
+ * @memberof Address6
9106
+ * @static
9107
+ */
9108
+ constants.RE_BAD_CHARACTERS = /([^0-9a-f:/%])/gi;
9109
+ /**
9110
+ * A regular expression that matches an incorrect IPv6 address
9111
+ * @memberof Address6
9112
+ * @static
9113
+ */
9114
+ constants.RE_BAD_ADDRESS = /([0-9a-f]{5,}|:{3,}|[^:]:$|^:[^:]|\/$)/gi;
9115
+ /**
9116
+ * A regular expression that matches an IPv6 subnet
9117
+ * @memberof Address6
9118
+ * @static
9119
+ */
9120
+ constants.RE_SUBNET_STRING = /\/\d{1,3}(?=%|$)/;
9121
+ /**
9122
+ * A regular expression that matches an IPv6 zone
9123
+ * @memberof Address6
9124
+ * @static
9125
+ */
9126
+ constants.RE_ZONE_STRING = /%.*$/;
9127
+ constants.RE_URL = /^\[{0,1}([0-9a-f:]+)\]{0,1}/;
9128
+ constants.RE_URL_WITH_PORT = /\[([0-9a-f:]+)\]:([0-9]{1,5})/;
9129
+
9130
+ var helpers$1 = {};
9131
+
9132
+ Object.defineProperty(helpers$1, "__esModule", { value: true });
9133
+ helpers$1.spanAllZeroes = spanAllZeroes;
9134
+ helpers$1.spanAll = spanAll;
9135
+ helpers$1.spanLeadingZeroes = spanLeadingZeroes;
9136
+ helpers$1.simpleGroup = simpleGroup;
9137
+ /**
9138
+ * @returns {String} the string with all zeroes contained in a <span>
9139
+ */
9140
+ function spanAllZeroes(s) {
9141
+ return s.replace(/(0+)/g, '<span class="zero">$1</span>');
9004
9142
  }
9005
-
9006
- function readMap(length) {
9007
- if (currentUnpackr.mapsAsObjects) {
9008
- let object = {};
9009
- for (let i = 0; i < length; i++) {
9010
- let key = readKey();
9011
- if (key === '__proto__')
9012
- key = '__proto_';
9013
- object[key] = read();
9014
- }
9015
- return object
9016
- } else {
9017
- let map = new Map();
9018
- for (let i = 0; i < length; i++) {
9019
- map.set(read(), read());
9020
- }
9021
- return map
9022
- }
9143
+ /**
9144
+ * @returns {String} the string with each character contained in a <span>
9145
+ */
9146
+ function spanAll(s, offset = 0) {
9147
+ const letters = s.split('');
9148
+ return letters
9149
+ .map((n, i) => `<span class="digit value-${n} position-${i + offset}">${spanAllZeroes(n)}</span>`)
9150
+ .join('');
9023
9151
  }
9024
-
9025
- var fromCharCode = String.fromCharCode;
9026
- function longStringInJS(length) {
9027
- let start = position$1;
9028
- let bytes = new Array(length);
9029
- for (let i = 0; i < length; i++) {
9030
- const byte = src[position$1++];
9031
- if ((byte & 0x80) > 0) {
9032
- position$1 = start;
9033
- return
9034
- }
9035
- bytes[i] = byte;
9036
- }
9037
- return fromCharCode.apply(String, bytes)
9152
+ function spanLeadingZeroesSimple(group) {
9153
+ return group.replace(/^(0+)/, '<span class="zero">$1</span>');
9038
9154
  }
9039
- function shortStringInJS(length) {
9040
- if (length < 4) {
9041
- if (length < 2) {
9042
- if (length === 0)
9043
- return ''
9044
- else {
9045
- let a = src[position$1++];
9046
- if ((a & 0x80) > 1) {
9047
- position$1 -= 1;
9048
- return
9049
- }
9050
- return fromCharCode(a)
9051
- }
9052
- } else {
9053
- let a = src[position$1++];
9054
- let b = src[position$1++];
9055
- if ((a & 0x80) > 0 || (b & 0x80) > 0) {
9056
- position$1 -= 2;
9057
- return
9058
- }
9059
- if (length < 3)
9060
- return fromCharCode(a, b)
9061
- let c = src[position$1++];
9062
- if ((c & 0x80) > 0) {
9063
- position$1 -= 3;
9064
- return
9065
- }
9066
- return fromCharCode(a, b, c)
9067
- }
9068
- } else {
9069
- let a = src[position$1++];
9070
- let b = src[position$1++];
9071
- let c = src[position$1++];
9072
- let d = src[position$1++];
9073
- if ((a & 0x80) > 0 || (b & 0x80) > 0 || (c & 0x80) > 0 || (d & 0x80) > 0) {
9074
- position$1 -= 4;
9075
- return
9076
- }
9077
- if (length < 6) {
9078
- if (length === 4)
9079
- return fromCharCode(a, b, c, d)
9080
- else {
9081
- let e = src[position$1++];
9082
- if ((e & 0x80) > 0) {
9083
- position$1 -= 5;
9084
- return
9085
- }
9086
- return fromCharCode(a, b, c, d, e)
9087
- }
9088
- } else if (length < 8) {
9089
- let e = src[position$1++];
9090
- let f = src[position$1++];
9091
- if ((e & 0x80) > 0 || (f & 0x80) > 0) {
9092
- position$1 -= 6;
9093
- return
9094
- }
9095
- if (length < 7)
9096
- return fromCharCode(a, b, c, d, e, f)
9097
- let g = src[position$1++];
9098
- if ((g & 0x80) > 0) {
9099
- position$1 -= 7;
9100
- return
9101
- }
9102
- return fromCharCode(a, b, c, d, e, f, g)
9103
- } else {
9104
- let e = src[position$1++];
9105
- let f = src[position$1++];
9106
- let g = src[position$1++];
9107
- let h = src[position$1++];
9108
- if ((e & 0x80) > 0 || (f & 0x80) > 0 || (g & 0x80) > 0 || (h & 0x80) > 0) {
9109
- position$1 -= 8;
9110
- return
9111
- }
9112
- if (length < 10) {
9113
- if (length === 8)
9114
- return fromCharCode(a, b, c, d, e, f, g, h)
9115
- else {
9116
- let i = src[position$1++];
9117
- if ((i & 0x80) > 0) {
9118
- position$1 -= 9;
9119
- return
9120
- }
9121
- return fromCharCode(a, b, c, d, e, f, g, h, i)
9122
- }
9123
- } else if (length < 12) {
9124
- let i = src[position$1++];
9125
- let j = src[position$1++];
9126
- if ((i & 0x80) > 0 || (j & 0x80) > 0) {
9127
- position$1 -= 10;
9128
- return
9129
- }
9130
- if (length < 11)
9131
- return fromCharCode(a, b, c, d, e, f, g, h, i, j)
9132
- let k = src[position$1++];
9133
- if ((k & 0x80) > 0) {
9134
- position$1 -= 11;
9135
- return
9136
- }
9137
- return fromCharCode(a, b, c, d, e, f, g, h, i, j, k)
9138
- } else {
9139
- let i = src[position$1++];
9140
- let j = src[position$1++];
9141
- let k = src[position$1++];
9142
- let l = src[position$1++];
9143
- if ((i & 0x80) > 0 || (j & 0x80) > 0 || (k & 0x80) > 0 || (l & 0x80) > 0) {
9144
- position$1 -= 12;
9145
- return
9146
- }
9147
- if (length < 14) {
9148
- if (length === 12)
9149
- return fromCharCode(a, b, c, d, e, f, g, h, i, j, k, l)
9150
- else {
9151
- let m = src[position$1++];
9152
- if ((m & 0x80) > 0) {
9153
- position$1 -= 13;
9154
- return
9155
- }
9156
- return fromCharCode(a, b, c, d, e, f, g, h, i, j, k, l, m)
9157
- }
9158
- } else {
9159
- let m = src[position$1++];
9160
- let n = src[position$1++];
9161
- if ((m & 0x80) > 0 || (n & 0x80) > 0) {
9162
- position$1 -= 14;
9163
- return
9164
- }
9165
- if (length < 15)
9166
- return fromCharCode(a, b, c, d, e, f, g, h, i, j, k, l, m, n)
9167
- let o = src[position$1++];
9168
- if ((o & 0x80) > 0) {
9169
- position$1 -= 15;
9170
- return
9171
- }
9172
- return fromCharCode(a, b, c, d, e, f, g, h, i, j, k, l, m, n, o)
9173
- }
9174
- }
9175
- }
9176
- }
9155
+ /**
9156
+ * @returns {String} the string with leading zeroes contained in a <span>
9157
+ */
9158
+ function spanLeadingZeroes(address) {
9159
+ const groups = address.split(':');
9160
+ return groups.map((g) => spanLeadingZeroesSimple(g)).join(':');
9177
9161
  }
9178
-
9179
- function readOnlyJSString() {
9180
- let token = src[position$1++];
9181
- let length;
9182
- if (token < 0xc0) {
9183
- // fixstr
9184
- length = token - 0xa0;
9185
- } else {
9186
- switch(token) {
9187
- case 0xd9:
9188
- // str 8
9189
- length = src[position$1++];
9190
- break
9191
- case 0xda:
9192
- // str 16
9193
- length = dataView.getUint16(position$1);
9194
- position$1 += 2;
9195
- break
9196
- case 0xdb:
9197
- // str 32
9198
- length = dataView.getUint32(position$1);
9199
- position$1 += 4;
9200
- break
9201
- default:
9202
- throw new Error('Expected string')
9203
- }
9204
- }
9205
- return readStringJS(length)
9162
+ /**
9163
+ * Groups an address
9164
+ * @returns {String} a grouped address
9165
+ */
9166
+ function simpleGroup(addressString, offset = 0) {
9167
+ const groups = addressString.split(':');
9168
+ return groups.map((g, i) => {
9169
+ if (/group-v4/.test(g)) {
9170
+ return g;
9171
+ }
9172
+ return `<span class="hover-group group-${i + offset}">${spanLeadingZeroesSimple(g)}</span>`;
9173
+ });
9206
9174
  }
9207
9175
 
9176
+ var regularExpressions = {};
9208
9177
 
9209
- function readBin(length) {
9210
- return currentUnpackr.copyBuffers ?
9211
- // specifically use the copying slice (not the node one)
9212
- Uint8Array.prototype.slice.call(src, position$1, position$1 += length) :
9213
- src.subarray(position$1, position$1 += length)
9178
+ var __createBinding$1 = (commonjsGlobal && commonjsGlobal.__createBinding) || (Object.create ? (function(o, m, k, k2) {
9179
+ if (k2 === undefined) k2 = k;
9180
+ var desc = Object.getOwnPropertyDescriptor(m, k);
9181
+ if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
9182
+ desc = { enumerable: true, get: function() { return m[k]; } };
9183
+ }
9184
+ Object.defineProperty(o, k2, desc);
9185
+ }) : (function(o, m, k, k2) {
9186
+ if (k2 === undefined) k2 = k;
9187
+ o[k2] = m[k];
9188
+ }));
9189
+ var __setModuleDefault$1 = (commonjsGlobal && commonjsGlobal.__setModuleDefault) || (Object.create ? (function(o, v) {
9190
+ Object.defineProperty(o, "default", { enumerable: true, value: v });
9191
+ }) : function(o, v) {
9192
+ o["default"] = v;
9193
+ });
9194
+ var __importStar$1 = (commonjsGlobal && commonjsGlobal.__importStar) || function (mod) {
9195
+ if (mod && mod.__esModule) return mod;
9196
+ var result = {};
9197
+ if (mod != null) for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding$1(result, mod, k);
9198
+ __setModuleDefault$1(result, mod);
9199
+ return result;
9200
+ };
9201
+ Object.defineProperty(regularExpressions, "__esModule", { value: true });
9202
+ regularExpressions.ADDRESS_BOUNDARY = void 0;
9203
+ regularExpressions.groupPossibilities = groupPossibilities;
9204
+ regularExpressions.padGroup = padGroup;
9205
+ regularExpressions.simpleRegularExpression = simpleRegularExpression;
9206
+ regularExpressions.possibleElisions = possibleElisions;
9207
+ const v6 = __importStar$1(constants);
9208
+ function groupPossibilities(possibilities) {
9209
+ return `(${possibilities.join('|')})`;
9214
9210
  }
9215
- function readExt(length) {
9216
- let type = src[position$1++];
9217
- if (currentExtensions[type]) {
9218
- let end;
9219
- return currentExtensions[type](src.subarray(position$1, end = (position$1 += length)), (readPosition) => {
9220
- position$1 = readPosition;
9221
- try {
9222
- return read();
9223
- } finally {
9224
- position$1 = end;
9225
- }
9226
- })
9227
- }
9228
- else
9229
- throw new Error('Unknown extension type ' + type)
9211
+ function padGroup(group) {
9212
+ if (group.length < 4) {
9213
+ return `0{0,${4 - group.length}}${group}`;
9214
+ }
9215
+ return group;
9230
9216
  }
9231
-
9232
- var keyCache = new Array(4096);
9233
- function readKey() {
9234
- let length = src[position$1++];
9235
- if (length >= 0xa0 && length < 0xc0) {
9236
- // fixstr, potentially use key cache
9237
- length = length - 0xa0;
9238
- if (srcStringEnd >= position$1) // if it has been extracted, must use it (and faster anyway)
9239
- return srcString.slice(position$1 - srcStringStart, (position$1 += length) - srcStringStart)
9240
- else if (!(srcStringEnd == 0 && srcEnd < 180))
9241
- return readFixedString(length)
9242
- } else { // not cacheable, go back and do a standard read
9243
- position$1--;
9244
- return asSafeString(read())
9245
- }
9246
- let key = ((length << 5) ^ (length > 1 ? dataView.getUint16(position$1) : length > 0 ? src[position$1] : 0)) & 0xfff;
9247
- let entry = keyCache[key];
9248
- let checkPosition = position$1;
9249
- let end = position$1 + length - 3;
9250
- let chunk;
9251
- let i = 0;
9252
- if (entry && entry.bytes == length) {
9253
- while (checkPosition < end) {
9254
- chunk = dataView.getUint32(checkPosition);
9255
- if (chunk != entry[i++]) {
9256
- checkPosition = 0x70000000;
9257
- break
9258
- }
9259
- checkPosition += 4;
9260
- }
9261
- end += 3;
9262
- while (checkPosition < end) {
9263
- chunk = src[checkPosition++];
9264
- if (chunk != entry[i++]) {
9265
- checkPosition = 0x70000000;
9266
- break
9267
- }
9268
- }
9269
- if (checkPosition === end) {
9270
- position$1 = checkPosition;
9271
- return entry.string
9272
- }
9273
- end -= 3;
9274
- checkPosition = position$1;
9275
- }
9276
- entry = [];
9277
- keyCache[key] = entry;
9278
- entry.bytes = length;
9279
- while (checkPosition < end) {
9280
- chunk = dataView.getUint32(checkPosition);
9281
- entry.push(chunk);
9282
- checkPosition += 4;
9283
- }
9284
- end += 3;
9285
- while (checkPosition < end) {
9286
- chunk = src[checkPosition++];
9287
- entry.push(chunk);
9288
- }
9289
- // for small blocks, avoiding the overhead of the extract call is helpful
9290
- let string = length < 16 ? shortStringInJS(length) : longStringInJS(length);
9291
- if (string != null)
9292
- return entry.string = string
9293
- return entry.string = readFixedString(length)
9217
+ regularExpressions.ADDRESS_BOUNDARY = '[^A-Fa-f0-9:]';
9218
+ function simpleRegularExpression(groups) {
9219
+ const zeroIndexes = [];
9220
+ groups.forEach((group, i) => {
9221
+ const groupInteger = parseInt(group, 16);
9222
+ if (groupInteger === 0) {
9223
+ zeroIndexes.push(i);
9224
+ }
9225
+ });
9226
+ // You can technically elide a single 0, this creates the regular expressions
9227
+ // to match that eventuality
9228
+ const possibilities = zeroIndexes.map((zeroIndex) => groups
9229
+ .map((group, i) => {
9230
+ if (i === zeroIndex) {
9231
+ const elision = i === 0 || i === v6.GROUPS - 1 ? ':' : '';
9232
+ return groupPossibilities([padGroup(group), elision]);
9233
+ }
9234
+ return padGroup(group);
9235
+ })
9236
+ .join(':'));
9237
+ // The simplest case
9238
+ possibilities.push(groups.map(padGroup).join(':'));
9239
+ return groupPossibilities(possibilities);
9294
9240
  }
9295
-
9296
- function asSafeString(property) {
9297
- // protect against expensive (DoS) string conversions
9298
- if (typeof property === 'string') return property;
9299
- if (typeof property === 'number' || typeof property === 'boolean' || typeof property === 'bigint') return property.toString();
9300
- if (property == null) return property + '';
9301
- throw new Error('Invalid property type for record', typeof property);
9241
+ function possibleElisions(elidedGroups, moreLeft, moreRight) {
9242
+ const left = moreLeft ? '' : ':';
9243
+ const right = moreRight ? '' : ':';
9244
+ const possibilities = [];
9245
+ // 1. elision of everything (::)
9246
+ if (!moreLeft && !moreRight) {
9247
+ possibilities.push('::');
9248
+ }
9249
+ // 2. complete elision of the middle
9250
+ if (moreLeft && moreRight) {
9251
+ possibilities.push('');
9252
+ }
9253
+ if ((moreRight && !moreLeft) || (!moreRight && moreLeft)) {
9254
+ // 3. complete elision of one side
9255
+ possibilities.push(':');
9256
+ }
9257
+ // 4. elision from the left side
9258
+ possibilities.push(`${left}(:0{1,4}){1,${elidedGroups - 1}}`);
9259
+ // 5. elision from the right side
9260
+ possibilities.push(`(0{1,4}:){1,${elidedGroups - 1}}${right}`);
9261
+ // 6. no elision
9262
+ possibilities.push(`(0{1,4}:){${elidedGroups - 1}}0{1,4}`);
9263
+ // 7. elision (including sloppy elision) from the middle
9264
+ for (let groups = 1; groups < elidedGroups - 1; groups++) {
9265
+ for (let position = 1; position < elidedGroups - groups; position++) {
9266
+ possibilities.push(`(0{1,4}:){${position}}:(0{1,4}:){${elidedGroups - position - groups - 1}}0{1,4}`);
9267
+ }
9268
+ }
9269
+ return groupPossibilities(possibilities);
9302
9270
  }
9303
- // the registration of the record definition extension (as "r")
9304
- const recordDefinition = (id, highByte) => {
9305
- let structure = read().map(asSafeString); // ensure that all keys are strings and
9306
- // that the array is mutable
9307
- let firstByte = id;
9308
- if (highByte !== undefined) {
9309
- id = id < 32 ? -((highByte << 5) + id) : ((highByte << 5) + id);
9310
- structure.highByte = highByte;
9311
- }
9312
- let existingStructure = currentStructures[id];
9313
- // If it is a shared structure, we need to restore any changes after reading.
9314
- // Also in sequential mode, we may get incomplete reads and thus errors, and we need to restore
9315
- // to the state prior to an incomplete read in order to properly resume.
9316
- if (existingStructure && (existingStructure.isShared || sequentialMode)) {
9317
- (currentStructures.restoreStructures || (currentStructures.restoreStructures = []))[id] = existingStructure;
9318
- }
9319
- currentStructures[id] = structure;
9320
- structure.read = createStructureReader(structure, firstByte);
9321
- return structure.read()
9322
- };
9323
- currentExtensions[0] = () => {}; // notepack defines extension 0 to mean undefined, so use that as the default here
9324
- currentExtensions[0].noBuffer = true;
9325
-
9326
- currentExtensions[0x42] = (data) => {
9327
- // decode bigint
9328
- let length = data.length;
9329
- let value = BigInt(data[0] & 0x80 ? data[0] - 0x100 : data[0]);
9330
- for (let i = 1; i < length; i++) {
9331
- value <<= 8n;
9332
- value += BigInt(data[i]);
9333
- }
9334
- return value;
9335
- };
9336
-
9337
- let errors = { Error, TypeError, ReferenceError };
9338
- currentExtensions[0x65] = () => {
9339
- let data = read();
9340
- return (errors[data[0]] || Error)(data[1], { cause: data[2] })
9341
- };
9342
9271
 
9343
- currentExtensions[0x69] = (data) => {
9344
- // id extension (for structured clones)
9345
- if (currentUnpackr.structuredClone === false) throw new Error('Structured clone extension is disabled')
9346
- let id = dataView.getUint32(position$1 - 4);
9347
- if (!referenceMap)
9348
- referenceMap = new Map();
9349
- let token = src[position$1];
9350
- let target;
9351
- // TODO: handle Maps, Sets, and other types that can cycle; this is complicated, because you potentially need to read
9352
- // ahead past references to record structure definitions
9353
- if (token >= 0x90 && token < 0xa0 || token == 0xdc || token == 0xdd)
9354
- target = [];
9355
- else
9356
- target = {};
9357
-
9358
- let refEntry = { target }; // a placeholder object
9359
- referenceMap.set(id, refEntry);
9360
- let targetProperties = read(); // read the next value as the target object to id
9361
- if (refEntry.used) // there is a cycle, so we have to assign properties to original target
9362
- return Object.assign(target, targetProperties)
9363
- refEntry.target = targetProperties; // the placeholder wasn't used, replace with the deserialized one
9364
- return targetProperties // no cycle, can just use the returned read object
9365
- };
9366
-
9367
- currentExtensions[0x70] = (data) => {
9368
- // pointer extension (for structured clones)
9369
- if (currentUnpackr.structuredClone === false) throw new Error('Structured clone extension is disabled')
9370
- let id = dataView.getUint32(position$1 - 4);
9371
- let refEntry = referenceMap.get(id);
9372
- refEntry.used = true;
9373
- return refEntry.target
9374
- };
9375
-
9376
- currentExtensions[0x73] = () => new Set(read());
9377
-
9378
- const typedArrays = ['Int8','Uint8','Uint8Clamped','Int16','Uint16','Int32','Uint32','Float32','Float64','BigInt64','BigUint64'].map(type => type + 'Array');
9379
-
9380
- let glbl = typeof globalThis === 'object' ? globalThis : window;
9381
- currentExtensions[0x74] = (data) => {
9382
- let typeCode = data[0];
9383
- let typedArrayName = typedArrays[typeCode];
9384
- if (!typedArrayName) {
9385
- if (typeCode === 16) {
9386
- let ab = new ArrayBuffer(data.length - 1);
9387
- let u8 = new Uint8Array(ab);
9388
- u8.set(data.subarray(1));
9389
- return ab;
9390
- }
9391
- throw new Error('Could not find typed array for code ' + typeCode)
9392
- }
9393
- // we have to always slice/copy here to get a new ArrayBuffer that is word/byte aligned
9394
- return new glbl[typedArrayName](Uint8Array.prototype.slice.call(data, 1).buffer)
9395
- };
9396
- currentExtensions[0x78] = () => {
9397
- let data = read();
9398
- return new RegExp(data[0], data[1])
9399
- };
9400
- const TEMP_BUNDLE = [];
9401
- currentExtensions[0x62] = (data) => {
9402
- let dataSize = (data[0] << 24) + (data[1] << 16) + (data[2] << 8) + data[3];
9403
- let dataPosition = position$1;
9404
- position$1 += dataSize - data.length;
9405
- bundledStrings$1 = TEMP_BUNDLE;
9406
- bundledStrings$1 = [readOnlyJSString(), readOnlyJSString()];
9407
- bundledStrings$1.position0 = 0;
9408
- bundledStrings$1.position1 = 0;
9409
- bundledStrings$1.postBundlePosition = position$1;
9410
- position$1 = dataPosition;
9411
- return read()
9272
+ /* eslint-disable prefer-destructuring */
9273
+ /* eslint-disable no-param-reassign */
9274
+ var __createBinding = (commonjsGlobal && commonjsGlobal.__createBinding) || (Object.create ? (function(o, m, k, k2) {
9275
+ if (k2 === undefined) k2 = k;
9276
+ var desc = Object.getOwnPropertyDescriptor(m, k);
9277
+ if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
9278
+ desc = { enumerable: true, get: function() { return m[k]; } };
9279
+ }
9280
+ Object.defineProperty(o, k2, desc);
9281
+ }) : (function(o, m, k, k2) {
9282
+ if (k2 === undefined) k2 = k;
9283
+ o[k2] = m[k];
9284
+ }));
9285
+ var __setModuleDefault = (commonjsGlobal && commonjsGlobal.__setModuleDefault) || (Object.create ? (function(o, v) {
9286
+ Object.defineProperty(o, "default", { enumerable: true, value: v });
9287
+ }) : function(o, v) {
9288
+ o["default"] = v;
9289
+ });
9290
+ var __importStar = (commonjsGlobal && commonjsGlobal.__importStar) || function (mod) {
9291
+ if (mod && mod.__esModule) return mod;
9292
+ var result = {};
9293
+ if (mod != null) for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k);
9294
+ __setModuleDefault(result, mod);
9295
+ return result;
9412
9296
  };
9413
-
9414
- currentExtensions[0xff] = (data) => {
9415
- // 32-bit date extension
9416
- if (data.length == 4)
9417
- return new Date((data[0] * 0x1000000 + (data[1] << 16) + (data[2] << 8) + data[3]) * 1000)
9418
- else if (data.length == 8)
9419
- return new Date(
9420
- ((data[0] << 22) + (data[1] << 14) + (data[2] << 6) + (data[3] >> 2)) / 1000000 +
9421
- ((data[3] & 0x3) * 0x100000000 + data[4] * 0x1000000 + (data[5] << 16) + (data[6] << 8) + data[7]) * 1000)
9422
- else if (data.length == 12)// TODO: Implement support for negative
9423
- return new Date(
9424
- ((data[0] << 24) + (data[1] << 16) + (data[2] << 8) + data[3]) / 1000000 +
9425
- (((data[4] & 0x80) ? -0x1000000000000 : 0) + data[6] * 0x10000000000 + data[7] * 0x100000000 + data[8] * 0x1000000 + (data[9] << 16) + (data[10] << 8) + data[11]) * 1000)
9426
- else
9427
- return new Date('invalid')
9428
- }; // notepack defines extension 0 to mean undefined, so use that as the default here
9429
- // registration of bulk record definition?
9430
- // currentExtensions[0x52] = () =>
9431
-
9432
- function saveState(callback) {
9433
- let savedSrcEnd = srcEnd;
9434
- let savedPosition = position$1;
9435
- let savedSrcStringStart = srcStringStart;
9436
- let savedSrcStringEnd = srcStringEnd;
9437
- let savedSrcString = srcString;
9438
- let savedReferenceMap = referenceMap;
9439
- let savedBundledStrings = bundledStrings$1;
9440
-
9441
- // TODO: We may need to revisit this if we do more external calls to user code (since it could be slow)
9442
- let savedSrc = new Uint8Array(src.slice(0, srcEnd)); // we copy the data in case it changes while external data is processed
9443
- let savedStructures = currentStructures;
9444
- let savedStructuresContents = currentStructures.slice(0, currentStructures.length);
9445
- let savedPackr = currentUnpackr;
9446
- let savedSequentialMode = sequentialMode;
9447
- let value = callback();
9448
- srcEnd = savedSrcEnd;
9449
- position$1 = savedPosition;
9450
- srcStringStart = savedSrcStringStart;
9451
- srcStringEnd = savedSrcStringEnd;
9452
- srcString = savedSrcString;
9453
- referenceMap = savedReferenceMap;
9454
- bundledStrings$1 = savedBundledStrings;
9455
- src = savedSrc;
9456
- sequentialMode = savedSequentialMode;
9457
- currentStructures = savedStructures;
9458
- currentStructures.splice(0, currentStructures.length, ...savedStructuresContents);
9459
- currentUnpackr = savedPackr;
9460
- dataView = new DataView(src.buffer, src.byteOffset, src.byteLength);
9461
- return value
9297
+ Object.defineProperty(ipv6, "__esModule", { value: true });
9298
+ ipv6.Address6 = void 0;
9299
+ const common = __importStar(common$2);
9300
+ const constants4 = __importStar(constants$2);
9301
+ const constants6 = __importStar(constants);
9302
+ const helpers = __importStar(helpers$1);
9303
+ const ipv4_1 = ipv4;
9304
+ const regular_expressions_1 = regularExpressions;
9305
+ const address_error_1 = addressError;
9306
+ const common_1 = common$2;
9307
+ function assert(condition) {
9308
+ if (!condition) {
9309
+ throw new Error('Assertion failed.');
9310
+ }
9462
9311
  }
9463
- function clearSource() {
9464
- src = null;
9465
- referenceMap = null;
9466
- currentStructures = null;
9312
+ function addCommas(number) {
9313
+ const r = /(\d+)(\d{3})/;
9314
+ while (r.test(number)) {
9315
+ number = number.replace(r, '$1,$2');
9316
+ }
9317
+ return number;
9467
9318
  }
9468
-
9469
- const mult10 = new Array(147); // this is a table matching binary exponents to the multiplier to determine significant digit rounding
9470
- for (let i = 0; i < 256; i++) {
9471
- mult10[i] = +('1e' + Math.floor(45.15 - i * 0.30103));
9319
+ function spanLeadingZeroes4(n) {
9320
+ n = n.replace(/^(0{1,})([1-9]+)$/, '<span class="parse-error">$1</span>$2');
9321
+ n = n.replace(/^(0{1,})(0)$/, '<span class="parse-error">$1</span>$2');
9322
+ return n;
9472
9323
  }
9473
- var defaultUnpackr = new Unpackr({ useRecords: false });
9474
- defaultUnpackr.unpack;
9475
- defaultUnpackr.unpackMultiple;
9476
- defaultUnpackr.unpack;
9477
- let f32Array = new Float32Array(1);
9478
- new Uint8Array(f32Array.buffer, 0, 4);
9479
-
9480
- let textEncoder;
9481
- try {
9482
- textEncoder = new TextEncoder();
9483
- } catch (error) {}
9484
- let extensions, extensionClasses;
9485
- const hasNodeBuffer = typeof Buffer !== 'undefined';
9486
- const ByteArrayAllocate = hasNodeBuffer ?
9487
- function(length) { return Buffer.allocUnsafeSlow(length) } : Uint8Array;
9488
- const ByteArray = hasNodeBuffer ? Buffer : Uint8Array;
9489
- const MAX_BUFFER_SIZE = hasNodeBuffer ? 0x100000000 : 0x7fd00000;
9490
- let target, keysTarget;
9491
- let targetView;
9492
- let position = 0;
9493
- let safeEnd;
9494
- let bundledStrings = null;
9495
- let writeStructSlots;
9496
- const MAX_BUNDLE_SIZE = 0x5500; // maximum characters such that the encoded bytes fits in 16 bits.
9497
- const hasNonLatin = /[\u0080-\uFFFF]/;
9498
- const RECORD_SYMBOL = Symbol('record-id');
9499
- class Packr extends Unpackr {
9500
- constructor(options) {
9501
- super(options);
9502
- this.offset = 0;
9503
- let start;
9504
- let hasSharedUpdate;
9505
- let structures;
9506
- let referenceMap;
9507
- let encodeUtf8 = ByteArray.prototype.utf8Write ? function(string, position) {
9508
- return target.utf8Write(string, position, 0xffffffff)
9509
- } : (textEncoder && textEncoder.encodeInto) ?
9510
- function(string, position) {
9511
- return textEncoder.encodeInto(string, target.subarray(position)).written
9512
- } : false;
9513
-
9514
- let packr = this;
9515
- if (!options)
9516
- options = {};
9517
- let isSequential = options && options.sequential;
9518
- let hasSharedStructures = options.structures || options.saveStructures;
9519
- let maxSharedStructures = options.maxSharedStructures;
9520
- if (maxSharedStructures == null)
9521
- maxSharedStructures = hasSharedStructures ? 32 : 0;
9522
- if (maxSharedStructures > 8160)
9523
- throw new Error('Maximum maxSharedStructure is 8160')
9524
- if (options.structuredClone && options.moreTypes == undefined) {
9525
- this.moreTypes = true;
9526
- }
9527
- let maxOwnStructures = options.maxOwnStructures;
9528
- if (maxOwnStructures == null)
9529
- maxOwnStructures = hasSharedStructures ? 32 : 64;
9530
- if (!this.structures && options.useRecords != false)
9531
- this.structures = [];
9532
- // two byte record ids for shared structures
9533
- let useTwoByteRecords = maxSharedStructures > 32 || (maxOwnStructures + maxSharedStructures > 64);
9534
- let sharedLimitId = maxSharedStructures + 0x40;
9535
- let maxStructureId = maxSharedStructures + maxOwnStructures + 0x40;
9536
- if (maxStructureId > 8256) {
9537
- throw new Error('Maximum maxSharedStructure + maxOwnStructure is 8192')
9538
- }
9539
- let recordIdsToRemove = [];
9540
- let transitionsCount = 0;
9541
- let serializationsSinceTransitionRebuild = 0;
9542
-
9543
- this.pack = this.encode = function(value, encodeOptions) {
9544
- if (!target) {
9545
- target = new ByteArrayAllocate(8192);
9546
- targetView = target.dataView || (target.dataView = new DataView(target.buffer, 0, 8192));
9547
- position = 0;
9548
- }
9549
- safeEnd = target.length - 10;
9550
- if (safeEnd - position < 0x800) {
9551
- // don't start too close to the end,
9552
- target = new ByteArrayAllocate(target.length);
9553
- targetView = target.dataView || (target.dataView = new DataView(target.buffer, 0, target.length));
9554
- safeEnd = target.length - 10;
9555
- position = 0;
9556
- } else
9557
- position = (position + 7) & 0x7ffffff8; // Word align to make any future copying of this buffer faster
9558
- start = position;
9559
- if (encodeOptions & RESERVE_START_SPACE) position += (encodeOptions & 0xff);
9560
- referenceMap = packr.structuredClone ? new Map() : null;
9561
- if (packr.bundleStrings && typeof value !== 'string') {
9562
- bundledStrings = [];
9563
- bundledStrings.size = Infinity; // force a new bundle start on first string
9564
- } else
9565
- bundledStrings = null;
9566
- structures = packr.structures;
9567
- if (structures) {
9568
- if (structures.uninitialized)
9569
- structures = packr._mergeStructures(packr.getStructures());
9570
- let sharedLength = structures.sharedLength || 0;
9571
- if (sharedLength > maxSharedStructures) {
9572
- //if (maxSharedStructures <= 32 && structures.sharedLength > 32) // TODO: could support this, but would need to update the limit ids
9573
- throw new Error('Shared structures is larger than maximum shared structures, try increasing maxSharedStructures to ' + structures.sharedLength)
9574
- }
9575
- if (!structures.transitions) {
9576
- // rebuild our structure transitions
9577
- structures.transitions = Object.create(null);
9578
- for (let i = 0; i < sharedLength; i++) {
9579
- let keys = structures[i];
9580
- if (!keys)
9581
- continue
9582
- let nextTransition, transition = structures.transitions;
9583
- for (let j = 0, l = keys.length; j < l; j++) {
9584
- let key = keys[j];
9585
- nextTransition = transition[key];
9586
- if (!nextTransition) {
9587
- nextTransition = transition[key] = Object.create(null);
9588
- }
9589
- transition = nextTransition;
9590
- }
9591
- transition[RECORD_SYMBOL] = i + 0x40;
9592
- }
9593
- this.lastNamedStructuresLength = sharedLength;
9594
- }
9595
- if (!isSequential) {
9596
- structures.nextId = sharedLength + 0x40;
9597
- }
9598
- }
9599
- if (hasSharedUpdate)
9600
- hasSharedUpdate = false;
9601
- let encodingError;
9602
- try {
9603
- if (packr.randomAccessStructure && value && value.constructor && value.constructor === Object)
9604
- writeStruct(value);
9605
- else
9606
- pack(value);
9607
- let lastBundle = bundledStrings;
9608
- if (bundledStrings)
9609
- writeBundles(start, pack, 0);
9610
- if (referenceMap && referenceMap.idsToInsert) {
9611
- let idsToInsert = referenceMap.idsToInsert.sort((a, b) => a.offset > b.offset ? 1 : -1);
9612
- let i = idsToInsert.length;
9613
- let incrementPosition = -1;
9614
- while (lastBundle && i > 0) {
9615
- let insertionPoint = idsToInsert[--i].offset + start;
9616
- if (insertionPoint < (lastBundle.stringsPosition + start) && incrementPosition === -1)
9617
- incrementPosition = 0;
9618
- if (insertionPoint > (lastBundle.position + start)) {
9619
- if (incrementPosition >= 0)
9620
- incrementPosition += 6;
9621
- } else {
9622
- if (incrementPosition >= 0) {
9623
- // update the bundle reference now
9624
- targetView.setUint32(lastBundle.position + start,
9625
- targetView.getUint32(lastBundle.position + start) + incrementPosition);
9626
- incrementPosition = -1; // reset
9627
- }
9628
- lastBundle = lastBundle.previous;
9629
- i++;
9630
- }
9631
- }
9632
- if (incrementPosition >= 0 && lastBundle) {
9633
- // update the bundle reference now
9634
- targetView.setUint32(lastBundle.position + start,
9635
- targetView.getUint32(lastBundle.position + start) + incrementPosition);
9636
- }
9637
- position += idsToInsert.length * 6;
9638
- if (position > safeEnd)
9639
- makeRoom(position);
9640
- packr.offset = position;
9641
- let serialized = insertIds(target.subarray(start, position), idsToInsert);
9642
- referenceMap = null;
9643
- return serialized
9644
- }
9645
- packr.offset = position; // update the offset so next serialization doesn't write over our buffer, but can continue writing to same buffer sequentially
9646
- if (encodeOptions & REUSE_BUFFER_MODE) {
9647
- target.start = start;
9648
- target.end = position;
9649
- return target
9650
- }
9651
- return target.subarray(start, position) // position can change if we call pack again in saveStructures, so we get the buffer now
9652
- } catch(error) {
9653
- encodingError = error;
9654
- throw error;
9655
- } finally {
9656
- if (structures) {
9657
- resetStructures();
9658
- if (hasSharedUpdate && packr.saveStructures) {
9659
- let sharedLength = structures.sharedLength || 0;
9660
- // we can't rely on start/end with REUSE_BUFFER_MODE since they will (probably) change when we save
9661
- let returnBuffer = target.subarray(start, position);
9662
- let newSharedData = prepareStructures(structures, packr);
9663
- if (!encodingError) { // TODO: If there is an encoding error, should make the structures as uninitialized so they get rebuilt next time
9664
- if (packr.saveStructures(newSharedData, newSharedData.isCompatible) === false) {
9665
- // get updated structures and try again if the update failed
9666
- return packr.pack(value, encodeOptions)
9667
- }
9668
- packr.lastNamedStructuresLength = sharedLength;
9669
- // don't keep large buffers around
9670
- if (target.length > 0x40000000) target = null;
9671
- return returnBuffer
9672
- }
9673
- }
9674
- }
9675
- // don't keep large buffers around, they take too much memory and cause problems (limit at 1GB)
9676
- if (target.length > 0x40000000) target = null;
9677
- if (encodeOptions & RESET_BUFFER_MODE)
9678
- position = start;
9679
- }
9680
- };
9681
- const resetStructures = () => {
9682
- if (serializationsSinceTransitionRebuild < 10)
9683
- serializationsSinceTransitionRebuild++;
9684
- let sharedLength = structures.sharedLength || 0;
9685
- if (structures.length > sharedLength && !isSequential)
9686
- structures.length = sharedLength;
9687
- if (transitionsCount > 10000) {
9688
- // force a rebuild occasionally after a lot of transitions so it can get cleaned up
9689
- structures.transitions = null;
9690
- serializationsSinceTransitionRebuild = 0;
9691
- transitionsCount = 0;
9692
- if (recordIdsToRemove.length > 0)
9693
- recordIdsToRemove = [];
9694
- } else if (recordIdsToRemove.length > 0 && !isSequential) {
9695
- for (let i = 0, l = recordIdsToRemove.length; i < l; i++) {
9696
- recordIdsToRemove[i][RECORD_SYMBOL] = 0;
9697
- }
9698
- recordIdsToRemove = [];
9699
- }
9700
- };
9701
- const packArray = (value) => {
9702
- var length = value.length;
9703
- if (length < 0x10) {
9704
- target[position++] = 0x90 | length;
9705
- } else if (length < 0x10000) {
9706
- target[position++] = 0xdc;
9707
- target[position++] = length >> 8;
9708
- target[position++] = length & 0xff;
9709
- } else {
9710
- target[position++] = 0xdd;
9711
- targetView.setUint32(position, length);
9712
- position += 4;
9713
- }
9714
- for (let i = 0; i < length; i++) {
9715
- pack(value[i]);
9716
- }
9717
- };
9718
- const pack = (value) => {
9719
- if (position > safeEnd)
9720
- target = makeRoom(position);
9721
-
9722
- var type = typeof value;
9723
- var length;
9724
- if (type === 'string') {
9725
- let strLength = value.length;
9726
- if (bundledStrings && strLength >= 4 && strLength < 0x1000) {
9727
- if ((bundledStrings.size += strLength) > MAX_BUNDLE_SIZE) {
9728
- let extStart;
9729
- let maxBytes = (bundledStrings[0] ? bundledStrings[0].length * 3 + bundledStrings[1].length : 0) + 10;
9730
- if (position + maxBytes > safeEnd)
9731
- target = makeRoom(position + maxBytes);
9732
- let lastBundle;
9733
- if (bundledStrings.position) { // here we use the 0x62 extension to write the last bundle and reserve space for the reference pointer to the next/current bundle
9734
- lastBundle = bundledStrings;
9735
- target[position] = 0xc8; // ext 16
9736
- position += 3; // reserve for the writing bundle size
9737
- target[position++] = 0x62; // 'b'
9738
- extStart = position - start;
9739
- position += 4; // reserve for writing bundle reference
9740
- writeBundles(start, pack, 0); // write the last bundles
9741
- targetView.setUint16(extStart + start - 3, position - start - extStart);
9742
- } else { // here we use the 0x62 extension just to reserve the space for the reference pointer to the bundle (will be updated once the bundle is written)
9743
- target[position++] = 0xd6; // fixext 4
9744
- target[position++] = 0x62; // 'b'
9745
- extStart = position - start;
9746
- position += 4; // reserve for writing bundle reference
9747
- }
9748
- bundledStrings = ['', '']; // create new ones
9749
- bundledStrings.previous = lastBundle;
9750
- bundledStrings.size = 0;
9751
- bundledStrings.position = extStart;
9752
- }
9753
- let twoByte = hasNonLatin.test(value);
9754
- bundledStrings[twoByte ? 0 : 1] += value;
9755
- target[position++] = 0xc1;
9756
- pack(twoByte ? -strLength : strLength);
9757
- return
9758
- }
9759
- let headerSize;
9760
- // first we estimate the header size, so we can write to the correct location
9761
- if (strLength < 0x20) {
9762
- headerSize = 1;
9763
- } else if (strLength < 0x100) {
9764
- headerSize = 2;
9765
- } else if (strLength < 0x10000) {
9766
- headerSize = 3;
9767
- } else {
9768
- headerSize = 5;
9769
- }
9770
- let maxBytes = strLength * 3;
9771
- if (position + maxBytes > safeEnd)
9772
- target = makeRoom(position + maxBytes);
9773
-
9774
- if (strLength < 0x40 || !encodeUtf8) {
9775
- let i, c1, c2, strPosition = position + headerSize;
9776
- for (i = 0; i < strLength; i++) {
9777
- c1 = value.charCodeAt(i);
9778
- if (c1 < 0x80) {
9779
- target[strPosition++] = c1;
9780
- } else if (c1 < 0x800) {
9781
- target[strPosition++] = c1 >> 6 | 0xc0;
9782
- target[strPosition++] = c1 & 0x3f | 0x80;
9783
- } else if (
9784
- (c1 & 0xfc00) === 0xd800 &&
9785
- ((c2 = value.charCodeAt(i + 1)) & 0xfc00) === 0xdc00
9786
- ) {
9787
- c1 = 0x10000 + ((c1 & 0x03ff) << 10) + (c2 & 0x03ff);
9788
- i++;
9789
- target[strPosition++] = c1 >> 18 | 0xf0;
9790
- target[strPosition++] = c1 >> 12 & 0x3f | 0x80;
9791
- target[strPosition++] = c1 >> 6 & 0x3f | 0x80;
9792
- target[strPosition++] = c1 & 0x3f | 0x80;
9793
- } else {
9794
- target[strPosition++] = c1 >> 12 | 0xe0;
9795
- target[strPosition++] = c1 >> 6 & 0x3f | 0x80;
9796
- target[strPosition++] = c1 & 0x3f | 0x80;
9797
- }
9798
- }
9799
- length = strPosition - position - headerSize;
9800
- } else {
9801
- length = encodeUtf8(value, position + headerSize);
9802
- }
9803
-
9804
- if (length < 0x20) {
9805
- target[position++] = 0xa0 | length;
9806
- } else if (length < 0x100) {
9807
- if (headerSize < 2) {
9808
- target.copyWithin(position + 2, position + 1, position + 1 + length);
9809
- }
9810
- target[position++] = 0xd9;
9811
- target[position++] = length;
9812
- } else if (length < 0x10000) {
9813
- if (headerSize < 3) {
9814
- target.copyWithin(position + 3, position + 2, position + 2 + length);
9815
- }
9816
- target[position++] = 0xda;
9817
- target[position++] = length >> 8;
9818
- target[position++] = length & 0xff;
9819
- } else {
9820
- if (headerSize < 5) {
9821
- target.copyWithin(position + 5, position + 3, position + 3 + length);
9822
- }
9823
- target[position++] = 0xdb;
9824
- targetView.setUint32(position, length);
9825
- position += 4;
9826
- }
9827
- position += length;
9828
- } else if (type === 'number') {
9829
- if (value >>> 0 === value) {// positive integer, 32-bit or less
9830
- // positive uint
9831
- if (value < 0x20 || (value < 0x80 && this.useRecords === false) || (value < 0x40 && !this.randomAccessStructure)) {
9832
- target[position++] = value;
9833
- } else if (value < 0x100) {
9834
- target[position++] = 0xcc;
9835
- target[position++] = value;
9836
- } else if (value < 0x10000) {
9837
- target[position++] = 0xcd;
9838
- target[position++] = value >> 8;
9839
- target[position++] = value & 0xff;
9840
- } else {
9841
- target[position++] = 0xce;
9842
- targetView.setUint32(position, value);
9843
- position += 4;
9844
- }
9845
- } else if (value >> 0 === value) { // negative integer
9846
- if (value >= -0x20) {
9847
- target[position++] = 0x100 + value;
9848
- } else if (value >= -0x80) {
9849
- target[position++] = 0xd0;
9850
- target[position++] = value + 0x100;
9851
- } else if (value >= -0x8000) {
9852
- target[position++] = 0xd1;
9853
- targetView.setInt16(position, value);
9854
- position += 2;
9855
- } else {
9856
- target[position++] = 0xd2;
9857
- targetView.setInt32(position, value);
9858
- position += 4;
9859
- }
9860
- } else {
9861
- let useFloat32;
9862
- if ((useFloat32 = this.useFloat32) > 0 && value < 0x100000000 && value >= -0x80000000) {
9863
- target[position++] = 0xca;
9864
- targetView.setFloat32(position, value);
9865
- let xShifted;
9866
- if (useFloat32 < 4 ||
9867
- // this checks for rounding of numbers that were encoded in 32-bit float to nearest significant decimal digit that could be preserved
9868
- ((xShifted = value * mult10[((target[position] & 0x7f) << 1) | (target[position + 1] >> 7)]) >> 0) === xShifted) {
9869
- position += 4;
9870
- return
9871
- } else
9872
- position--; // move back into position for writing a double
9873
- }
9874
- target[position++] = 0xcb;
9875
- targetView.setFloat64(position, value);
9876
- position += 8;
9877
- }
9878
- } else if (type === 'object' || type === 'function') {
9879
- if (!value)
9880
- target[position++] = 0xc0;
9881
- else {
9882
- if (referenceMap) {
9883
- let referee = referenceMap.get(value);
9884
- if (referee) {
9885
- if (!referee.id) {
9886
- let idsToInsert = referenceMap.idsToInsert || (referenceMap.idsToInsert = []);
9887
- referee.id = idsToInsert.push(referee);
9888
- }
9889
- target[position++] = 0xd6; // fixext 4
9890
- target[position++] = 0x70; // "p" for pointer
9891
- targetView.setUint32(position, referee.id);
9892
- position += 4;
9893
- return
9894
- } else
9895
- referenceMap.set(value, { offset: position - start });
9896
- }
9897
- let constructor = value.constructor;
9898
- if (constructor === Object) {
9899
- writeObject(value);
9900
- } else if (constructor === Array) {
9901
- packArray(value);
9902
- } else if (constructor === Map) {
9903
- if (this.mapAsEmptyObject) target[position++] = 0x80;
9904
- else {
9905
- length = value.size;
9906
- if (length < 0x10) {
9907
- target[position++] = 0x80 | length;
9908
- } else if (length < 0x10000) {
9909
- target[position++] = 0xde;
9910
- target[position++] = length >> 8;
9911
- target[position++] = length & 0xff;
9912
- } else {
9913
- target[position++] = 0xdf;
9914
- targetView.setUint32(position, length);
9915
- position += 4;
9916
- }
9917
- for (let [key, entryValue] of value) {
9918
- pack(key);
9919
- pack(entryValue);
9920
- }
9921
- }
9922
- } else {
9923
- for (let i = 0, l = extensions.length; i < l; i++) {
9924
- let extensionClass = extensionClasses[i];
9925
- if (value instanceof extensionClass) {
9926
- let extension = extensions[i];
9927
- if (extension.write) {
9928
- if (extension.type) {
9929
- target[position++] = 0xd4; // one byte "tag" extension
9930
- target[position++] = extension.type;
9931
- target[position++] = 0;
9932
- }
9933
- let writeResult = extension.write.call(this, value);
9934
- if (writeResult === value) { // avoid infinite recursion
9935
- if (Array.isArray(value)) {
9936
- packArray(value);
9937
- } else {
9938
- writeObject(value);
9939
- }
9940
- } else {
9941
- pack(writeResult);
9942
- }
9943
- return
9944
- }
9945
- let currentTarget = target;
9946
- let currentTargetView = targetView;
9947
- let currentPosition = position;
9948
- target = null;
9949
- let result;
9950
- try {
9951
- result = extension.pack.call(this, value, (size) => {
9952
- // restore target and use it
9953
- target = currentTarget;
9954
- currentTarget = null;
9955
- position += size;
9956
- if (position > safeEnd)
9957
- makeRoom(position);
9958
- return {
9959
- target, targetView, position: position - size
9960
- }
9961
- }, pack);
9962
- } finally {
9963
- // restore current target information (unless already restored)
9964
- if (currentTarget) {
9965
- target = currentTarget;
9966
- targetView = currentTargetView;
9967
- position = currentPosition;
9968
- safeEnd = target.length - 10;
9969
- }
9970
- }
9971
- if (result) {
9972
- if (result.length + position > safeEnd)
9973
- makeRoom(result.length + position);
9974
- position = writeExtensionData(result, target, position, extension.type);
9975
- }
9976
- return
9977
- }
9978
- }
9979
- // check isArray after extensions, because extensions can extend Array
9980
- if (Array.isArray(value)) {
9981
- packArray(value);
9982
- } else {
9983
- // use this as an alternate mechanism for expressing how to serialize
9984
- if (value.toJSON) {
9985
- const json = value.toJSON();
9986
- // if for some reason value.toJSON returns itself it'll loop forever
9987
- if (json !== value)
9988
- return pack(json)
9989
- }
9990
-
9991
- // if there is a writeFunction, use it, otherwise just encode as undefined
9992
- if (type === 'function')
9993
- return pack(this.writeFunction && this.writeFunction(value));
9994
-
9995
- // no extension found, write as plain object
9996
- writeObject(value);
9997
- }
9998
- }
9999
- }
10000
- } else if (type === 'boolean') {
10001
- target[position++] = value ? 0xc3 : 0xc2;
10002
- } else if (type === 'bigint') {
10003
- if (value < (BigInt(1)<<BigInt(63)) && value >= -(BigInt(1)<<BigInt(63))) {
10004
- // use a signed int as long as it fits
10005
- target[position++] = 0xd3;
10006
- targetView.setBigInt64(position, value);
10007
- } else if (value < (BigInt(1)<<BigInt(64)) && value > 0) {
10008
- // if we can fit an unsigned int, use that
10009
- target[position++] = 0xcf;
10010
- targetView.setBigUint64(position, value);
10011
- } else {
10012
- // overflow
10013
- if (this.largeBigIntToFloat) {
10014
- target[position++] = 0xcb;
10015
- targetView.setFloat64(position, Number(value));
10016
- } else if (this.useBigIntExtension && value < 2n**(1023n) && value > -(2n**(1023n))) {
10017
- target[position++] = 0xc7;
10018
- position++;
10019
- target[position++] = 0x42; // "B" for BigInt
10020
- let bytes = [];
10021
- let alignedSign;
10022
- do {
10023
- let byte = value & 0xffn;
10024
- alignedSign = (byte & 0x80n) === (value < 0n ? 0x80n : 0n);
10025
- bytes.push(byte);
10026
- value >>= 8n;
10027
- } while (!((value === 0n || value === -1n) && alignedSign));
10028
- target[position-2] = bytes.length;
10029
- for (let i = bytes.length; i > 0;) {
10030
- target[position++] = Number(bytes[--i]);
10031
- }
10032
- return
10033
- } else {
10034
- throw new RangeError(value + ' was too large to fit in MessagePack 64-bit integer format, use' +
10035
- ' useBigIntExtension or set largeBigIntToFloat to convert to float-64')
10036
- }
10037
- }
10038
- position += 8;
10039
- } else if (type === 'undefined') {
10040
- if (this.encodeUndefinedAsNil)
10041
- target[position++] = 0xc0;
10042
- else {
10043
- target[position++] = 0xd4; // a number of implementations use fixext1 with type 0, data 0 to denote undefined, so we follow suite
10044
- target[position++] = 0;
10045
- target[position++] = 0;
10046
- }
10047
- } else {
10048
- throw new Error('Unknown type: ' + type)
10049
- }
10050
- };
10051
-
10052
- const writePlainObject = (this.variableMapSize || this.coercibleKeyAsNumber) ? (object) => {
10053
- // this method is slightly slower, but generates "preferred serialization" (optimally small for smaller objects)
10054
- let keys = Object.keys(object);
10055
- let length = keys.length;
10056
- if (length < 0x10) {
10057
- target[position++] = 0x80 | length;
10058
- } else if (length < 0x10000) {
10059
- target[position++] = 0xde;
10060
- target[position++] = length >> 8;
10061
- target[position++] = length & 0xff;
10062
- } else {
10063
- target[position++] = 0xdf;
10064
- targetView.setUint32(position, length);
10065
- position += 4;
10066
- }
10067
- let key;
10068
- if (this.coercibleKeyAsNumber) {
10069
- for (let i = 0; i < length; i++) {
10070
- key = keys[i];
10071
- let num = Number(key);
10072
- pack(isNaN(num) ? key : num);
10073
- pack(object[key]);
10074
- }
10075
-
10076
- } else {
10077
- for (let i = 0; i < length; i++) {
10078
- pack(key = keys[i]);
10079
- pack(object[key]);
10080
- }
10081
- }
10082
- } :
10083
- (object) => {
10084
- target[position++] = 0xde; // always using map 16, so we can preallocate and set the length afterwards
10085
- let objectOffset = position - start;
10086
- position += 2;
10087
- let size = 0;
10088
- for (let key in object) {
10089
- if (typeof object.hasOwnProperty !== 'function' || object.hasOwnProperty(key)) {
10090
- pack(key);
10091
- pack(object[key]);
10092
- size++;
10093
- }
10094
- }
10095
- target[objectOffset++ + start] = size >> 8;
10096
- target[objectOffset + start] = size & 0xff;
10097
- };
10098
-
10099
- const writeRecord = this.useRecords === false ? writePlainObject :
10100
- (options.progressiveRecords && !useTwoByteRecords) ? // this is about 2% faster for highly stable structures, since it only requires one for-in loop (but much more expensive when new structure needs to be written)
10101
- (object) => {
10102
- let nextTransition, transition = structures.transitions || (structures.transitions = Object.create(null));
10103
- let objectOffset = position++ - start;
10104
- let wroteKeys;
10105
- for (let key in object) {
10106
- if (typeof object.hasOwnProperty !== 'function' || object.hasOwnProperty(key)) {
10107
- nextTransition = transition[key];
10108
- if (nextTransition)
10109
- transition = nextTransition;
10110
- else {
10111
- // record doesn't exist, create full new record and insert it
10112
- let keys = Object.keys(object);
10113
- let lastTransition = transition;
10114
- transition = structures.transitions;
10115
- let newTransitions = 0;
10116
- for (let i = 0, l = keys.length; i < l; i++) {
10117
- let key = keys[i];
10118
- nextTransition = transition[key];
10119
- if (!nextTransition) {
10120
- nextTransition = transition[key] = Object.create(null);
10121
- newTransitions++;
10122
- }
10123
- transition = nextTransition;
10124
- }
10125
- if (objectOffset + start + 1 == position) {
10126
- // first key, so we don't need to insert, we can just write record directly
10127
- position--;
10128
- newRecord(transition, keys, newTransitions);
10129
- } else // otherwise we need to insert the record, moving existing data after the record
10130
- insertNewRecord(transition, keys, objectOffset, newTransitions);
10131
- wroteKeys = true;
10132
- transition = lastTransition[key];
10133
- }
10134
- pack(object[key]);
10135
- }
10136
- }
10137
- if (!wroteKeys) {
10138
- let recordId = transition[RECORD_SYMBOL];
10139
- if (recordId)
10140
- target[objectOffset + start] = recordId;
10141
- else
10142
- insertNewRecord(transition, Object.keys(object), objectOffset, 0);
10143
- }
10144
- } :
10145
- (object) => {
10146
- let nextTransition, transition = structures.transitions || (structures.transitions = Object.create(null));
10147
- let newTransitions = 0;
10148
- for (let key in object) if (typeof object.hasOwnProperty !== 'function' || object.hasOwnProperty(key)) {
10149
- nextTransition = transition[key];
10150
- if (!nextTransition) {
10151
- nextTransition = transition[key] = Object.create(null);
10152
- newTransitions++;
10153
- }
10154
- transition = nextTransition;
10155
- }
10156
- let recordId = transition[RECORD_SYMBOL];
10157
- if (recordId) {
10158
- if (recordId >= 0x60 && useTwoByteRecords) {
10159
- target[position++] = ((recordId -= 0x60) & 0x1f) + 0x60;
10160
- target[position++] = recordId >> 5;
10161
- } else
10162
- target[position++] = recordId;
10163
- } else {
10164
- newRecord(transition, transition.__keys__ || Object.keys(object), newTransitions);
10165
- }
10166
- // now write the values
10167
- for (let key in object)
10168
- if (typeof object.hasOwnProperty !== 'function' || object.hasOwnProperty(key)) {
10169
- pack(object[key]);
10170
- }
10171
- };
10172
-
10173
- // craete reference to useRecords if useRecords is a function
10174
- const checkUseRecords = typeof this.useRecords == 'function' && this.useRecords;
10175
-
10176
- const writeObject = checkUseRecords ? (object) => {
10177
- checkUseRecords(object) ? writeRecord(object) : writePlainObject(object);
10178
- } : writeRecord;
10179
-
10180
- const makeRoom = (end) => {
10181
- let newSize;
10182
- if (end > 0x1000000) {
10183
- // special handling for really large buffers
10184
- if ((end - start) > MAX_BUFFER_SIZE)
10185
- throw new Error('Packed buffer would be larger than maximum buffer size')
10186
- newSize = Math.min(MAX_BUFFER_SIZE,
10187
- Math.round(Math.max((end - start) * (end > 0x4000000 ? 1.25 : 2), 0x400000) / 0x1000) * 0x1000);
10188
- } else // faster handling for smaller buffers
10189
- newSize = ((Math.max((end - start) << 2, target.length - 1) >> 12) + 1) << 12;
10190
- let newBuffer = new ByteArrayAllocate(newSize);
10191
- targetView = newBuffer.dataView || (newBuffer.dataView = new DataView(newBuffer.buffer, 0, newSize));
10192
- end = Math.min(end, target.length);
10193
- if (target.copy)
10194
- target.copy(newBuffer, 0, start, end);
10195
- else
10196
- newBuffer.set(target.slice(start, end));
10197
- position -= start;
10198
- start = 0;
10199
- safeEnd = newBuffer.length - 10;
10200
- return target = newBuffer
10201
- };
10202
- const newRecord = (transition, keys, newTransitions) => {
10203
- let recordId = structures.nextId;
10204
- if (!recordId)
10205
- recordId = 0x40;
10206
- if (recordId < sharedLimitId && this.shouldShareStructure && !this.shouldShareStructure(keys)) {
10207
- recordId = structures.nextOwnId;
10208
- if (!(recordId < maxStructureId))
10209
- recordId = sharedLimitId;
10210
- structures.nextOwnId = recordId + 1;
10211
- } else {
10212
- if (recordId >= maxStructureId)// cycle back around
10213
- recordId = sharedLimitId;
10214
- structures.nextId = recordId + 1;
10215
- }
10216
- let highByte = keys.highByte = recordId >= 0x60 && useTwoByteRecords ? (recordId - 0x60) >> 5 : -1;
10217
- transition[RECORD_SYMBOL] = recordId;
10218
- transition.__keys__ = keys;
10219
- structures[recordId - 0x40] = keys;
10220
-
10221
- if (recordId < sharedLimitId) {
10222
- keys.isShared = true;
10223
- structures.sharedLength = recordId - 0x3f;
10224
- hasSharedUpdate = true;
10225
- if (highByte >= 0) {
10226
- target[position++] = (recordId & 0x1f) + 0x60;
10227
- target[position++] = highByte;
10228
- } else {
10229
- target[position++] = recordId;
10230
- }
10231
- } else {
10232
- if (highByte >= 0) {
10233
- target[position++] = 0xd5; // fixext 2
10234
- target[position++] = 0x72; // "r" record defintion extension type
10235
- target[position++] = (recordId & 0x1f) + 0x60;
10236
- target[position++] = highByte;
10237
- } else {
10238
- target[position++] = 0xd4; // fixext 1
10239
- target[position++] = 0x72; // "r" record defintion extension type
10240
- target[position++] = recordId;
10241
- }
10242
-
10243
- if (newTransitions)
10244
- transitionsCount += serializationsSinceTransitionRebuild * newTransitions;
10245
- // record the removal of the id, we can maintain our shared structure
10246
- if (recordIdsToRemove.length >= maxOwnStructures)
10247
- recordIdsToRemove.shift()[RECORD_SYMBOL] = 0; // we are cycling back through, and have to remove old ones
10248
- recordIdsToRemove.push(transition);
10249
- pack(keys);
10250
- }
10251
- };
10252
- const insertNewRecord = (transition, keys, insertionOffset, newTransitions) => {
10253
- let mainTarget = target;
10254
- let mainPosition = position;
10255
- let mainSafeEnd = safeEnd;
10256
- let mainStart = start;
10257
- target = keysTarget;
10258
- position = 0;
10259
- start = 0;
10260
- if (!target)
10261
- keysTarget = target = new ByteArrayAllocate(8192);
10262
- safeEnd = target.length - 10;
10263
- newRecord(transition, keys, newTransitions);
10264
- keysTarget = target;
10265
- let keysPosition = position;
10266
- target = mainTarget;
10267
- position = mainPosition;
10268
- safeEnd = mainSafeEnd;
10269
- start = mainStart;
10270
- if (keysPosition > 1) {
10271
- let newEnd = position + keysPosition - 1;
10272
- if (newEnd > safeEnd)
10273
- makeRoom(newEnd);
10274
- let insertionPosition = insertionOffset + start;
10275
- target.copyWithin(insertionPosition + keysPosition, insertionPosition + 1, position);
10276
- target.set(keysTarget.slice(0, keysPosition), insertionPosition);
10277
- position = newEnd;
10278
- } else {
10279
- target[insertionOffset + start] = keysTarget[0];
10280
- }
10281
- };
10282
- const writeStruct = (object) => {
10283
- let newPosition = writeStructSlots(object, target, start, position, structures, makeRoom, (value, newPosition, notifySharedUpdate) => {
10284
- if (notifySharedUpdate)
10285
- return hasSharedUpdate = true;
10286
- position = newPosition;
10287
- let startTarget = target;
10288
- pack(value);
10289
- resetStructures();
10290
- if (startTarget !== target) {
10291
- return { position, targetView, target }; // indicate the buffer was re-allocated
10292
- }
10293
- return position;
10294
- }, this);
10295
- if (newPosition === 0) // bail and go to a msgpack object
10296
- return writeObject(object);
10297
- position = newPosition;
10298
- };
10299
- }
10300
- useBuffer(buffer) {
10301
- // this means we are finished using our own buffer and we can write over it safely
10302
- target = buffer;
10303
- targetView = new DataView(target.buffer, target.byteOffset, target.byteLength);
10304
- position = 0;
10305
- }
10306
- clearSharedData() {
10307
- if (this.structures)
10308
- this.structures = [];
10309
- if (this.typedStructs)
10310
- this.typedStructs = [];
10311
- }
10312
- }
10313
-
10314
- extensionClasses = [ Date, Set, Error, RegExp, ArrayBuffer, Object.getPrototypeOf(Uint8Array.prototype).constructor /*TypedArray*/, C1Type ];
10315
- extensions = [{
10316
- pack(date, allocateForWrite, pack) {
10317
- let seconds = date.getTime() / 1000;
10318
- if ((this.useTimestamp32 || date.getMilliseconds() === 0) && seconds >= 0 && seconds < 0x100000000) {
10319
- // Timestamp 32
10320
- let { target, targetView, position} = allocateForWrite(6);
10321
- target[position++] = 0xd6;
10322
- target[position++] = 0xff;
10323
- targetView.setUint32(position, seconds);
10324
- } else if (seconds > 0 && seconds < 0x100000000) {
10325
- // Timestamp 64
10326
- let { target, targetView, position} = allocateForWrite(10);
10327
- target[position++] = 0xd7;
10328
- target[position++] = 0xff;
10329
- targetView.setUint32(position, date.getMilliseconds() * 4000000 + ((seconds / 1000 / 0x100000000) >> 0));
10330
- targetView.setUint32(position + 4, seconds);
10331
- } else if (isNaN(seconds)) {
10332
- if (this.onInvalidDate) {
10333
- allocateForWrite(0);
10334
- return pack(this.onInvalidDate())
10335
- }
10336
- // Intentionally invalid timestamp
10337
- let { target, targetView, position} = allocateForWrite(3);
10338
- target[position++] = 0xd4;
10339
- target[position++] = 0xff;
10340
- target[position++] = 0xff;
10341
- } else {
10342
- // Timestamp 96
10343
- let { target, targetView, position} = allocateForWrite(15);
10344
- target[position++] = 0xc7;
10345
- target[position++] = 12;
10346
- target[position++] = 0xff;
10347
- targetView.setUint32(position, date.getMilliseconds() * 1000000);
10348
- targetView.setBigInt64(position + 4, BigInt(Math.floor(seconds)));
10349
- }
10350
- }
10351
- }, {
10352
- pack(set, allocateForWrite, pack) {
10353
- if (this.setAsEmptyObject) {
10354
- allocateForWrite(0);
10355
- return pack({})
10356
- }
10357
- let array = Array.from(set);
10358
- let { target, position} = allocateForWrite(this.moreTypes ? 3 : 0);
10359
- if (this.moreTypes) {
10360
- target[position++] = 0xd4;
10361
- target[position++] = 0x73; // 's' for Set
10362
- target[position++] = 0;
10363
- }
10364
- pack(array);
10365
- }
10366
- }, {
10367
- pack(error, allocateForWrite, pack) {
10368
- let { target, position} = allocateForWrite(this.moreTypes ? 3 : 0);
10369
- if (this.moreTypes) {
10370
- target[position++] = 0xd4;
10371
- target[position++] = 0x65; // 'e' for error
10372
- target[position++] = 0;
10373
- }
10374
- pack([ error.name, error.message, error.cause ]);
10375
- }
10376
- }, {
10377
- pack(regex, allocateForWrite, pack) {
10378
- let { target, position} = allocateForWrite(this.moreTypes ? 3 : 0);
10379
- if (this.moreTypes) {
10380
- target[position++] = 0xd4;
10381
- target[position++] = 0x78; // 'x' for regeXp
10382
- target[position++] = 0;
10383
- }
10384
- pack([ regex.source, regex.flags ]);
10385
- }
10386
- }, {
10387
- pack(arrayBuffer, allocateForWrite) {
10388
- if (this.moreTypes)
10389
- writeExtBuffer(arrayBuffer, 0x10, allocateForWrite);
10390
- else
10391
- writeBuffer(hasNodeBuffer ? Buffer.from(arrayBuffer) : new Uint8Array(arrayBuffer), allocateForWrite);
10392
- }
10393
- }, {
10394
- pack(typedArray, allocateForWrite) {
10395
- let constructor = typedArray.constructor;
10396
- if (constructor !== ByteArray && this.moreTypes)
10397
- writeExtBuffer(typedArray, typedArrays.indexOf(constructor.name), allocateForWrite);
10398
- else
10399
- writeBuffer(typedArray, allocateForWrite);
10400
- }
10401
- }, {
10402
- pack(c1, allocateForWrite) { // specific 0xC1 object
10403
- let { target, position} = allocateForWrite(1);
10404
- target[position] = 0xc1;
10405
- }
10406
- }];
10407
-
10408
- function writeExtBuffer(typedArray, type, allocateForWrite, encode) {
10409
- let length = typedArray.byteLength;
10410
- if (length + 1 < 0x100) {
10411
- var { target, position } = allocateForWrite(4 + length);
10412
- target[position++] = 0xc7;
10413
- target[position++] = length + 1;
10414
- } else if (length + 1 < 0x10000) {
10415
- var { target, position } = allocateForWrite(5 + length);
10416
- target[position++] = 0xc8;
10417
- target[position++] = (length + 1) >> 8;
10418
- target[position++] = (length + 1) & 0xff;
10419
- } else {
10420
- var { target, position, targetView } = allocateForWrite(7 + length);
10421
- target[position++] = 0xc9;
10422
- targetView.setUint32(position, length + 1); // plus one for the type byte
10423
- position += 4;
10424
- }
10425
- target[position++] = 0x74; // "t" for typed array
10426
- target[position++] = type;
10427
- if (!typedArray.buffer) typedArray = new Uint8Array(typedArray);
10428
- target.set(new Uint8Array(typedArray.buffer, typedArray.byteOffset, typedArray.byteLength), position);
10429
- }
10430
- function writeBuffer(buffer, allocateForWrite) {
10431
- let length = buffer.byteLength;
10432
- var target, position;
10433
- if (length < 0x100) {
10434
- var { target, position } = allocateForWrite(length + 2);
10435
- target[position++] = 0xc4;
10436
- target[position++] = length;
10437
- } else if (length < 0x10000) {
10438
- var { target, position } = allocateForWrite(length + 3);
10439
- target[position++] = 0xc5;
10440
- target[position++] = length >> 8;
10441
- target[position++] = length & 0xff;
10442
- } else {
10443
- var { target, position, targetView } = allocateForWrite(length + 5);
10444
- target[position++] = 0xc6;
10445
- targetView.setUint32(position, length);
10446
- position += 4;
10447
- }
10448
- target.set(buffer, position);
10449
- }
10450
-
10451
- function writeExtensionData(result, target, position, type) {
10452
- let length = result.length;
10453
- switch (length) {
10454
- case 1:
10455
- target[position++] = 0xd4;
10456
- break
10457
- case 2:
10458
- target[position++] = 0xd5;
10459
- break
10460
- case 4:
10461
- target[position++] = 0xd6;
10462
- break
10463
- case 8:
10464
- target[position++] = 0xd7;
10465
- break
10466
- case 16:
10467
- target[position++] = 0xd8;
10468
- break
10469
- default:
10470
- if (length < 0x100) {
10471
- target[position++] = 0xc7;
10472
- target[position++] = length;
10473
- } else if (length < 0x10000) {
10474
- target[position++] = 0xc8;
10475
- target[position++] = length >> 8;
10476
- target[position++] = length & 0xff;
10477
- } else {
10478
- target[position++] = 0xc9;
10479
- target[position++] = length >> 24;
10480
- target[position++] = (length >> 16) & 0xff;
10481
- target[position++] = (length >> 8) & 0xff;
10482
- target[position++] = length & 0xff;
10483
- }
10484
- }
10485
- target[position++] = type;
10486
- target.set(result, position);
10487
- position += length;
10488
- return position
10489
- }
10490
-
10491
- function insertIds(serialized, idsToInsert) {
10492
- // insert the ids that need to be referenced for structured clones
10493
- let nextId;
10494
- let distanceToMove = idsToInsert.length * 6;
10495
- let lastEnd = serialized.length - distanceToMove;
10496
- while (nextId = idsToInsert.pop()) {
10497
- let offset = nextId.offset;
10498
- let id = nextId.id;
10499
- serialized.copyWithin(offset + distanceToMove, offset, lastEnd);
10500
- distanceToMove -= 6;
10501
- let position = offset + distanceToMove;
10502
- serialized[position++] = 0xd6;
10503
- serialized[position++] = 0x69; // 'i'
10504
- serialized[position++] = id >> 24;
10505
- serialized[position++] = (id >> 16) & 0xff;
10506
- serialized[position++] = (id >> 8) & 0xff;
10507
- serialized[position++] = id & 0xff;
10508
- lastEnd = offset;
10509
- }
10510
- return serialized
9324
+ /*
9325
+ * A helper function to compact an array
9326
+ */
9327
+ function compact(address, slice) {
9328
+ const s1 = [];
9329
+ const s2 = [];
9330
+ let i;
9331
+ for (i = 0; i < address.length; i++) {
9332
+ if (i < slice[0]) {
9333
+ s1.push(address[i]);
9334
+ }
9335
+ else if (i > slice[1]) {
9336
+ s2.push(address[i]);
9337
+ }
9338
+ }
9339
+ return s1.concat(['compact']).concat(s2);
10511
9340
  }
10512
-
10513
- function writeBundles(start, pack, incrementPosition) {
10514
- if (bundledStrings.length > 0) {
10515
- targetView.setUint32(bundledStrings.position + start, position + incrementPosition - bundledStrings.position - start);
10516
- bundledStrings.stringsPosition = position - start;
10517
- let writeStrings = bundledStrings;
10518
- bundledStrings = null;
10519
- pack(writeStrings[0]);
10520
- pack(writeStrings[1]);
10521
- }
9341
+ function paddedHex(octet) {
9342
+ return parseInt(octet, 16).toString(16).padStart(4, '0');
10522
9343
  }
10523
- function prepareStructures(structures, packr) {
10524
- structures.isCompatible = (existingStructures) => {
10525
- let compatible = !existingStructures || ((packr.lastNamedStructuresLength || 0) === existingStructures.length);
10526
- if (!compatible) // we want to merge these existing structures immediately since we already have it and we are in the right transaction
10527
- packr._mergeStructures(existingStructures);
10528
- return compatible;
10529
- };
10530
- return structures
9344
+ function unsignByte(b) {
9345
+ // eslint-disable-next-line no-bitwise
9346
+ return b & 0xff;
10531
9347
  }
10532
-
10533
- let defaultPackr = new Packr({ useRecords: false });
10534
- defaultPackr.pack;
10535
- defaultPackr.pack;
10536
- const REUSE_BUFFER_MODE = 512;
10537
- const RESET_BUFFER_MODE = 1024;
10538
- const RESERVE_START_SPACE = 2048;
10539
-
10540
- console.log("webvpn imported");
10541
- const packr = new Packr();
10542
- const makeWebVPN = async ({ host, port }) => {
10543
- const webtransportOptions = await fetch("http://localhost:4002/").then((res) => res.json());
10544
- const webtransport = new WebTransport(
10545
- webtransportOptions.address,
10546
- {
10547
- serverCertificateHashes: [{
10548
- algorithm: webtransportOptions.serverCertificateHashes[0].algorithm,
10549
- value: new Uint8Array(webtransportOptions.serverCertificateHashes[0].value)
10550
- }]
9348
+ /**
9349
+ * Represents an IPv6 address
9350
+ * @class Address6
9351
+ * @param {string} address - An IPv6 address string
9352
+ * @param {number} [groups=8] - How many octets to parse
9353
+ * @example
9354
+ * var address = new Address6('2001::/32');
9355
+ */
9356
+ class Address6 {
9357
+ constructor(address, optionalGroups) {
9358
+ this.addressMinusSuffix = '';
9359
+ this.parsedSubnet = '';
9360
+ this.subnet = '/128';
9361
+ this.subnetMask = 128;
9362
+ this.v4 = false;
9363
+ this.zone = '';
9364
+ // #region Attributes
9365
+ /**
9366
+ * Returns true if the given address is in the subnet of the current address
9367
+ * @memberof Address6
9368
+ * @instance
9369
+ * @returns {boolean}
9370
+ */
9371
+ this.isInSubnet = common.isInSubnet;
9372
+ /**
9373
+ * Returns true if the address is correct, false otherwise
9374
+ * @memberof Address6
9375
+ * @instance
9376
+ * @returns {boolean}
9377
+ */
9378
+ this.isCorrect = common.isCorrect(constants6.BITS);
9379
+ if (optionalGroups === undefined) {
9380
+ this.groups = constants6.GROUPS;
9381
+ }
9382
+ else {
9383
+ this.groups = optionalGroups;
9384
+ }
9385
+ this.address = address;
9386
+ const subnet = constants6.RE_SUBNET_STRING.exec(address);
9387
+ if (subnet) {
9388
+ this.parsedSubnet = subnet[0].replace('/', '');
9389
+ this.subnetMask = parseInt(this.parsedSubnet, 10);
9390
+ this.subnet = `/${this.subnetMask}`;
9391
+ if (Number.isNaN(this.subnetMask) ||
9392
+ this.subnetMask < 0 ||
9393
+ this.subnetMask > constants6.BITS) {
9394
+ throw new address_error_1.AddressError('Invalid subnet mask.');
9395
+ }
9396
+ address = address.replace(constants6.RE_SUBNET_STRING, '');
9397
+ }
9398
+ else if (/\//.test(address)) {
9399
+ throw new address_error_1.AddressError('Invalid subnet mask.');
9400
+ }
9401
+ const zone = constants6.RE_ZONE_STRING.exec(address);
9402
+ if (zone) {
9403
+ this.zone = zone[0];
9404
+ address = address.replace(constants6.RE_ZONE_STRING, '');
9405
+ }
9406
+ this.addressMinusSuffix = address;
9407
+ this.parsedAddress = this.parse(this.addressMinusSuffix);
10551
9408
  }
10552
- );
10553
- await webtransport.ready;
10554
- const metaStream = await webtransport.createBidirectionalStream();
10555
- const metaReader = metaStream.readable.getReader();
10556
- const metaWriter = metaStream.writable.getWriter();
10557
- await metaWriter.ready;
10558
- await metaWriter.write(
10559
- packr.pack({
10560
- type: "tcp-connect",
10561
- host,
10562
- port
10563
- })
10564
- );
10565
- const { type, ...initPacket } = packr.unpack((await metaReader.read()).value);
10566
- const incomingBidirectionalStreamReader = webtransport.incomingBidirectionalStreams.getReader();
10567
- const { value: bidirectionalMetaStream } = await incomingBidirectionalStreamReader.read();
10568
- const { value: bidirectionalDataStream } = await incomingBidirectionalStreamReader.read();
10569
- if (!bidirectionalMetaStream)
10570
- throw new Error("bidirectionalMetaStream is undefined");
10571
- if (!bidirectionalDataStream)
10572
- throw new Error("bidirectionalDataStream is undefined");
10573
- const metaStreamReader = bidirectionalMetaStream.readable.getReader();
10574
- const metaStreamWriter = bidirectionalMetaStream.writable.getWriter();
10575
- const dataStreamReader = bidirectionalDataStream.readable.getReader();
10576
- const dataStreamWriter = bidirectionalDataStream.writable.getWriter();
10577
- const result = {
10578
- webtransport,
10579
- closed: false,
10580
- ...initPacket,
10581
- readMetaData: async () => {
10582
- const { done, value } = await metaStreamReader.read();
10583
- if (done)
10584
- return;
10585
- return value;
10586
- },
10587
- writeMetaData: (data) => metaStreamWriter.write(data),
10588
- readData: async () => {
10589
- const { done, value } = await dataStreamReader.read();
10590
- if (done)
10591
- return;
10592
- return value;
10593
- },
10594
- writeData: (data) => dataStreamWriter.write(data),
10595
- close: async () => {
10596
- if (result.closed)
10597
- return;
10598
- result.closed = true;
10599
- await metaReader.cancel();
10600
- await metaWriter.close();
10601
- await metaStreamReader.cancel();
10602
- await metaStreamWriter.close();
10603
- await dataStreamReader.cancel();
10604
- await dataStreamWriter.close();
10605
- webtransport.close();
9409
+ static isValid(address) {
9410
+ try {
9411
+ // eslint-disable-next-line no-new
9412
+ new Address6(address);
9413
+ return true;
9414
+ }
9415
+ catch (e) {
9416
+ return false;
9417
+ }
10606
9418
  }
10607
- };
10608
- return result;
10609
- };
10610
- const normalizeConnectArgs = (args) => {
10611
- if (typeof args[0] === "string")
9419
+ /**
9420
+ * Convert a BigInt to a v6 address object
9421
+ * @memberof Address6
9422
+ * @static
9423
+ * @param {bigint} bigInt - a BigInt to convert
9424
+ * @returns {Address6}
9425
+ * @example
9426
+ * var bigInt = BigInt('1000000000000');
9427
+ * var address = Address6.fromBigInt(bigInt);
9428
+ * address.correctForm(); // '::e8:d4a5:1000'
9429
+ */
9430
+ static fromBigInt(bigInt) {
9431
+ const hex = bigInt.toString(16).padStart(32, '0');
9432
+ const groups = [];
9433
+ let i;
9434
+ for (i = 0; i < constants6.GROUPS; i++) {
9435
+ groups.push(hex.slice(i * 4, (i + 1) * 4));
9436
+ }
9437
+ return new Address6(groups.join(':'));
9438
+ }
9439
+ /**
9440
+ * Convert a URL (with optional port number) to an address object
9441
+ * @memberof Address6
9442
+ * @static
9443
+ * @param {string} url - a URL with optional port number
9444
+ * @example
9445
+ * var addressAndPort = Address6.fromURL('http://[ffff::]:8080/foo/');
9446
+ * addressAndPort.address.correctForm(); // 'ffff::'
9447
+ * addressAndPort.port; // 8080
9448
+ */
9449
+ static fromURL(url) {
9450
+ let host;
9451
+ let port = null;
9452
+ let result;
9453
+ // If we have brackets parse them and find a port
9454
+ if (url.indexOf('[') !== -1 && url.indexOf(']:') !== -1) {
9455
+ result = constants6.RE_URL_WITH_PORT.exec(url);
9456
+ if (result === null) {
9457
+ return {
9458
+ error: 'failed to parse address with port',
9459
+ address: null,
9460
+ port: null,
9461
+ };
9462
+ }
9463
+ host = result[1];
9464
+ port = result[2];
9465
+ // If there's a URL extract the address
9466
+ }
9467
+ else if (url.indexOf('/') !== -1) {
9468
+ // Remove the protocol prefix
9469
+ url = url.replace(/^[a-z0-9]+:\/\//, '');
9470
+ // Parse the address
9471
+ result = constants6.RE_URL.exec(url);
9472
+ if (result === null) {
9473
+ return {
9474
+ error: 'failed to parse address from URL',
9475
+ address: null,
9476
+ port: null,
9477
+ };
9478
+ }
9479
+ host = result[1];
9480
+ // Otherwise just assign the URL to the host and let the library parse it
9481
+ }
9482
+ else {
9483
+ host = url;
9484
+ }
9485
+ // If there's a port convert it to an integer
9486
+ if (port) {
9487
+ port = parseInt(port, 10);
9488
+ // squelch out of range ports
9489
+ if (port < 0 || port > 65536) {
9490
+ port = null;
9491
+ }
9492
+ }
9493
+ else {
9494
+ // Standardize `undefined` to `null`
9495
+ port = null;
9496
+ }
9497
+ return {
9498
+ address: new Address6(host),
9499
+ port,
9500
+ };
9501
+ }
9502
+ /**
9503
+ * Create an IPv6-mapped address given an IPv4 address
9504
+ * @memberof Address6
9505
+ * @static
9506
+ * @param {string} address - An IPv4 address string
9507
+ * @returns {Address6}
9508
+ * @example
9509
+ * var address = Address6.fromAddress4('192.168.0.1');
9510
+ * address.correctForm(); // '::ffff:c0a8:1'
9511
+ * address.to4in6(); // '::ffff:192.168.0.1'
9512
+ */
9513
+ static fromAddress4(address) {
9514
+ const address4 = new ipv4_1.Address4(address);
9515
+ const mask6 = constants6.BITS - (constants4.BITS - address4.subnetMask);
9516
+ return new Address6(`::ffff:${address4.correctForm()}/${mask6}`);
9517
+ }
9518
+ /**
9519
+ * Return an address from ip6.arpa form
9520
+ * @memberof Address6
9521
+ * @static
9522
+ * @param {string} arpaFormAddress - an 'ip6.arpa' form address
9523
+ * @returns {Adress6}
9524
+ * @example
9525
+ * var address = Address6.fromArpa(e.f.f.f.3.c.2.6.f.f.f.e.6.6.8.e.1.0.6.7.9.4.e.c.0.0.0.0.1.0.0.2.ip6.arpa.)
9526
+ * address.correctForm(); // '2001:0:ce49:7601:e866:efff:62c3:fffe'
9527
+ */
9528
+ static fromArpa(arpaFormAddress) {
9529
+ // remove ending ".ip6.arpa." or just "."
9530
+ let address = arpaFormAddress.replace(/(\.ip6\.arpa)?\.$/, '');
9531
+ const semicolonAmount = 7;
9532
+ // correct ip6.arpa form with ending removed will be 63 characters
9533
+ if (address.length !== 63) {
9534
+ throw new address_error_1.AddressError("Invalid 'ip6.arpa' form.");
9535
+ }
9536
+ const parts = address.split('.').reverse();
9537
+ for (let i = semicolonAmount; i > 0; i--) {
9538
+ const insertIndex = i * 4;
9539
+ parts.splice(insertIndex, 0, ':');
9540
+ }
9541
+ address = parts.join('');
9542
+ return new Address6(address);
9543
+ }
9544
+ /**
9545
+ * Return the Microsoft UNC transcription of the address
9546
+ * @memberof Address6
9547
+ * @instance
9548
+ * @returns {String} the Microsoft UNC transcription of the address
9549
+ */
9550
+ microsoftTranscription() {
9551
+ return `${this.correctForm().replace(/:/g, '-')}.ipv6-literal.net`;
9552
+ }
9553
+ /**
9554
+ * Return the first n bits of the address, defaulting to the subnet mask
9555
+ * @memberof Address6
9556
+ * @instance
9557
+ * @param {number} [mask=subnet] - the number of bits to mask
9558
+ * @returns {String} the first n bits of the address as a string
9559
+ */
9560
+ mask(mask = this.subnetMask) {
9561
+ return this.getBitsBase2(0, mask);
9562
+ }
9563
+ /**
9564
+ * Return the number of possible subnets of a given size in the address
9565
+ * @memberof Address6
9566
+ * @instance
9567
+ * @param {number} [subnetSize=128] - the subnet size
9568
+ * @returns {String}
9569
+ */
9570
+ // TODO: probably useful to have a numeric version of this too
9571
+ possibleSubnets(subnetSize = 128) {
9572
+ const availableBits = constants6.BITS - this.subnetMask;
9573
+ const subnetBits = Math.abs(subnetSize - constants6.BITS);
9574
+ const subnetPowers = availableBits - subnetBits;
9575
+ if (subnetPowers < 0) {
9576
+ return '0';
9577
+ }
9578
+ return addCommas((BigInt('2') ** BigInt(subnetPowers)).toString(10));
9579
+ }
9580
+ /**
9581
+ * Helper function getting start address.
9582
+ * @memberof Address6
9583
+ * @instance
9584
+ * @returns {bigint}
9585
+ */
9586
+ _startAddress() {
9587
+ return BigInt(`0b${this.mask() + '0'.repeat(constants6.BITS - this.subnetMask)}`);
9588
+ }
9589
+ /**
9590
+ * The first address in the range given by this address' subnet
9591
+ * Often referred to as the Network Address.
9592
+ * @memberof Address6
9593
+ * @instance
9594
+ * @returns {Address6}
9595
+ */
9596
+ startAddress() {
9597
+ return Address6.fromBigInt(this._startAddress());
9598
+ }
9599
+ /**
9600
+ * The first host address in the range given by this address's subnet ie
9601
+ * the first address after the Network Address
9602
+ * @memberof Address6
9603
+ * @instance
9604
+ * @returns {Address6}
9605
+ */
9606
+ startAddressExclusive() {
9607
+ const adjust = BigInt('1');
9608
+ return Address6.fromBigInt(this._startAddress() + adjust);
9609
+ }
9610
+ /**
9611
+ * Helper function getting end address.
9612
+ * @memberof Address6
9613
+ * @instance
9614
+ * @returns {bigint}
9615
+ */
9616
+ _endAddress() {
9617
+ return BigInt(`0b${this.mask() + '1'.repeat(constants6.BITS - this.subnetMask)}`);
9618
+ }
9619
+ /**
9620
+ * The last address in the range given by this address' subnet
9621
+ * Often referred to as the Broadcast
9622
+ * @memberof Address6
9623
+ * @instance
9624
+ * @returns {Address6}
9625
+ */
9626
+ endAddress() {
9627
+ return Address6.fromBigInt(this._endAddress());
9628
+ }
9629
+ /**
9630
+ * The last host address in the range given by this address's subnet ie
9631
+ * the last address prior to the Broadcast Address
9632
+ * @memberof Address6
9633
+ * @instance
9634
+ * @returns {Address6}
9635
+ */
9636
+ endAddressExclusive() {
9637
+ const adjust = BigInt('1');
9638
+ return Address6.fromBigInt(this._endAddress() - adjust);
9639
+ }
9640
+ /**
9641
+ * Return the scope of the address
9642
+ * @memberof Address6
9643
+ * @instance
9644
+ * @returns {String}
9645
+ */
9646
+ getScope() {
9647
+ let scope = constants6.SCOPES[parseInt(this.getBits(12, 16).toString(10), 10)];
9648
+ if (this.getType() === 'Global unicast' && scope !== 'Link local') {
9649
+ scope = 'Global';
9650
+ }
9651
+ return scope || 'Unknown';
9652
+ }
9653
+ /**
9654
+ * Return the type of the address
9655
+ * @memberof Address6
9656
+ * @instance
9657
+ * @returns {String}
9658
+ */
9659
+ getType() {
9660
+ for (const subnet of Object.keys(constants6.TYPES)) {
9661
+ if (this.isInSubnet(new Address6(subnet))) {
9662
+ return constants6.TYPES[subnet];
9663
+ }
9664
+ }
9665
+ return 'Global unicast';
9666
+ }
9667
+ /**
9668
+ * Return the bits in the given range as a BigInt
9669
+ * @memberof Address6
9670
+ * @instance
9671
+ * @returns {bigint}
9672
+ */
9673
+ getBits(start, end) {
9674
+ return BigInt(`0b${this.getBitsBase2(start, end)}`);
9675
+ }
9676
+ /**
9677
+ * Return the bits in the given range as a base-2 string
9678
+ * @memberof Address6
9679
+ * @instance
9680
+ * @returns {String}
9681
+ */
9682
+ getBitsBase2(start, end) {
9683
+ return this.binaryZeroPad().slice(start, end);
9684
+ }
9685
+ /**
9686
+ * Return the bits in the given range as a base-16 string
9687
+ * @memberof Address6
9688
+ * @instance
9689
+ * @returns {String}
9690
+ */
9691
+ getBitsBase16(start, end) {
9692
+ const length = end - start;
9693
+ if (length % 4 !== 0) {
9694
+ throw new Error('Length of bits to retrieve must be divisible by four');
9695
+ }
9696
+ return this.getBits(start, end)
9697
+ .toString(16)
9698
+ .padStart(length / 4, '0');
9699
+ }
9700
+ /**
9701
+ * Return the bits that are set past the subnet mask length
9702
+ * @memberof Address6
9703
+ * @instance
9704
+ * @returns {String}
9705
+ */
9706
+ getBitsPastSubnet() {
9707
+ return this.getBitsBase2(this.subnetMask, constants6.BITS);
9708
+ }
9709
+ /**
9710
+ * Return the reversed ip6.arpa form of the address
9711
+ * @memberof Address6
9712
+ * @param {Object} options
9713
+ * @param {boolean} options.omitSuffix - omit the "ip6.arpa" suffix
9714
+ * @instance
9715
+ * @returns {String}
9716
+ */
9717
+ reverseForm(options) {
9718
+ if (!options) {
9719
+ options = {};
9720
+ }
9721
+ const characters = Math.floor(this.subnetMask / 4);
9722
+ const reversed = this.canonicalForm()
9723
+ .replace(/:/g, '')
9724
+ .split('')
9725
+ .slice(0, characters)
9726
+ .reverse()
9727
+ .join('.');
9728
+ if (characters > 0) {
9729
+ if (options.omitSuffix) {
9730
+ return reversed;
9731
+ }
9732
+ return `${reversed}.ip6.arpa.`;
9733
+ }
9734
+ if (options.omitSuffix) {
9735
+ return '';
9736
+ }
9737
+ return 'ip6.arpa.';
9738
+ }
9739
+ /**
9740
+ * Return the correct form of the address
9741
+ * @memberof Address6
9742
+ * @instance
9743
+ * @returns {String}
9744
+ */
9745
+ correctForm() {
9746
+ let i;
9747
+ let groups = [];
9748
+ let zeroCounter = 0;
9749
+ const zeroes = [];
9750
+ for (i = 0; i < this.parsedAddress.length; i++) {
9751
+ const value = parseInt(this.parsedAddress[i], 16);
9752
+ if (value === 0) {
9753
+ zeroCounter++;
9754
+ }
9755
+ if (value !== 0 && zeroCounter > 0) {
9756
+ if (zeroCounter > 1) {
9757
+ zeroes.push([i - zeroCounter, i - 1]);
9758
+ }
9759
+ zeroCounter = 0;
9760
+ }
9761
+ }
9762
+ // Do we end with a string of zeroes?
9763
+ if (zeroCounter > 1) {
9764
+ zeroes.push([this.parsedAddress.length - zeroCounter, this.parsedAddress.length - 1]);
9765
+ }
9766
+ const zeroLengths = zeroes.map((n) => n[1] - n[0] + 1);
9767
+ if (zeroes.length > 0) {
9768
+ const index = zeroLengths.indexOf(Math.max(...zeroLengths));
9769
+ groups = compact(this.parsedAddress, zeroes[index]);
9770
+ }
9771
+ else {
9772
+ groups = this.parsedAddress;
9773
+ }
9774
+ for (i = 0; i < groups.length; i++) {
9775
+ if (groups[i] !== 'compact') {
9776
+ groups[i] = parseInt(groups[i], 16).toString(16);
9777
+ }
9778
+ }
9779
+ let correct = groups.join(':');
9780
+ correct = correct.replace(/^compact$/, '::');
9781
+ correct = correct.replace(/(^compact)|(compact$)/, ':');
9782
+ correct = correct.replace(/compact/, '');
9783
+ return correct;
9784
+ }
9785
+ /**
9786
+ * Return a zero-padded base-2 string representation of the address
9787
+ * @memberof Address6
9788
+ * @instance
9789
+ * @returns {String}
9790
+ * @example
9791
+ * var address = new Address6('2001:4860:4001:803::1011');
9792
+ * address.binaryZeroPad();
9793
+ * // '0010000000000001010010000110000001000000000000010000100000000011
9794
+ * // 0000000000000000000000000000000000000000000000000001000000010001'
9795
+ */
9796
+ binaryZeroPad() {
9797
+ return this.bigInt().toString(2).padStart(constants6.BITS, '0');
9798
+ }
9799
+ // TODO: Improve the semantics of this helper function
9800
+ parse4in6(address) {
9801
+ const groups = address.split(':');
9802
+ const lastGroup = groups.slice(-1)[0];
9803
+ const address4 = lastGroup.match(constants4.RE_ADDRESS);
9804
+ if (address4) {
9805
+ this.parsedAddress4 = address4[0];
9806
+ this.address4 = new ipv4_1.Address4(this.parsedAddress4);
9807
+ for (let i = 0; i < this.address4.groups; i++) {
9808
+ if (/^0[0-9]+/.test(this.address4.parsedAddress[i])) {
9809
+ throw new address_error_1.AddressError("IPv4 addresses can't have leading zeroes.", address.replace(constants4.RE_ADDRESS, this.address4.parsedAddress.map(spanLeadingZeroes4).join('.')));
9810
+ }
9811
+ }
9812
+ this.v4 = true;
9813
+ groups[groups.length - 1] = this.address4.toGroup6();
9814
+ address = groups.join(':');
9815
+ }
9816
+ return address;
9817
+ }
9818
+ // TODO: Make private?
9819
+ parse(address) {
9820
+ address = this.parse4in6(address);
9821
+ const badCharacters = address.match(constants6.RE_BAD_CHARACTERS);
9822
+ if (badCharacters) {
9823
+ throw new address_error_1.AddressError(`Bad character${badCharacters.length > 1 ? 's' : ''} detected in address: ${badCharacters.join('')}`, address.replace(constants6.RE_BAD_CHARACTERS, '<span class="parse-error">$1</span>'));
9824
+ }
9825
+ const badAddress = address.match(constants6.RE_BAD_ADDRESS);
9826
+ if (badAddress) {
9827
+ throw new address_error_1.AddressError(`Address failed regex: ${badAddress.join('')}`, address.replace(constants6.RE_BAD_ADDRESS, '<span class="parse-error">$1</span>'));
9828
+ }
9829
+ let groups = [];
9830
+ const halves = address.split('::');
9831
+ if (halves.length === 2) {
9832
+ let first = halves[0].split(':');
9833
+ let last = halves[1].split(':');
9834
+ if (first.length === 1 && first[0] === '') {
9835
+ first = [];
9836
+ }
9837
+ if (last.length === 1 && last[0] === '') {
9838
+ last = [];
9839
+ }
9840
+ const remaining = this.groups - (first.length + last.length);
9841
+ if (!remaining) {
9842
+ throw new address_error_1.AddressError('Error parsing groups');
9843
+ }
9844
+ this.elidedGroups = remaining;
9845
+ this.elisionBegin = first.length;
9846
+ this.elisionEnd = first.length + this.elidedGroups;
9847
+ groups = groups.concat(first);
9848
+ for (let i = 0; i < remaining; i++) {
9849
+ groups.push('0');
9850
+ }
9851
+ groups = groups.concat(last);
9852
+ }
9853
+ else if (halves.length === 1) {
9854
+ groups = address.split(':');
9855
+ this.elidedGroups = 0;
9856
+ }
9857
+ else {
9858
+ throw new address_error_1.AddressError('Too many :: groups found');
9859
+ }
9860
+ groups = groups.map((group) => parseInt(group, 16).toString(16));
9861
+ if (groups.length !== this.groups) {
9862
+ throw new address_error_1.AddressError('Incorrect number of groups found');
9863
+ }
9864
+ return groups;
9865
+ }
9866
+ /**
9867
+ * Return the canonical form of the address
9868
+ * @memberof Address6
9869
+ * @instance
9870
+ * @returns {String}
9871
+ */
9872
+ canonicalForm() {
9873
+ return this.parsedAddress.map(paddedHex).join(':');
9874
+ }
9875
+ /**
9876
+ * Return the decimal form of the address
9877
+ * @memberof Address6
9878
+ * @instance
9879
+ * @returns {String}
9880
+ */
9881
+ decimal() {
9882
+ return this.parsedAddress.map((n) => parseInt(n, 16).toString(10).padStart(5, '0')).join(':');
9883
+ }
9884
+ /**
9885
+ * Return the address as a BigInt
9886
+ * @memberof Address6
9887
+ * @instance
9888
+ * @returns {bigint}
9889
+ */
9890
+ bigInt() {
9891
+ return BigInt(`0x${this.parsedAddress.map(paddedHex).join('')}`);
9892
+ }
9893
+ /**
9894
+ * Return the last two groups of this address as an IPv4 address string
9895
+ * @memberof Address6
9896
+ * @instance
9897
+ * @returns {Address4}
9898
+ * @example
9899
+ * var address = new Address6('2001:4860:4001::1825:bf11');
9900
+ * address.to4().correctForm(); // '24.37.191.17'
9901
+ */
9902
+ to4() {
9903
+ const binary = this.binaryZeroPad().split('');
9904
+ return ipv4_1.Address4.fromHex(BigInt(`0b${binary.slice(96, 128).join('')}`).toString(16));
9905
+ }
9906
+ /**
9907
+ * Return the v4-in-v6 form of the address
9908
+ * @memberof Address6
9909
+ * @instance
9910
+ * @returns {String}
9911
+ */
9912
+ to4in6() {
9913
+ const address4 = this.to4();
9914
+ const address6 = new Address6(this.parsedAddress.slice(0, 6).join(':'), 6);
9915
+ const correct = address6.correctForm();
9916
+ let infix = '';
9917
+ if (!/:$/.test(correct)) {
9918
+ infix = ':';
9919
+ }
9920
+ return correct + infix + address4.address;
9921
+ }
9922
+ /**
9923
+ * Return an object containing the Teredo properties of the address
9924
+ * @memberof Address6
9925
+ * @instance
9926
+ * @returns {Object}
9927
+ */
9928
+ inspectTeredo() {
9929
+ /*
9930
+ - Bits 0 to 31 are set to the Teredo prefix (normally 2001:0000::/32).
9931
+ - Bits 32 to 63 embed the primary IPv4 address of the Teredo server that
9932
+ is used.
9933
+ - Bits 64 to 79 can be used to define some flags. Currently only the
9934
+ higher order bit is used; it is set to 1 if the Teredo client is
9935
+ located behind a cone NAT, 0 otherwise. For Microsoft's Windows Vista
9936
+ and Windows Server 2008 implementations, more bits are used. In those
9937
+ implementations, the format for these 16 bits is "CRAAAAUG AAAAAAAA",
9938
+ where "C" remains the "Cone" flag. The "R" bit is reserved for future
9939
+ use. The "U" bit is for the Universal/Local flag (set to 0). The "G" bit
9940
+ is Individual/Group flag (set to 0). The A bits are set to a 12-bit
9941
+ randomly generated number chosen by the Teredo client to introduce
9942
+ additional protection for the Teredo node against IPv6-based scanning
9943
+ attacks.
9944
+ - Bits 80 to 95 contains the obfuscated UDP port number. This is the
9945
+ port number that is mapped by the NAT to the Teredo client with all
9946
+ bits inverted.
9947
+ - Bits 96 to 127 contains the obfuscated IPv4 address. This is the
9948
+ public IPv4 address of the NAT with all bits inverted.
9949
+ */
9950
+ const prefix = this.getBitsBase16(0, 32);
9951
+ const bitsForUdpPort = this.getBits(80, 96);
9952
+ // eslint-disable-next-line no-bitwise
9953
+ const udpPort = (bitsForUdpPort ^ BigInt('0xffff')).toString();
9954
+ const server4 = ipv4_1.Address4.fromHex(this.getBitsBase16(32, 64));
9955
+ const bitsForClient4 = this.getBits(96, 128);
9956
+ // eslint-disable-next-line no-bitwise
9957
+ const client4 = ipv4_1.Address4.fromHex((bitsForClient4 ^ BigInt('0xffffffff')).toString(16));
9958
+ const flagsBase2 = this.getBitsBase2(64, 80);
9959
+ const coneNat = (0, common_1.testBit)(flagsBase2, 15);
9960
+ const reserved = (0, common_1.testBit)(flagsBase2, 14);
9961
+ const groupIndividual = (0, common_1.testBit)(flagsBase2, 8);
9962
+ const universalLocal = (0, common_1.testBit)(flagsBase2, 9);
9963
+ const nonce = BigInt(`0b${flagsBase2.slice(2, 6) + flagsBase2.slice(8, 16)}`).toString(10);
9964
+ return {
9965
+ prefix: `${prefix.slice(0, 4)}:${prefix.slice(4, 8)}`,
9966
+ server4: server4.address,
9967
+ client4: client4.address,
9968
+ flags: flagsBase2,
9969
+ coneNat,
9970
+ microsoft: {
9971
+ reserved,
9972
+ universalLocal,
9973
+ groupIndividual,
9974
+ nonce,
9975
+ },
9976
+ udpPort,
9977
+ };
9978
+ }
9979
+ /**
9980
+ * Return an object containing the 6to4 properties of the address
9981
+ * @memberof Address6
9982
+ * @instance
9983
+ * @returns {Object}
9984
+ */
9985
+ inspect6to4() {
9986
+ /*
9987
+ - Bits 0 to 15 are set to the 6to4 prefix (2002::/16).
9988
+ - Bits 16 to 48 embed the IPv4 address of the 6to4 gateway that is used.
9989
+ */
9990
+ const prefix = this.getBitsBase16(0, 16);
9991
+ const gateway = ipv4_1.Address4.fromHex(this.getBitsBase16(16, 48));
9992
+ return {
9993
+ prefix: prefix.slice(0, 4),
9994
+ gateway: gateway.address,
9995
+ };
9996
+ }
9997
+ /**
9998
+ * Return a v6 6to4 address from a v6 v4inv6 address
9999
+ * @memberof Address6
10000
+ * @instance
10001
+ * @returns {Address6}
10002
+ */
10003
+ to6to4() {
10004
+ if (!this.is4()) {
10005
+ return null;
10006
+ }
10007
+ const addr6to4 = [
10008
+ '2002',
10009
+ this.getBitsBase16(96, 112),
10010
+ this.getBitsBase16(112, 128),
10011
+ '',
10012
+ '/16',
10013
+ ].join(':');
10014
+ return new Address6(addr6to4);
10015
+ }
10016
+ /**
10017
+ * Return a byte array
10018
+ * @memberof Address6
10019
+ * @instance
10020
+ * @returns {Array}
10021
+ */
10022
+ toByteArray() {
10023
+ const valueWithoutPadding = this.bigInt().toString(16);
10024
+ const leadingPad = '0'.repeat(valueWithoutPadding.length % 2);
10025
+ const value = `${leadingPad}${valueWithoutPadding}`;
10026
+ const bytes = [];
10027
+ for (let i = 0, length = value.length; i < length; i += 2) {
10028
+ bytes.push(parseInt(value.substring(i, i + 2), 16));
10029
+ }
10030
+ return bytes;
10031
+ }
10032
+ /**
10033
+ * Return an unsigned byte array
10034
+ * @memberof Address6
10035
+ * @instance
10036
+ * @returns {Array}
10037
+ */
10038
+ toUnsignedByteArray() {
10039
+ return this.toByteArray().map(unsignByte);
10040
+ }
10041
+ /**
10042
+ * Convert a byte array to an Address6 object
10043
+ * @memberof Address6
10044
+ * @static
10045
+ * @returns {Address6}
10046
+ */
10047
+ static fromByteArray(bytes) {
10048
+ return this.fromUnsignedByteArray(bytes.map(unsignByte));
10049
+ }
10050
+ /**
10051
+ * Convert an unsigned byte array to an Address6 object
10052
+ * @memberof Address6
10053
+ * @static
10054
+ * @returns {Address6}
10055
+ */
10056
+ static fromUnsignedByteArray(bytes) {
10057
+ const BYTE_MAX = BigInt('256');
10058
+ let result = BigInt('0');
10059
+ let multiplier = BigInt('1');
10060
+ for (let i = bytes.length - 1; i >= 0; i--) {
10061
+ result += multiplier * BigInt(bytes[i].toString(10));
10062
+ multiplier *= BYTE_MAX;
10063
+ }
10064
+ return Address6.fromBigInt(result);
10065
+ }
10066
+ /**
10067
+ * Returns true if the address is in the canonical form, false otherwise
10068
+ * @memberof Address6
10069
+ * @instance
10070
+ * @returns {boolean}
10071
+ */
10072
+ isCanonical() {
10073
+ return this.addressMinusSuffix === this.canonicalForm();
10074
+ }
10075
+ /**
10076
+ * Returns true if the address is a link local address, false otherwise
10077
+ * @memberof Address6
10078
+ * @instance
10079
+ * @returns {boolean}
10080
+ */
10081
+ isLinkLocal() {
10082
+ // Zeroes are required, i.e. we can't check isInSubnet with 'fe80::/10'
10083
+ if (this.getBitsBase2(0, 64) ===
10084
+ '1111111010000000000000000000000000000000000000000000000000000000') {
10085
+ return true;
10086
+ }
10087
+ return false;
10088
+ }
10089
+ /**
10090
+ * Returns true if the address is a multicast address, false otherwise
10091
+ * @memberof Address6
10092
+ * @instance
10093
+ * @returns {boolean}
10094
+ */
10095
+ isMulticast() {
10096
+ return this.getType() === 'Multicast';
10097
+ }
10098
+ /**
10099
+ * Returns true if the address is a v4-in-v6 address, false otherwise
10100
+ * @memberof Address6
10101
+ * @instance
10102
+ * @returns {boolean}
10103
+ */
10104
+ is4() {
10105
+ return this.v4;
10106
+ }
10107
+ /**
10108
+ * Returns true if the address is a Teredo address, false otherwise
10109
+ * @memberof Address6
10110
+ * @instance
10111
+ * @returns {boolean}
10112
+ */
10113
+ isTeredo() {
10114
+ return this.isInSubnet(new Address6('2001::/32'));
10115
+ }
10116
+ /**
10117
+ * Returns true if the address is a 6to4 address, false otherwise
10118
+ * @memberof Address6
10119
+ * @instance
10120
+ * @returns {boolean}
10121
+ */
10122
+ is6to4() {
10123
+ return this.isInSubnet(new Address6('2002::/16'));
10124
+ }
10125
+ /**
10126
+ * Returns true if the address is a loopback address, false otherwise
10127
+ * @memberof Address6
10128
+ * @instance
10129
+ * @returns {boolean}
10130
+ */
10131
+ isLoopback() {
10132
+ return this.getType() === 'Loopback';
10133
+ }
10134
+ // #endregion
10135
+ // #region HTML
10136
+ /**
10137
+ * @returns {String} the address in link form with a default port of 80
10138
+ */
10139
+ href(optionalPort) {
10140
+ if (optionalPort === undefined) {
10141
+ optionalPort = '';
10142
+ }
10143
+ else {
10144
+ optionalPort = `:${optionalPort}`;
10145
+ }
10146
+ return `http://[${this.correctForm()}]${optionalPort}/`;
10147
+ }
10148
+ /**
10149
+ * @returns {String} a link suitable for conveying the address via a URL hash
10150
+ */
10151
+ link(options) {
10152
+ if (!options) {
10153
+ options = {};
10154
+ }
10155
+ if (options.className === undefined) {
10156
+ options.className = '';
10157
+ }
10158
+ if (options.prefix === undefined) {
10159
+ options.prefix = '/#address=';
10160
+ }
10161
+ if (options.v4 === undefined) {
10162
+ options.v4 = false;
10163
+ }
10164
+ let formFunction = this.correctForm;
10165
+ if (options.v4) {
10166
+ formFunction = this.to4in6;
10167
+ }
10168
+ const form = formFunction.call(this);
10169
+ if (options.className) {
10170
+ return `<a href="${options.prefix}${form}" class="${options.className}">${form}</a>`;
10171
+ }
10172
+ return `<a href="${options.prefix}${form}">${form}</a>`;
10173
+ }
10174
+ /**
10175
+ * Groups an address
10176
+ * @returns {String}
10177
+ */
10178
+ group() {
10179
+ if (this.elidedGroups === 0) {
10180
+ // The simple case
10181
+ return helpers.simpleGroup(this.address).join(':');
10182
+ }
10183
+ assert(typeof this.elidedGroups === 'number');
10184
+ assert(typeof this.elisionBegin === 'number');
10185
+ // The elided case
10186
+ const output = [];
10187
+ const [left, right] = this.address.split('::');
10188
+ if (left.length) {
10189
+ output.push(...helpers.simpleGroup(left));
10190
+ }
10191
+ else {
10192
+ output.push('');
10193
+ }
10194
+ const classes = ['hover-group'];
10195
+ for (let i = this.elisionBegin; i < this.elisionBegin + this.elidedGroups; i++) {
10196
+ classes.push(`group-${i}`);
10197
+ }
10198
+ output.push(`<span class="${classes.join(' ')}"></span>`);
10199
+ if (right.length) {
10200
+ output.push(...helpers.simpleGroup(right, this.elisionEnd));
10201
+ }
10202
+ else {
10203
+ output.push('');
10204
+ }
10205
+ if (this.is4()) {
10206
+ assert(this.address4 instanceof ipv4_1.Address4);
10207
+ output.pop();
10208
+ output.push(this.address4.groupForV6());
10209
+ }
10210
+ return output.join(':');
10211
+ }
10212
+ // #endregion
10213
+ // #region Regular expressions
10214
+ /**
10215
+ * Generate a regular expression string that can be used to find or validate
10216
+ * all variations of this address
10217
+ * @memberof Address6
10218
+ * @instance
10219
+ * @param {boolean} substringSearch
10220
+ * @returns {string}
10221
+ */
10222
+ regularExpressionString(substringSearch = false) {
10223
+ let output = [];
10224
+ // TODO: revisit why this is necessary
10225
+ const address6 = new Address6(this.correctForm());
10226
+ if (address6.elidedGroups === 0) {
10227
+ // The simple case
10228
+ output.push((0, regular_expressions_1.simpleRegularExpression)(address6.parsedAddress));
10229
+ }
10230
+ else if (address6.elidedGroups === constants6.GROUPS) {
10231
+ // A completely elided address
10232
+ output.push((0, regular_expressions_1.possibleElisions)(constants6.GROUPS));
10233
+ }
10234
+ else {
10235
+ // A partially elided address
10236
+ const halves = address6.address.split('::');
10237
+ if (halves[0].length) {
10238
+ output.push((0, regular_expressions_1.simpleRegularExpression)(halves[0].split(':')));
10239
+ }
10240
+ assert(typeof address6.elidedGroups === 'number');
10241
+ output.push((0, regular_expressions_1.possibleElisions)(address6.elidedGroups, halves[0].length !== 0, halves[1].length !== 0));
10242
+ if (halves[1].length) {
10243
+ output.push((0, regular_expressions_1.simpleRegularExpression)(halves[1].split(':')));
10244
+ }
10245
+ output = [output.join(':')];
10246
+ }
10247
+ if (!substringSearch) {
10248
+ output = [
10249
+ '(?=^|',
10250
+ regular_expressions_1.ADDRESS_BOUNDARY,
10251
+ '|[^\\w\\:])(',
10252
+ ...output,
10253
+ ')(?=[^\\w\\:]|',
10254
+ regular_expressions_1.ADDRESS_BOUNDARY,
10255
+ '|$)',
10256
+ ];
10257
+ }
10258
+ return output.join('');
10259
+ }
10260
+ /**
10261
+ * Generate a regular expression that can be used to find or validate all
10262
+ * variations of this address.
10263
+ * @memberof Address6
10264
+ * @instance
10265
+ * @param {boolean} substringSearch
10266
+ * @returns {RegExp}
10267
+ */
10268
+ regularExpression(substringSearch = false) {
10269
+ return new RegExp(this.regularExpressionString(substringSearch), 'i');
10270
+ }
10271
+ }
10272
+ ipv6.Address6 = Address6;
10273
+
10274
+ (function (exports) {
10275
+ var __createBinding = (commonjsGlobal && commonjsGlobal.__createBinding) || (Object.create ? (function(o, m, k, k2) {
10276
+ if (k2 === undefined) k2 = k;
10277
+ var desc = Object.getOwnPropertyDescriptor(m, k);
10278
+ if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
10279
+ desc = { enumerable: true, get: function() { return m[k]; } };
10280
+ }
10281
+ Object.defineProperty(o, k2, desc);
10282
+ }) : (function(o, m, k, k2) {
10283
+ if (k2 === undefined) k2 = k;
10284
+ o[k2] = m[k];
10285
+ }));
10286
+ var __setModuleDefault = (commonjsGlobal && commonjsGlobal.__setModuleDefault) || (Object.create ? (function(o, v) {
10287
+ Object.defineProperty(o, "default", { enumerable: true, value: v });
10288
+ }) : function(o, v) {
10289
+ o["default"] = v;
10290
+ });
10291
+ var __importStar = (commonjsGlobal && commonjsGlobal.__importStar) || function (mod) {
10292
+ if (mod && mod.__esModule) return mod;
10293
+ var result = {};
10294
+ if (mod != null) for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k);
10295
+ __setModuleDefault(result, mod);
10296
+ return result;
10297
+ };
10298
+ Object.defineProperty(exports, "__esModule", { value: true });
10299
+ exports.v6 = exports.AddressError = exports.Address6 = exports.Address4 = void 0;
10300
+ var ipv4_1 = ipv4;
10301
+ Object.defineProperty(exports, "Address4", { enumerable: true, get: function () { return ipv4_1.Address4; } });
10302
+ var ipv6_1 = ipv6;
10303
+ Object.defineProperty(exports, "Address6", { enumerable: true, get: function () { return ipv6_1.Address6; } });
10304
+ var address_error_1 = addressError;
10305
+ Object.defineProperty(exports, "AddressError", { enumerable: true, get: function () { return address_error_1.AddressError; } });
10306
+ const helpers = __importStar(helpers$1);
10307
+ exports.v6 = { helpers };
10308
+
10309
+ } (ipAddress));
10310
+
10311
+ const _ = "https://fkn.app", l = globalThis?.document.querySelector(`iframe[src="${_}/api"]`), c = globalThis.document?.createElement("iframe");
10312
+ !l && c && (c.src = `${_}/api`, c.style.display = "none", document.body.appendChild(c));
10313
+ const w = l || c, z = w.contentWindow;
10314
+ if (!w.contentWindow)
10315
+ throw new Error("Missing iframe content window");
10316
+ const C = () => new Promise((r, e) => {
10317
+ ee({}, { key: "fkn-api", local: window, remote: z }).then(r).catch(e), setTimeout(() => {
10318
+ e(new Error("Timeout waiting for api to be exposed"));
10319
+ }, 50);
10320
+ }), P = () => C().then((r) => r).catch((r) => {
10321
+ if (r.message === "Timeout waiting for api to be exposed")
10322
+ return P();
10323
+ throw r;
10324
+ }), a = P(), I = new TextEncoder();
10325
+ new TextDecoder();
10326
+ const b = (...r) => {
10327
+ if (typeof r[0] == "string")
10612
10328
  throw new Error("FKN WebVPN does not support IPC connections");
10613
- if (args.length === 2 && typeof args[0] === "number" && typeof args[1] === "function") {
10614
- throw new Error("FKN WebVPN does not support local TCP connections");
10615
- }
10616
- let connectionListener = () => {
10329
+ const e = typeof r.at(-1) == "function" ? r.at(-1) : void 0;
10330
+ return r[0] && typeof r[0] == "object" ? {
10331
+ ...r[0],
10332
+ callback: e
10333
+ } : {
10334
+ port: r[0] ?? 0,
10335
+ host: typeof r[1] == "string" ? r[1] : "localhost",
10336
+ callback: e
10617
10337
  };
10618
- if (typeof args[args.length - 1] === "function") {
10619
- connectionListener = args.pop();
10620
- }
10621
- let port;
10622
- let host;
10623
- if (args.length === 2) {
10624
- port = args[0];
10625
- host = "localhost";
10338
+ }, R = (...r) => {
10339
+ const e = typeof r.at(-1) == "function" ? r.at(-1) : void 0, t = r[0] ?? 0, o = typeof r[1] == "string" ? r[1] : "localhost";
10340
+ return typeof r[0] == "object" ? {
10341
+ ...r[0],
10342
+ address: r[0].address ?? o,
10343
+ port: r[0].port ?? t,
10344
+ callback: e
10345
+ } : {
10346
+ address: o,
10347
+ port: t,
10348
+ callback: e
10349
+ };
10350
+ }, D = (...r) => {
10351
+ const e = typeof r.at(-1) == "function" ? r.at(-1) : void 0, t = r[0];
10352
+ if (typeof r[2] == "number") {
10353
+ const o = r[1], s = r[2], n = typeof r[3] == "number" ? r[3] : 0, i = typeof r[4] == "string" ? r[4] : "localhost";
10354
+ return {
10355
+ message: t,
10356
+ offset: o,
10357
+ length: s,
10358
+ port: n,
10359
+ address: i,
10360
+ callback: e
10361
+ };
10626
10362
  } else {
10627
- port = args[0];
10628
- host = args[1];
10363
+ const o = typeof r[1] == "number" ? r[1] : 0, s = typeof r[2] == "string" ? r[2] : "localhost";
10364
+ return {
10365
+ message: t,
10366
+ offset: 0,
10367
+ length: t.length,
10368
+ port: o,
10369
+ address: s,
10370
+ callback: e
10371
+ };
10629
10372
  }
10630
- return {
10631
- port,
10632
- host,
10633
- connectionListener
10634
- };
10635
10373
  };
10636
- class Socket extends streamBrowserify.Stream.Duplex {
10637
- constructor(options) {
10638
- console.log("new socket");
10639
- if (typeof options === "number")
10640
- options = { fd: options };
10641
- else
10642
- options = { ...options };
10643
- if (options?.fd !== void 0)
10374
+ class d extends streamBrowserify.Stream.Duplex {
10375
+ _localAddress;
10376
+ _remoteAddress;
10377
+ _webVPNTcpSocketPromise;
10378
+ constructor(e) {
10379
+ if (e?.fd !== void 0)
10644
10380
  throw new Error("FKN WebVPN does not support file descriptors");
10645
- if (options?.handle !== void 0)
10646
- throw new Error("FKN WebVPN does not support handle");
10647
- super(options);
10381
+ super(e), e?.connection && this.__webvpn_tcp_socket_init__(e.connection);
10648
10382
  }
10649
- _construct(callback) {
10650
- console.log("constructing");
10651
- this.webVPNPromise.then(() => callback());
10383
+ __webvpn_tcp_socket_init__(e) {
10384
+ if (this._webVPNTcpSocketPromise = e.then((t) => {
10385
+ const o = t.dataReadableStream.getReader(), s = t.dataWritableStream.getWriter();
10386
+ return this._localAddress = {
10387
+ address: t.localAddress,
10388
+ family: t.localFamily,
10389
+ port: t.localPort
10390
+ }, this._remoteAddress = {
10391
+ address: t.remoteAddress,
10392
+ family: t.remoteFamily,
10393
+ port: t.remotePort
10394
+ }, {
10395
+ ...t,
10396
+ reader: o,
10397
+ writer: s
10398
+ };
10399
+ }).catch((t) => {
10400
+ this.emit("error", t);
10401
+ }), !this._webVPNTcpSocketPromise)
10402
+ throw new Error("Socket not connected");
10403
+ return this._webVPNTcpSocketPromise.then((t) => {
10404
+ !t || this.emit("connect");
10405
+ }), this._webVPNTcpSocketPromise;
10652
10406
  }
10653
- _read(size) {
10654
- this.webVPNPromise.then(
10655
- (webVPN) => webVPN.readData().then((data) => this.push(data))
10656
- );
10407
+ _read(e) {
10408
+ if (!this._webVPNTcpSocketPromise)
10409
+ throw new Error("Socket not connected");
10410
+ this._webVPNTcpSocketPromise.then((t) => {
10411
+ if (!t)
10412
+ throw new Error("Socket not connected");
10413
+ t.reader.read().then(({ value: o, done: s }) => {
10414
+ if (s) {
10415
+ this.push(null);
10416
+ return;
10417
+ }
10418
+ this.push(o);
10419
+ }).catch((o) => {
10420
+ this.emit("error", o), this.destroy(o);
10421
+ });
10422
+ });
10657
10423
  }
10658
- _write(chunk, encoding, callback) {
10659
- this.webVPNPromise.then(
10660
- (webVPN) => webVPN.writeData(chunk).then(() => callback()).catch((err) => callback(err))
10424
+ _write(e, t, o) {
10425
+ if (!this._webVPNTcpSocketPromise)
10426
+ throw new Error("Socket not connected");
10427
+ this._webVPNTcpSocketPromise.then((s) => {
10428
+ if (!s)
10429
+ throw new Error("Socket not connected");
10430
+ s.writer.write(e), o && o();
10431
+ });
10432
+ }
10433
+ connect(...e) {
10434
+ const t = b(...e), o = this.__webvpn_tcp_socket_init__(
10435
+ a.then(
10436
+ (s) => s.WEBVPN_TCP_SOCKET({
10437
+ remoteAddress: t.host,
10438
+ remotePort: t.port
10439
+ })
10440
+ )
10661
10441
  );
10442
+ return t.callback && o.then((s) => {
10443
+ !s || t.callback();
10444
+ }), this;
10662
10445
  }
10663
- _destroy(error, callback) {
10664
- this.webVPNPromise.then((webVPN) => {
10665
- webVPN.close();
10666
- callback(error);
10667
- });
10446
+ _end(...e) {
10447
+ return this._webVPNTcpSocketPromise ? (e.length !== 0 && this.write(e[0], e[1], e[2]), this._webVPNTcpSocketPromise.then(async (t) => {
10448
+ !t || await t.end();
10449
+ }), this) : this;
10668
10450
  }
10669
- _final(callback) {
10670
- this.webVPNPromise.then((webVPN) => {
10671
- webVPN.close();
10672
- callback();
10673
- });
10451
+ _destroy(e) {
10452
+ return this._webVPNTcpSocketPromise ? (this._webVPNTcpSocketPromise.then(async (t) => {
10453
+ !t || await t.destroy();
10454
+ }), this) : this;
10674
10455
  }
10675
- connect(...args) {
10676
- const { port, host, connectionListener } = normalizeConnectArgs(args);
10677
- this.webVPNPromise = makeWebVPN({ host, port }).then((webVPN) => {
10678
- this.webVPN = webVPN;
10679
- this._host = webVPN.host;
10680
- this._port = webVPN.port;
10681
- this.remoteAddress = webVPN.remoteAddress;
10682
- this.remoteFamily = webVPN.remoteFamily;
10683
- this.remotePort = webVPN.remotePort;
10684
- this.localAddress = webVPN.localAddress;
10685
- this.localPort = webVPN.localPort;
10686
- webVPN.webtransport.closed.then(() => this.destroy());
10687
- connectionListener?.();
10688
- this.emit("connect");
10689
- return webVPN;
10690
- }).catch((err) => {
10691
- this.destroy(err);
10692
- throw err;
10456
+ destroySoon() {
10457
+ !this._webVPNTcpSocketPromise || this._webVPNTcpSocketPromise.then(async (e) => {
10458
+ !e || await e.destroySoon();
10693
10459
  });
10460
+ }
10461
+ resetAndDestroy() {
10462
+ return this._webVPNTcpSocketPromise ? (this._webVPNTcpSocketPromise.then(async (e) => {
10463
+ !e || await e.resetAndDestroy();
10464
+ }), this) : this;
10465
+ }
10466
+ setTimeout(e, t) {
10694
10467
  return this;
10695
10468
  }
10696
- ref() {
10469
+ setNoDelay(e) {
10470
+ return this;
10471
+ }
10472
+ setKeepAlive(e, t) {
10473
+ return this;
10474
+ }
10475
+ write(e, t, ...o) {
10476
+ return super.write(e, t, ...o);
10477
+ }
10478
+ address() {
10479
+ return this._localAddress ?? {};
10697
10480
  }
10698
10481
  unref() {
10482
+ return this;
10483
+ }
10484
+ ref() {
10485
+ return this;
10486
+ }
10487
+ autoSelectFamilyAttemptedAddresses;
10488
+ bufferSize;
10489
+ bytesRead;
10490
+ bytesWritten;
10491
+ connecting;
10492
+ pending;
10493
+ get localAddress() {
10494
+ if (!this._localAddress)
10495
+ throw new Error("Socket is not connected");
10496
+ return this._localAddress.address;
10497
+ }
10498
+ get localPort() {
10499
+ if (!this._localAddress)
10500
+ throw new Error("Socket is not connected");
10501
+ return this._localAddress.port;
10502
+ }
10503
+ get localFamily() {
10504
+ if (!this._localAddress)
10505
+ throw new Error("Socket is not connected");
10506
+ return this._localAddress.family;
10507
+ }
10508
+ readyState;
10509
+ get remoteAddress() {
10510
+ if (!this._remoteAddress)
10511
+ throw new Error("Socket is not connected");
10512
+ return this._remoteAddress.address;
10513
+ }
10514
+ get remotePort() {
10515
+ if (!this._remoteAddress)
10516
+ throw new Error("Socket is not connected");
10517
+ return this._remoteAddress.port;
10518
+ }
10519
+ get remoteFamily() {
10520
+ if (!this._remoteAddress)
10521
+ throw new Error("Socket is not connected");
10522
+ return this._remoteAddress.family;
10523
+ }
10524
+ timeout;
10525
+ }
10526
+ class E extends eventsExports.EventEmitter {
10527
+ _type;
10528
+ _localAddress;
10529
+ _remoteAddress;
10530
+ _webVPNUdpSocketPromise;
10531
+ constructor(e) {
10532
+ if (super(e), !e)
10533
+ throw new Error("Missing options");
10534
+ this._type = e.type;
10535
+ }
10536
+ addMembership(e, t) {
10699
10537
  }
10700
10538
  address() {
10539
+ if (!this._localAddress)
10540
+ throw new Error("EBADF");
10541
+ return this._localAddress;
10542
+ }
10543
+ bind(...e) {
10544
+ const t = R(...e);
10545
+ return this._webVPNUdpSocketPromise = a.then(
10546
+ (o) => o.WEBVPN_UDP_SOCKET({
10547
+ type: this._type,
10548
+ address: t.address,
10549
+ port: t.port
10550
+ })
10551
+ ).then((o) => {
10552
+ const s = o.dataReadableStream.getReader(), n = async () => {
10553
+ const { value: i, done: N } = await s.read();
10554
+ N || (this.emit("message", {
10555
+ data: i.data,
10556
+ rinfo: {
10557
+ address: i.address,
10558
+ family: i.family,
10559
+ port: i.port,
10560
+ size: i.size
10561
+ }
10562
+ }), n());
10563
+ };
10564
+ return n(), this._localAddress = {
10565
+ address: o.localAddress,
10566
+ family: o.localFamily,
10567
+ port: o.localPort
10568
+ }, o;
10569
+ }).catch((o) => {
10570
+ this.emit("error", o);
10571
+ }), this._webVPNUdpSocketPromise.then((o) => {
10572
+ !o || this.emit("listening");
10573
+ }), t.callback && this._webVPNUdpSocketPromise.then((o) => {
10574
+ !o || t.callback();
10575
+ }), this;
10576
+ }
10577
+ close(e) {
10578
+ if (!this._webVPNUdpSocketPromise)
10579
+ throw new Error("Socket not bound");
10580
+ return this._webVPNUdpSocketPromise.then(async (t) => {
10581
+ if (!t)
10582
+ throw new Error("Socket not bound");
10583
+ await t.close(), e && e(), this.emit("close");
10584
+ }), this;
10585
+ }
10586
+ connect(...e) {
10587
+ if (!this._webVPNUdpSocketPromise)
10588
+ throw new Error("Socket not bound");
10589
+ this._webVPNUdpSocketPromise.then(async (t) => {
10590
+ if (!t)
10591
+ throw new Error("Socket not bound");
10592
+ const o = e[0], s = typeof e[1] == "string" ? e[1] : "localhost", n = typeof e.at(-1) == "function" ? e.at(-1) : void 0;
10593
+ await t.connect({ remotePort: o, remoteAddress: s }), n && n();
10594
+ });
10595
+ }
10596
+ disconnect() {
10597
+ if (!this._webVPNUdpSocketPromise)
10598
+ throw new Error("Socket not bound");
10599
+ this._webVPNUdpSocketPromise.then(async (e) => {
10600
+ if (!e)
10601
+ throw new Error("Socket not bound");
10602
+ await e.connect({ remotePort: 0, remoteAddress: this._type === "udp4" ? "0.0.0.0" : "::" });
10603
+ });
10604
+ }
10605
+ dropMembership(e, t) {
10606
+ }
10607
+ getRecvBufferSize() {
10608
+ return 0;
10609
+ }
10610
+ getSendBufferSize() {
10611
+ return 0;
10612
+ }
10613
+ getSendQueueSize() {
10614
+ return 0;
10615
+ }
10616
+ getSendQueueCount() {
10617
+ return 0;
10618
+ }
10619
+ ref() {
10620
+ return this;
10621
+ }
10622
+ remoteAddress() {
10623
+ if (!this._remoteAddress)
10624
+ throw new Error("ERR_SOCKET_DGRAM_NOT_CONNECTED");
10701
10625
  return {
10702
- port: 0,
10703
- family: "IPv4",
10704
- address: ""
10626
+ address: this._remoteAddress.address,
10627
+ family: this._remoteAddress.family,
10628
+ port: this._remoteAddress.port
10705
10629
  };
10706
10630
  }
10707
- setKeepAlive() {
10631
+ send(...e) {
10632
+ this._webVPNUdpSocketPromise || this.bind();
10633
+ const t = D(...e);
10634
+ if (!this._webVPNUdpSocketPromise)
10635
+ throw new Error("Socket not bound");
10636
+ this._webVPNUdpSocketPromise.then((o) => {
10637
+ if (!o)
10638
+ throw new Error("Socket not bound");
10639
+ const s = typeof t.message == "string" ? I.encode(t.message) : t.message;
10640
+ o.send({
10641
+ ...t,
10642
+ message: s.buffer
10643
+ });
10644
+ });
10708
10645
  }
10709
- setNoDelay() {
10646
+ setBroadcast(e) {
10710
10647
  }
10711
- setTimeout() {
10648
+ setMulticastInterface(e) {
10712
10649
  }
10713
- static connect() {
10650
+ setMulticastLoopback(e) {
10651
+ return !0;
10714
10652
  }
10715
- static createConnection() {
10653
+ setMulticastTTL(e) {
10654
+ return e;
10716
10655
  }
10717
- static isIP() {
10656
+ setRecvBufferSize(e) {
10718
10657
  }
10719
- static isIPv4() {
10658
+ setSendBufferSize(e) {
10720
10659
  }
10721
- static isIPv6() {
10660
+ setTTL(e) {
10661
+ return e;
10722
10662
  }
10723
- static createServer() {
10663
+ unref() {
10664
+ return this;
10724
10665
  }
10725
- static createSecureServer() {
10666
+ addSourceSpecificMembership(e, t, o) {
10726
10667
  }
10727
- }
10728
- class Server extends eventsExports.EventEmitter {
10729
- constructor() {
10730
- super();
10668
+ dropSourceSpecificMembership(e, t, o) {
10731
10669
  }
10732
- listen(port) {
10733
- console.log(`Server is listening on port ${port}`);
10670
+ async [Symbol.asyncDispose]() {
10671
+ await new Promise((e) => {
10672
+ this.close(e);
10673
+ });
10734
10674
  }
10735
10675
  }
10736
- const connect = (options, connectionListener) => {
10737
- console.log("connect");
10738
- const socket = new Socket();
10739
- socket.connect(options, connectionListener);
10740
- return socket;
10741
- };
10742
- const createConnection = (options, connectionListener) => {
10743
- console.log("createConnection");
10744
- const socket = new Socket();
10745
- socket.connect(options, connectionListener);
10746
- return socket;
10747
- };
10748
- const createServer = () => {
10749
- console.log("createServer");
10750
- return new Server();
10751
- };
10752
- const createSecureServer = () => {
10753
- console.log("createSecureServer");
10754
- return new Server();
10755
- };
10756
- const isIP = () => {
10757
- };
10758
- const isIPv4 = () => {
10759
- };
10760
- const isIPv6 = () => {
10761
- };
10762
- const _default = {
10763
- Socket,
10764
- Server,
10765
- connect,
10766
- createConnection,
10767
- createServer,
10768
- createSecureServer,
10769
- isIP,
10770
- isIPv4,
10771
- isIPv6
10772
- };
10676
+ const M = (r, e) => {
10677
+ const t = new E(
10678
+ typeof r == "string" ? { type: r } : r
10679
+ );
10680
+ return e && t.on("message", e), t;
10681
+ }, K = /* @__PURE__ */ Object.freeze(/* @__PURE__ */ Object.defineProperty({
10682
+ __proto__: null,
10683
+ Socket: E,
10684
+ createSocket: M
10685
+ }, Symbol.toStringTag, { value: "Module" }));
10686
+
10687
+ const Socket = K.Socket;
10688
+ const createSocket = K.createSocket;
10773
10689
 
10774
- exports.Server = Server;
10775
10690
  exports.Socket = Socket;
10776
- exports._default = _default;
10777
- exports.connect = connect;
10778
- exports.createConnection = createConnection;
10779
- exports.createSecureServer = createSecureServer;
10780
- exports.createServer = createServer;
10781
- exports.default = _default;
10782
- exports.isIP = isIP;
10783
- exports.isIPv4 = isIPv4;
10784
- exports.isIPv6 = isIPv6;
10691
+ exports.createSocket = createSocket;
10692
+ exports.default = K;
10785
10693
  //# sourceMappingURL=index.cjs.map