cyshield-sdk
Version:
Firewall SDK to protect web apps by validating IP addresses and providing real-time threat monitoring.
1,634 lines (1,541 loc) • 305 kB
JavaScript
'use strict';
var React = require('react');
function asyncGeneratorStep(n, t, e, r, o, a, c) {
try {
var i = n[a](c),
u = i.value;
} catch (n) {
return void e(n);
}
i.done ? t(u) : Promise.resolve(u).then(r, o);
}
function _asyncToGenerator(n) {
return function () {
var t = this,
e = arguments;
return new Promise(function (r, o) {
var a = n.apply(t, e);
function _next(n) {
asyncGeneratorStep(a, r, o, _next, _throw, "next", n);
}
function _throw(n) {
asyncGeneratorStep(a, r, o, _next, _throw, "throw", n);
}
_next(void 0);
});
};
}
function _arrayWithHoles(r) {
if (Array.isArray(r)) return r;
}
function _iterableToArrayLimit(r, l) {
var t = null == r ? null : "undefined" != typeof Symbol && r[Symbol.iterator] || r["@@iterator"];
if (null != t) {
var e,
n,
i,
u,
a = [],
f = true,
o = false;
try {
if (i = (t = t.call(r)).next, 0 === l) ; else for (; !(f = (e = i.call(t)).done) && (a.push(e.value), a.length !== l); f = !0);
} catch (r) {
o = true, n = r;
} finally {
try {
if (!f && null != t["return"] && (u = t["return"](), Object(u) !== u)) return;
} finally {
if (o) throw n;
}
}
return a;
}
}
function _arrayLikeToArray(r, a) {
(null == a || a > r.length) && (a = r.length);
for (var e = 0, n = Array(a); e < a; e++) n[e] = r[e];
return n;
}
function _unsupportedIterableToArray(r, a) {
if (r) {
if ("string" == typeof r) return _arrayLikeToArray(r, a);
var t = {}.toString.call(r).slice(8, -1);
return "Object" === t && r.constructor && (t = r.constructor.name), "Map" === t || "Set" === t ? Array.from(r) : "Arguments" === t || /^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(t) ? _arrayLikeToArray(r, a) : void 0;
}
}
function _nonIterableRest() {
throw new TypeError("Invalid attempt to destructure non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.");
}
function _slicedToArray(r, e) {
return _arrayWithHoles(r) || _iterableToArrayLimit(r, e) || _unsupportedIterableToArray(r, e) || _nonIterableRest();
}
function getDefaultExportFromCjs (x) {
return x && x.__esModule && Object.prototype.hasOwnProperty.call(x, 'default') ? x['default'] : x;
}
var regeneratorRuntime$1 = {exports: {}};
var OverloadYield = {exports: {}};
var hasRequiredOverloadYield;
function requireOverloadYield () {
if (hasRequiredOverloadYield) return OverloadYield.exports;
hasRequiredOverloadYield = 1;
(function (module) {
function _OverloadYield(e, d) {
this.v = e, this.k = d;
}
module.exports = _OverloadYield, module.exports.__esModule = true, module.exports["default"] = module.exports;
} (OverloadYield));
return OverloadYield.exports;
}
var regenerator$1 = {exports: {}};
var regeneratorDefine = {exports: {}};
var hasRequiredRegeneratorDefine;
function requireRegeneratorDefine () {
if (hasRequiredRegeneratorDefine) return regeneratorDefine.exports;
hasRequiredRegeneratorDefine = 1;
(function (module) {
function _regeneratorDefine(e, r, n, t) {
var i = Object.defineProperty;
try {
i({}, "", {});
} catch (e) {
i = 0;
}
module.exports = _regeneratorDefine = function regeneratorDefine(e, r, n, t) {
if (r) i ? i(e, r, {
value: n,
enumerable: !t,
configurable: !t,
writable: !t
}) : e[r] = n;else {
var o = function o(r, n) {
_regeneratorDefine(e, r, function (e) {
return this._invoke(r, n, e);
});
};
o("next", 0), o("throw", 1), o("return", 2);
}
}, module.exports.__esModule = true, module.exports["default"] = module.exports, _regeneratorDefine(e, r, n, t);
}
module.exports = _regeneratorDefine, module.exports.__esModule = true, module.exports["default"] = module.exports;
} (regeneratorDefine));
return regeneratorDefine.exports;
}
var hasRequiredRegenerator$1;
function requireRegenerator$1 () {
if (hasRequiredRegenerator$1) return regenerator$1.exports;
hasRequiredRegenerator$1 = 1;
(function (module) {
var regeneratorDefine = requireRegeneratorDefine();
function _regenerator() {
/*! regenerator-runtime -- Copyright (c) 2014-present, Facebook, Inc. -- license (MIT): https://github.com/babel/babel/blob/main/packages/babel-helpers/LICENSE */
var e,
t,
r = "function" == typeof Symbol ? Symbol : {},
n = r.iterator || "@@iterator",
o = r.toStringTag || "@@toStringTag";
function i(r, n, o, i) {
var c = n && n.prototype instanceof Generator ? n : Generator,
u = Object.create(c.prototype);
return regeneratorDefine(u, "_invoke", function (r, n, o) {
var i,
c,
u,
f = 0,
p = o || [],
y = false,
G = {
p: 0,
n: 0,
v: e,
a: d,
f: d.bind(e, 4),
d: function d(t, r) {
return i = t, c = 0, u = e, G.n = r, a;
}
};
function d(r, n) {
for (c = r, u = n, t = 0; !y && f && !o && t < p.length; t++) {
var o,
i = p[t],
d = G.p,
l = i[2];
r > 3 ? (o = l === n) && (u = i[(c = i[4]) ? 5 : (c = 3, 3)], i[4] = i[5] = e) : i[0] <= d && ((o = r < 2 && d < i[1]) ? (c = 0, G.v = n, G.n = i[1]) : d < l && (o = r < 3 || i[0] > n || n > l) && (i[4] = r, i[5] = n, G.n = l, c = 0));
}
if (o || r > 1) return a;
throw y = true, n;
}
return function (o, p, l) {
if (f > 1) throw TypeError("Generator is already running");
for (y && 1 === p && d(p, l), c = p, u = l; (t = c < 2 ? e : u) || !y;) {
i || (c ? c < 3 ? (c > 1 && (G.n = -1), d(c, u)) : G.n = u : G.v = u);
try {
if (f = 2, i) {
if (c || (o = "next"), t = i[o]) {
if (!(t = t.call(i, u))) throw TypeError("iterator result is not an object");
if (!t.done) return t;
u = t.value, c < 2 && (c = 0);
} else 1 === c && (t = i["return"]) && t.call(i), c < 2 && (u = TypeError("The iterator does not provide a '" + o + "' method"), c = 1);
i = e;
} else if ((t = (y = G.n < 0) ? u : r.call(n, G)) !== a) break;
} catch (t) {
i = e, c = 1, u = t;
} finally {
f = 1;
}
}
return {
value: t,
done: y
};
};
}(r, o, i), true), u;
}
var a = {};
function Generator() {}
function GeneratorFunction() {}
function GeneratorFunctionPrototype() {}
t = Object.getPrototypeOf;
var c = [][n] ? t(t([][n]())) : (regeneratorDefine(t = {}, n, function () {
return this;
}), t),
u = GeneratorFunctionPrototype.prototype = Generator.prototype = Object.create(c);
function f(e) {
return Object.setPrototypeOf ? Object.setPrototypeOf(e, GeneratorFunctionPrototype) : (e.__proto__ = GeneratorFunctionPrototype, regeneratorDefine(e, o, "GeneratorFunction")), e.prototype = Object.create(u), e;
}
return GeneratorFunction.prototype = GeneratorFunctionPrototype, regeneratorDefine(u, "constructor", GeneratorFunctionPrototype), regeneratorDefine(GeneratorFunctionPrototype, "constructor", GeneratorFunction), GeneratorFunction.displayName = "GeneratorFunction", regeneratorDefine(GeneratorFunctionPrototype, o, "GeneratorFunction"), regeneratorDefine(u), regeneratorDefine(u, o, "Generator"), regeneratorDefine(u, n, function () {
return this;
}), regeneratorDefine(u, "toString", function () {
return "[object Generator]";
}), (module.exports = _regenerator = function _regenerator() {
return {
w: i,
m: f
};
}, module.exports.__esModule = true, module.exports["default"] = module.exports)();
}
module.exports = _regenerator, module.exports.__esModule = true, module.exports["default"] = module.exports;
} (regenerator$1));
return regenerator$1.exports;
}
var regeneratorAsync = {exports: {}};
var regeneratorAsyncGen = {exports: {}};
var regeneratorAsyncIterator = {exports: {}};
var hasRequiredRegeneratorAsyncIterator;
function requireRegeneratorAsyncIterator () {
if (hasRequiredRegeneratorAsyncIterator) return regeneratorAsyncIterator.exports;
hasRequiredRegeneratorAsyncIterator = 1;
(function (module) {
var OverloadYield = requireOverloadYield();
var regeneratorDefine = requireRegeneratorDefine();
function AsyncIterator(t, e) {
function n(r, o, i, f) {
try {
var c = t[r](o),
u = c.value;
return u instanceof OverloadYield ? e.resolve(u.v).then(function (t) {
n("next", t, i, f);
}, function (t) {
n("throw", t, i, f);
}) : e.resolve(u).then(function (t) {
c.value = t, i(c);
}, function (t) {
return n("throw", t, i, f);
});
} catch (t) {
f(t);
}
}
var r;
this.next || (regeneratorDefine(AsyncIterator.prototype), regeneratorDefine(AsyncIterator.prototype, "function" == typeof Symbol && Symbol.asyncIterator || "@asyncIterator", function () {
return this;
})), regeneratorDefine(this, "_invoke", function (t, o, i) {
function f() {
return new e(function (e, r) {
n(t, i, e, r);
});
}
return r = r ? r.then(f, f) : f();
}, true);
}
module.exports = AsyncIterator, module.exports.__esModule = true, module.exports["default"] = module.exports;
} (regeneratorAsyncIterator));
return regeneratorAsyncIterator.exports;
}
var hasRequiredRegeneratorAsyncGen;
function requireRegeneratorAsyncGen () {
if (hasRequiredRegeneratorAsyncGen) return regeneratorAsyncGen.exports;
hasRequiredRegeneratorAsyncGen = 1;
(function (module) {
var regenerator = requireRegenerator$1();
var regeneratorAsyncIterator = requireRegeneratorAsyncIterator();
function _regeneratorAsyncGen(r, e, t, o, n) {
return new regeneratorAsyncIterator(regenerator().w(r, e, t, o), n || Promise);
}
module.exports = _regeneratorAsyncGen, module.exports.__esModule = true, module.exports["default"] = module.exports;
} (regeneratorAsyncGen));
return regeneratorAsyncGen.exports;
}
var hasRequiredRegeneratorAsync;
function requireRegeneratorAsync () {
if (hasRequiredRegeneratorAsync) return regeneratorAsync.exports;
hasRequiredRegeneratorAsync = 1;
(function (module) {
var regeneratorAsyncGen = requireRegeneratorAsyncGen();
function _regeneratorAsync(n, e, r, t, o) {
var a = regeneratorAsyncGen(n, e, r, t, o);
return a.next().then(function (n) {
return n.done ? n.value : a.next();
});
}
module.exports = _regeneratorAsync, module.exports.__esModule = true, module.exports["default"] = module.exports;
} (regeneratorAsync));
return regeneratorAsync.exports;
}
var regeneratorKeys = {exports: {}};
var hasRequiredRegeneratorKeys;
function requireRegeneratorKeys () {
if (hasRequiredRegeneratorKeys) return regeneratorKeys.exports;
hasRequiredRegeneratorKeys = 1;
(function (module) {
function _regeneratorKeys(e) {
var n = Object(e),
r = [];
for (var t in n) r.unshift(t);
return function e() {
for (; r.length;) if ((t = r.pop()) in n) return e.value = t, e.done = false, e;
return e.done = true, e;
};
}
module.exports = _regeneratorKeys, module.exports.__esModule = true, module.exports["default"] = module.exports;
} (regeneratorKeys));
return regeneratorKeys.exports;
}
var regeneratorValues = {exports: {}};
var _typeof$1 = {exports: {}};
var hasRequired_typeof;
function require_typeof () {
if (hasRequired_typeof) return _typeof$1.exports;
hasRequired_typeof = 1;
(function (module) {
function _typeof(o) {
"@babel/helpers - typeof";
return module.exports = _typeof = "function" == typeof Symbol && "symbol" == typeof Symbol.iterator ? function (o) {
return typeof o;
} : function (o) {
return o && "function" == typeof Symbol && o.constructor === Symbol && o !== Symbol.prototype ? "symbol" : typeof o;
}, module.exports.__esModule = true, module.exports["default"] = module.exports, _typeof(o);
}
module.exports = _typeof, module.exports.__esModule = true, module.exports["default"] = module.exports;
} (_typeof$1));
return _typeof$1.exports;
}
var hasRequiredRegeneratorValues;
function requireRegeneratorValues () {
if (hasRequiredRegeneratorValues) return regeneratorValues.exports;
hasRequiredRegeneratorValues = 1;
(function (module) {
var _typeof = require_typeof()["default"];
function _regeneratorValues(e) {
if (null != e) {
var t = e["function" == typeof Symbol && Symbol.iterator || "@@iterator"],
r = 0;
if (t) return t.call(e);
if ("function" == typeof e.next) return e;
if (!isNaN(e.length)) return {
next: function next() {
return e && r >= e.length && (e = void 0), {
value: e && e[r++],
done: !e
};
}
};
}
throw new TypeError(_typeof(e) + " is not iterable");
}
module.exports = _regeneratorValues, module.exports.__esModule = true, module.exports["default"] = module.exports;
} (regeneratorValues));
return regeneratorValues.exports;
}
var hasRequiredRegeneratorRuntime;
function requireRegeneratorRuntime () {
if (hasRequiredRegeneratorRuntime) return regeneratorRuntime$1.exports;
hasRequiredRegeneratorRuntime = 1;
(function (module) {
var OverloadYield = requireOverloadYield();
var regenerator = requireRegenerator$1();
var regeneratorAsync = requireRegeneratorAsync();
var regeneratorAsyncGen = requireRegeneratorAsyncGen();
var regeneratorAsyncIterator = requireRegeneratorAsyncIterator();
var regeneratorKeys = requireRegeneratorKeys();
var regeneratorValues = requireRegeneratorValues();
function _regeneratorRuntime() {
var r = regenerator(),
e = r.m(_regeneratorRuntime),
t = (Object.getPrototypeOf ? Object.getPrototypeOf(e) : e.__proto__).constructor;
function n(r) {
var e = "function" == typeof r && r.constructor;
return !!e && (e === t || "GeneratorFunction" === (e.displayName || e.name));
}
var o = {
"throw": 1,
"return": 2,
"break": 3,
"continue": 3
};
function a(r) {
var e, t;
return function (n) {
e || (e = {
stop: function stop() {
return t(n.a, 2);
},
"catch": function _catch() {
return n.v;
},
abrupt: function abrupt(r, e) {
return t(n.a, o[r], e);
},
delegateYield: function delegateYield(r, o, a) {
return e.resultName = o, t(n.d, regeneratorValues(r), a);
},
finish: function finish(r) {
return t(n.f, r);
}
}, t = function t(r, _t, o) {
n.p = e.prev, n.n = e.next;
try {
return r(_t, o);
} finally {
e.next = n.n;
}
}), e.resultName && (e[e.resultName] = n.v, e.resultName = void 0), e.sent = n.v, e.next = n.n;
try {
return r.call(this, e);
} finally {
n.p = e.prev, n.n = e.next;
}
};
}
return (module.exports = _regeneratorRuntime = function _regeneratorRuntime() {
return {
wrap: function wrap(e, t, n, o) {
return r.w(a(e), t, n, o && o.reverse());
},
isGeneratorFunction: n,
mark: r.m,
awrap: function awrap(r, e) {
return new OverloadYield(r, e);
},
AsyncIterator: regeneratorAsyncIterator,
async: function async(r, e, t, o, u) {
return (n(e) ? regeneratorAsyncGen : regeneratorAsync)(a(r), e, t, o, u);
},
keys: regeneratorKeys,
values: regeneratorValues
};
}, module.exports.__esModule = true, module.exports["default"] = module.exports)();
}
module.exports = _regeneratorRuntime, module.exports.__esModule = true, module.exports["default"] = module.exports;
} (regeneratorRuntime$1));
return regeneratorRuntime$1.exports;
}
var regenerator;
var hasRequiredRegenerator;
function requireRegenerator () {
if (hasRequiredRegenerator) return regenerator;
hasRequiredRegenerator = 1;
// TODO(Babel 8): Remove this file.
var runtime = requireRegeneratorRuntime()();
regenerator = runtime;
// Copied from https://github.com/facebook/regenerator/blob/main/packages/runtime/runtime.js#L736=
try {
regeneratorRuntime = runtime;
} catch (accidentalStrictMode) {
if (typeof globalThis === "object") {
globalThis.regeneratorRuntime = runtime;
} else {
Function("r", "regeneratorRuntime = r")(runtime);
}
}
return regenerator;
}
var regeneratorExports = requireRegenerator();
var _regeneratorRuntime = /*@__PURE__*/getDefaultExportFromCjs(regeneratorExports);
// Multiple IP services for fallback
var IP_SERVICES = ["https://api.ipify.org?format=json", "https://api64.ipify.org?format=json", "https://api.my-ip.io/ip.json", "https://ipapi.co/json/"];
var getUserIP = /*#__PURE__*/function () {
var _ref = _asyncToGenerator(/*#__PURE__*/_regeneratorRuntime.mark(function _callee() {
var i, response, data, ip;
return _regeneratorRuntime.wrap(function _callee$(_context) {
while (1) switch (_context.prev = _context.next) {
case 0:
i = 0;
case 1:
if (!(i < IP_SERVICES.length)) {
_context.next = 23;
break;
}
_context.prev = 2;
_context.next = 5;
return fetch(IP_SERVICES[i], {
timeout: 5000 // 5 second timeout
});
case 5:
response = _context.sent;
if (response.ok) {
_context.next = 8;
break;
}
throw new Error("HTTP ".concat(response.status));
case 8:
_context.next = 10;
return response.json();
case 10:
data = _context.sent;
// Different services return IP in different formats
ip = data.ip || data.query || data.IPv4 || data.origin;
if (!(ip && isValidIP(ip))) {
_context.next = 14;
break;
}
return _context.abrupt("return", ip);
case 14:
_context.next = 20;
break;
case 16:
_context.prev = 16;
_context.t0 = _context["catch"](2);
console.warn("IP service ".concat(IP_SERVICES[i], " failed:"), _context.t0.message);
return _context.abrupt("continue", 20);
case 20:
i++;
_context.next = 1;
break;
case 23:
console.error("All IP services failed");
return _context.abrupt("return", null);
case 25:
case "end":
return _context.stop();
}
}, _callee, null, [[2, 16]]);
}));
return function getUserIP() {
return _ref.apply(this, arguments);
};
}();
// Basic IP validation
var isValidIP = function isValidIP(ip) {
var ipv4Regex = /^(?:(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.){3}(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)$/;
var ipv6Regex = /^(?:[0-9a-fA-F]{1,4}:){7}[0-9a-fA-F]{1,4}$/;
return ipv4Regex.test(ip) || ipv6Regex.test(ip);
};
function _typeof(o) {
"@babel/helpers - typeof";
return _typeof = "function" == typeof Symbol && "symbol" == typeof Symbol.iterator ? function (o) {
return typeof o;
} : function (o) {
return o && "function" == typeof Symbol && o.constructor === Symbol && o !== Symbol.prototype ? "symbol" : typeof o;
}, _typeof(o);
}
function toPrimitive(t, r) {
if ("object" != _typeof(t) || !t) return t;
var e = t[Symbol.toPrimitive];
if (void 0 !== e) {
var i = e.call(t, r);
if ("object" != _typeof(i)) return i;
throw new TypeError("@@toPrimitive must return a primitive value.");
}
return (String )(t);
}
function toPropertyKey(t) {
var i = toPrimitive(t, "string");
return "symbol" == _typeof(i) ? i : i + "";
}
function _defineProperty(e, r, t) {
return (r = toPropertyKey(r)) in e ? Object.defineProperty(e, r, {
value: t,
enumerable: true,
configurable: true,
writable: true
}) : e[r] = t, e;
}
const PACKET_TYPES = Object.create(null); // no Map = no polyfill
PACKET_TYPES["open"] = "0";
PACKET_TYPES["close"] = "1";
PACKET_TYPES["ping"] = "2";
PACKET_TYPES["pong"] = "3";
PACKET_TYPES["message"] = "4";
PACKET_TYPES["upgrade"] = "5";
PACKET_TYPES["noop"] = "6";
const PACKET_TYPES_REVERSE = Object.create(null);
Object.keys(PACKET_TYPES).forEach((key) => {
PACKET_TYPES_REVERSE[PACKET_TYPES[key]] = key;
});
const ERROR_PACKET = { type: "error", data: "parser error" };
const withNativeBlob$1 = typeof Blob === "function" ||
(typeof Blob !== "undefined" &&
Object.prototype.toString.call(Blob) === "[object BlobConstructor]");
const withNativeArrayBuffer$2 = typeof ArrayBuffer === "function";
// ArrayBuffer.isView method is not defined in IE10
const isView$1 = (obj) => {
return typeof ArrayBuffer.isView === "function"
? ArrayBuffer.isView(obj)
: obj && obj.buffer instanceof ArrayBuffer;
};
const encodePacket = ({ type, data }, supportsBinary, callback) => {
if (withNativeBlob$1 && data instanceof Blob) {
if (supportsBinary) {
return callback(data);
}
else {
return encodeBlobAsBase64(data, callback);
}
}
else if (withNativeArrayBuffer$2 &&
(data instanceof ArrayBuffer || isView$1(data))) {
if (supportsBinary) {
return callback(data);
}
else {
return encodeBlobAsBase64(new Blob([data]), callback);
}
}
// plain string
return callback(PACKET_TYPES[type] + (data || ""));
};
const encodeBlobAsBase64 = (data, callback) => {
const fileReader = new FileReader();
fileReader.onload = function () {
const content = fileReader.result.split(",")[1];
callback("b" + (content || ""));
};
return fileReader.readAsDataURL(data);
};
function toArray$1(data) {
if (data instanceof Uint8Array) {
return data;
}
else if (data instanceof ArrayBuffer) {
return new Uint8Array(data);
}
else {
return new Uint8Array(data.buffer, data.byteOffset, data.byteLength);
}
}
let TEXT_ENCODER;
function encodePacketToBinary(packet, callback) {
if (withNativeBlob$1 && packet.data instanceof Blob) {
return packet.data.arrayBuffer().then(toArray$1).then(callback);
}
else if (withNativeArrayBuffer$2 &&
(packet.data instanceof ArrayBuffer || isView$1(packet.data))) {
return callback(toArray$1(packet.data));
}
encodePacket(packet, false, (encoded) => {
if (!TEXT_ENCODER) {
TEXT_ENCODER = new TextEncoder();
}
callback(TEXT_ENCODER.encode(encoded));
});
}
// imported from https://github.com/socketio/base64-arraybuffer
const chars = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/';
// Use a lookup table to find the index.
const lookup$1 = typeof Uint8Array === 'undefined' ? [] : new Uint8Array(256);
for (let i = 0; i < chars.length; i++) {
lookup$1[chars.charCodeAt(i)] = i;
}
const decode$1 = (base64) => {
let bufferLength = base64.length * 0.75, len = base64.length, i, p = 0, encoded1, encoded2, encoded3, encoded4;
if (base64[base64.length - 1] === '=') {
bufferLength--;
if (base64[base64.length - 2] === '=') {
bufferLength--;
}
}
const arraybuffer = new ArrayBuffer(bufferLength), bytes = new Uint8Array(arraybuffer);
for (i = 0; i < len; i += 4) {
encoded1 = lookup$1[base64.charCodeAt(i)];
encoded2 = lookup$1[base64.charCodeAt(i + 1)];
encoded3 = lookup$1[base64.charCodeAt(i + 2)];
encoded4 = lookup$1[base64.charCodeAt(i + 3)];
bytes[p++] = (encoded1 << 2) | (encoded2 >> 4);
bytes[p++] = ((encoded2 & 15) << 4) | (encoded3 >> 2);
bytes[p++] = ((encoded3 & 3) << 6) | (encoded4 & 63);
}
return arraybuffer;
};
const withNativeArrayBuffer$1 = typeof ArrayBuffer === "function";
const decodePacket = (encodedPacket, binaryType) => {
if (typeof encodedPacket !== "string") {
return {
type: "message",
data: mapBinary(encodedPacket, binaryType),
};
}
const type = encodedPacket.charAt(0);
if (type === "b") {
return {
type: "message",
data: decodeBase64Packet(encodedPacket.substring(1), binaryType),
};
}
const packetType = PACKET_TYPES_REVERSE[type];
if (!packetType) {
return ERROR_PACKET;
}
return encodedPacket.length > 1
? {
type: PACKET_TYPES_REVERSE[type],
data: encodedPacket.substring(1),
}
: {
type: PACKET_TYPES_REVERSE[type],
};
};
const decodeBase64Packet = (data, binaryType) => {
if (withNativeArrayBuffer$1) {
const decoded = decode$1(data);
return mapBinary(decoded, binaryType);
}
else {
return { base64: true, data }; // fallback for old browsers
}
};
const mapBinary = (data, binaryType) => {
switch (binaryType) {
case "blob":
if (data instanceof Blob) {
// from WebSocket + binaryType "blob"
return data;
}
else {
// from HTTP long-polling or WebTransport
return new Blob([data]);
}
case "arraybuffer":
default:
if (data instanceof ArrayBuffer) {
// from HTTP long-polling (base64) or WebSocket + binaryType "arraybuffer"
return data;
}
else {
// from WebTransport (Uint8Array)
return data.buffer;
}
}
};
const SEPARATOR = String.fromCharCode(30); // see https://en.wikipedia.org/wiki/Delimiter#ASCII_delimited_text
const encodePayload = (packets, callback) => {
// some packets may be added to the array while encoding, so the initial length must be saved
const length = packets.length;
const encodedPackets = new Array(length);
let count = 0;
packets.forEach((packet, i) => {
// force base64 encoding for binary packets
encodePacket(packet, false, (encodedPacket) => {
encodedPackets[i] = encodedPacket;
if (++count === length) {
callback(encodedPackets.join(SEPARATOR));
}
});
});
};
const decodePayload = (encodedPayload, binaryType) => {
const encodedPackets = encodedPayload.split(SEPARATOR);
const packets = [];
for (let i = 0; i < encodedPackets.length; i++) {
const decodedPacket = decodePacket(encodedPackets[i], binaryType);
packets.push(decodedPacket);
if (decodedPacket.type === "error") {
break;
}
}
return packets;
};
function createPacketEncoderStream() {
return new TransformStream({
transform(packet, controller) {
encodePacketToBinary(packet, (encodedPacket) => {
const payloadLength = encodedPacket.length;
let header;
// inspired by the WebSocket format: https://developer.mozilla.org/en-US/docs/Web/API/WebSockets_API/Writing_WebSocket_servers#decoding_payload_length
if (payloadLength < 126) {
header = new Uint8Array(1);
new DataView(header.buffer).setUint8(0, payloadLength);
}
else if (payloadLength < 65536) {
header = new Uint8Array(3);
const view = new DataView(header.buffer);
view.setUint8(0, 126);
view.setUint16(1, payloadLength);
}
else {
header = new Uint8Array(9);
const view = new DataView(header.buffer);
view.setUint8(0, 127);
view.setBigUint64(1, BigInt(payloadLength));
}
// first bit indicates whether the payload is plain text (0) or binary (1)
if (packet.data && typeof packet.data !== "string") {
header[0] |= 0x80;
}
controller.enqueue(header);
controller.enqueue(encodedPacket);
});
},
});
}
let TEXT_DECODER;
function totalLength(chunks) {
return chunks.reduce((acc, chunk) => acc + chunk.length, 0);
}
function concatChunks(chunks, size) {
if (chunks[0].length === size) {
return chunks.shift();
}
const buffer = new Uint8Array(size);
let j = 0;
for (let i = 0; i < size; i++) {
buffer[i] = chunks[0][j++];
if (j === chunks[0].length) {
chunks.shift();
j = 0;
}
}
if (chunks.length && j < chunks[0].length) {
chunks[0] = chunks[0].slice(j);
}
return buffer;
}
function createPacketDecoderStream(maxPayload, binaryType) {
if (!TEXT_DECODER) {
TEXT_DECODER = new TextDecoder();
}
const chunks = [];
let state = 0 /* State.READ_HEADER */;
let expectedLength = -1;
let isBinary = false;
return new TransformStream({
transform(chunk, controller) {
chunks.push(chunk);
while (true) {
if (state === 0 /* State.READ_HEADER */) {
if (totalLength(chunks) < 1) {
break;
}
const header = concatChunks(chunks, 1);
isBinary = (header[0] & 0x80) === 0x80;
expectedLength = header[0] & 0x7f;
if (expectedLength < 126) {
state = 3 /* State.READ_PAYLOAD */;
}
else if (expectedLength === 126) {
state = 1 /* State.READ_EXTENDED_LENGTH_16 */;
}
else {
state = 2 /* State.READ_EXTENDED_LENGTH_64 */;
}
}
else if (state === 1 /* State.READ_EXTENDED_LENGTH_16 */) {
if (totalLength(chunks) < 2) {
break;
}
const headerArray = concatChunks(chunks, 2);
expectedLength = new DataView(headerArray.buffer, headerArray.byteOffset, headerArray.length).getUint16(0);
state = 3 /* State.READ_PAYLOAD */;
}
else if (state === 2 /* State.READ_EXTENDED_LENGTH_64 */) {
if (totalLength(chunks) < 8) {
break;
}
const headerArray = concatChunks(chunks, 8);
const view = new DataView(headerArray.buffer, headerArray.byteOffset, headerArray.length);
const n = view.getUint32(0);
if (n > Math.pow(2, 53 - 32) - 1) {
// the maximum safe integer in JavaScript is 2^53 - 1
controller.enqueue(ERROR_PACKET);
break;
}
expectedLength = n * Math.pow(2, 32) + view.getUint32(4);
state = 3 /* State.READ_PAYLOAD */;
}
else {
if (totalLength(chunks) < expectedLength) {
break;
}
const data = concatChunks(chunks, expectedLength);
controller.enqueue(decodePacket(isBinary ? data : TEXT_DECODER.decode(data), binaryType));
state = 0 /* State.READ_HEADER */;
}
if (expectedLength === 0 || expectedLength > maxPayload) {
controller.enqueue(ERROR_PACKET);
break;
}
}
},
});
}
const protocol$1 = 4;
/**
* Initialize a new `Emitter`.
*
* @api public
*/
function Emitter(obj) {
if (obj) return mixin(obj);
}
/**
* Mixin the emitter properties.
*
* @param {Object} obj
* @return {Object}
* @api private
*/
function mixin(obj) {
for (var key in Emitter.prototype) {
obj[key] = Emitter.prototype[key];
}
return obj;
}
/**
* Listen on the given `event` with `fn`.
*
* @param {String} event
* @param {Function} fn
* @return {Emitter}
* @api public
*/
Emitter.prototype.on =
Emitter.prototype.addEventListener = function(event, fn){
this._callbacks = this._callbacks || {};
(this._callbacks['$' + event] = this._callbacks['$' + event] || [])
.push(fn);
return this;
};
/**
* Adds an `event` listener that will be invoked a single
* time then automatically removed.
*
* @param {String} event
* @param {Function} fn
* @return {Emitter}
* @api public
*/
Emitter.prototype.once = function(event, fn){
function on() {
this.off(event, on);
fn.apply(this, arguments);
}
on.fn = fn;
this.on(event, on);
return this;
};
/**
* Remove the given callback for `event` or all
* registered callbacks.
*
* @param {String} event
* @param {Function} fn
* @return {Emitter}
* @api public
*/
Emitter.prototype.off =
Emitter.prototype.removeListener =
Emitter.prototype.removeAllListeners =
Emitter.prototype.removeEventListener = function(event, fn){
this._callbacks = this._callbacks || {};
// all
if (0 == arguments.length) {
this._callbacks = {};
return this;
}
// specific event
var callbacks = this._callbacks['$' + event];
if (!callbacks) return this;
// remove all handlers
if (1 == arguments.length) {
delete this._callbacks['$' + event];
return this;
}
// remove specific handler
var cb;
for (var i = 0; i < callbacks.length; i++) {
cb = callbacks[i];
if (cb === fn || cb.fn === fn) {
callbacks.splice(i, 1);
break;
}
}
// Remove event specific arrays for event types that no
// one is subscribed for to avoid memory leak.
if (callbacks.length === 0) {
delete this._callbacks['$' + event];
}
return this;
};
/**
* Emit `event` with the given args.
*
* @param {String} event
* @param {Mixed} ...
* @return {Emitter}
*/
Emitter.prototype.emit = function(event){
this._callbacks = this._callbacks || {};
var args = new Array(arguments.length - 1)
, callbacks = this._callbacks['$' + event];
for (var i = 1; i < arguments.length; i++) {
args[i - 1] = arguments[i];
}
if (callbacks) {
callbacks = callbacks.slice(0);
for (var i = 0, len = callbacks.length; i < len; ++i) {
callbacks[i].apply(this, args);
}
}
return this;
};
// alias used for reserved events (protected method)
Emitter.prototype.emitReserved = Emitter.prototype.emit;
/**
* Return array of callbacks for `event`.
*
* @param {String} event
* @return {Array}
* @api public
*/
Emitter.prototype.listeners = function(event){
this._callbacks = this._callbacks || {};
return this._callbacks['$' + event] || [];
};
/**
* Check if this emitter has `event` handlers.
*
* @param {String} event
* @return {Boolean}
* @api public
*/
Emitter.prototype.hasListeners = function(event){
return !! this.listeners(event).length;
};
const nextTick = (() => {
const isPromiseAvailable = typeof Promise === "function" && typeof Promise.resolve === "function";
if (isPromiseAvailable) {
return (cb) => Promise.resolve().then(cb);
}
else {
return (cb, setTimeoutFn) => setTimeoutFn(cb, 0);
}
})();
const globalThisShim = (() => {
if (typeof self !== "undefined") {
return self;
}
else if (typeof window !== "undefined") {
return window;
}
else {
return Function("return this")();
}
})();
const defaultBinaryType = "arraybuffer";
function createCookieJar() { }
function pick(obj, ...attr) {
return attr.reduce((acc, k) => {
if (obj.hasOwnProperty(k)) {
acc[k] = obj[k];
}
return acc;
}, {});
}
// Keep a reference to the real timeout functions so they can be used when overridden
const NATIVE_SET_TIMEOUT = globalThisShim.setTimeout;
const NATIVE_CLEAR_TIMEOUT = globalThisShim.clearTimeout;
function installTimerFunctions(obj, opts) {
if (opts.useNativeTimers) {
obj.setTimeoutFn = NATIVE_SET_TIMEOUT.bind(globalThisShim);
obj.clearTimeoutFn = NATIVE_CLEAR_TIMEOUT.bind(globalThisShim);
}
else {
obj.setTimeoutFn = globalThisShim.setTimeout.bind(globalThisShim);
obj.clearTimeoutFn = globalThisShim.clearTimeout.bind(globalThisShim);
}
}
// base64 encoded buffers are about 33% bigger (https://en.wikipedia.org/wiki/Base64)
const BASE64_OVERHEAD = 1.33;
// we could also have used `new Blob([obj]).size`, but it isn't supported in IE9
function byteLength(obj) {
if (typeof obj === "string") {
return utf8Length(obj);
}
// arraybuffer or blob
return Math.ceil((obj.byteLength || obj.size) * BASE64_OVERHEAD);
}
function utf8Length(str) {
let c = 0, length = 0;
for (let i = 0, l = str.length; i < l; i++) {
c = str.charCodeAt(i);
if (c < 0x80) {
length += 1;
}
else if (c < 0x800) {
length += 2;
}
else if (c < 0xd800 || c >= 0xe000) {
length += 3;
}
else {
i++;
length += 4;
}
}
return length;
}
/**
* Generates a random 8-characters string.
*/
function randomString() {
return (Date.now().toString(36).substring(3) +
Math.random().toString(36).substring(2, 5));
}
// imported from https://github.com/galkn/querystring
/**
* Compiles a querystring
* Returns string representation of the object
*
* @param {Object}
* @api private
*/
function encode$2(obj) {
let str = '';
for (let i in obj) {
if (obj.hasOwnProperty(i)) {
if (str.length)
str += '&';
str += encodeURIComponent(i) + '=' + encodeURIComponent(obj[i]);
}
}
return str;
}
/**
* Parses a simple querystring into an object
*
* @param {String} qs
* @api private
*/
function decode(qs) {
let qry = {};
let pairs = qs.split('&');
for (let i = 0, l = pairs.length; i < l; i++) {
let pair = pairs[i].split('=');
qry[decodeURIComponent(pair[0])] = decodeURIComponent(pair[1]);
}
return qry;
}
class TransportError extends Error {
constructor(reason, description, context) {
super(reason);
this.description = description;
this.context = context;
this.type = "TransportError";
}
}
class Transport extends Emitter {
/**
* Transport abstract constructor.
*
* @param {Object} opts - options
* @protected
*/
constructor(opts) {
super();
this.writable = false;
installTimerFunctions(this, opts);
this.opts = opts;
this.query = opts.query;
this.socket = opts.socket;
this.supportsBinary = !opts.forceBase64;
}
/**
* Emits an error.
*
* @param {String} reason
* @param description
* @param context - the error context
* @return {Transport} for chaining
* @protected
*/
onError(reason, description, context) {
super.emitReserved("error", new TransportError(reason, description, context));
return this;
}
/**
* Opens the transport.
*/
open() {
this.readyState = "opening";
this.doOpen();
return this;
}
/**
* Closes the transport.
*/
close() {
if (this.readyState === "opening" || this.readyState === "open") {
this.doClose();
this.onClose();
}
return this;
}
/**
* Sends multiple packets.
*
* @param {Array} packets
*/
send(packets) {
if (this.readyState === "open") {
this.write(packets);
}
}
/**
* Called upon open
*
* @protected
*/
onOpen() {
this.readyState = "open";
this.writable = true;
super.emitReserved("open");
}
/**
* Called with data.
*
* @param {String} data
* @protected
*/
onData(data) {
const packet = decodePacket(data, this.socket.binaryType);
this.onPacket(packet);
}
/**
* Called with a decoded packet.
*
* @protected
*/
onPacket(packet) {
super.emitReserved("packet", packet);
}
/**
* Called upon close.
*
* @protected
*/
onClose(details) {
this.readyState = "closed";
super.emitReserved("close", details);
}
/**
* Pauses the transport, in order not to lose packets during an upgrade.
*
* @param onPause
*/
pause(onPause) { }
createUri(schema, query = {}) {
return (schema +
"://" +
this._hostname() +
this._port() +
this.opts.path +
this._query(query));
}
_hostname() {
const hostname = this.opts.hostname;
return hostname.indexOf(":") === -1 ? hostname : "[" + hostname + "]";
}
_port() {
if (this.opts.port &&
((this.opts.secure && Number(this.opts.port !== 443)) ||
(!this.opts.secure && Number(this.opts.port) !== 80))) {
return ":" + this.opts.port;
}
else {
return "";
}
}
_query(query) {
const encodedQuery = encode$2(query);
return encodedQuery.length ? "?" + encodedQuery : "";
}
}
class Polling extends Transport {
constructor() {
super(...arguments);
this._polling = false;
}
get name() {
return "polling";
}
/**
* Opens the socket (triggers polling). We write a PING message to determine
* when the transport is open.
*
* @protected
*/
doOpen() {
this._poll();
}
/**
* Pauses polling.
*
* @param {Function} onPause - callback upon buffers are flushed and transport is paused
* @package
*/
pause(onPause) {
this.readyState = "pausing";
const pause = () => {
this.readyState = "paused";
onPause();
};
if (this._polling || !this.writable) {
let total = 0;
if (this._polling) {
total++;
this.once("pollComplete", function () {
--total || pause();
});
}
if (!this.writable) {
total++;
this.once("drain", function () {
--total || pause();
});
}
}
else {
pause();
}
}
/**
* Starts polling cycle.
*
* @private
*/
_poll() {
this._polling = true;
this.doPoll();
this.emitReserved("poll");
}
/**
* Overloads onData to detect payloads.
*
* @protected
*/
onData(data) {
const callback = (packet) => {
// if its the first message we consider the transport open
if ("opening" === this.readyState && packet.type === "open") {
this.onOpen();
}
// if its a close packet, we close the ongoing requests
if ("close" === packet.type) {
this.onClose({ description: "transport closed by the server" });
return false;
}
// otherwise bypass onData and handle the message
this.onPacket(packet);
};
// decode payload
decodePayload(data, this.socket.binaryType).forEach(callback);
// if an event did not trigger closing
if ("closed" !== this.readyState) {
// if we got data we're not polling
this._polling = false;
this.emitReserved("pollComplete");
if ("open" === this.readyState) {
this._poll();
}
}
}
/**
* For polling, send a close packet.
*
* @protected
*/
doClose() {
const close = () => {
this.write([{ type: "close" }]);
};
if ("open" === this.readyState) {
close();
}
else {
// in case we're trying to close while
// handshaking is in progress (GH-164)
this.once("open", close);
}
}
/**
* Writes a packets payload.
*
* @param {Array} packets - data packets
* @protected
*/
write(packets) {
this.writable = false;
encodePayload(packets, (data) => {
this.doWrite(data, () => {
this.writable = true;
this.emitReserved("drain");
});
});
}
/**
* Generates uri for connection.
*
* @private
*/
uri() {
const schema = this.opts.secure ? "https" : "http";
const query = this.query || {};
// cache busting is forced
if (false !== this.opts.timestampRequests) {
query[this.opts.timestampParam] = randomString();
}
if (!this.supportsBinary && !query.sid) {
query.b64 = 1;
}
return this.createUri(schema, query);
}
}
// imported from https://github.com/component/has-cors
let value = false;
try {
value = typeof XMLHttpRequest !== 'undefined' &&
'withCredentials' in new XMLHttpRequest();
}
catch (err) {
// if XMLHttp support is disabled in IE then it will throw
// when trying to create
}
const hasCORS = value;
function empty() { }
class BaseXHR extends Polling {
/**
* XHR Polling constructor.
*
* @param {Object} opts
* @package
*/
constructor(opts) {
super(opts);
if (typeof location !== "undefined") {
const isSSL = "https:" === location.protocol;
let port = location.port;
// some user agents have empty `location.port`
if (!port) {
port = isSSL ? "443" : "80";
}
this.xd =
(typeof location !== "undefined" &&
opts.hostname !== location.hostname) ||
port !== opts.port;
}
}
/**
* Sends data.
*
* @param {String} data to send.
* @param {Function} called upon flush.
* @private
*/
doWrite(data, fn) {
const req = this.request({
method: "POST",
data: data,
});
req.on("success", fn);
req.on("error", (xhrStatus, context) => {
this.onError("xhr post error", xhrStatus, context);
});
}
/**
* Starts a poll cycle.
*
* @private
*/
doPoll() {
const req = this.request();
req.on("data", this.onData.bind(this));
req.on("error", (xhrStatus, context) => {
this.onError("xhr poll error", xhrStatus, context);
});
this.pollXhr = req;
}
}
let Request$1 = class Request extends Emitter {
/**
* Request constructor
*
* @param {Object} options
* @package
*/
constructor(createRequest, uri, opts) {
super();
this.createRequest = createRequest;
installTimerFunctions(this, opts);
this._opts = opts;
this._method = opts.method || "GET";
this._uri = uri;
this._data = undefined !== opts.data ? opts.data : null;
this._create();
}
/**
* Creates the XHR object and sends the request.
*
* @private
*/
_create() {
var _a;
const opts = pick(this._opts, "agent", "pfx", "key", "passphrase", "cert", "ca", "ciphers", "rejectUnauthorized", "autoUnref");
opts.xdomain = !!this._opts.xd;
const xhr = (this._xhr = this.createRequest(opts));
try {
xhr.open(this._method, this._uri, true);
try {
if (this._opts.extraHeaders) {
// @ts-ignore
xhr.setDisableHeaderCheck && xhr.setDisableHeaderCheck(true);
for (let i in this._opts.extraHeaders) {
if (this._opts.extraHeaders.hasOwnProperty(i)) {
xhr.setRequestHeader(i, this._opts.extraHeaders[i]);
}
}
}
}
catch (e) { }
if ("POST" === this._method) {
try {
xhr.setRequestHeader("Content-type", "text/plain;charset=UTF-8");
}
catch (e) { }
}
try {
xhr.setRequestHeader("Accept", "*/*");
}
catch (e) { }
(_a = this._opts.cookieJar) === null || _a === void 0 ? void 0 : _a.addCookies(xhr);
// ie6 check
if ("withCredentials" in xhr) {
xhr.withCredentials = this._opts.withCredentials;
}
if (this._opts.requestTimeout) {
xhr.timeout = this._opts.requestTimeout;
}
xhr.onreadystatechange = () => {
var _a;
if (xhr.readyState === 3) {
(_a = this._opts.cookieJar) === null || _a === void 0 ? void 0 : _a.parseCookies(
//