@stackone/transport 2.13.1 → 2.14.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/index.cjs +6 -6
- package/dist/index.mjs +5 -5
- package/package.json +2 -2
package/dist/index.cjs
CHANGED
|
@@ -110,7 +110,7 @@ Example:
|
|
|
110
110
|
* Copyright (c) 2023, Robert Eisele (robert@raw.org)
|
|
111
111
|
* Dual licensed under the MIT or GPL Version 2 licenses.
|
|
112
112
|
**/
|
|
113
|
-
(function(n){"use strict";var r=2e3,i={s:1,n:0,d:1};function assign(e,t){if(isNaN(e=parseInt(e,10)))throw InvalidParameter();return e*t}function newFraction(e,t){if(t===0)throw DivisionByZero();var n=Object.create(Fraction$2.prototype);n.s=e<0?-1:1,e=e<0?-e:e;var r=gcd(e,t);return n.n=e/r,n.d=t/r,n}function factorize(e){for(var t={},n=e,r=2,i=4;i<=n;){for(;n%r===0;)n/=r,t[r]=(t[r]||0)+1;i+=1+2*r++}return n===e?t[e]=(t[e]||0)+1:n>1&&(t[n]=(t[n]||0)+1),t}var a=__name(function(e,t){var n=0,r=1,a=1,o=0,s=0,c=0,l=1,u=1,d=0,f=1,p=1,m=1,h=1e7,g;if(e!=null)if(t!==void 0){if(n=e,r=t,a=n*r,n%1!=0||r%1!=0)throw NonIntegerParameter()}else switch(typeof e){case`object`:if(`d`in e&&`n`in e)n=e.n,r=e.d,`s`in e&&(n*=e.s);else if(0 in e)n=e[0],1 in e&&(r=e[1]);else throw InvalidParameter();a=n*r;break;case`number`:if(e<0&&(a=e,e=-e),e%1==0)n=e;else if(e>0){for(e>=1&&(u=10**Math.floor(1+Math.log(e)/Math.LN10),e/=u);f<=h&&m<=h;)if(g=(d+p)/(f+m),e===g){f+m<=h?(n=d+p,r=f+m):m>f?(n=p,r=m):(n=d,r=f);break}else e>g?(d+=p,f+=m):(p+=d,m+=f),f>h?(n=p,r=m):(n=d,r=f);n*=u}else (isNaN(e)||isNaN(t))&&(r=n=NaN);break;case`string`:if(f=e.match(/\d+|./g),f===null)throw InvalidParameter();if(f[d]===`-`?(a=-1,d++):f[d]===`+`&&d++,f.length===d+1?s=assign(f[d++],a):f[d+1]===`.`||f[d]===`.`?(f[d]!==`.`&&(o=assign(f[d++],a)),d++,(d+1===f.length||f[d+1]===`(`&&f[d+3]===`)`||f[d+1]===`'`&&f[d+3]===`'`)&&(s=assign(f[d],a),l=10**f[d].length,d++),(f[d]===`(`&&f[d+2]===`)`||f[d]===`'`&&f[d+2]===`'`)&&(c=assign(f[d+1],a),u=10**f[d+1].length-1,d+=3)):f[d+1]===`/`||f[d+1]===`:`?(s=assign(f[d],a),l=assign(f[d+2],1),d+=3):f[d+3]===`/`&&f[d+1]===` `&&(o=assign(f[d],a),s=assign(f[d+2],a),l=assign(f[d+4],1),d+=5),f.length<=d){r=l*u,a=n=c+r*o+u*s;break}default:throw InvalidParameter()}if(r===0)throw DivisionByZero();i.s=a<0?-1:1,i.n=Math.abs(n),i.d=Math.abs(r)},`parse`);function modpow(e,t,n){for(var r=1;t>0;e=e*e%n,t>>=1)t&1&&(r=r*e%n);return r}function cycleLen(e,t){for(;t%2==0;t/=2);for(;t%5==0;t/=5);if(t===1)return 0;for(var n=10%t,i=1;n!==1;i++)if(n=n*10%t,i>r)return 0;return i}function cycleStart(e,t,n){for(var r=1,i=modpow(10,n,t),a=0;a<300;a++){if(r===i)return a;r=r*10%t,i=i*10%t}return 0}function gcd(e,t){if(!e)return t;if(!t)return e;for(;;){if(e%=t,!e)return t;if(t%=e,!t)return e}}function Fraction$2(e,t){if(a(e,t),this instanceof Fraction$2)e=gcd(i.d,i.n),this.s=i.s,this.n=i.n/e,this.d=i.d/e;else return newFraction(i.s*i.n,i.d)}__name(Fraction$2,`Fraction`);var DivisionByZero=function(){return Error(`Division by Zero`)},InvalidParameter=function(){return Error(`Invalid argument`)},NonIntegerParameter=function(){return Error(`Parameters must be integer`)};Fraction$2.prototype={s:1,n:0,d:1,abs:function(){return newFraction(this.n,this.d)},neg:function(){return newFraction(-this.s*this.n,this.d)},add:function(e,t){return a(e,t),newFraction(this.s*this.n*i.d+i.s*this.d*i.n,this.d*i.d)},sub:function(e,t){return a(e,t),newFraction(this.s*this.n*i.d-i.s*this.d*i.n,this.d*i.d)},mul:function(e,t){return a(e,t),newFraction(this.s*i.s*this.n*i.n,this.d*i.d)},div:function(e,t){return a(e,t),newFraction(this.s*i.s*this.n*i.d,this.d*i.n)},clone:function(){return newFraction(this.s*this.n,this.d)},mod:function(e,t){if(isNaN(this.n)||isNaN(this.d))return new Fraction$2(NaN);if(e===void 0)return newFraction(this.s*this.n%this.d,1);if(a(e,t),i.n===0&&this.d===0)throw DivisionByZero();return newFraction(this.s*(i.d*this.n)%(i.n*this.d),i.d*this.d)},gcd:function(e,t){return a(e,t),newFraction(gcd(i.n,this.n)*gcd(i.d,this.d),i.d*this.d)},lcm:function(e,t){return a(e,t),i.n===0&&this.n===0?newFraction(0,1):newFraction(i.n*this.n,gcd(i.n,this.n)*gcd(i.d,this.d))},ceil:function(e){return e=10**(e||0),isNaN(this.n)||isNaN(this.d)?new Fraction$2(NaN):newFraction(Math.ceil(e*this.s*this.n/this.d),e)},floor:function(e){return e=10**(e||0),isNaN(this.n)||isNaN(this.d)?new Fraction$2(NaN):newFraction(Math.floor(e*this.s*this.n/this.d),e)},round:function(e){return e=10**(e||0),isNaN(this.n)||isNaN(this.d)?new Fraction$2(NaN):newFraction(Math.round(e*this.s*this.n/this.d),e)},inverse:function(){return newFraction(this.s*this.d,this.n)},pow:function(e,t){if(a(e,t),i.d===1)return i.s<0?newFraction((this.s*this.d)**+i.n,this.n**+i.n):newFraction((this.s*this.n)**+i.n,this.d**+i.n);if(this.s<0)return null;var n=factorize(this.n),r=factorize(this.d),o=1,s=1;for(var c in n)if(c!==`1`){if(c===`0`){o=0;break}if(n[c]*=i.n,n[c]%i.d===0)n[c]/=i.d;else return null;o*=c**+n[c]}for(var c in r)if(c!==`1`){if(r[c]*=i.n,r[c]%i.d===0)r[c]/=i.d;else return null;s*=c**+r[c]}return i.s<0?newFraction(s,o):newFraction(o,s)},equals:function(e,t){return a(e,t),this.s*this.n*i.d===i.s*i.n*this.d},compare:function(e,t){a(e,t);var n=this.s*this.n*i.d-i.s*i.n*this.d;return(0<n)-(n<0)},simplify:function(e){if(isNaN(this.n)||isNaN(this.d))return this;e||=.001;for(var t=this.abs(),n=t.toContinued(),r=1;r<n.length;r++){for(var i=newFraction(n[r-1],1),a=r-2;a>=0;a--)i=i.inverse().add(n[a]);if(Math.abs(i.sub(t).valueOf())<e)return i.mul(this.s)}return this},divisible:function(e,t){return a(e,t),!(!(i.n*this.d)||this.n*i.d%(i.n*this.d))},valueOf:function(){return this.s*this.n/this.d},toFraction:function(e){var t,n=``,r=this.n,i=this.d;return this.s<0&&(n+=`-`),i===1?n+=r:(e&&(t=Math.floor(r/i))>0&&(n+=t,n+=` `,r%=i),n+=r,n+=`/`,n+=i),n},toLatex:function(e){var t,n=``,r=this.n,i=this.d;return this.s<0&&(n+=`-`),i===1?n+=r:(e&&(t=Math.floor(r/i))>0&&(n+=t,r%=i),n+=`\\frac{`,n+=r,n+=`}{`,n+=i,n+=`}`),n},toContinued:function(){var e,t=this.n,n=this.d,r=[];if(isNaN(t)||isNaN(n))return r;do r.push(Math.floor(t/n)),e=t%n,t=n,n=e;while(t!==1);return r},toString:function(e){var t=this.n,n=this.d;if(isNaN(t)||isNaN(n))return`NaN`;e||=15;var r=cycleLen(t,n),i=cycleStart(t,n,r),a=this.s<0?`-`:``;if(a+=t/n|0,t%=n,t*=10,t&&(a+=`.`),r){for(var o=i;o--;)a+=t/n|0,t%=n,t*=10;a+=`(`;for(var o=r;o--;)a+=t/n|0,t%=n,t*=10;a+=`)`}else for(var o=e;t&&o--;)a+=t/n|0,t%=n,t*=10;return a}},typeof e==`object`?(Object.defineProperty(Fraction$2,`__esModule`,{value:!0}),Fraction$2.default=Fraction$2,Fraction$2.Fraction=Fraction$2,t.exports=Fraction$2):n.Fraction=Fraction$2})(e)})),$=__toESM(Et(),1),Dt=`Fraction`,Ot=[],kt=factory(Dt,Ot,()=>(Object.defineProperty($.default,`name`,{value:`Fraction`}),$.default.prototype.constructor=$.default,$.default.prototype.type=`Fraction`,$.default.prototype.isFraction=!0,$.default.prototype.toJSON=function(){return{mathjs:`Fraction`,n:this.s*this.n,d:this.d}},$.default.fromJSON=function(e){return new $.default(e)},$.default),{isClass:!0}),At=`Matrix`,jt=[],Mt=factory(At,jt,()=>{function Matrix$1(){if(!(this instanceof Matrix$1))throw SyntaxError(`Constructor must be called with the new operator`)}return __name(Matrix$1,`Matrix`),Matrix$1.prototype.type=`Matrix`,Matrix$1.prototype.isMatrix=!0,Matrix$1.prototype.storage=function(){throw Error(`Cannot invoke storage on a Matrix interface`)},Matrix$1.prototype.datatype=function(){throw Error(`Cannot invoke datatype on a Matrix interface`)},Matrix$1.prototype.create=function(e,t){throw Error(`Cannot invoke create on a Matrix interface`)},Matrix$1.prototype.subset=function(e,t,n){throw Error(`Cannot invoke subset on a Matrix interface`)},Matrix$1.prototype.get=function(e){throw Error(`Cannot invoke get on a Matrix interface`)},Matrix$1.prototype.set=function(e,t,n){throw Error(`Cannot invoke set on a Matrix interface`)},Matrix$1.prototype.resize=function(e,t){throw Error(`Cannot invoke resize on a Matrix interface`)},Matrix$1.prototype.reshape=function(e,t){throw Error(`Cannot invoke reshape on a Matrix interface`)},Matrix$1.prototype.clone=function(){throw Error(`Cannot invoke clone on a Matrix interface`)},Matrix$1.prototype.size=function(){throw Error(`Cannot invoke size on a Matrix interface`)},Matrix$1.prototype.map=function(e,t){throw Error(`Cannot invoke map on a Matrix interface`)},Matrix$1.prototype.forEach=function(e){throw Error(`Cannot invoke forEach on a Matrix interface`)},Matrix$1.prototype[Symbol.iterator]=function(){throw Error(`Cannot iterate a Matrix interface`)},Matrix$1.prototype.toArray=function(){throw Error(`Cannot invoke toArray on a Matrix interface`)},Matrix$1.prototype.valueOf=function(){throw Error(`Cannot invoke valueOf on a Matrix interface`)},Matrix$1.prototype.format=function(e){throw Error(`Cannot invoke format on a Matrix interface`)},Matrix$1.prototype.toString=function(){throw Error(`Cannot invoke toString on a Matrix interface`)},Matrix$1},{isClass:!0});function maxArgumentCount(e){return Object.keys(e.signatures||{}).reduce(function(e,t){var n=(t.match(/,/g)||[]).length+1;return Math.max(e,n)},-1)}var Nt=`DenseMatrix`,Pt=[`Matrix`],Ft=factory(Nt,Pt,e=>{var{Matrix:t}=e;function DenseMatrix$1(e,t){if(!(this instanceof DenseMatrix$1))throw SyntaxError(`Constructor must be called with the new operator`);if(t&&!isString$1(t))throw Error(`Invalid datatype: `+t);if(isMatrix(e))e.type===`DenseMatrix`?(this._data=clone$2(e._data),this._size=clone$2(e._size),this._datatype=t||e._datatype):(this._data=e.toArray(),this._size=e.size(),this._datatype=t||e._datatype);else if(e&&L(e.data)&&L(e.size))this._data=e.data,this._size=e.size,validate$1(this._data,this._size),this._datatype=t||e.datatype;else if(L(e))this._data=preprocess(e),this._size=arraySize(this._data),validate$1(this._data,this._size),this._datatype=t;else if(e)throw TypeError(`Unsupported type of data (`+typeOf(e)+`)`);else this._data=[],this._size=[0],this._datatype=t}__name(DenseMatrix$1,`DenseMatrix`),DenseMatrix$1.prototype=new t,DenseMatrix$1.prototype.createDenseMatrix=function(e,t){return new DenseMatrix$1(e,t)},Object.defineProperty(DenseMatrix$1,`name`,{value:`DenseMatrix`}),DenseMatrix$1.prototype.constructor=DenseMatrix$1,DenseMatrix$1.prototype.type=`DenseMatrix`,DenseMatrix$1.prototype.isDenseMatrix=!0,DenseMatrix$1.prototype.getDataType=function(){return getArrayDataType(this._data,typeOf)},DenseMatrix$1.prototype.storage=function(){return`dense`},DenseMatrix$1.prototype.datatype=function(){return this._datatype},DenseMatrix$1.prototype.create=function(e,t){return new DenseMatrix$1(e,t)},DenseMatrix$1.prototype.subset=function(e,t,n){switch(arguments.length){case 1:return _get(this,e);case 2:case 3:return _set(this,e,t,n);default:throw SyntaxError(`Wrong number of arguments`)}},DenseMatrix$1.prototype.get=function(e){if(!L(e))throw TypeError(`Array expected`);if(e.length!==this._size.length)throw new DimensionError(e.length,this._size.length);for(var t=0;t<e.length;t++)validateIndex(e[t],this._size[t]);for(var n=this._data,r=0,i=e.length;r<i;r++){var a=e[r];validateIndex(a,n.length),n=n[a]}return n},DenseMatrix$1.prototype.set=function(e,t,n){if(!L(e))throw TypeError(`Array expected`);if(e.length<this._size.length)throw new DimensionError(e.length,this._size.length,`<`);var r,i,a,o=e.map(function(e){return e+1});_fit(this,o,n);var s=this._data;for(r=0,i=e.length-1;r<i;r++)a=e[r],validateIndex(a,s.length),s=s[a];return a=e[e.length-1],validateIndex(a,s.length),s[a]=t,this};function _get(e,t){if(!isIndex(t))throw TypeError(`Invalid index`);if(t.isScalar())return e.get(t.min());var n=t.size();if(n.length!==e._size.length)throw new DimensionError(n.length,e._size.length);for(var r=t.min(),i=t.max(),a=0,o=e._size.length;a<o;a++)validateIndex(r[a],e._size[a]),validateIndex(i[a],e._size[a]);return new DenseMatrix$1(_getSubmatrix(e._data,t,n.length,0),e._datatype)}function _getSubmatrix(e,t,n,r){var i=r===n-1,a=t.dimension(r);return i?a.map(function(t){return validateIndex(t,e.length),e[t]}).valueOf():a.map(function(i){validateIndex(i,e.length);var a=e[i];return _getSubmatrix(a,t,n,r+1)}).valueOf()}function _set(e,t,n,r){if(!t||t.isIndex!==!0)throw TypeError(`Invalid index`);var i=t.size(),a=t.isScalar(),o;if(isMatrix(n)?(o=n.size(),n=n.valueOf()):o=arraySize(n),a){if(o.length!==0)throw TypeError(`Scalar expected`);e.set(t.min(),n,r)}else{if(!deepStrictEqual(o,i))try{n=o.length===0?broadcastTo([n],i):broadcastTo(n,i),o=arraySize(n)}catch{}if(i.length<e._size.length)throw new DimensionError(i.length,e._size.length,`<`);if(o.length<i.length){for(var s=0,c=0;i[s]===1&&o[s]===1;)s++;for(;i[s]===1;)c++,s++;n=unsqueeze(n,i.length,c,o)}if(!deepStrictEqual(i,o))throw new DimensionError(i,o,`>`);_fit(e,t.max().map(function(e){return e+1}),r);var l=i.length;_setSubmatrix(e._data,t,n,l,0)}return e}function _setSubmatrix(e,t,n,r,i){var a=i===r-1,o=t.dimension(i);a?o.forEach(function(t,r){validateIndex(t),e[t]=n[r[0]]}):o.forEach(function(a,o){validateIndex(a),_setSubmatrix(e[a],t,n[o[0]],r,i+1)})}DenseMatrix$1.prototype.resize=function(e,t,n){if(!isCollection(e))throw TypeError(`Array or Matrix expected`);var r=e.valueOf().map(e=>Array.isArray(e)&&e.length===1?e[0]:e);return _resize$1(n?this.clone():this,r,t)};function _resize$1(e,t,n){if(t.length===0){for(var r=e._data;L(r);)r=r[0];return r}return e._size=t.slice(0),e._data=resize(e._data,e._size,n),e}__name(_resize$1,`_resize`),DenseMatrix$1.prototype.reshape=function(e,t){var n=t?this.clone():this;return n._data=reshape(n._data,e),n._size=processSizesWildcard(e,n._size.reduce((e,t)=>e*t)),n};function _fit(e,t,n){for(var r=e._size.slice(0),i=!1;r.length<t.length;)r.push(0),i=!0;for(var a=0,o=t.length;a<o;a++)t[a]>r[a]&&(r[a]=t[a],i=!0);i&&_resize$1(e,r,n)}DenseMatrix$1.prototype.clone=function(){return new DenseMatrix$1({data:clone$2(this._data),size:clone$2(this._size),datatype:this._datatype})},DenseMatrix$1.prototype.size=function(){return this._size.slice(0)},DenseMatrix$1.prototype.map=function(e){var t=this,n=maxArgumentCount(e),r=function recurse(r,i){return L(r)?r.map(function(e,t){return recurse(e,i.concat(t))}):n===1?e(r):n===2?e(r,i):e(r,i,t)}(this._data,[]);return new DenseMatrix$1(r,this._datatype===void 0?void 0:getArrayDataType(r,typeOf))},DenseMatrix$1.prototype.forEach=function(e){var t=this;(function recurse(n,r){L(n)?n.forEach(function(e,t){recurse(e,r.concat(t))}):e(n,r,t)})(this._data,[])},DenseMatrix$1.prototype[Symbol.iterator]=function*(){yield*function*recurse(e,t){if(L(e))for(var n=0;n<e.length;n++)yield*recurse(e[n],t.concat(n));else yield{value:e,index:t}}(this._data,[])},DenseMatrix$1.prototype.rows=function(){var e=[];if(this.size().length!==2)throw TypeError(`Rows can only be returned for a 2D matrix.`);for(var t of this._data)e.push(new DenseMatrix$1([t],this._datatype));return e},DenseMatrix$1.prototype.columns=function(){var e=this,t=[],n=this.size();if(n.length!==2)throw TypeError(`Rows can only be returned for a 2D matrix.`);for(var r=this._data,i=function _loop$1(n){var i=r.map(e=>[e[n]]);t.push(new DenseMatrix$1(i,e._datatype))},a=0;a<n[1];a++)i(a);return t},DenseMatrix$1.prototype.toArray=function(){return clone$2(this._data)},DenseMatrix$1.prototype.valueOf=function(){return this._data},DenseMatrix$1.prototype.format=function(e){return format(this._data,e)},DenseMatrix$1.prototype.toString=function(){return format(this._data)},DenseMatrix$1.prototype.toJSON=function(){return{mathjs:`DenseMatrix`,data:this._data,size:this._size,datatype:this._datatype}},DenseMatrix$1.prototype.diagonal=function(e){if(e){if(isBigNumber(e)&&(e=e.toNumber()),!isNumber$1(e)||!isInteger(e))throw TypeError(`The parameter k must be an integer number`)}else e=0;for(var t=e>0?e:0,n=e<0?-e:0,r=this._size[0],i=this._size[1],a=Math.min(r-n,i-t),o=[],s=0;s<a;s++)o[s]=this._data[s+n][s+t];return new DenseMatrix$1({data:o,size:[a],datatype:this._datatype})},DenseMatrix$1.diagonal=function(e,t,n,r){if(!L(e))throw TypeError(`Array expected, size parameter`);if(e.length!==2)throw Error(`Only two dimensions matrix are supported`);if(e=e.map(function(e){if(isBigNumber(e)&&(e=e.toNumber()),!isNumber$1(e)||!isInteger(e)||e<1)throw Error(`Size values must be positive integers`);return e}),n){if(isBigNumber(n)&&(n=n.toNumber()),!isNumber$1(n)||!isInteger(n))throw TypeError(`The parameter k must be an integer number`)}else n=0;var i=n>0?n:0,a=n<0?-n:0,o=e[0],s=e[1],c=Math.min(o-a,s-i),l;if(L(t)){if(t.length!==c)throw Error(`Invalid value array length`);l=function _value$1(e){return t[e]}}else if(isMatrix(t)){var u=t.size();if(u.length!==1||u[0]!==c)throw Error(`Invalid matrix length`);l=function _value$1(e){return t.get([e])}}else l=function _value$1(){return t};r||=isBigNumber(l(0))?l(0).mul(0):0;var d=[];if(e.length>0){d=resize(d,e,r);for(var f=0;f<c;f++)d[f+a][f+i]=l(f)}return new DenseMatrix$1({data:d,size:[o,s]})},DenseMatrix$1.fromJSON=function(e){return new DenseMatrix$1(e)},DenseMatrix$1.prototype.swapRows=function(e,t){if(!isNumber$1(e)||!isInteger(e)||!isNumber$1(t)||!isInteger(t))throw Error(`Row index must be positive integers`);if(this._size.length!==2)throw Error(`Only two dimensional matrix is supported`);return validateIndex(e,this._size[0]),validateIndex(t,this._size[0]),DenseMatrix$1._swapRows(e,t,this._data),this},DenseMatrix$1._swapRows=function(e,t,n){var r=n[e];n[e]=n[t],n[t]=r};function preprocess(e){return isMatrix(e)?preprocess(e.valueOf()):L(e)?e.map(preprocess):e}return DenseMatrix$1},{isClass:!0});function deepMap(e,t,n){return e&&typeof e.map==`function`?e.map(function(e){return deepMap(e,t,n)}):t(e)}var It=`isNumeric`,Lt=[`typed`],Rt=factory(It,Lt,e=>{var{typed:t}=e;return t(It,{"number | BigNumber | Fraction | boolean":()=>!0,"Complex | Unit | string | null | undefined | Node":()=>!1,"Array | Matrix":t.referToSelf(e=>t=>deepMap(t,e))})}),zt=`hasNumericValue`,Bt=[`typed`,`isNumeric`],Vt=factory(zt,Bt,e=>{var{typed:t,isNumeric:n}=e;return t(zt,{boolean:()=>!0,string:function string(e){return e.trim().length>0&&!isNaN(Number(e))},any:function any(e){return n(e)}})}),Ht=xt({config:qe}),Ut=Tt({}),Wt=kt({}),Gt=Mt({}),Kt=Ft({Matrix:Gt}),qt=nt({BigNumber:Ht,Complex:Ut,DenseMatrix:Kt,Fraction:Wt}),Jt=Rt({typed:qt}),Yt=Vt({isNumeric:Jt,typed:qt});const shortTimePeriodIsMilliseconds=e=>{let t=Number(e);return Number.isNaN(t)?!1:t>=120&&t<=36e4},resolveWaitTimeMs=e=>{let t=Number(e),n=Date.now();return Number.isNaN(t)?n+1e3:!shortTimePeriodIsMilliseconds(t)&&(0,o.isFutureUnixTimestamp)(t)?adjustUnixTimestamp(t):shortTimePeriodIsMilliseconds(t)?n+t:n+t*I},Xt=`ratelimitlimit`,Zt=`ratelimitremaining`,Qt=`ratelimitreset`,$t=`ratelimitconcurrencylimit`,en=`ratelimitconcurrencyremaining`,tn=`ratelimitconcurrencyreset`,superNormalizeHeaders=e=>{let t={};for(let[n,r]of Object.entries(e)){let e=n.toLowerCase().replace(/^x-/,``).replace(/concurren.+-/g,`concurrency-`).replace(/-/g,``);t[e]=Yt(r)?Number(r):null}return t},extractRateLimitHeaders=e=>{let t=superNormalizeHeaders(e);return{rateLimitLimit:t.ratelimitlimit,rateLimitRemaining:t.ratelimitremaining,rateLimitReset:resolveWaitTimeMs(t.ratelimitreset),concurrencyLimit:t.ratelimitconcurrencylimit,concurrencyRemaining:t.ratelimitconcurrencyremaining,concurrencyReset:resolveWaitTimeMs(t.ratelimitconcurrencyreset)}},generateRequestKey=e=>{let{accountSecureId:t,service:n,resource:r,subResource:i,childResource:a,action:s,behaviours:c}=e??{};return[t,n,r,s].some(o.isMissing)?null:[t,n,r,i,a,s,...c??[]].filter(Boolean).join(`-`)},getRetryAfterWaitTime=(e,t=10,n=1)=>{let r=Date.now();return(0,o.isFutureUnixTimestamp)(e)||(0,o.isNumber)(e)?evaluateRetryAfterNumber(Number(e),r,t,n):isString$1(e)&&e!==``?evaluateRetryAfterString(e,r,t,n):n},evaluateRetryAfterNumber=(e,t,n=10,r=1)=>{if(e<n)return e;let i=adjustUnixTimestamp(e);if(i>t){let e=Math.floor((i-t)/I);return e>0&&e<n?e:r}return r},evaluateRetryAfterString=(e,t,n=10,r=1)=>{if(Be.test(e)){let t=parseFloat(e);return t>0&&t<n?t:r}let i=new Date(e);if(Number.isNaN(i.getTime()))return r;let a=i.getTime();if(a>t){let e=Math.floor((a-t)/I);return e>0&&e<n?e:r}return r},retryErrorInterceptor=({axiosInstance:e,logger:t,requestConfig:n,context:r})=>__name(async i=>{let{response:a,config:s}=i;if(s?.signal?.aborted)return Promise.reject(createAxiosError(`Request aborted`,s,`ERR_CANCELED`,a));let{status:c,retryAfter:l}=convertError(a,r,n,t);if(c===429&&(0,o.notMissing)(s)){let n=getRetryAfterWaitTime(l);if(s._retryCount>=5)return t?.warning({category:`http-transport`,message:`Max retries exceeded for ${s?.url}. Aborting.`,context:{...r??{},retryAfterHeader:l,retryAfterAsNumber:n}}),Promise.reject(i);let c=s._retryCount??0,u={...s,_retryCount:c+1},d=l?n*I:(0,o.exponentialBackoffInMS)(u._retryCount);return t?.debug({category:`http-transport`,message:`Received 429 error from ${s?.url}`,context:{...r??{},retryAfterHeader:l,calculatedRetryAfter:d}}),await abortableDelay(d,s,a),e?.request(u)}return Promise.reject(i)},`retryErrorInterceptor`),convertError=(e,t,n,r)=>{let{provider:i}=t??{},{status:a,headers:s,data:c}=e??{},{retryafter:l}=superNormalizeHeaders(s??{});if((0,o.isMissing)(i)||(0,o.isMissing)(e))return r?.warning({category:`http-transport`,message:`Invalid parameters for convertError`,context:{...t,responseIsMissing:(0,o.isMissing)(e),providerIsMissing:(0,o.isMissing)(i),status:e?.status??`undefined`,statusText:e?.statusText??`undefined`,retryafter:l??`undefined`}}),{status:a,retryAfter:l};let u=n?.rateLimits?.mappedRateLimitErrors;if((0,o.notMissing)(u)&&(0,o.notMissing)(c))for(let e of u){let{errorStatus:t,errorMessagePath:n,errorMessage:r,retryAfterPath:i,retryAfterUnit:u,retryAfterValue:d}=e;if(t!==a)continue;let f=n??`message`,m=testMessage((0,o.isObject)(c)?(0,p.JSONPath)({path:f,json:c})[0]:c,r);if(t===a&&m){let e=convertRetryAfter(d??extractRetryAfter(s,i),u);return{status:429,retryAfter:l??e}}}return{status:a,retryAfter:l}},testMessage=(e,t)=>t instanceof RegExp?t.test(e??``):e?.includes(t)??!1,extractRetryAfter=(e,t)=>(0,o.notMissing)(t)&&(0,o.notMissing)(e)?(0,p.JSONPath)({path:t,json:e})[0]:null,convertRetryAfter=(e,t=`seconds`)=>(0,o.notMissing)(e)?transformToSeconds(e,t):null,transformToSeconds=(e,t)=>{if(t===`seconds`)return typeof e==`string`?parseFloat(e):e;if(t===`milliseconds`)return(typeof e==`string`?parseFloat(e):e)/I;if(t===`date`){let t=typeof e==`string`&&!isNaN(Number(e))?parseFloat(e):e,n=new Date(t);if(isNaN(n.getTime()))throw Error(`Invalid date value`);return n.getTime()}throw Error(`Invalid type`)},nn=`rateLimitErrorInterceptor`,rateLimitErrorInterceptor=({axiosInstance:e,logger:t,requestConfig:n,context:r,concurrencyManager:i})=>__name(async a=>{let{response:s,config:c}=a,l=c?.signal;if((0,o.isMissing)(r)||(0,o.isMissing)(c))return t?.warning({category:`HttpClient`,message:`No context or config for this response - that doesn't seem right.`,context:{interceptor:nn,...c,httpsAgent:void 0,headers:void 0,hasContext:(0,o.notMissing)(r),hasConfig:(0,o.notMissing)(c)},code:F.InterceptorContextNotPresent}),Promise.reject(a);if((0,o.isMissing)(i))return t?.error({category:`HttpClient`,message:`ConcurrencyManager is not initialized`,context:{interceptor:nn,...c,httpsAgent:void 0,headers:void 0,concurrencyManagerInitialized:(0,o.notMissing)(i)},code:F.RateLimitOrConcurrencyManagerNotInitialized}),Promise.reject(a);let{requestId:u,targetConcurrencyKey:d,leaseSubscription:f,setRemovalSubscription:p}=c?.requestMetadata??{};if(!((0,o.notMissing)(u)&&(0,o.notMissing)(d)&&await i.releaseRequest(u,d))&&(0,o.notMissing)(c?.requestMetadata)&&t?.error({category:`HttpClient`,message:`Failed to release request from concurrency manager`,context:{...r,interceptor:nn,requestId:u,targetConcurrencyKey:d,leaseSubscription:f,setRemovalSubscription:p},code:F.RateLimiterReleaseRequestFailed}),l?.aborted)return Promise.reject(createAxiosError(`Request aborted`,c,`ERR_CANCELED`,s));let{status:m,retryAfter:h}=convertError(s,r,n,t);if(m===429&&(0,o.notMissing)(c)){let n=getRetryAfterWaitTime(h);if(c._retryCount>=5)return t?.warning({category:`HttpClient`,message:`Max retries exceeded for ${c.url}. Aborting.`,context:{...r??{},...c.requestMetadata??{},retryAfterHeader:h,retryAfterAsNumber:n}}),Promise.reject(a);let i=c?._retryCount??0,l={...c,_retryCount:i+1},u=h?n*I:(0,o.exponentialBackoffInMS)(l._retryCount);return t?.debug({category:`HttpClient`,message:`Received 429 error from ${c.url}`,context:{...r,retryAfterHeader:h,calculatedRetryAfter:u}}),await abortableDelay(u,c,s),e?.request(l)}return Promise.reject(a)},`rateLimitErrorInterceptor`),rn=`rateLimitResponseInterceptor`,rateLimitResponseInterceptor=({logger:e,context:t,concurrencyManager:n})=>__name(async r=>{let i=r?.config,a=i?.signal;if((0,o.isMissing)(t))e?.warning({category:`HttpClient`,message:`No context for this response - that doesn't seem right.`,context:{interceptor:rn,...i,httpsAgent:void 0,headers:void 0}});else if((0,o.isMissing)(n))return e?.error({category:`HttpClient`,message:`ConcurrencyManager is not initialized`,context:{interceptor:rn,...i,httpsAgent:void 0,headers:void 0,concurrencyManagerInitialized:(0,o.notMissing)(n)},code:F.RateLimitOrConcurrencyManagerNotInitialized}),r;else if((0,o.notMissing)(t.provider)&&(0,o.notMissing)(t.accountSecureId)){let t=r?.headers;if((0,o.notMissing)(t)){let n=extractRateLimitHeaders(t);e?.debug({category:`HttpClient`,message:`Rate limit headers extracted`,context:{interceptor:rn,rateLimitHeaders:n}})}let{requestId:s,targetConcurrencyKey:c,leaseSubscription:l,setRemovalSubscription:u}=i?.requestMetadata??{};if(await n.releaseRequest(s,c)||e?.error({category:`HttpClient`,message:`Failed to release request from concurrency manager`,context:{interceptor:rn,requestId:s,targetConcurrencyKey:c,leaseSubscription:l,setRemovalSubscription:u},code:F.RateLimiterReleaseRequestFailed}),a?.aborted)return Promise.reject(createAxiosError(`Request aborted`,i,`ERR_CANCELED`,r))}return r},`rateLimitResponseInterceptor`),validateRequestInterceptor=e=>(e.validateStatus??=e=>e>=200&&e<300,e),an=[{onFulfilled:validateRequestInterceptor,onRejected:null,options:void 0}],on=[{onFulfilled:null,onRejected:retryErrorInterceptor},{onFulfilled:null,onRejected:abortErrorInterceptor}],sn=[{onFulfilled:validateRequestInterceptor,onRejected:null,options:void 0},{onFulfilled:checkConcurrencyInterceptor,onRejected:null,options:void 0}],cn=[{onFulfilled:rateLimitResponseInterceptor,onRejected:rateLimitErrorInterceptor},{onFulfilled:null,onRejected:abortErrorInterceptor}],un=1,dn=1e3,fn=0,pn=59,mn=.8,hn=500;var RateLimitManager=class extends ScriptManager{constructor(...e){super(...e),this.name=`RateLimitManager`}async additionalInitialization(){}getDynamicMaxWaitTime(e,t,n,r=59,i=.8,a=500){this.readyCheck();let o=e.subPools?.find(e=>e.urlPattern instanceof RegExp?e.urlPattern.test(n??``):n?.includes(e.urlPattern))?.rateLimit??e.mainRatelimit;if(o<=0)throw Error(`Requests per second (rps) must be greater than 0.`);let s=t.subPools?.find(e=>e.urlPattern instanceof RegExp?e.urlPattern.test(n??``):n?.includes(e.urlPattern))?.maxConcurrency??t.mainMaxConcurrency;if(s<=0)throw Error(`Concurrency must be greater than 0.`);let c=r*i,l=1/Math.min(o,s/(a/1e3)),u=Math.max(7.5,c*l);return Math.min(c,u)}async getWaitTime(e,t,n){this.readyCheck();let r=`rateLimit:${e}`,i=t.subPools?.find(e=>e.urlPattern instanceof RegExp?e.urlPattern.test(n??``):n?.includes(e.urlPattern))?.subPoolKey,a=(0,o.notMissing)(i)?`${r}-${i}`:r,{mainRatelimit:s,subPools:c}=t,l=[{key:r,rateLimit:s},...c?.map(e=>{let{subPoolKey:t,rateLimit:n}=e;return{key:`${r}-${t}`,rateLimit:n}})??[]],u=l.map(e=>e.key),d=l.map(e=>e.rateLimit);return await this.executeScript(Pe.incr,[a,...u],[s.toString(),...d.map(String)])}readyCheck(){if(!this.cacheClient||!this.scriptMap?.size)throw Error(`RateLimitManager not ready`)}isReady(){return!!this?.cacheClient&&!!this?.scriptMap?.size}close(){this.scriptMap?.clear(),this.reset()}},SingletonManager=class{static{this.instances=new Map}static async prepare(e,t,...n){if(!this.instances.has(e)){let t=new e;t.getSingleton=e=>{let t=this.instances.get(e);if((0,o.isMissing)(t))throw Error(`Singleton ${e.name} not prepared yet`);if(t.hasInitFailed?.())throw Error(`${e.name} initialization failed`);let n=t.getInstanceIfReady?.();if((0,o.notMissing)(n))return n;throw Error(`${e.name} not ready`)},this.instances.set(e,t)}let r=this.instances.get(e);try{return await r.getInstance(t,...n)}catch(t){throw r.hasInitFailed?.()&&this.instances.delete(e),t}}static getIfReady(e){return this.instances.get(e)?.getInstanceIfReady?.()??null}static reset(e){this.instances.get(e)?.reset?.(),this.instances.delete(e)}static cleanupFailed(){let e=0;for(let[t,n]of this.instances){let r=n;r?.hasInitFailed?.()&&(r?.reset?.(),this.instances.delete(t),e++)}return e}};let gn=function(e){return e.HttpTransportInstanceCreateError=`HttpTransportInstanceCreateError`,e}({});const getTransportInstance=async({logger:e,redisClientConfig:t,context:n,requestConfig:r,httpsAgentConfig:i}={})=>{let a,{NODE_ENV:s}=process.env,c=n?.behaviours??[`CONCURRENCY`,`RETRY`];try{if(a=c.includes(`RETRY`)?createDefaultRetryInstance(e,n):createDefaultInstance(e,n),(0,o.isMissing)(n?.service)||(0,o.isMissing)(n?.organizationId)||s===`test`||(0,o.isMissing)(t)||(0,o.isMissing)(e))return a;let l=SingletonManager.getIfReady(RateLimitManager)??void 0,u=SingletonManager.getIfReady(ConcurrencyManager)??void 0,d=l?.isReady(),f=u?.isRedisConfigured(),p=[],m=[];if(c.includes(`CONCURRENCY`)){if(!f)throw Error(`Concurrency Manager cannot connect to Redis. Cannot create advanced transport instance.`);if(!d)throw Error(`RateLimitManager is not ready. Cannot create advanced transport instance.`);p.push(...sn),m.push(...cn)}let h=generateRequestKey(n);if((0,o.isMissing)(h))return e?.warning({category:`http-transport`,message:`Unable to create a key for transport instance - Invalid state. Using base default instance.`,context:{...n,defaultInstanceInitialized:(0,o.notMissing)(a)}}),a;let g=await je.get(h);if((0,o.notMissing)(g))return g;let _={interceptors:{requestConfigs:p,responseConfigs:m},instanceConfig:{maxBodyLength:1/0},logger:e,context:n,requestConfig:r,httpsAgentConfig:i,concurrencyManager:u,rateLimitManager:l},v=HttpTransportFactory.createInstance(_);return e?.debug({category:`http-transport`,message:`Creating new Axios instance and caching it for key: [${h}]`,context:{...n}}),await je.set(h,v),v}catch(t){return e?.error({category:`http-transport`,message:`Failed to create advanced transport instance. Using default instance.`,context:{...n,usingDefaultInstance:(0,o.notMissing)(a)},error:t,code:gn.HttpTransportInstanceCreateError}),(0,o.notMissing)(a)?a:createAxiosInstance()}},createDefaultInstance=(e,t)=>{let n={instanceConfig:{maxBodyLength:1/0},logger:e,context:t};return HttpTransportFactory.createInstance(n)??createAxiosInstance()},createDefaultRetryInstance=(e,t)=>{let n={interceptors:{requestConfigs:an,responseConfigs:on},instanceConfig:{maxBodyLength:1/0},logger:e,context:t};return HttpTransportFactory.createInstance(n)??createAxiosInstance()},createAxiosInstance=()=>l.default.create({maxBodyLength:1/0});var HttpClient=class{#e;#t;#n;#r;#i;#a;constructor({transportFactory:e=getTransportInstance,getRedisClient:t=buildRedisClientInstance,logger:n,redisClientConfig:r,errorMappingFn:i}={}){this.name=`HttpClient`,this.#e=e,this.#t=t,this.#n=n,this.#r=r,this.#i=i}#o({url:e,payload:t,method:n,context:r}){if(!r?.accountSecureId||r.accountSecureId.length<20||!e||!n)return null;let i=t?(0,o.getContentHash)(t):``;return`${r.accountSecureId}-${n.toUpperCase()}${i}-${e}`}async#s({url:e,payload:t,method:n,cacheTTL:r,context:i}){if(!this.#a||!r||r<=0)return null;let a=this.#o({url:e,payload:t,method:n,context:i});if(!a)return null;let o=await this.#a.getData(a);return o?(this.#n?.debug({category:this.name,message:`Cache hit for key [${a}].`}),o):(this.#n?.debug({category:this.name,message:`Cache miss for key [${a}].`}),null)}async#c({url:e,payload:t,method:n,cacheTTL:r,context:i,response:a}){if(!this.#a||!r||r<=0)return!1;let o=this.#o({url:e,payload:t,method:n,context:i});return o?(this.#n?.debug({category:this.name,message:`Caching result for key [${o}].`}),this.#a.setData({key:o,value:a,cacheTTL:r*60})):!1}async request({headers:e={},url:t,method:n=`get`,queryParams:r,maxRedirects:i=0,responseType:a,cacheTTL:s,context:c,traceId:l,payload:u,httpsAgent:d,httpAgent:f,requestConfig:p,httpsAgentConfig:h}){try{(0,o.notMissing)(this.#r)&&(0,o.isMissing)(this.#a)&&(this.#a=await this.#t(this.#r,this.#n,`HttpClient`));let m=this.#_(t,r),g=this.#l(e),_=this.#m(u,e),v=await this.#s({url:m,payload:_,method:n,cacheTTL:s,context:c});if(v)return{...v,responseTime:new Date};let y=P.getInstance(),b=((0,o.notMissing)(l)?await y.get(l):null)?.signal,x=await(await this.#e({redisClientConfig:this.#r,logger:this.#n,context:c,requestConfig:p,httpsAgentConfig:h})).request({headers:g,url:m,method:n,maxRedirects:i,responseType:a,data:_,httpsAgent:d,httpAgent:f,signal:b}),S={data:x.data,status:x.status,body:_,method:n,headers:this.#u(x.headers),requestUrl:t,responseType:x?.config?.responseType,responseTime:new Date};return await this.#c({url:m,payload:_,method:n,cacheTTL:s,context:c,response:S}),S}catch(e){let r=e;r.url=(0,m.redactUrl)(t),this.#n?.warning({category:this.name,message:`Request error [${n?.toUpperCase()} ${r.url}]: ${r.message}.`,error:r});let i=this.#h(r);throw(0,o.notMissing)(i)?i:e}}async get({headers:e,url:t,queryParams:n,maxRedirects:r,cacheTTL:i,context:a,traceId:o,requestConfig:s}){return this.request({url:t,method:`get`,queryParams:n,headers:e,maxRedirects:r,cacheTTL:i,context:a,traceId:o,requestConfig:s})}async post({headers:e,url:t,maxRedirects:n,cacheTTL:r,context:i,traceId:a,payload:o,requestConfig:s}){return this.request({url:t,method:`post`,headers:e,maxRedirects:n,cacheTTL:r,context:i,traceId:a,payload:o,requestConfig:s})}async requestStream({headers:e={},url:t,method:n=`get`,queryParams:r,maxRedirects:i=0,context:a,traceId:s,payload:c,httpsAgent:l,httpAgent:u,requestConfig:d,httpsAgentConfig:f}){try{let p=this.#_(t,r),m=this.#l(e),h=this.#m(c,e),g=P.getInstance(),_=((0,o.notMissing)(s)?await g.get(s):null)?.signal,v=await(await this.#e({redisClientConfig:this.#r,logger:this.#n,context:a,requestConfig:d,httpsAgentConfig:f})).request({headers:m,url:p,method:n,maxRedirects:i,responseType:`stream`,data:h,httpsAgent:l,httpAgent:u,signal:_});return{status:v.status,headers:this.#u(v.headers),stream:v.data,requestUrl:t}}catch(e){let r=e;r.url=(0,m.redactUrl)(t),this.#n?.warning({category:this.name,message:`Stream request error [${n?.toUpperCase()} ${r.url}]: ${r.message}.`,error:r});let i=this.#h(r);throw(0,o.notMissing)(i)?i:e}}#l(e){if(!e)return{};let t={};return Object.keys(e).forEach(n=>{t[n.toLowerCase()]=e[n]||``}),t}#u(e){if(!e)return{};let t={};return Object.keys(e).forEach(n=>{t[n]=e[n]||``}),t}#d(e){return e[`content-type`]===`application/x-www-form-urlencoded`}#f(e){return(0,o.isString)(e[`content-type`])?e[`content-type`]?.startsWith(`multipart/form-data`)??!1:!1}#p(e){return(0,o.isMissing)(e)||typeof e!=`object`||!e?!1:`pipe`in e&&typeof e.pipe==`function`}#m(e,t){if(!((0,o.isMissing)(e)||(0,o.isObject)(e)&&Object.keys(e).length===0))return this.#f(t)||this.#p(e)?e:this.#d(t)?h.default.stringify(e):e}#h(e){if((0,l.isAxiosError)(e)&&this.#i)return this.#i(e)}#g(e){return typeof e==`object`&&!!e&&`value`in e&&(typeof e.value==`string`||Array.isArray(e.value))}#_(e,t){if((0,o.isMissing)(t)||Object.keys(t).length===0)return e;let n={},r={},i={},a={};for(let[e,o]of Object.entries(t))if(this.#g(o)){let t=o.arrayFormat,s=o.value;t===`repeat`?r[e]=Array.isArray(s)?s:[s]:t===`brackets`?i[e]=Array.isArray(s)?s:[s]:t===`comma`?a[e]=Array.isArray(s)?s:[s]:n[e]=s}else n[e]=o;let s=[];Object.keys(n).length>0&&s.push(h.default.stringify(n)),Object.keys(r).length>0&&s.push(h.default.stringify(r,{arrayFormat:`repeat`})),Object.keys(i).length>0&&s.push(h.default.stringify(i,{arrayFormat:`brackets`})),Object.keys(a).length>0&&s.push(h.default.stringify(a,{arrayFormat:`comma`}));let c=s.join(`&`);return(0,o.notMissing)(c)?`${e}?${c}`:e}};const buildHttpClientInstance=(e,t,n)=>new HttpClient({redisClientConfig:e,logger:t,errorMappingFn:n});var HttpClientManager=class{static{this.httpClientInstance=null}static async getInstance({redisClientConfig:e,logger:t,errorMappingFn:n,getHttpClient:r=buildHttpClientInstance}){return this.httpClientInstance??=r(e,t,n),this.httpClientInstance}static resetInstance(){this.httpClientInstance=null}};const _n=[`get`,`post`,`put`,`delete`,`patch`],vn={[k.rPush]:`
|
|
113
|
+
(function(n){"use strict";var r=2e3,i={s:1,n:0,d:1};function assign(e,t){if(isNaN(e=parseInt(e,10)))throw InvalidParameter();return e*t}function newFraction(e,t){if(t===0)throw DivisionByZero();var n=Object.create(Fraction$2.prototype);n.s=e<0?-1:1,e=e<0?-e:e;var r=gcd(e,t);return n.n=e/r,n.d=t/r,n}function factorize(e){for(var t={},n=e,r=2,i=4;i<=n;){for(;n%r===0;)n/=r,t[r]=(t[r]||0)+1;i+=1+2*r++}return n===e?t[e]=(t[e]||0)+1:n>1&&(t[n]=(t[n]||0)+1),t}var a=__name(function(e,t){var n=0,r=1,a=1,o=0,s=0,c=0,l=1,u=1,d=0,f=1,p=1,m=1,h=1e7,g;if(e!=null)if(t!==void 0){if(n=e,r=t,a=n*r,n%1!=0||r%1!=0)throw NonIntegerParameter()}else switch(typeof e){case`object`:if(`d`in e&&`n`in e)n=e.n,r=e.d,`s`in e&&(n*=e.s);else if(0 in e)n=e[0],1 in e&&(r=e[1]);else throw InvalidParameter();a=n*r;break;case`number`:if(e<0&&(a=e,e=-e),e%1==0)n=e;else if(e>0){for(e>=1&&(u=10**Math.floor(1+Math.log(e)/Math.LN10),e/=u);f<=h&&m<=h;)if(g=(d+p)/(f+m),e===g){f+m<=h?(n=d+p,r=f+m):m>f?(n=p,r=m):(n=d,r=f);break}else e>g?(d+=p,f+=m):(p+=d,m+=f),f>h?(n=p,r=m):(n=d,r=f);n*=u}else (isNaN(e)||isNaN(t))&&(r=n=NaN);break;case`string`:if(f=e.match(/\d+|./g),f===null)throw InvalidParameter();if(f[d]===`-`?(a=-1,d++):f[d]===`+`&&d++,f.length===d+1?s=assign(f[d++],a):f[d+1]===`.`||f[d]===`.`?(f[d]!==`.`&&(o=assign(f[d++],a)),d++,(d+1===f.length||f[d+1]===`(`&&f[d+3]===`)`||f[d+1]===`'`&&f[d+3]===`'`)&&(s=assign(f[d],a),l=10**f[d].length,d++),(f[d]===`(`&&f[d+2]===`)`||f[d]===`'`&&f[d+2]===`'`)&&(c=assign(f[d+1],a),u=10**f[d+1].length-1,d+=3)):f[d+1]===`/`||f[d+1]===`:`?(s=assign(f[d],a),l=assign(f[d+2],1),d+=3):f[d+3]===`/`&&f[d+1]===` `&&(o=assign(f[d],a),s=assign(f[d+2],a),l=assign(f[d+4],1),d+=5),f.length<=d){r=l*u,a=n=c+r*o+u*s;break}default:throw InvalidParameter()}if(r===0)throw DivisionByZero();i.s=a<0?-1:1,i.n=Math.abs(n),i.d=Math.abs(r)},`parse`);function modpow(e,t,n){for(var r=1;t>0;e=e*e%n,t>>=1)t&1&&(r=r*e%n);return r}function cycleLen(e,t){for(;t%2==0;t/=2);for(;t%5==0;t/=5);if(t===1)return 0;for(var n=10%t,i=1;n!==1;i++)if(n=n*10%t,i>r)return 0;return i}function cycleStart(e,t,n){for(var r=1,i=modpow(10,n,t),a=0;a<300;a++){if(r===i)return a;r=r*10%t,i=i*10%t}return 0}function gcd(e,t){if(!e)return t;if(!t)return e;for(;;){if(e%=t,!e)return t;if(t%=e,!t)return e}}function Fraction$2(e,t){if(a(e,t),this instanceof Fraction$2)e=gcd(i.d,i.n),this.s=i.s,this.n=i.n/e,this.d=i.d/e;else return newFraction(i.s*i.n,i.d)}__name(Fraction$2,`Fraction`);var DivisionByZero=function(){return Error(`Division by Zero`)},InvalidParameter=function(){return Error(`Invalid argument`)},NonIntegerParameter=function(){return Error(`Parameters must be integer`)};Fraction$2.prototype={s:1,n:0,d:1,abs:function(){return newFraction(this.n,this.d)},neg:function(){return newFraction(-this.s*this.n,this.d)},add:function(e,t){return a(e,t),newFraction(this.s*this.n*i.d+i.s*this.d*i.n,this.d*i.d)},sub:function(e,t){return a(e,t),newFraction(this.s*this.n*i.d-i.s*this.d*i.n,this.d*i.d)},mul:function(e,t){return a(e,t),newFraction(this.s*i.s*this.n*i.n,this.d*i.d)},div:function(e,t){return a(e,t),newFraction(this.s*i.s*this.n*i.d,this.d*i.n)},clone:function(){return newFraction(this.s*this.n,this.d)},mod:function(e,t){if(isNaN(this.n)||isNaN(this.d))return new Fraction$2(NaN);if(e===void 0)return newFraction(this.s*this.n%this.d,1);if(a(e,t),i.n===0&&this.d===0)throw DivisionByZero();return newFraction(this.s*(i.d*this.n)%(i.n*this.d),i.d*this.d)},gcd:function(e,t){return a(e,t),newFraction(gcd(i.n,this.n)*gcd(i.d,this.d),i.d*this.d)},lcm:function(e,t){return a(e,t),i.n===0&&this.n===0?newFraction(0,1):newFraction(i.n*this.n,gcd(i.n,this.n)*gcd(i.d,this.d))},ceil:function(e){return e=10**(e||0),isNaN(this.n)||isNaN(this.d)?new Fraction$2(NaN):newFraction(Math.ceil(e*this.s*this.n/this.d),e)},floor:function(e){return e=10**(e||0),isNaN(this.n)||isNaN(this.d)?new Fraction$2(NaN):newFraction(Math.floor(e*this.s*this.n/this.d),e)},round:function(e){return e=10**(e||0),isNaN(this.n)||isNaN(this.d)?new Fraction$2(NaN):newFraction(Math.round(e*this.s*this.n/this.d),e)},inverse:function(){return newFraction(this.s*this.d,this.n)},pow:function(e,t){if(a(e,t),i.d===1)return i.s<0?newFraction((this.s*this.d)**+i.n,this.n**+i.n):newFraction((this.s*this.n)**+i.n,this.d**+i.n);if(this.s<0)return null;var n=factorize(this.n),r=factorize(this.d),o=1,s=1;for(var c in n)if(c!==`1`){if(c===`0`){o=0;break}if(n[c]*=i.n,n[c]%i.d===0)n[c]/=i.d;else return null;o*=c**+n[c]}for(var c in r)if(c!==`1`){if(r[c]*=i.n,r[c]%i.d===0)r[c]/=i.d;else return null;s*=c**+r[c]}return i.s<0?newFraction(s,o):newFraction(o,s)},equals:function(e,t){return a(e,t),this.s*this.n*i.d===i.s*i.n*this.d},compare:function(e,t){a(e,t);var n=this.s*this.n*i.d-i.s*i.n*this.d;return(0<n)-(n<0)},simplify:function(e){if(isNaN(this.n)||isNaN(this.d))return this;e||=.001;for(var t=this.abs(),n=t.toContinued(),r=1;r<n.length;r++){for(var i=newFraction(n[r-1],1),a=r-2;a>=0;a--)i=i.inverse().add(n[a]);if(Math.abs(i.sub(t).valueOf())<e)return i.mul(this.s)}return this},divisible:function(e,t){return a(e,t),!(!(i.n*this.d)||this.n*i.d%(i.n*this.d))},valueOf:function(){return this.s*this.n/this.d},toFraction:function(e){var t,n=``,r=this.n,i=this.d;return this.s<0&&(n+=`-`),i===1?n+=r:(e&&(t=Math.floor(r/i))>0&&(n+=t,n+=` `,r%=i),n+=r,n+=`/`,n+=i),n},toLatex:function(e){var t,n=``,r=this.n,i=this.d;return this.s<0&&(n+=`-`),i===1?n+=r:(e&&(t=Math.floor(r/i))>0&&(n+=t,r%=i),n+=`\\frac{`,n+=r,n+=`}{`,n+=i,n+=`}`),n},toContinued:function(){var e,t=this.n,n=this.d,r=[];if(isNaN(t)||isNaN(n))return r;do r.push(Math.floor(t/n)),e=t%n,t=n,n=e;while(t!==1);return r},toString:function(e){var t=this.n,n=this.d;if(isNaN(t)||isNaN(n))return`NaN`;e||=15;var r=cycleLen(t,n),i=cycleStart(t,n,r),a=this.s<0?`-`:``;if(a+=t/n|0,t%=n,t*=10,t&&(a+=`.`),r){for(var o=i;o--;)a+=t/n|0,t%=n,t*=10;a+=`(`;for(var o=r;o--;)a+=t/n|0,t%=n,t*=10;a+=`)`}else for(var o=e;t&&o--;)a+=t/n|0,t%=n,t*=10;return a}},typeof e==`object`?(Object.defineProperty(Fraction$2,`__esModule`,{value:!0}),Fraction$2.default=Fraction$2,Fraction$2.Fraction=Fraction$2,t.exports=Fraction$2):n.Fraction=Fraction$2})(e)})),$=__toESM(Et(),1),Dt=`Fraction`,Ot=[],kt=factory(Dt,Ot,()=>(Object.defineProperty($.default,`name`,{value:`Fraction`}),$.default.prototype.constructor=$.default,$.default.prototype.type=`Fraction`,$.default.prototype.isFraction=!0,$.default.prototype.toJSON=function(){return{mathjs:`Fraction`,n:this.s*this.n,d:this.d}},$.default.fromJSON=function(e){return new $.default(e)},$.default),{isClass:!0}),At=`Matrix`,jt=[],Mt=factory(At,jt,()=>{function Matrix$1(){if(!(this instanceof Matrix$1))throw SyntaxError(`Constructor must be called with the new operator`)}return __name(Matrix$1,`Matrix`),Matrix$1.prototype.type=`Matrix`,Matrix$1.prototype.isMatrix=!0,Matrix$1.prototype.storage=function(){throw Error(`Cannot invoke storage on a Matrix interface`)},Matrix$1.prototype.datatype=function(){throw Error(`Cannot invoke datatype on a Matrix interface`)},Matrix$1.prototype.create=function(e,t){throw Error(`Cannot invoke create on a Matrix interface`)},Matrix$1.prototype.subset=function(e,t,n){throw Error(`Cannot invoke subset on a Matrix interface`)},Matrix$1.prototype.get=function(e){throw Error(`Cannot invoke get on a Matrix interface`)},Matrix$1.prototype.set=function(e,t,n){throw Error(`Cannot invoke set on a Matrix interface`)},Matrix$1.prototype.resize=function(e,t){throw Error(`Cannot invoke resize on a Matrix interface`)},Matrix$1.prototype.reshape=function(e,t){throw Error(`Cannot invoke reshape on a Matrix interface`)},Matrix$1.prototype.clone=function(){throw Error(`Cannot invoke clone on a Matrix interface`)},Matrix$1.prototype.size=function(){throw Error(`Cannot invoke size on a Matrix interface`)},Matrix$1.prototype.map=function(e,t){throw Error(`Cannot invoke map on a Matrix interface`)},Matrix$1.prototype.forEach=function(e){throw Error(`Cannot invoke forEach on a Matrix interface`)},Matrix$1.prototype[Symbol.iterator]=function(){throw Error(`Cannot iterate a Matrix interface`)},Matrix$1.prototype.toArray=function(){throw Error(`Cannot invoke toArray on a Matrix interface`)},Matrix$1.prototype.valueOf=function(){throw Error(`Cannot invoke valueOf on a Matrix interface`)},Matrix$1.prototype.format=function(e){throw Error(`Cannot invoke format on a Matrix interface`)},Matrix$1.prototype.toString=function(){throw Error(`Cannot invoke toString on a Matrix interface`)},Matrix$1},{isClass:!0});function maxArgumentCount(e){return Object.keys(e.signatures||{}).reduce(function(e,t){var n=(t.match(/,/g)||[]).length+1;return Math.max(e,n)},-1)}var Nt=`DenseMatrix`,Pt=[`Matrix`],Ft=factory(Nt,Pt,e=>{var{Matrix:t}=e;function DenseMatrix$1(e,t){if(!(this instanceof DenseMatrix$1))throw SyntaxError(`Constructor must be called with the new operator`);if(t&&!isString$1(t))throw Error(`Invalid datatype: `+t);if(isMatrix(e))e.type===`DenseMatrix`?(this._data=clone$2(e._data),this._size=clone$2(e._size),this._datatype=t||e._datatype):(this._data=e.toArray(),this._size=e.size(),this._datatype=t||e._datatype);else if(e&&L(e.data)&&L(e.size))this._data=e.data,this._size=e.size,validate$1(this._data,this._size),this._datatype=t||e.datatype;else if(L(e))this._data=preprocess(e),this._size=arraySize(this._data),validate$1(this._data,this._size),this._datatype=t;else if(e)throw TypeError(`Unsupported type of data (`+typeOf(e)+`)`);else this._data=[],this._size=[0],this._datatype=t}__name(DenseMatrix$1,`DenseMatrix`),DenseMatrix$1.prototype=new t,DenseMatrix$1.prototype.createDenseMatrix=function(e,t){return new DenseMatrix$1(e,t)},Object.defineProperty(DenseMatrix$1,`name`,{value:`DenseMatrix`}),DenseMatrix$1.prototype.constructor=DenseMatrix$1,DenseMatrix$1.prototype.type=`DenseMatrix`,DenseMatrix$1.prototype.isDenseMatrix=!0,DenseMatrix$1.prototype.getDataType=function(){return getArrayDataType(this._data,typeOf)},DenseMatrix$1.prototype.storage=function(){return`dense`},DenseMatrix$1.prototype.datatype=function(){return this._datatype},DenseMatrix$1.prototype.create=function(e,t){return new DenseMatrix$1(e,t)},DenseMatrix$1.prototype.subset=function(e,t,n){switch(arguments.length){case 1:return _get(this,e);case 2:case 3:return _set(this,e,t,n);default:throw SyntaxError(`Wrong number of arguments`)}},DenseMatrix$1.prototype.get=function(e){if(!L(e))throw TypeError(`Array expected`);if(e.length!==this._size.length)throw new DimensionError(e.length,this._size.length);for(var t=0;t<e.length;t++)validateIndex(e[t],this._size[t]);for(var n=this._data,r=0,i=e.length;r<i;r++){var a=e[r];validateIndex(a,n.length),n=n[a]}return n},DenseMatrix$1.prototype.set=function(e,t,n){if(!L(e))throw TypeError(`Array expected`);if(e.length<this._size.length)throw new DimensionError(e.length,this._size.length,`<`);var r,i,a,o=e.map(function(e){return e+1});_fit(this,o,n);var s=this._data;for(r=0,i=e.length-1;r<i;r++)a=e[r],validateIndex(a,s.length),s=s[a];return a=e[e.length-1],validateIndex(a,s.length),s[a]=t,this};function _get(e,t){if(!isIndex(t))throw TypeError(`Invalid index`);if(t.isScalar())return e.get(t.min());var n=t.size();if(n.length!==e._size.length)throw new DimensionError(n.length,e._size.length);for(var r=t.min(),i=t.max(),a=0,o=e._size.length;a<o;a++)validateIndex(r[a],e._size[a]),validateIndex(i[a],e._size[a]);return new DenseMatrix$1(_getSubmatrix(e._data,t,n.length,0),e._datatype)}function _getSubmatrix(e,t,n,r){var i=r===n-1,a=t.dimension(r);return i?a.map(function(t){return validateIndex(t,e.length),e[t]}).valueOf():a.map(function(i){validateIndex(i,e.length);var a=e[i];return _getSubmatrix(a,t,n,r+1)}).valueOf()}function _set(e,t,n,r){if(!t||t.isIndex!==!0)throw TypeError(`Invalid index`);var i=t.size(),a=t.isScalar(),o;if(isMatrix(n)?(o=n.size(),n=n.valueOf()):o=arraySize(n),a){if(o.length!==0)throw TypeError(`Scalar expected`);e.set(t.min(),n,r)}else{if(!deepStrictEqual(o,i))try{n=o.length===0?broadcastTo([n],i):broadcastTo(n,i),o=arraySize(n)}catch{}if(i.length<e._size.length)throw new DimensionError(i.length,e._size.length,`<`);if(o.length<i.length){for(var s=0,c=0;i[s]===1&&o[s]===1;)s++;for(;i[s]===1;)c++,s++;n=unsqueeze(n,i.length,c,o)}if(!deepStrictEqual(i,o))throw new DimensionError(i,o,`>`);_fit(e,t.max().map(function(e){return e+1}),r);var l=i.length;_setSubmatrix(e._data,t,n,l,0)}return e}function _setSubmatrix(e,t,n,r,i){var a=i===r-1,o=t.dimension(i);a?o.forEach(function(t,r){validateIndex(t),e[t]=n[r[0]]}):o.forEach(function(a,o){validateIndex(a),_setSubmatrix(e[a],t,n[o[0]],r,i+1)})}DenseMatrix$1.prototype.resize=function(e,t,n){if(!isCollection(e))throw TypeError(`Array or Matrix expected`);var r=e.valueOf().map(e=>Array.isArray(e)&&e.length===1?e[0]:e);return _resize$1(n?this.clone():this,r,t)};function _resize$1(e,t,n){if(t.length===0){for(var r=e._data;L(r);)r=r[0];return r}return e._size=t.slice(0),e._data=resize(e._data,e._size,n),e}__name(_resize$1,`_resize`),DenseMatrix$1.prototype.reshape=function(e,t){var n=t?this.clone():this;return n._data=reshape(n._data,e),n._size=processSizesWildcard(e,n._size.reduce((e,t)=>e*t)),n};function _fit(e,t,n){for(var r=e._size.slice(0),i=!1;r.length<t.length;)r.push(0),i=!0;for(var a=0,o=t.length;a<o;a++)t[a]>r[a]&&(r[a]=t[a],i=!0);i&&_resize$1(e,r,n)}DenseMatrix$1.prototype.clone=function(){return new DenseMatrix$1({data:clone$2(this._data),size:clone$2(this._size),datatype:this._datatype})},DenseMatrix$1.prototype.size=function(){return this._size.slice(0)},DenseMatrix$1.prototype.map=function(e){var t=this,n=maxArgumentCount(e),r=function recurse(r,i){return L(r)?r.map(function(e,t){return recurse(e,i.concat(t))}):n===1?e(r):n===2?e(r,i):e(r,i,t)}(this._data,[]);return new DenseMatrix$1(r,this._datatype===void 0?void 0:getArrayDataType(r,typeOf))},DenseMatrix$1.prototype.forEach=function(e){var t=this;(function recurse(n,r){L(n)?n.forEach(function(e,t){recurse(e,r.concat(t))}):e(n,r,t)})(this._data,[])},DenseMatrix$1.prototype[Symbol.iterator]=function*(){yield*function*recurse(e,t){if(L(e))for(var n=0;n<e.length;n++)yield*recurse(e[n],t.concat(n));else yield{value:e,index:t}}(this._data,[])},DenseMatrix$1.prototype.rows=function(){var e=[];if(this.size().length!==2)throw TypeError(`Rows can only be returned for a 2D matrix.`);for(var t of this._data)e.push(new DenseMatrix$1([t],this._datatype));return e},DenseMatrix$1.prototype.columns=function(){var e=this,t=[],n=this.size();if(n.length!==2)throw TypeError(`Rows can only be returned for a 2D matrix.`);for(var r=this._data,i=function _loop$1(n){var i=r.map(e=>[e[n]]);t.push(new DenseMatrix$1(i,e._datatype))},a=0;a<n[1];a++)i(a);return t},DenseMatrix$1.prototype.toArray=function(){return clone$2(this._data)},DenseMatrix$1.prototype.valueOf=function(){return this._data},DenseMatrix$1.prototype.format=function(e){return format(this._data,e)},DenseMatrix$1.prototype.toString=function(){return format(this._data)},DenseMatrix$1.prototype.toJSON=function(){return{mathjs:`DenseMatrix`,data:this._data,size:this._size,datatype:this._datatype}},DenseMatrix$1.prototype.diagonal=function(e){if(e){if(isBigNumber(e)&&(e=e.toNumber()),!isNumber$1(e)||!isInteger(e))throw TypeError(`The parameter k must be an integer number`)}else e=0;for(var t=e>0?e:0,n=e<0?-e:0,r=this._size[0],i=this._size[1],a=Math.min(r-n,i-t),o=[],s=0;s<a;s++)o[s]=this._data[s+n][s+t];return new DenseMatrix$1({data:o,size:[a],datatype:this._datatype})},DenseMatrix$1.diagonal=function(e,t,n,r){if(!L(e))throw TypeError(`Array expected, size parameter`);if(e.length!==2)throw Error(`Only two dimensions matrix are supported`);if(e=e.map(function(e){if(isBigNumber(e)&&(e=e.toNumber()),!isNumber$1(e)||!isInteger(e)||e<1)throw Error(`Size values must be positive integers`);return e}),n){if(isBigNumber(n)&&(n=n.toNumber()),!isNumber$1(n)||!isInteger(n))throw TypeError(`The parameter k must be an integer number`)}else n=0;var i=n>0?n:0,a=n<0?-n:0,o=e[0],s=e[1],c=Math.min(o-a,s-i),l;if(L(t)){if(t.length!==c)throw Error(`Invalid value array length`);l=function _value$1(e){return t[e]}}else if(isMatrix(t)){var u=t.size();if(u.length!==1||u[0]!==c)throw Error(`Invalid matrix length`);l=function _value$1(e){return t.get([e])}}else l=function _value$1(){return t};r||=isBigNumber(l(0))?l(0).mul(0):0;var d=[];if(e.length>0){d=resize(d,e,r);for(var f=0;f<c;f++)d[f+a][f+i]=l(f)}return new DenseMatrix$1({data:d,size:[o,s]})},DenseMatrix$1.fromJSON=function(e){return new DenseMatrix$1(e)},DenseMatrix$1.prototype.swapRows=function(e,t){if(!isNumber$1(e)||!isInteger(e)||!isNumber$1(t)||!isInteger(t))throw Error(`Row index must be positive integers`);if(this._size.length!==2)throw Error(`Only two dimensional matrix is supported`);return validateIndex(e,this._size[0]),validateIndex(t,this._size[0]),DenseMatrix$1._swapRows(e,t,this._data),this},DenseMatrix$1._swapRows=function(e,t,n){var r=n[e];n[e]=n[t],n[t]=r};function preprocess(e){return isMatrix(e)?preprocess(e.valueOf()):L(e)?e.map(preprocess):e}return DenseMatrix$1},{isClass:!0});function deepMap(e,t,n){return e&&typeof e.map==`function`?e.map(function(e){return deepMap(e,t,n)}):t(e)}var It=`isNumeric`,Lt=[`typed`],Rt=factory(It,Lt,e=>{var{typed:t}=e;return t(It,{"number | BigNumber | Fraction | boolean":()=>!0,"Complex | Unit | string | null | undefined | Node":()=>!1,"Array | Matrix":t.referToSelf(e=>t=>deepMap(t,e))})}),zt=`hasNumericValue`,Bt=[`typed`,`isNumeric`],Vt=factory(zt,Bt,e=>{var{typed:t,isNumeric:n}=e;return t(zt,{boolean:()=>!0,string:function string(e){return e.trim().length>0&&!isNaN(Number(e))},any:function any(e){return n(e)}})}),Ht=xt({config:qe}),Ut=Tt({}),Wt=kt({}),Gt=Mt({}),Kt=Ft({Matrix:Gt}),qt=nt({BigNumber:Ht,Complex:Ut,DenseMatrix:Kt,Fraction:Wt}),Jt=Rt({typed:qt}),Yt=Vt({isNumeric:Jt,typed:qt});const shortTimePeriodIsMilliseconds=e=>{let t=Number(e);return Number.isNaN(t)?!1:t>=120&&t<=36e4},resolveWaitTimeMs=e=>{let t=Number(e),n=Date.now();return Number.isNaN(t)?n+1e3:!shortTimePeriodIsMilliseconds(t)&&(0,o.isFutureUnixTimestamp)(t)?adjustUnixTimestamp(t):shortTimePeriodIsMilliseconds(t)?n+t:n+t*I},Xt=`ratelimitlimit`,Zt=`ratelimitremaining`,Qt=`ratelimitreset`,$t=`ratelimitconcurrencylimit`,en=`ratelimitconcurrencyremaining`,tn=`ratelimitconcurrencyreset`,superNormalizeHeaders=e=>{let t={};for(let[n,r]of Object.entries(e)){let e=n.toLowerCase().replace(/^x-/,``).replace(/concurren.+-/g,`concurrency-`).replace(/-/g,``);t[e]=Yt(r)?Number(r):null}return t},extractRateLimitHeaders=e=>{let t=superNormalizeHeaders(e);return{rateLimitLimit:t.ratelimitlimit,rateLimitRemaining:t.ratelimitremaining,rateLimitReset:resolveWaitTimeMs(t.ratelimitreset),concurrencyLimit:t.ratelimitconcurrencylimit,concurrencyRemaining:t.ratelimitconcurrencyremaining,concurrencyReset:resolveWaitTimeMs(t.ratelimitconcurrencyreset)}},generateRequestKey=e=>{let{accountSecureId:t,service:n,resource:r,subResource:i,childResource:a,action:s,behaviours:c}=e??{};return[t,n,r,s].some(o.isMissing)?null:[t,n,r,i,a,s,...c??[]].filter(Boolean).join(`-`)},getRetryAfterWaitTime=(e,t=10,n=1)=>{let r=Date.now();return(0,o.isFutureUnixTimestamp)(e)||(0,o.isNumber)(e)?evaluateRetryAfterNumber(Number(e),r,t,n):isString$1(e)&&e!==``?evaluateRetryAfterString(e,r,t,n):n},evaluateRetryAfterNumber=(e,t,n=10,r=1)=>{if(e<n)return e;let i=adjustUnixTimestamp(e);if(i>t){let e=Math.floor((i-t)/I);return e>0&&e<n?e:r}return r},evaluateRetryAfterString=(e,t,n=10,r=1)=>{if(Be.test(e)){let t=parseFloat(e);return t>0&&t<n?t:r}let i=new Date(e);if(Number.isNaN(i.getTime()))return r;let a=i.getTime();if(a>t){let e=Math.floor((a-t)/I);return e>0&&e<n?e:r}return r},retryErrorInterceptor=({axiosInstance:e,logger:t,requestConfig:n,context:r})=>__name(async i=>{let{response:a,config:s}=i;if(s?.signal?.aborted)return Promise.reject(createAxiosError(`Request aborted`,s,`ERR_CANCELED`,a));let{status:c,retryAfter:l}=convertError(a,r,n,t);if(c===429&&(0,o.notMissing)(s)){let n=getRetryAfterWaitTime(l);if(s._retryCount>=5)return t?.warning({category:`http-transport`,message:`Max retries exceeded for ${s?.url}. Aborting.`,context:{...r??{},retryAfterHeader:l,retryAfterAsNumber:n}}),Promise.reject(i);let c=s._retryCount??0,u={...s,_retryCount:c+1},d=l?n*I:(0,o.exponentialBackoffInMS)(u._retryCount);return t?.debug({category:`http-transport`,message:`Received 429 error from ${s?.url}`,context:{...r??{},retryAfterHeader:l,calculatedRetryAfter:d}}),await abortableDelay(d,s,a),e?.request(u)}return Promise.reject(i)},`retryErrorInterceptor`),convertError=(e,t,n,r)=>{let{provider:i}=t??{},{status:a,headers:s,data:c}=e??{},{retryafter:l}=superNormalizeHeaders(s??{});if((0,o.isMissing)(i)||(0,o.isMissing)(e))return r?.warning({category:`http-transport`,message:`Invalid parameters for convertError`,context:{...t,responseIsMissing:(0,o.isMissing)(e),providerIsMissing:(0,o.isMissing)(i),status:e?.status??`undefined`,statusText:e?.statusText??`undefined`,retryafter:l??`undefined`}}),{status:a,retryAfter:l};let u=n?.rateLimits?.mappedRateLimitErrors;if((0,o.notMissing)(u)&&(0,o.notMissing)(c))for(let e of u){let{errorStatus:t,errorMessagePath:n,errorMessage:r,retryAfterPath:i,retryAfterUnit:u,retryAfterValue:d}=e;if(t!==a)continue;let f=n??`message`,m=testMessage((0,o.isObject)(c)?(0,p.JSONPath)({path:f,json:c})[0]:c,r);if(t===a&&m){let e=convertRetryAfter(d??extractRetryAfter(s,i),u);return{status:429,retryAfter:l??e}}}return{status:a,retryAfter:l}},testMessage=(e,t)=>t instanceof RegExp?t.test(e??``):e?.includes(t)??!1,extractRetryAfter=(e,t)=>(0,o.notMissing)(t)&&(0,o.notMissing)(e)?(0,p.JSONPath)({path:t,json:e})[0]:null,convertRetryAfter=(e,t=`seconds`)=>(0,o.notMissing)(e)?transformToSeconds(e,t):null,transformToSeconds=(e,t)=>{if(t===`seconds`)return typeof e==`string`?parseFloat(e):e;if(t===`milliseconds`)return(typeof e==`string`?parseFloat(e):e)/I;if(t===`date`){let t=typeof e==`string`&&!isNaN(Number(e))?parseFloat(e):e,n=new Date(t);if(isNaN(n.getTime()))throw Error(`Invalid date value`);return n.getTime()}throw Error(`Invalid type`)},nn=`rateLimitErrorInterceptor`,rateLimitErrorInterceptor=({axiosInstance:e,logger:t,requestConfig:n,context:r,concurrencyManager:i})=>__name(async a=>{let{response:s,config:c}=a,l=c?.signal;if((0,o.isMissing)(r)||(0,o.isMissing)(c))return t?.warning({category:`HttpClient`,message:`No context or config for this response - that doesn't seem right.`,context:{interceptor:nn,...c,httpsAgent:void 0,headers:void 0,hasContext:(0,o.notMissing)(r),hasConfig:(0,o.notMissing)(c)},code:F.InterceptorContextNotPresent}),Promise.reject(a);if((0,o.isMissing)(i))return t?.error({category:`HttpClient`,message:`ConcurrencyManager is not initialized`,context:{interceptor:nn,...c,httpsAgent:void 0,headers:void 0,concurrencyManagerInitialized:(0,o.notMissing)(i)},code:F.RateLimitOrConcurrencyManagerNotInitialized}),Promise.reject(a);let{requestId:u,targetConcurrencyKey:d,leaseSubscription:f,setRemovalSubscription:p}=c?.requestMetadata??{};if(!((0,o.notMissing)(u)&&(0,o.notMissing)(d)&&await i.releaseRequest(u,d))&&(0,o.notMissing)(c?.requestMetadata)&&t?.error({category:`HttpClient`,message:`Failed to release request from concurrency manager`,context:{...r,interceptor:nn,requestId:u,targetConcurrencyKey:d,leaseSubscription:f,setRemovalSubscription:p},code:F.RateLimiterReleaseRequestFailed}),l?.aborted)return Promise.reject(createAxiosError(`Request aborted`,c,`ERR_CANCELED`,s));let{status:m,retryAfter:h}=convertError(s,r,n,t);if(m===429&&(0,o.notMissing)(c)){let n=getRetryAfterWaitTime(h);if(c._retryCount>=5)return t?.warning({category:`HttpClient`,message:`Max retries exceeded for ${c.url}. Aborting.`,context:{...r??{},...c.requestMetadata??{},retryAfterHeader:h,retryAfterAsNumber:n}}),Promise.reject(a);let i=c?._retryCount??0,l={...c,_retryCount:i+1},u=h?n*I:(0,o.exponentialBackoffInMS)(l._retryCount);return t?.debug({category:`HttpClient`,message:`Received 429 error from ${c.url}`,context:{...r,retryAfterHeader:h,calculatedRetryAfter:u}}),await abortableDelay(u,c,s),e?.request(l)}return Promise.reject(a)},`rateLimitErrorInterceptor`),rn=`rateLimitResponseInterceptor`,rateLimitResponseInterceptor=({logger:e,context:t,concurrencyManager:n})=>__name(async r=>{let i=r?.config,a=i?.signal;if((0,o.isMissing)(t))e?.warning({category:`HttpClient`,message:`No context for this response - that doesn't seem right.`,context:{interceptor:rn,...i,httpsAgent:void 0,headers:void 0}});else if((0,o.isMissing)(n))return e?.error({category:`HttpClient`,message:`ConcurrencyManager is not initialized`,context:{interceptor:rn,...i,httpsAgent:void 0,headers:void 0,concurrencyManagerInitialized:(0,o.notMissing)(n)},code:F.RateLimitOrConcurrencyManagerNotInitialized}),r;else if((0,o.notMissing)(t.provider)&&(0,o.notMissing)(t.accountSecureId)){let t=r?.headers;if((0,o.notMissing)(t)){let n=extractRateLimitHeaders(t);e?.debug({category:`HttpClient`,message:`Rate limit headers extracted`,context:{interceptor:rn,rateLimitHeaders:n}})}let{requestId:s,targetConcurrencyKey:c,leaseSubscription:l,setRemovalSubscription:u}=i?.requestMetadata??{};if(await n.releaseRequest(s,c)||e?.error({category:`HttpClient`,message:`Failed to release request from concurrency manager`,context:{interceptor:rn,requestId:s,targetConcurrencyKey:c,leaseSubscription:l,setRemovalSubscription:u},code:F.RateLimiterReleaseRequestFailed}),a?.aborted)return Promise.reject(createAxiosError(`Request aborted`,i,`ERR_CANCELED`,r))}return r},`rateLimitResponseInterceptor`),validateRequestInterceptor=e=>(e.validateStatus??=e=>e>=200&&e<300,e),an=[{onFulfilled:validateRequestInterceptor,onRejected:null,options:void 0}],on=[{onFulfilled:null,onRejected:retryErrorInterceptor},{onFulfilled:null,onRejected:abortErrorInterceptor}],sn=[{onFulfilled:validateRequestInterceptor,onRejected:null,options:void 0},{onFulfilled:checkConcurrencyInterceptor,onRejected:null,options:void 0}],cn=[{onFulfilled:rateLimitResponseInterceptor,onRejected:rateLimitErrorInterceptor},{onFulfilled:null,onRejected:abortErrorInterceptor}],un=1,dn=1e3,fn=0,pn=59,mn=.8,hn=500;var RateLimitManager=class extends ScriptManager{constructor(...e){super(...e),this.name=`RateLimitManager`}async additionalInitialization(){}getDynamicMaxWaitTime(e,t,n,r=59,i=.8,a=500){this.readyCheck();let o=e.subPools?.find(e=>e.urlPattern instanceof RegExp?e.urlPattern.test(n??``):n?.includes(e.urlPattern))?.rateLimit??e.mainRatelimit;if(o<=0)throw Error(`Requests per second (rps) must be greater than 0.`);let s=t.subPools?.find(e=>e.urlPattern instanceof RegExp?e.urlPattern.test(n??``):n?.includes(e.urlPattern))?.maxConcurrency??t.mainMaxConcurrency;if(s<=0)throw Error(`Concurrency must be greater than 0.`);let c=r*i,l=1/Math.min(o,s/(a/1e3)),u=Math.max(7.5,c*l);return Math.min(c,u)}async getWaitTime(e,t,n){this.readyCheck();let r=`rateLimit:${e}`,i=t.subPools?.find(e=>e.urlPattern instanceof RegExp?e.urlPattern.test(n??``):n?.includes(e.urlPattern))?.subPoolKey,a=(0,o.notMissing)(i)?`${r}-${i}`:r,{mainRatelimit:s,subPools:c}=t,l=[{key:r,rateLimit:s},...c?.map(e=>{let{subPoolKey:t,rateLimit:n}=e;return{key:`${r}-${t}`,rateLimit:n}})??[]],u=l.map(e=>e.key),d=l.map(e=>e.rateLimit);return await this.executeScript(Pe.incr,[a,...u],[s.toString(),...d.map(String)])}readyCheck(){if(!this.cacheClient||!this.scriptMap?.size)throw Error(`RateLimitManager not ready`)}isReady(){return!!this?.cacheClient&&!!this?.scriptMap?.size}close(){this.scriptMap?.clear(),this.reset()}},SingletonManager=class{static{this.instances=new Map}static async prepare(e,t,...n){if(!this.instances.has(e)){let t=new e;t.getSingleton=e=>{let t=this.instances.get(e);if((0,o.isMissing)(t))throw Error(`Singleton ${e.name} not prepared yet`);if(t.hasInitFailed?.())throw Error(`${e.name} initialization failed`);let n=t.getInstanceIfReady?.();if((0,o.notMissing)(n))return n;throw Error(`${e.name} not ready`)},this.instances.set(e,t)}let r=this.instances.get(e);try{return await r.getInstance(t,...n)}catch(t){throw r.hasInitFailed?.()&&this.instances.delete(e),t}}static getIfReady(e){return this.instances.get(e)?.getInstanceIfReady?.()??null}static reset(e){this.instances.get(e)?.reset?.(),this.instances.delete(e)}static cleanupFailed(){let e=0;for(let[t,n]of this.instances){let r=n;r?.hasInitFailed?.()&&(r?.reset?.(),this.instances.delete(t),e++)}return e}};let gn=function(e){return e.HttpTransportInstanceCreateError=`HttpTransportInstanceCreateError`,e}({});const getTransportInstance=async({logger:e,redisClientConfig:t,context:n,requestConfig:r,httpsAgentConfig:i}={})=>{let a,{NODE_ENV:s}=process.env,c=n?.behaviours??[`CONCURRENCY`,`RETRY`];try{if(a=c.includes(`RETRY`)?createDefaultRetryInstance(e,n):createDefaultInstance(e,n),(0,o.isMissing)(n?.service)||(0,o.isMissing)(n?.organizationId)||s===`test`||(0,o.isMissing)(t)||(0,o.isMissing)(e))return a;let l=SingletonManager.getIfReady(RateLimitManager)??void 0,u=SingletonManager.getIfReady(ConcurrencyManager)??void 0,d=l?.isReady(),f=u?.isRedisConfigured(),p=[],m=[];if(c.includes(`CONCURRENCY`)){if(!f)throw Error(`Concurrency Manager cannot connect to Redis. Cannot create advanced transport instance.`);if(!d)throw Error(`RateLimitManager is not ready. Cannot create advanced transport instance.`);p.push(...sn),m.push(...cn)}let h=generateRequestKey(n);if((0,o.isMissing)(h))return e?.warning({category:`http-transport`,message:`Unable to create a key for transport instance - Invalid state. Using base default instance.`,context:{...n,defaultInstanceInitialized:(0,o.notMissing)(a)}}),a;let g=await je.get(h);if((0,o.notMissing)(g))return g;let _={interceptors:{requestConfigs:p,responseConfigs:m},instanceConfig:{maxBodyLength:1/0},logger:e,context:n,requestConfig:r,httpsAgentConfig:i,concurrencyManager:u,rateLimitManager:l},v=HttpTransportFactory.createInstance(_);return e?.debug({category:`http-transport`,message:`Creating new Axios instance and caching it for key: [${h}]`,context:{...n}}),await je.set(h,v),v}catch(t){return e?.error({category:`http-transport`,message:`Failed to create advanced transport instance. Using default instance.`,context:{...n,usingDefaultInstance:(0,o.notMissing)(a)},error:t,code:gn.HttpTransportInstanceCreateError}),(0,o.notMissing)(a)?a:createAxiosInstance()}},createDefaultInstance=(e,t)=>{let n={instanceConfig:{maxBodyLength:1/0},logger:e,context:t};return HttpTransportFactory.createInstance(n)??createAxiosInstance()},createDefaultRetryInstance=(e,t)=>{let n={interceptors:{requestConfigs:an,responseConfigs:on},instanceConfig:{maxBodyLength:1/0},logger:e,context:t};return HttpTransportFactory.createInstance(n)??createAxiosInstance()},createAxiosInstance=()=>l.default.create({maxBodyLength:1/0});var HttpClient=class{#e;#t;#n;#r;#i;#a;constructor({transportFactory:e=getTransportInstance,getRedisClient:t=buildRedisClientInstance,logger:n,redisClientConfig:r,errorMappingFn:i}={}){this.name=`HttpClient`,this.#e=e,this.#t=t,this.#n=n,this.#r=r,this.#i=i}#o({url:e,payload:t,method:n,context:r}){if(!r?.accountSecureId||r.accountSecureId.length<20||!e||!n)return null;let i=t?(0,o.getContentHash)(t):``;return`${r.accountSecureId}-${n.toUpperCase()}${i}-${e}`}async#s({url:e,payload:t,method:n,cacheTTL:r,context:i}){if(!this.#a||!r||r<=0)return null;let a=this.#o({url:e,payload:t,method:n,context:i});if(!a)return null;let o=await this.#a.getData(a);return o?(this.#n?.debug({category:this.name,message:`Cache hit for key [${a}].`}),o):(this.#n?.debug({category:this.name,message:`Cache miss for key [${a}].`}),null)}async#c({url:e,payload:t,method:n,cacheTTL:r,context:i,response:a}){if(!this.#a||!r||r<=0)return!1;let o=this.#o({url:e,payload:t,method:n,context:i});return o?(this.#n?.debug({category:this.name,message:`Caching result for key [${o}].`}),this.#a.setData({key:o,value:a,cacheTTL:r*60})):!1}async request({headers:e={},url:t,method:n=`get`,queryParams:r,maxRedirects:i=0,responseType:a,cacheTTL:s,context:c,traceId:l,payload:u,httpsAgent:d,httpAgent:f,requestConfig:p,httpsAgentConfig:h}){try{(0,o.notMissing)(this.#r)&&(0,o.isMissing)(this.#a)&&(this.#a=await this.#t(this.#r,this.#n,`HttpClient`));let m=this.#v(t,r),g=this.#l(e),_=this.#h(u,e),v=await this.#s({url:m,payload:_,method:n,cacheTTL:s,context:c});if(v)return{...v,responseTime:new Date};let y=P.getInstance(),b=((0,o.notMissing)(l)?await y.get(l):null)?.signal,x=await(await this.#e({redisClientConfig:this.#r,logger:this.#n,context:c,requestConfig:p,httpsAgentConfig:h})).request({headers:g,url:m,method:n,maxRedirects:i,responseType:a,data:_,httpsAgent:d,httpAgent:f,signal:b}),S={data:x.data,status:x.status,body:_,method:n,headers:this.#u(x.headers),requestUrl:t,responseType:x?.config?.responseType,responseTime:new Date};return await this.#c({url:m,payload:_,method:n,cacheTTL:s,context:c,response:S}),S}catch(e){let r=e;r.url=(0,m.redactUrl)(t),this.#n?.warning({category:this.name,message:`Request error [${n?.toUpperCase()} ${r.url}]: ${r.message}.`,error:r});let i=this.#g(r);throw(0,o.notMissing)(i)?i:e}}async get({headers:e,url:t,queryParams:n,maxRedirects:r,cacheTTL:i,context:a,traceId:o,requestConfig:s}){return this.request({url:t,method:`get`,queryParams:n,headers:e,maxRedirects:r,cacheTTL:i,context:a,traceId:o,requestConfig:s})}async post({headers:e,url:t,maxRedirects:n,cacheTTL:r,context:i,traceId:a,payload:o,requestConfig:s}){return this.request({url:t,method:`post`,headers:e,maxRedirects:n,cacheTTL:r,context:i,traceId:a,payload:o,requestConfig:s})}async requestStream({headers:e={},url:t,method:n=`get`,queryParams:r,maxRedirects:i=0,context:a,traceId:s,payload:c,httpsAgent:l,httpAgent:u,requestConfig:d,httpsAgentConfig:f}){try{let p=this.#v(t,r),m=this.#l(e),h=this.#h(c,e),g=P.getInstance(),_=((0,o.notMissing)(s)?await g.get(s):null)?.signal,v=await(await this.#e({redisClientConfig:this.#r,logger:this.#n,context:a,requestConfig:d,httpsAgentConfig:f})).request({headers:m,url:p,method:n,maxRedirects:i,responseType:`stream`,data:h,httpsAgent:l,httpAgent:u,signal:_});return{status:v.status,headers:this.#u(v.headers),stream:v.data,requestUrl:t}}catch(e){let r=e;r.url=(0,m.redactUrl)(t),this.#n?.warning({category:this.name,message:`Stream request error [${n?.toUpperCase()} ${r.url}]: ${r.message}.`,error:r});let i=this.#g(r);throw(0,o.notMissing)(i)?i:e}}#l(e){if(!e)return{};let t={};return Object.keys(e).forEach(n=>{t[n.toLowerCase()]=e[n]||``}),t}#u(e){if(!e)return{};let t={};return Object.keys(e).forEach(n=>{t[n]=e[n]||``}),t}#d(e){return e[`content-type`]===`application/x-www-form-urlencoded`}#f(e){return(0,o.isString)(e[`content-type`])?e[`content-type`]?.startsWith(`multipart/form-data`)??!1:!1}#p(e){return(0,o.isMissing)(e)||typeof e!=`object`||!e?!1:`pipe`in e&&typeof e.pipe==`function`}#m(e){return Buffer.isBuffer(e)}#h(e,t){if(!((0,o.isMissing)(e)||(0,o.isObject)(e)&&Object.keys(e).length===0))return this.#f(t)||this.#p(e)||this.#m(e)?e:this.#d(t)?h.default.stringify(e):e}#g(e){if((0,l.isAxiosError)(e)&&this.#i)return this.#i(e)}#_(e){return typeof e==`object`&&!!e&&`value`in e&&(typeof e.value==`string`||Array.isArray(e.value))}#v(e,t){if((0,o.isMissing)(t)||Object.keys(t).length===0)return e;let n={},r={},i={},a={};for(let[e,o]of Object.entries(t))if(this.#_(o)){let t=o.arrayFormat,s=o.value;t===`repeat`?r[e]=Array.isArray(s)?s:[s]:t===`brackets`?i[e]=Array.isArray(s)?s:[s]:t===`comma`?a[e]=Array.isArray(s)?s:[s]:n[e]=s}else n[e]=o;let s=[];Object.keys(n).length>0&&s.push(h.default.stringify(n)),Object.keys(r).length>0&&s.push(h.default.stringify(r,{arrayFormat:`repeat`})),Object.keys(i).length>0&&s.push(h.default.stringify(i,{arrayFormat:`brackets`})),Object.keys(a).length>0&&s.push(h.default.stringify(a,{arrayFormat:`comma`}));let c=s.join(`&`);return(0,o.notMissing)(c)?`${e}?${c}`:e}};const buildHttpClientInstance=(e,t,n)=>new HttpClient({redisClientConfig:e,logger:t,errorMappingFn:n});var HttpClientManager=class{static{this.httpClientInstance=null}static async getInstance({redisClientConfig:e,logger:t,errorMappingFn:n,getHttpClient:r=buildHttpClientInstance}){return this.httpClientInstance??=r(e,t,n),this.httpClientInstance}static resetInstance(){this.httpClientInstance=null}};const _n=[`get`,`post`,`put`,`delete`,`patch`],vn={[k.rPush]:`
|
|
114
114
|
local queueLength = redis.call('RPUSH', KEYS[1], ARGV[1])
|
|
115
115
|
|
|
116
116
|
redis.call('PEXPIRE', KEYS[1], ARGV[2])
|
|
@@ -170,9 +170,9 @@ Example:
|
|
|
170
170
|
return nil
|
|
171
171
|
`},initializeTransportSystem=async e=>{let{redisClientConfig:t,logger:n,generateUUID:r}=e;try{n?.info({category:`TransportInitialization`,message:`Starting transport system initialization`});let[e,i,a]=await Promise.all([SingletonManager.prepare(ConcurrencyManager,{redisClientConfig:t,scripts:De,logger:n,additionalArgs:r?[r]:void 0}),SingletonManager.prepare(QueueManager,{redisClientConfig:t,scripts:vn,logger:n}),SingletonManager.prepare(RateLimitManager,{redisClientConfig:t,scripts:yn,logger:n})]),o=[{name:`ConcurrencyManager`,ready:e.isReady()},{name:`QueueManager`,ready:i.isReady()},{name:`RateLimitManager`,ready:a.isReady()}],s=o.filter(e=>!e.ready);if(s.length>0){let e=s.map(e=>e.name).join(`, `);throw Error(`Failed to initialize managers: ${e}`)}return n?.info({category:`TransportInitialization`,message:`Transport system initialization completed successfully`,context:{initializedManagers:o.map(e=>e.name)}}),{concurrencyManager:e,queueManager:i,rateLimitManager:a}}catch(e){n?.error({category:`TransportInitialization`,message:`Failed to initialize transport system`,code:`TRANSPORT_INIT_ERROR`,error:e});let t=SingletonManager.cleanupFailed();throw t>0&&n?.info({category:`TransportInitialization`,message:`Cleaned up ${t} failed singleton instances`}),e}},shutdownTransportSystem=e=>{try{e?.info({category:`TransportInitialization`,message:`Starting transport system shutdown`});let t=SingletonManager.getIfReady(ConcurrencyManager),n=SingletonManager.getIfReady(QueueManager),r=SingletonManager.getIfReady(RateLimitManager);t?.close(),n?.close(),r?.close(),SingletonManager.reset(ConcurrencyManager),SingletonManager.reset(QueueManager),SingletonManager.reset(RateLimitManager),e?.info({category:`TransportInitialization`,message:`Transport system shutdown completed`})}catch(t){e?.error({category:`TransportInitialization`,message:`Error during transport system shutdown`,code:`TRANSPORT_SHUTDOWN_ERROR`,error:t})}},isTransportSystemReady=()=>{let e=SingletonManager.getIfReady(ConcurrencyManager),t=SingletonManager.getIfReady(QueueManager),n=SingletonManager.getIfReady(RateLimitManager);return!!(e?.isReady()&&t?.isReady()&&n?.isReady())},getTransportManagers=()=>{let e=SingletonManager.getIfReady(ConcurrencyManager),t=SingletonManager.getIfReady(QueueManager),n=SingletonManager.getIfReady(RateLimitManager);return e&&t&&n?{concurrencyManager:e,queueManager:t,rateLimitManager:n}:null},isHttpQueryParamValue=e=>typeof e==`object`&&!!e&&`value`in e&&(typeof e.value==`string`||Array.isArray(e.value)),toStringArray=e=>Array.isArray(e)?e:[e],toQueryValue=e=>Array.isArray(e)?e.map(String):String(e),mergeQueryValues=(e,t,n)=>{let r=toStringArray(t);if(isHttpQueryParamValue(e))return{value:[...toStringArray(e.value),...r],arrayFormat:n??e.arrayFormat};let i=[...toStringArray(e),...r];return n?{value:i,arrayFormat:n}:i},parseQueryParam=(e,t,n)=>{let r=toQueryValue(t);return e===void 0?n?{value:r,arrayFormat:n}:r:mergeQueryValues(e,r,n)},parseBodyParam=(e,t)=>Array.isArray(e)?e.concat(t):typeof e==`object`&&e&&typeof t==`object`&&t?{...e,...t}:t,parseRequestParameters=e=>e.reduce((e,t)=>{if(t.in===`query`){let n=e.query[t.name];e.query[t.name]=parseQueryParam(n,t.value,t.arrayFormat)}else if(t.in===`body`)if(t.spread)Array.isArray(t.value)?Array.isArray(e.body)?e.body=e.body.concat(t.value):e.body=t.value:typeof t.value==`object`&&t.value!==null&&(e.body={...e.body,...t.value});else{let n=e.body[t.name];e.body[t.name]=parseBodyParam(n,t.value)}else e.headers[t.name]=String(t.value);return e},{query:{},body:{},headers:{}}),bn=[`query`,`body`,`headers`],xn=[`repeat`,`brackets`,`comma`],isSuccessStatusCode=e=>(0,o.notMissing)(e)&&e>=200&&e<=299,isFailedStatusCode=e=>(0,o.notMissing)(e)&&e>=400&&e<=599,isInfoStatusCode=e=>(0,o.notMissing)(e)&&e>=100&&e<=199;var RestClient=class{async performRequest({httpClient:e,url:t,method:n,headers:r,queryParams:i,body:a,customErrorConfigs:s,requestConfig:c}){let l;try{l=await e?.request({method:n,url:t,headers:r,queryParams:i,maxRedirects:0,payload:a,requestConfig:c})}catch(e){if((0,o.isMissing)(e?.response))throw e;l=e.response}let u=translateCustomError(l,s);if(isFailedStatusCode(u?.status))throw new N(u,u.message);return u}};const Sn=`:A-Za-z_\\u00C0-\\u00D6\\u00D8-\\u00F6\\u00F8-\\u02FF\\u0370-\\u037D\\u037F-\\u1FFF\\u200C-\\u200D\\u2070-\\u218F\\u2C00-\\u2FEF\\u3001-\\uD7FF\\uF900-\\uFDCF\\uFDF0-\\uFFFD`;Sn+``;const Cn=`[`+Sn+`][:A-Za-z_\\u00C0-\\u00D6\\u00D8-\\u00F6\\u00F8-\\u02FF\\u0370-\\u037D\\u037F-\\u1FFF\\u200C-\\u200D\\u2070-\\u218F\\u2C00-\\u2FEF\\u3001-\\uD7FF\\uF900-\\uFDCF\\uFDF0-\\uFFFD\\-.\\d\\u00B7\\u0300-\\u036F\\u203F-\\u2040]*`,wn=RegExp(`^[:A-Za-z_\\u00C0-\\u00D6\\u00D8-\\u00F6\\u00F8-\\u02FF\\u0370-\\u037D\\u037F-\\u1FFF\\u200C-\\u200D\\u2070-\\u218F\\u2C00-\\u2FEF\\u3001-\\uD7FF\\uF900-\\uFDCF\\uFDF0-\\uFFFD][:A-Za-z_\\u00C0-\\u00D6\\u00D8-\\u00F6\\u00F8-\\u02FF\\u0370-\\u037D\\u037F-\\u1FFF\\u200C-\\u200D\\u2070-\\u218F\\u2C00-\\u2FEF\\u3001-\\uD7FF\\uF900-\\uFDCF\\uFDF0-\\uFFFD\\-.\\d\\u00B7\\u0300-\\u036F\\u203F-\\u2040]*$`);function getAllMatches(e,t){let n=[],r=t.exec(e);for(;r;){let i=[];i.startIndex=t.lastIndex-r[0].length;let a=r.length;for(let e=0;e<a;e++)i.push(r[e]);n.push(i),r=t.exec(e)}return n}const isName=function(e){return wn.exec(e)!=null};function isExist(e){return e!==void 0}const Tn={allowBooleanAttributes:!1,unpairedTags:[]};function validate(e,t){t=Object.assign({},Tn,t);let n=[],r=!1,i=!1;e[0]===``&&(e=e.substr(1));for(let a=0;a<e.length;a++)if(e[a]===`<`&&e[a+1]===`?`){if(a+=2,a=readPI(e,a),a.err)return a}else if(e[a]===`<`){let o=a;if(a++,e[a]===`!`){a=readCommentAndCDATA(e,a);continue}else{let s=!1;e[a]===`/`&&(s=!0,a++);let c=``;for(;a<e.length&&e[a]!==`>`&&e[a]!==` `&&e[a]!==` `&&e[a]!==`
|
|
172
172
|
`&&e[a]!==`\r`;a++)c+=e[a];if(c=c.trim(),c[c.length-1]===`/`&&(c=c.substring(0,c.length-1),a--),!validateTagName(c)){let t;return t=c.trim().length===0?`Invalid space after '<'.`:`Tag '`+c+`' is an invalid name.`,getErrorObject(`InvalidTag`,t,getLineNumberForPosition(e,a))}let l=readAttributeStr(e,a);if(l===!1)return getErrorObject(`InvalidAttr`,`Attributes for '`+c+`' have open quote.`,getLineNumberForPosition(e,a));let u=l.value;if(a=l.index,u[u.length-1]===`/`){let n=a-u.length;u=u.substring(0,u.length-1);let i=validateAttributeString(u,t);if(i===!0)r=!0;else return getErrorObject(i.err.code,i.err.msg,getLineNumberForPosition(e,n+i.err.line))}else if(s)if(l.tagClosed){if(u.trim().length>0)return getErrorObject(`InvalidTag`,`Closing tag '`+c+`' can't have attributes or invalid starting.`,getLineNumberForPosition(e,o));if(n.length===0)return getErrorObject(`InvalidTag`,`Closing tag '`+c+`' has not been opened.`,getLineNumberForPosition(e,o));{let t=n.pop();if(c!==t.tagName){let n=getLineNumberForPosition(e,t.tagStartPos);return getErrorObject(`InvalidTag`,`Expected closing tag '`+t.tagName+`' (opened in line `+n.line+`, col `+n.col+`) instead of closing tag '`+c+`'.`,getLineNumberForPosition(e,o))}n.length==0&&(i=!0)}}else return getErrorObject(`InvalidTag`,`Closing tag '`+c+`' doesn't have proper closing.`,getLineNumberForPosition(e,a));else{let s=validateAttributeString(u,t);if(s!==!0)return getErrorObject(s.err.code,s.err.msg,getLineNumberForPosition(e,a-u.length+s.err.line));if(i===!0)return getErrorObject(`InvalidXml`,`Multiple possible root nodes found.`,getLineNumberForPosition(e,a));t.unpairedTags.indexOf(c)!==-1||n.push({tagName:c,tagStartPos:o}),r=!0}for(a++;a<e.length;a++)if(e[a]===`<`)if(e[a+1]===`!`){a++,a=readCommentAndCDATA(e,a);continue}else if(e[a+1]===`?`){if(a=readPI(e,++a),a.err)return a}else break;else if(e[a]===`&`){let t=validateAmpersand(e,a);if(t==-1)return getErrorObject(`InvalidChar`,`char '&' is not expected.`,getLineNumberForPosition(e,a));a=t}else if(i===!0&&!isWhiteSpace(e[a]))return getErrorObject(`InvalidXml`,`Extra text at the end`,getLineNumberForPosition(e,a));e[a]===`<`&&a--}}else{if(isWhiteSpace(e[a]))continue;return getErrorObject(`InvalidChar`,`char '`+e[a]+`' is not expected.`,getLineNumberForPosition(e,a))}if(r){if(n.length==1)return getErrorObject(`InvalidTag`,`Unclosed tag '`+n[0].tagName+`'.`,getLineNumberForPosition(e,n[0].tagStartPos));if(n.length>0)return getErrorObject(`InvalidXml`,`Invalid '`+JSON.stringify(n.map(e=>e.tagName),null,4).replace(/\r?\n/g,``)+`' found.`,{line:1,col:1})}else return getErrorObject(`InvalidXml`,`Start tag expected.`,1);return!0}function isWhiteSpace(e){return e===` `||e===` `||e===`
|
|
173
|
-
`||e===`\r`}function readPI(e,t){let n=t;for(;t<e.length;t++)if(e[t]==`?`||e[t]==` `){let r=e.substr(n,t-n);if(t>5&&r===`xml`)return getErrorObject(`InvalidXml`,`XML declaration allowed only at the start of the document.`,getLineNumberForPosition(e,t));if(e[t]==`?`&&e[t+1]==`>`){t++;break}else continue}return t}function readCommentAndCDATA(e,t){if(e.length>t+5&&e[t+1]===`-`&&e[t+2]===`-`){for(t+=3;t<e.length;t++)if(e[t]===`-`&&e[t+1]===`-`&&e[t+2]===`>`){t+=2;break}}else if(e.length>t+8&&e[t+1]===`D`&&e[t+2]===`O`&&e[t+3]===`C`&&e[t+4]===`T`&&e[t+5]===`Y`&&e[t+6]===`P`&&e[t+7]===`E`){let n=1;for(t+=8;t<e.length;t++)if(e[t]===`<`)n++;else if(e[t]===`>`&&(n--,n===0))break}else if(e.length>t+9&&e[t+1]===`[`&&e[t+2]===`C`&&e[t+3]===`D`&&e[t+4]===`A`&&e[t+5]===`T`&&e[t+6]===`A`&&e[t+7]===`[`){for(t+=8;t<e.length;t++)if(e[t]===`]`&&e[t+1]===`]`&&e[t+2]===`>`){t+=2;break}}return t}const En=`"`,Dn=`'`;function readAttributeStr(e,t){let n=``,r=``,i=!1;for(;t<e.length;t++){if(e[t]===`"`||e[t]===`'`)r===``?r=e[t]:r!==e[t]||(r=``);else if(e[t]===`>`&&r===``){i=!0;break}n+=e[t]}return r===``?{value:n,index:t,tagClosed:i}:!1}const On=RegExp(`(\\s*)([^\\s=]+)(\\s*=)?(\\s*(['"])(([\\s\\S])*?)\\5)?`,`g`);function validateAttributeString(e,t){let n=getAllMatches(e,On),r={};for(let e=0;e<n.length;e++){if(n[e][1].length===0)return getErrorObject(`InvalidAttr`,`Attribute '`+n[e][2]+`' has no space in starting.`,getPositionFromMatch(n[e]));if(n[e][3]!==void 0&&n[e][4]===void 0)return getErrorObject(`InvalidAttr`,`Attribute '`+n[e][2]+`' is without value.`,getPositionFromMatch(n[e]));if(n[e][3]===void 0&&!t.allowBooleanAttributes)return getErrorObject(`InvalidAttr`,`boolean attribute '`+n[e][2]+`' is not allowed.`,getPositionFromMatch(n[e]));let i=n[e][2];if(!validateAttrName(i))return getErrorObject(`InvalidAttr`,`Attribute '`+i+`' is an invalid name.`,getPositionFromMatch(n[e]));if(!r.hasOwnProperty(i))r[i]=1;else return getErrorObject(`InvalidAttr`,`Attribute '`+i+`' is repeated.`,getPositionFromMatch(n[e]))}return!0}function validateNumberAmpersand(e,t){let n=/\d/;for(e[t]===`x`&&(t++,n=/[\da-fA-F]/);t<e.length;t++){if(e[t]===`;`)return t;if(!e[t].match(n))break}return-1}function validateAmpersand(e,t){if(t++,e[t]===`;`)return-1;if(e[t]===`#`)return t++,validateNumberAmpersand(e,t);let n=0;for(;t<e.length;t++,n++)if(!(e[t].match(/\w/)&&n<20)){if(e[t]===`;`)break;return-1}return t}function getErrorObject(e,t,n){return{err:{code:e,msg:t,line:n.line||n,col:n.col}}}function validateAttrName(e){return isName(e)}function validateTagName(e){return isName(e)}function getLineNumberForPosition(e,t){let n=e.substring(0,t).split(/\r?\n/);return{line:n.length,col:n[n.length-1].length+1}}function getPositionFromMatch(e){return e.startIndex+e[1].length}const kn={preserveOrder:!1,attributeNamePrefix:`@_`,attributesGroupName:!1,textNodeName:`#text`,ignoreAttributes:!0,removeNSPrefix:!1,allowBooleanAttributes:!1,parseTagValue:!0,parseAttributeValue:!1,trimValues:!0,cdataPropName:!1,numberParseOptions:{hex:!0,leadingZeros:!0,eNotation:!0},tagValueProcessor:function(e,t){return t},attributeValueProcessor:function(e,t){return t},stopNodes:[],alwaysCreateTextNode:!1,isArray:()=>!1,commentPropName:!1,unpairedTags:[],processEntities:!0,htmlEntities:!1,ignoreDeclaration:!1,ignorePiTags:!1,transformTagName:!1,transformAttributeName:!1,updateTag:function(e,t,n){return e},captureMetaData:!1},buildOptions=function(e){return Object.assign({},kn,e)};let An;An=typeof Symbol==`function`?Symbol(`XML Node Metadata`):`@@xmlMetadata`;var XmlNode=class{constructor(e){this.tagname=e,this.child=[],this[`:@`]={}}add(e,t){e===`__proto__`&&(e=`#__proto__`),this.child.push({[e]:t})}addChild(e,t){e.tagname===`__proto__`&&(e.tagname=`#__proto__`),e[`:@`]&&Object.keys(e[`:@`]).length>0?this.child.push({[e.tagname]:e.child,":@":e[`:@`]}):this.child.push({[e.tagname]:e.child}),t!==void 0&&(this.child[this.child.length-1][An]={startIndex:t})}static getMetaDataSymbol(){return An}};function readDocType(e,t){let n={};if(e[t+3]===`O`&&e[t+4]===`C`&&e[t+5]===`T`&&e[t+6]===`Y`&&e[t+7]===`P`&&e[t+8]===`E`){t+=9;let r=1,i=!1,a=!1,o=``;for(;t<e.length;t++)if(e[t]===`<`&&!a){if(i&&hasSeq(e,`!ENTITY`,t)){t+=7;let r,i;[r,i,t]=readEntityExp(e,t+1),i.indexOf(`&`)===-1&&(n[r]={regx:RegExp(`&${r};`,`g`),val:i})}else if(i&&hasSeq(e,`!ELEMENT`,t)){t+=8;let{index:n}=readElementExp(e,t+1);t=n}else if(i&&hasSeq(e,`!ATTLIST`,t))t+=8;else if(i&&hasSeq(e,`!NOTATION`,t)){t+=9;let{index:n}=readNotationExp(e,t+1);t=n}else if(hasSeq(e,`!--`,t))a=!0;else throw Error(`Invalid DOCTYPE`);r++,o=``}else if(e[t]===`>`){if(a?e[t-1]===`-`&&e[t-2]===`-`&&(a=!1,r--):r--,r===0)break}else e[t]===`[`?i=!0:o+=e[t];if(r!==0)throw Error(`Unclosed DOCTYPE`)}else throw Error(`Invalid Tag instead of DOCTYPE`);return{entities:n,i:t}}const skipWhitespace=(e,t)=>{for(;t<e.length&&/\s/.test(e[t]);)t++;return t};function readEntityExp(e,t){t=skipWhitespace(e,t);let n=``;for(;t<e.length&&!/\s/.test(e[t])&&e[t]!==`"`&&e[t]!==`'`;)n+=e[t],t++;if(validateEntityName(n),t=skipWhitespace(e,t),e.substring(t,t+6).toUpperCase()===`SYSTEM`)throw Error(`External entities are not supported`);if(e[t]===`%`)throw Error(`Parameter entities are not supported`);let r=``;return[t,r]=readIdentifierVal(e,t,`entity`),t--,[n,r,t]}function readNotationExp(e,t){t=skipWhitespace(e,t);let n=``;for(;t<e.length&&!/\s/.test(e[t]);)n+=e[t],t++;validateEntityName(n),t=skipWhitespace(e,t);let r=e.substring(t,t+6).toUpperCase();if(r!==`SYSTEM`&&r!==`PUBLIC`)throw Error(`Expected SYSTEM or PUBLIC, found "${r}"`);t+=r.length,t=skipWhitespace(e,t);let i=null,a=null;if(r===`PUBLIC`)[t,i]=readIdentifierVal(e,t,`publicIdentifier`),t=skipWhitespace(e,t),(e[t]===`"`||e[t]===`'`)&&([t,a]=readIdentifierVal(e,t,`systemIdentifier`));else if(r===`SYSTEM`&&([t,a]=readIdentifierVal(e,t,`systemIdentifier`),!a))throw Error(`Missing mandatory system identifier for SYSTEM notation`);return{notationName:n,publicIdentifier:i,systemIdentifier:a,index:--t}}function readIdentifierVal(e,t,n){let r=``,i=e[t];if(i!==`"`&&i!==`'`)throw Error(`Expected quoted string, found "${i}"`);for(t++;t<e.length&&e[t]!==i;)r+=e[t],t++;if(e[t]!==i)throw Error(`Unterminated ${n} value`);return t++,[t,r]}function readElementExp(e,t){t=skipWhitespace(e,t);let n=``;for(;t<e.length&&!/\s/.test(e[t]);)n+=e[t],t++;if(!validateEntityName(n))throw Error(`Invalid element name: "${n}"`);t=skipWhitespace(e,t);let r=``;if(e[t]===`E`&&hasSeq(e,`MPTY`,t))t+=4;else if(e[t]===`A`&&hasSeq(e,`NY`,t))t+=2;else if(e[t]===`(`){for(t++;t<e.length&&e[t]!==`)`;)r+=e[t],t++;if(e[t]!==`)`)throw Error(`Unterminated content model`)}else throw Error(`Invalid Element Expression, found "${e[t]}"`);return{elementName:n,contentModel:r.trim(),index:t}}function hasSeq(e,t,n){for(let r=0;r<t.length;r++)if(t[r]!==e[n+r+1])return!1;return!0}function validateEntityName(e){if(isName(e))return e;throw Error(`Invalid entity name ${e}`)}const jn=/^[-+]?0x[a-fA-F0-9]+$/,Mn=/^([\-\+])?(0*)([0-9]*(\.[0-9]*)?)$/,Nn={hex:!0,leadingZeros:!0,decimalPoint:`.`,eNotation:!0};function toNumber(e,t={}){if(t=Object.assign({},Nn,t),!e||typeof e!=`string`)return e;let n=e.trim();if(t.skipLike!==void 0&&t.skipLike.test(n))return e;if(e===`0`)return 0;if(t.hex&&jn.test(n))return parse_int(n,16);if(n.includes(`e`)||n.includes(`E`))return resolveEnotation(e,n,t);{let r=Mn.exec(n);if(r){let i=r[1]||``,a=r[2],o=trimZeros(r[3]),s=i?e[a.length+1]===`.`:e[a.length]===`.`;if(!t.leadingZeros&&(a.length>1||a.length===1&&!s))return e;{let r=Number(n),s=String(r);if(r===0)return r;if(s.search(/[eE]/)!==-1)return t.eNotation?r:e;if(n.indexOf(`.`)!==-1)return s===`0`||s===o||s===`${i}${o}`?r:e;let c=a?o:n;return a?c===s||i+c===s?r:e:c===s||c===i+s?r:e}}else return e}}const Pn=/^([-+])?(0*)(\d*(\.\d*)?[eE][-\+]?\d+)$/;function resolveEnotation(e,t,n){if(!n.eNotation)return e;let r=t.match(Pn);if(r){let i=r[1]||``,a=r[3].indexOf(`e`)===-1?`E`:`e`,o=r[2],s=i?e[o.length+1]===a:e[o.length]===a;return o.length>1&&s?e:o.length===1&&(r[3].startsWith(`.${a}`)||r[3][0]===a)?Number(t):n.leadingZeros&&!s?(t=(r[1]||``)+r[3],Number(t)):e}else return e}function trimZeros(e){return e&&e.indexOf(`.`)!==-1?(e=e.replace(/0+$/,``),e===`.`?e=`0`:e[0]===`.`?e=`0`+e:e[e.length-1]===`.`&&(e=e.substring(0,e.length-1)),e):e}function parse_int(e,t){if(parseInt)return parseInt(e,t);if(Number.parseInt)return Number.parseInt(e,t);if(window&&window.parseInt)return window.parseInt(e,t);throw Error(`parseInt, Number.parseInt, window.parseInt are not supported`)}function getIgnoreAttributesFn(e){return typeof e==`function`?e:Array.isArray(e)?t=>{for(let n of e)if(typeof n==`string`&&t===n||n instanceof RegExp&&n.test(t))return!0}:()=>!1}var OrderedObjParser=class{constructor(e){this.options=e,this.currentNode=null,this.tagsNodeStack=[],this.docTypeEntities={},this.lastEntities={apos:{regex:/&(apos|#39|#x27);/g,val:`'`},gt:{regex:/&(gt|#62|#x3E);/g,val:`>`},lt:{regex:/&(lt|#60|#x3C);/g,val:`<`},quot:{regex:/&(quot|#34|#x22);/g,val:`"`}},this.ampEntity={regex:/&(amp|#38|#x26);/g,val:`&`},this.htmlEntities={space:{regex:/&(nbsp|#160);/g,val:` `},cent:{regex:/&(cent|#162);/g,val:`¢`},pound:{regex:/&(pound|#163);/g,val:`£`},yen:{regex:/&(yen|#165);/g,val:`¥`},euro:{regex:/&(euro|#8364);/g,val:`€`},copyright:{regex:/&(copy|#169);/g,val:`©`},reg:{regex:/&(reg|#174);/g,val:`®`},inr:{regex:/&(inr|#8377);/g,val:`₹`},num_dec:{regex:/&#([0-9]{1,7});/g,val:(e,t)=>String.fromCodePoint(Number.parseInt(t,10))},num_hex:{regex:/&#x([0-9a-fA-F]{1,6});/g,val:(e,t)=>String.fromCodePoint(Number.parseInt(t,16))}},this.addExternalEntities=addExternalEntities,this.parseXml=parseXml,this.parseTextData=parseTextData,this.resolveNameSpace=resolveNameSpace,this.buildAttributesMap=buildAttributesMap,this.isItStopNode=isItStopNode,this.replaceEntitiesValue=In,this.readStopNodeData=readStopNodeData,this.saveTextToParentTag=saveTextToParentTag,this.addChild=addChild,this.ignoreAttributesFn=getIgnoreAttributesFn(this.options.ignoreAttributes)}};function addExternalEntities(e){let t=Object.keys(e);for(let n=0;n<t.length;n++){let r=t[n];this.lastEntities[r]={regex:RegExp(`&`+r+`;`,`g`),val:e[r]}}}function parseTextData(e,t,n,r,i,a,o){if(e!==void 0&&(this.options.trimValues&&!r&&(e=e.trim()),e.length>0)){o||(e=this.replaceEntitiesValue(e));let r=this.options.tagValueProcessor(t,e,n,i,a);return r==null?e:typeof r!=typeof e||r!==e?r:this.options.trimValues||e.trim()===e?parseValue(e,this.options.parseTagValue,this.options.numberParseOptions):e}}function resolveNameSpace(e){if(this.options.removeNSPrefix){let t=e.split(`:`),n=e.charAt(0)===`/`?`/`:``;if(t[0]===`xmlns`)return``;t.length===2&&(e=n+t[1])}return e}const Fn=RegExp(`([^\\s=]+)\\s*(=\\s*(['"])([\\s\\S]*?)\\3)?`,`gm`);function buildAttributesMap(e,t,n){if(this.options.ignoreAttributes!==!0&&typeof e==`string`){let n=getAllMatches(e,Fn),r=n.length,i={};for(let e=0;e<r;e++){let r=this.resolveNameSpace(n[e][1]);if(this.ignoreAttributesFn(r,t))continue;let a=n[e][4],o=this.options.attributeNamePrefix+r;if(r.length)if(this.options.transformAttributeName&&(o=this.options.transformAttributeName(o)),o===`__proto__`&&(o=`#__proto__`),a!==void 0){this.options.trimValues&&(a=a.trim()),a=this.replaceEntitiesValue(a);let e=this.options.attributeValueProcessor(r,a,t);e==null?i[o]=a:typeof e!=typeof a||e!==a?i[o]=e:i[o]=parseValue(a,this.options.parseAttributeValue,this.options.numberParseOptions)}else this.options.allowBooleanAttributes&&(i[o]=!0)}if(!Object.keys(i).length)return;if(this.options.attributesGroupName){let e={};return e[this.options.attributesGroupName]=i,e}return i}}const parseXml=function(e){e=e.replace(/\r\n?/g,`
|
|
174
|
-
`);let t=new XmlNode(`!xml`),n=t,r=``,i=``;for(let a=0;a<e.length;a++)if(e[a]===`<`)if(e[a+1]===`/`){let t=findClosingIndex(e,`>`,a,`Closing Tag is not closed.`),o=e.substring(a+2,t).trim();if(this.options.removeNSPrefix){let e=o.indexOf(`:`);e!==-1&&(o=o.substr(e+1))}this.options.transformTagName&&(o=this.options.transformTagName(o)),n&&(r=this.saveTextToParentTag(r,n,i));let s=i.substring(i.lastIndexOf(`.`)+1);if(o&&this.options.unpairedTags.indexOf(o)!==-1)throw Error(`Unpaired tag can not be used as closing tag: </${o}>`);let c=0;s&&this.options.unpairedTags.indexOf(s)!==-1?(c=i.lastIndexOf(`.`,i.lastIndexOf(`.`)-1),this.tagsNodeStack.pop()):c=i.lastIndexOf(`.`),i=i.substring(0,c),n=this.tagsNodeStack.pop(),r=``,a=t}else if(e[a+1]===`?`){let t=readTagExp(e,a,!1,`?>`);if(!t)throw Error(`Pi Tag is not closed.`);if(r=this.saveTextToParentTag(r,n,i),!(this.options.ignoreDeclaration&&t.tagName===`?xml`||this.options.ignorePiTags)){let e=new XmlNode(t.tagName);e.add(this.options.textNodeName,``),t.tagName!==t.tagExp&&t.attrExpPresent&&(e[`:@`]=this.buildAttributesMap(t.tagExp,i,t.tagName)),this.addChild(n,e,i,a)}a=t.closeIndex+1}else if(e.substr(a+1,3)===`!--`){let t=findClosingIndex(e,`-->`,a+4,`Comment is not closed.`);if(this.options.commentPropName){let o=e.substring(a+4,t-2);r=this.saveTextToParentTag(r,n,i),n.add(this.options.commentPropName,[{[this.options.textNodeName]:o}])}a=t}else if(e.substr(a+1,2)===`!D`){let t=readDocType(e,a);this.docTypeEntities=t.entities,a=t.i}else if(e.substr(a+1,2)===`![`){let t=findClosingIndex(e,`]]>`,a,`CDATA is not closed.`)-2,o=e.substring(a+9,t);r=this.saveTextToParentTag(r,n,i);let s=this.parseTextData(o,n.tagname,i,!0,!1,!0,!0);s??=``,this.options.cdataPropName?n.add(this.options.cdataPropName,[{[this.options.textNodeName]:o}]):n.add(this.options.textNodeName,s),a=t+2}else{let o=readTagExp(e,a,this.options.removeNSPrefix),s=o.tagName,c=o.rawTagName,l=o.tagExp,u=o.attrExpPresent,d=o.closeIndex;this.options.transformTagName&&(s=this.options.transformTagName(s)),n&&r&&n.tagname!==`!xml`&&(r=this.saveTextToParentTag(r,n,i,!1));let f=n;f&&this.options.unpairedTags.indexOf(f.tagname)!==-1&&(n=this.tagsNodeStack.pop(),i=i.substring(0,i.lastIndexOf(`.`))),s!==t.tagname&&(i+=i?`.`+s:s);let p=a;if(this.isItStopNode(this.options.stopNodes,i,s)){let t=``;if(l.length>0&&l.lastIndexOf(`/`)===l.length-1)s[s.length-1]===`/`?(s=s.substr(0,s.length-1),i=i.substr(0,i.length-1),l=s):l=l.substr(0,l.length-1),a=o.closeIndex;else if(this.options.unpairedTags.indexOf(s)!==-1)a=o.closeIndex;else{let n=this.readStopNodeData(e,c,d+1);if(!n)throw Error(`Unexpected end of ${c}`);a=n.i,t=n.tagContent}let r=new XmlNode(s);s!==l&&u&&(r[`:@`]=this.buildAttributesMap(l,i,s)),t&&=this.parseTextData(t,s,i,!0,u,!0,!0),i=i.substr(0,i.lastIndexOf(`.`)),r.add(this.options.textNodeName,t),this.addChild(n,r,i,p)}else{if(l.length>0&&l.lastIndexOf(`/`)===l.length-1){s[s.length-1]===`/`?(s=s.substr(0,s.length-1),i=i.substr(0,i.length-1),l=s):l=l.substr(0,l.length-1),this.options.transformTagName&&(s=this.options.transformTagName(s));let e=new XmlNode(s);s!==l&&u&&(e[`:@`]=this.buildAttributesMap(l,i,s)),this.addChild(n,e,i,p),i=i.substr(0,i.lastIndexOf(`.`))}else{let e=new XmlNode(s);this.tagsNodeStack.push(n),s!==l&&u&&(e[`:@`]=this.buildAttributesMap(l,i,s)),this.addChild(n,e,i,p),n=e}r=``,a=d}}else r+=e[a];return t.child};function addChild(e,t,n,r){this.options.captureMetaData||(r=void 0);let i=this.options.updateTag(t.tagname,n,t[`:@`]);i===!1||(typeof i==`string`&&(t.tagname=i),e.addChild(t,r))}const In=__name(function(e){if(this.options.processEntities){for(let t in this.docTypeEntities){let n=this.docTypeEntities[t];e=e.replace(n.regx,n.val)}for(let t in this.lastEntities){let n=this.lastEntities[t];e=e.replace(n.regex,n.val)}if(this.options.htmlEntities)for(let t in this.htmlEntities){let n=this.htmlEntities[t];e=e.replace(n.regex,n.val)}e=e.replace(this.ampEntity.regex,this.ampEntity.val)}return e},`replaceEntitiesValue`);function saveTextToParentTag(e,t,n,r){return e&&=(r===void 0&&(r=t.child.length===0),e=this.parseTextData(e,t.tagname,n,!1,t[`:@`]?Object.keys(t[`:@`]).length!==0:!1,r),e!==void 0&&e!==``&&t.add(this.options.textNodeName,e),``),e}function isItStopNode(e,t,n){let r=`*.`+n;for(let n in e){let i=e[n];if(r===i||t===i)return!0}return!1}function tagExpWithClosingIndex(e,t,n=`>`){let r,i=``;for(let a=t;a<e.length;a++){let t=e[a];if(r)t===r&&(r=``);else if(t===`"`||t===`'`)r=t;else if(t===n[0])if(n[1]){if(e[a+1]===n[1])return{data:i,index:a}}else return{data:i,index:a};else t===` `&&(t=` `);i+=t}}function findClosingIndex(e,t,n,r){let i=e.indexOf(t,n);if(i===-1)throw Error(r);return i+t.length-1}function readTagExp(e,t,n,r=`>`){let i=tagExpWithClosingIndex(e,t+1,r);if(!i)return;let a=i.data,o=i.index,s=a.search(/\s/),c=a,l=!0;s!==-1&&(c=a.substring(0,s),a=a.substring(s+1).trimStart());let u=c;if(n){let e=c.indexOf(`:`);e!==-1&&(c=c.substr(e+1),l=c!==i.data.substr(e+1))}return{tagName:c,tagExp:a,closeIndex:o,attrExpPresent:l,rawTagName:u}}function readStopNodeData(e,t,n){let r=n,i=1;for(;n<e.length;n++)if(e[n]===`<`)if(e[n+1]===`/`){let a=findClosingIndex(e,`>`,n,`${t} is not closed`);if(e.substring(n+2,a).trim()===t&&(i--,i===0))return{tagContent:e.substring(r,n),i:a};n=a}else if(e[n+1]===`?`)n=findClosingIndex(e,`?>`,n+1,`StopNode is not closed.`);else if(e.substr(n+1,3)===`!--`)n=findClosingIndex(e,`-->`,n+3,`StopNode is not closed.`);else if(e.substr(n+1,2)===`![`)n=findClosingIndex(e,`]]>`,n,`StopNode is not closed.`)-2;else{let r=readTagExp(e,n,`>`);r&&((r&&r.tagName)===t&&r.tagExp[r.tagExp.length-1]!==`/`&&i++,n=r.closeIndex)}}function parseValue(e,t,n){if(t&&typeof e==`string`){let t=e.trim();return t===`true`?!0:t===`false`?!1:toNumber(e,n)}else if(isExist(e))return e;else return``}const Ln=XmlNode.getMetaDataSymbol();function prettify(e,t){return compress(e,t)}function compress(e,t,n){let r,i={};for(let a=0;a<e.length;a++){let o=e[a],s=propName$1(o),c=``;if(c=n===void 0?s:n+`.`+s,s===t.textNodeName)r===void 0?r=o[s]:r+=``+o[s];else if(s===void 0)continue;else if(o[s]){let e=compress(o[s],t,c),n=isLeafTag(e,t);o[Ln]!==void 0&&(e[Ln]=o[Ln]),o[`:@`]?assignAttributes(e,o[`:@`],c,t):Object.keys(e).length===1&&e[t.textNodeName]!==void 0&&!t.alwaysCreateTextNode?e=e[t.textNodeName]:Object.keys(e).length===0&&(t.alwaysCreateTextNode?e[t.textNodeName]=``:e=``),i[s]!==void 0&&i.hasOwnProperty(s)?(Array.isArray(i[s])||(i[s]=[i[s]]),i[s].push(e)):t.isArray(s,c,n)?i[s]=[e]:i[s]=e}}return typeof r==`string`?r.length>0&&(i[t.textNodeName]=r):r!==void 0&&(i[t.textNodeName]=r),i}function propName$1(e){let t=Object.keys(e);for(let e=0;e<t.length;e++){let n=t[e];if(n!==`:@`)return n}}__name(propName$1,`propName`);function assignAttributes(e,t,n,r){if(t){let i=Object.keys(t),a=i.length;for(let o=0;o<a;o++){let a=i[o];r.isArray(a,n+`.`+a,!0,!0)?e[a]=[t[a]]:e[a]=t[a]}}}function isLeafTag(e,t){let{textNodeName:n}=t,r=Object.keys(e).length;return!!(r===0||r===1&&(e[n]||typeof e[n]==`boolean`||e[n]===0))}var XMLParser=class{constructor(e){this.externalEntities={},this.options=buildOptions(e)}parse(e,t){if(typeof e!=`string`)if(e.toString)e=e.toString();else throw Error(`XML data is accepted in String or Bytes[] form.`);if(t){t===!0&&(t={});let n=validate(e,t);if(n!==!0)throw Error(`${n.err.msg}:${n.err.line}:${n.err.col}`)}let n=new OrderedObjParser(this.options);n.addExternalEntities(this.externalEntities);let r=n.parseXml(e);return this.options.preserveOrder||r===void 0?r:prettify(r,this.options)}addEntity(e,t){if(t.indexOf(`&`)!==-1)throw Error(`Entity value can't have '&'`);if(e.indexOf(`&`)!==-1||e.indexOf(`;`)!==-1)throw Error(`An entity must be set without '&' and ';'. Eg. use '#xD' for '
'`);if(t===`&`)throw Error(`An entity with value '&' is not permitted`);this.externalEntities[e]=t}static getMetaDataSymbol(){return XmlNode.getMetaDataSymbol()}};const Rn=`
|
|
175
|
-
`;function toXml(e,t){let n=``;
|
|
176
|
-
`)
|
|
173
|
+
`||e===`\r`}function readPI(e,t){let n=t;for(;t<e.length;t++)if(e[t]==`?`||e[t]==` `){let r=e.substr(n,t-n);if(t>5&&r===`xml`)return getErrorObject(`InvalidXml`,`XML declaration allowed only at the start of the document.`,getLineNumberForPosition(e,t));if(e[t]==`?`&&e[t+1]==`>`){t++;break}else continue}return t}function readCommentAndCDATA(e,t){if(e.length>t+5&&e[t+1]===`-`&&e[t+2]===`-`){for(t+=3;t<e.length;t++)if(e[t]===`-`&&e[t+1]===`-`&&e[t+2]===`>`){t+=2;break}}else if(e.length>t+8&&e[t+1]===`D`&&e[t+2]===`O`&&e[t+3]===`C`&&e[t+4]===`T`&&e[t+5]===`Y`&&e[t+6]===`P`&&e[t+7]===`E`){let n=1;for(t+=8;t<e.length;t++)if(e[t]===`<`)n++;else if(e[t]===`>`&&(n--,n===0))break}else if(e.length>t+9&&e[t+1]===`[`&&e[t+2]===`C`&&e[t+3]===`D`&&e[t+4]===`A`&&e[t+5]===`T`&&e[t+6]===`A`&&e[t+7]===`[`){for(t+=8;t<e.length;t++)if(e[t]===`]`&&e[t+1]===`]`&&e[t+2]===`>`){t+=2;break}}return t}const En=`"`,Dn=`'`;function readAttributeStr(e,t){let n=``,r=``,i=!1;for(;t<e.length;t++){if(e[t]===`"`||e[t]===`'`)r===``?r=e[t]:r!==e[t]||(r=``);else if(e[t]===`>`&&r===``){i=!0;break}n+=e[t]}return r===``?{value:n,index:t,tagClosed:i}:!1}const On=RegExp(`(\\s*)([^\\s=]+)(\\s*=)?(\\s*(['"])(([\\s\\S])*?)\\5)?`,`g`);function validateAttributeString(e,t){let n=getAllMatches(e,On),r={};for(let e=0;e<n.length;e++){if(n[e][1].length===0)return getErrorObject(`InvalidAttr`,`Attribute '`+n[e][2]+`' has no space in starting.`,getPositionFromMatch(n[e]));if(n[e][3]!==void 0&&n[e][4]===void 0)return getErrorObject(`InvalidAttr`,`Attribute '`+n[e][2]+`' is without value.`,getPositionFromMatch(n[e]));if(n[e][3]===void 0&&!t.allowBooleanAttributes)return getErrorObject(`InvalidAttr`,`boolean attribute '`+n[e][2]+`' is not allowed.`,getPositionFromMatch(n[e]));let i=n[e][2];if(!validateAttrName(i))return getErrorObject(`InvalidAttr`,`Attribute '`+i+`' is an invalid name.`,getPositionFromMatch(n[e]));if(!Object.prototype.hasOwnProperty.call(r,i))r[i]=1;else return getErrorObject(`InvalidAttr`,`Attribute '`+i+`' is repeated.`,getPositionFromMatch(n[e]))}return!0}function validateNumberAmpersand(e,t){let n=/\d/;for(e[t]===`x`&&(t++,n=/[\da-fA-F]/);t<e.length;t++){if(e[t]===`;`)return t;if(!e[t].match(n))break}return-1}function validateAmpersand(e,t){if(t++,e[t]===`;`)return-1;if(e[t]===`#`)return t++,validateNumberAmpersand(e,t);let n=0;for(;t<e.length;t++,n++)if(!(e[t].match(/\w/)&&n<20)){if(e[t]===`;`)break;return-1}return t}function getErrorObject(e,t,n){return{err:{code:e,msg:t,line:n.line||n,col:n.col}}}function validateAttrName(e){return isName(e)}function validateTagName(e){return isName(e)}function getLineNumberForPosition(e,t){let n=e.substring(0,t).split(/\r?\n/);return{line:n.length,col:n[n.length-1].length+1}}function getPositionFromMatch(e){return e.startIndex+e[1].length}const kn={preserveOrder:!1,attributeNamePrefix:`@_`,attributesGroupName:!1,textNodeName:`#text`,ignoreAttributes:!0,removeNSPrefix:!1,allowBooleanAttributes:!1,parseTagValue:!0,parseAttributeValue:!1,trimValues:!0,cdataPropName:!1,numberParseOptions:{hex:!0,leadingZeros:!0,eNotation:!0},tagValueProcessor:function(e,t){return t},attributeValueProcessor:function(e,t){return t},stopNodes:[],alwaysCreateTextNode:!1,isArray:()=>!1,commentPropName:!1,unpairedTags:[],processEntities:!0,htmlEntities:!1,ignoreDeclaration:!1,ignorePiTags:!1,transformTagName:!1,transformAttributeName:!1,updateTag:function(e,t,n){return e},captureMetaData:!1,maxNestedTags:100,strictReservedNames:!0};function normalizeProcessEntities(e){return typeof e==`boolean`?{enabled:e,maxEntitySize:1e4,maxExpansionDepth:10,maxTotalExpansions:1e3,maxExpandedLength:1e5,maxEntityCount:100,allowedTags:null,tagFilter:null}:typeof e==`object`&&e?{enabled:e.enabled!==!1,maxEntitySize:e.maxEntitySize??1e4,maxExpansionDepth:e.maxExpansionDepth??10,maxTotalExpansions:e.maxTotalExpansions??1e3,maxExpandedLength:e.maxExpandedLength??1e5,maxEntityCount:e.maxEntityCount??100,allowedTags:e.allowedTags??null,tagFilter:e.tagFilter??null}:normalizeProcessEntities(!0)}const buildOptions=function(e){let t=Object.assign({},kn,e);return t.processEntities=normalizeProcessEntities(t.processEntities),t};let An;An=typeof Symbol==`function`?Symbol(`XML Node Metadata`):`@@xmlMetadata`;var XmlNode=class{constructor(e){this.tagname=e,this.child=[],this[`:@`]=Object.create(null)}add(e,t){e===`__proto__`&&(e=`#__proto__`),this.child.push({[e]:t})}addChild(e,t){e.tagname===`__proto__`&&(e.tagname=`#__proto__`),e[`:@`]&&Object.keys(e[`:@`]).length>0?this.child.push({[e.tagname]:e.child,":@":e[`:@`]}):this.child.push({[e.tagname]:e.child}),t!==void 0&&(this.child[this.child.length-1][An]={startIndex:t})}static getMetaDataSymbol(){return An}},DocTypeReader=class{constructor(e){this.suppressValidationErr=!e,this.options=e}readDocType(e,t){let n=Object.create(null),r=0;if(e[t+3]===`O`&&e[t+4]===`C`&&e[t+5]===`T`&&e[t+6]===`Y`&&e[t+7]===`P`&&e[t+8]===`E`){t+=9;let i=1,a=!1,o=!1,s=``;for(;t<e.length;t++)if(e[t]===`<`&&!o){if(a&&hasSeq(e,`!ENTITY`,t)){t+=7;let i,a;if([i,a,t]=this.readEntityExp(e,t+1,this.suppressValidationErr),a.indexOf(`&`)===-1){if(this.options.enabled!==!1&&this.options.maxEntityCount&&r>=this.options.maxEntityCount)throw Error(`Entity count (${r+1}) exceeds maximum allowed (${this.options.maxEntityCount})`);let e=i.replace(/[.\-+*:]/g,`\\.`);n[i]={regx:RegExp(`&${e};`,`g`),val:a},r++}}else if(a&&hasSeq(e,`!ELEMENT`,t)){t+=8;let{index:n}=this.readElementExp(e,t+1);t=n}else if(a&&hasSeq(e,`!ATTLIST`,t))t+=8;else if(a&&hasSeq(e,`!NOTATION`,t)){t+=9;let{index:n}=this.readNotationExp(e,t+1,this.suppressValidationErr);t=n}else if(hasSeq(e,`!--`,t))o=!0;else throw Error(`Invalid DOCTYPE`);i++,s=``}else if(e[t]===`>`){if(o?e[t-1]===`-`&&e[t-2]===`-`&&(o=!1,i--):i--,i===0)break}else e[t]===`[`?a=!0:s+=e[t];if(i!==0)throw Error(`Unclosed DOCTYPE`)}else throw Error(`Invalid Tag instead of DOCTYPE`);return{entities:n,i:t}}readEntityExp(e,t){t=skipWhitespace(e,t);let n=``;for(;t<e.length&&!/\s/.test(e[t])&&e[t]!==`"`&&e[t]!==`'`;)n+=e[t],t++;if(validateEntityName(n),t=skipWhitespace(e,t),!this.suppressValidationErr){if(e.substring(t,t+6).toUpperCase()===`SYSTEM`)throw Error(`External entities are not supported`);if(e[t]===`%`)throw Error(`Parameter entities are not supported`)}let r=``;if([t,r]=this.readIdentifierVal(e,t,`entity`),this.options.enabled!==!1&&this.options.maxEntitySize&&r.length>this.options.maxEntitySize)throw Error(`Entity "${n}" size (${r.length}) exceeds maximum allowed size (${this.options.maxEntitySize})`);return t--,[n,r,t]}readNotationExp(e,t){t=skipWhitespace(e,t);let n=``;for(;t<e.length&&!/\s/.test(e[t]);)n+=e[t],t++;!this.suppressValidationErr&&validateEntityName(n),t=skipWhitespace(e,t);let r=e.substring(t,t+6).toUpperCase();if(!this.suppressValidationErr&&r!==`SYSTEM`&&r!==`PUBLIC`)throw Error(`Expected SYSTEM or PUBLIC, found "${r}"`);t+=r.length,t=skipWhitespace(e,t);let i=null,a=null;if(r===`PUBLIC`)[t,i]=this.readIdentifierVal(e,t,`publicIdentifier`),t=skipWhitespace(e,t),(e[t]===`"`||e[t]===`'`)&&([t,a]=this.readIdentifierVal(e,t,`systemIdentifier`));else if(r===`SYSTEM`&&([t,a]=this.readIdentifierVal(e,t,`systemIdentifier`),!this.suppressValidationErr&&!a))throw Error(`Missing mandatory system identifier for SYSTEM notation`);return{notationName:n,publicIdentifier:i,systemIdentifier:a,index:--t}}readIdentifierVal(e,t,n){let r=``,i=e[t];if(i!==`"`&&i!==`'`)throw Error(`Expected quoted string, found "${i}"`);for(t++;t<e.length&&e[t]!==i;)r+=e[t],t++;if(e[t]!==i)throw Error(`Unterminated ${n} value`);return t++,[t,r]}readElementExp(e,t){t=skipWhitespace(e,t);let n=``;for(;t<e.length&&!/\s/.test(e[t]);)n+=e[t],t++;if(!this.suppressValidationErr&&!isName(n))throw Error(`Invalid element name: "${n}"`);t=skipWhitespace(e,t);let r=``;if(e[t]===`E`&&hasSeq(e,`MPTY`,t))t+=4;else if(e[t]===`A`&&hasSeq(e,`NY`,t))t+=2;else if(e[t]===`(`){for(t++;t<e.length&&e[t]!==`)`;)r+=e[t],t++;if(e[t]!==`)`)throw Error(`Unterminated content model`)}else if(!this.suppressValidationErr)throw Error(`Invalid Element Expression, found "${e[t]}"`);return{elementName:n,contentModel:r.trim(),index:t}}readAttlistExp(e,t){t=skipWhitespace(e,t);let n=``;for(;t<e.length&&!/\s/.test(e[t]);)n+=e[t],t++;validateEntityName(n),t=skipWhitespace(e,t);let r=``;for(;t<e.length&&!/\s/.test(e[t]);)r+=e[t],t++;if(!validateEntityName(r))throw Error(`Invalid attribute name: "${r}"`);t=skipWhitespace(e,t);let i=``;if(e.substring(t,t+8).toUpperCase()===`NOTATION`){if(i=`NOTATION`,t+=8,t=skipWhitespace(e,t),e[t]!==`(`)throw Error(`Expected '(', found "${e[t]}"`);t++;let n=[];for(;t<e.length&&e[t]!==`)`;){let r=``;for(;t<e.length&&e[t]!==`|`&&e[t]!==`)`;)r+=e[t],t++;if(r=r.trim(),!validateEntityName(r))throw Error(`Invalid notation name: "${r}"`);n.push(r),e[t]===`|`&&(t++,t=skipWhitespace(e,t))}if(e[t]!==`)`)throw Error(`Unterminated list of notations`);t++,i+=` (`+n.join(`|`)+`)`}else{for(;t<e.length&&!/\s/.test(e[t]);)i+=e[t],t++;if(!this.suppressValidationErr&&![`CDATA`,`ID`,`IDREF`,`IDREFS`,`ENTITY`,`ENTITIES`,`NMTOKEN`,`NMTOKENS`].includes(i.toUpperCase()))throw Error(`Invalid attribute type: "${i}"`)}t=skipWhitespace(e,t);let a=``;return e.substring(t,t+8).toUpperCase()===`#REQUIRED`?(a=`#REQUIRED`,t+=8):e.substring(t,t+7).toUpperCase()===`#IMPLIED`?(a=`#IMPLIED`,t+=7):[t,a]=this.readIdentifierVal(e,t,`ATTLIST`),{elementName:n,attributeName:r,attributeType:i,defaultValue:a,index:t}}};const skipWhitespace=(e,t)=>{for(;t<e.length&&/\s/.test(e[t]);)t++;return t};function hasSeq(e,t,n){for(let r=0;r<t.length;r++)if(t[r]!==e[n+r+1])return!1;return!0}function validateEntityName(e){if(isName(e))return e;throw Error(`Invalid entity name ${e}`)}const jn=/^[-+]?0x[a-fA-F0-9]+$/,Mn=/^([\-\+])?(0*)([0-9]*(\.[0-9]*)?)$/,Nn={hex:!0,leadingZeros:!0,decimalPoint:`.`,eNotation:!0,infinity:`original`};function toNumber(e,t={}){if(t=Object.assign({},Nn,t),!e||typeof e!=`string`)return e;let n=e.trim();if(t.skipLike!==void 0&&t.skipLike.test(n))return e;if(e===`0`)return 0;if(t.hex&&jn.test(n))return parse_int(n,16);if(isFinite(n)){if(n.includes(`e`)||n.includes(`E`))return resolveEnotation(e,n,t);{let r=Mn.exec(n);if(r){let i=r[1]||``,a=r[2],o=trimZeros(r[3]),s=i?e[a.length+1]===`.`:e[a.length]===`.`;if(!t.leadingZeros&&(a.length>1||a.length===1&&!s))return e;{let r=Number(n),s=String(r);if(r===0)return r;if(s.search(/[eE]/)!==-1)return t.eNotation?r:e;if(n.indexOf(`.`)!==-1)return s===`0`||s===o||s===`${i}${o}`?r:e;let c=a?o:n;return a?c===s||i+c===s?r:e:c===s||c===i+s?r:e}}else return e}}else return handleInfinity(e,Number(n),t)}const Pn=/^([-+])?(0*)(\d*(\.\d*)?[eE][-\+]?\d+)$/;function resolveEnotation(e,t,n){if(!n.eNotation)return e;let r=t.match(Pn);if(r){let i=r[1]||``,a=r[3].indexOf(`e`)===-1?`E`:`e`,o=r[2],s=i?e[o.length+1]===a:e[o.length]===a;return o.length>1&&s?e:o.length===1&&(r[3].startsWith(`.${a}`)||r[3][0]===a)?Number(t):n.leadingZeros&&!s?(t=(r[1]||``)+r[3],Number(t)):e}else return e}function trimZeros(e){return e&&e.indexOf(`.`)!==-1?(e=e.replace(/0+$/,``),e===`.`?e=`0`:e[0]===`.`?e=`0`+e:e[e.length-1]===`.`&&(e=e.substring(0,e.length-1)),e):e}function parse_int(e,t){if(parseInt)return parseInt(e,t);if(Number.parseInt)return Number.parseInt(e,t);if(window&&window.parseInt)return window.parseInt(e,t);throw Error(`parseInt, Number.parseInt, window.parseInt are not supported`)}function handleInfinity(e,t,n){let r=t===1/0;switch(n.infinity.toLowerCase()){case`null`:return null;case`infinity`:return t;case`string`:return r?`Infinity`:`-Infinity`;case`original`:default:return e}}function getIgnoreAttributesFn$1(e){return typeof e==`function`?e:Array.isArray(e)?t=>{for(let n of e)if(typeof n==`string`&&t===n||n instanceof RegExp&&n.test(t))return!0}:()=>!1}__name(getIgnoreAttributesFn$1,`getIgnoreAttributesFn`);var OrderedObjParser=class{constructor(e){if(this.options=e,this.currentNode=null,this.tagsNodeStack=[],this.docTypeEntities={},this.lastEntities={apos:{regex:/&(apos|#39|#x27);/g,val:`'`},gt:{regex:/&(gt|#62|#x3E);/g,val:`>`},lt:{regex:/&(lt|#60|#x3C);/g,val:`<`},quot:{regex:/&(quot|#34|#x22);/g,val:`"`}},this.ampEntity={regex:/&(amp|#38|#x26);/g,val:`&`},this.htmlEntities={space:{regex:/&(nbsp|#160);/g,val:` `},cent:{regex:/&(cent|#162);/g,val:`¢`},pound:{regex:/&(pound|#163);/g,val:`£`},yen:{regex:/&(yen|#165);/g,val:`¥`},euro:{regex:/&(euro|#8364);/g,val:`€`},copyright:{regex:/&(copy|#169);/g,val:`©`},reg:{regex:/&(reg|#174);/g,val:`®`},inr:{regex:/&(inr|#8377);/g,val:`₹`},num_dec:{regex:/&#([0-9]{1,7});/g,val:(e,t)=>fromCodePoint(t,10,`&#`)},num_hex:{regex:/&#x([0-9a-fA-F]{1,6});/g,val:(e,t)=>fromCodePoint(t,16,`&#x`)}},this.addExternalEntities=addExternalEntities,this.parseXml=parseXml,this.parseTextData=parseTextData,this.resolveNameSpace=resolveNameSpace,this.buildAttributesMap=buildAttributesMap,this.isItStopNode=isItStopNode,this.replaceEntitiesValue=In,this.readStopNodeData=readStopNodeData,this.saveTextToParentTag=saveTextToParentTag,this.addChild=addChild,this.ignoreAttributesFn=getIgnoreAttributesFn$1(this.options.ignoreAttributes),this.entityExpansionCount=0,this.currentExpandedLength=0,this.options.stopNodes&&this.options.stopNodes.length>0){this.stopNodesExact=new Set,this.stopNodesWildcard=new Set;for(let e=0;e<this.options.stopNodes.length;e++){let t=this.options.stopNodes[e];typeof t==`string`&&(t.startsWith(`*.`)?this.stopNodesWildcard.add(t.substring(2)):this.stopNodesExact.add(t))}}}};function addExternalEntities(e){let t=Object.keys(e);for(let n=0;n<t.length;n++){let r=t[n],i=r.replace(/[.\-+*:]/g,`\\.`);this.lastEntities[r]={regex:RegExp(`&`+i+`;`,`g`),val:e[r]}}}function parseTextData(e,t,n,r,i,a,o){if(e!==void 0&&(this.options.trimValues&&!r&&(e=e.trim()),e.length>0)){o||(e=this.replaceEntitiesValue(e,t,n));let r=this.options.tagValueProcessor(t,e,n,i,a);return r==null?e:typeof r!=typeof e||r!==e?r:this.options.trimValues||e.trim()===e?parseValue(e,this.options.parseTagValue,this.options.numberParseOptions):e}}function resolveNameSpace(e){if(this.options.removeNSPrefix){let t=e.split(`:`),n=e.charAt(0)===`/`?`/`:``;if(t[0]===`xmlns`)return``;t.length===2&&(e=n+t[1])}return e}const Fn=RegExp(`([^\\s=]+)\\s*(=\\s*(['"])([\\s\\S]*?)\\3)?`,`gm`);function buildAttributesMap(e,t,n){if(this.options.ignoreAttributes!==!0&&typeof e==`string`){let r=getAllMatches(e,Fn),i=r.length,a={};for(let e=0;e<i;e++){let i=this.resolveNameSpace(r[e][1]);if(this.ignoreAttributesFn(i,t))continue;let o=r[e][4],s=this.options.attributeNamePrefix+i;if(i.length)if(this.options.transformAttributeName&&(s=this.options.transformAttributeName(s)),s===`__proto__`&&(s=`#__proto__`),o!==void 0){this.options.trimValues&&(o=o.trim()),o=this.replaceEntitiesValue(o,n,t);let e=this.options.attributeValueProcessor(i,o,t);e==null?a[s]=o:typeof e!=typeof o||e!==o?a[s]=e:a[s]=parseValue(o,this.options.parseAttributeValue,this.options.numberParseOptions)}else this.options.allowBooleanAttributes&&(a[s]=!0)}if(!Object.keys(a).length)return;if(this.options.attributesGroupName){let e={};return e[this.options.attributesGroupName]=a,e}return a}}const parseXml=function(e){e=e.replace(/\r\n?/g,`
|
|
174
|
+
`);let t=new XmlNode(`!xml`),n=t,r=``,i=``;this.entityExpansionCount=0,this.currentExpandedLength=0;let a=new DocTypeReader(this.options.processEntities);for(let o=0;o<e.length;o++)if(e[o]===`<`)if(e[o+1]===`/`){let t=findClosingIndex(e,`>`,o,`Closing Tag is not closed.`),a=e.substring(o+2,t).trim();if(this.options.removeNSPrefix){let e=a.indexOf(`:`);e!==-1&&(a=a.substr(e+1))}this.options.transformTagName&&(a=this.options.transformTagName(a)),n&&(r=this.saveTextToParentTag(r,n,i));let s=i.substring(i.lastIndexOf(`.`)+1);if(a&&this.options.unpairedTags.indexOf(a)!==-1)throw Error(`Unpaired tag can not be used as closing tag: </${a}>`);let c=0;s&&this.options.unpairedTags.indexOf(s)!==-1?(c=i.lastIndexOf(`.`,i.lastIndexOf(`.`)-1),this.tagsNodeStack.pop()):c=i.lastIndexOf(`.`),i=i.substring(0,c),n=this.tagsNodeStack.pop(),r=``,o=t}else if(e[o+1]===`?`){let t=readTagExp(e,o,!1,`?>`);if(!t)throw Error(`Pi Tag is not closed.`);if(r=this.saveTextToParentTag(r,n,i),!(this.options.ignoreDeclaration&&t.tagName===`?xml`||this.options.ignorePiTags)){let e=new XmlNode(t.tagName);e.add(this.options.textNodeName,``),t.tagName!==t.tagExp&&t.attrExpPresent&&(e[`:@`]=this.buildAttributesMap(t.tagExp,i,t.tagName)),this.addChild(n,e,i,o)}o=t.closeIndex+1}else if(e.substr(o+1,3)===`!--`){let t=findClosingIndex(e,`-->`,o+4,`Comment is not closed.`);if(this.options.commentPropName){let a=e.substring(o+4,t-2);r=this.saveTextToParentTag(r,n,i),n.add(this.options.commentPropName,[{[this.options.textNodeName]:a}])}o=t}else if(e.substr(o+1,2)===`!D`){let t=a.readDocType(e,o);this.docTypeEntities=t.entities,o=t.i}else if(e.substr(o+1,2)===`![`){let t=findClosingIndex(e,`]]>`,o,`CDATA is not closed.`)-2,a=e.substring(o+9,t);r=this.saveTextToParentTag(r,n,i);let s=this.parseTextData(a,n.tagname,i,!0,!1,!0,!0);s??=``,this.options.cdataPropName?n.add(this.options.cdataPropName,[{[this.options.textNodeName]:a}]):n.add(this.options.textNodeName,s),o=t+2}else{let a=readTagExp(e,o,this.options.removeNSPrefix),s=a.tagName,c=a.rawTagName,l=a.tagExp,u=a.attrExpPresent,d=a.closeIndex;if(this.options.transformTagName){let e=this.options.transformTagName(s);l===s&&(l=e),s=e}if(this.options.strictReservedNames&&(s===this.options.commentPropName||s===this.options.cdataPropName))throw Error(`Invalid tag name: ${s}`);n&&r&&n.tagname!==`!xml`&&(r=this.saveTextToParentTag(r,n,i,!1));let f=n;f&&this.options.unpairedTags.indexOf(f.tagname)!==-1&&(n=this.tagsNodeStack.pop(),i=i.substring(0,i.lastIndexOf(`.`))),s!==t.tagname&&(i+=i?`.`+s:s);let p=o;if(this.isItStopNode(this.stopNodesExact,this.stopNodesWildcard,i,s)){let t=``;if(l.length>0&&l.lastIndexOf(`/`)===l.length-1)s[s.length-1]===`/`?(s=s.substr(0,s.length-1),i=i.substr(0,i.length-1),l=s):l=l.substr(0,l.length-1),o=a.closeIndex;else if(this.options.unpairedTags.indexOf(s)!==-1)o=a.closeIndex;else{let n=this.readStopNodeData(e,c,d+1);if(!n)throw Error(`Unexpected end of ${c}`);o=n.i,t=n.tagContent}let r=new XmlNode(s);s!==l&&u&&(r[`:@`]=this.buildAttributesMap(l,i,s)),t&&=this.parseTextData(t,s,i,!0,u,!0,!0),i=i.substr(0,i.lastIndexOf(`.`)),r.add(this.options.textNodeName,t),this.addChild(n,r,i,p)}else{if(l.length>0&&l.lastIndexOf(`/`)===l.length-1){if(s[s.length-1]===`/`?(s=s.substr(0,s.length-1),i=i.substr(0,i.length-1),l=s):l=l.substr(0,l.length-1),this.options.transformTagName){let e=this.options.transformTagName(s);l===s&&(l=e),s=e}let e=new XmlNode(s);s!==l&&u&&(e[`:@`]=this.buildAttributesMap(l,i,s)),this.addChild(n,e,i,p),i=i.substr(0,i.lastIndexOf(`.`))}else if(this.options.unpairedTags.indexOf(s)!==-1){let e=new XmlNode(s);s!==l&&u&&(e[`:@`]=this.buildAttributesMap(l,i)),this.addChild(n,e,i,p),i=i.substr(0,i.lastIndexOf(`.`)),o=a.closeIndex;continue}else{let e=new XmlNode(s);if(this.tagsNodeStack.length>this.options.maxNestedTags)throw Error(`Maximum nested tags exceeded`);this.tagsNodeStack.push(n),s!==l&&u&&(e[`:@`]=this.buildAttributesMap(l,i,s)),this.addChild(n,e,i,p),n=e}r=``,o=d}}else r+=e[o];return t.child};function addChild(e,t,n,r){this.options.captureMetaData||(r=void 0);let i=this.options.updateTag(t.tagname,n,t[`:@`]);i===!1||(typeof i==`string`&&(t.tagname=i),e.addChild(t,r))}const In=__name(function(e,t,n){if(e.indexOf(`&`)===-1)return e;let r=this.options.processEntities;if(!r.enabled||r.allowedTags&&!r.allowedTags.includes(t)||r.tagFilter&&!r.tagFilter(t,n))return e;for(let t in this.docTypeEntities){let n=this.docTypeEntities[t],i=e.match(n.regx);if(i){if(this.entityExpansionCount+=i.length,r.maxTotalExpansions&&this.entityExpansionCount>r.maxTotalExpansions)throw Error(`Entity expansion limit exceeded: ${this.entityExpansionCount} > ${r.maxTotalExpansions}`);let t=e.length;if(e=e.replace(n.regx,n.val),r.maxExpandedLength&&(this.currentExpandedLength+=e.length-t,this.currentExpandedLength>r.maxExpandedLength))throw Error(`Total expanded content size exceeded: ${this.currentExpandedLength} > ${r.maxExpandedLength}`)}}if(e.indexOf(`&`)===-1)return e;for(let t in this.lastEntities){let n=this.lastEntities[t];e=e.replace(n.regex,n.val)}if(e.indexOf(`&`)===-1)return e;if(this.options.htmlEntities)for(let t in this.htmlEntities){let n=this.htmlEntities[t];e=e.replace(n.regex,n.val)}return e=e.replace(this.ampEntity.regex,this.ampEntity.val),e},`replaceEntitiesValue`);function saveTextToParentTag(e,t,n,r){return e&&=(r===void 0&&(r=t.child.length===0),e=this.parseTextData(e,t.tagname,n,!1,t[`:@`]?Object.keys(t[`:@`]).length!==0:!1,r),e!==void 0&&e!==``&&t.add(this.options.textNodeName,e),``),e}function isItStopNode(e,t,n,r){return!!(t&&t.has(r)||e&&e.has(n))}function tagExpWithClosingIndex(e,t,n=`>`){let r,i=``;for(let a=t;a<e.length;a++){let t=e[a];if(r)t===r&&(r=``);else if(t===`"`||t===`'`)r=t;else if(t===n[0])if(n[1]){if(e[a+1]===n[1])return{data:i,index:a}}else return{data:i,index:a};else t===` `&&(t=` `);i+=t}}function findClosingIndex(e,t,n,r){let i=e.indexOf(t,n);if(i===-1)throw Error(r);return i+t.length-1}function readTagExp(e,t,n,r=`>`){let i=tagExpWithClosingIndex(e,t+1,r);if(!i)return;let a=i.data,o=i.index,s=a.search(/\s/),c=a,l=!0;s!==-1&&(c=a.substring(0,s),a=a.substring(s+1).trimStart());let u=c;if(n){let e=c.indexOf(`:`);e!==-1&&(c=c.substr(e+1),l=c!==i.data.substr(e+1))}return{tagName:c,tagExp:a,closeIndex:o,attrExpPresent:l,rawTagName:u}}function readStopNodeData(e,t,n){let r=n,i=1;for(;n<e.length;n++)if(e[n]===`<`)if(e[n+1]===`/`){let a=findClosingIndex(e,`>`,n,`${t} is not closed`);if(e.substring(n+2,a).trim()===t&&(i--,i===0))return{tagContent:e.substring(r,n),i:a};n=a}else if(e[n+1]===`?`)n=findClosingIndex(e,`?>`,n+1,`StopNode is not closed.`);else if(e.substr(n+1,3)===`!--`)n=findClosingIndex(e,`-->`,n+3,`StopNode is not closed.`);else if(e.substr(n+1,2)===`![`)n=findClosingIndex(e,`]]>`,n,`StopNode is not closed.`)-2;else{let r=readTagExp(e,n,`>`);r&&((r&&r.tagName)===t&&r.tagExp[r.tagExp.length-1]!==`/`&&i++,n=r.closeIndex)}}function parseValue(e,t,n){if(t&&typeof e==`string`){let t=e.trim();return t===`true`?!0:t===`false`?!1:toNumber(e,n)}else if(isExist(e))return e;else return``}function fromCodePoint(e,t,n){let r=Number.parseInt(e,t);return r>=0&&r<=1114111?String.fromCodePoint(r):n+e+`;`}const Ln=XmlNode.getMetaDataSymbol();function prettify(e,t){return compress(e,t)}function compress(e,t,n){let r,i={};for(let a=0;a<e.length;a++){let o=e[a],s=propName$1(o),c=``;if(c=n===void 0?s:n+`.`+s,s===t.textNodeName)r===void 0?r=o[s]:r+=``+o[s];else if(s===void 0)continue;else if(o[s]){let e=compress(o[s],t,c),n=isLeafTag(e,t);o[`:@`]?assignAttributes(e,o[`:@`],c,t):Object.keys(e).length===1&&e[t.textNodeName]!==void 0&&!t.alwaysCreateTextNode?e=e[t.textNodeName]:Object.keys(e).length===0&&(t.alwaysCreateTextNode?e[t.textNodeName]=``:e=``),o[Ln]!==void 0&&typeof e==`object`&&e&&(e[Ln]=o[Ln]),i[s]!==void 0&&Object.prototype.hasOwnProperty.call(i,s)?(Array.isArray(i[s])||(i[s]=[i[s]]),i[s].push(e)):t.isArray(s,c,n)?i[s]=[e]:i[s]=e}}return typeof r==`string`?r.length>0&&(i[t.textNodeName]=r):r!==void 0&&(i[t.textNodeName]=r),i}function propName$1(e){let t=Object.keys(e);for(let e=0;e<t.length;e++){let n=t[e];if(n!==`:@`)return n}}__name(propName$1,`propName`);function assignAttributes(e,t,n,r){if(t){let i=Object.keys(t),a=i.length;for(let o=0;o<a;o++){let a=i[o];r.isArray(a,n+`.`+a,!0,!0)?e[a]=[t[a]]:e[a]=t[a]}}}function isLeafTag(e,t){let{textNodeName:n}=t,r=Object.keys(e).length;return!!(r===0||r===1&&(e[n]||typeof e[n]==`boolean`||e[n]===0))}var XMLParser=class{constructor(e){this.externalEntities={},this.options=buildOptions(e)}parse(e,t){if(typeof e!=`string`&&e.toString)e=e.toString();else if(typeof e!=`string`)throw Error(`XML data is accepted in String or Bytes[] form.`);if(t){t===!0&&(t={});let n=validate(e,t);if(n!==!0)throw Error(`${n.err.msg}:${n.err.line}:${n.err.col}`)}let n=new OrderedObjParser(this.options);n.addExternalEntities(this.externalEntities);let r=n.parseXml(e);return this.options.preserveOrder||r===void 0?r:prettify(r,this.options)}addEntity(e,t){if(t.indexOf(`&`)!==-1)throw Error(`Entity value can't have '&'`);if(e.indexOf(`&`)!==-1||e.indexOf(`;`)!==-1)throw Error(`An entity must be set without '&' and ';'. Eg. use '#xD' for '
'`);if(t===`&`)throw Error(`An entity with value '&' is not permitted`);this.externalEntities[e]=t}static getMetaDataSymbol(){return XmlNode.getMetaDataSymbol()}},Expression=class{constructor(e,t={}){this.pattern=e,this.separator=t.separator||`.`,this.segments=this._parse(e),this._hasDeepWildcard=this.segments.some(e=>e.type===`deep-wildcard`),this._hasAttributeCondition=this.segments.some(e=>e.attrName!==void 0),this._hasPositionSelector=this.segments.some(e=>e.position!==void 0)}_parse(e){let t=[],n=0,r=``;for(;n<e.length;)e[n]===this.separator?n+1<e.length&&e[n+1]===this.separator?(r.trim()&&(t.push(this._parseSegment(r.trim())),r=``),t.push({type:`deep-wildcard`}),n+=2):(r.trim()&&t.push(this._parseSegment(r.trim())),r=``,n++):(r+=e[n],n++);return r.trim()&&t.push(this._parseSegment(r.trim())),t}_parseSegment(e){let t={type:`tag`},n=null,r=e,i=e.match(/^([^\[]+)(\[[^\]]*\])(.*)$/);if(i&&(r=i[1]+i[3],i[2])){let e=i[2].slice(1,-1);e&&(n=e)}let a,o=r;if(r.includes(`::`)){let t=r.indexOf(`::`);if(a=r.substring(0,t).trim(),o=r.substring(t+2).trim(),!a)throw Error(`Invalid namespace in pattern: ${e}`)}let s,c=null;if(o.includes(`:`)){let e=o.lastIndexOf(`:`),t=o.substring(0,e).trim(),n=o.substring(e+1).trim();[`first`,`last`,`odd`,`even`].includes(n)||/^nth\(\d+\)$/.test(n)?(s=t,c=n):s=o}else s=o;if(!s)throw Error(`Invalid segment pattern: ${e}`);if(t.tag=s,a&&(t.namespace=a),n)if(n.includes(`=`)){let e=n.indexOf(`=`);t.attrName=n.substring(0,e).trim(),t.attrValue=n.substring(e+1).trim()}else t.attrName=n.trim();if(c){let e=c.match(/^nth\((\d+)\)$/);e?(t.position=`nth`,t.positionValue=parseInt(e[1],10)):t.position=c}return t}get length(){return this.segments.length}hasDeepWildcard(){return this._hasDeepWildcard}hasAttributeCondition(){return this._hasAttributeCondition}hasPositionSelector(){return this._hasPositionSelector}toString(){return this.pattern}},Matcher=class{constructor(e={}){this.separator=e.separator||`.`,this.path=[],this.siblingStacks=[]}push(e,t=null,n=null){if(this.path.length>0){let e=this.path[this.path.length-1];e.values=void 0}let r=this.path.length;this.siblingStacks[r]||(this.siblingStacks[r]=new Map);let i=this.siblingStacks[r],a=n?`${n}:${e}`:e,o=i.get(a)||0,s=0;for(let e of i.values())s+=e;i.set(a,o+1);let c={tag:e,position:s,counter:o};n!=null&&(c.namespace=n),t!=null&&(c.values=t),this.path.push(c)}pop(){if(this.path.length===0)return;let e=this.path.pop();return this.siblingStacks.length>this.path.length+1&&(this.siblingStacks.length=this.path.length+1),e}updateCurrent(e){if(this.path.length>0){let t=this.path[this.path.length-1];e!=null&&(t.values=e)}}getCurrentTag(){return this.path.length>0?this.path[this.path.length-1].tag:void 0}getCurrentNamespace(){return this.path.length>0?this.path[this.path.length-1].namespace:void 0}getAttrValue(e){if(this.path.length!==0)return this.path[this.path.length-1].values?.[e]}hasAttr(e){if(this.path.length===0)return!1;let t=this.path[this.path.length-1];return t.values!==void 0&&e in t.values}getPosition(){return this.path.length===0?-1:this.path[this.path.length-1].position??0}getCounter(){return this.path.length===0?-1:this.path[this.path.length-1].counter??0}getIndex(){return this.getPosition()}getDepth(){return this.path.length}toString(e,t=!0){let n=e||this.separator;return this.path.map(e=>t&&e.namespace?`${e.namespace}:${e.tag}`:e.tag).join(n)}toArray(){return this.path.map(e=>e.tag)}reset(){this.path=[],this.siblingStacks=[]}matches(e){let t=e.segments;return t.length===0?!1:e.hasDeepWildcard()?this._matchWithDeepWildcard(t):this._matchSimple(t)}_matchSimple(e){if(this.path.length!==e.length)return!1;for(let t=0;t<e.length;t++){let n=e[t],r=this.path[t],i=t===this.path.length-1;if(!this._matchSegment(n,r,i))return!1}return!0}_matchWithDeepWildcard(e){let t=this.path.length-1,n=e.length-1;for(;n>=0&&t>=0;){let r=e[n];if(r.type===`deep-wildcard`){if(n--,n<0)return!0;let r=e[n],i=!1;for(let e=t;e>=0;e--){let a=e===this.path.length-1;if(this._matchSegment(r,this.path[e],a)){t=e-1,n--,i=!0;break}}if(!i)return!1}else{let e=t===this.path.length-1;if(!this._matchSegment(r,this.path[t],e))return!1;t--,n--}}return n<0}_matchSegment(e,t,n){if(e.tag!==`*`&&e.tag!==t.tag||e.namespace!==void 0&&e.namespace!==`*`&&e.namespace!==t.namespace)return!1;if(e.attrName!==void 0){if(!n||!t.values||!(e.attrName in t.values))return!1;if(e.attrValue!==void 0){let n=t.values[e.attrName];if(String(n)!==String(e.attrValue))return!1}}if(e.position!==void 0){if(!n)return!1;let r=t.counter??0;if(e.position===`first`&&r!==0||e.position===`odd`&&r%2!=1||e.position===`even`&&r%2!=0||e.position===`nth`&&r!==e.positionValue)return!1}return!0}snapshot(){return{path:this.path.map(e=>({...e})),siblingStacks:this.siblingStacks.map(e=>new Map(e))}}restore(e){this.path=e.path.map(e=>({...e})),this.siblingStacks=e.siblingStacks.map(e=>new Map(e))}};const Rn=`
|
|
175
|
+
`;function toXml(e,t){let n=``;t.format&&t.indentBy.length>0&&(n=`
|
|
176
|
+
`);let r=[];if(t.stopNodes&&Array.isArray(t.stopNodes))for(let e=0;e<t.stopNodes.length;e++){let n=t.stopNodes[e];typeof n==`string`?r.push(new Expression(n)):n instanceof Expression&&r.push(n)}let i=new Matcher;return arrToStr(e,t,n,i,r)}function arrToStr(e,t,n,r,i){let a=``,o=!1;if(!Array.isArray(e)){if(e!=null){let n=e.toString();return n=replaceEntitiesValue(n,t),n}return``}for(let s=0;s<e.length;s++){let c=e[s],l=propName(c);if(l===void 0)continue;let u=extractAttributeValues(c[`:@`],t);r.push(l,u);let d=checkStopNode(r,i);if(l===t.textNodeName){let e=c[l];d||(e=t.tagValueProcessor(l,e),e=replaceEntitiesValue(e,t)),o&&(a+=n),a+=e,o=!1,r.pop();continue}else if(l===t.cdataPropName){o&&(a+=n),a+=`<![CDATA[${c[l][0][t.textNodeName]}]]>`,o=!1,r.pop();continue}else if(l===t.commentPropName){a+=n+`<!--${c[l][0][t.textNodeName]}-->`,o=!0,r.pop();continue}else if(l[0]===`?`){let e=attr_to_str(c[`:@`],t,d),i=l===`?xml`?``:n,s=c[l][0][t.textNodeName];s=s.length===0?``:` `+s,a+=i+`<${l}${s}${e}?>`,o=!0,r.pop();continue}let f=n;f!==``&&(f+=t.indentBy);let p=n+`<${l}${attr_to_str(c[`:@`],t,d)}`,m;m=d?getRawContent(c[l],t):arrToStr(c[l],t,f,r,i),t.unpairedTags.indexOf(l)===-1?(!m||m.length===0)&&t.suppressEmptyNode?a+=p+`/>`:m&&m.endsWith(`>`)?a+=p+`>${m}${n}</${l}>`:(a+=p+`>`,m&&n!==``&&(m.includes(`/>`)||m.includes(`</`))?a+=n+t.indentBy+m+n:a+=m,a+=`</${l}>`):t.suppressUnpairedNode?a+=p+`>`:a+=p+`/>`,o=!0,r.pop()}return a}function extractAttributeValues(e,t){if(!e||t.ignoreAttributes)return null;let n={},r=!1;for(let i in e){if(!Object.prototype.hasOwnProperty.call(e,i))continue;let a=i.startsWith(t.attributeNamePrefix)?i.substr(t.attributeNamePrefix.length):i;n[a]=e[i],r=!0}return r?n:null}function getRawContent(e,t){if(!Array.isArray(e))return e==null?``:e.toString();let n=``;for(let r=0;r<e.length;r++){let i=e[r],a=propName(i);if(a===t.textNodeName)n+=i[a];else if(a===t.cdataPropName)n+=i[a][0][t.textNodeName];else if(a===t.commentPropName)n+=i[a][0][t.textNodeName];else if(a&&a[0]===`?`)continue;else if(a){let e=attr_to_str_raw(i[`:@`],t),r=getRawContent(i[a],t);!r||r.length===0?n+=`<${a}${e}/>`:n+=`<${a}${e}>${r}</${a}>`}}return n}function attr_to_str_raw(e,t){let n=``;if(e&&!t.ignoreAttributes)for(let r in e){if(!Object.prototype.hasOwnProperty.call(e,r))continue;let i=e[r];i===!0&&t.suppressBooleanAttributes?n+=` ${r.substr(t.attributeNamePrefix.length)}`:n+=` ${r.substr(t.attributeNamePrefix.length)}="${i}"`}return n}function propName(e){let t=Object.keys(e);for(let n=0;n<t.length;n++){let r=t[n];if(Object.prototype.hasOwnProperty.call(e,r)&&r!==`:@`)return r}}function attr_to_str(e,t,n){let r=``;if(e&&!t.ignoreAttributes)for(let i in e){if(!Object.prototype.hasOwnProperty.call(e,i))continue;let a;n?a=e[i]:(a=t.attributeValueProcessor(i,e[i]),a=replaceEntitiesValue(a,t)),a===!0&&t.suppressBooleanAttributes?r+=` ${i.substr(t.attributeNamePrefix.length)}`:r+=` ${i.substr(t.attributeNamePrefix.length)}="${a}"`}return r}function checkStopNode(e,t){if(!t||t.length===0)return!1;for(let n=0;n<t.length;n++)if(e.matches(t[n]))return!0;return!1}function replaceEntitiesValue(e,t){if(e&&e.length>0&&t.processEntities)for(let n=0;n<t.entities.length;n++){let r=t.entities[n];e=e.replace(r.regex,r.val)}return e}function getIgnoreAttributesFn(e){return typeof e==`function`?e:Array.isArray(e)?t=>{for(let n of e)if(typeof n==`string`&&t===n||n instanceof RegExp&&n.test(t))return!0}:()=>!1}const zn={attributeNamePrefix:`@_`,attributesGroupName:!1,textNodeName:`#text`,ignoreAttributes:!0,cdataPropName:!1,format:!1,indentBy:` `,suppressEmptyNode:!1,suppressUnpairedNode:!0,suppressBooleanAttributes:!0,tagValueProcessor:function(e,t){return t},attributeValueProcessor:function(e,t){return t},preserveOrder:!1,commentPropName:!1,unpairedTags:[],entities:[{regex:RegExp(`&`,`g`),val:`&`},{regex:RegExp(`>`,`g`),val:`>`},{regex:RegExp(`<`,`g`),val:`<`},{regex:RegExp(`'`,`g`),val:`'`},{regex:RegExp(`"`,`g`),val:`"`}],processEntities:!0,stopNodes:[],oneListGroup:!1,jPath:!0};function Builder(e){if(this.options=Object.assign({},zn,e),this.options.stopNodes&&Array.isArray(this.options.stopNodes)&&(this.options.stopNodes=this.options.stopNodes.map(e=>typeof e==`string`&&e.startsWith(`*.`)?`..`+e.substring(2):e)),this.stopNodeExpressions=[],this.options.stopNodes&&Array.isArray(this.options.stopNodes))for(let e=0;e<this.options.stopNodes.length;e++){let t=this.options.stopNodes[e];typeof t==`string`?this.stopNodeExpressions.push(new Expression(t)):t instanceof Expression&&this.stopNodeExpressions.push(t)}this.options.ignoreAttributes===!0||this.options.attributesGroupName?this.isAttribute=function(){return!1}:(this.ignoreAttributesFn=getIgnoreAttributesFn(this.options.ignoreAttributes),this.attrPrefixLen=this.options.attributeNamePrefix.length,this.isAttribute=isAttribute),this.processTextOrObjNode=processTextOrObjNode,this.options.format?(this.indentate=indentate,this.tagEndChar=`>
|
|
177
177
|
`,this.newLine=`
|
|
178
|
-
`):(this.indentate=function(){return``},this.tagEndChar=`>`,this.newLine=``)}Builder.prototype.build=function(e){return this.options.preserveOrder?toXml(e,this.options):(Array.isArray(e)&&this.options.arrayNodeName&&this.options.arrayNodeName.length>1&&(e={[this.options.arrayNodeName]:e}),this.j2x(e,0,[]).val)},Builder.prototype.j2x=function(e,t,n){let r=``,i=``,a=n.join(`.`);for(let o in e)if(Object.prototype.hasOwnProperty.call(e,o))if(e[o]===void 0)this.isAttribute(o)&&(i+=``);else if(e[o]===null)this.isAttribute(o)||o===this.options.cdataPropName?i+=``:o[0]===`?`?i+=this.indentate(t)+`<`+o+`?`+this.tagEndChar:i+=this.indentate(t)+`<`+o+`/`+this.tagEndChar;else if(e[o]instanceof Date)i+=this.buildTextValNode(e[o],o,``,t);else if(typeof e[o]!=`object`){let n=this.isAttribute(o);if(n&&!this.ignoreAttributesFn(n,a))r+=this.buildAttrPairStr(n,``+e[o]);else if(!n)if(o===this.options.textNodeName){let t=this.options.tagValueProcessor(o,``+e[o]);i+=this.replaceEntitiesValue(t)}else i+=this.buildTextValNode(e[o],o,``,t)}else if(Array.isArray(e[o])){let r=e[o].length,a=``,s=``;for(let c=0;c<r;c++){let r=e[o][c];if(r!==void 0)if(r===null)o[0]===`?`?i+=this.indentate(t)+`<`+o+`?`+this.tagEndChar:i+=this.indentate(t)+`<`+o+`/`+this.tagEndChar;else if(typeof r==`object`)if(this.options.oneListGroup){let e=this.j2x(r,t+1,n.concat(o));a+=e.val,this.options.attributesGroupName&&r.hasOwnProperty(this.options.attributesGroupName)&&(s+=e.attrStr)}else a+=this.processTextOrObjNode(r,o,t,n);else if(this.options.oneListGroup){let e=this.options.tagValueProcessor(o,r);e=this.replaceEntitiesValue(e),a+=e}else a+=this.buildTextValNode(r,o,``,t)}this.options.oneListGroup&&(a=this.buildObjectNode(a,o,s,t)),i+=a}else if(this.options.attributesGroupName&&o===this.options.attributesGroupName){let t=Object.keys(e[o]),n=t.length;for(let i=0;i<n;i++)r+=this.buildAttrPairStr(t[i],``+e[o][t[i]])}else i+=this.processTextOrObjNode(e[o],o,t,n);return{attrStr:r,val:i}},Builder.prototype.buildAttrPairStr=function(e,t){return t=this.options.attributeValueProcessor(e,``+t),t=this.replaceEntitiesValue(t),this.options.suppressBooleanAttributes&&t===`true`?` `+e:` `+e+`="`+t+`"`};function processTextOrObjNode(e,t,n,r){let i=this.j2x(e,n+1,r.concat(t));return e[this.options.textNodeName]!==void 0&&Object.keys(e).length===1?this.buildTextValNode(e[this.options.textNodeName],t,i.attrStr,n):this.buildObjectNode(i.val,t,i.attrStr,n)}Builder.prototype.buildObjectNode=function(e,t,n,r){if(e===``)return t[0]===`?`?this.indentate(r)+`<`+t+n+`?`+this.tagEndChar:this.indentate(r)+`<`+t+n+this.closeTag(t)+this.tagEndChar;{let i=`</`+t+this.tagEndChar,a=``;return t[0]===`?`&&(a=`?`,i=``),(n||n===``)&&e.indexOf(`<`)===-1?this.indentate(r)+`<`+t+n+a+`>`+e+i:this.options.commentPropName!==!1&&t===this.options.commentPropName&&a.length===0?this.indentate(r)+`<!--${e}-->`+this.newLine:this.indentate(r)+`<`+t+n+a+this.tagEndChar+e+this.indentate(r)+i}},Builder.prototype.closeTag=function(e){let t=``;return this.options.unpairedTags.indexOf(e)===-1?t=this.options.suppressEmptyNode?`/`:`></${e}`:this.options.suppressUnpairedNode||(t=`/`),t},Builder.prototype.buildTextValNode=function(e,t,n,r){if(this.options.cdataPropName!==!1&&t===this.options.cdataPropName)return this.indentate(r)+`<![CDATA[${e}]]>`+this.newLine;if(this.options.commentPropName!==!1&&t===this.options.commentPropName)return this.indentate(r)+`<!--${e}-->`+this.newLine;if(t[0]===`?`)return this.indentate(r)+`<`+t+n+`?`+this.tagEndChar;{let i=this.options.tagValueProcessor(t,e);return i=this.replaceEntitiesValue(i),i===``?this.indentate(r)+`<`+t+n+this.closeTag(t)+this.tagEndChar:this.indentate(r)+`<`+t+n+`>`+i+`</`+t+this.tagEndChar}},Builder.prototype.replaceEntitiesValue=function(e){if(e&&e.length>0&&this.options.processEntities)for(let t=0;t<this.options.entities.length;t++){let n=this.options.entities[t];e=e.replace(n.regex,n.val)}return e};function indentate(e){return this.options.indentBy.repeat(e)}function isAttribute(e){return e.startsWith(this.options.attributeNamePrefix)&&e!==this.options.textNodeName?e.substr(this.attrPrefixLen):!1}const Bn={validate},Vn=`@_`;var SoapClient=class{async performRequest({httpClient:e,url:t,method:n,headers:r,queryParams:i,body:a,customErrorConfigs:s,requestConfig:c}){let l;if(l=typeof c?.envelope==`string`?c.envelope:typeof c?.envelope==`object`?Hn.build(c.envelope):await buildEnvelope(a,c),Bn.validate(l,{allowBooleanAttributes:!0})!==!0)throw Error(`Invalid XML envelope`);let u,d={"Content-Type":`application/xml`,...r};c?.soapAction&&(d.SOAPAction=c.soapAction);try{u=await e?.request({method:n,url:t,headers:d,queryParams:i,maxRedirects:0,payload:l,requestConfig:c})}catch(e){if((0,o.isMissing)(e?.response))throw e;u=e.response}let f=Un.parse(u.data),p=f.Envelope||f,m=p.Body||p,h=m.Fault;if(h)throw new N({...u,status:500,data:h,message:h.faultstring??h.faultcode??`SOAP Fault`},h.faultstring??`SOAP Fault occurred`);u.data=m;let g=translateCustomError(u,s);if(isFailedStatusCode(g?.status))throw new N(g,g.message);return g}};const Hn=new Builder({attributeNamePrefix:`@_`,ignoreAttributes:!1,suppressBooleanAttributes:!1}),Un=new XMLParser({ignoreAttributes:!1,attributeNamePrefix:`_`,removeNSPrefix:!0,numberParseOptions:{leadingZeros:!1,hex:!1}}),buildEnvelope=async(e,t)=>{if((0,o.notMissing)(t?.envelope)){let e=typeof t.envelope==`string`?t.envelope:Hn.build(t.envelope);if(Bn.validate(e,{allowBooleanAttributes:!0})!==!0)throw Error(`Invalid XML envelope`);return e}let n=await buildSoapEnvelope(t,e),r=Hn.build(n);if(Bn.validate(r,{allowBooleanAttributes:!0})!==!0)throw Error(`Invalid XML envelope`);return r},buildSoapEnvelope=async(e,t)=>{let n=await Promise.all((e?.namespaces||[]).map(async e=>({identifier:await(0,c.evaluate)(e.namespaceIdentifier),namespace:await(0,c.evaluate)(e.namespace)})));n.forEach(({identifier:e,namespace:t})=>{if((0,o.isMissing)(e)||(0,o.isMissing)(t)||e===``||t===``)throw Error(`Invalid namespace config: both identifier and namespace are required`)});let r=n.reduce((e,{identifier:t,namespace:n})=>(e[`@_xmlns:${t}`]=n,e),{});return{"soapenv:Envelope":{"soapenv:Header":await buildSoapHeaders(t,e??{}),"soapenv:Body":await buildSoapBody(t,e?.soapOperation??``,n[0]?.identifier??``),"@_xmlns:soapenv":`http://schemas.xmlsoap.org/soap/envelope/`,...r}}},buildSoapHeaders=async(e,t)=>[await buildSoapSecurity(e,t)],buildSoapSecurity=async(e,t)=>{if((0,o.isMissing)(t.soapContext))return{};let{username:n,password:r}=t.soapContext;return{"wsse:Security":{"wsse:UsernameToken":{"wsse:Username":n,"wsse:Password":{"#text":r,"@_Type":`http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-username-token-profile-1.0#PasswordText`}},"@_soapenv:mustUnderstand":`1`,"@_xmlns:wsse":`http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-secext-1.0.xsd`,"@_xmlns:wsu":`http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-utility-1.0.xsd`}}},buildSoapBody=async(e,t,n)=>{if((0,o.isMissing)(t))throw Error(`Missing soapOperation in config`);let r=expandArrayAttributes({[t]:e});return(Array.isArray(r)?r:[r]).map(e=>applyNamespace(e,n))},expandArrayAttributes=e=>{if(typeof e!=`object`||!e)return e;if(Array.isArray(e)){if(e.length===1){let t=e[0];if(typeof t==`object`&&t&&!Array.isArray(t)){let e=Object.keys(t).filter(e=>!e.startsWith(`@_`));if(e.length===1){let n=e[0],r=t[n];if(typeof r==`object`&&r&&!Array.isArray(r)){let e=Object.keys(r),t=e.filter(e=>e.startsWith(`@_`)),i=e.filter(e=>!e.startsWith(`@_`)),a=t.find(e=>Array.isArray(r[e]));if(a&&i.length===0){let e=r[a],i=t.filter(e=>e!==a),o=e.map(e=>{let t={[a]:e};for(let e of i)t[e]=r[e];return t});return{[n]:o}}}}}}return e.map(e=>expandArrayAttributes(e))}let t={};for(let n of Object.keys(e)){let r=e[n];t[n]=expandArrayAttributes(r)}return t},applyNamespace=(e,t)=>{if(typeof e!=`object`)return e;if(Array.isArray(e))return e.map(e=>applyNamespace(e,t));let n={};for(let r in e){let i=applyNamespaceToKey(r,t);n[i]=applyNamespace(e[r],t)}return n},applyNamespaceToKey=(e,t)=>{let n=e.split(`:`);return n.length>1&&n[0]||e.indexOf(`${t}:`)===0||e===`#text`?e:e.startsWith(`@_`)?`@_${t}:${e.slice(2)}`:`${t}:${e}`};var RequestClientFactory=class{static build(e=`rest`){if(e===`rest`)return new RestClient;if(e===`soap`)return new SoapClient;throw Error(`Unknown request client type: ${e}`)}};exports.CUSTOM_ERROR_CONFIG_SCHEMA=ke,exports.ConcurrencyManager=ConcurrencyManager,exports.EventClient=EventClient,exports.HttpClient=HttpClient,exports.HttpClientManager=HttpClientManager,exports.HttpErrorMessages=Oe,exports.HttpMethods=_n,exports.HttpResponseError=N,exports.HttpTransportFactory=HttpTransportFactory,exports.InstanceManager=P,exports.LockManager=LockManager,exports.MemoryStore=MemoryStore,exports.QueryArrayFormats=xn,exports.QueueManager=QueueManager,exports.RateLimitManager=RateLimitManager,exports.RedisClient=te,exports.RequestClientFactory=RequestClientFactory,exports.RequestParameterLocations=bn,exports.ScriptManager=ScriptManager,exports.SubscriptionManager=SubscriptionManager,exports.buildHttpClientInstance=buildHttpClientInstance,exports.convertError=convertError,exports.createAuthorizationHeaders=createAuthorizationHeaders,exports.getRetryAfterWaitTime=getRetryAfterWaitTime,exports.getTransportInstance=getTransportInstance,exports.getTransportManagers=getTransportManagers,exports.initializeTransportSystem=initializeTransportSystem,exports.isFailedStatusCode=isFailedStatusCode,exports.isInfoStatusCode=isInfoStatusCode,exports.isSuccessStatusCode=isSuccessStatusCode,exports.isTransportSystemReady=isTransportSystemReady,exports.parseRequestParameters=parseRequestParameters,exports.serializeHttpResponseError=serializeHttpResponseError,exports.shutdownTransportSystem=shutdownTransportSystem,exports.superNormalizeHeaders=superNormalizeHeaders,exports.translateCustomError=translateCustomError;
|
|
178
|
+
`):(this.indentate=function(){return``},this.tagEndChar=`>`,this.newLine=``)}Builder.prototype.build=function(e){if(this.options.preserveOrder)return toXml(e,this.options);{Array.isArray(e)&&this.options.arrayNodeName&&this.options.arrayNodeName.length>1&&(e={[this.options.arrayNodeName]:e});let t=new Matcher;return this.j2x(e,0,t).val}},Builder.prototype.j2x=function(e,t,n){let r=``,i=``,a=this.options.jPath?n.toString():n,o=this.checkStopNode(n);for(let s in e)if(Object.prototype.hasOwnProperty.call(e,s))if(e[s]===void 0)this.isAttribute(s)&&(i+=``);else if(e[s]===null)this.isAttribute(s)||s===this.options.cdataPropName?i+=``:s[0]===`?`?i+=this.indentate(t)+`<`+s+`?`+this.tagEndChar:i+=this.indentate(t)+`<`+s+`/`+this.tagEndChar;else if(e[s]instanceof Date)i+=this.buildTextValNode(e[s],s,``,t,n);else if(typeof e[s]!=`object`){let c=this.isAttribute(s);if(c&&!this.ignoreAttributesFn(c,a))r+=this.buildAttrPairStr(c,``+e[s],o);else if(!c)if(s===this.options.textNodeName){let t=this.options.tagValueProcessor(s,``+e[s]);i+=this.replaceEntitiesValue(t)}else{n.push(s);let r=this.checkStopNode(n);if(n.pop(),r){let n=``+e[s];n===``?i+=this.indentate(t)+`<`+s+this.closeTag(s)+this.tagEndChar:i+=this.indentate(t)+`<`+s+`>`+n+`</`+s+this.tagEndChar}else i+=this.buildTextValNode(e[s],s,``,t,n)}}else if(Array.isArray(e[s])){let r=e[s].length,a=``,o=``;for(let c=0;c<r;c++){let r=e[s][c];if(r!==void 0)if(r===null)s[0]===`?`?i+=this.indentate(t)+`<`+s+`?`+this.tagEndChar:i+=this.indentate(t)+`<`+s+`/`+this.tagEndChar;else if(typeof r==`object`)if(this.options.oneListGroup){n.push(s);let e=this.j2x(r,t+1,n);n.pop(),a+=e.val,this.options.attributesGroupName&&r.hasOwnProperty(this.options.attributesGroupName)&&(o+=e.attrStr)}else a+=this.processTextOrObjNode(r,s,t,n);else if(this.options.oneListGroup){let e=this.options.tagValueProcessor(s,r);e=this.replaceEntitiesValue(e),a+=e}else{n.push(s);let e=this.checkStopNode(n);if(n.pop(),e){let e=``+r;e===``?a+=this.indentate(t)+`<`+s+this.closeTag(s)+this.tagEndChar:a+=this.indentate(t)+`<`+s+`>`+e+`</`+s+this.tagEndChar}else a+=this.buildTextValNode(r,s,``,t,n)}}this.options.oneListGroup&&(a=this.buildObjectNode(a,s,o,t)),i+=a}else if(this.options.attributesGroupName&&s===this.options.attributesGroupName){let t=Object.keys(e[s]),n=t.length;for(let i=0;i<n;i++)r+=this.buildAttrPairStr(t[i],``+e[s][t[i]],o)}else i+=this.processTextOrObjNode(e[s],s,t,n);return{attrStr:r,val:i}},Builder.prototype.buildAttrPairStr=function(e,t,n){return n||(t=this.options.attributeValueProcessor(e,``+t),t=this.replaceEntitiesValue(t)),this.options.suppressBooleanAttributes&&t===`true`?` `+e:` `+e+`="`+t+`"`};function processTextOrObjNode(e,t,n,r){let i=this.extractAttributes(e);if(r.push(t,i),this.checkStopNode(r)){let i=this.buildRawContent(e),a=this.buildAttributesForStopNode(e);return r.pop(),this.buildObjectNode(i,t,a,n)}let a=this.j2x(e,n+1,r);return r.pop(),e[this.options.textNodeName]!==void 0&&Object.keys(e).length===1?this.buildTextValNode(e[this.options.textNodeName],t,a.attrStr,n,r):this.buildObjectNode(a.val,t,a.attrStr,n)}Builder.prototype.extractAttributes=function(e){if(!e||typeof e!=`object`)return null;let t={},n=!1;if(this.options.attributesGroupName&&e[this.options.attributesGroupName]){let r=e[this.options.attributesGroupName];for(let e in r){if(!Object.prototype.hasOwnProperty.call(r,e))continue;let i=e.startsWith(this.options.attributeNamePrefix)?e.substring(this.options.attributeNamePrefix.length):e;t[i]=r[e],n=!0}}else for(let r in e){if(!Object.prototype.hasOwnProperty.call(e,r))continue;let i=this.isAttribute(r);i&&(t[i]=e[r],n=!0)}return n?t:null},Builder.prototype.buildRawContent=function(e){if(typeof e==`string`)return e;if(typeof e!=`object`||!e)return String(e);if(e[this.options.textNodeName]!==void 0)return e[this.options.textNodeName];let t=``;for(let n in e){if(!Object.prototype.hasOwnProperty.call(e,n)||this.isAttribute(n)||this.options.attributesGroupName&&n===this.options.attributesGroupName)continue;let r=e[n];if(n===this.options.textNodeName)t+=r;else if(Array.isArray(r)){for(let e of r)if(typeof e==`string`||typeof e==`number`)t+=`<${n}>${e}</${n}>`;else if(typeof e==`object`&&e){let r=this.buildRawContent(e),i=this.buildAttributesForStopNode(e);r===``?t+=`<${n}${i}/>`:t+=`<${n}${i}>${r}</${n}>`}}else if(typeof r==`object`&&r){let e=this.buildRawContent(r),i=this.buildAttributesForStopNode(r);e===``?t+=`<${n}${i}/>`:t+=`<${n}${i}>${e}</${n}>`}else t+=`<${n}>${r}</${n}>`}return t},Builder.prototype.buildAttributesForStopNode=function(e){if(!e||typeof e!=`object`)return``;let t=``;if(this.options.attributesGroupName&&e[this.options.attributesGroupName]){let n=e[this.options.attributesGroupName];for(let e in n){if(!Object.prototype.hasOwnProperty.call(n,e))continue;let r=e.startsWith(this.options.attributeNamePrefix)?e.substring(this.options.attributeNamePrefix.length):e,i=n[e];i===!0&&this.options.suppressBooleanAttributes?t+=` `+r:t+=` `+r+`="`+i+`"`}}else for(let n in e){if(!Object.prototype.hasOwnProperty.call(e,n))continue;let r=this.isAttribute(n);if(r){let i=e[n];i===!0&&this.options.suppressBooleanAttributes?t+=` `+r:t+=` `+r+`="`+i+`"`}}return t},Builder.prototype.buildObjectNode=function(e,t,n,r){if(e===``)return t[0]===`?`?this.indentate(r)+`<`+t+n+`?`+this.tagEndChar:this.indentate(r)+`<`+t+n+this.closeTag(t)+this.tagEndChar;{let i=`</`+t+this.tagEndChar,a=``;return t[0]===`?`&&(a=`?`,i=``),(n||n===``)&&e.indexOf(`<`)===-1?this.indentate(r)+`<`+t+n+a+`>`+e+i:this.options.commentPropName!==!1&&t===this.options.commentPropName&&a.length===0?this.indentate(r)+`<!--${e}-->`+this.newLine:this.indentate(r)+`<`+t+n+a+this.tagEndChar+e+this.indentate(r)+i}},Builder.prototype.closeTag=function(e){let t=``;return this.options.unpairedTags.indexOf(e)===-1?t=this.options.suppressEmptyNode?`/`:`></${e}`:this.options.suppressUnpairedNode||(t=`/`),t},Builder.prototype.checkStopNode=function(e){if(!this.stopNodeExpressions||this.stopNodeExpressions.length===0)return!1;for(let t=0;t<this.stopNodeExpressions.length;t++)if(e.matches(this.stopNodeExpressions[t]))return!0;return!1},Builder.prototype.buildTextValNode=function(e,t,n,r,i){if(this.options.cdataPropName!==!1&&t===this.options.cdataPropName)return this.indentate(r)+`<![CDATA[${e}]]>`+this.newLine;if(this.options.commentPropName!==!1&&t===this.options.commentPropName)return this.indentate(r)+`<!--${e}-->`+this.newLine;if(t[0]===`?`)return this.indentate(r)+`<`+t+n+`?`+this.tagEndChar;{let i=this.options.tagValueProcessor(t,e);return i=this.replaceEntitiesValue(i),i===``?this.indentate(r)+`<`+t+n+this.closeTag(t)+this.tagEndChar:this.indentate(r)+`<`+t+n+`>`+i+`</`+t+this.tagEndChar}},Builder.prototype.replaceEntitiesValue=function(e){if(e&&e.length>0&&this.options.processEntities)for(let t=0;t<this.options.entities.length;t++){let n=this.options.entities[t];e=e.replace(n.regex,n.val)}return e};function indentate(e){return this.options.indentBy.repeat(e)}function isAttribute(e){return e.startsWith(this.options.attributeNamePrefix)&&e!==this.options.textNodeName?e.substr(this.attrPrefixLen):!1}var Bn=Builder;const Vn={validate},Hn=`@_`;var SoapClient=class{async performRequest({httpClient:e,url:t,method:n,headers:r,queryParams:i,body:a,customErrorConfigs:s,requestConfig:c}){let l;if(l=typeof c?.envelope==`string`?c.envelope:typeof c?.envelope==`object`?Un.build(c.envelope):await buildEnvelope(a,c),Vn.validate(l,{allowBooleanAttributes:!0})!==!0)throw Error(`Invalid XML envelope`);let u,d={"Content-Type":`application/xml`,...r};c?.soapAction&&(d.SOAPAction=c.soapAction);try{u=await e?.request({method:n,url:t,headers:d,queryParams:i,maxRedirects:0,payload:l,requestConfig:c})}catch(e){if((0,o.isMissing)(e?.response))throw e;u=e.response}let f=Wn.parse(u.data),p=f.Envelope||f,m=p.Body||p,h=m.Fault;if(h)throw new N({...u,status:500,data:h,message:h.faultstring??h.faultcode??`SOAP Fault`},h.faultstring??`SOAP Fault occurred`);u.data=m;let g=translateCustomError(u,s);if(isFailedStatusCode(g?.status))throw new N(g,g.message);return g}};const Un=new Bn({attributeNamePrefix:`@_`,ignoreAttributes:!1,suppressBooleanAttributes:!1}),Wn=new XMLParser({ignoreAttributes:!1,attributeNamePrefix:`_`,removeNSPrefix:!0,numberParseOptions:{leadingZeros:!1,hex:!1}}),buildEnvelope=async(e,t)=>{if((0,o.notMissing)(t?.envelope)){let e=typeof t.envelope==`string`?t.envelope:Un.build(t.envelope);if(Vn.validate(e,{allowBooleanAttributes:!0})!==!0)throw Error(`Invalid XML envelope`);return e}let n=await buildSoapEnvelope(t,e),r=Un.build(n);if(Vn.validate(r,{allowBooleanAttributes:!0})!==!0)throw Error(`Invalid XML envelope`);return r},buildSoapEnvelope=async(e,t)=>{let n=await Promise.all((e?.namespaces||[]).map(async e=>({identifier:await(0,c.evaluate)(e.namespaceIdentifier),namespace:await(0,c.evaluate)(e.namespace)})));n.forEach(({identifier:e,namespace:t})=>{if((0,o.isMissing)(e)||(0,o.isMissing)(t)||e===``||t===``)throw Error(`Invalid namespace config: both identifier and namespace are required`)});let r=n.reduce((e,{identifier:t,namespace:n})=>(e[`@_xmlns:${t}`]=n,e),{});return{"soapenv:Envelope":{"soapenv:Header":await buildSoapHeaders(t,e??{}),"soapenv:Body":await buildSoapBody(t,e?.soapOperation??``,n[0]?.identifier??``),"@_xmlns:soapenv":`http://schemas.xmlsoap.org/soap/envelope/`,...r}}},buildSoapHeaders=async(e,t)=>[await buildSoapSecurity(e,t)],buildSoapSecurity=async(e,t)=>{if((0,o.isMissing)(t.soapContext))return{};let{username:n,password:r}=t.soapContext;return{"wsse:Security":{"wsse:UsernameToken":{"wsse:Username":n,"wsse:Password":{"#text":r,"@_Type":`http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-username-token-profile-1.0#PasswordText`}},"@_soapenv:mustUnderstand":`1`,"@_xmlns:wsse":`http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-secext-1.0.xsd`,"@_xmlns:wsu":`http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-utility-1.0.xsd`}}},buildSoapBody=async(e,t,n)=>{if((0,o.isMissing)(t))throw Error(`Missing soapOperation in config`);let r=expandArrayAttributes({[t]:e});return(Array.isArray(r)?r:[r]).map(e=>applyNamespace(e,n))},expandArrayAttributes=e=>{if(typeof e!=`object`||!e)return e;if(Array.isArray(e)){if(e.length===1){let t=e[0];if(typeof t==`object`&&t&&!Array.isArray(t)){let e=Object.keys(t).filter(e=>!e.startsWith(`@_`));if(e.length===1){let n=e[0],r=t[n];if(typeof r==`object`&&r&&!Array.isArray(r)){let e=Object.keys(r),t=e.filter(e=>e.startsWith(`@_`)),i=e.filter(e=>!e.startsWith(`@_`)),a=t.find(e=>Array.isArray(r[e]));if(a&&i.length===0){let e=r[a],i=t.filter(e=>e!==a),o=e.map(e=>{let t={[a]:e};for(let e of i)t[e]=r[e];return t});return{[n]:o}}}}}}return e.map(e=>expandArrayAttributes(e))}let t={};for(let n of Object.keys(e)){let r=e[n];t[n]=expandArrayAttributes(r)}return t},applyNamespace=(e,t)=>{if(typeof e!=`object`)return e;if(Array.isArray(e))return e.map(e=>applyNamespace(e,t));let n={};for(let r in e){let i=applyNamespaceToKey(r,t);n[i]=applyNamespace(e[r],t)}return n},applyNamespaceToKey=(e,t)=>{let n=e.split(`:`);return n.length>1&&n[0]||e.indexOf(`${t}:`)===0||e===`#text`?e:e.startsWith(`@_`)?`@_${t}:${e.slice(2)}`:`${t}:${e}`};var RequestClientFactory=class{static build(e=`rest`){if(e===`rest`)return new RestClient;if(e===`soap`)return new SoapClient;throw Error(`Unknown request client type: ${e}`)}};exports.CUSTOM_ERROR_CONFIG_SCHEMA=ke,exports.ConcurrencyManager=ConcurrencyManager,exports.EventClient=EventClient,exports.HttpClient=HttpClient,exports.HttpClientManager=HttpClientManager,exports.HttpErrorMessages=Oe,exports.HttpMethods=_n,exports.HttpResponseError=N,exports.HttpTransportFactory=HttpTransportFactory,exports.InstanceManager=P,exports.LockManager=LockManager,exports.MemoryStore=MemoryStore,exports.QueryArrayFormats=xn,exports.QueueManager=QueueManager,exports.RateLimitManager=RateLimitManager,exports.RedisClient=te,exports.RequestClientFactory=RequestClientFactory,exports.RequestParameterLocations=bn,exports.ScriptManager=ScriptManager,exports.SubscriptionManager=SubscriptionManager,exports.buildHttpClientInstance=buildHttpClientInstance,exports.convertError=convertError,exports.createAuthorizationHeaders=createAuthorizationHeaders,exports.getRetryAfterWaitTime=getRetryAfterWaitTime,exports.getTransportInstance=getTransportInstance,exports.getTransportManagers=getTransportManagers,exports.initializeTransportSystem=initializeTransportSystem,exports.isFailedStatusCode=isFailedStatusCode,exports.isInfoStatusCode=isInfoStatusCode,exports.isSuccessStatusCode=isSuccessStatusCode,exports.isTransportSystemReady=isTransportSystemReady,exports.parseRequestParameters=parseRequestParameters,exports.serializeHttpResponseError=serializeHttpResponseError,exports.shutdownTransportSystem=shutdownTransportSystem,exports.superNormalizeHeaders=superNormalizeHeaders,exports.translateCustomError=translateCustomError;
|
package/dist/index.mjs
CHANGED
|
@@ -110,7 +110,7 @@ Example:
|
|
|
110
110
|
* Copyright (c) 2023, Robert Eisele (robert@raw.org)
|
|
111
111
|
* Dual licensed under the MIT or GPL Version 2 licenses.
|
|
112
112
|
**/
|
|
113
|
-
(function(r){var i=2e3,a={s:1,n:0,d:1};function assign(e,t){if(isNaN(e=parseInt(e,10)))throw InvalidParameter();return e*t}function newFraction(e,t){if(t===0)throw DivisionByZero();var n=Object.create(Fraction$2.prototype);n.s=e<0?-1:1,e=e<0?-e:e;var r=gcd(e,t);return n.n=e/r,n.d=t/r,n}function factorize(e){for(var t={},n=e,r=2,i=4;i<=n;){for(;n%r===0;)n/=r,t[r]=(t[r]||0)+1;i+=1+2*r++}return n===e?t[e]=(t[e]||0)+1:n>1&&(t[n]=(t[n]||0)+1),t}var o=e(function(e,t){var n=0,r=1,i=1,o=0,s=0,c=0,l=1,u=1,d=0,f=1,p=1,m=1,h=1e7,g;if(e!=null)if(t!==void 0){if(n=e,r=t,i=n*r,n%1!=0||r%1!=0)throw NonIntegerParameter()}else switch(typeof e){case`object`:if(`d`in e&&`n`in e)n=e.n,r=e.d,`s`in e&&(n*=e.s);else if(0 in e)n=e[0],1 in e&&(r=e[1]);else throw InvalidParameter();i=n*r;break;case`number`:if(e<0&&(i=e,e=-e),e%1==0)n=e;else if(e>0){for(e>=1&&(u=10**Math.floor(1+Math.log(e)/Math.LN10),e/=u);f<=h&&m<=h;)if(g=(d+p)/(f+m),e===g){f+m<=h?(n=d+p,r=f+m):m>f?(n=p,r=m):(n=d,r=f);break}else e>g?(d+=p,f+=m):(p+=d,m+=f),f>h?(n=p,r=m):(n=d,r=f);n*=u}else (isNaN(e)||isNaN(t))&&(r=n=NaN);break;case`string`:if(f=e.match(/\d+|./g),f===null)throw InvalidParameter();if(f[d]===`-`?(i=-1,d++):f[d]===`+`&&d++,f.length===d+1?s=assign(f[d++],i):f[d+1]===`.`||f[d]===`.`?(f[d]!==`.`&&(o=assign(f[d++],i)),d++,(d+1===f.length||f[d+1]===`(`&&f[d+3]===`)`||f[d+1]===`'`&&f[d+3]===`'`)&&(s=assign(f[d],i),l=10**f[d].length,d++),(f[d]===`(`&&f[d+2]===`)`||f[d]===`'`&&f[d+2]===`'`)&&(c=assign(f[d+1],i),u=10**f[d+1].length-1,d+=3)):f[d+1]===`/`||f[d+1]===`:`?(s=assign(f[d],i),l=assign(f[d+2],1),d+=3):f[d+3]===`/`&&f[d+1]===` `&&(o=assign(f[d],i),s=assign(f[d+2],i),l=assign(f[d+4],1),d+=5),f.length<=d){r=l*u,i=n=c+r*o+u*s;break}default:throw InvalidParameter()}if(r===0)throw DivisionByZero();a.s=i<0?-1:1,a.n=Math.abs(n),a.d=Math.abs(r)},`parse`);function modpow(e,t,n){for(var r=1;t>0;e=e*e%n,t>>=1)t&1&&(r=r*e%n);return r}function cycleLen(e,t){for(;t%2==0;t/=2);for(;t%5==0;t/=5);if(t===1)return 0;for(var n=10%t,r=1;n!==1;r++)if(n=n*10%t,r>i)return 0;return r}function cycleStart(e,t,n){for(var r=1,i=modpow(10,n,t),a=0;a<300;a++){if(r===i)return a;r=r*10%t,i=i*10%t}return 0}function gcd(e,t){if(!e)return t;if(!t)return e;for(;;){if(e%=t,!e)return t;if(t%=e,!t)return e}}function Fraction$2(e,t){if(o(e,t),this instanceof Fraction$2)e=gcd(a.d,a.n),this.s=a.s,this.n=a.n/e,this.d=a.d/e;else return newFraction(a.s*a.n,a.d)}e(Fraction$2,`Fraction`);var DivisionByZero=function(){return Error(`Division by Zero`)},InvalidParameter=function(){return Error(`Invalid argument`)},NonIntegerParameter=function(){return Error(`Parameters must be integer`)};Fraction$2.prototype={s:1,n:0,d:1,abs:function(){return newFraction(this.n,this.d)},neg:function(){return newFraction(-this.s*this.n,this.d)},add:function(e,t){return o(e,t),newFraction(this.s*this.n*a.d+a.s*this.d*a.n,this.d*a.d)},sub:function(e,t){return o(e,t),newFraction(this.s*this.n*a.d-a.s*this.d*a.n,this.d*a.d)},mul:function(e,t){return o(e,t),newFraction(this.s*a.s*this.n*a.n,this.d*a.d)},div:function(e,t){return o(e,t),newFraction(this.s*a.s*this.n*a.d,this.d*a.n)},clone:function(){return newFraction(this.s*this.n,this.d)},mod:function(e,t){if(isNaN(this.n)||isNaN(this.d))return new Fraction$2(NaN);if(e===void 0)return newFraction(this.s*this.n%this.d,1);if(o(e,t),a.n===0&&this.d===0)throw DivisionByZero();return newFraction(this.s*(a.d*this.n)%(a.n*this.d),a.d*this.d)},gcd:function(e,t){return o(e,t),newFraction(gcd(a.n,this.n)*gcd(a.d,this.d),a.d*this.d)},lcm:function(e,t){return o(e,t),a.n===0&&this.n===0?newFraction(0,1):newFraction(a.n*this.n,gcd(a.n,this.n)*gcd(a.d,this.d))},ceil:function(e){return e=10**(e||0),isNaN(this.n)||isNaN(this.d)?new Fraction$2(NaN):newFraction(Math.ceil(e*this.s*this.n/this.d),e)},floor:function(e){return e=10**(e||0),isNaN(this.n)||isNaN(this.d)?new Fraction$2(NaN):newFraction(Math.floor(e*this.s*this.n/this.d),e)},round:function(e){return e=10**(e||0),isNaN(this.n)||isNaN(this.d)?new Fraction$2(NaN):newFraction(Math.round(e*this.s*this.n/this.d),e)},inverse:function(){return newFraction(this.s*this.d,this.n)},pow:function(e,t){if(o(e,t),a.d===1)return a.s<0?newFraction((this.s*this.d)**+a.n,this.n**+a.n):newFraction((this.s*this.n)**+a.n,this.d**+a.n);if(this.s<0)return null;var n=factorize(this.n),r=factorize(this.d),i=1,s=1;for(var c in n)if(c!==`1`){if(c===`0`){i=0;break}if(n[c]*=a.n,n[c]%a.d===0)n[c]/=a.d;else return null;i*=c**+n[c]}for(var c in r)if(c!==`1`){if(r[c]*=a.n,r[c]%a.d===0)r[c]/=a.d;else return null;s*=c**+r[c]}return a.s<0?newFraction(s,i):newFraction(i,s)},equals:function(e,t){return o(e,t),this.s*this.n*a.d===a.s*a.n*this.d},compare:function(e,t){o(e,t);var n=this.s*this.n*a.d-a.s*a.n*this.d;return(0<n)-(n<0)},simplify:function(e){if(isNaN(this.n)||isNaN(this.d))return this;e||=.001;for(var t=this.abs(),n=t.toContinued(),r=1;r<n.length;r++){for(var i=newFraction(n[r-1],1),a=r-2;a>=0;a--)i=i.inverse().add(n[a]);if(Math.abs(i.sub(t).valueOf())<e)return i.mul(this.s)}return this},divisible:function(e,t){return o(e,t),!(!(a.n*this.d)||this.n*a.d%(a.n*this.d))},valueOf:function(){return this.s*this.n/this.d},toFraction:function(e){var t,n=``,r=this.n,i=this.d;return this.s<0&&(n+=`-`),i===1?n+=r:(e&&(t=Math.floor(r/i))>0&&(n+=t,n+=` `,r%=i),n+=r,n+=`/`,n+=i),n},toLatex:function(e){var t,n=``,r=this.n,i=this.d;return this.s<0&&(n+=`-`),i===1?n+=r:(e&&(t=Math.floor(r/i))>0&&(n+=t,r%=i),n+=`\\frac{`,n+=r,n+=`}{`,n+=i,n+=`}`),n},toContinued:function(){var e,t=this.n,n=this.d,r=[];if(isNaN(t)||isNaN(n))return r;do r.push(Math.floor(t/n)),e=t%n,t=n,n=e;while(t!==1);return r},toString:function(e){var t=this.n,n=this.d;if(isNaN(t)||isNaN(n))return`NaN`;e||=15;var r=cycleLen(t,n),i=cycleStart(t,n,r),a=this.s<0?`-`:``;if(a+=t/n|0,t%=n,t*=10,t&&(a+=`.`),r){for(var o=i;o--;)a+=t/n|0,t%=n,t*=10;a+=`(`;for(var o=r;o--;)a+=t/n|0,t%=n,t*=10;a+=`)`}else for(var o=e;t&&o--;)a+=t/n|0,t%=n,t*=10;return a}},typeof t==`object`?(Object.defineProperty(Fraction$2,`__esModule`,{value:!0}),Fraction$2.default=Fraction$2,Fraction$2.Fraction=Fraction$2,n.exports=Fraction$2):r.Fraction=Fraction$2})(t)}))(),1),$e=factory(`Fraction`,[],()=>(Object.defineProperty($.default,`name`,{value:`Fraction`}),$.default.prototype.constructor=$.default,$.default.prototype.type=`Fraction`,$.default.prototype.isFraction=!0,$.default.prototype.toJSON=function(){return{mathjs:`Fraction`,n:this.s*this.n,d:this.d}},$.default.fromJSON=function(e){return new $.default(e)},$.default),{isClass:!0}),et=factory(`Matrix`,[],()=>{function Matrix$1(){if(!(this instanceof Matrix$1))throw SyntaxError(`Constructor must be called with the new operator`)}return e(Matrix$1,`Matrix`),Matrix$1.prototype.type=`Matrix`,Matrix$1.prototype.isMatrix=!0,Matrix$1.prototype.storage=function(){throw Error(`Cannot invoke storage on a Matrix interface`)},Matrix$1.prototype.datatype=function(){throw Error(`Cannot invoke datatype on a Matrix interface`)},Matrix$1.prototype.create=function(e,t){throw Error(`Cannot invoke create on a Matrix interface`)},Matrix$1.prototype.subset=function(e,t,n){throw Error(`Cannot invoke subset on a Matrix interface`)},Matrix$1.prototype.get=function(e){throw Error(`Cannot invoke get on a Matrix interface`)},Matrix$1.prototype.set=function(e,t,n){throw Error(`Cannot invoke set on a Matrix interface`)},Matrix$1.prototype.resize=function(e,t){throw Error(`Cannot invoke resize on a Matrix interface`)},Matrix$1.prototype.reshape=function(e,t){throw Error(`Cannot invoke reshape on a Matrix interface`)},Matrix$1.prototype.clone=function(){throw Error(`Cannot invoke clone on a Matrix interface`)},Matrix$1.prototype.size=function(){throw Error(`Cannot invoke size on a Matrix interface`)},Matrix$1.prototype.map=function(e,t){throw Error(`Cannot invoke map on a Matrix interface`)},Matrix$1.prototype.forEach=function(e){throw Error(`Cannot invoke forEach on a Matrix interface`)},Matrix$1.prototype[Symbol.iterator]=function(){throw Error(`Cannot iterate a Matrix interface`)},Matrix$1.prototype.toArray=function(){throw Error(`Cannot invoke toArray on a Matrix interface`)},Matrix$1.prototype.valueOf=function(){throw Error(`Cannot invoke valueOf on a Matrix interface`)},Matrix$1.prototype.format=function(e){throw Error(`Cannot invoke format on a Matrix interface`)},Matrix$1.prototype.toString=function(){throw Error(`Cannot invoke toString on a Matrix interface`)},Matrix$1},{isClass:!0});function maxArgumentCount(e){return Object.keys(e.signatures||{}).reduce(function(e,t){var n=(t.match(/,/g)||[]).length+1;return Math.max(e,n)},-1)}var tt=factory(`DenseMatrix`,[`Matrix`],t=>{var{Matrix:n}=t;function DenseMatrix$1(e,t){if(!(this instanceof DenseMatrix$1))throw SyntaxError(`Constructor must be called with the new operator`);if(t&&!isString$1(t))throw Error(`Invalid datatype: `+t);if(isMatrix(e))e.type===`DenseMatrix`?(this._data=clone$2(e._data),this._size=clone$2(e._size),this._datatype=t||e._datatype):(this._data=e.toArray(),this._size=e.size(),this._datatype=t||e._datatype);else if(e&&L(e.data)&&L(e.size))this._data=e.data,this._size=e.size,validate$1(this._data,this._size),this._datatype=t||e.datatype;else if(L(e))this._data=preprocess(e),this._size=arraySize(this._data),validate$1(this._data,this._size),this._datatype=t;else if(e)throw TypeError(`Unsupported type of data (`+typeOf(e)+`)`);else this._data=[],this._size=[0],this._datatype=t}e(DenseMatrix$1,`DenseMatrix`),DenseMatrix$1.prototype=new n,DenseMatrix$1.prototype.createDenseMatrix=function(e,t){return new DenseMatrix$1(e,t)},Object.defineProperty(DenseMatrix$1,`name`,{value:`DenseMatrix`}),DenseMatrix$1.prototype.constructor=DenseMatrix$1,DenseMatrix$1.prototype.type=`DenseMatrix`,DenseMatrix$1.prototype.isDenseMatrix=!0,DenseMatrix$1.prototype.getDataType=function(){return getArrayDataType(this._data,typeOf)},DenseMatrix$1.prototype.storage=function(){return`dense`},DenseMatrix$1.prototype.datatype=function(){return this._datatype},DenseMatrix$1.prototype.create=function(e,t){return new DenseMatrix$1(e,t)},DenseMatrix$1.prototype.subset=function(e,t,n){switch(arguments.length){case 1:return _get(this,e);case 2:case 3:return _set(this,e,t,n);default:throw SyntaxError(`Wrong number of arguments`)}},DenseMatrix$1.prototype.get=function(e){if(!L(e))throw TypeError(`Array expected`);if(e.length!==this._size.length)throw new DimensionError(e.length,this._size.length);for(var t=0;t<e.length;t++)validateIndex(e[t],this._size[t]);for(var n=this._data,r=0,i=e.length;r<i;r++){var a=e[r];validateIndex(a,n.length),n=n[a]}return n},DenseMatrix$1.prototype.set=function(e,t,n){if(!L(e))throw TypeError(`Array expected`);if(e.length<this._size.length)throw new DimensionError(e.length,this._size.length,`<`);var r,i,a,o=e.map(function(e){return e+1});_fit(this,o,n);var s=this._data;for(r=0,i=e.length-1;r<i;r++)a=e[r],validateIndex(a,s.length),s=s[a];return a=e[e.length-1],validateIndex(a,s.length),s[a]=t,this};function _get(e,t){if(!isIndex(t))throw TypeError(`Invalid index`);if(t.isScalar())return e.get(t.min());var n=t.size();if(n.length!==e._size.length)throw new DimensionError(n.length,e._size.length);for(var r=t.min(),i=t.max(),a=0,o=e._size.length;a<o;a++)validateIndex(r[a],e._size[a]),validateIndex(i[a],e._size[a]);return new DenseMatrix$1(_getSubmatrix(e._data,t,n.length,0),e._datatype)}function _getSubmatrix(e,t,n,r){var i=r===n-1,a=t.dimension(r);return i?a.map(function(t){return validateIndex(t,e.length),e[t]}).valueOf():a.map(function(i){validateIndex(i,e.length);var a=e[i];return _getSubmatrix(a,t,n,r+1)}).valueOf()}function _set(e,t,n,r){if(!t||t.isIndex!==!0)throw TypeError(`Invalid index`);var i=t.size(),a=t.isScalar(),o;if(isMatrix(n)?(o=n.size(),n=n.valueOf()):o=arraySize(n),a){if(o.length!==0)throw TypeError(`Scalar expected`);e.set(t.min(),n,r)}else{if(!deepStrictEqual(o,i))try{n=o.length===0?broadcastTo([n],i):broadcastTo(n,i),o=arraySize(n)}catch{}if(i.length<e._size.length)throw new DimensionError(i.length,e._size.length,`<`);if(o.length<i.length){for(var s=0,c=0;i[s]===1&&o[s]===1;)s++;for(;i[s]===1;)c++,s++;n=unsqueeze(n,i.length,c,o)}if(!deepStrictEqual(i,o))throw new DimensionError(i,o,`>`);_fit(e,t.max().map(function(e){return e+1}),r);var l=i.length;_setSubmatrix(e._data,t,n,l,0)}return e}function _setSubmatrix(e,t,n,r,i){var a=i===r-1,o=t.dimension(i);a?o.forEach(function(t,r){validateIndex(t),e[t]=n[r[0]]}):o.forEach(function(a,o){validateIndex(a),_setSubmatrix(e[a],t,n[o[0]],r,i+1)})}DenseMatrix$1.prototype.resize=function(e,t,n){if(!isCollection(e))throw TypeError(`Array or Matrix expected`);var r=e.valueOf().map(e=>Array.isArray(e)&&e.length===1?e[0]:e);return _resize$1(n?this.clone():this,r,t)};function _resize$1(e,t,n){if(t.length===0){for(var r=e._data;L(r);)r=r[0];return r}return e._size=t.slice(0),e._data=resize(e._data,e._size,n),e}e(_resize$1,`_resize`),DenseMatrix$1.prototype.reshape=function(e,t){var n=t?this.clone():this;return n._data=reshape(n._data,e),n._size=processSizesWildcard(e,n._size.reduce((e,t)=>e*t)),n};function _fit(e,t,n){for(var r=e._size.slice(0),i=!1;r.length<t.length;)r.push(0),i=!0;for(var a=0,o=t.length;a<o;a++)t[a]>r[a]&&(r[a]=t[a],i=!0);i&&_resize$1(e,r,n)}DenseMatrix$1.prototype.clone=function(){return new DenseMatrix$1({data:clone$2(this._data),size:clone$2(this._size),datatype:this._datatype})},DenseMatrix$1.prototype.size=function(){return this._size.slice(0)},DenseMatrix$1.prototype.map=function(e){var t=this,n=maxArgumentCount(e),r=function recurse(r,i){return L(r)?r.map(function(e,t){return recurse(e,i.concat(t))}):n===1?e(r):n===2?e(r,i):e(r,i,t)}(this._data,[]);return new DenseMatrix$1(r,this._datatype===void 0?void 0:getArrayDataType(r,typeOf))},DenseMatrix$1.prototype.forEach=function(e){var t=this;(function recurse(n,r){L(n)?n.forEach(function(e,t){recurse(e,r.concat(t))}):e(n,r,t)})(this._data,[])},DenseMatrix$1.prototype[Symbol.iterator]=function*(){yield*function*recurse(e,t){if(L(e))for(var n=0;n<e.length;n++)yield*recurse(e[n],t.concat(n));else yield{value:e,index:t}}(this._data,[])},DenseMatrix$1.prototype.rows=function(){var e=[];if(this.size().length!==2)throw TypeError(`Rows can only be returned for a 2D matrix.`);for(var t of this._data)e.push(new DenseMatrix$1([t],this._datatype));return e},DenseMatrix$1.prototype.columns=function(){var e=this,t=[],n=this.size();if(n.length!==2)throw TypeError(`Rows can only be returned for a 2D matrix.`);for(var r=this._data,i=function _loop$1(n){var i=r.map(e=>[e[n]]);t.push(new DenseMatrix$1(i,e._datatype))},a=0;a<n[1];a++)i(a);return t},DenseMatrix$1.prototype.toArray=function(){return clone$2(this._data)},DenseMatrix$1.prototype.valueOf=function(){return this._data},DenseMatrix$1.prototype.format=function(e){return format(this._data,e)},DenseMatrix$1.prototype.toString=function(){return format(this._data)},DenseMatrix$1.prototype.toJSON=function(){return{mathjs:`DenseMatrix`,data:this._data,size:this._size,datatype:this._datatype}},DenseMatrix$1.prototype.diagonal=function(e){if(e){if(isBigNumber(e)&&(e=e.toNumber()),!isNumber$1(e)||!isInteger(e))throw TypeError(`The parameter k must be an integer number`)}else e=0;for(var t=e>0?e:0,n=e<0?-e:0,r=this._size[0],i=this._size[1],a=Math.min(r-n,i-t),o=[],s=0;s<a;s++)o[s]=this._data[s+n][s+t];return new DenseMatrix$1({data:o,size:[a],datatype:this._datatype})},DenseMatrix$1.diagonal=function(e,t,n,r){if(!L(e))throw TypeError(`Array expected, size parameter`);if(e.length!==2)throw Error(`Only two dimensions matrix are supported`);if(e=e.map(function(e){if(isBigNumber(e)&&(e=e.toNumber()),!isNumber$1(e)||!isInteger(e)||e<1)throw Error(`Size values must be positive integers`);return e}),n){if(isBigNumber(n)&&(n=n.toNumber()),!isNumber$1(n)||!isInteger(n))throw TypeError(`The parameter k must be an integer number`)}else n=0;var i=n>0?n:0,a=n<0?-n:0,o=e[0],s=e[1],c=Math.min(o-a,s-i),l;if(L(t)){if(t.length!==c)throw Error(`Invalid value array length`);l=function _value$1(e){return t[e]}}else if(isMatrix(t)){var u=t.size();if(u.length!==1||u[0]!==c)throw Error(`Invalid matrix length`);l=function _value$1(e){return t.get([e])}}else l=function _value$1(){return t};r||=isBigNumber(l(0))?l(0).mul(0):0;var d=[];if(e.length>0){d=resize(d,e,r);for(var f=0;f<c;f++)d[f+a][f+i]=l(f)}return new DenseMatrix$1({data:d,size:[o,s]})},DenseMatrix$1.fromJSON=function(e){return new DenseMatrix$1(e)},DenseMatrix$1.prototype.swapRows=function(e,t){if(!isNumber$1(e)||!isInteger(e)||!isNumber$1(t)||!isInteger(t))throw Error(`Row index must be positive integers`);if(this._size.length!==2)throw Error(`Only two dimensional matrix is supported`);return validateIndex(e,this._size[0]),validateIndex(t,this._size[0]),DenseMatrix$1._swapRows(e,t,this._data),this},DenseMatrix$1._swapRows=function(e,t,n){var r=n[e];n[e]=n[t],n[t]=r};function preprocess(e){return isMatrix(e)?preprocess(e.valueOf()):L(e)?e.map(preprocess):e}return DenseMatrix$1},{isClass:!0});function deepMap(e,t,n){return e&&typeof e.map==`function`?e.map(function(e){return deepMap(e,t,n)}):t(e)}var nt=`isNumeric`,rt=factory(nt,[`typed`],e=>{var{typed:t}=e;return t(nt,{"number | BigNumber | Fraction | boolean":()=>!0,"Complex | Unit | string | null | undefined | Node":()=>!1,"Array | Matrix":t.referToSelf(e=>t=>deepMap(t,e))})}),it=`hasNumericValue`,at=factory(it,[`typed`,`isNumeric`],e=>{var{typed:t,isNumeric:n}=e;return t(it,{boolean:()=>!0,string:function string(e){return e.trim().length>0&&!isNaN(Number(e))},any:function any(e){return n(e)}})}),ot=Ne({BigNumber:Xe({config:Ee}),Complex:Qe({}),DenseMatrix:tt({Matrix:et({})}),Fraction:$e({})}),st=at({isNumeric:rt({typed:ot}),typed:ot});const shortTimePeriodIsMilliseconds=e=>{let t=Number(e);return Number.isNaN(t)?!1:t>=120&&t<=36e4},resolveWaitTimeMs=e=>{let t=Number(e),n=Date.now();return Number.isNaN(t)?n+1e3:!shortTimePeriodIsMilliseconds(t)&&c(t)?adjustUnixTimestamp(t):shortTimePeriodIsMilliseconds(t)?n+t:n+t*I},superNormalizeHeaders=e=>{let t={};for(let[n,r]of Object.entries(e)){let e=n.toLowerCase().replace(/^x-/,``).replace(/concurren.+-/g,`concurrency-`).replace(/-/g,``);t[e]=st(r)?Number(r):null}return t},extractRateLimitHeaders=e=>{let t=superNormalizeHeaders(e);return{rateLimitLimit:t.ratelimitlimit,rateLimitRemaining:t.ratelimitremaining,rateLimitReset:resolveWaitTimeMs(t.ratelimitreset),concurrencyLimit:t.ratelimitconcurrencylimit,concurrencyRemaining:t.ratelimitconcurrencyremaining,concurrencyReset:resolveWaitTimeMs(t.ratelimitconcurrencyreset)}},generateRequestKey=e=>{let{accountSecureId:t,service:n,resource:r,subResource:i,childResource:a,action:o,behaviours:s}=e??{};return[t,n,r,o].some(l)?null:[t,n,r,i,a,o,...s??[]].filter(Boolean).join(`-`)},getRetryAfterWaitTime=(e,t=10,n=1)=>{let r=Date.now();return c(e)||u(e)?evaluateRetryAfterNumber(Number(e),r,t,n):isString$1(e)&&e!==``?evaluateRetryAfterString(e,r,t,n):n},evaluateRetryAfterNumber=(e,t,n=10,r=1)=>{if(e<n)return e;let i=adjustUnixTimestamp(e);if(i>t){let e=Math.floor((i-t)/I);return e>0&&e<n?e:r}return r},evaluateRetryAfterString=(e,t,n=10,r=1)=>{if(be.test(e)){let t=parseFloat(e);return t>0&&t<n?t:r}let i=new Date(e);if(Number.isNaN(i.getTime()))return r;let a=i.getTime();if(a>t){let e=Math.floor((a-t)/I);return e>0&&e<n?e:r}return r},retryErrorInterceptor=({axiosInstance:t,logger:n,requestConfig:r,context:a})=>e(async e=>{let{response:o,config:s}=e;if(s?.signal?.aborted)return Promise.reject(createAxiosError(`Request aborted`,s,`ERR_CANCELED`,o));let{status:c,retryAfter:l}=convertError(o,a,r,n);if(c===429&&p(s)){let r=getRetryAfterWaitTime(l);if(s._retryCount>=5)return n?.warning({category:`http-transport`,message:`Max retries exceeded for ${s?.url}. Aborting.`,context:{...a??{},retryAfterHeader:l,retryAfterAsNumber:r}}),Promise.reject(e);let c=s._retryCount??0,u={...s,_retryCount:c+1},d=l?r*I:i(u._retryCount);return n?.debug({category:`http-transport`,message:`Received 429 error from ${s?.url}`,context:{...a??{},retryAfterHeader:l,calculatedRetryAfter:d}}),await abortableDelay(d,s,o),t?.request(u)}return Promise.reject(e)},`retryErrorInterceptor`),convertError=(e,t,n,r)=>{let{provider:i}=t??{},{status:a,headers:o,data:s}=e??{},{retryafter:c}=superNormalizeHeaders(o??{});if(l(i)||l(e))return r?.warning({category:`http-transport`,message:`Invalid parameters for convertError`,context:{...t,responseIsMissing:l(e),providerIsMissing:l(i),status:e?.status??`undefined`,statusText:e?.statusText??`undefined`,retryafter:c??`undefined`}}),{status:a,retryAfter:c};let u=n?.rateLimits?.mappedRateLimitErrors;if(p(u)&&p(s))for(let e of u){let{errorStatus:t,errorMessagePath:n,errorMessage:r,retryAfterPath:i,retryAfterUnit:l,retryAfterValue:u}=e;if(t!==a)continue;let f=n??`message`,p=testMessage(d(s)?w({path:f,json:s})[0]:s,r);if(t===a&&p){let e=convertRetryAfter(u??extractRetryAfter(o,i),l);return{status:429,retryAfter:c??e}}}return{status:a,retryAfter:c}},testMessage=(e,t)=>t instanceof RegExp?t.test(e??``):e?.includes(t)??!1,extractRetryAfter=(e,t)=>p(t)&&p(e)?w({path:t,json:e})[0]:null,convertRetryAfter=(e,t=`seconds`)=>p(e)?transformToSeconds(e,t):null,transformToSeconds=(e,t)=>{if(t===`seconds`)return typeof e==`string`?parseFloat(e):e;if(t===`milliseconds`)return(typeof e==`string`?parseFloat(e):e)/I;if(t===`date`){let t=typeof e==`string`&&!isNaN(Number(e))?parseFloat(e):e,n=new Date(t);if(isNaN(n.getTime()))throw Error(`Invalid date value`);return n.getTime()}throw Error(`Invalid type`)},ct=`rateLimitErrorInterceptor`,rateLimitErrorInterceptor=({axiosInstance:t,logger:n,requestConfig:r,context:a,concurrencyManager:o})=>e(async e=>{let{response:s,config:c}=e,u=c?.signal;if(l(a)||l(c))return n?.warning({category:`HttpClient`,message:`No context or config for this response - that doesn't seem right.`,context:{interceptor:ct,...c,httpsAgent:void 0,headers:void 0,hasContext:p(a),hasConfig:p(c)},code:F.InterceptorContextNotPresent}),Promise.reject(e);if(l(o))return n?.error({category:`HttpClient`,message:`ConcurrencyManager is not initialized`,context:{interceptor:ct,...c,httpsAgent:void 0,headers:void 0,concurrencyManagerInitialized:p(o)},code:F.RateLimitOrConcurrencyManagerNotInitialized}),Promise.reject(e);let{requestId:d,targetConcurrencyKey:f,leaseSubscription:m,setRemovalSubscription:h}=c?.requestMetadata??{};if(!(p(d)&&p(f)&&await o.releaseRequest(d,f))&&p(c?.requestMetadata)&&n?.error({category:`HttpClient`,message:`Failed to release request from concurrency manager`,context:{...a,interceptor:ct,requestId:d,targetConcurrencyKey:f,leaseSubscription:m,setRemovalSubscription:h},code:F.RateLimiterReleaseRequestFailed}),u?.aborted)return Promise.reject(createAxiosError(`Request aborted`,c,`ERR_CANCELED`,s));let{status:g,retryAfter:_}=convertError(s,a,r,n);if(g===429&&p(c)){let r=getRetryAfterWaitTime(_);if(c._retryCount>=5)return n?.warning({category:`HttpClient`,message:`Max retries exceeded for ${c.url}. Aborting.`,context:{...a??{},...c.requestMetadata??{},retryAfterHeader:_,retryAfterAsNumber:r}}),Promise.reject(e);let o=c?._retryCount??0,l={...c,_retryCount:o+1},u=_?r*I:i(l._retryCount);return n?.debug({category:`HttpClient`,message:`Received 429 error from ${c.url}`,context:{...a,retryAfterHeader:_,calculatedRetryAfter:u}}),await abortableDelay(u,c,s),t?.request(l)}return Promise.reject(e)},`rateLimitErrorInterceptor`),lt=`rateLimitResponseInterceptor`,rateLimitResponseInterceptor=({logger:t,context:n,concurrencyManager:r})=>e(async e=>{let i=e?.config,a=i?.signal;if(l(n))t?.warning({category:`HttpClient`,message:`No context for this response - that doesn't seem right.`,context:{interceptor:lt,...i,httpsAgent:void 0,headers:void 0}});else if(l(r))return t?.error({category:`HttpClient`,message:`ConcurrencyManager is not initialized`,context:{interceptor:lt,...i,httpsAgent:void 0,headers:void 0,concurrencyManagerInitialized:p(r)},code:F.RateLimitOrConcurrencyManagerNotInitialized}),e;else if(p(n.provider)&&p(n.accountSecureId)){let n=e?.headers;if(p(n)){let e=extractRateLimitHeaders(n);t?.debug({category:`HttpClient`,message:`Rate limit headers extracted`,context:{interceptor:lt,rateLimitHeaders:e}})}let{requestId:o,targetConcurrencyKey:s,leaseSubscription:c,setRemovalSubscription:l}=i?.requestMetadata??{};if(await r.releaseRequest(o,s)||t?.error({category:`HttpClient`,message:`Failed to release request from concurrency manager`,context:{interceptor:lt,requestId:o,targetConcurrencyKey:s,leaseSubscription:c,setRemovalSubscription:l},code:F.RateLimiterReleaseRequestFailed}),a?.aborted)return Promise.reject(createAxiosError(`Request aborted`,i,`ERR_CANCELED`,e))}return e},`rateLimitResponseInterceptor`),validateRequestInterceptor=e=>(e.validateStatus??=e=>e>=200&&e<300,e),ut=[{onFulfilled:validateRequestInterceptor,onRejected:null,options:void 0}],dt=[{onFulfilled:null,onRejected:retryErrorInterceptor},{onFulfilled:null,onRejected:abortErrorInterceptor}],ft=[{onFulfilled:validateRequestInterceptor,onRejected:null,options:void 0},{onFulfilled:checkConcurrencyInterceptor,onRejected:null,options:void 0}],pt=[{onFulfilled:rateLimitResponseInterceptor,onRejected:rateLimitErrorInterceptor},{onFulfilled:null,onRejected:abortErrorInterceptor}];var RateLimitManager=class extends ScriptManager{constructor(...e){super(...e),this.name=`RateLimitManager`}async additionalInitialization(){}getDynamicMaxWaitTime(e,t,n,r=59,i=.8,a=500){this.readyCheck();let o=e.subPools?.find(e=>e.urlPattern instanceof RegExp?e.urlPattern.test(n??``):n?.includes(e.urlPattern))?.rateLimit??e.mainRatelimit;if(o<=0)throw Error(`Requests per second (rps) must be greater than 0.`);let s=t.subPools?.find(e=>e.urlPattern instanceof RegExp?e.urlPattern.test(n??``):n?.includes(e.urlPattern))?.maxConcurrency??t.mainMaxConcurrency;if(s<=0)throw Error(`Concurrency must be greater than 0.`);let c=r*i,l=1/Math.min(o,s/(a/1e3)),u=Math.max(7.5,c*l);return Math.min(c,u)}async getWaitTime(e,t,n){this.readyCheck();let r=`rateLimit:${e}`,i=t.subPools?.find(e=>e.urlPattern instanceof RegExp?e.urlPattern.test(n??``):n?.includes(e.urlPattern))?.subPoolKey,a=p(i)?`${r}-${i}`:r,{mainRatelimit:o,subPools:s}=t,c=[{key:r,rateLimit:o},...s?.map(e=>{let{subPoolKey:t,rateLimit:n}=e;return{key:`${r}-${t}`,rateLimit:n}})??[]],l=c.map(e=>e.key),u=c.map(e=>e.rateLimit);return await this.executeScript(ve.incr,[a,...l],[o.toString(),...u.map(String)])}readyCheck(){if(!this.cacheClient||!this.scriptMap?.size)throw Error(`RateLimitManager not ready`)}isReady(){return!!this?.cacheClient&&!!this?.scriptMap?.size}close(){this.scriptMap?.clear(),this.reset()}},SingletonManager=class{static{this.instances=new Map}static async prepare(e,t,...n){if(!this.instances.has(e)){let t=new e;t.getSingleton=e=>{let t=this.instances.get(e);if(l(t))throw Error(`Singleton ${e.name} not prepared yet`);if(t.hasInitFailed?.())throw Error(`${e.name} initialization failed`);let n=t.getInstanceIfReady?.();if(p(n))return n;throw Error(`${e.name} not ready`)},this.instances.set(e,t)}let r=this.instances.get(e);try{return await r.getInstance(t,...n)}catch(t){throw r.hasInitFailed?.()&&this.instances.delete(e),t}}static getIfReady(e){return this.instances.get(e)?.getInstanceIfReady?.()??null}static reset(e){this.instances.get(e)?.reset?.(),this.instances.delete(e)}static cleanupFailed(){let e=0;for(let[t,n]of this.instances){let r=n;r?.hasInitFailed?.()&&(r?.reset?.(),this.instances.delete(t),e++)}return e}};let mt=function(e){return e.HttpTransportInstanceCreateError=`HttpTransportInstanceCreateError`,e}({});const getTransportInstance=async({logger:e,redisClientConfig:t,context:n,requestConfig:r,httpsAgentConfig:i}={})=>{let a,{NODE_ENV:o}=process.env,s=n?.behaviours??[`CONCURRENCY`,`RETRY`];try{if(a=s.includes(`RETRY`)?createDefaultRetryInstance(e,n):createDefaultInstance(e,n),l(n?.service)||l(n?.organizationId)||o===`test`||l(t)||l(e))return a;let c=SingletonManager.getIfReady(RateLimitManager)??void 0,u=SingletonManager.getIfReady(ConcurrencyManager)??void 0,d=c?.isReady(),f=u?.isRedisConfigured(),m=[],h=[];if(s.includes(`CONCURRENCY`)){if(!f)throw Error(`Concurrency Manager cannot connect to Redis. Cannot create advanced transport instance.`);if(!d)throw Error(`RateLimitManager is not ready. Cannot create advanced transport instance.`);m.push(...ft),h.push(...pt)}let g=generateRequestKey(n);if(l(g))return e?.warning({category:`http-transport`,message:`Unable to create a key for transport instance - Invalid state. Using base default instance.`,context:{...n,defaultInstanceInitialized:p(a)}}),a;let _=await ge.get(g);if(p(_))return _;let v={interceptors:{requestConfigs:m,responseConfigs:h},instanceConfig:{maxBodyLength:1/0},logger:e,context:n,requestConfig:r,httpsAgentConfig:i,concurrencyManager:u,rateLimitManager:c},y=HttpTransportFactory.createInstance(v);return e?.debug({category:`http-transport`,message:`Creating new Axios instance and caching it for key: [${g}]`,context:{...n}}),await ge.set(g,y),y}catch(t){return e?.error({category:`http-transport`,message:`Failed to create advanced transport instance. Using default instance.`,context:{...n,usingDefaultInstance:p(a)},error:t,code:mt.HttpTransportInstanceCreateError}),p(a)?a:createAxiosInstance()}},createDefaultInstance=(e,t)=>{let n={instanceConfig:{maxBodyLength:1/0},logger:e,context:t};return HttpTransportFactory.createInstance(n)??createAxiosInstance()},createDefaultRetryInstance=(e,t)=>{let n={interceptors:{requestConfigs:ut,responseConfigs:dt},instanceConfig:{maxBodyLength:1/0},logger:e,context:t};return HttpTransportFactory.createInstance(n)??createAxiosInstance()},createAxiosInstance=()=>y.create({maxBodyLength:1/0});var HttpClient=class{#e;#t;#n;#r;#i;#a;constructor({transportFactory:e=getTransportInstance,getRedisClient:t=buildRedisClientInstance,logger:n,redisClientConfig:r,errorMappingFn:i}={}){this.name=`HttpClient`,this.#e=e,this.#t=t,this.#n=n,this.#r=r,this.#i=i}#o({url:e,payload:t,method:n,context:r}){if(!r?.accountSecureId||r.accountSecureId.length<20||!e||!n)return null;let i=t?o(t):``;return`${r.accountSecureId}-${n.toUpperCase()}${i}-${e}`}async#s({url:e,payload:t,method:n,cacheTTL:r,context:i}){if(!this.#a||!r||r<=0)return null;let a=this.#o({url:e,payload:t,method:n,context:i});if(!a)return null;let o=await this.#a.getData(a);return o?(this.#n?.debug({category:this.name,message:`Cache hit for key [${a}].`}),o):(this.#n?.debug({category:this.name,message:`Cache miss for key [${a}].`}),null)}async#c({url:e,payload:t,method:n,cacheTTL:r,context:i,response:a}){if(!this.#a||!r||r<=0)return!1;let o=this.#o({url:e,payload:t,method:n,context:i});return o?(this.#n?.debug({category:this.name,message:`Caching result for key [${o}].`}),this.#a.setData({key:o,value:a,cacheTTL:r*60})):!1}async request({headers:e={},url:t,method:n=`get`,queryParams:r,maxRedirects:i=0,responseType:a,cacheTTL:o,context:s,traceId:c,payload:u,httpsAgent:d,httpAgent:f,requestConfig:m,httpsAgentConfig:h}){try{p(this.#r)&&l(this.#a)&&(this.#a=await this.#t(this.#r,this.#n,`HttpClient`));let g=this.#_(t,r),_=this.#l(e),v=this.#m(u,e),y=await this.#s({url:g,payload:v,method:n,cacheTTL:o,context:s});if(y)return{...y,responseTime:new Date};let b=he.getInstance(),x=(p(c)?await b.get(c):null)?.signal,S=await(await this.#e({redisClientConfig:this.#r,logger:this.#n,context:s,requestConfig:m,httpsAgentConfig:h})).request({headers:_,url:g,method:n,maxRedirects:i,responseType:a,data:v,httpsAgent:d,httpAgent:f,signal:x}),C={data:S.data,status:S.status,body:v,method:n,headers:this.#u(S.headers),requestUrl:t,responseType:S?.config?.responseType,responseTime:new Date};return await this.#c({url:g,payload:v,method:n,cacheTTL:o,context:s,response:C}),C}catch(e){let r=e;r.url=T(t),this.#n?.warning({category:this.name,message:`Request error [${n?.toUpperCase()} ${r.url}]: ${r.message}.`,error:r});let i=this.#h(r);throw p(i)?i:e}}async get({headers:e,url:t,queryParams:n,maxRedirects:r,cacheTTL:i,context:a,traceId:o,requestConfig:s}){return this.request({url:t,method:`get`,queryParams:n,headers:e,maxRedirects:r,cacheTTL:i,context:a,traceId:o,requestConfig:s})}async post({headers:e,url:t,maxRedirects:n,cacheTTL:r,context:i,traceId:a,payload:o,requestConfig:s}){return this.request({url:t,method:`post`,headers:e,maxRedirects:n,cacheTTL:r,context:i,traceId:a,payload:o,requestConfig:s})}async requestStream({headers:e={},url:t,method:n=`get`,queryParams:r,maxRedirects:i=0,context:a,traceId:o,payload:s,httpsAgent:c,httpAgent:l,requestConfig:u,httpsAgentConfig:d}){try{let f=this.#_(t,r),m=this.#l(e),h=this.#m(s,e),g=he.getInstance(),_=(p(o)?await g.get(o):null)?.signal,v=await(await this.#e({redisClientConfig:this.#r,logger:this.#n,context:a,requestConfig:u,httpsAgentConfig:d})).request({headers:m,url:f,method:n,maxRedirects:i,responseType:`stream`,data:h,httpsAgent:c,httpAgent:l,signal:_});return{status:v.status,headers:this.#u(v.headers),stream:v.data,requestUrl:t}}catch(e){let r=e;r.url=T(t),this.#n?.warning({category:this.name,message:`Stream request error [${n?.toUpperCase()} ${r.url}]: ${r.message}.`,error:r});let i=this.#h(r);throw p(i)?i:e}}#l(e){if(!e)return{};let t={};return Object.keys(e).forEach(n=>{t[n.toLowerCase()]=e[n]||``}),t}#u(e){if(!e)return{};let t={};return Object.keys(e).forEach(n=>{t[n]=e[n]||``}),t}#d(e){return e[`content-type`]===`application/x-www-form-urlencoded`}#f(e){return f(e[`content-type`])?e[`content-type`]?.startsWith(`multipart/form-data`)??!1:!1}#p(e){return l(e)||typeof e!=`object`||!e?!1:`pipe`in e&&typeof e.pipe==`function`}#m(e,t){if(!(l(e)||d(e)&&Object.keys(e).length===0))return this.#f(t)||this.#p(e)?e:this.#d(t)?E.stringify(e):e}#h(e){if(b(e)&&this.#i)return this.#i(e)}#g(e){return typeof e==`object`&&!!e&&`value`in e&&(typeof e.value==`string`||Array.isArray(e.value))}#_(e,t){if(l(t)||Object.keys(t).length===0)return e;let n={},r={},i={},a={};for(let[e,o]of Object.entries(t))if(this.#g(o)){let t=o.arrayFormat,s=o.value;t===`repeat`?r[e]=Array.isArray(s)?s:[s]:t===`brackets`?i[e]=Array.isArray(s)?s:[s]:t===`comma`?a[e]=Array.isArray(s)?s:[s]:n[e]=s}else n[e]=o;let o=[];Object.keys(n).length>0&&o.push(E.stringify(n)),Object.keys(r).length>0&&o.push(E.stringify(r,{arrayFormat:`repeat`})),Object.keys(i).length>0&&o.push(E.stringify(i,{arrayFormat:`brackets`})),Object.keys(a).length>0&&o.push(E.stringify(a,{arrayFormat:`comma`}));let s=o.join(`&`);return p(s)?`${e}?${s}`:e}};const buildHttpClientInstance=(e,t,n)=>new HttpClient({redisClientConfig:e,logger:t,errorMappingFn:n});var HttpClientManager=class{static{this.httpClientInstance=null}static async getInstance({redisClientConfig:e,logger:t,errorMappingFn:n,getHttpClient:r=buildHttpClientInstance}){return this.httpClientInstance??=r(e,t,n),this.httpClientInstance}static resetInstance(){this.httpClientInstance=null}};const ht=[`get`,`post`,`put`,`delete`,`patch`],gt={[A.rPush]:`
|
|
113
|
+
(function(r){var i=2e3,a={s:1,n:0,d:1};function assign(e,t){if(isNaN(e=parseInt(e,10)))throw InvalidParameter();return e*t}function newFraction(e,t){if(t===0)throw DivisionByZero();var n=Object.create(Fraction$2.prototype);n.s=e<0?-1:1,e=e<0?-e:e;var r=gcd(e,t);return n.n=e/r,n.d=t/r,n}function factorize(e){for(var t={},n=e,r=2,i=4;i<=n;){for(;n%r===0;)n/=r,t[r]=(t[r]||0)+1;i+=1+2*r++}return n===e?t[e]=(t[e]||0)+1:n>1&&(t[n]=(t[n]||0)+1),t}var o=e(function(e,t){var n=0,r=1,i=1,o=0,s=0,c=0,l=1,u=1,d=0,f=1,p=1,m=1,h=1e7,g;if(e!=null)if(t!==void 0){if(n=e,r=t,i=n*r,n%1!=0||r%1!=0)throw NonIntegerParameter()}else switch(typeof e){case`object`:if(`d`in e&&`n`in e)n=e.n,r=e.d,`s`in e&&(n*=e.s);else if(0 in e)n=e[0],1 in e&&(r=e[1]);else throw InvalidParameter();i=n*r;break;case`number`:if(e<0&&(i=e,e=-e),e%1==0)n=e;else if(e>0){for(e>=1&&(u=10**Math.floor(1+Math.log(e)/Math.LN10),e/=u);f<=h&&m<=h;)if(g=(d+p)/(f+m),e===g){f+m<=h?(n=d+p,r=f+m):m>f?(n=p,r=m):(n=d,r=f);break}else e>g?(d+=p,f+=m):(p+=d,m+=f),f>h?(n=p,r=m):(n=d,r=f);n*=u}else (isNaN(e)||isNaN(t))&&(r=n=NaN);break;case`string`:if(f=e.match(/\d+|./g),f===null)throw InvalidParameter();if(f[d]===`-`?(i=-1,d++):f[d]===`+`&&d++,f.length===d+1?s=assign(f[d++],i):f[d+1]===`.`||f[d]===`.`?(f[d]!==`.`&&(o=assign(f[d++],i)),d++,(d+1===f.length||f[d+1]===`(`&&f[d+3]===`)`||f[d+1]===`'`&&f[d+3]===`'`)&&(s=assign(f[d],i),l=10**f[d].length,d++),(f[d]===`(`&&f[d+2]===`)`||f[d]===`'`&&f[d+2]===`'`)&&(c=assign(f[d+1],i),u=10**f[d+1].length-1,d+=3)):f[d+1]===`/`||f[d+1]===`:`?(s=assign(f[d],i),l=assign(f[d+2],1),d+=3):f[d+3]===`/`&&f[d+1]===` `&&(o=assign(f[d],i),s=assign(f[d+2],i),l=assign(f[d+4],1),d+=5),f.length<=d){r=l*u,i=n=c+r*o+u*s;break}default:throw InvalidParameter()}if(r===0)throw DivisionByZero();a.s=i<0?-1:1,a.n=Math.abs(n),a.d=Math.abs(r)},`parse`);function modpow(e,t,n){for(var r=1;t>0;e=e*e%n,t>>=1)t&1&&(r=r*e%n);return r}function cycleLen(e,t){for(;t%2==0;t/=2);for(;t%5==0;t/=5);if(t===1)return 0;for(var n=10%t,r=1;n!==1;r++)if(n=n*10%t,r>i)return 0;return r}function cycleStart(e,t,n){for(var r=1,i=modpow(10,n,t),a=0;a<300;a++){if(r===i)return a;r=r*10%t,i=i*10%t}return 0}function gcd(e,t){if(!e)return t;if(!t)return e;for(;;){if(e%=t,!e)return t;if(t%=e,!t)return e}}function Fraction$2(e,t){if(o(e,t),this instanceof Fraction$2)e=gcd(a.d,a.n),this.s=a.s,this.n=a.n/e,this.d=a.d/e;else return newFraction(a.s*a.n,a.d)}e(Fraction$2,`Fraction`);var DivisionByZero=function(){return Error(`Division by Zero`)},InvalidParameter=function(){return Error(`Invalid argument`)},NonIntegerParameter=function(){return Error(`Parameters must be integer`)};Fraction$2.prototype={s:1,n:0,d:1,abs:function(){return newFraction(this.n,this.d)},neg:function(){return newFraction(-this.s*this.n,this.d)},add:function(e,t){return o(e,t),newFraction(this.s*this.n*a.d+a.s*this.d*a.n,this.d*a.d)},sub:function(e,t){return o(e,t),newFraction(this.s*this.n*a.d-a.s*this.d*a.n,this.d*a.d)},mul:function(e,t){return o(e,t),newFraction(this.s*a.s*this.n*a.n,this.d*a.d)},div:function(e,t){return o(e,t),newFraction(this.s*a.s*this.n*a.d,this.d*a.n)},clone:function(){return newFraction(this.s*this.n,this.d)},mod:function(e,t){if(isNaN(this.n)||isNaN(this.d))return new Fraction$2(NaN);if(e===void 0)return newFraction(this.s*this.n%this.d,1);if(o(e,t),a.n===0&&this.d===0)throw DivisionByZero();return newFraction(this.s*(a.d*this.n)%(a.n*this.d),a.d*this.d)},gcd:function(e,t){return o(e,t),newFraction(gcd(a.n,this.n)*gcd(a.d,this.d),a.d*this.d)},lcm:function(e,t){return o(e,t),a.n===0&&this.n===0?newFraction(0,1):newFraction(a.n*this.n,gcd(a.n,this.n)*gcd(a.d,this.d))},ceil:function(e){return e=10**(e||0),isNaN(this.n)||isNaN(this.d)?new Fraction$2(NaN):newFraction(Math.ceil(e*this.s*this.n/this.d),e)},floor:function(e){return e=10**(e||0),isNaN(this.n)||isNaN(this.d)?new Fraction$2(NaN):newFraction(Math.floor(e*this.s*this.n/this.d),e)},round:function(e){return e=10**(e||0),isNaN(this.n)||isNaN(this.d)?new Fraction$2(NaN):newFraction(Math.round(e*this.s*this.n/this.d),e)},inverse:function(){return newFraction(this.s*this.d,this.n)},pow:function(e,t){if(o(e,t),a.d===1)return a.s<0?newFraction((this.s*this.d)**+a.n,this.n**+a.n):newFraction((this.s*this.n)**+a.n,this.d**+a.n);if(this.s<0)return null;var n=factorize(this.n),r=factorize(this.d),i=1,s=1;for(var c in n)if(c!==`1`){if(c===`0`){i=0;break}if(n[c]*=a.n,n[c]%a.d===0)n[c]/=a.d;else return null;i*=c**+n[c]}for(var c in r)if(c!==`1`){if(r[c]*=a.n,r[c]%a.d===0)r[c]/=a.d;else return null;s*=c**+r[c]}return a.s<0?newFraction(s,i):newFraction(i,s)},equals:function(e,t){return o(e,t),this.s*this.n*a.d===a.s*a.n*this.d},compare:function(e,t){o(e,t);var n=this.s*this.n*a.d-a.s*a.n*this.d;return(0<n)-(n<0)},simplify:function(e){if(isNaN(this.n)||isNaN(this.d))return this;e||=.001;for(var t=this.abs(),n=t.toContinued(),r=1;r<n.length;r++){for(var i=newFraction(n[r-1],1),a=r-2;a>=0;a--)i=i.inverse().add(n[a]);if(Math.abs(i.sub(t).valueOf())<e)return i.mul(this.s)}return this},divisible:function(e,t){return o(e,t),!(!(a.n*this.d)||this.n*a.d%(a.n*this.d))},valueOf:function(){return this.s*this.n/this.d},toFraction:function(e){var t,n=``,r=this.n,i=this.d;return this.s<0&&(n+=`-`),i===1?n+=r:(e&&(t=Math.floor(r/i))>0&&(n+=t,n+=` `,r%=i),n+=r,n+=`/`,n+=i),n},toLatex:function(e){var t,n=``,r=this.n,i=this.d;return this.s<0&&(n+=`-`),i===1?n+=r:(e&&(t=Math.floor(r/i))>0&&(n+=t,r%=i),n+=`\\frac{`,n+=r,n+=`}{`,n+=i,n+=`}`),n},toContinued:function(){var e,t=this.n,n=this.d,r=[];if(isNaN(t)||isNaN(n))return r;do r.push(Math.floor(t/n)),e=t%n,t=n,n=e;while(t!==1);return r},toString:function(e){var t=this.n,n=this.d;if(isNaN(t)||isNaN(n))return`NaN`;e||=15;var r=cycleLen(t,n),i=cycleStart(t,n,r),a=this.s<0?`-`:``;if(a+=t/n|0,t%=n,t*=10,t&&(a+=`.`),r){for(var o=i;o--;)a+=t/n|0,t%=n,t*=10;a+=`(`;for(var o=r;o--;)a+=t/n|0,t%=n,t*=10;a+=`)`}else for(var o=e;t&&o--;)a+=t/n|0,t%=n,t*=10;return a}},typeof t==`object`?(Object.defineProperty(Fraction$2,`__esModule`,{value:!0}),Fraction$2.default=Fraction$2,Fraction$2.Fraction=Fraction$2,n.exports=Fraction$2):r.Fraction=Fraction$2})(t)}))(),1),$e=factory(`Fraction`,[],()=>(Object.defineProperty($.default,`name`,{value:`Fraction`}),$.default.prototype.constructor=$.default,$.default.prototype.type=`Fraction`,$.default.prototype.isFraction=!0,$.default.prototype.toJSON=function(){return{mathjs:`Fraction`,n:this.s*this.n,d:this.d}},$.default.fromJSON=function(e){return new $.default(e)},$.default),{isClass:!0}),et=factory(`Matrix`,[],()=>{function Matrix$1(){if(!(this instanceof Matrix$1))throw SyntaxError(`Constructor must be called with the new operator`)}return e(Matrix$1,`Matrix`),Matrix$1.prototype.type=`Matrix`,Matrix$1.prototype.isMatrix=!0,Matrix$1.prototype.storage=function(){throw Error(`Cannot invoke storage on a Matrix interface`)},Matrix$1.prototype.datatype=function(){throw Error(`Cannot invoke datatype on a Matrix interface`)},Matrix$1.prototype.create=function(e,t){throw Error(`Cannot invoke create on a Matrix interface`)},Matrix$1.prototype.subset=function(e,t,n){throw Error(`Cannot invoke subset on a Matrix interface`)},Matrix$1.prototype.get=function(e){throw Error(`Cannot invoke get on a Matrix interface`)},Matrix$1.prototype.set=function(e,t,n){throw Error(`Cannot invoke set on a Matrix interface`)},Matrix$1.prototype.resize=function(e,t){throw Error(`Cannot invoke resize on a Matrix interface`)},Matrix$1.prototype.reshape=function(e,t){throw Error(`Cannot invoke reshape on a Matrix interface`)},Matrix$1.prototype.clone=function(){throw Error(`Cannot invoke clone on a Matrix interface`)},Matrix$1.prototype.size=function(){throw Error(`Cannot invoke size on a Matrix interface`)},Matrix$1.prototype.map=function(e,t){throw Error(`Cannot invoke map on a Matrix interface`)},Matrix$1.prototype.forEach=function(e){throw Error(`Cannot invoke forEach on a Matrix interface`)},Matrix$1.prototype[Symbol.iterator]=function(){throw Error(`Cannot iterate a Matrix interface`)},Matrix$1.prototype.toArray=function(){throw Error(`Cannot invoke toArray on a Matrix interface`)},Matrix$1.prototype.valueOf=function(){throw Error(`Cannot invoke valueOf on a Matrix interface`)},Matrix$1.prototype.format=function(e){throw Error(`Cannot invoke format on a Matrix interface`)},Matrix$1.prototype.toString=function(){throw Error(`Cannot invoke toString on a Matrix interface`)},Matrix$1},{isClass:!0});function maxArgumentCount(e){return Object.keys(e.signatures||{}).reduce(function(e,t){var n=(t.match(/,/g)||[]).length+1;return Math.max(e,n)},-1)}var tt=factory(`DenseMatrix`,[`Matrix`],t=>{var{Matrix:n}=t;function DenseMatrix$1(e,t){if(!(this instanceof DenseMatrix$1))throw SyntaxError(`Constructor must be called with the new operator`);if(t&&!isString$1(t))throw Error(`Invalid datatype: `+t);if(isMatrix(e))e.type===`DenseMatrix`?(this._data=clone$2(e._data),this._size=clone$2(e._size),this._datatype=t||e._datatype):(this._data=e.toArray(),this._size=e.size(),this._datatype=t||e._datatype);else if(e&&L(e.data)&&L(e.size))this._data=e.data,this._size=e.size,validate$1(this._data,this._size),this._datatype=t||e.datatype;else if(L(e))this._data=preprocess(e),this._size=arraySize(this._data),validate$1(this._data,this._size),this._datatype=t;else if(e)throw TypeError(`Unsupported type of data (`+typeOf(e)+`)`);else this._data=[],this._size=[0],this._datatype=t}e(DenseMatrix$1,`DenseMatrix`),DenseMatrix$1.prototype=new n,DenseMatrix$1.prototype.createDenseMatrix=function(e,t){return new DenseMatrix$1(e,t)},Object.defineProperty(DenseMatrix$1,`name`,{value:`DenseMatrix`}),DenseMatrix$1.prototype.constructor=DenseMatrix$1,DenseMatrix$1.prototype.type=`DenseMatrix`,DenseMatrix$1.prototype.isDenseMatrix=!0,DenseMatrix$1.prototype.getDataType=function(){return getArrayDataType(this._data,typeOf)},DenseMatrix$1.prototype.storage=function(){return`dense`},DenseMatrix$1.prototype.datatype=function(){return this._datatype},DenseMatrix$1.prototype.create=function(e,t){return new DenseMatrix$1(e,t)},DenseMatrix$1.prototype.subset=function(e,t,n){switch(arguments.length){case 1:return _get(this,e);case 2:case 3:return _set(this,e,t,n);default:throw SyntaxError(`Wrong number of arguments`)}},DenseMatrix$1.prototype.get=function(e){if(!L(e))throw TypeError(`Array expected`);if(e.length!==this._size.length)throw new DimensionError(e.length,this._size.length);for(var t=0;t<e.length;t++)validateIndex(e[t],this._size[t]);for(var n=this._data,r=0,i=e.length;r<i;r++){var a=e[r];validateIndex(a,n.length),n=n[a]}return n},DenseMatrix$1.prototype.set=function(e,t,n){if(!L(e))throw TypeError(`Array expected`);if(e.length<this._size.length)throw new DimensionError(e.length,this._size.length,`<`);var r,i,a,o=e.map(function(e){return e+1});_fit(this,o,n);var s=this._data;for(r=0,i=e.length-1;r<i;r++)a=e[r],validateIndex(a,s.length),s=s[a];return a=e[e.length-1],validateIndex(a,s.length),s[a]=t,this};function _get(e,t){if(!isIndex(t))throw TypeError(`Invalid index`);if(t.isScalar())return e.get(t.min());var n=t.size();if(n.length!==e._size.length)throw new DimensionError(n.length,e._size.length);for(var r=t.min(),i=t.max(),a=0,o=e._size.length;a<o;a++)validateIndex(r[a],e._size[a]),validateIndex(i[a],e._size[a]);return new DenseMatrix$1(_getSubmatrix(e._data,t,n.length,0),e._datatype)}function _getSubmatrix(e,t,n,r){var i=r===n-1,a=t.dimension(r);return i?a.map(function(t){return validateIndex(t,e.length),e[t]}).valueOf():a.map(function(i){validateIndex(i,e.length);var a=e[i];return _getSubmatrix(a,t,n,r+1)}).valueOf()}function _set(e,t,n,r){if(!t||t.isIndex!==!0)throw TypeError(`Invalid index`);var i=t.size(),a=t.isScalar(),o;if(isMatrix(n)?(o=n.size(),n=n.valueOf()):o=arraySize(n),a){if(o.length!==0)throw TypeError(`Scalar expected`);e.set(t.min(),n,r)}else{if(!deepStrictEqual(o,i))try{n=o.length===0?broadcastTo([n],i):broadcastTo(n,i),o=arraySize(n)}catch{}if(i.length<e._size.length)throw new DimensionError(i.length,e._size.length,`<`);if(o.length<i.length){for(var s=0,c=0;i[s]===1&&o[s]===1;)s++;for(;i[s]===1;)c++,s++;n=unsqueeze(n,i.length,c,o)}if(!deepStrictEqual(i,o))throw new DimensionError(i,o,`>`);_fit(e,t.max().map(function(e){return e+1}),r);var l=i.length;_setSubmatrix(e._data,t,n,l,0)}return e}function _setSubmatrix(e,t,n,r,i){var a=i===r-1,o=t.dimension(i);a?o.forEach(function(t,r){validateIndex(t),e[t]=n[r[0]]}):o.forEach(function(a,o){validateIndex(a),_setSubmatrix(e[a],t,n[o[0]],r,i+1)})}DenseMatrix$1.prototype.resize=function(e,t,n){if(!isCollection(e))throw TypeError(`Array or Matrix expected`);var r=e.valueOf().map(e=>Array.isArray(e)&&e.length===1?e[0]:e);return _resize$1(n?this.clone():this,r,t)};function _resize$1(e,t,n){if(t.length===0){for(var r=e._data;L(r);)r=r[0];return r}return e._size=t.slice(0),e._data=resize(e._data,e._size,n),e}e(_resize$1,`_resize`),DenseMatrix$1.prototype.reshape=function(e,t){var n=t?this.clone():this;return n._data=reshape(n._data,e),n._size=processSizesWildcard(e,n._size.reduce((e,t)=>e*t)),n};function _fit(e,t,n){for(var r=e._size.slice(0),i=!1;r.length<t.length;)r.push(0),i=!0;for(var a=0,o=t.length;a<o;a++)t[a]>r[a]&&(r[a]=t[a],i=!0);i&&_resize$1(e,r,n)}DenseMatrix$1.prototype.clone=function(){return new DenseMatrix$1({data:clone$2(this._data),size:clone$2(this._size),datatype:this._datatype})},DenseMatrix$1.prototype.size=function(){return this._size.slice(0)},DenseMatrix$1.prototype.map=function(e){var t=this,n=maxArgumentCount(e),r=function recurse(r,i){return L(r)?r.map(function(e,t){return recurse(e,i.concat(t))}):n===1?e(r):n===2?e(r,i):e(r,i,t)}(this._data,[]);return new DenseMatrix$1(r,this._datatype===void 0?void 0:getArrayDataType(r,typeOf))},DenseMatrix$1.prototype.forEach=function(e){var t=this;(function recurse(n,r){L(n)?n.forEach(function(e,t){recurse(e,r.concat(t))}):e(n,r,t)})(this._data,[])},DenseMatrix$1.prototype[Symbol.iterator]=function*(){yield*function*recurse(e,t){if(L(e))for(var n=0;n<e.length;n++)yield*recurse(e[n],t.concat(n));else yield{value:e,index:t}}(this._data,[])},DenseMatrix$1.prototype.rows=function(){var e=[];if(this.size().length!==2)throw TypeError(`Rows can only be returned for a 2D matrix.`);for(var t of this._data)e.push(new DenseMatrix$1([t],this._datatype));return e},DenseMatrix$1.prototype.columns=function(){var e=this,t=[],n=this.size();if(n.length!==2)throw TypeError(`Rows can only be returned for a 2D matrix.`);for(var r=this._data,i=function _loop$1(n){var i=r.map(e=>[e[n]]);t.push(new DenseMatrix$1(i,e._datatype))},a=0;a<n[1];a++)i(a);return t},DenseMatrix$1.prototype.toArray=function(){return clone$2(this._data)},DenseMatrix$1.prototype.valueOf=function(){return this._data},DenseMatrix$1.prototype.format=function(e){return format(this._data,e)},DenseMatrix$1.prototype.toString=function(){return format(this._data)},DenseMatrix$1.prototype.toJSON=function(){return{mathjs:`DenseMatrix`,data:this._data,size:this._size,datatype:this._datatype}},DenseMatrix$1.prototype.diagonal=function(e){if(e){if(isBigNumber(e)&&(e=e.toNumber()),!isNumber$1(e)||!isInteger(e))throw TypeError(`The parameter k must be an integer number`)}else e=0;for(var t=e>0?e:0,n=e<0?-e:0,r=this._size[0],i=this._size[1],a=Math.min(r-n,i-t),o=[],s=0;s<a;s++)o[s]=this._data[s+n][s+t];return new DenseMatrix$1({data:o,size:[a],datatype:this._datatype})},DenseMatrix$1.diagonal=function(e,t,n,r){if(!L(e))throw TypeError(`Array expected, size parameter`);if(e.length!==2)throw Error(`Only two dimensions matrix are supported`);if(e=e.map(function(e){if(isBigNumber(e)&&(e=e.toNumber()),!isNumber$1(e)||!isInteger(e)||e<1)throw Error(`Size values must be positive integers`);return e}),n){if(isBigNumber(n)&&(n=n.toNumber()),!isNumber$1(n)||!isInteger(n))throw TypeError(`The parameter k must be an integer number`)}else n=0;var i=n>0?n:0,a=n<0?-n:0,o=e[0],s=e[1],c=Math.min(o-a,s-i),l;if(L(t)){if(t.length!==c)throw Error(`Invalid value array length`);l=function _value$1(e){return t[e]}}else if(isMatrix(t)){var u=t.size();if(u.length!==1||u[0]!==c)throw Error(`Invalid matrix length`);l=function _value$1(e){return t.get([e])}}else l=function _value$1(){return t};r||=isBigNumber(l(0))?l(0).mul(0):0;var d=[];if(e.length>0){d=resize(d,e,r);for(var f=0;f<c;f++)d[f+a][f+i]=l(f)}return new DenseMatrix$1({data:d,size:[o,s]})},DenseMatrix$1.fromJSON=function(e){return new DenseMatrix$1(e)},DenseMatrix$1.prototype.swapRows=function(e,t){if(!isNumber$1(e)||!isInteger(e)||!isNumber$1(t)||!isInteger(t))throw Error(`Row index must be positive integers`);if(this._size.length!==2)throw Error(`Only two dimensional matrix is supported`);return validateIndex(e,this._size[0]),validateIndex(t,this._size[0]),DenseMatrix$1._swapRows(e,t,this._data),this},DenseMatrix$1._swapRows=function(e,t,n){var r=n[e];n[e]=n[t],n[t]=r};function preprocess(e){return isMatrix(e)?preprocess(e.valueOf()):L(e)?e.map(preprocess):e}return DenseMatrix$1},{isClass:!0});function deepMap(e,t,n){return e&&typeof e.map==`function`?e.map(function(e){return deepMap(e,t,n)}):t(e)}var nt=`isNumeric`,rt=factory(nt,[`typed`],e=>{var{typed:t}=e;return t(nt,{"number | BigNumber | Fraction | boolean":()=>!0,"Complex | Unit | string | null | undefined | Node":()=>!1,"Array | Matrix":t.referToSelf(e=>t=>deepMap(t,e))})}),it=`hasNumericValue`,at=factory(it,[`typed`,`isNumeric`],e=>{var{typed:t,isNumeric:n}=e;return t(it,{boolean:()=>!0,string:function string(e){return e.trim().length>0&&!isNaN(Number(e))},any:function any(e){return n(e)}})}),ot=Ne({BigNumber:Xe({config:Ee}),Complex:Qe({}),DenseMatrix:tt({Matrix:et({})}),Fraction:$e({})}),st=at({isNumeric:rt({typed:ot}),typed:ot});const shortTimePeriodIsMilliseconds=e=>{let t=Number(e);return Number.isNaN(t)?!1:t>=120&&t<=36e4},resolveWaitTimeMs=e=>{let t=Number(e),n=Date.now();return Number.isNaN(t)?n+1e3:!shortTimePeriodIsMilliseconds(t)&&c(t)?adjustUnixTimestamp(t):shortTimePeriodIsMilliseconds(t)?n+t:n+t*I},superNormalizeHeaders=e=>{let t={};for(let[n,r]of Object.entries(e)){let e=n.toLowerCase().replace(/^x-/,``).replace(/concurren.+-/g,`concurrency-`).replace(/-/g,``);t[e]=st(r)?Number(r):null}return t},extractRateLimitHeaders=e=>{let t=superNormalizeHeaders(e);return{rateLimitLimit:t.ratelimitlimit,rateLimitRemaining:t.ratelimitremaining,rateLimitReset:resolveWaitTimeMs(t.ratelimitreset),concurrencyLimit:t.ratelimitconcurrencylimit,concurrencyRemaining:t.ratelimitconcurrencyremaining,concurrencyReset:resolveWaitTimeMs(t.ratelimitconcurrencyreset)}},generateRequestKey=e=>{let{accountSecureId:t,service:n,resource:r,subResource:i,childResource:a,action:o,behaviours:s}=e??{};return[t,n,r,o].some(l)?null:[t,n,r,i,a,o,...s??[]].filter(Boolean).join(`-`)},getRetryAfterWaitTime=(e,t=10,n=1)=>{let r=Date.now();return c(e)||u(e)?evaluateRetryAfterNumber(Number(e),r,t,n):isString$1(e)&&e!==``?evaluateRetryAfterString(e,r,t,n):n},evaluateRetryAfterNumber=(e,t,n=10,r=1)=>{if(e<n)return e;let i=adjustUnixTimestamp(e);if(i>t){let e=Math.floor((i-t)/I);return e>0&&e<n?e:r}return r},evaluateRetryAfterString=(e,t,n=10,r=1)=>{if(be.test(e)){let t=parseFloat(e);return t>0&&t<n?t:r}let i=new Date(e);if(Number.isNaN(i.getTime()))return r;let a=i.getTime();if(a>t){let e=Math.floor((a-t)/I);return e>0&&e<n?e:r}return r},retryErrorInterceptor=({axiosInstance:t,logger:n,requestConfig:r,context:a})=>e(async e=>{let{response:o,config:s}=e;if(s?.signal?.aborted)return Promise.reject(createAxiosError(`Request aborted`,s,`ERR_CANCELED`,o));let{status:c,retryAfter:l}=convertError(o,a,r,n);if(c===429&&p(s)){let r=getRetryAfterWaitTime(l);if(s._retryCount>=5)return n?.warning({category:`http-transport`,message:`Max retries exceeded for ${s?.url}. Aborting.`,context:{...a??{},retryAfterHeader:l,retryAfterAsNumber:r}}),Promise.reject(e);let c=s._retryCount??0,u={...s,_retryCount:c+1},d=l?r*I:i(u._retryCount);return n?.debug({category:`http-transport`,message:`Received 429 error from ${s?.url}`,context:{...a??{},retryAfterHeader:l,calculatedRetryAfter:d}}),await abortableDelay(d,s,o),t?.request(u)}return Promise.reject(e)},`retryErrorInterceptor`),convertError=(e,t,n,r)=>{let{provider:i}=t??{},{status:a,headers:o,data:s}=e??{},{retryafter:c}=superNormalizeHeaders(o??{});if(l(i)||l(e))return r?.warning({category:`http-transport`,message:`Invalid parameters for convertError`,context:{...t,responseIsMissing:l(e),providerIsMissing:l(i),status:e?.status??`undefined`,statusText:e?.statusText??`undefined`,retryafter:c??`undefined`}}),{status:a,retryAfter:c};let u=n?.rateLimits?.mappedRateLimitErrors;if(p(u)&&p(s))for(let e of u){let{errorStatus:t,errorMessagePath:n,errorMessage:r,retryAfterPath:i,retryAfterUnit:l,retryAfterValue:u}=e;if(t!==a)continue;let f=n??`message`,p=testMessage(d(s)?w({path:f,json:s})[0]:s,r);if(t===a&&p){let e=convertRetryAfter(u??extractRetryAfter(o,i),l);return{status:429,retryAfter:c??e}}}return{status:a,retryAfter:c}},testMessage=(e,t)=>t instanceof RegExp?t.test(e??``):e?.includes(t)??!1,extractRetryAfter=(e,t)=>p(t)&&p(e)?w({path:t,json:e})[0]:null,convertRetryAfter=(e,t=`seconds`)=>p(e)?transformToSeconds(e,t):null,transformToSeconds=(e,t)=>{if(t===`seconds`)return typeof e==`string`?parseFloat(e):e;if(t===`milliseconds`)return(typeof e==`string`?parseFloat(e):e)/I;if(t===`date`){let t=typeof e==`string`&&!isNaN(Number(e))?parseFloat(e):e,n=new Date(t);if(isNaN(n.getTime()))throw Error(`Invalid date value`);return n.getTime()}throw Error(`Invalid type`)},ct=`rateLimitErrorInterceptor`,rateLimitErrorInterceptor=({axiosInstance:t,logger:n,requestConfig:r,context:a,concurrencyManager:o})=>e(async e=>{let{response:s,config:c}=e,u=c?.signal;if(l(a)||l(c))return n?.warning({category:`HttpClient`,message:`No context or config for this response - that doesn't seem right.`,context:{interceptor:ct,...c,httpsAgent:void 0,headers:void 0,hasContext:p(a),hasConfig:p(c)},code:F.InterceptorContextNotPresent}),Promise.reject(e);if(l(o))return n?.error({category:`HttpClient`,message:`ConcurrencyManager is not initialized`,context:{interceptor:ct,...c,httpsAgent:void 0,headers:void 0,concurrencyManagerInitialized:p(o)},code:F.RateLimitOrConcurrencyManagerNotInitialized}),Promise.reject(e);let{requestId:d,targetConcurrencyKey:f,leaseSubscription:m,setRemovalSubscription:h}=c?.requestMetadata??{};if(!(p(d)&&p(f)&&await o.releaseRequest(d,f))&&p(c?.requestMetadata)&&n?.error({category:`HttpClient`,message:`Failed to release request from concurrency manager`,context:{...a,interceptor:ct,requestId:d,targetConcurrencyKey:f,leaseSubscription:m,setRemovalSubscription:h},code:F.RateLimiterReleaseRequestFailed}),u?.aborted)return Promise.reject(createAxiosError(`Request aborted`,c,`ERR_CANCELED`,s));let{status:g,retryAfter:_}=convertError(s,a,r,n);if(g===429&&p(c)){let r=getRetryAfterWaitTime(_);if(c._retryCount>=5)return n?.warning({category:`HttpClient`,message:`Max retries exceeded for ${c.url}. Aborting.`,context:{...a??{},...c.requestMetadata??{},retryAfterHeader:_,retryAfterAsNumber:r}}),Promise.reject(e);let o=c?._retryCount??0,l={...c,_retryCount:o+1},u=_?r*I:i(l._retryCount);return n?.debug({category:`HttpClient`,message:`Received 429 error from ${c.url}`,context:{...a,retryAfterHeader:_,calculatedRetryAfter:u}}),await abortableDelay(u,c,s),t?.request(l)}return Promise.reject(e)},`rateLimitErrorInterceptor`),lt=`rateLimitResponseInterceptor`,rateLimitResponseInterceptor=({logger:t,context:n,concurrencyManager:r})=>e(async e=>{let i=e?.config,a=i?.signal;if(l(n))t?.warning({category:`HttpClient`,message:`No context for this response - that doesn't seem right.`,context:{interceptor:lt,...i,httpsAgent:void 0,headers:void 0}});else if(l(r))return t?.error({category:`HttpClient`,message:`ConcurrencyManager is not initialized`,context:{interceptor:lt,...i,httpsAgent:void 0,headers:void 0,concurrencyManagerInitialized:p(r)},code:F.RateLimitOrConcurrencyManagerNotInitialized}),e;else if(p(n.provider)&&p(n.accountSecureId)){let n=e?.headers;if(p(n)){let e=extractRateLimitHeaders(n);t?.debug({category:`HttpClient`,message:`Rate limit headers extracted`,context:{interceptor:lt,rateLimitHeaders:e}})}let{requestId:o,targetConcurrencyKey:s,leaseSubscription:c,setRemovalSubscription:l}=i?.requestMetadata??{};if(await r.releaseRequest(o,s)||t?.error({category:`HttpClient`,message:`Failed to release request from concurrency manager`,context:{interceptor:lt,requestId:o,targetConcurrencyKey:s,leaseSubscription:c,setRemovalSubscription:l},code:F.RateLimiterReleaseRequestFailed}),a?.aborted)return Promise.reject(createAxiosError(`Request aborted`,i,`ERR_CANCELED`,e))}return e},`rateLimitResponseInterceptor`),validateRequestInterceptor=e=>(e.validateStatus??=e=>e>=200&&e<300,e),ut=[{onFulfilled:validateRequestInterceptor,onRejected:null,options:void 0}],dt=[{onFulfilled:null,onRejected:retryErrorInterceptor},{onFulfilled:null,onRejected:abortErrorInterceptor}],ft=[{onFulfilled:validateRequestInterceptor,onRejected:null,options:void 0},{onFulfilled:checkConcurrencyInterceptor,onRejected:null,options:void 0}],pt=[{onFulfilled:rateLimitResponseInterceptor,onRejected:rateLimitErrorInterceptor},{onFulfilled:null,onRejected:abortErrorInterceptor}];var RateLimitManager=class extends ScriptManager{constructor(...e){super(...e),this.name=`RateLimitManager`}async additionalInitialization(){}getDynamicMaxWaitTime(e,t,n,r=59,i=.8,a=500){this.readyCheck();let o=e.subPools?.find(e=>e.urlPattern instanceof RegExp?e.urlPattern.test(n??``):n?.includes(e.urlPattern))?.rateLimit??e.mainRatelimit;if(o<=0)throw Error(`Requests per second (rps) must be greater than 0.`);let s=t.subPools?.find(e=>e.urlPattern instanceof RegExp?e.urlPattern.test(n??``):n?.includes(e.urlPattern))?.maxConcurrency??t.mainMaxConcurrency;if(s<=0)throw Error(`Concurrency must be greater than 0.`);let c=r*i,l=1/Math.min(o,s/(a/1e3)),u=Math.max(7.5,c*l);return Math.min(c,u)}async getWaitTime(e,t,n){this.readyCheck();let r=`rateLimit:${e}`,i=t.subPools?.find(e=>e.urlPattern instanceof RegExp?e.urlPattern.test(n??``):n?.includes(e.urlPattern))?.subPoolKey,a=p(i)?`${r}-${i}`:r,{mainRatelimit:o,subPools:s}=t,c=[{key:r,rateLimit:o},...s?.map(e=>{let{subPoolKey:t,rateLimit:n}=e;return{key:`${r}-${t}`,rateLimit:n}})??[]],l=c.map(e=>e.key),u=c.map(e=>e.rateLimit);return await this.executeScript(ve.incr,[a,...l],[o.toString(),...u.map(String)])}readyCheck(){if(!this.cacheClient||!this.scriptMap?.size)throw Error(`RateLimitManager not ready`)}isReady(){return!!this?.cacheClient&&!!this?.scriptMap?.size}close(){this.scriptMap?.clear(),this.reset()}},SingletonManager=class{static{this.instances=new Map}static async prepare(e,t,...n){if(!this.instances.has(e)){let t=new e;t.getSingleton=e=>{let t=this.instances.get(e);if(l(t))throw Error(`Singleton ${e.name} not prepared yet`);if(t.hasInitFailed?.())throw Error(`${e.name} initialization failed`);let n=t.getInstanceIfReady?.();if(p(n))return n;throw Error(`${e.name} not ready`)},this.instances.set(e,t)}let r=this.instances.get(e);try{return await r.getInstance(t,...n)}catch(t){throw r.hasInitFailed?.()&&this.instances.delete(e),t}}static getIfReady(e){return this.instances.get(e)?.getInstanceIfReady?.()??null}static reset(e){this.instances.get(e)?.reset?.(),this.instances.delete(e)}static cleanupFailed(){let e=0;for(let[t,n]of this.instances){let r=n;r?.hasInitFailed?.()&&(r?.reset?.(),this.instances.delete(t),e++)}return e}};let mt=function(e){return e.HttpTransportInstanceCreateError=`HttpTransportInstanceCreateError`,e}({});const getTransportInstance=async({logger:e,redisClientConfig:t,context:n,requestConfig:r,httpsAgentConfig:i}={})=>{let a,{NODE_ENV:o}=process.env,s=n?.behaviours??[`CONCURRENCY`,`RETRY`];try{if(a=s.includes(`RETRY`)?createDefaultRetryInstance(e,n):createDefaultInstance(e,n),l(n?.service)||l(n?.organizationId)||o===`test`||l(t)||l(e))return a;let c=SingletonManager.getIfReady(RateLimitManager)??void 0,u=SingletonManager.getIfReady(ConcurrencyManager)??void 0,d=c?.isReady(),f=u?.isRedisConfigured(),m=[],h=[];if(s.includes(`CONCURRENCY`)){if(!f)throw Error(`Concurrency Manager cannot connect to Redis. Cannot create advanced transport instance.`);if(!d)throw Error(`RateLimitManager is not ready. Cannot create advanced transport instance.`);m.push(...ft),h.push(...pt)}let g=generateRequestKey(n);if(l(g))return e?.warning({category:`http-transport`,message:`Unable to create a key for transport instance - Invalid state. Using base default instance.`,context:{...n,defaultInstanceInitialized:p(a)}}),a;let _=await ge.get(g);if(p(_))return _;let v={interceptors:{requestConfigs:m,responseConfigs:h},instanceConfig:{maxBodyLength:1/0},logger:e,context:n,requestConfig:r,httpsAgentConfig:i,concurrencyManager:u,rateLimitManager:c},y=HttpTransportFactory.createInstance(v);return e?.debug({category:`http-transport`,message:`Creating new Axios instance and caching it for key: [${g}]`,context:{...n}}),await ge.set(g,y),y}catch(t){return e?.error({category:`http-transport`,message:`Failed to create advanced transport instance. Using default instance.`,context:{...n,usingDefaultInstance:p(a)},error:t,code:mt.HttpTransportInstanceCreateError}),p(a)?a:createAxiosInstance()}},createDefaultInstance=(e,t)=>{let n={instanceConfig:{maxBodyLength:1/0},logger:e,context:t};return HttpTransportFactory.createInstance(n)??createAxiosInstance()},createDefaultRetryInstance=(e,t)=>{let n={interceptors:{requestConfigs:ut,responseConfigs:dt},instanceConfig:{maxBodyLength:1/0},logger:e,context:t};return HttpTransportFactory.createInstance(n)??createAxiosInstance()},createAxiosInstance=()=>y.create({maxBodyLength:1/0});var HttpClient=class{#e;#t;#n;#r;#i;#a;constructor({transportFactory:e=getTransportInstance,getRedisClient:t=buildRedisClientInstance,logger:n,redisClientConfig:r,errorMappingFn:i}={}){this.name=`HttpClient`,this.#e=e,this.#t=t,this.#n=n,this.#r=r,this.#i=i}#o({url:e,payload:t,method:n,context:r}){if(!r?.accountSecureId||r.accountSecureId.length<20||!e||!n)return null;let i=t?o(t):``;return`${r.accountSecureId}-${n.toUpperCase()}${i}-${e}`}async#s({url:e,payload:t,method:n,cacheTTL:r,context:i}){if(!this.#a||!r||r<=0)return null;let a=this.#o({url:e,payload:t,method:n,context:i});if(!a)return null;let o=await this.#a.getData(a);return o?(this.#n?.debug({category:this.name,message:`Cache hit for key [${a}].`}),o):(this.#n?.debug({category:this.name,message:`Cache miss for key [${a}].`}),null)}async#c({url:e,payload:t,method:n,cacheTTL:r,context:i,response:a}){if(!this.#a||!r||r<=0)return!1;let o=this.#o({url:e,payload:t,method:n,context:i});return o?(this.#n?.debug({category:this.name,message:`Caching result for key [${o}].`}),this.#a.setData({key:o,value:a,cacheTTL:r*60})):!1}async request({headers:e={},url:t,method:n=`get`,queryParams:r,maxRedirects:i=0,responseType:a,cacheTTL:o,context:s,traceId:c,payload:u,httpsAgent:d,httpAgent:f,requestConfig:m,httpsAgentConfig:h}){try{p(this.#r)&&l(this.#a)&&(this.#a=await this.#t(this.#r,this.#n,`HttpClient`));let g=this.#v(t,r),_=this.#l(e),v=this.#h(u,e),y=await this.#s({url:g,payload:v,method:n,cacheTTL:o,context:s});if(y)return{...y,responseTime:new Date};let b=he.getInstance(),x=(p(c)?await b.get(c):null)?.signal,S=await(await this.#e({redisClientConfig:this.#r,logger:this.#n,context:s,requestConfig:m,httpsAgentConfig:h})).request({headers:_,url:g,method:n,maxRedirects:i,responseType:a,data:v,httpsAgent:d,httpAgent:f,signal:x}),C={data:S.data,status:S.status,body:v,method:n,headers:this.#u(S.headers),requestUrl:t,responseType:S?.config?.responseType,responseTime:new Date};return await this.#c({url:g,payload:v,method:n,cacheTTL:o,context:s,response:C}),C}catch(e){let r=e;r.url=T(t),this.#n?.warning({category:this.name,message:`Request error [${n?.toUpperCase()} ${r.url}]: ${r.message}.`,error:r});let i=this.#g(r);throw p(i)?i:e}}async get({headers:e,url:t,queryParams:n,maxRedirects:r,cacheTTL:i,context:a,traceId:o,requestConfig:s}){return this.request({url:t,method:`get`,queryParams:n,headers:e,maxRedirects:r,cacheTTL:i,context:a,traceId:o,requestConfig:s})}async post({headers:e,url:t,maxRedirects:n,cacheTTL:r,context:i,traceId:a,payload:o,requestConfig:s}){return this.request({url:t,method:`post`,headers:e,maxRedirects:n,cacheTTL:r,context:i,traceId:a,payload:o,requestConfig:s})}async requestStream({headers:e={},url:t,method:n=`get`,queryParams:r,maxRedirects:i=0,context:a,traceId:o,payload:s,httpsAgent:c,httpAgent:l,requestConfig:u,httpsAgentConfig:d}){try{let f=this.#v(t,r),m=this.#l(e),h=this.#h(s,e),g=he.getInstance(),_=(p(o)?await g.get(o):null)?.signal,v=await(await this.#e({redisClientConfig:this.#r,logger:this.#n,context:a,requestConfig:u,httpsAgentConfig:d})).request({headers:m,url:f,method:n,maxRedirects:i,responseType:`stream`,data:h,httpsAgent:c,httpAgent:l,signal:_});return{status:v.status,headers:this.#u(v.headers),stream:v.data,requestUrl:t}}catch(e){let r=e;r.url=T(t),this.#n?.warning({category:this.name,message:`Stream request error [${n?.toUpperCase()} ${r.url}]: ${r.message}.`,error:r});let i=this.#g(r);throw p(i)?i:e}}#l(e){if(!e)return{};let t={};return Object.keys(e).forEach(n=>{t[n.toLowerCase()]=e[n]||``}),t}#u(e){if(!e)return{};let t={};return Object.keys(e).forEach(n=>{t[n]=e[n]||``}),t}#d(e){return e[`content-type`]===`application/x-www-form-urlencoded`}#f(e){return f(e[`content-type`])?e[`content-type`]?.startsWith(`multipart/form-data`)??!1:!1}#p(e){return l(e)||typeof e!=`object`||!e?!1:`pipe`in e&&typeof e.pipe==`function`}#m(e){return Buffer.isBuffer(e)}#h(e,t){if(!(l(e)||d(e)&&Object.keys(e).length===0))return this.#f(t)||this.#p(e)||this.#m(e)?e:this.#d(t)?E.stringify(e):e}#g(e){if(b(e)&&this.#i)return this.#i(e)}#_(e){return typeof e==`object`&&!!e&&`value`in e&&(typeof e.value==`string`||Array.isArray(e.value))}#v(e,t){if(l(t)||Object.keys(t).length===0)return e;let n={},r={},i={},a={};for(let[e,o]of Object.entries(t))if(this.#_(o)){let t=o.arrayFormat,s=o.value;t===`repeat`?r[e]=Array.isArray(s)?s:[s]:t===`brackets`?i[e]=Array.isArray(s)?s:[s]:t===`comma`?a[e]=Array.isArray(s)?s:[s]:n[e]=s}else n[e]=o;let o=[];Object.keys(n).length>0&&o.push(E.stringify(n)),Object.keys(r).length>0&&o.push(E.stringify(r,{arrayFormat:`repeat`})),Object.keys(i).length>0&&o.push(E.stringify(i,{arrayFormat:`brackets`})),Object.keys(a).length>0&&o.push(E.stringify(a,{arrayFormat:`comma`}));let s=o.join(`&`);return p(s)?`${e}?${s}`:e}};const buildHttpClientInstance=(e,t,n)=>new HttpClient({redisClientConfig:e,logger:t,errorMappingFn:n});var HttpClientManager=class{static{this.httpClientInstance=null}static async getInstance({redisClientConfig:e,logger:t,errorMappingFn:n,getHttpClient:r=buildHttpClientInstance}){return this.httpClientInstance??=r(e,t,n),this.httpClientInstance}static resetInstance(){this.httpClientInstance=null}};const ht=[`get`,`post`,`put`,`delete`,`patch`],gt={[A.rPush]:`
|
|
114
114
|
local queueLength = redis.call('RPUSH', KEYS[1], ARGV[1])
|
|
115
115
|
|
|
116
116
|
redis.call('PEXPIRE', KEYS[1], ARGV[2])
|
|
@@ -170,8 +170,8 @@ Example:
|
|
|
170
170
|
return nil
|
|
171
171
|
`},initializeTransportSystem=async e=>{let{redisClientConfig:t,logger:n,generateUUID:r}=e;try{n?.info({category:`TransportInitialization`,message:`Starting transport system initialization`});let[e,i,a]=await Promise.all([SingletonManager.prepare(ConcurrencyManager,{redisClientConfig:t,scripts:de,logger:n,additionalArgs:r?[r]:void 0}),SingletonManager.prepare(QueueManager,{redisClientConfig:t,scripts:gt,logger:n}),SingletonManager.prepare(RateLimitManager,{redisClientConfig:t,scripts:_t,logger:n})]),o=[{name:`ConcurrencyManager`,ready:e.isReady()},{name:`QueueManager`,ready:i.isReady()},{name:`RateLimitManager`,ready:a.isReady()}],s=o.filter(e=>!e.ready);if(s.length>0){let e=s.map(e=>e.name).join(`, `);throw Error(`Failed to initialize managers: ${e}`)}return n?.info({category:`TransportInitialization`,message:`Transport system initialization completed successfully`,context:{initializedManagers:o.map(e=>e.name)}}),{concurrencyManager:e,queueManager:i,rateLimitManager:a}}catch(e){n?.error({category:`TransportInitialization`,message:`Failed to initialize transport system`,code:`TRANSPORT_INIT_ERROR`,error:e});let t=SingletonManager.cleanupFailed();throw t>0&&n?.info({category:`TransportInitialization`,message:`Cleaned up ${t} failed singleton instances`}),e}},shutdownTransportSystem=e=>{try{e?.info({category:`TransportInitialization`,message:`Starting transport system shutdown`});let t=SingletonManager.getIfReady(ConcurrencyManager),n=SingletonManager.getIfReady(QueueManager),r=SingletonManager.getIfReady(RateLimitManager);t?.close(),n?.close(),r?.close(),SingletonManager.reset(ConcurrencyManager),SingletonManager.reset(QueueManager),SingletonManager.reset(RateLimitManager),e?.info({category:`TransportInitialization`,message:`Transport system shutdown completed`})}catch(t){e?.error({category:`TransportInitialization`,message:`Error during transport system shutdown`,code:`TRANSPORT_SHUTDOWN_ERROR`,error:t})}},isTransportSystemReady=()=>{let e=SingletonManager.getIfReady(ConcurrencyManager),t=SingletonManager.getIfReady(QueueManager),n=SingletonManager.getIfReady(RateLimitManager);return!!(e?.isReady()&&t?.isReady()&&n?.isReady())},getTransportManagers=()=>{let e=SingletonManager.getIfReady(ConcurrencyManager),t=SingletonManager.getIfReady(QueueManager),n=SingletonManager.getIfReady(RateLimitManager);return e&&t&&n?{concurrencyManager:e,queueManager:t,rateLimitManager:n}:null},isHttpQueryParamValue=e=>typeof e==`object`&&!!e&&`value`in e&&(typeof e.value==`string`||Array.isArray(e.value)),toStringArray=e=>Array.isArray(e)?e:[e],toQueryValue=e=>Array.isArray(e)?e.map(String):String(e),mergeQueryValues=(e,t,n)=>{let r=toStringArray(t);if(isHttpQueryParamValue(e))return{value:[...toStringArray(e.value),...r],arrayFormat:n??e.arrayFormat};let i=[...toStringArray(e),...r];return n?{value:i,arrayFormat:n}:i},parseQueryParam=(e,t,n)=>{let r=toQueryValue(t);return e===void 0?n?{value:r,arrayFormat:n}:r:mergeQueryValues(e,r,n)},parseBodyParam=(e,t)=>Array.isArray(e)?e.concat(t):typeof e==`object`&&e&&typeof t==`object`&&t?{...e,...t}:t,parseRequestParameters=e=>e.reduce((e,t)=>{if(t.in===`query`){let n=e.query[t.name];e.query[t.name]=parseQueryParam(n,t.value,t.arrayFormat)}else if(t.in===`body`)if(t.spread)Array.isArray(t.value)?Array.isArray(e.body)?e.body=e.body.concat(t.value):e.body=t.value:typeof t.value==`object`&&t.value!==null&&(e.body={...e.body,...t.value});else{let n=e.body[t.name];e.body[t.name]=parseBodyParam(n,t.value)}else e.headers[t.name]=String(t.value);return e},{query:{},body:{},headers:{}}),vt=[`query`,`body`,`headers`],yt=[`repeat`,`brackets`,`comma`],isSuccessStatusCode=e=>p(e)&&e>=200&&e<=299,isFailedStatusCode=e=>p(e)&&e>=400&&e<=599,isInfoStatusCode=e=>p(e)&&e>=100&&e<=199;var RestClient=class{async performRequest({httpClient:e,url:t,method:n,headers:r,queryParams:i,body:a,customErrorConfigs:o,requestConfig:s}){let c;try{c=await e?.request({method:n,url:t,headers:r,queryParams:i,maxRedirects:0,payload:a,requestConfig:s})}catch(e){if(l(e?.response))throw e;c=e.response}let u=translateCustomError(c,o);if(isFailedStatusCode(u?.status))throw new me(u,u.message);return u}};const bt=`:A-Za-z_\\u00C0-\\u00D6\\u00D8-\\u00F6\\u00F8-\\u02FF\\u0370-\\u037D\\u037F-\\u1FFF\\u200C-\\u200D\\u2070-\\u218F\\u2C00-\\u2FEF\\u3001-\\uD7FF\\uF900-\\uFDCF\\uFDF0-\\uFFFD`;bt+``,``+bt;const xt=RegExp(`^[:A-Za-z_\\u00C0-\\u00D6\\u00D8-\\u00F6\\u00F8-\\u02FF\\u0370-\\u037D\\u037F-\\u1FFF\\u200C-\\u200D\\u2070-\\u218F\\u2C00-\\u2FEF\\u3001-\\uD7FF\\uF900-\\uFDCF\\uFDF0-\\uFFFD][:A-Za-z_\\u00C0-\\u00D6\\u00D8-\\u00F6\\u00F8-\\u02FF\\u0370-\\u037D\\u037F-\\u1FFF\\u200C-\\u200D\\u2070-\\u218F\\u2C00-\\u2FEF\\u3001-\\uD7FF\\uF900-\\uFDCF\\uFDF0-\\uFFFD\\-.\\d\\u00B7\\u0300-\\u036F\\u203F-\\u2040]*$`);function getAllMatches(e,t){let n=[],r=t.exec(e);for(;r;){let i=[];i.startIndex=t.lastIndex-r[0].length;let a=r.length;for(let e=0;e<a;e++)i.push(r[e]);n.push(i),r=t.exec(e)}return n}const isName=function(e){return xt.exec(e)!=null};function isExist(e){return e!==void 0}const St={allowBooleanAttributes:!1,unpairedTags:[]};function validate(e,t){t=Object.assign({},St,t);let n=[],r=!1,i=!1;e[0]===``&&(e=e.substr(1));for(let a=0;a<e.length;a++)if(e[a]===`<`&&e[a+1]===`?`){if(a+=2,a=readPI(e,a),a.err)return a}else if(e[a]===`<`){let o=a;if(a++,e[a]===`!`){a=readCommentAndCDATA(e,a);continue}else{let s=!1;e[a]===`/`&&(s=!0,a++);let c=``;for(;a<e.length&&e[a]!==`>`&&e[a]!==` `&&e[a]!==` `&&e[a]!==`
|
|
172
172
|
`&&e[a]!==`\r`;a++)c+=e[a];if(c=c.trim(),c[c.length-1]===`/`&&(c=c.substring(0,c.length-1),a--),!validateTagName(c)){let t;return t=c.trim().length===0?`Invalid space after '<'.`:`Tag '`+c+`' is an invalid name.`,getErrorObject(`InvalidTag`,t,getLineNumberForPosition(e,a))}let l=readAttributeStr(e,a);if(l===!1)return getErrorObject(`InvalidAttr`,`Attributes for '`+c+`' have open quote.`,getLineNumberForPosition(e,a));let u=l.value;if(a=l.index,u[u.length-1]===`/`){let n=a-u.length;u=u.substring(0,u.length-1);let i=validateAttributeString(u,t);if(i===!0)r=!0;else return getErrorObject(i.err.code,i.err.msg,getLineNumberForPosition(e,n+i.err.line))}else if(s)if(l.tagClosed){if(u.trim().length>0)return getErrorObject(`InvalidTag`,`Closing tag '`+c+`' can't have attributes or invalid starting.`,getLineNumberForPosition(e,o));if(n.length===0)return getErrorObject(`InvalidTag`,`Closing tag '`+c+`' has not been opened.`,getLineNumberForPosition(e,o));{let t=n.pop();if(c!==t.tagName){let n=getLineNumberForPosition(e,t.tagStartPos);return getErrorObject(`InvalidTag`,`Expected closing tag '`+t.tagName+`' (opened in line `+n.line+`, col `+n.col+`) instead of closing tag '`+c+`'.`,getLineNumberForPosition(e,o))}n.length==0&&(i=!0)}}else return getErrorObject(`InvalidTag`,`Closing tag '`+c+`' doesn't have proper closing.`,getLineNumberForPosition(e,a));else{let s=validateAttributeString(u,t);if(s!==!0)return getErrorObject(s.err.code,s.err.msg,getLineNumberForPosition(e,a-u.length+s.err.line));if(i===!0)return getErrorObject(`InvalidXml`,`Multiple possible root nodes found.`,getLineNumberForPosition(e,a));t.unpairedTags.indexOf(c)!==-1||n.push({tagName:c,tagStartPos:o}),r=!0}for(a++;a<e.length;a++)if(e[a]===`<`)if(e[a+1]===`!`){a++,a=readCommentAndCDATA(e,a);continue}else if(e[a+1]===`?`){if(a=readPI(e,++a),a.err)return a}else break;else if(e[a]===`&`){let t=validateAmpersand(e,a);if(t==-1)return getErrorObject(`InvalidChar`,`char '&' is not expected.`,getLineNumberForPosition(e,a));a=t}else if(i===!0&&!isWhiteSpace(e[a]))return getErrorObject(`InvalidXml`,`Extra text at the end`,getLineNumberForPosition(e,a));e[a]===`<`&&a--}}else{if(isWhiteSpace(e[a]))continue;return getErrorObject(`InvalidChar`,`char '`+e[a]+`' is not expected.`,getLineNumberForPosition(e,a))}if(r){if(n.length==1)return getErrorObject(`InvalidTag`,`Unclosed tag '`+n[0].tagName+`'.`,getLineNumberForPosition(e,n[0].tagStartPos));if(n.length>0)return getErrorObject(`InvalidXml`,`Invalid '`+JSON.stringify(n.map(e=>e.tagName),null,4).replace(/\r?\n/g,``)+`' found.`,{line:1,col:1})}else return getErrorObject(`InvalidXml`,`Start tag expected.`,1);return!0}function isWhiteSpace(e){return e===` `||e===` `||e===`
|
|
173
|
-
`||e===`\r`}function readPI(e,t){let n=t;for(;t<e.length;t++)if(e[t]==`?`||e[t]==` `){let r=e.substr(n,t-n);if(t>5&&r===`xml`)return getErrorObject(`InvalidXml`,`XML declaration allowed only at the start of the document.`,getLineNumberForPosition(e,t));if(e[t]==`?`&&e[t+1]==`>`){t++;break}else continue}return t}function readCommentAndCDATA(e,t){if(e.length>t+5&&e[t+1]===`-`&&e[t+2]===`-`){for(t+=3;t<e.length;t++)if(e[t]===`-`&&e[t+1]===`-`&&e[t+2]===`>`){t+=2;break}}else if(e.length>t+8&&e[t+1]===`D`&&e[t+2]===`O`&&e[t+3]===`C`&&e[t+4]===`T`&&e[t+5]===`Y`&&e[t+6]===`P`&&e[t+7]===`E`){let n=1;for(t+=8;t<e.length;t++)if(e[t]===`<`)n++;else if(e[t]===`>`&&(n--,n===0))break}else if(e.length>t+9&&e[t+1]===`[`&&e[t+2]===`C`&&e[t+3]===`D`&&e[t+4]===`A`&&e[t+5]===`T`&&e[t+6]===`A`&&e[t+7]===`[`){for(t+=8;t<e.length;t++)if(e[t]===`]`&&e[t+1]===`]`&&e[t+2]===`>`){t+=2;break}}return t}function readAttributeStr(e,t){let n=``,r=``,i=!1;for(;t<e.length;t++){if(e[t]===`"`||e[t]===`'`)r===``?r=e[t]:r!==e[t]||(r=``);else if(e[t]===`>`&&r===``){i=!0;break}n+=e[t]}return r===``?{value:n,index:t,tagClosed:i}:!1}const Ct=RegExp(`(\\s*)([^\\s=]+)(\\s*=)?(\\s*(['"])(([\\s\\S])*?)\\5)?`,`g`);function validateAttributeString(e,t){let n=getAllMatches(e,Ct),r={};for(let e=0;e<n.length;e++){if(n[e][1].length===0)return getErrorObject(`InvalidAttr`,`Attribute '`+n[e][2]+`' has no space in starting.`,getPositionFromMatch(n[e]));if(n[e][3]!==void 0&&n[e][4]===void 0)return getErrorObject(`InvalidAttr`,`Attribute '`+n[e][2]+`' is without value.`,getPositionFromMatch(n[e]));if(n[e][3]===void 0&&!t.allowBooleanAttributes)return getErrorObject(`InvalidAttr`,`boolean attribute '`+n[e][2]+`' is not allowed.`,getPositionFromMatch(n[e]));let i=n[e][2];if(!validateAttrName(i))return getErrorObject(`InvalidAttr`,`Attribute '`+i+`' is an invalid name.`,getPositionFromMatch(n[e]));if(!r.hasOwnProperty(i))r[i]=1;else return getErrorObject(`InvalidAttr`,`Attribute '`+i+`' is repeated.`,getPositionFromMatch(n[e]))}return!0}function validateNumberAmpersand(e,t){let n=/\d/;for(e[t]===`x`&&(t++,n=/[\da-fA-F]/);t<e.length;t++){if(e[t]===`;`)return t;if(!e[t].match(n))break}return-1}function validateAmpersand(e,t){if(t++,e[t]===`;`)return-1;if(e[t]===`#`)return t++,validateNumberAmpersand(e,t);let n=0;for(;t<e.length;t++,n++)if(!(e[t].match(/\w/)&&n<20)){if(e[t]===`;`)break;return-1}return t}function getErrorObject(e,t,n){return{err:{code:e,msg:t,line:n.line||n,col:n.col}}}function validateAttrName(e){return isName(e)}function validateTagName(e){return isName(e)}function getLineNumberForPosition(e,t){let n=e.substring(0,t).split(/\r?\n/);return{line:n.length,col:n[n.length-1].length+1}}function getPositionFromMatch(e){return e.startIndex+e[1].length}const wt={preserveOrder:!1,attributeNamePrefix:`@_`,attributesGroupName:!1,textNodeName:`#text`,ignoreAttributes:!0,removeNSPrefix:!1,allowBooleanAttributes:!1,parseTagValue:!0,parseAttributeValue:!1,trimValues:!0,cdataPropName:!1,numberParseOptions:{hex:!0,leadingZeros:!0,eNotation:!0},tagValueProcessor:function(e,t){return t},attributeValueProcessor:function(e,t){return t},stopNodes:[],alwaysCreateTextNode:!1,isArray:()=>!1,commentPropName:!1,unpairedTags:[],processEntities:!0,htmlEntities:!1,ignoreDeclaration:!1,ignorePiTags:!1,transformTagName:!1,transformAttributeName:!1,updateTag:function(e,t,n){return e},captureMetaData:!1},buildOptions=function(e){return Object.assign({},wt,e)};let Tt;Tt=typeof Symbol==`function`?Symbol(`XML Node Metadata`):`@@xmlMetadata`;var XmlNode=class{constructor(e){this.tagname=e,this.child=[],this[`:@`]={}}add(e,t){e===`__proto__`&&(e=`#__proto__`),this.child.push({[e]:t})}addChild(e,t){e.tagname===`__proto__`&&(e.tagname=`#__proto__`),e[`:@`]&&Object.keys(e[`:@`]).length>0?this.child.push({[e.tagname]:e.child,":@":e[`:@`]}):this.child.push({[e.tagname]:e.child}),t!==void 0&&(this.child[this.child.length-1][Tt]={startIndex:t})}static getMetaDataSymbol(){return Tt}};function readDocType(e,t){let n={};if(e[t+3]===`O`&&e[t+4]===`C`&&e[t+5]===`T`&&e[t+6]===`Y`&&e[t+7]===`P`&&e[t+8]===`E`){t+=9;let r=1,i=!1,a=!1,o=``;for(;t<e.length;t++)if(e[t]===`<`&&!a){if(i&&hasSeq(e,`!ENTITY`,t)){t+=7;let r,i;[r,i,t]=readEntityExp(e,t+1),i.indexOf(`&`)===-1&&(n[r]={regx:RegExp(`&${r};`,`g`),val:i})}else if(i&&hasSeq(e,`!ELEMENT`,t)){t+=8;let{index:n}=readElementExp(e,t+1);t=n}else if(i&&hasSeq(e,`!ATTLIST`,t))t+=8;else if(i&&hasSeq(e,`!NOTATION`,t)){t+=9;let{index:n}=readNotationExp(e,t+1);t=n}else if(hasSeq(e,`!--`,t))a=!0;else throw Error(`Invalid DOCTYPE`);r++,o=``}else if(e[t]===`>`){if(a?e[t-1]===`-`&&e[t-2]===`-`&&(a=!1,r--):r--,r===0)break}else e[t]===`[`?i=!0:o+=e[t];if(r!==0)throw Error(`Unclosed DOCTYPE`)}else throw Error(`Invalid Tag instead of DOCTYPE`);return{entities:n,i:t}}const skipWhitespace=(e,t)=>{for(;t<e.length&&/\s/.test(e[t]);)t++;return t};function readEntityExp(e,t){t=skipWhitespace(e,t);let n=``;for(;t<e.length&&!/\s/.test(e[t])&&e[t]!==`"`&&e[t]!==`'`;)n+=e[t],t++;if(validateEntityName(n),t=skipWhitespace(e,t),e.substring(t,t+6).toUpperCase()===`SYSTEM`)throw Error(`External entities are not supported`);if(e[t]===`%`)throw Error(`Parameter entities are not supported`);let r=``;return[t,r]=readIdentifierVal(e,t,`entity`),t--,[n,r,t]}function readNotationExp(e,t){t=skipWhitespace(e,t);let n=``;for(;t<e.length&&!/\s/.test(e[t]);)n+=e[t],t++;validateEntityName(n),t=skipWhitespace(e,t);let r=e.substring(t,t+6).toUpperCase();if(r!==`SYSTEM`&&r!==`PUBLIC`)throw Error(`Expected SYSTEM or PUBLIC, found "${r}"`);t+=r.length,t=skipWhitespace(e,t);let i=null,a=null;if(r===`PUBLIC`)[t,i]=readIdentifierVal(e,t,`publicIdentifier`),t=skipWhitespace(e,t),(e[t]===`"`||e[t]===`'`)&&([t,a]=readIdentifierVal(e,t,`systemIdentifier`));else if(r===`SYSTEM`&&([t,a]=readIdentifierVal(e,t,`systemIdentifier`),!a))throw Error(`Missing mandatory system identifier for SYSTEM notation`);return{notationName:n,publicIdentifier:i,systemIdentifier:a,index:--t}}function readIdentifierVal(e,t,n){let r=``,i=e[t];if(i!==`"`&&i!==`'`)throw Error(`Expected quoted string, found "${i}"`);for(t++;t<e.length&&e[t]!==i;)r+=e[t],t++;if(e[t]!==i)throw Error(`Unterminated ${n} value`);return t++,[t,r]}function readElementExp(e,t){t=skipWhitespace(e,t);let n=``;for(;t<e.length&&!/\s/.test(e[t]);)n+=e[t],t++;if(!validateEntityName(n))throw Error(`Invalid element name: "${n}"`);t=skipWhitespace(e,t);let r=``;if(e[t]===`E`&&hasSeq(e,`MPTY`,t))t+=4;else if(e[t]===`A`&&hasSeq(e,`NY`,t))t+=2;else if(e[t]===`(`){for(t++;t<e.length&&e[t]!==`)`;)r+=e[t],t++;if(e[t]!==`)`)throw Error(`Unterminated content model`)}else throw Error(`Invalid Element Expression, found "${e[t]}"`);return{elementName:n,contentModel:r.trim(),index:t}}function hasSeq(e,t,n){for(let r=0;r<t.length;r++)if(t[r]!==e[n+r+1])return!1;return!0}function validateEntityName(e){if(isName(e))return e;throw Error(`Invalid entity name ${e}`)}const Et=/^[-+]?0x[a-fA-F0-9]+$/,Dt=/^([\-\+])?(0*)([0-9]*(\.[0-9]*)?)$/,Ot={hex:!0,leadingZeros:!0,decimalPoint:`.`,eNotation:!0};function toNumber(e,t={}){if(t=Object.assign({},Ot,t),!e||typeof e!=`string`)return e;let n=e.trim();if(t.skipLike!==void 0&&t.skipLike.test(n))return e;if(e===`0`)return 0;if(t.hex&&Et.test(n))return parse_int(n,16);if(n.includes(`e`)||n.includes(`E`))return resolveEnotation(e,n,t);{let r=Dt.exec(n);if(r){let i=r[1]||``,a=r[2],o=trimZeros(r[3]),s=i?e[a.length+1]===`.`:e[a.length]===`.`;if(!t.leadingZeros&&(a.length>1||a.length===1&&!s))return e;{let r=Number(n),s=String(r);if(r===0)return r;if(s.search(/[eE]/)!==-1)return t.eNotation?r:e;if(n.indexOf(`.`)!==-1)return s===`0`||s===o||s===`${i}${o}`?r:e;let c=a?o:n;return a?c===s||i+c===s?r:e:c===s||c===i+s?r:e}}else return e}}const kt=/^([-+])?(0*)(\d*(\.\d*)?[eE][-\+]?\d+)$/;function resolveEnotation(e,t,n){if(!n.eNotation)return e;let r=t.match(kt);if(r){let i=r[1]||``,a=r[3].indexOf(`e`)===-1?`E`:`e`,o=r[2],s=i?e[o.length+1]===a:e[o.length]===a;return o.length>1&&s?e:o.length===1&&(r[3].startsWith(`.${a}`)||r[3][0]===a)?Number(t):n.leadingZeros&&!s?(t=(r[1]||``)+r[3],Number(t)):e}else return e}function trimZeros(e){return e&&e.indexOf(`.`)!==-1?(e=e.replace(/0+$/,``),e===`.`?e=`0`:e[0]===`.`?e=`0`+e:e[e.length-1]===`.`&&(e=e.substring(0,e.length-1)),e):e}function parse_int(e,t){if(parseInt)return parseInt(e,t);if(Number.parseInt)return Number.parseInt(e,t);if(window&&window.parseInt)return window.parseInt(e,t);throw Error(`parseInt, Number.parseInt, window.parseInt are not supported`)}function getIgnoreAttributesFn(e){return typeof e==`function`?e:Array.isArray(e)?t=>{for(let n of e)if(typeof n==`string`&&t===n||n instanceof RegExp&&n.test(t))return!0}:()=>!1}var OrderedObjParser=class{constructor(e){this.options=e,this.currentNode=null,this.tagsNodeStack=[],this.docTypeEntities={},this.lastEntities={apos:{regex:/&(apos|#39|#x27);/g,val:`'`},gt:{regex:/&(gt|#62|#x3E);/g,val:`>`},lt:{regex:/&(lt|#60|#x3C);/g,val:`<`},quot:{regex:/&(quot|#34|#x22);/g,val:`"`}},this.ampEntity={regex:/&(amp|#38|#x26);/g,val:`&`},this.htmlEntities={space:{regex:/&(nbsp|#160);/g,val:` `},cent:{regex:/&(cent|#162);/g,val:`¢`},pound:{regex:/&(pound|#163);/g,val:`£`},yen:{regex:/&(yen|#165);/g,val:`¥`},euro:{regex:/&(euro|#8364);/g,val:`€`},copyright:{regex:/&(copy|#169);/g,val:`©`},reg:{regex:/&(reg|#174);/g,val:`®`},inr:{regex:/&(inr|#8377);/g,val:`₹`},num_dec:{regex:/&#([0-9]{1,7});/g,val:(e,t)=>String.fromCodePoint(Number.parseInt(t,10))},num_hex:{regex:/&#x([0-9a-fA-F]{1,6});/g,val:(e,t)=>String.fromCodePoint(Number.parseInt(t,16))}},this.addExternalEntities=addExternalEntities,this.parseXml=parseXml,this.parseTextData=parseTextData,this.resolveNameSpace=resolveNameSpace,this.buildAttributesMap=buildAttributesMap,this.isItStopNode=isItStopNode,this.replaceEntitiesValue=jt,this.readStopNodeData=readStopNodeData,this.saveTextToParentTag=saveTextToParentTag,this.addChild=addChild,this.ignoreAttributesFn=getIgnoreAttributesFn(this.options.ignoreAttributes)}};function addExternalEntities(e){let t=Object.keys(e);for(let n=0;n<t.length;n++){let r=t[n];this.lastEntities[r]={regex:RegExp(`&`+r+`;`,`g`),val:e[r]}}}function parseTextData(e,t,n,r,i,a,o){if(e!==void 0&&(this.options.trimValues&&!r&&(e=e.trim()),e.length>0)){o||(e=this.replaceEntitiesValue(e));let r=this.options.tagValueProcessor(t,e,n,i,a);return r==null?e:typeof r!=typeof e||r!==e?r:this.options.trimValues||e.trim()===e?parseValue(e,this.options.parseTagValue,this.options.numberParseOptions):e}}function resolveNameSpace(e){if(this.options.removeNSPrefix){let t=e.split(`:`),n=e.charAt(0)===`/`?`/`:``;if(t[0]===`xmlns`)return``;t.length===2&&(e=n+t[1])}return e}const At=RegExp(`([^\\s=]+)\\s*(=\\s*(['"])([\\s\\S]*?)\\3)?`,`gm`);function buildAttributesMap(e,t,n){if(this.options.ignoreAttributes!==!0&&typeof e==`string`){let n=getAllMatches(e,At),r=n.length,i={};for(let e=0;e<r;e++){let r=this.resolveNameSpace(n[e][1]);if(this.ignoreAttributesFn(r,t))continue;let a=n[e][4],o=this.options.attributeNamePrefix+r;if(r.length)if(this.options.transformAttributeName&&(o=this.options.transformAttributeName(o)),o===`__proto__`&&(o=`#__proto__`),a!==void 0){this.options.trimValues&&(a=a.trim()),a=this.replaceEntitiesValue(a);let e=this.options.attributeValueProcessor(r,a,t);e==null?i[o]=a:typeof e!=typeof a||e!==a?i[o]=e:i[o]=parseValue(a,this.options.parseAttributeValue,this.options.numberParseOptions)}else this.options.allowBooleanAttributes&&(i[o]=!0)}if(!Object.keys(i).length)return;if(this.options.attributesGroupName){let e={};return e[this.options.attributesGroupName]=i,e}return i}}const parseXml=function(e){e=e.replace(/\r\n?/g,`
|
|
174
|
-
`);let t=new XmlNode(`!xml`),n=t,r=``,i=``;for(let a=0;a<e.length;a++)if(e[a]===`<`)if(e[a+1]===`/`){let t=findClosingIndex(e,`>`,a,`Closing Tag is not closed.`),o=e.substring(a+2,t).trim();if(this.options.removeNSPrefix){let e=o.indexOf(`:`);e!==-1&&(o=o.substr(e+1))}this.options.transformTagName&&(o=this.options.transformTagName(o)),n&&(r=this.saveTextToParentTag(r,n,i));let s=i.substring(i.lastIndexOf(`.`)+1);if(o&&this.options.unpairedTags.indexOf(o)!==-1)throw Error(`Unpaired tag can not be used as closing tag: </${o}>`);let c=0;s&&this.options.unpairedTags.indexOf(s)!==-1?(c=i.lastIndexOf(`.`,i.lastIndexOf(`.`)-1),this.tagsNodeStack.pop()):c=i.lastIndexOf(`.`),i=i.substring(0,c),n=this.tagsNodeStack.pop(),r=``,a=t}else if(e[a+1]===`?`){let t=readTagExp(e,a,!1,`?>`);if(!t)throw Error(`Pi Tag is not closed.`);if(r=this.saveTextToParentTag(r,n,i),!(this.options.ignoreDeclaration&&t.tagName===`?xml`||this.options.ignorePiTags)){let e=new XmlNode(t.tagName);e.add(this.options.textNodeName,``),t.tagName!==t.tagExp&&t.attrExpPresent&&(e[`:@`]=this.buildAttributesMap(t.tagExp,i,t.tagName)),this.addChild(n,e,i,a)}a=t.closeIndex+1}else if(e.substr(a+1,3)===`!--`){let t=findClosingIndex(e,`-->`,a+4,`Comment is not closed.`);if(this.options.commentPropName){let o=e.substring(a+4,t-2);r=this.saveTextToParentTag(r,n,i),n.add(this.options.commentPropName,[{[this.options.textNodeName]:o}])}a=t}else if(e.substr(a+1,2)===`!D`){let t=readDocType(e,a);this.docTypeEntities=t.entities,a=t.i}else if(e.substr(a+1,2)===`![`){let t=findClosingIndex(e,`]]>`,a,`CDATA is not closed.`)-2,o=e.substring(a+9,t);r=this.saveTextToParentTag(r,n,i);let s=this.parseTextData(o,n.tagname,i,!0,!1,!0,!0);s??=``,this.options.cdataPropName?n.add(this.options.cdataPropName,[{[this.options.textNodeName]:o}]):n.add(this.options.textNodeName,s),a=t+2}else{let o=readTagExp(e,a,this.options.removeNSPrefix),s=o.tagName,c=o.rawTagName,l=o.tagExp,u=o.attrExpPresent,d=o.closeIndex;this.options.transformTagName&&(s=this.options.transformTagName(s)),n&&r&&n.tagname!==`!xml`&&(r=this.saveTextToParentTag(r,n,i,!1));let f=n;f&&this.options.unpairedTags.indexOf(f.tagname)!==-1&&(n=this.tagsNodeStack.pop(),i=i.substring(0,i.lastIndexOf(`.`))),s!==t.tagname&&(i+=i?`.`+s:s);let p=a;if(this.isItStopNode(this.options.stopNodes,i,s)){let t=``;if(l.length>0&&l.lastIndexOf(`/`)===l.length-1)s[s.length-1]===`/`?(s=s.substr(0,s.length-1),i=i.substr(0,i.length-1),l=s):l=l.substr(0,l.length-1),a=o.closeIndex;else if(this.options.unpairedTags.indexOf(s)!==-1)a=o.closeIndex;else{let n=this.readStopNodeData(e,c,d+1);if(!n)throw Error(`Unexpected end of ${c}`);a=n.i,t=n.tagContent}let r=new XmlNode(s);s!==l&&u&&(r[`:@`]=this.buildAttributesMap(l,i,s)),t&&=this.parseTextData(t,s,i,!0,u,!0,!0),i=i.substr(0,i.lastIndexOf(`.`)),r.add(this.options.textNodeName,t),this.addChild(n,r,i,p)}else{if(l.length>0&&l.lastIndexOf(`/`)===l.length-1){s[s.length-1]===`/`?(s=s.substr(0,s.length-1),i=i.substr(0,i.length-1),l=s):l=l.substr(0,l.length-1),this.options.transformTagName&&(s=this.options.transformTagName(s));let e=new XmlNode(s);s!==l&&u&&(e[`:@`]=this.buildAttributesMap(l,i,s)),this.addChild(n,e,i,p),i=i.substr(0,i.lastIndexOf(`.`))}else{let e=new XmlNode(s);this.tagsNodeStack.push(n),s!==l&&u&&(e[`:@`]=this.buildAttributesMap(l,i,s)),this.addChild(n,e,i,p),n=e}r=``,a=d}}else r+=e[a];return t.child};function addChild(e,t,n,r){this.options.captureMetaData||(r=void 0);let i=this.options.updateTag(t.tagname,n,t[`:@`]);i===!1||(typeof i==`string`&&(t.tagname=i),e.addChild(t,r))}const jt=e(function(e){if(this.options.processEntities){for(let t in this.docTypeEntities){let n=this.docTypeEntities[t];e=e.replace(n.regx,n.val)}for(let t in this.lastEntities){let n=this.lastEntities[t];e=e.replace(n.regex,n.val)}if(this.options.htmlEntities)for(let t in this.htmlEntities){let n=this.htmlEntities[t];e=e.replace(n.regex,n.val)}e=e.replace(this.ampEntity.regex,this.ampEntity.val)}return e},`replaceEntitiesValue`);function saveTextToParentTag(e,t,n,r){return e&&=(r===void 0&&(r=t.child.length===0),e=this.parseTextData(e,t.tagname,n,!1,t[`:@`]?Object.keys(t[`:@`]).length!==0:!1,r),e!==void 0&&e!==``&&t.add(this.options.textNodeName,e),``),e}function isItStopNode(e,t,n){let r=`*.`+n;for(let n in e){let i=e[n];if(r===i||t===i)return!0}return!1}function tagExpWithClosingIndex(e,t,n=`>`){let r,i=``;for(let a=t;a<e.length;a++){let t=e[a];if(r)t===r&&(r=``);else if(t===`"`||t===`'`)r=t;else if(t===n[0])if(n[1]){if(e[a+1]===n[1])return{data:i,index:a}}else return{data:i,index:a};else t===` `&&(t=` `);i+=t}}function findClosingIndex(e,t,n,r){let i=e.indexOf(t,n);if(i===-1)throw Error(r);return i+t.length-1}function readTagExp(e,t,n,r=`>`){let i=tagExpWithClosingIndex(e,t+1,r);if(!i)return;let a=i.data,o=i.index,s=a.search(/\s/),c=a,l=!0;s!==-1&&(c=a.substring(0,s),a=a.substring(s+1).trimStart());let u=c;if(n){let e=c.indexOf(`:`);e!==-1&&(c=c.substr(e+1),l=c!==i.data.substr(e+1))}return{tagName:c,tagExp:a,closeIndex:o,attrExpPresent:l,rawTagName:u}}function readStopNodeData(e,t,n){let r=n,i=1;for(;n<e.length;n++)if(e[n]===`<`)if(e[n+1]===`/`){let a=findClosingIndex(e,`>`,n,`${t} is not closed`);if(e.substring(n+2,a).trim()===t&&(i--,i===0))return{tagContent:e.substring(r,n),i:a};n=a}else if(e[n+1]===`?`)n=findClosingIndex(e,`?>`,n+1,`StopNode is not closed.`);else if(e.substr(n+1,3)===`!--`)n=findClosingIndex(e,`-->`,n+3,`StopNode is not closed.`);else if(e.substr(n+1,2)===`![`)n=findClosingIndex(e,`]]>`,n,`StopNode is not closed.`)-2;else{let r=readTagExp(e,n,`>`);r&&((r&&r.tagName)===t&&r.tagExp[r.tagExp.length-1]!==`/`&&i++,n=r.closeIndex)}}function parseValue(e,t,n){if(t&&typeof e==`string`){let t=e.trim();return t===`true`?!0:t===`false`?!1:toNumber(e,n)}else if(isExist(e))return e;else return``}const Mt=XmlNode.getMetaDataSymbol();function prettify(e,t){return compress(e,t)}function compress(e,t,n){let r,i={};for(let a=0;a<e.length;a++){let o=e[a],s=propName$1(o),c=``;if(c=n===void 0?s:n+`.`+s,s===t.textNodeName)r===void 0?r=o[s]:r+=``+o[s];else if(s===void 0)continue;else if(o[s]){let e=compress(o[s],t,c),n=isLeafTag(e,t);o[Mt]!==void 0&&(e[Mt]=o[Mt]),o[`:@`]?assignAttributes(e,o[`:@`],c,t):Object.keys(e).length===1&&e[t.textNodeName]!==void 0&&!t.alwaysCreateTextNode?e=e[t.textNodeName]:Object.keys(e).length===0&&(t.alwaysCreateTextNode?e[t.textNodeName]=``:e=``),i[s]!==void 0&&i.hasOwnProperty(s)?(Array.isArray(i[s])||(i[s]=[i[s]]),i[s].push(e)):t.isArray(s,c,n)?i[s]=[e]:i[s]=e}}return typeof r==`string`?r.length>0&&(i[t.textNodeName]=r):r!==void 0&&(i[t.textNodeName]=r),i}function propName$1(e){let t=Object.keys(e);for(let e=0;e<t.length;e++){let n=t[e];if(n!==`:@`)return n}}e(propName$1,`propName`);function assignAttributes(e,t,n,r){if(t){let i=Object.keys(t),a=i.length;for(let o=0;o<a;o++){let a=i[o];r.isArray(a,n+`.`+a,!0,!0)?e[a]=[t[a]]:e[a]=t[a]}}}function isLeafTag(e,t){let{textNodeName:n}=t,r=Object.keys(e).length;return!!(r===0||r===1&&(e[n]||typeof e[n]==`boolean`||e[n]===0))}var XMLParser=class{constructor(e){this.externalEntities={},this.options=buildOptions(e)}parse(e,t){if(typeof e!=`string`)if(e.toString)e=e.toString();else throw Error(`XML data is accepted in String or Bytes[] form.`);if(t){t===!0&&(t={});let n=validate(e,t);if(n!==!0)throw Error(`${n.err.msg}:${n.err.line}:${n.err.col}`)}let n=new OrderedObjParser(this.options);n.addExternalEntities(this.externalEntities);let r=n.parseXml(e);return this.options.preserveOrder||r===void 0?r:prettify(r,this.options)}addEntity(e,t){if(t.indexOf(`&`)!==-1)throw Error(`Entity value can't have '&'`);if(e.indexOf(`&`)!==-1||e.indexOf(`;`)!==-1)throw Error(`An entity must be set without '&' and ';'. Eg. use '#xD' for '
'`);if(t===`&`)throw Error(`An entity with value '&' is not permitted`);this.externalEntities[e]=t}static getMetaDataSymbol(){return XmlNode.getMetaDataSymbol()}};function toXml(e,t){let n=``;return t.format&&t.indentBy.length>0&&(n=`
|
|
175
|
-
`)
|
|
173
|
+
`||e===`\r`}function readPI(e,t){let n=t;for(;t<e.length;t++)if(e[t]==`?`||e[t]==` `){let r=e.substr(n,t-n);if(t>5&&r===`xml`)return getErrorObject(`InvalidXml`,`XML declaration allowed only at the start of the document.`,getLineNumberForPosition(e,t));if(e[t]==`?`&&e[t+1]==`>`){t++;break}else continue}return t}function readCommentAndCDATA(e,t){if(e.length>t+5&&e[t+1]===`-`&&e[t+2]===`-`){for(t+=3;t<e.length;t++)if(e[t]===`-`&&e[t+1]===`-`&&e[t+2]===`>`){t+=2;break}}else if(e.length>t+8&&e[t+1]===`D`&&e[t+2]===`O`&&e[t+3]===`C`&&e[t+4]===`T`&&e[t+5]===`Y`&&e[t+6]===`P`&&e[t+7]===`E`){let n=1;for(t+=8;t<e.length;t++)if(e[t]===`<`)n++;else if(e[t]===`>`&&(n--,n===0))break}else if(e.length>t+9&&e[t+1]===`[`&&e[t+2]===`C`&&e[t+3]===`D`&&e[t+4]===`A`&&e[t+5]===`T`&&e[t+6]===`A`&&e[t+7]===`[`){for(t+=8;t<e.length;t++)if(e[t]===`]`&&e[t+1]===`]`&&e[t+2]===`>`){t+=2;break}}return t}function readAttributeStr(e,t){let n=``,r=``,i=!1;for(;t<e.length;t++){if(e[t]===`"`||e[t]===`'`)r===``?r=e[t]:r!==e[t]||(r=``);else if(e[t]===`>`&&r===``){i=!0;break}n+=e[t]}return r===``?{value:n,index:t,tagClosed:i}:!1}const Ct=RegExp(`(\\s*)([^\\s=]+)(\\s*=)?(\\s*(['"])(([\\s\\S])*?)\\5)?`,`g`);function validateAttributeString(e,t){let n=getAllMatches(e,Ct),r={};for(let e=0;e<n.length;e++){if(n[e][1].length===0)return getErrorObject(`InvalidAttr`,`Attribute '`+n[e][2]+`' has no space in starting.`,getPositionFromMatch(n[e]));if(n[e][3]!==void 0&&n[e][4]===void 0)return getErrorObject(`InvalidAttr`,`Attribute '`+n[e][2]+`' is without value.`,getPositionFromMatch(n[e]));if(n[e][3]===void 0&&!t.allowBooleanAttributes)return getErrorObject(`InvalidAttr`,`boolean attribute '`+n[e][2]+`' is not allowed.`,getPositionFromMatch(n[e]));let i=n[e][2];if(!validateAttrName(i))return getErrorObject(`InvalidAttr`,`Attribute '`+i+`' is an invalid name.`,getPositionFromMatch(n[e]));if(!Object.prototype.hasOwnProperty.call(r,i))r[i]=1;else return getErrorObject(`InvalidAttr`,`Attribute '`+i+`' is repeated.`,getPositionFromMatch(n[e]))}return!0}function validateNumberAmpersand(e,t){let n=/\d/;for(e[t]===`x`&&(t++,n=/[\da-fA-F]/);t<e.length;t++){if(e[t]===`;`)return t;if(!e[t].match(n))break}return-1}function validateAmpersand(e,t){if(t++,e[t]===`;`)return-1;if(e[t]===`#`)return t++,validateNumberAmpersand(e,t);let n=0;for(;t<e.length;t++,n++)if(!(e[t].match(/\w/)&&n<20)){if(e[t]===`;`)break;return-1}return t}function getErrorObject(e,t,n){return{err:{code:e,msg:t,line:n.line||n,col:n.col}}}function validateAttrName(e){return isName(e)}function validateTagName(e){return isName(e)}function getLineNumberForPosition(e,t){let n=e.substring(0,t).split(/\r?\n/);return{line:n.length,col:n[n.length-1].length+1}}function getPositionFromMatch(e){return e.startIndex+e[1].length}const wt={preserveOrder:!1,attributeNamePrefix:`@_`,attributesGroupName:!1,textNodeName:`#text`,ignoreAttributes:!0,removeNSPrefix:!1,allowBooleanAttributes:!1,parseTagValue:!0,parseAttributeValue:!1,trimValues:!0,cdataPropName:!1,numberParseOptions:{hex:!0,leadingZeros:!0,eNotation:!0},tagValueProcessor:function(e,t){return t},attributeValueProcessor:function(e,t){return t},stopNodes:[],alwaysCreateTextNode:!1,isArray:()=>!1,commentPropName:!1,unpairedTags:[],processEntities:!0,htmlEntities:!1,ignoreDeclaration:!1,ignorePiTags:!1,transformTagName:!1,transformAttributeName:!1,updateTag:function(e,t,n){return e},captureMetaData:!1,maxNestedTags:100,strictReservedNames:!0};function normalizeProcessEntities(e){return typeof e==`boolean`?{enabled:e,maxEntitySize:1e4,maxExpansionDepth:10,maxTotalExpansions:1e3,maxExpandedLength:1e5,maxEntityCount:100,allowedTags:null,tagFilter:null}:typeof e==`object`&&e?{enabled:e.enabled!==!1,maxEntitySize:e.maxEntitySize??1e4,maxExpansionDepth:e.maxExpansionDepth??10,maxTotalExpansions:e.maxTotalExpansions??1e3,maxExpandedLength:e.maxExpandedLength??1e5,maxEntityCount:e.maxEntityCount??100,allowedTags:e.allowedTags??null,tagFilter:e.tagFilter??null}:normalizeProcessEntities(!0)}const buildOptions=function(e){let t=Object.assign({},wt,e);return t.processEntities=normalizeProcessEntities(t.processEntities),t};let Tt;Tt=typeof Symbol==`function`?Symbol(`XML Node Metadata`):`@@xmlMetadata`;var XmlNode=class{constructor(e){this.tagname=e,this.child=[],this[`:@`]=Object.create(null)}add(e,t){e===`__proto__`&&(e=`#__proto__`),this.child.push({[e]:t})}addChild(e,t){e.tagname===`__proto__`&&(e.tagname=`#__proto__`),e[`:@`]&&Object.keys(e[`:@`]).length>0?this.child.push({[e.tagname]:e.child,":@":e[`:@`]}):this.child.push({[e.tagname]:e.child}),t!==void 0&&(this.child[this.child.length-1][Tt]={startIndex:t})}static getMetaDataSymbol(){return Tt}},DocTypeReader=class{constructor(e){this.suppressValidationErr=!e,this.options=e}readDocType(e,t){let n=Object.create(null),r=0;if(e[t+3]===`O`&&e[t+4]===`C`&&e[t+5]===`T`&&e[t+6]===`Y`&&e[t+7]===`P`&&e[t+8]===`E`){t+=9;let i=1,a=!1,o=!1,s=``;for(;t<e.length;t++)if(e[t]===`<`&&!o){if(a&&hasSeq(e,`!ENTITY`,t)){t+=7;let i,a;if([i,a,t]=this.readEntityExp(e,t+1,this.suppressValidationErr),a.indexOf(`&`)===-1){if(this.options.enabled!==!1&&this.options.maxEntityCount&&r>=this.options.maxEntityCount)throw Error(`Entity count (${r+1}) exceeds maximum allowed (${this.options.maxEntityCount})`);let e=i.replace(/[.\-+*:]/g,`\\.`);n[i]={regx:RegExp(`&${e};`,`g`),val:a},r++}}else if(a&&hasSeq(e,`!ELEMENT`,t)){t+=8;let{index:n}=this.readElementExp(e,t+1);t=n}else if(a&&hasSeq(e,`!ATTLIST`,t))t+=8;else if(a&&hasSeq(e,`!NOTATION`,t)){t+=9;let{index:n}=this.readNotationExp(e,t+1,this.suppressValidationErr);t=n}else if(hasSeq(e,`!--`,t))o=!0;else throw Error(`Invalid DOCTYPE`);i++,s=``}else if(e[t]===`>`){if(o?e[t-1]===`-`&&e[t-2]===`-`&&(o=!1,i--):i--,i===0)break}else e[t]===`[`?a=!0:s+=e[t];if(i!==0)throw Error(`Unclosed DOCTYPE`)}else throw Error(`Invalid Tag instead of DOCTYPE`);return{entities:n,i:t}}readEntityExp(e,t){t=skipWhitespace(e,t);let n=``;for(;t<e.length&&!/\s/.test(e[t])&&e[t]!==`"`&&e[t]!==`'`;)n+=e[t],t++;if(validateEntityName(n),t=skipWhitespace(e,t),!this.suppressValidationErr){if(e.substring(t,t+6).toUpperCase()===`SYSTEM`)throw Error(`External entities are not supported`);if(e[t]===`%`)throw Error(`Parameter entities are not supported`)}let r=``;if([t,r]=this.readIdentifierVal(e,t,`entity`),this.options.enabled!==!1&&this.options.maxEntitySize&&r.length>this.options.maxEntitySize)throw Error(`Entity "${n}" size (${r.length}) exceeds maximum allowed size (${this.options.maxEntitySize})`);return t--,[n,r,t]}readNotationExp(e,t){t=skipWhitespace(e,t);let n=``;for(;t<e.length&&!/\s/.test(e[t]);)n+=e[t],t++;!this.suppressValidationErr&&validateEntityName(n),t=skipWhitespace(e,t);let r=e.substring(t,t+6).toUpperCase();if(!this.suppressValidationErr&&r!==`SYSTEM`&&r!==`PUBLIC`)throw Error(`Expected SYSTEM or PUBLIC, found "${r}"`);t+=r.length,t=skipWhitespace(e,t);let i=null,a=null;if(r===`PUBLIC`)[t,i]=this.readIdentifierVal(e,t,`publicIdentifier`),t=skipWhitespace(e,t),(e[t]===`"`||e[t]===`'`)&&([t,a]=this.readIdentifierVal(e,t,`systemIdentifier`));else if(r===`SYSTEM`&&([t,a]=this.readIdentifierVal(e,t,`systemIdentifier`),!this.suppressValidationErr&&!a))throw Error(`Missing mandatory system identifier for SYSTEM notation`);return{notationName:n,publicIdentifier:i,systemIdentifier:a,index:--t}}readIdentifierVal(e,t,n){let r=``,i=e[t];if(i!==`"`&&i!==`'`)throw Error(`Expected quoted string, found "${i}"`);for(t++;t<e.length&&e[t]!==i;)r+=e[t],t++;if(e[t]!==i)throw Error(`Unterminated ${n} value`);return t++,[t,r]}readElementExp(e,t){t=skipWhitespace(e,t);let n=``;for(;t<e.length&&!/\s/.test(e[t]);)n+=e[t],t++;if(!this.suppressValidationErr&&!isName(n))throw Error(`Invalid element name: "${n}"`);t=skipWhitespace(e,t);let r=``;if(e[t]===`E`&&hasSeq(e,`MPTY`,t))t+=4;else if(e[t]===`A`&&hasSeq(e,`NY`,t))t+=2;else if(e[t]===`(`){for(t++;t<e.length&&e[t]!==`)`;)r+=e[t],t++;if(e[t]!==`)`)throw Error(`Unterminated content model`)}else if(!this.suppressValidationErr)throw Error(`Invalid Element Expression, found "${e[t]}"`);return{elementName:n,contentModel:r.trim(),index:t}}readAttlistExp(e,t){t=skipWhitespace(e,t);let n=``;for(;t<e.length&&!/\s/.test(e[t]);)n+=e[t],t++;validateEntityName(n),t=skipWhitespace(e,t);let r=``;for(;t<e.length&&!/\s/.test(e[t]);)r+=e[t],t++;if(!validateEntityName(r))throw Error(`Invalid attribute name: "${r}"`);t=skipWhitespace(e,t);let i=``;if(e.substring(t,t+8).toUpperCase()===`NOTATION`){if(i=`NOTATION`,t+=8,t=skipWhitespace(e,t),e[t]!==`(`)throw Error(`Expected '(', found "${e[t]}"`);t++;let n=[];for(;t<e.length&&e[t]!==`)`;){let r=``;for(;t<e.length&&e[t]!==`|`&&e[t]!==`)`;)r+=e[t],t++;if(r=r.trim(),!validateEntityName(r))throw Error(`Invalid notation name: "${r}"`);n.push(r),e[t]===`|`&&(t++,t=skipWhitespace(e,t))}if(e[t]!==`)`)throw Error(`Unterminated list of notations`);t++,i+=` (`+n.join(`|`)+`)`}else{for(;t<e.length&&!/\s/.test(e[t]);)i+=e[t],t++;if(!this.suppressValidationErr&&![`CDATA`,`ID`,`IDREF`,`IDREFS`,`ENTITY`,`ENTITIES`,`NMTOKEN`,`NMTOKENS`].includes(i.toUpperCase()))throw Error(`Invalid attribute type: "${i}"`)}t=skipWhitespace(e,t);let a=``;return e.substring(t,t+8).toUpperCase()===`#REQUIRED`?(a=`#REQUIRED`,t+=8):e.substring(t,t+7).toUpperCase()===`#IMPLIED`?(a=`#IMPLIED`,t+=7):[t,a]=this.readIdentifierVal(e,t,`ATTLIST`),{elementName:n,attributeName:r,attributeType:i,defaultValue:a,index:t}}};const skipWhitespace=(e,t)=>{for(;t<e.length&&/\s/.test(e[t]);)t++;return t};function hasSeq(e,t,n){for(let r=0;r<t.length;r++)if(t[r]!==e[n+r+1])return!1;return!0}function validateEntityName(e){if(isName(e))return e;throw Error(`Invalid entity name ${e}`)}const Et=/^[-+]?0x[a-fA-F0-9]+$/,Dt=/^([\-\+])?(0*)([0-9]*(\.[0-9]*)?)$/,Ot={hex:!0,leadingZeros:!0,decimalPoint:`.`,eNotation:!0,infinity:`original`};function toNumber(e,t={}){if(t=Object.assign({},Ot,t),!e||typeof e!=`string`)return e;let n=e.trim();if(t.skipLike!==void 0&&t.skipLike.test(n))return e;if(e===`0`)return 0;if(t.hex&&Et.test(n))return parse_int(n,16);if(isFinite(n)){if(n.includes(`e`)||n.includes(`E`))return resolveEnotation(e,n,t);{let r=Dt.exec(n);if(r){let i=r[1]||``,a=r[2],o=trimZeros(r[3]),s=i?e[a.length+1]===`.`:e[a.length]===`.`;if(!t.leadingZeros&&(a.length>1||a.length===1&&!s))return e;{let r=Number(n),s=String(r);if(r===0)return r;if(s.search(/[eE]/)!==-1)return t.eNotation?r:e;if(n.indexOf(`.`)!==-1)return s===`0`||s===o||s===`${i}${o}`?r:e;let c=a?o:n;return a?c===s||i+c===s?r:e:c===s||c===i+s?r:e}}else return e}}else return handleInfinity(e,Number(n),t)}const kt=/^([-+])?(0*)(\d*(\.\d*)?[eE][-\+]?\d+)$/;function resolveEnotation(e,t,n){if(!n.eNotation)return e;let r=t.match(kt);if(r){let i=r[1]||``,a=r[3].indexOf(`e`)===-1?`E`:`e`,o=r[2],s=i?e[o.length+1]===a:e[o.length]===a;return o.length>1&&s?e:o.length===1&&(r[3].startsWith(`.${a}`)||r[3][0]===a)?Number(t):n.leadingZeros&&!s?(t=(r[1]||``)+r[3],Number(t)):e}else return e}function trimZeros(e){return e&&e.indexOf(`.`)!==-1?(e=e.replace(/0+$/,``),e===`.`?e=`0`:e[0]===`.`?e=`0`+e:e[e.length-1]===`.`&&(e=e.substring(0,e.length-1)),e):e}function parse_int(e,t){if(parseInt)return parseInt(e,t);if(Number.parseInt)return Number.parseInt(e,t);if(window&&window.parseInt)return window.parseInt(e,t);throw Error(`parseInt, Number.parseInt, window.parseInt are not supported`)}function handleInfinity(e,t,n){let r=t===1/0;switch(n.infinity.toLowerCase()){case`null`:return null;case`infinity`:return t;case`string`:return r?`Infinity`:`-Infinity`;case`original`:default:return e}}function getIgnoreAttributesFn$1(e){return typeof e==`function`?e:Array.isArray(e)?t=>{for(let n of e)if(typeof n==`string`&&t===n||n instanceof RegExp&&n.test(t))return!0}:()=>!1}e(getIgnoreAttributesFn$1,`getIgnoreAttributesFn`);var OrderedObjParser=class{constructor(e){if(this.options=e,this.currentNode=null,this.tagsNodeStack=[],this.docTypeEntities={},this.lastEntities={apos:{regex:/&(apos|#39|#x27);/g,val:`'`},gt:{regex:/&(gt|#62|#x3E);/g,val:`>`},lt:{regex:/&(lt|#60|#x3C);/g,val:`<`},quot:{regex:/&(quot|#34|#x22);/g,val:`"`}},this.ampEntity={regex:/&(amp|#38|#x26);/g,val:`&`},this.htmlEntities={space:{regex:/&(nbsp|#160);/g,val:` `},cent:{regex:/&(cent|#162);/g,val:`¢`},pound:{regex:/&(pound|#163);/g,val:`£`},yen:{regex:/&(yen|#165);/g,val:`¥`},euro:{regex:/&(euro|#8364);/g,val:`€`},copyright:{regex:/&(copy|#169);/g,val:`©`},reg:{regex:/&(reg|#174);/g,val:`®`},inr:{regex:/&(inr|#8377);/g,val:`₹`},num_dec:{regex:/&#([0-9]{1,7});/g,val:(e,t)=>fromCodePoint(t,10,`&#`)},num_hex:{regex:/&#x([0-9a-fA-F]{1,6});/g,val:(e,t)=>fromCodePoint(t,16,`&#x`)}},this.addExternalEntities=addExternalEntities,this.parseXml=parseXml,this.parseTextData=parseTextData,this.resolveNameSpace=resolveNameSpace,this.buildAttributesMap=buildAttributesMap,this.isItStopNode=isItStopNode,this.replaceEntitiesValue=jt,this.readStopNodeData=readStopNodeData,this.saveTextToParentTag=saveTextToParentTag,this.addChild=addChild,this.ignoreAttributesFn=getIgnoreAttributesFn$1(this.options.ignoreAttributes),this.entityExpansionCount=0,this.currentExpandedLength=0,this.options.stopNodes&&this.options.stopNodes.length>0){this.stopNodesExact=new Set,this.stopNodesWildcard=new Set;for(let e=0;e<this.options.stopNodes.length;e++){let t=this.options.stopNodes[e];typeof t==`string`&&(t.startsWith(`*.`)?this.stopNodesWildcard.add(t.substring(2)):this.stopNodesExact.add(t))}}}};function addExternalEntities(e){let t=Object.keys(e);for(let n=0;n<t.length;n++){let r=t[n],i=r.replace(/[.\-+*:]/g,`\\.`);this.lastEntities[r]={regex:RegExp(`&`+i+`;`,`g`),val:e[r]}}}function parseTextData(e,t,n,r,i,a,o){if(e!==void 0&&(this.options.trimValues&&!r&&(e=e.trim()),e.length>0)){o||(e=this.replaceEntitiesValue(e,t,n));let r=this.options.tagValueProcessor(t,e,n,i,a);return r==null?e:typeof r!=typeof e||r!==e?r:this.options.trimValues||e.trim()===e?parseValue(e,this.options.parseTagValue,this.options.numberParseOptions):e}}function resolveNameSpace(e){if(this.options.removeNSPrefix){let t=e.split(`:`),n=e.charAt(0)===`/`?`/`:``;if(t[0]===`xmlns`)return``;t.length===2&&(e=n+t[1])}return e}const At=RegExp(`([^\\s=]+)\\s*(=\\s*(['"])([\\s\\S]*?)\\3)?`,`gm`);function buildAttributesMap(e,t,n){if(this.options.ignoreAttributes!==!0&&typeof e==`string`){let r=getAllMatches(e,At),i=r.length,a={};for(let e=0;e<i;e++){let i=this.resolveNameSpace(r[e][1]);if(this.ignoreAttributesFn(i,t))continue;let o=r[e][4],s=this.options.attributeNamePrefix+i;if(i.length)if(this.options.transformAttributeName&&(s=this.options.transformAttributeName(s)),s===`__proto__`&&(s=`#__proto__`),o!==void 0){this.options.trimValues&&(o=o.trim()),o=this.replaceEntitiesValue(o,n,t);let e=this.options.attributeValueProcessor(i,o,t);e==null?a[s]=o:typeof e!=typeof o||e!==o?a[s]=e:a[s]=parseValue(o,this.options.parseAttributeValue,this.options.numberParseOptions)}else this.options.allowBooleanAttributes&&(a[s]=!0)}if(!Object.keys(a).length)return;if(this.options.attributesGroupName){let e={};return e[this.options.attributesGroupName]=a,e}return a}}const parseXml=function(e){e=e.replace(/\r\n?/g,`
|
|
174
|
+
`);let t=new XmlNode(`!xml`),n=t,r=``,i=``;this.entityExpansionCount=0,this.currentExpandedLength=0;let a=new DocTypeReader(this.options.processEntities);for(let o=0;o<e.length;o++)if(e[o]===`<`)if(e[o+1]===`/`){let t=findClosingIndex(e,`>`,o,`Closing Tag is not closed.`),a=e.substring(o+2,t).trim();if(this.options.removeNSPrefix){let e=a.indexOf(`:`);e!==-1&&(a=a.substr(e+1))}this.options.transformTagName&&(a=this.options.transformTagName(a)),n&&(r=this.saveTextToParentTag(r,n,i));let s=i.substring(i.lastIndexOf(`.`)+1);if(a&&this.options.unpairedTags.indexOf(a)!==-1)throw Error(`Unpaired tag can not be used as closing tag: </${a}>`);let c=0;s&&this.options.unpairedTags.indexOf(s)!==-1?(c=i.lastIndexOf(`.`,i.lastIndexOf(`.`)-1),this.tagsNodeStack.pop()):c=i.lastIndexOf(`.`),i=i.substring(0,c),n=this.tagsNodeStack.pop(),r=``,o=t}else if(e[o+1]===`?`){let t=readTagExp(e,o,!1,`?>`);if(!t)throw Error(`Pi Tag is not closed.`);if(r=this.saveTextToParentTag(r,n,i),!(this.options.ignoreDeclaration&&t.tagName===`?xml`||this.options.ignorePiTags)){let e=new XmlNode(t.tagName);e.add(this.options.textNodeName,``),t.tagName!==t.tagExp&&t.attrExpPresent&&(e[`:@`]=this.buildAttributesMap(t.tagExp,i,t.tagName)),this.addChild(n,e,i,o)}o=t.closeIndex+1}else if(e.substr(o+1,3)===`!--`){let t=findClosingIndex(e,`-->`,o+4,`Comment is not closed.`);if(this.options.commentPropName){let a=e.substring(o+4,t-2);r=this.saveTextToParentTag(r,n,i),n.add(this.options.commentPropName,[{[this.options.textNodeName]:a}])}o=t}else if(e.substr(o+1,2)===`!D`){let t=a.readDocType(e,o);this.docTypeEntities=t.entities,o=t.i}else if(e.substr(o+1,2)===`![`){let t=findClosingIndex(e,`]]>`,o,`CDATA is not closed.`)-2,a=e.substring(o+9,t);r=this.saveTextToParentTag(r,n,i);let s=this.parseTextData(a,n.tagname,i,!0,!1,!0,!0);s??=``,this.options.cdataPropName?n.add(this.options.cdataPropName,[{[this.options.textNodeName]:a}]):n.add(this.options.textNodeName,s),o=t+2}else{let a=readTagExp(e,o,this.options.removeNSPrefix),s=a.tagName,c=a.rawTagName,l=a.tagExp,u=a.attrExpPresent,d=a.closeIndex;if(this.options.transformTagName){let e=this.options.transformTagName(s);l===s&&(l=e),s=e}if(this.options.strictReservedNames&&(s===this.options.commentPropName||s===this.options.cdataPropName))throw Error(`Invalid tag name: ${s}`);n&&r&&n.tagname!==`!xml`&&(r=this.saveTextToParentTag(r,n,i,!1));let f=n;f&&this.options.unpairedTags.indexOf(f.tagname)!==-1&&(n=this.tagsNodeStack.pop(),i=i.substring(0,i.lastIndexOf(`.`))),s!==t.tagname&&(i+=i?`.`+s:s);let p=o;if(this.isItStopNode(this.stopNodesExact,this.stopNodesWildcard,i,s)){let t=``;if(l.length>0&&l.lastIndexOf(`/`)===l.length-1)s[s.length-1]===`/`?(s=s.substr(0,s.length-1),i=i.substr(0,i.length-1),l=s):l=l.substr(0,l.length-1),o=a.closeIndex;else if(this.options.unpairedTags.indexOf(s)!==-1)o=a.closeIndex;else{let n=this.readStopNodeData(e,c,d+1);if(!n)throw Error(`Unexpected end of ${c}`);o=n.i,t=n.tagContent}let r=new XmlNode(s);s!==l&&u&&(r[`:@`]=this.buildAttributesMap(l,i,s)),t&&=this.parseTextData(t,s,i,!0,u,!0,!0),i=i.substr(0,i.lastIndexOf(`.`)),r.add(this.options.textNodeName,t),this.addChild(n,r,i,p)}else{if(l.length>0&&l.lastIndexOf(`/`)===l.length-1){if(s[s.length-1]===`/`?(s=s.substr(0,s.length-1),i=i.substr(0,i.length-1),l=s):l=l.substr(0,l.length-1),this.options.transformTagName){let e=this.options.transformTagName(s);l===s&&(l=e),s=e}let e=new XmlNode(s);s!==l&&u&&(e[`:@`]=this.buildAttributesMap(l,i,s)),this.addChild(n,e,i,p),i=i.substr(0,i.lastIndexOf(`.`))}else if(this.options.unpairedTags.indexOf(s)!==-1){let e=new XmlNode(s);s!==l&&u&&(e[`:@`]=this.buildAttributesMap(l,i)),this.addChild(n,e,i,p),i=i.substr(0,i.lastIndexOf(`.`)),o=a.closeIndex;continue}else{let e=new XmlNode(s);if(this.tagsNodeStack.length>this.options.maxNestedTags)throw Error(`Maximum nested tags exceeded`);this.tagsNodeStack.push(n),s!==l&&u&&(e[`:@`]=this.buildAttributesMap(l,i,s)),this.addChild(n,e,i,p),n=e}r=``,o=d}}else r+=e[o];return t.child};function addChild(e,t,n,r){this.options.captureMetaData||(r=void 0);let i=this.options.updateTag(t.tagname,n,t[`:@`]);i===!1||(typeof i==`string`&&(t.tagname=i),e.addChild(t,r))}const jt=e(function(e,t,n){if(e.indexOf(`&`)===-1)return e;let r=this.options.processEntities;if(!r.enabled||r.allowedTags&&!r.allowedTags.includes(t)||r.tagFilter&&!r.tagFilter(t,n))return e;for(let t in this.docTypeEntities){let n=this.docTypeEntities[t],i=e.match(n.regx);if(i){if(this.entityExpansionCount+=i.length,r.maxTotalExpansions&&this.entityExpansionCount>r.maxTotalExpansions)throw Error(`Entity expansion limit exceeded: ${this.entityExpansionCount} > ${r.maxTotalExpansions}`);let t=e.length;if(e=e.replace(n.regx,n.val),r.maxExpandedLength&&(this.currentExpandedLength+=e.length-t,this.currentExpandedLength>r.maxExpandedLength))throw Error(`Total expanded content size exceeded: ${this.currentExpandedLength} > ${r.maxExpandedLength}`)}}if(e.indexOf(`&`)===-1)return e;for(let t in this.lastEntities){let n=this.lastEntities[t];e=e.replace(n.regex,n.val)}if(e.indexOf(`&`)===-1)return e;if(this.options.htmlEntities)for(let t in this.htmlEntities){let n=this.htmlEntities[t];e=e.replace(n.regex,n.val)}return e=e.replace(this.ampEntity.regex,this.ampEntity.val),e},`replaceEntitiesValue`);function saveTextToParentTag(e,t,n,r){return e&&=(r===void 0&&(r=t.child.length===0),e=this.parseTextData(e,t.tagname,n,!1,t[`:@`]?Object.keys(t[`:@`]).length!==0:!1,r),e!==void 0&&e!==``&&t.add(this.options.textNodeName,e),``),e}function isItStopNode(e,t,n,r){return!!(t&&t.has(r)||e&&e.has(n))}function tagExpWithClosingIndex(e,t,n=`>`){let r,i=``;for(let a=t;a<e.length;a++){let t=e[a];if(r)t===r&&(r=``);else if(t===`"`||t===`'`)r=t;else if(t===n[0])if(n[1]){if(e[a+1]===n[1])return{data:i,index:a}}else return{data:i,index:a};else t===` `&&(t=` `);i+=t}}function findClosingIndex(e,t,n,r){let i=e.indexOf(t,n);if(i===-1)throw Error(r);return i+t.length-1}function readTagExp(e,t,n,r=`>`){let i=tagExpWithClosingIndex(e,t+1,r);if(!i)return;let a=i.data,o=i.index,s=a.search(/\s/),c=a,l=!0;s!==-1&&(c=a.substring(0,s),a=a.substring(s+1).trimStart());let u=c;if(n){let e=c.indexOf(`:`);e!==-1&&(c=c.substr(e+1),l=c!==i.data.substr(e+1))}return{tagName:c,tagExp:a,closeIndex:o,attrExpPresent:l,rawTagName:u}}function readStopNodeData(e,t,n){let r=n,i=1;for(;n<e.length;n++)if(e[n]===`<`)if(e[n+1]===`/`){let a=findClosingIndex(e,`>`,n,`${t} is not closed`);if(e.substring(n+2,a).trim()===t&&(i--,i===0))return{tagContent:e.substring(r,n),i:a};n=a}else if(e[n+1]===`?`)n=findClosingIndex(e,`?>`,n+1,`StopNode is not closed.`);else if(e.substr(n+1,3)===`!--`)n=findClosingIndex(e,`-->`,n+3,`StopNode is not closed.`);else if(e.substr(n+1,2)===`![`)n=findClosingIndex(e,`]]>`,n,`StopNode is not closed.`)-2;else{let r=readTagExp(e,n,`>`);r&&((r&&r.tagName)===t&&r.tagExp[r.tagExp.length-1]!==`/`&&i++,n=r.closeIndex)}}function parseValue(e,t,n){if(t&&typeof e==`string`){let t=e.trim();return t===`true`?!0:t===`false`?!1:toNumber(e,n)}else if(isExist(e))return e;else return``}function fromCodePoint(e,t,n){let r=Number.parseInt(e,t);return r>=0&&r<=1114111?String.fromCodePoint(r):n+e+`;`}const Mt=XmlNode.getMetaDataSymbol();function prettify(e,t){return compress(e,t)}function compress(e,t,n){let r,i={};for(let a=0;a<e.length;a++){let o=e[a],s=propName$1(o),c=``;if(c=n===void 0?s:n+`.`+s,s===t.textNodeName)r===void 0?r=o[s]:r+=``+o[s];else if(s===void 0)continue;else if(o[s]){let e=compress(o[s],t,c),n=isLeafTag(e,t);o[`:@`]?assignAttributes(e,o[`:@`],c,t):Object.keys(e).length===1&&e[t.textNodeName]!==void 0&&!t.alwaysCreateTextNode?e=e[t.textNodeName]:Object.keys(e).length===0&&(t.alwaysCreateTextNode?e[t.textNodeName]=``:e=``),o[Mt]!==void 0&&typeof e==`object`&&e&&(e[Mt]=o[Mt]),i[s]!==void 0&&Object.prototype.hasOwnProperty.call(i,s)?(Array.isArray(i[s])||(i[s]=[i[s]]),i[s].push(e)):t.isArray(s,c,n)?i[s]=[e]:i[s]=e}}return typeof r==`string`?r.length>0&&(i[t.textNodeName]=r):r!==void 0&&(i[t.textNodeName]=r),i}function propName$1(e){let t=Object.keys(e);for(let e=0;e<t.length;e++){let n=t[e];if(n!==`:@`)return n}}e(propName$1,`propName`);function assignAttributes(e,t,n,r){if(t){let i=Object.keys(t),a=i.length;for(let o=0;o<a;o++){let a=i[o];r.isArray(a,n+`.`+a,!0,!0)?e[a]=[t[a]]:e[a]=t[a]}}}function isLeafTag(e,t){let{textNodeName:n}=t,r=Object.keys(e).length;return!!(r===0||r===1&&(e[n]||typeof e[n]==`boolean`||e[n]===0))}var XMLParser=class{constructor(e){this.externalEntities={},this.options=buildOptions(e)}parse(e,t){if(typeof e!=`string`&&e.toString)e=e.toString();else if(typeof e!=`string`)throw Error(`XML data is accepted in String or Bytes[] form.`);if(t){t===!0&&(t={});let n=validate(e,t);if(n!==!0)throw Error(`${n.err.msg}:${n.err.line}:${n.err.col}`)}let n=new OrderedObjParser(this.options);n.addExternalEntities(this.externalEntities);let r=n.parseXml(e);return this.options.preserveOrder||r===void 0?r:prettify(r,this.options)}addEntity(e,t){if(t.indexOf(`&`)!==-1)throw Error(`Entity value can't have '&'`);if(e.indexOf(`&`)!==-1||e.indexOf(`;`)!==-1)throw Error(`An entity must be set without '&' and ';'. Eg. use '#xD' for '
'`);if(t===`&`)throw Error(`An entity with value '&' is not permitted`);this.externalEntities[e]=t}static getMetaDataSymbol(){return XmlNode.getMetaDataSymbol()}},Expression=class{constructor(e,t={}){this.pattern=e,this.separator=t.separator||`.`,this.segments=this._parse(e),this._hasDeepWildcard=this.segments.some(e=>e.type===`deep-wildcard`),this._hasAttributeCondition=this.segments.some(e=>e.attrName!==void 0),this._hasPositionSelector=this.segments.some(e=>e.position!==void 0)}_parse(e){let t=[],n=0,r=``;for(;n<e.length;)e[n]===this.separator?n+1<e.length&&e[n+1]===this.separator?(r.trim()&&(t.push(this._parseSegment(r.trim())),r=``),t.push({type:`deep-wildcard`}),n+=2):(r.trim()&&t.push(this._parseSegment(r.trim())),r=``,n++):(r+=e[n],n++);return r.trim()&&t.push(this._parseSegment(r.trim())),t}_parseSegment(e){let t={type:`tag`},n=null,r=e,i=e.match(/^([^\[]+)(\[[^\]]*\])(.*)$/);if(i&&(r=i[1]+i[3],i[2])){let e=i[2].slice(1,-1);e&&(n=e)}let a,o=r;if(r.includes(`::`)){let t=r.indexOf(`::`);if(a=r.substring(0,t).trim(),o=r.substring(t+2).trim(),!a)throw Error(`Invalid namespace in pattern: ${e}`)}let s,c=null;if(o.includes(`:`)){let e=o.lastIndexOf(`:`),t=o.substring(0,e).trim(),n=o.substring(e+1).trim();[`first`,`last`,`odd`,`even`].includes(n)||/^nth\(\d+\)$/.test(n)?(s=t,c=n):s=o}else s=o;if(!s)throw Error(`Invalid segment pattern: ${e}`);if(t.tag=s,a&&(t.namespace=a),n)if(n.includes(`=`)){let e=n.indexOf(`=`);t.attrName=n.substring(0,e).trim(),t.attrValue=n.substring(e+1).trim()}else t.attrName=n.trim();if(c){let e=c.match(/^nth\((\d+)\)$/);e?(t.position=`nth`,t.positionValue=parseInt(e[1],10)):t.position=c}return t}get length(){return this.segments.length}hasDeepWildcard(){return this._hasDeepWildcard}hasAttributeCondition(){return this._hasAttributeCondition}hasPositionSelector(){return this._hasPositionSelector}toString(){return this.pattern}},Matcher=class{constructor(e={}){this.separator=e.separator||`.`,this.path=[],this.siblingStacks=[]}push(e,t=null,n=null){if(this.path.length>0){let e=this.path[this.path.length-1];e.values=void 0}let r=this.path.length;this.siblingStacks[r]||(this.siblingStacks[r]=new Map);let i=this.siblingStacks[r],a=n?`${n}:${e}`:e,o=i.get(a)||0,s=0;for(let e of i.values())s+=e;i.set(a,o+1);let c={tag:e,position:s,counter:o};n!=null&&(c.namespace=n),t!=null&&(c.values=t),this.path.push(c)}pop(){if(this.path.length===0)return;let e=this.path.pop();return this.siblingStacks.length>this.path.length+1&&(this.siblingStacks.length=this.path.length+1),e}updateCurrent(e){if(this.path.length>0){let t=this.path[this.path.length-1];e!=null&&(t.values=e)}}getCurrentTag(){return this.path.length>0?this.path[this.path.length-1].tag:void 0}getCurrentNamespace(){return this.path.length>0?this.path[this.path.length-1].namespace:void 0}getAttrValue(e){if(this.path.length!==0)return this.path[this.path.length-1].values?.[e]}hasAttr(e){if(this.path.length===0)return!1;let t=this.path[this.path.length-1];return t.values!==void 0&&e in t.values}getPosition(){return this.path.length===0?-1:this.path[this.path.length-1].position??0}getCounter(){return this.path.length===0?-1:this.path[this.path.length-1].counter??0}getIndex(){return this.getPosition()}getDepth(){return this.path.length}toString(e,t=!0){let n=e||this.separator;return this.path.map(e=>t&&e.namespace?`${e.namespace}:${e.tag}`:e.tag).join(n)}toArray(){return this.path.map(e=>e.tag)}reset(){this.path=[],this.siblingStacks=[]}matches(e){let t=e.segments;return t.length===0?!1:e.hasDeepWildcard()?this._matchWithDeepWildcard(t):this._matchSimple(t)}_matchSimple(e){if(this.path.length!==e.length)return!1;for(let t=0;t<e.length;t++){let n=e[t],r=this.path[t],i=t===this.path.length-1;if(!this._matchSegment(n,r,i))return!1}return!0}_matchWithDeepWildcard(e){let t=this.path.length-1,n=e.length-1;for(;n>=0&&t>=0;){let r=e[n];if(r.type===`deep-wildcard`){if(n--,n<0)return!0;let r=e[n],i=!1;for(let e=t;e>=0;e--){let a=e===this.path.length-1;if(this._matchSegment(r,this.path[e],a)){t=e-1,n--,i=!0;break}}if(!i)return!1}else{let e=t===this.path.length-1;if(!this._matchSegment(r,this.path[t],e))return!1;t--,n--}}return n<0}_matchSegment(e,t,n){if(e.tag!==`*`&&e.tag!==t.tag||e.namespace!==void 0&&e.namespace!==`*`&&e.namespace!==t.namespace)return!1;if(e.attrName!==void 0){if(!n||!t.values||!(e.attrName in t.values))return!1;if(e.attrValue!==void 0){let n=t.values[e.attrName];if(String(n)!==String(e.attrValue))return!1}}if(e.position!==void 0){if(!n)return!1;let r=t.counter??0;if(e.position===`first`&&r!==0||e.position===`odd`&&r%2!=1||e.position===`even`&&r%2!=0||e.position===`nth`&&r!==e.positionValue)return!1}return!0}snapshot(){return{path:this.path.map(e=>({...e})),siblingStacks:this.siblingStacks.map(e=>new Map(e))}}restore(e){this.path=e.path.map(e=>({...e})),this.siblingStacks=e.siblingStacks.map(e=>new Map(e))}};function toXml(e,t){let n=``;t.format&&t.indentBy.length>0&&(n=`
|
|
175
|
+
`);let r=[];if(t.stopNodes&&Array.isArray(t.stopNodes))for(let e=0;e<t.stopNodes.length;e++){let n=t.stopNodes[e];typeof n==`string`?r.push(new Expression(n)):n instanceof Expression&&r.push(n)}let i=new Matcher;return arrToStr(e,t,n,i,r)}function arrToStr(e,t,n,r,i){let a=``,o=!1;if(!Array.isArray(e)){if(e!=null){let n=e.toString();return n=replaceEntitiesValue(n,t),n}return``}for(let s=0;s<e.length;s++){let c=e[s],l=propName(c);if(l===void 0)continue;let u=extractAttributeValues(c[`:@`],t);r.push(l,u);let d=checkStopNode(r,i);if(l===t.textNodeName){let e=c[l];d||(e=t.tagValueProcessor(l,e),e=replaceEntitiesValue(e,t)),o&&(a+=n),a+=e,o=!1,r.pop();continue}else if(l===t.cdataPropName){o&&(a+=n),a+=`<![CDATA[${c[l][0][t.textNodeName]}]]>`,o=!1,r.pop();continue}else if(l===t.commentPropName){a+=n+`<!--${c[l][0][t.textNodeName]}-->`,o=!0,r.pop();continue}else if(l[0]===`?`){let e=attr_to_str(c[`:@`],t,d),i=l===`?xml`?``:n,s=c[l][0][t.textNodeName];s=s.length===0?``:` `+s,a+=i+`<${l}${s}${e}?>`,o=!0,r.pop();continue}let f=n;f!==``&&(f+=t.indentBy);let p=n+`<${l}${attr_to_str(c[`:@`],t,d)}`,m;m=d?getRawContent(c[l],t):arrToStr(c[l],t,f,r,i),t.unpairedTags.indexOf(l)===-1?(!m||m.length===0)&&t.suppressEmptyNode?a+=p+`/>`:m&&m.endsWith(`>`)?a+=p+`>${m}${n}</${l}>`:(a+=p+`>`,m&&n!==``&&(m.includes(`/>`)||m.includes(`</`))?a+=n+t.indentBy+m+n:a+=m,a+=`</${l}>`):t.suppressUnpairedNode?a+=p+`>`:a+=p+`/>`,o=!0,r.pop()}return a}function extractAttributeValues(e,t){if(!e||t.ignoreAttributes)return null;let n={},r=!1;for(let i in e){if(!Object.prototype.hasOwnProperty.call(e,i))continue;let a=i.startsWith(t.attributeNamePrefix)?i.substr(t.attributeNamePrefix.length):i;n[a]=e[i],r=!0}return r?n:null}function getRawContent(e,t){if(!Array.isArray(e))return e==null?``:e.toString();let n=``;for(let r=0;r<e.length;r++){let i=e[r],a=propName(i);if(a===t.textNodeName)n+=i[a];else if(a===t.cdataPropName)n+=i[a][0][t.textNodeName];else if(a===t.commentPropName)n+=i[a][0][t.textNodeName];else if(a&&a[0]===`?`)continue;else if(a){let e=attr_to_str_raw(i[`:@`],t),r=getRawContent(i[a],t);!r||r.length===0?n+=`<${a}${e}/>`:n+=`<${a}${e}>${r}</${a}>`}}return n}function attr_to_str_raw(e,t){let n=``;if(e&&!t.ignoreAttributes)for(let r in e){if(!Object.prototype.hasOwnProperty.call(e,r))continue;let i=e[r];i===!0&&t.suppressBooleanAttributes?n+=` ${r.substr(t.attributeNamePrefix.length)}`:n+=` ${r.substr(t.attributeNamePrefix.length)}="${i}"`}return n}function propName(e){let t=Object.keys(e);for(let n=0;n<t.length;n++){let r=t[n];if(Object.prototype.hasOwnProperty.call(e,r)&&r!==`:@`)return r}}function attr_to_str(e,t,n){let r=``;if(e&&!t.ignoreAttributes)for(let i in e){if(!Object.prototype.hasOwnProperty.call(e,i))continue;let a;n?a=e[i]:(a=t.attributeValueProcessor(i,e[i]),a=replaceEntitiesValue(a,t)),a===!0&&t.suppressBooleanAttributes?r+=` ${i.substr(t.attributeNamePrefix.length)}`:r+=` ${i.substr(t.attributeNamePrefix.length)}="${a}"`}return r}function checkStopNode(e,t){if(!t||t.length===0)return!1;for(let n=0;n<t.length;n++)if(e.matches(t[n]))return!0;return!1}function replaceEntitiesValue(e,t){if(e&&e.length>0&&t.processEntities)for(let n=0;n<t.entities.length;n++){let r=t.entities[n];e=e.replace(r.regex,r.val)}return e}function getIgnoreAttributesFn(e){return typeof e==`function`?e:Array.isArray(e)?t=>{for(let n of e)if(typeof n==`string`&&t===n||n instanceof RegExp&&n.test(t))return!0}:()=>!1}const Nt={attributeNamePrefix:`@_`,attributesGroupName:!1,textNodeName:`#text`,ignoreAttributes:!0,cdataPropName:!1,format:!1,indentBy:` `,suppressEmptyNode:!1,suppressUnpairedNode:!0,suppressBooleanAttributes:!0,tagValueProcessor:function(e,t){return t},attributeValueProcessor:function(e,t){return t},preserveOrder:!1,commentPropName:!1,unpairedTags:[],entities:[{regex:RegExp(`&`,`g`),val:`&`},{regex:RegExp(`>`,`g`),val:`>`},{regex:RegExp(`<`,`g`),val:`<`},{regex:RegExp(`'`,`g`),val:`'`},{regex:RegExp(`"`,`g`),val:`"`}],processEntities:!0,stopNodes:[],oneListGroup:!1,jPath:!0};function Builder(e){if(this.options=Object.assign({},Nt,e),this.options.stopNodes&&Array.isArray(this.options.stopNodes)&&(this.options.stopNodes=this.options.stopNodes.map(e=>typeof e==`string`&&e.startsWith(`*.`)?`..`+e.substring(2):e)),this.stopNodeExpressions=[],this.options.stopNodes&&Array.isArray(this.options.stopNodes))for(let e=0;e<this.options.stopNodes.length;e++){let t=this.options.stopNodes[e];typeof t==`string`?this.stopNodeExpressions.push(new Expression(t)):t instanceof Expression&&this.stopNodeExpressions.push(t)}this.options.ignoreAttributes===!0||this.options.attributesGroupName?this.isAttribute=function(){return!1}:(this.ignoreAttributesFn=getIgnoreAttributesFn(this.options.ignoreAttributes),this.attrPrefixLen=this.options.attributeNamePrefix.length,this.isAttribute=isAttribute),this.processTextOrObjNode=processTextOrObjNode,this.options.format?(this.indentate=indentate,this.tagEndChar=`>
|
|
176
176
|
`,this.newLine=`
|
|
177
|
-
`):(this.indentate=function(){return``},this.tagEndChar=`>`,this.newLine=``)}Builder.prototype.build=function(e){return this.options.preserveOrder?toXml(e,this.options):(Array.isArray(e)&&this.options.arrayNodeName&&this.options.arrayNodeName.length>1&&(e={[this.options.arrayNodeName]:e}),this.j2x(e,0,[]).val)},Builder.prototype.j2x=function(e,t,n){let r=``,i=``,a=n.join(`.`);for(let o in e)if(Object.prototype.hasOwnProperty.call(e,o))if(e[o]===void 0)this.isAttribute(o)&&(i+=``);else if(e[o]===null)this.isAttribute(o)||o===this.options.cdataPropName?i+=``:o[0]===`?`?i+=this.indentate(t)+`<`+o+`?`+this.tagEndChar:i+=this.indentate(t)+`<`+o+`/`+this.tagEndChar;else if(e[o]instanceof Date)i+=this.buildTextValNode(e[o],o,``,t);else if(typeof e[o]!=`object`){let n=this.isAttribute(o);if(n&&!this.ignoreAttributesFn(n,a))r+=this.buildAttrPairStr(n,``+e[o]);else if(!n)if(o===this.options.textNodeName){let t=this.options.tagValueProcessor(o,``+e[o]);i+=this.replaceEntitiesValue(t)}else i+=this.buildTextValNode(e[o],o,``,t)}else if(Array.isArray(e[o])){let r=e[o].length,a=``,s=``;for(let c=0;c<r;c++){let r=e[o][c];if(r!==void 0)if(r===null)o[0]===`?`?i+=this.indentate(t)+`<`+o+`?`+this.tagEndChar:i+=this.indentate(t)+`<`+o+`/`+this.tagEndChar;else if(typeof r==`object`)if(this.options.oneListGroup){let e=this.j2x(r,t+1,n.concat(o));a+=e.val,this.options.attributesGroupName&&r.hasOwnProperty(this.options.attributesGroupName)&&(s+=e.attrStr)}else a+=this.processTextOrObjNode(r,o,t,n);else if(this.options.oneListGroup){let e=this.options.tagValueProcessor(o,r);e=this.replaceEntitiesValue(e),a+=e}else a+=this.buildTextValNode(r,o,``,t)}this.options.oneListGroup&&(a=this.buildObjectNode(a,o,s,t)),i+=a}else if(this.options.attributesGroupName&&o===this.options.attributesGroupName){let t=Object.keys(e[o]),n=t.length;for(let i=0;i<n;i++)r+=this.buildAttrPairStr(t[i],``+e[o][t[i]])}else i+=this.processTextOrObjNode(e[o],o,t,n);return{attrStr:r,val:i}},Builder.prototype.buildAttrPairStr=function(e,t){return t=this.options.attributeValueProcessor(e,``+t),t=this.replaceEntitiesValue(t),this.options.suppressBooleanAttributes&&t===`true`?` `+e:` `+e+`="`+t+`"`};function processTextOrObjNode(e,t,n,r){let i=this.j2x(e,n+1,r.concat(t));return e[this.options.textNodeName]!==void 0&&Object.keys(e).length===1?this.buildTextValNode(e[this.options.textNodeName],t,i.attrStr,n):this.buildObjectNode(i.val,t,i.attrStr,n)}Builder.prototype.buildObjectNode=function(e,t,n,r){if(e===``)return t[0]===`?`?this.indentate(r)+`<`+t+n+`?`+this.tagEndChar:this.indentate(r)+`<`+t+n+this.closeTag(t)+this.tagEndChar;{let i=`</`+t+this.tagEndChar,a=``;return t[0]===`?`&&(a=`?`,i=``),(n||n===``)&&e.indexOf(`<`)===-1?this.indentate(r)+`<`+t+n+a+`>`+e+i:this.options.commentPropName!==!1&&t===this.options.commentPropName&&a.length===0?this.indentate(r)+`<!--${e}-->`+this.newLine:this.indentate(r)+`<`+t+n+a+this.tagEndChar+e+this.indentate(r)+i}},Builder.prototype.closeTag=function(e){let t=``;return this.options.unpairedTags.indexOf(e)===-1?t=this.options.suppressEmptyNode?`/`:`></${e}`:this.options.suppressUnpairedNode||(t=`/`),t},Builder.prototype.buildTextValNode=function(e,t,n,r){if(this.options.cdataPropName!==!1&&t===this.options.cdataPropName)return this.indentate(r)+`<![CDATA[${e}]]>`+this.newLine;if(this.options.commentPropName!==!1&&t===this.options.commentPropName)return this.indentate(r)+`<!--${e}-->`+this.newLine;if(t[0]===`?`)return this.indentate(r)+`<`+t+n+`?`+this.tagEndChar;{let i=this.options.tagValueProcessor(t,e);return i=this.replaceEntitiesValue(i),i===``?this.indentate(r)+`<`+t+n+this.closeTag(t)+this.tagEndChar:this.indentate(r)+`<`+t+n+`>`+i+`</`+t+this.tagEndChar}},Builder.prototype.replaceEntitiesValue=function(e){if(e&&e.length>0&&this.options.processEntities)for(let t=0;t<this.options.entities.length;t++){let n=this.options.entities[t];e=e.replace(n.regex,n.val)}return e};function indentate(e){return this.options.indentBy.repeat(e)}function isAttribute(e){return e.startsWith(this.options.attributeNamePrefix)&&e!==this.options.textNodeName?e.substr(this.attrPrefixLen):!1}const Pt={validate};var SoapClient=class{async performRequest({httpClient:e,url:t,method:n,headers:r,queryParams:i,body:a,customErrorConfigs:o,requestConfig:s}){let c;if(c=typeof s?.envelope==`string`?s.envelope:typeof s?.envelope==`object`?Ft.build(s.envelope):await buildEnvelope(a,s),Pt.validate(c,{allowBooleanAttributes:!0})!==!0)throw Error(`Invalid XML envelope`);let u,d={"Content-Type":`application/xml`,...r};s?.soapAction&&(d.SOAPAction=s.soapAction);try{u=await e?.request({method:n,url:t,headers:d,queryParams:i,maxRedirects:0,payload:c,requestConfig:s})}catch(e){if(l(e?.response))throw e;u=e.response}let f=It.parse(u.data),p=f.Envelope||f,m=p.Body||p,h=m.Fault;if(h)throw new me({...u,status:500,data:h,message:h.faultstring??h.faultcode??`SOAP Fault`},h.faultstring??`SOAP Fault occurred`);u.data=m;let g=translateCustomError(u,o);if(isFailedStatusCode(g?.status))throw new me(g,g.message);return g}};const Ft=new Builder({attributeNamePrefix:`@_`,ignoreAttributes:!1,suppressBooleanAttributes:!1}),It=new XMLParser({ignoreAttributes:!1,attributeNamePrefix:`_`,removeNSPrefix:!0,numberParseOptions:{leadingZeros:!1,hex:!1}}),buildEnvelope=async(e,t)=>{if(p(t?.envelope)){let e=typeof t.envelope==`string`?t.envelope:Ft.build(t.envelope);if(Pt.validate(e,{allowBooleanAttributes:!0})!==!0)throw Error(`Invalid XML envelope`);return e}let n=await buildSoapEnvelope(t,e),r=Ft.build(n);if(Pt.validate(r,{allowBooleanAttributes:!0})!==!0)throw Error(`Invalid XML envelope`);return r},buildSoapEnvelope=async(e,t)=>{let n=await Promise.all((e?.namespaces||[]).map(async e=>({identifier:await _(e.namespaceIdentifier),namespace:await _(e.namespace)})));n.forEach(({identifier:e,namespace:t})=>{if(l(e)||l(t)||e===``||t===``)throw Error(`Invalid namespace config: both identifier and namespace are required`)});let r=n.reduce((e,{identifier:t,namespace:n})=>(e[`@_xmlns:${t}`]=n,e),{});return{"soapenv:Envelope":{"soapenv:Header":await buildSoapHeaders(t,e??{}),"soapenv:Body":await buildSoapBody(t,e?.soapOperation??``,n[0]?.identifier??``),"@_xmlns:soapenv":`http://schemas.xmlsoap.org/soap/envelope/`,...r}}},buildSoapHeaders=async(e,t)=>[await buildSoapSecurity(e,t)],buildSoapSecurity=async(e,t)=>{if(l(t.soapContext))return{};let{username:n,password:r}=t.soapContext;return{"wsse:Security":{"wsse:UsernameToken":{"wsse:Username":n,"wsse:Password":{"#text":r,"@_Type":`http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-username-token-profile-1.0#PasswordText`}},"@_soapenv:mustUnderstand":`1`,"@_xmlns:wsse":`http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-secext-1.0.xsd`,"@_xmlns:wsu":`http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-utility-1.0.xsd`}}},buildSoapBody=async(e,t,n)=>{if(l(t))throw Error(`Missing soapOperation in config`);let r=expandArrayAttributes({[t]:e});return(Array.isArray(r)?r:[r]).map(e=>applyNamespace(e,n))},expandArrayAttributes=e=>{if(typeof e!=`object`||!e)return e;if(Array.isArray(e)){if(e.length===1){let t=e[0];if(typeof t==`object`&&t&&!Array.isArray(t)){let e=Object.keys(t).filter(e=>!e.startsWith(`@_`));if(e.length===1){let n=e[0],r=t[n];if(typeof r==`object`&&r&&!Array.isArray(r)){let e=Object.keys(r),t=e.filter(e=>e.startsWith(`@_`)),i=e.filter(e=>!e.startsWith(`@_`)),a=t.find(e=>Array.isArray(r[e]));if(a&&i.length===0){let e=r[a],i=t.filter(e=>e!==a),o=e.map(e=>{let t={[a]:e};for(let e of i)t[e]=r[e];return t});return{[n]:o}}}}}}return e.map(e=>expandArrayAttributes(e))}let t={};for(let n of Object.keys(e)){let r=e[n];t[n]=expandArrayAttributes(r)}return t},applyNamespace=(e,t)=>{if(typeof e!=`object`)return e;if(Array.isArray(e))return e.map(e=>applyNamespace(e,t));let n={};for(let r in e){let i=applyNamespaceToKey(r,t);n[i]=applyNamespace(e[r],t)}return n},applyNamespaceToKey=(e,t)=>{let n=e.split(`:`);return n.length>1&&n[0]||e.indexOf(`${t}:`)===0||e===`#text`?e:e.startsWith(`@_`)?`@_${t}:${e.slice(2)}`:`${t}:${e}`};var RequestClientFactory=class{static build(e=`rest`){if(e===`rest`)return new RestClient;if(e===`soap`)return new SoapClient;throw Error(`Unknown request client type: ${e}`)}};export{pe as CUSTOM_ERROR_CONFIG_SCHEMA,ConcurrencyManager,EventClient,HttpClient,HttpClientManager,fe as HttpErrorMessages,ht as HttpMethods,me as HttpResponseError,HttpTransportFactory,he as InstanceManager,LockManager,MemoryStore,yt as QueryArrayFormats,QueueManager,RateLimitManager,ee as RedisClient,RequestClientFactory,vt as RequestParameterLocations,ScriptManager,SubscriptionManager,buildHttpClientInstance,convertError,createAuthorizationHeaders,getRetryAfterWaitTime,getTransportInstance,getTransportManagers,initializeTransportSystem,isFailedStatusCode,isInfoStatusCode,isSuccessStatusCode,isTransportSystemReady,parseRequestParameters,serializeHttpResponseError,shutdownTransportSystem,superNormalizeHeaders,translateCustomError};
|
|
177
|
+
`):(this.indentate=function(){return``},this.tagEndChar=`>`,this.newLine=``)}Builder.prototype.build=function(e){if(this.options.preserveOrder)return toXml(e,this.options);{Array.isArray(e)&&this.options.arrayNodeName&&this.options.arrayNodeName.length>1&&(e={[this.options.arrayNodeName]:e});let t=new Matcher;return this.j2x(e,0,t).val}},Builder.prototype.j2x=function(e,t,n){let r=``,i=``,a=this.options.jPath?n.toString():n,o=this.checkStopNode(n);for(let s in e)if(Object.prototype.hasOwnProperty.call(e,s))if(e[s]===void 0)this.isAttribute(s)&&(i+=``);else if(e[s]===null)this.isAttribute(s)||s===this.options.cdataPropName?i+=``:s[0]===`?`?i+=this.indentate(t)+`<`+s+`?`+this.tagEndChar:i+=this.indentate(t)+`<`+s+`/`+this.tagEndChar;else if(e[s]instanceof Date)i+=this.buildTextValNode(e[s],s,``,t,n);else if(typeof e[s]!=`object`){let c=this.isAttribute(s);if(c&&!this.ignoreAttributesFn(c,a))r+=this.buildAttrPairStr(c,``+e[s],o);else if(!c)if(s===this.options.textNodeName){let t=this.options.tagValueProcessor(s,``+e[s]);i+=this.replaceEntitiesValue(t)}else{n.push(s);let r=this.checkStopNode(n);if(n.pop(),r){let n=``+e[s];n===``?i+=this.indentate(t)+`<`+s+this.closeTag(s)+this.tagEndChar:i+=this.indentate(t)+`<`+s+`>`+n+`</`+s+this.tagEndChar}else i+=this.buildTextValNode(e[s],s,``,t,n)}}else if(Array.isArray(e[s])){let r=e[s].length,a=``,o=``;for(let c=0;c<r;c++){let r=e[s][c];if(r!==void 0)if(r===null)s[0]===`?`?i+=this.indentate(t)+`<`+s+`?`+this.tagEndChar:i+=this.indentate(t)+`<`+s+`/`+this.tagEndChar;else if(typeof r==`object`)if(this.options.oneListGroup){n.push(s);let e=this.j2x(r,t+1,n);n.pop(),a+=e.val,this.options.attributesGroupName&&r.hasOwnProperty(this.options.attributesGroupName)&&(o+=e.attrStr)}else a+=this.processTextOrObjNode(r,s,t,n);else if(this.options.oneListGroup){let e=this.options.tagValueProcessor(s,r);e=this.replaceEntitiesValue(e),a+=e}else{n.push(s);let e=this.checkStopNode(n);if(n.pop(),e){let e=``+r;e===``?a+=this.indentate(t)+`<`+s+this.closeTag(s)+this.tagEndChar:a+=this.indentate(t)+`<`+s+`>`+e+`</`+s+this.tagEndChar}else a+=this.buildTextValNode(r,s,``,t,n)}}this.options.oneListGroup&&(a=this.buildObjectNode(a,s,o,t)),i+=a}else if(this.options.attributesGroupName&&s===this.options.attributesGroupName){let t=Object.keys(e[s]),n=t.length;for(let i=0;i<n;i++)r+=this.buildAttrPairStr(t[i],``+e[s][t[i]],o)}else i+=this.processTextOrObjNode(e[s],s,t,n);return{attrStr:r,val:i}},Builder.prototype.buildAttrPairStr=function(e,t,n){return n||(t=this.options.attributeValueProcessor(e,``+t),t=this.replaceEntitiesValue(t)),this.options.suppressBooleanAttributes&&t===`true`?` `+e:` `+e+`="`+t+`"`};function processTextOrObjNode(e,t,n,r){let i=this.extractAttributes(e);if(r.push(t,i),this.checkStopNode(r)){let i=this.buildRawContent(e),a=this.buildAttributesForStopNode(e);return r.pop(),this.buildObjectNode(i,t,a,n)}let a=this.j2x(e,n+1,r);return r.pop(),e[this.options.textNodeName]!==void 0&&Object.keys(e).length===1?this.buildTextValNode(e[this.options.textNodeName],t,a.attrStr,n,r):this.buildObjectNode(a.val,t,a.attrStr,n)}Builder.prototype.extractAttributes=function(e){if(!e||typeof e!=`object`)return null;let t={},n=!1;if(this.options.attributesGroupName&&e[this.options.attributesGroupName]){let r=e[this.options.attributesGroupName];for(let e in r){if(!Object.prototype.hasOwnProperty.call(r,e))continue;let i=e.startsWith(this.options.attributeNamePrefix)?e.substring(this.options.attributeNamePrefix.length):e;t[i]=r[e],n=!0}}else for(let r in e){if(!Object.prototype.hasOwnProperty.call(e,r))continue;let i=this.isAttribute(r);i&&(t[i]=e[r],n=!0)}return n?t:null},Builder.prototype.buildRawContent=function(e){if(typeof e==`string`)return e;if(typeof e!=`object`||!e)return String(e);if(e[this.options.textNodeName]!==void 0)return e[this.options.textNodeName];let t=``;for(let n in e){if(!Object.prototype.hasOwnProperty.call(e,n)||this.isAttribute(n)||this.options.attributesGroupName&&n===this.options.attributesGroupName)continue;let r=e[n];if(n===this.options.textNodeName)t+=r;else if(Array.isArray(r)){for(let e of r)if(typeof e==`string`||typeof e==`number`)t+=`<${n}>${e}</${n}>`;else if(typeof e==`object`&&e){let r=this.buildRawContent(e),i=this.buildAttributesForStopNode(e);r===``?t+=`<${n}${i}/>`:t+=`<${n}${i}>${r}</${n}>`}}else if(typeof r==`object`&&r){let e=this.buildRawContent(r),i=this.buildAttributesForStopNode(r);e===``?t+=`<${n}${i}/>`:t+=`<${n}${i}>${e}</${n}>`}else t+=`<${n}>${r}</${n}>`}return t},Builder.prototype.buildAttributesForStopNode=function(e){if(!e||typeof e!=`object`)return``;let t=``;if(this.options.attributesGroupName&&e[this.options.attributesGroupName]){let n=e[this.options.attributesGroupName];for(let e in n){if(!Object.prototype.hasOwnProperty.call(n,e))continue;let r=e.startsWith(this.options.attributeNamePrefix)?e.substring(this.options.attributeNamePrefix.length):e,i=n[e];i===!0&&this.options.suppressBooleanAttributes?t+=` `+r:t+=` `+r+`="`+i+`"`}}else for(let n in e){if(!Object.prototype.hasOwnProperty.call(e,n))continue;let r=this.isAttribute(n);if(r){let i=e[n];i===!0&&this.options.suppressBooleanAttributes?t+=` `+r:t+=` `+r+`="`+i+`"`}}return t},Builder.prototype.buildObjectNode=function(e,t,n,r){if(e===``)return t[0]===`?`?this.indentate(r)+`<`+t+n+`?`+this.tagEndChar:this.indentate(r)+`<`+t+n+this.closeTag(t)+this.tagEndChar;{let i=`</`+t+this.tagEndChar,a=``;return t[0]===`?`&&(a=`?`,i=``),(n||n===``)&&e.indexOf(`<`)===-1?this.indentate(r)+`<`+t+n+a+`>`+e+i:this.options.commentPropName!==!1&&t===this.options.commentPropName&&a.length===0?this.indentate(r)+`<!--${e}-->`+this.newLine:this.indentate(r)+`<`+t+n+a+this.tagEndChar+e+this.indentate(r)+i}},Builder.prototype.closeTag=function(e){let t=``;return this.options.unpairedTags.indexOf(e)===-1?t=this.options.suppressEmptyNode?`/`:`></${e}`:this.options.suppressUnpairedNode||(t=`/`),t},Builder.prototype.checkStopNode=function(e){if(!this.stopNodeExpressions||this.stopNodeExpressions.length===0)return!1;for(let t=0;t<this.stopNodeExpressions.length;t++)if(e.matches(this.stopNodeExpressions[t]))return!0;return!1},Builder.prototype.buildTextValNode=function(e,t,n,r,i){if(this.options.cdataPropName!==!1&&t===this.options.cdataPropName)return this.indentate(r)+`<![CDATA[${e}]]>`+this.newLine;if(this.options.commentPropName!==!1&&t===this.options.commentPropName)return this.indentate(r)+`<!--${e}-->`+this.newLine;if(t[0]===`?`)return this.indentate(r)+`<`+t+n+`?`+this.tagEndChar;{let i=this.options.tagValueProcessor(t,e);return i=this.replaceEntitiesValue(i),i===``?this.indentate(r)+`<`+t+n+this.closeTag(t)+this.tagEndChar:this.indentate(r)+`<`+t+n+`>`+i+`</`+t+this.tagEndChar}},Builder.prototype.replaceEntitiesValue=function(e){if(e&&e.length>0&&this.options.processEntities)for(let t=0;t<this.options.entities.length;t++){let n=this.options.entities[t];e=e.replace(n.regex,n.val)}return e};function indentate(e){return this.options.indentBy.repeat(e)}function isAttribute(e){return e.startsWith(this.options.attributeNamePrefix)&&e!==this.options.textNodeName?e.substr(this.attrPrefixLen):!1}var Pt=Builder;const Ft={validate};var SoapClient=class{async performRequest({httpClient:e,url:t,method:n,headers:r,queryParams:i,body:a,customErrorConfigs:o,requestConfig:s}){let c;if(c=typeof s?.envelope==`string`?s.envelope:typeof s?.envelope==`object`?It.build(s.envelope):await buildEnvelope(a,s),Ft.validate(c,{allowBooleanAttributes:!0})!==!0)throw Error(`Invalid XML envelope`);let u,d={"Content-Type":`application/xml`,...r};s?.soapAction&&(d.SOAPAction=s.soapAction);try{u=await e?.request({method:n,url:t,headers:d,queryParams:i,maxRedirects:0,payload:c,requestConfig:s})}catch(e){if(l(e?.response))throw e;u=e.response}let f=Lt.parse(u.data),p=f.Envelope||f,m=p.Body||p,h=m.Fault;if(h)throw new me({...u,status:500,data:h,message:h.faultstring??h.faultcode??`SOAP Fault`},h.faultstring??`SOAP Fault occurred`);u.data=m;let g=translateCustomError(u,o);if(isFailedStatusCode(g?.status))throw new me(g,g.message);return g}};const It=new Pt({attributeNamePrefix:`@_`,ignoreAttributes:!1,suppressBooleanAttributes:!1}),Lt=new XMLParser({ignoreAttributes:!1,attributeNamePrefix:`_`,removeNSPrefix:!0,numberParseOptions:{leadingZeros:!1,hex:!1}}),buildEnvelope=async(e,t)=>{if(p(t?.envelope)){let e=typeof t.envelope==`string`?t.envelope:It.build(t.envelope);if(Ft.validate(e,{allowBooleanAttributes:!0})!==!0)throw Error(`Invalid XML envelope`);return e}let n=await buildSoapEnvelope(t,e),r=It.build(n);if(Ft.validate(r,{allowBooleanAttributes:!0})!==!0)throw Error(`Invalid XML envelope`);return r},buildSoapEnvelope=async(e,t)=>{let n=await Promise.all((e?.namespaces||[]).map(async e=>({identifier:await _(e.namespaceIdentifier),namespace:await _(e.namespace)})));n.forEach(({identifier:e,namespace:t})=>{if(l(e)||l(t)||e===``||t===``)throw Error(`Invalid namespace config: both identifier and namespace are required`)});let r=n.reduce((e,{identifier:t,namespace:n})=>(e[`@_xmlns:${t}`]=n,e),{});return{"soapenv:Envelope":{"soapenv:Header":await buildSoapHeaders(t,e??{}),"soapenv:Body":await buildSoapBody(t,e?.soapOperation??``,n[0]?.identifier??``),"@_xmlns:soapenv":`http://schemas.xmlsoap.org/soap/envelope/`,...r}}},buildSoapHeaders=async(e,t)=>[await buildSoapSecurity(e,t)],buildSoapSecurity=async(e,t)=>{if(l(t.soapContext))return{};let{username:n,password:r}=t.soapContext;return{"wsse:Security":{"wsse:UsernameToken":{"wsse:Username":n,"wsse:Password":{"#text":r,"@_Type":`http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-username-token-profile-1.0#PasswordText`}},"@_soapenv:mustUnderstand":`1`,"@_xmlns:wsse":`http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-secext-1.0.xsd`,"@_xmlns:wsu":`http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-utility-1.0.xsd`}}},buildSoapBody=async(e,t,n)=>{if(l(t))throw Error(`Missing soapOperation in config`);let r=expandArrayAttributes({[t]:e});return(Array.isArray(r)?r:[r]).map(e=>applyNamespace(e,n))},expandArrayAttributes=e=>{if(typeof e!=`object`||!e)return e;if(Array.isArray(e)){if(e.length===1){let t=e[0];if(typeof t==`object`&&t&&!Array.isArray(t)){let e=Object.keys(t).filter(e=>!e.startsWith(`@_`));if(e.length===1){let n=e[0],r=t[n];if(typeof r==`object`&&r&&!Array.isArray(r)){let e=Object.keys(r),t=e.filter(e=>e.startsWith(`@_`)),i=e.filter(e=>!e.startsWith(`@_`)),a=t.find(e=>Array.isArray(r[e]));if(a&&i.length===0){let e=r[a],i=t.filter(e=>e!==a),o=e.map(e=>{let t={[a]:e};for(let e of i)t[e]=r[e];return t});return{[n]:o}}}}}}return e.map(e=>expandArrayAttributes(e))}let t={};for(let n of Object.keys(e)){let r=e[n];t[n]=expandArrayAttributes(r)}return t},applyNamespace=(e,t)=>{if(typeof e!=`object`)return e;if(Array.isArray(e))return e.map(e=>applyNamespace(e,t));let n={};for(let r in e){let i=applyNamespaceToKey(r,t);n[i]=applyNamespace(e[r],t)}return n},applyNamespaceToKey=(e,t)=>{let n=e.split(`:`);return n.length>1&&n[0]||e.indexOf(`${t}:`)===0||e===`#text`?e:e.startsWith(`@_`)?`@_${t}:${e.slice(2)}`:`${t}:${e}`};var RequestClientFactory=class{static build(e=`rest`){if(e===`rest`)return new RestClient;if(e===`soap`)return new SoapClient;throw Error(`Unknown request client type: ${e}`)}};export{pe as CUSTOM_ERROR_CONFIG_SCHEMA,ConcurrencyManager,EventClient,HttpClient,HttpClientManager,fe as HttpErrorMessages,ht as HttpMethods,me as HttpResponseError,HttpTransportFactory,he as InstanceManager,LockManager,MemoryStore,yt as QueryArrayFormats,QueueManager,RateLimitManager,ee as RedisClient,RequestClientFactory,vt as RequestParameterLocations,ScriptManager,SubscriptionManager,buildHttpClientInstance,convertError,createAuthorizationHeaders,getRetryAfterWaitTime,getTransportInstance,getTransportManagers,initializeTransportSystem,isFailedStatusCode,isInfoStatusCode,isSuccessStatusCode,isTransportSystemReady,parseRequestParameters,serializeHttpResponseError,shutdownTransportSystem,superNormalizeHeaders,translateCustomError};
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@stackone/transport",
|
|
3
|
-
"version": "2.
|
|
3
|
+
"version": "2.14.1",
|
|
4
4
|
"description": "",
|
|
5
5
|
"main": "dist/index.cjs",
|
|
6
6
|
"module": "dist/index.mjs",
|
|
@@ -45,7 +45,7 @@
|
|
|
45
45
|
"@stackone/logger": "*",
|
|
46
46
|
"@stackone/redaction": "*",
|
|
47
47
|
"@stackone/utils": "*",
|
|
48
|
-
"axios": "1.
|
|
48
|
+
"axios": "1.13.6",
|
|
49
49
|
"jsonpath-plus": "10.3.0",
|
|
50
50
|
"qs": "6.14.1",
|
|
51
51
|
"redis": "4.7.1"
|