@skyway-sdk/sfu-bot
Version:
The official Next Generation JavaScript SDK for SkyWay
53,683 lines • 1.97 MB
JavaScript
"use strict";
var skyway_sfu_bot = (() => {
var __create = Object.create;
var __defProp = Object.defineProperty;
var __defProps = Object.defineProperties;
var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
var __getOwnPropDescs = Object.getOwnPropertyDescriptors;
var __getOwnPropNames = Object.getOwnPropertyNames;
var __getOwnPropSymbols = Object.getOwnPropertySymbols;
var __getProtoOf = Object.getPrototypeOf;
var __hasOwnProp = Object.prototype.hasOwnProperty;
var __propIsEnum = Object.prototype.propertyIsEnumerable;
var __knownSymbol = (name, symbol) => (symbol = Symbol[name]) ? symbol : Symbol.for("Symbol." + name);
var __typeError = (msg) => {
throw TypeError(msg);
};
var __pow = Math.pow;
var __defNormalProp = (obj, key, value) => key in obj ? __defProp(obj, key, { enumerable: true, configurable: true, writable: true, value }) : obj[key] = value;
var __spreadValues = (a, b) => {
for (var prop in b || (b = {}))
if (__hasOwnProp.call(b, prop))
__defNormalProp(a, prop, b[prop]);
if (__getOwnPropSymbols)
for (var prop of __getOwnPropSymbols(b)) {
if (__propIsEnum.call(b, prop))
__defNormalProp(a, prop, b[prop]);
}
return a;
};
var __spreadProps = (a, b) => __defProps(a, __getOwnPropDescs(b));
var __esm = (fn, res) => function __init() {
return fn && (res = (0, fn[__getOwnPropNames(fn)[0]])(fn = 0)), res;
};
var __commonJS = (cb, mod) => function __require() {
return mod || (0, cb[__getOwnPropNames(cb)[0]])((mod = { exports: {} }).exports, mod), mod.exports;
};
var __export = (target, all3) => {
for (var name in all3)
__defProp(target, name, { get: all3[name], enumerable: true });
};
var __copyProps = (to, from, except, desc) => {
if (from && typeof from === "object" || typeof from === "function") {
for (let key of __getOwnPropNames(from))
if (!__hasOwnProp.call(to, key) && key !== except)
__defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
}
return to;
};
var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps(
// If the importer is in node compatibility mode or this is not an ESM
// file that has been converted to a CommonJS file using a Babel-
// compatible transform (i.e. "__esModule" has not been set), then set
// "default" to the CommonJS "module.exports" for node compatibility.
isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", { value: mod, enumerable: true }) : target,
mod
));
var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
var __publicField = (obj, key, value) => __defNormalProp(obj, typeof key !== "symbol" ? key + "" : key, value);
var __accessCheck = (obj, member, msg) => member.has(obj) || __typeError("Cannot " + msg);
var __privateGet = (obj, member, getter) => (__accessCheck(obj, member, "read from private field"), getter ? getter.call(obj) : member.get(obj));
var __privateAdd = (obj, member, value) => member.has(obj) ? __typeError("Cannot add the same private member more than once") : member instanceof WeakSet ? member.add(obj) : member.set(obj, value);
var __privateSet = (obj, member, value, setter) => (__accessCheck(obj, member, "write to private field"), setter ? setter.call(obj, value) : member.set(obj, value), value);
var __async = (__this, __arguments, generator) => {
return new Promise((resolve, reject) => {
var fulfilled = (value) => {
try {
step(generator.next(value));
} catch (e2) {
reject(e2);
}
};
var rejected = (value) => {
try {
step(generator.throw(value));
} catch (e2) {
reject(e2);
}
};
var step = (x) => x.done ? resolve(x.value) : Promise.resolve(x.value).then(fulfilled, rejected);
step((generator = generator.apply(__this, __arguments)).next());
});
};
var __await = function(promise, isYieldStar) {
this[0] = promise;
this[1] = isYieldStar;
};
var __asyncGenerator = (__this, __arguments, generator) => {
var resume = (k, v, yes, no) => {
try {
var x = generator[k](v), isAwait = (v = x.value) instanceof __await, done = x.done;
Promise.resolve(isAwait ? v[0] : v).then((y) => isAwait ? resume(k === "return" ? k : "next", v[1] ? { done: y.done, value: y.value } : y, yes, no) : yes({ value: y, done })).catch((e2) => resume("throw", e2, yes, no));
} catch (e2) {
no(e2);
}
}, method = (k) => it[k] = (x) => new Promise((yes, no) => resume(k, x, yes, no)), it = {};
return generator = generator.apply(__this, __arguments), it[__knownSymbol("asyncIterator")] = () => it, method("next"), method("throw"), method("return"), it;
};
var __yieldStar = (value) => {
var obj = value[__knownSymbol("asyncIterator")], isAwait = false, method, it = {};
if (obj == null) {
obj = value[__knownSymbol("iterator")]();
method = (k) => it[k] = (x) => obj[k](x);
} else {
obj = obj.call(value);
method = (k) => it[k] = (v) => {
if (isAwait) {
isAwait = false;
if (k === "throw") throw v;
return v;
}
isAwait = true;
return {
done: false,
value: new __await(new Promise((resolve) => {
var x = obj[k](v);
if (!(x instanceof Object)) __typeError("Object expected");
resolve(x);
}), 1)
};
};
}
return it[__knownSymbol("iterator")] = () => it, method("next"), "throw" in obj ? method("throw") : it.throw = (x) => {
throw x;
}, "return" in obj && method("return"), it;
};
var __forAwait = (obj, it, method) => (it = obj[__knownSymbol("asyncIterator")]) ? it.call(obj) : (obj = obj[__knownSymbol("iterator")](), it = {}, method = (key, fn) => (fn = obj[key]) && (it[key] = (arg) => new Promise((yes, no, done) => (arg = fn.call(obj, arg), done = arg.done, Promise.resolve(arg.value).then((value) => yes({ value, done }), no)))), method("next"), method("return"), it);
// shims/process.js
var process;
var init_process = __esm({
"shims/process.js"() {
"use strict";
process = void 0;
}
});
// ../../node_modules/.pnpm/jsrsasign@11.1.0/node_modules/jsrsasign/lib/jsrsasign.js
var require_jsrsasign = __commonJS({
"../../node_modules/.pnpm/jsrsasign@11.1.0/node_modules/jsrsasign/lib/jsrsasign.js"(exports) {
init_process();
var navigator2 = {};
navigator2.userAgent = false;
var window2 = {};
var VERSION3 = "11.1.0";
var VERSION_FULL = "jsrsasign(all) 11.1.0 (2024-02-01) (c) 2010-2023 Kenji Urushima | kjur.github.io/jsrsasign/license";
var CryptoJS = CryptoJS || (function(e2, g) {
var a = {};
var b = a.lib = {};
var j = b.Base = /* @__PURE__ */ (function() {
function n2() {
}
return { extend: function(p) {
n2.prototype = this;
var o2 = new n2();
if (p) {
o2.mixIn(p);
}
if (!o2.hasOwnProperty("init")) {
o2.init = function() {
o2.$super.init.apply(this, arguments);
};
}
o2.init.prototype = o2;
o2.$super = this;
return o2;
}, create: function() {
var o2 = this.extend();
o2.init.apply(o2, arguments);
return o2;
}, init: function() {
}, mixIn: function(p) {
for (var o2 in p) {
if (p.hasOwnProperty(o2)) {
this[o2] = p[o2];
}
}
if (p.hasOwnProperty("toString")) {
this.toString = p.toString;
}
}, clone: function() {
return this.init.prototype.extend(this);
} };
})();
var l = b.WordArray = j.extend({ init: function(o2, n2) {
o2 = this.words = o2 || [];
if (n2 != g) {
this.sigBytes = n2;
} else {
this.sigBytes = o2.length * 4;
}
}, toString: function(n2) {
return (n2 || h).stringify(this);
}, concat: function(t3) {
var q = this.words;
var p = t3.words;
var n2 = this.sigBytes;
var s = t3.sigBytes;
this.clamp();
if (n2 % 4) {
for (var r2 = 0; r2 < s; r2++) {
var o2 = p[r2 >>> 2] >>> 24 - r2 % 4 * 8 & 255;
q[n2 + r2 >>> 2] |= o2 << 24 - (n2 + r2) % 4 * 8;
}
} else {
for (var r2 = 0; r2 < s; r2 += 4) {
q[n2 + r2 >>> 2] = p[r2 >>> 2];
}
}
this.sigBytes += s;
return this;
}, clamp: function() {
var o2 = this.words;
var n2 = this.sigBytes;
o2[n2 >>> 2] &= 4294967295 << 32 - n2 % 4 * 8;
o2.length = e2.ceil(n2 / 4);
}, clone: function() {
var n2 = j.clone.call(this);
n2.words = this.words.slice(0);
return n2;
}, random: function(p) {
var o2 = [];
for (var n2 = 0; n2 < p; n2 += 4) {
o2.push(e2.random() * 4294967296 | 0);
}
return new l.init(o2, p);
} });
var m = a.enc = {};
var h = m.Hex = { stringify: function(p) {
var r2 = p.words;
var o2 = p.sigBytes;
var q = [];
for (var n2 = 0; n2 < o2; n2++) {
var s = r2[n2 >>> 2] >>> 24 - n2 % 4 * 8 & 255;
q.push((s >>> 4).toString(16));
q.push((s & 15).toString(16));
}
return q.join("");
}, parse: function(p) {
var n2 = p.length;
var q = [];
for (var o2 = 0; o2 < n2; o2 += 2) {
q[o2 >>> 3] |= parseInt(p.substr(o2, 2), 16) << 24 - o2 % 8 * 4;
}
return new l.init(q, n2 / 2);
} };
var d = m.Latin1 = { stringify: function(q) {
var r2 = q.words;
var p = q.sigBytes;
var n2 = [];
for (var o2 = 0; o2 < p; o2++) {
var s = r2[o2 >>> 2] >>> 24 - o2 % 4 * 8 & 255;
n2.push(String.fromCharCode(s));
}
return n2.join("");
}, parse: function(p) {
var n2 = p.length;
var q = [];
for (var o2 = 0; o2 < n2; o2++) {
q[o2 >>> 2] |= (p.charCodeAt(o2) & 255) << 24 - o2 % 4 * 8;
}
return new l.init(q, n2);
} };
var c = m.Utf8 = { stringify: function(n2) {
try {
return decodeURIComponent(escape(d.stringify(n2)));
} catch (o2) {
throw new Error("Malformed UTF-8 data");
}
}, parse: function(n2) {
return d.parse(unescape(encodeURIComponent(n2)));
} };
var i = b.BufferedBlockAlgorithm = j.extend({ reset: function() {
this._data = new l.init();
this._nDataBytes = 0;
}, _append: function(n2) {
if (typeof n2 == "string") {
n2 = c.parse(n2);
}
this._data.concat(n2);
this._nDataBytes += n2.sigBytes;
}, _process: function(w) {
var q = this._data;
var x = q.words;
var n2 = q.sigBytes;
var t3 = this.blockSize;
var v = t3 * 4;
var u = n2 / v;
if (w) {
u = e2.ceil(u);
} else {
u = e2.max((u | 0) - this._minBufferSize, 0);
}
var s = u * t3;
var r2 = e2.min(s * 4, n2);
if (s) {
for (var p = 0; p < s; p += t3) {
this._doProcessBlock(x, p);
}
var o2 = x.splice(0, s);
q.sigBytes -= r2;
}
return new l.init(o2, r2);
}, clone: function() {
var n2 = j.clone.call(this);
n2._data = this._data.clone();
return n2;
}, _minBufferSize: 0 });
var f = b.Hasher = i.extend({ cfg: j.extend(), init: function(n2) {
this.cfg = this.cfg.extend(n2);
this.reset();
}, reset: function() {
i.reset.call(this);
this._doReset();
}, update: function(n2) {
this._append(n2);
this._process();
return this;
}, finalize: function(n2) {
if (n2) {
this._append(n2);
}
var o2 = this._doFinalize();
return o2;
}, blockSize: 512 / 32, _createHelper: function(n2) {
return function(p, o2) {
return new n2.init(o2).finalize(p);
};
}, _createHmacHelper: function(n2) {
return function(p, o2) {
return new k.HMAC.init(n2, o2).finalize(p);
};
} });
var k = a.algo = {};
return a;
})(Math);
(function(g) {
var a = CryptoJS, f = a.lib, e2 = f.Base, h = f.WordArray, a = a.x64 = {};
a.Word = e2.extend({ init: function(b, c) {
this.high = b;
this.low = c;
} });
a.WordArray = e2.extend({ init: function(b, c) {
b = this.words = b || [];
this.sigBytes = c != g ? c : 8 * b.length;
}, toX32: function() {
for (var b = this.words, c = b.length, a2 = [], d = 0; d < c; d++) {
var e3 = b[d];
a2.push(e3.high);
a2.push(e3.low);
}
return h.create(a2, this.sigBytes);
}, clone: function() {
for (var b = e2.clone.call(this), c = b.words = this.words.slice(0), a2 = c.length, d = 0; d < a2; d++) c[d] = c[d].clone();
return b;
} });
})();
CryptoJS.lib.Cipher || (function(u) {
var g = CryptoJS, f = g.lib, k = f.Base, l = f.WordArray, q = f.BufferedBlockAlgorithm, r2 = g.enc.Base64, v = g.algo.EvpKDF, n2 = f.Cipher = q.extend({ cfg: k.extend(), createEncryptor: function(a, b) {
return this.create(this._ENC_XFORM_MODE, a, b);
}, createDecryptor: function(a, b) {
return this.create(this._DEC_XFORM_MODE, a, b);
}, init: function(a, b, c) {
this.cfg = this.cfg.extend(c);
this._xformMode = a;
this._key = b;
this.reset();
}, reset: function() {
q.reset.call(this);
this._doReset();
}, process: function(a) {
this._append(a);
return this._process();
}, finalize: function(a) {
a && this._append(a);
return this._doFinalize();
}, keySize: 4, ivSize: 4, _ENC_XFORM_MODE: 1, _DEC_XFORM_MODE: 2, _createHelper: function(a) {
return { encrypt: function(b, c, d) {
return ("string" == typeof c ? s : j).encrypt(a, b, c, d);
}, decrypt: function(b, c, d) {
return ("string" == typeof c ? s : j).decrypt(a, b, c, d);
} };
} });
f.StreamCipher = n2.extend({ _doFinalize: function() {
return this._process(true);
}, blockSize: 1 });
var m = g.mode = {}, t3 = function(a, b, c) {
var d = this._iv;
d ? this._iv = u : d = this._prevBlock;
for (var e2 = 0; e2 < c; e2++) a[b + e2] ^= d[e2];
}, h = (f.BlockCipherMode = k.extend({ createEncryptor: function(a, b) {
return this.Encryptor.create(a, b);
}, createDecryptor: function(a, b) {
return this.Decryptor.create(a, b);
}, init: function(a, b) {
this._cipher = a;
this._iv = b;
} })).extend();
h.Encryptor = h.extend({ processBlock: function(a, b) {
var c = this._cipher, d = c.blockSize;
t3.call(this, a, b, d);
c.encryptBlock(a, b);
this._prevBlock = a.slice(b, b + d);
} });
h.Decryptor = h.extend({ processBlock: function(a, b) {
var c = this._cipher, d = c.blockSize, e2 = a.slice(b, b + d);
c.decryptBlock(
a,
b
);
t3.call(this, a, b, d);
this._prevBlock = e2;
} });
m = m.CBC = h;
h = (g.pad = {}).Pkcs7 = { pad: function(a, b) {
for (var c = 4 * b, c = c - a.sigBytes % c, d = c << 24 | c << 16 | c << 8 | c, e2 = [], f2 = 0; f2 < c; f2 += 4) e2.push(d);
c = l.create(e2, c);
a.concat(c);
}, unpad: function(a) {
a.sigBytes -= a.words[a.sigBytes - 1 >>> 2] & 255;
} };
f.BlockCipher = n2.extend({ cfg: n2.cfg.extend({ mode: m, padding: h }), reset: function() {
n2.reset.call(this);
var a = this.cfg, b = a.iv, a = a.mode;
if (this._xformMode == this._ENC_XFORM_MODE) var c = a.createEncryptor;
else c = a.createDecryptor, this._minBufferSize = 1;
this._mode = c.call(a, this, b && b.words);
}, _doProcessBlock: function(a, b) {
this._mode.processBlock(a, b);
}, _doFinalize: function() {
var a = this.cfg.padding;
if (this._xformMode == this._ENC_XFORM_MODE) {
a.pad(this._data, this.blockSize);
var b = this._process(true);
} else b = this._process(true), a.unpad(b);
return b;
}, blockSize: 4 });
var p = f.CipherParams = k.extend({ init: function(a) {
this.mixIn(a);
}, toString: function(a) {
return (a || this.formatter).stringify(this);
} }), m = (g.format = {}).OpenSSL = { stringify: function(a) {
var b = a.ciphertext;
a = a.salt;
return (a ? l.create([1398893684, 1701076831]).concat(a).concat(b) : b).toString(r2);
}, parse: function(a) {
a = r2.parse(a);
var b = a.words;
if (1398893684 == b[0] && 1701076831 == b[1]) {
var c = l.create(b.slice(2, 4));
b.splice(0, 4);
a.sigBytes -= 16;
}
return p.create({ ciphertext: a, salt: c });
} }, j = f.SerializableCipher = k.extend({ cfg: k.extend({ format: m }), encrypt: function(a, b, c, d) {
d = this.cfg.extend(d);
var e2 = a.createEncryptor(c, d);
b = e2.finalize(b);
e2 = e2.cfg;
return p.create({
ciphertext: b,
key: c,
iv: e2.iv,
algorithm: a,
mode: e2.mode,
padding: e2.padding,
blockSize: a.blockSize,
formatter: d.format
});
}, decrypt: function(a, b, c, d) {
d = this.cfg.extend(d);
b = this._parse(b, d.format);
return a.createDecryptor(c, d).finalize(b.ciphertext);
}, _parse: function(a, b) {
return "string" == typeof a ? b.parse(a, this) : a;
} }), g = (g.kdf = {}).OpenSSL = { execute: function(a, b, c, d) {
d || (d = l.random(8));
a = v.create({ keySize: b + c }).compute(a, d);
c = l.create(a.words.slice(b), 4 * c);
a.sigBytes = 4 * b;
return p.create({ key: a, iv: c, salt: d });
} }, s = f.PasswordBasedCipher = j.extend({ cfg: j.cfg.extend({ kdf: g }), encrypt: function(a, b, c, d) {
d = this.cfg.extend(d);
c = d.kdf.execute(c, a.keySize, a.ivSize);
d.iv = c.iv;
a = j.encrypt.call(this, a, b, c.key, d);
a.mixIn(c);
return a;
}, decrypt: function(a, b, c, d) {
d = this.cfg.extend(d);
b = this._parse(b, d.format);
c = d.kdf.execute(c, a.keySize, a.ivSize, b.salt);
d.iv = c.iv;
return j.decrypt.call(this, a, b, c.key, d);
} });
})();
(function() {
for (var q = CryptoJS, x = q.lib.BlockCipher, r2 = q.algo, j = [], y = [], z2 = [], A = [], B = [], C = [], s = [], u = [], v = [], w = [], g = [], k = 0; 256 > k; k++) g[k] = 128 > k ? k << 1 : k << 1 ^ 283;
for (var n2 = 0, l = 0, k = 0; 256 > k; k++) {
var f = l ^ l << 1 ^ l << 2 ^ l << 3 ^ l << 4, f = f >>> 8 ^ f & 255 ^ 99;
j[n2] = f;
y[f] = n2;
var t3 = g[n2], D = g[t3], E = g[D], b = 257 * g[f] ^ 16843008 * f;
z2[n2] = b << 24 | b >>> 8;
A[n2] = b << 16 | b >>> 16;
B[n2] = b << 8 | b >>> 24;
C[n2] = b;
b = 16843009 * E ^ 65537 * D ^ 257 * t3 ^ 16843008 * n2;
s[f] = b << 24 | b >>> 8;
u[f] = b << 16 | b >>> 16;
v[f] = b << 8 | b >>> 24;
w[f] = b;
n2 ? (n2 = t3 ^ g[g[g[E ^ t3]]], l ^= g[g[l]]) : n2 = l = 1;
}
var F = [
0,
1,
2,
4,
8,
16,
32,
64,
128,
27,
54
], r2 = r2.AES = x.extend({ _doReset: function() {
for (var c = this._key, e2 = c.words, a = c.sigBytes / 4, c = 4 * ((this._nRounds = a + 6) + 1), b2 = this._keySchedule = [], h = 0; h < c; h++) if (h < a) b2[h] = e2[h];
else {
var d = b2[h - 1];
h % a ? 6 < a && 4 == h % a && (d = j[d >>> 24] << 24 | j[d >>> 16 & 255] << 16 | j[d >>> 8 & 255] << 8 | j[d & 255]) : (d = d << 8 | d >>> 24, d = j[d >>> 24] << 24 | j[d >>> 16 & 255] << 16 | j[d >>> 8 & 255] << 8 | j[d & 255], d ^= F[h / a | 0] << 24);
b2[h] = b2[h - a] ^ d;
}
e2 = this._invKeySchedule = [];
for (a = 0; a < c; a++) h = c - a, d = a % 4 ? b2[h] : b2[h - 4], e2[a] = 4 > a || 4 >= h ? d : s[j[d >>> 24]] ^ u[j[d >>> 16 & 255]] ^ v[j[d >>> 8 & 255]] ^ w[j[d & 255]];
}, encryptBlock: function(c, e2) {
this._doCryptBlock(c, e2, this._keySchedule, z2, A, B, C, j);
}, decryptBlock: function(c, e2) {
var a = c[e2 + 1];
c[e2 + 1] = c[e2 + 3];
c[e2 + 3] = a;
this._doCryptBlock(c, e2, this._invKeySchedule, s, u, v, w, y);
a = c[e2 + 1];
c[e2 + 1] = c[e2 + 3];
c[e2 + 3] = a;
}, _doCryptBlock: function(c, e2, a, b2, h, d, j2, m) {
for (var n3 = this._nRounds, f2 = c[e2] ^ a[0], g2 = c[e2 + 1] ^ a[1], k2 = c[e2 + 2] ^ a[2], p = c[e2 + 3] ^ a[3], l2 = 4, t4 = 1; t4 < n3; t4++) var q2 = b2[f2 >>> 24] ^ h[g2 >>> 16 & 255] ^ d[k2 >>> 8 & 255] ^ j2[p & 255] ^ a[l2++], r3 = b2[g2 >>> 24] ^ h[k2 >>> 16 & 255] ^ d[p >>> 8 & 255] ^ j2[f2 & 255] ^ a[l2++], s2 = b2[k2 >>> 24] ^ h[p >>> 16 & 255] ^ d[f2 >>> 8 & 255] ^ j2[g2 & 255] ^ a[l2++], p = b2[p >>> 24] ^ h[f2 >>> 16 & 255] ^ d[g2 >>> 8 & 255] ^ j2[k2 & 255] ^ a[l2++], f2 = q2, g2 = r3, k2 = s2;
q2 = (m[f2 >>> 24] << 24 | m[g2 >>> 16 & 255] << 16 | m[k2 >>> 8 & 255] << 8 | m[p & 255]) ^ a[l2++];
r3 = (m[g2 >>> 24] << 24 | m[k2 >>> 16 & 255] << 16 | m[p >>> 8 & 255] << 8 | m[f2 & 255]) ^ a[l2++];
s2 = (m[k2 >>> 24] << 24 | m[p >>> 16 & 255] << 16 | m[f2 >>> 8 & 255] << 8 | m[g2 & 255]) ^ a[l2++];
p = (m[p >>> 24] << 24 | m[f2 >>> 16 & 255] << 16 | m[g2 >>> 8 & 255] << 8 | m[k2 & 255]) ^ a[l2++];
c[e2] = q2;
c[e2 + 1] = r3;
c[e2 + 2] = s2;
c[e2 + 3] = p;
}, keySize: 8 });
q.AES = x._createHelper(r2);
})();
(function() {
function j(b, c) {
var a = (this._lBlock >>> b ^ this._rBlock) & c;
this._rBlock ^= a;
this._lBlock ^= a << b;
}
function l(b, c) {
var a = (this._rBlock >>> b ^ this._lBlock) & c;
this._lBlock ^= a;
this._rBlock ^= a << b;
}
var h = CryptoJS, e2 = h.lib, n2 = e2.WordArray, e2 = e2.BlockCipher, g = h.algo, q = [57, 49, 41, 33, 25, 17, 9, 1, 58, 50, 42, 34, 26, 18, 10, 2, 59, 51, 43, 35, 27, 19, 11, 3, 60, 52, 44, 36, 63, 55, 47, 39, 31, 23, 15, 7, 62, 54, 46, 38, 30, 22, 14, 6, 61, 53, 45, 37, 29, 21, 13, 5, 28, 20, 12, 4], p = [
14,
17,
11,
24,
1,
5,
3,
28,
15,
6,
21,
10,
23,
19,
12,
4,
26,
8,
16,
7,
27,
20,
13,
2,
41,
52,
31,
37,
47,
55,
30,
40,
51,
45,
33,
48,
44,
49,
39,
56,
34,
53,
46,
42,
50,
36,
29,
32
], r2 = [1, 2, 4, 6, 8, 10, 12, 14, 15, 17, 19, 21, 23, 25, 27, 28], s = [{
"0": 8421888,
268435456: 32768,
536870912: 8421378,
805306368: 2,
1073741824: 512,
1342177280: 8421890,
1610612736: 8389122,
1879048192: 8388608,
2147483648: 514,
2415919104: 8389120,
2684354560: 33280,
2952790016: 8421376,
3221225472: 32770,
3489660928: 8388610,
3758096384: 0,
4026531840: 33282,
134217728: 0,
402653184: 8421890,
671088640: 33282,
939524096: 32768,
1207959552: 8421888,
1476395008: 512,
1744830464: 8421378,
2013265920: 2,
2281701376: 8389120,
2550136832: 33280,
2818572288: 8421376,
3087007744: 8389122,
3355443200: 8388610,
3623878656: 32770,
3892314112: 514,
4160749568: 8388608,
1: 32768,
268435457: 2,
536870913: 8421888,
805306369: 8388608,
1073741825: 8421378,
1342177281: 33280,
1610612737: 512,
1879048193: 8389122,
2147483649: 8421890,
2415919105: 8421376,
2684354561: 8388610,
2952790017: 33282,
3221225473: 514,
3489660929: 8389120,
3758096385: 32770,
4026531841: 0,
134217729: 8421890,
402653185: 8421376,
671088641: 8388608,
939524097: 512,
1207959553: 32768,
1476395009: 8388610,
1744830465: 2,
2013265921: 33282,
2281701377: 32770,
2550136833: 8389122,
2818572289: 514,
3087007745: 8421888,
3355443201: 8389120,
3623878657: 0,
3892314113: 33280,
4160749569: 8421378
}, {
"0": 1074282512,
16777216: 16384,
33554432: 524288,
50331648: 1074266128,
67108864: 1073741840,
83886080: 1074282496,
100663296: 1073758208,
117440512: 16,
134217728: 540672,
150994944: 1073758224,
167772160: 1073741824,
184549376: 540688,
201326592: 524304,
218103808: 0,
234881024: 16400,
251658240: 1074266112,
8388608: 1073758208,
25165824: 540688,
41943040: 16,
58720256: 1073758224,
75497472: 1074282512,
92274688: 1073741824,
109051904: 524288,
125829120: 1074266128,
142606336: 524304,
159383552: 0,
176160768: 16384,
192937984: 1074266112,
209715200: 1073741840,
226492416: 540672,
243269632: 1074282496,
260046848: 16400,
268435456: 0,
285212672: 1074266128,
301989888: 1073758224,
318767104: 1074282496,
335544320: 1074266112,
352321536: 16,
369098752: 540688,
385875968: 16384,
402653184: 16400,
419430400: 524288,
436207616: 524304,
452984832: 1073741840,
469762048: 540672,
486539264: 1073758208,
503316480: 1073741824,
520093696: 1074282512,
276824064: 540688,
293601280: 524288,
310378496: 1074266112,
327155712: 16384,
343932928: 1073758208,
360710144: 1074282512,
377487360: 16,
394264576: 1073741824,
411041792: 1074282496,
427819008: 1073741840,
444596224: 1073758224,
461373440: 524304,
478150656: 0,
494927872: 16400,
511705088: 1074266128,
528482304: 540672
}, {
"0": 260,
1048576: 0,
2097152: 67109120,
3145728: 65796,
4194304: 65540,
5242880: 67108868,
6291456: 67174660,
7340032: 67174400,
8388608: 67108864,
9437184: 67174656,
10485760: 65792,
11534336: 67174404,
12582912: 67109124,
13631488: 65536,
14680064: 4,
15728640: 256,
524288: 67174656,
1572864: 67174404,
2621440: 0,
3670016: 67109120,
4718592: 67108868,
5767168: 65536,
6815744: 65540,
7864320: 260,
8912896: 4,
9961472: 256,
11010048: 67174400,
12058624: 65796,
13107200: 65792,
14155776: 67109124,
15204352: 67174660,
16252928: 67108864,
16777216: 67174656,
17825792: 65540,
18874368: 65536,
19922944: 67109120,
20971520: 256,
22020096: 67174660,
23068672: 67108868,
24117248: 0,
25165824: 67109124,
26214400: 67108864,
27262976: 4,
28311552: 65792,
29360128: 67174400,
30408704: 260,
31457280: 65796,
32505856: 67174404,
17301504: 67108864,
18350080: 260,
19398656: 67174656,
20447232: 0,
21495808: 65540,
22544384: 67109120,
23592960: 256,
24641536: 67174404,
25690112: 65536,
26738688: 67174660,
27787264: 65796,
28835840: 67108868,
29884416: 67109124,
30932992: 67174400,
31981568: 4,
33030144: 65792
}, {
"0": 2151682048,
65536: 2147487808,
131072: 4198464,
196608: 2151677952,
262144: 0,
327680: 4198400,
393216: 2147483712,
458752: 4194368,
524288: 2147483648,
589824: 4194304,
655360: 64,
720896: 2147487744,
786432: 2151678016,
851968: 4160,
917504: 4096,
983040: 2151682112,
32768: 2147487808,
98304: 64,
163840: 2151678016,
229376: 2147487744,
294912: 4198400,
360448: 2151682112,
425984: 0,
491520: 2151677952,
557056: 4096,
622592: 2151682048,
688128: 4194304,
753664: 4160,
819200: 2147483648,
884736: 4194368,
950272: 4198464,
1015808: 2147483712,
1048576: 4194368,
1114112: 4198400,
1179648: 2147483712,
1245184: 0,
1310720: 4160,
1376256: 2151678016,
1441792: 2151682048,
1507328: 2147487808,
1572864: 2151682112,
1638400: 2147483648,
1703936: 2151677952,
1769472: 4198464,
1835008: 2147487744,
1900544: 4194304,
1966080: 64,
2031616: 4096,
1081344: 2151677952,
1146880: 2151682112,
1212416: 0,
1277952: 4198400,
1343488: 4194368,
1409024: 2147483648,
1474560: 2147487808,
1540096: 64,
1605632: 2147483712,
1671168: 4096,
1736704: 2147487744,
1802240: 2151678016,
1867776: 4160,
1933312: 2151682048,
1998848: 4194304,
2064384: 4198464
}, {
"0": 128,
4096: 17039360,
8192: 262144,
12288: 536870912,
16384: 537133184,
20480: 16777344,
24576: 553648256,
28672: 262272,
32768: 16777216,
36864: 537133056,
40960: 536871040,
45056: 553910400,
49152: 553910272,
53248: 0,
57344: 17039488,
61440: 553648128,
2048: 17039488,
6144: 553648256,
10240: 128,
14336: 17039360,
18432: 262144,
22528: 537133184,
26624: 553910272,
30720: 536870912,
34816: 537133056,
38912: 0,
43008: 553910400,
47104: 16777344,
51200: 536871040,
55296: 553648128,
59392: 16777216,
63488: 262272,
65536: 262144,
69632: 128,
73728: 536870912,
77824: 553648256,
81920: 16777344,
86016: 553910272,
90112: 537133184,
94208: 16777216,
98304: 553910400,
102400: 553648128,
106496: 17039360,
110592: 537133056,
114688: 262272,
118784: 536871040,
122880: 0,
126976: 17039488,
67584: 553648256,
71680: 16777216,
75776: 17039360,
79872: 537133184,
83968: 536870912,
88064: 17039488,
92160: 128,
96256: 553910272,
100352: 262272,
104448: 553910400,
108544: 0,
112640: 553648128,
116736: 16777344,
120832: 262144,
124928: 537133056,
129024: 536871040
}, {
"0": 268435464,
256: 8192,
512: 270532608,
768: 270540808,
1024: 268443648,
1280: 2097152,
1536: 2097160,
1792: 268435456,
2048: 0,
2304: 268443656,
2560: 2105344,
2816: 8,
3072: 270532616,
3328: 2105352,
3584: 8200,
3840: 270540800,
128: 270532608,
384: 270540808,
640: 8,
896: 2097152,
1152: 2105352,
1408: 268435464,
1664: 268443648,
1920: 8200,
2176: 2097160,
2432: 8192,
2688: 268443656,
2944: 270532616,
3200: 0,
3456: 270540800,
3712: 2105344,
3968: 268435456,
4096: 268443648,
4352: 270532616,
4608: 270540808,
4864: 8200,
5120: 2097152,
5376: 268435456,
5632: 268435464,
5888: 2105344,
6144: 2105352,
6400: 0,
6656: 8,
6912: 270532608,
7168: 8192,
7424: 268443656,
7680: 270540800,
7936: 2097160,
4224: 8,
4480: 2105344,
4736: 2097152,
4992: 268435464,
5248: 268443648,
5504: 8200,
5760: 270540808,
6016: 270532608,
6272: 270540800,
6528: 270532616,
6784: 8192,
7040: 2105352,
7296: 2097160,
7552: 0,
7808: 268435456,
8064: 268443656
}, {
"0": 1048576,
16: 33555457,
32: 1024,
48: 1049601,
64: 34604033,
80: 0,
96: 1,
112: 34603009,
128: 33555456,
144: 1048577,
160: 33554433,
176: 34604032,
192: 34603008,
208: 1025,
224: 1049600,
240: 33554432,
8: 34603009,
24: 0,
40: 33555457,
56: 34604032,
72: 1048576,
88: 33554433,
104: 33554432,
120: 1025,
136: 1049601,
152: 33555456,
168: 34603008,
184: 1048577,
200: 1024,
216: 34604033,
232: 1,
248: 1049600,
256: 33554432,
272: 1048576,
288: 33555457,
304: 34603009,
320: 1048577,
336: 33555456,
352: 34604032,
368: 1049601,
384: 1025,
400: 34604033,
416: 1049600,
432: 1,
448: 0,
464: 34603008,
480: 33554433,
496: 1024,
264: 1049600,
280: 33555457,
296: 34603009,
312: 1,
328: 33554432,
344: 1048576,
360: 1025,
376: 34604032,
392: 33554433,
408: 34603008,
424: 0,
440: 34604033,
456: 1049601,
472: 1024,
488: 33555456,
504: 1048577
}, {
"0": 134219808,
1: 131072,
2: 134217728,
3: 32,
4: 131104,
5: 134350880,
6: 134350848,
7: 2048,
8: 134348800,
9: 134219776,
10: 133120,
11: 134348832,
12: 2080,
13: 0,
14: 134217760,
15: 133152,
2147483648: 2048,
2147483649: 134350880,
2147483650: 134219808,
2147483651: 134217728,
2147483652: 134348800,
2147483653: 133120,
2147483654: 133152,
2147483655: 32,
2147483656: 134217760,
2147483657: 2080,
2147483658: 131104,
2147483659: 134350848,
2147483660: 0,
2147483661: 134348832,
2147483662: 134219776,
2147483663: 131072,
16: 133152,
17: 134350848,
18: 32,
19: 2048,
20: 134219776,
21: 134217760,
22: 134348832,
23: 131072,
24: 0,
25: 131104,
26: 134348800,
27: 134219808,
28: 134350880,
29: 133120,
30: 2080,
31: 134217728,
2147483664: 131072,
2147483665: 2048,
2147483666: 134348832,
2147483667: 133152,
2147483668: 32,
2147483669: 134348800,
2147483670: 134217728,
2147483671: 134219808,
2147483672: 134350880,
2147483673: 134217760,
2147483674: 134219776,
2147483675: 0,
2147483676: 133120,
2147483677: 2080,
2147483678: 131104,
2147483679: 134350848
}], t3 = [4160749569, 528482304, 33030144, 2064384, 129024, 8064, 504, 2147483679], m = g.DES = e2.extend({ _doReset: function() {
for (var b = this._key.words, c = [], a = 0; 56 > a; a++) {
var f = q[a] - 1;
c[a] = b[f >>> 5] >>> 31 - f % 32 & 1;
}
b = this._subKeys = [];
for (f = 0; 16 > f; f++) {
for (var d = b[f] = [], e3 = r2[f], a = 0; 24 > a; a++) d[a / 6 | 0] |= c[(p[a] - 1 + e3) % 28] << 31 - a % 6, d[4 + (a / 6 | 0)] |= c[28 + (p[a + 24] - 1 + e3) % 28] << 31 - a % 6;
d[0] = d[0] << 1 | d[0] >>> 31;
for (a = 1; 7 > a; a++) d[a] >>>= 4 * (a - 1) + 3;
d[7] = d[7] << 5 | d[7] >>> 27;
}
c = this._invSubKeys = [];
for (a = 0; 16 > a; a++) c[a] = b[15 - a];
}, encryptBlock: function(b, c) {
this._doCryptBlock(b, c, this._subKeys);
}, decryptBlock: function(b, c) {
this._doCryptBlock(b, c, this._invSubKeys);
}, _doCryptBlock: function(b, c, a) {
this._lBlock = b[c];
this._rBlock = b[c + 1];
j.call(this, 4, 252645135);
j.call(this, 16, 65535);
l.call(this, 2, 858993459);
l.call(this, 8, 16711935);
j.call(this, 1, 1431655765);
for (var f = 0; 16 > f; f++) {
for (var d = a[f], e3 = this._lBlock, h2 = this._rBlock, g2 = 0, k = 0; 8 > k; k++) g2 |= s[k][((h2 ^ d[k]) & t3[k]) >>> 0];
this._lBlock = h2;
this._rBlock = e3 ^ g2;
}
a = this._lBlock;
this._lBlock = this._rBlock;
this._rBlock = a;
j.call(this, 1, 1431655765);
l.call(this, 8, 16711935);
l.call(this, 2, 858993459);
j.call(this, 16, 65535);
j.call(this, 4, 252645135);
b[c] = this._lBlock;
b[c + 1] = this._rBlock;
}, keySize: 2, ivSize: 2, blockSize: 2 });
h.DES = e2._createHelper(m);
g = g.TripleDES = e2.extend({ _doReset: function() {
var b = this._key.words;
this._des1 = m.createEncryptor(n2.create(b.slice(0, 2)));
this._des2 = m.createEncryptor(n2.create(b.slice(2, 4)));
this._des3 = m.createEncryptor(n2.create(b.slice(4, 6)));
}, encryptBlock: function(b, c) {
this._des1.encryptBlock(b, c);
this._des2.decryptBlock(b, c);
this._des3.encryptBlock(b, c);
}, decryptBlock: function(b, c) {
this._des3.decryptBlock(b, c);
this._des2.encryptBlock(b, c);
this._des1.decryptBlock(b, c);
}, keySize: 6, ivSize: 2, blockSize: 2 });
h.TripleDES = e2._createHelper(g);
})();
(function() {
var h = CryptoJS, j = h.lib.WordArray;
h.enc.Base64 = { stringify: function(b) {
var e2 = b.words, f = b.sigBytes, c = this._map;
b.clamp();
b = [];
for (var a = 0; a < f; a += 3) for (var d = (e2[a >>> 2] >>> 24 - 8 * (a % 4) & 255) << 16 | (e2[a + 1 >>> 2] >>> 24 - 8 * ((a + 1) % 4) & 255) << 8 | e2[a + 2 >>> 2] >>> 24 - 8 * ((a + 2) % 4) & 255, g = 0; 4 > g && a + 0.75 * g < f; g++) b.push(c.charAt(d >>> 6 * (3 - g) & 63));
if (e2 = c.charAt(64)) for (; b.length % 4; ) b.push(e2);
return b.join("");
}, parse: function(b) {
var e2 = b.length, f = this._map, c = f.charAt(64);
c && (c = b.indexOf(c), -1 != c && (e2 = c));
for (var c = [], a = 0, d = 0; d < e2; d++) if (d % 4) {
var g = f.indexOf(b.charAt(d - 1)) << 2 * (d % 4), h2 = f.indexOf(b.charAt(d)) >>> 6 - 2 * (d % 4);
c[a >>> 2] |= (g | h2) << 24 - 8 * (a % 4);
a++;
}
return j.create(c, a);
}, _map: "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=" };
})();
(function(E) {
function h(a2, f, g, j, p, h2, k2) {
a2 = a2 + (f & g | ~f & j) + p + k2;
return (a2 << h2 | a2 >>> 32 - h2) + f;
}
function k(a2, f, g, j, p, h2, k2) {
a2 = a2 + (f & j | g & ~j) + p + k2;
return (a2 << h2 | a2 >>> 32 - h2) + f;
}
function l(a2, f, g, j, h2, k2, l2) {
a2 = a2 + (f ^ g ^ j) + h2 + l2;
return (a2 << k2 | a2 >>> 32 - k2) + f;
}
function n2(a2, f, g, j, h2, k2, l2) {
a2 = a2 + (g ^ (f | ~j)) + h2 + l2;
return (a2 << k2 | a2 >>> 32 - k2) + f;
}
for (var r2 = CryptoJS, q = r2.lib, F = q.WordArray, s = q.Hasher, q = r2.algo, a = [], t3 = 0; 64 > t3; t3++) a[t3] = 4294967296 * E.abs(E.sin(t3 + 1)) | 0;
q = q.MD5 = s.extend({
_doReset: function() {
this._hash = new F.init([1732584193, 4023233417, 2562383102, 271733878]);
},
_doProcessBlock: function(m, f) {
for (var g = 0; 16 > g; g++) {
var j = f + g, p = m[j];
m[j] = (p << 8 | p >>> 24) & 16711935 | (p << 24 | p >>> 8) & 4278255360;
}
var g = this._hash.words, j = m[f + 0], p = m[f + 1], q2 = m[f + 2], r3 = m[f + 3], s2 = m[f + 4], t4 = m[f + 5], u = m[f + 6], v = m[f + 7], w = m[f + 8], x = m[f + 9], y = m[f + 10], z2 = m[f + 11], A = m[f + 12], B = m[f + 13], C = m[f + 14], D = m[f + 15], b = g[0], c = g[1], d = g[2], e2 = g[3], b = h(b, c, d, e2, j, 7, a[0]), e2 = h(e2, b, c, d, p, 12, a[1]), d = h(d, e2, b, c, q2, 17, a[2]), c = h(c, d, e2, b, r3, 22, a[3]), b = h(b, c, d, e2, s2, 7, a[4]), e2 = h(e2, b, c, d, t4, 12, a[5]), d = h(d, e2, b, c, u, 17, a[6]), c = h(c, d, e2, b, v, 22, a[7]), b = h(b, c, d, e2, w, 7, a[8]), e2 = h(e2, b, c, d, x, 12, a[9]), d = h(d, e2, b, c, y, 17, a[10]), c = h(c, d, e2, b, z2, 22, a[11]), b = h(b, c, d, e2, A, 7, a[12]), e2 = h(e2, b, c, d, B, 12, a[13]), d = h(d, e2, b, c, C, 17, a[14]), c = h(c, d, e2, b, D, 22, a[15]), b = k(b, c, d, e2, p, 5, a[16]), e2 = k(e2, b, c, d, u, 9, a[17]), d = k(d, e2, b, c, z2, 14, a[18]), c = k(c, d, e2, b, j, 20, a[19]), b = k(b, c, d, e2, t4, 5, a[20]), e2 = k(e2, b, c, d, y, 9, a[21]), d = k(d, e2, b, c, D, 14, a[22]), c = k(c, d, e2, b, s2, 20, a[23]), b = k(b, c, d, e2, x, 5, a[24]), e2 = k(e2, b, c, d, C, 9, a[25]), d = k(d, e2, b, c, r3, 14, a[26]), c = k(c, d, e2, b, w, 20, a[27]), b = k(b, c, d, e2, B, 5, a[28]), e2 = k(
e2,
b,
c,
d,
q2,
9,
a[29]
), d = k(d, e2, b, c, v, 14, a[30]), c = k(c, d, e2, b, A, 20, a[31]), b = l(b, c, d, e2, t4, 4, a[32]), e2 = l(e2, b, c, d, w, 11, a[33]), d = l(d, e2, b, c, z2, 16, a[34]), c = l(c, d, e2, b, C, 23, a[35]), b = l(b, c, d, e2, p, 4, a[36]), e2 = l(e2, b, c, d, s2, 11, a[37]), d = l(d, e2, b, c, v, 16, a[38]), c = l(c, d, e2, b, y, 23, a[39]), b = l(b, c, d, e2, B, 4, a[40]), e2 = l(e2, b, c, d, j, 11, a[41]), d = l(d, e2, b, c, r3, 16, a[42]), c = l(c, d, e2, b, u, 23, a[43]), b = l(b, c, d, e2, x, 4, a[44]), e2 = l(e2, b, c, d, A, 11, a[45]), d = l(d, e2, b, c, D, 16, a[46]), c = l(c, d, e2, b, q2, 23, a[47]), b = n2(b, c, d, e2, j, 6, a[48]), e2 = n2(e2, b, c, d, v, 10, a[49]), d = n2(
d,
e2,
b,
c,
C,
15,
a[50]
), c = n2(c, d, e2, b, t4, 21, a[51]), b = n2(b, c, d, e2, A, 6, a[52]), e2 = n2(e2, b, c, d, r3, 10, a[53]), d = n2(d, e2, b, c, y, 15, a[54]), c = n2(c, d, e2, b, p, 21, a[55]), b = n2(b, c, d, e2, w, 6, a[56]), e2 = n2(e2, b, c, d, D, 10, a[57]), d = n2(d, e2, b, c, u, 15, a[58]), c = n2(c, d, e2, b, B, 21, a[59]), b = n2(b, c, d, e2, s2, 6, a[60]), e2 = n2(e2, b, c, d, z2, 10, a[61]), d = n2(d, e2, b, c, q2, 15, a[62]), c = n2(c, d, e2, b, x, 21, a[63]);
g[0] = g[0] + b | 0;
g[1] = g[1] + c | 0;
g[2] = g[2] + d | 0;
g[3] = g[3] + e2 | 0;
},
_doFinalize: function() {
var a2 = this._data, f = a2.words, g = 8 * this._nDataBytes, j = 8 * a2.sigBytes;
f[j >>> 5] |= 128 << 24 - j % 32;
var h2 = E.floor(g / 4294967296);
f[(j + 64 >>> 9 << 4) + 15] = (h2 << 8 | h2 >>> 24) & 16711935 | (h2 << 24 | h2 >>> 8) & 4278255360;
f[(j + 64 >>> 9 << 4) + 14] = (g << 8 | g >>> 24) & 16711935 | (g << 24 | g >>> 8) & 4278255360;
a2.sigBytes = 4 * (f.length + 1);
this._process();
a2 = this._hash;
f = a2.words;
for (g = 0; 4 > g; g++) j = f[g], f[g] = (j << 8 | j >>> 24) & 16711935 | (j << 24 | j >>> 8) & 4278255360;
return a2;
},
clone: function() {
var a2 = s.clone.call(this);
a2._hash = this._hash.clone();
return a2;
}
});
r2.MD5 = s._createHelper(q);
r2.HmacMD5 = s._createHmacHelper(q);
})(Math);
(function() {
var k = CryptoJS, b = k.lib, m = b.WordArray, l = b.Hasher, d = [], b = k.algo.SHA1 = l.extend({ _doReset: function() {
this._hash = new m.init([1732584193, 4023233417, 2562383102, 271733878, 3285377520]);
}, _doProcessBlock: function(n2, p) {
for (var a = this._hash.words, e2 = a[0], f = a[1], h = a[2], j = a[3], b2 = a[4], c = 0; 80 > c; c++) {
if (16 > c) d[c] = n2[p + c] | 0;
else {
var g = d[c - 3] ^ d[c - 8] ^ d[c - 14] ^ d[c - 16];
d[c] = g << 1 | g >>> 31;
}
g = (e2 << 5 | e2 >>> 27) + b2 + d[c];
g = 20 > c ? g + ((f & h | ~f & j) + 1518500249) : 40 > c ? g + ((f ^ h ^ j) + 1859775393) : 60 > c ? g + ((f & h | f & j | h & j) - 1894007588) : g + ((f ^ h ^ j) - 899497514);
b2 = j;
j = h;
h = f << 30 | f >>> 2;
f = e2;
e2 = g;
}
a[0] = a[0] + e2 | 0;
a[1] = a[1] + f | 0;
a[2] = a[2] + h | 0;
a[3] = a[3] + j | 0;
a[4] = a[4] + b2 | 0;
}, _doFinalize: function() {
var b2 = this._data, d2 = b2.words, a = 8 * this._nDataBytes, e2 = 8 * b2.sigBytes;
d2[e2 >>> 5] |= 128 << 24 - e2 % 32;
d2[(e2 + 64 >>> 9 << 4) + 14] = Math.floor(a / 4294967296);
d2[(e2 + 64 >>> 9 << 4) + 15] = a;
b2.sigBytes = 4 * d2.length;
this._process();
return this._hash;
}, clone: function() {
var b2 = l.clone.call(this);
b2._hash = this._hash.clone();
return b2;
} });
k.SHA1 = l._createHelper(b);
k.HmacSHA1 = l._createHmacHelper(b);
})();
(function(k) {
for (var g = CryptoJS, h = g.lib, v = h.WordArray, j = h.Hasher, h = g.algo, s = [], t3 = [], u = function(q) {
return 4294967296 * (q - (q | 0)) | 0;
}, l = 2, b = 0; 64 > b; ) {
var d;
a: {
d = l;
for (var w = k.sqrt(d), r2 = 2; r2 <= w; r2++) if (!(d % r2)) {
d = false;
break a;
}
d = true;
}
d && (8 > b && (s[b] = u(k.pow(l, 0.5))), t3[b] = u(k.pow(l, 1 / 3)), b++);
l++;
}
var n2 = [], h = h.SHA256 = j.extend({ _doReset: function() {
this._hash = new v.init(s.slice(0));
}, _doProcessBlock: function(q, h2) {
for (var a = this._hash.words, c = a[0], d2 = a[1], b2 = a[2], k2 = a[3], f = a[4], g2 = a[5], j2 = a[6], l2 = a[7], e2 = 0; 64 > e2; e2++) {
if (16 > e2) n2[e2] = q[h2 + e2] | 0;
else {
var m = n2[e2 - 15], p = n2[e2 - 2];
n2[e2] = ((m << 25 | m >>> 7) ^ (m << 14 | m >>> 18) ^ m >>> 3) + n2[e2 - 7] + ((p << 15 | p >>> 17) ^ (p << 13 | p >>> 19) ^ p >>> 10) + n2[e2 - 16];
}
m = l2 + ((f << 26 | f >>> 6) ^ (f << 21 | f >>> 11) ^ (f << 7 | f >>> 25)) + (f & g2 ^ ~f & j2) + t3[e2] + n2[e2];
p = ((c << 30 | c >>> 2) ^ (c << 19 | c >>> 13) ^ (c << 10 | c >>> 22)) + (c & d2 ^ c & b2 ^ d2 & b2);
l2 = j2;
j2 = g2;
g2 = f;
f = k2 + m | 0;
k2 = b2;
b2 = d2;
d2 = c;
c = m + p | 0;
}
a[0] = a[0] + c | 0;
a[1] = a[1] + d2 | 0;
a[2] = a[2] + b2 | 0;
a[3] = a[3] + k2 | 0;
a[4] = a[4] + f | 0;
a[5] = a[5] + g2 | 0;
a[6] = a[6] + j2 | 0;
a[7] = a[7] + l2 | 0;
}, _doFinalize: function() {
var d2 = this._data, b2 = d2.words, a = 8 * this._nDataBytes, c = 8 * d2.sigBytes;
b2[c >>> 5] |= 128 << 24 - c % 32;
b2[(c + 64 >>> 9 << 4) + 14] = k.floor(a / 4294967296);
b2[(c + 64 >>> 9 << 4) + 15] = a;
d2.sigBytes = 4 * b2.length;
this._process();
return this._hash;
}, clone: function() {
var b2 = j.clone.call(this);
b2._hash = this._hash.clone();
return b2;
} });
g.SHA256 = j._createHelper(h);
g.HmacSHA256 = j._createHmacHelper(h);
})(Math);
(function() {
var b = CryptoJS, d = b.lib.WordArray, a = b.algo, c = a.SHA256, a = a.SHA224 = c.extend({ _doReset: function() {
this._hash = new d.init([3238371032, 914150663, 812702999, 4144912697, 4290775857, 1750603025, 1694076839, 3204075428]);
}, _doFinalize: function() {
var a2 = c._doFinalize.call(this);
a2.sigBytes -= 4;
return a2;
} });
b.SHA224 = c._createHelper(a);
b.HmacSHA224 = c._createHmacHelper(a);
})();
(function() {
function a() {
return d.create.apply(d, arguments);
}
for (var n2 = CryptoJS, r2 = n2.lib.Hasher, e2 = n2.x64, d = e2.Word, T = e2.WordArray, e2 = n2.algo, ea = [
a(1116352408, 3609767458),
a(1899447441, 602891725),
a(3049323471, 3964484399),
a(3921009573, 2173295548),
a(961987163, 4081628472),
a(1508970993, 3053834265),
a(2453635748, 2937671579),
a(2870763221, 3664609560),
a(3624381080, 2734883394),
a(310598401, 1164996542),
a(607225278, 1323610764),
a(1426881987, 3590304994),
a(1925078388, 4068182383),
a(2162078206, 991336113),
a(2614888103, 633803317),
a(3248222580, 3479774868),
a(3835390401, 2666613458),
a(4022224774, 944711139),
a(264347078, 2341262773),
a(604807628, 2007800933),
a(770255983, 1495990901),
a(1249150122, 1856431235),
a(1555081692, 3175218132),
a(1996064986, 2198950837),
a(2554220882, 3999719339),
a(2821834349, 766784016),
a(2952996808, 2566594879),
a(3210313671, 3203337956),
a(3336571891, 1034457026),
a(3584528711, 2466948901),
a(113926993, 3758326383),
a(338241895, 168717936),
a(666307205, 1188179964),
a(773529912, 1546045734),
a(1294757372, 1522805485),
a(
1396182291,
2643833823
),
a(1695183700, 2343527390),
a(1986661051, 1014477480),
a(2177026350, 1206759142),
a(2456956037, 344077627),
a(2730485921, 1290863460),
a(2820302411, 3158454273),
a(3259730800, 3505952657),
a(3345764771, 106217008),
a(3516065817, 3606008344),
a(3600352804, 1432725776),
a(4094571909, 1467031594),
a(275423344, 851169720),
a(430227734, 3100823752),
a(506948616, 1363258195),
a(659060556, 3750685593),
a(883997877, 3785050280),
a(958139571, 3318307427),
a(1322822218, 3812723403),
a(1537002063, 2003034995),
a(1747873779, 3602036899),
a(1955562222, 1575990012),
a(2024104815, 1125592928),
a(2227730452, 2716904306),
a(2361852424, 442776044),
a(2428436474, 593698344),
a(2756734187, 3733110249),
a(3204031479, 2999351573),
a(3329325298, 3815920427),
a(3391569614, 3928383900),
a(3515267271, 566280711),
a(3940187606, 3454069534),
a(4118630271, 4000239992),
a(116418474, 1914138554),
a(174292421, 2731055270),
a(289380356, 3203993006),
a(460393269, 320620315),
a(685471733, 587496836),
a(852142971, 1086792851),
a(1017036298, 365543100),
a(1126000580, 2618297676),
a(
1288033470,
3409855158
),
a(1501505948, 4234509866),
a(1607167915, 987167468),
a(1816402316, 1246189591)
], v = [], w = 0; 80 > w; w++) v[w] = a();
e2 = e2.SHA512 = r2.extend({ _doReset: function() {
this._hash = new T.init([new d.init(1779033703, 4089235720), new d.init(3144134277, 2227873595), new d.init(1013904242, 4271175723), new d.init(2773480762, 1595750129), new d.init(1359893119, 2917565137), new d.init(2600822924, 725511199), new d.init(528734635, 4215389547), new d.init(1541459225, 327033209)]);
}, _doProcessBlock: function(a2, d2) {
for (var f = this._hash.words, F = f[0], e3 = f[1], n3 = f[2], r3 = f[3], G = f[4], H = f[5], I = f[6], f = f[7], w2 = F.high, J = F.low, X = e3.high, K = e3.low, Y = n3.high, L = n3.low, Z = r3.high, M = r3.low, $ = G.high, N = G.low, aa = H.high, O = H.low, ba = I.high, P = I.low, ca = f.high, Q = f.low, k = w2, g = J, z2 = X, x = K, A = Y, y = L, U = Z, B = M, l = $, h = N, R = aa, C = O, S = ba, D = P, V = ca, E = Q, m = 0; 80 > m; m++) {
var s = v[m];
if (16 > m) var j = s.high = a2[d2 + 2 * m] | 0, b = s.low = a2[d2 + 2 * m + 1] | 0;
else {
var j = v[m - 15], b = j.high, p = j.low, j = (b >>> 1 | p << 31) ^ (b >>> 8 | p << 24) ^ b >>> 7, p = (p >>> 1 | b << 31) ^ (p >>> 8 | b << 24) ^ (p >>> 7 | b << 25), u = v[m - 2], b = u.high, c = u.low, u = (b >>> 19 | c << 13) ^ (b << 3 | c >>> 29) ^ b >>> 6, c = (c >>> 19 | b << 13) ^ (c << 3 | b >>> 29) ^ (c >>> 6 | b << 26), b = v[m - 7], W = b.high, t3 = v[m - 16], q = t3.high, t3 = t3.low, b = p + b.low, j = j + W + (b >>> 0 < p >>> 0 ? 1 : 0), b = b + c, j = j + u + (b >>> 0 < c >>> 0 ? 1 : 0), b = b + t3, j = j + q + (b >>> 0 < t3 >>> 0 ? 1 : 0);
s.high = j;
s.low = b;
}
var W = l & R ^ ~l & S, t3 = h & C ^ ~h & D, s = k & z2 ^ k & A ^ z2 & A, T2 = g & x ^ g & y ^ x & y, p = (k >>> 28 | g << 4) ^ (k << 30 | g >>> 2) ^ (k << 25 | g >>> 7), u = (g >>> 28 | k << 4) ^ (g << 30 | k >>> 2) ^ (g << 25 | k >>> 7), c = ea[m], fa = c.high, da = c.low, c = E + ((h >>> 14 | l << 18) ^ (h >>> 18 | l << 14) ^ (h << 23 | l >>> 9)), q = V + ((l >>> 14 | h << 18) ^ (l >>> 18 | h << 14) ^ (l << 23 | h >>> 9)) + (c >>> 0 < E >>> 0 ? 1 : 0), c = c + t3, q = q + W + (c >>> 0 < t3 >>> 0 ? 1 : 0), c = c + da, q = q + fa + (c >>> 0 < da >>> 0 ? 1 : 0), c = c + b, q = q + j + (c >>> 0 < b >>> 0 ? 1 : 0), b = u + T2, s = p + s + (b >>> 0 < u >>> 0 ? 1 : 0), V = S, E = D, S = R, D = C, R = l, C = h, h = B + c | 0, l = U + q + (h >>> 0 < B >>> 0 ? 1 : 0) | 0, U = A, B = y, A = z2, y = x, z2 = k, x = g, g = c + b | 0, k = q + s + (g >>> 0 < c >>> 0 ? 1 : 0) | 0;
}
J = F.low = J + g;
F.high = w2 + k + (J >>> 0 < g >>> 0 ? 1 : 0);
K = e3.low = K + x;
e3.high = X + z2 + (K >>> 0 < x >>> 0 ? 1 : 0);
L = n3.low = L + y;
n3.high = Y + A + (L >>> 0 < y >>> 0 ? 1 : 0);
M = r3.low = M + B;
r3.high = Z + U + (M >>> 0 < B >>> 0 ? 1 : 0);
N = G.low = N + h;
G.high = $ + l + (N >>> 0 < h >>> 0 ? 1 : 0);
O = H.low = O + C;
H.high = aa + R + (O >>> 0 < C >>> 0 ? 1 : 0);
P = I.low = P + D;
I.high = ba + S + (P >>> 0 < D >>> 0 ? 1 : 0);
Q = f.low = Q + E;
f.high = ca + V + (Q >>> 0 < E >>> 0 ? 1 : 0);
}, _doFinalize: function() {
var a2 = this._data, d2 = a2.words, f = 8 * this._nDataBytes, e3 = 8 * a2.sigBytes;
d2[e3 >>> 5] |= 128 << 24 - e3 % 32;
d2[(e3 + 128 >>> 10 << 5) + 30] = Math.floor(f / 4294967296);
d2[(e3 + 128 >>> 10 << 5) + 31] = f;
a2.sigBytes = 4 * d2.length;
this._process();
return this._hash.toX32();
}, clone: function() {
var a2 = r2.clone.call(this);
a2._hash = this._hash.clone();
return a2;
}, blockSize: 32 });
n2.SHA512 = r2._createHelper(e2);
n2.HmacSHA512 = r2._createHmacHelper(e2);
})();
(function() {
var c = CryptoJS, a = c.x64, b = a.Word, e2 = a.WordArray, a = c.algo, d = a.SHA512, a = a.SHA384 = d.extend({ _doReset: function() {
this._hash = new e2.init([new b.init(3418070365, 3238371032), new b.init(1654270250, 914150663), new b.init(2438529370, 812702999), new b.init(355462360, 4144912697), new b.init(1731405415, 4290775857), new b.init(2394180231, 1750603025), new b.init(3675008525, 1694076839), new b.init(1203062813, 3204075428)]);
}, _doFinalize: function() {
var a2 = d._doFinalize.call(this);
a2.sigBytes -= 16;
return a2;
} });
c.SHA384 = d._createHelper(a);
c.HmacSHA384 = d._createHmacHelper(a);
})();
(function() {
var q = CryptoJS, d = q.lib, n2 = d.WordArray, p = d.Hasher, d = q.algo, x = n2.create([0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 7, 4, 13, 1, 10, 6, 15, 3, 12, 0, 9, 5, 2, 14, 11, 8, 3, 10, 14, 4, 9, 15, 8, 1, 2, 7, 0, 6, 13, 11, 5, 12, 1, 9, 11, 10, 0, 8, 12, 4, 13, 3, 7, 15, 14, 5, 6, 2, 4, 0, 5, 9, 7, 12, 2, 10, 14, 1, 3, 8, 11, 6, 15, 13]), y = n2.create([5, 14, 7, 0, 9, 2, 11, 4, 13, 6, 15, 8, 1, 10, 3, 12, 6, 11, 3, 7, 0, 13, 5, 10, 14, 15, 8, 12, 4, 9, 1, 2, 15, 5, 1, 3, 7, 14, 6, 9, 11, 8, 12, 2, 10, 0, 4, 13, 8, 6, 4, 1, 3, 11, 15, 0, 5, 12, 2, 13, 9, 7, 10, 14, 12, 15, 10, 4, 1, 5, 8, 7, 6, 2, 13, 14, 0, 3, 9, 11]), z2 = n2.create([
11,
14,
15,
12,
5,
8,
7,
9,
11,
13,
14,
15,
6,
7,
9,
8,
7,
6,
8,
13,
11,
9,
7,
15,
7,
12,
15,
9,
11,
7,
13,
12,
11,
13,
6,
7,
14,
9,
13,
15,
14,
8,
13,
6,
5,
12,
7,
5,
11,
12,
14,
15,
14,
15,
9,
8,
9,
14,
5,
6,
8,
6,
5,
12,
9,
15,
5,
11,
6,
8,
13,
12,
5,
12,
13,
14,
11,
8,
5,
6
]), A = n2.create([8, 9, 9, 11, 13, 15, 15, 5, 7, 7, 8, 11, 14, 14, 12, 6, 9, 13, 15, 7, 12, 8, 9, 11, 7, 7, 12, 7, 6, 15, 13, 11, 9, 7, 15, 11, 8, 6, 6, 14, 12, 13, 5, 14, 13, 13, 7, 5, 15, 5, 8, 11, 14, 14, 6, 14, 6, 9, 12, 9, 12, 5, 15, 8, 8, 5, 12, 9, 12, 5, 14, 6, 8, 13, 6, 5, 15, 13, 11, 11]), B = n2.create([0, 1518500249, 1859775393, 2400959708, 2840853838]), C = n2.create([
1352829926,
1548603684,
1836072691,
2053994217,
0
]), d = d.RIPEMD160 = p.extend({ _doReset: function() {
this._hash = n2.create([1732584193, 4023233417, 2562383102, 271733878, 3285377520]);
}, _doProcessBlock: function(e2, v) {
for (var b = 0; 16 > b; b++) {
var c = v + b, f = e2[c];
e2[c] = (f << 8 | f >>> 24) & 16711935 | (f << 24 | f >>> 8) & 4278255360;
}
var c = this._hash.words, f = B.words, d2 = C.words, n3 = x.words, q2 = y.words, p2 = z2.words, w = A.words, t3, g, h, j, r2, u, k, l, m, s;
u = t3 = c[0];
k = g = c[1];
l = h = c[2];
m = j = c[3];
s = r2 = c[4];
for (var a, b = 0; 80 > b; b += 1) a = t3 + e2[v + n3[b]] | 0, a = 16 > b ? a + ((g ^ h ^ j) + f[0]) : 32 > b ? a + ((g & h | ~g & j) + f[1]) : 48 > b ? a + (((g | ~h) ^ j) + f[2]) : 64 > b ? a + ((g & j | h & ~j) + f[3]) : a + ((g ^ (h | ~j)) + f[4]), a |= 0, a = a << p2[b] | a >>> 32 - p2[b], a = a + r2 | 0, t3 = r2, r2 = j, j = h << 10 | h >>> 22, h = g, g = a, a = u + e2[v + q2[b]] | 0, a = 16 > b ? a + ((k ^ (l | ~m)) + d2[0]) : 32 > b ? a + ((k & m | l & ~m) + d2[1]) : 48 > b ? a + (((k | ~l) ^ m) + d2[2]) : 64 > b ? a + ((k & l | ~k & m) + d2[3]) : a + ((k ^ l ^ m) + d2[4]), a |= 0, a = a << w[b] | a >>> 32 - w[b], a = a + s | 0, u = s, s = m, m = l << 10 | l >>> 22, l = k, k = a;
a = c[1] + h + m | 0;
c[1] = c[2] + j + s | 0;
c[2] = c[3] + r2 + u | 0;
c[3] = c[4] + t3 + k | 0;
c[4] = c[0] + g + l | 0;
c[0] = a;
}, _doFinalize: function() {
var e2 = this._data, d2 = e2.words, b = 8 * this._nDataBytes, c = 8 * e2.sigBytes;
d2[c >>> 5] |= 128 << 24 - c % 32;
d2[(c + 64 >>> 9 << 4) + 14] = (b << 8 | b >>> 24) & 16711935 | (b << 24 | b >>> 8) & 4278255360;
e2.sigBytes = 4 * (d2.length + 1);
this._process();
e2 = this._hash;
d2 = e2.words;
for (b = 0; 5 > b; b++) c = d2[b], d2[b] = (c << 8 | c >>> 24) & 16711935 | (c << 24 | c >>> 8) & 4278255360;
return e2;
}, clone: function() {
var d2 = p.clone.call(this);
d2._hash = this._hash.clone();
return d2;
} });
q.RIPEMD160 = p._createHelper(d);
q.HmacRIPEMD160 = p._createHmacHelper(d);
})(Math);
(function() {
var c = CryptoJS, k = c.enc.Utf8;
c.algo.HMAC = c.lib.Base.extend({ init: function(a, b) {
a = this._hasher = new a.init();
"string" == typeof b && (b = k.parse(b));
var c2 = a.blockSize, e2 = 4 * c2;
b.sigBytes > e2 && (b = a.finalize(b));
b.clamp();
for (var f = this._oKey = b.clone(), g = this._iKey = b.clone(), h = f.words, j = g.words, d = 0; d < c2; d++) h[d] ^= 1549556828, j[d] ^= 909522486;
f.sigBytes = g.sigBytes = e2;
this.reset();
}, reset: function() {
var a = this._hasher;
a.reset();
a.update(this._iKey);
}, update: function(a) {
this._hasher.update(a);
return this;
}, finalize: function(a) {
var b = this._hasher;
a = b.finalize(a);
b.reset();
return b.finalize(this._oKey.clone().concat(a));
} });
})();
(function() {
var b = CryptoJS, a = b.lib, d = a.Base, m = a.WordArray, a = b.algo, q = a.HMAC, l = a.PBKDF2 = d.extend({ cfg: d.extend({ keySize: 4, hasher: a.SHA1, iterations: 1 }), init: function(a2) {
this.cfg = this.cfg.extend(a2);
}, compute: function(a2, b2) {
for (var c = this.cfg, f = q.create(c.hasher, a2), g = m.create(), d2 = m.create([1]), l2 = g.words, r2 = d2.words, n2 = c.keySize, c = c.iterations; l2.length < n2; ) {
var h = f.update(b2).finalize(d2);
f.reset();
for (var j = h.words, s = j.length, k = h, p = 1; p < c; p++) {
k = f.finalize(k);
f.reset();
for (var t3 = k.words, e2 = 0; e2 < s; e2++) j[e2] ^= t3[e2];
}
g.concat(h);
r2[0]++;
}
g.sigBytes = 4 * n2;
return g;
} });
b.PBKDF2 = function(a2, b2, c) {
return l.create(c).compute(a2, b2);
};
})();
var b64map = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
var b64pad = "=";
function hex2b64(d) {
var b;
var e2;
var a = "";
for (b = 0; b + 3 <= d.length; b += 3) {
e2 = parseInt(d.substring(b, b + 3), 16);
a += b64map.charAt(e2 >> 6) + b64map.charAt(e2 & 63);
}
if (b + 1 == d.length) {
e2 = parseInt(d.substring(b, b + 1), 16);
a += b64map.charAt(e2 << 2);
} else {
if (b + 2 == d.length) {
e2 = parseInt(d.substring(b, b + 2), 16);
a += b64map.charAt(e2 >> 2) + b64map.charAt((e2 & 3) << 4);
}
}
if (b64pad) {
while ((a.length & 3) > 0) {
a += b64pad;
}
}
return a;
}
function b64tohex(f) {
var d = "";
var e2;
var b = 0;
var c;
var a;
for (e2 = 0; e2 < f.length; ++e2) {
if (f.charAt(e2) == b64pad) {
break;
}
a = b64map.indexOf(f.charAt(e2));
if (a < 0) {
continue;
}
if (b == 0) {
d += int2char(a >> 2);
c = a & 3;
b = 1;
} else {
if (b == 1) {
d += int2char(c << 2 | a >> 4);
c = a & 15;
b = 2;
} else {
if (b == 2) {
d += int2char(c);
d += int2char(a >> 2);
c = a & 3;
b = 3;
} else {
d += int2char(c << 2 | a >> 4);
d += int2char(a & 15);
b = 0;
}
}
}
}
if (b == 1) {
d += int2char(c << 2);
}
return d;
}
function b64toBA(e2) {
var d = b64tohex(e2);
var c;
var b = new Array();
for (c = 0; 2 * c < d.length; ++c) {
b[c] = parseInt(d.substring(2 * c, 2 * c + 2), 16);
}
return b;
}
var dbits;
var canary = 244837814094590;
var j_lm = (canary & 16777215) == 15715070;
function BigInteger(e2, d, f) {
if (e2 != null) {
if ("number" == typeof e2) {
this.fromNumber(e2, d, f);
} else {
if (d == null && "string" != typeof e2) {
this.fromString(e2, 256);
} else {
this.fromString(e2, d);
}
}
}
}
function nbi() {
return new BigInteger(null);
}
function am1(f, a, b, e2, h, g) {
while (--g >= 0) {
var d = a * this[f++] + b[e2] + h;
h = Math.floor(d / 67108864);
b[e2++] = d & 67108863;
}
return h;
}
function am2(f, q, r2, e2, o2, a) {
var k = q & 32767, p = q >> 15;
while (--a >= 0) {
var d = this[f] & 32767;
var g = this[f++] >> 15;
var b = p * d + g * k;
d = k * d + ((b & 32767) << 15) + r2[e2] + (o2 & 1073741823);
o2 = (d >>> 30) + (b >>> 15) + p * g + (o2 >>> 30);
r2[e2++] = d & 1073741823;
}
return o2;
}
function am3(f, q, r2, e2, o2, a) {
var k = q & 16383, p = q >> 14;
while (--a >= 0) {
var d = this[f] & 16383;
var g = this[f++] >> 14;
var b = p * d + g * k;
d = k * d + ((b & 16383) << 14) + r2[e2] + o2;
o2 = (d >> 28) + (b >> 14) + p * g;
r2[e2++] = d & 268435455;
}
return o2;
}
if (j_lm && navigator2.appName == "Microsoft Internet Explorer") {
BigInteger.prototype.am = am2;
dbits = 30;
} else {
if (j_lm && navigator2.appName != "Netscape") {
BigInteger.prototype.am = am1;
dbits = 26;
} else {
BigInteger.prototype.am = am3;
dbits = 28;
}
}
BigInteger.prototype.DB = dbits;
BigInteger.prototype.DM = (1 << dbits) - 1;
BigInteger.prototype.DV = 1 << dbits;
var BI_FP = 52;
BigInteger.prototype.FV = Math.pow(2, BI_FP);
BigInteger.prototype.F1 = BI_FP - dbits;
BigInteger.prototype.F2 = 2 * dbits - BI_FP;
var BI_RM = "0123456789abcdefghijklmnopqrstuvwxyz";
var BI_RC = new Array();
var rr;
var vv;
rr = "0".charCodeAt(0);
for (vv = 0; vv <= 9; ++vv) {
BI_RC[rr++] = vv;
}
rr = "a".charCodeAt(0);
for (vv = 10; vv < 36; ++vv) {
BI_RC[rr++] = vv;
}
rr = "A".charCodeAt(0);
for (vv = 10; vv < 36; ++vv) {
BI_RC[rr++] = vv;
}
function int2char(a) {
return BI_RM.charAt(a);
}
function intAt(b, a) {
var d = BI_RC[b.charCodeAt(a)];
return d == null ? -1 : d;
}
function bnpCopyTo(b) {
for (var a = this.t - 1; a >= 0; --a) {
b[a] = this[a];
}
b.t = this.t;
b.s = this.s;
}
function bnpFromInt(a) {
this.t = 1;
this.s = a < 0 ? -1 : 0;
if (a > 0) {
this[0] = a;
} else {
if (a < -1) {
this[0] = a + this.DV;
} else {
this.t = 0;
}
}
}
function nbv(a) {
var b = nbi();
b.fromInt(a);
return b;
}
function bnpFromString(h, c) {
var e2;
if (c == 16) {
e2 = 4;
} else {
if (c == 8) {
e2 = 3;
} else {
if (c == 256) {
e2 = 8;
} else {
if (c == 2) {
e2 = 1;
} else {
if (c == 32) {
e2 = 5;
} else {
if (c == 4) {
e2 = 2;
} else {
this.fromRadix(h, c);
return;
}
}
}
}
}
}
this.t = 0;
this.s = 0;
var g = h.length, d = false, f = 0;
while (--g >= 0) {
var a = e2 == 8 ? h[g] & 255 : intAt(h, g);
if (a < 0) {
if (h.charAt(g) == "-") {
d = true;
}
continue;
}
d = false;
if (f == 0) {
this[this.t++] = a;
} else {
if (f + e2 > this.DB) {
this[this.t - 1] |= (a & (1 << this.DB - f) - 1) << f;
this[this.t++] = a >> this.DB - f;
} else {
this[this.t - 1] |= a << f;
}
}
f += e2;
if (f >= this.DB) {
f -= this.DB;
}
}
if (e2 == 8 && (h[0] & 128) != 0) {
this.s = -1;
if (f > 0) {
this[this.t - 1] |= (1 << this.DB - f) - 1 << f;
}
}
this.clamp();
if (d) {
BigInteger.ZERO.subTo(this, this);
}
}
function bnpClamp() {
var a = this.s & this.DM;
while (this.t > 0 && this[this.t - 1] == a) {
--this.t;
}
}
function bnToString(c) {
if (this.s < 0) {
return "-" + this.negate().toString(c);
}
var e2;
if (c == 16) {
e2 = 4;
} else {
if (c == 8) {
e2 = 3;
} else {
if (c == 2) {
e2 = 1;
} else {
if (c == 32) {
e2 = 5;
} else {
if (c == 4) {
e2 = 2;
} else {
return this.toRadix(c);
}
}
}
}
}
var g = (1 << e2) - 1, l, a = false, h = "", f = this.t;
var j = this.DB - f * this.DB % e2;
if (f-- > 0) {
if (j < this.DB && (l = this[f] >> j) > 0) {
a = true;
h = int2char(l);
}
while (f >= 0) {
if (j < e2) {
l = (this[f] & (1 << j) - 1) << e2 - j;
l |= this[--f] >> (j += this.DB - e2);
} else {
l = this[f] >> (j -= e2) & g;
if (j <= 0) {
j += this.DB;
--f;
}
}
if (l > 0) {
a = true;
}
if (a) {
h += int2char(l);
}
}
}
return a ? h : "0";
}
function bnNegate() {
var a = nbi();
BigInteger.ZERO.subTo(this, a);
return a;
}
function bnAbs() {
return this.s < 0 ? this.negate() : this;
}
function bnCompareTo(b) {
var d = this.s - b.s;
if (d != 0) {
return d;
}
var c = this.t;
d = c - b.t;
if (d != 0) {
return this.s < 0 ? -d : d;
}
while (--c >= 0) {
if ((d = this[c] - b[c]) != 0) {
return d;
}
}
return 0;
}
function nbits(a) {
var c = 1, b;
if ((b = a >>> 16) != 0) {
a = b;
c += 16;
}
if ((b = a >> 8) != 0) {
a = b;
c += 8;
}
if ((b = a >> 4) != 0) {
a = b;
c += 4;
}
if ((b = a >> 2) != 0) {
a = b;
c += 2;
}
if ((b = a >> 1) != 0) {
a = b;
c += 1;
}
return c;
}
function bnBitLength() {
if (this.t <= 0) {
return 0;
}
return this.DB * (this.t - 1) + nbits(this[this.t - 1] ^ this.s & this.DM);
}
function bnpDLShiftTo(c, b) {
var a;
for (a = this.t - 1; a >= 0; --a) {
b[a + c] = this[a];
}
for (a = c - 1; a >= 0; --a) {
b[a] = 0;
}
b.t = this.t + c;
b.s = this.s;
}
function bnpDRShiftTo(c, b) {
for (var a = c; a < this.t; ++a) {
b[a - c] = this[a];
}
b.t = Math.max(this.t - c, 0);
b.s = this.s;
}
function bnpLShiftTo(j, e2) {
var b = j % this.DB;
var a = this.DB - b;
var g = (1 << a) - 1;
var f = Math.floor(j / this.DB), h = this.s << b & this.DM, d;
for (d = this.t - 1; d >= 0; --d) {
e2[d + f + 1] = this[d] >> a | h;
h = (this[d] & g) << b;
}
for (d = f - 1; d >= 0; --d) {
e2[d] = 0;
}
e2[f] = h;
e2.t = this.t + f + 1;
e2.s = this.s;
e2.clamp();
}
function bnpRShiftTo(g, d) {
d.s = this.s;
var e2 = Math.floor(g / this.DB);
if (e2 >= this.t) {
d.t = 0;
return;
}
var b = g % this.DB;
var a = this.DB - b;
var f = (1 << b) - 1;
d[0] = this[e2] >> b;
for (var c = e2 + 1; c < this.t; ++c) {
d[c - e2 - 1] |= (this[c] & f) << a;
d[c - e2] = this[c] >> b;
}
if (b > 0) {
d[this.t - e2 - 1] |= (this.s & f) << a;
}
d.t = this.t - e2;
d.clamp();
}
function bnpSubTo(d, f) {
var e2 = 0, g = 0, b = Math.min(d.t, this.t);
while (e2 < b) {
g += this[e2] - d[e2];
f[e2++] = g & this.DM;
g >>= this.DB;
}
if (d.t < this.t) {
g -= d.s;
while (e2 < this.t) {
g += this[e2];
f[e2++] = g & this.DM;
g >>= this.DB;
}
g += this.s;
} else {
g += this.s;
while (e2 < d.t) {
g -= d[e2];
f[e2++] = g & this.DM;
g >>= this.DB;
}
g -= d.s;
}
f.s = g < 0 ? -1 : 0;
if (g < -1) {
f[e2++] = this.DV + g;
} else {
if (g > 0) {
f[e2++] = g;
}
}
f.t = e2;
f.clamp();
}
function bnpMultiplyTo(c, e2) {
var b = this.abs(), f = c.abs();
var d = b.t;
e2.t = d + f.t;
while (--d >= 0) {
e2[d] = 0;
}
for (d = 0; d < f.t; ++d) {
e2[d + b.t] = b.am(0, f[d], e2, d, 0, b.t);
}
e2.s = 0;
e2.clamp();
if (this.s != c.s) {
BigInteger.ZERO.subTo(e2, e2);
}
}
function bnpSquareTo(d) {
var a = this.abs();
var b = d.t = 2 * a.t;
while (--b >= 0) {
d[b] = 0;
}
for (b = 0; b < a.t - 1; ++b) {
var e2 = a.am(b, a[b], d, 2 * b, 0, 1);
if ((d[b + a.t] += a.am(b + 1, 2 * a[b], d, 2 * b + 1, e2, a.t - b - 1)) >= a.DV) {
d[b + a.t] -= a.DV;
d[b + a.t + 1] = 1;
}
}
if (d.t > 0) {
d[d.t - 1] += a.am(b, a[b], d, 2 * b, 0, 1);
}
d.s = 0;
d.clamp();
}
function bnpDivRemTo(n2, h, g) {
var w = n2.abs();
if (w.t <= 0) {
return;
}
var k = this.abs();
if (k.t < w.t) {
if (h != null) {
h.fromInt(0);
}
if (g != null) {
this.copyTo(g);
}
return;
}
if (g == null) {
g = nbi();
}
var d = nbi(), a = this.s, l = n2.s;
var v = this.DB - nbits(w[w.t - 1]);
if (v > 0) {
w.lShiftTo(v, d);
k.lShiftTo(v, g);
} else {
w.copyTo(d);
k.copyTo(g);
}
var p = d.t;
var b = d[p - 1];
if (b == 0) {
return;
}
var o2 = b * (1 << this.F1) + (p > 1 ? d[p - 2] >> this.F2 : 0);
var A = this.FV / o2, z2 = (1 << this.F1) / o2, x = 1 << this.F2;
var u = g.t, s = u - p, f = h == null ? nbi() : h;
d.dlShiftTo(s, f);
if (g.compareTo(f) >= 0) {
g[g.t++] = 1;
g.subTo(f, g);
}
BigInteger.ONE.dlShiftTo(p, f);
f.subTo(d, d);
while (d.t < p) {
d[d.t++] = 0;
}
while (--s >= 0) {
var c = g[--u] == b ? this.DM : Math.floor(g[u] * A + (g[u - 1] + x) * z2);
if ((g[u] += d.am(0, c, g, s, 0, p)) < c) {
d.dlShiftTo(s, f);
g.subTo(f, g);
while (g[u] < --c) {
g.subTo(f, g);
}
}
}
if (h != null) {
g.drShiftTo(p, h);
if (a != l) {
BigInteger.ZERO.subTo(h, h);
}
}
g.t = p;
g.clamp();
if (v > 0) {
g.rShiftTo(v, g);
}
if (a < 0) {
BigInteger.ZERO.subTo(g, g);
}
}
function bnMod(b) {
var c = nbi();
this.abs().divRemTo(b, null, c);
if (this.s < 0 && c.compareTo(BigInteger.ZERO) > 0) {
b.subTo(c, c);
}
return c;
}
function Classic(a) {
this.m = a;
}
function cConvert(a) {
if (a.s < 0 || a.compareTo(this.m) >= 0) {
return a.mod(this.m);
} else {
return a;
}
}
function cRevert(a) {
return a;
}
function cReduce(a) {
a.divRemTo(this.m, null, a);
}
function cMulTo(a, c, b) {
a.multiplyTo(c, b);
this.reduce(b);
}
function cSqrTo(a, b) {
a.squareTo(b);
this.reduce(b);
}
Classic.prototype.convert = cConvert;
Classic.prototype.revert = cRevert;
Classic.prototype.reduce = cReduce;
Classic.prototype.mulTo = cMulTo;
Classic.prototype.sqrTo = cSqrTo;
function bnpInvDigit() {
if (this.t < 1) {
return 0;
}
var a = this[0];
if ((a & 1) == 0) {
return 0;
}
var b = a & 3;
b = b * (2 - (a & 15) * b) & 15;
b = b * (2 - (a & 255) * b) & 255;
b = b * (2 - ((a & 65535) * b & 65535)) & 65535;
b = b * (2 - a * b % this.DV) % this.DV;
return b > 0 ? this.DV - b : -b;
}
function Montgomery(a) {
this.m = a;
this.mp = a.invDigit();
this.mpl = this.mp & 32767;
this.mph = this.mp >> 15;
this.um = (1 << a.DB - 15) - 1;
this.mt2 = 2 * a.t;
}
function montConvert(a) {
var b = nbi();
a.abs().dlShiftTo(this.m.t, b);
b.divRemTo(this.m, null, b);
if (a.s < 0 && b.compareTo(BigInteger.ZERO) > 0) {
this.m.subTo(b, b);
}
return b;
}
function montRevert(a) {
var b = nbi();
a.copyTo(b);
this.reduce(b);
return b;
}
function montReduce(a) {
while (a.t <= this.mt2) {
a[a.t++] = 0;
}
for (var c = 0; c < this.m.t; ++c) {
var b = a[c] & 32767;
var d = b * this.mpl + ((b * this.mph + (a[c] >> 15) * this.mpl & this.um) << 15) & a.DM;
b = c + this.m.t;
a[b] += this.m.am(0, d, a, c, 0, this.m.t);
while (a[b] >= a.DV) {
a[b] -= a.DV;
a[++b]++;
}
}
a.clamp();
a.drShiftTo(this.m.t, a);
if (a.compareTo(this.m) >= 0) {
a.subTo(this.m, a);
}
}
function montSqrTo(a, b) {
a.squareTo(b);
this.reduce(b);
}
function montMulTo(a, c, b) {
a.multiplyTo(c, b);
this.reduce(b);
}
Montgomery.prototype.convert = montConvert;
Montgomery.prototype.revert = montRevert;
Montgomery.prototype.reduce = montReduce;
Montgomery.prototype.mulTo = montMulTo;
Montgomery.prototype.sqrTo = montSqrTo;
function bnpIsEven() {
return (this.t > 0 ? this[0] & 1 : this.s) == 0;
}
function bnpExp(h, j) {
if (h > 4294967295 || h < 1) {
return BigInteger.ONE;
}
var f = nbi(), a = nbi(), d = j.convert(this), c = nbits(h) - 1;
d.copyTo(f);
while (--c >= 0) {
j.sqrTo(f, a);
if ((h & 1 << c) > 0) {
j.mulTo(a, d, f);
} else {
var b = f;
f = a;
a = b;
}
}
return j.revert(f);
}
function bnModPowInt(b, a) {
var c;
if (b < 256 || a.isEven()) {
c = new Classic(a);
} else {
c = new Montgomery(a);
}
return this.exp(b, c);
}
BigInteger.prototype.copyTo = bnpCopyTo;
BigInteger.prototype.fromInt = bnpFromInt;
BigInteger.prototype.fromString = bnpFromString;
BigInteger.prototype.clamp = bnpClamp;
BigInteger.prototype.dlShiftTo = bnpDLShiftTo;
BigInteger.prototype.drShiftTo = bnpDRShiftTo;
BigInteger.prototype.lShiftTo = bnpLShiftTo;
BigInteger.prototype.rShiftTo = bnpRShiftTo;
BigInteger.prototype.subTo = bnpSubTo;
BigInteger.prototype.multiplyTo = bnpMultiplyTo;
BigInteger.prototype.squareTo = bnpSquareTo;
BigInteger.prototype.divRemTo = bnpDivRemTo;
BigInteger.prototype.invDigit = bnpInvDigit;
BigInteger.prototype.isEven = bnpIsEven;
BigInteger.prototype.exp = bnpExp;
BigInteger.prototype.toString = bnToString;
BigInteger.prototype.negate = bnNegate;
BigInteger.prototype.abs = bnAbs;
BigInteger.prototype.compareTo = bnCompareTo;
BigInteger.prototype.bitLength = bnBitLength;
BigInteger.prototype.mod = bnMod;
BigInteger.prototype.modPowInt = bnModPowInt;
BigInteger.ZERO = nbv(0);
BigInteger.ONE = nbv(1);
function bnClone() {
var a = nbi();
this.copyTo(a);
return a;
}
function bnIntValue() {
if (this.s < 0) {
if (this.t == 1) {
return this[0] - this.DV;
} else {
if (this.t == 0) {
return -1;
}
}
} else {
if (this.t == 1) {
return this[0];
} else {
if (this.t == 0) {
return 0;
}
}
}
return (this[1] & (1 << 32 - this.DB) - 1) << this.DB | this[0];
}
function bnByteValue() {
return this.t == 0 ? this.s : this[0] << 24 >> 24;
}
function bnShortValue() {
return this.t == 0 ? this.s : this[0] << 16 >> 16;
}
function bnpChunkSize(a) {
return Math.floor(Math.LN2 * this.DB / Math.log(a));
}
function bnSigNum() {
if (this.s < 0) {
return -1;
} else {
if (this.t <= 0 || this.t == 1 && this[0] <= 0) {
return 0;
} else {
return 1;
}
}
}
function bnpToRadix(c) {
if (c == null) {
c = 10;
}
if (this.signum() == 0 || c < 2 || c > 36) {
return "0";
}
var f = this.chunkSize(c);
var e2 = Math.pow(c, f);
var i = nbv(e2), j = nbi(), h = nbi(), g = "";
this.divRemTo(i, j, h);
while (j.signum() > 0) {
g = (e2 + h.intValue()).toString(c).substr(1) + g;
j.divRemTo(i, j, h);
}
return h.intValue().toString(c) + g;
}
function bnpFromRadix(m, h) {
this.fromInt(0);
if (h == null) {
h = 10;
}
var f = this.chunkSize(h);
var g = Math.pow(h, f), e2 = false, a = 0, l = 0;
for (var c = 0; c < m.length; ++c) {
var k = intAt(m, c);
if (k < 0) {
if (m.charAt(c) == "-" && this.signum() == 0) {
e2 = true;
}
continue;
}
l = h * l + k;
if (++a >= f) {
this.dMultiply(g);
this.dAddOffset(l, 0);
a = 0;
l = 0;
}
}
if (a > 0) {
this.dMultiply(Math.pow(h, a));
this.dAddOffset(l, 0);
}
if (e2) {
BigInteger.ZERO.subTo(this, this);
}
}
function bnpFromNumber(f, e2, h) {
if ("number" == typeof e2) {
if (f < 2) {
this.fromInt(1);
} else {
this.fromNumber(f, h);
if (!this.testBit(f - 1)) {
this.bitwiseTo(BigInteger.ONE.shiftLeft(f - 1), op_or, this);
}
if (this.isEven()) {
this.dAddOffset(1, 0);
}
while (!this.isProbablePrime(e2)) {
this.dAddOffset(2, 0);
if (this.bitLength() > f) {
this.subTo(BigInteger.ONE.shiftLeft(f - 1), this);
}
}
}
} else {
var d = new Array(), g = f & 7;
d.length = (f >> 3) + 1;
e2.nextBytes(d);
if (g > 0) {
d[0] &= (1 << g) - 1;
} else {
d[0] = 0;
}
this.fromString(d, 256);
}
}
function bnToByteArray() {
var b = this.t, c = new Array();
c[0] = this.s;
var e2 = this.DB - b * this.DB % 8, f, a = 0;
if (b-- > 0) {
if (e2 < this.DB && (f = this[b] >> e2) != (this.s & this.DM) >> e2) {
c[a++] = f | this.s << this.DB - e2;
}
while (b >= 0) {
if (e2 < 8) {
f = (this[b] & (1 << e2) - 1) << 8 - e2;
f |= this[--b] >> (e2 += this.DB - 8);
} else {
f = this[b] >> (e2 -= 8) & 255;
if (e2 <= 0) {
e2 += this.DB;
--b;
}
}
if ((f & 128) != 0) {
f |= -256;
}
if (a == 0 && (this.s & 128) != (f & 128)) {
++a;
}
if (a > 0 || f != this.s) {
c[a++] = f;
}
}
}
return c;
}
function bnEquals(b) {
return this.compareTo(b) == 0;
}
function bnMin(b) {
return this.compareTo(b) < 0 ? this : b;
}
function bnMax(b) {
return this.compareTo(b) > 0 ? this : b;
}
function bnpBitwiseTo(c, h, e2) {
var d, g, b = Math.min(c.t, this.t);
for (d = 0; d < b; ++d) {
e2[d] = h(this[d], c[d]);
}
if (c.t < this.t) {
g = c.s & this.DM;
for (d = b; d < this.t; ++d) {
e2[d] = h(this[d], g);
}
e2.t = this.t;
} else {
g = this.s & this.DM;
for (d = b; d < c.t; ++d) {
e2[d] = h(g, c[d]);
}
e2.t = c.t;
}
e2.s = h(this.s, c.s);
e2.clamp();
}
function op_and(a, b) {
return a & b;
}
function bnAnd(b) {
var c = nbi();
this.bitwiseTo(b, op_and, c);
return c;
}
function op_or(a, b) {
return a | b;
}
function bnOr(b) {
var c = nbi();
this.bitwiseTo(b, op_or, c);
return c;
}
function op_xor(a, b) {
return a ^ b;
}
function bnXor(b) {
var c = nbi();
this.bitwiseTo(b, op_xor, c);
return c;
}
function op_andnot(a, b) {
return a & ~b;
}
function bnAndNot(b) {
var c = nbi();
this.bitwiseTo(b, op_andnot, c);
return c;
}
function bnNot() {
var b = nbi();
for (var a = 0; a < this.t; ++a) {
b[a] = this.DM & ~this[a];
}
b.t = this.t;
b.s = ~this.s;
return b;
}
function bnShiftLeft(b) {
var a = nbi();
if (b < 0) {
this.rShiftTo(-b, a);
} else {
this.lShiftTo(b, a);
}
return a;
}
function bnShiftRight(b) {
var a = nbi();
if (b < 0) {
this.lShiftTo(-b, a);
} else {
this.rShiftTo(b, a);
}
return a;
}
function lbit(a) {
if (a == 0) {
return -1;
}
var b = 0;
if ((a & 65535) == 0) {
a >>= 16;
b += 16;
}
if ((a & 255) == 0) {
a >>= 8;
b += 8;
}
if ((a & 15) == 0) {
a >>= 4;
b += 4;
}
if ((a & 3) == 0) {
a >>= 2;
b += 2;
}
if ((a & 1) == 0) {
++b;
}
return b;
}
function bnGetLowestSetBit() {
for (var a = 0; a < this.t; ++a) {
if (this[a] != 0) {
return a * this.DB + lbit(this[a]);
}
}
if (this.s < 0) {
return this.t * this.DB;
}
return -1;
}
function cbit(a) {
var b = 0;
while (a != 0) {
a &= a - 1;
++b;
}
return b;
}
function bnBitCount() {
var c = 0, a = this.s & this.DM;
for (var b = 0; b < this.t; ++b) {
c += cbit(this[b] ^ a);
}
return c;
}
function bnTestBit(b) {
var a = Math.floor(b / this.DB);
if (a >= this.t) {
return this.s != 0;
}
return (this[a] & 1 << b % this.DB) != 0;
}
function bnpChangeBit(c, b) {
var a = BigInteger.ONE.shiftLeft(c);
this.bitwiseTo(a, b, a);
return a;
}
function bnSetBit(a) {
return this.changeBit(a, op_or);
}
function bnClearBit(a) {
return this.changeBit(a, op_andnot);
}
function bnFlipBit(a) {
return this.changeBit(a, op_xor);
}
function bnpAddTo(d, f) {
var e2 = 0, g = 0, b = Math.min(d.t, this.t);
while (e2 < b) {
g += this[e2] + d[e2];
f[e2++] = g & this.DM;
g >>= this.DB;
}
if (d.t < this.t) {
g += d.s;
while (e2 < this.t) {
g += this[e2];
f[e2++] = g & this.DM;
g >>= this.DB;
}
g += this.s;
} else {
g += this.s;
while (e2 < d.t) {
g += d[e2];
f[e2++] = g & this.DM;
g >>= this.DB;
}
g += d.s;
}
f.s = g < 0 ? -1 : 0;
if (g > 0) {
f[e2++] = g;
} else {
if (g < -1) {
f[e2++] = this.DV + g;
}
}
f.t = e2;
f.clamp();
}
function bnAdd(b) {
var c = nbi();
this.addTo(b, c);
return c;
}
function bnSubtract(b) {
var c = nbi();
this.subTo(b, c);
return c;
}
function bnMultiply(b) {
var c = nbi();
this.multiplyTo(b, c);
return c;
}
function bnSquare() {
var a = nbi();
this.squareTo(a);
return a;
}
function bnDivide(b) {
var c = nbi();
this.divRemTo(b, c, null);
return c;
}
function bnRemainder(b) {
var c = nbi();
this.divRemTo(b, null, c);
return c;
}
function bnDivideAndRemainder(b) {
var d = nbi(), c = nbi();
this.divRemTo(b, d, c);
return new Array(d, c);
}
function bnpDMultiply(a) {
this[this.t] = this.am(0, a - 1, this, 0, 0, this.t);
++this.t;
this.clamp();
}
function bnpDAddOffset(b, a) {
if (b == 0) {
return;
}
while (this.t <= a) {
this[this.t++] = 0;
}
this[a] += b;
while (this[a] >= this.DV) {
this[a] -= this.DV;
if (++a >= this.t) {
this[this.t++] = 0;
}
++this[a];
}
}
function NullExp() {
}
function nNop(a) {
return a;
}
function nMulTo(a, c, b) {
a.multiplyTo(c, b);
}
function nSqrTo(a, b) {
a.squareTo(b);
}
NullExp.prototype.convert = nNop;
NullExp.prototype.revert = nNop;
NullExp.prototype.mulTo = nMulTo;
NullExp.prototype.sqrTo = nSqrTo;
function bnPow(a) {
return this.exp(a, new NullExp());
}
function bnpMultiplyLowerTo(b, f, e2) {
var d = Math.min(this.t + b.t, f);
e2.s = 0;
e2.t = d;
while (d > 0) {
e2[--d] = 0;
}
var c;
for (c = e2.t - this.t; d < c; ++d) {
e2[d + this.t] = this.am(0, b[d], e2, d, 0, this.t);
}
for (c = Math.min(b.t, f); d < c; ++d) {
this.am(0, b[d], e2, d, 0, f - d);
}
e2.clamp();
}
function bnpMultiplyUpperTo(b, e2, d) {
--e2;
var c = d.t = this.t + b.t - e2;
d.s = 0;
while (--c >= 0) {
d[c] = 0;
}
for (c = Math.max(e2 - this.t, 0); c < b.t; ++c) {
d[this.t + c - e2] = this.am(e2 - c, b[c], d, 0, 0, this.t + c - e2);
}
d.clamp();
d.drShiftTo(1, d);
}
function Barrett(a) {
this.r2 = nbi();
this.q3 = nbi();
BigInteger.ONE.dlShiftTo(2 * a.t, this.r2);
this.mu = this.r2.divide(a);
this.m = a;
}
function barrettConvert(a) {
if (a.s < 0 || a.t > 2 * this.m.t) {
return a.mod(this.m);
} else {
if (a.compareTo(this.m) < 0) {
return a;
} else {
var b = nbi();
a.copyTo(b);
this.reduce(b);
return b;
}
}
}
function barrettRevert(a) {
return a;
}
function barrettReduce(a) {
a.drShiftTo(this.m.t - 1, this.r2);
if (a.t > this.m.t + 1) {
a.t = this.m.t + 1;
a.clamp();
}
this.mu.multiplyUpperTo(this.r2, this.m.t + 1, this.q3);
this.m.multiplyLowerTo(this.q3, this.m.t + 1, this.r2);
while (a.compareTo(this.r2) < 0) {
a.dAddOffset(1, this.m.t + 1);
}
a.subTo(this.r2, a);
while (a.compareTo(this.m) >= 0) {
a.subTo(this.m, a);
}
}
function barrettSqrTo(a, b) {
a.squareTo(b);
this.reduce(b);
}
function barrettMulTo(a, c, b) {
a.multiplyTo(c, b);
this.reduce(b);
}
Barrett.prototype.convert = barrettConvert;
Barrett.prototype.revert = barrettRevert;
Barrett.prototype.reduce = barrettReduce;
Barrett.prototype.mulTo = barrettMulTo;
Barrett.prototype.sqrTo = barrettSqrTo;
function bnModPow(q, f) {
var o2 = q.bitLength(), h, b = nbv(1), v;
if (o2 <= 0) {
return b;
} else {
if (o2 < 18) {
h = 1;
} else {
if (o2 < 48) {
h = 3;
} else {
if (o2 < 144) {
h = 4;
} else {
if (o2 < 768) {
h = 5;
} else {
h = 6;
}
}
}
}
}
if (o2 < 8) {
v = new Classic(f);
} else {
if (f.isEven()) {
v = new Barrett(f);
} else {
v = new Montgomery(f);
}
}
var p = new Array(), d = 3, s = h - 1, a = (1 << h) - 1;
p[1] = v.convert(this);
if (h > 1) {
var A = nbi();
v.sqrTo(p[1], A);
while (d <= a) {
p[d] = nbi();
v.mulTo(A, p[d - 2], p[d]);
d += 2;
}
}
var l = q.t - 1, x, u = true, c = nbi(), y;
o2 = nbits(q[l]) - 1;
while (l >= 0) {
if (o2 >= s) {
x = q[l] >> o2 - s & a;
} else {
x = (q[l] & (1 << o2 + 1) - 1) << s - o2;
if (l > 0) {
x |= q[l - 1] >> this.DB + o2 - s;
}
}
d = h;
while ((x & 1) == 0) {
x >>= 1;
--d;
}
if ((o2 -= d) < 0) {
o2 += this.DB;
--l;
}
if (u) {
p[x].copyTo(b);
u = false;
} else {
while (d > 1) {
v.sqrTo(b, c);
v.sqrTo(c, b);
d -= 2;
}
if (d > 0) {
v.sqrTo(b, c);
} else {
y = b;
b = c;
c = y;
}
v.mulTo(c, p[x], b);
}
while (l >= 0 && (q[l] & 1 << o2) == 0) {
v.sqrTo(b, c);
y = b;
b = c;
c = y;
if (--o2 < 0) {
o2 = this.DB - 1;
--l;
}
}
}
return v.revert(b);
}
function bnGCD(c) {
var b = this.s < 0 ? this.negate() : this.clone();
var h = c.s < 0 ? c.negate() : c.clone();
if (b.compareTo(h) < 0) {
var e2 = b;
b = h;
h = e2;
}
var d = b.getLowestSetBit(), f = h.getLowestSetBit();
if (f < 0) {
return b;
}
if (d < f) {
f = d;
}
if (f > 0) {
b.rShiftTo(f, b);
h.rShiftTo(f, h);
}
while (b.signum() > 0) {
if ((d = b.getLowestSetBit()) > 0) {
b.rShiftTo(d, b);
}
if ((d = h.getLowestSetBit()) > 0) {
h.rShiftTo(d, h);
}
if (b.compareTo(h) >= 0) {
b.subTo(h, b);
b.rShiftTo(1, b);
} else {
h.subTo(b, h);
h.rShiftTo(1, h);
}
}
if (f > 0) {
h.lShiftTo(f, h);
}
return h;
}
function bnpModInt(e2) {
if (e2 <= 0) {
return 0;
}
var c = this.DV % e2, b = this.s < 0 ? e2 - 1 : 0;
if (this.t > 0) {
if (c == 0) {
b = this[0] % e2;
} else {
for (var a = this.t - 1; a >= 0; --a) {
b = (c * b + this[a]) % e2;
}
}
}
return b;
}
function bnModInverse(f) {
var j = f.isEven();
if (this.isEven() && j || f.signum() == 0) {
return BigInteger.ZERO;
}
var i = f.clone(), h = this.clone();
var g = nbv(1), e2 = nbv(0), l = nbv(0), k = nbv(1);
while (i.signum() != 0) {
while (i.isEven()) {
i.rShiftTo(1, i);
if (j) {
if (!g.isEven() || !e2.isEven()) {
g.addTo(this, g);
e2.subTo(f, e2);
}
g.rShiftTo(1, g);
} else {
if (!e2.isEven()) {
e2.subTo(f, e2);
}
}
e2.rShiftTo(1, e2);
}
while (h.isEven()) {
h.rShiftTo(1, h);
if (j) {
if (!l.isEven() || !k.isEven()) {
l.addTo(this, l);
k.subTo(f, k);
}
l.rShiftTo(1, l);
} else {
if (!k.isEven()) {
k.subTo(f, k);
}
}
k.rShiftTo(1, k);
}
if (i.compareTo(h) >= 0) {
i.subTo(h, i);
if (j) {
g.subTo(l, g);
}
e2.subTo(k, e2);
} else {
h.subTo(i, h);
if (j) {
l.subTo(g, l);
}
k.subTo(e2, k);
}
}
if (h.compareTo(BigInteger.ONE) != 0) {
return BigInteger.ZERO;
}
if (k.compareTo(f) >= 0) {
return k.subtract(f);
}
if (k.signum() < 0) {
k.addTo(f, k);
} else {
return k;
}
if (k.signum() < 0) {
return k.add(f);
} else {
return k;
}
}
var lowprimes = [2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37, 41, 43, 47, 53, 59, 61, 67, 71, 73, 79, 83, 89, 97, 101, 103, 107, 109, 113, 127, 131, 137, 139, 149, 151, 157, 163, 167, 173, 179, 181, 191, 193, 197, 199, 211, 223, 227, 229, 233, 239, 241, 251, 257, 263, 269, 271, 277, 281, 283, 293, 307, 311, 313, 317, 331, 337, 347, 349, 353, 359, 367, 373, 379, 383, 389, 397, 401, 409, 419, 421, 431, 433, 439, 443, 449, 457, 461, 463, 467, 479, 487, 491, 499, 503, 509, 521, 523, 541, 547, 557, 563, 569, 571, 577, 587, 593, 599, 601, 607, 613, 617, 619, 631, 641, 643, 647, 653, 659, 661, 673, 677, 683, 691, 701, 709, 719, 727, 733, 739, 743, 751, 757, 761, 769, 773, 787, 797, 809, 811, 821, 823, 827, 829, 839, 853, 857, 859, 863, 877, 881, 883, 887, 907, 911, 919, 929, 937, 941, 947, 953, 967, 971, 977, 983, 991, 997];
var lplim = (1 << 26) / lowprimes[lowprimes.length - 1];
function bnIsProbablePrime(e2) {
var d, b = this.abs();
if (b.t == 1 && b[0] <= lowprimes[lowprimes.length - 1]) {
for (d = 0; d < lowprimes.length; ++d) {
if (b[0] == lowprimes[d]) {
return true;
}
}
return false;
}
if (b.isEven()) {
return false;
}
d = 1;
while (d < lowprimes.length) {
var a = lowprimes[d], c = d + 1;
while (c < lowprimes.length && a < lplim) {
a *= lowprimes[c++];
}
a = b.modInt(a);
while (d < c) {
if (a % lowprimes[d++] == 0) {
return false;
}
}
}
return b.millerRabin(e2);
}
function bnpMillerRabin(f) {
var g = this.subtract(BigInteger.ONE);
var c = g.getLowestSetBit();
if (c <= 0) {
return false;
}
var h = g.shiftRight(c);
f = f + 1 >> 1;
if (f > lowprimes.length) {
f = lowprimes.length;
}
var b = nbi();
for (var e2 = 0; e2 < f; ++e2) {
b.fromInt(lowprimes[Math.floor(Math.random() * lowprimes.length)]);
var l = b.modPow(h, this);
if (l.compareTo(BigInteger.ONE) != 0 && l.compareTo(g) != 0) {
var d = 1;
while (d++ < c && l.compareTo(g) != 0) {
l = l.modPowInt(2, this);
if (l.compareTo(BigInteger.ONE) == 0) {
return false;
}
}
if (l.compareTo(g) != 0) {
return false;
}
}
}
return true;
}
BigInteger.prototype.chunkSize = bnpChunkSize;
BigInteger.prototype.toRadix = bnpToRadix;
BigInteger.prototype.fromRadix = bnpFromRadix;
BigInteger.prototype.fromNumber = bnpFromNumber;
BigInteger.prototype.bitwiseTo = bnpBitwiseTo;
BigInteger.prototype.changeBit = bnpChangeBit;
BigInteger.prototype.addTo = bnpAddTo;
BigInteger.prototype.dMultiply = bnpDMultiply;
BigInteger.prototype.dAddOffset = bnpDAddOffset;
BigInteger.prototype.multiplyLowerTo = bnpMultiplyLowerTo;
BigInteger.prototype.multiplyUpperTo = bnpMultiplyUpperTo;
BigInteger.prototype.modInt = bnpModInt;
BigInteger.prototype.millerRabin = bnpMillerRabin;
BigInteger.prototype.clone = bnClone;
BigInteger.prototype.intValue = bnIntValue;
BigInteger.prototype.byteValue = bnByteValue;
BigInteger.prototype.shortValue = bnShortValue;
BigInteger.prototype.signum = bnSigNum;
BigInteger.prototype.toByteArray = bnToByteArray;
BigInteger.prototype.equals = bnEquals;
BigInteger.prototype.min = bnMin;
BigInteger.prototype.max = bnMax;
BigInteger.prototype.and = bnAnd;
BigInteger.prototype.or = bnOr;
BigInteger.prototype.xor = bnXor;
BigInteger.prototype.andNot = bnAndNot;
BigInteger.prototype.not = bnNot;
BigInteger.prototype.shiftLeft = bnShiftLeft;
BigInteger.prototype.shiftRight = bnShiftRight;
BigInteger.prototype.getLowestSetBit = bnGetLowestSetBit;
BigInteger.prototype.bitCount = bnBitCount;
BigInteger.prototype.testBit = bnTestBit;
BigInteger.prototype.setBit = bnSetBit;
BigInteger.prototype.clearBit = bnClearBit;
BigInteger.prototype.flipBit = bnFlipBit;
BigInteger.prototype.add = bnAdd;
BigInteger.prototype.subtract = bnSubtract;
BigInteger.prototype.multiply = bnMultiply;
BigInteger.prototype.divide = bnDivide;
BigInteger.prototype.remainder = bnRemainder;
BigInteger.prototype.divideAndRemainder = bnDivideAndRemainder;
BigInteger.prototype.modPow = bnModPow;
BigInteger.prototype.modInverse = bnModInverse;
BigInteger.prototype.pow = bnPow;
BigInteger.prototype.gcd = bnGCD;
BigInteger.prototype.isProbablePrime = bnIsProbablePrime;
BigInteger.prototype.square = bnSquare;
function Arcfour() {
this.i = 0;
this.j = 0;
this.S = new Array();
}
function ARC4init(d) {
var c, a, b;
for (c = 0; c < 256; ++c) {
this.S[c] = c;
}
a = 0;
for (c = 0; c < 256; ++c) {
a = a + this.S[c] + d[c % d.length] & 255;
b = this.S[c];
this.S[c] = this.S[a];
this.S[a] = b;
}
this.i = 0;
this.j = 0;
}
function ARC4next() {
var a;
this.i = this.i + 1 & 255;
this.j = this.j + this.S[this.i] & 255;
a = this.S[this.i];
this.S[this.i] = this.S[this.j];
this.S[this.j] = a;
return this.S[a + this.S[this.i] & 255];
}
Arcfour.prototype.init = ARC4init;
Arcfour.prototype.next = ARC4next;
function prng_newstate() {
return new Arcfour();
}
var rng_psize = 256;
var rng_state;
var rng_pool;
var rng_pptr;
function rng_seed_int(a) {
rng_pool[rng_pptr++] ^= a & 255;
rng_pool[rng_pptr++] ^= a >> 8 & 255;
rng_pool[rng_pptr++] ^= a >> 16 & 255;
rng_pool[rng_pptr++] ^= a >> 24 & 255;
if (rng_pptr >= rng_psize) {
rng_pptr -= rng_psize;
}
}
function rng_seed_time() {
rng_seed_int((/* @__PURE__ */ new Date()).getTime());
}
if (rng_pool == null) {
rng_pool = new Array();
rng_pptr = 0;
if (window2 !== void 0 && (window2.crypto !== void 0 || window2.msCrypto !== void 0)) {
crypto2 = window2.crypto || window2.msCrypto;
if (crypto2.getRandomValues) {
ua = new Uint8Array(32);
crypto2.getRandomValues(ua);
for (t2 = 0; t2 < 32; ++t2) {
rng_pool[rng_pptr++] = ua[t2];
}
} else {
if (navigator2.appName == "Netscape" && navigator2.appVersion < "5") {
z = window2.crypto.random(32);
for (t2 = 0; t2 < z.length; ++t2) {
rng_pool[rng_pptr++] = z.charCodeAt(t2) & 255;
}
}
}
}
while (rng_pptr < rng_psize) {
t2 = Math.floor(65536 * Math.random());
rng_pool[rng_pptr++] = t2 >>> 8;
rng_pool[rng_pptr++] = t2 & 255;
}
rng_pptr = 0;
rng_seed_time();
}
var t2;
var crypto2;
var ua;
var z;
function rng_get_byte() {
if (rng_state == null) {
rng_seed_time();
rng_state = prng_newstate();
rng_state.init(rng_pool);
for (rng_pptr = 0; rng_pptr < rng_pool.length; ++rng_pptr) {
rng_pool[rng_pptr] = 0;
}
rng_pptr = 0;
}
return rng_state.next();
}
function rng_get_bytes(b) {
var a;
for (a = 0; a < b.length; ++a) {
b[a] = rng_get_byte();
}
}
function SecureRandom() {
}
SecureRandom.prototype.nextBytes = rng_get_bytes;
function parseBigInt(b, a) {
return new BigInteger(b, a);
}
function RSAKey() {
this.n = null;
this.e = 0;
this.d = null;
this.p = null;
this.q = null;
this.dmp1 = null;
this.dmq1 = null;
this.coeff = null;
}
function RSASetPublic(b, a) {
this.isPublic = true;
this.isPrivate = false;
if (typeof b !== "string") {
this.n = b;
this.e = a;
} else {
if (b != null && a != null && b.length > 0 && a.length > 0) {
this.n = parseBigInt(b, 16);
this.e = parseInt(a, 16);
} else {
throw "Invalid RSA public key";
}
}
}
function RSADoPublic(a) {
return a.modPowInt(this.e, this.n);
}
RSAKey.prototype.doPublic = RSADoPublic;
RSAKey.prototype.setPublic = RSASetPublic;
RSAKey.prototype.type = "RSA";
function RSASetPrivate(c, a, b) {
this.isPrivate = true;
if (typeof c !== "string") {
this.n = c;
this.e = a;
this.d = b;
} else {
if (c != null && a != null && c.length > 0 && a.length > 0) {
this.n = parseBigInt(c, 16);
this.e = parseInt(a, 16);
this.d = parseBigInt(b, 16);
} else {
throw "Invalid RSA private key";
}
}
}
function RSASetPrivateEx(g, d, e2, c, b, a, h, f) {
this.isPrivate = true;
this.isPublic = false;
if (g == null) {
throw "RSASetPrivateEx N == null";
}
if (d == null) {
throw "RSASetPrivateEx E == null";
}
if (g.length == 0) {
throw "RSASetPrivateEx N.length == 0";
}
if (d.length == 0) {
throw "RSASetPrivateEx E.length == 0";
}
if (g != null && d != null && g.length > 0 && d.length > 0) {
this.n = parseBigInt(g, 16);
this.e = parseInt(d, 16);
this.d = parseBigInt(e2, 16);
this.p = parseBigInt(c, 16);
this.q = parseBigInt(b, 16);
this.dmp1 = parseBigInt(a, 16);
this.dmq1 = parseBigInt(h, 16);
this.coeff = parseBigInt(f, 16);
} else {
throw "Invalid RSA private key in RSASetPrivateEx";
}
}
function RSAGenerate(b, l) {
var a = new SecureRandom();
var g = b >> 1;
this.e = parseInt(l, 16);
var c = new BigInteger(l, 16);
var d = b / 2 - 100;
var k = BigInteger.ONE.shiftLeft(d);
for (; ; ) {
for (; ; ) {
this.p = new BigInteger(b - g, 1, a);
if (this.p.subtract(BigInteger.ONE).gcd(c).compareTo(BigInteger.ONE) == 0 && this.p.isProbablePrime(10)) {
break;
}
}
for (; ; ) {
this.q = new BigInteger(g, 1, a);
if (this.q.subtract(BigInteger.ONE).gcd(c).compareTo(BigInteger.ONE) == 0 && this.q.isProbablePrime(10)) {
break;
}
}
if (this.p.compareTo(this.q) <= 0) {
var j = this.p;
this.p = this.q;
this.q = j;
}
var h = this.q.subtract(this.p).abs();
if (h.bitLength() < d || h.compareTo(k) <= 0) {
continue;
}
var i = this.p.subtract(BigInteger.ONE);
var e2 = this.q.subtract(BigInteger.ONE);
var f = i.multiply(e2);
if (f.gcd(c).compareTo(BigInteger.ONE) == 0) {
this.n = this.p.multiply(this.q);
if (this.n.bitLength() == b) {
this.d = c.modInverse(f);
this.dmp1 = this.d.mod(i);
this.dmq1 = this.d.mod(e2);
this.coeff = this.q.modInverse(this.p);
break;
}
}
}
this.isPrivate = true;
}
function RSADoPrivate(a) {
if (this.p == null || this.q == null) {
return a.modPow(this.d, this.n);
}
var c = a.mod(this.p).modPow(this.dmp1, this.p);
var b = a.mod(this.q).modPow(this.dmq1, this.q);
while (c.compareTo(b) < 0) {
c = c.add(this.p);
}
return c.subtract(b).multiply(this.coeff).mod(this.p).multiply(this.q).add(b);
}
RSAKey.prototype.doPrivate = RSADoPrivate;
RSAKey.prototype.setPrivate = RSASetPrivate;
RSAKey.prototype.setPrivateEx = RSASetPrivateEx;
RSAKey.prototype.generate = RSAGenerate;
function ECFieldElementFp(b, a) {
this.x = a;
this.q = b;
}
function feFpEquals(a) {
if (a == this) {
return true;
}
return this.q.equals(a.q) && this.x.equals(a.x);
}
function feFpToBigInteger() {
return this.x;
}
function feFpNegate() {
return new ECFieldElementFp(this.q, this.x.negate().mod(this.q));
}
function feFpAdd(a) {
return new ECFieldElementFp(this.q, this.x.add(a.toBigInteger()).mod(this.q));
}
function feFpSubtract(a) {
return new ECFieldElementFp(this.q, this.x.subtract(a.toBigInteger()).mod(this.q));
}
function feFpMultiply(a) {
return new ECFieldElementFp(this.q, this.x.multiply(a.toBigInteger()).mod(this.q));
}
function feFpSquare() {
return new ECFieldElementFp(this.q, this.x.square().mod(this.q));
}
function feFpDivide(a) {
return new ECFieldElementFp(this.q, this.x.multiply(a.toBigInteger().modInverse(this.q)).mod(this.q));
}
ECFieldElementFp.prototype.equals = feFpEquals;
ECFieldElementFp.prototype.toBigInteger = feFpToBigInteger;
ECFieldElementFp.prototype.negate = feFpNegate;
ECFieldElementFp.prototype.add = feFpAdd;
ECFieldElementFp.prototype.subtract = feFpSubtract;
ECFieldElementFp.prototype.multiply = feFpMultiply;
ECFieldElementFp.prototype.square = feFpSquare;
ECFieldElementFp.prototype.divide = feFpDivide;
ECFieldElementFp.prototype.sqrt = function() {
return new ECFieldElementFp(this.q, this.x.sqrt().mod(this.q));
};
function ECPointFp(c, a, d, b) {
this.curve = c;
this.x = a;
this.y = d;
if (b == null) {
this.z = BigInteger.ONE;
} else {
this.z = b;
}
this.zinv = null;
}
function pointFpGetX() {
if (this.zinv == null) {
this.zinv = this.z.modInverse(this.curve.q);
}
return this.curve.fromBigInteger(this.x.toBigInteger().multiply(this.zinv).mod(this.curve.q));
}
function pointFpGetY() {
if (this.zinv == null) {
this.zinv = this.z.modInverse(this.curve.q);
}
return this.curve.fromBigInteger(this.y.toBigInteger().multiply(this.zinv).mod(this.curve.q));
}
function pointFpEquals(a) {
if (a == this) {
return true;
}
if (this.isInfinity()) {
return a.isInfinity();
}
if (a.isInfinity()) {
return this.isInfinity();
}
var c, b;
c = a.y.toBigInteger().multiply(this.z).subtract(this.y.toBigInteger().multiply(a.z)).mod(this.curve.q);
if (!c.equals(BigInteger.ZERO)) {
return false;
}
b = a.x.toBigInteger().multiply(this.z).subtract(this.x.toBigInteger().multiply(a.z)).mod(this.curve.q);
return b.equals(BigInteger.ZERO);
}
function pointFpIsInfinity() {
if (this.x == null && this.y == null) {
return true;
}
return this.z.equals(BigInteger.ZERO) && !this.y.toBigInteger().equals(BigInteger.ZERO);
}
function pointFpNegate() {
return new ECPointFp(this.curve, this.x, this.y.negate(), this.z);
}
function pointFpAdd(l) {
if (this.isInfinity()) {
return l;
}
if (l.isInfinity()) {
return this;
}
var p = l.y.toBigInteger().multiply(this.z).subtract(this.y.toBigInteger().multiply(l.z)).mod(this.curve.q);
var o2 = l.x.toBigInteger().multiply(this.z).subtract(this.x.toBigInteger().multiply(l.z)).mod(this.curve.q);
if (BigInteger.ZERO.equals(o2)) {
if (BigInteger.ZERO.equals(p)) {
return this.twice();
}
return this.curve.getInfinity();
}
var j = new BigInteger("3");
var e2 = this.x.toBigInteger();
var n2 = this.y.toBigInteger();
var c = l.x.toBigInteger();
var k = l.y.toBigInteger();
var m = o2.square();
var i = m.multiply(o2);
var d = e2.multiply(m);
var g = p.square().multiply(this.z);
var a = g.subtract(d.shiftLeft(1)).multiply(l.z).subtract(i).multiply(o2).mod(this.curve.q);
var h = d.multiply(j).multiply(p).subtract(n2.multiply(i)).subtract(g.multiply(p)).multiply(l.z).add(p.multiply(i)).mod(this.curve.q);
var f = i.multiply(this.z).multiply(l.z).mod(this.curve.q);
return new ECPointFp(this.curve, this.curve.fromBigInteger(a), this.curve.fromBigInteger(h), f);
}
function pointFpTwice() {
if (this.isInfinity()) {
return this;
}
if (this.y.toBigInteger().signum() == 0) {
return this.curve.getInfinity();
}
var g = new BigInteger("3");
var c = this.x.toBigInteger();
var h = this.y.toBigInteger();
var e2 = h.multiply(this.z);
var j = e2.multiply(h).mod(this.curve.q);
var i = this.curve.a.toBigInteger();
var k = c.square().multiply(g);
if (!BigInteger.ZERO.equals(i)) {
k = k.add(this.z.square().multiply(i));
}
k = k.mod(this.curve.q);
var b = k.square().subtract(c.shiftLeft(3).multiply(j)).shiftLeft(1).multiply(e2).mod(this.curve.q);
var f = k.multiply(g).multiply(c).subtract(j.shiftLeft(1)).shiftLeft(2).multiply(j).subtract(k.square().multiply(k)).mod(this.curve.q);
var d = e2.square().multiply(e2).shiftLeft(3).mod(this.curve.q);
return new ECPointFp(this.curve, this.curve.fromBigInteger(b), this.curve.fromBigInteger(f), d);
}
function pointFpMultiply(d) {
if (this.isInfinity()) {
return this;
}
if (d.signum() == 0) {
return this.curve.getInfinity();
}
var m = d;
var l = m.multiply(new BigInteger("3"));
var b = this.negate();
var j = this;
var q = this.curve.q.subtract(d);
var o2 = q.multiply(new BigInteger("3"));
var c = new ECPointFp(this.curve, this.x, this.y);
var a = c.negate();
var g;
for (g = l.bitLength() - 2; g > 0; --g) {
j = j.twice();
var n2 = l.testBit(g);
var f = m.testBit(g);
if (n2 != f) {
j = j.add(n2 ? this : b);
}
}
for (g = o2.bitLength() - 2; g > 0; --g) {
c = c.twice();
var p = o2.testBit(g);
var r2 = q.testBit(g);
if (p != r2) {
c = c.add(p ? c : a);
}
}
return j;
}
function pointFpMultiplyTwo(c, a, b) {
var d;
if (c.bitLength() > b.bitLength()) {
d = c.bitLength() - 1;
} else {
d = b.bitLength() - 1;
}
var f = this.curve.getInfinity();
var e2 = this.add(a);
while (d >= 0) {
f = f.twice();
if (c.testBit(d)) {
if (b.testBit(d)) {
f = f.add(e2);
} else {
f = f.add(this);
}
} else {
if (b.testBit(d)) {
f = f.add(a);
}
}
--d;
}
return f;
}
ECPointFp.prototype.getX = pointFpGetX;
ECPointFp.prototype.getY = pointFpGetY;
ECPointFp.prototype.equals = pointFpEquals;
ECPointFp.prototype.isInfinity = pointFpIsInfinity;
ECPointFp.prototype.negate = pointFpNegate;
ECPointFp.prototype.add = pointFpAdd;
ECPointFp.prototype.twice = pointFpTwice;
ECPointFp.prototype.multiply = pointFpMultiply;
ECPointFp.prototype.multiplyTwo = pointFpMultiplyTwo;
function ECCurveFp(e2, d, c) {
this.q = e2;
this.a = this.fromBigInteger(d);
this.b = this.fromBigInteger(c);
this.infinity = new ECPointFp(this, null, null);
}
function curveFpGetQ() {
return this.q;
}
function curveFpGetA() {
return this.a;
}
function curveFpGetB() {
return this.b;
}
function curveFpEquals(a) {
if (a == this) {
return true;
}
return this.q.equals(a.q) && this.a.equals(a.a) && this.b.equals(a.b);
}
function curveFpGetInfinity() {
return this.infinity;
}
function curveFpFromBigInteger(a) {
return new ECFieldElementFp(this.q, a);
}
function curveFpDecodePointHex(m) {
switch (parseInt(m.substr(0, 2), 16)) {
case 0:
return this.infinity;
case 2:
case 3:
var c = m.substr(0, 2);
var l = m.substr(2);
var j = this.fromBigInteger(new BigInteger(k, 16));
var i = this.getA();
var h = this.getB();
var e2 = j.square().add(i).multiply(j).add(h);
var g = e2.sqrt();
if (c == "03") {
g = g.negate();
}
return new ECPointFp(this, j, g);
case 4:
case 6:
case 7:
var d = (m.length - 2) / 2;
var k = m.substr(2, d);
var f = m.substr(d + 2, d);
return new ECPointFp(this, this.fromBigInteger(new BigInteger(k, 16)), this.fromBigInteger(new BigInteger(f, 16)));
default:
return null;
}
}
ECCurveFp.prototype.getQ = curveFpGetQ;
ECCurveFp.prototype.getA = curveFpGetA;
ECCurveFp.prototype.getB = curveFpGetB;
ECCurveFp.prototype.equals = curveFpEquals;
ECCurveFp.prototype.getInfinity = curveFpGetInfinity;
ECCurveFp.prototype.fromBigInteger = curveFpFromBigInteger;
ECCurveFp.prototype.decodePointHex = curveFpDecodePointHex;
ECFieldElementFp.prototype.getByteLength = function() {
return Math.floor((this.toBigInteger().bitLength() + 7) / 8);
};
ECPointFp.prototype.getEncoded = function(c) {
var d = function(h, f) {
var g = h.toByteArrayUnsigned();
if (f < g.length) {
g = g.slice(g.length - f);
} else {
while (f > g.length) {
g.unshift(0);
}
}
return g;
};
var a = this.getX().toBigInteger();
var e2 = this.getY().toBigInteger();
var b = d(a, 32);
if (c) {
if (e2.isEven()) {
b.unshift(2);
} else {
b.unshift(3);
}
} else {
b.unshift(4);
b = b.concat(d(e2, 32));
}
return b;
};
ECPointFp.decodeFrom = function(g, c) {
var f = c[0];
var e2 = c.length - 1;
var d = c.slice(1, 1 + e2 / 2);
var b = c.slice(1 + e2 / 2, 1 + e2);
d.unshift(0);
b.unshift(0);
var a = new BigInteger(d);
var h = new BigInteger(b);
return new ECPointFp(g, g.fromBigInteger(a), g.fromBigInteger(h));
};
ECPointFp.decodeFromHex = function(g, c) {
var f = c.substr(0, 2);
var e2 = c.length - 2;
var d = c.substr(2, e2 / 2);
var b = c.substr(2 + e2 / 2, e2 / 2);
var a = new BigInteger(d, 16);
var h = new BigInteger(b, 16);
return new ECPointFp(g, g.fromBigInteger(a), g.fromBigInteger(h));
};
ECPointFp.prototype.add2D = function(c) {
if (this.isInfinity()) {
return c;
}
if (c.isInfinity()) {
return this;
}
if (this.x.equals(c.x)) {
if (this.y.equals(c.y)) {
return this.twice();
}
return this.curve.getInfinity();
}
var g = c.x.subtract(this.x);
var e2 = c.y.subtract(this.y);
var a = e2.divide(g);
var d = a.square().subtract(this.x).subtract(c.x);
var f = a.multiply(this.x.subtract(d)).subtract(this.y);
return new ECPointFp(this.curve, d, f);
};
ECPointFp.prototype.twice2D = function() {
if (this.isInfinity()) {
return this;
}
if (this.y.toBigInteger().signum() == 0) {
return this.curve.getInfinity();
}
var b = this.curve.fromBigInteger(BigInteger.valueOf(2));
var e2 = this.curve.fromBigInteger(BigInteger.valueOf(3));
var a = this.x.square().multiply(e2).add(this.curve.a).divide(this.y.multiply(b));
var c = a.square().subtract(this.x.multiply(b));
var d = a.multiply(this.x.subtract(c)).subtract(this.y);
return new ECPointFp(this.curve, c, d);
};
ECPointFp.prototype.multiply2D = function(b) {
if (this.isInfinity()) {
return this;
}
if (b.signum() == 0) {
return this.curve.getInfinity();
}
var g = b;
var f = g.multiply(new BigInteger("3"));
var l = this.negate();
var d = this;
var c;
for (c = f.bitLength() - 2; c > 0; --c) {
d = d.twice();
var a = f.testBit(c);
var j = g.testBit(c);
if (a != j) {
d = d.add2D(a ? this : l);
}
}
return d;
};
ECPointFp.prototype.isOnCurve = function() {
var d = this.getX().toBigInteger();
var i = this.getY().toBigInteger();
var f = this.curve.getA().toBigInteger();
var c = this.curve.getB().toBigInteger();
var h = this.curve.getQ();
var e2 = i.multiply(i).mod(h);
var g = d.multiply(d).multiply(d).add(f.multiply(d)).add(c).mod(h);
return e2.equals(g);
};
ECPointFp.prototype.toString = function() {
return "(" + this.getX().toBigInteger().toString() + "," + this.getY().toBigInteger().toString() + ")";
};
ECPointFp.prototype.validate = function() {
var c = this.curve.getQ();
if (this.isInfinity()) {
throw new Error("Point is at infinity.");
}
var a = this.getX().toBigInteger();
var b = this.getY().toBigInteger();
if (a.compareTo(BigInteger.ONE) < 0 || a.compareTo(c.subtract(BigInteger.ONE)) > 0) {
throw new Error("x coordinate out of bounds");
}
if (b.compareTo(BigInteger.ONE) < 0 || b.compareTo(c.subtract(BigInteger.ONE)) > 0) {
throw new Error("y coordinate out of bounds");
}
if (!this.isOnCurve()) {
throw new Error("Point is not on the curve.");
}
if (this.multiply(c).isInfinity()) {
throw new Error("Point is not a scalar multiple of G.");
}
return true;
};
var jsonParse = (function() {
var e2 = "(?:-?\\b(?:0|[1-9][0-9]*)(?:\\.[0-9]+)?(?:[eE][+-]?[0-9]+)?\\b)";
var j = '(?:[^\\0-\\x08\\x0a-\\x1f"\\\\]|\\\\(?:["/\\\\bfnrt]|u[0-9A-Fa-f]{4}))';
var i = '(?:"' + j + '*")';
var d = new RegExp("(?:false|true|null|[\\{\\}\\[\\]]|" + e2 + "|" + i + ")", "g");
var k = new RegExp("\\\\(?:([^u])|u(.{4}))", "g");
var g = { '"': '"', "/": "/", "\\": "\\", b: "\b", f: "\f", n: "\n", r: "\r", t: " " };
function h(l, m, n2) {
return m ? g[m] : String.fromCharCode(parseInt(n2, 16));
}
var c = new String("");
var a = "\\";
var f = { "{": Object, "[": Array };
var b = Object.hasOwnProperty;
return function(u, q) {
var p = u.match(d);
var x;
var v = p[0];
var l = false;
if ("{" === v) {
x = {};
} else {
if ("[" === v) {
x = [];
} else {
x = [];
l = true;
}
}
var t3;
var r2 = [x];
for (var o2 = 1 - l, m = p.length; o2 < m; ++o2) {
v = p[o2];
var w;
switch (v.charCodeAt(0)) {
default:
w = r2[0];
w[t3 || w.length] = +v;
t3 = void 0;
break;
case 34:
v = v.substring(1, v.length - 1);
if (v.indexOf(a) !== -1) {
v = v.replace(k, h);
}
w = r2[0];
if (!t3) {
if (w instanceof Array) {
t3 = w.length;
} else {
t3 = v || c;
break;
}
}
w[t3] = v;
t3 = void 0;
break;
case 91:
w = r2[0];
r2.unshift(w[t3 || w.length] = []);
t3 = void 0;
break;
case 93:
r2.shift();
break;
case 102:
w = r2[0];
w[t3 || w.length] = false;
t3 = void 0;
break;
case 110:
w = r2[0];
w[t3 || w.length] = null;
t3 = void 0;
break;
case 116:
w = r2[0];
w[t3 || w.length] = true;
t3 = void 0;
break;
case 123:
w = r2[0];
r2.unshift(w[t3 || w.length] = {});
t3 = void 0;
break;
case 125:
r2.shift();
break;
}
}
if (l) {
if (r2.length !== 1) {
throw new Error();
}
x = x[0];
} else {
if (r2.length) {
throw new Error();
}
}
if (q) {
var s = function(C, B) {
var D = C[B];
if (D && typeof D === "object") {
var n2 = null;
for (var z2 in D) {
if (b.call(D, z2) && D !== C) {
var y = s(D, z2);
if (y !== void 0) {
D[z2] = y;
} else {
if (!n2) {
n2 = [];
}
n2.push(z2);
}
}
}
if (n2) {
for (var A = n2.length; --A >= 0; ) {
delete D[n2[A]];
}
}
}
return q.call(C, B, D);
};
x = s({ "": x }, "");
}
return x;
};
})();
if (typeof KJUR == "undefined" || !KJUR) {
KJUR = {};
}
if (typeof KJUR.asn1 == "undefined" || !KJUR.asn1) {
KJUR.asn1 = {};
}
KJUR.asn1.ASN1Util = new function() {
this.integerToByteHex = function(a) {
var b = a.toString(16);
if (b.length % 2 == 1) {
b = "0" + b;
}
return b;
};
this.bigIntToMinTwosComplementsHex = function(a) {
return twoscompl(a);
};
this.getPEMStringFromHex = function(a, b) {
return hextopem(a, b);
};
this.newObject = function(k) {
var F = KJUR, o2 = F.asn1, v = o2.ASN1Object, B = o2.DERBoolean, e2 = o2.DERInteger, t3 = o2.DERBitString, h = o2.DEROctetString, x = o2.DERNull, y = o2.DERObjectIdentifier, m = o2.DEREnumerated, g = o2.DERUTF8String, f = o2.DERNumericString, A = o2.DERPrintableString, w = o2.DERTeletexString, q = o2.DERIA5String, E = o2.DERUTCTime, j = o2.DERGeneralizedTime, b = o2.DERVisibleString, l = o2.DERBMPString, n2 = o2.DERSequence, c = o2.DERSet, s = o2.DERTaggedObject, p = o2.ASN1Util.newObject;
if (k instanceof o2.ASN1Object) {
return k;
}
var u = Object.keys(k);
if (u.length != 1) {
throw new Error("key of param shall be only one.");
}
var H = u[0];
if (":asn1:bool:int:bitstr:octstr:null:oid:enum:utf8str:numstr:prnstr:telstr:ia5str:utctime:gentime:visstr:bmpstr:seq:set:tag:".indexOf(":" + H + ":") == -1) {
throw new Error("undefined key: " + H);
}
if (H == "bool") {
return new B(k[H]);
}
if (H == "int") {
return new e2(k[H]);
}
if (H == "bitstr") {
return new t3(k[H]);
}
if (H == "octstr") {
return new h(k[H]);
}
if (H == "null") {
return new x(k[H]);
}
if (H == "oid") {
return new y(k[H]);
}
if (H == "enum") {
return new m(k[H]);
}
if (H == "utf8str") {
return new g(k[H]);
}
if (H == "numstr") {
return new f(k[H]);
}
if (H == "prnstr") {
return new A(k[H]);
}
if (H == "telstr") {
return new w(k[H]);
}
if (H == "ia5str") {
return new q(k[H]);
}
if (H == "utctime") {
return new E(k[H]);
}
if (H == "gentime") {
return new j(k[H]);
}
if (H == "visstr") {
return new b(k[H]);
}
if (H == "bmpstr") {
return new l(k[H]);
}
if (H == "asn1") {
return new v(k[H]);
}
if (H == "seq") {
var d = k[H];
var G = [];
for (var z2 = 0; z2 < d.length; z2++) {
var D = p(d[z2]);
G.push(D);
}
return new n2({ array: G });
}
if (H == "set") {
var d = k[H];
var G = [];
for (var z2 = 0; z2 < d.length; z2++) {
var D = p(d[z2]);
G.push(D);
}
return new c({ array: G });
}
if (H == "tag") {
var C = k[H];
if (Object.prototype.toString.call(C) === "[object Array]" && C.length == 3) {
var r2 = p(C[2]);
return new s({ tag: C[0], explicit: C[1], obj: r2 });
} else {
return new s(C);
}
}
};
this.jsonToASN1HEX = function(b) {
var a = this.newObject(b);
return a.tohex();
};
}();
KJUR.asn1.ASN1Util.oidHexToInt = function(a) {
var j = "";
var k = parseInt(a.substr(0, 2), 16);
var d = Math.floor(k / 40);
var c = k % 40;
var j = d + "." + c;
var e2 = "";
for (var f = 2; f < a.length; f += 2) {
var g = parseInt(a.substr(f, 2), 16);
var h = ("00000000" + g.toString(2)).slice(-8);
e2 = e2 + h.substr(1, 7);
if (h.substr(0, 1) == "0") {
var b = new BigInteger(e2, 2);
j = j + "." + b.toString(10);
e2 = "";
}
}
return j;
};
KJUR.asn1.ASN1Util.oidIntToHex = function(f) {
var e2 = function(a) {
var k = a.toString(16);
if (k.length == 1) {
k = "0" + k;
}
return k;
};
var d = function(o2) {
var n2 = "";
var k = new BigInteger(o2, 10);
var a = k.toString(2);
var l = 7 - a.length % 7;
if (l == 7) {
l = 0;
}
var q = "";
for (var m = 0; m < l; m++) {
q += "0";
}
a = q + a;
for (var m = 0; m < a.length - 1; m += 7) {
var p = a.substr(m, 7);
if (m != a.length - 7) {
p = "1" + p;
}
n2 += e2(parseInt(p, 2));
}
return n2;
};
if (!f.match(/^[0-9.]+$/)) {
throw "malformed oid string: " + f;
}
var g = "";
var b = f.split(".");
var j = parseInt(b[0]) * 40 + parseInt(b[1]);
g += e2(j);
b.splice(0, 2);
for (var c = 0; c < b.length; c++) {
g += d(b[c]);
}
return g;
};
KJUR.asn1.ASN1Object = function(e2) {
var c = true;
var b = null;
var d = "00";
var f = "00";
var a = "";
this.params = null;
this.getLengthHexFromValue = function() {
if (typeof this.hV == "undefined" || this.hV == null) {
throw new Error("this.hV is null or undefined");
}
if (this.hV.length % 2 == 1) {
throw new Error("value hex must be even length: n=" + a.length + ",v=" + this.hV);
}
var j = this.hV.length / 2;
var i = j.toString(16);
if (i.length % 2 == 1) {
i = "0" + i;
}
if (j < 128) {
return i;
} else {
var h = i.length / 2;
if (h > 15) {
throw new Error("ASN.1 length too long to represent by 8x: n = " + j.toString(16));
}
var g = 128 + h;
return g.toString(16) + i;
}
};
this.tohex = function() {
if (this.hTLV == null || this.isModified) {
this.hV = this.getFreshValueHex();
this.hL = this.getLengthHexFromValue();
this.hTLV = this.hT + this.hL + this.hV;
this.isModified = false;
}
return this.hTLV;
};
this.getEncodedHex = function() {
return this.tohex();
};
this.getValueHex = function() {
this.tohex();
return this.hV;
};
this.getFreshValueHex = function() {
return "";
};
this.setByParam = function(g) {
this.params = g;
};
if (e2 != void 0) {
if (e2.tlv != void 0) {
this.hTLV = e2.tlv;
this.isModified = false;
}
}
};
KJUR.asn1.DERAbstractString = function(c) {
KJUR.asn1.DERAbstractString.superclass.constructor.call(this);
var b = null;
var a = null;
this.getString = function() {
return this.s;
};
this.setString = function(d) {
this.hTLV = null;
this.isModified = true;
this.s = d;
this.hV = utf8tohex(this.s).toLowerCase();
};
this.setStringHex = function(d) {
this.hTLV = null;
this.isModified = true;
this.s = null;
this.hV = d;
};
this.getFreshValueHex = function() {
return this.hV;
};
if (typeof c != "undefined") {
if (typeof c == "string") {
this.setString(c);
} else {
if (typeof c.str != "undefined") {
this.setString(c.str);
} else {
if (typeof c.hex != "undefined") {
this.setStringHex(c.hex);
}
}
}
}
};
extendClass(KJUR.asn1.DERAbstractString, KJUR.asn1.ASN1Object);
KJUR.asn1.DERAbstractTime = function(c) {
KJUR.asn1.DERAbstractTime.superclass.constructor.call(this);
var b = null;
var a = null;
this.localDateToUTC = function(g) {
var e2 = g.getTime() + g.getTimezoneOffset() * 6e4;
var f = new Date(e2);
return f;
};
this.formatDate = function(m, o2, e2) {
var g = this.zeroPadding;
var n2 = this.localDateToUTC(m);
var p = String(n2.getFullYear());
if (o2 == "utc") {
p = p.substr(2, 2);
}
var l = g(String(n2.getMonth() + 1), 2);
var q = g(String(n2.getDate()), 2);
var h = g(String(n2.getHours()), 2);
var i = g(String(n2.getMinutes()), 2);
var j = g(String(n2.getSeconds()), 2);
var r2 = p + l + q + h + i + j;
if (e2 === true) {
var f = n2.getMilliseconds();
if (f != 0) {
var k = g(String(f), 3);
k = k.replace(/[0]+$/, "");
r2 = r2 + "." + k;
}
}
return r2 + "Z";
};
this.zeroPadding = function(e2, d) {
if (e2.length >= d) {
return e2;
}
return new Array(d - e2.length + 1).join("0") + e2;
};
this.setByParam = function(d) {
this.hV = null;
this.hTLV = null;
this.params = d;
};
this.getString = function() {
return void 0;
};
this.setString = function(d) {
this.hTLV = null;
this.isModified = true;
if (this.params == void 0) {
this.params = {};
}
this.params.str = d;
};
this.setByDate = function(d) {
this.hTLV = null;
this.isModified = true;
if (this.params == void 0) {
this.params = {};
}
this.params.date = d;
};
this.setByDateValue = function(h, j, e2, d, f, g) {
var i = new Date(Date.UTC(h, j - 1, e2, d, f, g, 0));
this.setByDate(i);
};
this.getFreshValueHex = function() {
return this.hV;
};
};
extendClass(KJUR.asn1.DERAbstractTime, KJUR.asn1.ASN1Object);
KJUR.asn1.DERAbstractStructured = function(b) {
KJUR.asn1.DERAbstractString.superclass.constructor.call(this);
var a = null;
this.setByASN1ObjectArray = function(c) {
this.hTLV = null;
this.isModified = true;
this.asn1Array = c;
};
this.appendASN1Object = function(c) {
this.hTLV = null;
this.isModified = true;
this.asn1Array.push(c);
};
this.asn1Array = new Array();
if (typeof b != "undefined") {
if (typeof b.array != "undefined") {
this.asn1Array = b.array;
}
}
};
extendClass(KJUR.asn1.DERAbstractStructured, KJUR.asn1.ASN1Object);
KJUR.asn1.DERBoolean = function(a) {
KJUR.asn1.DERBoolean.superclass.constructor.call(this);
this.hT = "01";
if (a == false) {
this.hTLV = "010100";
} else {
this.hTLV = "0101ff";
}
};
extendClass(KJUR.asn1.DERBoolean, KJUR.asn1.ASN1Object);
KJUR.asn1.DERInteger = function(b) {
KJUR.asn1.DERInteger.superclass.constructor.call(this);
this.hT = "02";
this.params = null;
var a = twoscompl;
this.setByBigInteger = function(c) {
this.isModified = true;
this.params = { bigint: c };
};
this.setByInteger = function(c) {
this.isModified = true;
this.params = c;
};
this.setValueHex = function(c) {
this.isModified = true;
this.params = { hex: c };
};
this.getFreshValueHex = function() {
var d = this.params;
var c = null;
if (d == null) {
throw new Error("value not set");
}
if (typeof d == "object" && d.hex != void 0) {
this.hV = d.hex;
return this.hV;
}
if (typeof d == "number") {
c = new BigInteger(String(d), 10);
} else {
if (d["int"] != void 0) {
c = new BigInteger(String(d["int"]), 10);
} else {
if (d.bigint != void 0) {
c = d.bigint;
} else {
throw new Error("wrong parameter");
}
}
}
this.hV = a(c);
return this.hV;
};
if (b != void 0) {
this.params = b;
}
};
extendClass(KJUR.asn1.DERInteger, KJUR.asn1.ASN1Object);
KJUR.asn1.DERBitString = function(b) {
if (b !== void 0 && typeof b.obj !== "undefined") {
var a = KJUR.asn1.ASN1Util.newObject(b.obj);
b.hex = "00" + a.tohex();
}
KJUR.asn1.DERBitString.superclass.constructor.call(this);
this.hT = "03";
this.setHexValueIncludingUnusedBits = function(c) {
this.hTLV = null;
this.isModified = true;
this.hV = c;
};
this.setUnusedBitsAndHexValue = function(c, e2) {
if (c < 0 || 7 < c) {
throw "unused bits shall be from 0 to 7: u = " + c;
}
var d = "0" + c;
this.hTLV = null;
this.isModified = true;
this.hV = d + e2;
};
this.setByBinaryString = function(e2) {
e2 = e2.replace(/0+$/, "");
var f = 8 - e2.length % 8;
if (f == 8) {
f = 0;
}
e2 += "0000000".substr(0, f);
var j = "";
for (var g = 0; g < e2.length - 1; g += 8) {
var d = e2.substr(g, 8);
var c = parseInt(d, 2).toString(16);
if (c.length == 1) {
c = "0" + c;
}
j += c;
}
this.hTLV = null;
this.isModified = true;
this.hV = "0" + f + j;
};
this.setByBooleanArray = function(e2) {
var d = "";
for (var c = 0; c < e2.length; c++) {
if (e2[c] == true) {
d += "1";
} else {
d += "0";
}
}
this.setByBinaryString(d);
};
this.newFalseArray = function(e2) {
var c = new Array(e2);
for (var d = 0; d < e2; d++) {
c[d] = false;
}
return c;
};
this.getFreshValueHex = function() {
return this.hV;
};
if (typeof b != "undefined") {
if (typeof b == "string" && b.toLowerCase().match(/^[0-9a-f]+$/)) {
this.setHexValueIncludingUnusedBits(b);
} else {
if (typeof b.hex != "undefined") {
this.setHexValueIncludingUnusedBits(b.hex);
} else {
if (typeof b.bin != "undefined") {
this.setByBinaryString(b.bin);
} else {
if (typeof b.array != "undefined") {
this.setByBooleanArray(b.array);
}
}
}
}
}
};
extendClass(KJUR.asn1.DERBitString, KJUR.asn1.ASN1Object);
KJUR.asn1.DEROctetString = function(b) {
if (b !== void 0 && typeof b.obj !== "undefined") {
var a = KJUR.asn1.ASN1Util.newObject(b.obj);
b.hex = a.tohex();
}
KJUR.asn1.DEROctetString.superclass.constructor.call(this, b);
this.hT = "04";
};
extendClass(KJUR.asn1.DEROctetString, KJUR.asn1.DERAbstractString);
KJUR.asn1.DERNull = function() {
KJUR.asn1.DERNull.superclass.constructor.call(this);
this.hT = "05";
this.hTLV = "0500";
};
extendClass(KJUR.asn1.DERNull, KJUR.asn1.ASN1Object);
KJUR.asn1.DERObjectIdentifier = function(a) {
KJUR.asn1.DERObjectIdentifier.superclass.constructor.call(this);
this.hT = "06";
this.setValueHex = function(b) {
this.hTLV = null;
this.isModified = true;
this.s = null;
this.hV = b;
};
this.setValueOidString = function(b) {
var c = oidtohex(b);
if (c == null) {
throw new Error("malformed oid string: " + b);
}
this.hTLV = null;
this.isModified = true;
this.s = null;
this.hV = c;
};
this.setValueName = function(c) {
var b = KJUR.asn1.x509.OID.name2oid(c);
if (b !== "") {
this.setValueOidString(b);
} else {
throw new Error("DERObjectIdentifier oidName undefined: " + c);
}
};
this.setValueNameOrOid = function(b) {
if (b.match(/^[0-2].[0-9.]+$/)) {
this.setValueOidString(b);
} else {
this.setValueName(b);
}
};
this.getFreshValueHex = function() {
return this.hV;
};
this.setByParam = function(b) {
if (typeof b === "string") {
this.setValueNameOrOid(b);
} else {
if (b.oid !== void 0) {
this.setValueNameOrOid(b.oid);
} else {
if (b.name !== void 0) {
this.setValueNameOrOid(b.name);
} else {
if (b.hex !== void 0) {
this.setValueHex(b.hex);
}
}
}
}
};
if (a !== void 0) {
this.setByParam(a);
}
};
extendClass(KJUR.asn1.DERObjectIdentifier, KJUR.asn1.ASN1Object);
KJUR.asn1.DEREnumerated = function(a) {
KJUR.asn1.DEREnumerated.superclass.constructor.call(this);
this.hT = "0a";
this.setByBigInteger = function(b) {
this.hTLV = null;
this.isModified = true;
this.hV = twoscompl(b);
};
this.setByInteger = function(c) {
var b = new BigInteger(String(c), 10);
this.setByBigInteger(b);
};
this.setValueHex = function(b) {
this.hV = b;
};
this.getFreshValueHex = function() {
return this.hV;
};
if (typeof a != "undefined") {
if (typeof a["int"] != "undefined") {
this.setByInteger(a["int"]);
} else {
if (typeof a == "number") {
this.setByInteger(a);
} else {
if (typeof a.hex != "undefined") {
this.setValueHex(a.hex);
}
}
}
}
};
extendClass(KJUR.asn1.DEREnumerated, KJUR.asn1.ASN1Object);
KJUR.asn1.DERUTF8String = function(a) {
KJUR.asn1.DERUTF8String.superclass.constructor.call(this, a);
this.hT = "0c";
};
extendClass(KJUR.asn1.DERUTF8String, KJUR.asn1.DERAbstractString);
KJUR.asn1.DERNumericString = function(a) {
KJUR.asn1.DERNumericString.superclass.constructor.call(this, a);
this.hT = "12";
};
extendClass(KJUR.asn1.DERNumericString, KJUR.asn1.DERAbstractString);
KJUR.asn1.DERPrintableString = function(a) {
KJUR.asn1.DERPrintableString.superclass.constructor.call(this, a);
this.hT = "13";
};
extendClass(KJUR.asn1.DERPrintableString, KJUR.asn1.DERAbstractString);
KJUR.asn1.DERTeletexString = function(a) {
KJUR.asn1.DERTeletexString.superclass.constructor.call(this, a);
this.hT = "14";
};
extendClass(KJUR.asn1.DERTeletexString, KJUR.asn1.DERAbstractString);
KJUR.asn1.DERIA5String = function(a) {
KJUR.asn1.DERIA5String.superclass.constructor.call(this, a);
this.hT = "16";
};
extendClass(KJUR.asn1.DERIA5String, KJUR.asn1.DERAbstractString);
KJUR.asn1.DERVisibleString = function(a) {
KJUR.asn1.DERIA5String.superclass.constructor.call(this, a);
this.hT = "1a";
};
extendClass(KJUR.asn1.DERVisibleString, KJUR.asn1.DERAbstractString);
KJUR.asn1.DERBMPString = function(a) {
KJUR.asn1.DERBMPString.superclass.constructor.call(this, a);
this.hT = "1e";
};
extendClass(KJUR.asn1.DERBMPString, KJUR.asn1.DERAbstractString);
KJUR.asn1.DERUTCTime = function(a) {
KJUR.asn1.DERUTCTime.superclass.constructor.call(this, a);
this.hT = "17";
this.params = void 0;
this.getFreshValueHex = function() {
var d = this.params;
if (this.params == void 0) {
d = { date: /* @__PURE__ */ new Date() };
}
if (typeof d == "string") {
if (d.match(/^[0-9]{12}Z$/) || d.match(/^[0-9]{12}\.[0-9]+Z$/)) {
this.hV = stohex(d);
} else {
throw new Error("malformed string for UTCTime: " + d);
}
} else {
if (d.str != void 0) {
this.hV = stohex(d.str);
} else {
if (d.date == void 0 && d.millis == true) {
var c = /* @__PURE__ */ new Date();
this.hV = stohex(this.formatDate(c, "utc", true));
} else {
if (d.date != void 0 && d.date instanceof Date) {
var b = d.millis === true;
this.hV = stohex(this.formatDate(d.date, "utc", b));
} else {
if (d instanceof Date) {
this.hV = stohex(this.formatDate(d, "utc"));
}
}
}
}
}
if (this.hV == void 0) {
throw new Error("parameter not specified properly for UTCTime");
}
return this.hV;
};
if (a != void 0) {
this.setByParam(a);
}
};
extendClass(KJUR.asn1.DERUTCTime, KJUR.asn1.DERAbstractTime);
KJUR.asn1.DERGeneralizedTime = function(a) {
KJUR.asn1.DERGeneralizedTime.superclass.constructor.call(this, a);
this.hT = "18";
this.params = a;
this.getFreshValueHex = function() {
var d = this.params;
if (this.params == void 0) {
d = { date: /* @__PURE__ */ new Date() };
}
if (typeof d == "string") {
if (d.match(/^[0-9]{14}Z$/) || d.match(/^[0-9]{14}\.[0-9]+Z$/)) {
this.hV = stohex(d);
} else {
throw new Error("malformed string for GeneralizedTime: " + d);
}
} else {
if (d.str != void 0) {
this.hV = stohex(d.str);
} else {
if (d.date == void 0 && d.millis == true) {
var c = /* @__PURE__ */ new Date();
this.hV = stohex(this.formatDate(c, "gen", true));
} else {
if (d.date != void 0 && d.date instanceof Date) {
var b = d.millis === true;
this.hV = stohex(this.formatDate(d.date, "gen", b));
} else {
if (d instanceof Date) {
this.hV = stohex(this.formatDate(d, "gen"));
}
}
}
}
}
if (this.hV == void 0) {
throw new Error("parameter not specified properly for GeneralizedTime");
}
return this.hV;
};
if (a != void 0) {
this.setByParam(a);
}
};
extendClass(KJUR.asn1.DERGeneralizedTime, KJUR.asn1.DERAbstractTime);
KJUR.asn1.DERSequence = function(a) {
KJUR.asn1.DERSequence.superclass.constructor.call(this, a);
this.hT = "30";
this.getFreshValueHex = function() {
var c = "";
for (var b = 0; b < this.asn1Array.length; b++) {
var d = this.asn1Array[b];
c += d.tohex();
}
this.hV = c;
return this.hV;
};
};
extendClass(KJUR.asn1.DERSequence, KJUR.asn1.DERAbstractStructured);
KJUR.asn1.DERSet = function(a) {
KJUR.asn1.DERSet.superclass.constructor.call(this, a);
this.hT = "31";
this.sortFlag = true;
this.getFreshValueHex = function() {
var b = new Array();
for (var c = 0; c < this.asn1Array.length; c++) {
var d = this.asn1Array[c];
b.push(d.tohex());
}
if (this.sortFlag == true) {
b.sort();
}
this.hV = b.join("");
return this.hV;
};
if (typeof a != "undefined") {
if (typeof a.sortflag != "undefined" && a.sortflag == false) {
this.sortFlag = false;
}
}
};
extendClass(KJUR.asn1.DERSet, KJUR.asn1.DERAbstractStructured);
KJUR.asn1.DERTaggedObject = function(f) {
KJUR.asn1.DERTaggedObject.superclass.constructor.call(this);
var d = KJUR.asn1, e2 = ASN1HEX, a = e2.getV, c = e2.isASN1HEX, b = d.ASN1Util.newObject;
this.hT = "a0";
this.hV = "";
this.isExplicit = true;
this.asn1Object = null;
this.params = { tag: "a0", explicit: true };
this.setASN1Object = function(g, h, i) {
this.params = { tag: h, explicit: g, obj: i };
};
this.getFreshValueHex = function() {
var h = this.params;
if (h.explicit == void 0) {
h.explicit = true;
}
if (h.tage != void 0) {
h.tag = h.tage;
h.explicit = true;
}
if (h.tagi != void 0) {
h.tag = h.tagi;
h.explicit = false;
}
if (h.str != void 0) {
this.hV = utf8tohex(h.str);
} else {
if (h.hex != void 0) {
this.hV = h.hex;
} else {
if (h.obj != void 0) {
var g;
if (h.obj instanceof d.ASN1Object) {
g = h.obj.tohex();
} else {
if (typeof h.obj == "object") {
g = b(h.obj).tohex();
}
}
if (h.explicit) {
this.hV = g;
} else {
this.hV = a(g, 0);
}
} else {
throw new Error("str, hex nor obj not specified");
}
}
}
if (h.tag == void 0) {
h.tag = "a0";
}
this.hT = h.tag;
this.hTLV = null;
this.isModified = true;
return this.hV;
};
this.setByParam = function(g) {
this.params = g;
};
if (f !== void 0) {
this.setByParam(f);
}
};
extendClass(KJUR.asn1.DERTaggedObject, KJUR.asn1.ASN1Object);
var ASN1HEX = new function() {
}();
ASN1HEX.getLblen = function(c, a) {
if (c.substr(a + 2, 1) != "8") {
return 1;
}
var b = parseInt(c.substr(a + 3, 1));
if (b == 0) {
return -1;
}
if (0 < b && b < 10) {
return b + 1;
}
return -2;
};
ASN1HEX.getL = function(c, b) {
var a = ASN1HEX.getLblen(c, b);
if (a < 1) {
return "";
}
return c.substr(b + 2, a * 2);
};
ASN1HEX.getVblen = function(d, a) {
var c, b;
c = ASN1HEX.getL(d, a);
if (c == "") {
return -1;
}
if (c.substr(0, 1) === "8") {
b = new BigInteger(c.substr(2), 16);
} else {
b = new BigInteger(c, 16);
}
return b.intValue();
};
ASN1HEX.getVidx = function(c, b) {
var a = ASN1HEX.getLblen(c, b);
if (a < 0) {
return a;
}
return b + (a + 1) * 2;
};
ASN1HEX.getV = function(d, a) {
var c = ASN1HEX.getVidx(d, a);
var b = ASN1HEX.getVblen(d, a);
return d.substr(c, b * 2);
};
ASN1HEX.getTLV = function(b, a) {
return b.substr(a, 2) + ASN1HEX.getL(b, a) + ASN1HEX.getV(b, a);
};
ASN1HEX.getTLVblen = function(b, a) {
return 2 + ASN1HEX.getLblen(b, a) * 2 + ASN1HEX.getVblen(b, a) * 2;
};
ASN1HEX.getNextSiblingIdx = function(d, a) {
var c = ASN1HEX.getVidx(d, a);
var b = ASN1HEX.getVblen(d, a);
return c + b * 2;
};
ASN1HEX.getChildIdx = function(e2, k) {
var l = ASN1HEX;
var j = [];
var c, f, g;
c = l.getVidx(e2, k);
f = l.getVblen(e2, k) * 2;
if (e2.substr(k, 2) == "03") {
c += 2;
f -= 2;
}
g = 0;
var d = c;
while (g <= f) {
var b = l.getTLVblen(e2, d);
g += b;
if (g <= f) {
j.push(d);
}
d += b;
if (g >= f) {
break;
}
}
return j;
};
ASN1HEX.getNthChildIdx = function(d, b, e2) {
var c = ASN1HEX.getChildIdx(d, b);
return c[e2];
};
ASN1HEX.getIdxbyList = function(e2, d, c, i) {
var g = ASN1HEX;
var f, b;
if (c.length == 0) {
if (i !== void 0) {
if (e2.substr(d, 2) !== i) {
return -1;
}
}
return d;
}
f = c.shift();
b = g.getChildIdx(e2, d);
if (f >= b.length) {
return -1;
}
return g.getIdxbyList(e2, b[f], c, i);
};
ASN1HEX.getIdxbyListEx = function(f, k, b, g) {
var m = ASN1HEX;
var d, l;
if (b.length == 0) {
if (g !== void 0) {
if (f.substr(k, 2) !== g) {
return -1;
}
}
return k;
}
d = b.shift();
l = m.getChildIdx(f, k);
var j = 0;
for (var e2 = 0; e2 < l.length; e2++) {
var c = f.substr(l[e2], 2);
if (typeof d == "number" && !m.isContextTag(c) && j == d || typeof d == "string" && m.isContextTag(c, d)) {
return m.getIdxbyListEx(f, l[e2], b, g);
}
if (!m.isContextTag(c)) {
j++;
}
}
return -1;
};
ASN1HEX.getTLVbyList = function(d, c, b, f) {
var e2 = ASN1HEX;
var a = e2.getIdxbyList(d, c, b, f);
if (a == -1) {
return null;
}
if (a >= d.length) {
return null;
}
return e2.getTLV(d, a);
};
ASN1HEX.getTLVbyListEx = function(d, c, b, f) {
var e2 = ASN1HEX;
var a = e2.getIdxbyListEx(d, c, b, f);
if (a == -1) {
return null;
}
return e2.getTLV(d, a);
};
ASN1HEX.getVbyList = function(e2, c, b, g, i) {
var f = ASN1HEX;
var a, d;
a = f.getIdxbyList(e2, c, b, g);
if (a == -1) {
return null;
}
if (a >= e2.length) {
return null;
}
d = f.getV(e2, a);
if (i === true) {
d = d.substr(2);
}
return d;
};
ASN1HEX.getVbyListEx = function(b, e2, a, d, f) {
var j = ASN1HEX;
var g, c, i;
g = j.getIdxbyListEx(b, e2, a, d);
if (g == -1) {
return null;
}
i = j.getV(b, g);
if (b.substr(g, 2) == "03" && f !== false) {
i = i.substr(2);
}
return i;
};
ASN1HEX.getInt = function(e2, b, f) {
if (f == void 0) {
f = -1;
}
try {
var c = e2.substr(b, 2);
if (c != "02" && c != "03") {
return f;
}
var a = ASN1HEX.getV(e2, b);
if (c == "02") {
return parseInt(a, 16);
} else {
return bitstrtoint(a);
}
} catch (d) {
return f;
}
};
ASN1HEX.getOID = function(c, a, d) {
if (d == void 0) {
d = null;
}
try {
if (c.substr(a, 2) != "06") {
return d;
}
var e2 = ASN1HEX.getV(c, a);
return hextooid(e2);
} catch (b) {
return d;
}
};
ASN1HEX.getOIDName = function(d, a, f) {
if (f == void 0) {
f = null;
}
try {
var e2 = ASN1HEX.getOID(d, a, f);
if (e2 == f) {
return f;
}
var b = KJUR.asn1.x509.OID.oid2name(e2);
if (b == "") {
return e2;
}
return b;
} catch (c) {
return f;
}
};
ASN1HEX.getString = function(d, b, e2) {
if (e2 == void 0) {
e2 = null;
}
try {
var a = ASN1HEX.getV(d, b);
return hextorstr(a);
} catch (c) {
return e2;
}
};
ASN1HEX.hextooidstr = function(e2) {
var h = function(b, a) {
if (b.length >= a) {
return b;
}
return new Array(a - b.length + 1).join("0") + b;
};
var l = [];
var o2 = e2.substr(0, 2);
var f = parseInt(o2, 16);
l[0] = new String(Math.floor(f / 40));
l[1] = new String(f % 40);
var m = e2.substr(2);
var k = [];
for (var g = 0; g < m.length / 2; g++) {
k.push(parseInt(m.substr(g * 2, 2), 16));
}
var j = [];
var d = "";
for (var g = 0; g < k.length; g++) {
if (k[g] & 128) {
d = d + h((k[g] & 127).toString(2), 7);
} else {
d = d + h((k[g] & 127).toString(2), 7);
j.push(new String(parseInt(d, 2)));
d = "";
}
}
var n2 = l.join(".");
if (j.length > 0) {
n2 = n2 + "." + j.join(".");
}
return n2;
};
ASN1HEX.dump = function(t3, c, l, g) {
var p = ASN1HEX;
var j = p.getV;
var y = p.dump;
var w = p.getChildIdx;
var e2 = t3;
if (t3 instanceof KJUR.asn1.ASN1Object) {
e2 = t3.tohex();
}
var q = function(A, i) {
if (A.length <= i * 2) {
return A;
} else {
var v = A.substr(0, i) + "..(total " + A.length / 2 + "bytes).." + A.substr(A.length - i, i);
return v;
}
};
if (c === void 0) {
c = { ommit_long_octet: 32 };
}
if (l === void 0) {
l = 0;
}
if (g === void 0) {
g = "";
}
var x = c.ommit_long_octet;
var z2 = e2.substr(l, 2);
if (z2 == "01") {
var h = j(e2, l);
if (h == "00") {
return g + "BOOLEAN FALSE\n";
} else {
return g + "BOOLEAN TRUE\n";
}
}
if (z2 == "02") {
var h = j(e2, l);
return g + "INTEGER " + q(h, x) + "\n";
}
if (z2 == "03") {
var h = j(e2, l);
if (p.isASN1HEX(h.substr(2))) {
var k = g + "BITSTRING, encapsulates\n";
k = k + y(h.substr(2), c, 0, g + " ");
return k;
} else {
return g + "BITSTRING " + q(h, x) + "\n";
}
}
if (z2 == "04") {
var h = j(e2, l);
if (p.isASN1HEX(h)) {
var k = g + "OCTETSTRING, encapsulates\n";
k = k + y(h, c, 0, g + " ");
return k;
} else {
return g + "OCTETSTRING " + q(h, x) + "\n";
}
}
if (z2 == "05") {
return g + "NULL\n";
}
if (z2 == "06") {
var m = j(e2, l);
var b = KJUR.asn1.ASN1Util.oidHexToInt(m);
var o2 = KJUR.asn1.x509.OID.oid2name(b);
var a = b.replace(/\./g, " ");
if (o2 != "") {
return g + "ObjectIdentifier " + o2 + " (" + a + ")\n";
} else {
return g + "ObjectIdentifier (" + a + ")\n";
}
}
if (z2 == "0a") {
return g + "ENUMERATED " + parseInt(j(e2, l)) + "\n";
}
if (z2 == "0c") {
return g + "UTF8String '" + hextoutf8(j(e2, l)) + "'\n";
}
if (z2 == "13") {
return g + "PrintableString '" + hextoutf8(j(e2, l)) + "'\n";
}
if (z2 == "14") {
return g + "TeletexString '" + hextoutf8(j(e2, l)) + "'\n";
}
if (z2 == "16") {
return g + "IA5String '" + hextoutf8(j(e2, l)) + "'\n";
}
if (z2 == "17") {
return g + "UTCTime " + hextoutf8(j(e2, l)) + "\n";
}
if (z2 == "18") {
return g + "GeneralizedTime " + hextoutf8(j(e2, l)) + "\n";
}
if (z2 == "1a") {
return g + "VisualString '" + hextoutf8(j(e2, l)) + "'\n";
}
if (z2 == "1e") {
return g + "BMPString '" + ucs2hextoutf8(j(e2, l)) + "'\n";
}
if (z2 == "30") {
if (e2.substr(l, 4) == "3000") {
return g + "SEQUENCE {}\n";
}
var k = g + "SEQUENCE\n";
var d = w(e2, l);
var f = c;
if ((d.length == 2 || d.length == 3) && e2.substr(d[0], 2) == "06" && e2.substr(d[d.length - 1], 2) == "04") {
var o2 = p.oidname(j(e2, d[0]));
var r2 = JSON.parse(JSON.stringify(c));
r2.x509ExtName = o2;
f = r2;
}
for (var u = 0; u < d.length; u++) {
k = k + y(e2, f, d[u], g + " ");
}
return k;
}
if (z2 == "31") {
var k = g + "SET\n";
var d = w(e2, l);
for (var u = 0; u < d.length; u++) {
k = k + y(e2, c, d[u], g + " ");
}
return k;
}
var z2 = parseInt(z2, 16);
if ((z2 & 128) != 0) {
var n2 = z2 & 31;
if ((z2 & 32) != 0) {
var k = g + "[" + n2 + "]\n";
var d = w(e2, l);
for (var u = 0; u < d.length; u++) {
k = k + y(e2, c, d[u], g + " ");
}
return k;
} else {
var h = j(e2, l);
if (ASN1HEX.isASN1HEX(h)) {
var k = g + "[" + n2 + "]\n";
k = k + y(h, c, 0, g + " ");
return k;
} else {
if (h.substr(0, 8) == "68747470") {
h = hextoutf8(h);
} else {
if (c.x509ExtName === "subjectAltName" && n2 == 2) {
h = hextoutf8(h);
}
}
}
var k = g + "[" + n2 + "] " + h + "\n";
return k;
}
}
return g + "UNKNOWN(" + z2 + ") " + j(e2, l) + "\n";
};
ASN1HEX.parse = function(x) {
var t3 = ASN1HEX, f = t3.parse, a = t3.isASN1HEX, l = t3.getV, b = t3.getTLV, y = t3.getChildIdx, i = KJUR.asn1, e2 = i.ASN1Util.oidHexToInt, B = i.x509.OID.oid2name, k = hextoutf8, n2 = ucs2hextoutf8, q = iso88591hextoutf8;
var c = { "0c": "utf8str", "12": "numstr", "13": "prnstr", "14": "telstr", "16": "ia5str", "17": "utctime", "18": "gentime", "1a": "visstr", "1e": "bmpstr", "30": "seq", "31": "set" };
var u = function(H) {
var D = [];
var E = y(H, 0);
for (var G = 0; G < E.length; G++) {
var s = E[G];
var d = b(H, s);
var F = f(d);
D.push(F);
}
return D;
};
var C = x.substr(0, 2);
var j = {};
var p = l(x, 0);
if (C == "01") {
if (x == "0101ff") {
return { bool: true };
}
return { bool: false };
} else {
if (C == "02") {
return { "int": { hex: p } };
} else {
if (C == "03") {
try {
if (p.substr(0, 2) != "00") {
throw "not encap";
}
var v = p.substr(2);
if (!a(v)) {
throw "not encap";
}
return { bitstr: { obj: f(v) } };
} catch (z2) {
var m = null;
if (p.length <= 10) {
m = bitstrtobinstr(p);
}
if (m == null) {
return { bitstr: { hex: p } };
} else {
return { bitstr: { bin: m } };
}
}
} else {
if (C == "04") {
try {
if (!a(p)) {
throw "not encap";
}
return { octstr: { obj: f(p) } };
} catch (z2) {
return { octstr: { hex: p } };
}
} else {
if (C == "05") {
return { "null": "" };
} else {
if (C == "06") {
var g = e2(p);
var r2 = B(g);
if (r2 == "") {
return { oid: g };
} else {
return { oid: r2 };
}
} else {
if (C == "0a") {
if (p.length > 4) {
return { "enum": { hex: p } };
} else {
return { "enum": parseInt(p, 16) };
}
} else {
if (C == "30" || C == "31") {
j[c[C]] = u(x);
return j;
} else {
if (C == "14") {
var o2 = q(p);
j[c[C]] = { str: o2 };
return j;
} else {
if (C == "1e") {
var o2 = n2(p);
j[c[C]] = { str: o2 };
return j;
} else {
if (":0c:12:13:16:17:18:1a:".indexOf(C) != -1) {
var o2 = k(p);
j[c[C]] = { str: o2 };
return j;
} else {
if (C.match(/^8[0-9]$/)) {
var o2 = k(p);
if (o2 == null | o2 == "") {
return { tag: { tag: C, explicit: false, hex: p } };
} else {
if (o2.match(/[\x00-\x1F\x7F-\x9F]/) != null || o2.match(/[\u0000-\u001F\u0080–\u009F]/) != null) {
return { tag: { tag: C, explicit: false, hex: p } };
} else {
return { tag: { tag: C, explicit: false, str: o2 } };
}
}
} else {
if (C.match(/^a[0-9]$/)) {
try {
if (!a(p)) {
throw new Error("not encap");
}
return { tag: { tag: C, explicit: true, obj: f(p) } };
} catch (z2) {
return { tag: { tag: C, explicit: true, hex: p } };
}
} else {
var A = new KJUR.asn1.ASN1Object();
A.hV = p;
var w = A.getLengthHexFromValue();
return { asn1: { tlv: C + w + p } };
}
}
}
}
}
}
}
}
}
}
}
}
}
};
ASN1HEX.isContextTag = function(c, b) {
c = c.toLowerCase();
var f, e2;
try {
f = parseInt(c, 16);
} catch (d) {
return -1;
}
if (b === void 0) {
if ((f & 192) == 128) {
return true;
} else {
return false;
}
}
try {
var a = b.match(/^\[[0-9]+\]$/);
if (a == null) {
return false;
}
e2 = parseInt(b.substr(1, b.length - 1), 10);
if (e2 > 31) {
return false;
}
if ((f & 192) == 128 && (f & 31) == e2) {
return true;
}
return false;
} catch (d) {
return false;
}
};
ASN1HEX.isASN1HEX = function(e2) {
var d = ASN1HEX;
if (e2.length % 2 == 1) {
return false;
}
var c = d.getVblen(e2, 0);
var b = e2.substr(0, 2);
var f = d.getL(e2, 0);
var a = e2.length - b.length - f.length;
if (a == c * 2) {
return true;
}
return false;
};
ASN1HEX.checkStrictDER = function(g, o2, d, c, r2) {
var s = ASN1HEX;
if (d === void 0) {
if (typeof g != "string") {
throw new Error("not hex string");
}
g = g.toLowerCase();
if (!KJUR.lang.String.isHex(g)) {
throw new Error("not hex string");
}
d = g.length;
c = g.length / 2;
if (c < 128) {
r2 = 1;
} else {
r2 = Math.ceil(c.toString(16)) + 1;
}
}
var k = s.getL(g, o2);
if (k.length > r2 * 2) {
throw new Error("L of TLV too long: idx=" + o2);
}
var n2 = s.getVblen(g, o2);
if (n2 > c) {
throw new Error("value of L too long than hex: idx=" + o2);
}
var q = s.getTLV(g, o2);
var f = q.length - 2 - s.getL(g, o2).length;
if (f !== n2 * 2) {
throw new Error("V string length and L's value not the same:" + f + "/" + n2 * 2);
}
if (o2 === 0) {
if (g.length != q.length) {
throw new Error("total length and TLV length unmatch:" + g.length + "!=" + q.length);
}
}
var b = g.substr(o2, 2);
if (b === "02") {
var a = s.getVidx(g, o2);
if (g.substr(a, 2) == "00" && g.charCodeAt(a + 2) < 56) {
throw new Error("not least zeros for DER INTEGER");
}
}
if (parseInt(b, 16) & 32) {
var p = s.getVblen(g, o2);
var m = 0;
var l = s.getChildIdx(g, o2);
for (var e2 = 0; e2 < l.length; e2++) {
var j = s.getTLV(g, l[e2]);
m += j.length;
s.checkStrictDER(g, l[e2], d, c, r2);
}
if (p * 2 != m) {
throw new Error("sum of children's TLV length and L unmatch: " + p * 2 + "!=" + m);
}
}
};
ASN1HEX.oidname = function(a) {
var c = KJUR.asn1;
if (KJUR.lang.String.isHex(a)) {
a = c.ASN1Util.oidHexToInt(a);
}
var b = c.x509.OID.oid2name(a);
if (b === "") {
b = a;
}
return b;
};
if (typeof KJUR == "undefined" || !KJUR) {
KJUR = {};
}
if (typeof KJUR.asn1 == "undefined" || !KJUR.asn1) {
KJUR.asn1 = {};
}
if (typeof KJUR.asn1.x509 == "undefined" || !KJUR.asn1.x509) {
KJUR.asn1.x509 = {};
}
KJUR.asn1.x509.Certificate = function(h) {
KJUR.asn1.x509.Certificate.superclass.constructor.call(this);
var d = KJUR, c = d.asn1, f = c.DERBitString, b = c.DERSequence, g = c.x509, a = g.TBSCertificate, e2 = g.AlgorithmIdentifier;
this.params = void 0;
this.setByParam = function(i) {
this.params = i;
};
this.sign = function() {
var l = this.params;
var k = l.sigalg;
if (l.sigalg.name != void 0) {
k = l.sigalg.name;
}
var i = l.tbsobj.tohex();
var j = new KJUR.crypto.Signature({ alg: k });
j.init(l.cakey);
j.updateHex(i);
l.sighex = j.sign();
};
this.getPEM = function() {
return hextopem(this.tohex(), "CERTIFICATE");
};
this.tohex = function() {
var k = this.params;
if (k.tbsobj == void 0 || k.tbsobj == null) {
k.tbsobj = new a(k);
}
if (k.sighex == void 0 && k.cakey != void 0) {
this.sign();
}
if (k.sighex == void 0) {
throw new Error("sighex or cakey parameter not defined");
}
var i = [];
i.push(k.tbsobj);
i.push(new e2({ name: k.sigalg }));
i.push(new f({ hex: "00" + k.sighex }));
var j = new b({ array: i });
return j.tohex();
};
this.getEncodedHex = function() {
return this.tohex();
};
if (h != void 0) {
this.params = h;
}
};
extendClass(KJUR.asn1.x509.Certificate, KJUR.asn1.ASN1Object);
KJUR.asn1.x509.TBSCertificate = function(f) {
KJUR.asn1.x509.TBSCertificate.superclass.constructor.call(this);
var b = KJUR, i = b.asn1, d = i.x509, c = i.DERTaggedObject, h = i.DERInteger, g = i.DERSequence, l = d.AlgorithmIdentifier, e2 = d.Time, a = d.X500Name, j = d.Extensions, k = d.SubjectPublicKeyInfo;
this.params = null;
this.setByParam = function(m) {
this.params = m;
};
this.tohex = function() {
var n2 = [];
var q = this.params;
if (q.version != void 0 || q.version != 1) {
var m = 2;
if (q.version != void 0) {
m = q.version - 1;
}
var p = new c({ obj: new h({ "int": m }) });
n2.push(p);
}
n2.push(new h(q.serial));
n2.push(new l({ name: q.sigalg }));
n2.push(new a(q.issuer));
n2.push(new g({ array: [new e2(q.notbefore), new e2(q.notafter)] }));
n2.push(new a(q.subject));
n2.push(new k(KEYUTIL.getKey(q.sbjpubkey)));
if (q.ext !== void 0 && q.ext.length > 0) {
n2.push(new c({ tag: "a3", obj: new j(q.ext) }));
}
var o2 = new KJUR.asn1.DERSequence({ array: n2 });
return o2.tohex();
};
this.getEncodedHex = function() {
return this.tohex();
};
if (f !== void 0) {
this.setByParam(f);
}
};
extendClass(KJUR.asn1.x509.TBSCertificate, KJUR.asn1.ASN1Object);
KJUR.asn1.x509.Extensions = function(d) {
KJUR.asn1.x509.Extensions.superclass.constructor.call(this);
var c = KJUR, b = c.asn1, a = b.DERSequence, e2 = b.x509;
this.aParam = [];
this.setByParam = function(f) {
this.aParam = f;
};
this.tohex = function() {
var f = [];
for (var h = 0; h < this.aParam.length; h++) {
var l = this.aParam[h];
var k = l.extname;
var j = null;
if (l.extn != void 0) {
j = new e2.PrivateExtension(l);
} else {
if (k == "subjectKeyIdentifier") {
j = new e2.SubjectKeyIdentifier(l);
} else {
if (k == "keyUsage") {
j = new e2.KeyUsage(l);
} else {
if (k == "subjectAltName") {
j = new e2.SubjectAltName(l);
} else {
if (k == "issuerAltName") {
j = new e2.IssuerAltName(l);
} else {
if (k == "basicConstraints") {
j = new e2.BasicConstraints(l);
} else {
if (k == "nameConstraints") {
j = new e2.NameConstraints(l);
} else {
if (k == "cRLDistributionPoints") {
j = new e2.CRLDistributionPoints(l);
} else {
if (k == "certificatePolicies") {
j = new e2.CertificatePolicies(l);
} else {
if (k == "policyMappings") {
j = new e2.PolicyMappings(l);
} else {
if (k == "policyConstraints") {
j = new e2.PolicyConstraints(l);
} else {
if (k == "inhibitAnyPolicy") {
j = new e2.InhibitAnyPolicy(l);
} else {
if (k == "authorityKeyIdentifier") {
j = new e2.AuthorityKeyIdentifier(l);
} else {
if (k == "extKeyUsage") {
j = new e2.ExtKeyUsage(l);
} else {
if (k == "authorityInfoAccess") {
j = new e2.AuthorityInfoAccess(l);
} else {
if (k == "cRLNumber") {
j = new e2.CRLNumber(l);
} else {
if (k == "cRLReason") {
j = new e2.CRLReason(l);
} else {
if (k == "ocspNonce") {
j = new e2.OCSPNonce(l);
} else {
if (k == "ocspNoCheck") {
j = new e2.OCSPNoCheck(l);
} else {
if (k == "adobeTimeStamp") {
j = new e2.AdobeTimeStamp(l);
} else {
if (k == "subjectDirectoryAttributes") {
j = new e2.SubjectDirectoryAttributes(l);
} else {
throw new Error("extension not supported:" + JSON.stringify(l));
}
}
}
}
}
}
}
}
}
}
}
}
}
}
}
}
}
}
}
}
}
if (j != null) {
f.push(j);
}
}
var g = new a({ array: f });
return g.tohex();
};
this.getEncodedHex = function() {
return this.tohex();
};
if (d != void 0) {
this.setByParam(d);
}
};
extendClass(KJUR.asn1.x509.Extensions, KJUR.asn1.ASN1Object);
KJUR.asn1.x509.Extension = function(d) {
KJUR.asn1.x509.Extension.superclass.constructor.call(this);
var f = null, a = KJUR, e2 = a.asn1, h = e2.DERObjectIdentifier, i = e2.DEROctetString, b = e2.DERBitString, g = e2.DERBoolean, c = e2.DERSequence;
this.tohex = function() {
var m = new h({ oid: this.oid });
var l = new i({ hex: this.getExtnValueHex() });
var k = new Array();
k.push(m);
if (this.critical) {
k.push(new g());
}
k.push(l);
var j = new c({ array: k });
return j.tohex();
};
this.getEncodedHex = function() {
return this.tohex();
};
this.critical = false;
if (d !== void 0) {
if (d.critical !== void 0) {
this.critical = d.critical;
}
}
};
extendClass(KJUR.asn1.x509.Extension, KJUR.asn1.ASN1Object);
KJUR.asn1.x509.KeyUsage = function(c) {
KJUR.asn1.x509.KeyUsage.superclass.constructor.call(this, c);
var b = Error;
var a = { digitalSignature: 0, nonRepudiation: 1, keyEncipherment: 2, dataEncipherment: 3, keyAgreement: 4, keyCertSign: 5, cRLSign: 6, encipherOnly: 7, decipherOnly: 8 };
this.getExtnValueHex = function() {
var d = this.getBinValue();
this.asn1ExtnValue = new KJUR.asn1.DERBitString({ bin: d });
return this.asn1ExtnValue.tohex();
};
this.getBinValue = function() {
var d = this.params;
if (typeof d != "object" || typeof d.names != "object" && typeof d.bin != "string") {
throw new b("parameter not yet set");
}
if (d.names != void 0) {
return namearraytobinstr(d.names, a);
} else {
if (d.bin != void 0) {
return d.bin;
} else {
throw new b("parameter not set properly");
}
}
};
this.oid = "2.5.29.15";
if (c !== void 0) {
this.params = c;
}
};
extendClass(KJUR.asn1.x509.KeyUsage, KJUR.asn1.x509.Extension);
KJUR.asn1.x509.BasicConstraints = function(g) {
KJUR.asn1.x509.BasicConstraints.superclass.constructor.call(this, g);
var c = KJUR.asn1, e2 = c.DERBoolean, f = c.DERInteger, b = c.DERSequence;
var a = false;
var d = -1;
this.getExtnValueHex = function() {
var i = new Array();
if (this.cA) {
i.push(new e2());
}
if (this.pathLen > -1) {
i.push(new f({ "int": this.pathLen }));
}
var h = new b({ array: i });
this.asn1ExtnValue = h;
return this.asn1ExtnValue.tohex();
};
this.oid = "2.5.29.19";
this.cA = false;
this.pathLen = -1;
if (g !== void 0) {
if (g.cA !== void 0) {
this.cA = g.cA;
}
if (g.pathLen !== void 0) {
this.pathLen = g.pathLen;
}
}
};
extendClass(KJUR.asn1.x509.BasicConstraints, KJUR.asn1.x509.Extension);
KJUR.asn1.x509.CRLDistributionPoints = function(d) {
KJUR.asn1.x509.CRLDistributionPoints.superclass.constructor.call(this, d);
var b = KJUR, a = b.asn1, c = a.x509;
this.getExtnValueHex = function() {
return this.asn1ExtnValue.tohex();
};
this.setByDPArray = function(e2) {
var f = [];
for (var g = 0; g < e2.length; g++) {
if (e2[g] instanceof KJUR.asn1.ASN1Object) {
f.push(e2[g]);
} else {
var h = new c.DistributionPoint(e2[g]);
f.push(h);
}
}
this.asn1ExtnValue = new a.DERSequence({ array: f });
};
this.setByOneURI = function(f) {
var e2 = new c.DistributionPoint({ fulluri: f });
this.setByDPArray([e2]);
};
this.oid = "2.5.29.31";
if (d !== void 0) {
if (d.array !== void 0) {
this.setByDPArray(d.array);
} else {
if (d.uri !== void 0) {
this.setByOneURI(d.uri);
}
}
}
};
extendClass(KJUR.asn1.x509.CRLDistributionPoints, KJUR.asn1.x509.Extension);
KJUR.asn1.x509.DistributionPoint = function(e2) {
KJUR.asn1.x509.DistributionPoint.superclass.constructor.call(this);
var a = null, c = KJUR, b = c.asn1, d = b.x509.DistributionPointName;
this.tohex = function() {
var f = new b.DERSequence();
if (this.asn1DP != null) {
var g = new b.DERTaggedObject({ explicit: true, tag: "a0", obj: this.asn1DP });
f.appendASN1Object(g);
}
this.hTLV = f.tohex();
return this.hTLV;
};
this.getEncodedHex = function() {
return this.tohex();
};
if (e2 !== void 0) {
if (e2.dpobj !== void 0) {
this.asn1DP = e2.dpobj;
} else {
if (e2.dpname !== void 0) {
this.asn1DP = new d(e2.dpname);
} else {
if (e2.fulluri !== void 0) {
this.asn1DP = new d({ full: [{ uri: e2.fulluri }] });
}
}
}
}
};
extendClass(KJUR.asn1.x509.DistributionPoint, KJUR.asn1.ASN1Object);
KJUR.asn1.x509.DistributionPointName = function(h) {
KJUR.asn1.x509.DistributionPointName.superclass.constructor.call(this);
var g = null, d = null, a = null, f = null, c = KJUR, b = c.asn1, e2 = b.DERTaggedObject;
this.tohex = function() {
if (this.type != "full") {
throw new Error("currently type shall be 'full': " + this.type);
}
this.asn1Obj = new e2({ explicit: false, tag: this.tag, obj: this.asn1V });
this.hTLV = this.asn1Obj.tohex();
return this.hTLV;
};
this.getEncodedHex = function() {
return this.tohex();
};
if (h !== void 0) {
if (b.x509.GeneralNames.prototype.isPrototypeOf(h)) {
this.type = "full";
this.tag = "a0";
this.asn1V = h;
} else {
if (h.full !== void 0) {
this.type = "full";
this.tag = "a0";
this.asn1V = new b.x509.GeneralNames(h.full);
} else {
throw new Error("This class supports GeneralNames only as argument");
}
}
}
};
extendClass(KJUR.asn1.x509.DistributionPointName, KJUR.asn1.ASN1Object);
KJUR.asn1.x509.CertificatePolicies = function(f) {
KJUR.asn1.x509.CertificatePolicies.superclass.constructor.call(this, f);
var c = KJUR, b = c.asn1, e2 = b.x509, a = b.DERSequence, d = e2.PolicyInformation;
this.params = null;
this.getExtnValueHex = function() {
var j = [];
for (var h = 0; h < this.params.array.length; h++) {
j.push(new d(this.params.array[h]));
}
var g = new a({ array: j });
this.asn1ExtnValue = g;
return this.asn1ExtnValue.tohex();
};
this.oid = "2.5.29.32";
if (f !== void 0) {
this.params = f;
}
};
extendClass(KJUR.asn1.x509.CertificatePolicies, KJUR.asn1.x509.Extension);
KJUR.asn1.x509.PolicyInformation = function(d) {
KJUR.asn1.x509.PolicyInformation.superclass.constructor.call(this, d);
var c = KJUR.asn1, b = c.DERSequence, e2 = c.DERObjectIdentifier, a = c.x509.PolicyQualifierInfo;
this.params = null;
this.tohex = function() {
if (this.params.policyoid === void 0 && this.params.array === void 0) {
throw new Error("parameter oid and array missing");
}
var f = [new e2(this.params.policyoid)];
if (this.params.array !== void 0) {
var j = [];
for (var h = 0; h < this.params.array.length; h++) {
j.push(new a(this.params.array[h]));
}
if (j.length > 0) {
f.push(new b({ array: j }));
}
}
var g = new b({ array: f });
return g.tohex();
};
this.getEncodedHex = function() {
return this.tohex();
};
if (d !== void 0) {
this.params = d;
}
};
extendClass(KJUR.asn1.x509.PolicyInformation, KJUR.asn1.ASN1Object);
KJUR.asn1.x509.PolicyQualifierInfo = function(e2) {
KJUR.asn1.x509.PolicyQualifierInfo.superclass.constructor.call(this, e2);
var c = KJUR.asn1, b = c.DERSequence, d = c.DERIA5String, f = c.DERObjectIdentifier, a = c.x509.UserNotice;
this.params = null;
this.tohex = function() {
if (this.params.cps !== void 0) {
var g = new b({ array: [new f({ oid: "1.3.6.1.5.5.7.2.1" }), new d({ str: this.params.cps })] });
return g.tohex();
}
if (this.params.unotice != void 0) {
var g = new b({ array: [new f({ oid: "1.3.6.1.5.5.7.2.2" }), new a(this.params.unotice)] });
return g.tohex();
}
};
this.getEncodedHex = function() {
return this.tohex();
};
if (e2 !== void 0) {
this.params = e2;
}
};
extendClass(KJUR.asn1.x509.PolicyQualifierInfo, KJUR.asn1.ASN1Object);
KJUR.asn1.x509.UserNotice = function(e2) {
KJUR.asn1.x509.UserNotice.superclass.constructor.call(this, e2);
var a = KJUR.asn1.DERSequence, d = KJUR.asn1.DERInteger, c = KJUR.asn1.x509.DisplayText, b = KJUR.asn1.x509.NoticeReference;
this.params = null;
this.tohex = function() {
var f = [];
if (this.params.noticeref !== void 0) {
f.push(new b(this.params.noticeref));
}
if (this.params.exptext !== void 0) {
f.push(new c(this.params.exptext));
}
var g = new a({ array: f });
return g.tohex();
};
this.getEncodedHex = function() {
return this.tohex();
};
if (e2 !== void 0) {
this.params = e2;
}
};
extendClass(KJUR.asn1.x509.UserNotice, KJUR.asn1.ASN1Object);
KJUR.asn1.x509.NoticeReference = function(d) {
KJUR.asn1.x509.NoticeReference.superclass.constructor.call(this, d);
var a = KJUR.asn1.DERSequence, c = KJUR.asn1.DERInteger, b = KJUR.asn1.x509.DisplayText;
this.params = null;
this.tohex = function() {
var f = [];
if (this.params.org !== void 0) {
f.push(new b(this.params.org));
}
if (this.params.noticenum !== void 0) {
var h = [];
var e2 = this.params.noticenum;
for (var j = 0; j < e2.length; j++) {
h.push(new c(e2[j]));
}
f.push(new a({ array: h }));
}
if (f.length == 0) {
throw new Error("parameter is empty");
}
var g = new a({ array: f });
return g.tohex();
};
this.getEncodedHex = function() {
return this.tohex();
};
if (d !== void 0) {
this.params = d;
}
};
extendClass(KJUR.asn1.x509.NoticeReference, KJUR.asn1.ASN1Object);
KJUR.asn1.x509.DisplayText = function(a) {
KJUR.asn1.x509.DisplayText.superclass.constructor.call(this, a);
this.hT = "0c";
if (a !== void 0) {
if (a.type === "ia5") {
this.hT = "16";
} else {
if (a.type === "vis") {
this.hT = "1a";
} else {
if (a.type === "bmp") {
this.hT = "1e";
}
}
}
}
};
extendClass(KJUR.asn1.x509.DisplayText, KJUR.asn1.DERAbstractString);
KJUR.asn1.x509.PolicyMappings = function(e2) {
KJUR.asn1.x509.PolicyMappings.superclass.constructor.call(this, e2);
var c = KJUR, b = c.asn1, d = b.x509, a = b.ASN1Util.newObject;
this.params = null;
this.getExtnValueHex = function() {
var j = this.params;
var f = [];
for (var g = 0; g < j.array.length; g++) {
var h = j.array[g];
f.push({ seq: [{ oid: h[0] }, { oid: h[1] }] });
}
this.asn1ExtnValue = a({ seq: f });
return this.asn1ExtnValue.tohex();
};
this.oid = "2.5.29.33";
if (e2 !== void 0) {
this.params = e2;
}
};
extendClass(KJUR.asn1.x509.PolicyMappings, KJUR.asn1.x509.Extension);
KJUR.asn1.x509.PolicyConstraints = function(e2) {
KJUR.asn1.x509.PolicyConstraints.superclass.constructor.call(this, e2);
var c = KJUR, b = c.asn1, d = b.x509, a = b.ASN1Util.newObject;
this.params = null;
this.getExtnValueHex = function() {
var g = this.params;
var f = [];
if (g.reqexp != void 0) {
f.push({ tag: { tagi: "80", obj: { "int": g.reqexp } } });
}
if (g.inhibit != void 0) {
f.push({ tag: { tagi: "81", obj: { "int": g.inhibit } } });
}
this.asn1ExtnValue = a({ seq: f });
return this.asn1ExtnValue.tohex();
};
this.oid = "2.5.29.36";
if (e2 !== void 0) {
this.params = e2;
}
};
extendClass(KJUR.asn1.x509.PolicyConstraints, KJUR.asn1.x509.Extension);
KJUR.asn1.x509.InhibitAnyPolicy = function(e2) {
KJUR.asn1.x509.InhibitAnyPolicy.superclass.constructor.call(this, e2);
var c = KJUR, b = c.asn1, d = b.x509, a = b.ASN1Util.newObject;
this.params = null;
this.getExtnValueHex = function() {
this.asn1ExtnValue = a({ "int": this.params.skip });
return this.asn1ExtnValue.tohex();
};
this.oid = "2.5.29.54";
if (e2 !== void 0) {
this.params = e2;
}
};
extendClass(KJUR.asn1.x509.InhibitAnyPolicy, KJUR.asn1.x509.Extension);
KJUR.asn1.x509.NameConstraints = function(f) {
KJUR.asn1.x509.NameConstraints.superclass.constructor.call(this, f);
var c = KJUR, b = c.asn1, e2 = b.x509, a = b.ASN1Util.newObject, d = e2.GeneralSubtree;
this.params = null;
this.getExtnValueHex = function() {
var l = this.params;
var g = [];
if (l.permit != void 0 && l.permit.length != void 0) {
var k = [];
for (var h = 0; h < l.permit.length; h++) {
k.push(new d(l.permit[h]));
}
g.push({ tag: { tagi: "a0", obj: { seq: k } } });
}
if (l.exclude != void 0 && l.exclude.length != void 0) {
var j = [];
for (var h = 0; h < l.exclude.length; h++) {
j.push(new d(l.exclude[h]));
}
g.push({ tag: { tagi: "a1", obj: { seq: j } } });
}
this.asn1ExtnValue = a({ seq: g });
return this.asn1ExtnValue.tohex();
};
this.oid = "2.5.29.30";
if (f !== void 0) {
this.params = f;
}
};
extendClass(KJUR.asn1.x509.NameConstraints, KJUR.asn1.x509.Extension);
KJUR.asn1.x509.GeneralSubtree = function(e2) {
KJUR.asn1.x509.GeneralSubtree.superclass.constructor.call(this);
var b = KJUR.asn1, d = b.x509, c = d.GeneralName, a = b.ASN1Util.newObject;
this.params = null;
this.setByParam = function(f) {
this.params = f;
};
this.tohex = function() {
var h = this.params;
var f = [new c(h)];
if (h.min != void 0) {
f.push({ tag: { tagi: "80", obj: { "int": h.min } } });
}
if (h.max != void 0) {
f.push({ tag: { tagi: "81", obj: { "int": h.max } } });
}
var g = a({ seq: f });
return g.tohex();
};
this.getEncodedHex = function() {
return this.tohex();
};
if (e2 !== void 0) {
this.setByParam(e2);
}
};
extendClass(KJUR.asn1.x509.GeneralSubtree, KJUR.asn1.ASN1Object);
KJUR.asn1.x509.ExtKeyUsage = function(c) {
KJUR.asn1.x509.ExtKeyUsage.superclass.constructor.call(this, c);
var b = KJUR, a = b.asn1;
this.setPurposeArray = function(d) {
this.asn1ExtnValue = new a.DERSequence();
for (var e2 = 0; e2 < d.length; e2++) {
var f = new a.DERObjectIdentifier(d[e2]);
this.asn1ExtnValue.appendASN1Object(f);
}
};
this.getExtnValueHex = function() {
return this.asn1ExtnValue.tohex();
};
this.oid = "2.5.29.37";
if (c !== void 0) {
if (c.array !== void 0) {
this.setPurposeArray(c.array);
}
}
};
extendClass(KJUR.asn1.x509.ExtKeyUsage, KJUR.asn1.x509.Extension);
KJUR.asn1.x509.AuthorityKeyIdentifier = function(f) {
KJUR.asn1.x509.AuthorityKeyIdentifier.superclass.constructor.call(this, f);
var b = KJUR, a = b.asn1, d = a.DERTaggedObject, e2 = a.x509.GeneralNames, c = b.crypto.Util.isKey;
this.asn1KID = null;
this.asn1CertIssuer = null;
this.asn1CertSN = null;
this.getExtnValueHex = function() {
var h = new Array();
if (this.asn1KID) {
h.push(new d({ explicit: false, tag: "80", obj: this.asn1KID }));
}
if (this.asn1CertIssuer) {
h.push(new d({ explicit: false, tag: "a1", obj: new e2([{ dn: this.asn1CertIssuer }]) }));
}
if (this.asn1CertSN) {
h.push(new d({ explicit: false, tag: "82", obj: this.asn1CertSN }));
}
var g = new a.DERSequence({ array: h });
this.asn1ExtnValue = g;
return this.asn1ExtnValue.tohex();
};
this.setKIDByParam = function(i) {
if (i.str !== void 0 || i.hex !== void 0) {
this.asn1KID = new KJUR.asn1.DEROctetString(i);
} else {
if (typeof i === "object" && KJUR.crypto.Util.isKey(i) || typeof i === "string" && i.indexOf("BEGIN ") != -1) {
var h = i;
if (typeof i === "string") {
h = KEYUTIL.getKey(i);
}
var g = KEYUTIL.getKeyID(h);
this.asn1KID = new KJUR.asn1.DEROctetString({ hex: g });
}
}
};
this.setCertIssuerByParam = function(g) {
if (g.str !== void 0 || g.ldapstr !== void 0 || g.hex !== void 0 || g.certsubject !== void 0 || g.certissuer !== void 0) {
this.asn1CertIssuer = new KJUR.asn1.x509.X500Name(g);
} else {
if (typeof g === "string" && g.indexOf("BEGIN ") != -1 && g.indexOf("CERTIFICATE") != -1) {
this.asn1CertIssuer = new KJUR.asn1.x509.X500Name({ certissuer: g });
}
}
};
this.setCertSNByParam = function(i) {
if (i.str !== void 0 || i.bigint !== void 0 || i.hex !== void 0) {
this.asn1CertSN = new KJUR.asn1.DERInteger(i);
} else {
if (typeof i === "string" && i.indexOf("BEGIN ") != -1 && i.indexOf("CERTIFICATE")) {
var g = new X509();
g.readCertPEM(i);
var h = g.getSerialNumberHex();
this.asn1CertSN = new KJUR.asn1.DERInteger({ hex: h });
}
}
};
this.oid = "2.5.29.35";
if (f !== void 0) {
if (f.kid !== void 0) {
this.setKIDByParam(f.kid);
}
if (f.issuer !== void 0) {
this.setCertIssuerByParam(f.issuer);
}
if (f.sn !== void 0) {
this.setCertSNByParam(f.sn);
}
if (f.issuersn !== void 0 && typeof f.issuersn === "string" && f.issuersn.indexOf("BEGIN ") != -1 && f.issuersn.indexOf("CERTIFICATE")) {
this.setCertSNByParam(f.issuersn);
this.setCertIssuerByParam(f.issuersn);
}
}
};
extendClass(KJUR.asn1.x509.AuthorityKeyIdentifier, KJUR.asn1.x509.Extension);
KJUR.asn1.x509.SubjectKeyIdentifier = function(d) {
KJUR.asn1.x509.SubjectKeyIdentifier.superclass.constructor.call(this, d);
var b = KJUR, a = b.asn1, c = a.DEROctetString;
this.asn1KID = null;
this.getExtnValueHex = function() {
this.asn1ExtnValue = this.asn1KID;
return this.asn1ExtnValue.tohex();
};
this.setKIDByParam = function(g) {
if (g.str !== void 0 || g.hex !== void 0) {
this.asn1KID = new c(g);
} else {
if (typeof g === "object" && KJUR.crypto.Util.isKey(g) || typeof g === "string" && g.indexOf("BEGIN") != -1) {
var f = g;
if (typeof g === "string") {
f = KEYUTIL.getKey(g);
}
var e2 = KEYUTIL.getKeyID(f);
this.asn1KID = new KJUR.asn1.DEROctetString({ hex: e2 });
}
}
};
this.oid = "2.5.29.14";
if (d !== void 0) {
if (d.kid !== void 0) {
this.setKIDByParam(d.kid);
}
}
};
extendClass(KJUR.asn1.x509.SubjectKeyIdentifier, KJUR.asn1.x509.Extension);
KJUR.asn1.x509.AuthorityInfoAccess = function(a) {
KJUR.asn1.x509.AuthorityInfoAccess.superclass.constructor.call(this, a);
this.setAccessDescriptionArray = function(k) {
var d = new Array(), b = KJUR, g = b.asn1, c = g.DERSequence, j = g.DERObjectIdentifier, l = g.x509.GeneralName;
for (var f = 0; f < k.length; f++) {
var e2;
var h = k[f];
if (h.ocsp !== void 0) {
e2 = new c({ array: [new j({ oid: "1.3.6.1.5.5.7.48.1" }), new l({ uri: h.ocsp })] });
} else {
if (h.caissuer !== void 0) {
e2 = new c({ array: [new j({ oid: "1.3.6.1.5.5.7.48.2" }), new l({ uri: h.caissuer })] });
} else {
throw new Error("unknown AccessMethod parameter: " + JSON.stringify(h));
}
}
d.push(e2);
}
this.asn1ExtnValue = new c({ array: d });
};
this.getExtnValueHex = function() {
return this.asn1ExtnValue.tohex();
};
this.oid = "1.3.6.1.5.5.7.1.1";
if (a !== void 0) {
if (a.array !== void 0) {
this.setAccessDescriptionArray(a.array);
}
}
};
extendClass(KJUR.asn1.x509.AuthorityInfoAccess, KJUR.asn1.x509.Extension);
KJUR.asn1.x509.SubjectAltName = function(a) {
KJUR.asn1.x509.SubjectAltName.superclass.constructor.call(this, a);
this.setNameArray = function(b) {
this.asn1ExtnValue = new KJUR.asn1.x509.GeneralNames(b);
};
this.getExtnValueHex = function() {
return this.asn1ExtnValue.tohex();
};
this.oid = "2.5.29.17";
if (a !== void 0) {
if (a.array !== void 0) {
this.setNameArray(a.array);
}
}
};
extendClass(KJUR.asn1.x509.SubjectAltName, KJUR.asn1.x509.Extension);
KJUR.asn1.x509.IssuerAltName = function(a) {
KJUR.asn1.x509.IssuerAltName.superclass.constructor.call(this, a);
this.setNameArray = function(b) {
this.asn1ExtnValue = new KJUR.asn1.x509.GeneralNames(b);
};
this.getExtnValueHex = function() {
return this.asn1ExtnValue.tohex();
};
this.oid = "2.5.29.18";
if (a !== void 0) {
if (a.array !== void 0) {
this.setNameArray(a.array);
}
}
};
extendClass(KJUR.asn1.x509.IssuerAltName, KJUR.asn1.x509.Extension);
KJUR.asn1.x509.SubjectDirectoryAttributes = function(e2) {
KJUR.asn1.x509.SubjectDirectoryAttributes.superclass.constructor.call(this, e2);
var c = KJUR.asn1, a = c.DERSequence, b = c.ASN1Util.newObject, d = c.x509.OID.name2oid;
this.params = null;
this.getExtnValueHex = function() {
var f = [];
for (var j = 0; j < this.params.array.length; j++) {
var l = this.params.array[j];
if (l.attr != void 0 && l.array != void 0) {
var k = { seq: [{ oid: l.attr }, { set: l.array }] };
f.push(b(k));
continue;
}
var h = { seq: [{ oid: "1.2.3.4" }, { set: [{ utf8str: "DE" }] }] };
if (l.attr == "dateOfBirth") {
h.seq[0].oid = d(l.attr);
h.seq[1].set[0] = { gentime: l.str };
} else {
if (l.attr == "placeOfBirth") {
h.seq[0].oid = d(l.attr);
h.seq[1].set[0] = { utf8str: l.str };
} else {
if (l.attr == "gender") {
h.seq[0].oid = d(l.attr);
h.seq[1].set[0] = { prnstr: l.str };
} else {
if (l.attr == "countryOfCitizenship") {
h.seq[0].oid = d(l.attr);
h.seq[1].set[0] = { prnstr: l.str };
} else {
if (l.attr == "countryOfResidence") {
h.seq[0].oid = d(l.attr);
h.seq[1].set[0] = { prnstr: l.str };
} else {
throw new Error("unsupported attribute: " + l.attr);
}
}
}
}
}
f.push(new b(h));
}
var g = new a({ array: f });
this.asn1ExtnValue = g;
return this.asn1ExtnValue.tohex();
};
this.oid = "2.5.29.9";
if (e2 !== void 0) {
this.params = e2;
}
};
extendClass(KJUR.asn1.x509.SubjectDirectoryAttributes, KJUR.asn1.x509.Extension);
KJUR.asn1.x509.PrivateExtension = function(f) {
KJUR.asn1.x509.PrivateExtension.superclass.constructor.call(this, f);
var c = KJUR, e2 = c.lang.String.isHex, b = c.asn1, d = b.x509.OID.name2oid, a = b.ASN1Util.newObject;
this.params = null;
this.setByParam = function(g) {
this.oid = d(g.extname);
this.params = g;
};
this.getExtnValueHex = function() {
if (this.params.extname == void 0 || this.params.extn == void 0) {
throw new Error("extname or extnhex not specified");
}
var h = this.params.extn;
if (typeof h == "string" && e2(h)) {
return h;
} else {
if (typeof h == "object") {
try {
return a(h).tohex();
} catch (g) {
}
}
}
throw new Error("unsupported extn value");
};
if (f != void 0) {
this.setByParam(f);
}
};
extendClass(KJUR.asn1.x509.PrivateExtension, KJUR.asn1.x509.Extension);
KJUR.asn1.x509.CRL = function(g) {
KJUR.asn1.x509.CRL.superclass.constructor.call(this);
var c = KJUR, b = c.asn1, a = b.DERSequence, e2 = b.DERBitString, f = b.x509, d = f.AlgorithmIdentifier, h = f.TBSCertList;
this.params = void 0;
this.setByParam = function(i) {
this.params = i;
};
this.sign = function() {
var j = new h(this.params).tohex();
var k = new KJUR.crypto.Signature({ alg: this.params.sigalg });
k.init(this.params.cakey);
k.updateHex(j);
var i = k.sign();
this.params.sighex = i;
};
this.getPEM = function() {
return hextopem(this.tohex(), "X509 CRL");
};
this.tohex = function() {
var k = this.params;
if (k.tbsobj == void 0) {
k.tbsobj = new h(k);
}
if (k.sighex == void 0 && k.cakey != void 0) {
this.sign();
}
if (k.sighex == void 0) {
throw new Error("sighex or cakey parameter not defined");
}
var i = [];
i.push(k.tbsobj);
i.push(new d({ name: k.sigalg }));
i.push(new e2({ hex: "00" + k.sighex }));
var j = new a({ array: i });
return j.tohex();
};
this.getEncodedHex = function() {
return this.tohex();
};
if (g != void 0) {
this.params = g;
}
};
extendClass(KJUR.asn1.x509.CRL, KJUR.asn1.ASN1Object);
KJUR.asn1.x509.TBSCertList = function(f) {
KJUR.asn1.x509.TBSCertList.superclass.constructor.call(this);
var b = KJUR, i = b.asn1, h = i.DERInteger, g = i.DERSequence, c = i.DERTaggedObject, k = i.DERObjectIdentifier, d = i.x509, l = d.AlgorithmIdentifier, e2 = d.Time, j = d.Extensions, a = d.X500Name;
this.params = null;
this.setByParam = function(m) {
this.params = m;
};
this.getRevCertSequence = function() {
var m = [];
var n2 = this.params.revcert;
for (var o2 = 0; o2 < n2.length; o2++) {
var p = [new h(n2[o2].sn), new e2(n2[o2].date)];
if (n2[o2].ext != void 0) {
p.push(new j(n2[o2].ext));
}
m.push(new g({ array: p }));
}
return new g({ array: m });
};
this.tohex = function() {
var n2 = [];
var r2 = this.params;
if (r2.version != void 0) {
var m = r2.version - 1;
var p = new h({ "int": m });
n2.push(p);
}
n2.push(new l({ name: r2.sigalg }));
n2.push(new a(r2.issuer));
n2.push(new e2(r2.thisupdate));
if (r2.nextupdate != void 0) {
n2.push(new e2(r2.nextupdate));
}
if (r2.revcert != void 0) {
n2.push(this.getRevCertSequence());
}
if (r2.ext != void 0) {
var q = new j(r2.ext);
n2.push(new c({ tag: "a0", explicit: true, obj: q }));
}
var o2 = new g({ array: n2 });
return o2.tohex();
};
this.getEncodedHex = function() {
return this.tohex();
};
if (f !== void 0) {
this.setByParam(f);
}
};
extendClass(KJUR.asn1.x509.TBSCertList, KJUR.asn1.ASN1Object);
KJUR.asn1.x509.CRLEntry = function(e2) {
KJUR.asn1.x509.CRLEntry.superclass.constructor.call(this);
var d = null, c = null, b = KJUR, a = b.asn1;
this.setCertSerial = function(f) {
this.sn = new a.DERInteger(f);
};
this.setRevocationDate = function(f) {
this.time = new a.x509.Time(f);
};
this.tohex = function() {
var f = new a.DERSequence({ array: [this.sn, this.time] });
this.TLV = f.tohex();
return this.TLV;
};
this.getEncodedHex = function() {
return this.tohex();
};
if (e2 !== void 0) {
if (e2.time !== void 0) {
this.setRevocationDate(e2.time);
}
if (e2.sn !== void 0) {
this.setCertSerial(e2.sn);
}
}
};
extendClass(KJUR.asn1.x509.CRLEntry, KJUR.asn1.ASN1Object);
KJUR.asn1.x509.CRLNumber = function(a) {
KJUR.asn1.x509.CRLNumber.superclass.constructor.call(this, a);
this.params = void 0;
this.getExtnValueHex = function() {
this.asn1ExtnValue = new KJUR.asn1.DERInteger(this.params.num);
return this.asn1ExtnValue.tohex();
};
this.oid = "2.5.29.20";
if (a != void 0) {
this.params = a;
}
};
extendClass(KJUR.asn1.x509.CRLNumber, KJUR.asn1.x509.Extension);
KJUR.asn1.x509.CRLReason = function(a) {
KJUR.asn1.x509.CRLReason.superclass.constructor.call(this, a);
this.params = void 0;
this.getExtnValueHex = function() {
this.asn1ExtnValue = new KJUR.asn1.DEREnumerated(this.params.code);
return this.asn1ExtnValue.tohex();
};
this.oid = "2.5.29.21";
if (a != void 0) {
this.params = a;
}
};
extendClass(KJUR.asn1.x509.CRLReason, KJUR.asn1.x509.Extension);
KJUR.asn1.x509.OCSPNonce = function(a) {
KJUR.asn1.x509.OCSPNonce.superclass.constructor.call(this, a);
this.params = void 0;
this.getExtnValueHex = function() {
this.asn1ExtnValue = new KJUR.asn1.DEROctetString(this.params);
return this.asn1ExtnValue.tohex();
};
this.oid = "1.3.6.1.5.5.7.48.1.2";
if (a != void 0) {
this.params = a;
}
};
extendClass(KJUR.asn1.x509.OCSPNonce, KJUR.asn1.x509.Extension);
KJUR.asn1.x509.OCSPNoCheck = function(a) {
KJUR.asn1.x509.OCSPNoCheck.superclass.constructor.call(this, a);
this.params = void 0;
this.getExtnValueHex = function() {
this.asn1ExtnValue = new KJUR.asn1.DERNull();
return this.asn1ExtnValue.tohex();
};
this.oid = "1.3.6.1.5.5.7.48.1.5";
if (a != void 0) {
this.params = a;
}
};
extendClass(KJUR.asn1.x509.OCSPNoCheck, KJUR.asn1.x509.Extension);
KJUR.asn1.x509.AdobeTimeStamp = function(g) {
KJUR.asn1.x509.AdobeTimeStamp.superclass.constructor.call(this, g);
var c = KJUR, b = c.asn1, f = b.DERInteger, d = b.DERBoolean, a = b.DERSequence, e2 = b.x509.GeneralName;
this.params = null;
this.getExtnValueHex = function() {
var i = this.params;
var h = [new f(1)];
h.push(new e2({ uri: i.uri }));
if (i.reqauth != void 0) {
h.push(new d(i.reqauth));
}
this.asn1ExtnValue = new a({ array: h });
return this.asn1ExtnValue.tohex();
};
this.oid = "1.2.840.113583.1.1.9.1";
if (g !== void 0) {
this.setByParam(g);
}
};
extendClass(KJUR.asn1.x509.AdobeTimeStamp, KJUR.asn1.x509.Extension);
KJUR.asn1.x509.X500Name = function(f) {
KJUR.asn1.x509.X500Name.superclass.constructor.call(this);
this.asn1Array = [];
this.paramArray = [];
this.sRule = "utf8";
var c = KJUR, b = c.asn1, e2 = b.x509, d = e2.RDN, a = pemtohex;
this.setByString = function(g, l) {
if (l !== void 0) {
this.sRule = l;
}
var k = g.split("/");
k.shift();
var j = [];
for (var m = 0; m < k.length; m++) {
if (k[m].match(/^[^=]+=.+$/)) {
j.push(k[m]);
} else {
var h = j.length - 1;
j[h] = j[h] + "/" + k[m];
}
}
for (var m = 0; m < j.length; m++) {
this.asn1Array.push(new d({ str: j[m], rule: this.sRule }));
}
};
this.setByLdapString = function(g, h) {
if (h !== void 0) {
this.sRule = h;
}
var i = e2.X500Name.ldapToCompat(g);
this.setByString(i, h);
};
this.setByObject = function(j, i) {
if (i !== void 0) {
this.sRule = i;
}
for (var g in j) {
if (j.hasOwnProperty(g)) {
var h = new d({ str: g + "=" + j[g], rule: this.sRule });
this.asn1Array ? this.asn1Array.push(h) : this.asn1Array = [h];
}
}
};
this.setByParam = function(h) {
if (h.rule !== void 0) {
this.sRule = h.rule;
}
if (h.array !== void 0) {
this.paramArray = h.array;
} else {
if (h.str !== void 0) {
this.setByString(h.str);
} else {
if (h.ldapstr !== void 0) {
this.setByLdapString(h.ldapstr);
} else {
if (h.hex !== void 0) {
this.hTLV = h.hex;
} else {
if (h.certissuer !== void 0) {
var g = new X509();
g.readCertPEM(h.certissuer);
this.hTLV = g.getIssuerHex();
} else {
if (h.certsubject !== void 0) {
var g = new X509();
g.readCertPEM(h.certsubject);
this.hTLV = g.getSubjectHex();
} else {
if (typeof h === "object" && h.certsubject === void 0 && h.certissuer === void 0) {
this.setByObject(h);
}
}
}
}
}
}
}
};
this.tohex = function() {
if (typeof this.hTLV == "string") {
return this.hTLV;
}
if (this.asn1Array.length == 0 && this.paramArray.length > 0) {
for (var g = 0; g < this.paramArray.length; g++) {
var k = { array: this.paramArray[g] };
if (this.sRule != "utf8") {
k.rule = this.sRule;
}
var h = new d(k);
this.asn1Array.push(h);
}
}
var j = new b.DERSequence({ array: this.asn1Array });
this.hTLV = j.tohex();
return this.hTLV;
};
this.getEncodedHex = function() {
return this.tohex();
};
if (f !== void 0) {
this.setByParam(f);
}
};
extendClass(KJUR.asn1.x509.X500Name, KJUR.asn1.ASN1Object);
KJUR.asn1.x509.X500Name.compatToLDAP = function(d) {
if (d.substr(0, 1) !== "/") {
throw "malformed input";
}
var b = "";
d = d.substr(1);
var c = d.split("/");
c.reverse();
c = c.map(function(a) {
return a.replace(/,/, "\\,");
});
return c.join(",");
};
KJUR.asn1.x509.X500Name.onelineToLDAP = function(a) {
return KJUR.asn1.x509.X500Name.compatToLDAP(a);
};
KJUR.asn1.x509.X500Name.ldapToCompat = function(g) {
var c = g.split(",");
var e2 = false;
var b = [];
for (var f = 0; c.length > 0; f++) {
var h = c.shift();
if (e2 === true) {
var d = b.pop();
var j = (d + "," + h).replace(/\\,/g, ",");
b.push(j);
e2 = false;
} else {
b.push(h);
}
if (h.substr(-1, 1) === "\\") {
e2 = true;
}
}
b = b.map(function(a) {
return a.replace("/", "\\/");
});
b.reverse();
return "/" + b.join("/");
};
KJUR.asn1.x509.X500Name.ldapToOneline = function(a) {
return KJUR.asn1.x509.X500Name.ldapToCompat(a);
};
KJUR.asn1.x509.RDN = function(b) {
KJUR.asn1.x509.RDN.superclass.constructor.call(this);
this.asn1Array = [];
this.paramArray = [];
this.sRule = "utf8";
var a = KJUR.asn1.x509.AttributeTypeAndValue;
this.setByParam = function(c) {
if (c.rule !== void 0) {
this.sRule = c.rule;
}
if (c.str !== void 0) {
this.addByMultiValuedString(c.str);
}
if (c.array !== void 0) {
this.paramArray = c.array;
}
};
this.addByString = function(c) {
this.asn1Array.push(new KJUR.asn1.x509.AttributeTypeAndValue({ str: c, rule: this.sRule }));
};
this.addByMultiValuedString = function(e2) {
var c = KJUR.asn1.x509.RDN.parseString(e2);
for (var d = 0; d < c.length; d++) {
this.addByString(c[d]);
}
};
this.tohex = function() {
if (this.asn1Array.length == 0 && this.paramArray.length > 0) {
for (var d = 0; d < this.paramArray.length; d++) {
var f = this.paramArray[d];
if (f.rule !== void 0 && this.sRule != "utf8") {
f.rule = this.sRule;
}
var c = new a(f);
this.asn1Array.push(c);
}
}
var e2 = new KJUR.asn1.DERSet({ array: this.asn1Array });
this.TLV = e2.tohex();
return this.TLV;
};
this.getEncodedHex = function() {
return this.tohex();
};
if (b !== void 0) {
this.setByParam(b);
}
};
extendClass(KJUR.asn1.x509.RDN, KJUR.asn1.ASN1Object);
KJUR.asn1.x509.RDN.parseString = function(m) {
var j = m.split(/\+/);
var h = false;
var c = [];
for (var g = 0; j.length > 0; g++) {
var k = j.shift();
if (h === true) {
var f = c.pop();
var d = (f + "+" + k).replace(/\\\+/g, "+");
c.push(d);
h = false;
} else {
c.push(k);
}
if (k.substr(-1, 1) === "\\") {
h = true;
}
}
var l = false;
var b = [];
for (var g = 0; c.length > 0; g++) {
var k = c.shift();
if (l === true) {
var e2 = b.pop();
if (k.match(/"$/)) {
var d = (e2 + "+" + k).replace(/^([^=]+)="(.*)"$/, "$1=$2");
b.push(d);
l = false;
} else {
b.push(e2 + "+" + k);
}
} else {
b.push(k);
}
if (k.match(/^[^=]+="/)) {
l = true;
}
}
return b;
};
KJUR.asn1.x509.AttributeTypeAndValue = function(c) {
KJUR.asn1.x509.AttributeTypeAndValue.superclass.constructor.call(this);
this.sRule = "utf8";
this.sType = null;
this.sValue = null;
this.dsType = null;
var a = KJUR, g = a.asn1, d = g.DERSequence, l = g.DERUTF8String, i = g.DERPrintableString, h = g.DERTeletexString, b = g.DERIA5String, e2 = g.DERVisibleString, k = g.DERBMPString, f = a.lang.String.isMail, j = a.lang.String.isPrintable;
this.setByParam = function(o2) {
if (o2.rule !== void 0) {
this.sRule = o2.rule;
}
if (o2.ds !== void 0) {
this.dsType = o2.ds;
}
if (o2.value === void 0 && o2.str !== void 0) {
var n2 = o2.str;
var m = n2.match(/^([^=]+)=(.+)$/);
if (m) {
this.sType = m[1];
this.sValue = m[2];
} else {
throw new Error("malformed attrTypeAndValueStr: " + attrTypeAndValueStr);
}
} else {
this.sType = o2.type;
this.sValue = o2.value;
}
};
this.setByString = function(n2, o2) {
if (o2 !== void 0) {
this.sRule = o2;
}
var m = n2.match(/^([^=]+)=(.+)$/);
if (m) {
this.setByAttrTypeAndValueStr(m[1], m[2]);
} else {
throw new Error("malformed attrTypeAndValueStr: " + attrTypeAndValueStr);
}
};
this._getDsType = function() {
var o2 = this.sType;
var n2 = this.sValue;
var m = this.sRule;
if (m === "prn") {
if (o2 == "CN" && f(n2)) {
return "ia5";
}
if (j(n2)) {
return "prn";
}
return "utf8";
} else {
if (m === "utf8") {
if (o2 == "CN" && f(n2)) {
return "ia5";
}
if (o2 == "C") {
return "prn";
}
return "utf8";
}
}
return "utf8";
};
this.setByAttrTypeAndValueStr = function(o2, n2, m) {
if (m !== void 0) {
this.sRule = m;
}
this.sType = o2;
this.sValue = n2;
};
this.getValueObj = function(n2, m) {
if (n2 == "utf8") {
return new l({ str: m });
}
if (n2 == "prn") {
return new i({ str: m });
}
if (n2 == "tel") {
return new h({ str: m });
}
if (n2 == "ia5") {
return new b({ str: m });
}
if (n2 == "vis") {
return new e2({ str: m });
}
if (n2 == "bmp") {
return new k({ str: m });
}
throw new Error("unsupported directory string type: type=" + n2 + " value=" + m);
};
this.tohex = function() {
if (this.dsType == null) {
this.dsType = this._getDsType();
}
var n2 = KJUR.asn1.x509.OID.atype2obj(this.sType);
var m = this.getValueObj(this.dsType, this.sValue);
var p = new d({ array: [n2, m] });
this.TLV = p.tohex();
return this.TLV;
};
this.getEncodedHex = function() {
return this.tohex();
};
if (c !== void 0) {
this.setByParam(c);
}
};
extendClass(KJUR.asn1.x509.AttributeTypeAndValue, KJUR.asn1.ASN1Object);
KJUR.asn1.x509.SubjectPublicKeyInfo = function(f) {
KJUR.asn1.x509.SubjectPublicKeyInfo.superclass.constructor.call(this);
var l = null, k = null, a = KJUR, j = a.asn1, i = j.DERInteger, b = j.DERBitString, m = j.DERObjectIdentifier, e2 = j.DERSequence, h = j.ASN1Util.newObject, d = j.x509, o2 = d.AlgorithmIdentifier, g = a.crypto, n2 = g.ECDSA, c = g.DSA;
this.getASN1Object = function() {
if (this.asn1AlgId == null || this.asn1SubjPKey == null) {
throw "algId and/or subjPubKey not set";
}
var p = new e2({ array: [this.asn1AlgId, this.asn1SubjPKey] });
return p;
};
this.tohex = function() {
var p = this.getASN1Object();
this.hTLV = p.tohex();
return this.hTLV;
};
this.getEncodedHex = function() {
return this.tohex();
};
this.setPubKey = function(q) {
try {
if (q instanceof RSAKey) {
var u = h({ seq: [{ "int": { bigint: q.n } }, { "int": { "int": q.e } }] });
var s = u.tohex();
this.asn1AlgId = new o2({ name: "rsaEncryption" });
this.asn1SubjPKey = new b({ hex: "00" + s });
}
} catch (p) {
}
try {
if (q instanceof KJUR.crypto.ECDSA) {
var r2 = new m({ name: q.curveName });
this.asn1AlgId = new o2({ name: "ecPublicKey", asn1params: r2 });
this.asn1SubjPKey = new b({ hex: "00" + q.pubKeyHex });
}
} catch (p) {
}
try {
if (q instanceof KJUR.crypto.DSA) {
var r2 = new h({ seq: [{ "int": { bigint: q.p } }, { "int": { bigint: q.q } }, { "int": { bigint: q.g } }] });
this.asn1AlgId = new o2({ name: "dsa", asn1params: r2 });
var t3 = new i({ bigint: q.y });
this.asn1SubjPKey = new b({ hex: "00" + t3.tohex() });
}
} catch (p) {
}
};
if (f !== void 0) {
this.setPubKey(f);
}
};
extendClass(KJUR.asn1.x509.SubjectPublicKeyInfo, KJUR.asn1.ASN1Object);
KJUR.asn1.x509.Time = function(f) {
KJUR.asn1.x509.Time.superclass.constructor.call(this);
var e2 = null, a = null, d = KJUR, c = d.asn1, b = c.DERUTCTime, g = c.DERGeneralizedTime;
this.params = null;
this.type = null;
this.setTimeParams = function(h) {
this.timeParams = h;
};
this.setByParam = function(h) {
this.params = h;
};
this.getType = function(h) {
if (h.match(/^[0-9]{12}Z$/)) {
return "utc";
}
if (h.match(/^[0-9]{14}Z$/)) {
return "gen";
}
if (h.match(/^[0-9]{12}\.[0-9]+Z$/)) {
return "utc";
}
if (h.match(/^[0-9]{14}\.[0-9]+Z$/)) {
return "gen";
}
return null;
};
this.tohex = function() {
var i = this.params;
var h = null;
if (typeof i == "string") {
i = { str: i };
}
if (i != null && i.str && (i.type == null || i.type == void 0)) {
i.type = this.getType(i.str);
}
if (i != null && i.str) {
if (i.type == "utc") {
h = new b(i.str);
}
if (i.type == "gen") {
h = new g(i.str);
}
} else {
if (this.type == "gen") {
h = new g();
} else {
h = new b();
}
}
if (h == null) {
throw new Error("wrong setting for Time");
}
this.TLV = h.tohex();
return this.TLV;
};
this.getEncodedHex = function() {
return this.tohex();
};
if (f != void 0) {
this.setByParam(f);
}
};
KJUR.asn1.x509.Time_bak = function(f) {
KJUR.asn1.x509.Time_bak.superclass.constructor.call(this);
var e2 = null, a = null, d = KJUR, c = d.asn1, b = c.DERUTCTime, g = c.DERGeneralizedTime;
this.setTimeParams = function(h) {
this.timeParams = h;
};
this.tohex = function() {
var h = null;
if (this.timeParams != null) {
if (this.type == "utc") {
h = new b(this.timeParams);
} else {
h = new g(this.timeParams);
}
} else {
if (this.type == "utc") {
h = new b();
} else {
h = new g();
}
}
this.TLV = h.tohex();
return this.TLV;
};
this.getEncodedHex = function() {
return this.tohex();
};
this.type = "utc";
if (f !== void 0) {
if (f.type !== void 0) {
this.type = f.type;
} else {
if (f.str !== void 0) {
if (f.str.match(/^[0-9]{12}Z$/)) {
this.type = "utc";
}
if (f.str.match(/^[0-9]{14}Z$/)) {
this.type = "gen";
}
}
}
this.timeParams = f;
}
};
extendClass(KJUR.asn1.x509.Time, KJUR.asn1.ASN1Object);
KJUR.asn1.x509.AlgorithmIdentifier = function(e2) {
KJUR.asn1.x509.AlgorithmIdentifier.superclass.constructor.call(this);
this.nameAlg = null;
this.asn1Alg = null;
this.asn1Params = null;
this.paramEmpty = false;
var b = KJUR, a = b.asn1, c = a.x509.AlgorithmIdentifier.PSSNAME2ASN1TLV;
this.tohex = function() {
if (this.nameAlg === null && this.asn1Alg === null) {
throw new Error("algorithm not specified");
}
if (this.nameAlg !== null) {
var f = null;
for (var h in c) {
if (h === this.nameAlg) {
f = c[h];
}
}
if (f !== null) {
this.hTLV = f;
return this.hTLV;
}
}
if (this.nameAlg !== null && this.asn1Alg === null) {
this.asn1Alg = a.x509.OID.name2obj(this.nameAlg);
}
var g = [this.asn1Alg];
if (this.asn1Params !== null) {
g.push(this.asn1Params);
}
var i = new a.DERSequence({ array: g });
this.hTLV = i.tohex();
return this.hTLV;
};
this.getEncodedHex = function() {
return this.tohex();
};
if (e2 !== void 0) {
if (e2.name !== void 0) {
this.nameAlg = e2.name;
}
if (e2.asn1params !== void 0) {
this.asn1Params = e2.asn1params;
}
if (e2.paramempty !== void 0) {
this.paramEmpty = e2.paramempty;
}
}
if (this.asn1Params === null && this.paramEmpty === false && this.nameAlg !== null) {
if (this.nameAlg.name !== void 0) {
this.nameAlg = this.nameAlg.name;
}
var d = this.nameAlg.toLowerCase();
if (d.substr(-7, 7) !== "withdsa" && d.substr(-9, 9) !== "withecdsa") {
this.asn1Params = new a.DERNull();
}
}
};
extendClass(KJUR.asn1.x509.AlgorithmIdentifier, KJUR.asn1.ASN1Object);
KJUR.asn1.x509.AlgorithmIdentifier.PSSNAME2ASN1TLV = { SHAwithRSAandMGF1: "300d06092a864886f70d01010a3000", SHA256withRSAandMGF1: "303d06092a864886f70d01010a3030a00d300b0609608648016503040201a11a301806092a864886f70d010108300b0609608648016503040201a203020120", SHA384withRSAandMGF1: "303d06092a864886f70d01010a3030a00d300b0609608648016503040202a11a301806092a864886f70d010108300b0609608648016503040202a203020130", SHA512withRSAandMGF1: "303d06092a864886f70d01010a3030a00d300b0609608648016503040203a11a301806092a864886f70d010108300b0609608648016503040203a203020140" };
KJUR.asn1.x509.GeneralName = function(f) {
KJUR.asn1.x509.GeneralName.superclass.constructor.call(this);
var l = { rfc822: "81", dns: "82", dn: "a4", uri: "86", ip: "87", otherName: "a0" }, b = KJUR, h = b.asn1, d = h.x509, a = d.X500Name, g = d.OtherName, e2 = h.DERIA5String, i = h.DERPrintableString, k = h.DEROctetString, c = h.DERTaggedObject, m = h.ASN1Object, j = Error;
this.params = null;
this.setByParam = function(n2) {
this.params = n2;
};
this.tohex = function() {
var p = this.params;
var A, y, q;
var y = false;
if (p.other !== void 0) {
A = "a0", q = new g(p.other);
} else {
if (p.rfc822 !== void 0) {
A = "81";
q = new e2({ str: p.rfc822 });
} else {
if (p.dns !== void 0) {
A = "82";
q = new e2({ str: p.dns });
} else {
if (p.dn !== void 0) {
A = "a4";
y = true;
if (typeof p.dn === "string") {
q = new a({ str: p.dn });
} else {
if (p.dn instanceof KJUR.asn1.x509.X500Name) {
q = p.dn;
} else {
q = new a(p.dn);
}
}
} else {
if (p.ldapdn !== void 0) {
A = "a4";
y = true;
q = new a({ ldapstr: p.ldapdn });
} else {
if (p.certissuer !== void 0 || p.certsubj !== void 0) {
A = "a4";
y = true;
var n2, o2;
var z2 = null;
if (p.certsubj !== void 0) {
n2 = false;
o2 = p.certsubj;
} else {
n2 = true;
o2 = p.certissuer;
}
if (o2.match(/^[0-9A-Fa-f]+$/)) {
z2 == o2;
}
if (o2.indexOf("-----BEGIN ") != -1) {
z2 = pemtohex(o2);
}
if (z2 == null) {
throw new Error("certsubj/certissuer not cert");
}
var w = new X509();
w.hex = z2;
var s;
if (n2) {
s = w.getIssuerHex();
} else {
s = w.getSubjectHex();
}
q = new m();
q.hTLV = s;
} else {
if (p.uri !== void 0) {
A = "86";
q = new e2({ str: p.uri });
} else {
if (p.ip !== void 0) {
A = "87";
var v;
var t3 = p.ip;
try {
if (t3.match(/^[0-9a-f]+$/)) {
var r2 = t3.length;
if (r2 == 8 || r2 == 16 || r2 == 32 || r2 == 64) {
v = t3;
} else {
throw "err";
}
} else {
v = iptohex(t3);
}
} catch (u) {
throw new j("malformed IP address: " + p.ip + ":" + u.message);
}
q = new k({ hex: v });
} else {
throw new j("improper params");
}
}
}
}
}
}
}
}
var B = new c({ tag: A, explicit: y, obj: q });
return B.tohex();
};
this.getEncodedHex = function() {
return this.tohex();
};
if (f !== void 0) {
this.setByParam(f);
}
};
extendClass(KJUR.asn1.x509.GeneralName, KJUR.asn1.ASN1Object);
KJUR.asn1.x509.GeneralNames = function(d) {
KJUR.asn1.x509.GeneralNames.superclass.constructor.call(this);
var a = null, c = KJUR, b = c.asn1;
this.setByParamArray = function(g) {
for (var e2 = 0; e2 < g.length; e2++) {
var f = new b.x509.GeneralName(g[e2]);
this.asn1Array.push(f);
}
};
this.tohex = function() {
var e2 = new b.DERSequence({ array: this.asn1Array });
return e2.tohex();
};
this.getEncodedHex = function() {
return this.tohex();
};
this.asn1Array = new Array();
if (typeof d != "undefined") {
this.setByParamArray(d);
}
};
extendClass(KJUR.asn1.x509.GeneralNames, KJUR.asn1.ASN1Object);
KJUR.asn1.x509.OtherName = function(g) {
KJUR.asn1.x509.OtherName.superclass.constructor.call(this);
var f = null, e2 = null, d = KJUR, c = d.asn1, h = c.DERObjectIdentifier, a = c.DERSequence, b = c.ASN1Util.newObject;
this.params = null;
this.setByParam = function(i) {
this.params = i;
};
this.tohex = function() {
var k = this.params;
if (k.oid == void 0 || k.value == void 0) {
throw new Error("oid or value not specified");
}
var l = new h({ oid: k.oid });
var i = b({ tag: { tag: "a0", explicit: true, obj: k.value } });
var j = new a({ array: [l, i] });
return j.tohex();
};
this.getEncodedHex = function() {
return this.tohex();
};
if (g !== void 0) {
this.setByParam(g);
}
};
extendClass(KJUR.asn1.x509.OtherName, KJUR.asn1.ASN1Object);
KJUR.asn1.x509.OID = new function() {
var a = KJUR.asn1.DERObjectIdentifier;
this.name2oidList = { "aes128-CBC": "2.16.840.1.101.3.4.1.2", "aes256-CBC": "2.16.840.1.101.3.4.1.42", sha1: "1.3.14.3.2.26", sha256: "2.16.840.1.101.3.4.2.1", sha384: "2.16.840.1.101.3.4.2.2", sha512: "2.16.840.1.101.3.4.2.3", sha224: "2.16.840.1.101.3.4.2.4", md5: "1.2.840.113549.2.5", md2: "1.3.14.7.2.2.1", ripemd160: "1.3.36.3.2.1", hmacWithSHA1: "1.2.840.113549.2.7", hmacWithSHA224: "1.2.840.113549.2.8", hmacWithSHA256: "1.2.840.113549.2.9", hmacWithSHA384: "1.2.840.113549.2.10", hmacWithSHA512: "1.2.840.113549.2.11", MD2withRSA: "1.2.840.113549.1.1.2", MD4withRSA: "1.2.840.113549.1.1.3", MD5withRSA: "1.2.840.113549.1.1.4", SHA1withRSA: "1.2.840.113549.1.1.5", "pkcs1-MGF": "1.2.840.113549.1.1.8", rsaPSS: "1.2.840.113549.1.1.10", SHA224withRSA: "1.2.840.113549.1.1.14", SHA256withRSA: "1.2.840.113549.1.1.11", SHA384withRSA: "1.2.840.113549.1.1.12", SHA512withRSA: "1.2.840.113549.1.1.13", SHA1withECDSA: "1.2.840.10045.4.1", SHA224withECDSA: "1.2.840.10045.4.3.1", SHA256withECDSA: "1.2.840.10045.4.3.2", SHA384withECDSA: "1.2.840.10045.4.3.3", SHA512withECDSA: "1.2.840.10045.4.3.4", dsa: "1.2.840.10040.4.1", SHA1withDSA: "1.2.840.10040.4.3", SHA224withDSA: "2.16.840.1.101.3.4.3.1", SHA256withDSA: "2.16.840.1.101.3.4.3.2", rsaEncryption: "1.2.840.113549.1.1.1", commonName: "2.5.4.3", countryName: "2.5.4.6", localityName: "2.5.4.7", stateOrProvinceName: "2.5.4.8", streetAddress: "2.5.4.9", organizationName: "2.5.4.10", organizationalUnitName: "2.5.4.11", domainComponent: "0.9.2342.19200300.100.1.25", userId: "0.9.2342.19200300.100.1.1", surname: "2.5.4.4", givenName: "2.5.4.42", title: "2.5.4.12", distinguishedName: "2.5.4.49", emailAddress: "1.2.840.113549.1.9.1", description: "2.5.4.13", businessCategory: "2.5.4.15", postalCode: "2.5.4.17", uniqueIdentifier: "2.5.4.45", organizationIdentifier: "2.5.4.97", jurisdictionOfIncorporationL: "1.3.6.1.4.1.311.60.2.1.1", jurisdictionOfIncorporationSP: "1.3.6.1.4.1.311.60.2.1.2", jurisdictionOfIncorporationC: "1.3.6.1.4.1.311.60.2.1.3", subjectDirectoryAttributes: "2.5.29.9", subjectKeyIdentifier: "2.5.29.14", keyUsage: "2.5.29.15", subjectAltName: "2.5.29.17", issuerAltName: "2.5.29.18", basicConstraints: "2.5.29.19", cRLNumber: "2.5.29.20", cRLReason: "2.5.29.21", nameConstraints: "2.5.29.30", cRLDistributionPoints: "2.5.29.31", certificatePolicies: "2.5.29.32", anyPolicy: "2.5.29.32.0", policyMappings: "2.5.29.33", authorityKeyIdentifier: "2.5.29.35", policyConstraints: "2.5.29.36", extKeyUsage: "2.5.29.37", inhibitAnyPolicy: "2.5.29.54", authorityInfoAccess: "1.3.6.1.5.5.7.1.1", ocsp: "1.3.6.1.5.5.7.48.1", ocspBasic: "1.3.6.1.5.5.7.48.1.1", ocspNonce: "1.3.6.1.5.5.7.48.1.2", ocspNoCheck: "1.3.6.1.5.5.7.48.1.5", caIssuers: "1.3.6.1.5.5.7.48.2", anyExtendedKeyUsage: "2.5.29.37.0", serverAuth: "1.3.6.1.5.5.7.3.1", clientAuth: "1.3.6.1.5.5.7.3.2", codeSigning: "1.3.6.1.5.5.7.3.3", emailProtection: "1.3.6.1.5.5.7.3.4", timeStamping: "1.3.6.1.5.5.7.3.8", ocspSigning: "1.3.6.1.5.5.7.3.9", smtpUTF8Mailbox: "1.3.6.1.5.5.7.8.9", dateOfBirth: "1.3.6.1.5.5.7.9.1", placeOfBirth: "1.3.6.1.5.5.7.9.2", gender: "1.3.6.1.5.5.7.9.3", countryOfCitizenship: "1.3.6.1.5.5.7.9.4", countryOfResidence: "1.3.6.1.5.5.7.9.5", ecPublicKey: "1.2.840.10045.2.1", "P-256": "1.2.840.10045.3.1.7", secp256r1: "1.2.840.10045.3.1.7", secp256k1: "1.3.132.0.10", secp384r1: "1.3.132.0.34", secp521r1: "1.3.132.0.35", pkcs5PBES2: "1.2.840.113549.1.5.13", pkcs5PBKDF2: "1.2.840.113549.1.5.12", "des-EDE3-CBC": "1.2.840.113549.3.7", data: "1.2.840.113549.1.7.1", "signed-data": "1.2.840.113549.1.7.2", "enveloped-data": "1.2.840.113549.1.7.3", "digested-data": "1.2.840.113549.1.7.5", "encrypted-data": "1.2.840.113549.1.7.6", "authenticated-data": "1.2.840.113549.1.9.16.1.2", tstinfo: "1.2.840.113549.1.9.16.1.4", signingCertificate: "1.2.840.113549.1.9.16.2.12", timeStampToken: "1.2.840.113549.1.9.16.2.14", signaturePolicyIdentifier: "1.2.840.113549.1.9.16.2.15", etsArchiveTimeStamp: "1.2.840.113549.1.9.16.2.27", signingCertificateV2: "1.2.840.113549.1.9.16.2.47", etsArchiveTimeStampV2: "1.2.840.113549.1.9.16.2.48", extensionRequest: "1.2.840.113549.1.9.14", contentType: "1.2.840.113549.1.9.3", messageDigest: "1.2.840.113549.1.9.4", signingTime: "1.2.840.113549.1.9.5", counterSignature: "1.2.840.113549.1.9.6", archiveTimeStampV3: "0.4.0.1733.2.4", pdfRevocationInfoArchival: "1.2.840.113583.1.1.8", adobeTimeStamp: "1.2.840.113583.1.1.9.1", smimeMailboxLegacy: "2.23.140.1.5.1.1", smimeMailboxMulti: "2.23.140.1.5.1.2", smimeMailboxStrict: "2.23.140.1.5.1.3", smimeOrganizationLegacy: "2.23.140.1.5.2.1", smimeOrganizationMulti: "2.23.140.1.5.2.2", smimeOrganizationStrict: "2.23.140.1.5.2.3", smimeSponsorLegacy: "2.23.140.1.5.3.1", smimeSponsorMulti: "2.23.140.1.5.3.2", smimeSponsorStrict: "2.23.140.1.5.3.3", smimeIndividualLegacy: "2.23.140.1.5.4.1", smimeIndividualMulti: "2.23.140.1.5.4.2", smimeIndividualStrict: "2.23.140.1.5.4.3" };
this.atype2oidList = { CN: "2.5.4.3", L: "2.5.4.7", ST: "2.5.4.8", O: "2.5.4.10", OU: "2.5.4.11", C: "2.5.4.6", STREET: "2.5.4.9", DC: "0.9.2342.19200300.100.1.25", UID: "0.9.2342.19200300.100.1.1", SN: "2.5.4.4", T: "2.5.4.12", GN: "2.5.4.42", DN: "2.5.4.49", E: "1.2.840.113549.1.9.1", description: "2.5.4.13", businessCategory: "2.5.4.15", postalCode: "2.5.4.17", serialNumber: "2.5.4.5", uniqueIdentifier: "2.5.4.45", organizationIdentifier: "2.5.4.97", jurisdictionOfIncorporationL: "1.3.6.1.4.1.311.60.2.1.1", jurisdictionOfIncorporationSP: "1.3.6.1.4.1.311.60.2.1.2", jurisdictionOfIncorporationC: "1.3.6.1.4.1.311.60.2.1.3" };
this.objCache = {};
this.name2obj = function(b) {
if (typeof this.objCache[b] != "undefined") {
return this.objCache[b];
}
if (typeof this.name2oidList[b] == "undefined") {
throw "Name of ObjectIdentifier not defined: " + b;
}
var c = this.name2oidList[b];
var d = new a({ oid: c });
this.objCache[b] = d;
return d;
};
this.atype2obj = function(b) {
if (this.objCache[b] !== void 0) {
return this.objCache[b];
}
var c;
if (b.match(/^\d+\.\d+\.[0-9.]+$/)) {
c = b;
} else {
if (this.atype2oidList[b] !== void 0) {
c = this.atype2oidList[b];
} else {
if (this.name2oidList[b] !== void 0) {
c = this.name2oidList[b];
} else {
throw new Error("AttributeType name undefined: " + b);
}
}
}
var d = new a({ oid: c });
this.objCache[b] = d;
return d;
};
this.registerOIDs = function(b) {
if (!this.checkOIDs(b)) {
return;
}
for (var c in b) {
this.name2oidList[c] = b[c];
}
};
this.checkOIDs = function(b) {
try {
var d = Object.keys(b);
if (d.length == 0) {
return false;
}
d.map(function(g, e2, h) {
var f = this[g];
if (!f.match(/^[0-2]\.[0-9.]+$/)) {
throw new Error("value is not OID");
}
}, b);
return true;
} catch (c) {
return false;
}
};
}();
KJUR.asn1.x509.OID.oid2name = function(b) {
var c = KJUR.asn1.x509.OID.name2oidList;
for (var a in c) {
if (c[a] == b) {
return a;
}
}
return "";
};
KJUR.asn1.x509.OID.oid2atype = function(b) {
var c = KJUR.asn1.x509.OID.atype2oidList;
for (var a in c) {
if (c[a] == b) {
return a;
}
}
return b;
};
KJUR.asn1.x509.OID.name2oid = function(a) {
if (a.match(/^[0-9.]+$/)) {
return a;
}
var b = KJUR.asn1.x509.OID.name2oidList;
if (b[a] === void 0) {
return "";
}
return b[a];
};
KJUR.asn1.x509.X509Util = {};
KJUR.asn1.x509.X509Util.newCertPEM = function(e2) {
var d = KJUR.asn1.x509, b = d.TBSCertificate, a = d.Certificate;
var c = new a(e2);
return c.getPEM();
};
if (typeof KJUR == "undefined" || !KJUR) {
KJUR = {};
}
if (typeof KJUR.asn1 == "undefined" || !KJUR.asn1) {
KJUR.asn1 = {};
}
if (typeof KJUR.asn1.cms == "undefined" || !KJUR.asn1.cms) {
KJUR.asn1.cms = {};
}
KJUR.asn1.cms.Attribute = function(f) {
var e2 = Error, d = KJUR, c = d.asn1, b = c.DERSequence, a = c.DERSet, g = c.DERObjectIdentifier;
this.params = null;
this.typeOid = null;
this.setByParam = function(h) {
this.params = h;
};
this.getValueArray = function() {
throw new e2("not yet implemented abstract");
};
this.tohex = function() {
var j = new g({ oid: this.typeOid });
var h = new a({ array: this.getValueArray() });
var i = new b({ array: [j, h] });
return i.tohex();
};
this.getEncodedHex = function() {
return this.tohex();
};
};
extendClass(KJUR.asn1.cms.Attribute, KJUR.asn1.ASN1Object);
KJUR.asn1.cms.ContentType = function(c) {
var b = KJUR, a = b.asn1;
a.cms.ContentType.superclass.constructor.call(this);
this.typeOid = "1.2.840.113549.1.9.3";
this.getValueArray = function() {
var d = new a.DERObjectIdentifier(this.params.type);
return [d];
};
if (c != void 0) {
this.setByParam(c);
}
};
extendClass(KJUR.asn1.cms.ContentType, KJUR.asn1.cms.Attribute);
KJUR.asn1.cms.MessageDigest = function(e2) {
var b = KJUR, a = b.asn1, c = a.DEROctetString, d = a.cms;
d.MessageDigest.superclass.constructor.call(this);
this.typeOid = "1.2.840.113549.1.9.4";
this.getValueArray = function() {
var f = new c(this.params);
return [f];
};
if (e2 != void 0) {
this.setByParam(e2);
}
};
extendClass(KJUR.asn1.cms.MessageDigest, KJUR.asn1.cms.Attribute);
KJUR.asn1.cms.SigningTime = function(c) {
var b = KJUR, a = b.asn1;
a.cms.SigningTime.superclass.constructor.call(this);
this.typeOid = "1.2.840.113549.1.9.5";
this.getValueArray = function() {
var d = new a.x509.Time(this.params);
return [d];
};
if (c != void 0) {
this.setByParam(c);
}
};
extendClass(KJUR.asn1.cms.SigningTime, KJUR.asn1.cms.Attribute);
KJUR.asn1.cms.SigningCertificate = function(h) {
var e2 = Error, d = KJUR, c = d.asn1, b = c.DERSequence, g = c.cms, a = g.ESSCertID, f = d.crypto;
g.SigningCertificate.superclass.constructor.call(this);
this.typeOid = "1.2.840.113549.1.9.16.2.12";
this.getValueArray = function() {
if (this.params == null || this.params == void 0 || this.params.array == void 0) {
throw new e2("parameter 'array' not specified");
}
var o2 = this.params.array;
var k = [];
for (var l = 0; l < o2.length; l++) {
var n2 = o2[l];
if (h.hasis == false && (typeof n2 == "string" && (n2.indexOf("-----BEGIN") != -1 || ASN1HEX.isASN1HEX(n2)))) {
n2 = { cert: n2 };
}
if (n2.hasis != false && h.hasis == false) {
n2.hasis = false;
}
k.push(new a(n2));
}
var j = new b({ array: k });
var m = new b({ array: [j] });
return [m];
};
if (h != void 0) {
this.setByParam(h);
}
};
extendClass(KJUR.asn1.cms.SigningCertificate, KJUR.asn1.cms.Attribute);
KJUR.asn1.cms.ESSCertID = function(g) {
KJUR.asn1.cms.ESSCertID.superclass.constructor.call(this);
var d = Error, c = KJUR, b = c.asn1, f = b.DEROctetString, a = b.DERSequence, e2 = b.cms.IssuerSerial;
this.params = null;
this.getCertHash = function(k, h) {
if (k.hash != void 0) {
return k.hash;
}
if (typeof k == "string" && k.indexOf("-----BEGIN") == -1 && !ASN1HEX.isASN1HEX(k)) {
return k;
}
var i;
if (typeof k == "string") {
i = k;
} else {
if (k.cert != void 0) {
i = k.cert;
} else {
throw new d("hash nor cert unspecified");
}
}
var j;
if (i.indexOf("-----BEGIN") != -1) {
j = pemtohex(i);
} else {
j = i;
}
if (typeof k == "string") {
if (k.indexOf("-----BEGIN") != -1) {
j = pemtohex(k);
} else {
if (ASN1HEX.isASN1HEX(k)) {
j = k;
}
}
}
var l;
if (k.alg != void 0) {
l = k.alg;
} else {
if (h != void 0) {
l = h;
} else {
throw new d("hash alg unspecified");
}
}
return c.crypto.Util.hashHex(j, l);
};
this.tohex = function() {
var k = this.params;
var j = this.getCertHash(k, "sha1");
var h = [];
h.push(new f({ hex: j }));
if (typeof k == "string" && k.indexOf("-----BEGIN") != -1 || k.cert != void 0 && k.hasis != false || k.issuer != void 0 && k.serial != void 0) {
h.push(new e2(k));
}
var i = new a({ array: h });
return i.tohex();
};
this.getEncodedHex = function() {
return this.tohex();
};
if (g != void 0) {
this.setByParam(g);
}
};
extendClass(KJUR.asn1.cms.ESSCertID, KJUR.asn1.ASN1Object);
KJUR.asn1.cms.SigningCertificateV2 = function(d) {
var h = Error, a = KJUR, g = a.asn1, e2 = g.DERSequence, b = g.x509, i = g.cms, c = i.ESSCertIDv2, f = a.crypto;
i.SigningCertificateV2.superclass.constructor.call(this);
this.typeOid = "1.2.840.113549.1.9.16.2.47";
this.getValueArray = function() {
if (this.params == null || this.params == void 0 || this.params.array == void 0) {
throw new h("parameter 'array' not specified");
}
var o2 = this.params.array;
var l = [];
for (var m = 0; m < o2.length; m++) {
var n2 = o2[m];
if ((d.alg != void 0 || d.hasis == false) && (typeof n2 == "string" && (n2.indexOf("-----BEGIN") != -1 || ASN1HEX.isASN1HEX(n2)))) {
n2 = { cert: n2 };
}
if (n2.alg == void 0 && d.alg != void 0) {
n2.alg = d.alg;
}
if (n2.hasis != false && d.hasis == false) {
n2.hasis = false;
}
l.push(new c(n2));
}
var k = new e2({ array: l });
var j = new e2({ array: [k] });
return [j];
};
if (d != void 0) {
this.setByParam(d);
}
};
extendClass(KJUR.asn1.cms.SigningCertificateV2, KJUR.asn1.cms.Attribute);
KJUR.asn1.cms.ESSCertIDv2 = function(h) {
KJUR.asn1.cms.ESSCertIDv2.superclass.constructor.call(this);
var d = Error, c = KJUR, b = c.asn1, f = b.DEROctetString, a = b.DERSequence, e2 = b.cms.IssuerSerial, g = b.x509.AlgorithmIdentifier;
this.params = null;
this.tohex = function() {
var l = this.params;
var k = this.getCertHash(l, "sha256");
var i = [];
if (l.alg != void 0 && l.alg != "sha256") {
i.push(new g({ name: l.alg }));
}
i.push(new f({ hex: k }));
if (typeof l == "string" && l.indexOf("-----BEGIN") != -1 || l.cert != void 0 && l.hasis != false || l.issuer != void 0 && l.serial != void 0) {
i.push(new e2(l));
}
var j = new a({ array: i });
return j.tohex();
};
this.getEncodedHex = function() {
return this.tohex();
};
if (h != void 0) {
this.setByParam(h);
}
};
extendClass(KJUR.asn1.cms.ESSCertIDv2, KJUR.asn1.cms.ESSCertID);
KJUR.asn1.cms.IssuerSerial = function(e2) {
var i = Error, c = KJUR, h = c.asn1, g = h.DERInteger, f = h.DERSequence, j = h.cms, d = h.x509, a = d.GeneralNames, b = X509;
j.IssuerSerial.superclass.constructor.call(this);
this.setByParam = function(k) {
this.params = k;
};
this.tohex = function() {
var p = this.params;
var l, r2;
if (typeof p == "string" && p.indexOf("-----BEGIN") != -1 || p.cert != void 0) {
var n2;
if (p.cert != void 0) {
n2 = p.cert;
} else {
n2 = p;
}
var k = new b();
k.readCertPEM(n2);
l = k.getIssuer();
r2 = { hex: k.getSerialNumberHex() };
} else {
if (p.issuer != void 0 && p.serial) {
l = p.issuer;
r2 = p.serial;
} else {
throw new i("cert or issuer and serial parameter not specified");
}
}
var q = new a([{ dn: l }]);
var o2 = new g(r2);
var m = new f({ array: [q, o2] });
return m.tohex();
};
this.getEncodedHex = function() {
return this.tohex();
};
if (e2 != void 0) {
this.setByParam(e2);
}
};
extendClass(KJUR.asn1.cms.IssuerSerial, KJUR.asn1.ASN1Object);
KJUR.asn1.cms.SignerIdentifier = function(f) {
var c = KJUR, i = c.asn1, h = i.DERInteger, g = i.DERSequence, l = i.cms, k = l.IssuerAndSerialNumber, d = l.SubjectKeyIdentifier, e2 = i.x509, a = e2.X500Name, b = X509, j = Error;
l.SignerIdentifier.superclass.constructor.call(this);
this.params = null;
this.tohex = function() {
var o2 = this.params;
if (o2.type == "isssn") {
var m = new k(o2);
return m.tohex();
} else {
if (o2.type == "skid") {
var n2 = new d(o2);
return n2.tohex();
} else {
throw new Error("wrong property for isssn or skid");
}
}
};
this.getEncodedHex = function() {
return this.tohex();
};
if (f != void 0) {
this.setByParam(f);
}
};
extendClass(KJUR.asn1.cms.SignerIdentifier, KJUR.asn1.ASN1Object);
KJUR.asn1.cms.IssuerAndSerialNumber = function(e2) {
var c = KJUR, h = c.asn1, g = h.DERInteger, f = h.DERSequence, j = h.cms, d = h.x509, a = d.X500Name, b = X509, i = Error;
j.IssuerAndSerialNumber.superclass.constructor.call(this);
this.params = null;
this.tohex = function() {
var p = this.params;
var l, r2;
if (typeof p == "string" && p.indexOf("-----BEGIN") != -1 || p.cert != void 0) {
var n2;
if (p.cert != void 0) {
n2 = p.cert;
} else {
n2 = p;
}
var k = new b();
k.readCertPEM(n2);
l = k.getIssuer();
r2 = { hex: k.getSerialNumberHex() };
} else {
if (p.issuer != void 0 && p.serial) {
l = p.issuer;
r2 = p.serial;
} else {
throw new i("cert or issuer and serial parameter not specified");
}
}
var q = new a(l);
var o2 = new g(r2);
var m = new f({ array: [q, o2] });
return m.tohex();
};
this.getEncodedHex = function() {
return this.tohex();
};
this.setByParam = function(k) {
this.params = k;
};
if (e2 != void 0) {
this.setByParam(e2);
}
};
extendClass(KJUR.asn1.cms.IssuerAndSerialNumber, KJUR.asn1.ASN1Object);
KJUR.asn1.cms.SubjectKeyIdentifier = function(g) {
var d = KJUR, k = d.asn1, i = k.DERInteger, h = k.DERSequence, j = k.ASN1Util.newObject, m = k.cms, f = m.IssuerAndSerialName, c = m.SubjectKeyIdentifier, e2 = k.x509, a = e2.X500Name, b = X509, l = Error;
m.SubjectKeyIdentifier.superclass.constructor.call(this);
this.tohex = function() {
var r2 = this.params;
if (r2.cert == void 0 && r2.skid == void 0) {
throw new l("property cert nor skid undefined");
}
var q;
if (r2.cert != void 0) {
var n2 = new b(r2.cert);
var o2 = n2.getExtSubjectKeyIdentifier();
q = o2.kid.hex;
} else {
if (r2.skid != void 0) {
q = r2.skid;
}
}
var p = j({ tag: { tage: "a0", obj: { octstr: { hex: q } } } });
return p.tohex();
};
this.getEncodedHex = function() {
return this.tohex();
};
if (g != void 0) {
this.setByParam(g);
}
};
extendClass(KJUR.asn1.cms.SubjectKeyIdentifier, KJUR.asn1.ASN1Object);
KJUR.asn1.cms.AttributeList = function(f) {
var d = Error, c = KJUR, b = c.asn1, a = b.DERSet, e2 = b.cms;
e2.AttributeList.superclass.constructor.call(this);
this.params = null;
this.hTLV = null;
this.setByParam = function(g) {
this.params = g;
};
this.tohex = function() {
var o2 = this.params;
if (this.hTLV != null) {
return this.hTLV;
}
var m = true;
if (o2.sortflag != void 0) {
m = o2.sortflag;
}
var j = o2.array;
var g = [];
for (var l = 0; l < j.length; l++) {
var n2 = j[l];
var k = n2.attr;
if (k == "contentType") {
g.push(new e2.ContentType(n2));
} else {
if (k == "messageDigest") {
g.push(new e2.MessageDigest(n2));
} else {
if (k == "signingTime") {
g.push(new e2.SigningTime(n2));
} else {
if (k == "signingCertificate") {
g.push(new e2.SigningCertificate(n2));
} else {
if (k == "signingCertificateV2") {
g.push(new e2.SigningCertificateV2(n2));
} else {
if (k == "signaturePolicyIdentifier") {
g.push(new KJUR.asn1.cades.SignaturePolicyIdentifier(n2));
} else {
if (k == "signatureTimeStamp" || k == "timeStampToken") {
g.push(new KJUR.asn1.cades.SignatureTimeStamp(n2));
} else {
throw new d("unknown attr: " + k);
}
}
}
}
}
}
}
}
var h = new a({ array: g, sortflag: m });
this.hTLV = h.tohex();
return this.hTLV;
};
this.getEncodedHex = function() {
return this.tohex();
};
if (f != void 0) {
this.setByParam(f);
}
};
extendClass(KJUR.asn1.cms.AttributeList, KJUR.asn1.ASN1Object);
KJUR.asn1.cms.SignerInfo = function(q) {
var n2 = Error, r2 = KJUR, i = r2.asn1, c = i.DERInteger, f = i.DEROctetString, h = i.DERSequence, m = i.DERTaggedObject, k = i.cms, p = k.SignerIdentifier, l = k.AttributeList, g = k.ContentType, e2 = k.EncapsulatedContentInfo, d = k.MessageDigest, j = k.SignedData, a = i.x509, s = a.AlgorithmIdentifier, b = r2.crypto, o2 = KEYUTIL;
k.SignerInfo.superclass.constructor.call(this);
this.params = null;
this.sign = function() {
var y = this.params;
var x = y.sigalg;
var u = new l(y.sattrs).tohex();
var v = o2.getKey(y.signkey);
var w = new b.Signature({ alg: x });
w.init(v);
w.updateHex(u);
var t3 = w.sign();
y.sighex = t3;
};
this.tohex = function() {
var w = this.params;
var t3 = [];
t3.push(new c({ "int": w.version }));
t3.push(new p(w.id));
t3.push(new s({ name: w.hashalg }));
if (w.sattrs != void 0) {
var x = new l(w.sattrs);
try {
t3.push(new m({ tag: "a0", explicit: false, obj: x }));
} catch (v) {
throw new n2("si sattr error: " + v);
}
}
if (w.sigalgfield != void 0) {
t3.push(new s({ name: w.sigalgfield }));
} else {
t3.push(new s({ name: w.sigalg }));
}
if (w.sighex == void 0 && w.signkey != void 0) {
this.sign();
}
t3.push(new f({ hex: w.sighex }));
if (w.uattrs != void 0) {
var x = new l(w.uattrs);
try {
t3.push(new m({ tag: "a1", explicit: false, obj: x }));
} catch (v) {
throw new n2("si uattr error: " + v);
}
}
var u = new h({ array: t3 });
return u.tohex();
};
this.getEncodedHex = function() {
return this.tohex();
};
if (q != void 0) {
this.setByParam(q);
}
};
extendClass(KJUR.asn1.cms.SignerInfo, KJUR.asn1.ASN1Object);
KJUR.asn1.cms.EncapsulatedContentInfo = function(g) {
var c = KJUR, b = c.asn1, e2 = b.DERTaggedObject, a = b.DERSequence, h = b.DERObjectIdentifier, d = b.DEROctetString, f = b.cms;
f.EncapsulatedContentInfo.superclass.constructor.call(this);
this.params = null;
this.tohex = function() {
var m = this.params;
var i = [];
i.push(new h(m.type));
if (m.content != void 0 && (m.content.hex != void 0 || m.content.str != void 0) && m.isDetached != true) {
var k = new d(m.content);
var l = new e2({ tag: "a0", explicit: true, obj: k });
i.push(l);
}
var j = new a({ array: i });
return j.tohex();
};
this.getEncodedHex = function() {
return this.tohex();
};
this.setByParam = function(i) {
this.params = i;
};
if (g != void 0) {
this.setByParam(g);
}
};
extendClass(KJUR.asn1.cms.EncapsulatedContentInfo, KJUR.asn1.ASN1Object);
KJUR.asn1.cms.ContentInfo = function(g) {
var c = KJUR, b = c.asn1, d = b.DERTaggedObject, a = b.DERSequence, h = b.DERObjectIdentifier, f = b.x509, e2 = f.OID.name2obj;
KJUR.asn1.cms.ContentInfo.superclass.constructor.call(this);
this.params = null;
this.tohex = function() {
var l = this.params;
var i = [];
i.push(new h(l.type));
var k = new d({ tag: "a0", explicit: true, obj: l.obj });
i.push(k);
var j = new a({ array: i });
return j.tohex();
};
this.getEncodedHex = function() {
return this.tohex();
};
this.setByParam = function(i) {
this.params = i;
};
if (g != void 0) {
this.setByParam(g);
}
};
extendClass(KJUR.asn1.cms.ContentInfo, KJUR.asn1.ASN1Object);
KJUR.asn1.cms.SignedData = function(e2) {
var j = Error, a = KJUR, h = a.asn1, m = h.ASN1Object, g = h.DERInteger, p = h.DERSet, f = h.DERSequence, b = h.DERTaggedObject, o2 = h.cms, l = o2.EncapsulatedContentInfo, d = o2.SignerInfo, q = o2.ContentInfo, k = o2.CertificateSet, i = o2.RevocationInfoChoices, c = h.x509, n2 = c.AlgorithmIdentifier;
KJUR.asn1.cms.SignedData.superclass.constructor.call(this);
this.params = null;
this.checkAndFixParam = function() {
var r2 = this.params;
this._setDigestAlgs(r2);
this._setContentTypeByEContent(r2);
this._setMessageDigestByEContent(r2);
this._setSignerInfoVersion(r2);
this._setSignedDataVersion(r2);
};
this._setDigestAlgs = function(v) {
var u = {};
var t3 = v.sinfos;
for (var r2 = 0; r2 < t3.length; r2++) {
var s = t3[r2];
u[s.hashalg] = 1;
}
v.hashalgs = Object.keys(u).sort();
};
this._setContentTypeByEContent = function(w) {
var u = w.econtent.type;
var v = w.sinfos;
for (var r2 = 0; r2 < v.length; r2++) {
var t3 = v[r2];
var s = this._getAttrParamByName(t3, "contentType");
s.type = u;
}
};
this._setMessageDigestByEContent = function(r2) {
var v = r2.econtent;
var y = r2.econtent.type;
var x = v.content.hex;
if (x == void 0 && v.type == "data" && v.content.str != void 0) {
x = rstrtohex(v.content.str);
}
var A = r2.sinfos;
for (var u = 0; u < A.length; u++) {
var t3 = A[u];
var s = t3.hashalg;
var z2 = this._getAttrParamByName(t3, "messageDigest");
var w = KJUR.crypto.Util.hashHex(x, s);
z2.hex = w;
}
};
this._getAttrParamByName = function(t3, s) {
var u = t3.sattrs.array;
for (var r2 = 0; r2 < u.length; r2++) {
if (u[r2].attr == s) {
return u[r2];
}
}
};
this._setSignerInfoVersion = function(v) {
var t3 = v.sinfos;
for (var r2 = 0; r2 < t3.length; r2++) {
var s = t3[r2];
var u = 1;
if (s.id.type == "skid") {
u = 3;
}
s.version = u;
}
};
this._setSignedDataVersion = function(s) {
var r2 = this._getSignedDataVersion(s);
s.version = r2;
};
this._getSignedDataVersion = function(w) {
if (w.revinfos != void 0) {
var r2 = w.revinfos;
for (var t3 = 0; t3 < r2.length; t3++) {
var s = r2[t3];
if (s.ocsp != void 0) {
return 5;
}
}
}
var v = w.sinfos;
for (var t3 = 0; t3 < v.length; t3++) {
var u = w.sinfos[t3];
if (u.version == 3) {
return 3;
}
}
if (w.econtent.type != "data") {
return 3;
}
return 1;
};
this.tohex = function() {
var y = this.params;
if (this.getEncodedHexPrepare != void 0) {
this.getEncodedHexPrepare();
}
if (y.fixed != true) {
this.checkAndFixParam();
}
var r2 = [];
r2.push(new g({ "int": y.version }));
var w = [];
for (var v = 0; v < y.hashalgs.length; v++) {
var t3 = y.hashalgs[v];
w.push(new n2({ name: t3 }));
}
r2.push(new p({ array: w }));
r2.push(new l(y.econtent));
if (y.certs != void 0) {
r2.push(new k(y.certs));
}
if (y.revinfos != void 0) {
r2.push(new i(y.revinfos));
}
var u = [];
for (var v = 0; v < y.sinfos.length; v++) {
var x = y.sinfos[v];
u.push(new d(x));
}
r2.push(new p({ array: u }));
var s = new f({ array: r2 });
return s.tohex();
};
this.getEncodedHex = function() {
return this.tohex();
};
this.getContentInfo = function() {
var r2 = new q({ type: "signed-data", obj: this });
return r2;
};
this.getContentInfoEncodedHex = function() {
return this.getContentInfo().tohex();
};
if (e2 != void 0) {
this.setByParam(e2);
}
};
extendClass(KJUR.asn1.cms.SignedData, KJUR.asn1.ASN1Object);
KJUR.asn1.cms.CertificateSet = function(f) {
KJUR.asn1.cms.CertificateSet.superclass.constructor.call(this);
var c = Error, b = KJUR.asn1, e2 = b.DERTaggedObject, a = b.DERSet, d = b.ASN1Object;
this.params = null;
this.tohex = function() {
var j = this.params;
var p = [];
var q;
if (j instanceof Array) {
q = j;
} else {
if (j.array != void 0) {
q = j.array;
} else {
throw new c("cert array not specified");
}
}
for (var k = 0; k < q.length; k++) {
var l = q[k];
var n2 = pemtohex(l);
var g = new d();
g.hTLV = n2;
p.push(g);
}
var m = { array: p };
if (j.sortflag == false) {
m.sortflag = false;
}
var o2 = new a(m);
var h = new e2({ tag: "a0", explicit: false, obj: o2 });
return h.tohex();
};
this.getEncodedHex = function() {
return this.tohex();
};
if (f != void 0) {
this.setByParam(f);
}
};
extendClass(KJUR.asn1.cms.CertificateSet, KJUR.asn1.ASN1Object);
KJUR.asn1.cms.RevocationInfoChoices = function(a) {
KJUR.asn1.cms.RevocationInfoChoices.superclass.constructor.call(this);
this.params = null;
this.tohex = function() {
var e2 = this.params;
if (!e2 instanceof Array) {
throw new Error("params is not array");
}
var b = [];
for (var c = 0; c < e2.length; c++) {
b.push(new KJUR.asn1.cms.RevocationInfoChoice(e2[c]));
}
var d = KJUR.asn1.ASN1Util.newObject({ tag: { tagi: "a1", obj: { set: b } } });
return d.tohex();
};
this.getEncodedHex = function() {
return this.tohex();
};
if (a != void 0) {
this.setByParam(a);
}
};
extendClass(KJUR.asn1.cms.RevocationInfoChoices, KJUR.asn1.ASN1Object);
KJUR.asn1.cms.RevocationInfoChoice = function(a) {
KJUR.asn1.cms.RevocationInfoChoice.superclass.constructor.call(this);
this.params = null;
this.tohex = function() {
var d = this.params;
if (d.crl != void 0 && typeof d.crl == "string") {
var b = d.crl;
if (d.crl.indexOf("-----BEGIN") != -1) {
b = pemtohex(d.crl);
}
return b;
} else {
if (d.ocsp != void 0) {
var c = KJUR.asn1.ASN1Util.newObject({ tag: { tagi: "a1", obj: new KJUR.asn1.cms.OtherRevocationFormat(d) } });
return c.tohex();
} else {
throw new Error("property crl or ocsp undefined");
}
}
};
this.getEncodedHex = function() {
return this.tohex();
};
if (a != void 0) {
this.setByParam(a);
}
};
extendClass(KJUR.asn1.cms.RevocationInfoChoice, KJUR.asn1.ASN1Object);
KJUR.asn1.cms.OtherRevocationFormat = function(f) {
KJUR.asn1.cms.OtherRevocationFormat.superclass.constructor.call(this);
var d = Error, c = KJUR, b = c.asn1, a = b.ASN1Util.newObject, e2 = c.lang.String.isHex;
this.params = null;
this.tohex = function() {
var h = this.params;
if (h.ocsp == void 0) {
throw new d("property ocsp not specified");
}
if (!e2(h.ocsp) || !ASN1HEX.isASN1HEX(h.ocsp)) {
throw new d("ocsp value not ASN.1 hex string");
}
var g = a({ seq: [{ oid: "1.3.6.1.5.5.7.16.2" }, { asn1: { tlv: h.ocsp } }] });
return g.tohex();
};
this.getEncodedHex = function() {
return this.tohex();
};
if (f != void 0) {
this.setByParam(f);
}
};
extendClass(KJUR.asn1.cms.OtherRevocationFormat, KJUR.asn1.ASN1Object);
KJUR.asn1.cms.CMSUtil = new function() {
}();
KJUR.asn1.cms.CMSUtil.newSignedData = function(a) {
return new KJUR.asn1.cms.SignedData(a);
};
KJUR.asn1.cms.CMSUtil.verifySignedData = function(n2) {
var C = KJUR, p = C.asn1, s = p.cms, D = s.SignerInfo, q = s.SignedData, y = s.SigningTime, b = s.SigningCertificate, d = s.SigningCertificateV2, A = p.cades, u = A.SignaturePolicyIdentifier, i = C.lang.String.isHex, v = ASN1HEX, h = v.getVbyList, a = v.getTLVbyList, t3 = v.getIdxbyList, z2 = v.getChildIdx, c = v.getTLV, B = v.oidname, j = C.crypto.Util.hashHex;
if (n2.cms === void 0 && !i(n2.cms)) {
}
var E = n2.cms;
var g = function(J, H) {
var G;
for (var I = 3; I < 6; I++) {
G = t3(J, 0, [1, 0, I]);
if (G !== void 0) {
var F = J.substr(G, 2);
if (F === "a0") {
H.certsIdx = G;
}
if (F === "a1") {
H.revinfosIdx = G;
}
if (F === "31") {
H.signerinfosIdx = G;
}
}
}
};
var l = function(I, F) {
var H = F.signerinfosIdx;
if (H === void 0) {
return;
}
var L = z2(I, H);
F.signerInfoIdxList = L;
for (var G = 0; G < L.length; G++) {
var K = L[G];
var J = { idx: K };
k(I, J);
F.signerInfos.push(J);
}
};
var k = function(I, J) {
var F = J.idx;
J.signerid_issuer1 = a(I, F, [1, 0], "30");
J.signerid_serial1 = h(I, F, [1, 1], "02");
J.hashalg = B(h(I, F, [2, 0], "06"));
var H = t3(I, F, [3], "a0");
J.idxSignedAttrs = H;
f(I, J, H);
var G = z2(I, F);
var K = G.length;
if (K < 6) {
throw "malformed SignerInfo";
}
J.sigalg = B(h(I, F, [K - 2, 0], "06"));
J.sigval = h(I, F, [K - 1], "04");
};
var f = function(L, M, F) {
var J = z2(L, F);
M.signedAttrIdxList = J;
for (var K = 0; K < J.length; K++) {
var I = J[K];
var G = h(L, I, [0], "06");
var H;
if (G === "2a864886f70d010905") {
H = hextoutf8(h(L, I, [1, 0]));
M.saSigningTime = H;
} else {
if (G === "2a864886f70d010904") {
H = h(L, I, [1, 0], "04");
M.saMessageDigest = H;
}
}
}
};
var w = function(G, F) {
if (h(G, 0, [0], "06") !== "2a864886f70d010702") {
return F;
}
F.cmsType = "signedData";
F.econtent = h(G, 0, [1, 0, 2, 1, 0]);
g(G, F);
F.signerInfos = [];
l(G, F);
};
var o2 = function(J, F) {
var G = F.parse.signerInfos;
var L = G.length;
var K = true;
for (var I = 0; I < L; I++) {
var H = G[I];
e2(J, F, H, I);
if (!H.isValid) {
K = false;
}
}
F.isValid = K;
};
var x = function(F, Q, J, P) {
var N = Q.parse.certsIdx;
var H;
if (Q.certs === void 0) {
H = [];
Q.certkeys = [];
var K = z2(F, N);
for (var I = 0; I < K.length; I++) {
var M = c(F, K[I]);
var O = new X509();
O.readCertHex(M);
H[I] = O;
Q.certkeys[I] = O.getPublicKey();
}
Q.certs = H;
} else {
H = Q.certs;
}
Q.cccc = H.length;
Q.cccci = K.length;
for (var I = 0; I < H.length; I++) {
var L = O.getIssuerHex();
var G = O.getSerialNumberHex();
if (J.signerid_issuer1 === L && J.signerid_serial1 === G) {
J.certkey_idx = I;
}
}
};
var e2 = function(F, R, I, N) {
I.verifyDetail = {};
var Q = I.verifyDetail;
var K = R.parse.econtent;
var G = I.hashalg;
var L = I.saMessageDigest;
Q.validMessageDigest = false;
if (j(K, G) === L) {
Q.validMessageDigest = true;
}
x(F, R, I, N);
Q.validSignatureValue = false;
var H = I.sigalg;
var M = "31" + c(F, I.idxSignedAttrs).substr(2);
I.signedattrshex = M;
var J = R.certs[I.certkey_idx].getPublicKey();
var P = new KJUR.crypto.Signature({ alg: H });
P.init(J);
P.updateHex(M);
var O = P.verify(I.sigval);
Q.validSignatureValue_isValid = O;
if (O === true) {
Q.validSignatureValue = true;
}
I.isValid = false;
if (Q.validMessageDigest && Q.validSignatureValue) {
I.isValid = true;
}
};
var m = function() {
};
var r2 = { isValid: false, parse: {} };
w(E, r2.parse);
o2(E, r2);
return r2;
};
KJUR.asn1.cms.CMSParser = function() {
var g = Error, a = X509, h = new a(), l = ASN1HEX, i = l.getV, b = l.getTLV, f = l.getIdxbyList, c = l.getTLVbyList, d = l.getTLVbyListEx, e2 = l.getVbyList, k = l.getVbyListEx, j = l.getChildIdx;
this.getCMSSignedData = function(m) {
var o2 = c(m, 0, [1, 0]);
var n2 = this.getSignedData(o2);
return n2;
};
this.getSignedData = function(o2) {
var q = j(o2, 0);
var v = {};
var p = i(o2, q[0]);
var n2 = parseInt(p, 16);
v.version = n2;
var r2 = b(o2, q[1]);
v.hashalgs = this.getHashAlgArray(r2);
var t3 = b(o2, q[2]);
v.econtent = this.getEContent(t3);
var m = d(o2, 0, ["[0]"]);
if (m != null) {
v.certs = this.getCertificateSet(m);
}
var u = d(o2, 0, ["[1]"]);
if (u != null) {
}
var s = d(o2, 0, [3]);
v.sinfos = this.getSignerInfos(s);
return v;
};
this.getHashAlgArray = function(s) {
var q = j(s, 0);
var m = new a();
var n2 = [];
for (var r2 = 0; r2 < q.length; r2++) {
var p = b(s, q[r2]);
var o2 = m.getAlgorithmIdentifierName(p);
n2.push(o2);
}
return n2;
};
this.getEContent = function(m) {
var n2 = {};
var p = e2(m, 0, [0]);
var o2 = e2(m, 0, [1, 0]);
n2.type = KJUR.asn1.x509.OID.oid2name(ASN1HEX.hextooidstr(p));
n2.content = { hex: o2 };
return n2;
};
this.getSignerInfos = function(p) {
var r2 = [];
var m = j(p, 0);
for (var n2 = 0; n2 < m.length; n2++) {
var o2 = b(p, m[n2]);
var q = this.getSignerInfo(o2);
r2.push(q);
}
return r2;
};
this.getSignerInfo = function(s) {
var y = {};
var u = j(s, 0);
var q = l.getInt(s, u[0], -1);
if (q != -1) {
y.version = q;
}
var t3 = b(s, u[1]);
var p = this.getIssuerAndSerialNumber(t3);
y.id = p;
var z2 = b(s, u[2]);
var n2 = h.getAlgorithmIdentifierName(z2);
y.hashalg = n2;
var w = d(s, 0, ["[0]"]);
if (w != null) {
var A = this.getAttributeList(w);
y.sattrs = A;
}
var m = d(s, 0, [3]);
var x = h.getAlgorithmIdentifierName(m);
y.sigalg = x;
var o2 = k(s, 0, [4]);
y.sighex = o2;
var r2 = d(s, 0, ["[1]"]);
if (r2 != null) {
var v = this.getAttributeList(r2);
y.uattrs = v;
}
return y;
};
this.getSignerIdentifier = function(m) {
if (m.substr(0, 2) == "30") {
return this.getIssuerAndSerialNumber(m);
} else {
throw new Error("SKID of signerIdentifier not supported");
}
};
this.getIssuerAndSerialNumber = function(n2) {
var o2 = { type: "isssn" };
var m = j(n2, 0);
var p = b(n2, m[0]);
o2.issuer = h.getX500Name(p);
var q = i(n2, m[1]);
o2.serial = { hex: q };
return o2;
};
this.getAttributeList = function(q) {
var m = [];
var n2 = j(q, 0);
for (var o2 = 0; o2 < n2.length; o2++) {
var p = b(q, n2[o2]);
var r2 = this.getAttribute(p);
m.push(r2);
}
return { array: m };
};
this.getAttribute = function(p) {
var t3 = {};
var q = j(p, 0);
var o2 = l.getOID(p, q[0]);
var m = KJUR.asn1.x509.OID.oid2name(o2);
t3.attr = m;
var r2 = b(p, q[1]);
var u = j(r2, 0);
if (u.length == 1) {
t3.valhex = b(r2, u[0]);
} else {
var s = [];
for (var n2 = 0; n2 < u.length; n2++) {
s.push(b(r2, u[n2]));
}
t3.valhex = s;
}
if (m == "contentType") {
this.setContentType(t3);
} else {
if (m == "messageDigest") {
this.setMessageDigest(t3);
} else {
if (m == "signingTime") {
this.setSigningTime(t3);
} else {
if (m == "signingCertificate") {
this.setSigningCertificate(t3);
} else {
if (m == "signingCertificateV2") {
this.setSigningCertificateV2(t3);
} else {
if (m == "signaturePolicyIdentifier") {
this.setSignaturePolicyIdentifier(t3);
}
}
}
}
}
}
return t3;
};
this.setContentType = function(m) {
var n2 = l.getOIDName(m.valhex, 0, null);
if (n2 != null) {
m.type = n2;
delete m.valhex;
}
};
this.setSigningTime = function(o2) {
var n2 = i(o2.valhex, 0);
var m = hextoutf8(n2);
o2.str = m;
delete o2.valhex;
};
this.setMessageDigest = function(m) {
var n2 = i(m.valhex, 0);
m.hex = n2;
delete m.valhex;
};
this.setSigningCertificate = function(n2) {
var q = j(n2.valhex, 0);
if (q.length > 0) {
var m = b(n2.valhex, q[0]);
var p = j(m, 0);
var t3 = [];
for (var o2 = 0; o2 < p.length; o2++) {
var s = b(m, p[o2]);
var u = this.getESSCertID(s);
t3.push(u);
}
n2.array = t3;
}
if (q.length > 1) {
var r2 = b(n2.valhex, q[1]);
n2.polhex = r2;
}
delete n2.valhex;
};
this.setSignaturePolicyIdentifier = function(s) {
var q = j(s.valhex, 0);
if (q.length > 0) {
var r2 = l.getOID(s.valhex, q[0]);
s.oid = r2;
}
if (q.length > 1) {
var m = new a();
var t3 = j(s.valhex, q[1]);
var p = b(s.valhex, t3[0]);
var o2 = m.getAlgorithmIdentifierName(p);
s.alg = o2;
var n2 = i(s.valhex, t3[1]);
s.hash = n2;
}
delete s.valhex;
};
this.setSigningCertificateV2 = function(o2) {
var s = j(o2.valhex, 0);
if (s.length > 0) {
var n2 = b(o2.valhex, s[0]);
var r2 = j(n2, 0);
var u = [];
for (var q = 0; q < r2.length; q++) {
var m = b(n2, r2[q]);
var p = this.getESSCertIDv2(m);
u.push(p);
}
o2.array = u;
}
if (s.length > 1) {
var t3 = b(o2.valhex, s[1]);
o2.polhex = t3;
}
delete o2.valhex;
};
this.getESSCertID = function(o2) {
var p = {};
var n2 = j(o2, 0);
if (n2.length > 0) {
var q = i(o2, n2[0]);
p.hash = q;
}
if (n2.length > 1) {
var m = b(o2, n2[1]);
var r2 = this.getIssuerSerial(m);
if (r2.serial != void 0) {
p.serial = r2.serial;
}
if (r2.issuer != void 0) {
p.issuer = r2.issuer;
}
}
return p;
};
this.getESSCertIDv2 = function(q) {
var s = {};
var p = j(q, 0);
if (p.length < 1 || 3 < p.length) {
throw new g("wrong number of elements");
}
var r2 = 0;
if (q.substr(p[0], 2) == "30") {
var o2 = b(q, p[0]);
s.alg = h.getAlgorithmIdentifierName(o2);
r2++;
} else {
s.alg = "sha256";
}
var n2 = i(q, p[r2]);
s.hash = n2;
if (p.length > r2 + 1) {
var m = b(q, p[r2 + 1]);
var t3 = this.getIssuerSerial(m);
s.issuer = t3.issuer;
s.serial = t3.serial;
}
return s;
};
this.getIssuerSerial = function(q) {
var r2 = {};
var n2 = j(q, 0);
var m = b(q, n2[0]);
var p = h.getGeneralNames(m);
var o2 = p[0].dn;
r2.issuer = o2;
var s = i(q, n2[1]);
r2.serial = { hex: s };
return r2;
};
this.getCertificateSet = function(p) {
var n2 = j(p, 0);
var m = [];
for (var o2 = 0; o2 < n2.length; o2++) {
var r2 = b(p, n2[o2]);
if (r2.substr(0, 2) == "30") {
var q = hextopem(r2, "CERTIFICATE");
m.push(q);
}
}
return { array: m, sortflag: false };
};
};
if (typeof KJUR == "undefined" || !KJUR) {
KJUR = {};
}
if (typeof KJUR.asn1 == "undefined" || !KJUR.asn1) {
KJUR.asn1 = {};
}
if (typeof KJUR.asn1.tsp == "undefined" || !KJUR.asn1.tsp) {
KJUR.asn1.tsp = {};
}
KJUR.asn1.tsp.TimeStampToken = function(d) {
var c = KJUR, b = c.asn1, a = b.tsp;
a.TimeStampToken.superclass.constructor.call(this);
this.params = null;
this.getEncodedHexPrepare = function() {
var e2 = new a.TSTInfo(this.params.econtent.content);
this.params.econtent.content.hex = e2.tohex();
};
if (d != void 0) {
this.setByParam(d);
}
};
extendClass(KJUR.asn1.tsp.TimeStampToken, KJUR.asn1.cms.SignedData);
KJUR.asn1.tsp.TSTInfo = function(f) {
var m = Error, c = KJUR, j = c.asn1, g = j.DERSequence, i = j.DERInteger, l = j.DERBoolean, h = j.DERGeneralizedTime, n2 = j.DERObjectIdentifier, e2 = j.DERTaggedObject, k = j.tsp, d = k.MessageImprint, b = k.Accuracy, a = j.x509.X500Name, o2 = j.x509.GeneralName;
k.TSTInfo.superclass.constructor.call(this);
this.dVersion = new i({ "int": 1 });
this.dPolicy = null;
this.dMessageImprint = null;
this.dSerial = null;
this.dGenTime = null;
this.dAccuracy = null;
this.dOrdering = null;
this.dNonce = null;
this.dTsa = null;
this.tohex = function() {
var p = [this.dVersion];
if (this.dPolicy == null) {
throw new Error("policy shall be specified.");
}
p.push(this.dPolicy);
if (this.dMessageImprint == null) {
throw new Error("messageImprint shall be specified.");
}
p.push(this.dMessageImprint);
if (this.dSerial == null) {
throw new Error("serialNumber shall be specified.");
}
p.push(this.dSerial);
if (this.dGenTime == null) {
throw new Error("genTime shall be specified.");
}
p.push(this.dGenTime);
if (this.dAccuracy != null) {
p.push(this.dAccuracy);
}
if (this.dOrdering != null) {
p.push(this.dOrdering);
}
if (this.dNonce != null) {
p.push(this.dNonce);
}
if (this.dTsa != null) {
p.push(this.dTsa);
}
var q = new g({ array: p });
this.hTLV = q.tohex();
return this.hTLV;
};
this.getEncodedHex = function() {
return this.tohex();
};
if (f !== void 0) {
if (typeof f.policy == "string") {
if (!f.policy.match(/^[0-9.]+$/)) {
throw "policy shall be oid like 0.1.4.134";
}
this.dPolicy = new n2({ oid: f.policy });
}
if (f.messageImprint !== void 0) {
this.dMessageImprint = new d(f.messageImprint);
}
if (f.serial !== void 0) {
this.dSerial = new i(f.serial);
}
if (f.genTime !== void 0) {
this.dGenTime = new h(f.genTime);
}
if (f.accuracy !== void 0) {
this.dAccuracy = new b(f.accuracy);
}
if (f.ordering !== void 0 && f.ordering == true) {
this.dOrdering = new l();
}
if (f.nonce !== void 0) {
this.dNonce = new i(f.nonce);
}
if (f.tsa !== void 0) {
this.dTsa = new e2({ tag: "a0", explicit: true, obj: new o2({ dn: f.tsa }) });
}
}
};
extendClass(KJUR.asn1.tsp.TSTInfo, KJUR.asn1.ASN1Object);
KJUR.asn1.tsp.Accuracy = function(d) {
var c = KJUR, b = c.asn1, a = b.ASN1Util.newObject;
b.tsp.Accuracy.superclass.constructor.call(this);
this.params = null;
this.tohex = function() {
var f = this.params;
var e2 = [];
if (f.seconds != void 0 && typeof f.seconds == "number") {
e2.push({ "int": f.seconds });
}
if (f.millis != void 0 && typeof f.millis == "number") {
e2.push({ tag: { tagi: "80", obj: { "int": f.millis } } });
}
if (f.micros != void 0 && typeof f.micros == "number") {
e2.push({ tag: { tagi: "81", obj: { "int": f.micros } } });
}
return a({ seq: e2 }).tohex();
};
this.getEncodedHex = function() {
return this.tohex();
};
if (d != void 0) {
this.setByParam(d);
}
};
extendClass(KJUR.asn1.tsp.Accuracy, KJUR.asn1.ASN1Object);
KJUR.asn1.tsp.MessageImprint = function(g) {
var c = KJUR, b = c.asn1, a = b.DERSequence, d = b.DEROctetString, f = b.x509, e2 = f.AlgorithmIdentifier;
b.tsp.MessageImprint.superclass.constructor.call(this);
this.params = null;
this.tohex = function() {
var k = this.params;
var j = new e2({ name: k.alg });
var h = new d({ hex: k.hash });
var i = new a({ array: [j, h] });
return i.tohex();
};
this.getEncodedHex = function() {
return this.tohex();
};
if (g !== void 0) {
this.setByParam(g);
}
};
extendClass(KJUR.asn1.tsp.MessageImprint, KJUR.asn1.ASN1Object);
KJUR.asn1.tsp.TimeStampReq = function(c) {
var a = KJUR, f = a.asn1, d = f.DERSequence, e2 = f.DERInteger, h = f.DERBoolean, j = f.ASN1Object, i = f.DERObjectIdentifier, g = f.tsp, b = g.MessageImprint;
g.TimeStampReq.superclass.constructor.call(this);
this.params = null;
this.tohex = function() {
var m = this.params;
var k = [];
k.push(new e2({ "int": 1 }));
if (m.messageImprint instanceof KJUR.asn1.ASN1Object) {
k.push(m.messageImprint);
} else {
k.push(new b(m.messageImprint));
}
if (m.policy != void 0) {
k.push(new i(m.policy));
}
if (m.nonce != void 0) {
k.push(new e2(m.nonce));
}
if (m.certreq == true) {
k.push(new h());
}
var l = new d({ array: k });
return l.tohex();
};
this.getEncodedHex = function() {
return this.tohex();
};
if (c != void 0) {
this.setByParam(c);
}
};
extendClass(KJUR.asn1.tsp.TimeStampReq, KJUR.asn1.ASN1Object);
KJUR.asn1.tsp.TimeStampResp = function(g) {
var e2 = KJUR, d = e2.asn1, c = d.DERSequence, f = d.ASN1Object, a = d.tsp, b = a.PKIStatusInfo;
a.TimeStampResp.superclass.constructor.call(this);
this.params = null;
this.tohex = function() {
var j = this.params;
var h = [];
if (j.econtent != void 0 || j.tst != void 0) {
if (j.statusinfo != void 0) {
h.push(new b(j.statusinfo));
} else {
h.push(new b("granted"));
}
if (j.econtent != void 0) {
h.push(new a.TimeStampToken(j).getContentInfo());
} else {
if (j.tst instanceof d.ASN1Object) {
h.push(j.tst);
} else {
throw new Error("improper member tst value");
}
}
} else {
if (j.statusinfo != void 0) {
h.push(new b(j.statusinfo));
} else {
throw new Error("parameter for token nor statusinfo not specified");
}
}
var i = new c({ array: h });
return i.tohex();
};
this.getEncodedHex = function() {
return this.tohex();
};
if (g != void 0) {
this.setByParam(g);
}
};
extendClass(KJUR.asn1.tsp.TimeStampResp, KJUR.asn1.ASN1Object);
KJUR.asn1.tsp.PKIStatusInfo = function(d) {
var h = Error, a = KJUR, g = a.asn1, e2 = g.DERSequence, i = g.tsp, f = i.PKIStatus, c = i.PKIFreeText, b = i.PKIFailureInfo;
i.PKIStatusInfo.superclass.constructor.call(this);
this.params = null;
this.tohex = function() {
var l = this.params;
var j = [];
if (typeof l == "string") {
j.push(new f(l));
} else {
if (l.status == void 0) {
throw new h("property 'status' unspecified");
}
j.push(new f(l.status));
if (l.statusstr != void 0) {
j.push(new c(l.statusstr));
}
if (l.failinfo != void 0) {
j.push(new b(l.failinfo));
}
}
var k = new e2({ array: j });
return k.tohex();
};
this.getEncodedHex = function() {
return this.tohex();
};
if (d != void 0) {
this.setByParam(d);
}
};
extendClass(KJUR.asn1.tsp.PKIStatusInfo, KJUR.asn1.ASN1Object);
KJUR.asn1.tsp.PKIStatus = function(g) {
var e2 = Error, d = KJUR, c = d.asn1, f = c.DERInteger, b = c.tsp;
b.PKIStatus.superclass.constructor.call(this);
var a = { granted: 0, grantedWithMods: 1, rejection: 2, waiting: 3, revocationWarning: 4, revocationNotification: 5 };
this.params = null;
this.tohex = function() {
var k = this.params;
var h, j;
if (typeof k == "string") {
try {
j = a[k];
} catch (i) {
throw new e2("undefined name: " + k);
}
} else {
if (typeof k == "number") {
j = k;
} else {
throw new e2("unsupported params");
}
}
return new f({ "int": j }).tohex();
};
this.getEncodedHex = function() {
return this.tohex();
};
if (g != void 0) {
this.setByParam(g);
}
};
extendClass(KJUR.asn1.tsp.PKIStatus, KJUR.asn1.ASN1Object);
KJUR.asn1.tsp.PKIFreeText = function(g) {
var f = Error, e2 = KJUR, d = e2.asn1, b = d.DERSequence, c = d.DERUTF8String, a = d.tsp;
a.PKIFreeText.superclass.constructor.call(this);
this.params = null;
this.tohex = function() {
var l = this.params;
if (!l instanceof Array) {
throw new f("wrong params: not array");
}
var h = [];
for (var k = 0; k < l.length; k++) {
h.push(new c({ str: l[k] }));
}
var j = new b({ array: h });
return j.tohex();
};
this.getEncodedHex = function() {
return this.tohex();
};
if (g != void 0) {
this.setByParam(g);
}
};
extendClass(KJUR.asn1.tsp.PKIFreeText, KJUR.asn1.ASN1Object);
KJUR.asn1.tsp.PKIFailureInfo = function(h) {
var f = Error, e2 = KJUR, d = e2.asn1, g = d.DERBitString, b = d.tsp, c = b.PKIFailureInfo;
var a = { badAlg: 0, badRequest: 2, badDataFormat: 5, timeNotAvailable: 14, unacceptedPolicy: 15, unacceptedExtension: 16, addInfoNotAvailable: 17, systemFailure: 25 };
c.superclass.constructor.call(this);
this.params = null;
this.getBinValue = function() {
var n2 = this.params;
var m = 0;
if (typeof n2 == "number" && 0 <= n2 && n2 <= 25) {
m |= 1 << n2;
var k = m.toString(2);
var l = "";
for (var j = k.length - 1; j >= 0; j--) {
l += k[j];
}
return l;
} else {
if (typeof n2 == "string" && a[n2] != void 0) {
return namearraytobinstr([n2], a);
} else {
if (typeof n2 == "object" && n2.length != void 0) {
return namearraytobinstr(n2, a);
} else {
throw new f("wrong params");
}
}
}
return;
};
this.tohex = function() {
var j = this.params;
var i = this.getBinValue();
return new g({ bin: i }).tohex();
};
this.getEncodedHex = function() {
return this.tohex();
};
if (h != void 0) {
this.setByParam(h);
}
};
extendClass(KJUR.asn1.tsp.PKIFailureInfo, KJUR.asn1.ASN1Object);
KJUR.asn1.tsp.AbstractTSAAdapter = function(a) {
this.getTSTHex = function(c, b) {
throw "not implemented yet";
};
};
KJUR.asn1.tsp.SimpleTSAAdapter = function(e2) {
var d = KJUR, c = d.asn1, a = c.tsp, b = d.crypto.Util.hashHex;
a.SimpleTSAAdapter.superclass.constructor.call(this);
this.params = null;
this.serial = 0;
this.getTSTHex = function(g, f) {
var i = b(g, f);
this.params.econtent.content.messageImprint = { alg: f, hash: i };
this.params.econtent.content.serial = { "int": this.serial++ };
var h = Math.floor(Math.random() * 1e9);
this.params.econtent.content.nonce = { "int": h };
var j = new a.TimeStampToken(this.params);
return j.getContentInfoEncodedHex();
};
if (e2 !== void 0) {
this.params = e2;
}
};
extendClass(KJUR.asn1.tsp.SimpleTSAAdapter, KJUR.asn1.tsp.AbstractTSAAdapter);
KJUR.asn1.tsp.FixedTSAAdapter = function(e2) {
var d = KJUR, c = d.asn1, a = c.tsp, b = d.crypto.Util.hashHex;
a.FixedTSAAdapter.superclass.constructor.call(this);
this.params = null;
this.getTSTHex = function(g, f) {
var h = b(g, f);
this.params.econtent.content.messageImprint = { alg: f, hash: h };
var i = new a.TimeStampToken(this.params);
return i.getContentInfoEncodedHex();
};
if (e2 !== void 0) {
this.params = e2;
}
};
extendClass(KJUR.asn1.tsp.FixedTSAAdapter, KJUR.asn1.tsp.AbstractTSAAdapter);
KJUR.asn1.tsp.TSPUtil = new function() {
}();
KJUR.asn1.tsp.TSPUtil.newTimeStampToken = function(a) {
return new KJUR.asn1.tsp.TimeStampToken(a);
};
KJUR.asn1.tsp.TSPUtil.parseTimeStampReq = function(a) {
var b = new KJUR.asn1.tsp.TSPParser();
return b.getTimeStampReq(a);
};
KJUR.asn1.tsp.TSPUtil.parseMessageImprint = function(a) {
var b = new KJUR.asn1.tsp.TSPParser();
return b.getMessageImprint(a);
};
KJUR.asn1.tsp.TSPParser = function() {
var e2 = Error, a = X509, f = new a(), k = ASN1HEX, g = k.getV, b = k.getTLV, d = k.getIdxbyList, c = k.getTLVbyListEx, i = k.getChildIdx;
var j = ["granted", "grantedWithMods", "rejection", "waiting", "revocationWarning", "revocationNotification"];
var h = { 0: "badAlg", 2: "badRequest", 5: "badDataFormat", 14: "timeNotAvailable", 15: "unacceptedPolicy", 16: "unacceptedExtension", 17: "addInfoNotAvailable", 25: "systemFailure" };
this.getResponse = function(n2) {
var l = i(n2, 0);
if (l.length == 1) {
return this.getPKIStatusInfo(b(n2, l[0]));
} else {
if (l.length > 1) {
var o2 = this.getPKIStatusInfo(b(n2, l[0]));
var m = b(n2, l[1]);
var p = this.getToken(m);
p.statusinfo = o2;
return p;
}
}
};
this.getToken = function(m) {
var l = new KJUR.asn1.cms.CMSParser();
var n2 = l.getCMSSignedData(m);
this.setTSTInfo(n2);
return n2;
};
this.setTSTInfo = function(l) {
var o2 = l.econtent;
if (o2.type == "tstinfo") {
var n2 = o2.content.hex;
var m = this.getTSTInfo(n2);
o2.content = m;
}
};
this.getTSTInfo = function(r2) {
var x = {};
var s = i(r2, 0);
var p = g(r2, s[1]);
x.policy = hextooid(p);
var o2 = b(r2, s[2]);
x.messageImprint = this.getMessageImprint(o2);
var u = g(r2, s[3]);
x.serial = { hex: u };
var y = g(r2, s[4]);
x.genTime = { str: hextoutf8(y) };
var q = 0;
if (s.length > 5 && r2.substr(s[5], 2) == "30") {
var v = b(r2, s[5]);
x.accuracy = this.getAccuracy(v);
q++;
}
if (s.length > 5 + q && r2.substr(s[5 + q], 2) == "01") {
var z2 = g(r2, s[5 + q]);
if (z2 == "ff") {
x.ordering = true;
}
q++;
}
if (s.length > 5 + q && r2.substr(s[5 + q], 2) == "02") {
var n2 = g(r2, s[5 + q]);
x.nonce = { hex: n2 };
q++;
}
if (s.length > 5 + q && r2.substr(s[5 + q], 2) == "a0") {
var m = b(r2, s[5 + q]);
m = "30" + m.substr(2);
pGeneralNames = f.getGeneralNames(m);
var t3 = pGeneralNames[0].dn;
x.tsa = t3;
q++;
}
if (s.length > 5 + q && r2.substr(s[5 + q], 2) == "a1") {
var l = b(r2, s[5 + q]);
l = "30" + l.substr(2);
var w = f.getExtParamArray(l);
x.ext = w;
q++;
}
return x;
};
this.getAccuracy = function(q) {
var r2 = {};
var o2 = i(q, 0);
for (var p = 0; p < o2.length; p++) {
var m = q.substr(o2[p], 2);
var l = g(q, o2[p]);
var n2 = parseInt(l, 16);
if (m == "02") {
r2.seconds = n2;
} else {
if (m == "80") {
r2.millis = n2;
} else {
if (m == "81") {
r2.micros = n2;
}
}
}
}
return r2;
};
this.getMessageImprint = function(n2) {
if (n2.substr(0, 2) != "30") {
throw new Error("head of messageImprint hex shall be x30");
}
var s = {};
var l = i(n2, 0);
var t3 = d(n2, 0, [0, 0]);
var o2 = g(n2, t3);
var p = k.hextooidstr(o2);
var r2 = KJUR.asn1.x509.OID.oid2name(p);
if (r2 == "") {
throw new Error("hashAlg name undefined: " + p);
}
var m = r2;
var q = d(n2, 0, [1]);
s.alg = m;
s.hash = g(n2, q);
return s;
};
this.getPKIStatusInfo = function(o2) {
var t3 = {};
var r2 = i(o2, 0);
var n2 = 0;
try {
var l = g(o2, r2[0]);
var p = parseInt(l, 16);
t3.status = j[p];
} catch (s) {
}
if (r2.length > 1 && o2.substr(r2[1], 2) == "30") {
var m = b(o2, r2[1]);
t3.statusstr = this.getPKIFreeText(m);
n2++;
}
if (r2.length > n2 && o2.substr(r2[1 + n2], 2) == "03") {
var q = b(o2, r2[1 + n2]);
t3.failinfo = this.getPKIFailureInfo(q);
}
return t3;
};
this.getPKIFreeText = function(n2) {
var o2 = [];
var l = i(n2, 0);
for (var m = 0; m < l.length; m++) {
o2.push(k.getString(n2, l[m]));
}
return o2;
};
this.getPKIFailureInfo = function(l) {
var m = k.getInt(l, 0);
if (h[m] != void 0) {
return h[m];
} else {
return m;
}
};
this.getTimeStampReq = function(q) {
var p = {};
p.certreq = false;
var s = i(q, 0);
if (s.length < 2) {
throw new Error("TimeStampReq must have at least 2 items");
}
var n2 = b(q, s[1]);
p.messageImprint = KJUR.asn1.tsp.TSPUtil.parseMessageImprint(n2);
for (var o2 = 2; o2 < s.length; o2++) {
var m = s[o2];
var l = q.substr(m, 2);
if (l == "06") {
var r2 = g(q, m);
p.policy = k.hextooidstr(r2);
}
if (l == "02") {
p.nonce = g(q, m);
}
if (l == "01") {
p.certreq = true;
}
}
return p;
};
};
if (typeof KJUR == "undefined" || !KJUR) {
KJUR = {};
}
if (typeof KJUR.asn1 == "undefined" || !KJUR.asn1) {
KJUR.asn1 = {};
}
if (typeof KJUR.asn1.cades == "undefined" || !KJUR.asn1.cades) {
KJUR.asn1.cades = {};
}
KJUR.asn1.cades.SignaturePolicyIdentifier = function(e2) {
var c = KJUR, b = c.asn1, a = b.cades, d = a.SignaturePolicyId;
a.SignaturePolicyIdentifier.superclass.constructor.call(this);
this.typeOid = "1.2.840.113549.1.9.16.2.15";
this.params = null;
this.getValueArray = function() {
return [new d(this.params)];
};
this.setByParam = function(f) {
this.params = f;
};
if (e2 != void 0) {
this.setByParam(e2);
}
};
extendClass(KJUR.asn1.cades.SignaturePolicyIdentifier, KJUR.asn1.cms.Attribute);
KJUR.asn1.cades.SignaturePolicyId = function(e2) {
var a = KJUR, g = a.asn1, f = g.DERSequence, i = g.DERObjectIdentifier, d = g.x509, j = d.AlgorithmIdentifier, c = g.cades, h = c.SignaturePolicyId, b = c.OtherHashAlgAndValue;
h.superclass.constructor.call(this);
this.params = null;
this.tohex = function() {
var m = this.params;
var k = [];
k.push(new i(m.oid));
k.push(new b(m));
var l = new f({ array: k });
return l.tohex();
};
this.getEncodedHex = function() {
return this.tohex();
};
this.setByParam = function(k) {
this.params = k;
};
if (e2 != void 0) {
this.setByParam(e2);
}
};
extendClass(KJUR.asn1.cades.SignaturePolicyId, KJUR.asn1.ASN1Object);
KJUR.asn1.cades.OtherHashAlgAndValue = function(e2) {
var h = Error, a = KJUR, g = a.asn1, f = g.DERSequence, i = g.DEROctetString, d = g.x509, j = d.AlgorithmIdentifier, c = g.cades, b = c.OtherHashAlgAndValue;
b.superclass.constructor.call(this);
this.params = null;
this.tohex = function() {
var o2 = this.params;
if (o2.alg == void 0) {
throw new h("property 'alg' not specified");
}
if (o2.hash == void 0 && o2.cert == void 0) {
throw new h("property 'hash' nor 'cert' not specified");
}
var m = null;
if (o2.hash != void 0) {
m = o2.hash;
} else {
if (o2.cert != void 0) {
if (typeof o2.cert != "string") {
throw new h("cert not string");
}
var n2 = o2.cert;
if (o2.cert.indexOf("-----BEGIN") != -1) {
n2 = pemtohex(o2.cert);
}
m = KJUR.crypto.Util.hashHex(n2, o2.alg);
}
}
var k = [];
k.push(new j({ name: o2.alg }));
k.push(new i({ hex: m }));
var l = new f({ array: k });
return l.tohex();
};
this.getEncodedHex = function() {
return this.tohex();
};
if (e2 != void 0) {
this.setByParam(e2);
}
};
extendClass(KJUR.asn1.cades.OtherHashAlgAndValue, KJUR.asn1.ASN1Object);
KJUR.asn1.cades.OtherHashValue = function(g) {
KJUR.asn1.cades.OtherHashValue.superclass.constructor.call(this);
var d = Error, c = KJUR, f = c.lang.String.isHex, b = c.asn1, e2 = b.DEROctetString, a = c.crypto.Util.hashHex;
this.params = null;
this.tohex = function() {
var j = this.params;
if (j.hash == void 0 && j.cert == void 0) {
throw new d("hash or cert not specified");
}
var h = null;
if (j.hash != void 0) {
h = j.hash;
} else {
if (j.cert != void 0) {
if (typeof j.cert != "string") {
throw new d("cert not string");
}
var i = j.cert;
if (j.cert.indexOf("-----BEGIN") != -1) {
i = pemtohex(j.cert);
}
h = KJUR.crypto.Util.hashHex(i, "sha1");
}
}
return new e2({ hex: h }).tohex();
};
this.getEncodedHex = function() {
return this.tohex();
};
if (g != void 0) {
this.setByParam(g);
}
};
extendClass(KJUR.asn1.cades.OtherHashValue, KJUR.asn1.ASN1Object);
KJUR.asn1.cades.SignatureTimeStamp = function(h) {
var d = Error, c = KJUR, f = c.lang.String.isHex, b = c.asn1, e2 = b.ASN1Object, g = b.x509, a = b.cades;
a.SignatureTimeStamp.superclass.constructor.call(this);
this.typeOid = "1.2.840.113549.1.9.16.2.14";
this.params = null;
this.getValueArray = function() {
var l = this.params;
if (l.tst != void 0) {
if (f(l.tst)) {
var j = new e2();
j.hTLV = l.tst;
return [j];
} else {
if (l.tst instanceof e2) {
return [l.tst];
} else {
throw new d("params.tst has wrong value");
}
}
} else {
if (l.res != void 0) {
var k = l.res;
if (k instanceof e2) {
k = k.tohex();
}
if (typeof k != "string" || !f(k)) {
throw new d("params.res has wrong value");
}
var i = ASN1HEX.getTLVbyList(k, 0, [1]);
var j = new e2();
j.hTLV = l.tst;
return [j];
}
}
};
if (h != null) {
this.setByParam(h);
}
};
extendClass(KJUR.asn1.cades.SignatureTimeStamp, KJUR.asn1.cms.Attribute);
KJUR.asn1.cades.CompleteCertificateRefs = function(h) {
var f = Error, e2 = KJUR, d = e2.asn1, b = d.DERSequence, c = d.cades, a = c.OtherCertID, g = e2.lang.String.isHex;
c.CompleteCertificateRefs.superclass.constructor.call(this);
this.typeOid = "1.2.840.113549.1.9.16.2.21";
this.params = null;
this.getValueArray = function() {
var o2 = this.params;
var k = [];
for (var m = 0; m < o2.array.length; m++) {
var n2 = o2.array[m];
if (typeof n2 == "string") {
if (n2.indexOf("-----BEGIN") != -1) {
n2 = { cert: n2 };
} else {
if (g(n2)) {
n2 = { hash: n2 };
} else {
throw new f("unsupported value: " + n2);
}
}
}
if (o2.alg != void 0 && n2.alg == void 0) {
n2.alg = o2.alg;
}
if (o2.hasis != void 0 && n2.hasis == void 0) {
n2.hasis = o2.hasis;
}
var j = new a(n2);
k.push(j);
}
var l = new b({ array: k });
return [l];
};
if (h != void 0) {
this.setByParam(h);
}
};
extendClass(KJUR.asn1.cades.CompleteCertificateRefs, KJUR.asn1.cms.Attribute);
KJUR.asn1.cades.OtherCertID = function(e2) {
var a = KJUR, h = a.asn1, f = h.DERSequence, i = h.cms, g = i.IssuerSerial, c = h.cades, d = c.OtherHashValue, b = c.OtherHashAlgAndValue;
c.OtherCertID.superclass.constructor.call(this);
this.params = e2;
this.tohex = function() {
var n2 = this.params;
if (typeof n2 == "string") {
if (n2.indexOf("-----BEGIN") != -1) {
n2 = { cert: n2 };
} else {
if (_isHex(n2)) {
n2 = { hash: n2 };
}
}
}
var j = [];
var m = null;
if (n2.alg != void 0) {
m = new b(n2);
} else {
m = new d(n2);
}
j.push(m);
if (n2.cert != void 0 && n2.hasis == true || n2.issuer != void 0 && n2.serial != void 0) {
var l = new g(n2);
j.push(l);
}
var k = new f({ array: j });
return k.tohex();
};
this.getEncodedHex = function() {
return this.tohex();
};
if (e2 != void 0) {
this.setByParam(e2);
}
};
extendClass(KJUR.asn1.cades.OtherCertID, KJUR.asn1.ASN1Object);
KJUR.asn1.cades.OtherHash = function(g) {
var i = Error, a = KJUR, h = a.asn1, j = h.cms, c = h.cades, b = c.OtherHashAlgAndValue, e2 = c.OtherHashValue, d = a.crypto.Util.hashHex, f = a.lang.String.isHex;
c.OtherHash.superclass.constructor.call(this);
this.params = null;
this.tohex = function() {
var l = this.params;
if (typeof l == "string") {
if (l.indexOf("-----BEGIN") != -1) {
l = { cert: l };
} else {
if (f(l)) {
l = { hash: l };
}
}
}
var k = null;
if (l.alg != void 0) {
k = new b(l);
} else {
k = new e2(l);
}
return k.tohex();
};
this.getEncodedHex = function() {
return this.tohex();
};
if (g != void 0) {
this.setByParam(g);
}
};
extendClass(KJUR.asn1.cades.OtherHash, KJUR.asn1.ASN1Object);
KJUR.asn1.cades.CAdESUtil = new function() {
}();
KJUR.asn1.cades.CAdESUtil.parseSignedDataForAddingUnsigned = function(a) {
var c = new KJUR.asn1.cms.CMSParser();
var b = c.getCMSSignedData(a);
return b;
};
KJUR.asn1.cades.CAdESUtil.parseSignerInfoForAddingUnsigned = function(g, q, c) {
var p = ASN1HEX, s = p.getChildIdx, a = p.getTLV, l = p.getV, v = KJUR, h = v.asn1, n2 = h.ASN1Object, j = h.cms, k = j.AttributeList, w = j.SignerInfo;
var o2 = {};
var t3 = s(g, q);
if (t3.length != 6) {
throw "not supported items for SignerInfo (!=6)";
}
var d = t3.shift();
o2.version = a(g, d);
var e2 = t3.shift();
o2.si = a(g, e2);
var m = t3.shift();
o2.digalg = a(g, m);
var f = t3.shift();
o2.sattrs = a(g, f);
var i = t3.shift();
o2.sigalg = a(g, i);
var b = t3.shift();
o2.sig = a(g, b);
o2.sigval = l(g, b);
var u = null;
o2.obj = new w();
u = new n2();
u.hTLV = o2.version;
o2.obj.dCMSVersion = u;
u = new n2();
u.hTLV = o2.si;
o2.obj.dSignerIdentifier = u;
u = new n2();
u.hTLV = o2.digalg;
o2.obj.dDigestAlgorithm = u;
u = new n2();
u.hTLV = o2.sattrs;
o2.obj.dSignedAttrs = u;
u = new n2();
u.hTLV = o2.sigalg;
o2.obj.dSigAlg = u;
u = new n2();
u.hTLV = o2.sig;
o2.obj.dSig = u;
o2.obj.dUnsignedAttrs = new k();
return o2;
};
if (typeof KJUR.asn1.csr == "undefined" || !KJUR.asn1.csr) {
KJUR.asn1.csr = {};
}
KJUR.asn1.csr.CertificationRequest = function(g) {
var d = KJUR, c = d.asn1, e2 = c.DERBitString, b = c.DERSequence, a = c.csr, f = c.x509, h = a.CertificationRequestInfo;
a.CertificationRequest.superclass.constructor.call(this);
this.setByParam = function(i) {
this.params = i;
};
this.sign = function() {
var j = new h(this.params).tohex();
var k = new KJUR.crypto.Signature({ alg: this.params.sigalg });
k.init(this.params.sbjprvkey);
k.updateHex(j);
var i = k.sign();
this.params.sighex = i;
};
this.getPEM = function() {
return hextopem(this.tohex(), "CERTIFICATE REQUEST");
};
this.tohex = function() {
var l = this.params;
var j = new KJUR.asn1.csr.CertificationRequestInfo(this.params);
var m = new KJUR.asn1.x509.AlgorithmIdentifier({ name: l.sigalg });
if (l.sighex == void 0 && l.sbjprvkey != void 0) {
this.sign();
}
if (l.sighex == void 0) {
throw new Error("sighex or sbjprvkey parameter not defined");
}
var k = new e2({ hex: "00" + l.sighex });
var i = new b({ array: [j, m, k] });
return i.tohex();
};
this.getEncodedHex = function() {
return this.tohex();
};
if (g !== void 0) {
this.setByParam(g);
}
};
extendClass(KJUR.asn1.csr.CertificationRequest, KJUR.asn1.ASN1Object);
KJUR.asn1.csr.CertificationRequestInfo = function(f) {
var b = KJUR, j = b.asn1, c = j.DERBitString, g = j.DERSequence, i = j.DERInteger, p = j.DERUTF8String, d = j.DERTaggedObject, h = j.ASN1Util.newObject, n2 = j.csr, e2 = j.x509, a = e2.X500Name, l = e2.Extensions, o2 = e2.SubjectPublicKeyInfo, k = n2.AttributeList;
n2.CertificationRequestInfo.superclass.constructor.call(this);
this.params = null;
this.setByParam = function(q) {
if (q != void 0) {
this.params = q;
}
};
this.tohex = function() {
var v = this.params;
var r2 = [];
r2.push(new i({ "int": 0 }));
r2.push(new a(v.subject));
r2.push(new o2(KEYUTIL.getKey(v.sbjpubkey)));
if (v.attrs != void 0) {
var u = m(v.attrs);
var t3 = h({ tag: { tage: "a0", obj: u } });
r2.push(t3);
} else {
if (v.extreq != void 0) {
var q = new l(v.extreq);
var t3 = h({ tag: { tage: "a0", obj: { seq: [{ oid: "1.2.840.113549.1.9.14" }, { set: [q] }] } } });
r2.push(t3);
} else {
r2.push(new d({ tag: "a0", explicit: false, obj: new p({ str: "" }) }));
}
}
var s = new g({ array: r2 });
return s.tohex();
};
this.getEncodedHex = function() {
return this.tohex();
};
function m(s) {
var w = Error, v = KJUR.asn1.x509.Extensions;
var y = [];
for (var u = 0; u < s.length; u++) {
var r2 = s[u];
var x = r2.attr;
if (x == "extensionRequest") {
var t3 = new v(r2.ext);
var q = { seq: [{ oid: "1.2.840.113549.1.9.14" }, { set: [t3] }] };
y.push(q);
} else {
if (x == "unstructuredName") {
var q = { seq: [{ oid: "1.2.840.113549.1.9.2" }, { set: r2.names }] };
y.push(q);
} else {
if (x == "challengePassword") {
var q = { seq: [{ oid: "1.2.840.113549.1.9.7" }, { set: [{ utf8str: r2.password }] }] };
y.push(q);
} else {
throw new w("unknown CSR attribute");
}
}
}
}
return { set: y };
}
if (f != void 0) {
this.setByParam(f);
}
};
extendClass(KJUR.asn1.csr.CertificationRequestInfo, KJUR.asn1.ASN1Object);
KJUR.asn1.csr.AttributeList = function(b) {
function a(c) {
}
};
extendClass(KJUR.asn1.csr.AttributeList, KJUR.asn1.ASN1Object);
KJUR.asn1.csr.CSRUtil = new function() {
}();
KJUR.asn1.csr.CSRUtil.newCSRPEM = function(e2) {
var b = KEYUTIL, a = KJUR.asn1.csr;
var c = new a.CertificationRequest(e2);
var d = c.getPEM();
return d;
};
KJUR.asn1.csr.CSRUtil.getParam = function(d, a) {
var m = ASN1HEX, i = m.getV, j = m.getIdxbyList, b = m.getTLVbyList, o2 = m.getTLVbyListEx, n2 = m.getVbyListEx;
var l = function(u) {
var t3 = j(u, 0, [0, 3, 0, 0], "06");
if (i(u, t3) != "2a864886f70d01090e") {
return null;
}
return b(u, 0, [0, 3, 0, 1, 0], "30");
};
var g = {};
if (d.indexOf("-----BEGIN CERTIFICATE REQUEST") == -1) {
throw new Error("argument is not PEM file");
}
var e2 = pemtohex(d, "CERTIFICATE REQUEST");
if (a) {
g.tbs = b(e2, 0, [0]);
}
try {
var p = o2(e2, 0, [0, 1]);
if (p == "3000") {
g.subject = {};
} else {
var f = new X509();
g.subject = f.getX500Name(p);
}
} catch (q) {
}
var k = o2(e2, 0, [0, 2]);
var r2 = KEYUTIL.getKey(k, null, "pkcs8pub");
g.sbjpubkey = KEYUTIL.getPEM(r2, "PKCS8PUB");
var c = l(e2);
var f = new X509();
if (c != null) {
g.extreq = f.getExtParamArray(c);
}
try {
var h = o2(e2, 0, [1], "30");
var f = new X509();
g.sigalg = f.getAlgorithmIdentifierName(h);
} catch (q) {
}
try {
var s = n2(e2, 0, [2]);
g.sighex = s;
} catch (q) {
}
return g;
};
KJUR.asn1.csr.CSRUtil.verifySignature = function(b) {
try {
var c = null;
if (typeof b == "string" && b.indexOf("-----BEGIN CERTIFICATE REQUEST") != -1) {
c = KJUR.asn1.csr.CSRUtil.getParam(b, true);
} else {
if (typeof b == "object" && b.sbjpubkey != void 0 && b.sigalg != void 0 && b.sighex != void 0 && b.tbs != void 0) {
c = b;
}
}
if (c == null) {
return false;
}
var d = new KJUR.crypto.Signature({ alg: c.sigalg });
d.init(c.sbjpubkey);
d.updateHex(c.tbs);
return d.verify(c.sighex);
} catch (a) {
alert(a);
return false;
}
};
if (typeof KJUR == "undefined" || !KJUR) {
KJUR = {};
}
if (typeof KJUR.asn1 == "undefined" || !KJUR.asn1) {
KJUR.asn1 = {};
}
if (typeof KJUR.asn1.ocsp == "undefined" || !KJUR.asn1.ocsp) {
KJUR.asn1.ocsp = {};
}
KJUR.asn1.ocsp.DEFAULT_HASH = "sha1";
KJUR.asn1.ocsp.OCSPResponse = function(e2) {
KJUR.asn1.ocsp.OCSPResponse.superclass.constructor.call(this);
var a = KJUR.asn1.DEREnumerated, b = KJUR.asn1.ASN1Util.newObject, c = KJUR.asn1.ocsp.ResponseBytes;
var d = ["successful", "malformedRequest", "internalError", "tryLater", "_not_used_", "sigRequired", "unauthorized"];
this.params = null;
this._getStatusCode = function() {
var f = this.params.resstatus;
if (typeof f == "number") {
return f;
}
if (typeof f != "string") {
return -1;
}
return d.indexOf(f);
};
this.setByParam = function(f) {
this.params = f;
};
this.tohex = function() {
var h = this.params;
var g = this._getStatusCode();
if (g == -1) {
throw new Error("responseStatus not supported: " + h.resstatus);
}
if (g != 0) {
return b({ seq: [{ "enum": { "int": g } }] }).tohex();
}
var f = new c(h);
return b({ seq: [{ "enum": { "int": 0 } }, { tag: { tag: "a0", explicit: true, obj: f } }] }).tohex();
};
this.getEncodedHex = function() {
return this.tohex();
};
if (e2 !== void 0) {
this.setByParam(e2);
}
};
extendClass(KJUR.asn1.ocsp.OCSPResponse, KJUR.asn1.ASN1Object);
KJUR.asn1.ocsp.ResponseBytes = function(e2) {
KJUR.asn1.ocsp.ResponseBytes.superclass.constructor.call(this);
var b = KJUR.asn1, a = b.DERSequence, f = b.DERObjectIdentifier, c = b.DEROctetString, d = b.ocsp.BasicOCSPResponse;
this.params = null;
this.setByParam = function(g) {
this.params = g;
};
this.tohex = function() {
var j = this.params;
if (j.restype != "ocspBasic") {
throw new Error("not supported responseType: " + j.restype);
}
var i = new d(j);
var g = [];
g.push(new f({ name: "ocspBasic" }));
g.push(new c({ hex: i.tohex() }));
var h = new a({ array: g });
return h.tohex();
};
this.getEncodedHex = function() {
return this.tohex();
};
if (e2 !== void 0) {
this.setByParam(e2);
}
};
extendClass(KJUR.asn1.ocsp.ResponseBytes, KJUR.asn1.ASN1Object);
KJUR.asn1.ocsp.BasicOCSPResponse = function(d) {
KJUR.asn1.ocsp.BasicOCSPResponse.superclass.constructor.call(this);
var i = Error, g = KJUR.asn1, j = g.ASN1Object, e2 = g.DERSequence, f = g.DERGeneralizedTime, c = g.DERTaggedObject, b = g.DERBitString, h = g.x509.Extensions, k = g.x509.AlgorithmIdentifier, l = g.ocsp, a = l.ResponderID;
_SingleResponseList = l.SingleResponseList, _ResponseData = l.ResponseData;
this.params = null;
this.setByParam = function(m) {
this.params = m;
};
this.sign = function() {
var o2 = this.params;
var m = o2.tbsresp.tohex();
var n2 = new KJUR.crypto.Signature({ alg: o2.sigalg });
n2.init(o2.reskey);
n2.updateHex(m);
o2.sighex = n2.sign();
};
this.tohex = function() {
var t3 = this.params;
if (t3.tbsresp == void 0) {
t3.tbsresp = new _ResponseData(t3);
}
if (t3.sighex == void 0 && t3.reskey != void 0) {
this.sign();
}
var n2 = [];
n2.push(t3.tbsresp);
n2.push(new k({ name: t3.sigalg }));
n2.push(new b({ hex: "00" + t3.sighex }));
if (t3.certs != void 0 && t3.certs.length != void 0) {
var m = [];
for (var q = 0; q < t3.certs.length; q++) {
var s = t3.certs[q];
var r2 = null;
if (ASN1HEX.isASN1HEX(s)) {
r2 = s;
} else {
if (s.match(/-----BEGIN/)) {
r2 = pemtohex(s);
} else {
throw new i("certs[" + q + "] not hex or PEM");
}
}
m.push(new j({ tlv: r2 }));
}
var p = new e2({ array: m });
n2.push(new c({ tag: "a0", explicit: true, obj: p }));
}
var o2 = new e2({ array: n2 });
return o2.tohex();
};
this.getEncodedHex = function() {
return this.tohex();
};
if (d !== void 0) {
this.setByParam(d);
}
};
extendClass(KJUR.asn1.ocsp.BasicOCSPResponse, KJUR.asn1.ASN1Object);
KJUR.asn1.ocsp.ResponseData = function(c) {
KJUR.asn1.ocsp.ResponseData.superclass.constructor.call(this);
var h = Error, f = KJUR.asn1, d = f.DERSequence, e2 = f.DERGeneralizedTime, b = f.DERTaggedObject, g = f.x509.Extensions, i = f.ocsp, a = i.ResponderID;
_SingleResponseList = i.SingleResponseList;
this.params = null;
this.tohex = function() {
var m = this.params;
if (m.respid != void 0) {
new h("respid not specified");
}
if (m.prodat != void 0) {
new h("prodat not specified");
}
if (m.array != void 0) {
new h("array not specified");
}
var j = [];
j.push(new a(m.respid));
j.push(new e2(m.prodat));
j.push(new _SingleResponseList(m.array));
if (m.ext != void 0) {
var l = new g(m.ext);
j.push(new b({ tag: "a1", explicit: true, obj: l }));
}
var k = new d({ array: j });
return k.tohex();
};
this.getEncodedHex = function() {
return this.tohex();
};
this.setByParam = function(j) {
this.params = j;
};
if (c !== void 0) {
this.setByParam(c);
}
};
extendClass(KJUR.asn1.ocsp.ResponseData, KJUR.asn1.ASN1Object);
KJUR.asn1.ocsp.ResponderID = function(g) {
KJUR.asn1.ocsp.ResponderID.superclass.constructor.call(this);
var d = KJUR, c = d.asn1, b = c.ASN1Util.newObject, f = c.x509.X500Name, e2 = d.lang.String.isHex, a = Error;
this.params = null;
this.tohex = function() {
var m = this.params;
if (m.key != void 0) {
var l = null;
if (typeof m.key == "string") {
if (e2(m.key)) {
l = m.key;
}
if (m.key.match(/-----BEGIN CERTIFICATE/)) {
var h = new X509(m.key);
var k = h.getExtSubjectKeyIdentifier();
if (k != null) {
l = k.kid.hex;
}
}
} else {
if (m.key instanceof X509) {
var k = m.key.getExtSubjectKeyIdentifier();
if (k != null) {
l = k.kid.hex;
}
}
}
if (l == null) {
throw new a("wrong key member value");
}
var j = b({ tag: { tag: "a2", explicit: true, obj: { octstr: { hex: l } } } });
return j.tohex();
} else {
if (m.name != void 0) {
var i = null;
if (typeof m.name == "string" && m.name.match(/-----BEGIN CERTIFICATE/)) {
var h = new X509(m.name);
i = h.getSubject();
} else {
if (m.name instanceof X509) {
i = m.name.getSubject();
} else {
if (typeof m.name == "object" && (m.name.array != void 0 || m.name.str != void 0)) {
i = m.name;
}
}
}
if (i == null) {
throw new a("wrong name member value");
}
var j = b({ tag: { tag: "a1", explicit: true, obj: new f(i) } });
return j.tohex();
}
}
throw new a("key or name not specified");
};
this.getEncodedHex = function() {
return this.tohex();
};
this.setByParam = function(h) {
this.params = h;
};
if (g !== void 0) {
this.setByParam(g);
}
};
extendClass(KJUR.asn1.ocsp.ResponderID, KJUR.asn1.ASN1Object);
KJUR.asn1.ocsp.SingleResponseList = function(d) {
KJUR.asn1.ocsp.SingleResponseList.superclass.constructor.call(this);
var c = KJUR.asn1, b = c.DERSequence, a = c.ocsp.SingleResponse;
this.params = null;
this.tohex = function() {
var h = this.params;
if (typeof h != "object" || h.length == void 0) {
throw new Error("params not specified properly");
}
var e2 = [];
for (var g = 0; g < h.length; g++) {
e2.push(new a(h[g]));
}
var f = new b({ array: e2 });
return f.tohex();
};
this.getEncodedHex = function() {
return this.tohex();
};
this.setByParam = function(e2) {
this.params = e2;
};
if (d !== void 0) {
this.setByParam(d);
}
};
extendClass(KJUR.asn1.ocsp.SingleResponseList, KJUR.asn1.ASN1Object);
KJUR.asn1.ocsp.SingleResponse = function(e2) {
var k = Error, a = KJUR, i = a.asn1, f = i.DERSequence, g = i.DERGeneralizedTime, b = i.DERTaggedObject, l = i.ocsp, h = l.CertID, c = l.CertStatus, d = i.x509, j = d.Extensions;
l.SingleResponse.superclass.constructor.call(this);
this.params = null;
this.tohex = function() {
var q = this.params;
var n2 = [];
if (q.certid == void 0) {
throw new k("certid unspecified");
}
if (q.status == void 0) {
throw new k("status unspecified");
}
if (q.thisupdate == void 0) {
throw new k("thisupdate unspecified");
}
n2.push(new h(q.certid));
n2.push(new c(q.status));
n2.push(new g(q.thisupdate));
if (q.nextupdate != void 0) {
var m = new g(q.nextupdate);
n2.push(new b({ tag: "a0", explicit: true, obj: m }));
}
if (q.ext != void 0) {
var p = new j(q.ext);
n2.push(new b({ tag: "a1", explicit: true, obj: p }));
}
var o2 = new f({ array: n2 });
return o2.tohex();
};
this.getEncodedHex = function() {
return this.tohex();
};
this.setByParam = function(m) {
this.params = m;
};
if (e2 !== void 0) {
this.setByParam(e2);
}
};
extendClass(KJUR.asn1.ocsp.SingleResponse, KJUR.asn1.ASN1Object);
KJUR.asn1.ocsp.CertID = function(e2) {
var b = KJUR, i = b.asn1, l = i.DEROctetString, h = i.DERInteger, f = i.DERSequence, d = i.x509, m = d.AlgorithmIdentifier, n2 = i.ocsp, k = n2.DEFAULT_HASH, g = b.crypto, c = g.Util.hashHex, a = X509, o2 = ASN1HEX, j = o2.getVbyList;
n2.CertID.superclass.constructor.call(this);
this.DEFAULT_HASH = "sha1";
this.params = null;
this.setByValue = function(s, r2, p, q) {
if (q == void 0) {
q = this.DEFAULT_HASH;
}
this.params = { alg: q, issname: s, isskey: r2, sbjsn: p };
};
this.setByCert = function(p, q, r2) {
if (r2 == void 0) {
r2 = this.DEFAULT_HASH;
}
this.params = { alg: r2, issuerCert: p, subjectCert: q };
};
this.getParamByCerts = function(y, x, t3) {
if (t3 == void 0) {
t3 = this.DEFAULT_HASH;
}
var q = new a(y);
var v = new a(x);
var s = c(q.getSubjectHex(), t3);
var u = q.getPublicKeyHex();
var p = c(j(u, 0, [1], "03", true), t3);
var w = v.getSerialNumberHex();
var r2 = { alg: t3, issname: s, isskey: p, sbjsn: w };
return r2;
};
this.tohex = function() {
if (typeof this.params != "object") {
throw new Error("params not set");
}
var s = this.params;
var u, r2, y, q;
if (s.alg == void 0) {
q = this.DEFAULT_HASH;
} else {
q = s.alg;
}
if (s.issuerCert != void 0 && s.subjectCert != void 0) {
var t3 = this.getParamByCerts(s.issuerCert, s.subjectCert, q);
u = t3.issname;
r2 = t3.isskey;
y = t3.sbjsn;
} else {
if (s.issname != void 0 && s.isskey != void 0 && s.sbjsn != void 0) {
u = s.issname;
r2 = s.isskey;
y = s.sbjsn;
} else {
throw new Error("required param members not defined");
}
}
var A = new m({ name: q });
var v = new l({ hex: u });
var x = new l({ hex: r2 });
var w = new h({ hex: y });
var z2 = new f({ array: [A, v, x, w] });
this.hTLV = z2.tohex();
return this.hTLV;
};
this.getEncodedHex = function() {
return this.tohex();
};
if (e2 !== void 0) {
this.setByParam(e2);
}
};
extendClass(KJUR.asn1.ocsp.CertID, KJUR.asn1.ASN1Object);
KJUR.asn1.ocsp.CertStatus = function(a) {
KJUR.asn1.ocsp.CertStatus.superclass.constructor.call(this);
this.params = null;
this.tohex = function() {
var d = this.params;
if (d.status == "good") {
return "8000";
}
if (d.status == "unknown") {
return "8200";
}
if (d.status == "revoked") {
var c = [{ gentime: { str: d.time } }];
if (d.reason != void 0) {
c.push({ tag: { tag: "a0", explicit: true, obj: { "enum": { "int": d.reason } } } });
}
var b = { tag: "a1", explicit: false, obj: { seq: c } };
return KJUR.asn1.ASN1Util.newObject({ tag: b }).tohex();
}
throw new Error("bad status");
};
this.getEncodedHex = function() {
return this.tohex();
};
this.setByParam = function(b) {
this.params = b;
};
if (a !== void 0) {
this.setByParam(a);
}
};
extendClass(KJUR.asn1.ocsp.CertStatus, KJUR.asn1.ASN1Object);
KJUR.asn1.ocsp.Request = function(f) {
var c = KJUR, b = c.asn1, a = b.DERSequence, d = b.ocsp;
d.Request.superclass.constructor.call(this);
this.dReqCert = null;
this.dExt = null;
this.tohex = function() {
var g = [];
if (this.dReqCert === null) {
throw "reqCert not set";
}
g.push(this.dReqCert);
var h = new a({ array: g });
this.hTLV = h.tohex();
return this.hTLV;
};
this.getEncodedHex = function() {
return this.tohex();
};
if (typeof f !== "undefined") {
var e2 = new d.CertID(f);
this.dReqCert = e2;
}
};
extendClass(KJUR.asn1.ocsp.Request, KJUR.asn1.ASN1Object);
KJUR.asn1.ocsp.TBSRequest = function(e2) {
var c = KJUR, b = c.asn1, a = b.DERSequence, d = b.ocsp;
d.TBSRequest.superclass.constructor.call(this);
this.version = 0;
this.dRequestorName = null;
this.dRequestList = [];
this.dRequestExt = null;
this.setRequestListByParam = function(h) {
var f = [];
for (var g = 0; g < h.length; g++) {
var j = new d.Request(h[0]);
f.push(j);
}
this.dRequestList = f;
};
this.tohex = function() {
var f = [];
if (this.version !== 0) {
throw "not supported version: " + this.version;
}
if (this.dRequestorName !== null) {
throw "requestorName not supported";
}
var h = new a({ array: this.dRequestList });
f.push(h);
if (this.dRequestExt !== null) {
throw "requestExtensions not supported";
}
var g = new a({ array: f });
this.hTLV = g.tohex();
return this.hTLV;
};
this.getEncodedHex = function() {
return this.tohex();
};
if (e2 !== void 0) {
if (e2.reqList !== void 0) {
this.setRequestListByParam(e2.reqList);
}
}
};
extendClass(KJUR.asn1.ocsp.TBSRequest, KJUR.asn1.ASN1Object);
KJUR.asn1.ocsp.OCSPRequest = function(f) {
var c = KJUR, b = c.asn1, a = b.DERSequence, d = b.ocsp;
d.OCSPRequest.superclass.constructor.call(this);
this.dTbsRequest = null;
this.dOptionalSignature = null;
this.tohex = function() {
var g = [];
if (this.dTbsRequest !== null) {
g.push(this.dTbsRequest);
} else {
throw "tbsRequest not set";
}
if (this.dOptionalSignature !== null) {
throw "optionalSignature not supported";
}
var h = new a({ array: g });
this.hTLV = h.tohex();
return this.hTLV;
};
this.getEncodedHex = function() {
return this.tohex();
};
if (f !== void 0) {
if (f.reqList !== void 0) {
var e2 = new d.TBSRequest(f);
this.dTbsRequest = e2;
}
}
};
extendClass(KJUR.asn1.ocsp.OCSPRequest, KJUR.asn1.ASN1Object);
KJUR.asn1.ocsp.OCSPUtil = {};
KJUR.asn1.ocsp.OCSPUtil.getRequestHex = function(a, b, h) {
var d = KJUR, c = d.asn1, e2 = c.ocsp;
if (h === void 0) {
h = e2.DEFAULT_HASH;
}
var g = { alg: h, issuerCert: a, subjectCert: b };
var f = new e2.OCSPRequest({ reqList: [g] });
return f.tohex();
};
KJUR.asn1.ocsp.OCSPUtil.getOCSPResponseInfo = function(b) {
var m = ASN1HEX, c = m.getVbyList, k = m.getVbyListEx, e2 = m.getIdxbyList, d = m.getIdxbyListEx, g = m.getV;
var n2 = {};
try {
var j = k(b, 0, [0], "0a");
n2.responseStatus = parseInt(j, 16);
} catch (f) {
}
if (n2.responseStatus !== 0) {
return n2;
}
try {
var i = e2(b, 0, [1, 0, 1, 0, 0, 2, 0, 1]);
if (b.substr(i, 2) === "80") {
n2.certStatus = "good";
} else {
if (b.substr(i, 2) === "a1") {
n2.certStatus = "revoked";
n2.revocationTime = hextoutf8(c(b, i, [0]));
} else {
if (b.substr(i, 2) === "82") {
n2.certStatus = "unknown";
}
}
}
} catch (f) {
}
try {
var a = e2(b, 0, [1, 0, 1, 0, 0, 2, 0, 2]);
n2.thisUpdate = hextoutf8(g(b, a));
} catch (f) {
}
try {
var l = e2(b, 0, [1, 0, 1, 0, 0, 2, 0, 3]);
if (b.substr(l, 2) === "a0") {
n2.nextUpdate = hextoutf8(c(b, l, [0]));
}
} catch (f) {
}
return n2;
};
KJUR.asn1.ocsp.OCSPParser = function() {
var g = Error, a = X509, h = new a(), l = ASN1HEX, i = l.getV, b = l.getTLV, f = l.getIdxbyList, e2 = l.getVbyList, c = l.getTLVbyList, k = l.getVbyListEx, d = l.getTLVbyListEx, j = l.getChildIdx;
this.getOCSPRequest = function(o2) {
var n2 = j(o2, 0);
if (n2.length != 1 && n2.length != 2) {
throw new g("wrong number elements: " + n2.length);
}
var m = this.getTBSRequest(b(o2, n2[0]));
return m;
};
this.getTBSRequest = function(o2) {
var m = {};
var n2 = d(o2, 0, [0], "30");
m.array = this.getRequestList(n2);
var p = d(o2, 0, ["[2]", 0], "30");
if (p != null) {
m.ext = h.getExtParamArray(p);
}
return m;
};
this.getRequestList = function(p) {
var m = [];
var n2 = j(p, 0);
for (var o2 = 0; o2 < n2.length; o2++) {
var p = b(p, n2[o2]);
m.push(this.getRequest(p));
}
return m;
};
this.getRequest = function(n2) {
var m = j(n2, 0);
if (m.length != 1 && m.length != 2) {
throw new g("wrong number elements: " + m.length);
}
var p = this.getCertID(b(n2, m[0]));
if (m.length == 2) {
var o2 = f(n2, 0, [1, 0]);
p.ext = h.getExtParamArray(b(n2, o2));
}
return p;
};
this.getCertID = function(p) {
var o2 = j(p, 0);
if (o2.length != 4) {
throw new g("wrong number elements: " + o2.length);
}
var n2 = new a();
var m = {};
m.alg = n2.getAlgorithmIdentifierName(b(p, o2[0]));
m.issname = i(p, o2[1]);
m.isskey = i(p, o2[2]);
m.sbjsn = i(p, o2[3]);
return m;
};
this.getOCSPResponse = function(r2) {
var o2 = j(r2, 0);
var m;
var q = i(r2, o2[0]);
var p = parseInt(q);
if (o2.length == 1) {
return { resstatus: p };
}
var n2 = c(r2, 0, [1, 0]);
m = this.getResponseBytes(n2);
m.resstatus = p;
return m;
};
this.getResponseBytes = function(p) {
var o2 = j(p, 0);
var n2;
var q = c(p, 0, [1, 0]);
n2 = this.getBasicOCSPResponse(q);
var m = i(p, o2[0]);
n2.restype = KJUR.asn1.x509.OID.oid2name(hextooid(m));
return n2;
};
this.getBasicOCSPResponse = function(q) {
var t3 = j(q, 0);
var v;
v = this.getResponseData(b(q, t3[0]));
var u = new X509();
v.alg = u.getAlgorithmIdentifierName(b(q, t3[1]));
var n2 = i(q, t3[2]);
v.sighex = n2.substr(2);
var m = k(q, 0, ["[0]"]);
if (m != null) {
var r2 = j(m, 0);
var o2 = [];
for (var p = 0; p < r2.length; p++) {
var s = b(m, r2[p]);
o2.push(s);
}
v.certs = o2;
}
return v;
};
this.getResponseData = function(q) {
var p = j(q, 0);
var r2 = p.length;
var o2 = {};
var n2 = 0;
if (q.substr(p[0], 2) == "a0") {
n2++;
}
o2.respid = this.getResponderID(b(q, p[n2++]));
var t3 = i(q, p[n2++]);
o2.prodat = hextoutf8(t3);
o2.array = this.getSingleResponseList(b(q, p[n2++]));
if (q.substr(p[r2 - 1], 2) == "a1") {
var s = c(q, p[r2 - 1], [0]);
var m = new X509();
o2.ext = m.getExtParamArray(s);
}
return o2;
};
this.getResponderID = function(o2) {
var n2 = {};
if (o2.substr(0, 2) == "a2") {
var p = e2(o2, 0, [0]);
n2.key = p;
}
if (o2.substr(0, 2) == "a1") {
var q = c(o2, 0, [0]);
var m = new X509();
n2.name = m.getX500Name(q);
}
return n2;
};
this.getSingleResponseList = function(q) {
var n2 = j(q, 0);
var m = [];
for (var o2 = 0; o2 < n2.length; o2++) {
var r2 = this.getSingleResponse(b(q, n2[o2]));
m.push(r2);
}
return m;
};
this.getSingleResponse = function(p) {
var t3 = j(p, 0);
var v = {};
var r2 = this.getCertID(b(p, t3[0]));
v.certid = r2;
var u = this.getCertStatus(b(p, t3[1]));
v.status = u;
if (p.substr(t3[2], 2) == "18") {
var q = i(p, t3[2]);
v.thisupdate = hextoutf8(q);
}
for (var o2 = 3; o2 < t3.length; o2++) {
if (p.substr(t3[o2], 2) == "a0") {
var m = e2(p, t3[o2], [0], "18");
v.nextupdate = hextoutf8(m);
}
if (p.substr(t3[o2], 2) == "a1") {
var s = new X509();
var n2 = c(p, 0, [o2, 0]);
v.ext = s.getExtParamArray(n2);
}
}
return v;
};
this.getCertStatus = function(p) {
var m = {};
if (p == "8000") {
return { status: "good" };
}
if (p == "8200") {
return { status: "unknown" };
}
if (p.substr(0, 2) == "a1") {
m.status = "revoked";
var o2 = e2(p, 0, [0]);
var n2 = hextoutf8(o2);
m.time = n2;
}
return m;
};
};
var KJUR;
if (typeof KJUR == "undefined" || !KJUR) {
KJUR = {};
}
if (typeof KJUR.lang == "undefined" || !KJUR.lang) {
KJUR.lang = {};
}
KJUR.lang.String = function() {
};
function stoBA(d) {
var b = new Array();
for (var c = 0; c < d.length; c++) {
b[c] = d.charCodeAt(c);
}
return b;
}
function BAtos(b) {
var d = "";
for (var c = 0; c < b.length; c++) {
d = d + String.fromCharCode(b[c]);
}
return d;
}
function BAtohex(b) {
var e2 = "";
for (var d = 0; d < b.length; d++) {
var c = b[d].toString(16);
if (c.length == 1) {
c = "0" + c;
}
e2 = e2 + c;
}
return e2;
}
function stohex(a) {
return BAtohex(stoBA(a));
}
function stob64(a) {
return hex2b64(stohex(a));
}
function stob64u(a) {
return b64tob64u(hex2b64(stohex(a)));
}
function b64utos(a) {
return BAtos(b64toBA(b64utob64(a)));
}
function b64tob64u(a) {
a = a.replace(/\=/g, "");
a = a.replace(/\+/g, "-");
a = a.replace(/\//g, "_");
return a;
}
function b64utob64(a) {
if (a.length % 4 == 2) {
a = a + "==";
} else {
if (a.length % 4 == 3) {
a = a + "=";
}
}
a = a.replace(/-/g, "+");
a = a.replace(/_/g, "/");
return a;
}
function hextob64u(a) {
if (a.length % 2 == 1) {
a = "0" + a;
}
return b64tob64u(hex2b64(a));
}
function b64utohex(a) {
return b64tohex(b64utob64(a));
}
var utf8tob64u;
var b64utoutf8;
if (typeof Buffer === "function") {
utf8tob64u = function(a) {
return b64tob64u(Buffer.from(a, "utf8").toString("base64"));
};
b64utoutf8 = function(a) {
return Buffer.from(b64utob64(a), "base64").toString("utf8");
};
} else {
utf8tob64u = function(a) {
return hextob64u(uricmptohex(encodeURIComponentAll(a)));
};
b64utoutf8 = function(a) {
return decodeURIComponent(hextouricmp(b64utohex(a)));
};
}
function utf8tob64(a) {
return hex2b64(uricmptohex(encodeURIComponentAll(a)));
}
function b64toutf8(a) {
return decodeURIComponent(hextouricmp(b64tohex(a)));
}
function utf8tohex(a) {
return uricmptohex(encodeURIComponentAll(a)).toLowerCase();
}
function hextoutf8(b) {
try {
return decodeURIComponent(hextouricmp(b));
} catch (a) {
return null;
}
}
function iso88591hextoutf8(a) {
return hextoutf8(iso88591hextoutf8hex(a));
}
function iso88591hextoutf8hex(e2) {
var c = e2.match(/.{1,2}/g);
var b = [];
for (var d = 0; d < c.length; d++) {
var f = parseInt(c[d], 16);
if (161 <= f && f <= 191) {
b.push("c2");
b.push(c[d]);
} else {
if (192 <= f && f <= 255) {
b.push("c3");
b.push((f - 64).toString(16));
} else {
b.push(c[d]);
}
}
}
return b.join("");
}
function hextorstr(c) {
var b = "";
for (var a = 0; a < c.length - 1; a += 2) {
b += String.fromCharCode(parseInt(c.substr(a, 2), 16));
}
return b;
}
function rstrtohex(c) {
var a = "";
for (var b = 0; b < c.length; b++) {
a += ("0" + c.charCodeAt(b).toString(16)).slice(-2);
}
return a;
}
function hextob64(a) {
return hex2b64(a);
}
function hextob64nl(a) {
return foldnl(hextob64(a), 64);
}
function foldnl(a, b) {
a = a.replace(new RegExp("(.{" + b + "})", "g"), "$1\r\n");
a = a.replace(/\s+$/, "");
return a;
}
function b64nltohex(b) {
var a = b.replace(/[^0-9A-Za-z\/+=]*/g, "");
var c = b64tohex(a);
return c;
}
function b64topem(b, a) {
return "-----BEGIN " + a + "-----\r\n" + foldnl(b, 64) + "\r\n-----END " + a + "-----\r\n";
}
function hextopem(a, b) {
return "-----BEGIN " + b + "-----\r\n" + foldnl(hextob64(a), 64) + "\r\n-----END " + b + "-----\r\n";
}
function pemtohex(a, b) {
if (a.indexOf("-----BEGIN ") == -1) {
throw new Error("can't find PEM header");
}
if (b !== void 0) {
a = a.replace(new RegExp("^[^]*-----BEGIN " + b + "-----"), "");
a = a.replace(new RegExp("-----END " + b + "-----[^]*$"), "");
} else {
a = a.replace(/^[^]*-----BEGIN [^-]+-----/, "");
a = a.replace(/-----END [^-]+-----[^]*$/, "");
}
return b64nltohex(a);
}
function pemtob64(a) {
if (a.indexOf("-----BEGIN ") == -1 || a.indexOf("-----END ") == -1) {
return null;
}
a = a.replace(/^[\s\S]*?-----BEGIN [^-]+-----/m, "");
a = a.replace(/-----END [\s\S]+$/m, "");
a = a.replace(/\s+/g, "");
return a.match(/^[0-9a-zA-Z+/=]+$/) ? a : null;
}
function hextoArrayBuffer(d) {
if (d.length % 2 != 0) {
throw "input is not even length";
}
if (d.match(/^[0-9A-Fa-f]+$/) == null) {
throw "input is not hexadecimal";
}
var b = new ArrayBuffer(d.length / 2);
var a = new DataView(b);
for (var c = 0; c < d.length / 2; c++) {
a.setUint8(c, parseInt(d.substr(c * 2, 2), 16));
}
return b;
}
function ArrayBuffertohex(b) {
var d = "";
var a = new DataView(b);
for (var c = 0; c < b.byteLength; c++) {
d += ("00" + a.getUint8(c).toString(16)).slice(-2);
}
return d;
}
function zulutomsec(n2) {
var l, j, m, e2, f, i, b, k;
var a, h, g, c;
n2 = timetogen(n2);
c = n2.match(/^(\d{4})(\d\d)(\d\d)(\d\d)(\d\d)(\d\d)(|\.\d+)Z$/);
if (c) {
l = parseInt(c[1]);
j = parseInt(c[2]) - 1;
m = parseInt(c[3]);
e2 = parseInt(c[4]);
f = parseInt(c[5]);
i = parseInt(c[6]);
b = 0;
h = c[7];
if (h !== "") {
g = (h.substr(1) + "00").substr(0, 3);
b = parseInt(g);
}
return Date.UTC(l, j, m, e2, f, i, b);
}
throw new Error("unsupported zulu format: " + n2);
}
function msectozulu(b) {
var h = new Date(b), i = ("0000" + h.getUTCFullYear()).slice(-4), c = ("00" + (h.getUTCMonth() + 1)).slice(-2), j = ("00" + h.getUTCDate()).slice(-2), e2 = ("00" + h.getUTCHours()).slice(-2), f = ("00" + h.getUTCMinutes()).slice(-2), g = ("00" + h.getUTCSeconds()).slice(-2), a = ("000" + h.getUTCMilliseconds()).slice(-3);
a = a.replace(/0+$/, "");
a = a != "" ? "." + a : a;
return i + c + j + e2 + f + g + a + "Z";
}
function zulutosec(a) {
return Math.round(zulutomsec(a) / 1e3);
}
function zulutodate(a) {
return new Date(zulutomsec(a));
}
function datetozulu(g, e2, f) {
var b;
var a = g.getUTCFullYear();
if (e2) {
if (a < 1950 || 2049 < a) {
throw "not proper year for UTCTime: " + a;
}
b = ("" + a).slice(-2);
} else {
b = ("000" + a).slice(-4);
}
b += ("0" + (g.getUTCMonth() + 1)).slice(-2);
b += ("0" + g.getUTCDate()).slice(-2);
b += ("0" + g.getUTCHours()).slice(-2);
b += ("0" + g.getUTCMinutes()).slice(-2);
b += ("0" + g.getUTCSeconds()).slice(-2);
if (f) {
var c = g.getUTCMilliseconds();
if (c !== 0) {
c = ("00" + c).slice(-3);
c = c.replace(/0+$/g, "");
b += "." + c;
}
}
b += "Z";
return b;
}
function timetogen(a) {
if (a.match(/^[0-9]{12}Z$/) || a.match(/^[0-9]{12}[.][0-9]*Z$/)) {
return a.match(/^[0-4]/) ? "20" + a : "19" + a;
}
return a;
}
function uricmptohex(a) {
return a.replace(/%/g, "");
}
function hextouricmp(a) {
return a.replace(/(..)/g, "%$1");
}
function ipv6tohex(g) {
var b = "malformed IPv6 address";
if (!g.match(/^[0-9A-Fa-f:]+$/)) {
throw b;
}
g = g.toLowerCase();
var d = g.split(":").length - 1;
if (d < 2) {
throw b;
}
var e2 = ":".repeat(7 - d + 2);
g = g.replace("::", e2);
var c = g.split(":");
if (c.length != 8) {
throw b;
}
for (var f = 0; f < 8; f++) {
c[f] = ("0000" + c[f]).slice(-4);
}
return c.join("");
}
function hextoipv6(d) {
if (!d.match(/^[0-9A-Fa-f]{32}$/)) {
throw new Error("malformed IPv6 address: " + d);
}
d = d.toLowerCase();
var b = d.match(/.{1,4}/g);
b = b.map(function(a) {
return a.replace(/^0+/, "");
});
b = b.map(function(a) {
return a == "" ? "0" : a;
});
d = ":" + b.join(":") + ":";
var c = d.match(/:(0:){2,}/g);
if (c == null) {
return d.slice(1, -1);
}
var e2 = c.sort().slice(-1)[0];
d = d.replace(e2.substr(0, e2.length - 1), ":");
if (d.substr(0, 2) != "::") {
d = d.substr(1);
}
if (d.substr(-2, 2) != "::") {
d = d.substr(0, d.length - 1);
}
return d;
}
function hextoip(b) {
var c = new Error("malformed hex value");
if (!b.match(/^([0-9A-Fa-f][0-9A-Fa-f]){1,}$/)) {
throw c;
}
if (b.length == 8) {
var d;
try {
d = parseInt(b.substr(0, 2), 16) + "." + parseInt(b.substr(2, 2), 16) + "." + parseInt(b.substr(4, 2), 16) + "." + parseInt(b.substr(6, 2), 16);
return d;
} catch (a) {
throw c;
}
} else {
if (b.length == 16) {
try {
return hextoip(b.substr(0, 8)) + "/" + ipprefixlen(b.substr(8));
} catch (a) {
throw c;
}
} else {
if (b.length == 32) {
return hextoipv6(b);
} else {
if (b.length == 64) {
try {
return hextoipv6(b.substr(0, 32)) + "/" + ipprefixlen(b.substr(32));
} catch (a) {
throw c;
}
return;
} else {
return b;
}
}
}
}
}
function ipprefixlen(c) {
var d = new Error("malformed mask");
var a;
try {
a = new BigInteger(c, 16).toString(2);
} catch (b) {
throw d;
}
if (!a.match(/^1*0*$/)) {
throw d;
}
return a.replace(/0+$/, "").length;
}
function iptohex(g) {
var j = new Error("malformed IP address");
g = g.toLowerCase(g);
if (!g.match(/^[0-9a-f.:/]+$/)) {
throw j;
}
if (g.match(/^[0-9.]+$/)) {
var b = g.split(".");
if (b.length !== 4) {
throw j;
}
var h = "";
try {
for (var f = 0; f < 4; f++) {
var k = parseInt(b[f]);
h += ("0" + k.toString(16)).slice(-2);
}
return h;
} catch (e2) {
throw j;
}
} else {
if (g.match(/^[0-9.]+\/[0-9]+$/)) {
var c = g.split("/");
return iptohex(c[0]) + ipnetmask(parseInt(c[1]), 32);
} else {
if (g.match(/^[0-9a-f:]+$/) && g.indexOf(":") !== -1) {
return ipv6tohex(g);
} else {
if (g.match(/^[0-9a-f:]+\/[0-9]+$/) && g.indexOf(":") !== -1) {
var c = g.split("/");
return ipv6tohex(c[0]) + ipnetmask(parseInt(c[1]), 128);
} else {
throw j;
}
}
}
}
}
function ipnetmask(d, c) {
if (c == 32 && d == 0) {
return "00000000";
}
if (c == 128 && d == 0) {
return "00000000000000000000000000000000";
}
var a = Array(d + 1).join("1") + Array(c - d + 1).join("0");
return new BigInteger(a, 2).toString(16);
}
function ucs2hextoutf8(d) {
function e2(f) {
var h = parseInt(f.substr(0, 2), 16);
var a = parseInt(f.substr(2), 16);
if (h == 0 & a < 128) {
return String.fromCharCode(a);
}
if (h < 8) {
var j = 192 | (h & 7) << 3 | (a & 192) >> 6;
var i = 128 | a & 63;
return hextoutf8(j.toString(16) + i.toString(16));
}
var j = 224 | (h & 240) >> 4;
var i = 128 | (h & 15) << 2 | (a & 192) >> 6;
var g = 128 | a & 63;
return hextoutf8(j.toString(16) + i.toString(16) + g.toString(16));
}
var c = d.match(/.{4}/g);
var b = c.map(e2);
return b.join("");
}
function encodeURIComponentAll(a) {
var d = encodeURIComponent(a);
var b = "";
for (var c = 0; c < d.length; c++) {
if (d[c] == "%") {
b = b + d.substr(c, 3);
c = c + 2;
} else {
b = b + "%" + stohex(d[c]);
}
}
return b;
}
function newline_toUnix(a) {
a = a.replace(/\r\n/mg, "\n");
return a;
}
function newline_toDos(a) {
a = a.replace(/\r\n/mg, "\n");
a = a.replace(/\n/mg, "\r\n");
return a;
}
KJUR.lang.String.isInteger = function(a) {
if (a.match(/^[0-9]+$/)) {
return true;
} else {
if (a.match(/^-[0-9]+$/)) {
return true;
} else {
return false;
}
}
};
KJUR.lang.String.isHex = function(a) {
return ishex(a);
};
function ishex(a) {
if (a.length % 2 == 0 && (a.match(/^[0-9a-f]+$/) || a.match(/^[0-9A-F]+$/))) {
return true;
} else {
return false;
}
}
KJUR.lang.String.isBase64 = function(a) {
a = a.replace(/\s+/g, "");
if (a.match(/^[0-9A-Za-z+\/]+={0,3}$/) && a.length % 4 == 0) {
return true;
} else {
return false;
}
};
KJUR.lang.String.isBase64URL = function(a) {
if (a.match(/[+/=]/)) {
return false;
}
a = b64utob64(a);
return KJUR.lang.String.isBase64(a);
};
function isBase64URLDot(a) {
if (a.match(/^[0-9A-Za-z-_.]+$/)) {
return true;
}
return false;
}
KJUR.lang.String.isIntegerArray = function(a) {
a = a.replace(/\s+/g, "");
if (a.match(/^\[[0-9,]+\]$/)) {
return true;
} else {
return false;
}
};
KJUR.lang.String.isPrintable = function(a) {
if (a.match(/^[0-9A-Za-z '()+,-./:=?]*$/) !== null) {
return true;
}
return false;
};
KJUR.lang.String.isIA5 = function(a) {
if (a.match(/^[\x20-\x21\x23-\x7f]*$/) !== null) {
return true;
}
return false;
};
KJUR.lang.String.isMail = function(a) {
if (a.match(/^[A-Za-z0-9]{1}[A-Za-z0-9_.-]*@{1}[A-Za-z0-9_.-]{1,}\.[A-Za-z0-9]{1,}$/) !== null) {
return true;
}
return false;
};
function hextoposhex(a) {
if (a.length % 2 == 1) {
return "0" + a;
}
if (a.substr(0, 1) > "7") {
return "00" + a;
}
return a;
}
function intarystrtohex(b) {
b = b.replace(/^\s*\[\s*/, "");
b = b.replace(/\s*\]\s*$/, "");
b = b.replace(/\s*/g, "");
try {
var c = b.split(/,/).map(function(g, e2, h) {
var f = parseInt(g);
if (f < 0 || 255 < f) {
throw "integer not in range 0-255";
}
var d = ("00" + f.toString(16)).slice(-2);
return d;
}).join("");
return c;
} catch (a) {
throw "malformed integer array string: " + a;
}
}
var strdiffidx = function(c, a) {
var d = c.length;
if (c.length > a.length) {
d = a.length;
}
for (var b = 0; b < d; b++) {
if (c.charCodeAt(b) != a.charCodeAt(b)) {
return b;
}
}
if (c.length != a.length) {
return d;
}
return -1;
};
function oidtohex(g) {
var f = function(a) {
var l = a.toString(16);
if (l.length == 1) {
l = "0" + l;
}
return l;
};
var e2 = function(p) {
var o2 = "";
var l = parseInt(p, 10);
var a = l.toString(2);
var m = 7 - a.length % 7;
if (m == 7) {
m = 0;
}
var r2 = "";
for (var n2 = 0; n2 < m; n2++) {
r2 += "0";
}
a = r2 + a;
for (var n2 = 0; n2 < a.length - 1; n2 += 7) {
var q = a.substr(n2, 7);
if (n2 != a.length - 7) {
q = "1" + q;
}
o2 += f(parseInt(q, 2));
}
return o2;
};
try {
if (!g.match(/^[0-9.]+$/)) {
return null;
}
var j = "";
var b = g.split(".");
var k = parseInt(b[0], 10) * 40 + parseInt(b[1], 10);
j += f(k);
b.splice(0, 2);
for (var d = 0; d < b.length; d++) {
j += e2(b[d]);
}
return j;
} catch (c) {
return null;
}
}
function hextooid(g) {
if (!ishex(g)) {
return null;
}
try {
var m = [];
var p = g.substr(0, 2);
var e2 = parseInt(p, 16);
m[0] = new String(Math.floor(e2 / 40));
m[1] = new String(e2 % 40);
var n2 = g.substr(2);
var l = [];
for (var f = 0; f < n2.length / 2; f++) {
l.push(parseInt(n2.substr(f * 2, 2), 16));
}
var k = [];
var d = "";
for (var f = 0; f < l.length; f++) {
if (l[f] & 128) {
d = d + strpad((l[f] & 127).toString(2), 7);
} else {
d = d + strpad((l[f] & 127).toString(2), 7);
k.push(new String(parseInt(d, 2)));
d = "";
}
}
var o2 = m.join(".");
if (k.length > 0) {
o2 = o2 + "." + k.join(".");
}
return o2;
} catch (j) {
return null;
}
}
function inttohex(b) {
var a = new BigInteger(String(b), 10);
return twoscompl(a);
}
function twoscompl(b) {
var g = b.toString(16);
if (g.substr(0, 1) != "-") {
if (g.length % 2 == 1) {
g = "0" + g;
} else {
if (!g.match(/^[0-7]/)) {
g = "00" + g;
}
}
return g;
}
var a = g.substr(1);
var f = a.length;
if (f % 2 == 1) {
f += 1;
} else {
if (!g.match(/^[0-7]/)) {
f += 2;
}
}
var j = "";
for (var e2 = 0; e2 < f; e2++) {
j += "f";
}
var d = new BigInteger(j, 16);
var c = d.xor(b).add(BigInteger.ONE);
g = c.toString(16).replace(/^-/, "");
return g;
}
var strpad = function(c, b, a) {
if (a == void 0) {
a = "0";
}
if (c.length >= b) {
return c;
}
return new Array(b - c.length + 1).join(a) + c;
};
function bitstrtoint(e2) {
if (e2.length % 2 != 0) {
return -1;
}
e2 = e2.toLowerCase();
if (e2.match(/^[0-9a-f]+$/) == null) {
return -1;
}
try {
var a = e2.substr(0, 2);
if (a == "00") {
return parseInt(e2.substr(2), 16);
}
var b = parseInt(a, 16);
if (b > 7) {
return -1;
}
var g = e2.substr(2);
var d = parseInt(g, 16).toString(2);
if (d == "0") {
d = "00000000";
}
d = d.slice(0, 0 - b);
var f = parseInt(d, 2);
if (f == NaN) {
return -1;
}
return f;
} catch (c) {
return -1;
}
}
function inttobitstr(e2) {
if (typeof e2 != "number") {
return null;
}
if (e2 < 0) {
return null;
}
var c = Number(e2).toString(2);
var b = 8 - c.length % 8;
if (b == 8) {
b = 0;
}
c = c + strpad("", b, "0");
var d = parseInt(c, 2).toString(16);
if (d.length % 2 == 1) {
d = "0" + d;
}
var a = "0" + b;
return a + d;
}
function bitstrtobinstr(g) {
if (typeof g != "string") {
return null;
}
if (g.length % 2 != 0) {
return null;
}
if (!g.match(/^[0-9a-f]+$/)) {
return null;
}
try {
var c = parseInt(g.substr(0, 2), 16);
if (c < 0 || 7 < c) {
return null;
}
var j = g.substr(2);
var f = "";
for (var e2 = 0; e2 < j.length; e2 += 2) {
var b = j.substr(e2, 2);
var a = parseInt(b, 16).toString(2);
a = ("0000000" + a).slice(-8);
f += a;
}
return f.substr(0, f.length - c);
} catch (d) {
return null;
}
}
function binstrtobitstr(b) {
if (typeof b != "string") {
return null;
}
if (b.match(/^[01]+$/) == null) {
return null;
}
try {
var c = parseInt(b, 2);
return inttobitstr(c);
} catch (a) {
return null;
}
}
function namearraytobinstr(e2, g) {
var f = 0;
for (var a = 0; a < e2.length; a++) {
f |= 1 << g[e2[a]];
}
var b = f.toString(2);
var c = "";
for (var a = b.length - 1; a >= 0; a--) {
c += b[a];
}
return c;
}
function aryval(e2, c, d) {
if (typeof e2 != "object") {
return void 0;
}
var c = String(c).split(".");
for (var b = 0; b < c.length && e2; b++) {
var a = c[b];
if (a.match(/^[0-9]+$/)) {
a = parseInt(a);
}
e2 = e2[a];
}
return e2 || e2 === false ? e2 : d;
}
function extendClass(c, a) {
var b = function() {
};
b.prototype = a.prototype;
c.prototype = new b();
c.prototype.constructor = c;
c.superclass = a.prototype;
if (a.prototype.constructor == Object.prototype.constructor) {
a.prototype.constructor = a;
}
}
if (typeof KJUR == "undefined" || !KJUR) {
KJUR = {};
}
if (typeof KJUR.crypto == "undefined" || !KJUR.crypto) {
KJUR.crypto = {};
}
KJUR.crypto.Util = new function() {
this.DIGESTINFOHEAD = { sha1: "3021300906052b0e03021a05000414", sha224: "302d300d06096086480165030402040500041c", sha256: "3031300d060960864801650304020105000420", sha384: "3041300d060960864801650304020205000430", sha512: "3051300d060960864801650304020305000440", md2: "3020300c06082a864886f70d020205000410", md5: "3020300c06082a864886f70d020505000410", ripemd160: "3021300906052b2403020105000414" };
this.DEFAULTPROVIDER = { md5: "cryptojs", sha1: "cryptojs", sha224: "cryptojs", sha256: "cryptojs", sha384: "cryptojs", sha512: "cryptojs", ripemd160: "cryptojs", hmacmd5: "cryptojs", hmacsha1: "cryptojs", hmacsha224: "cryptojs", hmacsha256: "cryptojs", hmacsha384: "cryptojs", hmacsha512: "cryptojs", hmacripemd160: "cryptojs", MD5withRSA: "cryptojs/jsrsa", SHA1withRSA: "cryptojs/jsrsa", SHA224withRSA: "cryptojs/jsrsa", SHA256withRSA: "cryptojs/jsrsa", SHA384withRSA: "cryptojs/jsrsa", SHA512withRSA: "cryptojs/jsrsa", RIPEMD160withRSA: "cryptojs/jsrsa", MD5withECDSA: "cryptojs/jsrsa", SHA1withECDSA: "cryptojs/jsrsa", SHA224withECDSA: "cryptojs/jsrsa", SHA256withECDSA: "cryptojs/jsrsa", SHA384withECDSA: "cryptojs/jsrsa", SHA512withECDSA: "cryptojs/jsrsa", RIPEMD160withECDSA: "cryptojs/jsrsa", SHA1withDSA: "cryptojs/jsrsa", SHA224withDSA: "cryptojs/jsrsa", SHA256withDSA: "cryptojs/jsrsa", MD5withRSAandMGF1: "cryptojs/jsrsa", SHAwithRSAandMGF1: "cryptojs/jsrsa", SHA1withRSAandMGF1: "cryptojs/jsrsa", SHA224withRSAandMGF1: "cryptojs/jsrsa", SHA256withRSAandMGF1: "cryptojs/jsrsa", SHA384withRSAandMGF1: "cryptojs/jsrsa", SHA512withRSAandMGF1: "cryptojs/jsrsa", RIPEMD160withRSAandMGF1: "cryptojs/jsrsa" };
this.CRYPTOJSMESSAGEDIGESTNAME = { md5: CryptoJS.algo.MD5, sha1: CryptoJS.algo.SHA1, sha224: CryptoJS.algo.SHA224, sha256: CryptoJS.algo.SHA256, sha384: CryptoJS.algo.SHA384, sha512: CryptoJS.algo.SHA512, ripemd160: CryptoJS.algo.RIPEMD160 };
this.getDigestInfoHex = function(a, b) {
if (typeof this.DIGESTINFOHEAD[b] == "undefined") {
throw "alg not supported in Util.DIGESTINFOHEAD: " + b;
}
return this.DIGESTINFOHEAD[b] + a;
};
this.getPaddedDigestInfoHex = function(h, a, j) {
var c = this.getDigestInfoHex(h, a);
var d = j / 4;
if (c.length + 22 > d) {
throw "key is too short for SigAlg: keylen=" + j + "," + a;
}
var b = "0001";
var k = "00" + c;
var g = "";
var l = d - b.length - k.length;
for (var f = 0; f < l; f += 2) {
g += "ff";
}
var e2 = b + g + k;
return e2;
};
this.hashString = function(a, c) {
var b = new KJUR.crypto.MessageDigest({ alg: c });
return b.digestString(a);
};
this.hashHex = function(b, c) {
var a = new KJUR.crypto.MessageDigest({ alg: c });
return a.digestHex(b);
};
this.sha1 = function(a) {
return this.hashString(a, "sha1");
};
this.sha256 = function(a) {
return this.hashString(a, "sha256");
};
this.sha256Hex = function(a) {
return this.hashHex(a, "sha256");
};
this.sha512 = function(a) {
return this.hashString(a, "sha512");
};
this.sha512Hex = function(a) {
return this.hashHex(a, "sha512");
};
this.isKey = function(a) {
if (a instanceof RSAKey || a instanceof KJUR.crypto.DSA || a instanceof KJUR.crypto.ECDSA) {
return true;
} else {
return false;
}
};
}();
KJUR.crypto.Util.md5 = function(a) {
var b = new KJUR.crypto.MessageDigest({ alg: "md5", prov: "cryptojs" });
return b.digestString(a);
};
KJUR.crypto.Util.ripemd160 = function(a) {
var b = new KJUR.crypto.MessageDigest({ alg: "ripemd160", prov: "cryptojs" });
return b.digestString(a);
};
KJUR.crypto.Util.SECURERANDOMGEN = new SecureRandom();
KJUR.crypto.Util.getRandomHexOfNbytes = function(b) {
var a = new Array(b);
KJUR.crypto.Util.SECURERANDOMGEN.nextBytes(a);
return BAtohex(a);
};
KJUR.crypto.Util.getRandomBigIntegerOfNbytes = function(a) {
return new BigInteger(KJUR.crypto.Util.getRandomHexOfNbytes(a), 16);
};
KJUR.crypto.Util.getRandomHexOfNbits = function(d) {
var c = d % 8;
var a = (d - c) / 8;
var b = new Array(a + 1);
KJUR.crypto.Util.SECURERANDOMGEN.nextBytes(b);
b[0] = (255 << c & 255 ^ 255) & b[0];
return BAtohex(b);
};
KJUR.crypto.Util.getRandomBigIntegerOfNbits = function(a) {
return new BigInteger(KJUR.crypto.Util.getRandomHexOfNbits(a), 16);
};
KJUR.crypto.Util.getRandomBigIntegerZeroToMax = function(b) {
var a = b.bitLength();
while (1) {
var c = KJUR.crypto.Util.getRandomBigIntegerOfNbits(a);
if (b.compareTo(c) != -1) {
return c;
}
}
};
KJUR.crypto.Util.getRandomBigIntegerMinToMax = function(e2, b) {
var c = e2.compareTo(b);
if (c == 1) {
throw "biMin is greater than biMax";
}
if (c == 0) {
return e2;
}
var a = b.subtract(e2);
var d = KJUR.crypto.Util.getRandomBigIntegerZeroToMax(a);
return d.add(e2);
};
KJUR.crypto.MessageDigest = function(c) {
var b = null;
var a = null;
var d = null;
this.setAlgAndProvider = function(g, f) {
g = KJUR.crypto.MessageDigest.getCanonicalAlgName(g);
if (g !== null && f === void 0) {
f = KJUR.crypto.Util.DEFAULTPROVIDER[g];
}
if (":md5:sha1:sha224:sha256:sha384:sha512:ripemd160:".indexOf(g) != -1 && f == "cryptojs") {
try {
this.md = KJUR.crypto.Util.CRYPTOJSMESSAGEDIGESTNAME[g].create();
} catch (e2) {
throw "setAlgAndProvider hash alg set fail alg=" + g + "/" + e2;
}
this.updateString = function(h) {
this.md.update(h);
};
this.updateHex = function(h) {
var i = CryptoJS.enc.Hex.parse(h);
this.md.update(i);
};
this.digest = function() {
var h = this.md.finalize();
return h.toString(CryptoJS.enc.Hex);
};
this.digestString = function(h) {
this.updateString(h);
return this.digest();
};
this.digestHex = function(h) {
this.updateHex(h);
return this.digest();
};
}
if (":sha256:".indexOf(g) != -1 && f == "sjcl") {
try {
this.md = new sjcl.hash.sha256();
} catch (e2) {
throw "setAlgAndProvider hash alg set fail alg=" + g + "/" + e2;
}
this.updateString = function(h) {
this.md.update(h);
};
this.updateHex = function(i) {
var h = sjcl.codec.hex.toBits(i);
this.md.update(h);
};
this.digest = function() {
var h = this.md.finalize();
return sjcl.codec.hex.fromBits(h);
};
this.digestString = function(h) {
this.updateString(h);
return this.digest();
};
this.digestHex = function(h) {
this.updateHex(h);
return this.digest();
};
}
};
this.updateString = function(e2) {
throw "updateString(str) not supported for this alg/prov: " + this.algName + "/" + this.provName;
};
this.updateHex = function(e2) {
throw "updateHex(hex) not supported for this alg/prov: " + this.algName + "/" + this.provName;
};
this.digest = function() {
throw "digest() not supported for this alg/prov: " + this.algName + "/" + this.provName;
};
this.digestString = function(e2) {
throw "digestString(str) not supported for this alg/prov: " + this.algName + "/" + this.provName;
};
this.digestHex = function(e2) {
throw "digestHex(hex) not supported for this alg/prov: " + this.algName + "/" + this.provName;
};
if (c !== void 0) {
if (c.alg !== void 0) {
this.algName = c.alg;
if (c.prov === void 0) {
this.provName = KJUR.crypto.Util.DEFAULTPROVIDER[this.algName];
}
this.setAlgAndProvider(this.algName, this.provName);
}
}
};
KJUR.crypto.MessageDigest.getCanonicalAlgName = function(a) {
if (typeof a === "string") {
a = a.toLowerCase();
a = a.replace(/-/, "");
}
return a;
};
KJUR.crypto.MessageDigest.getHashLength = function(c) {
var b = KJUR.crypto.MessageDigest;
var a = b.getCanonicalAlgName(c);
if (b.HASHLENGTH[a] === void 0) {
throw "not supported algorithm: " + c;
}
return b.HASHLENGTH[a];
};
KJUR.crypto.MessageDigest.HASHLENGTH = { md5: 16, sha1: 20, sha224: 28, sha256: 32, sha384: 48, sha512: 64, ripemd160: 20 };
KJUR.crypto.Mac = function(d) {
var f = null;
var c = null;
var a = null;
var e2 = null;
var b = null;
this.setAlgAndProvider = function(k, i) {
k = k.toLowerCase();
if (k == null) {
k = "hmacsha1";
}
k = k.toLowerCase();
if (k.substr(0, 4) != "hmac") {
throw "setAlgAndProvider unsupported HMAC alg: " + k;
}
if (i === void 0) {
i = KJUR.crypto.Util.DEFAULTPROVIDER[k];
}
this.algProv = k + "/" + i;
var g = k.substr(4);
if (":md5:sha1:sha224:sha256:sha384:sha512:ripemd160:".indexOf(g) != -1 && i == "cryptojs") {
try {
var j = KJUR.crypto.Util.CRYPTOJSMESSAGEDIGESTNAME[g];
this.mac = CryptoJS.algo.HMAC.create(j, this.pass);
} catch (h) {
throw "setAlgAndProvider hash alg set fail hashAlg=" + g + "/" + h;
}
this.updateString = function(l) {
this.mac.update(l);
};
this.updateHex = function(l) {
var m = CryptoJS.enc.Hex.parse(l);
this.mac.update(m);
};
this.doFinal = function() {
var l = this.mac.finalize();
return l.toString(CryptoJS.enc.Hex);
};
this.doFinalString = function(l) {
this.updateString(l);
return this.doFinal();
};
this.doFinalHex = function(l) {
this.updateHex(l);
return this.doFinal();
};
}
};
this.updateString = function(g) {
throw "updateString(str) not supported for this alg/prov: " + this.algProv;
};
this.updateHex = function(g) {
throw "updateHex(hex) not supported for this alg/prov: " + this.algProv;
};
this.doFinal = function() {
throw "digest() not supported for this alg/prov: " + this.algProv;
};
this.doFinalString = function(g) {
throw "digestString(str) not supported for this alg/prov: " + this.algProv;
};
this.doFinalHex = function(g) {
throw "digestHex(hex) not supported for this alg/prov: " + this.algProv;
};
this.setPassword = function(h) {
if (typeof h == "string") {
var g = h;
if (h.length % 2 == 1 || !h.match(/^[0-9A-Fa-f]+$/)) {
g = rstrtohex(h);
}
this.pass = CryptoJS.enc.Hex.parse(g);
return;
}
if (typeof h != "object") {
throw "KJUR.crypto.Mac unsupported password type: " + h;
}
var g = null;
if (h.hex !== void 0) {
if (h.hex.length % 2 != 0 || !h.hex.match(/^[0-9A-Fa-f]+$/)) {
throw "Mac: wrong hex password: " + h.hex;
}
g = h.hex;
}
if (h.utf8 !== void 0) {
g = utf8tohex(h.utf8);
}
if (h.rstr !== void 0) {
g = rstrtohex(h.rstr);
}
if (h.b64 !== void 0) {
g = b64tohex(h.b64);
}
if (h.b64u !== void 0) {
g = b64utohex(h.b64u);
}
if (g == null) {
throw "KJUR.crypto.Mac unsupported password type: " + h;
}
this.pass = CryptoJS.enc.Hex.parse(g);
};
if (d !== void 0) {
if (d.pass !== void 0) {
this.setPassword(d.pass);
}
if (d.alg !== void 0) {
this.algName = d.alg;
if (d.prov === void 0) {
this.provName = KJUR.crypto.Util.DEFAULTPROVIDER[this.algName];
}
this.setAlgAndProvider(this.algName, this.provName);
}
}
};
KJUR.crypto.Signature = function(o2) {
var q = null;
var n2 = null;
var r2 = null;
var c = null;
var l = null;
var d = null;
var k = null;
var h = null;
var p = null;
var e2 = null;
var b = -1;
var g = null;
var j = null;
var a = null;
var i = null;
var f = null;
this._setAlgNames = function() {
var s = this.algName.match(/^(.+)with(.+)$/);
if (s) {
this.mdAlgName = s[1].toLowerCase();
this.pubkeyAlgName = s[2].toLowerCase();
if (this.pubkeyAlgName == "rsaandmgf1" && this.mdAlgName == "sha") {
this.mdAlgName = "sha1";
}
}
};
this._zeroPaddingOfSignature = function(x, w) {
var v = "";
var t3 = w / 4 - x.length;
for (var u = 0; u < t3; u++) {
v = v + "0";
}
return v + x;
};
this.setAlgAndProvider = function(u, t3) {
this._setAlgNames();
if (t3 != "cryptojs/jsrsa") {
throw new Error("provider not supported: " + t3);
}
if (":md5:sha1:sha224:sha256:sha384:sha512:ripemd160:".indexOf(this.mdAlgName) != -1) {
try {
this.md = new KJUR.crypto.MessageDigest({ alg: this.mdAlgName });
} catch (s) {
throw new Error("setAlgAndProvider hash alg set fail alg=" + this.mdAlgName + "/" + s);
}
this.init = function(w, x) {
var y = null;
try {
if (x === void 0) {
y = KEYUTIL.getKey(w);
} else {
y = KEYUTIL.getKey(w, x);
}
} catch (v) {
throw "init failed:" + v;
}
if (y.isPrivate === true) {
this.prvKey = y;
this.state = "SIGN";
} else {
if (y.isPublic === true) {
this.pubKey = y;
this.state = "VERIFY";
} else {
throw "init failed.:" + y;
}
}
};
this.updateString = function(v) {
this.md.updateString(v);
};
this.updateHex = function(v) {
this.md.updateHex(v);
};
this.sign = function() {
this.sHashHex = this.md.digest();
if (this.prvKey === void 0 && this.ecprvhex !== void 0 && this.eccurvename !== void 0 && KJUR.crypto.ECDSA !== void 0) {
this.prvKey = new KJUR.crypto.ECDSA({ curve: this.eccurvename, prv: this.ecprvhex });
}
if (this.prvKey instanceof RSAKey && this.pubkeyAlgName === "rsaandmgf1") {
this.hSign = this.prvKey.signWithMessageHashPSS(this.sHashHex, this.mdAlgName, this.pssSaltLen);
} else {
if (this.prvKey instanceof RSAKey && this.pubkeyAlgName === "rsa") {
this.hSign = this.prvKey.signWithMessageHash(this.sHashHex, this.mdAlgName);
} else {
if (this.prvKey instanceof KJUR.crypto.ECDSA) {
this.hSign = this.prvKey.signWithMessageHash(this.sHashHex);
} else {
if (this.prvKey instanceof KJUR.crypto.DSA) {
this.hSign = this.prvKey.signWithMessageHash(this.sHashHex);
} else {
throw "Signature: unsupported private key alg: " + this.pubkeyAlgName;
}
}
}
}
return this.hSign;
};
this.signString = function(v) {
this.updateString(v);
return this.sign();
};
this.signHex = function(v) {
this.updateHex(v);
return this.sign();
};
this.verify = function(v) {
this.sHashHex = this.md.digest();
if (this.pubKey === void 0 && this.ecpubhex !== void 0 && this.eccurvename !== void 0 && KJUR.crypto.ECDSA !== void 0) {
this.pubKey = new KJUR.crypto.ECDSA({ curve: this.eccurvename, pub: this.ecpubhex });
}
if (this.pubKey instanceof RSAKey && this.pubkeyAlgName === "rsaandmgf1") {
return this.pubKey.verifyWithMessageHashPSS(this.sHashHex, v, this.mdAlgName, this.pssSaltLen);
} else {
if (this.pubKey instanceof RSAKey && this.pubkeyAlgName === "rsa") {
return this.pubKey.verifyWithMessageHash(this.sHashHex, v);
} else {
if (KJUR.crypto.ECDSA !== void 0 && this.pubKey instanceof KJUR.crypto.ECDSA) {
return this.pubKey.verifyWithMessageHash(this.sHashHex, v);
} else {
if (KJUR.crypto.DSA !== void 0 && this.pubKey instanceof KJUR.crypto.DSA) {
return this.pubKey.verifyWithMessageHash(this.sHashHex, v);
} else {
throw "Signature: unsupported public key alg: " + this.pubkeyAlgName;
}
}
}
}
};
}
};
this.init = function(s, t3) {
throw "init(key, pass) not supported for this alg:prov=" + this.algProvName;
};
this.updateString = function(s) {
throw "updateString(str) not supported for this alg:prov=" + this.algProvName;
};
this.updateHex = function(s) {
throw "updateHex(hex) not supported for this alg:prov=" + this.algProvName;
};
this.sign = function() {
throw "sign() not supported for this alg:prov=" + this.algProvName;
};
this.signString = function(s) {
throw "digestString(str) not supported for this alg:prov=" + this.algProvName;
};
this.signHex = function(s) {
throw "digestHex(hex) not supported for this alg:prov=" + this.algProvName;
};
this.verify = function(s) {
throw "verify(hSigVal) not supported for this alg:prov=" + this.algProvName;
};
this.initParams = o2;
if (o2 !== void 0) {
if (o2.alg !== void 0) {
this.algName = o2.alg;
if (o2.prov === void 0) {
this.provName = KJUR.crypto.Util.DEFAULTPROVIDER[this.algName];
} else {
this.provName = o2.prov;
}
this.algProvName = this.algName + ":" + this.provName;
this.setAlgAndProvider(this.algName, this.provName);
this._setAlgNames();
}
if (o2.psssaltlen !== void 0) {
this.pssSaltLen = o2.psssaltlen;
}
if (o2.prvkeypem !== void 0) {
if (o2.prvkeypas !== void 0) {
throw "both prvkeypem and prvkeypas parameters not supported";
} else {
try {
var q = KEYUTIL.getKey(o2.prvkeypem);
this.init(q);
} catch (m) {
throw "fatal error to load pem private key: " + m;
}
}
}
}
};
KJUR.crypto.Cipher = function(a) {
};
KJUR.crypto.Cipher.encrypt = function(j, i, b, c) {
if (aryval(c, "enclag") != void 0) {
b = c.encalg;
}
if (typeof b == "string" && b.substr(-4) == "-CBC") {
var g = i;
var e2 = j;
if (aryval(c, "key") != void 0) {
g = c.key;
}
if (aryval(c, "enc") != void 0) {
hEnc = c.enc;
}
var h = CryptoJS.enc.Hex.parse(g);
var a = CryptoJS.enc.Hex.parse(e2);
var f = CryptoJS.enc.Hex.parse(c.iv);
var d;
if (b == "des-EDE3-CBC") {
d = CryptoJS.TripleDES.encrypt(a, h, { iv: f });
} else {
if (b == "aes128-CBC" || b == "aes256-CBC") {
d = CryptoJS.AES.encrypt(a, h, { iv: f });
} else {
throw new Error("unsupported algorithm: " + b);
}
}
return d + "";
} else {
throw new Error("Cipher.encrypt: unsupported key or algorithm");
}
};
KJUR.crypto.Cipher.decrypt = function(c, j, a, b) {
if (aryval(b, "enclag") != void 0) {
a = b.encalg;
}
if (typeof a == "string" && a.substr(-4) == "-CBC") {
var h = j;
var e2 = c;
if (aryval(b, "key") != void 0) {
h = b.key;
}
if (aryval(b, "enc") != void 0) {
e2 = b.enc;
}
var i = CryptoJS.enc.Hex.parse(h);
var f = CryptoJS.enc.Hex.parse(e2);
var g = CryptoJS.enc.Hex.parse(b.iv);
var d;
if (a == "des-EDE3-CBC") {
d = CryptoJS.TripleDES.decrypt({ ciphertext: f }, i, { iv: g });
} else {
if (a == "aes128-CBC" || a == "aes256-CBC") {
d = CryptoJS.AES.decrypt({ ciphertext: f }, i, { iv: g });
} else {
throw new Error("unsupported algorithm: " + a);
}
}
return CryptoJS.enc.Hex.stringify(d);
} else {
throw new Error("Cipher.decrypt: unsupported key or algorithm");
}
};
KJUR.crypto.OID = new function() {
this.oidhex2name = { "2a864886f70d010101": "rsaEncryption", "2a8648ce3d0201": "ecPublicKey", "2a8648ce380401": "dsa", "2a8648ce3d030107": "secp256r1", "2b8104001f": "secp192k1", "2b81040021": "secp224r1", "2b8104000a": "secp256k1", "2b81040022": "secp384r1", "2b81040023": "secp521r1", "2a8648ce380403": "SHA1withDSA", "608648016503040301": "SHA224withDSA", "608648016503040302": "SHA256withDSA" };
}();
if (typeof KJUR == "undefined" || !KJUR) {
KJUR = {};
}
if (typeof KJUR.crypto == "undefined" || !KJUR.crypto) {
KJUR.crypto = {};
}
KJUR.crypto.ECDSA = function(e2) {
var g = "secp256r1";
var p = null;
var b = null;
var i = null;
var j = Error, f = BigInteger, h = ECPointFp, m = KJUR.crypto.ECDSA, c = KJUR.crypto.ECParameterDB, d = m.getName, q = ASN1HEX, n2 = q.getVbyListEx, k = q.isASN1HEX;
var a = new SecureRandom();
var o2 = null;
this.type = "EC";
this.isPrivate = false;
this.isPublic = false;
function l(x, t3, w, s) {
var r2 = Math.max(t3.bitLength(), s.bitLength());
var y = x.add2D(w);
var v = x.curve.getInfinity();
for (var u = r2 - 1; u >= 0; --u) {
v = v.twice2D();
v.z = f.ONE;
if (t3.testBit(u)) {
if (s.testBit(u)) {
v = v.add2D(y);
} else {
v = v.add2D(x);
}
} else {
if (s.testBit(u)) {
v = v.add2D(w);
}
}
}
return v;
}
this.getBigRandom = function(r2) {
return new f(r2.bitLength(), a).mod(r2.subtract(f.ONE)).add(f.ONE);
};
this.setNamedCurve = function(r2) {
this.ecparams = c.getByName(r2);
this.prvKeyHex = null;
this.pubKeyHex = null;
this.curveName = r2;
};
this.setPrivateKeyHex = function(r2) {
this.isPrivate = true;
this.prvKeyHex = r2;
};
this.setPublicKeyHex = function(r2) {
this.isPublic = true;
this.pubKeyHex = r2;
};
this.getPublicKeyXYHex = function() {
var t3 = this.pubKeyHex;
if (t3.substr(0, 2) !== "04") {
throw "this method supports uncompressed format(04) only";
}
var s = this.ecparams.keycharlen;
if (t3.length !== 2 + s * 2) {
throw "malformed public key hex length";
}
var r2 = {};
r2.x = t3.substr(2, s);
r2.y = t3.substr(2 + s);
return r2;
};
this.getShortNISTPCurveName = function() {
var r2 = this.curveName;
if (r2 === "secp256r1" || r2 === "NIST P-256" || r2 === "P-256" || r2 === "prime256v1") {
return "P-256";
}
if (r2 === "secp384r1" || r2 === "NIST P-384" || r2 === "P-384") {
return "P-384";
}
if (r2 === "secp521r1" || r2 === "NIST P-521" || r2 === "P-521") {
return "P-521";
}
return null;
};
this.generateKeyPairHex = function() {
var s = this.ecparams.n;
var u = this.getBigRandom(s);
var r2 = this.ecparams.keycharlen;
var t3 = ("0000000000" + u.toString(16)).slice(-r2);
this.setPrivateKeyHex(t3);
var v = this.generatePublicKeyHex();
return { ecprvhex: t3, ecpubhex: v };
};
this.generatePublicKeyHex = function() {
var u = new f(this.prvKeyHex, 16);
var w = this.ecparams.G.multiply(u);
var t3 = w.getX().toBigInteger();
var s = w.getY().toBigInteger();
var r2 = this.ecparams.keycharlen;
var y = ("0000000000" + t3.toString(16)).slice(-r2);
var v = ("0000000000" + s.toString(16)).slice(-r2);
var x = "04" + y + v;
this.setPublicKeyHex(x);
return x;
};
this.signWithMessageHash = function(r2) {
return this.signHex(r2, this.prvKeyHex);
};
this.signHex = function(x, u) {
var A = new f(u, 16);
var v = this.ecparams.n;
var z2 = new f(x.substring(0, this.ecparams.keycharlen), 16);
do {
var w = this.getBigRandom(v);
var B = this.ecparams.G;
var y = B.multiply(w);
var t3 = y.getX().toBigInteger().mod(v);
} while (t3.compareTo(f.ZERO) <= 0);
var C = w.modInverse(v).multiply(z2.add(A.multiply(t3))).mod(v);
return m.biRSSigToASN1Sig(t3, C);
};
this.sign = function(w, B) {
var z2 = B;
var u = this.ecparams.n;
var y = f.fromByteArrayUnsigned(w);
do {
var v = this.getBigRandom(u);
var A = this.ecparams.G;
var x = A.multiply(v);
var t3 = x.getX().toBigInteger().mod(u);
} while (t3.compareTo(BigInteger.ZERO) <= 0);
var C = v.modInverse(u).multiply(y.add(z2.multiply(t3))).mod(u);
return this.serializeSig(t3, C);
};
this.verifyWithMessageHash = function(s, r2) {
return this.verifyHex(s, r2, this.pubKeyHex);
};
this.verifyHex = function(v, y, u) {
try {
var t3, B;
var w = m.parseSigHex(y);
t3 = w.r;
B = w.s;
var x = h.decodeFromHex(this.ecparams.curve, u);
var z2 = new f(v.substring(0, this.ecparams.keycharlen), 16);
return this.verifyRaw(z2, t3, B, x);
} catch (A) {
return false;
}
};
this.verify = function(z2, A, u) {
var w, t3;
if (Bitcoin.Util.isArray(A)) {
var y = this.parseSig(A);
w = y.r;
t3 = y.s;
} else {
if ("object" === typeof A && A.r && A.s) {
w = A.r;
t3 = A.s;
} else {
throw "Invalid value for signature";
}
}
var v;
if (u instanceof ECPointFp) {
v = u;
} else {
if (Bitcoin.Util.isArray(u)) {
v = h.decodeFrom(this.ecparams.curve, u);
} else {
throw "Invalid format for pubkey value, must be byte array or ECPointFp";
}
}
var x = f.fromByteArrayUnsigned(z2);
return this.verifyRaw(x, w, t3, v);
};
this.verifyRaw = function(z2, t3, E, y) {
var x = this.ecparams.n;
var D = this.ecparams.G;
if (t3.compareTo(f.ONE) < 0 || t3.compareTo(x) >= 0) {
return false;
}
if (E.compareTo(f.ONE) < 0 || E.compareTo(x) >= 0) {
return false;
}
var A = E.modInverse(x);
var w = z2.multiply(A).mod(x);
var u = t3.multiply(A).mod(x);
var B = D.multiply(w).add(y.multiply(u));
var C = B.getX().toBigInteger().mod(x);
return C.equals(t3);
};
this.serializeSig = function(v, u) {
var w = v.toByteArraySigned();
var t3 = u.toByteArraySigned();
var x = [];
x.push(2);
x.push(w.length);
x = x.concat(w);
x.push(2);
x.push(t3.length);
x = x.concat(t3);
x.unshift(x.length);
x.unshift(48);
return x;
};
this.parseSig = function(y) {
var x;
if (y[0] != 48) {
throw new Error("Signature not a valid DERSequence");
}
x = 2;
if (y[x] != 2) {
throw new Error("First element in signature must be a DERInteger");
}
var w = y.slice(x + 2, x + 2 + y[x + 1]);
x += 2 + y[x + 1];
if (y[x] != 2) {
throw new Error("Second element in signature must be a DERInteger");
}
var t3 = y.slice(x + 2, x + 2 + y[x + 1]);
x += 2 + y[x + 1];
var v = f.fromByteArrayUnsigned(w);
var u = f.fromByteArrayUnsigned(t3);
return { r: v, s: u };
};
this.parseSigCompact = function(w) {
if (w.length !== 65) {
throw "Signature has the wrong length";
}
var t3 = w[0] - 27;
if (t3 < 0 || t3 > 7) {
throw "Invalid signature type";
}
var x = this.ecparams.n;
var v = f.fromByteArrayUnsigned(w.slice(1, 33)).mod(x);
var u = f.fromByteArrayUnsigned(w.slice(33, 65)).mod(x);
return { r: v, s: u, i: t3 };
};
this.readPKCS5PrvKeyHex = function(u) {
if (k(u) === false) {
throw new Error("not ASN.1 hex string");
}
var r2, t3, v;
try {
r2 = n2(u, 0, ["[0]", 0], "06");
t3 = n2(u, 0, [1], "04");
try {
v = n2(u, 0, ["[1]", 0], "03");
} catch (s) {
}
} catch (s) {
throw new Error("malformed PKCS#1/5 plain ECC private key");
}
this.curveName = d(r2);
if (this.curveName === void 0) {
throw "unsupported curve name";
}
this.setNamedCurve(this.curveName);
this.setPublicKeyHex(v);
this.setPrivateKeyHex(t3);
this.isPublic = false;
};
this.readPKCS8PrvKeyHex = function(v) {
if (k(v) === false) {
throw new j("not ASN.1 hex string");
}
var t3, r2, u, w;
try {
t3 = n2(v, 0, [1, 0], "06");
r2 = n2(v, 0, [1, 1], "06");
u = n2(v, 0, [2, 0, 1], "04");
try {
w = n2(v, 0, [2, 0, "[1]", 0], "03");
} catch (s) {
}
} catch (s) {
throw new j("malformed PKCS#8 plain ECC private key");
}
this.curveName = d(r2);
if (this.curveName === void 0) {
throw new j("unsupported curve name");
}
this.setNamedCurve(this.curveName);
this.setPublicKeyHex(w);
this.setPrivateKeyHex(u);
this.isPublic = false;
};
this.readPKCS8PubKeyHex = function(u) {
if (k(u) === false) {
throw new j("not ASN.1 hex string");
}
var t3, r2, v;
try {
t3 = n2(u, 0, [0, 0], "06");
r2 = n2(u, 0, [0, 1], "06");
v = n2(u, 0, [1], "03");
} catch (s) {
throw new j("malformed PKCS#8 ECC public key");
}
this.curveName = d(r2);
if (this.curveName === null) {
throw new j("unsupported curve name");
}
this.setNamedCurve(this.curveName);
this.setPublicKeyHex(v);
};
this.readCertPubKeyHex = function(t3, v) {
if (k(t3) === false) {
throw new j("not ASN.1 hex string");
}
var r2, u;
try {
r2 = n2(t3, 0, [0, 5, 0, 1], "06");
u = n2(t3, 0, [0, 5, 1], "03");
} catch (s) {
throw new j("malformed X.509 certificate ECC public key");
}
this.curveName = d(r2);
if (this.curveName === null) {
throw new j("unsupported curve name");
}
this.setNamedCurve(this.curveName);
this.setPublicKeyHex(u);
};
if (e2 !== void 0) {
if (e2.curve !== void 0) {
this.curveName = e2.curve;
}
}
if (this.curveName === void 0) {
this.curveName = g;
}
this.setNamedCurve(this.curveName);
if (e2 !== void 0) {
if (e2.prv !== void 0) {
this.setPrivateKeyHex(e2.prv);
}
if (e2.pub !== void 0) {
this.setPublicKeyHex(e2.pub);
}
}
};
KJUR.crypto.ECDSA.parseSigHex = function(a) {
var b = KJUR.crypto.ECDSA.parseSigHexInHexRS(a);
var d = new BigInteger(b.r, 16);
var c = new BigInteger(b.s, 16);
return { r: d, s: c };
};
KJUR.crypto.ECDSA.parseSigHexInHexRS = function(f) {
var j = ASN1HEX, i = j.getChildIdx, g = j.getV;
j.checkStrictDER(f, 0);
if (f.substr(0, 2) != "30") {
throw new Error("signature is not a ASN.1 sequence");
}
var h = i(f, 0);
if (h.length != 2) {
throw new Error("signature shall have two elements");
}
var e2 = h[0];
var d = h[1];
if (f.substr(e2, 2) != "02") {
throw new Error("1st item not ASN.1 integer");
}
if (f.substr(d, 2) != "02") {
throw new Error("2nd item not ASN.1 integer");
}
var c = g(f, e2);
var b = g(f, d);
return { r: c, s: b };
};
KJUR.crypto.ECDSA.asn1SigToConcatSig = function(d) {
var e2 = KJUR.crypto.ECDSA.parseSigHexInHexRS(d);
var b = e2.r;
var a = e2.s;
if (b.length >= 130 && b.length <= 134) {
if (b.length % 2 != 0) {
throw Error("unknown ECDSA sig r length error");
}
if (a.length % 2 != 0) {
throw Error("unknown ECDSA sig s length error");
}
if (b.substr(0, 2) == "00") {
b = b.substr(2);
}
if (a.substr(0, 2) == "00") {
a = a.substr(2);
}
var c = Math.max(b.length, a.length);
b = ("000000" + b).slice(-c);
a = ("000000" + a).slice(-c);
return b + a;
}
if (b.substr(0, 2) == "00" && b.length % 32 == 2) {
b = b.substr(2);
}
if (a.substr(0, 2) == "00" && a.length % 32 == 2) {
a = a.substr(2);
}
if (b.length % 32 == 30) {
b = "00" + b;
}
if (a.length % 32 == 30) {
a = "00" + a;
}
if (b.length % 32 != 0) {
throw Error("unknown ECDSA sig r length error");
}
if (a.length % 32 != 0) {
throw Error("unknown ECDSA sig s length error");
}
return b + a;
};
KJUR.crypto.ECDSA.concatSigToASN1Sig = function(a) {
if (a.length % 4 != 0) {
throw Error("unknown ECDSA concatinated r-s sig length error");
}
var c = a.substr(0, a.length / 2);
var b = a.substr(a.length / 2);
return KJUR.crypto.ECDSA.hexRSSigToASN1Sig(c, b);
};
KJUR.crypto.ECDSA.hexRSSigToASN1Sig = function(b, a) {
var d = new BigInteger(b, 16);
var c = new BigInteger(a, 16);
return KJUR.crypto.ECDSA.biRSSigToASN1Sig(d, c);
};
KJUR.crypto.ECDSA.biRSSigToASN1Sig = function(f, d) {
var c = KJUR.asn1;
var b = new c.DERInteger({ bigint: f });
var a = new c.DERInteger({ bigint: d });
var e2 = new c.DERSequence({ array: [b, a] });
return e2.tohex();
};
KJUR.crypto.ECDSA.getName = function(a) {
if (a === "2b8104001f") {
return "secp192k1";
}
if (a === "2a8648ce3d030107") {
return "secp256r1";
}
if (a === "2b8104000a") {
return "secp256k1";
}
if (a === "2b81040021") {
return "secp224r1";
}
if (a === "2b81040022") {
return "secp384r1";
}
if (a === "2b81040023") {
return "secp521r1";
}
if ("|secp256r1|NIST P-256|P-256|prime256v1|".indexOf(a) !== -1) {
return "secp256r1";
}
if ("|secp256k1|".indexOf(a) !== -1) {
return "secp256k1";
}
if ("|secp224r1|NIST P-224|P-224|".indexOf(a) !== -1) {
return "secp224r1";
}
if ("|secp384r1|NIST P-384|P-384|".indexOf(a) !== -1) {
return "secp384r1";
}
if ("|secp521r1|NIST P-521|P-521|".indexOf(a) !== -1) {
return "secp521r1";
}
return null;
};
if (typeof KJUR == "undefined" || !KJUR) {
KJUR = {};
}
if (typeof KJUR.crypto == "undefined" || !KJUR.crypto) {
KJUR.crypto = {};
}
KJUR.crypto.ECParameterDB = new function() {
var b = {};
var c = {};
function a(d) {
return new BigInteger(d, 16);
}
this.getByName = function(e2) {
var d = e2;
if (typeof c[d] != "undefined") {
d = c[e2];
}
if (typeof b[d] != "undefined") {
return b[d];
}
throw "unregistered EC curve name: " + d;
};
this.regist = function(A, l, o2, g, m, e2, j, f, k, u, d, x) {
b[A] = {};
var s = a(o2);
var z2 = a(g);
var y = a(m);
var t3 = a(e2);
var w = a(j);
var r2 = new ECCurveFp(s, z2, y);
var q = r2.decodePointHex("04" + f + k);
b[A]["name"] = A;
b[A]["keylen"] = l;
b[A]["keycharlen"] = Math.ceil(l / 8) * 2;
b[A]["curve"] = r2;
b[A]["G"] = q;
b[A]["n"] = t3;
b[A]["h"] = w;
b[A]["oid"] = d;
b[A]["info"] = x;
for (var v = 0; v < u.length; v++) {
c[u[v]] = A;
}
};
}();
KJUR.crypto.ECParameterDB.regist("secp128r1", 128, "FFFFFFFDFFFFFFFFFFFFFFFFFFFFFFFF", "FFFFFFFDFFFFFFFFFFFFFFFFFFFFFFFC", "E87579C11079F43DD824993C2CEE5ED3", "FFFFFFFE0000000075A30D1B9038A115", "1", "161FF7528B899B2D0C28607CA52C5B86", "CF5AC8395BAFEB13C02DA292DDED7A83", [], "", "secp128r1 : SECG curve over a 128 bit prime field");
KJUR.crypto.ECParameterDB.regist("secp160k1", 160, "FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFEFFFFAC73", "0", "7", "0100000000000000000001B8FA16DFAB9ACA16B6B3", "1", "3B4C382CE37AA192A4019E763036F4F5DD4D7EBB", "938CF935318FDCED6BC28286531733C3F03C4FEE", [], "", "secp160k1 : SECG curve over a 160 bit prime field");
KJUR.crypto.ECParameterDB.regist("secp160r1", 160, "FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF7FFFFFFF", "FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF7FFFFFFC", "1C97BEFC54BD7A8B65ACF89F81D4D4ADC565FA45", "0100000000000000000001F4C8F927AED3CA752257", "1", "4A96B5688EF573284664698968C38BB913CBFC82", "23A628553168947D59DCC912042351377AC5FB32", [], "", "secp160r1 : SECG curve over a 160 bit prime field");
KJUR.crypto.ECParameterDB.regist("secp192k1", 192, "FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFEFFFFEE37", "0", "3", "FFFFFFFFFFFFFFFFFFFFFFFE26F2FC170F69466A74DEFD8D", "1", "DB4FF10EC057E9AE26B07D0280B7F4341DA5D1B1EAE06C7D", "9B2F2F6D9C5628A7844163D015BE86344082AA88D95E2F9D", []);
KJUR.crypto.ECParameterDB.regist("secp192r1", 192, "FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFEFFFFFFFFFFFFFFFF", "FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFEFFFFFFFFFFFFFFFC", "64210519E59C80E70FA7E9AB72243049FEB8DEECC146B9B1", "FFFFFFFFFFFFFFFFFFFFFFFF99DEF836146BC9B1B4D22831", "1", "188DA80EB03090F67CBF20EB43A18800F4FF0AFD82FF1012", "07192B95FFC8DA78631011ED6B24CDD573F977A11E794811", []);
KJUR.crypto.ECParameterDB.regist("secp224r1", 224, "FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF000000000000000000000001", "FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFEFFFFFFFFFFFFFFFFFFFFFFFE", "B4050A850C04B3ABF54132565044B0B7D7BFD8BA270B39432355FFB4", "FFFFFFFFFFFFFFFFFFFFFFFFFFFF16A2E0B8F03E13DD29455C5C2A3D", "1", "B70E0CBD6BB4BF7F321390B94A03C1D356C21122343280D6115C1D21", "BD376388B5F723FB4C22DFE6CD4375A05A07476444D5819985007E34", []);
KJUR.crypto.ECParameterDB.regist("secp256k1", 256, "FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFEFFFFFC2F", "0", "7", "FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFEBAAEDCE6AF48A03BBFD25E8CD0364141", "1", "79BE667EF9DCBBAC55A06295CE870B07029BFCDB2DCE28D959F2815B16F81798", "483ADA7726A3C4655DA4FBFC0E1108A8FD17B448A68554199C47D08FFB10D4B8", []);
KJUR.crypto.ECParameterDB.regist("secp256r1", 256, "FFFFFFFF00000001000000000000000000000000FFFFFFFFFFFFFFFFFFFFFFFF", "FFFFFFFF00000001000000000000000000000000FFFFFFFFFFFFFFFFFFFFFFFC", "5AC635D8AA3A93E7B3EBBD55769886BC651D06B0CC53B0F63BCE3C3E27D2604B", "FFFFFFFF00000000FFFFFFFFFFFFFFFFBCE6FAADA7179E84F3B9CAC2FC632551", "1", "6B17D1F2E12C4247F8BCE6E563A440F277037D812DEB33A0F4A13945D898C296", "4FE342E2FE1A7F9B8EE7EB4A7C0F9E162BCE33576B315ECECBB6406837BF51F5", ["NIST P-256", "P-256", "prime256v1"]);
KJUR.crypto.ECParameterDB.regist("secp384r1", 384, "FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFEFFFFFFFF0000000000000000FFFFFFFF", "FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFEFFFFFFFF0000000000000000FFFFFFFC", "B3312FA7E23EE7E4988E056BE3F82D19181D9C6EFE8141120314088F5013875AC656398D8A2ED19D2A85C8EDD3EC2AEF", "FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFC7634D81F4372DDF581A0DB248B0A77AECEC196ACCC52973", "1", "AA87CA22BE8B05378EB1C71EF320AD746E1D3B628BA79B9859F741E082542A385502F25DBF55296C3A545E3872760AB7", "3617de4a96262c6f5d9e98bf9292dc29f8f41dbd289a147ce9da3113b5f0b8c00a60b1ce1d7e819d7a431d7c90ea0e5f", ["NIST P-384", "P-384"]);
KJUR.crypto.ECParameterDB.regist("secp521r1", 521, "1FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF", "1FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFC", "051953EB9618E1C9A1F929A21A0B68540EEA2DA725B99B315F3B8B489918EF109E156193951EC7E937B1652C0BD3BB1BF073573DF883D2C34F1EF451FD46B503F00", "1FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFA51868783BF2F966B7FCC0148F709A5D03BB5C9B8899C47AEBB6FB71E91386409", "1", "00C6858E06B70404E9CD9E3ECB662395B4429C648139053FB521F828AF606B4D3DBAA14B5E77EFE75928FE1DC127A2FFA8DE3348B3C1856A429BF97E7E31C2E5BD66", "011839296a789a3bc0045c8a5fb42c7d1bd998f54449579b446817afbd17273e662c97ee72995ef42640c550b9013fad0761353c7086a272c24088be94769fd16650", ["NIST P-521", "P-521"]);
if (typeof KJUR == "undefined" || !KJUR) {
KJUR = {};
}
if (typeof KJUR.crypto == "undefined" || !KJUR.crypto) {
KJUR.crypto = {};
}
KJUR.crypto.DSA = function() {
var b = ASN1HEX, e2 = b.getVbyList, d = b.getVbyListEx, a = b.isASN1HEX, c = BigInteger;
this.p = null;
this.q = null;
this.g = null;
this.y = null;
this.x = null;
this.type = "DSA";
this.isPrivate = false;
this.isPublic = false;
this.setPrivate = function(j, i, h, k, f) {
this.isPrivate = true;
this.p = j;
this.q = i;
this.g = h;
this.y = k;
this.x = f;
};
this.setPrivateHex = function(i, g, k, n2, o2) {
var h, f, j, l, m;
h = new BigInteger(i, 16);
f = new BigInteger(g, 16);
j = new BigInteger(k, 16);
if (typeof n2 === "string" && n2.length > 1) {
l = new BigInteger(n2, 16);
} else {
l = null;
}
m = new BigInteger(o2, 16);
this.setPrivate(h, f, j, l, m);
};
this.setPublic = function(i, h, f, j) {
this.isPublic = true;
this.p = i;
this.q = h;
this.g = f;
this.y = j;
this.x = null;
};
this.setPublicHex = function(k, j, i, l) {
var g, f, m, h;
g = new BigInteger(k, 16);
f = new BigInteger(j, 16);
m = new BigInteger(i, 16);
h = new BigInteger(l, 16);
this.setPublic(g, f, m, h);
};
this.signWithMessageHash = function(j) {
var i = this.p;
var h = this.q;
var m = this.g;
var o2 = this.y;
var t3 = this.x;
var l = KJUR.crypto.Util.getRandomBigIntegerMinToMax(BigInteger.ONE.add(BigInteger.ONE), h.subtract(BigInteger.ONE));
var u = j.substr(0, h.bitLength() / 4);
var n2 = new BigInteger(u, 16);
var f = m.modPow(l, i).mod(h);
var w = l.modInverse(h).multiply(n2.add(t3.multiply(f))).mod(h);
var v = KJUR.asn1.ASN1Util.jsonToASN1HEX({ seq: [{ "int": { bigint: f } }, { "int": { bigint: w } }] });
return v;
};
this.verifyWithMessageHash = function(m, l) {
var j = this.p;
var h = this.q;
var o2 = this.g;
var u = this.y;
var n2 = this.parseASN1Signature(l);
var f = n2[0];
var C = n2[1];
var B = m.substr(0, h.bitLength() / 4);
var t3 = new BigInteger(B, 16);
if (BigInteger.ZERO.compareTo(f) > 0 || f.compareTo(h) > 0) {
throw "invalid DSA signature";
}
if (BigInteger.ZERO.compareTo(C) >= 0 || C.compareTo(h) > 0) {
throw "invalid DSA signature";
}
var x = C.modInverse(h);
var k = t3.multiply(x).mod(h);
var i = f.multiply(x).mod(h);
var A = o2.modPow(k, j).multiply(u.modPow(i, j)).mod(j).mod(h);
return A.compareTo(f) == 0;
};
this.parseASN1Signature = function(f) {
try {
var i = new c(d(f, 0, [0], "02"), 16);
var h = new c(d(f, 0, [1], "02"), 16);
return [i, h];
} catch (g) {
throw new Error("malformed ASN.1 DSA signature");
}
};
this.readPKCS5PrvKeyHex = function(j) {
var k, i, g, l, m;
if (a(j) === false) {
throw new Error("not ASN.1 hex string");
}
try {
k = d(j, 0, [1], "02");
i = d(j, 0, [2], "02");
g = d(j, 0, [3], "02");
l = d(j, 0, [4], "02");
m = d(j, 0, [5], "02");
} catch (f) {
throw new Error("malformed PKCS#1/5 plain DSA private key");
}
this.setPrivateHex(k, i, g, l, m);
};
this.readPKCS8PrvKeyHex = function(j) {
var k, i, g, l;
if (a(j) === false) {
throw new Error("not ASN.1 hex string");
}
try {
k = d(j, 0, [1, 1, 0], "02");
i = d(j, 0, [1, 1, 1], "02");
g = d(j, 0, [1, 1, 2], "02");
l = d(j, 0, [2, 0], "02");
} catch (f) {
throw new Error("malformed PKCS#8 plain DSA private key");
}
this.setPrivateHex(k, i, g, null, l);
};
this.readPKCS8PubKeyHex = function(j) {
var k, i, g, l;
if (a(j) === false) {
throw new Error("not ASN.1 hex string");
}
try {
k = d(j, 0, [0, 1, 0], "02");
i = d(j, 0, [0, 1, 1], "02");
g = d(j, 0, [0, 1, 2], "02");
l = d(j, 0, [1, 0], "02");
} catch (f) {
throw new Error("malformed PKCS#8 DSA public key");
}
this.setPublicHex(k, i, g, l);
};
this.readCertPubKeyHex = function(j, m) {
var k, i, g, l;
if (a(j) === false) {
throw new Error("not ASN.1 hex string");
}
try {
k = d(j, 0, [0, 5, 0, 1, 0], "02");
i = d(j, 0, [0, 5, 0, 1, 1], "02");
g = d(j, 0, [0, 5, 0, 1, 2], "02");
l = d(j, 0, [0, 5, 1, 0], "02");
} catch (f) {
throw new Error("malformed X.509 certificate DSA public key");
}
this.setPublicHex(k, i, g, l);
};
};
var KEYUTIL = /* @__PURE__ */ (function() {
var d = function(p, r2, q) {
return k(CryptoJS.AES, p, r2, q);
};
var e2 = function(p, r2, q) {
return k(CryptoJS.TripleDES, p, r2, q);
};
var a = function(p, r2, q) {
return k(CryptoJS.DES, p, r2, q);
};
var k = function(s, x, u, q) {
var r2 = CryptoJS.enc.Hex.parse(x);
var w = CryptoJS.enc.Hex.parse(u);
var p = CryptoJS.enc.Hex.parse(q);
var t3 = {};
t3.key = w;
t3.iv = p;
t3.ciphertext = r2;
var v = s.decrypt(t3, w, { iv: p });
return CryptoJS.enc.Hex.stringify(v);
};
var l = function(p, r2, q) {
return g(CryptoJS.AES, p, r2, q);
};
var o2 = function(p, r2, q) {
return g(CryptoJS.TripleDES, p, r2, q);
};
var f = function(p, r2, q) {
return g(CryptoJS.DES, p, r2, q);
};
var g = function(t3, y, v, q) {
var s = CryptoJS.enc.Hex.parse(y);
var x = CryptoJS.enc.Hex.parse(v);
var p = CryptoJS.enc.Hex.parse(q);
var w = t3.encrypt(s, x, { iv: p });
var r2 = CryptoJS.enc.Hex.parse(w.toString());
var u = CryptoJS.enc.Base64.stringify(r2);
return u;
};
var i = { "AES-256-CBC": { proc: d, eproc: l, keylen: 32, ivlen: 16 }, "AES-192-CBC": { proc: d, eproc: l, keylen: 24, ivlen: 16 }, "AES-128-CBC": { proc: d, eproc: l, keylen: 16, ivlen: 16 }, "DES-EDE3-CBC": { proc: e2, eproc: o2, keylen: 24, ivlen: 8 }, "DES-CBC": { proc: a, eproc: f, keylen: 8, ivlen: 8 } };
var c = function(p) {
return i[p]["proc"];
};
var m = function(p) {
var r2 = CryptoJS.lib.WordArray.random(p);
var q = CryptoJS.enc.Hex.stringify(r2);
return q;
};
var n2 = function(v) {
var w = {};
var q = v.match(new RegExp("DEK-Info: ([^,]+),([0-9A-Fa-f]+)", "m"));
if (q) {
w.cipher = q[1];
w.ivsalt = q[2];
}
var p = v.match(new RegExp("-----BEGIN ([A-Z]+) PRIVATE KEY-----"));
if (p) {
w.type = p[1];
}
var u = -1;
var x = 0;
if (v.indexOf("\r\n\r\n") != -1) {
u = v.indexOf("\r\n\r\n");
x = 2;
}
if (v.indexOf("\n\n") != -1) {
u = v.indexOf("\n\n");
x = 1;
}
var t3 = v.indexOf("-----END");
if (u != -1 && t3 != -1) {
var r2 = v.substring(u + x * 2, t3 - x);
r2 = r2.replace(/\s+/g, "");
w.data = r2;
}
return w;
};
var j = function(q, y, p) {
var v = p.substring(0, 16);
var t3 = CryptoJS.enc.Hex.parse(v);
var r2 = CryptoJS.enc.Utf8.parse(y);
var u = i[q]["keylen"] + i[q]["ivlen"];
var x = "";
var w = null;
for (; ; ) {
var s = CryptoJS.algo.MD5.create();
if (w != null) {
s.update(w);
}
s.update(r2);
s.update(t3);
w = s.finalize();
x = x + CryptoJS.enc.Hex.stringify(w);
if (x.length >= u * 2) {
break;
}
}
var z2 = {};
z2.keyhex = x.substr(0, i[q]["keylen"] * 2);
z2.ivhex = x.substr(i[q]["keylen"] * 2, i[q]["ivlen"] * 2);
return z2;
};
var b = function(p, v, r2, w) {
var s = CryptoJS.enc.Base64.parse(p);
var q = CryptoJS.enc.Hex.stringify(s);
var u = i[v]["proc"];
var t3 = u(q, r2, w);
return t3;
};
var h = function(p, s, q, u) {
var r2 = i[s]["eproc"];
var t3 = r2(p, q, u);
return t3;
};
return { version: "1.0.0", parsePKCS5PEM: function(p) {
return n2(p);
}, getKeyAndUnusedIvByPasscodeAndIvsalt: function(q, p, r2) {
return j(q, p, r2);
}, decryptKeyB64: function(p, r2, q, s) {
return b(p, r2, q, s);
}, getDecryptedKeyHex: function(y, x) {
var q = n2(y);
var t3 = q.type;
var r2 = q.cipher;
var p = q.ivsalt;
var s = q.data;
var w = j(r2, x, p);
var v = w.keyhex;
var u = b(s, r2, v, p);
return u;
}, getEncryptedPKCS5PEMFromPrvKeyHex: function(x, s, A, t3, r2) {
var p = "";
if (typeof t3 == "undefined" || t3 == null) {
t3 = "AES-256-CBC";
}
if (typeof i[t3] == "undefined") {
throw new Error("KEYUTIL unsupported algorithm: " + t3);
}
if (typeof r2 == "undefined" || r2 == null) {
var v = i[t3]["ivlen"];
var u = m(v);
r2 = u.toUpperCase();
}
var z2 = j(t3, A, r2);
var y = z2.keyhex;
var w = h(s, t3, y, r2);
var q = w.replace(/(.{64})/g, "$1\r\n");
var p = "-----BEGIN " + x + " PRIVATE KEY-----\r\n";
p += "Proc-Type: 4,ENCRYPTED\r\n";
p += "DEK-Info: " + t3 + "," + r2 + "\r\n";
p += "\r\n";
p += q;
p += "\r\n-----END " + x + " PRIVATE KEY-----\r\n";
return p;
}, getEncryptedPKCS8PEM: function(r2, p, s) {
var q = this.getEncryptedPKCS8Hex(r2, p, s);
return hextopem(q, "ENCRYPTED PRIVATE KEY");
}, getEncryptedPKCS8Hex: function(r2, p, t3) {
var q;
if (t3 == void 0 || t3 == null) {
q = {};
} else {
q = JSON.parse(JSON.stringify(t3));
}
q.plain = r2;
this.initPBES2Param(q);
this.encryptPBES2Param(q, p);
var s = this.generatePBES2ASN1Param(q);
return KJUR.asn1.ASN1Util.newObject(s).tohex();
}, initPBES2Param: function(p) {
if (aryval(p, "encalg") == void 0) {
p.encalg = "aes256-CBC";
}
if (aryval(p, "iter") == void 0) {
p.iter = 2048;
}
if (aryval(p, "prf") == void 0) {
p.prf = "hmacWithSHA256";
}
if (aryval(p, "salt") == void 0) {
p.salt = CryptoJS.enc.Hex.stringify(CryptoJS.lib.WordArray.random(8));
}
if (aryval(p, "enciv") == void 0) {
var q;
if (p.encalg == "des-EDE3-CBC") {
q = 8;
}
if (p.encalg == "aes128-CBC") {
q = 16;
}
if (p.encalg == "aes256-CBC") {
q = 16;
}
p.enciv = CryptoJS.enc.Hex.stringify(CryptoJS.lib.WordArray.random(q));
}
}, encryptPBES2Param: function(p, q) {
var t3 = KEYUTIL.getDKFromPBES2Param(p, q);
try {
var s = KJUR.crypto.Cipher.encrypt(p.plain, t3, p.encalg, { iv: p.enciv });
} catch (r2) {
throw new Error("encrypt error: " + p.plain + " " + t3 + " " + p.encalg + " " + p.enciv);
}
p.enc = s;
}, generatePBES2ASN1Param: function(p) {
var q = { seq: [{ seq: [{ oid: "pkcs5PBES2" }, { seq: [{ seq: [{ oid: "pkcs5PBKDF2" }, { seq: [{ octstr: { hex: p.salt } }, { "int": { hex: inttohex(p.iter) } }] }] }, { seq: [{ oid: p.encalg }, { octstr: { hex: p.enciv } }] }] }] }, { octstr: { hex: p.enc } }] };
if (p.prf != "hmacWithSHA1") {
q.seq[0].seq[1].seq[0].seq[1].seq.push({ seq: [{ oid: p.prf }, { "null": "" }] });
}
return q;
}, parseHexOfEncryptedPKCS8: function(y) {
var B = ASN1HEX;
var z2 = B.getChildIdx;
var w = B.getV;
var t3 = {};
var r2 = z2(y, 0);
if (r2.length != 2) {
throw new Error("malformed format: SEQUENCE(0).items != 2: " + r2.length);
}
t3.ciphertext = w(y, r2[1]);
var A = z2(y, r2[0]);
if (A.length != 2) {
throw new Error("malformed format: SEQUENCE(0.0).items != 2: " + A.length);
}
if (w(y, A[0]) != "2a864886f70d01050d") {
throw new Error("this only supports pkcs5PBES2");
}
var p = z2(y, A[1]);
if (A.length != 2) {
throw new Error("malformed format: SEQUENCE(0.0.1).items != 2: " + p.length);
}
var q = z2(y, p[1]);
if (q.length != 2) {
throw new Error("malformed format: SEQUENCE(0.0.1.1).items != 2: " + q.length);
}
if (w(y, q[0]) != "2a864886f70d0307") {
throw "this only supports TripleDES";
}
t3.encryptionSchemeAlg = "TripleDES";
t3.encryptionSchemeIV = w(y, q[1]);
var s = z2(y, p[0]);
if (s.length != 2) {
throw new Error("malformed format: SEQUENCE(0.0.1.0).items != 2: " + s.length);
}
if (w(y, s[0]) != "2a864886f70d01050c") {
throw new Error("this only supports pkcs5PBKDF2");
}
var x = z2(y, s[1]);
if (x.length < 2) {
throw new Error("malformed format: SEQUENCE(0.0.1.0.1).items < 2: " + x.length);
}
t3.pbkdf2Salt = w(y, x[0]);
var u = w(y, x[1]);
try {
t3.pbkdf2Iter = parseInt(u, 16);
} catch (v) {
throw new Error("malformed format pbkdf2Iter: " + u);
}
return t3;
}, getPBKDF2KeyHexFromParam: function(u, p) {
var t3 = CryptoJS.enc.Hex.parse(u.pbkdf2Salt);
var q = u.pbkdf2Iter;
var s = CryptoJS.PBKDF2(p, t3, { keySize: 192 / 32, iterations: q });
var r2 = CryptoJS.enc.Hex.stringify(s);
return r2;
}, _getPlainPKCS8HexFromEncryptedPKCS8PEM: function(x, y) {
var r2 = pemtohex(x, "ENCRYPTED PRIVATE KEY");
var p = this.parseHexOfEncryptedPKCS8(r2);
var u = KEYUTIL.getPBKDF2KeyHexFromParam(p, y);
var v = {};
v.ciphertext = CryptoJS.enc.Hex.parse(p.ciphertext);
var t3 = CryptoJS.enc.Hex.parse(u);
var s = CryptoJS.enc.Hex.parse(p.encryptionSchemeIV);
var w = CryptoJS.TripleDES.decrypt(v, t3, { iv: s });
var q = CryptoJS.enc.Hex.stringify(w);
return q;
}, parsePBES2: function(z2) {
var v = ASN1HEX.parse(z2);
if (aryval(v, "seq.0.seq.0.oid") != "pkcs5PBES2" || aryval(v, "seq.0.seq.1.seq.0.seq.0.oid") != "pkcs5PBKDF2") {
throw new Error("not pkcs5PBES2 and pkcs5PBKDF2 used");
}
var y = aryval(v, "seq.0.seq.1.seq.0.seq.1.seq");
if (y == void 0) {
throw new Error("PBKDF2 parameter not found");
}
var t3 = aryval(y, "0.octstr.hex");
var p = aryval(y, "1.int.hex");
var q = aryval(y, "2.seq.0.oid", "hmacWithSHA1");
var x = -1;
try {
x = parseInt(p, 16);
} catch (w) {
throw new Error("iter not proper value");
}
var u = aryval(v, "seq.0.seq.1.seq.1.seq.0.oid");
var s = aryval(v, "seq.0.seq.1.seq.1.seq.1.octstr.hex");
var r2 = aryval(v, "seq.1.octstr.hex");
if (u == void 0 || s == void 0 || r2 == void 0) {
throw new Error("encalg, enciv or enc is undefined");
}
var A = { salt: t3, iter: x, prf: q, encalg: u, enciv: s, enc: r2 };
return A;
}, getDKFromPBES2Param: function(p, w) {
var x = { hmacWithSHA1: CryptoJS.algo.SHA1, hmacWithSHA224: CryptoJS.algo.SHA224, hmacWithSHA256: CryptoJS.algo.SHA256, hmacWithSHA384: CryptoJS.algo.SHA384, hmacWithSHA512: CryptoJS.algo.SHA512 };
var q = { "des-EDE3-CBC": 192 / 32, "aes128-CBC": 128 / 32, "aes256-CBC": 256 / 32 };
var y = x[p.prf];
if (y == void 0) {
throw new Error("unsupported prf");
}
var r2 = q[p.encalg];
if (r2 == void 0) {
throw new Error("unsupported encalg");
}
var s = CryptoJS.enc.Hex.parse(p.salt);
var u = p.iter;
try {
var v = CryptoJS.PBKDF2(w, s, { keySize: r2, iterations: u, hasher: y });
return CryptoJS.enc.Hex.stringify(v);
} catch (t3) {
throw new Error("PBKDF2 error: " + t3 + " " + JSON.stringify(p) + " " + w);
}
}, getPlainHexFromEncryptedPKCS8PEM: function(t3, q) {
if (t3.indexOf("BEGIN ENCRYPTED PRIVATE KEY") == -1) {
throw new Error("not Encrypted PKCS#8 PEM string");
}
var u = pemtohex(t3);
var p;
try {
p = KEYUTIL.parsePBES2(u);
} catch (r2) {
throw new Error("malformed PBES2 format: " + r2.message);
}
var s = KEYUTIL.getDKFromPBES2Param(p, q);
return KJUR.crypto.Cipher.decrypt(p.enc, s, p.encalg, { iv: p.enciv });
}, getKeyFromEncryptedPKCS8PEM: function(s, q) {
var p = this.getPlainHexFromEncryptedPKCS8PEM(s, q);
var r2 = this.getKeyFromPlainPrivatePKCS8Hex(p);
return r2;
}, parsePlainPrivatePKCS8Hex: function(s) {
var v = ASN1HEX;
var u = v.getChildIdx;
var t3 = v.getV;
var q = {};
q.algparam = null;
if (s.substr(0, 2) != "30") {
throw new Error("malformed plain PKCS8 private key(code:001)");
}
var r2 = u(s, 0);
if (r2.length < 3) {
throw new Error("malformed plain PKCS8 private key(code:002)");
}
if (s.substr(r2[1], 2) != "30") {
throw new Error("malformed PKCS8 private key(code:003)");
}
var p = u(s, r2[1]);
if (p.length != 2) {
throw new Error("malformed PKCS8 private key(code:004)");
}
if (s.substr(p[0], 2) != "06") {
throw new Error("malformed PKCS8 private key(code:005)");
}
q.algoid = t3(s, p[0]);
if (s.substr(p[1], 2) == "06") {
q.algparam = t3(s, p[1]);
}
if (s.substr(r2[2], 2) != "04") {
throw new Error("malformed PKCS8 private key(code:006)");
}
q.keyidx = v.getVidx(s, r2[2]);
return q;
}, getKeyFromPlainPrivatePKCS8PEM: function(q) {
var p = pemtohex(q, "PRIVATE KEY");
var r2 = this.getKeyFromPlainPrivatePKCS8Hex(p);
return r2;
}, getKeyFromPlainPrivatePKCS8Hex: function(p) {
var q = this.parsePlainPrivatePKCS8Hex(p);
var r2;
if (q.algoid == "2a864886f70d010101") {
r2 = new RSAKey();
} else {
if (q.algoid == "2a8648ce380401") {
r2 = new KJUR.crypto.DSA();
} else {
if (q.algoid == "2a8648ce3d0201") {
r2 = new KJUR.crypto.ECDSA();
} else {
throw new Error("unsupported private key algorithm");
}
}
}
r2.readPKCS8PrvKeyHex(p);
return r2;
}, _getKeyFromPublicPKCS8Hex: function(q) {
var p;
var r2 = ASN1HEX.getVbyList(q, 0, [0, 0], "06");
if (r2 === "2a864886f70d010101") {
p = new RSAKey();
} else {
if (r2 === "2a8648ce380401") {
p = new KJUR.crypto.DSA();
} else {
if (r2 === "2a8648ce3d0201") {
p = new KJUR.crypto.ECDSA();
} else {
throw new Error("unsupported PKCS#8 public key hex");
}
}
}
p.readPKCS8PubKeyHex(q);
return p;
}, parsePublicRawRSAKeyHex: function(r2) {
var u = ASN1HEX;
var t3 = u.getChildIdx;
var s = u.getV;
var p = {};
if (r2.substr(0, 2) != "30") {
throw new Error("malformed RSA key(code:001)");
}
var q = t3(r2, 0);
if (q.length != 2) {
throw new Error("malformed RSA key(code:002)");
}
if (r2.substr(q[0], 2) != "02") {
throw new Error("malformed RSA key(code:003)");
}
p.n = s(r2, q[0]);
if (r2.substr(q[1], 2) != "02") {
throw new Error("malformed RSA key(code:004)");
}
p.e = s(r2, q[1]);
return p;
}, parsePublicPKCS8Hex: function(t3) {
var v = ASN1HEX;
var u = v.getChildIdx;
var s = v.getV;
var q = {};
q.algparam = null;
var r2 = u(t3, 0);
if (r2.length != 2) {
throw new Error("outer DERSequence shall have 2 elements: " + r2.length);
}
var w = r2[0];
if (t3.substr(w, 2) != "30") {
throw new Error("malformed PKCS8 public key(code:001)");
}
var p = u(t3, w);
if (p.length != 2) {
throw new Error("malformed PKCS8 public key(code:002)");
}
if (t3.substr(p[0], 2) != "06") {
throw new Error("malformed PKCS8 public key(code:003)");
}
q.algoid = s(t3, p[0]);
if (t3.substr(p[1], 2) == "06") {
q.algparam = s(t3, p[1]);
} else {
if (t3.substr(p[1], 2) == "30") {
q.algparam = {};
q.algparam.p = v.getVbyList(t3, p[1], [0], "02");
q.algparam.q = v.getVbyList(t3, p[1], [1], "02");
q.algparam.g = v.getVbyList(t3, p[1], [2], "02");
}
}
if (t3.substr(r2[1], 2) != "03") {
throw new Error("malformed PKCS8 public key(code:004)");
}
q.key = s(t3, r2[1]).substr(2);
return q;
} };
})();
KEYUTIL.getKey = function(l, k, n2) {
var G = ASN1HEX, L = G.getChildIdx, v = G.getV, d = G.getVbyList, c = KJUR.crypto, i = c.ECDSA, C = c.DSA, w = RSAKey, M = pemtohex, F = KEYUTIL;
if (typeof w != "undefined" && l instanceof w) {
return l;
}
if (typeof i != "undefined" && l instanceof i) {
return l;
}
if (typeof C != "undefined" && l instanceof C) {
return l;
}
if (l.curve !== void 0 && l.xy !== void 0 && l.d === void 0) {
return new i({ pub: l.xy, curve: l.curve });
}
if (l.curve !== void 0 && l.d !== void 0) {
return new i({ prv: l.d, curve: l.curve });
}
if (l.kty === void 0 && l.n !== void 0 && l.e !== void 0 && l.d === void 0) {
var P = new w();
P.setPublic(l.n, l.e);
return P;
}
if (l.kty === void 0 && l.n !== void 0 && l.e !== void 0 && l.d !== void 0 && l.p !== void 0 && l.q !== void 0 && l.dp !== void 0 && l.dq !== void 0 && l.co !== void 0 && l.qi === void 0) {
var P = new w();
P.setPrivateEx(l.n, l.e, l.d, l.p, l.q, l.dp, l.dq, l.co);
return P;
}
if (l.kty === void 0 && l.n !== void 0 && l.e !== void 0 && l.d !== void 0 && l.p === void 0) {
var P = new w();
P.setPrivate(l.n, l.e, l.d);
return P;
}
if (l.p !== void 0 && l.q !== void 0 && l.g !== void 0 && l.y !== void 0 && l.x === void 0) {
var P = new C();
P.setPublic(l.p, l.q, l.g, l.y);
return P;
}
if (l.p !== void 0 && l.q !== void 0 && l.g !== void 0 && l.y !== void 0 && l.x !== void 0) {
var P = new C();
P.setPrivate(l.p, l.q, l.g, l.y, l.x);
return P;
}
if (l.kty === "RSA" && l.n !== void 0 && l.e !== void 0 && l.d === void 0) {
var P = new w();
P.setPublic(b64utohex(l.n), b64utohex(l.e));
return P;
}
if (l.kty === "RSA" && l.n !== void 0 && l.e !== void 0 && l.d !== void 0 && l.p !== void 0 && l.q !== void 0 && l.dp !== void 0 && l.dq !== void 0 && l.qi !== void 0) {
var P = new w();
P.setPrivateEx(b64utohex(l.n), b64utohex(l.e), b64utohex(l.d), b64utohex(l.p), b64utohex(l.q), b64utohex(l.dp), b64utohex(l.dq), b64utohex(l.qi));
return P;
}
if (l.kty === "RSA" && l.n !== void 0 && l.e !== void 0 && l.d !== void 0) {
var P = new w();
P.setPrivate(b64utohex(l.n), b64utohex(l.e), b64utohex(l.d));
return P;
}
if (l.kty === "EC" && l.crv !== void 0 && l.x !== void 0 && l.y !== void 0 && l.d === void 0) {
var j = new i({ curve: l.crv });
var t3 = j.ecparams.keycharlen;
var B = ("0000000000" + b64utohex(l.x)).slice(-t3);
var z2 = ("0000000000" + b64utohex(l.y)).slice(-t3);
var u = "04" + B + z2;
j.setPublicKeyHex(u);
return j;
}
if (l.kty === "EC" && l.crv !== void 0 && l.x !== void 0 && l.y !== void 0 && l.d !== void 0) {
var j = new i({ curve: l.crv });
var t3 = j.ecparams.keycharlen;
var B = ("0000000000" + b64utohex(l.x)).slice(-t3);
var z2 = ("0000000000" + b64utohex(l.y)).slice(-t3);
var u = "04" + B + z2;
var b = ("0000000000" + b64utohex(l.d)).slice(-t3);
j.setPublicKeyHex(u);
j.setPrivateKeyHex(b);
return j;
}
if (n2 === "pkcs5prv") {
var J = l, G = ASN1HEX, N, P;
N = L(J, 0);
if (N.length === 9) {
P = new w();
P.readPKCS5PrvKeyHex(J);
} else {
if (N.length === 6) {
P = new C();
P.readPKCS5PrvKeyHex(J);
} else {
if (N.length > 2 && J.substr(N[1], 2) === "04") {
P = new i();
P.readPKCS5PrvKeyHex(J);
} else {
throw new Error("unsupported PKCS#1/5 hexadecimal key");
}
}
}
return P;
}
if (n2 === "pkcs8prv") {
var P = F.getKeyFromPlainPrivatePKCS8Hex(l);
return P;
}
if (n2 === "pkcs8pub") {
return F._getKeyFromPublicPKCS8Hex(l);
}
if (n2 === "x509pub") {
return X509.getPublicKeyFromCertHex(l);
}
if (l.indexOf("-END CERTIFICATE-", 0) != -1 || l.indexOf("-END X509 CERTIFICATE-", 0) != -1 || l.indexOf("-END TRUSTED CERTIFICATE-", 0) != -1) {
return X509.getPublicKeyFromCertPEM(l);
}
if (l.indexOf("-END PUBLIC KEY-") != -1) {
var O = pemtohex(l, "PUBLIC KEY");
return F._getKeyFromPublicPKCS8Hex(O);
}
if (l.indexOf("-END RSA PRIVATE KEY-") != -1 && l.indexOf("4,ENCRYPTED") == -1) {
var m = M(l, "RSA PRIVATE KEY");
return F.getKey(m, null, "pkcs5prv");
}
if (l.indexOf("-END DSA PRIVATE KEY-") != -1 && l.indexOf("4,ENCRYPTED") == -1) {
var I = M(l, "DSA PRIVATE KEY");
var E = d(I, 0, [1], "02");
var D = d(I, 0, [2], "02");
var K = d(I, 0, [3], "02");
var r2 = d(I, 0, [4], "02");
var s = d(I, 0, [5], "02");
var P = new C();
P.setPrivate(new BigInteger(E, 16), new BigInteger(D, 16), new BigInteger(K, 16), new BigInteger(r2, 16), new BigInteger(s, 16));
return P;
}
if (l.indexOf("-END EC PRIVATE KEY-") != -1 && l.indexOf("4,ENCRYPTED") == -1) {
var m = M(l, "EC PRIVATE KEY");
return F.getKey(m, null, "pkcs5prv");
}
if (l.indexOf("-END PRIVATE KEY-") != -1) {
return F.getKeyFromPlainPrivatePKCS8PEM(l);
}
if (l.indexOf("-END RSA PRIVATE KEY-") != -1 && l.indexOf("4,ENCRYPTED") != -1) {
var o2 = F.getDecryptedKeyHex(l, k);
var H = new RSAKey();
H.readPKCS5PrvKeyHex(o2);
return H;
}
if (l.indexOf("-END EC PRIVATE KEY-") != -1 && l.indexOf("4,ENCRYPTED") != -1) {
var I = F.getDecryptedKeyHex(l, k);
var P = d(I, 0, [1], "04");
var f = d(I, 0, [2, 0], "06");
var A = d(I, 0, [3, 0], "03").substr(2);
var e2 = "";
if (KJUR.crypto.OID.oidhex2name[f] !== void 0) {
e2 = KJUR.crypto.OID.oidhex2name[f];
} else {
throw new Error("undefined OID(hex) in KJUR.crypto.OID: " + f);
}
var j = new i({ curve: e2 });
j.setPublicKeyHex(A);
j.setPrivateKeyHex(P);
j.isPublic = false;
return j;
}
if (l.indexOf("-END DSA PRIVATE KEY-") != -1 && l.indexOf("4,ENCRYPTED") != -1) {
var I = F.getDecryptedKeyHex(l, k);
var E = d(I, 0, [1], "02");
var D = d(I, 0, [2], "02");
var K = d(I, 0, [3], "02");
var r2 = d(I, 0, [4], "02");
var s = d(I, 0, [5], "02");
var P = new C();
P.setPrivate(new BigInteger(E, 16), new BigInteger(D, 16), new BigInteger(K, 16), new BigInteger(r2, 16), new BigInteger(s, 16));
return P;
}
if (l.indexOf("-END ENCRYPTED PRIVATE KEY-") != -1) {
return F.getKeyFromEncryptedPKCS8PEM(l, k);
}
throw new Error("not supported argument");
};
KEYUTIL.generateKeypair = function(a, c) {
if (a == "RSA") {
var b = c;
var h = new RSAKey();
h.generate(b, "10001");
h.isPrivate = true;
h.isPublic = true;
var f = new RSAKey();
var e2 = h.n.toString(16);
var i = h.e.toString(16);
f.setPublic(e2, i);
f.isPrivate = false;
f.isPublic = true;
var k = {};
k.prvKeyObj = h;
k.pubKeyObj = f;
return k;
} else {
if (a == "EC") {
var d = c;
var g = new KJUR.crypto.ECDSA({ curve: d });
var j = g.generateKeyPairHex();
var h = new KJUR.crypto.ECDSA({ curve: d });
h.setPublicKeyHex(j.ecpubhex);
h.setPrivateKeyHex(j.ecprvhex);
h.isPrivate = true;
h.isPublic = false;
var f = new KJUR.crypto.ECDSA({ curve: d });
f.setPublicKeyHex(j.ecpubhex);
f.isPrivate = false;
f.isPublic = true;
var k = {};
k.prvKeyObj = h;
k.pubKeyObj = f;
return k;
} else {
throw new Error("unknown algorithm: " + a);
}
}
};
KEYUTIL.getPEM = function(b, C, x, m, p, j) {
var E = KJUR, k = E.asn1, y = k.DERObjectIdentifier, e2 = k.DERInteger, l = k.ASN1Util.newObject, a = k.x509, B = a.SubjectPublicKeyInfo, d = E.crypto, t3 = d.DSA, q = d.ECDSA, n2 = RSAKey;
function z2(s) {
var G = l({ seq: [{ "int": 0 }, { "int": { bigint: s.n } }, { "int": s.e }, { "int": { bigint: s.d } }, { "int": { bigint: s.p } }, { "int": { bigint: s.q } }, { "int": { bigint: s.dmp1 } }, { "int": { bigint: s.dmq1 } }, { "int": { bigint: s.coeff } }] });
return G;
}
function A(G) {
var s = l({ seq: [{ "int": 1 }, { octstr: { hex: G.prvKeyHex } }, { tag: ["a0", true, { oid: { name: G.curveName } }] }, { tag: ["a1", true, { bitstr: { hex: "00" + G.pubKeyHex } }] }] });
return s;
}
function w(s) {
var G = l({ seq: [{ "int": 0 }, { "int": { bigint: s.p } }, { "int": { bigint: s.q } }, { "int": { bigint: s.g } }, { "int": { bigint: s.y } }, { "int": { bigint: s.x } }] });
return G;
}
if ((n2 !== void 0 && b instanceof n2 || t3 !== void 0 && b instanceof t3 || q !== void 0 && b instanceof q) && b.isPublic == true && (C === void 0 || C == "PKCS8PUB")) {
var D = new B(b);
var v = D.tohex();
return hextopem(v, "PUBLIC KEY");
}
if (C == "PKCS1PRV" && n2 !== void 0 && b instanceof n2 && (x === void 0 || x == null) && b.isPrivate == true) {
var D = z2(b);
var v = D.tohex();
return hextopem(v, "RSA PRIVATE KEY");
}
if (C == "PKCS1PRV" && q !== void 0 && b instanceof q && (x === void 0 || x == null) && b.isPrivate == true) {
var i = new y({ name: b.curveName });
var u = i.tohex();
var h = A(b);
var r2 = h.tohex();
var o2 = "";
o2 += hextopem(u, "EC PARAMETERS");
o2 += hextopem(r2, "EC PRIVATE KEY");
return o2;
}
if (C == "PKCS1PRV" && t3 !== void 0 && b instanceof t3 && (x === void 0 || x == null) && b.isPrivate == true) {
var D = w(b);
var v = D.tohex();
return hextopem(v, "DSA PRIVATE KEY");
}
if (C == "PKCS5PRV" && n2 !== void 0 && b instanceof n2 && (x !== void 0 && x != null) && b.isPrivate == true) {
var D = z2(b);
var v = D.tohex();
if (m === void 0) {
m = "DES-EDE3-CBC";
}
return this.getEncryptedPKCS5PEMFromPrvKeyHex("RSA", v, x, m, j);
}
if (C == "PKCS5PRV" && q !== void 0 && b instanceof q && (x !== void 0 && x != null) && b.isPrivate == true) {
var D = A(b);
var v = D.tohex();
if (m === void 0) {
m = "DES-EDE3-CBC";
}
return this.getEncryptedPKCS5PEMFromPrvKeyHex("EC", v, x, m, j);
}
if (C == "PKCS5PRV" && t3 !== void 0 && b instanceof t3 && (x !== void 0 && x != null) && b.isPrivate == true) {
var D = w(b);
var v = D.tohex();
if (m === void 0) {
m = "DES-EDE3-CBC";
}
return this.getEncryptedPKCS5PEMFromPrvKeyHex("DSA", v, x, m, j);
}
var f = function(G, H) {
if (typeof H == "string") {
return KEYUTIL.getEncryptedPKCS8PEM(G, H);
} else {
if (typeof H == "object" && aryval(H, "passcode") != void 0) {
var I = JSON.parse(JSON.stringify(H));
var s = I.passcode;
delete I.passcode;
return KEYUTIL.getEncryptedPKCS8PEM(G, s, I);
}
}
};
if (C == "PKCS8PRV" && n2 != void 0 && b instanceof n2 && b.isPrivate == true) {
var g = z2(b);
var c = g.tohex();
var D = l({ seq: [{ "int": 0 }, { seq: [{ oid: { name: "rsaEncryption" } }, { "null": true }] }, { octstr: { hex: c } }] });
var v = D.tohex();
if (x === void 0 || x == null) {
return hextopem(v, "PRIVATE KEY");
} else {
return f(v, x);
}
}
if (C == "PKCS8PRV" && q !== void 0 && b instanceof q && b.isPrivate == true) {
var F = { seq: [{ "int": 1 }, { octstr: { hex: b.prvKeyHex } }] };
if (typeof b.pubKeyHex == "string") {
F.seq.push({ tag: ["a1", true, { bitstr: { hex: "00" + b.pubKeyHex } }] });
}
var g = new l(F);
var c = g.tohex();
var D = l({ seq: [{ "int": 0 }, { seq: [{ oid: { name: "ecPublicKey" } }, { oid: { name: b.curveName } }] }, { octstr: { hex: c } }] });
var v = D.tohex();
if (x === void 0 || x == null) {
return hextopem(v, "PRIVATE KEY");
} else {
return f(v, x);
}
}
if (C == "PKCS8PRV" && t3 !== void 0 && b instanceof t3 && b.isPrivate == true) {
var g = new e2({ bigint: b.x });
var c = g.tohex();
var D = l({ seq: [{ "int": 0 }, { seq: [{ oid: { name: "dsa" } }, { seq: [{ "int": { bigint: b.p } }, { "int": { bigint: b.q } }, { "int": { bigint: b.g } }] }] }, { octstr: { hex: c } }] });
var v = D.tohex();
if (x === void 0 || x == null) {
return hextopem(v, "PRIVATE KEY");
} else {
return f(v, x);
}
}
throw new Error("unsupported object nor format");
};
KEYUTIL.getKeyFromCSRPEM = function(b) {
var a = pemtohex(b, "CERTIFICATE REQUEST");
var c = KEYUTIL.getKeyFromCSRHex(a);
return c;
};
KEYUTIL.getKeyFromCSRHex = function(a) {
var c = KEYUTIL.parseCSRHex(a);
var b = KEYUTIL.getKey(c.p8pubkeyhex, null, "pkcs8pub");
return b;
};
KEYUTIL.parseCSRHex = function(d) {
var i = ASN1HEX;
var f = i.getChildIdx;
var c = i.getTLV;
var b = {};
var g = d;
if (g.substr(0, 2) != "30") {
throw new Error("malformed CSR(code:001)");
}
var e2 = f(g, 0);
if (e2.length < 1) {
throw new Error("malformed CSR(code:002)");
}
if (g.substr(e2[0], 2) != "30") {
throw new Error("malformed CSR(code:003)");
}
var a = f(g, e2[0]);
if (a.length < 3) {
throw new Error("malformed CSR(code:004)");
}
b.p8pubkeyhex = c(g, a[2]);
return b;
};
KEYUTIL.getKeyID = function(f) {
var c = KEYUTIL;
var e2 = ASN1HEX;
if (typeof f === "string" && f.indexOf("BEGIN ") != -1) {
f = c.getKey(f);
}
var d = pemtohex(c.getPEM(f));
var b = e2.getIdxbyList(d, 0, [1]);
var a = e2.getV(d, b).substring(2);
return KJUR.crypto.Util.hashHex(a, "sha1");
};
KEYUTIL.getJWK = function(d, h, g, b, f) {
var i;
var k = {};
var e2;
var c = KJUR.crypto.Util.hashHex;
if (typeof d == "string") {
i = KEYUTIL.getKey(d);
if (d.indexOf("CERTIFICATE") != -1) {
e2 = pemtohex(d);
}
} else {
if (typeof d == "object") {
if (d instanceof X509) {
i = d.getPublicKey();
e2 = d.hex;
} else {
i = d;
}
} else {
throw new Error("unsupported keyinfo type");
}
}
if (i instanceof RSAKey && i.isPrivate) {
k.kty = "RSA";
k.n = hextob64u(i.n.toString(16));
k.e = hextob64u(i.e.toString(16));
k.d = hextob64u(i.d.toString(16));
k.p = hextob64u(i.p.toString(16));
k.q = hextob64u(i.q.toString(16));
k.dp = hextob64u(i.dmp1.toString(16));
k.dq = hextob64u(i.dmq1.toString(16));
k.qi = hextob64u(i.coeff.toString(16));
} else {
if (i instanceof RSAKey && i.isPublic) {
k.kty = "RSA";
k.n = hextob64u(i.n.toString(16));
k.e = hextob64u(i.e.toString(16));
} else {
if (i instanceof KJUR.crypto.ECDSA && i.isPrivate) {
var a = i.getShortNISTPCurveName();
if (a !== "P-256" && a !== "P-384" && a !== "P-521") {
throw new Error("unsupported curve name for JWT: " + a);
}
var j = i.getPublicKeyXYHex();
k.kty = "EC";
k.crv = a;
k.x = hextob64u(j.x);
k.y = hextob64u(j.y);
k.d = hextob64u(i.prvKeyHex);
} else {
if (i instanceof KJUR.crypto.ECDSA && i.isPublic) {
var a = i.getShortNISTPCurveName();
if (a !== "P-256" && a !== "P-384" && a !== "P-521") {
throw new Error("unsupported curve name for JWT: " + a);
}
var j = i.getPublicKeyXYHex();
k.kty = "EC";
k.crv = a;
k.x = hextob64u(j.x);
k.y = hextob64u(j.y);
}
}
}
}
if (k.kty == void 0) {
throw new Error("unsupported keyinfo");
}
if (!i.isPrivate && h != true) {
k.kid = KJUR.jws.JWS.getJWKthumbprint(k);
}
if (e2 != void 0 && g != true) {
k.x5c = [hex2b64(e2)];
}
if (e2 != void 0 && b != true) {
k.x5t = b64tob64u(hex2b64(c(e2, "sha1")));
}
if (e2 != void 0 && f != true) {
k["x5t#S256"] = b64tob64u(hex2b64(c(e2, "sha256")));
}
return k;
};
KEYUTIL.getJWKFromKey = function(a) {
return KEYUTIL.getJWK(a, true, true, true, true);
};
RSAKey.getPosArrayOfChildrenFromHex = function(a) {
return ASN1HEX.getChildIdx(a, 0);
};
RSAKey.getHexValueArrayOfChildrenFromHex = function(f) {
var n2 = ASN1HEX;
var i = n2.getV;
var k = RSAKey.getPosArrayOfChildrenFromHex(f);
var e2 = i(f, k[0]);
var j = i(f, k[1]);
var b = i(f, k[2]);
var c = i(f, k[3]);
var h = i(f, k[4]);
var g = i(f, k[5]);
var m = i(f, k[6]);
var l = i(f, k[7]);
var d = i(f, k[8]);
var k = new Array();
k.push(e2, j, b, c, h, g, m, l, d);
return k;
};
RSAKey.prototype.readPrivateKeyFromPEMString = function(d) {
var c = pemtohex(d);
var b = RSAKey.getHexValueArrayOfChildrenFromHex(c);
this.setPrivateEx(b[1], b[2], b[3], b[4], b[5], b[6], b[7], b[8]);
};
RSAKey.prototype.readPKCS5PrvKeyHex = function(c) {
var b = RSAKey.getHexValueArrayOfChildrenFromHex(c);
this.setPrivateEx(b[1], b[2], b[3], b[4], b[5], b[6], b[7], b[8]);
};
RSAKey.prototype.readPKCS8PrvKeyHex = function(e2) {
var c, i, k, b, a, f, d, j;
var m = ASN1HEX;
var l = m.getVbyListEx;
if (m.isASN1HEX(e2) === false) {
throw new Error("not ASN.1 hex string");
}
try {
c = l(e2, 0, [2, 0, 1], "02");
i = l(e2, 0, [2, 0, 2], "02");
k = l(e2, 0, [2, 0, 3], "02");
b = l(e2, 0, [2, 0, 4], "02");
a = l(e2, 0, [2, 0, 5], "02");
f = l(e2, 0, [2, 0, 6], "02");
d = l(e2, 0, [2, 0, 7], "02");
j = l(e2, 0, [2, 0, 8], "02");
} catch (g) {
throw new Error("malformed PKCS#8 plain RSA private key");
}
this.setPrivateEx(c, i, k, b, a, f, d, j);
};
RSAKey.prototype.readPKCS5PubKeyHex = function(c) {
var e2 = ASN1HEX;
var b = e2.getV;
if (e2.isASN1HEX(c) === false) {
throw new Error("keyHex is not ASN.1 hex string");
}
var a = e2.getChildIdx(c, 0);
if (a.length !== 2 || c.substr(a[0], 2) !== "02" || c.substr(a[1], 2) !== "02") {
throw new Error("wrong hex for PKCS#5 public key");
}
var f = b(c, a[0]);
var d = b(c, a[1]);
this.setPublic(f, d);
};
RSAKey.prototype.readPKCS8PubKeyHex = function(b) {
var c = ASN1HEX;
if (c.isASN1HEX(b) === false) {
throw new Error("not ASN.1 hex string");
}
if (c.getTLVbyListEx(b, 0, [0, 0]) !== "06092a864886f70d010101") {
throw new Error("not PKCS8 RSA public key");
}
var a = c.getTLVbyListEx(b, 0, [1, 0]);
this.readPKCS5PubKeyHex(a);
};
RSAKey.prototype.readCertPubKeyHex = function(b, d) {
var a, c;
a = new X509();
a.readCertHex(b);
c = a.getPublicKeyHex();
this.readPKCS8PubKeyHex(c);
};
var _RE_HEXDECONLY = new RegExp("[^0-9a-f]", "gi");
function _zeroPaddingOfSignature(e2, d) {
var c = "";
var a = d / 4 - e2.length;
for (var b = 0; b < a; b++) {
c = c + "0";
}
return c + e2;
}
RSAKey.prototype.sign = function(d, a) {
var b = function(e2) {
return KJUR.crypto.Util.hashString(e2, a);
};
var c = b(d);
return this.signWithMessageHash(c, a);
};
RSAKey.prototype.signWithMessageHash = function(e2, c) {
var f = KJUR.crypto.Util.getPaddedDigestInfoHex(e2, c, this.n.bitLength());
var b = parseBigInt(f, 16);
var d = this.doPrivate(b);
var a = d.toString(16);
return _zeroPaddingOfSignature(a, this.n.bitLength());
};
function pss_mgf1_str(c, a, e2) {
var b = "", d = 0;
while (b.length < a) {
b += hextorstr(e2(rstrtohex(c + String.fromCharCode.apply(String, [(d & 4278190080) >> 24, (d & 16711680) >> 16, (d & 65280) >> 8, d & 255]))));
d += 1;
}
return b;
}
RSAKey.prototype.signPSS = function(e2, a, d) {
var c = function(f) {
return KJUR.crypto.Util.hashHex(f, a);
};
var b = c(rstrtohex(e2));
if (d === void 0) {
d = -1;
}
return this.signWithMessageHashPSS(b, a, d);
};
RSAKey.prototype.signWithMessageHashPSS = function(l, a, k) {
var b = hextorstr(l);
var g = b.length;
var m = this.n.bitLength() - 1;
var c = Math.ceil(m / 8);
var d;
var o2 = function(i) {
return KJUR.crypto.Util.hashHex(i, a);
};
if (k === -1 || k === void 0) {
k = g;
} else {
if (k === -2) {
k = c - g - 2;
} else {
if (k < -2) {
throw new Error("invalid salt length");
}
}
}
if (c < g + k + 2) {
throw new Error("data too long");
}
var f = "";
if (k > 0) {
f = new Array(k);
new SecureRandom().nextBytes(f);
f = String.fromCharCode.apply(String, f);
}
var n2 = hextorstr(o2(rstrtohex("\0\0\0\0\0\0\0\0" + b + f)));
var j = [];
for (d = 0; d < c - k - g - 2; d += 1) {
j[d] = 0;
}
var e2 = String.fromCharCode.apply(String, j) + "" + f;
var h = pss_mgf1_str(n2, e2.length, o2);
var q = [];
for (d = 0; d < e2.length; d += 1) {
q[d] = e2.charCodeAt(d) ^ h.charCodeAt(d);
}
var p = 65280 >> 8 * c - m & 255;
q[0] &= ~p;
for (d = 0; d < g; d++) {
q.push(n2.charCodeAt(d));
}
q.push(188);
return _zeroPaddingOfSignature(this.doPrivate(new BigInteger(q)).toString(16), this.n.bitLength());
};
function _rsasign_getAlgNameAndHashFromHexDisgestInfo(f) {
for (var e2 in KJUR.crypto.Util.DIGESTINFOHEAD) {
var d = KJUR.crypto.Util.DIGESTINFOHEAD[e2];
var b = d.length;
if (f.substring(0, b) == d) {
var c = [e2, f.substring(b)];
return c;
}
}
return [];
}
RSAKey.prototype.verify = function(f, l) {
l = l.toLowerCase();
if (l.match(/^[0-9a-f]+$/) == null) {
return false;
}
var b = parseBigInt(l, 16);
var k = this.n.bitLength();
if (b.bitLength() > k) {
return false;
}
var j = this.doPublic(b);
var i = j.toString(16);
if (i.length + 3 != k / 4) {
return false;
}
var e2 = i.replace(/^1f+00/, "");
var g = _rsasign_getAlgNameAndHashFromHexDisgestInfo(e2);
if (g.length == 0) {
return false;
}
var d = g[0];
var h = g[1];
var a = function(m) {
return KJUR.crypto.Util.hashString(m, d);
};
var c = a(f);
return h == c;
};
RSAKey.prototype.verifyWithMessageHash = function(e2, a) {
if (a.length != Math.ceil(this.n.bitLength() / 4)) {
return false;
}
var b = parseBigInt(a, 16);
if (b.bitLength() > this.n.bitLength()) {
return 0;
}
var h = this.doPublic(b);
var g = h.toString(16).replace(/^1f+00/, "");
var c = _rsasign_getAlgNameAndHashFromHexDisgestInfo(g);
if (c.length == 0) {
return false;
}
var d = c[0];
var f = c[1];
return f == e2;
};
RSAKey.prototype.verifyPSS = function(c, b, a, f) {
var e2 = function(g) {
return KJUR.crypto.Util.hashHex(g, a);
};
var d = e2(rstrtohex(c));
if (f === void 0) {
f = -1;
}
return this.verifyWithMessageHashPSS(d, b, a, f);
};
RSAKey.prototype.verifyWithMessageHashPSS = function(f, s, l, c) {
if (s.length != Math.ceil(this.n.bitLength() / 4)) {
return false;
}
var k = new BigInteger(s, 16);
var r2 = function(i) {
return KJUR.crypto.Util.hashHex(i, l);
};
var j = hextorstr(f);
var h = j.length;
var g = this.n.bitLength() - 1;
var m = Math.ceil(g / 8);
var q;
if (c === -1 || c === void 0) {
c = h;
} else {
if (c === -2) {
c = m - h - 2;
} else {
if (c < -2) {
throw new Error("invalid salt length");
}
}
}
if (m < h + c + 2) {
throw new Error("data too long");
}
var a = this.doPublic(k).toByteArray();
for (q = 0; q < a.length; q += 1) {
a[q] &= 255;
}
while (a.length < m) {
a.unshift(0);
}
if (a[m - 1] !== 188) {
throw new Error("encoded message does not end in 0xbc");
}
a = String.fromCharCode.apply(String, a);
var d = a.substr(0, m - h - 1);
var e2 = a.substr(d.length, h);
var p = 65280 >> 8 * m - g & 255;
if ((d.charCodeAt(0) & p) !== 0) {
throw new Error("bits beyond keysize not zero");
}
var n2 = pss_mgf1_str(e2, d.length, r2);
var o2 = [];
for (q = 0; q < d.length; q += 1) {
o2[q] = d.charCodeAt(q) ^ n2.charCodeAt(q);
}
o2[0] &= ~p;
var b = m - h - c - 2;
for (q = 0; q < b; q += 1) {
if (o2[q] !== 0) {
throw new Error("leftmost octets not zero");
}
}
if (o2[b] !== 1) {
throw new Error("0x01 marker not found");
}
return e2 === hextorstr(r2(rstrtohex("\0\0\0\0\0\0\0\0" + j + String.fromCharCode.apply(String, o2.slice(-c)))));
};
RSAKey.SALT_LEN_HLEN = -1;
RSAKey.SALT_LEN_MAX = -2;
RSAKey.SALT_LEN_RECOVER = -2;
function X509(v) {
var o2 = ASN1HEX, s = o2.getChildIdx, k = o2.getV, y = o2.dump, j = o2.parse, b = o2.getTLV, c = o2.getVbyList, p = o2.getVbyListEx, a = o2.getTLVbyList, q = o2.getTLVbyListEx, l = o2.getIdxbyList, f = o2.getIdxbyListEx, n2 = o2.getVidx, x = o2.getInt, u = o2.oidname, r2 = o2.hextooidstr, d = X509, w = pemtohex, g, m = Error;
try {
g = KJUR.asn1.x509.AlgorithmIdentifier.PSSNAME2ASN1TLV;
} catch (t3) {
}
this.HEX2STAG = { "0c": "utf8", "13": "prn", "16": "ia5", "1a": "vis", "1e": "bmp" };
this.hex = null;
this.version = 0;
this.foffset = 0;
this.aExtInfo = null;
this.getVersion = function() {
if (this.hex === null || this.version !== 0) {
return this.version;
}
var A = a(this.hex, 0, [0, 0]);
if (A.substr(0, 2) == "a0") {
var B = a(A, 0, [0]);
var z2 = x(B, 0);
if (z2 < 0 || 2 < z2) {
throw new Error("malformed version field");
}
this.version = z2 + 1;
return this.version;
} else {
this.version = 1;
this.foffset = -1;
return 1;
}
};
this.getSerialNumberHex = function() {
return p(this.hex, 0, [0, 0], "02");
};
this.getSignatureAlgorithmField = function() {
var z2 = q(this.hex, 0, [0, 1]);
return this.getAlgorithmIdentifierName(z2);
};
this.getAlgorithmIdentifierName = function(z2) {
for (var A in g) {
if (z2 === g[A]) {
return A;
}
}
return u(p(z2, 0, [0], "06"));
};
this.getIssuer = function(A, z2) {
return this.getX500Name(this.getIssuerHex(), A, z2);
};
this.getIssuerHex = function() {
return a(this.hex, 0, [0, 3 + this.foffset], "30");
};
this.getIssuerString = function() {
var z2 = this.getIssuer();
return z2.str;
};
this.getSubject = function(A, z2) {
return this.getX500Name(this.getSubjectHex(), A, z2);
};
this.getSubjectHex = function() {
return a(this.hex, 0, [0, 5 + this.foffset], "30");
};
this.getSubjectString = function() {
var z2 = this.getSubject();
return z2.str;
};
this.getNotBefore = function() {
var z2 = c(this.hex, 0, [0, 4 + this.foffset, 0]);
z2 = z2.replace(/(..)/g, "%$1");
z2 = decodeURIComponent(z2);
return z2;
};
this.getNotAfter = function() {
var z2 = c(this.hex, 0, [0, 4 + this.foffset, 1]);
z2 = z2.replace(/(..)/g, "%$1");
z2 = decodeURIComponent(z2);
return z2;
};
this.getPublicKeyHex = function() {
return this.getSPKI();
};
this.getSPKI = function() {
return a(this.hex, 0, [0, 6 + this.foffset], "30");
};
this.getSPKIValue = function() {
var z2 = this.getSPKI();
if (z2 == null) {
return null;
}
return c(z2, 0, [1], "03", true);
};
this.getPublicKeyIdx = function() {
return l(this.hex, 0, [0, 6 + this.foffset], "30");
};
this.getPublicKeyContentIdx = function() {
var z2 = this.getPublicKeyIdx();
return l(this.hex, z2, [1, 0], "30");
};
this.getPublicKey = function() {
return KEYUTIL.getKey(this.getPublicKeyHex(), null, "pkcs8pub");
};
this.getSignatureAlgorithmName = function() {
var z2 = a(this.hex, 0, [1], "30");
return this.getAlgorithmIdentifierName(z2);
};
this.getSignatureValueHex = function() {
return c(this.hex, 0, [2], "03", true);
};
this.verifySignature = function(B) {
var C = this.getSignatureAlgorithmField();
var z2 = this.getSignatureValueHex();
var A = a(this.hex, 0, [0], "30");
var D = new KJUR.crypto.Signature({ alg: C });
D.init(B);
D.updateHex(A);
return D.verify(z2);
};
this.parseExt = function(I) {
var B, z2, D;
if (I === void 0) {
D = this.hex;
if (this.version !== 3) {
return -1;
}
B = l(D, 0, [0, 7, 0], "30");
z2 = s(D, B);
} else {
D = pemtohex(I);
var E = l(D, 0, [0, 3, 0, 0], "06");
if (k(D, E) != "2a864886f70d01090e") {
this.aExtInfo = new Array();
return;
}
B = l(D, 0, [0, 3, 0, 1, 0], "30");
z2 = s(D, B);
this.hex = D;
}
this.aExtInfo = new Array();
for (var C = 0; C < z2.length; C++) {
var G = {};
G.critical = false;
var F = s(D, z2[C]);
var A = 0;
if (F.length === 3) {
G.critical = true;
A = 1;
}
G.oid = o2.hextooidstr(c(D, z2[C], [0], "06"));
var H = l(D, z2[C], [1 + A]);
G.vidx = n2(D, H);
this.aExtInfo.push(G);
}
};
this.getExtInfo = function(B) {
var z2 = this.aExtInfo;
var C = B;
if (!B.match(/^[0-9.]+$/)) {
C = KJUR.asn1.x509.OID.name2oid(B);
}
if (C === "") {
return void 0;
}
for (var A = 0; A < z2.length; A++) {
if (z2[A].oid === C) {
return z2[A];
}
}
return void 0;
};
this.getCriticalExtV = function(C, z2, B) {
if (z2 != void 0) {
return [z2, B];
}
var A = this.getExtInfo(C);
if (A == void 0) {
return [null, null];
}
return [b(this.hex, A.vidx), A.critical];
};
this.getExtBasicConstraints = function(A, E) {
if (A === void 0 && E === void 0) {
var C = this.getExtInfo("basicConstraints");
if (C === void 0) {
return void 0;
}
A = b(this.hex, C.vidx);
E = C.critical;
}
var z2 = { extname: "basicConstraints" };
if (E) {
z2.critical = true;
}
if (A === "3000") {
return z2;
}
if (A === "30030101ff") {
z2.cA = true;
return z2;
}
if (A.substr(0, 12) === "30060101ff02") {
var D = k(A, 10);
var B = parseInt(D, 16);
z2.cA = true;
z2.pathLen = B;
return z2;
}
throw new Error("hExtV parse error: " + A);
};
this.getExtNameConstraints = function(I, G) {
var A = this.getCriticalExtV("nameConstraints", I, G);
I = A[0];
G = A[1];
if (I == null) {
return void 0;
}
var K = { extname: "nameConstraints" };
if (G) {
K.critical = true;
}
var F = s(I, 0);
for (var D = 0; D < F.length; D++) {
var E = [];
var B = s(I, F[D]);
for (var C = 0; C < B.length; C++) {
var H = b(I, B[C]);
var z2 = this.getGeneralSubtree(H);
E.push(z2);
}
var J = I.substr(F[D], 2);
if (J == "a0") {
K.permit = E;
} else {
if (J == "a1") {
K.exclude = E;
}
}
}
return K;
};
this.getGeneralSubtree = function(F) {
var D = s(F, 0);
var C = D.length;
if (C < 1 || 2 < C) {
throw new Error("wrong num elements");
}
var B = this.getGeneralName(b(F, D[0]));
for (var E = 1; E < C; E++) {
var A = F.substr(D[E], 2);
var z2 = k(F, D[E]);
var G = parseInt(z2, 16);
if (A == "80") {
B.min = G;
}
if (A == "81") {
B.max = G;
}
}
return B;
};
this.getExtKeyUsage = function(A, C) {
var B = this.getCriticalExtV("keyUsage", A, C);
A = B[0];
C = B[1];
if (A == null) {
return void 0;
}
var z2 = { extname: "keyUsage" };
if (C) {
z2.critical = true;
}
z2.names = this.getExtKeyUsageString(A).split(",");
return z2;
};
this.getExtKeyUsageBin = function(A) {
if (A === void 0) {
var B = this.getExtInfo("keyUsage");
if (B === void 0) {
return "";
}
A = b(this.hex, B.vidx);
}
if (A.length != 8 && A.length != 10) {
throw new Error("malformed key usage value: " + A);
}
var z2 = "000000000000000" + parseInt(A.substr(6), 16).toString(2);
if (A.length == 8) {
z2 = z2.slice(-8);
}
if (A.length == 10) {
z2 = z2.slice(-16);
}
z2 = z2.replace(/0+$/, "");
if (z2 == "") {
z2 = "0";
}
return z2;
};
this.getExtKeyUsageString = function(B) {
var C = this.getExtKeyUsageBin(B);
var z2 = new Array();
for (var A = 0; A < C.length; A++) {
if (C.substr(A, 1) == "1") {
z2.push(X509.KEYUSAGE_NAME[A]);
}
}
return z2.join(",");
};
this.getExtSubjectKeyIdentifier = function(B, D) {
if (B === void 0 && D === void 0) {
var C = this.getExtInfo("subjectKeyIdentifier");
if (C === void 0) {
return void 0;
}
B = b(this.hex, C.vidx);
D = C.critical;
}
var z2 = { extname: "subjectKeyIdentifier" };
if (D) {
z2.critical = true;
}
var A = k(B, 0);
z2.kid = { hex: A };
return z2;
};
this.getExtAuthorityKeyIdentifier = function(F, D) {
if (F === void 0 && D === void 0) {
var z2 = this.getExtInfo("authorityKeyIdentifier");
if (z2 === void 0) {
return void 0;
}
F = b(this.hex, z2.vidx);
D = z2.critical;
}
var G = { extname: "authorityKeyIdentifier" };
if (D) {
G.critical = true;
}
var E = s(F, 0);
for (var A = 0; A < E.length; A++) {
var H = F.substr(E[A], 2);
if (H === "80") {
G.kid = { hex: k(F, E[A]) };
}
if (H === "a1") {
var C = b(F, E[A]);
var B = this.getGeneralNames(C);
G.issuer = B[0]["dn"];
}
if (H === "82") {
G.sn = { hex: k(F, E[A]) };
}
}
return G;
};
this.getExtExtKeyUsage = function(C, E) {
if (C === void 0 && E === void 0) {
var D = this.getExtInfo("extKeyUsage");
if (D === void 0) {
return void 0;
}
C = b(this.hex, D.vidx);
E = D.critical;
}
var z2 = { extname: "extKeyUsage", array: [] };
if (E) {
z2.critical = true;
}
var A = s(C, 0);
for (var B = 0; B < A.length; B++) {
z2.array.push(u(k(C, A[B])));
}
return z2;
};
this.getExtExtKeyUsageName = function() {
var D = this.getExtInfo("extKeyUsage");
if (D === void 0) {
return D;
}
var z2 = new Array();
var C = b(this.hex, D.vidx);
if (C === "") {
return z2;
}
var A = s(C, 0);
for (var B = 0; B < A.length; B++) {
z2.push(u(k(C, A[B])));
}
return z2;
};
this.getExtSubjectAltName = function(A, C) {
if (A === void 0 && C === void 0) {
var B = this.getExtInfo("subjectAltName");
if (B === void 0) {
return void 0;
}
A = b(this.hex, B.vidx);
C = B.critical;
}
var z2 = { extname: "subjectAltName", array: [] };
if (C) {
z2.critical = true;
}
z2.array = this.getGeneralNames(A);
return z2;
};
this.getExtIssuerAltName = function(A, C) {
if (A === void 0 && C === void 0) {
var B = this.getExtInfo("issuerAltName");
if (B === void 0) {
return void 0;
}
A = b(this.hex, B.vidx);
C = B.critical;
}
var z2 = { extname: "issuerAltName", array: [] };
if (C) {
z2.critical = true;
}
z2.array = this.getGeneralNames(A);
return z2;
};
this.getGeneralNames = function(D) {
var B = s(D, 0);
var z2 = [];
for (var C = 0; C < B.length; C++) {
var A = this.getGeneralName(b(D, B[C]));
if (A !== void 0) {
z2.push(A);
}
}
return z2;
};
this.getGeneralName = function(A) {
var z2 = A.substr(0, 2);
var C = k(A, 0);
var B = hextorstr(C);
if (z2 == "81") {
return { rfc822: B };
}
if (z2 == "82") {
return { dns: B };
}
if (z2 == "86") {
return { uri: B };
}
if (z2 == "87") {
return { ip: hextoip(C) };
}
if (z2 == "a4") {
return { dn: this.getX500Name(C) };
}
if (z2 == "a0") {
return { other: this.getOtherName(A) };
}
return void 0;
};
this.getExtSubjectAltName2 = function() {
var D, G, F;
var E = this.getExtInfo("subjectAltName");
if (E === void 0) {
return E;
}
var z2 = new Array();
var C = b(this.hex, E.vidx);
var A = s(C, 0);
for (var B = 0; B < A.length; B++) {
F = C.substr(A[B], 2);
D = k(C, A[B]);
if (F === "81") {
G = hextoutf8(D);
z2.push(["MAIL", G]);
}
if (F === "82") {
G = hextoutf8(D);
z2.push(["DNS", G]);
}
if (F === "84") {
G = X509.hex2dn(D, 0);
z2.push(["DN", G]);
}
if (F === "86") {
G = hextoutf8(D);
z2.push(["URI", G]);
}
if (F === "87") {
G = hextoip(D);
z2.push(["IP", G]);
}
}
return z2;
};
this.getExtCRLDistributionPoints = function(D, F) {
if (D === void 0 && F === void 0) {
var E = this.getExtInfo("cRLDistributionPoints");
if (E === void 0) {
return void 0;
}
D = b(this.hex, E.vidx);
F = E.critical;
}
var A = { extname: "cRLDistributionPoints", array: [] };
if (F) {
A.critical = true;
}
var B = s(D, 0);
for (var C = 0; C < B.length; C++) {
var z2 = b(D, B[C]);
A.array.push(this.getDistributionPoint(z2));
}
return A;
};
this.getDistributionPoint = function(E) {
var B = {};
var C = s(E, 0);
for (var D = 0; D < C.length; D++) {
var A = E.substr(C[D], 2);
var z2 = b(E, C[D]);
if (A == "a0") {
B.dpname = this.getDistributionPointName(z2);
}
}
return B;
};
this.getDistributionPointName = function(E) {
var B = {};
var C = s(E, 0);
for (var D = 0; D < C.length; D++) {
var A = E.substr(C[D], 2);
var z2 = b(E, C[D]);
if (A == "a0") {
B.full = this.getGeneralNames(z2);
}
}
return B;
};
this.getExtCRLDistributionPointsURI = function() {
var D = this.getExtCRLDistributionPoints();
if (D == void 0) {
return D;
}
var A = D.array;
var z2 = [];
for (var C = 0; C < A.length; C++) {
try {
if (A[C].dpname.full[0].uri != void 0) {
z2.push(A[C].dpname.full[0].uri);
}
} catch (B) {
}
}
return z2;
};
this.getExtAIAInfo = function() {
var D = this.getExtInfo("authorityInfoAccess");
if (D === void 0) {
return D;
}
var z2 = { ocsp: [], caissuer: [] };
var A = s(this.hex, D.vidx);
for (var B = 0; B < A.length; B++) {
var E = c(this.hex, A[B], [0], "06");
var C = c(this.hex, A[B], [1], "86");
if (E === "2b06010505073001") {
z2.ocsp.push(hextoutf8(C));
}
if (E === "2b06010505073002") {
z2.caissuer.push(hextoutf8(C));
}
}
return z2;
};
this.getExtAuthorityInfoAccess = function(G, E) {
if (G === void 0 && E === void 0) {
var z2 = this.getExtInfo("authorityInfoAccess");
if (z2 === void 0) {
return void 0;
}
G = b(this.hex, z2.vidx);
E = z2.critical;
}
var H = { extname: "authorityInfoAccess", array: [] };
if (E) {
H.critical = true;
}
var F = s(G, 0);
for (var A = 0; A < F.length; A++) {
var D = p(G, F[A], [0], "06");
var B = c(G, F[A], [1], "86");
var C = hextoutf8(B);
if (D == "2b06010505073001") {
H.array.push({ ocsp: C });
} else {
if (D == "2b06010505073002") {
H.array.push({ caissuer: C });
} else {
throw new Error("unknown method: " + D);
}
}
}
return H;
};
this.getExtCertificatePolicies = function(D, G) {
if (D === void 0 && G === void 0) {
var F = this.getExtInfo("certificatePolicies");
if (F === void 0) {
return void 0;
}
D = b(this.hex, F.vidx);
G = F.critical;
}
var z2 = { extname: "certificatePolicies", array: [] };
if (G) {
z2.critical = true;
}
var A = s(D, 0);
for (var B = 0; B < A.length; B++) {
var E = b(D, A[B]);
var C = this.getPolicyInformation(E);
z2.array.push(C);
}
return z2;
};
this.getPolicyInformation = function(D) {
var z2 = {};
var F = c(D, 0, [0], "06");
z2.policyoid = u(F);
var G = f(D, 0, [1], "30");
if (G != -1) {
z2.array = [];
var A = s(D, G);
for (var B = 0; B < A.length; B++) {
var E = b(D, A[B]);
var C = this.getPolicyQualifierInfo(E);
z2.array.push(C);
}
}
return z2;
};
this.getOtherName = function(B) {
var z2 = {};
var A = s(B, 0);
var D = c(B, A[0], [], "06");
var C = c(B, A[1], []);
z2.oid = u(D);
z2.value = j(C);
return z2;
};
this.getPolicyQualifierInfo = function(A) {
var z2 = {};
var B = c(A, 0, [0], "06");
if (B === "2b06010505070201") {
var D = p(A, 0, [1], "16");
z2.cps = hextorstr(D);
} else {
if (B === "2b06010505070202") {
var C = a(A, 0, [1], "30");
z2.unotice = this.getUserNotice(C);
}
}
return z2;
};
this.getUserNotice = function(B) {
var D = null;
var z2 = {};
try {
D = o2.parse(B);
var C = this._asn1ToUnotice(D);
return C;
} catch (A) {
return void 0;
}
};
this._asn1ToUnotice = function(E) {
try {
var z2 = {};
var A = aryval(E, "seq");
for (var C = 0; C < A.length; C++) {
var D = this._asn1ToNoticeRef(A[C]);
if (D != void 0) {
z2.noticeref = D;
}
var F = this.asn1ToDisplayText(A[C]);
if (F != void 0) {
z2.exptext = F;
}
}
if (Object.keys(z2).length > 0) {
return z2;
}
return void 0;
} catch (B) {
return void 0;
}
};
this._asn1ToNoticeRef = function(F) {
try {
var A = {};
var B = aryval(F, "seq");
for (var D = 0; D < B.length; D++) {
var E = this._asn1ToNoticeNum(B[D]);
if (E != void 0) {
A.noticenum = E;
}
var z2 = this.asn1ToDisplayText(B[D]);
if (z2 != void 0) {
A.org = z2;
}
}
if (Object.keys(A).length > 0) {
return A;
}
return void 0;
} catch (C) {
return void 0;
}
};
this._asn1ToNoticeNum = function(E) {
try {
var A = aryval(E, "seq");
var z2 = [];
for (var C = 0; C < A.length; C++) {
var D = A[C];
z2.push(parseInt(aryval(D, "int.hex"), 16));
}
return z2;
} catch (B) {
return void 0;
}
};
this.getDisplayText = function(A) {
var B = { "0c": "utf8", "16": "ia5", "1a": "vis", "1e": "bmp" };
var z2 = {};
z2.type = B[A.substr(0, 2)];
z2.str = hextorstr(k(A, 0));
return z2;
};
this.asn1ToDisplayText = function(z2) {
if (z2.utf8str != void 0) {
return { type: "utf8", str: z2.utf8str.str };
}
if (z2.ia5str != void 0) {
return { type: "ia5", str: z2.ia5str.str };
}
if (z2.visstr != void 0) {
return { type: "vis", str: z2.visstr.str };
}
if (z2.bmpstr != void 0) {
return { type: "bmp", str: z2.bmpstr.str };
}
if (z2.prnstr != void 0) {
return { type: "prn", str: z2.prnstr.str };
}
return void 0;
};
this.getExtPolicyMappings = function(G, E) {
var z2 = this.getCriticalExtV("policyMappings", G, E);
G = z2[0];
E = z2[1];
if (G == null) {
return void 0;
}
var I = { extname: "policyMappings" };
if (E) {
I.critical = true;
}
try {
var A = j(G);
var B = A.seq;
var F = [];
for (var C = 0; C < B.length; C++) {
var H = B[C].seq;
F.push([H[0].oid, H[1].oid]);
}
I.array = F;
} catch (D) {
throw new m("malformed policyMappings");
}
return I;
};
this.getExtPolicyConstraints = function(G, D) {
var z2 = this.getCriticalExtV("policyConstraints", G, D);
G = z2[0];
D = z2[1];
if (G == null) {
return void 0;
}
var H = { extname: "policyConstraints" };
if (D) {
H.critical = true;
}
var A = j(G);
try {
var F = A.seq;
for (var B = 0; B < F.length; B++) {
var E = F[B].tag;
if (E.explicit != false) {
continue;
}
if (E.tag == "80") {
H.reqexp = parseInt(E.hex, 16);
}
if (E.tag == "81") {
H.inhibit = parseInt(E.hex, 16);
}
}
} catch (C) {
return new m("malformed policyConstraints value");
}
return H;
};
this.getExtInhibitAnyPolicy = function(A, D) {
var C = this.getCriticalExtV("inhibitAnyPolicy", A, D);
A = C[0];
D = C[1];
if (A == null) {
return void 0;
}
var z2 = { extname: "inhibitAnyPolicy" };
if (D) {
z2.critical = true;
}
var B = x(A, 0);
if (B == -1) {
return new m("wrong value");
}
z2.skip = B;
return z2;
};
this.getExtCRLNumber = function(A, B) {
var z2 = { extname: "cRLNumber" };
if (B) {
z2.critical = true;
}
if (A.substr(0, 2) == "02") {
z2.num = { hex: k(A, 0) };
return z2;
}
throw new m("hExtV parse error: " + A);
};
this.getExtCRLReason = function(A, B) {
var z2 = { extname: "cRLReason" };
if (B) {
z2.critical = true;
}
if (A.substr(0, 2) == "0a") {
z2.code = parseInt(k(A, 0), 16);
return z2;
}
throw new Error("hExtV parse error: " + A);
};
this.getExtOcspNonce = function(A, C) {
var z2 = { extname: "ocspNonce" };
if (C) {
z2.critical = true;
}
var B = k(A, 0);
z2.hex = B;
return z2;
};
this.getExtOcspNoCheck = function(A, B) {
var z2 = { extname: "ocspNoCheck" };
if (B) {
z2.critical = true;
}
return z2;
};
this.getExtAdobeTimeStamp = function(C, F) {
if (C === void 0 && F === void 0) {
var E = this.getExtInfo("adobeTimeStamp");
if (E === void 0) {
return void 0;
}
C = b(this.hex, E.vidx);
F = E.critical;
}
var z2 = { extname: "adobeTimeStamp" };
if (F) {
z2.critical = true;
}
var B = s(C, 0);
if (B.length > 1) {
var G = b(C, B[1]);
var A = this.getGeneralName(G);
if (A.uri != void 0) {
z2.uri = A.uri;
}
}
if (B.length > 2) {
var D = b(C, B[2]);
if (D == "0101ff") {
z2.reqauth = true;
}
if (D == "010100") {
z2.reqauth = false;
}
}
return z2;
};
this.getExtSubjectDirectoryAttributes = function(I, H) {
if (I === void 0 && H === void 0) {
var B = this.getExtInfo("subjectDirectoryAttributes");
if (B === void 0) {
return void 0;
}
I = b(this.hex, B.vidx);
H = B.critical;
}
var J = { extname: "subjectDirectoryAttributes" };
if (H) {
J.critical = true;
}
try {
var z2 = j(I);
var D = [];
for (var E = 0; E < z2.seq.length; E++) {
var A = z2.seq[E];
var C = aryval(A, "seq.0.oid");
var F = aryval(A, "seq.1.set");
if (C == void 0 || F == void 0) {
throw "error";
}
D.push({ attr: C, array: F });
}
J.array = D;
return J;
} catch (G) {
throw new Error("malformed subjectDirectoryAttributes extension value");
}
};
var e2 = function(E) {
var z2 = {};
try {
var B = E.seq[0].oid;
var D = KJUR.asn1.x509.OID.name2oid(B);
z2.type = KJUR.asn1.x509.OID.oid2atype(D);
var A = E.seq[1];
if (A.utf8str != void 0) {
z2.ds = "utf8";
z2.value = A.utf8str.str;
} else {
if (A.numstr != void 0) {
z2.ds = "num";
z2.value = A.numstr.str;
} else {
if (A.telstr != void 0) {
z2.ds = "tel";
z2.value = A.telstr.str;
} else {
if (A.prnstr != void 0) {
z2.ds = "prn";
z2.value = A.prnstr.str;
} else {
if (A.ia5str != void 0) {
z2.ds = "ia5";
z2.value = A.ia5str.str;
} else {
if (A.visstr != void 0) {
z2.ds = "vis";
z2.value = A.visstr.str;
} else {
if (A.bmpstr != void 0) {
z2.ds = "bmp";
z2.value = A.bmpstr.str;
} else {
throw "error";
}
}
}
}
}
}
}
return z2;
} catch (C) {
throw new Erorr("improper ASN.1 parsed AttrTypeAndValue");
}
};
var i = function(A) {
try {
return A.set.map(function(B) {
return e2(B);
});
} catch (z2) {
throw new Error("improper ASN.1 parsed RDN: " + z2);
}
};
var h = function(A) {
try {
return A.seq.map(function(B) {
return i(B);
});
} catch (z2) {
throw new Error("improper ASN.1 parsed X500Name: " + z2);
}
};
this.getX500NameRule = function(z2) {
var G = true;
var K = true;
var J = false;
var A = "";
var D = "";
var M = null;
var H = [];
for (var C = 0; C < z2.length; C++) {
var E = z2[C];
for (var B = 0; B < E.length; B++) {
H.push(E[B]);
}
}
for (var C = 0; C < H.length; C++) {
var L = H[C];
var N = L.ds;
var I = L.value;
var F = L.type;
A += ":" + N;
if (N != "prn" && N != "utf8" && N != "ia5") {
return "mixed";
}
if (N == "ia5") {
if (F != "CN") {
return "mixed";
} else {
if (!KJUR.lang.String.isMail(I)) {
return "mixed";
} else {
continue;
}
}
}
if (F == "C") {
if (N == "prn") {
continue;
} else {
return "mixed";
}
}
D += ":" + N;
if (M == null) {
M = N;
} else {
if (M !== N) {
return "mixed";
}
}
}
if (M == null) {
return "prn";
} else {
return M;
}
};
this.getAttrTypeAndValue = function(z2) {
var A = j(z2);
return e2(A);
};
this.getRDN = function(z2) {
var A = j(z2);
return i(A);
};
this.getX500NameArray = function(z2) {
var A = j(z2);
return h(A);
};
this.getX500Name = function(C, E, D) {
var A = this.getX500NameArray(C);
var B = this.dnarraytostr(A);
var z2 = { str: B };
z2.array = A;
if (D == true) {
z2.hex = C;
}
if (E == true) {
z2.canon = this.c14nRDNArray(A);
}
return z2;
};
this.readCertPEM = function(z2) {
this.readCertHex(w(z2));
};
this.readCertHex = function(z2) {
this.hex = z2;
this.getVersion();
try {
l(this.hex, 0, [0, 7], "a3");
this.parseExt();
} catch (A) {
}
};
this.getParam = function(A) {
var z2 = {};
if (A == void 0) {
A = {};
}
z2.version = this.getVersion();
z2.serial = { hex: this.getSerialNumberHex() };
z2.sigalg = this.getSignatureAlgorithmField();
z2.issuer = this.getIssuer(A.dncanon, A.dnhex);
z2.notbefore = this.getNotBefore();
z2.notafter = this.getNotAfter();
z2.subject = this.getSubject(A.dncanon, A.dnhex);
z2.sbjpubkey = hextopem(this.getPublicKeyHex(), "PUBLIC KEY");
if (this.aExtInfo != void 0 && this.aExtInfo.length > 0) {
z2.ext = this.getExtParamArray();
}
z2.sighex = this.getSignatureValueHex();
if (A.tbshex == true) {
z2.tbshex = a(this.hex, 0, [0]);
}
if (A.nodnarray == true) {
delete z2.issuer.array;
delete z2.subject.array;
}
return z2;
};
this.getExtParamArray = function(A) {
if (A == void 0) {
var C = f(this.hex, 0, [0, "[3]"]);
if (C != -1) {
A = q(this.hex, 0, [0, "[3]", 0], "30");
}
}
var z2 = [];
var B = s(A, 0);
for (var D = 0; D < B.length; D++) {
var F = b(A, B[D]);
var E = this.getExtParam(F);
if (E != null) {
z2.push(E);
}
}
return z2;
};
this.getExtParam = function(A) {
var I = {};
var C = s(A, 0);
var E = C.length;
if (E != 2 && E != 3) {
throw new Error("wrong number elements in Extension: " + E + " " + A);
}
var B = r2(c(A, 0, [0], "06"));
var G = false;
if (E == 3 && a(A, 0, [1]) == "0101ff") {
G = true;
}
var H = a(A, 0, [E - 1, 0]);
var F = void 0;
if (B == "2.5.29.14") {
F = this.getExtSubjectKeyIdentifier(H, G);
} else {
if (B == "2.5.29.15") {
F = this.getExtKeyUsage(H, G);
} else {
if (B == "2.5.29.17") {
F = this.getExtSubjectAltName(H, G);
} else {
if (B == "2.5.29.18") {
F = this.getExtIssuerAltName(H, G);
} else {
if (B == "2.5.29.19") {
F = this.getExtBasicConstraints(H, G);
} else {
if (B == "2.5.29.30") {
F = this.getExtNameConstraints(H, G);
} else {
if (B == "2.5.29.31") {
F = this.getExtCRLDistributionPoints(H, G);
} else {
if (B == "2.5.29.32") {
F = this.getExtCertificatePolicies(H, G);
} else {
if (B == "2.5.29.33") {
F = this.getExtPolicyMappings(H, G);
} else {
if (B == "2.5.29.35") {
F = this.getExtAuthorityKeyIdentifier(H, G);
} else {
if (B == "2.5.29.36") {
F = this.getExtPolicyConstraints(H, G);
} else {
if (B == "2.5.29.37") {
F = this.getExtExtKeyUsage(H, G);
} else {
if (B == "2.5.29.54") {
F = this.getExtInhibitAnyPolicy(H, G);
} else {
if (B == "1.3.6.1.5.5.7.1.1") {
F = this.getExtAuthorityInfoAccess(H, G);
} else {
if (B == "2.5.29.20") {
F = this.getExtCRLNumber(H, G);
} else {
if (B == "2.5.29.21") {
F = this.getExtCRLReason(H, G);
} else {
if (B == "2.5.29.9") {
F = this.getExtSubjectDirectoryAttributes(H, G);
} else {
if (B == "1.3.6.1.5.5.7.48.1.2") {
F = this.getExtOcspNonce(H, G);
} else {
if (B == "1.3.6.1.5.5.7.48.1.5") {
F = this.getExtOcspNoCheck(H, G);
} else {
if (B == "1.2.840.113583.1.1.9.1") {
F = this.getExtAdobeTimeStamp(H, G);
} else {
if (X509.EXT_PARSER[B] != void 0) {
F = X509.EXT_PARSER[B](B, G, H);
}
}
}
}
}
}
}
}
}
}
}
}
}
}
}
}
}
}
}
}
}
if (F != void 0) {
return F;
}
var z2 = { extname: B, extn: H };
try {
z2.extn = j(H);
} catch (D) {
}
if (G) {
z2.critical = true;
}
return z2;
};
this.findExt = function(A, B) {
for (var z2 = 0; z2 < A.length; z2++) {
if (A[z2].extname == B) {
return A[z2];
}
}
return null;
};
this.updateExtCDPFullURI = function(D, z2) {
var C = this.findExt(D, "cRLDistributionPoints");
if (C == null) {
return;
}
if (C.array == void 0) {
return;
}
var F = C.array;
for (var B = 0; B < F.length; B++) {
if (F[B].dpname == void 0) {
continue;
}
if (F[B].dpname.full == void 0) {
continue;
}
var G = F[B].dpname.full;
for (var A = 0; A < G.length; A++) {
var E = G[B];
if (E.uri == void 0) {
continue;
}
E.uri = z2;
}
}
};
this.updateExtAIAOCSP = function(D, A) {
var C = this.findExt(D, "authorityInfoAccess");
if (C == null) {
return;
}
if (C.array == void 0) {
return;
}
var z2 = C.array;
for (var B = 0; B < z2.length; B++) {
if (z2[B].ocsp != void 0) {
z2[B].ocsp = A;
}
}
};
this.updateExtAIACAIssuer = function(D, A) {
var C = this.findExt(D, "authorityInfoAccess");
if (C == null) {
return;
}
if (C.array == void 0) {
return;
}
var z2 = C.array;
for (var B = 0; B < z2.length; B++) {
if (z2[B].caissuer != void 0) {
z2[B].caissuer = A;
}
}
};
this.dnarraytostr = function(B) {
function z2(C) {
return C.map(function(D) {
return A(D).replace(/\+/, "\\+");
}).join("+");
}
function A(C) {
return C.type + "=" + C.value;
}
return "/" + B.map(function(C) {
return z2(C).replace(/\//, "\\/");
}).join("/");
};
this.setCanonicalizedDN = function(A) {
var C;
if (A.str != void 0 && A.array == void 0) {
var B = new KJUR.asn1.x509.X500Name({ str: A.str });
var z2 = B.tohex();
C = this.getX500NameArray(z2);
} else {
C = A.array;
}
if (A.canon == void 0) {
A.canon = this.c14nRDNArray(C);
}
};
this.c14nRDNArray = function(G) {
var A = [];
for (var C = 0; C < G.length; C++) {
var E = G[C];
var z2 = [];
for (var B = 0; B < E.length; B++) {
var D = E[B];
var F = D.value;
F = F.replace(/^\s*/, "");
F = F.replace(/\s*$/, "");
F = F.replace(/\s+/g, " ");
F = F.toLowerCase();
z2.push(D.type.toLowerCase() + "=" + F);
}
A.push(z2.join("+"));
}
return "/" + A.join("/");
};
this.getInfo = function() {
var A = function(W) {
var ac = "";
var U = " ";
var Y = "\n";
var Z = W.array;
for (var X = 0; X < Z.length; X++) {
var V = Z[X];
if (V.dn != void 0) {
ac += U + "dn: " + V.dn.str + Y;
}
if (V.ip != void 0) {
ac += U + "ip: " + V.ip + Y;
}
if (V.rfc822 != void 0) {
ac += U + "rfc822: " + V.rfc822 + Y;
}
if (V.dns != void 0) {
ac += U + "dns: " + V.dns + Y;
}
if (V.uri != void 0) {
ac += U + "uri: " + V.uri + Y;
}
if (V.other != void 0) {
var ab = V.other.oid;
var aa = JSON.stringify(V.other.value).replace(/\"/g, "");
ac += U + "other: " + ab + "=" + aa + Y;
}
}
ac = ac.replace(/\n$/, "");
return ac;
};
var H = function(aa) {
var Y = "";
var U = aa.array;
for (var X = 0; X < U.length; X++) {
var Z = U[X];
Y += " policy oid: " + Z.policyoid + "\n";
if (Z.array === void 0) {
continue;
}
for (var W = 0; W < Z.array.length; W++) {
var V = Z.array[W];
if (V.cps !== void 0) {
Y += " cps: " + V.cps + "\n";
}
}
}
return Y;
};
var K = function(Y) {
var X = "";
var U = Y.array;
for (var W = 0; W < U.length; W++) {
var Z = U[W];
try {
if (Z.dpname.full[0].uri !== void 0) {
X += " " + Z.dpname.full[0].uri + "\n";
}
} catch (V) {
}
try {
if (Z.dname.full[0].dn.hex !== void 0) {
X += " " + X509.hex2dn(Z.dpname.full[0].dn.hex) + "\n";
}
} catch (V) {
}
}
return X;
};
var I = function(Y) {
var X = "";
var U = Y.array;
for (var V = 0; V < U.length; V++) {
var W = U[V];
if (W.caissuer !== void 0) {
X += " caissuer: " + W.caissuer + "\n";
}
if (W.ocsp !== void 0) {
X += " ocsp: " + W.ocsp + "\n";
}
}
return X;
};
var B = X509;
var M, L, T;
M = "Basic Fields\n";
M += " serial number: " + this.getSerialNumberHex() + "\n";
M += " signature algorithm: " + this.getSignatureAlgorithmField() + "\n";
M += " issuer: " + this.getIssuerString() + "\n";
M += " notBefore: " + this.getNotBefore() + "\n";
M += " notAfter: " + this.getNotAfter() + "\n";
M += " subject: " + this.getSubjectString() + "\n";
M += " subject public key info: \n";
L = this.getPublicKey();
M += " key algorithm: " + L.type + "\n";
if (L.type === "RSA") {
M += " n=" + hextoposhex(L.n.toString(16)).substr(0, 16) + "...\n";
M += " e=" + hextoposhex(L.e.toString(16)) + "\n";
}
T = this.aExtInfo;
if (T !== void 0 && T !== null) {
M += "X509v3 Extensions:\n";
for (var P = 0; P < T.length; P++) {
var R = T[P];
var z2 = KJUR.asn1.x509.OID.oid2name(R.oid);
if (z2 === "") {
z2 = R.oid;
}
var O = "";
if (R.critical === true) {
O = "CRITICAL";
}
M += " " + z2 + " " + O + ":\n";
if (z2 === "basicConstraints") {
var C = this.getExtBasicConstraints();
if (C.cA === void 0) {
M += " {}\n";
} else {
M += " cA=true";
if (C.pathLen !== void 0) {
M += ", pathLen=" + C.pathLen;
}
M += "\n";
}
} else {
if (z2 == "policyMappings") {
var S = this.getExtPolicyMappings().array;
var G = S.map(function(U) {
var V = U;
return V[0] + ":" + V[1];
}).join(", ");
M += " " + G + "\n";
} else {
if (z2 == "policyConstraints") {
var N = this.getExtPolicyConstraints();
M += " ";
if (N.reqexp != void 0) {
M += " reqexp=" + N.reqexp;
}
if (N.inhibit != void 0) {
M += " inhibit=" + N.inhibit;
}
M += "\n";
} else {
if (z2 == "inhibitAnyPolicy") {
var N = this.getExtInhibitAnyPolicy();
M += " skip=" + N.skip + "\n";
} else {
if (z2 == "keyUsage") {
M += " " + this.getExtKeyUsageString() + "\n";
} else {
if (z2 == "subjectKeyIdentifier") {
M += " " + this.getExtSubjectKeyIdentifier().kid.hex + "\n";
} else {
if (z2 == "authorityKeyIdentifier") {
var D = this.getExtAuthorityKeyIdentifier();
if (D.kid !== void 0) {
M += " kid=" + D.kid.hex + "\n";
}
} else {
if (z2 == "extKeyUsage") {
var Q = this.getExtExtKeyUsage().array;
M += " " + Q.join(", ") + "\n";
} else {
if (z2 == "subjectAltName") {
var E = A(this.getExtSubjectAltName());
M += E + "\n";
} else {
if (z2 == "cRLDistributionPoints") {
var J = this.getExtCRLDistributionPoints();
M += K(J);
} else {
if (z2 == "authorityInfoAccess") {
var F = this.getExtAuthorityInfoAccess();
M += I(F);
} else {
if (z2 == "certificatePolicies") {
M += H(this.getExtCertificatePolicies());
}
}
}
}
}
}
}
}
}
}
}
}
}
}
M += "signature algorithm: " + this.getSignatureAlgorithmName() + "\n";
M += "signature: " + this.getSignatureValueHex().substr(0, 16) + "...\n";
return M;
};
if (typeof v == "string") {
if (v.indexOf("-----BEGIN") != -1) {
this.readCertPEM(v);
} else {
if (KJUR.lang.String.isHex(v)) {
this.readCertHex(v);
}
}
}
}
X509.EXT_PARSER = {};
X509.registExtParser = function(b, a) {
X509.EXT_PARSER[b] = a;
};
X509.hex2dn = function(e2, b) {
if (b === void 0) {
b = 0;
}
var a = new X509();
var c = ASN1HEX.getTLV(e2, b);
var d = a.getX500Name(e2);
return d.str;
};
X509.hex2rdn = function(f, b) {
if (b === void 0) {
b = 0;
}
if (f.substr(b, 2) !== "31") {
throw new Error("malformed RDN");
}
var c = new Array();
var d = ASN1HEX.getChildIdx(f, b);
for (var e2 = 0; e2 < d.length; e2++) {
c.push(X509.hex2attrTypeValue(f, d[e2]));
}
c = c.map(function(a) {
return a.replace("+", "\\+");
});
return c.join("+");
};
X509.hex2attrTypeValue = function(d, i) {
var j = ASN1HEX;
var h = j.getV;
if (i === void 0) {
i = 0;
}
if (d.substr(i, 2) !== "30") {
throw new Error("malformed attribute type and value");
}
var g = j.getChildIdx(d, i);
if (g.length !== 2 || d.substr(g[0], 2) !== "06") {
"malformed attribute type and value";
}
var b = h(d, g[0]);
var f = KJUR.asn1.ASN1Util.oidHexToInt(b);
var e2 = KJUR.asn1.x509.OID.oid2atype(f);
var a = h(d, g[1]);
var c = hextorstr(a);
return e2 + "=" + c;
};
X509.getPublicKeyFromCertHex = function(b) {
var a = new X509();
a.readCertHex(b);
return a.getPublicKey();
};
X509.getPublicKeyFromCertPEM = function(b) {
var a = new X509();
a.readCertPEM(b);
return a.getPublicKey();
};
X509.getPublicKeyInfoPropOfCertPEM = function(c) {
var e2 = ASN1HEX;
var g = e2.getVbyList;
var b = {};
var a, f, d;
b.algparam = null;
a = new X509();
a.readCertPEM(c);
f = a.getPublicKeyHex();
b.keyhex = g(f, 0, [1], "03").substr(2);
b.algoid = g(f, 0, [0, 0], "06");
if (b.algoid === "2a8648ce3d0201") {
b.algparam = g(f, 0, [0, 1], "06");
}
return b;
};
X509.KEYUSAGE_NAME = ["digitalSignature", "nonRepudiation", "keyEncipherment", "dataEncipherment", "keyAgreement", "keyCertSign", "cRLSign", "encipherOnly", "decipherOnly"];
var X509CRL = function(e2) {
var a = KJUR, f = a.lang.String.isHex, m = ASN1HEX, k = m.getV, b = m.getTLV, h = m.getVbyList, c = m.getTLVbyList, d = m.getTLVbyListEx, i = m.getIdxbyList, g = m.getIdxbyListEx, l = m.getChildIdx, j = new X509();
this.hex = null;
this.posSigAlg = null;
this.posRevCert = null;
this.parsed = null;
this._setPos = function() {
var o2 = i(this.hex, 0, [0, 0]);
var n2 = this.hex.substr(o2, 2);
if (n2 == "02") {
this.posSigAlg = 1;
} else {
if (n2 == "30") {
this.posSigAlg = 0;
} else {
throw new Error("malformed 1st item of TBSCertList: " + n2);
}
}
var s = i(this.hex, 0, [0, this.posSigAlg + 3]);
var r2 = this.hex.substr(s, 2);
if (r2 == "17" || r2 == "18") {
var q, p;
q = i(this.hex, 0, [0, this.posSigAlg + 4]);
this.posRevCert = null;
if (q != -1) {
p = this.hex.substr(q, 2);
if (p == "30") {
this.posRevCert = this.posSigAlg + 4;
}
}
} else {
if (r2 == "30") {
this.posRevCert = this.posSigAlg + 3;
} else {
if (r2 == "a0") {
this.posRevCert = null;
} else {
throw new Error("malformed nextUpdate or revCert tag: " + r2);
}
}
}
};
this.getVersion = function() {
if (this.posSigAlg == 0) {
return null;
}
return parseInt(h(this.hex, 0, [0, 0], "02"), 16) + 1;
};
this.getSignatureAlgorithmField = function() {
var n2 = c(this.hex, 0, [0, this.posSigAlg], "30");
return j.getAlgorithmIdentifierName(n2);
};
this.getIssuer = function() {
return j.getX500Name(this.getIssuerHex());
};
this.getIssuerHex = function() {
return c(this.hex, 0, [0, this.posSigAlg + 1], "30");
};
this.getThisUpdate = function() {
var n2 = h(this.hex, 0, [0, this.posSigAlg + 2]);
return result = hextorstr(n2);
};
this.getNextUpdate = function() {
var o2 = i(this.hex, 0, [0, this.posSigAlg + 3]);
var n2 = this.hex.substr(o2, 2);
if (n2 != "17" && n2 != "18") {
return null;
}
return hextorstr(k(this.hex, o2));
};
this.getRevCertArray = function() {
if (this.posRevCert == null) {
return null;
}
var o2 = [];
var n2 = i(this.hex, 0, [0, this.posRevCert]);
var p = l(this.hex, n2);
for (var q = 0; q < p.length; q++) {
var r2 = b(this.hex, p[q]);
o2.push(this.getRevCert(r2));
}
return o2;
};
this.getRevCert = function(p) {
var o2 = {};
var n2 = l(p, 0);
o2.sn = { hex: h(p, 0, [0], "02") };
o2.date = hextorstr(h(p, 0, [1]));
if (n2.length == 3) {
o2.ext = j.getExtParamArray(c(p, 0, [2]));
}
return o2;
};
this.findRevCert = function(p) {
var n2 = new X509(p);
var o2 = n2.getSerialNumberHex();
return this.findRevCertBySN(o2);
};
this.findRevCertBySN = function(o2) {
if (this.parsed == null) {
this.getParam();
}
if (this.parsed.revcert == null) {
return null;
}
var n2 = this.parsed.revcert;
for (var p = 0; p < n2.length; p++) {
if (o2 == n2[p].sn.hex) {
return n2[p];
}
}
return null;
};
this.getSignatureValueHex = function() {
return h(this.hex, 0, [2], "03", true);
};
this.verifySignature = function(o2) {
var p = this.getSignatureAlgorithmField();
var n2 = this.getSignatureValueHex();
var q = c(this.hex, 0, [0], "30");
var r2 = new KJUR.crypto.Signature({ alg: p });
r2.init(o2);
r2.updateHex(q);
return r2.verify(n2);
};
this.getParam = function(r2) {
var n2 = {};
var p = this.getVersion();
if (p != null) {
n2.version = p;
}
n2.sigalg = this.getSignatureAlgorithmField();
n2.issuer = this.getIssuer();
n2.thisupdate = this.getThisUpdate();
var q = this.getNextUpdate();
if (q != null) {
n2.nextupdate = q;
}
var t3 = this.getRevCertArray();
if (t3 != null) {
n2.revcert = t3;
}
var s = g(this.hex, 0, [0, "[0]"]);
if (s != -1) {
var o2 = d(this.hex, 0, [0, "[0]", 0]);
n2.ext = j.getExtParamArray(o2);
}
n2.sighex = this.getSignatureValueHex();
this.parsed = n2;
if (typeof r2 == "object") {
if (r2.tbshex == true) {
n2.tbshex = c(this.hex, 0, [0]);
}
if (r2.nodnarray == true) {
delete n2.issuer.array;
}
}
return n2;
};
if (typeof e2 == "string") {
if (f(e2)) {
this.hex = e2;
} else {
if (e2.match(/-----BEGIN X509 CRL/)) {
this.hex = pemtohex(e2);
}
}
this._setPos();
}
};
if (typeof KJUR == "undefined" || !KJUR) {
KJUR = {};
}
if (typeof KJUR.jws == "undefined" || !KJUR.jws) {
KJUR.jws = {};
}
KJUR.jws.JWS = function() {
var b = KJUR, a = b.jws.JWS, c = a.isSafeJSONString;
this.parseJWS = function(g, j) {
if (this.parsedJWS !== void 0 && (j || this.parsedJWS.sigvalH !== void 0)) {
return;
}
var i = g.match(/^([^.]+)\.([^.]+)\.([^.]+)$/);
if (i == null) {
throw "JWS signature is not a form of 'Head.Payload.SigValue'.";
}
var k = i[1];
var e2 = i[2];
var l = i[3];
var n2 = k + "." + e2;
this.parsedJWS = {};
this.parsedJWS.headB64U = k;
this.parsedJWS.payloadB64U = e2;
this.parsedJWS.sigvalB64U = l;
this.parsedJWS.si = n2;
if (!j) {
var h = b64utohex(l);
var f = parseBigInt(h, 16);
this.parsedJWS.sigvalH = h;
this.parsedJWS.sigvalBI = f;
}
var d = b64utoutf8(k);
var m = b64utoutf8(e2);
this.parsedJWS.headS = d;
this.parsedJWS.payloadS = m;
if (!c(d, this.parsedJWS, "headP")) {
throw "malformed JSON string for JWS Head: " + d;
}
};
};
KJUR.jws.JWS.sign = function(j, w, z2, A, a) {
var x = KJUR, n2 = x.jws, r2 = n2.JWS, h = r2.readSafeJSONString, q = r2.isSafeJSONString, d = x.crypto, l = d.ECDSA, p = d.Mac, c = d.Signature, u = JSON;
var t3, k, o2;
if (typeof w != "string" && typeof w != "object") {
throw "spHeader must be JSON string or object: " + w;
}
if (typeof w == "object") {
k = w;
t3 = u.stringify(k);
}
if (typeof w == "string") {
t3 = w;
if (!q(t3)) {
throw "JWS Head is not safe JSON string: " + t3;
}
k = h(t3);
}
o2 = z2;
if (typeof z2 == "object") {
o2 = u.stringify(z2);
}
if ((j == "" || j == null) && k.alg !== void 0) {
j = k.alg;
}
if (j != "" && j != null && k.alg === void 0) {
k.alg = j;
t3 = u.stringify(k);
}
if (j !== k.alg) {
throw "alg and sHeader.alg doesn't match: " + j + "!=" + k.alg;
}
var s = null;
if (r2.jwsalg2sigalg[j] === void 0) {
throw "unsupported alg name: " + j;
} else {
s = r2.jwsalg2sigalg[j];
}
var e2 = utf8tob64u(t3);
var m = utf8tob64u(o2);
var b = e2 + "." + m;
var y = "";
if (s.substr(0, 4) == "Hmac") {
if (A === void 0) {
throw "mac key shall be specified for HS* alg";
}
var i = new p({ alg: s, prov: "cryptojs", pass: A });
i.updateString(b);
y = i.doFinal();
} else {
if (s.indexOf("withECDSA") != -1) {
var f = new c({ alg: s });
f.init(A, a);
f.updateString(b);
var g = f.sign();
y = KJUR.crypto.ECDSA.asn1SigToConcatSig(g);
} else {
if (s != "none") {
var f = new c({ alg: s });
f.init(A, a);
f.updateString(b);
y = f.sign();
}
}
}
var v = hextob64u(y);
return b + "." + v;
};
KJUR.jws.JWS.verify = function(w, B, n2) {
var x = KJUR, q = x.jws, t3 = q.JWS, i = t3.readSafeJSONString, e2 = x.crypto, p = e2.ECDSA, s = e2.Mac, d = e2.Signature, m;
if (typeof RSAKey !== void 0) {
m = RSAKey;
}
if (!isBase64URLDot(w)) {
return false;
}
var y = w.split(".");
if (y.length !== 3) {
return false;
}
var f = y[0];
var r2 = y[1];
var c = f + "." + r2;
var A = b64utohex(y[2]);
var l = i(b64utoutf8(y[0]));
var k = null;
var z2 = null;
if (l.alg === void 0) {
throw "algorithm not specified in header";
} else {
k = l.alg;
z2 = k.substr(0, 2);
}
if (n2 != null && Object.prototype.toString.call(n2) === "[object Array]" && n2.length > 0) {
var b = ":" + n2.join(":") + ":";
if (b.indexOf(":" + k + ":") == -1) {
throw "algorithm '" + k + "' not accepted in the list";
}
}
if (k != "none" && B === null) {
throw "key shall be specified to verify.";
}
if (typeof B == "string" && B.indexOf("-----BEGIN ") != -1) {
B = KEYUTIL.getKey(B);
}
if (z2 == "RS" || z2 == "PS") {
if (!(B instanceof m)) {
throw "key shall be a RSAKey obj for RS* and PS* algs";
}
}
if (z2 == "ES") {
if (!(B instanceof p)) {
throw "key shall be a ECDSA obj for ES* algs";
}
}
if (k == "none") {
}
var u = null;
if (t3.jwsalg2sigalg[l.alg] === void 0) {
throw "unsupported alg name: " + k;
} else {
u = t3.jwsalg2sigalg[k];
}
if (u == "none") {
throw "not supported";
} else {
if (u.substr(0, 4) == "Hmac") {
var o2 = null;
if (B === void 0) {
throw "hexadecimal key shall be specified for HMAC";
}
var j = new s({ alg: u, pass: B });
j.updateString(c);
o2 = j.doFinal();
return A == o2;
} else {
if (u.indexOf("withECDSA") != -1) {
var h = null;
try {
h = p.concatSigToASN1Sig(A);
} catch (v) {
return false;
}
var g = new d({ alg: u });
g.init(B);
g.updateString(c);
return g.verify(h);
} else {
var g = new d({ alg: u });
g.init(B);
g.updateString(c);
return g.verify(A);
}
}
}
};
KJUR.jws.JWS.parse = function(g) {
var c = g.split(".");
var b = {};
var f, e2, d;
if (c.length != 2 && c.length != 3) {
throw "malformed sJWS: wrong number of '.' splitted elements";
}
f = c[0];
e2 = c[1];
if (c.length == 3) {
d = c[2];
}
b.headerObj = KJUR.jws.JWS.readSafeJSONString(b64utoutf8(f));
b.payloadObj = KJUR.jws.JWS.readSafeJSONString(b64utoutf8(e2));
b.headerPP = JSON.stringify(b.headerObj, null, " ");
if (b.payloadObj == null) {
b.payloadPP = b64utoutf8(e2);
} else {
b.payloadPP = JSON.stringify(b.payloadObj, null, " ");
}
if (d !== void 0) {
b.sigHex = b64utohex(d);
}
return b;
};
KJUR.jws.JWS.verifyJWT = function(e2, l, r2) {
var d = KJUR, j = d.jws, o2 = j.JWS, n2 = o2.readSafeJSONString, p = o2.inArray, f = o2.includedArray;
if (!isBase64URLDot(e2)) {
return false;
}
var k = e2.split(".");
if (k.length != 3) {
return false;
}
var c = k[0];
var i = k[1];
var q = c + "." + i;
var m = b64utohex(k[2]);
var h = n2(b64utoutf8(c));
var g = n2(b64utoutf8(i));
if (h.alg === void 0) {
return false;
}
if (r2.alg === void 0) {
throw "acceptField.alg shall be specified";
}
if (!p(h.alg, r2.alg)) {
return false;
}
if (g.iss !== void 0 && typeof r2.iss === "object") {
if (!p(g.iss, r2.iss)) {
return false;
}
}
if (g.sub !== void 0 && typeof r2.sub === "object") {
if (!p(g.sub, r2.sub)) {
return false;
}
}
if (g.aud !== void 0 && typeof r2.aud === "object") {
if (typeof g.aud == "string") {
if (!p(g.aud, r2.aud)) {
return false;
}
} else {
if (typeof g.aud == "object") {
if (!f(g.aud, r2.aud)) {
return false;
}
}
}
}
var b = j.IntDate.getNow();
if (r2.verifyAt !== void 0 && typeof r2.verifyAt === "number") {
b = r2.verifyAt;
}
if (r2.gracePeriod === void 0 || typeof r2.gracePeriod !== "number") {
r2.gracePeriod = 0;
}
if (g.exp !== void 0 && typeof g.exp == "number") {
if (g.exp + r2.gracePeriod < b) {
return false;
}
}
if (g.nbf !== void 0 && typeof g.nbf == "number") {
if (b < g.nbf - r2.gracePeriod) {
return false;
}
}
if (g.iat !== void 0 && typeof g.iat == "number") {
if (b < g.iat - r2.gracePeriod) {
return false;
}
}
if (g.jti !== void 0 && r2.jti !== void 0) {
if (g.jti !== r2.jti) {
return false;
}
}
if (!o2.verify(e2, l, r2.alg)) {
return false;
}
return true;
};
KJUR.jws.JWS.includedArray = function(b, a) {
var c = KJUR.jws.JWS.inArray;
if (b === null) {
return false;
}
if (typeof b !== "object") {
return false;
}
if (typeof b.length !== "number") {
return false;
}
for (var d = 0; d < b.length; d++) {
if (!c(b[d], a)) {
return false;
}
}
return true;
};
KJUR.jws.JWS.inArray = function(d, b) {
if (b === null) {
return false;
}
if (typeof b !== "object") {
return false;
}
if (typeof b.length !== "number") {
return false;
}
for (var c = 0; c < b.length; c++) {
if (b[c] == d) {
return true;
}
}
return false;
};
KJUR.jws.JWS.jwsalg2sigalg = { HS256: "HmacSHA256", HS384: "HmacSHA384", HS512: "HmacSHA512", RS256: "SHA256withRSA", RS384: "SHA384withRSA", RS512: "SHA512withRSA", ES256: "SHA256withECDSA", ES384: "SHA384withECDSA", ES512: "SHA512withECDSA", PS256: "SHA256withRSAandMGF1", PS384: "SHA384withRSAandMGF1", PS512: "SHA512withRSAandMGF1", none: "none" };
KJUR.jws.JWS.isSafeJSONString = function(c, b, d) {
var e2 = null;
try {
e2 = jsonParse(c);
if (typeof e2 != "object") {
return 0;
}
if (e2.constructor === Array) {
return 0;
}
if (b) {
b[d] = e2;
}
return 1;
} catch (a) {
return 0;
}
};
KJUR.jws.JWS.readSafeJSONString = function(b) {
var c = null;
try {
c = jsonParse(b);
if (typeof c != "object") {
return null;
}
if (c.constructor === Array) {
return null;
}
return c;
} catch (a) {
return null;
}
};
KJUR.jws.JWS.getEncodedSignatureValueFromJWS = function(b) {
var a = b.match(/^[^.]+\.[^.]+\.([^.]+)$/);
if (a == null) {
throw "JWS signature is not a form of 'Head.Payload.SigValue'.";
}
return a[1];
};
KJUR.jws.JWS.getJWKthumbprint = function(d) {
if (d.kty !== "RSA" && d.kty !== "EC" && d.kty !== "oct") {
throw "unsupported algorithm for JWK Thumprint";
}
var a = "{";
if (d.kty === "RSA") {
if (typeof d.n != "string" || typeof d.e != "string") {
throw "wrong n and e value for RSA key";
}
a += '"e":"' + d.e + '",';
a += '"kty":"' + d.kty + '",';
a += '"n":"' + d.n + '"}';
} else {
if (d.kty === "EC") {
if (typeof d.crv != "string" || typeof d.x != "string" || typeof d.y != "string") {
throw "wrong crv, x and y value for EC key";
}
a += '"crv":"' + d.crv + '",';
a += '"kty":"' + d.kty + '",';
a += '"x":"' + d.x + '",';
a += '"y":"' + d.y + '"}';
} else {
if (d.kty === "oct") {
if (typeof d.k != "string") {
throw "wrong k value for oct(symmetric) key";
}
a += '"kty":"' + d.kty + '",';
a += '"k":"' + d.k + '"}';
}
}
}
var b = rstrtohex(a);
var c = KJUR.crypto.Util.hashHex(b, "sha256");
var e2 = hextob64u(c);
return e2;
};
KJUR.jws.IntDate = {};
KJUR.jws.IntDate.get = function(c) {
var b = KJUR.jws.IntDate, d = b.getNow, a = b.getZulu;
if (c == "now") {
return d();
} else {
if (c == "now + 1hour") {
return d() + 60 * 60;
} else {
if (c == "now + 1day") {
return d() + 60 * 60 * 24;
} else {
if (c == "now + 1month") {
return d() + 60 * 60 * 24 * 30;
} else {
if (c == "now + 1year") {
return d() + 60 * 60 * 24 * 365;
} else {
if (c.match(/Z$/)) {
return a(c);
} else {
if (c.match(/^[0-9]+$/)) {
return parseInt(c);
}
}
}
}
}
}
}
throw "unsupported format: " + c;
};
KJUR.jws.IntDate.getZulu = function(a) {
return zulutosec(a);
};
KJUR.jws.IntDate.getNow = function() {
var a = ~~(/* @__PURE__ */ new Date() / 1e3);
return a;
};
KJUR.jws.IntDate.intDate2UTCString = function(a) {
var b = new Date(a * 1e3);
return b.toUTCString();
};
KJUR.jws.IntDate.intDate2Zulu = function(e2) {
var i = new Date(e2 * 1e3), h = ("0000" + i.getUTCFullYear()).slice(-4), g = ("00" + (i.getUTCMonth() + 1)).slice(-2), b = ("00" + i.getUTCDate()).slice(-2), a = ("00" + i.getUTCHours()).slice(-2), c = ("00" + i.getUTCMinutes()).slice(-2), f = ("00" + i.getUTCSeconds()).slice(-2);
return h + g + b + a + c + f + "Z";
};
if (typeof KJUR == "undefined" || !KJUR) {
KJUR = {};
}
if (typeof KJUR.jws == "undefined" || !KJUR.jws) {
KJUR.jws = {};
}
KJUR.jws.JWSJS = function() {
var c = KJUR, b = c.jws, a = b.JWS, d = a.readSafeJSONString;
this.aHeader = [];
this.sPayload = "";
this.aSignature = [];
this.init = function() {
this.aHeader = [];
this.sPayload = void 0;
this.aSignature = [];
};
this.initWithJWS = function(f) {
this.init();
var e2 = f.split(".");
if (e2.length != 3) {
throw "malformed input JWS";
}
this.aHeader.push(e2[0]);
this.sPayload = e2[1];
this.aSignature.push(e2[2]);
};
this.addSignature = function(e2, h, m, k) {
if (this.sPayload === void 0 || this.sPayload === null) {
throw "there's no JSON-JS signature to add.";
}
var l = this.aHeader.length;
if (this.aHeader.length != this.aSignature.length) {
throw "aHeader.length != aSignature.length";
}
try {
var f = KJUR.jws.JWS.sign(e2, h, this.sPayload, m, k);
var j = f.split(".");
var n2 = j[0];
var g = j[2];
this.aHeader.push(j[0]);
this.aSignature.push(j[2]);
} catch (i) {
if (this.aHeader.length > l) {
this.aHeader.pop();
}
if (this.aSignature.length > l) {
this.aSignature.pop();
}
throw "addSignature failed: " + i;
}
};
this.verifyAll = function(h) {
if (this.aHeader.length !== h.length || this.aSignature.length !== h.length) {
return false;
}
for (var g = 0; g < h.length; g++) {
var f = h[g];
if (f.length !== 2) {
return false;
}
var e2 = this.verifyNth(g, f[0], f[1]);
if (e2 === false) {
return false;
}
}
return true;
};
this.verifyNth = function(f, j, g) {
if (this.aHeader.length <= f || this.aSignature.length <= f) {
return false;
}
var h = this.aHeader[f];
var k = this.aSignature[f];
var l = h + "." + this.sPayload + "." + k;
var e2 = false;
try {
e2 = a.verify(l, j, g);
} catch (i) {
return false;
}
return e2;
};
this.readJWSJS = function(g) {
if (typeof g === "string") {
var f = d(g);
if (f == null) {
throw "argument is not safe JSON object string";
}
this.aHeader = f.headers;
this.sPayload = f.payload;
this.aSignature = f.signatures;
} else {
try {
if (g.headers.length > 0) {
this.aHeader = g.headers;
} else {
throw "malformed header";
}
if (typeof g.payload === "string") {
this.sPayload = g.payload;
} else {
throw "malformed signatures";
}
if (g.signatures.length > 0) {
this.aSignature = g.signatures;
} else {
throw "malformed signatures";
}
} catch (e2) {
throw "malformed JWS-JS JSON object: " + e2;
}
}
};
this.getJSON = function() {
return { headers: this.aHeader, payload: this.sPayload, signatures: this.aSignature };
};
this.isEmpty = function() {
if (this.aHeader.length == 0) {
return 1;
}
return 0;
};
};
exports.SecureRandom = SecureRandom;
exports.rng_seed_time = rng_seed_time;
exports.BigInteger = BigInteger;
exports.RSAKey = RSAKey;
exports.ECDSA = KJUR.crypto.ECDSA;
exports.DSA = KJUR.crypto.DSA;
exports.Signature = KJUR.crypto.Signature;
exports.MessageDigest = KJUR.crypto.MessageDigest;
exports.Mac = KJUR.crypto.Mac;
exports.KEYUTIL = KEYUTIL;
exports.ASN1HEX = ASN1HEX;
exports.X509 = X509;
exports.X509CRL = X509CRL;
exports.CryptoJS = CryptoJS;
exports.b64tohex = b64tohex;
exports.b64toBA = b64toBA;
exports.ECFieldElementFp = ECFieldElementFp;
exports.ECPointFp = ECPointFp;
exports.ECCurveFp = ECCurveFp;
exports.stoBA = stoBA;
exports.BAtos = BAtos;
exports.BAtohex = BAtohex;
exports.stohex = stohex;
exports.stob64 = stob64;
exports.stob64u = stob64u;
exports.b64utos = b64utos;
exports.b64tob64u = b64tob64u;
exports.b64utob64 = b64utob64;
exports.hex2b64 = hex2b64;
exports.hextob64u = hextob64u;
exports.b64utohex = b64utohex;
exports.utf8tob64u = utf8tob64u;
exports.b64utoutf8 = b64utoutf8;
exports.utf8tob64 = utf8tob64;
exports.b64toutf8 = b64toutf8;
exports.utf8tohex = utf8tohex;
exports.hextoutf8 = hextoutf8;
exports.hextorstr = hextorstr;
exports.rstrtohex = rstrtohex;
exports.hextob64 = hextob64;
exports.hextob64nl = hextob64nl;
exports.b64nltohex = b64nltohex;
exports.hextopem = hextopem;
exports.pemtohex = pemtohex;
exports.hextoArrayBuffer = hextoArrayBuffer;
exports.ArrayBuffertohex = ArrayBuffertohex;
exports.zulutomsec = zulutomsec;
exports.msectozulu = msectozulu;
exports.zulutosec = zulutosec;
exports.zulutodate = zulutodate;
exports.datetozulu = datetozulu;
exports.uricmptohex = uricmptohex;
exports.hextouricmp = hextouricmp;
exports.ipv6tohex = ipv6tohex;
exports.hextoipv6 = hextoipv6;
exports.hextoip = hextoip;
exports.iptohex = iptohex;
exports.ucs2hextoutf8 = ucs2hextoutf8;
exports.encodeURIComponentAll = encodeURIComponentAll;
exports.newline_toUnix = newline_toUnix;
exports.newline_toDos = newline_toDos;
exports.hextoposhex = hextoposhex;
exports.intarystrtohex = intarystrtohex;
exports.strdiffidx = strdiffidx;
exports.oidtohex = oidtohex;
exports.hextooid = hextooid;
exports.strpad = strpad;
exports.bitstrtoint = bitstrtoint;
exports.inttobitstr = inttobitstr;
exports.bitstrtobinstr = bitstrtobinstr;
exports.binstrtobitstr = binstrtobitstr;
exports.isBase64URLDot = isBase64URLDot;
exports.namearraytobinstr = namearraytobinstr;
exports.extendClass = extendClass;
exports.foldnl = foldnl;
exports.b64topem = b64topem;
exports.pemtob64 = pemtob64;
exports.timeogen = timetogen;
exports.aryval = aryval;
exports.inttohex = inttohex;
exports.twoscompl = twoscompl;
exports.KJUR = KJUR;
exports.crypto = KJUR.crypto;
exports.asn1 = KJUR.asn1;
exports.jws = KJUR.jws;
exports.lang = KJUR.lang;
exports.VERSION = VERSION3;
exports.VERSION_FULL = VERSION_FULL;
}
});
// ../../node_modules/.pnpm/bowser@2.11.0/node_modules/bowser/es5.js
var require_es5 = __commonJS({
"../../node_modules/.pnpm/bowser@2.11.0/node_modules/bowser/es5.js"(exports, module) {
init_process();
!(function(e2, t2) {
"object" == typeof exports && "object" == typeof module ? module.exports = t2() : "function" == typeof define && define.amd ? define([], t2) : "object" == typeof exports ? exports.bowser = t2() : e2.bowser = t2();
})(exports, (function() {
return (function(e2) {
var t2 = {};
function r2(n2) {
if (t2[n2]) return t2[n2].exports;
var i = t2[n2] = { i: n2, l: false, exports: {} };
return e2[n2].call(i.exports, i, i.exports, r2), i.l = true, i.exports;
}
return r2.m = e2, r2.c = t2, r2.d = function(e3, t3, n2) {
r2.o(e3, t3) || Object.defineProperty(e3, t3, { enumerable: true, get: n2 });
}, r2.r = function(e3) {
"undefined" != typeof Symbol && Symbol.toStringTag && Object.defineProperty(e3, Symbol.toStringTag, { value: "Module" }), Object.defineProperty(e3, "__esModule", { value: true });
}, r2.t = function(e3, t3) {
if (1 & t3 && (e3 = r2(e3)), 8 & t3) return e3;
if (4 & t3 && "object" == typeof e3 && e3 && e3.__esModule) return e3;
var n2 = /* @__PURE__ */ Object.create(null);
if (r2.r(n2), Object.defineProperty(n2, "default", { enumerable: true, value: e3 }), 2 & t3 && "string" != typeof e3) for (var i in e3) r2.d(n2, i, function(t4) {
return e3[t4];
}.bind(null, i));
return n2;
}, r2.n = function(e3) {
var t3 = e3 && e3.__esModule ? function() {
return e3.default;
} : function() {
return e3;
};
return r2.d(t3, "a", t3), t3;
}, r2.o = function(e3, t3) {
return Object.prototype.hasOwnProperty.call(e3, t3);
}, r2.p = "", r2(r2.s = 90);
})({ 17: function(e2, t2, r2) {
"use strict";
t2.__esModule = true, t2.default = void 0;
var n2 = r2(18), i = (function() {
function e3() {
}
return e3.getFirstMatch = function(e4, t3) {
var r3 = t3.match(e4);
return r3 && r3.length > 0 && r3[1] || "";
}, e3.getSecondMatch = function(e4, t3) {
var r3 = t3.match(e4);
return r3 && r3.length > 1 && r3[2] || "";
}, e3.matchAndReturnConst = function(e4, t3, r3) {
if (e4.test(t3)) return r3;
}, e3.getWindowsVersionName = function(e4) {
switch (e4) {
case "NT":
return "NT";
case "XP":
return "XP";
case "NT 5.0":
return "2000";
case "NT 5.1":
return "XP";
case "NT 5.2":
return "2003";
case "NT 6.0":
return "Vista";
case "NT 6.1":
return "7";
case "NT 6.2":
return "8";
case "NT 6.3":
return "8.1";
case "NT 10.0":
return "10";
default:
return;
}
}, e3.getMacOSVersionName = function(e4) {
var t3 = e4.split(".").splice(0, 2).map((function(e5) {
return parseInt(e5, 10) || 0;
}));
if (t3.push(0), 10 === t3[0]) switch (t3[1]) {
case 5:
return "Leopard";
case 6:
return "Snow Leopard";
case 7:
return "Lion";
case 8:
return "Mountain Lion";
case 9:
return "Mavericks";
case 10:
return "Yosemite";
case 11:
return "El Capitan";
case 12:
return "Sierra";
case 13:
return "High Sierra";
case 14:
return "Mojave";
case 15:
return "Catalina";
default:
return;
}
}, e3.getAndroidVersionName = function(e4) {
var t3 = e4.split(".").splice(0, 2).map((function(e5) {
return parseInt(e5, 10) || 0;
}));
if (t3.push(0), !(1 === t3[0] && t3[1] < 5)) return 1 === t3[0] && t3[1] < 6 ? "Cupcake" : 1 === t3[0] && t3[1] >= 6 ? "Donut" : 2 === t3[0] && t3[1] < 2 ? "Eclair" : 2 === t3[0] && 2 === t3[1] ? "Froyo" : 2 === t3[0] && t3[1] > 2 ? "Gingerbread" : 3 === t3[0] ? "Honeycomb" : 4 === t3[0] && t3[1] < 1 ? "Ice Cream Sandwich" : 4 === t3[0] && t3[1] < 4 ? "Jelly Bean" : 4 === t3[0] && t3[1] >= 4 ? "KitKat" : 5 === t3[0] ? "Lollipop" : 6 === t3[0] ? "Marshmallow" : 7 === t3[0] ? "Nougat" : 8 === t3[0] ? "Oreo" : 9 === t3[0] ? "Pie" : void 0;
}, e3.getVersionPrecision = function(e4) {
return e4.split(".").length;
}, e3.compareVersions = function(t3, r3, n3) {
void 0 === n3 && (n3 = false);
var i2 = e3.getVersionPrecision(t3), s = e3.getVersionPrecision(r3), a = Math.max(i2, s), o2 = 0, u = e3.map([t3, r3], (function(t4) {
var r4 = a - e3.getVersionPrecision(t4), n4 = t4 + new Array(r4 + 1).join(".0");
return e3.map(n4.split("."), (function(e4) {
return new Array(20 - e4.length).join("0") + e4;
})).reverse();
}));
for (n3 && (o2 = a - Math.min(i2, s)), a -= 1; a >= o2; ) {
if (u[0][a] > u[1][a]) return 1;
if (u[0][a] === u[1][a]) {
if (a === o2) return 0;
a -= 1;
} else if (u[0][a] < u[1][a]) return -1;
}
}, e3.map = function(e4, t3) {
var r3, n3 = [];
if (Array.prototype.map) return Array.prototype.map.call(e4, t3);
for (r3 = 0; r3 < e4.length; r3 += 1) n3.push(t3(e4[r3]));
return n3;
}, e3.find = function(e4, t3) {
var r3, n3;
if (Array.prototype.find) return Array.prototype.find.call(e4, t3);
for (r3 = 0, n3 = e4.length; r3 < n3; r3 += 1) {
var i2 = e4[r3];
if (t3(i2, r3)) return i2;
}
}, e3.assign = function(e4) {
for (var t3, r3, n3 = e4, i2 = arguments.length, s = new Array(i2 > 1 ? i2 - 1 : 0), a = 1; a < i2; a++) s[a - 1] = arguments[a];
if (Object.assign) return Object.assign.apply(Object, [e4].concat(s));
var o2 = function() {
var e5 = s[t3];
"object" == typeof e5 && null !== e5 && Object.keys(e5).forEach((function(t4) {
n3[t4] = e5[t4];
}));
};
for (t3 = 0, r3 = s.length; t3 < r3; t3 += 1) o2();
return e4;
}, e3.getBrowserAlias = function(e4) {
return n2.BROWSER_ALIASES_MAP[e4];
}, e3.getBrowserTypeByAlias = function(e4) {
return n2.BROWSER_MAP[e4] || "";
}, e3;
})();
t2.default = i, e2.exports = t2.default;
}, 18: function(e2, t2, r2) {
"use strict";
t2.__esModule = true, t2.ENGINE_MAP = t2.OS_MAP = t2.PLATFORMS_MAP = t2.BROWSER_MAP = t2.BROWSER_ALIASES_MAP = void 0;
t2.BROWSER_ALIASES_MAP = { "Amazon Silk": "amazon_silk", "Android Browser": "android", Bada: "bada", BlackBerry: "blackberry", Chrome: "chrome", Chromium: "chromium", Electron: "electron", Epiphany: "epiphany", Firefox: "firefox", Focus: "focus", Generic: "generic", "Google Search": "google_search", Googlebot: "googlebot", "Internet Explorer": "ie", "K-Meleon": "k_meleon", Maxthon: "maxthon", "Microsoft Edge": "edge", "MZ Browser": "mz", "NAVER Whale Browser": "naver", Opera: "opera", "Opera Coast": "opera_coast", PhantomJS: "phantomjs", Puffin: "puffin", QupZilla: "qupzilla", QQ: "qq", QQLite: "qqlite", Safari: "safari", Sailfish: "sailfish", "Samsung Internet for Android": "samsung_internet", SeaMonkey: "seamonkey", Sleipnir: "sleipnir", Swing: "swing", Tizen: "tizen", "UC Browser": "uc", Vivaldi: "vivaldi", "WebOS Browser": "webos", WeChat: "wechat", "Yandex Browser": "yandex", Roku: "roku" };
t2.BROWSER_MAP = { amazon_silk: "Amazon Silk", android: "Android Browser", bada: "Bada", blackberry: "BlackBerry", chrome: "Chrome", chromium: "Chromium", electron: "Electron", epiphany: "Epiphany", firefox: "Firefox", focus: "Focus", generic: "Generic", googlebot: "Googlebot", google_search: "Google Search", ie: "Internet Explorer", k_meleon: "K-Meleon", maxthon: "Maxthon", edge: "Microsoft Edge", mz: "MZ Browser", naver: "NAVER Whale Browser", opera: "Opera", opera_coast: "Opera Coast", phantomjs: "PhantomJS", puffin: "Puffin", qupzilla: "QupZilla", qq: "QQ Browser", qqlite: "QQ Browser Lite", safari: "Safari", sailfish: "Sailfish", samsung_internet: "Samsung Internet for Android", seamonkey: "SeaMonkey", sleipnir: "Sleipnir", swing: "Swing", tizen: "Tizen", uc: "UC Browser", vivaldi: "Vivaldi", webos: "WebOS Browser", wechat: "WeChat", yandex: "Yandex Browser" };
t2.PLATFORMS_MAP = { tablet: "tablet", mobile: "mobile", desktop: "desktop", tv: "tv" };
t2.OS_MAP = { WindowsPhone: "Windows Phone", Windows: "Windows", MacOS: "macOS", iOS: "iOS", Android: "Android", WebOS: "WebOS", BlackBerry: "BlackBerry", Bada: "Bada", Tizen: "Tizen", Linux: "Linux", ChromeOS: "Chrome OS", PlayStation4: "PlayStation 4", Roku: "Roku" };
t2.ENGINE_MAP = { EdgeHTML: "EdgeHTML", Blink: "Blink", Trident: "Trident", Presto: "Presto", Gecko: "Gecko", WebKit: "WebKit" };
}, 90: function(e2, t2, r2) {
"use strict";
t2.__esModule = true, t2.default = void 0;
var n2, i = (n2 = r2(91)) && n2.__esModule ? n2 : { default: n2 }, s = r2(18);
function a(e3, t3) {
for (var r3 = 0; r3 < t3.length; r3++) {
var n3 = t3[r3];
n3.enumerable = n3.enumerable || false, n3.configurable = true, "value" in n3 && (n3.writable = true), Object.defineProperty(e3, n3.key, n3);
}
}
var o2 = (function() {
function e3() {
}
var t3, r3, n3;
return e3.getParser = function(e4, t4) {
if (void 0 === t4 && (t4 = false), "string" != typeof e4) throw new Error("UserAgent should be a string");
return new i.default(e4, t4);
}, e3.parse = function(e4) {
return new i.default(e4).getResult();
}, t3 = e3, n3 = [{ key: "BROWSER_MAP", get: function() {
return s.BROWSER_MAP;
} }, { key: "ENGINE_MAP", get: function() {
return s.ENGINE_MAP;
} }, { key: "OS_MAP", get: function() {
return s.OS_MAP;
} }, { key: "PLATFORMS_MAP", get: function() {
return s.PLATFORMS_MAP;
} }], (r3 = null) && a(t3.prototype, r3), n3 && a(t3, n3), e3;
})();
t2.default = o2, e2.exports = t2.default;
}, 91: function(e2, t2, r2) {
"use strict";
t2.__esModule = true, t2.default = void 0;
var n2 = u(r2(92)), i = u(r2(93)), s = u(r2(94)), a = u(r2(95)), o2 = u(r2(17));
function u(e3) {
return e3 && e3.__esModule ? e3 : { default: e3 };
}
var d = (function() {
function e3(e4, t4) {
if (void 0 === t4 && (t4 = false), null == e4 || "" === e4) throw new Error("UserAgent parameter can't be empty");
this._ua = e4, this.parsedResult = {}, true !== t4 && this.parse();
}
var t3 = e3.prototype;
return t3.getUA = function() {
return this._ua;
}, t3.test = function(e4) {
return e4.test(this._ua);
}, t3.parseBrowser = function() {
var e4 = this;
this.parsedResult.browser = {};
var t4 = o2.default.find(n2.default, (function(t5) {
if ("function" == typeof t5.test) return t5.test(e4);
if (t5.test instanceof Array) return t5.test.some((function(t6) {
return e4.test(t6);
}));
throw new Error("Browser's test function is not valid");
}));
return t4 && (this.parsedResult.browser = t4.describe(this.getUA())), this.parsedResult.browser;
}, t3.getBrowser = function() {
return this.parsedResult.browser ? this.parsedResult.browser : this.parseBrowser();
}, t3.getBrowserName = function(e4) {
return e4 ? String(this.getBrowser().name).toLowerCase() || "" : this.getBrowser().name || "";
}, t3.getBrowserVersion = function() {
return this.getBrowser().version;
}, t3.getOS = function() {
return this.parsedResult.os ? this.parsedResult.os : this.parseOS();
}, t3.parseOS = function() {
var e4 = this;
this.parsedResult.os = {};
var t4 = o2.default.find(i.default, (function(t5) {
if ("function" == typeof t5.test) return t5.test(e4);
if (t5.test instanceof Array) return t5.test.some((function(t6) {
return e4.test(t6);
}));
throw new Error("Browser's test function is not valid");
}));
return t4 && (this.parsedResult.os = t4.describe(this.getUA())), this.parsedResult.os;
}, t3.getOSName = function(e4) {
var t4 = this.getOS().name;
return e4 ? String(t4).toLowerCase() || "" : t4 || "";
}, t3.getOSVersion = function() {
return this.getOS().version;
}, t3.getPlatform = function() {
return this.parsedResult.platform ? this.parsedResult.platform : this.parsePlatform();
}, t3.getPlatformType = function(e4) {
void 0 === e4 && (e4 = false);
var t4 = this.getPlatform().type;
return e4 ? String(t4).toLowerCase() || "" : t4 || "";
}, t3.parsePlatform = function() {
var e4 = this;
this.parsedResult.platform = {};
var t4 = o2.default.find(s.default, (function(t5) {
if ("function" == typeof t5.test) return t5.test(e4);
if (t5.test instanceof Array) return t5.test.some((function(t6) {
return e4.test(t6);
}));
throw new Error("Browser's test function is not valid");
}));
return t4 && (this.parsedResult.platform = t4.describe(this.getUA())), this.parsedResult.platform;
}, t3.getEngine = function() {
return this.parsedResult.engine ? this.parsedResult.engine : this.parseEngine();
}, t3.getEngineName = function(e4) {
return e4 ? String(this.getEngine().name).toLowerCase() || "" : this.getEngine().name || "";
}, t3.parseEngine = function() {
var e4 = this;
this.parsedResult.engine = {};
var t4 = o2.default.find(a.default, (function(t5) {
if ("function" == typeof t5.test) return t5.test(e4);
if (t5.test instanceof Array) return t5.test.some((function(t6) {
return e4.test(t6);
}));
throw new Error("Browser's test function is not valid");
}));
return t4 && (this.parsedResult.engine = t4.describe(this.getUA())), this.parsedResult.engine;
}, t3.parse = function() {
return this.parseBrowser(), this.parseOS(), this.parsePlatform(), this.parseEngine(), this;
}, t3.getResult = function() {
return o2.default.assign({}, this.parsedResult);
}, t3.satisfies = function(e4) {
var t4 = this, r3 = {}, n3 = 0, i2 = {}, s2 = 0;
if (Object.keys(e4).forEach((function(t5) {
var a3 = e4[t5];
"string" == typeof a3 ? (i2[t5] = a3, s2 += 1) : "object" == typeof a3 && (r3[t5] = a3, n3 += 1);
})), n3 > 0) {
var a2 = Object.keys(r3), u2 = o2.default.find(a2, (function(e5) {
return t4.isOS(e5);
}));
if (u2) {
var d2 = this.satisfies(r3[u2]);
if (void 0 !== d2) return d2;
}
var c = o2.default.find(a2, (function(e5) {
return t4.isPlatform(e5);
}));
if (c) {
var f = this.satisfies(r3[c]);
if (void 0 !== f) return f;
}
}
if (s2 > 0) {
var l = Object.keys(i2), h = o2.default.find(l, (function(e5) {
return t4.isBrowser(e5, true);
}));
if (void 0 !== h) return this.compareVersion(i2[h]);
}
}, t3.isBrowser = function(e4, t4) {
void 0 === t4 && (t4 = false);
var r3 = this.getBrowserName().toLowerCase(), n3 = e4.toLowerCase(), i2 = o2.default.getBrowserTypeByAlias(n3);
return t4 && i2 && (n3 = i2.toLowerCase()), n3 === r3;
}, t3.compareVersion = function(e4) {
var t4 = [0], r3 = e4, n3 = false, i2 = this.getBrowserVersion();
if ("string" == typeof i2) return ">" === e4[0] || "<" === e4[0] ? (r3 = e4.substr(1), "=" === e4[1] ? (n3 = true, r3 = e4.substr(2)) : t4 = [], ">" === e4[0] ? t4.push(1) : t4.push(-1)) : "=" === e4[0] ? r3 = e4.substr(1) : "~" === e4[0] && (n3 = true, r3 = e4.substr(1)), t4.indexOf(o2.default.compareVersions(i2, r3, n3)) > -1;
}, t3.isOS = function(e4) {
return this.getOSName(true) === String(e4).toLowerCase();
}, t3.isPlatform = function(e4) {
return this.getPlatformType(true) === String(e4).toLowerCase();
}, t3.isEngine = function(e4) {
return this.getEngineName(true) === String(e4).toLowerCase();
}, t3.is = function(e4, t4) {
return void 0 === t4 && (t4 = false), this.isBrowser(e4, t4) || this.isOS(e4) || this.isPlatform(e4);
}, t3.some = function(e4) {
var t4 = this;
return void 0 === e4 && (e4 = []), e4.some((function(e5) {
return t4.is(e5);
}));
}, e3;
})();
t2.default = d, e2.exports = t2.default;
}, 92: function(e2, t2, r2) {
"use strict";
t2.__esModule = true, t2.default = void 0;
var n2, i = (n2 = r2(17)) && n2.__esModule ? n2 : { default: n2 };
var s = /version\/(\d+(\.?_?\d+)+)/i, a = [{ test: [/googlebot/i], describe: function(e3) {
var t3 = { name: "Googlebot" }, r3 = i.default.getFirstMatch(/googlebot\/(\d+(\.\d+))/i, e3) || i.default.getFirstMatch(s, e3);
return r3 && (t3.version = r3), t3;
} }, { test: [/opera/i], describe: function(e3) {
var t3 = { name: "Opera" }, r3 = i.default.getFirstMatch(s, e3) || i.default.getFirstMatch(/(?:opera)[\s/](\d+(\.?_?\d+)+)/i, e3);
return r3 && (t3.version = r3), t3;
} }, { test: [/opr\/|opios/i], describe: function(e3) {
var t3 = { name: "Opera" }, r3 = i.default.getFirstMatch(/(?:opr|opios)[\s/](\S+)/i, e3) || i.default.getFirstMatch(s, e3);
return r3 && (t3.version = r3), t3;
} }, { test: [/SamsungBrowser/i], describe: function(e3) {
var t3 = { name: "Samsung Internet for Android" }, r3 = i.default.getFirstMatch(s, e3) || i.default.getFirstMatch(/(?:SamsungBrowser)[\s/](\d+(\.?_?\d+)+)/i, e3);
return r3 && (t3.version = r3), t3;
} }, { test: [/Whale/i], describe: function(e3) {
var t3 = { name: "NAVER Whale Browser" }, r3 = i.default.getFirstMatch(s, e3) || i.default.getFirstMatch(/(?:whale)[\s/](\d+(?:\.\d+)+)/i, e3);
return r3 && (t3.version = r3), t3;
} }, { test: [/MZBrowser/i], describe: function(e3) {
var t3 = { name: "MZ Browser" }, r3 = i.default.getFirstMatch(/(?:MZBrowser)[\s/](\d+(?:\.\d+)+)/i, e3) || i.default.getFirstMatch(s, e3);
return r3 && (t3.version = r3), t3;
} }, { test: [/focus/i], describe: function(e3) {
var t3 = { name: "Focus" }, r3 = i.default.getFirstMatch(/(?:focus)[\s/](\d+(?:\.\d+)+)/i, e3) || i.default.getFirstMatch(s, e3);
return r3 && (t3.version = r3), t3;
} }, { test: [/swing/i], describe: function(e3) {
var t3 = { name: "Swing" }, r3 = i.default.getFirstMatch(/(?:swing)[\s/](\d+(?:\.\d+)+)/i, e3) || i.default.getFirstMatch(s, e3);
return r3 && (t3.version = r3), t3;
} }, { test: [/coast/i], describe: function(e3) {
var t3 = { name: "Opera Coast" }, r3 = i.default.getFirstMatch(s, e3) || i.default.getFirstMatch(/(?:coast)[\s/](\d+(\.?_?\d+)+)/i, e3);
return r3 && (t3.version = r3), t3;
} }, { test: [/opt\/\d+(?:.?_?\d+)+/i], describe: function(e3) {
var t3 = { name: "Opera Touch" }, r3 = i.default.getFirstMatch(/(?:opt)[\s/](\d+(\.?_?\d+)+)/i, e3) || i.default.getFirstMatch(s, e3);
return r3 && (t3.version = r3), t3;
} }, { test: [/yabrowser/i], describe: function(e3) {
var t3 = { name: "Yandex Browser" }, r3 = i.default.getFirstMatch(/(?:yabrowser)[\s/](\d+(\.?_?\d+)+)/i, e3) || i.default.getFirstMatch(s, e3);
return r3 && (t3.version = r3), t3;
} }, { test: [/ucbrowser/i], describe: function(e3) {
var t3 = { name: "UC Browser" }, r3 = i.default.getFirstMatch(s, e3) || i.default.getFirstMatch(/(?:ucbrowser)[\s/](\d+(\.?_?\d+)+)/i, e3);
return r3 && (t3.version = r3), t3;
} }, { test: [/Maxthon|mxios/i], describe: function(e3) {
var t3 = { name: "Maxthon" }, r3 = i.default.getFirstMatch(s, e3) || i.default.getFirstMatch(/(?:Maxthon|mxios)[\s/](\d+(\.?_?\d+)+)/i, e3);
return r3 && (t3.version = r3), t3;
} }, { test: [/epiphany/i], describe: function(e3) {
var t3 = { name: "Epiphany" }, r3 = i.default.getFirstMatch(s, e3) || i.default.getFirstMatch(/(?:epiphany)[\s/](\d+(\.?_?\d+)+)/i, e3);
return r3 && (t3.version = r3), t3;
} }, { test: [/puffin/i], describe: function(e3) {
var t3 = { name: "Puffin" }, r3 = i.default.getFirstMatch(s, e3) || i.default.getFirstMatch(/(?:puffin)[\s/](\d+(\.?_?\d+)+)/i, e3);
return r3 && (t3.version = r3), t3;
} }, { test: [/sleipnir/i], describe: function(e3) {
var t3 = { name: "Sleipnir" }, r3 = i.default.getFirstMatch(s, e3) || i.default.getFirstMatch(/(?:sleipnir)[\s/](\d+(\.?_?\d+)+)/i, e3);
return r3 && (t3.version = r3), t3;
} }, { test: [/k-meleon/i], describe: function(e3) {
var t3 = { name: "K-Meleon" }, r3 = i.default.getFirstMatch(s, e3) || i.default.getFirstMatch(/(?:k-meleon)[\s/](\d+(\.?_?\d+)+)/i, e3);
return r3 && (t3.version = r3), t3;
} }, { test: [/micromessenger/i], describe: function(e3) {
var t3 = { name: "WeChat" }, r3 = i.default.getFirstMatch(/(?:micromessenger)[\s/](\d+(\.?_?\d+)+)/i, e3) || i.default.getFirstMatch(s, e3);
return r3 && (t3.version = r3), t3;
} }, { test: [/qqbrowser/i], describe: function(e3) {
var t3 = { name: /qqbrowserlite/i.test(e3) ? "QQ Browser Lite" : "QQ Browser" }, r3 = i.default.getFirstMatch(/(?:qqbrowserlite|qqbrowser)[/](\d+(\.?_?\d+)+)/i, e3) || i.default.getFirstMatch(s, e3);
return r3 && (t3.version = r3), t3;
} }, { test: [/msie|trident/i], describe: function(e3) {
var t3 = { name: "Internet Explorer" }, r3 = i.default.getFirstMatch(/(?:msie |rv:)(\d+(\.?_?\d+)+)/i, e3);
return r3 && (t3.version = r3), t3;
} }, { test: [/\sedg\//i], describe: function(e3) {
var t3 = { name: "Microsoft Edge" }, r3 = i.default.getFirstMatch(/\sedg\/(\d+(\.?_?\d+)+)/i, e3);
return r3 && (t3.version = r3), t3;
} }, { test: [/edg([ea]|ios)/i], describe: function(e3) {
var t3 = { name: "Microsoft Edge" }, r3 = i.default.getSecondMatch(/edg([ea]|ios)\/(\d+(\.?_?\d+)+)/i, e3);
return r3 && (t3.version = r3), t3;
} }, { test: [/vivaldi/i], describe: function(e3) {
var t3 = { name: "Vivaldi" }, r3 = i.default.getFirstMatch(/vivaldi\/(\d+(\.?_?\d+)+)/i, e3);
return r3 && (t3.version = r3), t3;
} }, { test: [/seamonkey/i], describe: function(e3) {
var t3 = { name: "SeaMonkey" }, r3 = i.default.getFirstMatch(/seamonkey\/(\d+(\.?_?\d+)+)/i, e3);
return r3 && (t3.version = r3), t3;
} }, { test: [/sailfish/i], describe: function(e3) {
var t3 = { name: "Sailfish" }, r3 = i.default.getFirstMatch(/sailfish\s?browser\/(\d+(\.\d+)?)/i, e3);
return r3 && (t3.version = r3), t3;
} }, { test: [/silk/i], describe: function(e3) {
var t3 = { name: "Amazon Silk" }, r3 = i.default.getFirstMatch(/silk\/(\d+(\.?_?\d+)+)/i, e3);
return r3 && (t3.version = r3), t3;
} }, { test: [/phantom/i], describe: function(e3) {
var t3 = { name: "PhantomJS" }, r3 = i.default.getFirstMatch(/phantomjs\/(\d+(\.?_?\d+)+)/i, e3);
return r3 && (t3.version = r3), t3;
} }, { test: [/slimerjs/i], describe: function(e3) {
var t3 = { name: "SlimerJS" }, r3 = i.default.getFirstMatch(/slimerjs\/(\d+(\.?_?\d+)+)/i, e3);
return r3 && (t3.version = r3), t3;
} }, { test: [/blackberry|\bbb\d+/i, /rim\stablet/i], describe: function(e3) {
var t3 = { name: "BlackBerry" }, r3 = i.default.getFirstMatch(s, e3) || i.default.getFirstMatch(/blackberry[\d]+\/(\d+(\.?_?\d+)+)/i, e3);
return r3 && (t3.version = r3), t3;
} }, { test: [/(web|hpw)[o0]s/i], describe: function(e3) {
var t3 = { name: "WebOS Browser" }, r3 = i.default.getFirstMatch(s, e3) || i.default.getFirstMatch(/w(?:eb)?[o0]sbrowser\/(\d+(\.?_?\d+)+)/i, e3);
return r3 && (t3.version = r3), t3;
} }, { test: [/bada/i], describe: function(e3) {
var t3 = { name: "Bada" }, r3 = i.default.getFirstMatch(/dolfin\/(\d+(\.?_?\d+)+)/i, e3);
return r3 && (t3.version = r3), t3;
} }, { test: [/tizen/i], describe: function(e3) {
var t3 = { name: "Tizen" }, r3 = i.default.getFirstMatch(/(?:tizen\s?)?browser\/(\d+(\.?_?\d+)+)/i, e3) || i.default.getFirstMatch(s, e3);
return r3 && (t3.version = r3), t3;
} }, { test: [/qupzilla/i], describe: function(e3) {
var t3 = { name: "QupZilla" }, r3 = i.default.getFirstMatch(/(?:qupzilla)[\s/](\d+(\.?_?\d+)+)/i, e3) || i.default.getFirstMatch(s, e3);
return r3 && (t3.version = r3), t3;
} }, { test: [/firefox|iceweasel|fxios/i], describe: function(e3) {
var t3 = { name: "Firefox" }, r3 = i.default.getFirstMatch(/(?:firefox|iceweasel|fxios)[\s/](\d+(\.?_?\d+)+)/i, e3);
return r3 && (t3.version = r3), t3;
} }, { test: [/electron/i], describe: function(e3) {
var t3 = { name: "Electron" }, r3 = i.default.getFirstMatch(/(?:electron)\/(\d+(\.?_?\d+)+)/i, e3);
return r3 && (t3.version = r3), t3;
} }, { test: [/MiuiBrowser/i], describe: function(e3) {
var t3 = { name: "Miui" }, r3 = i.default.getFirstMatch(/(?:MiuiBrowser)[\s/](\d+(\.?_?\d+)+)/i, e3);
return r3 && (t3.version = r3), t3;
} }, { test: [/chromium/i], describe: function(e3) {
var t3 = { name: "Chromium" }, r3 = i.default.getFirstMatch(/(?:chromium)[\s/](\d+(\.?_?\d+)+)/i, e3) || i.default.getFirstMatch(s, e3);
return r3 && (t3.version = r3), t3;
} }, { test: [/chrome|crios|crmo/i], describe: function(e3) {
var t3 = { name: "Chrome" }, r3 = i.default.getFirstMatch(/(?:chrome|crios|crmo)\/(\d+(\.?_?\d+)+)/i, e3);
return r3 && (t3.version = r3), t3;
} }, { test: [/GSA/i], describe: function(e3) {
var t3 = { name: "Google Search" }, r3 = i.default.getFirstMatch(/(?:GSA)\/(\d+(\.?_?\d+)+)/i, e3);
return r3 && (t3.version = r3), t3;
} }, { test: function(e3) {
var t3 = !e3.test(/like android/i), r3 = e3.test(/android/i);
return t3 && r3;
}, describe: function(e3) {
var t3 = { name: "Android Browser" }, r3 = i.default.getFirstMatch(s, e3);
return r3 && (t3.version = r3), t3;
} }, { test: [/playstation 4/i], describe: function(e3) {
var t3 = { name: "PlayStation 4" }, r3 = i.default.getFirstMatch(s, e3);
return r3 && (t3.version = r3), t3;
} }, { test: [/safari|applewebkit/i], describe: function(e3) {
var t3 = { name: "Safari" }, r3 = i.default.getFirstMatch(s, e3);
return r3 && (t3.version = r3), t3;
} }, { test: [/.*/i], describe: function(e3) {
var t3 = -1 !== e3.search("\\(") ? /^(.*)\/(.*)[ \t]\((.*)/ : /^(.*)\/(.*) /;
return { name: i.default.getFirstMatch(t3, e3), version: i.default.getSecondMatch(t3, e3) };
} }];
t2.default = a, e2.exports = t2.default;
}, 93: function(e2, t2, r2) {
"use strict";
t2.__esModule = true, t2.default = void 0;
var n2, i = (n2 = r2(17)) && n2.__esModule ? n2 : { default: n2 }, s = r2(18);
var a = [{ test: [/Roku\/DVP/], describe: function(e3) {
var t3 = i.default.getFirstMatch(/Roku\/DVP-(\d+\.\d+)/i, e3);
return { name: s.OS_MAP.Roku, version: t3 };
} }, { test: [/windows phone/i], describe: function(e3) {
var t3 = i.default.getFirstMatch(/windows phone (?:os)?\s?(\d+(\.\d+)*)/i, e3);
return { name: s.OS_MAP.WindowsPhone, version: t3 };
} }, { test: [/windows /i], describe: function(e3) {
var t3 = i.default.getFirstMatch(/Windows ((NT|XP)( \d\d?.\d)?)/i, e3), r3 = i.default.getWindowsVersionName(t3);
return { name: s.OS_MAP.Windows, version: t3, versionName: r3 };
} }, { test: [/Macintosh(.*?) FxiOS(.*?)\//], describe: function(e3) {
var t3 = { name: s.OS_MAP.iOS }, r3 = i.default.getSecondMatch(/(Version\/)(\d[\d.]+)/, e3);
return r3 && (t3.version = r3), t3;
} }, { test: [/macintosh/i], describe: function(e3) {
var t3 = i.default.getFirstMatch(/mac os x (\d+(\.?_?\d+)+)/i, e3).replace(/[_\s]/g, "."), r3 = i.default.getMacOSVersionName(t3), n3 = { name: s.OS_MAP.MacOS, version: t3 };
return r3 && (n3.versionName = r3), n3;
} }, { test: [/(ipod|iphone|ipad)/i], describe: function(e3) {
var t3 = i.default.getFirstMatch(/os (\d+([_\s]\d+)*) like mac os x/i, e3).replace(/[_\s]/g, ".");
return { name: s.OS_MAP.iOS, version: t3 };
} }, { test: function(e3) {
var t3 = !e3.test(/like android/i), r3 = e3.test(/android/i);
return t3 && r3;
}, describe: function(e3) {
var t3 = i.default.getFirstMatch(/android[\s/-](\d+(\.\d+)*)/i, e3), r3 = i.default.getAndroidVersionName(t3), n3 = { name: s.OS_MAP.Android, version: t3 };
return r3 && (n3.versionName = r3), n3;
} }, { test: [/(web|hpw)[o0]s/i], describe: function(e3) {
var t3 = i.default.getFirstMatch(/(?:web|hpw)[o0]s\/(\d+(\.\d+)*)/i, e3), r3 = { name: s.OS_MAP.WebOS };
return t3 && t3.length && (r3.version = t3), r3;
} }, { test: [/blackberry|\bbb\d+/i, /rim\stablet/i], describe: function(e3) {
var t3 = i.default.getFirstMatch(/rim\stablet\sos\s(\d+(\.\d+)*)/i, e3) || i.default.getFirstMatch(/blackberry\d+\/(\d+([_\s]\d+)*)/i, e3) || i.default.getFirstMatch(/\bbb(\d+)/i, e3);
return { name: s.OS_MAP.BlackBerry, version: t3 };
} }, { test: [/bada/i], describe: function(e3) {
var t3 = i.default.getFirstMatch(/bada\/(\d+(\.\d+)*)/i, e3);
return { name: s.OS_MAP.Bada, version: t3 };
} }, { test: [/tizen/i], describe: function(e3) {
var t3 = i.default.getFirstMatch(/tizen[/\s](\d+(\.\d+)*)/i, e3);
return { name: s.OS_MAP.Tizen, version: t3 };
} }, { test: [/linux/i], describe: function() {
return { name: s.OS_MAP.Linux };
} }, { test: [/CrOS/], describe: function() {
return { name: s.OS_MAP.ChromeOS };
} }, { test: [/PlayStation 4/], describe: function(e3) {
var t3 = i.default.getFirstMatch(/PlayStation 4[/\s](\d+(\.\d+)*)/i, e3);
return { name: s.OS_MAP.PlayStation4, version: t3 };
} }];
t2.default = a, e2.exports = t2.default;
}, 94: function(e2, t2, r2) {
"use strict";
t2.__esModule = true, t2.default = void 0;
var n2, i = (n2 = r2(17)) && n2.__esModule ? n2 : { default: n2 }, s = r2(18);
var a = [{ test: [/googlebot/i], describe: function() {
return { type: "bot", vendor: "Google" };
} }, { test: [/huawei/i], describe: function(e3) {
var t3 = i.default.getFirstMatch(/(can-l01)/i, e3) && "Nova", r3 = { type: s.PLATFORMS_MAP.mobile, vendor: "Huawei" };
return t3 && (r3.model = t3), r3;
} }, { test: [/nexus\s*(?:7|8|9|10).*/i], describe: function() {
return { type: s.PLATFORMS_MAP.tablet, vendor: "Nexus" };
} }, { test: [/ipad/i], describe: function() {
return { type: s.PLATFORMS_MAP.tablet, vendor: "Apple", model: "iPad" };
} }, { test: [/Macintosh(.*?) FxiOS(.*?)\//], describe: function() {
return { type: s.PLATFORMS_MAP.tablet, vendor: "Apple", model: "iPad" };
} }, { test: [/kftt build/i], describe: function() {
return { type: s.PLATFORMS_MAP.tablet, vendor: "Amazon", model: "Kindle Fire HD 7" };
} }, { test: [/silk/i], describe: function() {
return { type: s.PLATFORMS_MAP.tablet, vendor: "Amazon" };
} }, { test: [/tablet(?! pc)/i], describe: function() {
return { type: s.PLATFORMS_MAP.tablet };
} }, { test: function(e3) {
var t3 = e3.test(/ipod|iphone/i), r3 = e3.test(/like (ipod|iphone)/i);
return t3 && !r3;
}, describe: function(e3) {
var t3 = i.default.getFirstMatch(/(ipod|iphone)/i, e3);
return { type: s.PLATFORMS_MAP.mobile, vendor: "Apple", model: t3 };
} }, { test: [/nexus\s*[0-6].*/i, /galaxy nexus/i], describe: function() {
return { type: s.PLATFORMS_MAP.mobile, vendor: "Nexus" };
} }, { test: [/[^-]mobi/i], describe: function() {
return { type: s.PLATFORMS_MAP.mobile };
} }, { test: function(e3) {
return "blackberry" === e3.getBrowserName(true);
}, describe: function() {
return { type: s.PLATFORMS_MAP.mobile, vendor: "BlackBerry" };
} }, { test: function(e3) {
return "bada" === e3.getBrowserName(true);
}, describe: function() {
return { type: s.PLATFORMS_MAP.mobile };
} }, { test: function(e3) {
return "windows phone" === e3.getBrowserName();
}, describe: function() {
return { type: s.PLATFORMS_MAP.mobile, vendor: "Microsoft" };
} }, { test: function(e3) {
var t3 = Number(String(e3.getOSVersion()).split(".")[0]);
return "android" === e3.getOSName(true) && t3 >= 3;
}, describe: function() {
return { type: s.PLATFORMS_MAP.tablet };
} }, { test: function(e3) {
return "android" === e3.getOSName(true);
}, describe: function() {
return { type: s.PLATFORMS_MAP.mobile };
} }, { test: function(e3) {
return "macos" === e3.getOSName(true);
}, describe: function() {
return { type: s.PLATFORMS_MAP.desktop, vendor: "Apple" };
} }, { test: function(e3) {
return "windows" === e3.getOSName(true);
}, describe: function() {
return { type: s.PLATFORMS_MAP.desktop };
} }, { test: function(e3) {
return "linux" === e3.getOSName(true);
}, describe: function() {
return { type: s.PLATFORMS_MAP.desktop };
} }, { test: function(e3) {
return "playstation 4" === e3.getOSName(true);
}, describe: function() {
return { type: s.PLATFORMS_MAP.tv };
} }, { test: function(e3) {
return "roku" === e3.getOSName(true);
}, describe: function() {
return { type: s.PLATFORMS_MAP.tv };
} }];
t2.default = a, e2.exports = t2.default;
}, 95: function(e2, t2, r2) {
"use strict";
t2.__esModule = true, t2.default = void 0;
var n2, i = (n2 = r2(17)) && n2.__esModule ? n2 : { default: n2 }, s = r2(18);
var a = [{ test: function(e3) {
return "microsoft edge" === e3.getBrowserName(true);
}, describe: function(e3) {
if (/\sedg\//i.test(e3)) return { name: s.ENGINE_MAP.Blink };
var t3 = i.default.getFirstMatch(/edge\/(\d+(\.?_?\d+)+)/i, e3);
return { name: s.ENGINE_MAP.EdgeHTML, version: t3 };
} }, { test: [/trident/i], describe: function(e3) {
var t3 = { name: s.ENGINE_MAP.Trident }, r3 = i.default.getFirstMatch(/trident\/(\d+(\.?_?\d+)+)/i, e3);
return r3 && (t3.version = r3), t3;
} }, { test: function(e3) {
return e3.test(/presto/i);
}, describe: function(e3) {
var t3 = { name: s.ENGINE_MAP.Presto }, r3 = i.default.getFirstMatch(/presto\/(\d+(\.?_?\d+)+)/i, e3);
return r3 && (t3.version = r3), t3;
} }, { test: function(e3) {
var t3 = e3.test(/gecko/i), r3 = e3.test(/like gecko/i);
return t3 && !r3;
}, describe: function(e3) {
var t3 = { name: s.ENGINE_MAP.Gecko }, r3 = i.default.getFirstMatch(/gecko\/(\d+(\.?_?\d+)+)/i, e3);
return r3 && (t3.version = r3), t3;
} }, { test: [/(apple)?webkit\/537\.36/i], describe: function() {
return { name: s.ENGINE_MAP.Blink };
} }, { test: [/(apple)?webkit/i], describe: function(e3) {
var t3 = { name: s.ENGINE_MAP.WebKit }, r3 = i.default.getFirstMatch(/webkit\/(\d+(\.?_?\d+)+)/i, e3);
return r3 && (t3.version = r3), t3;
} }];
t2.default = a, e2.exports = t2.default;
} });
}));
}
});
// ../../node_modules/.pnpm/sdp-transform@2.15.0/node_modules/sdp-transform/lib/grammar.js
var require_grammar = __commonJS({
"../../node_modules/.pnpm/sdp-transform@2.15.0/node_modules/sdp-transform/lib/grammar.js"(exports, module) {
init_process();
var grammar = module.exports = {
v: [{
name: "version",
reg: /^(\d*)$/
}],
o: [{
// o=- 20518 0 IN IP4 203.0.113.1
// NB: sessionId will be a String in most cases because it is huge
name: "origin",
reg: /^(\S*) (\d*) (\d*) (\S*) IP(\d) (\S*)/,
names: ["username", "sessionId", "sessionVersion", "netType", "ipVer", "address"],
format: "%s %s %d %s IP%d %s"
}],
// default parsing of these only (though some of these feel outdated)
s: [{ name: "name" }],
i: [{ name: "description" }],
u: [{ name: "uri" }],
e: [{ name: "email" }],
p: [{ name: "phone" }],
z: [{ name: "timezones" }],
// TODO: this one can actually be parsed properly...
r: [{ name: "repeats" }],
// TODO: this one can also be parsed properly
// k: [{}], // outdated thing ignored
t: [{
// t=0 0
name: "timing",
reg: /^(\d*) (\d*)/,
names: ["start", "stop"],
format: "%d %d"
}],
c: [{
// c=IN IP4 10.47.197.26
name: "connection",
reg: /^IN IP(\d) (\S*)/,
names: ["version", "ip"],
format: "IN IP%d %s"
}],
b: [{
// b=AS:4000
push: "bandwidth",
reg: /^(TIAS|AS|CT|RR|RS):(\d*)/,
names: ["type", "limit"],
format: "%s:%s"
}],
m: [{
// m=video 51744 RTP/AVP 126 97 98 34 31
// NB: special - pushes to session
// TODO: rtp/fmtp should be filtered by the payloads found here?
reg: /^(\w*) (\d*) ([\w/]*)(?: (.*))?/,
names: ["type", "port", "protocol", "payloads"],
format: "%s %d %s %s"
}],
a: [
{
// a=rtpmap:110 opus/48000/2
push: "rtp",
reg: /^rtpmap:(\d*) ([\w\-.]*)(?:\s*\/(\d*)(?:\s*\/(\S*))?)?/,
names: ["payload", "codec", "rate", "encoding"],
format: function(o2) {
return o2.encoding ? "rtpmap:%d %s/%s/%s" : o2.rate ? "rtpmap:%d %s/%s" : "rtpmap:%d %s";
}
},
{
// a=fmtp:108 profile-level-id=24;object=23;bitrate=64000
// a=fmtp:111 minptime=10; useinbandfec=1
push: "fmtp",
reg: /^fmtp:(\d*) ([\S| ]*)/,
names: ["payload", "config"],
format: "fmtp:%d %s"
},
{
// a=control:streamid=0
name: "control",
reg: /^control:(.*)/,
format: "control:%s"
},
{
// a=rtcp:65179 IN IP4 193.84.77.194
name: "rtcp",
reg: /^rtcp:(\d*)(?: (\S*) IP(\d) (\S*))?/,
names: ["port", "netType", "ipVer", "address"],
format: function(o2) {
return o2.address != null ? "rtcp:%d %s IP%d %s" : "rtcp:%d";
}
},
{
// a=rtcp-fb:98 trr-int 100
push: "rtcpFbTrrInt",
reg: /^rtcp-fb:(\*|\d*) trr-int (\d*)/,
names: ["payload", "value"],
format: "rtcp-fb:%s trr-int %d"
},
{
// a=rtcp-fb:98 nack rpsi
push: "rtcpFb",
reg: /^rtcp-fb:(\*|\d*) ([\w-_]*)(?: ([\w-_]*))?/,
names: ["payload", "type", "subtype"],
format: function(o2) {
return o2.subtype != null ? "rtcp-fb:%s %s %s" : "rtcp-fb:%s %s";
}
},
{
// a=extmap:2 urn:ietf:params:rtp-hdrext:toffset
// a=extmap:1/recvonly URI-gps-string
// a=extmap:3 urn:ietf:params:rtp-hdrext:encrypt urn:ietf:params:rtp-hdrext:smpte-tc 25@600/24
push: "ext",
reg: /^extmap:(\d+)(?:\/(\w+))?(?: (urn:ietf:params:rtp-hdrext:encrypt))? (\S*)(?: (\S*))?/,
names: ["value", "direction", "encrypt-uri", "uri", "config"],
format: function(o2) {
return "extmap:%d" + (o2.direction ? "/%s" : "%v") + (o2["encrypt-uri"] ? " %s" : "%v") + " %s" + (o2.config ? " %s" : "");
}
},
{
// a=extmap-allow-mixed
name: "extmapAllowMixed",
reg: /^(extmap-allow-mixed)/
},
{
// a=crypto:1 AES_CM_128_HMAC_SHA1_80 inline:PS1uQCVeeCFCanVmcjkpPywjNWhcYD0mXXtxaVBR|2^20|1:32
push: "crypto",
reg: /^crypto:(\d*) ([\w_]*) (\S*)(?: (\S*))?/,
names: ["id", "suite", "config", "sessionConfig"],
format: function(o2) {
return o2.sessionConfig != null ? "crypto:%d %s %s %s" : "crypto:%d %s %s";
}
},
{
// a=setup:actpass
name: "setup",
reg: /^setup:(\w*)/,
format: "setup:%s"
},
{
// a=connection:new
name: "connectionType",
reg: /^connection:(new|existing)/,
format: "connection:%s"
},
{
// a=mid:1
name: "mid",
reg: /^mid:([^\s]*)/,
format: "mid:%s"
},
{
// a=msid:0c8b064d-d807-43b4-b434-f92a889d8587 98178685-d409-46e0-8e16-7ef0db0db64a
name: "msid",
reg: /^msid:(.*)/,
format: "msid:%s"
},
{
// a=ptime:20
name: "ptime",
reg: /^ptime:(\d*(?:\.\d*)*)/,
format: "ptime:%d"
},
{
// a=maxptime:60
name: "maxptime",
reg: /^maxptime:(\d*(?:\.\d*)*)/,
format: "maxptime:%d"
},
{
// a=sendrecv
name: "direction",
reg: /^(sendrecv|recvonly|sendonly|inactive)/
},
{
// a=ice-lite
name: "icelite",
reg: /^(ice-lite)/
},
{
// a=ice-ufrag:F7gI
name: "iceUfrag",
reg: /^ice-ufrag:(\S*)/,
format: "ice-ufrag:%s"
},
{
// a=ice-pwd:x9cml/YzichV2+XlhiMu8g
name: "icePwd",
reg: /^ice-pwd:(\S*)/,
format: "ice-pwd:%s"
},
{
// a=fingerprint:SHA-1 00:11:22:33:44:55:66:77:88:99:AA:BB:CC:DD:EE:FF:00:11:22:33
name: "fingerprint",
reg: /^fingerprint:(\S*) (\S*)/,
names: ["type", "hash"],
format: "fingerprint:%s %s"
},
{
// a=candidate:0 1 UDP 2113667327 203.0.113.1 54400 typ host
// a=candidate:1162875081 1 udp 2113937151 192.168.34.75 60017 typ host generation 0 network-id 3 network-cost 10
// a=candidate:3289912957 2 udp 1845501695 193.84.77.194 60017 typ srflx raddr 192.168.34.75 rport 60017 generation 0 network-id 3 network-cost 10
// a=candidate:229815620 1 tcp 1518280447 192.168.150.19 60017 typ host tcptype active generation 0 network-id 3 network-cost 10
// a=candidate:3289912957 2 tcp 1845501695 193.84.77.194 60017 typ srflx raddr 192.168.34.75 rport 60017 tcptype passive generation 0 network-id 3 network-cost 10
push: "candidates",
reg: /^candidate:(\S*) (\d*) (\S*) (\d*) (\S*) (\d*) typ (\S*)(?: raddr (\S*) rport (\d*))?(?: tcptype (\S*))?(?: generation (\d*))?(?: network-id (\d*))?(?: network-cost (\d*))?/,
names: ["foundation", "component", "transport", "priority", "ip", "port", "type", "raddr", "rport", "tcptype", "generation", "network-id", "network-cost"],
format: function(o2) {
var str = "candidate:%s %d %s %d %s %d typ %s";
str += o2.raddr != null ? " raddr %s rport %d" : "%v%v";
str += o2.tcptype != null ? " tcptype %s" : "%v";
if (o2.generation != null) {
str += " generation %d";
}
str += o2["network-id"] != null ? " network-id %d" : "%v";
str += o2["network-cost"] != null ? " network-cost %d" : "%v";
return str;
}
},
{
// a=end-of-candidates (keep after the candidates line for readability)
name: "endOfCandidates",
reg: /^(end-of-candidates)/
},
{
// a=remote-candidates:1 203.0.113.1 54400 2 203.0.113.1 54401 ...
name: "remoteCandidates",
reg: /^remote-candidates:(.*)/,
format: "remote-candidates:%s"
},
{
// a=ice-options:google-ice
name: "iceOptions",
reg: /^ice-options:(\S*)/,
format: "ice-options:%s"
},
{
// a=ssrc:2566107569 cname:t9YU8M1UxTF8Y1A1
push: "ssrcs",
reg: /^ssrc:(\d*) ([\w_-]*)(?::(.*))?/,
names: ["id", "attribute", "value"],
format: function(o2) {
var str = "ssrc:%d";
if (o2.attribute != null) {
str += " %s";
if (o2.value != null) {
str += ":%s";
}
}
return str;
}
},
{
// a=ssrc-group:FEC 1 2
// a=ssrc-group:FEC-FR 3004364195 1080772241
push: "ssrcGroups",
// token-char = %x21 / %x23-27 / %x2A-2B / %x2D-2E / %x30-39 / %x41-5A / %x5E-7E
reg: /^ssrc-group:([\x21\x23\x24\x25\x26\x27\x2A\x2B\x2D\x2E\w]*) (.*)/,
names: ["semantics", "ssrcs"],
format: "ssrc-group:%s %s"
},
{
// a=msid-semantic: WMS Jvlam5X3SX1OP6pn20zWogvaKJz5Hjf9OnlV
name: "msidSemantic",
reg: /^msid-semantic:\s?(\w*) (\S*)/,
names: ["semantic", "token"],
format: "msid-semantic: %s %s"
// space after ':' is not accidental
},
{
// a=group:BUNDLE audio video
push: "groups",
reg: /^group:(\w*) (.*)/,
names: ["type", "mids"],
format: "group:%s %s"
},
{
// a=rtcp-mux
name: "rtcpMux",
reg: /^(rtcp-mux)/
},
{
// a=rtcp-rsize
name: "rtcpRsize",
reg: /^(rtcp-rsize)/
},
{
// a=sctpmap:5000 webrtc-datachannel 1024
name: "sctpmap",
reg: /^sctpmap:([\w_/]*) (\S*)(?: (\S*))?/,
names: ["sctpmapNumber", "app", "maxMessageSize"],
format: function(o2) {
return o2.maxMessageSize != null ? "sctpmap:%s %s %s" : "sctpmap:%s %s";
}
},
{
// a=x-google-flag:conference
name: "xGoogleFlag",
reg: /^x-google-flag:([^\s]*)/,
format: "x-google-flag:%s"
},
{
// a=rid:1 send max-width=1280;max-height=720;max-fps=30;depend=0
push: "rids",
reg: /^rid:([\d\w]+) (\w+)(?: ([\S| ]*))?/,
names: ["id", "direction", "params"],
format: function(o2) {
return o2.params ? "rid:%s %s %s" : "rid:%s %s";
}
},
{
// a=imageattr:97 send [x=800,y=640,sar=1.1,q=0.6] [x=480,y=320] recv [x=330,y=250]
// a=imageattr:* send [x=800,y=640] recv *
// a=imageattr:100 recv [x=320,y=240]
push: "imageattrs",
reg: new RegExp(
// a=imageattr:97
"^imageattr:(\\d+|\\*)[\\s\\t]+(send|recv)[\\s\\t]+(\\*|\\[\\S+\\](?:[\\s\\t]+\\[\\S+\\])*)(?:[\\s\\t]+(recv|send)[\\s\\t]+(\\*|\\[\\S+\\](?:[\\s\\t]+\\[\\S+\\])*))?"
),
names: ["pt", "dir1", "attrs1", "dir2", "attrs2"],
format: function(o2) {
return "imageattr:%s %s %s" + (o2.dir2 ? " %s %s" : "");
}
},
{
// a=simulcast:send 1,2,3;~4,~5 recv 6;~7,~8
// a=simulcast:recv 1;4,5 send 6;7
name: "simulcast",
reg: new RegExp(
// a=simulcast:
"^simulcast:(send|recv) ([a-zA-Z0-9\\-_~;,]+)(?:\\s?(send|recv) ([a-zA-Z0-9\\-_~;,]+))?$"
),
names: ["dir1", "list1", "dir2", "list2"],
format: function(o2) {
return "simulcast:%s %s" + (o2.dir2 ? " %s %s" : "");
}
},
{
// old simulcast draft 03 (implemented by Firefox)
// https://tools.ietf.org/html/draft-ietf-mmusic-sdp-simulcast-03
// a=simulcast: recv pt=97;98 send pt=97
// a=simulcast: send rid=5;6;7 paused=6,7
name: "simulcast_03",
reg: /^simulcast:[\s\t]+([\S+\s\t]+)$/,
names: ["value"],
format: "simulcast: %s"
},
{
// a=framerate:25
// a=framerate:29.97
name: "framerate",
reg: /^framerate:(\d+(?:$|\.\d+))/,
format: "framerate:%s"
},
{
// RFC4570
// a=source-filter: incl IN IP4 239.5.2.31 10.1.15.5
name: "sourceFilter",
reg: /^source-filter: *(excl|incl) (\S*) (IP4|IP6|\*) (\S*) (.*)/,
names: ["filterMode", "netType", "addressTypes", "destAddress", "srcList"],
format: "source-filter: %s %s %s %s %s"
},
{
// a=bundle-only
name: "bundleOnly",
reg: /^(bundle-only)/
},
{
// a=label:1
name: "label",
reg: /^label:(.+)/,
format: "label:%s"
},
{
// RFC version 26 for SCTP over DTLS
// https://tools.ietf.org/html/draft-ietf-mmusic-sctp-sdp-26#section-5
name: "sctpPort",
reg: /^sctp-port:(\d+)$/,
format: "sctp-port:%s"
},
{
// RFC version 26 for SCTP over DTLS
// https://tools.ietf.org/html/draft-ietf-mmusic-sctp-sdp-26#section-6
name: "maxMessageSize",
reg: /^max-message-size:(\d+)$/,
format: "max-message-size:%s"
},
{
// RFC7273
// a=ts-refclk:ptp=IEEE1588-2008:39-A7-94-FF-FE-07-CB-D0:37
push: "tsRefClocks",
reg: /^ts-refclk:([^\s=]*)(?:=(\S*))?/,
names: ["clksrc", "clksrcExt"],
format: function(o2) {
return "ts-refclk:%s" + (o2.clksrcExt != null ? "=%s" : "");
}
},
{
// RFC7273
// a=mediaclk:direct=963214424
name: "mediaClk",
reg: /^mediaclk:(?:id=(\S*))? *([^\s=]*)(?:=(\S*))?(?: *rate=(\d+)\/(\d+))?/,
names: ["id", "mediaClockName", "mediaClockValue", "rateNumerator", "rateDenominator"],
format: function(o2) {
var str = "mediaclk:";
str += o2.id != null ? "id=%s %s" : "%v%s";
str += o2.mediaClockValue != null ? "=%s" : "";
str += o2.rateNumerator != null ? " rate=%s" : "";
str += o2.rateDenominator != null ? "/%s" : "";
return str;
}
},
{
// a=keywds:keywords
name: "keywords",
reg: /^keywds:(.+)$/,
format: "keywds:%s"
},
{
// a=content:main
name: "content",
reg: /^content:(.+)/,
format: "content:%s"
},
// BFCP https://tools.ietf.org/html/rfc4583
{
// a=floorctrl:c-s
name: "bfcpFloorCtrl",
reg: /^floorctrl:(c-only|s-only|c-s)/,
format: "floorctrl:%s"
},
{
// a=confid:1
name: "bfcpConfId",
reg: /^confid:(\d+)/,
format: "confid:%s"
},
{
// a=userid:1
name: "bfcpUserId",
reg: /^userid:(\d+)/,
format: "userid:%s"
},
{
// a=floorid:1
name: "bfcpFloorId",
reg: /^floorid:(.+) (?:m-stream|mstrm):(.+)/,
names: ["id", "mStream"],
format: "floorid:%s mstrm:%s"
},
{
// any a= that we don't understand is kept verbatim on media.invalid
push: "invalid",
names: ["value"]
}
]
};
Object.keys(grammar).forEach(function(key) {
var objs = grammar[key];
objs.forEach(function(obj) {
if (!obj.reg) {
obj.reg = /(.*)/;
}
if (!obj.format) {
obj.format = "%s";
}
});
});
}
});
// ../../node_modules/.pnpm/sdp-transform@2.15.0/node_modules/sdp-transform/lib/parser.js
var require_parser = __commonJS({
"../../node_modules/.pnpm/sdp-transform@2.15.0/node_modules/sdp-transform/lib/parser.js"(exports) {
init_process();
var toIntIfInt = function(v) {
return String(Number(v)) === v ? Number(v) : v;
};
var attachProperties = function(match, location, names, rawName) {
if (rawName && !names) {
location[rawName] = toIntIfInt(match[1]);
} else {
for (var i = 0; i < names.length; i += 1) {
if (match[i + 1] != null) {
location[names[i]] = toIntIfInt(match[i + 1]);
}
}
}
};
var parseReg = function(obj, location, content) {
var needsBlank = obj.name && obj.names;
if (obj.push && !location[obj.push]) {
location[obj.push] = [];
} else if (needsBlank && !location[obj.name]) {
location[obj.name] = {};
}
var keyLocation = obj.push ? {} : (
// blank object that will be pushed
needsBlank ? location[obj.name] : location
);
attachProperties(content.match(obj.reg), keyLocation, obj.names, obj.name);
if (obj.push) {
location[obj.push].push(keyLocation);
}
};
var grammar = require_grammar();
var validLine = RegExp.prototype.test.bind(/^([a-z])=(.*)/);
exports.parse = function(sdp) {
var session = {}, media = [], location = session;
sdp.split(/(\r\n|\r|\n)/).filter(validLine).forEach(function(l) {
var type = l[0];
var content = l.slice(2);
if (type === "m") {
media.push({ rtp: [], fmtp: [] });
location = media[media.length - 1];
}
for (var j = 0; j < (grammar[type] || []).length; j += 1) {
var obj = grammar[type][j];
if (obj.reg.test(content)) {
return parseReg(obj, location, content);
}
}
});
session.media = media;
return session;
};
var paramReducer = function(acc, expr) {
var s = expr.split(/=(.+)/, 2);
if (s.length === 2) {
acc[s[0]] = toIntIfInt(s[1]);
} else if (s.length === 1 && expr.length > 1) {
acc[s[0]] = void 0;
}
return acc;
};
exports.parseParams = function(str) {
return str.split(/;\s?/).reduce(paramReducer, {});
};
exports.parseFmtpConfig = exports.parseParams;
exports.parsePayloads = function(str) {
return str.toString().split(" ").map(Number);
};
exports.parseRemoteCandidates = function(str) {
var candidates = [];
var parts = str.split(" ").map(toIntIfInt);
for (var i = 0; i < parts.length; i += 3) {
candidates.push({
component: parts[i],
ip: parts[i + 1],
port: parts[i + 2]
});
}
return candidates;
};
exports.parseImageAttributes = function(str) {
return str.split(" ").map(function(item) {
return item.substring(1, item.length - 1).split(",").reduce(paramReducer, {});
});
};
exports.parseSimulcastStreamList = function(str) {
return str.split(";").map(function(stream) {
return stream.split(",").map(function(format) {
var scid, paused = false;
if (format[0] !== "~") {
scid = toIntIfInt(format);
} else {
scid = toIntIfInt(format.substring(1, format.length));
paused = true;
}
return {
scid,
paused
};
});
});
};
}
});
// ../../node_modules/.pnpm/sdp-transform@2.15.0/node_modules/sdp-transform/lib/writer.js
var require_writer = __commonJS({
"../../node_modules/.pnpm/sdp-transform@2.15.0/node_modules/sdp-transform/lib/writer.js"(exports, module) {
init_process();
var grammar = require_grammar();
var formatRegExp = /%[sdv%]/g;
var format = function(formatStr) {
var i = 1;
var args = arguments;
var len = args.length;
return formatStr.replace(formatRegExp, function(x) {
if (i >= len) {
return x;
}
var arg = args[i];
i += 1;
switch (x) {
case "%%":
return "%";
case "%s":
return String(arg);
case "%d":
return Number(arg);
case "%v":
return "";
}
});
};
var makeLine = function(type, obj, location) {
var str = obj.format instanceof Function ? obj.format(obj.push ? location : location[obj.name]) : obj.format;
var args = [type + "=" + str];
if (obj.names) {
for (var i = 0; i < obj.names.length; i += 1) {
var n2 = obj.names[i];
if (obj.name) {
args.push(location[obj.name][n2]);
} else {
args.push(location[obj.names[i]]);
}
}
} else {
args.push(location[obj.name]);
}
return format.apply(null, args);
};
var defaultOuterOrder = [
"v",
"o",
"s",
"i",
"u",
"e",
"p",
"c",
"b",
"t",
"r",
"z",
"a"
];
var defaultInnerOrder = ["i", "c", "b", "a"];
module.exports = function(session, opts) {
opts = opts || {};
if (session.version == null) {
session.version = 0;
}
if (session.name == null) {
session.name = " ";
}
session.media.forEach(function(mLine) {
if (mLine.payloads == null) {
mLine.payloads = "";
}
});
var outerOrder = opts.outerOrder || defaultOuterOrder;
var innerOrder = opts.innerOrder || defaultInnerOrder;
var sdp = [];
outerOrder.forEach(function(type) {
grammar[type].forEach(function(obj) {
if (obj.name in session && session[obj.name] != null) {
sdp.push(makeLine(type, obj, session));
} else if (obj.push in session && session[obj.push] != null) {
session[obj.push].forEach(function(el) {
sdp.push(makeLine(type, obj, el));
});
}
});
});
session.media.forEach(function(mLine) {
sdp.push(makeLine("m", grammar.m[0], mLine));
innerOrder.forEach(function(type) {
grammar[type].forEach(function(obj) {
if (obj.name in mLine && mLine[obj.name] != null) {
sdp.push(makeLine(type, obj, mLine));
} else if (obj.push in mLine && mLine[obj.push] != null) {
mLine[obj.push].forEach(function(el) {
sdp.push(makeLine(type, obj, el));
});
}
});
});
});
return sdp.join("\r\n") + "\r\n";
};
}
});
// ../../node_modules/.pnpm/sdp-transform@2.15.0/node_modules/sdp-transform/lib/index.js
var require_lib = __commonJS({
"../../node_modules/.pnpm/sdp-transform@2.15.0/node_modules/sdp-transform/lib/index.js"(exports) {
init_process();
var parser = require_parser();
var writer = require_writer();
var grammar = require_grammar();
exports.grammar = grammar;
exports.write = writer;
exports.parse = parser.parse;
exports.parseParams = parser.parseParams;
exports.parseFmtpConfig = parser.parseFmtpConfig;
exports.parsePayloads = parser.parsePayloads;
exports.parseRemoteCandidates = parser.parseRemoteCandidates;
exports.parseImageAttributes = parser.parseImageAttributes;
exports.parseSimulcastStreamList = parser.parseSimulcastStreamList;
}
});
// ../../node_modules/.pnpm/ua-parser-js@1.0.40/node_modules/ua-parser-js/src/ua-parser.js
var require_ua_parser = __commonJS({
"../../node_modules/.pnpm/ua-parser-js@1.0.40/node_modules/ua-parser-js/src/ua-parser.js"(exports, module) {
init_process();
(function(window2, undefined2) {
"use strict";
var LIBVERSION = "1.0.40", EMPTY = "", UNKNOWN = "?", FUNC_TYPE = "function", UNDEF_TYPE = "undefined", OBJ_TYPE = "object", STR_TYPE = "string", MAJOR = "major", MODEL = "model", NAME = "name", TYPE = "type", VENDOR = "vendor", VERSION3 = "version", ARCHITECTURE = "architecture", CONSOLE = "console", MOBILE = "mobile", TABLET = "tablet", SMARTTV = "smarttv", WEARABLE = "wearable", EMBEDDED = "embedded", UA_MAX_LENGTH = 500;
var AMAZON = "Amazon", APPLE = "Apple", ASUS = "ASUS", BLACKBERRY = "BlackBerry", BROWSER = "Browser", CHROME = "Chrome", EDGE = "Edge", FIREFOX = "Firefox", GOOGLE = "Google", HUAWEI = "Huawei", LG = "LG", MICROSOFT = "Microsoft", MOTOROLA = "Motorola", OPERA = "Opera", SAMSUNG = "Samsung", SHARP = "Sharp", SONY = "Sony", XIAOMI = "Xiaomi", ZEBRA = "Zebra", FACEBOOK = "Facebook", CHROMIUM_OS = "Chromium OS", MAC_OS = "Mac OS", SUFFIX_BROWSER = " Browser";
var extend2 = function(regexes2, extensions) {
var mergedRegexes = {};
for (var i in regexes2) {
if (extensions[i] && extensions[i].length % 2 === 0) {
mergedRegexes[i] = extensions[i].concat(regexes2[i]);
} else {
mergedRegexes[i] = regexes2[i];
}
}
return mergedRegexes;
}, enumerize = function(arr) {
var enums = {};
for (var i = 0; i < arr.length; i++) {
enums[arr[i].toUpperCase()] = arr[i];
}
return enums;
}, has = function(str1, str2) {
return typeof str1 === STR_TYPE ? lowerize(str2).indexOf(lowerize(str1)) !== -1 : false;
}, lowerize = function(str) {
return str.toLowerCase();
}, majorize = function(version) {
return typeof version === STR_TYPE ? version.replace(/[^\d\.]/g, EMPTY).split(".")[0] : undefined2;
}, trim2 = function(str, len) {
if (typeof str === STR_TYPE) {
str = str.replace(/^\s\s*/, EMPTY);
return typeof len === UNDEF_TYPE ? str : str.substring(0, UA_MAX_LENGTH);
}
};
var rgxMapper = function(ua, arrays) {
var i = 0, j, k, p, q, matches, match;
while (i < arrays.length && !matches) {
var regex = arrays[i], props = arrays[i + 1];
j = k = 0;
while (j < regex.length && !matches) {
if (!regex[j]) {
break;
}
matches = regex[j++].exec(ua);
if (!!matches) {
for (p = 0; p < props.length; p++) {
match = matches[++k];
q = props[p];
if (typeof q === OBJ_TYPE && q.length > 0) {
if (q.length === 2) {
if (typeof q[1] == FUNC_TYPE) {
this[q[0]] = q[1].call(this, match);
} else {
this[q[0]] = q[1];
}
} else if (q.length === 3) {
if (typeof q[1] === FUNC_TYPE && !(q[1].exec && q[1].test)) {
this[q[0]] = match ? q[1].call(this, match, q[2]) : undefined2;
} else {
this[q[0]] = match ? match.replace(q[1], q[2]) : undefined2;
}
} else if (q.length === 4) {
this[q[0]] = match ? q[3].call(this, match.replace(q[1], q[2])) : undefined2;
}
} else {
this[q] = match ? match : undefined2;
}
}
}
}
i += 2;
}
}, strMapper = function(str, map) {
for (var i in map) {
if (typeof map[i] === OBJ_TYPE && map[i].length > 0) {
for (var j = 0; j < map[i].length; j++) {
if (has(map[i][j], str)) {
return i === UNKNOWN ? undefined2 : i;
}
}
} else if (has(map[i], str)) {
return i === UNKNOWN ? undefined2 : i;
}
}
return map.hasOwnProperty("*") ? map["*"] : str;
};
var oldSafariMap = {
"1.0": "/8",
"1.2": "/1",
"1.3": "/3",
"2.0": "/412",
"2.0.2": "/416",
"2.0.3": "/417",
"2.0.4": "/419",
"?": "/"
}, windowsVersionMap = {
"ME": "4.90",
"NT 3.11": "NT3.51",
"NT 4.0": "NT4.0",
"2000": "NT 5.0",
"XP": ["NT 5.1", "NT 5.2"],
"Vista": "NT 6.0",
"7": "NT 6.1",
"8": "NT 6.2",
"8.1": "NT 6.3",
"10": ["NT 6.4", "NT 10.0"],
"RT": "ARM"
};
var regexes = {
browser: [
[
/\b(?:crmo|crios)\/([\w\.]+)/i
// Chrome for Android/iOS
],
[VERSION3, [NAME, "Chrome"]],
[
/edg(?:e|ios|a)?\/([\w\.]+)/i
// Microsoft Edge
],
[VERSION3, [NAME, "Edge"]],
[
// Presto based
/(opera mini)\/([-\w\.]+)/i,
// Opera Mini
/(opera [mobiletab]{3,6})\b.+version\/([-\w\.]+)/i,
// Opera Mobi/Tablet
/(opera)(?:.+version\/|[\/ ]+)([\w\.]+)/i
// Opera
],
[NAME, VERSION3],
[
/opios[\/ ]+([\w\.]+)/i
// Opera mini on iphone >= 8.0
],
[VERSION3, [NAME, OPERA + " Mini"]],
[
/\bop(?:rg)?x\/([\w\.]+)/i
// Opera GX
],
[VERSION3, [NAME, OPERA + " GX"]],
[
/\bopr\/([\w\.]+)/i
// Opera Webkit
],
[VERSION3, [NAME, OPERA]],
[
// Mixed
/\bb[ai]*d(?:uhd|[ub]*[aekoprswx]{5,6})[\/ ]?([\w\.]+)/i
// Baidu
],
[VERSION3, [NAME, "Baidu"]],
[
/\b(?:mxbrowser|mxios|myie2)\/?([-\w\.]*)\b/i
// Maxthon
],
[VERSION3, [NAME, "Maxthon"]],
[
/(kindle)\/([\w\.]+)/i,
// Kindle
/(lunascape|maxthon|netfront|jasmine|blazer|sleipnir)[\/ ]?([\w\.]*)/i,
// Lunascape/Maxthon/Netfront/Jasmine/Blazer/Sleipnir
// Trident based
/(avant|iemobile|slim(?:browser|boat|jet))[\/ ]?([\d\.]*)/i,
// Avant/IEMobile/SlimBrowser/SlimBoat/Slimjet
/(?:ms|\()(ie) ([\w\.]+)/i,
// Internet Explorer
// Blink/Webkit/KHTML based // Flock/RockMelt/Midori/Epiphany/Silk/Skyfire/Bolt/Iron/Iridium/PhantomJS/Bowser/QupZilla/Falkon
/(flock|rockmelt|midori|epiphany|silk|skyfire|ovibrowser|bolt|iron|vivaldi|iridium|phantomjs|bowser|qupzilla|falkon|rekonq|puffin|brave|whale(?!.+naver)|qqbrowserlite|duckduckgo|klar|helio|(?=comodo_)?dragon)\/([-\w\.]+)/i,
// Rekonq/Puffin/Brave/Whale/QQBrowserLite/QQ//Vivaldi/DuckDuckGo/Klar/Helio/Dragon
/(heytap|ovi|115)browser\/([\d\.]+)/i,
// HeyTap/Ovi/115
/(weibo)__([\d\.]+)/i
// Weibo
],
[NAME, VERSION3],
[
/quark(?:pc)?\/([-\w\.]+)/i
// Quark
],
[VERSION3, [NAME, "Quark"]],
[
/\bddg\/([\w\.]+)/i
// DuckDuckGo
],
[VERSION3, [NAME, "DuckDuckGo"]],
[
/(?:\buc? ?browser|(?:juc.+)ucweb)[\/ ]?([\w\.]+)/i
// UCBrowser
],
[VERSION3, [NAME, "UC" + BROWSER]],
[
/microm.+\bqbcore\/([\w\.]+)/i,
// WeChat Desktop for Windows Built-in Browser
/\bqbcore\/([\w\.]+).+microm/i,
/micromessenger\/([\w\.]+)/i
// WeChat
],
[VERSION3, [NAME, "WeChat"]],
[
/konqueror\/([\w\.]+)/i
// Konqueror
],
[VERSION3, [NAME, "Konqueror"]],
[
/trident.+rv[: ]([\w\.]{1,9})\b.+like gecko/i
// IE11
],
[VERSION3, [NAME, "IE"]],
[
/ya(?:search)?browser\/([\w\.]+)/i
// Yandex
],
[VERSION3, [NAME, "Yandex"]],
[
/slbrowser\/([\w\.]+)/i
// Smart Lenovo Browser
],
[VERSION3, [NAME, "Smart Lenovo " + BROWSER]],
[
/(avast|avg)\/([\w\.]+)/i
// Avast/AVG Secure Browser
],
[[NAME, /(.+)/, "$1 Secure " + BROWSER], VERSION3],
[
/\bfocus\/([\w\.]+)/i
// Firefox Focus
],
[VERSION3, [NAME, FIREFOX + " Focus"]],
[
/\bopt\/([\w\.]+)/i
// Opera Touch
],
[VERSION3, [NAME, OPERA + " Touch"]],
[
/coc_coc\w+\/([\w\.]+)/i
// Coc Coc Browser
],
[VERSION3, [NAME, "Coc Coc"]],
[
/dolfin\/([\w\.]+)/i
// Dolphin
],
[VERSION3, [NAME, "Dolphin"]],
[
/coast\/([\w\.]+)/i
// Opera Coast
],
[VERSION3, [NAME, OPERA + " Coast"]],
[
/miuibrowser\/([\w\.]+)/i
// MIUI Browser
],
[VERSION3, [NAME, "MIUI" + SUFFIX_BROWSER]],
[
/fxios\/([\w\.-]+)/i
// Firefox for iOS
],
[VERSION3, [NAME, FIREFOX]],
[
/\bqihoobrowser\/?([\w\.]*)/i
// 360
],
[VERSION3, [NAME, "360"]],
[
/\b(qq)\/([\w\.]+)/i
// QQ
],
[[NAME, /(.+)/, "$1Browser"], VERSION3],
[
/(oculus|sailfish|huawei|vivo|pico)browser\/([\w\.]+)/i
],
[[NAME, /(.+)/, "$1" + SUFFIX_BROWSER], VERSION3],
[
// Oculus/Sailfish/HuaweiBrowser/VivoBrowser/PicoBrowser
/samsungbrowser\/([\w\.]+)/i
// Samsung Internet
],
[VERSION3, [NAME, SAMSUNG + " Internet"]],
[
/metasr[\/ ]?([\d\.]+)/i
// Sogou Explorer
],
[VERSION3, [NAME, "Sogou Explorer"]],
[
/(sogou)mo\w+\/([\d\.]+)/i
// Sogou Mobile
],
[[NAME, "Sogou Mobile"], VERSION3],
[
/(electron)\/([\w\.]+) safari/i,
// Electron-based App
/(tesla)(?: qtcarbrowser|\/(20\d\d\.[-\w\.]+))/i,
// Tesla
/m?(qqbrowser|2345(?=browser|chrome|explorer))\w*[\/ ]?v?([\w\.]+)/i
// QQ/2345
],
[NAME, VERSION3],
[
/(lbbrowser|rekonq)/i,
// LieBao Browser/Rekonq
/\[(linkedin)app\]/i
// LinkedIn App for iOS & Android
],
[NAME],
[
/ome\/([\w\.]+) \w* ?(iron) saf/i,
// Iron
/ome\/([\w\.]+).+qihu (360)[es]e/i
// 360
],
[VERSION3, NAME],
[
// WebView
/((?:fban\/fbios|fb_iab\/fb4a)(?!.+fbav)|;fbav\/([\w\.]+);)/i
// Facebook App for iOS & Android
],
[[NAME, FACEBOOK], VERSION3],
[
/(Klarna)\/([\w\.]+)/i,
// Klarna Shopping Browser for iOS & Android
/(kakao(?:talk|story))[\/ ]([\w\.]+)/i,
// Kakao App
/(naver)\(.*?(\d+\.[\w\.]+).*\)/i,
// Naver InApp
/safari (line)\/([\w\.]+)/i,
// Line App for iOS
/\b(line)\/([\w\.]+)\/iab/i,
// Line App for Android
/(alipay)client\/([\w\.]+)/i,
// Alipay
/(twitter)(?:and| f.+e\/([\w\.]+))/i,
// Twitter
/(chromium|instagram|snapchat)[\/ ]([-\w\.]+)/i
// Chromium/Instagram/Snapchat
],
[NAME, VERSION3],
[
/\bgsa\/([\w\.]+) .*safari\//i
// Google Search Appliance on iOS
],
[VERSION3, [NAME, "GSA"]],
[
/musical_ly(?:.+app_?version\/|_)([\w\.]+)/i
// TikTok
],
[VERSION3, [NAME, "TikTok"]],
[
/headlesschrome(?:\/([\w\.]+)| )/i
// Chrome Headless
],
[VERSION3, [NAME, CHROME + " Headless"]],
[
/ wv\).+(chrome)\/([\w\.]+)/i
// Chrome WebView
],
[[NAME, CHROME + " WebView"], VERSION3],
[
/droid.+ version\/([\w\.]+)\b.+(?:mobile safari|safari)/i
// Android Browser
],
[VERSION3, [NAME, "Android " + BROWSER]],
[
/(chrome|omniweb|arora|[tizenoka]{5} ?browser)\/v?([\w\.]+)/i
// Chrome/OmniWeb/Arora/Tizen/Nokia
],
[NAME, VERSION3],
[
/version\/([\w\.\,]+) .*mobile\/\w+ (safari)/i
// Mobile Safari
],
[VERSION3, [NAME, "Mobile Safari"]],
[
/version\/([\w(\.|\,)]+) .*(mobile ?safari|safari)/i
// Safari & Safari Mobile
],
[VERSION3, NAME],
[
/webkit.+?(mobile ?safari|safari)(\/[\w\.]+)/i
// Safari < 3.0
],
[NAME, [VERSION3, strMapper, oldSafariMap]],
[
/(webkit|khtml)\/([\w\.]+)/i
],
[NAME, VERSION3],
[
// Gecko based
/(navigator|netscape\d?)\/([-\w\.]+)/i
// Netscape
],
[[NAME, "Netscape"], VERSION3],
[
/(wolvic|librewolf)\/([\w\.]+)/i
// Wolvic/LibreWolf
],
[NAME, VERSION3],
[
/mobile vr; rv:([\w\.]+)\).+firefox/i
// Firefox Reality
],
[VERSION3, [NAME, FIREFOX + " Reality"]],
[
/ekiohf.+(flow)\/([\w\.]+)/i,
// Flow
/(swiftfox)/i,
// Swiftfox
/(icedragon|iceweasel|camino|chimera|fennec|maemo browser|minimo|conkeror)[\/ ]?([\w\.\+]+)/i,
// IceDragon/Iceweasel/Camino/Chimera/Fennec/Maemo/Minimo/Conkeror
/(seamonkey|k-meleon|icecat|iceape|firebird|phoenix|palemoon|basilisk|waterfox)\/([-\w\.]+)$/i,
// Firefox/SeaMonkey/K-Meleon/IceCat/IceApe/Firebird/Phoenix
/(firefox)\/([\w\.]+)/i,
// Other Firefox-based
/(mozilla)\/([\w\.]+) .+rv\:.+gecko\/\d+/i,
// Mozilla
// Other
/(polaris|lynx|dillo|icab|doris|amaya|w3m|netsurf|obigo|mosaic|(?:go|ice|up)[\. ]?browser)[-\/ ]?v?([\w\.]+)/i,
// Polaris/Lynx/Dillo/iCab/Doris/Amaya/w3m/NetSurf/Obigo/Mosaic/Go/ICE/UP.Browser
/(links) \(([\w\.]+)/i
// Links
],
[NAME, [VERSION3, /_/g, "."]],
[
/(cobalt)\/([\w\.]+)/i
// Cobalt
],
[NAME, [VERSION3, /master.|lts./, ""]]
],
cpu: [
[
/(?:(amd|x(?:(?:86|64)[-_])?|wow|win)64)[;\)]/i
// AMD64 (x64)
],
[[ARCHITECTURE, "amd64"]],
[
/(ia32(?=;))/i
// IA32 (quicktime)
],
[[ARCHITECTURE, lowerize]],
[
/((?:i[346]|x)86)[;\)]/i
// IA32 (x86)
],
[[ARCHITECTURE, "ia32"]],
[
/\b(aarch64|arm(v?8e?l?|_?64))\b/i
// ARM64
],
[[ARCHITECTURE, "arm64"]],
[
/\b(arm(?:v[67])?ht?n?[fl]p?)\b/i
// ARMHF
],
[[ARCHITECTURE, "armhf"]],
[
// PocketPC mistakenly identified as PowerPC
/windows (ce|mobile); ppc;/i
],
[[ARCHITECTURE, "arm"]],
[
/((?:ppc|powerpc)(?:64)?)(?: mac|;|\))/i
// PowerPC
],
[[ARCHITECTURE, /ower/, EMPTY, lowerize]],
[
/(sun4\w)[;\)]/i
// SPARC
],
[[ARCHITECTURE, "sparc"]],
[
/((?:avr32|ia64(?=;))|68k(?=\))|\barm(?=v(?:[1-7]|[5-7]1)l?|;|eabi)|(?=atmel )avr|(?:irix|mips|sparc)(?:64)?\b|pa-risc)/i
// IA64, 68K, ARM/64, AVR/32, IRIX/64, MIPS/64, SPARC/64, PA-RISC
],
[[ARCHITECTURE, lowerize]]
],
device: [
[
//////////////////////////
// MOBILES & TABLETS
/////////////////////////
// Samsung
/\b(sch-i[89]0\d|shw-m380s|sm-[ptx]\w{2,4}|gt-[pn]\d{2,4}|sgh-t8[56]9|nexus 10)/i
],
[MODEL, [VENDOR, SAMSUNG], [TYPE, TABLET]],
[
/\b((?:s[cgp]h|gt|sm)-(?![lr])\w+|sc[g-]?[\d]+a?|galaxy nexus)/i,
/samsung[- ]((?!sm-[lr])[-\w]+)/i,
/sec-(sgh\w+)/i
],
[MODEL, [VENDOR, SAMSUNG], [TYPE, MOBILE]],
[
// Apple
/(?:\/|\()(ip(?:hone|od)[\w, ]*)(?:\/|;)/i
// iPod/iPhone
],
[MODEL, [VENDOR, APPLE], [TYPE, MOBILE]],
[
/\((ipad);[-\w\),; ]+apple/i,
// iPad
/applecoremedia\/[\w\.]+ \((ipad)/i,
/\b(ipad)\d\d?,\d\d?[;\]].+ios/i
],
[MODEL, [VENDOR, APPLE], [TYPE, TABLET]],
[
/(macintosh);/i
],
[MODEL, [VENDOR, APPLE]],
[
// Sharp
/\b(sh-?[altvz]?\d\d[a-ekm]?)/i
],
[MODEL, [VENDOR, SHARP], [TYPE, MOBILE]],
[
// Honor
/(?:honor)([-\w ]+)[;\)]/i
],
[MODEL, [VENDOR, "Honor"], [TYPE, MOBILE]],
[
// Huawei
/\b((?:ag[rs][23]?|bah2?|sht?|btv)-a?[lw]\d{2})\b(?!.+d\/s)/i
],
[MODEL, [VENDOR, HUAWEI], [TYPE, TABLET]],
[
/(?:huawei)([-\w ]+)[;\)]/i,
/\b(nexus 6p|\w{2,4}e?-[atu]?[ln][\dx][012359c][adn]?)\b(?!.+d\/s)/i
],
[MODEL, [VENDOR, HUAWEI], [TYPE, MOBILE]],
[
// Xiaomi
/\b(poco[\w ]+|m2\d{3}j\d\d[a-z]{2})(?: bui|\))/i,
// Xiaomi POCO
/\b; (\w+) build\/hm\1/i,
// Xiaomi Hongmi 'numeric' models
/\b(hm[-_ ]?note?[_ ]?(?:\d\w)?) bui/i,
// Xiaomi Hongmi
/\b(redmi[\-_ ]?(?:note|k)?[\w_ ]+)(?: bui|\))/i,
// Xiaomi Redmi
/oid[^\)]+; (m?[12][0-389][01]\w{3,6}[c-y])( bui|; wv|\))/i,
// Xiaomi Redmi 'numeric' models
/\b(mi[-_ ]?(?:a\d|one|one[_ ]plus|note lte|max|cc)?[_ ]?(?:\d?\w?)[_ ]?(?:plus|se|lite|pro)?)(?: bui|\))/i
// Xiaomi Mi
],
[[MODEL, /_/g, " "], [VENDOR, XIAOMI], [TYPE, MOBILE]],
[
/oid[^\)]+; (2\d{4}(283|rpbf)[cgl])( bui|\))/i,
// Redmi Pad
/\b(mi[-_ ]?(?:pad)(?:[\w_ ]+))(?: bui|\))/i
// Mi Pad tablets
],
[[MODEL, /_/g, " "], [VENDOR, XIAOMI], [TYPE, TABLET]],
[
// OPPO
/; (\w+) bui.+ oppo/i,
/\b(cph[12]\d{3}|p(?:af|c[al]|d\w|e[ar])[mt]\d0|x9007|a101op)\b/i
],
[MODEL, [VENDOR, "OPPO"], [TYPE, MOBILE]],
[
/\b(opd2\d{3}a?) bui/i
],
[MODEL, [VENDOR, "OPPO"], [TYPE, TABLET]],
[
// Vivo
/vivo (\w+)(?: bui|\))/i,
/\b(v[12]\d{3}\w?[at])(?: bui|;)/i
],
[MODEL, [VENDOR, "Vivo"], [TYPE, MOBILE]],
[
// Realme
/\b(rmx[1-3]\d{3})(?: bui|;|\))/i
],
[MODEL, [VENDOR, "Realme"], [TYPE, MOBILE]],
[
// Motorola
/\b(milestone|droid(?:[2-4x]| (?:bionic|x2|pro|razr))?:?( 4g)?)\b[\w ]+build\//i,
/\bmot(?:orola)?[- ](\w*)/i,
/((?:moto[\w\(\) ]+|xt\d{3,4}|nexus 6)(?= bui|\)))/i
],
[MODEL, [VENDOR, MOTOROLA], [TYPE, MOBILE]],
[
/\b(mz60\d|xoom[2 ]{0,2}) build\//i
],
[MODEL, [VENDOR, MOTOROLA], [TYPE, TABLET]],
[
// LG
/((?=lg)?[vl]k\-?\d{3}) bui| 3\.[-\w; ]{10}lg?-([06cv9]{3,4})/i
],
[MODEL, [VENDOR, LG], [TYPE, TABLET]],
[
/(lm(?:-?f100[nv]?|-[\w\.]+)(?= bui|\))|nexus [45])/i,
/\blg[-e;\/ ]+((?!browser|netcast|android tv)\w+)/i,
/\blg-?([\d\w]+) bui/i
],
[MODEL, [VENDOR, LG], [TYPE, MOBILE]],
[
// Lenovo
/(ideatab[-\w ]+)/i,
/lenovo ?(s[56]000[-\w]+|tab(?:[\w ]+)|yt[-\d\w]{6}|tb[-\d\w]{6})/i
],
[MODEL, [VENDOR, "Lenovo"], [TYPE, TABLET]],
[
// Nokia
/(?:maemo|nokia).*(n900|lumia \d+)/i,
/nokia[-_ ]?([-\w\.]*)/i
],
[[MODEL, /_/g, " "], [VENDOR, "Nokia"], [TYPE, MOBILE]],
[
// Google
/(pixel c)\b/i
// Google Pixel C
],
[MODEL, [VENDOR, GOOGLE], [TYPE, TABLET]],
[
/droid.+; (pixel[\daxl ]{0,6})(?: bui|\))/i
// Google Pixel
],
[MODEL, [VENDOR, GOOGLE], [TYPE, MOBILE]],
[
// Sony
/droid.+; (a?\d[0-2]{2}so|[c-g]\d{4}|so[-gl]\w+|xq-a\w[4-7][12])(?= bui|\).+chrome\/(?![1-6]{0,1}\d\.))/i
],
[MODEL, [VENDOR, SONY], [TYPE, MOBILE]],
[
/sony tablet [ps]/i,
/\b(?:sony)?sgp\w+(?: bui|\))/i
],
[[MODEL, "Xperia Tablet"], [VENDOR, SONY], [TYPE, TABLET]],
[
// OnePlus
/ (kb2005|in20[12]5|be20[12][59])\b/i,
/(?:one)?(?:plus)? (a\d0\d\d)(?: b|\))/i
],
[MODEL, [VENDOR, "OnePlus"], [TYPE, MOBILE]],
[
// Amazon
/(alexa)webm/i,
/(kf[a-z]{2}wi|aeo(?!bc)\w\w)( bui|\))/i,
// Kindle Fire without Silk / Echo Show
/(kf[a-z]+)( bui|\)).+silk\//i
// Kindle Fire HD
],
[MODEL, [VENDOR, AMAZON], [TYPE, TABLET]],
[
/((?:sd|kf)[0349hijorstuw]+)( bui|\)).+silk\//i
// Fire Phone
],
[[MODEL, /(.+)/g, "Fire Phone $1"], [VENDOR, AMAZON], [TYPE, MOBILE]],
[
// BlackBerry
/(playbook);[-\w\),; ]+(rim)/i
// BlackBerry PlayBook
],
[MODEL, VENDOR, [TYPE, TABLET]],
[
/\b((?:bb[a-f]|st[hv])100-\d)/i,
/\(bb10; (\w+)/i
// BlackBerry 10
],
[MODEL, [VENDOR, BLACKBERRY], [TYPE, MOBILE]],
[
// Asus
/(?:\b|asus_)(transfo[prime ]{4,10} \w+|eeepc|slider \w+|nexus 7|padfone|p00[cj])/i
],
[MODEL, [VENDOR, ASUS], [TYPE, TABLET]],
[
/ (z[bes]6[027][012][km][ls]|zenfone \d\w?)\b/i
],
[MODEL, [VENDOR, ASUS], [TYPE, MOBILE]],
[
// HTC
/(nexus 9)/i
// HTC Nexus 9
],
[MODEL, [VENDOR, "HTC"], [TYPE, TABLET]],
[
/(htc)[-;_ ]{1,2}([\w ]+(?=\)| bui)|\w+)/i,
// HTC
// ZTE
/(zte)[- ]([\w ]+?)(?: bui|\/|\))/i,
/(alcatel|geeksphone|nexian|panasonic(?!(?:;|\.))|sony(?!-bra))[-_ ]?([-\w]*)/i
// Alcatel/GeeksPhone/Nexian/Panasonic/Sony
],
[VENDOR, [MODEL, /_/g, " "], [TYPE, MOBILE]],
[
// TCL
/droid [\w\.]+; ((?:8[14]9[16]|9(?:0(?:48|60|8[01])|1(?:3[27]|66)|2(?:6[69]|9[56])|466))[gqswx])\w*(\)| bui)/i
],
[MODEL, [VENDOR, "TCL"], [TYPE, TABLET]],
[
// itel
/(itel) ((\w+))/i
],
[[VENDOR, lowerize], MODEL, [TYPE, strMapper, { "tablet": ["p10001l", "w7001"], "*": "mobile" }]],
[
// Acer
/droid.+; ([ab][1-7]-?[0178a]\d\d?)/i
],
[MODEL, [VENDOR, "Acer"], [TYPE, TABLET]],
[
// Meizu
/droid.+; (m[1-5] note) bui/i,
/\bmz-([-\w]{2,})/i
],
[MODEL, [VENDOR, "Meizu"], [TYPE, MOBILE]],
[
// Ulefone
/; ((?:power )?armor(?:[\w ]{0,8}))(?: bui|\))/i
],
[MODEL, [VENDOR, "Ulefone"], [TYPE, MOBILE]],
[
// Energizer
/; (energy ?\w+)(?: bui|\))/i,
/; energizer ([\w ]+)(?: bui|\))/i
],
[MODEL, [VENDOR, "Energizer"], [TYPE, MOBILE]],
[
// Cat
/; cat (b35);/i,
/; (b15q?|s22 flip|s48c|s62 pro)(?: bui|\))/i
],
[MODEL, [VENDOR, "Cat"], [TYPE, MOBILE]],
[
// Smartfren
/((?:new )?andromax[\w- ]+)(?: bui|\))/i
],
[MODEL, [VENDOR, "Smartfren"], [TYPE, MOBILE]],
[
// Nothing
/droid.+; (a(?:015|06[35]|142p?))/i
],
[MODEL, [VENDOR, "Nothing"], [TYPE, MOBILE]],
[
// MIXED
/(blackberry|benq|palm(?=\-)|sonyericsson|acer|asus|dell|meizu|motorola|polytron|infinix|tecno|micromax|advan)[-_ ]?([-\w]*)/i,
// BlackBerry/BenQ/Palm/Sony-Ericsson/Acer/Asus/Dell/Meizu/Motorola/Polytron/Infinix/Tecno/Micromax/Advan
/; (imo) ((?!tab)[\w ]+?)(?: bui|\))/i,
// IMO
/(hp) ([\w ]+\w)/i,
// HP iPAQ
/(asus)-?(\w+)/i,
// Asus
/(microsoft); (lumia[\w ]+)/i,
// Microsoft Lumia
/(lenovo)[-_ ]?([-\w]+)/i,
// Lenovo
/(jolla)/i,
// Jolla
/(oppo) ?([\w ]+) bui/i
// OPPO
],
[VENDOR, MODEL, [TYPE, MOBILE]],
[
/(imo) (tab \w+)/i,
// IMO
/(kobo)\s(ereader|touch)/i,
// Kobo
/(archos) (gamepad2?)/i,
// Archos
/(hp).+(touchpad(?!.+tablet)|tablet)/i,
// HP TouchPad
/(kindle)\/([\w\.]+)/i,
// Kindle
/(nook)[\w ]+build\/(\w+)/i,
// Nook
/(dell) (strea[kpr\d ]*[\dko])/i,
// Dell Streak
/(le[- ]+pan)[- ]+(\w{1,9}) bui/i,
// Le Pan Tablets
/(trinity)[- ]*(t\d{3}) bui/i,
// Trinity Tablets
/(gigaset)[- ]+(q\w{1,9}) bui/i,
// Gigaset Tablets
/(vodafone) ([\w ]+)(?:\)| bui)/i
// Vodafone
],
[VENDOR, MODEL, [TYPE, TABLET]],
[
/(surface duo)/i
// Surface Duo
],
[MODEL, [VENDOR, MICROSOFT], [TYPE, TABLET]],
[
/droid [\d\.]+; (fp\du?)(?: b|\))/i
// Fairphone
],
[MODEL, [VENDOR, "Fairphone"], [TYPE, MOBILE]],
[
/(u304aa)/i
// AT&T
],
[MODEL, [VENDOR, "AT&T"], [TYPE, MOBILE]],
[
/\bsie-(\w*)/i
// Siemens
],
[MODEL, [VENDOR, "Siemens"], [TYPE, MOBILE]],
[
/\b(rct\w+) b/i
// RCA Tablets
],
[MODEL, [VENDOR, "RCA"], [TYPE, TABLET]],
[
/\b(venue[\d ]{2,7}) b/i
// Dell Venue Tablets
],
[MODEL, [VENDOR, "Dell"], [TYPE, TABLET]],
[
/\b(q(?:mv|ta)\w+) b/i
// Verizon Tablet
],
[MODEL, [VENDOR, "Verizon"], [TYPE, TABLET]],
[
/\b(?:barnes[& ]+noble |bn[rt])([\w\+ ]*) b/i
// Barnes & Noble Tablet
],
[MODEL, [VENDOR, "Barnes & Noble"], [TYPE, TABLET]],
[
/\b(tm\d{3}\w+) b/i
],
[MODEL, [VENDOR, "NuVision"], [TYPE, TABLET]],
[
/\b(k88) b/i
// ZTE K Series Tablet
],
[MODEL, [VENDOR, "ZTE"], [TYPE, TABLET]],
[
/\b(nx\d{3}j) b/i
// ZTE Nubia
],
[MODEL, [VENDOR, "ZTE"], [TYPE, MOBILE]],
[
/\b(gen\d{3}) b.+49h/i
// Swiss GEN Mobile
],
[MODEL, [VENDOR, "Swiss"], [TYPE, MOBILE]],
[
/\b(zur\d{3}) b/i
// Swiss ZUR Tablet
],
[MODEL, [VENDOR, "Swiss"], [TYPE, TABLET]],
[
/\b((zeki)?tb.*\b) b/i
// Zeki Tablets
],
[MODEL, [VENDOR, "Zeki"], [TYPE, TABLET]],
[
/\b([yr]\d{2}) b/i,
/\b(dragon[- ]+touch |dt)(\w{5}) b/i
// Dragon Touch Tablet
],
[[VENDOR, "Dragon Touch"], MODEL, [TYPE, TABLET]],
[
/\b(ns-?\w{0,9}) b/i
// Insignia Tablets
],
[MODEL, [VENDOR, "Insignia"], [TYPE, TABLET]],
[
/\b((nxa|next)-?\w{0,9}) b/i
// NextBook Tablets
],
[MODEL, [VENDOR, "NextBook"], [TYPE, TABLET]],
[
/\b(xtreme\_)?(v(1[045]|2[015]|[3469]0|7[05])) b/i
// Voice Xtreme Phones
],
[[VENDOR, "Voice"], MODEL, [TYPE, MOBILE]],
[
/\b(lvtel\-)?(v1[12]) b/i
// LvTel Phones
],
[[VENDOR, "LvTel"], MODEL, [TYPE, MOBILE]],
[
/\b(ph-1) /i
// Essential PH-1
],
[MODEL, [VENDOR, "Essential"], [TYPE, MOBILE]],
[
/\b(v(100md|700na|7011|917g).*\b) b/i
// Envizen Tablets
],
[MODEL, [VENDOR, "Envizen"], [TYPE, TABLET]],
[
/\b(trio[-\w\. ]+) b/i
// MachSpeed Tablets
],
[MODEL, [VENDOR, "MachSpeed"], [TYPE, TABLET]],
[
/\btu_(1491) b/i
// Rotor Tablets
],
[MODEL, [VENDOR, "Rotor"], [TYPE, TABLET]],
[
/(shield[\w ]+) b/i
// Nvidia Shield Tablets
],
[MODEL, [VENDOR, "Nvidia"], [TYPE, TABLET]],
[
/(sprint) (\w+)/i
// Sprint Phones
],
[VENDOR, MODEL, [TYPE, MOBILE]],
[
/(kin\.[onetw]{3})/i
// Microsoft Kin
],
[[MODEL, /\./g, " "], [VENDOR, MICROSOFT], [TYPE, MOBILE]],
[
/droid.+; (cc6666?|et5[16]|mc[239][23]x?|vc8[03]x?)\)/i
// Zebra
],
[MODEL, [VENDOR, ZEBRA], [TYPE, TABLET]],
[
/droid.+; (ec30|ps20|tc[2-8]\d[kx])\)/i
],
[MODEL, [VENDOR, ZEBRA], [TYPE, MOBILE]],
[
///////////////////
// SMARTTVS
///////////////////
/smart-tv.+(samsung)/i
// Samsung
],
[VENDOR, [TYPE, SMARTTV]],
[
/hbbtv.+maple;(\d+)/i
],
[[MODEL, /^/, "SmartTV"], [VENDOR, SAMSUNG], [TYPE, SMARTTV]],
[
/(nux; netcast.+smarttv|lg (netcast\.tv-201\d|android tv))/i
// LG SmartTV
],
[[VENDOR, LG], [TYPE, SMARTTV]],
[
/(apple) ?tv/i
// Apple TV
],
[VENDOR, [MODEL, APPLE + " TV"], [TYPE, SMARTTV]],
[
/crkey/i
// Google Chromecast
],
[[MODEL, CHROME + "cast"], [VENDOR, GOOGLE], [TYPE, SMARTTV]],
[
/droid.+aft(\w+)( bui|\))/i
// Fire TV
],
[MODEL, [VENDOR, AMAZON], [TYPE, SMARTTV]],
[
/\(dtv[\);].+(aquos)/i,
/(aquos-tv[\w ]+)\)/i
// Sharp
],
[MODEL, [VENDOR, SHARP], [TYPE, SMARTTV]],
[
/(bravia[\w ]+)( bui|\))/i
// Sony
],
[MODEL, [VENDOR, SONY], [TYPE, SMARTTV]],
[
/(mitv-\w{5}) bui/i
// Xiaomi
],
[MODEL, [VENDOR, XIAOMI], [TYPE, SMARTTV]],
[
/Hbbtv.*(technisat) (.*);/i
// TechniSAT
],
[VENDOR, MODEL, [TYPE, SMARTTV]],
[
/\b(roku)[\dx]*[\)\/]((?:dvp-)?[\d\.]*)/i,
// Roku
/hbbtv\/\d+\.\d+\.\d+ +\([\w\+ ]*; *([\w\d][^;]*);([^;]*)/i
// HbbTV devices
],
[[VENDOR, trim2], [MODEL, trim2], [TYPE, SMARTTV]],
[
/\b(android tv|smart[- ]?tv|opera tv|tv; rv:)\b/i
// SmartTV from Unidentified Vendors
],
[[TYPE, SMARTTV]],
[
///////////////////
// CONSOLES
///////////////////
/(ouya)/i,
// Ouya
/(nintendo) ([wids3utch]+)/i
// Nintendo
],
[VENDOR, MODEL, [TYPE, CONSOLE]],
[
/droid.+; (shield) bui/i
// Nvidia
],
[MODEL, [VENDOR, "Nvidia"], [TYPE, CONSOLE]],
[
/(playstation [345portablevi]+)/i
// Playstation
],
[MODEL, [VENDOR, SONY], [TYPE, CONSOLE]],
[
/\b(xbox(?: one)?(?!; xbox))[\); ]/i
// Microsoft Xbox
],
[MODEL, [VENDOR, MICROSOFT], [TYPE, CONSOLE]],
[
///////////////////
// WEARABLES
///////////////////
/\b(sm-[lr]\d\d[05][fnuw]?s?)\b/i
// Samsung Galaxy Watch
],
[MODEL, [VENDOR, SAMSUNG], [TYPE, WEARABLE]],
[
/((pebble))app/i
// Pebble
],
[VENDOR, MODEL, [TYPE, WEARABLE]],
[
/(watch)(?: ?os[,\/]|\d,\d\/)[\d\.]+/i
// Apple Watch
],
[MODEL, [VENDOR, APPLE], [TYPE, WEARABLE]],
[
/droid.+; (glass) \d/i
// Google Glass
],
[MODEL, [VENDOR, GOOGLE], [TYPE, WEARABLE]],
[
/droid.+; (wt63?0{2,3})\)/i
],
[MODEL, [VENDOR, ZEBRA], [TYPE, WEARABLE]],
[
///////////////////
// XR
///////////////////
/droid.+; (glass) \d/i
// Google Glass
],
[MODEL, [VENDOR, GOOGLE], [TYPE, WEARABLE]],
[
/(pico) (4|neo3(?: link|pro)?)/i
// Pico
],
[VENDOR, MODEL, [TYPE, WEARABLE]],
[
/; (quest( \d| pro)?)/i
// Oculus Quest
],
[MODEL, [VENDOR, FACEBOOK], [TYPE, WEARABLE]],
[
///////////////////
// EMBEDDED
///////////////////
/(tesla)(?: qtcarbrowser|\/[-\w\.]+)/i
// Tesla
],
[VENDOR, [TYPE, EMBEDDED]],
[
/(aeobc)\b/i
// Echo Dot
],
[MODEL, [VENDOR, AMAZON], [TYPE, EMBEDDED]],
[
////////////////////
// MIXED (GENERIC)
///////////////////
/droid .+?; ([^;]+?)(?: bui|; wv\)|\) applew).+? mobile safari/i
// Android Phones from Unidentified Vendors
],
[MODEL, [TYPE, MOBILE]],
[
/droid .+?; ([^;]+?)(?: bui|\) applew).+?(?! mobile) safari/i
// Android Tablets from Unidentified Vendors
],
[MODEL, [TYPE, TABLET]],
[
/\b((tablet|tab)[;\/]|focus\/\d(?!.+mobile))/i
// Unidentifiable Tablet
],
[[TYPE, TABLET]],
[
/(phone|mobile(?:[;\/]| [ \w\/\.]*safari)|pda(?=.+windows ce))/i
// Unidentifiable Mobile
],
[[TYPE, MOBILE]],
[
/(android[-\w\. ]{0,9});.+buil/i
// Generic Android Device
],
[MODEL, [VENDOR, "Generic"]]
],
engine: [
[
/windows.+ edge\/([\w\.]+)/i
// EdgeHTML
],
[VERSION3, [NAME, EDGE + "HTML"]],
[
/(arkweb)\/([\w\.]+)/i
// ArkWeb
],
[NAME, VERSION3],
[
/webkit\/537\.36.+chrome\/(?!27)([\w\.]+)/i
// Blink
],
[VERSION3, [NAME, "Blink"]],
[
/(presto)\/([\w\.]+)/i,
// Presto
/(webkit|trident|netfront|netsurf|amaya|lynx|w3m|goanna|servo)\/([\w\.]+)/i,
// WebKit/Trident/NetFront/NetSurf/Amaya/Lynx/w3m/Goanna/Servo
/ekioh(flow)\/([\w\.]+)/i,
// Flow
/(khtml|tasman|links)[\/ ]\(?([\w\.]+)/i,
// KHTML/Tasman/Links
/(icab)[\/ ]([23]\.[\d\.]+)/i,
// iCab
/\b(libweb)/i
],
[NAME, VERSION3],
[
/rv\:([\w\.]{1,9})\b.+(gecko)/i
// Gecko
],
[VERSION3, NAME]
],
os: [
[
// Windows
/microsoft (windows) (vista|xp)/i
// Windows (iTunes)
],
[NAME, VERSION3],
[
/(windows (?:phone(?: os)?|mobile))[\/ ]?([\d\.\w ]*)/i
// Windows Phone
],
[NAME, [VERSION3, strMapper, windowsVersionMap]],
[
/windows nt 6\.2; (arm)/i,
// Windows RT
/windows[\/ ]?([ntce\d\. ]+\w)(?!.+xbox)/i,
/(?:win(?=3|9|n)|win 9x )([nt\d\.]+)/i
],
[[VERSION3, strMapper, windowsVersionMap], [NAME, "Windows"]],
[
// iOS/macOS
/ip[honead]{2,4}\b(?:.*os ([\w]+) like mac|; opera)/i,
// iOS
/(?:ios;fbsv\/|iphone.+ios[\/ ])([\d\.]+)/i,
/cfnetwork\/.+darwin/i
],
[[VERSION3, /_/g, "."], [NAME, "iOS"]],
[
/(mac os x) ?([\w\. ]*)/i,
/(macintosh|mac_powerpc\b)(?!.+haiku)/i
// Mac OS
],
[[NAME, MAC_OS], [VERSION3, /_/g, "."]],
[
// Mobile OSes
/droid ([\w\.]+)\b.+(android[- ]x86|harmonyos)/i
// Android-x86/HarmonyOS
],
[VERSION3, NAME],
[
// Android/WebOS/QNX/Bada/RIM/Maemo/MeeGo/Sailfish OS/OpenHarmony
/(android|webos|qnx|bada|rim tablet os|maemo|meego|sailfish|openharmony)[-\/ ]?([\w\.]*)/i,
/(blackberry)\w*\/([\w\.]*)/i,
// Blackberry
/(tizen|kaios)[\/ ]([\w\.]+)/i,
// Tizen/KaiOS
/\((series40);/i
// Series 40
],
[NAME, VERSION3],
[
/\(bb(10);/i
// BlackBerry 10
],
[VERSION3, [NAME, BLACKBERRY]],
[
/(?:symbian ?os|symbos|s60(?=;)|series60)[-\/ ]?([\w\.]*)/i
// Symbian
],
[VERSION3, [NAME, "Symbian"]],
[
/mozilla\/[\d\.]+ \((?:mobile|tablet|tv|mobile; [\w ]+); rv:.+ gecko\/([\w\.]+)/i
// Firefox OS
],
[VERSION3, [NAME, FIREFOX + " OS"]],
[
/web0s;.+rt(tv)/i,
/\b(?:hp)?wos(?:browser)?\/([\w\.]+)/i
// WebOS
],
[VERSION3, [NAME, "webOS"]],
[
/watch(?: ?os[,\/]|\d,\d\/)([\d\.]+)/i
// watchOS
],
[VERSION3, [NAME, "watchOS"]],
[
// Google Chromecast
/crkey\/([\d\.]+)/i
// Google Chromecast
],
[VERSION3, [NAME, CHROME + "cast"]],
[
/(cros) [\w]+(?:\)| ([\w\.]+)\b)/i
// Chromium OS
],
[[NAME, CHROMIUM_OS], VERSION3],
[
// Smart TVs
/panasonic;(viera)/i,
// Panasonic Viera
/(netrange)mmh/i,
// Netrange
/(nettv)\/(\d+\.[\w\.]+)/i,
// NetTV
// Console
/(nintendo|playstation) ([wids345portablevuch]+)/i,
// Nintendo/Playstation
/(xbox); +xbox ([^\);]+)/i,
// Microsoft Xbox (360, One, X, S, Series X, Series S)
// Other
/\b(joli|palm)\b ?(?:os)?\/?([\w\.]*)/i,
// Joli/Palm
/(mint)[\/\(\) ]?(\w*)/i,
// Mint
/(mageia|vectorlinux)[; ]/i,
// Mageia/VectorLinux
/([kxln]?ubuntu|debian|suse|opensuse|gentoo|arch(?= linux)|slackware|fedora|mandriva|centos|pclinuxos|red ?hat|zenwalk|linpus|raspbian|plan 9|minix|risc os|contiki|deepin|manjaro|elementary os|sabayon|linspire)(?: gnu\/linux)?(?: enterprise)?(?:[- ]linux)?(?:-gnu)?[-\/ ]?(?!chrom|package)([-\w\.]*)/i,
// Ubuntu/Debian/SUSE/Gentoo/Arch/Slackware/Fedora/Mandriva/CentOS/PCLinuxOS/RedHat/Zenwalk/Linpus/Raspbian/Plan9/Minix/RISCOS/Contiki/Deepin/Manjaro/elementary/Sabayon/Linspire
/(hurd|linux) ?([\w\.]*)/i,
// Hurd/Linux
/(gnu) ?([\w\.]*)/i,
// GNU
/\b([-frentopcghs]{0,5}bsd|dragonfly)[\/ ]?(?!amd|[ix346]{1,2}86)([\w\.]*)/i,
// FreeBSD/NetBSD/OpenBSD/PC-BSD/GhostBSD/DragonFly
/(haiku) (\w+)/i
// Haiku
],
[NAME, VERSION3],
[
/(sunos) ?([\w\.\d]*)/i
// Solaris
],
[[NAME, "Solaris"], VERSION3],
[
/((?:open)?solaris)[-\/ ]?([\w\.]*)/i,
// Solaris
/(aix) ((\d)(?=\.|\)| )[\w\.])*/i,
// AIX
/\b(beos|os\/2|amigaos|morphos|openvms|fuchsia|hp-ux|serenityos)/i,
// BeOS/OS2/AmigaOS/MorphOS/OpenVMS/Fuchsia/HP-UX/SerenityOS
/(unix) ?([\w\.]*)/i
// UNIX
],
[NAME, VERSION3]
]
};
var UAParser2 = function(ua, extensions) {
if (typeof ua === OBJ_TYPE) {
extensions = ua;
ua = undefined2;
}
if (!(this instanceof UAParser2)) {
return new UAParser2(ua, extensions).getResult();
}
var _navigator2 = typeof window2 !== UNDEF_TYPE && window2.navigator ? window2.navigator : undefined2;
var _ua = ua || (_navigator2 && _navigator2.userAgent ? _navigator2.userAgent : EMPTY);
var _uach = _navigator2 && _navigator2.userAgentData ? _navigator2.userAgentData : undefined2;
var _rgxmap = extensions ? extend2(regexes, extensions) : regexes;
var _isSelfNav = _navigator2 && _navigator2.userAgent == _ua;
this.getBrowser = function() {
var _browser = {};
_browser[NAME] = undefined2;
_browser[VERSION3] = undefined2;
rgxMapper.call(_browser, _ua, _rgxmap.browser);
_browser[MAJOR] = majorize(_browser[VERSION3]);
if (_isSelfNav && _navigator2 && _navigator2.brave && typeof _navigator2.brave.isBrave == FUNC_TYPE) {
_browser[NAME] = "Brave";
}
return _browser;
};
this.getCPU = function() {
var _cpu = {};
_cpu[ARCHITECTURE] = undefined2;
rgxMapper.call(_cpu, _ua, _rgxmap.cpu);
return _cpu;
};
this.getDevice = function() {
var _device = {};
_device[VENDOR] = undefined2;
_device[MODEL] = undefined2;
_device[TYPE] = undefined2;
rgxMapper.call(_device, _ua, _rgxmap.device);
if (_isSelfNav && !_device[TYPE] && _uach && _uach.mobile) {
_device[TYPE] = MOBILE;
}
if (_isSelfNav && _device[MODEL] == "Macintosh" && _navigator2 && typeof _navigator2.standalone !== UNDEF_TYPE && _navigator2.maxTouchPoints && _navigator2.maxTouchPoints > 2) {
_device[MODEL] = "iPad";
_device[TYPE] = TABLET;
}
return _device;
};
this.getEngine = function() {
var _engine = {};
_engine[NAME] = undefined2;
_engine[VERSION3] = undefined2;
rgxMapper.call(_engine, _ua, _rgxmap.engine);
return _engine;
};
this.getOS = function() {
var _os = {};
_os[NAME] = undefined2;
_os[VERSION3] = undefined2;
rgxMapper.call(_os, _ua, _rgxmap.os);
if (_isSelfNav && !_os[NAME] && _uach && _uach.platform && _uach.platform != "Unknown") {
_os[NAME] = _uach.platform.replace(/chrome os/i, CHROMIUM_OS).replace(/macos/i, MAC_OS);
}
return _os;
};
this.getResult = function() {
return {
ua: this.getUA(),
browser: this.getBrowser(),
engine: this.getEngine(),
os: this.getOS(),
device: this.getDevice(),
cpu: this.getCPU()
};
};
this.getUA = function() {
return _ua;
};
this.setUA = function(ua2) {
_ua = typeof ua2 === STR_TYPE && ua2.length > UA_MAX_LENGTH ? trim2(ua2, UA_MAX_LENGTH) : ua2;
return this;
};
this.setUA(_ua);
return this;
};
UAParser2.VERSION = LIBVERSION;
UAParser2.BROWSER = enumerize([NAME, VERSION3, MAJOR]);
UAParser2.CPU = enumerize([ARCHITECTURE]);
UAParser2.DEVICE = enumerize([MODEL, VENDOR, TYPE, CONSOLE, MOBILE, SMARTTV, TABLET, WEARABLE, EMBEDDED]);
UAParser2.ENGINE = UAParser2.OS = enumerize([NAME, VERSION3]);
if (typeof exports !== UNDEF_TYPE) {
if (typeof module !== UNDEF_TYPE && module.exports) {
exports = module.exports = UAParser2;
}
exports.UAParser = UAParser2;
} else {
if (typeof define === FUNC_TYPE && define.amd) {
define(function() {
return UAParser2;
});
} else if (typeof window2 !== UNDEF_TYPE) {
window2.UAParser = UAParser2;
}
}
var $ = typeof window2 !== UNDEF_TYPE && (window2.jQuery || window2.Zepto);
if ($ && !$.ua) {
var parser = new UAParser2();
$.ua = parser.getResult();
$.ua.get = function() {
return parser.getUA();
};
$.ua.set = function(ua) {
parser.setUA(ua);
var result2 = parser.getResult();
for (var prop in result2) {
$.ua[prop] = result2[prop];
}
};
}
})(typeof window === "object" ? window : exports);
}
});
// ../../node_modules/.pnpm/isomorphic-ws@4.0.1_ws@8.18.2/node_modules/isomorphic-ws/browser.js
var require_browser = __commonJS({
"../../node_modules/.pnpm/isomorphic-ws@4.0.1_ws@8.18.2/node_modules/isomorphic-ws/browser.js"(exports, module) {
init_process();
var ws = null;
if (typeof WebSocket !== "undefined") {
ws = WebSocket;
} else if (typeof MozWebSocket !== "undefined") {
ws = MozWebSocket;
} else if (typeof global !== "undefined") {
ws = global.WebSocket || global.MozWebSocket;
} else if (typeof window !== "undefined") {
ws = window.WebSocket || window.MozWebSocket;
} else if (typeof self !== "undefined") {
ws = self.WebSocket || self.MozWebSocket;
}
module.exports = ws;
}
});
// ../../node_modules/.pnpm/deepmerge@4.3.1/node_modules/deepmerge/dist/cjs.js
var require_cjs = __commonJS({
"../../node_modules/.pnpm/deepmerge@4.3.1/node_modules/deepmerge/dist/cjs.js"(exports, module) {
"use strict";
init_process();
var isMergeableObject = function isMergeableObject2(value) {
return isNonNullObject(value) && !isSpecial(value);
};
function isNonNullObject(value) {
return !!value && typeof value === "object";
}
function isSpecial(value) {
var stringValue = Object.prototype.toString.call(value);
return stringValue === "[object RegExp]" || stringValue === "[object Date]" || isReactElement(value);
}
var canUseSymbol = typeof Symbol === "function" && Symbol.for;
var REACT_ELEMENT_TYPE = canUseSymbol ? Symbol.for("react.element") : 60103;
function isReactElement(value) {
return value.$$typeof === REACT_ELEMENT_TYPE;
}
function emptyTarget(val) {
return Array.isArray(val) ? [] : {};
}
function cloneUnlessOtherwiseSpecified(value, options) {
return options.clone !== false && options.isMergeableObject(value) ? deepmerge3(emptyTarget(value), value, options) : value;
}
function defaultArrayMerge(target, source, options) {
return target.concat(source).map(function(element) {
return cloneUnlessOtherwiseSpecified(element, options);
});
}
function getMergeFunction(key, options) {
if (!options.customMerge) {
return deepmerge3;
}
var customMerge = options.customMerge(key);
return typeof customMerge === "function" ? customMerge : deepmerge3;
}
function getEnumerableOwnPropertySymbols(target) {
return Object.getOwnPropertySymbols ? Object.getOwnPropertySymbols(target).filter(function(symbol) {
return Object.propertyIsEnumerable.call(target, symbol);
}) : [];
}
function getKeys(target) {
return Object.keys(target).concat(getEnumerableOwnPropertySymbols(target));
}
function propertyIsOnObject(object, property) {
try {
return property in object;
} catch (_) {
return false;
}
}
function propertyIsUnsafe(target, key) {
return propertyIsOnObject(target, key) && !(Object.hasOwnProperty.call(target, key) && Object.propertyIsEnumerable.call(target, key));
}
function mergeObject(target, source, options) {
var destination = {};
if (options.isMergeableObject(target)) {
getKeys(target).forEach(function(key) {
destination[key] = cloneUnlessOtherwiseSpecified(target[key], options);
});
}
getKeys(source).forEach(function(key) {
if (propertyIsUnsafe(target, key)) {
return;
}
if (propertyIsOnObject(target, key) && options.isMergeableObject(source[key])) {
destination[key] = getMergeFunction(key, options)(target[key], source[key], options);
} else {
destination[key] = cloneUnlessOtherwiseSpecified(source[key], options);
}
});
return destination;
}
function deepmerge3(target, source, options) {
options = options || {};
options.arrayMerge = options.arrayMerge || defaultArrayMerge;
options.isMergeableObject = options.isMergeableObject || isMergeableObject;
options.cloneUnlessOtherwiseSpecified = cloneUnlessOtherwiseSpecified;
var sourceIsArray = Array.isArray(source);
var targetIsArray = Array.isArray(target);
var sourceAndTargetTypesMatch = sourceIsArray === targetIsArray;
if (!sourceAndTargetTypesMatch) {
return cloneUnlessOtherwiseSpecified(source, options);
} else if (sourceIsArray) {
return options.arrayMerge(target, source, options);
} else {
return mergeObject(target, source, options);
}
}
deepmerge3.all = function deepmergeAll(array, options) {
if (!Array.isArray(array)) {
throw new Error("first argument should be an array");
}
return array.reduce(function(prev, next) {
return deepmerge3(prev, next, options);
}, {});
};
var deepmerge_1 = deepmerge3;
module.exports = deepmerge_1;
}
});
// ../../node_modules/.pnpm/lodash@4.17.21/node_modules/lodash/_listCacheClear.js
var require_listCacheClear = __commonJS({
"../../node_modules/.pnpm/lodash@4.17.21/node_modules/lodash/_listCacheClear.js"(exports, module) {
init_process();
function listCacheClear() {
this.__data__ = [];
this.size = 0;
}
module.exports = listCacheClear;
}
});
// ../../node_modules/.pnpm/lodash@4.17.21/node_modules/lodash/eq.js
var require_eq = __commonJS({
"../../node_modules/.pnpm/lodash@4.17.21/node_modules/lodash/eq.js"(exports, module) {
init_process();
function eq(value, other) {
return value === other || value !== value && other !== other;
}
module.exports = eq;
}
});
// ../../node_modules/.pnpm/lodash@4.17.21/node_modules/lodash/_assocIndexOf.js
var require_assocIndexOf = __commonJS({
"../../node_modules/.pnpm/lodash@4.17.21/node_modules/lodash/_assocIndexOf.js"(exports, module) {
init_process();
var eq = require_eq();
function assocIndexOf(array, key) {
var length = array.length;
while (length--) {
if (eq(array[length][0], key)) {
return length;
}
}
return -1;
}
module.exports = assocIndexOf;
}
});
// ../../node_modules/.pnpm/lodash@4.17.21/node_modules/lodash/_listCacheDelete.js
var require_listCacheDelete = __commonJS({
"../../node_modules/.pnpm/lodash@4.17.21/node_modules/lodash/_listCacheDelete.js"(exports, module) {
init_process();
var assocIndexOf = require_assocIndexOf();
var arrayProto = Array.prototype;
var splice = arrayProto.splice;
function listCacheDelete(key) {
var data = this.__data__, index = assocIndexOf(data, key);
if (index < 0) {
return false;
}
var lastIndex = data.length - 1;
if (index == lastIndex) {
data.pop();
} else {
splice.call(data, index, 1);
}
--this.size;
return true;
}
module.exports = listCacheDelete;
}
});
// ../../node_modules/.pnpm/lodash@4.17.21/node_modules/lodash/_listCacheGet.js
var require_listCacheGet = __commonJS({
"../../node_modules/.pnpm/lodash@4.17.21/node_modules/lodash/_listCacheGet.js"(exports, module) {
init_process();
var assocIndexOf = require_assocIndexOf();
function listCacheGet(key) {
var data = this.__data__, index = assocIndexOf(data, key);
return index < 0 ? void 0 : data[index][1];
}
module.exports = listCacheGet;
}
});
// ../../node_modules/.pnpm/lodash@4.17.21/node_modules/lodash/_listCacheHas.js
var require_listCacheHas = __commonJS({
"../../node_modules/.pnpm/lodash@4.17.21/node_modules/lodash/_listCacheHas.js"(exports, module) {
init_process();
var assocIndexOf = require_assocIndexOf();
function listCacheHas(key) {
return assocIndexOf(this.__data__, key) > -1;
}
module.exports = listCacheHas;
}
});
// ../../node_modules/.pnpm/lodash@4.17.21/node_modules/lodash/_listCacheSet.js
var require_listCacheSet = __commonJS({
"../../node_modules/.pnpm/lodash@4.17.21/node_modules/lodash/_listCacheSet.js"(exports, module) {
init_process();
var assocIndexOf = require_assocIndexOf();
function listCacheSet(key, value) {
var data = this.__data__, index = assocIndexOf(data, key);
if (index < 0) {
++this.size;
data.push([key, value]);
} else {
data[index][1] = value;
}
return this;
}
module.exports = listCacheSet;
}
});
// ../../node_modules/.pnpm/lodash@4.17.21/node_modules/lodash/_ListCache.js
var require_ListCache = __commonJS({
"../../node_modules/.pnpm/lodash@4.17.21/node_modules/lodash/_ListCache.js"(exports, module) {
init_process();
var listCacheClear = require_listCacheClear();
var listCacheDelete = require_listCacheDelete();
var listCacheGet = require_listCacheGet();
var listCacheHas = require_listCacheHas();
var listCacheSet = require_listCacheSet();
function ListCache(entries) {
var index = -1, length = entries == null ? 0 : entries.length;
this.clear();
while (++index < length) {
var entry = entries[index];
this.set(entry[0], entry[1]);
}
}
ListCache.prototype.clear = listCacheClear;
ListCache.prototype["delete"] = listCacheDelete;
ListCache.prototype.get = listCacheGet;
ListCache.prototype.has = listCacheHas;
ListCache.prototype.set = listCacheSet;
module.exports = ListCache;
}
});
// ../../node_modules/.pnpm/lodash@4.17.21/node_modules/lodash/_stackClear.js
var require_stackClear = __commonJS({
"../../node_modules/.pnpm/lodash@4.17.21/node_modules/lodash/_stackClear.js"(exports, module) {
init_process();
var ListCache = require_ListCache();
function stackClear() {
this.__data__ = new ListCache();
this.size = 0;
}
module.exports = stackClear;
}
});
// ../../node_modules/.pnpm/lodash@4.17.21/node_modules/lodash/_stackDelete.js
var require_stackDelete = __commonJS({
"../../node_modules/.pnpm/lodash@4.17.21/node_modules/lodash/_stackDelete.js"(exports, module) {
init_process();
function stackDelete(key) {
var data = this.__data__, result2 = data["delete"](key);
this.size = data.size;
return result2;
}
module.exports = stackDelete;
}
});
// ../../node_modules/.pnpm/lodash@4.17.21/node_modules/lodash/_stackGet.js
var require_stackGet = __commonJS({
"../../node_modules/.pnpm/lodash@4.17.21/node_modules/lodash/_stackGet.js"(exports, module) {
init_process();
function stackGet(key) {
return this.__data__.get(key);
}
module.exports = stackGet;
}
});
// ../../node_modules/.pnpm/lodash@4.17.21/node_modules/lodash/_stackHas.js
var require_stackHas = __commonJS({
"../../node_modules/.pnpm/lodash@4.17.21/node_modules/lodash/_stackHas.js"(exports, module) {
init_process();
function stackHas(key) {
return this.__data__.has(key);
}
module.exports = stackHas;
}
});
// ../../node_modules/.pnpm/lodash@4.17.21/node_modules/lodash/_freeGlobal.js
var require_freeGlobal = __commonJS({
"../../node_modules/.pnpm/lodash@4.17.21/node_modules/lodash/_freeGlobal.js"(exports, module) {
init_process();
var freeGlobal = typeof global == "object" && global && global.Object === Object && global;
module.exports = freeGlobal;
}
});
// ../../node_modules/.pnpm/lodash@4.17.21/node_modules/lodash/_root.js
var require_root = __commonJS({
"../../node_modules/.pnpm/lodash@4.17.21/node_modules/lodash/_root.js"(exports, module) {
init_process();
var freeGlobal = require_freeGlobal();
var freeSelf = typeof self == "object" && self && self.Object === Object && self;
var root = freeGlobal || freeSelf || Function("return this")();
module.exports = root;
}
});
// ../../node_modules/.pnpm/lodash@4.17.21/node_modules/lodash/_Symbol.js
var require_Symbol = __commonJS({
"../../node_modules/.pnpm/lodash@4.17.21/node_modules/lodash/_Symbol.js"(exports, module) {
init_process();
var root = require_root();
var Symbol2 = root.Symbol;
module.exports = Symbol2;
}
});
// ../../node_modules/.pnpm/lodash@4.17.21/node_modules/lodash/_getRawTag.js
var require_getRawTag = __commonJS({
"../../node_modules/.pnpm/lodash@4.17.21/node_modules/lodash/_getRawTag.js"(exports, module) {
init_process();
var Symbol2 = require_Symbol();
var objectProto = Object.prototype;
var hasOwnProperty2 = objectProto.hasOwnProperty;
var nativeObjectToString = objectProto.toString;
var symToStringTag = Symbol2 ? Symbol2.toStringTag : void 0;
function getRawTag(value) {
var isOwn = hasOwnProperty2.call(value, symToStringTag), tag = value[symToStringTag];
try {
value[symToStringTag] = void 0;
var unmasked = true;
} catch (e2) {
}
var result2 = nativeObjectToString.call(value);
if (unmasked) {
if (isOwn) {
value[symToStringTag] = tag;
} else {
delete value[symToStringTag];
}
}
return result2;
}
module.exports = getRawTag;
}
});
// ../../node_modules/.pnpm/lodash@4.17.21/node_modules/lodash/_objectToString.js
var require_objectToString = __commonJS({
"../../node_modules/.pnpm/lodash@4.17.21/node_modules/lodash/_objectToString.js"(exports, module) {
init_process();
var objectProto = Object.prototype;
var nativeObjectToString = objectProto.toString;
function objectToString(value) {
return nativeObjectToString.call(value);
}
module.exports = objectToString;
}
});
// ../../node_modules/.pnpm/lodash@4.17.21/node_modules/lodash/_baseGetTag.js
var require_baseGetTag = __commonJS({
"../../node_modules/.pnpm/lodash@4.17.21/node_modules/lodash/_baseGetTag.js"(exports, module) {
init_process();
var Symbol2 = require_Symbol();
var getRawTag = require_getRawTag();
var objectToString = require_objectToString();
var nullTag = "[object Null]";
var undefinedTag = "[object Undefined]";
var symToStringTag = Symbol2 ? Symbol2.toStringTag : void 0;
function baseGetTag(value) {
if (value == null) {
return value === void 0 ? undefinedTag : nullTag;
}
return symToStringTag && symToStringTag in Object(value) ? getRawTag(value) : objectToString(value);
}
module.exports = baseGetTag;
}
});
// ../../node_modules/.pnpm/lodash@4.17.21/node_modules/lodash/isObject.js
var require_isObject = __commonJS({
"../../node_modules/.pnpm/lodash@4.17.21/node_modules/lodash/isObject.js"(exports, module) {
init_process();
function isObject2(value) {
var type = typeof value;
return value != null && (type == "object" || type == "function");
}
module.exports = isObject2;
}
});
// ../../node_modules/.pnpm/lodash@4.17.21/node_modules/lodash/isFunction.js
var require_isFunction = __commonJS({
"../../node_modules/.pnpm/lodash@4.17.21/node_modules/lodash/isFunction.js"(exports, module) {
init_process();
var baseGetTag = require_baseGetTag();
var isObject2 = require_isObject();
var asyncTag = "[object AsyncFunction]";
var funcTag = "[object Function]";
var genTag = "[object GeneratorFunction]";
var proxyTag = "[object Proxy]";
function isFunction3(value) {
if (!isObject2(value)) {
return false;
}
var tag = baseGetTag(value);
return tag == funcTag || tag == genTag || tag == asyncTag || tag == proxyTag;
}
module.exports = isFunction3;
}
});
// ../../node_modules/.pnpm/lodash@4.17.21/node_modules/lodash/_coreJsData.js
var require_coreJsData = __commonJS({
"../../node_modules/.pnpm/lodash@4.17.21/node_modules/lodash/_coreJsData.js"(exports, module) {
init_process();
var root = require_root();
var coreJsData = root["__core-js_shared__"];
module.exports = coreJsData;
}
});
// ../../node_modules/.pnpm/lodash@4.17.21/node_modules/lodash/_isMasked.js
var require_isMasked = __commonJS({
"../../node_modules/.pnpm/lodash@4.17.21/node_modules/lodash/_isMasked.js"(exports, module) {
init_process();
var coreJsData = require_coreJsData();
var maskSrcKey = (function() {
var uid = /[^.]+$/.exec(coreJsData && coreJsData.keys && coreJsData.keys.IE_PROTO || "");
return uid ? "Symbol(src)_1." + uid : "";
})();
function isMasked(func) {
return !!maskSrcKey && maskSrcKey in func;
}
module.exports = isMasked;
}
});
// ../../node_modules/.pnpm/lodash@4.17.21/node_modules/lodash/_toSource.js
var require_toSource = __commonJS({
"../../node_modules/.pnpm/lodash@4.17.21/node_modules/lodash/_toSource.js"(exports, module) {
init_process();
var funcProto = Function.prototype;
var funcToString = funcProto.toString;
function toSource(func) {
if (func != null) {
try {
return funcToString.call(func);
} catch (e2) {
}
try {
return func + "";
} catch (e2) {
}
}
return "";
}
module.exports = toSource;
}
});
// ../../node_modules/.pnpm/lodash@4.17.21/node_modules/lodash/_baseIsNative.js
var require_baseIsNative = __commonJS({
"../../node_modules/.pnpm/lodash@4.17.21/node_modules/lodash/_baseIsNative.js"(exports, module) {
init_process();
var isFunction3 = require_isFunction();
var isMasked = require_isMasked();
var isObject2 = require_isObject();
var toSource = require_toSource();
var reRegExpChar = /[\\^$.*+?()[\]{}|]/g;
var reIsHostCtor = /^\[object .+?Constructor\]$/;
var funcProto = Function.prototype;
var objectProto = Object.prototype;
var funcToString = funcProto.toString;
var hasOwnProperty2 = objectProto.hasOwnProperty;
var reIsNative = RegExp(
"^" + funcToString.call(hasOwnProperty2).replace(reRegExpChar, "\\$&").replace(/hasOwnProperty|(function).*?(?=\\\()| for .+?(?=\\\])/g, "$1.*?") + "$"
);
function baseIsNative(value) {
if (!isObject2(value) || isMasked(value)) {
return false;
}
var pattern = isFunction3(value) ? reIsNative : reIsHostCtor;
return pattern.test(toSource(value));
}
module.exports = baseIsNative;
}
});
// ../../node_modules/.pnpm/lodash@4.17.21/node_modules/lodash/_getValue.js
var require_getValue = __commonJS({
"../../node_modules/.pnpm/lodash@4.17.21/node_modules/lodash/_getValue.js"(exports, module) {
init_process();
function getValue(object, key) {
return object == null ? void 0 : object[key];
}
module.exports = getValue;
}
});
// ../../node_modules/.pnpm/lodash@4.17.21/node_modules/lodash/_getNative.js
var require_getNative = __commonJS({
"../../node_modules/.pnpm/lodash@4.17.21/node_modules/lodash/_getNative.js"(exports, module) {
init_process();
var baseIsNative = require_baseIsNative();
var getValue = require_getValue();
function getNative(object, key) {
var value = getValue(object, key);
return baseIsNative(value) ? value : void 0;
}
module.exports = getNative;
}
});
// ../../node_modules/.pnpm/lodash@4.17.21/node_modules/lodash/_Map.js
var require_Map = __commonJS({
"../../node_modules/.pnpm/lodash@4.17.21/node_modules/lodash/_Map.js"(exports, module) {
init_process();
var getNative = require_getNative();
var root = require_root();
var Map2 = getNative(root, "Map");
module.exports = Map2;
}
});
// ../../node_modules/.pnpm/lodash@4.17.21/node_modules/lodash/_nativeCreate.js
var require_nativeCreate = __commonJS({
"../../node_modules/.pnpm/lodash@4.17.21/node_modules/lodash/_nativeCreate.js"(exports, module) {
init_process();
var getNative = require_getNative();
var nativeCreate = getNative(Object, "create");
module.exports = nativeCreate;
}
});
// ../../node_modules/.pnpm/lodash@4.17.21/node_modules/lodash/_hashClear.js
var require_hashClear = __commonJS({
"../../node_modules/.pnpm/lodash@4.17.21/node_modules/lodash/_hashClear.js"(exports, module) {
init_process();
var nativeCreate = require_nativeCreate();
function hashClear() {
this.__data__ = nativeCreate ? nativeCreate(null) : {};
this.size = 0;
}
module.exports = hashClear;
}
});
// ../../node_modules/.pnpm/lodash@4.17.21/node_modules/lodash/_hashDelete.js
var require_hashDelete = __commonJS({
"../../node_modules/.pnpm/lodash@4.17.21/node_modules/lodash/_hashDelete.js"(exports, module) {
init_process();
function hashDelete(key) {
var result2 = this.has(key) && delete this.__data__[key];
this.size -= result2 ? 1 : 0;
return result2;
}
module.exports = hashDelete;
}
});
// ../../node_modules/.pnpm/lodash@4.17.21/node_modules/lodash/_hashGet.js
var require_hashGet = __commonJS({
"../../node_modules/.pnpm/lodash@4.17.21/node_modules/lodash/_hashGet.js"(exports, module) {
init_process();
var nativeCreate = require_nativeCreate();
var HASH_UNDEFINED = "__lodash_hash_undefined__";
var objectProto = Object.prototype;
var hasOwnProperty2 = objectProto.hasOwnProperty;
function hashGet(key) {
var data = this.__data__;
if (nativeCreate) {
var result2 = data[key];
return result2 === HASH_UNDEFINED ? void 0 : result2;
}
return hasOwnProperty2.call(data, key) ? data[key] : void 0;
}
module.exports = hashGet;
}
});
// ../../node_modules/.pnpm/lodash@4.17.21/node_modules/lodash/_hashHas.js
var require_hashHas = __commonJS({
"../../node_modules/.pnpm/lodash@4.17.21/node_modules/lodash/_hashHas.js"(exports, module) {
init_process();
var nativeCreate = require_nativeCreate();
var objectProto = Object.prototype;
var hasOwnProperty2 = objectProto.hasOwnProperty;
function hashHas(key) {
var data = this.__data__;
return nativeCreate ? data[key] !== void 0 : hasOwnProperty2.call(data, key);
}
module.exports = hashHas;
}
});
// ../../node_modules/.pnpm/lodash@4.17.21/node_modules/lodash/_hashSet.js
var require_hashSet = __commonJS({
"../../node_modules/.pnpm/lodash@4.17.21/node_modules/lodash/_hashSet.js"(exports, module) {
init_process();
var nativeCreate = require_nativeCreate();
var HASH_UNDEFINED = "__lodash_hash_undefined__";
function hashSet(key, value) {
var data = this.__data__;
this.size += this.has(key) ? 0 : 1;
data[key] = nativeCreate && value === void 0 ? HASH_UNDEFINED : value;
return this;
}
module.exports = hashSet;
}
});
// ../../node_modules/.pnpm/lodash@4.17.21/node_modules/lodash/_Hash.js
var require_Hash = __commonJS({
"../../node_modules/.pnpm/lodash@4.17.21/node_modules/lodash/_Hash.js"(exports, module) {
init_process();
var hashClear = require_hashClear();
var hashDelete = require_hashDelete();
var hashGet = require_hashGet();
var hashHas = require_hashHas();
var hashSet = require_hashSet();
function Hash(entries) {
var index = -1, length = entries == null ? 0 : entries.length;
this.clear();
while (++index < length) {
var entry = entries[index];
this.set(entry[0], entry[1]);
}
}
Hash.prototype.clear = hashClear;
Hash.prototype["delete"] = hashDelete;
Hash.prototype.get = hashGet;
Hash.prototype.has = hashHas;
Hash.prototype.set = hashSet;
module.exports = Hash;
}
});
// ../../node_modules/.pnpm/lodash@4.17.21/node_modules/lodash/_mapCacheClear.js
var require_mapCacheClear = __commonJS({
"../../node_modules/.pnpm/lodash@4.17.21/node_modules/lodash/_mapCacheClear.js"(exports, module) {
init_process();
var Hash = require_Hash();
var ListCache = require_ListCache();
var Map2 = require_Map();
function mapCacheClear() {
this.size = 0;
this.__data__ = {
"hash": new Hash(),
"map": new (Map2 || ListCache)(),
"string": new Hash()
};
}
module.exports = mapCacheClear;
}
});
// ../../node_modules/.pnpm/lodash@4.17.21/node_modules/lodash/_isKeyable.js
var require_isKeyable = __commonJS({
"../../node_modules/.pnpm/lodash@4.17.21/node_modules/lodash/_isKeyable.js"(exports, module) {
init_process();
function isKeyable(value) {
var type = typeof value;
return type == "string" || type == "number" || type == "symbol" || type == "boolean" ? value !== "__proto__" : value === null;
}
module.exports = isKeyable;
}
});
// ../../node_modules/.pnpm/lodash@4.17.21/node_modules/lodash/_getMapData.js
var require_getMapData = __commonJS({
"../../node_modules/.pnpm/lodash@4.17.21/node_modules/lodash/_getMapData.js"(exports, module) {
init_process();
var isKeyable = require_isKeyable();
function getMapData(map, key) {
var data = map.__data__;
return isKeyable(key) ? data[typeof key == "string" ? "string" : "hash"] : data.map;
}
module.exports = getMapData;
}
});
// ../../node_modules/.pnpm/lodash@4.17.21/node_modules/lodash/_mapCacheDelete.js
var require_mapCacheDelete = __commonJS({
"../../node_modules/.pnpm/lodash@4.17.21/node_modules/lodash/_mapCacheDelete.js"(exports, module) {
init_process();
var getMapData = require_getMapData();
function mapCacheDelete(key) {
var result2 = getMapData(this, key)["delete"](key);
this.size -= result2 ? 1 : 0;
return result2;
}
module.exports = mapCacheDelete;
}
});
// ../../node_modules/.pnpm/lodash@4.17.21/node_modules/lodash/_mapCacheGet.js
var require_mapCacheGet = __commonJS({
"../../node_modules/.pnpm/lodash@4.17.21/node_modules/lodash/_mapCacheGet.js"(exports, module) {
init_process();
var getMapData = require_getMapData();
function mapCacheGet(key) {
return getMapData(this, key).get(key);
}
module.exports = mapCacheGet;
}
});
// ../../node_modules/.pnpm/lodash@4.17.21/node_modules/lodash/_mapCacheHas.js
var require_mapCacheHas = __commonJS({
"../../node_modules/.pnpm/lodash@4.17.21/node_modules/lodash/_mapCacheHas.js"(exports, module) {
init_process();
var getMapData = require_getMapData();
function mapCacheHas(key) {
return getMapData(this, key).has(key);
}
module.exports = mapCacheHas;
}
});
// ../../node_modules/.pnpm/lodash@4.17.21/node_modules/lodash/_mapCacheSet.js
var require_mapCacheSet = __commonJS({
"../../node_modules/.pnpm/lodash@4.17.21/node_modules/lodash/_mapCacheSet.js"(exports, module) {
init_process();
var getMapData = require_getMapData();
function mapCacheSet(key, value) {
var data = getMapData(this, key), size = data.size;
data.set(key, value);
this.size += data.size == size ? 0 : 1;
return this;
}
module.exports = mapCacheSet;
}
});
// ../../node_modules/.pnpm/lodash@4.17.21/node_modules/lodash/_MapCache.js
var require_MapCache = __commonJS({
"../../node_modules/.pnpm/lodash@4.17.21/node_modules/lodash/_MapCache.js"(exports, module) {
init_process();
var mapCacheClear = require_mapCacheClear();
var mapCacheDelete = require_mapCacheDelete();
var mapCacheGet = require_mapCacheGet();
var mapCacheHas = require_mapCacheHas();
var mapCacheSet = require_mapCacheSet();
function MapCache(entries) {
var index = -1, length = entries == null ? 0 : entries.length;
this.clear();
while (++index < length) {
var entry = entries[index];
this.set(entry[0], entry[1]);
}
}
MapCache.prototype.clear = mapCacheClear;
MapCache.prototype["delete"] = mapCacheDelete;
MapCache.prototype.get = mapCacheGet;
MapCache.prototype.has = mapCacheHas;
MapCache.prototype.set = mapCacheSet;
module.exports = MapCache;
}
});
// ../../node_modules/.pnpm/lodash@4.17.21/node_modules/lodash/_stackSet.js
var require_stackSet = __commonJS({
"../../node_modules/.pnpm/lodash@4.17.21/node_modules/lodash/_stackSet.js"(exports, module) {
init_process();
var ListCache = require_ListCache();
var Map2 = require_Map();
var MapCache = require_MapCache();
var LARGE_ARRAY_SIZE = 200;
function stackSet(key, value) {
var data = this.__data__;
if (data instanceof ListCache) {
var pairs = data.__data__;
if (!Map2 || pairs.length < LARGE_ARRAY_SIZE - 1) {
pairs.push([key, value]);
this.size = ++data.size;
return this;
}
data = this.__data__ = new MapCache(pairs);
}
data.set(key, value);
this.size = data.size;
return this;
}
module.exports = stackSet;
}
});
// ../../node_modules/.pnpm/lodash@4.17.21/node_modules/lodash/_Stack.js
var require_Stack = __commonJS({
"../../node_modules/.pnpm/lodash@4.17.21/node_modules/lodash/_Stack.js"(exports, module) {
init_process();
var ListCache = require_ListCache();
var stackClear = require_stackClear();
var stackDelete = require_stackDelete();
var stackGet = require_stackGet();
var stackHas = require_stackHas();
var stackSet = require_stackSet();
function Stack(entries) {
var data = this.__data__ = new ListCache(entries);
this.size = data.size;
}
Stack.prototype.clear = stackClear;
Stack.prototype["delete"] = stackDelete;
Stack.prototype.get = stackGet;
Stack.prototype.has = stackHas;
Stack.prototype.set = stackSet;
module.exports = Stack;
}
});
// ../../node_modules/.pnpm/lodash@4.17.21/node_modules/lodash/_setCacheAdd.js
var require_setCacheAdd = __commonJS({
"../../node_modules/.pnpm/lodash@4.17.21/node_modules/lodash/_setCacheAdd.js"(exports, module) {
init_process();
var HASH_UNDEFINED = "__lodash_hash_undefined__";
function setCacheAdd(value) {
this.__data__.set(value, HASH_UNDEFINED);
return this;
}
module.exports = setCacheAdd;
}
});
// ../../node_modules/.pnpm/lodash@4.17.21/node_modules/lodash/_setCacheHas.js
var require_setCacheHas = __commonJS({
"../../node_modules/.pnpm/lodash@4.17.21/node_modules/lodash/_setCacheHas.js"(exports, module) {
init_process();
function setCacheHas(value) {
return this.__data__.has(value);
}
module.exports = setCacheHas;
}
});
// ../../node_modules/.pnpm/lodash@4.17.21/node_modules/lodash/_SetCache.js
var require_SetCache = __commonJS({
"../../node_modules/.pnpm/lodash@4.17.21/node_modules/lodash/_SetCache.js"(exports, module) {
init_process();
var MapCache = require_MapCache();
var setCacheAdd = require_setCacheAdd();
var setCacheHas = require_setCacheHas();
function SetCache(values) {
var index = -1, length = values == null ? 0 : values.length;
this.__data__ = new MapCache();
while (++index < length) {
this.add(values[index]);
}
}
SetCache.prototype.add = SetCache.prototype.push = setCacheAdd;
SetCache.prototype.has = setCacheHas;
module.exports = SetCache;
}
});
// ../../node_modules/.pnpm/lodash@4.17.21/node_modules/lodash/_arraySome.js
var require_arraySome = __commonJS({
"../../node_modules/.pnpm/lodash@4.17.21/node_modules/lodash/_arraySome.js"(exports, module) {
init_process();
function arraySome(array, predicate) {
var index = -1, length = array == null ? 0 : array.length;
while (++index < length) {
if (predicate(array[index], index, array)) {
return true;
}
}
return false;
}
module.exports = arraySome;
}
});
// ../../node_modules/.pnpm/lodash@4.17.21/node_modules/lodash/_cacheHas.js
var require_cacheHas = __commonJS({
"../../node_modules/.pnpm/lodash@4.17.21/node_modules/lodash/_cacheHas.js"(exports, module) {
init_process();
function cacheHas(cache, key) {
return cache.has(key);
}
module.exports = cacheHas;
}
});
// ../../node_modules/.pnpm/lodash@4.17.21/node_modules/lodash/_equalArrays.js
var require_equalArrays = __commonJS({
"../../node_modules/.pnpm/lodash@4.17.21/node_modules/lodash/_equalArrays.js"(exports, module) {
init_process();
var SetCache = require_SetCache();
var arraySome = require_arraySome();
var cacheHas = require_cacheHas();
var COMPARE_PARTIAL_FLAG = 1;
var COMPARE_UNORDERED_FLAG = 2;
function equalArrays(array, other, bitmask, customizer, equalFunc, stack) {
var isPartial = bitmask & COMPARE_PARTIAL_FLAG, arrLength = array.length, othLength = other.length;
if (arrLength != othLength && !(isPartial && othLength > arrLength)) {
return false;
}
var arrStacked = stack.get(array);
var othStacked = stack.get(other);
if (arrStacked && othStacked) {
return arrStacked == other && othStacked == array;
}
var index = -1, result2 = true, seen = bitmask & COMPARE_UNORDERED_FLAG ? new SetCache() : void 0;
stack.set(array, other);
stack.set(other, array);
while (++index < arrLength) {
var arrValue = array[index], othValue = other[index];
if (customizer) {
var compared = isPartial ? customizer(othValue, arrValue, index, other, array, stack) : customizer(arrValue, othValue, index, array, other, stack);
}
if (compared !== void 0) {
if (compared) {
continue;
}
result2 = false;
break;
}
if (seen) {
if (!arraySome(other, function(othValue2, othIndex) {
if (!cacheHas(seen, othIndex) && (arrValue === othValue2 || equalFunc(arrValue, othValue2, bitmask, customizer, stack))) {
return seen.push(othIndex);
}
})) {
result2 = false;
break;
}
} else if (!(arrValue === othValue || equalFunc(arrValue, othValue, bitmask, customizer, stack))) {
result2 = false;
break;
}
}
stack["delete"](array);
stack["delete"](other);
return result2;
}
module.exports = equalArrays;
}
});
// ../../node_modules/.pnpm/lodash@4.17.21/node_modules/lodash/_Uint8Array.js
var require_Uint8Array = __commonJS({
"../../node_modules/.pnpm/lodash@4.17.21/node_modules/lodash/_Uint8Array.js"(exports, module) {
init_process();
var root = require_root();
var Uint8Array2 = root.Uint8Array;
module.exports = Uint8Array2;
}
});
// ../../node_modules/.pnpm/lodash@4.17.21/node_modules/lodash/_mapToArray.js
var require_mapToArray = __commonJS({
"../../node_modules/.pnpm/lodash@4.17.21/node_modules/lodash/_mapToArray.js"(exports, module) {
init_process();
function mapToArray(map) {
var index = -1, result2 = Array(map.size);
map.forEach(function(value, key) {
result2[++index] = [key, value];
});
return result2;
}
module.exports = mapToArray;
}
});
// ../../node_modules/.pnpm/lodash@4.17.21/node_modules/lodash/_setToArray.js
var require_setToArray = __commonJS({
"../../node_modules/.pnpm/lodash@4.17.21/node_modules/lodash/_setToArray.js"(exports, module) {
init_process();
function setToArray(set) {
var index = -1, result2 = Array(set.size);
set.forEach(function(value) {
result2[++index] = value;
});
return result2;
}
module.exports = setToArray;
}
});
// ../../node_modules/.pnpm/lodash@4.17.21/node_modules/lodash/_equalByTag.js
var require_equalByTag = __commonJS({
"../../node_modules/.pnpm/lodash@4.17.21/node_modules/lodash/_equalByTag.js"(exports, module) {
init_process();
var Symbol2 = require_Symbol();
var Uint8Array2 = require_Uint8Array();
var eq = require_eq();
var equalArrays = require_equalArrays();
var mapToArray = require_mapToArray();
var setToArray = require_setToArray();
var COMPARE_PARTIAL_FLAG = 1;
var COMPARE_UNORDERED_FLAG = 2;
var boolTag = "[object Boolean]";
var dateTag = "[object Date]";
var errorTag = "[object Error]";
var mapTag = "[object Map]";
var numberTag = "[object Number]";
var regexpTag = "[object RegExp]";
var setTag = "[object Set]";
var stringTag = "[object String]";
var symbolTag = "[object Symbol]";
var arrayBufferTag = "[object ArrayBuffer]";
var dataViewTag = "[object DataView]";
var symbolProto = Symbol2 ? Symbol2.prototype : void 0;
var symbolValueOf = symbolProto ? symbolProto.valueOf : void 0;
function equalByTag(object, other, tag, bitmask, customizer, equalFunc, stack) {
switch (tag) {
case dataViewTag:
if (object.byteLength != other.byteLength || object.byteOffset != other.byteOffset) {
return false;
}
object = object.buffer;
other = other.buffer;
case arrayBufferTag:
if (object.byteLength != other.byteLength || !equalFunc(new Uint8Array2(object), new Uint8Array2(other))) {
return false;
}
return true;
case boolTag:
case dateTag:
case numberTag:
return eq(+object, +other);
case errorTag:
return object.name == other.name && object.message == other.message;
case regexpTag:
case stringTag:
return object == other + "";
case mapTag:
var convert = mapToArray;
case setTag:
var isPartial = bitmask & COMPARE_PARTIAL_FLAG;
convert || (convert = setToArray);
if (object.size != other.size && !isPartial) {
return false;
}
var stacked = stack.get(object);
if (stacked) {
return stacked == other;
}
bitmask |= COMPARE_UNORDERED_FLAG;
stack.set(object, other);
var result2 = equalArrays(convert(object), convert(other), bitmask, customizer, equalFunc, stack);
stack["delete"](object);
return result2;
case symbolTag:
if (symbolValueOf) {
return symbolValueOf.call(object) == symbolValueOf.call(other);
}
}
return false;
}
module.exports = equalByTag;
}
});
// ../../node_modules/.pnpm/lodash@4.17.21/node_modules/lodash/_arrayPush.js
var require_arrayPush = __commonJS({
"../../node_modules/.pnpm/lodash@4.17.21/node_modules/lodash/_arrayPush.js"(exports, module) {
init_process();
function arrayPush(array, values) {
var index = -1, length = values.length, offset = array.length;
while (++index < length) {
array[offset + index] = values[index];
}
return array;
}
module.exports = arrayPush;
}
});
// ../../node_modules/.pnpm/lodash@4.17.21/node_modules/lodash/isArray.js
var require_isArray = __commonJS({
"../../node_modules/.pnpm/lodash@4.17.21/node_modules/lodash/isArray.js"(exports, module) {
init_process();
var isArray2 = Array.isArray;
module.exports = isArray2;
}
});
// ../../node_modules/.pnpm/lodash@4.17.21/node_modules/lodash/_baseGetAllKeys.js
var require_baseGetAllKeys = __commonJS({
"../../node_modules/.pnpm/lodash@4.17.21/node_modules/lodash/_baseGetAllKeys.js"(exports, module) {
init_process();
var arrayPush = require_arrayPush();
var isArray2 = require_isArray();
function baseGetAllKeys(object, keysFunc, symbolsFunc) {
var result2 = keysFunc(object);
return isArray2(object) ? result2 : arrayPush(result2, symbolsFunc(object));
}
module.exports = baseGetAllKeys;
}
});
// ../../node_modules/.pnpm/lodash@4.17.21/node_modules/lodash/_arrayFilter.js
var require_arrayFilter = __commonJS({
"../../node_modules/.pnpm/lodash@4.17.21/node_modules/lodash/_arrayFilter.js"(exports, module) {
init_process();
function arrayFilter(array, predicate) {
var index = -1, length = array == null ? 0 : array.length, resIndex = 0, result2 = [];
while (++index < length) {
var value = array[index];
if (predicate(value, index, array)) {
result2[resIndex++] = value;
}
}
return result2;
}
module.exports = arrayFilter;
}
});
// ../../node_modules/.pnpm/lodash@4.17.21/node_modules/lodash/stubArray.js
var require_stubArray = __commonJS({
"../../node_modules/.pnpm/lodash@4.17.21/node_modules/lodash/stubArray.js"(exports, module) {
init_process();
function stubArray() {
return [];
}
module.exports = stubArray;
}
});
// ../../node_modules/.pnpm/lodash@4.17.21/node_modules/lodash/_getSymbols.js
var require_getSymbols = __commonJS({
"../../node_modules/.pnpm/lodash@4.17.21/node_modules/lodash/_getSymbols.js"(exports, module) {
init_process();
var arrayFilter = require_arrayFilter();
var stubArray = require_stubArray();
var objectProto = Object.prototype;
var propertyIsEnumerable = objectProto.propertyIsEnumerable;
var nativeGetSymbols = Object.getOwnPropertySymbols;
var getSymbols = !nativeGetSymbols ? stubArray : function(object) {
if (object == null) {
return [];
}
object = Object(object);
return arrayFilter(nativeGetSymbols(object), function(symbol) {
return propertyIsEnumerable.call(object, symbol);
});
};
module.exports = getSymbols;
}
});
// ../../node_modules/.pnpm/lodash@4.17.21/node_modules/lodash/_baseTimes.js
var require_baseTimes = __commonJS({
"../../node_modules/.pnpm/lodash@4.17.21/node_modules/lodash/_baseTimes.js"(exports, module) {
init_process();
function baseTimes(n2, iteratee) {
var index = -1, result2 = Array(n2);
while (++index < n2) {
result2[index] = iteratee(index);
}
return result2;
}
module.exports = baseTimes;
}
});
// ../../node_modules/.pnpm/lodash@4.17.21/node_modules/lodash/isObjectLike.js
var require_isObjectLike = __commonJS({
"../../node_modules/.pnpm/lodash@4.17.21/node_modules/lodash/isObjectLike.js"(exports, module) {
init_process();
function isObjectLike(value) {
return value != null && typeof value == "object";
}
module.exports = isObjectLike;
}
});
// ../../node_modules/.pnpm/lodash@4.17.21/node_modules/lodash/_baseIsArguments.js
var require_baseIsArguments = __commonJS({
"../../node_modules/.pnpm/lodash@4.17.21/node_modules/lodash/_baseIsArguments.js"(exports, module) {
init_process();
var baseGetTag = require_baseGetTag();
var isObjectLike = require_isObjectLike();
var argsTag = "[object Arguments]";
function baseIsArguments(value) {
return isObjectLike(value) && baseGetTag(value) == argsTag;
}
module.exports = baseIsArguments;
}
});
// ../../node_modules/.pnpm/lodash@4.17.21/node_modules/lodash/isArguments.js
var require_isArguments = __commonJS({
"../../node_modules/.pnpm/lodash@4.17.21/node_modules/lodash/isArguments.js"(exports, module) {
init_process();
var baseIsArguments = require_baseIsArguments();
var isObjectLike = require_isObjectLike();
var objectProto = Object.prototype;
var hasOwnProperty2 = objectProto.hasOwnProperty;
var propertyIsEnumerable = objectProto.propertyIsEnumerable;
var isArguments = baseIsArguments(/* @__PURE__ */ (function() {
return arguments;
})()) ? baseIsArguments : function(value) {
return isObjectLike(value) && hasOwnProperty2.call(value, "callee") && !propertyIsEnumerable.call(value, "callee");
};
module.exports = isArguments;
}
});
// ../../node_modules/.pnpm/lodash@4.17.21/node_modules/lodash/stubFalse.js
var require_stubFalse = __commonJS({
"../../node_modules/.pnpm/lodash@4.17.21/node_modules/lodash/stubFalse.js"(exports, module) {
init_process();
function stubFalse() {
return false;
}
module.exports = stubFalse;
}
});
// ../../node_modules/.pnpm/lodash@4.17.21/node_modules/lodash/isBuffer.js
var require_isBuffer = __commonJS({
"../../node_modules/.pnpm/lodash@4.17.21/node_modules/lodash/isBuffer.js"(exports, module) {
init_process();
var root = require_root();
var stubFalse = require_stubFalse();
var freeExports = typeof exports == "object" && exports && !exports.nodeType && exports;
var freeModule = freeExports && typeof module == "object" && module && !module.nodeType && module;
var moduleExports = freeModule && freeModule.exports === freeExports;
var Buffer2 = moduleExports ? root.Buffer : void 0;
var nativeIsBuffer = Buffer2 ? Buffer2.isBuffer : void 0;
var isBuffer2 = nativeIsBuffer || stubFalse;
module.exports = isBuffer2;
}
});
// ../../node_modules/.pnpm/lodash@4.17.21/node_modules/lodash/_isIndex.js
var require_isIndex = __commonJS({
"../../node_modules/.pnpm/lodash@4.17.21/node_modules/lodash/_isIndex.js"(exports, module) {
init_process();
var MAX_SAFE_INTEGER = 9007199254740991;
var reIsUint = /^(?:0|[1-9]\d*)$/;
function isIndex(value, length) {
var type = typeof value;
length = length == null ? MAX_SAFE_INTEGER : length;
return !!length && (type == "number" || type != "symbol" && reIsUint.test(value)) && (value > -1 && value % 1 == 0 && value < length);
}
module.exports = isIndex;
}
});
// ../../node_modules/.pnpm/lodash@4.17.21/node_modules/lodash/isLength.js
var require_isLength = __commonJS({
"../../node_modules/.pnpm/lodash@4.17.21/node_modules/lodash/isLength.js"(exports, module) {
init_process();
var MAX_SAFE_INTEGER = 9007199254740991;
function isLength(value) {
return typeof value == "number" && value > -1 && value % 1 == 0 && value <= MAX_SAFE_INTEGER;
}
module.exports = isLength;
}
});
// ../../node_modules/.pnpm/lodash@4.17.21/node_modules/lodash/_baseIsTypedArray.js
var require_baseIsTypedArray = __commonJS({
"../../node_modules/.pnpm/lodash@4.17.21/node_modules/lodash/_baseIsTypedArray.js"(exports, module) {
init_process();
var baseGetTag = require_baseGetTag();
var isLength = require_isLength();
var isObjectLike = require_isObjectLike();
var argsTag = "[object Arguments]";
var arrayTag = "[object Array]";
var boolTag = "[object Boolean]";
var dateTag = "[object Date]";
var errorTag = "[object Error]";
var funcTag = "[object Function]";
var mapTag = "[object Map]";
var numberTag = "[object Number]";
var objectTag = "[object Object]";
var regexpTag = "[object RegExp]";
var setTag = "[object Set]";
var stringTag = "[object String]";
var weakMapTag = "[object WeakMap]";
var arrayBufferTag = "[object ArrayBuffer]";
var dataViewTag = "[object DataView]";
var float32Tag = "[object Float32Array]";
var float64Tag = "[object Float64Array]";
var int8Tag = "[object Int8Array]";
var int16Tag = "[object Int16Array]";
var int32Tag = "[object Int32Array]";
var uint8Tag = "[object Uint8Array]";
var uint8ClampedTag = "[object Uint8ClampedArray]";
var uint16Tag = "[object Uint16Array]";
var uint32Tag = "[object Uint32Array]";
var typedArrayTags = {};
typedArrayTags[float32Tag] = typedArrayTags[float64Tag] = typedArrayTags[int8Tag] = typedArrayTags[int16Tag] = typedArrayTags[int32Tag] = typedArrayTags[uint8Tag] = typedArrayTags[uint8ClampedTag] = typedArrayTags[uint16Tag] = typedArrayTags[uint32Tag] = true;
typedArrayTags[argsTag] = typedArrayTags[arrayTag] = typedArrayTags[arrayBufferTag] = typedArrayTags[boolTag] = typedArrayTags[dataViewTag] = typedArrayTags[dateTag] = typedArrayTags[errorTag] = typedArrayTags[funcTag] = typedArrayTags[mapTag] = typedArrayTags[numberTag] = typedArrayTags[objectTag] = typedArrayTags[regexpTag] = typedArrayTags[setTag] = typedArrayTags[stringTag] = typedArrayTags[weakMapTag] = false;
function baseIsTypedArray(value) {
return isObjectLike(value) && isLength(value.length) && !!typedArrayTags[baseGetTag(value)];
}
module.exports = baseIsTypedArray;
}
});
// ../../node_modules/.pnpm/lodash@4.17.21/node_modules/lodash/_baseUnary.js
var require_baseUnary = __commonJS({
"../../node_modules/.pnpm/lodash@4.17.21/node_modules/lodash/_baseUnary.js"(exports, module) {
init_process();
function baseUnary(func) {
return function(value) {
return func(value);
};
}
module.exports = baseUnary;
}
});
// ../../node_modules/.pnpm/lodash@4.17.21/node_modules/lodash/_nodeUtil.js
var require_nodeUtil = __commonJS({
"../../node_modules/.pnpm/lodash@4.17.21/node_modules/lodash/_nodeUtil.js"(exports, module) {
init_process();
var freeGlobal = require_freeGlobal();
var freeExports = typeof exports == "object" && exports && !exports.nodeType && exports;
var freeModule = freeExports && typeof module == "object" && module && !module.nodeType && module;
var moduleExports = freeModule && freeModule.exports === freeExports;
var freeProcess = moduleExports && freeGlobal.process;
var nodeUtil = (function() {
try {
var types = freeModule && freeModule.require && freeModule.require("util").types;
if (types) {
return types;
}
return freeProcess && freeProcess.binding && freeProcess.binding("util");
} catch (e2) {
}
})();
module.exports = nodeUtil;
}
});
// ../../node_modules/.pnpm/lodash@4.17.21/node_modules/lodash/isTypedArray.js
var require_isTypedArray = __commonJS({
"../../node_modules/.pnpm/lodash@4.17.21/node_modules/lodash/isTypedArray.js"(exports, module) {
init_process();
var baseIsTypedArray = require_baseIsTypedArray();
var baseUnary = require_baseUnary();
var nodeUtil = require_nodeUtil();
var nodeIsTypedArray = nodeUtil && nodeUtil.isTypedArray;
var isTypedArray2 = nodeIsTypedArray ? baseUnary(nodeIsTypedArray) : baseIsTypedArray;
module.exports = isTypedArray2;
}
});
// ../../node_modules/.pnpm/lodash@4.17.21/node_modules/lodash/_arrayLikeKeys.js
var require_arrayLikeKeys = __commonJS({
"../../node_modules/.pnpm/lodash@4.17.21/node_modules/lodash/_arrayLikeKeys.js"(exports, module) {
init_process();
var baseTimes = require_baseTimes();
var isArguments = require_isArguments();
var isArray2 = require_isArray();
var isBuffer2 = require_isBuffer();
var isIndex = require_isIndex();
var isTypedArray2 = require_isTypedArray();
var objectProto = Object.prototype;
var hasOwnProperty2 = objectProto.hasOwnProperty;
function arrayLikeKeys(value, inherited) {
var isArr = isArray2(value), isArg = !isArr && isArguments(value), isBuff = !isArr && !isArg && isBuffer2(value), isType = !isArr && !isArg && !isBuff && isTypedArray2(value), skipIndexes = isArr || isArg || isBuff || isType, result2 = skipIndexes ? baseTimes(value.length, String) : [], length = result2.length;
for (var key in value) {
if ((inherited || hasOwnProperty2.call(value, key)) && !(skipIndexes && // Safari 9 has enumerable `arguments.length` in strict mode.
(key == "length" || // Node.js 0.10 has enumerable non-index properties on buffers.
isBuff && (key == "offset" || key == "parent") || // PhantomJS 2 has enumerable non-index properties on typed arrays.
isType && (key == "buffer" || key == "byteLength" || key == "byteOffset") || // Skip index properties.
isIndex(key, length)))) {
result2.push(key);
}
}
return result2;
}
module.exports = arrayLikeKeys;
}
});
// ../../node_modules/.pnpm/lodash@4.17.21/node_modules/lodash/_isPrototype.js
var require_isPrototype = __commonJS({
"../../node_modules/.pnpm/lodash@4.17.21/node_modules/lodash/_isPrototype.js"(exports, module) {
init_process();
var objectProto = Object.prototype;
function isPrototype(value) {
var Ctor = value && value.constructor, proto = typeof Ctor == "function" && Ctor.prototype || objectProto;
return value === proto;
}
module.exports = isPrototype;
}
});
// ../../node_modules/.pnpm/lodash@4.17.21/node_modules/lodash/_overArg.js
var require_overArg = __commonJS({
"../../node_modules/.pnpm/lodash@4.17.21/node_modules/lodash/_overArg.js"(exports, module) {
init_process();
function overArg(func, transform) {
return function(arg) {
return func(transform(arg));
};
}
module.exports = overArg;
}
});
// ../../node_modules/.pnpm/lodash@4.17.21/node_modules/lodash/_nativeKeys.js
var require_nativeKeys = __commonJS({
"../../node_modules/.pnpm/lodash@4.17.21/node_modules/lodash/_nativeKeys.js"(exports, module) {
init_process();
var overArg = require_overArg();
var nativeKeys = overArg(Object.keys, Object);
module.exports = nativeKeys;
}
});
// ../../node_modules/.pnpm/lodash@4.17.21/node_modules/lodash/_baseKeys.js
var require_baseKeys = __commonJS({
"../../node_modules/.pnpm/lodash@4.17.21/node_modules/lodash/_baseKeys.js"(exports, module) {
init_process();
var isPrototype = require_isPrototype();
var nativeKeys = require_nativeKeys();
var objectProto = Object.prototype;
var hasOwnProperty2 = objectProto.hasOwnProperty;
function baseKeys(object) {
if (!isPrototype(object)) {
return nativeKeys(object);
}
var result2 = [];
for (var key in Object(object)) {
if (hasOwnProperty2.call(object, key) && key != "constructor") {
result2.push(key);
}
}
return result2;
}
module.exports = baseKeys;
}
});
// ../../node_modules/.pnpm/lodash@4.17.21/node_modules/lodash/isArrayLike.js
var require_isArrayLike = __commonJS({
"../../node_modules/.pnpm/lodash@4.17.21/node_modules/lodash/isArrayLike.js"(exports, module) {
init_process();
var isFunction3 = require_isFunction();
var isLength = require_isLength();
function isArrayLike(value) {
return value != null && isLength(value.length) && !isFunction3(value);
}
module.exports = isArrayLike;
}
});
// ../../node_modules/.pnpm/lodash@4.17.21/node_modules/lodash/keys.js
var require_keys = __commonJS({
"../../node_modules/.pnpm/lodash@4.17.21/node_modules/lodash/keys.js"(exports, module) {
init_process();
var arrayLikeKeys = require_arrayLikeKeys();
var baseKeys = require_baseKeys();
var isArrayLike = require_isArrayLike();
function keys(object) {
return isArrayLike(object) ? arrayLikeKeys(object) : baseKeys(object);
}
module.exports = keys;
}
});
// ../../node_modules/.pnpm/lodash@4.17.21/node_modules/lodash/_getAllKeys.js
var require_getAllKeys = __commonJS({
"../../node_modules/.pnpm/lodash@4.17.21/node_modules/lodash/_getAllKeys.js"(exports, module) {
init_process();
var baseGetAllKeys = require_baseGetAllKeys();
var getSymbols = require_getSymbols();
var keys = require_keys();
function getAllKeys(object) {
return baseGetAllKeys(object, keys, getSymbols);
}
module.exports = getAllKeys;
}
});
// ../../node_modules/.pnpm/lodash@4.17.21/node_modules/lodash/_equalObjects.js
var require_equalObjects = __commonJS({
"../../node_modules/.pnpm/lodash@4.17.21/node_modules/lodash/_equalObjects.js"(exports, module) {
init_process();
var getAllKeys = require_getAllKeys();
var COMPARE_PARTIAL_FLAG = 1;
var objectProto = Object.prototype;
var hasOwnProperty2 = objectProto.hasOwnProperty;
function equalObjects(object, other, bitmask, customizer, equalFunc, stack) {
var isPartial = bitmask & COMPARE_PARTIAL_FLAG, objProps = getAllKeys(object), objLength = objProps.length, othProps = getAllKeys(other), othLength = othProps.length;
if (objLength != othLength && !isPartial) {
return false;
}
var index = objLength;
while (index--) {
var key = objProps[index];
if (!(isPartial ? key in other : hasOwnProperty2.call(other, key))) {
return false;
}
}
var objStacked = stack.get(object);
var othStacked = stack.get(other);
if (objStacked && othStacked) {
return objStacked == other && othStacked == object;
}
var result2 = true;
stack.set(object, other);
stack.set(other, object);
var skipCtor = isPartial;
while (++index < objLength) {
key = objProps[index];
var objValue = object[key], othValue = other[key];
if (customizer) {
var compared = isPartial ? customizer(othValue, objValue, key, other, object, stack) : customizer(objValue, othValue, key, object, other, stack);
}
if (!(compared === void 0 ? objValue === othValue || equalFunc(objValue, othValue, bitmask, customizer, stack) : compared)) {
result2 = false;
break;
}
skipCtor || (skipCtor = key == "constructor");
}
if (result2 && !skipCtor) {
var objCtor = object.constructor, othCtor = other.constructor;
if (objCtor != othCtor && ("constructor" in object && "constructor" in other) && !(typeof objCtor == "function" && objCtor instanceof objCtor && typeof othCtor == "function" && othCtor instanceof othCtor)) {
result2 = false;
}
}
stack["delete"](object);
stack["delete"](other);
return result2;
}
module.exports = equalObjects;
}
});
// ../../node_modules/.pnpm/lodash@4.17.21/node_modules/lodash/_DataView.js
var require_DataView = __commonJS({
"../../node_modules/.pnpm/lodash@4.17.21/node_modules/lodash/_DataView.js"(exports, module) {
init_process();
var getNative = require_getNative();
var root = require_root();
var DataView2 = getNative(root, "DataView");
module.exports = DataView2;
}
});
// ../../node_modules/.pnpm/lodash@4.17.21/node_modules/lodash/_Promise.js
var require_Promise = __commonJS({
"../../node_modules/.pnpm/lodash@4.17.21/node_modules/lodash/_Promise.js"(exports, module) {
init_process();
var getNative = require_getNative();
var root = require_root();
var Promise2 = getNative(root, "Promise");
module.exports = Promise2;
}
});
// ../../node_modules/.pnpm/lodash@4.17.21/node_modules/lodash/_Set.js
var require_Set = __commonJS({
"../../node_modules/.pnpm/lodash@4.17.21/node_modules/lodash/_Set.js"(exports, module) {
init_process();
var getNative = require_getNative();
var root = require_root();
var Set2 = getNative(root, "Set");
module.exports = Set2;
}
});
// ../../node_modules/.pnpm/lodash@4.17.21/node_modules/lodash/_WeakMap.js
var require_WeakMap = __commonJS({
"../../node_modules/.pnpm/lodash@4.17.21/node_modules/lodash/_WeakMap.js"(exports, module) {
init_process();
var getNative = require_getNative();
var root = require_root();
var WeakMap2 = getNative(root, "WeakMap");
module.exports = WeakMap2;
}
});
// ../../node_modules/.pnpm/lodash@4.17.21/node_modules/lodash/_getTag.js
var require_getTag = __commonJS({
"../../node_modules/.pnpm/lodash@4.17.21/node_modules/lodash/_getTag.js"(exports, module) {
init_process();
var DataView2 = require_DataView();
var Map2 = require_Map();
var Promise2 = require_Promise();
var Set2 = require_Set();
var WeakMap2 = require_WeakMap();
var baseGetTag = require_baseGetTag();
var toSource = require_toSource();
var mapTag = "[object Map]";
var objectTag = "[object Object]";
var promiseTag = "[object Promise]";
var setTag = "[object Set]";
var weakMapTag = "[object WeakMap]";
var dataViewTag = "[object DataView]";
var dataViewCtorString = toSource(DataView2);
var mapCtorString = toSource(Map2);
var promiseCtorString = toSource(Promise2);
var setCtorString = toSource(Set2);
var weakMapCtorString = toSource(WeakMap2);
var getTag = baseGetTag;
if (DataView2 && getTag(new DataView2(new ArrayBuffer(1))) != dataViewTag || Map2 && getTag(new Map2()) != mapTag || Promise2 && getTag(Promise2.resolve()) != promiseTag || Set2 && getTag(new Set2()) != setTag || WeakMap2 && getTag(new WeakMap2()) != weakMapTag) {
getTag = function(value) {
var result2 = baseGetTag(value), Ctor = result2 == objectTag ? value.constructor : void 0, ctorString = Ctor ? toSource(Ctor) : "";
if (ctorString) {
switch (ctorString) {
case dataViewCtorString:
return dataViewTag;
case mapCtorString:
return mapTag;
case promiseCtorString:
return promiseTag;
case setCtorString:
return setTag;
case weakMapCtorString:
return weakMapTag;
}
}
return result2;
};
}
module.exports = getTag;
}
});
// ../../node_modules/.pnpm/lodash@4.17.21/node_modules/lodash/_baseIsEqualDeep.js
var require_baseIsEqualDeep = __commonJS({
"../../node_modules/.pnpm/lodash@4.17.21/node_modules/lodash/_baseIsEqualDeep.js"(exports, module) {
init_process();
var Stack = require_Stack();
var equalArrays = require_equalArrays();
var equalByTag = require_equalByTag();
var equalObjects = require_equalObjects();
var getTag = require_getTag();
var isArray2 = require_isArray();
var isBuffer2 = require_isBuffer();
var isTypedArray2 = require_isTypedArray();
var COMPARE_PARTIAL_FLAG = 1;
var argsTag = "[object Arguments]";
var arrayTag = "[object Array]";
var objectTag = "[object Object]";
var objectProto = Object.prototype;
var hasOwnProperty2 = objectProto.hasOwnProperty;
function baseIsEqualDeep(object, other, bitmask, customizer, equalFunc, stack) {
var objIsArr = isArray2(object), othIsArr = isArray2(other), objTag = objIsArr ? arrayTag : getTag(object), othTag = othIsArr ? arrayTag : getTag(other);
objTag = objTag == argsTag ? objectTag : objTag;
othTag = othTag == argsTag ? objectTag : othTag;
var objIsObj = objTag == objectTag, othIsObj = othTag == objectTag, isSameTag = objTag == othTag;
if (isSameTag && isBuffer2(object)) {
if (!isBuffer2(other)) {
return false;
}
objIsArr = true;
objIsObj = false;
}
if (isSameTag && !objIsObj) {
stack || (stack = new Stack());
return objIsArr || isTypedArray2(object) ? equalArrays(object, other, bitmask, customizer, equalFunc, stack) : equalByTag(object, other, objTag, bitmask, customizer, equalFunc, stack);
}
if (!(bitmask & COMPARE_PARTIAL_FLAG)) {
var objIsWrapped = objIsObj && hasOwnProperty2.call(object, "__wrapped__"), othIsWrapped = othIsObj && hasOwnProperty2.call(other, "__wrapped__");
if (objIsWrapped || othIsWrapped) {
var objUnwrapped = objIsWrapped ? object.value() : object, othUnwrapped = othIsWrapped ? other.value() : other;
stack || (stack = new Stack());
return equalFunc(objUnwrapped, othUnwrapped, bitmask, customizer, stack);
}
}
if (!isSameTag) {
return false;
}
stack || (stack = new Stack());
return equalObjects(object, other, bitmask, customizer, equalFunc, stack);
}
module.exports = baseIsEqualDeep;
}
});
// ../../node_modules/.pnpm/lodash@4.17.21/node_modules/lodash/_baseIsEqual.js
var require_baseIsEqual = __commonJS({
"../../node_modules/.pnpm/lodash@4.17.21/node_modules/lodash/_baseIsEqual.js"(exports, module) {
init_process();
var baseIsEqualDeep = require_baseIsEqualDeep();
var isObjectLike = require_isObjectLike();
function baseIsEqual(value, other, bitmask, customizer, stack) {
if (value === other) {
return true;
}
if (value == null || other == null || !isObjectLike(value) && !isObjectLike(other)) {
return value !== value && other !== other;
}
return baseIsEqualDeep(value, other, bitmask, customizer, baseIsEqual, stack);
}
module.exports = baseIsEqual;
}
});
// ../../node_modules/.pnpm/lodash@4.17.21/node_modules/lodash/isEqual.js
var require_isEqual = __commonJS({
"../../node_modules/.pnpm/lodash@4.17.21/node_modules/lodash/isEqual.js"(exports, module) {
init_process();
var baseIsEqual = require_baseIsEqual();
function isEqual3(value, other) {
return baseIsEqual(value, other);
}
module.exports = isEqual3;
}
});
// ../../node_modules/.pnpm/ms@2.1.3/node_modules/ms/index.js
var require_ms = __commonJS({
"../../node_modules/.pnpm/ms@2.1.3/node_modules/ms/index.js"(exports, module) {
init_process();
var s = 1e3;
var m = s * 60;
var h = m * 60;
var d = h * 24;
var w = d * 7;
var y = d * 365.25;
module.exports = function(val, options) {
options = options || {};
var type = typeof val;
if (type === "string" && val.length > 0) {
return parse3(val);
} else if (type === "number" && isFinite(val)) {
return options.long ? fmtLong(val) : fmtShort(val);
}
throw new Error(
"val is not a non-empty string or a valid number. val=" + JSON.stringify(val)
);
};
function parse3(str) {
str = String(str);
if (str.length > 100) {
return;
}
var match = /^(-?(?:\d+)?\.?\d+) *(milliseconds?|msecs?|ms|seconds?|secs?|s|minutes?|mins?|m|hours?|hrs?|h|days?|d|weeks?|w|years?|yrs?|y)?$/i.exec(
str
);
if (!match) {
return;
}
var n2 = parseFloat(match[1]);
var type = (match[2] || "ms").toLowerCase();
switch (type) {
case "years":
case "year":
case "yrs":
case "yr":
case "y":
return n2 * y;
case "weeks":
case "week":
case "w":
return n2 * w;
case "days":
case "day":
case "d":
return n2 * d;
case "hours":
case "hour":
case "hrs":
case "hr":
case "h":
return n2 * h;
case "minutes":
case "minute":
case "mins":
case "min":
case "m":
return n2 * m;
case "seconds":
case "second":
case "secs":
case "sec":
case "s":
return n2 * s;
case "milliseconds":
case "millisecond":
case "msecs":
case "msec":
case "ms":
return n2;
default:
return void 0;
}
}
function fmtShort(ms) {
var msAbs = Math.abs(ms);
if (msAbs >= d) {
return Math.round(ms / d) + "d";
}
if (msAbs >= h) {
return Math.round(ms / h) + "h";
}
if (msAbs >= m) {
return Math.round(ms / m) + "m";
}
if (msAbs >= s) {
return Math.round(ms / s) + "s";
}
return ms + "ms";
}
function fmtLong(ms) {
var msAbs = Math.abs(ms);
if (msAbs >= d) {
return plural(ms, msAbs, d, "day");
}
if (msAbs >= h) {
return plural(ms, msAbs, h, "hour");
}
if (msAbs >= m) {
return plural(ms, msAbs, m, "minute");
}
if (msAbs >= s) {
return plural(ms, msAbs, s, "second");
}
return ms + " ms";
}
function plural(ms, msAbs, n2, name) {
var isPlural = msAbs >= n2 * 1.5;
return Math.round(ms / n2) + " " + name + (isPlural ? "s" : "");
}
}
});
// ../../node_modules/.pnpm/debug@4.4.3_supports-color@10.2.2/node_modules/debug/src/common.js
var require_common = __commonJS({
"../../node_modules/.pnpm/debug@4.4.3_supports-color@10.2.2/node_modules/debug/src/common.js"(exports, module) {
init_process();
function setup(env) {
createDebug.debug = createDebug;
createDebug.default = createDebug;
createDebug.coerce = coerce2;
createDebug.disable = disable;
createDebug.enable = enable;
createDebug.enabled = enabled;
createDebug.humanize = require_ms();
createDebug.destroy = destroy;
Object.keys(env).forEach((key) => {
createDebug[key] = env[key];
});
createDebug.names = [];
createDebug.skips = [];
createDebug.formatters = {};
function selectColor(namespace) {
let hash = 0;
for (let i = 0; i < namespace.length; i++) {
hash = (hash << 5) - hash + namespace.charCodeAt(i);
hash |= 0;
}
return createDebug.colors[Math.abs(hash) % createDebug.colors.length];
}
createDebug.selectColor = selectColor;
function createDebug(namespace) {
let prevTime;
let enableOverride = null;
let namespacesCache;
let enabledCache;
function debug(...args) {
if (!debug.enabled) {
return;
}
const self2 = debug;
const curr = Number(/* @__PURE__ */ new Date());
const ms = curr - (prevTime || curr);
self2.diff = ms;
self2.prev = prevTime;
self2.curr = curr;
prevTime = curr;
args[0] = createDebug.coerce(args[0]);
if (typeof args[0] !== "string") {
args.unshift("%O");
}
let index = 0;
args[0] = args[0].replace(/%([a-zA-Z%])/g, (match, format) => {
if (match === "%%") {
return "%";
}
index++;
const formatter = createDebug.formatters[format];
if (typeof formatter === "function") {
const val = args[index];
match = formatter.call(self2, val);
args.splice(index, 1);
index--;
}
return match;
});
createDebug.formatArgs.call(self2, args);
const logFn = self2.log || createDebug.log;
logFn.apply(self2, args);
}
debug.namespace = namespace;
debug.useColors = createDebug.useColors();
debug.color = createDebug.selectColor(namespace);
debug.extend = extend2;
debug.destroy = createDebug.destroy;
Object.defineProperty(debug, "enabled", {
enumerable: true,
configurable: false,
get: () => {
if (enableOverride !== null) {
return enableOverride;
}
if (namespacesCache !== createDebug.namespaces) {
namespacesCache = createDebug.namespaces;
enabledCache = createDebug.enabled(namespace);
}
return enabledCache;
},
set: (v) => {
enableOverride = v;
}
});
if (typeof createDebug.init === "function") {
createDebug.init(debug);
}
return debug;
}
function extend2(namespace, delimiter) {
const newDebug = createDebug(this.namespace + (typeof delimiter === "undefined" ? ":" : delimiter) + namespace);
newDebug.log = this.log;
return newDebug;
}
function enable(namespaces) {
createDebug.save(namespaces);
createDebug.namespaces = namespaces;
createDebug.names = [];
createDebug.skips = [];
const split = (typeof namespaces === "string" ? namespaces : "").trim().replace(/\s+/g, ",").split(",").filter(Boolean);
for (const ns of split) {
if (ns[0] === "-") {
createDebug.skips.push(ns.slice(1));
} else {
createDebug.names.push(ns);
}
}
}
function matchesTemplate(search, template) {
let searchIndex = 0;
let templateIndex = 0;
let starIndex = -1;
let matchIndex = 0;
while (searchIndex < search.length) {
if (templateIndex < template.length && (template[templateIndex] === search[searchIndex] || template[templateIndex] === "*")) {
if (template[templateIndex] === "*") {
starIndex = templateIndex;
matchIndex = searchIndex;
templateIndex++;
} else {
searchIndex++;
templateIndex++;
}
} else if (starIndex !== -1) {
templateIndex = starIndex + 1;
matchIndex++;
searchIndex = matchIndex;
} else {
return false;
}
}
while (templateIndex < template.length && template[templateIndex] === "*") {
templateIndex++;
}
return templateIndex === template.length;
}
function disable() {
const namespaces = [
...createDebug.names,
...createDebug.skips.map((namespace) => "-" + namespace)
].join(",");
createDebug.enable("");
return namespaces;
}
function enabled(name) {
for (const skip of createDebug.skips) {
if (matchesTemplate(name, skip)) {
return false;
}
}
for (const ns of createDebug.names) {
if (matchesTemplate(name, ns)) {
return true;
}
}
return false;
}
function coerce2(val) {
if (val instanceof Error) {
return val.stack || val.message;
}
return val;
}
function destroy() {
console.warn("Instance method `debug.destroy()` is deprecated and no longer does anything. It will be removed in the next major version of `debug`.");
}
createDebug.enable(createDebug.load());
return createDebug;
}
module.exports = setup;
}
});
// ../../node_modules/.pnpm/debug@4.4.3_supports-color@10.2.2/node_modules/debug/src/browser.js
var require_browser2 = __commonJS({
"../../node_modules/.pnpm/debug@4.4.3_supports-color@10.2.2/node_modules/debug/src/browser.js"(exports, module) {
init_process();
exports.formatArgs = formatArgs;
exports.save = save;
exports.load = load;
exports.useColors = useColors;
exports.storage = localstorage();
exports.destroy = /* @__PURE__ */ (() => {
let warned = false;
return () => {
if (!warned) {
warned = true;
console.warn("Instance method `debug.destroy()` is deprecated and no longer does anything. It will be removed in the next major version of `debug`.");
}
};
})();
exports.colors = [
"#0000CC",
"#0000FF",
"#0033CC",
"#0033FF",
"#0066CC",
"#0066FF",
"#0099CC",
"#0099FF",
"#00CC00",
"#00CC33",
"#00CC66",
"#00CC99",
"#00CCCC",
"#00CCFF",
"#3300CC",
"#3300FF",
"#3333CC",
"#3333FF",
"#3366CC",
"#3366FF",
"#3399CC",
"#3399FF",
"#33CC00",
"#33CC33",
"#33CC66",
"#33CC99",
"#33CCCC",
"#33CCFF",
"#6600CC",
"#6600FF",
"#6633CC",
"#6633FF",
"#66CC00",
"#66CC33",
"#9900CC",
"#9900FF",
"#9933CC",
"#9933FF",
"#99CC00",
"#99CC33",
"#CC0000",
"#CC0033",
"#CC0066",
"#CC0099",
"#CC00CC",
"#CC00FF",
"#CC3300",
"#CC3333",
"#CC3366",
"#CC3399",
"#CC33CC",
"#CC33FF",
"#CC6600",
"#CC6633",
"#CC9900",
"#CC9933",
"#CCCC00",
"#CCCC33",
"#FF0000",
"#FF0033",
"#FF0066",
"#FF0099",
"#FF00CC",
"#FF00FF",
"#FF3300",
"#FF3333",
"#FF3366",
"#FF3399",
"#FF33CC",
"#FF33FF",
"#FF6600",
"#FF6633",
"#FF9900",
"#FF9933",
"#FFCC00",
"#FFCC33"
];
function useColors() {
if (typeof window !== "undefined" && window.process && (window.process.type === "renderer" || window.process.__nwjs)) {
return true;
}
if (typeof navigator !== "undefined" && navigator.userAgent && navigator.userAgent.toLowerCase().match(/(edge|trident)\/(\d+)/)) {
return false;
}
let m;
return typeof document !== "undefined" && document.documentElement && document.documentElement.style && document.documentElement.style.WebkitAppearance || // Is firebug? http://stackoverflow.com/a/398120/376773
typeof window !== "undefined" && window.console && (window.console.firebug || window.console.exception && window.console.table) || // Is firefox >= v31?
// https://developer.mozilla.org/en-US/docs/Tools/Web_Console#Styling_messages
typeof navigator !== "undefined" && navigator.userAgent && (m = navigator.userAgent.toLowerCase().match(/firefox\/(\d+)/)) && parseInt(m[1], 10) >= 31 || // Double check webkit in userAgent just in case we are in a worker
typeof navigator !== "undefined" && navigator.userAgent && navigator.userAgent.toLowerCase().match(/applewebkit\/(\d+)/);
}
function formatArgs(args) {
args[0] = (this.useColors ? "%c" : "") + this.namespace + (this.useColors ? " %c" : " ") + args[0] + (this.useColors ? "%c " : " ") + "+" + module.exports.humanize(this.diff);
if (!this.useColors) {
return;
}
const c = "color: " + this.color;
args.splice(1, 0, c, "color: inherit");
let index = 0;
let lastC = 0;
args[0].replace(/%[a-zA-Z%]/g, (match) => {
if (match === "%%") {
return;
}
index++;
if (match === "%c") {
lastC = index;
}
});
args.splice(lastC, 0, c);
}
exports.log = console.debug || console.log || (() => {
});
function save(namespaces) {
try {
if (namespaces) {
exports.storage.setItem("debug", namespaces);
} else {
exports.storage.removeItem("debug");
}
} catch (error) {
}
}
function load() {
let r2;
try {
r2 = exports.storage.getItem("debug") || exports.storage.getItem("DEBUG");
} catch (error) {
}
if (!r2 && typeof process !== "undefined" && "env" in process) {
r2 = process.env.DEBUG;
}
return r2;
}
function localstorage() {
try {
return localStorage;
} catch (error) {
}
}
module.exports = require_common()(exports);
var { formatters } = module.exports;
formatters.j = function(v) {
try {
return JSON.stringify(v);
} catch (error) {
return "[UnexpectedJSONParseError]: " + error.message;
}
};
}
});
// ../../node_modules/.pnpm/mediasoup-client@3.18.3/node_modules/mediasoup-client/lib/types.js
var require_types = __commonJS({
"../../node_modules/.pnpm/mediasoup-client@3.18.3/node_modules/mediasoup-client/lib/types.js"(exports) {
"use strict";
init_process();
Object.defineProperty(exports, "__esModule", { value: true });
}
});
// ../../node_modules/.pnpm/mediasoup-client@3.18.3/node_modules/mediasoup-client/lib/Logger.js
var require_Logger = __commonJS({
"../../node_modules/.pnpm/mediasoup-client@3.18.3/node_modules/mediasoup-client/lib/Logger.js"(exports) {
"use strict";
init_process();
Object.defineProperty(exports, "__esModule", { value: true });
exports.Logger = void 0;
var debug_1 = require_browser2();
var APP_NAME = "mediasoup-client";
var Logger4 = class {
constructor(prefix) {
__publicField(this, "_debug");
__publicField(this, "_warn");
__publicField(this, "_error");
if (prefix) {
this._debug = (0, debug_1.default)(`${APP_NAME}:${prefix}`);
this._warn = (0, debug_1.default)(`${APP_NAME}:WARN:${prefix}`);
this._error = (0, debug_1.default)(`${APP_NAME}:ERROR:${prefix}`);
} else {
this._debug = (0, debug_1.default)(APP_NAME);
this._warn = (0, debug_1.default)(`${APP_NAME}:WARN`);
this._error = (0, debug_1.default)(`${APP_NAME}:ERROR`);
}
this._debug.log = console.info.bind(console);
this._warn.log = console.warn.bind(console);
this._error.log = console.error.bind(console);
}
get debug() {
return this._debug;
}
get warn() {
return this._warn;
}
get error() {
return this._error;
}
};
exports.Logger = Logger4;
}
});
// ../../node_modules/.pnpm/events@3.3.0/node_modules/events/events.js
var require_events = __commonJS({
"../../node_modules/.pnpm/events@3.3.0/node_modules/events/events.js"(exports, module) {
"use strict";
init_process();
var R = typeof Reflect === "object" ? Reflect : null;
var ReflectApply = R && typeof R.apply === "function" ? R.apply : function ReflectApply2(target, receiver, args) {
return Function.prototype.apply.call(target, receiver, args);
};
var ReflectOwnKeys;
if (R && typeof R.ownKeys === "function") {
ReflectOwnKeys = R.ownKeys;
} else if (Object.getOwnPropertySymbols) {
ReflectOwnKeys = function ReflectOwnKeys2(target) {
return Object.getOwnPropertyNames(target).concat(Object.getOwnPropertySymbols(target));
};
} else {
ReflectOwnKeys = function ReflectOwnKeys2(target) {
return Object.getOwnPropertyNames(target);
};
}
function ProcessEmitWarning(warning) {
if (console && console.warn) console.warn(warning);
}
var NumberIsNaN = Number.isNaN || function NumberIsNaN2(value) {
return value !== value;
};
function EventEmitter() {
EventEmitter.init.call(this);
}
module.exports = EventEmitter;
module.exports.once = once;
EventEmitter.EventEmitter = EventEmitter;
EventEmitter.prototype._events = void 0;
EventEmitter.prototype._eventsCount = 0;
EventEmitter.prototype._maxListeners = void 0;
var defaultMaxListeners = 10;
function checkListener(listener) {
if (typeof listener !== "function") {
throw new TypeError('The "listener" argument must be of type Function. Received type ' + typeof listener);
}
}
Object.defineProperty(EventEmitter, "defaultMaxListeners", {
enumerable: true,
get: function() {
return defaultMaxListeners;
},
set: function(arg) {
if (typeof arg !== "number" || arg < 0 || NumberIsNaN(arg)) {
throw new RangeError('The value of "defaultMaxListeners" is out of range. It must be a non-negative number. Received ' + arg + ".");
}
defaultMaxListeners = arg;
}
});
EventEmitter.init = function() {
if (this._events === void 0 || this._events === Object.getPrototypeOf(this)._events) {
this._events = /* @__PURE__ */ Object.create(null);
this._eventsCount = 0;
}
this._maxListeners = this._maxListeners || void 0;
};
EventEmitter.prototype.setMaxListeners = function setMaxListeners(n2) {
if (typeof n2 !== "number" || n2 < 0 || NumberIsNaN(n2)) {
throw new RangeError('The value of "n" is out of range. It must be a non-negative number. Received ' + n2 + ".");
}
this._maxListeners = n2;
return this;
};
function _getMaxListeners(that) {
if (that._maxListeners === void 0)
return EventEmitter.defaultMaxListeners;
return that._maxListeners;
}
EventEmitter.prototype.getMaxListeners = function getMaxListeners() {
return _getMaxListeners(this);
};
EventEmitter.prototype.emit = function emit(type) {
var args = [];
for (var i = 1; i < arguments.length; i++) args.push(arguments[i]);
var doError = type === "error";
var events = this._events;
if (events !== void 0)
doError = doError && events.error === void 0;
else if (!doError)
return false;
if (doError) {
var er;
if (args.length > 0)
er = args[0];
if (er instanceof Error) {
throw er;
}
var err = new Error("Unhandled error." + (er ? " (" + er.message + ")" : ""));
err.context = er;
throw err;
}
var handler = events[type];
if (handler === void 0)
return false;
if (typeof handler === "function") {
ReflectApply(handler, this, args);
} else {
var len = handler.length;
var listeners = arrayClone(handler, len);
for (var i = 0; i < len; ++i)
ReflectApply(listeners[i], this, args);
}
return true;
};
function _addListener(target, type, listener, prepend) {
var m;
var events;
var existing;
checkListener(listener);
events = target._events;
if (events === void 0) {
events = target._events = /* @__PURE__ */ Object.create(null);
target._eventsCount = 0;
} else {
if (events.newListener !== void 0) {
target.emit(
"newListener",
type,
listener.listener ? listener.listener : listener
);
events = target._events;
}
existing = events[type];
}
if (existing === void 0) {
existing = events[type] = listener;
++target._eventsCount;
} else {
if (typeof existing === "function") {
existing = events[type] = prepend ? [listener, existing] : [existing, listener];
} else if (prepend) {
existing.unshift(listener);
} else {
existing.push(listener);
}
m = _getMaxListeners(target);
if (m > 0 && existing.length > m && !existing.warned) {
existing.warned = true;
var w = new Error("Possible EventEmitter memory leak detected. " + existing.length + " " + String(type) + " listeners added. Use emitter.setMaxListeners() to increase limit");
w.name = "MaxListenersExceededWarning";
w.emitter = target;
w.type = type;
w.count = existing.length;
ProcessEmitWarning(w);
}
}
return target;
}
EventEmitter.prototype.addListener = function addListener(type, listener) {
return _addListener(this, type, listener, false);
};
EventEmitter.prototype.on = EventEmitter.prototype.addListener;
EventEmitter.prototype.prependListener = function prependListener(type, listener) {
return _addListener(this, type, listener, true);
};
function onceWrapper() {
if (!this.fired) {
this.target.removeListener(this.type, this.wrapFn);
this.fired = true;
if (arguments.length === 0)
return this.listener.call(this.target);
return this.listener.apply(this.target, arguments);
}
}
function _onceWrap(target, type, listener) {
var state = { fired: false, wrapFn: void 0, target, type, listener };
var wrapped = onceWrapper.bind(state);
wrapped.listener = listener;
state.wrapFn = wrapped;
return wrapped;
}
EventEmitter.prototype.once = function once2(type, listener) {
checkListener(listener);
this.on(type, _onceWrap(this, type, listener));
return this;
};
EventEmitter.prototype.prependOnceListener = function prependOnceListener(type, listener) {
checkListener(listener);
this.prependListener(type, _onceWrap(this, type, listener));
return this;
};
EventEmitter.prototype.removeListener = function removeListener(type, listener) {
var list, events, position, i, originalListener;
checkListener(listener);
events = this._events;
if (events === void 0)
return this;
list = events[type];
if (list === void 0)
return this;
if (list === listener || list.listener === listener) {
if (--this._eventsCount === 0)
this._events = /* @__PURE__ */ Object.create(null);
else {
delete events[type];
if (events.removeListener)
this.emit("removeListener", type, list.listener || listener);
}
} else if (typeof list !== "function") {
position = -1;
for (i = list.length - 1; i >= 0; i--) {
if (list[i] === listener || list[i].listener === listener) {
originalListener = list[i].listener;
position = i;
break;
}
}
if (position < 0)
return this;
if (position === 0)
list.shift();
else {
spliceOne(list, position);
}
if (list.length === 1)
events[type] = list[0];
if (events.removeListener !== void 0)
this.emit("removeListener", type, originalListener || listener);
}
return this;
};
EventEmitter.prototype.off = EventEmitter.prototype.removeListener;
EventEmitter.prototype.removeAllListeners = function removeAllListeners(type) {
var listeners, events, i;
events = this._events;
if (events === void 0)
return this;
if (events.removeListener === void 0) {
if (arguments.length === 0) {
this._events = /* @__PURE__ */ Object.create(null);
this._eventsCount = 0;
} else if (events[type] !== void 0) {
if (--this._eventsCount === 0)
this._events = /* @__PURE__ */ Object.create(null);
else
delete events[type];
}
return this;
}
if (arguments.length === 0) {
var keys = Object.keys(events);
var key;
for (i = 0; i < keys.length; ++i) {
key = keys[i];
if (key === "removeListener") continue;
this.removeAllListeners(key);
}
this.removeAllListeners("removeListener");
this._events = /* @__PURE__ */ Object.create(null);
this._eventsCount = 0;
return this;
}
listeners = events[type];
if (typeof listeners === "function") {
this.removeListener(type, listeners);
} else if (listeners !== void 0) {
for (i = listeners.length - 1; i >= 0; i--) {
this.removeListener(type, listeners[i]);
}
}
return this;
};
function _listeners(target, type, unwrap) {
var events = target._events;
if (events === void 0)
return [];
var evlistener = events[type];
if (evlistener === void 0)
return [];
if (typeof evlistener === "function")
return unwrap ? [evlistener.listener || evlistener] : [evlistener];
return unwrap ? unwrapListeners(evlistener) : arrayClone(evlistener, evlistener.length);
}
EventEmitter.prototype.listeners = function listeners(type) {
return _listeners(this, type, true);
};
EventEmitter.prototype.rawListeners = function rawListeners(type) {
return _listeners(this, type, false);
};
EventEmitter.listenerCount = function(emitter, type) {
if (typeof emitter.listenerCount === "function") {
return emitter.listenerCount(type);
} else {
return listenerCount.call(emitter, type);
}
};
EventEmitter.prototype.listenerCount = listenerCount;
function listenerCount(type) {
var events = this._events;
if (events !== void 0) {
var evlistener = events[type];
if (typeof evlistener === "function") {
return 1;
} else if (evlistener !== void 0) {
return evlistener.length;
}
}
return 0;
}
EventEmitter.prototype.eventNames = function eventNames() {
return this._eventsCount > 0 ? ReflectOwnKeys(this._events) : [];
};
function arrayClone(arr, n2) {
var copy = new Array(n2);
for (var i = 0; i < n2; ++i)
copy[i] = arr[i];
return copy;
}
function spliceOne(list, index) {
for (; index + 1 < list.length; index++)
list[index] = list[index + 1];
list.pop();
}
function unwrapListeners(arr) {
var ret = new Array(arr.length);
for (var i = 0; i < ret.length; ++i) {
ret[i] = arr[i].listener || arr[i];
}
return ret;
}
function once(emitter, name) {
return new Promise(function(resolve, reject) {
function errorListener(err) {
emitter.removeListener(name, resolver);
reject(err);
}
function resolver() {
if (typeof emitter.removeListener === "function") {
emitter.removeListener("error", errorListener);
}
resolve([].slice.call(arguments));
}
;
eventTargetAgnosticAddListener(emitter, name, resolver, { once: true });
if (name !== "error") {
addErrorHandlerIfEventEmitter(emitter, errorListener, { once: true });
}
});
}
function addErrorHandlerIfEventEmitter(emitter, handler, flags) {
if (typeof emitter.on === "function") {
eventTargetAgnosticAddListener(emitter, "error", handler, flags);
}
}
function eventTargetAgnosticAddListener(emitter, name, listener, flags) {
if (typeof emitter.on === "function") {
if (flags.once) {
emitter.once(name, listener);
} else {
emitter.on(name, listener);
}
} else if (typeof emitter.addEventListener === "function") {
emitter.addEventListener(name, function wrapListener(arg) {
if (flags.once) {
emitter.removeEventListener(name, wrapListener);
}
listener(arg);
});
} else {
throw new TypeError('The "emitter" argument must be of type EventEmitter. Received type ' + typeof emitter);
}
}
}
});
// ../../node_modules/.pnpm/mediasoup-client@3.18.3/node_modules/mediasoup-client/lib/enhancedEvents.js
var require_enhancedEvents = __commonJS({
"../../node_modules/.pnpm/mediasoup-client@3.18.3/node_modules/mediasoup-client/lib/enhancedEvents.js"(exports) {
"use strict";
init_process();
Object.defineProperty(exports, "__esModule", { value: true });
exports.EnhancedEventEmitter = void 0;
var events_alias_1 = require_events();
var Logger_1 = require_Logger();
var enhancedEventEmitterLogger = new Logger_1.Logger("EnhancedEventEmitter");
var EnhancedEventEmitter = class extends events_alias_1.EventEmitter {
constructor() {
super();
this.setMaxListeners(Infinity);
}
/**
* Empties all stored event listeners.
*/
close() {
super.removeAllListeners();
}
emit(eventName, ...args) {
return super.emit(eventName, ...args);
}
/**
* Special addition to the EventEmitter API.
*/
safeEmit(eventName, ...args) {
try {
return super.emit(eventName, ...args);
} catch (error) {
enhancedEventEmitterLogger.error("safeEmit() | event listener threw an error [eventName:%s]:%o", eventName, error);
try {
super.emit("listenererror", eventName, error);
} catch (error2) {
}
return Boolean(super.listenerCount(eventName));
}
}
on(eventName, listener) {
super.on(eventName, listener);
return this;
}
off(eventName, listener) {
super.off(eventName, listener);
return this;
}
addListener(eventName, listener) {
super.on(eventName, listener);
return this;
}
prependListener(eventName, listener) {
super.prependListener(eventName, listener);
return this;
}
once(eventName, listener) {
super.once(eventName, listener);
return this;
}
prependOnceListener(eventName, listener) {
super.prependOnceListener(eventName, listener);
return this;
}
removeListener(eventName, listener) {
super.off(eventName, listener);
return this;
}
removeAllListeners(eventName) {
super.removeAllListeners(eventName);
return this;
}
listenerCount(eventName) {
return super.listenerCount(eventName);
}
listeners(eventName) {
return super.listeners(eventName);
}
rawListeners(eventName) {
return super.rawListeners(eventName);
}
};
exports.EnhancedEventEmitter = EnhancedEventEmitter;
}
});
// ../../node_modules/.pnpm/mediasoup-client@3.18.3/node_modules/mediasoup-client/lib/errors.js
var require_errors = __commonJS({
"../../node_modules/.pnpm/mediasoup-client@3.18.3/node_modules/mediasoup-client/lib/errors.js"(exports) {
"use strict";
init_process();
Object.defineProperty(exports, "__esModule", { value: true });
exports.InvalidStateError = exports.UnsupportedError = void 0;
var UnsupportedError = class _UnsupportedError extends Error {
constructor(message) {
super(message);
this.name = "UnsupportedError";
if (Error.hasOwnProperty("captureStackTrace")) {
Error.captureStackTrace(this, _UnsupportedError);
} else {
this.stack = new Error(message).stack;
}
}
};
exports.UnsupportedError = UnsupportedError;
var InvalidStateError = class _InvalidStateError extends Error {
constructor(message) {
super(message);
this.name = "InvalidStateError";
if (Error.hasOwnProperty("captureStackTrace")) {
Error.captureStackTrace(this, _InvalidStateError);
} else {
this.stack = new Error(message).stack;
}
}
};
exports.InvalidStateError = InvalidStateError;
}
});
// ../../node_modules/.pnpm/mediasoup-client@3.18.3/node_modules/mediasoup-client/lib/utils.js
var require_utils = __commonJS({
"../../node_modules/.pnpm/mediasoup-client@3.18.3/node_modules/mediasoup-client/lib/utils.js"(exports) {
"use strict";
init_process();
Object.defineProperty(exports, "__esModule", { value: true });
exports.clone = clone;
exports.generateRandomNumber = generateRandomNumber;
exports.deepFreeze = deepFreeze;
function clone(value) {
if (value === void 0) {
return void 0;
} else if (Number.isNaN(value)) {
return NaN;
} else if (typeof structuredClone === "function") {
return structuredClone(value);
} else {
return JSON.parse(JSON.stringify(value));
}
}
function generateRandomNumber() {
return Math.round(Math.random() * 1e7);
}
function deepFreeze(data) {
const propNames = Reflect.ownKeys(data);
for (const name of propNames) {
const value = data[name];
if (value && typeof value === "object" || typeof value === "function") {
deepFreeze(value);
}
}
return Object.freeze(data);
}
}
});
// ../../node_modules/.pnpm/h264-profile-level-id@2.3.1_supports-color@10.2.2/node_modules/h264-profile-level-id/lib/Logger.js
var require_Logger2 = __commonJS({
"../../node_modules/.pnpm/h264-profile-level-id@2.3.1_supports-color@10.2.2/node_modules/h264-profile-level-id/lib/Logger.js"(exports) {
"use strict";
init_process();
Object.defineProperty(exports, "__esModule", { value: true });
exports.Logger = void 0;
var debug_1 = require_browser2();
var APP_NAME = "h264-profile-level-id";
var Logger4 = class {
constructor(prefix) {
__publicField(this, "_debug");
__publicField(this, "_warn");
__publicField(this, "_error");
if (prefix) {
this._debug = (0, debug_1.default)(`${APP_NAME}:${prefix}`);
this._warn = (0, debug_1.default)(`${APP_NAME}:WARN:${prefix}`);
this._error = (0, debug_1.default)(`${APP_NAME}:ERROR:${prefix}`);
} else {
this._debug = (0, debug_1.default)(APP_NAME);
this._warn = (0, debug_1.default)(`${APP_NAME}:WARN`);
this._error = (0, debug_1.default)(`${APP_NAME}:ERROR`);
}
this._debug.log = console.info.bind(console);
this._warn.log = console.warn.bind(console);
this._error.log = console.error.bind(console);
}
get debug() {
return this._debug;
}
get warn() {
return this._warn;
}
get error() {
return this._error;
}
};
exports.Logger = Logger4;
}
});
// ../../node_modules/.pnpm/h264-profile-level-id@2.3.1_supports-color@10.2.2/node_modules/h264-profile-level-id/lib/index.js
var require_lib2 = __commonJS({
"../../node_modules/.pnpm/h264-profile-level-id@2.3.1_supports-color@10.2.2/node_modules/h264-profile-level-id/lib/index.js"(exports) {
"use strict";
init_process();
Object.defineProperty(exports, "__esModule", { value: true });
exports.ProfileLevelId = exports.Level = exports.Profile = void 0;
exports.parseProfileLevelId = parseProfileLevelId;
exports.profileLevelIdToString = profileLevelIdToString;
exports.profileToString = profileToString;
exports.levelToString = levelToString;
exports.parseSdpProfileLevelId = parseSdpProfileLevelId;
exports.isSameProfile = isSameProfile;
exports.isSameProfileAndLevel = isSameProfileAndLevel;
exports.generateProfileLevelIdStringForAnswer = generateProfileLevelIdStringForAnswer;
exports.supportedLevel = supportedLevel;
var Logger_1 = require_Logger2();
var logger2 = new Logger_1.Logger();
var Profile;
(function(Profile2) {
Profile2[Profile2["ConstrainedBaseline"] = 1] = "ConstrainedBaseline";
Profile2[Profile2["Baseline"] = 2] = "Baseline";
Profile2[Profile2["Main"] = 3] = "Main";
Profile2[Profile2["ConstrainedHigh"] = 4] = "ConstrainedHigh";
Profile2[Profile2["High"] = 5] = "High";
Profile2[Profile2["PredictiveHigh444"] = 6] = "PredictiveHigh444";
})(Profile || (exports.Profile = Profile = {}));
var Level;
(function(Level2) {
Level2[Level2["L1_b"] = 0] = "L1_b";
Level2[Level2["L1"] = 10] = "L1";
Level2[Level2["L1_1"] = 11] = "L1_1";
Level2[Level2["L1_2"] = 12] = "L1_2";
Level2[Level2["L1_3"] = 13] = "L1_3";
Level2[Level2["L2"] = 20] = "L2";
Level2[Level2["L2_1"] = 21] = "L2_1";
Level2[Level2["L2_2"] = 22] = "L2_2";
Level2[Level2["L3"] = 30] = "L3";
Level2[Level2["L3_1"] = 31] = "L3_1";
Level2[Level2["L3_2"] = 32] = "L3_2";
Level2[Level2["L4"] = 40] = "L4";
Level2[Level2["L4_1"] = 41] = "L4_1";
Level2[Level2["L4_2"] = 42] = "L4_2";
Level2[Level2["L5"] = 50] = "L5";
Level2[Level2["L5_1"] = 51] = "L5_1";
Level2[Level2["L5_2"] = 52] = "L5_2";
})(Level || (exports.Level = Level = {}));
var ProfileLevelId = class {
constructor(profile, level) {
__publicField(this, "profile");
__publicField(this, "level");
this.profile = profile;
this.level = level;
}
};
exports.ProfileLevelId = ProfileLevelId;
var DefaultProfileLevelId = new ProfileLevelId(Profile.ConstrainedBaseline, Level.L3_1);
var BitPattern = class {
constructor(str) {
__publicField(this, "mask");
__publicField(this, "masked_value");
this.mask = ~byteMaskString("x", str);
this.masked_value = byteMaskString("1", str);
}
isMatch(value) {
return this.masked_value === (value & this.mask);
}
};
var ProfilePattern = class {
constructor(profile_idc, profile_iop, profile) {
__publicField(this, "profile_idc");
__publicField(this, "profile_iop");
__publicField(this, "profile");
this.profile_idc = profile_idc;
this.profile_iop = profile_iop;
this.profile = profile;
}
};
var ProfilePatterns = [
new ProfilePattern(66, new BitPattern("x1xx0000"), Profile.ConstrainedBaseline),
new ProfilePattern(77, new BitPattern("1xxx0000"), Profile.ConstrainedBaseline),
new ProfilePattern(88, new BitPattern("11xx0000"), Profile.ConstrainedBaseline),
new ProfilePattern(66, new BitPattern("x0xx0000"), Profile.Baseline),
new ProfilePattern(88, new BitPattern("10xx0000"), Profile.Baseline),
new ProfilePattern(77, new BitPattern("0x0x0000"), Profile.Main),
new ProfilePattern(100, new BitPattern("00000000"), Profile.High),
new ProfilePattern(100, new BitPattern("00001100"), Profile.ConstrainedHigh),
new ProfilePattern(244, new BitPattern("00000000"), Profile.PredictiveHigh444)
];
var LevelConstraints = [
{
max_macroblocks_per_second: 1485,
max_macroblock_frame_size: 99,
level: Level.L1
},
{
max_macroblocks_per_second: 1485,
max_macroblock_frame_size: 99,
level: Level.L1_b
},
{
max_macroblocks_per_second: 3e3,
max_macroblock_frame_size: 396,
level: Level.L1_1
},
{
max_macroblocks_per_second: 6e3,
max_macroblock_frame_size: 396,
level: Level.L1_2
},
{
max_macroblocks_per_second: 11880,
max_macroblock_frame_size: 396,
level: Level.L1_3
},
{
max_macroblocks_per_second: 11880,
max_macroblock_frame_size: 396,
level: Level.L2
},
{
max_macroblocks_per_second: 19800,
max_macroblock_frame_size: 792,
level: Level.L2_1
},
{
max_macroblocks_per_second: 20250,
max_macroblock_frame_size: 1620,
level: Level.L2_2
},
{
max_macroblocks_per_second: 40500,
max_macroblock_frame_size: 1620,
level: Level.L3
},
{
max_macroblocks_per_second: 108e3,
max_macroblock_frame_size: 3600,
level: Level.L3_1
},
{
max_macroblocks_per_second: 216e3,
max_macroblock_frame_size: 5120,
level: Level.L3_2
},
{
max_macroblocks_per_second: 245760,
max_macroblock_frame_size: 8192,
level: Level.L4
},
{
max_macroblocks_per_second: 245760,
max_macroblock_frame_size: 8192,
level: Level.L4_1
},
{
max_macroblocks_per_second: 522240,
max_macroblock_frame_size: 8704,
level: Level.L4_2
},
{
max_macroblocks_per_second: 589824,
max_macroblock_frame_size: 22080,
level: Level.L5
},
{
max_macroblocks_per_second: 983040,
max_macroblock_frame_size: 36864,
level: Level.L5_1
},
{
max_macroblocks_per_second: 2073600,
max_macroblock_frame_size: 36864,
level: Level.L5_2
}
];
function parseProfileLevelId(str) {
const ConstraintSet3Flag = 16;
if (typeof str !== "string" || str.length !== 6) {
return void 0;
}
const profile_level_id_numeric = parseInt(str, 16);
if (profile_level_id_numeric === 0) {
return void 0;
}
const level_idc = profile_level_id_numeric & 255;
const profile_iop = profile_level_id_numeric >> 8 & 255;
const profile_idc = profile_level_id_numeric >> 16 & 255;
let level;
switch (level_idc) {
case Level.L1_1: {
level = (profile_iop & ConstraintSet3Flag) !== 0 ? Level.L1_b : Level.L1_1;
break;
}
case Level.L1:
case Level.L1_2:
case Level.L1_3:
case Level.L2:
case Level.L2_1:
case Level.L2_2:
case Level.L3:
case Level.L3_1:
case Level.L3_2:
case Level.L4:
case Level.L4_1:
case Level.L4_2:
case Level.L5:
case Level.L5_1:
case Level.L5_2: {
level = level_idc;
break;
}
// Unrecognized level_idc.
default: {
logger2.warn(`parseProfileLevelId() | unrecognized level_idc [str:${str}, level_idc:${level_idc}]`);
return void 0;
}
}
for (const pattern of ProfilePatterns) {
if (profile_idc === pattern.profile_idc && pattern.profile_iop.isMatch(profile_iop)) {
logger2.debug(`parseProfileLevelId() | result [str:${str}, profile:${pattern.profile}, level:${level}]`);
return new ProfileLevelId(pattern.profile, level);
}
}
logger2.warn(`parseProfileLevelId() | unrecognized profile_idc/profile_iop combination [str:${str}, profile_idc:${profile_idc}, profile_iop:${profile_iop}]`);
return void 0;
}
function profileLevelIdToString(profile_level_id) {
if (profile_level_id.level == Level.L1_b) {
switch (profile_level_id.profile) {
case Profile.ConstrainedBaseline: {
return "42f00b";
}
case Profile.Baseline: {
return "42100b";
}
case Profile.Main: {
return "4d100b";
}
// Level 1_b is not allowed for other profiles.
default: {
logger2.warn(`profileLevelIdToString() | Level 1_b not is allowed for profile ${profile_level_id.profile}`);
return void 0;
}
}
}
let profile_idc_iop_string;
switch (profile_level_id.profile) {
case Profile.ConstrainedBaseline: {
profile_idc_iop_string = "42e0";
break;
}
case Profile.Baseline: {
profile_idc_iop_string = "4200";
break;
}
case Profile.Main: {
profile_idc_iop_string = "4d00";
break;
}
case Profile.ConstrainedHigh: {
profile_idc_iop_string = "640c";
break;
}
case Profile.High: {
profile_idc_iop_string = "6400";
break;
}
case Profile.PredictiveHigh444: {
profile_idc_iop_string = "f400";
break;
}
default: {
logger2.warn(`profileLevelIdToString() | unrecognized profile ${profile_level_id.profile}`);
return void 0;
}
}
let levelStr = profile_level_id.level.toString(16);
if (levelStr.length === 1) {
levelStr = `0${levelStr}`;
}
return `${profile_idc_iop_string}${levelStr}`;
}
function profileToString(profile) {
switch (profile) {
case Profile.ConstrainedBaseline: {
return "ConstrainedBaseline";
}
case Profile.Baseline: {
return "Baseline";
}
case Profile.Main: {
return "Main";
}
case Profile.ConstrainedHigh: {
return "ConstrainedHigh";
}
case Profile.High: {
return "High";
}
case Profile.PredictiveHigh444: {
return "PredictiveHigh444";
}
default: {
logger2.warn(`profileToString() | unrecognized profile ${profile}`);
return void 0;
}
}
}
function levelToString(level) {
switch (level) {
case Level.L1_b: {
return "1b";
}
case Level.L1: {
return "1";
}
case Level.L1_1: {
return "1.1";
}
case Level.L1_2: {
return "1.2";
}
case Level.L1_3: {
return "1.3";
}
case Level.L2: {
return "2";
}
case Level.L2_1: {
return "2.1";
}
case Level.L2_2: {
return "2.2";
}
case Level.L3: {
return "3";
}
case Level.L3_1: {
return "3.1";
}
case Level.L3_2: {
return "3.2";
}
case Level.L4: {
return "4";
}
case Level.L4_1: {
return "4.1";
}
case Level.L4_2: {
return "4.2";
}
case Level.L5: {
return "5";
}
case Level.L5_1: {
return "5.1";
}
case Level.L5_2: {
return "5.2";
}
default: {
logger2.warn(`levelToString() | unrecognized level ${level}`);
return void 0;
}
}
}
function parseSdpProfileLevelId(params = {}) {
const profile_level_id = params["profile-level-id"];
return profile_level_id ? parseProfileLevelId(profile_level_id) : DefaultProfileLevelId;
}
function isSameProfile(params1 = {}, params2 = {}) {
const profile_level_id_1 = parseSdpProfileLevelId(params1);
const profile_level_id_2 = parseSdpProfileLevelId(params2);
return Boolean(profile_level_id_1 && profile_level_id_2 && profile_level_id_1.profile === profile_level_id_2.profile);
}
function isSameProfileAndLevel(params1 = {}, params2 = {}) {
const profile_level_id_1 = parseSdpProfileLevelId(params1);
const profile_level_id_2 = parseSdpProfileLevelId(params2);
return Boolean(profile_level_id_1 && profile_level_id_2 && profile_level_id_1.profile === profile_level_id_2.profile && profile_level_id_1.level == profile_level_id_2.level);
}
function generateProfileLevelIdStringForAnswer(local_supported_params = {}, remote_offered_params = {}) {
if (!local_supported_params["profile-level-id"] && !remote_offered_params["profile-level-id"]) {
logger2.warn("generateProfileLevelIdStringForAnswer() | profile-level-id missing in local and remote params");
return void 0;
}
const local_profile_level_id = parseSdpProfileLevelId(local_supported_params);
const remote_profile_level_id = parseSdpProfileLevelId(remote_offered_params);
if (!local_profile_level_id) {
throw new TypeError("invalid local_profile_level_id");
}
if (!remote_profile_level_id) {
throw new TypeError("invalid remote_profile_level_id");
}
if (local_profile_level_id.profile !== remote_profile_level_id.profile) {
throw new TypeError("H264 Profile mismatch");
}
const level_asymmetry_allowed = isLevelAsymmetryAllowed(local_supported_params) && isLevelAsymmetryAllowed(remote_offered_params);
const local_level = local_profile_level_id.level;
const remote_level = remote_profile_level_id.level;
const min_level = minLevel(local_level, remote_level);
const answer_level = level_asymmetry_allowed ? local_level : min_level;
logger2.debug(`generateProfileLevelIdStringForAnswer() | result [profile:${local_profile_level_id.profile}, level:${answer_level}]`);
return profileLevelIdToString(new ProfileLevelId(local_profile_level_id.profile, answer_level));
}
function supportedLevel(max_frame_pixel_count, max_fps) {
const PixelsPerMacroblock = 16 * 16;
for (let i = LevelConstraints.length - 1; i >= 0; --i) {
const level_constraint = LevelConstraints[i];
if (level_constraint.max_macroblock_frame_size * PixelsPerMacroblock <= max_frame_pixel_count && level_constraint.max_macroblocks_per_second <= max_fps * level_constraint.max_macroblock_frame_size) {
logger2.debug(`supportedLevel() | result [max_frame_pixel_count:${max_frame_pixel_count}, max_fps:${max_fps}, level:${level_constraint.level}]`);
return level_constraint.level;
}
}
logger2.warn(`supportedLevel() | no level supported [max_frame_pixel_count:${max_frame_pixel_count}, max_fps:${max_fps}]`);
return void 0;
}
function byteMaskString(c, str) {
return Number(str[0] === c) << 7 | Number(str[1] === c) << 6 | Number(str[2] === c) << 5 | Number(str[3] === c) << 4 | Number(str[4] === c) << 3 | Number(str[5] === c) << 2 | Number(str[6] === c) << 1 | Number(str[7] === c) << 0;
}
function isLessLevel(a, b) {
if (a === Level.L1_b) {
return b !== Level.L1 && b !== Level.L1_b;
}
if (b === Level.L1_b) {
return a !== Level.L1;
}
return a < b;
}
function minLevel(a, b) {
return isLessLevel(a, b) ? a : b;
}
function isLevelAsymmetryAllowed(params = {}) {
const level_asymmetry_allowed = params["level-asymmetry-allowed"];
return level_asymmetry_allowed === true || level_asymmetry_allowed === 1 || level_asymmetry_allowed === "1";
}
}
});
// ../../node_modules/.pnpm/mediasoup-client@3.18.3/node_modules/mediasoup-client/lib/ortc.js
var require_ortc = __commonJS({
"../../node_modules/.pnpm/mediasoup-client@3.18.3/node_modules/mediasoup-client/lib/ortc.js"(exports) {
"use strict";
init_process();
Object.defineProperty(exports, "__esModule", { value: true });
exports.validateAndNormalizeRtpCapabilities = validateAndNormalizeRtpCapabilities;
exports.validateAndNormalizeRtpParameters = validateAndNormalizeRtpParameters;
exports.validateAndNormalizeSctpStreamParameters = validateAndNormalizeSctpStreamParameters;
exports.validateSctpCapabilities = validateSctpCapabilities;
exports.getExtendedRtpCapabilities = getExtendedRtpCapabilities;
exports.getRecvRtpCapabilities = getRecvRtpCapabilities;
exports.getSendingRtpParameters = getSendingRtpParameters;
exports.getSendingRemoteRtpParameters = getSendingRemoteRtpParameters;
exports.reduceCodecs = reduceCodecs;
exports.generateProbatorRtpParameters = generateProbatorRtpParameters;
exports.canSend = canSend;
exports.canReceive = canReceive;
var h264 = require_lib2();
var utils = require_utils();
var RTP_PROBATOR_MID = "probator";
var RTP_PROBATOR_SSRC = 1234;
var RTP_PROBATOR_CODEC_PAYLOAD_TYPE = 127;
function validateAndNormalizeRtpCapabilities(caps) {
if (typeof caps !== "object") {
throw new TypeError("caps is not an object");
}
if (caps.codecs && !Array.isArray(caps.codecs)) {
throw new TypeError("caps.codecs is not an array");
} else if (!caps.codecs) {
caps.codecs = [];
}
for (const codec of caps.codecs) {
validateAndNormalizeRtpCodecCapability(codec);
}
if (caps.headerExtensions && !Array.isArray(caps.headerExtensions)) {
throw new TypeError("caps.headerExtensions is not an array");
} else if (!caps.headerExtensions) {
caps.headerExtensions = [];
}
for (const ext of caps.headerExtensions) {
validateAndNormalizeRtpHeaderExtension(ext);
}
}
function validateAndNormalizeRtpParameters(params) {
if (typeof params !== "object") {
throw new TypeError("params is not an object");
}
if (params.mid && typeof params.mid !== "string") {
throw new TypeError("params.mid is not a string");
}
if (!Array.isArray(params.codecs)) {
throw new TypeError("missing params.codecs");
}
for (const codec of params.codecs) {
validateAndNormalizeRtpCodecParameters(codec);
}
if (params.headerExtensions && !Array.isArray(params.headerExtensions)) {
throw new TypeError("params.headerExtensions is not an array");
} else if (!params.headerExtensions) {
params.headerExtensions = [];
}
for (const ext of params.headerExtensions) {
validateRtpHeaderExtensionParameters(ext);
}
if (params.encodings && !Array.isArray(params.encodings)) {
throw new TypeError("params.encodings is not an array");
} else if (!params.encodings) {
params.encodings = [];
}
for (const encoding of params.encodings) {
validateAndNormalizeRtpEncodingParameters(encoding);
}
if (params.rtcp && typeof params.rtcp !== "object") {
throw new TypeError("params.rtcp is not an object");
} else if (!params.rtcp) {
params.rtcp = {};
}
validateAndNormalizeRtcpParameters(params.rtcp);
}
function validateAndNormalizeSctpStreamParameters(params) {
if (typeof params !== "object") {
throw new TypeError("params is not an object");
}
if (typeof params.streamId !== "number") {
throw new TypeError("missing params.streamId");
}
let orderedGiven = false;
if (typeof params.ordered === "boolean") {
orderedGiven = true;
} else {
params.ordered = true;
}
if (params.maxPacketLifeTime && typeof params.maxPacketLifeTime !== "number") {
throw new TypeError("invalid params.maxPacketLifeTime");
}
if (params.maxRetransmits && typeof params.maxRetransmits !== "number") {
throw new TypeError("invalid params.maxRetransmits");
}
if (params.maxPacketLifeTime && params.maxRetransmits) {
throw new TypeError("cannot provide both maxPacketLifeTime and maxRetransmits");
}
if (orderedGiven && params.ordered && (params.maxPacketLifeTime || params.maxRetransmits)) {
throw new TypeError("cannot be ordered with maxPacketLifeTime or maxRetransmits");
} else if (!orderedGiven && (params.maxPacketLifeTime || params.maxRetransmits)) {
params.ordered = false;
}
if (params.label && typeof params.label !== "string") {
throw new TypeError("invalid params.label");
}
if (params.protocol && typeof params.protocol !== "string") {
throw new TypeError("invalid params.protocol");
}
}
function validateSctpCapabilities(caps) {
if (typeof caps !== "object") {
throw new TypeError("caps is not an object");
}
if (!caps.numStreams || typeof caps.numStreams !== "object") {
throw new TypeError("missing caps.numStreams");
}
validateNumSctpStreams(caps.numStreams);
}
function getExtendedRtpCapabilities(localCaps, remoteCaps, preferLocalCodecsOrder) {
var _a2, _b2, _c, _d, _e, _f, _g, _h, _i;
const extendedRtpCapabilities = {
codecs: [],
headerExtensions: []
};
if (preferLocalCodecsOrder) {
for (const localCodec of (_a2 = localCaps.codecs) != null ? _a2 : []) {
if (isRtxCodec(localCodec)) {
continue;
}
const matchingRemoteCodec = ((_b2 = remoteCaps.codecs) != null ? _b2 : []).find((remoteCodec) => matchCodecs(remoteCodec, localCodec, { strict: true, modify: true }));
if (!matchingRemoteCodec) {
continue;
}
const extendedCodec = {
kind: localCodec.kind,
mimeType: localCodec.mimeType,
clockRate: localCodec.clockRate,
channels: localCodec.channels,
localPayloadType: localCodec.preferredPayloadType,
localRtxPayloadType: void 0,
remotePayloadType: matchingRemoteCodec.preferredPayloadType,
remoteRtxPayloadType: void 0,
localParameters: (_c = localCodec.parameters) != null ? _c : {},
remoteParameters: (_d = matchingRemoteCodec.parameters) != null ? _d : {},
rtcpFeedback: reduceRtcpFeedback(localCodec, matchingRemoteCodec)
};
extendedRtpCapabilities.codecs.push(extendedCodec);
}
} else {
for (const remoteCodec of (_e = remoteCaps.codecs) != null ? _e : []) {
if (isRtxCodec(remoteCodec)) {
continue;
}
const matchingLocalCodec = ((_f = localCaps.codecs) != null ? _f : []).find((localCodec) => matchCodecs(localCodec, remoteCodec, { strict: true, modify: true }));
if (!matchingLocalCodec) {
continue;
}
const extendedCodec = {
kind: matchingLocalCodec.kind,
mimeType: matchingLocalCodec.mimeType,
clockRate: matchingLocalCodec.clockRate,
channels: matchingLocalCodec.channels,
localPayloadType: matchingLocalCodec.preferredPayloadType,
localRtxPayloadType: void 0,
remotePayloadType: remoteCodec.preferredPayloadType,
remoteRtxPayloadType: void 0,
localParameters: (_g = matchingLocalCodec.parameters) != null ? _g : {},
remoteParameters: (_h = remoteCodec.parameters) != null ? _h : {},
rtcpFeedback: reduceRtcpFeedback(matchingLocalCodec, remoteCodec)
};
extendedRtpCapabilities.codecs.push(extendedCodec);
}
}
for (const extendedCodec of extendedRtpCapabilities.codecs) {
const matchingLocalRtxCodec = localCaps.codecs.find((localCodec) => {
var _a3;
return isRtxCodec(localCodec) && ((_a3 = localCodec.parameters) == null ? void 0 : _a3["apt"]) === extendedCodec.localPayloadType;
});
const matchingRemoteRtxCodec = remoteCaps.codecs.find((remoteCodec) => {
var _a3;
return isRtxCodec(remoteCodec) && ((_a3 = remoteCodec.parameters) == null ? void 0 : _a3["apt"]) === extendedCodec.remotePayloadType;
});
if (matchingLocalRtxCodec && matchingRemoteRtxCodec) {
extendedCodec.localRtxPayloadType = matchingLocalRtxCodec.preferredPayloadType;
extendedCodec.remoteRtxPayloadType = matchingRemoteRtxCodec.preferredPayloadType;
}
}
for (const remoteExt of remoteCaps.headerExtensions) {
const matchingLocalExt = localCaps.headerExtensions.find((localExt) => matchHeaderExtensions(localExt, remoteExt));
if (!matchingLocalExt) {
continue;
}
const extendedExt = {
kind: remoteExt.kind,
uri: remoteExt.uri,
sendId: matchingLocalExt.preferredId,
recvId: remoteExt.preferredId,
encrypt: (_i = matchingLocalExt.preferredEncrypt) != null ? _i : false,
direction: "sendrecv"
};
switch (remoteExt.direction) {
case "sendrecv": {
extendedExt.direction = "sendrecv";
break;
}
case "recvonly": {
extendedExt.direction = "sendonly";
break;
}
case "sendonly": {
extendedExt.direction = "recvonly";
break;
}
case "inactive": {
extendedExt.direction = "inactive";
break;
}
}
extendedRtpCapabilities.headerExtensions.push(extendedExt);
}
return extendedRtpCapabilities;
}
function getRecvRtpCapabilities(extendedRtpCapabilities) {
var _a2;
const rtpCapabilities = {
codecs: [],
headerExtensions: []
};
for (const extendedCodec of extendedRtpCapabilities.codecs) {
const codec = {
kind: extendedCodec.kind,
mimeType: extendedCodec.mimeType,
preferredPayloadType: extendedCodec.remotePayloadType,
clockRate: extendedCodec.clockRate,
channels: extendedCodec.channels,
parameters: extendedCodec.localParameters,
rtcpFeedback: extendedCodec.rtcpFeedback
};
rtpCapabilities.codecs.push(codec);
if (!extendedCodec.remoteRtxPayloadType) {
continue;
}
const rtxCodec = {
kind: extendedCodec.kind,
mimeType: `${extendedCodec.kind}/rtx`,
preferredPayloadType: extendedCodec.remoteRtxPayloadType,
clockRate: extendedCodec.clockRate,
parameters: {
apt: extendedCodec.remotePayloadType
},
rtcpFeedback: []
};
rtpCapabilities.codecs.push(rtxCodec);
}
for (const extendedExtension of extendedRtpCapabilities.headerExtensions) {
if (extendedExtension.direction !== "sendrecv" && extendedExtension.direction !== "recvonly") {
continue;
}
const ext = {
kind: extendedExtension.kind,
uri: extendedExtension.uri,
preferredId: extendedExtension.recvId,
preferredEncrypt: (_a2 = extendedExtension.encrypt) != null ? _a2 : false,
direction: extendedExtension.direction
};
rtpCapabilities.headerExtensions.push(ext);
}
return rtpCapabilities;
}
function getSendingRtpParameters(kind, extendedRtpCapabilities) {
const rtpParameters = {
mid: void 0,
codecs: [],
headerExtensions: [],
encodings: [],
rtcp: {}
};
for (const extendedCodec of extendedRtpCapabilities.codecs) {
if (extendedCodec.kind !== kind) {
continue;
}
const codec = {
mimeType: extendedCodec.mimeType,
payloadType: extendedCodec.localPayloadType,
clockRate: extendedCodec.clockRate,
channels: extendedCodec.channels,
parameters: extendedCodec.localParameters,
rtcpFeedback: extendedCodec.rtcpFeedback
};
rtpParameters.codecs.push(codec);
if (extendedCodec.localRtxPayloadType) {
const rtxCodec = {
mimeType: `${extendedCodec.kind}/rtx`,
payloadType: extendedCodec.localRtxPayloadType,
clockRate: extendedCodec.clockRate,
parameters: {
apt: extendedCodec.localPayloadType
},
rtcpFeedback: []
};
rtpParameters.codecs.push(rtxCodec);
}
}
for (const extendedExtension of extendedRtpCapabilities.headerExtensions) {
if (extendedExtension.kind && extendedExtension.kind !== kind || extendedExtension.direction !== "sendrecv" && extendedExtension.direction !== "sendonly") {
continue;
}
const ext = {
uri: extendedExtension.uri,
id: extendedExtension.sendId,
encrypt: extendedExtension.encrypt,
parameters: {}
};
rtpParameters.headerExtensions.push(ext);
}
return rtpParameters;
}
function getSendingRemoteRtpParameters(kind, extendedRtpCapabilities) {
var _a2, _b2, _c;
const rtpParameters = {
mid: void 0,
codecs: [],
headerExtensions: [],
encodings: [],
rtcp: {}
};
for (const extendedCodec of extendedRtpCapabilities.codecs) {
if (extendedCodec.kind !== kind) {
continue;
}
const codec = {
mimeType: extendedCodec.mimeType,
payloadType: extendedCodec.localPayloadType,
clockRate: extendedCodec.clockRate,
channels: extendedCodec.channels,
parameters: extendedCodec.remoteParameters,
rtcpFeedback: extendedCodec.rtcpFeedback
};
rtpParameters.codecs.push(codec);
if (extendedCodec.localRtxPayloadType) {
const rtxCodec = {
mimeType: `${extendedCodec.kind}/rtx`,
payloadType: extendedCodec.localRtxPayloadType,
clockRate: extendedCodec.clockRate,
parameters: {
apt: extendedCodec.localPayloadType
},
rtcpFeedback: []
};
rtpParameters.codecs.push(rtxCodec);
}
}
for (const extendedExtension of extendedRtpCapabilities.headerExtensions) {
if (extendedExtension.kind && extendedExtension.kind !== kind || extendedExtension.direction !== "sendrecv" && extendedExtension.direction !== "sendonly") {
continue;
}
const ext = {
uri: extendedExtension.uri,
id: extendedExtension.sendId,
encrypt: extendedExtension.encrypt,
parameters: {}
};
rtpParameters.headerExtensions.push(ext);
}
if (rtpParameters.headerExtensions.some((ext) => ext.uri === "http://www.ietf.org/id/draft-holmer-rmcat-transport-wide-cc-extensions-01")) {
for (const codec of rtpParameters.codecs) {
codec.rtcpFeedback = ((_a2 = codec.rtcpFeedback) != null ? _a2 : []).filter((fb) => fb.type !== "goog-remb");
}
} else if (rtpParameters.headerExtensions.some((ext) => ext.uri === "http://www.webrtc.org/experiments/rtp-hdrext/abs-send-time")) {
for (const codec of rtpParameters.codecs) {
codec.rtcpFeedback = ((_b2 = codec.rtcpFeedback) != null ? _b2 : []).filter((fb) => fb.type !== "transport-cc");
}
} else {
for (const codec of rtpParameters.codecs) {
codec.rtcpFeedback = ((_c = codec.rtcpFeedback) != null ? _c : []).filter((fb) => fb.type !== "transport-cc" && fb.type !== "goog-remb");
}
}
return rtpParameters;
}
function reduceCodecs(codecs, capCodec) {
const filteredCodecs = [];
if (!capCodec) {
filteredCodecs.push(codecs[0]);
if (isRtxCodec(codecs[1])) {
filteredCodecs.push(codecs[1]);
}
} else {
for (let idx = 0; idx < codecs.length; ++idx) {
if (matchCodecs(codecs[idx], capCodec, { strict: true })) {
filteredCodecs.push(codecs[idx]);
if (isRtxCodec(codecs[idx + 1])) {
filteredCodecs.push(codecs[idx + 1]);
}
break;
}
}
if (filteredCodecs.length === 0) {
throw new TypeError("no matching codec found");
}
}
return filteredCodecs;
}
function generateProbatorRtpParameters(videoRtpParameters) {
videoRtpParameters = utils.clone(videoRtpParameters);
validateAndNormalizeRtpParameters(videoRtpParameters);
const rtpParameters = {
mid: RTP_PROBATOR_MID,
codecs: [],
headerExtensions: [],
encodings: [{ ssrc: RTP_PROBATOR_SSRC }],
rtcp: { cname: "probator" }
};
rtpParameters.codecs.push(videoRtpParameters.codecs[0]);
rtpParameters.codecs[0].payloadType = RTP_PROBATOR_CODEC_PAYLOAD_TYPE;
rtpParameters.headerExtensions = videoRtpParameters.headerExtensions;
return rtpParameters;
}
function canSend(kind, rtpCapabilities) {
var _a2;
return ((_a2 = rtpCapabilities.codecs) != null ? _a2 : []).some((codec) => codec.kind === kind);
}
function canReceive(rtpParameters, rtpCapabilities) {
var _a2;
validateAndNormalizeRtpParameters(rtpParameters);
if (rtpParameters.codecs.length === 0) {
return false;
}
const firstMediaCodec = rtpParameters.codecs[0];
return ((_a2 = rtpCapabilities.codecs) != null ? _a2 : []).some((codec) => codec.preferredPayloadType === firstMediaCodec.payloadType);
}
function validateAndNormalizeRtpCodecCapability(codec) {
const MimeTypeRegex = new RegExp("^(audio|video)/(.+)", "i");
if (typeof codec !== "object") {
throw new TypeError("codec is not an object");
}
if (!codec.mimeType || typeof codec.mimeType !== "string") {
throw new TypeError("missing codec.mimeType");
}
const mimeTypeMatch = MimeTypeRegex.exec(codec.mimeType);
if (!mimeTypeMatch) {
throw new TypeError("invalid codec.mimeType");
}
codec.kind = mimeTypeMatch[1].toLowerCase();
if (typeof codec.preferredPayloadType !== "number") {
throw new TypeError("missing codec.preferredPayloadType");
}
if (typeof codec.clockRate !== "number") {
throw new TypeError("missing codec.clockRate");
}
if (codec.kind === "audio") {
if (typeof codec.channels !== "number") {
codec.channels = 1;
}
} else {
delete codec.channels;
}
if (!codec.parameters || typeof codec.parameters !== "object") {
codec.parameters = {};
}
for (const key of Object.keys(codec.parameters)) {
let value = codec.parameters[key];
if (value === void 0) {
codec.parameters[key] = "";
value = "";
}
if (typeof value !== "string" && typeof value !== "number") {
throw new TypeError(`invalid codec parameter [key:${key}s, value:${value}]`);
}
if (key === "apt") {
if (typeof value !== "number") {
throw new TypeError("invalid codec apt parameter");
}
}
}
if (!codec.rtcpFeedback || !Array.isArray(codec.rtcpFeedback)) {
codec.rtcpFeedback = [];
}
for (const fb of codec.rtcpFeedback) {
validateAndNormalizeRtcpFeedback(fb);
}
}
function validateAndNormalizeRtcpFeedback(fb) {
if (typeof fb !== "object") {
throw new TypeError("fb is not an object");
}
if (!fb.type || typeof fb.type !== "string") {
throw new TypeError("missing fb.type");
}
if (!fb.parameter || typeof fb.parameter !== "string") {
fb.parameter = "";
}
}
function validateAndNormalizeRtpHeaderExtension(ext) {
if (typeof ext !== "object") {
throw new TypeError("ext is not an object");
}
if (ext.kind !== "audio" && ext.kind !== "video") {
throw new TypeError("invalid ext.kind");
}
if (!ext.uri || typeof ext.uri !== "string") {
throw new TypeError("missing ext.uri");
}
if (typeof ext.preferredId !== "number") {
throw new TypeError("missing ext.preferredId");
}
if (ext.preferredEncrypt && typeof ext.preferredEncrypt !== "boolean") {
throw new TypeError("invalid ext.preferredEncrypt");
} else if (!ext.preferredEncrypt) {
ext.preferredEncrypt = false;
}
if (ext.direction && typeof ext.direction !== "string") {
throw new TypeError("invalid ext.direction");
} else if (!ext.direction) {
ext.direction = "sendrecv";
}
}
function validateAndNormalizeRtpCodecParameters(codec) {
const MimeTypeRegex = new RegExp("^(audio|video)/(.+)", "i");
if (typeof codec !== "object") {
throw new TypeError("codec is not an object");
}
if (!codec.mimeType || typeof codec.mimeType !== "string") {
throw new TypeError("missing codec.mimeType");
}
const mimeTypeMatch = MimeTypeRegex.exec(codec.mimeType);
if (!mimeTypeMatch) {
throw new TypeError("invalid codec.mimeType");
}
if (typeof codec.payloadType !== "number") {
throw new TypeError("missing codec.payloadType");
}
if (typeof codec.clockRate !== "number") {
throw new TypeError("missing codec.clockRate");
}
const kind = mimeTypeMatch[1].toLowerCase();
if (kind === "audio") {
if (typeof codec.channels !== "number") {
codec.channels = 1;
}
} else {
delete codec.channels;
}
if (!codec.parameters || typeof codec.parameters !== "object") {
codec.parameters = {};
}
for (const key of Object.keys(codec.parameters)) {
let value = codec.parameters[key];
if (value === void 0) {
codec.parameters[key] = "";
value = "";
}
if (typeof value !== "string" && typeof value !== "number") {
throw new TypeError(`invalid codec parameter [key:${key}s, value:${value}]`);
}
if (key === "apt") {
if (typeof value !== "number") {
throw new TypeError("invalid codec apt parameter");
}
}
}
if (!codec.rtcpFeedback || !Array.isArray(codec.rtcpFeedback)) {
codec.rtcpFeedback = [];
}
for (const fb of codec.rtcpFeedback) {
validateAndNormalizeRtcpFeedback(fb);
}
}
function validateRtpHeaderExtensionParameters(ext) {
if (typeof ext !== "object") {
throw new TypeError("ext is not an object");
}
if (!ext.uri || typeof ext.uri !== "string") {
throw new TypeError("missing ext.uri");
}
if (typeof ext.id !== "number") {
throw new TypeError("missing ext.id");
}
if (ext.encrypt && typeof ext.encrypt !== "boolean") {
throw new TypeError("invalid ext.encrypt");
} else if (!ext.encrypt) {
ext.encrypt = false;
}
if (!ext.parameters || typeof ext.parameters !== "object") {
ext.parameters = {};
}
for (const key of Object.keys(ext.parameters)) {
let value = ext.parameters[key];
if (value === void 0) {
ext.parameters[key] = "";
value = "";
}
if (typeof value !== "string" && typeof value !== "number") {
throw new TypeError("invalid header extension parameter");
}
}
}
function validateAndNormalizeRtpEncodingParameters(encoding) {
if (typeof encoding !== "object") {
throw new TypeError("encoding is not an object");
}
if (encoding.ssrc && typeof encoding.ssrc !== "number") {
throw new TypeError("invalid encoding.ssrc");
}
if (encoding.rid && typeof encoding.rid !== "string") {
throw new TypeError("invalid encoding.rid");
}
if (encoding.rtx && typeof encoding.rtx !== "object") {
throw new TypeError("invalid encoding.rtx");
} else if (encoding.rtx) {
if (typeof encoding.rtx.ssrc !== "number") {
throw new TypeError("missing encoding.rtx.ssrc");
}
}
if (!encoding.dtx || typeof encoding.dtx !== "boolean") {
encoding.dtx = false;
}
if (encoding.scalabilityMode && typeof encoding.scalabilityMode !== "string") {
throw new TypeError("invalid encoding.scalabilityMode");
}
}
function validateAndNormalizeRtcpParameters(rtcp) {
if (typeof rtcp !== "object") {
throw new TypeError("rtcp is not an object");
}
if (rtcp.cname && typeof rtcp.cname !== "string") {
throw new TypeError("invalid rtcp.cname");
}
if (!rtcp.reducedSize || typeof rtcp.reducedSize !== "boolean") {
rtcp.reducedSize = true;
}
}
function validateNumSctpStreams(numStreams) {
if (typeof numStreams !== "object") {
throw new TypeError("numStreams is not an object");
}
if (typeof numStreams.OS !== "number") {
throw new TypeError("missing numStreams.OS");
}
if (typeof numStreams.MIS !== "number") {
throw new TypeError("missing numStreams.MIS");
}
}
function isRtxCodec(codec) {
if (!codec) {
return false;
}
return /.+\/rtx$/i.test(codec.mimeType);
}
function matchCodecs(aCodec, bCodec, { strict = false, modify = false } = {}) {
var _a2, _b2, _c, _d;
const aMimeType = aCodec.mimeType.toLowerCase();
const bMimeType = bCodec.mimeType.toLowerCase();
if (aMimeType !== bMimeType) {
return false;
}
if (aCodec.clockRate !== bCodec.clockRate) {
return false;
}
if (aCodec.channels !== bCodec.channels) {
return false;
}
switch (aMimeType) {
case "video/h264": {
if (strict) {
const aPacketizationMode = (_a2 = aCodec.parameters["packetization-mode"]) != null ? _a2 : 0;
const bPacketizationMode = (_b2 = bCodec.parameters["packetization-mode"]) != null ? _b2 : 0;
if (aPacketizationMode !== bPacketizationMode) {
return false;
}
if (!h264.isSameProfile(aCodec.parameters, bCodec.parameters)) {
return false;
}
let selectedProfileLevelId;
try {
selectedProfileLevelId = h264.generateProfileLevelIdStringForAnswer(aCodec.parameters, bCodec.parameters);
} catch (error) {
return false;
}
if (modify) {
if (selectedProfileLevelId) {
aCodec.parameters["profile-level-id"] = selectedProfileLevelId;
bCodec.parameters["profile-level-id"] = selectedProfileLevelId;
} else {
delete aCodec.parameters["profile-level-id"];
delete bCodec.parameters["profile-level-id"];
}
}
}
break;
}
case "video/vp9": {
if (strict) {
const aProfileId = (_c = aCodec.parameters["profile-id"]) != null ? _c : 0;
const bProfileId = (_d = bCodec.parameters["profile-id"]) != null ? _d : 0;
if (aProfileId !== bProfileId) {
return false;
}
}
break;
}
}
return true;
}
function matchHeaderExtensions(aExt, bExt) {
if (aExt.kind && bExt.kind && aExt.kind !== bExt.kind) {
return false;
}
if (aExt.uri !== bExt.uri) {
return false;
}
return true;
}
function reduceRtcpFeedback(codecA, codecB) {
var _a2, _b2;
const reducedRtcpFeedback = [];
for (const aFb of (_a2 = codecA.rtcpFeedback) != null ? _a2 : []) {
const matchingBFb = ((_b2 = codecB.rtcpFeedback) != null ? _b2 : []).find((bFb) => bFb.type === aFb.type && (bFb.parameter === aFb.parameter || !bFb.parameter && !aFb.parameter));
if (matchingBFb) {
reducedRtcpFeedback.push(matchingBFb);
}
}
return reducedRtcpFeedback;
}
}
});
// ../../node_modules/.pnpm/awaitqueue@3.3.0_supports-color@10.2.2/node_modules/awaitqueue/lib/Logger.js
var require_Logger3 = __commonJS({
"../../node_modules/.pnpm/awaitqueue@3.3.0_supports-color@10.2.2/node_modules/awaitqueue/lib/Logger.js"(exports) {
"use strict";
init_process();
Object.defineProperty(exports, "__esModule", { value: true });
exports.Logger = void 0;
var debug = require_browser2();
var LIB_NAME = "awaitqueue";
var Logger4 = class {
constructor(prefix) {
__publicField(this, "_debug");
__publicField(this, "_warn");
__publicField(this, "_error");
if (prefix) {
this._debug = debug(`${LIB_NAME}:${prefix}`);
this._warn = debug(`${LIB_NAME}:WARN:${prefix}`);
this._error = debug(`${LIB_NAME}:ERROR:${prefix}`);
} else {
this._debug = debug(LIB_NAME);
this._warn = debug(`${LIB_NAME}:WARN`);
this._error = debug(`${LIB_NAME}:ERROR`);
}
this._debug.log = console.info.bind(console);
this._warn.log = console.warn.bind(console);
this._error.log = console.error.bind(console);
}
get debug() {
return this._debug;
}
get warn() {
return this._warn;
}
get error() {
return this._error;
}
};
exports.Logger = Logger4;
}
});
// ../../node_modules/.pnpm/awaitqueue@3.3.0_supports-color@10.2.2/node_modules/awaitqueue/lib/errors.js
var require_errors2 = __commonJS({
"../../node_modules/.pnpm/awaitqueue@3.3.0_supports-color@10.2.2/node_modules/awaitqueue/lib/errors.js"(exports) {
"use strict";
init_process();
Object.defineProperty(exports, "__esModule", { value: true });
exports.AwaitQueueRemovedTaskError = exports.AwaitQueueStoppedError = void 0;
var AwaitQueueStoppedError = class _AwaitQueueStoppedError extends Error {
constructor(message) {
super(message != null ? message : "queue stopped");
this.name = "AwaitQueueStoppedError";
if (typeof Error.captureStackTrace === "function") {
Error.captureStackTrace(this, _AwaitQueueStoppedError);
}
}
};
exports.AwaitQueueStoppedError = AwaitQueueStoppedError;
var AwaitQueueRemovedTaskError = class _AwaitQueueRemovedTaskError extends Error {
constructor(message) {
super(message != null ? message : "queue task removed");
this.name = "AwaitQueueRemovedTaskError";
if (typeof Error.captureStackTrace === "function") {
Error.captureStackTrace(this, _AwaitQueueRemovedTaskError);
}
}
};
exports.AwaitQueueRemovedTaskError = AwaitQueueRemovedTaskError;
}
});
// ../../node_modules/.pnpm/awaitqueue@3.3.0_supports-color@10.2.2/node_modules/awaitqueue/lib/AwaitQueue.js
var require_AwaitQueue = __commonJS({
"../../node_modules/.pnpm/awaitqueue@3.3.0_supports-color@10.2.2/node_modules/awaitqueue/lib/AwaitQueue.js"(exports) {
"use strict";
init_process();
Object.defineProperty(exports, "__esModule", { value: true });
exports.AwaitQueue = void 0;
var Logger_1 = require_Logger3();
var errors_1 = require_errors2();
var logger2 = new Logger_1.Logger("AwaitQueue");
var AwaitQueue = class {
constructor() {
// Queue of pending tasks (map of PendingTasks indexed by id).
__publicField(this, "pendingTasks", /* @__PURE__ */ new Map());
// Incrementing PendingTask id.
__publicField(this, "nextTaskId", 0);
logger2.debug("constructor()");
}
get size() {
return this.pendingTasks.size;
}
push(task, name, options) {
return __async(this, null, function* () {
name = name != null ? name : task.name;
logger2.debug(`push() [name:${name}, options:%o]`, options);
if (typeof task !== "function") {
throw new TypeError("given task is not a function");
}
if (name) {
try {
Object.defineProperty(task, "name", { value: name });
} catch (error) {
}
}
return new Promise((resolve, reject) => {
if (name && (options == null ? void 0 : options.removeOngoingTasksWithSameName)) {
for (const pendingTask2 of this.pendingTasks.values()) {
if (pendingTask2.name === name) {
pendingTask2.reject(new errors_1.AwaitQueueRemovedTaskError(), {
canExecuteNextTask: false
});
}
}
}
const pendingTask = {
id: this.nextTaskId++,
task,
name,
enqueuedAt: Date.now(),
executedAt: void 0,
completed: false,
resolve: (result2) => {
if (pendingTask.completed) {
return;
}
pendingTask.completed = true;
this.pendingTasks.delete(pendingTask.id);
logger2.debug(`resolving task [name:${pendingTask.name}]`);
resolve(result2);
const [nextPendingTask] = this.pendingTasks.values();
if (nextPendingTask && !nextPendingTask.executedAt) {
void this.execute(nextPendingTask);
}
},
reject: (error, { canExecuteNextTask }) => {
if (pendingTask.completed) {
return;
}
pendingTask.completed = true;
this.pendingTasks.delete(pendingTask.id);
logger2.debug(`rejecting task [name:${pendingTask.name}]: %s`, String(error));
reject(error);
if (canExecuteNextTask) {
const [nextPendingTask] = this.pendingTasks.values();
if (nextPendingTask && !nextPendingTask.executedAt) {
void this.execute(nextPendingTask);
}
}
}
};
this.pendingTasks.set(pendingTask.id, pendingTask);
if (this.pendingTasks.size === 1) {
void this.execute(pendingTask);
}
});
});
}
stop() {
logger2.debug("stop()");
for (const pendingTask of this.pendingTasks.values()) {
logger2.debug(`stop() | stopping task [name:${pendingTask.name}]`);
pendingTask.reject(new errors_1.AwaitQueueStoppedError(), {
canExecuteNextTask: false
});
}
}
remove(taskIdx) {
logger2.debug(`remove() [taskIdx:${taskIdx}]`);
const pendingTask = Array.from(this.pendingTasks.values())[taskIdx];
if (!pendingTask) {
logger2.debug(`stop() | no task with given idx [taskIdx:${taskIdx}]`);
return;
}
pendingTask.reject(new errors_1.AwaitQueueRemovedTaskError(), {
canExecuteNextTask: true
});
}
dump() {
const now = Date.now();
let idx = 0;
return Array.from(this.pendingTasks.values()).map((pendingTask) => ({
idx: idx++,
task: pendingTask.task,
name: pendingTask.name,
enqueuedTime: pendingTask.executedAt ? pendingTask.executedAt - pendingTask.enqueuedAt : now - pendingTask.enqueuedAt,
executionTime: pendingTask.executedAt ? now - pendingTask.executedAt : 0
}));
}
execute(pendingTask) {
return __async(this, null, function* () {
logger2.debug(`execute() [name:${pendingTask.name}]`);
if (pendingTask.executedAt) {
throw new Error("task already being executed");
}
pendingTask.executedAt = Date.now();
try {
const result2 = yield pendingTask.task();
pendingTask.resolve(result2);
} catch (error) {
pendingTask.reject(error, { canExecuteNextTask: true });
}
});
}
};
exports.AwaitQueue = AwaitQueue;
}
});
// ../../node_modules/.pnpm/awaitqueue@3.3.0_supports-color@10.2.2/node_modules/awaitqueue/lib/index.js
var require_lib3 = __commonJS({
"../../node_modules/.pnpm/awaitqueue@3.3.0_supports-color@10.2.2/node_modules/awaitqueue/lib/index.js"(exports) {
"use strict";
init_process();
Object.defineProperty(exports, "__esModule", { value: true });
exports.AwaitQueueRemovedTaskError = exports.AwaitQueueStoppedError = exports.AwaitQueue = void 0;
var AwaitQueue_1 = require_AwaitQueue();
Object.defineProperty(exports, "AwaitQueue", { enumerable: true, get: function() {
return AwaitQueue_1.AwaitQueue;
} });
var errors_1 = require_errors2();
Object.defineProperty(exports, "AwaitQueueStoppedError", { enumerable: true, get: function() {
return errors_1.AwaitQueueStoppedError;
} });
Object.defineProperty(exports, "AwaitQueueRemovedTaskError", { enumerable: true, get: function() {
return errors_1.AwaitQueueRemovedTaskError;
} });
}
});
// ../../node_modules/.pnpm/mediasoup-client@3.18.3/node_modules/mediasoup-client/lib/Producer.js
var require_Producer = __commonJS({
"../../node_modules/.pnpm/mediasoup-client@3.18.3/node_modules/mediasoup-client/lib/Producer.js"(exports) {
"use strict";
init_process();
Object.defineProperty(exports, "__esModule", { value: true });
exports.Producer = void 0;
var Logger_1 = require_Logger();
var enhancedEvents_1 = require_enhancedEvents();
var errors_1 = require_errors();
var logger2 = new Logger_1.Logger("Producer");
var Producer = class extends enhancedEvents_1.EnhancedEventEmitter {
constructor({ id, localId, rtpSender, track, rtpParameters, stopTracks, disableTrackOnPause, zeroRtpOnPause, appData }) {
super();
// Id.
__publicField(this, "_id");
// Local id.
__publicField(this, "_localId");
// Closed flag.
__publicField(this, "_closed", false);
// Associated RTCRtpSender.
__publicField(this, "_rtpSender");
// Local track.
__publicField(this, "_track");
// Producer kind.
__publicField(this, "_kind");
// RTP parameters.
__publicField(this, "_rtpParameters");
// Paused flag.
__publicField(this, "_paused");
// Video max spatial layer.
__publicField(this, "_maxSpatialLayer");
// Whether the Producer should call stop() in given tracks.
__publicField(this, "_stopTracks");
// Whether the Producer should set track.enabled = false when paused.
__publicField(this, "_disableTrackOnPause");
// Whether we should mark the transceiver as inactive when paused.
__publicField(this, "_zeroRtpOnPause");
// App custom data.
__publicField(this, "_appData");
// Observer instance.
__publicField(this, "_observer", new enhancedEvents_1.EnhancedEventEmitter());
logger2.debug("constructor()");
this._id = id;
this._localId = localId;
this._rtpSender = rtpSender;
this._track = track;
this._kind = track.kind;
this._rtpParameters = rtpParameters;
this._paused = disableTrackOnPause ? !track.enabled : false;
this._maxSpatialLayer = void 0;
this._stopTracks = stopTracks;
this._disableTrackOnPause = disableTrackOnPause;
this._zeroRtpOnPause = zeroRtpOnPause;
this._appData = appData != null ? appData : {};
this.onTrackEnded = this.onTrackEnded.bind(this);
this.handleTrack();
}
/**
* Producer id.
*/
get id() {
return this._id;
}
/**
* Local id.
*/
get localId() {
return this._localId;
}
/**
* Whether the Producer is closed.
*/
get closed() {
return this._closed;
}
/**
* Media kind.
*/
get kind() {
return this._kind;
}
/**
* Associated RTCRtpSender.
*/
get rtpSender() {
return this._rtpSender;
}
/**
* The associated track.
*/
get track() {
return this._track;
}
/**
* RTP parameters.
*/
get rtpParameters() {
return this._rtpParameters;
}
/**
* Whether the Producer is paused.
*/
get paused() {
return this._paused;
}
/**
* Max spatial layer.
*
* @type {Number | undefined}
*/
get maxSpatialLayer() {
return this._maxSpatialLayer;
}
/**
* App custom data.
*/
get appData() {
return this._appData;
}
/**
* App custom data setter.
*/
set appData(appData) {
this._appData = appData;
}
get observer() {
return this._observer;
}
/**
* Closes the Producer.
*/
close() {
if (this._closed) {
return;
}
logger2.debug("close()");
this._closed = true;
this.destroyTrack();
this.emit("@close");
this._observer.safeEmit("close");
super.close();
this._observer.close();
}
/**
* Transport was closed.
*/
transportClosed() {
if (this._closed) {
return;
}
logger2.debug("transportClosed()");
this._closed = true;
this.destroyTrack();
this.safeEmit("transportclose");
this._observer.safeEmit("close");
}
/**
* Get associated RTCRtpSender stats.
*/
getStats() {
return __async(this, null, function* () {
if (this._closed) {
throw new errors_1.InvalidStateError("closed");
}
return new Promise((resolve, reject) => {
this.safeEmit("@getstats", resolve, reject);
});
});
}
/**
* Pauses sending media.
*/
pause() {
logger2.debug("pause()");
if (this._closed) {
logger2.error("pause() | Producer closed");
return;
}
this._paused = true;
if (this._track && this._disableTrackOnPause) {
this._track.enabled = false;
}
if (this._zeroRtpOnPause) {
new Promise((resolve, reject) => {
this.safeEmit("@pause", resolve, reject);
}).catch(() => {
});
}
this._observer.safeEmit("pause");
}
/**
* Resumes sending media.
*/
resume() {
logger2.debug("resume()");
if (this._closed) {
logger2.error("resume() | Producer closed");
return;
}
this._paused = false;
if (this._track && this._disableTrackOnPause) {
this._track.enabled = true;
}
if (this._zeroRtpOnPause) {
new Promise((resolve, reject) => {
this.safeEmit("@resume", resolve, reject);
}).catch(() => {
});
}
this._observer.safeEmit("resume");
}
/**
* Replaces the current track with a new one or null.
*/
replaceTrack(_0) {
return __async(this, arguments, function* ({ track }) {
logger2.debug("replaceTrack() [track:%o]", track);
if (this._closed) {
if (track && this._stopTracks) {
try {
track.stop();
} catch (error) {
}
}
throw new errors_1.InvalidStateError("closed");
} else if ((track == null ? void 0 : track.readyState) === "ended") {
throw new errors_1.InvalidStateError("track ended");
}
if (track === this._track) {
logger2.debug("replaceTrack() | same track, ignored");
return;
}
yield new Promise((resolve, reject) => {
this.safeEmit("@replacetrack", track, resolve, reject);
});
this.destroyTrack();
this._track = track;
if (this._track && this._disableTrackOnPause) {
if (!this._paused) {
this._track.enabled = true;
} else if (this._paused) {
this._track.enabled = false;
}
}
this.handleTrack();
});
}
/**
* Sets the video max spatial layer to be sent.
*/
setMaxSpatialLayer(spatialLayer) {
return __async(this, null, function* () {
if (this._closed) {
throw new errors_1.InvalidStateError("closed");
} else if (this._kind !== "video") {
throw new errors_1.UnsupportedError("not a video Producer");
} else if (typeof spatialLayer !== "number") {
throw new TypeError("invalid spatialLayer");
}
if (spatialLayer === this._maxSpatialLayer) {
return;
}
yield new Promise((resolve, reject) => {
this.safeEmit("@setmaxspatiallayer", spatialLayer, resolve, reject);
}).catch(() => {
});
this._maxSpatialLayer = spatialLayer;
});
}
setRtpEncodingParameters(params) {
return __async(this, null, function* () {
if (this._closed) {
throw new errors_1.InvalidStateError("closed");
} else if (typeof params !== "object") {
throw new TypeError("invalid params");
}
yield new Promise((resolve, reject) => {
this.safeEmit("@setrtpencodingparameters", params, resolve, reject);
});
});
}
onTrackEnded() {
logger2.debug('track "ended" event');
this.safeEmit("trackended");
this._observer.safeEmit("trackended");
}
handleTrack() {
if (!this._track) {
return;
}
this._track.addEventListener("ended", this.onTrackEnded);
}
destroyTrack() {
if (!this._track) {
return;
}
try {
this._track.removeEventListener("ended", this.onTrackEnded);
if (this._stopTracks) {
this._track.stop();
}
} catch (error) {
}
}
};
exports.Producer = Producer;
}
});
// ../../node_modules/.pnpm/mediasoup-client@3.18.3/node_modules/mediasoup-client/lib/Consumer.js
var require_Consumer = __commonJS({
"../../node_modules/.pnpm/mediasoup-client@3.18.3/node_modules/mediasoup-client/lib/Consumer.js"(exports) {
"use strict";
init_process();
Object.defineProperty(exports, "__esModule", { value: true });
exports.Consumer = void 0;
var Logger_1 = require_Logger();
var enhancedEvents_1 = require_enhancedEvents();
var errors_1 = require_errors();
var logger2 = new Logger_1.Logger("Consumer");
var Consumer = class extends enhancedEvents_1.EnhancedEventEmitter {
constructor({ id, localId, producerId, rtpReceiver, track, rtpParameters, appData }) {
super();
// Id.
__publicField(this, "_id");
// Local id.
__publicField(this, "_localId");
// Associated Producer id.
__publicField(this, "_producerId");
// Closed flag.
__publicField(this, "_closed", false);
// Associated RTCRtpReceiver.
__publicField(this, "_rtpReceiver");
// Remote track.
__publicField(this, "_track");
// RTP parameters.
__publicField(this, "_rtpParameters");
// Paused flag.
__publicField(this, "_paused");
// App custom data.
__publicField(this, "_appData");
// Observer instance.
__publicField(this, "_observer", new enhancedEvents_1.EnhancedEventEmitter());
logger2.debug("constructor()");
this._id = id;
this._localId = localId;
this._producerId = producerId;
this._rtpReceiver = rtpReceiver;
this._track = track;
this._rtpParameters = rtpParameters;
this._paused = !track.enabled;
this._appData = appData != null ? appData : {};
this.onTrackEnded = this.onTrackEnded.bind(this);
this.handleTrack();
}
/**
* Consumer id.
*/
get id() {
return this._id;
}
/**
* Local id.
*/
get localId() {
return this._localId;
}
/**
* Associated Producer id.
*/
get producerId() {
return this._producerId;
}
/**
* Whether the Consumer is closed.
*/
get closed() {
return this._closed;
}
/**
* Media kind.
*/
get kind() {
return this._track.kind;
}
/**
* Associated RTCRtpReceiver.
*/
get rtpReceiver() {
return this._rtpReceiver;
}
/**
* The associated track.
*/
get track() {
return this._track;
}
/**
* RTP parameters.
*/
get rtpParameters() {
return this._rtpParameters;
}
/**
* Whether the Consumer is paused.
*/
get paused() {
return this._paused;
}
/**
* App custom data.
*/
get appData() {
return this._appData;
}
/**
* App custom data setter.
*/
set appData(appData) {
this._appData = appData;
}
get observer() {
return this._observer;
}
/**
* Closes the Consumer.
*/
close() {
if (this._closed) {
return;
}
logger2.debug("close()");
this._closed = true;
this.destroyTrack();
this.emit("@close");
this._observer.safeEmit("close");
super.close();
this._observer.close();
}
/**
* Transport was closed.
*/
transportClosed() {
if (this._closed) {
return;
}
logger2.debug("transportClosed()");
this._closed = true;
this.destroyTrack();
this.safeEmit("transportclose");
this._observer.safeEmit("close");
}
/**
* Get associated RTCRtpReceiver stats.
*/
getStats() {
return __async(this, null, function* () {
if (this._closed) {
throw new errors_1.InvalidStateError("closed");
}
return new Promise((resolve, reject) => {
this.safeEmit("@getstats", resolve, reject);
});
});
}
/**
* Pauses receiving media.
*/
pause() {
logger2.debug("pause()");
if (this._closed) {
logger2.error("pause() | Consumer closed");
return;
}
if (this._paused) {
logger2.debug("pause() | Consumer is already paused");
return;
}
this._paused = true;
this._track.enabled = false;
this.emit("@pause");
this._observer.safeEmit("pause");
}
/**
* Resumes receiving media.
*/
resume() {
logger2.debug("resume()");
if (this._closed) {
logger2.error("resume() | Consumer closed");
return;
}
if (!this._paused) {
logger2.debug("resume() | Consumer is already resumed");
return;
}
this._paused = false;
this._track.enabled = true;
this.emit("@resume");
this._observer.safeEmit("resume");
}
onTrackEnded() {
logger2.debug('track "ended" event');
this.safeEmit("trackended");
this._observer.safeEmit("trackended");
}
handleTrack() {
this._track.addEventListener("ended", this.onTrackEnded);
}
destroyTrack() {
try {
this._track.removeEventListener("ended", this.onTrackEnded);
this._track.stop();
} catch (error) {
}
}
};
exports.Consumer = Consumer;
}
});
// ../../node_modules/.pnpm/mediasoup-client@3.18.3/node_modules/mediasoup-client/lib/DataProducer.js
var require_DataProducer = __commonJS({
"../../node_modules/.pnpm/mediasoup-client@3.18.3/node_modules/mediasoup-client/lib/DataProducer.js"(exports) {
"use strict";
init_process();
Object.defineProperty(exports, "__esModule", { value: true });
exports.DataProducer = void 0;
var Logger_1 = require_Logger();
var enhancedEvents_1 = require_enhancedEvents();
var errors_1 = require_errors();
var logger2 = new Logger_1.Logger("DataProducer");
var DataProducer = class extends enhancedEvents_1.EnhancedEventEmitter {
constructor({ id, dataChannel, sctpStreamParameters, appData }) {
super();
// Id.
__publicField(this, "_id");
// The underlying RTCDataChannel instance.
__publicField(this, "_dataChannel");
// Closed flag.
__publicField(this, "_closed", false);
// SCTP stream parameters.
__publicField(this, "_sctpStreamParameters");
// App custom data.
__publicField(this, "_appData");
// Observer instance.
__publicField(this, "_observer", new enhancedEvents_1.EnhancedEventEmitter());
logger2.debug("constructor()");
this._id = id;
this._dataChannel = dataChannel;
this._sctpStreamParameters = sctpStreamParameters;
this._appData = appData != null ? appData : {};
this.handleDataChannel();
}
/**
* DataProducer id.
*/
get id() {
return this._id;
}
/**
* Whether the DataProducer is closed.
*/
get closed() {
return this._closed;
}
/**
* SCTP stream parameters.
*/
get sctpStreamParameters() {
return this._sctpStreamParameters;
}
/**
* DataChannel readyState.
*/
get readyState() {
return this._dataChannel.readyState;
}
/**
* DataChannel label.
*/
get label() {
return this._dataChannel.label;
}
/**
* DataChannel protocol.
*/
get protocol() {
return this._dataChannel.protocol;
}
/**
* DataChannel bufferedAmount.
*/
get bufferedAmount() {
return this._dataChannel.bufferedAmount;
}
/**
* DataChannel bufferedAmountLowThreshold.
*/
get bufferedAmountLowThreshold() {
return this._dataChannel.bufferedAmountLowThreshold;
}
/**
* Set DataChannel bufferedAmountLowThreshold.
*/
set bufferedAmountLowThreshold(bufferedAmountLowThreshold) {
this._dataChannel.bufferedAmountLowThreshold = bufferedAmountLowThreshold;
}
/**
* App custom data.
*/
get appData() {
return this._appData;
}
/**
* App custom data setter.
*/
set appData(appData) {
this._appData = appData;
}
get observer() {
return this._observer;
}
/**
* Closes the DataProducer.
*/
close() {
if (this._closed) {
return;
}
logger2.debug("close()");
this._closed = true;
this._dataChannel.close();
this.emit("@close");
this._observer.safeEmit("close");
super.close();
this._observer.close();
}
/**
* Transport was closed.
*/
transportClosed() {
if (this._closed) {
return;
}
logger2.debug("transportClosed()");
this._closed = true;
this._dataChannel.close();
this.safeEmit("transportclose");
this._observer.safeEmit("close");
}
/**
* Send a message.
*
* @param {String|Blob|ArrayBuffer|ArrayBufferView} data.
*/
// eslint-disable-next-line @typescript-eslint/no-explicit-any
send(data) {
logger2.debug("send()");
if (this._closed) {
throw new errors_1.InvalidStateError("closed");
}
this._dataChannel.send(data);
}
handleDataChannel() {
this._dataChannel.addEventListener("open", () => {
if (this._closed) {
return;
}
logger2.debug('DataChannel "open" event');
this.safeEmit("open");
});
this._dataChannel.addEventListener("error", (event) => {
var _a2, _b2, _c;
if (this._closed) {
return;
}
const error = (_a2 = event.error) != null ? _a2 : new Error("unknown DataChannel error");
if (((_b2 = event.error) == null ? void 0 : _b2.errorDetail) === "sctp-failure") {
logger2.error("DataChannel SCTP error [sctpCauseCode:%s]: %s", (_c = event.error) == null ? void 0 : _c.sctpCauseCode, event.error.message);
} else {
logger2.error('DataChannel "error" event: %o', error);
}
this.safeEmit("error", error);
});
this._dataChannel.addEventListener("close", () => {
if (this._closed) {
return;
}
logger2.warn('DataChannel "close" event');
this._closed = true;
this.emit("@close");
this.safeEmit("close");
this._observer.safeEmit("close");
});
this._dataChannel.addEventListener("message", () => {
if (this._closed) {
return;
}
logger2.warn('DataChannel "message" event in a DataProducer, message discarded');
});
this._dataChannel.addEventListener("bufferedamountlow", () => {
if (this._closed) {
return;
}
this.safeEmit("bufferedamountlow");
});
}
};
exports.DataProducer = DataProducer;
}
});
// ../../node_modules/.pnpm/mediasoup-client@3.18.3/node_modules/mediasoup-client/lib/DataConsumer.js
var require_DataConsumer = __commonJS({
"../../node_modules/.pnpm/mediasoup-client@3.18.3/node_modules/mediasoup-client/lib/DataConsumer.js"(exports) {
"use strict";
init_process();
Object.defineProperty(exports, "__esModule", { value: true });
exports.DataConsumer = void 0;
var Logger_1 = require_Logger();
var enhancedEvents_1 = require_enhancedEvents();
var logger2 = new Logger_1.Logger("DataConsumer");
var DataConsumer = class extends enhancedEvents_1.EnhancedEventEmitter {
constructor({ id, dataProducerId, dataChannel, sctpStreamParameters, appData }) {
super();
// Id.
__publicField(this, "_id");
// Associated DataProducer Id.
__publicField(this, "_dataProducerId");
// The underlying RTCDataChannel instance.
__publicField(this, "_dataChannel");
// Closed flag.
__publicField(this, "_closed", false);
// SCTP stream parameters.
__publicField(this, "_sctpStreamParameters");
// App custom data.
__publicField(this, "_appData");
// Observer instance.
__publicField(this, "_observer", new enhancedEvents_1.EnhancedEventEmitter());
logger2.debug("constructor()");
this._id = id;
this._dataProducerId = dataProducerId;
this._dataChannel = dataChannel;
this._sctpStreamParameters = sctpStreamParameters;
this._appData = appData != null ? appData : {};
this.handleDataChannel();
}
/**
* DataConsumer id.
*/
get id() {
return this._id;
}
/**
* Associated DataProducer id.
*/
get dataProducerId() {
return this._dataProducerId;
}
/**
* Whether the DataConsumer is closed.
*/
get closed() {
return this._closed;
}
/**
* SCTP stream parameters.
*/
get sctpStreamParameters() {
return this._sctpStreamParameters;
}
/**
* DataChannel readyState.
*/
get readyState() {
return this._dataChannel.readyState;
}
/**
* DataChannel label.
*/
get label() {
return this._dataChannel.label;
}
/**
* DataChannel protocol.
*/
get protocol() {
return this._dataChannel.protocol;
}
/**
* DataChannel binaryType.
*/
get binaryType() {
return this._dataChannel.binaryType;
}
/**
* Set DataChannel binaryType.
*/
set binaryType(binaryType) {
this._dataChannel.binaryType = binaryType;
}
/**
* App custom data.
*/
get appData() {
return this._appData;
}
/**
* App custom data setter.
*/
set appData(appData) {
this._appData = appData;
}
get observer() {
return this._observer;
}
/**
* Closes the DataConsumer.
*/
close() {
if (this._closed) {
return;
}
logger2.debug("close()");
this._closed = true;
this._dataChannel.close();
this.emit("@close");
this._observer.safeEmit("close");
super.close();
this._observer.close();
}
/**
* Transport was closed.
*/
transportClosed() {
if (this._closed) {
return;
}
logger2.debug("transportClosed()");
this._closed = true;
this._dataChannel.close();
this.safeEmit("transportclose");
this._observer.safeEmit("close");
}
handleDataChannel() {
this._dataChannel.addEventListener("open", () => {
if (this._closed) {
return;
}
logger2.debug('DataChannel "open" event');
this.safeEmit("open");
});
this._dataChannel.addEventListener("error", (event) => {
var _a2, _b2, _c;
if (this._closed) {
return;
}
const error = (_a2 = event.error) != null ? _a2 : new Error("unknown DataChannel error");
if (((_b2 = event.error) == null ? void 0 : _b2.errorDetail) === "sctp-failure") {
logger2.error("DataChannel SCTP error [sctpCauseCode:%s]: %s", (_c = event.error) == null ? void 0 : _c.sctpCauseCode, event.error.message);
} else {
logger2.error('DataChannel "error" event: %o', error);
}
this.safeEmit("error", error);
});
this._dataChannel.addEventListener("close", () => {
if (this._closed) {
return;
}
logger2.warn('DataChannel "close" event');
this._closed = true;
this.emit("@close");
this.safeEmit("close");
this._observer.safeEmit("close");
});
this._dataChannel.addEventListener("message", (event) => {
if (this._closed) {
return;
}
this.safeEmit("message", event.data);
});
}
};
exports.DataConsumer = DataConsumer;
}
});
// ../../node_modules/.pnpm/mediasoup-client@3.18.3/node_modules/mediasoup-client/lib/Transport.js
var require_Transport = __commonJS({
"../../node_modules/.pnpm/mediasoup-client@3.18.3/node_modules/mediasoup-client/lib/Transport.js"(exports) {
"use strict";
init_process();
Object.defineProperty(exports, "__esModule", { value: true });
exports.Transport = void 0;
var awaitqueue_1 = require_lib3();
var Logger_1 = require_Logger();
var enhancedEvents_1 = require_enhancedEvents();
var errors_1 = require_errors();
var utils = require_utils();
var ortc = require_ortc();
var Producer_1 = require_Producer();
var Consumer_1 = require_Consumer();
var DataProducer_1 = require_DataProducer();
var DataConsumer_1 = require_DataConsumer();
var logger2 = new Logger_1.Logger("Transport");
var ConsumerCreationTask = class {
constructor(consumerOptions) {
__publicField(this, "consumerOptions");
__publicField(this, "promise");
__publicField(this, "resolve");
__publicField(this, "reject");
this.consumerOptions = consumerOptions;
this.promise = new Promise((resolve, reject) => {
this.resolve = resolve;
this.reject = reject;
});
}
};
var Transport = class extends enhancedEvents_1.EnhancedEventEmitter {
constructor({ direction, id, iceParameters, iceCandidates, dtlsParameters, sctpParameters, iceServers, iceTransportPolicy, additionalSettings, appData, handlerFactory, getSendExtendedRtpCapabilities, recvRtpCapabilities, canProduceByKind }) {
var _a2;
super();
// Id.
__publicField(this, "_id");
// Closed flag.
__publicField(this, "_closed", false);
// Direction.
__publicField(this, "_direction");
// Callback for sending Transports to request sending extended RTP capabilities
// on demand.
__publicField(this, "_getSendExtendedRtpCapabilities");
// Recv RTP capabilities.
__publicField(this, "_recvRtpCapabilities");
// Whether we can produce audio/video based on computed extended RTP
// capabilities.
__publicField(this, "_canProduceByKind");
// SCTP max message size if enabled, null otherwise.
__publicField(this, "_maxSctpMessageSize");
// RTC handler isntance.
__publicField(this, "_handler");
// Transport ICE gathering state.
__publicField(this, "_iceGatheringState", "new");
// Transport connection state.
__publicField(this, "_connectionState", "new");
// App custom data.
__publicField(this, "_appData");
// Map of Producers indexed by id.
__publicField(this, "_producers", /* @__PURE__ */ new Map());
// Map of Consumers indexed by id.
__publicField(this, "_consumers", /* @__PURE__ */ new Map());
// Map of DataProducers indexed by id.
__publicField(this, "_dataProducers", /* @__PURE__ */ new Map());
// Map of DataConsumers indexed by id.
__publicField(this, "_dataConsumers", /* @__PURE__ */ new Map());
// Whether the Consumer for RTP probation has been created.
__publicField(this, "_probatorConsumerCreated", false);
// AwaitQueue instance to make async tasks happen sequentially.
__publicField(this, "_awaitQueue", new awaitqueue_1.AwaitQueue());
// Consumer creation tasks awaiting to be processed.
__publicField(this, "_pendingConsumerTasks", []);
// Consumer creation in progress flag.
__publicField(this, "_consumerCreationInProgress", false);
// Consumers pending to be paused.
__publicField(this, "_pendingPauseConsumers", /* @__PURE__ */ new Map());
// Consumer pause in progress flag.
__publicField(this, "_consumerPauseInProgress", false);
// Consumers pending to be resumed.
__publicField(this, "_pendingResumeConsumers", /* @__PURE__ */ new Map());
// Consumer resume in progress flag.
__publicField(this, "_consumerResumeInProgress", false);
// Consumers pending to be closed.
__publicField(this, "_pendingCloseConsumers", /* @__PURE__ */ new Map());
// Consumer close in progress flag.
__publicField(this, "_consumerCloseInProgress", false);
// Observer instance.
__publicField(this, "_observer", new enhancedEvents_1.EnhancedEventEmitter());
logger2.debug("constructor() [id:%s, direction:%s]", id, direction);
this._id = id;
this._direction = direction;
this._getSendExtendedRtpCapabilities = getSendExtendedRtpCapabilities;
this._recvRtpCapabilities = recvRtpCapabilities;
this._canProduceByKind = canProduceByKind;
this._maxSctpMessageSize = sctpParameters ? sctpParameters.maxMessageSize : null;
const clonedAdditionalSettings = (_a2 = utils.clone(additionalSettings)) != null ? _a2 : {};
delete clonedAdditionalSettings.iceServers;
delete clonedAdditionalSettings.iceTransportPolicy;
delete clonedAdditionalSettings.bundlePolicy;
delete clonedAdditionalSettings.rtcpMuxPolicy;
this._handler = handlerFactory.factory({
direction,
iceParameters,
iceCandidates,
dtlsParameters,
sctpParameters,
iceServers,
iceTransportPolicy,
additionalSettings: clonedAdditionalSettings,
getSendExtendedRtpCapabilities: this._getSendExtendedRtpCapabilities
});
this._appData = appData != null ? appData : {};
this.handleHandler();
}
/**
* Transport id.
*/
get id() {
return this._id;
}
/**
* Whether the Transport is closed.
*/
get closed() {
return this._closed;
}
/**
* Transport direction.
*/
get direction() {
return this._direction;
}
/**
* RTC handler instance.
*/
get handler() {
return this._handler;
}
/**
* ICE gathering state.
*/
get iceGatheringState() {
return this._iceGatheringState;
}
/**
* Connection state.
*/
get connectionState() {
return this._connectionState;
}
/**
* App custom data.
*/
get appData() {
return this._appData;
}
/**
* App custom data setter.
*/
set appData(appData) {
this._appData = appData;
}
get observer() {
return this._observer;
}
/**
* Close the Transport.
*/
close() {
if (this._closed) {
return;
}
logger2.debug("close()");
this._closed = true;
this._awaitQueue.stop();
this._handler.close();
this._connectionState = "closed";
for (const producer of this._producers.values()) {
producer.transportClosed();
}
this._producers.clear();
for (const consumer of this._consumers.values()) {
consumer.transportClosed();
}
this._consumers.clear();
for (const dataProducer of this._dataProducers.values()) {
dataProducer.transportClosed();
}
this._dataProducers.clear();
for (const dataConsumer of this._dataConsumers.values()) {
dataConsumer.transportClosed();
}
this._dataConsumers.clear();
this._observer.safeEmit("close");
super.close();
this._observer.close();
}
/**
* Get associated Transport (RTCPeerConnection) stats.
*
* @returns {RTCStatsReport}
*/
getStats() {
return __async(this, null, function* () {
if (this._closed) {
throw new errors_1.InvalidStateError("closed");
}
return this._handler.getTransportStats();
});
}
/**
* Restart ICE connection.
*/
restartIce(_0) {
return __async(this, arguments, function* ({ iceParameters }) {
logger2.debug("restartIce()");
if (this._closed) {
throw new errors_1.InvalidStateError("closed");
} else if (!iceParameters) {
throw new TypeError("missing iceParameters");
}
return this._awaitQueue.push(() => __async(this, null, function* () {
return yield this._handler.restartIce(iceParameters);
}), "transport.restartIce()");
});
}
/**
* Update ICE servers.
*/
updateIceServers() {
return __async(this, arguments, function* ({ iceServers } = {}) {
logger2.debug("updateIceServers()");
if (this._closed) {
throw new errors_1.InvalidStateError("closed");
} else if (!Array.isArray(iceServers)) {
throw new TypeError("missing iceServers");
}
return this._awaitQueue.push(() => __async(this, null, function* () {
return this._handler.updateIceServers(iceServers);
}), "transport.updateIceServers()");
});
}
/**
* Create a Producer.
*/
produce() {
return __async(this, arguments, function* ({ track, streamId, encodings, codecOptions, headerExtensionOptions, codec, stopTracks = true, disableTrackOnPause = true, zeroRtpOnPause = false, onRtpSender, appData = {} } = {}) {
logger2.debug("produce() [track:%o]", track);
if (this._closed) {
throw new errors_1.InvalidStateError("closed");
} else if (!track) {
throw new TypeError("missing track");
} else if (this._direction !== "send") {
throw new errors_1.UnsupportedError("not a sending Transport");
} else if (!this._canProduceByKind[track.kind]) {
throw new errors_1.UnsupportedError(`cannot produce ${track.kind}`);
} else if (track.readyState === "ended") {
throw new errors_1.InvalidStateError("track ended");
} else if (this.listenerCount("connect") === 0 && this._connectionState === "new") {
throw new TypeError('no "connect" listener set into this transport');
} else if (this.listenerCount("produce") === 0) {
throw new TypeError('no "produce" listener set into this transport');
} else if (appData && typeof appData !== "object") {
throw new TypeError("if given, appData must be an object");
}
return this._awaitQueue.push(() => __async(this, null, function* () {
let normalizedEncodings;
if (encodings && !Array.isArray(encodings)) {
throw TypeError("encodings must be an array");
} else if ((encodings == null ? void 0 : encodings.length) === 0) {
normalizedEncodings = void 0;
} else if (encodings) {
normalizedEncodings = encodings.map((encoding) => {
const normalizedEncoding = {
active: true
};
if (encoding.active === false) {
normalizedEncoding.active = false;
}
if (typeof encoding.dtx === "boolean") {
normalizedEncoding.dtx = encoding.dtx;
}
if (typeof encoding.scalabilityMode === "string") {
normalizedEncoding.scalabilityMode = encoding.scalabilityMode;
}
if (typeof encoding.scaleResolutionDownBy === "number") {
normalizedEncoding.scaleResolutionDownBy = encoding.scaleResolutionDownBy;
}
if (typeof encoding.maxBitrate === "number") {
normalizedEncoding.maxBitrate = encoding.maxBitrate;
}
if (typeof encoding.maxFramerate === "number") {
normalizedEncoding.maxFramerate = encoding.maxFramerate;
}
if (typeof encoding.adaptivePtime === "boolean") {
normalizedEncoding.adaptivePtime = encoding.adaptivePtime;
}
if (typeof encoding.priority === "string") {
normalizedEncoding.priority = encoding.priority;
}
if (typeof encoding.networkPriority === "string") {
normalizedEncoding.networkPriority = encoding.networkPriority;
}
return normalizedEncoding;
});
}
const { localId, rtpParameters, rtpSender } = yield this._handler.send({
track,
streamId,
encodings: normalizedEncodings,
codecOptions,
headerExtensionOptions,
codec,
onRtpSender
});
try {
ortc.validateAndNormalizeRtpParameters(rtpParameters);
const { id } = yield new Promise((resolve, reject) => {
this.safeEmit("produce", {
kind: track.kind,
rtpParameters,
appData
}, resolve, reject);
});
const producer = new Producer_1.Producer({
id,
localId,
rtpSender,
track,
rtpParameters,
stopTracks,
disableTrackOnPause,
zeroRtpOnPause,
appData
});
this._producers.set(producer.id, producer);
this.handleProducer(producer);
this._observer.safeEmit("newproducer", producer);
return producer;
} catch (error) {
this._handler.stopSending(localId).catch(() => {
});
throw error;
}
}), "transport.produce()").catch((error) => {
if (stopTracks) {
try {
track.stop();
} catch (error2) {
}
}
throw error;
});
});
}
/**
* Create a Consumer to consume a remote Producer.
*/
consume(_0) {
return __async(this, arguments, function* ({ id, producerId, kind, rtpParameters, streamId, onRtpReceiver, appData = {} }) {
logger2.debug("consume()");
if (this._closed) {
throw new errors_1.InvalidStateError("closed");
} else if (this._direction !== "recv") {
throw new errors_1.UnsupportedError("not a receiving Transport");
} else if (typeof id !== "string") {
throw new TypeError("missing id");
} else if (typeof producerId !== "string") {
throw new TypeError("missing producerId");
} else if (kind !== "audio" && kind !== "video") {
throw new TypeError(`invalid kind '${kind}'`);
} else if (this.listenerCount("connect") === 0 && this._connectionState === "new") {
throw new TypeError('no "connect" listener set into this transport');
} else if (appData && typeof appData !== "object") {
throw new TypeError("if given, appData must be an object");
}
const clonedRtpParameters = utils.clone(rtpParameters);
const canConsume = ortc.canReceive(clonedRtpParameters, this._recvRtpCapabilities);
if (!canConsume) {
throw new errors_1.UnsupportedError("cannot consume this Producer");
}
const consumerCreationTask = new ConsumerCreationTask({
id,
producerId,
kind,
rtpParameters: clonedRtpParameters,
streamId,
onRtpReceiver,
appData
});
this._pendingConsumerTasks.push(consumerCreationTask);
queueMicrotask(() => {
if (this._closed) {
return;
}
if (this._consumerCreationInProgress === false) {
this.createPendingConsumers();
}
});
return consumerCreationTask.promise;
});
}
/**
* Create a DataProducer
*/
produceData() {
return __async(this, arguments, function* ({ ordered = true, maxPacketLifeTime, maxRetransmits, label = "", protocol = "", appData = {} } = {}) {
logger2.debug("produceData()");
if (this._closed) {
throw new errors_1.InvalidStateError("closed");
} else if (this._direction !== "send") {
throw new errors_1.UnsupportedError("not a sending Transport");
} else if (!this._maxSctpMessageSize) {
throw new errors_1.UnsupportedError("SCTP not enabled by remote Transport");
} else if (this.listenerCount("connect") === 0 && this._connectionState === "new") {
throw new TypeError('no "connect" listener set into this transport');
} else if (this.listenerCount("producedata") === 0) {
throw new TypeError('no "producedata" listener set into this transport');
} else if (appData && typeof appData !== "object") {
throw new TypeError("if given, appData must be an object");
}
if (maxPacketLifeTime || maxRetransmits) {
ordered = false;
}
return this._awaitQueue.push(() => __async(this, null, function* () {
const { dataChannel, sctpStreamParameters } = yield this._handler.sendDataChannel({
ordered,
maxPacketLifeTime,
maxRetransmits,
label,
protocol
});
ortc.validateAndNormalizeSctpStreamParameters(sctpStreamParameters);
const { id } = yield new Promise((resolve, reject) => {
this.safeEmit("producedata", {
sctpStreamParameters,
label,
protocol,
appData
}, resolve, reject);
});
const dataProducer = new DataProducer_1.DataProducer({
id,
dataChannel,
sctpStreamParameters,
appData
});
this._dataProducers.set(dataProducer.id, dataProducer);
this.handleDataProducer(dataProducer);
this._observer.safeEmit("newdataproducer", dataProducer);
return dataProducer;
}), "transport.produceData()");
});
}
/**
* Create a DataConsumer
*/
consumeData(_0) {
return __async(this, arguments, function* ({ id, dataProducerId, sctpStreamParameters, label = "", protocol = "", appData = {} }) {
logger2.debug("consumeData()");
if (this._closed) {
throw new errors_1.InvalidStateError("closed");
} else if (this._direction !== "recv") {
throw new errors_1.UnsupportedError("not a receiving Transport");
} else if (!this._maxSctpMessageSize) {
throw new errors_1.UnsupportedError("SCTP not enabled by remote Transport");
} else if (typeof id !== "string") {
throw new TypeError("missing id");
} else if (typeof dataProducerId !== "string") {
throw new TypeError("missing dataProducerId");
} else if (this.listenerCount("connect") === 0 && this._connectionState === "new") {
throw new TypeError('no "connect" listener set into this transport');
} else if (appData && typeof appData !== "object") {
throw new TypeError("if given, appData must be an object");
}
const clonedSctpStreamParameters = utils.clone(sctpStreamParameters);
ortc.validateAndNormalizeSctpStreamParameters(clonedSctpStreamParameters);
return this._awaitQueue.push(() => __async(this, null, function* () {
const { dataChannel } = yield this._handler.receiveDataChannel({
sctpStreamParameters: clonedSctpStreamParameters,
label,
protocol
});
const dataConsumer = new DataConsumer_1.DataConsumer({
id,
dataProducerId,
dataChannel,
sctpStreamParameters: clonedSctpStreamParameters,
appData
});
this._dataConsumers.set(dataConsumer.id, dataConsumer);
this.handleDataConsumer(dataConsumer);
this._observer.safeEmit("newdataconsumer", dataConsumer);
return dataConsumer;
}), "transport.consumeData()");
});
}
// This method is guaranteed to never throw.
createPendingConsumers() {
this._consumerCreationInProgress = true;
this._awaitQueue.push(() => __async(this, null, function* () {
if (this._pendingConsumerTasks.length === 0) {
logger2.debug("createPendingConsumers() | there is no Consumer to be created");
return;
}
const pendingConsumerTasks = [...this._pendingConsumerTasks];
this._pendingConsumerTasks = [];
let videoConsumerForProbator = void 0;
const optionsList = [];
for (const task of pendingConsumerTasks) {
const { id, kind, rtpParameters, streamId, onRtpReceiver } = task.consumerOptions;
optionsList.push({
trackId: id,
kind,
rtpParameters,
streamId,
onRtpReceiver
});
}
try {
const results = yield this._handler.receive(optionsList);
for (let idx = 0; idx < results.length; ++idx) {
const task = pendingConsumerTasks[idx];
const result2 = results[idx];
const { id, producerId, kind, rtpParameters, appData } = task.consumerOptions;
const { localId, rtpReceiver, track } = result2;
const consumer = new Consumer_1.Consumer({
id,
localId,
producerId,
rtpReceiver,
track,
rtpParameters,
appData
});
this._consumers.set(consumer.id, consumer);
this.handleConsumer(consumer);
if (!this._probatorConsumerCreated && !videoConsumerForProbator && kind === "video") {
videoConsumerForProbator = consumer;
}
this._observer.safeEmit("newconsumer", consumer);
task.resolve(consumer);
}
} catch (error) {
for (const task of pendingConsumerTasks) {
task.reject(error);
}
}
if (videoConsumerForProbator) {
try {
const probatorRtpParameters = ortc.generateProbatorRtpParameters(videoConsumerForProbator.rtpParameters);
yield this._handler.receive([
{
trackId: "probator",
kind: "video",
rtpParameters: probatorRtpParameters
}
]);
logger2.debug("createPendingConsumers() | Consumer for RTP probation created");
this._probatorConsumerCreated = true;
} catch (error) {
logger2.error("createPendingConsumers() | failed to create Consumer for RTP probation:%o", error);
}
}
}), "transport.createPendingConsumers()").then(() => {
this._consumerCreationInProgress = false;
if (this._pendingConsumerTasks.length > 0) {
this.createPendingConsumers();
}
}).catch(() => {
});
}
pausePendingConsumers() {
this._consumerPauseInProgress = true;
this._awaitQueue.push(() => __async(this, null, function* () {
if (this._pendingPauseConsumers.size === 0) {
logger2.debug("pausePendingConsumers() | there is no Consumer to be paused");
return;
}
const pendingPauseConsumers = Array.from(this._pendingPauseConsumers.values());
this._pendingPauseConsumers.clear();
try {
const localIds = pendingPauseConsumers.map((consumer) => consumer.localId);
yield this._handler.pauseReceiving(localIds);
} catch (error) {
logger2.error("pausePendingConsumers() | failed to pause Consumers:", error);
}
}), "transport.pausePendingConsumers()").then(() => {
this._consumerPauseInProgress = false;
if (this._pendingPauseConsumers.size > 0) {
this.pausePendingConsumers();
}
}).catch(() => {
});
}
resumePendingConsumers() {
this._consumerResumeInProgress = true;
this._awaitQueue.push(() => __async(this, null, function* () {
if (this._pendingResumeConsumers.size === 0) {
logger2.debug("resumePendingConsumers() | there is no Consumer to be resumed");
return;
}
const pendingResumeConsumers = Array.from(this._pendingResumeConsumers.values());
this._pendingResumeConsumers.clear();
try {
const localIds = pendingResumeConsumers.map((consumer) => consumer.localId);
yield this._handler.resumeReceiving(localIds);
} catch (error) {
logger2.error("resumePendingConsumers() | failed to resume Consumers:", error);
}
}), "transport.resumePendingConsumers()").then(() => {
this._consumerResumeInProgress = false;
if (this._pendingResumeConsumers.size > 0) {
this.resumePendingConsumers();
}
}).catch(() => {
});
}
closePendingConsumers() {
this._consumerCloseInProgress = true;
this._awaitQueue.push(() => __async(this, null, function* () {
if (this._pendingCloseConsumers.size === 0) {
logger2.debug("closePendingConsumers() | there is no Consumer to be closed");
return;
}
const pendingCloseConsumers = Array.from(this._pendingCloseConsumers.values());
this._pendingCloseConsumers.clear();
try {
yield this._handler.stopReceiving(pendingCloseConsumers.map((consumer) => consumer.localId));
} catch (error) {
logger2.error("closePendingConsumers() | failed to close Consumers:", error);
}
}), "transport.closePendingConsumers()").then(() => {
this._consumerCloseInProgress = false;
if (this._pendingCloseConsumers.size > 0) {
this.closePendingConsumers();
}
}).catch(() => {
});
}
handleHandler() {
const handler = this._handler;
handler.on("@connect", ({ dtlsParameters }, callback, errback) => {
if (this._closed) {
errback(new errors_1.InvalidStateError("closed"));
return;
}
this.safeEmit("connect", { dtlsParameters }, callback, errback);
});
handler.on("@icegatheringstatechange", (iceGatheringState) => {
if (iceGatheringState === this._iceGatheringState) {
return;
}
logger2.debug("ICE gathering state changed to %s", iceGatheringState);
this._iceGatheringState = iceGatheringState;
if (!this._closed) {
this.safeEmit("icegatheringstatechange", iceGatheringState);
}
});
handler.on("@icecandidateerror", (event) => {
logger2.warn(`ICE candidate error [url:${event.url}, localAddress:${event.address}, localPort:${event.port}]: ${event.errorCode} "${event.errorText}"`);
this.safeEmit("icecandidateerror", event);
});
handler.on("@connectionstatechange", (connectionState) => {
if (connectionState === this._connectionState) {
return;
}
logger2.debug("connection state changed to %s", connectionState);
this._connectionState = connectionState;
if (!this._closed) {
this.safeEmit("connectionstatechange", connectionState);
}
});
}
handleProducer(producer) {
producer.on("@close", () => {
this._producers.delete(producer.id);
if (this._closed) {
return;
}
this._awaitQueue.push(() => __async(this, null, function* () {
return yield this._handler.stopSending(producer.localId);
}), "producer @close event").catch((error) => logger2.warn("producer.close() failed:%o", error));
});
producer.on("@pause", (callback, errback) => {
this._awaitQueue.push(() => __async(this, null, function* () {
return yield this._handler.pauseSending(producer.localId);
}), "producer @pause event").then(callback).catch(errback);
});
producer.on("@resume", (callback, errback) => {
this._awaitQueue.push(() => __async(this, null, function* () {
return yield this._handler.resumeSending(producer.localId);
}), "producer @resume event").then(callback).catch(errback);
});
producer.on("@replacetrack", (track, callback, errback) => {
this._awaitQueue.push(() => __async(this, null, function* () {
return yield this._handler.replaceTrack(producer.localId, track);
}), "producer @replacetrack event").then(callback).catch(errback);
});
producer.on("@setmaxspatiallayer", (spatialLayer, callback, errback) => {
this._awaitQueue.push(() => __async(this, null, function* () {
return yield this._handler.setMaxSpatialLayer(producer.localId, spatialLayer);
}), "producer @setmaxspatiallayer event").then(callback).catch(errback);
});
producer.on("@setrtpencodingparameters", (params, callback, errback) => {
this._awaitQueue.push(() => __async(this, null, function* () {
return yield this._handler.setRtpEncodingParameters(producer.localId, params);
}), "producer @setrtpencodingparameters event").then(callback).catch(errback);
});
producer.on("@getstats", (callback, errback) => {
if (this._closed) {
return errback(new errors_1.InvalidStateError("closed"));
}
this._handler.getSenderStats(producer.localId).then(callback).catch(errback);
});
}
handleConsumer(consumer) {
consumer.on("@close", () => {
this._consumers.delete(consumer.id);
this._pendingPauseConsumers.delete(consumer.id);
this._pendingResumeConsumers.delete(consumer.id);
if (this._closed) {
return;
}
this._pendingCloseConsumers.set(consumer.id, consumer);
if (this._consumerCloseInProgress === false) {
this.closePendingConsumers();
}
});
consumer.on("@pause", () => {
if (this._pendingResumeConsumers.has(consumer.id)) {
this._pendingResumeConsumers.delete(consumer.id);
}
this._pendingPauseConsumers.set(consumer.id, consumer);
queueMicrotask(() => {
if (this._closed) {
return;
}
if (this._consumerPauseInProgress === false) {
this.pausePendingConsumers();
}
});
});
consumer.on("@resume", () => {
if (this._pendingPauseConsumers.has(consumer.id)) {
this._pendingPauseConsumers.delete(consumer.id);
}
this._pendingResumeConsumers.set(consumer.id, consumer);
queueMicrotask(() => {
if (this._closed) {
return;
}
if (this._consumerResumeInProgress === false) {
this.resumePendingConsumers();
}
});
});
consumer.on("@getstats", (callback, errback) => {
if (this._closed) {
return errback(new errors_1.InvalidStateError("closed"));
}
this._handler.getReceiverStats(consumer.localId).then(callback).catch(errback);
});
}
handleDataProducer(dataProducer) {
dataProducer.on("@close", () => {
this._dataProducers.delete(dataProducer.id);
});
}
handleDataConsumer(dataConsumer) {
dataConsumer.on("@close", () => {
this._dataConsumers.delete(dataConsumer.id);
});
}
};
exports.Transport = Transport;
}
});
// ../../node_modules/.pnpm/sdp-transform@3.0.0/node_modules/sdp-transform/lib/grammar.js
var require_grammar2 = __commonJS({
"../../node_modules/.pnpm/sdp-transform@3.0.0/node_modules/sdp-transform/lib/grammar.js"(exports, module) {
init_process();
var grammar = module.exports = {
v: [{
name: "version",
reg: /^(\d*)$/
}],
o: [{
// o=- 20518 0 IN IP4 203.0.113.1
// NB: sessionId will be a String in most cases because it is huge
name: "origin",
reg: /^(\S*) (\d*) (\d*) (\S*) IP(\d) (\S*)/,
names: ["username", "sessionId", "sessionVersion", "netType", "ipVer", "address"],
format: "%s %s %d %s IP%d %s"
}],
// default parsing of these only (though some of these feel outdated)
s: [{ name: "name" }],
i: [{ name: "description" }],
u: [{ name: "uri" }],
e: [{ name: "email" }],
p: [{ name: "phone" }],
z: [{ name: "timezones" }],
// TODO: this one can actually be parsed properly...
r: [{ name: "repeats" }],
// TODO: this one can also be parsed properly
// k: [{}], // outdated thing ignored
t: [{
// t=0 0
name: "timing",
reg: /^(\d*) (\d*)/,
names: ["start", "stop"],
format: "%d %d"
}],
c: [{
// c=IN IP4 10.47.197.26
name: "connection",
reg: /^IN IP(\d) (\S*)/,
names: ["version", "ip"],
format: "IN IP%d %s"
}],
b: [{
// b=AS:4000
push: "bandwidth",
reg: /^(TIAS|AS|CT|RR|RS):(\d*)/,
names: ["type", "limit"],
format: "%s:%s"
}],
m: [{
// m=video 51744 RTP/AVP 126 97 98 34 31
// NB: special - pushes to session
// TODO: rtp/fmtp should be filtered by the payloads found here?
reg: /^(\w*) (\d*) ([\w/]*)(?: (.*))?/,
names: ["type", "port", "protocol", "payloads"],
format: "%s %d %s %s"
}],
a: [
{
// a=rtpmap:110 opus/48000/2
push: "rtp",
reg: /^rtpmap:(\d*) ([\w\-.]*)(?:\s*\/(\d*)(?:\s*\/(\S*))?)?/,
names: ["payload", "codec", "rate", "encoding"],
format: function(o2) {
return o2.encoding ? "rtpmap:%d %s/%s/%s" : o2.rate ? "rtpmap:%d %s/%s" : "rtpmap:%d %s";
}
},
{
// a=fmtp:108 profile-level-id=24;object=23;bitrate=64000
// a=fmtp:111 minptime=10; useinbandfec=1
push: "fmtp",
reg: /^fmtp:(\d*) ([\S| ]*)/,
names: ["payload", "config"],
format: "fmtp:%d %s"
},
{
// a=control:streamid=0
name: "control",
reg: /^control:(.*)/,
format: "control:%s"
},
{
// a=rtcp:65179 IN IP4 193.84.77.194
name: "rtcp",
reg: /^rtcp:(\d*)(?: (\S*) IP(\d) (\S*))?/,
names: ["port", "netType", "ipVer", "address"],
format: function(o2) {
return o2.address != null ? "rtcp:%d %s IP%d %s" : "rtcp:%d";
}
},
{
// a=rtcp-fb:98 trr-int 100
push: "rtcpFbTrrInt",
reg: /^rtcp-fb:(\*|\d*) trr-int (\d*)/,
names: ["payload", "value"],
format: "rtcp-fb:%s trr-int %d"
},
{
// a=rtcp-fb:98 nack rpsi
push: "rtcpFb",
reg: /^rtcp-fb:(\*|\d*) ([\w-_]*)(?: ([\w-_]*))?/,
names: ["payload", "type", "subtype"],
format: function(o2) {
return o2.subtype != null ? "rtcp-fb:%s %s %s" : "rtcp-fb:%s %s";
}
},
{
// a=extmap:2 urn:ietf:params:rtp-hdrext:toffset
// a=extmap:1/recvonly URI-gps-string
// a=extmap:3 urn:ietf:params:rtp-hdrext:encrypt urn:ietf:params:rtp-hdrext:smpte-tc 25@600/24
push: "ext",
reg: /^extmap:(\d+)(?:\/(\w+))?(?: (urn:ietf:params:rtp-hdrext:encrypt))? (\S*)(?: (\S*))?/,
names: ["value", "direction", "encrypt-uri", "uri", "config"],
format: function(o2) {
return "extmap:%d" + (o2.direction ? "/%s" : "%v") + (o2["encrypt-uri"] ? " %s" : "%v") + " %s" + (o2.config ? " %s" : "");
}
},
{
// a=extmap-allow-mixed
name: "extmapAllowMixed",
reg: /^(extmap-allow-mixed)/
},
{
// a=crypto:1 AES_CM_128_HMAC_SHA1_80 inline:PS1uQCVeeCFCanVmcjkpPywjNWhcYD0mXXtxaVBR|2^20|1:32
push: "crypto",
reg: /^crypto:(\d*) ([\w_]*) (\S*)(?: (\S*))?/,
names: ["id", "suite", "config", "sessionConfig"],
format: function(o2) {
return o2.sessionConfig != null ? "crypto:%d %s %s %s" : "crypto:%d %s %s";
}
},
{
// a=setup:actpass
name: "setup",
reg: /^setup:(\w*)/,
format: "setup:%s"
},
{
// a=connection:new
name: "connectionType",
reg: /^connection:(new|existing)/,
format: "connection:%s"
},
{
// a=mid:1
name: "mid",
reg: /^mid:([^\s]*)/,
format: "mid:%s"
},
{
// a=msid:0c8b064d-d807-43b4-b434-f92a889d8587 98178685-d409-46e0-8e16-7ef0db0db64a
push: "msid",
reg: /^msid:([\w-]+)(?: ([\w-]+))?/,
names: ["id", "appdata"],
format: "msid:%s %s"
},
{
// a=ptime:20
name: "ptime",
reg: /^ptime:(\d*(?:\.\d*)*)/,
format: "ptime:%d"
},
{
// a=maxptime:60
name: "maxptime",
reg: /^maxptime:(\d*(?:\.\d*)*)/,
format: "maxptime:%d"
},
{
// a=sendrecv
name: "direction",
reg: /^(sendrecv|recvonly|sendonly|inactive)/
},
{
// a=ice-lite
name: "icelite",
reg: /^(ice-lite)/
},
{
// a=ice-ufrag:F7gI
name: "iceUfrag",
reg: /^ice-ufrag:(\S*)/,
format: "ice-ufrag:%s"
},
{
// a=ice-pwd:x9cml/YzichV2+XlhiMu8g
name: "icePwd",
reg: /^ice-pwd:(\S*)/,
format: "ice-pwd:%s"
},
{
// a=fingerprint:SHA-1 00:11:22:33:44:55:66:77:88:99:AA:BB:CC:DD:EE:FF:00:11:22:33
name: "fingerprint",
reg: /^fingerprint:(\S*) (\S*)/,
names: ["type", "hash"],
format: "fingerprint:%s %s"
},
{
// a=candidate:0 1 UDP 2113667327 203.0.113.1 54400 typ host
// a=candidate:1162875081 1 udp 2113937151 192.168.34.75 60017 typ host generation 0 network-id 3 network-cost 10
// a=candidate:3289912957 2 udp 1845501695 193.84.77.194 60017 typ srflx raddr 192.168.34.75 rport 60017 generation 0 network-id 3 network-cost 10
// a=candidate:229815620 1 tcp 1518280447 192.168.150.19 60017 typ host tcptype active generation 0 network-id 3 network-cost 10
// a=candidate:3289912957 2 tcp 1845501695 193.84.77.194 60017 typ srflx raddr 192.168.34.75 rport 60017 tcptype passive generation 0 network-id 3 network-cost 10
push: "candidates",
reg: /^candidate:(\S*) (\d*) (\S*) (\d*) (\S*) (\d*) typ (\S*)(?: raddr (\S*) rport (\d*))?(?: tcptype (\S*))?(?: generation (\d*))?(?: network-id (\d*))?(?: network-cost (\d*))?/,
names: ["foundation", "component", "transport", "priority", "ip", "port", "type", "raddr", "rport", "tcptype", "generation", "network-id", "network-cost"],
format: function(o2) {
var str = "candidate:%s %d %s %d %s %d typ %s";
str += o2.raddr != null ? " raddr %s rport %d" : "%v%v";
str += o2.tcptype != null ? " tcptype %s" : "%v";
if (o2.generation != null) {
str += " generation %d";
}
str += o2["network-id"] != null ? " network-id %d" : "%v";
str += o2["network-cost"] != null ? " network-cost %d" : "%v";
return str;
}
},
{
// a=end-of-candidates (keep after the candidates line for readability)
name: "endOfCandidates",
reg: /^(end-of-candidates)/
},
{
// a=remote-candidates:1 203.0.113.1 54400 2 203.0.113.1 54401 ...
name: "remoteCandidates",
reg: /^remote-candidates:(.*)/,
format: "remote-candidates:%s"
},
{
// a=ice-options:google-ice
name: "iceOptions",
reg: /^ice-options:(\S*)/,
format: "ice-options:%s"
},
{
// a=ssrc:2566107569 cname:t9YU8M1UxTF8Y1A1
push: "ssrcs",
reg: /^ssrc:(\d*) ([\w_-]*)(?::(.*))?/,
names: ["id", "attribute", "value"],
format: function(o2) {
var str = "ssrc:%d";
if (o2.attribute != null) {
str += " %s";
if (o2.value != null) {
str += ":%s";
}
}
return str;
}
},
{
// a=ssrc-group:FEC 1 2
// a=ssrc-group:FEC-FR 3004364195 1080772241
push: "ssrcGroups",
// token-char = %x21 / %x23-27 / %x2A-2B / %x2D-2E / %x30-39 / %x41-5A / %x5E-7E
reg: /^ssrc-group:([\x21\x23\x24\x25\x26\x27\x2A\x2B\x2D\x2E\w]*) (.*)/,
names: ["semantics", "ssrcs"],
format: "ssrc-group:%s %s"
},
{
// a=msid-semantic: WMS Jvlam5X3SX1OP6pn20zWogvaKJz5Hjf9OnlV
name: "msidSemantic",
reg: /^msid-semantic:\s?(\w*) (\S*)/,
names: ["semantic", "token"],
format: "msid-semantic: %s %s"
// space after ':' is not accidental
},
{
// a=group:BUNDLE audio video
push: "groups",
reg: /^group:(\w*) (.*)/,
names: ["type", "mids"],
format: "group:%s %s"
},
{
// a=rtcp-mux
name: "rtcpMux",
reg: /^(rtcp-mux)/
},
{
// a=rtcp-rsize
name: "rtcpRsize",
reg: /^(rtcp-rsize)/
},
{
// a=sctpmap:5000 webrtc-datachannel 1024
name: "sctpmap",
reg: /^sctpmap:([\w_/]*) (\S*)(?: (\S*))?/,
names: ["sctpmapNumber", "app", "maxMessageSize"],
format: function(o2) {
return o2.maxMessageSize != null ? "sctpmap:%s %s %s" : "sctpmap:%s %s";
}
},
{
// a=x-google-flag:conference
name: "xGoogleFlag",
reg: /^x-google-flag:([^\s]*)/,
format: "x-google-flag:%s"
},
{
// a=rid:1 send max-width=1280;max-height=720;max-fps=30;depend=0
push: "rids",
reg: /^rid:([\d\w]+) (\w+)(?: ([\S| ]*))?/,
names: ["id", "direction", "params"],
format: function(o2) {
return o2.params ? "rid:%s %s %s" : "rid:%s %s";
}
},
{
// a=imageattr:97 send [x=800,y=640,sar=1.1,q=0.6] [x=480,y=320] recv [x=330,y=250]
// a=imageattr:* send [x=800,y=640] recv *
// a=imageattr:100 recv [x=320,y=240]
push: "imageattrs",
reg: new RegExp(
// a=imageattr:97
"^imageattr:(\\d+|\\*)[\\s\\t]+(send|recv)[\\s\\t]+(\\*|\\[\\S+\\](?:[\\s\\t]+\\[\\S+\\])*)(?:[\\s\\t]+(recv|send)[\\s\\t]+(\\*|\\[\\S+\\](?:[\\s\\t]+\\[\\S+\\])*))?"
),
names: ["pt", "dir1", "attrs1", "dir2", "attrs2"],
format: function(o2) {
return "imageattr:%s %s %s" + (o2.dir2 ? " %s %s" : "");
}
},
{
// a=simulcast:send 1,2,3;~4,~5 recv 6;~7,~8
// a=simulcast:recv 1;4,5 send 6;7
name: "simulcast",
reg: new RegExp(
// a=simulcast:
"^simulcast:(send|recv) ([a-zA-Z0-9\\-_~;,]+)(?:\\s?(send|recv) ([a-zA-Z0-9\\-_~;,]+))?$"
),
names: ["dir1", "list1", "dir2", "list2"],
format: function(o2) {
return "simulcast:%s %s" + (o2.dir2 ? " %s %s" : "");
}
},
{
// old simulcast draft 03 (implemented by Firefox)
// https://tools.ietf.org/html/draft-ietf-mmusic-sdp-simulcast-03
// a=simulcast: recv pt=97;98 send pt=97
// a=simulcast: send rid=5;6;7 paused=6,7
name: "simulcast_03",
reg: /^simulcast:[\s\t]+([\S+\s\t]+)$/,
names: ["value"],
format: "simulcast: %s"
},
{
// a=framerate:25
// a=framerate:29.97
name: "framerate",
reg: /^framerate:(\d+(?:$|\.\d+))/,
format: "framerate:%s"
},
{
// RFC4570
// a=source-filter: incl IN IP4 239.5.2.31 10.1.15.5
name: "sourceFilter",
reg: /^source-filter: *(excl|incl) (\S*) (IP4|IP6|\*) (\S*) (.*)/,
names: ["filterMode", "netType", "addressTypes", "destAddress", "srcList"],
format: "source-filter: %s %s %s %s %s"
},
{
// a=bundle-only
name: "bundleOnly",
reg: /^(bundle-only)/
},
{
// a=label:1
name: "label",
reg: /^label:(.+)/,
format: "label:%s"
},
{
// RFC version 26 for SCTP over DTLS
// https://tools.ietf.org/html/draft-ietf-mmusic-sctp-sdp-26#section-5
name: "sctpPort",
reg: /^sctp-port:(\d+)$/,
format: "sctp-port:%s"
},
{
// RFC version 26 for SCTP over DTLS
// https://tools.ietf.org/html/draft-ietf-mmusic-sctp-sdp-26#section-6
name: "maxMessageSize",
reg: /^max-message-size:(\d+)$/,
format: "max-message-size:%s"
},
{
// RFC7273
// a=ts-refclk:ptp=IEEE1588-2008:39-A7-94-FF-FE-07-CB-D0:37
push: "tsRefClocks",
reg: /^ts-refclk:([^\s=]*)(?:=(\S*))?/,
names: ["clksrc", "clksrcExt"],
format: function(o2) {
return "ts-refclk:%s" + (o2.clksrcExt != null ? "=%s" : "");
}
},
{
// RFC7273
// a=mediaclk:direct=963214424
name: "mediaClk",
reg: /^mediaclk:(?:id=(\S*))? *([^\s=]*)(?:=(\S*))?(?: *rate=(\d+)\/(\d+))?/,
names: ["id", "mediaClockName", "mediaClockValue", "rateNumerator", "rateDenominator"],
format: function(o2) {
var str = "mediaclk:";
str += o2.id != null ? "id=%s %s" : "%v%s";
str += o2.mediaClockValue != null ? "=%s" : "";
str += o2.rateNumerator != null ? " rate=%s" : "";
str += o2.rateDenominator != null ? "/%s" : "";
return str;
}
},
{
// a=keywds:keywords
name: "keywords",
reg: /^keywds:(.+)$/,
format: "keywds:%s"
},
{
// a=content:main
name: "content",
reg: /^content:(.+)/,
format: "content:%s"
},
// BFCP https://tools.ietf.org/html/rfc4583
{
// a=floorctrl:c-s
name: "bfcpFloorCtrl",
reg: /^floorctrl:(c-only|s-only|c-s)/,
format: "floorctrl:%s"
},
{
// a=confid:1
name: "bfcpConfId",
reg: /^confid:(\d+)/,
format: "confid:%s"
},
{
// a=userid:1
name: "bfcpUserId",
reg: /^userid:(\d+)/,
format: "userid:%s"
},
{
// a=floorid:1
name: "bfcpFloorId",
reg: /^floorid:(.+) (?:m-stream|mstrm):(.+)/,
names: ["id", "mStream"],
format: "floorid:%s mstrm:%s"
},
{
// any a= that we don't understand is kept verbatim on media.invalid
push: "invalid",
names: ["value"]
}
]
};
Object.keys(grammar).forEach(function(key) {
var objs = grammar[key];
objs.forEach(function(obj) {
if (!obj.reg) {
obj.reg = /(.*)/;
}
if (!obj.format) {
obj.format = "%s";
}
});
});
}
});
// ../../node_modules/.pnpm/sdp-transform@3.0.0/node_modules/sdp-transform/lib/parser.js
var require_parser2 = __commonJS({
"../../node_modules/.pnpm/sdp-transform@3.0.0/node_modules/sdp-transform/lib/parser.js"(exports) {
init_process();
var toIntIfInt = function(v) {
return String(Number(v)) === v ? Number(v) : v;
};
var attachProperties = function(match, location, names, rawName) {
if (rawName && !names) {
location[rawName] = toIntIfInt(match[1]);
} else {
for (var i = 0; i < names.length; i += 1) {
if (match[i + 1] != null) {
location[names[i]] = toIntIfInt(match[i + 1]);
}
}
}
};
var parseReg = function(obj, location, content) {
var needsBlank = obj.name && obj.names;
if (obj.push && !location[obj.push]) {
location[obj.push] = [];
} else if (needsBlank && !location[obj.name]) {
location[obj.name] = {};
}
var keyLocation = obj.push ? {} : (
// blank object that will be pushed
needsBlank ? location[obj.name] : location
);
attachProperties(content.match(obj.reg), keyLocation, obj.names, obj.name);
if (obj.push) {
location[obj.push].push(keyLocation);
}
};
var grammar = require_grammar2();
var validLine = RegExp.prototype.test.bind(/^([a-z])=(.*)/);
exports.parse = function(sdp) {
var session = {}, media = [], location = session;
sdp.split(/(\r\n|\r|\n)/).filter(validLine).forEach(function(l) {
var type = l[0];
var content = l.slice(2);
if (type === "m") {
media.push({ rtp: [], fmtp: [] });
location = media[media.length - 1];
}
for (var j = 0; j < (grammar[type] || []).length; j += 1) {
var obj = grammar[type][j];
if (obj.reg.test(content)) {
return parseReg(obj, location, content);
}
}
});
session.media = media;
return session;
};
var paramReducer = function(acc, expr) {
var s = expr.split(/=(.+)/, 2);
if (s.length === 2) {
acc[s[0]] = toIntIfInt(s[1]);
} else if (s.length === 1 && expr.length > 1) {
acc[s[0]] = void 0;
}
return acc;
};
exports.parseParams = function(str) {
return str.split(/;\s?/).reduce(paramReducer, {});
};
exports.parseFmtpConfig = exports.parseParams;
exports.parsePayloads = function(str) {
return str.toString().split(" ").map(Number);
};
exports.parseRemoteCandidates = function(str) {
var candidates = [];
var parts = str.split(" ").map(toIntIfInt);
for (var i = 0; i < parts.length; i += 3) {
candidates.push({
component: parts[i],
ip: parts[i + 1],
port: parts[i + 2]
});
}
return candidates;
};
exports.parseImageAttributes = function(str) {
return str.split(" ").map(function(item) {
return item.substring(1, item.length - 1).split(",").reduce(paramReducer, {});
});
};
exports.parseSimulcastStreamList = function(str) {
return str.split(";").map(function(stream) {
return stream.split(",").map(function(format) {
var scid, paused = false;
if (format[0] !== "~") {
scid = toIntIfInt(format);
} else {
scid = toIntIfInt(format.substring(1, format.length));
paused = true;
}
return {
scid,
paused
};
});
});
};
}
});
// ../../node_modules/.pnpm/sdp-transform@3.0.0/node_modules/sdp-transform/lib/writer.js
var require_writer2 = __commonJS({
"../../node_modules/.pnpm/sdp-transform@3.0.0/node_modules/sdp-transform/lib/writer.js"(exports, module) {
init_process();
var grammar = require_grammar2();
var formatRegExp = /%[sdv%]/g;
var format = function(formatStr) {
var i = 1;
var args = arguments;
var len = args.length;
return formatStr.replace(formatRegExp, function(x) {
if (i >= len) {
return x;
}
var arg = args[i];
i += 1;
switch (x) {
case "%%":
return "%";
case "%s":
return String(arg);
case "%d":
return Number(arg);
case "%v":
return "";
}
});
};
var makeLine = function(type, obj, location) {
var str = obj.format instanceof Function ? obj.format(obj.push ? location : location[obj.name]) : obj.format;
var args = [type + "=" + str];
if (obj.names) {
for (var i = 0; i < obj.names.length; i += 1) {
var n2 = obj.names[i];
if (obj.name) {
args.push(location[obj.name][n2]);
} else {
args.push(location[obj.names[i]]);
}
}
} else {
args.push(location[obj.name]);
}
return format.apply(null, args);
};
var defaultOuterOrder = [
"v",
"o",
"s",
"i",
"u",
"e",
"p",
"c",
"b",
"t",
"r",
"z",
"a"
];
var defaultInnerOrder = ["i", "c", "b", "a"];
module.exports = function(session, opts) {
opts = opts || {};
if (session.version == null) {
session.version = 0;
}
if (session.name == null) {
session.name = " ";
}
session.media.forEach(function(mLine) {
if (mLine.payloads == null) {
mLine.payloads = "";
}
});
var outerOrder = opts.outerOrder || defaultOuterOrder;
var innerOrder = opts.innerOrder || defaultInnerOrder;
var sdp = [];
outerOrder.forEach(function(type) {
grammar[type].forEach(function(obj) {
if (obj.name in session && session[obj.name] != null) {
sdp.push(makeLine(type, obj, session));
} else if (obj.push in session && session[obj.push] != null) {
session[obj.push].forEach(function(el) {
sdp.push(makeLine(type, obj, el));
});
}
});
});
session.media.forEach(function(mLine) {
sdp.push(makeLine("m", grammar.m[0], mLine));
innerOrder.forEach(function(type) {
grammar[type].forEach(function(obj) {
if (obj.name in mLine && mLine[obj.name] != null) {
sdp.push(makeLine(type, obj, mLine));
} else if (obj.push in mLine && mLine[obj.push] != null) {
mLine[obj.push].forEach(function(el) {
sdp.push(makeLine(type, obj, el));
});
}
});
});
});
return sdp.join("\r\n") + "\r\n";
};
}
});
// ../../node_modules/.pnpm/sdp-transform@3.0.0/node_modules/sdp-transform/lib/index.js
var require_lib4 = __commonJS({
"../../node_modules/.pnpm/sdp-transform@3.0.0/node_modules/sdp-transform/lib/index.js"(exports) {
init_process();
var parser = require_parser2();
var writer = require_writer2();
var grammar = require_grammar2();
exports.grammar = grammar;
exports.write = writer;
exports.parse = parser.parse;
exports.parseParams = parser.parseParams;
exports.parseFmtpConfig = parser.parseFmtpConfig;
exports.parsePayloads = parser.parsePayloads;
exports.parseRemoteCandidates = parser.parseRemoteCandidates;
exports.parseImageAttributes = parser.parseImageAttributes;
exports.parseSimulcastStreamList = parser.parseSimulcastStreamList;
}
});
// ../../node_modules/.pnpm/mediasoup-client@3.18.3/node_modules/mediasoup-client/lib/scalabilityModes.js
var require_scalabilityModes = __commonJS({
"../../node_modules/.pnpm/mediasoup-client@3.18.3/node_modules/mediasoup-client/lib/scalabilityModes.js"(exports) {
"use strict";
init_process();
Object.defineProperty(exports, "__esModule", { value: true });
exports.parse = parse3;
var ScalabilityModeRegex = new RegExp("^[LS]([1-9]\\d{0,1})T([1-9]\\d{0,1})");
function parse3(scalabilityMode) {
const match = ScalabilityModeRegex.exec(scalabilityMode != null ? scalabilityMode : "");
if (match) {
return {
spatialLayers: Number(match[1]),
temporalLayers: Number(match[2])
};
} else {
return {
spatialLayers: 1,
temporalLayers: 1
};
}
}
}
});
// ../../node_modules/.pnpm/mediasoup-client@3.18.3/node_modules/mediasoup-client/lib/handlers/sdp/MediaSection.js
var require_MediaSection = __commonJS({
"../../node_modules/.pnpm/mediasoup-client@3.18.3/node_modules/mediasoup-client/lib/handlers/sdp/MediaSection.js"(exports) {
"use strict";
init_process();
Object.defineProperty(exports, "__esModule", { value: true });
exports.OfferMediaSection = exports.AnswerMediaSection = exports.MediaSection = void 0;
var sdpTransform4 = require_lib4();
var utils = require_utils();
var MediaSection = class {
constructor({ iceParameters, iceCandidates, dtlsParameters }) {
// SDP media object.
__publicField(this, "_mediaObject");
var _a2;
this._mediaObject = {
type: "",
port: 0,
protocol: "",
payloads: "",
rtp: [],
fmtp: []
};
if (iceParameters) {
this.setIceParameters(iceParameters);
}
if (iceCandidates) {
this._mediaObject.candidates = [];
for (const candidate of iceCandidates) {
const candidateObject = {
foundation: candidate.foundation,
// mediasoup does mandates rtcp-mux so candidates component is always
// RTP (1).
component: 1,
// Be ready for new candidate.address field in mediasoup server side
// field and keep backward compatibility with deprecated candidate.ip.
ip: (_a2 = candidate.address) != null ? _a2 : candidate.ip,
port: candidate.port,
priority: candidate.priority,
transport: candidate.protocol,
type: candidate.type
};
if (candidate.tcpType) {
candidateObject.tcptype = candidate.tcpType;
}
this._mediaObject.candidates.push(candidateObject);
}
this._mediaObject.endOfCandidates = "end-of-candidates";
this._mediaObject.iceOptions = "renomination";
}
if (dtlsParameters) {
this.setDtlsRole(dtlsParameters.role);
}
}
get mid() {
return String(this._mediaObject.mid);
}
get closed() {
return this._mediaObject.port === 0;
}
getObject() {
return this._mediaObject;
}
setIceParameters(iceParameters) {
this._mediaObject.iceUfrag = iceParameters.usernameFragment;
this._mediaObject.icePwd = iceParameters.password;
}
pause() {
this._mediaObject.direction = "inactive";
}
disable() {
this.pause();
}
close() {
this.disable();
this._mediaObject.port = 0;
delete this._mediaObject.candidates;
delete this._mediaObject.endOfCandidates;
delete this._mediaObject.iceUfrag;
delete this._mediaObject.icePwd;
delete this._mediaObject.iceOptions;
this._mediaObject.rtp = [];
this._mediaObject.fmtp = [];
delete this._mediaObject.rtcp;
delete this._mediaObject.rtcpFb;
delete this._mediaObject.ssrcs;
delete this._mediaObject.ssrcGroups;
delete this._mediaObject.simulcast;
delete this._mediaObject.simulcast_03;
delete this._mediaObject.rids;
delete this._mediaObject.extmapAllowMixed;
}
};
exports.MediaSection = MediaSection;
var AnswerMediaSection = class extends MediaSection {
constructor({ iceParameters, iceCandidates, dtlsParameters, sctpParameters, plainRtpParameters, offerMediaObject, offerRtpParameters, answerRtpParameters, codecOptions }) {
var _a2, _b2, _c, _d, _e;
super({ iceParameters, iceCandidates, dtlsParameters });
this._mediaObject.mid = String(offerMediaObject.mid);
this._mediaObject.type = offerMediaObject.type;
this._mediaObject.protocol = offerMediaObject.protocol;
if (!plainRtpParameters) {
this._mediaObject.connection = { ip: "127.0.0.1", version: 4 };
this._mediaObject.port = 7;
} else {
this._mediaObject.connection = {
ip: plainRtpParameters.ip,
version: plainRtpParameters.ipVersion
};
this._mediaObject.port = plainRtpParameters.port;
}
switch (offerMediaObject.type) {
case "audio":
case "video": {
this._mediaObject.direction = "recvonly";
this._mediaObject.rtp = [];
this._mediaObject.rtcpFb = [];
this._mediaObject.fmtp = [];
for (const codec of answerRtpParameters.codecs) {
const rtp = {
payload: codec.payloadType,
codec: getCodecName(codec),
rate: codec.clockRate
};
if (codec.channels > 1) {
rtp.encoding = codec.channels;
}
this._mediaObject.rtp.push(rtp);
const codecParameters = (_a2 = utils.clone(codec.parameters)) != null ? _a2 : {};
let codecRtcpFeedback = (_b2 = utils.clone(codec.rtcpFeedback)) != null ? _b2 : [];
if (codecOptions) {
const { opusStereo, opusFec, opusDtx, opusMaxPlaybackRate, opusMaxAverageBitrate, opusPtime, opusNack, videoGoogleStartBitrate, videoGoogleMaxBitrate, videoGoogleMinBitrate } = codecOptions;
const offerCodec = offerRtpParameters.codecs.find((c) => c.payloadType === codec.payloadType);
switch (codec.mimeType.toLowerCase()) {
case "audio/opus":
case "audio/multiopus": {
if (opusStereo !== void 0) {
offerCodec.parameters["sprop-stereo"] = opusStereo ? 1 : 0;
codecParameters["stereo"] = opusStereo ? 1 : 0;
}
if (opusFec !== void 0) {
offerCodec.parameters["useinbandfec"] = opusFec ? 1 : 0;
codecParameters["useinbandfec"] = opusFec ? 1 : 0;
}
if (opusDtx !== void 0) {
offerCodec.parameters["usedtx"] = opusDtx ? 1 : 0;
codecParameters["usedtx"] = opusDtx ? 1 : 0;
}
if (opusMaxPlaybackRate !== void 0) {
codecParameters["maxplaybackrate"] = opusMaxPlaybackRate;
}
if (opusMaxAverageBitrate !== void 0) {
codecParameters["maxaveragebitrate"] = opusMaxAverageBitrate;
}
if (opusPtime !== void 0) {
offerCodec.parameters["ptime"] = opusPtime;
codecParameters["ptime"] = opusPtime;
}
if (!opusNack) {
offerCodec.rtcpFeedback = offerCodec.rtcpFeedback.filter((fb) => fb.type !== "nack" || fb.parameter);
codecRtcpFeedback = codecRtcpFeedback.filter((fb) => fb.type !== "nack" || fb.parameter);
}
break;
}
case "video/vp8":
case "video/vp9":
case "video/h264":
case "video/h265":
case "video/av1": {
if (videoGoogleStartBitrate !== void 0) {
codecParameters["x-google-start-bitrate"] = videoGoogleStartBitrate;
}
if (videoGoogleMaxBitrate !== void 0) {
codecParameters["x-google-max-bitrate"] = videoGoogleMaxBitrate;
}
if (videoGoogleMinBitrate !== void 0) {
codecParameters["x-google-min-bitrate"] = videoGoogleMinBitrate;
}
break;
}
}
}
const fmtp = {
payload: codec.payloadType,
config: ""
};
for (const key of Object.keys(codecParameters)) {
if (fmtp.config) {
fmtp.config += ";";
}
fmtp.config += `${key}=${codecParameters[key]}`;
}
if (fmtp.config) {
this._mediaObject.fmtp.push(fmtp);
}
for (const fb of codecRtcpFeedback) {
this._mediaObject.rtcpFb.push({
payload: codec.payloadType,
type: fb.type,
subtype: fb.parameter
});
}
}
this._mediaObject.payloads = answerRtpParameters.codecs.map((codec) => codec.payloadType).join(" ");
this._mediaObject.ext = [];
for (const ext of answerRtpParameters.headerExtensions) {
const found = ((_c = offerMediaObject.ext) != null ? _c : []).some((localExt) => localExt.uri === ext.uri);
if (!found) {
continue;
}
this._mediaObject.ext.push({
uri: ext.uri,
value: ext.id
});
}
if (offerMediaObject.extmapAllowMixed === "extmap-allow-mixed") {
this._mediaObject.extmapAllowMixed = "extmap-allow-mixed";
}
if (offerMediaObject.simulcast) {
this._mediaObject.simulcast = {
dir1: "recv",
list1: offerMediaObject.simulcast.list1
};
this._mediaObject.rids = [];
for (const rid of (_d = offerMediaObject.rids) != null ? _d : []) {
if (rid.direction !== "send") {
continue;
}
this._mediaObject.rids.push({
id: rid.id,
direction: "recv"
});
}
} else if (offerMediaObject.simulcast_03) {
this._mediaObject.simulcast_03 = {
value: offerMediaObject.simulcast_03.value.replace(/send/g, "recv")
};
this._mediaObject.rids = [];
for (const rid of (_e = offerMediaObject.rids) != null ? _e : []) {
if (rid.direction !== "send") {
continue;
}
this._mediaObject.rids.push({
id: rid.id,
direction: "recv"
});
}
}
this._mediaObject.rtcpMux = "rtcp-mux";
this._mediaObject.rtcpRsize = "rtcp-rsize";
break;
}
case "application": {
if (typeof offerMediaObject.sctpPort === "number") {
this._mediaObject.payloads = "webrtc-datachannel";
this._mediaObject.sctpPort = sctpParameters.port;
this._mediaObject.maxMessageSize = sctpParameters.maxMessageSize;
} else if (offerMediaObject.sctpmap) {
this._mediaObject.payloads = String(sctpParameters.port);
this._mediaObject.sctpmap = {
app: "webrtc-datachannel",
sctpmapNumber: sctpParameters.port,
maxMessageSize: sctpParameters.maxMessageSize
};
}
break;
}
}
}
setDtlsRole(role) {
switch (role) {
case "client": {
this._mediaObject.setup = "active";
break;
}
case "server": {
this._mediaObject.setup = "passive";
break;
}
case "auto": {
this._mediaObject.setup = "actpass";
break;
}
}
}
resume() {
this._mediaObject.direction = "recvonly";
}
muxSimulcastStreams(encodings) {
var _a2, _b2;
if (!((_a2 = this._mediaObject.simulcast) == null ? void 0 : _a2.list1)) {
return;
}
const layers = {};
for (const encoding of encodings) {
if (encoding.rid) {
layers[encoding.rid] = encoding;
}
}
const raw = this._mediaObject.simulcast.list1;
const simulcastStreams = sdpTransform4.parseSimulcastStreamList(raw);
for (const simulcastStream of simulcastStreams) {
for (const simulcastFormat of simulcastStream) {
simulcastFormat.paused = !((_b2 = layers[simulcastFormat.scid]) == null ? void 0 : _b2.active);
}
}
this._mediaObject.simulcast.list1 = simulcastStreams.map((simulcastFormats) => simulcastFormats.map((f) => `${f.paused ? "~" : ""}${f.scid}`).join(",")).join(";");
}
};
exports.AnswerMediaSection = AnswerMediaSection;
var OfferMediaSection = class extends MediaSection {
constructor({ iceParameters, iceCandidates, dtlsParameters, sctpParameters, plainRtpParameters, mid, kind, offerRtpParameters, streamId, trackId }) {
var _a2, _b2;
super({ iceParameters, iceCandidates, dtlsParameters });
this._mediaObject.mid = String(mid);
this._mediaObject.type = kind;
if (!plainRtpParameters) {
this._mediaObject.connection = { ip: "127.0.0.1", version: 4 };
if (!sctpParameters) {
this._mediaObject.protocol = "UDP/TLS/RTP/SAVPF";
} else {
this._mediaObject.protocol = "UDP/DTLS/SCTP";
}
this._mediaObject.port = 7;
} else {
this._mediaObject.connection = {
ip: plainRtpParameters.ip,
version: plainRtpParameters.ipVersion
};
this._mediaObject.protocol = "RTP/AVP";
this._mediaObject.port = plainRtpParameters.port;
}
this._mediaObject.extmapAllowMixed = "extmap-allow-mixed";
switch (kind) {
case "audio":
case "video": {
this._mediaObject.direction = "sendonly";
this._mediaObject.rtp = [];
this._mediaObject.rtcpFb = [];
this._mediaObject.fmtp = [];
this._mediaObject.msid = [{ id: streamId, appdata: trackId }];
for (const codec of offerRtpParameters.codecs) {
const rtp = {
payload: codec.payloadType,
codec: getCodecName(codec),
rate: codec.clockRate
};
if (codec.channels > 1) {
rtp.encoding = codec.channels;
}
this._mediaObject.rtp.push(rtp);
const fmtp = {
payload: codec.payloadType,
config: ""
};
for (const key of Object.keys((_a2 = codec.parameters) != null ? _a2 : {})) {
if (fmtp.config) {
fmtp.config += ";";
}
fmtp.config += `${key}=${codec.parameters[key]}`;
}
if (fmtp.config) {
this._mediaObject.fmtp.push(fmtp);
}
for (const fb of codec.rtcpFeedback) {
this._mediaObject.rtcpFb.push({
payload: codec.payloadType,
type: fb.type,
subtype: fb.parameter
});
}
}
this._mediaObject.payloads = offerRtpParameters.codecs.map((codec) => codec.payloadType).join(" ");
this._mediaObject.ext = [];
for (const ext of offerRtpParameters.headerExtensions) {
this._mediaObject.ext.push({
uri: ext.uri,
value: ext.id
});
}
this._mediaObject.rtcpMux = "rtcp-mux";
this._mediaObject.rtcpRsize = "rtcp-rsize";
const encoding = offerRtpParameters.encodings[0];
const ssrc = encoding.ssrc;
const rtxSsrc = (_b2 = encoding.rtx) == null ? void 0 : _b2.ssrc;
this._mediaObject.ssrcs = [];
this._mediaObject.ssrcGroups = [];
if (ssrc && offerRtpParameters.rtcp.cname) {
this._mediaObject.ssrcs.push({
id: ssrc,
attribute: "cname",
value: offerRtpParameters.rtcp.cname
});
}
if (rtxSsrc) {
if (offerRtpParameters.rtcp.cname) {
this._mediaObject.ssrcs.push({
id: rtxSsrc,
attribute: "cname",
value: offerRtpParameters.rtcp.cname
});
}
if (ssrc) {
this._mediaObject.ssrcGroups.push({
semantics: "FID",
ssrcs: `${ssrc} ${rtxSsrc}`
});
}
}
break;
}
case "application": {
this._mediaObject.payloads = "webrtc-datachannel";
this._mediaObject.sctpPort = sctpParameters.port;
this._mediaObject.maxMessageSize = sctpParameters.maxMessageSize;
break;
}
}
}
// eslint-disable-next-line @typescript-eslint/no-unused-vars
setDtlsRole(role) {
this._mediaObject.setup = "actpass";
}
resume() {
this._mediaObject.direction = "sendonly";
}
};
exports.OfferMediaSection = OfferMediaSection;
function getCodecName(codec) {
const MimeTypeRegex = new RegExp("^(audio|video)/(.+)", "i");
const mimeTypeMatch = MimeTypeRegex.exec(codec.mimeType);
if (!mimeTypeMatch) {
throw new TypeError("invalid codec.mimeType");
}
return mimeTypeMatch[2];
}
}
});
// ../../node_modules/.pnpm/mediasoup-client@3.18.3/node_modules/mediasoup-client/lib/handlers/sdp/RemoteSdp.js
var require_RemoteSdp = __commonJS({
"../../node_modules/.pnpm/mediasoup-client@3.18.3/node_modules/mediasoup-client/lib/handlers/sdp/RemoteSdp.js"(exports) {
"use strict";
init_process();
Object.defineProperty(exports, "__esModule", { value: true });
exports.RemoteSdp = void 0;
var sdpTransform4 = require_lib4();
var Logger_1 = require_Logger();
var MediaSection_1 = require_MediaSection();
var DD_CODECS = ["av1", "h264"];
var logger2 = new Logger_1.Logger("RemoteSdp");
var RemoteSdp = class {
constructor({ iceParameters, iceCandidates, dtlsParameters, sctpParameters, plainRtpParameters }) {
// Remote ICE parameters.
__publicField(this, "_iceParameters");
// Remote ICE candidates.
__publicField(this, "_iceCandidates");
// Remote DTLS parameters.
__publicField(this, "_dtlsParameters");
// Remote SCTP parameters.
__publicField(this, "_sctpParameters");
// Parameters for plain RTP (no SRTP nor DTLS no BUNDLE).
__publicField(this, "_plainRtpParameters");
// MediaSection instances with same order as in the SDP.
__publicField(this, "_mediaSections", []);
// MediaSection indices indexed by MID.
__publicField(this, "_midToIndex", /* @__PURE__ */ new Map());
// First MID.
__publicField(this, "_firstMid");
// SDP object.
__publicField(this, "_sdpObject");
this._iceParameters = iceParameters;
this._iceCandidates = iceCandidates;
this._dtlsParameters = dtlsParameters;
this._sctpParameters = sctpParameters;
this._plainRtpParameters = plainRtpParameters;
this._sdpObject = {
version: 0,
origin: {
address: "0.0.0.0",
ipVer: 4,
netType: "IN",
sessionId: "10000",
sessionVersion: 0,
username: "mediasoup-client"
},
name: "-",
timing: { start: 0, stop: 0 },
media: []
};
this._sdpObject.iceOptions = "ice2";
if (iceParameters == null ? void 0 : iceParameters.iceLite) {
this._sdpObject.icelite = "ice-lite";
}
if (dtlsParameters) {
this._sdpObject.msidSemantic = { semantic: "WMS", token: "*" };
const numFingerprints = this._dtlsParameters.fingerprints.length;
this._sdpObject.fingerprint = {
type: dtlsParameters.fingerprints[numFingerprints - 1].algorithm,
hash: dtlsParameters.fingerprints[numFingerprints - 1].value
};
this._sdpObject.groups = [{ type: "BUNDLE", mids: "" }];
}
if (plainRtpParameters) {
this._sdpObject.origin.address = plainRtpParameters.ip;
this._sdpObject.origin.ipVer = plainRtpParameters.ipVersion;
}
}
updateIceParameters(iceParameters) {
logger2.debug("updateIceParameters() [iceParameters:%o]", iceParameters);
this._iceParameters = iceParameters;
this._sdpObject.icelite = iceParameters.iceLite ? "ice-lite" : void 0;
for (const mediaSection of this._mediaSections) {
mediaSection.setIceParameters(iceParameters);
}
}
updateDtlsRole(role) {
logger2.debug("updateDtlsRole() [role:%s]", role);
this._dtlsParameters.role = role;
for (const mediaSection of this._mediaSections) {
mediaSection.setDtlsRole(role);
}
}
/**
* Set session level a=extmap-allow-mixed attibute.
*/
setSessionExtmapAllowMixed() {
logger2.debug("setSessionExtmapAllowMixed()");
this._sdpObject.extmapAllowMixed = "extmap-allow-mixed";
}
getNextMediaSectionIdx() {
for (let idx = 0; idx < this._mediaSections.length; ++idx) {
const mediaSection = this._mediaSections[idx];
if (mediaSection.closed) {
return { idx, reuseMid: mediaSection.mid };
}
}
return { idx: this._mediaSections.length };
}
send({ offerMediaObject, reuseMid, offerRtpParameters, answerRtpParameters, codecOptions }) {
var _a2;
const mediaSection = new MediaSection_1.AnswerMediaSection({
iceParameters: this._iceParameters,
iceCandidates: this._iceCandidates,
dtlsParameters: this._dtlsParameters,
plainRtpParameters: this._plainRtpParameters,
offerMediaObject,
offerRtpParameters,
answerRtpParameters,
codecOptions
});
const mediaObject = mediaSection.getObject();
const ddCodec = mediaObject.rtp.find((rtp) => DD_CODECS.includes(rtp.codec.toLowerCase()));
if (!ddCodec) {
mediaObject.ext = (_a2 = mediaObject.ext) == null ? void 0 : _a2.filter((extmap) => extmap.uri !== "https://aomediacodec.github.io/av1-rtp-spec/#dependency-descriptor-rtp-header-extension");
}
if (reuseMid) {
this.replaceMediaSection(mediaSection, reuseMid);
} else if (!this._midToIndex.has(mediaSection.mid)) {
this.addMediaSection(mediaSection);
} else {
this.replaceMediaSection(mediaSection);
}
}
receive({ mid, kind, offerRtpParameters, streamId, trackId }) {
this.setSessionExtmapAllowMixed();
const mediaSection = new MediaSection_1.OfferMediaSection({
iceParameters: this._iceParameters,
iceCandidates: this._iceCandidates,
dtlsParameters: this._dtlsParameters,
plainRtpParameters: this._plainRtpParameters,
mid,
kind,
offerRtpParameters,
streamId,
trackId
});
const oldMediaSection = this._mediaSections.find((m) => m.closed);
if (oldMediaSection) {
this.replaceMediaSection(mediaSection, oldMediaSection.mid);
} else {
this.addMediaSection(mediaSection);
}
}
pauseMediaSection(mid) {
const mediaSection = this.findMediaSection(mid);
mediaSection.pause();
}
resumeSendingMediaSection(mid) {
const mediaSection = this.findMediaSection(mid);
mediaSection.resume();
}
resumeReceivingMediaSection(mid) {
const mediaSection = this.findMediaSection(mid);
mediaSection.resume();
}
disableMediaSection(mid) {
const mediaSection = this.findMediaSection(mid);
mediaSection.disable();
}
/**
* Closes media section. Returns true if the given MID corresponds to a m
* section that has been indeed closed. False otherwise.
*
* NOTE: Closing the first m section is a pain since it invalidates the bundled
* transport, so instead closing it we just disable it.
*/
closeMediaSection(mid) {
const mediaSection = this.findMediaSection(mid);
if (mid === this._firstMid) {
logger2.debug("closeMediaSection() | cannot close first media section, disabling it instead [mid:%s]", mid);
this.disableMediaSection(mid);
return false;
}
mediaSection.close();
this.regenerateBundleMids();
return true;
}
muxMediaSectionSimulcast(mid, encodings) {
const mediaSection = this.findMediaSection(mid);
mediaSection.muxSimulcastStreams(encodings);
this.replaceMediaSection(mediaSection);
}
sendSctpAssociation({ offerMediaObject }) {
const mediaSection = new MediaSection_1.AnswerMediaSection({
iceParameters: this._iceParameters,
iceCandidates: this._iceCandidates,
dtlsParameters: this._dtlsParameters,
sctpParameters: this._sctpParameters,
plainRtpParameters: this._plainRtpParameters,
offerMediaObject
});
this.addMediaSection(mediaSection);
}
receiveSctpAssociation() {
const mediaSection = new MediaSection_1.OfferMediaSection({
iceParameters: this._iceParameters,
iceCandidates: this._iceCandidates,
dtlsParameters: this._dtlsParameters,
sctpParameters: this._sctpParameters,
plainRtpParameters: this._plainRtpParameters,
mid: "datachannel",
kind: "application"
});
this.addMediaSection(mediaSection);
}
getSdp() {
this._sdpObject.origin.sessionVersion++;
return sdpTransform4.write(this._sdpObject);
}
addMediaSection(newMediaSection) {
if (!this._firstMid) {
this._firstMid = newMediaSection.mid;
}
this._mediaSections.push(newMediaSection);
this._midToIndex.set(newMediaSection.mid, this._mediaSections.length - 1);
this._sdpObject.media.push(newMediaSection.getObject());
this.regenerateBundleMids();
}
replaceMediaSection(newMediaSection, reuseMid) {
if (typeof reuseMid === "string") {
const idx = this._midToIndex.get(reuseMid);
if (idx === void 0) {
throw new Error(`no media section found for reuseMid '${reuseMid}'`);
}
const oldMediaSection = this._mediaSections[idx];
this._mediaSections[idx] = newMediaSection;
this._midToIndex.delete(oldMediaSection.mid);
this._midToIndex.set(newMediaSection.mid, idx);
this._sdpObject.media[idx] = newMediaSection.getObject();
this.regenerateBundleMids();
} else {
const idx = this._midToIndex.get(newMediaSection.mid);
if (idx === void 0) {
throw new Error(`no media section found with mid '${newMediaSection.mid}'`);
}
this._mediaSections[idx] = newMediaSection;
this._sdpObject.media[idx] = newMediaSection.getObject();
}
}
findMediaSection(mid) {
const idx = this._midToIndex.get(mid);
if (idx === void 0) {
throw new Error(`no media section found with mid '${mid}'`);
}
return this._mediaSections[idx];
}
regenerateBundleMids() {
if (!this._dtlsParameters) {
return;
}
this._sdpObject.groups[0].mids = this._mediaSections.filter((mediaSection) => !mediaSection.closed).map((mediaSection) => mediaSection.mid).join(" ");
}
};
exports.RemoteSdp = RemoteSdp;
}
});
// ../../node_modules/.pnpm/mediasoup-client@3.18.3/node_modules/mediasoup-client/lib/handlers/sdp/commonUtils.js
var require_commonUtils = __commonJS({
"../../node_modules/.pnpm/mediasoup-client@3.18.3/node_modules/mediasoup-client/lib/handlers/sdp/commonUtils.js"(exports) {
"use strict";
init_process();
Object.defineProperty(exports, "__esModule", { value: true });
exports.extractRtpCapabilities = extractRtpCapabilities;
exports.extractDtlsParameters = extractDtlsParameters;
exports.getCname = getCname;
exports.applyCodecParameters = applyCodecParameters;
exports.addHeaderExtension = addHeaderExtension;
var sdpTransform4 = require_lib4();
function extractRtpCapabilities({ sdpObject }) {
var _a2, _b2, _c;
const codecsMap = /* @__PURE__ */ new Map();
const headerExtensionMap = /* @__PURE__ */ new Map();
for (const m of sdpObject.media) {
const kind = m.type;
switch (kind) {
case "audio":
case "video": {
break;
}
default: {
continue;
}
}
for (const rtp of m.rtp) {
const codec = {
kind,
mimeType: `${kind}/${rtp.codec}`,
preferredPayloadType: rtp.payload,
clockRate: rtp.rate,
channels: rtp.encoding,
parameters: {},
rtcpFeedback: []
};
codecsMap.set(codec.preferredPayloadType, codec);
}
for (const fmtp of (_a2 = m.fmtp) != null ? _a2 : []) {
const parameters = sdpTransform4.parseParams(fmtp.config);
const codec = codecsMap.get(fmtp.payload);
if (!codec) {
continue;
}
if (parameters == null ? void 0 : parameters.hasOwnProperty("profile-level-id")) {
parameters["profile-level-id"] = String(parameters["profile-level-id"]);
}
codec.parameters = parameters;
}
for (const fb of (_b2 = m.rtcpFb) != null ? _b2 : []) {
const feedback = {
type: fb.type,
parameter: fb.subtype
};
if (!feedback.parameter) {
delete feedback.parameter;
}
if (fb.payload !== "*") {
const codec = codecsMap.get(Number(fb.payload));
if (!codec) {
continue;
}
codec.rtcpFeedback.push(feedback);
} else {
for (const codec of codecsMap.values()) {
if (codec.kind === kind && !/.+\/rtx$/i.test(codec.mimeType)) {
codec.rtcpFeedback.push(feedback);
}
}
}
}
for (const ext of (_c = m.ext) != null ? _c : []) {
if (ext["encrypt-uri"]) {
continue;
}
const headerExtension = {
kind,
uri: ext.uri,
preferredId: ext.value
};
headerExtensionMap.set(headerExtension.preferredId, headerExtension);
}
}
const rtpCapabilities = {
codecs: Array.from(codecsMap.values()),
headerExtensions: Array.from(headerExtensionMap.values())
};
return rtpCapabilities;
}
function extractDtlsParameters({ sdpObject }) {
var _a2;
let setup = sdpObject.setup;
let fingerprint = sdpObject.fingerprint;
if (!setup || !fingerprint) {
const mediaObject = ((_a2 = sdpObject.media) != null ? _a2 : []).find((m) => m.port !== 0);
if (mediaObject) {
setup = setup != null ? setup : mediaObject.setup;
fingerprint = fingerprint != null ? fingerprint : mediaObject.fingerprint;
}
}
if (!setup) {
throw new Error("no a=setup found at SDP session or media level");
} else if (!fingerprint) {
throw new Error("no a=fingerprint found at SDP session or media level");
}
let role;
switch (setup) {
case "active": {
role = "client";
break;
}
case "passive": {
role = "server";
break;
}
case "actpass": {
role = "auto";
break;
}
}
const dtlsParameters = {
role,
fingerprints: [
{
algorithm: fingerprint.type,
value: fingerprint.hash
}
]
};
return dtlsParameters;
}
function getCname({ offerMediaObject }) {
var _a2;
const ssrcCnameLine = ((_a2 = offerMediaObject.ssrcs) != null ? _a2 : []).find((line) => line.attribute === "cname");
if (!ssrcCnameLine) {
return "";
}
return ssrcCnameLine.value;
}
function applyCodecParameters({ offerRtpParameters, answerMediaObject }) {
var _a2, _b2, _c;
for (const codec of offerRtpParameters.codecs) {
const mimeType = codec.mimeType.toLowerCase();
if (mimeType !== "audio/opus") {
continue;
}
const rtp = ((_a2 = answerMediaObject.rtp) != null ? _a2 : []).find((r2) => r2.payload === codec.payloadType);
if (!rtp) {
continue;
}
answerMediaObject.fmtp = (_b2 = answerMediaObject.fmtp) != null ? _b2 : [];
let fmtp = answerMediaObject.fmtp.find((f) => f.payload === codec.payloadType);
if (!fmtp) {
fmtp = { payload: codec.payloadType, config: "" };
answerMediaObject.fmtp.push(fmtp);
}
const parameters = sdpTransform4.parseParams(fmtp.config);
switch (mimeType) {
case "audio/opus": {
const spropStereo = (_c = codec.parameters) == null ? void 0 : _c["sprop-stereo"];
if (spropStereo !== void 0) {
parameters["stereo"] = Number(spropStereo) ? 1 : 0;
}
break;
}
}
fmtp.config = "";
for (const key of Object.keys(parameters)) {
if (fmtp.config) {
fmtp.config += ";";
}
fmtp.config += `${key}=${parameters[key]}`;
}
}
}
function addHeaderExtension({ offerMediaObject, headerExtensionUri, headerExtensionId }) {
if (!offerMediaObject.ext) {
offerMediaObject.ext = [];
}
offerMediaObject.ext.push({
uri: headerExtensionUri,
value: headerExtensionId
});
}
}
});
// ../../node_modules/.pnpm/mediasoup-client@3.18.3/node_modules/mediasoup-client/lib/handlers/sdp/unifiedPlanUtils.js
var require_unifiedPlanUtils = __commonJS({
"../../node_modules/.pnpm/mediasoup-client@3.18.3/node_modules/mediasoup-client/lib/handlers/sdp/unifiedPlanUtils.js"(exports) {
"use strict";
init_process();
Object.defineProperty(exports, "__esModule", { value: true });
exports.getRtpEncodings = getRtpEncodings;
exports.addLegacySimulcast = addLegacySimulcast;
function getRtpEncodings({ offerMediaObject }) {
var _a2, _b2;
const ssrcs = /* @__PURE__ */ new Set();
for (const line of (_a2 = offerMediaObject.ssrcs) != null ? _a2 : []) {
const ssrc = line.id;
if (ssrc) {
ssrcs.add(ssrc);
}
}
if (ssrcs.size === 0) {
throw new Error("no a=ssrc lines found");
}
const ssrcToRtxSsrc = /* @__PURE__ */ new Map();
for (const line of (_b2 = offerMediaObject.ssrcGroups) != null ? _b2 : []) {
if (line.semantics !== "FID") {
continue;
}
const ssrcsStr = line.ssrcs.split(/\s+/);
const ssrc = Number(ssrcsStr[0]);
const rtxSsrc = Number(ssrcsStr[1]);
if (ssrcs.has(ssrc)) {
ssrcs.delete(ssrc);
ssrcs.delete(rtxSsrc);
ssrcToRtxSsrc.set(ssrc, rtxSsrc);
}
}
for (const ssrc of ssrcs) {
ssrcToRtxSsrc.set(ssrc, void 0);
}
const encodings = [];
for (const [ssrc, rtxSsrc] of ssrcToRtxSsrc) {
const encoding = { ssrc };
if (rtxSsrc) {
encoding.rtx = { ssrc: rtxSsrc };
}
encodings.push(encoding);
}
return encodings;
}
function addLegacySimulcast({ offerMediaObject, numStreams }) {
var _a2, _b2, _c;
if (numStreams <= 1) {
throw new TypeError("numStreams must be greater than 1");
}
const ssrcMsidLine = ((_a2 = offerMediaObject.ssrcs) != null ? _a2 : []).find((line) => line.attribute === "msid");
if (!ssrcMsidLine) {
throw new Error("a=ssrc line with msid information not found");
}
const [streamId, trackId] = ssrcMsidLine.value.split(" ");
const firstSsrc = Number(ssrcMsidLine.id);
let firstRtxSsrc;
((_b2 = offerMediaObject.ssrcGroups) != null ? _b2 : []).some((line) => {
if (line.semantics !== "FID") {
return false;
}
const ssrcs2 = line.ssrcs.split(/\s+/);
if (Number(ssrcs2[0]) === firstSsrc) {
firstRtxSsrc = Number(ssrcs2[1]);
return true;
} else {
return false;
}
});
const ssrcCnameLine = ((_c = offerMediaObject.ssrcs) != null ? _c : []).find((line) => line.attribute === "cname");
if (!ssrcCnameLine) {
throw new Error("a=ssrc line with cname information not found");
}
const cname = ssrcCnameLine.value;
const ssrcs = [];
const rtxSsrcs = [];
for (let i = 0; i < numStreams; ++i) {
ssrcs.push(firstSsrc + i);
if (firstRtxSsrc) {
rtxSsrcs.push(firstRtxSsrc + i);
}
}
offerMediaObject.ssrcGroups = [];
offerMediaObject.ssrcs = [];
offerMediaObject.ssrcGroups.push({
semantics: "SIM",
ssrcs: ssrcs.join(" ")
});
for (const ssrc of ssrcs) {
offerMediaObject.ssrcs.push({
id: ssrc,
attribute: "cname",
value: cname
});
offerMediaObject.ssrcs.push({
id: ssrc,
attribute: "msid",
value: `${streamId} ${trackId}`
});
}
for (let i = 0; i < rtxSsrcs.length; ++i) {
const ssrc = ssrcs[i];
const rtxSsrc = rtxSsrcs[i];
offerMediaObject.ssrcs.push({
id: rtxSsrc,
attribute: "cname",
value: cname
});
offerMediaObject.ssrcs.push({
id: rtxSsrc,
attribute: "msid",
value: `${streamId} ${trackId}`
});
offerMediaObject.ssrcGroups.push({
semantics: "FID",
ssrcs: `${ssrc} ${rtxSsrc}`
});
}
}
}
});
// ../../node_modules/.pnpm/mediasoup-client@3.18.3/node_modules/mediasoup-client/lib/handlers/ortc/utils.js
var require_utils2 = __commonJS({
"../../node_modules/.pnpm/mediasoup-client@3.18.3/node_modules/mediasoup-client/lib/handlers/ortc/utils.js"(exports) {
"use strict";
init_process();
Object.defineProperty(exports, "__esModule", { value: true });
exports.addNackSupportForOpus = addNackSupportForOpus;
exports.addHeaderExtensionSupport = addHeaderExtensionSupport;
exports.getMsidStreamIdAndTrackId = getMsidStreamIdAndTrackId;
function addNackSupportForOpus(rtpCapabilities) {
var _a2, _b2;
for (const codec of (_a2 = rtpCapabilities.codecs) != null ? _a2 : []) {
if ((codec.mimeType.toLowerCase() === "audio/opus" || codec.mimeType.toLowerCase() === "audio/multiopus") && !((_b2 = codec.rtcpFeedback) == null ? void 0 : _b2.some((fb) => fb.type === "nack" && !fb.parameter))) {
if (!codec.rtcpFeedback) {
codec.rtcpFeedback = [];
}
codec.rtcpFeedback.push({ type: "nack" });
}
}
}
function addHeaderExtensionSupport(rtpCapabilities, headerExtension) {
var _a2;
let preferredId;
const existingHeaderExtension = (_a2 = rtpCapabilities.headerExtensions) == null ? void 0 : _a2.find((exten) => exten.uri === headerExtension.uri);
if (existingHeaderExtension) {
if (existingHeaderExtension.kind === headerExtension.kind) {
return;
} else {
preferredId = existingHeaderExtension.preferredId;
}
}
if (!rtpCapabilities.headerExtensions) {
rtpCapabilities.headerExtensions = [];
}
if (preferredId === void 0) {
preferredId = 1;
const setPreferredIds = new Set(rtpCapabilities.headerExtensions.map((exten) => exten.preferredId));
while (setPreferredIds.has(preferredId)) {
++preferredId;
}
}
const newHeaderExtension = {
kind: headerExtension.kind,
uri: headerExtension.uri,
preferredId,
preferredEncrypt: false,
direction: headerExtension.direction
};
rtpCapabilities.headerExtensions.push(newHeaderExtension);
}
function getMsidStreamIdAndTrackId(msid) {
if (!msid || typeof msid !== "string") {
return { msidStreamId: void 0, msidTrackId: void 0 };
}
const [msidStreamId, msidTrackId] = msid.trim().split(/\s+/);
if (!msidStreamId) {
return { msidStreamId: void 0, msidTrackId: void 0 };
}
return { msidStreamId, msidTrackId };
}
}
});
// ../../node_modules/.pnpm/mediasoup-client@3.18.3/node_modules/mediasoup-client/lib/handlers/Chrome111.js
var require_Chrome111 = __commonJS({
"../../node_modules/.pnpm/mediasoup-client@3.18.3/node_modules/mediasoup-client/lib/handlers/Chrome111.js"(exports) {
"use strict";
init_process();
Object.defineProperty(exports, "__esModule", { value: true });
exports.Chrome111 = void 0;
var sdpTransform4 = require_lib4();
var enhancedEvents_1 = require_enhancedEvents();
var Logger_1 = require_Logger();
var ortc = require_ortc();
var errors_1 = require_errors();
var scalabilityModes_1 = require_scalabilityModes();
var RemoteSdp_1 = require_RemoteSdp();
var sdpCommonUtils = require_commonUtils();
var sdpUnifiedPlanUtils = require_unifiedPlanUtils();
var ortcUtils = require_utils2();
var logger2 = new Logger_1.Logger("Chrome111");
var NAME = "Chrome111";
var SCTP_NUM_STREAMS = { OS: 1024, MIS: 1024 };
var Chrome111 = class _Chrome111 extends enhancedEvents_1.EnhancedEventEmitter {
constructor({ direction, iceParameters, iceCandidates, dtlsParameters, sctpParameters, iceServers, iceTransportPolicy, additionalSettings, getSendExtendedRtpCapabilities }) {
super();
// Closed flag.
__publicField(this, "_closed", false);
// Handler direction.
__publicField(this, "_direction");
// Remote SDP handler.
__publicField(this, "_remoteSdp");
// Callback to request sending extended RTP capabilities on demand.
__publicField(this, "_getSendExtendedRtpCapabilities");
// Initial server side DTLS role. If not 'auto', it will force the opposite
// value in client side.
__publicField(this, "_forcedLocalDtlsRole");
// RTCPeerConnection instance.
__publicField(this, "_pc");
// Map of RTCTransceivers indexed by MID.
__publicField(this, "_mapMidTransceiver", /* @__PURE__ */ new Map());
// Default local stream for sending if no `streamId` is given in send().
__publicField(this, "_sendStream", new MediaStream());
// Whether a DataChannel m=application section has been created.
__publicField(this, "_hasDataChannelMediaSection", false);
// Sending DataChannel id value counter. Incremented for each new DataChannel.
__publicField(this, "_nextSendSctpStreamId", 0);
// Got transport local and remote parameters.
__publicField(this, "_transportReady", false);
__publicField(this, "onIceGatheringStateChange", () => {
this.emit("@icegatheringstatechange", this._pc.iceGatheringState);
});
__publicField(this, "onIceCandidateError", (event) => {
this.emit("@icecandidateerror", event);
});
__publicField(this, "onConnectionStateChange", () => {
this.emit("@connectionstatechange", this._pc.connectionState);
});
__publicField(this, "onIceConnectionStateChange", () => {
switch (this._pc.iceConnectionState) {
case "checking": {
this.emit("@connectionstatechange", "connecting");
break;
}
case "connected":
case "completed": {
this.emit("@connectionstatechange", "connected");
break;
}
case "failed": {
this.emit("@connectionstatechange", "failed");
break;
}
case "disconnected": {
this.emit("@connectionstatechange", "disconnected");
break;
}
case "closed": {
this.emit("@connectionstatechange", "closed");
break;
}
}
});
logger2.debug("constructor()");
this._direction = direction;
this._remoteSdp = new RemoteSdp_1.RemoteSdp({
iceParameters,
iceCandidates,
dtlsParameters,
sctpParameters
});
this._getSendExtendedRtpCapabilities = getSendExtendedRtpCapabilities;
if (dtlsParameters.role && dtlsParameters.role !== "auto") {
this._forcedLocalDtlsRole = dtlsParameters.role === "server" ? "client" : "server";
}
this._pc = new RTCPeerConnection(__spreadValues({
iceServers: iceServers != null ? iceServers : [],
iceTransportPolicy: iceTransportPolicy != null ? iceTransportPolicy : "all",
bundlePolicy: "max-bundle",
rtcpMuxPolicy: "require"
}, additionalSettings));
this._pc.addEventListener("icegatheringstatechange", this.onIceGatheringStateChange);
this._pc.addEventListener("icecandidateerror", this.onIceCandidateError);
if (this._pc.connectionState) {
this._pc.addEventListener("connectionstatechange", this.onConnectionStateChange);
} else {
logger2.warn("run() | pc.connectionState not supported, using pc.iceConnectionState");
this._pc.addEventListener("iceconnectionstatechange", this.onIceConnectionStateChange);
}
}
/**
* Creates a factory function.
*/
static createFactory() {
return {
name: NAME,
factory: (options) => new _Chrome111(options),
getNativeRtpCapabilities: () => __async(null, null, function* () {
logger2.debug("getNativeRtpCapabilities()");
let pc = new RTCPeerConnection({
iceServers: [],
iceTransportPolicy: "all",
bundlePolicy: "max-bundle",
rtcpMuxPolicy: "require"
});
try {
pc.addTransceiver("audio");
pc.addTransceiver("video", {
sendEncodings: [{ scalabilityMode: "L3T3" }]
});
const offer = yield pc.createOffer();
try {
pc.close();
} catch (error) {
}
pc = void 0;
const sdpObject = sdpTransform4.parse(offer.sdp);
const nativeRtpCapabilities = _Chrome111.getLocalRtpCapabilities(sdpObject);
return nativeRtpCapabilities;
} catch (error) {
try {
pc == null ? void 0 : pc.close();
} catch (error2) {
}
pc = void 0;
throw error;
}
}),
getNativeSctpCapabilities: () => __async(null, null, function* () {
logger2.debug("getNativeSctpCapabilities()");
return {
numStreams: SCTP_NUM_STREAMS
};
})
};
}
static getLocalRtpCapabilities(localSdpObject, extraHeaderExtensions = []) {
const nativeRtpCapabilities = sdpCommonUtils.extractRtpCapabilities({
sdpObject: localSdpObject
});
ortc.validateAndNormalizeRtpCapabilities(nativeRtpCapabilities);
ortcUtils.addNackSupportForOpus(nativeRtpCapabilities);
for (const headerExtension of extraHeaderExtensions) {
ortcUtils.addHeaderExtensionSupport(nativeRtpCapabilities, headerExtension);
}
return nativeRtpCapabilities;
}
get name() {
return NAME;
}
close() {
logger2.debug("close()");
if (this._closed) {
return;
}
this._closed = true;
try {
this._pc.close();
} catch (error) {
}
this._pc.removeEventListener("icegatheringstatechange", this.onIceGatheringStateChange);
this._pc.removeEventListener("icecandidateerror", this.onIceCandidateError);
this._pc.removeEventListener("connectionstatechange", this.onConnectionStateChange);
this._pc.removeEventListener("iceconnectionstatechange", this.onIceConnectionStateChange);
this.emit("@close");
super.close();
}
updateIceServers(iceServers) {
return __async(this, null, function* () {
this.assertNotClosed();
logger2.debug("updateIceServers()");
const configuration = this._pc.getConfiguration();
configuration.iceServers = iceServers;
this._pc.setConfiguration(configuration);
});
}
restartIce(iceParameters) {
return __async(this, null, function* () {
this.assertNotClosed();
logger2.debug("restartIce()");
this._remoteSdp.updateIceParameters(iceParameters);
if (!this._transportReady) {
return;
}
if (this._direction === "send") {
const offer = yield this._pc.createOffer({ iceRestart: true });
logger2.debug("restartIce() | calling pc.setLocalDescription() [offer:%o]", offer);
yield this._pc.setLocalDescription(offer);
const answer = {
type: "answer",
sdp: this._remoteSdp.getSdp()
};
logger2.debug("restartIce() | calling pc.setRemoteDescription() [answer:%o]", answer);
yield this._pc.setRemoteDescription(answer);
} else {
const offer = {
type: "offer",
sdp: this._remoteSdp.getSdp()
};
logger2.debug("restartIce() | calling pc.setRemoteDescription() [offer:%o]", offer);
yield this._pc.setRemoteDescription(offer);
const answer = yield this._pc.createAnswer();
logger2.debug("restartIce() | calling pc.setLocalDescription() [answer:%o]", answer);
yield this._pc.setLocalDescription(answer);
}
});
}
getTransportStats() {
return __async(this, null, function* () {
this.assertNotClosed();
return this._pc.getStats();
});
}
send(_0) {
return __async(this, arguments, function* ({ track, streamId, encodings, codecOptions, headerExtensionOptions, codec, onRtpSender }) {
var _a2;
this.assertNotClosed();
this.assertSendDirection();
logger2.debug("send() [kind:%s, track.id:%s, streamId:%s]", track.kind, track.id, streamId);
if (encodings && encodings.length > 1) {
let maxTemporalLayers = 1;
for (const encoding of encodings) {
const temporalLayers = encoding.scalabilityMode ? (0, scalabilityModes_1.parse)(encoding.scalabilityMode).temporalLayers : 3;
if (temporalLayers > maxTemporalLayers) {
maxTemporalLayers = temporalLayers;
}
}
encodings.forEach((encoding, idx) => {
encoding.rid = `r${idx}`;
encoding.scalabilityMode = `L1T${maxTemporalLayers}`;
});
}
const mediaSectionIdx = this._remoteSdp.getNextMediaSectionIdx();
const transceiver = this._pc.addTransceiver(track, {
direction: "sendonly",
streams: [this._sendStream],
sendEncodings: encodings
});
if (onRtpSender) {
onRtpSender(transceiver.sender);
}
let offer = yield this._pc.createOffer();
let localSdpObject = sdpTransform4.parse(offer.sdp);
if (localSdpObject.extmapAllowMixed) {
this._remoteSdp.setSessionExtmapAllowMixed();
}
const extraHeaderExtensions = [];
extraHeaderExtensions.push({
uri: "http://www.webrtc.org/experiments/rtp-hdrext/abs-capture-time",
kind: track.kind,
direction: "sendonly"
});
const nativeRtpCapabilities = _Chrome111.getLocalRtpCapabilities(localSdpObject, extraHeaderExtensions);
const sendExtendedRtpCapabilities = this._getSendExtendedRtpCapabilities(nativeRtpCapabilities);
const sendingRtpParameters = ortc.getSendingRtpParameters(track.kind, sendExtendedRtpCapabilities);
sendingRtpParameters.codecs = ortc.reduceCodecs(sendingRtpParameters.codecs, codec);
const sendingRemoteRtpParameters = ortc.getSendingRemoteRtpParameters(track.kind, sendExtendedRtpCapabilities);
sendingRemoteRtpParameters.codecs = ortc.reduceCodecs(sendingRemoteRtpParameters.codecs, codec);
if (!this._transportReady) {
yield this.setupTransport({
localDtlsRole: (_a2 = this._forcedLocalDtlsRole) != null ? _a2 : "client",
localSdpObject
});
}
if (headerExtensionOptions == null ? void 0 : headerExtensionOptions.absCaptureTime) {
const offerMediaObject2 = localSdpObject.media[mediaSectionIdx.idx];
sdpCommonUtils.addHeaderExtension({
offerMediaObject: offerMediaObject2,
headerExtensionUri: "http://www.webrtc.org/experiments/rtp-hdrext/abs-capture-time",
headerExtensionId: sendingRemoteRtpParameters.headerExtensions.find((headerExtension) => headerExtension.uri === "http://www.webrtc.org/experiments/rtp-hdrext/abs-capture-time").id
});
offer = {
type: "offer",
sdp: sdpTransform4.write(localSdpObject)
};
}
logger2.debug("send() | calling pc.setLocalDescription() [offer:%o]", offer);
yield this._pc.setLocalDescription(offer);
const localId = transceiver.mid;
sendingRtpParameters.mid = localId;
localSdpObject = sdpTransform4.parse(this._pc.localDescription.sdp);
const offerMediaObject = localSdpObject.media[mediaSectionIdx.idx];
sendingRtpParameters.rtcp.cname = sdpCommonUtils.getCname({
offerMediaObject
});
sendingRtpParameters.msid = `${streamId != null ? streamId : this._sendStream.id} ${track.id}`;
if (!encodings) {
sendingRtpParameters.encodings = sdpUnifiedPlanUtils.getRtpEncodings({
offerMediaObject
});
} else if (encodings.length === 1) {
const newEncodings = sdpUnifiedPlanUtils.getRtpEncodings({
offerMediaObject
});
Object.assign(newEncodings[0], encodings[0]);
sendingRtpParameters.encodings = newEncodings;
} else {
sendingRtpParameters.encodings = encodings;
}
this._remoteSdp.send({
offerMediaObject,
reuseMid: mediaSectionIdx.reuseMid,
offerRtpParameters: sendingRtpParameters,
answerRtpParameters: sendingRemoteRtpParameters,
codecOptions
});
const answer = {
type: "answer",
sdp: this._remoteSdp.getSdp()
};
logger2.debug("send() | calling pc.setRemoteDescription() [answer:%o]", answer);
yield this._pc.setRemoteDescription(answer);
this._mapMidTransceiver.set(localId, transceiver);
return {
localId,
rtpParameters: sendingRtpParameters,
rtpSender: transceiver.sender
};
});
}
stopSending(localId) {
return __async(this, null, function* () {
this.assertSendDirection();
logger2.debug("stopSending() [localId:%s]", localId);
if (this._closed) {
return;
}
const transceiver = this._mapMidTransceiver.get(localId);
if (!transceiver) {
throw new Error("associated RTCRtpTransceiver not found");
}
void transceiver.sender.replaceTrack(null);
this._pc.removeTrack(transceiver.sender);
const mediaSectionClosed = this._remoteSdp.closeMediaSection(transceiver.mid);
if (mediaSectionClosed) {
try {
transceiver.stop();
} catch (error) {
}
}
const offer = yield this._pc.createOffer();
logger2.debug("stopSending() | calling pc.setLocalDescription() [offer:%o]", offer);
yield this._pc.setLocalDescription(offer);
const answer = {
type: "answer",
sdp: this._remoteSdp.getSdp()
};
logger2.debug("stopSending() | calling pc.setRemoteDescription() [answer:%o]", answer);
yield this._pc.setRemoteDescription(answer);
this._mapMidTransceiver.delete(localId);
});
}
pauseSending(localId) {
return __async(this, null, function* () {
this.assertNotClosed();
this.assertSendDirection();
logger2.debug("pauseSending() [localId:%s]", localId);
const transceiver = this._mapMidTransceiver.get(localId);
if (!transceiver) {
throw new Error("associated RTCRtpTransceiver not found");
}
transceiver.direction = "inactive";
this._remoteSdp.pauseMediaSection(localId);
const offer = yield this._pc.createOffer();
logger2.debug("pauseSending() | calling pc.setLocalDescription() [offer:%o]", offer);
yield this._pc.setLocalDescription(offer);
const answer = {
type: "answer",
sdp: this._remoteSdp.getSdp()
};
logger2.debug("pauseSending() | calling pc.setRemoteDescription() [answer:%o]", answer);
yield this._pc.setRemoteDescription(answer);
});
}
resumeSending(localId) {
return __async(this, null, function* () {
this.assertNotClosed();
this.assertSendDirection();
logger2.debug("resumeSending() [localId:%s]", localId);
const transceiver = this._mapMidTransceiver.get(localId);
this._remoteSdp.resumeSendingMediaSection(localId);
if (!transceiver) {
throw new Error("associated RTCRtpTransceiver not found");
}
transceiver.direction = "sendonly";
const offer = yield this._pc.createOffer();
logger2.debug("resumeSending() | calling pc.setLocalDescription() [offer:%o]", offer);
yield this._pc.setLocalDescription(offer);
const answer = {
type: "answer",
sdp: this._remoteSdp.getSdp()
};
logger2.debug("resumeSending() | calling pc.setRemoteDescription() [answer:%o]", answer);
yield this._pc.setRemoteDescription(answer);
});
}
replaceTrack(localId, track) {
return __async(this, null, function* () {
this.assertNotClosed();
this.assertSendDirection();
if (track) {
logger2.debug("replaceTrack() [localId:%s, track.id:%s]", localId, track.id);
} else {
logger2.debug("replaceTrack() [localId:%s, no track]", localId);
}
const transceiver = this._mapMidTransceiver.get(localId);
if (!transceiver) {
throw new Error("associated RTCRtpTransceiver not found");
}
yield transceiver.sender.replaceTrack(track);
});
}
setMaxSpatialLayer(localId, spatialLayer) {
return __async(this, null, function* () {
this.assertNotClosed();
this.assertSendDirection();
logger2.debug("setMaxSpatialLayer() [localId:%s, spatialLayer:%s]", localId, spatialLayer);
const transceiver = this._mapMidTransceiver.get(localId);
if (!transceiver) {
throw new Error("associated RTCRtpTransceiver not found");
}
const parameters = transceiver.sender.getParameters();
parameters.encodings.forEach((encoding, idx) => {
if (idx <= spatialLayer) {
encoding.active = true;
} else {
encoding.active = false;
}
});
yield transceiver.sender.setParameters(parameters);
this._remoteSdp.muxMediaSectionSimulcast(localId, parameters.encodings);
const offer = yield this._pc.createOffer();
logger2.debug("setMaxSpatialLayer() | calling pc.setLocalDescription() [offer:%o]", offer);
yield this._pc.setLocalDescription(offer);
const answer = {
type: "answer",
sdp: this._remoteSdp.getSdp()
};
logger2.debug("setMaxSpatialLayer() | calling pc.setRemoteDescription() [answer:%o]", answer);
yield this._pc.setRemoteDescription(answer);
});
}
setRtpEncodingParameters(localId, params) {
return __async(this, null, function* () {
this.assertNotClosed();
this.assertSendDirection();
logger2.debug("setRtpEncodingParameters() [localId:%s, params:%o]", localId, params);
const transceiver = this._mapMidTransceiver.get(localId);
if (!transceiver) {
throw new Error("associated RTCRtpTransceiver not found");
}
const parameters = transceiver.sender.getParameters();
parameters.encodings.forEach((encoding, idx) => {
parameters.encodings[idx] = __spreadValues(__spreadValues({}, encoding), params);
});
yield transceiver.sender.setParameters(parameters);
this._remoteSdp.muxMediaSectionSimulcast(localId, parameters.encodings);
const offer = yield this._pc.createOffer();
logger2.debug("setRtpEncodingParameters() | calling pc.setLocalDescription() [offer:%o]", offer);
yield this._pc.setLocalDescription(offer);
const answer = {
type: "answer",
sdp: this._remoteSdp.getSdp()
};
logger2.debug("setRtpEncodingParameters() | calling pc.setRemoteDescription() [answer:%o]", answer);
yield this._pc.setRemoteDescription(answer);
});
}
getSenderStats(localId) {
return __async(this, null, function* () {
this.assertNotClosed();
this.assertSendDirection();
const transceiver = this._mapMidTransceiver.get(localId);
if (!transceiver) {
throw new Error("associated RTCRtpTransceiver not found");
}
return transceiver.sender.getStats();
});
}
sendDataChannel(_0) {
return __async(this, arguments, function* ({ ordered, maxPacketLifeTime, maxRetransmits, label, protocol }) {
var _a2;
this.assertNotClosed();
this.assertSendDirection();
const options = {
negotiated: true,
id: this._nextSendSctpStreamId,
ordered,
maxPacketLifeTime,
maxRetransmits,
protocol
};
logger2.debug("sendDataChannel() [options:%o]", options);
const dataChannel = this._pc.createDataChannel(label, options);
this._nextSendSctpStreamId = ++this._nextSendSctpStreamId % SCTP_NUM_STREAMS.MIS;
if (!this._hasDataChannelMediaSection) {
const offer = yield this._pc.createOffer();
const localSdpObject = sdpTransform4.parse(offer.sdp);
const offerMediaObject = localSdpObject.media.find((m) => m.type === "application");
if (!this._transportReady) {
yield this.setupTransport({
localDtlsRole: (_a2 = this._forcedLocalDtlsRole) != null ? _a2 : "client",
localSdpObject
});
}
logger2.debug("sendDataChannel() | calling pc.setLocalDescription() [offer:%o]", offer);
yield this._pc.setLocalDescription(offer);
this._remoteSdp.sendSctpAssociation({ offerMediaObject });
const answer = {
type: "answer",
sdp: this._remoteSdp.getSdp()
};
logger2.debug("sendDataChannel() | calling pc.setRemoteDescription() [answer:%o]", answer);
yield this._pc.setRemoteDescription(answer);
this._hasDataChannelMediaSection = true;
}
const sctpStreamParameters = {
streamId: options.id,
ordered: options.ordered,
maxPacketLifeTime: options.maxPacketLifeTime,
maxRetransmits: options.maxRetransmits
};
return { dataChannel, sctpStreamParameters };
});
}
receive(optionsList) {
return __async(this, null, function* () {
var _a2, _b2, _c, _d, _e;
this.assertNotClosed();
this.assertRecvDirection();
const results = [];
const mapLocalId = /* @__PURE__ */ new Map();
for (const options of optionsList) {
const { trackId, kind, rtpParameters, streamId } = options;
logger2.debug("receive() [trackId:%s, kind:%s]", trackId, kind);
const localId = (_a2 = rtpParameters.mid) != null ? _a2 : String(this._mapMidTransceiver.size);
mapLocalId.set(trackId, localId);
const { msidStreamId } = ortcUtils.getMsidStreamIdAndTrackId(rtpParameters.msid);
this._remoteSdp.receive({
mid: localId,
kind,
offerRtpParameters: rtpParameters,
streamId: (_d = (_c = streamId != null ? streamId : msidStreamId) != null ? _c : (_b2 = rtpParameters.rtcp) == null ? void 0 : _b2.cname) != null ? _d : "-",
trackId
});
}
const offer = {
type: "offer",
sdp: this._remoteSdp.getSdp()
};
logger2.debug("receive() | calling pc.setRemoteDescription() [offer:%o]", offer);
yield this._pc.setRemoteDescription(offer);
for (const options of optionsList) {
const { trackId, onRtpReceiver } = options;
if (onRtpReceiver) {
const localId = mapLocalId.get(trackId);
const transceiver = this._pc.getTransceivers().find((t2) => t2.mid === localId);
if (!transceiver) {
throw new Error("transceiver not found");
}
onRtpReceiver(transceiver.receiver);
}
}
let answer = yield this._pc.createAnswer();
const localSdpObject = sdpTransform4.parse(answer.sdp);
for (const options of optionsList) {
const { trackId, rtpParameters } = options;
const localId = mapLocalId.get(trackId);
const answerMediaObject = localSdpObject.media.find((m) => String(m.mid) === localId);
sdpCommonUtils.applyCodecParameters({
offerRtpParameters: rtpParameters,
answerMediaObject
});
}
answer = {
type: "answer",
sdp: sdpTransform4.write(localSdpObject)
};
if (!this._transportReady) {
yield this.setupTransport({
localDtlsRole: (_e = this._forcedLocalDtlsRole) != null ? _e : "client",
localSdpObject
});
}
logger2.debug("receive() | calling pc.setLocalDescription() [answer:%o]", answer);
yield this._pc.setLocalDescription(answer);
for (const options of optionsList) {
const { trackId } = options;
const localId = mapLocalId.get(trackId);
const transceiver = this._pc.getTransceivers().find((t2) => t2.mid === localId);
if (!transceiver) {
throw new Error("new RTCRtpTransceiver not found");
} else {
this._mapMidTransceiver.set(localId, transceiver);
results.push({
localId,
track: transceiver.receiver.track,
rtpReceiver: transceiver.receiver
});
}
}
return results;
});
}
stopReceiving(localIds) {
return __async(this, null, function* () {
this.assertRecvDirection();
if (this._closed) {
return;
}
for (const localId of localIds) {
logger2.debug("stopReceiving() [localId:%s]", localId);
const transceiver = this._mapMidTransceiver.get(localId);
if (!transceiver) {
throw new Error("associated RTCRtpTransceiver not found");
}
this._remoteSdp.closeMediaSection(transceiver.mid);
}
const offer = {
type: "offer",
sdp: this._remoteSdp.getSdp()
};
logger2.debug("stopReceiving() | calling pc.setRemoteDescription() [offer:%o]", offer);
yield this._pc.setRemoteDescription(offer);
const answer = yield this._pc.createAnswer();
logger2.debug("stopReceiving() | calling pc.setLocalDescription() [answer:%o]", answer);
yield this._pc.setLocalDescription(answer);
for (const localId of localIds) {
this._mapMidTransceiver.delete(localId);
}
});
}
pauseReceiving(localIds) {
return __async(this, null, function* () {
this.assertNotClosed();
this.assertRecvDirection();
for (const localId of localIds) {
logger2.debug("pauseReceiving() [localId:%s]", localId);
const transceiver = this._mapMidTransceiver.get(localId);
if (!transceiver) {
throw new Error("associated RTCRtpTransceiver not found");
}
transceiver.direction = "inactive";
this._remoteSdp.pauseMediaSection(localId);
}
const offer = {
type: "offer",
sdp: this._remoteSdp.getSdp()
};
logger2.debug("pauseReceiving() | calling pc.setRemoteDescription() [offer:%o]", offer);
yield this._pc.setRemoteDescription(offer);
const answer = yield this._pc.createAnswer();
logger2.debug("pauseReceiving() | calling pc.setLocalDescription() [answer:%o]", answer);
yield this._pc.setLocalDescription(answer);
});
}
resumeReceiving(localIds) {
return __async(this, null, function* () {
this.assertNotClosed();
this.assertRecvDirection();
for (const localId of localIds) {
logger2.debug("resumeReceiving() [localId:%s]", localId);
const transceiver = this._mapMidTransceiver.get(localId);
if (!transceiver) {
throw new Error("associated RTCRtpTransceiver not found");
}
transceiver.direction = "recvonly";
this._remoteSdp.resumeReceivingMediaSection(localId);
}
const offer = {
type: "offer",
sdp: this._remoteSdp.getSdp()
};
logger2.debug("resumeReceiving() | calling pc.setRemoteDescription() [offer:%o]", offer);
yield this._pc.setRemoteDescription(offer);
const answer = yield this._pc.createAnswer();
logger2.debug("resumeReceiving() | calling pc.setLocalDescription() [answer:%o]", answer);
yield this._pc.setLocalDescription(answer);
});
}
getReceiverStats(localId) {
return __async(this, null, function* () {
this.assertNotClosed();
this.assertRecvDirection();
const transceiver = this._mapMidTransceiver.get(localId);
if (!transceiver) {
throw new Error("associated RTCRtpTransceiver not found");
}
return transceiver.receiver.getStats();
});
}
receiveDataChannel(_0) {
return __async(this, arguments, function* ({ sctpStreamParameters, label, protocol }) {
var _a2;
this.assertNotClosed();
this.assertRecvDirection();
const { streamId, ordered, maxPacketLifeTime, maxRetransmits } = sctpStreamParameters;
const options = {
negotiated: true,
id: streamId,
ordered,
maxPacketLifeTime,
maxRetransmits,
protocol
};
logger2.debug("receiveDataChannel() [options:%o]", options);
const dataChannel = this._pc.createDataChannel(label, options);
if (!this._hasDataChannelMediaSection) {
this._remoteSdp.receiveSctpAssociation();
const offer = {
type: "offer",
sdp: this._remoteSdp.getSdp()
};
logger2.debug("receiveDataChannel() | calling pc.setRemoteDescription() [offer:%o]", offer);
yield this._pc.setRemoteDescription(offer);
const answer = yield this._pc.createAnswer();
if (!this._transportReady) {
const localSdpObject = sdpTransform4.parse(answer.sdp);
yield this.setupTransport({
localDtlsRole: (_a2 = this._forcedLocalDtlsRole) != null ? _a2 : "client",
localSdpObject
});
}
logger2.debug("receiveDataChannel() | calling pc.setRemoteDescription() [answer:%o]", answer);
yield this._pc.setLocalDescription(answer);
this._hasDataChannelMediaSection = true;
}
return { dataChannel };
});
}
setupTransport(_0) {
return __async(this, arguments, function* ({ localDtlsRole, localSdpObject }) {
if (!localSdpObject) {
localSdpObject = sdpTransform4.parse(this._pc.localDescription.sdp);
}
const dtlsParameters = sdpCommonUtils.extractDtlsParameters({
sdpObject: localSdpObject
});
dtlsParameters.role = localDtlsRole;
this._remoteSdp.updateDtlsRole(localDtlsRole === "client" ? "server" : "client");
yield new Promise((resolve, reject) => {
this.safeEmit("@connect", { dtlsParameters }, resolve, reject);
});
this._transportReady = true;
});
}
assertNotClosed() {
if (this._closed) {
throw new errors_1.InvalidStateError("method called in a closed handler");
}
}
assertSendDirection() {
if (this._direction !== "send") {
throw new Error('method can just be called for handlers with "send" direction');
}
}
assertRecvDirection() {
if (this._direction !== "recv") {
throw new Error('method can just be called for handlers with "recv" direction');
}
}
};
exports.Chrome111 = Chrome111;
}
});
// ../../node_modules/.pnpm/mediasoup-client@3.18.3/node_modules/mediasoup-client/lib/handlers/Chrome74.js
var require_Chrome74 = __commonJS({
"../../node_modules/.pnpm/mediasoup-client@3.18.3/node_modules/mediasoup-client/lib/handlers/Chrome74.js"(exports) {
"use strict";
init_process();
Object.defineProperty(exports, "__esModule", { value: true });
exports.Chrome74 = void 0;
var sdpTransform4 = require_lib4();
var Logger_1 = require_Logger();
var enhancedEvents_1 = require_enhancedEvents();
var ortc = require_ortc();
var errors_1 = require_errors();
var scalabilityModes_1 = require_scalabilityModes();
var RemoteSdp_1 = require_RemoteSdp();
var sdpCommonUtils = require_commonUtils();
var sdpUnifiedPlanUtils = require_unifiedPlanUtils();
var ortcUtils = require_utils2();
var logger2 = new Logger_1.Logger("Chrome74");
var NAME = "Chrome74";
var SCTP_NUM_STREAMS = { OS: 1024, MIS: 1024 };
var Chrome74 = class _Chrome74 extends enhancedEvents_1.EnhancedEventEmitter {
constructor({ direction, iceParameters, iceCandidates, dtlsParameters, sctpParameters, iceServers, iceTransportPolicy, additionalSettings, getSendExtendedRtpCapabilities }) {
super();
// Closed flag.
__publicField(this, "_closed", false);
// Handler direction.
__publicField(this, "_direction");
// Remote SDP handler.
__publicField(this, "_remoteSdp");
// Callback to request sending extended RTP capabilities on demand.
__publicField(this, "_getSendExtendedRtpCapabilities");
// Initial server side DTLS role. If not 'auto', it will force the opposite
// value in client side.
__publicField(this, "_forcedLocalDtlsRole");
// RTCPeerConnection instance.
__publicField(this, "_pc");
// Map of RTCTransceivers indexed by MID.
__publicField(this, "_mapMidTransceiver", /* @__PURE__ */ new Map());
// Default local stream for sending if no `streamId` is given in send().
__publicField(this, "_sendStream", new MediaStream());
// Whether a DataChannel m=application section has been created.
__publicField(this, "_hasDataChannelMediaSection", false);
// Sending DataChannel id value counter. Incremented for each new DataChannel.
__publicField(this, "_nextSendSctpStreamId", 0);
// Got transport local and remote parameters.
__publicField(this, "_transportReady", false);
__publicField(this, "onIceGatheringStateChange", () => {
this.emit("@icegatheringstatechange", this._pc.iceGatheringState);
});
__publicField(this, "onIceCandidateError", (event) => {
this.emit("@icecandidateerror", event);
});
__publicField(this, "onConnectionStateChange", () => {
this.emit("@connectionstatechange", this._pc.connectionState);
});
__publicField(this, "onIceConnectionStateChange", () => {
switch (this._pc.iceConnectionState) {
case "checking": {
this.emit("@connectionstatechange", "connecting");
break;
}
case "connected":
case "completed": {
this.emit("@connectionstatechange", "connected");
break;
}
case "failed": {
this.emit("@connectionstatechange", "failed");
break;
}
case "disconnected": {
this.emit("@connectionstatechange", "disconnected");
break;
}
case "closed": {
this.emit("@connectionstatechange", "closed");
break;
}
}
});
logger2.debug("constructor()");
this._direction = direction;
this._remoteSdp = new RemoteSdp_1.RemoteSdp({
iceParameters,
iceCandidates,
dtlsParameters,
sctpParameters
});
this._getSendExtendedRtpCapabilities = getSendExtendedRtpCapabilities;
if (dtlsParameters.role && dtlsParameters.role !== "auto") {
this._forcedLocalDtlsRole = dtlsParameters.role === "server" ? "client" : "server";
}
this._pc = new RTCPeerConnection(__spreadValues({
iceServers: iceServers != null ? iceServers : [],
iceTransportPolicy: iceTransportPolicy != null ? iceTransportPolicy : "all",
bundlePolicy: "max-bundle",
rtcpMuxPolicy: "require"
}, additionalSettings));
this._pc.addEventListener("icegatheringstatechange", this.onIceGatheringStateChange);
this._pc.addEventListener("icecandidateerror", this.onIceCandidateError);
if (this._pc.connectionState) {
this._pc.addEventListener("connectionstatechange", this.onConnectionStateChange);
} else {
logger2.warn("run() | pc.connectionState not supported, using pc.iceConnectionState");
this._pc.addEventListener("iceconnectionstatechange", this.onIceConnectionStateChange);
}
}
/**
* Creates a factory function.
*/
static createFactory() {
return {
name: NAME,
factory: (options) => new _Chrome74(options),
getNativeRtpCapabilities: () => __async(null, null, function* () {
logger2.debug("getNativeRtpCapabilities()");
let pc = new RTCPeerConnection({
iceServers: [],
iceTransportPolicy: "all",
bundlePolicy: "max-bundle",
rtcpMuxPolicy: "require"
});
try {
pc.addTransceiver("audio");
pc.addTransceiver("video");
const offer = yield pc.createOffer();
try {
pc.close();
} catch (error) {
}
pc = void 0;
const sdpObject = sdpTransform4.parse(offer.sdp);
const nativeRtpCapabilities = _Chrome74.getLocalRtpCapabilities(sdpObject);
return nativeRtpCapabilities;
} catch (error) {
try {
pc == null ? void 0 : pc.close();
} catch (error2) {
}
pc = void 0;
throw error;
}
}),
getNativeSctpCapabilities: () => __async(null, null, function* () {
logger2.debug("getNativeSctpCapabilities()");
return {
numStreams: SCTP_NUM_STREAMS
};
})
};
}
static getLocalRtpCapabilities(localSdpObject, extraHeaderExtensions = []) {
const nativeRtpCapabilities = sdpCommonUtils.extractRtpCapabilities({
sdpObject: localSdpObject
});
ortc.validateAndNormalizeRtpCapabilities(nativeRtpCapabilities);
ortcUtils.addNackSupportForOpus(nativeRtpCapabilities);
for (const headerExtension of extraHeaderExtensions) {
ortcUtils.addHeaderExtensionSupport(nativeRtpCapabilities, headerExtension);
}
return nativeRtpCapabilities;
}
get name() {
return NAME;
}
close() {
logger2.debug("close()");
if (this._closed) {
return;
}
this._closed = true;
try {
this._pc.close();
} catch (error) {
}
this._pc.removeEventListener("icegatheringstatechange", this.onIceGatheringStateChange);
this._pc.removeEventListener("icecandidateerror", this.onIceCandidateError);
this._pc.removeEventListener("connectionstatechange", this.onConnectionStateChange);
this._pc.removeEventListener("iceconnectionstatechange", this.onIceConnectionStateChange);
this.emit("@close");
super.close();
}
updateIceServers(iceServers) {
return __async(this, null, function* () {
this.assertNotClosed();
logger2.debug("updateIceServers()");
const configuration = this._pc.getConfiguration();
configuration.iceServers = iceServers;
this._pc.setConfiguration(configuration);
});
}
restartIce(iceParameters) {
return __async(this, null, function* () {
this.assertNotClosed();
logger2.debug("restartIce()");
this._remoteSdp.updateIceParameters(iceParameters);
if (!this._transportReady) {
return;
}
if (this._direction === "send") {
const offer = yield this._pc.createOffer({ iceRestart: true });
logger2.debug("restartIce() | calling pc.setLocalDescription() [offer:%o]", offer);
yield this._pc.setLocalDescription(offer);
const answer = {
type: "answer",
sdp: this._remoteSdp.getSdp()
};
logger2.debug("restartIce() | calling pc.setRemoteDescription() [answer:%o]", answer);
yield this._pc.setRemoteDescription(answer);
} else {
const offer = {
type: "offer",
sdp: this._remoteSdp.getSdp()
};
logger2.debug("restartIce() | calling pc.setRemoteDescription() [offer:%o]", offer);
yield this._pc.setRemoteDescription(offer);
const answer = yield this._pc.createAnswer();
logger2.debug("restartIce() | calling pc.setLocalDescription() [answer:%o]", answer);
yield this._pc.setLocalDescription(answer);
}
});
}
getTransportStats() {
return __async(this, null, function* () {
this.assertNotClosed();
return this._pc.getStats();
});
}
send(_0) {
return __async(this, arguments, function* ({ track, streamId, encodings, codecOptions, headerExtensionOptions, codec }) {
var _a2;
this.assertNotClosed();
this.assertSendDirection();
logger2.debug("send() [kind:%s, track.id:%s, streamId:%s]", track.kind, track.id, streamId);
if (encodings && encodings.length > 1) {
encodings.forEach((encoding, idx) => {
encoding.rid = `r${idx}`;
});
}
const mediaSectionIdx = this._remoteSdp.getNextMediaSectionIdx();
const transceiver = this._pc.addTransceiver(track, {
direction: "sendonly",
streams: [this._sendStream],
sendEncodings: encodings
});
let offer = yield this._pc.createOffer();
let localSdpObject = sdpTransform4.parse(offer.sdp);
if (localSdpObject.extmapAllowMixed) {
this._remoteSdp.setSessionExtmapAllowMixed();
}
const extraHeaderExtensions = [];
extraHeaderExtensions.push({
uri: "http://www.webrtc.org/experiments/rtp-hdrext/abs-capture-time",
kind: track.kind,
direction: "sendonly"
});
const nativeRtpCapabilities = _Chrome74.getLocalRtpCapabilities(localSdpObject, extraHeaderExtensions);
const sendExtendedRtpCapabilities = this._getSendExtendedRtpCapabilities(nativeRtpCapabilities);
const sendingRtpParameters = ortc.getSendingRtpParameters(track.kind, sendExtendedRtpCapabilities);
sendingRtpParameters.codecs = ortc.reduceCodecs(sendingRtpParameters.codecs, codec);
const sendingRemoteRtpParameters = ortc.getSendingRemoteRtpParameters(track.kind, sendExtendedRtpCapabilities);
sendingRemoteRtpParameters.codecs = ortc.reduceCodecs(sendingRemoteRtpParameters.codecs, codec);
if (!this._transportReady) {
yield this.setupTransport({
localDtlsRole: (_a2 = this._forcedLocalDtlsRole) != null ? _a2 : "client",
localSdpObject
});
}
let hackVp9Svc = false;
const layers = (0, scalabilityModes_1.parse)((encodings != null ? encodings : [{}])[0].scalabilityMode);
let offerMediaObject;
if ((encodings == null ? void 0 : encodings.length) === 1 && layers.spatialLayers > 1 && sendingRtpParameters.codecs[0].mimeType.toLowerCase() === "video/vp9") {
logger2.debug("send() | enabling legacy simulcast for VP9 SVC");
hackVp9Svc = true;
localSdpObject = sdpTransform4.parse(offer.sdp);
offerMediaObject = localSdpObject.media[mediaSectionIdx.idx];
sdpUnifiedPlanUtils.addLegacySimulcast({
offerMediaObject,
numStreams: layers.spatialLayers
});
offer = {
type: "offer",
sdp: sdpTransform4.write(localSdpObject)
};
}
logger2.debug("send() | calling pc.setLocalDescription() [offer:%o]", offer);
if (headerExtensionOptions == null ? void 0 : headerExtensionOptions.absCaptureTime) {
offerMediaObject = localSdpObject.media[mediaSectionIdx.idx];
sdpCommonUtils.addHeaderExtension({
offerMediaObject,
headerExtensionUri: "http://www.webrtc.org/experiments/rtp-hdrext/abs-capture-time",
headerExtensionId: sendingRemoteRtpParameters.headerExtensions.find((headerExtension) => headerExtension.uri === "http://www.webrtc.org/experiments/rtp-hdrext/abs-capture-time").id
});
offer = {
type: "offer",
sdp: sdpTransform4.write(localSdpObject)
};
}
yield this._pc.setLocalDescription(offer);
const localId = transceiver.mid;
sendingRtpParameters.mid = localId;
localSdpObject = sdpTransform4.parse(this._pc.localDescription.sdp);
offerMediaObject = localSdpObject.media[mediaSectionIdx.idx];
sendingRtpParameters.rtcp.cname = sdpCommonUtils.getCname({
offerMediaObject
});
sendingRtpParameters.msid = `${streamId != null ? streamId : this._sendStream.id} ${track.id}`;
if (!encodings) {
sendingRtpParameters.encodings = sdpUnifiedPlanUtils.getRtpEncodings({
offerMediaObject
});
} else if (encodings.length === 1) {
let newEncodings = sdpUnifiedPlanUtils.getRtpEncodings({
offerMediaObject
});
Object.assign(newEncodings[0], encodings[0]);
if (hackVp9Svc) {
newEncodings = [newEncodings[0]];
}
sendingRtpParameters.encodings = newEncodings;
} else {
sendingRtpParameters.encodings = encodings;
}
if (sendingRtpParameters.encodings.length > 1 && (sendingRtpParameters.codecs[0].mimeType.toLowerCase() === "video/vp8" || sendingRtpParameters.codecs[0].mimeType.toLowerCase() === "video/h264")) {
for (const encoding of sendingRtpParameters.encodings) {
if (encoding.scalabilityMode) {
encoding.scalabilityMode = `L1T${layers.temporalLayers}`;
} else {
encoding.scalabilityMode = "L1T3";
}
}
}
this._remoteSdp.send({
offerMediaObject,
reuseMid: mediaSectionIdx.reuseMid,
offerRtpParameters: sendingRtpParameters,
answerRtpParameters: sendingRemoteRtpParameters,
codecOptions
});
const answer = {
type: "answer",
sdp: this._remoteSdp.getSdp()
};
logger2.debug("send() | calling pc.setRemoteDescription() [answer:%o]", answer);
yield this._pc.setRemoteDescription(answer);
this._mapMidTransceiver.set(localId, transceiver);
return {
localId,
rtpParameters: sendingRtpParameters,
rtpSender: transceiver.sender
};
});
}
stopSending(localId) {
return __async(this, null, function* () {
this.assertSendDirection();
logger2.debug("stopSending() [localId:%s]", localId);
if (this._closed) {
return;
}
const transceiver = this._mapMidTransceiver.get(localId);
if (!transceiver) {
throw new Error("associated RTCRtpTransceiver not found");
}
void transceiver.sender.replaceTrack(null);
this._pc.removeTrack(transceiver.sender);
const mediaSectionClosed = this._remoteSdp.closeMediaSection(transceiver.mid);
if (mediaSectionClosed) {
try {
transceiver.stop();
} catch (error) {
}
}
const offer = yield this._pc.createOffer();
logger2.debug("stopSending() | calling pc.setLocalDescription() [offer:%o]", offer);
yield this._pc.setLocalDescription(offer);
const answer = {
type: "answer",
sdp: this._remoteSdp.getSdp()
};
logger2.debug("stopSending() | calling pc.setRemoteDescription() [answer:%o]", answer);
yield this._pc.setRemoteDescription(answer);
this._mapMidTransceiver.delete(localId);
});
}
pauseSending(localId) {
return __async(this, null, function* () {
this.assertNotClosed();
this.assertSendDirection();
logger2.debug("pauseSending() [localId:%s]", localId);
const transceiver = this._mapMidTransceiver.get(localId);
if (!transceiver) {
throw new Error("associated RTCRtpTransceiver not found");
}
transceiver.direction = "inactive";
this._remoteSdp.pauseMediaSection(localId);
const offer = yield this._pc.createOffer();
logger2.debug("pauseSending() | calling pc.setLocalDescription() [offer:%o]", offer);
yield this._pc.setLocalDescription(offer);
const answer = {
type: "answer",
sdp: this._remoteSdp.getSdp()
};
logger2.debug("pauseSending() | calling pc.setRemoteDescription() [answer:%o]", answer);
yield this._pc.setRemoteDescription(answer);
});
}
resumeSending(localId) {
return __async(this, null, function* () {
this.assertNotClosed();
this.assertSendDirection();
logger2.debug("resumeSending() [localId:%s]", localId);
const transceiver = this._mapMidTransceiver.get(localId);
this._remoteSdp.resumeSendingMediaSection(localId);
if (!transceiver) {
throw new Error("associated RTCRtpTransceiver not found");
}
transceiver.direction = "sendonly";
const offer = yield this._pc.createOffer();
logger2.debug("resumeSending() | calling pc.setLocalDescription() [offer:%o]", offer);
yield this._pc.setLocalDescription(offer);
const answer = {
type: "answer",
sdp: this._remoteSdp.getSdp()
};
logger2.debug("resumeSending() | calling pc.setRemoteDescription() [answer:%o]", answer);
yield this._pc.setRemoteDescription(answer);
});
}
replaceTrack(localId, track) {
return __async(this, null, function* () {
this.assertNotClosed();
this.assertSendDirection();
if (track) {
logger2.debug("replaceTrack() [localId:%s, track.id:%s]", localId, track.id);
} else {
logger2.debug("replaceTrack() [localId:%s, no track]", localId);
}
const transceiver = this._mapMidTransceiver.get(localId);
if (!transceiver) {
throw new Error("associated RTCRtpTransceiver not found");
}
yield transceiver.sender.replaceTrack(track);
});
}
setMaxSpatialLayer(localId, spatialLayer) {
return __async(this, null, function* () {
this.assertNotClosed();
this.assertSendDirection();
logger2.debug("setMaxSpatialLayer() [localId:%s, spatialLayer:%s]", localId, spatialLayer);
const transceiver = this._mapMidTransceiver.get(localId);
if (!transceiver) {
throw new Error("associated RTCRtpTransceiver not found");
}
const parameters = transceiver.sender.getParameters();
parameters.encodings.forEach((encoding, idx) => {
if (idx <= spatialLayer) {
encoding.active = true;
} else {
encoding.active = false;
}
});
yield transceiver.sender.setParameters(parameters);
this._remoteSdp.muxMediaSectionSimulcast(localId, parameters.encodings);
const offer = yield this._pc.createOffer();
logger2.debug("setMaxSpatialLayer() | calling pc.setLocalDescription() [offer:%o]", offer);
yield this._pc.setLocalDescription(offer);
const answer = {
type: "answer",
sdp: this._remoteSdp.getSdp()
};
logger2.debug("setMaxSpatialLayer() | calling pc.setRemoteDescription() [answer:%o]", answer);
yield this._pc.setRemoteDescription(answer);
});
}
setRtpEncodingParameters(localId, params) {
return __async(this, null, function* () {
this.assertNotClosed();
this.assertSendDirection();
logger2.debug("setRtpEncodingParameters() [localId:%s, params:%o]", localId, params);
const transceiver = this._mapMidTransceiver.get(localId);
if (!transceiver) {
throw new Error("associated RTCRtpTransceiver not found");
}
const parameters = transceiver.sender.getParameters();
parameters.encodings.forEach((encoding, idx) => {
parameters.encodings[idx] = __spreadValues(__spreadValues({}, encoding), params);
});
yield transceiver.sender.setParameters(parameters);
this._remoteSdp.muxMediaSectionSimulcast(localId, parameters.encodings);
const offer = yield this._pc.createOffer();
logger2.debug("setRtpEncodingParameters() | calling pc.setLocalDescription() [offer:%o]", offer);
yield this._pc.setLocalDescription(offer);
const answer = {
type: "answer",
sdp: this._remoteSdp.getSdp()
};
logger2.debug("setRtpEncodingParameters() | calling pc.setRemoteDescription() [answer:%o]", answer);
yield this._pc.setRemoteDescription(answer);
});
}
getSenderStats(localId) {
return __async(this, null, function* () {
this.assertNotClosed();
this.assertSendDirection();
const transceiver = this._mapMidTransceiver.get(localId);
if (!transceiver) {
throw new Error("associated RTCRtpTransceiver not found");
}
return transceiver.sender.getStats();
});
}
sendDataChannel(_0) {
return __async(this, arguments, function* ({ ordered, maxPacketLifeTime, maxRetransmits, label, protocol }) {
var _a2;
this.assertNotClosed();
this.assertSendDirection();
const options = {
negotiated: true,
id: this._nextSendSctpStreamId,
ordered,
maxPacketLifeTime,
maxRetransmits,
protocol
};
logger2.debug("sendDataChannel() [options:%o]", options);
const dataChannel = this._pc.createDataChannel(label, options);
this._nextSendSctpStreamId = ++this._nextSendSctpStreamId % SCTP_NUM_STREAMS.MIS;
if (!this._hasDataChannelMediaSection) {
const offer = yield this._pc.createOffer();
const localSdpObject = sdpTransform4.parse(offer.sdp);
const offerMediaObject = localSdpObject.media.find((m) => m.type === "application");
if (!this._transportReady) {
yield this.setupTransport({
localDtlsRole: (_a2 = this._forcedLocalDtlsRole) != null ? _a2 : "client",
localSdpObject
});
}
logger2.debug("sendDataChannel() | calling pc.setLocalDescription() [offer:%o]", offer);
yield this._pc.setLocalDescription(offer);
this._remoteSdp.sendSctpAssociation({ offerMediaObject });
const answer = {
type: "answer",
sdp: this._remoteSdp.getSdp()
};
logger2.debug("sendDataChannel() | calling pc.setRemoteDescription() [answer:%o]", answer);
yield this._pc.setRemoteDescription(answer);
this._hasDataChannelMediaSection = true;
}
const sctpStreamParameters = {
streamId: options.id,
ordered: options.ordered,
maxPacketLifeTime: options.maxPacketLifeTime,
maxRetransmits: options.maxRetransmits
};
return { dataChannel, sctpStreamParameters };
});
}
receive(optionsList) {
return __async(this, null, function* () {
var _a2, _b2, _c, _d, _e;
this.assertNotClosed();
this.assertRecvDirection();
const results = [];
const mapLocalId = /* @__PURE__ */ new Map();
for (const options of optionsList) {
const { trackId, kind, rtpParameters, streamId } = options;
logger2.debug("receive() [trackId:%s, kind:%s]", trackId, kind);
const localId = (_a2 = rtpParameters.mid) != null ? _a2 : String(this._mapMidTransceiver.size);
mapLocalId.set(trackId, localId);
const { msidStreamId } = ortcUtils.getMsidStreamIdAndTrackId(rtpParameters.msid);
this._remoteSdp.receive({
mid: localId,
kind,
offerRtpParameters: rtpParameters,
streamId: (_d = (_c = streamId != null ? streamId : msidStreamId) != null ? _c : (_b2 = rtpParameters.rtcp) == null ? void 0 : _b2.cname) != null ? _d : "-",
trackId
});
}
const offer = {
type: "offer",
sdp: this._remoteSdp.getSdp()
};
logger2.debug("receive() | calling pc.setRemoteDescription() [offer:%o]", offer);
yield this._pc.setRemoteDescription(offer);
let answer = yield this._pc.createAnswer();
const localSdpObject = sdpTransform4.parse(answer.sdp);
for (const options of optionsList) {
const { trackId, rtpParameters } = options;
const localId = mapLocalId.get(trackId);
const answerMediaObject = localSdpObject.media.find((m) => String(m.mid) === localId);
sdpCommonUtils.applyCodecParameters({
offerRtpParameters: rtpParameters,
answerMediaObject
});
}
answer = {
type: "answer",
sdp: sdpTransform4.write(localSdpObject)
};
if (!this._transportReady) {
yield this.setupTransport({
localDtlsRole: (_e = this._forcedLocalDtlsRole) != null ? _e : "client",
localSdpObject
});
}
logger2.debug("receive() | calling pc.setLocalDescription() [answer:%o]", answer);
yield this._pc.setLocalDescription(answer);
for (const options of optionsList) {
const { trackId } = options;
const localId = mapLocalId.get(trackId);
const transceiver = this._pc.getTransceivers().find((t2) => t2.mid === localId);
if (!transceiver) {
throw new Error("new RTCRtpTransceiver not found");
} else {
this._mapMidTransceiver.set(localId, transceiver);
results.push({
localId,
track: transceiver.receiver.track,
rtpReceiver: transceiver.receiver
});
}
}
return results;
});
}
stopReceiving(localIds) {
return __async(this, null, function* () {
this.assertRecvDirection();
if (this._closed) {
return;
}
for (const localId of localIds) {
logger2.debug("stopReceiving() [localId:%s]", localId);
const transceiver = this._mapMidTransceiver.get(localId);
if (!transceiver) {
throw new Error("associated RTCRtpTransceiver not found");
}
this._remoteSdp.closeMediaSection(transceiver.mid);
}
const offer = {
type: "offer",
sdp: this._remoteSdp.getSdp()
};
logger2.debug("stopReceiving() | calling pc.setRemoteDescription() [offer:%o]", offer);
yield this._pc.setRemoteDescription(offer);
const answer = yield this._pc.createAnswer();
logger2.debug("stopReceiving() | calling pc.setLocalDescription() [answer:%o]", answer);
yield this._pc.setLocalDescription(answer);
for (const localId of localIds) {
this._mapMidTransceiver.delete(localId);
}
});
}
pauseReceiving(localIds) {
return __async(this, null, function* () {
this.assertNotClosed();
this.assertRecvDirection();
for (const localId of localIds) {
logger2.debug("pauseReceiving() [localId:%s]", localId);
const transceiver = this._mapMidTransceiver.get(localId);
if (!transceiver) {
throw new Error("associated RTCRtpTransceiver not found");
}
transceiver.direction = "inactive";
this._remoteSdp.pauseMediaSection(localId);
}
const offer = {
type: "offer",
sdp: this._remoteSdp.getSdp()
};
logger2.debug("pauseReceiving() | calling pc.setRemoteDescription() [offer:%o]", offer);
yield this._pc.setRemoteDescription(offer);
const answer = yield this._pc.createAnswer();
logger2.debug("pauseReceiving() | calling pc.setLocalDescription() [answer:%o]", answer);
yield this._pc.setLocalDescription(answer);
});
}
resumeReceiving(localIds) {
return __async(this, null, function* () {
this.assertNotClosed();
this.assertRecvDirection();
for (const localId of localIds) {
logger2.debug("resumeReceiving() [localId:%s]", localId);
const transceiver = this._mapMidTransceiver.get(localId);
if (!transceiver) {
throw new Error("associated RTCRtpTransceiver not found");
}
transceiver.direction = "recvonly";
this._remoteSdp.resumeReceivingMediaSection(localId);
}
const offer = {
type: "offer",
sdp: this._remoteSdp.getSdp()
};
logger2.debug("resumeReceiving() | calling pc.setRemoteDescription() [offer:%o]", offer);
yield this._pc.setRemoteDescription(offer);
const answer = yield this._pc.createAnswer();
logger2.debug("resumeReceiving() | calling pc.setLocalDescription() [answer:%o]", answer);
yield this._pc.setLocalDescription(answer);
});
}
getReceiverStats(localId) {
return __async(this, null, function* () {
this.assertNotClosed();
this.assertRecvDirection();
const transceiver = this._mapMidTransceiver.get(localId);
if (!transceiver) {
throw new Error("associated RTCRtpTransceiver not found");
}
return transceiver.receiver.getStats();
});
}
receiveDataChannel(_0) {
return __async(this, arguments, function* ({ sctpStreamParameters, label, protocol }) {
var _a2;
this.assertNotClosed();
this.assertRecvDirection();
const { streamId, ordered, maxPacketLifeTime, maxRetransmits } = sctpStreamParameters;
const options = {
negotiated: true,
id: streamId,
ordered,
maxPacketLifeTime,
maxRetransmits,
protocol
};
logger2.debug("receiveDataChannel() [options:%o]", options);
const dataChannel = this._pc.createDataChannel(label, options);
if (!this._hasDataChannelMediaSection) {
this._remoteSdp.receiveSctpAssociation();
const offer = {
type: "offer",
sdp: this._remoteSdp.getSdp()
};
logger2.debug("receiveDataChannel() | calling pc.setRemoteDescription() [offer:%o]", offer);
yield this._pc.setRemoteDescription(offer);
const answer = yield this._pc.createAnswer();
if (!this._transportReady) {
const localSdpObject = sdpTransform4.parse(answer.sdp);
yield this.setupTransport({
localDtlsRole: (_a2 = this._forcedLocalDtlsRole) != null ? _a2 : "client",
localSdpObject
});
}
logger2.debug("receiveDataChannel() | calling pc.setRemoteDescription() [answer:%o]", answer);
yield this._pc.setLocalDescription(answer);
this._hasDataChannelMediaSection = true;
}
return { dataChannel };
});
}
setupTransport(_0) {
return __async(this, arguments, function* ({ localDtlsRole, localSdpObject }) {
if (!localSdpObject) {
localSdpObject = sdpTransform4.parse(this._pc.localDescription.sdp);
}
const dtlsParameters = sdpCommonUtils.extractDtlsParameters({
sdpObject: localSdpObject
});
dtlsParameters.role = localDtlsRole;
this._remoteSdp.updateDtlsRole(localDtlsRole === "client" ? "server" : "client");
yield new Promise((resolve, reject) => {
this.safeEmit("@connect", { dtlsParameters }, resolve, reject);
});
this._transportReady = true;
});
}
assertNotClosed() {
if (this._closed) {
throw new errors_1.InvalidStateError("method called in a closed handler");
}
}
assertSendDirection() {
if (this._direction !== "send") {
throw new Error('method can just be called for handlers with "send" direction');
}
}
assertRecvDirection() {
if (this._direction !== "recv") {
throw new Error('method can just be called for handlers with "recv" direction');
}
}
};
exports.Chrome74 = Chrome74;
}
});
// ../../node_modules/.pnpm/mediasoup-client@3.18.3/node_modules/mediasoup-client/lib/handlers/Firefox120.js
var require_Firefox120 = __commonJS({
"../../node_modules/.pnpm/mediasoup-client@3.18.3/node_modules/mediasoup-client/lib/handlers/Firefox120.js"(exports) {
"use strict";
init_process();
Object.defineProperty(exports, "__esModule", { value: true });
exports.Firefox120 = void 0;
var sdpTransform4 = require_lib4();
var enhancedEvents_1 = require_enhancedEvents();
var Logger_1 = require_Logger();
var errors_1 = require_errors();
var ortc = require_ortc();
var scalabilityModes_1 = require_scalabilityModes();
var RemoteSdp_1 = require_RemoteSdp();
var sdpCommonUtils = require_commonUtils();
var sdpUnifiedPlanUtils = require_unifiedPlanUtils();
var ortcUtils = require_utils2();
var logger2 = new Logger_1.Logger("Firefox120");
var NAME = "Firefox120";
var SCTP_NUM_STREAMS = { OS: 16, MIS: 2048 };
var Firefox120 = class _Firefox120 extends enhancedEvents_1.EnhancedEventEmitter {
constructor({ direction, iceParameters, iceCandidates, dtlsParameters, sctpParameters, iceServers, iceTransportPolicy, additionalSettings, getSendExtendedRtpCapabilities }) {
super();
// Closed flag.
__publicField(this, "_closed", false);
// Handler direction.
__publicField(this, "_direction");
// Remote SDP handler.
__publicField(this, "_remoteSdp");
// Callback to request sending extended RTP capabilities on demand.
__publicField(this, "_getSendExtendedRtpCapabilities");
// RTCPeerConnection instance.
__publicField(this, "_pc");
// Map of RTCTransceivers indexed by MID.
__publicField(this, "_mapMidTransceiver", /* @__PURE__ */ new Map());
// Default local stream for sending if no `streamId` is given in send().
__publicField(this, "_sendStream", new MediaStream());
// Whether a DataChannel m=application section has been created.
__publicField(this, "_hasDataChannelMediaSection", false);
// Sending DataChannel id value counter. Incremented for each new DataChannel.
__publicField(this, "_nextSendSctpStreamId", 0);
// Got transport local and remote parameters.
__publicField(this, "_transportReady", false);
__publicField(this, "onIceGatheringStateChange", () => {
this.emit("@icegatheringstatechange", this._pc.iceGatheringState);
});
__publicField(this, "onIceCandidateError", (event) => {
this.emit("@icecandidateerror", event);
});
__publicField(this, "onConnectionStateChange", () => {
this.emit("@connectionstatechange", this._pc.connectionState);
});
__publicField(this, "onIceConnectionStateChange", () => {
switch (this._pc.iceConnectionState) {
case "checking": {
this.emit("@connectionstatechange", "connecting");
break;
}
case "connected":
case "completed": {
this.emit("@connectionstatechange", "connected");
break;
}
case "failed": {
this.emit("@connectionstatechange", "failed");
break;
}
case "disconnected": {
this.emit("@connectionstatechange", "disconnected");
break;
}
case "closed": {
this.emit("@connectionstatechange", "closed");
break;
}
}
});
logger2.debug("constructor()");
this._direction = direction;
this._remoteSdp = new RemoteSdp_1.RemoteSdp({
iceParameters,
iceCandidates,
dtlsParameters,
sctpParameters
});
this._getSendExtendedRtpCapabilities = getSendExtendedRtpCapabilities;
this._pc = new RTCPeerConnection(__spreadValues({
iceServers: iceServers != null ? iceServers : [],
iceTransportPolicy: iceTransportPolicy != null ? iceTransportPolicy : "all",
bundlePolicy: "max-bundle",
rtcpMuxPolicy: "require"
}, additionalSettings));
this._pc.addEventListener("icegatheringstatechange", this.onIceGatheringStateChange);
this._pc.addEventListener("icecandidateerror", this.onIceCandidateError);
if (this._pc.connectionState) {
this._pc.addEventListener("connectionstatechange", this.onConnectionStateChange);
} else {
logger2.warn("run() | pc.connectionState not supported, using pc.iceConnectionState");
this._pc.addEventListener("iceconnectionstatechange", this.onIceConnectionStateChange);
}
}
/**
* Creates a factory function.
*/
static createFactory() {
return {
name: NAME,
factory: (options) => new _Firefox120(options),
getNativeRtpCapabilities: () => __async(null, null, function* () {
logger2.debug("getNativeRtpCapabilities()");
let pc = new RTCPeerConnection({
iceServers: [],
iceTransportPolicy: "all",
bundlePolicy: "max-bundle",
rtcpMuxPolicy: "require"
});
const canvas = document.createElement("canvas");
canvas.getContext("2d");
const fakeStream = canvas.captureStream();
const fakeVideoTrack = fakeStream.getVideoTracks()[0];
try {
pc.addTransceiver("audio", { direction: "sendrecv" });
pc.addTransceiver(fakeVideoTrack, {
direction: "sendrecv",
sendEncodings: [
{ rid: "r0", maxBitrate: 1e5 },
{ rid: "r1", maxBitrate: 5e5 }
]
});
const offer = yield pc.createOffer();
try {
canvas.remove();
} catch (error) {
}
try {
fakeVideoTrack.stop();
} catch (error) {
}
try {
pc.close();
} catch (error) {
}
pc = void 0;
const sdpObject = sdpTransform4.parse(offer.sdp);
const nativeRtpCapabilities = _Firefox120.getLocalRtpCapabilities(sdpObject);
return nativeRtpCapabilities;
} catch (error) {
try {
canvas.remove();
} catch (error2) {
}
try {
fakeVideoTrack.stop();
} catch (error2) {
}
try {
pc == null ? void 0 : pc.close();
} catch (error2) {
}
pc = void 0;
throw error;
}
}),
getNativeSctpCapabilities: () => __async(null, null, function* () {
logger2.debug("getNativeSctpCapabilities()");
return {
numStreams: SCTP_NUM_STREAMS
};
})
};
}
static getLocalRtpCapabilities(localSdpObject) {
const nativeRtpCapabilities = sdpCommonUtils.extractRtpCapabilities({
sdpObject: localSdpObject
});
ortc.validateAndNormalizeRtpCapabilities(nativeRtpCapabilities);
return nativeRtpCapabilities;
}
get name() {
return NAME;
}
close() {
logger2.debug("close()");
if (this._closed) {
return;
}
this._closed = true;
try {
this._pc.close();
} catch (error) {
}
this._pc.removeEventListener("icegatheringstatechange", this.onIceGatheringStateChange);
this._pc.removeEventListener("icecandidateerror", this.onIceCandidateError);
this._pc.removeEventListener("connectionstatechange", this.onConnectionStateChange);
this._pc.removeEventListener("iceconnectionstatechange", this.onIceConnectionStateChange);
this.emit("@close");
super.close();
}
// eslint-disable-next-line @typescript-eslint/no-unused-vars
updateIceServers(iceServers) {
return __async(this, null, function* () {
this.assertNotClosed();
throw new errors_1.UnsupportedError("not supported");
});
}
restartIce(iceParameters) {
return __async(this, null, function* () {
this.assertNotClosed();
logger2.debug("restartIce()");
this._remoteSdp.updateIceParameters(iceParameters);
if (!this._transportReady) {
return;
}
if (this._direction === "send") {
const offer = yield this._pc.createOffer({ iceRestart: true });
logger2.debug("restartIce() | calling pc.setLocalDescription() [offer:%o]", offer);
yield this._pc.setLocalDescription(offer);
const answer = {
type: "answer",
sdp: this._remoteSdp.getSdp()
};
logger2.debug("restartIce() | calling pc.setRemoteDescription() [answer:%o]", answer);
yield this._pc.setRemoteDescription(answer);
} else {
const offer = {
type: "offer",
sdp: this._remoteSdp.getSdp()
};
logger2.debug("restartIce() | calling pc.setRemoteDescription() [offer:%o]", offer);
yield this._pc.setRemoteDescription(offer);
const answer = yield this._pc.createAnswer();
logger2.debug("restartIce() | calling pc.setLocalDescription() [answer:%o]", answer);
yield this._pc.setLocalDescription(answer);
}
});
}
getTransportStats() {
return __async(this, null, function* () {
this.assertNotClosed();
return this._pc.getStats();
});
}
send(_0) {
return __async(this, arguments, function* ({ track, streamId, encodings, codecOptions, codec, onRtpSender }) {
this.assertNotClosed();
this.assertSendDirection();
logger2.debug("send() [kind:%s, track.id:%s, streamId:%s]", track.kind, track.id, streamId);
if (encodings && encodings.length > 1) {
encodings.forEach((encoding, idx) => {
encoding.rid = `r${idx}`;
});
}
const transceiver = this._pc.addTransceiver(track, {
direction: "sendonly",
streams: [this._sendStream],
sendEncodings: encodings
});
if (onRtpSender) {
onRtpSender(transceiver.sender);
}
const offer = yield this._pc.createOffer();
let localSdpObject = sdpTransform4.parse(offer.sdp);
if (localSdpObject.extmapAllowMixed) {
this._remoteSdp.setSessionExtmapAllowMixed();
}
const nativeRtpCapabilities = _Firefox120.getLocalRtpCapabilities(localSdpObject);
const sendExtendedRtpCapabilities = this._getSendExtendedRtpCapabilities(nativeRtpCapabilities);
const sendingRtpParameters = ortc.getSendingRtpParameters(track.kind, sendExtendedRtpCapabilities);
sendingRtpParameters.codecs = ortc.reduceCodecs(sendingRtpParameters.codecs, codec);
const sendingRemoteRtpParameters = ortc.getSendingRemoteRtpParameters(track.kind, sendExtendedRtpCapabilities);
sendingRemoteRtpParameters.codecs = ortc.reduceCodecs(sendingRemoteRtpParameters.codecs, codec);
if (!this._transportReady) {
yield this.setupTransport({ localDtlsRole: "client", localSdpObject });
}
const layers = (0, scalabilityModes_1.parse)((encodings != null ? encodings : [{}])[0].scalabilityMode);
logger2.debug("send() | calling pc.setLocalDescription() [offer:%o]", offer);
yield this._pc.setLocalDescription(offer);
const localId = transceiver.mid;
sendingRtpParameters.mid = localId;
localSdpObject = sdpTransform4.parse(this._pc.localDescription.sdp);
const offerMediaObject = localSdpObject.media[localSdpObject.media.length - 1];
sendingRtpParameters.rtcp.cname = sdpCommonUtils.getCname({
offerMediaObject
});
sendingRtpParameters.msid = `${streamId != null ? streamId : this._sendStream.id} ${track.id}`;
if (!encodings) {
sendingRtpParameters.encodings = sdpUnifiedPlanUtils.getRtpEncodings({
offerMediaObject
});
} else if (encodings.length === 1) {
const newEncodings = sdpUnifiedPlanUtils.getRtpEncodings({
offerMediaObject
});
Object.assign(newEncodings[0], encodings[0]);
sendingRtpParameters.encodings = newEncodings;
} else {
sendingRtpParameters.encodings = encodings;
}
if (sendingRtpParameters.encodings.length > 1 && (sendingRtpParameters.codecs[0].mimeType.toLowerCase() === "video/vp8" || sendingRtpParameters.codecs[0].mimeType.toLowerCase() === "video/h264")) {
for (const encoding of sendingRtpParameters.encodings) {
if (encoding.scalabilityMode) {
encoding.scalabilityMode = `L1T${layers.temporalLayers}`;
} else {
encoding.scalabilityMode = "L1T3";
}
}
}
this._remoteSdp.send({
offerMediaObject,
offerRtpParameters: sendingRtpParameters,
answerRtpParameters: sendingRemoteRtpParameters,
codecOptions
});
const answer = {
type: "answer",
sdp: this._remoteSdp.getSdp()
};
logger2.debug("send() | calling pc.setRemoteDescription() [answer:%o]", answer);
yield this._pc.setRemoteDescription(answer);
this._mapMidTransceiver.set(localId, transceiver);
return {
localId,
rtpParameters: sendingRtpParameters,
rtpSender: transceiver.sender
};
});
}
stopSending(localId) {
return __async(this, null, function* () {
this.assertSendDirection();
logger2.debug("stopSending() [localId:%s]", localId);
if (this._closed) {
return;
}
const transceiver = this._mapMidTransceiver.get(localId);
if (!transceiver) {
throw new Error("associated transceiver not found");
}
void transceiver.sender.replaceTrack(null);
this._pc.removeTrack(transceiver.sender);
this._remoteSdp.disableMediaSection(transceiver.mid);
const offer = yield this._pc.createOffer();
logger2.debug("stopSending() | calling pc.setLocalDescription() [offer:%o]", offer);
yield this._pc.setLocalDescription(offer);
const answer = {
type: "answer",
sdp: this._remoteSdp.getSdp()
};
logger2.debug("stopSending() | calling pc.setRemoteDescription() [answer:%o]", answer);
yield this._pc.setRemoteDescription(answer);
this._mapMidTransceiver.delete(localId);
});
}
pauseSending(localId) {
return __async(this, null, function* () {
this.assertNotClosed();
this.assertSendDirection();
logger2.debug("pauseSending() [localId:%s]", localId);
const transceiver = this._mapMidTransceiver.get(localId);
if (!transceiver) {
throw new Error("associated RTCRtpTransceiver not found");
}
transceiver.direction = "inactive";
this._remoteSdp.pauseMediaSection(localId);
const offer = yield this._pc.createOffer();
logger2.debug("pauseSending() | calling pc.setLocalDescription() [offer:%o]", offer);
yield this._pc.setLocalDescription(offer);
const answer = {
type: "answer",
sdp: this._remoteSdp.getSdp()
};
logger2.debug("pauseSending() | calling pc.setRemoteDescription() [answer:%o]", answer);
yield this._pc.setRemoteDescription(answer);
});
}
resumeSending(localId) {
return __async(this, null, function* () {
this.assertNotClosed();
this.assertSendDirection();
logger2.debug("resumeSending() [localId:%s]", localId);
const transceiver = this._mapMidTransceiver.get(localId);
if (!transceiver) {
throw new Error("associated RTCRtpTransceiver not found");
}
transceiver.direction = "sendonly";
this._remoteSdp.resumeSendingMediaSection(localId);
const offer = yield this._pc.createOffer();
logger2.debug("resumeSending() | calling pc.setLocalDescription() [offer:%o]", offer);
yield this._pc.setLocalDescription(offer);
const answer = {
type: "answer",
sdp: this._remoteSdp.getSdp()
};
logger2.debug("resumeSending() | calling pc.setRemoteDescription() [answer:%o]", answer);
yield this._pc.setRemoteDescription(answer);
});
}
replaceTrack(localId, track) {
return __async(this, null, function* () {
this.assertNotClosed();
this.assertSendDirection();
if (track) {
logger2.debug("replaceTrack() [localId:%s, track.id:%s]", localId, track.id);
} else {
logger2.debug("replaceTrack() [localId:%s, no track]", localId);
}
const transceiver = this._mapMidTransceiver.get(localId);
if (!transceiver) {
throw new Error("associated RTCRtpTransceiver not found");
}
yield transceiver.sender.replaceTrack(track);
});
}
setMaxSpatialLayer(localId, spatialLayer) {
return __async(this, null, function* () {
this.assertNotClosed();
this.assertSendDirection();
logger2.debug("setMaxSpatialLayer() [localId:%s, spatialLayer:%s]", localId, spatialLayer);
const transceiver = this._mapMidTransceiver.get(localId);
if (!transceiver) {
throw new Error("associated transceiver not found");
}
const parameters = transceiver.sender.getParameters();
parameters.encodings.forEach((encoding, idx) => {
if (idx <= spatialLayer) {
encoding.active = true;
} else {
encoding.active = false;
}
});
yield transceiver.sender.setParameters(parameters);
this._remoteSdp.muxMediaSectionSimulcast(localId, parameters.encodings);
const offer = yield this._pc.createOffer();
logger2.debug("setMaxSpatialLayer() | calling pc.setLocalDescription() [offer:%o]", offer);
yield this._pc.setLocalDescription(offer);
const answer = {
type: "answer",
sdp: this._remoteSdp.getSdp()
};
logger2.debug("setMaxSpatialLayer() | calling pc.setRemoteDescription() [answer:%o]", answer);
yield this._pc.setRemoteDescription(answer);
});
}
setRtpEncodingParameters(localId, params) {
return __async(this, null, function* () {
this.assertNotClosed();
this.assertSendDirection();
logger2.debug("setRtpEncodingParameters() [localId:%s, params:%o]", localId, params);
const transceiver = this._mapMidTransceiver.get(localId);
if (!transceiver) {
throw new Error("associated RTCRtpTransceiver not found");
}
const parameters = transceiver.sender.getParameters();
parameters.encodings.forEach((encoding, idx) => {
parameters.encodings[idx] = __spreadValues(__spreadValues({}, encoding), params);
});
yield transceiver.sender.setParameters(parameters);
this._remoteSdp.muxMediaSectionSimulcast(localId, parameters.encodings);
const offer = yield this._pc.createOffer();
logger2.debug("setRtpEncodingParameters() | calling pc.setLocalDescription() [offer:%o]", offer);
yield this._pc.setLocalDescription(offer);
const answer = {
type: "answer",
sdp: this._remoteSdp.getSdp()
};
logger2.debug("setRtpEncodingParameters() | calling pc.setRemoteDescription() [answer:%o]", answer);
yield this._pc.setRemoteDescription(answer);
});
}
getSenderStats(localId) {
return __async(this, null, function* () {
this.assertNotClosed();
this.assertSendDirection();
const transceiver = this._mapMidTransceiver.get(localId);
if (!transceiver) {
throw new Error("associated RTCRtpTransceiver not found");
}
return transceiver.sender.getStats();
});
}
sendDataChannel(_0) {
return __async(this, arguments, function* ({ ordered, maxPacketLifeTime, maxRetransmits, label, protocol }) {
this.assertNotClosed();
this.assertSendDirection();
const options = {
negotiated: true,
id: this._nextSendSctpStreamId,
ordered,
maxPacketLifeTime,
maxRetransmits,
protocol
};
logger2.debug("sendDataChannel() [options:%o]", options);
const dataChannel = this._pc.createDataChannel(label, options);
this._nextSendSctpStreamId = ++this._nextSendSctpStreamId % SCTP_NUM_STREAMS.MIS;
if (!this._hasDataChannelMediaSection) {
const offer = yield this._pc.createOffer();
const localSdpObject = sdpTransform4.parse(offer.sdp);
const offerMediaObject = localSdpObject.media.find((m) => m.type === "application");
if (!this._transportReady) {
yield this.setupTransport({ localDtlsRole: "client", localSdpObject });
}
logger2.debug("sendDataChannel() | calling pc.setLocalDescription() [offer:%o]", offer);
yield this._pc.setLocalDescription(offer);
this._remoteSdp.sendSctpAssociation({ offerMediaObject });
const answer = {
type: "answer",
sdp: this._remoteSdp.getSdp()
};
logger2.debug("sendDataChannel() | calling pc.setRemoteDescription() [answer:%o]", answer);
yield this._pc.setRemoteDescription(answer);
this._hasDataChannelMediaSection = true;
}
const sctpStreamParameters = {
streamId: options.id,
ordered: options.ordered,
maxPacketLifeTime: options.maxPacketLifeTime,
maxRetransmits: options.maxRetransmits
};
return { dataChannel, sctpStreamParameters };
});
}
receive(optionsList) {
return __async(this, null, function* () {
var _a2, _b2, _c, _d;
this.assertNotClosed();
this.assertRecvDirection();
const results = [];
const mapLocalId = /* @__PURE__ */ new Map();
for (const options of optionsList) {
const { trackId, kind, rtpParameters, streamId } = options;
logger2.debug("receive() [trackId:%s, kind:%s]", trackId, kind);
const localId = (_a2 = rtpParameters.mid) != null ? _a2 : String(this._mapMidTransceiver.size);
mapLocalId.set(trackId, localId);
const { msidStreamId } = ortcUtils.getMsidStreamIdAndTrackId(rtpParameters.msid);
this._remoteSdp.receive({
mid: localId,
kind,
offerRtpParameters: rtpParameters,
streamId: (_d = (_c = streamId != null ? streamId : msidStreamId) != null ? _c : (_b2 = rtpParameters.rtcp) == null ? void 0 : _b2.cname) != null ? _d : "-",
trackId
});
}
const offer = {
type: "offer",
sdp: this._remoteSdp.getSdp()
};
logger2.debug("receive() | calling pc.setRemoteDescription() [offer:%o]", offer);
yield this._pc.setRemoteDescription(offer);
for (const options of optionsList) {
const { trackId, onRtpReceiver } = options;
if (onRtpReceiver) {
const localId = mapLocalId.get(trackId);
const transceiver = this._pc.getTransceivers().find((t2) => t2.mid === localId);
if (!transceiver) {
throw new Error("transceiver not found");
}
onRtpReceiver(transceiver.receiver);
}
}
let answer = yield this._pc.createAnswer();
const localSdpObject = sdpTransform4.parse(answer.sdp);
for (const options of optionsList) {
const { trackId, rtpParameters } = options;
const localId = mapLocalId.get(trackId);
const answerMediaObject = localSdpObject.media.find((m) => String(m.mid) === localId);
sdpCommonUtils.applyCodecParameters({
offerRtpParameters: rtpParameters,
answerMediaObject
});
answer = {
type: "answer",
sdp: sdpTransform4.write(localSdpObject)
};
}
if (!this._transportReady) {
yield this.setupTransport({ localDtlsRole: "client", localSdpObject });
}
logger2.debug("receive() | calling pc.setLocalDescription() [answer:%o]", answer);
yield this._pc.setLocalDescription(answer);
for (const options of optionsList) {
const { trackId } = options;
const localId = mapLocalId.get(trackId);
const transceiver = this._pc.getTransceivers().find((t2) => t2.mid === localId);
if (!transceiver) {
throw new Error("new RTCRtpTransceiver not found");
}
this._mapMidTransceiver.set(localId, transceiver);
results.push({
localId,
track: transceiver.receiver.track,
rtpReceiver: transceiver.receiver
});
}
return results;
});
}
stopReceiving(localIds) {
return __async(this, null, function* () {
this.assertRecvDirection();
if (this._closed) {
return;
}
for (const localId of localIds) {
logger2.debug("stopReceiving() [localId:%s]", localId);
const transceiver = this._mapMidTransceiver.get(localId);
if (!transceiver) {
throw new Error("associated RTCRtpTransceiver not found");
}
this._remoteSdp.closeMediaSection(transceiver.mid);
}
const offer = {
type: "offer",
sdp: this._remoteSdp.getSdp()
};
logger2.debug("stopReceiving() | calling pc.setRemoteDescription() [offer:%o]", offer);
yield this._pc.setRemoteDescription(offer);
const answer = yield this._pc.createAnswer();
logger2.debug("stopReceiving() | calling pc.setLocalDescription() [answer:%o]", answer);
yield this._pc.setLocalDescription(answer);
for (const localId of localIds) {
this._mapMidTransceiver.delete(localId);
}
});
}
pauseReceiving(localIds) {
return __async(this, null, function* () {
this.assertNotClosed();
this.assertRecvDirection();
for (const localId of localIds) {
logger2.debug("pauseReceiving() [localId:%s]", localId);
const transceiver = this._mapMidTransceiver.get(localId);
if (!transceiver) {
throw new Error("associated RTCRtpTransceiver not found");
}
transceiver.direction = "inactive";
this._remoteSdp.pauseMediaSection(localId);
}
const offer = {
type: "offer",
sdp: this._remoteSdp.getSdp()
};
logger2.debug("pauseReceiving() | calling pc.setRemoteDescription() [offer:%o]", offer);
yield this._pc.setRemoteDescription(offer);
const answer = yield this._pc.createAnswer();
logger2.debug("pauseReceiving() | calling pc.setLocalDescription() [answer:%o]", answer);
yield this._pc.setLocalDescription(answer);
});
}
resumeReceiving(localIds) {
return __async(this, null, function* () {
this.assertNotClosed();
this.assertRecvDirection();
for (const localId of localIds) {
logger2.debug("resumeReceiving() [localId:%s]", localId);
const transceiver = this._mapMidTransceiver.get(localId);
if (!transceiver) {
throw new Error("associated RTCRtpTransceiver not found");
}
transceiver.direction = "recvonly";
this._remoteSdp.resumeReceivingMediaSection(localId);
}
const offer = {
type: "offer",
sdp: this._remoteSdp.getSdp()
};
logger2.debug("resumeReceiving() | calling pc.setRemoteDescription() [offer:%o]", offer);
yield this._pc.setRemoteDescription(offer);
const answer = yield this._pc.createAnswer();
logger2.debug("resumeReceiving() | calling pc.setLocalDescription() [answer:%o]", answer);
yield this._pc.setLocalDescription(answer);
});
}
getReceiverStats(localId) {
return __async(this, null, function* () {
this.assertRecvDirection();
const transceiver = this._mapMidTransceiver.get(localId);
if (!transceiver) {
throw new Error("associated RTCRtpTransceiver not found");
}
return transceiver.receiver.getStats();
});
}
receiveDataChannel(_0) {
return __async(this, arguments, function* ({ sctpStreamParameters, label, protocol }) {
this.assertNotClosed();
this.assertRecvDirection();
const { streamId, ordered, maxPacketLifeTime, maxRetransmits } = sctpStreamParameters;
const options = {
negotiated: true,
id: streamId,
ordered,
maxPacketLifeTime,
maxRetransmits,
protocol
};
logger2.debug("receiveDataChannel() [options:%o]", options);
const dataChannel = this._pc.createDataChannel(label, options);
if (!this._hasDataChannelMediaSection) {
this._remoteSdp.receiveSctpAssociation();
const offer = {
type: "offer",
sdp: this._remoteSdp.getSdp()
};
logger2.debug("receiveDataChannel() | calling pc.setRemoteDescription() [offer:%o]", offer);
yield this._pc.setRemoteDescription(offer);
const answer = yield this._pc.createAnswer();
if (!this._transportReady) {
const localSdpObject = sdpTransform4.parse(answer.sdp);
yield this.setupTransport({ localDtlsRole: "client", localSdpObject });
}
logger2.debug("receiveDataChannel() | calling pc.setRemoteDescription() [answer:%o]", answer);
yield this._pc.setLocalDescription(answer);
this._hasDataChannelMediaSection = true;
}
return { dataChannel };
});
}
setupTransport(_0) {
return __async(this, arguments, function* ({ localDtlsRole, localSdpObject }) {
if (!localSdpObject) {
localSdpObject = sdpTransform4.parse(this._pc.localDescription.sdp);
}
const dtlsParameters = sdpCommonUtils.extractDtlsParameters({
sdpObject: localSdpObject
});
dtlsParameters.role = localDtlsRole;
this._remoteSdp.updateDtlsRole(localDtlsRole === "client" ? "server" : "client");
yield new Promise((resolve, reject) => {
this.safeEmit("@connect", { dtlsParameters }, resolve, reject);
});
this._transportReady = true;
});
}
assertNotClosed() {
if (this._closed) {
throw new errors_1.InvalidStateError("method called in a closed handler");
}
}
assertSendDirection() {
if (this._direction !== "send") {
throw new Error('method can just be called for handlers with "send" direction');
}
}
assertRecvDirection() {
if (this._direction !== "recv") {
throw new Error('method can just be called for handlers with "recv" direction');
}
}
};
exports.Firefox120 = Firefox120;
}
});
// ../../node_modules/.pnpm/mediasoup-client@3.18.3/node_modules/mediasoup-client/lib/handlers/Safari12.js
var require_Safari12 = __commonJS({
"../../node_modules/.pnpm/mediasoup-client@3.18.3/node_modules/mediasoup-client/lib/handlers/Safari12.js"(exports) {
"use strict";
init_process();
Object.defineProperty(exports, "__esModule", { value: true });
exports.Safari12 = void 0;
var sdpTransform4 = require_lib4();
var enhancedEvents_1 = require_enhancedEvents();
var Logger_1 = require_Logger();
var ortc = require_ortc();
var errors_1 = require_errors();
var scalabilityModes_1 = require_scalabilityModes();
var RemoteSdp_1 = require_RemoteSdp();
var sdpCommonUtils = require_commonUtils();
var sdpUnifiedPlanUtils = require_unifiedPlanUtils();
var ortcUtils = require_utils2();
var logger2 = new Logger_1.Logger("Safari12");
var NAME = "Safari12";
var SCTP_NUM_STREAMS = { OS: 1024, MIS: 1024 };
var Safari12 = class _Safari12 extends enhancedEvents_1.EnhancedEventEmitter {
constructor({ direction, iceParameters, iceCandidates, dtlsParameters, sctpParameters, iceServers, iceTransportPolicy, additionalSettings, getSendExtendedRtpCapabilities }) {
super();
// Closed flag.
__publicField(this, "_closed", false);
// Handler direction.
__publicField(this, "_direction");
// Remote SDP handler.
__publicField(this, "_remoteSdp");
// Callback to request sending extended RTP capabilities on demand.
__publicField(this, "_getSendExtendedRtpCapabilities");
// Initial server side DTLS role. If not 'auto', it will force the opposite
// value in client side.
__publicField(this, "_forcedLocalDtlsRole");
// RTCPeerConnection instance.
__publicField(this, "_pc");
// Map of RTCTransceivers indexed by MID.
__publicField(this, "_mapMidTransceiver", /* @__PURE__ */ new Map());
// Default local stream for sending if no `streamId` is given in send().
__publicField(this, "_sendStream", new MediaStream());
// Whether a DataChannel m=application section has been created.
__publicField(this, "_hasDataChannelMediaSection", false);
// Sending DataChannel id value counter. Incremented for each new DataChannel.
__publicField(this, "_nextSendSctpStreamId", 0);
// Got transport local and remote parameters.
__publicField(this, "_transportReady", false);
__publicField(this, "onIceGatheringStateChange", () => {
this.emit("@icegatheringstatechange", this._pc.iceGatheringState);
});
__publicField(this, "onIceCandidateError", (event) => {
this.emit("@icecandidateerror", event);
});
__publicField(this, "onConnectionStateChange", () => {
this.emit("@connectionstatechange", this._pc.connectionState);
});
__publicField(this, "onIceConnectionStateChange", () => {
switch (this._pc.iceConnectionState) {
case "checking": {
this.emit("@connectionstatechange", "connecting");
break;
}
case "connected":
case "completed": {
this.emit("@connectionstatechange", "connected");
break;
}
case "failed": {
this.emit("@connectionstatechange", "failed");
break;
}
case "disconnected": {
this.emit("@connectionstatechange", "disconnected");
break;
}
case "closed": {
this.emit("@connectionstatechange", "closed");
break;
}
}
});
logger2.debug("constructor()");
this._direction = direction;
this._remoteSdp = new RemoteSdp_1.RemoteSdp({
iceParameters,
iceCandidates,
dtlsParameters,
sctpParameters
});
this._getSendExtendedRtpCapabilities = getSendExtendedRtpCapabilities;
if (dtlsParameters.role && dtlsParameters.role !== "auto") {
this._forcedLocalDtlsRole = dtlsParameters.role === "server" ? "client" : "server";
}
this._pc = new RTCPeerConnection(__spreadValues({
iceServers: iceServers != null ? iceServers : [],
iceTransportPolicy: iceTransportPolicy != null ? iceTransportPolicy : "all",
bundlePolicy: "max-bundle",
rtcpMuxPolicy: "require"
}, additionalSettings));
this._pc.addEventListener("icegatheringstatechange", () => {
this.emit("@icegatheringstatechange", this._pc.iceGatheringState);
});
this._pc.addEventListener("icecandidateerror", (event) => {
this.emit("@icecandidateerror", event);
});
this._pc.addEventListener("icegatheringstatechange", this.onIceGatheringStateChange);
this._pc.addEventListener("icecandidateerror", this.onIceCandidateError);
if (this._pc.connectionState) {
this._pc.addEventListener("connectionstatechange", this.onConnectionStateChange);
} else {
logger2.warn("run() | pc.connectionState not supported, using pc.iceConnectionState");
this._pc.addEventListener("iceconnectionstatechange", this.onIceConnectionStateChange);
}
}
/**
* Creates a factory function.
*/
static createFactory() {
return {
name: NAME,
factory: (options) => new _Safari12(options),
getNativeRtpCapabilities: () => __async(null, null, function* () {
logger2.debug("getNativeRtpCapabilities()");
let pc = new RTCPeerConnection({
iceServers: [],
iceTransportPolicy: "all",
bundlePolicy: "max-bundle",
rtcpMuxPolicy: "require"
});
try {
pc.addTransceiver("audio");
pc.addTransceiver("video");
const offer = yield pc.createOffer();
try {
pc.close();
} catch (error) {
}
pc = void 0;
const sdpObject = sdpTransform4.parse(offer.sdp);
const nativeRtpCapabilities = _Safari12.getLocalRtpCapabilities(sdpObject);
return nativeRtpCapabilities;
} catch (error) {
try {
pc == null ? void 0 : pc.close();
} catch (error2) {
}
pc = void 0;
throw error;
}
}),
getNativeSctpCapabilities: () => __async(null, null, function* () {
logger2.debug("getNativeSctpCapabilities()");
return {
numStreams: SCTP_NUM_STREAMS
};
})
};
}
static getLocalRtpCapabilities(localSdpObject, extraHeaderExtensions = []) {
const nativeRtpCapabilities = sdpCommonUtils.extractRtpCapabilities({
sdpObject: localSdpObject
});
ortc.validateAndNormalizeRtpCapabilities(nativeRtpCapabilities);
ortcUtils.addNackSupportForOpus(nativeRtpCapabilities);
for (const headerExtension of extraHeaderExtensions) {
ortcUtils.addHeaderExtensionSupport(nativeRtpCapabilities, headerExtension);
}
return nativeRtpCapabilities;
}
get name() {
return NAME;
}
close() {
logger2.debug("close()");
if (this._closed) {
return;
}
this._closed = true;
try {
this._pc.close();
} catch (error) {
}
this._pc.removeEventListener("icegatheringstatechange", this.onIceGatheringStateChange);
this._pc.removeEventListener("icecandidateerror", this.onIceCandidateError);
this._pc.removeEventListener("connectionstatechange", this.onConnectionStateChange);
this._pc.removeEventListener("iceconnectionstatechange", this.onIceConnectionStateChange);
this.emit("@close");
super.close();
}
updateIceServers(iceServers) {
return __async(this, null, function* () {
this.assertNotClosed();
logger2.debug("updateIceServers()");
const configuration = this._pc.getConfiguration();
configuration.iceServers = iceServers;
this._pc.setConfiguration(configuration);
});
}
restartIce(iceParameters) {
return __async(this, null, function* () {
this.assertNotClosed();
logger2.debug("restartIce()");
this._remoteSdp.updateIceParameters(iceParameters);
if (!this._transportReady) {
return;
}
if (this._direction === "send") {
const offer = yield this._pc.createOffer({ iceRestart: true });
logger2.debug("restartIce() | calling pc.setLocalDescription() [offer:%o]", offer);
yield this._pc.setLocalDescription(offer);
const answer = {
type: "answer",
sdp: this._remoteSdp.getSdp()
};
logger2.debug("restartIce() | calling pc.setRemoteDescription() [answer:%o]", answer);
yield this._pc.setRemoteDescription(answer);
} else {
const offer = {
type: "offer",
sdp: this._remoteSdp.getSdp()
};
logger2.debug("restartIce() | calling pc.setRemoteDescription() [offer:%o]", offer);
yield this._pc.setRemoteDescription(offer);
const answer = yield this._pc.createAnswer();
logger2.debug("restartIce() | calling pc.setLocalDescription() [answer:%o]", answer);
yield this._pc.setLocalDescription(answer);
}
});
}
getTransportStats() {
return __async(this, null, function* () {
this.assertNotClosed();
return this._pc.getStats();
});
}
send(_0) {
return __async(this, arguments, function* ({ track, streamId, encodings, codecOptions, headerExtensionOptions, codec, onRtpSender }) {
var _a2;
this.assertNotClosed();
this.assertSendDirection();
logger2.debug("send() [kind:%s, track.id:%s, streamId:%s]", track.kind, track.id, streamId);
const mediaSectionIdx = this._remoteSdp.getNextMediaSectionIdx();
const transceiver = this._pc.addTransceiver(track, {
direction: "sendonly",
streams: [this._sendStream]
});
if (onRtpSender) {
onRtpSender(transceiver.sender);
}
let offer = yield this._pc.createOffer();
let localSdpObject = sdpTransform4.parse(offer.sdp);
if (localSdpObject.extmapAllowMixed) {
this._remoteSdp.setSessionExtmapAllowMixed();
}
const extraHeaderExtensions = [];
extraHeaderExtensions.push({
uri: "http://www.webrtc.org/experiments/rtp-hdrext/abs-capture-time",
kind: track.kind,
direction: "sendonly"
});
const nativeRtpCapabilities = _Safari12.getLocalRtpCapabilities(localSdpObject, extraHeaderExtensions);
const sendExtendedRtpCapabilities = this._getSendExtendedRtpCapabilities(nativeRtpCapabilities);
const sendingRtpParameters = ortc.getSendingRtpParameters(track.kind, sendExtendedRtpCapabilities);
sendingRtpParameters.codecs = ortc.reduceCodecs(sendingRtpParameters.codecs, codec);
const sendingRemoteRtpParameters = ortc.getSendingRemoteRtpParameters(track.kind, sendExtendedRtpCapabilities);
sendingRemoteRtpParameters.codecs = ortc.reduceCodecs(sendingRemoteRtpParameters.codecs, codec);
let offerMediaObject;
if (!this._transportReady) {
yield this.setupTransport({
localDtlsRole: (_a2 = this._forcedLocalDtlsRole) != null ? _a2 : "client",
localSdpObject
});
}
const layers = (0, scalabilityModes_1.parse)((encodings != null ? encodings : [{}])[0].scalabilityMode);
if (encodings && encodings.length > 1) {
logger2.debug("send() | enabling legacy simulcast");
localSdpObject = sdpTransform4.parse(offer.sdp);
offerMediaObject = localSdpObject.media[mediaSectionIdx.idx];
sdpUnifiedPlanUtils.addLegacySimulcast({
offerMediaObject,
numStreams: encodings.length
});
offer = {
type: "offer",
sdp: sdpTransform4.write(localSdpObject)
};
}
if (headerExtensionOptions == null ? void 0 : headerExtensionOptions.absCaptureTime) {
offerMediaObject = localSdpObject.media[mediaSectionIdx.idx];
sdpCommonUtils.addHeaderExtension({
offerMediaObject,
headerExtensionUri: "http://www.webrtc.org/experiments/rtp-hdrext/abs-capture-time",
headerExtensionId: sendingRemoteRtpParameters.headerExtensions.find((headerExtension) => headerExtension.uri === "http://www.webrtc.org/experiments/rtp-hdrext/abs-capture-time").id
});
offer = {
type: "offer",
sdp: sdpTransform4.write(localSdpObject)
};
}
logger2.debug("send() | calling pc.setLocalDescription() [offer:%o]", offer);
yield this._pc.setLocalDescription(offer);
const localId = transceiver.mid;
sendingRtpParameters.mid = localId;
localSdpObject = sdpTransform4.parse(this._pc.localDescription.sdp);
offerMediaObject = localSdpObject.media[mediaSectionIdx.idx];
sendingRtpParameters.rtcp.cname = sdpCommonUtils.getCname({
offerMediaObject
});
sendingRtpParameters.msid = `${streamId != null ? streamId : this._sendStream.id} ${track.id}`;
sendingRtpParameters.encodings = sdpUnifiedPlanUtils.getRtpEncodings({
offerMediaObject
});
if (encodings) {
for (let idx = 0; idx < sendingRtpParameters.encodings.length; ++idx) {
if (encodings[idx]) {
Object.assign(sendingRtpParameters.encodings[idx], encodings[idx]);
}
}
}
if (sendingRtpParameters.encodings.length > 1 && (sendingRtpParameters.codecs[0].mimeType.toLowerCase() === "video/vp8" || sendingRtpParameters.codecs[0].mimeType.toLowerCase() === "video/h264")) {
for (const encoding of sendingRtpParameters.encodings) {
if (encoding.scalabilityMode) {
encoding.scalabilityMode = `L1T${layers.temporalLayers}`;
} else {
encoding.scalabilityMode = "L1T3";
}
}
}
this._remoteSdp.send({
offerMediaObject,
reuseMid: mediaSectionIdx.reuseMid,
offerRtpParameters: sendingRtpParameters,
answerRtpParameters: sendingRemoteRtpParameters,
codecOptions
});
const answer = {
type: "answer",
sdp: this._remoteSdp.getSdp()
};
logger2.debug("send() | calling pc.setRemoteDescription() [answer:%o]", answer);
yield this._pc.setRemoteDescription(answer);
this._mapMidTransceiver.set(localId, transceiver);
return {
localId,
rtpParameters: sendingRtpParameters,
rtpSender: transceiver.sender
};
});
}
stopSending(localId) {
return __async(this, null, function* () {
this.assertSendDirection();
if (this._closed) {
return;
}
logger2.debug("stopSending() [localId:%s]", localId);
const transceiver = this._mapMidTransceiver.get(localId);
if (!transceiver) {
throw new Error("associated RTCRtpTransceiver not found");
}
void transceiver.sender.replaceTrack(null);
this._pc.removeTrack(transceiver.sender);
const mediaSectionClosed = this._remoteSdp.closeMediaSection(transceiver.mid);
if (mediaSectionClosed) {
try {
transceiver.stop();
} catch (error) {
}
}
const offer = yield this._pc.createOffer();
logger2.debug("stopSending() | calling pc.setLocalDescription() [offer:%o]", offer);
yield this._pc.setLocalDescription(offer);
const answer = {
type: "answer",
sdp: this._remoteSdp.getSdp()
};
logger2.debug("stopSending() | calling pc.setRemoteDescription() [answer:%o]", answer);
yield this._pc.setRemoteDescription(answer);
this._mapMidTransceiver.delete(localId);
});
}
pauseSending(localId) {
return __async(this, null, function* () {
this.assertNotClosed();
this.assertSendDirection();
logger2.debug("pauseSending() [localId:%s]", localId);
const transceiver = this._mapMidTransceiver.get(localId);
if (!transceiver) {
throw new Error("associated RTCRtpTransceiver not found");
}
transceiver.direction = "inactive";
this._remoteSdp.pauseMediaSection(localId);
const offer = yield this._pc.createOffer();
logger2.debug("pauseSending() | calling pc.setLocalDescription() [offer:%o]", offer);
yield this._pc.setLocalDescription(offer);
const answer = {
type: "answer",
sdp: this._remoteSdp.getSdp()
};
logger2.debug("pauseSending() | calling pc.setRemoteDescription() [answer:%o]", answer);
yield this._pc.setRemoteDescription(answer);
});
}
resumeSending(localId) {
return __async(this, null, function* () {
this.assertNotClosed();
this.assertSendDirection();
logger2.debug("resumeSending() [localId:%s]", localId);
const transceiver = this._mapMidTransceiver.get(localId);
if (!transceiver) {
throw new Error("associated RTCRtpTransceiver not found");
}
transceiver.direction = "sendonly";
this._remoteSdp.resumeSendingMediaSection(localId);
const offer = yield this._pc.createOffer();
logger2.debug("resumeSending() | calling pc.setLocalDescription() [offer:%o]", offer);
yield this._pc.setLocalDescription(offer);
const answer = {
type: "answer",
sdp: this._remoteSdp.getSdp()
};
logger2.debug("resumeSending() | calling pc.setRemoteDescription() [answer:%o]", answer);
yield this._pc.setRemoteDescription(answer);
});
}
replaceTrack(localId, track) {
return __async(this, null, function* () {
this.assertNotClosed();
this.assertSendDirection();
if (track) {
logger2.debug("replaceTrack() [localId:%s, track.id:%s]", localId, track.id);
} else {
logger2.debug("replaceTrack() [localId:%s, no track]", localId);
}
const transceiver = this._mapMidTransceiver.get(localId);
if (!transceiver) {
throw new Error("associated RTCRtpTransceiver not found");
}
yield transceiver.sender.replaceTrack(track);
});
}
setMaxSpatialLayer(localId, spatialLayer) {
return __async(this, null, function* () {
this.assertNotClosed();
this.assertSendDirection();
logger2.debug("setMaxSpatialLayer() [localId:%s, spatialLayer:%s]", localId, spatialLayer);
const transceiver = this._mapMidTransceiver.get(localId);
if (!transceiver) {
throw new Error("associated RTCRtpTransceiver not found");
}
const parameters = transceiver.sender.getParameters();
parameters.encodings.forEach((encoding, idx) => {
if (idx <= spatialLayer) {
encoding.active = true;
} else {
encoding.active = false;
}
});
yield transceiver.sender.setParameters(parameters);
this._remoteSdp.muxMediaSectionSimulcast(localId, parameters.encodings);
const offer = yield this._pc.createOffer();
logger2.debug("setMaxSpatialLayer() | calling pc.setLocalDescription() [offer:%o]", offer);
yield this._pc.setLocalDescription(offer);
const answer = {
type: "answer",
sdp: this._remoteSdp.getSdp()
};
logger2.debug("setMaxSpatialLayer() | calling pc.setRemoteDescription() [answer:%o]", answer);
yield this._pc.setRemoteDescription(answer);
});
}
setRtpEncodingParameters(localId, params) {
return __async(this, null, function* () {
this.assertNotClosed();
this.assertSendDirection();
logger2.debug("setRtpEncodingParameters() [localId:%s, params:%o]", localId, params);
const transceiver = this._mapMidTransceiver.get(localId);
if (!transceiver) {
throw new Error("associated RTCRtpTransceiver not found");
}
const parameters = transceiver.sender.getParameters();
parameters.encodings.forEach((encoding, idx) => {
parameters.encodings[idx] = __spreadValues(__spreadValues({}, encoding), params);
});
yield transceiver.sender.setParameters(parameters);
this._remoteSdp.muxMediaSectionSimulcast(localId, parameters.encodings);
const offer = yield this._pc.createOffer();
logger2.debug("setRtpEncodingParameters() | calling pc.setLocalDescription() [offer:%o]", offer);
yield this._pc.setLocalDescription(offer);
const answer = {
type: "answer",
sdp: this._remoteSdp.getSdp()
};
logger2.debug("setRtpEncodingParameters() | calling pc.setRemoteDescription() [answer:%o]", answer);
yield this._pc.setRemoteDescription(answer);
});
}
getSenderStats(localId) {
return __async(this, null, function* () {
this.assertNotClosed();
this.assertSendDirection();
const transceiver = this._mapMidTransceiver.get(localId);
if (!transceiver) {
throw new Error("associated RTCRtpTransceiver not found");
}
return transceiver.sender.getStats();
});
}
sendDataChannel(_0) {
return __async(this, arguments, function* ({ ordered, maxPacketLifeTime, maxRetransmits, label, protocol }) {
var _a2;
this.assertNotClosed();
this.assertSendDirection();
const options = {
negotiated: true,
id: this._nextSendSctpStreamId,
ordered,
maxPacketLifeTime,
maxRetransmits,
protocol
};
logger2.debug("sendDataChannel() [options:%o]", options);
const dataChannel = this._pc.createDataChannel(label, options);
this._nextSendSctpStreamId = ++this._nextSendSctpStreamId % SCTP_NUM_STREAMS.MIS;
if (!this._hasDataChannelMediaSection) {
const offer = yield this._pc.createOffer();
const localSdpObject = sdpTransform4.parse(offer.sdp);
const offerMediaObject = localSdpObject.media.find((m) => m.type === "application");
if (!this._transportReady) {
yield this.setupTransport({
localDtlsRole: (_a2 = this._forcedLocalDtlsRole) != null ? _a2 : "client",
localSdpObject
});
}
logger2.debug("sendDataChannel() | calling pc.setLocalDescription() [offer:%o]", offer);
yield this._pc.setLocalDescription(offer);
this._remoteSdp.sendSctpAssociation({ offerMediaObject });
const answer = {
type: "answer",
sdp: this._remoteSdp.getSdp()
};
logger2.debug("sendDataChannel() | calling pc.setRemoteDescription() [answer:%o]", answer);
yield this._pc.setRemoteDescription(answer);
this._hasDataChannelMediaSection = true;
}
const sctpStreamParameters = {
streamId: options.id,
ordered: options.ordered,
maxPacketLifeTime: options.maxPacketLifeTime,
maxRetransmits: options.maxRetransmits
};
return { dataChannel, sctpStreamParameters };
});
}
receive(optionsList) {
return __async(this, null, function* () {
var _a2, _b2, _c, _d, _e;
this.assertNotClosed();
this.assertRecvDirection();
const results = [];
const mapLocalId = /* @__PURE__ */ new Map();
for (const options of optionsList) {
const { trackId, kind, rtpParameters, streamId } = options;
logger2.debug("receive() [trackId:%s, kind:%s]", trackId, kind);
const localId = (_a2 = rtpParameters.mid) != null ? _a2 : String(this._mapMidTransceiver.size);
mapLocalId.set(trackId, localId);
const { msidStreamId } = ortcUtils.getMsidStreamIdAndTrackId(rtpParameters.msid);
this._remoteSdp.receive({
mid: localId,
kind,
offerRtpParameters: rtpParameters,
streamId: (_d = (_c = streamId != null ? streamId : msidStreamId) != null ? _c : (_b2 = rtpParameters.rtcp) == null ? void 0 : _b2.cname) != null ? _d : "-",
trackId
});
}
const offer = {
type: "offer",
sdp: this._remoteSdp.getSdp()
};
logger2.debug("receive() | calling pc.setRemoteDescription() [offer:%o]", offer);
yield this._pc.setRemoteDescription(offer);
for (const options of optionsList) {
const { trackId, onRtpReceiver } = options;
if (onRtpReceiver) {
const localId = mapLocalId.get(trackId);
const transceiver = this._pc.getTransceivers().find((t2) => t2.mid === localId);
if (!transceiver) {
throw new Error("transceiver not found");
}
onRtpReceiver(transceiver.receiver);
}
}
let answer = yield this._pc.createAnswer();
const localSdpObject = sdpTransform4.parse(answer.sdp);
for (const options of optionsList) {
const { trackId, rtpParameters } = options;
const localId = mapLocalId.get(trackId);
const answerMediaObject = localSdpObject.media.find((m) => String(m.mid) === localId);
sdpCommonUtils.applyCodecParameters({
offerRtpParameters: rtpParameters,
answerMediaObject
});
}
answer = {
type: "answer",
sdp: sdpTransform4.write(localSdpObject)
};
if (!this._transportReady) {
yield this.setupTransport({
localDtlsRole: (_e = this._forcedLocalDtlsRole) != null ? _e : "client",
localSdpObject
});
}
logger2.debug("receive() | calling pc.setLocalDescription() [answer:%o]", answer);
yield this._pc.setLocalDescription(answer);
for (const options of optionsList) {
const { trackId } = options;
const localId = mapLocalId.get(trackId);
const transceiver = this._pc.getTransceivers().find((t2) => t2.mid === localId);
if (!transceiver) {
throw new Error("new RTCRtpTransceiver not found");
}
this._mapMidTransceiver.set(localId, transceiver);
results.push({
localId,
track: transceiver.receiver.track,
rtpReceiver: transceiver.receiver
});
}
return results;
});
}
stopReceiving(localIds) {
return __async(this, null, function* () {
this.assertRecvDirection();
if (this._closed) {
return;
}
for (const localId of localIds) {
logger2.debug("stopReceiving() [localId:%s]", localId);
const transceiver = this._mapMidTransceiver.get(localId);
if (!transceiver) {
throw new Error("associated RTCRtpTransceiver not found");
}
this._remoteSdp.closeMediaSection(transceiver.mid);
}
const offer = {
type: "offer",
sdp: this._remoteSdp.getSdp()
};
logger2.debug("stopReceiving() | calling pc.setRemoteDescription() [offer:%o]", offer);
yield this._pc.setRemoteDescription(offer);
const answer = yield this._pc.createAnswer();
logger2.debug("stopReceiving() | calling pc.setLocalDescription() [answer:%o]", answer);
yield this._pc.setLocalDescription(answer);
for (const localId of localIds) {
this._mapMidTransceiver.delete(localId);
}
});
}
pauseReceiving(localIds) {
return __async(this, null, function* () {
this.assertNotClosed();
this.assertRecvDirection();
for (const localId of localIds) {
logger2.debug("pauseReceiving() [localId:%s]", localId);
const transceiver = this._mapMidTransceiver.get(localId);
if (!transceiver) {
throw new Error("associated RTCRtpTransceiver not found");
}
transceiver.direction = "inactive";
this._remoteSdp.pauseMediaSection(localId);
}
const offer = {
type: "offer",
sdp: this._remoteSdp.getSdp()
};
logger2.debug("pauseReceiving() | calling pc.setRemoteDescription() [offer:%o]", offer);
yield this._pc.setRemoteDescription(offer);
const answer = yield this._pc.createAnswer();
logger2.debug("pauseReceiving() | calling pc.setLocalDescription() [answer:%o]", answer);
yield this._pc.setLocalDescription(answer);
});
}
resumeReceiving(localIds) {
return __async(this, null, function* () {
this.assertNotClosed();
this.assertRecvDirection();
for (const localId of localIds) {
logger2.debug("resumeReceiving() [localId:%s]", localId);
const transceiver = this._mapMidTransceiver.get(localId);
if (!transceiver) {
throw new Error("associated RTCRtpTransceiver not found");
}
transceiver.direction = "recvonly";
this._remoteSdp.resumeReceivingMediaSection(localId);
}
const offer = {
type: "offer",
sdp: this._remoteSdp.getSdp()
};
logger2.debug("resumeReceiving() | calling pc.setRemoteDescription() [offer:%o]", offer);
yield this._pc.setRemoteDescription(offer);
const answer = yield this._pc.createAnswer();
logger2.debug("resumeReceiving() | calling pc.setLocalDescription() [answer:%o]", answer);
yield this._pc.setLocalDescription(answer);
});
}
getReceiverStats(localId) {
return __async(this, null, function* () {
this.assertNotClosed();
this.assertRecvDirection();
const transceiver = this._mapMidTransceiver.get(localId);
if (!transceiver) {
throw new Error("associated RTCRtpTransceiver not found");
}
return transceiver.receiver.getStats();
});
}
receiveDataChannel(_0) {
return __async(this, arguments, function* ({ sctpStreamParameters, label, protocol }) {
var _a2;
this.assertNotClosed();
this.assertRecvDirection();
const { streamId, ordered, maxPacketLifeTime, maxRetransmits } = sctpStreamParameters;
const options = {
negotiated: true,
id: streamId,
ordered,
maxPacketLifeTime,
maxRetransmits,
protocol
};
logger2.debug("receiveDataChannel() [options:%o]", options);
const dataChannel = this._pc.createDataChannel(label, options);
if (!this._hasDataChannelMediaSection) {
this._remoteSdp.receiveSctpAssociation();
const offer = {
type: "offer",
sdp: this._remoteSdp.getSdp()
};
logger2.debug("receiveDataChannel() | calling pc.setRemoteDescription() [offer:%o]", offer);
yield this._pc.setRemoteDescription(offer);
const answer = yield this._pc.createAnswer();
if (!this._transportReady) {
const localSdpObject = sdpTransform4.parse(answer.sdp);
yield this.setupTransport({
localDtlsRole: (_a2 = this._forcedLocalDtlsRole) != null ? _a2 : "client",
localSdpObject
});
}
logger2.debug("receiveDataChannel() | calling pc.setRemoteDescription() [answer:%o]", answer);
yield this._pc.setLocalDescription(answer);
this._hasDataChannelMediaSection = true;
}
return { dataChannel };
});
}
setupTransport(_0) {
return __async(this, arguments, function* ({ localDtlsRole, localSdpObject }) {
if (!localSdpObject) {
localSdpObject = sdpTransform4.parse(this._pc.localDescription.sdp);
}
const dtlsParameters = sdpCommonUtils.extractDtlsParameters({
sdpObject: localSdpObject
});
dtlsParameters.role = localDtlsRole;
this._remoteSdp.updateDtlsRole(localDtlsRole === "client" ? "server" : "client");
yield new Promise((resolve, reject) => {
this.safeEmit("@connect", { dtlsParameters }, resolve, reject);
});
this._transportReady = true;
});
}
assertNotClosed() {
if (this._closed) {
throw new errors_1.InvalidStateError("method called in a closed handler");
}
}
assertSendDirection() {
if (this._direction !== "send") {
throw new Error('method can just be called for handlers with "send" direction');
}
}
assertRecvDirection() {
if (this._direction !== "recv") {
throw new Error('method can just be called for handlers with "recv" direction');
}
}
};
exports.Safari12 = Safari12;
}
});
// ../../node_modules/.pnpm/mediasoup-client@3.18.3/node_modules/mediasoup-client/lib/handlers/ReactNative106.js
var require_ReactNative106 = __commonJS({
"../../node_modules/.pnpm/mediasoup-client@3.18.3/node_modules/mediasoup-client/lib/handlers/ReactNative106.js"(exports) {
"use strict";
init_process();
Object.defineProperty(exports, "__esModule", { value: true });
exports.ReactNative106 = void 0;
var sdpTransform4 = require_lib4();
var enhancedEvents_1 = require_enhancedEvents();
var Logger_1 = require_Logger();
var ortc = require_ortc();
var errors_1 = require_errors();
var scalabilityModes_1 = require_scalabilityModes();
var RemoteSdp_1 = require_RemoteSdp();
var sdpCommonUtils = require_commonUtils();
var sdpUnifiedPlanUtils = require_unifiedPlanUtils();
var ortcUtils = require_utils2();
var logger2 = new Logger_1.Logger("ReactNative106");
var NAME = "ReactNative106";
var SCTP_NUM_STREAMS = { OS: 1024, MIS: 1024 };
var ReactNative106 = class _ReactNative106 extends enhancedEvents_1.EnhancedEventEmitter {
constructor({ direction, iceParameters, iceCandidates, dtlsParameters, sctpParameters, iceServers, iceTransportPolicy, additionalSettings, getSendExtendedRtpCapabilities }) {
super();
// Closed flag.
__publicField(this, "_closed", false);
// Handler direction.
__publicField(this, "_direction");
// Remote SDP handler.
__publicField(this, "_remoteSdp");
// Callback to request sending extended RTP capabilities on demand.
__publicField(this, "_getSendExtendedRtpCapabilities");
// Initial server side DTLS role. If not 'auto', it will force the opposite
// value in client side.
__publicField(this, "_forcedLocalDtlsRole");
// RTCPeerConnection instance.
__publicField(this, "_pc");
// Map of RTCTransceivers indexed by MID.
__publicField(this, "_mapMidTransceiver", /* @__PURE__ */ new Map());
// Default local stream for sending if no `streamId` is given in send().
__publicField(this, "_sendStream", new MediaStream());
// Whether a DataChannel m=application section has been created.
__publicField(this, "_hasDataChannelMediaSection", false);
// Sending DataChannel id value counter. Incremented for each new DataChannel.
__publicField(this, "_nextSendSctpStreamId", 0);
// Got transport local and remote parameters.
__publicField(this, "_transportReady", false);
__publicField(this, "onIceGatheringStateChange", () => {
this.emit("@icegatheringstatechange", this._pc.iceGatheringState);
});
__publicField(this, "onIceCandidateError", (event) => {
this.emit("@icecandidateerror", event);
});
__publicField(this, "onConnectionStateChange", () => {
this.emit("@connectionstatechange", this._pc.connectionState);
});
__publicField(this, "onIceConnectionStateChange", () => {
switch (this._pc.iceConnectionState) {
case "checking": {
this.emit("@connectionstatechange", "connecting");
break;
}
case "connected":
case "completed": {
this.emit("@connectionstatechange", "connected");
break;
}
case "failed": {
this.emit("@connectionstatechange", "failed");
break;
}
case "disconnected": {
this.emit("@connectionstatechange", "disconnected");
break;
}
case "closed": {
this.emit("@connectionstatechange", "closed");
break;
}
}
});
logger2.debug("constructor()");
this._direction = direction;
this._remoteSdp = new RemoteSdp_1.RemoteSdp({
iceParameters,
iceCandidates,
dtlsParameters,
sctpParameters
});
this._getSendExtendedRtpCapabilities = getSendExtendedRtpCapabilities;
if (dtlsParameters.role && dtlsParameters.role !== "auto") {
this._forcedLocalDtlsRole = dtlsParameters.role === "server" ? "client" : "server";
}
this._pc = new RTCPeerConnection(__spreadValues({
iceServers: iceServers != null ? iceServers : [],
iceTransportPolicy: iceTransportPolicy != null ? iceTransportPolicy : "all",
bundlePolicy: "max-bundle",
rtcpMuxPolicy: "require"
}, additionalSettings));
this._pc.addEventListener("icegatheringstatechange", this.onIceGatheringStateChange);
this._pc.addEventListener("icecandidateerror", this.onIceCandidateError);
if (this._pc.connectionState) {
this._pc.addEventListener("connectionstatechange", this.onConnectionStateChange);
} else {
logger2.warn("run() | pc.connectionState not supported, using pc.iceConnectionState");
this._pc.addEventListener("iceconnectionstatechange", this.onIceConnectionStateChange);
}
}
/**
* Creates a factory function.
*/
static createFactory() {
return {
name: NAME,
factory: (options) => new _ReactNative106(options),
getNativeRtpCapabilities: () => __async(null, null, function* () {
logger2.debug("getNativeRtpCapabilities()");
let pc = new RTCPeerConnection({
iceServers: [],
iceTransportPolicy: "all",
bundlePolicy: "max-bundle",
rtcpMuxPolicy: "require"
});
try {
pc.addTransceiver("audio");
pc.addTransceiver("video");
const offer = yield pc.createOffer();
try {
pc.close();
} catch (error) {
}
pc = void 0;
const sdpObject = sdpTransform4.parse(offer.sdp);
const nativeRtpCapabilities = _ReactNative106.getLocalRtpCapabilities(sdpObject);
return nativeRtpCapabilities;
} catch (error) {
try {
pc == null ? void 0 : pc.close();
} catch (error2) {
}
pc = void 0;
throw error;
}
}),
getNativeSctpCapabilities: () => __async(null, null, function* () {
logger2.debug("getNativeSctpCapabilities()");
return {
numStreams: SCTP_NUM_STREAMS
};
})
};
}
static getLocalRtpCapabilities(localSdpObject, extraHeaderExtensions = []) {
const nativeRtpCapabilities = sdpCommonUtils.extractRtpCapabilities({
sdpObject: localSdpObject
});
ortc.validateAndNormalizeRtpCapabilities(nativeRtpCapabilities);
ortcUtils.addNackSupportForOpus(nativeRtpCapabilities);
for (const headerExtension of extraHeaderExtensions) {
ortcUtils.addHeaderExtensionSupport(nativeRtpCapabilities, headerExtension);
}
return nativeRtpCapabilities;
}
get name() {
return NAME;
}
close() {
logger2.debug("close()");
if (this._closed) {
return;
}
this._closed = true;
this._sendStream.release(
/* releaseTracks */
false
);
try {
this._pc.close();
} catch (error) {
}
this._pc.removeEventListener("icegatheringstatechange", this.onIceGatheringStateChange);
this._pc.removeEventListener("icecandidateerror", this.onIceCandidateError);
this._pc.removeEventListener("connectionstatechange", this.onConnectionStateChange);
this._pc.removeEventListener("iceconnectionstatechange", this.onIceConnectionStateChange);
this.emit("@close");
super.close();
}
updateIceServers(iceServers) {
return __async(this, null, function* () {
this.assertNotClosed();
logger2.debug("updateIceServers()");
const configuration = this._pc.getConfiguration();
configuration.iceServers = iceServers;
this._pc.setConfiguration(configuration);
});
}
restartIce(iceParameters) {
return __async(this, null, function* () {
this.assertNotClosed();
logger2.debug("restartIce()");
this._remoteSdp.updateIceParameters(iceParameters);
if (!this._transportReady) {
return;
}
if (this._direction === "send") {
const offer = yield this._pc.createOffer({ iceRestart: true });
logger2.debug("restartIce() | calling pc.setLocalDescription() [offer:%o]", offer);
yield this._pc.setLocalDescription(offer);
const answer = {
type: "answer",
sdp: this._remoteSdp.getSdp()
};
logger2.debug("restartIce() | calling pc.setRemoteDescription() [answer:%o]", answer);
yield this._pc.setRemoteDescription(answer);
} else {
const offer = {
type: "offer",
sdp: this._remoteSdp.getSdp()
};
logger2.debug("restartIce() | calling pc.setRemoteDescription() [offer:%o]", offer);
yield this._pc.setRemoteDescription(offer);
const answer = yield this._pc.createAnswer();
logger2.debug("restartIce() | calling pc.setLocalDescription() [answer:%o]", answer);
yield this._pc.setLocalDescription(answer);
}
});
}
getTransportStats() {
return __async(this, null, function* () {
this.assertNotClosed();
return this._pc.getStats();
});
}
send(_0) {
return __async(this, arguments, function* ({ track, streamId, encodings, codecOptions, headerExtensionOptions, codec, onRtpSender }) {
var _a2, _b2;
this.assertNotClosed();
this.assertSendDirection();
logger2.debug("send() [kind:%s, track.id:%s, streamId:%s]", track.kind, track.id, streamId);
if (encodings && encodings.length > 1) {
encodings.forEach((encoding, idx) => {
encoding.rid = `r${idx}`;
});
}
const mediaSectionIdx = this._remoteSdp.getNextMediaSectionIdx();
const transceiver = this._pc.addTransceiver(track, {
direction: "sendonly",
streams: [this._sendStream],
sendEncodings: encodings
});
if (onRtpSender) {
onRtpSender(transceiver.sender);
}
let offer = yield this._pc.createOffer();
let localSdpObject = sdpTransform4.parse(offer.sdp);
if (localSdpObject.extmapAllowMixed) {
this._remoteSdp.setSessionExtmapAllowMixed();
}
const extraHeaderExtensions = [];
extraHeaderExtensions.push({
uri: "http://www.webrtc.org/experiments/rtp-hdrext/abs-capture-time",
kind: track.kind,
direction: "sendonly"
});
const nativeRtpCapabilities = _ReactNative106.getLocalRtpCapabilities(localSdpObject, extraHeaderExtensions);
const sendExtendedRtpCapabilities = this._getSendExtendedRtpCapabilities(nativeRtpCapabilities);
const sendingRtpParameters = ortc.getSendingRtpParameters(track.kind, sendExtendedRtpCapabilities);
sendingRtpParameters.codecs = ortc.reduceCodecs(sendingRtpParameters.codecs, codec);
const sendingRemoteRtpParameters = ortc.getSendingRemoteRtpParameters(track.kind, sendExtendedRtpCapabilities);
sendingRemoteRtpParameters.codecs = ortc.reduceCodecs(sendingRemoteRtpParameters.codecs, codec);
if (!this._transportReady) {
yield this.setupTransport({
localDtlsRole: (_a2 = this._forcedLocalDtlsRole) != null ? _a2 : "client",
localSdpObject
});
}
let hackVp9Svc = false;
const layers = (0, scalabilityModes_1.parse)((encodings != null ? encodings : [{}])[0].scalabilityMode);
let offerMediaObject;
if ((encodings == null ? void 0 : encodings.length) === 1 && layers.spatialLayers > 1 && sendingRtpParameters.codecs[0].mimeType.toLowerCase() === "video/vp9") {
logger2.debug("send() | enabling legacy simulcast for VP9 SVC");
hackVp9Svc = true;
localSdpObject = sdpTransform4.parse(offer.sdp);
offerMediaObject = localSdpObject.media[mediaSectionIdx.idx];
sdpUnifiedPlanUtils.addLegacySimulcast({
offerMediaObject,
numStreams: layers.spatialLayers
});
offer = {
type: "offer",
sdp: sdpTransform4.write(localSdpObject)
};
}
if (headerExtensionOptions == null ? void 0 : headerExtensionOptions.absCaptureTime) {
offerMediaObject = localSdpObject.media[mediaSectionIdx.idx];
sdpCommonUtils.addHeaderExtension({
offerMediaObject,
headerExtensionUri: "http://www.webrtc.org/experiments/rtp-hdrext/abs-capture-time",
headerExtensionId: sendingRemoteRtpParameters.headerExtensions.find((headerExtension) => headerExtension.uri === "http://www.webrtc.org/experiments/rtp-hdrext/abs-capture-time").id
});
offer = {
type: "offer",
sdp: sdpTransform4.write(localSdpObject)
};
}
logger2.debug("send() | calling pc.setLocalDescription() [offer:%o]", offer);
yield this._pc.setLocalDescription(offer);
let localId = (_b2 = transceiver.mid) != null ? _b2 : void 0;
if (!localId) {
logger2.warn("send() | missing transceiver.mid (bug in react-native-webrtc, using a workaround");
}
sendingRtpParameters.mid = localId;
localSdpObject = sdpTransform4.parse(this._pc.localDescription.sdp);
offerMediaObject = localSdpObject.media[mediaSectionIdx.idx];
sendingRtpParameters.rtcp.cname = sdpCommonUtils.getCname({
offerMediaObject
});
sendingRtpParameters.msid = `${streamId != null ? streamId : this._sendStream.id} ${track.id}`;
if (!encodings) {
sendingRtpParameters.encodings = sdpUnifiedPlanUtils.getRtpEncodings({
offerMediaObject
});
} else if (encodings.length === 1) {
let newEncodings = sdpUnifiedPlanUtils.getRtpEncodings({
offerMediaObject
});
Object.assign(newEncodings[0], encodings[0]);
if (hackVp9Svc) {
newEncodings = [newEncodings[0]];
}
sendingRtpParameters.encodings = newEncodings;
} else {
sendingRtpParameters.encodings = encodings;
}
if (sendingRtpParameters.encodings.length > 1 && (sendingRtpParameters.codecs[0].mimeType.toLowerCase() === "video/vp8" || sendingRtpParameters.codecs[0].mimeType.toLowerCase() === "video/h264")) {
for (const encoding of sendingRtpParameters.encodings) {
if (encoding.scalabilityMode) {
encoding.scalabilityMode = `L1T${layers.temporalLayers}`;
} else {
encoding.scalabilityMode = "L1T3";
}
}
}
this._remoteSdp.send({
offerMediaObject,
reuseMid: mediaSectionIdx.reuseMid,
offerRtpParameters: sendingRtpParameters,
answerRtpParameters: sendingRemoteRtpParameters,
codecOptions
});
const answer = {
type: "answer",
sdp: this._remoteSdp.getSdp()
};
logger2.debug("send() | calling pc.setRemoteDescription() [answer:%o]", answer);
yield this._pc.setRemoteDescription(answer);
if (!localId) {
localId = transceiver.mid;
sendingRtpParameters.mid = localId;
}
this._mapMidTransceiver.set(localId, transceiver);
return {
localId,
rtpParameters: sendingRtpParameters,
rtpSender: transceiver.sender
};
});
}
stopSending(localId) {
return __async(this, null, function* () {
this.assertSendDirection();
if (this._closed) {
return;
}
logger2.debug("stopSending() [localId:%s]", localId);
const transceiver = this._mapMidTransceiver.get(localId);
if (!transceiver) {
throw new Error("associated RTCRtpTransceiver not found");
}
void transceiver.sender.replaceTrack(null);
this._pc.removeTrack(transceiver.sender);
const mediaSectionClosed = this._remoteSdp.closeMediaSection(transceiver.mid);
if (mediaSectionClosed) {
try {
transceiver.stop();
} catch (error) {
}
}
const offer = yield this._pc.createOffer();
logger2.debug("stopSending() | calling pc.setLocalDescription() [offer:%o]", offer);
yield this._pc.setLocalDescription(offer);
const answer = {
type: "answer",
sdp: this._remoteSdp.getSdp()
};
logger2.debug("stopSending() | calling pc.setRemoteDescription() [answer:%o]", answer);
yield this._pc.setRemoteDescription(answer);
this._mapMidTransceiver.delete(localId);
});
}
pauseSending(localId) {
return __async(this, null, function* () {
this.assertNotClosed();
this.assertSendDirection();
logger2.debug("pauseSending() [localId:%s]", localId);
const transceiver = this._mapMidTransceiver.get(localId);
if (!transceiver) {
throw new Error("associated RTCRtpTransceiver not found");
}
transceiver.direction = "inactive";
this._remoteSdp.pauseMediaSection(localId);
const offer = yield this._pc.createOffer();
logger2.debug("pauseSending() | calling pc.setLocalDescription() [offer:%o]", offer);
yield this._pc.setLocalDescription(offer);
const answer = {
type: "answer",
sdp: this._remoteSdp.getSdp()
};
logger2.debug("pauseSending() | calling pc.setRemoteDescription() [answer:%o]", answer);
yield this._pc.setRemoteDescription(answer);
});
}
resumeSending(localId) {
return __async(this, null, function* () {
this.assertNotClosed();
this.assertSendDirection();
logger2.debug("resumeSending() [localId:%s]", localId);
const transceiver = this._mapMidTransceiver.get(localId);
this._remoteSdp.resumeSendingMediaSection(localId);
if (!transceiver) {
throw new Error("associated RTCRtpTransceiver not found");
}
transceiver.direction = "sendonly";
const offer = yield this._pc.createOffer();
logger2.debug("resumeSending() | calling pc.setLocalDescription() [offer:%o]", offer);
yield this._pc.setLocalDescription(offer);
const answer = {
type: "answer",
sdp: this._remoteSdp.getSdp()
};
logger2.debug("resumeSending() | calling pc.setRemoteDescription() [answer:%o]", answer);
yield this._pc.setRemoteDescription(answer);
});
}
replaceTrack(localId, track) {
return __async(this, null, function* () {
this.assertNotClosed();
this.assertSendDirection();
if (track) {
logger2.debug("replaceTrack() [localId:%s, track.id:%s]", localId, track.id);
} else {
logger2.debug("replaceTrack() [localId:%s, no track]", localId);
}
const transceiver = this._mapMidTransceiver.get(localId);
if (!transceiver) {
throw new Error("associated RTCRtpTransceiver not found");
}
yield transceiver.sender.replaceTrack(track);
});
}
setMaxSpatialLayer(localId, spatialLayer) {
return __async(this, null, function* () {
this.assertNotClosed();
this.assertSendDirection();
logger2.debug("setMaxSpatialLayer() [localId:%s, spatialLayer:%s]", localId, spatialLayer);
const transceiver = this._mapMidTransceiver.get(localId);
if (!transceiver) {
throw new Error("associated RTCRtpTransceiver not found");
}
const parameters = transceiver.sender.getParameters();
parameters.encodings.forEach((encoding, idx) => {
if (idx <= spatialLayer) {
encoding.active = true;
} else {
encoding.active = false;
}
});
yield transceiver.sender.setParameters(parameters);
this._remoteSdp.muxMediaSectionSimulcast(localId, parameters.encodings);
const offer = yield this._pc.createOffer();
logger2.debug("setMaxSpatialLayer() | calling pc.setLocalDescription() [offer:%o]", offer);
yield this._pc.setLocalDescription(offer);
const answer = {
type: "answer",
sdp: this._remoteSdp.getSdp()
};
logger2.debug("setMaxSpatialLayer() | calling pc.setRemoteDescription() [answer:%o]", answer);
yield this._pc.setRemoteDescription(answer);
});
}
setRtpEncodingParameters(localId, params) {
return __async(this, null, function* () {
this.assertNotClosed();
this.assertSendDirection();
logger2.debug("setRtpEncodingParameters() [localId:%s, params:%o]", localId, params);
const transceiver = this._mapMidTransceiver.get(localId);
if (!transceiver) {
throw new Error("associated RTCRtpTransceiver not found");
}
const parameters = transceiver.sender.getParameters();
parameters.encodings.forEach((encoding, idx) => {
parameters.encodings[idx] = __spreadValues(__spreadValues({}, encoding), params);
});
yield transceiver.sender.setParameters(parameters);
this._remoteSdp.muxMediaSectionSimulcast(localId, parameters.encodings);
const offer = yield this._pc.createOffer();
logger2.debug("setRtpEncodingParameters() | calling pc.setLocalDescription() [offer:%o]", offer);
yield this._pc.setLocalDescription(offer);
const answer = {
type: "answer",
sdp: this._remoteSdp.getSdp()
};
logger2.debug("setRtpEncodingParameters() | calling pc.setRemoteDescription() [answer:%o]", answer);
yield this._pc.setRemoteDescription(answer);
});
}
getSenderStats(localId) {
return __async(this, null, function* () {
this.assertNotClosed();
this.assertSendDirection();
const transceiver = this._mapMidTransceiver.get(localId);
if (!transceiver) {
throw new Error("associated RTCRtpTransceiver not found");
}
return transceiver.sender.getStats();
});
}
sendDataChannel(_0) {
return __async(this, arguments, function* ({ ordered, maxPacketLifeTime, maxRetransmits, label, protocol }) {
var _a2;
this.assertNotClosed();
this.assertSendDirection();
const options = {
negotiated: true,
id: this._nextSendSctpStreamId,
ordered,
maxPacketLifeTime,
maxRetransmits,
protocol
};
logger2.debug("sendDataChannel() [options:%o]", options);
const dataChannel = this._pc.createDataChannel(label, options);
this._nextSendSctpStreamId = ++this._nextSendSctpStreamId % SCTP_NUM_STREAMS.MIS;
if (!this._hasDataChannelMediaSection) {
const offer = yield this._pc.createOffer();
const localSdpObject = sdpTransform4.parse(offer.sdp);
const offerMediaObject = localSdpObject.media.find((m) => m.type === "application");
if (!this._transportReady) {
yield this.setupTransport({
localDtlsRole: (_a2 = this._forcedLocalDtlsRole) != null ? _a2 : "client",
localSdpObject
});
}
logger2.debug("sendDataChannel() | calling pc.setLocalDescription() [offer:%o]", offer);
yield this._pc.setLocalDescription(offer);
this._remoteSdp.sendSctpAssociation({ offerMediaObject });
const answer = {
type: "answer",
sdp: this._remoteSdp.getSdp()
};
logger2.debug("sendDataChannel() | calling pc.setRemoteDescription() [answer:%o]", answer);
yield this._pc.setRemoteDescription(answer);
this._hasDataChannelMediaSection = true;
}
const sctpStreamParameters = {
streamId: options.id,
ordered: options.ordered,
maxPacketLifeTime: options.maxPacketLifeTime,
maxRetransmits: options.maxRetransmits
};
return { dataChannel, sctpStreamParameters };
});
}
receive(optionsList) {
return __async(this, null, function* () {
var _a2, _b2, _c, _d, _e;
this.assertNotClosed();
this.assertRecvDirection();
const results = [];
const mapLocalId = /* @__PURE__ */ new Map();
for (const options of optionsList) {
const { trackId, kind, rtpParameters, streamId } = options;
logger2.debug("receive() [trackId:%s, kind:%s]", trackId, kind);
const localId = (_a2 = rtpParameters.mid) != null ? _a2 : String(this._mapMidTransceiver.size);
mapLocalId.set(trackId, localId);
const { msidStreamId } = ortcUtils.getMsidStreamIdAndTrackId(rtpParameters.msid);
this._remoteSdp.receive({
mid: localId,
kind,
offerRtpParameters: rtpParameters,
streamId: (_d = (_c = streamId != null ? streamId : msidStreamId) != null ? _c : (_b2 = rtpParameters.rtcp) == null ? void 0 : _b2.cname) != null ? _d : "-",
trackId
});
}
const offer = {
type: "offer",
sdp: this._remoteSdp.getSdp()
};
logger2.debug("receive() | calling pc.setRemoteDescription() [offer:%o]", offer);
yield this._pc.setRemoteDescription(offer);
for (const options of optionsList) {
const { trackId, onRtpReceiver } = options;
if (onRtpReceiver) {
const localId = mapLocalId.get(trackId);
const transceiver = this._pc.getTransceivers().find((t2) => t2.mid === localId);
if (!transceiver) {
throw new Error("transceiver not found");
}
onRtpReceiver(transceiver.receiver);
}
}
let answer = yield this._pc.createAnswer();
const localSdpObject = sdpTransform4.parse(answer.sdp);
for (const options of optionsList) {
const { trackId, rtpParameters } = options;
const localId = mapLocalId.get(trackId);
const answerMediaObject = localSdpObject.media.find((m) => String(m.mid) === localId);
sdpCommonUtils.applyCodecParameters({
offerRtpParameters: rtpParameters,
answerMediaObject
});
}
answer = {
type: "answer",
sdp: sdpTransform4.write(localSdpObject)
};
if (!this._transportReady) {
yield this.setupTransport({
localDtlsRole: (_e = this._forcedLocalDtlsRole) != null ? _e : "client",
localSdpObject
});
}
logger2.debug("receive() | calling pc.setLocalDescription() [answer:%o]", answer);
yield this._pc.setLocalDescription(answer);
for (const options of optionsList) {
const { trackId } = options;
const localId = mapLocalId.get(trackId);
const transceiver = this._pc.getTransceivers().find((t2) => t2.mid === localId);
if (!transceiver) {
throw new Error("new RTCRtpTransceiver not found");
} else {
this._mapMidTransceiver.set(localId, transceiver);
results.push({
localId,
track: transceiver.receiver.track,
rtpReceiver: transceiver.receiver
});
}
}
return results;
});
}
stopReceiving(localIds) {
return __async(this, null, function* () {
this.assertRecvDirection();
if (this._closed) {
return;
}
for (const localId of localIds) {
logger2.debug("stopReceiving() [localId:%s]", localId);
const transceiver = this._mapMidTransceiver.get(localId);
if (!transceiver) {
throw new Error("associated RTCRtpTransceiver not found");
}
this._remoteSdp.closeMediaSection(transceiver.mid);
}
const offer = {
type: "offer",
sdp: this._remoteSdp.getSdp()
};
logger2.debug("stopReceiving() | calling pc.setRemoteDescription() [offer:%o]", offer);
yield this._pc.setRemoteDescription(offer);
const answer = yield this._pc.createAnswer();
logger2.debug("stopReceiving() | calling pc.setLocalDescription() [answer:%o]", answer);
yield this._pc.setLocalDescription(answer);
for (const localId of localIds) {
this._mapMidTransceiver.delete(localId);
}
});
}
pauseReceiving(localIds) {
return __async(this, null, function* () {
this.assertNotClosed();
this.assertRecvDirection();
for (const localId of localIds) {
logger2.debug("pauseReceiving() [localId:%s]", localId);
const transceiver = this._mapMidTransceiver.get(localId);
if (!transceiver) {
throw new Error("associated RTCRtpTransceiver not found");
}
transceiver.direction = "inactive";
this._remoteSdp.pauseMediaSection(localId);
}
const offer = {
type: "offer",
sdp: this._remoteSdp.getSdp()
};
logger2.debug("pauseReceiving() | calling pc.setRemoteDescription() [offer:%o]", offer);
yield this._pc.setRemoteDescription(offer);
const answer = yield this._pc.createAnswer();
logger2.debug("pauseReceiving() | calling pc.setLocalDescription() [answer:%o]", answer);
yield this._pc.setLocalDescription(answer);
});
}
resumeReceiving(localIds) {
return __async(this, null, function* () {
this.assertNotClosed();
this.assertRecvDirection();
for (const localId of localIds) {
logger2.debug("resumeReceiving() [localId:%s]", localId);
const transceiver = this._mapMidTransceiver.get(localId);
if (!transceiver) {
throw new Error("associated RTCRtpTransceiver not found");
}
transceiver.direction = "recvonly";
this._remoteSdp.resumeReceivingMediaSection(localId);
}
const offer = {
type: "offer",
sdp: this._remoteSdp.getSdp()
};
logger2.debug("resumeReceiving() | calling pc.setRemoteDescription() [offer:%o]", offer);
yield this._pc.setRemoteDescription(offer);
const answer = yield this._pc.createAnswer();
logger2.debug("resumeReceiving() | calling pc.setLocalDescription() [answer:%o]", answer);
yield this._pc.setLocalDescription(answer);
});
}
getReceiverStats(localId) {
return __async(this, null, function* () {
this.assertNotClosed();
this.assertRecvDirection();
const transceiver = this._mapMidTransceiver.get(localId);
if (!transceiver) {
throw new Error("associated RTCRtpTransceiver not found");
}
return transceiver.receiver.getStats();
});
}
receiveDataChannel(_0) {
return __async(this, arguments, function* ({ sctpStreamParameters, label, protocol }) {
var _a2;
this.assertNotClosed();
this.assertRecvDirection();
const { streamId, ordered, maxPacketLifeTime, maxRetransmits } = sctpStreamParameters;
const options = {
negotiated: true,
id: streamId,
ordered,
maxPacketLifeTime,
maxRetransmits,
protocol
};
logger2.debug("receiveDataChannel() [options:%o]", options);
const dataChannel = this._pc.createDataChannel(label, options);
if (!this._hasDataChannelMediaSection) {
this._remoteSdp.receiveSctpAssociation();
const offer = {
type: "offer",
sdp: this._remoteSdp.getSdp()
};
logger2.debug("receiveDataChannel() | calling pc.setRemoteDescription() [offer:%o]", offer);
yield this._pc.setRemoteDescription(offer);
const answer = yield this._pc.createAnswer();
if (!this._transportReady) {
const localSdpObject = sdpTransform4.parse(answer.sdp);
yield this.setupTransport({
localDtlsRole: (_a2 = this._forcedLocalDtlsRole) != null ? _a2 : "client",
localSdpObject
});
}
logger2.debug("receiveDataChannel() | calling pc.setRemoteDescription() [answer:%o]", answer);
yield this._pc.setLocalDescription(answer);
this._hasDataChannelMediaSection = true;
}
return { dataChannel };
});
}
setupTransport(_0) {
return __async(this, arguments, function* ({ localDtlsRole, localSdpObject }) {
if (!localSdpObject) {
localSdpObject = sdpTransform4.parse(this._pc.localDescription.sdp);
}
const dtlsParameters = sdpCommonUtils.extractDtlsParameters({
sdpObject: localSdpObject
});
dtlsParameters.role = localDtlsRole;
this._remoteSdp.updateDtlsRole(localDtlsRole === "client" ? "server" : "client");
yield new Promise((resolve, reject) => {
this.safeEmit("@connect", { dtlsParameters }, resolve, reject);
});
this._transportReady = true;
});
}
assertNotClosed() {
if (this._closed) {
throw new errors_1.InvalidStateError("method called in a closed handler");
}
}
assertSendDirection() {
if (this._direction !== "send") {
throw new Error('method can just be called for handlers with "send" direction');
}
}
assertRecvDirection() {
if (this._direction !== "recv") {
throw new Error('method can just be called for handlers with "recv" direction');
}
}
};
exports.ReactNative106 = ReactNative106;
}
});
// ../../node_modules/.pnpm/mediasoup-client@3.18.3/node_modules/mediasoup-client/lib/Device.js
var require_Device = __commonJS({
"../../node_modules/.pnpm/mediasoup-client@3.18.3/node_modules/mediasoup-client/lib/Device.js"(exports) {
"use strict";
init_process();
Object.defineProperty(exports, "__esModule", { value: true });
exports.Device = void 0;
exports.detectDevice = detectDevice2;
exports.detectDeviceAsync = detectDeviceAsync;
var Logger_1 = require_Logger();
var enhancedEvents_1 = require_enhancedEvents();
var errors_1 = require_errors();
var utils = require_utils();
var ortc = require_ortc();
var Transport_1 = require_Transport();
var Chrome111_1 = require_Chrome111();
var Chrome74_1 = require_Chrome74();
var Firefox120_1 = require_Firefox120();
var Safari12_1 = require_Safari12();
var ReactNative106_1 = require_ReactNative106();
var logger2 = new Logger_1.Logger("Device");
function detectDevice2(userAgent, userAgentData) {
logger2.debug("detectDevice()");
if (!userAgent && typeof navigator === "object") {
userAgent = navigator.userAgent;
}
if (!userAgentData && typeof navigator === "object") {
userAgentData = navigator.userAgentData;
}
return detectDeviceImpl(userAgent, userAgentData);
}
function detectDeviceAsync(userAgent, userAgentData) {
return __async(this, null, function* () {
logger2.debug("detectDeviceAsync()");
if (!userAgent && typeof navigator === "object") {
userAgent = navigator.userAgent;
}
if (!userAgentData && typeof navigator === "object") {
userAgentData = navigator.userAgentData;
}
return detectDeviceImpl(userAgent, userAgentData);
});
}
var Device2 = class _Device {
/**
* Create a new Device to connect to mediasoup server.
*
* @throws {UnsupportedError} if device is not supported.
*/
constructor({ handlerName, handlerFactory } = {}) {
// RTC handler factory.
__publicField(this, "_handlerFactory");
// Handler name.
__publicField(this, "_handlerName");
// Loaded flag.
__publicField(this, "_loaded", false);
// Callback for sending Transports to request sending extended RTP capabilities
// on demand.
__publicField(this, "_getSendExtendedRtpCapabilities");
// Local RTP capabilities for receiving media.
__publicField(this, "_recvRtpCapabilities");
// Whether we can produce audio/video based on remote RTP capabilities.
__publicField(this, "_canProduceByKind", {
audio: false,
video: false
});
// Local SCTP capabilities.
__publicField(this, "_sctpCapabilities");
// Observer instance.
__publicField(this, "_observer", new enhancedEvents_1.EnhancedEventEmitter());
logger2.debug("constructor()");
if (handlerName && handlerFactory) {
throw new TypeError("just one of handlerName or handlerInterface can be given");
}
if (handlerFactory) {
this._handlerFactory = handlerFactory;
} else {
if (handlerName) {
logger2.debug("constructor() | handler given: %s", handlerName);
} else {
handlerName = detectDevice2();
if (handlerName) {
logger2.debug("constructor() | detected handler: %s", handlerName);
} else {
throw new errors_1.UnsupportedError("device not supported");
}
}
switch (handlerName) {
case "Chrome111": {
this._handlerFactory = Chrome111_1.Chrome111.createFactory();
break;
}
case "Chrome74": {
this._handlerFactory = Chrome74_1.Chrome74.createFactory();
break;
}
case "Firefox120": {
this._handlerFactory = Firefox120_1.Firefox120.createFactory();
break;
}
case "Safari12": {
this._handlerFactory = Safari12_1.Safari12.createFactory();
break;
}
case "ReactNative106": {
this._handlerFactory = ReactNative106_1.ReactNative106.createFactory();
break;
}
default: {
throw new TypeError(`unknown handlerName "${handlerName}"`);
}
}
}
this._handlerName = this._handlerFactory.name;
}
/**
* Create a new Device to connect to mediasoup server. It uses a more advanced
* device detection.
*
* @throws {UnsupportedError} if device is not supported.
*/
static factory() {
return __async(this, arguments, function* ({ handlerName, handlerFactory } = {}) {
logger2.debug("factory()");
if (handlerName && handlerFactory) {
throw new TypeError("just one of handlerName or handlerInterface can be given");
}
if (!handlerName && !handlerFactory) {
handlerName = yield detectDeviceAsync();
if (!handlerName) {
throw new errors_1.UnsupportedError("device not supported");
}
}
return new _Device({ handlerName, handlerFactory });
});
}
/**
* The RTC handler name.
*/
get handlerName() {
return this._handlerName;
}
/**
* Whether the Device is loaded.
*/
get loaded() {
return this._loaded;
}
/**
* RTP capabilities of the Device for receiving media.
*
* @throws {InvalidStateError} if not loaded.
*/
get rtpCapabilities() {
if (!this._loaded) {
throw new errors_1.InvalidStateError("not loaded");
}
return this._recvRtpCapabilities;
}
/**
* SCTP capabilities of the Device.
*
* @throws {InvalidStateError} if not loaded.
*/
get sctpCapabilities() {
if (!this._loaded) {
throw new errors_1.InvalidStateError("not loaded");
}
return this._sctpCapabilities;
}
get observer() {
return this._observer;
}
/**
* Initialize the Device.
*/
load(_0) {
return __async(this, arguments, function* ({ routerRtpCapabilities, preferLocalCodecsOrder = false }) {
logger2.debug("load() [routerRtpCapabilities:%o]", routerRtpCapabilities);
if (this._loaded) {
throw new errors_1.InvalidStateError("already loaded");
}
const clonedRouterRtpCapabilities = utils.clone(routerRtpCapabilities);
ortc.validateAndNormalizeRtpCapabilities(clonedRouterRtpCapabilities);
const { getNativeRtpCapabilities, getNativeSctpCapabilities } = this._handlerFactory;
const clonedNativeRtpCapabilities = utils.clone(yield getNativeRtpCapabilities());
ortc.validateAndNormalizeRtpCapabilities(clonedNativeRtpCapabilities);
logger2.debug("load() | got native RTP capabilities:%o", clonedNativeRtpCapabilities);
this._getSendExtendedRtpCapabilities = (nativeRtpCapabilities) => {
return utils.clone(ortc.getExtendedRtpCapabilities(nativeRtpCapabilities, clonedRouterRtpCapabilities, preferLocalCodecsOrder));
};
const recvExtendedRtpCapabilities = ortc.getExtendedRtpCapabilities(
clonedNativeRtpCapabilities,
clonedRouterRtpCapabilities,
/* preferLocalCodecsOrder */
false
);
this._recvRtpCapabilities = ortc.getRecvRtpCapabilities(recvExtendedRtpCapabilities);
ortc.validateAndNormalizeRtpCapabilities(this._recvRtpCapabilities);
logger2.debug("load() | got receiving RTP capabilities:%o", this._recvRtpCapabilities);
this._canProduceByKind.audio = ortc.canSend("audio", this._recvRtpCapabilities);
this._canProduceByKind.video = ortc.canSend("video", this._recvRtpCapabilities);
this._sctpCapabilities = yield getNativeSctpCapabilities();
ortc.validateSctpCapabilities(this._sctpCapabilities);
logger2.debug("load() | got native SCTP capabilities:%o", this._sctpCapabilities);
logger2.debug("load() succeeded");
this._loaded = true;
});
}
/**
* Whether we can produce audio/video.
*
* @throws {InvalidStateError} if not loaded.
* @throws {TypeError} if wrong arguments.
*/
canProduce(kind) {
if (!this._loaded) {
throw new errors_1.InvalidStateError("not loaded");
} else if (kind !== "audio" && kind !== "video") {
throw new TypeError(`invalid kind "${kind}"`);
}
return this._canProduceByKind[kind];
}
/**
* Creates a Transport for sending media.
*
* @throws {InvalidStateError} if not loaded.
* @throws {TypeError} if wrong arguments.
*/
createSendTransport({ id, iceParameters, iceCandidates, dtlsParameters, sctpParameters, iceServers, iceTransportPolicy, additionalSettings, appData }) {
logger2.debug("createSendTransport()");
return this.createTransport({
direction: "send",
id,
iceParameters,
iceCandidates,
dtlsParameters,
sctpParameters,
iceServers,
iceTransportPolicy,
additionalSettings,
appData
});
}
/**
* Creates a Transport for receiving media.
*
* @throws {InvalidStateError} if not loaded.
* @throws {TypeError} if wrong arguments.
*/
createRecvTransport({ id, iceParameters, iceCandidates, dtlsParameters, sctpParameters, iceServers, iceTransportPolicy, additionalSettings, appData }) {
logger2.debug("createRecvTransport()");
return this.createTransport({
direction: "recv",
id,
iceParameters,
iceCandidates,
dtlsParameters,
sctpParameters,
iceServers,
iceTransportPolicy,
additionalSettings,
appData
});
}
createTransport({ direction, id, iceParameters, iceCandidates, dtlsParameters, sctpParameters, iceServers, iceTransportPolicy, additionalSettings, appData }) {
if (!this._loaded) {
throw new errors_1.InvalidStateError("not loaded");
} else if (typeof id !== "string") {
throw new TypeError("missing id");
} else if (typeof iceParameters !== "object") {
throw new TypeError("missing iceParameters");
} else if (!Array.isArray(iceCandidates)) {
throw new TypeError("missing iceCandidates");
} else if (typeof dtlsParameters !== "object") {
throw new TypeError("missing dtlsParameters");
} else if (sctpParameters && typeof sctpParameters !== "object") {
throw new TypeError("wrong sctpParameters");
} else if (appData && typeof appData !== "object") {
throw new TypeError("if given, appData must be an object");
}
const transport = new Transport_1.Transport({
direction,
id,
iceParameters,
iceCandidates,
dtlsParameters,
sctpParameters,
iceServers,
iceTransportPolicy,
additionalSettings,
appData,
handlerFactory: this._handlerFactory,
getSendExtendedRtpCapabilities: this._getSendExtendedRtpCapabilities,
recvRtpCapabilities: this._recvRtpCapabilities,
canProduceByKind: this._canProduceByKind
});
this._observer.safeEmit("newtransport", transport);
return transport;
}
};
exports.Device = Device2;
function detectDeviceImpl(userAgent, userAgentData) {
logger2.debug('detectDeviceImpl() [userAgent:"%s", userAgentData:%o]', userAgent, userAgentData);
const chromiumMajorVersion = getChromiumMajorVersion(userAgent, userAgentData);
if (chromiumMajorVersion) {
if (chromiumMajorVersion >= 111) {
logger2.debug("detectDeviceImpl() | using Chrome111 handler");
return "Chrome111";
} else if (chromiumMajorVersion >= 74) {
logger2.debug("detectDeviceImpl() | using Chrome74 handler");
return "Chrome74";
} else {
logger2.warn("detectDeviceImpl() | unsupported Chromium based browser/version");
return void 0;
}
}
const firefoxMajorVersion = getFirefoxMajorVersion(userAgent);
if (firefoxMajorVersion) {
if (firefoxMajorVersion >= 120) {
logger2.debug("detectDeviceImpl() | using Firefox120 handler");
return "Firefox120";
} else {
logger2.warn("detectDeviceImpl() | unsupported Firefox browser/version");
return void 0;
}
}
const macOSWebKitMajorVersion = getMacOSWebKitMajorVersion(userAgent);
if (macOSWebKitMajorVersion) {
if (macOSWebKitMajorVersion >= 605) {
logger2.debug("detectDeviceImpl() | using Safari12 handler");
return "Safari12";
} else {
logger2.warn("detectDeviceImpl() | unsupported desktop Safari browser/version");
return void 0;
}
}
const iOSWebKitMajorVersion = getIOSWebKitMajorVersion(userAgent);
if (iOSWebKitMajorVersion) {
if (iOSWebKitMajorVersion >= 605) {
logger2.debug("detectDeviceImpl() | using Safari12 handler");
return "Safari12";
} else {
logger2.warn("detectDeviceImpl() | unsupported iOS Safari based browser/version");
return void 0;
}
}
if (isReactNative()) {
if (typeof RTCPeerConnection !== "undefined" && typeof RTCRtpTransceiver !== "undefined") {
logger2.debug("detectDeviceImpl() | using ReactNative106 handler");
return "ReactNative106";
} else {
logger2.warn("detectDeviceImpl() | unsupported react-native-webrtc version without RTCPeerConnection or RTCRtpTransceiver, forgot to call registerGlobals() on it?");
return void 0;
}
}
logger2.warn('detectDeviceImpl() | device not supported [userAgent:"%s", userAgentData:%o]', userAgent, userAgentData);
return void 0;
}
function getChromiumMajorVersion(userAgent, userAgentData) {
var _a2;
logger2.debug("getChromiumMajorVersion()");
if (isIOS(userAgent, userAgentData)) {
logger2.debug("getChromiumMajorVersion() | this is iOS => undefined");
return void 0;
}
if (isReactNative()) {
logger2.debug("getChromiumMajorVersion() | this is React-Native => undefined");
return void 0;
}
if (userAgentData) {
const chromiumBrand = ((_a2 = userAgentData.brands) != null ? _a2 : []).find((b) => b.brand === "Chromium");
if (chromiumBrand) {
const majorVersion = Number(chromiumBrand.version);
logger2.debug(`getChromiumMajorVersion() | Chromium major version based on NavigatorUAData => ${majorVersion}`);
return majorVersion;
}
}
const match = userAgent == null ? void 0 : userAgent.match(/\b(?:Chrome|Chromium)\/(\w+)/i);
if (match == null ? void 0 : match[1]) {
const majorVersion = Number(match[1]);
logger2.debug(`getChromiumMajorVersion() | Chromium major version based on User-Agent => ${majorVersion}`);
return majorVersion;
}
logger2.debug("getChromiumMajorVersion() | this is not Chromium => undefined");
return void 0;
}
function getFirefoxMajorVersion(userAgent) {
logger2.debug("getFirefoxMajorVersion()");
if (isIOS(userAgent)) {
logger2.debug("getFirefoxMajorVersion() | this is iOS => undefined");
return void 0;
}
if (isReactNative()) {
logger2.debug("getFirefoxMajorVersion() | this is React-Native => undefined");
return void 0;
}
const match = userAgent == null ? void 0 : userAgent.match(/\bFirefox\/(\w+)/i);
if (match == null ? void 0 : match[1]) {
const majorVersion = Number(match[1]);
logger2.debug(`getFirefoxMajorVersion() | Firefox major version based on User-Agent => ${majorVersion}`);
return majorVersion;
}
logger2.debug("getFirefoxMajorVersion() | this is not Firefox => undefined");
return void 0;
}
function getMacOSWebKitMajorVersion(userAgent) {
logger2.debug("getMacOSWebKitMajorVersion()");
if (isIOS(userAgent)) {
logger2.debug("getMacOSWebKitMajorVersion() | this is iOS => undefined");
return void 0;
}
if (isReactNative()) {
logger2.debug("getMacOSWebKitMajorVersion() | this is React-Native => undefined");
return void 0;
}
const isSafari2 = userAgent && /\bSafari\b/i.test(userAgent) && !/\bChrome\b/i.test(userAgent) && !/\bChromium\b/i.test(userAgent) && !/\bFirefox\b/i.test(userAgent);
if (!isSafari2) {
logger2.debug("getMacOSWebKitMajorVersion() | this is not Safari => undefined");
return void 0;
}
const match = userAgent.match(/AppleWebKit\/(\w+)/i);
if (match == null ? void 0 : match[1]) {
const majorVersion = Number(match[1]);
logger2.debug(`getMacOSWebKitMajorVersion() | WebKit major version based on User-Agent => ${majorVersion}`);
return majorVersion;
}
logger2.debug("getMacOSWebKitMajorVersion() | this is not WebKit => undefined");
return void 0;
}
function getIOSWebKitMajorVersion(userAgent) {
logger2.debug("getIOSWebKitMajorVersion()");
if (!isIOS(userAgent)) {
logger2.debug("getIOSWebKitMajorVersion() | this is not iOS => undefined");
return void 0;
}
if (isReactNative()) {
logger2.debug("getIOSWebKitMajorVersion() | this is React-Native => undefined");
return void 0;
}
const match = userAgent == null ? void 0 : userAgent.match(/AppleWebKit\/(\w+)/i);
if (match == null ? void 0 : match[1]) {
const majorVersion = Number(match[1]);
logger2.debug(`getIOSWebKitMajorVersion() | WebKit major version based on User-Agent => ${majorVersion}`);
return majorVersion;
}
logger2.debug("getIOSWebKitMajorVersion() | this is not WebKit => undefined");
return void 0;
}
function isIOS(userAgent, userAgentData) {
logger2.debug("isIOS()");
if ((userAgentData == null ? void 0 : userAgentData.platform) === "iOS") {
logger2.debug("isIOS() | this is iOS based on NavigatorUAData.platform => true");
return true;
}
if (userAgentData == null ? void 0 : userAgentData.platform) {
logger2.debug("isIOS() | this is not iOS based on NavigatorUAData.platform => false");
return false;
}
if (userAgent && /iPad|iPhone|iPod/.test(userAgent)) {
logger2.debug("isIOS() | this is iOS based on User-Agent => true");
return true;
}
if (typeof navigator === "object" && navigator.platform === "MacIntel" && navigator.maxTouchPoints > 1) {
logger2.debug("isIOS() | this is iPadOS 13+ based on User-Agent => true");
return true;
}
logger2.debug("isIOS() | this is not iOS => false");
return false;
}
function isReactNative() {
logger2.debug("isReactNative()");
if (typeof navigator === "object" && navigator.product === "ReactNative") {
logger2.debug("isReactNative() | this is React-Native based on navigator.product");
return true;
}
logger2.debug("isReactNative() | this is not React-Native => false");
return false;
}
}
});
// ../../node_modules/.pnpm/@lukeed+uuid@2.0.1/node_modules/@lukeed/uuid/dist/index.js
var require_dist = __commonJS({
"../../node_modules/.pnpm/@lukeed+uuid@2.0.1/node_modules/@lukeed/uuid/dist/index.js"(exports) {
init_process();
var IDX = 256;
var HEX = [];
var BUFFER;
while (IDX--) HEX[IDX] = (IDX + 256).toString(16).substring(1);
function v42() {
var i = 0, num, out = "";
if (!BUFFER || IDX + 16 > 256) {
BUFFER = Array(i = 256);
while (i--) BUFFER[i] = 256 * Math.random() | 0;
i = IDX = 0;
}
for (; i < 16; i++) {
num = BUFFER[IDX + i];
if (i == 6) out += HEX[num & 15 | 64];
else if (i == 8) out += HEX[num & 63 | 128];
else out += HEX[num];
if (i & 1 && i > 1 && i < 11) out += "-";
}
IDX++;
return out;
}
exports.v4 = v42;
}
});
// ../../node_modules/.pnpm/fake-mediastreamtrack@2.2.1/node_modules/fake-mediastreamtrack/lib/fakeEvents/FakeEventTarget.js
var require_FakeEventTarget = __commonJS({
"../../node_modules/.pnpm/fake-mediastreamtrack@2.2.1/node_modules/fake-mediastreamtrack/lib/fakeEvents/FakeEventTarget.js"(exports) {
"use strict";
init_process();
Object.defineProperty(exports, "__esModule", { value: true });
exports.FakeEventTarget = void 0;
var FakeEventTarget = class {
constructor() {
__publicField(this, "listeners", {});
}
addEventListener(type, callback, options) {
var _a2;
if (!callback) {
return;
}
this.listeners[type] = (_a2 = this.listeners[type]) != null ? _a2 : [];
this.listeners[type].push({
callback: (
// eslint-disable-next-line @typescript-eslint/unbound-method
typeof callback === "function" ? callback : callback.handleEvent
),
once: typeof options === "object" && options.once === true
});
}
removeEventListener(type, callback, options) {
if (!this.listeners[type]) {
return;
}
if (!callback) {
return;
}
this.listeners[type] = this.listeners[type].filter((listener) => listener.callback !== // eslint-disable-next-line @typescript-eslint/unbound-method
(typeof callback === "function" ? callback : callback.handleEvent));
}
dispatchEvent(event) {
if (!event || typeof event.type !== "string") {
throw new Error("invalid event object");
}
const entries = this.listeners[event.type];
if (!entries) {
return true;
}
for (const listener of [...entries]) {
try {
listener.callback.call(this, event);
} catch (error) {
setTimeout(() => {
throw error;
}, 0);
}
if (listener.once) {
this.removeEventListener(event.type, listener.callback);
}
}
return !event.defaultPrevented;
}
};
exports.FakeEventTarget = FakeEventTarget;
}
});
// ../../node_modules/.pnpm/fake-mediastreamtrack@2.2.1/node_modules/fake-mediastreamtrack/lib/fakeEvents/FakeEvent.js
var require_FakeEvent = __commonJS({
"../../node_modules/.pnpm/fake-mediastreamtrack@2.2.1/node_modules/fake-mediastreamtrack/lib/fakeEvents/FakeEvent.js"(exports) {
"use strict";
init_process();
Object.defineProperty(exports, "__esModule", { value: true });
exports.FakeEvent = void 0;
var FakeEvent = class {
constructor(type, options = {}) {
/**
* Constants.
*/
__publicField(this, "NONE", 0);
__publicField(this, "CAPTURING_PHASE", 1);
__publicField(this, "AT_TARGET", 2);
__publicField(this, "BUBBLING_PHASE", 3);
/**
* Members.
*/
__publicField(this, "type");
__publicField(this, "bubbles");
__publicField(this, "cancelable");
__publicField(this, "defaultPrevented", false);
__publicField(this, "composed", false);
__publicField(this, "currentTarget", null);
// Not implemented.
__publicField(this, "eventPhase", this.NONE);
__publicField(this, "isTrusted", true);
__publicField(this, "target", null);
__publicField(this, "timeStamp", 0);
// Deprecated.
__publicField(this, "cancelBubble", false);
__publicField(this, "returnValue", true);
__publicField(this, "srcElement", null);
var _a2, _b2;
this.type = type;
this.bubbles = (_a2 = options.bubbles) != null ? _a2 : false;
this.cancelable = (_b2 = options.cancelable) != null ? _b2 : false;
}
preventDefault() {
if (this.cancelable) {
this.defaultPrevented = true;
}
}
/**
* Not implemented.
*/
stopPropagation() {
}
/**
* Not implemented.
*/
stopImmediatePropagation() {
}
/**
* Not implemented.
*/
composedPath() {
return [];
}
/**
* Not implemented.
* @deprecated
*/
// eslint-disable-next-line @typescript-eslint/no-unused-vars
initEvent(type, bubbles, cancelable) {
}
};
exports.FakeEvent = FakeEvent;
}
});
// ../../node_modules/.pnpm/fake-mediastreamtrack@2.2.1/node_modules/fake-mediastreamtrack/lib/utils.js
var require_utils3 = __commonJS({
"../../node_modules/.pnpm/fake-mediastreamtrack@2.2.1/node_modules/fake-mediastreamtrack/lib/utils.js"(exports) {
"use strict";
init_process();
Object.defineProperty(exports, "__esModule", { value: true });
exports.clone = clone;
function clone(value) {
if (value === void 0) {
return void 0;
} else if (Number.isNaN(value)) {
return NaN;
} else if (typeof structuredClone === "function") {
return structuredClone(value);
} else {
return JSON.parse(JSON.stringify(value));
}
}
}
});
// ../../node_modules/.pnpm/fake-mediastreamtrack@2.2.1/node_modules/fake-mediastreamtrack/lib/index.js
var require_lib5 = __commonJS({
"../../node_modules/.pnpm/fake-mediastreamtrack@2.2.1/node_modules/fake-mediastreamtrack/lib/index.js"(exports) {
"use strict";
init_process();
Object.defineProperty(exports, "__esModule", { value: true });
exports.FakeMediaStreamTrack = void 0;
var uuid_1 = require_dist();
var FakeEventTarget_1 = require_FakeEventTarget();
var FakeEvent_1 = require_FakeEvent();
var utils_1 = require_utils3();
var _id, _kind, _label, _readyState, _enabled, _muted, _contentHint, _capabilities, _constraints, _settings, _data, _onmute, _onunmute, _onended, _onenabledchange, _onstopped;
var _FakeMediaStreamTrack = class _FakeMediaStreamTrack extends FakeEventTarget_1.FakeEventTarget {
constructor({ kind, id, label, contentHint, enabled, muted, readyState, capabilities, constraints, settings, data }) {
super();
__privateAdd(this, _id);
__privateAdd(this, _kind);
__privateAdd(this, _label);
__privateAdd(this, _readyState);
__privateAdd(this, _enabled);
__privateAdd(this, _muted);
__privateAdd(this, _contentHint);
__privateAdd(this, _capabilities);
__privateAdd(this, _constraints);
__privateAdd(this, _settings);
__privateAdd(this, _data);
// Events.
__privateAdd(this, _onmute, null);
__privateAdd(this, _onunmute, null);
__privateAdd(this, _onended, null);
// Custom events.
__privateAdd(this, _onenabledchange, null);
__privateAdd(this, _onstopped, null);
__privateSet(this, _id, id != null ? id : (0, uuid_1.v4)());
__privateSet(this, _kind, kind);
__privateSet(this, _label, label != null ? label : "");
__privateSet(this, _contentHint, contentHint != null ? contentHint : "");
__privateSet(this, _enabled, enabled != null ? enabled : true);
__privateSet(this, _muted, muted != null ? muted : false);
__privateSet(this, _readyState, readyState != null ? readyState : "live");
__privateSet(this, _capabilities, capabilities != null ? capabilities : {});
__privateSet(this, _constraints, constraints != null ? constraints : {});
__privateSet(this, _settings, settings != null ? settings : {});
__privateSet(this, _data, data != null ? data : {});
}
get id() {
return __privateGet(this, _id);
}
get kind() {
return __privateGet(this, _kind);
}
get label() {
return __privateGet(this, _label);
}
get contentHint() {
return __privateGet(this, _contentHint);
}
set contentHint(contentHint) {
__privateSet(this, _contentHint, contentHint);
}
get enabled() {
return __privateGet(this, _enabled);
}
/**
* Changes `enabled` member value and fires a custom "enabledchange" event.
*/
set enabled(enabled) {
const changed = __privateGet(this, _enabled) !== enabled;
__privateSet(this, _enabled, enabled);
if (changed) {
this.dispatchEvent(new FakeEvent_1.FakeEvent("enabledchange"));
}
}
get muted() {
return __privateGet(this, _muted);
}
get readyState() {
return __privateGet(this, _readyState);
}
/**
* Application custom data getter.
*/
get data() {
return __privateGet(this, _data);
}
/**
* Application custom data setter.
*/
set data(data) {
__privateSet(this, _data, data);
}
get onmute() {
return __privateGet(this, _onmute);
}
set onmute(handler) {
if (__privateGet(this, _onmute)) {
this.removeEventListener("mute", __privateGet(this, _onmute));
}
__privateSet(this, _onmute, handler);
if (handler) {
this.addEventListener("mute", handler);
}
}
get onunmute() {
return __privateGet(this, _onunmute);
}
set onunmute(handler) {
if (__privateGet(this, _onunmute)) {
this.removeEventListener("unmute", __privateGet(this, _onunmute));
}
__privateSet(this, _onunmute, handler);
if (handler) {
this.addEventListener("unmute", handler);
}
}
get onended() {
return __privateGet(this, _onended);
}
set onended(handler) {
if (__privateGet(this, _onended)) {
this.removeEventListener("ended", __privateGet(this, _onended));
}
__privateSet(this, _onended, handler);
if (handler) {
this.addEventListener("ended", handler);
}
}
get onenabledchange() {
return __privateGet(this, _onenabledchange);
}
set onenabledchange(handler) {
if (__privateGet(this, _onenabledchange)) {
this.removeEventListener("enabledchange", __privateGet(this, _onenabledchange));
}
__privateSet(this, _onenabledchange, handler);
if (handler) {
this.addEventListener("enabledchange", handler);
}
}
get onstopped() {
return __privateGet(this, _onstopped);
}
set onstopped(handler) {
if (__privateGet(this, _onstopped)) {
this.removeEventListener("stopped", __privateGet(this, _onstopped));
}
__privateSet(this, _onstopped, handler);
if (handler) {
this.addEventListener("stopped", handler);
}
}
addEventListener(type, listener, options) {
super.addEventListener(type, listener, options);
}
removeEventListener(type, listener, options) {
super.removeEventListener(type, listener, options);
}
/**
* Changes `readyState` member to "ended" and fires a custom "stopped" event
* (if not already stopped).
*/
stop() {
if (__privateGet(this, _readyState) === "ended") {
return;
}
__privateSet(this, _readyState, "ended");
this.dispatchEvent(new FakeEvent_1.FakeEvent("stopped"));
}
/**
* Clones current track into another FakeMediaStreamTrack. `id` and `data`
* can be optionally given.
*/
clone({ id, data } = {}) {
return new _FakeMediaStreamTrack({
id: id != null ? id : (0, uuid_1.v4)(),
kind: __privateGet(this, _kind),
label: __privateGet(this, _label),
contentHint: __privateGet(this, _contentHint),
enabled: __privateGet(this, _enabled),
muted: __privateGet(this, _muted),
readyState: __privateGet(this, _readyState),
capabilities: (0, utils_1.clone)(__privateGet(this, _capabilities)),
constraints: (0, utils_1.clone)(__privateGet(this, _constraints)),
settings: (0, utils_1.clone)(__privateGet(this, _settings)),
data: data != null ? data : (0, utils_1.clone)(__privateGet(this, _data))
});
}
getCapabilities() {
return __privateGet(this, _capabilities);
}
getConstraints() {
return __privateGet(this, _constraints);
}
applyConstraints() {
return __async(this, arguments, function* (constraints = {}) {
__privateSet(this, _constraints, constraints);
return Promise.resolve();
});
}
getSettings() {
return __privateGet(this, _settings);
}
/**
* Simulates a remotely triggered stop. It fires a custom "stopped" event and
* the standard "ended" event (if the track was not already stopped).
*/
remoteStop() {
if (__privateGet(this, _readyState) === "ended") {
return;
}
__privateSet(this, _readyState, "ended");
this.dispatchEvent(new FakeEvent_1.FakeEvent("stopped"));
this.dispatchEvent(new FakeEvent_1.FakeEvent("ended"));
}
/**
* Simulates a remotely triggered mute. It fires a "mute" event (if the track
* was not already muted).
*/
remoteMute() {
if (__privateGet(this, _muted)) {
return;
}
__privateSet(this, _muted, true);
this.dispatchEvent(new FakeEvent_1.FakeEvent("mute"));
}
/**
* Simulates a remotely triggered unmute. It fires an "unmute" event (if the
* track was muted).
*/
remoteUnmute() {
if (!__privateGet(this, _muted)) {
return;
}
__privateSet(this, _muted, false);
this.dispatchEvent(new FakeEvent_1.FakeEvent("unmute"));
}
};
_id = new WeakMap();
_kind = new WeakMap();
_label = new WeakMap();
_readyState = new WeakMap();
_enabled = new WeakMap();
_muted = new WeakMap();
_contentHint = new WeakMap();
_capabilities = new WeakMap();
_constraints = new WeakMap();
_settings = new WeakMap();
_data = new WeakMap();
_onmute = new WeakMap();
_onunmute = new WeakMap();
_onended = new WeakMap();
_onenabledchange = new WeakMap();
_onstopped = new WeakMap();
var FakeMediaStreamTrack = _FakeMediaStreamTrack;
exports.FakeMediaStreamTrack = FakeMediaStreamTrack;
}
});
// ../../node_modules/.pnpm/mediasoup-client@3.18.3/node_modules/mediasoup-client/lib/handlers/fakeEvents/FakeEventTarget.js
var require_FakeEventTarget2 = __commonJS({
"../../node_modules/.pnpm/mediasoup-client@3.18.3/node_modules/mediasoup-client/lib/handlers/fakeEvents/FakeEventTarget.js"(exports) {
"use strict";
init_process();
Object.defineProperty(exports, "__esModule", { value: true });
exports.FakeEventTarget = void 0;
var FakeEventTarget = class {
constructor() {
__publicField(this, "listeners", {});
}
addEventListener(type, callback, options) {
var _a2;
if (!callback) {
return;
}
this.listeners[type] = (_a2 = this.listeners[type]) != null ? _a2 : [];
this.listeners[type].push({
callback: typeof callback === "function" ? callback : callback.handleEvent,
once: typeof options === "object" && options.once === true
});
}
removeEventListener(type, callback, options) {
if (!this.listeners[type]) {
return;
}
if (!callback) {
return;
}
this.listeners[type] = this.listeners[type].filter((listener) => listener.callback !== (typeof callback === "function" ? callback : callback.handleEvent));
}
dispatchEvent(event) {
if (!event || typeof event.type !== "string") {
throw new Error("invalid event object");
}
const entries = this.listeners[event.type];
if (!entries) {
return true;
}
for (const listener of [...entries]) {
try {
listener.callback.call(this, event);
} catch (error) {
setTimeout(() => {
throw error;
}, 0);
}
if (listener.once) {
this.removeEventListener(event.type, listener.callback);
}
}
return !event.defaultPrevented;
}
};
exports.FakeEventTarget = FakeEventTarget;
}
});
// ../../node_modules/.pnpm/mediasoup-client@3.18.3/node_modules/mediasoup-client/lib/handlers/FakeHandler.js
var require_FakeHandler = __commonJS({
"../../node_modules/.pnpm/mediasoup-client@3.18.3/node_modules/mediasoup-client/lib/handlers/FakeHandler.js"(exports) {
"use strict";
init_process();
Object.defineProperty(exports, "__esModule", { value: true });
exports.FakeHandler = void 0;
var fake_mediastreamtrack_1 = require_lib5();
var enhancedEvents_1 = require_enhancedEvents();
var Logger_1 = require_Logger();
var utils = require_utils();
var ortc = require_ortc();
var errors_1 = require_errors();
var FakeEventTarget_1 = require_FakeEventTarget2();
var logger2 = new Logger_1.Logger("FakeHandler");
var NAME = "FakeHandler";
var FakeHandler = class _FakeHandler extends enhancedEvents_1.EnhancedEventEmitter {
constructor({
// direction,
// iceParameters,
// iceCandidates,
// dtlsParameters,
// sctpParameters,
// iceServers,
// iceTransportPolicy,
// additionalSettings,
getSendExtendedRtpCapabilities
}, fakeParameters) {
super();
// Closed flag.
__publicField(this, "_closed", false);
// Fake parameters source of RTP and SCTP parameters and capabilities.
__publicField(this, "_fakeParameters");
// Callback to request sending extended RTP capabilities on demand.
__publicField(this, "_getSendExtendedRtpCapabilities");
// Local RTCP CNAME.
__publicField(this, "_cname", `CNAME-${utils.generateRandomNumber()}`);
// Default sending MediaStream id.
__publicField(this, "_defaultSendStreamId", `${utils.generateRandomNumber()}`);
// Got transport local and remote parameters.
__publicField(this, "_transportReady", false);
// Next localId.
__publicField(this, "_nextLocalId", 1);
// Sending and receiving tracks indexed by localId.
__publicField(this, "_tracks", /* @__PURE__ */ new Map());
// DataChannel id value counter. It must be incremented for each new DataChannel.
__publicField(this, "_nextSctpStreamId", 0);
logger2.debug("constructor()");
this._getSendExtendedRtpCapabilities = getSendExtendedRtpCapabilities;
this._fakeParameters = fakeParameters;
}
/**
* Creates a factory function.
*/
static createFactory(fakeParameters) {
return {
name: NAME,
factory: (options) => new _FakeHandler(options, fakeParameters),
getNativeRtpCapabilities: () => __async(null, null, function* () {
logger2.debug("getNativeRtpCapabilities()");
return _FakeHandler.getLocalRtpCapabilities(fakeParameters);
}),
getNativeSctpCapabilities: () => __async(null, null, function* () {
logger2.debug("getNativeSctpCapabilities()");
return fakeParameters.generateNativeSctpCapabilities();
})
};
}
static getLocalRtpCapabilities(fakeParameters) {
const nativeRtpCapabilities = fakeParameters.generateNativeRtpCapabilities();
ortc.validateAndNormalizeRtpCapabilities(nativeRtpCapabilities);
return nativeRtpCapabilities;
}
get name() {
return NAME;
}
close() {
logger2.debug("close()");
if (this._closed) {
return;
}
this._closed = true;
super.close();
}
// NOTE: Custom method for simulation purposes.
setIceGatheringState(iceGatheringState) {
this.emit("@icegatheringstatechange", iceGatheringState);
}
// NOTE: Custom method for simulation purposes.
setConnectionState(connectionState) {
this.emit("@connectionstatechange", connectionState);
}
// eslint-disable-next-line @typescript-eslint/no-unused-vars
updateIceServers(iceServers) {
return __async(this, null, function* () {
this.assertNotClosed();
logger2.debug("updateIceServers()");
});
}
// eslint-disable-next-line @typescript-eslint/no-unused-vars
restartIce(iceParameters) {
return __async(this, null, function* () {
this.assertNotClosed();
logger2.debug("restartIce()");
});
}
getTransportStats() {
return __async(this, null, function* () {
this.assertNotClosed();
return /* @__PURE__ */ new Map();
});
}
send(_0) {
return __async(this, arguments, function* ({ track, streamId, encodings, codecOptions, codec }) {
this.assertNotClosed();
logger2.debug("send() [kind:%s, track.id:%s]", track.kind, track.id);
if (!this._transportReady) {
yield this.setupTransport({ localDtlsRole: "server" });
}
const nativeRtpCapabilities = _FakeHandler.getLocalRtpCapabilities(this._fakeParameters);
const sendExtendedRtpCapabilities = this._getSendExtendedRtpCapabilities(nativeRtpCapabilities);
const sendingRtpParameters = ortc.getSendingRtpParameters(track.kind, sendExtendedRtpCapabilities);
sendingRtpParameters.codecs = ortc.reduceCodecs(sendingRtpParameters.codecs, codec);
const useRtx = sendingRtpParameters.codecs.some((_codec) => /.+\/rtx$/i.test(_codec.mimeType));
sendingRtpParameters.mid = `mid-${utils.generateRandomNumber()}`;
sendingRtpParameters.msid = `${streamId != null ? streamId : "-"} ${track.id}`;
if (!encodings) {
encodings = [{}];
}
for (const encoding of encodings) {
encoding.ssrc = utils.generateRandomNumber();
if (useRtx) {
encoding.rtx = { ssrc: utils.generateRandomNumber() };
}
}
sendingRtpParameters.encodings = encodings;
sendingRtpParameters.rtcp = {
cname: this._cname,
reducedSize: true,
mux: true
};
sendingRtpParameters.msid = `${streamId != null ? streamId : this._defaultSendStreamId} ${track.id}`;
const localId = this._nextLocalId++;
this._tracks.set(localId, track);
return { localId: String(localId), rtpParameters: sendingRtpParameters };
});
}
stopSending(localId) {
return __async(this, null, function* () {
logger2.debug("stopSending() [localId:%s]", localId);
if (this._closed) {
return;
}
if (!this._tracks.has(Number(localId))) {
throw new Error("local track not found");
}
this._tracks.delete(Number(localId));
});
}
// eslint-disable-next-line @typescript-eslint/no-unused-vars
pauseSending(localId) {
return __async(this, null, function* () {
this.assertNotClosed();
});
}
// eslint-disable-next-line @typescript-eslint/no-unused-vars
resumeSending(localId) {
return __async(this, null, function* () {
this.assertNotClosed();
});
}
replaceTrack(localId, track) {
return __async(this, null, function* () {
this.assertNotClosed();
if (track) {
logger2.debug("replaceTrack() [localId:%s, track.id:%s]", localId, track.id);
} else {
logger2.debug("replaceTrack() [localId:%s, no track]", localId);
}
this._tracks.delete(Number(localId));
this._tracks.set(Number(localId), track);
});
}
setMaxSpatialLayer(localId, spatialLayer) {
return __async(this, null, function* () {
this.assertNotClosed();
logger2.debug("setMaxSpatialLayer() [localId:%s, spatialLayer:%s]", localId, spatialLayer);
});
}
setRtpEncodingParameters(localId, params) {
return __async(this, null, function* () {
this.assertNotClosed();
logger2.debug("setRtpEncodingParameters() [localId:%s, params:%o]", localId, params);
});
}
// eslint-disable-next-line @typescript-eslint/no-unused-vars
getSenderStats(localId) {
return __async(this, null, function* () {
this.assertNotClosed();
return /* @__PURE__ */ new Map();
});
}
sendDataChannel(_0) {
return __async(this, arguments, function* ({ ordered, maxPacketLifeTime, maxRetransmits, label, protocol }) {
this.assertNotClosed();
if (!this._transportReady) {
yield this.setupTransport({ localDtlsRole: "server" });
}
logger2.debug("sendDataChannel()");
const dataChannel = new FakeRTCDataChannel({
id: this._nextSctpStreamId++,
ordered,
maxPacketLifeTime,
maxRetransmits,
label,
protocol
});
const sctpStreamParameters = {
streamId: this._nextSctpStreamId,
ordered,
maxPacketLifeTime,
maxRetransmits
};
return { dataChannel, sctpStreamParameters };
});
}
receive(optionsList) {
return __async(this, null, function* () {
this.assertNotClosed();
const results = [];
for (const options of optionsList) {
const { trackId, kind } = options;
if (!this._transportReady) {
yield this.setupTransport({ localDtlsRole: "client" });
}
logger2.debug("receive() [trackId:%s, kind:%s]", trackId, kind);
const localId = this._nextLocalId++;
const track = new fake_mediastreamtrack_1.FakeMediaStreamTrack({ kind });
this._tracks.set(localId, track);
results.push({ localId: String(localId), track });
}
return results;
});
}
stopReceiving(localIds) {
return __async(this, null, function* () {
if (this._closed) {
return;
}
for (const localId of localIds) {
logger2.debug("stopReceiving() [localId:%s]", localId);
this._tracks.delete(Number(localId));
}
});
}
pauseReceiving(localIds) {
return __async(this, null, function* () {
this.assertNotClosed();
});
}
resumeReceiving(localIds) {
return __async(this, null, function* () {
this.assertNotClosed();
});
}
// eslint-disable-next-line @typescript-eslint/no-unused-vars
getReceiverStats(localId) {
return __async(this, null, function* () {
this.assertNotClosed();
return /* @__PURE__ */ new Map();
});
}
receiveDataChannel(_0) {
return __async(this, arguments, function* ({ sctpStreamParameters, label, protocol }) {
this.assertNotClosed();
if (!this._transportReady) {
yield this.setupTransport({ localDtlsRole: "client" });
}
logger2.debug("receiveDataChannel()");
const dataChannel = new FakeRTCDataChannel({
id: sctpStreamParameters.streamId,
ordered: sctpStreamParameters.ordered,
maxPacketLifeTime: sctpStreamParameters.maxPacketLifeTime,
maxRetransmits: sctpStreamParameters.maxRetransmits,
label,
protocol
});
return { dataChannel };
});
}
setupTransport(_0) {
return __async(this, arguments, function* ({
localDtlsRole,
// eslint-disable-next-line @typescript-eslint/no-unused-vars
localSdpObject
}) {
const dtlsParameters = utils.clone(this._fakeParameters.generateLocalDtlsParameters());
if (localDtlsRole) {
dtlsParameters.role = localDtlsRole;
}
this.emit("@connectionstatechange", "connecting");
yield new Promise((resolve, reject) => this.emit("@connect", { dtlsParameters }, resolve, reject));
this._transportReady = true;
});
}
assertNotClosed() {
if (this._closed) {
throw new errors_1.InvalidStateError("method called in a closed handler");
}
}
};
exports.FakeHandler = FakeHandler;
var FakeRTCDataChannel = class extends FakeEventTarget_1.FakeEventTarget {
constructor({ id, ordered = true, maxPacketLifeTime = null, maxRetransmits = null, label = "", protocol = "" }) {
super();
// Members for RTCDataChannel standard public getters/setters.
__publicField(this, "_id");
__publicField(this, "_negotiated", true);
// mediasoup just uses negotiated DataChannels.
__publicField(this, "_ordered");
__publicField(this, "_maxPacketLifeTime");
__publicField(this, "_maxRetransmits");
__publicField(this, "_label");
__publicField(this, "_protocol");
__publicField(this, "_readyState", "connecting");
__publicField(this, "_bufferedAmount", 0);
__publicField(this, "_bufferedAmountLowThreshold", 0);
__publicField(this, "_binaryType", "arraybuffer");
// Events.
__publicField(this, "_onopen", null);
__publicField(this, "_onclosing", null);
__publicField(this, "_onclose", null);
__publicField(this, "_onmessage", null);
__publicField(this, "_onbufferedamountlow", null);
__publicField(this, "_onerror", null);
logger2.debug(`constructor() [id:${id}, ordered:${ordered}, maxPacketLifeTime:${maxPacketLifeTime}, maxRetransmits:${maxRetransmits}, label:${label}, protocol:${protocol}`);
this._id = id;
this._ordered = ordered;
this._maxPacketLifeTime = maxPacketLifeTime;
this._maxRetransmits = maxRetransmits;
this._label = label;
this._protocol = protocol;
}
get id() {
return this._id;
}
get negotiated() {
return this._negotiated;
}
get ordered() {
return this._ordered;
}
get maxPacketLifeTime() {
return this._maxPacketLifeTime;
}
get maxRetransmits() {
return this._maxRetransmits;
}
get label() {
return this._label;
}
get protocol() {
return this._protocol;
}
get readyState() {
return this._readyState;
}
get bufferedAmount() {
return this._bufferedAmount;
}
get bufferedAmountLowThreshold() {
return this._bufferedAmountLowThreshold;
}
set bufferedAmountLowThreshold(value) {
this._bufferedAmountLowThreshold = value;
}
get binaryType() {
return this._binaryType;
}
set binaryType(binaryType) {
this._binaryType = binaryType;
}
get onopen() {
return this._onopen;
}
set onopen(handler) {
if (this._onopen) {
this.removeEventListener("open", this._onopen);
}
this._onopen = handler;
if (handler) {
this.addEventListener("open", handler);
}
}
get onclosing() {
return this._onclosing;
}
set onclosing(handler) {
if (this._onclosing) {
this.removeEventListener("closing", this._onclosing);
}
this._onclosing = handler;
if (handler) {
this.addEventListener("closing", handler);
}
}
get onclose() {
return this._onclose;
}
set onclose(handler) {
if (this._onclose) {
this.removeEventListener("close", this._onclose);
}
this._onclose = handler;
if (handler) {
this.addEventListener("close", handler);
}
}
get onmessage() {
return this._onmessage;
}
set onmessage(handler) {
if (this._onmessage) {
this.removeEventListener("message", this._onmessage);
}
this._onmessage = handler;
if (handler) {
this.addEventListener("message", handler);
}
}
get onbufferedamountlow() {
return this._onbufferedamountlow;
}
set onbufferedamountlow(handler) {
if (this._onbufferedamountlow) {
this.removeEventListener("bufferedamountlow", this._onbufferedamountlow);
}
this._onbufferedamountlow = handler;
if (handler) {
this.addEventListener("bufferedamountlow", handler);
}
}
get onerror() {
return this._onerror;
}
set onerror(handler) {
if (this._onerror) {
this.removeEventListener("error", this._onerror);
}
this._onerror = handler;
if (handler) {
this.addEventListener("error", handler);
}
}
addEventListener(type, listener, options) {
super.addEventListener(type, listener, options);
}
removeEventListener(type, listener, options) {
super.removeEventListener(type, listener, options);
}
close() {
if (["closing", "closed"].includes(this._readyState)) {
return;
}
this._readyState = "closed";
}
/**
* We extend the definition of send() to allow Node Buffer. However
* ArrayBufferView and Blob do not exist in Node.
*/
// eslint-disable-next-line @typescript-eslint/no-unused-vars
send(data) {
if (this._readyState !== "open") {
throw new errors_1.InvalidStateError("not open");
}
}
};
}
});
// ../../node_modules/.pnpm/mediasoup-client@3.18.3/node_modules/mediasoup-client/lib/test/fakeParameters.js
var require_fakeParameters = __commonJS({
"../../node_modules/.pnpm/mediasoup-client@3.18.3/node_modules/mediasoup-client/lib/test/fakeParameters.js"(exports) {
"use strict";
init_process();
Object.defineProperty(exports, "__esModule", { value: true });
exports.generateRouterRtpCapabilities = generateRouterRtpCapabilities;
exports.generateNativeRtpCapabilities = generateNativeRtpCapabilities;
exports.generateNativeSctpCapabilities = generateNativeSctpCapabilities;
exports.generateLocalDtlsParameters = generateLocalDtlsParameters;
exports.generateTransportRemoteParameters = generateTransportRemoteParameters;
exports.generateProducerRemoteParameters = generateProducerRemoteParameters;
exports.generateConsumerRemoteParameters = generateConsumerRemoteParameters;
exports.generateDataProducerRemoteParameters = generateDataProducerRemoteParameters;
exports.generateDataConsumerRemoteParameters = generateDataConsumerRemoteParameters;
var utils = require_utils();
function generateFakeUuid() {
return String(utils.generateRandomNumber());
}
function generateRouterRtpCapabilities() {
return utils.deepFreeze({
codecs: [
{
mimeType: "audio/opus",
kind: "audio",
preferredPayloadType: 100,
clockRate: 48e3,
channels: 2,
rtcpFeedback: [{ type: "transport-cc" }],
parameters: {
useinbandfec: 1,
foo: "bar"
}
},
{
mimeType: "video/VP8",
kind: "video",
preferredPayloadType: 101,
clockRate: 9e4,
rtcpFeedback: [
{ type: "nack" },
{ type: "nack", parameter: "pli" },
{ type: "ccm", parameter: "fir" },
{ type: "goog-remb" },
{ type: "transport-cc" }
],
parameters: {
"x-google-start-bitrate": 1500
}
},
{
mimeType: "video/rtx",
kind: "video",
preferredPayloadType: 102,
clockRate: 9e4,
rtcpFeedback: [],
parameters: {
apt: 101
}
},
{
mimeType: "video/H264",
kind: "video",
preferredPayloadType: 103,
clockRate: 9e4,
rtcpFeedback: [
{ type: "nack" },
{ type: "nack", parameter: "pli" },
{ type: "ccm", parameter: "fir" },
{ type: "goog-remb" },
{ type: "transport-cc" }
],
parameters: {
"level-asymmetry-allowed": 1,
"packetization-mode": 1,
"profile-level-id": "42e01f"
}
},
{
mimeType: "video/rtx",
kind: "video",
preferredPayloadType: 104,
clockRate: 9e4,
rtcpFeedback: [],
parameters: {
apt: 103
}
},
{
mimeType: "video/VP9",
kind: "video",
preferredPayloadType: 105,
clockRate: 9e4,
rtcpFeedback: [
{ type: "nack" },
{ type: "nack", parameter: "pli" },
{ type: "ccm", parameter: "fir" },
{ type: "goog-remb" },
{ type: "transport-cc" }
],
parameters: {
"profile-id": 0,
"x-google-start-bitrate": 1500
}
},
{
mimeType: "video/rtx",
kind: "video",
preferredPayloadType: 106,
clockRate: 9e4,
rtcpFeedback: [],
parameters: {
apt: 105
}
}
],
headerExtensions: [
{
kind: "audio",
uri: "urn:ietf:params:rtp-hdrext:sdes:mid",
preferredId: 1,
preferredEncrypt: false,
direction: "sendrecv"
},
{
kind: "video",
uri: "urn:ietf:params:rtp-hdrext:sdes:mid",
preferredId: 1,
preferredEncrypt: false,
direction: "sendrecv"
},
{
kind: "video",
uri: "urn:ietf:params:rtp-hdrext:sdes:rtp-stream-id",
preferredId: 2,
preferredEncrypt: false,
direction: "recvonly"
},
{
kind: "video",
uri: "urn:ietf:params:rtp-hdrext:sdes:repaired-rtp-stream-id",
preferredId: 3,
preferredEncrypt: false,
direction: "recvonly"
},
{
kind: "audio",
uri: "http://www.webrtc.org/experiments/rtp-hdrext/abs-send-time",
preferredId: 4,
preferredEncrypt: false,
direction: "sendrecv"
},
{
kind: "video",
uri: "http://www.webrtc.org/experiments/rtp-hdrext/abs-send-time",
preferredId: 4,
preferredEncrypt: false,
direction: "sendrecv"
},
{
kind: "audio",
uri: "http://www.ietf.org/id/draft-holmer-rmcat-transport-wide-cc-extensions-01",
preferredId: 5,
preferredEncrypt: false,
direction: "recvonly"
},
{
kind: "video",
uri: "http://www.ietf.org/id/draft-holmer-rmcat-transport-wide-cc-extensions-01",
preferredId: 5,
preferredEncrypt: false,
direction: "sendrecv"
},
{
kind: "audio",
uri: "urn:ietf:params:rtp-hdrext:ssrc-audio-level",
preferredId: 10,
preferredEncrypt: false,
direction: "sendrecv"
},
{
kind: "video",
uri: "urn:3gpp:video-orientation",
preferredId: 11,
preferredEncrypt: false,
direction: "sendrecv"
},
{
kind: "video",
uri: "urn:ietf:params:rtp-hdrext:toffset",
preferredId: 12,
preferredEncrypt: false,
direction: "sendrecv"
}
]
});
}
function generateNativeRtpCapabilities() {
return {
codecs: [
{
mimeType: "audio/opus",
kind: "audio",
preferredPayloadType: 111,
clockRate: 48e3,
channels: 2,
rtcpFeedback: [{ type: "transport-cc" }],
parameters: {
minptime: 10,
useinbandfec: 1
}
},
{
mimeType: "audio/ISAC",
kind: "audio",
preferredPayloadType: 103,
clockRate: 16e3,
channels: 1,
rtcpFeedback: [{ type: "transport-cc" }],
parameters: {}
},
{
mimeType: "audio/CN",
kind: "audio",
preferredPayloadType: 106,
clockRate: 32e3,
channels: 1,
rtcpFeedback: [{ type: "transport-cc" }],
parameters: {}
},
{
mimeType: "audio/foo",
kind: "audio",
preferredPayloadType: 107,
clockRate: 9e4,
channels: 4,
rtcpFeedback: [{ type: "foo-qwe-qwe" }],
parameters: {
foo: "lalala"
}
},
{
mimeType: "video/BAZCODEC",
kind: "video",
preferredPayloadType: 100,
clockRate: 9e4,
rtcpFeedback: [
{ type: "foo" },
{ type: "transport-cc" },
{ type: "ccm", parameter: "fir" },
{ type: "nack" },
{ type: "nack", parameter: "pli" }
],
parameters: {
baz: "1234abcd"
}
},
{
mimeType: "video/rtx",
kind: "video",
preferredPayloadType: 101,
clockRate: 9e4,
rtcpFeedback: [],
parameters: {
apt: 100
}
},
{
mimeType: "video/VP8",
kind: "video",
preferredPayloadType: 96,
clockRate: 9e4,
rtcpFeedback: [
{ type: "goog-remb" },
{ type: "transport-cc" },
{ type: "ccm", parameter: "fir" },
{ type: "nack" },
{ type: "nack", parameter: "pli" }
],
parameters: {
baz: "1234abcd"
}
},
{
mimeType: "video/rtx",
kind: "video",
preferredPayloadType: 97,
clockRate: 9e4,
rtcpFeedback: [],
parameters: {
apt: 96
}
},
{
mimeType: "video/VP9",
kind: "video",
preferredPayloadType: 98,
clockRate: 9e4,
rtcpFeedback: [
{ type: "goog-remb" },
{ type: "transport-cc" },
{ type: "ccm", parameter: "fir" },
{ type: "nack" },
{ type: "nack", parameter: "pli" }
],
parameters: {
"profile-id": 0
}
},
{
mimeType: "video/rtx",
kind: "video",
preferredPayloadType: 99,
clockRate: 9e4,
rtcpFeedback: [],
parameters: {
apt: 98
}
}
],
headerExtensions: [
{
kind: "audio",
uri: "urn:ietf:params:rtp-hdrext:sdes:mid",
preferredId: 1
},
{
kind: "video",
uri: "urn:ietf:params:rtp-hdrext:sdes:mid",
preferredId: 1
},
{
kind: "video",
uri: "urn:ietf:params:rtp-hdrext:toffset",
preferredId: 2
},
{
kind: "video",
uri: "http://www.webrtc.org/experiments/rtp-hdrext/abs-send-time",
preferredId: 3
},
{
kind: "video",
uri: "urn:3gpp:video-orientation",
preferredId: 4
},
{
kind: "video",
uri: "http://www.ietf.org/id/draft-holmer-rmcat-transport-wide-cc-extensions-01",
preferredId: 5
},
{
kind: "video",
uri: "http://www.webrtc.org/experiments/rtp-hdrext/playout-delay",
preferredId: 6
},
{
kind: "video",
// @ts-expect-error --- ON purpose.
uri: "http://www.webrtc.org/experiments/rtp-hdrext/video-content-type",
preferredId: 7
},
{
kind: "video",
// @ts-expect-error --- ON purpose.
uri: "http://www.webrtc.org/experiments/rtp-hdrext/video-timing",
preferredId: 8
},
{
kind: "audio",
uri: "urn:ietf:params:rtp-hdrext:ssrc-audio-level",
preferredId: 10
}
]
};
}
function generateNativeSctpCapabilities() {
return utils.deepFreeze({
numStreams: { OS: 2048, MIS: 2048 }
});
}
function generateLocalDtlsParameters() {
return utils.deepFreeze({
fingerprints: [
{
algorithm: "sha-256",
value: "82:5A:68:3D:36:C3:0A:DE:AF:E7:32:43:D2:88:83:57:AC:2D:65:E5:80:C4:B6:FB:AF:1A:A0:21:9F:6D:0C:AD"
}
],
role: "auto"
});
}
function generateTransportRemoteParameters() {
return {
id: generateFakeUuid(),
iceParameters: utils.deepFreeze({
iceLite: true,
password: "yku5ej8nvfaor28lvtrabcx0wkrpkztz",
usernameFragment: "h3hk1iz6qqlnqlne"
}),
iceCandidates: utils.deepFreeze([
{
foundation: "udpcandidate",
address: "9.9.9.9",
ip: "9.9.9.9",
port: 40533,
priority: 1078862079,
protocol: "udp",
type: "host",
tcpType: "passive"
},
{
foundation: "udpcandidate",
address: "9.9.9.9",
ip: "9:9:9:9:9:9",
port: 41333,
priority: 1078862089,
protocol: "udp",
type: "host",
tcpType: "passive"
}
]),
dtlsParameters: utils.deepFreeze({
fingerprints: [
{
algorithm: "sha-256",
value: "A9:F4:E0:D2:74:D3:0F:D9:CA:A5:2F:9F:7F:47:FA:F0:C4:72:DD:73:49:D0:3B:14:90:20:51:30:1B:90:8E:71"
},
{
algorithm: "sha-384",
value: "03:D9:0B:87:13:98:F6:6D:BC:FC:92:2E:39:D4:E1:97:32:61:30:56:84:70:81:6E:D1:82:97:EA:D9:C1:21:0F:6B:C5:E7:7F:E1:97:0C:17:97:6E:CF:B3:EF:2E:74:B0"
},
{
algorithm: "sha-512",
value: "84:27:A4:28:A4:73:AF:43:02:2A:44:68:FF:2F:29:5C:3B:11:9A:60:F4:A8:F0:F5:AC:A0:E3:49:3E:B1:34:53:A9:85:CE:51:9B:ED:87:5E:B8:F4:8E:3D:FA:20:51:B8:96:EE:DA:56:DC:2F:5C:62:79:15:23:E0:21:82:2B:2C"
}
],
role: "auto"
}),
sctpParameters: utils.deepFreeze({
port: 5e3,
OS: 2048,
MIS: 2048,
maxMessageSize: 2e6
})
};
}
function generateProducerRemoteParameters() {
return utils.deepFreeze({
id: generateFakeUuid()
});
}
function generateConsumerRemoteParameters({ id, codecMimeType } = {}) {
switch (codecMimeType) {
case "audio/opus": {
return {
id: id != null ? id : generateFakeUuid(),
producerId: generateFakeUuid(),
kind: "audio",
rtpParameters: utils.deepFreeze({
codecs: [
{
mimeType: "audio/opus",
payloadType: 100,
clockRate: 48e3,
channels: 2,
rtcpFeedback: [{ type: "transport-cc" }],
parameters: {
useinbandfec: 1,
foo: "bar"
}
}
],
encodings: [
{
ssrc: 46687003
}
],
headerExtensions: [
{
uri: "urn:ietf:params:rtp-hdrext:sdes:mid",
id: 1
},
{
uri: "http://www.ietf.org/id/draft-holmer-rmcat-transport-wide-cc-extensions-01",
id: 5
},
{
uri: "urn:ietf:params:rtp-hdrext:ssrc-audio-level",
id: 10
}
],
rtcp: {
cname: "wB4Ql4lrsxYLjzuN",
reducedSize: true,
mux: true
}
})
};
}
case "audio/ISAC": {
return {
id: id != null ? id : generateFakeUuid(),
producerId: generateFakeUuid(),
kind: "audio",
rtpParameters: utils.deepFreeze({
codecs: [
{
mimeType: "audio/ISAC",
payloadType: 111,
clockRate: 16e3,
channels: 1,
rtcpFeedback: [{ type: "transport-cc" }],
parameters: {}
}
],
encodings: [
{
ssrc: 46687004
}
],
headerExtensions: [
{
uri: "urn:ietf:params:rtp-hdrext:sdes:mid",
id: 1
},
{
uri: "http://www.ietf.org/id/draft-holmer-rmcat-transport-wide-cc-extensions-01",
id: 5
}
],
rtcp: {
cname: "wB4Ql4lrsxYLjzuN",
reducedSize: true,
mux: true
}
})
};
}
case "video/VP8": {
return {
id: id != null ? id : generateFakeUuid(),
producerId: generateFakeUuid(),
kind: "video",
rtpParameters: utils.deepFreeze({
codecs: [
{
mimeType: "video/VP8",
payloadType: 101,
clockRate: 9e4,
rtcpFeedback: [
{ type: "nack" },
{ type: "nack", parameter: "pli" },
{ type: "ccm", parameter: "fir" },
{ type: "goog-remb" },
{ type: "transport-cc" }
],
parameters: {
"x-google-start-bitrate": 1500
}
},
{
mimeType: "video/rtx",
payloadType: 102,
clockRate: 9e4,
rtcpFeedback: [],
parameters: {
apt: 101
}
}
],
encodings: [
{
ssrc: 99991111,
rtx: {
ssrc: 99991112
}
}
],
headerExtensions: [
{
uri: "urn:ietf:params:rtp-hdrext:sdes:mid",
id: 1
},
{
uri: "http://www.webrtc.org/experiments/rtp-hdrext/abs-send-time",
id: 4
},
{
uri: "http://www.ietf.org/id/draft-holmer-rmcat-transport-wide-cc-extensions-01",
id: 5
},
{
uri: "urn:3gpp:video-orientation",
id: 11
},
{
uri: "urn:ietf:params:rtp-hdrext:toffset",
id: 12
}
],
rtcp: {
cname: "wB4Ql4lrsxYLjzuN",
reducedSize: true,
mux: true
}
})
};
}
case "video/H264": {
return {
id: id != null ? id : generateFakeUuid(),
producerId: generateFakeUuid(),
kind: "video",
rtpParameters: utils.deepFreeze({
codecs: [
{
mimeType: "video/H264",
payloadType: 103,
clockRate: 9e4,
rtcpFeedback: [
{ type: "nack" },
{ type: "nack", parameter: "pli" },
{ type: "ccm", parameter: "fir" },
{ type: "goog-remb" },
{ type: "transport-cc" }
],
parameters: {
"level-asymmetry-allowed": 1,
"packetization-mode": 1,
"profile-level-id": "42e01f"
}
},
{
mimeType: "video/rtx",
payloadType: 104,
clockRate: 9e4,
rtcpFeedback: [],
parameters: {
apt: 103
}
}
],
encodings: [
{
ssrc: 99991113,
rtx: {
ssrc: 99991114
}
}
],
headerExtensions: [
{
uri: "urn:ietf:params:rtp-hdrext:sdes:mid",
id: 1
},
{
uri: "http://www.webrtc.org/experiments/rtp-hdrext/abs-send-time",
id: 4
},
{
uri: "http://www.ietf.org/id/draft-holmer-rmcat-transport-wide-cc-extensions-01",
id: 5
},
{
uri: "urn:3gpp:video-orientation",
id: 11
},
{
uri: "urn:ietf:params:rtp-hdrext:toffset",
id: 12
}
],
rtcp: {
cname: "wB4Ql4lrsxYLjzuN",
reducedSize: true,
mux: true
}
})
};
}
default: {
throw new TypeError(`unknown codecMimeType '${codecMimeType}'`);
}
}
}
function generateDataProducerRemoteParameters() {
return utils.deepFreeze({
id: generateFakeUuid()
});
}
function generateDataConsumerRemoteParameters({ id } = {}) {
return {
id: id != null ? id : generateFakeUuid(),
dataProducerId: generateFakeUuid(),
sctpStreamParameters: utils.deepFreeze({
streamId: 666,
maxPacketLifeTime: 5e3,
maxRetransmits: void 0
})
};
}
}
});
// ../../node_modules/.pnpm/mediasoup-client@3.18.3/node_modules/mediasoup-client/lib/index.js
var require_lib6 = __commonJS({
"../../node_modules/.pnpm/mediasoup-client@3.18.3/node_modules/mediasoup-client/lib/index.js"(exports) {
"use strict";
init_process();
Object.defineProperty(exports, "__esModule", { value: true });
exports.debug = exports.testFakeParameters = exports.FakeHandler = exports.enhancedEvents = exports.ortc = exports.parseScalabilityMode = exports.detectDeviceAsync = exports.detectDevice = exports.Device = exports.version = exports.types = void 0;
var debug_1 = require_browser2();
exports.debug = debug_1.default;
exports.types = require_types();
exports.version = "3.18.3";
var Device_1 = require_Device();
Object.defineProperty(exports, "Device", { enumerable: true, get: function() {
return Device_1.Device;
} });
Object.defineProperty(exports, "detectDevice", { enumerable: true, get: function() {
return Device_1.detectDevice;
} });
Object.defineProperty(exports, "detectDeviceAsync", { enumerable: true, get: function() {
return Device_1.detectDeviceAsync;
} });
var scalabilityModes_1 = require_scalabilityModes();
Object.defineProperty(exports, "parseScalabilityMode", { enumerable: true, get: function() {
return scalabilityModes_1.parse;
} });
exports.ortc = require_ortc();
exports.enhancedEvents = require_enhancedEvents();
var FakeHandler_1 = require_FakeHandler();
Object.defineProperty(exports, "FakeHandler", { enumerable: true, get: function() {
return FakeHandler_1.FakeHandler;
} });
exports.testFakeParameters = require_fakeParameters();
}
});
// src/index.ts
var index_exports = {};
__export(index_exports, {
Forwarding: () => Forwarding,
PACKAGE_VERSION: () => PACKAGE_VERSION3,
SFUBotMember: () => SFUBotMember,
SFUBotPlugin: () => SFUBotPlugin,
SFUConnection: () => SFUConnection,
defaultSFUBotPluginOptions: () => defaultSFUBotPluginOptions,
errors: () => errors5
});
init_process();
// src/connection/index.ts
init_process();
// ../common/src/index.ts
init_process();
// ../common/src/error.ts
init_process();
// ../common/src/logger.ts
init_process();
var logLevelTypes = [
"disable",
"error",
"warn",
"info",
"debug"
];
var _Logger = class _Logger {
/**@internal */
constructor(prefix) {
/**@internal */
this.debug = (...msg) => {
this._log("debug", ...msg);
return Date.now();
};
/**@internal */
this.info = (...msg) => {
this._log("info", ...msg);
return Date.now();
};
/**@internal */
this.warn = (...msg) => {
this._log("warn", ...msg);
};
/**@internal */
this.error = (...msg) => {
this._log("error", ...msg);
};
/**@internal */
this.elapsed = (timestamp, ...msg) => {
const elapsed = Date.now() - timestamp;
this._log("info", `elapsed ms:${elapsed}`, ...msg);
};
this.prefix = prefix;
}
_log(level, ...msg) {
const logType = logLevelTypes.indexOf(level);
const logLevel = logLevelTypes.indexOf(_Logger.level);
const now = /* @__PURE__ */ new Date();
const parts = _Logger.formatter.formatToParts(now);
const get = (type) => {
var _a2;
return (_a2 = parts.find((p) => p.type === type)) == null ? void 0 : _a2.value;
};
const milliseconds = String(now.getMilliseconds()).padStart(3, "0");
const timestamp = `${get("year")}-${get("month")}-${get("day")}T${get(
"hour"
)}:${get("minute")}:${get("second")}.${milliseconds}+09:00`;
if (logLevel >= logType) {
const parsed = [this.prefix, ...msg].map((m) => {
if (m instanceof Error) {
if (m.toJSON) {
return m.toJSON();
}
return { name: m.name, message: m.message, stack: m.stack };
}
if (typeof m === "object") {
try {
return JSON.parse(JSON.stringify(m));
} catch (e2) {
return "json error";
}
}
return m;
});
msg = parsed;
let log48 = [timestamp, level, ...msg];
if (_Logger.format === "string") {
log48 = [`${timestamp} ${level} ${JSON.stringify(msg)}`];
}
switch (level) {
case "debug":
console.debug(...log48);
break;
case "info":
console.info(...log48);
break;
case "warn":
console.warn(...log48);
break;
case "error":
console.error(...log48);
break;
}
_Logger.onLog({
id: _Logger.id,
timestamp,
level,
message: msg
});
}
_Logger._onLogForAnalytics({
id: _Logger.id,
timestamp,
level,
message: msg,
prefix: this.prefix
});
}
/**@internal */
createBlock(info) {
return {
warn: (...msg) => {
this.warn(__spreadValues({}, info), ...msg);
},
debug: (...msg) => {
this.debug(__spreadValues({}, info), ...msg);
},
info: (...msg) => {
this.info(__spreadValues({}, info), ...msg);
},
error: (...msg) => {
this.error(__spreadValues({}, info), ...msg);
}
};
}
};
_Logger.level = "error";
_Logger.format = "object";
_Logger.onLog = () => {
};
/**@internal */
_Logger._onLogForAnalytics = () => {
};
/**@internal */
_Logger.id = Math.random().toString().slice(2, 7);
_Logger.formatter = new Intl.DateTimeFormat("ja-JP", {
timeZone: "Asia/Tokyo",
year: "numeric",
month: "2-digit",
day: "2-digit",
hour: "2-digit",
minute: "2-digit",
second: "2-digit",
hour12: false
});
var Logger = _Logger;
// ../common/src/error.ts
var log = new Logger("packages/common/src/error.ts");
var SkyWayError = class extends Error {
/**@internal */
constructor(init, logging = true) {
super(init.info.detail);
this.id = Math.random().toString().slice(2, 10);
Object.assign(this, init);
this.name = this.info.name;
if (logging) {
const messages = [
"SkyWayError",
`name:${this.info.name}, detail:${this.info.detail}, solution:${this.info.solution}`
];
if (this.path) {
messages.push(this.path);
}
if (this.error) {
messages.push(this.error);
}
if (this.payload) {
messages.push(this.payload);
}
messages.push(this.id);
log.warn(...messages);
}
}
toJSON() {
return {
id: this.id,
info: this.info,
path: this.path,
payload: this.payload,
error: this.error,
stack: this.stack
};
}
};
// ../common/src/event.ts
init_process();
var log2 = new Logger("packages/common/src/event.ts");
var Event = class {
/**@internal */
constructor(_onSetListener = () => {
}) {
this._onSetListener = _onSetListener;
this._stack = [];
this._eventIndex = 0;
/**@internal */
this.emit = (arg) => {
for (const task of this._stack) {
try {
task.execute(arg);
} catch (error) {
log2.error("task throws error", error);
}
}
};
/**@internal */
this.removeAllListeners = () => {
this._stack = [];
};
/**@internal */
this.pipe = (event) => {
return this.add((arg) => event.emit(arg));
};
/**
* イベントが起きた時に実行する関数を登録する。
* 戻り値として関数の登録を解除する関数が帰ってくる
*/
this.add = (callback) => {
const id = this._eventIndex;
this._stack.push({ execute: callback, id });
this._eventIndex++;
const removeListener = () => {
this._stack = this._stack.filter((item) => item.id !== id && item);
};
const disposer = (disposer2) => {
disposer2.push(removeListener);
};
this._onSetListener();
return { removeListener, disposer };
};
/**イベントが起きた時に一度だけ実行される関数を登録する */
this.once = (callback) => {
const off = this.add((arg) => {
off.removeListener();
callback(arg);
});
return off;
};
/**
* イベントが起きた時に Promise が resolve される
* @param timeLimit ms
*/
this.asPromise = (timeLimit) => new Promise((resolve, reject) => {
const timeout = timeLimit && setTimeout(() => {
reject(
new SerializableError(`Event asPromise timeout : ${timeLimit}`)
);
}, timeLimit);
this.once((arg) => {
if (timeout) clearTimeout(timeout);
resolve(arg);
});
});
/**
* イベントが起きた時に実行される boolean を返す関数を登録する。
* 登録した関数が true を返した時に Promise が resolve される
* */
this.watch = (callback, timeLimit) => new Promise((resolve, reject) => {
const timeout = timeLimit && setTimeout(() => {
reject(new SerializableError(`Event watch timeout : ${timeLimit}`));
}, timeLimit);
const { removeListener } = this.add((arg) => {
const done = callback(arg);
if (done) {
if (timeout) clearTimeout(timeout);
removeListener();
resolve(arg);
}
});
});
}
/**@internal */
get length() {
return this._stack.length;
}
};
var Events = class {
constructor() {
this.events = [];
}
make() {
const event = new Event();
this.events.push(event);
return event;
}
dispose() {
this.events.forEach((event) => {
event.removeAllListeners();
});
this.events = [];
}
};
var EventDisposer = class {
constructor() {
this._disposer = [];
}
push(disposer) {
this._disposer.push(disposer);
}
dispose() {
this._disposer.forEach((d) => {
d();
});
this._disposer = [];
}
};
var SerializableError = class extends Error {
toJSON() {
return {
name: this.name,
message: this.message,
stack: this.stack
};
}
};
// ../common/src/http.ts
init_process();
// ../../node_modules/.pnpm/axios@1.12.0/node_modules/axios/index.js
init_process();
// ../../node_modules/.pnpm/axios@1.12.0/node_modules/axios/lib/axios.js
init_process();
// ../../node_modules/.pnpm/axios@1.12.0/node_modules/axios/lib/utils.js
init_process();
// ../../node_modules/.pnpm/axios@1.12.0/node_modules/axios/lib/helpers/bind.js
init_process();
function bind(fn, thisArg) {
return function wrap() {
return fn.apply(thisArg, arguments);
};
}
// ../../node_modules/.pnpm/axios@1.12.0/node_modules/axios/lib/utils.js
var { toString } = Object.prototype;
var { getPrototypeOf } = Object;
var { iterator, toStringTag } = Symbol;
var kindOf = /* @__PURE__ */ ((cache) => (thing) => {
const str = toString.call(thing);
return cache[str] || (cache[str] = str.slice(8, -1).toLowerCase());
})(/* @__PURE__ */ Object.create(null));
var kindOfTest = (type) => {
type = type.toLowerCase();
return (thing) => kindOf(thing) === type;
};
var typeOfTest = (type) => (thing) => typeof thing === type;
var { isArray } = Array;
var isUndefined = typeOfTest("undefined");
function isBuffer(val) {
return val !== null && !isUndefined(val) && val.constructor !== null && !isUndefined(val.constructor) && isFunction(val.constructor.isBuffer) && val.constructor.isBuffer(val);
}
var isArrayBuffer = kindOfTest("ArrayBuffer");
function isArrayBufferView(val) {
let result2;
if (typeof ArrayBuffer !== "undefined" && ArrayBuffer.isView) {
result2 = ArrayBuffer.isView(val);
} else {
result2 = val && val.buffer && isArrayBuffer(val.buffer);
}
return result2;
}
var isString = typeOfTest("string");
var isFunction = typeOfTest("function");
var isNumber = typeOfTest("number");
var isObject = (thing) => thing !== null && typeof thing === "object";
var isBoolean = (thing) => thing === true || thing === false;
var isPlainObject = (val) => {
if (kindOf(val) !== "object") {
return false;
}
const prototype3 = getPrototypeOf(val);
return (prototype3 === null || prototype3 === Object.prototype || Object.getPrototypeOf(prototype3) === null) && !(toStringTag in val) && !(iterator in val);
};
var isEmptyObject = (val) => {
if (!isObject(val) || isBuffer(val)) {
return false;
}
try {
return Object.keys(val).length === 0 && Object.getPrototypeOf(val) === Object.prototype;
} catch (e2) {
return false;
}
};
var isDate = kindOfTest("Date");
var isFile = kindOfTest("File");
var isBlob = kindOfTest("Blob");
var isFileList = kindOfTest("FileList");
var isStream = (val) => isObject(val) && isFunction(val.pipe);
var isFormData = (thing) => {
let kind;
return thing && (typeof FormData === "function" && thing instanceof FormData || isFunction(thing.append) && ((kind = kindOf(thing)) === "formdata" || // detect form-data instance
kind === "object" && isFunction(thing.toString) && thing.toString() === "[object FormData]"));
};
var isURLSearchParams = kindOfTest("URLSearchParams");
var [isReadableStream, isRequest, isResponse, isHeaders] = ["ReadableStream", "Request", "Response", "Headers"].map(kindOfTest);
var trim = (str) => str.trim ? str.trim() : str.replace(/^[\s\uFEFF\xA0]+|[\s\uFEFF\xA0]+$/g, "");
function forEach(obj, fn, { allOwnKeys = false } = {}) {
if (obj === null || typeof obj === "undefined") {
return;
}
let i;
let l;
if (typeof obj !== "object") {
obj = [obj];
}
if (isArray(obj)) {
for (i = 0, l = obj.length; i < l; i++) {
fn.call(null, obj[i], i, obj);
}
} else {
if (isBuffer(obj)) {
return;
}
const keys = allOwnKeys ? Object.getOwnPropertyNames(obj) : Object.keys(obj);
const len = keys.length;
let key;
for (i = 0; i < len; i++) {
key = keys[i];
fn.call(null, obj[key], key, obj);
}
}
}
function findKey(obj, key) {
if (isBuffer(obj)) {
return null;
}
key = key.toLowerCase();
const keys = Object.keys(obj);
let i = keys.length;
let _key;
while (i-- > 0) {
_key = keys[i];
if (key === _key.toLowerCase()) {
return _key;
}
}
return null;
}
var _global = (() => {
if (typeof globalThis !== "undefined") return globalThis;
return typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : global;
})();
var isContextDefined = (context) => !isUndefined(context) && context !== _global;
function merge() {
const { caseless, skipUndefined } = isContextDefined(this) && this || {};
const result2 = {};
const assignValue = (val, key) => {
const targetKey = caseless && findKey(result2, key) || key;
if (isPlainObject(result2[targetKey]) && isPlainObject(val)) {
result2[targetKey] = merge(result2[targetKey], val);
} else if (isPlainObject(val)) {
result2[targetKey] = merge({}, val);
} else if (isArray(val)) {
result2[targetKey] = val.slice();
} else {
if (!skipUndefined || !isUndefined(val)) {
result2[targetKey] = val;
}
}
};
for (let i = 0, l = arguments.length; i < l; i++) {
arguments[i] && forEach(arguments[i], assignValue);
}
return result2;
}
var extend = (a, b, thisArg, { allOwnKeys } = {}) => {
forEach(b, (val, key) => {
if (thisArg && isFunction(val)) {
a[key] = bind(val, thisArg);
} else {
a[key] = val;
}
}, { allOwnKeys });
return a;
};
var stripBOM = (content) => {
if (content.charCodeAt(0) === 65279) {
content = content.slice(1);
}
return content;
};
var inherits = (constructor, superConstructor, props, descriptors2) => {
constructor.prototype = Object.create(superConstructor.prototype, descriptors2);
constructor.prototype.constructor = constructor;
Object.defineProperty(constructor, "super", {
value: superConstructor.prototype
});
props && Object.assign(constructor.prototype, props);
};
var toFlatObject = (sourceObj, destObj, filter2, propFilter) => {
let props;
let i;
let prop;
const merged = {};
destObj = destObj || {};
if (sourceObj == null) return destObj;
do {
props = Object.getOwnPropertyNames(sourceObj);
i = props.length;
while (i-- > 0) {
prop = props[i];
if ((!propFilter || propFilter(prop, sourceObj, destObj)) && !merged[prop]) {
destObj[prop] = sourceObj[prop];
merged[prop] = true;
}
}
sourceObj = filter2 !== false && getPrototypeOf(sourceObj);
} while (sourceObj && (!filter2 || filter2(sourceObj, destObj)) && sourceObj !== Object.prototype);
return destObj;
};
var endsWith = (str, searchString, position) => {
str = String(str);
if (position === void 0 || position > str.length) {
position = str.length;
}
position -= searchString.length;
const lastIndex = str.indexOf(searchString, position);
return lastIndex !== -1 && lastIndex === position;
};
var toArray = (thing) => {
if (!thing) return null;
if (isArray(thing)) return thing;
let i = thing.length;
if (!isNumber(i)) return null;
const arr = new Array(i);
while (i-- > 0) {
arr[i] = thing[i];
}
return arr;
};
var isTypedArray = /* @__PURE__ */ ((TypedArray) => {
return (thing) => {
return TypedArray && thing instanceof TypedArray;
};
})(typeof Uint8Array !== "undefined" && getPrototypeOf(Uint8Array));
var forEachEntry = (obj, fn) => {
const generator = obj && obj[iterator];
const _iterator = generator.call(obj);
let result2;
while ((result2 = _iterator.next()) && !result2.done) {
const pair = result2.value;
fn.call(obj, pair[0], pair[1]);
}
};
var matchAll = (regExp, str) => {
let matches;
const arr = [];
while ((matches = regExp.exec(str)) !== null) {
arr.push(matches);
}
return arr;
};
var isHTMLForm = kindOfTest("HTMLFormElement");
var toCamelCase = (str) => {
return str.toLowerCase().replace(
/[-_\s]([a-z\d])(\w*)/g,
function replacer(m, p1, p2) {
return p1.toUpperCase() + p2;
}
);
};
var hasOwnProperty = (({ hasOwnProperty: hasOwnProperty2 }) => (obj, prop) => hasOwnProperty2.call(obj, prop))(Object.prototype);
var isRegExp = kindOfTest("RegExp");
var reduceDescriptors = (obj, reducer) => {
const descriptors2 = Object.getOwnPropertyDescriptors(obj);
const reducedDescriptors = {};
forEach(descriptors2, (descriptor, name) => {
let ret;
if ((ret = reducer(descriptor, name, obj)) !== false) {
reducedDescriptors[name] = ret || descriptor;
}
});
Object.defineProperties(obj, reducedDescriptors);
};
var freezeMethods = (obj) => {
reduceDescriptors(obj, (descriptor, name) => {
if (isFunction(obj) && ["arguments", "caller", "callee"].indexOf(name) !== -1) {
return false;
}
const value = obj[name];
if (!isFunction(value)) return;
descriptor.enumerable = false;
if ("writable" in descriptor) {
descriptor.writable = false;
return;
}
if (!descriptor.set) {
descriptor.set = () => {
throw Error("Can not rewrite read-only method '" + name + "'");
};
}
});
};
var toObjectSet = (arrayOrString, delimiter) => {
const obj = {};
const define2 = (arr) => {
arr.forEach((value) => {
obj[value] = true;
});
};
isArray(arrayOrString) ? define2(arrayOrString) : define2(String(arrayOrString).split(delimiter));
return obj;
};
var noop = () => {
};
var toFiniteNumber = (value, defaultValue) => {
return value != null && Number.isFinite(value = +value) ? value : defaultValue;
};
function isSpecCompliantForm(thing) {
return !!(thing && isFunction(thing.append) && thing[toStringTag] === "FormData" && thing[iterator]);
}
var toJSONObject = (obj) => {
const stack = new Array(10);
const visit = (source, i) => {
if (isObject(source)) {
if (stack.indexOf(source) >= 0) {
return;
}
if (isBuffer(source)) {
return source;
}
if (!("toJSON" in source)) {
stack[i] = source;
const target = isArray(source) ? [] : {};
forEach(source, (value, key) => {
const reducedValue = visit(value, i + 1);
!isUndefined(reducedValue) && (target[key] = reducedValue);
});
stack[i] = void 0;
return target;
}
}
return source;
};
return visit(obj, 0);
};
var isAsyncFn = kindOfTest("AsyncFunction");
var isThenable = (thing) => thing && (isObject(thing) || isFunction(thing)) && isFunction(thing.then) && isFunction(thing.catch);
var _setImmediate = ((setImmediateSupported, postMessageSupported) => {
if (setImmediateSupported) {
return setImmediate;
}
return postMessageSupported ? ((token, callbacks) => {
_global.addEventListener("message", ({ source, data }) => {
if (source === _global && data === token) {
callbacks.length && callbacks.shift()();
}
}, false);
return (cb) => {
callbacks.push(cb);
_global.postMessage(token, "*");
};
})(`axios@${Math.random()}`, []) : (cb) => setTimeout(cb);
})(
typeof setImmediate === "function",
isFunction(_global.postMessage)
);
var asap = typeof queueMicrotask !== "undefined" ? queueMicrotask.bind(_global) : typeof process !== "undefined" && process.nextTick || _setImmediate;
var isIterable = (thing) => thing != null && isFunction(thing[iterator]);
var utils_default = {
isArray,
isArrayBuffer,
isBuffer,
isFormData,
isArrayBufferView,
isString,
isNumber,
isBoolean,
isObject,
isPlainObject,
isEmptyObject,
isReadableStream,
isRequest,
isResponse,
isHeaders,
isUndefined,
isDate,
isFile,
isBlob,
isRegExp,
isFunction,
isStream,
isURLSearchParams,
isTypedArray,
isFileList,
forEach,
merge,
extend,
trim,
stripBOM,
inherits,
toFlatObject,
kindOf,
kindOfTest,
endsWith,
toArray,
forEachEntry,
matchAll,
isHTMLForm,
hasOwnProperty,
hasOwnProp: hasOwnProperty,
// an alias to avoid ESLint no-prototype-builtins detection
reduceDescriptors,
freezeMethods,
toObjectSet,
toCamelCase,
noop,
toFiniteNumber,
findKey,
global: _global,
isContextDefined,
isSpecCompliantForm,
toJSONObject,
isAsyncFn,
isThenable,
setImmediate: _setImmediate,
asap,
isIterable
};
// ../../node_modules/.pnpm/axios@1.12.0/node_modules/axios/lib/core/Axios.js
init_process();
// ../../node_modules/.pnpm/axios@1.12.0/node_modules/axios/lib/helpers/buildURL.js
init_process();
// ../../node_modules/.pnpm/axios@1.12.0/node_modules/axios/lib/helpers/AxiosURLSearchParams.js
init_process();
// ../../node_modules/.pnpm/axios@1.12.0/node_modules/axios/lib/helpers/toFormData.js
init_process();
// ../../node_modules/.pnpm/axios@1.12.0/node_modules/axios/lib/core/AxiosError.js
init_process();
function AxiosError(message, code, config, request, response) {
Error.call(this);
if (Error.captureStackTrace) {
Error.captureStackTrace(this, this.constructor);
} else {
this.stack = new Error().stack;
}
this.message = message;
this.name = "AxiosError";
code && (this.code = code);
config && (this.config = config);
request && (this.request = request);
if (response) {
this.response = response;
this.status = response.status ? response.status : null;
}
}
utils_default.inherits(AxiosError, Error, {
toJSON: function toJSON() {
return {
// Standard
message: this.message,
name: this.name,
// Microsoft
description: this.description,
number: this.number,
// Mozilla
fileName: this.fileName,
lineNumber: this.lineNumber,
columnNumber: this.columnNumber,
stack: this.stack,
// Axios
config: utils_default.toJSONObject(this.config),
code: this.code,
status: this.status
};
}
});
var prototype = AxiosError.prototype;
var descriptors = {};
[
"ERR_BAD_OPTION_VALUE",
"ERR_BAD_OPTION",
"ECONNABORTED",
"ETIMEDOUT",
"ERR_NETWORK",
"ERR_FR_TOO_MANY_REDIRECTS",
"ERR_DEPRECATED",
"ERR_BAD_RESPONSE",
"ERR_BAD_REQUEST",
"ERR_CANCELED",
"ERR_NOT_SUPPORT",
"ERR_INVALID_URL"
// eslint-disable-next-line func-names
].forEach((code) => {
descriptors[code] = { value: code };
});
Object.defineProperties(AxiosError, descriptors);
Object.defineProperty(prototype, "isAxiosError", { value: true });
AxiosError.from = (error, code, config, request, response, customProps) => {
const axiosError = Object.create(prototype);
utils_default.toFlatObject(error, axiosError, function filter2(obj) {
return obj !== Error.prototype;
}, (prop) => {
return prop !== "isAxiosError";
});
const msg = error && error.message ? error.message : "Error";
const errCode = code == null && error ? error.code : code;
AxiosError.call(axiosError, msg, errCode, config, request, response);
if (error && axiosError.cause == null) {
Object.defineProperty(axiosError, "cause", { value: error, configurable: true });
}
axiosError.name = error && error.name || "Error";
customProps && Object.assign(axiosError, customProps);
return axiosError;
};
var AxiosError_default = AxiosError;
// ../../node_modules/.pnpm/axios@1.12.0/node_modules/axios/lib/helpers/null.js
init_process();
var null_default = null;
// ../../node_modules/.pnpm/axios@1.12.0/node_modules/axios/lib/helpers/toFormData.js
function isVisitable(thing) {
return utils_default.isPlainObject(thing) || utils_default.isArray(thing);
}
function removeBrackets(key) {
return utils_default.endsWith(key, "[]") ? key.slice(0, -2) : key;
}
function renderKey(path, key, dots) {
if (!path) return key;
return path.concat(key).map(function each(token, i) {
token = removeBrackets(token);
return !dots && i ? "[" + token + "]" : token;
}).join(dots ? "." : "");
}
function isFlatArray(arr) {
return utils_default.isArray(arr) && !arr.some(isVisitable);
}
var predicates = utils_default.toFlatObject(utils_default, {}, null, function filter(prop) {
return /^is[A-Z]/.test(prop);
});
function toFormData(obj, formData, options) {
if (!utils_default.isObject(obj)) {
throw new TypeError("target must be an object");
}
formData = formData || new (null_default || FormData)();
options = utils_default.toFlatObject(options, {
metaTokens: true,
dots: false,
indexes: false
}, false, function defined(option, source) {
return !utils_default.isUndefined(source[option]);
});
const metaTokens = options.metaTokens;
const visitor = options.visitor || defaultVisitor;
const dots = options.dots;
const indexes = options.indexes;
const _Blob = options.Blob || typeof Blob !== "undefined" && Blob;
const useBlob = _Blob && utils_default.isSpecCompliantForm(formData);
if (!utils_default.isFunction(visitor)) {
throw new TypeError("visitor must be a function");
}
function convertValue(value) {
if (value === null) return "";
if (utils_default.isDate(value)) {
return value.toISOString();
}
if (utils_default.isBoolean(value)) {
return value.toString();
}
if (!useBlob && utils_default.isBlob(value)) {
throw new AxiosError_default("Blob is not supported. Use a Buffer instead.");
}
if (utils_default.isArrayBuffer(value) || utils_default.isTypedArray(value)) {
return useBlob && typeof Blob === "function" ? new Blob([value]) : Buffer.from(value);
}
return value;
}
function defaultVisitor(value, key, path) {
let arr = value;
if (value && !path && typeof value === "object") {
if (utils_default.endsWith(key, "{}")) {
key = metaTokens ? key : key.slice(0, -2);
value = JSON.stringify(value);
} else if (utils_default.isArray(value) && isFlatArray(value) || (utils_default.isFileList(value) || utils_default.endsWith(key, "[]")) && (arr = utils_default.toArray(value))) {
key = removeBrackets(key);
arr.forEach(function each(el, index) {
!(utils_default.isUndefined(el) || el === null) && formData.append(
// eslint-disable-next-line no-nested-ternary
indexes === true ? renderKey([key], index, dots) : indexes === null ? key : key + "[]",
convertValue(el)
);
});
return false;
}
}
if (isVisitable(value)) {
return true;
}
formData.append(renderKey(path, key, dots), convertValue(value));
return false;
}
const stack = [];
const exposedHelpers = Object.assign(predicates, {
defaultVisitor,
convertValue,
isVisitable
});
function build(value, path) {
if (utils_default.isUndefined(value)) return;
if (stack.indexOf(value) !== -1) {
throw Error("Circular reference detected in " + path.join("."));
}
stack.push(value);
utils_default.forEach(value, function each(el, key) {
const result2 = !(utils_default.isUndefined(el) || el === null) && visitor.call(
formData,
el,
utils_default.isString(key) ? key.trim() : key,
path,
exposedHelpers
);
if (result2 === true) {
build(el, path ? path.concat(key) : [key]);
}
});
stack.pop();
}
if (!utils_default.isObject(obj)) {
throw new TypeError("data must be an object");
}
build(obj);
return formData;
}
var toFormData_default = toFormData;
// ../../node_modules/.pnpm/axios@1.12.0/node_modules/axios/lib/helpers/AxiosURLSearchParams.js
function encode(str) {
const charMap = {
"!": "%21",
"'": "%27",
"(": "%28",
")": "%29",
"~": "%7E",
"%20": "+",
"%00": "\0"
};
return encodeURIComponent(str).replace(/[!'()~]|%20|%00/g, function replacer(match) {
return charMap[match];
});
}
function AxiosURLSearchParams(params, options) {
this._pairs = [];
params && toFormData_default(params, this, options);
}
var prototype2 = AxiosURLSearchParams.prototype;
prototype2.append = function append(name, value) {
this._pairs.push([name, value]);
};
prototype2.toString = function toString2(encoder) {
const _encode = encoder ? function(value) {
return encoder.call(this, value, encode);
} : encode;
return this._pairs.map(function each(pair) {
return _encode(pair[0]) + "=" + _encode(pair[1]);
}, "").join("&");
};
var AxiosURLSearchParams_default = AxiosURLSearchParams;
// ../../node_modules/.pnpm/axios@1.12.0/node_modules/axios/lib/helpers/buildURL.js
function encode2(val) {
return encodeURIComponent(val).replace(/%3A/gi, ":").replace(/%24/g, "$").replace(/%2C/gi, ",").replace(/%20/g, "+");
}
function buildURL(url, params, options) {
if (!params) {
return url;
}
const _encode = options && options.encode || encode2;
if (utils_default.isFunction(options)) {
options = {
serialize: options
};
}
const serializeFn = options && options.serialize;
let serializedParams;
if (serializeFn) {
serializedParams = serializeFn(params, options);
} else {
serializedParams = utils_default.isURLSearchParams(params) ? params.toString() : new AxiosURLSearchParams_default(params, options).toString(_encode);
}
if (serializedParams) {
const hashmarkIndex = url.indexOf("#");
if (hashmarkIndex !== -1) {
url = url.slice(0, hashmarkIndex);
}
url += (url.indexOf("?") === -1 ? "?" : "&") + serializedParams;
}
return url;
}
// ../../node_modules/.pnpm/axios@1.12.0/node_modules/axios/lib/core/InterceptorManager.js
init_process();
var InterceptorManager = class {
constructor() {
this.handlers = [];
}
/**
* Add a new interceptor to the stack
*
* @param {Function} fulfilled The function to handle `then` for a `Promise`
* @param {Function} rejected The function to handle `reject` for a `Promise`
*
* @return {Number} An ID used to remove interceptor later
*/
use(fulfilled, rejected, options) {
this.handlers.push({
fulfilled,
rejected,
synchronous: options ? options.synchronous : false,
runWhen: options ? options.runWhen : null
});
return this.handlers.length - 1;
}
/**
* Remove an interceptor from the stack
*
* @param {Number} id The ID that was returned by `use`
*
* @returns {Boolean} `true` if the interceptor was removed, `false` otherwise
*/
eject(id) {
if (this.handlers[id]) {
this.handlers[id] = null;
}
}
/**
* Clear all interceptors from the stack
*
* @returns {void}
*/
clear() {
if (this.handlers) {
this.handlers = [];
}
}
/**
* Iterate over all the registered interceptors
*
* This method is particularly useful for skipping over any
* interceptors that may have become `null` calling `eject`.
*
* @param {Function} fn The function to call for each interceptor
*
* @returns {void}
*/
forEach(fn) {
utils_default.forEach(this.handlers, function forEachHandler(h) {
if (h !== null) {
fn(h);
}
});
}
};
var InterceptorManager_default = InterceptorManager;
// ../../node_modules/.pnpm/axios@1.12.0/node_modules/axios/lib/core/dispatchRequest.js
init_process();
// ../../node_modules/.pnpm/axios@1.12.0/node_modules/axios/lib/core/transformData.js
init_process();
// ../../node_modules/.pnpm/axios@1.12.0/node_modules/axios/lib/defaults/index.js
init_process();
// ../../node_modules/.pnpm/axios@1.12.0/node_modules/axios/lib/defaults/transitional.js
init_process();
var transitional_default = {
silentJSONParsing: true,
forcedJSONParsing: true,
clarifyTimeoutError: false
};
// ../../node_modules/.pnpm/axios@1.12.0/node_modules/axios/lib/helpers/toURLEncodedForm.js
init_process();
// ../../node_modules/.pnpm/axios@1.12.0/node_modules/axios/lib/platform/index.js
init_process();
// ../../node_modules/.pnpm/axios@1.12.0/node_modules/axios/lib/platform/browser/index.js
init_process();
// ../../node_modules/.pnpm/axios@1.12.0/node_modules/axios/lib/platform/browser/classes/URLSearchParams.js
init_process();
var URLSearchParams_default = typeof URLSearchParams !== "undefined" ? URLSearchParams : AxiosURLSearchParams_default;
// ../../node_modules/.pnpm/axios@1.12.0/node_modules/axios/lib/platform/browser/classes/FormData.js
init_process();
var FormData_default = typeof FormData !== "undefined" ? FormData : null;
// ../../node_modules/.pnpm/axios@1.12.0/node_modules/axios/lib/platform/browser/classes/Blob.js
init_process();
var Blob_default = typeof Blob !== "undefined" ? Blob : null;
// ../../node_modules/.pnpm/axios@1.12.0/node_modules/axios/lib/platform/browser/index.js
var browser_default = {
isBrowser: true,
classes: {
URLSearchParams: URLSearchParams_default,
FormData: FormData_default,
Blob: Blob_default
},
protocols: ["http", "https", "file", "blob", "url", "data"]
};
// ../../node_modules/.pnpm/axios@1.12.0/node_modules/axios/lib/platform/common/utils.js
var utils_exports = {};
__export(utils_exports, {
hasBrowserEnv: () => hasBrowserEnv,
hasStandardBrowserEnv: () => hasStandardBrowserEnv,
hasStandardBrowserWebWorkerEnv: () => hasStandardBrowserWebWorkerEnv,
navigator: () => _navigator,
origin: () => origin
});
init_process();
var hasBrowserEnv = typeof window !== "undefined" && typeof document !== "undefined";
var _navigator = typeof navigator === "object" && navigator || void 0;
var hasStandardBrowserEnv = hasBrowserEnv && (!_navigator || ["ReactNative", "NativeScript", "NS"].indexOf(_navigator.product) < 0);
var hasStandardBrowserWebWorkerEnv = (() => {
return typeof WorkerGlobalScope !== "undefined" && // eslint-disable-next-line no-undef
self instanceof WorkerGlobalScope && typeof self.importScripts === "function";
})();
var origin = hasBrowserEnv && window.location.href || "http://localhost";
// ../../node_modules/.pnpm/axios@1.12.0/node_modules/axios/lib/platform/index.js
var platform_default = __spreadValues(__spreadValues({}, utils_exports), browser_default);
// ../../node_modules/.pnpm/axios@1.12.0/node_modules/axios/lib/helpers/toURLEncodedForm.js
function toURLEncodedForm(data, options) {
return toFormData_default(data, new platform_default.classes.URLSearchParams(), __spreadValues({
visitor: function(value, key, path, helpers) {
if (platform_default.isNode && utils_default.isBuffer(value)) {
this.append(key, value.toString("base64"));
return false;
}
return helpers.defaultVisitor.apply(this, arguments);
}
}, options));
}
// ../../node_modules/.pnpm/axios@1.12.0/node_modules/axios/lib/helpers/formDataToJSON.js
init_process();
function parsePropPath(name) {
return utils_default.matchAll(/\w+|\[(\w*)]/g, name).map((match) => {
return match[0] === "[]" ? "" : match[1] || match[0];
});
}
function arrayToObject(arr) {
const obj = {};
const keys = Object.keys(arr);
let i;
const len = keys.length;
let key;
for (i = 0; i < len; i++) {
key = keys[i];
obj[key] = arr[key];
}
return obj;
}
function formDataToJSON(formData) {
function buildPath(path, value, target, index) {
let name = path[index++];
if (name === "__proto__") return true;
const isNumericKey = Number.isFinite(+name);
const isLast = index >= path.length;
name = !name && utils_default.isArray(target) ? target.length : name;
if (isLast) {
if (utils_default.hasOwnProp(target, name)) {
target[name] = [target[name], value];
} else {
target[name] = value;
}
return !isNumericKey;
}
if (!target[name] || !utils_default.isObject(target[name])) {
target[name] = [];
}
const result2 = buildPath(path, value, target[name], index);
if (result2 && utils_default.isArray(target[name])) {
target[name] = arrayToObject(target[name]);
}
return !isNumericKey;
}
if (utils_default.isFormData(formData) && utils_default.isFunction(formData.entries)) {
const obj = {};
utils_default.forEachEntry(formData, (name, value) => {
buildPath(parsePropPath(name), value, obj, 0);
});
return obj;
}
return null;
}
var formDataToJSON_default = formDataToJSON;
// ../../node_modules/.pnpm/axios@1.12.0/node_modules/axios/lib/defaults/index.js
function stringifySafely(rawValue, parser, encoder) {
if (utils_default.isString(rawValue)) {
try {
(parser || JSON.parse)(rawValue);
return utils_default.trim(rawValue);
} catch (e2) {
if (e2.name !== "SyntaxError") {
throw e2;
}
}
}
return (encoder || JSON.stringify)(rawValue);
}
var defaults = {
transitional: transitional_default,
adapter: ["xhr", "http", "fetch"],
transformRequest: [function transformRequest(data, headers) {
const contentType = headers.getContentType() || "";
const hasJSONContentType = contentType.indexOf("application/json") > -1;
const isObjectPayload = utils_default.isObject(data);
if (isObjectPayload && utils_default.isHTMLForm(data)) {
data = new FormData(data);
}
const isFormData2 = utils_default.isFormData(data);
if (isFormData2) {
return hasJSONContentType ? JSON.stringify(formDataToJSON_default(data)) : data;
}
if (utils_default.isArrayBuffer(data) || utils_default.isBuffer(data) || utils_default.isStream(data) || utils_default.isFile(data) || utils_default.isBlob(data) || utils_default.isReadableStream(data)) {
return data;
}
if (utils_default.isArrayBufferView(data)) {
return data.buffer;
}
if (utils_default.isURLSearchParams(data)) {
headers.setContentType("application/x-www-form-urlencoded;charset=utf-8", false);
return data.toString();
}
let isFileList2;
if (isObjectPayload) {
if (contentType.indexOf("application/x-www-form-urlencoded") > -1) {
return toURLEncodedForm(data, this.formSerializer).toString();
}
if ((isFileList2 = utils_default.isFileList(data)) || contentType.indexOf("multipart/form-data") > -1) {
const _FormData = this.env && this.env.FormData;
return toFormData_default(
isFileList2 ? { "files[]": data } : data,
_FormData && new _FormData(),
this.formSerializer
);
}
}
if (isObjectPayload || hasJSONContentType) {
headers.setContentType("application/json", false);
return stringifySafely(data);
}
return data;
}],
transformResponse: [function transformResponse(data) {
const transitional2 = this.transitional || defaults.transitional;
const forcedJSONParsing = transitional2 && transitional2.forcedJSONParsing;
const JSONRequested = this.responseType === "json";
if (utils_default.isResponse(data) || utils_default.isReadableStream(data)) {
return data;
}
if (data && utils_default.isString(data) && (forcedJSONParsing && !this.responseType || JSONRequested)) {
const silentJSONParsing = transitional2 && transitional2.silentJSONParsing;
const strictJSONParsing = !silentJSONParsing && JSONRequested;
try {
return JSON.parse(data, this.parseReviver);
} catch (e2) {
if (strictJSONParsing) {
if (e2.name === "SyntaxError") {
throw AxiosError_default.from(e2, AxiosError_default.ERR_BAD_RESPONSE, this, null, this.response);
}
throw e2;
}
}
}
return data;
}],
/**
* A timeout in milliseconds to abort a request. If set to 0 (default) a
* timeout is not created.
*/
timeout: 0,
xsrfCookieName: "XSRF-TOKEN",
xsrfHeaderName: "X-XSRF-TOKEN",
maxContentLength: -1,
maxBodyLength: -1,
env: {
FormData: platform_default.classes.FormData,
Blob: platform_default.classes.Blob
},
validateStatus: function validateStatus(status) {
return status >= 200 && status < 300;
},
headers: {
common: {
"Accept": "application/json, text/plain, */*",
"Content-Type": void 0
}
}
};
utils_default.forEach(["delete", "get", "head", "post", "put", "patch"], (method) => {
defaults.headers[method] = {};
});
var defaults_default = defaults;
// ../../node_modules/.pnpm/axios@1.12.0/node_modules/axios/lib/core/AxiosHeaders.js
init_process();
// ../../node_modules/.pnpm/axios@1.12.0/node_modules/axios/lib/helpers/parseHeaders.js
init_process();
var ignoreDuplicateOf = utils_default.toObjectSet([
"age",
"authorization",
"content-length",
"content-type",
"etag",
"expires",
"from",
"host",
"if-modified-since",
"if-unmodified-since",
"last-modified",
"location",
"max-forwards",
"proxy-authorization",
"referer",
"retry-after",
"user-agent"
]);
var parseHeaders_default = (rawHeaders) => {
const parsed = {};
let key;
let val;
let i;
rawHeaders && rawHeaders.split("\n").forEach(function parser(line) {
i = line.indexOf(":");
key = line.substring(0, i).trim().toLowerCase();
val = line.substring(i + 1).trim();
if (!key || parsed[key] && ignoreDuplicateOf[key]) {
return;
}
if (key === "set-cookie") {
if (parsed[key]) {
parsed[key].push(val);
} else {
parsed[key] = [val];
}
} else {
parsed[key] = parsed[key] ? parsed[key] + ", " + val : val;
}
});
return parsed;
};
// ../../node_modules/.pnpm/axios@1.12.0/node_modules/axios/lib/core/AxiosHeaders.js
var $internals = Symbol("internals");
function normalizeHeader(header) {
return header && String(header).trim().toLowerCase();
}
function normalizeValue(value) {
if (value === false || value == null) {
return value;
}
return utils_default.isArray(value) ? value.map(normalizeValue) : String(value);
}
function parseTokens(str) {
const tokens = /* @__PURE__ */ Object.create(null);
const tokensRE = /([^\s,;=]+)\s*(?:=\s*([^,;]+))?/g;
let match;
while (match = tokensRE.exec(str)) {
tokens[match[1]] = match[2];
}
return tokens;
}
var isValidHeaderName = (str) => /^[-_a-zA-Z0-9^`|~,!#$%&'*+.]+$/.test(str.trim());
function matchHeaderValue(context, value, header, filter2, isHeaderNameFilter) {
if (utils_default.isFunction(filter2)) {
return filter2.call(this, value, header);
}
if (isHeaderNameFilter) {
value = header;
}
if (!utils_default.isString(value)) return;
if (utils_default.isString(filter2)) {
return value.indexOf(filter2) !== -1;
}
if (utils_default.isRegExp(filter2)) {
return filter2.test(value);
}
}
function formatHeader(header) {
return header.trim().toLowerCase().replace(/([a-z\d])(\w*)/g, (w, char, str) => {
return char.toUpperCase() + str;
});
}
function buildAccessors(obj, header) {
const accessorName = utils_default.toCamelCase(" " + header);
["get", "set", "has"].forEach((methodName) => {
Object.defineProperty(obj, methodName + accessorName, {
value: function(arg1, arg2, arg3) {
return this[methodName].call(this, header, arg1, arg2, arg3);
},
configurable: true
});
});
}
var AxiosHeaders = class {
constructor(headers) {
headers && this.set(headers);
}
set(header, valueOrRewrite, rewrite) {
const self2 = this;
function setHeader(_value, _header, _rewrite) {
const lHeader = normalizeHeader(_header);
if (!lHeader) {
throw new Error("header name must be a non-empty string");
}
const key = utils_default.findKey(self2, lHeader);
if (!key || self2[key] === void 0 || _rewrite === true || _rewrite === void 0 && self2[key] !== false) {
self2[key || _header] = normalizeValue(_value);
}
}
const setHeaders = (headers, _rewrite) => utils_default.forEach(headers, (_value, _header) => setHeader(_value, _header, _rewrite));
if (utils_default.isPlainObject(header) || header instanceof this.constructor) {
setHeaders(header, valueOrRewrite);
} else if (utils_default.isString(header) && (header = header.trim()) && !isValidHeaderName(header)) {
setHeaders(parseHeaders_default(header), valueOrRewrite);
} else if (utils_default.isObject(header) && utils_default.isIterable(header)) {
let obj = {}, dest, key;
for (const entry of header) {
if (!utils_default.isArray(entry)) {
throw TypeError("Object iterator must return a key-value pair");
}
obj[key = entry[0]] = (dest = obj[key]) ? utils_default.isArray(dest) ? [...dest, entry[1]] : [dest, entry[1]] : entry[1];
}
setHeaders(obj, valueOrRewrite);
} else {
header != null && setHeader(valueOrRewrite, header, rewrite);
}
return this;
}
get(header, parser) {
header = normalizeHeader(header);
if (header) {
const key = utils_default.findKey(this, header);
if (key) {
const value = this[key];
if (!parser) {
return value;
}
if (parser === true) {
return parseTokens(value);
}
if (utils_default.isFunction(parser)) {
return parser.call(this, value, key);
}
if (utils_default.isRegExp(parser)) {
return parser.exec(value);
}
throw new TypeError("parser must be boolean|regexp|function");
}
}
}
has(header, matcher) {
header = normalizeHeader(header);
if (header) {
const key = utils_default.findKey(this, header);
return !!(key && this[key] !== void 0 && (!matcher || matchHeaderValue(this, this[key], key, matcher)));
}
return false;
}
delete(header, matcher) {
const self2 = this;
let deleted = false;
function deleteHeader(_header) {
_header = normalizeHeader(_header);
if (_header) {
const key = utils_default.findKey(self2, _header);
if (key && (!matcher || matchHeaderValue(self2, self2[key], key, matcher))) {
delete self2[key];
deleted = true;
}
}
}
if (utils_default.isArray(header)) {
header.forEach(deleteHeader);
} else {
deleteHeader(header);
}
return deleted;
}
clear(matcher) {
const keys = Object.keys(this);
let i = keys.length;
let deleted = false;
while (i--) {
const key = keys[i];
if (!matcher || matchHeaderValue(this, this[key], key, matcher, true)) {
delete this[key];
deleted = true;
}
}
return deleted;
}
normalize(format) {
const self2 = this;
const headers = {};
utils_default.forEach(this, (value, header) => {
const key = utils_default.findKey(headers, header);
if (key) {
self2[key] = normalizeValue(value);
delete self2[header];
return;
}
const normalized = format ? formatHeader(header) : String(header).trim();
if (normalized !== header) {
delete self2[header];
}
self2[normalized] = normalizeValue(value);
headers[normalized] = true;
});
return this;
}
concat(...targets) {
return this.constructor.concat(this, ...targets);
}
toJSON(asStrings) {
const obj = /* @__PURE__ */ Object.create(null);
utils_default.forEach(this, (value, header) => {
value != null && value !== false && (obj[header] = asStrings && utils_default.isArray(value) ? value.join(", ") : value);
});
return obj;
}
[Symbol.iterator]() {
return Object.entries(this.toJSON())[Symbol.iterator]();
}
toString() {
return Object.entries(this.toJSON()).map(([header, value]) => header + ": " + value).join("\n");
}
getSetCookie() {
return this.get("set-cookie") || [];
}
get [Symbol.toStringTag]() {
return "AxiosHeaders";
}
static from(thing) {
return thing instanceof this ? thing : new this(thing);
}
static concat(first, ...targets) {
const computed = new this(first);
targets.forEach((target) => computed.set(target));
return computed;
}
static accessor(header) {
const internals = this[$internals] = this[$internals] = {
accessors: {}
};
const accessors = internals.accessors;
const prototype3 = this.prototype;
function defineAccessor(_header) {
const lHeader = normalizeHeader(_header);
if (!accessors[lHeader]) {
buildAccessors(prototype3, _header);
accessors[lHeader] = true;
}
}
utils_default.isArray(header) ? header.forEach(defineAccessor) : defineAccessor(header);
return this;
}
};
AxiosHeaders.accessor(["Content-Type", "Content-Length", "Accept", "Accept-Encoding", "User-Agent", "Authorization"]);
utils_default.reduceDescriptors(AxiosHeaders.prototype, ({ value }, key) => {
let mapped = key[0].toUpperCase() + key.slice(1);
return {
get: () => value,
set(headerValue) {
this[mapped] = headerValue;
}
};
});
utils_default.freezeMethods(AxiosHeaders);
var AxiosHeaders_default = AxiosHeaders;
// ../../node_modules/.pnpm/axios@1.12.0/node_modules/axios/lib/core/transformData.js
function transformData(fns, response) {
const config = this || defaults_default;
const context = response || config;
const headers = AxiosHeaders_default.from(context.headers);
let data = context.data;
utils_default.forEach(fns, function transform(fn) {
data = fn.call(config, data, headers.normalize(), response ? response.status : void 0);
});
headers.normalize();
return data;
}
// ../../node_modules/.pnpm/axios@1.12.0/node_modules/axios/lib/cancel/isCancel.js
init_process();
function isCancel(value) {
return !!(value && value.__CANCEL__);
}
// ../../node_modules/.pnpm/axios@1.12.0/node_modules/axios/lib/cancel/CanceledError.js
init_process();
function CanceledError(message, config, request) {
AxiosError_default.call(this, message == null ? "canceled" : message, AxiosError_default.ERR_CANCELED, config, request);
this.name = "CanceledError";
}
utils_default.inherits(CanceledError, AxiosError_default, {
__CANCEL__: true
});
var CanceledError_default = CanceledError;
// ../../node_modules/.pnpm/axios@1.12.0/node_modules/axios/lib/adapters/adapters.js
init_process();
// ../../node_modules/.pnpm/axios@1.12.0/node_modules/axios/lib/adapters/xhr.js
init_process();
// ../../node_modules/.pnpm/axios@1.12.0/node_modules/axios/lib/core/settle.js
init_process();
function settle(resolve, reject, response) {
const validateStatus2 = response.config.validateStatus;
if (!response.status || !validateStatus2 || validateStatus2(response.status)) {
resolve(response);
} else {
reject(new AxiosError_default(
"Request failed with status code " + response.status,
[AxiosError_default.ERR_BAD_REQUEST, AxiosError_default.ERR_BAD_RESPONSE][Math.floor(response.status / 100) - 4],
response.config,
response.request,
response
));
}
}
// ../../node_modules/.pnpm/axios@1.12.0/node_modules/axios/lib/helpers/parseProtocol.js
init_process();
function parseProtocol(url) {
const match = /^([-+\w]{1,25})(:?\/\/|:)/.exec(url);
return match && match[1] || "";
}
// ../../node_modules/.pnpm/axios@1.12.0/node_modules/axios/lib/helpers/progressEventReducer.js
init_process();
// ../../node_modules/.pnpm/axios@1.12.0/node_modules/axios/lib/helpers/speedometer.js
init_process();
function speedometer(samplesCount, min) {
samplesCount = samplesCount || 10;
const bytes = new Array(samplesCount);
const timestamps = new Array(samplesCount);
let head = 0;
let tail = 0;
let firstSampleTS;
min = min !== void 0 ? min : 1e3;
return function push(chunkLength) {
const now = Date.now();
const startedAt = timestamps[tail];
if (!firstSampleTS) {
firstSampleTS = now;
}
bytes[head] = chunkLength;
timestamps[head] = now;
let i = tail;
let bytesCount = 0;
while (i !== head) {
bytesCount += bytes[i++];
i = i % samplesCount;
}
head = (head + 1) % samplesCount;
if (head === tail) {
tail = (tail + 1) % samplesCount;
}
if (now - firstSampleTS < min) {
return;
}
const passed = startedAt && now - startedAt;
return passed ? Math.round(bytesCount * 1e3 / passed) : void 0;
};
}
var speedometer_default = speedometer;
// ../../node_modules/.pnpm/axios@1.12.0/node_modules/axios/lib/helpers/throttle.js
init_process();
function throttle(fn, freq) {
let timestamp = 0;
let threshold = 1e3 / freq;
let lastArgs;
let timer;
const invoke = (args, now = Date.now()) => {
timestamp = now;
lastArgs = null;
if (timer) {
clearTimeout(timer);
timer = null;
}
fn(...args);
};
const throttled = (...args) => {
const now = Date.now();
const passed = now - timestamp;
if (passed >= threshold) {
invoke(args, now);
} else {
lastArgs = args;
if (!timer) {
timer = setTimeout(() => {
timer = null;
invoke(lastArgs);
}, threshold - passed);
}
}
};
const flush = () => lastArgs && invoke(lastArgs);
return [throttled, flush];
}
var throttle_default = throttle;
// ../../node_modules/.pnpm/axios@1.12.0/node_modules/axios/lib/helpers/progressEventReducer.js
var progressEventReducer = (listener, isDownloadStream, freq = 3) => {
let bytesNotified = 0;
const _speedometer = speedometer_default(50, 250);
return throttle_default((e2) => {
const loaded = e2.loaded;
const total = e2.lengthComputable ? e2.total : void 0;
const progressBytes = loaded - bytesNotified;
const rate = _speedometer(progressBytes);
const inRange = loaded <= total;
bytesNotified = loaded;
const data = {
loaded,
total,
progress: total ? loaded / total : void 0,
bytes: progressBytes,
rate: rate ? rate : void 0,
estimated: rate && total && inRange ? (total - loaded) / rate : void 0,
event: e2,
lengthComputable: total != null,
[isDownloadStream ? "download" : "upload"]: true
};
listener(data);
}, freq);
};
var progressEventDecorator = (total, throttled) => {
const lengthComputable = total != null;
return [(loaded) => throttled[0]({
lengthComputable,
total,
loaded
}), throttled[1]];
};
var asyncDecorator = (fn) => (...args) => utils_default.asap(() => fn(...args));
// ../../node_modules/.pnpm/axios@1.12.0/node_modules/axios/lib/helpers/resolveConfig.js
init_process();
// ../../node_modules/.pnpm/axios@1.12.0/node_modules/axios/lib/helpers/isURLSameOrigin.js
init_process();
var isURLSameOrigin_default = platform_default.hasStandardBrowserEnv ? /* @__PURE__ */ ((origin2, isMSIE) => (url) => {
url = new URL(url, platform_default.origin);
return origin2.protocol === url.protocol && origin2.host === url.host && (isMSIE || origin2.port === url.port);
})(
new URL(platform_default.origin),
platform_default.navigator && /(msie|trident)/i.test(platform_default.navigator.userAgent)
) : () => true;
// ../../node_modules/.pnpm/axios@1.12.0/node_modules/axios/lib/helpers/cookies.js
init_process();
var cookies_default = platform_default.hasStandardBrowserEnv ? (
// Standard browser envs support document.cookie
{
write(name, value, expires, path, domain, secure) {
const cookie = [name + "=" + encodeURIComponent(value)];
utils_default.isNumber(expires) && cookie.push("expires=" + new Date(expires).toGMTString());
utils_default.isString(path) && cookie.push("path=" + path);
utils_default.isString(domain) && cookie.push("domain=" + domain);
secure === true && cookie.push("secure");
document.cookie = cookie.join("; ");
},
read(name) {
const match = document.cookie.match(new RegExp("(^|;\\s*)(" + name + ")=([^;]*)"));
return match ? decodeURIComponent(match[3]) : null;
},
remove(name) {
this.write(name, "", Date.now() - 864e5);
}
}
) : (
// Non-standard browser env (web workers, react-native) lack needed support.
{
write() {
},
read() {
return null;
},
remove() {
}
}
);
// ../../node_modules/.pnpm/axios@1.12.0/node_modules/axios/lib/core/buildFullPath.js
init_process();
// ../../node_modules/.pnpm/axios@1.12.0/node_modules/axios/lib/helpers/isAbsoluteURL.js
init_process();
function isAbsoluteURL(url) {
return /^([a-z][a-z\d+\-.]*:)?\/\//i.test(url);
}
// ../../node_modules/.pnpm/axios@1.12.0/node_modules/axios/lib/helpers/combineURLs.js
init_process();
function combineURLs(baseURL, relativeURL) {
return relativeURL ? baseURL.replace(/\/?\/$/, "") + "/" + relativeURL.replace(/^\/+/, "") : baseURL;
}
// ../../node_modules/.pnpm/axios@1.12.0/node_modules/axios/lib/core/buildFullPath.js
function buildFullPath(baseURL, requestedURL, allowAbsoluteUrls) {
let isRelativeUrl = !isAbsoluteURL(requestedURL);
if (baseURL && (isRelativeUrl || allowAbsoluteUrls == false)) {
return combineURLs(baseURL, requestedURL);
}
return requestedURL;
}
// ../../node_modules/.pnpm/axios@1.12.0/node_modules/axios/lib/core/mergeConfig.js
init_process();
var headersToObject = (thing) => thing instanceof AxiosHeaders_default ? __spreadValues({}, thing) : thing;
function mergeConfig(config1, config2) {
config2 = config2 || {};
const config = {};
function getMergedValue(target, source, prop, caseless) {
if (utils_default.isPlainObject(target) && utils_default.isPlainObject(source)) {
return utils_default.merge.call({ caseless }, target, source);
} else if (utils_default.isPlainObject(source)) {
return utils_default.merge({}, source);
} else if (utils_default.isArray(source)) {
return source.slice();
}
return source;
}
function mergeDeepProperties(a, b, prop, caseless) {
if (!utils_default.isUndefined(b)) {
return getMergedValue(a, b, prop, caseless);
} else if (!utils_default.isUndefined(a)) {
return getMergedValue(void 0, a, prop, caseless);
}
}
function valueFromConfig2(a, b) {
if (!utils_default.isUndefined(b)) {
return getMergedValue(void 0, b);
}
}
function defaultToConfig2(a, b) {
if (!utils_default.isUndefined(b)) {
return getMergedValue(void 0, b);
} else if (!utils_default.isUndefined(a)) {
return getMergedValue(void 0, a);
}
}
function mergeDirectKeys(a, b, prop) {
if (prop in config2) {
return getMergedValue(a, b);
} else if (prop in config1) {
return getMergedValue(void 0, a);
}
}
const mergeMap = {
url: valueFromConfig2,
method: valueFromConfig2,
data: valueFromConfig2,
baseURL: defaultToConfig2,
transformRequest: defaultToConfig2,
transformResponse: defaultToConfig2,
paramsSerializer: defaultToConfig2,
timeout: defaultToConfig2,
timeoutMessage: defaultToConfig2,
withCredentials: defaultToConfig2,
withXSRFToken: defaultToConfig2,
adapter: defaultToConfig2,
responseType: defaultToConfig2,
xsrfCookieName: defaultToConfig2,
xsrfHeaderName: defaultToConfig2,
onUploadProgress: defaultToConfig2,
onDownloadProgress: defaultToConfig2,
decompress: defaultToConfig2,
maxContentLength: defaultToConfig2,
maxBodyLength: defaultToConfig2,
beforeRedirect: defaultToConfig2,
transport: defaultToConfig2,
httpAgent: defaultToConfig2,
httpsAgent: defaultToConfig2,
cancelToken: defaultToConfig2,
socketPath: defaultToConfig2,
responseEncoding: defaultToConfig2,
validateStatus: mergeDirectKeys,
headers: (a, b, prop) => mergeDeepProperties(headersToObject(a), headersToObject(b), prop, true)
};
utils_default.forEach(Object.keys(__spreadValues(__spreadValues({}, config1), config2)), function computeConfigValue(prop) {
const merge2 = mergeMap[prop] || mergeDeepProperties;
const configValue = merge2(config1[prop], config2[prop], prop);
utils_default.isUndefined(configValue) && merge2 !== mergeDirectKeys || (config[prop] = configValue);
});
return config;
}
// ../../node_modules/.pnpm/axios@1.12.0/node_modules/axios/lib/helpers/resolveConfig.js
var resolveConfig_default = (config) => {
const newConfig = mergeConfig({}, config);
let { data, withXSRFToken, xsrfHeaderName, xsrfCookieName, headers, auth } = newConfig;
newConfig.headers = headers = AxiosHeaders_default.from(headers);
newConfig.url = buildURL(buildFullPath(newConfig.baseURL, newConfig.url, newConfig.allowAbsoluteUrls), config.params, config.paramsSerializer);
if (auth) {
headers.set(
"Authorization",
"Basic " + btoa((auth.username || "") + ":" + (auth.password ? unescape(encodeURIComponent(auth.password)) : ""))
);
}
if (utils_default.isFormData(data)) {
if (platform_default.hasStandardBrowserEnv || platform_default.hasStandardBrowserWebWorkerEnv) {
headers.setContentType(void 0);
} else if (utils_default.isFunction(data.getHeaders)) {
const formHeaders = data.getHeaders();
const allowedHeaders = ["content-type", "content-length"];
Object.entries(formHeaders).forEach(([key, val]) => {
if (allowedHeaders.includes(key.toLowerCase())) {
headers.set(key, val);
}
});
}
}
if (platform_default.hasStandardBrowserEnv) {
withXSRFToken && utils_default.isFunction(withXSRFToken) && (withXSRFToken = withXSRFToken(newConfig));
if (withXSRFToken || withXSRFToken !== false && isURLSameOrigin_default(newConfig.url)) {
const xsrfValue = xsrfHeaderName && xsrfCookieName && cookies_default.read(xsrfCookieName);
if (xsrfValue) {
headers.set(xsrfHeaderName, xsrfValue);
}
}
}
return newConfig;
};
// ../../node_modules/.pnpm/axios@1.12.0/node_modules/axios/lib/adapters/xhr.js
var isXHRAdapterSupported = typeof XMLHttpRequest !== "undefined";
var xhr_default = isXHRAdapterSupported && function(config) {
return new Promise(function dispatchXhrRequest(resolve, reject) {
const _config = resolveConfig_default(config);
let requestData = _config.data;
const requestHeaders = AxiosHeaders_default.from(_config.headers).normalize();
let { responseType, onUploadProgress, onDownloadProgress } = _config;
let onCanceled;
let uploadThrottled, downloadThrottled;
let flushUpload, flushDownload;
function done() {
flushUpload && flushUpload();
flushDownload && flushDownload();
_config.cancelToken && _config.cancelToken.unsubscribe(onCanceled);
_config.signal && _config.signal.removeEventListener("abort", onCanceled);
}
let request = new XMLHttpRequest();
request.open(_config.method.toUpperCase(), _config.url, true);
request.timeout = _config.timeout;
function onloadend() {
if (!request) {
return;
}
const responseHeaders = AxiosHeaders_default.from(
"getAllResponseHeaders" in request && request.getAllResponseHeaders()
);
const responseData = !responseType || responseType === "text" || responseType === "json" ? request.responseText : request.response;
const response = {
data: responseData,
status: request.status,
statusText: request.statusText,
headers: responseHeaders,
config,
request
};
settle(function _resolve(value) {
resolve(value);
done();
}, function _reject(err) {
reject(err);
done();
}, response);
request = null;
}
if ("onloadend" in request) {
request.onloadend = onloadend;
} else {
request.onreadystatechange = function handleLoad() {
if (!request || request.readyState !== 4) {
return;
}
if (request.status === 0 && !(request.responseURL && request.responseURL.indexOf("file:") === 0)) {
return;
}
setTimeout(onloadend);
};
}
request.onabort = function handleAbort() {
if (!request) {
return;
}
reject(new AxiosError_default("Request aborted", AxiosError_default.ECONNABORTED, config, request));
request = null;
};
request.onerror = function handleError(event) {
const msg = event && event.message ? event.message : "Network Error";
const err = new AxiosError_default(msg, AxiosError_default.ERR_NETWORK, config, request);
err.event = event || null;
reject(err);
request = null;
};
request.ontimeout = function handleTimeout() {
let timeoutErrorMessage = _config.timeout ? "timeout of " + _config.timeout + "ms exceeded" : "timeout exceeded";
const transitional2 = _config.transitional || transitional_default;
if (_config.timeoutErrorMessage) {
timeoutErrorMessage = _config.timeoutErrorMessage;
}
reject(new AxiosError_default(
timeoutErrorMessage,
transitional2.clarifyTimeoutError ? AxiosError_default.ETIMEDOUT : AxiosError_default.ECONNABORTED,
config,
request
));
request = null;
};
requestData === void 0 && requestHeaders.setContentType(null);
if ("setRequestHeader" in request) {
utils_default.forEach(requestHeaders.toJSON(), function setRequestHeader(val, key) {
request.setRequestHeader(key, val);
});
}
if (!utils_default.isUndefined(_config.withCredentials)) {
request.withCredentials = !!_config.withCredentials;
}
if (responseType && responseType !== "json") {
request.responseType = _config.responseType;
}
if (onDownloadProgress) {
[downloadThrottled, flushDownload] = progressEventReducer(onDownloadProgress, true);
request.addEventListener("progress", downloadThrottled);
}
if (onUploadProgress && request.upload) {
[uploadThrottled, flushUpload] = progressEventReducer(onUploadProgress);
request.upload.addEventListener("progress", uploadThrottled);
request.upload.addEventListener("loadend", flushUpload);
}
if (_config.cancelToken || _config.signal) {
onCanceled = (cancel) => {
if (!request) {
return;
}
reject(!cancel || cancel.type ? new CanceledError_default(null, config, request) : cancel);
request.abort();
request = null;
};
_config.cancelToken && _config.cancelToken.subscribe(onCanceled);
if (_config.signal) {
_config.signal.aborted ? onCanceled() : _config.signal.addEventListener("abort", onCanceled);
}
}
const protocol = parseProtocol(_config.url);
if (protocol && platform_default.protocols.indexOf(protocol) === -1) {
reject(new AxiosError_default("Unsupported protocol " + protocol + ":", AxiosError_default.ERR_BAD_REQUEST, config));
return;
}
request.send(requestData || null);
});
};
// ../../node_modules/.pnpm/axios@1.12.0/node_modules/axios/lib/adapters/fetch.js
init_process();
// ../../node_modules/.pnpm/axios@1.12.0/node_modules/axios/lib/helpers/composeSignals.js
init_process();
var composeSignals = (signals, timeout) => {
const { length } = signals = signals ? signals.filter(Boolean) : [];
if (timeout || length) {
let controller = new AbortController();
let aborted;
const onabort = function(reason) {
if (!aborted) {
aborted = true;
unsubscribe();
const err = reason instanceof Error ? reason : this.reason;
controller.abort(err instanceof AxiosError_default ? err : new CanceledError_default(err instanceof Error ? err.message : err));
}
};
let timer = timeout && setTimeout(() => {
timer = null;
onabort(new AxiosError_default(`timeout ${timeout} of ms exceeded`, AxiosError_default.ETIMEDOUT));
}, timeout);
const unsubscribe = () => {
if (signals) {
timer && clearTimeout(timer);
timer = null;
signals.forEach((signal2) => {
signal2.unsubscribe ? signal2.unsubscribe(onabort) : signal2.removeEventListener("abort", onabort);
});
signals = null;
}
};
signals.forEach((signal2) => signal2.addEventListener("abort", onabort));
const { signal } = controller;
signal.unsubscribe = () => utils_default.asap(unsubscribe);
return signal;
}
};
var composeSignals_default = composeSignals;
// ../../node_modules/.pnpm/axios@1.12.0/node_modules/axios/lib/helpers/trackStream.js
init_process();
var streamChunk = function* (chunk, chunkSize) {
let len = chunk.byteLength;
if (!chunkSize || len < chunkSize) {
yield chunk;
return;
}
let pos = 0;
let end;
while (pos < len) {
end = pos + chunkSize;
yield chunk.slice(pos, end);
pos = end;
}
};
var readBytes = function(iterable, chunkSize) {
return __asyncGenerator(this, null, function* () {
try {
for (var iter = __forAwait(readStream(iterable)), more, temp, error; more = !(temp = yield new __await(iter.next())).done; more = false) {
const chunk = temp.value;
yield* __yieldStar(streamChunk(chunk, chunkSize));
}
} catch (temp) {
error = [temp];
} finally {
try {
more && (temp = iter.return) && (yield new __await(temp.call(iter)));
} finally {
if (error)
throw error[0];
}
}
});
};
var readStream = function(stream) {
return __asyncGenerator(this, null, function* () {
if (stream[Symbol.asyncIterator]) {
yield* __yieldStar(stream);
return;
}
const reader = stream.getReader();
try {
for (; ; ) {
const { done, value } = yield new __await(reader.read());
if (done) {
break;
}
yield value;
}
} finally {
yield new __await(reader.cancel());
}
});
};
var trackStream = (stream, chunkSize, onProgress, onFinish) => {
const iterator2 = readBytes(stream, chunkSize);
let bytes = 0;
let done;
let _onFinish = (e2) => {
if (!done) {
done = true;
onFinish && onFinish(e2);
}
};
return new ReadableStream({
pull(controller) {
return __async(this, null, function* () {
try {
const { done: done2, value } = yield iterator2.next();
if (done2) {
_onFinish();
controller.close();
return;
}
let len = value.byteLength;
if (onProgress) {
let loadedBytes = bytes += len;
onProgress(loadedBytes);
}
controller.enqueue(new Uint8Array(value));
} catch (err) {
_onFinish(err);
throw err;
}
});
},
cancel(reason) {
_onFinish(reason);
return iterator2.return();
}
}, {
highWaterMark: 2
});
};
// ../../node_modules/.pnpm/axios@1.12.0/node_modules/axios/lib/adapters/fetch.js
var DEFAULT_CHUNK_SIZE = 64 * 1024;
var { isFunction: isFunction2 } = utils_default;
var globalFetchAPI = (({ fetch, Request, Response }) => ({
fetch,
Request,
Response
}))(utils_default.global);
var {
ReadableStream: ReadableStream2,
TextEncoder
} = utils_default.global;
var test = (fn, ...args) => {
try {
return !!fn(...args);
} catch (e2) {
return false;
}
};
var factory = (env) => {
const { fetch, Request, Response } = Object.assign({}, globalFetchAPI, env);
const isFetchSupported = isFunction2(fetch);
const isRequestSupported = isFunction2(Request);
const isResponseSupported = isFunction2(Response);
if (!isFetchSupported) {
return false;
}
const isReadableStreamSupported = isFetchSupported && isFunction2(ReadableStream2);
const encodeText = isFetchSupported && (typeof TextEncoder === "function" ? /* @__PURE__ */ ((encoder) => (str) => encoder.encode(str))(new TextEncoder()) : (str) => __async(null, null, function* () {
return new Uint8Array(yield new Request(str).arrayBuffer());
}));
const supportsRequestStream = isRequestSupported && isReadableStreamSupported && test(() => {
let duplexAccessed = false;
const hasContentType = new Request(platform_default.origin, {
body: new ReadableStream2(),
method: "POST",
get duplex() {
duplexAccessed = true;
return "half";
}
}).headers.has("Content-Type");
return duplexAccessed && !hasContentType;
});
const supportsResponseStream = isResponseSupported && isReadableStreamSupported && test(() => utils_default.isReadableStream(new Response("").body));
const resolvers = {
stream: supportsResponseStream && ((res) => res.body)
};
isFetchSupported && (() => {
["text", "arrayBuffer", "blob", "formData", "stream"].forEach((type) => {
!resolvers[type] && (resolvers[type] = (res, config) => {
let method = res && res[type];
if (method) {
return method.call(res);
}
throw new AxiosError_default(`Response type '${type}' is not supported`, AxiosError_default.ERR_NOT_SUPPORT, config);
});
});
})();
const getBodyLength = (body) => __async(null, null, function* () {
if (body == null) {
return 0;
}
if (utils_default.isBlob(body)) {
return body.size;
}
if (utils_default.isSpecCompliantForm(body)) {
const _request = new Request(platform_default.origin, {
method: "POST",
body
});
return (yield _request.arrayBuffer()).byteLength;
}
if (utils_default.isArrayBufferView(body) || utils_default.isArrayBuffer(body)) {
return body.byteLength;
}
if (utils_default.isURLSearchParams(body)) {
body = body + "";
}
if (utils_default.isString(body)) {
return (yield encodeText(body)).byteLength;
}
});
const resolveBodyLength = (headers, body) => __async(null, null, function* () {
const length = utils_default.toFiniteNumber(headers.getContentLength());
return length == null ? getBodyLength(body) : length;
});
return (config) => __async(null, null, function* () {
let {
url,
method,
data,
signal,
cancelToken,
timeout,
onDownloadProgress,
onUploadProgress,
responseType,
headers,
withCredentials = "same-origin",
fetchOptions
} = resolveConfig_default(config);
responseType = responseType ? (responseType + "").toLowerCase() : "text";
let composedSignal = composeSignals_default([signal, cancelToken && cancelToken.toAbortSignal()], timeout);
let request = null;
const unsubscribe = composedSignal && composedSignal.unsubscribe && (() => {
composedSignal.unsubscribe();
});
let requestContentLength;
try {
if (onUploadProgress && supportsRequestStream && method !== "get" && method !== "head" && (requestContentLength = yield resolveBodyLength(headers, data)) !== 0) {
let _request = new Request(url, {
method: "POST",
body: data,
duplex: "half"
});
let contentTypeHeader;
if (utils_default.isFormData(data) && (contentTypeHeader = _request.headers.get("content-type"))) {
headers.setContentType(contentTypeHeader);
}
if (_request.body) {
const [onProgress, flush] = progressEventDecorator(
requestContentLength,
progressEventReducer(asyncDecorator(onUploadProgress))
);
data = trackStream(_request.body, DEFAULT_CHUNK_SIZE, onProgress, flush);
}
}
if (!utils_default.isString(withCredentials)) {
withCredentials = withCredentials ? "include" : "omit";
}
const isCredentialsSupported = isRequestSupported && "credentials" in Request.prototype;
const resolvedOptions = __spreadProps(__spreadValues({}, fetchOptions), {
signal: composedSignal,
method: method.toUpperCase(),
headers: headers.normalize().toJSON(),
body: data,
duplex: "half",
credentials: isCredentialsSupported ? withCredentials : void 0
});
request = isRequestSupported && new Request(url, resolvedOptions);
let response = yield isRequestSupported ? fetch(request, fetchOptions) : fetch(url, resolvedOptions);
const isStreamResponse = supportsResponseStream && (responseType === "stream" || responseType === "response");
if (supportsResponseStream && (onDownloadProgress || isStreamResponse && unsubscribe)) {
const options = {};
["status", "statusText", "headers"].forEach((prop) => {
options[prop] = response[prop];
});
const responseContentLength = utils_default.toFiniteNumber(response.headers.get("content-length"));
const [onProgress, flush] = onDownloadProgress && progressEventDecorator(
responseContentLength,
progressEventReducer(asyncDecorator(onDownloadProgress), true)
) || [];
response = new Response(
trackStream(response.body, DEFAULT_CHUNK_SIZE, onProgress, () => {
flush && flush();
unsubscribe && unsubscribe();
}),
options
);
}
responseType = responseType || "text";
let responseData = yield resolvers[utils_default.findKey(resolvers, responseType) || "text"](response, config);
!isStreamResponse && unsubscribe && unsubscribe();
return yield new Promise((resolve, reject) => {
settle(resolve, reject, {
data: responseData,
headers: AxiosHeaders_default.from(response.headers),
status: response.status,
statusText: response.statusText,
config,
request
});
});
} catch (err) {
unsubscribe && unsubscribe();
if (err && err.name === "TypeError" && /Load failed|fetch/i.test(err.message)) {
throw Object.assign(
new AxiosError_default("Network Error", AxiosError_default.ERR_NETWORK, config, request),
{
cause: err.cause || err
}
);
}
throw AxiosError_default.from(err, err && err.code, config, request);
}
});
};
var seedCache = /* @__PURE__ */ new Map();
var getFetch = (config) => {
let env = utils_default.merge.call({
skipUndefined: true
}, globalFetchAPI, config ? config.env : null);
const { fetch, Request, Response } = env;
const seeds = [
Request,
Response,
fetch
];
let len = seeds.length, i = len, seed, target, map = seedCache;
while (i--) {
seed = seeds[i];
target = map.get(seed);
target === void 0 && map.set(seed, target = i ? /* @__PURE__ */ new Map() : factory(env));
map = target;
}
return target;
};
var adapter = getFetch();
// ../../node_modules/.pnpm/axios@1.12.0/node_modules/axios/lib/adapters/adapters.js
var knownAdapters = {
http: null_default,
xhr: xhr_default,
fetch: {
get: getFetch
}
};
utils_default.forEach(knownAdapters, (fn, value) => {
if (fn) {
try {
Object.defineProperty(fn, "name", { value });
} catch (e2) {
}
Object.defineProperty(fn, "adapterName", { value });
}
});
var renderReason = (reason) => `- ${reason}`;
var isResolvedHandle = (adapter2) => utils_default.isFunction(adapter2) || adapter2 === null || adapter2 === false;
var adapters_default = {
getAdapter: (adapters, config) => {
adapters = utils_default.isArray(adapters) ? adapters : [adapters];
const { length } = adapters;
let nameOrAdapter;
let adapter2;
const rejectedReasons = {};
for (let i = 0; i < length; i++) {
nameOrAdapter = adapters[i];
let id;
adapter2 = nameOrAdapter;
if (!isResolvedHandle(nameOrAdapter)) {
adapter2 = knownAdapters[(id = String(nameOrAdapter)).toLowerCase()];
if (adapter2 === void 0) {
throw new AxiosError_default(`Unknown adapter '${id}'`);
}
}
if (adapter2 && (utils_default.isFunction(adapter2) || (adapter2 = adapter2.get(config)))) {
break;
}
rejectedReasons[id || "#" + i] = adapter2;
}
if (!adapter2) {
const reasons = Object.entries(rejectedReasons).map(
([id, state]) => `adapter ${id} ` + (state === false ? "is not supported by the environment" : "is not available in the build")
);
let s = length ? reasons.length > 1 ? "since :\n" + reasons.map(renderReason).join("\n") : " " + renderReason(reasons[0]) : "as no adapter specified";
throw new AxiosError_default(
`There is no suitable adapter to dispatch the request ` + s,
"ERR_NOT_SUPPORT"
);
}
return adapter2;
},
adapters: knownAdapters
};
// ../../node_modules/.pnpm/axios@1.12.0/node_modules/axios/lib/core/dispatchRequest.js
function throwIfCancellationRequested(config) {
if (config.cancelToken) {
config.cancelToken.throwIfRequested();
}
if (config.signal && config.signal.aborted) {
throw new CanceledError_default(null, config);
}
}
function dispatchRequest(config) {
throwIfCancellationRequested(config);
config.headers = AxiosHeaders_default.from(config.headers);
config.data = transformData.call(
config,
config.transformRequest
);
if (["post", "put", "patch"].indexOf(config.method) !== -1) {
config.headers.setContentType("application/x-www-form-urlencoded", false);
}
const adapter2 = adapters_default.getAdapter(config.adapter || defaults_default.adapter, config);
return adapter2(config).then(function onAdapterResolution(response) {
throwIfCancellationRequested(config);
response.data = transformData.call(
config,
config.transformResponse,
response
);
response.headers = AxiosHeaders_default.from(response.headers);
return response;
}, function onAdapterRejection(reason) {
if (!isCancel(reason)) {
throwIfCancellationRequested(config);
if (reason && reason.response) {
reason.response.data = transformData.call(
config,
config.transformResponse,
reason.response
);
reason.response.headers = AxiosHeaders_default.from(reason.response.headers);
}
}
return Promise.reject(reason);
});
}
// ../../node_modules/.pnpm/axios@1.12.0/node_modules/axios/lib/helpers/validator.js
init_process();
// ../../node_modules/.pnpm/axios@1.12.0/node_modules/axios/lib/env/data.js
init_process();
var VERSION = "1.12.0";
// ../../node_modules/.pnpm/axios@1.12.0/node_modules/axios/lib/helpers/validator.js
var validators = {};
["object", "boolean", "number", "function", "string", "symbol"].forEach((type, i) => {
validators[type] = function validator(thing) {
return typeof thing === type || "a" + (i < 1 ? "n " : " ") + type;
};
});
var deprecatedWarnings = {};
validators.transitional = function transitional(validator, version, message) {
function formatMessage(opt, desc) {
return "[Axios v" + VERSION + "] Transitional option '" + opt + "'" + desc + (message ? ". " + message : "");
}
return (value, opt, opts) => {
if (validator === false) {
throw new AxiosError_default(
formatMessage(opt, " has been removed" + (version ? " in " + version : "")),
AxiosError_default.ERR_DEPRECATED
);
}
if (version && !deprecatedWarnings[opt]) {
deprecatedWarnings[opt] = true;
console.warn(
formatMessage(
opt,
" has been deprecated since v" + version + " and will be removed in the near future"
)
);
}
return validator ? validator(value, opt, opts) : true;
};
};
validators.spelling = function spelling(correctSpelling) {
return (value, opt) => {
console.warn(`${opt} is likely a misspelling of ${correctSpelling}`);
return true;
};
};
function assertOptions(options, schema, allowUnknown) {
if (typeof options !== "object") {
throw new AxiosError_default("options must be an object", AxiosError_default.ERR_BAD_OPTION_VALUE);
}
const keys = Object.keys(options);
let i = keys.length;
while (i-- > 0) {
const opt = keys[i];
const validator = schema[opt];
if (validator) {
const value = options[opt];
const result2 = value === void 0 || validator(value, opt, options);
if (result2 !== true) {
throw new AxiosError_default("option " + opt + " must be " + result2, AxiosError_default.ERR_BAD_OPTION_VALUE);
}
continue;
}
if (allowUnknown !== true) {
throw new AxiosError_default("Unknown option " + opt, AxiosError_default.ERR_BAD_OPTION);
}
}
}
var validator_default = {
assertOptions,
validators
};
// ../../node_modules/.pnpm/axios@1.12.0/node_modules/axios/lib/core/Axios.js
var validators2 = validator_default.validators;
var Axios = class {
constructor(instanceConfig) {
this.defaults = instanceConfig || {};
this.interceptors = {
request: new InterceptorManager_default(),
response: new InterceptorManager_default()
};
}
/**
* Dispatch a request
*
* @param {String|Object} configOrUrl The config specific for this request (merged with this.defaults)
* @param {?Object} config
*
* @returns {Promise} The Promise to be fulfilled
*/
request(configOrUrl, config) {
return __async(this, null, function* () {
try {
return yield this._request(configOrUrl, config);
} catch (err) {
if (err instanceof Error) {
let dummy = {};
Error.captureStackTrace ? Error.captureStackTrace(dummy) : dummy = new Error();
const stack = dummy.stack ? dummy.stack.replace(/^.+\n/, "") : "";
try {
if (!err.stack) {
err.stack = stack;
} else if (stack && !String(err.stack).endsWith(stack.replace(/^.+\n.+\n/, ""))) {
err.stack += "\n" + stack;
}
} catch (e2) {
}
}
throw err;
}
});
}
_request(configOrUrl, config) {
if (typeof configOrUrl === "string") {
config = config || {};
config.url = configOrUrl;
} else {
config = configOrUrl || {};
}
config = mergeConfig(this.defaults, config);
const { transitional: transitional2, paramsSerializer, headers } = config;
if (transitional2 !== void 0) {
validator_default.assertOptions(transitional2, {
silentJSONParsing: validators2.transitional(validators2.boolean),
forcedJSONParsing: validators2.transitional(validators2.boolean),
clarifyTimeoutError: validators2.transitional(validators2.boolean)
}, false);
}
if (paramsSerializer != null) {
if (utils_default.isFunction(paramsSerializer)) {
config.paramsSerializer = {
serialize: paramsSerializer
};
} else {
validator_default.assertOptions(paramsSerializer, {
encode: validators2.function,
serialize: validators2.function
}, true);
}
}
if (config.allowAbsoluteUrls !== void 0) {
} else if (this.defaults.allowAbsoluteUrls !== void 0) {
config.allowAbsoluteUrls = this.defaults.allowAbsoluteUrls;
} else {
config.allowAbsoluteUrls = true;
}
validator_default.assertOptions(config, {
baseUrl: validators2.spelling("baseURL"),
withXsrfToken: validators2.spelling("withXSRFToken")
}, true);
config.method = (config.method || this.defaults.method || "get").toLowerCase();
let contextHeaders = headers && utils_default.merge(
headers.common,
headers[config.method]
);
headers && utils_default.forEach(
["delete", "get", "head", "post", "put", "patch", "common"],
(method) => {
delete headers[method];
}
);
config.headers = AxiosHeaders_default.concat(contextHeaders, headers);
const requestInterceptorChain = [];
let synchronousRequestInterceptors = true;
this.interceptors.request.forEach(function unshiftRequestInterceptors(interceptor) {
if (typeof interceptor.runWhen === "function" && interceptor.runWhen(config) === false) {
return;
}
synchronousRequestInterceptors = synchronousRequestInterceptors && interceptor.synchronous;
requestInterceptorChain.unshift(interceptor.fulfilled, interceptor.rejected);
});
const responseInterceptorChain = [];
this.interceptors.response.forEach(function pushResponseInterceptors(interceptor) {
responseInterceptorChain.push(interceptor.fulfilled, interceptor.rejected);
});
let promise;
let i = 0;
let len;
if (!synchronousRequestInterceptors) {
const chain = [dispatchRequest.bind(this), void 0];
chain.unshift(...requestInterceptorChain);
chain.push(...responseInterceptorChain);
len = chain.length;
promise = Promise.resolve(config);
while (i < len) {
promise = promise.then(chain[i++], chain[i++]);
}
return promise;
}
len = requestInterceptorChain.length;
let newConfig = config;
i = 0;
while (i < len) {
const onFulfilled = requestInterceptorChain[i++];
const onRejected = requestInterceptorChain[i++];
try {
newConfig = onFulfilled(newConfig);
} catch (error) {
onRejected.call(this, error);
break;
}
}
try {
promise = dispatchRequest.call(this, newConfig);
} catch (error) {
return Promise.reject(error);
}
i = 0;
len = responseInterceptorChain.length;
while (i < len) {
promise = promise.then(responseInterceptorChain[i++], responseInterceptorChain[i++]);
}
return promise;
}
getUri(config) {
config = mergeConfig(this.defaults, config);
const fullPath = buildFullPath(config.baseURL, config.url, config.allowAbsoluteUrls);
return buildURL(fullPath, config.params, config.paramsSerializer);
}
};
utils_default.forEach(["delete", "get", "head", "options"], function forEachMethodNoData(method) {
Axios.prototype[method] = function(url, config) {
return this.request(mergeConfig(config || {}, {
method,
url,
data: (config || {}).data
}));
};
});
utils_default.forEach(["post", "put", "patch"], function forEachMethodWithData(method) {
function generateHTTPMethod(isForm) {
return function httpMethod(url, data, config) {
return this.request(mergeConfig(config || {}, {
method,
headers: isForm ? {
"Content-Type": "multipart/form-data"
} : {},
url,
data
}));
};
}
Axios.prototype[method] = generateHTTPMethod();
Axios.prototype[method + "Form"] = generateHTTPMethod(true);
});
var Axios_default = Axios;
// ../../node_modules/.pnpm/axios@1.12.0/node_modules/axios/lib/cancel/CancelToken.js
init_process();
var CancelToken = class _CancelToken {
constructor(executor) {
if (typeof executor !== "function") {
throw new TypeError("executor must be a function.");
}
let resolvePromise;
this.promise = new Promise(function promiseExecutor(resolve) {
resolvePromise = resolve;
});
const token = this;
this.promise.then((cancel) => {
if (!token._listeners) return;
let i = token._listeners.length;
while (i-- > 0) {
token._listeners[i](cancel);
}
token._listeners = null;
});
this.promise.then = (onfulfilled) => {
let _resolve;
const promise = new Promise((resolve) => {
token.subscribe(resolve);
_resolve = resolve;
}).then(onfulfilled);
promise.cancel = function reject() {
token.unsubscribe(_resolve);
};
return promise;
};
executor(function cancel(message, config, request) {
if (token.reason) {
return;
}
token.reason = new CanceledError_default(message, config, request);
resolvePromise(token.reason);
});
}
/**
* Throws a `CanceledError` if cancellation has been requested.
*/
throwIfRequested() {
if (this.reason) {
throw this.reason;
}
}
/**
* Subscribe to the cancel signal
*/
subscribe(listener) {
if (this.reason) {
listener(this.reason);
return;
}
if (this._listeners) {
this._listeners.push(listener);
} else {
this._listeners = [listener];
}
}
/**
* Unsubscribe from the cancel signal
*/
unsubscribe(listener) {
if (!this._listeners) {
return;
}
const index = this._listeners.indexOf(listener);
if (index !== -1) {
this._listeners.splice(index, 1);
}
}
toAbortSignal() {
const controller = new AbortController();
const abort = (err) => {
controller.abort(err);
};
this.subscribe(abort);
controller.signal.unsubscribe = () => this.unsubscribe(abort);
return controller.signal;
}
/**
* Returns an object that contains a new `CancelToken` and a function that, when called,
* cancels the `CancelToken`.
*/
static source() {
let cancel;
const token = new _CancelToken(function executor(c) {
cancel = c;
});
return {
token,
cancel
};
}
};
var CancelToken_default = CancelToken;
// ../../node_modules/.pnpm/axios@1.12.0/node_modules/axios/lib/helpers/spread.js
init_process();
function spread(callback) {
return function wrap(arr) {
return callback.apply(null, arr);
};
}
// ../../node_modules/.pnpm/axios@1.12.0/node_modules/axios/lib/helpers/isAxiosError.js
init_process();
function isAxiosError(payload) {
return utils_default.isObject(payload) && payload.isAxiosError === true;
}
// ../../node_modules/.pnpm/axios@1.12.0/node_modules/axios/lib/helpers/HttpStatusCode.js
init_process();
var HttpStatusCode = {
Continue: 100,
SwitchingProtocols: 101,
Processing: 102,
EarlyHints: 103,
Ok: 200,
Created: 201,
Accepted: 202,
NonAuthoritativeInformation: 203,
NoContent: 204,
ResetContent: 205,
PartialContent: 206,
MultiStatus: 207,
AlreadyReported: 208,
ImUsed: 226,
MultipleChoices: 300,
MovedPermanently: 301,
Found: 302,
SeeOther: 303,
NotModified: 304,
UseProxy: 305,
Unused: 306,
TemporaryRedirect: 307,
PermanentRedirect: 308,
BadRequest: 400,
Unauthorized: 401,
PaymentRequired: 402,
Forbidden: 403,
NotFound: 404,
MethodNotAllowed: 405,
NotAcceptable: 406,
ProxyAuthenticationRequired: 407,
RequestTimeout: 408,
Conflict: 409,
Gone: 410,
LengthRequired: 411,
PreconditionFailed: 412,
PayloadTooLarge: 413,
UriTooLong: 414,
UnsupportedMediaType: 415,
RangeNotSatisfiable: 416,
ExpectationFailed: 417,
ImATeapot: 418,
MisdirectedRequest: 421,
UnprocessableEntity: 422,
Locked: 423,
FailedDependency: 424,
TooEarly: 425,
UpgradeRequired: 426,
PreconditionRequired: 428,
TooManyRequests: 429,
RequestHeaderFieldsTooLarge: 431,
UnavailableForLegalReasons: 451,
InternalServerError: 500,
NotImplemented: 501,
BadGateway: 502,
ServiceUnavailable: 503,
GatewayTimeout: 504,
HttpVersionNotSupported: 505,
VariantAlsoNegotiates: 506,
InsufficientStorage: 507,
LoopDetected: 508,
NotExtended: 510,
NetworkAuthenticationRequired: 511
};
Object.entries(HttpStatusCode).forEach(([key, value]) => {
HttpStatusCode[value] = key;
});
var HttpStatusCode_default = HttpStatusCode;
// ../../node_modules/.pnpm/axios@1.12.0/node_modules/axios/lib/axios.js
function createInstance(defaultConfig) {
const context = new Axios_default(defaultConfig);
const instance = bind(Axios_default.prototype.request, context);
utils_default.extend(instance, Axios_default.prototype, context, { allOwnKeys: true });
utils_default.extend(instance, context, null, { allOwnKeys: true });
instance.create = function create(instanceConfig) {
return createInstance(mergeConfig(defaultConfig, instanceConfig));
};
return instance;
}
var axios = createInstance(defaults_default);
axios.Axios = Axios_default;
axios.CanceledError = CanceledError_default;
axios.CancelToken = CancelToken_default;
axios.isCancel = isCancel;
axios.VERSION = VERSION;
axios.toFormData = toFormData_default;
axios.AxiosError = AxiosError_default;
axios.Cancel = axios.CanceledError;
axios.all = function all(promises) {
return Promise.all(promises);
};
axios.spread = spread;
axios.isAxiosError = isAxiosError;
axios.mergeConfig = mergeConfig;
axios.AxiosHeaders = AxiosHeaders_default;
axios.formToJSON = (thing) => formDataToJSON_default(utils_default.isHTMLForm(thing) ? new FormData(thing) : thing);
axios.getAdapter = adapters_default.getAdapter;
axios.HttpStatusCode = HttpStatusCode_default;
axios.default = axios;
var axios_default = axios;
// ../../node_modules/.pnpm/axios@1.12.0/node_modules/axios/index.js
var {
Axios: Axios2,
AxiosError: AxiosError2,
CanceledError: CanceledError2,
isCancel: isCancel2,
CancelToken: CancelToken2,
VERSION: VERSION2,
all: all2,
Cancel,
isAxiosError: isAxiosError2,
spread: spread2,
toFormData: toFormData2,
AxiosHeaders: AxiosHeaders2,
HttpStatusCode: HttpStatusCode2,
formToJSON,
getAdapter,
mergeConfig: mergeConfig2
} = axios_default;
// ../common/src/http.ts
var log3 = new Logger("packages/common/src/http.ts");
var HttpClient = class {
constructor(baseURL) {
this.api = axios_default.create({ baseURL });
}
/**@throws {@link HttpResponse} */
get(url, config) {
return __async(this, null, function* () {
const res = yield this.api.get(url, config).catch((err) => err);
if (axios_default.isAxiosError(res)) {
const error = __spreadProps(__spreadValues({}, res.response), { message: res.message });
if (config == null ? void 0 : config.retry) {
const retry = yield config.retry(error);
if (retry) {
log3.warn("retry get", { url });
return this.get(url, config);
} else {
log3.warn("retry get failed", { url });
throw error;
}
}
log3.warn("response error", { error });
throw error;
} else {
return res.data;
}
});
}
/**@throws {@link HttpResponse} */
post(url, data, config) {
return __async(this, null, function* () {
var _a2, _b2, _c;
const res = yield this.api.post(url, data, config).catch((err) => err);
if (axios_default.isAxiosError(res)) {
const error = {
data: (_a2 = res.response) == null ? void 0 : _a2.data,
status: (_b2 = res.response) == null ? void 0 : _b2.status,
statusText: (_c = res.response) == null ? void 0 : _c.statusText,
message: res.message
};
log3.warn("error received", error);
if (config == null ? void 0 : config.retry) {
const needRetry = yield config.retry(error);
if (needRetry) {
log3.warn("retry post", url, { data, error, needRetry });
return this.post(url, data, config);
} else {
throw error;
}
}
throw error;
} else {
return res.data;
}
});
}
/**@throws {@link HttpResponse} */
put(url, data, config) {
return __async(this, null, function* () {
const res = yield this.api.put(url, data, config).catch((err) => err);
if (axios_default.isAxiosError(res)) {
const error = __spreadProps(__spreadValues({}, res.response), { message: res.message });
if (config == null ? void 0 : config.retry) {
const retry = yield config.retry(error);
if (retry) {
log3.warn("retry put", { url, data });
return this.put(url, data, config);
} else {
log3.warn("retry put failed", { url, data });
throw error;
}
}
log3.warn("response error", { error });
throw error;
} else {
return res.data;
}
});
}
/**@throws {@link HttpResponse} */
delete(url, config) {
return __async(this, null, function* () {
const res = yield this.api.delete(url, config).catch((err) => err);
if (axios_default.isAxiosError(res)) {
const error = __spreadProps(__spreadValues({}, res.response), { message: res.message });
if (config == null ? void 0 : config.retry) {
const retry = yield config.retry(error);
if (retry) {
log3.warn("retry delete", { url });
return this.delete(url, config);
} else {
log3.warn("retry delete failed", { url });
throw error;
}
}
log3.warn("response error", { error });
throw error;
} else {
return res.data;
}
});
}
};
// ../common/src/promise.ts
init_process();
var log4 = new Logger("packages/common/src/promise.ts");
var PromiseQueue = class {
constructor() {
this.queue = [];
this.running = false;
this.push = (promise) => new Promise((r2, f) => {
this.queue.push({ promise, done: r2, failed: f });
if (!this.running) {
this.run().catch((e2) => {
log4.error("push", e2);
});
}
});
}
run() {
return __async(this, null, function* () {
const task = this.queue.shift();
if (task) {
this.running = true;
try {
const res = yield task.promise();
task.done(res);
} catch (error) {
task.failed(error);
}
yield this.run();
} else {
this.running = false;
}
});
}
};
// ../common/src/util.ts
init_process();
var BackOff = class {
/**20.4 sec {var sum=0;for(i=0;i<=8;i++){sum +=i ** 2 * 100}} */
constructor(props = {}) {
this.count = 0;
this.times = 8;
/**ms */
this.interval = 100;
/**ms */
this.jitter = 0;
Object.assign(this, props);
}
/**if need wait return true */
wait() {
return __async(this, null, function* () {
if (this.exceeded) {
return false;
}
const timeout = this.timeout;
this.count++;
yield new Promise((r2) => setTimeout(r2, timeout));
return true;
});
}
get timeout() {
const timeout = __pow(this.count, 2) * this.interval + __pow(this.count, 2) * this.jitter * Math.random();
return timeout;
}
get exceeded() {
return this.count >= this.times;
}
reset() {
this.count = 0;
}
};
var deepCopy = (o2) => JSON.parse(JSON.stringify(o2));
// ../core/src/index.ts
init_process();
// ../token/src/index.ts
init_process();
// ../../node_modules/.pnpm/uuid@9.0.1/node_modules/uuid/dist/esm-browser/index.js
init_process();
// ../../node_modules/.pnpm/uuid@9.0.1/node_modules/uuid/dist/esm-browser/rng.js
init_process();
var getRandomValues;
var rnds8 = new Uint8Array(16);
function rng() {
if (!getRandomValues) {
getRandomValues = typeof crypto !== "undefined" && crypto.getRandomValues && crypto.getRandomValues.bind(crypto);
if (!getRandomValues) {
throw new Error("crypto.getRandomValues() not supported. See https://github.com/uuidjs/uuid#getrandomvalues-not-supported");
}
}
return getRandomValues(rnds8);
}
// ../../node_modules/.pnpm/uuid@9.0.1/node_modules/uuid/dist/esm-browser/stringify.js
init_process();
var byteToHex = [];
for (let i = 0; i < 256; ++i) {
byteToHex.push((i + 256).toString(16).slice(1));
}
function unsafeStringify(arr, offset = 0) {
return byteToHex[arr[offset + 0]] + byteToHex[arr[offset + 1]] + byteToHex[arr[offset + 2]] + byteToHex[arr[offset + 3]] + "-" + byteToHex[arr[offset + 4]] + byteToHex[arr[offset + 5]] + "-" + byteToHex[arr[offset + 6]] + byteToHex[arr[offset + 7]] + "-" + byteToHex[arr[offset + 8]] + byteToHex[arr[offset + 9]] + "-" + byteToHex[arr[offset + 10]] + byteToHex[arr[offset + 11]] + byteToHex[arr[offset + 12]] + byteToHex[arr[offset + 13]] + byteToHex[arr[offset + 14]] + byteToHex[arr[offset + 15]];
}
// ../../node_modules/.pnpm/uuid@9.0.1/node_modules/uuid/dist/esm-browser/v4.js
init_process();
// ../../node_modules/.pnpm/uuid@9.0.1/node_modules/uuid/dist/esm-browser/native.js
init_process();
var randomUUID = typeof crypto !== "undefined" && crypto.randomUUID && crypto.randomUUID.bind(crypto);
var native_default = {
randomUUID
};
// ../../node_modules/.pnpm/uuid@9.0.1/node_modules/uuid/dist/esm-browser/v4.js
function v4(options, buf, offset) {
if (native_default.randomUUID && !buf && !options) {
return native_default.randomUUID();
}
options = options || {};
const rnds = options.random || (options.rng || rng)();
rnds[6] = rnds[6] & 15 | 64;
rnds[8] = rnds[8] & 63 | 128;
if (buf) {
offset = offset || 0;
for (let i = 0; i < 16; ++i) {
buf[offset + i] = rnds[i];
}
return buf;
}
return unsafeStringify(rnds);
}
var v4_default = v4;
// ../token/src/encoder.ts
init_process();
var import_jsrsasign = __toESM(require_jsrsasign());
// ../../node_modules/.pnpm/jwt-decode@3.1.2/node_modules/jwt-decode/build/jwt-decode.esm.js
init_process();
function e(e2) {
this.message = e2;
}
e.prototype = new Error(), e.prototype.name = "InvalidCharacterError";
var r = "undefined" != typeof window && window.atob && window.atob.bind(window) || function(r2) {
var t2 = String(r2).replace(/=+$/, "");
if (t2.length % 4 == 1) throw new e("'atob' failed: The string to be decoded is not correctly encoded.");
for (var n2, o2, a = 0, i = 0, c = ""; o2 = t2.charAt(i++); ~o2 && (n2 = a % 4 ? 64 * n2 + o2 : o2, a++ % 4) ? c += String.fromCharCode(255 & n2 >> (-2 * a & 6)) : 0) o2 = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=".indexOf(o2);
return c;
};
function t(e2) {
var t2 = e2.replace(/-/g, "+").replace(/_/g, "/");
switch (t2.length % 4) {
case 0:
break;
case 2:
t2 += "==";
break;
case 3:
t2 += "=";
break;
default:
throw "Illegal base64url string!";
}
try {
return (function(e3) {
return decodeURIComponent(r(e3).replace(/(.)/g, (function(e4, r2) {
var t3 = r2.charCodeAt(0).toString(16).toUpperCase();
return t3.length < 2 && (t3 = "0" + t3), "%" + t3;
})));
})(t2);
} catch (e3) {
return r(t2);
}
}
function n(e2) {
this.message = e2;
}
function o(e2, r2) {
if ("string" != typeof e2) throw new n("Invalid token specified");
var o2 = true === (r2 = r2 || {}).header ? 0 : 1;
try {
return JSON.parse(t(e2.split(".")[o2]));
} catch (e3) {
throw new n("Invalid token specified: " + e3.message);
}
}
n.prototype = new Error(), n.prototype.name = "InvalidTokenError";
var jwt_decode_esm_default = o;
// ../../node_modules/.pnpm/zod@3.25.67/node_modules/zod/dist/esm/index.js
init_process();
// ../../node_modules/.pnpm/zod@3.25.67/node_modules/zod/dist/esm/v3/index.js
init_process();
// ../../node_modules/.pnpm/zod@3.25.67/node_modules/zod/dist/esm/v3/external.js
var external_exports = {};
__export(external_exports, {
BRAND: () => BRAND,
DIRTY: () => DIRTY,
EMPTY_PATH: () => EMPTY_PATH,
INVALID: () => INVALID,
NEVER: () => NEVER,
OK: () => OK,
ParseStatus: () => ParseStatus,
Schema: () => ZodType,
ZodAny: () => ZodAny,
ZodArray: () => ZodArray,
ZodBigInt: () => ZodBigInt,
ZodBoolean: () => ZodBoolean,
ZodBranded: () => ZodBranded,
ZodCatch: () => ZodCatch,
ZodDate: () => ZodDate,
ZodDefault: () => ZodDefault,
ZodDiscriminatedUnion: () => ZodDiscriminatedUnion,
ZodEffects: () => ZodEffects,
ZodEnum: () => ZodEnum,
ZodError: () => ZodError,
ZodFirstPartyTypeKind: () => ZodFirstPartyTypeKind,
ZodFunction: () => ZodFunction,
ZodIntersection: () => ZodIntersection,
ZodIssueCode: () => ZodIssueCode,
ZodLazy: () => ZodLazy,
ZodLiteral: () => ZodLiteral,
ZodMap: () => ZodMap,
ZodNaN: () => ZodNaN,
ZodNativeEnum: () => ZodNativeEnum,
ZodNever: () => ZodNever,
ZodNull: () => ZodNull,
ZodNullable: () => ZodNullable,
ZodNumber: () => ZodNumber,
ZodObject: () => ZodObject,
ZodOptional: () => ZodOptional,
ZodParsedType: () => ZodParsedType,
ZodPipeline: () => ZodPipeline,
ZodPromise: () => ZodPromise,
ZodReadonly: () => ZodReadonly,
ZodRecord: () => ZodRecord,
ZodSchema: () => ZodType,
ZodSet: () => ZodSet,
ZodString: () => ZodString,
ZodSymbol: () => ZodSymbol,
ZodTransformer: () => ZodEffects,
ZodTuple: () => ZodTuple,
ZodType: () => ZodType,
ZodUndefined: () => ZodUndefined,
ZodUnion: () => ZodUnion,
ZodUnknown: () => ZodUnknown,
ZodVoid: () => ZodVoid,
addIssueToContext: () => addIssueToContext,
any: () => anyType,
array: () => arrayType,
bigint: () => bigIntType,
boolean: () => booleanType,
coerce: () => coerce,
custom: () => custom,
date: () => dateType,
datetimeRegex: () => datetimeRegex,
defaultErrorMap: () => en_default,
discriminatedUnion: () => discriminatedUnionType,
effect: () => effectsType,
enum: () => enumType,
function: () => functionType,
getErrorMap: () => getErrorMap,
getParsedType: () => getParsedType,
instanceof: () => instanceOfType,
intersection: () => intersectionType,
isAborted: () => isAborted,
isAsync: () => isAsync,
isDirty: () => isDirty,
isValid: () => isValid,
late: () => late,
lazy: () => lazyType,
literal: () => literalType,
makeIssue: () => makeIssue,
map: () => mapType,
nan: () => nanType,
nativeEnum: () => nativeEnumType,
never: () => neverType,
null: () => nullType,
nullable: () => nullableType,
number: () => numberType,
object: () => objectType,
objectUtil: () => objectUtil,
oboolean: () => oboolean,
onumber: () => onumber,
optional: () => optionalType,
ostring: () => ostring,
pipeline: () => pipelineType,
preprocess: () => preprocessType,
promise: () => promiseType,
quotelessJson: () => quotelessJson,
record: () => recordType,
set: () => setType,
setErrorMap: () => setErrorMap,
strictObject: () => strictObjectType,
string: () => stringType,
symbol: () => symbolType,
transformer: () => effectsType,
tuple: () => tupleType,
undefined: () => undefinedType,
union: () => unionType,
unknown: () => unknownType,
util: () => util,
void: () => voidType
});
init_process();
// ../../node_modules/.pnpm/zod@3.25.67/node_modules/zod/dist/esm/v3/errors.js
init_process();
// ../../node_modules/.pnpm/zod@3.25.67/node_modules/zod/dist/esm/v3/locales/en.js
init_process();
// ../../node_modules/.pnpm/zod@3.25.67/node_modules/zod/dist/esm/v3/ZodError.js
init_process();
// ../../node_modules/.pnpm/zod@3.25.67/node_modules/zod/dist/esm/v3/helpers/util.js
init_process();
var util;
(function(util2) {
util2.assertEqual = (_) => {
};
function assertIs(_arg) {
}
util2.assertIs = assertIs;
function assertNever(_x) {
throw new Error();
}
util2.assertNever = assertNever;
util2.arrayToEnum = (items) => {
const obj = {};
for (const item of items) {
obj[item] = item;
}
return obj;
};
util2.getValidEnumValues = (obj) => {
const validKeys = util2.objectKeys(obj).filter((k) => typeof obj[obj[k]] !== "number");
const filtered = {};
for (const k of validKeys) {
filtered[k] = obj[k];
}
return util2.objectValues(filtered);
};
util2.objectValues = (obj) => {
return util2.objectKeys(obj).map(function(e2) {
return obj[e2];
});
};
util2.objectKeys = typeof Object.keys === "function" ? (obj) => Object.keys(obj) : (object) => {
const keys = [];
for (const key in object) {
if (Object.prototype.hasOwnProperty.call(object, key)) {
keys.push(key);
}
}
return keys;
};
util2.find = (arr, checker) => {
for (const item of arr) {
if (checker(item))
return item;
}
return void 0;
};
util2.isInteger = typeof Number.isInteger === "function" ? (val) => Number.isInteger(val) : (val) => typeof val === "number" && Number.isFinite(val) && Math.floor(val) === val;
function joinValues(array, separator = " | ") {
return array.map((val) => typeof val === "string" ? `'${val}'` : val).join(separator);
}
util2.joinValues = joinValues;
util2.jsonStringifyReplacer = (_, value) => {
if (typeof value === "bigint") {
return value.toString();
}
return value;
};
})(util || (util = {}));
var objectUtil;
(function(objectUtil2) {
objectUtil2.mergeShapes = (first, second) => {
return __spreadValues(__spreadValues({}, first), second);
};
})(objectUtil || (objectUtil = {}));
var ZodParsedType = util.arrayToEnum([
"string",
"nan",
"number",
"integer",
"float",
"boolean",
"date",
"bigint",
"symbol",
"function",
"undefined",
"null",
"array",
"object",
"unknown",
"promise",
"void",
"never",
"map",
"set"
]);
var getParsedType = (data) => {
const t2 = typeof data;
switch (t2) {
case "undefined":
return ZodParsedType.undefined;
case "string":
return ZodParsedType.string;
case "number":
return Number.isNaN(data) ? ZodParsedType.nan : ZodParsedType.number;
case "boolean":
return ZodParsedType.boolean;
case "function":
return ZodParsedType.function;
case "bigint":
return ZodParsedType.bigint;
case "symbol":
return ZodParsedType.symbol;
case "object":
if (Array.isArray(data)) {
return ZodParsedType.array;
}
if (data === null) {
return ZodParsedType.null;
}
if (data.then && typeof data.then === "function" && data.catch && typeof data.catch === "function") {
return ZodParsedType.promise;
}
if (typeof Map !== "undefined" && data instanceof Map) {
return ZodParsedType.map;
}
if (typeof Set !== "undefined" && data instanceof Set) {
return ZodParsedType.set;
}
if (typeof Date !== "undefined" && data instanceof Date) {
return ZodParsedType.date;
}
return ZodParsedType.object;
default:
return ZodParsedType.unknown;
}
};
// ../../node_modules/.pnpm/zod@3.25.67/node_modules/zod/dist/esm/v3/ZodError.js
var ZodIssueCode = util.arrayToEnum([
"invalid_type",
"invalid_literal",
"custom",
"invalid_union",
"invalid_union_discriminator",
"invalid_enum_value",
"unrecognized_keys",
"invalid_arguments",
"invalid_return_type",
"invalid_date",
"invalid_string",
"too_small",
"too_big",
"invalid_intersection_types",
"not_multiple_of",
"not_finite"
]);
var quotelessJson = (obj) => {
const json = JSON.stringify(obj, null, 2);
return json.replace(/"([^"]+)":/g, "$1:");
};
var ZodError = class _ZodError extends Error {
get errors() {
return this.issues;
}
constructor(issues) {
super();
this.issues = [];
this.addIssue = (sub) => {
this.issues = [...this.issues, sub];
};
this.addIssues = (subs = []) => {
this.issues = [...this.issues, ...subs];
};
const actualProto = new.target.prototype;
if (Object.setPrototypeOf) {
Object.setPrototypeOf(this, actualProto);
} else {
this.__proto__ = actualProto;
}
this.name = "ZodError";
this.issues = issues;
}
format(_mapper) {
const mapper = _mapper || function(issue) {
return issue.message;
};
const fieldErrors = { _errors: [] };
const processError = (error) => {
for (const issue of error.issues) {
if (issue.code === "invalid_union") {
issue.unionErrors.map(processError);
} else if (issue.code === "invalid_return_type") {
processError(issue.returnTypeError);
} else if (issue.code === "invalid_arguments") {
processError(issue.argumentsError);
} else if (issue.path.length === 0) {
fieldErrors._errors.push(mapper(issue));
} else {
let curr = fieldErrors;
let i = 0;
while (i < issue.path.length) {
const el = issue.path[i];
const terminal = i === issue.path.length - 1;
if (!terminal) {
curr[el] = curr[el] || { _errors: [] };
} else {
curr[el] = curr[el] || { _errors: [] };
curr[el]._errors.push(mapper(issue));
}
curr = curr[el];
i++;
}
}
}
};
processError(this);
return fieldErrors;
}
static assert(value) {
if (!(value instanceof _ZodError)) {
throw new Error(`Not a ZodError: ${value}`);
}
}
toString() {
return this.message;
}
get message() {
return JSON.stringify(this.issues, util.jsonStringifyReplacer, 2);
}
get isEmpty() {
return this.issues.length === 0;
}
flatten(mapper = (issue) => issue.message) {
const fieldErrors = {};
const formErrors = [];
for (const sub of this.issues) {
if (sub.path.length > 0) {
fieldErrors[sub.path[0]] = fieldErrors[sub.path[0]] || [];
fieldErrors[sub.path[0]].push(mapper(sub));
} else {
formErrors.push(mapper(sub));
}
}
return { formErrors, fieldErrors };
}
get formErrors() {
return this.flatten();
}
};
ZodError.create = (issues) => {
const error = new ZodError(issues);
return error;
};
// ../../node_modules/.pnpm/zod@3.25.67/node_modules/zod/dist/esm/v3/locales/en.js
var errorMap = (issue, _ctx) => {
let message;
switch (issue.code) {
case ZodIssueCode.invalid_type:
if (issue.received === ZodParsedType.undefined) {
message = "Required";
} else {
message = `Expected ${issue.expected}, received ${issue.received}`;
}
break;
case ZodIssueCode.invalid_literal:
message = `Invalid literal value, expected ${JSON.stringify(issue.expected, util.jsonStringifyReplacer)}`;
break;
case ZodIssueCode.unrecognized_keys:
message = `Unrecognized key(s) in object: ${util.joinValues(issue.keys, ", ")}`;
break;
case ZodIssueCode.invalid_union:
message = `Invalid input`;
break;
case ZodIssueCode.invalid_union_discriminator:
message = `Invalid discriminator value. Expected ${util.joinValues(issue.options)}`;
break;
case ZodIssueCode.invalid_enum_value:
message = `Invalid enum value. Expected ${util.joinValues(issue.options)}, received '${issue.received}'`;
break;
case ZodIssueCode.invalid_arguments:
message = `Invalid function arguments`;
break;
case ZodIssueCode.invalid_return_type:
message = `Invalid function return type`;
break;
case ZodIssueCode.invalid_date:
message = `Invalid date`;
break;
case ZodIssueCode.invalid_string:
if (typeof issue.validation === "object") {
if ("includes" in issue.validation) {
message = `Invalid input: must include "${issue.validation.includes}"`;
if (typeof issue.validation.position === "number") {
message = `${message} at one or more positions greater than or equal to ${issue.validation.position}`;
}
} else if ("startsWith" in issue.validation) {
message = `Invalid input: must start with "${issue.validation.startsWith}"`;
} else if ("endsWith" in issue.validation) {
message = `Invalid input: must end with "${issue.validation.endsWith}"`;
} else {
util.assertNever(issue.validation);
}
} else if (issue.validation !== "regex") {
message = `Invalid ${issue.validation}`;
} else {
message = "Invalid";
}
break;
case ZodIssueCode.too_small:
if (issue.type === "array")
message = `Array must contain ${issue.exact ? "exactly" : issue.inclusive ? `at least` : `more than`} ${issue.minimum} element(s)`;
else if (issue.type === "string")
message = `String must contain ${issue.exact ? "exactly" : issue.inclusive ? `at least` : `over`} ${issue.minimum} character(s)`;
else if (issue.type === "number")
message = `Number must be ${issue.exact ? `exactly equal to ` : issue.inclusive ? `greater than or equal to ` : `greater than `}${issue.minimum}`;
else if (issue.type === "date")
message = `Date must be ${issue.exact ? `exactly equal to ` : issue.inclusive ? `greater than or equal to ` : `greater than `}${new Date(Number(issue.minimum))}`;
else
message = "Invalid input";
break;
case ZodIssueCode.too_big:
if (issue.type === "array")
message = `Array must contain ${issue.exact ? `exactly` : issue.inclusive ? `at most` : `less than`} ${issue.maximum} element(s)`;
else if (issue.type === "string")
message = `String must contain ${issue.exact ? `exactly` : issue.inclusive ? `at most` : `under`} ${issue.maximum} character(s)`;
else if (issue.type === "number")
message = `Number must be ${issue.exact ? `exactly` : issue.inclusive ? `less than or equal to` : `less than`} ${issue.maximum}`;
else if (issue.type === "bigint")
message = `BigInt must be ${issue.exact ? `exactly` : issue.inclusive ? `less than or equal to` : `less than`} ${issue.maximum}`;
else if (issue.type === "date")
message = `Date must be ${issue.exact ? `exactly` : issue.inclusive ? `smaller than or equal to` : `smaller than`} ${new Date(Number(issue.maximum))}`;
else
message = "Invalid input";
break;
case ZodIssueCode.custom:
message = `Invalid input`;
break;
case ZodIssueCode.invalid_intersection_types:
message = `Intersection results could not be merged`;
break;
case ZodIssueCode.not_multiple_of:
message = `Number must be a multiple of ${issue.multipleOf}`;
break;
case ZodIssueCode.not_finite:
message = "Number must be finite";
break;
default:
message = _ctx.defaultError;
util.assertNever(issue);
}
return { message };
};
var en_default = errorMap;
// ../../node_modules/.pnpm/zod@3.25.67/node_modules/zod/dist/esm/v3/errors.js
var overrideErrorMap = en_default;
function setErrorMap(map) {
overrideErrorMap = map;
}
function getErrorMap() {
return overrideErrorMap;
}
// ../../node_modules/.pnpm/zod@3.25.67/node_modules/zod/dist/esm/v3/helpers/parseUtil.js
init_process();
var makeIssue = (params) => {
const { data, path, errorMaps, issueData } = params;
const fullPath = [...path, ...issueData.path || []];
const fullIssue = __spreadProps(__spreadValues({}, issueData), {
path: fullPath
});
if (issueData.message !== void 0) {
return __spreadProps(__spreadValues({}, issueData), {
path: fullPath,
message: issueData.message
});
}
let errorMessage = "";
const maps = errorMaps.filter((m) => !!m).slice().reverse();
for (const map of maps) {
errorMessage = map(fullIssue, { data, defaultError: errorMessage }).message;
}
return __spreadProps(__spreadValues({}, issueData), {
path: fullPath,
message: errorMessage
});
};
var EMPTY_PATH = [];
function addIssueToContext(ctx, issueData) {
const overrideMap = getErrorMap();
const issue = makeIssue({
issueData,
data: ctx.data,
path: ctx.path,
errorMaps: [
ctx.common.contextualErrorMap,
// contextual error map is first priority
ctx.schemaErrorMap,
// then schema-bound map if available
overrideMap,
// then global override map
overrideMap === en_default ? void 0 : en_default
// then global default map
].filter((x) => !!x)
});
ctx.common.issues.push(issue);
}
var ParseStatus = class _ParseStatus {
constructor() {
this.value = "valid";
}
dirty() {
if (this.value === "valid")
this.value = "dirty";
}
abort() {
if (this.value !== "aborted")
this.value = "aborted";
}
static mergeArray(status, results) {
const arrayValue = [];
for (const s of results) {
if (s.status === "aborted")
return INVALID;
if (s.status === "dirty")
status.dirty();
arrayValue.push(s.value);
}
return { status: status.value, value: arrayValue };
}
static mergeObjectAsync(status, pairs) {
return __async(this, null, function* () {
const syncPairs = [];
for (const pair of pairs) {
const key = yield pair.key;
const value = yield pair.value;
syncPairs.push({
key,
value
});
}
return _ParseStatus.mergeObjectSync(status, syncPairs);
});
}
static mergeObjectSync(status, pairs) {
const finalObject = {};
for (const pair of pairs) {
const { key, value } = pair;
if (key.status === "aborted")
return INVALID;
if (value.status === "aborted")
return INVALID;
if (key.status === "dirty")
status.dirty();
if (value.status === "dirty")
status.dirty();
if (key.value !== "__proto__" && (typeof value.value !== "undefined" || pair.alwaysSet)) {
finalObject[key.value] = value.value;
}
}
return { status: status.value, value: finalObject };
}
};
var INVALID = Object.freeze({
status: "aborted"
});
var DIRTY = (value) => ({ status: "dirty", value });
var OK = (value) => ({ status: "valid", value });
var isAborted = (x) => x.status === "aborted";
var isDirty = (x) => x.status === "dirty";
var isValid = (x) => x.status === "valid";
var isAsync = (x) => typeof Promise !== "undefined" && x instanceof Promise;
// ../../node_modules/.pnpm/zod@3.25.67/node_modules/zod/dist/esm/v3/helpers/typeAliases.js
init_process();
// ../../node_modules/.pnpm/zod@3.25.67/node_modules/zod/dist/esm/v3/types.js
init_process();
// ../../node_modules/.pnpm/zod@3.25.67/node_modules/zod/dist/esm/v3/helpers/errorUtil.js
init_process();
var errorUtil;
(function(errorUtil2) {
errorUtil2.errToObj = (message) => typeof message === "string" ? { message } : message || {};
errorUtil2.toString = (message) => typeof message === "string" ? message : message == null ? void 0 : message.message;
})(errorUtil || (errorUtil = {}));
// ../../node_modules/.pnpm/zod@3.25.67/node_modules/zod/dist/esm/v3/types.js
var ParseInputLazyPath = class {
constructor(parent, value, path, key) {
this._cachedPath = [];
this.parent = parent;
this.data = value;
this._path = path;
this._key = key;
}
get path() {
if (!this._cachedPath.length) {
if (Array.isArray(this._key)) {
this._cachedPath.push(...this._path, ...this._key);
} else {
this._cachedPath.push(...this._path, this._key);
}
}
return this._cachedPath;
}
};
var handleResult = (ctx, result2) => {
if (isValid(result2)) {
return { success: true, data: result2.value };
} else {
if (!ctx.common.issues.length) {
throw new Error("Validation failed but no issues detected.");
}
return {
success: false,
get error() {
if (this._error)
return this._error;
const error = new ZodError(ctx.common.issues);
this._error = error;
return this._error;
}
};
}
};
function processCreateParams(params) {
if (!params)
return {};
const { errorMap: errorMap2, invalid_type_error, required_error, description } = params;
if (errorMap2 && (invalid_type_error || required_error)) {
throw new Error(`Can't use "invalid_type_error" or "required_error" in conjunction with custom error map.`);
}
if (errorMap2)
return { errorMap: errorMap2, description };
const customMap = (iss, ctx) => {
var _a2, _b2;
const { message } = params;
if (iss.code === "invalid_enum_value") {
return { message: message != null ? message : ctx.defaultError };
}
if (typeof ctx.data === "undefined") {
return { message: (_a2 = message != null ? message : required_error) != null ? _a2 : ctx.defaultError };
}
if (iss.code !== "invalid_type")
return { message: ctx.defaultError };
return { message: (_b2 = message != null ? message : invalid_type_error) != null ? _b2 : ctx.defaultError };
};
return { errorMap: customMap, description };
}
var ZodType = class {
get description() {
return this._def.description;
}
_getType(input) {
return getParsedType(input.data);
}
_getOrReturnCtx(input, ctx) {
return ctx || {
common: input.parent.common,
data: input.data,
parsedType: getParsedType(input.data),
schemaErrorMap: this._def.errorMap,
path: input.path,
parent: input.parent
};
}
_processInputParams(input) {
return {
status: new ParseStatus(),
ctx: {
common: input.parent.common,
data: input.data,
parsedType: getParsedType(input.data),
schemaErrorMap: this._def.errorMap,
path: input.path,
parent: input.parent
}
};
}
_parseSync(input) {
const result2 = this._parse(input);
if (isAsync(result2)) {
throw new Error("Synchronous parse encountered promise.");
}
return result2;
}
_parseAsync(input) {
const result2 = this._parse(input);
return Promise.resolve(result2);
}
parse(data, params) {
const result2 = this.safeParse(data, params);
if (result2.success)
return result2.data;
throw result2.error;
}
safeParse(data, params) {
var _a2;
const ctx = {
common: {
issues: [],
async: (_a2 = params == null ? void 0 : params.async) != null ? _a2 : false,
contextualErrorMap: params == null ? void 0 : params.errorMap
},
path: (params == null ? void 0 : params.path) || [],
schemaErrorMap: this._def.errorMap,
parent: null,
data,
parsedType: getParsedType(data)
};
const result2 = this._parseSync({ data, path: ctx.path, parent: ctx });
return handleResult(ctx, result2);
}
"~validate"(data) {
var _a2, _b2;
const ctx = {
common: {
issues: [],
async: !!this["~standard"].async
},
path: [],
schemaErrorMap: this._def.errorMap,
parent: null,
data,
parsedType: getParsedType(data)
};
if (!this["~standard"].async) {
try {
const result2 = this._parseSync({ data, path: [], parent: ctx });
return isValid(result2) ? {
value: result2.value
} : {
issues: ctx.common.issues
};
} catch (err) {
if ((_b2 = (_a2 = err == null ? void 0 : err.message) == null ? void 0 : _a2.toLowerCase()) == null ? void 0 : _b2.includes("encountered")) {
this["~standard"].async = true;
}
ctx.common = {
issues: [],
async: true
};
}
}
return this._parseAsync({ data, path: [], parent: ctx }).then((result2) => isValid(result2) ? {
value: result2.value
} : {
issues: ctx.common.issues
});
}
parseAsync(data, params) {
return __async(this, null, function* () {
const result2 = yield this.safeParseAsync(data, params);
if (result2.success)
return result2.data;
throw result2.error;
});
}
safeParseAsync(data, params) {
return __async(this, null, function* () {
const ctx = {
common: {
issues: [],
contextualErrorMap: params == null ? void 0 : params.errorMap,
async: true
},
path: (params == null ? void 0 : params.path) || [],
schemaErrorMap: this._def.errorMap,
parent: null,
data,
parsedType: getParsedType(data)
};
const maybeAsyncResult = this._parse({ data, path: ctx.path, parent: ctx });
const result2 = yield isAsync(maybeAsyncResult) ? maybeAsyncResult : Promise.resolve(maybeAsyncResult);
return handleResult(ctx, result2);
});
}
refine(check, message) {
const getIssueProperties = (val) => {
if (typeof message === "string" || typeof message === "undefined") {
return { message };
} else if (typeof message === "function") {
return message(val);
} else {
return message;
}
};
return this._refinement((val, ctx) => {
const result2 = check(val);
const setError = () => ctx.addIssue(__spreadValues({
code: ZodIssueCode.custom
}, getIssueProperties(val)));
if (typeof Promise !== "undefined" && result2 instanceof Promise) {
return result2.then((data) => {
if (!data) {
setError();
return false;
} else {
return true;
}
});
}
if (!result2) {
setError();
return false;
} else {
return true;
}
});
}
refinement(check, refinementData) {
return this._refinement((val, ctx) => {
if (!check(val)) {
ctx.addIssue(typeof refinementData === "function" ? refinementData(val, ctx) : refinementData);
return false;
} else {
return true;
}
});
}
_refinement(refinement) {
return new ZodEffects({
schema: this,
typeName: ZodFirstPartyTypeKind.ZodEffects,
effect: { type: "refinement", refinement }
});
}
superRefine(refinement) {
return this._refinement(refinement);
}
constructor(def) {
this.spa = this.safeParseAsync;
this._def = def;
this.parse = this.parse.bind(this);
this.safeParse = this.safeParse.bind(this);
this.parseAsync = this.parseAsync.bind(this);
this.safeParseAsync = this.safeParseAsync.bind(this);
this.spa = this.spa.bind(this);
this.refine = this.refine.bind(this);
this.refinement = this.refinement.bind(this);
this.superRefine = this.superRefine.bind(this);
this.optional = this.optional.bind(this);
this.nullable = this.nullable.bind(this);
this.nullish = this.nullish.bind(this);
this.array = this.array.bind(this);
this.promise = this.promise.bind(this);
this.or = this.or.bind(this);
this.and = this.and.bind(this);
this.transform = this.transform.bind(this);
this.brand = this.brand.bind(this);
this.default = this.default.bind(this);
this.catch = this.catch.bind(this);
this.describe = this.describe.bind(this);
this.pipe = this.pipe.bind(this);
this.readonly = this.readonly.bind(this);
this.isNullable = this.isNullable.bind(this);
this.isOptional = this.isOptional.bind(this);
this["~standard"] = {
version: 1,
vendor: "zod",
validate: (data) => this["~validate"](data)
};
}
optional() {
return ZodOptional.create(this, this._def);
}
nullable() {
return ZodNullable.create(this, this._def);
}
nullish() {
return this.nullable().optional();
}
array() {
return ZodArray.create(this);
}
promise() {
return ZodPromise.create(this, this._def);
}
or(option) {
return ZodUnion.create([this, option], this._def);
}
and(incoming) {
return ZodIntersection.create(this, incoming, this._def);
}
transform(transform) {
return new ZodEffects(__spreadProps(__spreadValues({}, processCreateParams(this._def)), {
schema: this,
typeName: ZodFirstPartyTypeKind.ZodEffects,
effect: { type: "transform", transform }
}));
}
default(def) {
const defaultValueFunc = typeof def === "function" ? def : () => def;
return new ZodDefault(__spreadProps(__spreadValues({}, processCreateParams(this._def)), {
innerType: this,
defaultValue: defaultValueFunc,
typeName: ZodFirstPartyTypeKind.ZodDefault
}));
}
brand() {
return new ZodBranded(__spreadValues({
typeName: ZodFirstPartyTypeKind.ZodBranded,
type: this
}, processCreateParams(this._def)));
}
catch(def) {
const catchValueFunc = typeof def === "function" ? def : () => def;
return new ZodCatch(__spreadProps(__spreadValues({}, processCreateParams(this._def)), {
innerType: this,
catchValue: catchValueFunc,
typeName: ZodFirstPartyTypeKind.ZodCatch
}));
}
describe(description) {
const This = this.constructor;
return new This(__spreadProps(__spreadValues({}, this._def), {
description
}));
}
pipe(target) {
return ZodPipeline.create(this, target);
}
readonly() {
return ZodReadonly.create(this);
}
isOptional() {
return this.safeParse(void 0).success;
}
isNullable() {
return this.safeParse(null).success;
}
};
var cuidRegex = /^c[^\s-]{8,}$/i;
var cuid2Regex = /^[0-9a-z]+$/;
var ulidRegex = /^[0-9A-HJKMNP-TV-Z]{26}$/i;
var uuidRegex = /^[0-9a-fA-F]{8}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{12}$/i;
var nanoidRegex = /^[a-z0-9_-]{21}$/i;
var jwtRegex = /^[A-Za-z0-9-_]+\.[A-Za-z0-9-_]+\.[A-Za-z0-9-_]*$/;
var durationRegex = /^[-+]?P(?!$)(?:(?:[-+]?\d+Y)|(?:[-+]?\d+[.,]\d+Y$))?(?:(?:[-+]?\d+M)|(?:[-+]?\d+[.,]\d+M$))?(?:(?:[-+]?\d+W)|(?:[-+]?\d+[.,]\d+W$))?(?:(?:[-+]?\d+D)|(?:[-+]?\d+[.,]\d+D$))?(?:T(?=[\d+-])(?:(?:[-+]?\d+H)|(?:[-+]?\d+[.,]\d+H$))?(?:(?:[-+]?\d+M)|(?:[-+]?\d+[.,]\d+M$))?(?:[-+]?\d+(?:[.,]\d+)?S)?)??$/;
var emailRegex = /^(?!\.)(?!.*\.\.)([A-Z0-9_'+\-\.]*)[A-Z0-9_+-]@([A-Z0-9][A-Z0-9\-]*\.)+[A-Z]{2,}$/i;
var _emojiRegex = `^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$`;
var emojiRegex;
var ipv4Regex = /^(?:(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\.){3}(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])$/;
var ipv4CidrRegex = /^(?:(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\.){3}(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\/(3[0-2]|[12]?[0-9])$/;
var ipv6Regex = /^(([0-9a-fA-F]{1,4}:){7,7}[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,7}:|([0-9a-fA-F]{1,4}:){1,6}:[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,5}(:[0-9a-fA-F]{1,4}){1,2}|([0-9a-fA-F]{1,4}:){1,4}(:[0-9a-fA-F]{1,4}){1,3}|([0-9a-fA-F]{1,4}:){1,3}(:[0-9a-fA-F]{1,4}){1,4}|([0-9a-fA-F]{1,4}:){1,2}(:[0-9a-fA-F]{1,4}){1,5}|[0-9a-fA-F]{1,4}:((:[0-9a-fA-F]{1,4}){1,6})|:((:[0-9a-fA-F]{1,4}){1,7}|:)|fe80:(:[0-9a-fA-F]{0,4}){0,4}%[0-9a-zA-Z]{1,}|::(ffff(:0{1,4}){0,1}:){0,1}((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])|([0-9a-fA-F]{1,4}:){1,4}:((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9]))$/;
var ipv6CidrRegex = /^(([0-9a-fA-F]{1,4}:){7,7}[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,7}:|([0-9a-fA-F]{1,4}:){1,6}:[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,5}(:[0-9a-fA-F]{1,4}){1,2}|([0-9a-fA-F]{1,4}:){1,4}(:[0-9a-fA-F]{1,4}){1,3}|([0-9a-fA-F]{1,4}:){1,3}(:[0-9a-fA-F]{1,4}){1,4}|([0-9a-fA-F]{1,4}:){1,2}(:[0-9a-fA-F]{1,4}){1,5}|[0-9a-fA-F]{1,4}:((:[0-9a-fA-F]{1,4}){1,6})|:((:[0-9a-fA-F]{1,4}){1,7}|:)|fe80:(:[0-9a-fA-F]{0,4}){0,4}%[0-9a-zA-Z]{1,}|::(ffff(:0{1,4}){0,1}:){0,1}((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])|([0-9a-fA-F]{1,4}:){1,4}:((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9]))\/(12[0-8]|1[01][0-9]|[1-9]?[0-9])$/;
var base64Regex = /^([0-9a-zA-Z+/]{4})*(([0-9a-zA-Z+/]{2}==)|([0-9a-zA-Z+/]{3}=))?$/;
var base64urlRegex = /^([0-9a-zA-Z-_]{4})*(([0-9a-zA-Z-_]{2}(==)?)|([0-9a-zA-Z-_]{3}(=)?))?$/;
var dateRegexSource = `((\\d\\d[2468][048]|\\d\\d[13579][26]|\\d\\d0[48]|[02468][048]00|[13579][26]00)-02-29|\\d{4}-((0[13578]|1[02])-(0[1-9]|[12]\\d|3[01])|(0[469]|11)-(0[1-9]|[12]\\d|30)|(02)-(0[1-9]|1\\d|2[0-8])))`;
var dateRegex = new RegExp(`^${dateRegexSource}$`);
function timeRegexSource(args) {
let secondsRegexSource = `[0-5]\\d`;
if (args.precision) {
secondsRegexSource = `${secondsRegexSource}\\.\\d{${args.precision}}`;
} else if (args.precision == null) {
secondsRegexSource = `${secondsRegexSource}(\\.\\d+)?`;
}
const secondsQuantifier = args.precision ? "+" : "?";
return `([01]\\d|2[0-3]):[0-5]\\d(:${secondsRegexSource})${secondsQuantifier}`;
}
function timeRegex(args) {
return new RegExp(`^${timeRegexSource(args)}$`);
}
function datetimeRegex(args) {
let regex = `${dateRegexSource}T${timeRegexSource(args)}`;
const opts = [];
opts.push(args.local ? `Z?` : `Z`);
if (args.offset)
opts.push(`([+-]\\d{2}:?\\d{2})`);
regex = `${regex}(${opts.join("|")})`;
return new RegExp(`^${regex}$`);
}
function isValidIP(ip, version) {
if ((version === "v4" || !version) && ipv4Regex.test(ip)) {
return true;
}
if ((version === "v6" || !version) && ipv6Regex.test(ip)) {
return true;
}
return false;
}
function isValidJWT(jwt, alg) {
if (!jwtRegex.test(jwt))
return false;
try {
const [header] = jwt.split(".");
const base64 = header.replace(/-/g, "+").replace(/_/g, "/").padEnd(header.length + (4 - header.length % 4) % 4, "=");
const decoded = JSON.parse(atob(base64));
if (typeof decoded !== "object" || decoded === null)
return false;
if ("typ" in decoded && (decoded == null ? void 0 : decoded.typ) !== "JWT")
return false;
if (!decoded.alg)
return false;
if (alg && decoded.alg !== alg)
return false;
return true;
} catch (e2) {
return false;
}
}
function isValidCidr(ip, version) {
if ((version === "v4" || !version) && ipv4CidrRegex.test(ip)) {
return true;
}
if ((version === "v6" || !version) && ipv6CidrRegex.test(ip)) {
return true;
}
return false;
}
var ZodString = class _ZodString extends ZodType {
_parse(input) {
if (this._def.coerce) {
input.data = String(input.data);
}
const parsedType = this._getType(input);
if (parsedType !== ZodParsedType.string) {
const ctx2 = this._getOrReturnCtx(input);
addIssueToContext(ctx2, {
code: ZodIssueCode.invalid_type,
expected: ZodParsedType.string,
received: ctx2.parsedType
});
return INVALID;
}
const status = new ParseStatus();
let ctx = void 0;
for (const check of this._def.checks) {
if (check.kind === "min") {
if (input.data.length < check.value) {
ctx = this._getOrReturnCtx(input, ctx);
addIssueToContext(ctx, {
code: ZodIssueCode.too_small,
minimum: check.value,
type: "string",
inclusive: true,
exact: false,
message: check.message
});
status.dirty();
}
} else if (check.kind === "max") {
if (input.data.length > check.value) {
ctx = this._getOrReturnCtx(input, ctx);
addIssueToContext(ctx, {
code: ZodIssueCode.too_big,
maximum: check.value,
type: "string",
inclusive: true,
exact: false,
message: check.message
});
status.dirty();
}
} else if (check.kind === "length") {
const tooBig = input.data.length > check.value;
const tooSmall = input.data.length < check.value;
if (tooBig || tooSmall) {
ctx = this._getOrReturnCtx(input, ctx);
if (tooBig) {
addIssueToContext(ctx, {
code: ZodIssueCode.too_big,
maximum: check.value,
type: "string",
inclusive: true,
exact: true,
message: check.message
});
} else if (tooSmall) {
addIssueToContext(ctx, {
code: ZodIssueCode.too_small,
minimum: check.value,
type: "string",
inclusive: true,
exact: true,
message: check.message
});
}
status.dirty();
}
} else if (check.kind === "email") {
if (!emailRegex.test(input.data)) {
ctx = this._getOrReturnCtx(input, ctx);
addIssueToContext(ctx, {
validation: "email",
code: ZodIssueCode.invalid_string,
message: check.message
});
status.dirty();
}
} else if (check.kind === "emoji") {
if (!emojiRegex) {
emojiRegex = new RegExp(_emojiRegex, "u");
}
if (!emojiRegex.test(input.data)) {
ctx = this._getOrReturnCtx(input, ctx);
addIssueToContext(ctx, {
validation: "emoji",
code: ZodIssueCode.invalid_string,
message: check.message
});
status.dirty();
}
} else if (check.kind === "uuid") {
if (!uuidRegex.test(input.data)) {
ctx = this._getOrReturnCtx(input, ctx);
addIssueToContext(ctx, {
validation: "uuid",
code: ZodIssueCode.invalid_string,
message: check.message
});
status.dirty();
}
} else if (check.kind === "nanoid") {
if (!nanoidRegex.test(input.data)) {
ctx = this._getOrReturnCtx(input, ctx);
addIssueToContext(ctx, {
validation: "nanoid",
code: ZodIssueCode.invalid_string,
message: check.message
});
status.dirty();
}
} else if (check.kind === "cuid") {
if (!cuidRegex.test(input.data)) {
ctx = this._getOrReturnCtx(input, ctx);
addIssueToContext(ctx, {
validation: "cuid",
code: ZodIssueCode.invalid_string,
message: check.message
});
status.dirty();
}
} else if (check.kind === "cuid2") {
if (!cuid2Regex.test(input.data)) {
ctx = this._getOrReturnCtx(input, ctx);
addIssueToContext(ctx, {
validation: "cuid2",
code: ZodIssueCode.invalid_string,
message: check.message
});
status.dirty();
}
} else if (check.kind === "ulid") {
if (!ulidRegex.test(input.data)) {
ctx = this._getOrReturnCtx(input, ctx);
addIssueToContext(ctx, {
validation: "ulid",
code: ZodIssueCode.invalid_string,
message: check.message
});
status.dirty();
}
} else if (check.kind === "url") {
try {
new URL(input.data);
} catch (e2) {
ctx = this._getOrReturnCtx(input, ctx);
addIssueToContext(ctx, {
validation: "url",
code: ZodIssueCode.invalid_string,
message: check.message
});
status.dirty();
}
} else if (check.kind === "regex") {
check.regex.lastIndex = 0;
const testResult = check.regex.test(input.data);
if (!testResult) {
ctx = this._getOrReturnCtx(input, ctx);
addIssueToContext(ctx, {
validation: "regex",
code: ZodIssueCode.invalid_string,
message: check.message
});
status.dirty();
}
} else if (check.kind === "trim") {
input.data = input.data.trim();
} else if (check.kind === "includes") {
if (!input.data.includes(check.value, check.position)) {
ctx = this._getOrReturnCtx(input, ctx);
addIssueToContext(ctx, {
code: ZodIssueCode.invalid_string,
validation: { includes: check.value, position: check.position },
message: check.message
});
status.dirty();
}
} else if (check.kind === "toLowerCase") {
input.data = input.data.toLowerCase();
} else if (check.kind === "toUpperCase") {
input.data = input.data.toUpperCase();
} else if (check.kind === "startsWith") {
if (!input.data.startsWith(check.value)) {
ctx = this._getOrReturnCtx(input, ctx);
addIssueToContext(ctx, {
code: ZodIssueCode.invalid_string,
validation: { startsWith: check.value },
message: check.message
});
status.dirty();
}
} else if (check.kind === "endsWith") {
if (!input.data.endsWith(check.value)) {
ctx = this._getOrReturnCtx(input, ctx);
addIssueToContext(ctx, {
code: ZodIssueCode.invalid_string,
validation: { endsWith: check.value },
message: check.message
});
status.dirty();
}
} else if (check.kind === "datetime") {
const regex = datetimeRegex(check);
if (!regex.test(input.data)) {
ctx = this._getOrReturnCtx(input, ctx);
addIssueToContext(ctx, {
code: ZodIssueCode.invalid_string,
validation: "datetime",
message: check.message
});
status.dirty();
}
} else if (check.kind === "date") {
const regex = dateRegex;
if (!regex.test(input.data)) {
ctx = this._getOrReturnCtx(input, ctx);
addIssueToContext(ctx, {
code: ZodIssueCode.invalid_string,
validation: "date",
message: check.message
});
status.dirty();
}
} else if (check.kind === "time") {
const regex = timeRegex(check);
if (!regex.test(input.data)) {
ctx = this._getOrReturnCtx(input, ctx);
addIssueToContext(ctx, {
code: ZodIssueCode.invalid_string,
validation: "time",
message: check.message
});
status.dirty();
}
} else if (check.kind === "duration") {
if (!durationRegex.test(input.data)) {
ctx = this._getOrReturnCtx(input, ctx);
addIssueToContext(ctx, {
validation: "duration",
code: ZodIssueCode.invalid_string,
message: check.message
});
status.dirty();
}
} else if (check.kind === "ip") {
if (!isValidIP(input.data, check.version)) {
ctx = this._getOrReturnCtx(input, ctx);
addIssueToContext(ctx, {
validation: "ip",
code: ZodIssueCode.invalid_string,
message: check.message
});
status.dirty();
}
} else if (check.kind === "jwt") {
if (!isValidJWT(input.data, check.alg)) {
ctx = this._getOrReturnCtx(input, ctx);
addIssueToContext(ctx, {
validation: "jwt",
code: ZodIssueCode.invalid_string,
message: check.message
});
status.dirty();
}
} else if (check.kind === "cidr") {
if (!isValidCidr(input.data, check.version)) {
ctx = this._getOrReturnCtx(input, ctx);
addIssueToContext(ctx, {
validation: "cidr",
code: ZodIssueCode.invalid_string,
message: check.message
});
status.dirty();
}
} else if (check.kind === "base64") {
if (!base64Regex.test(input.data)) {
ctx = this._getOrReturnCtx(input, ctx);
addIssueToContext(ctx, {
validation: "base64",
code: ZodIssueCode.invalid_string,
message: check.message
});
status.dirty();
}
} else if (check.kind === "base64url") {
if (!base64urlRegex.test(input.data)) {
ctx = this._getOrReturnCtx(input, ctx);
addIssueToContext(ctx, {
validation: "base64url",
code: ZodIssueCode.invalid_string,
message: check.message
});
status.dirty();
}
} else {
util.assertNever(check);
}
}
return { status: status.value, value: input.data };
}
_regex(regex, validation, message) {
return this.refinement((data) => regex.test(data), __spreadValues({
validation,
code: ZodIssueCode.invalid_string
}, errorUtil.errToObj(message)));
}
_addCheck(check) {
return new _ZodString(__spreadProps(__spreadValues({}, this._def), {
checks: [...this._def.checks, check]
}));
}
email(message) {
return this._addCheck(__spreadValues({ kind: "email" }, errorUtil.errToObj(message)));
}
url(message) {
return this._addCheck(__spreadValues({ kind: "url" }, errorUtil.errToObj(message)));
}
emoji(message) {
return this._addCheck(__spreadValues({ kind: "emoji" }, errorUtil.errToObj(message)));
}
uuid(message) {
return this._addCheck(__spreadValues({ kind: "uuid" }, errorUtil.errToObj(message)));
}
nanoid(message) {
return this._addCheck(__spreadValues({ kind: "nanoid" }, errorUtil.errToObj(message)));
}
cuid(message) {
return this._addCheck(__spreadValues({ kind: "cuid" }, errorUtil.errToObj(message)));
}
cuid2(message) {
return this._addCheck(__spreadValues({ kind: "cuid2" }, errorUtil.errToObj(message)));
}
ulid(message) {
return this._addCheck(__spreadValues({ kind: "ulid" }, errorUtil.errToObj(message)));
}
base64(message) {
return this._addCheck(__spreadValues({ kind: "base64" }, errorUtil.errToObj(message)));
}
base64url(message) {
return this._addCheck(__spreadValues({
kind: "base64url"
}, errorUtil.errToObj(message)));
}
jwt(options) {
return this._addCheck(__spreadValues({ kind: "jwt" }, errorUtil.errToObj(options)));
}
ip(options) {
return this._addCheck(__spreadValues({ kind: "ip" }, errorUtil.errToObj(options)));
}
cidr(options) {
return this._addCheck(__spreadValues({ kind: "cidr" }, errorUtil.errToObj(options)));
}
datetime(options) {
var _a2, _b2;
if (typeof options === "string") {
return this._addCheck({
kind: "datetime",
precision: null,
offset: false,
local: false,
message: options
});
}
return this._addCheck(__spreadValues({
kind: "datetime",
precision: typeof (options == null ? void 0 : options.precision) === "undefined" ? null : options == null ? void 0 : options.precision,
offset: (_a2 = options == null ? void 0 : options.offset) != null ? _a2 : false,
local: (_b2 = options == null ? void 0 : options.local) != null ? _b2 : false
}, errorUtil.errToObj(options == null ? void 0 : options.message)));
}
date(message) {
return this._addCheck({ kind: "date", message });
}
time(options) {
if (typeof options === "string") {
return this._addCheck({
kind: "time",
precision: null,
message: options
});
}
return this._addCheck(__spreadValues({
kind: "time",
precision: typeof (options == null ? void 0 : options.precision) === "undefined" ? null : options == null ? void 0 : options.precision
}, errorUtil.errToObj(options == null ? void 0 : options.message)));
}
duration(message) {
return this._addCheck(__spreadValues({ kind: "duration" }, errorUtil.errToObj(message)));
}
regex(regex, message) {
return this._addCheck(__spreadValues({
kind: "regex",
regex
}, errorUtil.errToObj(message)));
}
includes(value, options) {
return this._addCheck(__spreadValues({
kind: "includes",
value,
position: options == null ? void 0 : options.position
}, errorUtil.errToObj(options == null ? void 0 : options.message)));
}
startsWith(value, message) {
return this._addCheck(__spreadValues({
kind: "startsWith",
value
}, errorUtil.errToObj(message)));
}
endsWith(value, message) {
return this._addCheck(__spreadValues({
kind: "endsWith",
value
}, errorUtil.errToObj(message)));
}
min(minLength, message) {
return this._addCheck(__spreadValues({
kind: "min",
value: minLength
}, errorUtil.errToObj(message)));
}
max(maxLength, message) {
return this._addCheck(__spreadValues({
kind: "max",
value: maxLength
}, errorUtil.errToObj(message)));
}
length(len, message) {
return this._addCheck(__spreadValues({
kind: "length",
value: len
}, errorUtil.errToObj(message)));
}
/**
* Equivalent to `.min(1)`
*/
nonempty(message) {
return this.min(1, errorUtil.errToObj(message));
}
trim() {
return new _ZodString(__spreadProps(__spreadValues({}, this._def), {
checks: [...this._def.checks, { kind: "trim" }]
}));
}
toLowerCase() {
return new _ZodString(__spreadProps(__spreadValues({}, this._def), {
checks: [...this._def.checks, { kind: "toLowerCase" }]
}));
}
toUpperCase() {
return new _ZodString(__spreadProps(__spreadValues({}, this._def), {
checks: [...this._def.checks, { kind: "toUpperCase" }]
}));
}
get isDatetime() {
return !!this._def.checks.find((ch) => ch.kind === "datetime");
}
get isDate() {
return !!this._def.checks.find((ch) => ch.kind === "date");
}
get isTime() {
return !!this._def.checks.find((ch) => ch.kind === "time");
}
get isDuration() {
return !!this._def.checks.find((ch) => ch.kind === "duration");
}
get isEmail() {
return !!this._def.checks.find((ch) => ch.kind === "email");
}
get isURL() {
return !!this._def.checks.find((ch) => ch.kind === "url");
}
get isEmoji() {
return !!this._def.checks.find((ch) => ch.kind === "emoji");
}
get isUUID() {
return !!this._def.checks.find((ch) => ch.kind === "uuid");
}
get isNANOID() {
return !!this._def.checks.find((ch) => ch.kind === "nanoid");
}
get isCUID() {
return !!this._def.checks.find((ch) => ch.kind === "cuid");
}
get isCUID2() {
return !!this._def.checks.find((ch) => ch.kind === "cuid2");
}
get isULID() {
return !!this._def.checks.find((ch) => ch.kind === "ulid");
}
get isIP() {
return !!this._def.checks.find((ch) => ch.kind === "ip");
}
get isCIDR() {
return !!this._def.checks.find((ch) => ch.kind === "cidr");
}
get isBase64() {
return !!this._def.checks.find((ch) => ch.kind === "base64");
}
get isBase64url() {
return !!this._def.checks.find((ch) => ch.kind === "base64url");
}
get minLength() {
let min = null;
for (const ch of this._def.checks) {
if (ch.kind === "min") {
if (min === null || ch.value > min)
min = ch.value;
}
}
return min;
}
get maxLength() {
let max = null;
for (const ch of this._def.checks) {
if (ch.kind === "max") {
if (max === null || ch.value < max)
max = ch.value;
}
}
return max;
}
};
ZodString.create = (params) => {
var _a2;
return new ZodString(__spreadValues({
checks: [],
typeName: ZodFirstPartyTypeKind.ZodString,
coerce: (_a2 = params == null ? void 0 : params.coerce) != null ? _a2 : false
}, processCreateParams(params)));
};
function floatSafeRemainder(val, step) {
const valDecCount = (val.toString().split(".")[1] || "").length;
const stepDecCount = (step.toString().split(".")[1] || "").length;
const decCount = valDecCount > stepDecCount ? valDecCount : stepDecCount;
const valInt = Number.parseInt(val.toFixed(decCount).replace(".", ""));
const stepInt = Number.parseInt(step.toFixed(decCount).replace(".", ""));
return valInt % stepInt / __pow(10, decCount);
}
var ZodNumber = class _ZodNumber extends ZodType {
constructor() {
super(...arguments);
this.min = this.gte;
this.max = this.lte;
this.step = this.multipleOf;
}
_parse(input) {
if (this._def.coerce) {
input.data = Number(input.data);
}
const parsedType = this._getType(input);
if (parsedType !== ZodParsedType.number) {
const ctx2 = this._getOrReturnCtx(input);
addIssueToContext(ctx2, {
code: ZodIssueCode.invalid_type,
expected: ZodParsedType.number,
received: ctx2.parsedType
});
return INVALID;
}
let ctx = void 0;
const status = new ParseStatus();
for (const check of this._def.checks) {
if (check.kind === "int") {
if (!util.isInteger(input.data)) {
ctx = this._getOrReturnCtx(input, ctx);
addIssueToContext(ctx, {
code: ZodIssueCode.invalid_type,
expected: "integer",
received: "float",
message: check.message
});
status.dirty();
}
} else if (check.kind === "min") {
const tooSmall = check.inclusive ? input.data < check.value : input.data <= check.value;
if (tooSmall) {
ctx = this._getOrReturnCtx(input, ctx);
addIssueToContext(ctx, {
code: ZodIssueCode.too_small,
minimum: check.value,
type: "number",
inclusive: check.inclusive,
exact: false,
message: check.message
});
status.dirty();
}
} else if (check.kind === "max") {
const tooBig = check.inclusive ? input.data > check.value : input.data >= check.value;
if (tooBig) {
ctx = this._getOrReturnCtx(input, ctx);
addIssueToContext(ctx, {
code: ZodIssueCode.too_big,
maximum: check.value,
type: "number",
inclusive: check.inclusive,
exact: false,
message: check.message
});
status.dirty();
}
} else if (check.kind === "multipleOf") {
if (floatSafeRemainder(input.data, check.value) !== 0) {
ctx = this._getOrReturnCtx(input, ctx);
addIssueToContext(ctx, {
code: ZodIssueCode.not_multiple_of,
multipleOf: check.value,
message: check.message
});
status.dirty();
}
} else if (check.kind === "finite") {
if (!Number.isFinite(input.data)) {
ctx = this._getOrReturnCtx(input, ctx);
addIssueToContext(ctx, {
code: ZodIssueCode.not_finite,
message: check.message
});
status.dirty();
}
} else {
util.assertNever(check);
}
}
return { status: status.value, value: input.data };
}
gte(value, message) {
return this.setLimit("min", value, true, errorUtil.toString(message));
}
gt(value, message) {
return this.setLimit("min", value, false, errorUtil.toString(message));
}
lte(value, message) {
return this.setLimit("max", value, true, errorUtil.toString(message));
}
lt(value, message) {
return this.setLimit("max", value, false, errorUtil.toString(message));
}
setLimit(kind, value, inclusive, message) {
return new _ZodNumber(__spreadProps(__spreadValues({}, this._def), {
checks: [
...this._def.checks,
{
kind,
value,
inclusive,
message: errorUtil.toString(message)
}
]
}));
}
_addCheck(check) {
return new _ZodNumber(__spreadProps(__spreadValues({}, this._def), {
checks: [...this._def.checks, check]
}));
}
int(message) {
return this._addCheck({
kind: "int",
message: errorUtil.toString(message)
});
}
positive(message) {
return this._addCheck({
kind: "min",
value: 0,
inclusive: false,
message: errorUtil.toString(message)
});
}
negative(message) {
return this._addCheck({
kind: "max",
value: 0,
inclusive: false,
message: errorUtil.toString(message)
});
}
nonpositive(message) {
return this._addCheck({
kind: "max",
value: 0,
inclusive: true,
message: errorUtil.toString(message)
});
}
nonnegative(message) {
return this._addCheck({
kind: "min",
value: 0,
inclusive: true,
message: errorUtil.toString(message)
});
}
multipleOf(value, message) {
return this._addCheck({
kind: "multipleOf",
value,
message: errorUtil.toString(message)
});
}
finite(message) {
return this._addCheck({
kind: "finite",
message: errorUtil.toString(message)
});
}
safe(message) {
return this._addCheck({
kind: "min",
inclusive: true,
value: Number.MIN_SAFE_INTEGER,
message: errorUtil.toString(message)
})._addCheck({
kind: "max",
inclusive: true,
value: Number.MAX_SAFE_INTEGER,
message: errorUtil.toString(message)
});
}
get minValue() {
let min = null;
for (const ch of this._def.checks) {
if (ch.kind === "min") {
if (min === null || ch.value > min)
min = ch.value;
}
}
return min;
}
get maxValue() {
let max = null;
for (const ch of this._def.checks) {
if (ch.kind === "max") {
if (max === null || ch.value < max)
max = ch.value;
}
}
return max;
}
get isInt() {
return !!this._def.checks.find((ch) => ch.kind === "int" || ch.kind === "multipleOf" && util.isInteger(ch.value));
}
get isFinite() {
let max = null;
let min = null;
for (const ch of this._def.checks) {
if (ch.kind === "finite" || ch.kind === "int" || ch.kind === "multipleOf") {
return true;
} else if (ch.kind === "min") {
if (min === null || ch.value > min)
min = ch.value;
} else if (ch.kind === "max") {
if (max === null || ch.value < max)
max = ch.value;
}
}
return Number.isFinite(min) && Number.isFinite(max);
}
};
ZodNumber.create = (params) => {
return new ZodNumber(__spreadValues({
checks: [],
typeName: ZodFirstPartyTypeKind.ZodNumber,
coerce: (params == null ? void 0 : params.coerce) || false
}, processCreateParams(params)));
};
var ZodBigInt = class _ZodBigInt extends ZodType {
constructor() {
super(...arguments);
this.min = this.gte;
this.max = this.lte;
}
_parse(input) {
if (this._def.coerce) {
try {
input.data = BigInt(input.data);
} catch (e2) {
return this._getInvalidInput(input);
}
}
const parsedType = this._getType(input);
if (parsedType !== ZodParsedType.bigint) {
return this._getInvalidInput(input);
}
let ctx = void 0;
const status = new ParseStatus();
for (const check of this._def.checks) {
if (check.kind === "min") {
const tooSmall = check.inclusive ? input.data < check.value : input.data <= check.value;
if (tooSmall) {
ctx = this._getOrReturnCtx(input, ctx);
addIssueToContext(ctx, {
code: ZodIssueCode.too_small,
type: "bigint",
minimum: check.value,
inclusive: check.inclusive,
message: check.message
});
status.dirty();
}
} else if (check.kind === "max") {
const tooBig = check.inclusive ? input.data > check.value : input.data >= check.value;
if (tooBig) {
ctx = this._getOrReturnCtx(input, ctx);
addIssueToContext(ctx, {
code: ZodIssueCode.too_big,
type: "bigint",
maximum: check.value,
inclusive: check.inclusive,
message: check.message
});
status.dirty();
}
} else if (check.kind === "multipleOf") {
if (input.data % check.value !== BigInt(0)) {
ctx = this._getOrReturnCtx(input, ctx);
addIssueToContext(ctx, {
code: ZodIssueCode.not_multiple_of,
multipleOf: check.value,
message: check.message
});
status.dirty();
}
} else {
util.assertNever(check);
}
}
return { status: status.value, value: input.data };
}
_getInvalidInput(input) {
const ctx = this._getOrReturnCtx(input);
addIssueToContext(ctx, {
code: ZodIssueCode.invalid_type,
expected: ZodParsedType.bigint,
received: ctx.parsedType
});
return INVALID;
}
gte(value, message) {
return this.setLimit("min", value, true, errorUtil.toString(message));
}
gt(value, message) {
return this.setLimit("min", value, false, errorUtil.toString(message));
}
lte(value, message) {
return this.setLimit("max", value, true, errorUtil.toString(message));
}
lt(value, message) {
return this.setLimit("max", value, false, errorUtil.toString(message));
}
setLimit(kind, value, inclusive, message) {
return new _ZodBigInt(__spreadProps(__spreadValues({}, this._def), {
checks: [
...this._def.checks,
{
kind,
value,
inclusive,
message: errorUtil.toString(message)
}
]
}));
}
_addCheck(check) {
return new _ZodBigInt(__spreadProps(__spreadValues({}, this._def), {
checks: [...this._def.checks, check]
}));
}
positive(message) {
return this._addCheck({
kind: "min",
value: BigInt(0),
inclusive: false,
message: errorUtil.toString(message)
});
}
negative(message) {
return this._addCheck({
kind: "max",
value: BigInt(0),
inclusive: false,
message: errorUtil.toString(message)
});
}
nonpositive(message) {
return this._addCheck({
kind: "max",
value: BigInt(0),
inclusive: true,
message: errorUtil.toString(message)
});
}
nonnegative(message) {
return this._addCheck({
kind: "min",
value: BigInt(0),
inclusive: true,
message: errorUtil.toString(message)
});
}
multipleOf(value, message) {
return this._addCheck({
kind: "multipleOf",
value,
message: errorUtil.toString(message)
});
}
get minValue() {
let min = null;
for (const ch of this._def.checks) {
if (ch.kind === "min") {
if (min === null || ch.value > min)
min = ch.value;
}
}
return min;
}
get maxValue() {
let max = null;
for (const ch of this._def.checks) {
if (ch.kind === "max") {
if (max === null || ch.value < max)
max = ch.value;
}
}
return max;
}
};
ZodBigInt.create = (params) => {
var _a2;
return new ZodBigInt(__spreadValues({
checks: [],
typeName: ZodFirstPartyTypeKind.ZodBigInt,
coerce: (_a2 = params == null ? void 0 : params.coerce) != null ? _a2 : false
}, processCreateParams(params)));
};
var ZodBoolean = class extends ZodType {
_parse(input) {
if (this._def.coerce) {
input.data = Boolean(input.data);
}
const parsedType = this._getType(input);
if (parsedType !== ZodParsedType.boolean) {
const ctx = this._getOrReturnCtx(input);
addIssueToContext(ctx, {
code: ZodIssueCode.invalid_type,
expected: ZodParsedType.boolean,
received: ctx.parsedType
});
return INVALID;
}
return OK(input.data);
}
};
ZodBoolean.create = (params) => {
return new ZodBoolean(__spreadValues({
typeName: ZodFirstPartyTypeKind.ZodBoolean,
coerce: (params == null ? void 0 : params.coerce) || false
}, processCreateParams(params)));
};
var ZodDate = class _ZodDate extends ZodType {
_parse(input) {
if (this._def.coerce) {
input.data = new Date(input.data);
}
const parsedType = this._getType(input);
if (parsedType !== ZodParsedType.date) {
const ctx2 = this._getOrReturnCtx(input);
addIssueToContext(ctx2, {
code: ZodIssueCode.invalid_type,
expected: ZodParsedType.date,
received: ctx2.parsedType
});
return INVALID;
}
if (Number.isNaN(input.data.getTime())) {
const ctx2 = this._getOrReturnCtx(input);
addIssueToContext(ctx2, {
code: ZodIssueCode.invalid_date
});
return INVALID;
}
const status = new ParseStatus();
let ctx = void 0;
for (const check of this._def.checks) {
if (check.kind === "min") {
if (input.data.getTime() < check.value) {
ctx = this._getOrReturnCtx(input, ctx);
addIssueToContext(ctx, {
code: ZodIssueCode.too_small,
message: check.message,
inclusive: true,
exact: false,
minimum: check.value,
type: "date"
});
status.dirty();
}
} else if (check.kind === "max") {
if (input.data.getTime() > check.value) {
ctx = this._getOrReturnCtx(input, ctx);
addIssueToContext(ctx, {
code: ZodIssueCode.too_big,
message: check.message,
inclusive: true,
exact: false,
maximum: check.value,
type: "date"
});
status.dirty();
}
} else {
util.assertNever(check);
}
}
return {
status: status.value,
value: new Date(input.data.getTime())
};
}
_addCheck(check) {
return new _ZodDate(__spreadProps(__spreadValues({}, this._def), {
checks: [...this._def.checks, check]
}));
}
min(minDate, message) {
return this._addCheck({
kind: "min",
value: minDate.getTime(),
message: errorUtil.toString(message)
});
}
max(maxDate, message) {
return this._addCheck({
kind: "max",
value: maxDate.getTime(),
message: errorUtil.toString(message)
});
}
get minDate() {
let min = null;
for (const ch of this._def.checks) {
if (ch.kind === "min") {
if (min === null || ch.value > min)
min = ch.value;
}
}
return min != null ? new Date(min) : null;
}
get maxDate() {
let max = null;
for (const ch of this._def.checks) {
if (ch.kind === "max") {
if (max === null || ch.value < max)
max = ch.value;
}
}
return max != null ? new Date(max) : null;
}
};
ZodDate.create = (params) => {
return new ZodDate(__spreadValues({
checks: [],
coerce: (params == null ? void 0 : params.coerce) || false,
typeName: ZodFirstPartyTypeKind.ZodDate
}, processCreateParams(params)));
};
var ZodSymbol = class extends ZodType {
_parse(input) {
const parsedType = this._getType(input);
if (parsedType !== ZodParsedType.symbol) {
const ctx = this._getOrReturnCtx(input);
addIssueToContext(ctx, {
code: ZodIssueCode.invalid_type,
expected: ZodParsedType.symbol,
received: ctx.parsedType
});
return INVALID;
}
return OK(input.data);
}
};
ZodSymbol.create = (params) => {
return new ZodSymbol(__spreadValues({
typeName: ZodFirstPartyTypeKind.ZodSymbol
}, processCreateParams(params)));
};
var ZodUndefined = class extends ZodType {
_parse(input) {
const parsedType = this._getType(input);
if (parsedType !== ZodParsedType.undefined) {
const ctx = this._getOrReturnCtx(input);
addIssueToContext(ctx, {
code: ZodIssueCode.invalid_type,
expected: ZodParsedType.undefined,
received: ctx.parsedType
});
return INVALID;
}
return OK(input.data);
}
};
ZodUndefined.create = (params) => {
return new ZodUndefined(__spreadValues({
typeName: ZodFirstPartyTypeKind.ZodUndefined
}, processCreateParams(params)));
};
var ZodNull = class extends ZodType {
_parse(input) {
const parsedType = this._getType(input);
if (parsedType !== ZodParsedType.null) {
const ctx = this._getOrReturnCtx(input);
addIssueToContext(ctx, {
code: ZodIssueCode.invalid_type,
expected: ZodParsedType.null,
received: ctx.parsedType
});
return INVALID;
}
return OK(input.data);
}
};
ZodNull.create = (params) => {
return new ZodNull(__spreadValues({
typeName: ZodFirstPartyTypeKind.ZodNull
}, processCreateParams(params)));
};
var ZodAny = class extends ZodType {
constructor() {
super(...arguments);
this._any = true;
}
_parse(input) {
return OK(input.data);
}
};
ZodAny.create = (params) => {
return new ZodAny(__spreadValues({
typeName: ZodFirstPartyTypeKind.ZodAny
}, processCreateParams(params)));
};
var ZodUnknown = class extends ZodType {
constructor() {
super(...arguments);
this._unknown = true;
}
_parse(input) {
return OK(input.data);
}
};
ZodUnknown.create = (params) => {
return new ZodUnknown(__spreadValues({
typeName: ZodFirstPartyTypeKind.ZodUnknown
}, processCreateParams(params)));
};
var ZodNever = class extends ZodType {
_parse(input) {
const ctx = this._getOrReturnCtx(input);
addIssueToContext(ctx, {
code: ZodIssueCode.invalid_type,
expected: ZodParsedType.never,
received: ctx.parsedType
});
return INVALID;
}
};
ZodNever.create = (params) => {
return new ZodNever(__spreadValues({
typeName: ZodFirstPartyTypeKind.ZodNever
}, processCreateParams(params)));
};
var ZodVoid = class extends ZodType {
_parse(input) {
const parsedType = this._getType(input);
if (parsedType !== ZodParsedType.undefined) {
const ctx = this._getOrReturnCtx(input);
addIssueToContext(ctx, {
code: ZodIssueCode.invalid_type,
expected: ZodParsedType.void,
received: ctx.parsedType
});
return INVALID;
}
return OK(input.data);
}
};
ZodVoid.create = (params) => {
return new ZodVoid(__spreadValues({
typeName: ZodFirstPartyTypeKind.ZodVoid
}, processCreateParams(params)));
};
var ZodArray = class _ZodArray extends ZodType {
_parse(input) {
const { ctx, status } = this._processInputParams(input);
const def = this._def;
if (ctx.parsedType !== ZodParsedType.array) {
addIssueToContext(ctx, {
code: ZodIssueCode.invalid_type,
expected: ZodParsedType.array,
received: ctx.parsedType
});
return INVALID;
}
if (def.exactLength !== null) {
const tooBig = ctx.data.length > def.exactLength.value;
const tooSmall = ctx.data.length < def.exactLength.value;
if (tooBig || tooSmall) {
addIssueToContext(ctx, {
code: tooBig ? ZodIssueCode.too_big : ZodIssueCode.too_small,
minimum: tooSmall ? def.exactLength.value : void 0,
maximum: tooBig ? def.exactLength.value : void 0,
type: "array",
inclusive: true,
exact: true,
message: def.exactLength.message
});
status.dirty();
}
}
if (def.minLength !== null) {
if (ctx.data.length < def.minLength.value) {
addIssueToContext(ctx, {
code: ZodIssueCode.too_small,
minimum: def.minLength.value,
type: "array",
inclusive: true,
exact: false,
message: def.minLength.message
});
status.dirty();
}
}
if (def.maxLength !== null) {
if (ctx.data.length > def.maxLength.value) {
addIssueToContext(ctx, {
code: ZodIssueCode.too_big,
maximum: def.maxLength.value,
type: "array",
inclusive: true,
exact: false,
message: def.maxLength.message
});
status.dirty();
}
}
if (ctx.common.async) {
return Promise.all([...ctx.data].map((item, i) => {
return def.type._parseAsync(new ParseInputLazyPath(ctx, item, ctx.path, i));
})).then((result3) => {
return ParseStatus.mergeArray(status, result3);
});
}
const result2 = [...ctx.data].map((item, i) => {
return def.type._parseSync(new ParseInputLazyPath(ctx, item, ctx.path, i));
});
return ParseStatus.mergeArray(status, result2);
}
get element() {
return this._def.type;
}
min(minLength, message) {
return new _ZodArray(__spreadProps(__spreadValues({}, this._def), {
minLength: { value: minLength, message: errorUtil.toString(message) }
}));
}
max(maxLength, message) {
return new _ZodArray(__spreadProps(__spreadValues({}, this._def), {
maxLength: { value: maxLength, message: errorUtil.toString(message) }
}));
}
length(len, message) {
return new _ZodArray(__spreadProps(__spreadValues({}, this._def), {
exactLength: { value: len, message: errorUtil.toString(message) }
}));
}
nonempty(message) {
return this.min(1, message);
}
};
ZodArray.create = (schema, params) => {
return new ZodArray(__spreadValues({
type: schema,
minLength: null,
maxLength: null,
exactLength: null,
typeName: ZodFirstPartyTypeKind.ZodArray
}, processCreateParams(params)));
};
function deepPartialify(schema) {
if (schema instanceof ZodObject) {
const newShape = {};
for (const key in schema.shape) {
const fieldSchema = schema.shape[key];
newShape[key] = ZodOptional.create(deepPartialify(fieldSchema));
}
return new ZodObject(__spreadProps(__spreadValues({}, schema._def), {
shape: () => newShape
}));
} else if (schema instanceof ZodArray) {
return new ZodArray(__spreadProps(__spreadValues({}, schema._def), {
type: deepPartialify(schema.element)
}));
} else if (schema instanceof ZodOptional) {
return ZodOptional.create(deepPartialify(schema.unwrap()));
} else if (schema instanceof ZodNullable) {
return ZodNullable.create(deepPartialify(schema.unwrap()));
} else if (schema instanceof ZodTuple) {
return ZodTuple.create(schema.items.map((item) => deepPartialify(item)));
} else {
return schema;
}
}
var ZodObject = class _ZodObject extends ZodType {
constructor() {
super(...arguments);
this._cached = null;
this.nonstrict = this.passthrough;
this.augment = this.extend;
}
_getCached() {
if (this._cached !== null)
return this._cached;
const shape = this._def.shape();
const keys = util.objectKeys(shape);
this._cached = { shape, keys };
return this._cached;
}
_parse(input) {
const parsedType = this._getType(input);
if (parsedType !== ZodParsedType.object) {
const ctx2 = this._getOrReturnCtx(input);
addIssueToContext(ctx2, {
code: ZodIssueCode.invalid_type,
expected: ZodParsedType.object,
received: ctx2.parsedType
});
return INVALID;
}
const { status, ctx } = this._processInputParams(input);
const { shape, keys: shapeKeys } = this._getCached();
const extraKeys = [];
if (!(this._def.catchall instanceof ZodNever && this._def.unknownKeys === "strip")) {
for (const key in ctx.data) {
if (!shapeKeys.includes(key)) {
extraKeys.push(key);
}
}
}
const pairs = [];
for (const key of shapeKeys) {
const keyValidator = shape[key];
const value = ctx.data[key];
pairs.push({
key: { status: "valid", value: key },
value: keyValidator._parse(new ParseInputLazyPath(ctx, value, ctx.path, key)),
alwaysSet: key in ctx.data
});
}
if (this._def.catchall instanceof ZodNever) {
const unknownKeys = this._def.unknownKeys;
if (unknownKeys === "passthrough") {
for (const key of extraKeys) {
pairs.push({
key: { status: "valid", value: key },
value: { status: "valid", value: ctx.data[key] }
});
}
} else if (unknownKeys === "strict") {
if (extraKeys.length > 0) {
addIssueToContext(ctx, {
code: ZodIssueCode.unrecognized_keys,
keys: extraKeys
});
status.dirty();
}
} else if (unknownKeys === "strip") {
} else {
throw new Error(`Internal ZodObject error: invalid unknownKeys value.`);
}
} else {
const catchall = this._def.catchall;
for (const key of extraKeys) {
const value = ctx.data[key];
pairs.push({
key: { status: "valid", value: key },
value: catchall._parse(
new ParseInputLazyPath(ctx, value, ctx.path, key)
//, ctx.child(key), value, getParsedType(value)
),
alwaysSet: key in ctx.data
});
}
}
if (ctx.common.async) {
return Promise.resolve().then(() => __async(this, null, function* () {
const syncPairs = [];
for (const pair of pairs) {
const key = yield pair.key;
const value = yield pair.value;
syncPairs.push({
key,
value,
alwaysSet: pair.alwaysSet
});
}
return syncPairs;
})).then((syncPairs) => {
return ParseStatus.mergeObjectSync(status, syncPairs);
});
} else {
return ParseStatus.mergeObjectSync(status, pairs);
}
}
get shape() {
return this._def.shape();
}
strict(message) {
errorUtil.errToObj;
return new _ZodObject(__spreadValues(__spreadProps(__spreadValues({}, this._def), {
unknownKeys: "strict"
}), message !== void 0 ? {
errorMap: (issue, ctx) => {
var _a2, _b2, _c, _d;
const defaultError = (_c = (_b2 = (_a2 = this._def).errorMap) == null ? void 0 : _b2.call(_a2, issue, ctx).message) != null ? _c : ctx.defaultError;
if (issue.code === "unrecognized_keys")
return {
message: (_d = errorUtil.errToObj(message).message) != null ? _d : defaultError
};
return {
message: defaultError
};
}
} : {}));
}
strip() {
return new _ZodObject(__spreadProps(__spreadValues({}, this._def), {
unknownKeys: "strip"
}));
}
passthrough() {
return new _ZodObject(__spreadProps(__spreadValues({}, this._def), {
unknownKeys: "passthrough"
}));
}
// const AugmentFactory =
// <Def extends ZodObjectDef>(def: Def) =>
// <Augmentation extends ZodRawShape>(
// augmentation: Augmentation
// ): ZodObject<
// extendShape<ReturnType<Def["shape"]>, Augmentation>,
// Def["unknownKeys"],
// Def["catchall"]
// > => {
// return new ZodObject({
// ...def,
// shape: () => ({
// ...def.shape(),
// ...augmentation,
// }),
// }) as any;
// };
extend(augmentation) {
return new _ZodObject(__spreadProps(__spreadValues({}, this._def), {
shape: () => __spreadValues(__spreadValues({}, this._def.shape()), augmentation)
}));
}
/**
* Prior to zod@1.0.12 there was a bug in the
* inferred type of merged objects. Please
* upgrade if you are experiencing issues.
*/
merge(merging) {
const merged = new _ZodObject({
unknownKeys: merging._def.unknownKeys,
catchall: merging._def.catchall,
shape: () => __spreadValues(__spreadValues({}, this._def.shape()), merging._def.shape()),
typeName: ZodFirstPartyTypeKind.ZodObject
});
return merged;
}
// merge<
// Incoming extends AnyZodObject,
// Augmentation extends Incoming["shape"],
// NewOutput extends {
// [k in keyof Augmentation | keyof Output]: k extends keyof Augmentation
// ? Augmentation[k]["_output"]
// : k extends keyof Output
// ? Output[k]
// : never;
// },
// NewInput extends {
// [k in keyof Augmentation | keyof Input]: k extends keyof Augmentation
// ? Augmentation[k]["_input"]
// : k extends keyof Input
// ? Input[k]
// : never;
// }
// >(
// merging: Incoming
// ): ZodObject<
// extendShape<T, ReturnType<Incoming["_def"]["shape"]>>,
// Incoming["_def"]["unknownKeys"],
// Incoming["_def"]["catchall"],
// NewOutput,
// NewInput
// > {
// const merged: any = new ZodObject({
// unknownKeys: merging._def.unknownKeys,
// catchall: merging._def.catchall,
// shape: () =>
// objectUtil.mergeShapes(this._def.shape(), merging._def.shape()),
// typeName: ZodFirstPartyTypeKind.ZodObject,
// }) as any;
// return merged;
// }
setKey(key, schema) {
return this.augment({ [key]: schema });
}
// merge<Incoming extends AnyZodObject>(
// merging: Incoming
// ): //ZodObject<T & Incoming["_shape"], UnknownKeys, Catchall> = (merging) => {
// ZodObject<
// extendShape<T, ReturnType<Incoming["_def"]["shape"]>>,
// Incoming["_def"]["unknownKeys"],
// Incoming["_def"]["catchall"]
// > {
// // const mergedShape = objectUtil.mergeShapes(
// // this._def.shape(),
// // merging._def.shape()
// // );
// const merged: any = new ZodObject({
// unknownKeys: merging._def.unknownKeys,
// catchall: merging._def.catchall,
// shape: () =>
// objectUtil.mergeShapes(this._def.shape(), merging._def.shape()),
// typeName: ZodFirstPartyTypeKind.ZodObject,
// }) as any;
// return merged;
// }
catchall(index) {
return new _ZodObject(__spreadProps(__spreadValues({}, this._def), {
catchall: index
}));
}
pick(mask) {
const shape = {};
for (const key of util.objectKeys(mask)) {
if (mask[key] && this.shape[key]) {
shape[key] = this.shape[key];
}
}
return new _ZodObject(__spreadProps(__spreadValues({}, this._def), {
shape: () => shape
}));
}
omit(mask) {
const shape = {};
for (const key of util.objectKeys(this.shape)) {
if (!mask[key]) {
shape[key] = this.shape[key];
}
}
return new _ZodObject(__spreadProps(__spreadValues({}, this._def), {
shape: () => shape
}));
}
/**
* @deprecated
*/
deepPartial() {
return deepPartialify(this);
}
partial(mask) {
const newShape = {};
for (const key of util.objectKeys(this.shape)) {
const fieldSchema = this.shape[key];
if (mask && !mask[key]) {
newShape[key] = fieldSchema;
} else {
newShape[key] = fieldSchema.optional();
}
}
return new _ZodObject(__spreadProps(__spreadValues({}, this._def), {
shape: () => newShape
}));
}
required(mask) {
const newShape = {};
for (const key of util.objectKeys(this.shape)) {
if (mask && !mask[key]) {
newShape[key] = this.shape[key];
} else {
const fieldSchema = this.shape[key];
let newField = fieldSchema;
while (newField instanceof ZodOptional) {
newField = newField._def.innerType;
}
newShape[key] = newField;
}
}
return new _ZodObject(__spreadProps(__spreadValues({}, this._def), {
shape: () => newShape
}));
}
keyof() {
return createZodEnum(util.objectKeys(this.shape));
}
};
ZodObject.create = (shape, params) => {
return new ZodObject(__spreadValues({
shape: () => shape,
unknownKeys: "strip",
catchall: ZodNever.create(),
typeName: ZodFirstPartyTypeKind.ZodObject
}, processCreateParams(params)));
};
ZodObject.strictCreate = (shape, params) => {
return new ZodObject(__spreadValues({
shape: () => shape,
unknownKeys: "strict",
catchall: ZodNever.create(),
typeName: ZodFirstPartyTypeKind.ZodObject
}, processCreateParams(params)));
};
ZodObject.lazycreate = (shape, params) => {
return new ZodObject(__spreadValues({
shape,
unknownKeys: "strip",
catchall: ZodNever.create(),
typeName: ZodFirstPartyTypeKind.ZodObject
}, processCreateParams(params)));
};
var ZodUnion = class extends ZodType {
_parse(input) {
const { ctx } = this._processInputParams(input);
const options = this._def.options;
function handleResults(results) {
for (const result2 of results) {
if (result2.result.status === "valid") {
return result2.result;
}
}
for (const result2 of results) {
if (result2.result.status === "dirty") {
ctx.common.issues.push(...result2.ctx.common.issues);
return result2.result;
}
}
const unionErrors = results.map((result2) => new ZodError(result2.ctx.common.issues));
addIssueToContext(ctx, {
code: ZodIssueCode.invalid_union,
unionErrors
});
return INVALID;
}
if (ctx.common.async) {
return Promise.all(options.map((option) => __async(this, null, function* () {
const childCtx = __spreadProps(__spreadValues({}, ctx), {
common: __spreadProps(__spreadValues({}, ctx.common), {
issues: []
}),
parent: null
});
return {
result: yield option._parseAsync({
data: ctx.data,
path: ctx.path,
parent: childCtx
}),
ctx: childCtx
};
}))).then(handleResults);
} else {
let dirty = void 0;
const issues = [];
for (const option of options) {
const childCtx = __spreadProps(__spreadValues({}, ctx), {
common: __spreadProps(__spreadValues({}, ctx.common), {
issues: []
}),
parent: null
});
const result2 = option._parseSync({
data: ctx.data,
path: ctx.path,
parent: childCtx
});
if (result2.status === "valid") {
return result2;
} else if (result2.status === "dirty" && !dirty) {
dirty = { result: result2, ctx: childCtx };
}
if (childCtx.common.issues.length) {
issues.push(childCtx.common.issues);
}
}
if (dirty) {
ctx.common.issues.push(...dirty.ctx.common.issues);
return dirty.result;
}
const unionErrors = issues.map((issues2) => new ZodError(issues2));
addIssueToContext(ctx, {
code: ZodIssueCode.invalid_union,
unionErrors
});
return INVALID;
}
}
get options() {
return this._def.options;
}
};
ZodUnion.create = (types, params) => {
return new ZodUnion(__spreadValues({
options: types,
typeName: ZodFirstPartyTypeKind.ZodUnion
}, processCreateParams(params)));
};
var getDiscriminator = (type) => {
if (type instanceof ZodLazy) {
return getDiscriminator(type.schema);
} else if (type instanceof ZodEffects) {
return getDiscriminator(type.innerType());
} else if (type instanceof ZodLiteral) {
return [type.value];
} else if (type instanceof ZodEnum) {
return type.options;
} else if (type instanceof ZodNativeEnum) {
return util.objectValues(type.enum);
} else if (type instanceof ZodDefault) {
return getDiscriminator(type._def.innerType);
} else if (type instanceof ZodUndefined) {
return [void 0];
} else if (type instanceof ZodNull) {
return [null];
} else if (type instanceof ZodOptional) {
return [void 0, ...getDiscriminator(type.unwrap())];
} else if (type instanceof ZodNullable) {
return [null, ...getDiscriminator(type.unwrap())];
} else if (type instanceof ZodBranded) {
return getDiscriminator(type.unwrap());
} else if (type instanceof ZodReadonly) {
return getDiscriminator(type.unwrap());
} else if (type instanceof ZodCatch) {
return getDiscriminator(type._def.innerType);
} else {
return [];
}
};
var ZodDiscriminatedUnion = class _ZodDiscriminatedUnion extends ZodType {
_parse(input) {
const { ctx } = this._processInputParams(input);
if (ctx.parsedType !== ZodParsedType.object) {
addIssueToContext(ctx, {
code: ZodIssueCode.invalid_type,
expected: ZodParsedType.object,
received: ctx.parsedType
});
return INVALID;
}
const discriminator = this.discriminator;
const discriminatorValue = ctx.data[discriminator];
const option = this.optionsMap.get(discriminatorValue);
if (!option) {
addIssueToContext(ctx, {
code: ZodIssueCode.invalid_union_discriminator,
options: Array.from(this.optionsMap.keys()),
path: [discriminator]
});
return INVALID;
}
if (ctx.common.async) {
return option._parseAsync({
data: ctx.data,
path: ctx.path,
parent: ctx
});
} else {
return option._parseSync({
data: ctx.data,
path: ctx.path,
parent: ctx
});
}
}
get discriminator() {
return this._def.discriminator;
}
get options() {
return this._def.options;
}
get optionsMap() {
return this._def.optionsMap;
}
/**
* The constructor of the discriminated union schema. Its behaviour is very similar to that of the normal z.union() constructor.
* However, it only allows a union of objects, all of which need to share a discriminator property. This property must
* have a different value for each object in the union.
* @param discriminator the name of the discriminator property
* @param types an array of object schemas
* @param params
*/
static create(discriminator, options, params) {
const optionsMap = /* @__PURE__ */ new Map();
for (const type of options) {
const discriminatorValues = getDiscriminator(type.shape[discriminator]);
if (!discriminatorValues.length) {
throw new Error(`A discriminator value for key \`${discriminator}\` could not be extracted from all schema options`);
}
for (const value of discriminatorValues) {
if (optionsMap.has(value)) {
throw new Error(`Discriminator property ${String(discriminator)} has duplicate value ${String(value)}`);
}
optionsMap.set(value, type);
}
}
return new _ZodDiscriminatedUnion(__spreadValues({
typeName: ZodFirstPartyTypeKind.ZodDiscriminatedUnion,
discriminator,
options,
optionsMap
}, processCreateParams(params)));
}
};
function mergeValues(a, b) {
const aType = getParsedType(a);
const bType = getParsedType(b);
if (a === b) {
return { valid: true, data: a };
} else if (aType === ZodParsedType.object && bType === ZodParsedType.object) {
const bKeys = util.objectKeys(b);
const sharedKeys = util.objectKeys(a).filter((key) => bKeys.indexOf(key) !== -1);
const newObj = __spreadValues(__spreadValues({}, a), b);
for (const key of sharedKeys) {
const sharedValue = mergeValues(a[key], b[key]);
if (!sharedValue.valid) {
return { valid: false };
}
newObj[key] = sharedValue.data;
}
return { valid: true, data: newObj };
} else if (aType === ZodParsedType.array && bType === ZodParsedType.array) {
if (a.length !== b.length) {
return { valid: false };
}
const newArray = [];
for (let index = 0; index < a.length; index++) {
const itemA = a[index];
const itemB = b[index];
const sharedValue = mergeValues(itemA, itemB);
if (!sharedValue.valid) {
return { valid: false };
}
newArray.push(sharedValue.data);
}
return { valid: true, data: newArray };
} else if (aType === ZodParsedType.date && bType === ZodParsedType.date && +a === +b) {
return { valid: true, data: a };
} else {
return { valid: false };
}
}
var ZodIntersection = class extends ZodType {
_parse(input) {
const { status, ctx } = this._processInputParams(input);
const handleParsed = (parsedLeft, parsedRight) => {
if (isAborted(parsedLeft) || isAborted(parsedRight)) {
return INVALID;
}
const merged = mergeValues(parsedLeft.value, parsedRight.value);
if (!merged.valid) {
addIssueToContext(ctx, {
code: ZodIssueCode.invalid_intersection_types
});
return INVALID;
}
if (isDirty(parsedLeft) || isDirty(parsedRight)) {
status.dirty();
}
return { status: status.value, value: merged.data };
};
if (ctx.common.async) {
return Promise.all([
this._def.left._parseAsync({
data: ctx.data,
path: ctx.path,
parent: ctx
}),
this._def.right._parseAsync({
data: ctx.data,
path: ctx.path,
parent: ctx
})
]).then(([left, right]) => handleParsed(left, right));
} else {
return handleParsed(this._def.left._parseSync({
data: ctx.data,
path: ctx.path,
parent: ctx
}), this._def.right._parseSync({
data: ctx.data,
path: ctx.path,
parent: ctx
}));
}
}
};
ZodIntersection.create = (left, right, params) => {
return new ZodIntersection(__spreadValues({
left,
right,
typeName: ZodFirstPartyTypeKind.ZodIntersection
}, processCreateParams(params)));
};
var ZodTuple = class _ZodTuple extends ZodType {
_parse(input) {
const { status, ctx } = this._processInputParams(input);
if (ctx.parsedType !== ZodParsedType.array) {
addIssueToContext(ctx, {
code: ZodIssueCode.invalid_type,
expected: ZodParsedType.array,
received: ctx.parsedType
});
return INVALID;
}
if (ctx.data.length < this._def.items.length) {
addIssueToContext(ctx, {
code: ZodIssueCode.too_small,
minimum: this._def.items.length,
inclusive: true,
exact: false,
type: "array"
});
return INVALID;
}
const rest = this._def.rest;
if (!rest && ctx.data.length > this._def.items.length) {
addIssueToContext(ctx, {
code: ZodIssueCode.too_big,
maximum: this._def.items.length,
inclusive: true,
exact: false,
type: "array"
});
status.dirty();
}
const items = [...ctx.data].map((item, itemIndex) => {
const schema = this._def.items[itemIndex] || this._def.rest;
if (!schema)
return null;
return schema._parse(new ParseInputLazyPath(ctx, item, ctx.path, itemIndex));
}).filter((x) => !!x);
if (ctx.common.async) {
return Promise.all(items).then((results) => {
return ParseStatus.mergeArray(status, results);
});
} else {
return ParseStatus.mergeArray(status, items);
}
}
get items() {
return this._def.items;
}
rest(rest) {
return new _ZodTuple(__spreadProps(__spreadValues({}, this._def), {
rest
}));
}
};
ZodTuple.create = (schemas, params) => {
if (!Array.isArray(schemas)) {
throw new Error("You must pass an array of schemas to z.tuple([ ... ])");
}
return new ZodTuple(__spreadValues({
items: schemas,
typeName: ZodFirstPartyTypeKind.ZodTuple,
rest: null
}, processCreateParams(params)));
};
var ZodRecord = class _ZodRecord extends ZodType {
get keySchema() {
return this._def.keyType;
}
get valueSchema() {
return this._def.valueType;
}
_parse(input) {
const { status, ctx } = this._processInputParams(input);
if (ctx.parsedType !== ZodParsedType.object) {
addIssueToContext(ctx, {
code: ZodIssueCode.invalid_type,
expected: ZodParsedType.object,
received: ctx.parsedType
});
return INVALID;
}
const pairs = [];
const keyType = this._def.keyType;
const valueType = this._def.valueType;
for (const key in ctx.data) {
pairs.push({
key: keyType._parse(new ParseInputLazyPath(ctx, key, ctx.path, key)),
value: valueType._parse(new ParseInputLazyPath(ctx, ctx.data[key], ctx.path, key)),
alwaysSet: key in ctx.data
});
}
if (ctx.common.async) {
return ParseStatus.mergeObjectAsync(status, pairs);
} else {
return ParseStatus.mergeObjectSync(status, pairs);
}
}
get element() {
return this._def.valueType;
}
static create(first, second, third) {
if (second instanceof ZodType) {
return new _ZodRecord(__spreadValues({
keyType: first,
valueType: second,
typeName: ZodFirstPartyTypeKind.ZodRecord
}, processCreateParams(third)));
}
return new _ZodRecord(__spreadValues({
keyType: ZodString.create(),
valueType: first,
typeName: ZodFirstPartyTypeKind.ZodRecord
}, processCreateParams(second)));
}
};
var ZodMap = class extends ZodType {
get keySchema() {
return this._def.keyType;
}
get valueSchema() {
return this._def.valueType;
}
_parse(input) {
const { status, ctx } = this._processInputParams(input);
if (ctx.parsedType !== ZodParsedType.map) {
addIssueToContext(ctx, {
code: ZodIssueCode.invalid_type,
expected: ZodParsedType.map,
received: ctx.parsedType
});
return INVALID;
}
const keyType = this._def.keyType;
const valueType = this._def.valueType;
const pairs = [...ctx.data.entries()].map(([key, value], index) => {
return {
key: keyType._parse(new ParseInputLazyPath(ctx, key, ctx.path, [index, "key"])),
value: valueType._parse(new ParseInputLazyPath(ctx, value, ctx.path, [index, "value"]))
};
});
if (ctx.common.async) {
const finalMap = /* @__PURE__ */ new Map();
return Promise.resolve().then(() => __async(this, null, function* () {
for (const pair of pairs) {
const key = yield pair.key;
const value = yield pair.value;
if (key.status === "aborted" || value.status === "aborted") {
return INVALID;
}
if (key.status === "dirty" || value.status === "dirty") {
status.dirty();
}
finalMap.set(key.value, value.value);
}
return { status: status.value, value: finalMap };
}));
} else {
const finalMap = /* @__PURE__ */ new Map();
for (const pair of pairs) {
const key = pair.key;
const value = pair.value;
if (key.status === "aborted" || value.status === "aborted") {
return INVALID;
}
if (key.status === "dirty" || value.status === "dirty") {
status.dirty();
}
finalMap.set(key.value, value.value);
}
return { status: status.value, value: finalMap };
}
}
};
ZodMap.create = (keyType, valueType, params) => {
return new ZodMap(__spreadValues({
valueType,
keyType,
typeName: ZodFirstPartyTypeKind.ZodMap
}, processCreateParams(params)));
};
var ZodSet = class _ZodSet extends ZodType {
_parse(input) {
const { status, ctx } = this._processInputParams(input);
if (ctx.parsedType !== ZodParsedType.set) {
addIssueToContext(ctx, {
code: ZodIssueCode.invalid_type,
expected: ZodParsedType.set,
received: ctx.parsedType
});
return INVALID;
}
const def = this._def;
if (def.minSize !== null) {
if (ctx.data.size < def.minSize.value) {
addIssueToContext(ctx, {
code: ZodIssueCode.too_small,
minimum: def.minSize.value,
type: "set",
inclusive: true,
exact: false,
message: def.minSize.message
});
status.dirty();
}
}
if (def.maxSize !== null) {
if (ctx.data.size > def.maxSize.value) {
addIssueToContext(ctx, {
code: ZodIssueCode.too_big,
maximum: def.maxSize.value,
type: "set",
inclusive: true,
exact: false,
message: def.maxSize.message
});
status.dirty();
}
}
const valueType = this._def.valueType;
function finalizeSet(elements2) {
const parsedSet = /* @__PURE__ */ new Set();
for (const element of elements2) {
if (element.status === "aborted")
return INVALID;
if (element.status === "dirty")
status.dirty();
parsedSet.add(element.value);
}
return { status: status.value, value: parsedSet };
}
const elements = [...ctx.data.values()].map((item, i) => valueType._parse(new ParseInputLazyPath(ctx, item, ctx.path, i)));
if (ctx.common.async) {
return Promise.all(elements).then((elements2) => finalizeSet(elements2));
} else {
return finalizeSet(elements);
}
}
min(minSize, message) {
return new _ZodSet(__spreadProps(__spreadValues({}, this._def), {
minSize: { value: minSize, message: errorUtil.toString(message) }
}));
}
max(maxSize, message) {
return new _ZodSet(__spreadProps(__spreadValues({}, this._def), {
maxSize: { value: maxSize, message: errorUtil.toString(message) }
}));
}
size(size, message) {
return this.min(size, message).max(size, message);
}
nonempty(message) {
return this.min(1, message);
}
};
ZodSet.create = (valueType, params) => {
return new ZodSet(__spreadValues({
valueType,
minSize: null,
maxSize: null,
typeName: ZodFirstPartyTypeKind.ZodSet
}, processCreateParams(params)));
};
var ZodFunction = class _ZodFunction extends ZodType {
constructor() {
super(...arguments);
this.validate = this.implement;
}
_parse(input) {
const { ctx } = this._processInputParams(input);
if (ctx.parsedType !== ZodParsedType.function) {
addIssueToContext(ctx, {
code: ZodIssueCode.invalid_type,
expected: ZodParsedType.function,
received: ctx.parsedType
});
return INVALID;
}
function makeArgsIssue(args, error) {
return makeIssue({
data: args,
path: ctx.path,
errorMaps: [ctx.common.contextualErrorMap, ctx.schemaErrorMap, getErrorMap(), en_default].filter((x) => !!x),
issueData: {
code: ZodIssueCode.invalid_arguments,
argumentsError: error
}
});
}
function makeReturnsIssue(returns, error) {
return makeIssue({
data: returns,
path: ctx.path,
errorMaps: [ctx.common.contextualErrorMap, ctx.schemaErrorMap, getErrorMap(), en_default].filter((x) => !!x),
issueData: {
code: ZodIssueCode.invalid_return_type,
returnTypeError: error
}
});
}
const params = { errorMap: ctx.common.contextualErrorMap };
const fn = ctx.data;
if (this._def.returns instanceof ZodPromise) {
const me = this;
return OK(function(...args) {
return __async(this, null, function* () {
const error = new ZodError([]);
const parsedArgs = yield me._def.args.parseAsync(args, params).catch((e2) => {
error.addIssue(makeArgsIssue(args, e2));
throw error;
});
const result2 = yield Reflect.apply(fn, this, parsedArgs);
const parsedReturns = yield me._def.returns._def.type.parseAsync(result2, params).catch((e2) => {
error.addIssue(makeReturnsIssue(result2, e2));
throw error;
});
return parsedReturns;
});
});
} else {
const me = this;
return OK(function(...args) {
const parsedArgs = me._def.args.safeParse(args, params);
if (!parsedArgs.success) {
throw new ZodError([makeArgsIssue(args, parsedArgs.error)]);
}
const result2 = Reflect.apply(fn, this, parsedArgs.data);
const parsedReturns = me._def.returns.safeParse(result2, params);
if (!parsedReturns.success) {
throw new ZodError([makeReturnsIssue(result2, parsedReturns.error)]);
}
return parsedReturns.data;
});
}
}
parameters() {
return this._def.args;
}
returnType() {
return this._def.returns;
}
args(...items) {
return new _ZodFunction(__spreadProps(__spreadValues({}, this._def), {
args: ZodTuple.create(items).rest(ZodUnknown.create())
}));
}
returns(returnType) {
return new _ZodFunction(__spreadProps(__spreadValues({}, this._def), {
returns: returnType
}));
}
implement(func) {
const validatedFunc = this.parse(func);
return validatedFunc;
}
strictImplement(func) {
const validatedFunc = this.parse(func);
return validatedFunc;
}
static create(args, returns, params) {
return new _ZodFunction(__spreadValues({
args: args ? args : ZodTuple.create([]).rest(ZodUnknown.create()),
returns: returns || ZodUnknown.create(),
typeName: ZodFirstPartyTypeKind.ZodFunction
}, processCreateParams(params)));
}
};
var ZodLazy = class extends ZodType {
get schema() {
return this._def.getter();
}
_parse(input) {
const { ctx } = this._processInputParams(input);
const lazySchema = this._def.getter();
return lazySchema._parse({ data: ctx.data, path: ctx.path, parent: ctx });
}
};
ZodLazy.create = (getter, params) => {
return new ZodLazy(__spreadValues({
getter,
typeName: ZodFirstPartyTypeKind.ZodLazy
}, processCreateParams(params)));
};
var ZodLiteral = class extends ZodType {
_parse(input) {
if (input.data !== this._def.value) {
const ctx = this._getOrReturnCtx(input);
addIssueToContext(ctx, {
received: ctx.data,
code: ZodIssueCode.invalid_literal,
expected: this._def.value
});
return INVALID;
}
return { status: "valid", value: input.data };
}
get value() {
return this._def.value;
}
};
ZodLiteral.create = (value, params) => {
return new ZodLiteral(__spreadValues({
value,
typeName: ZodFirstPartyTypeKind.ZodLiteral
}, processCreateParams(params)));
};
function createZodEnum(values, params) {
return new ZodEnum(__spreadValues({
values,
typeName: ZodFirstPartyTypeKind.ZodEnum
}, processCreateParams(params)));
}
var ZodEnum = class _ZodEnum extends ZodType {
_parse(input) {
if (typeof input.data !== "string") {
const ctx = this._getOrReturnCtx(input);
const expectedValues = this._def.values;
addIssueToContext(ctx, {
expected: util.joinValues(expectedValues),
received: ctx.parsedType,
code: ZodIssueCode.invalid_type
});
return INVALID;
}
if (!this._cache) {
this._cache = new Set(this._def.values);
}
if (!this._cache.has(input.data)) {
const ctx = this._getOrReturnCtx(input);
const expectedValues = this._def.values;
addIssueToContext(ctx, {
received: ctx.data,
code: ZodIssueCode.invalid_enum_value,
options: expectedValues
});
return INVALID;
}
return OK(input.data);
}
get options() {
return this._def.values;
}
get enum() {
const enumValues = {};
for (const val of this._def.values) {
enumValues[val] = val;
}
return enumValues;
}
get Values() {
const enumValues = {};
for (const val of this._def.values) {
enumValues[val] = val;
}
return enumValues;
}
get Enum() {
const enumValues = {};
for (const val of this._def.values) {
enumValues[val] = val;
}
return enumValues;
}
extract(values, newDef = this._def) {
return _ZodEnum.create(values, __spreadValues(__spreadValues({}, this._def), newDef));
}
exclude(values, newDef = this._def) {
return _ZodEnum.create(this.options.filter((opt) => !values.includes(opt)), __spreadValues(__spreadValues({}, this._def), newDef));
}
};
ZodEnum.create = createZodEnum;
var ZodNativeEnum = class extends ZodType {
_parse(input) {
const nativeEnumValues = util.getValidEnumValues(this._def.values);
const ctx = this._getOrReturnCtx(input);
if (ctx.parsedType !== ZodParsedType.string && ctx.parsedType !== ZodParsedType.number) {
const expectedValues = util.objectValues(nativeEnumValues);
addIssueToContext(ctx, {
expected: util.joinValues(expectedValues),
received: ctx.parsedType,
code: ZodIssueCode.invalid_type
});
return INVALID;
}
if (!this._cache) {
this._cache = new Set(util.getValidEnumValues(this._def.values));
}
if (!this._cache.has(input.data)) {
const expectedValues = util.objectValues(nativeEnumValues);
addIssueToContext(ctx, {
received: ctx.data,
code: ZodIssueCode.invalid_enum_value,
options: expectedValues
});
return INVALID;
}
return OK(input.data);
}
get enum() {
return this._def.values;
}
};
ZodNativeEnum.create = (values, params) => {
return new ZodNativeEnum(__spreadValues({
values,
typeName: ZodFirstPartyTypeKind.ZodNativeEnum
}, processCreateParams(params)));
};
var ZodPromise = class extends ZodType {
unwrap() {
return this._def.type;
}
_parse(input) {
const { ctx } = this._processInputParams(input);
if (ctx.parsedType !== ZodParsedType.promise && ctx.common.async === false) {
addIssueToContext(ctx, {
code: ZodIssueCode.invalid_type,
expected: ZodParsedType.promise,
received: ctx.parsedType
});
return INVALID;
}
const promisified = ctx.parsedType === ZodParsedType.promise ? ctx.data : Promise.resolve(ctx.data);
return OK(promisified.then((data) => {
return this._def.type.parseAsync(data, {
path: ctx.path,
errorMap: ctx.common.contextualErrorMap
});
}));
}
};
ZodPromise.create = (schema, params) => {
return new ZodPromise(__spreadValues({
type: schema,
typeName: ZodFirstPartyTypeKind.ZodPromise
}, processCreateParams(params)));
};
var ZodEffects = class extends ZodType {
innerType() {
return this._def.schema;
}
sourceType() {
return this._def.schema._def.typeName === ZodFirstPartyTypeKind.ZodEffects ? this._def.schema.sourceType() : this._def.schema;
}
_parse(input) {
const { status, ctx } = this._processInputParams(input);
const effect = this._def.effect || null;
const checkCtx = {
addIssue: (arg) => {
addIssueToContext(ctx, arg);
if (arg.fatal) {
status.abort();
} else {
status.dirty();
}
},
get path() {
return ctx.path;
}
};
checkCtx.addIssue = checkCtx.addIssue.bind(checkCtx);
if (effect.type === "preprocess") {
const processed = effect.transform(ctx.data, checkCtx);
if (ctx.common.async) {
return Promise.resolve(processed).then((processed2) => __async(this, null, function* () {
if (status.value === "aborted")
return INVALID;
const result2 = yield this._def.schema._parseAsync({
data: processed2,
path: ctx.path,
parent: ctx
});
if (result2.status === "aborted")
return INVALID;
if (result2.status === "dirty")
return DIRTY(result2.value);
if (status.value === "dirty")
return DIRTY(result2.value);
return result2;
}));
} else {
if (status.value === "aborted")
return INVALID;
const result2 = this._def.schema._parseSync({
data: processed,
path: ctx.path,
parent: ctx
});
if (result2.status === "aborted")
return INVALID;
if (result2.status === "dirty")
return DIRTY(result2.value);
if (status.value === "dirty")
return DIRTY(result2.value);
return result2;
}
}
if (effect.type === "refinement") {
const executeRefinement = (acc) => {
const result2 = effect.refinement(acc, checkCtx);
if (ctx.common.async) {
return Promise.resolve(result2);
}
if (result2 instanceof Promise) {
throw new Error("Async refinement encountered during synchronous parse operation. Use .parseAsync instead.");
}
return acc;
};
if (ctx.common.async === false) {
const inner = this._def.schema._parseSync({
data: ctx.data,
path: ctx.path,
parent: ctx
});
if (inner.status === "aborted")
return INVALID;
if (inner.status === "dirty")
status.dirty();
executeRefinement(inner.value);
return { status: status.value, value: inner.value };
} else {
return this._def.schema._parseAsync({ data: ctx.data, path: ctx.path, parent: ctx }).then((inner) => {
if (inner.status === "aborted")
return INVALID;
if (inner.status === "dirty")
status.dirty();
return executeRefinement(inner.value).then(() => {
return { status: status.value, value: inner.value };
});
});
}
}
if (effect.type === "transform") {
if (ctx.common.async === false) {
const base = this._def.schema._parseSync({
data: ctx.data,
path: ctx.path,
parent: ctx
});
if (!isValid(base))
return INVALID;
const result2 = effect.transform(base.value, checkCtx);
if (result2 instanceof Promise) {
throw new Error(`Asynchronous transform encountered during synchronous parse operation. Use .parseAsync instead.`);
}
return { status: status.value, value: result2 };
} else {
return this._def.schema._parseAsync({ data: ctx.data, path: ctx.path, parent: ctx }).then((base) => {
if (!isValid(base))
return INVALID;
return Promise.resolve(effect.transform(base.value, checkCtx)).then((result2) => ({
status: status.value,
value: result2
}));
});
}
}
util.assertNever(effect);
}
};
ZodEffects.create = (schema, effect, params) => {
return new ZodEffects(__spreadValues({
schema,
typeName: ZodFirstPartyTypeKind.ZodEffects,
effect
}, processCreateParams(params)));
};
ZodEffects.createWithPreprocess = (preprocess, schema, params) => {
return new ZodEffects(__spreadValues({
schema,
effect: { type: "preprocess", transform: preprocess },
typeName: ZodFirstPartyTypeKind.ZodEffects
}, processCreateParams(params)));
};
var ZodOptional = class extends ZodType {
_parse(input) {
const parsedType = this._getType(input);
if (parsedType === ZodParsedType.undefined) {
return OK(void 0);
}
return this._def.innerType._parse(input);
}
unwrap() {
return this._def.innerType;
}
};
ZodOptional.create = (type, params) => {
return new ZodOptional(__spreadValues({
innerType: type,
typeName: ZodFirstPartyTypeKind.ZodOptional
}, processCreateParams(params)));
};
var ZodNullable = class extends ZodType {
_parse(input) {
const parsedType = this._getType(input);
if (parsedType === ZodParsedType.null) {
return OK(null);
}
return this._def.innerType._parse(input);
}
unwrap() {
return this._def.innerType;
}
};
ZodNullable.create = (type, params) => {
return new ZodNullable(__spreadValues({
innerType: type,
typeName: ZodFirstPartyTypeKind.ZodNullable
}, processCreateParams(params)));
};
var ZodDefault = class extends ZodType {
_parse(input) {
const { ctx } = this._processInputParams(input);
let data = ctx.data;
if (ctx.parsedType === ZodParsedType.undefined) {
data = this._def.defaultValue();
}
return this._def.innerType._parse({
data,
path: ctx.path,
parent: ctx
});
}
removeDefault() {
return this._def.innerType;
}
};
ZodDefault.create = (type, params) => {
return new ZodDefault(__spreadValues({
innerType: type,
typeName: ZodFirstPartyTypeKind.ZodDefault,
defaultValue: typeof params.default === "function" ? params.default : () => params.default
}, processCreateParams(params)));
};
var ZodCatch = class extends ZodType {
_parse(input) {
const { ctx } = this._processInputParams(input);
const newCtx = __spreadProps(__spreadValues({}, ctx), {
common: __spreadProps(__spreadValues({}, ctx.common), {
issues: []
})
});
const result2 = this._def.innerType._parse({
data: newCtx.data,
path: newCtx.path,
parent: __spreadValues({}, newCtx)
});
if (isAsync(result2)) {
return result2.then((result3) => {
return {
status: "valid",
value: result3.status === "valid" ? result3.value : this._def.catchValue({
get error() {
return new ZodError(newCtx.common.issues);
},
input: newCtx.data
})
};
});
} else {
return {
status: "valid",
value: result2.status === "valid" ? result2.value : this._def.catchValue({
get error() {
return new ZodError(newCtx.common.issues);
},
input: newCtx.data
})
};
}
}
removeCatch() {
return this._def.innerType;
}
};
ZodCatch.create = (type, params) => {
return new ZodCatch(__spreadValues({
innerType: type,
typeName: ZodFirstPartyTypeKind.ZodCatch,
catchValue: typeof params.catch === "function" ? params.catch : () => params.catch
}, processCreateParams(params)));
};
var ZodNaN = class extends ZodType {
_parse(input) {
const parsedType = this._getType(input);
if (parsedType !== ZodParsedType.nan) {
const ctx = this._getOrReturnCtx(input);
addIssueToContext(ctx, {
code: ZodIssueCode.invalid_type,
expected: ZodParsedType.nan,
received: ctx.parsedType
});
return INVALID;
}
return { status: "valid", value: input.data };
}
};
ZodNaN.create = (params) => {
return new ZodNaN(__spreadValues({
typeName: ZodFirstPartyTypeKind.ZodNaN
}, processCreateParams(params)));
};
var BRAND = Symbol("zod_brand");
var ZodBranded = class extends ZodType {
_parse(input) {
const { ctx } = this._processInputParams(input);
const data = ctx.data;
return this._def.type._parse({
data,
path: ctx.path,
parent: ctx
});
}
unwrap() {
return this._def.type;
}
};
var ZodPipeline = class _ZodPipeline extends ZodType {
_parse(input) {
const { status, ctx } = this._processInputParams(input);
if (ctx.common.async) {
const handleAsync = () => __async(this, null, function* () {
const inResult = yield this._def.in._parseAsync({
data: ctx.data,
path: ctx.path,
parent: ctx
});
if (inResult.status === "aborted")
return INVALID;
if (inResult.status === "dirty") {
status.dirty();
return DIRTY(inResult.value);
} else {
return this._def.out._parseAsync({
data: inResult.value,
path: ctx.path,
parent: ctx
});
}
});
return handleAsync();
} else {
const inResult = this._def.in._parseSync({
data: ctx.data,
path: ctx.path,
parent: ctx
});
if (inResult.status === "aborted")
return INVALID;
if (inResult.status === "dirty") {
status.dirty();
return {
status: "dirty",
value: inResult.value
};
} else {
return this._def.out._parseSync({
data: inResult.value,
path: ctx.path,
parent: ctx
});
}
}
}
static create(a, b) {
return new _ZodPipeline({
in: a,
out: b,
typeName: ZodFirstPartyTypeKind.ZodPipeline
});
}
};
var ZodReadonly = class extends ZodType {
_parse(input) {
const result2 = this._def.innerType._parse(input);
const freeze = (data) => {
if (isValid(data)) {
data.value = Object.freeze(data.value);
}
return data;
};
return isAsync(result2) ? result2.then((data) => freeze(data)) : freeze(result2);
}
unwrap() {
return this._def.innerType;
}
};
ZodReadonly.create = (type, params) => {
return new ZodReadonly(__spreadValues({
innerType: type,
typeName: ZodFirstPartyTypeKind.ZodReadonly
}, processCreateParams(params)));
};
function cleanParams(params, data) {
const p = typeof params === "function" ? params(data) : typeof params === "string" ? { message: params } : params;
const p2 = typeof p === "string" ? { message: p } : p;
return p2;
}
function custom(check, _params = {}, fatal) {
if (check)
return ZodAny.create().superRefine((data, ctx) => {
var _a2, _b2;
const r2 = check(data);
if (r2 instanceof Promise) {
return r2.then((r3) => {
var _a3, _b3;
if (!r3) {
const params = cleanParams(_params, data);
const _fatal = (_b3 = (_a3 = params.fatal) != null ? _a3 : fatal) != null ? _b3 : true;
ctx.addIssue(__spreadProps(__spreadValues({ code: "custom" }, params), { fatal: _fatal }));
}
});
}
if (!r2) {
const params = cleanParams(_params, data);
const _fatal = (_b2 = (_a2 = params.fatal) != null ? _a2 : fatal) != null ? _b2 : true;
ctx.addIssue(__spreadProps(__spreadValues({ code: "custom" }, params), { fatal: _fatal }));
}
return;
});
return ZodAny.create();
}
var late = {
object: ZodObject.lazycreate
};
var ZodFirstPartyTypeKind;
(function(ZodFirstPartyTypeKind2) {
ZodFirstPartyTypeKind2["ZodString"] = "ZodString";
ZodFirstPartyTypeKind2["ZodNumber"] = "ZodNumber";
ZodFirstPartyTypeKind2["ZodNaN"] = "ZodNaN";
ZodFirstPartyTypeKind2["ZodBigInt"] = "ZodBigInt";
ZodFirstPartyTypeKind2["ZodBoolean"] = "ZodBoolean";
ZodFirstPartyTypeKind2["ZodDate"] = "ZodDate";
ZodFirstPartyTypeKind2["ZodSymbol"] = "ZodSymbol";
ZodFirstPartyTypeKind2["ZodUndefined"] = "ZodUndefined";
ZodFirstPartyTypeKind2["ZodNull"] = "ZodNull";
ZodFirstPartyTypeKind2["ZodAny"] = "ZodAny";
ZodFirstPartyTypeKind2["ZodUnknown"] = "ZodUnknown";
ZodFirstPartyTypeKind2["ZodNever"] = "ZodNever";
ZodFirstPartyTypeKind2["ZodVoid"] = "ZodVoid";
ZodFirstPartyTypeKind2["ZodArray"] = "ZodArray";
ZodFirstPartyTypeKind2["ZodObject"] = "ZodObject";
ZodFirstPartyTypeKind2["ZodUnion"] = "ZodUnion";
ZodFirstPartyTypeKind2["ZodDiscriminatedUnion"] = "ZodDiscriminatedUnion";
ZodFirstPartyTypeKind2["ZodIntersection"] = "ZodIntersection";
ZodFirstPartyTypeKind2["ZodTuple"] = "ZodTuple";
ZodFirstPartyTypeKind2["ZodRecord"] = "ZodRecord";
ZodFirstPartyTypeKind2["ZodMap"] = "ZodMap";
ZodFirstPartyTypeKind2["ZodSet"] = "ZodSet";
ZodFirstPartyTypeKind2["ZodFunction"] = "ZodFunction";
ZodFirstPartyTypeKind2["ZodLazy"] = "ZodLazy";
ZodFirstPartyTypeKind2["ZodLiteral"] = "ZodLiteral";
ZodFirstPartyTypeKind2["ZodEnum"] = "ZodEnum";
ZodFirstPartyTypeKind2["ZodEffects"] = "ZodEffects";
ZodFirstPartyTypeKind2["ZodNativeEnum"] = "ZodNativeEnum";
ZodFirstPartyTypeKind2["ZodOptional"] = "ZodOptional";
ZodFirstPartyTypeKind2["ZodNullable"] = "ZodNullable";
ZodFirstPartyTypeKind2["ZodDefault"] = "ZodDefault";
ZodFirstPartyTypeKind2["ZodCatch"] = "ZodCatch";
ZodFirstPartyTypeKind2["ZodPromise"] = "ZodPromise";
ZodFirstPartyTypeKind2["ZodBranded"] = "ZodBranded";
ZodFirstPartyTypeKind2["ZodPipeline"] = "ZodPipeline";
ZodFirstPartyTypeKind2["ZodReadonly"] = "ZodReadonly";
})(ZodFirstPartyTypeKind || (ZodFirstPartyTypeKind = {}));
var instanceOfType = (cls, params = {
message: `Input not instance of ${cls.name}`
}) => custom((data) => data instanceof cls, params);
var stringType = ZodString.create;
var numberType = ZodNumber.create;
var nanType = ZodNaN.create;
var bigIntType = ZodBigInt.create;
var booleanType = ZodBoolean.create;
var dateType = ZodDate.create;
var symbolType = ZodSymbol.create;
var undefinedType = ZodUndefined.create;
var nullType = ZodNull.create;
var anyType = ZodAny.create;
var unknownType = ZodUnknown.create;
var neverType = ZodNever.create;
var voidType = ZodVoid.create;
var arrayType = ZodArray.create;
var objectType = ZodObject.create;
var strictObjectType = ZodObject.strictCreate;
var unionType = ZodUnion.create;
var discriminatedUnionType = ZodDiscriminatedUnion.create;
var intersectionType = ZodIntersection.create;
var tupleType = ZodTuple.create;
var recordType = ZodRecord.create;
var mapType = ZodMap.create;
var setType = ZodSet.create;
var functionType = ZodFunction.create;
var lazyType = ZodLazy.create;
var literalType = ZodLiteral.create;
var enumType = ZodEnum.create;
var nativeEnumType = ZodNativeEnum.create;
var promiseType = ZodPromise.create;
var effectsType = ZodEffects.create;
var optionalType = ZodOptional.create;
var nullableType = ZodNullable.create;
var preprocessType = ZodEffects.createWithPreprocess;
var pipelineType = ZodPipeline.create;
var ostring = () => stringType().optional();
var onumber = () => numberType().optional();
var oboolean = () => booleanType().optional();
var coerce = {
string: ((arg) => ZodString.create(__spreadProps(__spreadValues({}, arg), { coerce: true }))),
number: ((arg) => ZodNumber.create(__spreadProps(__spreadValues({}, arg), { coerce: true }))),
boolean: ((arg) => ZodBoolean.create(__spreadProps(__spreadValues({}, arg), {
coerce: true
}))),
bigint: ((arg) => ZodBigInt.create(__spreadProps(__spreadValues({}, arg), { coerce: true }))),
date: ((arg) => ZodDate.create(__spreadProps(__spreadValues({}, arg), { coerce: true })))
};
var NEVER = INVALID;
// ../token/src/encoder.ts
var log5 = new Logger("packages/token/src/encoder.ts");
var SkyWayAuthToken = class _SkyWayAuthToken {
constructor(props) {
let parsedProps;
try {
parsedProps = AuthTokenSchema.parse(props);
} catch (error) {
if (error instanceof external_exports.ZodError) {
throw new SkyWayError({
path: log5.prefix,
info: tokenErrors.invalidParameter,
error: new Error(
"Received invalid token. Please check your SkyWayAuthToken."
)
});
} else {
throw new SkyWayError({
path: log5.prefix,
info: tokenErrors.invalidParameter,
error: new Error(
"Received invalid token. Please check your SkyWayAuthToken."
)
});
}
}
Object.assign(this, parsedProps);
}
static Decode(token) {
try {
const props = jwt_decode_esm_default(token);
const authToken = new _SkyWayAuthToken(props);
authToken.tokenString = token;
return authToken;
} catch (error) {
throw new SkyWayError({
path: log5.prefix,
info: tokenErrors.invalidParameter,
error
});
}
}
encode(secret) {
const payload = {
jti: this.jti,
iat: this.iat,
exp: this.exp,
scope: this.scope,
version: this.version
};
this.tokenString = import_jsrsasign.default.KJUR.jws.JWS.sign(
"HS256",
JSON.stringify({ alg: "HS256", typ: "JWT" }),
JSON.stringify(payload),
secret
);
return this.tokenString;
}
/**@internal */
toJSON() {
return {
jti: this.jti,
iat: this.iat,
exp: this.exp,
scope: this.scope,
encoded: this.tokenString,
version: this.version
};
}
/**@internal */
getAppId() {
switch (this.version) {
case void 0:
case 1:
case 2: {
const scope = this.scope;
return scope.app.id;
}
case 3: {
const scope = this.scope;
return scope.appId;
}
default:
throw new SkyWayError({
path: log5.prefix,
info: tokenErrors.invalidParameter,
error: new Error(
`invalid token version: version ${this.version} is not supported.`
)
});
}
}
/**@internal */
getAnalyticsEnabled() {
var _a2, _b2, _c;
switch (this.version) {
case void 0:
case 1:
case 2: {
const scope = this.scope;
return (_a2 = scope.app.analytics) != null ? _a2 : false;
}
case 3: {
const scope = this.scope;
return (_c = (_b2 = scope.analytics) == null ? void 0 : _b2.enabled) != null ? _c : true;
}
default:
throw new SkyWayError({
path: log5.prefix,
info: tokenErrors.invalidParameter,
error: new Error(
`invalid token version: version ${this.version} is not supported.`
)
});
}
}
};
// ../token/src/scope/sfu.ts
init_process();
var forwardingActions = ["create", "write", "delete"];
var forwardingScopeSchema = external_exports.object({
/**
* 以下を複数指定可能
* - write: Forwarding のすべての操作
* - create: Forwarding の作成 (任意のメディアをSFU経由で新たに転送することができる)
* - delete: Forwarding の削除 (SFU経由でのメディア転送を取りやめることができる)
*/
actions: external_exports.array(
// 型補完のため enum で定義しておく
external_exports.enum(forwardingActions).refine((arg) => {
return typeof arg === "string";
})
)
}).passthrough();
var sfuBotActions = ["create", "write", "delete"];
var sfuScopeSchema = external_exports.object({
/**
* 以下を複数指定可能
* - write: SFU Bot のすべての操作をすることができる
* - create: SFU Bot の作成ができる
* - delete: SFU Bot の削除ができる
*/
actions: external_exports.array(
// 型補完のため enum で定義しておく
external_exports.enum(sfuBotActions).refine((arg) => {
return typeof arg === "string";
})
),
/**forwarding リソースに関するオブジェクトを指定(forwardingオブジェクトについては後述) */
forwardings: external_exports.array(forwardingScopeSchema)
}).passthrough();
// ../token/src/scope/v1-2.ts
init_process();
var publicationActions = [
"write",
"create",
"delete",
"updateMetadata",
"enable",
"disable"
];
var publicationScopeSchema = external_exports.object({
/**
* 以下を複数指定可能
* - write: すべて可能
* - create: publish(publish時に publication が作成される)
* - delete: unpublish(unpublish時に publication が削除される)
* - updateMetadata: metadata の編集
* - enable: enable
* - disable: disable
*/
actions: external_exports.array(
// 型補完のため enum で定義しておく
external_exports.enum(publicationActions).refine((arg) => {
return typeof arg === "string";
})
)
}).passthrough();
var subscriptionActions = ["write", "create", "delete"];
var subscriptionScopeSchema = external_exports.object({
/**
* 以下を複数指定可能
* - write: すべて可能
* - create: subscribe(subscribe時に subscription が作成される)
* - delete: unsubscribe(unsubscribe時に subscription が削除される)
*/
actions: external_exports.array(
// 型補完のため enum で定義しておく
external_exports.enum(subscriptionActions).refine((arg) => {
return typeof arg === "string";
})
)
}).passthrough();
var memberActions = [
"write",
"create",
"delete",
"updateMetadata",
"signal"
];
var memberScopeSchemaBase = external_exports.object({
/**
* id (id または name のどちらかが必須 *)
* - id で対象の member を指定
* - '*' を指定することで、すべての member を指定
*/
id: external_exports.string().optional(),
/**
* name (id または name のどちらかが必須 *)
* - name で対象の channel を指定
* - '*' を指定することで、すべての member を指定
*/
name: external_exports.string().optional()
}).refine((arg) => arg.id !== void 0 || arg.name !== void 0, {
message: "Either id or name is required."
});
var memberScopeSchema = external_exports.intersection(
memberScopeSchemaBase,
external_exports.object({
/**
* 以下を複数指定可能
* - write: すべて可能
* - create: 入室(入室時に member が作成される)
* - delete: 退室(入室時に member が削除される)
* - signal: シグナリング情報のやり取り (p2p通信を利用する際に必須)
* - updateMetadata: metadata の編集
*/
actions: external_exports.array(
// 型補完のため enum で定義しておく
external_exports.enum(memberActions).refine((arg) => {
return typeof arg === "string";
})
),
/**publication リソースに関するオブジェクトを指定*/
publication: publicationScopeSchema.optional(),
/**subscription リソースに関するオブジェクトを指定*/
subscription: subscriptionScopeSchema.optional()
}).passthrough()
);
var channelActions = [
"write",
"read",
"create",
"delete",
"updateMetadata"
];
var channelScopeSchemaBase = external_exports.object({
/**
* id (id または name のどちらかが必須 *)
* - id で対象の member を指定
* - '*' を指定することで、すべての member を指定
*/
id: external_exports.string().optional(),
/**
* name (id または name のどちらかが必須 *)
* - name で対象の channel を指定
* - '*' を指定することで、すべての member を指定
*/
name: external_exports.string().optional()
}).refine((arg) => arg.id !== void 0 || arg.name !== void 0, {
message: "Either id or name is required."
});
var channelScopeSchema = external_exports.intersection(
channelScopeSchemaBase,
external_exports.object({
/**
* 以下を複数指定可能
* - write: すべて可能
* - read: 参照
* - create: 作成
* - delete: 削除
* - updateMetadata: metadata の編集
*/
actions: external_exports.array(
// 型補完のため enum で定義しておく
external_exports.enum(channelActions).refine((arg) => {
return typeof arg === "string";
})
),
/**member リソースに関するオブジェクトを配列で指定 */
members: external_exports.array(memberScopeSchema),
/**sfuBot リソースに関するオブジェクトを配列で指定 */
sfuBots: external_exports.array(sfuScopeSchema).optional()
}).passthrough()
// [key: string]: unknown; として他のkeyを許容していた部分
);
var appActions = ["read"];
var appScopeSchema = external_exports.object({
/**アプリケーションIDを指定 */
id: external_exports.string(),
/**AnalyticsDashboardへのデータ送信をするかどうかの設定 */
analytics: external_exports.boolean().optional(),
/**アプリケーション自体に関する権限。現在は'read'固定 */
actions: external_exports.array(
// 型補完のため enum で定義しておく
external_exports.enum(appActions).refine((arg) => {
return typeof arg === "string";
})
).optional(),
/**channelリソースに関するオブジェクトを配列で指定*/
channels: external_exports.array(channelScopeSchema).optional(),
/**falseの場合はTurnサーバを経由してメディア通信を行いません。 */
turn: external_exports.boolean().optional()
}).passthrough();
// ../token/src/scope/v3.ts
init_process();
var memberMethods = ["publish", "subscribe", "updateMetadata"];
var memberScopeV3SchemaBase = external_exports.object({
/**
* id (id または name のどちらかが必須 *)
* - id で対象の member を指定
* - '*' を指定することで、すべての member を指定
*/
id: external_exports.string().optional(),
/**
* name (id または name のどちらかが必須 *)
* - name で対象の member を指定
* - '*' を指定することで、すべての member を指定
*/
name: external_exports.string().optional()
}).refine((arg) => arg.id !== void 0 || arg.name !== void 0, {
message: "Either id or name is required."
});
var memberScopeV3Schema = external_exports.intersection(
memberScopeV3SchemaBase,
external_exports.object({
/**
* 以下を複数指定可能
* - publish: media/dataのpublish
* - subscribe: media/dataのsubscribe
* - updateMetadata: metadata の編集
*/
methods: external_exports.array(
// 型補完のため enum で定義しておく
external_exports.enum(memberMethods).refine((arg) => {
return typeof arg === "string";
})
)
}).passthrough()
);
var roomMethods = ["create", "close", "updateMetadata"];
var roomScopeV3SchemaBase = external_exports.object({
/**
* - id または name のどちらかが必須。
* - id で対象の room を指定。
* - '*' を指定することで、すべての room を指定。
* */
id: external_exports.string().optional(),
/**
* - id または name のどちらかが必須。
* - name で対象の room を指定。
* - '*' を指定することで、すべての room を指定。
* */
name: external_exports.string().optional()
}).refine((arg) => arg.id !== void 0 || arg.name !== void 0, {
message: "Either id or name is required."
});
var roomScopeV3Schema = external_exports.intersection(
roomScopeV3SchemaBase,
external_exports.object({
/**
* 以下を複数指定可能
* - create: 作成
* - close: 削除
* - updateMetadata: metadata の編集
*/
methods: external_exports.array(
// 型補完のため enum で定義しておく
external_exports.enum(roomMethods).refine((arg) => {
return typeof arg === "string";
})
),
/** memberリソースに関するオブジェクトを指定 */
member: memberScopeV3Schema.optional(),
sfu: external_exports.object({
/**SFUサーバーの利用有無。enabledがfalseの場合はSFUサーバーを利用したメディア通信を行わない。指定しない場合は enabled: true として扱われる。 */
enabled: external_exports.boolean().optional(),
/**maxSubscribersの上限値の設定。指定しない場合はSFUサーバー側において設定可能な上限値になる。*/
maxSubscribersLimit: external_exports.number().optional()
}).optional()
}).passthrough()
);
var scopeV3Schema = external_exports.object({
/**アプリケーションIDを指定 */
appId: external_exports.string(),
/**AnalyticsDashboardへのデータ送信をするかどうかの設定。指定しない場合は enabled: true として扱われる。 */
analytics: external_exports.object({
enabled: external_exports.boolean().optional()
}).optional(),
/**AI Noise Cancellerの認可を有効化するかどうかの設定。設定しない場合は enabled: true として扱われる。 */
noiseCancelling: external_exports.object({
enabled: external_exports.boolean().optional()
}).optional(),
/**TURNサーバー利用の設定。enabledがfalseの場合はTURNサーバーを経由してメディア通信を行わない。指定しない場合は enabled: true として扱われる。 */
turn: external_exports.object({
enabled: external_exports.boolean().optional()
}).optional(),
/**roomリソースに関するオブジェクトを配列で指定*/
rooms: external_exports.array(roomScopeV3Schema)
}).passthrough();
// ../token/src/token.ts
init_process();
var authTokenBaseSchema = external_exports.object({
/** トークンのユニークなid(uuid) */
jti: external_exports.string().uuid(),
/** トークンが発行された日時(UNIX timestamp) */
iat: external_exports.number().nonnegative(),
/** このトークンが無効になる時間を表すタイムスタンプ(UNIX timestamp) */
exp: external_exports.number().nonnegative()
});
var authTokenV1_2Schema = external_exports.intersection(
authTokenBaseSchema,
external_exports.object({
/**
* tokenの権限を表すクレーム[version:1,2,undefined]
* */
scope: external_exports.object({
app: appScopeSchema
}),
/**
* tokenのバージョン[version:1,2,undefined]
* - 未指定やundefinedの場合は1として扱われます。
* - 3の場合とでscopeの構造に違いがあります。
* */
version: external_exports.union([external_exports.literal(1), external_exports.literal(2), external_exports.literal(void 0)]).optional()
})
);
var authTokenV3Schema = external_exports.intersection(
authTokenBaseSchema,
external_exports.object({
/**
* tokenの権限を表すクレーム[version:3]
* */
scope: scopeV3Schema,
/**
* tokenのバージョン[version:3]
* - 2以下の場合とでscopeの構造に違いがあります。
* */
version: external_exports.literal(3)
})
);
var AuthTokenSchema = external_exports.union([
authTokenV1_2Schema,
authTokenV3Schema
]);
// ../token/src/errors.ts
init_process();
var tokenErrors = {
invalidParameter: {
name: "invalidParameter",
detail: "failed to decode token",
solution: "Use the correct token according to the specification"
},
invalidAppIdParameter: {
name: "invalidAppIdParameter",
detail: "failed to get AppId",
solution: "Use the correct token according to the specification"
},
invalidAnalyticsParameter: {
name: "invalidAnalyticsParameter",
detail: "failed to get analytics scope",
solution: "Use the correct token according to the specification"
}
};
// ../token/src/util.ts
init_process();
// ../token/src/index.ts
var uuidV4 = v4_default;
// ../core/src/channel/index.ts
init_process();
// ../core/src/errors.ts
init_process();
var errors = {
internal: {
name: "internal",
detail: "",
solution: ""
},
timeout: { name: "timeout", detail: "", solution: "" },
missingProperty: { name: "missingProperty", detail: "", solution: "" },
notFound: { name: "notFound", detail: "", solution: "" },
invalidParameter: { name: "invalidParameter", detail: "", solution: "" },
invalidArgumentValue: {
name: "invalidArgumentValue",
detail: "\u5F15\u6570\u306E\u5024\u304C\u4E0D\u6B63\u3067\u3059",
solution: "\u6B63\u3057\u3044\u5024\u3092\u5F15\u6570\u306B\u6E21\u3057\u3066\u304F\u3060\u3055\u3044"
},
invalidContentType: {
name: "invalidContentType",
detail: "contentType\u304C\u6B63\u3057\u304F\u3042\u308A\u307E\u305B\u3093",
solution: "ContentType\u3092\u78BA\u8A8D\u3057\u3066\u304F\u3060\u3055\u3044"
},
localPersonNotJoinedChannel: {
name: "localPersonNotJoinedChannel",
detail: "\u64CD\u4F5C\u3057\u3088\u3046\u3068\u3057\u305FPerson\u304CChannel\u306B\u5C45\u306A\u3044\u306E\u3067\u3001\u64CD\u4F5C\u3067\u304D\u307E\u305B\u3093 The person who tried to operate is not in the channel, so the operation is not possible",
solution: "Channel\u306B\u5C45\u306A\u3044Person\u3092\u64CD\u4F5C\u3057\u3066\u3044\u308B\u53EF\u80FD\u6027\u304C\u3042\u308B\u306E\u3067\u78BA\u8A8D\u3057\u3066\u304F\u3060\u3055\u3044 Please check as you may be operating a person which is not in the channel"
},
alreadyLocalPersonExist: {
name: "alreadyLocalPersonExist",
detail: "Channel\u306B\u3059\u3067\u306BLocalPerson\u304C\u5B58\u5728\u3057\u307E\u3059\u3002\u4E00\u3064\u306EChannel\u30A4\u30F3\u30B9\u30BF\u30F3\u30B9\u306B\u306FLocalPerson\u304C\u4E00\u3064\u3057\u304BJoin\u3067\u304D\u307E\u305B\u3093",
solution: "\u8907\u6570\u306ELocalPerson\u3092\u7528\u610F\u3057\u305F\u3044\u5834\u5408\u306F\u500B\u5225\u306BChannel\u30A4\u30F3\u30B9\u30BF\u30F3\u30B9\u3092\u7528\u610F\u3057\u3066\u304F\u3060\u3055\u3044\u3002"
},
alreadySameNameMemberExist: {
name: "alreadySameNameMemberExist",
detail: "Channel\u306B\u3059\u3067\u306B\u540C\u3058Name\u306EMember\u304C\u5B58\u5728\u3057\u307E\u3059",
solution: "\u5225\u306EName\u3092\u4F7F\u7528\u3057\u3066\u304F\u3060\u3055\u3044"
},
alreadyPublishedStream: {
name: "alreadyPublishedStream",
detail: "\u3059\u3067\u306BPublish\u3057\u305FStream\u3092\u518D\u5EA6Publish\u3059\u308B\u3053\u3068\u306F\u3067\u304D\u307E\u305B\u3093 You cannot re-publish a stream that has already been published",
solution: "\u305D\u306EStream\u3092Publish\u3057\u305FPublication\u3092Unpublish\u3059\u308B\u304B\u3001\u5225\u306E\u65B0\u3057\u3044Stream\u3092\u4F5C\u3063\u3066Publish\u3057\u3066\u304F\u3060\u3055\u3044 Unpublish the publication that published that stream, or create another new stream and publish it"
},
alreadySubscribedPublication: {
name: "alreadySubscribedPublication",
detail: "\u3059\u3067\u306BSubscribe\u3057\u305FPublication\u3092Subscribe\u3059\u308B\u3053\u3068\u306F\u3067\u304D\u307E\u305B\u3093",
solution: "\u3042\u308A\u307E\u305B\u3093"
},
invalidTrackKind: {
name: "invalidTrackKind",
detail: "Stream\u306E\u7A2E\u985E\u3068MediaStreamTrack\u306E\u7A2E\u985E\u304C\u4E00\u81F4\u3057\u307E\u305B\u3093",
solution: "Stream\u306E\u7A2E\u985E\u3068\u540C\u3058MediaStreamTrack\u3092\u5229\u7528\u3057\u3066\u304F\u3060\u3055\u3044"
},
cantMoveSameIdChannel: {
name: "cantMoveSameIdChannel",
detail: "moveChannel\u3067\u540C\u3058id\u306EChannel\u306B\u79FB\u52D5\u3059\u308B\u3053\u3068\u306F\u51FA\u6765\u307E\u305B\u3093",
solution: "\u79FB\u52D5\u5148\u306EChannel\u304C\u6B63\u3057\u3044\u304B\u78BA\u304B\u3081\u3066\u304F\u3060\u3055\u3044"
},
alreadyChannelClosed: {
name: "alreadyChannelClosed",
detail: "Channel\u304C\u3059\u3067\u306BClose\u3055\u308C\u3066\u3044\u307E\u3059",
solution: "\u3042\u308A\u307E\u305B\u3093"
},
disabledDataStream: {
name: "disabledDataStream",
detail: "\u95A2\u9023\u3059\u308BPublication\u304CDisable\u306ADataStream\u306B\u306F\u66F8\u304D\u8FBC\u307F\u3067\u304D\u307E\u305B\u3093",
solution: "\u95A2\u9023\u3059\u308BPublication\u3092Enable\u3057\u3066\u304B\u3089\u66F8\u304D\u8FBC\u3093\u3067\u304F\u3060\u3055\u3044"
},
publicationNotExist: {
name: "publicationNotExist",
detail: "channel\u306B\u8A72\u5F53\u3059\u308BPublication\u304C\u5B58\u5728\u3057\u307E\u305B\u3093",
solution: "publicationId\u304C\u6B63\u3057\u3044\u304B\u78BA\u304B\u3081\u3066\u304F\u3060\u3055\u3044"
},
subscriptionNotExist: {
name: "subscriptionNotExist",
detail: "channel\u306B\u8A72\u5F53\u3059\u308BSubscription\u304C\u5B58\u5728\u3057\u307E\u305B\u3093",
solution: "subscriptionId\u304C\u6B63\u3057\u3044\u304B\u78BA\u304B\u3081\u3066\u304F\u3060\u3055\u3044"
},
unknownMemberType: {
name: "unknownMemberType",
detail: "\u5BFE\u8C61\u306EMember\u306ESubtype\u306E\u30D7\u30E9\u30B0\u30A4\u30F3\u304C\u767B\u9332\u3055\u308C\u3066\u3044\u307E\u305B\u3093",
solution: "\u5BFE\u8C61\u306EMember\u306ESubtype\u306E\u30D7\u30E9\u30B0\u30A4\u30F3(SFUBot\u306A\u3069)\u3092SkyWayContext\u306B\u767B\u9332\u3057\u3066\u304F\u3060\u3055\u3044"
},
streamNotExistInSubscription: {
name: "streamNotExistInSubscription",
detail: "Subscription\u306BStream\u304C\u3042\u308A\u307E\u305B\u3093\u3002RemoteMember\u306ESubscription\u306EStream\u306B\u306F\u30A2\u30AF\u30BB\u30B9\u3067\u304D\u307E\u305B\u3093",
solution: "\u53C2\u7167\u3057\u3066\u3044\u308BSubscription\u304C\u76EE\u7684\u306E\u3082\u306E\u304B\u78BA\u304B\u3081\u3066\u304F\u3060\u3055\u3044\u3002"
},
streamNotExistInPublication: {
name: "streamNotExistInPublication",
detail: "Publication\u306BStream\u304C\u3042\u308A\u307E\u305B\u3093\u3002RemoteMember\u306EPublication\u306EStream\u306B\u306F\u30A2\u30AF\u30BB\u30B9\u3067\u304D\u307E\u305B\u3093",
solution: "\u53C2\u7167\u3057\u3066\u3044\u308BPublication\u304C\u76EE\u7684\u306E\u3082\u306E\u304B\u78BA\u304B\u3081\u3066\u304F\u3060\u3055\u3044\u3002"
},
dataStreamNotSupportEncoding: {
name: "dataStreamNotSupportEncoding",
detail: "dataStream\u306FEncode\u8A2D\u5B9A\u306E\u5909\u66F4\u306B\u5BFE\u5FDC\u3057\u3066\u3044\u307E\u305B\u3093",
solution: "\u3042\u308A\u307E\u305B\u3093"
},
correspondingEncodeNotExistForId: {
name: "correspondingEncodeNotExistForId",
detail: "\u6307\u5B9A\u3055\u308C\u305FID\u306B\u5BFE\u5FDC\u3059\u308BEncode\u8A2D\u5B9A\u304C\u5B58\u5728\u3057\u307E\u305B\u3093",
solution: "\u6B63\u3057\u3044EncodingID\u3092\u6307\u5B9A\u3057\u3066\u304F\u3060\u3055\u3044"
},
updateIceParamsFailed: {
name: "updateIceParamsFailed",
detail: "iceParams\u306E\u66F4\u65B0\u306B\u5931\u6557\u3057\u307E\u3057\u305F",
solution: "\u3042\u308A\u307E\u305B\u3093"
},
invalidElement: {
name: "invalidElement",
detail: "\u6E21\u3055\u308C\u305FHTML Element\u304C\u6B63\u3057\u304F\u3042\u308A\u307E\u305B\u3093",
solution: "\u8981\u6C42\u3055\u308C\u305F\u6B63\u3057\u3044Element\u3092\u6E21\u3057\u3066\u304F\u3060\u3055\u3044"
},
connectRtcApiFailed: {
name: "connectRtcApiFailed",
detail: "RtcAPI\u3078\u306E\u63A5\u7D9A\u306B\u5931\u6557\u3057\u307E\u3057\u305F",
solution: "\u30A4\u30F3\u30BF\u30FC\u30CD\u30C3\u30C8\u3078\u63A5\u7D9A\u3067\u304D\u3066\u3044\u308B\u304B\u3001\u3082\u3057\u304F\u306FToken\u306E\u30D1\u30E9\u30E1\u30FC\u30BF\u304C\u6B63\u3057\u3044\u304B\u3092\u78BA\u304B\u3081\u3066\u304F\u3060\u3055\u3044"
},
rtcApiFatalError: {
name: "rtcApiFatalError",
detail: "RtcAPI\u306E\u56DE\u5FA9\u4E0D\u80FD\u306A\u30A8\u30E9\u30FC\u3067\u3059\u3002\u30B5\u30FC\u30D0\u30FC\u5074\u306E\u554F\u984C\u306E\u53EF\u80FD\u6027\u304C\u3042\u308A\u307E\u3059",
solution: "\u30A4\u30F3\u30BF\u30FC\u30CD\u30C3\u30C8\u3078\u306E\u63A5\u7D9A\u304C\u51FA\u6765\u3066\u3044\u308B\u304B\u3092\u78BA\u304B\u3081\u3066\u304F\u3060\u3055\u3044"
},
invalidExpireTokenValue: {
name: "invalidExpireTokenValue",
detail: "token\u306EExpire\u6642\u523B\u304C\u4E0D\u6B63\u3067\u3059",
solution: "\u6B63\u3057\u3044\u6642\u523B\u3092\u6307\u5B9A\u3057\u3066\u304F\u3060\u3055\u3044"
},
invalidRemindExpireTokenValue: {
name: "invalidRemindExpireTokenValue",
detail: "token\u306EExpire\u3092\u30EA\u30DE\u30A4\u30F3\u30C9\u3059\u308B\u6642\u9593\u306E\u5024\u304C\u4E0D\u6B63\u3067\u3059",
solution: "\u6B63\u3057\u3044\u6642\u9593\u3092\u6307\u5B9A\u3057\u3066\u304F\u3060\u3055\u3044"
},
invalidTokenAppId: {
name: "invalidTokenAppId",
detail: "token\u306EappId\u304C\u6B63\u3057\u304F\u3042\u308A\u307E\u305B\u3093",
solution: "\u6B63\u3057\u3044appId\u3092\u542B\u3080Token\u3092\u4F7F\u7528\u3057\u3066\u304F\u3060\u3055\u3044"
},
mediaDevicesNotFound: {
name: "mediaDevicesNotFound",
detail: "navigator.mediaDevices\u304C\u307F\u3064\u304B\u308A\u307E\u305B\u3093",
solution: "\u30A2\u30D7\u30EA\u30B1\u30FC\u30B7\u30E7\u30F3\u3092https,localhost,127.0.0.1\u306E\u3044\u305A\u308C\u304B\u306E\u74B0\u5883\u3067\u52D5\u4F5C\u3055\u305B\u3066\u304F\u3060\u3055\u3044"
},
canNotUseReplaceStream: {
name: "canNotUseReplaceStream",
detail: "remote\u306EPublication\u304B\u3089replaceStream\u3067\u304D\u307E\u305B\u3093",
solution: "\u5BFE\u8C61\u306EPublication\u304CLocal\u306E\u3082\u306E\u304B\u78BA\u8A8D\u3057\u3066\u304F\u3060\u3055\u3044"
},
canNotEnableRemotePublication: {
name: "canNotEnableRemotePublication",
detail: "remote\u306EPublication\u3092enable\u3059\u308B\u3053\u3068\u306F\u3067\u304D\u307E\u305B\u3093",
solution: "\u5BFE\u8C61\u306EPublication\u304CLocal\u306E\u3082\u306E\u304B\u78BA\u8A8D\u3057\u3066\u304F\u3060\u3055\u3044"
},
dataChannelSendError: {
name: "dataChannelSendError",
detail: "\u30C7\u30FC\u30BF\u9001\u4FE1\u306B\u5931\u6557\u3057\u307E\u3057\u305F",
solution: "\u63A5\u7D9A\u304C\u9589\u3058\u3089\u308C\u3066\u3044\u308B\u3001\u30D0\u30C3\u30D5\u30A1\u306B\u7A7A\u304D\u5BB9\u91CF\u304C\u7121\u3044\u3001\u30C7\u30FC\u30BF\u30B5\u30A4\u30BA\u304C\u5927\u304D\u3059\u304E\u308B\u7B49\u306E\u7406\u7531\u3067\u9001\u4FE1\u306B\u5931\u6557\u3057\u3066\u3044\u307E\u3059\u3002\u518D\u5EA6publish \u3082\u3057\u304F\u306F \u9001\u4FE1\u3059\u308B\u30C7\u30FC\u30BF\u3092\u5206\u5272\u3057\u3066\u304F\u3060\u3055\u3044"
},
dataChannelGeneralError: {
name: "dataChannelGeneralError",
detail: "DataStream\u306E\u5185\u90E8\u3067\u30A8\u30E9\u30FC\u304C\u767A\u751F\u3057\u307E\u3057\u305F",
solution: "DataStream\u3092\u4F5C\u308A\u76F4\u3057\u3066\u518D\u5EA6publish\u3057\u3066\u304F\u3060\u3055\u3044"
},
invalidRequestParameter: {
name: "invalidRequestParameter",
detail: "\u30EA\u30AF\u30A8\u30B9\u30C8\u306E\u30D1\u30E9\u30E1\u30FC\u30BF\u30FC\u304C\u6B63\u3057\u304F\u306A\u3044\u3001\u3082\u3057\u304F\u306F\u4E0D\u6B63\u306A\u6587\u5B57\u5217\u3092\u4F7F\u7528\u3057\u3066\u3044\u307E\u3059",
solution: "API\u4ED5\u69D8\u3092\u78BA\u8A8D\u3057\u6B63\u3057\u3044\u5024\u3092\u5165\u529B\u3057\u3066\u304F\u3060\u3055\u3044"
}
};
// ../core/src/member/localPerson/index.ts
init_process();
// ../core/src/member/index.ts
init_process();
// ../core/src/util.ts
init_process();
var import_bowser = __toESM(require_es5());
var import_sdp_transform = __toESM(require_lib());
var import_ua_parser_js = __toESM(require_ua_parser());
var log6 = new Logger("packages/core/src/util.ts");
function statsToArray(stats) {
const arr = [];
stats.forEach((stat) => {
arr.push(stat);
});
return arr;
}
function createLogPayload(_0) {
return __async(this, arguments, function* ({
operationName,
channel
}) {
const payload = {
operationName,
appId: channel.appId,
channelId: channel.id
};
if (channel.localPerson) {
const member = channel.localPerson;
const publishing = yield Promise.all(
member.publications.map((p) => __async(null, null, function* () {
var _a2, _b2, _c;
const publication = {
id: p.id,
contentType: p.contentType,
state: p.state,
stats: {},
connectionStats: {}
};
if (p.stream) {
for (const { memberId, stats } of yield p.stream._getStatsAll()) {
const localCandidate = stats.find(
(s) => s.type.includes("local-candidate")
);
publication.stats[memberId] = {
transportType: (_a2 = localCandidate == null ? void 0 : localCandidate.protocol) != null ? _a2 : "none",
relayProtocol: (_b2 = localCandidate == null ? void 0 : localCandidate.relayProtocol) != null ? _b2 : "none",
callType: (_c = p.subscriptions.find(
(s) => s.subscriber.id === memberId
)) == null ? void 0 : _c.subscriber.subtype,
outbound: stats.find((s) => s.type.includes("outbound-rtp")),
localCandidate
};
}
}
if (p.stream) {
for (const {
memberId,
connectionState
} of p.stream._getConnectionStateAll()) {
publication.connectionStats[memberId] = connectionState;
}
}
return publication;
}))
);
payload.publishing = publishing;
const subscribing = yield Promise.all(
member.subscriptions.map((s) => __async(null, null, function* () {
const subscription = {
id: s.id,
contentType: s.contentType,
stats: {}
};
subscription.callType = s.publication.publisher.subtype;
if (s.stream) {
const stats = yield s.stream._getStats();
subscription.stats = stats.find(
(s2) => s2.type.includes("inbound-rtp")
);
const iceCandidate = stats.find(
(s2) => s2.type.includes("local-candidate")
);
subscription.transportType = iceCandidate == null ? void 0 : iceCandidate.protocol;
subscription.relayProtocol = iceCandidate == null ? void 0 : iceCandidate.relayProtocol;
}
if (s.stream) {
subscription.connectionState = s.stream._getConnectionState();
}
return subscription;
}))
);
payload.subscribing = subscribing;
}
return payload;
});
}
function createWarnPayload({
member,
detail,
channel,
operationName,
payload
}) {
const warn = {
operationName,
payload,
detail
};
if (member) {
warn.appId = member.channel.appId;
warn.channelId = member.channel.id;
warn.memberId = member.id;
}
if (channel) {
warn.appId = channel.appId;
warn.channelId = channel.id;
}
return warn;
}
function createError({
operationName,
context,
info,
error,
path,
payload,
channel
}) {
const errPayload = {
operationName,
payload
};
if (channel) {
errPayload.appId = channel.appId;
errPayload.channelId = channel.id;
if (channel.localPerson) {
errPayload.memberId = channel.localPerson.id;
}
}
if (context) {
errPayload.info = context.info;
errPayload.plugins = context.plugins.map((p) => p.subtype);
}
return new SkyWayError({ error, info, payload: errPayload, path });
}
var waitForLocalStats = (_0) => __async(null, [_0], function* ({
stream,
remoteMember,
end,
interval,
timeout
}) {
return new Promise((r2, f) => {
const intervalMs = interval != null ? interval : 100;
const timeoutMs = timeout != null ? timeout : 1e4;
const checkStats = () => __async(null, null, function* () {
for (let elapsed = 0; ; elapsed += intervalMs) {
if (elapsed >= timeoutMs) {
f(
createError({
operationName: "Peer.waitForStats",
info: __spreadProps(__spreadValues({}, errors.timeout), {
detail: "waitForStats timeout"
}),
path: log6.prefix
})
);
break;
}
const stats = yield stream._getStats(remoteMember);
if (end(stats)) {
r2(stats);
break;
}
yield new Promise((r3) => setTimeout(r3, intervalMs));
}
});
checkStats().catch(f);
});
});
var getParameters = (fmtp, payload) => {
var _a2, _b2;
return fmtpConfigParser((_b2 = (_a2 = fmtp.find((f) => f.payload === payload)) == null ? void 0 : _a2.config) != null ? _b2 : "");
};
var fmtpConfigParser = (config) => {
const parameters = config.split(";").reduce((acc, cur) => {
const [k, v] = cur.split("=");
if (k) {
acc[k] = !Number.isNaN(Number(v)) ? Number(v) : v;
}
return acc;
}, {});
return parameters;
};
var getRuntimeInfo = ({
isNotBrowser
} = {}) => {
if (isNotBrowser) {
return isNotBrowser;
}
const browser = import_bowser.default.getParser(window.navigator.userAgent);
const osName = browser.getOSName();
const osVersion = browser.getOSVersion();
const browserName = browser.getBrowserName();
const browserVersion = browser.getBrowserVersion();
return {
browserName,
browserVersion,
osName,
osVersion
};
};
function detectDevice() {
var _a2, _b2, _c, _d, _e, _f, _g, _h;
if (typeof navigator === "object" && navigator.product === "ReactNative") {
if (typeof RTCPeerConnection === "undefined") {
return void 0;
}
if (typeof RTCRtpTransceiver !== "undefined") {
return "ReactNativeUnifiedPlan";
} else {
return "ReactNative";
}
} else if (typeof navigator === "object" && typeof navigator.userAgent === "string") {
const ua = navigator.userAgent;
const uaParser = new import_ua_parser_js.UAParser(ua);
const browser = uaParser.getBrowser();
const browserName = (_b2 = (_a2 = browser.name) == null ? void 0 : _a2.toLowerCase()) != null ? _b2 : "";
const browserVersion = parseInt((_c = browser.major) != null ? _c : "0", 10);
const engine = uaParser.getEngine();
const engineName = (_e = (_d = engine.name) == null ? void 0 : _d.toLowerCase()) != null ? _e : "";
const os = uaParser.getOS();
const osName = (_g = (_f = os.name) == null ? void 0 : _f.toLowerCase()) != null ? _g : "";
const osVersion = parseFloat((_h = os.version) != null ? _h : "0");
const isIOS = osName === "ios";
const isChrome = [
"chrome",
"chromium",
"mobile chrome",
"chrome webview",
"chrome headless"
].includes(browserName);
const isFirefox = ["firefox", "mobile firefox", "mobile focus"].includes(
browserName
);
const isSafari2 = ["safari", "mobile safari"].includes(browserName);
const isEdge = ["edge"].includes(browserName);
if ((isChrome || isEdge) && !isIOS && browserVersion >= 111) {
return "Chrome111";
} else if (isChrome && !isIOS && browserVersion >= 74 || isEdge && !isIOS && browserVersion >= 88) {
return "Chrome74";
} else if (isChrome && !isIOS && browserVersion >= 70) {
return "Chrome70";
} else if (isChrome && !isIOS && browserVersion >= 67) {
return "Chrome67";
} else if (isChrome && !isIOS && browserVersion >= 55) {
return "Chrome55";
} else if (isFirefox && !isIOS && browserVersion >= 60) {
return "Firefox60";
} else if (isFirefox && isIOS && osVersion >= 14.3) {
return "Safari12";
} else if (isSafari2 && browserVersion >= 12 && typeof RTCRtpTransceiver !== "undefined" && // biome-ignore lint/suspicious/noPrototypeBuiltins: Legacy compatibility
RTCRtpTransceiver.prototype.hasOwnProperty("currentDirection")) {
return "Safari12";
} else if (isSafari2 && browserVersion >= 11) {
return "Safari11";
} else if (isEdge && !isIOS && browserVersion >= 11 && browserVersion <= 18) {
return "Edge11";
} else if (engineName === "webkit" && isIOS && osVersion >= 14.3 && typeof RTCRtpTransceiver !== "undefined" && // biome-ignore lint/suspicious/noPrototypeBuiltins: Legacy compatibility
RTCRtpTransceiver.prototype.hasOwnProperty("currentDirection")) {
return "Safari12";
} else if (engineName === "blink") {
const match = ua.match(/(?:(?:Chrome|Chromium))[ /](\w+)/i);
if (match) {
const version = Number(match[1]);
if (version >= 111) {
return "Chrome111";
} else if (version >= 74) {
return "Chrome74";
} else if (version >= 70) {
return "Chrome70";
} else if (version >= 67) {
return "Chrome67";
} else {
return "Chrome55";
}
} else {
return "Chrome111";
}
} else {
return void 0;
}
} else {
return void 0;
}
}
// ../core/src/member/index.ts
var log7 = new Logger("packages/core/src/member/index.ts");
var MemberImpl = class {
constructor(args) {
this._state = "joined";
/**@internal */
this._events = new Events();
this.onLeft = this._events.make();
this.onMetadataUpdated = this._events.make();
this.channel = args.channel;
this.id = args.id;
this.name = args.name;
this._metadata = args.metadata;
this.context = args.context;
}
get metadata() {
return this._metadata;
}
get state() {
return this._state;
}
get publications() {
return this.channel.publications.filter((p) => p.publisher.id === this.id);
}
get subscriptions() {
return this.channel.subscriptions.filter(
(p) => p.subscriber.id === this.id
);
}
/**@internal */
toJSON() {
return {
id: this.id,
name: this.name,
type: this.type,
subtype: this.subtype,
metadata: this.metadata
};
}
/** @private*/
_left() {
this._state = "left";
this.onLeft.emit();
this._events.dispose();
}
/** @private*/
_metadataUpdated(metadata) {
this._metadata = metadata;
this.onMetadataUpdated.emit(metadata);
}
updateMetadata(metadata) {
return __async(this, null, function* () {
yield this.channel._updateMemberMetadata(this.id, metadata);
});
}
/**@throws {@link SkyWayError} */
leave() {
return __async(this, null, function* () {
const timestamp = log7.info(
"[start] leave",
yield createLogPayload({
operationName: "localPerson.leave",
channel: this.channel
})
);
if (this.state === "left") {
throw createError({
operationName: "localPerson.leave",
info: errors.localPersonNotJoinedChannel,
path: log7.prefix,
context: this.context,
channel: this.channel
});
}
yield this.channel.leave(this);
log7.elapsed(timestamp, "[end] leave");
});
}
};
// ../core/src/plugin/internal/unknown/member.ts
init_process();
// ../core/src/plugin/internal/unknown/connection.ts
init_process();
var log8 = new Logger(
"packages/core/src/plugin/internal/unknown/connection.ts"
);
var UnknownConnection = class {
constructor(localPerson, remoteMember) {
this.localPerson = localPerson;
this.remoteMember = remoteMember;
this.type = "unknown";
this.onDisconnect = new Event();
this.onClose = new Event();
this.closed = false;
}
close() {
this.closed = true;
this.onClose.emit();
}
startPublishing(publication) {
return __async(this, null, function* () {
log8.debug(
`this is unknown type connection. should install ${this.remoteMember.subtype} plugin`,
{ publication }
);
});
}
stopPublishing(publication) {
return __async(this, null, function* () {
log8.debug(
`this is unknown type connection. should install ${this.remoteMember.subtype} plugin`,
{ publication }
);
});
}
startSubscribing(subscription) {
return __async(this, null, function* () {
log8.debug(
`this is unknown type connection. should install ${this.remoteMember.subtype} plugin`,
{ subscription }
);
});
}
stopSubscribing(subscription) {
return __async(this, null, function* () {
log8.debug(
`this is unknown type connection. should install ${this.remoteMember.subtype} plugin`,
{ subscription }
);
});
}
};
// ../core/src/plugin/internal/unknown/member.ts
var UnknownMemberImpl = class extends MemberImpl {
constructor(args) {
super(args);
this.type = "bot";
this.side = "remote";
this._connections = {};
this.plugin = args.plugin;
this.subtype = args.subtype;
}
/**@private */
_getConnection(localPersonId) {
return this._connections[localPersonId];
}
/**@private */
_getOrCreateConnection(localPerson) {
var _a2;
const connection = (_a2 = this._getConnection(localPerson.id)) != null ? _a2 : this._createConnection(localPerson, this);
return connection;
}
_createConnection(localPerson, endpointMember) {
return new UnknownConnection(localPerson, endpointMember);
}
_dispose() {
}
};
// ../core/src/publication/index.ts
init_process();
// ../core/src/media/stream/local/data.ts
init_process();
// ../core/src/media/stream/local/index.ts
init_process();
// ../core/src/media/stream/local/audio.ts
init_process();
// ../core/src/media/stream/audioLevel.ts
init_process();
var AudioLevel = class {
constructor(audioStreamTrack) {
// ChromeのAudioLevelに近い挙動とするために取得範囲と更新周期を100msとする
this.LEVEL_RANGE_MS = 100;
// ChromeのAudioLevelに近い挙動とするために100ms毎に1/4減衰させる
this.DECAY_FACTOR = 0.25;
// 1/4
this.DECAY_INTERVAL_MS = 100;
// 使用する環境によってサンプリングレートは8000〜48000Hzまで様々であるため、中間値24000Hzを想定したデフォルト値を設定する
this.DEFAULT_BUFFER_SIZE = 24e3 * (this.LEVEL_RANGE_MS / 1e3);
this.currentMaxLevel = 0;
this.audioContext = new AudioContext();
this.analyser = this.setupAnalyser(audioStreamTrack);
this.decayTimer = this.setDecayTimer();
}
[Symbol.dispose]() {
return __async(this, null, function* () {
yield this.dispose();
});
}
calculate() {
const sampleRate = this.audioContext.sampleRate;
const duration = this.LEVEL_RANGE_MS / 1e3;
const bufferLength = sampleRate ? sampleRate * duration : this.DEFAULT_BUFFER_SIZE;
const timeDomainData = new Float32Array(bufferLength);
this.analyser.getFloatTimeDomainData(timeDomainData);
let level = Math.max(...timeDomainData);
const _currentMaxLevel = this.currentMaxLevel;
if (level > _currentMaxLevel) {
this.currentMaxLevel = level;
} else {
level = _currentMaxLevel;
}
return this.clamp(level, 0, 1);
}
setupAnalyser(audioStreamTrack) {
const mediaStream = new MediaStream([audioStreamTrack]);
const source = this.audioContext.createMediaStreamSource(mediaStream);
const analyser = this.audioContext.createAnalyser();
source.connect(analyser);
return analyser;
}
setDecayTimer() {
return setInterval(() => {
this.currentMaxLevel = this.currentMaxLevel * this.DECAY_FACTOR;
}, this.DECAY_INTERVAL_MS);
}
clamp(value, min, max) {
return Math.min(Math.max(value, min), max);
}
dispose() {
return __async(this, null, function* () {
if (this.decayTimer) {
clearInterval(this.decayTimer);
this.decayTimer = null;
}
yield this.audioContext.close();
});
}
};
// ../core/src/media/stream/local/media.ts
init_process();
// ../core/src/media/stream/base.ts
init_process();
var log9 = new Logger("packages/core/src/media/stream/base.ts");
function attachElement(element, track) {
if ((element == null ? void 0 : element.srcObject) === void 0) {
throw createError({
operationName: "attachElement",
info: errors.invalidElement,
payload: { element },
path: log9.prefix
});
}
if (element.srcObject) {
const stream = element.srcObject;
const ended = stream.getTracks().find((t2) => t2.readyState === "ended");
if (ended) {
stream.removeTrack(ended);
}
const duplicate = stream.getTracks().find((t2) => t2.kind === track.kind);
if (duplicate) {
stream.removeTrack(duplicate);
}
stream.addTrack(track);
} else {
element.srcObject = new MediaStream([track]);
}
}
function detachElement(element, track) {
if ((element == null ? void 0 : element.srcObject) === void 0) {
throw createError({
operationName: "attachElement",
info: errors.invalidElement,
payload: { element },
path: log9.prefix
});
}
const stream = element.srcObject;
if (stream.getTracks().length > 0) {
stream.removeTrack(track);
}
if (stream.getTracks().length === 0) {
element.srcObject = null;
}
}
// ../core/src/media/stream/local/base.ts
init_process();
var LocalStreamBase = class {
/**@internal */
constructor(contentType) {
this.contentType = contentType;
this.side = "local";
/**@internal */
this._onConnectionStateChanged = new Event();
this.id = uuidV4();
/**@internal */
this._label = "";
this.published = false;
/**@private */
this._getTransportCallbacks = {};
/**@private */
this._getStatsCallbacks = {};
this._connectionState = {};
}
/**@internal */
_setLabel(label) {
this._label = label;
}
/**@internal */
_unpublished() {
this.published = false;
this._getTransportCallbacks = {};
this._getStatsCallbacks = {};
}
/**@internal */
_getTransport(selector) {
var _a2, _b2;
const id = typeof selector === "string" ? selector : selector.id;
return (_b2 = (_a2 = this._getTransportCallbacks)[id]) == null ? void 0 : _b2.call(_a2);
}
/**@internal */
_setConnectionState(remoteMember, state) {
if (this._connectionState[remoteMember.id] === state) return;
this._connectionState[remoteMember.id] = state;
this._onConnectionStateChanged.emit({ remoteMember, state });
}
/**@internal */
_getStats(selector) {
var _a2, _b2, _c;
const id = typeof selector === "string" ? selector : selector.id;
return (_c = (_b2 = (_a2 = this._getStatsCallbacks)[id]) == null ? void 0 : _b2.call(_a2)) != null ? _c : [];
}
/**@internal */
_getStatsAll() {
return Promise.all(
Object.entries(this._getStatsCallbacks).map((_0) => __async(this, [_0], function* ([key, cb]) {
return {
memberId: key,
stats: yield cb().catch(() => [])
};
}))
);
}
/**@internal */
_getRTCPeerConnection(selector) {
var _a2;
return (_a2 = this._getTransport(selector)) == null ? void 0 : _a2.rtcPeerConnection;
}
/**@internal */
_getConnectionState(selector) {
var _a2;
const id = typeof selector === "string" ? selector : selector.id;
return (_a2 = this._connectionState[id]) != null ? _a2 : "new";
}
/**@internal */
_getConnectionStateAll() {
return Object.keys(this._getTransportCallbacks).map((memberId) => ({
memberId,
connectionState: this._getConnectionState(memberId)
}));
}
/**@internal */
toJSON() {
return {
label: this._label,
contentType: this.contentType,
id: this.id,
side: this.side
};
}
};
// ../core/src/media/stream/local/media.ts
var logger = new Logger("packages/core/src/media/stream/local/media.ts");
var LocalMediaStreamBase = class extends LocalStreamBase {
constructor(track, contentType, options = {}) {
super(contentType);
/**@description [japanese] PublicationのDisable/EnableなどでStreamのtrackが更新された時に発火するイベント */
this.onTrackUpdated = new Event();
/**
* @description [japanese] streamが破棄された時に発火するイベント (例. 画面共有が終了したときなど)
* @example [japanese] ハンドリング例
* const publication = await member.publish(audio);
audio.onDestroyed.once(async () => {
await member.unpublish(publication);
});
* */
this.onDestroyed = new Event();
this._disposer = new EventDisposer();
this._trackConstraints = {};
/**@internal */
this._replacingTrack = false;
/**@internal */
this._onReplacingTrackDone = new Event();
/**@internal */
this._onEnableChanged = new Event();
this._track = track;
this._listenTrackEvent();
this._options = options;
this._trackConstraints = __spreadValues({}, options);
}
/**@internal */
get trackConstraints() {
return this._trackConstraints;
}
toJSON() {
const base = super.toJSON();
return __spreadProps(__spreadValues({}, base), {
trackConstraints: this.trackConstraints,
_options: this._options
});
}
get track() {
return this._track;
}
/**
* @description [english] Attach the stream to the element.
* @description [japanese] streamをelementに適用する.
*/
attach(element) {
this._element = element;
attachElement(element, this._track);
}
/**
* @description [english] Detach the stream from the element.
* @description [japanese] elementからstreamを取り除く.
*/
detach() {
if (this._element) {
detachElement(this._element, this._track);
this._element = void 0;
}
}
/**@internal */
_disable(kind) {
if (this._options.stopTrackWhenDisabled) {
this._trackConstraints = __spreadValues(__spreadValues({}, this.trackConstraints), this.track.getConstraints());
this.track.stop();
} else {
this._oldTrack = this.track;
}
const track = kind === "video" ? emptyVideoTrack : emptyAudioTrack;
track.enabled = false;
this._onEnableChanged.emit(track);
this._updateTrack(track);
}
/**@internal */
_updateTrack(track) {
this._track = track;
if (this._element) {
this.attach(this._element);
}
this.onTrackUpdated.emit(track);
this._listenTrackEvent();
}
_listenTrackEvent() {
const onended = () => {
logger.info("onDestroyed", this.toJSON());
this.onDestroyed.emit();
};
this._track.addEventListener("ended", onended);
this._disposer.push(
() => this._track.removeEventListener("ended", onended)
);
}
/**
* @description [japanese] Streamを解放します。
* カメラやマイクなどのデバイスを解放するためにはそのデバイスに関連するすべてのStreamを解放する必要があります
*/
release() {
this._disposer.dispose();
this._track.stop();
}
};
var createEmptyTrack = new RTCPeerConnection();
var emptyAudioTrack = createEmptyTrack.addTransceiver("audio").receiver.track;
var emptyVideoTrack = createEmptyTrack.addTransceiver("video").receiver.track;
// ../core/src/media/stream/local/audio.ts
var log10 = new Logger("packages/core/src/media/stream/local/audio.ts");
var LocalAudioStream = class extends LocalMediaStreamBase {
constructor(track, options = {}) {
super(track, "audio", options);
this.contentType = "audio";
this._isEnabled = true;
this._promiseQueue = new PromiseQueue();
if (track.kind !== "audio") {
throw createError({
operationName: "LocalAudioStream.constructor",
path: log10.prefix,
info: errors.invalidTrackKind,
payload: { track }
});
}
}
/**@internal */
setEnabled(enabled) {
return __async(this, null, function* () {
yield this._promiseQueue.push(() => __async(this, null, function* () {
if (this._isEnabled === true && enabled === false) {
this._isEnabled = enabled;
this._disable("audio");
log10.debug("stopped");
} else if (this._isEnabled === false && enabled === true) {
this._isEnabled = enabled;
if (this._options.stopTrackWhenDisabled) {
const track = this._options.isDisplayMedia === true ? yield this.enableDisplay() : yield this.enableMic();
this._updateTrack(track);
this._onEnableChanged.emit(track);
} else if (this._oldTrack) {
this._updateTrack(this._oldTrack);
this._onEnableChanged.emit(this._oldTrack);
}
log10.debug("resumed");
}
}));
});
}
enableMic() {
return __async(this, null, function* () {
const [track] = (yield navigator.mediaDevices.getUserMedia({
audio: this.trackConstraints
})).getAudioTracks();
return track;
});
}
enableDisplay() {
return __async(this, null, function* () {
const [track] = (yield navigator.mediaDevices.getDisplayMedia({
audio: this.trackConstraints
})).getAudioTracks();
return track;
});
}
/**@description [japanese] 直近100msにおける最大音量を取得する(値の範囲:0-1) */
getAudioLevel() {
if (this._audioLevel === void 0) {
this._audioLevel = new AudioLevel(this.track);
}
return this._isEnabled ? this._audioLevel.calculate() : 0;
}
};
// ../core/src/media/stream/local/customVideo.ts
init_process();
var log11 = new Logger("packages/core/src/media/stream/local/customVideo.ts");
var LocalCustomVideoStream = class extends LocalMediaStreamBase {
constructor(options = {}) {
super(emptyVideoTrack, "video", options);
this.contentType = "video";
this._promiseQueue = new PromiseQueue();
this._stream = null;
}
/**@internal */
setStream(processedStream) {
return __async(this, null, function* () {
if (this._stream) {
throw new Error("ProcessedStream is already exists");
}
this._stream = processedStream;
this._updateTrack(processedStream.track);
});
}
/**@internal */
setEnabled(enabled) {
return __async(this, null, function* () {
yield this._promiseQueue.push(() => __async(this, null, function* () {
var _a2;
yield (_a2 = this._stream) == null ? void 0 : _a2.setEnabled(enabled);
}));
});
}
/**@internal */
updateTrack(track) {
return __async(this, null, function* () {
this._updateTrack(track);
this._onEnableChanged.emit(track);
});
}
release() {
var _a2;
(_a2 = this._stream) == null ? void 0 : _a2.dispose().catch(() => {
log11.error("release failed");
});
}
};
// ../core/src/media/stream/local/video.ts
init_process();
var log12 = new Logger("packages/core/src/media/stream/local/video.ts");
var LocalVideoStream = class extends LocalMediaStreamBase {
constructor(track, options = {}) {
super(track, "video", options);
this.contentType = "video";
this._isEnabled = true;
this._promiseQueue = new PromiseQueue();
if (track.kind !== "video") {
throw createError({
operationName: "LocalVideoStream.constructor",
path: log12.prefix,
info: errors.invalidTrackKind,
payload: { track }
});
}
log12.debug("LocalVideoStream spawned", this.toJSON());
}
/**@internal */
setEnabled(enabled) {
return __async(this, null, function* () {
yield this._promiseQueue.push(() => __async(this, null, function* () {
if (this._isEnabled === true && enabled === false) {
this._isEnabled = enabled;
this._disable("video");
log12.debug("stopped", this.toJSON());
} else if (this._isEnabled === false && enabled === true) {
this._isEnabled = enabled;
if (this._options.stopTrackWhenDisabled) {
const track = this._options.isDisplayMedia === true ? yield this.enableDisplay() : yield this.enableCamera();
this._updateTrack(track);
this._onEnableChanged.emit(track);
} else if (this._oldTrack) {
this._updateTrack(this._oldTrack);
this._onEnableChanged.emit(this._oldTrack);
}
log12.debug("resumed", this.toJSON());
}
}));
});
}
enableCamera() {
return __async(this, null, function* () {
const [track] = (yield navigator.mediaDevices.getUserMedia({
video: this.trackConstraints
})).getVideoTracks();
return track;
});
}
enableDisplay() {
return __async(this, null, function* () {
const [track] = (yield navigator.mediaDevices.getDisplayMedia({
video: this.trackConstraints
})).getVideoTracks();
return track;
});
}
};
// ../core/src/media/stream/local/data.ts
var log13 = new Logger("packages/core/src/media/stream/local/data.ts");
var LocalDataStream = class extends LocalStreamBase {
constructor(options = {}) {
super("data");
this.options = options;
this.contentType = "data";
/**@private */
this._onWriteData = new Event();
this._isEnabled = true;
/**
* @description [japanese] データストリームが書き込み可能な状態になったことを通知するイベント
* イベントデータとして、書き込み可能になったデータストリームのSubscriberの情報が通知される。
*/
this.onWritable = new Event();
/**
* @description [japanese] データストリームが書き込み不可能な状態になったことを通知するイベント。
* イベントデータとして、書き込み不可能になったデータストリームのSubscriberの情報が通知される。
*/
this.onUnwritable = new Event();
this._setLabel("LocalDataStream");
}
/**@internal */
setIsEnabled(b) {
this._isEnabled = b;
}
/**@description [japanese] データを送信する */
write(data) {
if (!this._isEnabled) {
throw createError({
operationName: "LocalDataStream.write",
path: log13.prefix,
info: errors.disabledDataStream
});
}
const isObject2 = !ArrayBuffer.isView(data) && !(data instanceof ArrayBuffer) && !(typeof data === "string");
if (isObject2) {
data = objectFlag + JSON.stringify(data);
}
this._onWriteData.emit(data);
}
};
var objectFlag = "skyway_object:";
// ../core/src/publication/factory.ts
init_process();
// ../core/src/publication/index.ts
var log14 = new Logger("packages/core/src/publication/index.ts");
var PublicationImpl = class {
constructor(args) {
this._codecCapabilities = [];
this._encodings = [];
this._state = "enabled";
this._events = new Events();
this.onSubscribed = this._events.make();
this.onUnsubscribed = this._events.make();
this.onSubscriptionListChanged = this._events.make();
this.onMetadataUpdated = this._events.make();
this.onEnabled = this._events.make();
this.onDisabled = this._events.make();
this.onStateChanged = this._events.make();
this.onConnectionStateChanged = new Event();
/**@private */
this._onEncodingsChanged = this._events.make();
/**@private */
this._onReplaceStream = this._events.make();
this._onEnabled = this._events.make();
this.streamEventDisposer = new EventDisposer();
this.updateMetadata = (metadata) => new Promise((r2, f) => {
const executeUpdate = () => __async(this, null, function* () {
const timestamp = log14.info(
"[start] updateMetadata",
yield createLogPayload({
operationName: "Publication.updateMetadata",
channel: this._channel
}),
this
);
let failed = false;
this._channel._updatePublicationMetadata(this.id, metadata).catch((e2) => {
failed = true;
f(e2);
});
this.onMetadataUpdated.watch(
(e2) => e2.metadata === metadata,
this._context.config.rtcApi.timeout
).then(() => __async(this, null, function* () {
r2();
log14.elapsed(
timestamp,
"[end] updateMetadata",
yield createLogPayload({
operationName: "Publication.updateMetadata",
channel: this._channel
}),
this
);
})).catch((error) => {
if (!failed) {
throw createError({
operationName: "PublicationImpl.updateMetadata",
info: __spreadProps(__spreadValues({}, errors.timeout), {
detail: "publication onMetadataUpdated"
}),
path: log14.prefix,
context: this._context,
channel: this._channel,
error
});
}
});
});
executeUpdate().catch(f);
});
this.disable = () => new Promise((r2, f) => {
if (this.state === "disabled") {
r2();
return;
}
const executeDisable = () => __async(this, null, function* () {
const timestamp = log14.info(
"[start] disable",
yield createLogPayload({
operationName: "Publication.disable",
channel: this._channel
}),
this
);
yield this._disableStream();
let failed = false;
this._channel._disablePublication(this.id).catch((e2) => {
failed = true;
f(e2);
});
this.onDisabled.asPromise(this._context.config.rtcApi.timeout).then(() => __async(this, null, function* () {
r2();
log14.elapsed(
timestamp,
"[end] disable",
yield createLogPayload({
operationName: "Publication.disable",
channel: this._channel
}),
this
);
})).catch((e2) => {
if (!failed) {
f(e2);
}
});
});
executeDisable().catch(f);
});
this.enable = () => new Promise((r2, f) => {
if (this.stream === void 0) {
f(
createError({
operationName: "Publication.enable",
context: this._context,
info: errors.canNotEnableRemotePublication,
path: log14.prefix
})
);
return;
}
if (this.state === "enabled") {
r2();
return;
}
const executeEnable = () => __async(this, null, function* () {
const timestamp = log14.info(
"[start] enable",
yield createLogPayload({
operationName: "Publication.enable",
channel: this._channel
}),
this
);
let failed = false;
this._channel._enablePublication(this.id).catch((e2) => {
failed = true;
f(e2);
});
this._onEnabled.asPromise(this._context.config.rtcApi.timeout).then(() => __async(this, null, function* () {
yield this._enableStream();
this.onEnabled.emit();
this.onStateChanged.emit();
log14.elapsed(
timestamp,
"[end] enable",
yield createLogPayload({
operationName: "Publication.enable",
channel: this._channel
}),
this
);
r2();
})).catch((e2) => {
if (!failed) {
f(e2);
}
});
});
executeEnable().catch(f);
});
var _a2, _b2, _c;
this.id = args.id;
this._channel = args.channel;
this._context = this._channel._context;
this.publisher = args.publisher;
this.contentType = args.contentType;
this._metadata = args.metadata;
this.origin = args.origin;
this.setCodecCapabilities((_a2 = args.codecCapabilities) != null ? _a2 : []);
this.setEncodings(normalizeEncodings((_b2 = args.encodings) != null ? _b2 : []));
this._state = args.isEnabled ? "enabled" : "disabled";
if (args.stream) {
this._setStream(args.stream);
}
this._analytics = (_c = this._channel.localPerson) == null ? void 0 : _c._analytics;
this.type = args.type;
log14.debug("publication spawned", this.toJSON());
}
get codecCapabilities() {
return this._codecCapabilities;
}
setCodecCapabilities(_codecCapabilities) {
this._codecCapabilities = _codecCapabilities;
}
get encodings() {
return this._encodings;
}
setEncodings(_encodings) {
this._encodings = _encodings;
}
get stream() {
return this._stream;
}
/**@internal */
_setStream(stream) {
this._stream = stream;
if (stream) {
stream._onConnectionStateChanged.add((e2) => {
log14.debug("onConnectionStateChanged", this.id, e2);
this.onConnectionStateChanged.emit(e2);
}).disposer(this.streamEventDisposer);
} else {
this.streamEventDisposer.dispose();
}
}
get metadata() {
return this._metadata;
}
get state() {
return this._state;
}
get deviceName() {
if (this.stream instanceof LocalDataStream) {
return void 0;
} else {
const withDeviceStream = this.stream;
return withDeviceStream.track.label;
}
}
get subscriptions() {
return this._channel.subscriptions.filter(
(s) => s.publication.id === this.id
);
}
/**@private */
_updateMetadata(metadata) {
this._metadata = metadata;
this.onMetadataUpdated.emit({ metadata });
}
/**@private */
_disable() {
return __async(this, null, function* () {
yield this._disableStream();
this.onDisabled.emit();
this.onStateChanged.emit();
});
}
/**@private */
_enable() {
if (this.stream) {
this._onEnabled.emit();
} else {
this._state = "enabled";
this.onEnabled.emit();
this.onStateChanged.emit();
}
}
/**@private */
_unpublished() {
this._state = "canceled";
if (this.stream) {
this.stream._unpublished();
}
this.onStateChanged.emit();
this._dispose();
}
/**@private */
_subscribed(subscription) {
this.onSubscribed.emit({ subscription });
this.onSubscriptionListChanged.emit();
}
/**@private */
_unsubscribed(subscription) {
this.onUnsubscribed.emit({ subscription });
this.onSubscriptionListChanged.emit();
}
updateEncodings(encodings) {
log14.info("updateEncodings", { encodings }, this);
this.setEncodings(normalizeEncodings(sortEncodingParameters(encodings)));
this._onEncodingsChanged.emit(encodings);
if (this._analytics && !this._analytics.isClosed()) {
void this._analytics.client.sendPublicationUpdateEncodingsReport({
publicationId: this.id,
encodings: this.encodings,
updatedAt: Date.now()
});
}
}
_disableStream() {
return __async(this, null, function* () {
if (this.state === "disabled") {
return;
}
this._state = "disabled";
if (!this.stream) {
return;
}
if (this.stream.contentType === "data") {
this.stream.setIsEnabled(false);
} else {
yield this.stream.setEnabled(false).catch((e2) => {
log14.warn(
createWarnPayload({
channel: this._channel,
operationName: "Publication._disableStream",
payload: e2,
detail: "setEnabled failed"
})
);
});
}
createLogPayload({
operationName: "Publication._disableStream",
channel: this._channel
}).then(
(p) => log14.info("publication _disableStream", p, { publication: this })
).catch(() => {
});
});
}
_enableStream() {
return __async(this, null, function* () {
if (this.state === "enabled") {
return;
}
this._state = "enabled";
if (!this.stream) {
return;
}
createLogPayload({
operationName: "Publication._enableStream",
channel: this._channel
}).then(
(p) => log14.info("publication _enableStream", p, { publication: this })
).catch(() => {
});
if (this.stream.contentType === "data") {
this.stream.setIsEnabled(true);
} else {
yield this.stream.setEnabled(true).catch((e2) => {
log14.warn(
createWarnPayload({
channel: this._channel,
operationName: "Publication._disableStream",
payload: e2,
detail: "setEnabled failed"
})
);
});
}
});
}
replaceStream(stream, options = {}) {
var _a2;
log14.info("replaceStream", { stream, options }, this);
if (!this.stream) {
throw createError({
operationName: "PublicationImpl.replaceStream",
context: this._context,
info: errors.canNotUseReplaceStream,
path: log14.prefix
});
}
if (stream.contentType !== this.contentType) {
throw createError({
operationName: "PublicationImpl.replaceStream",
context: this._context,
info: errors.invalidContentType,
path: log14.prefix
});
}
if ((_a2 = options.releaseOldStream) != null ? _a2 : true) {
const old = this.stream;
old.release();
}
createLogPayload({
operationName: "PublicationImpl.replaceStream",
channel: this._channel
}).then((res) => log14.debug(res, { old: this.stream, new: stream })).catch((e2) => e2);
stream.setEnabled(this._state === "enabled").catch((e2) => {
log14.error("replaceStream stream.setEnabled", e2, this.toJSON());
});
const oldStream = this._stream;
this._setStream(stream);
this._onReplaceStream.emit({ newStream: stream, oldStream });
oldStream._unpublished();
if (this._analytics && !this._analytics.isClosed()) {
void this._analytics.client.sendMediaDeviceReport({
publicationId: this.id,
mediaDeviceName: this.deviceName,
mediaDeviceTrigger: "replaceStream",
updatedAt: Date.now()
});
}
}
getStats(selector) {
if (!this.stream) {
throw createError({
operationName: "PublicationImpl.getStats",
context: this._context,
info: errors.streamNotExistInSubscription,
path: log14.prefix
});
}
return this.stream._getStats(selector);
}
getRTCPeerConnection(selector) {
if (!this.stream) {
throw createError({
operationName: "PublicationImpl.getRTCPeerConnection",
context: this._context,
info: errors.streamNotExistInSubscription,
path: log14.prefix
});
}
return this.stream._getRTCPeerConnection(selector);
}
getConnectionState(selector) {
if (!this.stream) {
throw createError({
operationName: "PublicationImpl.getConnectionState",
context: this._context,
info: errors.streamNotExistInSubscription,
path: log14.prefix
});
}
return this.stream._getConnectionState(selector);
}
/**@private */
toJSON() {
var _a2;
return {
id: this.id,
channelId: this._channel.id,
publisherId: this.publisher.id,
origin: (_a2 = this.origin) == null ? void 0 : _a2.id,
contentType: this.contentType,
metadata: this.metadata,
codecCapabilities: this.codecCapabilities,
encodings: this.encodings,
state: this.state,
stream: this.stream,
type: this.type
};
}
_dispose() {
this._events.dispose();
}
};
var normalizeEncodings = (encodings) => encodings.map((e2, i) => {
var _a2;
return __spreadProps(__spreadValues({}, e2), {
id: (_a2 = e2.id) != null ? _a2 : i.toString()
});
});
var sortEncodingParameters = (encodings) => {
const [encode3] = encodings;
if (encode3.maxBitrate) {
return encodings.sort((a, b) => {
var _a2, _b2;
return ((_a2 = a.maxBitrate) != null ? _a2 : 0) - ((_b2 = b.maxBitrate) != null ? _b2 : 0);
});
} else if (encode3.scaleResolutionDownBy) {
return encodings.sort(
(a, b) => {
var _a2, _b2;
return ((_a2 = b.scaleResolutionDownBy) != null ? _a2 : 0) - ((_b2 = a.scaleResolutionDownBy) != null ? _b2 : 0);
}
);
} else if (encode3.maxFramerate) {
return encodings.sort(
(a, b) => {
var _a2, _b2;
return ((_a2 = a.maxFramerate) != null ? _a2 : 0) - ((_b2 = b.maxFramerate) != null ? _b2 : 0);
}
);
}
return encodings;
};
// ../core/src/member/remoteMember.ts
init_process();
// ../core/src/member/localPerson/agent/index.ts
init_process();
// ../core/src/member/localPerson/agent/publishing.ts
init_process();
var log15 = new Logger("packages/core/src/dataPlane/agent/publishing.ts");
// ../core/src/member/localPerson/agent/subscribing.ts
init_process();
// ../core/src/member/localPerson/adapter.ts
init_process();
// ../core/src/member/localPerson/factory.ts
init_process();
// ../core/src/const.ts
init_process();
var MaxIceParamServerTTL = 24 * 60 * 60;
// ../core/src/external/ice.ts
init_process();
var log16 = new Logger("packages/core/src/external/ice.ts");
// ../core/src/external/signaling.ts
init_process();
// ../signaling-client/src/index.ts
init_process();
// ../signaling-client/src/signalingClient.ts
init_process();
// ../signaling-client/src/clientEvent.ts
init_process();
// ../signaling-client/src/payloadTypes.ts
init_process();
// ../signaling-client/src/socket.ts
init_process();
var import_isomorphic_ws = __toESM(require_browser());
// ../signaling-client/src/utils/event.ts
init_process();
// ../signaling-client/src/version.ts
init_process();
// ../signaling-client/src/utils/logger.ts
init_process();
// ../core/src/external/signaling.ts
var log17 = new Logger("packages/core/src/external/signaling.ts");
// ../core/src/member/localPerson/factory.ts
var log18 = new Logger("packages/core/src/member/person/local/factory.ts");
// ../core/src/member/localPerson/index.ts
var log19 = new Logger("packages/core/src/member/localPerson/index.ts");
// ../core/src/subscription/factory.ts
init_process();
// ../core/src/subscription/index.ts
init_process();
var log20 = new Logger("packages/core/src/subscription/index.ts");
// ../core/src/validation.ts
init_process();
// ../core/src/channel/index.ts
var log21 = new Logger("packages/core/src/channel/index.ts");
// ../core/src/channel/event.ts
init_process();
// ../core/src/config.ts
init_process();
var import_deepmerge = __toESM(require_cjs());
var ContextConfig = class {
/**@internal */
constructor(options = {}) {
/**@internal */
this.rtcApi = {
domain: "rtc-api.skyway.ntt.com",
timeout: 3e4,
secure: true,
eventSubscribeTimeout: 5e3
};
/**@internal */
this.iceParamServer = {
domain: "ice-params.skyway.ntt.com",
version: 1,
secure: true
};
/**@internal */
this.signalingService = {
domain: "signaling.skyway.ntt.com",
secure: true
};
/**@internal */
this.analyticsService = {
domain: "analytics-logging.skyway.ntt.com",
secure: true
};
this.rtcConfig = {
timeout: 3e4,
turnPolicy: "enable",
turnProtocol: "all",
iceDisconnectBufferTimeout: 5e3
};
this.token = {
updateRemindSec: 30
};
this.log = {
level: "error",
format: "string"
};
/**@internal */
this.internal = {
disableDPlane: false
};
this.member = {
keepaliveIntervalGapSec: 30,
keepaliveIntervalSec: 30,
preventAutoLeaveOnBeforeUnload: false
};
Object.assign(this, (0, import_deepmerge.default)(this, options));
}
};
// ../core/src/context.ts
init_process();
// ../rtc-api-client/src/index.ts
init_process();
// ../rtc-api-client/src/client.ts
init_process();
// ../rtc-rpc-api-client/src/index.ts
init_process();
// ../rtc-rpc-api-client/src/client.ts
init_process();
// ../rtc-rpc-api-client/src/const.ts
init_process();
var defaultDomain = "rtc-api.skyway.ntt.com";
var rpcTimeout = 2e4;
var MaxRetry = 8;
// ../rtc-rpc-api-client/src/errors.ts
init_process();
var errors2 = {
timeout: { name: "timeout", detail: "", solution: "" },
internalError: { name: "internalError", detail: "", solution: "" },
invalidParameter: { name: "invalidParameter", detail: "", solution: "" },
connectionDisconnected: {
name: "connectionDisconnected",
detail: "",
solution: ""
},
websocketConnectionFailure: {
name: "connectionFailure",
detail: "\u30B5\u30FC\u30D0\u3078\u306E\u63A5\u7D9A\u306B\u5931\u6557\u3057\u307E\u3057\u305F",
solution: "\u30CD\u30C3\u30C8\u30EF\u30FC\u30AF\u63A5\u7D9A\u72B6\u6CC1\u304A\u3088\u3073\u30D5\u30EA\u30FC\u30D7\u30E9\u30F3\u3092\u3054\u5229\u7528\u306E\u5834\u5408\u306F\u30EA\u30BD\u30FC\u30B9\u5229\u7528\u91CF\u3092\u78BA\u8A8D\u3057\u3066\u304F\u3060\u3055\u3044"
},
rpcResponseError: {
name: "rpcResponseError",
detail: "",
solution: "",
error: {}
},
onClosedWhileRequesting: {
name: "onClosedWhileRequesting",
detail: "request\u4E2D\u306B\u30AF\u30E9\u30A4\u30A2\u30F3\u30C8\u304C\u7D42\u4E86\u3055\u308C\u307E\u3057\u305F",
solution: "\u30EA\u30AF\u30A8\u30B9\u30C8\u306E\u5B8C\u4E86\u3092\u78BA\u8A8D\u3057\u3066\u304B\u3089\u30AF\u30E9\u30A4\u30A2\u30F3\u30C8\u3092\u7D42\u4E86\u3055\u305B\u3066\u304F\u3060\u3055\u3044"
},
failedToConnectRtcAPI: {
name: "failedToConnectRtcAPI",
detail: "rtc-api server\u3078\u306E\u63A5\u7D9A\u306B\u5931\u6557\u3057\u307E\u3057\u305F",
solution: "\u30A4\u30F3\u30BF\u30FC\u30CD\u30C3\u30C8\u63A5\u7D9A\u72B6\u6CC1\u3068Token\u306E\u5185\u5BB9\u304C\u6B63\u3057\u3044\u304B\u3001\u307E\u305F\u30D5\u30EA\u30FC\u30D7\u30E9\u30F3\u3092\u3054\u5229\u7528\u306E\u5834\u5408\u306F\u30EA\u30BD\u30FC\u30B9\u5229\u7528\u91CF\u3092\u78BA\u304B\u3081\u3066\u304F\u3060\u3055\u3044"
},
failedToUpdateMemberTTL: {
name: "failedToUpdateMemberTTL",
detail: "updateMemberTTL\u3092\u518D\u8A66\u884C\u3057\u307E\u3057\u305F\u304C\u3001\u5931\u6557\u3057\u307E\u3057\u305F",
solution: "\u30A4\u30F3\u30BF\u30FC\u30CD\u30C3\u30C8\u63A5\u7D9A\u72B6\u6CC1\u3092\u78BA\u8A8D\u3057\u3066\u304F\u3060\u3055\u3044"
}
};
// ../rtc-rpc-api-client/src/rpc.ts
init_process();
var import_isomorphic_ws2 = __toESM(require_browser());
// ../rtc-rpc-api-client/src/util.ts
init_process();
function createError2({
operationName,
info,
error,
path,
payload,
channelId,
appId,
memberId
}) {
return new SkyWayError({
error,
info,
payload: { payload, operationName, channelId, appId, memberId },
path
});
}
function createWarnPayload2({
appId,
detail,
channelId,
operationName,
payload,
memberId
}) {
const warn = {
operationName,
payload,
detail,
appId,
channelId,
memberId
};
return warn;
}
// ../rtc-rpc-api-client/src/rpc.ts
var log22 = new Logger("packages/rtc-rpc-api-client/src/rpc.ts");
var WS_CLOSE_CODE_USAGE_LIMIT_EXCEEDED = 4291;
var RPC = class {
constructor() {
this._id = v4_default();
this.closed = false;
this.negotiated = false;
this._reconnecting = false;
this._pendingRequests = [];
this._events = new Events();
this._onMessage = this._events.make();
this.onNotify = this._events.make();
this.onFatalError = this._events.make();
this.onDisconnected = this._events.make();
this.onClosed = this._events.make();
this._send = (request) => new Promise((r2, f) => {
const executeSend = () => __async(this, null, function* () {
yield new Promise((r3) => setTimeout(r3, 0));
if (this._ws.readyState !== this._ws.OPEN) {
f(
createError2({
operationName: "RPC._send",
info: __spreadProps(__spreadValues({}, errors2.internalError), { detail: "wrong state" }),
path: log22.prefix,
payload: {
request,
wsReadyState: wsStates[this._ws.readyState]
}
})
);
return;
}
this._ws.send(JSON.stringify(request), (error) => {
if (error) {
throw f(
createError2({
operationName: "RPC._send",
info: __spreadProps(__spreadValues({}, errors2.internalError), {
detail: "failed to send rpc message"
}),
path: log22.prefix,
error
})
);
}
});
r2();
});
executeSend().catch(f);
});
}
set reconnecting(b) {
this._reconnecting = b;
}
get reconnecting() {
return this._reconnecting;
}
connect(_0) {
return __async(this, arguments, function* ({
domain,
token,
secure
}) {
const subProtocol = token;
this._ws = new import_isomorphic_ws2.default(
`${secure ? "wss" : "ws"}://${domain}/ws`,
subProtocol
);
this._ws.onmessage = (ev) => {
this._onMessage.emit(JSON.parse(ev.data));
};
this._ws.onclose = (e2) => __async(this, null, function* () {
log22.debug("websocket closed", {
id: this._id,
code: e2.code,
reason: e2.reason
});
if (e2.code === WS_CLOSE_CODE_USAGE_LIMIT_EXCEEDED) {
this.close();
} else {
this.onDisconnected.emit();
}
});
this._onMessage.add((msg) => {
if (isNotifyMessage(msg)) {
this.onNotify.emit(msg);
}
});
const error = yield new Promise((r2, f) => {
const timeout = setTimeout(() => {
f(
createError2({
operationName: "RPC.connect",
info: __spreadProps(__spreadValues({}, errors2.timeout), { detail: "ws.open" }),
path: log22.prefix
})
);
}, 5e3);
this._ws.onerror = (e2) => {
f(
createError2({
operationName: "RPC.connect",
info: errors2.websocketConnectionFailure,
path: log22.prefix,
error: e2
})
);
};
this._ws.onopen = () => {
clearTimeout(timeout);
r2();
};
}).catch((e2) => e2);
if (error) {
throw error;
}
this.negotiated = true;
});
}
close() {
if (this.closed) {
return;
}
this.closed = true;
log22.debug("closed");
this._ws.close();
this.onClosed.emit();
this._events.dispose();
}
resolvePendingRequests() {
log22.debug("resolve pendingRequests", [...this._pendingRequests]);
this._pendingRequests.forEach((req) => __async(this, null, function* () {
yield this._send(req);
}));
this._pendingRequests = [];
}
/**
* @throws {@link SkyWayError}
*/
request(method, params) {
return __async(this, null, function* () {
if (this.closed) {
throw createError2({
operationName: "RPC.request",
info: __spreadProps(__spreadValues({}, errors2.internalError), {
detail: "rpc closed"
}),
path: log22.prefix,
payload: { method, params, id: this._id }
});
}
let promiseResolved = false;
try {
const request = buildRequest(method, params);
const handleMessage = () => __async(this, null, function* () {
return yield this._onMessage.watch((msg) => msg.id === request.id, rpcTimeout).catch(() => {
if (promiseResolved) {
return;
}
throw createError2({
operationName: "RPC.request",
info: __spreadProps(__spreadValues({}, errors2.timeout), {
detail: "rpc request timeout"
}),
path: log22.prefix,
payload: {
rpcTimeout,
method,
params,
wsReadyState: wsStates[this._ws.readyState],
id: this._id
}
});
});
});
const pendingRequest = () => __async(this, null, function* () {
log22.warn(
"[start] reconnecting. pending request",
createWarnPayload2({
operationName: "RPC.request",
detail: "[start] reconnecting. pending request",
payload: { request, id: this._id }
})
);
this._pendingRequests.push(request);
const message2 = yield Promise.race([
handleMessage(),
this.onFatalError.asPromise(rpcTimeout + 100).then((e2) => {
if (!promiseResolved) {
log22.error(
"[failed] reconnecting. pending request",
createError2({
operationName: "RPC.request",
info: __spreadProps(__spreadValues({}, errors2.internalError), {
detail: "onFatalError while request"
}),
path: log22.prefix
}),
e2
);
}
throw e2;
})
]);
promiseResolved = true;
log22.warn(
"[end] reconnecting. pending request",
createWarnPayload2({
operationName: "RPC.request",
detail: "[end] reconnecting. pending request",
payload: { request, id: this._id }
})
);
return message2;
});
let message;
if (!this._reconnecting) {
this._send(request).catch((e2) => {
log22.error("send error", e2);
});
message = yield Promise.race([
handleMessage(),
// 返信待ち中に接続が切れた場合
(() => __async(this, null, function* () {
yield this.onDisconnected.asPromise(rpcTimeout + 100);
if (promiseResolved) {
return {};
}
try {
const message2 = yield pendingRequest();
log22.warn(
createWarnPayload2({
operationName: "request.pendingRequest",
detail: "success to handle disconnected"
})
);
return message2;
} catch (error) {
throw createError2({
operationName: "RPC.request",
info: errors2.connectionDisconnected,
path: log22.prefix,
error
});
}
}))(),
this.onFatalError.asPromise(rpcTimeout + 100).then((e2) => {
if (promiseResolved) {
return {};
}
throw createError2({
operationName: "RPC.request",
info: __spreadProps(__spreadValues({}, errors2.internalError), {
detail: "onFatalError while requesting"
}),
path: log22.prefix,
error: e2
});
}),
this.onClosed.asPromise(rpcTimeout + 100).then(() => {
if (promiseResolved) {
return {};
}
throw createError2({
operationName: "RPC.request",
info: errors2.onClosedWhileRequesting,
path: log22.prefix,
payload: { method, params }
});
})
]);
promiseResolved = true;
} else {
message = yield pendingRequest();
}
if (message.error) {
log22.warn("[failed] request ", { message, method, params });
throw createError2({
operationName: "RPC.request",
info: __spreadProps(__spreadValues({}, errors2.rpcResponseError), {
detail: method,
error: message.error
}),
payload: { message, method, params },
path: log22.prefix
});
}
return message.result;
} catch (error) {
promiseResolved = true;
throw error;
}
});
}
notify(method, params) {
return __async(this, null, function* () {
const request = buildRequest(method, params, true);
yield this._send(request);
});
}
batch(requests) {
return __async(this, null, function* () {
const messages = requests.map(
({ method, params }) => buildRequest(method, params)
);
this._send(messages).catch((e2) => {
throw e2;
});
const responses = yield Promise.all(
messages.map((_0) => __async(this, [_0], function* ({ id }) {
const message = yield this._onMessage.watch(
(msg) => msg.id === id,
rpcTimeout
);
return message;
}))
);
return responses;
});
}
};
var buildRequest = (method, params, notify) => {
if (notify) {
return { jsonrpc: "2.0", method, params };
}
const id = v4_default();
return { jsonrpc: "2.0", method, params, id };
};
var isNotifyMessage = (msg) => {
const notify = msg;
if (notify.method && notify.id === void 0) {
return true;
}
return false;
};
var wsStates = ["CONNECTING", "OPEN", "CLOSING", "CLOSED"];
// ../rtc-rpc-api-client/src/client.ts
var log23 = new Logger("packages/rtc-rpc-api-client/src/client.ts");
var _a, _b;
var RtcRpcApiClient = class {
constructor(config) {
this.config = config;
this.closed = false;
this._domain = (_a = this.config.domain) != null ? _a : defaultDomain;
this._secure = (_b = this.config.secure) != null ? _b : true;
this._token = this.config.token;
/**@private */
this._rpc = new RPC();
this._subscribingChannelEvents = /* @__PURE__ */ new Set();
this._subscribingChannelVersions = {};
this._httpClient = new HttpClient(
`http${this.config.secure ? "s" : ""}://${this.config.domain}`
);
this._reconnectCount = 0;
this._reconnectLimit = MaxRetry;
this._events = new Events();
this.onEvent = this._events.make();
this.onFatalError = this._events.make();
this.onClose = this._events.make();
this.onReconnected = this._events.make();
var _a2, _b2, _c, _d;
Logger.level = (_b2 = (_a2 = config.log) == null ? void 0 : _a2.level) != null ? _b2 : Logger.level;
Logger.format = (_d = (_c = config.log) == null ? void 0 : _c.format) != null ? _d : Logger.format;
log23.debug("RtcRpcApiClient spawned", config);
this._rpc.onNotify.add((notify) => {
if (notify.method === "channelEventNotification") {
const event = notify.params;
this._subscribingChannelVersions[event.data.channel.id] = event.data.channel.version;
this.onEvent.emit({ channelId: event.data.channel.id, event });
}
});
this._rpc.onDisconnected.add(() => __async(this, null, function* () {
if (this._rpc.negotiated && !this._rpc.closed && !this._rpc.reconnecting) {
yield this._reconnect();
}
}));
this._rpc.onFatalError.once((e2) => {
log23.error("fatal error", e2);
this.onFatalError.emit(e2);
this.close();
});
}
get token() {
return this._token;
}
_reconnect() {
return __async(this, null, function* () {
if (this._reconnectCount >= this._reconnectLimit) {
this._rpc.onFatalError.emit(
createError2({
operationName: "RtcRpcApiClient._reconnect",
info: {
name: "failed to reconnect",
detail: "_reconnectLimit exceeded",
solution: ""
},
path: log23.prefix
})
);
this.close();
return;
}
this._rpc.reconnecting = true;
log23.warn(
"[start] reconnect",
createWarnPayload2({
operationName: "RtcRpcApiClient._reconnect",
detail: "reconnect start",
payload: {
reconnectCount: this._reconnectCount,
limit: this._reconnectLimit
}
})
);
this._reconnectCount++;
const backOffTime = __pow(this._reconnectCount, 2) * 100 + __pow(this._reconnectCount, 2) * 100 * Math.random();
yield new Promise((r2) => setTimeout(r2, backOffTime));
try {
yield this.connect().catch((err) => {
log23.warn(
`[failed] reconnect rtc api`,
createWarnPayload2({
operationName: "RtcRpcApiClient._reconnect",
detail: "connect rpc failed",
payload: {
reconnectCount: this._reconnectCount
}
}),
err
);
throw err;
});
this._rpc.reconnecting = false;
this._reconnectCount = 0;
this._rpc.resolvePendingRequests();
yield Promise.all(
[...this._subscribingChannelEvents].map((s) => __async(this, null, function* () {
const [appId, channelId] = s.split(":");
const offset = this._subscribingChannelVersions[channelId];
yield this.subscribeChannelEvents({
appId,
channelId,
offset
});
}))
).catch((e2) => {
log23.warn(
"subscribeChannelEvents failed",
createWarnPayload2({
operationName: "RtcRpcApiClient._reconnect",
detail: "subscribeChannelEvents failed",
payload: {
reconnectCount: this._reconnectCount
}
}),
e2
);
throw e2;
});
log23.warn(
"[end] reconnect",
createWarnPayload2({
operationName: "RtcRpcApiClient._reconnect",
detail: "reconnect finished",
payload: {
reconnectCount: this._reconnectCount
}
})
);
this.onReconnected.emit();
} catch (error) {
log23.warn(
"[failed] reconnect",
createWarnPayload2({
operationName: "RtcRpcApiClient._reconnect",
detail: "reconnect failed",
payload: {
reconnectCount: this._reconnectCount
}
}),
error
);
yield this._reconnect();
}
});
}
updateToken(token) {
return __async(this, null, function* () {
log23.debug("token update", { token });
this._token = token;
yield this._updateAuthToken();
});
}
close() {
if (this.closed) {
return;
}
this.closed = true;
log23.debug("closed");
this._rpc.close();
this.onClose.emit();
this._events.dispose();
}
health() {
return __async(this, null, function* () {
const response = yield this._httpClient.get("/health");
return response;
});
}
/** @throws {@link SkyWayError} */
connect() {
return __async(this, null, function* () {
log23.debug("connect to rtc api rpc", this._domain);
yield this._rpc.connect({
domain: this._domain,
token: this.token,
secure: this._secure
}).catch((e2) => {
throw createError2({
operationName: "RtcRpcApiClient.connect",
info: errors2.failedToConnectRtcAPI,
error: e2,
path: log23.prefix
});
});
});
}
_channelSubscribed(appId, channelId) {
this._subscribingChannelEvents.add(`${appId}:${channelId}`);
log23.debug("_channelSubscribed", {
appId,
channelId,
_subscribingChannelEvents: [...this._subscribingChannelEvents]
});
}
_isSubscribingChannel(appId, channelId) {
return this._subscribingChannelEvents.has(`${appId}:${channelId}`);
}
createChannel(_0) {
return __async(this, arguments, function* ({
name,
metadata,
appId
}) {
const { channel } = yield this._rpc.request("createChannel", {
name,
metadata,
appId,
authToken: this.token
});
this._channelSubscribed(appId, channel.id);
return channel;
});
}
findOrCreateChannel(_0) {
return __async(this, arguments, function* ({
name,
metadata,
appId
}) {
const { channel } = yield this._rpc.request(
"findOrCreateChannel",
{
name,
metadata,
appId,
authToken: this.token
}
);
this._channelSubscribed(appId, channel.id);
return channel;
});
}
getChannel(_0) {
return __async(this, arguments, function* ({ appId, id }) {
const res = yield this._rpc.request(
"getChannel",
{
id,
appId,
authToken: this.token
}
);
if (!this._isSubscribingChannel(appId, id)) {
this._channelSubscribed(appId, id);
yield this.subscribeChannelEvents({
appId,
channelId: id,
offset: res.channel.version
});
}
return res.channel;
});
}
getChannelByName(_0) {
return __async(this, arguments, function* ({
name,
appId
}) {
const res = yield this._rpc.request(
"getChannelByName",
{
name,
appId,
authToken: this.token
}
);
const channelId = res.channel.id;
if (!this._isSubscribingChannel(appId, channelId)) {
this._channelSubscribed(appId, channelId);
yield this.subscribeChannelEvents({
appId,
channelId,
offset: res.channel.version
});
}
return res.channel;
});
}
deleteChannel(_0) {
return __async(this, arguments, function* ({ id, appId }) {
yield this._rpc.request("deleteChannel", {
id,
appId,
authToken: this.token
});
});
}
updateChannelMetadata(_0) {
return __async(this, arguments, function* ({
id,
metadata,
appId
}) {
yield this._rpc.request("updateChannelMetadata", {
id,
metadata,
appId,
authToken: this.token
});
});
}
addMember(_0) {
return __async(this, arguments, function* ({
channelId,
name,
metadata,
subscribeChannelEvents,
appId,
ttlSec,
subtype,
type
}) {
const res = yield this._rpc.request("addMember", {
channelId,
name,
metadata,
subscribeChannelEvents,
appId,
ttlSec: ttlSec && parseInt(ttlSec.toString(), 10),
authToken: this.token,
subtype,
type
});
return res;
});
}
updateMemberTtl(_0) {
return __async(this, arguments, function* (args, backoff = new BackOff({ times: 8 })) {
const { appId, channelId, memberId, ttlSec } = args;
try {
yield this._rpc.request("updateMemberTtl", {
appId,
channelId,
memberId,
ttlSec: ttlSec && parseInt(ttlSec.toString(), 10),
authToken: this.token
});
} catch (e2) {
if (!backoff.exceeded) {
log23.warn(
"retry updateMemberTtl",
createWarnPayload2({
operationName: "RtcRpcApiClient.updateMemberTtl",
detail: "retry updateMemberTtl",
appId,
channelId,
memberId,
payload: { backoff: backoff.count }
}),
e2
);
yield backoff.wait();
yield this.updateMemberTtl(args, backoff);
} else {
const error = new SkyWayError({
path: log23.prefix,
info: errors2.failedToUpdateMemberTTL,
error: e2
});
throw error;
}
}
});
}
updateMemberMetadata(_0) {
return __async(this, arguments, function* ({
channelId,
memberId,
metadata,
appId
}) {
yield this._rpc.request("updateMemberMetadata", {
channelId,
memberId,
metadata,
appId,
authToken: this.token
});
});
}
leaveChannel(_0) {
return __async(this, arguments, function* ({
channelId,
id,
appId
}) {
yield this._rpc.request("removeMember", {
channelId,
id,
appId,
authToken: this.token
});
});
}
publishStream(_0) {
return __async(this, arguments, function* ({
appId,
channelId,
publisherId,
contentType,
metadata,
origin: origin2,
codecCapabilities,
encodings,
isEnabled,
type
}) {
const res = yield this._rpc.request("publishStream", {
channelId,
publisherId,
contentType: contentType[0].toUpperCase() + contentType.slice(1),
metadata,
origin: origin2,
codecCapabilities,
encodings: encodings == null ? void 0 : encodings.map((e2) => ({
id: e2.id
})),
isEnabled,
type,
appId,
authToken: this.token
});
return { publicationId: res.id };
});
}
disablePublication(_0) {
return __async(this, arguments, function* ({
channelId,
publicationId,
appId
}) {
yield this._rpc.request("disablePublication", {
channelId,
appId,
publicationId,
authToken: this.token
});
});
}
enablePublication(_0) {
return __async(this, arguments, function* ({
channelId,
publicationId,
appId
}) {
yield this._rpc.request("enablePublication", {
channelId,
appId,
publicationId,
authToken: this.token
});
});
}
updatePublicationMetadata(_0) {
return __async(this, arguments, function* ({
channelId,
publicationId,
appId,
metadata
}) {
yield this._rpc.request("updatePublicationMetadata", {
channelId,
publicationId,
metadata,
appId,
authToken: this.token
});
});
}
unpublishStream(_0) {
return __async(this, arguments, function* ({
channelId,
publicationId,
appId
}) {
yield this._rpc.request("unpublishStream", {
channelId,
publicationId,
appId,
authToken: this.token
});
});
}
subscribeStream(_0) {
return __async(this, arguments, function* ({
channelId,
subscriberId,
publicationId,
appId
}) {
const res = yield this._rpc.request("subscribeStream", {
channelId,
subscriberId,
publicationId,
appId,
authToken: this.token
});
return { subscriptionId: res.id };
});
}
unsubscribeStream(_0) {
return __async(this, arguments, function* ({
channelId,
subscriptionId,
appId
}) {
yield this._rpc.request("unsubscribeStream", {
channelId,
subscriptionId,
appId,
authToken: this.token
});
});
}
/**
* @returns Date.now()
*/
getServerUnixtime(_0) {
return __async(this, arguments, function* (args, backoff = new BackOff({ times: 8 })) {
const { appId } = args;
try {
const res = yield this._rpc.request("getServerUnixtime", {
appId,
authToken: this.token
});
return res.unixtime;
} catch (error) {
if (!backoff.exceeded) {
log23.warn(
createWarnPayload2({
operationName: "RtcRpcApiClient.getServerUnixtime",
detail: "retry getServerUnixtime",
appId,
payload: { backoff: backoff.count }
}),
error
);
yield backoff.wait();
return this.getServerUnixtime(args, backoff);
} else {
throw error;
}
}
});
}
/**@description [japanese] 現在のセッションに関連付けられている SkyWayAuthToken を更新します */
_updateAuthToken() {
return __async(this, null, function* () {
yield this._rpc.request("updateAuthToken", {
authToken: this.token
});
});
}
/**
* @description
* - 指定した Channel の Event を Subscribe していなければ Event が生じるたびに Notification が送られるようになります。
* - Subscribeした時点で、指定された offset (default to 0) の version から、最新の version までのイベントが送られます。
*/
subscribeChannelEvents(_0) {
return __async(this, arguments, function* ({
appId,
channelId,
offset
}) {
try {
log23.debug("[start] subscribeChannelEvents", { offset });
yield this._rpc.request("subscribeChannelEvents", {
appId,
authToken: this.token,
channelId,
offset
});
log23.debug("[end] subscribeChannelEvents", { offset });
} catch (error) {
if (error instanceof SkyWayError && error.info.name === errors2.connectionDisconnected.name) {
log23.warn(
"reconnect happened while subscribeChannelEvents. retry",
createWarnPayload2({
operationName: "RtcRpcApiClient.subscribeChannelEvents",
detail: "reconnect happened while subscribeChannelEvents. retry",
appId,
channelId,
payload: { offset }
}),
error
);
yield this.subscribeChannelEvents({ appId, channelId, offset });
} else {
log23.error(
"[failed] subscribeChannelEvents",
createError2({
operationName: "RtcRpcApiClient.subscribeChannelEvents",
info: __spreadProps(__spreadValues({}, errors2.internalError), {
detail: "subscribeChannelEvents failed"
}),
path: log23.prefix,
error,
payload: { offset },
appId,
channelId
})
);
throw error;
}
}
});
}
};
// ../rtc-rpc-api-client/src/event.ts
init_process();
// ../rtc-api-client/src/config.ts
init_process();
var import_deepmerge2 = __toESM(require_cjs());
var Config = class {
constructor(options = {}) {
this.rtcApi = {
domain: "rtc-api.skyway.ntt.com",
timeout: 3e4,
secure: true,
eventSubscribeTimeout: 5e3
};
this.log = {
level: "error",
format: "object"
};
Object.assign(this, (0, import_deepmerge2.default)(this, options));
}
};
// ../rtc-api-client/src/infrastructure/api.ts
init_process();
// ../rtc-api-client/src/errors.ts
init_process();
var errors3 = __spreadProps(__spreadValues({}, errors2), {
invalidParameter: { name: "invalidParameter", detail: "", solution: "" },
notFound: { name: "notFound", detail: "", solution: "" },
timeout: { name: "timeout", detail: "", solution: "" },
internalError: {
name: "internalError",
detail: "",
solution: ""
},
invalidRequestParameter: {
name: "invalidRequestParameter",
detail: "\u30EA\u30AF\u30A8\u30B9\u30C8\u306E\u30D1\u30E9\u30E1\u30FC\u30BF\u30FC\u304C\u6B63\u3057\u304F\u3042\u308A\u307E\u305B\u3093",
solution: "API\u4ED5\u69D8\u3092\u78BA\u8A8D\u3057\u6B63\u3057\u3044\u5024\u3092\u5165\u529B\u3057\u3066\u304F\u3060\u3055\u3044"
},
insufficientPermissions: {
name: "insufficientPermissions",
detail: "token\u306E\u6A29\u9650\u304C\u4E0D\u8DB3\u3057\u3066\u3044\u307E\u3059 Token permissions are insufficient",
solution: "Token\u306B\u5FC5\u8981\u306A\u6A29\u9650\u3092\u52A0\u3048\u3066\u304F\u3060\u3055\u3044 Add the necessary permissions to the Token"
},
publicationNestedTooMuch: {
name: "publicationNestedTooMuch",
detail: "origin\u304C\u8A2D\u5B9A\u3055\u308C\u3066\u3044\u308BPublication\u3092Publication\u306Eorigin\u306B\u6307\u5B9A\u3059\u308B\u3053\u3068\u306F\u51FA\u6765\u307E\u305B\u3093 It is not possible to specify the origin of a publication for which Origin has been set",
solution: "\u4ED5\u69D8\u4E0A\u306E\u5236\u7D04\u306A\u306E\u3067\u89E3\u6C7A\u6CD5\u306F\u3042\u308A\u307E\u305B\u3093 There is no solution because it is a specification limitation"
},
channelNotFound: {
name: "channelNotFound",
detail: "\u53C2\u7167\u3057\u3088\u3046\u3068\u3057\u305Fchannel\u306F\u5B58\u5728\u3057\u307E\u305B\u3093 The channel you tried to reference does not exist.",
solution: "channelId\u3084channelName\u304C\u6B63\u3057\u3044\u304B\u78BA\u304B\u3081\u3066\u304F\u3060\u3055\u3044 Make sure that the Channel id and channel name are correct."
},
memberNotFound: {
name: "memberNotFound",
detail: "\u53C2\u7167\u3057\u3088\u3046\u3068\u3057\u305FMember\u306F\u5B58\u5728\u3057\u307E\u305B\u3093 The member you tried to reference does not exist.",
solution: "memberId\u3084memberName\u304C\u6B63\u3057\u3044\u304B\u78BA\u304B\u3081\u3066\u304F\u3060\u3055\u3044 Make sure that the member id and member name is correct."
},
publicationNotFound: {
name: "publicationNotFound",
detail: "\u53C2\u7167\u3057\u3088\u3046\u3068\u3057\u305FPublication\u306F\u5B58\u5728\u3057\u307E\u305B\u3093 The Publication you tried to reference does not exist.",
solution: "publicationId\u304C\u6B63\u3057\u3044\u304B\u78BA\u304B\u3081\u3066\u304F\u3060\u3055\u3044 Make sure that the publication id is correct."
},
subscriptionNotFound: {
name: "subscriptionNotFound",
detail: "\u53C2\u7167\u3057\u3088\u3046\u3068\u3057\u305FSubscription\u306F\u5B58\u5728\u3057\u307E\u305B\u3093 The Subscription you tried to reference does not exist.",
solution: "subscriptionId\u304C\u6B63\u3057\u3044\u304B\u78BA\u304B\u3081\u3066\u304F\u3060\u3055\u3044 Make sure that the subscription id is correct."
},
operationConflicted: {
name: "operationConflicted",
detail: "\u4E0E\u3048\u3089\u308C\u305F\u540D\u524D\u306E\u30C1\u30E3\u30CD\u30EB\u306F\u3001\u4ECA\u307E\u3067\u306E\u7AF6\u5408\u3059\u308B\u8981\u6C42\u306B\u3088\u3063\u3066\u3001\u3059\u3067\u306B\u4F5C\u6210\u3055\u308C\u3066\u3044\u307E\u3059 The channel with the given name has already been created by a conflicting request up to now",
solution: "\u5225\u306E\u540D\u524D\u3092\u4F7F\u3063\u3066channel\u3092\u4F5C\u6210\u3057\u3066\u304F\u3060\u3055\u3044"
},
channelNameDuplicated: {
name: "channelNameDuplicated",
detail: "\u305D\u306E\u540D\u524D\u306EChannel\u306F\u3059\u3067\u306B\u5B58\u5728\u3057\u307E\u3059 A channel with that name already exists",
solution: "\u5225\u306E\u540D\u524D\u3092\u4F7F\u3063\u3066channel\u3092\u4F5C\u6210\u3057\u3066\u304F\u3060\u3055\u3044"
},
memberNameDuplicated: {
name: "memberNameDuplicated",
detail: "\u305D\u306E\u540D\u524D\u306EMember\u306F\u3059\u3067\u306B\u5B58\u5728\u3057\u307E\u3059 A member with that name already exists",
solution: "\u5225\u306E\u540D\u524D\u3092\u4F7F\u3063\u3066member\u3092\u4F5C\u6210\u3057\u3066\u304F\u3060\u3055\u3044"
},
subscriptionAlreadyExists: {
name: "subscriptionAlreadyExists",
detail: "Publication\u306F\u3059\u3067\u306BSubscribe\u3055\u308C\u3066\u3044\u307E\u3059",
solution: "publicationId\u304C\u6B63\u3057\u3044\u304B\u78BA\u304B\u3081\u3066\u304F\u3060\u3055\u3044"
},
rateLimitExceeded: {
name: "rateLimitExceeded",
detail: "\u30EA\u30BD\u30FC\u30B9\u3092\u898F\u5B9A\u4ED5\u69D8\u4EE5\u4E0A\u306B\u6D88\u8CBB\u3057\u3066\u3044\u307E\u3059",
solution: "\u30EA\u30BD\u30FC\u30B9\u306E\u6D88\u8CBB\u91CF\u3092\u6E1B\u3089\u3057\u3066\u304F\u3060\u3055\u3044"
},
projectUsageLimitExceeded: {
name: "projectUsageLimitExceeded",
detail: "\u30D5\u30EA\u30FC\u30D7\u30E9\u30F3\u30D7\u30ED\u30B8\u30A7\u30AF\u30C8\u306E\u30EA\u30BD\u30FC\u30B9\u5229\u7528\u4E0A\u9650\u306B\u9054\u3057\u3066\u3044\u307E\u3059",
solution: "\u30A8\u30F3\u30BF\u30FC\u30D7\u30E9\u30A4\u30BA\u30D7\u30E9\u30F3\u306B\u30A2\u30C3\u30D7\u30B0\u30EC\u30FC\u30C9\u3057\u3066\u304F\u3060\u3055\u3044"
},
invalidAuthToken: {
name: "invalidAuthToken",
detail: "AuthToken\u304C\u7121\u52B9\u3067\u3059",
solution: "\u9069\u5207\u306AAuthToken\u3092\u4F7F\u7528\u3057\u3066\u304F\u3060\u3055\u3044"
},
authTokenExpired: {
name: "authTokenExpired",
detail: "AuthToken\u304C\u671F\u9650\u5207\u308C\u3067\u3059",
solution: "\u9069\u5207\u306AExp\u3092\u8A2D\u5B9A\u3057\u305FAuthToken\u3092\u4F7F\u7528\u3057\u3066\u304F\u3060\u3055\u3044"
},
serverBusy: {
name: "serverBusy",
detail: "\u30B5\u30FC\u30D3\u30B9\u5074\u306E\u554F\u984C\u3067\u3059",
solution: "\u3057\u3070\u3089\u304F\u6642\u9593\u3092\u7F6E\u3044\u3066\u518D\u8A66\u884C\u3057\u3066\u304F\u3060\u3055\u3044"
},
invalidPublicationType: {
name: "invalidPublicationType",
detail: "Publication\u306Etype\u304C\u6B63\u3057\u304F\u3042\u308A\u307E\u305B\u3093",
solution: 'type\u3092\u6B63\u3057\u3044\u5024\u306B\u8A2D\u5B9A\u3057\u3066\u304F\u3060\u3055\u3044\u3002 "p2p" \u307E\u305F\u306F "sfu" \u306E\u3044\u305A\u308C\u304B\u3092\u6307\u5B9A\u3067\u304D\u307E\u3059\u3002'
}
});
var ErrorNames = Object.keys(errors3);
// ../rtc-api-client/src/util.ts
init_process();
function createWarnPayload3({
appId,
detail,
channelId,
operationName,
payload
}) {
const warn = {
operationName,
payload,
detail,
appId,
channelId
};
return warn;
}
function createError3({
operationName,
info,
error,
path,
channelId,
appId,
payload
}) {
return new SkyWayError({
error,
info,
payload: { payload, operationName, channelId, appId },
path
});
}
// ../rtc-api-client/src/infrastructure/api.ts
var log24 = new Logger("packages/rtc-api-client/src/infrastructure/api.ts");
var RtcApiImpl = class {
constructor(_client) {
this._client = _client;
this.closed = false;
this.onClose = new Event();
this.onFatalError = new Event();
SkyWayAuthToken.Decode(this._client.token);
_client.onClose.once(() => {
this.close();
});
_client.onFatalError.add((e2) => {
this.onFatalError.emit(e2);
});
}
/** @throws {@link SkyWayError} */
connect() {
return __async(this, null, function* () {
yield this._client.connect();
});
}
updateAuthToken(token) {
return __async(this, null, function* () {
SkyWayAuthToken.Decode(token);
yield this._client.updateToken(token).catch((e2) => {
var _a2, _b2, _c, _d, _e;
const { info } = e2;
if (((_b2 = (_a2 = info == null ? void 0 : info.error) == null ? void 0 : _a2.data) == null ? void 0 : _b2.code) === 429001) {
throw createError3({
operationName: "RtcApiImpl.updateAuthToken",
path: log24.prefix,
info: errors3.projectUsageLimitExceeded,
error: e2
});
}
const error = this._commonError(
"RtcApiImpl.updateAuthToken",
(_d = (_c = info == null ? void 0 : info.error) == null ? void 0 : _c.code) != null ? _d : -1,
e2
);
if (error) {
throw error;
}
switch ((_e = info == null ? void 0 : info.error) == null ? void 0 : _e.code) {
case 401:
throw createError3({
operationName: "RtcApiImpl.updateAuthToken",
path: log24.prefix,
info: errors3.invalidAuthToken,
error: e2
});
default:
throw createError3({
operationName: "RtcApiImpl.updateAuthToken",
path: log24.prefix,
info: errors3.internalError,
error: e2
});
}
});
});
}
close() {
if (this.closed) {
return;
}
this.closed = true;
log24.debug("closed");
this._client.close();
this.onClose.emit();
this.onClose.removeAllListeners();
}
_commonError(method, code, detail) {
switch (code) {
case -32602:
return createError3({
operationName: method,
info: errors3.invalidRequestParameter,
path: log24.prefix,
error: detail
});
case -32603:
return createError3({
operationName: method,
info: errors3.internalError,
path: log24.prefix,
error: detail
});
case 403:
case 4030:
return createError3({
operationName: method,
info: errors3.insufficientPermissions,
path: log24.prefix,
error: detail
});
case 429:
return createError3({
operationName: method,
info: errors3.rateLimitExceeded,
path: log24.prefix,
error: detail
});
}
}
/**@throws {@link SkyWayError} */
createChannel(appId, channelInit) {
return __async(this, null, function* () {
const { id } = yield this._client.createChannel({
appId,
name: channelInit.name,
metadata: channelInit.metadata
}).catch((e2) => {
var _a2, _b2, _c;
const { info } = e2;
const error = this._commonError(
"RtcApiImpl.createChannel",
(_b2 = (_a2 = info == null ? void 0 : info.error) == null ? void 0 : _a2.code) != null ? _b2 : -1,
e2
);
if (error) {
throw error;
}
switch ((_c = info == null ? void 0 : info.error) == null ? void 0 : _c.code) {
case 404:
throw createError3({
operationName: "RtcApiImpl.createChannel",
path: log24.prefix,
info: errors3.channelNotFound,
error: e2
});
case 409:
throw createError3({
operationName: "RtcApiImpl.createChannel",
path: log24.prefix,
info: errors3.channelNameDuplicated,
error: e2
});
default:
throw createError3({
operationName: "RtcApiImpl.createChannel",
path: log24.prefix,
info: errors3.internalError,
error: e2
});
}
});
const res = yield this.getChannel(appId, { id });
return res;
});
}
getChannel(_0, _1) {
return __async(this, arguments, function* (appId, { name, id }) {
if (id) {
return yield this._client.getChannel({ appId, id }).catch((e2) => {
var _a2, _b2, _c;
const { info } = e2;
const error = this._commonError(
"RtcApiImpl.getChannel",
(_b2 = (_a2 = info == null ? void 0 : info.error) == null ? void 0 : _a2.code) != null ? _b2 : -1,
e2
);
if (error) {
throw error;
}
switch ((_c = info == null ? void 0 : info.error) == null ? void 0 : _c.code) {
case 404:
throw createError3({
operationName: "RtcApiImpl.getChannel",
path: log24.prefix,
info: errors3.channelNotFound,
error: e2
});
default:
throw createError3({
operationName: "RtcApiImpl.getChannel",
path: log24.prefix,
info: errors3.internalError,
error: e2
});
}
});
}
if (name) {
return yield this._client.getChannelByName({ appId, name }).catch((e2) => {
var _a2, _b2, _c;
const { info } = e2;
const error = this._commonError(
"RtcApiImpl.getChannel",
(_b2 = (_a2 = info == null ? void 0 : info.error) == null ? void 0 : _a2.code) != null ? _b2 : -1,
e2
);
if (error) {
throw error;
}
switch ((_c = info == null ? void 0 : info.error) == null ? void 0 : _c.code) {
case 404:
throw createError3({
operationName: "getChannel",
path: log24.prefix,
info: errors3.channelNotFound,
error: e2
});
default:
throw createError3({
operationName: "getChannel",
path: log24.prefix,
info: errors3.internalError,
error: e2
});
}
});
}
throw createError3({
operationName: "RtcApiImpl.getChannel",
path: log24.prefix,
info: errors3.invalidRequestParameter
});
});
}
findOrCreateChannel(appId, query) {
return __async(this, null, function* () {
return this._client.findOrCreateChannel(__spreadProps(__spreadValues({}, query), { appId })).catch((e2) => {
var _a2, _b2, _c, _d;
const { info } = e2;
const error = this._commonError(
"RtcApiImpl.findOrCreateChannel",
(_b2 = (_a2 = info == null ? void 0 : info.error) == null ? void 0 : _a2.code) != null ? _b2 : -1,
e2
);
if (error) {
throw error;
}
if (query.name && ((_c = info == null ? void 0 : info.error) == null ? void 0 : _c.code) === 409) {
return this.getChannel(appId, { name: query.name });
}
switch ((_d = info == null ? void 0 : info.error) == null ? void 0 : _d.code) {
case 404:
throw createError3({
operationName: "RtcApiImpl.findOrCreateChannel",
path: log24.prefix,
info: errors3.channelNotFound,
error: e2
});
case 409:
throw createError3({
operationName: "RtcApiImpl.findOrCreateChannel",
path: log24.prefix,
info: errors3.channelNameDuplicated,
error: e2
});
default:
throw createError3({
operationName: "RtcApiImpl.findOrCreateChannel",
path: log24.prefix,
info: errors3.internalError,
error: e2
});
}
});
});
}
deleteChannel(appId, id) {
return __async(this, null, function* () {
yield this._client.deleteChannel({ appId, id }).catch((e2) => {
var _a2, _b2, _c;
const { info } = e2;
const error = this._commonError(
"RtcApiImpl.deleteChannel",
(_b2 = (_a2 = info == null ? void 0 : info.error) == null ? void 0 : _a2.code) != null ? _b2 : -1,
e2
);
if (error) {
throw error;
}
switch ((_c = info == null ? void 0 : info.error) == null ? void 0 : _c.code) {
case 404:
throw createError3({
operationName: "RtcApiImpl.deleteChannel",
path: log24.prefix,
info: errors3.channelNotFound,
error: e2
});
default:
throw createError3({
operationName: "RtcApiImpl.deleteChannel",
path: log24.prefix,
info: errors3.internalError,
error: e2
});
}
});
});
}
updateChannelMetadata(appId, id, metadata) {
return __async(this, null, function* () {
yield this._client.updateChannelMetadata({ appId, id, metadata }).catch((e2) => {
var _a2, _b2, _c;
const { info } = e2;
const error = this._commonError(
"RtcApiImpl.updateChannelMetadata",
(_b2 = (_a2 = info == null ? void 0 : info.error) == null ? void 0 : _a2.code) != null ? _b2 : -1,
e2
);
if (error) {
throw error;
}
switch ((_c = info == null ? void 0 : info.error) == null ? void 0 : _c.code) {
case 404:
throw createError3({
operationName: "RtcApiImpl.updateChannelMetadata",
path: log24.prefix,
info: errors3.channelNotFound,
error: e2
});
default:
throw createError3({
operationName: "RtcApiImpl.updateChannelMetadata",
path: log24.prefix,
info: errors3.internalError,
error: e2
});
}
});
});
}
join(appId, channelId, memberInit) {
return __async(this, null, function* () {
const { memberId } = yield this._client.addMember({
appId,
channelId,
name: memberInit.name,
metadata: memberInit.metadata,
ttlSec: memberInit.ttlSec,
type: memberInit.type,
subtype: memberInit.subtype
}).catch((e2) => {
var _a2, _b2, _c;
const { info } = e2;
const error = this._commonError(
"RtcApiImpl.addMember",
(_b2 = (_a2 = info == null ? void 0 : info.error) == null ? void 0 : _a2.code) != null ? _b2 : -1,
e2
);
if (error) {
throw error;
}
switch ((_c = info == null ? void 0 : info.error) == null ? void 0 : _c.code) {
case 404:
throw createError3({
operationName: "RtcApiImpl.addMember",
path: log24.prefix,
info: errors3.channelNotFound,
error: e2
});
case 409:
throw createError3({
operationName: "RtcApiImpl.addMember",
path: log24.prefix,
info: errors3.memberNameDuplicated,
error: e2
});
default:
throw createError3({
operationName: "RtcApiImpl.addMember",
path: log24.prefix,
info: errors3.internalError,
error: e2
});
}
});
const member = {
id: memberId,
name: memberInit.name,
type: memberInit.type,
subtype: memberInit.subtype,
metadata: memberInit.metadata
};
return member;
});
}
updateMemberTtl(appId, channelId, memberId, ttlSec) {
return __async(this, null, function* () {
yield this._client.updateMemberTtl({
appId,
channelId,
memberId,
ttlSec
}).catch((e2) => {
var _a2, _b2, _c;
const { info } = e2;
const error = this._commonError(
"RtcApiImpl.updateMemberTtl",
(_b2 = (_a2 = info == null ? void 0 : info.error) == null ? void 0 : _a2.code) != null ? _b2 : -1,
e2
);
if (error) {
throw error;
}
switch ((_c = info == null ? void 0 : info.error) == null ? void 0 : _c.code) {
case 404:
throw createError3({
operationName: "RtcApiImpl.updateMemberTtl",
path: log24.prefix,
info: errors3.memberNotFound,
error: e2
});
default:
throw createError3({
operationName: "RtcApiImpl.updateMemberTtl",
path: log24.prefix,
info: errors3.internalError,
error: e2
});
}
});
});
}
/**
* @returns Date.now()
*/
getServerUnixtime(appId) {
return __async(this, null, function* () {
return yield this._client.getServerUnixtime({
appId
}).catch((e2) => {
var _a2, _b2;
const { info } = e2;
const error = this._commonError(
"RtcApiImpl.getServerUnixtime",
(_b2 = (_a2 = info == null ? void 0 : info.error) == null ? void 0 : _a2.code) != null ? _b2 : -1,
e2
);
if (error) {
throw error;
}
throw createError3({
operationName: "RtcApiImpl.getServerUnixtime",
path: log24.prefix,
info: errors3.internalError,
error: e2
});
});
});
}
updateMemberMetadata(appId, channelId, memberId, metadata) {
return __async(this, null, function* () {
yield this._client.updateMemberMetadata({
appId,
channelId,
memberId,
metadata
}).catch((e2) => {
var _a2, _b2, _c;
const { info } = e2;
const error = this._commonError(
"RtcApiImpl.updateMemberMetadata",
(_b2 = (_a2 = info == null ? void 0 : info.error) == null ? void 0 : _a2.code) != null ? _b2 : -1,
e2
);
if (error) {
throw error;
}
switch ((_c = info == null ? void 0 : info.error) == null ? void 0 : _c.code) {
case 404:
throw createError3({
operationName: "RtcApiImpl.updateMemberMetadata",
path: log24.prefix,
info: errors3.memberNotFound,
error: e2
});
default:
throw createError3({
operationName: "RtcApiImpl.updateMemberMetadata",
path: log24.prefix,
info: errors3.internalError,
error: e2
});
}
});
});
}
leave(appId, channelId, memberId) {
return __async(this, null, function* () {
yield this._client.leaveChannel({
channelId,
id: memberId,
appId
}).catch((e2) => {
var _a2, _b2, _c;
const { info } = e2;
const error = this._commonError(
"RtcApiImpl.leaveChannel",
(_b2 = (_a2 = info == null ? void 0 : info.error) == null ? void 0 : _a2.code) != null ? _b2 : -1,
e2
);
if (error) {
throw error;
}
switch ((_c = info == null ? void 0 : info.error) == null ? void 0 : _c.code) {
case 404:
throw createError3({
operationName: "RtcApiImpl.leaveChannel",
path: log24.prefix,
info: errors3.memberNotFound,
error: e2
});
default:
throw createError3({
operationName: "RtcApiImpl.leaveChannel",
path: log24.prefix,
info: errors3.internalError,
error: e2
});
}
});
});
}
/**@throws {@link SkyWayError} */
publish(appId, init) {
return __async(this, null, function* () {
const { publicationId } = yield this._client.publishStream({
channelId: init.channel,
publisherId: init.publisher,
contentType: init.contentType,
metadata: init.metadata,
origin: init.origin,
codecCapabilities: init.codecCapabilities,
encodings: init.encodings,
isEnabled: init.isEnabled,
type: init.type,
appId
}).catch((e2) => {
var _a2, _b2, _c;
const { info } = e2;
const error = this._commonError(
"RtcApiImpl.publish",
(_b2 = (_a2 = info == null ? void 0 : info.error) == null ? void 0 : _a2.code) != null ? _b2 : -1,
e2
);
if (error) {
throw error;
}
switch ((_c = info == null ? void 0 : info.error) == null ? void 0 : _c.code) {
default:
throw createError3({
operationName: "RtcApiImpl.publish",
path: log24.prefix,
info: errors3.internalError,
error: e2
});
}
});
return publicationId;
});
}
updatePublicationMetadata(appId, channelId, publicationId, metadata) {
return __async(this, null, function* () {
yield this._client.updatePublicationMetadata({
channelId,
publicationId,
metadata,
appId
}).catch((e2) => {
var _a2, _b2, _c;
const { info } = e2;
const error = this._commonError(
"RtcApiImpl.updatePublicationMetadata",
(_b2 = (_a2 = info == null ? void 0 : info.error) == null ? void 0 : _a2.code) != null ? _b2 : -1,
e2
);
if (error) {
throw error;
}
switch ((_c = info == null ? void 0 : info.error) == null ? void 0 : _c.code) {
case 404:
throw createError3({
operationName: "RtcApiImpl.updatePublicationMetadata",
path: log24.prefix,
info: errors3.publicationNotFound,
error: e2
});
default:
throw createError3({
operationName: "RtcApiImpl.updatePublicationMetadata",
path: log24.prefix,
info: errors3.internalError,
error: e2
});
}
});
});
}
disablePublication(appId, channelId, publicationId) {
return __async(this, null, function* () {
yield this._client.disablePublication({
channelId,
publicationId,
appId
}).catch((e2) => {
var _a2, _b2, _c;
const { info } = e2;
const error = this._commonError(
"RtcApiImpl.disablePublication",
(_b2 = (_a2 = info == null ? void 0 : info.error) == null ? void 0 : _a2.code) != null ? _b2 : -1,
e2
);
if (error) {
throw error;
}
switch ((_c = info == null ? void 0 : info.error) == null ? void 0 : _c.code) {
case 404:
throw createError3({
operationName: "RtcApiImpl.disablePublication",
path: log24.prefix,
info: errors3.publicationNotFound,
error: e2
});
default:
throw createError3({
operationName: "RtcApiImpl.disablePublication",
path: log24.prefix,
info: errors3.internalError,
error: e2
});
}
});
});
}
enablePublication(appId, channelId, publicationId) {
return __async(this, null, function* () {
yield this._client.enablePublication({
channelId,
publicationId,
appId
}).catch((e2) => {
var _a2, _b2, _c;
const { info } = e2;
const error = this._commonError(
"RtcApiImpl.enablePublication",
(_b2 = (_a2 = info == null ? void 0 : info.error) == null ? void 0 : _a2.code) != null ? _b2 : -1,
e2
);
if (error) {
throw error;
}
switch ((_c = info == null ? void 0 : info.error) == null ? void 0 : _c.code) {
case 404:
throw createError3({
operationName: "RtcApiImpl.enablePublication",
path: log24.prefix,
info: errors3.publicationNotFound,
error: e2
});
default:
throw createError3({
operationName: "RtcApiImpl.enablePublication",
path: log24.prefix,
info: errors3.internalError,
error: e2
});
}
});
});
}
unpublish(appId, channelId, publicationId) {
return __async(this, null, function* () {
yield this._client.unpublishStream({ channelId, publicationId, appId }).catch((e2) => {
var _a2, _b2, _c;
const { info } = e2;
const error = this._commonError(
"RtcApiImpl.unpublishStream",
(_b2 = (_a2 = info == null ? void 0 : info.error) == null ? void 0 : _a2.code) != null ? _b2 : -1,
e2
);
if (error) {
throw error;
}
switch ((_c = info == null ? void 0 : info.error) == null ? void 0 : _c.code) {
case 404:
throw createError3({
operationName: "RtcApiImpl.unpublishStream",
path: log24.prefix,
info: errors3.publicationNotFound,
error: e2
});
default:
throw createError3({
operationName: "RtcApiImpl.unpublishStream",
path: log24.prefix,
info: errors3.internalError,
error: e2
});
}
});
});
}
/**@throws {@link SkyWayError} */
subscribe(appId, init) {
return __async(this, null, function* () {
const { subscriptionId } = yield this._client.subscribeStream({
channelId: init.channel.id,
subscriberId: init.subscriber.id,
publicationId: init.publication.id,
appId
}).catch((e2) => {
var _a2, _b2, _c;
const { info } = e2;
const error = this._commonError(
"RtcApiImpl.subscribeStream",
(_b2 = (_a2 = info == null ? void 0 : info.error) == null ? void 0 : _a2.code) != null ? _b2 : -1,
e2
);
if (error) {
throw error;
}
switch ((_c = info == null ? void 0 : info.error) == null ? void 0 : _c.code) {
case 404:
throw createError3({
operationName: "RtcApiImpl.subscribeStream",
path: log24.prefix,
info: errors3.publicationNotFound,
error: e2
});
case 409:
throw createError3({
operationName: "RtcApiImpl.subscribeStream",
path: log24.prefix,
info: errors3.subscriptionAlreadyExists,
error: e2
});
default:
throw createError3({
operationName: "RtcApiImpl.subscribeStream",
path: log24.prefix,
info: errors3.internalError,
error: e2
});
}
});
return subscriptionId;
});
}
unsubscribe(appId, channelId, subscriptionId) {
return __async(this, null, function* () {
yield this._client.unsubscribeStream({
appId,
channelId,
subscriptionId
}).catch((e2) => {
var _a2, _b2, _c;
const { info } = e2;
const error = this._commonError(
"RtcApiImpl.unsubscribeStream",
(_b2 = (_a2 = info == null ? void 0 : info.error) == null ? void 0 : _a2.code) != null ? _b2 : -1,
e2
);
if (error) {
throw error;
}
switch ((_c = info == null ? void 0 : info.error) == null ? void 0 : _c.code) {
case 404:
throw createError3({
operationName: "RtcApiImpl.unsubscribeStream",
path: log24.prefix,
info: errors3.publicationNotFound,
error: e2
});
default:
throw createError3({
operationName: "RtcApiImpl.unsubscribeStream",
path: log24.prefix,
info: errors3.internalError,
error: e2
});
}
});
});
}
};
// ../rtc-api-client/src/infrastructure/eventObserver.ts
init_process();
var log25 = new Logger(
"packages/rtc-api-client/src/infrastructure/eventObserver.ts"
);
var EventObserverImpl = class {
constructor(appId, client, channelDto, config) {
this.onEvent = new Event();
this._disposer = [];
const eventBuffer = new EventJitterBuffer(
channelDto.version,
(expectNextVersion) => __async(null, null, function* () {
yield client.subscribeChannelEvents({
appId,
channelId: channelDto.id,
offset: expectNextVersion
});
yield new Promise((r2) => setTimeout(r2, config.eventSubscribeTimeout));
if (eventBuffer.packetLostHappened) {
log25.error(
createError3({
operationName: "EventObserverImpl.eventJitterBuffer",
info: __spreadProps(__spreadValues({}, errors3.internalError), {
detail: "failed to resolve event lost"
}),
channelId: channelDto.id,
appId,
path: log25.prefix
})
);
}
})
);
this._disposer = [
client.onEvent.add((_0) => __async(this, [_0], function* ({ channelId, event }) {
if (channelId === channelDto.id) {
eventBuffer.push({ event, version: event.data.channel.version });
}
})).removeListener,
eventBuffer.onEvent.add((e2) => {
this.onEvent.emit(e2);
}).removeListener
];
}
dispose() {
this._disposer.forEach((d) => {
d();
});
this.onEvent.removeAllListeners();
}
};
var EventJitterBuffer = class {
constructor(presentVersion, onPacketLost, packetLifetime = 1e3) {
this.presentVersion = presentVersion;
this.onPacketLost = onPacketLost;
this.packetLifetime = packetLifetime;
this.onEvent = new Event();
this.eventBuffer = {};
this.packetLostHappened = false;
}
get expectNextVersion() {
return this.presentVersion + 1;
}
push(eventFrame) {
const incomingVersion = eventFrame.version;
if (incomingVersion < this.expectNextVersion) {
log25.debug("duplicate event", __spreadProps(__spreadValues({}, eventFrame), {
presentVersion: this.presentVersion
}));
return;
}
if (incomingVersion > this.expectNextVersion) {
log25.debug("maybe miss order event received", __spreadProps(__spreadValues({}, eventFrame), {
presentVersion: this.presentVersion
}));
this.eventBuffer[incomingVersion] = eventFrame;
this.handlePacketLifetime();
return;
}
if (this.packetLostHappened) {
log25.warn(
"event packetLost resolved",
createWarnPayload3({
operationName: "EventJitterBuffer.push",
detail: "event packetLost resolved",
payload: { eventFrame }
})
);
this.packetLostHappened = false;
}
this.eventBuffer[incomingVersion] = eventFrame;
this.resolveEvents();
}
handlePacketLifetime() {
const [oldestBufferedEvent] = Object.keys(this.eventBuffer).sort().map((key) => this.eventBuffer[Number(key)]);
if (this.packetLifeTimer === void 0 && oldestBufferedEvent) {
log25.debug("set event packetLost timer", __spreadProps(__spreadValues({}, oldestBufferedEvent), {
presentVersion: this.presentVersion
}));
this.packetLifeTimer = setTimeout(() => __async(this, null, function* () {
if (this.presentVersion < oldestBufferedEvent.version) {
log25.warn(
"event packetLost",
createWarnPayload3({
operationName: "EventJitterBuffer.handlePacketLifetime",
detail: "eventPacket lost",
payload: {
oldestBufferedEvent,
eventBufferLength: Object.keys(this.eventBuffer).length,
presentVersion: this.presentVersion
}
})
);
if (this.packetLostHappened) {
return;
} else {
this.packetLostHappened = true;
yield this.onPacketLost(this.expectNextVersion);
}
}
this.packetLifeTimer = void 0;
this.handlePacketLifetime();
}), this.packetLifetime);
}
}
resolveEvents() {
const resolve = [];
for (let i = this.expectNextVersion; ; i++) {
const frame = this.eventBuffer[i];
if (frame) {
resolve.push(frame);
delete this.eventBuffer[i];
} else {
break;
}
}
if (resolve.length > 0) {
this.presentVersion = resolve.slice(-1)[0].version;
resolve.forEach((frame) => {
this.onEvent.emit(frame.event);
});
}
}
};
// ../rtc-api-client/src/client.ts
var log26 = new Logger("packages/rtc-api-client/src/client.ts");
var RtcApiClient = class _RtcApiClient {
constructor(appId, config, apiClient, _eventObserverFactory) {
this.appId = appId;
this.config = config;
this.apiClient = apiClient;
this._eventObserverFactory = _eventObserverFactory;
this.closed = false;
this.onFatalError = new Event();
this.apiClient.onFatalError.pipe(this.onFatalError);
}
/** @throws {@link SkyWayError} */
static Create(args) {
return __async(this, null, function* () {
const config = new Config(args);
if (config.log) {
Logger.level = config.log.level;
Logger.format = config.log.format;
}
log26.debug("RtcApiClient spawned", config);
const rpc = new RtcRpcApiClient(__spreadProps(__spreadValues({}, config.rtcApi), {
token: args.token,
log: config.log
}));
const api = new RtcApiImpl(rpc);
yield api.connect();
const eventObserverFactory = (appId, channel) => new EventObserverImpl(appId, rpc, channel, config.rtcApi);
return new _RtcApiClient(args.appId, config, api, eventObserverFactory);
});
}
updateAuthToken(token) {
return __async(this, null, function* () {
yield this.apiClient.updateAuthToken(token);
});
}
/**ms */
getServerUnixtimeInMs() {
return __async(this, null, function* () {
return this.apiClient.getServerUnixtime(this.appId);
});
}
/**sec */
getServerUnixtimeInSec() {
return __async(this, null, function* () {
return Math.floor((yield this.getServerUnixtimeInMs()) / 1e3);
});
}
/**@throws {@link SkyWayError} */
createChannel() {
return __async(this, arguments, function* (init = {}) {
log26.debug("[start] apiClient.createChannel", { init });
const channelDto = yield this.apiClient.createChannel(this.appId, init).catch((e2) => {
log26.debug("[failed] apiClient.createChannel", { init, e: e2 });
throw e2;
});
log26.debug("[end] apiClient.createChannel", { init, channelDto });
const channel = channelFactory(
this.appId,
this._eventObserverFactory(this.appId, channelDto),
this.apiClient,
channelDto,
this.config
);
return channel;
});
}
findChannel(query) {
return __async(this, null, function* () {
log26.debug("[start] apiClient.getChannel", { query });
const channelDto = yield this.apiClient.getChannel(this.appId, query).catch((e2) => {
log26.debug("[failed] apiClient.getChannel", { query, e: e2 });
throw e2;
});
const channel = channelFactory(
this.appId,
this._eventObserverFactory(this.appId, channelDto),
this.apiClient,
channelDto,
this.config
);
log26.debug("[end] apiClient.getChannel", { channelId: channel.id });
return channel;
});
}
findOrCreateChannel(query) {
return __async(this, null, function* () {
log26.debug("[start] apiClient.findOrCreateChannel", { query });
const channelDto = yield this.apiClient.findOrCreateChannel(this.appId, query).catch((e2) => {
log26.debug("[failed] apiClient.findOrCreateChannel", { query, e: e2 });
throw e2;
});
log26.debug("[end] apiClient.findOrCreateChannel", { query });
const channel = channelFactory(
this.appId,
this._eventObserverFactory(this.appId, channelDto),
this.apiClient,
channelDto,
this.config
);
return channel;
});
}
deleteChannel(channelId) {
return this.apiClient.deleteChannel(this.appId, channelId);
}
close() {
if (this.closed) {
return;
}
this.closed = true;
log26.debug("closed", { appid: this.appId });
this.apiClient.close();
}
};
// ../rtc-api-client/src/domain/api.ts
init_process();
// ../rtc-api-client/src/domain/channel.ts
init_process();
// ../model/src/index.ts
init_process();
// ../model/src/domain.ts
var domain_exports = {};
__export(domain_exports, {
PublicationType: () => PublicationType
});
init_process();
var PublicationType = ["p2p", "sfu", null];
// ../model/src/index.ts
var src_default = domain_exports;
// ../rtc-api-client/src/model/event.ts
var event_exports = {};
init_process();
// ../rtc-api-client/src/domain/channel.ts
var log27 = new Logger("packages/rtc-api-client/src/domain/channel.ts");
var ChannelImpl = class {
constructor(appId, {
id,
name,
members,
metadata,
publications,
subscriptions,
version
}, eventObserver, apiClient, config) {
this.appId = appId;
this.eventObserver = eventObserver;
this.apiClient = apiClient;
this.config = config;
this.disposed = false;
// events
this._events = new Events();
this.onClosed = this._events.make();
this.onMetadataUpdated = this._events.make();
this.onMemberListChanged = this._events.make();
this.onMemberJoined = this._events.make();
this.onMemberLeft = this._events.make();
this.onMemberMetadataUpdated = this._events.make();
this.onPublicationDisabled = this._events.make();
this.onPublicationEnabled = this._events.make();
this.onPublicationListChanged = this._events.make();
this.onStreamPublished = this._events.make();
this.onStreamUnpublished = this._events.make();
this.onPublicationMetadataUpdated = this._events.make();
this.onSubscriptionListChanged = this._events.make();
this.onPublicationSubscribed = this._events.make();
this.onPublicationUnsubscribed = this._events.make();
this.updateChannelMetadata = (metadata) => new Promise((r2, f) => {
let failed = false;
this.apiClient.updateChannelMetadata(this.appId, this.id, metadata).catch((e2) => {
failed = true;
f(e2);
});
this.onMetadataUpdated.watch((e2) => e2.channel.metadata === metadata).then(() => r2()).catch((error) => {
if (!failed)
f(
createError3({
operationName: "ChannelImpl.updateChannelMetadata",
info: __spreadProps(__spreadValues({}, errors3.timeout), { detail: "onMetadataUpdated" }),
path: log27.prefix,
error,
appId: this.appId,
channelId: this.id
})
);
});
});
this.leave = (channelId, memberId) => new Promise((r2, f) => {
let failed = false;
this.apiClient.leave(this.appId, channelId, memberId).catch((e2) => {
failed = true;
f(e2);
});
this.onMemberLeft.watch((e2) => e2.member.id === memberId, this.config.rtcApi.timeout).then(() => r2()).catch((error) => {
if (!failed)
f(
createError3({
operationName: "ChannelImpl.leave",
info: __spreadProps(__spreadValues({}, errors3.timeout), { detail: "onMemberLeft" }),
path: log27.prefix,
error,
appId: this.appId,
channelId: this.id
})
);
});
});
this.updateMemberMetadata = (memberId, metadata) => new Promise((r2, f) => {
let failed = false;
this.apiClient.updateMemberMetadata(this.appId, this.id, memberId, metadata).catch((e2) => {
failed = true;
f(e2);
});
this.onMemberMetadataUpdated.watch(
(e2) => e2.member.id === memberId && e2.member.metadata === metadata
).then(() => r2()).catch((error) => {
if (!failed)
f(
createError3({
operationName: "ChannelImpl.updateMemberMetadata",
info: __spreadProps(__spreadValues({}, errors3.timeout), { detail: "onMemberMetadataUpdated" }),
path: log27.prefix,
error,
appId: this.appId,
channelId: this.id
})
);
});
});
this.unpublish = (publicationId) => new Promise((r2, f) => {
let failed = false;
this.apiClient.unpublish(this.appId, this.id, publicationId).catch((e2) => {
failed = true;
f(e2);
});
this.onStreamUnpublished.watch((e2) => e2.publication.id === publicationId).then(() => r2()).catch((error) => {
if (!failed)
f(
createError3({
operationName: "ChannelImpl.unpublish",
info: __spreadProps(__spreadValues({}, errors3.timeout), { detail: "onStreamUnpublished" }),
path: log27.prefix,
error,
payload: { publicationId },
appId: this.appId,
channelId: this.id
})
);
});
});
this.updatePublicationMetadata = (publicationId, metadata) => new Promise((r2, f) => {
let failed = false;
this.apiClient.updatePublicationMetadata(this.appId, this.id, publicationId, metadata).catch((e2) => {
failed = true;
f(e2);
});
this.onPublicationMetadataUpdated.watch(
(e2) => e2.publication.id === publicationId && e2.publication.metadata === metadata
).then(() => r2()).catch((error) => {
if (!failed)
f(
createError3({
operationName: "ChannelImpl.updatePublicationMetadata",
info: __spreadProps(__spreadValues({}, errors3.timeout), {
detail: "onPublicationMetadataUpdated"
}),
path: log27.prefix,
error,
payload: { publicationId },
appId: this.appId,
channelId: this.id
})
);
});
});
this.disablePublication = (publicationId) => new Promise((r2, f) => {
let failed = false;
this.apiClient.disablePublication(this.appId, this.id, publicationId).catch((e2) => {
failed = true;
f(e2);
});
this.onPublicationDisabled.watch((e2) => e2.publication.id === publicationId).then(() => r2()).catch((error) => {
if (!failed)
f(
createError3({
operationName: "ChannelImpl.disablePublication",
info: __spreadProps(__spreadValues({}, errors3.timeout), { detail: "onPublicationDisabled" }),
path: log27.prefix,
error,
payload: { publicationId },
appId: this.appId,
channelId: this.id
})
);
});
});
this.enablePublication = (publicationId) => new Promise((r2, f) => {
let failed = false;
this.apiClient.enablePublication(this.appId, this.id, publicationId).catch((e2) => {
failed = true;
f(e2);
});
this.onPublicationEnabled.watch((e2) => e2.publication.id === publicationId).then(() => r2()).catch((error) => {
if (!failed)
f(
createError3({
operationName: "ChannelImpl.enablePublication",
info: __spreadProps(__spreadValues({}, errors3.timeout), { detail: "onPublicationEnabled" }),
path: log27.prefix,
error,
payload: { publicationId },
appId: this.appId,
channelId: this.id
})
);
});
});
this.unsubscribe = (subscriptionId) => new Promise((r2, f) => {
let failed = false;
this.apiClient.unsubscribe(this.appId, this.id, subscriptionId).catch((e2) => {
failed = true;
f(e2);
});
this.onPublicationUnsubscribed.watch((e2) => e2.subscription.id === subscriptionId).then(() => r2()).catch((error) => {
if (!failed)
f(
createError3({
operationName: "ChannelImpl.unsubscribe",
info: __spreadProps(__spreadValues({}, errors3.timeout), {
detail: "onPublicationUnsubscribed"
}),
path: log27.prefix,
error,
payload: { subscriptionId },
appId: this.appId,
channelId: this.id
})
);
});
});
this.id = id;
this.name = name;
this.metadata = metadata;
this.members = members;
this.publications = publications;
this.subscriptions = subscriptions;
this.version = version;
eventObserver.onEvent.add((event) => {
log27.debug("received event: ", event);
this.version = event.data.channel.version;
try {
switch (event.type) {
case "ChannelDeleted":
{
this._channelClosed();
}
break;
case "ChannelMetadataUpdated":
{
this._channelMetadataUpdated(event.data);
}
break;
case "MemberAdded":
{
this._memberJoined(event.data);
}
break;
case "MemberRemoved":
{
this._memberLeft(event.data);
}
break;
case "MemberMetadataUpdated":
{
this._memberMetadataUpdated(event.data);
}
break;
case "StreamPublished":
{
this._streamPublished(event.data);
}
break;
case "StreamUnpublished":
{
this._streamUnpublished(event.data);
}
break;
case "PublicationMetadataUpdated":
{
this._publicationMetadataUpdated(event.data);
}
break;
case "PublicationDisabled":
{
this._publicationDisabled(event.data);
}
break;
case "PublicationEnabled":
{
this._publicationEnabled(event.data);
}
break;
case "StreamSubscribed":
{
this._streamSubscribed(event.data);
}
break;
case "StreamUnsubscribed":
{
this._streamUnsubscribed(event.data);
}
break;
}
} catch (error) {
log27.error(error);
}
});
apiClient.onClose.once(() => {
this.dispose();
});
}
getMember(id) {
return this.members.find((s) => s.id === id);
}
addMember(member) {
const exist = this.getMember(member.id);
if (exist) {
return exist;
}
this.members.push(member);
return member;
}
deleteMember(id) {
this.members = this.members.filter((m) => m.id !== id);
}
getPublication(id) {
return this.publications.find((s) => s.id === id);
}
addPublication(summary) {
var _a2, _b2;
const exist = this.getPublication(summary.id);
if (exist) {
return exist;
}
const publication = __spreadProps(__spreadValues({}, summary), {
channelId: this.id,
codecCapabilities: (_a2 = summary.codecCapabilities) != null ? _a2 : [],
encodings: (_b2 = summary.encodings) != null ? _b2 : []
});
this.publications.push(publication);
return publication;
}
deletePublication(publicationId) {
this.publications = this.publications.filter((p) => p.id !== publicationId);
}
getSubscription(id) {
return this.subscriptions.find((s) => s.id === id);
}
addSubscription(summary) {
const exist = this.getSubscription(summary.id);
if (exist) {
return exist;
}
const publication = this.getPublication(summary.publicationId);
const subscription = __spreadProps(__spreadValues({}, summary), {
channelId: this.id,
publisherId: publication.publisherId,
contentType: publication.contentType
});
this.subscriptions.push(subscription);
return subscription;
}
deleteSubscription(subscriptionId) {
this.subscriptions = this.subscriptions.filter(
(s) => s.id !== subscriptionId
);
}
_channelClosed() {
this.onClosed.emit({});
}
_channelMetadataUpdated(event) {
this.metadata = event.channel.metadata;
this.onMetadataUpdated.emit(event);
}
_memberJoined(event) {
this.addMember(event.member);
this.onMemberJoined.emit(event);
this.onMemberListChanged.emit({});
}
_memberLeft(event) {
const member = this.getMember(event.member.id);
if (!member) {
throw createError3({
operationName: "ChannelImpl._memberLeft",
info: errors3.memberNotFound,
path: log27.prefix,
payload: { event },
appId: this.appId,
channelId: this.id
});
}
this.deleteMember(member.id);
this.onMemberLeft.emit({ member });
this.onMemberListChanged.emit({});
}
_memberMetadataUpdated(event) {
const member = this.getMember(event.member.id);
if (!member) {
throw createError3({
operationName: "ChannelImpl._memberMetadataUpdated",
info: errors3.memberNotFound,
path: log27.prefix,
payload: { event },
appId: this.appId,
channelId: this.id
});
}
member.metadata = event.member.metadata;
this.onMemberMetadataUpdated.emit(event);
}
_streamPublished(event) {
const publication = this.addPublication(event.publication);
const outgoing = __spreadProps(__spreadValues({}, event), {
publication
});
this.onStreamPublished.emit(outgoing);
this.onPublicationListChanged.emit({});
}
_streamUnpublished(event) {
const publication = this.getPublication(event.publication.id);
if (!publication) {
throw createError3({
operationName: "ChannelImpl._streamUnpublished",
info: errors3.publicationNotFound,
path: log27.prefix,
payload: { event },
appId: this.appId,
channelId: this.id
});
}
this.deletePublication(publication.id);
const outgoing = __spreadProps(__spreadValues({}, event), { publication });
this.onStreamUnpublished.emit(outgoing);
this.onPublicationListChanged.emit({});
}
_publicationMetadataUpdated(event) {
const publication = this.getPublication(event.publication.id);
if (!publication) {
throw createError3({
operationName: "ChannelImpl._publicationMetadataUpdated",
info: errors3.publicationNotFound,
path: log27.prefix,
payload: { event },
appId: this.appId,
channelId: this.id
});
}
publication.metadata = event.publication.metadata;
const outgoing = __spreadProps(__spreadValues({}, event), {
publication
});
this.onPublicationMetadataUpdated.emit(outgoing);
}
_publicationDisabled(event) {
const publication = this.getPublication(event.publication.id);
if (!publication) {
throw createError3({
operationName: "ChannelImpl._publicationDisabled",
info: errors3.publicationNotFound,
path: log27.prefix,
payload: { event },
appId: this.appId,
channelId: this.id
});
}
publication.isEnabled = event.publication.isEnabled;
const outgoing = {
publication
};
this.onPublicationDisabled.emit(outgoing);
}
_publicationEnabled(incoming) {
const publication = this.getPublication(incoming.publication.id);
if (!publication) {
throw createError3({
operationName: "ChannelImpl._publicationEnabled",
info: errors3.publicationNotFound,
path: log27.prefix,
payload: { event: event_exports },
appId: this.appId,
channelId: this.id
});
}
publication.isEnabled = incoming.publication.isEnabled;
const outgoing = {
publication
};
this.onPublicationEnabled.emit(outgoing);
}
_streamSubscribed(incoming) {
const subscription = this.addSubscription(incoming.subscription);
const outgoing = __spreadProps(__spreadValues({}, incoming), {
subscription
});
this.onPublicationSubscribed.emit(outgoing);
this.onSubscriptionListChanged.emit({});
}
_streamUnsubscribed(event) {
const subscription = this.getSubscription(event.subscription.id);
if (!subscription) {
throw createError3({
operationName: "ChannelImpl._streamUnsubscribed",
info: errors3.subscriptionNotFound,
path: log27.prefix,
payload: { event },
appId: this.appId,
channelId: this.id
});
}
this.deleteSubscription(subscription.id);
const outgoing = __spreadProps(__spreadValues({}, event), {
subscription
});
this.onPublicationUnsubscribed.emit(outgoing);
this.onSubscriptionListChanged.emit({});
}
joinChannel(memberInit) {
return __async(this, null, function* () {
var _a2;
if (memberInit.type) {
memberInit.type = memberInit.type[0].toUpperCase() + memberInit.type.slice(1);
}
if (memberInit.subtype) {
memberInit.subtype = memberInit.subtype[0].toUpperCase() + memberInit.subtype.slice(1);
}
log27.debug("[start] joinChannel", { memberInit });
const res = yield this.apiClient.join(this.appId, this.id, __spreadValues({}, memberInit));
const member = (_a2 = this.getMember(res.id)) != null ? _a2 : (yield this.onMemberJoined.watch((e2) => e2.member.id === res.id, this.config.rtcApi.timeout).catch((error) => {
throw createError3({
operationName: "ChannelImpl.joinChannel",
info: __spreadProps(__spreadValues({}, errors3.timeout), { detail: "onMemberJoined" }),
path: log27.prefix,
error,
appId: this.appId,
channelId: this.id
});
})).member;
log27.debug("[end] joinChannel", { member });
return member;
});
}
updateMemberTtl(memberId, ttlSec) {
return this.apiClient.updateMemberTtl(
this.appId,
this.id,
memberId,
ttlSec
);
}
/**@throws {SkyWayError} */
publish(init) {
return __async(this, null, function* () {
var _a2, _b2, _c, _d;
const ts = log27.debug("[start] apiClient.publish", { init });
const allowedTypes = src_default.PublicationType.filter((t2) => t2 !== null);
if (init.type && !allowedTypes.includes(init.type)) {
throw createError3({
operationName: "ChannelImpl.publish",
error: new Error("The type in PublicationOptions is invalid."),
info: __spreadValues({}, errors3.invalidPublicationType),
path: log27.prefix,
payload: { init },
appId: this.appId,
channelId: this.id
});
}
const channelId = this.id;
const publicationId = yield this.apiClient.publish(this.appId, __spreadProps(__spreadValues({}, init), {
channel: channelId
}));
const publicationDto = {
id: publicationId,
channelId,
publisherId: init.publisher,
origin: init.origin,
contentType: init.contentType,
metadata: init.metadata,
codecCapabilities: (_a2 = init.codecCapabilities) != null ? _a2 : [],
encodings: (_b2 = init.encodings) != null ? _b2 : [],
isEnabled: (_c = init.isEnabled) != null ? _c : true,
type: (_d = init.type) != null ? _d : "p2p"
};
log27.elapsed(ts, "[ongoing] apiClient.publish", { publicationDto });
const exist = this.getPublication(publicationId);
if (exist) {
return exist;
}
const { publication } = yield this.onStreamPublished.watch(
(e2) => e2.publication.id === publicationId,
this.config.rtcApi.timeout
).catch((error) => {
throw createError3({
operationName: "ChannelImpl.publish",
info: __spreadProps(__spreadValues({}, errors3.timeout), { detail: "onStreamPublished" }),
path: log27.prefix,
error,
payload: { publicationDto },
appId: this.appId,
channelId: this.id
});
});
log27.elapsed(ts, "[end] apiClient.publish", { publicationDto });
return publication;
});
}
/**@throws {@link SkyWayError} */
subscribe(init) {
return __async(this, null, function* () {
const ts = log27.debug("[start] apiClient.subscribe", { init });
const subscriptionId = yield this.apiClient.subscribe(this.appId, __spreadProps(__spreadValues({}, init), {
channel: this
}));
const subscriptionDto = {
id: subscriptionId,
publicationId: init.publication.id,
channelId: this.id,
publisherId: init.publication.publisherId,
subscriberId: init.subscriber.id,
contentType: init.publication.contentType
};
log27.elapsed(ts, "[ongoing] apiClient.subscribe", { subscriptionDto });
const exist = this.getSubscription(subscriptionId);
if (exist) {
log27.elapsed(ts, "[end] apiClient.subscribe", { subscriptionDto });
return exist;
}
const { subscription } = yield this.onPublicationSubscribed.watch(
(e2) => e2.subscription.id === subscriptionId,
this.config.rtcApi.timeout
).catch((error) => {
log27.elapsed(ts, "[fail] apiClient.subscribe", error);
throw createError3({
operationName: "ChannelImpl.subscribe",
info: __spreadProps(__spreadValues({}, errors3.timeout), { detail: "onPublicationSubscribed" }),
path: log27.prefix,
error,
payload: { subscriptionDto }
});
});
log27.elapsed(ts, "[end] apiClient.subscribe", { subscriptionDto });
return subscription;
});
}
close() {
return this.apiClient.deleteChannel(this.appId, this.id);
}
/**
* リソースの解放
* - Channelイベントの購読停止
* - イベントリスナー
*/
dispose() {
if (this.disposed) {
return;
}
this.disposed = true;
log27.debug("disposed", { id: this.id });
this.eventObserver.dispose();
this._events.dispose();
}
};
function channelFactory(appId, eventObserver, api, channelDto, config) {
const channel = new ChannelImpl(
appId,
channelDto,
eventObserver,
api,
config
);
return channel;
}
// ../core/src/external/analytics.ts
init_process();
// ../analytics-client/src/index.ts
init_process();
// ../analytics-client/src/analyticsClient.ts
init_process();
// ../analytics-client/src/clientEvent.ts
init_process();
var ClientEvent2 = class {
constructor(type, payload) {
this.id = v4_default();
this.type = type;
this.payload = payload;
}
toJSON() {
return {
id: this.id,
type: this.type,
payload: this.payload
};
}
};
// ../analytics-client/src/payloadTypes.ts
init_process();
function isRecord(arg) {
if (typeof arg !== "object") return false;
if (arg === null) return false;
if (Array.isArray(arg)) return false;
return true;
}
function isOpenServerEventPayload(payload) {
if (!payload || typeof payload !== "object") return false;
if (!payload.statsRequest || typeof payload.statsRequest !== "object")
return false;
if (!payload.statsRequest.intervalSec || typeof payload.statsRequest.intervalSec !== "number")
return false;
if (!payload.statsRequest.types || !Array.isArray(payload.statsRequest.types))
return false;
for (const statsRequestType of payload.statsRequest.types) {
if (!statsRequestType.type || typeof statsRequestType.type !== "string")
return false;
if (!statsRequestType.properties || !isRecord(statsRequestType.properties))
return false;
for (const key of Object.keys(statsRequestType.properties)) {
if (!("normalization" in statsRequestType.properties[key]) || typeof statsRequestType.properties[key].normalization !== "boolean")
return false;
if (!statsRequestType.properties[key].outputKey || typeof statsRequestType.properties[key].outputKey !== "string")
return false;
}
}
return true;
}
var AcknowledgeReason = ["invalidPayload", "unexpected"];
function isAcknowledgePayload2(payload) {
if (!payload || typeof payload !== "object") return false;
if (typeof payload.eventId !== "string") return false;
if (typeof payload.ok !== "boolean") return false;
if (typeof payload.reason !== "undefined" && (typeof payload.reason !== "string" || !AcknowledgeReason.includes(payload.reason)))
return false;
return true;
}
// ../analytics-client/src/socket.ts
init_process();
var import_isomorphic_ws3 = __toESM(require_browser());
// ../analytics-client/src/utils/event.ts
init_process();
var Event3 = class {
constructor() {
this._listeners = /* @__PURE__ */ new Map();
this._listenerIndex = 0;
this.emit = (arg) => {
this._listeners.forEach((listener) => {
listener(arg);
});
};
this.removeAllListeners = () => {
this._listeners.clear();
};
this.addListener = (listener) => {
const id = this._listenerIndex;
this._listeners.set(id, listener);
this._listenerIndex++;
const removeListener = () => {
this._listeners.delete(id);
};
return { removeListener };
};
this.addOneTimeListener = (listener) => {
const off = this.addListener((arg) => {
off.removeListener();
listener(arg);
});
return off;
};
this.asPromise = (timeLimit) => new Promise((resolve, reject) => {
let removeListener = () => {
};
const timeout = timeLimit && setTimeout(() => {
reject("Event asPromise timeout");
removeListener();
}, timeLimit);
const off = this.addOneTimeListener((arg) => {
if (timeout) clearTimeout(timeout);
resolve(arg);
});
removeListener = off.removeListener;
});
}
};
// ../analytics-client/src/socket.ts
var ServerEventType = ["Open", "Acknowledge"];
var getReconnectWaitTime = (reconnectCount) => {
return (__pow(2, reconnectCount) + Math.random()) * 1e3;
};
var Socket2 = class {
constructor({
sessionEndpoint,
token,
logger: logger2,
sdkVersion,
contextId
}) {
this._isOpen = false;
this._isClosed = false;
this._reconnectCount = 0;
this.connectionState = "connecting";
// コンストラクタ作成時点で繋ぎにいくので初期値はconnecting
this.onConnectionStateChanged = new Event3();
this.onOpened = new Event3();
this.onTokenExpired = new Event3();
this.onEventReceived = new Event3();
this.onConnectionFailed = new Event3();
this._resendClientEvents = [];
this._sessionEndpoint = sessionEndpoint;
this._token = token;
this._logger = logger2;
this._sdkVersion = sdkVersion;
this._contextId = contextId;
this._connect();
}
_setConnectionState(state) {
if (this.connectionState === state) return;
this._logger.debug(`connectionState changed : ${state}`);
this.connectionState = state;
this.onConnectionStateChanged.emit(state);
}
_connect() {
let ws;
try {
const subProtocol = `SkyWayAuthToken!${this._token}`;
const wsProperties = {
sdkPlatform: "js",
sdkVersion: this._sdkVersion,
contextId: this._contextId
};
const queryString = Object.entries(wsProperties).filter(([_, v]) => v !== void 0).map((pair) => pair.join("=")).join("&");
const wsURL = `${this._sessionEndpoint}?${queryString}`;
ws = new import_isomorphic_ws3.default(wsURL, subProtocol);
this._logger.debug(
`Connecting to analytics-logging-server: ${this._sessionEndpoint}`
);
ws.onerror = (event) => {
this._logger.error("WebSocket error occurred", event.error);
ws.close(4202);
};
} catch (err) {
const error = err instanceof Error ? err : new Error();
this._logger.error("Failed to create WebSocket instance", error);
this.reconnect();
return;
}
ws.onopen = () => {
this._logger.debug("Connected to analytics-logging-server");
};
ws.onclose = (event) => {
const logMessage = `Close event fired: ${JSON.stringify({ code: event.code, reason: event.reason, type: event.type })}`;
if (4100 <= event.code && event.code <= 4199 || event.code === 1009) {
this._logger.error(logMessage, new Error());
} else {
this._logger.debug(logMessage);
}
if (event.code !== 1e3 && event.code !== 1009 && !(4e3 <= event.code && event.code <= 4199)) {
if (4200 === event.code) {
this.onTokenExpired.emit();
} else {
this.reconnect();
}
return;
}
this._logger.debug("Closed the connection to analytics-logging-server");
this.onConnectionFailed.emit({ code: event.code, reason: event.reason });
this.close();
};
ws.onmessage = (event) => {
this._messageHandler(event.data);
};
this._ws = ws;
}
updateAuthToken(token) {
this._token = token;
}
reconnect() {
if (this._ws !== void 0) {
this._ws.close(4e3);
}
this._ws = void 0;
this._isOpen = false;
if (this._reconnectCount >= 5) {
this.onConnectionFailed.emit({});
this.close();
this._logger.error("Failed to reconnect for five times", new Error());
} else {
this._setConnectionState("reconnecting");
const waitTime = getReconnectWaitTime(this._reconnectCount);
this._reconnectTimer = setTimeout(() => {
this._connect();
this._reconnectCount++;
this._logger.debug(`Try to reconnect: count = ${this._reconnectCount}`);
}, waitTime);
}
}
close() {
this._isClosed = true;
this.destroy();
}
destroy() {
this._setConnectionState("closed");
this.onConnectionStateChanged.removeAllListeners();
this.onOpened.removeAllListeners();
this.onEventReceived.removeAllListeners();
this.onConnectionFailed.removeAllListeners();
if (this._reconnectTimer) {
clearTimeout(this._reconnectTimer);
}
if (this._ws !== void 0) {
this._ws.close(1e3);
}
}
send(clientEvent) {
return __async(this, null, function* () {
if (this._ws === void 0 || !this._isOpen || this._ws.readyState !== import_isomorphic_ws3.default.OPEN) {
this._logger.debug("Try to reconnect because connection is lost");
this.resendAfterReconnect(clientEvent);
return;
}
const data = JSON.stringify(clientEvent.toJSON());
this._ws.send(data, (err) => {
if (err) {
this._logger.debug(
`Try to reconnect because failed to send: ${err.message}`
);
this.resendAfterReconnect(clientEvent);
return;
}
});
});
}
resendAfterReconnect(data) {
const isEventExist = this._resendClientEvents.some(
(event) => event.id === data.id
);
if (!isEventExist) this._resendClientEvents.push(data);
if (this.connectionState !== "reconnecting") {
this.reconnect();
}
}
pushResendClientEventsQueue(data) {
this._resendClientEvents.push(data);
}
isClosed() {
return this._isClosed;
}
_messageHandler(data) {
if (typeof data !== "string") {
this._logger.error("Received invalid message: not string", new Error());
return;
}
let parsedData;
try {
parsedData = JSON.parse(data);
} catch (err) {
const error = err instanceof Error ? err : new Error();
this._logger.error("Received invalid message: parse error", error);
return;
}
if (!isServerEvent(parsedData)) {
this._logger.error(
`Received invalid message: ${JSON.stringify(parsedData)}`,
new Error()
);
return;
}
if (parsedData.type === "Open") {
if (!isOpenServerEventPayload(parsedData.payload)) {
this._logger.error(
`Received invalid message: ${JSON.stringify(parsedData.payload)}`,
new Error()
);
return;
}
this._logger.debug("Received a open event");
this._isOpen = true;
this._setConnectionState("connected");
if (this._reconnectCount !== 0) {
this._reconnectCount = 0;
this._logger.debug("Succeeded to reconnect");
}
if (this._resendClientEvents.length > 0) {
for (const event of this._resendClientEvents) {
if (this._ws === void 0 || !this._isOpen || this._ws.readyState !== import_isomorphic_ws3.default.OPEN) {
this._logger.error(
`Failed to resend event because connection lost after reconnect: ${event}`,
new Error()
);
continue;
}
const data2 = JSON.stringify(event.toJSON());
this._ws.send(data2, (err) => {
if (err) {
this._logger.error(`Failed to resend event: ${event}`, err);
return;
}
this._logger.debug(`Succeed to resend ClientEvent: ${event}`);
});
}
this._logger.debug("Process of resending ClientEvents is completed");
this._resendClientEvents = [];
}
this.onOpened.emit(parsedData.payload);
} else {
this._logger.debug(
`Received the event: ${parsedData.type}, payload: ${JSON.stringify(parsedData.payload)}`
);
this.onEventReceived.emit(parsedData);
}
}
};
function isServerEvent(data) {
if (!data || typeof data !== "object") return false;
if (typeof data.type !== "string" || !ServerEventType.includes(data.type))
return false;
if (typeof data.id !== "string") return false;
if (data.payload && typeof data.payload !== "object") return false;
return true;
}
// ../analytics-client/src/utils/backoff.ts
init_process();
var BackOff2 = class {
/**20.4 sec {var sum=0;for(i=0;i<=8;i++){sum +=i ** 2 * 100}} */
constructor(props = {}) {
this.count = 0;
this.times = 8;
/**ms */
this.interval = 100;
/**ms */
this.jitter = 0;
Object.assign(this, props);
}
wait() {
return __async(this, null, function* () {
if (this.exceeded) {
return false;
}
const timeout = this.timeout;
this.count++;
yield new Promise((r2) => setTimeout(r2, timeout));
return true;
});
}
get timeout() {
const timeout = __pow(this.count, 2) * this.interval + __pow(this.count, 2) * this.jitter * Math.random();
return timeout;
}
get exceeded() {
return this.count >= this.times;
}
reset() {
this.count = 0;
}
stop() {
this.count = this.times;
}
};
// ../analytics-client/src/analyticsClient.ts
var ANALYTICS_LOGGING_SERVER_DOMAIN = "analytics-logging.skyway.ntt.com";
var API_VERSION = "v2";
var TIMEOUT_SEC = 5;
var _AnalyticsClient = class _AnalyticsClient {
constructor({ token, sdkVersion, contextId }, options) {
this.onConnectionStateChanged = new Event3();
this.onConnectionFailed = new Event3();
this.onAnalyticsNotEnabledError = new Event3();
this._isClosed = false;
this._responseCallbacks = /* @__PURE__ */ new Map();
this._acknowledgeCallbacks = /* @__PURE__ */ new Map();
this._mediaDeviceVersion = /* @__PURE__ */ new Map();
this._encodingsVersion = /* @__PURE__ */ new Map();
this._preferredEncodingVersion = /* @__PURE__ */ new Map();
this._previousSubscriptionStats = /* @__PURE__ */ new Map();
this._statsRequest = {
// connect()時のopenServerEventPayload.statsRequest代入でそれぞれ値が入るが,一度初期値として定義しておく
intervalSec: 5,
types: []
};
this._pendingSdkLogs = [];
this._token = token;
this._newToken = void 0;
this._sdkVersion = sdkVersion;
this._contextId = contextId;
const defaultOptions = {
analyticsLoggingServerDomain: ANALYTICS_LOGGING_SERVER_DOMAIN,
secure: true,
logger: {
debug: (message, ...optionalParams) => {
console.debug(message, ...optionalParams);
},
warn: (message, ...optionalParams) => {
console.warn(message, ...optionalParams);
},
error: (error) => {
console.error(error);
}
}
};
this._options = Object.assign({}, defaultOptions, options != null ? options : {});
this._logger = this._options.logger;
this._logger.debug(`Created instance with the options: ${this._options}`);
this._sdkLogTimer = setInterval(() => {
if (this._pendingSdkLogs.length > 0) {
const logs = this._pendingSdkLogs.splice(
0,
this._pendingSdkLogs.length
);
this.sendSdkLogReport(logs).catch((err) => {
this._logger.warn("sendSdkLogReport (interval) failed", err);
});
}
}, 5 * 1e3);
}
get connectionState() {
var _a2, _b2;
return (_b2 = (_a2 = this._socket) == null ? void 0 : _a2.connectionState) != null ? _b2 : "closed";
}
connect() {
return __async(this, null, function* () {
const WSProtocol = this._options.secure ? "wss" : "ws";
const analyticsLoggingServerDomain = this._options.analyticsLoggingServerDomain || ANALYTICS_LOGGING_SERVER_DOMAIN;
this._socket = new Socket2({
sessionEndpoint: `${WSProtocol}://${analyticsLoggingServerDomain}/${API_VERSION}/client/ws`,
contextId: this._contextId,
token: this._token,
logger: this._logger,
sdkVersion: this._sdkVersion
});
this._socket.onEventReceived.addListener((data) => {
try {
this._eventReceivedHandler(data);
} catch (error) {
this._logger.error("in _eventReceivedHandler", error);
}
});
this._socket.onConnectionFailed.addListener((data) => {
if (data.code === 4e3) {
this.onAnalyticsNotEnabledError.emit(data);
}
this.onConnectionFailed.emit();
this.dispose();
});
this._socket.onConnectionStateChanged.addListener((state) => {
var _a2;
if (state === "closed" && !this.isClosed() && ((_a2 = this._socket) == null ? void 0 : _a2.isClosed())) {
this._isClosed = true;
this.dispose();
}
this.onConnectionStateChanged.emit(state);
});
this._socket.onTokenExpired.addListener(() => {
void this._reconnectWithNewSkyWayAuthToken();
});
const openServerEventPayload = yield this._socket.onOpened.asPromise();
if (openServerEventPayload !== void 0) {
this._statsRequest = openServerEventPayload.statsRequest;
return;
} else {
this._logger.error(
"First time connection payload is undefined",
new Error()
);
this.onConnectionFailed.emit();
return;
}
});
}
bufferOrSendSdkLog(log48) {
const shouldImmediateSend = log48.level === "warn" || log48.level === "error";
this._pendingSdkLogs.push(log48);
if (shouldImmediateSend || this._pendingSdkLogs.length >= _AnalyticsClient.MAX_PENDING_SDK_LOGS) {
const logsToSend = [...this._pendingSdkLogs];
this._pendingSdkLogs.length = 0;
this.sendSdkLogReport(logsToSend).catch((err) => {
this._logger.warn("sendSdkLogReport failed", err);
});
}
}
dispose() {
clearInterval(this._sdkLogTimer);
this._disconnect();
this._cleanupAnalyticsClientMaps();
}
setNewSkyWayAuthToken(token) {
if (this._socket !== void 0) {
this._newToken = token;
this._logger.debug("setNewSkyWayAuthToken is success");
}
}
cleanupOnUnpublished(publicationId) {
this._mediaDeviceVersion.delete(publicationId);
this._encodingsVersion.delete(publicationId);
}
cleanupOnUnsubscribed(subscriptionId) {
this._preferredEncodingVersion.delete(subscriptionId);
this._previousSubscriptionStats.delete(subscriptionId);
}
_disconnect() {
var _a2;
(_a2 = this._socket) == null ? void 0 : _a2.destroy();
this._socket = void 0;
this._responseCallbacks.clear();
this._acknowledgeCallbacks.clear();
}
sendMediaDeviceReport(report) {
return __async(this, null, function* () {
let currentMediaDeviceVersion = this._mediaDeviceVersion.get(
report.publicationId
);
if (currentMediaDeviceVersion === void 0) {
currentMediaDeviceVersion = 0;
} else {
currentMediaDeviceVersion++;
}
this._mediaDeviceVersion.set(
report.publicationId,
currentMediaDeviceVersion
);
const payload = {
publicationId: report.publicationId,
mediaDeviceName: report.mediaDeviceName,
mediaDeviceVersion: currentMediaDeviceVersion,
mediaDeviceTrigger: report.mediaDeviceTrigger,
updatedAt: report.updatedAt
};
const clientEvent = new ClientEvent2("MediaDeviceReport", payload);
yield this._sendClientEvent(clientEvent).catch((err) => {
this._logger.warn(
"_sendClientEvent in sendMediaDeviceReport is failed",
err
);
});
});
}
sendSdkLogReport(logs) {
return __async(this, null, function* () {
if (logs.length === 0) return;
const sdkLogs = logs.map((l) => ({
timestamp: l.timestamp,
level: l.level,
message: Array.isArray(l.message) ? l.message.map((m) => typeof m === "string" ? m : JSON.stringify(m)).join(",") : String(l.message)
}));
const clientEvent = new ClientEvent2("SdkLog", {
sdkLogs,
contextId: this._contextId
});
yield this._sendClientEvent(clientEvent).catch((err) => {
this._logger.warn("_sendClientEvent in sendSdkLogReport is failed", err);
});
});
}
sendBindingRtcPeerConnectionToSubscription(bindingData) {
return __async(this, null, function* () {
const clientEvent = new ClientEvent2(
"BindingRtcPeerConnectionToSubscription",
bindingData
);
yield this._sendClientEvent(clientEvent).catch((err) => {
this._logger.warn(
"_sendClientEvent in sendBindingRtcPeerConnectionToSubscription is failed",
err
);
});
});
}
/**
* RTCStatsReportにはcandidate-pair, local-candidate, remote-candidateが複数含まれる場合がある。
* 現在利用されているもののみを選出して返す。
*/
filterStatsReport(report) {
const connectedTransport = Array.from(report.values()).find(
(rtcStatsReportValue) => rtcStatsReportValue.type === "transport" && rtcStatsReportValue.dtlsState === "connected"
);
const candidatePairKeys = [];
if (connectedTransport) {
const nominatedCandidatePair = Array.from(report.values()).find(
(rtcStatsReportValue) => rtcStatsReportValue.type === "candidate-pair" && rtcStatsReportValue.nominated && rtcStatsReportValue.id === (connectedTransport == null ? void 0 : connectedTransport.selectedCandidatePairId)
);
if (nominatedCandidatePair) {
candidatePairKeys.push(
nominatedCandidatePair.id,
nominatedCandidatePair.localCandidateId,
nominatedCandidatePair.remoteCandidateId,
nominatedCandidatePair.transportId
);
}
} else {
const nominatedCandidatePair = Array.from(report.values()).find(
(rtcStatsReportValue) => rtcStatsReportValue.type === "candidate-pair" && rtcStatsReportValue.nominated && rtcStatsReportValue.selected
);
if (nominatedCandidatePair) {
candidatePairKeys.push(
nominatedCandidatePair.id,
nominatedCandidatePair.localCandidateId,
nominatedCandidatePair.remoteCandidateId,
nominatedCandidatePair.transportId
);
}
}
const filteredReport = /* @__PURE__ */ new Map();
const duplicatableTypes = [
"candidate-pair",
"local-candidate",
"remote-candidate",
"transport"
];
for (const [key, rtcStatsReportValue] of report.entries()) {
if (duplicatableTypes.includes(rtcStatsReportValue.type)) {
if (candidatePairKeys.includes(rtcStatsReportValue.id)) {
filteredReport.set(key, rtcStatsReportValue);
}
} else {
filteredReport.set(key, rtcStatsReportValue);
}
}
return filteredReport;
}
bundleStatsReportByStatsType(report) {
const stats = {};
for (const v of report.values()) {
stats[v.type] = v;
}
return stats;
}
sendSubscriptionStatsReport(report, subscriptionParams) {
return __async(this, null, function* () {
var _a2;
const previousSubscriptionStat = this._previousSubscriptionStats.get(
subscriptionParams.subscriptionId
);
this._previousSubscriptionStats.set(subscriptionParams.subscriptionId, {
stats: report,
createdAt: subscriptionParams.createdAt
});
if (previousSubscriptionStat === void 0) {
return;
}
const filteredPreviousSubscriptionStats = this.filterStatsReport(
previousSubscriptionStat.stats
);
const prevBundledSubscriptionStats = this.bundleStatsReportByStatsType(
filteredPreviousSubscriptionStats
);
const previousCreatedAt = previousSubscriptionStat.createdAt;
const duration = (subscriptionParams.createdAt - previousCreatedAt) / 1e3;
if (duration <= 0) {
throw new Error(
"duration must be greater than 0. also sendSubscriptionStatsReport was duplicated."
);
}
const filteredStatsReport = this.filterStatsReport(report);
const bundledStatsReport = this.bundleStatsReportByStatsType(filteredStatsReport);
const subscriptionStats = {};
for (const { type, properties } of this._statsRequest.types) {
for (const [
prop,
{ normalization: normRequired, outputKey, contentType }
] of Object.entries(properties)) {
if (!contentType.includes(subscriptionParams.contentType)) {
continue;
}
const statsReport = bundledStatsReport[type];
if (statsReport === void 0 || statsReport[prop] === void 0) {
continue;
}
if (normRequired) {
const previousValue = (_a2 = prevBundledSubscriptionStats[type]) == null ? void 0 : _a2[prop];
if (previousValue === void 0) {
this._logger.warn(`${type} in previous statsReport is undefined`);
continue;
}
const perSecondValue = (Number(statsReport[prop]) - Number(previousValue)) / duration;
subscriptionStats[type] = __spreadProps(__spreadValues({}, subscriptionStats[type]), {
[outputKey]: String(perSecondValue)
});
} else {
subscriptionStats[type] = __spreadProps(__spreadValues({}, subscriptionStats[type]), {
[outputKey]: String(statsReport[prop])
});
}
}
}
const payload = {
subscriptionId: subscriptionParams.subscriptionId,
stats: subscriptionStats,
role: subscriptionParams.role,
createdAt: subscriptionParams.createdAt
};
const clientEvent = new ClientEvent2("SubscriptionStatsReport", payload);
yield this._sendClientEvent(clientEvent).catch((err) => {
this._logger.warn(
"_sendClientEvent in sendSubscriptionStatsReport is failed",
err
);
});
});
}
sendRtcPeerConnectionEventReport(report) {
return __async(this, null, function* () {
const clientEvent = new ClientEvent2("RtcPeerConnectionEventReport", report);
yield this._sendClientEvent(clientEvent).catch((err) => {
this._logger.warn(
"_sendClientEvent in sendRtcPeerConnectionEventReport is failed",
err
);
});
});
}
sendPublicationUpdateEncodingsReport(report) {
return __async(this, null, function* () {
let currentEncodingsVersion = this._encodingsVersion.get(
report.publicationId
);
if (currentEncodingsVersion === void 0) {
currentEncodingsVersion = 0;
} else {
currentEncodingsVersion++;
}
this._encodingsVersion.set(report.publicationId, currentEncodingsVersion);
const payload = {
publicationId: report.publicationId,
encodings: report.encodings,
encodingsVersion: currentEncodingsVersion,
updatedAt: report.updatedAt
};
const clientEvent = new ClientEvent2(
"PublicationUpdateEncodingsReport",
payload
);
yield this._sendClientEvent(clientEvent).catch((err) => {
this._logger.warn(
"_sendClientEvent in sendPublicationUpdateEncodingsReport is failed",
err
);
});
});
}
sendSubscriptionUpdatePreferredEncodingReport(report) {
return __async(this, null, function* () {
let currentPreferredEncodingVersion = this._preferredEncodingVersion.get(
report.subscriptionId
);
if (currentPreferredEncodingVersion === void 0) {
currentPreferredEncodingVersion = 0;
} else {
currentPreferredEncodingVersion++;
}
this._preferredEncodingVersion.set(
report.subscriptionId,
currentPreferredEncodingVersion
);
const payload = {
subscriptionId: report.subscriptionId,
preferredEncodingIndex: report.preferredEncodingIndex,
preferredEncodingVersion: currentPreferredEncodingVersion,
updatedAt: report.updatedAt
};
const clientEvent = new ClientEvent2(
"SubscriptionUpdatePreferredEncodingReport",
payload
);
yield this._sendClientEvent(clientEvent).catch((err) => {
this._logger.warn(
"_sendClientEvent in sendSubscriptionUpdatePreferredEncodingReport is failed",
err
);
});
});
}
sendJoinReport(report) {
return __async(this, null, function* () {
const clientEvent = new ClientEvent2("JoinReport", report);
yield this._sendClientEvent(clientEvent).catch((err) => {
this._logger.warn("_sendClientEvent in sendJoinReport is failed", err);
});
});
}
_sendClientEvent(clientEvent) {
return __async(this, null, function* () {
return new Promise((resolve, reject) => {
if (this._socket === void 0 || this._socket.connectionState === "closed") {
reject(new Error("websocket is not connected"));
return;
}
if (this._socket.connectionState === "connecting") {
this._socket.pushResendClientEventsQueue(clientEvent);
this._setAcknowledgeCallback(
clientEvent.id,
(data) => __async(this, null, function* () {
if (data.ok) {
this._acknowledgeCallbacks.delete(clientEvent.id);
resolve();
} else {
this._acknowledgeCallbacks.delete(clientEvent.id);
reject(data);
}
})
);
this._logger.debug(
`pushResendClientEventsQueue and setAcknowledgeCallback. clientEvent.id: ${clientEvent.id}`
);
reject(new Error("websocket is connecting now"));
return;
}
const executeAsync = () => __async(this, null, function* () {
const backoff = new BackOff2({ times: 6, interval: 500, jitter: 100 });
for (; !backoff.exceeded; ) {
const timer = setTimeout(() => __async(this, null, function* () {
if (this._socket === void 0) {
this._acknowledgeCallbacks.delete(clientEvent.id);
reject(new Error("Socket closed when trying to resend"));
return;
} else {
this._socket.resendAfterReconnect(clientEvent);
}
reject(new Error("Timeout to send data"));
return;
}), TIMEOUT_SEC * 1e3);
this._logger.debug(
`send clientEvent, ${JSON.stringify(clientEvent)}`
);
if (this._socket) {
this._socket.send(clientEvent).catch((err) => {
this._acknowledgeCallbacks.delete(clientEvent.id);
clearTimeout(timer);
reject(err);
return;
});
} else {
this._acknowledgeCallbacks.delete(clientEvent.id);
clearTimeout(timer);
reject(new Error("Socket is undefined"));
return;
}
const result2 = yield this._waitForAcknowledge(clientEvent.id).catch(
(err) => {
return err;
}
);
clearTimeout(timer);
if (isAcknowledgePayload2(result2)) {
if (result2.reason === "unexpected") {
yield backoff.wait();
} else {
reject(result2);
return;
}
} else {
resolve();
return;
}
}
reject(new Error("unexpected has occurred at server"));
return;
});
executeAsync().catch(reject);
});
});
}
_waitForAcknowledge(clientEventId) {
return __async(this, null, function* () {
return new Promise((resolve, reject) => {
this._setAcknowledgeCallback(
clientEventId,
(data) => __async(this, null, function* () {
if (data.ok) {
this._acknowledgeCallbacks.delete(clientEventId);
resolve();
} else {
this._acknowledgeCallbacks.delete(clientEventId);
reject(data);
}
})
);
});
});
}
_reconnectWithNewSkyWayAuthToken() {
return __async(this, null, function* () {
this._disconnect();
if (this._newToken !== void 0) {
this._token = this._newToken;
this._newToken = void 0;
yield this.connect();
} else {
this._logger.warn("new token is not set. so not reconnect.");
}
});
}
_eventReceivedHandler(data) {
switch (data.type) {
case "Acknowledge":
this._acknowledgeHandler(data.payload);
break;
case "Open":
break;
// nop
default: {
const _ = data.type;
this._logger.warn(`Unknown event: ${data.type}`);
}
}
}
_acknowledgeHandler(payload) {
if (!isAcknowledgePayload2(payload)) {
throw new Error("Invalid payload");
}
const { eventId } = payload;
if (!this._acknowledgeCallbacks.has(eventId)) {
throw new Error(`acknowledge event has unknown eventId: ${eventId}`);
}
const callback = this._acknowledgeCallbacks.get(eventId);
if (callback) {
this._acknowledgeCallbacks.delete(eventId);
callback(payload);
}
}
_setAcknowledgeCallback(eventId, callback) {
this._acknowledgeCallbacks.set(eventId, callback);
}
_cleanupAnalyticsClientMaps() {
this._mediaDeviceVersion.clear();
this._encodingsVersion.clear();
this._preferredEncodingVersion.clear();
this._previousSubscriptionStats.clear();
}
getIntervalSec() {
return this._statsRequest.intervalSec;
}
isConnectionEstablished() {
if (!this._socket || this._socket.connectionState === "connecting" || this._socket.connectionState === "closed") {
return false;
} else {
return true;
}
}
isClosed() {
return this._isClosed;
}
};
_AnalyticsClient.MAX_PENDING_SDK_LOGS = 50;
var AnalyticsClient = _AnalyticsClient;
// ../analytics-client/src/utils/logger.ts
init_process();
// ../core/src/external/analytics.ts
var LOGGER_PREFIX = "packages/core/src/external/analytics.ts";
var log28 = new Logger(LOGGER_PREFIX);
function setupAnalyticsSession(context) {
return __async(this, null, function* () {
const { analyticsService } = context.config;
const client = new AnalyticsClient(
{
token: context.authTokenString,
sdkVersion: SkyWayContext.version,
// coreパッケージのバージョンを引き渡す
contextId: SkyWayContext.id
},
{
logger: {
error: (message, error) => __async(null, null, function* () {
log28.error(
`AnalyticsClient error: ${message}`,
createError({
operationName: "AnalyticsClient.logger",
context,
info: __spreadProps(__spreadValues({}, errors.internal), { detail: "AnalyticsClient error" }),
error,
path: log28.prefix
})
);
}),
debug: (message, ...optionalParams) => {
log28.debug("[analytics]:", message, ...optionalParams);
},
warn: (message, ...optionalParams) => {
log28.warn("[analytics]:", message, ...optionalParams);
}
},
analyticsLoggingServerDomain: analyticsService.domain,
secure: analyticsService.secure
}
);
const analyticsSession = new AnalyticsSession(client, context);
Logger._onLogForAnalytics = (props) => {
if (props.prefix === LOGGER_PREFIX) {
return;
}
void client.bufferOrSendSdkLog(props);
};
analyticsSession.connectWithTimeout().catch((error) => {
analyticsSession.close();
log28.error(
`AnalyticsClient error: ${error.message}`,
createError({
operationName: "AnalyticsClient.logger",
context,
info: __spreadProps(__spreadValues({}, errors.internal), { detail: "AnalyticsClient error" }),
error,
path: log28.prefix
})
);
analyticsSession.onConnectionFailed.emit({});
});
return analyticsSession;
});
}
var AnalyticsSession = class {
constructor(client, context) {
this.client = client;
this.onConnectionFailed = new Event();
this.onConnectionStateChanged = new Event();
this.onMessage = new Event();
this._isClosed = false;
this._listen();
context.onTokenUpdated.add((token) => {
this.client.setNewSkyWayAuthToken(token);
});
}
_listen() {
this.client.onConnectionFailed.addOneTimeListener(() => {
this.onConnectionFailed.emit({});
});
this.client.onConnectionStateChanged.addListener((state) => {
if (state === "closed" && !this.isClosed() && this.client.isClosed()) {
this.close();
}
this.onConnectionStateChanged.emit(state);
});
}
get connectionState() {
return this.client.connectionState;
}
_connect() {
return __async(this, null, function* () {
log28.debug("[start] connect analyticsService");
yield this.client.connect().then(() => {
log28.debug("[end] connect analyticsService");
}).catch((error) => {
this.close();
log28.debug(
"[end] failed connect analyticsService: also unreachable to server"
);
log28.error(
`AnalyticsClient error: ${error.message}`,
createError({
operationName: "AnalyticsClient.logger",
info: __spreadProps(__spreadValues({}, errors.internal), { detail: "AnalyticsClient error" }),
error,
path: log28.prefix
})
);
this.onConnectionFailed.emit({});
});
return;
});
}
connectWithTimeout() {
return __async(this, null, function* () {
let connectTimeout;
const timeoutPromise = new Promise((_, reject) => {
connectTimeout = setTimeout(() => {
log28.debug(
"[end] failed connect analyticsService: no initial response from the server"
);
reject(new Error("failed connect analyticsService"));
}, 30 * 1e3);
});
const firstConnectionFailedPromise = new Promise((resolve, _) => {
this.client.onAnalyticsNotEnabledError.addOneTimeListener((data) => {
log28.warn(`[end] failed connect analyticsService: ${data.reason}`);
resolve();
});
});
return Promise.race([
this._connect(),
timeoutPromise,
firstConnectionFailedPromise
]).finally(() => {
clearTimeout(connectTimeout);
});
});
}
close() {
this._isClosed = true;
this.onConnectionFailed.removeAllListeners();
this.onConnectionStateChanged.removeAllListeners();
this.onMessage.removeAllListeners();
}
isClosed() {
return this._isClosed;
}
};
// ../core/src/plugin/internal/person/plugin.ts
init_process();
// ../core/src/plugin/interface/plugin.ts
init_process();
var SkyWayPlugin = class {
constructor() {
/**@internal */
this._onContextAttached = new Event();
}
/**@internal */
_attachContext(context) {
this._context = context;
this._onContextAttached.emit(context);
}
};
// ../core/src/plugin/internal/person/connection/messageBuffer.ts
init_process();
var log29 = new Logger(
"packages/core/src/plugin/internal/person/connection/messageBuffer.ts"
);
var MessageBuffer = class {
constructor(signaling) {
this.signaling = signaling;
this._indicateMessageBuffer = {};
this._excludeConnectionIndicateBuffering = /* @__PURE__ */ new Set();
this._disposer = new EventDisposer();
this.signaling.onMessage.add((req) => {
const requesterIdName = req.src.id + req.src.name;
if (this._excludeConnectionIndicateBuffering.has(requesterIdName)) {
return;
}
if (!this._indicateMessageBuffer[requesterIdName]) {
this._indicateMessageBuffer[requesterIdName] = [];
}
this._indicateMessageBuffer[requesterIdName].push(req);
}).disposer(this._disposer);
}
resolveMessagingBuffer({ id, name }) {
const endpointIdName = id + name;
const bufferedIndicates = this._indicateMessageBuffer[endpointIdName];
if ((bufferedIndicates == null ? void 0 : bufferedIndicates.length) > 0) {
log29.debug("resolveMessagingBuffer", { length: bufferedIndicates.length });
bufferedIndicates.forEach((req) => {
this.signaling.onMessage.emit(req);
});
delete this._indicateMessageBuffer[endpointIdName];
}
this._excludeConnectionIndicateBuffering.add(endpointIdName);
}
close() {
this._disposer.dispose();
this._indicateMessageBuffer = {};
this._excludeConnectionIndicateBuffering = /* @__PURE__ */ new Set();
}
};
// ../core/src/plugin/internal/person/member.ts
init_process();
// ../core/src/plugin/internal/person/connection/index.ts
init_process();
// ../core/src/plugin/internal/person/connection/receiver.ts
init_process();
var sdpTransform2 = __toESM(require_lib());
// ../core/src/media/stream/remote/factory.ts
init_process();
// ../core/src/media/stream/remote/audio.ts
init_process();
// ../core/src/media/stream/remote/media.ts
init_process();
// ../core/src/media/stream/remote/base.ts
init_process();
var RemoteStreamBase = class {
/**@internal */
constructor(id, contentType) {
this.id = id;
this.contentType = contentType;
this.side = "remote";
/**@internal */
this._onConnectionStateChanged = new Event();
this._connectionState = "new";
/**@internal */
this._getTransport = () => void 0;
/**@internal */
this._getStats = () => __async(null, null, function* () {
return [];
});
}
/**@internal */
_setConnectionState(state) {
if (this._connectionState === state) return;
this._connectionState = state;
this._onConnectionStateChanged.emit(state);
}
/**@internal */
_getRTCPeerConnection() {
var _a2;
return (_a2 = this._getTransport()) == null ? void 0 : _a2.rtcPeerConnection;
}
/**@internal */
_getConnectionState() {
return this._connectionState;
}
/**@internal */
toJSON() {
return {
contentType: this.contentType,
id: this.id,
codec: this.codec,
side: this.side
};
}
};
// ../core/src/media/stream/remote/media.ts
var RemoteMediaStreamBase = class extends RemoteStreamBase {
constructor(id, contentType, track) {
super(id, contentType);
this.id = id;
this.contentType = contentType;
this.track = track;
}
/**@internal */
setIsEnabled(b) {
this.track.enabled = b;
}
/**
* @description [english] Attach the stream to the element.
* @description [japanese] streamをelementに適用する.
*/
attach(element) {
this._element = element;
attachElement(element, this.track);
}
/**
* @description [english] Detach the stream from the element.
* @description [japanese] elementからstreamを取り除く.
*/
detach() {
if (this._element) {
detachElement(this._element, this.track);
this._element = void 0;
}
}
};
// ../core/src/media/stream/remote/audio.ts
var RemoteAudioStream = class extends RemoteMediaStreamBase {
/**@internal */
constructor(id, track) {
super(id, "audio", track);
this.track = track;
this.contentType = "audio";
}
/**@description [japanese] 直近100msにおける最大音量を取得する(値の範囲:0-1) */
getAudioLevel() {
if (this._audioLevel === void 0) {
this._audioLevel = new AudioLevel(this.track);
}
return this.track.enabled ? this._audioLevel.calculate() : 0;
}
};
// ../core/src/media/stream/remote/data.ts
init_process();
var RemoteDataStream = class extends RemoteStreamBase {
/**@internal */
constructor(id, _datachannel) {
super(id, "data");
this._datachannel = _datachannel;
this._isEnabled = true;
this.contentType = "data";
this.onData = new Event();
_datachannel.onmessage = ({ data }) => {
if (!this._isEnabled) {
return;
}
if (typeof data === "string" && data.includes(objectFlag)) {
data = JSON.parse(data.slice(objectFlag.length));
}
this.onData.emit(data);
};
}
/**@internal */
setIsEnabled(b) {
this._isEnabled = b;
}
};
// ../core/src/media/stream/remote/video.ts
init_process();
var RemoteVideoStream = class extends RemoteMediaStreamBase {
/**@internal */
constructor(id, track) {
super(id, "video", track);
this.track = track;
this.contentType = "video";
}
};
// ../core/src/media/stream/remote/factory.ts
var log30 = new Logger("packages/core/src/media/stream/remote/factory.ts");
var createRemoteStream = (id, media, codec) => {
if (media instanceof RTCDataChannel) {
const stream = new RemoteDataStream(id, media);
stream.codec = codec;
return stream;
} else {
if (media.kind === "audio") {
const stream = new RemoteAudioStream(id, media);
stream.codec = codec;
return stream;
} else if (media.kind === "video") {
const stream = new RemoteVideoStream(id, media);
stream.codec = codec;
return stream;
}
}
throw createError({
operationName: "createRemoteStream",
path: log30.prefix,
info: __spreadProps(__spreadValues({}, errors.invalidArgumentValue), { detail: "invalid stream type" })
});
};
// ../core/src/plugin/internal/person/util.ts
init_process();
var log31 = new Logger("packages/core/src/plugin/internal/person/util.ts");
var setEncodingParams = (sender, newEncodings) => __async(null, null, function* () {
const info = log31.createBlock({ label: "setEncodingParams" });
const params = sender.getParameters();
info.debug("getParameters", { params, newEncodings });
if (params.encodings === void 0 || params.encodings === null) {
params.encodings = [];
}
params.encodings = newEncodings.map((encoding, i) => __spreadValues(__spreadValues({}, params.encodings[i] || {}), encoding));
yield sender.setParameters(params);
});
var isSafari = () => detectDevice() === "Safari12" || detectDevice() === "Safari11";
function convertConnectionState(state) {
switch (state) {
case "closed":
case "disconnected":
case "failed":
return "disconnected";
case "connected":
return "connected";
case "connecting":
return "connecting";
case "new":
return "new";
case "reconnecting":
return "reconnecting";
}
}
var statsToJson = (report) => {
const stats = [];
report.forEach((stat) => {
stats.push(JSON.parse(JSON.stringify(stat)));
});
return stats;
};
// ../core/src/plugin/internal/person/connection/datachannel.ts
init_process();
var DataChannelNegotiationLabel = class _DataChannelNegotiationLabel {
constructor(publicationId, streamId) {
this.publicationId = publicationId;
this.streamId = streamId;
}
static fromLabel(label) {
const { p, s } = JSON.parse(label);
return new _DataChannelNegotiationLabel(p, s);
}
toLabel() {
return JSON.stringify({
p: this.publicationId,
s: this.streamId
});
}
};
// ../core/src/plugin/internal/person/connection/peer.ts
init_process();
var log32 = new Logger(
"packages/core/src/plugin/internal/person/connection/peer.ts"
);
var Peer = class {
constructor(_context, _iceManager, signaling, analytics, localPerson, endpoint, role) {
this._context = _context;
this._iceManager = _iceManager;
this.signaling = signaling;
this.analytics = analytics;
this.localPerson = localPerson;
this.endpoint = endpoint;
this.role = role;
this._pendingCandidates = [];
this.pc = new RTCPeerConnection(__spreadProps(__spreadValues({}, this._context.config.rtcConfig), {
iceTransportPolicy: this._context.config.rtcConfig.turnPolicy === "turnOnly" ? "relay" : void 0,
iceServers: this._iceManager.iceServers
}));
this.onSignalingStateChanged = new Event();
this.onPeerConnectionStateChanged = new Event();
this.onDisconnect = new Event();
this.connected = false;
this.disconnected = false;
this.rtcPeerConnectionId = uuidV4();
this._onICECandidate = (ev) => __async(this, null, function* () {
if (ev.candidate == null || // eslint-disable-next-line @typescript-eslint/ban-ts-comment
//@ts-expect-error firefox
ev.candidate === "" || this.pc.connectionState === "closed") {
return;
}
const message = {
kind: "iceCandidateMessage",
payload: {
candidate: ev.candidate,
role: this.role
}
};
log32.debug("[start] send candidate", {
message,
localPerson: this.localPerson
});
if (this.localPerson._analytics && !this.localPerson._analytics.isClosed()) {
void this.localPerson._analytics.client.sendRtcPeerConnectionEventReport({
rtcPeerConnectionId: this.rtcPeerConnectionId,
type: "iceCandidate",
data: {
candidate: JSON.stringify(ev.candidate)
},
createdAt: Date.now()
});
}
try {
yield this.signaling.send(this.endpoint, message);
log32.debug(`[end] send candidate`, {
message,
localPerson: this.localPerson
});
} catch (error) {
log32.warn(
`[failed] send candidate`,
createWarnPayload({
operationName: "Peer._onICECandidate",
channel: this.localPerson.channel,
detail: "[failed] send candidate",
payload: { message }
}),
error
);
}
});
this._onICECandidateError = (ev) => __async(this, null, function* () {
if (this.localPerson._analytics && !this.localPerson._analytics.isClosed()) {
void this.localPerson._analytics.client.sendRtcPeerConnectionEventReport({
rtcPeerConnectionId: this.rtcPeerConnectionId,
type: "iceCandidateError",
data: {
event: JSON.stringify(ev)
},
createdAt: Date.now()
});
}
});
this._onIceGatheringStateChange = () => __async(this, null, function* () {
if (this.localPerson._analytics && !this.localPerson._analytics.isClosed()) {
const state = this.pc.iceGatheringState;
void this.localPerson._analytics.client.sendRtcPeerConnectionEventReport({
rtcPeerConnectionId: this.rtcPeerConnectionId,
type: "iceGatheringStateChange",
data: {
event: state
},
createdAt: Date.now()
});
}
});
this._onConnectionStateChange = () => __async(this, null, function* () {
const state = this.pc.connectionState;
if (this.localPerson._analytics && !this.localPerson._analytics.isClosed()) {
void this.localPerson._analytics.client.sendRtcPeerConnectionEventReport({
rtcPeerConnectionId: this.rtcPeerConnectionId,
type: "connectionStateChange",
data: {
connectionState: state
},
createdAt: Date.now()
});
}
switch (state) {
case "connected":
this.connected = true;
this._pendingCandidates = [];
break;
}
this.onPeerConnectionStateChanged.emit(this.pc.connectionState);
});
this._onIceConnectionStateChange = () => __async(this, null, function* () {
if (this.localPerson._analytics && !this.localPerson._analytics.isClosed()) {
const state = this.pc.iceConnectionState;
void this.localPerson._analytics.client.sendRtcPeerConnectionEventReport({
rtcPeerConnectionId: this.rtcPeerConnectionId,
type: "iceConnectionStateChange",
data: {
iceConnectionState: state
},
createdAt: Date.now()
});
}
});
this._onSignalingStateChange = () => __async(this, null, function* () {
if (this.localPerson._analytics && !this.localPerson._analytics.isClosed()) {
const state = this.pc.signalingState;
void this.localPerson._analytics.client.sendRtcPeerConnectionEventReport({
rtcPeerConnectionId: this.rtcPeerConnectionId,
type: "signalingStateChange",
data: {
signalingState: state
},
createdAt: Date.now()
});
}
});
/**@throws {@link SkyWayError} */
this.waitForSignalingState = (state, timeout = 1e4) => __async(this, null, function* () {
if (this.pc.signalingState === state) return;
yield this.onSignalingStateChanged.watch(() => this.pc.signalingState === state, timeout).catch((err) => {
throw createError({
operationName: "Peer.waitForSignalingState",
info: __spreadProps(__spreadValues({}, errors.timeout), {
detail: "waitForSignalingState timeout"
}),
path: log32.prefix,
context: this._context,
channel: this.localPerson.channel,
error: err
});
});
});
/**@throws {@link SkyWayError} */
this.waitForConnectionState = (state, timeout = 1e4) => __async(this, null, function* () {
if (state === this.pc.connectionState) return;
yield this.onPeerConnectionStateChanged.watch(() => state === this.pc.connectionState, timeout).catch((err) => {
throw createError({
operationName: "Peer.waitForConnectionState",
info: __spreadProps(__spreadValues({}, errors.timeout), {
detail: "waitForConnectionState timeout"
}),
path: log32.prefix,
context: this._context,
channel: this.localPerson.channel,
error: err
});
});
});
/**@throws {@link SkyWayError} */
this.waitForStats = (_0) => __async(this, [_0], function* ({
track,
cb,
interval,
timeout,
logging
}) {
interval != null ? interval : interval = 100;
timeout != null ? timeout : timeout = 1e4;
for (let elapsed = 0; ; elapsed += interval) {
if (elapsed >= timeout) {
throw createError({
operationName: "Peer.waitForStats",
info: __spreadProps(__spreadValues({}, errors.timeout), {
detail: "waitForStats timeout"
}),
path: log32.prefix,
context: this._context,
channel: this.localPerson.channel
});
}
const report = yield this.pc.getStats(track);
const stats = statsToJson(report);
if (logging) {
log32.debug("Peer.waitForStats", stats);
}
if (cb(stats)) {
break;
}
yield new Promise((r2) => setTimeout(r2, interval));
}
});
var _a2;
log32.debug("peerConfig", this.pc.getConfiguration());
this.setPeerConnectionListener();
const peerIdentity = (_a2 = this.pc) == null ? void 0 : _a2.peerIdentity;
if (peerIdentity) {
peerIdentity.catch((err) => {
log32.debug("firefox peerIdentity", err);
});
}
}
setPeerConnectionListener() {
this.pc.onicecandidate = this._onICECandidate;
this.pc.onicecandidateerror = this._onICECandidateError;
this.pc.onicegatheringstatechange = this._onIceGatheringStateChange;
this.pc.onconnectionstatechange = this._onConnectionStateChange;
this.pc.oniceconnectionstatechange = this._onIceConnectionStateChange;
this.pc.onsignalingstatechange = () => {
void this._onSignalingStateChange();
this.onSignalingStateChanged.emit(this.pc.signalingState);
};
}
unSetPeerConnectionListener() {
this.pc.onicecandidate = null;
this.pc.onicecandidateerror = null;
this.pc.onicegatheringstatechange = null;
this.pc.onconnectionstatechange = null;
this.pc.oniceconnectionstatechange = null;
this.pc.onsignalingstatechange = null;
}
handleCandidate(candidate) {
return __async(this, null, function* () {
this._pendingCandidates.push(candidate);
if (this.pc.remoteDescription) {
yield this.resolveCandidates();
}
});
}
resolveCandidates() {
return __async(this, null, function* () {
const candidates = [...this._pendingCandidates];
this._pendingCandidates = [];
log32.debug("addIceCandidates", candidates);
yield Promise.all(
candidates.map((candidate) => {
if (this.pc.signalingState === "closed") return Promise.resolve();
return this.pc.addIceCandidate(candidate).catch((err) => {
log32.warn(
"[failed] add ice candidate",
createWarnPayload({
operationName: "Peer.resolveCandidates",
channel: this.localPerson.channel,
detail: "[failed] send candidate",
payload: { endpointId: this.endpoint.id }
}),
err
);
});
})
);
});
}
};
// ../core/src/plugin/internal/person/connection/receiver.ts
var log33 = new Logger(
"packages/core/src/plugin/internal/person/connection/receiver.ts"
);
var Receiver = class extends Peer {
constructor(context, iceManager, signaling, analytics, localPerson, endpoint) {
super(
context,
iceManager,
signaling,
analytics,
localPerson,
endpoint,
"receiver"
);
this.id = v4_default();
this.onConnectionStateChanged = new Event();
this.onStreamAdded = new Event();
this.onError = new Event();
this._connectionState = "new";
this._publicationInfo = {};
this.streams = {};
this._subscriptions = {};
this._promiseQueue = new PromiseQueue();
this._disposer = new EventDisposer();
this._log = log33.createBlock({
localPersonId: this.localPerson.id,
id: this.id
});
this._log.debug("spawned");
this.signaling.onMessage.add((_0) => __async(this, [_0], function* ({ src, data }) {
if (!(src.id === endpoint.id && src.name === endpoint.name)) return;
const message = data;
switch (message.kind) {
case "senderProduceMessage":
{
this._promiseQueue.push(() => this._handleSenderProduce(message.payload)).catch(
(err) => this._log.error("handle senderProduceMessage failed", err, {
localPersonId: this.localPerson.id,
endpointId: this.endpoint.id
})
);
}
break;
case "senderUnproduceMessage":
{
this._promiseQueue.push(() => this._handleSenderUnproduce(message.payload)).catch(
(err) => this._log.error("handle handleSenderUnproduce", err, {
localPersonId: this.localPerson.id,
endpointId: this.endpoint.id
})
);
}
break;
case "senderRestartIceMessage":
{
this._promiseQueue.push(() => this._handleSenderRestartIce(message.payload)).catch(
(err) => this._log.error("_handleSenderRestartIce", err, {
localPersonId: this.localPerson.id,
endpointId: this.endpoint.id
})
);
}
break;
case "iceCandidateMessage":
{
const { role, candidate } = message.payload;
if (role === "sender") {
yield this.handleCandidate(candidate);
}
}
break;
}
})).disposer(this._disposer);
this.pc.ontrack = (_0) => __async(this, [_0], function* ({ track, transceiver }) {
if (!transceiver.mid) {
throw createError({
operationName: "Receiver.pc.ontrack",
info: __spreadProps(__spreadValues({}, errors.missingProperty), {
detail: "mid missing"
}),
path: log33.prefix,
context: this._context,
channel: this.localPerson.channel
});
}
const info = Object.values(this._publicationInfo).find(
(i) => {
var _a2;
return i.mid === ((_a2 = transceiver.mid) == null ? void 0 : _a2.toString());
}
);
if (!info) {
const error = createError({
operationName: "Receiver.pc.ontrack",
info: __spreadProps(__spreadValues({}, errors.notFound), { detail: "publicationInfo not found" }),
path: log33.prefix,
context: this._context,
channel: localPerson.channel,
payload: {
endpointId: this.endpoint.id,
publicationInfo: this._publicationInfo,
mid: transceiver.mid
}
});
this.onError.emit(error);
this._log.error(error);
return;
}
const sdpObject = sdpTransform2.parse(this.pc.remoteDescription.sdp);
const codec = this._getCodecFromSdp(sdpObject, transceiver, track.kind);
const stream = createRemoteStream(info.streamId, track, codec);
stream.codec = codec;
this._setupTransportAccessForStream(stream);
this.streams[info.publicationId] = stream;
this._log.debug("MediaStreamTrack added", info, track, codec);
this.onStreamAdded.emit({
publicationId: info.publicationId,
stream
});
});
this.pc.ondatachannel = (_0) => __async(this, [_0], function* ({ channel }) {
const { publicationId, streamId } = DataChannelNegotiationLabel.fromLabel(
channel.label
);
const codec = { mimeType: "datachannel" };
const stream = createRemoteStream(streamId, channel, codec);
this._setupTransportAccessForStream(stream);
this.streams[publicationId] = stream;
this._log.debug("DataChannel added", publicationId, channel, codec);
this.onStreamAdded.emit({
publicationId,
stream
});
});
this.onPeerConnectionStateChanged.add((state) => {
switch (state) {
case "connecting":
case "connected":
this._setConnectionState(state);
break;
case "failed":
case "closed":
this._setConnectionState("disconnected");
break;
}
}).disposer(this._disposer);
}
_setConnectionState(state) {
if (this._connectionState === state) {
return;
}
this._log.debug(
"onConnectionStateChanged",
this.id,
this._connectionState,
state
);
this._connectionState = state;
this.onConnectionStateChanged.emit(state);
}
_setupTransportAccessForStream(stream) {
stream._getTransport = () => ({
rtcPeerConnection: this.pc,
connectionState: convertConnectionState(this.pc.connectionState)
});
stream._getStats = () => __async(this, null, function* () {
if (stream.contentType === "data") {
const stats2 = yield this.pc.getStats();
const arr2 = statsToArray(stats2);
return arr2;
}
const stats = yield this.pc.getStats(stream.track);
const arr = statsToArray(stats);
return arr;
});
this._disposer.push(() => {
stream._getTransport = () => void 0;
});
this.onConnectionStateChanged.add((state) => {
stream._setConnectionState(state);
if (this.localPerson._analytics && !this.localPerson._analytics.isClosed()) {
void this.localPerson._analytics.client.sendRtcPeerConnectionEventReport(
{
rtcPeerConnectionId: this.rtcPeerConnectionId,
type: "skywayConnectionStateChange",
data: {
skywayConnectionState: state
},
createdAt: Date.now()
}
);
}
}).disposer(this._disposer);
}
_getCodecFromSdp(sdpObject, transceiver, kind) {
var _a2, _b2;
const media = sdpObject.media.find(
// sdpTransformのmidは実際はnumber
(m) => {
var _a3, _b3;
return ((_a3 = m.mid) == null ? void 0 : _a3.toString()) === ((_b3 = transceiver.mid) == null ? void 0 : _b3.toString());
}
);
if (!media) {
throw createError({
operationName: "Receiver._getCodecFromSdp",
info: __spreadProps(__spreadValues({}, errors.notFound), {
detail: "m-line not exist"
}),
path: log33.prefix,
context: this._context,
channel: this.localPerson.channel
});
}
const codecPT = (_b2 = (_a2 = media.payloads) == null ? void 0 : _a2.toString()) == null ? void 0 : _b2.split(" ")[0];
const rtp = media.rtp.find((r2) => r2.payload.toString() === codecPT);
const mimeType = `${kind}/${rtp.codec}`.toLowerCase();
let parameters = {};
const fmtp = media.fmtp.find((f) => f.payload.toString() === codecPT);
if (fmtp == null ? void 0 : fmtp.config) {
parameters = fmtpConfigParser(fmtp.config);
}
const codec = { mimeType, parameters };
return codec;
}
get hasMedia() {
const count = Object.values(this.streams).length;
this._log.debug("hasMedia", { count });
if (count > 0) {
return true;
}
return false;
}
close() {
this._log.debug("closed");
this.unSetPeerConnectionListener();
this.pc.close();
this._setConnectionState("disconnected");
this._disposer.dispose();
}
add(subscription) {
this._subscriptions[subscription.id] = subscription;
}
remove(subscriptionId) {
const subscription = this._subscriptions[subscriptionId];
if (!subscription) return;
delete this._subscriptions[subscription.id];
const publicationId = subscription.publication.id;
const stream = this.streams[publicationId];
if (!stream) return;
delete this.streams[publicationId];
}
/**@throws {SkyWayError} */
_validateRemoteOffer(sdp) {
const sdpObject = sdpTransform2.parse(sdp);
this._log.debug("_validateRemoteOffer", { sdpObject });
for (const sdpMediaLine of sdpObject.media) {
if (sdpMediaLine.direction === "inactive") {
continue;
}
const exist = Object.values(this._publicationInfo).find(
(info) => {
var _a2;
return ((_a2 = sdpMediaLine.mid) == null ? void 0 : _a2.toString()) === info.mid;
}
);
if (!exist) {
const error = createError({
operationName: "Receiver._validateRemoteOffer",
info: __spreadProps(__spreadValues({}, errors.notFound), {
detail: "mismatch between sdp and state"
}),
path: log33.prefix,
context: this._context,
channel: this.localPerson.channel,
payload: {
sdpMedia: sdpObject.media,
sdpMediaLine,
info: this._publicationInfo
}
});
this.onError.emit(error);
throw error;
}
}
}
get isWrongSignalingState() {
return this.pc.signalingState === "have-local-offer" && this.pc.remoteDescription || this.pc.signalingState === "have-remote-offer";
}
/**@throws {SkyWayError} */
_handleSenderProduce(_0) {
return __async(this, arguments, function* ({
sdp,
publicationId,
info
}) {
if (this.pc.signalingState === "closed") {
return;
}
if (this.pc.signalingState !== "stable") {
if (this.isWrongSignalingState) {
this._log.warn(
"_handleSenderProduce wait for be stable",
createWarnPayload({
operationName: "Receiver._handleSenderProduce",
channel: this.localPerson.channel,
detail: "_handleSenderProduce wait for be stable",
payload: { signalingState: this.pc.signalingState }
})
);
yield this.waitForSignalingState("stable");
yield this._handleSenderProduce({
sdp,
publicationId,
info
});
return;
}
throw createError({
operationName: "Receiver._handleSenderProduce",
context: this._context,
channel: this.localPerson.channel,
info: __spreadProps(__spreadValues({}, errors.internal), { detail: "wrong signalingState" }),
payload: { signalingState: this.pc.signalingState },
path: log33.prefix
});
}
this._log.debug("_handleSenderProduce", {
info,
publicationId,
publicationInfo: Object.values(this._publicationInfo)
});
this._publicationInfo[info.publicationId] = info;
this._validateRemoteOffer(sdp.sdp);
yield this.sendAnswer(sdp);
yield this.resolveCandidates();
});
}
/**@throws {SkyWayError} */
_handleSenderUnproduce(_0) {
return __async(this, arguments, function* ({
sdp,
publicationId
}) {
if (this.pc.signalingState === "closed") {
this._log.warn(
"signalingState closed",
createWarnPayload({
channel: this.localPerson.channel,
detail: "signalingState closed",
operationName: "Receiver._handleSenderUnproduce"
})
);
return;
}
this._log.debug("<handleSenderUnproduce> start", { sdp, publicationId });
if (this.pc.signalingState !== "stable") {
if (this.isWrongSignalingState) {
this._log.warn(
"signalingState is not stable",
createWarnPayload({
channel: this.localPerson.channel,
detail: "signalingState is not stable",
operationName: "Receiver._handleSenderUnproduce",
payload: { signalingState: this.pc.signalingState }
})
);
yield this.waitForSignalingState("stable");
yield this._handleSenderUnproduce({
sdp,
publicationId
});
return;
}
throw createError({
operationName: "Receiver._handleSenderProduce",
context: this._context,
channel: this.localPerson.channel,
info: __spreadProps(__spreadValues({}, errors.internal), { detail: "wrong signalingState" }),
payload: { signalingState: this.pc.signalingState },
path: log33.prefix
});
}
delete this._publicationInfo[publicationId];
yield this.sendAnswer(sdp);
yield this.resolveCandidates();
this._log.debug("<handleSenderUnproduce> end", { publicationId });
});
}
/**@throws {SkyWayError} */
_handleSenderRestartIce(_0) {
return __async(this, arguments, function* ({
sdp
}) {
if (this.pc.signalingState === "closed") {
return;
}
if (this.pc.signalingState !== "stable") {
if (this.isWrongSignalingState) {
this._log.warn(
"signalingState is not stable",
createWarnPayload({
channel: this.localPerson.channel,
detail: "signalingState is not stable",
operationName: "Receiver._handleSenderRestartIce",
payload: { signalingState: this.pc.signalingState }
})
);
yield this.waitForSignalingState("stable");
yield this._handleSenderRestartIce({ sdp });
return;
}
throw createError({
operationName: "Receiver._handleSenderRestartIce",
context: this._context,
channel: this.localPerson.channel,
info: __spreadProps(__spreadValues({}, errors.internal), { detail: "wrong signalingState" }),
payload: { signalingState: this.pc.signalingState },
path: log33.prefix
});
}
this._setConnectionState("reconnecting");
yield this.sendAnswer(sdp);
yield this.resolveCandidates();
if (this.pc.connectionState === "connected") {
this._setConnectionState("connected");
}
});
}
sendAnswer(sdp) {
return __async(this, null, function* () {
this._log.debug(`[receiver] start: sendAnswer`);
yield this.pc.setRemoteDescription(sdp);
const answer = yield this.pc.createAnswer();
if (this.localPerson._analytics && !this.localPerson._analytics.isClosed()) {
void this.localPerson._analytics.client.sendRtcPeerConnectionEventReport({
rtcPeerConnectionId: this.rtcPeerConnectionId,
type: "answer",
data: {
answer: JSON.stringify(answer)
},
createdAt: Date.now()
});
}
const offerObject = sdpTransform2.parse(this.pc.remoteDescription.sdp);
const answerObject = sdpTransform2.parse(answer.sdp);
offerObject.media.forEach((offerMedia, i) => {
const answerMedia = answerObject.media[i];
answerMedia.fmtp = deepCopy(answerMedia.fmtp).map((answerFmtp) => {
const offerFmtp = offerMedia.fmtp.find(
(f) => f.payload === answerFmtp.payload
);
if (offerFmtp) {
return offerFmtp;
}
return answerFmtp;
});
});
const munged = sdpTransform2.write(answerObject);
yield this.pc.setLocalDescription({ type: "answer", sdp: munged });
const message = {
kind: "receiverAnswerMessage",
payload: { sdp: this.pc.localDescription }
};
yield this.signaling.send(this.endpoint, message).catch(
(e2) => this._log.error("failed to send answer", e2, {
localPersonId: this.localPerson.id,
endpointId: this.endpoint.id
})
);
this._log.debug(`[receiver] end: sendAnswer`);
});
}
get subscriptions() {
return this._subscriptions;
}
};
// ../core/src/plugin/internal/person/connection/sender.ts
init_process();
var import_isEqual = __toESM(require_isEqual());
var sdpTransform3 = __toESM(require_lib());
var log34 = new Logger(
"packages/core/src/plugin/internal/person/connection/sender.ts"
);
var Sender = class extends Peer {
constructor(context, iceManager, signaling, analytics, localPerson, endpoint) {
super(
context,
iceManager,
signaling,
analytics,
localPerson,
endpoint,
"sender"
);
this.id = v4_default();
this.onConnectionStateChanged = new Event();
this.publications = {};
this.transceivers = {};
this.datachannels = {};
this._pendingPublications = [];
this._isNegotiating = false;
this.promiseQueue = new PromiseQueue();
this._disposer = new EventDisposer();
this._ms = new MediaStream();
this._backoffIceRestarted = new BackOff({
times: 8,
interval: 100,
jitter: 100
});
this._connectionState = "new";
this._log = log34.createBlock({
localPersonId: this.localPerson.id,
id: this.id
});
this._unsubscribeStreamEnableChange = {};
this._cleanupStreamCallbacks = {};
this._sendDataQueue = new PromiseQueue();
/**@throws */
this.restartIce = () => __async(this, null, function* () {
if (this._backoffIceRestarted.exceeded) {
this._log.error(
createError({
operationName: "Sender.restartIce",
context: this._context,
channel: this.localPerson.channel,
info: __spreadProps(__spreadValues({}, errors.internal), { detail: "restartIce limit exceeded" }),
path: log34.prefix
})
);
this._setConnectionState("disconnected");
return;
}
this._log.warn(
"[start] restartIce",
createWarnPayload({
operationName: "Sender.restartIce",
detail: "start restartIce",
channel: this.localPerson.channel,
payload: { count: this._backoffIceRestarted.count }
})
);
const checkNeedEnd = () => {
if (this.endpoint.state === "left") {
this._log.warn(
"endpointMemberLeft",
createWarnPayload({
operationName: "restartIce",
detail: "endpointMemberLeft",
channel: this.localPerson.channel,
payload: { endpointId: this.endpoint.id }
})
);
this._setConnectionState("disconnected");
return true;
}
if (this.pc.connectionState === "connected") {
this._log.warn(
"[end] restartIce",
createWarnPayload({
operationName: "restartIce",
detail: "reconnected",
channel: this.localPerson.channel,
payload: { count: this._backoffIceRestarted.count }
})
);
this._backoffIceRestarted.reset();
this._setConnectionState("connected");
if (this.localPerson._analytics && !this.localPerson._analytics.isClosed()) {
void this.localPerson._analytics.client.sendRtcPeerConnectionEventReport(
{
rtcPeerConnectionId: this.id,
type: "restartIce",
data: void 0,
createdAt: Date.now()
}
);
}
return true;
}
};
this._setConnectionState("reconnecting");
yield this._backoffIceRestarted.wait();
if (checkNeedEnd()) return;
let e2 = yield this._iceManager.updateIceParams().catch((e3) => e3);
if (e2) {
this._log.warn(
"[failed] restartIce",
createWarnPayload({
operationName: "restartIce",
detail: "update IceParams failed",
channel: this.localPerson.channel,
payload: { count: this._backoffIceRestarted.count }
}),
e2
);
yield this.restartIce();
return;
}
if (this.pc.setConfiguration) {
this.pc.setConfiguration(__spreadProps(__spreadValues({}, this.pc.getConfiguration()), {
iceServers: this._iceManager.iceServers
}));
this._log.debug("<restartIce> setConfiguration", {
iceServers: this._iceManager.iceServers
});
}
if (checkNeedEnd()) return;
if (this.signaling.connectionState !== "connected") {
this._log.warn(
"<restartIce> reconnect signaling service",
createWarnPayload({
operationName: "restartIce",
detail: "reconnect signaling service",
channel: this.localPerson.channel,
payload: { count: this._backoffIceRestarted.count }
})
);
e2 = yield this.signaling.onConnectionStateChanged.watch((s) => s === "connected", 1e4).catch((e3) => e3).then(() => {
});
if (e2 instanceof SkyWayError) {
yield this.restartIce();
return;
}
if (checkNeedEnd()) return;
}
const offer = yield this.pc.createOffer({ iceRestart: true });
if (this.localPerson._analytics && !this.localPerson._analytics.isClosed()) {
void this.localPerson._analytics.client.sendRtcPeerConnectionEventReport({
rtcPeerConnectionId: this.rtcPeerConnectionId,
type: "offer",
data: {
offer: JSON.stringify(offer)
},
createdAt: Date.now()
});
}
yield this.pc.setLocalDescription(offer);
const message = {
kind: "senderRestartIceMessage",
payload: { sdp: this.pc.localDescription }
};
e2 = yield this.signaling.send(this.endpoint, message, 1e4).catch((e3) => e3);
if (e2) {
this._log.warn(
"<restartIce> [failed]",
createWarnPayload({
operationName: "restartIce",
detail: "timeout send signaling message",
channel: this.localPerson.channel,
payload: { count: this._backoffIceRestarted.count }
}),
e2
);
yield this.restartIce();
return;
}
e2 = yield this.waitForConnectionState(
"connected",
this._context.config.rtcConfig.iceDisconnectBufferTimeout
).catch((e3) => e3);
if (!e2) {
if (checkNeedEnd()) return;
}
yield this.restartIce();
});
this._log.debug("spawned");
this._endpoint = endpoint;
this.signaling.onMessage.add((_0) => __async(this, [_0], function* ({ src, data }) {
if (!(src.id === endpoint.id && src.name === endpoint.name)) return;
const message = data;
switch (message.kind) {
case "receiverAnswerMessage":
{
this.promiseQueue.push(() => this._handleReceiverAnswer(message.payload)).catch(
(err) => this._log.error("handle receiverAnswerMessage", {
localPersonId: this.localPerson.id,
endpointId: this.endpoint.id,
err
})
);
}
break;
case "iceCandidateMessage":
{
const { role, candidate } = message.payload;
if (role === "receiver") {
yield this.handleCandidate(candidate);
}
}
break;
}
})).disposer(this._disposer);
this.onPeerConnectionStateChanged.add((state) => __async(this, null, function* () {
try {
log34.debug("onPeerConnectionStateChanged", { state });
switch (state) {
case "disconnected":
case "failed":
{
const e2 = yield this.waitForConnectionState(
"connected",
context.config.rtcConfig.iceDisconnectBufferTimeout
).catch((e3) => e3);
if (e2 && this._connectionState !== "reconnecting") {
yield this.restartIce();
}
}
break;
case "connecting":
case "connected":
this._setConnectionState(state);
break;
case "closed":
this._setConnectionState("disconnected");
break;
}
} catch (error) {
log34.error("onPeerConnectionStateChanged", error, this.id);
}
})).disposer(this._disposer);
}
_setConnectionState(state) {
if (this._connectionState === state) {
return;
}
this._log.debug(
"onConnectionStateChanged",
this.id,
this._connectionState,
state
);
this._connectionState = state;
this.onConnectionStateChanged.emit(state);
}
get hasMedia() {
const count = Object.keys(this.publications).length;
this._log.debug("hasMedia", { count });
if (count > 0) {
return true;
}
return false;
}
_getMid(publication, sdpObject) {
if (publication.contentType === "data") {
const media = sdpObject.media.find((m) => m.type === "application");
if ((media == null ? void 0 : media.mid) === void 0) {
throw createError({
operationName: "Sender._getMid",
info: __spreadProps(__spreadValues({}, errors.missingProperty), {
detail: "datachannel mid undefined"
}),
path: log34.prefix,
context: this._context,
channel: this.localPerson.channel
});
}
return media.mid.toString();
} else {
const transceiver = this.transceivers[publication.id];
const mid = transceiver.mid;
if (mid === null) {
throw createError({
operationName: "Sender._getMid",
info: __spreadProps(__spreadValues({}, errors.missingProperty), {
detail: "media mid undefined"
}),
path: log34.prefix,
context: this._context,
channel: this.localPerson.channel
});
}
return mid.toString();
}
}
_listenStreamEnableChange(stream, publicationId) {
if (this._unsubscribeStreamEnableChange[publicationId]) {
this._unsubscribeStreamEnableChange[publicationId]();
}
const { removeListener } = stream._onEnableChanged.add((track) => __async(this, null, function* () {
yield this._replaceTrack(publicationId, track).catch((e2) => {
log34.warn(
createWarnPayload({
member: this.localPerson,
detail: "_replaceTrack failed",
operationName: "Sender._listenStreamEnableChange",
payload: e2
})
);
});
}));
this._unsubscribeStreamEnableChange[publicationId] = removeListener;
}
/**@throws {@link SkyWayError} */
add(publication) {
return __async(this, null, function* () {
var _a2, _b2;
if (this._isNegotiating || this.pc.signalingState !== "stable") {
this._pendingPublications.push(publication);
this._log.debug("<add> isNegotiating", {
publication,
isNegotiating: this._isNegotiating,
signalingState: this.pc.signalingState,
pendingPublications: this._pendingPublications.length
});
return;
}
this._isNegotiating = true;
this._log.debug("<add> add publication", { publication });
this.publications[publication.id] = publication;
const stream = publication.stream;
if (!stream) {
throw createError({
operationName: "Sender.add",
info: __spreadProps(__spreadValues({}, errors.missingProperty), {
detail: "<add> stream not found"
}),
path: log34.prefix,
context: this._context,
channel: this.localPerson.channel
});
}
this._cleanupStreamCallbacks[stream.id] = this._setupTransportAccessForStream(stream);
if (stream.contentType === "data") {
const dc = this.pc.createDataChannel(
new DataChannelNegotiationLabel(publication.id, stream.id).toLabel(),
stream.options
);
const dataStreamSubscriber = {
id: this._endpoint.id,
name: this._endpoint.name
};
dc.onopen = () => {
stream.onWritable.emit(dataStreamSubscriber);
};
dc.onclose = () => {
stream.onUnwritable.emit(dataStreamSubscriber);
};
dc.onerror = (err) => {
if ("error" in err && err.error.errorDetail.includes("data-channel")) {
this._log.error(
"datachannel.send failed",
createError({
operationName: "RTCDataChannel.onerror",
info: errors.dataChannelSendError,
path: log34.prefix,
context: this._context,
channel: this.localPerson.channel
})
);
} else {
this._log.error(
"datachannel operation failed",
createError({
operationName: "RTCDataChannel.onerror",
info: errors.dataChannelGeneralError,
path: log34.prefix,
context: this._context,
channel: this.localPerson.channel
})
);
}
};
dc.bufferedAmountLowThreshold = 65536;
let waitForBufferedAmountLowResolve;
let waitForBufferedAmountLow = new Promise((resolve) => {
waitForBufferedAmountLowResolve = resolve;
});
dc.onbufferedamountlow = () => {
waitForBufferedAmountLowResolve();
};
stream._onWriteData.add((data) => __async(this, null, function* () {
if (dc.readyState === "open") {
yield this._sendDataQueue.push(() => __async(this, null, function* () {
if (dc.bufferedAmount > dc.bufferedAmountLowThreshold) {
yield waitForBufferedAmountLow;
waitForBufferedAmountLow = new Promise((resolve) => {
waitForBufferedAmountLowResolve = resolve;
});
}
dc.send(data);
}));
} else {
this._log.error(
"datachannel.send failed",
createError({
operationName: "RTCDataChannel.onerror",
info: errors.dataChannelSendError,
path: log34.prefix,
context: this._context,
channel: this.localPerson.channel
})
);
}
})).disposer(this._disposer);
this.datachannels[publication.id] = dc;
} else {
publication._onReplaceStream.add((_0) => __async(this, [_0], function* ({ newStream, oldStream }) {
newStream._replacingTrack = true;
this._listenStreamEnableChange(
newStream,
publication.id
);
if (this._cleanupStreamCallbacks[oldStream.id]) {
this._cleanupStreamCallbacks[oldStream.id]();
}
this._cleanupStreamCallbacks[newStream.id] = this._setupTransportAccessForStream(newStream);
yield this._replaceTrack(publication.id, newStream.track);
newStream._replacingTrack = false;
newStream._onReplacingTrackDone.emit();
})).disposer(this._disposer);
this._listenStreamEnableChange(stream, publication.id);
const transceiver = this.pc.addTransceiver(stream.track, {
direction: "sendonly",
streams: [this._ms]
});
publication._onEncodingsChanged.add((encodings) => __async(this, null, function* () {
yield setEncodingParams(transceiver.sender, encodings).catch((e2) => {
this._log.error("_onEncodingsChanged failed", e2);
});
})).disposer(this._disposer);
this.transceivers[publication.id] = transceiver;
}
const offer = yield this.pc.createOffer().catch((err) => {
throw createError({
operationName: "Sender.add",
info: __spreadProps(__spreadValues({}, errors.internal), {
detail: "can't create offer"
}),
path: log34.prefix,
context: this._context,
channel: this.localPerson.channel,
error: err
});
});
if (this.localPerson._analytics && !this.localPerson._analytics.isClosed()) {
void this.localPerson._analytics.client.sendRtcPeerConnectionEventReport({
rtcPeerConnectionId: this.rtcPeerConnectionId,
type: "offer",
data: {
offer: JSON.stringify(offer)
},
createdAt: Date.now()
});
}
yield this.pc.setLocalDescription(offer);
const sdpObject = sdpTransform3.parse(this.pc.localDescription.sdp);
this._log.debug("<add> create offer base", sdpObject);
const mid = this._getMid(publication, sdpObject);
if (publication.contentType !== "data") {
applyCodecCapabilities(
(_a2 = publication.codecCapabilities) != null ? _a2 : [],
mid,
sdpObject
);
const offerSdp = sdpTransform3.write(sdpObject);
yield this.pc.setLocalDescription({ type: "offer", sdp: offerSdp });
this._log.debug("<add> create offer", this.pc.localDescription);
if (((_b2 = publication.encodings) == null ? void 0 : _b2.length) > 0) {
if (isSafari()) {
this._safariSetupEncoding(
publication
);
} else {
const transceiver = this.transceivers[publication.id];
yield setEncodingParams(transceiver.sender, [
publication.encodings[0]
]);
}
}
}
const message = {
kind: "senderProduceMessage",
payload: {
sdp: this.pc.localDescription,
publicationId: publication.id,
info: {
publicationId: publication.id,
streamId: stream.id,
mid
}
}
};
this._log.debug("[start] send message", message);
yield this.signaling.send(this.endpoint, message).catch((error) => {
this._log.error("[failed] send message :", error, {
localPersonId: this.localPerson.id,
endpointId: this.endpoint.id
});
throw error;
});
this._log.debug("[end] send message", message);
});
}
_setupTransportAccessForStream(stream) {
stream._getTransportCallbacks[this.endpoint.id] = () => ({
rtcPeerConnection: this.pc,
connectionState: this._connectionState
});
stream._getStatsCallbacks[this.endpoint.id] = () => __async(this, null, function* () {
if (stream.contentType === "data") {
const stats2 = yield this.pc.getStats();
const arr2 = statsToArray(stats2);
return arr2;
}
if (stream._replacingTrack) {
yield stream._onReplacingTrackDone.asPromise(200);
}
const stats = yield this.pc.getStats(stream.track);
const arr = statsToArray(stats);
return arr;
});
const cleanupCallbacks = () => {
delete stream._getTransportCallbacks[this.endpoint.id];
delete stream._getStatsCallbacks[this.endpoint.id];
};
this._disposer.push(() => {
cleanupCallbacks();
});
this.onConnectionStateChanged.add((state) => {
stream._setConnectionState(this.endpoint, state);
if (this.localPerson._analytics && !this.localPerson._analytics.isClosed()) {
void this.localPerson._analytics.client.sendRtcPeerConnectionEventReport(
{
rtcPeerConnectionId: this.rtcPeerConnectionId,
type: "skywayConnectionStateChange",
data: {
skywayConnectionState: state
},
createdAt: Date.now()
}
);
}
}).disposer(this._disposer);
return cleanupCallbacks;
}
/**@throws {SkyWayError} */
remove(publicationId) {
return __async(this, null, function* () {
const publication = this.publications[publicationId];
if (!publication) {
this._log.warn(
"<remove> publication not found",
createWarnPayload({
operationName: "Sender.remove",
detail: "publication already removed",
channel: this.localPerson.channel,
payload: { publicationId }
})
);
return;
}
delete this.publications[publicationId];
if (this._isNegotiating || this.pc.signalingState !== "stable") {
this._pendingPublications.push(publicationId);
this._log.debug("<remove> isNegotiating", {
publicationId,
_isNegotiating: this._isNegotiating,
signalingState: this.pc.signalingState
});
return;
}
this._isNegotiating = true;
this._log.debug("<remove> [start]", { publicationId });
const stream = publication.stream;
if (!stream) {
throw createError({
operationName: "Sender.remove",
info: __spreadProps(__spreadValues({}, errors.missingProperty), {
detail: "<remove> publication not have stream"
}),
path: log34.prefix,
context: this._context,
channel: this.localPerson.channel,
payload: { publication }
});
}
if (stream.contentType === "data") {
const dc = this.datachannels[publicationId];
dc.close();
delete this.datachannels[publicationId];
} else {
const transceiver = this.transceivers[publicationId];
transceiver.stop();
delete this.transceivers[publicationId];
}
const offer = yield this.pc.createOffer().catch((err) => {
throw createError({
operationName: "Sender.remove",
info: __spreadProps(__spreadValues({}, errors.internal), {
detail: "<remove> can't create offer"
}),
path: log34.prefix,
context: this._context,
channel: this.localPerson.channel,
error: err
});
});
if (this.localPerson._analytics && !this.localPerson._analytics.isClosed()) {
void this.localPerson._analytics.client.sendRtcPeerConnectionEventReport({
rtcPeerConnectionId: this.rtcPeerConnectionId,
type: "offer",
data: {
offer: JSON.stringify(offer)
},
createdAt: Date.now()
});
}
yield this.pc.setLocalDescription(offer);
const message = {
kind: "senderUnproduceMessage",
payload: { sdp: this.pc.localDescription, publicationId }
};
this._log.debug("<remove> send message", { message });
yield this.signaling.send(this.endpoint, message).catch((error) => {
this._log.error("<remove> in remote error :", error, {
localPersonId: this.localPerson.id,
endpointId: this.endpoint.id
});
throw error;
});
this._log.debug("<remove> [end]", { publicationId });
});
}
_replaceTrack(publicationId, track) {
return __async(this, null, function* () {
const transceiver = this.transceivers[publicationId];
if (!transceiver) {
this._log.warn(
"can't replace track, transceiver not found",
createWarnPayload({
operationName: "Sender._replaceTrack",
detail: "transceiver already removed",
channel: this.localPerson.channel,
payload: { publicationId }
})
);
return;
}
yield transceiver.sender.replaceTrack(track).catch((e2) => {
throw createError({
operationName: "Sender._replaceTrack",
context: this._context,
info: errors.internal,
error: e2,
path: log34.prefix,
channel: this.localPerson.channel
});
});
});
}
_handleReceiverAnswer(_0) {
return __async(this, arguments, function* ({
sdp
}) {
if (this.pc.signalingState === "closed") {
return;
}
this._log.debug("<handleReceiverAnswer> [start]");
yield this.pc.setRemoteDescription(new RTCSessionDescription(sdp)).catch((err) => {
const error = createError({
operationName: "Sender._handleReceiverAnswer",
context: this._context,
info: __spreadProps(__spreadValues({}, errors.internal), {
detail: "failed to setRemoteDescription"
}),
path: log34.prefix,
payload: { sdp },
channel: this.localPerson.channel,
error: err
});
this._log.error(error);
throw error;
});
this._log.debug("<handleReceiverAnswer> sRD");
yield this.resolveCandidates();
this._log.debug("<handleReceiverAnswer> resolveCandidates");
yield this.waitForSignalingState("stable");
this._log.debug("<handleReceiverAnswer> waitForSignalingState");
this._isNegotiating = false;
yield this._resolvePendingSender();
this._log.debug(
"<handleReceiverAnswer> _resolvePendingSender",
this._pendingPublications.length
);
this._log.debug("<handleReceiverAnswer> [end]");
});
}
_safariSetupEncoding(publication) {
const transceiver = this.transceivers[publication.id];
const stream = publication.stream;
this.waitForStats({
track: stream.track,
cb: (stats) => {
const outbound = stats.find(
(s) => s.id.includes("RTCOutboundRTP") || s.type.includes("outbound-rtp")
);
if ((outbound == null ? void 0 : outbound.keyFramesEncoded) > 0) return true;
return false;
},
interval: 10,
timeout: this._context.config.rtcConfig.timeout
}).then(() => {
log34.debug("safari wait for stats resolved, setEncodingParams");
setEncodingParams(transceiver.sender, [publication.encodings[0]]).catch(
(e2) => {
this._log.error("setEncodingParams failed", e2);
}
);
}).catch((e2) => {
this._log.error("waitForStats", e2);
});
}
/**@throws {@link SkyWayError} */
_resolvePendingSender() {
return __async(this, null, function* () {
const publication = this._pendingPublications.shift();
if (!publication) return;
this._log.debug("resolve pending sender", { publication });
if (typeof publication === "string") {
yield this.remove(publication);
} else {
yield this.add(publication);
}
});
}
close() {
this._log.debug("closed");
this.unSetPeerConnectionListener();
Object.values(this._unsubscribeStreamEnableChange).forEach((f) => {
f();
});
this.pc.close();
this._setConnectionState("disconnected");
this._disposer.dispose();
}
};
function applyCodecCapabilities(codecCapabilities, mid, sdpObject) {
var _a2, _b2;
const media = sdpObject.media.find((m) => {
var _a3;
return ((_a3 = m.mid) == null ? void 0 : _a3.toString()) === mid;
});
if (!media) {
throw createError({
operationName: "applyCodecCapabilities",
info: __spreadProps(__spreadValues({}, errors.notFound), {
detail: "media not found"
}),
path: log34.prefix
});
}
codecCapabilities.forEach((cap) => {
var _a3;
if (cap.parameters) {
for (const [key, value] of Object.entries((_a3 = cap.parameters) != null ? _a3 : {})) {
if (value === false || !cap.parameters[key]) {
return;
}
if (key === "usedtx" && value) {
cap.parameters[key] = 1;
}
}
}
});
const findCodecFromCodecCapability = (cap, rtp, fmtp) => {
var _a3;
const rtpList = rtp.map((r2) => __spreadProps(__spreadValues({}, r2), {
parameters: getParameters(fmtp, r2.payload)
}));
const codecName = mimeTypeToCodec(cap.mimeType);
if (!codecName) {
return void 0;
}
const matched = (_a3 = rtpList.find((r2) => {
var _a4, _b3;
if (r2.codec.toLowerCase() !== codecName.toLowerCase()) {
return false;
}
if (Object.keys((_a4 = cap.parameters) != null ? _a4 : {}).length === 0) {
return true;
}
if (mimeTypeToContentType(cap.mimeType) === "audio") {
return true;
}
return (0, import_isEqual.default)(r2.parameters, (_b3 = cap.parameters) != null ? _b3 : {});
})) != null ? _a3 : void 0;
return matched;
};
const preferredCodecs = codecCapabilities.map((cap) => findCodecFromCodecCapability(cap, media.rtp, media.fmtp)).filter((v) => v !== void 0);
const sorted = [
...preferredCodecs,
...media.rtp.filter(
(rtp) => !preferredCodecs.find((p) => p.payload === rtp.payload)
)
];
for (const fmtp of media.fmtp) {
const payloadType = fmtp.payload;
const targetCodecWithPayload = sorted.find(
(c) => c.payload === payloadType
);
if (targetCodecWithPayload) {
const targetCodecCapability = codecCapabilities.find(
(c) => findCodecFromCodecCapability(c, [targetCodecWithPayload], media.fmtp)
);
if (targetCodecCapability) {
if (targetCodecCapability.parameters && Object.keys(targetCodecCapability.parameters).length > 0) {
fmtp.config = "";
Object.entries(targetCodecCapability.parameters).forEach(
([key, value]) => {
if (value === false || fmtp.config.includes(key)) {
return;
}
if (fmtp.config.length > 0) {
fmtp.config += `;${key}=${value}`;
} else {
fmtp.config = `${key}=${value}`;
}
}
);
}
}
}
const opus = sorted.find((rtp) => rtp.codec.toLowerCase() === "opus");
const opusDtx = (_b2 = (_a2 = codecCapabilities.find(
(f) => mimeTypeToCodec(f.mimeType).toLowerCase() === "opus"
)) == null ? void 0 : _a2.parameters) == null ? void 0 : _b2.usedtx;
if (opus && opusDtx !== false && fmtp.payload === opus.payload && !fmtp.config.includes("usedtx")) {
if (fmtp.config.length > 0) {
fmtp.config += ";usedtx=1";
} else {
fmtp.config = "usedtx=1";
}
}
}
media.payloads = sorted.map((rtp) => rtp.payload.toString()).join(" ");
}
var mimeTypeToCodec = (mimeType) => mimeType.split("/")[1];
var mimeTypeToContentType = (mimeType) => mimeType.split("/")[0];
// ../core/src/plugin/internal/person/connection/index.ts
var log35 = new Logger(
"packages/core/src/plugin/internal/person/connection/index.ts"
);
var P2PConnection = class {
/**@internal */
constructor(_iceManager, _signaling, _analytics, _context, channelId, localPerson, remoteMember) {
this._iceManager = _iceManager;
this._signaling = _signaling;
this._analytics = _analytics;
this._context = _context;
this.channelId = channelId;
this.localPerson = localPerson;
this.remoteMember = remoteMember;
this.id = v4_default();
this.type = "p2p";
this.onDisconnect = new Event();
this.onClose = new Event();
this.closed = false;
this.disconnected = false;
this._log = log35.createBlock({
id: this.id,
localPersonId: this.localPerson.id
});
this._pubsubQueue = new PromiseQueue();
this.sendSubscriptionStatsReportTimers = /* @__PURE__ */ new Map();
this._waitingSendSubscriptionStatsReportsFromPublish = /* @__PURE__ */ new Map();
this._waitingSendSubscriptionStatsReportsFromSubscribe = [];
this.sender = new Sender(
this._context,
this._iceManager,
this._signaling,
this._analytics,
this.localPerson,
this.remoteMember
);
this.receiver = new Receiver(
this._context,
this._iceManager,
this._signaling,
this._analytics,
this.localPerson,
this.remoteMember
);
this.sender.onDisconnect.once(() => {
this.disconnected = true;
this.onDisconnect.emit();
});
this.receiver.onDisconnect.once(() => {
this.disconnected = true;
this.onDisconnect.emit();
});
if (this._analytics) {
this._analytics.onConnectionStateChanged.add((state) => {
if (state !== "connected") return;
if (this._waitingSendSubscriptionStatsReportsFromPublish.size > 0) {
for (const [subscriptionId, publicationId] of this._waitingSendSubscriptionStatsReportsFromPublish) {
const publication = this.sender.publications[publicationId];
if (publication) {
this.startSendSubscriptionStatsReportTimer(
publication,
subscriptionId
);
}
}
this._waitingSendSubscriptionStatsReportsFromPublish.clear();
}
if (this._waitingSendSubscriptionStatsReportsFromSubscribe.length > 0) {
for (const subscriptionId of this._waitingSendSubscriptionStatsReportsFromSubscribe) {
const subscription = this.receiver.subscriptions[subscriptionId];
if (subscription) {
this.startSendSubscriptionStatsReportTimer(
subscription,
subscriptionId
);
}
}
this._waitingSendSubscriptionStatsReportsFromSubscribe = [];
}
});
}
}
/**
* @internal
* @throws {SkyWayError}
*/
startPublishing(publication, subscriptionId) {
return __async(this, null, function* () {
yield this._pubsubQueue.push(() => __async(this, null, function* () {
this._log.debug("startPublishing", { publication });
yield this.sender.add(publication);
}));
if (this._analytics && !this._analytics.isClosed()) {
void this._analytics.client.sendBindingRtcPeerConnectionToSubscription({
subscriptionId,
role: "sender",
rtcPeerConnectionId: this.sender.rtcPeerConnectionId
});
if (this._analytics.client.isConnectionEstablished()) {
this.startSendSubscriptionStatsReportTimer(publication, subscriptionId);
} else {
this._waitingSendSubscriptionStatsReportsFromPublish.set(
subscriptionId,
publication.id
);
}
}
});
}
/**@internal */
stopPublishing(publication) {
return __async(this, null, function* () {
yield this._pubsubQueue.push(() => __async(this, null, function* () {
this._log.debug("<stopPublishing> start", { publication });
this.sender.remove(publication.id).then(() => {
this._log.debug("<stopPublishing> removed", { publication });
}).catch((e2) => {
this._log.error("<stopPublishing> remove failed", e2, { publication });
});
this._closeIfNeeded();
this._log.debug("<stopPublishing> end", { publication });
}));
const sendSubscriptionStatsReportTimer = this.sendSubscriptionStatsReportTimers.get(publication.id);
if (sendSubscriptionStatsReportTimer) {
clearInterval(sendSubscriptionStatsReportTimer);
this.sendSubscriptionStatsReportTimers.delete(publication.id);
}
});
}
/**@internal */
startSubscribing(subscription) {
return __async(this, null, function* () {
yield this._pubsubQueue.push(() => __async(this, null, function* () {
this._log.debug("startSubscribing", { subscription });
this.receiver.add(subscription);
const publicationId = subscription.publication.id;
let stream = this.receiver.streams[publicationId];
if (!stream) {
yield this.receiver.onStreamAdded.watch(
(res) => res.publicationId === publicationId,
this._context.config.rtcConfig.timeout
).catch(() => {
throw createError({
operationName: "P2PConnection.startSubscribing",
info: __spreadProps(__spreadValues({}, errors.timeout), { detail: "onStreamAdded" }),
path: log35.prefix,
context: this._context,
channel: this.localPerson.channel,
payload: { subscription }
});
});
stream = this.receiver.streams[publicationId];
}
stream.setIsEnabled(subscription.publication.state === "enabled");
subscription.codec = stream.codec;
subscription._setStream(stream);
if (this._analytics && !this._analytics.isClosed()) {
void this._analytics.client.sendBindingRtcPeerConnectionToSubscription({
subscriptionId: subscription.id,
role: "receiver",
rtcPeerConnectionId: this.receiver.rtcPeerConnectionId
});
if (this._analytics.client.isConnectionEstablished()) {
this.startSendSubscriptionStatsReportTimer(
subscription,
subscription.id
);
} else {
this._waitingSendSubscriptionStatsReportsFromSubscribe.push(
subscription.id
);
}
}
}));
});
}
/**@internal */
stopSubscribing(subscription) {
return __async(this, null, function* () {
yield this._pubsubQueue.push(() => __async(this, null, function* () {
this._log.debug("stopSubscribing", { subscription });
this.receiver.remove(subscription.id);
this._closeIfNeeded();
}));
const sendSubscriptionStatsReportTimer = this.sendSubscriptionStatsReportTimers.get(subscription.id);
if (sendSubscriptionStatsReportTimer) {
clearInterval(sendSubscriptionStatsReportTimer);
this.sendSubscriptionStatsReportTimers.delete(subscription.id);
}
});
}
_closeIfNeeded() {
if (this.sender.hasMedia || this.receiver.hasMedia) return;
this.close({ reason: "no media" });
}
getStats(content) {
return __async(this, null, function* () {
const stream = content.stream;
if (!stream) {
throw createError({
operationName: "P2PConnection.getStats",
info: __spreadProps(__spreadValues({}, errors.invalidArgumentValue), {
detail: "Subscription or Publication must has stream"
}),
path: log35.prefix,
context: this._context,
channel: this.localPerson.channel
});
}
if (stream.side === "local") {
if (stream.contentType === "data") {
return this.sender.pc.getStats();
}
return this.sender.pc.getStats(stream.track);
} else {
if (stream.contentType === "data") {
return this.receiver.pc.getStats();
}
return this.receiver.pc.getStats(stream.track);
}
});
}
/**@internal */
close({ reason } = {}) {
if (this.closed) {
return;
}
this.closed = true;
this._log.debug("closed", {
endpointId: this.remoteMember.id,
reason,
sender: this.sender.id,
receiver: this.receiver.id,
id: this.id
});
this.sender.close();
this.receiver.close();
for (const timer of this.sendSubscriptionStatsReportTimers.values()) {
clearInterval(timer);
}
this.sendSubscriptionStatsReportTimers.clear();
this._waitingSendSubscriptionStatsReportsFromPublish.clear();
this._waitingSendSubscriptionStatsReportsFromSubscribe = [];
this.onClose.emit();
}
startSendSubscriptionStatsReportTimer(stream, subscriptionId) {
if (this._analytics) {
const role = stream instanceof PublicationImpl ? "sender" : "receiver";
const intervalSec = this._analytics.client.getIntervalSec();
this.sendSubscriptionStatsReportTimers.set(
stream.id,
setInterval(() => __async(this, null, function* () {
if (!this._analytics) {
throw createError({
operationName: "P2PConnection.sendSubscriptionStatsReportTimer",
info: __spreadProps(__spreadValues({}, errors.missingProperty), {
detail: "AnalyticsSession not exist"
}),
path: log35.prefix,
context: this._context,
channel: this.localPerson.channel
});
}
if (this._analytics.isClosed()) {
const subscriptionStatsReportTimer = this.sendSubscriptionStatsReportTimers.get(stream.id);
if (subscriptionStatsReportTimer) {
clearInterval(subscriptionStatsReportTimer);
this.sendSubscriptionStatsReportTimers.delete(stream.id);
}
return;
}
const stats = yield this.getStats(stream);
if (stats) {
void this._analytics.client.sendSubscriptionStatsReport(stats, {
subscriptionId,
role,
contentType: stream.contentType,
createdAt: Date.now()
});
}
}), intervalSec * 1e3)
);
}
}
};
// ../core/src/plugin/internal/person/member.ts
var log36 = new Logger("packages/core/src/plugin/internal/person/member.ts");
var RemotePersonImpl = class extends MemberImpl {
constructor(args) {
super(args);
this.args = args;
this.type = "person";
this.subtype = "person";
this.side = "remote";
this._connections = {};
this._context = this.args.channel._context;
this._disposer = new EventDisposer();
this.onPublicationSubscribed = this._events.make();
this.onPublicationUnsubscribed = this._events.make();
this.onPublicationListChanged = this._events.make();
this.onSubscriptionListChanged = this._events.make();
this.subscribe = (publicationId) => new Promise((r2, f) => {
let failed = false;
this.channel._subscribe(this.id, publicationId).catch((e2) => {
failed = true;
f(e2);
});
this.onPublicationSubscribed.watch(
({ subscription }) => subscription.publication.id === publicationId,
this._context.config.rtcApi.timeout
).then(({ subscription }) => {
r2({ subscription });
}).catch(() => {
if (!failed) {
f(
createError({
operationName: "RemotePersonImpl.subscribe",
info: __spreadProps(__spreadValues({}, errors.timeout), {
detail: "onPublicationSubscribed"
}),
path: log36.prefix,
context: this._context,
channel: this.channel
})
);
}
});
});
this.plugin = args.plugin;
this.channel.onPublicationUnsubscribed.add(({ subscription }) => {
if (subscription.subscriber.id === this.id) {
this.onPublicationUnsubscribed.emit({ subscription });
this.onSubscriptionListChanged.emit();
}
}).disposer(this._disposer);
this.channel.onPublicationSubscribed.add(({ subscription }) => {
if (subscription.subscriber.id === this.id) {
this.onPublicationSubscribed.emit({ subscription });
this.onSubscriptionListChanged.emit();
}
}).disposer(this._disposer);
this.channel.onStreamPublished.add(({ publication }) => {
if (publication.publisher.id === this.id) {
this.onPublicationListChanged.emit();
}
}).disposer(this._disposer);
this.channel.onStreamUnpublished.add(({ publication }) => {
if (publication.publisher.id === this.id) {
this.onPublicationListChanged.emit();
}
}).disposer(this._disposer);
this.onLeft.once(() => {
log36.debug("RemotePerson left: ", this.toJSON());
Object.values(this._connections).forEach((connection) => {
connection.close({ reason: "remote person left" });
});
this._connections = {};
});
}
/**@private */
_getConnection(localPersonId) {
return this._connections[localPersonId];
}
/**@private */
_getOrCreateConnection(localPerson) {
var _a2;
const connection = (_a2 = this._getConnection(localPerson.id)) != null ? _a2 : this._createConnection(this.channel, localPerson, this);
return connection;
}
_createConnection(channel, localPerson, endpointMember) {
if (localPerson.side !== "local") {
throw createError({
operationName: "RemotePersonImpl._createConnection",
info: __spreadProps(__spreadValues({}, errors.invalidArgumentValue), {
detail: "wrong localPerson type"
}),
path: log36.prefix,
context: this._context,
channel: this.channel
});
}
if (!localPerson._signaling) {
throw createError({
operationName: "RemotePersonImpl._createConnection",
info: __spreadProps(__spreadValues({}, errors.missingProperty), {
detail: "signalingSession not exist"
}),
path: log36.prefix,
context: this._context,
channel: this.channel
});
}
const connection = new P2PConnection(
localPerson.iceManager,
localPerson._signaling,
localPerson._analytics,
this._context,
channel.id,
localPerson,
endpointMember
);
this.plugin._messageBuffers[localPerson.id].resolveMessagingBuffer(
endpointMember
);
connection.onClose.once(() => {
log36.debug("connection closed", this.toJSON(), {
connectionId: connection.id
});
delete this._connections[localPerson.id];
});
this._connections[localPerson.id] = connection;
return connection;
}
unsubscribe(subscriptionId) {
return __async(this, null, function* () {
yield this.channel._unsubscribe(subscriptionId);
});
}
_dispose() {
this._disposer.dispose();
}
};
// ../core/src/plugin/internal/person/plugin.ts
var PersonPlugin = class extends SkyWayPlugin {
constructor() {
super(...arguments);
this.subtype = "person";
this._messageBuffers = {};
this._whenCreateLocalPerson = (person) => __async(this, null, function* () {
if (person._signaling) {
this._messageBuffers[person.id] = new MessageBuffer(person._signaling);
}
});
this._whenDisposeLocalPerson = (person) => __async(this, null, function* () {
const messageBuffer = this._messageBuffers[person.id];
if (messageBuffer) {
messageBuffer.close();
delete this._messageBuffers[person.id];
}
});
this._createRemoteMember = (channel, memberDto) => {
const person = new RemotePersonImpl(__spreadProps(__spreadValues({}, this._context), {
context: this._context,
channel,
metadata: memberDto.metadata,
id: memberDto.id,
name: memberDto.name,
plugin: this
}));
return person;
};
}
};
var registerPersonPlugin = (context) => {
const plugin = new PersonPlugin();
context.registerPlugin(plugin);
return plugin;
};
// ../core/src/plugin/internal/unknown/plugin.ts
init_process();
var UnknownPlugin = class extends SkyWayPlugin {
constructor() {
super(...arguments);
this.subtype = "unknown";
this._createRemoteMember = (channel, memberDto) => {
const person = new UnknownMemberImpl(__spreadProps(__spreadValues({}, this._context), {
context: this._context,
channel,
metadata: memberDto.metadata,
id: memberDto.id,
name: memberDto.name,
plugin: this,
subtype: memberDto.subtype
}));
return person;
};
}
};
// ../core/src/version.ts
init_process();
var PACKAGE_VERSION2 = "2.2.1";
// ../core/src/context.ts
var log37 = new Logger("packages/core/src/context.ts");
var _SkyWayContext = class _SkyWayContext {
/**@private */
constructor(api, config, authToken, info) {
this.config = config;
this.authToken = authToken;
this.info = info;
this.disposed = false;
/**@internal */
this.plugins = [];
this._unknownPlugin = new UnknownPlugin();
/**seconds */
this._remindSec = this.config.token.updateRemindSec;
this._events = new Events();
/**
* @description [japanese] トークンの期限がまもなく切れることを通知するイベント
* @example
* context.onTokenUpdateReminder.add(() => {
context.updateAuthToken(tokenString);
});
*/
this.onTokenUpdateReminder = this._events.make();
/**
* @description [japanese] トークンの期限切れを通知するイベント。このイベントが発火された場合、トークンを更新するまでサービスを利用できない
*/
this.onTokenExpired = this._events.make();
/**
* @description [japanese] 回復不能なエラーが発生したことを通知するイベント。インターネット接続状況を確認した上で別のインスタンスを作り直す必要がある
*/
this.onFatalError = this._events.make();
/**@private @deprecated */
this._onTokenUpdated = this._events.make();
/**@private @deprecated */
this._onDisposed = this._events.make();
/**@description [japanese] トークンが更新されたことを通知するイベント */
this.onTokenUpdated = this._events.make();
/**@description [japanese] コンテキストが破棄されたことを通知するイベント */
this.onDisposed = this._events.make();
this._authTokenString = authToken.tokenString;
this.appId = this.authToken.getAppId();
registerPersonPlugin(this);
this._api = api;
this._api.onFatalError.once((error) => {
log37.error("onFatalError", { appId: this.appId, error });
this.onFatalError.emit(
createError({
operationName: "SkyWayContext._api.onFatalError",
context: this,
info: errors.rtcApiFatalError,
error,
path: log37.prefix
})
);
this.dispose();
});
}
/**
* @description [japanese] Contextの作成
*/
static Create(_0) {
return __async(this, arguments, function* (authTokenString, configOptions = {}) {
const config = new ContextConfig(configOptions);
Logger.level = config.log.level;
Logger.format = config.log.format;
const token = SkyWayAuthToken.Decode(authTokenString);
const { osName, osVersion, browserName, browserVersion } = getRuntimeInfo();
const runtime = {
sdkName: "core",
sdkVersion: _SkyWayContext.version,
osName,
osVersion,
browserName,
browserVersion
};
const endpoint = {
rapi: config.rtcApi.domain,
signaling: config.signalingService.domain,
ice: config.iceParamServer.domain
};
log37.info("core sdk spawned", {
operationName: "SkyWayContext.Create",
runtime,
endpoint,
config,
token
});
try {
const appId = token.getAppId();
const api = yield RtcApiClient.Create({
appId,
token: authTokenString,
log: config.log,
rtcApi: config.rtcApi
});
const context = new _SkyWayContext(api, config, token, {
endpoint,
runtime
});
yield context._setTokenExpireTimer();
if (token.getAnalyticsEnabled()) {
context.analyticsSession = yield setupAnalyticsSession(context);
}
return context;
} catch (error) {
throw createError({
operationName: "SkyWayContext.Create",
info: errors.connectRtcApiFailed,
error,
path: log37.prefix
});
}
});
}
/**@description [japanese] トークンのエンコード済み文字列 */
get authTokenString() {
return this._authTokenString;
}
/**@internal */
_setTokenExpireTimer() {
return __async(this, null, function* () {
const now = yield this._api.getServerUnixtimeInSec();
const expiresInSec = this.authToken.exp - now;
if (expiresInSec < 0) {
throw createError({
operationName: "SkyWayContext._setTokenExpireTimer",
context: this,
info: errors.invalidExpireTokenValue,
path: log37.prefix,
payload: { exp: this.authToken.exp, now }
});
}
if (this._tokenUpdateRemindTimer) {
clearTimeout(this._tokenUpdateRemindTimer);
}
const tokenExpireRemindTimeSec = expiresInSec - this._remindSec;
if (tokenExpireRemindTimeSec < 0) {
throw createError({
operationName: "SkyWayContext._setTokenExpireTimer",
context: this,
info: errors.invalidRemindExpireTokenValue,
path: log37.prefix,
payload: { expiresInSec, remindSec: this._remindSec }
});
}
log37.debug("_setTokenExpireTimer", {
expiresInSec,
tokenExpireReminderTimeSec: tokenExpireRemindTimeSec
});
this._tokenUpdateRemindTimer = setTimeout(() => {
log37.debug("tokenUpdateReminder", { appid: this.appId });
this.onTokenUpdateReminder.emit();
}, tokenExpireRemindTimeSec * 1e3);
if (this._tokenExpiredTimer) {
clearTimeout(this._tokenExpiredTimer);
}
this._tokenExpiredTimer = setTimeout(() => {
log37.debug("tokenExpired", { appid: this.appId });
this.onTokenExpired.emit();
}, expiresInSec * 1e3);
});
}
/**
* @description [japanese] トークンの更新
*/
updateAuthToken(token) {
return __async(this, null, function* () {
const newToken = SkyWayAuthToken.Decode(token);
const newAppId = newToken.getAppId();
log37.info(
{ operationName: "SkyWayContext.updateAuthToken" },
{ oldToken: this.authToken, newToken }
);
if (newAppId !== this.appId) {
throw createError({
operationName: "SkyWayContext.updateAuthToken",
context: this,
info: errors.invalidTokenAppId,
path: log37.prefix,
payload: { invalid: newAppId, expect: this.appId }
});
}
this._authTokenString = token;
this.authToken = newToken;
this._onTokenUpdated.emit(token);
this.onTokenUpdated.emit(token);
yield this._setTokenExpireTimer();
yield this._api.updateAuthToken(token).catch((e2) => {
var _a2;
log37.warn("[failed] SkyWayContext.updateAuthToken", { detail: e2 });
if (e2 instanceof SkyWayError && ((_a2 = e2.info) == null ? void 0 : _a2.name) === "projectUsageLimitExceeded") {
this.dispose();
clearTimeout(this._tokenExpiredTimer);
}
throw e2;
});
});
}
/**
* @description [japanese] プラグインの登録
*/
registerPlugin(plugin) {
if (this.plugins.find((p) => p.subtype === plugin.subtype)) {
return;
}
plugin._attachContext(this);
this.plugins.push(plugin);
}
/**@private */
_createRemoteMember(channel, memberDto) {
log37.debug("createRemoteMember", { memberDto });
memberDto.type = memberDto.type.toLowerCase();
memberDto.subtype = memberDto.subtype.toLowerCase();
let plugin = this.plugins.find((p) => p.subtype === memberDto.subtype);
if (!plugin) {
plugin = this._unknownPlugin;
}
const member = plugin._createRemoteMember(channel, memberDto);
return member;
}
/**
* @description [japanese] Contextの利用を終了し次のリソースを解放する
* - イベントリスナー
* - バックエンドサーバとの通信
* - コンテキストを参照する全Channelインスタンス
*/
dispose() {
if (this.disposed) {
return;
}
this.disposed = true;
log37.debug("disposed", { appid: this.appId });
clearTimeout(this._tokenUpdateRemindTimer);
this._onDisposed.emit();
this.onDisposed.emit();
this._events.dispose();
this._api.close();
Logger._onLogForAnalytics = () => {
};
}
};
/**@internal */
_SkyWayContext.version = PACKAGE_VERSION2;
/**@internal */
_SkyWayContext.id = v4_default();
var SkyWayContext = _SkyWayContext;
// ../core/src/media/index.ts
init_process();
// ../core/src/media/factory.ts
init_process();
var log38 = new Logger("packages/core/src/media/factory.ts");
var StreamFactory = class {
/**@private */
constructor() {
/**
* @description [japanese] 一度参照した種類のデバイスの状態が変化した時に発火するイベント
*/
this.onDeviceChange = new Event();
this._devices = [];
if (!(navigator == null ? void 0 : navigator.mediaDevices)) {
throw createError({
operationName: "StreamFactory.constructor",
info: errors.mediaDevicesNotFound,
path: log38.prefix
});
}
navigator.mediaDevices.addEventListener("devicechange", () => __async(this, null, function* () {
const devices = yield this._enumerateDevicesArray();
const removed = [];
this._devices.forEach((prev) => {
if (!devices.map((d) => d.id).includes(prev.id)) {
removed.push(prev);
}
});
const added = [];
devices.map((d) => d.id).forEach((next) => {
if (!this._devices.map((d) => d.id).includes(next)) {
added.push(devices.find((d) => d.id === next));
}
});
log38.debug("device changed", { added, removed });
removed.forEach((device) => {
this.onDeviceChange.emit({ state: "removed", device });
});
added.forEach((device) => {
this.onDeviceChange.emit({ state: "added", device });
});
this._devices = devices;
}));
}
_enumerateDevicesArray() {
return __async(this, null, function* () {
const devices = yield navigator.mediaDevices.enumerateDevices();
return devices.map((d) => new MediaDevice(d)).filter((d) => d.id.length > 0);
});
}
_enumerateDevicesWithAuth() {
return __async(this, arguments, function* ({ video, audio } = {
audio: true,
video: true
}) {
let tracks = [];
if (video || audio) {
const stream = yield navigator.mediaDevices.getUserMedia({
video,
audio
});
tracks = stream.getTracks();
}
this._devices = yield this._enumerateDevicesArray();
tracks.forEach((t2) => {
t2.stop();
});
return this._devices;
});
}
/**
* @description [japanese] デバイスの一覧を取得する
*/
enumerateDevices() {
return __async(this, null, function* () {
const devices = yield this._enumerateDevicesWithAuth();
return devices;
});
}
/**
* @description [japanese] 映像入力デバイスの一覧を取得する
*/
enumerateInputVideoDevices() {
return __async(this, null, function* () {
const devices = yield this._enumerateDevicesWithAuth({ video: true });
return devices.filter((d) => d.kind === "videoinput");
});
}
/**
* @description [japanese] 音声入力デバイスの一覧を取得する
*/
enumerateInputAudioDevices() {
return __async(this, null, function* () {
const devices = yield this._enumerateDevicesWithAuth({ audio: true });
return devices.filter((d) => d.kind === "audioinput");
});
}
/**
* @description [japanese] 音声出力デバイスの一覧を取得する
*/
enumerateOutputAudioDevices() {
return __async(this, null, function* () {
const devices = yield this._enumerateDevicesWithAuth({ audio: true });
return devices.filter((d) => d.kind === "audiooutput");
});
}
/**
* @description [japanese] CameraのVideoStreamを作成する
*/
createCameraVideoStream() {
return __async(this, arguments, function* (options = {}) {
var _a2;
options.stopTrackWhenDisabled = (_a2 = options.stopTrackWhenDisabled) != null ? _a2 : true;
const [track] = (yield navigator.mediaDevices.getUserMedia({ video: options })).getTracks();
const stream = new LocalVideoStream(track, options);
stream._setLabel("camera");
return stream;
});
}
/**
* @description [japanese] マイクのAudioStreamを作成する
*/
createMicrophoneAudioStream() {
return __async(this, arguments, function* (options = {}) {
var _a2;
options.stopTrackWhenDisabled = (_a2 = options.stopTrackWhenDisabled) != null ? _a2 : true;
const [track] = (yield navigator.mediaDevices.getUserMedia({ audio: options })).getTracks();
const stream = new LocalAudioStream(track, options);
stream._setLabel("microphone");
return stream;
});
}
/**
* @description [japanese]
* PCブラウザでのみ利用可能なAPI。
* VideoStreamは常に取得される(AudioStreamのみ取得することはできない)
* audioオプションを有効にするとAudioStreamを取得することができる。
* audioオプションはWindowsのChromeにしか対応しておらず、
* それ以外の環境では有効にしても戻り値のaudioにはundefinedが返される。
*/
createDisplayStreams() {
return __async(this, arguments, function* (options = {}) {
var _a2, _b2, _c;
const videoOption = (_a2 = options.video) != null ? _a2 : {};
(_b2 = videoOption.stopTrackWhenDisabled) != null ? _b2 : videoOption.stopTrackWhenDisabled = true;
let audioOption = options.audio;
if (audioOption) {
audioOption = typeof audioOption === "boolean" ? {} : audioOption;
(_c = audioOption.stopTrackWhenDisabled) != null ? _c : audioOption.stopTrackWhenDisabled = true;
}
options = { audio: audioOption, video: videoOption };
const stream = yield navigator.mediaDevices.getDisplayMedia(options);
const [video] = stream.getVideoTracks();
const [audio] = stream.getAudioTracks();
if (options.audio && !audio) {
log38.warn(
createWarnPayload({
operationName: "StreamFactory.createDisplayStreams",
detail: "This client does not support device audio capture"
})
);
}
const videoStream = new LocalVideoStream(video, __spreadProps(__spreadValues({}, videoOption), {
isDisplayMedia: true
}));
videoStream._setLabel("displayVideo");
const audioStream = audio ? new LocalAudioStream(audio, __spreadProps(__spreadValues({}, audioOption), {
isDisplayMedia: true
})) : void 0;
if (audioStream) {
audioStream._setLabel("displayAudio");
}
return {
video: videoStream,
audio: audioStream
};
});
}
/**
* @description [japanese] DataStreamを作成する
*/
createDataStream() {
return __async(this, arguments, function* (options = {}) {
return new LocalDataStream(options);
});
}
/**
* @description [japanese] CameraのVideoStreamとマイクのAudioStreamを作成する
*/
createMicrophoneAudioAndCameraStream() {
return __async(this, arguments, function* ({
audio,
video
} = {}) {
var _a2, _b2;
const stream = yield navigator.mediaDevices.getUserMedia({
audio: audio != null ? audio : true,
video: video != null ? video : true
});
const [audioTrack] = stream.getAudioTracks();
const [videoTrack] = stream.getVideoTracks();
audio = audio != null ? audio : {};
audio.stopTrackWhenDisabled = (_a2 = audio.stopTrackWhenDisabled) != null ? _a2 : true;
const audioStream = new LocalAudioStream(audioTrack, audio);
audioStream._setLabel("microphone");
video = video != null ? video : {};
video.stopTrackWhenDisabled = (_b2 = video.stopTrackWhenDisabled) != null ? _b2 : true;
const videoStream = new LocalVideoStream(videoTrack, video);
videoStream._setLabel("camera");
return {
audio: audioStream,
video: videoStream
};
});
}
/**
* @description [japanese] CustomVideoStreamを作成する
*/
createCustomVideoStream(_0) {
return __async(this, arguments, function* (processor, options = {}) {
var _a2, _b2;
options.stopTrackWhenDisabled = (_a2 = options.stopTrackWhenDisabled) != null ? _a2 : true;
const stream = new LocalCustomVideoStream(options);
const processedStream = yield processor.createProcessedStream({
constraints: (_b2 = options.constraints) != null ? _b2 : {},
stopTrackWhenDisabled: options.stopTrackWhenDisabled,
onUpdateTrack: (track) => {
return stream.updateTrack(track);
}
});
yield stream.setStream(processedStream);
return stream;
});
}
};
var SkyWayStreamFactory = new StreamFactory();
var MediaDevice = class {
/**@private */
constructor(info) {
this.id = info.deviceId;
this.label = info.label;
this.kind = info.kind;
}
};
// ../core/src/media/stream/index.ts
init_process();
// ../core/src/media/stream/remote/index.ts
init_process();
// ../core/src/member/person.ts
init_process();
// ../core/src/plugin/interface/connection.ts
init_process();
// src/errors.ts
init_process();
// ../sfu-api-client/src/index.ts
init_process();
// ../sfu-api-client/src/api.ts
init_process();
// ../sfu-api-client/src/const.ts
init_process();
var defaultSFUApiOptions = {
domain: "sfu.skyway.ntt.com",
secure: true,
version: 4
};
// ../sfu-api-client/src/errors.ts
init_process();
var errors4 = {
invalidParameter: { name: "invalidParameter", detail: "", solution: "" },
invalidRequestParameter: {
name: "invalidRequestParameter",
detail: "\u30EA\u30AF\u30A8\u30B9\u30C8\u306E\u5024\u304C\u4E0D\u6B63\u3067\u3059",
solution: "\u6B63\u3057\u3044\u5024\u3092\u5165\u529B\u3057\u3066\u304F\u3060\u3055\u3044"
},
notFound: {
name: "notFound",
detail: "\u5BFE\u8C61\u306E\u30EA\u30BD\u30FC\u30B9\u304C\u898B\u3064\u304B\u308A\u307E\u305B\u3093",
solution: "\u5BFE\u8C61\u306E\u30EA\u30BD\u30FC\u30B9\u304C\u5B58\u5728\u3059\u308B\u304B\u78BA\u304B\u3081\u3066\u304F\u3060\u3055\u3044"
},
maxSubscriberExceededError: {
name: "maxSubscribersExceededError",
detail: "forwarding\u306EmaxSubscribers\u306E\u5236\u9650\u3092\u8D85\u3048\u3066\u3044\u307E\u3059\u3002maxSubscribers\u306E\u5024\u3092\u8D85\u3048\u3066Subscribe\u3059\u308B\u3053\u3068\u306F\u3067\u304D\u307E\u305B\u3093",
solution: "maxSubscribers\u306E\u7BC4\u56F2\u5185\u3067\u3054\u5229\u7528\u304F\u3060\u3055\u3044"
},
quotaExceededError: {
name: "quotaExceededError",
detail: "\u30EA\u30BD\u30FC\u30B9\u306E\u5236\u9650\u91CF\u3092\u8D85\u3048\u3066\u30EA\u30BD\u30FC\u30B9\u3092\u5229\u7528\u3059\u308B\u3053\u3068\u306F\u3067\u304D\u307E\u305B\u3093",
solution: "\u30EA\u30BD\u30FC\u30B9\u5236\u9650\u91CF\u306E\u7BC4\u56F2\u5185\u3067\u3054\u5229\u7528\u304F\u3060\u3055\u3044"
},
timeout: { name: "timeout", detail: "", solution: "" },
insufficientPermissions: {
name: "insufficientPermissions",
detail: "token\u306E\u6A29\u9650\u304C\u4E0D\u8DB3\u3057\u3066\u3044\u307E\u3059",
solution: "token\u306B\u5FC5\u8981\u306A\u6A29\u9650\u3092\u4ED8\u4E0E\u3057\u3066\u304F\u3060\u3055\u3044"
},
backendError: { name: "backendError:", detail: "", solution: "" },
notAllowedConsumeError: {
name: "notAllowedConsumeError",
detail: "Forwarding\u304B\u3089\u306EConsume\u8A31\u53EF\u304C\u3042\u308A\u307E\u305B\u3093",
solution: "Forwarding\u3057\u3066\u3044\u308Bmember\u306B\u3088\u308B\u8A31\u53EF\u64CD\u4F5C\u304C\u5FC5\u8981\u3067\u3059"
}
};
// ../sfu-api-client/src/util.ts
init_process();
function createError4({
operationName,
info,
error,
path,
payload
}) {
return new SkyWayError({
error,
info,
payload: { payload, operationName },
path
});
}
function createWarnPayload4({
appId,
detail,
channelId,
operationName,
payload,
memberId,
botId
}) {
const warn = {
operationName,
payload,
detail,
appId,
channelId,
memberId,
botId
};
return warn;
}
// ../sfu-api-client/src/api.ts
var log39 = new Logger("packages/sfu-api-client/src/api.ts");
var SFURestApiClient = class {
constructor(_token, _options) {
this._token = _token;
this._headers = { authorization: `Bearer ${this._token}` };
this.options = __spreadValues(__spreadValues({}, defaultSFUApiOptions), _options);
this.endpoint = `http${this.options.secure ? "s" : ""}://${this.options.domain}/v${this.options.version}`;
this.http = new HttpClient(this.endpoint);
Logger.level = this.options.log.level;
Logger.format = this.options.log.format;
log39.debug("SFURestApiClient spawned", { endpoint: this.endpoint });
}
updateToken(token) {
this._token = token;
}
_commonErrorHandler(e2, operationName) {
switch (e2 == null ? void 0 : e2.status) {
case 401:
return createError4({
operationName,
info: errors4.invalidRequestParameter,
path: log39.prefix,
payload: e2
});
case 403:
return createError4({
operationName,
info: errors4.insufficientPermissions,
path: log39.prefix,
payload: e2
});
case 404:
return createError4({
operationName,
info: errors4.notFound,
path: log39.prefix,
payload: e2
});
case 429:
return createError4({
operationName,
info: errors4.quotaExceededError,
path: log39.prefix,
payload: e2
});
default:
return createError4({
operationName,
info: errors4.backendError,
path: log39.prefix,
payload: e2
});
}
}
createBot(_0) {
return __async(this, arguments, function* ({
appId,
channelId
}) {
const res = yield this.http.post(
"/bots",
{
appId,
channelId
},
{ headers: { authorization: `Bearer ${this._token}` } }
).catch((e2) => {
throw this._commonErrorHandler(e2, "SFURestApiClient.createBot");
});
return res.id;
});
}
deleteBot(_0) {
return __async(this, arguments, function* ({ botId }) {
yield this.http.delete(`/bots/${botId}`, {
headers: { authorization: `Bearer ${this._token}` }
}).catch((e2) => {
throw this._commonErrorHandler(e2, "SFURestApiClient.deleteBot");
});
});
}
startForwarding(_0) {
return __async(this, arguments, function* ({
botId,
publicationId,
maxSubscribers,
contentType,
publisherId
}) {
const backOff = new BackOff();
const body = {
publicationId,
maxSubscribers,
contentType: contentType[0].toUpperCase() + contentType.slice(1),
publisherId
};
const res = yield this.http.post(`/bots/${botId}/forwardings`, body, {
headers: { authorization: `Bearer ${this._token}` },
retry: (err) => __async(this, null, function* () {
if ([400, 403, 429].includes(err.status)) {
return false;
}
return yield backOff.wait();
})
}).catch((e2) => {
throw this._commonErrorHandler(e2, "SFURestApiClient.startForwarding");
});
if (backOff.count > 0) {
log39.warn(
"success to retry startForwarding",
createWarnPayload4({
operationName: "SFURestApiClient.startForwarding",
detail: "success to retry startForwarding",
botId,
memberId: publisherId,
payload: { publicationId, count: backOff.count }
})
);
}
return res;
});
}
createProducer(_0) {
return __async(this, arguments, function* ({
botId,
forwardingId,
transportId,
producerOptions
}) {
const backOff = new BackOff();
const res = yield this.http.put(
`/bots/${botId}/forwardings/${forwardingId}/transports/producers`,
{ transportId, producerOptions },
{
headers: { authorization: `Bearer ${this._token}` },
retry: () => __async(this, null, function* () {
return yield backOff.wait();
})
}
).catch((e2) => {
throw this._commonErrorHandler(e2, "SFURestApiClient.createProducer");
});
if (backOff.count > 0) {
log39.warn(
"success to retry createProducer",
createWarnPayload4({
operationName: "SFURestApiClient.createProducer",
detail: "success to retry createProducer",
botId,
payload: { forwardingId, transportId, count: backOff.count }
})
);
}
return res;
});
}
/**@throws {maxSubscriberExceededError,} */
createConsumer(_0) {
return __async(this, arguments, function* ({
botId,
forwardingId,
rtpCapabilities,
subscriptionId,
subscriberId,
spatialLayer,
originPublicationId
}) {
const backOff = new BackOff({ times: 5, interval: 100 });
const requestPayload = {
rtpCapabilities,
subscriptionId,
subscriberId,
spatialLayer,
originPublicationId
};
const res = yield this.http.post(
`/bots/${botId}/forwardings/${forwardingId}/transports/consumers`,
requestPayload,
{
retry: (err) => __async(this, null, function* () {
if ([
400,
403,
// 404,
429
].includes(err.status)) {
return false;
}
return yield backOff.wait();
}),
headers: { authorization: `Bearer ${this._token}` }
}
).catch((e2) => {
if (e2.status === 429) {
throw createError4({
operationName: "SFURestApiClient.createConsumer",
info: errors4.maxSubscriberExceededError,
path: log39.prefix,
payload: e2
});
} else if (e2.status === 403) {
throw createError4({
operationName: "SFURestApiClient.createConsumer",
info: errors4.notAllowedConsumeError,
path: log39.prefix,
payload: e2
});
} else {
throw this._commonErrorHandler(e2, "SFURestApiClient.createConsumer");
}
});
if (backOff.count > 0) {
log39.warn(
"success to retry createConsumer",
createWarnPayload4({
operationName: "SFURestApiClient.createConsumer",
detail: "success to retry createConsumer",
botId,
payload: { forwardingId, count: backOff.count }
})
);
}
log39.debug("response of createConsumer", res);
return res;
});
}
connect(_0) {
return __async(this, arguments, function* ({
transportId,
dtlsParameters
}) {
const backOff = new BackOff();
const body = { transportId, dtlsParameters };
const res = yield this.http.put(`/transports/connections`, body, {
headers: { authorization: `Bearer ${this._token}` },
retry: () => __async(this, null, function* () {
return yield backOff.wait();
})
}).catch((e2) => {
throw this._commonErrorHandler(e2, "SFURestApiClient.connect");
});
if (backOff.count > 0) {
log39.warn(
"success to retry connect",
createWarnPayload4({
operationName: "SFURestApiClient.connect",
detail: "success to retry connect",
payload: { transportId, count: backOff.count }
})
);
}
return res;
});
}
changeConsumerLayer(_0) {
return __async(this, arguments, function* ({
transportId,
consumerId,
spatialLayer,
publicationId
}) {
const res = yield this.http.put(
`transports/consumers/${consumerId}/layers`,
{ transportId, spatialLayer, publicationId },
{
headers: { authorization: `Bearer ${this._token}` }
}
).catch((e2) => {
throw this._commonErrorHandler(
e2,
"SFURestApiClient.changeConsumerLayer"
);
});
return res;
});
}
stopForwarding({
botId,
forwardingId
}) {
let fulfilled = false;
const promise = this.http.delete(`/bots/${botId}/forwardings/${forwardingId}`, {
headers: { authorization: `Bearer ${this._token}` }
}).catch((e2) => {
throw this._commonErrorHandler(e2, "SFURestApiClient.stopForwarding");
}).then((res) => {
fulfilled = res;
});
return { promise, fulfilled };
}
iceRestart(_0) {
return __async(this, arguments, function* ({ transportId }) {
const res = yield this.http.put(
`/transports/connections/ice`,
{ transportId },
{ headers: this._headers }
).catch((e2) => {
throw this._commonErrorHandler(e2, "SFURestApiClient.iceRestart");
});
return res.iceParameters;
});
}
getRtpCapabilities(_0) {
return __async(this, arguments, function* ({
botId,
forwardingId,
originPublicationId
}) {
const backOff = new BackOff();
const res = yield this.http.get(
`/bots/${botId}/forwardings/${forwardingId}/transports/rtp-capabilities?originPublicationId=${originPublicationId}`,
{
headers: { authorization: `Bearer ${this._token}` },
retry: () => __async(this, null, function* () {
return yield backOff.wait();
})
}
).catch((e2) => {
throw this._commonErrorHandler(
e2,
"SFURestApiClient.getRtpCapabilities"
);
});
if (backOff.count > 0) {
log39.warn(
"getCapabilities to retry connect",
createWarnPayload4({
operationName: "SFURestApiClient.getRtpCapabilities",
detail: "getCapabilities to retry connect",
botId,
payload: { forwardingId, count: backOff.count }
})
);
}
return res.rtpCapabilities;
});
}
confirmSubscription(_0) {
return __async(this, arguments, function* ({
forwardingId,
subscriptionId,
identifierKey
}) {
const requestPayload = {
forwardingId,
subscriptionId,
identifierKey
};
const res = yield this.http.post("/confirm-subscription", requestPayload, {
headers: { authorization: `Bearer ${this._token}` }
}).catch((e2) => {
throw this._commonErrorHandler(
e2,
"SFURestApiClient.confirmSubscription"
);
});
log39.debug("response of confirmSubscription", res);
return res;
});
}
};
// src/errors.ts
var errors5 = __spreadProps(__spreadValues({}, errors4), {
invalidParameter: { name: "invalidParameter", detail: "", solution: "" },
timeout: { name: "timeout", detail: "", solution: "" },
internal: { name: "internal", detail: "", solution: "" },
sfuBotNotInChannel: {
name: "sfuBotNotInChannel",
detail: "SFUBot\u304CChannel\u306B\u5B58\u5728\u3057\u307E\u305B\u3093",
solution: "\u64CD\u4F5C\u3057\u3088\u3046\u3068\u3057\u3066\u3044\u308BSFUBot\u304C\u6B63\u3057\u3044\u304B\u78BA\u304B\u3081\u3066\u304F\u3060\u3055\u3044"
},
remotePublisherId: {
name: "remotePublisherId",
detail: "publisher\u304Cremote\u306EPublication\u3092Forwarding\u3059\u308B\u3053\u3068\u306F\u3067\u304D\u307E\u305B\u3093",
solution: "Publication\u304CLocal\u3067Publish\u3055\u308C\u305F\u3082\u306E\u304B\u78BA\u304B\u3081\u3066\u304F\u3060\u3055\u3044"
},
dataStreamNotSupported: {
name: "dataStreamNotSupported",
detail: "dataStream\u306FSFU\u306B\u5BFE\u5FDC\u3057\u3066\u3044\u307E\u305B\u3093",
solution: "\u3042\u308A\u307E\u305B\u3093"
},
streamNotExistInPublication: {
name: "streamNotExistInPublication",
detail: "Publication\u306BStream\u304C\u3042\u308A\u307E\u305B\u3093\u3002RemoteMember\u306EPublication\u306EStream\u306B\u306F\u30A2\u30AF\u30BB\u30B9\u3067\u304D\u307E\u305B\u3093",
solution: "\u53C2\u7167\u3057\u3066\u3044\u308BPublication\u304C\u76EE\u7684\u306E\u3082\u306E\u304B\u78BA\u304B\u3081\u3066\u304F\u3060\u3055\u3044\u3002"
},
invalidPreferredEncoding: {
name: "invalidPreferredEncoding",
detail: "preferredEncoding\u306E\u5024\u304C\u4E0D\u6B63\u3067\u3059\u3002\u30A8\u30F3\u30B3\u30FC\u30C9\u8A2D\u5B9A\u5207\u308A\u66FF\u3048\u6A5F\u80FD\u304C\u4F7F\u3048\u307E\u305B\u3093",
solution: "\u6B63\u3057\u3044\u6587\u5B57\u5217\u3092\u5165\u529B\u3057\u3066\u304F\u3060\u3055\u3044"
},
invalidEncodings: {
name: "invalidEncodings",
detail: "\u30A8\u30F3\u30B3\u30FC\u30C9\u8A2D\u5B9A\u304C\u8A2D\u5B9A\u3055\u308C\u3066\u3044\u307E\u305B\u3093\u3002\u30A8\u30F3\u30B3\u30FC\u30C9\u8A2D\u5B9A\u5207\u308A\u66FF\u3048\u6A5F\u80FD\u304C\u4F7F\u3048\u307E\u305B\u3093",
solution: "\u30A8\u30F3\u30B3\u30FC\u30C9\u8A2D\u5B9A\u5207\u308A\u66FF\u3048\u6A5F\u80FD\u3092\u5229\u7528\u3059\u308B\u5834\u5408\u306F\u30A8\u30F3\u30B3\u30FC\u30C9\u8A2D\u5B9A\u3092\u3057\u305FPublication\u3092Forwarding\u3057\u3066\u304F\u3060\u3055\u3044"
},
receiverNotFound: {
name: "receiverNotFound",
detail: "SFU\u306FRemoteMember\u306ESubscription\u3092\u64CD\u4F5C\u3067\u304D\u307E\u305B\u3093",
solution: "SFU\u3067subscription\u306E\u64CD\u4F5C\u3092\u3059\u308B\u969B\u306B\u306FLocalPerson\u304CSubscribe\u3057\u3066\u3044\u308BSubscription\u30A4\u30F3\u30B9\u30BF\u30F3\u30B9\u3092\u5229\u7528\u3057\u3066\u304F\u3060\u3055\u3044"
},
consumerNotFound: {
name: "consumerNotFound",
detail: "SFU\u306FLocalPerson\u304CUnsubscribe\u3057\u305FSubscription\u3092\u64CD\u51FA\u6765\u307E\u305B\u3093",
solution: "\u64CD\u4F5C\u5BFE\u8C61\u306ESubscription\u304C\u6B63\u3057\u3044\u304B\u78BA\u304B\u3081\u3066\u304F\u3060\u3055\u3044"
},
forwardingNotFound: {
name: "forwardingNotFound",
detail: "\u5B58\u5728\u3057\u306A\u3044Forwarding\u3092\u64CD\u4F5C\u3057\u3088\u3046\u3068\u3057\u3066\u3044\u307E\u3059",
solution: "\u5BFE\u8C61\u306EForwarding\u304C\u6B63\u3057\u3044\u304B\u78BA\u304B\u3081\u3066\u304F\u3060\u3055\u3044"
},
netWorkError: {
name: "netWorkError",
detail: "\u901A\u4FE1\u74B0\u5883\u306B\u554F\u984C\u304C\u3042\u308A\u307E\u3059",
solution: "\u30CD\u30C3\u30C8\u30EF\u30FC\u30AF\u63A5\u7D9A\u72B6\u6CC1\u3092\u78BA\u8A8D\u3057\u3066\u304F\u3060\u3055\u3044"
},
confirmSubscriptionFailed: {
name: "confirmSubscriptionFailed",
detail: "Forwarding\u306Econsume\u8A31\u53EF\u3092\u51FA\u3059\u306E\u306B\u5931\u6557\u3057\u307E\u3057\u305F",
solution: "\u3042\u308A\u307E\u305B\u3093"
}
});
// src/util.ts
init_process();
function getLayerFromEncodings(id, encodings) {
let layer = 0;
for (; layer < encodings.length; layer++) {
const encoding = encodings[layer];
if (encoding.id === id) {
break;
}
}
return layer;
}
function createWarnPayload5({
channel,
detail,
operationName,
payload,
bot
}) {
var _a2;
const warn = {
operationName,
payload,
detail
};
if (channel) {
warn.appId = channel.appId;
warn.channelId = channel.id;
if (channel.localPerson) {
warn.memberId = channel.localPerson.id;
}
}
if (bot) {
warn.botId = bot.id;
warn.appId = bot.channel.appId;
warn.channelId = bot.channel.id;
warn.memberId = (_a2 = bot.channel.localPerson) == null ? void 0 : _a2.id;
}
return warn;
}
// src/connection/receiver.ts
init_process();
var log40 = new Logger("packages/sfu-bot/src/connection/receiver.ts");
var Receiver2 = class {
constructor(subscription, _api, _transportRepository, _localPerson, _bot, _iceManager, _context) {
this.subscription = subscription;
this._api = _api;
this._transportRepository = _transportRepository;
this._localPerson = _localPerson;
this._bot = _bot;
this._iceManager = _iceManager;
this._context = _context;
this._disposer = new EventDisposer();
this.sendSubscriptionStatsReportTimer = null;
this._waitingSendSubscriptionStatsReports = [];
const analyticsSession = this._localPerson._analytics;
if (analyticsSession) {
analyticsSession.onConnectionStateChanged.add((state) => {
if (state === "connected" && this._waitingSendSubscriptionStatsReports.length > 0) {
for (const consumerId of this._waitingSendSubscriptionStatsReports) {
if (this.consumer && this.consumer.id === consumerId) {
this.startSendSubscriptionStatsReportTimer();
}
}
this._waitingSendSubscriptionStatsReports = [];
}
});
}
}
toJSON() {
return {
transport: this.transport,
subscription: this.subscription
};
}
/**@throws {maxSubscriberExceededError} */
consume() {
return __async(this, null, function* () {
var _a2, _b2;
let rtpCapabilities = this._transportRepository.rtpCapabilities;
if (!rtpCapabilities) {
log40.debug("[start] getCapabilities");
rtpCapabilities = yield this._api.getRtpCapabilities({
botId: this._bot.id,
forwardingId: this.subscription.publication.id,
originPublicationId: this.subscription.publication.origin.id
});
log40.debug("[end] getCapabilities");
yield this._transportRepository.loadDevice(rtpCapabilities).catch((e2) => {
throw createError({
operationName: "Receiver.consume",
context: this._context,
channel: this._localPerson.channel,
info: __spreadProps(__spreadValues({}, errors5.internal), { detail: "sfu loadDevice failed" }),
path: log40.prefix,
error: e2
});
});
}
const spatialLayer = this.subscription.preferredEncoding ? getLayerFromEncodings(
this.subscription.preferredEncoding,
(_b2 = (_a2 = this.subscription.publication.origin) == null ? void 0 : _a2.encodings) != null ? _b2 : []
) : void 0;
log40.debug("[start] createConsumer", { subscription: this.subscription });
const { consumerOptions, transportOptions, transportId, producerId } = yield this._api.createConsumer({
botId: this._bot.id,
forwardingId: this.subscription.publication.id,
rtpCapabilities,
subscriptionId: this.subscription.id,
subscriberId: this.subscription.subscriber.id,
spatialLayer,
originPublicationId: this.subscription.publication.origin.id
});
if (transportOptions) {
this._transportRepository.createTransport(
this._localPerson.id,
this._bot,
transportOptions,
"recv",
this._iceManager,
this._localPerson._analytics
);
}
this.transport = this._transportRepository.getTransport(
this._localPerson.id,
transportId
);
if (!this.transport) {
log40.warn("transport is under race condition", { transportId });
yield this._transportRepository.onTransportCreated.watch((id) => id === transportId, this._bot.options.endpointTimeout).catch((e2) => {
throw createError({
operationName: "Receiver.consume",
context: this._context,
channel: this._localPerson.channel,
info: __spreadProps(__spreadValues({}, errors5.timeout), {
detail: "receiver sfuTransport not found"
}),
path: log40.prefix,
error: e2,
payload: {
transportOptions,
transportId,
producerId,
consumerOptions,
subscription: this.subscription
}
});
});
this.transport = this._transportRepository.getTransport(
this._localPerson.id,
transportId
);
}
if (this._localPerson._analytics && !this._localPerson._analytics.isClosed()) {
void this._localPerson._analytics.client.sendBindingRtcPeerConnectionToSubscription(
{
subscriptionId: this.subscription.id,
role: "receiver",
rtcPeerConnectionId: this.transport.id
}
);
}
log40.debug("[end] createConsumer");
log40.debug("[start] consume", {
consumerOptions,
subscription: this.subscription
});
const consumer = yield this.transport.msTransport.consume(__spreadProps(__spreadValues({}, consumerOptions), {
producerId
})).catch((e2) => {
throw createError({
operationName: "Receiver.consume",
context: this._context,
channel: this._localPerson.channel,
info: __spreadProps(__spreadValues({}, errors5.internal), {
detail: "consume failed, maybe subscribing unsupported codec"
}),
path: log40.prefix,
error: e2
});
});
this.consumer = consumer;
log40.debug("[end] consume", { subscription: this.subscription });
const [selectedCodec] = consumer.rtpParameters.codecs;
const stream = createRemoteStream(uuidV4(), consumer.track, selectedCodec);
const codec = {
mimeType: selectedCodec.mimeType,
parameters: selectedCodec.parameters
};
this._setupTransportAccessForStream(stream, consumer);
const analyticsSession = this._localPerson._analytics;
if (analyticsSession && !analyticsSession.isClosed()) {
if (analyticsSession.client.isConnectionEstablished()) {
this.startSendSubscriptionStatsReportTimer();
} else {
this._waitingSendSubscriptionStatsReports.push(consumer.id);
}
}
return { stream, codec };
});
}
_setupTransportAccessForStream(stream, consumer) {
const transport = this.transport;
const pc = this.pc;
stream._getTransport = () => ({
rtcPeerConnection: pc,
connectionState: transport.connectionState,
info: this
});
stream._getStats = () => __async(this, null, function* () {
const stats = yield consumer.getStats();
let arr = statsToArray(stats);
arr = arr.map((stats2) => {
stats2.sfuTransportId = transport.id;
return stats2;
});
return arr;
});
this._disposer.push(() => {
stream._getTransport = () => void 0;
});
transport.onConnectionStateChanged.add((state) => {
log40.debug("transport connection state changed", transport.id, state);
stream._setConnectionState(state);
});
}
unconsume() {
if (!this.consumer) {
log40.debug("unconsume failed, consumer not exist", {
subscription: this.subscription
});
return;
}
this.consumer.close();
this.consumer = void 0;
if (this.sendSubscriptionStatsReportTimer) {
clearInterval(this.sendSubscriptionStatsReportTimer);
}
}
close() {
this._disposer.dispose();
}
get pc() {
var _a2;
return (_a2 = this.transport) == null ? void 0 : _a2.pc;
}
startSendSubscriptionStatsReportTimer() {
const analyticsSession = this._localPerson._analytics;
if (analyticsSession) {
const intervalSec = analyticsSession.client.getIntervalSec();
this.sendSubscriptionStatsReportTimer = setInterval(() => __async(this, null, function* () {
if (!analyticsSession || analyticsSession.isClosed()) {
if (this.sendSubscriptionStatsReportTimer) {
clearInterval(this.sendSubscriptionStatsReportTimer);
}
return;
}
if (this.consumer) {
const stats = yield this.consumer.getStats();
if (stats) {
void analyticsSession.client.sendSubscriptionStatsReport(stats, {
subscriptionId: this.subscription.id,
role: "receiver",
contentType: this.subscription.contentType,
createdAt: Date.now()
});
}
}
}), intervalSec * 1e3);
}
}
};
// src/connection/sender.ts
init_process();
var import_isEqual2 = __toESM(require_isEqual());
// src/forwarding.ts
init_process();
var log41 = new Logger("packages/sfu-bot/src/connection/sender.ts");
var Forwarding = class {
/**@internal */
constructor(props) {
this.props = props;
this.state = "started";
this.configure = this.props.configure;
this.originPublication = this.props.originPublication;
this.relayingPublication = this.props.relayingPublication;
this._identifierKey = this.props.identifierKey;
this._api = this.props.api;
this._context = this.props.context;
/** @description [japanese] forwardingが終了された時に発火するイベント */
this.onStopped = new Event();
this.relayingPublication.onSubscribed.add((e2) => __async(this, null, function* () {
yield this.confirmSubscription(e2.subscription).catch((e3) => e3);
}));
this.relayingPublication.subscriptions.forEach((subscription) => __async(this, null, function* () {
yield this.confirmSubscription(subscription).catch((e2) => e2);
}));
}
get id() {
return this.relayingPublication.id;
}
/**@private */
_stop() {
this.state = "stopped";
this.onStopped.emit();
}
/**@internal */
toJSON() {
return {
id: this.id,
configure: this.configure,
originPublication: this.originPublication,
relayingPublication: this.relayingPublication
};
}
/** @private */
confirmSubscription(subscription) {
return __async(this, null, function* () {
log41.debug("[start] Forwarding confirmSubscription");
const { message } = yield this._api.confirmSubscription({
forwardingId: this.id,
subscriptionId: subscription.id,
identifierKey: this._identifierKey
}).catch((error) => {
log41.error("Forwarding confirmSubscription failed:", error);
throw createError({
operationName: "Forwarding.confirmSubscription",
context: this._context,
info: errors5.confirmSubscriptionFailed,
path: log41.prefix,
payload: error
});
});
log41.debug("[end] Forwarding confirmSubscription", { message });
});
}
};
// src/connection/sender.ts
var log42 = new Logger("packages/sfu-bot/src/connection/sender.ts");
var Sender2 = class {
constructor(publication, channel, _api, _transportRepository, _localPerson, _bot, _iceManager, _context) {
this.publication = publication;
this.channel = channel;
this._api = _api;
this._transportRepository = _transportRepository;
this._localPerson = _localPerson;
this._bot = _bot;
this._iceManager = _iceManager;
this._context = _context;
this._disposer = new EventDisposer();
this._connectionState = "new";
this.onConnectionStateChanged = new Event();
this.closed = false;
this.sendSubscriptionStatsReportTimer = null;
this._waitingSendSubscriptionStatsReports = [];
const analyticsSession = this._localPerson._analytics;
if (analyticsSession) {
analyticsSession.onConnectionStateChanged.add((state) => {
if (state === "connected" && this._waitingSendSubscriptionStatsReports.length > 0) {
for (const producerId of this._waitingSendSubscriptionStatsReports) {
if (this._producer && this._producer.id === producerId) {
this.startSendSubscriptionStatsReportTimer();
}
}
this._waitingSendSubscriptionStatsReports = [];
}
});
}
}
_setConnectionState(state) {
if (this._connectionState === state) {
return;
}
log42.debug("_setConnectionState", {
state,
forwardingId: this.forwardingId
});
this._connectionState = state;
this.onConnectionStateChanged.emit(state);
}
toJSON() {
return {
forwarding: this.forwarding,
broadcasterTransport: this._broadcasterTransport,
_connectionState: this._connectionState
};
}
/**@throws {SkyWayError} */
startForwarding(configure) {
return __async(this, null, function* () {
if (this.publication.contentType === "data") {
throw createError({
operationName: "Sender.startForwarding",
context: this._context,
info: errors5.dataStreamNotSupported,
path: log42.prefix,
channel: this.channel
});
}
const stream = this.publication.stream;
if (!stream) {
throw createError({
operationName: "Sender.startForwarding",
context: this._context,
info: errors5.streamNotExistInPublication,
path: log42.prefix,
channel: this.channel
});
}
this.onConnectionStateChanged.add((state) => {
var _a2;
log42.debug(
"transport connection state changed",
(_a2 = this._broadcasterTransport) == null ? void 0 : _a2.id,
state
);
stream._setConnectionState(this._bot, state);
}).disposer(this._disposer);
log42.debug("[start] Sender startForwarding", {
botId: this._bot.id,
publicationId: this.publication.id,
contentType: this.publication.contentType,
maxSubscribers: configure.maxSubscribers
});
const {
forwardingId,
broadcasterTransportId,
// optional
broadcasterTransportOptions,
rtpCapabilities,
identifierKey
} = yield this._api.startForwarding({
botId: this._bot.id,
publicationId: this.publication.id,
contentType: this.publication.contentType,
maxSubscribers: configure.maxSubscribers,
publisherId: this.publication.publisher.id
});
this.forwardingId = forwardingId;
if (broadcasterTransportOptions) {
log42.debug("sender create new transport", {
broadcasterTransportOptions
});
yield this._transportRepository.loadDevice(rtpCapabilities);
this._broadcasterTransport = this._transportRepository.createTransport(
this._localPerson.id,
this._bot,
broadcasterTransportOptions,
"send",
this._iceManager,
this._localPerson._analytics
);
}
this._broadcasterTransport = this._transportRepository.getTransport(
this._localPerson.id,
broadcasterTransportId
);
if (!this._broadcasterTransport) {
throw createError({
operationName: "Sender.startForwarding",
context: this._context,
info: __spreadProps(__spreadValues({}, errors5.internal), { detail: "_broadcasterTransport not found" }),
path: log42.prefix,
channel: this.channel,
payload: { broadcasterTransportOptions }
});
}
this._broadcasterTransport.onConnectionStateChanged.add((state) => {
this._setConnectionState(state);
}).disposer(this._disposer);
this._setConnectionState(this._broadcasterTransport.connectionState);
const producer = yield this._produce(stream, this._broadcasterTransport);
this._cleanupStreamCallbacks = this._setupTransportAccessForStream(
stream,
this._broadcasterTransport,
producer
);
const analyticsSession = this._localPerson._analytics;
if (analyticsSession && !analyticsSession.isClosed()) {
if (analyticsSession.client.isConnectionEstablished()) {
this.startSendSubscriptionStatsReportTimer();
} else {
this._waitingSendSubscriptionStatsReports.push(producer.id);
}
}
log42.debug("[end] Sender startForwarding", {
forwardingId
});
let relayingPublication = this.channel._getPublication(forwardingId);
if (!relayingPublication) {
relayingPublication = (yield this.channel.onStreamPublished.watch(
(e2) => e2.publication.id === forwardingId,
this._context.config.rtcApi.timeout
).catch(() => {
throw createError({
operationName: "Sender.startForwarding",
context: this._context,
info: __spreadProps(__spreadValues({}, errors5.timeout), {
detail: "SFUBotMember onStreamPublished"
}),
path: log42.prefix,
channel: this.channel,
payload: { forwardingId }
});
})).publication;
}
const forwarding = new Forwarding({
configure,
originPublication: this.publication,
relayingPublication,
api: this._api,
context: this._context,
identifierKey
});
this.forwarding = forwarding;
const botSubscribing = this.channel.subscriptions.find(
(s) => s.publication.id === this.publication.id
);
const [codec] = producer.rtpParameters.codecs;
botSubscribing.codec = codec;
if (this._localPerson._analytics && this._localPerson._analytics.client.connectionState !== "closed") {
void this._localPerson._analytics.client.sendBindingRtcPeerConnectionToSubscription(
{
subscriptionId: botSubscribing.id,
role: "sender",
rtcPeerConnectionId: this._broadcasterTransport.id
}
);
}
if (isSafari()) {
waitForLocalStats({
stream,
remoteMember: this._bot.id,
end: (stats) => {
const outbound = stats.find(
(s) => s.id.includes("RTCOutboundRTP") || s.type.includes("outbound-rtp")
);
if ((outbound == null ? void 0 : outbound.keyFramesEncoded) > 0) return true;
return false;
},
interval: 10
}).then(() => __async(this, null, function* () {
const encodings = this.publication.encodings;
if ((encodings == null ? void 0 : encodings.length) > 0) {
yield setEncodingParams(producer.rtpSender, encodings).catch(
(e2) => {
log42.error("_onEncodingsChanged failed", e2, this);
}
);
}
})).catch((err) => {
log42.error("setEncodingParams waitForLocalStats failed", err, this);
});
}
waitForLocalStats({
stream,
remoteMember: this._bot.id,
end: (stats) => !!stats.find((s) => s.type.includes("local-candidate"))
}).then(() => __async(this, null, function* () {
const payload = yield createLogPayload({
operationName: "startForwarding/waitForLocalStats",
channel: this.channel
});
log42.debug(payload, "forwarding connection connected", {
broadcasterTransportId
});
})).catch(() => {
});
return forwarding;
});
}
_listenStreamEnableChange(stream) {
if (this._unsubscribeStreamEnableChange) {
this._unsubscribeStreamEnableChange();
}
const { removeListener } = stream._onEnableChanged.add((track) => __async(this, null, function* () {
yield this._replaceTrack(track).catch((e2) => {
log42.warn(
createWarnPayload5({
detail: "replaceTrack failed",
operationName: "Sender._listenStreamEnableChange",
bot: this._bot,
payload: e2
})
);
});
}));
this._unsubscribeStreamEnableChange = removeListener;
}
_produce(stream, transport) {
return __async(this, null, function* () {
var _a2, _b2, _c, _d, _e, _f, _g, _h;
this.publication._onReplaceStream.add((_0) => __async(this, [_0], function* ({ newStream }) {
if (!this._broadcasterTransport) {
throw createError({
operationName: "Sender._produce",
context: this._context,
info: __spreadProps(__spreadValues({}, errors5.internal), {
detail: "_broadcasterTransport not found"
}),
path: log42.prefix,
channel: this.channel
});
}
this._listenStreamEnableChange(newStream);
if (this._cleanupStreamCallbacks) {
this._cleanupStreamCallbacks();
}
this._cleanupStreamCallbacks = this._setupTransportAccessForStream(
newStream,
this._broadcasterTransport,
producer
);
yield this._replaceTrack(newStream.track);
})).disposer(this._disposer);
this._listenStreamEnableChange(stream);
const transactionId = uuidV4();
const producerOptions = {
track: stream.track,
// mediasoup-clientはデフォルトでunproduce時にtrack.stopを実行する
stopTracks: false,
appData: { transactionId },
// デフォルトで一度mutedなTrackをProduceするとreplaceTrackしたTrackがDisableされる
disableTrackOnPause: false
};
const encodings = this.publication.encodings;
if (encodings) {
producerOptions.encodings = encodings;
}
this.publication._onEncodingsChanged.add((encodings2) => __async(this, null, function* () {
yield setEncodingParams(producer.rtpSender, encodings2).catch((e2) => {
log42.error("_onEncodingsChanged failed", e2, this);
});
})).disposer(this._disposer);
const codecCapabilities = this.publication.codecCapabilities;
const deviceCodecs = (_b2 = (_a2 = this._transportRepository.rtpCapabilities) == null ? void 0 : _a2.codecs) != null ? _b2 : [];
log42.debug("select codec", { codecCapabilities, deviceCodecs });
const [codec] = codecCapabilities.map((cap) => {
if (cap.mimeType.toLowerCase().includes("video")) {
const codec3 = deviceCodecs.find((c) => {
var _a3;
if (c.mimeType.toLowerCase() !== cap.mimeType.toLowerCase()) {
return false;
}
if (Object.keys((_a3 = cap.parameters) != null ? _a3 : {}).length > 0 && !(0, import_isEqual2.default)(cap.parameters, c.parameters)) {
return false;
}
return true;
});
return codec3;
}
const codec2 = deviceCodecs.find(
(c) => c.mimeType.toLowerCase() === cap.mimeType.toLowerCase()
);
return codec2;
});
log42.debug("selected codec", { codec });
if (codec) {
const [codecType, codecName] = codec.mimeType.split("/");
producerOptions.codec = __spreadProps(__spreadValues({}, codec), {
mimeType: `${codecType}/${codecName.toUpperCase()}`
});
if (stream.contentType === "video") {
this._fixVideoCodecWithParametersOrder(codec);
}
} else if (codecCapabilities.length > 0) {
log42.warn(
"preferred codec not supported",
createWarnPayload5({
channel: this.channel,
detail: "preferred codec not supported",
operationName: "Sender._produce",
bot: this._bot,
payload: {
codecCapabilities,
deviceCodecs
}
})
);
}
if (stream.contentType === "audio") {
const opusDtx = (_d = (_c = codecCapabilities.find(
(c) => c.mimeType.toLowerCase() === "audio/opus"
)) == null ? void 0 : _c.parameters) == null ? void 0 : _d.usedtx;
if (opusDtx !== false) {
producerOptions.codecOptions = __spreadProps(__spreadValues({}, producerOptions.codecOptions), {
opusDtx: true
});
}
const opusStereo = (_f = (_e = codecCapabilities.find(
(c) => c.mimeType.toLowerCase() === "audio/opus"
)) == null ? void 0 : _e.parameters) == null ? void 0 : _f.stereo;
if (opusStereo) {
producerOptions.codecOptions = __spreadProps(__spreadValues({}, producerOptions.codecOptions), {
opusStereo: true
});
}
const opusFec = (_h = (_g = codecCapabilities.find(
(c) => c.mimeType.toLowerCase() === "audio/opus"
)) == null ? void 0 : _g.parameters) == null ? void 0 : _h.useinbandfec;
if (opusFec) {
producerOptions.codecOptions = __spreadProps(__spreadValues({}, producerOptions.codecOptions), {
opusFec: true
});
}
}
transport.onProduce.watch(
(p) => {
var _a3;
return ((_a3 = p.producerOptions.appData) == null ? void 0 : _a3.transactionId) === transactionId;
},
this._context.config.rtcConfig.timeout
).then((producer2) => __async(this, null, function* () {
try {
const { producerId } = yield this._api.createProducer({
botId: this._bot.id,
transportId: transport.id,
forwardingId: this.forwardingId,
producerOptions: producer2.producerOptions
});
producer2.callback({ id: producerId });
} catch (error) {
producer2.errback(error);
}
})).catch((e2) => {
log42.error("onProduce failed", e2, this);
});
log42.debug("[start] msTransport.produce", this);
const producer = yield transport.msTransport.produce(producerOptions).catch((err) => {
throw createError({
operationName: "Sender._produce",
context: this._context,
info: __spreadProps(__spreadValues({}, errors5.internal), { detail: "msTransport.produce failed" }),
path: log42.prefix,
channel: this.channel,
error: err
});
});
log42.debug("[end] msTransport.produce", this);
this._producer = producer;
return producer;
});
}
/** @description 引数のParametersを持ったCodecを優先度配列の先頭に持ってくる
* @description H264対応のため
*/
_fixVideoCodecWithParametersOrder(codec) {
var _a2;
const handler = (_a2 = this._broadcasterTransport) == null ? void 0 : _a2.msTransport._handler;
const findCodecWithParameters = (c) => {
if (c.mimeType === codec.mimeType) {
if (codec.parameters && Object.keys(codec.parameters).length > 0) {
if ((0, import_isEqual2.default)(c.parameters, codec.parameters)) {
return true;
}
return false;
}
return true;
}
return false;
};
const copyCodecExceptPayloadType = (target, src) => {
for (const key of Object.keys(target)) {
if (key === "payloadType") {
continue;
}
target[key] = src[key];
}
};
if (handler._sendingRtpParametersByKind) {
const parameters = handler._sendingRtpParametersByKind.video;
const target = parameters.codecs.find(findCodecWithParameters);
if (parameters && target) {
const origin2 = JSON.parse(JSON.stringify(parameters));
const [head] = parameters.codecs;
const copyOfHead = JSON.parse(JSON.stringify(head));
copyCodecExceptPayloadType(head, target);
copyCodecExceptPayloadType(target, copyOfHead);
log42.debug("sort _sendingRtpParametersByKind", {
origin: origin2,
new: parameters.codecs
});
}
}
if (handler._sendingRemoteRtpParametersByKind) {
const parameters = handler._sendingRemoteRtpParametersByKind.video;
const target = parameters.codecs.find(findCodecWithParameters);
if (parameters && target) {
const origin2 = JSON.parse(JSON.stringify(parameters));
const [head] = parameters.codecs;
const copyOfHead = JSON.parse(JSON.stringify(head));
copyCodecExceptPayloadType(head, target);
copyCodecExceptPayloadType(target, copyOfHead);
log42.debug("sort _sendingRemoteRtpParametersByKind", {
origin: origin2,
new: parameters.codecs
});
}
}
}
_setupTransportAccessForStream(stream, transport, producer) {
stream._getTransportCallbacks[this._bot.id] = () => ({
rtcPeerConnection: transport.pc,
connectionState: transport.connectionState,
info: this
});
stream._getStatsCallbacks[this._bot.id] = () => __async(this, null, function* () {
if (producer.closed) {
delete stream._getStatsCallbacks[this._bot.id];
return [];
}
const stats = yield producer.getStats();
let arr = statsToArray(stats);
arr = arr.map((stats2) => {
stats2.sfuTransportId = transport.id;
return stats2;
});
return arr;
});
const cleanupCallbacks = () => {
delete stream._getTransportCallbacks[this._bot.id];
delete stream._getStatsCallbacks[this._bot.id];
};
this._disposer.push(() => {
cleanupCallbacks();
});
return cleanupCallbacks;
}
unproduce() {
if (!this._producer) {
return;
}
this._producer.close();
this._producer = void 0;
if (this.sendSubscriptionStatsReportTimer) {
clearInterval(this.sendSubscriptionStatsReportTimer);
}
}
_replaceTrack(track) {
return __async(this, null, function* () {
var _a2, _b2;
yield (_b2 = (_a2 = this._producer) == null ? void 0 : _a2.replaceTrack) == null ? void 0 : _b2.call(_a2, { track }).catch((e2) => {
throw createError({
operationName: "Sender._replaceTrack",
context: this._context,
info: errors5.internal,
error: e2,
path: log42.prefix,
channel: this.channel
});
});
});
}
close() {
this.closed = true;
if (this._unsubscribeStreamEnableChange) {
this._unsubscribeStreamEnableChange();
}
this._setConnectionState("disconnected");
this._disposer.dispose();
}
get pc() {
var _a2;
return (_a2 = this._broadcasterTransport) == null ? void 0 : _a2.pc;
}
startSendSubscriptionStatsReportTimer() {
const analyticsSession = this._localPerson._analytics;
const subscription = this._bot.subscriptions.find(
(s) => s.publication.id === this.publication.id
);
if (subscription && analyticsSession) {
const intervalSec = analyticsSession.client.getIntervalSec();
this.sendSubscriptionStatsReportTimer = setInterval(() => __async(this, null, function* () {
if (!analyticsSession || analyticsSession.isClosed()) {
if (this.sendSubscriptionStatsReportTimer) {
clearInterval(this.sendSubscriptionStatsReportTimer);
}
return;
}
if (this._producer) {
const stats = yield this._producer.getStats();
if (stats) {
void analyticsSession.client.sendSubscriptionStatsReport(stats, {
subscriptionId: subscription.id,
role: "sender",
contentType: this.publication.contentType,
createdAt: Date.now()
});
}
}
}), intervalSec * 1e3);
}
}
};
// src/connection/index.ts
var log43 = new Logger("packages/sfu-bot/src/connection/index.ts");
var SFUConnection = class {
/**@internal */
constructor(_api, channel, localPerson, remoteMember, _transportRepository, _context) {
this._api = _api;
this.channel = channel;
this.localPerson = localPerson;
this.remoteMember = remoteMember;
this._transportRepository = _transportRepository;
this._context = _context;
this.type = "sfu";
this.onDisconnect = new Event();
this.onClose = new Event();
this.closed = false;
/**@private */
this._receivers = {};
/**@private */
this._senders = {};
}
/**@internal */
addSender(publication) {
const sender = new Sender2(
publication,
this.channel,
this._api,
this._transportRepository,
this.localPerson,
this.remoteMember,
this.localPerson.iceManager,
this._context
);
this._senders[publication.id] = sender;
return sender;
}
/**@internal */
removeSender(originPublicationId) {
log43.debug("removeSender", originPublicationId);
const sender = this._senders[originPublicationId];
if (!sender) {
return;
}
sender.unproduce();
}
startSubscribing(subscription) {
return __async(this, null, function* () {
var _a2;
const receiver = new Receiver2(
subscription,
this._api,
this._transportRepository,
this.localPerson,
this.remoteMember,
this.localPerson.iceManager,
this._context
);
this._receivers[subscription.id] = receiver;
const ts = log43.debug("[start] _startSubscribing consume");
const { stream, codec } = yield receiver.consume().catch((e2) => {
log43.error(
"[failed] _startSubscribing consume",
createError({
operationName: "SFUConnection.startSubscribing",
context: this._context,
channel: this.channel,
info: __spreadProps(__spreadValues({}, errors5.internal), { detail: "failed to receiver.consume" }),
error: e2,
path: log43.prefix,
payload: { subscription: subscription.toJSON() }
})
);
throw e2;
});
log43.elapsed(ts, "[end] _startSubscribing consume");
stream.setIsEnabled(subscription.publication.state === "enabled");
subscription.codec = codec;
subscription._setStream(stream);
if (this.localPerson._analytics && !this.localPerson._analytics.isClosed()) {
const preferredEncoding = subscription.preferredEncoding;
const encodings = (_a2 = subscription.publication.origin) == null ? void 0 : _a2.encodings;
if (!preferredEncoding || !encodings || encodings.length === 0) {
return;
}
const layer = getLayerFromEncodings(preferredEncoding, encodings);
void this.localPerson._analytics.client.sendSubscriptionUpdatePreferredEncodingReport(
{
subscriptionId: subscription.id,
preferredEncodingIndex: layer,
updatedAt: Date.now()
}
);
}
});
}
/**@internal */
stopSubscribing(subscription) {
return __async(this, null, function* () {
const connection = this._receivers[subscription.id];
if (!connection) {
return;
}
connection.unconsume();
});
}
/**@internal */
stopPublishing(publication) {
return __async(this, null, function* () {
this.removeSender(publication.id);
});
}
/**@internal */
close({ reason } = {}) {
if (this.closed) {
return;
}
log43.debug("close sfu connection", {
remote: this.remoteMember,
local: this.localPerson,
reason
});
this.closed = true;
Object.values(this._senders).forEach((sender) => {
sender.close();
});
Object.values(this._receivers).forEach((receiver) => {
receiver.close();
});
this._senders = {};
this._receivers = {};
this.onClose.emit();
}
_getReceiver(subscriptionId) {
return this._receivers[subscriptionId];
}
changePreferredEncoding(subscription) {
return __async(this, null, function* () {
var _a2;
const preferredEncoding = subscription.preferredEncoding;
const encodings = (_a2 = subscription.publication.origin) == null ? void 0 : _a2.encodings;
log43.debug("changePreferredEncoding", {
preferredEncoding,
encodings,
subscription
});
if (!preferredEncoding) {
throw createError({
operationName: "SFUConnection.changePreferredEncoding",
context: this._context,
channel: this.channel,
info: errors5.invalidPreferredEncoding,
path: log43.prefix,
payload: { subscription }
});
}
if (!encodings || encodings.length === 0) {
throw createError({
operationName: "SFUConnection.changePreferredEncoding",
context: this._context,
channel: this.channel,
info: errors5.invalidEncodings,
path: log43.prefix,
payload: { subscription }
});
}
const layer = getLayerFromEncodings(preferredEncoding, encodings);
const receiver = this._getReceiver(subscription.id);
if (!receiver) {
throw createError({
operationName: "SFUConnection.changePreferredEncoding",
context: this._context,
channel: this.channel,
info: errors5.receiverNotFound,
path: log43.prefix,
payload: { subscription }
});
}
const transport = receiver.transport;
if (!transport) {
throw createError({
operationName: "SFUConnection.changePreferredEncoding",
context: this._context,
channel: this.channel,
info: __spreadProps(__spreadValues({}, errors5.internal), { detail: "transport not found" }),
path: log43.prefix,
payload: { subscription }
});
}
const consumer = receiver.consumer;
if (!consumer) {
throw createError({
operationName: "SFUConnection.changePreferredEncoding",
context: this._context,
channel: this.channel,
info: errors5.consumerNotFound,
path: log43.prefix,
payload: { subscription }
});
}
yield this._api.changeConsumerLayer({
transportId: transport.id,
consumerId: consumer.id,
publicationId: subscription.publication.id,
spatialLayer: layer
});
if (this.localPerson._analytics && !this.localPerson._analytics.isClosed()) {
void this.localPerson._analytics.client.sendSubscriptionUpdatePreferredEncodingReport(
{
subscriptionId: subscription.id,
preferredEncodingIndex: layer,
updatedAt: Date.now()
}
);
}
});
}
};
// src/member.ts
init_process();
// src/const.ts
init_process();
var defaultMaxSubscribers = 10;
// src/member.ts
var log44 = new Logger("packages/sfu-bot/src/member.ts");
var _SFUBotMember = class _SFUBotMember extends MemberImpl {
/**@internal */
constructor(args) {
super(args);
this.side = "remote";
this.subtype = _SFUBotMember.subtype;
this.type = "bot";
this._connections = {};
/** @description [japanese] forwardingを開始した時に発火するイベント */
this.onForwardingStarted = new Event();
/** @description [japanese] forwardingを終了した時に発火するイベント */
this.onForwardingStopped = new Event();
/** @description [japanese] forwardingの数が変化した時に発火するイベント */
this.onForwardingListChanged = new Event();
this._startForwardQueue = new PromiseQueue();
this._forwardings = {};
/**
* @description [japanese] Forwardingを停止する
*/
this.stopForwarding = (target) => new Promise((r2, f) => {
if (this.state !== "joined") {
f(
createError({
operationName: "SFUBotMember.stopForwarding",
context: this._context,
info: errors5.sfuBotNotInChannel,
path: log44.prefix,
channel: this.channel,
payload: { status: this.state }
})
);
return;
}
const forwardingId = typeof target === "string" ? target : target.id;
const forwarding = this._forwardings[forwardingId];
if (!forwarding) {
f(
createError({
operationName: "SFUBotMember.stopForwarding",
context: this._context,
info: errors5.forwardingNotFound,
path: log44.prefix,
channel: this.channel,
payload: {
forwardingId,
_forwardings: Object.keys(this._forwardings)
}
})
);
return;
}
const executeStop = () => __async(this, null, function* () {
const timestamp = log44.info(
"[start] stopForwarding",
yield createLogPayload({
operationName: "SFUBotMember.stopForwarding",
channel: this.channel
})
);
delete this._forwardings[forwarding.id];
const { promise, fulfilled } = this._api.stopForwarding({
botId: this.id,
forwardingId
});
let failed = false;
promise.catch((e2) => {
failed = true;
f(e2);
});
this.onForwardingStopped.watch(
(e2) => e2.forwarding.id === forwardingId,
this._context.config.rtcApi.timeout
).then(() => __async(this, null, function* () {
log44.elapsed(
timestamp,
"[end] stopForwarding",
yield createLogPayload({
operationName: "SFUBotMember.stopForwarding",
channel: this.channel
})
);
r2();
})).catch((error) => {
if (!failed)
f(
createError({
operationName: "SFUBotMember.stopForwarding",
context: this._context,
info: __spreadProps(__spreadValues({}, errors5.timeout), { detail: "onForwardingStopped" }),
path: log44.prefix,
channel: this.channel,
payload: { fulfilled },
error
})
);
});
});
executeStop().catch(f);
});
this._api = args.api;
this._context = args.context;
this._transportRepository = args.transportRepository;
this.options = args.options;
this.onLeft.once(() => {
log44.debug("SFUBotMember left: ", { id: this.id });
Object.values(this._connections).forEach((c) => {
c.close({ reason: "sfu bot left" });
});
this._connections = {};
});
}
get forwardings() {
return Object.values(this._forwardings);
}
/**@private */
_getConnection(localPersonId) {
return this._connections[localPersonId];
}
/**@private */
_getOrCreateConnection(localPerson) {
var _a2;
const connection = (_a2 = this._getConnection(localPerson.id)) != null ? _a2 : this._createConnection(this.channel, localPerson, this);
return connection;
}
/**@private */
_createConnection(channel, localPerson, endpointBot) {
const connection = new SFUConnection(
endpointBot._api,
channel,
localPerson,
endpointBot,
this._transportRepository,
this._context
);
connection.onClose.once(() => {
delete this._connections[localPerson.id];
});
this._connections[localPerson.id] = connection;
return connection;
}
/**
* @description [japanese] StreamのPublicationをForwardingする
* @throws {SkyWayError}
* @example
* const forwarding = await bot.startForwarding(publication, { maxSubscribers: 99 });
*/
startForwarding(_0) {
return __async(this, arguments, function* (publication, configure = {}) {
const timestamp = log44.info(
"[start] startForwarding",
yield createLogPayload({
operationName: "SFUBotMember.startForwarding",
channel: this.channel
})
);
const res = yield this._startForwardQueue.push(
() => this._startForwarding(
publication,
configure
)
);
log44.elapsed(
timestamp,
"[end] startForwarding",
yield createLogPayload({
operationName: "SFUBotMember.startForwarding",
channel: this.channel
})
);
return res;
});
}
_startForwarding(origin2, configure) {
return __async(this, null, function* () {
if (configure.maxSubscribers === void 0) {
configure.maxSubscribers = defaultMaxSubscribers;
}
if (this.state !== "joined") {
throw createError({
operationName: "SFUBotMember._startForwarding",
context: this._context,
channel: this.channel,
info: errors5.sfuBotNotInChannel,
path: log44.prefix,
payload: { status: this.state }
});
}
if (!this.channel._getPublication(origin2.id)) {
throw createError({
operationName: "SFUBotMember._startForwarding",
context: this._context,
channel: this.channel,
info: errors.publicationNotExist,
path: log44.prefix
});
}
const localPerson = this.channel.localPerson;
if (!localPerson) {
throw createError({
operationName: "SFUBotMember._startForwarding",
context: this._context,
channel: this.channel,
info: errors.localPersonNotJoinedChannel,
path: log44.prefix
});
}
if (localPerson.id !== origin2.publisher.id) {
throw createError({
operationName: "SFUBotMember._startForwarding",
context: this._context,
info: errors5.remotePublisherId,
path: log44.prefix,
channel: this.channel
});
}
const ts = log44.debug("[start] SFUBotMember startForwarding", {
publication: origin2.toJSON(),
configure
});
const connection = this._getOrCreateConnection(localPerson);
const sender = connection.addSender(origin2);
const forwarding = yield sender.startForwarding(configure).catch((error) => {
throw createError({
operationName: "SFUBotMember._startForwarding",
context: this._context,
info: __spreadProps(__spreadValues({}, errors5.internal), {
detail: "[failed] SFUBotMember startForwarding"
}),
path: log44.prefix,
channel: this.channel,
error,
payload: { publication: origin2.toJSON() }
});
});
this._forwardings[forwarding.id] = forwarding;
this.listenStopForwardEvent(forwarding);
this.onForwardingStarted.emit({ forwarding });
this.onForwardingListChanged.emit();
log44.elapsed(ts, "[end] SFUBotMember startForwarding", {
forwarding: forwarding.toJSON()
});
return forwarding;
});
}
listenStopForwardEvent(forwarding) {
const { removeListener } = this.channel.onStreamUnpublished.add((e2) => {
if (e2.publication.id === forwarding.id) {
removeListener();
forwarding._stop();
const origin2 = forwarding.originPublication;
const connection = this._getConnection(origin2.publisher.id);
if (connection) {
connection.removeSender(origin2.id);
}
this.onForwardingStopped.emit({ forwarding });
this.onForwardingListChanged.emit();
}
});
}
/**@private */
_dispose() {
}
};
_SFUBotMember.subtype = "sfu";
var SFUBotMember = _SFUBotMember;
// src/option.ts
init_process();
var defaultSFUBotPluginOptions = __spreadProps(__spreadValues({}, defaultSFUApiOptions), {
endpointTimeout: 3e4,
ackTimeout: 1e4,
disableRestartIce: false
});
// src/plugin.ts
init_process();
// src/connection/transport/transportRepository.ts
init_process();
var import_mediasoup_client = __toESM(require_lib6());
// src/connection/transport/transport.ts
init_process();
var log45 = new Logger(
"packages/sfu-bot/src/connection/transport/transport.ts"
);
var SFUTransport = class {
constructor(msTransport, _bot, _iceManager, _sfuApi, _context, _analyticsSession) {
this.msTransport = msTransport;
this._bot = _bot;
this._iceManager = _iceManager;
this._sfuApi = _sfuApi;
this._context = _context;
this._analyticsSession = _analyticsSession;
this._backoffIceRestart = new BackOff({
times: 8,
interval: 100,
jitter: 100
});
this._connectionState = "new";
this.onProduce = new Event();
this.onProduceData = new Event();
this.onMediasoupConnectionStateChanged = new Event();
this.onConnectionStateChanged = new Event();
this.restartIce = () => __async(this, null, function* () {
if (this._backoffIceRestart.exceeded) {
log45.error(
"_iceRestartedCount exceeded",
createError({
operationName: "SFUTransport.restartIce",
context: this._context,
info: errors5.netWorkError,
path: log45.prefix
})
);
this._setConnectionState("disconnected");
return;
}
log45.warn(
"[start] restartIce",
createWarnPayload5({
bot: this._bot,
detail: "start restartIce",
operationName: "SFUTransport.restartIce",
payload: { count: this._backoffIceRestart.count, transport: this }
})
);
const checkNeedEnd = () => {
if (this._bot.state === "left") {
log45.debug("bot already left", this);
this._setConnectionState("disconnected");
log45.warn(
"[end] restartIce",
createWarnPayload5({
bot: this._bot,
detail: "end restartIce",
operationName: "SFUTransport.restartIce",
payload: { count: this._backoffIceRestart.count, transport: this }
})
);
return true;
}
if (this.msTransport.connectionState === "connected") {
this._backoffIceRestart.reset();
this._setConnectionState("connected");
log45.warn(
"[end] restartIce",
createWarnPayload5({
bot: this._bot,
detail: "end restartIce",
operationName: "SFUTransport.restartIce",
payload: { count: this._backoffIceRestart.count, transport: this }
})
);
if (this._analyticsSession && !this._analyticsSession.isClosed()) {
void this._analyticsSession.client.sendRtcPeerConnectionEventReport({
rtcPeerConnectionId: this.id,
type: "restartIce",
data: void 0,
createdAt: Date.now()
});
}
return true;
}
};
this._setConnectionState("reconnecting");
yield this._backoffIceRestart.wait();
if (checkNeedEnd()) {
return;
}
let e2 = yield this._iceManager.updateIceParams().catch((e3) => e3);
if (e2) {
log45.warn(
"updateIceParams failed",
createWarnPayload5({
operationName: "SFUTransport.restartIce",
detail: "updateIceParams failed",
bot: this._bot,
payload: { transport: this }
}),
e2
);
yield this.restartIce();
return;
}
yield this.msTransport.updateIceServers({
iceServers: this._iceManager.iceServers
});
if (checkNeedEnd()) {
return;
}
const iceParameters = yield this._mediasoupRestartIce();
e2 = yield this._waitForMsConnectionState(
"connected",
this._context.config.rtcConfig.iceDisconnectBufferTimeout
).catch((e3) => e3);
if (!e2 && checkNeedEnd()) {
return iceParameters;
}
yield this.restartIce();
});
this._waitForMsConnectionState = (state, timeout = 1e4) => __async(this, null, function* () {
if (state === this.msTransport.connectionState) return;
yield this.onMediasoupConnectionStateChanged.watch(() => state === this.msTransport.connectionState, timeout).catch((err) => {
throw createError({
operationName: "SFUTransport._waitForMsConnectionState",
context: this._context,
info: __spreadProps(__spreadValues({}, errors5.timeout), { detail: "waitForConnectionState timeout" }),
error: err,
path: log45.prefix
});
});
});
this._onConnect = (transportId) => (_0, _1, _2) => __async(this, [_0, _1, _2], function* ({
dtlsParameters
}, callback, errback) {
try {
log45.debug("[start] transport connect", { transportId });
yield this._sfuApi.connect({ transportId, dtlsParameters });
log45.debug("[end] transport connect", { transportId });
callback();
} catch (error) {
log45.error("[failed] transport connect", {
error,
transportId
});
errback(error);
}
});
var _a2, _b2, _c;
log45.debug("peerConfig", (_c = (_b2 = (_a2 = this.pc) == null ? void 0 : _a2.getConfiguration) == null ? void 0 : _b2.call(_a2)) != null ? _c : {});
msTransport.on("connect", (params, callback, errback) => {
return this._onConnect(msTransport.id)(
params,
callback,
errback
);
});
msTransport.on("connectionstatechange", (e2) => {
this.onMediasoupConnectionStateChanged.emit(e2);
if (this._analyticsSession && !this._analyticsSession.isClosed()) {
void this._analyticsSession.client.sendRtcPeerConnectionEventReport({
rtcPeerConnectionId: this.id,
type: "connectionStateChange",
data: {
connectionState: e2
},
createdAt: Date.now()
});
}
});
msTransport.on("produce", (producerOptions, callback, errback) => {
this.onProduce.emit({
producerOptions,
callback,
errback
});
});
msTransport.on("producedata", (producerOptions, callback, errback) => {
this.onProduceData.emit({
producerOptions,
callback,
errback
});
});
this.onMediasoupConnectionStateChanged.add(
(state) => __async(this, null, function* () {
createLogPayload({
operationName: "onMediasoupConnectionStateChanged",
channel: this._bot.channel
}).then((debug) => {
log45.debug(debug, { state, transportId: this.id, bot: _bot });
}).catch(() => {
});
switch (state) {
case "disconnected":
case "failed":
{
if (this._connectionState === "reconnecting") {
return;
}
const e2 = yield this._waitForMsConnectionState(
"connected",
_context.config.rtcConfig.iceDisconnectBufferTimeout
).catch((e3) => e3);
if (e2 && this._connectionState !== "reconnecting" && _bot.options.disableRestartIce !== true) {
yield this.restartIce();
}
}
break;
case "connecting":
case "connected":
this._setConnectionState(state);
break;
case "closed":
this._setConnectionState("disconnected");
break;
}
log45.debug("onMediasoupConnectionStateChanged", this);
})
);
}
get pc() {
var _a2, _b2, _c;
return (_c = (_b2 = (_a2 = this.msTransport) == null ? void 0 : _a2._handler) == null ? void 0 : _b2._pc) != null ? _c : {};
}
get id() {
return this.msTransport.id;
}
get connectionState() {
return this._connectionState;
}
toJSON() {
return {
id: this.id,
direction: this.msTransport.direction,
connectionState: this._connectionState
};
}
close() {
var _a2;
log45.debug("close", this.id);
if ((_a2 = this.pc) == null ? void 0 : _a2.peerIdentity) {
this.pc.peerIdentity.catch(() => {
});
}
this.msTransport.close();
this._setConnectionState("disconnected");
}
_setConnectionState(state) {
if (this._connectionState === state) {
return;
}
log45.debug("onConnectionStateChanged", this._connectionState, state, this);
this._connectionState = state;
this.onConnectionStateChanged.emit(state);
if (this._analyticsSession && !this._analyticsSession.isClosed()) {
void this._analyticsSession.client.sendRtcPeerConnectionEventReport({
rtcPeerConnectionId: this.id,
type: "skywayConnectionStateChange",
data: {
skywayConnectionState: state
},
createdAt: Date.now()
});
}
}
/**@private */
_mediasoupRestartIce() {
return __async(this, null, function* () {
const iceParameters = yield this._sfuApi.iceRestart({
transportId: this.id
}).catch((e2) => e2);
if (iceParameters instanceof Error) {
log45.warn(
"iceRestart failed",
createWarnPayload5({
operationName: "SFUTransport._mediasoupRestartIce",
detail: "iceRestart failed",
bot: this._bot,
payload: { transport: this }
}),
iceParameters
);
yield this.restartIce();
return;
}
yield this.msTransport.restartIce({ iceParameters });
return iceParameters;
});
}
};
// src/connection/transport/transportRepository.ts
var log46 = new Logger(
"packages/sfu-bot/src/connection/transport/transportRepository.ts"
);
var TransportRepository = class {
constructor(_context, _api) {
this._context = _context;
this._api = _api;
this.onTransportCreated = new Event();
/**@private */
this._transports = {};
this.getTransport = (personId, id) => this._transports[personId + id];
const { browserName, browserVersion } = getRuntimeInfo();
log46.debug("runtime info", { browserName, browserVersion });
if (browserName === "Safari" && browserVersion === void 0) {
this._device = new import_mediasoup_client.Device({ handlerName: "Safari12" });
} else {
this._device = new import_mediasoup_client.Device();
}
}
get rtpCapabilities() {
if (!this._device.loaded) {
return void 0;
}
return this._device.rtpCapabilities;
}
loadDevice(rtpCapabilities) {
return __async(this, null, function* () {
if (!this._device.loaded) {
yield this._device.load({
routerRtpCapabilities: rtpCapabilities
}).catch((err) => {
throw createError({
operationName: "TransportRepository.loadDevice",
context: this._context,
info: __spreadProps(__spreadValues({}, errors5.internal), { detail: "loadDevice failed" }),
path: log46.prefix,
payload: { rtpCapabilities },
error: err
});
});
log46.debug("device loaded", {
routerRtpCapabilities: rtpCapabilities,
rtpCapabilities: this._device.rtpCapabilities
});
}
});
}
/**worker内にmemberIdに紐つくTransportが無ければ新しいTransportが作られる */
createTransport(personId, bot, transportOptions, direction, iceManager, analyticsSession) {
const createTransport = direction === "send" ? (o2) => this._device.createSendTransport(o2) : (o2) => this._device.createRecvTransport(o2);
const msTransport = createTransport(__spreadProps(__spreadValues({}, transportOptions), {
iceServers: iceManager.iceServers,
iceTransportPolicy: this._context.config.rtcConfig.turnPolicy === "turnOnly" ? "relay" : void 0
}));
const transport = new SFUTransport(
msTransport,
bot,
iceManager,
this._api,
this._context,
analyticsSession
);
this._transports[personId + msTransport.id] = transport;
this.onTransportCreated.emit(msTransport.id);
return transport;
}
deleteTransports(personId) {
Object.entries(__spreadValues({}, this._transports)).forEach(([id, transport]) => {
if (id.includes(personId)) {
transport.close();
delete this._transports[id];
}
});
}
};
// src/version.ts
init_process();
var PACKAGE_VERSION3 = "2.0.3";
// src/plugin.ts
var log47 = new Logger("packages/sfu-bot/src/plugin.ts");
var _SFUBotPlugin = class _SFUBotPlugin extends SkyWayPlugin {
constructor(_options = {}) {
super();
this.subtype = _SFUBotPlugin.subtype;
/**@private */
this._createRemoteMember = (channel, sfuBot) => {
const member = new SFUBotMember(__spreadProps(__spreadValues({}, this._context), {
channel,
id: sfuBot.id,
name: sfuBot.name,
metadata: sfuBot.metadata,
plugin: this,
api: this._api,
context: this._context,
transportRepository: this._transportRepository,
options: this.options
}));
return member;
};
/**
* @description [japanese] SFU BotをChannelに呼び出す
*/
this.createBot = (channel) => __async(this, null, function* () {
var _a2;
const timestamp = log47.info(
"[start] createBot",
yield createLogPayload({
operationName: "SFUBotPlugin.createBot",
channel
})
);
const appId = this._context.authToken.getAppId();
const botId = yield this._api.createBot({
appId,
channelId: channel.id
});
const member = (_a2 = channel._getMember(botId)) != null ? _a2 : (yield channel.onMemberJoined.watch(
(e2) => e2.member.id === botId,
this._context.config.rtcApi.timeout
).catch((error) => {
throw createError({
operationName: "SFUBotPlugin.createBot",
info: __spreadProps(__spreadValues({}, errors5.timeout), { detail: "onMemberJoined" }),
path: log47.prefix,
error,
context: this._context
});
})).member;
log47.elapsed(
timestamp,
"[end] createBot",
yield createLogPayload({
operationName: "SFUBotPlugin.createBot",
channel
})
);
return member;
});
/**
* @description [japanese] SFU BotをChannelから削除する。
* @remarks SkyWayAuthToken v3 を利用した場合はこのメソッドを使うことができません。代替手段として Channel.leave メソッドまたは Member.leave メソッドを使用して SFU Bot を Channel から退出させてください。
*/
this.deleteBot = (channel, botId) => __async(this, null, function* () {
return new Promise((r2, f) => {
const executeDelete = () => __async(this, null, function* () {
var _a2;
const timestamp = log47.info(
"[start] deleteBot",
yield createLogPayload({
operationName: "SFUBotPlugin.deleteBot",
channel
})
);
let failed = false;
this._api.deleteBot({ botId }).catch((e2) => {
failed = true;
f(e2);
});
channel.onMemberLeft.watch(
(e2) => e2.member.id === botId,
(_a2 = this._context) == null ? void 0 : _a2.config.rtcApi.timeout
).then(() => __async(this, null, function* () {
log47.elapsed(
timestamp,
"[end] deleteBot",
yield createLogPayload({
operationName: "SFUBotPlugin.deleteBot",
channel
})
);
r2();
})).catch((error) => {
if (!failed)
f(
createError({
operationName: "SFUBotPlugin.deleteBot",
info: __spreadProps(__spreadValues({}, errors5.timeout), { detail: "onMemberLeft" }),
path: log47.prefix,
channel,
error,
context: this._context
})
);
});
});
executeDelete().catch(f);
});
});
this.options = __spreadValues(__spreadValues({}, defaultSFUBotPluginOptions), _options);
this._onContextAttached.once((context) => {
Logger.level = context.config.log.level;
Logger.format = context.config.log.format;
log47.info("SFUBotPlugin spawned", {
operationName: "SFUBotPlugin.constructor",
endpoint: { sfu: this.options.domain },
options: this.options,
sdkName: "sfu-bot",
sdkVersion: PACKAGE_VERSION3
});
this._api = new SFURestApiClient(context.authTokenString, __spreadProps(__spreadValues({}, this.options), {
log: context.config.log
}));
this._transportRepository = new TransportRepository(context, this._api);
context.onTokenUpdated.add((token) => {
this._api.updateToken(token);
});
});
this._whenDisposeLocalPerson = (person) => __async(this, null, function* () {
this._transportRepository.deleteTransports(person.id);
});
}
};
_SFUBotPlugin.subtype = SFUBotMember.subtype;
var SFUBotPlugin = _SFUBotPlugin;
return __toCommonJS(index_exports);
})();
/*! Bundled license information:
jsrsasign/lib/jsrsasign.js:
(*! CryptoJS v3.1.2 core-fix.js
* code.google.com/p/crypto-js
* (c) 2009-2013 by Jeff Mott. All rights reserved.
* code.google.com/p/crypto-js/wiki/License
* THIS IS FIX of 'core.js' to fix Hmac issue.
* https://code.google.com/p/crypto-js/issues/detail?id=84
* https://crypto-js.googlecode.com/svn-history/r667/branches/3.x/src/core.js
*)
(*! (c) Tom Wu | http://www-cs-students.stanford.edu/~tjw/jsbn/
*)
(*! (c) Tom Wu, Kenji Urushima | http://www-cs-students.stanford.edu/~tjw/jsbn/
*)
(*! (c) Stefan Thomas | https://github.com/bitcoinjs/bitcoinjs-lib
*)
(*! Mike Samuel (c) 2009 | code.google.com/p/json-sans-eval
*)
*/
/*
@skyway-sdk/sfu-bot@2.0.3
MIT
https://github.com/skyway/js-sdk
MIT License
Copyright (c) 2023 NTT DOCOMO BUSINESS, Inc.
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
---
@skyway-sdk/sfu-api-client@2.0.2
MIT
https://github.com/skyway/js-sdk
MIT License
Copyright (c) 2023 NTT DOCOMO BUSINESS, Inc.
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
---
@skyway-sdk/common@2.0.2
MIT
https://github.com/skyway/js-sdk
MIT License
Copyright (c) 2023 NTT DOCOMO BUSINESS, Inc.
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
---
@skyway-sdk/core@2.2.1
MIT
https://github.com/skyway/js-sdk
MIT License
Copyright (c) 2023 NTT DOCOMO BUSINESS, Inc.
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
---
@skyway-sdk/token@2.0.2
MIT
https://github.com/skyway/js-sdk
MIT License
Copyright (c) 2023 NTT DOCOMO BUSINESS, Inc.
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
---
@skyway-sdk/signaling-client@2.0.0
MIT
https://github.com/skyway/js-sdk
MIT License
Copyright (c) 2023 NTT DOCOMO BUSINESS, Inc.
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
---
@skyway-sdk/rtc-api-client@2.0.3
MIT
https://github.com/skyway/js-sdk
MIT License
Copyright (c) 2023 NTT DOCOMO BUSINESS, Inc.
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
---
@skyway-sdk/rtc-rpc-api-client@2.0.2
MIT
https://github.com/skyway/js-sdk
MIT License
Copyright (c) 2023 NTT DOCOMO BUSINESS, Inc.
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
---
@skyway-sdk/model@2.0.0
MIT
https://github.com/skyway/js-sdk
MIT License
Copyright (c) 2023 NTT DOCOMO BUSINESS, Inc.
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
---
@skyway-sdk/analytics-client@2.0.0
MIT
https://github.com/skyway/js-sdk
MIT License
Copyright (c) 2024 NTT DOCOMO BUSINESS, Inc.
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
---
@lukeed/csprng@1.1.0
MIT
https://github.com/lukeed/csprng
MIT License
Copyright (c) Luke Edwards <luke.edwards05@gmail.com> (lukeed.com)
Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
---
@lukeed/uuid@2.0.1
MIT
https://github.com/lukeed/uuid
MIT License
Copyright (c) Luke Edwards <luke.edwards05@gmail.com> (lukeed.com)
Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
---
@types/debug@4.1.12
MIT
https://github.com/DefinitelyTyped/DefinitelyTyped
MIT License
Copyright (c) Microsoft Corporation.
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE
---
@types/events@3.0.3
MIT
https://github.com/DefinitelyTyped/DefinitelyTyped
MIT License
Copyright (c) Microsoft Corporation.
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE
---
@types/ms@2.1.0
MIT
https://github.com/DefinitelyTyped/DefinitelyTyped
MIT License
Copyright (c) Microsoft Corporation.
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE
---
asynckit@0.4.0
MIT
https://github.com/alexindigo/asynckit
The MIT License (MIT)
Copyright (c) 2016 Alex Indigo
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
---
axios@1.12.0
MIT
https://github.com/axios/axios
# Copyright (c) 2014-present Matt Zabriskie & Collaborators
Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
---
bowser@2.11.0
MIT
https://github.com/lancedikson/bowser
Copyright 2015, Dustin Diaz (the "Original Author")
All rights reserved.
MIT License
Permission is hereby granted, free of charge, to any person
obtaining a copy of this software and associated documentation
files (the "Software"), to deal in the Software without
restriction, including without limitation the rights to use,
copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the
Software is furnished to do so, subject to the following
conditions:
The above copyright notice and this permission notice shall be
included in all copies or substantial portions of the Software.
Distributions of all or part of the Software intended to be used
by the recipients as they would use the unmodified Software,
containing modifications that substantially alter, remove, or
disable functionality of the Software, outside of the documented
configuration mechanisms provided by the Software, shall be
modified such that the Original Author's bug reporting email
addresses and urls are either replaced with the contact information
of the parties responsible for the changes, or removed entirely.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES
OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
OTHER DEALINGS IN THE SOFTWARE.
Except where noted, this license applies to any and all software
programs and associated documentation files created by the
Original Author, when distributed with the Software.
---
call-bind-apply-helpers@1.0.2
MIT
https://github.com/ljharb/call-bind-apply-helpers
MIT License
Copyright (c) 2024 Jordan Harband
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
---
combined-stream@1.0.8
MIT
https://github.com/felixge/node-combined-stream
---
debug@4.4.3
MIT
https://github.com/debug-js/debug
(The MIT License)
Copyright (c) 2014-2017 TJ Holowaychuk <tj@vision-media.ca>
Copyright (c) 2018-2021 Josh Junon
Permission is hereby granted, free of charge, to any person obtaining a copy of this software
and associated documentation files (the 'Software'), to deal in the Software without restriction,
including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense,
and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so,
subject to the following conditions:
The above copyright notice and this permission notice shall be included in all copies or substantial
portions of the Software.
THE SOFTWARE IS PROVIDED 'AS IS', WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT
LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE
SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
---
deepmerge@4.3.1
MIT
https://github.com/TehShrike/deepmerge
---
delayed-stream@1.0.0
MIT
https://github.com/felixge/node-delayed-stream
---
dunder-proto@1.0.1
MIT
https://github.com/es-shims/dunder-proto
MIT License
Copyright (c) 2024 ECMAScript Shims
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
---
es-define-property@1.0.1
MIT
https://github.com/ljharb/es-define-property
MIT License
Copyright (c) 2024 Jordan Harband
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
---
es-errors@1.3.0
MIT
https://github.com/ljharb/es-errors
MIT License
Copyright (c) 2024 Jordan Harband
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
---
es-object-atoms@1.1.1
MIT
https://github.com/ljharb/es-object-atoms
MIT License
Copyright (c) 2024 Jordan Harband
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
---
es-set-tostringtag@2.1.0
MIT
https://github.com/es-shims/es-set-tostringtag
MIT License
Copyright (c) 2022 ECMAScript Shims
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
---
events@3.3.0
MIT
https://github.com/Gozala/events
MIT
Copyright Joyent, Inc. and other Node contributors.
Permission is hereby granted, free of charge, to any person obtaining a
copy of this software and associated documentation files (the
"Software"), to deal in the Software without restriction, including
without limitation the rights to use, copy, modify, merge, publish,
distribute, sublicense, and/or sell copies of the Software, and to permit
persons to whom the Software is furnished to do so, subject to the
following conditions:
The above copyright notice and this permission notice shall be included
in all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN
NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE
USE OR OTHER DEALINGS IN THE SOFTWARE.
---
follow-redirects@1.15.11
MIT
https://github.com/follow-redirects/follow-redirects
Copyright 2014–present Olivier Lalonde <olalonde@gmail.com>, James Talmage <james@talmage.io>, Ruben Verborgh
Permission is hereby granted, free of charge, to any person obtaining a copy of
this software and associated documentation files (the "Software"), to deal in
the Software without restriction, including without limitation the rights to
use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies
of the Software, and to permit persons to whom the Software is furnished to do
so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR
IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
---
form-data@4.0.4
MIT
https://github.com/form-data/form-data
---
function-bind@1.1.2
MIT
https://github.com/Raynos/function-bind
Copyright (c) 2013 Raynos.
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
---
get-intrinsic@1.3.0
MIT
https://github.com/ljharb/get-intrinsic
MIT License
Copyright (c) 2020 Jordan Harband
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
---
get-proto@1.0.1
MIT
https://github.com/ljharb/get-proto
MIT License
Copyright (c) 2025 Jordan Harband
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
---
gopd@1.2.0
MIT
https://github.com/ljharb/gopd
MIT License
Copyright (c) 2022 Jordan Harband
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
---
has-symbols@1.1.0
MIT
https://github.com/inspect-js/has-symbols
MIT License
Copyright (c) 2016 Jordan Harband
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
---
has-tostringtag@1.0.2
MIT
https://github.com/inspect-js/has-tostringtag
MIT License
Copyright (c) 2021 Inspect JS
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
---
hasown@2.0.2
MIT
https://github.com/inspect-js/hasOwn
MIT License
Copyright (c) Jordan Harband and contributors
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
---
isomorphic-fetch@3.0.0
MIT
https://github.com/matthew-andrews/isomorphic-fetch
The MIT License (MIT)
Copyright (c) 2015 Matt Andrews
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
---
isomorphic-ws@4.0.1
MIT
https://github.com/heineiuo/isomorphic-ws
The MIT License (MIT)
Copyright (c) 2018 Zejin Zhuang <heineiuo@gmail.com>
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
---
jsrsasign@11.1.0
MIT
https://github.com/kjur/jsrsasign
---
jwt-decode@3.1.2
MIT
https://github.com/auth0/jwt-decode
The MIT License (MIT)
Copyright (c) 2015 Auth0, Inc. <support@auth0.com> (http://auth0.com)
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
---
lodash@4.17.21
MIT
https://github.com/lodash/lodash
Copyright OpenJS Foundation and other contributors <https://openjsf.org/>
Based on Underscore.js, copyright Jeremy Ashkenas,
DocumentCloud and Investigative Reporters & Editors <http://underscorejs.org/>
This software consists of voluntary contributions made by many
individuals. For exact contribution history, see the revision history
available at https://github.com/lodash/lodash
The following license applies to all parts of this software except as
documented below:
====
Permission is hereby granted, free of charge, to any person obtaining
a copy of this software and associated documentation files (the
"Software"), to deal in the Software without restriction, including
without limitation the rights to use, copy, modify, merge, publish,
distribute, sublicense, and/or sell copies of the Software, and to
permit persons to whom the Software is furnished to do so, subject to
the following conditions:
The above copyright notice and this permission notice shall be
included in all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
====
Copyright and related rights for sample code are waived via CC0. Sample
code is defined as all source code displayed within the prose of the
documentation.
CC0: http://creativecommons.org/publicdomain/zero/1.0/
====
Files located in the node_modules and vendor directories are externally
maintained libraries used by this software which have their own
licenses; we recommend you read them, as their terms may differ from the
terms above.
---
math-intrinsics@1.1.0
MIT
https://github.com/es-shims/math-intrinsics
MIT License
Copyright (c) 2024 ECMAScript Shims
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
---
mime-db@1.52.0
MIT
https://github.com/jshttp/mime-db
(The MIT License)
Copyright (c) 2014 Jonathan Ong <me@jongleberry.com>
Copyright (c) 2015-2022 Douglas Christopher Wilson <doug@somethingdoug.com>
Permission is hereby granted, free of charge, to any person obtaining
a copy of this software and associated documentation files (the
'Software'), to deal in the Software without restriction, including
without limitation the rights to use, copy, modify, merge, publish,
distribute, sublicense, and/or sell copies of the Software, and to
permit persons to whom the Software is furnished to do so, subject to
the following conditions:
The above copyright notice and this permission notice shall be
included in all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED 'AS IS', WITHOUT WARRANTY OF ANY KIND,
EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY
CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,
TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE
SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
---
mime-types@2.1.35
MIT
https://github.com/jshttp/mime-types
(The MIT License)
Copyright (c) 2014 Jonathan Ong <me@jongleberry.com>
Copyright (c) 2015 Douglas Christopher Wilson <doug@somethingdoug.com>
Permission is hereby granted, free of charge, to any person obtaining
a copy of this software and associated documentation files (the
'Software'), to deal in the Software without restriction, including
without limitation the rights to use, copy, modify, merge, publish,
distribute, sublicense, and/or sell copies of the Software, and to
permit persons to whom the Software is furnished to do so, subject to
the following conditions:
The above copyright notice and this permission notice shall be
included in all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED 'AS IS', WITHOUT WARRANTY OF ANY KIND,
EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY
CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,
TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE
SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
---
ms@2.1.3
MIT
https://github.com/vercel/ms
The MIT License (MIT)
Copyright (c) 2020 Vercel, Inc.
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
---
node-fetch@2.7.0
MIT
https://github.com/bitinn/node-fetch
The MIT License (MIT)
Copyright (c) 2016 David Frank
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
---
proxy-from-env@1.1.0
MIT
https://github.com/Rob--W/proxy-from-env
The MIT License
Copyright (C) 2016-2018 Rob Wu <rob@robwu.nl>
Permission is hereby granted, free of charge, to any person obtaining a copy of
this software and associated documentation files (the "Software"), to deal in
the Software without restriction, including without limitation the rights to
use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies
of the Software, and to permit persons to whom the Software is furnished to do
so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS
FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR
COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER
IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
---
sdp-transform@2.15.0
MIT
https://github.com/clux/sdp-transform
(The MIT License)
Copyright (c) 2013 Eirik Albrigtsen
Permission is hereby granted, free of charge, to any person obtaining
a copy of this software and associated documentation files (the
'Software'), to deal in the Software without restriction, including
without limitation the rights to use, copy, modify, merge, publish,
distribute, sublicense, and/or sell copies of the Software, and to
permit persons to whom the Software is furnished to do so, subject to
the following conditions:
The above copyright notice and this permission notice shall be
included in all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED 'AS IS', WITHOUT WARRANTY OF ANY KIND,
EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY
CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,
TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE
SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
---
sdp-transform@3.0.0
MIT
https://github.com/clux/sdp-transform
(The MIT License)
Copyright (c) 2013 Eirik Albrigtsen
Permission is hereby granted, free of charge, to any person obtaining
a copy of this software and associated documentation files (the
'Software'), to deal in the Software without restriction, including
without limitation the rights to use, copy, modify, merge, publish,
distribute, sublicense, and/or sell copies of the Software, and to
permit persons to whom the Software is furnished to do so, subject to
the following conditions:
The above copyright notice and this permission notice shall be
included in all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED 'AS IS', WITHOUT WARRANTY OF ANY KIND,
EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY
CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,
TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE
SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
---
supports-color@10.2.2
MIT
https://github.com/chalk/supports-color
MIT License
Copyright (c) Sindre Sorhus <sindresorhus@gmail.com> (https://sindresorhus.com)
Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
---
tr46@0.0.3
MIT
https://github.com/Sebmaster/tr46.js
The MIT License (MIT)
Copyright (c) Sebastian Mayr
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
---
ua-parser-js@1.0.40
MIT
https://github.com/faisalman/ua-parser-js
MIT License
Copyright (c) 2012-2024 Faisal Salman <<f@faisalman.com>>
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
---
uuid@9.0.1
MIT
https://github.com/uuidjs/uuid
The MIT License (MIT)
Copyright (c) 2010-2020 Robert Kieffer and other contributors
Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
---
whatwg-fetch@3.6.20
MIT
https://github.com/github/fetch
Copyright (c) 2014-2023 GitHub, Inc.
Permission is hereby granted, free of charge, to any person obtaining
a copy of this software and associated documentation files (the
"Software"), to deal in the Software without restriction, including
without limitation the rights to use, copy, modify, merge, publish,
distribute, sublicense, and/or sell copies of the Software, and to
permit persons to whom the Software is furnished to do so, subject to
the following conditions:
The above copyright notice and this permission notice shall be
included in all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
---
whatwg-url@5.0.0
MIT
https://github.com/jsdom/whatwg-url
---
ws@8.18.2
MIT
https://github.com/websockets/ws
Copyright (c) 2011 Einar Otto Stangvik <einaros@gmail.com>
Copyright (c) 2013 Arnout Kazemier and contributors
Copyright (c) 2016 Luigi Pinca and contributors
Permission is hereby granted, free of charge, to any person obtaining a copy of
this software and associated documentation files (the "Software"), to deal in
the Software without restriction, including without limitation the rights to
use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of
the Software, and to permit persons to whom the Software is furnished to do so,
subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS
FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR
COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER
IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
---
zod@3.25.67
MIT
https://github.com/colinhacks/zod
MIT License
Copyright (c) 2025 Colin McDonnell
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
---
zod-validation-error@3.5.2
MIT
https://github.com/causaly/zod-validation-error
(The MIT License)
Copyright 2022 Causaly, Inc <front-end@causaly.com>
Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
---
awaitqueue@3.3.0
ISC
https://github.com/versatica/awaitqueue
ISC License
Copyright © 2019, Iñaki Baz Castillo <ibc@aliax.net>
Permission to use, copy, modify, and/or distribute this software for any
purpose with or without fee is hereby granted, provided that the above
copyright notice and this permission notice appear in all copies.
THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
---
fake-mediastreamtrack@2.2.1
ISC
https://github.com/ibc/fake-mediastreamtrack
ISC License
Copyright © 2020, Iñaki Baz Castillo <ibc@aliax.net>
Permission to use, copy, modify, and/or distribute this software for any
purpose with or without fee is hereby granted, provided that the above
copyright notice and this permission notice appear in all copies.
THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
---
h264-profile-level-id@2.3.1
ISC
https://github.com/versatica/h264-profile-level-id
ISC License
Copyright © 2019, Iñaki Baz Castillo <ibc@aliax.net>
Permission to use, copy, modify, and/or distribute this software for any
purpose with or without fee is hereby granted, provided that the above
copyright notice and this permission notice appear in all copies.
THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
---
mediasoup-client@3.18.3
ISC
https://github.com/versatica/mediasoup-client
ISC License
Copyright © 2015, Iñaki Baz Castillo <ibc@aliax.net>
Permission to use, copy, modify, and/or distribute this software for any
purpose with or without fee is hereby granted, provided that the above
copyright notice and this permission notice appear in all copies.
THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
---
webidl-conversions@3.0.1
BSD-2-Clause
https://github.com/jsdom/webidl-conversions
# The BSD 2-Clause License
Copyright (c) 2014, Domenic Denicola
All rights reserved.
Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met:
1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer.
2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
---
*/