@smartledger/bsv 9.22.0 → 9.23.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +95 -0
- package/README.md +19 -19
- package/bsv-gdaf.min.js +3 -3
- package/bsv-ltp.min.js +29 -29
- package/bsv-smartcontract.min.js +1 -1
- package/bsv.bundle.js +3 -3
- package/bsv.d.ts +5 -5
- package/bsv.min.js +3 -3
- package/docs/AUDIT_SCOPE.md +6 -6
- package/docs/MODULE_REFERENCE_COMPLETE.md +27 -27
- package/docs/advanced/UTXO_MANAGER_GUIDE.md +1 -1
- package/docs/audit-rfq/cure53.txt +1 -1
- package/docs/audit-rfq/ncc-group.txt +1 -1
- package/docs/audit-rfq/trail-of-bits.txt +1 -1
- package/docs/getting-started/INSTALLATION.md +23 -23
- package/docs/getting-started/QUICK_START.md +7 -7
- package/docs/migration/FROM_BSV_1_5_6.md +5 -5
- package/lib/gdaf/index.js +14 -14
- package/lib/transaction/sighash.js +33 -3
- package/lib/transaction/transaction.js +47 -7
- package/package.json +1 -1
- package/version.js +1 -1
package/bsv.bundle.js
CHANGED
|
@@ -8,7 +8,7 @@ var bsv=(()=>{var qH=Object.create;var Df=Object.defineProperty;var UH=Object.ge
|
|
|
8
8
|
`)>=0&&i++,o+a.replace(/\u001b\[\d\d?m/g,"").length+1},0);return n>60?r[0]+(t===""?"":t+`
|
|
9
9
|
`)+" "+e.join(`,
|
|
10
10
|
`)+" "+r[1]:r[0]+t+" "+e.join(", ")+" "+r[1]}Qe.types=CO();function qO(e){return Array.isArray(e)}Qe.isArray=qO;function Z0(e){return typeof e=="boolean"}Qe.isBoolean=Z0;function Jd(e){return e===null}Qe.isNull=Jd;function i8(e){return e==null}Qe.isNullOrUndefined=i8;function UO(e){return typeof e=="number"}Qe.isNumber=UO;function Qd(e){return typeof e=="string"}Qe.isString=Qd;function n8(e){return typeof e=="symbol"}Qe.isSymbol=n8;function Ls(e){return e===void 0}Qe.isUndefined=Ls;function Yf(e){return ec(e)&&$0(e)==="[object RegExp]"}Qe.isRegExp=Yf;Qe.types.isRegExp=Yf;function ec(e){return typeof e=="object"&&e!==null}Qe.isObject=ec;function Xd(e){return ec(e)&&$0(e)==="[object Date]"}Qe.isDate=Xd;Qe.types.isDate=Xd;function Zf(e){return ec(e)&&($0(e)==="[object Error]"||e instanceof Error)}Qe.isError=Zf;Qe.types.isNativeError=Zf;function Zd(e){return typeof e=="function"}Qe.isFunction=Zd;function o8(e){return e===null||typeof e=="boolean"||typeof e=="number"||typeof e=="string"||typeof e=="symbol"||typeof e>"u"}Qe.isPrimitive=o8;Qe.isBuffer=MO();function $0(e){return Object.prototype.toString.call(e)}function W0(e){return e<10?"0"+e.toString(10):e.toString(10)}var a8=["Jan","Feb","Mar","Apr","May","Jun","Jul","Aug","Sep","Oct","Nov","Dec"];function s8(){var e=new Date,t=[W0(e.getHours()),W0(e.getMinutes()),W0(e.getSeconds())].join(":");return[e.getDate(),a8[e.getMonth()],t].join(" ")}Qe.log=function(){console.log("%s - %s",s8(),Qe.format.apply(Qe,arguments))};Qe.inherits=Rt();Qe._extend=function(e,t){if(!t||!ec(t))return e;for(var r=Object.keys(t),i=r.length;i--;)e[r[i]]=t[r[i]];return e};function FO(e,t){return Object.prototype.hasOwnProperty.call(e,t)}var Cs=typeof Symbol<"u"?Symbol("util.promisify.custom"):void 0;Qe.promisify=function(t){if(typeof t!="function")throw new TypeError('The "original" argument must be of type Function');if(Cs&&t[Cs]){var r=t[Cs];if(typeof r!="function")throw new TypeError('The "util.promisify.custom" argument must be of type Function');return Object.defineProperty(r,Cs,{value:r,enumerable:!1,writable:!1,configurable:!0}),r}function r(){for(var i,n,o=new Promise(function(u,c){i=u,n=c}),a=[],s=0;s<arguments.length;s++)a.push(arguments[s]);a.push(function(u,c){u?n(u):i(c)});try{t.apply(this,a)}catch(u){n(u)}return o}return Object.setPrototypeOf(r,Object.getPrototypeOf(t)),Cs&&Object.defineProperty(r,Cs,{value:r,enumerable:!1,writable:!1,configurable:!0}),Object.defineProperties(r,DO(t))};Qe.promisify.custom=Cs;function u8(e,t){if(!e){var r=new Error("Promise was rejected with a falsy value");r.reason=e,e=r}return t(e)}function c8(e){if(typeof e!="function")throw new TypeError('The "original" argument must be of type Function');function t(){for(var r=[],i=0;i<arguments.length;i++)r.push(arguments[i]);var n=r.pop();if(typeof n!="function")throw new TypeError("The last argument must be of type Function");var o=this,a=function(){return n.apply(o,arguments)};e.apply(this,r).then(function(s){b.default.nextTick(a.bind(null,null,s))},function(s){b.default.nextTick(u8.bind(null,s,a))})}return Object.setPrototypeOf(t,Object.getPrototypeOf(e)),Object.defineProperties(t,DO(e)),t}Qe.callbackify=c8});var WO=T((Pre,GO)=>{"use strict";g();function jO(e,t){var r=Object.keys(e);if(Object.getOwnPropertySymbols){var i=Object.getOwnPropertySymbols(e);t&&(i=i.filter(function(n){return Object.getOwnPropertyDescriptor(e,n).enumerable})),r.push.apply(r,i)}return r}function zO(e){for(var t=1;t<arguments.length;t++){var r=arguments[t]!=null?arguments[t]:{};t%2?jO(Object(r),!0).forEach(function(i){f8(e,i,r[i])}):Object.getOwnPropertyDescriptors?Object.defineProperties(e,Object.getOwnPropertyDescriptors(r)):jO(Object(r)).forEach(function(i){Object.defineProperty(e,i,Object.getOwnPropertyDescriptor(r,i))})}return e}function f8(e,t,r){return t=VO(t),t in e?Object.defineProperty(e,t,{value:r,enumerable:!0,configurable:!0,writable:!0}):e[t]=r,e}function l8(e,t){if(!(e instanceof t))throw new TypeError("Cannot call a class as a function")}function KO(e,t){for(var r=0;r<t.length;r++){var i=t[r];i.enumerable=i.enumerable||!1,i.configurable=!0,"value"in i&&(i.writable=!0),Object.defineProperty(e,VO(i.key),i)}}function h8(e,t,r){return t&&KO(e.prototype,t),r&&KO(e,r),Object.defineProperty(e,"prototype",{writable:!1}),e}function VO(e){var t=d8(e,"string");return typeof t=="symbol"?t:String(t)}function d8(e,t){if(typeof e!="object"||e===null)return e;var r=e[Symbol.toPrimitive];if(r!==void 0){var i=r.call(e,t||"default");if(typeof i!="object")return i;throw new TypeError("@@toPrimitive must return a primitive value.")}return(t==="string"?String:Number)(e)}var p8=rr(),ep=p8.Buffer,g8=nn(),X0=g8.inspect,m8=X0&&X0.custom||"inspect";function v8(e,t,r){ep.prototype.copy.call(e,t,r)}GO.exports=(function(){function e(){l8(this,e),this.head=null,this.tail=null,this.length=0}return h8(e,[{key:"push",value:function(r){var i={data:r,next:null};this.length>0?this.tail.next=i:this.head=i,this.tail=i,++this.length}},{key:"unshift",value:function(r){var i={data:r,next:this.head};this.length===0&&(this.tail=i),this.head=i,++this.length}},{key:"shift",value:function(){if(this.length!==0){var r=this.head.data;return this.length===1?this.head=this.tail=null:this.head=this.head.next,--this.length,r}}},{key:"clear",value:function(){this.head=this.tail=null,this.length=0}},{key:"join",value:function(r){if(this.length===0)return"";for(var i=this.head,n=""+i.data;i=i.next;)n+=r+i.data;return n}},{key:"concat",value:function(r){if(this.length===0)return ep.alloc(0);for(var i=ep.allocUnsafe(r>>>0),n=this.head,o=0;n;)v8(n.data,i,o),o+=n.data.length,n=n.next;return i}},{key:"consume",value:function(r,i){var n;return r<this.head.data.length?(n=this.head.data.slice(0,r),this.head.data=this.head.data.slice(r)):r===this.head.data.length?n=this.shift():n=i?this._getString(r):this._getBuffer(r),n}},{key:"first",value:function(){return this.head.data}},{key:"_getString",value:function(r){var i=this.head,n=1,o=i.data;for(r-=o.length;i=i.next;){var a=i.data,s=r>a.length?a.length:r;if(s===a.length?o+=a:o+=a.slice(0,r),r-=s,r===0){s===a.length?(++n,i.next?this.head=i.next:this.head=this.tail=null):(this.head=i,i.data=a.slice(s));break}++n}return this.length-=n,o}},{key:"_getBuffer",value:function(r){var i=ep.allocUnsafe(r),n=this.head,o=1;for(n.data.copy(i),r-=n.data.length;n=n.next;){var a=n.data,s=r>a.length?a.length:r;if(a.copy(i,i.length-r,0,s),r-=s,r===0){s===a.length?(++o,n.next?this.head=n.next:this.head=this.tail=null):(this.head=n,n.data=a.slice(s));break}++o}return this.length-=o,i}},{key:m8,value:function(r,i){return X0(this,zO(zO({},i),{},{depth:0,customInspect:!1}))}}]),e})()});var Q0=T((kre,ZO)=>{"use strict";g();function y8(e,t){var r=this,i=this._readableState&&this._readableState.destroyed,n=this._writableState&&this._writableState.destroyed;return i||n?(t?t(e):e&&(this._writableState?this._writableState.errorEmitted||(this._writableState.errorEmitted=!0,b.default.nextTick(J0,this,e)):b.default.nextTick(J0,this,e)),this):(this._readableState&&(this._readableState.destroyed=!0),this._writableState&&(this._writableState.destroyed=!0),this._destroy(e||null,function(o){!t&&o?r._writableState?r._writableState.errorEmitted?b.default.nextTick(tp,r):(r._writableState.errorEmitted=!0,b.default.nextTick(YO,r,o)):b.default.nextTick(YO,r,o):t?(b.default.nextTick(tp,r),t(o)):b.default.nextTick(tp,r)}),this)}function YO(e,t){J0(e,t),tp(e)}function tp(e){e._writableState&&!e._writableState.emitClose||e._readableState&&!e._readableState.emitClose||e.emit("close")}function b8(){this._readableState&&(this._readableState.destroyed=!1,this._readableState.reading=!1,this._readableState.ended=!1,this._readableState.endEmitted=!1),this._writableState&&(this._writableState.destroyed=!1,this._writableState.ended=!1,this._writableState.ending=!1,this._writableState.finalCalled=!1,this._writableState.prefinished=!1,this._writableState.finished=!1,this._writableState.errorEmitted=!1)}function J0(e,t){e.emit("error",t)}function _8(e,t){var r=e._readableState,i=e._writableState;r&&r.autoDestroy||i&&i.autoDestroy?e.destroy(t):e.emit("error",t)}ZO.exports={destroy:y8,undestroy:b8,errorOrDestroy:_8}});var Ms=T((Nre,JO)=>{"use strict";g();function w8(e,t){e.prototype=Object.create(t.prototype),e.prototype.constructor=e,e.__proto__=t}var XO={};function on(e,t,r){r||(r=Error);function i(o,a,s){return typeof t=="string"?t:t(o,a,s)}var n=(function(o){w8(a,o);function a(s,u,c){return o.call(this,i(s,u,c))||this}return a})(r);n.prototype.name=r.name,n.prototype.code=e,XO[e]=n}function $O(e,t){if(Array.isArray(e)){var r=e.length;return e=e.map(function(i){return String(i)}),r>2?"one of ".concat(t," ").concat(e.slice(0,r-1).join(", "),", or ")+e[r-1]:r===2?"one of ".concat(t," ").concat(e[0]," or ").concat(e[1]):"of ".concat(t," ").concat(e[0])}else return"of ".concat(t," ").concat(String(e))}function S8(e,t,r){return e.substr(!r||r<0?0:+r,t.length)===t}function E8(e,t,r){return(r===void 0||r>e.length)&&(r=e.length),e.substring(r-t.length,r)===t}function x8(e,t,r){return typeof r!="number"&&(r=0),r+t.length>e.length?!1:e.indexOf(t,r)!==-1}on("ERR_INVALID_OPT_VALUE",function(e,t){return'The value "'+t+'" is invalid for option "'+e+'"'},TypeError);on("ERR_INVALID_ARG_TYPE",function(e,t,r){var i;typeof t=="string"&&S8(t,"not ")?(i="must not be",t=t.replace(/^not /,"")):i="must be";var n;if(E8(e," argument"))n="The ".concat(e," ").concat(i," ").concat($O(t,"type"));else{var o=x8(e,".")?"property":"argument";n='The "'.concat(e,'" ').concat(o," ").concat(i," ").concat($O(t,"type"))}return n+=". Received type ".concat(typeof r),n},TypeError);on("ERR_STREAM_PUSH_AFTER_EOF","stream.push() after EOF");on("ERR_METHOD_NOT_IMPLEMENTED",function(e){return"The "+e+" method is not implemented"});on("ERR_STREAM_PREMATURE_CLOSE","Premature close");on("ERR_STREAM_DESTROYED",function(e){return"Cannot call "+e+" after a stream was destroyed"});on("ERR_MULTIPLE_CALLBACK","Callback called multiple times");on("ERR_STREAM_CANNOT_PIPE","Cannot pipe, not readable");on("ERR_STREAM_WRITE_AFTER_END","write after end");on("ERR_STREAM_NULL_VALUES","May not write null values to stream",TypeError);on("ERR_UNKNOWN_ENCODING",function(e){return"Unknown encoding: "+e},TypeError);on("ERR_STREAM_UNSHIFT_AFTER_END_EVENT","stream.unshift() after end event");JO.exports.codes=XO});var ey=T((Lre,QO)=>{"use strict";g();var O8=Ms().codes.ERR_INVALID_OPT_VALUE;function I8(e,t,r){return e.highWaterMark!=null?e.highWaterMark:t?e[r]:null}function A8(e,t,r,i){var n=I8(t,i,r);if(n!=null){if(!(isFinite(n)&&Math.floor(n)===n)||n<0){var o=i?r:"highWaterMark";throw new O8(o,n)}return Math.floor(n)}return e.objectMode?16:16*1024}QO.exports={getHighWaterMark:A8}});var ry=T((Dre,eI)=>{g();eI.exports=T8;function T8(e,t){if(ty("noDeprecation"))return e;var r=!1;function i(){if(!r){if(ty("throwDeprecation"))throw new Error(t);ty("traceDeprecation")?console.trace(t):console.warn(t),r=!0}return e.apply(this,arguments)}return i}function ty(e){try{if(!globalThis.localStorage)return!1}catch{return!1}var t=globalThis.localStorage[e];return t==null?!1:String(t).toLowerCase()==="true"}});var oy=T((qre,aI)=>{"use strict";g();aI.exports=ir;function rI(e){var t=this;this.next=null,this.entry=null,this.finish=function(){t4(t,e)}}var tc;ir.WritableState=Xf;var P8={deprecate:ry()},iI=y0(),ip=rr().Buffer,R8=(typeof globalThis<"u"?globalThis:typeof window<"u"?window:typeof self<"u"?self:{}).Uint8Array||function(){};function k8(e){return ip.from(e)}function B8(e){return ip.isBuffer(e)||e instanceof R8}var ny=Q0(),N8=ey(),C8=N8.getHighWaterMark,Ba=Ms().codes,L8=Ba.ERR_INVALID_ARG_TYPE,M8=Ba.ERR_METHOD_NOT_IMPLEMENTED,D8=Ba.ERR_MULTIPLE_CALLBACK,H8=Ba.ERR_STREAM_CANNOT_PIPE,q8=Ba.ERR_STREAM_DESTROYED,U8=Ba.ERR_STREAM_NULL_VALUES,F8=Ba.ERR_STREAM_WRITE_AFTER_END,j8=Ba.ERR_UNKNOWN_ENCODING,rc=ny.errorOrDestroy;Rt()(ir,iI);function z8(){}function Xf(e,t,r){tc=tc||Ds(),e=e||{},typeof r!="boolean"&&(r=t instanceof tc),this.objectMode=!!e.objectMode,r&&(this.objectMode=this.objectMode||!!e.writableObjectMode),this.highWaterMark=C8(this,e,"writableHighWaterMark",r),this.finalCalled=!1,this.needDrain=!1,this.ending=!1,this.ended=!1,this.finished=!1,this.destroyed=!1;var i=e.decodeStrings===!1;this.decodeStrings=!i,this.defaultEncoding=e.defaultEncoding||"utf8",this.length=0,this.writing=!1,this.corked=0,this.sync=!0,this.bufferProcessing=!1,this.onwrite=function(n){$8(t,n)},this.writecb=null,this.writelen=0,this.bufferedRequest=null,this.lastBufferedRequest=null,this.pendingcb=0,this.prefinished=!1,this.errorEmitted=!1,this.emitClose=e.emitClose!==!1,this.autoDestroy=!!e.autoDestroy,this.bufferedRequestCount=0,this.corkedRequestsFree=new rI(this)}Xf.prototype.getBuffer=function(){for(var t=this.bufferedRequest,r=[];t;)r.push(t),t=t.next;return r};(function(){try{Object.defineProperty(Xf.prototype,"buffer",{get:P8.deprecate(function(){return this.getBuffer()},"_writableState.buffer is deprecated. Use _writableState.getBuffer instead.","DEP0003")})}catch{}})();var rp;typeof Symbol=="function"&&Symbol.hasInstance&&typeof Function.prototype[Symbol.hasInstance]=="function"?(rp=Function.prototype[Symbol.hasInstance],Object.defineProperty(ir,Symbol.hasInstance,{value:function(t){return rp.call(this,t)?!0:this!==ir?!1:t&&t._writableState instanceof Xf}})):rp=function(t){return t instanceof this};function ir(e){tc=tc||Ds();var t=this instanceof tc;if(!t&&!rp.call(ir,this))return new ir(e);this._writableState=new Xf(e,this,t),this.writable=!0,e&&(typeof e.write=="function"&&(this._write=e.write),typeof e.writev=="function"&&(this._writev=e.writev),typeof e.destroy=="function"&&(this._destroy=e.destroy),typeof e.final=="function"&&(this._final=e.final)),iI.call(this)}ir.prototype.pipe=function(){rc(this,new H8)};function K8(e,t){var r=new F8;rc(e,r),b.default.nextTick(t,r)}function V8(e,t,r,i){var n;return r===null?n=new U8:typeof r!="string"&&!t.objectMode&&(n=new L8("chunk",["string","Buffer"],r)),n?(rc(e,n),b.default.nextTick(i,n),!1):!0}ir.prototype.write=function(e,t,r){var i=this._writableState,n=!1,o=!i.objectMode&&B8(e);return o&&!ip.isBuffer(e)&&(e=k8(e)),typeof t=="function"&&(r=t,t=null),o?t="buffer":t||(t=i.defaultEncoding),typeof r!="function"&&(r=z8),i.ending?K8(this,r):(o||V8(this,i,e,r))&&(i.pendingcb++,n=W8(this,i,o,e,t,r)),n};ir.prototype.cork=function(){this._writableState.corked++};ir.prototype.uncork=function(){var e=this._writableState;e.corked&&(e.corked--,!e.writing&&!e.corked&&!e.bufferProcessing&&e.bufferedRequest&&nI(this,e))};ir.prototype.setDefaultEncoding=function(t){if(typeof t=="string"&&(t=t.toLowerCase()),!(["hex","utf8","utf-8","ascii","binary","base64","ucs2","ucs-2","utf16le","utf-16le","raw"].indexOf((t+"").toLowerCase())>-1))throw new j8(t);return this._writableState.defaultEncoding=t,this};Object.defineProperty(ir.prototype,"writableBuffer",{enumerable:!1,get:function(){return this._writableState&&this._writableState.getBuffer()}});function G8(e,t,r){return!e.objectMode&&e.decodeStrings!==!1&&typeof t=="string"&&(t=ip.from(t,r)),t}Object.defineProperty(ir.prototype,"writableHighWaterMark",{enumerable:!1,get:function(){return this._writableState.highWaterMark}});function W8(e,t,r,i,n,o){if(!r){var a=G8(t,i,n);i!==a&&(r=!0,n="buffer",i=a)}var s=t.objectMode?1:i.length;t.length+=s;var u=t.length<t.highWaterMark;if(u||(t.needDrain=!0),t.writing||t.corked){var c=t.lastBufferedRequest;t.lastBufferedRequest={chunk:i,encoding:n,isBuf:r,callback:o,next:null},c?c.next=t.lastBufferedRequest:t.bufferedRequest=t.lastBufferedRequest,t.bufferedRequestCount+=1}else iy(e,t,!1,s,i,n,o);return u}function iy(e,t,r,i,n,o,a){t.writelen=i,t.writecb=a,t.writing=!0,t.sync=!0,t.destroyed?t.onwrite(new q8("write")):r?e._writev(n,t.onwrite):e._write(n,o,t.onwrite),t.sync=!1}function Y8(e,t,r,i,n){--t.pendingcb,r?(b.default.nextTick(n,i),b.default.nextTick($f,e,t),e._writableState.errorEmitted=!0,rc(e,i)):(n(i),e._writableState.errorEmitted=!0,rc(e,i),$f(e,t))}function Z8(e){e.writing=!1,e.writecb=null,e.length-=e.writelen,e.writelen=0}function $8(e,t){var r=e._writableState,i=r.sync,n=r.writecb;if(typeof n!="function")throw new D8;if(Z8(r),t)Y8(e,r,i,t,n);else{var o=oI(r)||e.destroyed;!o&&!r.corked&&!r.bufferProcessing&&r.bufferedRequest&&nI(e,r),i?b.default.nextTick(tI,e,r,o,n):tI(e,r,o,n)}}function tI(e,t,r,i){r||X8(e,t),t.pendingcb--,i(),$f(e,t)}function X8(e,t){t.length===0&&t.needDrain&&(t.needDrain=!1,e.emit("drain"))}function nI(e,t){t.bufferProcessing=!0;var r=t.bufferedRequest;if(e._writev&&r&&r.next){var i=t.bufferedRequestCount,n=new Array(i),o=t.corkedRequestsFree;o.entry=r;for(var a=0,s=!0;r;)n[a]=r,r.isBuf||(s=!1),r=r.next,a+=1;n.allBuffers=s,iy(e,t,!0,t.length,n,"",o.finish),t.pendingcb++,t.lastBufferedRequest=null,o.next?(t.corkedRequestsFree=o.next,o.next=null):t.corkedRequestsFree=new rI(t),t.bufferedRequestCount=0}else{for(;r;){var u=r.chunk,c=r.encoding,l=r.callback,p=t.objectMode?1:u.length;if(iy(e,t,!1,p,u,c,l),r=r.next,t.bufferedRequestCount--,t.writing)break}r===null&&(t.lastBufferedRequest=null)}t.bufferedRequest=r,t.bufferProcessing=!1}ir.prototype._write=function(e,t,r){r(new M8("_write()"))};ir.prototype._writev=null;ir.prototype.end=function(e,t,r){var i=this._writableState;return typeof e=="function"?(r=e,e=null,t=null):typeof t=="function"&&(r=t,t=null),e!=null&&this.write(e,t),i.corked&&(i.corked=1,this.uncork()),i.ending||e4(this,i,r),this};Object.defineProperty(ir.prototype,"writableLength",{enumerable:!1,get:function(){return this._writableState.length}});function oI(e){return e.ending&&e.length===0&&e.bufferedRequest===null&&!e.finished&&!e.writing}function J8(e,t){e._final(function(r){t.pendingcb--,r&&rc(e,r),t.prefinished=!0,e.emit("prefinish"),$f(e,t)})}function Q8(e,t){!t.prefinished&&!t.finalCalled&&(typeof e._final=="function"&&!t.destroyed?(t.pendingcb++,t.finalCalled=!0,b.default.nextTick(J8,e,t)):(t.prefinished=!0,e.emit("prefinish")))}function $f(e,t){var r=oI(t);if(r&&(Q8(e,t),t.pendingcb===0&&(t.finished=!0,e.emit("finish"),t.autoDestroy))){var i=e._readableState;(!i||i.autoDestroy&&i.endEmitted)&&e.destroy()}return r}function e4(e,t,r){t.ending=!0,$f(e,t),r&&(t.finished?b.default.nextTick(r):e.once("finish",r)),t.ended=!0,e.writable=!1}function t4(e,t,r){var i=e.entry;for(e.entry=null;i;){var n=i.callback;t.pendingcb--,n(r),i=i.next}t.corkedRequestsFree.next=e}Object.defineProperty(ir.prototype,"destroyed",{enumerable:!1,get:function(){return this._writableState===void 0?!1:this._writableState.destroyed},set:function(t){this._writableState&&(this._writableState.destroyed=t)}});ir.prototype.destroy=ny.destroy;ir.prototype._undestroy=ny.undestroy;ir.prototype._destroy=function(e,t){t(e)}});var Ds=T((Fre,uI)=>{"use strict";g();var r4=Object.keys||function(e){var t=[];for(var r in e)t.push(r);return t};uI.exports=eo;var sI=uy(),sy=oy();Rt()(eo,sI);for(ay=r4(sy.prototype),np=0;np<ay.length;np++)op=ay[np],eo.prototype[op]||(eo.prototype[op]=sy.prototype[op]);var ay,op,np;function eo(e){if(!(this instanceof eo))return new eo(e);sI.call(this,e),sy.call(this,e),this.allowHalfOpen=!0,e&&(e.readable===!1&&(this.readable=!1),e.writable===!1&&(this.writable=!1),e.allowHalfOpen===!1&&(this.allowHalfOpen=!1,this.once("end",i4)))}Object.defineProperty(eo.prototype,"writableHighWaterMark",{enumerable:!1,get:function(){return this._writableState.highWaterMark}});Object.defineProperty(eo.prototype,"writableBuffer",{enumerable:!1,get:function(){return this._writableState&&this._writableState.getBuffer()}});Object.defineProperty(eo.prototype,"writableLength",{enumerable:!1,get:function(){return this._writableState.length}});function i4(){this._writableState.ended||b.default.nextTick(n4,this)}function n4(e){e.end()}Object.defineProperty(eo.prototype,"destroyed",{enumerable:!1,get:function(){return this._readableState===void 0||this._writableState===void 0?!1:this._readableState.destroyed&&this._writableState.destroyed},set:function(t){this._readableState===void 0||this._writableState===void 0||(this._readableState.destroyed=t,this._writableState.destroyed=t)}})});var lI=T((cy,fI)=>{g();var ap=rr(),Ko=ap.Buffer;function cI(e,t){for(var r in e)t[r]=e[r]}Ko.from&&Ko.alloc&&Ko.allocUnsafe&&Ko.allocUnsafeSlow?fI.exports=ap:(cI(ap,cy),cy.Buffer=ic);function ic(e,t,r){return Ko(e,t,r)}cI(Ko,ic);ic.from=function(e,t,r){if(typeof e=="number")throw new TypeError("Argument must not be a number");return Ko(e,t,r)};ic.alloc=function(e,t,r){if(typeof e!="number")throw new TypeError("Argument must be a number");var i=Ko(e);return t!==void 0?typeof r=="string"?i.fill(t,r):i.fill(t):i.fill(0),i};ic.allocUnsafe=function(e){if(typeof e!="number")throw new TypeError("Argument must be a number");return Ko(e)};ic.allocUnsafeSlow=function(e){if(typeof e!="number")throw new TypeError("Argument must be a number");return ap.SlowBuffer(e)}});var nc=T(dI=>{"use strict";g();var ly=lI().Buffer,hI=ly.isEncoding||function(e){switch(e=""+e,e&&e.toLowerCase()){case"hex":case"utf8":case"utf-8":case"ascii":case"binary":case"base64":case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":case"raw":return!0;default:return!1}};function o4(e){if(!e)return"utf8";for(var t;;)switch(e){case"utf8":case"utf-8":return"utf8";case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":return"utf16le";case"latin1":case"binary":return"latin1";case"base64":case"ascii":case"hex":return e;default:if(t)return;e=(""+e).toLowerCase(),t=!0}}function a4(e){var t=o4(e);if(typeof t!="string"&&(ly.isEncoding===hI||!hI(e)))throw new Error("Unknown encoding: "+e);return t||e}dI.StringDecoder=Jf;function Jf(e){this.encoding=a4(e);var t;switch(this.encoding){case"utf16le":this.text=h4,this.end=d4,t=4;break;case"utf8":this.fillLast=c4,t=4;break;case"base64":this.text=p4,this.end=g4,t=3;break;default:this.write=m4,this.end=v4;return}this.lastNeed=0,this.lastTotal=0,this.lastChar=ly.allocUnsafe(t)}Jf.prototype.write=function(e){if(e.length===0)return"";var t,r;if(this.lastNeed){if(t=this.fillLast(e),t===void 0)return"";r=this.lastNeed,this.lastNeed=0}else r=0;return r<e.length?t?t+this.text(e,r):this.text(e,r):t||""};Jf.prototype.end=l4;Jf.prototype.text=f4;Jf.prototype.fillLast=function(e){if(this.lastNeed<=e.length)return e.copy(this.lastChar,this.lastTotal-this.lastNeed,0,this.lastNeed),this.lastChar.toString(this.encoding,0,this.lastTotal);e.copy(this.lastChar,this.lastTotal-this.lastNeed,0,e.length),this.lastNeed-=e.length};function fy(e){return e<=127?0:e>>5===6?2:e>>4===14?3:e>>3===30?4:e>>6===2?-1:-2}function s4(e,t,r){var i=t.length-1;if(i<r)return 0;var n=fy(t[i]);return n>=0?(n>0&&(e.lastNeed=n-1),n):--i<r||n===-2?0:(n=fy(t[i]),n>=0?(n>0&&(e.lastNeed=n-2),n):--i<r||n===-2?0:(n=fy(t[i]),n>=0?(n>0&&(n===2?n=0:e.lastNeed=n-3),n):0))}function u4(e,t,r){if((t[0]&192)!==128)return e.lastNeed=0,"\uFFFD";if(e.lastNeed>1&&t.length>1){if((t[1]&192)!==128)return e.lastNeed=1,"\uFFFD";if(e.lastNeed>2&&t.length>2&&(t[2]&192)!==128)return e.lastNeed=2,"\uFFFD"}}function c4(e){var t=this.lastTotal-this.lastNeed,r=u4(this,e,t);if(r!==void 0)return r;if(this.lastNeed<=e.length)return e.copy(this.lastChar,t,0,this.lastNeed),this.lastChar.toString(this.encoding,0,this.lastTotal);e.copy(this.lastChar,t,0,e.length),this.lastNeed-=e.length}function f4(e,t){var r=s4(this,e,t);if(!this.lastNeed)return e.toString("utf8",t);this.lastTotal=r;var i=e.length-(r-this.lastNeed);return e.copy(this.lastChar,0,i),e.toString("utf8",t,i)}function l4(e){var t=e&&e.length?this.write(e):"";return this.lastNeed?t+"\uFFFD":t}function h4(e,t){if((e.length-t)%2===0){var r=e.toString("utf16le",t);if(r){var i=r.charCodeAt(r.length-1);if(i>=55296&&i<=56319)return this.lastNeed=2,this.lastTotal=4,this.lastChar[0]=e[e.length-2],this.lastChar[1]=e[e.length-1],r.slice(0,-1)}return r}return this.lastNeed=1,this.lastTotal=2,this.lastChar[0]=e[e.length-1],e.toString("utf16le",t,e.length-1)}function d4(e){var t=e&&e.length?this.write(e):"";if(this.lastNeed){var r=this.lastTotal-this.lastNeed;return t+this.lastChar.toString("utf16le",0,r)}return t}function p4(e,t){var r=(e.length-t)%3;return r===0?e.toString("base64",t):(this.lastNeed=3-r,this.lastTotal=3,r===1?this.lastChar[0]=e[e.length-1]:(this.lastChar[0]=e[e.length-2],this.lastChar[1]=e[e.length-1]),e.toString("base64",t,e.length-r))}function g4(e){var t=e&&e.length?this.write(e):"";return this.lastNeed?t+this.lastChar.toString("base64",0,3-this.lastNeed):t}function m4(e){return e.toString(this.encoding)}function v4(e){return e&&e.length?this.write(e):""}});var sp=T((Gre,mI)=>{"use strict";g();var pI=Ms().codes.ERR_STREAM_PREMATURE_CLOSE;function y4(e){var t=!1;return function(){if(!t){t=!0;for(var r=arguments.length,i=new Array(r),n=0;n<r;n++)i[n]=arguments[n];e.apply(this,i)}}}function b4(){}function _4(e){return e.setHeader&&typeof e.abort=="function"}function gI(e,t,r){if(typeof t=="function")return gI(e,null,t);t||(t={}),r=y4(r||b4);var i=t.readable||t.readable!==!1&&e.readable,n=t.writable||t.writable!==!1&&e.writable,o=function(){e.writable||s()},a=e._writableState&&e._writableState.finished,s=function(){n=!1,a=!0,i||r.call(e)},u=e._readableState&&e._readableState.endEmitted,c=function(){i=!1,u=!0,n||r.call(e)},l=function(_){r.call(e,_)},p=function(){var _;if(i&&!u)return(!e._readableState||!e._readableState.ended)&&(_=new pI),r.call(e,_);if(n&&!a)return(!e._writableState||!e._writableState.ended)&&(_=new pI),r.call(e,_)},d=function(){e.req.on("finish",s)};return _4(e)?(e.on("complete",s),e.on("abort",p),e.req?d():e.on("request",d)):n&&!e._writableState&&(e.on("end",o),e.on("close",o)),e.on("end",c),e.on("finish",s),t.error!==!1&&e.on("error",l),e.on("close",p),function(){e.removeListener("complete",s),e.removeListener("abort",p),e.removeListener("request",d),e.req&&e.req.removeListener("finish",s),e.removeListener("end",o),e.removeListener("close",o),e.removeListener("finish",s),e.removeListener("end",c),e.removeListener("error",l),e.removeListener("close",p)}}mI.exports=gI});var yI=T((Yre,vI)=>{"use strict";g();var up;function Na(e,t,r){return t=w4(t),t in e?Object.defineProperty(e,t,{value:r,enumerable:!0,configurable:!0,writable:!0}):e[t]=r,e}function w4(e){var t=S4(e,"string");return typeof t=="symbol"?t:String(t)}function S4(e,t){if(typeof e!="object"||e===null)return e;var r=e[Symbol.toPrimitive];if(r!==void 0){var i=r.call(e,t||"default");if(typeof i!="object")return i;throw new TypeError("@@toPrimitive must return a primitive value.")}return(t==="string"?String:Number)(e)}var E4=sp(),Ca=Symbol("lastResolve"),Hs=Symbol("lastReject"),Qf=Symbol("error"),cp=Symbol("ended"),qs=Symbol("lastPromise"),hy=Symbol("handlePromise"),Us=Symbol("stream");function La(e,t){return{value:e,done:t}}function x4(e){var t=e[Ca];if(t!==null){var r=e[Us].read();r!==null&&(e[qs]=null,e[Ca]=null,e[Hs]=null,t(La(r,!1)))}}function O4(e){b.default.nextTick(x4,e)}function I4(e,t){return function(r,i){e.then(function(){if(t[cp]){r(La(void 0,!0));return}t[hy](r,i)},i)}}var A4=Object.getPrototypeOf(function(){}),T4=Object.setPrototypeOf((up={get stream(){return this[Us]},next:function(){var t=this,r=this[Qf];if(r!==null)return Promise.reject(r);if(this[cp])return Promise.resolve(La(void 0,!0));if(this[Us].destroyed)return new Promise(function(a,s){b.default.nextTick(function(){t[Qf]?s(t[Qf]):a(La(void 0,!0))})});var i=this[qs],n;if(i)n=new Promise(I4(i,this));else{var o=this[Us].read();if(o!==null)return Promise.resolve(La(o,!1));n=new Promise(this[hy])}return this[qs]=n,n}},Na(up,Symbol.asyncIterator,function(){return this}),Na(up,"return",function(){var t=this;return new Promise(function(r,i){t[Us].destroy(null,function(n){if(n){i(n);return}r(La(void 0,!0))})})}),up),A4),P4=function(t){var r,i=Object.create(T4,(r={},Na(r,Us,{value:t,writable:!0}),Na(r,Ca,{value:null,writable:!0}),Na(r,Hs,{value:null,writable:!0}),Na(r,Qf,{value:null,writable:!0}),Na(r,cp,{value:t._readableState.endEmitted,writable:!0}),Na(r,hy,{value:function(o,a){var s=i[Us].read();s?(i[qs]=null,i[Ca]=null,i[Hs]=null,o(La(s,!1))):(i[Ca]=o,i[Hs]=a)},writable:!0}),r));return i[qs]=null,E4(t,function(n){if(n&&n.code!=="ERR_STREAM_PREMATURE_CLOSE"){var o=i[Hs];o!==null&&(i[qs]=null,i[Ca]=null,i[Hs]=null,o(n)),i[Qf]=n;return}var a=i[Ca];a!==null&&(i[qs]=null,i[Ca]=null,i[Hs]=null,a(La(void 0,!0))),i[cp]=!0}),t.on("readable",O4.bind(null,i)),i};vI.exports=P4});var _I=T(($re,bI)=>{g();bI.exports=function(){throw new Error("Readable.from is not available in the browser")}});var uy=T((Qre,RI)=>{"use strict";g();RI.exports=ht;var oc;ht.ReadableState=xI;var Jre=Vu().EventEmitter,EI=function(t,r){return t.listeners(r).length},tl=y0(),fp=rr().Buffer,R4=(typeof globalThis<"u"?globalThis:typeof window<"u"?window:typeof self<"u"?self:{}).Uint8Array||function(){};function k4(e){return fp.from(e)}function B4(e){return fp.isBuffer(e)||e instanceof R4}var dy=nn(),ze;dy&&dy.debuglog?ze=dy.debuglog("stream"):ze=function(){};var N4=WO(),_y=Q0(),C4=ey(),L4=C4.getHighWaterMark,lp=Ms().codes,M4=lp.ERR_INVALID_ARG_TYPE,D4=lp.ERR_STREAM_PUSH_AFTER_EOF,H4=lp.ERR_METHOD_NOT_IMPLEMENTED,q4=lp.ERR_STREAM_UNSHIFT_AFTER_END_EVENT,ac,py,gy;Rt()(ht,tl);var el=_y.errorOrDestroy,my=["error","close","destroy","pause","resume"];function U4(e,t,r){if(typeof e.prependListener=="function")return e.prependListener(t,r);!e._events||!e._events[t]?e.on(t,r):Array.isArray(e._events[t])?e._events[t].unshift(r):e._events[t]=[r,e._events[t]]}function xI(e,t,r){oc=oc||Ds(),e=e||{},typeof r!="boolean"&&(r=t instanceof oc),this.objectMode=!!e.objectMode,r&&(this.objectMode=this.objectMode||!!e.readableObjectMode),this.highWaterMark=L4(this,e,"readableHighWaterMark",r),this.buffer=new N4,this.length=0,this.pipes=null,this.pipesCount=0,this.flowing=null,this.ended=!1,this.endEmitted=!1,this.reading=!1,this.sync=!0,this.needReadable=!1,this.emittedReadable=!1,this.readableListening=!1,this.resumeScheduled=!1,this.paused=!0,this.emitClose=e.emitClose!==!1,this.autoDestroy=!!e.autoDestroy,this.destroyed=!1,this.defaultEncoding=e.defaultEncoding||"utf8",this.awaitDrain=0,this.readingMore=!1,this.decoder=null,this.encoding=null,e.encoding&&(ac||(ac=nc().StringDecoder),this.decoder=new ac(e.encoding),this.encoding=e.encoding)}function ht(e){if(oc=oc||Ds(),!(this instanceof ht))return new ht(e);var t=this instanceof oc;this._readableState=new xI(e,this,t),this.readable=!0,e&&(typeof e.read=="function"&&(this._read=e.read),typeof e.destroy=="function"&&(this._destroy=e.destroy)),tl.call(this)}Object.defineProperty(ht.prototype,"destroyed",{enumerable:!1,get:function(){return this._readableState===void 0?!1:this._readableState.destroyed},set:function(t){this._readableState&&(this._readableState.destroyed=t)}});ht.prototype.destroy=_y.destroy;ht.prototype._undestroy=_y.undestroy;ht.prototype._destroy=function(e,t){t(e)};ht.prototype.push=function(e,t){var r=this._readableState,i;return r.objectMode?i=!0:typeof e=="string"&&(t=t||r.defaultEncoding,t!==r.encoding&&(e=fp.from(e,t),t=""),i=!0),OI(this,e,t,!1,i)};ht.prototype.unshift=function(e){return OI(this,e,null,!0,!1)};function OI(e,t,r,i,n){ze("readableAddChunk",t);var o=e._readableState;if(t===null)o.reading=!1,z4(e,o);else{var a;if(n||(a=F4(o,t)),a)el(e,a);else if(o.objectMode||t&&t.length>0)if(typeof t!="string"&&!o.objectMode&&Object.getPrototypeOf(t)!==fp.prototype&&(t=k4(t)),i)o.endEmitted?el(e,new q4):vy(e,o,t,!0);else if(o.ended)el(e,new D4);else{if(o.destroyed)return!1;o.reading=!1,o.decoder&&!r?(t=o.decoder.write(t),o.objectMode||t.length!==0?vy(e,o,t,!1):by(e,o)):vy(e,o,t,!1)}else i||(o.reading=!1,by(e,o))}return!o.ended&&(o.length<o.highWaterMark||o.length===0)}function vy(e,t,r,i){t.flowing&&t.length===0&&!t.sync?(t.awaitDrain=0,e.emit("data",r)):(t.length+=t.objectMode?1:r.length,i?t.buffer.unshift(r):t.buffer.push(r),t.needReadable&&hp(e)),by(e,t)}function F4(e,t){var r;return!B4(t)&&typeof t!="string"&&t!==void 0&&!e.objectMode&&(r=new M4("chunk",["string","Buffer","Uint8Array"],t)),r}ht.prototype.isPaused=function(){return this._readableState.flowing===!1};ht.prototype.setEncoding=function(e){ac||(ac=nc().StringDecoder);var t=new ac(e);this._readableState.decoder=t,this._readableState.encoding=this._readableState.decoder.encoding;for(var r=this._readableState.buffer.head,i="";r!==null;)i+=t.write(r.data),r=r.next;return this._readableState.buffer.clear(),i!==""&&this._readableState.buffer.push(i),this._readableState.length=i.length,this};var wI=1073741824;function j4(e){return e>=wI?e=wI:(e--,e|=e>>>1,e|=e>>>2,e|=e>>>4,e|=e>>>8,e|=e>>>16,e++),e}function SI(e,t){return e<=0||t.length===0&&t.ended?0:t.objectMode?1:e!==e?t.flowing&&t.length?t.buffer.head.data.length:t.length:(e>t.highWaterMark&&(t.highWaterMark=j4(e)),e<=t.length?e:t.ended?t.length:(t.needReadable=!0,0))}ht.prototype.read=function(e){ze("read",e),e=parseInt(e,10);var t=this._readableState,r=e;if(e!==0&&(t.emittedReadable=!1),e===0&&t.needReadable&&((t.highWaterMark!==0?t.length>=t.highWaterMark:t.length>0)||t.ended))return ze("read: emitReadable",t.length,t.ended),t.length===0&&t.ended?yy(this):hp(this),null;if(e=SI(e,t),e===0&&t.ended)return t.length===0&&yy(this),null;var i=t.needReadable;ze("need readable",i),(t.length===0||t.length-e<t.highWaterMark)&&(i=!0,ze("length less than watermark",i)),t.ended||t.reading?(i=!1,ze("reading or ended",i)):i&&(ze("do read"),t.reading=!0,t.sync=!0,t.length===0&&(t.needReadable=!0),this._read(t.highWaterMark),t.sync=!1,t.reading||(e=SI(r,t)));var n;return e>0?n=TI(e,t):n=null,n===null?(t.needReadable=t.length<=t.highWaterMark,e=0):(t.length-=e,t.awaitDrain=0),t.length===0&&(t.ended||(t.needReadable=!0),r!==e&&t.ended&&yy(this)),n!==null&&this.emit("data",n),n};function z4(e,t){if(ze("onEofChunk"),!t.ended){if(t.decoder){var r=t.decoder.end();r&&r.length&&(t.buffer.push(r),t.length+=t.objectMode?1:r.length)}t.ended=!0,t.sync?hp(e):(t.needReadable=!1,t.emittedReadable||(t.emittedReadable=!0,II(e)))}}function hp(e){var t=e._readableState;ze("emitReadable",t.needReadable,t.emittedReadable),t.needReadable=!1,t.emittedReadable||(ze("emitReadable",t.flowing),t.emittedReadable=!0,b.default.nextTick(II,e))}function II(e){var t=e._readableState;ze("emitReadable_",t.destroyed,t.length,t.ended),!t.destroyed&&(t.length||t.ended)&&(e.emit("readable"),t.emittedReadable=!1),t.needReadable=!t.flowing&&!t.ended&&t.length<=t.highWaterMark,wy(e)}function by(e,t){t.readingMore||(t.readingMore=!0,b.default.nextTick(K4,e,t))}function K4(e,t){for(;!t.reading&&!t.ended&&(t.length<t.highWaterMark||t.flowing&&t.length===0);){var r=t.length;if(ze("maybeReadMore read 0"),e.read(0),r===t.length)break}t.readingMore=!1}ht.prototype._read=function(e){el(this,new H4("_read()"))};ht.prototype.pipe=function(e,t){var r=this,i=this._readableState;switch(i.pipesCount){case 0:i.pipes=e;break;case 1:i.pipes=[i.pipes,e];break;default:i.pipes.push(e);break}i.pipesCount+=1,ze("pipe count=%d opts=%j",i.pipesCount,t);var n=(!t||t.end!==!1)&&e!==b.default.stdout&&e!==b.default.stderr,o=n?s:I;i.endEmitted?b.default.nextTick(o):r.once("end",o),e.on("unpipe",a);function a(R,k){ze("onunpipe"),R===r&&k&&k.hasUnpiped===!1&&(k.hasUnpiped=!0,l())}function s(){ze("onend"),e.end()}var u=V4(r);e.on("drain",u);var c=!1;function l(){ze("cleanup"),e.removeListener("close",v),e.removeListener("finish",_),e.removeListener("drain",u),e.removeListener("error",d),e.removeListener("unpipe",a),r.removeListener("end",s),r.removeListener("end",I),r.removeListener("data",p),c=!0,i.awaitDrain&&(!e._writableState||e._writableState.needDrain)&&u()}r.on("data",p);function p(R){ze("ondata");var k=e.write(R);ze("dest.write",k),k===!1&&((i.pipesCount===1&&i.pipes===e||i.pipesCount>1&&PI(i.pipes,e)!==-1)&&!c&&(ze("false write response, pause",i.awaitDrain),i.awaitDrain++),r.pause())}function d(R){ze("onerror",R),I(),e.removeListener("error",d),EI(e,"error")===0&&el(e,R)}U4(e,"error",d);function v(){e.removeListener("finish",_),I()}e.once("close",v);function _(){ze("onfinish"),e.removeListener("close",v),I()}e.once("finish",_);function I(){ze("unpipe"),r.unpipe(e)}return e.emit("pipe",r),i.flowing||(ze("pipe resume"),r.resume()),e};function V4(e){return function(){var r=e._readableState;ze("pipeOnDrain",r.awaitDrain),r.awaitDrain&&r.awaitDrain--,r.awaitDrain===0&&EI(e,"data")&&(r.flowing=!0,wy(e))}}ht.prototype.unpipe=function(e){var t=this._readableState,r={hasUnpiped:!1};if(t.pipesCount===0)return this;if(t.pipesCount===1)return e&&e!==t.pipes?this:(e||(e=t.pipes),t.pipes=null,t.pipesCount=0,t.flowing=!1,e&&e.emit("unpipe",this,r),this);if(!e){var i=t.pipes,n=t.pipesCount;t.pipes=null,t.pipesCount=0,t.flowing=!1;for(var o=0;o<n;o++)i[o].emit("unpipe",this,{hasUnpiped:!1});return this}var a=PI(t.pipes,e);return a===-1?this:(t.pipes.splice(a,1),t.pipesCount-=1,t.pipesCount===1&&(t.pipes=t.pipes[0]),e.emit("unpipe",this,r),this)};ht.prototype.on=function(e,t){var r=tl.prototype.on.call(this,e,t),i=this._readableState;return e==="data"?(i.readableListening=this.listenerCount("readable")>0,i.flowing!==!1&&this.resume()):e==="readable"&&!i.endEmitted&&!i.readableListening&&(i.readableListening=i.needReadable=!0,i.flowing=!1,i.emittedReadable=!1,ze("on readable",i.length,i.reading),i.length?hp(this):i.reading||b.default.nextTick(G4,this)),r};ht.prototype.addListener=ht.prototype.on;ht.prototype.removeListener=function(e,t){var r=tl.prototype.removeListener.call(this,e,t);return e==="readable"&&b.default.nextTick(AI,this),r};ht.prototype.removeAllListeners=function(e){var t=tl.prototype.removeAllListeners.apply(this,arguments);return(e==="readable"||e===void 0)&&b.default.nextTick(AI,this),t};function AI(e){var t=e._readableState;t.readableListening=e.listenerCount("readable")>0,t.resumeScheduled&&!t.paused?t.flowing=!0:e.listenerCount("data")>0&&e.resume()}function G4(e){ze("readable nexttick read 0"),e.read(0)}ht.prototype.resume=function(){var e=this._readableState;return e.flowing||(ze("resume"),e.flowing=!e.readableListening,W4(this,e)),e.paused=!1,this};function W4(e,t){t.resumeScheduled||(t.resumeScheduled=!0,b.default.nextTick(Y4,e,t))}function Y4(e,t){ze("resume",t.reading),t.reading||e.read(0),t.resumeScheduled=!1,e.emit("resume"),wy(e),t.flowing&&!t.reading&&e.read(0)}ht.prototype.pause=function(){return ze("call pause flowing=%j",this._readableState.flowing),this._readableState.flowing!==!1&&(ze("pause"),this._readableState.flowing=!1,this.emit("pause")),this._readableState.paused=!0,this};function wy(e){var t=e._readableState;for(ze("flow",t.flowing);t.flowing&&e.read()!==null;);}ht.prototype.wrap=function(e){var t=this,r=this._readableState,i=!1;e.on("end",function(){if(ze("wrapped end"),r.decoder&&!r.ended){var a=r.decoder.end();a&&a.length&&t.push(a)}t.push(null)}),e.on("data",function(a){if(ze("wrapped data"),r.decoder&&(a=r.decoder.write(a)),!(r.objectMode&&a==null)&&!(!r.objectMode&&(!a||!a.length))){var s=t.push(a);s||(i=!0,e.pause())}});for(var n in e)this[n]===void 0&&typeof e[n]=="function"&&(this[n]=(function(s){return function(){return e[s].apply(e,arguments)}})(n));for(var o=0;o<my.length;o++)e.on(my[o],this.emit.bind(this,my[o]));return this._read=function(a){ze("wrapped _read",a),i&&(i=!1,e.resume())},this};typeof Symbol=="function"&&(ht.prototype[Symbol.asyncIterator]=function(){return py===void 0&&(py=yI()),py(this)});Object.defineProperty(ht.prototype,"readableHighWaterMark",{enumerable:!1,get:function(){return this._readableState.highWaterMark}});Object.defineProperty(ht.prototype,"readableBuffer",{enumerable:!1,get:function(){return this._readableState&&this._readableState.buffer}});Object.defineProperty(ht.prototype,"readableFlowing",{enumerable:!1,get:function(){return this._readableState.flowing},set:function(t){this._readableState&&(this._readableState.flowing=t)}});ht._fromList=TI;Object.defineProperty(ht.prototype,"readableLength",{enumerable:!1,get:function(){return this._readableState.length}});function TI(e,t){if(t.length===0)return null;var r;return t.objectMode?r=t.buffer.shift():!e||e>=t.length?(t.decoder?r=t.buffer.join(""):t.buffer.length===1?r=t.buffer.first():r=t.buffer.concat(t.length),t.buffer.clear()):r=t.buffer.consume(e,t.decoder),r}function yy(e){var t=e._readableState;ze("endReadable",t.endEmitted),t.endEmitted||(t.ended=!0,b.default.nextTick(Z4,t,e))}function Z4(e,t){if(ze("endReadableNT",e.endEmitted,e.length),!e.endEmitted&&e.length===0&&(e.endEmitted=!0,t.readable=!1,t.emit("end"),e.autoDestroy)){var r=t._writableState;(!r||r.autoDestroy&&r.finished)&&t.destroy()}}typeof Symbol=="function"&&(ht.from=function(e,t){return gy===void 0&&(gy=_I()),gy(ht,e,t)});function PI(e,t){for(var r=0,i=e.length;r<i;r++)if(e[r]===t)return r;return-1}});var Sy=T((tie,BI)=>{"use strict";g();BI.exports=Vo;var dp=Ms().codes,$4=dp.ERR_METHOD_NOT_IMPLEMENTED,X4=dp.ERR_MULTIPLE_CALLBACK,J4=dp.ERR_TRANSFORM_ALREADY_TRANSFORMING,Q4=dp.ERR_TRANSFORM_WITH_LENGTH_0,pp=Ds();Rt()(Vo,pp);function e5(e,t){var r=this._transformState;r.transforming=!1;var i=r.writecb;if(i===null)return this.emit("error",new X4);r.writechunk=null,r.writecb=null,t!=null&&this.push(t),i(e);var n=this._readableState;n.reading=!1,(n.needReadable||n.length<n.highWaterMark)&&this._read(n.highWaterMark)}function Vo(e){if(!(this instanceof Vo))return new Vo(e);pp.call(this,e),this._transformState={afterTransform:e5.bind(this),needTransform:!1,transforming:!1,writecb:null,writechunk:null,writeencoding:null},this._readableState.needReadable=!0,this._readableState.sync=!1,e&&(typeof e.transform=="function"&&(this._transform=e.transform),typeof e.flush=="function"&&(this._flush=e.flush)),this.on("prefinish",t5)}function t5(){var e=this;typeof this._flush=="function"&&!this._readableState.destroyed?this._flush(function(t,r){kI(e,t,r)}):kI(this,null,null)}Vo.prototype.push=function(e,t){return this._transformState.needTransform=!1,pp.prototype.push.call(this,e,t)};Vo.prototype._transform=function(e,t,r){r(new $4("_transform()"))};Vo.prototype._write=function(e,t,r){var i=this._transformState;if(i.writecb=r,i.writechunk=e,i.writeencoding=t,!i.transforming){var n=this._readableState;(i.needTransform||n.needReadable||n.length<n.highWaterMark)&&this._read(n.highWaterMark)}};Vo.prototype._read=function(e){var t=this._transformState;t.writechunk!==null&&!t.transforming?(t.transforming=!0,this._transform(t.writechunk,t.writeencoding,t.afterTransform)):t.needTransform=!0};Vo.prototype._destroy=function(e,t){pp.prototype._destroy.call(this,e,function(r){t(r)})};function kI(e,t,r){if(t)return e.emit("error",t);if(r!=null&&e.push(r),e._writableState.length)throw new Q4;if(e._transformState.transforming)throw new J4;return e.push(null)}});var LI=T((iie,CI)=>{"use strict";g();CI.exports=rl;var NI=Sy();Rt()(rl,NI);function rl(e){if(!(this instanceof rl))return new rl(e);NI.call(this,e)}rl.prototype._transform=function(e,t,r){r(null,e)}});var UI=T((oie,qI)=>{"use strict";g();var Ey;function r5(e){var t=!1;return function(){t||(t=!0,e.apply(void 0,arguments))}}var HI=Ms().codes,i5=HI.ERR_MISSING_ARGS,n5=HI.ERR_STREAM_DESTROYED;function MI(e){if(e)throw e}function o5(e){return e.setHeader&&typeof e.abort=="function"}function a5(e,t,r,i){i=r5(i);var n=!1;e.on("close",function(){n=!0}),Ey===void 0&&(Ey=sp()),Ey(e,{readable:t,writable:r},function(a){if(a)return i(a);n=!0,i()});var o=!1;return function(a){if(!n&&!o){if(o=!0,o5(e))return e.abort();if(typeof e.destroy=="function")return e.destroy();i(a||new n5("pipe"))}}}function DI(e){e()}function s5(e,t){return e.pipe(t)}function u5(e){return!e.length||typeof e[e.length-1]!="function"?MI:e.pop()}function c5(){for(var e=arguments.length,t=new Array(e),r=0;r<e;r++)t[r]=arguments[r];var i=u5(t);if(Array.isArray(t[0])&&(t=t[0]),t.length<2)throw new i5("streams");var n,o=t.map(function(a,s){var u=s<t.length-1,c=s>0;return a5(a,u,c,function(l){n||(n=l),l&&o.forEach(DI),!u&&(o.forEach(DI),i(n))})});return t.reduce(s5)}qI.exports=c5});var gp=T((sie,FI)=>{g();FI.exports=an;var xy=Vu().EventEmitter,f5=Rt();f5(an,xy);an.Readable=uy();an.Writable=oy();an.Duplex=Ds();an.Transform=Sy();an.PassThrough=LI();an.finished=sp();an.pipeline=UI();an.Stream=an;function an(){xy.call(this)}an.prototype.pipe=function(e,t){var r=this;function i(l){e.writable&&e.write(l)===!1&&r.pause&&r.pause()}r.on("data",i);function n(){r.readable&&r.resume&&r.resume()}e.on("drain",n),!e._isStdio&&(!t||t.end!==!1)&&(r.on("end",a),r.on("close",s));var o=!1;function a(){o||(o=!0,e.end())}function s(){o||(o=!0,typeof e.destroy=="function"&&e.destroy())}function u(l){if(c(),xy.listenerCount(this,"error")===0)throw l}r.on("error",u),e.on("error",u);function c(){r.removeListener("data",i),e.removeListener("drain",n),r.removeListener("end",a),r.removeListener("close",s),r.removeListener("error",u),e.removeListener("error",u),r.removeListener("end",c),r.removeListener("close",c),e.removeListener("close",c)}return r.on("end",c),r.on("close",c),e.on("close",c),e.emit("pipe",r),e}});var KI=T((cie,zI)=>{"use strict";g();var to=ii().Buffer,jI=gp().Transform,l5=Rt();function Ma(e){jI.call(this),this._block=to.allocUnsafe(e),this._blockSize=e,this._blockOffset=0,this._length=[0,0,0,0],this._finalized=!1}l5(Ma,jI);Ma.prototype._transform=function(e,t,r){var i=null;try{this.update(e,t)}catch(n){i=n}r(i)};Ma.prototype._flush=function(e){var t=null;try{this.push(this.digest())}catch(r){t=r}e(t)};var h5=typeof Uint8Array<"u",d5=typeof ArrayBuffer<"u"&&typeof Uint8Array<"u"&&ArrayBuffer.isView&&(to.prototype instanceof Uint8Array||to.TYPED_ARRAY_SUPPORT);function p5(e,t){if(e instanceof to)return e;if(typeof e=="string")return to.from(e,t);if(d5&&ArrayBuffer.isView(e)){if(e.byteLength===0)return to.alloc(0);var r=to.from(e.buffer,e.byteOffset,e.byteLength);if(r.byteLength===e.byteLength)return r}if(h5&&e instanceof Uint8Array||to.isBuffer(e)&&e.constructor&&typeof e.constructor.isBuffer=="function"&&e.constructor.isBuffer(e))return to.from(e);throw new TypeError('The "data" argument must be of type string or an instance of Buffer, TypedArray, or DataView.')}Ma.prototype.update=function(e,t){if(this._finalized)throw new Error("Digest already called");e=p5(e,t);for(var r=this._block,i=0;this._blockOffset+e.length-i>=this._blockSize;){for(var n=this._blockOffset;n<this._blockSize;)r[n++]=e[i++];this._update(),this._blockOffset=0}for(;i<e.length;)r[this._blockOffset++]=e[i++];for(var o=0,a=e.length*8;a>0;++o)this._length[o]+=a,a=this._length[o]/4294967296|0,a>0&&(this._length[o]-=4294967296*a);return this};Ma.prototype._update=function(){throw new Error("_update is not implemented")};Ma.prototype.digest=function(e){if(this._finalized)throw new Error("Digest already called");this._finalized=!0;var t=this._digest();e!==void 0&&(t=t.toString(e)),this._block.fill(0),this._blockOffset=0;for(var r=0;r<4;++r)this._length[r]=0;return t};Ma.prototype._digest=function(){throw new Error("_digest is not implemented")};zI.exports=Ma});var Oy=T((lie,GI)=>{"use strict";g();var g5=Rt(),VI=KI(),m5=ii().Buffer,v5=new Array(16);function mp(){VI.call(this,64),this._a=1732584193,this._b=4023233417,this._c=2562383102,this._d=271733878}g5(mp,VI);mp.prototype._update=function(){for(var e=v5,t=0;t<16;++t)e[t]=this._block.readInt32LE(t*4);var r=this._a,i=this._b,n=this._c,o=this._d;r=ci(r,i,n,o,e[0],3614090360,7),o=ci(o,r,i,n,e[1],3905402710,12),n=ci(n,o,r,i,e[2],606105819,17),i=ci(i,n,o,r,e[3],3250441966,22),r=ci(r,i,n,o,e[4],4118548399,7),o=ci(o,r,i,n,e[5],1200080426,12),n=ci(n,o,r,i,e[6],2821735955,17),i=ci(i,n,o,r,e[7],4249261313,22),r=ci(r,i,n,o,e[8],1770035416,7),o=ci(o,r,i,n,e[9],2336552879,12),n=ci(n,o,r,i,e[10],4294925233,17),i=ci(i,n,o,r,e[11],2304563134,22),r=ci(r,i,n,o,e[12],1804603682,7),o=ci(o,r,i,n,e[13],4254626195,12),n=ci(n,o,r,i,e[14],2792965006,17),i=ci(i,n,o,r,e[15],1236535329,22),r=fi(r,i,n,o,e[1],4129170786,5),o=fi(o,r,i,n,e[6],3225465664,9),n=fi(n,o,r,i,e[11],643717713,14),i=fi(i,n,o,r,e[0],3921069994,20),r=fi(r,i,n,o,e[5],3593408605,5),o=fi(o,r,i,n,e[10],38016083,9),n=fi(n,o,r,i,e[15],3634488961,14),i=fi(i,n,o,r,e[4],3889429448,20),r=fi(r,i,n,o,e[9],568446438,5),o=fi(o,r,i,n,e[14],3275163606,9),n=fi(n,o,r,i,e[3],4107603335,14),i=fi(i,n,o,r,e[8],1163531501,20),r=fi(r,i,n,o,e[13],2850285829,5),o=fi(o,r,i,n,e[2],4243563512,9),n=fi(n,o,r,i,e[7],1735328473,14),i=fi(i,n,o,r,e[12],2368359562,20),r=li(r,i,n,o,e[5],4294588738,4),o=li(o,r,i,n,e[8],2272392833,11),n=li(n,o,r,i,e[11],1839030562,16),i=li(i,n,o,r,e[14],4259657740,23),r=li(r,i,n,o,e[1],2763975236,4),o=li(o,r,i,n,e[4],1272893353,11),n=li(n,o,r,i,e[7],4139469664,16),i=li(i,n,o,r,e[10],3200236656,23),r=li(r,i,n,o,e[13],681279174,4),o=li(o,r,i,n,e[0],3936430074,11),n=li(n,o,r,i,e[3],3572445317,16),i=li(i,n,o,r,e[6],76029189,23),r=li(r,i,n,o,e[9],3654602809,4),o=li(o,r,i,n,e[12],3873151461,11),n=li(n,o,r,i,e[15],530742520,16),i=li(i,n,o,r,e[2],3299628645,23),r=hi(r,i,n,o,e[0],4096336452,6),o=hi(o,r,i,n,e[7],1126891415,10),n=hi(n,o,r,i,e[14],2878612391,15),i=hi(i,n,o,r,e[5],4237533241,21),r=hi(r,i,n,o,e[12],1700485571,6),o=hi(o,r,i,n,e[3],2399980690,10),n=hi(n,o,r,i,e[10],4293915773,15),i=hi(i,n,o,r,e[1],2240044497,21),r=hi(r,i,n,o,e[8],1873313359,6),o=hi(o,r,i,n,e[15],4264355552,10),n=hi(n,o,r,i,e[6],2734768916,15),i=hi(i,n,o,r,e[13],1309151649,21),r=hi(r,i,n,o,e[4],4149444226,6),o=hi(o,r,i,n,e[11],3174756917,10),n=hi(n,o,r,i,e[2],718787259,15),i=hi(i,n,o,r,e[9],3951481745,21),this._a=this._a+r|0,this._b=this._b+i|0,this._c=this._c+n|0,this._d=this._d+o|0};mp.prototype._digest=function(){this._block[this._blockOffset++]=128,this._blockOffset>56&&(this._block.fill(0,this._blockOffset,64),this._update(),this._blockOffset=0),this._block.fill(0,this._blockOffset,56),this._block.writeUInt32LE(this._length[0],56),this._block.writeUInt32LE(this._length[1],60),this._update();var e=m5.allocUnsafe(16);return e.writeInt32LE(this._a,0),e.writeInt32LE(this._b,4),e.writeInt32LE(this._c,8),e.writeInt32LE(this._d,12),e};function vp(e,t){return e<<t|e>>>32-t}function ci(e,t,r,i,n,o,a){return vp(e+(t&r|~t&i)+n+o|0,a)+t|0}function fi(e,t,r,i,n,o,a){return vp(e+(t&i|r&~i)+n+o|0,a)+t|0}function li(e,t,r,i,n,o,a){return vp(e+(t^r^i)+n+o|0,a)+t|0}function hi(e,t,r,i,n,o,a){return vp(e+(r^(t|~i))+n+o|0,a)+t|0}GI.exports=mp});var YI=T((die,WI)=>{g();var y5={}.toString;WI.exports=Array.isArray||function(e){return y5.call(e)=="[object Array]"}});var $I=T((gie,ZI)=>{"use strict";g();var b5=ks(),_5=Ra(),w5=_5("TypedArray.prototype.buffer",!0),S5=z0();ZI.exports=w5||function(t){if(!S5(t))throw new b5("Not a Typed Array");return t.buffer}});var yp=T((vie,JI)=>{"use strict";g();var xn=ii().Buffer,E5=YI(),x5=$I(),O5=ArrayBuffer.isView||function(t){try{return x5(t),!0}catch{return!1}},I5=typeof Uint8Array<"u",XI=typeof ArrayBuffer<"u"&&typeof Uint8Array<"u",A5=XI&&(xn.prototype instanceof Uint8Array||xn.TYPED_ARRAY_SUPPORT);JI.exports=function(t,r){if(xn.isBuffer(t))return t.constructor&&!("isBuffer"in t)?xn.from(t):t;if(typeof t=="string")return xn.from(t,r);if(XI&&O5(t)){if(t.byteLength===0)return xn.alloc(0);if(A5){var i=xn.from(t.buffer,t.byteOffset,t.byteLength);if(i.byteLength===t.byteLength)return i}var n=t instanceof Uint8Array?t:new Uint8Array(t.buffer,t.byteOffset,t.byteLength),o=xn.from(n);if(o.length===t.byteLength)return o}if(I5&&t instanceof Uint8Array)return xn.from(t);var a=E5(t);if(a)for(var s=0;s<t.length;s+=1){var u=t[s];if(typeof u!="number"||u<0||u>255||~~u!==u)throw new RangeError("Array items must be numbers in the range 0-255.")}if(a||xn.isBuffer(t)&&t.constructor&&typeof t.constructor.isBuffer=="function"&&t.constructor.isBuffer(t))return xn.from(t);throw new TypeError('The "data" argument must be a string, an Array, a Buffer, a Uint8Array, or a DataView.')}});var rA=T((bie,tA)=>{"use strict";g();var T5=ii().Buffer,P5=yp(),eA=typeof Uint8Array<"u",R5=eA&&typeof ArrayBuffer<"u",QI=R5&&ArrayBuffer.isView;tA.exports=function(e,t){if(typeof e=="string"||T5.isBuffer(e)||eA&&e instanceof Uint8Array||QI&&QI(e))return P5(e,t);throw new TypeError('The "data" argument must be a string, a Buffer, a Uint8Array, or a DataView')}});var il=T((wie,Iy)=>{"use strict";g();typeof b.default>"u"||!b.default.version||b.default.version.indexOf("v0.")===0||b.default.version.indexOf("v1.")===0&&b.default.version.indexOf("v1.8.")!==0?Iy.exports={nextTick:k5}:Iy.exports=b.default;function k5(e,t,r,i){if(typeof e!="function")throw new TypeError('"callback" argument must be a function');var n=arguments.length,o,a;switch(n){case 0:case 1:return b.default.nextTick(e);case 2:return b.default.nextTick(function(){e.call(null,t)});case 3:return b.default.nextTick(function(){e.call(null,t,r)});case 4:return b.default.nextTick(function(){e.call(null,t,r,i)});default:for(o=new Array(n-1),a=0;a<o.length;)o[a++]=arguments[a];return b.default.nextTick(function(){e.apply(null,o)})}}});var nA=T((Eie,iA)=>{g();var B5={}.toString;iA.exports=Array.isArray||function(e){return B5.call(e)=="[object Array]"}});var Ay=T((Oie,oA)=>{g();oA.exports=Vu().EventEmitter});var _p=T((Ty,sA)=>{g();var bp=rr(),Go=bp.Buffer;function aA(e,t){for(var r in e)t[r]=e[r]}Go.from&&Go.alloc&&Go.allocUnsafe&&Go.allocUnsafeSlow?sA.exports=bp:(aA(bp,Ty),Ty.Buffer=sc);function sc(e,t,r){return Go(e,t,r)}aA(Go,sc);sc.from=function(e,t,r){if(typeof e=="number")throw new TypeError("Argument must not be a number");return Go(e,t,r)};sc.alloc=function(e,t,r){if(typeof e!="number")throw new TypeError("Argument must be a number");var i=Go(e);return t!==void 0?typeof r=="string"?i.fill(t,r):i.fill(t):i.fill(0),i};sc.allocUnsafe=function(e){if(typeof e!="number")throw new TypeError("Argument must be a number");return Go(e)};sc.allocUnsafeSlow=function(e){if(typeof e!="number")throw new TypeError("Argument must be a number");return bp.SlowBuffer(e)}});var uc=T(di=>{g();function N5(e){return Array.isArray?Array.isArray(e):wp(e)==="[object Array]"}di.isArray=N5;function C5(e){return typeof e=="boolean"}di.isBoolean=C5;function L5(e){return e===null}di.isNull=L5;function M5(e){return e==null}di.isNullOrUndefined=M5;function D5(e){return typeof e=="number"}di.isNumber=D5;function H5(e){return typeof e=="string"}di.isString=H5;function q5(e){return typeof e=="symbol"}di.isSymbol=q5;function U5(e){return e===void 0}di.isUndefined=U5;function F5(e){return wp(e)==="[object RegExp]"}di.isRegExp=F5;function j5(e){return typeof e=="object"&&e!==null}di.isObject=j5;function z5(e){return wp(e)==="[object Date]"}di.isDate=z5;function K5(e){return wp(e)==="[object Error]"||e instanceof Error}di.isError=K5;function V5(e){return typeof e=="function"}di.isFunction=V5;function G5(e){return e===null||typeof e=="boolean"||typeof e=="number"||typeof e=="string"||typeof e=="symbol"||typeof e>"u"}di.isPrimitive=G5;di.isBuffer=rr().Buffer.isBuffer;function wp(e){return Object.prototype.toString.call(e)}});var cA=T((Rie,Py)=>{"use strict";g();function W5(e,t){if(!(e instanceof t))throw new TypeError("Cannot call a class as a function")}var uA=_p().Buffer,nl=nn();function Y5(e,t,r){e.copy(t,r)}Py.exports=(function(){function e(){W5(this,e),this.head=null,this.tail=null,this.length=0}return e.prototype.push=function(r){var i={data:r,next:null};this.length>0?this.tail.next=i:this.head=i,this.tail=i,++this.length},e.prototype.unshift=function(r){var i={data:r,next:this.head};this.length===0&&(this.tail=i),this.head=i,++this.length},e.prototype.shift=function(){if(this.length!==0){var r=this.head.data;return this.length===1?this.head=this.tail=null:this.head=this.head.next,--this.length,r}},e.prototype.clear=function(){this.head=this.tail=null,this.length=0},e.prototype.join=function(r){if(this.length===0)return"";for(var i=this.head,n=""+i.data;i=i.next;)n+=r+i.data;return n},e.prototype.concat=function(r){if(this.length===0)return uA.alloc(0);for(var i=uA.allocUnsafe(r>>>0),n=this.head,o=0;n;)Y5(n.data,i,o),o+=n.data.length,n=n.next;return i},e})();nl&&nl.inspect&&nl.inspect.custom&&(Py.exports.prototype[nl.inspect.custom]=function(){var e=nl.inspect({length:this.length});return this.constructor.name+" "+e})});var Ry=T((Bie,fA)=>{"use strict";g();var Sp=il();function Z5(e,t){var r=this,i=this._readableState&&this._readableState.destroyed,n=this._writableState&&this._writableState.destroyed;return i||n?(t?t(e):e&&(this._writableState?this._writableState.errorEmitted||(this._writableState.errorEmitted=!0,Sp.nextTick(Ep,this,e)):Sp.nextTick(Ep,this,e)),this):(this._readableState&&(this._readableState.destroyed=!0),this._writableState&&(this._writableState.destroyed=!0),this._destroy(e||null,function(o){!t&&o?r._writableState?r._writableState.errorEmitted||(r._writableState.errorEmitted=!0,Sp.nextTick(Ep,r,o)):Sp.nextTick(Ep,r,o):t&&t(o)}),this)}function $5(){this._readableState&&(this._readableState.destroyed=!1,this._readableState.reading=!1,this._readableState.ended=!1,this._readableState.endEmitted=!1),this._writableState&&(this._writableState.destroyed=!1,this._writableState.ended=!1,this._writableState.ending=!1,this._writableState.finalCalled=!1,this._writableState.prefinished=!1,this._writableState.finished=!1,this._writableState.errorEmitted=!1)}function Ep(e,t){e.emit("error",t)}fA.exports={destroy:Z5,undestroy:$5}});var By=T((Cie,yA)=>{"use strict";g();var Fs=il();yA.exports=Ir;function hA(e){var t=this;this.next=null,this.entry=null,this.finish=function(){pj(t,e)}}var X5=!b.default.browser&&["v0.10","v0.9."].indexOf(b.default.version.slice(0,5))>-1?setImmediate:Fs.nextTick,cc;Ir.WritableState=al;var dA=Object.create(uc());dA.inherits=Rt();var J5={deprecate:ry()},pA=Ay(),Op=_p().Buffer,Q5=(typeof globalThis<"u"?globalThis:typeof window<"u"?window:typeof self<"u"?self:{}).Uint8Array||function(){};function ej(e){return Op.from(e)}function tj(e){return Op.isBuffer(e)||e instanceof Q5}var gA=Ry();dA.inherits(Ir,pA);function rj(){}function al(e,t){cc=cc||js(),e=e||{};var r=t instanceof cc;this.objectMode=!!e.objectMode,r&&(this.objectMode=this.objectMode||!!e.writableObjectMode);var i=e.highWaterMark,n=e.writableHighWaterMark,o=this.objectMode?16:16*1024;i||i===0?this.highWaterMark=i:r&&(n||n===0)?this.highWaterMark=n:this.highWaterMark=o,this.highWaterMark=Math.floor(this.highWaterMark),this.finalCalled=!1,this.needDrain=!1,this.ending=!1,this.ended=!1,this.finished=!1,this.destroyed=!1;var a=e.decodeStrings===!1;this.decodeStrings=!a,this.defaultEncoding=e.defaultEncoding||"utf8",this.length=0,this.writing=!1,this.corked=0,this.sync=!0,this.bufferProcessing=!1,this.onwrite=function(s){cj(t,s)},this.writecb=null,this.writelen=0,this.bufferedRequest=null,this.lastBufferedRequest=null,this.pendingcb=0,this.prefinished=!1,this.errorEmitted=!1,this.bufferedRequestCount=0,this.corkedRequestsFree=new hA(this)}al.prototype.getBuffer=function(){for(var t=this.bufferedRequest,r=[];t;)r.push(t),t=t.next;return r};(function(){try{Object.defineProperty(al.prototype,"buffer",{get:J5.deprecate(function(){return this.getBuffer()},"_writableState.buffer is deprecated. Use _writableState.getBuffer instead.","DEP0003")})}catch{}})();var xp;typeof Symbol=="function"&&Symbol.hasInstance&&typeof Function.prototype[Symbol.hasInstance]=="function"?(xp=Function.prototype[Symbol.hasInstance],Object.defineProperty(Ir,Symbol.hasInstance,{value:function(e){return xp.call(this,e)?!0:this!==Ir?!1:e&&e._writableState instanceof al}})):xp=function(e){return e instanceof this};function Ir(e){if(cc=cc||js(),!xp.call(Ir,this)&&!(this instanceof cc))return new Ir(e);this._writableState=new al(e,this),this.writable=!0,e&&(typeof e.write=="function"&&(this._write=e.write),typeof e.writev=="function"&&(this._writev=e.writev),typeof e.destroy=="function"&&(this._destroy=e.destroy),typeof e.final=="function"&&(this._final=e.final)),pA.call(this)}Ir.prototype.pipe=function(){this.emit("error",new Error("Cannot pipe, not readable"))};function ij(e,t){var r=new Error("write after end");e.emit("error",r),Fs.nextTick(t,r)}function nj(e,t,r,i){var n=!0,o=!1;return r===null?o=new TypeError("May not write null values to stream"):typeof r!="string"&&r!==void 0&&!t.objectMode&&(o=new TypeError("Invalid non-string/buffer chunk")),o&&(e.emit("error",o),Fs.nextTick(i,o),n=!1),n}Ir.prototype.write=function(e,t,r){var i=this._writableState,n=!1,o=!i.objectMode&&tj(e);return o&&!Op.isBuffer(e)&&(e=ej(e)),typeof t=="function"&&(r=t,t=null),o?t="buffer":t||(t=i.defaultEncoding),typeof r!="function"&&(r=rj),i.ended?ij(this,r):(o||nj(this,i,e,r))&&(i.pendingcb++,n=aj(this,i,o,e,t,r)),n};Ir.prototype.cork=function(){var e=this._writableState;e.corked++};Ir.prototype.uncork=function(){var e=this._writableState;e.corked&&(e.corked--,!e.writing&&!e.corked&&!e.bufferProcessing&&e.bufferedRequest&&mA(this,e))};Ir.prototype.setDefaultEncoding=function(t){if(typeof t=="string"&&(t=t.toLowerCase()),!(["hex","utf8","utf-8","ascii","binary","base64","ucs2","ucs-2","utf16le","utf-16le","raw"].indexOf((t+"").toLowerCase())>-1))throw new TypeError("Unknown encoding: "+t);return this._writableState.defaultEncoding=t,this};function oj(e,t,r){return!e.objectMode&&e.decodeStrings!==!1&&typeof t=="string"&&(t=Op.from(t,r)),t}Object.defineProperty(Ir.prototype,"writableHighWaterMark",{enumerable:!1,get:function(){return this._writableState.highWaterMark}});function aj(e,t,r,i,n,o){if(!r){var a=oj(t,i,n);i!==a&&(r=!0,n="buffer",i=a)}var s=t.objectMode?1:i.length;t.length+=s;var u=t.length<t.highWaterMark;if(u||(t.needDrain=!0),t.writing||t.corked){var c=t.lastBufferedRequest;t.lastBufferedRequest={chunk:i,encoding:n,isBuf:r,callback:o,next:null},c?c.next=t.lastBufferedRequest:t.bufferedRequest=t.lastBufferedRequest,t.bufferedRequestCount+=1}else ky(e,t,!1,s,i,n,o);return u}function ky(e,t,r,i,n,o,a){t.writelen=i,t.writecb=a,t.writing=!0,t.sync=!0,r?e._writev(n,t.onwrite):e._write(n,o,t.onwrite),t.sync=!1}function sj(e,t,r,i,n){--t.pendingcb,r?(Fs.nextTick(n,i),Fs.nextTick(ol,e,t),e._writableState.errorEmitted=!0,e.emit("error",i)):(n(i),e._writableState.errorEmitted=!0,e.emit("error",i),ol(e,t))}function uj(e){e.writing=!1,e.writecb=null,e.length-=e.writelen,e.writelen=0}function cj(e,t){var r=e._writableState,i=r.sync,n=r.writecb;if(uj(r),t)sj(e,r,i,t,n);else{var o=vA(r);!o&&!r.corked&&!r.bufferProcessing&&r.bufferedRequest&&mA(e,r),i?X5(lA,e,r,o,n):lA(e,r,o,n)}}function lA(e,t,r,i){r||fj(e,t),t.pendingcb--,i(),ol(e,t)}function fj(e,t){t.length===0&&t.needDrain&&(t.needDrain=!1,e.emit("drain"))}function mA(e,t){t.bufferProcessing=!0;var r=t.bufferedRequest;if(e._writev&&r&&r.next){var i=t.bufferedRequestCount,n=new Array(i),o=t.corkedRequestsFree;o.entry=r;for(var a=0,s=!0;r;)n[a]=r,r.isBuf||(s=!1),r=r.next,a+=1;n.allBuffers=s,ky(e,t,!0,t.length,n,"",o.finish),t.pendingcb++,t.lastBufferedRequest=null,o.next?(t.corkedRequestsFree=o.next,o.next=null):t.corkedRequestsFree=new hA(t),t.bufferedRequestCount=0}else{for(;r;){var u=r.chunk,c=r.encoding,l=r.callback,p=t.objectMode?1:u.length;if(ky(e,t,!1,p,u,c,l),r=r.next,t.bufferedRequestCount--,t.writing)break}r===null&&(t.lastBufferedRequest=null)}t.bufferedRequest=r,t.bufferProcessing=!1}Ir.prototype._write=function(e,t,r){r(new Error("_write() is not implemented"))};Ir.prototype._writev=null;Ir.prototype.end=function(e,t,r){var i=this._writableState;typeof e=="function"?(r=e,e=null,t=null):typeof t=="function"&&(r=t,t=null),e!=null&&this.write(e,t),i.corked&&(i.corked=1,this.uncork()),i.ending||dj(this,i,r)};function vA(e){return e.ending&&e.length===0&&e.bufferedRequest===null&&!e.finished&&!e.writing}function lj(e,t){e._final(function(r){t.pendingcb--,r&&e.emit("error",r),t.prefinished=!0,e.emit("prefinish"),ol(e,t)})}function hj(e,t){!t.prefinished&&!t.finalCalled&&(typeof e._final=="function"?(t.pendingcb++,t.finalCalled=!0,Fs.nextTick(lj,e,t)):(t.prefinished=!0,e.emit("prefinish")))}function ol(e,t){var r=vA(t);return r&&(hj(e,t),t.pendingcb===0&&(t.finished=!0,e.emit("finish"))),r}function dj(e,t,r){t.ending=!0,ol(e,t),r&&(t.finished?Fs.nextTick(r):e.once("finish",r)),t.ended=!0,e.writable=!1}function pj(e,t,r){var i=e.entry;for(e.entry=null;i;){var n=i.callback;t.pendingcb--,n(r),i=i.next}t.corkedRequestsFree.next=e}Object.defineProperty(Ir.prototype,"destroyed",{get:function(){return this._writableState===void 0?!1:this._writableState.destroyed},set:function(e){this._writableState&&(this._writableState.destroyed=e)}});Ir.prototype.destroy=gA.destroy;Ir.prototype._undestroy=gA.undestroy;Ir.prototype._destroy=function(e,t){this.end(),t(e)}});var js=T((Mie,SA)=>{"use strict";g();var bA=il(),gj=Object.keys||function(e){var t=[];for(var r in e)t.push(r);return t};SA.exports=Wo;var _A=Object.create(uc());_A.inherits=Rt();var wA=Ly(),Cy=By();_A.inherits(Wo,wA);for(Ny=gj(Cy.prototype),Ip=0;Ip<Ny.length;Ip++)Ap=Ny[Ip],Wo.prototype[Ap]||(Wo.prototype[Ap]=Cy.prototype[Ap]);var Ny,Ap,Ip;function Wo(e){if(!(this instanceof Wo))return new Wo(e);wA.call(this,e),Cy.call(this,e),e&&e.readable===!1&&(this.readable=!1),e&&e.writable===!1&&(this.writable=!1),this.allowHalfOpen=!0,e&&e.allowHalfOpen===!1&&(this.allowHalfOpen=!1),this.once("end",mj)}Object.defineProperty(Wo.prototype,"writableHighWaterMark",{enumerable:!1,get:function(){return this._writableState.highWaterMark}});function mj(){this.allowHalfOpen||this._writableState.ended||bA.nextTick(vj,this)}function vj(e){e.end()}Object.defineProperty(Wo.prototype,"destroyed",{get:function(){return this._readableState===void 0||this._writableState===void 0?!1:this._readableState.destroyed&&this._writableState.destroyed},set:function(e){this._readableState===void 0||this._writableState===void 0||(this._readableState.destroyed=e,this._writableState.destroyed=e)}});Wo.prototype._destroy=function(e,t){this.push(null),this.end(),bA.nextTick(t,e)}});var Ly=T((qie,CA)=>{"use strict";g();var lc=il();CA.exports=jt;var yj=nA(),sl;jt.ReadableState=PA;var Hie=Vu().EventEmitter,IA=function(e,t){return e.listeners(t).length},Uy=Ay(),ul=_p().Buffer,bj=(typeof globalThis<"u"?globalThis:typeof window<"u"?window:typeof self<"u"?self:{}).Uint8Array||function(){};function _j(e){return ul.from(e)}function wj(e){return ul.isBuffer(e)||e instanceof bj}var AA=Object.create(uc());AA.inherits=Rt();var My=nn(),yt=void 0;My&&My.debuglog?yt=My.debuglog("stream"):yt=function(){};var Sj=cA(),TA=Ry(),fc;AA.inherits(jt,Uy);var Dy=["error","close","destroy","pause","resume"];function Ej(e,t,r){if(typeof e.prependListener=="function")return e.prependListener(t,r);!e._events||!e._events[t]?e.on(t,r):yj(e._events[t])?e._events[t].unshift(r):e._events[t]=[r,e._events[t]]}function PA(e,t){sl=sl||js(),e=e||{};var r=t instanceof sl;this.objectMode=!!e.objectMode,r&&(this.objectMode=this.objectMode||!!e.readableObjectMode);var i=e.highWaterMark,n=e.readableHighWaterMark,o=this.objectMode?16:16*1024;i||i===0?this.highWaterMark=i:r&&(n||n===0)?this.highWaterMark=n:this.highWaterMark=o,this.highWaterMark=Math.floor(this.highWaterMark),this.buffer=new Sj,this.length=0,this.pipes=null,this.pipesCount=0,this.flowing=null,this.ended=!1,this.endEmitted=!1,this.reading=!1,this.sync=!0,this.needReadable=!1,this.emittedReadable=!1,this.readableListening=!1,this.resumeScheduled=!1,this.destroyed=!1,this.defaultEncoding=e.defaultEncoding||"utf8",this.awaitDrain=0,this.readingMore=!1,this.decoder=null,this.encoding=null,e.encoding&&(fc||(fc=nc().StringDecoder),this.decoder=new fc(e.encoding),this.encoding=e.encoding)}function jt(e){if(sl=sl||js(),!(this instanceof jt))return new jt(e);this._readableState=new PA(e,this),this.readable=!0,e&&(typeof e.read=="function"&&(this._read=e.read),typeof e.destroy=="function"&&(this._destroy=e.destroy)),Uy.call(this)}Object.defineProperty(jt.prototype,"destroyed",{get:function(){return this._readableState===void 0?!1:this._readableState.destroyed},set:function(e){this._readableState&&(this._readableState.destroyed=e)}});jt.prototype.destroy=TA.destroy;jt.prototype._undestroy=TA.undestroy;jt.prototype._destroy=function(e,t){this.push(null),t(e)};jt.prototype.push=function(e,t){var r=this._readableState,i;return r.objectMode?i=!0:typeof e=="string"&&(t=t||r.defaultEncoding,t!==r.encoding&&(e=ul.from(e,t),t=""),i=!0),RA(this,e,t,!1,i)};jt.prototype.unshift=function(e){return RA(this,e,null,!0,!1)};function RA(e,t,r,i,n){var o=e._readableState;if(t===null)o.reading=!1,Aj(e,o);else{var a;n||(a=xj(o,t)),a?e.emit("error",a):o.objectMode||t&&t.length>0?(typeof t!="string"&&!o.objectMode&&Object.getPrototypeOf(t)!==ul.prototype&&(t=_j(t)),i?o.endEmitted?e.emit("error",new Error("stream.unshift() after end event")):Hy(e,o,t,!0):o.ended?e.emit("error",new Error("stream.push() after EOF")):(o.reading=!1,o.decoder&&!r?(t=o.decoder.write(t),o.objectMode||t.length!==0?Hy(e,o,t,!1):kA(e,o)):Hy(e,o,t,!1))):i||(o.reading=!1)}return Oj(o)}function Hy(e,t,r,i){t.flowing&&t.length===0&&!t.sync?(e.emit("data",r),e.read(0)):(t.length+=t.objectMode?1:r.length,i?t.buffer.unshift(r):t.buffer.push(r),t.needReadable&&Tp(e)),kA(e,t)}function xj(e,t){var r;return!wj(t)&&typeof t!="string"&&t!==void 0&&!e.objectMode&&(r=new TypeError("Invalid non-string/buffer chunk")),r}function Oj(e){return!e.ended&&(e.needReadable||e.length<e.highWaterMark||e.length===0)}jt.prototype.isPaused=function(){return this._readableState.flowing===!1};jt.prototype.setEncoding=function(e){return fc||(fc=nc().StringDecoder),this._readableState.decoder=new fc(e),this._readableState.encoding=e,this};var EA=8388608;function Ij(e){return e>=EA?e=EA:(e--,e|=e>>>1,e|=e>>>2,e|=e>>>4,e|=e>>>8,e|=e>>>16,e++),e}function xA(e,t){return e<=0||t.length===0&&t.ended?0:t.objectMode?1:e!==e?t.flowing&&t.length?t.buffer.head.data.length:t.length:(e>t.highWaterMark&&(t.highWaterMark=Ij(e)),e<=t.length?e:t.ended?t.length:(t.needReadable=!0,0))}jt.prototype.read=function(e){yt("read",e),e=parseInt(e,10);var t=this._readableState,r=e;if(e!==0&&(t.emittedReadable=!1),e===0&&t.needReadable&&(t.length>=t.highWaterMark||t.ended))return yt("read: emitReadable",t.length,t.ended),t.length===0&&t.ended?qy(this):Tp(this),null;if(e=xA(e,t),e===0&&t.ended)return t.length===0&&qy(this),null;var i=t.needReadable;yt("need readable",i),(t.length===0||t.length-e<t.highWaterMark)&&(i=!0,yt("length less than watermark",i)),t.ended||t.reading?(i=!1,yt("reading or ended",i)):i&&(yt("do read"),t.reading=!0,t.sync=!0,t.length===0&&(t.needReadable=!0),this._read(t.highWaterMark),t.sync=!1,t.reading||(e=xA(r,t)));var n;return e>0?n=BA(e,t):n=null,n===null?(t.needReadable=!0,e=0):t.length-=e,t.length===0&&(t.ended||(t.needReadable=!0),r!==e&&t.ended&&qy(this)),n!==null&&this.emit("data",n),n};function Aj(e,t){if(!t.ended){if(t.decoder){var r=t.decoder.end();r&&r.length&&(t.buffer.push(r),t.length+=t.objectMode?1:r.length)}t.ended=!0,Tp(e)}}function Tp(e){var t=e._readableState;t.needReadable=!1,t.emittedReadable||(yt("emitReadable",t.flowing),t.emittedReadable=!0,t.sync?lc.nextTick(OA,e):OA(e))}function OA(e){yt("emit readable"),e.emit("readable"),Fy(e)}function kA(e,t){t.readingMore||(t.readingMore=!0,lc.nextTick(Tj,e,t))}function Tj(e,t){for(var r=t.length;!t.reading&&!t.flowing&&!t.ended&&t.length<t.highWaterMark&&(yt("maybeReadMore read 0"),e.read(0),r!==t.length);)r=t.length;t.readingMore=!1}jt.prototype._read=function(e){this.emit("error",new Error("_read() is not implemented"))};jt.prototype.pipe=function(e,t){var r=this,i=this._readableState;switch(i.pipesCount){case 0:i.pipes=e;break;case 1:i.pipes=[i.pipes,e];break;default:i.pipes.push(e);break}i.pipesCount+=1,yt("pipe count=%d opts=%j",i.pipesCount,t);var n=(!t||t.end!==!1)&&e!==b.default.stdout&&e!==b.default.stderr,o=n?s:R;i.endEmitted?lc.nextTick(o):r.once("end",o),e.on("unpipe",a);function a(k,q){yt("onunpipe"),k===r&&q&&q.hasUnpiped===!1&&(q.hasUnpiped=!0,l())}function s(){yt("onend"),e.end()}var u=Pj(r);e.on("drain",u);var c=!1;function l(){yt("cleanup"),e.removeListener("close",_),e.removeListener("finish",I),e.removeListener("drain",u),e.removeListener("error",v),e.removeListener("unpipe",a),r.removeListener("end",s),r.removeListener("end",R),r.removeListener("data",d),c=!0,i.awaitDrain&&(!e._writableState||e._writableState.needDrain)&&u()}var p=!1;r.on("data",d);function d(k){yt("ondata"),p=!1;var q=e.write(k);q===!1&&!p&&((i.pipesCount===1&&i.pipes===e||i.pipesCount>1&&NA(i.pipes,e)!==-1)&&!c&&(yt("false write response, pause",i.awaitDrain),i.awaitDrain++,p=!0),r.pause())}function v(k){yt("onerror",k),R(),e.removeListener("error",v),IA(e,"error")===0&&e.emit("error",k)}Ej(e,"error",v);function _(){e.removeListener("finish",I),R()}e.once("close",_);function I(){yt("onfinish"),e.removeListener("close",_),R()}e.once("finish",I);function R(){yt("unpipe"),r.unpipe(e)}return e.emit("pipe",r),i.flowing||(yt("pipe resume"),r.resume()),e};function Pj(e){return function(){var t=e._readableState;yt("pipeOnDrain",t.awaitDrain),t.awaitDrain&&t.awaitDrain--,t.awaitDrain===0&&IA(e,"data")&&(t.flowing=!0,Fy(e))}}jt.prototype.unpipe=function(e){var t=this._readableState,r={hasUnpiped:!1};if(t.pipesCount===0)return this;if(t.pipesCount===1)return e&&e!==t.pipes?this:(e||(e=t.pipes),t.pipes=null,t.pipesCount=0,t.flowing=!1,e&&e.emit("unpipe",this,r),this);if(!e){var i=t.pipes,n=t.pipesCount;t.pipes=null,t.pipesCount=0,t.flowing=!1;for(var o=0;o<n;o++)i[o].emit("unpipe",this,{hasUnpiped:!1});return this}var a=NA(t.pipes,e);return a===-1?this:(t.pipes.splice(a,1),t.pipesCount-=1,t.pipesCount===1&&(t.pipes=t.pipes[0]),e.emit("unpipe",this,r),this)};jt.prototype.on=function(e,t){var r=Uy.prototype.on.call(this,e,t);if(e==="data")this._readableState.flowing!==!1&&this.resume();else if(e==="readable"){var i=this._readableState;!i.endEmitted&&!i.readableListening&&(i.readableListening=i.needReadable=!0,i.emittedReadable=!1,i.reading?i.length&&Tp(this):lc.nextTick(Rj,this))}return r};jt.prototype.addListener=jt.prototype.on;function Rj(e){yt("readable nexttick read 0"),e.read(0)}jt.prototype.resume=function(){var e=this._readableState;return e.flowing||(yt("resume"),e.flowing=!0,kj(this,e)),this};function kj(e,t){t.resumeScheduled||(t.resumeScheduled=!0,lc.nextTick(Bj,e,t))}function Bj(e,t){t.reading||(yt("resume read 0"),e.read(0)),t.resumeScheduled=!1,t.awaitDrain=0,e.emit("resume"),Fy(e),t.flowing&&!t.reading&&e.read(0)}jt.prototype.pause=function(){return yt("call pause flowing=%j",this._readableState.flowing),this._readableState.flowing!==!1&&(yt("pause"),this._readableState.flowing=!1,this.emit("pause")),this};function Fy(e){var t=e._readableState;for(yt("flow",t.flowing);t.flowing&&e.read()!==null;);}jt.prototype.wrap=function(e){var t=this,r=this._readableState,i=!1;e.on("end",function(){if(yt("wrapped end"),r.decoder&&!r.ended){var a=r.decoder.end();a&&a.length&&t.push(a)}t.push(null)}),e.on("data",function(a){if(yt("wrapped data"),r.decoder&&(a=r.decoder.write(a)),!(r.objectMode&&a==null)&&!(!r.objectMode&&(!a||!a.length))){var s=t.push(a);s||(i=!0,e.pause())}});for(var n in e)this[n]===void 0&&typeof e[n]=="function"&&(this[n]=(function(a){return function(){return e[a].apply(e,arguments)}})(n));for(var o=0;o<Dy.length;o++)e.on(Dy[o],this.emit.bind(this,Dy[o]));return this._read=function(a){yt("wrapped _read",a),i&&(i=!1,e.resume())},this};Object.defineProperty(jt.prototype,"readableHighWaterMark",{enumerable:!1,get:function(){return this._readableState.highWaterMark}});jt._fromList=BA;function BA(e,t){if(t.length===0)return null;var r;return t.objectMode?r=t.buffer.shift():!e||e>=t.length?(t.decoder?r=t.buffer.join(""):t.buffer.length===1?r=t.buffer.head.data:r=t.buffer.concat(t.length),t.buffer.clear()):r=Nj(e,t.buffer,t.decoder),r}function Nj(e,t,r){var i;return e<t.head.data.length?(i=t.head.data.slice(0,e),t.head.data=t.head.data.slice(e)):e===t.head.data.length?i=t.shift():i=r?Cj(e,t):Lj(e,t),i}function Cj(e,t){var r=t.head,i=1,n=r.data;for(e-=n.length;r=r.next;){var o=r.data,a=e>o.length?o.length:e;if(a===o.length?n+=o:n+=o.slice(0,e),e-=a,e===0){a===o.length?(++i,r.next?t.head=r.next:t.head=t.tail=null):(t.head=r,r.data=o.slice(a));break}++i}return t.length-=i,n}function Lj(e,t){var r=ul.allocUnsafe(e),i=t.head,n=1;for(i.data.copy(r),e-=i.data.length;i=i.next;){var o=i.data,a=e>o.length?o.length:e;if(o.copy(r,r.length-e,0,a),e-=a,e===0){a===o.length?(++n,i.next?t.head=i.next:t.head=t.tail=null):(t.head=i,i.data=o.slice(a));break}++n}return t.length-=n,r}function qy(e){var t=e._readableState;if(t.length>0)throw new Error('"endReadable()" called on non-empty stream');t.endEmitted||(t.ended=!0,lc.nextTick(Mj,t,e))}function Mj(e,t){!e.endEmitted&&e.length===0&&(e.endEmitted=!0,t.readable=!1,t.emit("end"))}function NA(e,t){for(var r=0,i=e.length;r<i;r++)if(e[r]===t)return r;return-1}});var jy=T((Fie,DA)=>{"use strict";g();DA.exports=Yo;var Pp=js(),MA=Object.create(uc());MA.inherits=Rt();MA.inherits(Yo,Pp);function Dj(e,t){var r=this._transformState;r.transforming=!1;var i=r.writecb;if(!i)return this.emit("error",new Error("write callback called multiple times"));r.writechunk=null,r.writecb=null,t!=null&&this.push(t),i(e);var n=this._readableState;n.reading=!1,(n.needReadable||n.length<n.highWaterMark)&&this._read(n.highWaterMark)}function Yo(e){if(!(this instanceof Yo))return new Yo(e);Pp.call(this,e),this._transformState={afterTransform:Dj.bind(this),needTransform:!1,transforming:!1,writecb:null,writechunk:null,writeencoding:null},this._readableState.needReadable=!0,this._readableState.sync=!1,e&&(typeof e.transform=="function"&&(this._transform=e.transform),typeof e.flush=="function"&&(this._flush=e.flush)),this.on("prefinish",Hj)}function Hj(){var e=this;typeof this._flush=="function"?this._flush(function(t,r){LA(e,t,r)}):LA(this,null,null)}Yo.prototype.push=function(e,t){return this._transformState.needTransform=!1,Pp.prototype.push.call(this,e,t)};Yo.prototype._transform=function(e,t,r){throw new Error("_transform() is not implemented")};Yo.prototype._write=function(e,t,r){var i=this._transformState;if(i.writecb=r,i.writechunk=e,i.writeencoding=t,!i.transforming){var n=this._readableState;(i.needTransform||n.needReadable||n.length<n.highWaterMark)&&this._read(n.highWaterMark)}};Yo.prototype._read=function(e){var t=this._transformState;t.writechunk!==null&&t.writecb&&!t.transforming?(t.transforming=!0,this._transform(t.writechunk,t.writeencoding,t.afterTransform)):t.needTransform=!0};Yo.prototype._destroy=function(e,t){var r=this;Pp.prototype._destroy.call(this,e,function(i){t(i),r.emit("close")})};function LA(e,t,r){if(t)return e.emit("error",t);if(r!=null&&e.push(r),e._writableState.length)throw new Error("Calling transform done when ws.length != 0");if(e._transformState.transforming)throw new Error("Calling transform done when still transforming");return e.push(null)}});var FA=T((zie,UA)=>{"use strict";g();UA.exports=cl;var HA=jy(),qA=Object.create(uc());qA.inherits=Rt();qA.inherits(cl,HA);function cl(e){if(!(this instanceof cl))return new cl(e);HA.call(this,e)}cl.prototype._transform=function(e,t,r){r(null,e)}});var zA=T((ro,jA)=>{g();ro=jA.exports=Ly();ro.Stream=ro;ro.Readable=ro;ro.Writable=By();ro.Duplex=js();ro.Transform=jy();ro.PassThrough=FA()});var GA=T((Gie,VA)=>{"use strict";g();var qj=ii().Buffer,Uj=rA(),KA=zA().Transform,Fj=Rt();function Da(e){KA.call(this),this._block=qj.allocUnsafe(e),this._blockSize=e,this._blockOffset=0,this._length=[0,0,0,0],this._finalized=!1}Fj(Da,KA);Da.prototype._transform=function(e,t,r){var i=null;try{this.update(e,t)}catch(n){i=n}r(i)};Da.prototype._flush=function(e){var t=null;try{this.push(this.digest())}catch(r){t=r}e(t)};Da.prototype.update=function(e,t){if(this._finalized)throw new Error("Digest already called");for(var r=Uj(e,t),i=this._block,n=0;this._blockOffset+r.length-n>=this._blockSize;){for(var o=this._blockOffset;o<this._blockSize;)i[o]=r[n],o+=1,n+=1;this._update(),this._blockOffset=0}for(;n<r.length;)i[this._blockOffset]=r[n],this._blockOffset+=1,n+=1;for(var a=0,s=r.length*8;s>0;++a)this._length[a]+=s,s=this._length[a]/4294967296|0,s>0&&(this._length[a]-=4294967296*s);return this};Da.prototype._update=function(){throw new Error("_update is not implemented")};Da.prototype.digest=function(e){if(this._finalized)throw new Error("Digest already called");this._finalized=!0;var t=this._digest();e!==void 0&&(t=t.toString(e)),this._block.fill(0),this._blockOffset=0;for(var r=0;r<4;++r)this._length[r]=0;return t};Da.prototype._digest=function(){throw new Error("_digest is not implemented")};VA.exports=Da});var Ky=T((Yie,QA)=>{"use strict";g();var zy=rr().Buffer,jj=Rt(),JA=GA(),zj=new Array(16),fl=[0,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,7,4,13,1,10,6,15,3,12,0,9,5,2,14,11,8,3,10,14,4,9,15,8,1,2,7,0,6,13,11,5,12,1,9,11,10,0,8,12,4,13,3,7,15,14,5,6,2,4,0,5,9,7,12,2,10,14,1,3,8,11,6,15,13],ll=[5,14,7,0,9,2,11,4,13,6,15,8,1,10,3,12,6,11,3,7,0,13,5,10,14,15,8,12,4,9,1,2,15,5,1,3,7,14,6,9,11,8,12,2,10,0,4,13,8,6,4,1,3,11,15,0,5,12,2,13,9,7,10,14,12,15,10,4,1,5,8,7,6,2,13,14,0,3,9,11],hl=[11,14,15,12,5,8,7,9,11,13,14,15,6,7,9,8,7,6,8,13,11,9,7,15,7,12,15,9,11,7,13,12,11,13,6,7,14,9,13,15,14,8,13,6,5,12,7,5,11,12,14,15,14,15,9,8,9,14,5,6,8,6,5,12,9,15,5,11,6,8,13,12,5,12,13,14,11,8,5,6],dl=[8,9,9,11,13,15,15,5,7,7,8,11,14,14,12,6,9,13,15,7,12,8,9,11,7,7,12,7,6,15,13,11,9,7,15,11,8,6,6,14,12,13,5,14,13,13,7,5,15,5,8,11,14,14,6,14,6,9,12,9,12,5,15,8,8,5,12,9,12,5,14,6,8,13,6,5,15,13,11,11],pl=[0,1518500249,1859775393,2400959708,2840853838],gl=[1352829926,1548603684,1836072691,2053994217,0];function zs(e,t){return e<<t|e>>>32-t}function WA(e,t,r,i,n,o,a,s){return zs(e+(t^r^i)+o+a|0,s)+n|0}function YA(e,t,r,i,n,o,a,s){return zs(e+(t&r|~t&i)+o+a|0,s)+n|0}function ZA(e,t,r,i,n,o,a,s){return zs(e+((t|~r)^i)+o+a|0,s)+n|0}function $A(e,t,r,i,n,o,a,s){return zs(e+(t&i|r&~i)+o+a|0,s)+n|0}function XA(e,t,r,i,n,o,a,s){return zs(e+(t^(r|~i))+o+a|0,s)+n|0}function Rp(){JA.call(this,64),this._a=1732584193,this._b=4023233417,this._c=2562383102,this._d=271733878,this._e=3285377520}jj(Rp,JA);Rp.prototype._update=function(){for(var e=zj,t=0;t<16;++t)e[t]=this._block.readInt32LE(t*4);for(var r=this._a|0,i=this._b|0,n=this._c|0,o=this._d|0,a=this._e|0,s=this._a|0,u=this._b|0,c=this._c|0,l=this._d|0,p=this._e|0,d=0;d<80;d+=1){var v,_;d<16?(v=WA(r,i,n,o,a,e[fl[d]],pl[0],hl[d]),_=XA(s,u,c,l,p,e[ll[d]],gl[0],dl[d])):d<32?(v=YA(r,i,n,o,a,e[fl[d]],pl[1],hl[d]),_=$A(s,u,c,l,p,e[ll[d]],gl[1],dl[d])):d<48?(v=ZA(r,i,n,o,a,e[fl[d]],pl[2],hl[d]),_=ZA(s,u,c,l,p,e[ll[d]],gl[2],dl[d])):d<64?(v=$A(r,i,n,o,a,e[fl[d]],pl[3],hl[d]),_=YA(s,u,c,l,p,e[ll[d]],gl[3],dl[d])):(v=XA(r,i,n,o,a,e[fl[d]],pl[4],hl[d]),_=WA(s,u,c,l,p,e[ll[d]],gl[4],dl[d])),r=a,a=o,o=zs(n,10),n=i,i=v,s=p,p=l,l=zs(c,10),c=u,u=_}var I=this._b+n+l|0;this._b=this._c+o+p|0,this._c=this._d+a+s|0,this._d=this._e+r+u|0,this._e=this._a+i+c|0,this._a=I};Rp.prototype._digest=function(){this._block[this._blockOffset]=128,this._blockOffset+=1,this._blockOffset>56&&(this._block.fill(0,this._blockOffset,64),this._update(),this._blockOffset=0),this._block.fill(0,this._blockOffset,56),this._block.writeUInt32LE(this._length[0],56),this._block.writeUInt32LE(this._length[1],60),this._update();var e=zy.alloc?zy.alloc(20):new zy(20);return e.writeInt32LE(this._a,0),e.writeInt32LE(this._b,4),e.writeInt32LE(this._c,8),e.writeInt32LE(this._d,12),e.writeInt32LE(this._e,16),e};QA.exports=Rp});var Ks=T(($ie,eT)=>{"use strict";g();var Kj=ii().Buffer,Vj=yp();function kp(e,t){this._block=Kj.alloc(e),this._finalSize=t,this._blockSize=e,this._len=0}kp.prototype.update=function(e,t){e=Vj(e,t||"utf8");for(var r=this._block,i=this._blockSize,n=e.length,o=this._len,a=0;a<n;){for(var s=o%i,u=Math.min(n-a,i-s),c=0;c<u;c++)r[s+c]=e[a+c];o+=u,a+=u,o%i===0&&this._update(r)}return this._len+=n,this};kp.prototype.digest=function(e){var t=this._len%this._blockSize;this._block[t]=128,this._block.fill(0,t+1),t>=this._finalSize&&(this._update(this._block),this._block.fill(0));var r=this._len*8;if(r<=4294967295)this._block.writeUInt32BE(r,this._blockSize-4);else{var i=(r&4294967295)>>>0,n=(r-i)/4294967296;this._block.writeUInt32BE(n,this._blockSize-8),this._block.writeUInt32BE(i,this._blockSize-4)}this._update(this._block);var o=this._hash();return e?o.toString(e):o};kp.prototype._update=function(){throw new Error("_update must be implemented by subclass")};eT.exports=kp});var iT=T((Jie,rT)=>{"use strict";g();var Gj=Rt(),tT=Ks(),Wj=ii().Buffer,Yj=[1518500249,1859775393,-1894007588,-899497514],Zj=new Array(80);function ml(){this.init(),this._w=Zj,tT.call(this,64,56)}Gj(ml,tT);ml.prototype.init=function(){return this._a=1732584193,this._b=4023233417,this._c=2562383102,this._d=271733878,this._e=3285377520,this};function $j(e){return e<<5|e>>>27}function Xj(e){return e<<30|e>>>2}function Jj(e,t,r,i){return e===0?t&r|~t&i:e===2?t&r|t&i|r&i:t^r^i}ml.prototype._update=function(e){for(var t=this._w,r=this._a|0,i=this._b|0,n=this._c|0,o=this._d|0,a=this._e|0,s=0;s<16;++s)t[s]=e.readInt32BE(s*4);for(;s<80;++s)t[s]=t[s-3]^t[s-8]^t[s-14]^t[s-16];for(var u=0;u<80;++u){var c=~~(u/20),l=$j(r)+Jj(c,i,n,o)+a+t[u]+Yj[c]|0;a=o,o=n,n=Xj(i),i=r,r=l}this._a=r+this._a|0,this._b=i+this._b|0,this._c=n+this._c|0,this._d=o+this._d|0,this._e=a+this._e|0};ml.prototype._hash=function(){var e=Wj.allocUnsafe(20);return e.writeInt32BE(this._a|0,0),e.writeInt32BE(this._b|0,4),e.writeInt32BE(this._c|0,8),e.writeInt32BE(this._d|0,12),e.writeInt32BE(this._e|0,16),e};rT.exports=ml});var aT=T((ene,oT)=>{"use strict";g();var Qj=Rt(),nT=Ks(),ez=ii().Buffer,tz=[1518500249,1859775393,-1894007588,-899497514],rz=new Array(80);function vl(){this.init(),this._w=rz,nT.call(this,64,56)}Qj(vl,nT);vl.prototype.init=function(){return this._a=1732584193,this._b=4023233417,this._c=2562383102,this._d=271733878,this._e=3285377520,this};function iz(e){return e<<1|e>>>31}function nz(e){return e<<5|e>>>27}function oz(e){return e<<30|e>>>2}function az(e,t,r,i){return e===0?t&r|~t&i:e===2?t&r|t&i|r&i:t^r^i}vl.prototype._update=function(e){for(var t=this._w,r=this._a|0,i=this._b|0,n=this._c|0,o=this._d|0,a=this._e|0,s=0;s<16;++s)t[s]=e.readInt32BE(s*4);for(;s<80;++s)t[s]=iz(t[s-3]^t[s-8]^t[s-14]^t[s-16]);for(var u=0;u<80;++u){var c=~~(u/20),l=nz(r)+az(c,i,n,o)+a+t[u]+tz[c]|0;a=o,o=n,n=oz(i),i=r,r=l}this._a=r+this._a|0,this._b=i+this._b|0,this._c=n+this._c|0,this._d=o+this._d|0,this._e=a+this._e|0};vl.prototype._hash=function(){var e=ez.allocUnsafe(20);return e.writeInt32BE(this._a|0,0),e.writeInt32BE(this._b|0,4),e.writeInt32BE(this._c|0,8),e.writeInt32BE(this._d|0,12),e.writeInt32BE(this._e|0,16),e};oT.exports=vl});var Vy=T((rne,uT)=>{"use strict";g();var sz=Rt(),sT=Ks(),uz=ii().Buffer,cz=[1116352408,1899447441,3049323471,3921009573,961987163,1508970993,2453635748,2870763221,3624381080,310598401,607225278,1426881987,1925078388,2162078206,2614888103,3248222580,3835390401,4022224774,264347078,604807628,770255983,1249150122,1555081692,1996064986,2554220882,2821834349,2952996808,3210313671,3336571891,3584528711,113926993,338241895,666307205,773529912,1294757372,1396182291,1695183700,1986661051,2177026350,2456956037,2730485921,2820302411,3259730800,3345764771,3516065817,3600352804,4094571909,275423344,430227734,506948616,659060556,883997877,958139571,1322822218,1537002063,1747873779,1955562222,2024104815,2227730452,2361852424,2428436474,2756734187,3204031479,3329325298],fz=new Array(64);function yl(){this.init(),this._w=fz,sT.call(this,64,56)}sz(yl,sT);yl.prototype.init=function(){return this._a=1779033703,this._b=3144134277,this._c=1013904242,this._d=2773480762,this._e=1359893119,this._f=2600822924,this._g=528734635,this._h=1541459225,this};function lz(e,t,r){return r^e&(t^r)}function hz(e,t,r){return e&t|r&(e|t)}function dz(e){return(e>>>2|e<<30)^(e>>>13|e<<19)^(e>>>22|e<<10)}function pz(e){return(e>>>6|e<<26)^(e>>>11|e<<21)^(e>>>25|e<<7)}function gz(e){return(e>>>7|e<<25)^(e>>>18|e<<14)^e>>>3}function mz(e){return(e>>>17|e<<15)^(e>>>19|e<<13)^e>>>10}yl.prototype._update=function(e){for(var t=this._w,r=this._a|0,i=this._b|0,n=this._c|0,o=this._d|0,a=this._e|0,s=this._f|0,u=this._g|0,c=this._h|0,l=0;l<16;++l)t[l]=e.readInt32BE(l*4);for(;l<64;++l)t[l]=mz(t[l-2])+t[l-7]+gz(t[l-15])+t[l-16]|0;for(var p=0;p<64;++p){var d=c+pz(a)+lz(a,s,u)+cz[p]+t[p]|0,v=dz(r)+hz(r,i,n)|0;c=u,u=s,s=a,a=o+d|0,o=n,n=i,i=r,r=d+v|0}this._a=r+this._a|0,this._b=i+this._b|0,this._c=n+this._c|0,this._d=o+this._d|0,this._e=a+this._e|0,this._f=s+this._f|0,this._g=u+this._g|0,this._h=c+this._h|0};yl.prototype._hash=function(){var e=uz.allocUnsafe(32);return e.writeInt32BE(this._a,0),e.writeInt32BE(this._b,4),e.writeInt32BE(this._c,8),e.writeInt32BE(this._d,12),e.writeInt32BE(this._e,16),e.writeInt32BE(this._f,20),e.writeInt32BE(this._g,24),e.writeInt32BE(this._h,28),e};uT.exports=yl});var fT=T((nne,cT)=>{"use strict";g();var vz=Rt(),yz=Vy(),bz=Ks(),_z=ii().Buffer,wz=new Array(64);function Bp(){this.init(),this._w=wz,bz.call(this,64,56)}vz(Bp,yz);Bp.prototype.init=function(){return this._a=3238371032,this._b=914150663,this._c=812702999,this._d=4144912697,this._e=4290775857,this._f=1750603025,this._g=1694076839,this._h=3204075428,this};Bp.prototype._hash=function(){var e=_z.allocUnsafe(28);return e.writeInt32BE(this._a,0),e.writeInt32BE(this._b,4),e.writeInt32BE(this._c,8),e.writeInt32BE(this._d,12),e.writeInt32BE(this._e,16),e.writeInt32BE(this._f,20),e.writeInt32BE(this._g,24),e};cT.exports=Bp});var Gy=T((ane,vT)=>{"use strict";g();var Sz=Rt(),mT=Ks(),Ez=ii().Buffer,lT=[1116352408,3609767458,1899447441,602891725,3049323471,3964484399,3921009573,2173295548,961987163,4081628472,1508970993,3053834265,2453635748,2937671579,2870763221,3664609560,3624381080,2734883394,310598401,1164996542,607225278,1323610764,1426881987,3590304994,1925078388,4068182383,2162078206,991336113,2614888103,633803317,3248222580,3479774868,3835390401,2666613458,4022224774,944711139,264347078,2341262773,604807628,2007800933,770255983,1495990901,1249150122,1856431235,1555081692,3175218132,1996064986,2198950837,2554220882,3999719339,2821834349,766784016,2952996808,2566594879,3210313671,3203337956,3336571891,1034457026,3584528711,2466948901,113926993,3758326383,338241895,168717936,666307205,1188179964,773529912,1546045734,1294757372,1522805485,1396182291,2643833823,1695183700,2343527390,1986661051,1014477480,2177026350,1206759142,2456956037,344077627,2730485921,1290863460,2820302411,3158454273,3259730800,3505952657,3345764771,106217008,3516065817,3606008344,3600352804,1432725776,4094571909,1467031594,275423344,851169720,430227734,3100823752,506948616,1363258195,659060556,3750685593,883997877,3785050280,958139571,3318307427,1322822218,3812723403,1537002063,2003034995,1747873779,3602036899,1955562222,1575990012,2024104815,1125592928,2227730452,2716904306,2361852424,442776044,2428436474,593698344,2756734187,3733110249,3204031479,2999351573,3329325298,3815920427,3391569614,3928383900,3515267271,566280711,3940187606,3454069534,4118630271,4000239992,116418474,1914138554,174292421,2731055270,289380356,3203993006,460393269,320620315,685471733,587496836,852142971,1086792851,1017036298,365543100,1126000580,2618297676,1288033470,3409855158,1501505948,4234509866,1607167915,987167468,1816402316,1246189591],xz=new Array(160);function bl(){this.init(),this._w=xz,mT.call(this,128,112)}Sz(bl,mT);bl.prototype.init=function(){return this._ah=1779033703,this._bh=3144134277,this._ch=1013904242,this._dh=2773480762,this._eh=1359893119,this._fh=2600822924,this._gh=528734635,this._hh=1541459225,this._al=4089235720,this._bl=2227873595,this._cl=4271175723,this._dl=1595750129,this._el=2917565137,this._fl=725511199,this._gl=4215389547,this._hl=327033209,this};function hT(e,t,r){return r^e&(t^r)}function dT(e,t,r){return e&t|r&(e|t)}function pT(e,t){return(e>>>28|t<<4)^(t>>>2|e<<30)^(t>>>7|e<<25)}function gT(e,t){return(e>>>14|t<<18)^(e>>>18|t<<14)^(t>>>9|e<<23)}function Oz(e,t){return(e>>>1|t<<31)^(e>>>8|t<<24)^e>>>7}function Iz(e,t){return(e>>>1|t<<31)^(e>>>8|t<<24)^(e>>>7|t<<25)}function Az(e,t){return(e>>>19|t<<13)^(t>>>29|e<<3)^e>>>6}function Tz(e,t){return(e>>>19|t<<13)^(t>>>29|e<<3)^(e>>>6|t<<26)}function $r(e,t){return e>>>0<t>>>0?1:0}bl.prototype._update=function(e){for(var t=this._w,r=this._ah|0,i=this._bh|0,n=this._ch|0,o=this._dh|0,a=this._eh|0,s=this._fh|0,u=this._gh|0,c=this._hh|0,l=this._al|0,p=this._bl|0,d=this._cl|0,v=this._dl|0,_=this._el|0,I=this._fl|0,R=this._gl|0,k=this._hl|0,q=0;q<32;q+=2)t[q]=e.readInt32BE(q*4),t[q+1]=e.readInt32BE(q*4+4);for(;q<160;q+=2){var z=t[q-30],A=t[q-30+1],B=Oz(z,A),M=Iz(A,z);z=t[q-4],A=t[q-4+1];var F=Az(z,A),V=Tz(A,z),Y=t[q-14],E=t[q-14+1],h=t[q-32],y=t[q-32+1],w=M+E|0,S=B+Y+$r(w,M)|0;w=w+V|0,S=S+F+$r(w,V)|0,w=w+y|0,S=S+h+$r(w,y)|0,t[q]=S,t[q+1]=w}for(var O=0;O<160;O+=2){S=t[O],w=t[O+1];var C=dT(r,i,n),D=dT(l,p,d),P=pT(r,l),m=pT(l,r),x=gT(a,_),K=gT(_,a),U=lT[O],G=lT[O+1],te=hT(a,s,u),ae=hT(_,I,R),oe=k+K|0,le=c+x+$r(oe,k)|0;oe=oe+ae|0,le=le+te+$r(oe,ae)|0,oe=oe+G|0,le=le+U+$r(oe,G)|0,oe=oe+w|0,le=le+S+$r(oe,w)|0;var he=m+D|0,ve=P+C+$r(he,m)|0;c=u,k=R,u=s,R=I,s=a,I=_,_=v+oe|0,a=o+le+$r(_,v)|0,o=n,v=d,n=i,d=p,i=r,p=l,l=oe+he|0,r=le+ve+$r(l,oe)|0}this._al=this._al+l|0,this._bl=this._bl+p|0,this._cl=this._cl+d|0,this._dl=this._dl+v|0,this._el=this._el+_|0,this._fl=this._fl+I|0,this._gl=this._gl+R|0,this._hl=this._hl+k|0,this._ah=this._ah+r+$r(this._al,l)|0,this._bh=this._bh+i+$r(this._bl,p)|0,this._ch=this._ch+n+$r(this._cl,d)|0,this._dh=this._dh+o+$r(this._dl,v)|0,this._eh=this._eh+a+$r(this._el,_)|0,this._fh=this._fh+s+$r(this._fl,I)|0,this._gh=this._gh+u+$r(this._gl,R)|0,this._hh=this._hh+c+$r(this._hl,k)|0};bl.prototype._hash=function(){var e=Ez.allocUnsafe(64);function t(r,i,n){e.writeInt32BE(r,n),e.writeInt32BE(i,n+4)}return t(this._ah,this._al,0),t(this._bh,this._bl,8),t(this._ch,this._cl,16),t(this._dh,this._dl,24),t(this._eh,this._el,32),t(this._fh,this._fl,40),t(this._gh,this._gl,48),t(this._hh,this._hl,56),e};vT.exports=bl});var bT=T((une,yT)=>{"use strict";g();var Pz=Rt(),Rz=Gy(),kz=Ks(),Bz=ii().Buffer,Nz=new Array(160);function Np(){this.init(),this._w=Nz,kz.call(this,128,112)}Pz(Np,Rz);Np.prototype.init=function(){return this._ah=3418070365,this._bh=1654270250,this._ch=2438529370,this._dh=355462360,this._eh=1731405415,this._fh=2394180231,this._gh=3675008525,this._hh=1203062813,this._al=3238371032,this._bl=914150663,this._cl=812702999,this._dl=4144912697,this._el=4290775857,this._fl=1750603025,this._gl=1694076839,this._hl=3204075428,this};Np.prototype._hash=function(){var e=Bz.allocUnsafe(48);function t(r,i,n){e.writeInt32BE(r,n),e.writeInt32BE(i,n+4)}return t(this._ah,this._al,0),t(this._bh,this._bl,8),t(this._ch,this._cl,16),t(this._dh,this._dl,24),t(this._eh,this._el,32),t(this._fh,this._fl,40),e};yT.exports=Np});var Wy=T((fne,Zo)=>{"use strict";g();Zo.exports=function(t){var r=t.toLowerCase(),i=Zo.exports[r];if(!i)throw new Error(r+" is not supported (we accept pull requests)");return new i};Zo.exports.sha=iT();Zo.exports.sha1=aT();Zo.exports.sha224=fT();Zo.exports.sha256=Vy();Zo.exports.sha384=bT();Zo.exports.sha512=Gy()});var Cp=T((hne,wT)=>{"use strict";g();var Cz=ii().Buffer,_T=gp().Transform,Lz=nc().StringDecoder,Mz=Rt(),Dz=yp();function On(e){_T.call(this),this.hashMode=typeof e=="string",this.hashMode?this[e]=this._finalOrDigest:this.final=this._finalOrDigest,this._final&&(this.__final=this._final,this._final=null),this._decoder=null,this._encoding=null}Mz(On,_T);On.prototype.update=function(e,t,r){var i=Dz(e,t),n=this._update(i);return this.hashMode?this:(r&&(n=this._toString(n,r)),n)};On.prototype.setAutoPadding=function(){};On.prototype.getAuthTag=function(){throw new Error("trying to get auth tag in unsupported state")};On.prototype.setAuthTag=function(){throw new Error("trying to set auth tag in unsupported state")};On.prototype.setAAD=function(){throw new Error("trying to set aad in unsupported state")};On.prototype._transform=function(e,t,r){var i;try{this.hashMode?this._update(e):this.push(this._update(e))}catch(n){i=n}finally{r(i)}};On.prototype._flush=function(e){var t;try{this.push(this.__final())}catch(r){t=r}e(t)};On.prototype._finalOrDigest=function(e){var t=this.__final()||Cz.alloc(0);return e&&(t=this._toString(t,e,!0)),t};On.prototype._toString=function(e,t,r){if(this._decoder||(this._decoder=new Lz(t),this._encoding=t),this._encoding!==t)throw new Error("can\u2019t switch encodings");var i=this._decoder.write(e);return r&&(i+=this._decoder.end()),i};wT.exports=On});var xT=T((pne,ET)=>{"use strict";g();var Hz=Rt(),qz=Oy(),Uz=Ky(),Fz=Wy(),ST=Cp();function Lp(e){ST.call(this,"digest"),this._hash=e}Hz(Lp,ST);Lp.prototype._update=function(e){this._hash.update(e)};Lp.prototype._final=function(){return this._hash.digest()};ET.exports=function(t){return t=t.toLowerCase(),t==="md5"?new qz:t==="rmd160"||t==="ripemd160"?new Uz:new Lp(Fz(t))}});var AT=T((mne,IT)=>{"use strict";g();var jz=Rt(),Vs=ii().Buffer,OT=Cp(),zz=Vs.alloc(128),hc=64;function Mp(e,t){OT.call(this,"digest"),typeof t=="string"&&(t=Vs.from(t)),this._alg=e,this._key=t,t.length>hc?t=e(t):t.length<hc&&(t=Vs.concat([t,zz],hc));for(var r=this._ipad=Vs.allocUnsafe(hc),i=this._opad=Vs.allocUnsafe(hc),n=0;n<hc;n++)r[n]=t[n]^54,i[n]=t[n]^92;this._hash=[r]}jz(Mp,OT);Mp.prototype._update=function(e){this._hash.push(e)};Mp.prototype._final=function(){var e=this._alg(Vs.concat(this._hash));return this._alg(Vs.concat([this._opad,e]))};IT.exports=Mp});var PT=T((yne,TT)=>{g();var Kz=Oy();TT.exports=function(e){return new Kz().update(e).digest()}});var BT=T((_ne,kT)=>{"use strict";g();var Vz=Rt(),Gz=AT(),RT=Cp(),_l=ii().Buffer,Wz=PT(),Yy=Ky(),Zy=Wy(),Yz=_l.alloc(128);function wl(e,t){RT.call(this,"digest"),typeof t=="string"&&(t=_l.from(t));var r=e==="sha512"||e==="sha384"?128:64;if(this._alg=e,this._key=t,t.length>r){var i=e==="rmd160"?new Yy:Zy(e);t=i.update(t).digest()}else t.length<r&&(t=_l.concat([t,Yz],r));for(var n=this._ipad=_l.allocUnsafe(r),o=this._opad=_l.allocUnsafe(r),a=0;a<r;a++)n[a]=t[a]^54,o[a]=t[a]^92;this._hash=e==="rmd160"?new Yy:Zy(e),this._hash.update(n)}Vz(wl,RT);wl.prototype._update=function(e){this._hash.update(e)};wl.prototype._final=function(){var e=this._hash.digest(),t=this._alg==="rmd160"?new Yy:Zy(this._alg);return t.update(this._opad).update(e).digest()};kT.exports=function(t,r){return t=t.toLowerCase(),t==="rmd160"||t==="ripemd160"?new wl("rmd160",r):t==="md5"?new Gz(Wz,r):new wl(t,r)}});var NT=T((Sne,Xy)=>{"use strict";g();var $y=65536,Zz=4294967295;function $z(){throw new Error(`Secure random number generation is not supported by this browser.
|
|
11
|
-
Use Chrome, Firefox or Internet Explorer 11`)}var Xz=ii().Buffer,Dp=globalThis.crypto||globalThis.msCrypto;Dp&&Dp.getRandomValues?Xy.exports=Jz:Xy.exports=$z;function Jz(e,t){if(e>Zz)throw new RangeError("requested too many random bytes");var r=Xz.allocUnsafe(e);if(e>0)if(e>$y)for(var i=0;i<e;i+=$y)Dp.getRandomValues(r.slice(i,i+$y));else Dp.getRandomValues(r);return typeof t=="function"?b.default.nextTick(function(){t(null,r)}):r}});var nr=T(Hp=>{"use strict";g();Hp.createHash=xT();Hp.createHmac=BT();Hp.randomBytes=NT()});var Ki=T((Ine,LT)=>{"use strict";g();var CT=65536;function Gs(){}Gs.getRandomBuffer=function(e){var t=typeof globalThis<"u"?globalThis.crypto:void 0;if(t&&typeof t.getRandomValues=="function")return Gs._fromGetRandomValues(t,e);try{var r=nr();if(r&&typeof r.randomBytes=="function")return r.randomBytes(e)}catch{}throw new Error("bsv: no CSPRNG available in this environment (needs globalThis.crypto.getRandomValues or node crypto)")};Gs._fromGetRandomValues=function(e,t){for(var r=f.Buffer.alloc(t),i=0;i<t;i+=CT){var n=new Uint8Array(Math.min(CT,t-i));e.getRandomValues(n),f.Buffer.from(n).copy(r,i)}return r};Gs.getRandomBufferNode=function(e){var t=nr();return t.randomBytes(e)};Gs.getRandomBufferBrowser=function(e){var t=typeof globalThis<"u"?globalThis:{},r=null;if(t.crypto&&typeof t.crypto.getRandomValues=="function"?r=t.crypto:t.msCrypto&&typeof t.msCrypto.getRandomValues=="function"&&(r=t.msCrypto),!r)throw new Error("window.crypto.getRandomValues not available");return Gs._fromGetRandomValues(r,e)};LT.exports=Gs});var at=T((Tne,MT)=>{"use strict";g();var Qz=Ki(),Ht={};Ht.isArray=e=>Array.isArray(e);Ht.isNumber=e=>typeof e=="number";Ht.isObject=e=>e&&typeof e=="object";Ht.isString=e=>typeof e=="string";Ht.isUndefined=e=>typeof e>"u";Ht.isFunction=e=>typeof e=="function";Ht.isNull=e=>e===null;Ht.isDate=e=>e instanceof Date;Ht.extend=(e,t)=>Object.assign(e,t);Ht.noop=()=>{};Ht.every=(e,t)=>e.every(t||(r=>r));Ht.map=(e,t)=>Array.from(e).map(t||(r=>r));Ht.includes=(e,t)=>e.includes(t);Ht.each=(e,t)=>e.forEach(t);Ht.clone=e=>Object.assign({},e);Ht.pick=(e,t)=>{let r={};return t.forEach(i=>{typeof e[i]<"u"&&(r[i]=e[i])}),r};Ht.values=e=>Object.values(e);Ht.filter=(e,t)=>e.filter(t);Ht.reduce=(e,t,r)=>e.reduce(t,r);Ht.without=(e,t)=>e.filter(r=>r!==t);Ht.shuffle=e=>{let t=e.slice(0);for(let r=t.length-1;r>0;r--){let n=Qz.getRandomBuffer(4).readUInt32BE(0)/4294967296,o=Math.floor(n*(r+1));[t[r],t[o]]=[t[o],t[r]]}return t};Ht.difference=(e,t)=>e.filter(r=>!t.includes(r));Ht.findIndex=(e,t)=>e.findIndex(t);Ht.some=(e,t)=>e.some(t);Ht.range=e=>[...Array(e).keys()];MT.exports=Ht});var pc=T((Rne,qT)=>{"use strict";g();var Jy=at(),DT=rr(),dc="123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz".split(""),HT={};for(Sl=0;Sl<dc.length;Sl++)HT[dc[Sl]]=Sl;var Sl;function eK(e){if(e.length===0)return"";var t=[0],r,i,n;for(r=0;r<e.length;r++){for(i=0,n=e[r];i<t.length;i++)n+=t[i]<<8,t[i]=n%58,n=n/58|0;for(;n>0;)t.push(n%58),n=n/58|0}var o="";for(r=0;e[r]===0&&r<e.length-1;r++)o+=dc[0];for(r=t.length-1;r>=0;r--)o+=dc[t[r]];return o}function tK(e){if(e.length===0)return f.Buffer.alloc(0);var t=[0],r,i,n;for(r=0;r<e.length;r++){var o=HT[e[r]];if(o===void 0)throw new Error("Non-base58 character");for(i=0,n=o;i<t.length;i++)n+=t[i]*58,t[i]=n&255,n>>=8;for(;n>0;)t.push(n&255),n>>=8}for(r=0;e[r]===dc[0]&&r<e.length-1;r++)t.push(0);return f.Buffer.from(t.reverse())}var Xr=function e(t){if(!(this instanceof e))return new e(t);if(f.Buffer.isBuffer(t)){var r=t;this.fromBuffer(r)}else if(typeof t=="string"){var i=t;this.fromString(i)}};Xr.validCharacters=function(t){return DT.Buffer.isBuffer(t)&&(t=t.toString()),Jy.every(Jy.map(t,function(r){return Jy.includes(dc,r)}))};Xr.prototype.set=function(e){return this.buf=e.buf||this.buf||void 0,this};Xr.encode=function(e){if(!DT.Buffer.isBuffer(e))throw new Error("Input should be a buffer");return eK(e)};Xr.decode=function(e){if(typeof e!="string")throw new Error("Input should be a string");return tK(e)};Xr.prototype.fromBuffer=function(e){return this.buf=e,this};Xr.fromBuffer=function(e){return new Xr().fromBuffer(e)};Xr.fromHex=function(e){return Xr.fromBuffer(f.Buffer.from(e,"hex"))};Xr.prototype.fromString=function(e){var t=Xr.decode(e);return this.buf=t,this};Xr.fromString=function(e){return new Xr().fromString(e)};Xr.prototype.toBuffer=function(){return this.buf};Xr.prototype.toHex=function(){return this.toBuffer().toString("hex")};Xr.prototype.toString=function(){return Xr.encode(this.buf)};qT.exports=Xr});var qp=T((UT,Qy)=>{g();(function(e,t){"use strict";function r(E,h){if(!E)throw new Error(h||"Assertion failed")}function i(E,h){E.super_=h;var y=function(){};y.prototype=h.prototype,E.prototype=new y,E.prototype.constructor=E}function n(E,h,y){if(n.isBN(E))return E;this.negative=0,this.words=null,this.length=0,this.red=null,E!==null&&((h==="le"||h==="be")&&(y=h,h=10),this._init(E||0,h||10,y||"be"))}typeof e=="object"?e.exports=n:t.BN=n,n.BN=n,n.wordSize=26;var o;try{typeof window<"u"&&typeof window.Buffer<"u"?o=window.Buffer:o=rr().Buffer}catch{}n.isBN=function(h){return h instanceof n?!0:h!==null&&typeof h=="object"&&h.constructor.wordSize===n.wordSize&&Array.isArray(h.words)},n.max=function(h,y){return h.cmp(y)>0?h:y},n.min=function(h,y){return h.cmp(y)<0?h:y},n.prototype._init=function(h,y,w){if(typeof h=="number")return this._initNumber(h,y,w);if(typeof h=="object")return this._initArray(h,y,w);y==="hex"&&(y=16),r(y===(y|0)&&y>=2&&y<=36),h=h.toString().replace(/\s+/g,"");var S=0;h[0]==="-"&&(S++,this.negative=1),S<h.length&&(y===16?this._parseHex(h,S,w):(this._parseBase(h,y,S),w==="le"&&this._initArray(this.toArray(),y,w)))},n.prototype._initNumber=function(h,y,w){h<0&&(this.negative=1,h=-h),h<67108864?(this.words=[h&67108863],this.length=1):h<4503599627370496?(this.words=[h&67108863,h/67108864&67108863],this.length=2):(r(h<9007199254740992),this.words=[h&67108863,h/67108864&67108863,1],this.length=3),w==="le"&&this._initArray(this.toArray(),y,w)},n.prototype._initArray=function(h,y,w){if(r(typeof h.length=="number"),h.length<=0)return this.words=[0],this.length=1,this;this.length=Math.ceil(h.length/3),this.words=new Array(this.length);for(var S=0;S<this.length;S++)this.words[S]=0;var O,C,D=0;if(w==="be")for(S=h.length-1,O=0;S>=0;S-=3)C=h[S]|h[S-1]<<8|h[S-2]<<16,this.words[O]|=C<<D&67108863,this.words[O+1]=C>>>26-D&67108863,D+=24,D>=26&&(D-=26,O++);else if(w==="le")for(S=0,O=0;S<h.length;S+=3)C=h[S]|h[S+1]<<8|h[S+2]<<16,this.words[O]|=C<<D&67108863,this.words[O+1]=C>>>26-D&67108863,D+=24,D>=26&&(D-=26,O++);return this.strip()};function a(E,h){var y=E.charCodeAt(h);return y>=65&&y<=70?y-55:y>=97&&y<=102?y-87:y-48&15}function s(E,h,y){var w=a(E,y);return y-1>=h&&(w|=a(E,y-1)<<4),w}n.prototype._parseHex=function(h,y,w){this.length=Math.ceil((h.length-y)/6),this.words=new Array(this.length);for(var S=0;S<this.length;S++)this.words[S]=0;var O=0,C=0,D;if(w==="be")for(S=h.length-1;S>=y;S-=2)D=s(h,y,S)<<O,this.words[C]|=D&67108863,O>=18?(O-=18,C+=1,this.words[C]|=D>>>26):O+=8;else{var P=h.length-y;for(S=P%2===0?y+1:y;S<h.length;S+=2)D=s(h,y,S)<<O,this.words[C]|=D&67108863,O>=18?(O-=18,C+=1,this.words[C]|=D>>>26):O+=8}this.strip()};function u(E,h,y,w){for(var S=0,O=Math.min(E.length,y),C=h;C<O;C++){var D=E.charCodeAt(C)-48;S*=w,D>=49?S+=D-49+10:D>=17?S+=D-17+10:S+=D}return S}n.prototype._parseBase=function(h,y,w){this.words=[0],this.length=1;for(var S=0,O=1;O<=67108863;O*=y)S++;S--,O=O/y|0;for(var C=h.length-w,D=C%S,P=Math.min(C,C-D)+w,m=0,x=w;x<P;x+=S)m=u(h,x,x+S,y),this.imuln(O),this.words[0]+m<67108864?this.words[0]+=m:this._iaddn(m);if(D!==0){var K=1;for(m=u(h,x,h.length,y),x=0;x<D;x++)K*=y;this.imuln(K),this.words[0]+m<67108864?this.words[0]+=m:this._iaddn(m)}this.strip()},n.prototype.copy=function(h){h.words=new Array(this.length);for(var y=0;y<this.length;y++)h.words[y]=this.words[y];h.length=this.length,h.negative=this.negative,h.red=this.red},n.prototype.clone=function(){var h=new n(null);return this.copy(h),h},n.prototype._expand=function(h){for(;this.length<h;)this.words[this.length++]=0;return this},n.prototype.strip=function(){for(;this.length>1&&this.words[this.length-1]===0;)this.length--;return this._normSign()},n.prototype._normSign=function(){return this.length===1&&this.words[0]===0&&(this.negative=0),this},n.prototype.inspect=function(){return(this.red?"<BN-R: ":"<BN: ")+this.toString(16)+">"};var c=["","0","00","000","0000","00000","000000","0000000","00000000","000000000","0000000000","00000000000","000000000000","0000000000000","00000000000000","000000000000000","0000000000000000","00000000000000000","000000000000000000","0000000000000000000","00000000000000000000","000000000000000000000","0000000000000000000000","00000000000000000000000","000000000000000000000000","0000000000000000000000000"],l=[0,0,25,16,12,11,10,9,8,8,7,7,7,7,6,6,6,6,6,6,6,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5],p=[0,0,33554432,43046721,16777216,48828125,60466176,40353607,16777216,43046721,1e7,19487171,35831808,62748517,7529536,11390625,16777216,24137569,34012224,47045881,64e6,4084101,5153632,6436343,7962624,9765625,11881376,14348907,17210368,20511149,243e5,28629151,33554432,39135393,45435424,52521875,60466176];n.prototype.toString=function(h,y){h=h||10,y=y|0||1;var w;if(h===16||h==="hex"){w="";for(var S=0,O=0,C=0;C<this.length;C++){var D=this.words[C],P=((D<<S|O)&16777215).toString(16);O=D>>>24-S&16777215,S+=2,S>=26&&(S-=26,C--),O!==0||C!==this.length-1?w=c[6-P.length]+P+w:w=P+w}for(O!==0&&(w=O.toString(16)+w);w.length%y!==0;)w="0"+w;return this.negative!==0&&(w="-"+w),w}if(h===(h|0)&&h>=2&&h<=36){var m=l[h],x=p[h];w="";var K=this.clone();for(K.negative=0;!K.isZero();){var U=K.modn(x).toString(h);K=K.idivn(x),K.isZero()?w=U+w:w=c[m-U.length]+U+w}for(this.isZero()&&(w="0"+w);w.length%y!==0;)w="0"+w;return this.negative!==0&&(w="-"+w),w}r(!1,"Base should be between 2 and 36")},n.prototype.toNumber=function(){var h=this.words[0];return this.length===2?h+=this.words[1]*67108864:this.length===3&&this.words[2]===1?h+=4503599627370496+this.words[1]*67108864:this.length>2&&r(!1,"Number can only safely store up to 53 bits"),this.negative!==0?-h:h},n.prototype.toJSON=function(){return this.toString(16)},n.prototype.toBuffer=function(h,y){return r(typeof o<"u"),this.toArrayLike(o,h,y)},n.prototype.toArray=function(h,y){return this.toArrayLike(Array,h,y)},n.prototype.toArrayLike=function(h,y,w){var S=this.byteLength(),O=w||Math.max(1,S);r(S<=O,"byte array longer than desired length"),r(O>0,"Requested array length <= 0"),this.strip();var C=y==="le",D=new h(O),P,m,x=this.clone();if(C){for(m=0;!x.isZero();m++)P=x.andln(255),x.iushrn(8),D[m]=P;for(;m<O;m++)D[m]=0}else{for(m=0;m<O-S;m++)D[m]=0;for(m=0;!x.isZero();m++)P=x.andln(255),x.iushrn(8),D[O-m-1]=P}return D},Math.clz32?n.prototype._countBits=function(h){return 32-Math.clz32(h)}:n.prototype._countBits=function(h){var y=h,w=0;return y>=4096&&(w+=13,y>>>=13),y>=64&&(w+=7,y>>>=7),y>=8&&(w+=4,y>>>=4),y>=2&&(w+=2,y>>>=2),w+y},n.prototype._zeroBits=function(h){if(h===0)return 26;var y=h,w=0;return(y&8191)===0&&(w+=13,y>>>=13),(y&127)===0&&(w+=7,y>>>=7),(y&15)===0&&(w+=4,y>>>=4),(y&3)===0&&(w+=2,y>>>=2),(y&1)===0&&w++,w},n.prototype.bitLength=function(){var h=this.words[this.length-1],y=this._countBits(h);return(this.length-1)*26+y};function d(E){for(var h=new Array(E.bitLength()),y=0;y<h.length;y++){var w=y/26|0,S=y%26;h[y]=(E.words[w]&1<<S)>>>S}return h}n.prototype.zeroBits=function(){if(this.isZero())return 0;for(var h=0,y=0;y<this.length;y++){var w=this._zeroBits(this.words[y]);if(h+=w,w!==26)break}return h},n.prototype.byteLength=function(){return Math.ceil(this.bitLength()/8)},n.prototype.toTwos=function(h){return this.negative!==0?this.abs().inotn(h).iaddn(1):this.clone()},n.prototype.fromTwos=function(h){return this.testn(h-1)?this.notn(h).iaddn(1).ineg():this.clone()},n.prototype.isNeg=function(){return this.negative!==0},n.prototype.neg=function(){return this.clone().ineg()},n.prototype.ineg=function(){return this.isZero()||(this.negative^=1),this},n.prototype.iuor=function(h){for(;this.length<h.length;)this.words[this.length++]=0;for(var y=0;y<h.length;y++)this.words[y]=this.words[y]|h.words[y];return this.strip()},n.prototype.ior=function(h){return r((this.negative|h.negative)===0),this.iuor(h)},n.prototype.or=function(h){return this.length>h.length?this.clone().ior(h):h.clone().ior(this)},n.prototype.uor=function(h){return this.length>h.length?this.clone().iuor(h):h.clone().iuor(this)},n.prototype.iuand=function(h){var y;this.length>h.length?y=h:y=this;for(var w=0;w<y.length;w++)this.words[w]=this.words[w]&h.words[w];return this.length=y.length,this.strip()},n.prototype.iand=function(h){return r((this.negative|h.negative)===0),this.iuand(h)},n.prototype.and=function(h){return this.length>h.length?this.clone().iand(h):h.clone().iand(this)},n.prototype.uand=function(h){return this.length>h.length?this.clone().iuand(h):h.clone().iuand(this)},n.prototype.iuxor=function(h){var y,w;this.length>h.length?(y=this,w=h):(y=h,w=this);for(var S=0;S<w.length;S++)this.words[S]=y.words[S]^w.words[S];if(this!==y)for(;S<y.length;S++)this.words[S]=y.words[S];return this.length=y.length,this.strip()},n.prototype.ixor=function(h){return r((this.negative|h.negative)===0),this.iuxor(h)},n.prototype.xor=function(h){return this.length>h.length?this.clone().ixor(h):h.clone().ixor(this)},n.prototype.uxor=function(h){return this.length>h.length?this.clone().iuxor(h):h.clone().iuxor(this)},n.prototype.inotn=function(h){r(typeof h=="number"&&h>=0);var y=Math.ceil(h/26)|0,w=h%26;this._expand(y),w>0&&y--;for(var S=0;S<y;S++)this.words[S]=~this.words[S]&67108863;for(w>0&&(this.words[S]=~this.words[S]&67108863>>26-w,S++);S<this.length;S++)this.words[S]=0;return this.strip()},n.prototype.notn=function(h){return this.clone().inotn(h)},n.prototype.setn=function(h,y){r(typeof h=="number"&&h>=0);var w=h/26|0,S=h%26;return this._expand(w+1),y?this.words[w]=this.words[w]|1<<S:this.words[w]=this.words[w]&~(1<<S),this.strip()},n.prototype.iadd=function(h){var y;if(this.negative!==0&&h.negative===0)return this.negative=0,y=this.isub(h),this.negative^=1,this._normSign();if(this.negative===0&&h.negative!==0)return h.negative=0,y=this.isub(h),h.negative=1,y._normSign();var w,S;this.length>h.length?(w=this,S=h):(w=h,S=this);for(var O=0,C=0;C<S.length;C++)y=(w.words[C]|0)+(S.words[C]|0)+O,this.words[C]=y&67108863,O=y>>>26;for(;O!==0&&C<w.length;C++)y=(w.words[C]|0)+O,this.words[C]=y&67108863,O=y>>>26;if(this.length=w.length,O!==0)this.words[this.length]=O,this.length++;else if(w!==this)for(;C<w.length;C++)this.words[C]=w.words[C];return this},n.prototype.add=function(h){var y;return h.negative!==0&&this.negative===0?(h.negative=0,y=this.sub(h),h.negative^=1,y):h.negative===0&&this.negative!==0?(this.negative=0,y=h.sub(this),this.negative=1,y):this.length>h.length?this.clone().iadd(h):h.clone().iadd(this)},n.prototype.isub=function(h){if(h.negative!==0){h.negative=0;var y=this.iadd(h);return h.negative=1,y._normSign()}else if(this.negative!==0)return this.negative=0,this.iadd(h),this.negative=1,this._normSign();var w=this.cmp(h);if(w===0)return this.negative=0,this.length=1,this.words[0]=0,this;var S,O;w>0?(S=this,O=h):(S=h,O=this);for(var C=0,D=0;D<O.length;D++)y=(S.words[D]|0)-(O.words[D]|0)+C,C=y>>26,this.words[D]=y&67108863;for(;C!==0&&D<S.length;D++)y=(S.words[D]|0)+C,C=y>>26,this.words[D]=y&67108863;if(C===0&&D<S.length&&S!==this)for(;D<S.length;D++)this.words[D]=S.words[D];return this.length=Math.max(this.length,D),S!==this&&(this.negative=1),this.strip()},n.prototype.sub=function(h){return this.clone().isub(h)};function v(E,h,y){y.negative=h.negative^E.negative;var w=E.length+h.length|0;y.length=w,w=w-1|0;var S=E.words[0]|0,O=h.words[0]|0,C=S*O,D=C&67108863,P=C/67108864|0;y.words[0]=D;for(var m=1;m<w;m++){for(var x=P>>>26,K=P&67108863,U=Math.min(m,h.length-1),G=Math.max(0,m-E.length+1);G<=U;G++){var te=m-G|0;S=E.words[te]|0,O=h.words[G]|0,C=S*O+K,x+=C/67108864|0,K=C&67108863}y.words[m]=K|0,P=x|0}return P!==0?y.words[m]=P|0:y.length--,y.strip()}var _=function(h,y,w){var S=h.words,O=y.words,C=w.words,D=0,P,m,x,K=S[0]|0,U=K&8191,G=K>>>13,te=S[1]|0,ae=te&8191,oe=te>>>13,le=S[2]|0,he=le&8191,ve=le>>>13,je=S[3]|0,be=je&8191,_e=je>>>13,We=S[4]|0,Pe=We&8191,Me=We>>>13,rt=S[5]|0,Be=rt&8191,vt=rt>>>13,ui=S[6]|0,Et=ui&8191,_t=ui>>>13,Yn=S[7]|0,Lt=Yn&8191,N=Yn>>>13,W=S[8]|0,X=W&8191,ie=W>>>13,pe=S[9]|0,se=pe&8191,me=pe>>>13,ge=O[0]|0,ke=ge&8191,Oe=ge>>>13,Ye=O[1]|0,Ze=Ye&8191,Pt=Ye>>>13,Mt=O[2]|0,$e=Mt&8191,Ee=Mt>>>13,Jt=O[3]|0,wt=Jt&8191,Ft=Jt>>>13,Hu=O[4]|0,Dt=Hu&8191,gr=Hu>>>13,wE=O[5]|0,mr=wE&8191,vr=wE>>>13,SE=O[6]|0,yr=SE&8191,br=SE>>>13,EE=O[7]|0,_r=EE&8191,wr=EE>>>13,xE=O[8]|0,Sr=xE&8191,Er=xE>>>13,OE=O[9]|0,xr=OE&8191,Or=OE>>>13;w.negative=h.negative^y.negative,w.length=19,P=Math.imul(U,ke),m=Math.imul(U,Oe),m=m+Math.imul(G,ke)|0,x=Math.imul(G,Oe);var Hv=(D+P|0)+((m&8191)<<13)|0;D=(x+(m>>>13)|0)+(Hv>>>26)|0,Hv&=67108863,P=Math.imul(ae,ke),m=Math.imul(ae,Oe),m=m+Math.imul(oe,ke)|0,x=Math.imul(oe,Oe),P=P+Math.imul(U,Ze)|0,m=m+Math.imul(U,Pt)|0,m=m+Math.imul(G,Ze)|0,x=x+Math.imul(G,Pt)|0;var qv=(D+P|0)+((m&8191)<<13)|0;D=(x+(m>>>13)|0)+(qv>>>26)|0,qv&=67108863,P=Math.imul(he,ke),m=Math.imul(he,Oe),m=m+Math.imul(ve,ke)|0,x=Math.imul(ve,Oe),P=P+Math.imul(ae,Ze)|0,m=m+Math.imul(ae,Pt)|0,m=m+Math.imul(oe,Ze)|0,x=x+Math.imul(oe,Pt)|0,P=P+Math.imul(U,$e)|0,m=m+Math.imul(U,Ee)|0,m=m+Math.imul(G,$e)|0,x=x+Math.imul(G,Ee)|0;var Uv=(D+P|0)+((m&8191)<<13)|0;D=(x+(m>>>13)|0)+(Uv>>>26)|0,Uv&=67108863,P=Math.imul(be,ke),m=Math.imul(be,Oe),m=m+Math.imul(_e,ke)|0,x=Math.imul(_e,Oe),P=P+Math.imul(he,Ze)|0,m=m+Math.imul(he,Pt)|0,m=m+Math.imul(ve,Ze)|0,x=x+Math.imul(ve,Pt)|0,P=P+Math.imul(ae,$e)|0,m=m+Math.imul(ae,Ee)|0,m=m+Math.imul(oe,$e)|0,x=x+Math.imul(oe,Ee)|0,P=P+Math.imul(U,wt)|0,m=m+Math.imul(U,Ft)|0,m=m+Math.imul(G,wt)|0,x=x+Math.imul(G,Ft)|0;var Fv=(D+P|0)+((m&8191)<<13)|0;D=(x+(m>>>13)|0)+(Fv>>>26)|0,Fv&=67108863,P=Math.imul(Pe,ke),m=Math.imul(Pe,Oe),m=m+Math.imul(Me,ke)|0,x=Math.imul(Me,Oe),P=P+Math.imul(be,Ze)|0,m=m+Math.imul(be,Pt)|0,m=m+Math.imul(_e,Ze)|0,x=x+Math.imul(_e,Pt)|0,P=P+Math.imul(he,$e)|0,m=m+Math.imul(he,Ee)|0,m=m+Math.imul(ve,$e)|0,x=x+Math.imul(ve,Ee)|0,P=P+Math.imul(ae,wt)|0,m=m+Math.imul(ae,Ft)|0,m=m+Math.imul(oe,wt)|0,x=x+Math.imul(oe,Ft)|0,P=P+Math.imul(U,Dt)|0,m=m+Math.imul(U,gr)|0,m=m+Math.imul(G,Dt)|0,x=x+Math.imul(G,gr)|0;var jv=(D+P|0)+((m&8191)<<13)|0;D=(x+(m>>>13)|0)+(jv>>>26)|0,jv&=67108863,P=Math.imul(Be,ke),m=Math.imul(Be,Oe),m=m+Math.imul(vt,ke)|0,x=Math.imul(vt,Oe),P=P+Math.imul(Pe,Ze)|0,m=m+Math.imul(Pe,Pt)|0,m=m+Math.imul(Me,Ze)|0,x=x+Math.imul(Me,Pt)|0,P=P+Math.imul(be,$e)|0,m=m+Math.imul(be,Ee)|0,m=m+Math.imul(_e,$e)|0,x=x+Math.imul(_e,Ee)|0,P=P+Math.imul(he,wt)|0,m=m+Math.imul(he,Ft)|0,m=m+Math.imul(ve,wt)|0,x=x+Math.imul(ve,Ft)|0,P=P+Math.imul(ae,Dt)|0,m=m+Math.imul(ae,gr)|0,m=m+Math.imul(oe,Dt)|0,x=x+Math.imul(oe,gr)|0,P=P+Math.imul(U,mr)|0,m=m+Math.imul(U,vr)|0,m=m+Math.imul(G,mr)|0,x=x+Math.imul(G,vr)|0;var zv=(D+P|0)+((m&8191)<<13)|0;D=(x+(m>>>13)|0)+(zv>>>26)|0,zv&=67108863,P=Math.imul(Et,ke),m=Math.imul(Et,Oe),m=m+Math.imul(_t,ke)|0,x=Math.imul(_t,Oe),P=P+Math.imul(Be,Ze)|0,m=m+Math.imul(Be,Pt)|0,m=m+Math.imul(vt,Ze)|0,x=x+Math.imul(vt,Pt)|0,P=P+Math.imul(Pe,$e)|0,m=m+Math.imul(Pe,Ee)|0,m=m+Math.imul(Me,$e)|0,x=x+Math.imul(Me,Ee)|0,P=P+Math.imul(be,wt)|0,m=m+Math.imul(be,Ft)|0,m=m+Math.imul(_e,wt)|0,x=x+Math.imul(_e,Ft)|0,P=P+Math.imul(he,Dt)|0,m=m+Math.imul(he,gr)|0,m=m+Math.imul(ve,Dt)|0,x=x+Math.imul(ve,gr)|0,P=P+Math.imul(ae,mr)|0,m=m+Math.imul(ae,vr)|0,m=m+Math.imul(oe,mr)|0,x=x+Math.imul(oe,vr)|0,P=P+Math.imul(U,yr)|0,m=m+Math.imul(U,br)|0,m=m+Math.imul(G,yr)|0,x=x+Math.imul(G,br)|0;var Kv=(D+P|0)+((m&8191)<<13)|0;D=(x+(m>>>13)|0)+(Kv>>>26)|0,Kv&=67108863,P=Math.imul(Lt,ke),m=Math.imul(Lt,Oe),m=m+Math.imul(N,ke)|0,x=Math.imul(N,Oe),P=P+Math.imul(Et,Ze)|0,m=m+Math.imul(Et,Pt)|0,m=m+Math.imul(_t,Ze)|0,x=x+Math.imul(_t,Pt)|0,P=P+Math.imul(Be,$e)|0,m=m+Math.imul(Be,Ee)|0,m=m+Math.imul(vt,$e)|0,x=x+Math.imul(vt,Ee)|0,P=P+Math.imul(Pe,wt)|0,m=m+Math.imul(Pe,Ft)|0,m=m+Math.imul(Me,wt)|0,x=x+Math.imul(Me,Ft)|0,P=P+Math.imul(be,Dt)|0,m=m+Math.imul(be,gr)|0,m=m+Math.imul(_e,Dt)|0,x=x+Math.imul(_e,gr)|0,P=P+Math.imul(he,mr)|0,m=m+Math.imul(he,vr)|0,m=m+Math.imul(ve,mr)|0,x=x+Math.imul(ve,vr)|0,P=P+Math.imul(ae,yr)|0,m=m+Math.imul(ae,br)|0,m=m+Math.imul(oe,yr)|0,x=x+Math.imul(oe,br)|0,P=P+Math.imul(U,_r)|0,m=m+Math.imul(U,wr)|0,m=m+Math.imul(G,_r)|0,x=x+Math.imul(G,wr)|0;var Vv=(D+P|0)+((m&8191)<<13)|0;D=(x+(m>>>13)|0)+(Vv>>>26)|0,Vv&=67108863,P=Math.imul(X,ke),m=Math.imul(X,Oe),m=m+Math.imul(ie,ke)|0,x=Math.imul(ie,Oe),P=P+Math.imul(Lt,Ze)|0,m=m+Math.imul(Lt,Pt)|0,m=m+Math.imul(N,Ze)|0,x=x+Math.imul(N,Pt)|0,P=P+Math.imul(Et,$e)|0,m=m+Math.imul(Et,Ee)|0,m=m+Math.imul(_t,$e)|0,x=x+Math.imul(_t,Ee)|0,P=P+Math.imul(Be,wt)|0,m=m+Math.imul(Be,Ft)|0,m=m+Math.imul(vt,wt)|0,x=x+Math.imul(vt,Ft)|0,P=P+Math.imul(Pe,Dt)|0,m=m+Math.imul(Pe,gr)|0,m=m+Math.imul(Me,Dt)|0,x=x+Math.imul(Me,gr)|0,P=P+Math.imul(be,mr)|0,m=m+Math.imul(be,vr)|0,m=m+Math.imul(_e,mr)|0,x=x+Math.imul(_e,vr)|0,P=P+Math.imul(he,yr)|0,m=m+Math.imul(he,br)|0,m=m+Math.imul(ve,yr)|0,x=x+Math.imul(ve,br)|0,P=P+Math.imul(ae,_r)|0,m=m+Math.imul(ae,wr)|0,m=m+Math.imul(oe,_r)|0,x=x+Math.imul(oe,wr)|0,P=P+Math.imul(U,Sr)|0,m=m+Math.imul(U,Er)|0,m=m+Math.imul(G,Sr)|0,x=x+Math.imul(G,Er)|0;var Gv=(D+P|0)+((m&8191)<<13)|0;D=(x+(m>>>13)|0)+(Gv>>>26)|0,Gv&=67108863,P=Math.imul(se,ke),m=Math.imul(se,Oe),m=m+Math.imul(me,ke)|0,x=Math.imul(me,Oe),P=P+Math.imul(X,Ze)|0,m=m+Math.imul(X,Pt)|0,m=m+Math.imul(ie,Ze)|0,x=x+Math.imul(ie,Pt)|0,P=P+Math.imul(Lt,$e)|0,m=m+Math.imul(Lt,Ee)|0,m=m+Math.imul(N,$e)|0,x=x+Math.imul(N,Ee)|0,P=P+Math.imul(Et,wt)|0,m=m+Math.imul(Et,Ft)|0,m=m+Math.imul(_t,wt)|0,x=x+Math.imul(_t,Ft)|0,P=P+Math.imul(Be,Dt)|0,m=m+Math.imul(Be,gr)|0,m=m+Math.imul(vt,Dt)|0,x=x+Math.imul(vt,gr)|0,P=P+Math.imul(Pe,mr)|0,m=m+Math.imul(Pe,vr)|0,m=m+Math.imul(Me,mr)|0,x=x+Math.imul(Me,vr)|0,P=P+Math.imul(be,yr)|0,m=m+Math.imul(be,br)|0,m=m+Math.imul(_e,yr)|0,x=x+Math.imul(_e,br)|0,P=P+Math.imul(he,_r)|0,m=m+Math.imul(he,wr)|0,m=m+Math.imul(ve,_r)|0,x=x+Math.imul(ve,wr)|0,P=P+Math.imul(ae,Sr)|0,m=m+Math.imul(ae,Er)|0,m=m+Math.imul(oe,Sr)|0,x=x+Math.imul(oe,Er)|0,P=P+Math.imul(U,xr)|0,m=m+Math.imul(U,Or)|0,m=m+Math.imul(G,xr)|0,x=x+Math.imul(G,Or)|0;var Wv=(D+P|0)+((m&8191)<<13)|0;D=(x+(m>>>13)|0)+(Wv>>>26)|0,Wv&=67108863,P=Math.imul(se,Ze),m=Math.imul(se,Pt),m=m+Math.imul(me,Ze)|0,x=Math.imul(me,Pt),P=P+Math.imul(X,$e)|0,m=m+Math.imul(X,Ee)|0,m=m+Math.imul(ie,$e)|0,x=x+Math.imul(ie,Ee)|0,P=P+Math.imul(Lt,wt)|0,m=m+Math.imul(Lt,Ft)|0,m=m+Math.imul(N,wt)|0,x=x+Math.imul(N,Ft)|0,P=P+Math.imul(Et,Dt)|0,m=m+Math.imul(Et,gr)|0,m=m+Math.imul(_t,Dt)|0,x=x+Math.imul(_t,gr)|0,P=P+Math.imul(Be,mr)|0,m=m+Math.imul(Be,vr)|0,m=m+Math.imul(vt,mr)|0,x=x+Math.imul(vt,vr)|0,P=P+Math.imul(Pe,yr)|0,m=m+Math.imul(Pe,br)|0,m=m+Math.imul(Me,yr)|0,x=x+Math.imul(Me,br)|0,P=P+Math.imul(be,_r)|0,m=m+Math.imul(be,wr)|0,m=m+Math.imul(_e,_r)|0,x=x+Math.imul(_e,wr)|0,P=P+Math.imul(he,Sr)|0,m=m+Math.imul(he,Er)|0,m=m+Math.imul(ve,Sr)|0,x=x+Math.imul(ve,Er)|0,P=P+Math.imul(ae,xr)|0,m=m+Math.imul(ae,Or)|0,m=m+Math.imul(oe,xr)|0,x=x+Math.imul(oe,Or)|0;var Yv=(D+P|0)+((m&8191)<<13)|0;D=(x+(m>>>13)|0)+(Yv>>>26)|0,Yv&=67108863,P=Math.imul(se,$e),m=Math.imul(se,Ee),m=m+Math.imul(me,$e)|0,x=Math.imul(me,Ee),P=P+Math.imul(X,wt)|0,m=m+Math.imul(X,Ft)|0,m=m+Math.imul(ie,wt)|0,x=x+Math.imul(ie,Ft)|0,P=P+Math.imul(Lt,Dt)|0,m=m+Math.imul(Lt,gr)|0,m=m+Math.imul(N,Dt)|0,x=x+Math.imul(N,gr)|0,P=P+Math.imul(Et,mr)|0,m=m+Math.imul(Et,vr)|0,m=m+Math.imul(_t,mr)|0,x=x+Math.imul(_t,vr)|0,P=P+Math.imul(Be,yr)|0,m=m+Math.imul(Be,br)|0,m=m+Math.imul(vt,yr)|0,x=x+Math.imul(vt,br)|0,P=P+Math.imul(Pe,_r)|0,m=m+Math.imul(Pe,wr)|0,m=m+Math.imul(Me,_r)|0,x=x+Math.imul(Me,wr)|0,P=P+Math.imul(be,Sr)|0,m=m+Math.imul(be,Er)|0,m=m+Math.imul(_e,Sr)|0,x=x+Math.imul(_e,Er)|0,P=P+Math.imul(he,xr)|0,m=m+Math.imul(he,Or)|0,m=m+Math.imul(ve,xr)|0,x=x+Math.imul(ve,Or)|0;var Zv=(D+P|0)+((m&8191)<<13)|0;D=(x+(m>>>13)|0)+(Zv>>>26)|0,Zv&=67108863,P=Math.imul(se,wt),m=Math.imul(se,Ft),m=m+Math.imul(me,wt)|0,x=Math.imul(me,Ft),P=P+Math.imul(X,Dt)|0,m=m+Math.imul(X,gr)|0,m=m+Math.imul(ie,Dt)|0,x=x+Math.imul(ie,gr)|0,P=P+Math.imul(Lt,mr)|0,m=m+Math.imul(Lt,vr)|0,m=m+Math.imul(N,mr)|0,x=x+Math.imul(N,vr)|0,P=P+Math.imul(Et,yr)|0,m=m+Math.imul(Et,br)|0,m=m+Math.imul(_t,yr)|0,x=x+Math.imul(_t,br)|0,P=P+Math.imul(Be,_r)|0,m=m+Math.imul(Be,wr)|0,m=m+Math.imul(vt,_r)|0,x=x+Math.imul(vt,wr)|0,P=P+Math.imul(Pe,Sr)|0,m=m+Math.imul(Pe,Er)|0,m=m+Math.imul(Me,Sr)|0,x=x+Math.imul(Me,Er)|0,P=P+Math.imul(be,xr)|0,m=m+Math.imul(be,Or)|0,m=m+Math.imul(_e,xr)|0,x=x+Math.imul(_e,Or)|0;var $v=(D+P|0)+((m&8191)<<13)|0;D=(x+(m>>>13)|0)+($v>>>26)|0,$v&=67108863,P=Math.imul(se,Dt),m=Math.imul(se,gr),m=m+Math.imul(me,Dt)|0,x=Math.imul(me,gr),P=P+Math.imul(X,mr)|0,m=m+Math.imul(X,vr)|0,m=m+Math.imul(ie,mr)|0,x=x+Math.imul(ie,vr)|0,P=P+Math.imul(Lt,yr)|0,m=m+Math.imul(Lt,br)|0,m=m+Math.imul(N,yr)|0,x=x+Math.imul(N,br)|0,P=P+Math.imul(Et,_r)|0,m=m+Math.imul(Et,wr)|0,m=m+Math.imul(_t,_r)|0,x=x+Math.imul(_t,wr)|0,P=P+Math.imul(Be,Sr)|0,m=m+Math.imul(Be,Er)|0,m=m+Math.imul(vt,Sr)|0,x=x+Math.imul(vt,Er)|0,P=P+Math.imul(Pe,xr)|0,m=m+Math.imul(Pe,Or)|0,m=m+Math.imul(Me,xr)|0,x=x+Math.imul(Me,Or)|0;var Xv=(D+P|0)+((m&8191)<<13)|0;D=(x+(m>>>13)|0)+(Xv>>>26)|0,Xv&=67108863,P=Math.imul(se,mr),m=Math.imul(se,vr),m=m+Math.imul(me,mr)|0,x=Math.imul(me,vr),P=P+Math.imul(X,yr)|0,m=m+Math.imul(X,br)|0,m=m+Math.imul(ie,yr)|0,x=x+Math.imul(ie,br)|0,P=P+Math.imul(Lt,_r)|0,m=m+Math.imul(Lt,wr)|0,m=m+Math.imul(N,_r)|0,x=x+Math.imul(N,wr)|0,P=P+Math.imul(Et,Sr)|0,m=m+Math.imul(Et,Er)|0,m=m+Math.imul(_t,Sr)|0,x=x+Math.imul(_t,Er)|0,P=P+Math.imul(Be,xr)|0,m=m+Math.imul(Be,Or)|0,m=m+Math.imul(vt,xr)|0,x=x+Math.imul(vt,Or)|0;var Jv=(D+P|0)+((m&8191)<<13)|0;D=(x+(m>>>13)|0)+(Jv>>>26)|0,Jv&=67108863,P=Math.imul(se,yr),m=Math.imul(se,br),m=m+Math.imul(me,yr)|0,x=Math.imul(me,br),P=P+Math.imul(X,_r)|0,m=m+Math.imul(X,wr)|0,m=m+Math.imul(ie,_r)|0,x=x+Math.imul(ie,wr)|0,P=P+Math.imul(Lt,Sr)|0,m=m+Math.imul(Lt,Er)|0,m=m+Math.imul(N,Sr)|0,x=x+Math.imul(N,Er)|0,P=P+Math.imul(Et,xr)|0,m=m+Math.imul(Et,Or)|0,m=m+Math.imul(_t,xr)|0,x=x+Math.imul(_t,Or)|0;var Qv=(D+P|0)+((m&8191)<<13)|0;D=(x+(m>>>13)|0)+(Qv>>>26)|0,Qv&=67108863,P=Math.imul(se,_r),m=Math.imul(se,wr),m=m+Math.imul(me,_r)|0,x=Math.imul(me,wr),P=P+Math.imul(X,Sr)|0,m=m+Math.imul(X,Er)|0,m=m+Math.imul(ie,Sr)|0,x=x+Math.imul(ie,Er)|0,P=P+Math.imul(Lt,xr)|0,m=m+Math.imul(Lt,Or)|0,m=m+Math.imul(N,xr)|0,x=x+Math.imul(N,Or)|0;var e0=(D+P|0)+((m&8191)<<13)|0;D=(x+(m>>>13)|0)+(e0>>>26)|0,e0&=67108863,P=Math.imul(se,Sr),m=Math.imul(se,Er),m=m+Math.imul(me,Sr)|0,x=Math.imul(me,Er),P=P+Math.imul(X,xr)|0,m=m+Math.imul(X,Or)|0,m=m+Math.imul(ie,xr)|0,x=x+Math.imul(ie,Or)|0;var t0=(D+P|0)+((m&8191)<<13)|0;D=(x+(m>>>13)|0)+(t0>>>26)|0,t0&=67108863,P=Math.imul(se,xr),m=Math.imul(se,Or),m=m+Math.imul(me,xr)|0,x=Math.imul(me,Or);var r0=(D+P|0)+((m&8191)<<13)|0;return D=(x+(m>>>13)|0)+(r0>>>26)|0,r0&=67108863,C[0]=Hv,C[1]=qv,C[2]=Uv,C[3]=Fv,C[4]=jv,C[5]=zv,C[6]=Kv,C[7]=Vv,C[8]=Gv,C[9]=Wv,C[10]=Yv,C[11]=Zv,C[12]=$v,C[13]=Xv,C[14]=Jv,C[15]=Qv,C[16]=e0,C[17]=t0,C[18]=r0,D!==0&&(C[19]=D,w.length++),w};Math.imul||(_=v);function I(E,h,y){y.negative=h.negative^E.negative,y.length=E.length+h.length;for(var w=0,S=0,O=0;O<y.length-1;O++){var C=S;S=0;for(var D=w&67108863,P=Math.min(O,h.length-1),m=Math.max(0,O-E.length+1);m<=P;m++){var x=O-m,K=E.words[x]|0,U=h.words[m]|0,G=K*U,te=G&67108863;C=C+(G/67108864|0)|0,te=te+D|0,D=te&67108863,C=C+(te>>>26)|0,S+=C>>>26,C&=67108863}y.words[O]=D,w=C,C=S}return w!==0?y.words[O]=w:y.length--,y.strip()}function R(E,h,y){var w=new k;return w.mulp(E,h,y)}n.prototype.mulTo=function(h,y){var w,S=this.length+h.length;return this.length===10&&h.length===10?w=_(this,h,y):S<63?w=v(this,h,y):S<1024?w=I(this,h,y):w=R(this,h,y),w};function k(E,h){this.x=E,this.y=h}k.prototype.makeRBT=function(h){for(var y=new Array(h),w=n.prototype._countBits(h)-1,S=0;S<h;S++)y[S]=this.revBin(S,w,h);return y},k.prototype.revBin=function(h,y,w){if(h===0||h===w-1)return h;for(var S=0,O=0;O<y;O++)S|=(h&1)<<y-O-1,h>>=1;return S},k.prototype.permute=function(h,y,w,S,O,C){for(var D=0;D<C;D++)S[D]=y[h[D]],O[D]=w[h[D]]},k.prototype.transform=function(h,y,w,S,O,C){this.permute(C,h,y,w,S,O);for(var D=1;D<O;D<<=1)for(var P=D<<1,m=Math.cos(2*Math.PI/P),x=Math.sin(2*Math.PI/P),K=0;K<O;K+=P)for(var U=m,G=x,te=0;te<D;te++){var ae=w[K+te],oe=S[K+te],le=w[K+te+D],he=S[K+te+D],ve=U*le-G*he;he=U*he+G*le,le=ve,w[K+te]=ae+le,S[K+te]=oe+he,w[K+te+D]=ae-le,S[K+te+D]=oe-he,te!==P&&(ve=m*U-x*G,G=m*G+x*U,U=ve)}},k.prototype.guessLen13b=function(h,y){var w=Math.max(y,h)|1,S=w&1,O=0;for(w=w/2|0;w;w=w>>>1)O++;return 1<<O+1+S},k.prototype.conjugate=function(h,y,w){if(!(w<=1))for(var S=0;S<w/2;S++){var O=h[S];h[S]=h[w-S-1],h[w-S-1]=O,O=y[S],y[S]=-y[w-S-1],y[w-S-1]=-O}},k.prototype.normalize13b=function(h,y){for(var w=0,S=0;S<y/2;S++){var O=Math.round(h[2*S+1]/y)*8192+Math.round(h[2*S]/y)+w;h[S]=O&67108863,O<67108864?w=0:w=O/67108864|0}return h},k.prototype.convert13b=function(h,y,w,S){for(var O=0,C=0;C<y;C++)O=O+(h[C]|0),w[2*C]=O&8191,O=O>>>13,w[2*C+1]=O&8191,O=O>>>13;for(C=2*y;C<S;++C)w[C]=0;r(O===0),r((O&-8192)===0)},k.prototype.stub=function(h){for(var y=new Array(h),w=0;w<h;w++)y[w]=0;return y},k.prototype.mulp=function(h,y,w){var S=2*this.guessLen13b(h.length,y.length),O=this.makeRBT(S),C=this.stub(S),D=new Array(S),P=new Array(S),m=new Array(S),x=new Array(S),K=new Array(S),U=new Array(S),G=w.words;G.length=S,this.convert13b(h.words,h.length,D,S),this.convert13b(y.words,y.length,x,S),this.transform(D,C,P,m,S,O),this.transform(x,C,K,U,S,O);for(var te=0;te<S;te++){var ae=P[te]*K[te]-m[te]*U[te];m[te]=P[te]*U[te]+m[te]*K[te],P[te]=ae}return this.conjugate(P,m,S),this.transform(P,m,G,C,S,O),this.conjugate(G,C,S),this.normalize13b(G,S),w.negative=h.negative^y.negative,w.length=h.length+y.length,w.strip()},n.prototype.mul=function(h){var y=new n(null);return y.words=new Array(this.length+h.length),this.mulTo(h,y)},n.prototype.mulf=function(h){var y=new n(null);return y.words=new Array(this.length+h.length),R(this,h,y)},n.prototype.imul=function(h){return this.clone().mulTo(h,this)},n.prototype.imuln=function(h){r(typeof h=="number"),r(h<67108864);for(var y=0,w=0;w<this.length;w++){var S=(this.words[w]|0)*h,O=(S&67108863)+(y&67108863);y>>=26,y+=S/67108864|0,y+=O>>>26,this.words[w]=O&67108863}return y!==0&&(this.words[w]=y,this.length++),h===0&&(this.length=1,this._normSign()),this},n.prototype.muln=function(h){return this.clone().imuln(h)},n.prototype.sqr=function(){return this.mul(this)},n.prototype.isqr=function(){return this.imul(this.clone())},n.prototype.pow=function(h){var y=d(h);if(y.length===0)return new n(1);for(var w=this,S=0;S<y.length&&y[S]===0;S++,w=w.sqr());if(++S<y.length)for(var O=w.sqr();S<y.length;S++,O=O.sqr())y[S]!==0&&(w=w.mul(O));return w},n.prototype.iushln=function(h){r(typeof h=="number"&&h>=0);var y=h%26,w=(h-y)/26,S=67108863>>>26-y<<26-y,O;if(y!==0){var C=0;for(O=0;O<this.length;O++){var D=this.words[O]&S,P=(this.words[O]|0)-D<<y;this.words[O]=P|C,C=D>>>26-y}C&&(this.words[O]=C,this.length++)}if(w!==0){for(O=this.length-1;O>=0;O--)this.words[O+w]=this.words[O];for(O=0;O<w;O++)this.words[O]=0;this.length+=w}return this.strip()},n.prototype.ishln=function(h){return r(this.negative===0),this.iushln(h)},n.prototype.iushrn=function(h,y,w){r(typeof h=="number"&&h>=0);var S;y?S=(y-y%26)/26:S=0;var O=h%26,C=Math.min((h-O)/26,this.length),D=67108863^67108863>>>O<<O,P=w;if(S-=C,S=Math.max(0,S),P){for(var m=0;m<C;m++)P.words[m]=this.words[m];P.length=C}if(C!==0)if(this.length>C)for(this.length-=C,m=0;m<this.length;m++)this.words[m]=this.words[m+C];else this.words[0]=0,this.length=1;var x=0;for(m=this.length-1;m>=0&&(x!==0||m>=S);m--){var K=this.words[m]|0;this.words[m]=x<<26-O|K>>>O,x=K&D}return P&&x!==0&&(P.words[P.length++]=x),this.length===0&&(this.words[0]=0,this.length=1),this.strip()},n.prototype.ishrn=function(h,y,w){return r(this.negative===0),this.iushrn(h,y,w)},n.prototype.shln=function(h){return this.clone().ishln(h)},n.prototype.ushln=function(h){return this.clone().iushln(h)},n.prototype.shrn=function(h){return this.clone().ishrn(h)},n.prototype.ushrn=function(h){return this.clone().iushrn(h)},n.prototype.testn=function(h){r(typeof h=="number"&&h>=0);var y=h%26,w=(h-y)/26,S=1<<y;if(this.length<=w)return!1;var O=this.words[w];return!!(O&S)},n.prototype.imaskn=function(h){r(typeof h=="number"&&h>=0);var y=h%26,w=(h-y)/26;if(r(this.negative===0,"imaskn works only with positive numbers"),this.length<=w)return this;if(y!==0&&w++,this.length=Math.min(w,this.length),y!==0){var S=67108863^67108863>>>y<<y;this.words[this.length-1]&=S}return this.length===0&&(this.words[0]=0,this.length=1),this.strip()},n.prototype.maskn=function(h){return this.clone().imaskn(h)},n.prototype.iaddn=function(h){return r(typeof h=="number"),r(h<67108864),h<0?this.isubn(-h):this.negative!==0?this.length===1&&(this.words[0]|0)<h?(this.words[0]=h-(this.words[0]|0),this.negative=0,this):(this.negative=0,this.isubn(h),this.negative=1,this):this._iaddn(h)},n.prototype._iaddn=function(h){this.words[0]+=h;for(var y=0;y<this.length&&this.words[y]>=67108864;y++)this.words[y]-=67108864,y===this.length-1?this.words[y+1]=1:this.words[y+1]++;return this.length=Math.max(this.length,y+1),this},n.prototype.isubn=function(h){if(r(typeof h=="number"),r(h<67108864),h<0)return this.iaddn(-h);if(this.negative!==0)return this.negative=0,this.iaddn(h),this.negative=1,this;if(this.words[0]-=h,this.length===1&&this.words[0]<0)this.words[0]=-this.words[0],this.negative=1;else for(var y=0;y<this.length&&this.words[y]<0;y++)this.words[y]+=67108864,this.words[y+1]-=1;return this.strip()},n.prototype.addn=function(h){return this.clone().iaddn(h)},n.prototype.subn=function(h){return this.clone().isubn(h)},n.prototype.iabs=function(){return this.negative=0,this},n.prototype.abs=function(){return this.clone().iabs()},n.prototype._ishlnsubmul=function(h,y,w){var S=h.length+w,O;this._expand(S);var C,D=0;for(O=0;O<h.length;O++){C=(this.words[O+w]|0)+D;var P=(h.words[O]|0)*y;C-=P&67108863,D=(C>>26)-(P/67108864|0),this.words[O+w]=C&67108863}for(;O<this.length-w;O++)C=(this.words[O+w]|0)+D,D=C>>26,this.words[O+w]=C&67108863;if(D===0)return this.strip();for(r(D===-1),D=0,O=0;O<this.length;O++)C=-(this.words[O]|0)+D,D=C>>26,this.words[O]=C&67108863;return this.negative=1,this.strip()},n.prototype._wordDiv=function(h,y){var w=this.length-h.length,S=this.clone(),O=h,C=O.words[O.length-1]|0,D=this._countBits(C);w=26-D,w!==0&&(O=O.ushln(w),S.iushln(w),C=O.words[O.length-1]|0);var P=S.length-O.length,m;if(y!=="mod"){m=new n(null),m.length=P+1,m.words=new Array(m.length);for(var x=0;x<m.length;x++)m.words[x]=0}var K=S.clone()._ishlnsubmul(O,1,P);K.negative===0&&(S=K,m&&(m.words[P]=1));for(var U=P-1;U>=0;U--){var G=(S.words[O.length+U]|0)*67108864+(S.words[O.length+U-1]|0);for(G=Math.min(G/C|0,67108863),S._ishlnsubmul(O,G,U);S.negative!==0;)G--,S.negative=0,S._ishlnsubmul(O,1,U),S.isZero()||(S.negative^=1);m&&(m.words[U]=G)}return m&&m.strip(),S.strip(),y!=="div"&&w!==0&&S.iushrn(w),{div:m||null,mod:S}},n.prototype.divmod=function(h,y,w){if(r(!h.isZero()),this.isZero())return{div:new n(0),mod:new n(0)};var S,O,C;return this.negative!==0&&h.negative===0?(C=this.neg().divmod(h,y),y!=="mod"&&(S=C.div.neg()),y!=="div"&&(O=C.mod.neg(),w&&O.negative!==0&&O.iadd(h)),{div:S,mod:O}):this.negative===0&&h.negative!==0?(C=this.divmod(h.neg(),y),y!=="mod"&&(S=C.div.neg()),{div:S,mod:C.mod}):(this.negative&h.negative)!==0?(C=this.neg().divmod(h.neg(),y),y!=="div"&&(O=C.mod.neg(),w&&O.negative!==0&&O.isub(h)),{div:C.div,mod:O}):h.length>this.length||this.cmp(h)<0?{div:new n(0),mod:this}:h.length===1?y==="div"?{div:this.divn(h.words[0]),mod:null}:y==="mod"?{div:null,mod:new n(this.modn(h.words[0]))}:{div:this.divn(h.words[0]),mod:new n(this.modn(h.words[0]))}:this._wordDiv(h,y)},n.prototype.div=function(h){return this.divmod(h,"div",!1).div},n.prototype.mod=function(h){return this.divmod(h,"mod",!1).mod},n.prototype.umod=function(h){return this.divmod(h,"mod",!0).mod},n.prototype.divRound=function(h){var y=this.divmod(h);if(y.mod.isZero())return y.div;var w=y.mod.abs(),S=h.abs().iushrn(1),O=h.words[0]&1,C=w.cmp(S);if(C<0||O===1&&C===0)return y.div;var D=new n(1);return D.negative=this.negative^h.negative,y.div.iadd(D)},n.prototype.modn=function(h){r(h<=67108863);for(var y=(1<<26)%h,w=0,S=this.length-1;S>=0;S--)w=(y*w+(this.words[S]|0))%h;return w},n.prototype.idivn=function(h){r(h<=67108863);for(var y=0,w=this.length-1;w>=0;w--){var S=(this.words[w]|0)+y*67108864;this.words[w]=S/h|0,y=S%h}return this.strip()},n.prototype.divn=function(h){return this.clone().idivn(h)},n.prototype.egcd=function(h){r(h.negative===0),r(!h.isZero());var y=this,w=h.clone();y.negative!==0?y=y.umod(h):y=y.clone();for(var S=new n(1),O=new n(0),C=new n(0),D=new n(1),P=0;y.isEven()&&w.isEven();)y.iushrn(1),w.iushrn(1),++P;for(var m=w.clone(),x=y.clone();!y.isZero();){for(var K=0,U=1;(y.words[0]&U)===0&&K<26;++K,U<<=1);if(K>0)for(y.iushrn(K);K-- >0;)(S.isOdd()||O.isOdd())&&(S.iadd(m),O.isub(x)),S.iushrn(1),O.iushrn(1);for(var G=0,te=1;(w.words[0]&te)===0&&G<26;++G,te<<=1);if(G>0)for(w.iushrn(G);G-- >0;)(C.isOdd()||D.isOdd())&&(C.iadd(m),D.isub(x)),C.iushrn(1),D.iushrn(1);y.cmp(w)>=0?(y.isub(w),S.isub(C),O.isub(D)):(w.isub(y),C.isub(S),D.isub(O))}return{a:C,b:D,gcd:w.iushln(P)}},n.prototype._invmp=function(h){r(h.negative===0),r(!h.isZero());var y=this,w=h.clone();y.negative!==0?y=y.umod(h):y=y.clone();for(var S=new n(1),O=new n(0),C=w.clone();y.cmpn(1)>0&&w.cmpn(1)>0;){for(var D=0,P=1;(y.words[0]&P)===0&&D<26;++D,P<<=1);if(D>0)for(y.iushrn(D);D-- >0;)S.isOdd()&&S.iadd(C),S.iushrn(1);for(var m=0,x=1;(w.words[0]&x)===0&&m<26;++m,x<<=1);if(m>0)for(w.iushrn(m);m-- >0;)O.isOdd()&&O.iadd(C),O.iushrn(1);y.cmp(w)>=0?(y.isub(w),S.isub(O)):(w.isub(y),O.isub(S))}var K;return y.cmpn(1)===0?K=S:K=O,K.cmpn(0)<0&&K.iadd(h),K},n.prototype.gcd=function(h){if(this.isZero())return h.abs();if(h.isZero())return this.abs();var y=this.clone(),w=h.clone();y.negative=0,w.negative=0;for(var S=0;y.isEven()&&w.isEven();S++)y.iushrn(1),w.iushrn(1);do{for(;y.isEven();)y.iushrn(1);for(;w.isEven();)w.iushrn(1);var O=y.cmp(w);if(O<0){var C=y;y=w,w=C}else if(O===0||w.cmpn(1)===0)break;y.isub(w)}while(!0);return w.iushln(S)},n.prototype.invm=function(h){return this.egcd(h).a.umod(h)},n.prototype.isEven=function(){return(this.words[0]&1)===0},n.prototype.isOdd=function(){return(this.words[0]&1)===1},n.prototype.andln=function(h){return this.words[0]&h},n.prototype.bincn=function(h){r(typeof h=="number");var y=h%26,w=(h-y)/26,S=1<<y;if(this.length<=w)return this._expand(w+1),this.words[w]|=S,this;for(var O=S,C=w;O!==0&&C<this.length;C++){var D=this.words[C]|0;D+=O,O=D>>>26,D&=67108863,this.words[C]=D}return O!==0&&(this.words[C]=O,this.length++),this},n.prototype.isZero=function(){return this.length===1&&this.words[0]===0},n.prototype.cmpn=function(h){var y=h<0;if(this.negative!==0&&!y)return-1;if(this.negative===0&&y)return 1;this.strip();var w;if(this.length>1)w=1;else{y&&(h=-h),r(h<=67108863,"Number is too big");var S=this.words[0]|0;w=S===h?0:S<h?-1:1}return this.negative!==0?-w|0:w},n.prototype.cmp=function(h){if(this.negative!==0&&h.negative===0)return-1;if(this.negative===0&&h.negative!==0)return 1;var y=this.ucmp(h);return this.negative!==0?-y|0:y},n.prototype.ucmp=function(h){if(this.length>h.length)return 1;if(this.length<h.length)return-1;for(var y=0,w=this.length-1;w>=0;w--){var S=this.words[w]|0,O=h.words[w]|0;if(S!==O){S<O?y=-1:S>O&&(y=1);break}}return y},n.prototype.gtn=function(h){return this.cmpn(h)===1},n.prototype.gt=function(h){return this.cmp(h)===1},n.prototype.gten=function(h){return this.cmpn(h)>=0},n.prototype.gte=function(h){return this.cmp(h)>=0},n.prototype.ltn=function(h){return this.cmpn(h)===-1},n.prototype.lt=function(h){return this.cmp(h)===-1},n.prototype.lten=function(h){return this.cmpn(h)<=0},n.prototype.lte=function(h){return this.cmp(h)<=0},n.prototype.eqn=function(h){return this.cmpn(h)===0},n.prototype.eq=function(h){return this.cmp(h)===0},n.red=function(h){return new V(h)},n.prototype.toRed=function(h){return r(!this.red,"Already a number in reduction context"),r(this.negative===0,"red works only with positives"),h.convertTo(this)._forceRed(h)},n.prototype.fromRed=function(){return r(this.red,"fromRed works only with numbers in reduction context"),this.red.convertFrom(this)},n.prototype._forceRed=function(h){return this.red=h,this},n.prototype.forceRed=function(h){return r(!this.red,"Already a number in reduction context"),this._forceRed(h)},n.prototype.redAdd=function(h){return r(this.red,"redAdd works only with red numbers"),this.red.add(this,h)},n.prototype.redIAdd=function(h){return r(this.red,"redIAdd works only with red numbers"),this.red.iadd(this,h)},n.prototype.redSub=function(h){return r(this.red,"redSub works only with red numbers"),this.red.sub(this,h)},n.prototype.redISub=function(h){return r(this.red,"redISub works only with red numbers"),this.red.isub(this,h)},n.prototype.redShl=function(h){return r(this.red,"redShl works only with red numbers"),this.red.shl(this,h)},n.prototype.redMul=function(h){return r(this.red,"redMul works only with red numbers"),this.red._verify2(this,h),this.red.mul(this,h)},n.prototype.redIMul=function(h){return r(this.red,"redMul works only with red numbers"),this.red._verify2(this,h),this.red.imul(this,h)},n.prototype.redSqr=function(){return r(this.red,"redSqr works only with red numbers"),this.red._verify1(this),this.red.sqr(this)},n.prototype.redISqr=function(){return r(this.red,"redISqr works only with red numbers"),this.red._verify1(this),this.red.isqr(this)},n.prototype.redSqrt=function(){return r(this.red,"redSqrt works only with red numbers"),this.red._verify1(this),this.red.sqrt(this)},n.prototype.redInvm=function(){return r(this.red,"redInvm works only with red numbers"),this.red._verify1(this),this.red.invm(this)},n.prototype.redNeg=function(){return r(this.red,"redNeg works only with red numbers"),this.red._verify1(this),this.red.neg(this)},n.prototype.redPow=function(h){return r(this.red&&!h.red,"redPow(normalNum)"),this.red._verify1(this),this.red.pow(this,h)};var q={k256:null,p224:null,p192:null,p25519:null};function z(E,h){this.name=E,this.p=new n(h,16),this.n=this.p.bitLength(),this.k=new n(1).iushln(this.n).isub(this.p),this.tmp=this._tmp()}z.prototype._tmp=function(){var h=new n(null);return h.words=new Array(Math.ceil(this.n/13)),h},z.prototype.ireduce=function(h){var y=h,w;do this.split(y,this.tmp),y=this.imulK(y),y=y.iadd(this.tmp),w=y.bitLength();while(w>this.n);var S=w<this.n?-1:y.ucmp(this.p);return S===0?(y.words[0]=0,y.length=1):S>0?y.isub(this.p):y.strip!==void 0?y.strip():y._strip(),y},z.prototype.split=function(h,y){h.iushrn(this.n,0,y)},z.prototype.imulK=function(h){return h.imul(this.k)};function A(){z.call(this,"k256","ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff fffffffe fffffc2f")}i(A,z),A.prototype.split=function(h,y){for(var w=4194303,S=Math.min(h.length,9),O=0;O<S;O++)y.words[O]=h.words[O];if(y.length=S,h.length<=9){h.words[0]=0,h.length=1;return}var C=h.words[9];for(y.words[y.length++]=C&w,O=10;O<h.length;O++){var D=h.words[O]|0;h.words[O-10]=(D&w)<<4|C>>>22,C=D}C>>>=22,h.words[O-10]=C,C===0&&h.length>10?h.length-=10:h.length-=9},A.prototype.imulK=function(h){h.words[h.length]=0,h.words[h.length+1]=0,h.length+=2;for(var y=0,w=0;w<h.length;w++){var S=h.words[w]|0;y+=S*977,h.words[w]=y&67108863,y=S*64+(y/67108864|0)}return h.words[h.length-1]===0&&(h.length--,h.words[h.length-1]===0&&h.length--),h};function B(){z.call(this,"p224","ffffffff ffffffff ffffffff ffffffff 00000000 00000000 00000001")}i(B,z);function M(){z.call(this,"p192","ffffffff ffffffff ffffffff fffffffe ffffffff ffffffff")}i(M,z);function F(){z.call(this,"25519","7fffffffffffffff ffffffffffffffff ffffffffffffffff ffffffffffffffed")}i(F,z),F.prototype.imulK=function(h){for(var y=0,w=0;w<h.length;w++){var S=(h.words[w]|0)*19+y,O=S&67108863;S>>>=26,h.words[w]=O,y=S}return y!==0&&(h.words[h.length++]=y),h},n._prime=function(h){if(q[h])return q[h];var y;if(h==="k256")y=new A;else if(h==="p224")y=new B;else if(h==="p192")y=new M;else if(h==="p25519")y=new F;else throw new Error("Unknown prime "+h);return q[h]=y,y};function V(E){if(typeof E=="string"){var h=n._prime(E);this.m=h.p,this.prime=h}else r(E.gtn(1),"modulus must be greater than 1"),this.m=E,this.prime=null}V.prototype._verify1=function(h){r(h.negative===0,"red works only with positives"),r(h.red,"red works only with red numbers")},V.prototype._verify2=function(h,y){r((h.negative|y.negative)===0,"red works only with positives"),r(h.red&&h.red===y.red,"red works only with red numbers")},V.prototype.imod=function(h){return this.prime?this.prime.ireduce(h)._forceRed(this):h.umod(this.m)._forceRed(this)},V.prototype.neg=function(h){return h.isZero()?h.clone():this.m.sub(h)._forceRed(this)},V.prototype.add=function(h,y){this._verify2(h,y);var w=h.add(y);return w.cmp(this.m)>=0&&w.isub(this.m),w._forceRed(this)},V.prototype.iadd=function(h,y){this._verify2(h,y);var w=h.iadd(y);return w.cmp(this.m)>=0&&w.isub(this.m),w},V.prototype.sub=function(h,y){this._verify2(h,y);var w=h.sub(y);return w.cmpn(0)<0&&w.iadd(this.m),w._forceRed(this)},V.prototype.isub=function(h,y){this._verify2(h,y);var w=h.isub(y);return w.cmpn(0)<0&&w.iadd(this.m),w},V.prototype.shl=function(h,y){return this._verify1(h),this.imod(h.ushln(y))},V.prototype.imul=function(h,y){return this._verify2(h,y),this.imod(h.imul(y))},V.prototype.mul=function(h,y){return this._verify2(h,y),this.imod(h.mul(y))},V.prototype.isqr=function(h){return this.imul(h,h.clone())},V.prototype.sqr=function(h){return this.mul(h,h)},V.prototype.sqrt=function(h){if(h.isZero())return h.clone();var y=this.m.andln(3);if(r(y%2===1),y===3){var w=this.m.add(new n(1)).iushrn(2);return this.pow(h,w)}for(var S=this.m.subn(1),O=0;!S.isZero()&&S.andln(1)===0;)O++,S.iushrn(1);r(!S.isZero());var C=new n(1).toRed(this),D=C.redNeg(),P=this.m.subn(1).iushrn(1),m=this.m.bitLength();for(m=new n(2*m*m).toRed(this);this.pow(m,P).cmp(D)!==0;)m.redIAdd(D);for(var x=this.pow(m,S),K=this.pow(h,S.addn(1).iushrn(1)),U=this.pow(h,S),G=O;U.cmp(C)!==0;){for(var te=U,ae=0;te.cmp(C)!==0;ae++)te=te.redSqr();r(ae<G);var oe=this.pow(x,new n(1).iushln(G-ae-1));K=K.redMul(oe),x=oe.redSqr(),U=U.redMul(x),G=ae}return K},V.prototype.invm=function(h){var y=h._invmp(this.m);return y.negative!==0?(y.negative=0,this.imod(y).redNeg()):this.imod(y)},V.prototype.pow=function(h,y){if(y.isZero())return new n(1).toRed(this);if(y.cmpn(1)===0)return h.clone();var w=4,S=new Array(1<<w);S[0]=new n(1).toRed(this),S[1]=h;for(var O=2;O<S.length;O++)S[O]=this.mul(S[O-1],h);var C=S[0],D=0,P=0,m=y.bitLength()%26;for(m===0&&(m=26),O=y.length-1;O>=0;O--){for(var x=y.words[O],K=m-1;K>=0;K--){var U=x>>K&1;if(C!==S[0]&&(C=this.sqr(C)),U===0&&D===0){P=0;continue}D<<=1,D|=U,P++,!(P!==w&&(O!==0||K!==0))&&(C=this.mul(C,S[D]),P=0,D=0)}m=26}return C},V.prototype.convertTo=function(h){var y=h.umod(this.m);return y===h?y.clone():y},V.prototype.convertFrom=function(h){var y=h.clone();return y.red=null,y},n.mont=function(h){return new Y(h)};function Y(E){V.call(this,E),this.shift=this.m.bitLength(),this.shift%26!==0&&(this.shift+=26-this.shift%26),this.r=new n(1).iushln(this.shift),this.r2=this.imod(this.r.sqr()),this.rinv=this.r._invmp(this.m),this.minv=this.rinv.mul(this.r).isubn(1).div(this.m),this.minv=this.minv.umod(this.r),this.minv=this.r.sub(this.minv)}i(Y,V),Y.prototype.convertTo=function(h){return this.imod(h.ushln(this.shift))},Y.prototype.convertFrom=function(h){var y=this.imod(h.mul(this.rinv));return y.red=null,y},Y.prototype.imul=function(h,y){if(h.isZero()||y.isZero())return h.words[0]=0,h.length=1,h;var w=h.imul(y),S=w.maskn(this.shift).mul(this.minv).imaskn(this.shift).mul(this.m),O=w.isub(S).iushrn(this.shift),C=O;return O.cmp(this.m)>=0?C=O.isub(this.m):O.cmpn(0)<0&&(C=O.iadd(this.m)),C._forceRed(this)},Y.prototype.mul=function(h,y){if(h.isZero()||y.isZero())return new n(0)._forceRed(this);var w=h.mul(y),S=w.maskn(this.shift).mul(this.minv).imaskn(this.shift).mul(this.m),O=w.isub(S).iushrn(this.shift),C=O;return O.cmp(this.m)>=0?C=O.isub(this.m):O.cmpn(0)<0&&(C=O.iadd(this.m)),C._forceRed(this)},Y.prototype.invm=function(h){var y=this.imod(h._invmp(this.m).mul(this.r2));return y._forceRed(this)}})(typeof Qy>"u"||Qy,UT)});var eb=T((Nne,FT)=>{"use strict";g();FT.exports="9.22.0"});var zT=T((Lne,jT)=>{"use strict";g();var rK="https://docs.moneybutton.com/";jT.exports=[{name:"InvalidB58Char",message:"Invalid Base58 character: {0} in {1}"},{name:"InvalidB58Checksum",message:"Invalid Base58 checksum for {0}"},{name:"InvalidNetwork",message:"Invalid version for network: got {0}"},{name:"InvalidState",message:"Invalid state: {0}"},{name:"NotImplemented",message:"Function {0} was not implemented yet"},{name:"InvalidNetworkArgument",message:'Invalid network: must be "livenet" or "testnet", got {0}'},{name:"InvalidArgument",message:function(){return"Invalid Argument"+(arguments[0]?": "+arguments[0]:"")+(arguments[1]?" Documentation: "+rK+arguments[1]:"")}},{name:"AbstractMethodInvoked",message:"Abstract Method Invocation: {0}"},{name:"InvalidArgumentType",message:function(){return"Invalid Argument for "+arguments[2]+", expected "+arguments[1]+" but got "+typeof arguments[0]}},{name:"Unit",message:"Internal Error on Unit {0}",errors:[{name:"UnknownCode",message:"Unrecognized unit code: {0}"},{name:"InvalidRate",message:"Invalid exchange rate: {0}"}]},{name:"MerkleBlock",message:"Internal Error on MerkleBlock {0}",errors:[{name:"InvalidMerkleTree",message:"This MerkleBlock contain an invalid Merkle Tree"}]},{name:"Transaction",message:"Internal Error on Transaction {0}",errors:[{name:"Input",message:"Internal Error on Input {0}",errors:[{name:"MissingScript",message:"Need a script to create an input"},{name:"UnsupportedScript",message:"Unsupported input script type: {0}"},{name:"MissingPreviousOutput",message:"No previous output information."}]},{name:"NeedMoreInfo",message:"{0}"},{name:"InvalidSorting",message:"The sorting function provided did not return the change output as one of the array elements"},{name:"InvalidOutputAmountSum",message:"{0}"},{name:"MissingSignatures",message:"Some inputs have not been fully signed"},{name:"InvalidIndex",message:"Invalid index: {0} is not between 0, {1}"},{name:"UnableToVerifySignature",message:"Unable to verify signature: {0}"},{name:"DustOutputs",message:"Dust amount detected in one output"},{name:"InvalidSatoshis",message:"Output satoshis are invalid"},{name:"FeeError",message:"Internal Error on Fee {0}",errors:[{name:"TooSmall",message:"Fee is too small: {0}"},{name:"TooLarge",message:"Fee is too large: {0}"},{name:"Different",message:"Unspent value is different from specified fee: {0}"}]},{name:"ChangeAddressMissing",message:"Change address is missing"},{name:"BlockHeightTooHigh",message:"Block Height can be at most 2^32 -1"},{name:"NLockTimeOutOfRange",message:"Block Height can only be between 0 and 499 999 999"},{name:"LockTimeTooEarly",message:"Lock Time can't be earlier than UNIX date 500 000 000"}]},{name:"Script",message:"Internal Error on Script {0}",errors:[{name:"UnrecognizedAddress",message:"Expected argument {0} to be an address"},{name:"CantDeriveAddress",message:"Can't derive address associated with script {0}, needs to be p2pkh in, p2pkh out, p2sh in, or p2sh out."},{name:"InvalidBuffer",message:"Invalid script buffer: can't parse valid script from given buffer {0}"}]},{name:"HDPrivateKey",message:"Internal Error on HDPrivateKey {0}",errors:[{name:"InvalidDerivationArgument",message:"Invalid derivation argument {0}, expected string, or number and boolean"},{name:"InvalidEntropyArgument",message:"Invalid entropy: must be an hexa string or binary buffer, got {0}",errors:[{name:"TooMuchEntropy",message:'Invalid entropy: more than 512 bits is non standard, got "{0}"'},{name:"NotEnoughEntropy",message:'Invalid entropy: at least 128 bits needed, got "{0}"'}]},{name:"InvalidLength",message:"Invalid length for xprivkey string in {0}"},{name:"InvalidPath",message:"Invalid derivation path: {0}"},{name:"UnrecognizedArgument",message:'Invalid argument: creating a HDPrivateKey requires a string, buffer, json or object, got "{0}"'}]},{name:"HDPublicKey",message:"Internal Error on HDPublicKey {0}",errors:[{name:"ArgumentIsPrivateExtended",message:"Argument is an extended private key: {0}"},{name:"InvalidDerivationArgument",message:"Invalid derivation argument: got {0}"},{name:"InvalidLength",message:'Invalid length for xpubkey: got "{0}"'},{name:"InvalidPath",message:'Invalid derivation path, it should look like: "m/1/100", got "{0}"'},{name:"InvalidIndexCantDeriveHardened",message:"Invalid argument: creating a hardened path requires an HDPrivateKey"},{name:"MustSupplyArgument",message:"Must supply an argument to create a HDPublicKey"},{name:"UnrecognizedArgument",message:"Invalid argument for creation, must be string, json, buffer, or object"}]}]});var pi=T((Dne,rb)=>{"use strict";g();var tb=at();function iK(e,t){return e.replace("{0}",t[0]).replace("{1}",t[1]).replace("{2}",t[2])}var KT=function(e,t){var r=function(){if(tb.isString(t.message))this.message=iK(t.message,arguments);else if(tb.isFunction(t.message))this.message=t.message.apply(null,arguments);else throw new Error("Invalid error definition for "+t.name);this.stack=this.message+`
|
|
11
|
+
Use Chrome, Firefox or Internet Explorer 11`)}var Xz=ii().Buffer,Dp=globalThis.crypto||globalThis.msCrypto;Dp&&Dp.getRandomValues?Xy.exports=Jz:Xy.exports=$z;function Jz(e,t){if(e>Zz)throw new RangeError("requested too many random bytes");var r=Xz.allocUnsafe(e);if(e>0)if(e>$y)for(var i=0;i<e;i+=$y)Dp.getRandomValues(r.slice(i,i+$y));else Dp.getRandomValues(r);return typeof t=="function"?b.default.nextTick(function(){t(null,r)}):r}});var nr=T(Hp=>{"use strict";g();Hp.createHash=xT();Hp.createHmac=BT();Hp.randomBytes=NT()});var Ki=T((Ine,LT)=>{"use strict";g();var CT=65536;function Gs(){}Gs.getRandomBuffer=function(e){var t=typeof globalThis<"u"?globalThis.crypto:void 0;if(t&&typeof t.getRandomValues=="function")return Gs._fromGetRandomValues(t,e);try{var r=nr();if(r&&typeof r.randomBytes=="function")return r.randomBytes(e)}catch{}throw new Error("bsv: no CSPRNG available in this environment (needs globalThis.crypto.getRandomValues or node crypto)")};Gs._fromGetRandomValues=function(e,t){for(var r=f.Buffer.alloc(t),i=0;i<t;i+=CT){var n=new Uint8Array(Math.min(CT,t-i));e.getRandomValues(n),f.Buffer.from(n).copy(r,i)}return r};Gs.getRandomBufferNode=function(e){var t=nr();return t.randomBytes(e)};Gs.getRandomBufferBrowser=function(e){var t=typeof globalThis<"u"?globalThis:{},r=null;if(t.crypto&&typeof t.crypto.getRandomValues=="function"?r=t.crypto:t.msCrypto&&typeof t.msCrypto.getRandomValues=="function"&&(r=t.msCrypto),!r)throw new Error("window.crypto.getRandomValues not available");return Gs._fromGetRandomValues(r,e)};LT.exports=Gs});var at=T((Tne,MT)=>{"use strict";g();var Qz=Ki(),Ht={};Ht.isArray=e=>Array.isArray(e);Ht.isNumber=e=>typeof e=="number";Ht.isObject=e=>e&&typeof e=="object";Ht.isString=e=>typeof e=="string";Ht.isUndefined=e=>typeof e>"u";Ht.isFunction=e=>typeof e=="function";Ht.isNull=e=>e===null;Ht.isDate=e=>e instanceof Date;Ht.extend=(e,t)=>Object.assign(e,t);Ht.noop=()=>{};Ht.every=(e,t)=>e.every(t||(r=>r));Ht.map=(e,t)=>Array.from(e).map(t||(r=>r));Ht.includes=(e,t)=>e.includes(t);Ht.each=(e,t)=>e.forEach(t);Ht.clone=e=>Object.assign({},e);Ht.pick=(e,t)=>{let r={};return t.forEach(i=>{typeof e[i]<"u"&&(r[i]=e[i])}),r};Ht.values=e=>Object.values(e);Ht.filter=(e,t)=>e.filter(t);Ht.reduce=(e,t,r)=>e.reduce(t,r);Ht.without=(e,t)=>e.filter(r=>r!==t);Ht.shuffle=e=>{let t=e.slice(0);for(let r=t.length-1;r>0;r--){let n=Qz.getRandomBuffer(4).readUInt32BE(0)/4294967296,o=Math.floor(n*(r+1));[t[r],t[o]]=[t[o],t[r]]}return t};Ht.difference=(e,t)=>e.filter(r=>!t.includes(r));Ht.findIndex=(e,t)=>e.findIndex(t);Ht.some=(e,t)=>e.some(t);Ht.range=e=>[...Array(e).keys()];MT.exports=Ht});var pc=T((Rne,qT)=>{"use strict";g();var Jy=at(),DT=rr(),dc="123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz".split(""),HT={};for(Sl=0;Sl<dc.length;Sl++)HT[dc[Sl]]=Sl;var Sl;function eK(e){if(e.length===0)return"";var t=[0],r,i,n;for(r=0;r<e.length;r++){for(i=0,n=e[r];i<t.length;i++)n+=t[i]<<8,t[i]=n%58,n=n/58|0;for(;n>0;)t.push(n%58),n=n/58|0}var o="";for(r=0;e[r]===0&&r<e.length-1;r++)o+=dc[0];for(r=t.length-1;r>=0;r--)o+=dc[t[r]];return o}function tK(e){if(e.length===0)return f.Buffer.alloc(0);var t=[0],r,i,n;for(r=0;r<e.length;r++){var o=HT[e[r]];if(o===void 0)throw new Error("Non-base58 character");for(i=0,n=o;i<t.length;i++)n+=t[i]*58,t[i]=n&255,n>>=8;for(;n>0;)t.push(n&255),n>>=8}for(r=0;e[r]===dc[0]&&r<e.length-1;r++)t.push(0);return f.Buffer.from(t.reverse())}var Xr=function e(t){if(!(this instanceof e))return new e(t);if(f.Buffer.isBuffer(t)){var r=t;this.fromBuffer(r)}else if(typeof t=="string"){var i=t;this.fromString(i)}};Xr.validCharacters=function(t){return DT.Buffer.isBuffer(t)&&(t=t.toString()),Jy.every(Jy.map(t,function(r){return Jy.includes(dc,r)}))};Xr.prototype.set=function(e){return this.buf=e.buf||this.buf||void 0,this};Xr.encode=function(e){if(!DT.Buffer.isBuffer(e))throw new Error("Input should be a buffer");return eK(e)};Xr.decode=function(e){if(typeof e!="string")throw new Error("Input should be a string");return tK(e)};Xr.prototype.fromBuffer=function(e){return this.buf=e,this};Xr.fromBuffer=function(e){return new Xr().fromBuffer(e)};Xr.fromHex=function(e){return Xr.fromBuffer(f.Buffer.from(e,"hex"))};Xr.prototype.fromString=function(e){var t=Xr.decode(e);return this.buf=t,this};Xr.fromString=function(e){return new Xr().fromString(e)};Xr.prototype.toBuffer=function(){return this.buf};Xr.prototype.toHex=function(){return this.toBuffer().toString("hex")};Xr.prototype.toString=function(){return Xr.encode(this.buf)};qT.exports=Xr});var qp=T((UT,Qy)=>{g();(function(e,t){"use strict";function r(E,h){if(!E)throw new Error(h||"Assertion failed")}function i(E,h){E.super_=h;var y=function(){};y.prototype=h.prototype,E.prototype=new y,E.prototype.constructor=E}function n(E,h,y){if(n.isBN(E))return E;this.negative=0,this.words=null,this.length=0,this.red=null,E!==null&&((h==="le"||h==="be")&&(y=h,h=10),this._init(E||0,h||10,y||"be"))}typeof e=="object"?e.exports=n:t.BN=n,n.BN=n,n.wordSize=26;var o;try{typeof window<"u"&&typeof window.Buffer<"u"?o=window.Buffer:o=rr().Buffer}catch{}n.isBN=function(h){return h instanceof n?!0:h!==null&&typeof h=="object"&&h.constructor.wordSize===n.wordSize&&Array.isArray(h.words)},n.max=function(h,y){return h.cmp(y)>0?h:y},n.min=function(h,y){return h.cmp(y)<0?h:y},n.prototype._init=function(h,y,w){if(typeof h=="number")return this._initNumber(h,y,w);if(typeof h=="object")return this._initArray(h,y,w);y==="hex"&&(y=16),r(y===(y|0)&&y>=2&&y<=36),h=h.toString().replace(/\s+/g,"");var S=0;h[0]==="-"&&(S++,this.negative=1),S<h.length&&(y===16?this._parseHex(h,S,w):(this._parseBase(h,y,S),w==="le"&&this._initArray(this.toArray(),y,w)))},n.prototype._initNumber=function(h,y,w){h<0&&(this.negative=1,h=-h),h<67108864?(this.words=[h&67108863],this.length=1):h<4503599627370496?(this.words=[h&67108863,h/67108864&67108863],this.length=2):(r(h<9007199254740992),this.words=[h&67108863,h/67108864&67108863,1],this.length=3),w==="le"&&this._initArray(this.toArray(),y,w)},n.prototype._initArray=function(h,y,w){if(r(typeof h.length=="number"),h.length<=0)return this.words=[0],this.length=1,this;this.length=Math.ceil(h.length/3),this.words=new Array(this.length);for(var S=0;S<this.length;S++)this.words[S]=0;var O,C,D=0;if(w==="be")for(S=h.length-1,O=0;S>=0;S-=3)C=h[S]|h[S-1]<<8|h[S-2]<<16,this.words[O]|=C<<D&67108863,this.words[O+1]=C>>>26-D&67108863,D+=24,D>=26&&(D-=26,O++);else if(w==="le")for(S=0,O=0;S<h.length;S+=3)C=h[S]|h[S+1]<<8|h[S+2]<<16,this.words[O]|=C<<D&67108863,this.words[O+1]=C>>>26-D&67108863,D+=24,D>=26&&(D-=26,O++);return this.strip()};function a(E,h){var y=E.charCodeAt(h);return y>=65&&y<=70?y-55:y>=97&&y<=102?y-87:y-48&15}function s(E,h,y){var w=a(E,y);return y-1>=h&&(w|=a(E,y-1)<<4),w}n.prototype._parseHex=function(h,y,w){this.length=Math.ceil((h.length-y)/6),this.words=new Array(this.length);for(var S=0;S<this.length;S++)this.words[S]=0;var O=0,C=0,D;if(w==="be")for(S=h.length-1;S>=y;S-=2)D=s(h,y,S)<<O,this.words[C]|=D&67108863,O>=18?(O-=18,C+=1,this.words[C]|=D>>>26):O+=8;else{var P=h.length-y;for(S=P%2===0?y+1:y;S<h.length;S+=2)D=s(h,y,S)<<O,this.words[C]|=D&67108863,O>=18?(O-=18,C+=1,this.words[C]|=D>>>26):O+=8}this.strip()};function u(E,h,y,w){for(var S=0,O=Math.min(E.length,y),C=h;C<O;C++){var D=E.charCodeAt(C)-48;S*=w,D>=49?S+=D-49+10:D>=17?S+=D-17+10:S+=D}return S}n.prototype._parseBase=function(h,y,w){this.words=[0],this.length=1;for(var S=0,O=1;O<=67108863;O*=y)S++;S--,O=O/y|0;for(var C=h.length-w,D=C%S,P=Math.min(C,C-D)+w,m=0,x=w;x<P;x+=S)m=u(h,x,x+S,y),this.imuln(O),this.words[0]+m<67108864?this.words[0]+=m:this._iaddn(m);if(D!==0){var K=1;for(m=u(h,x,h.length,y),x=0;x<D;x++)K*=y;this.imuln(K),this.words[0]+m<67108864?this.words[0]+=m:this._iaddn(m)}this.strip()},n.prototype.copy=function(h){h.words=new Array(this.length);for(var y=0;y<this.length;y++)h.words[y]=this.words[y];h.length=this.length,h.negative=this.negative,h.red=this.red},n.prototype.clone=function(){var h=new n(null);return this.copy(h),h},n.prototype._expand=function(h){for(;this.length<h;)this.words[this.length++]=0;return this},n.prototype.strip=function(){for(;this.length>1&&this.words[this.length-1]===0;)this.length--;return this._normSign()},n.prototype._normSign=function(){return this.length===1&&this.words[0]===0&&(this.negative=0),this},n.prototype.inspect=function(){return(this.red?"<BN-R: ":"<BN: ")+this.toString(16)+">"};var c=["","0","00","000","0000","00000","000000","0000000","00000000","000000000","0000000000","00000000000","000000000000","0000000000000","00000000000000","000000000000000","0000000000000000","00000000000000000","000000000000000000","0000000000000000000","00000000000000000000","000000000000000000000","0000000000000000000000","00000000000000000000000","000000000000000000000000","0000000000000000000000000"],l=[0,0,25,16,12,11,10,9,8,8,7,7,7,7,6,6,6,6,6,6,6,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5],p=[0,0,33554432,43046721,16777216,48828125,60466176,40353607,16777216,43046721,1e7,19487171,35831808,62748517,7529536,11390625,16777216,24137569,34012224,47045881,64e6,4084101,5153632,6436343,7962624,9765625,11881376,14348907,17210368,20511149,243e5,28629151,33554432,39135393,45435424,52521875,60466176];n.prototype.toString=function(h,y){h=h||10,y=y|0||1;var w;if(h===16||h==="hex"){w="";for(var S=0,O=0,C=0;C<this.length;C++){var D=this.words[C],P=((D<<S|O)&16777215).toString(16);O=D>>>24-S&16777215,S+=2,S>=26&&(S-=26,C--),O!==0||C!==this.length-1?w=c[6-P.length]+P+w:w=P+w}for(O!==0&&(w=O.toString(16)+w);w.length%y!==0;)w="0"+w;return this.negative!==0&&(w="-"+w),w}if(h===(h|0)&&h>=2&&h<=36){var m=l[h],x=p[h];w="";var K=this.clone();for(K.negative=0;!K.isZero();){var U=K.modn(x).toString(h);K=K.idivn(x),K.isZero()?w=U+w:w=c[m-U.length]+U+w}for(this.isZero()&&(w="0"+w);w.length%y!==0;)w="0"+w;return this.negative!==0&&(w="-"+w),w}r(!1,"Base should be between 2 and 36")},n.prototype.toNumber=function(){var h=this.words[0];return this.length===2?h+=this.words[1]*67108864:this.length===3&&this.words[2]===1?h+=4503599627370496+this.words[1]*67108864:this.length>2&&r(!1,"Number can only safely store up to 53 bits"),this.negative!==0?-h:h},n.prototype.toJSON=function(){return this.toString(16)},n.prototype.toBuffer=function(h,y){return r(typeof o<"u"),this.toArrayLike(o,h,y)},n.prototype.toArray=function(h,y){return this.toArrayLike(Array,h,y)},n.prototype.toArrayLike=function(h,y,w){var S=this.byteLength(),O=w||Math.max(1,S);r(S<=O,"byte array longer than desired length"),r(O>0,"Requested array length <= 0"),this.strip();var C=y==="le",D=new h(O),P,m,x=this.clone();if(C){for(m=0;!x.isZero();m++)P=x.andln(255),x.iushrn(8),D[m]=P;for(;m<O;m++)D[m]=0}else{for(m=0;m<O-S;m++)D[m]=0;for(m=0;!x.isZero();m++)P=x.andln(255),x.iushrn(8),D[O-m-1]=P}return D},Math.clz32?n.prototype._countBits=function(h){return 32-Math.clz32(h)}:n.prototype._countBits=function(h){var y=h,w=0;return y>=4096&&(w+=13,y>>>=13),y>=64&&(w+=7,y>>>=7),y>=8&&(w+=4,y>>>=4),y>=2&&(w+=2,y>>>=2),w+y},n.prototype._zeroBits=function(h){if(h===0)return 26;var y=h,w=0;return(y&8191)===0&&(w+=13,y>>>=13),(y&127)===0&&(w+=7,y>>>=7),(y&15)===0&&(w+=4,y>>>=4),(y&3)===0&&(w+=2,y>>>=2),(y&1)===0&&w++,w},n.prototype.bitLength=function(){var h=this.words[this.length-1],y=this._countBits(h);return(this.length-1)*26+y};function d(E){for(var h=new Array(E.bitLength()),y=0;y<h.length;y++){var w=y/26|0,S=y%26;h[y]=(E.words[w]&1<<S)>>>S}return h}n.prototype.zeroBits=function(){if(this.isZero())return 0;for(var h=0,y=0;y<this.length;y++){var w=this._zeroBits(this.words[y]);if(h+=w,w!==26)break}return h},n.prototype.byteLength=function(){return Math.ceil(this.bitLength()/8)},n.prototype.toTwos=function(h){return this.negative!==0?this.abs().inotn(h).iaddn(1):this.clone()},n.prototype.fromTwos=function(h){return this.testn(h-1)?this.notn(h).iaddn(1).ineg():this.clone()},n.prototype.isNeg=function(){return this.negative!==0},n.prototype.neg=function(){return this.clone().ineg()},n.prototype.ineg=function(){return this.isZero()||(this.negative^=1),this},n.prototype.iuor=function(h){for(;this.length<h.length;)this.words[this.length++]=0;for(var y=0;y<h.length;y++)this.words[y]=this.words[y]|h.words[y];return this.strip()},n.prototype.ior=function(h){return r((this.negative|h.negative)===0),this.iuor(h)},n.prototype.or=function(h){return this.length>h.length?this.clone().ior(h):h.clone().ior(this)},n.prototype.uor=function(h){return this.length>h.length?this.clone().iuor(h):h.clone().iuor(this)},n.prototype.iuand=function(h){var y;this.length>h.length?y=h:y=this;for(var w=0;w<y.length;w++)this.words[w]=this.words[w]&h.words[w];return this.length=y.length,this.strip()},n.prototype.iand=function(h){return r((this.negative|h.negative)===0),this.iuand(h)},n.prototype.and=function(h){return this.length>h.length?this.clone().iand(h):h.clone().iand(this)},n.prototype.uand=function(h){return this.length>h.length?this.clone().iuand(h):h.clone().iuand(this)},n.prototype.iuxor=function(h){var y,w;this.length>h.length?(y=this,w=h):(y=h,w=this);for(var S=0;S<w.length;S++)this.words[S]=y.words[S]^w.words[S];if(this!==y)for(;S<y.length;S++)this.words[S]=y.words[S];return this.length=y.length,this.strip()},n.prototype.ixor=function(h){return r((this.negative|h.negative)===0),this.iuxor(h)},n.prototype.xor=function(h){return this.length>h.length?this.clone().ixor(h):h.clone().ixor(this)},n.prototype.uxor=function(h){return this.length>h.length?this.clone().iuxor(h):h.clone().iuxor(this)},n.prototype.inotn=function(h){r(typeof h=="number"&&h>=0);var y=Math.ceil(h/26)|0,w=h%26;this._expand(y),w>0&&y--;for(var S=0;S<y;S++)this.words[S]=~this.words[S]&67108863;for(w>0&&(this.words[S]=~this.words[S]&67108863>>26-w,S++);S<this.length;S++)this.words[S]=0;return this.strip()},n.prototype.notn=function(h){return this.clone().inotn(h)},n.prototype.setn=function(h,y){r(typeof h=="number"&&h>=0);var w=h/26|0,S=h%26;return this._expand(w+1),y?this.words[w]=this.words[w]|1<<S:this.words[w]=this.words[w]&~(1<<S),this.strip()},n.prototype.iadd=function(h){var y;if(this.negative!==0&&h.negative===0)return this.negative=0,y=this.isub(h),this.negative^=1,this._normSign();if(this.negative===0&&h.negative!==0)return h.negative=0,y=this.isub(h),h.negative=1,y._normSign();var w,S;this.length>h.length?(w=this,S=h):(w=h,S=this);for(var O=0,C=0;C<S.length;C++)y=(w.words[C]|0)+(S.words[C]|0)+O,this.words[C]=y&67108863,O=y>>>26;for(;O!==0&&C<w.length;C++)y=(w.words[C]|0)+O,this.words[C]=y&67108863,O=y>>>26;if(this.length=w.length,O!==0)this.words[this.length]=O,this.length++;else if(w!==this)for(;C<w.length;C++)this.words[C]=w.words[C];return this},n.prototype.add=function(h){var y;return h.negative!==0&&this.negative===0?(h.negative=0,y=this.sub(h),h.negative^=1,y):h.negative===0&&this.negative!==0?(this.negative=0,y=h.sub(this),this.negative=1,y):this.length>h.length?this.clone().iadd(h):h.clone().iadd(this)},n.prototype.isub=function(h){if(h.negative!==0){h.negative=0;var y=this.iadd(h);return h.negative=1,y._normSign()}else if(this.negative!==0)return this.negative=0,this.iadd(h),this.negative=1,this._normSign();var w=this.cmp(h);if(w===0)return this.negative=0,this.length=1,this.words[0]=0,this;var S,O;w>0?(S=this,O=h):(S=h,O=this);for(var C=0,D=0;D<O.length;D++)y=(S.words[D]|0)-(O.words[D]|0)+C,C=y>>26,this.words[D]=y&67108863;for(;C!==0&&D<S.length;D++)y=(S.words[D]|0)+C,C=y>>26,this.words[D]=y&67108863;if(C===0&&D<S.length&&S!==this)for(;D<S.length;D++)this.words[D]=S.words[D];return this.length=Math.max(this.length,D),S!==this&&(this.negative=1),this.strip()},n.prototype.sub=function(h){return this.clone().isub(h)};function v(E,h,y){y.negative=h.negative^E.negative;var w=E.length+h.length|0;y.length=w,w=w-1|0;var S=E.words[0]|0,O=h.words[0]|0,C=S*O,D=C&67108863,P=C/67108864|0;y.words[0]=D;for(var m=1;m<w;m++){for(var x=P>>>26,K=P&67108863,U=Math.min(m,h.length-1),G=Math.max(0,m-E.length+1);G<=U;G++){var te=m-G|0;S=E.words[te]|0,O=h.words[G]|0,C=S*O+K,x+=C/67108864|0,K=C&67108863}y.words[m]=K|0,P=x|0}return P!==0?y.words[m]=P|0:y.length--,y.strip()}var _=function(h,y,w){var S=h.words,O=y.words,C=w.words,D=0,P,m,x,K=S[0]|0,U=K&8191,G=K>>>13,te=S[1]|0,ae=te&8191,oe=te>>>13,le=S[2]|0,he=le&8191,ve=le>>>13,je=S[3]|0,be=je&8191,_e=je>>>13,We=S[4]|0,Pe=We&8191,Me=We>>>13,rt=S[5]|0,Be=rt&8191,vt=rt>>>13,ui=S[6]|0,Et=ui&8191,_t=ui>>>13,Yn=S[7]|0,Lt=Yn&8191,N=Yn>>>13,W=S[8]|0,X=W&8191,ie=W>>>13,pe=S[9]|0,se=pe&8191,me=pe>>>13,ge=O[0]|0,ke=ge&8191,Oe=ge>>>13,Ye=O[1]|0,Ze=Ye&8191,Pt=Ye>>>13,Mt=O[2]|0,$e=Mt&8191,Ee=Mt>>>13,Jt=O[3]|0,wt=Jt&8191,Ft=Jt>>>13,Hu=O[4]|0,Dt=Hu&8191,gr=Hu>>>13,wE=O[5]|0,mr=wE&8191,vr=wE>>>13,SE=O[6]|0,yr=SE&8191,br=SE>>>13,EE=O[7]|0,_r=EE&8191,wr=EE>>>13,xE=O[8]|0,Sr=xE&8191,Er=xE>>>13,OE=O[9]|0,xr=OE&8191,Or=OE>>>13;w.negative=h.negative^y.negative,w.length=19,P=Math.imul(U,ke),m=Math.imul(U,Oe),m=m+Math.imul(G,ke)|0,x=Math.imul(G,Oe);var Hv=(D+P|0)+((m&8191)<<13)|0;D=(x+(m>>>13)|0)+(Hv>>>26)|0,Hv&=67108863,P=Math.imul(ae,ke),m=Math.imul(ae,Oe),m=m+Math.imul(oe,ke)|0,x=Math.imul(oe,Oe),P=P+Math.imul(U,Ze)|0,m=m+Math.imul(U,Pt)|0,m=m+Math.imul(G,Ze)|0,x=x+Math.imul(G,Pt)|0;var qv=(D+P|0)+((m&8191)<<13)|0;D=(x+(m>>>13)|0)+(qv>>>26)|0,qv&=67108863,P=Math.imul(he,ke),m=Math.imul(he,Oe),m=m+Math.imul(ve,ke)|0,x=Math.imul(ve,Oe),P=P+Math.imul(ae,Ze)|0,m=m+Math.imul(ae,Pt)|0,m=m+Math.imul(oe,Ze)|0,x=x+Math.imul(oe,Pt)|0,P=P+Math.imul(U,$e)|0,m=m+Math.imul(U,Ee)|0,m=m+Math.imul(G,$e)|0,x=x+Math.imul(G,Ee)|0;var Uv=(D+P|0)+((m&8191)<<13)|0;D=(x+(m>>>13)|0)+(Uv>>>26)|0,Uv&=67108863,P=Math.imul(be,ke),m=Math.imul(be,Oe),m=m+Math.imul(_e,ke)|0,x=Math.imul(_e,Oe),P=P+Math.imul(he,Ze)|0,m=m+Math.imul(he,Pt)|0,m=m+Math.imul(ve,Ze)|0,x=x+Math.imul(ve,Pt)|0,P=P+Math.imul(ae,$e)|0,m=m+Math.imul(ae,Ee)|0,m=m+Math.imul(oe,$e)|0,x=x+Math.imul(oe,Ee)|0,P=P+Math.imul(U,wt)|0,m=m+Math.imul(U,Ft)|0,m=m+Math.imul(G,wt)|0,x=x+Math.imul(G,Ft)|0;var Fv=(D+P|0)+((m&8191)<<13)|0;D=(x+(m>>>13)|0)+(Fv>>>26)|0,Fv&=67108863,P=Math.imul(Pe,ke),m=Math.imul(Pe,Oe),m=m+Math.imul(Me,ke)|0,x=Math.imul(Me,Oe),P=P+Math.imul(be,Ze)|0,m=m+Math.imul(be,Pt)|0,m=m+Math.imul(_e,Ze)|0,x=x+Math.imul(_e,Pt)|0,P=P+Math.imul(he,$e)|0,m=m+Math.imul(he,Ee)|0,m=m+Math.imul(ve,$e)|0,x=x+Math.imul(ve,Ee)|0,P=P+Math.imul(ae,wt)|0,m=m+Math.imul(ae,Ft)|0,m=m+Math.imul(oe,wt)|0,x=x+Math.imul(oe,Ft)|0,P=P+Math.imul(U,Dt)|0,m=m+Math.imul(U,gr)|0,m=m+Math.imul(G,Dt)|0,x=x+Math.imul(G,gr)|0;var jv=(D+P|0)+((m&8191)<<13)|0;D=(x+(m>>>13)|0)+(jv>>>26)|0,jv&=67108863,P=Math.imul(Be,ke),m=Math.imul(Be,Oe),m=m+Math.imul(vt,ke)|0,x=Math.imul(vt,Oe),P=P+Math.imul(Pe,Ze)|0,m=m+Math.imul(Pe,Pt)|0,m=m+Math.imul(Me,Ze)|0,x=x+Math.imul(Me,Pt)|0,P=P+Math.imul(be,$e)|0,m=m+Math.imul(be,Ee)|0,m=m+Math.imul(_e,$e)|0,x=x+Math.imul(_e,Ee)|0,P=P+Math.imul(he,wt)|0,m=m+Math.imul(he,Ft)|0,m=m+Math.imul(ve,wt)|0,x=x+Math.imul(ve,Ft)|0,P=P+Math.imul(ae,Dt)|0,m=m+Math.imul(ae,gr)|0,m=m+Math.imul(oe,Dt)|0,x=x+Math.imul(oe,gr)|0,P=P+Math.imul(U,mr)|0,m=m+Math.imul(U,vr)|0,m=m+Math.imul(G,mr)|0,x=x+Math.imul(G,vr)|0;var zv=(D+P|0)+((m&8191)<<13)|0;D=(x+(m>>>13)|0)+(zv>>>26)|0,zv&=67108863,P=Math.imul(Et,ke),m=Math.imul(Et,Oe),m=m+Math.imul(_t,ke)|0,x=Math.imul(_t,Oe),P=P+Math.imul(Be,Ze)|0,m=m+Math.imul(Be,Pt)|0,m=m+Math.imul(vt,Ze)|0,x=x+Math.imul(vt,Pt)|0,P=P+Math.imul(Pe,$e)|0,m=m+Math.imul(Pe,Ee)|0,m=m+Math.imul(Me,$e)|0,x=x+Math.imul(Me,Ee)|0,P=P+Math.imul(be,wt)|0,m=m+Math.imul(be,Ft)|0,m=m+Math.imul(_e,wt)|0,x=x+Math.imul(_e,Ft)|0,P=P+Math.imul(he,Dt)|0,m=m+Math.imul(he,gr)|0,m=m+Math.imul(ve,Dt)|0,x=x+Math.imul(ve,gr)|0,P=P+Math.imul(ae,mr)|0,m=m+Math.imul(ae,vr)|0,m=m+Math.imul(oe,mr)|0,x=x+Math.imul(oe,vr)|0,P=P+Math.imul(U,yr)|0,m=m+Math.imul(U,br)|0,m=m+Math.imul(G,yr)|0,x=x+Math.imul(G,br)|0;var Kv=(D+P|0)+((m&8191)<<13)|0;D=(x+(m>>>13)|0)+(Kv>>>26)|0,Kv&=67108863,P=Math.imul(Lt,ke),m=Math.imul(Lt,Oe),m=m+Math.imul(N,ke)|0,x=Math.imul(N,Oe),P=P+Math.imul(Et,Ze)|0,m=m+Math.imul(Et,Pt)|0,m=m+Math.imul(_t,Ze)|0,x=x+Math.imul(_t,Pt)|0,P=P+Math.imul(Be,$e)|0,m=m+Math.imul(Be,Ee)|0,m=m+Math.imul(vt,$e)|0,x=x+Math.imul(vt,Ee)|0,P=P+Math.imul(Pe,wt)|0,m=m+Math.imul(Pe,Ft)|0,m=m+Math.imul(Me,wt)|0,x=x+Math.imul(Me,Ft)|0,P=P+Math.imul(be,Dt)|0,m=m+Math.imul(be,gr)|0,m=m+Math.imul(_e,Dt)|0,x=x+Math.imul(_e,gr)|0,P=P+Math.imul(he,mr)|0,m=m+Math.imul(he,vr)|0,m=m+Math.imul(ve,mr)|0,x=x+Math.imul(ve,vr)|0,P=P+Math.imul(ae,yr)|0,m=m+Math.imul(ae,br)|0,m=m+Math.imul(oe,yr)|0,x=x+Math.imul(oe,br)|0,P=P+Math.imul(U,_r)|0,m=m+Math.imul(U,wr)|0,m=m+Math.imul(G,_r)|0,x=x+Math.imul(G,wr)|0;var Vv=(D+P|0)+((m&8191)<<13)|0;D=(x+(m>>>13)|0)+(Vv>>>26)|0,Vv&=67108863,P=Math.imul(X,ke),m=Math.imul(X,Oe),m=m+Math.imul(ie,ke)|0,x=Math.imul(ie,Oe),P=P+Math.imul(Lt,Ze)|0,m=m+Math.imul(Lt,Pt)|0,m=m+Math.imul(N,Ze)|0,x=x+Math.imul(N,Pt)|0,P=P+Math.imul(Et,$e)|0,m=m+Math.imul(Et,Ee)|0,m=m+Math.imul(_t,$e)|0,x=x+Math.imul(_t,Ee)|0,P=P+Math.imul(Be,wt)|0,m=m+Math.imul(Be,Ft)|0,m=m+Math.imul(vt,wt)|0,x=x+Math.imul(vt,Ft)|0,P=P+Math.imul(Pe,Dt)|0,m=m+Math.imul(Pe,gr)|0,m=m+Math.imul(Me,Dt)|0,x=x+Math.imul(Me,gr)|0,P=P+Math.imul(be,mr)|0,m=m+Math.imul(be,vr)|0,m=m+Math.imul(_e,mr)|0,x=x+Math.imul(_e,vr)|0,P=P+Math.imul(he,yr)|0,m=m+Math.imul(he,br)|0,m=m+Math.imul(ve,yr)|0,x=x+Math.imul(ve,br)|0,P=P+Math.imul(ae,_r)|0,m=m+Math.imul(ae,wr)|0,m=m+Math.imul(oe,_r)|0,x=x+Math.imul(oe,wr)|0,P=P+Math.imul(U,Sr)|0,m=m+Math.imul(U,Er)|0,m=m+Math.imul(G,Sr)|0,x=x+Math.imul(G,Er)|0;var Gv=(D+P|0)+((m&8191)<<13)|0;D=(x+(m>>>13)|0)+(Gv>>>26)|0,Gv&=67108863,P=Math.imul(se,ke),m=Math.imul(se,Oe),m=m+Math.imul(me,ke)|0,x=Math.imul(me,Oe),P=P+Math.imul(X,Ze)|0,m=m+Math.imul(X,Pt)|0,m=m+Math.imul(ie,Ze)|0,x=x+Math.imul(ie,Pt)|0,P=P+Math.imul(Lt,$e)|0,m=m+Math.imul(Lt,Ee)|0,m=m+Math.imul(N,$e)|0,x=x+Math.imul(N,Ee)|0,P=P+Math.imul(Et,wt)|0,m=m+Math.imul(Et,Ft)|0,m=m+Math.imul(_t,wt)|0,x=x+Math.imul(_t,Ft)|0,P=P+Math.imul(Be,Dt)|0,m=m+Math.imul(Be,gr)|0,m=m+Math.imul(vt,Dt)|0,x=x+Math.imul(vt,gr)|0,P=P+Math.imul(Pe,mr)|0,m=m+Math.imul(Pe,vr)|0,m=m+Math.imul(Me,mr)|0,x=x+Math.imul(Me,vr)|0,P=P+Math.imul(be,yr)|0,m=m+Math.imul(be,br)|0,m=m+Math.imul(_e,yr)|0,x=x+Math.imul(_e,br)|0,P=P+Math.imul(he,_r)|0,m=m+Math.imul(he,wr)|0,m=m+Math.imul(ve,_r)|0,x=x+Math.imul(ve,wr)|0,P=P+Math.imul(ae,Sr)|0,m=m+Math.imul(ae,Er)|0,m=m+Math.imul(oe,Sr)|0,x=x+Math.imul(oe,Er)|0,P=P+Math.imul(U,xr)|0,m=m+Math.imul(U,Or)|0,m=m+Math.imul(G,xr)|0,x=x+Math.imul(G,Or)|0;var Wv=(D+P|0)+((m&8191)<<13)|0;D=(x+(m>>>13)|0)+(Wv>>>26)|0,Wv&=67108863,P=Math.imul(se,Ze),m=Math.imul(se,Pt),m=m+Math.imul(me,Ze)|0,x=Math.imul(me,Pt),P=P+Math.imul(X,$e)|0,m=m+Math.imul(X,Ee)|0,m=m+Math.imul(ie,$e)|0,x=x+Math.imul(ie,Ee)|0,P=P+Math.imul(Lt,wt)|0,m=m+Math.imul(Lt,Ft)|0,m=m+Math.imul(N,wt)|0,x=x+Math.imul(N,Ft)|0,P=P+Math.imul(Et,Dt)|0,m=m+Math.imul(Et,gr)|0,m=m+Math.imul(_t,Dt)|0,x=x+Math.imul(_t,gr)|0,P=P+Math.imul(Be,mr)|0,m=m+Math.imul(Be,vr)|0,m=m+Math.imul(vt,mr)|0,x=x+Math.imul(vt,vr)|0,P=P+Math.imul(Pe,yr)|0,m=m+Math.imul(Pe,br)|0,m=m+Math.imul(Me,yr)|0,x=x+Math.imul(Me,br)|0,P=P+Math.imul(be,_r)|0,m=m+Math.imul(be,wr)|0,m=m+Math.imul(_e,_r)|0,x=x+Math.imul(_e,wr)|0,P=P+Math.imul(he,Sr)|0,m=m+Math.imul(he,Er)|0,m=m+Math.imul(ve,Sr)|0,x=x+Math.imul(ve,Er)|0,P=P+Math.imul(ae,xr)|0,m=m+Math.imul(ae,Or)|0,m=m+Math.imul(oe,xr)|0,x=x+Math.imul(oe,Or)|0;var Yv=(D+P|0)+((m&8191)<<13)|0;D=(x+(m>>>13)|0)+(Yv>>>26)|0,Yv&=67108863,P=Math.imul(se,$e),m=Math.imul(se,Ee),m=m+Math.imul(me,$e)|0,x=Math.imul(me,Ee),P=P+Math.imul(X,wt)|0,m=m+Math.imul(X,Ft)|0,m=m+Math.imul(ie,wt)|0,x=x+Math.imul(ie,Ft)|0,P=P+Math.imul(Lt,Dt)|0,m=m+Math.imul(Lt,gr)|0,m=m+Math.imul(N,Dt)|0,x=x+Math.imul(N,gr)|0,P=P+Math.imul(Et,mr)|0,m=m+Math.imul(Et,vr)|0,m=m+Math.imul(_t,mr)|0,x=x+Math.imul(_t,vr)|0,P=P+Math.imul(Be,yr)|0,m=m+Math.imul(Be,br)|0,m=m+Math.imul(vt,yr)|0,x=x+Math.imul(vt,br)|0,P=P+Math.imul(Pe,_r)|0,m=m+Math.imul(Pe,wr)|0,m=m+Math.imul(Me,_r)|0,x=x+Math.imul(Me,wr)|0,P=P+Math.imul(be,Sr)|0,m=m+Math.imul(be,Er)|0,m=m+Math.imul(_e,Sr)|0,x=x+Math.imul(_e,Er)|0,P=P+Math.imul(he,xr)|0,m=m+Math.imul(he,Or)|0,m=m+Math.imul(ve,xr)|0,x=x+Math.imul(ve,Or)|0;var Zv=(D+P|0)+((m&8191)<<13)|0;D=(x+(m>>>13)|0)+(Zv>>>26)|0,Zv&=67108863,P=Math.imul(se,wt),m=Math.imul(se,Ft),m=m+Math.imul(me,wt)|0,x=Math.imul(me,Ft),P=P+Math.imul(X,Dt)|0,m=m+Math.imul(X,gr)|0,m=m+Math.imul(ie,Dt)|0,x=x+Math.imul(ie,gr)|0,P=P+Math.imul(Lt,mr)|0,m=m+Math.imul(Lt,vr)|0,m=m+Math.imul(N,mr)|0,x=x+Math.imul(N,vr)|0,P=P+Math.imul(Et,yr)|0,m=m+Math.imul(Et,br)|0,m=m+Math.imul(_t,yr)|0,x=x+Math.imul(_t,br)|0,P=P+Math.imul(Be,_r)|0,m=m+Math.imul(Be,wr)|0,m=m+Math.imul(vt,_r)|0,x=x+Math.imul(vt,wr)|0,P=P+Math.imul(Pe,Sr)|0,m=m+Math.imul(Pe,Er)|0,m=m+Math.imul(Me,Sr)|0,x=x+Math.imul(Me,Er)|0,P=P+Math.imul(be,xr)|0,m=m+Math.imul(be,Or)|0,m=m+Math.imul(_e,xr)|0,x=x+Math.imul(_e,Or)|0;var $v=(D+P|0)+((m&8191)<<13)|0;D=(x+(m>>>13)|0)+($v>>>26)|0,$v&=67108863,P=Math.imul(se,Dt),m=Math.imul(se,gr),m=m+Math.imul(me,Dt)|0,x=Math.imul(me,gr),P=P+Math.imul(X,mr)|0,m=m+Math.imul(X,vr)|0,m=m+Math.imul(ie,mr)|0,x=x+Math.imul(ie,vr)|0,P=P+Math.imul(Lt,yr)|0,m=m+Math.imul(Lt,br)|0,m=m+Math.imul(N,yr)|0,x=x+Math.imul(N,br)|0,P=P+Math.imul(Et,_r)|0,m=m+Math.imul(Et,wr)|0,m=m+Math.imul(_t,_r)|0,x=x+Math.imul(_t,wr)|0,P=P+Math.imul(Be,Sr)|0,m=m+Math.imul(Be,Er)|0,m=m+Math.imul(vt,Sr)|0,x=x+Math.imul(vt,Er)|0,P=P+Math.imul(Pe,xr)|0,m=m+Math.imul(Pe,Or)|0,m=m+Math.imul(Me,xr)|0,x=x+Math.imul(Me,Or)|0;var Xv=(D+P|0)+((m&8191)<<13)|0;D=(x+(m>>>13)|0)+(Xv>>>26)|0,Xv&=67108863,P=Math.imul(se,mr),m=Math.imul(se,vr),m=m+Math.imul(me,mr)|0,x=Math.imul(me,vr),P=P+Math.imul(X,yr)|0,m=m+Math.imul(X,br)|0,m=m+Math.imul(ie,yr)|0,x=x+Math.imul(ie,br)|0,P=P+Math.imul(Lt,_r)|0,m=m+Math.imul(Lt,wr)|0,m=m+Math.imul(N,_r)|0,x=x+Math.imul(N,wr)|0,P=P+Math.imul(Et,Sr)|0,m=m+Math.imul(Et,Er)|0,m=m+Math.imul(_t,Sr)|0,x=x+Math.imul(_t,Er)|0,P=P+Math.imul(Be,xr)|0,m=m+Math.imul(Be,Or)|0,m=m+Math.imul(vt,xr)|0,x=x+Math.imul(vt,Or)|0;var Jv=(D+P|0)+((m&8191)<<13)|0;D=(x+(m>>>13)|0)+(Jv>>>26)|0,Jv&=67108863,P=Math.imul(se,yr),m=Math.imul(se,br),m=m+Math.imul(me,yr)|0,x=Math.imul(me,br),P=P+Math.imul(X,_r)|0,m=m+Math.imul(X,wr)|0,m=m+Math.imul(ie,_r)|0,x=x+Math.imul(ie,wr)|0,P=P+Math.imul(Lt,Sr)|0,m=m+Math.imul(Lt,Er)|0,m=m+Math.imul(N,Sr)|0,x=x+Math.imul(N,Er)|0,P=P+Math.imul(Et,xr)|0,m=m+Math.imul(Et,Or)|0,m=m+Math.imul(_t,xr)|0,x=x+Math.imul(_t,Or)|0;var Qv=(D+P|0)+((m&8191)<<13)|0;D=(x+(m>>>13)|0)+(Qv>>>26)|0,Qv&=67108863,P=Math.imul(se,_r),m=Math.imul(se,wr),m=m+Math.imul(me,_r)|0,x=Math.imul(me,wr),P=P+Math.imul(X,Sr)|0,m=m+Math.imul(X,Er)|0,m=m+Math.imul(ie,Sr)|0,x=x+Math.imul(ie,Er)|0,P=P+Math.imul(Lt,xr)|0,m=m+Math.imul(Lt,Or)|0,m=m+Math.imul(N,xr)|0,x=x+Math.imul(N,Or)|0;var e0=(D+P|0)+((m&8191)<<13)|0;D=(x+(m>>>13)|0)+(e0>>>26)|0,e0&=67108863,P=Math.imul(se,Sr),m=Math.imul(se,Er),m=m+Math.imul(me,Sr)|0,x=Math.imul(me,Er),P=P+Math.imul(X,xr)|0,m=m+Math.imul(X,Or)|0,m=m+Math.imul(ie,xr)|0,x=x+Math.imul(ie,Or)|0;var t0=(D+P|0)+((m&8191)<<13)|0;D=(x+(m>>>13)|0)+(t0>>>26)|0,t0&=67108863,P=Math.imul(se,xr),m=Math.imul(se,Or),m=m+Math.imul(me,xr)|0,x=Math.imul(me,Or);var r0=(D+P|0)+((m&8191)<<13)|0;return D=(x+(m>>>13)|0)+(r0>>>26)|0,r0&=67108863,C[0]=Hv,C[1]=qv,C[2]=Uv,C[3]=Fv,C[4]=jv,C[5]=zv,C[6]=Kv,C[7]=Vv,C[8]=Gv,C[9]=Wv,C[10]=Yv,C[11]=Zv,C[12]=$v,C[13]=Xv,C[14]=Jv,C[15]=Qv,C[16]=e0,C[17]=t0,C[18]=r0,D!==0&&(C[19]=D,w.length++),w};Math.imul||(_=v);function I(E,h,y){y.negative=h.negative^E.negative,y.length=E.length+h.length;for(var w=0,S=0,O=0;O<y.length-1;O++){var C=S;S=0;for(var D=w&67108863,P=Math.min(O,h.length-1),m=Math.max(0,O-E.length+1);m<=P;m++){var x=O-m,K=E.words[x]|0,U=h.words[m]|0,G=K*U,te=G&67108863;C=C+(G/67108864|0)|0,te=te+D|0,D=te&67108863,C=C+(te>>>26)|0,S+=C>>>26,C&=67108863}y.words[O]=D,w=C,C=S}return w!==0?y.words[O]=w:y.length--,y.strip()}function R(E,h,y){var w=new k;return w.mulp(E,h,y)}n.prototype.mulTo=function(h,y){var w,S=this.length+h.length;return this.length===10&&h.length===10?w=_(this,h,y):S<63?w=v(this,h,y):S<1024?w=I(this,h,y):w=R(this,h,y),w};function k(E,h){this.x=E,this.y=h}k.prototype.makeRBT=function(h){for(var y=new Array(h),w=n.prototype._countBits(h)-1,S=0;S<h;S++)y[S]=this.revBin(S,w,h);return y},k.prototype.revBin=function(h,y,w){if(h===0||h===w-1)return h;for(var S=0,O=0;O<y;O++)S|=(h&1)<<y-O-1,h>>=1;return S},k.prototype.permute=function(h,y,w,S,O,C){for(var D=0;D<C;D++)S[D]=y[h[D]],O[D]=w[h[D]]},k.prototype.transform=function(h,y,w,S,O,C){this.permute(C,h,y,w,S,O);for(var D=1;D<O;D<<=1)for(var P=D<<1,m=Math.cos(2*Math.PI/P),x=Math.sin(2*Math.PI/P),K=0;K<O;K+=P)for(var U=m,G=x,te=0;te<D;te++){var ae=w[K+te],oe=S[K+te],le=w[K+te+D],he=S[K+te+D],ve=U*le-G*he;he=U*he+G*le,le=ve,w[K+te]=ae+le,S[K+te]=oe+he,w[K+te+D]=ae-le,S[K+te+D]=oe-he,te!==P&&(ve=m*U-x*G,G=m*G+x*U,U=ve)}},k.prototype.guessLen13b=function(h,y){var w=Math.max(y,h)|1,S=w&1,O=0;for(w=w/2|0;w;w=w>>>1)O++;return 1<<O+1+S},k.prototype.conjugate=function(h,y,w){if(!(w<=1))for(var S=0;S<w/2;S++){var O=h[S];h[S]=h[w-S-1],h[w-S-1]=O,O=y[S],y[S]=-y[w-S-1],y[w-S-1]=-O}},k.prototype.normalize13b=function(h,y){for(var w=0,S=0;S<y/2;S++){var O=Math.round(h[2*S+1]/y)*8192+Math.round(h[2*S]/y)+w;h[S]=O&67108863,O<67108864?w=0:w=O/67108864|0}return h},k.prototype.convert13b=function(h,y,w,S){for(var O=0,C=0;C<y;C++)O=O+(h[C]|0),w[2*C]=O&8191,O=O>>>13,w[2*C+1]=O&8191,O=O>>>13;for(C=2*y;C<S;++C)w[C]=0;r(O===0),r((O&-8192)===0)},k.prototype.stub=function(h){for(var y=new Array(h),w=0;w<h;w++)y[w]=0;return y},k.prototype.mulp=function(h,y,w){var S=2*this.guessLen13b(h.length,y.length),O=this.makeRBT(S),C=this.stub(S),D=new Array(S),P=new Array(S),m=new Array(S),x=new Array(S),K=new Array(S),U=new Array(S),G=w.words;G.length=S,this.convert13b(h.words,h.length,D,S),this.convert13b(y.words,y.length,x,S),this.transform(D,C,P,m,S,O),this.transform(x,C,K,U,S,O);for(var te=0;te<S;te++){var ae=P[te]*K[te]-m[te]*U[te];m[te]=P[te]*U[te]+m[te]*K[te],P[te]=ae}return this.conjugate(P,m,S),this.transform(P,m,G,C,S,O),this.conjugate(G,C,S),this.normalize13b(G,S),w.negative=h.negative^y.negative,w.length=h.length+y.length,w.strip()},n.prototype.mul=function(h){var y=new n(null);return y.words=new Array(this.length+h.length),this.mulTo(h,y)},n.prototype.mulf=function(h){var y=new n(null);return y.words=new Array(this.length+h.length),R(this,h,y)},n.prototype.imul=function(h){return this.clone().mulTo(h,this)},n.prototype.imuln=function(h){r(typeof h=="number"),r(h<67108864);for(var y=0,w=0;w<this.length;w++){var S=(this.words[w]|0)*h,O=(S&67108863)+(y&67108863);y>>=26,y+=S/67108864|0,y+=O>>>26,this.words[w]=O&67108863}return y!==0&&(this.words[w]=y,this.length++),h===0&&(this.length=1,this._normSign()),this},n.prototype.muln=function(h){return this.clone().imuln(h)},n.prototype.sqr=function(){return this.mul(this)},n.prototype.isqr=function(){return this.imul(this.clone())},n.prototype.pow=function(h){var y=d(h);if(y.length===0)return new n(1);for(var w=this,S=0;S<y.length&&y[S]===0;S++,w=w.sqr());if(++S<y.length)for(var O=w.sqr();S<y.length;S++,O=O.sqr())y[S]!==0&&(w=w.mul(O));return w},n.prototype.iushln=function(h){r(typeof h=="number"&&h>=0);var y=h%26,w=(h-y)/26,S=67108863>>>26-y<<26-y,O;if(y!==0){var C=0;for(O=0;O<this.length;O++){var D=this.words[O]&S,P=(this.words[O]|0)-D<<y;this.words[O]=P|C,C=D>>>26-y}C&&(this.words[O]=C,this.length++)}if(w!==0){for(O=this.length-1;O>=0;O--)this.words[O+w]=this.words[O];for(O=0;O<w;O++)this.words[O]=0;this.length+=w}return this.strip()},n.prototype.ishln=function(h){return r(this.negative===0),this.iushln(h)},n.prototype.iushrn=function(h,y,w){r(typeof h=="number"&&h>=0);var S;y?S=(y-y%26)/26:S=0;var O=h%26,C=Math.min((h-O)/26,this.length),D=67108863^67108863>>>O<<O,P=w;if(S-=C,S=Math.max(0,S),P){for(var m=0;m<C;m++)P.words[m]=this.words[m];P.length=C}if(C!==0)if(this.length>C)for(this.length-=C,m=0;m<this.length;m++)this.words[m]=this.words[m+C];else this.words[0]=0,this.length=1;var x=0;for(m=this.length-1;m>=0&&(x!==0||m>=S);m--){var K=this.words[m]|0;this.words[m]=x<<26-O|K>>>O,x=K&D}return P&&x!==0&&(P.words[P.length++]=x),this.length===0&&(this.words[0]=0,this.length=1),this.strip()},n.prototype.ishrn=function(h,y,w){return r(this.negative===0),this.iushrn(h,y,w)},n.prototype.shln=function(h){return this.clone().ishln(h)},n.prototype.ushln=function(h){return this.clone().iushln(h)},n.prototype.shrn=function(h){return this.clone().ishrn(h)},n.prototype.ushrn=function(h){return this.clone().iushrn(h)},n.prototype.testn=function(h){r(typeof h=="number"&&h>=0);var y=h%26,w=(h-y)/26,S=1<<y;if(this.length<=w)return!1;var O=this.words[w];return!!(O&S)},n.prototype.imaskn=function(h){r(typeof h=="number"&&h>=0);var y=h%26,w=(h-y)/26;if(r(this.negative===0,"imaskn works only with positive numbers"),this.length<=w)return this;if(y!==0&&w++,this.length=Math.min(w,this.length),y!==0){var S=67108863^67108863>>>y<<y;this.words[this.length-1]&=S}return this.length===0&&(this.words[0]=0,this.length=1),this.strip()},n.prototype.maskn=function(h){return this.clone().imaskn(h)},n.prototype.iaddn=function(h){return r(typeof h=="number"),r(h<67108864),h<0?this.isubn(-h):this.negative!==0?this.length===1&&(this.words[0]|0)<h?(this.words[0]=h-(this.words[0]|0),this.negative=0,this):(this.negative=0,this.isubn(h),this.negative=1,this):this._iaddn(h)},n.prototype._iaddn=function(h){this.words[0]+=h;for(var y=0;y<this.length&&this.words[y]>=67108864;y++)this.words[y]-=67108864,y===this.length-1?this.words[y+1]=1:this.words[y+1]++;return this.length=Math.max(this.length,y+1),this},n.prototype.isubn=function(h){if(r(typeof h=="number"),r(h<67108864),h<0)return this.iaddn(-h);if(this.negative!==0)return this.negative=0,this.iaddn(h),this.negative=1,this;if(this.words[0]-=h,this.length===1&&this.words[0]<0)this.words[0]=-this.words[0],this.negative=1;else for(var y=0;y<this.length&&this.words[y]<0;y++)this.words[y]+=67108864,this.words[y+1]-=1;return this.strip()},n.prototype.addn=function(h){return this.clone().iaddn(h)},n.prototype.subn=function(h){return this.clone().isubn(h)},n.prototype.iabs=function(){return this.negative=0,this},n.prototype.abs=function(){return this.clone().iabs()},n.prototype._ishlnsubmul=function(h,y,w){var S=h.length+w,O;this._expand(S);var C,D=0;for(O=0;O<h.length;O++){C=(this.words[O+w]|0)+D;var P=(h.words[O]|0)*y;C-=P&67108863,D=(C>>26)-(P/67108864|0),this.words[O+w]=C&67108863}for(;O<this.length-w;O++)C=(this.words[O+w]|0)+D,D=C>>26,this.words[O+w]=C&67108863;if(D===0)return this.strip();for(r(D===-1),D=0,O=0;O<this.length;O++)C=-(this.words[O]|0)+D,D=C>>26,this.words[O]=C&67108863;return this.negative=1,this.strip()},n.prototype._wordDiv=function(h,y){var w=this.length-h.length,S=this.clone(),O=h,C=O.words[O.length-1]|0,D=this._countBits(C);w=26-D,w!==0&&(O=O.ushln(w),S.iushln(w),C=O.words[O.length-1]|0);var P=S.length-O.length,m;if(y!=="mod"){m=new n(null),m.length=P+1,m.words=new Array(m.length);for(var x=0;x<m.length;x++)m.words[x]=0}var K=S.clone()._ishlnsubmul(O,1,P);K.negative===0&&(S=K,m&&(m.words[P]=1));for(var U=P-1;U>=0;U--){var G=(S.words[O.length+U]|0)*67108864+(S.words[O.length+U-1]|0);for(G=Math.min(G/C|0,67108863),S._ishlnsubmul(O,G,U);S.negative!==0;)G--,S.negative=0,S._ishlnsubmul(O,1,U),S.isZero()||(S.negative^=1);m&&(m.words[U]=G)}return m&&m.strip(),S.strip(),y!=="div"&&w!==0&&S.iushrn(w),{div:m||null,mod:S}},n.prototype.divmod=function(h,y,w){if(r(!h.isZero()),this.isZero())return{div:new n(0),mod:new n(0)};var S,O,C;return this.negative!==0&&h.negative===0?(C=this.neg().divmod(h,y),y!=="mod"&&(S=C.div.neg()),y!=="div"&&(O=C.mod.neg(),w&&O.negative!==0&&O.iadd(h)),{div:S,mod:O}):this.negative===0&&h.negative!==0?(C=this.divmod(h.neg(),y),y!=="mod"&&(S=C.div.neg()),{div:S,mod:C.mod}):(this.negative&h.negative)!==0?(C=this.neg().divmod(h.neg(),y),y!=="div"&&(O=C.mod.neg(),w&&O.negative!==0&&O.isub(h)),{div:C.div,mod:O}):h.length>this.length||this.cmp(h)<0?{div:new n(0),mod:this}:h.length===1?y==="div"?{div:this.divn(h.words[0]),mod:null}:y==="mod"?{div:null,mod:new n(this.modn(h.words[0]))}:{div:this.divn(h.words[0]),mod:new n(this.modn(h.words[0]))}:this._wordDiv(h,y)},n.prototype.div=function(h){return this.divmod(h,"div",!1).div},n.prototype.mod=function(h){return this.divmod(h,"mod",!1).mod},n.prototype.umod=function(h){return this.divmod(h,"mod",!0).mod},n.prototype.divRound=function(h){var y=this.divmod(h);if(y.mod.isZero())return y.div;var w=y.mod.abs(),S=h.abs().iushrn(1),O=h.words[0]&1,C=w.cmp(S);if(C<0||O===1&&C===0)return y.div;var D=new n(1);return D.negative=this.negative^h.negative,y.div.iadd(D)},n.prototype.modn=function(h){r(h<=67108863);for(var y=(1<<26)%h,w=0,S=this.length-1;S>=0;S--)w=(y*w+(this.words[S]|0))%h;return w},n.prototype.idivn=function(h){r(h<=67108863);for(var y=0,w=this.length-1;w>=0;w--){var S=(this.words[w]|0)+y*67108864;this.words[w]=S/h|0,y=S%h}return this.strip()},n.prototype.divn=function(h){return this.clone().idivn(h)},n.prototype.egcd=function(h){r(h.negative===0),r(!h.isZero());var y=this,w=h.clone();y.negative!==0?y=y.umod(h):y=y.clone();for(var S=new n(1),O=new n(0),C=new n(0),D=new n(1),P=0;y.isEven()&&w.isEven();)y.iushrn(1),w.iushrn(1),++P;for(var m=w.clone(),x=y.clone();!y.isZero();){for(var K=0,U=1;(y.words[0]&U)===0&&K<26;++K,U<<=1);if(K>0)for(y.iushrn(K);K-- >0;)(S.isOdd()||O.isOdd())&&(S.iadd(m),O.isub(x)),S.iushrn(1),O.iushrn(1);for(var G=0,te=1;(w.words[0]&te)===0&&G<26;++G,te<<=1);if(G>0)for(w.iushrn(G);G-- >0;)(C.isOdd()||D.isOdd())&&(C.iadd(m),D.isub(x)),C.iushrn(1),D.iushrn(1);y.cmp(w)>=0?(y.isub(w),S.isub(C),O.isub(D)):(w.isub(y),C.isub(S),D.isub(O))}return{a:C,b:D,gcd:w.iushln(P)}},n.prototype._invmp=function(h){r(h.negative===0),r(!h.isZero());var y=this,w=h.clone();y.negative!==0?y=y.umod(h):y=y.clone();for(var S=new n(1),O=new n(0),C=w.clone();y.cmpn(1)>0&&w.cmpn(1)>0;){for(var D=0,P=1;(y.words[0]&P)===0&&D<26;++D,P<<=1);if(D>0)for(y.iushrn(D);D-- >0;)S.isOdd()&&S.iadd(C),S.iushrn(1);for(var m=0,x=1;(w.words[0]&x)===0&&m<26;++m,x<<=1);if(m>0)for(w.iushrn(m);m-- >0;)O.isOdd()&&O.iadd(C),O.iushrn(1);y.cmp(w)>=0?(y.isub(w),S.isub(O)):(w.isub(y),O.isub(S))}var K;return y.cmpn(1)===0?K=S:K=O,K.cmpn(0)<0&&K.iadd(h),K},n.prototype.gcd=function(h){if(this.isZero())return h.abs();if(h.isZero())return this.abs();var y=this.clone(),w=h.clone();y.negative=0,w.negative=0;for(var S=0;y.isEven()&&w.isEven();S++)y.iushrn(1),w.iushrn(1);do{for(;y.isEven();)y.iushrn(1);for(;w.isEven();)w.iushrn(1);var O=y.cmp(w);if(O<0){var C=y;y=w,w=C}else if(O===0||w.cmpn(1)===0)break;y.isub(w)}while(!0);return w.iushln(S)},n.prototype.invm=function(h){return this.egcd(h).a.umod(h)},n.prototype.isEven=function(){return(this.words[0]&1)===0},n.prototype.isOdd=function(){return(this.words[0]&1)===1},n.prototype.andln=function(h){return this.words[0]&h},n.prototype.bincn=function(h){r(typeof h=="number");var y=h%26,w=(h-y)/26,S=1<<y;if(this.length<=w)return this._expand(w+1),this.words[w]|=S,this;for(var O=S,C=w;O!==0&&C<this.length;C++){var D=this.words[C]|0;D+=O,O=D>>>26,D&=67108863,this.words[C]=D}return O!==0&&(this.words[C]=O,this.length++),this},n.prototype.isZero=function(){return this.length===1&&this.words[0]===0},n.prototype.cmpn=function(h){var y=h<0;if(this.negative!==0&&!y)return-1;if(this.negative===0&&y)return 1;this.strip();var w;if(this.length>1)w=1;else{y&&(h=-h),r(h<=67108863,"Number is too big");var S=this.words[0]|0;w=S===h?0:S<h?-1:1}return this.negative!==0?-w|0:w},n.prototype.cmp=function(h){if(this.negative!==0&&h.negative===0)return-1;if(this.negative===0&&h.negative!==0)return 1;var y=this.ucmp(h);return this.negative!==0?-y|0:y},n.prototype.ucmp=function(h){if(this.length>h.length)return 1;if(this.length<h.length)return-1;for(var y=0,w=this.length-1;w>=0;w--){var S=this.words[w]|0,O=h.words[w]|0;if(S!==O){S<O?y=-1:S>O&&(y=1);break}}return y},n.prototype.gtn=function(h){return this.cmpn(h)===1},n.prototype.gt=function(h){return this.cmp(h)===1},n.prototype.gten=function(h){return this.cmpn(h)>=0},n.prototype.gte=function(h){return this.cmp(h)>=0},n.prototype.ltn=function(h){return this.cmpn(h)===-1},n.prototype.lt=function(h){return this.cmp(h)===-1},n.prototype.lten=function(h){return this.cmpn(h)<=0},n.prototype.lte=function(h){return this.cmp(h)<=0},n.prototype.eqn=function(h){return this.cmpn(h)===0},n.prototype.eq=function(h){return this.cmp(h)===0},n.red=function(h){return new V(h)},n.prototype.toRed=function(h){return r(!this.red,"Already a number in reduction context"),r(this.negative===0,"red works only with positives"),h.convertTo(this)._forceRed(h)},n.prototype.fromRed=function(){return r(this.red,"fromRed works only with numbers in reduction context"),this.red.convertFrom(this)},n.prototype._forceRed=function(h){return this.red=h,this},n.prototype.forceRed=function(h){return r(!this.red,"Already a number in reduction context"),this._forceRed(h)},n.prototype.redAdd=function(h){return r(this.red,"redAdd works only with red numbers"),this.red.add(this,h)},n.prototype.redIAdd=function(h){return r(this.red,"redIAdd works only with red numbers"),this.red.iadd(this,h)},n.prototype.redSub=function(h){return r(this.red,"redSub works only with red numbers"),this.red.sub(this,h)},n.prototype.redISub=function(h){return r(this.red,"redISub works only with red numbers"),this.red.isub(this,h)},n.prototype.redShl=function(h){return r(this.red,"redShl works only with red numbers"),this.red.shl(this,h)},n.prototype.redMul=function(h){return r(this.red,"redMul works only with red numbers"),this.red._verify2(this,h),this.red.mul(this,h)},n.prototype.redIMul=function(h){return r(this.red,"redMul works only with red numbers"),this.red._verify2(this,h),this.red.imul(this,h)},n.prototype.redSqr=function(){return r(this.red,"redSqr works only with red numbers"),this.red._verify1(this),this.red.sqr(this)},n.prototype.redISqr=function(){return r(this.red,"redISqr works only with red numbers"),this.red._verify1(this),this.red.isqr(this)},n.prototype.redSqrt=function(){return r(this.red,"redSqrt works only with red numbers"),this.red._verify1(this),this.red.sqrt(this)},n.prototype.redInvm=function(){return r(this.red,"redInvm works only with red numbers"),this.red._verify1(this),this.red.invm(this)},n.prototype.redNeg=function(){return r(this.red,"redNeg works only with red numbers"),this.red._verify1(this),this.red.neg(this)},n.prototype.redPow=function(h){return r(this.red&&!h.red,"redPow(normalNum)"),this.red._verify1(this),this.red.pow(this,h)};var q={k256:null,p224:null,p192:null,p25519:null};function z(E,h){this.name=E,this.p=new n(h,16),this.n=this.p.bitLength(),this.k=new n(1).iushln(this.n).isub(this.p),this.tmp=this._tmp()}z.prototype._tmp=function(){var h=new n(null);return h.words=new Array(Math.ceil(this.n/13)),h},z.prototype.ireduce=function(h){var y=h,w;do this.split(y,this.tmp),y=this.imulK(y),y=y.iadd(this.tmp),w=y.bitLength();while(w>this.n);var S=w<this.n?-1:y.ucmp(this.p);return S===0?(y.words[0]=0,y.length=1):S>0?y.isub(this.p):y.strip!==void 0?y.strip():y._strip(),y},z.prototype.split=function(h,y){h.iushrn(this.n,0,y)},z.prototype.imulK=function(h){return h.imul(this.k)};function A(){z.call(this,"k256","ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff fffffffe fffffc2f")}i(A,z),A.prototype.split=function(h,y){for(var w=4194303,S=Math.min(h.length,9),O=0;O<S;O++)y.words[O]=h.words[O];if(y.length=S,h.length<=9){h.words[0]=0,h.length=1;return}var C=h.words[9];for(y.words[y.length++]=C&w,O=10;O<h.length;O++){var D=h.words[O]|0;h.words[O-10]=(D&w)<<4|C>>>22,C=D}C>>>=22,h.words[O-10]=C,C===0&&h.length>10?h.length-=10:h.length-=9},A.prototype.imulK=function(h){h.words[h.length]=0,h.words[h.length+1]=0,h.length+=2;for(var y=0,w=0;w<h.length;w++){var S=h.words[w]|0;y+=S*977,h.words[w]=y&67108863,y=S*64+(y/67108864|0)}return h.words[h.length-1]===0&&(h.length--,h.words[h.length-1]===0&&h.length--),h};function B(){z.call(this,"p224","ffffffff ffffffff ffffffff ffffffff 00000000 00000000 00000001")}i(B,z);function M(){z.call(this,"p192","ffffffff ffffffff ffffffff fffffffe ffffffff ffffffff")}i(M,z);function F(){z.call(this,"25519","7fffffffffffffff ffffffffffffffff ffffffffffffffff ffffffffffffffed")}i(F,z),F.prototype.imulK=function(h){for(var y=0,w=0;w<h.length;w++){var S=(h.words[w]|0)*19+y,O=S&67108863;S>>>=26,h.words[w]=O,y=S}return y!==0&&(h.words[h.length++]=y),h},n._prime=function(h){if(q[h])return q[h];var y;if(h==="k256")y=new A;else if(h==="p224")y=new B;else if(h==="p192")y=new M;else if(h==="p25519")y=new F;else throw new Error("Unknown prime "+h);return q[h]=y,y};function V(E){if(typeof E=="string"){var h=n._prime(E);this.m=h.p,this.prime=h}else r(E.gtn(1),"modulus must be greater than 1"),this.m=E,this.prime=null}V.prototype._verify1=function(h){r(h.negative===0,"red works only with positives"),r(h.red,"red works only with red numbers")},V.prototype._verify2=function(h,y){r((h.negative|y.negative)===0,"red works only with positives"),r(h.red&&h.red===y.red,"red works only with red numbers")},V.prototype.imod=function(h){return this.prime?this.prime.ireduce(h)._forceRed(this):h.umod(this.m)._forceRed(this)},V.prototype.neg=function(h){return h.isZero()?h.clone():this.m.sub(h)._forceRed(this)},V.prototype.add=function(h,y){this._verify2(h,y);var w=h.add(y);return w.cmp(this.m)>=0&&w.isub(this.m),w._forceRed(this)},V.prototype.iadd=function(h,y){this._verify2(h,y);var w=h.iadd(y);return w.cmp(this.m)>=0&&w.isub(this.m),w},V.prototype.sub=function(h,y){this._verify2(h,y);var w=h.sub(y);return w.cmpn(0)<0&&w.iadd(this.m),w._forceRed(this)},V.prototype.isub=function(h,y){this._verify2(h,y);var w=h.isub(y);return w.cmpn(0)<0&&w.iadd(this.m),w},V.prototype.shl=function(h,y){return this._verify1(h),this.imod(h.ushln(y))},V.prototype.imul=function(h,y){return this._verify2(h,y),this.imod(h.imul(y))},V.prototype.mul=function(h,y){return this._verify2(h,y),this.imod(h.mul(y))},V.prototype.isqr=function(h){return this.imul(h,h.clone())},V.prototype.sqr=function(h){return this.mul(h,h)},V.prototype.sqrt=function(h){if(h.isZero())return h.clone();var y=this.m.andln(3);if(r(y%2===1),y===3){var w=this.m.add(new n(1)).iushrn(2);return this.pow(h,w)}for(var S=this.m.subn(1),O=0;!S.isZero()&&S.andln(1)===0;)O++,S.iushrn(1);r(!S.isZero());var C=new n(1).toRed(this),D=C.redNeg(),P=this.m.subn(1).iushrn(1),m=this.m.bitLength();for(m=new n(2*m*m).toRed(this);this.pow(m,P).cmp(D)!==0;)m.redIAdd(D);for(var x=this.pow(m,S),K=this.pow(h,S.addn(1).iushrn(1)),U=this.pow(h,S),G=O;U.cmp(C)!==0;){for(var te=U,ae=0;te.cmp(C)!==0;ae++)te=te.redSqr();r(ae<G);var oe=this.pow(x,new n(1).iushln(G-ae-1));K=K.redMul(oe),x=oe.redSqr(),U=U.redMul(x),G=ae}return K},V.prototype.invm=function(h){var y=h._invmp(this.m);return y.negative!==0?(y.negative=0,this.imod(y).redNeg()):this.imod(y)},V.prototype.pow=function(h,y){if(y.isZero())return new n(1).toRed(this);if(y.cmpn(1)===0)return h.clone();var w=4,S=new Array(1<<w);S[0]=new n(1).toRed(this),S[1]=h;for(var O=2;O<S.length;O++)S[O]=this.mul(S[O-1],h);var C=S[0],D=0,P=0,m=y.bitLength()%26;for(m===0&&(m=26),O=y.length-1;O>=0;O--){for(var x=y.words[O],K=m-1;K>=0;K--){var U=x>>K&1;if(C!==S[0]&&(C=this.sqr(C)),U===0&&D===0){P=0;continue}D<<=1,D|=U,P++,!(P!==w&&(O!==0||K!==0))&&(C=this.mul(C,S[D]),P=0,D=0)}m=26}return C},V.prototype.convertTo=function(h){var y=h.umod(this.m);return y===h?y.clone():y},V.prototype.convertFrom=function(h){var y=h.clone();return y.red=null,y},n.mont=function(h){return new Y(h)};function Y(E){V.call(this,E),this.shift=this.m.bitLength(),this.shift%26!==0&&(this.shift+=26-this.shift%26),this.r=new n(1).iushln(this.shift),this.r2=this.imod(this.r.sqr()),this.rinv=this.r._invmp(this.m),this.minv=this.rinv.mul(this.r).isubn(1).div(this.m),this.minv=this.minv.umod(this.r),this.minv=this.r.sub(this.minv)}i(Y,V),Y.prototype.convertTo=function(h){return this.imod(h.ushln(this.shift))},Y.prototype.convertFrom=function(h){var y=this.imod(h.mul(this.rinv));return y.red=null,y},Y.prototype.imul=function(h,y){if(h.isZero()||y.isZero())return h.words[0]=0,h.length=1,h;var w=h.imul(y),S=w.maskn(this.shift).mul(this.minv).imaskn(this.shift).mul(this.m),O=w.isub(S).iushrn(this.shift),C=O;return O.cmp(this.m)>=0?C=O.isub(this.m):O.cmpn(0)<0&&(C=O.iadd(this.m)),C._forceRed(this)},Y.prototype.mul=function(h,y){if(h.isZero()||y.isZero())return new n(0)._forceRed(this);var w=h.mul(y),S=w.maskn(this.shift).mul(this.minv).imaskn(this.shift).mul(this.m),O=w.isub(S).iushrn(this.shift),C=O;return O.cmp(this.m)>=0?C=O.isub(this.m):O.cmpn(0)<0&&(C=O.iadd(this.m)),C._forceRed(this)},Y.prototype.invm=function(h){var y=this.imod(h._invmp(this.m).mul(this.r2));return y._forceRed(this)}})(typeof Qy>"u"||Qy,UT)});var eb=T((Nne,FT)=>{"use strict";g();FT.exports="9.23.0"});var zT=T((Lne,jT)=>{"use strict";g();var rK="https://docs.moneybutton.com/";jT.exports=[{name:"InvalidB58Char",message:"Invalid Base58 character: {0} in {1}"},{name:"InvalidB58Checksum",message:"Invalid Base58 checksum for {0}"},{name:"InvalidNetwork",message:"Invalid version for network: got {0}"},{name:"InvalidState",message:"Invalid state: {0}"},{name:"NotImplemented",message:"Function {0} was not implemented yet"},{name:"InvalidNetworkArgument",message:'Invalid network: must be "livenet" or "testnet", got {0}'},{name:"InvalidArgument",message:function(){return"Invalid Argument"+(arguments[0]?": "+arguments[0]:"")+(arguments[1]?" Documentation: "+rK+arguments[1]:"")}},{name:"AbstractMethodInvoked",message:"Abstract Method Invocation: {0}"},{name:"InvalidArgumentType",message:function(){return"Invalid Argument for "+arguments[2]+", expected "+arguments[1]+" but got "+typeof arguments[0]}},{name:"Unit",message:"Internal Error on Unit {0}",errors:[{name:"UnknownCode",message:"Unrecognized unit code: {0}"},{name:"InvalidRate",message:"Invalid exchange rate: {0}"}]},{name:"MerkleBlock",message:"Internal Error on MerkleBlock {0}",errors:[{name:"InvalidMerkleTree",message:"This MerkleBlock contain an invalid Merkle Tree"}]},{name:"Transaction",message:"Internal Error on Transaction {0}",errors:[{name:"Input",message:"Internal Error on Input {0}",errors:[{name:"MissingScript",message:"Need a script to create an input"},{name:"UnsupportedScript",message:"Unsupported input script type: {0}"},{name:"MissingPreviousOutput",message:"No previous output information."}]},{name:"NeedMoreInfo",message:"{0}"},{name:"InvalidSorting",message:"The sorting function provided did not return the change output as one of the array elements"},{name:"InvalidOutputAmountSum",message:"{0}"},{name:"MissingSignatures",message:"Some inputs have not been fully signed"},{name:"InvalidIndex",message:"Invalid index: {0} is not between 0, {1}"},{name:"UnableToVerifySignature",message:"Unable to verify signature: {0}"},{name:"DustOutputs",message:"Dust amount detected in one output"},{name:"InvalidSatoshis",message:"Output satoshis are invalid"},{name:"FeeError",message:"Internal Error on Fee {0}",errors:[{name:"TooSmall",message:"Fee is too small: {0}"},{name:"TooLarge",message:"Fee is too large: {0}"},{name:"Different",message:"Unspent value is different from specified fee: {0}"}]},{name:"ChangeAddressMissing",message:"Change address is missing"},{name:"BlockHeightTooHigh",message:"Block Height can be at most 2^32 -1"},{name:"NLockTimeOutOfRange",message:"Block Height can only be between 0 and 499 999 999"},{name:"LockTimeTooEarly",message:"Lock Time can't be earlier than UNIX date 500 000 000"}]},{name:"Script",message:"Internal Error on Script {0}",errors:[{name:"UnrecognizedAddress",message:"Expected argument {0} to be an address"},{name:"CantDeriveAddress",message:"Can't derive address associated with script {0}, needs to be p2pkh in, p2pkh out, p2sh in, or p2sh out."},{name:"InvalidBuffer",message:"Invalid script buffer: can't parse valid script from given buffer {0}"}]},{name:"HDPrivateKey",message:"Internal Error on HDPrivateKey {0}",errors:[{name:"InvalidDerivationArgument",message:"Invalid derivation argument {0}, expected string, or number and boolean"},{name:"InvalidEntropyArgument",message:"Invalid entropy: must be an hexa string or binary buffer, got {0}",errors:[{name:"TooMuchEntropy",message:'Invalid entropy: more than 512 bits is non standard, got "{0}"'},{name:"NotEnoughEntropy",message:'Invalid entropy: at least 128 bits needed, got "{0}"'}]},{name:"InvalidLength",message:"Invalid length for xprivkey string in {0}"},{name:"InvalidPath",message:"Invalid derivation path: {0}"},{name:"UnrecognizedArgument",message:'Invalid argument: creating a HDPrivateKey requires a string, buffer, json or object, got "{0}"'}]},{name:"HDPublicKey",message:"Internal Error on HDPublicKey {0}",errors:[{name:"ArgumentIsPrivateExtended",message:"Argument is an extended private key: {0}"},{name:"InvalidDerivationArgument",message:"Invalid derivation argument: got {0}"},{name:"InvalidLength",message:'Invalid length for xpubkey: got "{0}"'},{name:"InvalidPath",message:'Invalid derivation path, it should look like: "m/1/100", got "{0}"'},{name:"InvalidIndexCantDeriveHardened",message:"Invalid argument: creating a hardened path requires an HDPrivateKey"},{name:"MustSupplyArgument",message:"Must supply an argument to create a HDPublicKey"},{name:"UnrecognizedArgument",message:"Invalid argument for creation, must be string, json, buffer, or object"}]}]});var pi=T((Dne,rb)=>{"use strict";g();var tb=at();function iK(e,t){return e.replace("{0}",t[0]).replace("{1}",t[1]).replace("{2}",t[2])}var KT=function(e,t){var r=function(){if(tb.isString(t.message))this.message=iK(t.message,arguments);else if(tb.isFunction(t.message))this.message=t.message.apply(null,arguments);else throw new Error("Invalid error definition for "+t.name);this.stack=this.message+`
|
|
12
12
|
`+new Error().stack};return r.prototype=Object.create(e.prototype),r.prototype.name=e.prototype.name+t.name,e[t.name]=r,t.errors&&VT(r,t.errors),r},VT=function(e,t){tb.each(t,function(r){KT(e,r)})},nK=function(e,t){return VT(e,t),e},gc={};gc.Error=function(){this.message="Internal error",this.stack=this.message+`
|
|
13
13
|
`+new Error().stack};gc.Error.prototype=Object.create(Error.prototype);gc.Error.prototype.name="bsv.Error";var oK=zT();nK(gc.Error,oK);rb.exports=gc.Error;rb.exports.extend=function(e){return KT(gc.Error,e)}});var Ie=T((qne,GT)=>{"use strict";g();var El=pi(),aK=at();GT.exports={checkState:function(e,t){if(!e)throw new El.InvalidState(t)},checkArgument:function(e,t,r,i){if(!e)throw new El.InvalidArgument(t,r,i)},checkArgumentType:function(e,t,r){if(r=r||"(unknown name)",aK.isString(t)){if(t==="Buffer"){var i=rr();if(!i.Buffer.isBuffer(e))throw new El.InvalidArgumentType(e,t,r)}else if(typeof e!==t)throw new El.InvalidArgumentType(e,t,r)}else if(!(e instanceof t))throw new El.InvalidArgumentType(e,t.name,r)}}});var Ke=T((Fne,$T)=>{"use strict";g();var pt=qp(),YT=Ie(),ZT=at(),Up=function(e){for(var t=f.Buffer.alloc(e.length),r=0;r<e.length;r++)t[r]=e[e.length-1-r];return t};pt.Zero=new pt(0);pt.One=new pt(1);pt.Minus1=new pt(-1);pt.fromNumber=function(e){return YT.checkArgument(ZT.isNumber(e)),new pt(e)};pt.fromString=function(e,t){return YT.checkArgument(ZT.isString(e)),new pt(e,t)};pt.fromBuffer=function(e,t){typeof t<"u"&&t.endian==="little"&&(e=Up(e));var r=e.toString("hex"),i=new pt(r,16);return i};pt.fromSM=function(e,t){var r;if(e.length===0)return pt.fromBuffer(f.Buffer.from([0]));var i="big";return t&&(i=t.endian),i==="little"&&(e=Up(e)),e[0]&128?(e[0]=e[0]&127,r=pt.fromBuffer(e),r.neg().copy(r)):r=pt.fromBuffer(e),r};pt.prototype.toNumber=function(){return parseInt(this.toString(10),10)};pt.prototype.toBuffer=function(e){var t,r;if(e&&e.size){r=this.toString(16,2);var i=r.length/2;t=f.Buffer.from(r,"hex"),i===e.size||(i>e.size?t=pt.trim(t,i):i<e.size&&(t=pt.pad(t,i,e.size)))}else r=this.toString(16,2),t=f.Buffer.from(r,"hex");return typeof e<"u"&&e.endian==="little"&&(t=Up(t)),t};pt.prototype.toSMBigEndian=function(){var e;return this.cmp(pt.Zero)===-1?(e=this.neg().toBuffer(),e[0]&128?e=f.Buffer.concat([f.Buffer.from([128]),e]):e[0]=e[0]|128):(e=this.toBuffer(),e[0]&128&&(e=f.Buffer.concat([f.Buffer.from([0]),e]))),e.length===1&&e[0]===0&&(e=f.Buffer.from([])),e};pt.prototype.toSM=function(e){var t=e?e.endian:"big",r=this.toSMBigEndian();return t==="little"&&(r=Up(r)),r};function WT(e,t){var r=new Error(e);return r.scriptErr=t,r}pt.fromScriptNumBuffer=function(e,t,r){var i=r||4;if(e.length>i)throw WT("script number overflow","SCRIPT_ERR_SCRIPTNUM_OVERFLOW");if(t&&e.length>0&&(e[e.length-1]&127)===0&&(e.length<=1||(e[e.length-2]&128)===0))throw WT("non-minimally encoded script number","SCRIPT_ERR_SCRIPTNUM_MINENCODE");return pt.fromSM(e,{endian:"little"})};pt.prototype.toScriptNumBuffer=function(){return this.toSM({endian:"little"})};pt.trim=function(e,t){return e.slice(t-e.length,e.length)};pt.pad=function(e,t,r){for(var i=f.Buffer.alloc(r),n=0;n<e.length;n++)i[i.length-1-n]=e[e.length-1-n];for(n=0;n<r-t;n++)i[n]=0;return i};pt.prototype.toHex=function(...e){return this.toBuffer(...e).toString("hex")};pt.fromHex=function(e,...t){return pt.fromBuffer(f.Buffer.from(e,"hex"),...t)};$T.exports=pt});function sK(e,t=!1){return t?{h:Number(e&Fp),l:Number(e>>XT&Fp)}:{h:Number(e>>XT&Fp)|0,l:Number(e&Fp)|0}}function JT(e,t=!1){let r=e.length,i=new Uint32Array(r),n=new Uint32Array(r);for(let o=0;o<r;o++){let{h:a,l:s}=sK(e[o],t);[i[o],n[o]]=[a,s]}return[i,n]}function QT(e,t,r,i){let n=uK(r),o=cK(r);e.setUint32(t,i?o:n,i),e.setUint32(t+4,i?n:o,i)}function io(e,t,r,i){let n=(t>>>0)+(i>>>0);return{h:e+r+(n/2**32|0)|0,l:n|0}}var Fp,XT,uK,cK,ib,nb,Ws,Ys,xl,Ol,eP,tP,rP,iP,nP,oP,ob=Dr(()=>{g();Fp=BigInt(4294967295),XT=BigInt(32);uK=e=>e/2**32|0,cK=e=>e>>>0;ib=(e,t,r)=>e>>>r,nb=(e,t,r)=>e<<32-r|t>>>r,Ws=(e,t,r)=>e>>>r|t<<32-r,Ys=(e,t,r)=>e<<32-r|t>>>r,xl=(e,t,r)=>e<<64-r|t>>>r-32,Ol=(e,t,r)=>e>>>r-32|t<<64-r;eP=(e,t,r)=>(e>>>0)+(t>>>0)+(r>>>0),tP=(e,t,r,i)=>t+r+i+(e/2**32|0)|0,rP=(e,t,r,i)=>(e>>>0)+(t>>>0)+(r>>>0)+(i>>>0),iP=(e,t,r,i,n)=>t+r+i+n+(e/2**32|0)|0,nP=(e,t,r,i,n)=>(e>>>0)+(t>>>0)+(r>>>0)+(i>>>0)+(n>>>0),oP=(e,t,r,i,n,o)=>t+r+i+n+o+(e/2**32|0)|0});function jp(e){return e instanceof Uint8Array||ArrayBuffer.isView(e)&&e.constructor.name==="Uint8Array"&&"BYTES_PER_ELEMENT"in e&&e.BYTES_PER_ELEMENT===1}function $o(e,t=""){if(typeof e!="number")throw new TypeError(ab(t)+"expected number, got "+typeof e);if(!Number.isSafeInteger(e)||e<0)throw new RangeError(ab(t)+"expected integer >= 0, got "+e);return e}function no(e,t,r=""){if(jp(e)&&(t===void 0||e.length===t))return e;t!==void 0&&$o(t,"length");let i=jp(e),n=t!==void 0?` of length ${t}`:"",o=i?`length=${e.length}`:`type=${typeof e}`,a=ab(r)+"expected Uint8Array"+n+", got "+o;throw i?new RangeError(a):new TypeError(a)}function zp(e){if(typeof e!="function"||typeof e.create!="function")throw new TypeError("expected hash wrapped by utils.createHasher");if($o(e.outputLen),$o(e.blockLen),e.outputLen<1||e.blockLen<1)throw new Error("hash blockLen / outputLen must be >= 1")}function mc(e,t=!0){if(e.destroyed)throw new Error("hash was destroyed");if(t&&e.finished)throw new Error("digest() was already called")}function Kp(e,t){no(e,void 0,"output");let r=t.outputLen;if(!(e.length>=r))throw new RangeError('"output" expected length >= '+r)}function wi(...e){for(let t=0;t<e.length;t++)e[t].fill(0)}function Vp(e){return new DataView(e.buffer,e.byteOffset,e.byteLength)}function In(e,t){return e<<32-t|e>>>t}function Xo(e,t){return e<<t|e>>>32-t>>>0}function Gp(e){if(no(e),uP)return e.toHex();let t="";for(let r=0;r<e.length;r++)t+=hK[e[r]];return t}function sP(e){return e>=48&&e<=57?e-48:e>=65&&e<=70?e-55:e>=97&&e<=102?e-87:void 0}function sb(e){if(typeof e!="string")throw new TypeError("hex string expected, got "+typeof e);if(uP)try{return Uint8Array.fromHex(e)}catch(n){throw n instanceof SyntaxError?new RangeError(n.message):n}let t=e.length,r=t/2;if(t%2)throw new RangeError("hex string expected, got unpadded hex of length "+t);let i=new Uint8Array(r);for(let n=0,o=0;n<r;n++,o+=2){let a=sP(e.charCodeAt(o)),s=sP(e.charCodeAt(o+1));if(a===void 0||s===void 0){let u=e[o]+e[o+1];throw new RangeError('hex string expected, got non-hex character "'+u+'" at index '+o)}i[n]=a*16+s}return i}function Jo(e){if(typeof e!="string")throw new TypeError("string expected");let t=new TextEncoder().encode(e);try{return new Uint8Array(t)}finally{wi(t)}}function cP(...e){let t=0;for(let i=0;i<e.length;i++){let n=e[i];no(n),t+=n.length}let r=new Uint8Array(t);for(let i=0,n=0;i<e.length;i++){let o=e[i];r.set(o,n),n+=o.length}return r}function dK(e,t,r="opts"){return aP(e,"defaults"),t!==void 0&&aP(t,r),Object.assign(Object.create(null),e,t)}function An(e,t={}){if(typeof e!="function")throw new TypeError('"hashCons" expected function, got type='+typeof e);t=dK({},t,"info");let r=(n,o)=>e(o).update(n).digest(),i=e(void 0);return r.outputLen=i.outputLen,r.blockLen=i.blockLen,r.canXOF=i.canXOF,r.create=n=>e(n),Object.assign(r,t),Object.freeze(r)}function Il(e=32){$o(e,"bytesLength");let t=typeof globalThis=="object"?globalThis.crypto:null;if(typeof t?.getRandomValues!="function")throw new Error("crypto.getRandomValues must be defined");if(e>65536)throw new RangeError(`"bytesLength" expected <= 65536, got ${e}`);return t.getRandomValues(new Uint8Array(e))}var ab,lK,aP,uP,hK,Zs,Qo=Dr(()=>{g();ab=e=>e?`"${e}" `:"";lK=(e,t)=>{if(e===null||typeof e!="object"||Array.isArray(e))throw new TypeError((t==="object"?"":`"${t}" `)+"expected object, got type="+typeof e)},aP=(e,t)=>{lK(e,t);let r=Object.getPrototypeOf(e);if(r!==Object.prototype&&r!==null)throw new TypeError(`"${t}" expected plain object`);if(Object.hasOwn(e,"__proto__"))throw new TypeError(`"${t}.__proto__" is not allowed`)};uP=typeof Uint8Array.from([]).toHex=="function"&&typeof Uint8Array.fromHex=="function",hK=Array.from({length:256},(e,t)=>t.toString(16).padStart(2,"0"));Zs=e=>({oid:Uint8Array.from([6,9,96,134,72,1,101,3,4,2,e])})});function vc(e,t,r){return e&t^~e&r}function Wp(e,t,r){return e&t^e&r^t&r}var ea,fP,lP,hP,dP,ub=Dr(()=>{g();ob();Qo();ea=class{constructor(t,r,i,n){ee(this,"blockLen");ee(this,"outputLen");ee(this,"canXOF",!1);ee(this,"padOffset");ee(this,"isLE");ee(this,"buffer");ee(this,"view");ee(this,"finished",!1);ee(this,"length",0);ee(this,"pos",0);ee(this,"destroyed",!1);this.blockLen=t,this.outputLen=r,this.padOffset=i,this.isLE=n,this.buffer=new Uint8Array(t),this.view=Vp(this.buffer)}update(t){mc(this),no(t);let{view:r,buffer:i,blockLen:n}=this,o=t.length,a=!1;for(let s=0;s<o;){let u=Math.min(n-this.pos,o-s);if(u===n){let c=Vp(t);for(;n<=o-s;s+=n)this.process(c,s);a=!0;continue}i.set(s===0&&u===o?t:t.subarray(s,s+u),this.pos),this.pos+=u,s+=u,this.pos===n&&(this.process(r,0),this.pos=0,a=!0)}return this.length+=t.length,a&&this.roundClean(),this}digestInto(t){mc(this),Kp(t,this),this.finished=!0;let{buffer:r,view:i,blockLen:n,isLE:o}=this,{pos:a}=this;r[a++]=128,r.fill(0,a),this.padOffset>n-a&&(this.process(i,0),r.fill(0)),QT(i,n-8,this.length*8,o),this.process(i,0),this.roundClean();let s=t===r?i:Vp(t),u=this.outputLen,c=u/4,l=this.get();if(u%4||c>l.length)throw new Error("invalid outputLen");for(let p=0;p<c;p++)s.setUint32(4*p,l[p],o)}digest(){let{buffer:t,outputLen:r}=this;this.digestInto(t);let i=t.slice(0,r);return this.destroy(),i}_cloneIntoMeta(t){let{buffer:r,length:i,finished:n,destroyed:o,pos:a}=this;return t.destroyed=o,t.finished=n,t.length=i,t.pos=a,a&&t.buffer.set(r),t}clone(){return this._cloneInto()}},fP=Uint32Array.from([1779033703,3144134277,1013904242,2773480762,1359893119,2600822924,528734635,1541459225]),lP=Uint32Array.from([3238371032,914150663,812702999,4144912697,4290775857,1750603025,1694076839,3204075428]),hP=Uint32Array.from([3418070365,3238371032,1654270250,914150663,2438529370,812702999,355462360,4144912697,1731405415,4290775857,2394180231,1750603025,3675008525,1694076839,1203062813,3204075428]),dP=Uint32Array.from([1779033703,4089235720,3144134277,2227873595,1013904242,4271175723,2773480762,1595750129,1359893119,2917565137,2600822924,725511199,528734635,4215389547,1541459225,327033209])});var tg={};Hf(tg,{_SHA224:()=>$p,_SHA256:()=>Zp,_SHA384:()=>Jp,_SHA512:()=>Xp,_SHA512_224:()=>Qp,_SHA512_256:()=>eg,sha224:()=>bK,sha256:()=>Fa,sha384:()=>wK,sha512:()=>_K,sha512_224:()=>EK,sha512_256:()=>SK});var pK,Ha,Yp,Zp,$p,pP,gK,mK,qa,Ua,yc,Xp,Jp,vK,yK,Qp,eg,Fa,bK,_K,wK,SK,EK,Al=Dr(()=>{g();ub();ob();Qo();pK=Uint32Array.from([1116352408,1899447441,3049323471,3921009573,961987163,1508970993,2453635748,2870763221,3624381080,310598401,607225278,1426881987,1925078388,2162078206,2614888103,3248222580,3835390401,4022224774,264347078,604807628,770255983,1249150122,1555081692,1996064986,2554220882,2821834349,2952996808,3210313671,3336571891,3584528711,113926993,338241895,666307205,773529912,1294757372,1396182291,1695183700,1986661051,2177026350,2456956037,2730485921,2820302411,3259730800,3345764771,3516065817,3600352804,4094571909,275423344,430227734,506948616,659060556,883997877,958139571,1322822218,1537002063,1747873779,1955562222,2024104815,2227730452,2361852424,2428436474,2756734187,3204031479,3329325298]),Ha=new Uint32Array(64),Yp=class extends ea{constructor(r,i){super(64,r,8,!1);ee(this,"A",0);ee(this,"B",0);ee(this,"C",0);ee(this,"D",0);ee(this,"E",0);ee(this,"F",0);ee(this,"G",0);ee(this,"H",0);this.A=i[0]|0,this.B=i[1]|0,this.C=i[2]|0,this.D=i[3]|0,this.E=i[4]|0,this.F=i[5]|0,this.G=i[6]|0,this.H=i[7]|0}get(){let{A:r,B:i,C:n,D:o,E:a,F:s,G:u,H:c}=this;return[r,i,n,o,a,s,u,c]}set(r,i,n,o,a,s,u,c){this.A=r|0,this.B=i|0,this.C=n|0,this.D=o|0,this.E=a|0,this.F=s|0,this.G=u|0,this.H=c|0}_cloneInto(r){return(r||(r=new this.constructor)).set(...this.get()),this._cloneIntoMeta(r)}process(r,i){for(let d=0;d<16;d++,i+=4)Ha[d]=r.getUint32(i,!1);for(let d=16;d<64;d++){let v=Ha[d-15],_=Ha[d-2],I=In(v,7)^In(v,18)^v>>>3,R=In(_,17)^In(_,19)^_>>>10;Ha[d]=R+Ha[d-7]+I+Ha[d-16]|0}let{A:n,B:o,C:a,D:s,E:u,F:c,G:l,H:p}=this;for(let d=0;d<64;d++){let v=In(u,6)^In(u,11)^In(u,25),_=p+v+vc(u,c,l)+pK[d]+Ha[d]|0,R=(In(n,2)^In(n,13)^In(n,22))+Wp(n,o,a)|0;p=l,l=c,c=u,u=s+_|0,s=a,a=o,o=n,n=_+R|0}n=n+this.A|0,o=o+this.B|0,a=a+this.C|0,s=s+this.D|0,u=u+this.E|0,c=c+this.F|0,l=l+this.G|0,p=p+this.H|0,this.set(n,o,a,s,u,c,l,p)}roundClean(){wi(Ha)}destroy(){this.destroyed=!0,this.set(0,0,0,0,0,0,0,0),wi(this.buffer)}},Zp=class extends Yp{constructor(){super(32,fP)}},$p=class extends Yp{constructor(){super(28,lP)}},pP=JT(["0x428a2f98d728ae22","0x7137449123ef65cd","0xb5c0fbcfec4d3b2f","0xe9b5dba58189dbbc","0x3956c25bf348b538","0x59f111f1b605d019","0x923f82a4af194f9b","0xab1c5ed5da6d8118","0xd807aa98a3030242","0x12835b0145706fbe","0x243185be4ee4b28c","0x550c7dc3d5ffb4e2","0x72be5d74f27b896f","0x80deb1fe3b1696b1","0x9bdc06a725c71235","0xc19bf174cf692694","0xe49b69c19ef14ad2","0xefbe4786384f25e3","0x0fc19dc68b8cd5b5","0x240ca1cc77ac9c65","0x2de92c6f592b0275","0x4a7484aa6ea6e483","0x5cb0a9dcbd41fbd4","0x76f988da831153b5","0x983e5152ee66dfab","0xa831c66d2db43210","0xb00327c898fb213f","0xbf597fc7beef0ee4","0xc6e00bf33da88fc2","0xd5a79147930aa725","0x06ca6351e003826f","0x142929670a0e6e70","0x27b70a8546d22ffc","0x2e1b21385c26c926","0x4d2c6dfc5ac42aed","0x53380d139d95b3df","0x650a73548baf63de","0x766a0abb3c77b2a8","0x81c2c92e47edaee6","0x92722c851482353b","0xa2bfe8a14cf10364","0xa81a664bbc423001","0xc24b8b70d0f89791","0xc76c51a30654be30","0xd192e819d6ef5218","0xd69906245565a910","0xf40e35855771202a","0x106aa07032bbd1b8","0x19a4c116b8d2d0c8","0x1e376c085141ab53","0x2748774cdf8eeb99","0x34b0bcb5e19b48a8","0x391c0cb3c5c95a63","0x4ed8aa4ae3418acb","0x5b9cca4f7763e373","0x682e6ff3d6b2b8a3","0x748f82ee5defb2fc","0x78a5636f43172f60","0x84c87814a1f0ab72","0x8cc702081a6439ec","0x90befffa23631e28","0xa4506cebde82bde9","0xbef9a3f7b2c67915","0xc67178f2e372532b","0xca273eceea26619c","0xd186b8c721c0c207","0xeada7dd6cde0eb1e","0xf57d4f7fee6ed178","0x06f067aa72176fba","0x0a637dc5a2c898a6","0x113f9804bef90dae","0x1b710b35131c471b","0x28db77f523047d84","0x32caab7b40c72493","0x3c9ebe0a15c9bebc","0x431d67c49c100d4c","0x4cc5d4becb3e42b6","0x597f299cfc657e2a","0x5fcb6fab3ad6faec","0x6c44198c4a475817"].map(e=>BigInt(e))),gK=pP[0],mK=pP[1],qa=new Uint32Array(80),Ua=new Uint32Array(80),yc=class extends ea{constructor(r,i){super(128,r,16,!1);ee(this,"Ah",0);ee(this,"Al",0);ee(this,"Bh",0);ee(this,"Bl",0);ee(this,"Ch",0);ee(this,"Cl",0);ee(this,"Dh",0);ee(this,"Dl",0);ee(this,"Eh",0);ee(this,"El",0);ee(this,"Fh",0);ee(this,"Fl",0);ee(this,"Gh",0);ee(this,"Gl",0);ee(this,"Hh",0);ee(this,"Hl",0);this.Ah=i[0]|0,this.Al=i[1]|0,this.Bh=i[2]|0,this.Bl=i[3]|0,this.Ch=i[4]|0,this.Cl=i[5]|0,this.Dh=i[6]|0,this.Dl=i[7]|0,this.Eh=i[8]|0,this.El=i[9]|0,this.Fh=i[10]|0,this.Fl=i[11]|0,this.Gh=i[12]|0,this.Gl=i[13]|0,this.Hh=i[14]|0,this.Hl=i[15]|0}get(){let{Ah:r,Al:i,Bh:n,Bl:o,Ch:a,Cl:s,Dh:u,Dl:c,Eh:l,El:p,Fh:d,Fl:v,Gh:_,Gl:I,Hh:R,Hl:k}=this;return[r,i,n,o,a,s,u,c,l,p,d,v,_,I,R,k]}set(r,i,n,o,a,s,u,c,l,p,d,v,_,I,R,k){this.Ah=r|0,this.Al=i|0,this.Bh=n|0,this.Bl=o|0,this.Ch=a|0,this.Cl=s|0,this.Dh=u|0,this.Dl=c|0,this.Eh=l|0,this.El=p|0,this.Fh=d|0,this.Fl=v|0,this.Gh=_|0,this.Gl=I|0,this.Hh=R|0,this.Hl=k|0}_cloneInto(r){return(r||(r=new this.constructor)).set(...this.get()),this._cloneIntoMeta(r)}process(r,i){for(let A=0;A<16;A++,i+=4)qa[A]=r.getUint32(i),Ua[A]=r.getUint32(i+=4);for(let A=16;A<80;A++){let B=qa[A-15]|0,M=Ua[A-15]|0,F=Ws(B,M,1)^Ws(B,M,8)^ib(B,M,7),V=Ys(B,M,1)^Ys(B,M,8)^nb(B,M,7),Y=qa[A-2]|0,E=Ua[A-2]|0,h=Ws(Y,E,19)^xl(Y,E,61)^ib(Y,E,6),y=Ys(Y,E,19)^Ol(Y,E,61)^nb(Y,E,6),w=rP(V,y,Ua[A-7],Ua[A-16]),S=iP(w,F,h,qa[A-7],qa[A-16]);qa[A]=S|0,Ua[A]=w|0}let{Ah:n,Al:o,Bh:a,Bl:s,Ch:u,Cl:c,Dh:l,Dl:p,Eh:d,El:v,Fh:_,Fl:I,Gh:R,Gl:k,Hh:q,Hl:z}=this;for(let A=0;A<80;A++){let B=Ws(d,v,14)^Ws(d,v,18)^xl(d,v,41),M=Ys(d,v,14)^Ys(d,v,18)^Ol(d,v,41),F=d&_^~d&R,V=v&I^~v&k,Y=nP(z,M,V,mK[A],Ua[A]),E=oP(Y,q,B,F,gK[A],qa[A]),h=Y|0,y=Ws(n,o,28)^xl(n,o,34)^xl(n,o,39),w=Ys(n,o,28)^Ol(n,o,34)^Ol(n,o,39),S=n&a^n&u^a&u,O=o&s^o&c^s&c;q=R|0,z=k|0,R=_|0,k=I|0,_=d|0,I=v|0,{h:d,l:v}=io(l|0,p|0,E|0,h|0),l=u|0,p=c|0,u=a|0,c=s|0,a=n|0,s=o|0;let C=eP(h,w,O);n=tP(C,E,y,S),o=C|0}({h:n,l:o}=io(this.Ah|0,this.Al|0,n|0,o|0)),{h:a,l:s}=io(this.Bh|0,this.Bl|0,a|0,s|0),{h:u,l:c}=io(this.Ch|0,this.Cl|0,u|0,c|0),{h:l,l:p}=io(this.Dh|0,this.Dl|0,l|0,p|0),{h:d,l:v}=io(this.Eh|0,this.El|0,d|0,v|0),{h:_,l:I}=io(this.Fh|0,this.Fl|0,_|0,I|0),{h:R,l:k}=io(this.Gh|0,this.Gl|0,R|0,k|0),{h:q,l:z}=io(this.Hh|0,this.Hl|0,q|0,z|0),this.set(n,o,a,s,u,c,l,p,d,v,_,I,R,k,q,z)}roundClean(){wi(qa,Ua)}destroy(){this.destroyed=!0,wi(this.buffer),this.set(0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0)}},Xp=class extends yc{constructor(){super(64,dP)}},Jp=class extends yc{constructor(){super(48,hP)}},vK=Uint32Array.from([2352822216,424955298,1944164710,2312950998,502970286,855612546,1738396948,1479516111,258812777,2077511080,2011393907,79989058,1067287976,1780299464,286451373,2446758561]),yK=Uint32Array.from([573645204,4230739756,2673172387,3360449730,596883563,1867755857,2520282905,1497426621,2519219938,2827943907,3193839141,1401305490,721525244,746961066,246885852,2177182882]),Qp=class extends yc{constructor(){super(28,vK)}},eg=class extends yc{constructor(){super(32,yK)}},Fa=An(()=>new Zp,Zs(1)),bK=An(()=>new $p,Zs(4)),_K=An(()=>new Xp,Zs(3)),wK=An(()=>new Jp,Zs(2)),SK=An(()=>new eg,Zs(6)),EK=An(()=>new Qp,Zs(5))});function lr(e,t,r=()=>{}){if(!Array.isArray(e))throw new TypeError(`"${t}" expected array, got type=${typeof e}`);for(let i=0;i<e.length;i++)r(e[i],`${t}[${i}]`);return e}function Tl(e,t=""){if(typeof e!="string"){let r=t&&`"${t}" `;throw new TypeError(r+"expected string, got type="+typeof e)}return e}function ja(e,t="object"){if(e===null||typeof e!="object"||Array.isArray(e))throw new TypeError(t==="object"?"expected valid options object":`"${t}" expected object, got type=${typeof e}`);return e}function $s(e,t){if(typeof e!="function")throw new TypeError(`"${t}" is invalid: expected function, got ${typeof e}`);return e}function ao(e,t=""){if(typeof e!="boolean")throw new TypeError(xK(t)+"expected boolean, got type="+typeof e);return e}function ig(e){if(typeof e=="bigint"){if(!za(e))throw new RangeError("positive bigint expected, got "+e)}else cb(e);return e}function or(e,t=""){if(typeof e!="number"){let r=t&&`"${t}" `;throw new TypeError(r+"expected number, got type="+typeof e)}if(!Number.isSafeInteger(e)){let r=t&&`"${t}" `;throw new RangeError(r+"expected safe integer, got "+e)}}function Pl(e){let t=ig(e).toString(16);return t.length&1?"0"+t:t}function mP(e){if(typeof e!="string")throw new TypeError("hex string expected, got "+typeof e);return e===""?rg:BigInt("0x"+e)}function Hr(e){return mP(Gp(e))}function _c(e){return mP(Gp(ra(no(e)).reverse()))}function ng(e,t){if($o(t),t===0)throw new Error("zero output length is invalid");e=ig(e);let r=t*2,i=e.toString(16);if(i.length>r)throw new RangeError("number is too large");return sb(i.padStart(r,"0"))}function fb(e,t){return ng(e,t).reverse()}function lb(e,t){if(e=Ce(e),t=Ce(t),e.length!==t.length)return!1;let r=0;for(let i=0;i<e.length;i++)r|=e[i]^t[i];return r===0}function ra(e){return Uint8Array.from(Ce(e))}function wc(e){if(typeof e!="string")throw new TypeError("ascii string expected, got "+typeof e);return Uint8Array.from(e,(t,r)=>{let i=t.charCodeAt(0);if(t.length!==1||i>127)throw new RangeError(`string contains non-ASCII character "${e[r]}" with code ${i} at position ${r}`);return i})}function za(e){return typeof e=="bigint"&&rg<=e}function hb(e,t,r){return za(e)&&za(t)&&za(r)&&t<=e&&e<r}function db(e,t,r,i){if(!hb(t,r,i))throw new RangeError("expected valid "+e+": "+r+" <= n < "+i+", got "+t)}function Sc(e){if(e<rg)throw new Error("expected non-negative bigint, got "+e);return e===rg?0:e.toString(2).length}function vP(e,t,r){if($o(e,"hashLen"),$o(t,"qByteLen"),typeof r!="function")throw new TypeError("hmacFn must be a function");let i=R=>new Uint8Array(R),n=Uint8Array.of(),o=Uint8Array.of(0),a=Uint8Array.of(1),s=1e3,u=i(e),c=i(e),l=0,p=()=>{u.fill(1),c.fill(0),l=0},d=(...R)=>r(c,bt(u,...R)),v=(R=n)=>{c=d(o,R),u=d(),R.length!==0&&(c=d(a,R),u=d())},_=()=>{if(l++>=s)throw new Error("drbg: tried max amount of iterations");let R=0,k=[];for(;R<t;){u=d();let q=u.slice();k.push(q),R+=u.length}return bt(...k)};return(R,k)=>{p(),v(R);let q;for(;(q=k(_()))===void 0;)v();return p(),q}}function At(e,t={},r={},i="object"){ja(e,i),ja(t,"fields"),ja(r,"optFields");function n(a,s,u){let c=i==="object"?`param "${String(a)}"`:`"${i}.${String(a)}"`,l=e[a];if(!Object.hasOwn(e,a)&&(u?l!==void 0:s!=="function"))throw new TypeError(`${c} is invalid: expected own property`);if(u&&l===void 0)return;let p=typeof l;if(p!==s||l===null)throw new TypeError(`${c} is invalid: expected ${s}, got ${p}`)}let o=(a,s)=>Object.entries(a).forEach(([u,c])=>n(u,c,s));o(t,!1),o(r,!0)}var Ce,cb,ta,bt,bc,oo,Si,rg,gP,xK,Rl,Ka=Dr(()=>{g();Qo();Ce=(e,t,r)=>no(e,t,r),cb=$o;ta=Gp,bt=(...e)=>cP(...e),bc=e=>sb(e),oo=jp,Si=e=>Il(e),rg=BigInt(0),gP=BigInt(1),xK=e=>e?`"${e}" `:"";Rl=e=>(or(e,"n"),(gP<<BigInt(e))-gP)});function Ei(e,t){if(t<=qr)throw new Error("mod: expected positive modulus, got "+t);let r=e%t;return r>=qr?r:t+r}function xP(e,t,r){if(r<=Tt)throw new Error("pow: expected modulus > 1, got "+r);if(typeof t!="bigint")throw new TypeError("invalid exponent: expected bigint, got "+typeof t);if(t<qr)throw new Error("invalid exponent, negatives unsupported");if(t===qr)return Tt;if(t===Tt)return e;let i=e%r;if(i<qr&&(i+=r),t<TK){let s=Tt;for(;t>qr;)t&Tt&&(s=s*i%r),i=i*i%r,t>>=Tt;return s}let n=[];for(;t>qr;)n.push(Number(t&AK)),t>>=gb;let o=new Array(16);o[0]=Tt,o[1]=i;for(let s=2;s<16;s++)o[s]=o[s-1]*i%r;let a=o[n[n.length-1]];for(let s=n.length-2;s>=0;s--){a=a*a%r,a=a*a%r,a=a*a%r,a=a*a%r;let u=n[s];u!==0&&(a=a*o[u]%r)}return a}function Vi(e,t,r){if(r<=Tt)throw new Error("pow2: expected modulus > 1, got "+r);if(t<qr)throw new Error("pow2: expected non-negative exponent, got "+t);let i=e;for(;t-- >qr;)i*=i,i%=r;return i}function yP(e,t){if(e===qr)throw new Error("invert: expected non-zero number");if(t<=Tt)throw new Error("invert: expected modulus > 1, got "+t);let r=Ei(e,t),i=t,n=qr,o=Tt;for(;r!==qr;){let s=i/r,u=i-r*s,c=n-o*s;i=r,r=u,n=o,o=c}if(i!==Tt)throw new Error("invert: does not exist");return Ei(n,t)}function OP(e,t){if(t<=Tt)throw new Error("invertCt: expected prime modulus > 1, got "+t);let r=Ei(e,t);if(r===qr)throw new Error("invertCt: expected non-zero number");let i=xP(r,t-Va,t);if(Ei(r*i,t)!==Tt)throw new Error("invertCt: does not exist");return i}function mb(e,t,r){let i=e;if(!i.eql(i.sqr(t),r))throw new Error("Cannot find square root")}function vb(e,t){if((e&Tt)===qr)throw new Error(t+": expected odd modulus, got "+e)}function IP(e,t){let r=e,i=(r.ORDER+Tt)/gb,n=r.pow(t,i);return mb(r,n,t),n}function PK(e,t){let r=e,i=(r.ORDER-wP)/SP,n=r.mul(t,Va),o=r.pow(n,i),a=r.mul(t,o),s=r.mul(r.mul(a,Va),o),u=r.mul(a,r.sub(s,r.ONE));return mb(r,u,t),u}function RK(e){let t=xc(e),r=AP(e),i=r(t,t.neg(t.ONE)),n=r(t,i),o=r(t,t.neg(i)),a=(e+OK)/EP;return((s,u)=>{let c=s,l=c.pow(u,a),p=c.mul(l,i),d=c.mul(l,n),v=c.mul(l,o),_=c.eql(c.sqr(p),u),I=c.eql(c.sqr(d),u);l=c.cmov(l,p,_),p=c.cmov(v,d,I);let R=c.eql(c.sqr(p),u),k=c.cmov(l,p,R);return mb(c,k,u),k})}function AP(e){if(e<_P)throw new Error("sqrt is not defined for small field");vb(e,"tonelliShanks");let t=e-Tt,r=0;for(;t%Va===qr;)t/=Va,r++;let i=Va,n=xc(e);for(;pb(n,i)===1;)if(i++>1e3)throw new Error("Cannot find square root: probably non-prime P");if(r===1)return IP;let o=n.pow(i,t),a=(t+Tt)/Va;return function(u,c){let l=u;if(l.is0(c))return c;if(pb(l,c)!==1)throw new Error("Cannot find square root");let p=r,d=l.mul(l.ONE,o),v=l.pow(c,t),_=l.pow(c,a);for(;!l.eql(v,l.ONE);){if(l.is0(v))throw new Error("Cannot find square root: probably non-prime P");let I=1,R=l.sqr(v);for(;!l.eql(R,l.ONE);)if(I++,R=l.sqr(R),I===p)throw new Error("Cannot find square root");let k=Tt<<BigInt(p-I-1),q=l.pow(d,k);p=I,d=l.sqr(q),v=l.mul(v,d),_=l.mul(_,q)}return _}}function kK(e){return vb(e,"Fp.sqrt"),e%gb===_P?IP:e%SP===wP?PK:e%EP===IK?RK(e):AP(e)}function sn(e){if(ja(e,"field"),typeof e.ORDER!="bigint")throw new TypeError('param "ORDER" is invalid: expected bigint, got '+typeof e.ORDER);or(e.BYTES,"BYTES"),or(e.BITS,"BITS");for(let t of BK)$s(e[t],"field."+t);if(e.BYTES<1||e.BITS<1)throw new Error("invalid field: expected BYTES/BITS > 0");if(e.ORDER<=Tt)throw new Error("invalid field: expected ORDER > 1, got "+e.ORDER);return e}function Ec(e,t,r=!1){sn(e),lr(t,"nums"),ao(r,"passZero");let i=e,n=new Array(t.length).fill(r?i.ZERO:void 0),o=t.reduce((s,u,c)=>i.is0(u)?s:(n[c]=s,i.mul(s,u)),i.ONE),a=i.inv(o);return t.reduceRight((s,u,c)=>i.is0(u)?s:(n[c]=i.mul(s,n[c]),i.mul(s,u)),a),n}function pb(e,t){sn(e);let r=e;vb(r.ORDER,"FpLegendre");let i=(r.ORDER-Tt)/Va,n=r.pow(t,i),o=r.eql(n,r.ONE),a=r.eql(n,r.ZERO),s=r.eql(n,r.neg(r.ONE));if(!o&&!a&&!s)throw new Error("invalid Legendre symbol result");return o?1:a?0:-1}function yb(e,t){return pb(e,t)!==-1}function NK(e,t){if(t!==void 0&&cb(t),e<=qr)throw new Error("invalid n length: expected positive n, got "+e);if(t!==void 0&&t<1)throw new Error("invalid n length: expected positive bit length, got "+t);let r=Sc(e);if(t!==void 0&&t<r)throw new Error(`invalid n length: expected nBitLength (${t}) >= bitLen(n) (${r})`);let i=t!==void 0?t:r,n=Math.ceil(i/8);return{nBitLength:i,nByteLength:n}}function xc(e,t={}){return Object.freeze(og.prototype),new og(e,t)}function TP(e){if(typeof e!="bigint")throw new Error("field order must be bigint");if(e<=Tt)throw new Error("field order must be greater than 1");let t=Sc(e-Tt);return Math.ceil(t/8)}function Oc(e){let t=TP(e);return t+Math.ceil(t/2)}function Xs(e,t,r=!1){Ce(e);let i=e.length,n=TP(t),o=Math.max(Oc(t),16);if(i<o||i>1024)throw new Error("expected "+o+"-1024 bytes of input, got "+i);let a=r?_c(e):Hr(e),s=Ei(a,t-Tt)+Tt;return r?fb(s,n):ng(s,n)}var qr,Tt,Va,_P,gb,wP,OK,SP,IK,AK,EP,TK,BK,bP,og,Js=Dr(()=>{g();Ka();qr=BigInt(0),Tt=BigInt(1),Va=BigInt(2),_P=BigInt(3),gb=BigInt(4),wP=BigInt(5),OK=BigInt(7),SP=BigInt(8),IK=BigInt(9),AK=BigInt(15),EP=BigInt(16),TK=BigInt("0x10000000000000000");BK=["create","isValid","is0","neg","inv","sqrt","sqr","eql","add","sub","mul","pow","div","addN","subN","mulN","sqrN"];bP=new WeakMap,og=class{constructor(t,r={}){ee(this,"ORDER");ee(this,"BITS");ee(this,"BYTES");ee(this,"isLE");ee(this,"ZERO",qr);ee(this,"ONE",Tt);ee(this,"_lengths");ee(this,"_mod");if(t<=Tt)throw new Error("invalid field: expected ORDER > 1, got "+t);let i;this.isLE=!1,r!=null&&typeof r=="object"&&(typeof r.BITS=="number"&&(i=r.BITS),typeof r.sqrt=="function"&&Object.defineProperty(this,"sqrt",{value:r.sqrt,enumerable:!0}),typeof r.isLE=="boolean"&&(this.isLE=r.isLE),r.allowedLengths&&(this._lengths=Object.freeze(r.allowedLengths.slice())),typeof r.modFromBytes=="boolean"&&(this._mod=r.modFromBytes));let{nBitLength:n,nByteLength:o}=NK(t,i);if(o>2048)throw new Error("invalid field: expected ORDER of <= 2048 bytes");this.ORDER=t,this.BITS=n,this.BYTES=o,Object.freeze(this)}create(t){return Ei(t,this.ORDER)}isValid(t){if(typeof t!="bigint")throw new TypeError("invalid field element: expected bigint, got "+typeof t);return qr<=t&&t<this.ORDER}is0(t){return t===qr}isValidNot0(t){return!this.is0(t)&&this.isValid(t)}isOdd(t){return(t&Tt)===Tt}neg(t){return Ei(-t,this.ORDER)}eql(t,r){return t===r}sqr(t){return Ei(t*t,this.ORDER)}add(t,r){return Ei(t+r,this.ORDER)}sub(t,r){return Ei(t-r,this.ORDER)}mul(t,r){return Ei(t*r,this.ORDER)}pow(t,r){return xP(t,r,this.ORDER)}div(t,r){return Ei(t*yP(r,this.ORDER),this.ORDER)}sqrN(t){return t*t}addN(t,r){return t+r}subN(t,r){return t-r}mulN(t,r){return t*r}inv(t){return yP(t,this.ORDER)}sqrt(t){let r=bP.get(this);return r||bP.set(this,r=kK(this.ORDER)),r(this,t)}toBytes(t){return this.isLE?fb(t,this.BYTES):ng(t,this.BYTES)}fromBytes(t,r=!1){Ce(t);let{_lengths:i,BYTES:n,isLE:o,ORDER:a,_mod:s}=this;if(i){if(t.length<1||!i.includes(t.length)||t.length>n)throw new Error("Field.fromBytes: expected "+i+" bytes, got "+t.length);let c=new Uint8Array(n);c.set(t,o?0:c.length-t.length),t=c}if(t.length!==n)throw new Error("Field.fromBytes: expected "+n+" bytes, got "+t.length);let u=o?_c(t):Hr(t);if(s&&(u=Ei(u,a)),!r&&!this.isValid(u))throw new Error("invalid field element: outside of range 0..ORDER");return u}invertBatch(t){return Ec(this,t,!0)}cmov(t,r,i){return ao(i,"condition"),i?r:t}}});function Ga(e){let t=e;if(typeof t!="function")throw new TypeError('"Point" expected constructor, got type='+typeof e);$s(t.fromAffine,"Point.fromAffine"),$s(t.fromBytes,"Point.fromBytes"),$s(t.fromHex,"Point.fromHex"),ja(t.BASE,"Point.BASE"),ja(t.ZERO,"Point.ZERO"),sn(t.Fp),sn(t.Fn)}function BP(e,t){Ga(e),NP(t,e);let r=Ec(e.Fp,t.map(i=>i.Z));return t.map((i,n)=>e.fromAffine(i.toAffine(r[n])))}function MK(e,t,r=1){if(!Number.isSafeInteger(e)||e<r||e>t)throw new Error("invalid window size, expected ["+r+".."+t+"], got W="+e)}function DK(e,t){let r=e*(4*t+128);if(r>RP)throw new Error("invalid window size: table would need ~"+Math.ceil(r/2**20)+" MiB, max "+RP/2**20+" MiB")}function Sb(e,t){if(e!==void 0){$s(e,"randomBytes");try{let r=e(t);if(!oo(r)||r.length!==t)return}catch{return}return e}}function NP(e,t){lr(e,"points"),e.forEach((r,i)=>{if(!(r instanceof t))throw new Error("invalid point at index "+i)})}function HK(e,t,r){if(!Array.isArray(e))throw new Error("array of scalars expected");e.forEach((i,n)=>{if(!(r===void 0?t.isValid(i):za(i)&&i<r))throw new Error("invalid scalar at index "+n)})}function _b(e){return CP.get(e)||1}function qK(e,t){let r=e.double(),i=[e];for(let n=1;n<t;n++)i.push(i[n-1].add(r));return i}function UK(e,t){let r=2**t,i=r/2,n=BigInt(r-1),o=[];for(;e>wb;){let a=0;e&kl&&(a=Number(e&n),a>=i&&(a-=r),e-=BigInt(a)),o.push(a),e>>=kl}return o}function FK(e,t,r){let i=2**t,n=i/2,o=BigInt(i-1),a=BigInt(t),s=[];for(let u=0;u<r;u++){let c=Number(e&o);e>>=a,c>n&&(c-=i,e+=kl),s.push(c)}if(e!==wb)throw new Error("invalid wnaf");return s}function jK(e,t,r){let i=0;for(let o of r)i=Math.max(i,o.length);let n=e;for(let o=i-1;o>=0;o--){o!==i-1&&(n=n.double());for(let a=0;a<r.length;a++){let s=r[a][o];if(s){let u=t[a][Math.abs(s)-1>>1];n=n.add(s<0?u.negate():u)}}}return n}function Ic(e,t,r,i=!1){if(Ga(e),NP(t,e),ao(i,"allowOversized"),HK(r,e.Fn,i?e.Fn.ORDER**CK:void 0),t.length!==r.length)throw new Error("arrays of points and scalars must have equal length");let n=t.map(a=>qK(a,4)),o=r.map(a=>UK(a,4));return jK(e.ZERO,n,o)}function kP(e,t,r){if(t){if(t.ORDER!==e)throw new Error("Field.ORDER must match order: Fp == p, Fn == n");return sn(t),t}else return xc(e,{isLE:r})}function LP(e,t,r={},i){if(e!=="weierstrass"&&e!=="edwards")throw new Error('expected curve type "weierstrass" or "edwards"');if(i===void 0&&(i=e==="edwards"),!t||typeof t!="object")throw new Error(`expected valid ${e} CURVE object`);At(r);for(let u of["p","n","h"]){let c=t[u];if(!(za(c)&&c!==wb))throw new Error(`CURVE.${u} must be positive bigint`)}let n=kP(t.p,r.Fp,i),o=kP(t.n,r.Fn,i),s=["Gx","Gy","a",e==="weierstrass"?"b":"d"];for(let u of s)if(!n.isValid(t[u]))throw new Error(`CURVE.${u} must be valid field element of CURVE.Fp`);return t=Object.freeze(Object.assign({},t)),{CURVE:t,Fp:n,Fn:o}}function sg(e,t){return function(i){let n=e(i);return{secretKey:n,publicKey:t(n)}}}var wb,kl,CK,bb,PP,LK,RP,CP,ag,ug=Dr(()=>{g();Ka();Js();wb=BigInt(0),kl=BigInt(1),CK=BigInt(4),bb=16,PP=128,LK=5,RP=2**31;CP=new WeakMap;ag=class{constructor(t,r){ee(this,"Point");ee(this,"BASE");ee(this,"ZERO");ee(this,"randomBytes");ee(this,"wnafPrecomputes",new WeakMap);ee(this,"baseCanBeBlinded");ee(this,"bits");Ga(t),this.randomBytes=Sb(r,bb),this.Point=t,this.BASE=t.BASE,this.ZERO=t.ZERO,this.bits=t.Fn.BITS}buildWnafTable(t,r,i){let n=Math.ceil(i/r)+1,o=2**(r-1),a=[],s=t;for(let u=0;u<n;u++){let c=s;for(let l=0;l<o;l++)a.push(c),c=c.add(s);s=a[a.length-1].double()}return{W:r,bits:i,windows:n,comp:a}}wnafCachedCT(t,r){let{W:i,windows:n,comp:o}=t,a=2**(i-1),s=FK(r,i,n),u=this.ZERO,c=this.BASE;for(let l=0;l<n;l++){let p=s[l],d=l*a,v=Math.abs(p)-1,_=o[d];for(let R=1;R<a;R++)_=R===v?o[d+R]:_;let I=_.negate();p===0?c=c.add(o[d]):u=u.add(p<0?I:_)}return{p:u,f:c}}getWnafPrecomputes(t,r,i,n){let o=this.wnafPrecomputes.get(r),a=o?.find(s=>s.W===t&&s.bits===i);return a||(a=this.buildWnafTable(r,t,i),typeof n=="function"&&(a={...a,comp:n(a.comp)}),o||(o=[],this.wnafPrecomputes.set(r,o)),o.push(a)),a}assertPoint(t){if(!(t instanceof this.Point))throw new TypeError('"point" expected Point instance, got type='+typeof t)}validateMulInput(t,r){if(this.assertPoint(t),!hb(r,kl,this.Point.Fn.ORDER))throw new Error("invalid scalar")}runCT(t,r,i,n){let o=_b(t);return o===1?this.fixedWindowCT(t,r,i):this.wnafCachedCT(this.getWnafPrecomputes(o,t,i,n),r)}mulCT(t,r,i){return this.validateMulInput(t,r),this.runCT(t,r,this.bits,i)}mulCTBlinded(t,r,i){if(this.validateMulInput(t,r),this.randomBytes===void 0)throw new Error("randomBytes is required for scalar blinding");let n=this.Point.Fn.BITS+PP,o=this.randomBytes(bb);if(!oo(o)||o.length!==bb)throw new Error("randomBytes returned invalid byte array");o[0]=o[0]&63|128;let a=r+Hr(o)*this.Point.Fn.ORDER;return this.runCT(t,a,n,i)}fixedWindowCT(t,r,i){let n=LK,o=1<<n,a=Rl(n),s=new Array(o);s[0]=this.ZERO;for(let l=1;l<o;l++)s[l]=s[l-1].add(t);let u=Math.ceil(i/n),c=this.ZERO;for(let l=u-1;l>=0;l--){if(l!==u-1)for(let v=0;v<n;v++)c=c.double();let p=Number(r>>BigInt(l*n)&a),d=s[0];for(let v=1;v<o;v++)d=v===p?s[v]:d;c=c.add(d)}return{p:c,f:c}}shouldBlind(t,r){return this.randomBytes===void 0?!1:r===kl?!0:t!==this.BASE?!1:(this.baseCanBeBlinded===void 0&&(this.baseCanBeBlinded=this.mulUnsafe(this.BASE,this.Point.Fn.ORDER).is0()),this.baseCanBeBlinded)}mulSecret(t,r,i,n){return this.shouldBlind(t,i)?this.mulCTBlinded(t,r,n):this.mulCT(t,r,n)}mulUnsafe(t,r,i){if(this.assertPoint(t),!za(r))throw new Error("invalid scalar");let n=_b(t);if(n===1||r>=this.Point.Fn.ORDER)return Ic(this.Point,[t],[r],!0);let o=this.getWnafPrecomputes(n,t,this.bits,i);return this.wnafCachedCT(o,r).p}setWindowSize(t,r){this.assertPoint(t),MK(r,this.bits);let i=Math.ceil((this.bits+PP)/r)+1;DK(i*2**(r-1),this.Point.Fp.BYTES),CP.set(t,r),this.wnafPrecomputes.delete(t)}hasWindowSize(t){return _b(t)!==1}}});function Eb(e,t="n"){if(typeof e!="number")throw new TypeError(`wrong u32 integer "${t}": expected number, got type=${typeof e}`);if(!Number.isSafeInteger(e)||e<0||e>4294967295)throw new RangeError(`wrong u32 integer "${t}": expected 0..4294967295, got ${e}`);return e}function MP(e){return Eb(e,"x"),(e&e-1)===0&&e!==0}function zK(e){if(Eb(e),e<=1)return 1;if(e>2147483648)throw new Error("nextPowerOfTwo overflow: result does not fit u32");return 1<<cg(e-1)+1>>>0}function cg(e){return Eb(e),31-Math.clz32(e)}function DP(e,t,r,i,n){sn(e);let o=e,a=r||((p,d)=>new Array(p).fill(d??o.ZERO)),s=p=>{if(Array.isArray(p))return!0;if(!ArrayBuffer.isView(p))return!1;let d=p;return typeof d.length=="number"&&typeof d.slice=="function"&&typeof d[Symbol.iterator]=="function"},u=(p,d)=>{if(!s(d))throw new TypeError(`"${p}" expected polynomial, got type=${typeof d}`)},c=(p,d)=>{u("a",p);let v=p.length;if(d!==void 0&&(u("b",d),d.length!==v))throw new Error(`poly: mismatched lengths ${v} vs ${d.length}`);if(n!==void 0&&v!==n)throw new Error(`poly: expected fixed length ${n}, got ${v}`);return v};function l(p,d,v=!1,_){if(!MP(d))throw new Error("poly.lagrange: expected power of two length, got "+d);let I=_||(v?t.brp(cg(d)):t.roots(cg(d)));for(let R=0;R<d;R++)if(o.eql(p,I[R]))return R;return-1}return{roots:t,create:a,length:n,extend:(p,d)=>{c(p);let v=a(d,o.ZERO);for(let _=0;_<Math.min(p.length,d);_++)v[_]=p[_];return v},degree:p=>{c(p);for(let d=p.length-1;d>=0;d--)if(!o.is0(p[d]))return d;return-1},add:(p,d)=>{let v=c(p,d),_=a(v);for(let I=0;I<v;I++)_[I]=o.add(p[I],d[I]);return _},sub:(p,d)=>{let v=c(p,d),_=a(v);for(let I=0;I<v;I++)_[I]=o.sub(p[I],d[I]);return _},dot:(p,d)=>{let v=c(p,d),_=a(v);for(let I=0;I<v;I++)_[I]=o.mul(p[I],d[I]);return _},mul:(p,d)=>{if(s(d)){let v=c(p,d);if(i){let _=i.direct(p,!1,!0),I=i.direct(d,!1,!0);for(let R=0;R<_.length;R++)_[R]=o.mul(_[R],I[R]);return i.inverse(_,!0,!1)}else{let _=a(v);for(let I=0;I<v;I++)for(let R=0;R<v;R++){let k=(I+R)%v;_[k]=o.add(_[k],o.mul(p[I],d[R]))}return _}}else{let v=a(c(p));for(let _=0;_<v.length;_++)v[_]=o.mul(p[_],d);return v}},convolve(p,d){u("a",p),u("b",d);let v=zK(p.length+d.length-1);return this.mul(this.extend(p,v),this.extend(d,v))},shift(p,d){u("p",p);let v=a(p.length);if(n!==void 0&&p.length!==n)throw new Error(`poly: expected fixed length ${n}, got ${p.length}`);if(!p.length)return v;v[0]=p[0];for(let _=1,I=o.ONE;_<p.length;_++)I=o.mul(I,d),v[_]=o.mul(p[_],I);return v},clone:p=>{c(p);let d=a(p.length);for(let v=0;v<p.length;v++)d[v]=p[v];return d},eval:(p,d)=>{c(p,d);let v=o.ZERO;for(let _=0;_<p.length;_++)v=o.add(v,o.mul(p[_],d[_]));return v},monomial:{basis:(p,d)=>{let v=a(d),_=o.ONE;for(let I=0;I<d;I++)v[I]=_,_=o.mul(_,p);return v},eval:(p,d)=>{c(p);let v=o.ZERO;for(let _=p.length-1;_>=0;_--)v=o.add(o.mul(v,d),p[_]);return v}},lagrange:{basis:(p,d,v=!1,_)=>{if(!MP(d))throw new Error("poly.lagrange: expected power of two length, got "+d);let I=cg(d),R=_||(v?t.brp(I):t.roots(I)),k=a(d),q=l(p,d,v,_);if(q!==-1)return k[q]=o.ONE,k;let z=o.pow(p,BigInt(d)),A=o.mul(o.sub(z,o.ONE),o.inv(BigInt(d))),B=a(d);for(let F=0;F<d;F++)B[F]=o.sub(p,R[F]);let M=o.invertBatch(B);for(let F=0;F<d;F++)k[F]=o.mul(A,o.mul(R[F],M[F]));return k},eval(p,d,v=!1){c(p);let _=l(d,p.length,v);if(_!==-1)return p[_];let I=this.basis(d,p.length,v),R=o.ZERO;for(let k=0;k<p.length;k++)o.is0(p[k])||(R=o.add(R,o.mul(p[k],I[k])));return R}},vanishing(p){if(u("roots",p),n!==void 0&&p.length!==n)throw new Error(`poly: expected fixed length ${n}, got ${p.length}`);let d=a(p.length+1,o.ZERO);d[0]=o.ONE;for(let v of p){let _=o.neg(v);for(let I=d.length-1;I>0;I--)d[I]=o.add(o.mul(d[I],_),d[I-1]);d[0]=o.mul(d[0],_)}return d}}}var HP=Dr(()=>{g();Js()});function Qs(e,t){if(or(e),or(t),t<0||t>4)throw new Error("invalid I2OSP length: "+t);if(e<0||e>2**(8*t)-1)throw new Error("invalid I2OSP input: "+e);let r=Array.from({length:t}).fill(0);for(let i=t-1;i>=0;i--)r[i]=e&255,e>>>=8;return new Uint8Array(r)}function VK(e,t){let r=new Uint8Array(e.length);for(let i=0;i<e.length;i++)r[i]=e[i]^t[i];return r}function jP(e){if(!oo(e)&&typeof e!="string")throw new Error("DST must be Uint8Array or ascii string");let t=typeof e=="string"?wc(e):e;if(t.length===0)throw new Error("DST must be non-empty");return t}function GK(e,t,r,i){if(Ce(e),or(r),typeof i!="function")throw new Error("expand_message_xmd: expected hash function");or(i.outputLen,"hash.outputLen"),or(i.blockLen,"hash.blockLen"),t=jP(t),t.length>255&&(t=i(bt(wc("H2C-OVERSIZE-DST-"),t)));let{outputLen:n,blockLen:o}=i,a=Math.ceil(r/n);if(r>65535||a>255)throw new Error("expand_message_xmd: invalid lenInBytes");let s=bt(t,Qs(t.length,1)),u=new Uint8Array(o),c=Qs(r,2),l=new Array(a),p=i(bt(u,e,c,Qs(0,1),s));l[0]=i(bt(p,Qs(1,1),s));for(let v=1;v<a;v++){let _=[VK(p,l[v-1]),Qs(v+1,1),s];l[v]=i(bt(..._))}return bt(...l).slice(0,r)}function WK(e,t,r,i,n){if(Ce(e),or(r),or(i,"k"),i<0)throw new Error("expand_message_xof: invalid k");if(typeof n!="function")throw new Error("expand_message_xof: expected XOF function");if(typeof n.create!="function")throw new Error("expand_message_xof: expected XOF create");if(t=jP(t),r<0||r>65535)throw new Error("expand_message_xof: invalid lenInBytes");if(t.length>255){let o=Math.ceil(2*i/8);t=n.create({dkLen:o}).update(wc("H2C-OVERSIZE-DST-")).update(t).digest()}if(t.length>255)throw new Error("expand_message_xof: invalid DST");return n.create({dkLen:r}).update(e).update(Qs(r,2)).update(t).update(Qs(t.length,1)).digest()}function xb(e,t,r){At(r,{p:"bigint",m:"number",k:"number",hash:"function"});let{p:i,k:n,m:o,hash:a,expand:s,DST:u}=r;if(or(a.outputLen,"valid hash"),Ce(e),or(t),or(o,"m"),or(n,"k"),i<=BigInt(1))throw new Error("hash_to_field: expected valid field characteristic");if(t<1)throw new Error("hash_to_field: expected count >= 1");if(o<1)throw new Error("hash_to_field: expected m >= 1");if(n<0)throw new Error("hash_to_field: invalid k");let c=i.toString(2).length,l=Math.ceil((c+n)/8),p=t*o*l,d;if(s==="xmd")d=GK(e,u,p,a);else if(s==="xof")d=WK(e,u,p,n,a);else if(s==="_internal_pass")d=e;else throw new Error('expand must be "xmd" or "xof"');let v=new Array(t);for(let _=0;_<t;_++){let I=new Array(o);for(let R=0;R<o;R++){let k=l*(R+_*o),q=d.subarray(k,k+l);I[R]=Ei(KK(q),i)}v[_]=I}return v}function zP(e,t){sn(e),lr(t,"map");let r=t.map((i,n)=>{if(lr(i,"map["+n+"]"),i.length<1)throw new Error("isogenyMap: expected non-empty coefficients");return Array.from(i).reverse()});return(i,n)=>{let[o,a,s,u]=r.map(d=>d.reduce((v,_)=>e.add(e.mul(v,i),_))),c=e.is0(a)||e.is0(u),[l,p]=Ec(e,[a,u],!0);return i=e.mul(o,l),n=e.mul(n,e.mul(s,p)),c?{x:e.ZERO,y:e.ZERO}:{x:i,y:n}}}function KP(e,t,r){if(typeof t!="function")throw new Error("mapToCurve() must be defined");At(r);let i=u=>Object.freeze({...u,DST:oo(u.DST)?ra(u.DST):u.DST,...u.encodeDST===void 0?{}:{encodeDST:oo(u.encodeDST)?ra(u.encodeDST):u.encodeDST}}),n=i(r),o=u=>u&&u.DST!==void 0?{DST:u.DST}:void 0;function a(u){return e.fromAffine(t(u))}function s(u){let c=u.clearCofactor();return c.equals(e.ZERO)?e.ZERO:(c.assertValidity(),c)}return Object.freeze({get defaults(){return i(n)},Point:e,hashToCurve(u,c){let l=Object.assign({},n,o(c)),p=xb(u,2,l),d=a(p[0]),v=a(p[1]);return s(d.add(v))},encodeToCurve(u,c){let l=n.encodeDST===void 0?{}:{DST:n.encodeDST},p=Object.assign({},n,l,o(c)),d=xb(u,1,p),v=a(d[0]);return s(v)},mapToCurve(u){if(n.m===1){if(typeof u!="bigint")throw new Error("expected bigint (m=1)");return s(a([u]))}if(!Array.isArray(u))throw new Error("expected array of bigints");if(u.length!==n.m)throw new Error(`expected array of ${n.m} bigints`);for(let c of u)if(typeof c!="bigint")throw new Error("expected array of bigints");return s(a(u))},hashToScalar(u,c){let l=e.Fn.ORDER,p=Object.assign({},n,{DST:YK},o(c),{p:l,m:1});return xb(u,1,p)[0][0]}})}function ZK(e,t){let r=sn(e),i=r.ORDER,n=qP;for(let I=i-so;I%Wa===qP;I/=Wa)n+=so;let o=n,a=Wa<<o-so-so,s=a*Wa,u=(i-so)/s,c=(u-so)/Wa,l=s-so,p=a,d=r.pow(t,u),v=r.pow(t,(u+so)/Wa),_=(I,R)=>{let k=d,q=r.pow(R,l),z=r.sqr(q);z=r.mul(z,R);let A=r.mul(I,z);A=r.pow(A,c),A=r.mul(A,q),q=r.mul(A,R),z=r.mul(A,I);let B=r.mul(z,q);A=r.pow(B,p);let M=r.eql(A,r.ONE);q=r.mul(z,v),A=r.mul(B,k),z=r.cmov(q,z,M),B=r.cmov(A,B,M);for(let F=o;F>so;F--){let V=F-Wa;V=Wa<<V-so;let Y=r.pow(B,V),E=r.eql(Y,r.ONE);q=r.mul(z,k),k=r.mul(k,k),Y=r.mul(B,k),z=r.cmov(q,z,E),B=r.cmov(Y,B,E)}return{isValid:!r.is0(R)&&(M||r.is0(I)),value:z}};if(r.ORDER%FP===UP){let I=(r.ORDER-UP)/FP,R=r.sqrt(r.neg(t));_=(k,q)=>{let z=r.sqr(q),A=r.mul(k,q);z=r.mul(z,A);let B=r.pow(z,I);B=r.mul(B,A);let M=r.mul(B,R),F=r.mul(r.sqr(B),q),V=r.eql(F,k),Y=r.cmov(M,B,V);return{isValid:!r.is0(q)&&V,value:Y}}}return _}function VP(e,t){let r=sn(e);At(t,{},{},"opts");let{A:i,B:n,Z:o}=t;if(!r.isValidNot0(i)||!r.isValidNot0(n)||!r.isValid(o))throw new Error("mapToCurveSimpleSWU: invalid opts");if(r.eql(o,r.neg(r.ONE))||yb(r,o))throw new Error("mapToCurveSimpleSWU: invalid opts");let a=r.mul(n,r.inv(r.mul(o,i))),s=r.add(r.add(r.mul(r.sqr(a),a),r.mul(i,a)),n);if(!yb(r,s))throw new Error("mapToCurveSimpleSWU: invalid opts");let u=ZK(r,o);if(!r.isOdd)throw new Error("Field does not have .isOdd()");return c=>{let l,p,d,v,_,I,R,k;l=r.sqr(c),l=r.mul(l,o),p=r.sqr(l),p=r.add(p,l),d=r.add(p,r.ONE),d=r.mul(d,n),v=r.cmov(o,r.neg(p),!r.eql(p,r.ZERO)),v=r.mul(v,i),p=r.sqr(d),I=r.sqr(v),_=r.mul(I,i),p=r.add(p,_),p=r.mul(p,d),I=r.mul(I,v),_=r.mul(I,n),p=r.add(p,_),R=r.mul(l,d);let{isValid:q,value:z}=u(p,I);k=r.mul(l,c),k=r.mul(k,z),R=r.cmov(R,d,q),k=r.cmov(k,z,q);let A=r.isOdd(c)===r.isOdd(k);k=r.cmov(r.neg(k),k,A);let B=Ec(r,[v],!0)[0];return R=r.mul(R,B),{x:R,y:k}}}var qP,so,Wa,UP,FP,KK,YK,GP=Dr(()=>{g();Ka();Js();qP=BigInt(0),so=BigInt(1),Wa=BigInt(2),UP=BigInt(3),FP=BigInt(4),KK=Hr;YK="HashToScalar-"});function Ob(e){At(e,{name:"string",hash:"function"},{hashToScalar:"function",validatePoint:"function",parsePublicKey:"function",adjustScalar:"function",adjustPoint:"function",challenge:"function",adjustNonces:"function",adjustSecret:"function",adjustPublic:"function",adjustGroupCommitmentShare:"function",adjustTx:"object",adjustDKG:"function"}),Ga(e.Point);let{Point:t,validatePoint:r,parsePublicKey:i,adjustScalar:n,adjustPoint:o,challenge:a,adjustNonces:s,adjustSecret:u,adjustPublic:c,adjustGroupCommitmentShare:l,adjustDKG:p}=e,d=e.Fn===void 0?t.Fn:e.Fn,v=e.adjustTx===void 0?void 0:{encode:e.adjustTx.encode,decode:e.adjustTx.decode};v&&At(v,{encode:"function",decode:"function"});let _=e.hash,I=e.hashToScalar===void 0?(N,W={DST:new Uint8Array})=>{let X=_(bt(W.DST,N));return d.create(d.isLE?_c(X):Hr(X))}:e.hashToScalar,R=Jo(e.H1!==void 0?e.H1:e.name+"rho"),k=Jo(e.H2!==void 0?e.H2:e.name+"chal"),q=Jo(e.H3!==void 0?e.H3:e.name+"nonce"),z=Jo(e.H4!==void 0?e.H4:e.name+"msg"),A=Jo(e.H5!==void 0?e.H5:e.name+"com"),B=Jo(e.HDKG!==void 0?e.HDKG:e.name+"dkg"),M=Jo(e.HID!==void 0?e.HID:e.name+"id"),F=N=>I(N,{DST:R}),V=N=>I(N,{DST:k}),Y=N=>I(N,{DST:q}),E=N=>_(bt(z,N)),h=N=>_(bt(A,N)),y=N=>I(N,{DST:B}),w=N=>I(N,{DST:M}),S=(N=Si)=>{if(typeof N!="function")throw new TypeError('"rng" expected function, got type='+typeof N);let W=Xs(N(Oc(d.ORDER)),d.ORDER,d.isLE);return d.isLE?_c(W):Hr(W)},O=N=>N.toBytes(),C=N=>{if(N.assertValidity(),N.is0())throw new Error("invalid point: identity");if(!N.isTorsionFree())throw new Error("bad point: not in prime-order subgroup");return r&&r(N),N},D=N=>C(t.fromBytes(N)),P=(N,W)=>({identifier:N,hiding:O(t.BASE.multiply(d.fromBytes(W.hiding))),binding:O(t.BASE.multiply(d.fromBytes(W.binding)))}),m=o===void 0?N=>N:o,x=N=>{if(!d.isValid(N)||d.is0(N))throw new Error("Invalid identifier "+N);return N},K=N=>ta(d.toBytes(x(N))),U=(N,W="identifier")=>{Tl(N,W);let X=x(d.fromBytes(bc(N)));if(K(X)!==N)throw new Error("expected canonical identifier hex");return X},G=N=>({identifier:K(U(N.identifier)),commitment:N.commitment.map(W=>ra(W)),proofOfKnowledge:ra(N.proofOfKnowledge)}),te=N=>{let W=N.map(G);return W.sort((X,ie)=>{let pe=U(X.identifier),se=U(ie.identifier);return pe<se?-1:pe>se?1:0}),W},ae=(N,W)=>{if(N.length!==W.length)return!1;for(let X=0;X<N.length;X++){let ie=N[X],pe=W[X];if(ie.identifier!==pe.identifier||ie.commitment.length!==pe.commitment.length)return!1;for(let se=0;se<ie.commitment.length;se++)if(!lb(ie.commitment[se],pe.commitment[se]))return!1;if(!lb(ie.proofOfKnowledge,pe.proofOfKnowledge))return!1}return!0},oe={encode:(N,W)=>{let X=bt(O(N),d.toBytes(W));return v&&(X=v.encode(X)),X},decode:N=>{v&&(N=v.decode(N));let W=N.subarray(0,-d.BYTES),X=D(W);if(O(X).length!==W.length)throw new Error("invalid signature encoding");let ie=d.fromBytes(N.subarray(-d.BYTES));return{R:X,z:ie}}},le=(N=Si)=>{let W=S(N);n&&(W=n(W));let X=t.BASE.multiply(W);return{scalar:W,point:X}},he="roots are unavailable in FROST polynomial mode",ve={info:{G:d.ZERO,oddFactor:d.ZERO,powerOfTwo:0},roots(){throw new Error(he)},brp(){throw new Error(he)},inverse(){throw new Error(he)},omega(){throw new Error(he)},clear(){}},je=DP(d,ve),be=(N,W)=>Ic(t,N,W),_e=(N,W)=>{if(!W.length)throw new Error("empty coefficients");return je.monomial.eval(W,N)},We=(N,W)=>{let X="invalid parameters";if(!N.some(me=>d.eql(me,W)))throw new Error(X);let ie=new Set(N);if(ie.size!==N.length)throw new Error(X);if(!ie.has(W))throw new Error(X);let pe=d.ONE,se=d.ONE;for(let me of N)d.eql(me,W)||(pe=d.mul(pe,me),se=d.mul(se,d.sub(me,W)));return d.div(pe,se)},Pe=(N,W)=>{let X=je.monomial.basis(N,W.length);return be(W,X)},Me=(N,W,X,ie=Si)=>{if(uo(N),W!==void 0&&Ce(W,d.BYTES,"secret"),X!==void 0&&lr(X,"coeffs"),typeof ie!="function")throw new TypeError('"rng" expected function, got type='+typeof ie);let pe=W===void 0?S(ie):d.fromBytes(W);if(!X){X=[];for(let ge=0;ge<N.min-1;ge++)X.push(S(ie))}if(X.length!==N.min-1)throw new Error("wrong coefficients length");let se=[pe,...X],me=se.map(ge=>t.BASE.multiply(ge));return{coefficients:se,commitment:me,secret:pe}},rt={challenge:(N,W,X)=>y(bt(d.toBytes(N),O(W),O(X))),compute(N,W,X,ie=Si){if(W.length<1)throw new Error("coefficients should have at least one element");let{point:pe,scalar:se}=le(ie),me=X[0],ge=this.challenge(N,me,pe),ke=d.add(se,d.mul(W[0],ge));return oe.encode(pe,ke)},validate(N,W,X){if(W.length<1)throw new Error("commitment should have at least one element");let{R:ie,z:pe}=oe.decode(X),se=D(W[0]),me=this.challenge(N,se,ie);if(!ie.equals(t.BASE.multiplyUnsafe(pe).subtract(se.multiplyUnsafe(me))))throw new Error("invalid proof of knowledge")}},Be={challenge:(N,W,X)=>a?a(N,W,X):V(bt(O(N),O(W),X)),sign(N,W,X=Si){let{point:ie,scalar:pe}=le(X),se=t.BASE.multiply(W),me=this.challenge(ie,se,N),ge=d.add(pe,d.mul(me,W));return[ie,ge]},verify(N,W,X,ie){o&&(ie=o(ie)),o&&(W=o(W));let pe=this.challenge(W,ie,N),se=t.BASE.multiplyUnsafe(X),me=ie.multiplyUnsafe(pe),ge=se.subtract(me).subtract(W);return ge.clearCofactor&&(ge=ge.clearCofactor()),t.ZERO.equals(ge)}},vt=(N,W,X)=>{if(!t.BASE.multiply(X).equals(Pe(N,W)))throw new Error("invalid secret share")},ui={fromNumber(N){if(!Number.isSafeInteger(N))throw new Error("expected safe interger");return K(BigInt(N))},derive(N){return Tl(N,"s"),K(w(Jo(N)))}},Et=(N,W=Si)=>Y(bt(W(32),d.toBytes(N))),_t=(N,W,X)=>{let ie=W.map(Mt=>[Mt.identifier,U(Mt.identifier),D(Mt.hiding),D(Mt.binding)]);ie.sort((Mt,$e)=>Mt[1]<$e[1]?-1:Mt[1]>$e[1]?1:0);let pe=[];for(let[Mt,$e,Ee,Jt]of ie)pe.push(d.toBytes($e),O(Ee),O(Jt));let se=h(bt(...pe)),me=bt(O(N),E(X),se),ge={};for(let[Mt,$e]of ie)ge[Mt]=F(bt(me,d.toBytes($e)));let ke=t.ZERO,Oe=[],Ye=[];for(let[Mt,$e,Ee,Jt]of ie){if(t.ZERO.equals(Ee)||t.ZERO.equals(Jt))throw new Error("infinity commitment");ke=ke.add(Ee),Oe.push(Jt),Ye.push(ge[Mt])}let Ze=ke.add(be(Oe,Ye));return{identifiers:ie.map(Mt=>Mt[1]),groupCommitment:Ze,bindingFactors:ge}},Yn=(N,W,X,ie)=>{let pe=m(D(N)),se=U(ie),{identifiers:me,groupCommitment:ge,bindingFactors:ke}=_t(pe,W,X),Oe=ke[ie],Ye=We(me,se),Ze=Be.challenge(ge,pe,X);return{lambda:Ye,challenge:Ze,bindingFactor:Oe,groupCommitment:ge}};Object.freeze(ui);let Lt={Identifier:ui,DKG:Object.freeze({round1:(N,W,X,ie=Si)=>{let pe=U(N,"id");uo(W);let{coefficients:se,commitment:me}=Me(W,X,void 0,ie),ge=rt.compute(pe,se,me,ie),ke=me.map(O),Oe={identifier:K(pe),commitment:ke,proofOfKnowledge:ge},Ye={identifier:pe,coefficients:se,commitment:me.map(O),signers:{min:W.min,max:W.max},step:1};return{public:Oe,secret:Ye}},round2:(N,W)=>{if(At(N,{identifier:"bigint",commitment:"object",signers:"object"},{coefficients:"object",round1Cache:"object",round2Cache:"object",step:"number"},"secret"),uo(N.signers,"secret.signers"),lr(W,"others"),W.length!==N.signers.max-1)throw new Error("wrong number of round1 packages");if(!N.coefficients||N.step===3)throw new Error("round3 package used in round2");let X=te(W);if(N.round2Cache!==void 0){if(N.round1Cache===void 0||!ae(N.round1Cache,X))throw new Error("round1 packages do not match authenticated transcript");return N.round2Cache}let ie={};for(let pe of X){if(pe.commitment.length!==N.signers.min)throw new Error("wrong number of commitments");let se=U(pe.identifier);if(se===N.identifier)throw new Error("duplicate id="+K(se));rt.validate(se,pe.commitment,pe.proofOfKnowledge);for(let ge of pe.commitment)D(ge);if(ie[pe.identifier])throw new Error("Duplicate id="+se);let me=d.toBytes(_e(se,N.coefficients));ie[pe.identifier]={identifier:K(N.identifier),signingShare:me}}return N.round1Cache=X,N.round2Cache=ie,N.step=2,ie},round3:(N,W,X)=>{if(At(N,{identifier:"bigint",commitment:"object",signers:"object"},{coefficients:"object",round1Cache:"object",round2Cache:"object",step:"number"},"secret"),uo(N.signers,"secret.signers"),lr(W,"round1"),lr(X,"round2"),W.length!==N.signers.max-1)throw new Error("wrong length of round1 packages");if(!N.coefficients||N.step!==2||!N.round1Cache)throw new Error("round2 package used in round3");let ie=te(W),pe=N.round1Cache;if(!ae(pe,ie))throw new Error("round1 packages do not match authenticated transcript");if(X.length!==pe.length)throw new Error("wrong length of round2 packages");let se={};for(let Ee of pe){if(!Ee.identifier||!Ee.commitment)throw new Error("wrong round1 share");se[Ee.identifier]={...Ee}}for(let Ee of X){if(!Ee.identifier||!Ee.signingShare)throw new Error("wrong round2 share");if(!se[Ee.identifier])throw new Error("round1 share for "+Ee.identifier+" is missing");se[Ee.identifier].signingShare=Ee.signingShare}if(Object.keys(se).length!==pe.length)throw new Error("mismatch identifiers between rounds");let me=d.ZERO;if(N.commitment.length!==N.signers.min)throw new Error("wrong commitments length");let ge=N.commitment.map(D),ke=_e(N.identifier,N.coefficients);vt(N.identifier,ge,ke);let Oe=ge.map(O),Ye={[K(N.identifier)]:Oe};for(let Ee in se){let Jt=se[Ee];if(!Jt.signingShare||!Jt.commitment)throw new Error("mismatch identifiers");let wt=U(Ee),Ft=d.fromBytes(Jt.signingShare),Hu=Jt.commitment.map(D);vt(N.identifier,Hu,Ft),me=d.add(me,Ft);let Dt=K(wt);if(Ye[Dt])throw new Error("duplicated id="+Dt);Ye[Dt]=Jt.commitment}me=d.add(me,ke);let Ze=new Array(N.signers.min).fill(t.ZERO);for(let Ee in Ye){let Jt=Ye[Ee];if(Jt.length!==N.signers.min)throw new Error("wrong commitments length");for(let wt=0;wt<Jt.length;wt++)Ze[wt]=Ze[wt].add(D(Jt[wt]))}let Pt=Ze.map(O),Mt={};for(let Ee in Ye)Mt[Ee]=O(Pe(U(Ee),Ze));let $e={public:{signers:{min:N.signers.min,max:N.signers.max},commitments:Pt,verifyingShares:Object.fromEntries(Object.entries(Mt).map(([Ee,Jt])=>[Ee,Jt.slice()]))},secret:{identifier:K(N.identifier),signingShare:d.toBytes(me)}};p&&($e=p($e));for(let Ee=0;Ee<N.coefficients.length;Ee++)N.coefficients[Ee]-=N.coefficients[Ee];return delete N.coefficients,delete N.round1Cache,delete N.round2Cache,N.step=3,$e},clean(N){if(At(N,{identifier:"bigint",commitment:"object",signers:"object"},{coefficients:"object",round1Cache:"object",round2Cache:"object",step:"number"},"secret"),N.identifier-=N.identifier,N.coefficients)for(let W=0;W<N.coefficients.length;W++)N.coefficients[W]-=N.coefficients[W];delete N.round1Cache,delete N.round2Cache,N.step=3}}),trustedDealer(N,W,X,ie=Si){if(uo(N),W===void 0){W=[];for(let Oe=1;Oe<=N.max;Oe++)W.push(ui.fromNumber(Oe))}else if(lr(W,"identifiers"),W.length!==N.max)throw new Error("identifiers should be array of "+N.max);let pe={};for(let Oe of W){let Ye=U(Oe);if(Oe in pe)throw new Error("duplicated id="+Oe);pe[Oe]=Ye}let se=Me(N,X,void 0,ie),me=se.commitment.map(O),ge={},ke={};for(let Oe of W){let Ye=_e(pe[Oe],se.coefficients);ke[Oe]=O(t.BASE.multiply(Ye)),ge[Oe]={identifier:Oe,signingShare:d.toBytes(Ye)}}return{public:{signers:{min:N.min,max:N.max},commitments:me,verifyingShares:ke},secretShares:ge}},validateSecret(N,W){At(N,{identifier:"string",signingShare:"object"},{},"secret"),Ce(N.signingShare,d.BYTES,"secret.signingShare"),At(W,{signers:"object",commitments:"object",verifyingShares:"object"},{},"pub"),uo(W.signers,"pub.signers"),lr(W.commitments,"pub.commitments");let X=U(N.identifier),ie=W.commitments.map(D),pe=d.fromBytes(N.signingShare);vt(X,ie,pe)},commit(N,W=Si){if(At(N,{identifier:"string",signingShare:"object"},{},"secret"),Ce(N.signingShare,d.BYTES,"secret.signingShare"),typeof W!="function")throw new TypeError('"rng" expected function, got type='+typeof W);let X=d.fromBytes(N.signingShare),ie=Et(X,W),pe=Et(X,W),se={hiding:d.toBytes(ie),binding:d.toBytes(pe)};return{nonces:se,commitments:P(N.identifier,se)}},signShare(N,W,X,ie,pe){At(N,{identifier:"string",signingShare:"object"},{},"secret"),Ce(N.signingShare,d.BYTES,"secret.signingShare"),At(W,{signers:"object",commitments:"object",verifyingShares:"object"},{},"pub"),uo(W.signers,"pub.signers"),lr(W.commitments,"pub.commitments"),At(X,{hiding:"object",binding:"object"},{},"nonces"),Ce(X.hiding,d.BYTES,"nonces.hiding"),Ce(X.binding,d.BYTES,"nonces.binding"),lr(ie,"commitmentList"),Ce(pe,void 0,"msg"),WP(W.signers,ie.length);let se=d.fromBytes(X.hiding),me=d.fromBytes(X.binding);if(d.is0(se)||d.is0(me))throw new Error("signing nonces already used");let ge={identifier:N.identifier,hiding:O(t.BASE.multiply(se)),binding:O(t.BASE.multiply(me))},ke=ie.find(Dt=>Dt.identifier===N.identifier);if(!ke)throw new Error("missing signer commitment");if(ta(ke.hiding)!==ta(ge.hiding)||ta(ke.binding)!==ta(ge.binding))throw new Error("incorrect signer commitment");u&&(N=u(N,W)),c&&(W=c(W));let Oe=d.fromBytes(N.signingShare),{lambda:Ye,challenge:Ze,bindingFactor:Pt,groupCommitment:Mt}=Yn(W.commitments[0],ie,pe,N.identifier),$e=s?s(Mt,X):X,Ee=s?d.fromBytes($e.hiding):se,Jt=s?d.fromBytes($e.binding):me,wt=d.mul(d.mul(Ye,Oe),Ze),Ft=d.mul(Jt,Pt),Hu=d.toBytes(d.add(d.add(Ee,Ft),wt));return X.hiding.fill(0),X.binding.fill(0),Hu},verifyShare(N,W,X,ie,pe){At(N,{signers:"object",commitments:"object",verifyingShares:"object"},{},"pub"),uo(N.signers,"pub.signers"),lr(N.commitments,"pub.commitments"),lr(W,"commitmentList"),Ce(X,void 0,"msg"),U(ie),Ce(pe,d.BYTES,"sigShare"),c&&(N=c(N));let se=W.find(Jt=>Jt.identifier===ie);if(!se)throw new Error("cannot find identifier commitment");let me=D(N.verifyingShares[ie]),ge=D(se.hiding),ke=D(se.binding),{lambda:Oe,challenge:Ye,bindingFactor:Ze,groupCommitment:Pt}=Yn(N.commitments[0],W,X,ie),Mt=ge.add(ke.multiplyUnsafe(Ze));l&&(Mt=l(Pt,Mt));let $e=t.BASE.multiplyUnsafe(d.fromBytes(pe)),Ee=Mt.add(me.multiplyUnsafe(d.mul(Ye,Oe)));return $e.equals(Ee)},aggregate(N,W,X,ie){At(N,{signers:"object",commitments:"object",verifyingShares:"object"},{},"pub"),uo(N.signers,"pub.signers"),lr(N.commitments,"pub.commitments"),lr(W,"commitmentList"),Ce(X,void 0,"msg"),At(ie,{},{},"sigShares");let pe=N;c&&(N=c(N));try{WP(N.signers,W.length)}catch{throw new eu("aggregation failed",[])}let se=W.map(Ye=>Ye.identifier),me=new Set;for(let Ye of se){if(me.has(Ye))throw new eu("aggregation failed",[]);me.add(Ye)}if(se.length!==Object.keys(ie).length)throw new eu("aggregation failed",[]);for(let Ye of se)if(!(Ye in ie)||!(Ye in N.verifyingShares))throw new eu("aggregation failed",[]);let ge=D(N.commitments[0]),{groupCommitment:ke}=_t(ge,W,X),Oe=d.ZERO;for(let Ye of se)Oe=d.add(Oe,d.fromBytes(ie[Ye]));if(!Be.verify(X,ke,Oe,ge)){let Ye=[];for(let Ze of se)this.verifyShare(pe,W,X,Ze,ie[Ze])||Ye.push(Ze);throw new eu("aggregation failed",Ye)}return oe.encode(ke,Oe)},sign(N,W){let X=d.fromBytes(W);n&&(X=n(X));let[ie,pe]=Be.sign(N,X);return oe.encode(ie,pe)},verify(N,W,X){let ie=i?C(i(X)):D(X),{R:pe,z:se}=oe.decode(N);return Be.verify(W,pe,se,ie)},combineSecret(N,W){if(lr(N,"shares"),uo(W),N.length<W.min||N.length>W.max)throw new Error("wrong secret shares array");let X=[],ie={};for(let me of N){let ge=U(me.identifier),ke=K(ge);if(ie[ke])throw new Error("duplicated id="+ke);ie[ke]=!0,X.push([ge,d.fromBytes(me.signingShare)])}let pe=X.map(([me])=>me),se=d.ZERO;for(let[me,ge]of X)se=d.add(se,d.mul(ge,We(pe,me)));return d.toBytes(se)},utils:Object.freeze({Fn:d,randomScalar:(N=Si)=>d.toBytes(le(N).scalar),generateSecretPolynomial:(N,W,X,ie)=>{let pe=Me(N,W,X,ie);return{...pe,commitment:pe.commitment.map(O)}}})};return Object.freeze(Lt)}var uo,WP,eu,YP=Dr(()=>{g();Qo();Ka();ug();HP();Js();uo=(e,t="signers")=>{if(At(e,{min:"number",max:"number"},{},t),or(e.min,t+".min"),or(e.max,t+".max"),e.min<2||e.max<2||e.min>e.max)throw new Error("Wrong signers info: min="+e.min+" max="+e.max)},WP=(e,t)=>{if(t<e.min||t>e.max)throw new Error("Wrong number of commitments="+t)},eu=class extends Error{constructor(r,i){super(r);ee(this,"cheaters");this.cheaters=i}}});var Ab={};Hf(Ab,{_HMAC:()=>Bl,hmac:()=>Ib});var Bl,Ib,fg=Dr(()=>{g();Qo();Bl=class{constructor(t,r){ee(this,"oHash");ee(this,"iHash");ee(this,"blockLen");ee(this,"outputLen");ee(this,"canXOF",!1);ee(this,"finished",!1);ee(this,"destroyed",!1);if(zp(t),no(r,void 0,"key"),this.iHash=t.create(),typeof this.iHash.update!="function")throw new Error("expected Hash instance");this.blockLen=this.iHash.blockLen,this.outputLen=this.iHash.outputLen;let i=this.blockLen,n=new Uint8Array(i);n.set(r.length>i?t.create().update(r).digest():r);for(let o=0;o<n.length;o++)n[o]^=54;this.iHash.update(n),this.oHash=t.create();for(let o=0;o<n.length;o++)n[o]^=106;this.oHash.update(n),wi(n)}update(t){return mc(this),this.iHash.update(t),this}digestInto(t){mc(this),Kp(t,this),this.finished=!0;let r=t.subarray(0,this.outputLen);this.iHash.digestInto(r),this.oHash.update(r),this.oHash.digestInto(r),this.destroy()}digest(){let t=new Uint8Array(this.oHash.outputLen);return this.digestInto(t),t}_cloneInto(t){t||(t=Object.create(Object.getPrototypeOf(this),{}));let{oHash:r,iHash:i,finished:n,destroyed:o,blockLen:a,outputLen:s,canXOF:u}=this;return t=t,t.finished=n,t.destroyed=o,t.blockLen=a,t.outputLen=s,t.canXOF=u,t.oHash=r._cloneInto(t.oHash),t.iHash=i._cloneInto(t.iHash),t}clone(){return this._cloneInto()}destroy(){this.destroyed=!0,this.oHash.destroy(),this.iHash.destroy()}},Ib=(()=>{let e=((t,r,i)=>new Bl(t,r).update(i).digest());return e.create=(t,r)=>new Bl(t,r),e})()});var $K,Tb,ia,lg,ZP=Dr(()=>{g();Ka();$K=BigInt(0),Tb=class extends Error{constructor(t=""){super(t)}},ia={Err:Tb,_tlv:{encode:(e,t)=>{let{Err:r}=ia;if(or(e,"tag"),e<0||e>255)throw new r("tlv.encode: wrong tag");if(Tl(t,"data"),t.length&1)throw new r("tlv.encode: unpadded data");let i=t.length/2,n=Pl(i);if(n.length/2&128)throw new r("tlv.encode: long form length too big");let o=i>127?Pl(n.length/2|128):"";return Pl(e)+o+n+t},decode(e,t){let{Err:r}=ia;t=Ce(t,void 0,"DER data");let i=0;if(e<0||e>255)throw new r("tlv.decode: wrong tag");if(t.length<2||t[i++]!==e)throw new r("tlv.decode: wrong tlv");let n=t[i++],o=!!(n&128),a=0;if(!o)a=n;else{let u=n&127;if(!u)throw new r("tlv.decode(long): indefinite length not supported");if(u>4)throw new r("tlv.decode(long): byte length is too big");let c=t.subarray(i,i+u);if(c.length!==u)throw new r("tlv.decode: length bytes not complete");if(c[0]===0)throw new r("tlv.decode(long): zero leftmost byte");for(let l of c)a=a<<8|l;if(i+=u,a<128)throw new r("tlv.decode(long): not minimal encoding")}let s=t.subarray(i,i+a);if(s.length!==a)throw new r("tlv.decode: wrong value length");return{v:s,l:t.subarray(i+a)}}},_int:{encode(e){let{Err:t}=ia;if(ig(e),e<$K)throw new t("integer: negative integers are not allowed");let r=Pl(e);if(Number.parseInt(r[0],16)&8&&(r="00"+r),r.length&1)throw new t("unexpected DER parsing assertion: unpadded hex");return r},decode(e){let{Err:t}=ia;if(e.length<1)throw new t("invalid signature integer: empty");if(e[0]&128)throw new t("invalid signature integer: negative");if(e.length>1&&e[0]===0&&!(e[1]&128))throw new t("invalid signature integer: unnecessary leading zero");return Hr(e)}},toSig(e,t){let{Err:r,_int:i,_tlv:n}=ia;if(t!==void 0&&(or(t,"maxScalarBytes"),t<1))throw new r("invalid signature: maxScalarBytes must be positive");let o=Ce(e,void 0,"signature"),{v:a,l:s}=n.decode(48,o);if(s.length)throw new r("invalid signature: left bytes after parsing");let{v:u,l:c}=n.decode(2,a),{v:l,l:p}=n.decode(2,c);if(p.length)throw new r("invalid signature: left bytes after parsing");if(t!==void 0&&(u.length>t||l.length>t))throw new r("invalid signature: integer too large");return{r:i.decode(u),s:i.decode(l)}},hexFromSig(e){let{_tlv:t,_int:r}=ia;At(e,{r:"bigint",s:"bigint"},{},"sig");let i=t.encode(2,r.encode(e.r)),n=t.encode(2,r.encode(e.s)),o=i+n;return t.encode(48,o)}},lg=(Object.freeze(ia._tlv),Object.freeze(ia._int),Object.freeze(ia))});function XK(e,t,r){db("scalar",e,na,r);let[[i,n],[o,a]]=t,s=$P(a*e,r),u=$P(-n*e,r),c=e-s*i-u*o,l=-s*n-u*a,p=c<na,d=l<na;p&&(c=-c),d&&(l=-l);let v=Rl(Math.ceil(Sc(r)/2))+tu;if(c<na||c>=v||l<na||l>=v)throw new Error("splitScalar (endomorphism): failed for k");return{k1neg:p,k1:c,k2neg:d,k2:l}}function kb(e){if(!["compact","recovered","der"].includes(e))throw new Error('Signature format must be "compact", "recovered", or "der"');return e}function Pb(e,t){At(e);let r={};for(let i of Object.keys(t))r[i]=e[i]===void 0?t[i]:e[i];return ao(r.lowS,"lowS"),ao(r.prehash,"prehash"),r.format!==void 0&&kb(r.format),r}function JP(e,t={}){let r=LP("weierstrass",e,t),i=r.Fp,n=r.Fn,o=r.CURVE,{h:a,n:s}=o;At(t,{},{allowInfinityPoint:"boolean",clearCofactor:"function",isTorsionFree:"function",fromBytes:"function",toBytes:"function",endo:"object",randomBytes:"function"});let{endo:u,allowInfinityPoint:c,clearCofactor:l,isTorsionFree:p,fromBytes:d,toBytes:v}=t,_=t.randomBytes===void 0?Si:t.randomBytes;if(u&&(!i.is0(o.a)||typeof u.beta!="bigint"||!Array.isArray(u.basises)))throw new Error('invalid endo: expected "beta": bigint and "basises": array');let I=u?{beta:u.beta,basises:u.basises.map(K=>[...K])}:void 0,R=e2(i,n);function k(){if(!i.isOdd)throw new Error("compression is not supported: Field does not have .isOdd()")}function q(K,U,G){if(U.is0()){if(!c)throw new Error("bad point: ZERO");return Uint8Array.of(0)}let{x:te,y:ae}=U.toAffine(),oe=i.toBytes(te);if(ao(G,"isCompressed"),G){k();let le=!i.isOdd(ae);return bt(QP(le),oe)}else return bt(Uint8Array.of(4),oe,i.toBytes(ae))}function z(K){Ce(K,void 0,"Point");let{publicKey:U,publicKeyUncompressed:G}=R,te=K.length,ae=K[0],oe=K.subarray(1);if(c&&te===1&&ae===0)return{x:i.ZERO,y:i.ZERO};if(te===U&&(ae===2||ae===3)){let le=i.fromBytes(oe);if(!i.isValid(le))throw new Error("bad point: is not on curve, wrong x");let he=V(le),ve;try{ve=i.sqrt(he)}catch(_e){let We=_e instanceof Error?": "+_e.message:"";throw new Error("bad point: is not on curve, sqrt error"+We)}k();let je=i.isOdd(ve);return(ae&1)===1!==je&&(ve=i.neg(ve)),{x:le,y:ve}}else if(te===G&&ae===4){let le=i.BYTES,he=i.fromBytes(oe.subarray(0,le)),ve=i.fromBytes(oe.subarray(le,le*2));if(!Y(he,ve))throw new Error("bad point: is not on curve");return{x:he,y:ve}}else throw new Error(`bad point: got length ${te}, expected compressed=${U} or uncompressed=${G}`)}let A=v===void 0?q:v,B=d===void 0?z:d,M=i.mul(o.b,Rb),F=i.is0(o.a)?K=>i.ZERO:K=>i.mul(o.a,K);function V(K){let U=i.sqr(K),G=i.mul(U,K);return i.add(i.add(G,i.mul(K,o.a)),o.b)}function Y(K,U){let G=i.sqr(U),te=V(K);return i.eql(G,te)}if(!Y(o.Gx,o.Gy))throw new Error("bad curve params: generator point");let E=i.mul(i.pow(o.a,Rb),JK),h=i.mul(i.sqr(o.b),BigInt(27));if(i.is0(i.add(E,h)))throw new Error("bad curve params: a or b");function y(K,U,G=!1){if(!i.isValid(U)||G&&i.is0(U))throw new Error(`bad point coordinate ${K}`);return typeof U=="object"&&U!==null?i.create(U):U}function w(K){if(!(K instanceof D))throw new Error("Weierstrass Point expected")}function S(K){if(!I||!I.basises)throw new Error("no endo");return XK(K,I.basises,n.ORDER)}function O(K,U,G,te){if(!n.isValid(te))throw new RangeError("invalid scalar: out of range");if(I){let{k1neg:ae,k1:oe,k2neg:le,k2:he}=S(te),ve=new D(i.mul(G.X,I.beta),G.Y,G.Z);K.push(ae?G.negate():G,le?ve.negate():ve),U.push(oe,he)}else K.push(G),U.push(te)}let C=new WeakSet,x=class x{constructor(U,G,te){ee(this,"X");ee(this,"Y");ee(this,"Z");this.X=y("x",U),this.Y=y("y",G,!0),this.Z=y("z",te),Object.freeze(this)}static CURVE(){return o}static fromAffine(U){let{x:G,y:te}=U||{};if(!U||!i.isValid(G)||!i.isValid(te))throw new Error("invalid affine point");if(U instanceof x)throw new Error("projective point not allowed");return i.is0(G)&&i.is0(te)?x.ZERO:new x(G,te,i.ONE)}static fromBytes(U){let G=x.fromAffine(B(Ce(U,void 0,"point")));return G.assertValidity(),G}static fromHex(U){return x.fromBytes(bc(U))}get x(){return this.toAffine().x}get y(){return this.toAffine().y}precompute(U=6,G=!0){return m.setWindowSize(this,U),G||this.multiply(Rb),this}assertValidity(){let U=this;if(U.is0()){if(c&&i.is0(U.X)&&i.eql(U.Y,i.ONE)&&i.is0(U.Z))return;throw new Error("bad point: ZERO")}if(C.has(U))return;let{x:G,y:te}=U.toAffine();if(!i.isValid(G)||!i.isValid(te))throw new Error("bad point: x or y not field elements");if(!Y(G,te))throw new Error("bad point: equation left != right");if(!U.isTorsionFree())throw new Error("bad point: not in prime-order subgroup");C.add(U)}hasEvenY(){let{y:U}=this.toAffine();if(!i.isOdd)throw new Error("Field doesn't support isOdd");return!i.isOdd(U)}equals(U){w(U);let{X:G,Y:te,Z:ae}=this,{X:oe,Y:le,Z:he}=U,ve=i.eql(i.mul(G,he),i.mul(oe,ae)),je=i.eql(i.mul(te,he),i.mul(le,ae));return ve&&je}negate(){return new x(this.X,i.neg(this.Y),this.Z)}double(){let{X:U,Y:G,Z:te}=this,ae=i.ZERO,oe=i.ZERO,le=i.ZERO,he=i.mul(U,U),ve=i.mul(G,G),je=i.mul(te,te),be=i.mul(U,G);return be=i.add(be,be),le=i.mul(U,te),le=i.add(le,le),ae=F(le),oe=i.mul(M,je),oe=i.add(ae,oe),ae=i.sub(ve,oe),oe=i.add(ve,oe),oe=i.mul(ae,oe),ae=i.mul(be,ae),le=i.mul(M,le),je=F(je),be=i.sub(he,je),be=F(be),be=i.add(be,le),le=i.add(he,he),he=i.add(le,he),he=i.add(he,je),he=i.mul(he,be),oe=i.add(oe,he),je=i.mul(G,te),je=i.add(je,je),he=i.mul(je,be),ae=i.sub(ae,he),le=i.mul(je,ve),le=i.add(le,le),le=i.add(le,le),new x(ae,oe,le)}add(U){w(U);let{X:G,Y:te,Z:ae}=this,{X:oe,Y:le,Z:he}=U,ve=i.ZERO,je=i.ZERO,be=i.ZERO,_e=i.mul(G,oe),We=i.mul(te,le),Pe=i.mul(ae,he),Me=i.add(G,te),rt=i.add(oe,le);Me=i.mul(Me,rt),rt=i.add(_e,We),Me=i.sub(Me,rt),rt=i.add(G,ae);let Be=i.add(oe,he);return rt=i.mul(rt,Be),Be=i.add(_e,Pe),rt=i.sub(rt,Be),Be=i.add(te,ae),ve=i.add(le,he),Be=i.mul(Be,ve),ve=i.add(We,Pe),Be=i.sub(Be,ve),be=F(rt),ve=i.mul(M,Pe),be=i.add(ve,be),ve=i.sub(We,be),be=i.add(We,be),je=i.mul(ve,be),We=i.add(_e,_e),We=i.add(We,_e),Pe=F(Pe),rt=i.mul(M,rt),We=i.add(We,Pe),Pe=i.sub(_e,Pe),Pe=F(Pe),rt=i.add(rt,Pe),_e=i.mul(We,rt),je=i.add(je,_e),_e=i.mul(Be,rt),ve=i.mul(Me,ve),ve=i.sub(ve,_e),_e=i.mul(Me,We),be=i.mul(Be,be),be=i.add(be,_e),new x(ve,je,be)}subtract(U){return w(U),this.add(U.negate())}is0(){return this.equals(x.ZERO)}multiply(U){if(!n.isValidNot0(U))throw new RangeError("invalid scalar: out of range");let{p:G,f:te}=m.mulSecret(this,U,a,P);return P([G,te])[0]}multiplyUnsafe(U){let G=this,te=U;if(!n.isValid(te))throw new RangeError("invalid scalar: out of range");if(te===na||G.is0())return x.ZERO;if(te===tu)return G;if(m.hasWindowSize(this))return m.mulUnsafe(G,te,P);let ae=[],oe=[];return O(ae,oe,G,te),Ic(x,ae,oe)}mulAddUnsafe(U,G,te){w(G);let ae=[],oe=[];return O(ae,oe,this,U),O(ae,oe,G,te),Ic(x,ae,oe)}toAffine(U){let G=this,te=U;if(te!=null&&!i.isValid(te))throw new RangeError('"invertedZ" expected valid field element');let{X:ae,Y:oe,Z:le}=G;if(i.eql(le,i.ONE))return{x:ae,y:oe};let he=G.is0();te==null&&(te=he?i.ONE:i.inv(le));let ve=i.mul(ae,te),je=i.mul(oe,te),be=i.mul(le,te);if(he)return{x:i.ZERO,y:i.ZERO};if(!i.eql(be,i.ONE))throw new Error("invZ was invalid");return{x:ve,y:je}}isTorsionFree(){return a===tu?!0:p?p(x,this):m.mulUnsafe(this,s).is0()}clearCofactor(){return a===tu?this:l?l(x,this):this.multiplyUnsafe(a)}isSmallOrder(){return a===tu?this.is0():this.clearCofactor().is0()}toBytes(U=!0){return ao(U,"isCompressed"),this.assertValidity(),A(x,this,U)}toHex(U=!0){return ta(this.toBytes(U))}toString(){return`<Point ${this.is0()?"ZERO":this.toHex()}>`}};ee(x,"BASE",new x(o.Gx,o.Gy,i.ONE)),ee(x,"ZERO",new x(i.ZERO,i.ONE,i.ZERO)),ee(x,"Fp",i),ee(x,"Fn",n);let D=x,P=K=>BP(D,K),m=new ag(D,_);return m.bits>=6&&D.BASE.precompute(6),Object.freeze(D.prototype),Object.freeze(D),D}function QP(e){return Uint8Array.of(e?2:3)}function e2(e,t){return{secretKey:t.BYTES,publicKey:1+e.BYTES,publicKeyUncompressed:1+2*e.BYTES,publicKeyHasPrefix:!0,signature:2*t.BYTES}}function QK(e,t={}){Ga(e);let{Fn:r}=e,i=t.randomBytes===void 0?Si:t.randomBytes,n=Object.assign(e2(e.Fp,r),{seed:Math.max(Oc(r.ORDER),16)});function o(v){try{let _=r.fromBytes(v);return r.isValidNot0(_)}catch{return!1}}function a(v,_){let{publicKey:I,publicKeyUncompressed:R}=n;try{let k=v.length;return _===!0&&k!==I||_===!1&&k!==R?!1:!e.fromBytes(v).is0()}catch{return!1}}function s(v){return v=v===void 0?i(n.seed):v,Xs(Ce(v,n.seed,"seed"),r.ORDER)}function u(v,_=!0){return e.BASE.multiply(r.fromBytes(v)).toBytes(_)}function c(v){let{secretKey:_,publicKey:I,publicKeyUncompressed:R}=n,k=r._lengths;if(!oo(v))return;let q=Ce(v,void 0,"key").length,z=q===I||q===R,A=q===_||!!k?.includes(q);if(!(z&&A))return z}function l(v,_,I=!0){if(c(v)===!0)throw new Error("first arg must be private key");if(c(_)===!1)throw new Error("second arg must be public key");let R=r.fromBytes(v),k=e.fromBytes(_);if(k.is0())throw new Error("invalid public key: point at infinity");return k.multiply(R).toBytes(I)}let p={isValidSecretKey:o,isValidPublicKey:a,randomSecretKey:s},d=sg(s,u);return Object.freeze(p),Object.freeze(n),Object.freeze({getPublicKey:u,getSharedSecret:l,keygen:d,Point:e,utils:p,lengths:n})}function t2(e,t,r={}){Ga(e);let i=t;zp(i),At(r,{},{hmac:"function",lowS:"boolean",randomBytes:"function",bits2int:"function",bits2int_modN:"function"});let n=Object.assign({},r),o=n.randomBytes===void 0?Si:n.randomBytes,a=n.hmac===void 0?(x,K)=>Ib(i,x,K):n.hmac,{Fp:s,Fn:u}=e,{ORDER:c,BITS:l}=u,p=Oc(c),d=Sb(o,p),{keygen:v,getPublicKey:_,getSharedSecret:I,utils:R,lengths:k}=QK(e,n),q={prehash:!0,lowS:typeof n.lowS=="boolean"?n.lowS:!0,format:"compact",extraEntropy:!1},z=c*XP+tu<s.ORDER;function A(x){let K=c>>tu;return x>K}function B(x,K){if(!u.isValidNot0(K))throw new Error(`invalid signature ${x}: out of range 1..Point.Fn.ORDER`);return K}function M(){if(!s.isOdd)throw new Error("Field doesn't support isOdd")}function F(x,K,U){return M(),(x===U?0:2)|Number(s.isOdd(K))}function V(){if(z)throw new Error('"recovered" sig type is not supported for cofactor >2 curves')}function Y(x,K){kb(K);let U=k.signature,G=K==="compact"?U:K==="recovered"?U+1:void 0;return Ce(x,G)}class E{constructor(K,U,G){ee(this,"r");ee(this,"s");ee(this,"recovery");if(this.r=B("r",K),this.s=B("s",U),G!=null){if(V(),![0,1,2,3].includes(G))throw new Error("invalid recovery id");this.recovery=G}Object.freeze(this)}static fromBytes(K,U=q.format){Y(K,U);let G;if(U==="der"){if(K.length>2*u.BYTES+16)throw new lg.Err("invalid signature: DER signature too long");let{r:le,s:he}=lg.toSig(Ce(K),u.BYTES+1);return new E(le,he)}U==="recovered"&&(G=K[0],U="compact",K=K.subarray(1));let te=k.signature/2,ae=K.subarray(0,te),oe=K.subarray(te,te*2);return new E(u.fromBytes(ae),u.fromBytes(oe),G)}static fromHex(K,U){return this.fromBytes(bc(K),U)}assertRecovery(){let{recovery:K}=this;if(K==null)throw new Error("invalid recovery id: must be present");return K}addRecoveryBit(K){return new E(this.r,this.s,K)}recoverPublicKey(K){let{r:U,s:G}=this,te=this.assertRecovery(),ae=te===2||te===3?U+c:U;if(!s.isValid(ae))throw new Error("invalid recovery id: sig.r+curve.n != R.x");let oe=s.toBytes(ae),le=e.fromBytes(bt(QP((te&1)===0),oe)),he=u.inv(ae),ve=y(Ce(K,void 0,"msgHash")),je=u.create(-ve*he),be=u.create(G*he),_e=e.BASE.mulAddUnsafe(je,le,be);if(_e.is0())throw new Error("invalid recovery: point at infinify");return _e.assertValidity(),_e}hasHighS(){return A(this.s)}toBytes(K=q.format){if(kb(K),K==="der")return bc(lg.hexFromSig(this));let{r:U,s:G}=this,te=u.toBytes(U),ae=u.toBytes(G);return K==="recovered"?(V(),bt(Uint8Array.of(this.assertRecovery()),te,ae)):bt(te,ae)}toHex(K){return ta(this.toBytes(K))}}Object.freeze(E.prototype),Object.freeze(E);let h=n.bits2int===void 0?function(K){if(K.length>8192)throw new Error("input is too large");let U=Hr(K),G=K.length*8-l;return G>0?U>>BigInt(G):U}:n.bits2int,y=n.bits2int_modN===void 0?function(K){return u.create(h(K))}:n.bits2int_modN,w=Rl(l);function S(x){return db("num < 2^"+l,x,na,w),u.toBytes(x)}function O(x,K){return Ce(x,void 0,"message"),K?Ce(i(x),void 0,"prehashed message"):x}function C(x,K,U){let{lowS:G,prehash:te,extraEntropy:ae}=Pb(U,q);x=O(x,te);let oe=y(x),le=u.fromBytes(K);if(!u.isValidNot0(le))throw new Error("invalid private key");let he=[S(le),S(oe)];if(ae!=null&&ae!==!1){let _e=ae===!0?o(k.secretKey):ae;he.push(Ce(_e,void 0,"extraEntropy"))}let ve=bt(...he),je=oe;function be(_e){let We=h(_e);if(!u.isValidNot0(We))return;let Pe=e.BASE.multiply(We).toAffine(),Me=u.create(Pe.x);if(Me===na)return;let rt;if(d!==void 0){let ui=Hr(Xs(d(p),c)),Et=u.inv(u.mul(ui,We)),_t=u.mul(ui,je),Yn=u.mul(ui,le);rt=u.create(Et*u.create(_t+Yn*Me))}else{let ui=OP(We,c);rt=u.create(ui*u.create(je+Me*le))}if(rt===na)return;let Be=F(Pe.x,Pe.y,Me),vt=rt;return G&&A(rt)&&(vt=u.neg(rt),Be^=1),new E(Me,vt,z?void 0:Be)}return{seed:ve,k2sig:be}}function D(x,K,U={}){let{seed:G,k2sig:te}=C(x,K,U);return vP(i.outputLen,u.BYTES,a)(G,te).toBytes(U.format)}function P(x,K,U,G={}){let{lowS:te,prehash:ae,format:oe}=Pb(G,q);if(U=Ce(U,void 0,"publicKey"),K=O(K,ae),!oo(x)){let le=x instanceof E?", use sig.toBytes()":"";throw new Error("verify expects Uint8Array signature"+le)}Y(x,oe);try{let le=E.fromBytes(x,oe),he=e.fromBytes(U);if(he.is0()||te&&le.hasHighS())return!1;let{r:ve,s:je}=le,be=y(K),_e=u.inv(je),We=u.create(be*_e),Pe=u.create(ve*_e),Me=e.BASE.mulAddUnsafe(We,he,Pe);if(Me.is0())return!1;let rt=Me.toAffine();return!(u.create(rt.x)!==ve||oe==="recovered"&&le.recovery!==F(rt.x,rt.y,ve))}catch{return!1}}function m(x,K,U={}){let{prehash:G}=Pb(U,q);return K=O(K,G),E.fromBytes(x,"recovered").recoverPublicKey(K).toBytes()}return Object.freeze({keygen:v,getPublicKey:_,getSharedSecret:I,utils:R,lengths:k,Point:e,sign:D,verify:P,recoverPublicKey:m,Signature:E,hash:i})}var $P,na,tu,XP,Rb,JK,r2=Dr(()=>{g();fg();Qo();Ka();ug();ZP();Js();$P=(e,t)=>(e+(e>=0?t:-t)/XP)/t;na=BigInt(0),tu=BigInt(1),XP=BigInt(2),Rb=BigInt(3),JK=BigInt(4)});var Ll={};Hf(Ll,{__TEST:()=>nV,schnorr:()=>oV,schnorr_FROST:()=>fV,secp256k1:()=>rV,secp256k1_FROST:()=>uV,secp256k1_hasher:()=>Cb});function tV(e){let t=hg.p,r=BigInt(3),i=BigInt(6),n=BigInt(11),o=BigInt(22),a=BigInt(23),s=BigInt(44),u=BigInt(88),c=e*e*e%t,l=c*c*e%t,p=Vi(l,r,t)*l%t,d=Vi(p,r,t)*l%t,v=Vi(d,i2,t)*c%t,_=Vi(v,n,t)*v%t,I=Vi(_,o,t)*_%t,R=Vi(I,s,t)*I%t,k=Vi(R,u,t)*R%t,q=Vi(k,s,t)*I%t,z=Vi(q,r,t)*l%t,A=Vi(z,a,t)*_%t,B=Vi(A,i,t)*c%t,M=Vi(B,i2,t);if(!Tn.eql(Tn.sqr(M),e))throw new Error("Cannot find square root");return M}function Nl(e,...t){let r=n2[e];if(r===void 0){let i=Fa(wc(e));r=bt(i,i),n2[e]=r}return Fa(bt(r,...t))}function u2(e){let{Fn:t,BASE:r}=kt,i=t.fromBytes(Ce(e,32,"secretKey")),o=r.multiply(i).toAffine();return{scalar:co(o.y)?i:t.neg(i),bytes:s2(o)}}function dg(e){let t=Tn;if(!t.isValidNot0(e))throw new Error("invalid x: Fail if x \u2265 p");let r=t.sqr(e),i=t.add(t.mulN(r,e),BigInt(7)),n=t.sqrt(i);co(n)||(n=t.neg(n));let o=kt.fromAffine({x:e,y:n});return o.assertValidity(),o}function Nb(...e){return kt.Fn.create(Ac(Nl("BIP0340/challenge",...e)))}function o2(e){return u2(e).bytes}function iV(e,t,r=Il(32)){let{Fn:i,BASE:n}=kt,o=ra(Ce(e,void 0,"message")),{bytes:a,scalar:s}=u2(t),u=Ce(r,32,"auxRand"),c=i.toBytes(s^Ac(Nl("BIP0340/aux",u))),l=Nl("BIP0340/nonce",c,a,o),p=i.create(Ac(l));if(p===Bb)throw new Error("sign failed: k is zero");let v=n.multiply(p).toAffine(),_=co(v.y)?p:i.neg(p),I=s2(v),R=Nb(I,a,o),k=new Uint8Array(64);if(k.set(I,0),k.set(i.toBytes(i.create(_+R*s)),32),!c2(k,o,a))throw new Error("sign: Invalid signature produced");return k}function c2(e,t,r){let{Fp:i,Fn:n,BASE:o}=kt,a=Ce(e,64,"signature"),s=Ce(t,void 0,"message"),u=Ce(r,32,"publicKey");try{let c=dg(Ac(u)),l=a.subarray(0,32),p=Ac(l);if(!i.isValidNot0(p))return!1;let d=Ac(a.subarray(32,64));if(!n.isValidNot0(d))return!1;let v=Nb(l,Cl(c),s),_=o.mulAddUnsafe(d,c,n.neg(v)),{x:I,y:R}=_.toAffine();return!(_.is0()||!co(R)||!i.eql(I,p))}catch{return!1}}function f2(e,t){if(t===void 0)return Bb;let r=Cl(e),i=Hr(Nl("TapTweak",r,t));if(!kt.Fn.isValid(i))throw new Error("invalid TapTweak hash");return i}function Lb(e){let t=kt.fromBytes(e.commitments[0]);return co(t.y)?e:{signers:{min:e.signers.min,max:e.signers.max},commitments:e.commitments.map(r=>kt.fromBytes(r).negate().toBytes()),verifyingShares:Object.fromEntries(Object.entries(e.verifyingShares).map(([r,i])=>[r,kt.fromBytes(i).negate().toBytes()]))}}function l2(e,t){let r=kt.fromBytes(t.commitments[0]);if(co(r.y))return e;let i=kt.Fn;return{...e,signingShare:i.toBytes(i.neg(i.fromBytes(e.signingShare)))}}function cV(e,t){if(co(e.y))return t;let r=kt.Fn;return{binding:r.toBytes(r.neg(r.fromBytes(t.binding))),hiding:r.toBytes(r.neg(r.fromBytes(t.hiding)))}}function h2(e,t,r){let i=kt.Fn,n=l2(e,t),o=Lb(t),a=f2(kt.fromBytes(o.commitments[0]),r),s=i.toBytes(i.add(i.fromBytes(n.signingShare),a));return{identifier:n.identifier,signingShare:s}}function d2(e,t){let r=Lb(e),i=f2(kt.fromBytes(r.commitments[0]),t);if(i===Bb)return r;let n=kt.BASE.multiply(i),o=r.commitments.map((s,u)=>(u===0?kt.fromBytes(s).add(n):kt.fromBytes(s)).toBytes()),a={};for(let s in r.verifyingShares)a[s]=kt.fromBytes(r.verifyingShares[s]).add(n).toBytes();return{signers:{min:r.signers.min,max:r.signers.max},commitments:o,verifyingShares:a}}var hg,eV,Bb,i2,Tn,kt,rV,n2,Cl,s2,co,Ac,nV,oV,aV,a2,sV,Cb,uV,fV,Ml=Dr(()=>{g();Al();Qo();ug();YP();GP();Js();r2();Ka();hg={p:BigInt("0xfffffffffffffffffffffffffffffffffffffffffffffffffffffffefffffc2f"),n:BigInt("0xfffffffffffffffffffffffffffffffebaaedce6af48a03bbfd25e8cd0364141"),h:BigInt(1),a:BigInt(0),b:BigInt(7),Gx:BigInt("0x79be667ef9dcbbac55a06295ce870b07029bfcdb2dce28d959f2815b16f81798"),Gy:BigInt("0x483ada7726a3c4655da4fbfc0e1108a8fd17b448a68554199c47d08ffb10d4b8")},eV={beta:BigInt("0x7ae96a2b657c07106e64479eac3434e99cf0497512f58995c1396c28719501ee"),basises:[[BigInt("0x3086d221a7d46bcde86c90e49284eb15"),-BigInt("0xe4437ed6010e88286f547fa90abfe4c3")],[BigInt("0x114ca50f7a8e2f3f657c1108d9d44cfd8"),BigInt("0x3086d221a7d46bcde86c90e49284eb15")]]},Bb=BigInt(0),i2=BigInt(2);Tn=xc(hg.p,{sqrt:tV}),kt=JP(hg,{Fp:Tn,endo:eV}),rV=t2(kt,Fa),n2=Object.create(null);Cl=e=>e.toBytes(!0).slice(1),s2=({x:e})=>Tn.toBytes(e),co=e=>!Tn.isOdd(e);Ac=Hr;nV=Object.freeze({lift_x:dg,frostTweakPublic:d2,frostTweakSecret:h2}),oV=(()=>{let r=i=>(i=i===void 0?Il(48):i,Xs(Ce(i,48,"seed"),hg.n));return Object.freeze({keygen:sg(r,o2),getPublicKey:o2,sign:iV,verify:c2,Point:kt,utils:Object.freeze({randomSecretKey:r,taggedHash:Nl,lift_x:dg,pointToBytes:Cl}),lengths:Object.freeze({secretKey:32,publicKey:32,publicKeyHasPrefix:!1,signature:64,seed:48})})})(),aV=zP(Tn,[["0x8e38e38e38e38e38e38e38e38e38e38e38e38e38e38e38e38e38e38daaaaa8c7","0x7d3d4c80bc321d5b9f315cea7fd44c5d595d2fc0bf63b92dfff1044f17c6581","0x534c328d23f234e6e2a413deca25caece4506144037c40314ecbd0b53d9dd262","0x8e38e38e38e38e38e38e38e38e38e38e38e38e38e38e38e38e38e38daaaaa88c"],["0xd35771193d94918a9ca34ccbb7b640dd86cd409542f8487d9fe6b745781eb49b","0xedadc6f64383dc1df7c4b2d51b54225406d36b641f5e41bbc52a56612a8c6d14","0x0000000000000000000000000000000000000000000000000000000000000001"],["0x4bda12f684bda12f684bda12f684bda12f684bda12f684bda12f684b8e38e23c","0xc75e0c32d5cb7c0fa9d0a54b12a0a6d5647ab046d686da6fdffc90fc201d71a3","0x29a6194691f91a73715209ef6512e576722830a201be2018a765e85a9ecee931","0x2f684bda12f684bda12f684bda12f684bda12f684bda12f684bda12f38e38d84"],["0xfffffffffffffffffffffffffffffffffffffffffffffffffffffffefffff93b","0x7a06534bb8bdb49fd5e9e6632722c2989467c1bfc8e8d978dfb425d2685c2573","0x6484aa716545ca2cf3a70c3fa8fe337e0a3d21162f0d6299a7bf8192bfd2a76f","0x0000000000000000000000000000000000000000000000000000000000000001"]].map(e=>e.map(t=>BigInt(t)))),sV=()=>a2||(a2=VP(Tn,{A:BigInt("0x3f8731abdd661adca08a5558f0f5d272e953d363cb6f0e5d405447c01a444533"),B:BigInt("1771"),Z:Tn.create(BigInt("-11"))})),Cb=KP(kt,e=>{let{x:t,y:r}=sV()(Tn.create(e[0]));return aV(t,r)},{DST:"secp256k1_XMD:SHA-256_SSWU_RO_",encodeDST:"secp256k1_XMD:SHA-256_SSWU_NU_",p:Tn.ORDER,m:1,k:128,expand:"xmd",hash:Fa}),uV=Ob({name:"FROST-secp256k1-SHA256-v1",Point:kt,hashToScalar:Cb.hashToScalar,hash:Fa});fV=Ob({name:"FROST-secp256k1-SHA256-TR-v1",Point:kt,hashToScalar:Cb.hashToScalar,hash:Fa,parsePublicKey(e){if(e.length===32)return dg(Hr(e));if(e.length===33)return kt.fromBytes(e);throw new Error(`expected x-only or compressed public key, got length=${e.length}`)},adjustScalar(e){let t=kt.BASE.multiply(e);return co(t.y)?e:kt.Fn.neg(e)},adjustPoint:e=>co(e.y)?e:e.negate(),challenge(e,t,r){return Nb(Cl(e),Cl(t),r)},adjustNonces:cV,adjustGroupCommitmentShare:(e,t)=>co(e.y)?t:t.negate(),adjustPublic:Lb,adjustSecret:l2,adjustTx:{encode:e=>e.subarray(1),decode:e=>bt(Uint8Array.of(2),e)},adjustDKG:e=>{let t=new Uint8Array(0);return{public:d2(e.public,t),secret:h2(e.secret,e.public,t)}}})});var un=T((Joe,v2)=>{"use strict";g();var p2=Ke(),{secp256k1:lV}=(Ml(),en(Ll)),Hl=lV.Point,pg=Hl.Fn.ORDER;function hV(e){return BigInt("0x"+(e.toString(16)||"0"))}function Mb(e){var t=e.toString(16);return t.length%2&&(t="0"+t),new p2(t,16)}function gg(e){if(e==null)throw new Error("Invalid Point");if(typeof e=="bigint")return e;if(typeof e=="number")return BigInt(e);if(typeof e=="string")return BigInt(e.indexOf("0x")===0?e:"0x"+e);if(typeof e.toString=="function")return hV(e);throw new Error("Invalid Point")}function Dl(e){var t=Object.create(Bt.prototype);return t._p=e,t}function g2(e,t){var r=gg(t).toString(16).padStart(64,"0");return Hl.fromHex((e?"03":"02")+r)}function m2(e,t){var r;try{r=g2((t&1n)===1n,e)}catch{throw new Error("Point does not lie on the curve")}if(r.toAffine().y!==t)throw new Error("Invalid y value for curve.")}function Bt(e,t,r){if(!(this instanceof Bt))return new Bt(e,t,r);var i,n;try{i=gg(e),n=gg(t)}catch{throw new Error("Invalid Point")}m2(i,n);try{this._p=Hl.fromAffine({x:i,y:n})}catch{throw new Error("Invalid Point")}return this}Bt.fromX=function(t,r){try{var i=Dl(g2(t,r))}catch{throw new Error("Invalid X")}return i.validate(),i};Bt.getG=function(){return Dl(Hl.BASE)};Bt.getN=function(){return Mb(pg)};Bt.prototype.getX=function(){return Mb(this._p.toAffine().x)};Bt.prototype.getY=function(){return Mb(this._p.toAffine().y)};Object.defineProperty(Bt.prototype,"x",{configurable:!0,enumerable:!0,get:function(){return this.getX()}});Object.defineProperty(Bt.prototype,"y",{configurable:!0,enumerable:!0,get:function(){return this.getY()}});Bt.prototype.mul=function(t){var r=(gg(t)%pg+pg)%pg;return r===0n||this._p.is0()?Dl(Hl.ZERO):Dl(this._p.multiply(r))};Bt.prototype.add=function(t){return Dl(this._p.add(t._p))};Bt.prototype.mulAdd=function(t,r,i){return this.mul(t).add(r.mul(i))};Bt.prototype.eq=function(t){return this._p.equals(t._p)};Bt.prototype.isInfinity=function(){return this._p.is0()};Bt.prototype.validate=function(){if(this.isInfinity())throw new Error("Point cannot be equal to Infinity");var t=this._p.toAffine();return m2(t.x,t.y),this};Bt.pointToCompressed=function(t){var r=t.getX().toBuffer({size:32}),i=t.getY().toBuffer({size:32}),n,o=i[i.length-1]%2;return o?n=f.Buffer.from([3]):n=f.Buffer.from([2]),f.Buffer.concat([n,r])};Bt.pointFromCompressed=function(e){if(e.length!==33)throw new Error("invalid buffer length");var t=e[0],r;if(t===3)r=!0;else if(t===2)r=!1;else throw new Error("invalid value of compressed prefix");var i=p2.fromBuffer(e.slice(1,33));return Bt.fromX(r,i)};Bt.prototype.toBuffer=function(){return Bt.pointToCompressed(this)};Bt.prototype.toHex=function(){return this.toBuffer().toString("hex")};Bt.fromBuffer=function(e){return Bt.pointFromCompressed(e)};Bt.fromHex=function(e){return Bt.fromBuffer(f.Buffer.from(e,"hex"))};v2.exports=Bt});var ni=T((eae,_2)=>{"use strict";g();var b2=at(),dV=Ie(),y2=function(t){return b2.isString(t)?/^[0-9a-fA-F]+$/.test(t):!1};_2.exports={isValidJSON:function(t){var r;if(!b2.isString(t))return!1;try{r=JSON.parse(t)}catch{return!1}return typeof r=="object"},isHexa:y2,isHexaString:y2,defineImmutable:function(t,r){return Object.keys(r).forEach(function(i){Object.defineProperty(t,i,{configurable:!1,enumerable:!0,value:r[i]})}),t},isNaturalNumber:function(t){return typeof t=="number"&&isFinite(t)&&Math.floor(t)===t&&t>=0},integerAsBuffer:function(t){dV.checkArgumentType(t,"number","integer");let r=f.Buffer.allocUnsafe(4);return r.writeUInt32BE(t,0),r}}});var gt=T((rae,S2)=>{"use strict";g();var ru=Ke(),pV=at(),xi=Ie(),gV=ni(),it=function e(t,r){if(!(this instanceof e))return new e(t,r);if(t instanceof ru)this.set({r:t,s:r});else if(t){var i=t;this.set(i)}};it.prototype.set=function(e){return this.r=e.r||this.r||void 0,this.s=e.s||this.s||void 0,this.i=typeof e.i<"u"?e.i:this.i,this.compressed=typeof e.compressed<"u"?e.compressed:this.compressed,this.nhashtype=e.nhashtype||this.nhashtype||void 0,this};it.fromCompact=function(e){xi.checkArgument(f.Buffer.isBuffer(e),"Argument is expected to be a Buffer");var t=new it,r=!0,i=e.slice(0,1)[0]-27-4;i<0&&(r=!1,i=i+4);var n=e.slice(1,33),o=e.slice(33,65);return xi.checkArgument(i===0||i===1||i===2||i===3,new Error("i must be 0, 1, 2, or 3")),xi.checkArgument(n.length===32,new Error("r must be 32 bytes")),xi.checkArgument(o.length===32,new Error("s must be 32 bytes")),t.compressed=r,t.i=i,t.r=ru.fromBuffer(n),t.s=ru.fromBuffer(o),t};it.fromDER=it.fromBuffer=function(e,t){var r=it.parseDER(e,t),i=new it;return i.r=r.r,i.s=r.s,i};it.fromTxFormat=function(e){var t=e.readUInt8(e.length-1),r=e.slice(0,e.length-1),i=it.fromDER(r,!1);return i.nhashtype=t,i};it.fromString=function(e){var t=f.Buffer.from(e,"hex");return it.fromDER(t)};function w2(e,t){xi.checkArgument(t.length>0,new Error("Length of "+e+" is zero")),xi.checkArgument(!(t[0]&128),new Error("Value of "+e+" is negative")),xi.checkArgument(!(t.length>1&&t[0]===0&&!(t[1]&128)),new Error("Value of "+e+" is excessively padded"))}it.parseDER=function(e,t){xi.checkArgument(f.Buffer.isBuffer(e),new Error("DER formatted signature should be a buffer")),pV.isUndefined(t)&&(t=!0);var r=e[0];xi.checkArgument(r===48,new Error("Header byte should be 0x30"));var i=e[1],n=e.slice(2).length;xi.checkArgument(!t||i===n,new Error("Length byte should length of what follows")),i=i<n?i:n;var o=e[2];xi.checkArgument(o===2,new Error("Integer byte for r should be 0x02"));var a=e[3],s=e.slice(4,4+a),u=ru.fromBuffer(s),c=e[4]===0;xi.checkArgument(a===s.length,new Error("Length of r incorrect"));var l=e[4+a+0];xi.checkArgument(l===2,new Error("Integer byte for s should be 0x02"));var p=e[4+a+1],d=e.slice(4+a+2,4+a+2+p),v=ru.fromBuffer(d),_=e[4+a+2]===0;xi.checkArgument(p===d.length,new Error("Length of s incorrect"));var I=4+a+2+p;xi.checkArgument(i===I-2,new Error("Length of signature incorrect")),t&&(w2("r",s),w2("s",d));var R={header:r,length:i,rheader:o,rlength:a,rneg:c,rbuf:s,r:u,sheader:l,slength:p,sneg:_,sbuf:d,s:v};return R};it.prototype.toCompact=function(e,t){if(e=typeof e=="number"?e:this.i,t=typeof t=="boolean"?t:this.compressed,!(e===0||e===1||e===2||e===3))throw new Error("i must be equal to 0, 1, 2, or 3");var r=e+27+4;t===!1&&(r=r-4);var i=f.Buffer.from([r]),n=this.r.toBuffer({size:32}),o=this.s.toBuffer({size:32});return f.Buffer.concat([i,n,o])};it.prototype.toBuffer=it.prototype.toDER=function(){var e=this.r.toBuffer(),t=this.s.toBuffer(),r=!!(e[0]&128),i=!!(t[0]&128),n=r?f.Buffer.concat([f.Buffer.from([0]),e]):e,o=i?f.Buffer.concat([f.Buffer.from([0]),t]):t,a=n.length,s=o.length,u=2+a+2+s,c=2,l=2,p=48,d=f.Buffer.concat([f.Buffer.from([p,u,c,a]),n,f.Buffer.from([l,s]),o]);return d};it.prototype.toString=function(){var e=this.toDER();return e.toString("hex")};it.isTxDER=function(e){if(e.length<9||e.length>73||e[0]!==48||e[1]!==e.length-3)return!1;var t=e[3];if(5+t>=e.length)return!1;var r=e[5+t];if(t+r+7!==e.length)return!1;var i=e.slice(4);if(e[2]!==2||t===0||i[0]&128||t>1&&i[0]===0&&!(i[1]&128))return!1;var n=e.slice(6+t);return!(e[6+t-2]!==2||r===0||n[0]&128||r>1&&n[0]===0&&!(n[1]&128))};it.prototype.hasLowS=function(){return!(this.s.lt(new ru(1))||this.s.gt(new ru("7FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF5D576E7357A4501DDFE92F46681B20A0","hex")))};it.prototype.hasDefinedHashtype=function(){if(!gV.isNaturalNumber(this.nhashtype))return!1;var e=this.nhashtype&31;return!(e<it.SIGHASH_ALL||e>it.SIGHASH_SINGLE)};it.prototype.toTxFormat=function(){var e=this.toDER(),t=f.Buffer.alloc(1);return t.writeUInt8(this.nhashtype,0),f.Buffer.concat([e,t])};it.SIGHASH_ALL=1;it.SIGHASH_NONE=2;it.SIGHASH_SINGLE=3;it.SIGHASH_CHRONICLE=32;it.SIGHASH_FORKID=64;it.SIGHASH_ANYONECANPAY=128;it.prototype.isCanonical=function(){var e=un(),t=e.getN().shrn(1);return this.s.lte(t)};it.prototype.toCanonical=function(){if(this.isCanonical())return new it({r:this.r,s:this.s,i:this.i,compressed:this.compressed,nhashtype:this.nhashtype});var e=un(),t=e.getN(),r=t.sub(this.s);return new it({r:this.r,s:r,i:this.i,compressed:this.compressed,nhashtype:this.nhashtype})};it.prototype.validate=function(){if(!this.r||!this.s)throw new Error("Signature missing r or s component");if(this.r.isZero())throw new Error("Signature r component is zero");if(this.s.isZero())throw new Error("Signature s component is zero");var e=un(),t=e.getN();if(this.r.gte(t))throw new Error("Signature r component >= curve order");if(this.s.gte(t))throw new Error("Signature s component >= curve order");if(this.r.isNeg())throw new Error("Signature r component is negative");if(this.s.isNeg())throw new Error("Signature s component is negative");return!0};it.prototype.isValid=function(){try{return this.validate(),!0}catch{return!1}};it.prototype.applySecurityPatches=function(){var e=un(),t=e.getN(),r=t.shrn(1);if(this.r.isZero()||this.s.isZero())throw new Error("Invalid signature: zero r or s");if(this.r.gte(t)||this.s.gte(t))throw new Error("Invalid signature: out of range");if(this.s.gt(r))throw new Error("Invalid signature: non-canonical (high) s");return this};S2.exports=it});var x2=T((nae,E2)=>{"use strict";g();var mg=nr(),oa=Ie(),Ar=E2.exports;Ar.sha1=function(e){return oa.checkArgument(f.Buffer.isBuffer(e)),mg.createHash("sha1").update(e).digest()};Ar.sha1.blocksize=512;Ar.sha256=function(e){return oa.checkArgument(f.Buffer.isBuffer(e)),mg.createHash("sha256").update(e).digest()};Ar.sha256.blocksize=512;Ar.sha256sha256=function(e){return oa.checkArgument(f.Buffer.isBuffer(e)),Ar.sha256(Ar.sha256(e))};Ar.ripemd160=function(e){return oa.checkArgument(f.Buffer.isBuffer(e)),mg.createHash("ripemd160").update(e).digest()};Ar.sha256ripemd160=function(e){return oa.checkArgument(f.Buffer.isBuffer(e)),Ar.ripemd160(Ar.sha256(e))};Ar.sha512=function(e){return oa.checkArgument(f.Buffer.isBuffer(e)),mg.createHash("sha512").update(e).digest()};Ar.sha512.blocksize=1024;Ar.hmac=function(e,t,r){oa.checkArgument(f.Buffer.isBuffer(t)),oa.checkArgument(f.Buffer.isBuffer(r)),oa.checkArgument(e.blocksize);var i=e.blocksize/8;if(r.length>i)r=e(r);else if(r.length<i){var n=f.Buffer.alloc(i);n.fill(0),r.copy(n),r=n}var o=f.Buffer.alloc(i);o.fill(92);var a=f.Buffer.alloc(i);a.fill(54);for(var s=f.Buffer.alloc(i),u=f.Buffer.alloc(i),c=0;c<i;c++)s[c]=o[c]^r[c],u[c]=a[c]^r[c];return e(f.Buffer.concat([s,e(f.Buffer.concat([u,t]))]))};Ar.sha256hmac=function(e,t){return Ar.hmac(Ar.sha256,e,t)};Ar.sha512hmac=function(e,t){return Ar.hmac(Ar.sha512,e,t)}});var k2={};Hf(k2,{_MD5:()=>_g,_RIPEMD160:()=>wg,_SHA1:()=>bg,md5:()=>_V,ripemd160:()=>AV,sha1:()=>mV});function O2(e,t,r,i){return e===0?t^r^i:e===1?t&r|~t&i:e===2?(t|~r)^i:e===3?t&i|r&~i:t^(r|~i)}var Tc,Ya,bg,mV,vV,yV,vg,Db,bV,_g,_V,wV,I2,SV,A2,T2,P2,R2,EV,xV,OV,IV,yg,wg,AV,B2=Dr(()=>{g();ub();Qo();Tc=Uint32Array.from([1732584193,4023233417,2562383102,271733878,3285377520]),Ya=new Uint32Array(80),bg=class extends ea{constructor(){super(64,20,8,!1);ee(this,"A",Tc[0]|0);ee(this,"B",Tc[1]|0);ee(this,"C",Tc[2]|0);ee(this,"D",Tc[3]|0);ee(this,"E",Tc[4]|0)}get(){let{A:r,B:i,C:n,D:o,E:a}=this;return[r,i,n,o,a]}set(r,i,n,o,a){this.A=r|0,this.B=i|0,this.C=n|0,this.D=o|0,this.E=a|0}_cloneInto(r){return(r||(r=new this.constructor)).set(...this.get()),this._cloneIntoMeta(r)}process(r,i){for(let c=0;c<16;c++,i+=4)Ya[c]=r.getUint32(i,!1);for(let c=16;c<80;c++)Ya[c]=Xo(Ya[c-3]^Ya[c-8]^Ya[c-14]^Ya[c-16],1);let{A:n,B:o,C:a,D:s,E:u}=this;for(let c=0;c<80;c++){let l,p;c<20?(l=vc(o,a,s),p=1518500249):c<40?(l=o^a^s,p=1859775393):c<60?(l=Wp(o,a,s),p=2400959708):(l=o^a^s,p=3395469782);let d=Xo(n,5)+l+u+p+Ya[c]|0;u=s,s=a,a=Xo(o,30),o=n,n=d}n=n+this.A|0,o=o+this.B|0,a=a+this.C|0,s=s+this.D|0,u=u+this.E|0,this.set(n,o,a,s,u)}roundClean(){wi(Ya)}destroy(){this.destroyed=!0,this.set(0,0,0,0,0),wi(this.buffer)}},mV=An(()=>new bg),vV=Math.pow(2,32),yV=Array.from({length:64},(e,t)=>Math.floor(vV*Math.abs(Math.sin(t+1)))),vg=Tc.slice(0,4),Db=new Uint32Array(16),bV=(()=>{let e=[[7,12,17,22],[5,9,14,20],[4,11,16,23],[6,10,15,21]];return Uint8Array.from({length:64},(t,r)=>e[Math.floor(r/16)][r%4])})(),_g=class extends ea{constructor(){super(64,16,8,!0);ee(this,"A",vg[0]|0);ee(this,"B",vg[1]|0);ee(this,"C",vg[2]|0);ee(this,"D",vg[3]|0)}get(){let{A:r,B:i,C:n,D:o}=this;return[r,i,n,o]}set(r,i,n,o){this.A=r|0,this.B=i|0,this.C=n|0,this.D=o|0}_cloneInto(r){return(r||(r=new this.constructor)).set(...this.get()),this._cloneIntoMeta(r)}process(r,i){for(let u=0;u<16;u++,i+=4)Db[u]=r.getUint32(i,!0);let{A:n,B:o,C:a,D:s}=this;for(let u=0;u<64;u++){let c,l;u<16?(c=vc(o,a,s),l=u):u<32?(c=vc(s,o,a),l=(5*u+1)%16):u<48?(c=o^a^s,l=(3*u+5)%16):(c=a^(o|~s),l=7*u%16),c=c+n+yV[u]+Db[l],n=s,s=a,a=o,o=o+Xo(c,bV[u])}n=n+this.A|0,o=o+this.B|0,a=a+this.C|0,s=s+this.D|0,this.set(n,o,a,s)}roundClean(){wi(Db)}destroy(){this.destroyed=!0,this.set(0,0,0,0),wi(this.buffer)}},_V=An(()=>new _g),wV=Uint8Array.from([7,4,13,1,10,6,15,3,12,0,9,5,2,14,11,8]),I2=Uint8Array.from(new Array(16).fill(0).map((e,t)=>t)),SV=I2.map(e=>(9*e+5)%16),A2=(()=>{let r=[[I2],[SV]];for(let i=0;i<4;i++)for(let n of r)n.push(n[i].map(o=>wV[o]));return r})(),T2=A2[0],P2=A2[1],R2=[[11,14,15,12,5,8,7,9,11,13,14,15,6,7,9,8],[12,13,11,15,6,9,9,7,12,15,11,13,7,8,7,7],[13,15,14,11,7,7,6,8,13,14,13,12,5,5,6,9],[14,11,12,14,8,6,5,5,15,12,15,14,9,9,8,6],[15,12,13,13,9,5,8,6,14,11,12,11,8,6,5,5]].map(e=>Uint8Array.from(e)),EV=T2.map((e,t)=>e.map(r=>R2[t][r])),xV=P2.map((e,t)=>e.map(r=>R2[t][r])),OV=Uint32Array.from([0,1518500249,1859775393,2400959708,2840853838]),IV=Uint32Array.from([1352829926,1548603684,1836072691,2053994217,0]);yg=new Uint32Array(16),wg=class extends ea{constructor(){super(64,20,8,!0);ee(this,"h0",1732584193);ee(this,"h1",-271733879);ee(this,"h2",-1732584194);ee(this,"h3",271733878);ee(this,"h4",-1009589776)}get(){let{h0:r,h1:i,h2:n,h3:o,h4:a}=this;return[r,i,n,o,a]}set(r,i,n,o,a){this.h0=r|0,this.h1=i|0,this.h2=n|0,this.h3=o|0,this.h4=a|0}_cloneInto(r){return(r||(r=new this.constructor)).set(...this.get()),this._cloneIntoMeta(r)}process(r,i){for(let _=0;_<16;_++,i+=4)yg[_]=r.getUint32(i,!0);let n=this.h0|0,o=n,a=this.h1|0,s=a,u=this.h2|0,c=u,l=this.h3|0,p=l,d=this.h4|0,v=d;for(let _=0;_<5;_++){let I=4-_,R=OV[_],k=IV[_],q=T2[_],z=P2[_],A=EV[_],B=xV[_];for(let M=0;M<16;M++){let F=Xo(n+O2(_,a,u,l)+yg[q[M]]+R,A[M])+d|0;n=d,d=l,l=Xo(u,10)|0,u=a,a=F}for(let M=0;M<16;M++){let F=Xo(o+O2(I,s,c,p)+yg[z[M]]+k,B[M])+v|0;o=v,v=p,p=Xo(c,10)|0,c=s,s=F}}this.set(this.h1+u+p|0,this.h2+l+v|0,this.h3+d+o|0,this.h4+n+s|0,this.h0+a+c|0)}roundClean(){wi(yg)}destroy(){this.destroyed=!0,wi(this.buffer),this.set(0,0,0,0,0)}},AV=An(()=>new wg)});var C2=T((fae,N2)=>{"use strict";g();var{sha256:TV,sha512:PV}=(Al(),en(tg)),{sha1:RV,ripemd160:kV}=(B2(),en(k2)),aa=Ie(),Tr=N2.exports;Tr.sha1=function(e){return aa.checkArgument(f.Buffer.isBuffer(e)),f.Buffer.from(RV(e))};Tr.sha1.blocksize=512;Tr.sha256=function(e){return aa.checkArgument(f.Buffer.isBuffer(e)),f.Buffer.from(TV(e))};Tr.sha256.blocksize=512;Tr.sha256sha256=function(e){return aa.checkArgument(f.Buffer.isBuffer(e)),Tr.sha256(Tr.sha256(e))};Tr.ripemd160=function(e){return aa.checkArgument(f.Buffer.isBuffer(e)),f.Buffer.from(kV(e))};Tr.sha256ripemd160=function(e){return aa.checkArgument(f.Buffer.isBuffer(e)),Tr.ripemd160(Tr.sha256(e))};Tr.sha512=function(e){return aa.checkArgument(f.Buffer.isBuffer(e)),f.Buffer.from(PV(e))};Tr.sha512.blocksize=1024;Tr.hmac=function(e,t,r){aa.checkArgument(f.Buffer.isBuffer(t)),aa.checkArgument(f.Buffer.isBuffer(r)),aa.checkArgument(e.blocksize);var i=e.blocksize/8;if(r.length>i)r=e(r);else if(r.length<i){var n=f.Buffer.alloc(i);n.fill(0),r.copy(n),r=n}var o=f.Buffer.alloc(i);o.fill(92);var a=f.Buffer.alloc(i);a.fill(54);for(var s=f.Buffer.alloc(i),u=f.Buffer.alloc(i),c=0;c<i;c++)s[c]=o[c]^r[c],u[c]=a[c]^r[c];return e(f.Buffer.concat([s,e(f.Buffer.concat([u,t]))]))};Tr.sha256hmac=function(e,t){return Tr.hmac(Tr.sha256,e,t)};Tr.sha512hmac=function(e,t){return Tr.hmac(Tr.sha512,e,t)}});var Le=T((hae,M2)=>{"use strict";g();var L2={sha1:"a9993e364706816aba3e25717850c26c9cd0d89d",sha256:"ba7816bf8f01cfea414140de5dae2223b00361a396177a9cb410ff61f20015ad",sha512:"ddaf35a193617abacc417349ae20413112e6fa4e89a97ea20a9eeee64b55d39a2192992a274fc1a836ba3c23a3feebbd454d4423643ce80e2a9ac94fa54ca49f",ripemd160:"8eb208f7e05d987a9b044a8e98c6b087f15a0bfc"};function BV(){var e;try{e=nr()}catch{return!1}if(!e||typeof e.createHash!="function")return!1;for(var t=Object.keys(L2),r=0;r<t.length;r++){var i=t[r];try{if(e.createHash(i).update("abc").digest("hex")!==L2[i])return!1}catch{return!1}}return!0}M2.exports=BV()?x2():C2()});var ca=T((pae,q2)=>{"use strict";g();var sa=at(),ql=ni(),iu=[],Ul={};function D2(){}D2.prototype.toString=function(){return this.name};function Fl(e,t){if(~iu.indexOf(e))return e;if(t){sa.isArray(t)||(t=[t]);for(var r=0;r<iu.length;r++){var i=iu[r],n=sa.pick(i,t),o=sa.values(n);if(~o.indexOf(e))return i}return}return Ul[e]}function Sg(e){for(var t=[],r=0;r<e.length;r++)t.push(e.charCodeAt(r)&31);return t}function jl(e){var t=new D2;ql.defineImmutable(t,{name:e.name,alias:e.alias,pubkeyhash:e.pubkeyhash,privatekey:e.privatekey,scripthash:e.scripthash,xpubkey:e.xpubkey,xprivkey:e.xprivkey});var r=e.indexBy||Object.keys(e);return e.cashAddrPrefix&&sa.extend(t,{cashAddrPrefix:e.cashAddrPrefix,cashAddrPrefixArray:Sg(e.cashAddrPrefix)}),e.networkMagic&&sa.extend(t,{networkMagic:ql.integerAsBuffer(e.networkMagic)}),e.port&&sa.extend(t,{port:e.port}),e.dnsSeeds&&sa.extend(t,{dnsSeeds:e.dnsSeeds}),iu.push(t),NV(t,r),t}function NV(e,t){for(var r=0;r<t.length;r++){var i=t[r],n=e[i];!sa.isUndefined(n)&&!sa.isObject(n)&&(Ul[n]=e)}}function CV(e,t){for(var r=0;r<t.length;r++){var i=t[r];Ul[i]===e&&delete Ul[i]}}function LV(e){for(var t=0;t<iu.length;t++)iu[t]===e&&iu.splice(t,1);CV(e,Object.keys(Ul))}var Eg={livenet:3823236072,testnet:4108710900,regtest:3669344250,stn:4224632057},H2=["seed.bitcoinsv.org","seed.bitcoinunlimited.info"],Za={PORT:18333,NETWORK_MAGIC:Eg.testnet,DNS_SEEDS:H2,PREFIX:"testnet",CASHADDRPREFIX:"bchtest"},ua={PORT:18444,NETWORK_MAGIC:Eg.regtest,DNS_SEEDS:[],PREFIX:"regtest",CASHADDRPREFIX:"bchreg"},$a={PORT:9333,NETWORK_MAGIC:Eg.stn,DNS_SEEDS:["stn-seed.bitcoinsv.io"],PREFIX:"stn",CASHADDRPREFIX:"bsvstn"},MV={name:"livenet",alias:"mainnet",prefix:"bitcoin",cashAddrPrefix:"bitcoincash",pubkeyhash:0,privatekey:128,scripthash:5,xpubkey:76067358,xprivkey:76066276,networkMagic:Eg.livenet,port:8333,dnsSeeds:H2},DV={name:"testnet",prefix:Za.PREFIX,cashAddrPrefix:Za.CASHADDRPREFIX,pubkeyhash:111,privatekey:239,scripthash:196,xpubkey:70617039,xprivkey:70615956,networkMagic:Za.NETWORK_MAGIC},HV={name:"regtest",prefix:ua.PREFIX,cashAddrPrefix:ua.CASHADDRPREFIX,pubkeyhash:111,privatekey:239,scripthash:196,xpubkey:70617039,xprivkey:70615956,networkMagic:ua.NETWORK_MAGIC,port:ua.PORT,dnsSeeds:[],indexBy:["port","name","cashAddrPrefix","networkMagic"]},qV={name:"stn",prefix:$a.PREFIX,cashAddrPrefix:$a.CASHADDRPREFIX,pubkeyhash:111,privatekey:239,scripthash:196,xpubkey:70617039,xprivkey:70615956,networkMagic:$a.NETWORK_MAGIC,indexBy:["port","name","cashAddrPrefix","networkMagic"]};jl(DV);jl(qV);jl(HV);jl(MV);var Hb=Fl("livenet"),UV=Fl("regtest"),fo=Fl("testnet"),FV=Fl("stn");Object.defineProperty(fo,"port",{enumerable:!0,configurable:!1,get:function(){return this.regtestEnabled?ua.PORT:this.stnEnabled?$a.PORT:Za.PORT}});Object.defineProperty(fo,"networkMagic",{enumerable:!0,configurable:!1,get:function(){return this.regtestEnabled?ql.integerAsBuffer(ua.NETWORK_MAGIC):this.stnEnabled?ql.integerAsBuffer($a.NETWORK_MAGIC):ql.integerAsBuffer(Za.NETWORK_MAGIC)}});Object.defineProperty(fo,"dnsSeeds",{enumerable:!0,configurable:!1,get:function(){return this.regtestEnabled?ua.DNS_SEEDS:this.stnEnabled?$a.DNS_SEEDS:Za.DNS_SEEDS}});Object.defineProperty(fo,"cashAddrPrefix",{enumerable:!0,configurable:!1,get:function(){return this.regtestEnabled?ua.CASHADDRPREFIX:this.stnEnabled?$a.CASHADDRPREFIX:Za.CASHADDRPREFIX}});Object.defineProperty(fo,"cashAddrPrefixArray",{enumerable:!0,configurable:!1,get:function(){return this.regtestEnabled?Sg(ua.CASHADDRPREFIX):this.stnEnabled?Sg($a.CASHADDRPREFIX):Sg(Za.CASHADDRPREFIX)}});function jV(){fo.regtestEnabled=!0}function zV(){fo.regtestEnabled=!1}function KV(){fo.stnEnabled=!0}function VV(){fo.stnEnabled=!1}q2.exports={add:jl,remove:LV,defaultNetwork:Hb,livenet:Hb,mainnet:Hb,testnet:fo,regtest:UV,stn:FV,get:Fl,enableRegtest:jV,disableRegtest:zV,enableStn:KV,disableStn:VV}});var Pc=T((mae,z2)=>{"use strict";g();var U2=at(),xg=pc(),F2=rr(),j2=Le().sha256sha256,ar=function e(t){if(!(this instanceof e))return new e(t);if(f.Buffer.isBuffer(t)){var r=t;this.fromBuffer(r)}else if(typeof t=="string"){var i=t;this.fromString(i)}};ar.prototype.set=function(e){return this.buf=e.buf||this.buf||void 0,this};ar.validChecksum=function(t,r){return U2.isString(t)&&(t=F2.Buffer.from(xg.decode(t))),U2.isString(r)&&(r=F2.Buffer.from(xg.decode(r))),r||(r=t.slice(-4),t=t.slice(0,-4)),ar.checksum(t).toString("hex")===r.toString("hex")};ar.decode=function(e){if(typeof e!="string")throw new Error("Input must be a string");var t=f.Buffer.from(xg.decode(e));if(t.length<4)throw new Error("Input string too short");var r=t.slice(0,-4),i=t.slice(-4),n=j2(r),o=n.slice(0,4);if(i.toString("hex")!==o.toString("hex"))throw new Error("Checksum mismatch");return r};ar.checksum=function(e){return j2(e).slice(0,4)};ar.encode=function(e){if(!f.Buffer.isBuffer(e))throw new Error("Input must be a buffer");var t=f.Buffer.alloc(e.length+4),r=ar.checksum(e);return e.copy(t),r.copy(t,e.length),xg.encode(t)};ar.prototype.fromBuffer=function(e){return this.buf=e,this};ar.fromBuffer=function(e){return new ar().fromBuffer(e)};ar.fromHex=function(e){return ar.fromBuffer(f.Buffer.from(e,"hex"))};ar.prototype.fromString=function(e){var t=ar.decode(e);return this.buf=t,this};ar.fromString=function(e){var t=ar.decode(e);return new ar(t)};ar.prototype.toBuffer=function(){return this.buf};ar.prototype.toHex=function(){return this.toBuffer().toString("hex")};ar.prototype.toString=function(){return ar.encode(this.buf)};z2.exports=ar});var Fb=T((yae,W2)=>{"use strict";g();function Xa(e){"@babel/helpers - typeof";return Xa=typeof Symbol=="function"&&typeof Symbol.iterator=="symbol"?function(t){return typeof t}:function(t){return t&&typeof Symbol=="function"&&t.constructor===Symbol&&t!==Symbol.prototype?"symbol":typeof t},Xa(e)}function K2(e,t){for(var r=0;r<t.length;r++){var i=t[r];i.enumerable=i.enumerable||!1,i.configurable=!0,"value"in i&&(i.writable=!0),Object.defineProperty(e,WV(i.key),i)}}function GV(e,t,r){return t&&K2(e.prototype,t),r&&K2(e,r),Object.defineProperty(e,"prototype",{writable:!1}),e}function WV(e){var t=YV(e,"string");return Xa(t)==="symbol"?t:String(t)}function YV(e,t){if(Xa(e)!=="object"||e===null)return e;var r=e[Symbol.toPrimitive];if(r!==void 0){var i=r.call(e,t||"default");if(Xa(i)!=="object")return i;throw new TypeError("@@toPrimitive must return a primitive value.")}return(t==="string"?String:Number)(e)}function ZV(e,t){if(!(e instanceof t))throw new TypeError("Cannot call a class as a function")}function $V(e,t){if(typeof t!="function"&&t!==null)throw new TypeError("Super expression must either be null or a function");e.prototype=Object.create(t&&t.prototype,{constructor:{value:e,writable:!0,configurable:!0}}),Object.defineProperty(e,"prototype",{writable:!1}),t&&Ub(e,t)}function Ub(e,t){return Ub=Object.setPrototypeOf?Object.setPrototypeOf.bind():function(i,n){return i.__proto__=n,i},Ub(e,t)}function XV(e){var t=eG();return function(){var i=Og(e),n;if(t){var o=Og(this).constructor;n=Reflect.construct(i,arguments,o)}else n=i.apply(this,arguments);return JV(this,n)}}function JV(e,t){if(t&&(Xa(t)==="object"||typeof t=="function"))return t;if(t!==void 0)throw new TypeError("Derived constructors may only return object or undefined");return QV(e)}function QV(e){if(e===void 0)throw new ReferenceError("this hasn't been initialised - super() hasn't been called");return e}function eG(){if(typeof Reflect>"u"||!Reflect.construct||Reflect.construct.sham)return!1;if(typeof Proxy=="function")return!0;try{return Boolean.prototype.valueOf.call(Reflect.construct(Boolean,[],function(){})),!0}catch{return!1}}function Og(e){return Og=Object.setPrototypeOf?Object.getPrototypeOf.bind():function(r){return r.__proto__||Object.getPrototypeOf(r)},Og(e)}var G2={},Rc,qb;function zl(e,t,r){r||(r=Error);function i(o,a,s){return typeof t=="string"?t:t(o,a,s)}var n=(function(o){$V(s,o);var a=XV(s);function s(u,c,l){var p;return ZV(this,s),p=a.call(this,i(u,c,l)),p.code=e,p}return GV(s)})(r);G2[e]=n}function V2(e,t){if(Array.isArray(e)){var r=e.length;return e=e.map(function(i){return String(i)}),r>2?"one of ".concat(t," ").concat(e.slice(0,r-1).join(", "),", or ")+e[r-1]:r===2?"one of ".concat(t," ").concat(e[0]," or ").concat(e[1]):"of ".concat(t," ").concat(e[0])}else return"of ".concat(t," ").concat(String(e))}function tG(e,t,r){return e.substr(!r||r<0?0:+r,t.length)===t}function rG(e,t,r){return(r===void 0||r>e.length)&&(r=e.length),e.substring(r-t.length,r)===t}function iG(e,t,r){return typeof r!="number"&&(r=0),r+t.length>e.length?!1:e.indexOf(t,r)!==-1}zl("ERR_AMBIGUOUS_ARGUMENT",'The "%s" argument is ambiguous. %s',TypeError);zl("ERR_INVALID_ARG_TYPE",function(e,t,r){Rc===void 0&&(Rc=fa()),Rc(typeof e=="string","'name' must be a string");var i;typeof t=="string"&&tG(t,"not ")?(i="must not be",t=t.replace(/^not /,"")):i="must be";var n;if(rG(e," argument"))n="The ".concat(e," ").concat(i," ").concat(V2(t,"type"));else{var o=iG(e,".")?"property":"argument";n='The "'.concat(e,'" ').concat(o," ").concat(i," ").concat(V2(t,"type"))}return n+=". Received type ".concat(Xa(r)),n},TypeError);zl("ERR_INVALID_ARG_VALUE",function(e,t){var r=arguments.length>2&&arguments[2]!==void 0?arguments[2]:"is invalid";qb===void 0&&(qb=nn());var i=qb.inspect(t);return i.length>128&&(i="".concat(i.slice(0,128),"...")),"The argument '".concat(e,"' ").concat(r,". Received ").concat(i)},TypeError,RangeError);zl("ERR_INVALID_RETURN_VALUE",function(e,t,r){var i;return r&&r.constructor&&r.constructor.name?i="instance of ".concat(r.constructor.name):i="type ".concat(Xa(r)),"Expected ".concat(e,' to be returned from the "').concat(t,'"')+" function but got ".concat(i,".")},TypeError);zl("ERR_MISSING_ARGS",function(){for(var e=arguments.length,t=new Array(e),r=0;r<e;r++)t[r]=arguments[r];Rc===void 0&&(Rc=fa()),Rc(t.length>0,"At least one arg needs to be specified");var i="The ",n=t.length;switch(t=t.map(function(o){return'"'.concat(o,'"')}),n){case 1:i+="".concat(t[0]," argument");break;case 2:i+="".concat(t[0]," and ").concat(t[1]," arguments");break;default:i+=t.slice(0,n-1).join(", "),i+=", and ".concat(t[n-1]," arguments");break}return"".concat(i," must be specified")},TypeError);W2.exports.codes=G2});var iR=T((_ae,rR)=>{"use strict";g();function Y2(e,t){var r=Object.keys(e);if(Object.getOwnPropertySymbols){var i=Object.getOwnPropertySymbols(e);t&&(i=i.filter(function(n){return Object.getOwnPropertyDescriptor(e,n).enumerable})),r.push.apply(r,i)}return r}function Z2(e){for(var t=1;t<arguments.length;t++){var r=arguments[t]!=null?arguments[t]:{};t%2?Y2(Object(r),!0).forEach(function(i){nG(e,i,r[i])}):Object.getOwnPropertyDescriptors?Object.defineProperties(e,Object.getOwnPropertyDescriptors(r)):Y2(Object(r)).forEach(function(i){Object.defineProperty(e,i,Object.getOwnPropertyDescriptor(r,i))})}return e}function nG(e,t,r){return t=Q2(t),t in e?Object.defineProperty(e,t,{value:r,enumerable:!0,configurable:!0,writable:!0}):e[t]=r,e}function oG(e,t){if(!(e instanceof t))throw new TypeError("Cannot call a class as a function")}function $2(e,t){for(var r=0;r<t.length;r++){var i=t[r];i.enumerable=i.enumerable||!1,i.configurable=!0,"value"in i&&(i.writable=!0),Object.defineProperty(e,Q2(i.key),i)}}function aG(e,t,r){return t&&$2(e.prototype,t),r&&$2(e,r),Object.defineProperty(e,"prototype",{writable:!1}),e}function Q2(e){var t=sG(e,"string");return Bi(t)==="symbol"?t:String(t)}function sG(e,t){if(Bi(e)!=="object"||e===null)return e;var r=e[Symbol.toPrimitive];if(r!==void 0){var i=r.call(e,t||"default");if(Bi(i)!=="object")return i;throw new TypeError("@@toPrimitive must return a primitive value.")}return(t==="string"?String:Number)(e)}function uG(e,t){if(typeof t!="function"&&t!==null)throw new TypeError("Super expression must either be null or a function");e.prototype=Object.create(t&&t.prototype,{constructor:{value:e,writable:!0,configurable:!0}}),Object.defineProperty(e,"prototype",{writable:!1}),t&&Wl(e,t)}function cG(e){var t=tR();return function(){var i=Yl(e),n;if(t){var o=Yl(this).constructor;n=Reflect.construct(i,arguments,o)}else n=i.apply(this,arguments);return eR(this,n)}}function eR(e,t){if(t&&(Bi(t)==="object"||typeof t=="function"))return t;if(t!==void 0)throw new TypeError("Derived constructors may only return object or undefined");return jb(e)}function jb(e){if(e===void 0)throw new ReferenceError("this hasn't been initialised - super() hasn't been called");return e}function zb(e){var t=typeof Map=="function"?new Map:void 0;return zb=function(i){if(i===null||!fG(i))return i;if(typeof i!="function")throw new TypeError("Super expression must either be null or a function");if(typeof t<"u"){if(t.has(i))return t.get(i);t.set(i,n)}function n(){return Ig(i,arguments,Yl(this).constructor)}return n.prototype=Object.create(i.prototype,{constructor:{value:n,enumerable:!1,writable:!0,configurable:!0}}),Wl(n,i)},zb(e)}function Ig(e,t,r){return tR()?Ig=Reflect.construct.bind():Ig=function(n,o,a){var s=[null];s.push.apply(s,o);var u=Function.bind.apply(n,s),c=new u;return a&&Wl(c,a.prototype),c},Ig.apply(null,arguments)}function tR(){if(typeof Reflect>"u"||!Reflect.construct||Reflect.construct.sham)return!1;if(typeof Proxy=="function")return!0;try{return Boolean.prototype.valueOf.call(Reflect.construct(Boolean,[],function(){})),!0}catch{return!1}}function fG(e){return Function.toString.call(e).indexOf("[native code]")!==-1}function Wl(e,t){return Wl=Object.setPrototypeOf?Object.setPrototypeOf.bind():function(i,n){return i.__proto__=n,i},Wl(e,t)}function Yl(e){return Yl=Object.setPrototypeOf?Object.getPrototypeOf.bind():function(r){return r.__proto__||Object.getPrototypeOf(r)},Yl(e)}function Bi(e){"@babel/helpers - typeof";return Bi=typeof Symbol=="function"&&typeof Symbol.iterator=="symbol"?function(t){return typeof t}:function(t){return t&&typeof Symbol=="function"&&t.constructor===Symbol&&t!==Symbol.prototype?"symbol":typeof t},Bi(e)}var lG=nn(),Kb=lG.inspect,hG=Fb(),dG=hG.codes.ERR_INVALID_ARG_TYPE;function X2(e,t,r){return(r===void 0||r>e.length)&&(r=e.length),e.substring(r-t.length,r)===t}function pG(e,t){if(t=Math.floor(t),e.length==0||t==0)return"";var r=e.length*t;for(t=Math.floor(Math.log(t)/Math.log(2));t;)e+=e,t--;return e+=e.substring(0,r-e.length),e}var Pn="",Kl="",Vl="",oi="",nu={deepStrictEqual:"Expected values to be strictly deep-equal:",strictEqual:"Expected values to be strictly equal:",strictEqualObject:'Expected "actual" to be reference-equal to "expected":',deepEqual:"Expected values to be loosely deep-equal:",equal:"Expected values to be loosely equal:",notDeepStrictEqual:'Expected "actual" not to be strictly deep-equal to:',notStrictEqual:'Expected "actual" to be strictly unequal to:',notStrictEqualObject:'Expected "actual" not to be reference-equal to "expected":',notDeepEqual:'Expected "actual" not to be loosely deep-equal to:',notEqual:'Expected "actual" to be loosely unequal to:',notIdentical:"Values identical but not reference-equal:"},gG=10;function J2(e){var t=Object.keys(e),r=Object.create(Object.getPrototypeOf(e));return t.forEach(function(i){r[i]=e[i]}),Object.defineProperty(r,"message",{value:e.message}),r}function Gl(e){return Kb(e,{compact:!1,customInspect:!1,depth:1e3,maxArrayLength:1/0,showHidden:!1,breakLength:1/0,showProxy:!1,sorted:!0,getters:!0})}function mG(e,t,r){var i="",n="",o=0,a="",s=!1,u=Gl(e),c=u.split(`
|
|
14
14
|
`),l=Gl(t).split(`
|
|
@@ -66,7 +66,7 @@ In order to be iterable, non-array objects must have a [Symbol.iterator]() metho
|
|
|
66
66
|
`))}throw i}};function kk(e,t,r,i,n){if(!qg(t))throw new kc("regexp","RegExp",t);var o=n==="match";if(typeof e!="string"||Ug(t,e)!==o){if(r instanceof Error)throw r;var a=!r;r=r||(typeof e!="string"?'The "string" argument must be of type string. Received type '+"".concat(Rn(e)," (").concat(Hg(e),")"):(o?"The input did not match the regular expression ":"The input was expected to not match the regular expression ")+"".concat(Hg(t),`. Input:
|
|
67
67
|
|
|
68
68
|
`).concat(Hg(e),`
|
|
69
|
-
`));var s=new es({actual:e,expected:t,message:r,operator:n,stackStartFn:i});throw s.generatedMessage=a,s}}qt.match=function e(t,r,i){kk(t,r,i,e,"match")};qt.doesNotMatch=function e(t,r,i){kk(t,r,i,e,"doesNotMatch")};function Bk(){for(var e=arguments.length,t=new Array(e),r=0;r<e;r++)t[r]=arguments[r];xk.apply(void 0,[Bk,t.length].concat(t))}qt.strict=T7(Bk,qt,{equal:qt.strictEqual,deepEqual:qt.deepStrictEqual,notEqual:qt.notStrictEqual,notDeepEqual:qt.notDeepStrictEqual});qt.strict.strict=qt.strict});var lo=T((rse,Lk)=>{"use strict";g();var rh=at(),Ck=Ie(),Bc=Ke(),hr=function e(t){if(!(this instanceof e))return new e(t);if(!rh.isUndefined(t))if(f.Buffer.isBuffer(t))this.set({buf:t});else if(rh.isString(t)){var r=f.Buffer.from(t,"hex");if(r.length*2!==t.length)throw new TypeError("Invalid hex string");this.set({buf:r})}else if(rh.isObject(t)){var i=t;this.set(i)}else throw new TypeError("Unrecognized argument for BufferReader")};hr.prototype.set=function(e){return this.buf=e.buf||this.buf||void 0,this.pos=e.pos||this.pos||0,this};hr.prototype.eof=function(){return this.pos>=this.buf.length};hr.prototype.finished=hr.prototype.eof;hr.prototype.read=function(e){Ck.checkArgument(!rh.isUndefined(e),"Must specify a length");var t=this.buf.slice(this.pos,this.pos+e);return this.pos=this.pos+e,t};hr.prototype.readAll=function(){var e=this.buf.slice(this.pos,this.buf.length);return this.pos=this.buf.length,e};hr.prototype.readUInt8=function(){var e=this.buf.readUInt8(this.pos);return this.pos=this.pos+1,e};hr.prototype.readUInt16BE=function(){var e=this.buf.readUInt16BE(this.pos);return this.pos=this.pos+2,e};hr.prototype.readUInt16LE=function(){var e=this.buf.readUInt16LE(this.pos);return this.pos=this.pos+2,e};hr.prototype.readUInt32BE=function(){var e=this.buf.readUInt32BE(this.pos);return this.pos=this.pos+4,e};hr.prototype.readUInt32LE=function(){var e=this.buf.readUInt32LE(this.pos);return this.pos=this.pos+4,e};hr.prototype.readInt32LE=function(){var e=this.buf.readInt32LE(this.pos);return this.pos=this.pos+4,e};hr.prototype.readUInt64BEBN=function(){var e=this.buf.slice(this.pos,this.pos+8),t=Bc.fromBuffer(e);return this.pos=this.pos+8,t};hr.prototype.readUInt64LEBN=function(){var e=this.buf.readUInt32LE(this.pos),t=this.buf.readUInt32LE(this.pos+4),r=t*4294967296+e,i;if(r<=9007199254740991)i=new Bc(r);else{var n=Array.prototype.slice.call(this.buf,this.pos,this.pos+8);i=new Bc(n,10,"le")}return this.pos=this.pos+8,i};hr.prototype.readVarintNum=function(){var e=this.readUInt8();switch(e){case 253:return this.readUInt16LE();case 254:return this.readUInt32LE();case 255:var t=this.readUInt64LEBN(),r=t.toNumber();if(r<=Math.pow(2,53))return r;throw new Error("number too large to retain precision - use readVarintBN");default:return e}};hr.prototype.readVarLengthBuffer=function(){var e=this.readVarintNum(),t=this.read(e);return Ck.checkState(t.length===e,"Invalid length while reading varlength buffer. Expected to read: "+e+" and read "+t.length),t};hr.prototype.readVarintBuf=function(){var e=this.buf.readUInt8(this.pos);switch(e){case 253:return this.read(3);case 254:return this.read(5);case 255:return this.read(9);default:return this.read(1)}};hr.prototype.readVarintBN=function(){var e=this.readUInt8();switch(e){case 253:return new Bc(this.readUInt16LE());case 254:return new Bc(this.readUInt32LE());case 255:return this.readUInt64LEBN();default:return new Bc(e)}};hr.prototype.reverse=function(){for(var e=f.Buffer.alloc(this.buf.length),t=0;t<e.length;t++)e[t]=this.buf[this.buf.length-1-t];return this.buf=e,this};hr.prototype.readReverse=function(e){rh.isUndefined(e)&&(e=this.buf.length);var t=this.buf.slice(this.pos,this.pos+e);return this.pos=this.pos+e,f.Buffer.from(t).reverse()};Lk.exports=hr});var Pr=T((nse,Mk)=>{"use strict";g();var Nc=at(),ih=Ie(),R7=ni();function dt(e){if(!(this instanceof dt))return new dt(e);var t;if(Nc.isNumber(e))t=e;else if(Nc.isString(e))t=dt.map[e];else throw new TypeError('Unrecognized num type: "'+typeof e+'" for Opcode');return R7.defineImmutable(this,{num:t}),this}dt.fromBuffer=function(e){return ih.checkArgument(f.Buffer.isBuffer(e)),new dt(+("0x"+e.toString("hex")))};dt.fromNumber=function(e){return ih.checkArgument(Nc.isNumber(e)),new dt(e)};dt.fromString=function(e){ih.checkArgument(Nc.isString(e));var t=dt.map[e];if(typeof t>"u")throw new TypeError("Invalid opcodestr");return new dt(t)};dt.prototype.toHex=function(){return this.num.toString(16)};dt.prototype.toBuffer=function(){return f.Buffer.from(this.toHex(),"hex")};dt.prototype.toNumber=function(){return this.num};dt.prototype.toString=function(){var e=dt.reverseMap[this.num];if(typeof e>"u")throw new Error("Opcode does not have a string representation");return e};dt.smallInt=function(e){return ih.checkArgument(Nc.isNumber(e),"Invalid Argument: n should be number"),ih.checkArgument(e>=0&&e<=16,"Invalid Argument: n must be between 0 and 16"),e===0?dt("OP_0"):new dt(dt.map.OP_1+e-1)};dt.map={OP_FALSE:0,OP_0:0,OP_PUSHDATA1:76,OP_PUSHDATA2:77,OP_PUSHDATA4:78,OP_1NEGATE:79,OP_RESERVED:80,OP_TRUE:81,OP_1:81,OP_2:82,OP_3:83,OP_4:84,OP_5:85,OP_6:86,OP_7:87,OP_8:88,OP_9:89,OP_10:90,OP_11:91,OP_12:92,OP_13:93,OP_14:94,OP_15:95,OP_16:96,OP_NOP:97,OP_VER:98,OP_IF:99,OP_NOTIF:100,OP_VERIF:101,OP_VERNOTIF:102,OP_ELSE:103,OP_ENDIF:104,OP_VERIFY:105,OP_RETURN:106,OP_TOALTSTACK:107,OP_FROMALTSTACK:108,OP_2DROP:109,OP_2DUP:110,OP_3DUP:111,OP_2OVER:112,OP_2ROT:113,OP_2SWAP:114,OP_IFDUP:115,OP_DEPTH:116,OP_DROP:117,OP_DUP:118,OP_NIP:119,OP_OVER:120,OP_PICK:121,OP_ROLL:122,OP_ROT:123,OP_SWAP:124,OP_TUCK:125,OP_CAT:126,OP_SPLIT:127,OP_NUM2BIN:128,OP_BIN2NUM:129,OP_SIZE:130,OP_INVERT:131,OP_AND:132,OP_OR:133,OP_XOR:134,OP_EQUAL:135,OP_EQUALVERIFY:136,OP_RESERVED1:137,OP_RESERVED2:138,OP_1ADD:139,OP_1SUB:140,OP_2MUL:141,OP_2DIV:142,OP_NEGATE:143,OP_ABS:144,OP_NOT:145,OP_0NOTEQUAL:146,OP_ADD:147,OP_SUB:148,OP_MUL:149,OP_DIV:150,OP_MOD:151,OP_LSHIFT:152,OP_RSHIFT:153,OP_BOOLAND:154,OP_BOOLOR:155,OP_NUMEQUAL:156,OP_NUMEQUALVERIFY:157,OP_NUMNOTEQUAL:158,OP_LESSTHAN:159,OP_GREATERTHAN:160,OP_LESSTHANOREQUAL:161,OP_GREATERTHANOREQUAL:162,OP_MIN:163,OP_MAX:164,OP_WITHIN:165,OP_RIPEMD160:166,OP_SHA1:167,OP_SHA256:168,OP_HASH160:169,OP_HASH256:170,OP_CODESEPARATOR:171,OP_CHECKSIG:172,OP_CHECKSIGVERIFY:173,OP_CHECKMULTISIG:174,OP_CHECKMULTISIGVERIFY:175,OP_CHECKLOCKTIMEVERIFY:177,OP_CHECKSEQUENCEVERIFY:178,OP_NOP1:176,OP_NOP2:177,OP_NOP3:178,OP_SUBSTR:179,OP_LEFT:180,OP_RIGHT:181,OP_LSHIFTNUM:182,OP_RSHIFTNUM:183,OP_NOP9:184,OP_NOP10:185,OP_PUBKEYHASH:253,OP_PUBKEY:254,OP_INVALIDOPCODE:255};dt.reverseMap=[];for(n_ in dt.map)dt.reverseMap[dt.map[n_]]=n_;var n_;Nc.extend(dt,dt.map);dt.isSmallIntOp=function(e){return e instanceof dt&&(e=e.toNumber()),e===dt.map.OP_0||e>=dt.map.OP_1&&e<=dt.map.OP_16};dt.prototype.inspect=function(){return"<Opcode: "+this.toString()+", hex: "+this.toHex()+", decimal: "+this.num+">"};Mk.exports=dt});var ts=T((ase,Hk)=>{"use strict";g();var o_=Object.create(null),a_=[],s_=!(typeof b.default<"u"&&b.default.env&&b.default.env.BSV_NO_DEPRECATION_WARNINGS==="1");function Dk(e,t){if(!e||typeof e.what!="string"||e.what==="")throw new TypeError(t+"() requires { what: string }")}function k7(e){var t="[@smartledger/bsv] "+e.what+" is deprecated";return e.since&&(t+=" since "+e.since),t+=".",e.why&&(t+=" "+e.why.charAt(0).toUpperCase()+e.why.slice(1)+"."),e.use&&(t+=" Use "+e.use+" instead."),t+=e.removeIn?" It will be removed in "+e.removeIn+".":" A removal version has not been set; it will not be removed in a 9.x release.",t}function la(e){if(!e||!e.what)throw new TypeError("deprecate() requires { what }");if(o_[e.what])return!1;o_[e.what]=!0;var t=k7(e);return a_.push({what:e.what,since:e.since||null,removeIn:e.removeIn||null,use:e.use||null,message:t}),s_&&console.warn(t),!0}la.fn=function(e,t){if(typeof e!="function")throw new TypeError("deprecate.fn() requires a function");Dk(t,"deprecate.fn");var r=function(){return la(t),e.apply(this,arguments)};return Object.defineProperty(r,"name",{value:e.name,configurable:!0}),Object.defineProperty(r,"length",{value:e.length,configurable:!0}),r.__wrapped=e,r.__deprecation=t,r};la.property=function(e,t,r,i){Dk(i,"deprecate.property");var n,o=!1;return Object.defineProperty(e,t,{configurable:!0,enumerable:!0,get:function(){return la(i),o||(n=r(),o=!0),n}}),e};la.fired=function(){return a_.slice()};la.setEnabled=function(e){s_=!!e};la.isEnabled=function(){return s_};la.reset=function(){o_=Object.create(null),a_.length=0};Hk.exports=la});var Kg=T((use,jk)=>{"use strict";g();var B7=fa(),Bn=Ni(),N7=lo(),u_=Le(),ce=Pr(),au=sr(),ou=gt(),qk=ca(),Gt=Ie(),st=at(),c_=pi(),C7=ts(),Uk=rr(),L7=ni(),$=function e(t){if(!(this instanceof e))return new e(t);if(this.chunks=[],f.Buffer.isBuffer(t))return e.fromBuffer(t);if(t instanceof Bn)return e.fromAddress(t);if(t instanceof e)return e.fromBuffer(t.toBuffer());if(st.isString(t))return e.fromString(t);st.isObject(t)&&st.isArray(t.chunks)&&this.set(t)};$.prototype.set=function(e){return Gt.checkArgument(st.isObject(e)),Gt.checkArgument(st.isArray(e.chunks)),this.chunks=e.chunks,this};$.fromBuffer=function(e){var t=new $;t.chunks=[];for(var r=new N7(e);!r.finished();)try{var i=r.readUInt8(),n,o;i>0&&i<ce.OP_PUSHDATA1?(n=i,t.chunks.push({buf:r.read(n),len:n,opcodenum:i})):i===ce.OP_PUSHDATA1?(n=r.readUInt8(),o=r.read(n),t.chunks.push({buf:o,len:n,opcodenum:i})):i===ce.OP_PUSHDATA2?(n=r.readUInt16LE(),o=r.read(n),t.chunks.push({buf:o,len:n,opcodenum:i})):i===ce.OP_PUSHDATA4?(n=r.readUInt32LE(),o=r.read(n),t.chunks.push({buf:o,len:n,opcodenum:i})):t.chunks.push({opcodenum:i})}catch(a){throw a instanceof RangeError?new c_.Script.InvalidBuffer(e.toString("hex")):a}return t};$.prototype.toBuffer=function(){var e=this.chunks,t=0,r,i,n;for(r=0;r<e.length;r++)i=e[r],n=i.opcodenum,t+=1,i.buf&&(n<ce.OP_PUSHDATA1?t+=zg(i.buf):n===ce.OP_PUSHDATA1?t+=1+zg(i.buf):n===ce.OP_PUSHDATA2?t+=2+zg(i.buf):n===ce.OP_PUSHDATA4&&(t+=4+zg(i.buf)));var o=f.Buffer.alloc(t),a=0;for(r=0;r<e.length;r++)i=e[r],n=i.opcodenum,a=o.writeUInt8(i.opcodenum,a),i.buf&&(n<ce.OP_PUSHDATA1?a+=i.buf.copy(o,a):n===ce.OP_PUSHDATA1?(a=o.writeUInt8(i.len,a),a+=i.buf.copy(o,a)):n===ce.OP_PUSHDATA2?(a=o.writeUInt16LE(i.len,a),a+=i.buf.copy(o,a)):n===ce.OP_PUSHDATA4&&(a=o.writeUInt32LE(i.len,a),a+=i.buf.copy(o,a)));return o};function zg(e){if(!f.Buffer.isBuffer(e))throw new B7.AssertionError({message:"chunk data must be a Buffer",actual:e,expected:"Buffer",operator:"isBuffer"});return e.length}function Fk(e){if(/^0x[0-9a-fA-F]{2}$/.test(e)){var t=parseInt(e.slice(2),16);return t>ce.OP_PUSHDATA4?t:void 0}}$.fromASM=function(e){var t=new $;if(t.chunks=[],e==="")return t;for(var r=e.split(" "),i=0;i<r.length;){var n=r[i],o=ce(n),a=o.toNumber(),s=Fk(n);if(s!==void 0)t.chunks.push({opcodenum:s}),i=i+1;else if(n==="0")a=0,t.chunks.push({opcodenum:a}),i=i+1;else if(n==="-1")a=ce.OP_1NEGATE,t.chunks.push({opcodenum:a}),i=i+1;else if(st.isUndefined(a)){var u=f.Buffer.from(r[i],"hex");if(u.toString("hex")!==r[i])throw new Error("invalid hex string in script");var c=u.length;c>=0&&c<ce.OP_PUSHDATA1?a=c:c<Math.pow(2,8)?a=ce.OP_PUSHDATA1:c<Math.pow(2,16)?a=ce.OP_PUSHDATA2:c<Math.pow(2,32)&&(a=ce.OP_PUSHDATA4),t.chunks.push({buf:u,len:u.length,opcodenum:a}),i=i+1}else t.chunks.push({opcodenum:a}),i=i+1}return t};var M7=/^(?:[0-9a-fA-F]{2})*$/;$.fromHex=function(e){return typeof e=="string"&&!M7.test(e)&&C7({what:"Script.fromHex() with a string that is not whole hex",since:"9.17.0",removeIn:"10.0.0",why:"Buffer.from() stops at the first character it cannot decode, so the script is silently truncated",use:"a round-trip check, Script.fromHex(h).toHex() === h.toLowerCase()"}),new $(Uk.Buffer.from(e,"hex"))};$.fromString=function(e){if(L7.isHexa(e)||e.length===0)return new $(Uk.Buffer.from(e,"hex"));var t=new $;t.chunks=[];for(var r=e.split(" "),i=0;i<r.length;){var n=r[i],o=ce(n),a=o.toNumber(),s=Fk(n);if(s!==void 0)t.chunks.push({opcodenum:s}),i=i+1;else if(st.isUndefined(a))if(a=parseInt(n),a>0&&a<ce.OP_PUSHDATA1)t.chunks.push({buf:f.Buffer.from(r[i+1].slice(2),"hex"),len:a,opcodenum:a}),i=i+2;else throw new Error("Invalid script: "+JSON.stringify(e));else if(a===ce.OP_PUSHDATA1||a===ce.OP_PUSHDATA2||a===ce.OP_PUSHDATA4){if(r[i+2].slice(0,2)!=="0x")throw new Error("Pushdata data must start with 0x");t.chunks.push({buf:f.Buffer.from(r[i+2].slice(2),"hex"),len:parseInt(r[i+1]),opcodenum:a}),i=i+3}else t.chunks.push({opcodenum:a}),i=i+1}return t};$.prototype._chunkToString=function(e,t){var r=e.opcodenum,i=t==="asm",n="";if(e.buf){var a=r===ce.OP_PUSHDATA1||r===ce.OP_PUSHDATA2||r===ce.OP_PUSHDATA4;!i&&a&&(n=n+" "+ce(r).toString()),e.len>0?i?n=n+" "+e.buf.toString("hex"):n=n+" "+e.len+" 0x"+e.buf.toString("hex"):i?n=n+" 0":a?n=n+" 0 0x":n=n+" OP_0"}else if(typeof ce.reverseMap[r]<"u")i?r===0?n=n+" 0":r===79?n=n+" -1":n=n+" "+ce(r).toString():n=n+" "+ce(r).toString();else{var o=r.toString(16);o.length%2!==0&&(o="0"+o),n=n+" 0x"+o}return n};$.prototype.toASM=function(){for(var e="",t=0;t<this.chunks.length;t++){var r=this.chunks[t];e+=this._chunkToString(r,"asm")}return e.substr(1)};$.prototype.toString=function(){for(var e="",t=0;t<this.chunks.length;t++){var r=this.chunks[t];e+=this._chunkToString(r)}return e.substr(1)};$.prototype.toHex=function(){return this.toBuffer().toString("hex")};$.prototype.inspect=function(){return"<Script: "+this.toString()+">"};$.prototype.isPublicKeyHashOut=function(){return!!(this.chunks.length===5&&this.chunks[0].opcodenum===ce.OP_DUP&&this.chunks[1].opcodenum===ce.OP_HASH160&&this.chunks[2].buf&&this.chunks[2].buf.length===20&&this.chunks[3].opcodenum===ce.OP_EQUALVERIFY&&this.chunks[4].opcodenum===ce.OP_CHECKSIG)};$.prototype.isPublicKeyHashOutPrefix=function(){return!!(this.chunks.length>=5&&this.chunks[0].opcodenum===ce.OP_DUP&&this.chunks[1].opcodenum===ce.OP_HASH160&&this.chunks[2].buf&&this.chunks[2].buf.length===20&&this.chunks[3].opcodenum===ce.OP_EQUALVERIFY&&this.chunks[4].opcodenum===ce.OP_CHECKSIG)};$.prototype.isPublicKeyHashIn=function(){if(this.chunks.length===2){var e=this.chunks[0].buf,t=this.chunks[1].buf;if(e&&e.length&&e[0]===48&&t&&t.length){var r=t[0];if((r===4||r===6||r===7)&&t.length===65)return!0;if((r===3||r===2)&&t.length===33)return!0}}return!1};$.prototype.getPublicKey=function(){return Gt.checkState(this.isPublicKeyOut(),"Can't retrieve PublicKey from a non-PK output"),this.chunks[0].buf};$.prototype.getPublicKeyHash=function(){return Gt.checkState(this.isPublicKeyHashOut(),"Can't retrieve PublicKeyHash from a non-PKH output"),this.chunks[2].buf};$.prototype.isPublicKeyOut=function(){if(this.chunks.length===2&&this.chunks[0].buf&&this.chunks[0].buf.length&&this.chunks[1].opcodenum===ce.OP_CHECKSIG){var e=this.chunks[0].buf,t=e[0],r=!1;if(((t===4||t===6||t===7)&&e.length===65||(t===3||t===2)&&e.length===33)&&(r=!0),r)return au.isValid(e)}return!1};$.prototype.isPublicKeyIn=function(){if(this.chunks.length===1){var e=this.chunks[0].buf;if(e&&e.length&&e[0]===48)return!0}return!1};$.prototype.isScriptHashOut=function(){var e=this.toBuffer();return e.length===23&&e[0]===ce.OP_HASH160&&e[1]===20&&e[e.length-1]===ce.OP_EQUAL};$.prototype.isScriptHashIn=function(){if(this.chunks.length<=1)return!1;var e=this.chunks[this.chunks.length-1],t=e.buf;if(!t)return!1;var r;try{r=$.fromBuffer(t)}catch(n){if(n instanceof c_.Script.InvalidBuffer)return!1;throw n}var i=r.classify();return i!==$.types.UNKNOWN};$.prototype.isMultisigOut=function(){return this.chunks.length>3&&ce.isSmallIntOp(this.chunks[0].opcodenum)&&this.chunks.slice(1,this.chunks.length-2).every(function(e){return e.buf&&f.Buffer.isBuffer(e.buf)})&&ce.isSmallIntOp(this.chunks[this.chunks.length-2].opcodenum)&&this.chunks[this.chunks.length-1].opcodenum===ce.OP_CHECKMULTISIG};$.prototype.isMultisigIn=function(){return this.chunks.length>=2&&this.chunks[0].opcodenum===0&&this.chunks.slice(1,this.chunks.length).every(function(e){return e.buf&&f.Buffer.isBuffer(e.buf)&&ou.isTxDER(e.buf)})};$.prototype.isDataOut=function(){var e=this.chunks.length>=1&&this.chunks[0].opcodenum===ce.OP_RETURN;if(!e)return!1;var t=this.chunks.slice(1),r=new $({chunks:t});return r.isPushOnly()};$.prototype.isSafeDataOut=function(){if(this.chunks.length<2||this.chunks[0].opcodenum!==ce.OP_FALSE)return!1;var e=this.chunks.slice(1),t=new $({chunks:e});return t.isDataOut()};$.prototype.getData=function(){if(this.isSafeDataOut()){var e=this.chunks.slice(2),t=e.map(r=>r.buf);return t}if(this.isDataOut()||this.isScriptHashOut())return st.isUndefined(this.chunks[1])?f.Buffer.alloc(0):f.Buffer.from(this.chunks[1].buf);if(this.isPublicKeyHashOut())return f.Buffer.from(this.chunks[2].buf);throw new Error("Unrecognized script type to get data from")};$.prototype.isPushOnly=function(){return st.every(this.chunks,function(e){return e.opcodenum<=ce.OP_16||e.opcodenum===ce.OP_PUSHDATA1||e.opcodenum===ce.OP_PUSHDATA2||e.opcodenum===ce.OP_PUSHDATA4})};$.types={};$.types.UNKNOWN="Unknown";$.types.PUBKEY_OUT="Pay to public key";$.types.PUBKEY_IN="Spend from public key";$.types.PUBKEYHASH_OUT="Pay to public key hash";$.types.PUBKEYHASH_IN="Spend from public key hash";$.types.SCRIPTHASH_OUT="Pay to script hash";$.types.SCRIPTHASH_IN="Spend from script hash";$.types.MULTISIG_OUT="Pay to multisig";$.types.MULTISIG_IN="Spend from multisig";$.types.DATA_OUT="Data push";$.types.SAFE_DATA_OUT="Safe data push";$.OP_RETURN_STANDARD_SIZE=220;$.prototype.classify=function(){if(this._isInput)return this.classifyInput();if(this._isOutput)return this.classifyOutput();var e=this.classifyOutput();return e!==$.types.UNKNOWN?e:this.classifyInput()};$.outputIdentifiers={};$.outputIdentifiers.PUBKEY_OUT=$.prototype.isPublicKeyOut;$.outputIdentifiers.PUBKEYHASH_OUT=$.prototype.isPublicKeyHashOut;$.outputIdentifiers.MULTISIG_OUT=$.prototype.isMultisigOut;$.outputIdentifiers.SCRIPTHASH_OUT=$.prototype.isScriptHashOut;$.outputIdentifiers.DATA_OUT=$.prototype.isDataOut;$.outputIdentifiers.SAFE_DATA_OUT=$.prototype.isSafeDataOut;$.prototype.classifyOutput=function(){for(var e in $.outputIdentifiers)if($.outputIdentifiers[e].bind(this)())return $.types[e];return $.types.UNKNOWN};$.inputIdentifiers={};$.inputIdentifiers.PUBKEY_IN=$.prototype.isPublicKeyIn;$.inputIdentifiers.PUBKEYHASH_IN=$.prototype.isPublicKeyHashIn;$.inputIdentifiers.MULTISIG_IN=$.prototype.isMultisigIn;$.inputIdentifiers.SCRIPTHASH_IN=$.prototype.isScriptHashIn;$.prototype.classifyInput=function(){for(var e in $.inputIdentifiers)if($.inputIdentifiers[e].bind(this)())return $.types[e];return $.types.UNKNOWN};$.prototype.isStandard=function(){return this.classify()!==$.types.UNKNOWN};$.prototype.prepend=function(e){return this._addByType(e,!0),this};$.prototype.equals=function(e){if(Gt.checkState(e instanceof $,"Must provide another script"),this.chunks.length!==e.chunks.length)return!1;var t;for(t=0;t<this.chunks.length;t++){if(f.Buffer.isBuffer(this.chunks[t].buf)&&!f.Buffer.isBuffer(e.chunks[t].buf)||f.Buffer.isBuffer(this.chunks[t].buf)&&!this.chunks[t].buf.equals(e.chunks[t].buf))return!1;if(this.chunks[t].opcodenum!==e.chunks[t].opcodenum)return!1}return!0};$.prototype.add=function(e){return this._addByType(e,!1),this};$.prototype._addByType=function(e,t){if(typeof e=="string")this._addOpcode(e,t);else if(typeof e=="number")this._addOpcode(e,t);else if(e instanceof ce)this._addOpcode(e,t);else if(f.Buffer.isBuffer(e))this._addBuffer(e,t);else if(e instanceof $)this.chunks=this.chunks.concat(e.chunks);else if(typeof e=="object")this._insertAtPosition(e,t);else throw new Error("Invalid script chunk")};$.prototype._insertAtPosition=function(e,t){t?this.chunks.unshift(e):this.chunks.push(e)};$.prototype._addOpcode=function(e,t){var r;return typeof e=="number"?r=e:e instanceof ce?r=e.toNumber():r=ce(e).toNumber(),this._insertAtPosition({opcodenum:r},t),this};$.prototype._addBuffer=function(e,t){var r,i=e.length;if(i>=0&&i<ce.OP_PUSHDATA1)r=i;else if(i<Math.pow(2,8))r=ce.OP_PUSHDATA1;else if(i<Math.pow(2,16))r=ce.OP_PUSHDATA2;else if(i<Math.pow(2,32))r=ce.OP_PUSHDATA4;else throw new Error("You can't push that much data");return this._insertAtPosition({buf:e,len:i,opcodenum:r},t),this};$.prototype.removeCodeseparators=function(){for(var e=[],t=0;t<this.chunks.length;t++)this.chunks[t].opcodenum!==ce.OP_CODESEPARATOR&&e.push(this.chunks[t]);return this.chunks=e,this};$.buildMultisigOut=function(e,t,r){Gt.checkArgument(t<=e.length,"Number of required signatures must be less than or equal to the number of public keys"),r=r||{};var i=new $;i.add(ce.smallInt(t)),e=st.map(e,au);var n=e;r.noSorting||(n=e.map(s=>s.toString("hex")).sort().map(s=>new au(s)));for(var o=0;o<n.length;o++){var a=n[o];i.add(a.toBuffer())}return i.add(ce.smallInt(e.length)),i.add(ce.OP_CHECKMULTISIG),i};$.buildMultisigIn=function(e,t,r,i){Gt.checkArgument(st.isArray(e)),Gt.checkArgument(st.isNumber(t)),Gt.checkArgument(st.isArray(r)),i=i||{};var n=new $;return n.add(ce.OP_0),st.each(r,function(o){Gt.checkArgument(f.Buffer.isBuffer(o),"Signatures must be an array of Buffers"),n.add(o)}),n};$.buildP2SHMultisigIn=function(e,t,r,i){Gt.checkArgument(st.isArray(e)),Gt.checkArgument(st.isNumber(t)),Gt.checkArgument(st.isArray(r)),i=i||{};var n=new $;return n.add(ce.OP_0),st.each(r,function(o){Gt.checkArgument(f.Buffer.isBuffer(o),"Signatures must be an array of Buffers"),n.add(o)}),n.add((i.cachedMultisig||$.buildMultisigOut(e,t,i)).toBuffer()),n};$.buildPublicKeyHashOut=function(e){Gt.checkArgument(!st.isUndefined(e)),Gt.checkArgument(e instanceof au||e instanceof Bn||st.isString(e)),e instanceof au?e=e.toAddress():st.isString(e)&&(e=new Bn(e));var t=new $;return t.add(ce.OP_DUP).add(ce.OP_HASH160).add(e.hashBuffer).add(ce.OP_EQUALVERIFY).add(ce.OP_CHECKSIG),t._network=e.network,t};$.buildPublicKeyOut=function(e){Gt.checkArgument(e instanceof au);var t=new $;return t.add(e.toBuffer()).add(ce.OP_CHECKSIG),t};$.buildDataOut=function(e,t){Gt.checkArgument(st.isUndefined(e)||st.isString(e)||st.isArray(e)||f.Buffer.isBuffer(e));var r=e;st.isArray(r)||(r=[e]);var i=new $;i.add(ce.OP_RETURN);for(let n of r)Gt.checkArgument(st.isUndefined(n)||st.isString(n)||f.Buffer.isBuffer(n)),st.isString(n)&&(n=f.Buffer.from(n,t)),st.isUndefined(n)||i.add(n);return i};$.buildSafeDataOut=function(e,t){var r=$.buildDataOut(e,t),i=new $;return i.add(ce.OP_FALSE),i.add(r),i};$.buildScriptHashOut=function(e){Gt.checkArgument(e instanceof $||e instanceof Bn&&e.isPayToScriptHash());var t=new $;return t.add(ce.OP_HASH160).add(e instanceof Bn?e.hashBuffer:u_.sha256ripemd160(e.toBuffer())).add(ce.OP_EQUAL),t._network=e._network||e.network,t};$.buildPublicKeyIn=function(e,t){Gt.checkArgument(e instanceof ou||f.Buffer.isBuffer(e)),Gt.checkArgument(st.isUndefined(t)||st.isNumber(t)),e instanceof ou&&(e=e.toBuffer());var r=new $;return r.add(f.Buffer.concat([e,f.Buffer.from([(t||ou.SIGHASH_ALL)&255])])),r};$.buildPublicKeyHashIn=function(e,t,r){Gt.checkArgument(t instanceof ou||f.Buffer.isBuffer(t)),Gt.checkArgument(st.isUndefined(r)||st.isNumber(r)),t instanceof ou&&(t=t.toBuffer());var i=new $().add(f.Buffer.concat([t,f.Buffer.from([(r||ou.SIGHASH_ALL)&255])])).add(new au(e).toBuffer());return i};$.empty=function(){return new $};$.prototype.toScriptHashOut=function(){return $.buildScriptHashOut(this)};$.fromAddress=function(e){if(e=Bn(e),e.isPayToScriptHash())return $.buildScriptHashOut(e);if(e.isPayToPublicKeyHash())return $.buildPublicKeyHashOut(e);throw new c_.Script.UnrecognizedAddress(e)};$.prototype.getAddressInfo=function(e){if(this._isInput)return this._getInputAddressInfo();if(this._isOutput)return this._getOutputAddressInfo();var t=this._getOutputAddressInfo();return t||this._getInputAddressInfo()};$.prototype._getOutputAddressInfo=function(){var e={};if(this.isScriptHashOut())e.hashBuffer=this.getData(),e.type=Bn.PayToScriptHash;else if(this.isPublicKeyHashOut())e.hashBuffer=this.getData(),e.type=Bn.PayToPublicKeyHash;else return!1;return e};$.prototype._getInputAddressInfo=function(){var e={};if(this.isPublicKeyHashIn())e.hashBuffer=u_.sha256ripemd160(this.chunks[1].buf),e.type=Bn.PayToPublicKeyHash;else if(this.isScriptHashIn())e.hashBuffer=u_.sha256ripemd160(this.chunks[this.chunks.length-1].buf),e.type=Bn.PayToScriptHash;else return!1;return e};$.prototype.toAddress=function(e){var t=this.getAddressInfo();return t?(t.network=qk.get(e)||this._network||qk.defaultNetwork,new Bn(t)):!1};$.prototype.findAndDelete=function(e){for(var t=e.toBuffer(),r=t.length?t[0]:-1,i=0;i<this.chunks.length;i++){var n=this.chunks[i];if(!(n.opcodenum!==r&&D7(n))){var o=$({chunks:[n]}).toBuffer();t.equals(o)&&(this.chunks.splice(i,1),i--)}}return this};function D7(e){var t=e.opcodenum;if(typeof t!="number"||!Number.isInteger(t)||t<0||t>255)return!1;if(!e.buf||t>ce.OP_PUSHDATA4)return!0;if(!f.Buffer.isBuffer(e.buf))return!1;var r=e.len;return t===ce.OP_PUSHDATA1?Number.isInteger(r)&&r>=0&&r<=255:t===ce.OP_PUSHDATA2?Number.isInteger(r)&&r>=0&&r<=65535:t===ce.OP_PUSHDATA4?Number.isInteger(r)&&r>=0&&r<=4294967295:!0}$.prototype.checkMinimalPush=function(e){var t=this.chunks[e],r=t.buf,i=t.opcodenum;return r?r.length===0?i===ce.OP_0:r.length===1&&r[0]>=1&&r[0]<=16?i===ce.OP_1+(r[0]-1):r.length===1&&r[0]===129?i===ce.OP_1NEGATE:r.length<=75?i===r.length:r.length<=255?i===ce.OP_PUSHDATA1:r.length<=65535?i===ce.OP_PUSHDATA2:!0:!0};$.prototype._decodeOP_N=function(e){if(e===ce.OP_0)return 0;if(e>=ce.OP_1&&e<=ce.OP_16)return e-(ce.OP_1-1);throw new Error("Invalid opcode: "+JSON.stringify(e))};$.prototype.getSignatureOperationsCount=function(e){e=st.isUndefined(e)?!0:e;var t=this,r=0,i=ce.OP_INVALIDOPCODE;return st.each(t.chunks,function(o){var a=o.opcodenum;a===ce.OP_CHECKSIG||a===ce.OP_CHECKSIGVERIFY?r++:(a===ce.OP_CHECKMULTISIG||a===ce.OP_CHECKMULTISIGVERIFY)&&(e&&i>=ce.OP_1&&i<=ce.OP_16?r+=t._decodeOP_N(i):r+=20),i=a}),r};jk.exports=$});var Nn=T((fse,Kk)=>{"use strict";g();var zk=fa(),dr=function e(t){if(!(this instanceof e))return new e(t);this.bufLen=0,t?this.set(t):this.bufs=[]};dr.prototype.set=function(e){return this.bufs=e.bufs||this.bufs||[],this.bufLen=this.bufs.reduce(function(t,r){return t+r.length},0),this};dr.prototype.toBuffer=function(){return this.concat()};dr.prototype.concat=function(){return f.Buffer.concat(this.bufs,this.bufLen)};dr.prototype.write=function(e){return zk(f.Buffer.isBuffer(e)),this.bufs.push(e),this.bufLen+=e.length,this};dr.prototype.writeReverse=function(e){return zk(f.Buffer.isBuffer(e)),this.bufs.push(f.Buffer.from(e).reverse()),this.bufLen+=e.length,this};dr.prototype.writeUInt8=function(e){var t=f.Buffer.alloc(1);return t.writeUInt8(e,0),this.write(t),this};dr.prototype.writeUInt16BE=function(e){var t=f.Buffer.alloc(2);return t.writeUInt16BE(e,0),this.write(t),this};dr.prototype.writeUInt16LE=function(e){var t=f.Buffer.alloc(2);return t.writeUInt16LE(e,0),this.write(t),this};dr.prototype.writeUInt32BE=function(e){var t=f.Buffer.alloc(4);return t.writeUInt32BE(e,0),this.write(t),this};dr.prototype.writeInt32LE=function(e){var t=f.Buffer.alloc(4);return t.writeInt32LE(e,0),this.write(t),this};dr.prototype.writeUInt32LE=function(e){var t=f.Buffer.alloc(4);return t.writeUInt32LE(e,0),this.write(t),this};dr.prototype.writeUInt64BEBN=function(e){var t=e.toBuffer({size:8});return this.write(t),this};dr.prototype.writeUInt64LEBN=function(e){var t=e.toBuffer({size:8});return this.writeReverse(t),this};dr.prototype.writeVarintNum=function(e){var t=dr.varintBufNum(e);return this.write(t),this};dr.prototype.writeVarintBN=function(e){var t=dr.varintBufBN(e);return this.write(t),this};dr.varintBufNum=function(e){var t;return e<253?(t=f.Buffer.alloc(1),t.writeUInt8(e,0)):e<65536?(t=f.Buffer.alloc(3),t.writeUInt8(253,0),t.writeUInt16LE(e,1)):e<4294967296?(t=f.Buffer.alloc(5),t.writeUInt8(254,0),t.writeUInt32LE(e,1)):(t=f.Buffer.alloc(9),t.writeUInt8(255,0),t.writeInt32LE(e&-1,1),t.writeUInt32LE(Math.floor(e/4294967296),5)),t};dr.varintBufBN=function(e){var t,r=e.toNumber();if(r<253)t=f.Buffer.alloc(1),t.writeUInt8(r,0);else if(r<65536)t=f.Buffer.alloc(3),t.writeUInt8(253,0),t.writeUInt16LE(r,1);else if(r<4294967296)t=f.Buffer.alloc(5),t.writeUInt8(254,0),t.writeUInt32LE(r,1);else{var i=new dr;i.writeUInt8(255),i.writeUInt64LEBN(e),t=i.concat()}return t};Kk.exports=dr});var Cc=T((hse,Wk)=>{"use strict";g();var Vk=Nn(),Gk=lo(),H7=Ke(),Cn=function e(t){if(!(this instanceof e))return new e(t);if(f.Buffer.isBuffer(t))this.buf=t;else if(typeof t=="number"){var r=t;this.fromNumber(r)}else if(t instanceof H7){var i=t;this.fromBN(i)}else if(t){var n=t;this.set(n)}};Cn.prototype.set=function(e){return this.buf=e.buf||this.buf,this};Cn.prototype.fromString=function(e){return this.set({buf:f.Buffer.from(e,"hex")}),this};Cn.prototype.toString=function(){return this.buf.toString("hex")};Cn.prototype.fromBuffer=function(e){return this.buf=e,this};Cn.prototype.fromBufferReader=function(e){return this.buf=e.readVarintBuf(),this};Cn.prototype.fromBN=function(e){return this.buf=Vk().writeVarintBN(e).concat(),this};Cn.prototype.fromNumber=function(e){return this.buf=Vk().writeVarintNum(e).concat(),this};Cn.prototype.toBuffer=function(){return this.buf};Cn.prototype.toBN=function(){return Gk(this.buf).readVarintBN()};Cn.prototype.toNumber=function(){return Gk(this.buf).readVarintNum()};Wk.exports=Cn});var gi=T((pse,Zk)=>{"use strict";g();var Vg=at(),f_=Ke(),Yk=rr(),Gg=ni(),q7=Nn(),U7=Cc(),l_=ut(),h_=Ie(),F7=pi(),j7=9007199254740991;function Jr(e){if(!(this instanceof Jr))return new Jr(e);if(Vg.isObject(e))if(this.satoshis=e.satoshis,f.Buffer.isBuffer(e.script))this._scriptBuffer=e.script;else{var t;Vg.isString(e.script)&&Gg.isHexa(e.script)?t=Yk.Buffer.from(e.script,"hex"):t=e.script,this.setScript(t)}else throw new TypeError("Unrecognized argument for Output")}Object.defineProperty(Jr.prototype,"script",{configurable:!1,enumerable:!0,get:function(){return this._script?this._script:(this.setScriptFromBuffer(this._scriptBuffer),this._script)}});Object.defineProperty(Jr.prototype,"satoshis",{configurable:!1,enumerable:!0,get:function(){return this._satoshis},set:function(e){e instanceof f_?(this._satoshisBN=e,this._satoshis=e.toNumber()):Vg.isString(e)?(this._satoshis=parseInt(e),this._satoshisBN=f_.fromNumber(this._satoshis)):(h_.checkArgument(Gg.isNaturalNumber(e),"Output satoshis is not a natural number"),this._satoshisBN=f_.fromNumber(e),this._satoshis=e),h_.checkState(Gg.isNaturalNumber(this._satoshis),"Output satoshis is not a natural number")}});Jr.prototype.invalidSatoshis=function(){return this._satoshis>j7?"transaction txout satoshis greater than max safe integer":this._satoshis!==this._satoshisBN.toNumber()?"transaction txout satoshis has corrupted value":this._satoshis<0?"transaction txout negative":!1};Object.defineProperty(Jr.prototype,"satoshisBN",{configurable:!1,enumerable:!0,get:function(){return this._satoshisBN},set:function(e){this._satoshisBN=e,this._satoshis=e.toNumber(),h_.checkState(Gg.isNaturalNumber(this._satoshis),"Output satoshis is not a natural number")}});Jr.prototype.toObject=Jr.prototype.toJSON=function(){var t={satoshis:this.satoshis};return t.script=this._scriptBuffer.toString("hex"),t};Jr.fromObject=function(e){return new Jr(e)};Jr.prototype.setScriptFromBuffer=function(e){this._scriptBuffer=e;try{this._script=l_.fromBuffer(this._scriptBuffer),this._script._isOutput=!0}catch(t){if(t instanceof F7.Script.InvalidBuffer)this._script=null;else throw t}};Jr.prototype.setScript=function(e){if(e instanceof l_)this._scriptBuffer=e.toBuffer(),this._script=e,this._script._isOutput=!0;else if(Vg.isString(e))this._script=l_.fromString(e),this._scriptBuffer=this._script.toBuffer(),this._script._isOutput=!0;else if(f.Buffer.isBuffer(e))this.setScriptFromBuffer(e);else throw new TypeError("Invalid argument type: script");return this};Jr.prototype.inspect=function(){var e;return this.script?e=this.script.inspect():e=this._scriptBuffer.toString("hex"),"<Output ("+this.satoshis+" sats) "+e+">"};Jr.fromBufferReader=function(e){var t={};t.satoshis=e.readUInt64LEBN();var r=e.readVarintNum();return r!==0?t.script=e.read(r):t.script=Yk.Buffer.from([]),new Jr(t)};Jr.prototype.toBufferWriter=function(e){e||(e=new q7),e.writeUInt64LEBN(this._satoshisBN);var t=this._scriptBuffer;return e.writeVarintNum(t.length),e.write(t),e};Jr.prototype.getSize=function(){var e=this.script.toBuffer().length,t=U7(e).toBuffer().length;return 8+t+e};Zk.exports=Jr});var Lc=T((mse,Qk)=>{"use strict";g();var rs=at(),z7=Ie(),nh=pi(),K7=Nn(),d_=rr(),Xk=ni(),Wg=ut(),V7=mi(),$k=gi(),Yg=4294967295,G7=Yg-2,Jk=Yg,W7=Yg-1;function Nt(e){if(!(this instanceof Nt))return new Nt(e);if(e)return this._fromObject(e)}Nt.MAXINT=Yg;Nt.DEFAULT_SEQNUMBER=Jk;Nt.DEFAULT_LOCKTIME_SEQNUMBER=W7;Nt.DEFAULT_RBF_SEQNUMBER=G7;Nt.BASE_SIZE=40;Object.defineProperty(Nt.prototype,"script",{configurable:!1,enumerable:!0,get:function(){return this.isNull()?null:(this._script||(this._script=new Wg(this._scriptBuffer),this._script._isInput=!0),this._script)}});Nt.fromObject=function(e){z7.checkArgument(rs.isObject(e));var t=new Nt;return t._fromObject(e)};Nt.prototype._fromObject=function(e){var t;if(rs.isString(e.prevTxId)&&Xk.isHexa(e.prevTxId)?t=d_.Buffer.from(e.prevTxId,"hex"):t=e.prevTxId,this.output=e.output?e.output instanceof $k?e.output:new $k(e.output):void 0,this.prevTxId=t||e.txidbuf,this.outputIndex=rs.isUndefined(e.outputIndex)?e.txoutnum:e.outputIndex,this.sequenceNumber=rs.isUndefined(e.sequenceNumber)?rs.isUndefined(e.seqnum)?Jk:e.seqnum:e.sequenceNumber,rs.isUndefined(e.script)&&rs.isUndefined(e.scriptBuffer))throw new nh.Transaction.Input.MissingScript;return this.setScript(e.scriptBuffer||e.script),this};Nt.prototype.toObject=Nt.prototype.toJSON=function(){var t={prevTxId:this.prevTxId.toString("hex"),outputIndex:this.outputIndex,sequenceNumber:this.sequenceNumber,script:this._scriptBuffer.toString("hex")};return this.script&&(t.scriptString=this.script.toString()),this.output&&(t.output=this.output.toObject()),t};Nt.fromBufferReader=function(e){var t=new Nt;return t.prevTxId=e.readReverse(32),t.outputIndex=e.readUInt32LE(),t._scriptBuffer=e.readVarLengthBuffer(),t.sequenceNumber=e.readUInt32LE(),t};Nt.prototype.toBufferWriter=function(e){e||(e=new K7),e.writeReverse(this.prevTxId),e.writeUInt32LE(this.outputIndex);var t=this._scriptBuffer;return e.writeVarintNum(t.length),e.write(t),e.writeUInt32LE(this.sequenceNumber),e};Nt.prototype.setScript=function(e){if(this._script=null,e instanceof Wg)this._script=e,this._script._isInput=!0,this._scriptBuffer=e.toBuffer();else if(e===null)this._script=Wg.empty(),this._script._isInput=!0,this._scriptBuffer=this._script.toBuffer();else if(Xk.isHexa(e))this._scriptBuffer=d_.Buffer.from(e,"hex");else if(rs.isString(e))this._script=new Wg(e),this._script._isInput=!0,this._scriptBuffer=this._script.toBuffer();else if(f.Buffer.isBuffer(e))this._scriptBuffer=d_.Buffer.from(e);else throw new TypeError("Invalid argument type: script");return this};Nt.prototype.getSignatures=function(){throw new nh.AbstractMethodInvoked("Trying to sign unsupported output type (only P2PKH and P2SH multisig inputs are supported) for input: "+JSON.stringify(this))};Nt.prototype.isFullySigned=function(){throw new nh.AbstractMethodInvoked("Input#isFullySigned")};Nt.prototype.isFinal=function(){return this.sequenceNumber===Nt.MAXINT};Nt.prototype.addSignature=function(){throw new nh.AbstractMethodInvoked("Input#addSignature")};Nt.prototype.clearSignatures=function(){throw new nh.AbstractMethodInvoked("Input#clearSignatures")};Nt.prototype.isValidSignature=function(e,t){return t.signature.nhashtype=t.sigtype,V7.verify(e,t.signature,t.publicKey,t.inputIndex,this.output.script,this.output.satoshisBN)};Nt.prototype.isNull=function(){return this.prevTxId.toString("hex")==="0000000000000000000000000000000000000000000000000000000000000000"&&this.outputIndex===4294967295};Nt.prototype._estimateSize=function(){return this.toBufferWriter().toBuffer().length};Qk.exports=Nt});var Mc=T((yse,eB)=>{"use strict";g();eB.exports=function(t,r){r&&(t.super_=r,t.prototype=Object.create(r.prototype,{constructor:{value:t,enumerable:!1,writable:!0,configurable:!0}}))}});var Hc=T((_se,iB)=>{"use strict";g();var Dc=at(),ln=Ie(),Y7=Mc(),tB=ni(),rB=sr(),Z7=pi(),oh=gt();function Ln(e){if(!(this instanceof Ln))return new Ln(e);if(e instanceof Ln)return e;if(Dc.isObject(e))return this._fromObject(e);throw new Z7.InvalidArgument("TransactionSignatures must be instantiated from an object")}Y7(Ln,oh);Ln.prototype._fromObject=function(e){return this._checkObjectArgs(e),this.publicKey=new rB(e.publicKey),this.prevTxId=f.Buffer.isBuffer(e.prevTxId)?e.prevTxId:f.Buffer.from(e.prevTxId,"hex"),this.outputIndex=e.outputIndex,this.inputIndex=e.inputIndex,this.signature=e.signature instanceof oh?e.signature:f.Buffer.isBuffer(e.signature)?oh.fromBuffer(e.signature):oh.fromString(e.signature),this.sigtype=e.sigtype,this};Ln.prototype._checkObjectArgs=function(e){ln.checkArgument(rB(e.publicKey),"publicKey"),ln.checkArgument(!Dc.isUndefined(e.inputIndex),"inputIndex"),ln.checkArgument(!Dc.isUndefined(e.outputIndex),"outputIndex"),ln.checkState(Dc.isNumber(e.inputIndex),"inputIndex must be a number"),ln.checkState(Dc.isNumber(e.outputIndex),"outputIndex must be a number"),ln.checkArgument(e.signature,"signature"),ln.checkArgument(e.prevTxId,"prevTxId"),ln.checkState(e.signature instanceof oh||f.Buffer.isBuffer(e.signature)||tB.isHexa(e.signature),"signature must be a buffer or hexa value"),ln.checkState(f.Buffer.isBuffer(e.prevTxId)||tB.isHexa(e.prevTxId),"prevTxId must be a buffer or hexa value"),ln.checkArgument(e.sigtype,"sigtype"),ln.checkState(Dc.isNumber(e.sigtype),"sigtype must be a number")};Ln.prototype.toObject=Ln.prototype.toJSON=function(){return{publicKey:this.publicKey.toString(),prevTxId:this.prevTxId.toString("hex"),outputIndex:this.outputIndex,inputIndex:this.inputIndex,signature:this.signature.toString(),sigtype:this.sigtype}};Ln.fromObject=function(e){return ln.checkArgument(e),new Ln(e)};iB.exports=Ln});var uB=T((Sse,sB)=>{"use strict";g();var $7=Mc(),oB=Ie(),p_=Lc(),X7=gi(),J7=mi(),aB=ut(),nB=gt(),Q7=Hc();function ha(){p_.apply(this,arguments)}$7(ha,p_);ha.prototype.getSignatures=function(e,t,r,i){oB.checkState(this.output instanceof X7),i=i||nB.SIGHASH_ALL|nB.SIGHASH_FORKID;var n=t.toPublicKey();return n.toString()===this.output.script.getPublicKey().toString("hex")?[new Q7({publicKey:n,prevTxId:this.prevTxId,outputIndex:this.outputIndex,inputIndex:r,signature:J7.sign(e,t,i,r,this.output.script,this.output.satoshisBN),sigtype:i})]:[]};ha.prototype.addSignature=function(e,t){return oB.checkState(this.isValidSignature(e,t),"Signature is invalid"),this.setScript(aB.buildPublicKeyIn(t.signature.toDER(),t.sigtype)),this};ha.prototype.clearSignatures=function(){return this.setScript(aB.empty()),this};ha.prototype.isFullySigned=function(){return this.script.isPublicKeyIn()};ha.SCRIPT_MAX_SIZE=74;ha.prototype._estimateSize=function(){return p_.BASE_SIZE+ha.SCRIPT_MAX_SIZE};sB.exports=ha});var dB=T((xse,hB)=>{"use strict";g();var e9=Mc(),fB=Ie(),t9=Le(),g_=Lc(),r9=gi(),i9=mi(),lB=ut(),cB=gt(),n9=Hc();function da(){g_.apply(this,arguments)}e9(da,g_);da.prototype.getSignatures=function(e,t,r,i,n){fB.checkState(this.output instanceof r9),n=n||t9.sha256ripemd160(t.publicKey.toBuffer()),i=i||cB.SIGHASH_ALL|cB.SIGHASH_FORKID;var o=this.output.script.chunks[2]&&this.output.script.chunks[2].buf;return o&&n.equals(o)?[new n9({publicKey:t.publicKey,prevTxId:this.prevTxId,outputIndex:this.outputIndex,inputIndex:r,signature:i9.sign(e,t,i,r,this.output.script,this.output.satoshisBN),sigtype:i})]:[]};da.prototype.addSignature=function(e,t){return fB.checkState(this.isValidSignature(e,t),"Signature is invalid"),this.setScript(lB.buildPublicKeyHashIn(t.publicKey,t.signature.toDER(),t.sigtype)),this};da.prototype.clearSignatures=function(){return this.setScript(lB.empty()),this};da.prototype.isFullySigned=function(){return this.script.isPublicKeyHashIn()};da.SCRIPT_MAX_SIZE=108;da.prototype._estimateSize=function(){return g_.BASE_SIZE+da.SCRIPT_MAX_SIZE};hB.exports=da});var mB=T((Ise,gB)=>{"use strict";g();var Mn=at(),o9=Mc(),$g=Lc(),a9=gi(),ah=Ie(),pB=ut(),Zg=gt(),m_=mi(),v_=Hc(),s9=sr(),u9=Cc();function Ur(e,t,r,i){$g.apply(this,arguments);var n=this;t=t||e.publicKeys,r=r||e.threshold,i=i||e.signatures,this.publicKeys=t.map(o=>o.toString("hex")).sort().map(o=>new s9(o)),ah.checkState(pB.buildMultisigOut(this.publicKeys,r).equals(this.output.script),"Provided public keys don't match to the provided output script"),this.publicKeyIndex={},Mn.each(this.publicKeys,function(o,a){n.publicKeyIndex[o.toString()]=a}),this.threshold=r,this.signatures=i?this._deserializeSignatures(i):new Array(this.publicKeys.length)}o9(Ur,$g);Ur.prototype.toObject=function(){var e=$g.prototype.toObject.apply(this,arguments);return e.threshold=this.threshold,e.publicKeys=Mn.map(this.publicKeys,function(t){return t.toString()}),e.signatures=this._serializeSignatures(),e};Ur.prototype._deserializeSignatures=function(e){return Mn.map(e,function(t){if(t)return new v_(t)})};Ur.prototype._serializeSignatures=function(){return Mn.map(this.signatures,function(e){if(e)return e.toObject()})};Ur.prototype.getSignatures=function(e,t,r,i){ah.checkState(this.output instanceof a9),i=i||Zg.SIGHASH_ALL|Zg.SIGHASH_FORKID;var n=this,o=[];return Mn.each(this.publicKeys,function(a){a.toString()===t.publicKey.toString()&&o.push(new v_({publicKey:t.publicKey,prevTxId:n.prevTxId,outputIndex:n.outputIndex,inputIndex:r,signature:m_.sign(e,t,i,r,n.output.script,n.output.satoshisBN),sigtype:i}))}),o};Ur.prototype.addSignature=function(e,t){return ah.checkState(!this.isFullySigned(),"All needed signatures have already been added"),ah.checkArgument(!Mn.isUndefined(this.publicKeyIndex[t.publicKey.toString()]),"Signature has no matching public key"),ah.checkState(this.isValidSignature(e,t)),this.signatures[this.publicKeyIndex[t.publicKey.toString()]]=t,this._updateScript(),this};Ur.prototype._updateScript=function(){return this.setScript(pB.buildMultisigIn(this.publicKeys,this.threshold,this._createSignatures())),this};Ur.prototype._createSignatures=function(){return Mn.map(Mn.filter(this.signatures,function(e){return!Mn.isUndefined(e)}),function(e){return f.Buffer.concat([e.signature.toDER(),f.Buffer.from([e.sigtype&255])])})};Ur.prototype.clearSignatures=function(){this.signatures=new Array(this.publicKeys.length),this._updateScript()};Ur.prototype.isFullySigned=function(){return this.countSignatures()===this.threshold};Ur.prototype.countMissingSignatures=function(){return this.threshold-this.countSignatures()};Ur.prototype.countSignatures=function(){return Mn.reduce(this.signatures,function(e,t){return e+!!t},0)};Ur.prototype.publicKeysWithoutSignature=function(){var e=this;return Mn.filter(this.publicKeys,function(t){return!e.signatures[e.publicKeyIndex[t.toString()]]})};Ur.prototype.isValidSignature=function(e,t){return t.signature.nhashtype=t.sigtype,m_.verify(e,t.signature,t.publicKey,t.inputIndex,this.output.script,this.output.satoshisBN)};Ur.normalizeSignatures=function(e,t,r,i,n){return n.map(function(o){var a=null;return i=i.filter(function(s){if(a)return!0;var u=new v_({signature:Zg.fromTxFormat(s),publicKey:o,prevTxId:t.prevTxId,outputIndex:t.outputIndex,inputIndex:r,sigtype:Zg.SIGHASH_ALL});u.signature.nhashtype=u.sigtype;var c=m_.verify(e,u.signature,u.publicKey,u.inputIndex,t.output.script);return c?(a=u,!1):!0}),a||null})};Ur.SIGNATURE_SIZE=73;Ur.prototype._estimateSize=function(){var e=1+this.threshold*Ur.SIGNATURE_SIZE;return $g.BASE_SIZE+u9(e).toBuffer().length+e};gB.exports=Ur});var wB=T((Tse,_B)=>{"use strict";g();var Dn=at(),c9=Mc(),Xg=Lc(),f9=gi(),sh=Ie(),y_=ut(),vB=gt(),yB=mi(),bB=Hc(),l9=sr(),h9=Cc();function Rr(e,t,r,i){Xg.apply(this,arguments);var n=this;t=t||e.publicKeys,r=r||e.threshold,i=i||e.signatures,this.publicKeys=t.map(o=>o.toString("hex")).sort().map(o=>new l9(o)),this.redeemScript=y_.buildMultisigOut(this.publicKeys,r),sh.checkState(y_.buildScriptHashOut(this.redeemScript).equals(this.output.script),"Provided public keys don't hash to the provided output"),this.publicKeyIndex={},Dn.each(this.publicKeys,function(o,a){n.publicKeyIndex[o.toString()]=a}),this.threshold=r,this.signatures=i?this._deserializeSignatures(i):new Array(this.publicKeys.length)}c9(Rr,Xg);Rr.prototype.toObject=function(){var e=Xg.prototype.toObject.apply(this,arguments);return e.threshold=this.threshold,e.publicKeys=Dn.map(this.publicKeys,function(t){return t.toString()}),e.signatures=this._serializeSignatures(),e};Rr.prototype._deserializeSignatures=function(e){return Dn.map(e,function(t){if(t)return new bB(t)})};Rr.prototype._serializeSignatures=function(){return Dn.map(this.signatures,function(e){if(e)return e.toObject()})};Rr.prototype.getSignatures=function(e,t,r,i){sh.checkState(this.output instanceof f9),i=i||vB.SIGHASH_ALL|vB.SIGHASH_FORKID;var n=this,o=[];return Dn.each(this.publicKeys,function(a){a.toString()===t.publicKey.toString()&&o.push(new bB({publicKey:t.publicKey,prevTxId:n.prevTxId,outputIndex:n.outputIndex,inputIndex:r,signature:yB.sign(e,t,i,r,n.redeemScript,n.output.satoshisBN),sigtype:i}))}),o};Rr.prototype.addSignature=function(e,t){return sh.checkState(!this.isFullySigned(),"All needed signatures have already been added"),sh.checkArgument(!Dn.isUndefined(this.publicKeyIndex[t.publicKey.toString()]),"Signature has no matching public key"),sh.checkState(this.isValidSignature(e,t)),this.signatures[this.publicKeyIndex[t.publicKey.toString()]]=t,this._updateScript(),this};Rr.prototype._updateScript=function(){return this.setScript(y_.buildP2SHMultisigIn(this.publicKeys,this.threshold,this._createSignatures(),{cachedMultisig:this.redeemScript})),this};Rr.prototype._createSignatures=function(){return Dn.map(Dn.filter(this.signatures,function(e){return!Dn.isUndefined(e)}),function(e){return f.Buffer.concat([e.signature.toDER(),f.Buffer.from([e.sigtype&255])])})};Rr.prototype.clearSignatures=function(){this.signatures=new Array(this.publicKeys.length),this._updateScript()};Rr.prototype.isFullySigned=function(){return this.countSignatures()===this.threshold};Rr.prototype.countMissingSignatures=function(){return this.threshold-this.countSignatures()};Rr.prototype.countSignatures=function(){return Dn.reduce(this.signatures,function(e,t){return e+!!t},0)};Rr.prototype.publicKeysWithoutSignature=function(){var e=this;return Dn.filter(this.publicKeys,function(t){return!e.signatures[e.publicKeyIndex[t.toString()]]})};Rr.prototype.isValidSignature=function(e,t){return t.signature.nhashtype=t.sigtype,yB.verify(e,t.signature,t.publicKey,t.inputIndex,this.redeemScript,this.output.satoshisBN)};Rr.SIGNATURE_SIZE=73;Rr.PUBKEY_SIZE=34;Rr.prototype._estimateSize=function(){var e=this.publicKeys.length*Rr.PUBKEY_SIZE,t=this.threshold*Rr.SIGNATURE_SIZE,r=3+e,i=r<=75?1:r<=255?2:3,n=t+1+i+r;return Xg.BASE_SIZE+h9(n).toBuffer().length+n};_B.exports=Rr});var ho=T((Rse,qc)=>{g();qc.exports=Lc();qc.exports.PublicKey=uB();qc.exports.PublicKeyHash=dB();qc.exports.MultiSig=mB();qc.exports.MultiSigScriptHash=wB()});var mi=T((Bse,IB)=>{"use strict";g();var d9=rr(),Ci=gt(),uh=ut(),p9=gi(),g9=lo(),ch=Nn(),SB=Ke(),Jg=Le(),EB=dn(),b_=Ie(),__=hn(),is=at(),xB=f.Buffer.from("0000000000000000000000000000000000000000000000000000000000000001","hex"),m9="ffffffffffffffff",v9=__.SCRIPT_ENABLE_SIGHASH_FORKID,y9=function(e,t,r,i,n){var o=e.inputs[r];b_.checkArgument(n instanceof SB,"For ForkId=0 signatures, satoshis or complete input must be provided");function a(R){var k=new ch;is.each(R.inputs,function(A){k.writeReverse(A.prevTxId),k.writeUInt32LE(A.outputIndex)});var q=k.toBuffer(),z=Jg.sha256sha256(q);return z}function s(R){var k=new ch;is.each(R.inputs,function(A){k.writeUInt32LE(A.sequenceNumber)});var q=k.toBuffer(),z=Jg.sha256sha256(q);return z}function u(R,k){var q=new ch;is.isUndefined(k)?is.each(R.outputs,function(B){B.toBufferWriter(q)}):R.outputs[k].toBufferWriter(q);var z=q.toBuffer(),A=Jg.sha256sha256(z);return A}var c=f.Buffer.alloc(32),l=f.Buffer.alloc(32),p=f.Buffer.alloc(32);t&Ci.SIGHASH_ANYONECANPAY||(c=a(e)),!(t&Ci.SIGHASH_ANYONECANPAY)&&(t&31)!==Ci.SIGHASH_SINGLE&&(t&31)!==Ci.SIGHASH_NONE&&(l=s(e)),(t&31)!==Ci.SIGHASH_SINGLE&&(t&31)!==Ci.SIGHASH_NONE?p=u(e):(t&31)===Ci.SIGHASH_SINGLE&&r<e.outputs.length&&(p=u(e,r));var d=new ch;d.writeInt32LE(e.version),d.write(c),d.write(l),d.writeReverse(o.prevTxId),d.writeUInt32LE(o.outputIndex);var v=i.toBuffer();d.writeVarintNum(v.length),d.write(v),d.writeUInt64LEBN(n);var _=o.sequenceNumber;d.writeUInt32LE(_),d.write(p),d.writeUInt32LE(e.nLockTime),d.writeUInt32LE(t>>>0);var I=d.toBuffer();return I},OB=function(t,r,i,n,o,a){var s=S_(),u=ho();is.isUndefined(a)&&(a=v9);var c=s.shallowCopy(t);if(n instanceof uh||(n=new uh(n)),a&__.SCRIPT_ENABLE_REPLAY_PROTECTION){var l=r>>8,p=16711680|l^57005;r=p<<8|r&255}if(r&Ci.SIGHASH_FORKID&&!(r&Ci.SIGHASH_CHRONICLE)&&a&__.SCRIPT_ENABLE_SIGHASH_FORKID)return y9(c,r,i,n,o);n=new uh(n),n.removeCodeseparators();var d;for(d=0;d<c.inputs.length;d++)c.inputs[d]=new u(c.inputs[d]).setScript(uh.empty());if(c.inputs[i]=new u(c.inputs[i]).setScript(n),(r&31)===Ci.SIGHASH_NONE||(r&31)===Ci.SIGHASH_SINGLE)for(d=0;d<c.inputs.length;d++)d!==i&&(c.inputs[d].sequenceNumber=0);if((r&31)===Ci.SIGHASH_NONE)c.outputs=[];else if((r&31)===Ci.SIGHASH_SINGLE){if(i>=c.outputs.length)return xB;for(c.outputs.length=i+1,d=0;d<i;d++)c.outputs[d]=new p9({satoshis:SB.fromBuffer(d9.Buffer.from(m9,"hex")),script:uh.empty()})}r&Ci.SIGHASH_ANYONECANPAY&&(c.inputs=[c.inputs[i]]);var v=new ch().write(c.toBuffer()).writeInt32LE(r).toBuffer();return v},w_=function(t,r,i,n,o,a){var s=OB(t,r,i,n,o,a);if(s.compare(xB)===0)return s;var u=Jg.sha256sha256(s);return u=new g9(u).readReverse(),u};function b9(e,t,r,i,n,o,a){var s=w_(e,r,i,n,o,a),u=EB.sign(s,t,"little").set({nhashtype:r});return u}function _9(e,t,r,i,n,o,a){b_.checkArgument(!is.isUndefined(e)),b_.checkArgument(!is.isUndefined(t)&&!is.isUndefined(t.nhashtype));var s=w_(e,t.nhashtype,i,n,o,a);return EB.verify(s,t,r,"little")}IB.exports={sighashPreimage:OB,sighash:w_,sign:b9,verify:_9}});var E_=T((Cse,TB)=>{"use strict";g();var pa=at(),Qg=Ie(),AB=ni(),w9=ut(),S9=Ni();function ga(e){if(!(this instanceof ga))return new ga(e);Qg.checkArgument(pa.isObject(e),"Must provide an object from where to extract data");var t=e.address?new S9(e.address):void 0,r=e.txid?e.txid:e.txId;if(!r||!AB.isHexaString(r)||r.length>64)throw new Error("Invalid TXID in object",e);var i=pa.isUndefined(e.vout)?e.outputIndex:e.vout;if(!pa.isNumber(i))throw new Error("Invalid outputIndex, received "+i);Qg.checkArgument(!pa.isUndefined(e.scriptPubKey)||!pa.isUndefined(e.script),"Must provide the scriptPubKey for that output!");var n=new w9(e.scriptPubKey||e.script);Qg.checkArgument(!pa.isUndefined(e.amount)||!pa.isUndefined(e.satoshis),"Must provide an amount for the output");var o=pa.isUndefined(e.amount)?e.satoshis:Math.round(e.amount*1e8);Qg.checkArgument(pa.isNumber(o),"Amount must be a number"),AB.defineImmutable(this,{address:t,txId:r,outputIndex:i,script:n,satoshis:o})}ga.prototype.inspect=function(){return"<UnspentOutput: "+this.txId+":"+this.outputIndex+", satoshis: "+this.satoshis+", address: "+this.address+">"};ga.prototype.toString=function(){return this.txId+":"+this.outputIndex};ga.fromObject=function(e){return new ga(e)};ga.prototype.toObject=ga.prototype.toJSON=function(){return{address:this.address?this.address.toString():void 0,txid:this.txId,vout:this.outputIndex,scriptPubKey:this.script.toBuffer().toString("hex"),amount:Number.parseFloat((this.satoshis/1e8).toFixed(8))}};TB.exports=ga});var S_=T((Mse,MB)=>{"use strict";g();var Ae=at(),Qr=Ie(),E9=rr(),jr=pi(),RB=ni(),kB=lo(),x9=Nn(),PB=Cc(),BB=Le(),tm=gt(),NB=mi(),O9=Ni(),CB=E_(),Fr=ho(),I9=Fr.PublicKeyHash,A9=Fr.PublicKey,T9=Fr.MultiSigScriptHash,P9=Fr.MultiSig,Hn=gi(),po=ut(),R9=ei(),em=Ke(),k9=hn(),B9=k9.SCRIPT_ENABLE_SIGHASH_FORKID;function ue(e){if(!(this instanceof ue))return new ue(e);if(this.inputs=[],this.outputs=[],this._inputAmount=void 0,this._outputAmount=void 0,e){if(e instanceof ue)return ue.shallowCopy(e);if(RB.isHexa(e))this.fromString(e);else if(f.Buffer.isBuffer(e))this.fromBuffer(e);else if(Ae.isObject(e))this.fromObject(e);else throw new jr.InvalidArgument("Must provide an object or string to deserialize a transaction")}else this._newTransaction()}var N9=1,C9=0,L9=1e6;ue.DUST_AMOUNT=546;ue.FEE_SECURITY_MARGIN=150;ue.MAX_MONEY=21e6*1e8;ue.NLOCKTIME_BLOCKHEIGHT_LIMIT=5e8;ue.NLOCKTIME_MAX_VALUE=4294967295;ue.FEE_PER_KB=500;ue.CHANGE_OUTPUT_MAX_SIZE=62;ue.shallowCopy=function(e){var t=new ue(e.toBuffer());return t};var LB={configurable:!1,enumerable:!0,get:function(){return this._hash=new kB(this._getHash()).readReverse().toString("hex"),this._hash}};Object.defineProperty(ue.prototype,"hash",LB);Object.defineProperty(ue.prototype,"id",LB);var x_={configurable:!1,enumerable:!0,get:function(){return this._getInputAmount()}};Object.defineProperty(ue.prototype,"inputAmount",x_);x_.get=function(){return this._getOutputAmount()};Object.defineProperty(ue.prototype,"outputAmount",x_);ue.prototype._getHash=function(){return BB.sha256sha256(this.toBuffer())};ue.prototype.serialize=function(e){return e===!0||e&&e.disableAll?this.uncheckedSerialize():this.checkedSerialize(e)};ue.prototype.uncheckedSerialize=ue.prototype.toString=function(){return this.toBuffer().toString("hex")};ue.prototype.checkedSerialize=function(e){var t=this.getSerializationError(e);if(t)throw t.message+=" - For more information please see: https://bsv.io/api/lib/transaction#serialization-checks",t;return this.uncheckedSerialize()};ue.prototype.invalidSatoshis=function(){for(var e=!1,t=0;t<this.outputs.length;t++)this.outputs[t].invalidSatoshis()&&(e=!0);return e};ue.prototype.getSerializationError=function(e){if(e=e||{},this.invalidSatoshis())return new jr.Transaction.InvalidSatoshis;var t=this._getUnspentValue(),r;return t<0?e.disableMoreOutputThanInput||(r=new jr.Transaction.InvalidOutputAmountSum):r=this._hasFeeError(e,t),r||this._hasDustOutputs(e)||this._isMissingSignatures(e)};ue.prototype._hasFeeError=function(e,t){if(!Ae.isUndefined(this._fee)&&this._fee!==t)return new jr.Transaction.FeeError.Different("Unspent value is "+t+" but specified fee is "+this._fee);if(!e.disableLargeFees){var r=Math.floor(ue.FEE_SECURITY_MARGIN*this._estimateFee());if(t>r)return this._missingChange()?new jr.Transaction.ChangeAddressMissing("Fee is too large and no change address was provided"):new jr.Transaction.FeeError.TooLarge("expected less than "+r+" but got "+t)}};ue.prototype._missingChange=function(){return!this._changeScript};ue.prototype._hasDustOutputs=function(e){if(!e.disableDustOutputs){var t,r;for(t in this.outputs)if(r=this.outputs[t],r.satoshis<ue.DUST_AMOUNT&&!r.script.isDataOut()&&!r.script.isSafeDataOut())return new jr.Transaction.DustOutputs}};ue.prototype._isMissingSignatures=function(e){if(!e.disableIsFullySigned&&!this.isFullySigned())return new jr.Transaction.MissingSignatures};ue.prototype.inspect=function(){return"<Transaction: "+this.uncheckedSerialize()+">"};ue.prototype.toBuffer=function(){var e=new x9;return this.toBufferWriter(e).toBuffer()};ue.prototype.toBufferWriter=function(e){return e.writeInt32LE(this.version),e.writeVarintNum(this.inputs.length),Ae.each(this.inputs,function(t){t.toBufferWriter(e)}),e.writeVarintNum(this.outputs.length),Ae.each(this.outputs,function(t){t.toBufferWriter(e)}),e.writeUInt32LE(this.nLockTime),e};ue.prototype.fromBuffer=function(e){var t=new kB(e);return this.fromBufferReader(t)};ue.prototype.fromBufferReader=function(e){Qr.checkArgument(!e.finished(),"No transaction data received");var t,r,i;for(this.version=e.readInt32LE(),r=e.readVarintNum(),t=0;t<r;t++){var n=Fr.fromBufferReader(e);this.inputs.push(n)}for(i=e.readVarintNum(),t=0;t<i;t++)this.outputs.push(Hn.fromBufferReader(e));return this.nLockTime=e.readUInt32LE(),this};ue.prototype.toObject=ue.prototype.toJSON=function(){var t=[];this.inputs.forEach(function(n){t.push(n.toObject())});var r=[];this.outputs.forEach(function(n){r.push(n.toObject())});var i={hash:this.hash,version:this.version,inputs:t,outputs:r,nLockTime:this.nLockTime};return this._changeScript&&(i.changeScript=this._changeScript.toString()),Ae.isUndefined(this._changeIndex)||(i.changeIndex=this._changeIndex),Ae.isUndefined(this._fee)||(i.fee=this._fee),i};ue.prototype.fromObject=function(t){Qr.checkArgument(Ae.isObject(t)||t instanceof ue);var r=this,i;return t instanceof ue?i=t.toObject():i=t,Ae.each(i.inputs,function(n){if(!n.output||!n.output.script){r.uncheckedAddInput(new Fr(n));return}var o=new po(n.output.script),a;if(o.isPublicKeyHashOut())a=new Fr.PublicKeyHash(n);else if(o.isScriptHashOut()&&n.publicKeys&&n.threshold)a=new Fr.MultiSigScriptHash(n,n.publicKeys,n.threshold,n.signatures);else if(o.isPublicKeyOut())a=new Fr.PublicKey(n);else throw new jr.Transaction.Input.UnsupportedScript(n.output.script);r.addInput(a)}),Ae.each(i.outputs,function(n){r.addOutput(new Hn(n))}),i.changeIndex&&(this._changeIndex=i.changeIndex),i.changeScript&&(this._changeScript=new po(i.changeScript)),i.fee&&(this._fee=i.fee),this.nLockTime=i.nLockTime,this.version=i.version,this._checkConsistency(t),this};ue.prototype._checkConsistency=function(e){Ae.isUndefined(this._changeIndex)||(Qr.checkState(this._changeScript,"Change script is expected."),Qr.checkState(this.outputs[this._changeIndex],"Change index points to undefined output."),Qr.checkState(this.outputs[this._changeIndex].script.toString()===this._changeScript.toString(),"Change output has an unexpected script.")),e&&e.hash&&Qr.checkState(e.hash===this.hash,"Hash in object does not match transaction hash.")};ue.prototype.lockUntilDate=function(e){if(Qr.checkArgument(e),Ae.isNumber(e)&&e<ue.NLOCKTIME_BLOCKHEIGHT_LIMIT)throw new jr.Transaction.LockTimeTooEarly;Ae.isDate(e)&&(e=e.getTime()/1e3);for(var t=0;t<this.inputs.length;t++)this.inputs[t].sequenceNumber===Fr.DEFAULT_SEQNUMBER&&(this.inputs[t].sequenceNumber=Fr.DEFAULT_LOCKTIME_SEQNUMBER);return this.nLockTime=e,this};ue.prototype.lockUntilBlockHeight=function(e){if(Qr.checkArgument(Ae.isNumber(e)),e>=ue.NLOCKTIME_BLOCKHEIGHT_LIMIT)throw new jr.Transaction.BlockHeightTooHigh;if(e<0)throw new jr.Transaction.NLockTimeOutOfRange;for(var t=0;t<this.inputs.length;t++)this.inputs[t].sequenceNumber===Fr.DEFAULT_SEQNUMBER&&(this.inputs[t].sequenceNumber=Fr.DEFAULT_LOCKTIME_SEQNUMBER);return this.nLockTime=e,this};ue.prototype.getLockTime=function(){return this.nLockTime?this.nLockTime<ue.NLOCKTIME_BLOCKHEIGHT_LIMIT?this.nLockTime:new Date(1e3*this.nLockTime):null};ue.prototype.fromString=function(e){this.fromBuffer(E9.Buffer.from(e,"hex"))};ue.prototype._newTransaction=function(){this.version=N9,this.nLockTime=C9};ue.prototype.from=function(e,t,r){if(Ae.isArray(e)){var i=this;return Ae.each(e,function(o){i.from(o,t,r)}),this}var n=Ae.some(this.inputs,function(o){return o.prevTxId.toString("hex")===e.txId&&o.outputIndex===e.outputIndex});return n?this:(t&&r?this._fromMultisigUtxo(e,t,r):this._fromNonP2SH(e),this)};ue.prototype._fromNonP2SH=function(e){var t;e=new CB(e),e.script.isPublicKeyHashOutPrefix()?t=I9:e.script.isPublicKeyOut()?t=A9:t=Fr,this.addInput(new t({output:new Hn({script:e.script,satoshis:e.satoshis}),prevTxId:e.txId,outputIndex:e.outputIndex,script:po.empty()}))};ue.prototype._fromMultisigUtxo=function(e,t,r){Qr.checkArgument(r<=t.length,"Number of required signatures must be greater than the number of public keys");var i;if(e=new CB(e),e.script.isMultisigOut())i=P9;else if(e.script.isScriptHashOut())i=T9;else throw new jr.Transaction.Input.UnsupportedScript(e.script.toString());this.addInput(new i({output:new Hn({script:e.script,satoshis:e.satoshis}),prevTxId:e.txId,outputIndex:e.outputIndex,script:po.empty()},t,r))};ue.prototype.addInput=function(e,t,r){if(Qr.checkArgumentType(e,Fr,"input"),!e.output&&(Ae.isUndefined(t)||Ae.isUndefined(r)))throw new jr.Transaction.NeedMoreInfo("Need information about the UTXO script and satoshis");return!e.output&&t&&!Ae.isUndefined(r)&&(t=t instanceof po?t:new po(t),Qr.checkArgumentType(r,"number","satoshis"),e.output=new Hn({script:t,satoshis:r})),this.uncheckedAddInput(e)};ue.prototype.uncheckedAddInput=function(e){return Qr.checkArgumentType(e,Fr,"input"),this.inputs.push(e),this._inputAmount=void 0,this._updateChangeOutput(),this};ue.prototype.hasAllUtxoInfo=function(){return Ae.every(this.inputs.map(function(e){return!!e.output}))};ue.prototype.fee=function(e){return Qr.checkArgument(Ae.isNumber(e),"amount must be a number"),this._fee=e,this._updateChangeOutput(),this};ue.prototype.feePerKb=function(e){return Qr.checkArgument(Ae.isNumber(e),"amount must be a number"),this._feePerKb=e,this._updateChangeOutput(),this};ue.prototype.change=function(e){return Qr.checkArgument(e,"address is required"),this._changeScript=po.fromAddress(e),this._updateChangeOutput(),this};ue.prototype.getChangeOutput=function(){return Ae.isUndefined(this._changeIndex)?null:this.outputs[this._changeIndex]};ue.prototype.to=function(e,t){if(Ae.isArray(e)){var r=this;return Ae.each(e,function(i){r.to(i.address,i.satoshis)}),this}return Qr.checkArgument(RB.isNaturalNumber(t),"Amount is expected to be a positive integer"),this.addOutput(new Hn({script:po(new O9(e)),satoshis:t})),this};ue.prototype.addData=function(e){return this.addOutput(new Hn({script:po.buildDataOut(e),satoshis:0})),this};ue.prototype.addSafeData=function(e){return this.addOutput(new Hn({script:po.buildSafeDataOut(e),satoshis:0})),this};ue.prototype.addOutput=function(e){return Qr.checkArgumentType(e,Hn,"output"),this._addOutput(e),this._updateChangeOutput(),this};ue.prototype.clearOutputs=function(){return this.outputs=[],this._clearSignatures(),this._outputAmount=void 0,this._changeIndex=void 0,this._updateChangeOutput(),this};ue.prototype._addOutput=function(e){this.outputs.push(e),this._outputAmount=void 0};ue.prototype._getOutputAmount=function(){if(Ae.isUndefined(this._outputAmount)){var e=this;this._outputAmount=0,Ae.each(this.outputs,function(t){e._outputAmount+=t.satoshis})}return this._outputAmount};ue.prototype._getInputAmount=function(){if(Ae.isUndefined(this._inputAmount)){var e=this;this._inputAmount=0,Ae.each(this.inputs,function(t){if(Ae.isUndefined(t.output))throw new jr.Transaction.Input.MissingPreviousOutput;e._inputAmount+=t.output.satoshis})}return this._inputAmount};ue.prototype._updateChangeOutput=function(){if(this._changeScript){this._clearSignatures(),Ae.isUndefined(this._changeIndex)||this._removeOutput(this._changeIndex),this._changeIndex=this.outputs.length,this._addOutput(new Hn({script:this._changeScript,satoshis:0}));var e=this._getUnspentValue(),t=this.getFee(),r=e-t;this._removeOutput(this._changeIndex),this._changeIndex=void 0,r>=ue.DUST_AMOUNT&&(this._changeIndex=this.outputs.length,this._addOutput(new Hn({script:this._changeScript,satoshis:r})))}};ue.prototype.getFee=function(){return this.isCoinbase()?0:Ae.isUndefined(this._fee)?this._changeScript?this._estimateFee():this._getUnspentValue():this._fee};ue.prototype._estimateFee=function(){var e=this._estimateSize();return Math.ceil(e/1e3*(this._feePerKb||ue.FEE_PER_KB))};ue.prototype._getUnspentValue=function(){return this._getInputAmount()-this._getOutputAmount()};ue.prototype._clearSignatures=function(){Ae.each(this.inputs,function(e){e.clearSignatures!==Fr.prototype.clearSignatures&&e.clearSignatures()})};ue.prototype._estimateSize=function(){var e=8;return e+=PB(this.inputs.length).toBuffer().length,e+=PB(this.outputs.length).toBuffer().length,Ae.each(this.inputs,function(t){e+=t._estimateSize()}),Ae.each(this.outputs,function(t){e+=t.getSize()}),e};ue.prototype._removeOutput=function(e){var t=this.outputs[e];this.outputs=Ae.without(this.outputs,t),this._outputAmount=void 0};ue.prototype.removeOutput=function(e){this._removeOutput(e),this._updateChangeOutput()};ue.prototype.sort=function(){return this.sortInputs(function(e){var t=Array.prototype.concat.apply([],e);return t.sort(function(r,i){return r.prevTxId.compare(i.prevTxId)||r.outputIndex-i.outputIndex}),t}),this.sortOutputs(function(e){var t=Array.prototype.concat.apply([],e);return t.sort(function(r,i){return r.satoshis-i.satoshis||r.script.toBuffer().compare(i.script.toBuffer())}),t}),this};ue.prototype.shuffleOutputs=function(){return this.sortOutputs(Ae.shuffle)};ue.prototype.sortOutputs=function(e){var t=e(this.outputs);return this._newOutputOrder(t)};ue.prototype.sortInputs=function(e){return this.inputs=e(this.inputs),this._clearSignatures(),this};ue.prototype._newOutputOrder=function(e){var t=this.outputs.length!==e.length||Ae.difference(this.outputs,e).length!==0;if(t)throw new jr.Transaction.InvalidSorting;if(!Ae.isUndefined(this._changeIndex)){var r=this.outputs[this._changeIndex];this._changeIndex=e.indexOf(r)}return this.outputs=e,this};ue.prototype.removeInput=function(e,t){var r;if(!t&&Ae.isNumber(e)?r=e:r=Ae.findIndex(this.inputs,function(n){return n.prevTxId.toString("hex")===e&&n.outputIndex===t}),r<0||r>=this.inputs.length)throw new jr.Transaction.InvalidIndex(r,this.inputs.length);var i=this.inputs[r];this.inputs=Ae.without(this.inputs,i),this._inputAmount=void 0,this._updateChangeOutput()};ue.prototype.sign=function(e,t){Qr.checkState(this.hasAllUtxoInfo(),"Not all utxo information is available to sign the transaction.");var r=this;return Ae.isArray(e)?(Ae.each(e,function(i){r.sign(i,t)}),this):(Ae.each(this.getSignatures(e,t),function(i){r.applySignature(i)}),this)};ue.prototype.getSignatures=function(e,t){e=new R9(e),t=t||tm.SIGHASH_ALL|tm.SIGHASH_FORKID;var r=this,i=[],n=BB.sha256ripemd160(e.publicKey.toBuffer());return Ae.each(this.inputs,function(a,s){Ae.each(a.getSignatures(r,e,s,t,n),function(u){i.push(u)})}),i};ue.prototype.applySignature=function(e){return this.inputs[e.inputIndex].addSignature(this,e),this};ue.prototype.isFullySigned=function(){return Ae.each(this.inputs,function(e){if(e.isFullySigned===Fr.prototype.isFullySigned)throw new jr.Transaction.UnableToVerifySignature("Unrecognized script kind, or not enough information to execute script.This usually happens when creating a transaction from a serialized transaction")}),Ae.every(Ae.map(this.inputs,function(e){return e.isFullySigned()}))};ue.prototype.isValidSignature=function(e){var t=this;if(this.inputs[e.inputIndex].isValidSignature===Fr.prototype.isValidSignature)throw new jr.Transaction.UnableToVerifySignature("Unrecognized script kind, or not enough information to execute script.This usually happens when creating a transaction from a serialized transaction");return this.inputs[e.inputIndex].isValidSignature(t,e)};ue.prototype.verifySignature=function(e,t,r,i,n,o){return NB.verify(this,e,t,r,i,n,o)};ue.prototype.verify=function(){if(this.inputs.length===0)return"transaction txins empty";if(this.outputs.length===0)return"transaction txouts empty";for(var e=new em(0),t=0;t<this.outputs.length;t++){var r=this.outputs[t];if(r.invalidSatoshis())return"transaction txout "+t+" satoshis is invalid";if(r._satoshisBN.gt(new em(ue.MAX_MONEY,10)))return"transaction txout "+t+" greater than MAX_MONEY";if(e=e.add(r._satoshisBN),e.gt(new em(ue.MAX_MONEY)))return"transaction txout "+t+" total output greater than MAX_MONEY"}if(this.toBuffer().length>L9)return"transaction over the maximum block size";var i={};for(t=0;t<this.inputs.length;t++){var n=this.inputs[t],o=n.prevTxId+":"+n.outputIndex;if(!Ae.isUndefined(i[o]))return"transaction input "+t+" duplicate input";i[o]=!0}var a=this.isCoinbase();if(a){var s=this.inputs[0]._scriptBuffer;if(s.length<2||s.length>100)return"coinbase transaction script size invalid"}else for(t=0;t<this.inputs.length;t++)if(this.inputs[t].isNull())return"transaction input "+t+" has null input";return!0};ue.prototype.isCoinbase=function(){return this.inputs.length===1&&this.inputs[0].isNull()};ue.prototype.sighash=function(e,t,r,i,n){t=t||tm.SIGHASH_ALL|tm.SIGHASH_FORKID;var o=this.inputs[e];if(!o)throw new Error("Input index "+e+" does not exist");return!r&&o.output&&(r=o.output.script),!i&&o.output&&(i=new em(o.output.satoshis)),n=n||B9,NB.sighash(this,t,e,r,i,n)};MB.exports=ue});var zt=T((Hse,su)=>{g();su.exports=S_();su.exports.Input=ho();su.exports.Output=gi();su.exports.UnspentOutput=E_();su.exports.Signature=Hc();su.exports.Sighash=mi()});var hn=T((Use,FB)=>{"use strict";g();var rm=at(),im=Kg(),j=Pr(),we=Ke(),fh=Le(),ma=gt(),O_=sr();function DB(e){return e.map(function(t){return f.Buffer.isBuffer(t)?f.Buffer.from(t):t})}var L=function e(t){if(!(this instanceof e))return new e(t);t?(this.initialize(),this.set(t)):this.initialize()};L.prototype._verifyCore=function(e,t,r,i,n,o){var a=zt();if(rm.isUndefined(r)&&(r=new a),rm.isUndefined(i)&&(i=0),rm.isUndefined(n)&&(n=L.currentConsensusFlags(),o||(n&=~L.SCRIPT_ENABLE_SIGHASH_FORKID)),n&L.SCRIPT_ENABLE_SIGHASH_FORKID&&(n|=L.SCRIPT_VERIFY_STRICTENC,!o))throw new Error("internal error - need satoshisBN to verify FORKID transactions");this.set({script:e,tx:r,nin:i,flags:n,satoshisBN:o});var s;if((n&L.SCRIPT_UTXO_AFTER_CHRONICLE)!==0&&(n&L.SCRIPT_UTXO_AFTER_GENESIS)===0)return this.errstr="SCRIPT_ERR_INVALID_FLAGS",!1;if((n&L.SCRIPT_VERIFY_SIGPUSHONLY)!==0){var u=(n&L.SCRIPT_CHRONICLE)!==0,c=(n&L.SCRIPT_GENESIS)!==0&&!u||u&&UB(n,r);if(c&&!e.isPushOnly())return this.errstr="SCRIPT_ERR_SIG_PUSHONLY",!1}if(!this.evaluate())return!1;var l=(n&L.SCRIPT_VERIFY_P2SH)!==0&&(n&L.SCRIPT_UTXO_AFTER_GENESIS)===0;l&&(s=this.stack.slice());var p=this.stack;if(this.initialize(),this.set({script:t,stack:p,tx:r,nin:i,flags:n,satoshisBN:o}),!this.evaluate())return!1;if(this.stack.length===0)return this.errstr="SCRIPT_ERR_EVAL_FALSE_NO_RESULT",!1;var d=this.stack[this.stack.length-1];if(!L.castToBool(d))return this.errstr="SCRIPT_ERR_EVAL_FALSE_IN_STACK",!1;if(l&&t.isScriptHashOut()){if(!e.isPushOnly())return this.errstr="SCRIPT_ERR_SIG_PUSHONLY",!1;if(s.length===0)throw new Error("internal error - stack copy empty");var v=s[s.length-1],_=im.fromBuffer(v);if(s.pop(),this.initialize(),this.set({script:_,stack:s,tx:r,nin:i,flags:n,satoshisBN:o}),!this.evaluate())return!1;if(s.length===0)return this.errstr="SCRIPT_ERR_EVAL_FALSE_NO_P2SH_STACK",!1;if(!L.castToBool(s[s.length-1]))return this.errstr="SCRIPT_ERR_EVAL_FALSE_IN_P2SH_STACK",!1}if((n&L.SCRIPT_VERIFY_CLEANSTACK)!==0){if((n&L.SCRIPT_VERIFY_P2SH)===0)return this.errstr="SCRIPT_ERR_INVALID_FLAGS",!1;if(this.enforceNonMalleability()&&this.stack.length!==1)return this.errstr="SCRIPT_ERR_CLEANSTACK",!1}return!0};FB.exports=L;L.prototype.initialize=function(e){this.stack=[],this.altstack=[],this.pc=0,this.pbegincodehash=0,this.nOpCount=0,this.returned=!1,this.nonTopLevelReturnAfterGenesis=!1,this.vfExec=[],this.vfElse=[],this.errstr="",this.flags=0};L.prototype.set=function(e){this.script=e.script||this.script,this.tx=e.tx||this.tx,this.nin=typeof e.nin<"u"?e.nin:this.nin,this.satoshisBN=e.satoshisBN||this.satoshisBN,this.stack=e.stack||this.stack,this.altstack=e.altstack||this.altstack,this.pc=typeof e.pc<"u"?e.pc:this.pc,this.pbegincodehash=typeof e.pbegincodehash<"u"?e.pbegincodehash:this.pbegincodehash,this.nOpCount=typeof e.nOpCount<"u"?e.nOpCount:this.nOpCount,this.returned=typeof e.returned<"u"?e.returned:this.returned,this.nonTopLevelReturnAfterGenesis=typeof e.nonTopLevelReturnAfterGenesis<"u"?e.nonTopLevelReturnAfterGenesis:this.nonTopLevelReturnAfterGenesis,this.vfExec=e.vfExec||this.vfExec,this.vfElse=e.vfElse||this.vfElse,this.errstr=e.errstr||this.errstr,this.flags=typeof e.flags<"u"?e.flags:this.flags};L.true=f.Buffer.from([1]);L.false=f.Buffer.from([]);L.MAX_SCRIPT_ELEMENT_SIZE=520;L.MAXIMUM_ELEMENT_SIZE=4;L.MAX_OPS_PER_SCRIPT=500;L.MAX_SCRIPT_SIZE=1e4;L.UNLIMITED=Number.MAX_SAFE_INTEGER;L.MAX_SCRIPT_NUM_LENGTH_AFTER_GENESIS=75e4;L.MAX_SCRIPT_NUM_LENGTH_AFTER_CHRONICLE=32e6;L.MAX_PUBKEYS_PER_MULTISIG_AFTER_GENESIS=4294967295;L.MAX_STACK_SIZE=1e3;L.MAX_STACK_MEMORY_USAGE_AFTER_GENESIS=L.UNLIMITED;L.STACK_MEMORY_USAGE_POLICY=100*1024*1024;L.STACK_ELEMENT_OVERHEAD=32;L.LOCKTIME_THRESHOLD=5e8;L.LOCKTIME_THRESHOLD_BN=new we(L.LOCKTIME_THRESHOLD);L.useGenesisLimits=function(e){return e=e||2147483647,L.MAX_SCRIPT_ELEMENT_SIZE=e,L.MAX_OPS_PER_SCRIPT=e,L.MAX_SCRIPT_SIZE=e,L};L.getLimits=function(){return{maxScriptElementSize:L.MAX_SCRIPT_ELEMENT_SIZE,maximumElementSize:L.MAXIMUM_ELEMENT_SIZE,maxOpsPerScript:L.MAX_OPS_PER_SCRIPT,maxScriptSize:L.MAX_SCRIPT_SIZE}};L.setLimits=function(e){return e=e||{},e.maxScriptElementSize!=null&&(L.MAX_SCRIPT_ELEMENT_SIZE=e.maxScriptElementSize),e.maximumElementSize!=null&&(L.MAXIMUM_ELEMENT_SIZE=e.maximumElementSize),e.maxOpsPerScript!=null&&(L.MAX_OPS_PER_SCRIPT=e.maxOpsPerScript),e.maxScriptSize!=null&&(L.MAX_SCRIPT_SIZE=e.maxScriptSize),L};L.SCRIPT_VERIFY_NONE=0;L.SCRIPT_VERIFY_P2SH=1;L.SCRIPT_VERIFY_STRICTENC=2;L.SCRIPT_VERIFY_DERSIG=4;L.SCRIPT_VERIFY_LOW_S=8;L.SCRIPT_VERIFY_NULLDUMMY=16;L.SCRIPT_VERIFY_SIGPUSHONLY=32;L.SCRIPT_VERIFY_MINIMALDATA=64;L.SCRIPT_VERIFY_DISCOURAGE_UPGRADABLE_NOPS=128;L.SCRIPT_VERIFY_CLEANSTACK=256;L.SCRIPT_VERIFY_CHECKLOCKTIMEVERIFY=512;L.SCRIPT_VERIFY_CHECKSEQUENCEVERIFY=1024;L.SCRIPT_VERIFY_MINIMALIF=8192;L.SCRIPT_VERIFY_NULLFAIL=16384;L.SCRIPT_VERIFY_COMPRESSED_PUBKEYTYPE=32768;L.SCRIPT_ENABLE_SIGHASH_FORKID=65536;L.SCRIPT_ENABLE_REPLAY_PROTECTION=1<<17;L.SCRIPT_ENABLE_MONOLITH_OPCODES=2048;L.SCRIPT_ENABLE_MAGNETIC_OPCODES=4096;L.SCRIPT_GENESIS=1<<18;L.SCRIPT_UTXO_AFTER_GENESIS=1<<19;L.SCRIPT_ENABLE_CHRONICLE=1<<20;L.SCRIPT_CHRONICLE=L.SCRIPT_ENABLE_CHRONICLE;L.SCRIPT_UTXO_AFTER_CHRONICLE=1<<21;L.CHRONICLE_ACTIVATION_HEIGHT=943816;L.ERA_SENSITIVE_ERRORS={SCRIPT_ERR_PUSH_SIZE:{cap:"stack element size (capped at 520 bytes pre-Genesis, unbounded after)",lifts:L.SCRIPT_UTXO_AFTER_GENESIS},SCRIPT_ERR_SCRIPT_SIZE:{cap:"total script size (capped at 10,000 bytes pre-Genesis, unbounded after)",lifts:L.SCRIPT_UTXO_AFTER_GENESIS},SCRIPT_ERR_OP_COUNT:{cap:"opcode count (capped at 201 pre-Genesis, unbounded after)",lifts:L.SCRIPT_UTXO_AFTER_GENESIS},SCRIPT_ERR_SCRIPTNUM_OVERFLOW:{cap:"script number width (4 bytes pre-Genesis, 750,000 after Genesis, 32,000,000 after Chronicle)",lifts:L.SCRIPT_UTXO_AFTER_GENESIS|L.SCRIPT_UTXO_AFTER_CHRONICLE}};L.ERA_FLAGS=L.SCRIPT_GENESIS|L.SCRIPT_UTXO_AFTER_GENESIS|L.SCRIPT_ENABLE_CHRONICLE|L.SCRIPT_UTXO_AFTER_CHRONICLE;L.eraDiagnostics=!(typeof b.default<"u"&&b.default.env&&b.default.env.BSV_NO_ERA_HINT==="1");var I_=!1;L.prototype._eraDiagnose=function(e){if(e!==void 0){var t=L.ERA_SENSITIVE_ERRORS[this.errstr];if(t&&(e&t.lifts)===0){var r=t.cap;this.eraHint=this.errstr+" was produced under PRE-GENESIS limits: "+r+`.
|
|
69
|
+
`));var s=new es({actual:e,expected:t,message:r,operator:n,stackStartFn:i});throw s.generatedMessage=a,s}}qt.match=function e(t,r,i){kk(t,r,i,e,"match")};qt.doesNotMatch=function e(t,r,i){kk(t,r,i,e,"doesNotMatch")};function Bk(){for(var e=arguments.length,t=new Array(e),r=0;r<e;r++)t[r]=arguments[r];xk.apply(void 0,[Bk,t.length].concat(t))}qt.strict=T7(Bk,qt,{equal:qt.strictEqual,deepEqual:qt.deepStrictEqual,notEqual:qt.notStrictEqual,notDeepEqual:qt.notDeepStrictEqual});qt.strict.strict=qt.strict});var lo=T((rse,Lk)=>{"use strict";g();var rh=at(),Ck=Ie(),Bc=Ke(),hr=function e(t){if(!(this instanceof e))return new e(t);if(!rh.isUndefined(t))if(f.Buffer.isBuffer(t))this.set({buf:t});else if(rh.isString(t)){var r=f.Buffer.from(t,"hex");if(r.length*2!==t.length)throw new TypeError("Invalid hex string");this.set({buf:r})}else if(rh.isObject(t)){var i=t;this.set(i)}else throw new TypeError("Unrecognized argument for BufferReader")};hr.prototype.set=function(e){return this.buf=e.buf||this.buf||void 0,this.pos=e.pos||this.pos||0,this};hr.prototype.eof=function(){return this.pos>=this.buf.length};hr.prototype.finished=hr.prototype.eof;hr.prototype.read=function(e){Ck.checkArgument(!rh.isUndefined(e),"Must specify a length");var t=this.buf.slice(this.pos,this.pos+e);return this.pos=this.pos+e,t};hr.prototype.readAll=function(){var e=this.buf.slice(this.pos,this.buf.length);return this.pos=this.buf.length,e};hr.prototype.readUInt8=function(){var e=this.buf.readUInt8(this.pos);return this.pos=this.pos+1,e};hr.prototype.readUInt16BE=function(){var e=this.buf.readUInt16BE(this.pos);return this.pos=this.pos+2,e};hr.prototype.readUInt16LE=function(){var e=this.buf.readUInt16LE(this.pos);return this.pos=this.pos+2,e};hr.prototype.readUInt32BE=function(){var e=this.buf.readUInt32BE(this.pos);return this.pos=this.pos+4,e};hr.prototype.readUInt32LE=function(){var e=this.buf.readUInt32LE(this.pos);return this.pos=this.pos+4,e};hr.prototype.readInt32LE=function(){var e=this.buf.readInt32LE(this.pos);return this.pos=this.pos+4,e};hr.prototype.readUInt64BEBN=function(){var e=this.buf.slice(this.pos,this.pos+8),t=Bc.fromBuffer(e);return this.pos=this.pos+8,t};hr.prototype.readUInt64LEBN=function(){var e=this.buf.readUInt32LE(this.pos),t=this.buf.readUInt32LE(this.pos+4),r=t*4294967296+e,i;if(r<=9007199254740991)i=new Bc(r);else{var n=Array.prototype.slice.call(this.buf,this.pos,this.pos+8);i=new Bc(n,10,"le")}return this.pos=this.pos+8,i};hr.prototype.readVarintNum=function(){var e=this.readUInt8();switch(e){case 253:return this.readUInt16LE();case 254:return this.readUInt32LE();case 255:var t=this.readUInt64LEBN(),r=t.toNumber();if(r<=Math.pow(2,53))return r;throw new Error("number too large to retain precision - use readVarintBN");default:return e}};hr.prototype.readVarLengthBuffer=function(){var e=this.readVarintNum(),t=this.read(e);return Ck.checkState(t.length===e,"Invalid length while reading varlength buffer. Expected to read: "+e+" and read "+t.length),t};hr.prototype.readVarintBuf=function(){var e=this.buf.readUInt8(this.pos);switch(e){case 253:return this.read(3);case 254:return this.read(5);case 255:return this.read(9);default:return this.read(1)}};hr.prototype.readVarintBN=function(){var e=this.readUInt8();switch(e){case 253:return new Bc(this.readUInt16LE());case 254:return new Bc(this.readUInt32LE());case 255:return this.readUInt64LEBN();default:return new Bc(e)}};hr.prototype.reverse=function(){for(var e=f.Buffer.alloc(this.buf.length),t=0;t<e.length;t++)e[t]=this.buf[this.buf.length-1-t];return this.buf=e,this};hr.prototype.readReverse=function(e){rh.isUndefined(e)&&(e=this.buf.length);var t=this.buf.slice(this.pos,this.pos+e);return this.pos=this.pos+e,f.Buffer.from(t).reverse()};Lk.exports=hr});var Pr=T((nse,Mk)=>{"use strict";g();var Nc=at(),ih=Ie(),R7=ni();function dt(e){if(!(this instanceof dt))return new dt(e);var t;if(Nc.isNumber(e))t=e;else if(Nc.isString(e))t=dt.map[e];else throw new TypeError('Unrecognized num type: "'+typeof e+'" for Opcode');return R7.defineImmutable(this,{num:t}),this}dt.fromBuffer=function(e){return ih.checkArgument(f.Buffer.isBuffer(e)),new dt(+("0x"+e.toString("hex")))};dt.fromNumber=function(e){return ih.checkArgument(Nc.isNumber(e)),new dt(e)};dt.fromString=function(e){ih.checkArgument(Nc.isString(e));var t=dt.map[e];if(typeof t>"u")throw new TypeError("Invalid opcodestr");return new dt(t)};dt.prototype.toHex=function(){return this.num.toString(16)};dt.prototype.toBuffer=function(){return f.Buffer.from(this.toHex(),"hex")};dt.prototype.toNumber=function(){return this.num};dt.prototype.toString=function(){var e=dt.reverseMap[this.num];if(typeof e>"u")throw new Error("Opcode does not have a string representation");return e};dt.smallInt=function(e){return ih.checkArgument(Nc.isNumber(e),"Invalid Argument: n should be number"),ih.checkArgument(e>=0&&e<=16,"Invalid Argument: n must be between 0 and 16"),e===0?dt("OP_0"):new dt(dt.map.OP_1+e-1)};dt.map={OP_FALSE:0,OP_0:0,OP_PUSHDATA1:76,OP_PUSHDATA2:77,OP_PUSHDATA4:78,OP_1NEGATE:79,OP_RESERVED:80,OP_TRUE:81,OP_1:81,OP_2:82,OP_3:83,OP_4:84,OP_5:85,OP_6:86,OP_7:87,OP_8:88,OP_9:89,OP_10:90,OP_11:91,OP_12:92,OP_13:93,OP_14:94,OP_15:95,OP_16:96,OP_NOP:97,OP_VER:98,OP_IF:99,OP_NOTIF:100,OP_VERIF:101,OP_VERNOTIF:102,OP_ELSE:103,OP_ENDIF:104,OP_VERIFY:105,OP_RETURN:106,OP_TOALTSTACK:107,OP_FROMALTSTACK:108,OP_2DROP:109,OP_2DUP:110,OP_3DUP:111,OP_2OVER:112,OP_2ROT:113,OP_2SWAP:114,OP_IFDUP:115,OP_DEPTH:116,OP_DROP:117,OP_DUP:118,OP_NIP:119,OP_OVER:120,OP_PICK:121,OP_ROLL:122,OP_ROT:123,OP_SWAP:124,OP_TUCK:125,OP_CAT:126,OP_SPLIT:127,OP_NUM2BIN:128,OP_BIN2NUM:129,OP_SIZE:130,OP_INVERT:131,OP_AND:132,OP_OR:133,OP_XOR:134,OP_EQUAL:135,OP_EQUALVERIFY:136,OP_RESERVED1:137,OP_RESERVED2:138,OP_1ADD:139,OP_1SUB:140,OP_2MUL:141,OP_2DIV:142,OP_NEGATE:143,OP_ABS:144,OP_NOT:145,OP_0NOTEQUAL:146,OP_ADD:147,OP_SUB:148,OP_MUL:149,OP_DIV:150,OP_MOD:151,OP_LSHIFT:152,OP_RSHIFT:153,OP_BOOLAND:154,OP_BOOLOR:155,OP_NUMEQUAL:156,OP_NUMEQUALVERIFY:157,OP_NUMNOTEQUAL:158,OP_LESSTHAN:159,OP_GREATERTHAN:160,OP_LESSTHANOREQUAL:161,OP_GREATERTHANOREQUAL:162,OP_MIN:163,OP_MAX:164,OP_WITHIN:165,OP_RIPEMD160:166,OP_SHA1:167,OP_SHA256:168,OP_HASH160:169,OP_HASH256:170,OP_CODESEPARATOR:171,OP_CHECKSIG:172,OP_CHECKSIGVERIFY:173,OP_CHECKMULTISIG:174,OP_CHECKMULTISIGVERIFY:175,OP_CHECKLOCKTIMEVERIFY:177,OP_CHECKSEQUENCEVERIFY:178,OP_NOP1:176,OP_NOP2:177,OP_NOP3:178,OP_SUBSTR:179,OP_LEFT:180,OP_RIGHT:181,OP_LSHIFTNUM:182,OP_RSHIFTNUM:183,OP_NOP9:184,OP_NOP10:185,OP_PUBKEYHASH:253,OP_PUBKEY:254,OP_INVALIDOPCODE:255};dt.reverseMap=[];for(n_ in dt.map)dt.reverseMap[dt.map[n_]]=n_;var n_;Nc.extend(dt,dt.map);dt.isSmallIntOp=function(e){return e instanceof dt&&(e=e.toNumber()),e===dt.map.OP_0||e>=dt.map.OP_1&&e<=dt.map.OP_16};dt.prototype.inspect=function(){return"<Opcode: "+this.toString()+", hex: "+this.toHex()+", decimal: "+this.num+">"};Mk.exports=dt});var ts=T((ase,Hk)=>{"use strict";g();var o_=Object.create(null),a_=[],s_=!(typeof b.default<"u"&&b.default.env&&b.default.env.BSV_NO_DEPRECATION_WARNINGS==="1");function Dk(e,t){if(!e||typeof e.what!="string"||e.what==="")throw new TypeError(t+"() requires { what: string }")}function k7(e){var t="[@smartledger/bsv] "+e.what+" is deprecated";return e.since&&(t+=" since "+e.since),t+=".",e.why&&(t+=" "+e.why.charAt(0).toUpperCase()+e.why.slice(1)+"."),e.use&&(t+=" Use "+e.use+" instead."),t+=e.removeIn?" It will be removed in "+e.removeIn+".":" A removal version has not been set; it will not be removed in a 9.x release.",t}function la(e){if(!e||!e.what)throw new TypeError("deprecate() requires { what }");if(o_[e.what])return!1;o_[e.what]=!0;var t=k7(e);return a_.push({what:e.what,since:e.since||null,removeIn:e.removeIn||null,use:e.use||null,message:t}),s_&&console.warn(t),!0}la.fn=function(e,t){if(typeof e!="function")throw new TypeError("deprecate.fn() requires a function");Dk(t,"deprecate.fn");var r=function(){return la(t),e.apply(this,arguments)};return Object.defineProperty(r,"name",{value:e.name,configurable:!0}),Object.defineProperty(r,"length",{value:e.length,configurable:!0}),r.__wrapped=e,r.__deprecation=t,r};la.property=function(e,t,r,i){Dk(i,"deprecate.property");var n,o=!1;return Object.defineProperty(e,t,{configurable:!0,enumerable:!0,get:function(){return la(i),o||(n=r(),o=!0),n}}),e};la.fired=function(){return a_.slice()};la.setEnabled=function(e){s_=!!e};la.isEnabled=function(){return s_};la.reset=function(){o_=Object.create(null),a_.length=0};Hk.exports=la});var Kg=T((use,jk)=>{"use strict";g();var B7=fa(),Bn=Ni(),N7=lo(),u_=Le(),ce=Pr(),au=sr(),ou=gt(),qk=ca(),Gt=Ie(),st=at(),c_=pi(),C7=ts(),Uk=rr(),L7=ni(),$=function e(t){if(!(this instanceof e))return new e(t);if(this.chunks=[],f.Buffer.isBuffer(t))return e.fromBuffer(t);if(t instanceof Bn)return e.fromAddress(t);if(t instanceof e)return e.fromBuffer(t.toBuffer());if(st.isString(t))return e.fromString(t);st.isObject(t)&&st.isArray(t.chunks)&&this.set(t)};$.prototype.set=function(e){return Gt.checkArgument(st.isObject(e)),Gt.checkArgument(st.isArray(e.chunks)),this.chunks=e.chunks,this};$.fromBuffer=function(e){var t=new $;t.chunks=[];for(var r=new N7(e);!r.finished();)try{var i=r.readUInt8(),n,o;i>0&&i<ce.OP_PUSHDATA1?(n=i,t.chunks.push({buf:r.read(n),len:n,opcodenum:i})):i===ce.OP_PUSHDATA1?(n=r.readUInt8(),o=r.read(n),t.chunks.push({buf:o,len:n,opcodenum:i})):i===ce.OP_PUSHDATA2?(n=r.readUInt16LE(),o=r.read(n),t.chunks.push({buf:o,len:n,opcodenum:i})):i===ce.OP_PUSHDATA4?(n=r.readUInt32LE(),o=r.read(n),t.chunks.push({buf:o,len:n,opcodenum:i})):t.chunks.push({opcodenum:i})}catch(a){throw a instanceof RangeError?new c_.Script.InvalidBuffer(e.toString("hex")):a}return t};$.prototype.toBuffer=function(){var e=this.chunks,t=0,r,i,n;for(r=0;r<e.length;r++)i=e[r],n=i.opcodenum,t+=1,i.buf&&(n<ce.OP_PUSHDATA1?t+=zg(i.buf):n===ce.OP_PUSHDATA1?t+=1+zg(i.buf):n===ce.OP_PUSHDATA2?t+=2+zg(i.buf):n===ce.OP_PUSHDATA4&&(t+=4+zg(i.buf)));var o=f.Buffer.alloc(t),a=0;for(r=0;r<e.length;r++)i=e[r],n=i.opcodenum,a=o.writeUInt8(i.opcodenum,a),i.buf&&(n<ce.OP_PUSHDATA1?a+=i.buf.copy(o,a):n===ce.OP_PUSHDATA1?(a=o.writeUInt8(i.len,a),a+=i.buf.copy(o,a)):n===ce.OP_PUSHDATA2?(a=o.writeUInt16LE(i.len,a),a+=i.buf.copy(o,a)):n===ce.OP_PUSHDATA4&&(a=o.writeUInt32LE(i.len,a),a+=i.buf.copy(o,a)));return o};function zg(e){if(!f.Buffer.isBuffer(e))throw new B7.AssertionError({message:"chunk data must be a Buffer",actual:e,expected:"Buffer",operator:"isBuffer"});return e.length}function Fk(e){if(/^0x[0-9a-fA-F]{2}$/.test(e)){var t=parseInt(e.slice(2),16);return t>ce.OP_PUSHDATA4?t:void 0}}$.fromASM=function(e){var t=new $;if(t.chunks=[],e==="")return t;for(var r=e.split(" "),i=0;i<r.length;){var n=r[i],o=ce(n),a=o.toNumber(),s=Fk(n);if(s!==void 0)t.chunks.push({opcodenum:s}),i=i+1;else if(n==="0")a=0,t.chunks.push({opcodenum:a}),i=i+1;else if(n==="-1")a=ce.OP_1NEGATE,t.chunks.push({opcodenum:a}),i=i+1;else if(st.isUndefined(a)){var u=f.Buffer.from(r[i],"hex");if(u.toString("hex")!==r[i])throw new Error("invalid hex string in script");var c=u.length;c>=0&&c<ce.OP_PUSHDATA1?a=c:c<Math.pow(2,8)?a=ce.OP_PUSHDATA1:c<Math.pow(2,16)?a=ce.OP_PUSHDATA2:c<Math.pow(2,32)&&(a=ce.OP_PUSHDATA4),t.chunks.push({buf:u,len:u.length,opcodenum:a}),i=i+1}else t.chunks.push({opcodenum:a}),i=i+1}return t};var M7=/^(?:[0-9a-fA-F]{2})*$/;$.fromHex=function(e){return typeof e=="string"&&!M7.test(e)&&C7({what:"Script.fromHex() with a string that is not whole hex",since:"9.17.0",removeIn:"10.0.0",why:"Buffer.from() stops at the first character it cannot decode, so the script is silently truncated",use:"a round-trip check, Script.fromHex(h).toHex() === h.toLowerCase()"}),new $(Uk.Buffer.from(e,"hex"))};$.fromString=function(e){if(L7.isHexa(e)||e.length===0)return new $(Uk.Buffer.from(e,"hex"));var t=new $;t.chunks=[];for(var r=e.split(" "),i=0;i<r.length;){var n=r[i],o=ce(n),a=o.toNumber(),s=Fk(n);if(s!==void 0)t.chunks.push({opcodenum:s}),i=i+1;else if(st.isUndefined(a))if(a=parseInt(n),a>0&&a<ce.OP_PUSHDATA1)t.chunks.push({buf:f.Buffer.from(r[i+1].slice(2),"hex"),len:a,opcodenum:a}),i=i+2;else throw new Error("Invalid script: "+JSON.stringify(e));else if(a===ce.OP_PUSHDATA1||a===ce.OP_PUSHDATA2||a===ce.OP_PUSHDATA4){if(r[i+2].slice(0,2)!=="0x")throw new Error("Pushdata data must start with 0x");t.chunks.push({buf:f.Buffer.from(r[i+2].slice(2),"hex"),len:parseInt(r[i+1]),opcodenum:a}),i=i+3}else t.chunks.push({opcodenum:a}),i=i+1}return t};$.prototype._chunkToString=function(e,t){var r=e.opcodenum,i=t==="asm",n="";if(e.buf){var a=r===ce.OP_PUSHDATA1||r===ce.OP_PUSHDATA2||r===ce.OP_PUSHDATA4;!i&&a&&(n=n+" "+ce(r).toString()),e.len>0?i?n=n+" "+e.buf.toString("hex"):n=n+" "+e.len+" 0x"+e.buf.toString("hex"):i?n=n+" 0":a?n=n+" 0 0x":n=n+" OP_0"}else if(typeof ce.reverseMap[r]<"u")i?r===0?n=n+" 0":r===79?n=n+" -1":n=n+" "+ce(r).toString():n=n+" "+ce(r).toString();else{var o=r.toString(16);o.length%2!==0&&(o="0"+o),n=n+" 0x"+o}return n};$.prototype.toASM=function(){for(var e="",t=0;t<this.chunks.length;t++){var r=this.chunks[t];e+=this._chunkToString(r,"asm")}return e.substr(1)};$.prototype.toString=function(){for(var e="",t=0;t<this.chunks.length;t++){var r=this.chunks[t];e+=this._chunkToString(r)}return e.substr(1)};$.prototype.toHex=function(){return this.toBuffer().toString("hex")};$.prototype.inspect=function(){return"<Script: "+this.toString()+">"};$.prototype.isPublicKeyHashOut=function(){return!!(this.chunks.length===5&&this.chunks[0].opcodenum===ce.OP_DUP&&this.chunks[1].opcodenum===ce.OP_HASH160&&this.chunks[2].buf&&this.chunks[2].buf.length===20&&this.chunks[3].opcodenum===ce.OP_EQUALVERIFY&&this.chunks[4].opcodenum===ce.OP_CHECKSIG)};$.prototype.isPublicKeyHashOutPrefix=function(){return!!(this.chunks.length>=5&&this.chunks[0].opcodenum===ce.OP_DUP&&this.chunks[1].opcodenum===ce.OP_HASH160&&this.chunks[2].buf&&this.chunks[2].buf.length===20&&this.chunks[3].opcodenum===ce.OP_EQUALVERIFY&&this.chunks[4].opcodenum===ce.OP_CHECKSIG)};$.prototype.isPublicKeyHashIn=function(){if(this.chunks.length===2){var e=this.chunks[0].buf,t=this.chunks[1].buf;if(e&&e.length&&e[0]===48&&t&&t.length){var r=t[0];if((r===4||r===6||r===7)&&t.length===65)return!0;if((r===3||r===2)&&t.length===33)return!0}}return!1};$.prototype.getPublicKey=function(){return Gt.checkState(this.isPublicKeyOut(),"Can't retrieve PublicKey from a non-PK output"),this.chunks[0].buf};$.prototype.getPublicKeyHash=function(){return Gt.checkState(this.isPublicKeyHashOut(),"Can't retrieve PublicKeyHash from a non-PKH output"),this.chunks[2].buf};$.prototype.isPublicKeyOut=function(){if(this.chunks.length===2&&this.chunks[0].buf&&this.chunks[0].buf.length&&this.chunks[1].opcodenum===ce.OP_CHECKSIG){var e=this.chunks[0].buf,t=e[0],r=!1;if(((t===4||t===6||t===7)&&e.length===65||(t===3||t===2)&&e.length===33)&&(r=!0),r)return au.isValid(e)}return!1};$.prototype.isPublicKeyIn=function(){if(this.chunks.length===1){var e=this.chunks[0].buf;if(e&&e.length&&e[0]===48)return!0}return!1};$.prototype.isScriptHashOut=function(){var e=this.toBuffer();return e.length===23&&e[0]===ce.OP_HASH160&&e[1]===20&&e[e.length-1]===ce.OP_EQUAL};$.prototype.isScriptHashIn=function(){if(this.chunks.length<=1)return!1;var e=this.chunks[this.chunks.length-1],t=e.buf;if(!t)return!1;var r;try{r=$.fromBuffer(t)}catch(n){if(n instanceof c_.Script.InvalidBuffer)return!1;throw n}var i=r.classify();return i!==$.types.UNKNOWN};$.prototype.isMultisigOut=function(){return this.chunks.length>3&&ce.isSmallIntOp(this.chunks[0].opcodenum)&&this.chunks.slice(1,this.chunks.length-2).every(function(e){return e.buf&&f.Buffer.isBuffer(e.buf)})&&ce.isSmallIntOp(this.chunks[this.chunks.length-2].opcodenum)&&this.chunks[this.chunks.length-1].opcodenum===ce.OP_CHECKMULTISIG};$.prototype.isMultisigIn=function(){return this.chunks.length>=2&&this.chunks[0].opcodenum===0&&this.chunks.slice(1,this.chunks.length).every(function(e){return e.buf&&f.Buffer.isBuffer(e.buf)&&ou.isTxDER(e.buf)})};$.prototype.isDataOut=function(){var e=this.chunks.length>=1&&this.chunks[0].opcodenum===ce.OP_RETURN;if(!e)return!1;var t=this.chunks.slice(1),r=new $({chunks:t});return r.isPushOnly()};$.prototype.isSafeDataOut=function(){if(this.chunks.length<2||this.chunks[0].opcodenum!==ce.OP_FALSE)return!1;var e=this.chunks.slice(1),t=new $({chunks:e});return t.isDataOut()};$.prototype.getData=function(){if(this.isSafeDataOut()){var e=this.chunks.slice(2),t=e.map(r=>r.buf);return t}if(this.isDataOut()||this.isScriptHashOut())return st.isUndefined(this.chunks[1])?f.Buffer.alloc(0):f.Buffer.from(this.chunks[1].buf);if(this.isPublicKeyHashOut())return f.Buffer.from(this.chunks[2].buf);throw new Error("Unrecognized script type to get data from")};$.prototype.isPushOnly=function(){return st.every(this.chunks,function(e){return e.opcodenum<=ce.OP_16||e.opcodenum===ce.OP_PUSHDATA1||e.opcodenum===ce.OP_PUSHDATA2||e.opcodenum===ce.OP_PUSHDATA4})};$.types={};$.types.UNKNOWN="Unknown";$.types.PUBKEY_OUT="Pay to public key";$.types.PUBKEY_IN="Spend from public key";$.types.PUBKEYHASH_OUT="Pay to public key hash";$.types.PUBKEYHASH_IN="Spend from public key hash";$.types.SCRIPTHASH_OUT="Pay to script hash";$.types.SCRIPTHASH_IN="Spend from script hash";$.types.MULTISIG_OUT="Pay to multisig";$.types.MULTISIG_IN="Spend from multisig";$.types.DATA_OUT="Data push";$.types.SAFE_DATA_OUT="Safe data push";$.OP_RETURN_STANDARD_SIZE=220;$.prototype.classify=function(){if(this._isInput)return this.classifyInput();if(this._isOutput)return this.classifyOutput();var e=this.classifyOutput();return e!==$.types.UNKNOWN?e:this.classifyInput()};$.outputIdentifiers={};$.outputIdentifiers.PUBKEY_OUT=$.prototype.isPublicKeyOut;$.outputIdentifiers.PUBKEYHASH_OUT=$.prototype.isPublicKeyHashOut;$.outputIdentifiers.MULTISIG_OUT=$.prototype.isMultisigOut;$.outputIdentifiers.SCRIPTHASH_OUT=$.prototype.isScriptHashOut;$.outputIdentifiers.DATA_OUT=$.prototype.isDataOut;$.outputIdentifiers.SAFE_DATA_OUT=$.prototype.isSafeDataOut;$.prototype.classifyOutput=function(){for(var e in $.outputIdentifiers)if($.outputIdentifiers[e].bind(this)())return $.types[e];return $.types.UNKNOWN};$.inputIdentifiers={};$.inputIdentifiers.PUBKEY_IN=$.prototype.isPublicKeyIn;$.inputIdentifiers.PUBKEYHASH_IN=$.prototype.isPublicKeyHashIn;$.inputIdentifiers.MULTISIG_IN=$.prototype.isMultisigIn;$.inputIdentifiers.SCRIPTHASH_IN=$.prototype.isScriptHashIn;$.prototype.classifyInput=function(){for(var e in $.inputIdentifiers)if($.inputIdentifiers[e].bind(this)())return $.types[e];return $.types.UNKNOWN};$.prototype.isStandard=function(){return this.classify()!==$.types.UNKNOWN};$.prototype.prepend=function(e){return this._addByType(e,!0),this};$.prototype.equals=function(e){if(Gt.checkState(e instanceof $,"Must provide another script"),this.chunks.length!==e.chunks.length)return!1;var t;for(t=0;t<this.chunks.length;t++){if(f.Buffer.isBuffer(this.chunks[t].buf)&&!f.Buffer.isBuffer(e.chunks[t].buf)||f.Buffer.isBuffer(this.chunks[t].buf)&&!this.chunks[t].buf.equals(e.chunks[t].buf))return!1;if(this.chunks[t].opcodenum!==e.chunks[t].opcodenum)return!1}return!0};$.prototype.add=function(e){return this._addByType(e,!1),this};$.prototype._addByType=function(e,t){if(typeof e=="string")this._addOpcode(e,t);else if(typeof e=="number")this._addOpcode(e,t);else if(e instanceof ce)this._addOpcode(e,t);else if(f.Buffer.isBuffer(e))this._addBuffer(e,t);else if(e instanceof $)this.chunks=this.chunks.concat(e.chunks);else if(typeof e=="object")this._insertAtPosition(e,t);else throw new Error("Invalid script chunk")};$.prototype._insertAtPosition=function(e,t){t?this.chunks.unshift(e):this.chunks.push(e)};$.prototype._addOpcode=function(e,t){var r;return typeof e=="number"?r=e:e instanceof ce?r=e.toNumber():r=ce(e).toNumber(),this._insertAtPosition({opcodenum:r},t),this};$.prototype._addBuffer=function(e,t){var r,i=e.length;if(i>=0&&i<ce.OP_PUSHDATA1)r=i;else if(i<Math.pow(2,8))r=ce.OP_PUSHDATA1;else if(i<Math.pow(2,16))r=ce.OP_PUSHDATA2;else if(i<Math.pow(2,32))r=ce.OP_PUSHDATA4;else throw new Error("You can't push that much data");return this._insertAtPosition({buf:e,len:i,opcodenum:r},t),this};$.prototype.removeCodeseparators=function(){for(var e=[],t=0;t<this.chunks.length;t++)this.chunks[t].opcodenum!==ce.OP_CODESEPARATOR&&e.push(this.chunks[t]);return this.chunks=e,this};$.buildMultisigOut=function(e,t,r){Gt.checkArgument(t<=e.length,"Number of required signatures must be less than or equal to the number of public keys"),r=r||{};var i=new $;i.add(ce.smallInt(t)),e=st.map(e,au);var n=e;r.noSorting||(n=e.map(s=>s.toString("hex")).sort().map(s=>new au(s)));for(var o=0;o<n.length;o++){var a=n[o];i.add(a.toBuffer())}return i.add(ce.smallInt(e.length)),i.add(ce.OP_CHECKMULTISIG),i};$.buildMultisigIn=function(e,t,r,i){Gt.checkArgument(st.isArray(e)),Gt.checkArgument(st.isNumber(t)),Gt.checkArgument(st.isArray(r)),i=i||{};var n=new $;return n.add(ce.OP_0),st.each(r,function(o){Gt.checkArgument(f.Buffer.isBuffer(o),"Signatures must be an array of Buffers"),n.add(o)}),n};$.buildP2SHMultisigIn=function(e,t,r,i){Gt.checkArgument(st.isArray(e)),Gt.checkArgument(st.isNumber(t)),Gt.checkArgument(st.isArray(r)),i=i||{};var n=new $;return n.add(ce.OP_0),st.each(r,function(o){Gt.checkArgument(f.Buffer.isBuffer(o),"Signatures must be an array of Buffers"),n.add(o)}),n.add((i.cachedMultisig||$.buildMultisigOut(e,t,i)).toBuffer()),n};$.buildPublicKeyHashOut=function(e){Gt.checkArgument(!st.isUndefined(e)),Gt.checkArgument(e instanceof au||e instanceof Bn||st.isString(e)),e instanceof au?e=e.toAddress():st.isString(e)&&(e=new Bn(e));var t=new $;return t.add(ce.OP_DUP).add(ce.OP_HASH160).add(e.hashBuffer).add(ce.OP_EQUALVERIFY).add(ce.OP_CHECKSIG),t._network=e.network,t};$.buildPublicKeyOut=function(e){Gt.checkArgument(e instanceof au);var t=new $;return t.add(e.toBuffer()).add(ce.OP_CHECKSIG),t};$.buildDataOut=function(e,t){Gt.checkArgument(st.isUndefined(e)||st.isString(e)||st.isArray(e)||f.Buffer.isBuffer(e));var r=e;st.isArray(r)||(r=[e]);var i=new $;i.add(ce.OP_RETURN);for(let n of r)Gt.checkArgument(st.isUndefined(n)||st.isString(n)||f.Buffer.isBuffer(n)),st.isString(n)&&(n=f.Buffer.from(n,t)),st.isUndefined(n)||i.add(n);return i};$.buildSafeDataOut=function(e,t){var r=$.buildDataOut(e,t),i=new $;return i.add(ce.OP_FALSE),i.add(r),i};$.buildScriptHashOut=function(e){Gt.checkArgument(e instanceof $||e instanceof Bn&&e.isPayToScriptHash());var t=new $;return t.add(ce.OP_HASH160).add(e instanceof Bn?e.hashBuffer:u_.sha256ripemd160(e.toBuffer())).add(ce.OP_EQUAL),t._network=e._network||e.network,t};$.buildPublicKeyIn=function(e,t){Gt.checkArgument(e instanceof ou||f.Buffer.isBuffer(e)),Gt.checkArgument(st.isUndefined(t)||st.isNumber(t)),e instanceof ou&&(e=e.toBuffer());var r=new $;return r.add(f.Buffer.concat([e,f.Buffer.from([(t||ou.SIGHASH_ALL)&255])])),r};$.buildPublicKeyHashIn=function(e,t,r){Gt.checkArgument(t instanceof ou||f.Buffer.isBuffer(t)),Gt.checkArgument(st.isUndefined(r)||st.isNumber(r)),t instanceof ou&&(t=t.toBuffer());var i=new $().add(f.Buffer.concat([t,f.Buffer.from([(r||ou.SIGHASH_ALL)&255])])).add(new au(e).toBuffer());return i};$.empty=function(){return new $};$.prototype.toScriptHashOut=function(){return $.buildScriptHashOut(this)};$.fromAddress=function(e){if(e=Bn(e),e.isPayToScriptHash())return $.buildScriptHashOut(e);if(e.isPayToPublicKeyHash())return $.buildPublicKeyHashOut(e);throw new c_.Script.UnrecognizedAddress(e)};$.prototype.getAddressInfo=function(e){if(this._isInput)return this._getInputAddressInfo();if(this._isOutput)return this._getOutputAddressInfo();var t=this._getOutputAddressInfo();return t||this._getInputAddressInfo()};$.prototype._getOutputAddressInfo=function(){var e={};if(this.isScriptHashOut())e.hashBuffer=this.getData(),e.type=Bn.PayToScriptHash;else if(this.isPublicKeyHashOut())e.hashBuffer=this.getData(),e.type=Bn.PayToPublicKeyHash;else return!1;return e};$.prototype._getInputAddressInfo=function(){var e={};if(this.isPublicKeyHashIn())e.hashBuffer=u_.sha256ripemd160(this.chunks[1].buf),e.type=Bn.PayToPublicKeyHash;else if(this.isScriptHashIn())e.hashBuffer=u_.sha256ripemd160(this.chunks[this.chunks.length-1].buf),e.type=Bn.PayToScriptHash;else return!1;return e};$.prototype.toAddress=function(e){var t=this.getAddressInfo();return t?(t.network=qk.get(e)||this._network||qk.defaultNetwork,new Bn(t)):!1};$.prototype.findAndDelete=function(e){for(var t=e.toBuffer(),r=t.length?t[0]:-1,i=0;i<this.chunks.length;i++){var n=this.chunks[i];if(!(n.opcodenum!==r&&D7(n))){var o=$({chunks:[n]}).toBuffer();t.equals(o)&&(this.chunks.splice(i,1),i--)}}return this};function D7(e){var t=e.opcodenum;if(typeof t!="number"||!Number.isInteger(t)||t<0||t>255)return!1;if(!e.buf||t>ce.OP_PUSHDATA4)return!0;if(!f.Buffer.isBuffer(e.buf))return!1;var r=e.len;return t===ce.OP_PUSHDATA1?Number.isInteger(r)&&r>=0&&r<=255:t===ce.OP_PUSHDATA2?Number.isInteger(r)&&r>=0&&r<=65535:t===ce.OP_PUSHDATA4?Number.isInteger(r)&&r>=0&&r<=4294967295:!0}$.prototype.checkMinimalPush=function(e){var t=this.chunks[e],r=t.buf,i=t.opcodenum;return r?r.length===0?i===ce.OP_0:r.length===1&&r[0]>=1&&r[0]<=16?i===ce.OP_1+(r[0]-1):r.length===1&&r[0]===129?i===ce.OP_1NEGATE:r.length<=75?i===r.length:r.length<=255?i===ce.OP_PUSHDATA1:r.length<=65535?i===ce.OP_PUSHDATA2:!0:!0};$.prototype._decodeOP_N=function(e){if(e===ce.OP_0)return 0;if(e>=ce.OP_1&&e<=ce.OP_16)return e-(ce.OP_1-1);throw new Error("Invalid opcode: "+JSON.stringify(e))};$.prototype.getSignatureOperationsCount=function(e){e=st.isUndefined(e)?!0:e;var t=this,r=0,i=ce.OP_INVALIDOPCODE;return st.each(t.chunks,function(o){var a=o.opcodenum;a===ce.OP_CHECKSIG||a===ce.OP_CHECKSIGVERIFY?r++:(a===ce.OP_CHECKMULTISIG||a===ce.OP_CHECKMULTISIGVERIFY)&&(e&&i>=ce.OP_1&&i<=ce.OP_16?r+=t._decodeOP_N(i):r+=20),i=a}),r};jk.exports=$});var Nn=T((fse,Kk)=>{"use strict";g();var zk=fa(),dr=function e(t){if(!(this instanceof e))return new e(t);this.bufLen=0,t?this.set(t):this.bufs=[]};dr.prototype.set=function(e){return this.bufs=e.bufs||this.bufs||[],this.bufLen=this.bufs.reduce(function(t,r){return t+r.length},0),this};dr.prototype.toBuffer=function(){return this.concat()};dr.prototype.concat=function(){return f.Buffer.concat(this.bufs,this.bufLen)};dr.prototype.write=function(e){return zk(f.Buffer.isBuffer(e)),this.bufs.push(e),this.bufLen+=e.length,this};dr.prototype.writeReverse=function(e){return zk(f.Buffer.isBuffer(e)),this.bufs.push(f.Buffer.from(e).reverse()),this.bufLen+=e.length,this};dr.prototype.writeUInt8=function(e){var t=f.Buffer.alloc(1);return t.writeUInt8(e,0),this.write(t),this};dr.prototype.writeUInt16BE=function(e){var t=f.Buffer.alloc(2);return t.writeUInt16BE(e,0),this.write(t),this};dr.prototype.writeUInt16LE=function(e){var t=f.Buffer.alloc(2);return t.writeUInt16LE(e,0),this.write(t),this};dr.prototype.writeUInt32BE=function(e){var t=f.Buffer.alloc(4);return t.writeUInt32BE(e,0),this.write(t),this};dr.prototype.writeInt32LE=function(e){var t=f.Buffer.alloc(4);return t.writeInt32LE(e,0),this.write(t),this};dr.prototype.writeUInt32LE=function(e){var t=f.Buffer.alloc(4);return t.writeUInt32LE(e,0),this.write(t),this};dr.prototype.writeUInt64BEBN=function(e){var t=e.toBuffer({size:8});return this.write(t),this};dr.prototype.writeUInt64LEBN=function(e){var t=e.toBuffer({size:8});return this.writeReverse(t),this};dr.prototype.writeVarintNum=function(e){var t=dr.varintBufNum(e);return this.write(t),this};dr.prototype.writeVarintBN=function(e){var t=dr.varintBufBN(e);return this.write(t),this};dr.varintBufNum=function(e){var t;return e<253?(t=f.Buffer.alloc(1),t.writeUInt8(e,0)):e<65536?(t=f.Buffer.alloc(3),t.writeUInt8(253,0),t.writeUInt16LE(e,1)):e<4294967296?(t=f.Buffer.alloc(5),t.writeUInt8(254,0),t.writeUInt32LE(e,1)):(t=f.Buffer.alloc(9),t.writeUInt8(255,0),t.writeInt32LE(e&-1,1),t.writeUInt32LE(Math.floor(e/4294967296),5)),t};dr.varintBufBN=function(e){var t,r=e.toNumber();if(r<253)t=f.Buffer.alloc(1),t.writeUInt8(r,0);else if(r<65536)t=f.Buffer.alloc(3),t.writeUInt8(253,0),t.writeUInt16LE(r,1);else if(r<4294967296)t=f.Buffer.alloc(5),t.writeUInt8(254,0),t.writeUInt32LE(r,1);else{var i=new dr;i.writeUInt8(255),i.writeUInt64LEBN(e),t=i.concat()}return t};Kk.exports=dr});var Cc=T((hse,Wk)=>{"use strict";g();var Vk=Nn(),Gk=lo(),H7=Ke(),Cn=function e(t){if(!(this instanceof e))return new e(t);if(f.Buffer.isBuffer(t))this.buf=t;else if(typeof t=="number"){var r=t;this.fromNumber(r)}else if(t instanceof H7){var i=t;this.fromBN(i)}else if(t){var n=t;this.set(n)}};Cn.prototype.set=function(e){return this.buf=e.buf||this.buf,this};Cn.prototype.fromString=function(e){return this.set({buf:f.Buffer.from(e,"hex")}),this};Cn.prototype.toString=function(){return this.buf.toString("hex")};Cn.prototype.fromBuffer=function(e){return this.buf=e,this};Cn.prototype.fromBufferReader=function(e){return this.buf=e.readVarintBuf(),this};Cn.prototype.fromBN=function(e){return this.buf=Vk().writeVarintBN(e).concat(),this};Cn.prototype.fromNumber=function(e){return this.buf=Vk().writeVarintNum(e).concat(),this};Cn.prototype.toBuffer=function(){return this.buf};Cn.prototype.toBN=function(){return Gk(this.buf).readVarintBN()};Cn.prototype.toNumber=function(){return Gk(this.buf).readVarintNum()};Wk.exports=Cn});var gi=T((pse,Zk)=>{"use strict";g();var Vg=at(),f_=Ke(),Yk=rr(),Gg=ni(),q7=Nn(),U7=Cc(),l_=ut(),h_=Ie(),F7=pi(),j7=9007199254740991;function Jr(e){if(!(this instanceof Jr))return new Jr(e);if(Vg.isObject(e))if(this.satoshis=e.satoshis,f.Buffer.isBuffer(e.script))this._scriptBuffer=e.script;else{var t;Vg.isString(e.script)&&Gg.isHexa(e.script)?t=Yk.Buffer.from(e.script,"hex"):t=e.script,this.setScript(t)}else throw new TypeError("Unrecognized argument for Output")}Object.defineProperty(Jr.prototype,"script",{configurable:!1,enumerable:!0,get:function(){return this._script?this._script:(this.setScriptFromBuffer(this._scriptBuffer),this._script)}});Object.defineProperty(Jr.prototype,"satoshis",{configurable:!1,enumerable:!0,get:function(){return this._satoshis},set:function(e){e instanceof f_?(this._satoshisBN=e,this._satoshis=e.toNumber()):Vg.isString(e)?(this._satoshis=parseInt(e),this._satoshisBN=f_.fromNumber(this._satoshis)):(h_.checkArgument(Gg.isNaturalNumber(e),"Output satoshis is not a natural number"),this._satoshisBN=f_.fromNumber(e),this._satoshis=e),h_.checkState(Gg.isNaturalNumber(this._satoshis),"Output satoshis is not a natural number")}});Jr.prototype.invalidSatoshis=function(){return this._satoshis>j7?"transaction txout satoshis greater than max safe integer":this._satoshis!==this._satoshisBN.toNumber()?"transaction txout satoshis has corrupted value":this._satoshis<0?"transaction txout negative":!1};Object.defineProperty(Jr.prototype,"satoshisBN",{configurable:!1,enumerable:!0,get:function(){return this._satoshisBN},set:function(e){this._satoshisBN=e,this._satoshis=e.toNumber(),h_.checkState(Gg.isNaturalNumber(this._satoshis),"Output satoshis is not a natural number")}});Jr.prototype.toObject=Jr.prototype.toJSON=function(){var t={satoshis:this.satoshis};return t.script=this._scriptBuffer.toString("hex"),t};Jr.fromObject=function(e){return new Jr(e)};Jr.prototype.setScriptFromBuffer=function(e){this._scriptBuffer=e;try{this._script=l_.fromBuffer(this._scriptBuffer),this._script._isOutput=!0}catch(t){if(t instanceof F7.Script.InvalidBuffer)this._script=null;else throw t}};Jr.prototype.setScript=function(e){if(e instanceof l_)this._scriptBuffer=e.toBuffer(),this._script=e,this._script._isOutput=!0;else if(Vg.isString(e))this._script=l_.fromString(e),this._scriptBuffer=this._script.toBuffer(),this._script._isOutput=!0;else if(f.Buffer.isBuffer(e))this.setScriptFromBuffer(e);else throw new TypeError("Invalid argument type: script");return this};Jr.prototype.inspect=function(){var e;return this.script?e=this.script.inspect():e=this._scriptBuffer.toString("hex"),"<Output ("+this.satoshis+" sats) "+e+">"};Jr.fromBufferReader=function(e){var t={};t.satoshis=e.readUInt64LEBN();var r=e.readVarintNum();return r!==0?t.script=e.read(r):t.script=Yk.Buffer.from([]),new Jr(t)};Jr.prototype.toBufferWriter=function(e){e||(e=new q7),e.writeUInt64LEBN(this._satoshisBN);var t=this._scriptBuffer;return e.writeVarintNum(t.length),e.write(t),e};Jr.prototype.getSize=function(){var e=this.script.toBuffer().length,t=U7(e).toBuffer().length;return 8+t+e};Zk.exports=Jr});var Lc=T((mse,Qk)=>{"use strict";g();var rs=at(),z7=Ie(),nh=pi(),K7=Nn(),d_=rr(),Xk=ni(),Wg=ut(),V7=mi(),$k=gi(),Yg=4294967295,G7=Yg-2,Jk=Yg,W7=Yg-1;function Nt(e){if(!(this instanceof Nt))return new Nt(e);if(e)return this._fromObject(e)}Nt.MAXINT=Yg;Nt.DEFAULT_SEQNUMBER=Jk;Nt.DEFAULT_LOCKTIME_SEQNUMBER=W7;Nt.DEFAULT_RBF_SEQNUMBER=G7;Nt.BASE_SIZE=40;Object.defineProperty(Nt.prototype,"script",{configurable:!1,enumerable:!0,get:function(){return this.isNull()?null:(this._script||(this._script=new Wg(this._scriptBuffer),this._script._isInput=!0),this._script)}});Nt.fromObject=function(e){z7.checkArgument(rs.isObject(e));var t=new Nt;return t._fromObject(e)};Nt.prototype._fromObject=function(e){var t;if(rs.isString(e.prevTxId)&&Xk.isHexa(e.prevTxId)?t=d_.Buffer.from(e.prevTxId,"hex"):t=e.prevTxId,this.output=e.output?e.output instanceof $k?e.output:new $k(e.output):void 0,this.prevTxId=t||e.txidbuf,this.outputIndex=rs.isUndefined(e.outputIndex)?e.txoutnum:e.outputIndex,this.sequenceNumber=rs.isUndefined(e.sequenceNumber)?rs.isUndefined(e.seqnum)?Jk:e.seqnum:e.sequenceNumber,rs.isUndefined(e.script)&&rs.isUndefined(e.scriptBuffer))throw new nh.Transaction.Input.MissingScript;return this.setScript(e.scriptBuffer||e.script),this};Nt.prototype.toObject=Nt.prototype.toJSON=function(){var t={prevTxId:this.prevTxId.toString("hex"),outputIndex:this.outputIndex,sequenceNumber:this.sequenceNumber,script:this._scriptBuffer.toString("hex")};return this.script&&(t.scriptString=this.script.toString()),this.output&&(t.output=this.output.toObject()),t};Nt.fromBufferReader=function(e){var t=new Nt;return t.prevTxId=e.readReverse(32),t.outputIndex=e.readUInt32LE(),t._scriptBuffer=e.readVarLengthBuffer(),t.sequenceNumber=e.readUInt32LE(),t};Nt.prototype.toBufferWriter=function(e){e||(e=new K7),e.writeReverse(this.prevTxId),e.writeUInt32LE(this.outputIndex);var t=this._scriptBuffer;return e.writeVarintNum(t.length),e.write(t),e.writeUInt32LE(this.sequenceNumber),e};Nt.prototype.setScript=function(e){if(this._script=null,e instanceof Wg)this._script=e,this._script._isInput=!0,this._scriptBuffer=e.toBuffer();else if(e===null)this._script=Wg.empty(),this._script._isInput=!0,this._scriptBuffer=this._script.toBuffer();else if(Xk.isHexa(e))this._scriptBuffer=d_.Buffer.from(e,"hex");else if(rs.isString(e))this._script=new Wg(e),this._script._isInput=!0,this._scriptBuffer=this._script.toBuffer();else if(f.Buffer.isBuffer(e))this._scriptBuffer=d_.Buffer.from(e);else throw new TypeError("Invalid argument type: script");return this};Nt.prototype.getSignatures=function(){throw new nh.AbstractMethodInvoked("Trying to sign unsupported output type (only P2PKH and P2SH multisig inputs are supported) for input: "+JSON.stringify(this))};Nt.prototype.isFullySigned=function(){throw new nh.AbstractMethodInvoked("Input#isFullySigned")};Nt.prototype.isFinal=function(){return this.sequenceNumber===Nt.MAXINT};Nt.prototype.addSignature=function(){throw new nh.AbstractMethodInvoked("Input#addSignature")};Nt.prototype.clearSignatures=function(){throw new nh.AbstractMethodInvoked("Input#clearSignatures")};Nt.prototype.isValidSignature=function(e,t){return t.signature.nhashtype=t.sigtype,V7.verify(e,t.signature,t.publicKey,t.inputIndex,this.output.script,this.output.satoshisBN)};Nt.prototype.isNull=function(){return this.prevTxId.toString("hex")==="0000000000000000000000000000000000000000000000000000000000000000"&&this.outputIndex===4294967295};Nt.prototype._estimateSize=function(){return this.toBufferWriter().toBuffer().length};Qk.exports=Nt});var Mc=T((yse,eB)=>{"use strict";g();eB.exports=function(t,r){r&&(t.super_=r,t.prototype=Object.create(r.prototype,{constructor:{value:t,enumerable:!1,writable:!0,configurable:!0}}))}});var Hc=T((_se,iB)=>{"use strict";g();var Dc=at(),ln=Ie(),Y7=Mc(),tB=ni(),rB=sr(),Z7=pi(),oh=gt();function Ln(e){if(!(this instanceof Ln))return new Ln(e);if(e instanceof Ln)return e;if(Dc.isObject(e))return this._fromObject(e);throw new Z7.InvalidArgument("TransactionSignatures must be instantiated from an object")}Y7(Ln,oh);Ln.prototype._fromObject=function(e){return this._checkObjectArgs(e),this.publicKey=new rB(e.publicKey),this.prevTxId=f.Buffer.isBuffer(e.prevTxId)?e.prevTxId:f.Buffer.from(e.prevTxId,"hex"),this.outputIndex=e.outputIndex,this.inputIndex=e.inputIndex,this.signature=e.signature instanceof oh?e.signature:f.Buffer.isBuffer(e.signature)?oh.fromBuffer(e.signature):oh.fromString(e.signature),this.sigtype=e.sigtype,this};Ln.prototype._checkObjectArgs=function(e){ln.checkArgument(rB(e.publicKey),"publicKey"),ln.checkArgument(!Dc.isUndefined(e.inputIndex),"inputIndex"),ln.checkArgument(!Dc.isUndefined(e.outputIndex),"outputIndex"),ln.checkState(Dc.isNumber(e.inputIndex),"inputIndex must be a number"),ln.checkState(Dc.isNumber(e.outputIndex),"outputIndex must be a number"),ln.checkArgument(e.signature,"signature"),ln.checkArgument(e.prevTxId,"prevTxId"),ln.checkState(e.signature instanceof oh||f.Buffer.isBuffer(e.signature)||tB.isHexa(e.signature),"signature must be a buffer or hexa value"),ln.checkState(f.Buffer.isBuffer(e.prevTxId)||tB.isHexa(e.prevTxId),"prevTxId must be a buffer or hexa value"),ln.checkArgument(e.sigtype,"sigtype"),ln.checkState(Dc.isNumber(e.sigtype),"sigtype must be a number")};Ln.prototype.toObject=Ln.prototype.toJSON=function(){return{publicKey:this.publicKey.toString(),prevTxId:this.prevTxId.toString("hex"),outputIndex:this.outputIndex,inputIndex:this.inputIndex,signature:this.signature.toString(),sigtype:this.sigtype}};Ln.fromObject=function(e){return ln.checkArgument(e),new Ln(e)};iB.exports=Ln});var uB=T((Sse,sB)=>{"use strict";g();var $7=Mc(),oB=Ie(),p_=Lc(),X7=gi(),J7=mi(),aB=ut(),nB=gt(),Q7=Hc();function ha(){p_.apply(this,arguments)}$7(ha,p_);ha.prototype.getSignatures=function(e,t,r,i){oB.checkState(this.output instanceof X7),i=i||nB.SIGHASH_ALL|nB.SIGHASH_FORKID;var n=t.toPublicKey();return n.toString()===this.output.script.getPublicKey().toString("hex")?[new Q7({publicKey:n,prevTxId:this.prevTxId,outputIndex:this.outputIndex,inputIndex:r,signature:J7.sign(e,t,i,r,this.output.script,this.output.satoshisBN),sigtype:i})]:[]};ha.prototype.addSignature=function(e,t){return oB.checkState(this.isValidSignature(e,t),"Signature is invalid"),this.setScript(aB.buildPublicKeyIn(t.signature.toDER(),t.sigtype)),this};ha.prototype.clearSignatures=function(){return this.setScript(aB.empty()),this};ha.prototype.isFullySigned=function(){return this.script.isPublicKeyIn()};ha.SCRIPT_MAX_SIZE=74;ha.prototype._estimateSize=function(){return p_.BASE_SIZE+ha.SCRIPT_MAX_SIZE};sB.exports=ha});var dB=T((xse,hB)=>{"use strict";g();var e9=Mc(),fB=Ie(),t9=Le(),g_=Lc(),r9=gi(),i9=mi(),lB=ut(),cB=gt(),n9=Hc();function da(){g_.apply(this,arguments)}e9(da,g_);da.prototype.getSignatures=function(e,t,r,i,n){fB.checkState(this.output instanceof r9),n=n||t9.sha256ripemd160(t.publicKey.toBuffer()),i=i||cB.SIGHASH_ALL|cB.SIGHASH_FORKID;var o=this.output.script.chunks[2]&&this.output.script.chunks[2].buf;return o&&n.equals(o)?[new n9({publicKey:t.publicKey,prevTxId:this.prevTxId,outputIndex:this.outputIndex,inputIndex:r,signature:i9.sign(e,t,i,r,this.output.script,this.output.satoshisBN),sigtype:i})]:[]};da.prototype.addSignature=function(e,t){return fB.checkState(this.isValidSignature(e,t),"Signature is invalid"),this.setScript(lB.buildPublicKeyHashIn(t.publicKey,t.signature.toDER(),t.sigtype)),this};da.prototype.clearSignatures=function(){return this.setScript(lB.empty()),this};da.prototype.isFullySigned=function(){return this.script.isPublicKeyHashIn()};da.SCRIPT_MAX_SIZE=108;da.prototype._estimateSize=function(){return g_.BASE_SIZE+da.SCRIPT_MAX_SIZE};hB.exports=da});var mB=T((Ise,gB)=>{"use strict";g();var Mn=at(),o9=Mc(),$g=Lc(),a9=gi(),ah=Ie(),pB=ut(),Zg=gt(),m_=mi(),v_=Hc(),s9=sr(),u9=Cc();function Ur(e,t,r,i){$g.apply(this,arguments);var n=this;t=t||e.publicKeys,r=r||e.threshold,i=i||e.signatures,this.publicKeys=t.map(o=>o.toString("hex")).sort().map(o=>new s9(o)),ah.checkState(pB.buildMultisigOut(this.publicKeys,r).equals(this.output.script),"Provided public keys don't match to the provided output script"),this.publicKeyIndex={},Mn.each(this.publicKeys,function(o,a){n.publicKeyIndex[o.toString()]=a}),this.threshold=r,this.signatures=i?this._deserializeSignatures(i):new Array(this.publicKeys.length)}o9(Ur,$g);Ur.prototype.toObject=function(){var e=$g.prototype.toObject.apply(this,arguments);return e.threshold=this.threshold,e.publicKeys=Mn.map(this.publicKeys,function(t){return t.toString()}),e.signatures=this._serializeSignatures(),e};Ur.prototype._deserializeSignatures=function(e){return Mn.map(e,function(t){if(t)return new v_(t)})};Ur.prototype._serializeSignatures=function(){return Mn.map(this.signatures,function(e){if(e)return e.toObject()})};Ur.prototype.getSignatures=function(e,t,r,i){ah.checkState(this.output instanceof a9),i=i||Zg.SIGHASH_ALL|Zg.SIGHASH_FORKID;var n=this,o=[];return Mn.each(this.publicKeys,function(a){a.toString()===t.publicKey.toString()&&o.push(new v_({publicKey:t.publicKey,prevTxId:n.prevTxId,outputIndex:n.outputIndex,inputIndex:r,signature:m_.sign(e,t,i,r,n.output.script,n.output.satoshisBN),sigtype:i}))}),o};Ur.prototype.addSignature=function(e,t){return ah.checkState(!this.isFullySigned(),"All needed signatures have already been added"),ah.checkArgument(!Mn.isUndefined(this.publicKeyIndex[t.publicKey.toString()]),"Signature has no matching public key"),ah.checkState(this.isValidSignature(e,t)),this.signatures[this.publicKeyIndex[t.publicKey.toString()]]=t,this._updateScript(),this};Ur.prototype._updateScript=function(){return this.setScript(pB.buildMultisigIn(this.publicKeys,this.threshold,this._createSignatures())),this};Ur.prototype._createSignatures=function(){return Mn.map(Mn.filter(this.signatures,function(e){return!Mn.isUndefined(e)}),function(e){return f.Buffer.concat([e.signature.toDER(),f.Buffer.from([e.sigtype&255])])})};Ur.prototype.clearSignatures=function(){this.signatures=new Array(this.publicKeys.length),this._updateScript()};Ur.prototype.isFullySigned=function(){return this.countSignatures()===this.threshold};Ur.prototype.countMissingSignatures=function(){return this.threshold-this.countSignatures()};Ur.prototype.countSignatures=function(){return Mn.reduce(this.signatures,function(e,t){return e+!!t},0)};Ur.prototype.publicKeysWithoutSignature=function(){var e=this;return Mn.filter(this.publicKeys,function(t){return!e.signatures[e.publicKeyIndex[t.toString()]]})};Ur.prototype.isValidSignature=function(e,t){return t.signature.nhashtype=t.sigtype,m_.verify(e,t.signature,t.publicKey,t.inputIndex,this.output.script,this.output.satoshisBN)};Ur.normalizeSignatures=function(e,t,r,i,n){return n.map(function(o){var a=null;return i=i.filter(function(s){if(a)return!0;var u=new v_({signature:Zg.fromTxFormat(s),publicKey:o,prevTxId:t.prevTxId,outputIndex:t.outputIndex,inputIndex:r,sigtype:Zg.SIGHASH_ALL});u.signature.nhashtype=u.sigtype;var c=m_.verify(e,u.signature,u.publicKey,u.inputIndex,t.output.script);return c?(a=u,!1):!0}),a||null})};Ur.SIGNATURE_SIZE=73;Ur.prototype._estimateSize=function(){var e=1+this.threshold*Ur.SIGNATURE_SIZE;return $g.BASE_SIZE+u9(e).toBuffer().length+e};gB.exports=Ur});var wB=T((Tse,_B)=>{"use strict";g();var Dn=at(),c9=Mc(),Xg=Lc(),f9=gi(),sh=Ie(),y_=ut(),vB=gt(),yB=mi(),bB=Hc(),l9=sr(),h9=Cc();function Rr(e,t,r,i){Xg.apply(this,arguments);var n=this;t=t||e.publicKeys,r=r||e.threshold,i=i||e.signatures,this.publicKeys=t.map(o=>o.toString("hex")).sort().map(o=>new l9(o)),this.redeemScript=y_.buildMultisigOut(this.publicKeys,r),sh.checkState(y_.buildScriptHashOut(this.redeemScript).equals(this.output.script),"Provided public keys don't hash to the provided output"),this.publicKeyIndex={},Dn.each(this.publicKeys,function(o,a){n.publicKeyIndex[o.toString()]=a}),this.threshold=r,this.signatures=i?this._deserializeSignatures(i):new Array(this.publicKeys.length)}c9(Rr,Xg);Rr.prototype.toObject=function(){var e=Xg.prototype.toObject.apply(this,arguments);return e.threshold=this.threshold,e.publicKeys=Dn.map(this.publicKeys,function(t){return t.toString()}),e.signatures=this._serializeSignatures(),e};Rr.prototype._deserializeSignatures=function(e){return Dn.map(e,function(t){if(t)return new bB(t)})};Rr.prototype._serializeSignatures=function(){return Dn.map(this.signatures,function(e){if(e)return e.toObject()})};Rr.prototype.getSignatures=function(e,t,r,i){sh.checkState(this.output instanceof f9),i=i||vB.SIGHASH_ALL|vB.SIGHASH_FORKID;var n=this,o=[];return Dn.each(this.publicKeys,function(a){a.toString()===t.publicKey.toString()&&o.push(new bB({publicKey:t.publicKey,prevTxId:n.prevTxId,outputIndex:n.outputIndex,inputIndex:r,signature:yB.sign(e,t,i,r,n.redeemScript,n.output.satoshisBN),sigtype:i}))}),o};Rr.prototype.addSignature=function(e,t){return sh.checkState(!this.isFullySigned(),"All needed signatures have already been added"),sh.checkArgument(!Dn.isUndefined(this.publicKeyIndex[t.publicKey.toString()]),"Signature has no matching public key"),sh.checkState(this.isValidSignature(e,t)),this.signatures[this.publicKeyIndex[t.publicKey.toString()]]=t,this._updateScript(),this};Rr.prototype._updateScript=function(){return this.setScript(y_.buildP2SHMultisigIn(this.publicKeys,this.threshold,this._createSignatures(),{cachedMultisig:this.redeemScript})),this};Rr.prototype._createSignatures=function(){return Dn.map(Dn.filter(this.signatures,function(e){return!Dn.isUndefined(e)}),function(e){return f.Buffer.concat([e.signature.toDER(),f.Buffer.from([e.sigtype&255])])})};Rr.prototype.clearSignatures=function(){this.signatures=new Array(this.publicKeys.length),this._updateScript()};Rr.prototype.isFullySigned=function(){return this.countSignatures()===this.threshold};Rr.prototype.countMissingSignatures=function(){return this.threshold-this.countSignatures()};Rr.prototype.countSignatures=function(){return Dn.reduce(this.signatures,function(e,t){return e+!!t},0)};Rr.prototype.publicKeysWithoutSignature=function(){var e=this;return Dn.filter(this.publicKeys,function(t){return!e.signatures[e.publicKeyIndex[t.toString()]]})};Rr.prototype.isValidSignature=function(e,t){return t.signature.nhashtype=t.sigtype,yB.verify(e,t.signature,t.publicKey,t.inputIndex,this.redeemScript,this.output.satoshisBN)};Rr.SIGNATURE_SIZE=73;Rr.PUBKEY_SIZE=34;Rr.prototype._estimateSize=function(){var e=this.publicKeys.length*Rr.PUBKEY_SIZE,t=this.threshold*Rr.SIGNATURE_SIZE,r=3+e,i=r<=75?1:r<=255?2:3,n=t+1+i+r;return Xg.BASE_SIZE+h9(n).toBuffer().length+n};_B.exports=Rr});var ho=T((Rse,qc)=>{g();qc.exports=Lc();qc.exports.PublicKey=uB();qc.exports.PublicKeyHash=dB();qc.exports.MultiSig=mB();qc.exports.MultiSigScriptHash=wB()});var mi=T((Bse,IB)=>{"use strict";g();var d9=rr(),Ci=gt(),uh=ut(),p9=gi(),g9=lo(),ch=Nn(),SB=Ke(),Jg=Le(),EB=dn(),b_=Ie(),__=hn(),is=at(),xB=f.Buffer.from("0000000000000000000000000000000000000000000000000000000000000001","hex"),m9="ffffffffffffffff",v9=__.SCRIPT_ENABLE_SIGHASH_FORKID,y9=function(e,t,r,i,n){var o=e.inputs[r];b_.checkArgument(n instanceof SB,"For ForkId=0 signatures, satoshis or complete input must be provided");function a(k){var q=new ch;is.each(k.inputs,function(B){q.writeReverse(B.prevTxId),q.writeUInt32LE(B.outputIndex)});var z=q.toBuffer(),A=Jg.sha256sha256(z);return A}function s(k){var q=new ch;is.each(k.inputs,function(B){q.writeUInt32LE(B.sequenceNumber)});var z=q.toBuffer(),A=Jg.sha256sha256(z);return A}function u(k,q){var z=new ch;is.isUndefined(q)?is.each(k.outputs,function(M){M.toBufferWriter(z)}):k.outputs[q].toBufferWriter(z);var A=z.toBuffer(),B=Jg.sha256sha256(A);return B}var c=f.Buffer.alloc(32),l=f.Buffer.alloc(32),p=f.Buffer.alloc(32),d=e&&e._sighashMidstates;t&Ci.SIGHASH_ANYONECANPAY||(d?(d.prevouts||(d.prevouts=a(e)),c=d.prevouts):c=a(e)),!(t&Ci.SIGHASH_ANYONECANPAY)&&(t&31)!==Ci.SIGHASH_SINGLE&&(t&31)!==Ci.SIGHASH_NONE&&(d?(d.sequence||(d.sequence=s(e)),l=d.sequence):l=s(e)),(t&31)!==Ci.SIGHASH_SINGLE&&(t&31)!==Ci.SIGHASH_NONE?d?(d.outputsAll||(d.outputsAll=u(e)),p=d.outputsAll):p=u(e):(t&31)===Ci.SIGHASH_SINGLE&&r<e.outputs.length&&(p=u(e,r));var v=new ch;v.writeInt32LE(e.version),v.write(c),v.write(l),v.writeReverse(o.prevTxId),v.writeUInt32LE(o.outputIndex);var _=i.toBuffer();v.writeVarintNum(_.length),v.write(_),v.writeUInt64LEBN(n);var I=o.sequenceNumber;v.writeUInt32LE(I),v.write(p),v.writeUInt32LE(e.nLockTime),v.writeUInt32LE(t>>>0);var R=v.toBuffer();return R},OB=function(t,r,i,n,o,a){var s=S_(),u=ho();is.isUndefined(a)&&(a=v9);var c=s.shallowCopy(t);if(n instanceof uh||(n=new uh(n)),a&__.SCRIPT_ENABLE_REPLAY_PROTECTION){var l=r>>8,p=16711680|l^57005;r=p<<8|r&255}if(r&Ci.SIGHASH_FORKID&&!(r&Ci.SIGHASH_CHRONICLE)&&a&__.SCRIPT_ENABLE_SIGHASH_FORKID)return y9(c,r,i,n,o);n=new uh(n),n.removeCodeseparators();var d;for(d=0;d<c.inputs.length;d++)c.inputs[d]=new u(c.inputs[d]).setScript(uh.empty());if(c.inputs[i]=new u(c.inputs[i]).setScript(n),(r&31)===Ci.SIGHASH_NONE||(r&31)===Ci.SIGHASH_SINGLE)for(d=0;d<c.inputs.length;d++)d!==i&&(c.inputs[d].sequenceNumber=0);if((r&31)===Ci.SIGHASH_NONE)c.outputs=[];else if((r&31)===Ci.SIGHASH_SINGLE){if(i>=c.outputs.length)return xB;for(c.outputs.length=i+1,d=0;d<i;d++)c.outputs[d]=new p9({satoshis:SB.fromBuffer(d9.Buffer.from(m9,"hex")),script:uh.empty()})}r&Ci.SIGHASH_ANYONECANPAY&&(c.inputs=[c.inputs[i]]);var v=new ch().write(c.toBuffer()).writeInt32LE(r).toBuffer();return v},w_=function(t,r,i,n,o,a){var s=OB(t,r,i,n,o,a);if(s.compare(xB)===0)return s;var u=Jg.sha256sha256(s);return u=new g9(u).readReverse(),u};function b9(e,t,r,i,n,o,a){var s=w_(e,r,i,n,o,a),u=EB.sign(s,t,"little").set({nhashtype:r});return u}function _9(e,t,r,i,n,o,a){b_.checkArgument(!is.isUndefined(e)),b_.checkArgument(!is.isUndefined(t)&&!is.isUndefined(t.nhashtype));var s=w_(e,t.nhashtype,i,n,o,a);return EB.verify(s,t,r,"little")}IB.exports={sighashPreimage:OB,sighash:w_,sign:b9,verify:_9}});var E_=T((Cse,TB)=>{"use strict";g();var pa=at(),Qg=Ie(),AB=ni(),w9=ut(),S9=Ni();function ga(e){if(!(this instanceof ga))return new ga(e);Qg.checkArgument(pa.isObject(e),"Must provide an object from where to extract data");var t=e.address?new S9(e.address):void 0,r=e.txid?e.txid:e.txId;if(!r||!AB.isHexaString(r)||r.length>64)throw new Error("Invalid TXID in object",e);var i=pa.isUndefined(e.vout)?e.outputIndex:e.vout;if(!pa.isNumber(i))throw new Error("Invalid outputIndex, received "+i);Qg.checkArgument(!pa.isUndefined(e.scriptPubKey)||!pa.isUndefined(e.script),"Must provide the scriptPubKey for that output!");var n=new w9(e.scriptPubKey||e.script);Qg.checkArgument(!pa.isUndefined(e.amount)||!pa.isUndefined(e.satoshis),"Must provide an amount for the output");var o=pa.isUndefined(e.amount)?e.satoshis:Math.round(e.amount*1e8);Qg.checkArgument(pa.isNumber(o),"Amount must be a number"),AB.defineImmutable(this,{address:t,txId:r,outputIndex:i,script:n,satoshis:o})}ga.prototype.inspect=function(){return"<UnspentOutput: "+this.txId+":"+this.outputIndex+", satoshis: "+this.satoshis+", address: "+this.address+">"};ga.prototype.toString=function(){return this.txId+":"+this.outputIndex};ga.fromObject=function(e){return new ga(e)};ga.prototype.toObject=ga.prototype.toJSON=function(){return{address:this.address?this.address.toString():void 0,txid:this.txId,vout:this.outputIndex,scriptPubKey:this.script.toBuffer().toString("hex"),amount:Number.parseFloat((this.satoshis/1e8).toFixed(8))}};TB.exports=ga});var S_=T((Mse,MB)=>{"use strict";g();var Ae=at(),Qr=Ie(),E9=rr(),jr=pi(),RB=ni(),kB=lo(),x9=Nn(),PB=Cc(),BB=Le(),tm=gt(),NB=mi(),O9=Ni(),CB=E_(),Fr=ho(),I9=Fr.PublicKeyHash,A9=Fr.PublicKey,T9=Fr.MultiSigScriptHash,P9=Fr.MultiSig,Hn=gi(),po=ut(),R9=ei(),em=Ke(),k9=hn(),B9=k9.SCRIPT_ENABLE_SIGHASH_FORKID;function ue(e){if(!(this instanceof ue))return new ue(e);if(this.inputs=[],this.outputs=[],this._inputAmount=void 0,this._outputAmount=void 0,e){if(e instanceof ue)return ue.shallowCopy(e);if(RB.isHexa(e))this.fromString(e);else if(f.Buffer.isBuffer(e))this.fromBuffer(e);else if(Ae.isObject(e))this.fromObject(e);else throw new jr.InvalidArgument("Must provide an object or string to deserialize a transaction")}else this._newTransaction()}var N9=1,C9=0,L9=1e6;ue.DUST_AMOUNT=546;ue.FEE_SECURITY_MARGIN=150;ue.MAX_MONEY=21e6*1e8;ue.NLOCKTIME_BLOCKHEIGHT_LIMIT=5e8;ue.NLOCKTIME_MAX_VALUE=4294967295;ue.FEE_PER_KB=500;ue.CHANGE_OUTPUT_MAX_SIZE=62;ue.shallowCopy=function(e){var t=new ue(e.toBuffer());return t};var LB={configurable:!1,enumerable:!0,get:function(){return this._hash=new kB(this._getHash()).readReverse().toString("hex"),this._hash}};Object.defineProperty(ue.prototype,"hash",LB);Object.defineProperty(ue.prototype,"id",LB);var x_={configurable:!1,enumerable:!0,get:function(){return this._getInputAmount()}};Object.defineProperty(ue.prototype,"inputAmount",x_);x_.get=function(){return this._getOutputAmount()};Object.defineProperty(ue.prototype,"outputAmount",x_);ue.prototype._getHash=function(){return BB.sha256sha256(this.toBuffer())};ue.prototype.serialize=function(e){return e===!0||e&&e.disableAll?this.uncheckedSerialize():this.checkedSerialize(e)};ue.prototype.uncheckedSerialize=ue.prototype.toString=function(){return this.toBuffer().toString("hex")};ue.prototype.checkedSerialize=function(e){var t=this.getSerializationError(e);if(t)throw t.message+=" - For more information please see: https://bsv.io/api/lib/transaction#serialization-checks",t;return this.uncheckedSerialize()};ue.prototype.invalidSatoshis=function(){for(var e=!1,t=0;t<this.outputs.length;t++)this.outputs[t].invalidSatoshis()&&(e=!0);return e};ue.prototype.getSerializationError=function(e){if(e=e||{},this.invalidSatoshis())return new jr.Transaction.InvalidSatoshis;var t=this._getUnspentValue(),r;return t<0?e.disableMoreOutputThanInput||(r=new jr.Transaction.InvalidOutputAmountSum):r=this._hasFeeError(e,t),r||this._hasDustOutputs(e)||this._isMissingSignatures(e)};ue.prototype._hasFeeError=function(e,t){if(!Ae.isUndefined(this._fee)&&this._fee!==t)return new jr.Transaction.FeeError.Different("Unspent value is "+t+" but specified fee is "+this._fee);if(!e.disableLargeFees){var r=Math.floor(ue.FEE_SECURITY_MARGIN*this._estimateFee());if(t>r)return this._missingChange()?new jr.Transaction.ChangeAddressMissing("Fee is too large and no change address was provided"):new jr.Transaction.FeeError.TooLarge("expected less than "+r+" but got "+t)}};ue.prototype._missingChange=function(){return!this._changeScript};ue.prototype._hasDustOutputs=function(e){if(!e.disableDustOutputs){var t,r;for(t in this.outputs)if(r=this.outputs[t],r.satoshis<ue.DUST_AMOUNT&&!r.script.isDataOut()&&!r.script.isSafeDataOut())return new jr.Transaction.DustOutputs}};ue.prototype._isMissingSignatures=function(e){if(!e.disableIsFullySigned&&!this.isFullySigned())return new jr.Transaction.MissingSignatures};ue.prototype.inspect=function(){return"<Transaction: "+this.uncheckedSerialize()+">"};ue.prototype.toBuffer=function(){var e=new x9;return this.toBufferWriter(e).toBuffer()};ue.prototype.toBufferWriter=function(e){return e.writeInt32LE(this.version),e.writeVarintNum(this.inputs.length),Ae.each(this.inputs,function(t){t.toBufferWriter(e)}),e.writeVarintNum(this.outputs.length),Ae.each(this.outputs,function(t){t.toBufferWriter(e)}),e.writeUInt32LE(this.nLockTime),e};ue.prototype.fromBuffer=function(e){var t=new kB(e);return this.fromBufferReader(t)};ue.prototype.fromBufferReader=function(e){Qr.checkArgument(!e.finished(),"No transaction data received");var t,r,i;for(this.version=e.readInt32LE(),r=e.readVarintNum(),t=0;t<r;t++){var n=Fr.fromBufferReader(e);this.inputs.push(n)}for(i=e.readVarintNum(),t=0;t<i;t++)this.outputs.push(Hn.fromBufferReader(e));return this.nLockTime=e.readUInt32LE(),this};ue.prototype.toObject=ue.prototype.toJSON=function(){var t=[];this.inputs.forEach(function(n){t.push(n.toObject())});var r=[];this.outputs.forEach(function(n){r.push(n.toObject())});var i={hash:this.hash,version:this.version,inputs:t,outputs:r,nLockTime:this.nLockTime};return this._changeScript&&(i.changeScript=this._changeScript.toString()),Ae.isUndefined(this._changeIndex)||(i.changeIndex=this._changeIndex),Ae.isUndefined(this._fee)||(i.fee=this._fee),i};ue.prototype.fromObject=function(t){Qr.checkArgument(Ae.isObject(t)||t instanceof ue);var r=this,i;return t instanceof ue?i=t.toObject():i=t,Ae.each(i.inputs,function(n){if(!n.output||!n.output.script){r.uncheckedAddInput(new Fr(n));return}var o=new po(n.output.script),a;if(o.isPublicKeyHashOut())a=new Fr.PublicKeyHash(n);else if(o.isScriptHashOut()&&n.publicKeys&&n.threshold)a=new Fr.MultiSigScriptHash(n,n.publicKeys,n.threshold,n.signatures);else if(o.isPublicKeyOut())a=new Fr.PublicKey(n);else throw new jr.Transaction.Input.UnsupportedScript(n.output.script);r.addInput(a)}),Ae.each(i.outputs,function(n){r.addOutput(new Hn(n))}),i.changeIndex&&(this._changeIndex=i.changeIndex),i.changeScript&&(this._changeScript=new po(i.changeScript)),i.fee&&(this._fee=i.fee),this.nLockTime=i.nLockTime,this.version=i.version,this._checkConsistency(t),this};ue.prototype._checkConsistency=function(e){Ae.isUndefined(this._changeIndex)||(Qr.checkState(this._changeScript,"Change script is expected."),Qr.checkState(this.outputs[this._changeIndex],"Change index points to undefined output."),Qr.checkState(this.outputs[this._changeIndex].script.toString()===this._changeScript.toString(),"Change output has an unexpected script.")),e&&e.hash&&Qr.checkState(e.hash===this.hash,"Hash in object does not match transaction hash.")};ue.prototype.lockUntilDate=function(e){if(Qr.checkArgument(e),Ae.isNumber(e)&&e<ue.NLOCKTIME_BLOCKHEIGHT_LIMIT)throw new jr.Transaction.LockTimeTooEarly;Ae.isDate(e)&&(e=e.getTime()/1e3);for(var t=0;t<this.inputs.length;t++)this.inputs[t].sequenceNumber===Fr.DEFAULT_SEQNUMBER&&(this.inputs[t].sequenceNumber=Fr.DEFAULT_LOCKTIME_SEQNUMBER);return this.nLockTime=e,this};ue.prototype.lockUntilBlockHeight=function(e){if(Qr.checkArgument(Ae.isNumber(e)),e>=ue.NLOCKTIME_BLOCKHEIGHT_LIMIT)throw new jr.Transaction.BlockHeightTooHigh;if(e<0)throw new jr.Transaction.NLockTimeOutOfRange;for(var t=0;t<this.inputs.length;t++)this.inputs[t].sequenceNumber===Fr.DEFAULT_SEQNUMBER&&(this.inputs[t].sequenceNumber=Fr.DEFAULT_LOCKTIME_SEQNUMBER);return this.nLockTime=e,this};ue.prototype.getLockTime=function(){return this.nLockTime?this.nLockTime<ue.NLOCKTIME_BLOCKHEIGHT_LIMIT?this.nLockTime:new Date(1e3*this.nLockTime):null};ue.prototype.fromString=function(e){this.fromBuffer(E9.Buffer.from(e,"hex"))};ue.prototype._newTransaction=function(){this.version=N9,this.nLockTime=C9};ue.prototype.from=function(e,t,r){if(Ae.isArray(e)){var i=this;return Ae.each(e,function(o){i.from(o,t,r)}),this}var n=Ae.some(this.inputs,function(o){return o.prevTxId.toString("hex")===e.txId&&o.outputIndex===e.outputIndex});return n?this:(t&&r?this._fromMultisigUtxo(e,t,r):this._fromNonP2SH(e),this)};ue.prototype._fromNonP2SH=function(e){var t;e=new CB(e),e.script.isPublicKeyHashOutPrefix()?t=I9:e.script.isPublicKeyOut()?t=A9:t=Fr,this.addInput(new t({output:new Hn({script:e.script,satoshis:e.satoshis}),prevTxId:e.txId,outputIndex:e.outputIndex,script:po.empty()}))};ue.prototype._fromMultisigUtxo=function(e,t,r){Qr.checkArgument(r<=t.length,"Number of required signatures must be greater than the number of public keys");var i;if(e=new CB(e),e.script.isMultisigOut())i=P9;else if(e.script.isScriptHashOut())i=T9;else throw new jr.Transaction.Input.UnsupportedScript(e.script.toString());this.addInput(new i({output:new Hn({script:e.script,satoshis:e.satoshis}),prevTxId:e.txId,outputIndex:e.outputIndex,script:po.empty()},t,r))};ue.prototype.addInput=function(e,t,r){if(Qr.checkArgumentType(e,Fr,"input"),!e.output&&(Ae.isUndefined(t)||Ae.isUndefined(r)))throw new jr.Transaction.NeedMoreInfo("Need information about the UTXO script and satoshis");return!e.output&&t&&!Ae.isUndefined(r)&&(t=t instanceof po?t:new po(t),Qr.checkArgumentType(r,"number","satoshis"),e.output=new Hn({script:t,satoshis:r})),this.uncheckedAddInput(e)};ue.prototype.uncheckedAddInput=function(e){return Qr.checkArgumentType(e,Fr,"input"),this.inputs.push(e),this._inputAmount=void 0,this._updateChangeOutput(),this};ue.prototype.hasAllUtxoInfo=function(){return Ae.every(this.inputs.map(function(e){return!!e.output}))};ue.prototype.fee=function(e){return Qr.checkArgument(Ae.isNumber(e),"amount must be a number"),this._fee=e,this._updateChangeOutput(),this};ue.prototype.feePerKb=function(e){return Qr.checkArgument(Ae.isNumber(e),"amount must be a number"),this._feePerKb=e,this._updateChangeOutput(),this};ue.prototype.change=function(e){return Qr.checkArgument(e,"address is required"),this._changeScript=po.fromAddress(e),this._updateChangeOutput(),this};ue.prototype.getChangeOutput=function(){return Ae.isUndefined(this._changeIndex)?null:this.outputs[this._changeIndex]};ue.prototype.to=function(e,t){if(Ae.isArray(e)){var r=this;return Ae.each(e,function(i){r.to(i.address,i.satoshis)}),this}return Qr.checkArgument(RB.isNaturalNumber(t),"Amount is expected to be a positive integer"),this.addOutput(new Hn({script:po(new O9(e)),satoshis:t})),this};ue.prototype.addData=function(e){return this.addOutput(new Hn({script:po.buildDataOut(e),satoshis:0})),this};ue.prototype.addSafeData=function(e){return this.addOutput(new Hn({script:po.buildSafeDataOut(e),satoshis:0})),this};ue.prototype.addOutput=function(e){return Qr.checkArgumentType(e,Hn,"output"),this._addOutput(e),this._updateChangeOutput(),this};ue.prototype.clearOutputs=function(){return this.outputs=[],this._clearSignatures(),this._outputAmount=void 0,this._changeIndex=void 0,this._updateChangeOutput(),this};ue.prototype._addOutput=function(e){this.outputs.push(e),this._outputAmount=void 0};ue.prototype._getOutputAmount=function(){if(Ae.isUndefined(this._outputAmount)){var e=this;this._outputAmount=0,Ae.each(this.outputs,function(t){e._outputAmount+=t.satoshis})}return this._outputAmount};ue.prototype._getInputAmount=function(){if(Ae.isUndefined(this._inputAmount)){var e=this;this._inputAmount=0,Ae.each(this.inputs,function(t){if(Ae.isUndefined(t.output))throw new jr.Transaction.Input.MissingPreviousOutput;e._inputAmount+=t.output.satoshis})}return this._inputAmount};ue.prototype._updateChangeOutput=function(){if(this._changeScript){this._clearSignatures(),Ae.isUndefined(this._changeIndex)||this._removeOutput(this._changeIndex),this._changeIndex=this.outputs.length,this._addOutput(new Hn({script:this._changeScript,satoshis:0}));var e=this._getUnspentValue(),t=this.getFee(),r=e-t;this._removeOutput(this._changeIndex),this._changeIndex=void 0,r>=ue.DUST_AMOUNT&&(this._changeIndex=this.outputs.length,this._addOutput(new Hn({script:this._changeScript,satoshis:r})))}};ue.prototype.getFee=function(){return this.isCoinbase()?0:Ae.isUndefined(this._fee)?this._changeScript?this._estimateFee():this._getUnspentValue():this._fee};ue.prototype._estimateFee=function(){var e=this._estimateSize();return Math.ceil(e/1e3*(this._feePerKb||ue.FEE_PER_KB))};ue.prototype._getUnspentValue=function(){return this._getInputAmount()-this._getOutputAmount()};ue.prototype._clearSignatures=function(){Ae.each(this.inputs,function(e){e.clearSignatures!==Fr.prototype.clearSignatures&&e.clearSignatures()})};ue.prototype._estimateSize=function(){var e=8;return e+=PB(this.inputs.length).toBuffer().length,e+=PB(this.outputs.length).toBuffer().length,Ae.each(this.inputs,function(t){e+=t._estimateSize()}),Ae.each(this.outputs,function(t){e+=t.getSize()}),e};ue.prototype._removeOutput=function(e){var t=this.outputs[e];this.outputs=Ae.without(this.outputs,t),this._outputAmount=void 0};ue.prototype.removeOutput=function(e){this._removeOutput(e),this._updateChangeOutput()};ue.prototype.sort=function(){return this.sortInputs(function(e){var t=Array.prototype.concat.apply([],e);return t.sort(function(r,i){return r.prevTxId.compare(i.prevTxId)||r.outputIndex-i.outputIndex}),t}),this.sortOutputs(function(e){var t=Array.prototype.concat.apply([],e);return t.sort(function(r,i){return r.satoshis-i.satoshis||r.script.toBuffer().compare(i.script.toBuffer())}),t}),this};ue.prototype.shuffleOutputs=function(){return this.sortOutputs(Ae.shuffle)};ue.prototype.sortOutputs=function(e){var t=e(this.outputs);return this._newOutputOrder(t)};ue.prototype.sortInputs=function(e){return this.inputs=e(this.inputs),this._clearSignatures(),this};ue.prototype._newOutputOrder=function(e){var t=this.outputs.length!==e.length||Ae.difference(this.outputs,e).length!==0;if(t)throw new jr.Transaction.InvalidSorting;if(!Ae.isUndefined(this._changeIndex)){var r=this.outputs[this._changeIndex];this._changeIndex=e.indexOf(r)}return this.outputs=e,this};ue.prototype.removeInput=function(e,t){var r;if(!t&&Ae.isNumber(e)?r=e:r=Ae.findIndex(this.inputs,function(n){return n.prevTxId.toString("hex")===e&&n.outputIndex===t}),r<0||r>=this.inputs.length)throw new jr.Transaction.InvalidIndex(r,this.inputs.length);var i=this.inputs[r];this.inputs=Ae.without(this.inputs,i),this._inputAmount=void 0,this._updateChangeOutput()};ue.prototype.sign=function(e,t){Qr.checkState(this.hasAllUtxoInfo(),"Not all utxo information is available to sign the transaction.");var r=this;if(Ae.isArray(e))return Ae.each(e,function(n){r.sign(n,t)}),this;var i=!this._sighashMidstates;i&&(this._sighashMidstates={});try{Ae.each(this.getSignatures(e,t),function(n){r.applySignature(n)})}finally{i&&delete this._sighashMidstates}return this};ue.prototype.getSignatures=function(e,t){e=new R9(e),t=t||tm.SIGHASH_ALL|tm.SIGHASH_FORKID;var r=this,i=[],n=BB.sha256ripemd160(e.publicKey.toBuffer()),o=!this._sighashMidstates;o&&(this._sighashMidstates={});try{Ae.each(this.inputs,function(s,u){Ae.each(s.getSignatures(r,e,u,t,n),function(c){i.push(c)})})}finally{o&&delete this._sighashMidstates}return i};ue.prototype.applySignature=function(e){return this.inputs[e.inputIndex].addSignature(this,e),this};ue.prototype.isFullySigned=function(){return Ae.each(this.inputs,function(e){if(e.isFullySigned===Fr.prototype.isFullySigned)throw new jr.Transaction.UnableToVerifySignature("Unrecognized script kind, or not enough information to execute script.This usually happens when creating a transaction from a serialized transaction")}),Ae.every(Ae.map(this.inputs,function(e){return e.isFullySigned()}))};ue.prototype.isValidSignature=function(e){var t=this;if(this.inputs[e.inputIndex].isValidSignature===Fr.prototype.isValidSignature)throw new jr.Transaction.UnableToVerifySignature("Unrecognized script kind, or not enough information to execute script.This usually happens when creating a transaction from a serialized transaction");return this.inputs[e.inputIndex].isValidSignature(t,e)};ue.prototype.verifySignature=function(e,t,r,i,n,o){return NB.verify(this,e,t,r,i,n,o)};ue.prototype.verify=function(){if(this.inputs.length===0)return"transaction txins empty";if(this.outputs.length===0)return"transaction txouts empty";for(var e=new em(0),t=0;t<this.outputs.length;t++){var r=this.outputs[t];if(r.invalidSatoshis())return"transaction txout "+t+" satoshis is invalid";if(r._satoshisBN.gt(new em(ue.MAX_MONEY,10)))return"transaction txout "+t+" greater than MAX_MONEY";if(e=e.add(r._satoshisBN),e.gt(new em(ue.MAX_MONEY)))return"transaction txout "+t+" total output greater than MAX_MONEY"}if(this.toBuffer().length>L9)return"transaction over the maximum block size";var i={};for(t=0;t<this.inputs.length;t++){var n=this.inputs[t],o=n.prevTxId+":"+n.outputIndex;if(!Ae.isUndefined(i[o]))return"transaction input "+t+" duplicate input";i[o]=!0}var a=this.isCoinbase();if(a){var s=this.inputs[0]._scriptBuffer;if(s.length<2||s.length>100)return"coinbase transaction script size invalid"}else for(t=0;t<this.inputs.length;t++)if(this.inputs[t].isNull())return"transaction input "+t+" has null input";return!0};ue.prototype.isCoinbase=function(){return this.inputs.length===1&&this.inputs[0].isNull()};ue.prototype.sighash=function(e,t,r,i,n){t=t||tm.SIGHASH_ALL|tm.SIGHASH_FORKID;var o=this.inputs[e];if(!o)throw new Error("Input index "+e+" does not exist");return!r&&o.output&&(r=o.output.script),!i&&o.output&&(i=new em(o.output.satoshis)),n=n||B9,NB.sighash(this,t,e,r,i,n)};MB.exports=ue});var zt=T((Hse,su)=>{g();su.exports=S_();su.exports.Input=ho();su.exports.Output=gi();su.exports.UnspentOutput=E_();su.exports.Signature=Hc();su.exports.Sighash=mi()});var hn=T((Use,FB)=>{"use strict";g();var rm=at(),im=Kg(),j=Pr(),we=Ke(),fh=Le(),ma=gt(),O_=sr();function DB(e){return e.map(function(t){return f.Buffer.isBuffer(t)?f.Buffer.from(t):t})}var L=function e(t){if(!(this instanceof e))return new e(t);t?(this.initialize(),this.set(t)):this.initialize()};L.prototype._verifyCore=function(e,t,r,i,n,o){var a=zt();if(rm.isUndefined(r)&&(r=new a),rm.isUndefined(i)&&(i=0),rm.isUndefined(n)&&(n=L.currentConsensusFlags(),o||(n&=~L.SCRIPT_ENABLE_SIGHASH_FORKID)),n&L.SCRIPT_ENABLE_SIGHASH_FORKID&&(n|=L.SCRIPT_VERIFY_STRICTENC,!o))throw new Error("internal error - need satoshisBN to verify FORKID transactions");this.set({script:e,tx:r,nin:i,flags:n,satoshisBN:o});var s;if((n&L.SCRIPT_UTXO_AFTER_CHRONICLE)!==0&&(n&L.SCRIPT_UTXO_AFTER_GENESIS)===0)return this.errstr="SCRIPT_ERR_INVALID_FLAGS",!1;if((n&L.SCRIPT_VERIFY_SIGPUSHONLY)!==0){var u=(n&L.SCRIPT_CHRONICLE)!==0,c=(n&L.SCRIPT_GENESIS)!==0&&!u||u&&UB(n,r);if(c&&!e.isPushOnly())return this.errstr="SCRIPT_ERR_SIG_PUSHONLY",!1}if(!this.evaluate())return!1;var l=(n&L.SCRIPT_VERIFY_P2SH)!==0&&(n&L.SCRIPT_UTXO_AFTER_GENESIS)===0;l&&(s=this.stack.slice());var p=this.stack;if(this.initialize(),this.set({script:t,stack:p,tx:r,nin:i,flags:n,satoshisBN:o}),!this.evaluate())return!1;if(this.stack.length===0)return this.errstr="SCRIPT_ERR_EVAL_FALSE_NO_RESULT",!1;var d=this.stack[this.stack.length-1];if(!L.castToBool(d))return this.errstr="SCRIPT_ERR_EVAL_FALSE_IN_STACK",!1;if(l&&t.isScriptHashOut()){if(!e.isPushOnly())return this.errstr="SCRIPT_ERR_SIG_PUSHONLY",!1;if(s.length===0)throw new Error("internal error - stack copy empty");var v=s[s.length-1],_=im.fromBuffer(v);if(s.pop(),this.initialize(),this.set({script:_,stack:s,tx:r,nin:i,flags:n,satoshisBN:o}),!this.evaluate())return!1;if(s.length===0)return this.errstr="SCRIPT_ERR_EVAL_FALSE_NO_P2SH_STACK",!1;if(!L.castToBool(s[s.length-1]))return this.errstr="SCRIPT_ERR_EVAL_FALSE_IN_P2SH_STACK",!1}if((n&L.SCRIPT_VERIFY_CLEANSTACK)!==0){if((n&L.SCRIPT_VERIFY_P2SH)===0)return this.errstr="SCRIPT_ERR_INVALID_FLAGS",!1;if(this.enforceNonMalleability()&&this.stack.length!==1)return this.errstr="SCRIPT_ERR_CLEANSTACK",!1}return!0};FB.exports=L;L.prototype.initialize=function(e){this.stack=[],this.altstack=[],this.pc=0,this.pbegincodehash=0,this.nOpCount=0,this.returned=!1,this.nonTopLevelReturnAfterGenesis=!1,this.vfExec=[],this.vfElse=[],this.errstr="",this.flags=0};L.prototype.set=function(e){this.script=e.script||this.script,this.tx=e.tx||this.tx,this.nin=typeof e.nin<"u"?e.nin:this.nin,this.satoshisBN=e.satoshisBN||this.satoshisBN,this.stack=e.stack||this.stack,this.altstack=e.altstack||this.altstack,this.pc=typeof e.pc<"u"?e.pc:this.pc,this.pbegincodehash=typeof e.pbegincodehash<"u"?e.pbegincodehash:this.pbegincodehash,this.nOpCount=typeof e.nOpCount<"u"?e.nOpCount:this.nOpCount,this.returned=typeof e.returned<"u"?e.returned:this.returned,this.nonTopLevelReturnAfterGenesis=typeof e.nonTopLevelReturnAfterGenesis<"u"?e.nonTopLevelReturnAfterGenesis:this.nonTopLevelReturnAfterGenesis,this.vfExec=e.vfExec||this.vfExec,this.vfElse=e.vfElse||this.vfElse,this.errstr=e.errstr||this.errstr,this.flags=typeof e.flags<"u"?e.flags:this.flags};L.true=f.Buffer.from([1]);L.false=f.Buffer.from([]);L.MAX_SCRIPT_ELEMENT_SIZE=520;L.MAXIMUM_ELEMENT_SIZE=4;L.MAX_OPS_PER_SCRIPT=500;L.MAX_SCRIPT_SIZE=1e4;L.UNLIMITED=Number.MAX_SAFE_INTEGER;L.MAX_SCRIPT_NUM_LENGTH_AFTER_GENESIS=75e4;L.MAX_SCRIPT_NUM_LENGTH_AFTER_CHRONICLE=32e6;L.MAX_PUBKEYS_PER_MULTISIG_AFTER_GENESIS=4294967295;L.MAX_STACK_SIZE=1e3;L.MAX_STACK_MEMORY_USAGE_AFTER_GENESIS=L.UNLIMITED;L.STACK_MEMORY_USAGE_POLICY=100*1024*1024;L.STACK_ELEMENT_OVERHEAD=32;L.LOCKTIME_THRESHOLD=5e8;L.LOCKTIME_THRESHOLD_BN=new we(L.LOCKTIME_THRESHOLD);L.useGenesisLimits=function(e){return e=e||2147483647,L.MAX_SCRIPT_ELEMENT_SIZE=e,L.MAX_OPS_PER_SCRIPT=e,L.MAX_SCRIPT_SIZE=e,L};L.getLimits=function(){return{maxScriptElementSize:L.MAX_SCRIPT_ELEMENT_SIZE,maximumElementSize:L.MAXIMUM_ELEMENT_SIZE,maxOpsPerScript:L.MAX_OPS_PER_SCRIPT,maxScriptSize:L.MAX_SCRIPT_SIZE}};L.setLimits=function(e){return e=e||{},e.maxScriptElementSize!=null&&(L.MAX_SCRIPT_ELEMENT_SIZE=e.maxScriptElementSize),e.maximumElementSize!=null&&(L.MAXIMUM_ELEMENT_SIZE=e.maximumElementSize),e.maxOpsPerScript!=null&&(L.MAX_OPS_PER_SCRIPT=e.maxOpsPerScript),e.maxScriptSize!=null&&(L.MAX_SCRIPT_SIZE=e.maxScriptSize),L};L.SCRIPT_VERIFY_NONE=0;L.SCRIPT_VERIFY_P2SH=1;L.SCRIPT_VERIFY_STRICTENC=2;L.SCRIPT_VERIFY_DERSIG=4;L.SCRIPT_VERIFY_LOW_S=8;L.SCRIPT_VERIFY_NULLDUMMY=16;L.SCRIPT_VERIFY_SIGPUSHONLY=32;L.SCRIPT_VERIFY_MINIMALDATA=64;L.SCRIPT_VERIFY_DISCOURAGE_UPGRADABLE_NOPS=128;L.SCRIPT_VERIFY_CLEANSTACK=256;L.SCRIPT_VERIFY_CHECKLOCKTIMEVERIFY=512;L.SCRIPT_VERIFY_CHECKSEQUENCEVERIFY=1024;L.SCRIPT_VERIFY_MINIMALIF=8192;L.SCRIPT_VERIFY_NULLFAIL=16384;L.SCRIPT_VERIFY_COMPRESSED_PUBKEYTYPE=32768;L.SCRIPT_ENABLE_SIGHASH_FORKID=65536;L.SCRIPT_ENABLE_REPLAY_PROTECTION=1<<17;L.SCRIPT_ENABLE_MONOLITH_OPCODES=2048;L.SCRIPT_ENABLE_MAGNETIC_OPCODES=4096;L.SCRIPT_GENESIS=1<<18;L.SCRIPT_UTXO_AFTER_GENESIS=1<<19;L.SCRIPT_ENABLE_CHRONICLE=1<<20;L.SCRIPT_CHRONICLE=L.SCRIPT_ENABLE_CHRONICLE;L.SCRIPT_UTXO_AFTER_CHRONICLE=1<<21;L.CHRONICLE_ACTIVATION_HEIGHT=943816;L.ERA_SENSITIVE_ERRORS={SCRIPT_ERR_PUSH_SIZE:{cap:"stack element size (capped at 520 bytes pre-Genesis, unbounded after)",lifts:L.SCRIPT_UTXO_AFTER_GENESIS},SCRIPT_ERR_SCRIPT_SIZE:{cap:"total script size (capped at 10,000 bytes pre-Genesis, unbounded after)",lifts:L.SCRIPT_UTXO_AFTER_GENESIS},SCRIPT_ERR_OP_COUNT:{cap:"opcode count (capped at 201 pre-Genesis, unbounded after)",lifts:L.SCRIPT_UTXO_AFTER_GENESIS},SCRIPT_ERR_SCRIPTNUM_OVERFLOW:{cap:"script number width (4 bytes pre-Genesis, 750,000 after Genesis, 32,000,000 after Chronicle)",lifts:L.SCRIPT_UTXO_AFTER_GENESIS|L.SCRIPT_UTXO_AFTER_CHRONICLE}};L.ERA_FLAGS=L.SCRIPT_GENESIS|L.SCRIPT_UTXO_AFTER_GENESIS|L.SCRIPT_ENABLE_CHRONICLE|L.SCRIPT_UTXO_AFTER_CHRONICLE;L.eraDiagnostics=!(typeof b.default<"u"&&b.default.env&&b.default.env.BSV_NO_ERA_HINT==="1");var I_=!1;L.prototype._eraDiagnose=function(e){if(e!==void 0){var t=L.ERA_SENSITIVE_ERRORS[this.errstr];if(t&&(e&t.lifts)===0){var r=t.cap;this.eraHint=this.errstr+" was produced under PRE-GENESIS limits: "+r+`.
|
|
70
70
|
The flags passed to verify() (0x`+(e>>>0).toString(16)+`) carry no era bit, so those caps applied regardless of which feature opcodes were enabled.
|
|
71
71
|
To validate against BSV as it is today, omit the flags argument or pass Interpreter.mainnetFlags(). If you are deliberately testing pre-Genesis consensus this failure is correct \u2014 set Interpreter.eraDiagnostics = false (or BSV_NO_ERA_HINT=1) to silence this.`,L.eraDiagnostics&&!I_&&(I_=!0,console.warn(`
|
|
72
72
|
[@smartledger/bsv] `+this.eraHint+`
|
|
@@ -95,7 +95,7 @@ To validate against BSV as it is today, omit the flags argument or pass Interpre
|
|
|
95
95
|
===========================================`),console.log("\u2705 Final Stack State:"),eS(i.stack||[],i.altstack||[]),console.log("===========================================")}function _M(e,t,r){console.log("==========================================="),console.log("\u{1F50D} SCRIPT INTERPRETER DEBUGGER (FULL RUN)"),console.log(`===========================================
|
|
96
96
|
`);let i=new Gm,n=new qZ(1e5),o=i.verify(e,t,r,0,Gm.SCRIPT_ENABLE_SIGHASH_FORKID,n);console.log("\u{1F510} Locking Script:",t.toASM()),console.log("\u{1F513} Unlocking Script:",e.toASM()),console.log("-------------------------------------------"),console.log("\u2705 Result:",o?"TRUE (Success)":"\u274C FALSE (Failure)"),console.log("Final Stack:",i.stack.map(a=>a.toString("hex"))),console.log("AltStack:",i.altstack.map(a=>a.toString("hex"))),console.log("===========================================")}async function wM(){if(typeof b.default>"u"||!b.default.argv){console.log("\u2699\uFE0F CLI mode not available in browser environment");return}let e=b.default.argv.slice(2),t=d=>{let v=e.indexOf(d);return v!==-1&&e[v+1]?e[v+1]:null},r=t("--unlocking"),i=t("--locking"),n=t("--combined"),o=e.includes("--step"),a=e.includes("--truth"),s,u,c;if(n)c=Km(n);else{s=Km(r),u=Km(i);let d=f.Buffer.concat([s.toBuffer(),u.toBuffer()]);c=Sa.fromBuffer(d)}let l=new UZ,p=new FZ({prevTxId:"0".repeat(64),outputIndex:0,script:Sa.empty(),satoshis:1e5,output:new yM({satoshis:1e5,script:Sa.empty()})});l.addInput(p),l.addOutput(new yM({satoshis:1e5,script:Sa.empty()})),o?await bM(c,l,!0):a?_M(s||Sa.empty(),u||Sa.empty(),l):console.log("\u2699\uFE0F No mode specified. Use --step or --truth")}tS.exports={parseScript:Km,printStack:eS,stepThroughScript:bM,runFullEvaluation:_M,main:wM};typeof Wr<"u"&&Wr.main===tS&&wM()});var To=T((gfe,RM)=>{"use strict";g();var xM=ut(),OM=hn(),rS=Pr(),iS=zt(),jZ=ho(),IM=gi(),AM=mi(),Wm=Ke(),zZ=Le(),EM=gt(),nS=EM.SIGHASH_ALL|EM.SIGHASH_FORKID;function TM(){return OM.mainnetFlags()}function KZ(e,t,r){r=r||{};var i=new OM,n=i.verify(e,t,r.tx||new iS,r.inputIndex||0,r.flags||TM(),new Wm(r.satoshis||0));return{ok:n,err:i.errstr||""}}function PM(e,t,r,i,n){return AM.sighashPreimage(e,n||nS,t,r,new Wm(i))}function VZ(e,t,r,i,n){return zZ.sha256sha256(PM(e,t,r,i,n))}function GZ(e,t,r,i,n,o){o=o||nS;var a=AM.sign(e,t,o,r,i,new Wm(n));return f.Buffer.concat([a.toDER(),f.Buffer.from([o])])}function WZ(e,t,r){r=r||{};var i=new iS().addOutput(new IM({script:e,satoshis:t})),n=new iS;return n.addInput(new jZ({prevTxId:i.hash,outputIndex:0,script:xM.empty()}),e,t),r.outputs&&r.outputs.forEach(function(o){n.addOutput(o)}),{funding:i,spend:n}}function YZ(e,t){var r=e.toAddress?e.toAddress():e;return new IM({script:xM.buildPublicKeyHashOut(r),satoshis:t})}function ZZ(e){return e===0?rS.OP_0:e===-1?rS.OP_1NEGATE:e>=1&&e<=16?rS["OP_"+e]:new Wm(e).toScriptNumBuffer()}RM.exports={SIGHASH:nS,flags:TM,verify:KZ,rawPreimage:PM,sighashDigest:VZ,signInput:GZ,fundAndSpend:WZ,p2pkhOutput:YZ,scriptNum:ZZ}});var NM=T((vfe,BM)=>{"use strict";g();var $Z=Le(),XZ=To(),df=ut(),hf=Pr(),kM=XZ.signInput;function JZ(e){var t=$Z.sha256(e),r=new df().add(hf.OP_SHA256).add(t).add(hf.OP_EQUAL);return{lock:r,meta:{name:"hash-lock",digest:t.toString("hex")},unlock:function(i,n,o){return new df().add(o||e)}}}function QZ(e){var t=e.toPublicKey(),r=df.buildPublicKeyHashOut(t.toAddress());return{lock:r,meta:{name:"p2pkh",address:t.toAddress().toString()},unlock:function(i,n){return new df().add(kM(i,e,0,r,n)).add(t.toBuffer())}}}function e$(e,t){var r=t.map(function(n){return n.toPublicKey()}),i=new df().add(hf["OP_"+e]);return r.forEach(function(n){i.add(n.toBuffer())}),i.add(hf["OP_"+r.length]).add(hf.OP_CHECKMULTISIG),{lock:i,meta:{name:e+"-of-"+r.length+"-multisig"},unlock:function(n,o,a){a=a||t.slice(0,e);var s=new df().add(hf.OP_0);return a.forEach(function(u){s.add(kM(n,u,0,i,o))}),s}}}BM.exports={hashLock:JZ,p2pkh:QZ,multisig:e$}});var gf=T((bfe,FM)=>{"use strict";g();var CM=ut(),xt=Pr(),Po=gt(),Ym=Ke(),LM=Le(),aS=To(),sS=aS.SIGHASH,Zm=aS.scriptNum,pf=f.Buffer.from("79be667ef9dcbbac55a06295ce870b07029bfcdb2dce28d959f2815b16f81798","hex"),uS=new Ym("fffffffffffffffffffffffffffffffebaaedce6af48a03bbfd25e8cd0364141",16),t$=f.Buffer.concat([f.Buffer.from([2]),pf]),MM=f.Buffer.from(pf).reverse(),DM=f.Buffer.concat([f.Buffer.from(uS.toBuffer()).reverse(),f.Buffer.from([0])]),r$=f.Buffer.concat([f.Buffer.from([48,68,2,32]),pf,f.Buffer.from([2,32])]);function oS(e,t){var r;for(r=0;r<t-1;r++)e.add(xt.OP_1).add(xt.OP_SPLIT);for(r=0;r<t-1;r++)e.add(xt.OP_SWAP).add(xt.OP_CAT);return e}var i$=Po.SIGHASH_ALL|Po.SIGHASH_FORKID,n$=Po.SIGHASH_SINGLE|Po.SIGHASH_FORKID,o$=Po.SIGHASH_SINGLE|Po.SIGHASH_ANYONECANPAY|Po.SIGHASH_FORKID,a$=Po.SIGHASH_ALL|Po.SIGHASH_ANYONECANPAY|Po.SIGHASH_FORKID;function cS(e,t){var r=t&&t.sighashType||sS;return e.add(xt.OP_HASH256),oS(e,32),e.add(MM).add(xt.OP_ADD),e.add(DM).add(xt.OP_MOD),e.add(Zm(32)).add(xt.OP_NUM2BIN),oS(e,32),e.add(pf).add(xt.OP_DUP),e.add(xt.OP_2).add(xt.OP_SWAP).add(xt.OP_CAT),e.add(xt.OP_TOALTSTACK),e.add(f.Buffer.from([48,68,2,32])).add(xt.OP_SWAP).add(xt.OP_CAT),e.add(f.Buffer.from([2,32])).add(xt.OP_CAT),e.add(xt.OP_SWAP).add(xt.OP_CAT),e.add(f.Buffer.from([r])).add(xt.OP_CAT),e.add(xt.OP_FROMALTSTACK).add(xt.OP_CHECKSIG),e}function s$(){return cS(new CM)}function HM(e){return e.add(Zm(40)).add(xt.OP_RIGHT).add(Zm(32)).add(xt.OP_LEFT),e}function u$(e){return qM(e,sS)}function qM(e,t){var r=f.Buffer.from([t&255,0,0,0]);return e.add(xt.OP_DUP).add(Zm(4)).add(xt.OP_RIGHT).add(r).add(xt.OP_EQUALVERIFY),e}function c$(e){var t=f.Buffer.concat(e.map(function(r){return r.toBufferWriter().toBuffer()}));return LM.sha256sha256(t)}function f$(e){var t=new CM().add(xt.OP_DUP);return cS(t),t.add(xt.OP_VERIFY),HM(t),t.add(f.Buffer.from(e)).add(xt.OP_EQUAL),t}var l$=new Ym("7FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF5D576E7357A4501DDFE92F46681B20A0","hex");function UM(e){var t=LM.sha256sha256(e);if(t[0]<1||t[0]>127)return null;var r=new Ym(t).add(new Ym(pf)).mod(uS);if(r.gt(l$))return null;var i=r.toBuffer("be",32);return i[0]>=1?i:null}function h$(e,t,r,i,n){typeof n=="number"&&(n={maxTries:n}),n=n||{};var o=n.maxTries||5e3,a=n.start||0,s=n.field||"nLockTime",u=n.sighashType||sS;if(s!=="nLockTime"&&s!=="sequence")throw new Error("grind field must be 'nLockTime' or 'sequence'");for(var c=e.inputs[t],l=0;l<o;l++){var p=a+l;s==="nLockTime"?e.nLockTime=p:c.sequenceNumber=4294967294-p;var d=aS.rawPreimage(e,t,r,i,u);if(UM(d))return{preimage:d,tries:l+1,field:s,nonce:p}}throw new Error("OP_PUSH_TX grind failed after "+o+" tries")}FM.exports={Gx:pf,N:uS,PUBKEY:t$,gxLe:MM,N_LE:DM,DER_PREFIX:r$,reverseBytes:oS,pushTxCore:cS,authenticator:s$,extractHashOutputs:HM,assertSighashAll:u$,assertSighashType:qM,SIGHASH_ALL_FORKID:i$,SIGHASH_SINGLE_FORKID:n$,SIGHASH_SINGLE_ANYONECANPAY_FORKID:o$,SIGHASH_ALL_ANYONECANPAY_FORKID:a$,hashOutputs:c$,valueCovenant:f$,sFromPreimage:UM,grind:h$}});var lS=T((wfe,jM)=>{"use strict";g();var fS=gf(),d$=To(),p$=ut(),Cr=Pr(),mf=d$.scriptNum;function g$(e){var t=new p$;return t.add(Cr.OP_DUP),fS.pushTxCore(t),t.add(Cr.OP_VERIFY),fS.assertSighashAll(t),t.add(Cr.OP_DUP),t.add(mf(104)).add(Cr.OP_SPLIT).add(Cr.OP_NIP),t.add(Cr.OP_SIZE).add(mf(52)).add(Cr.OP_SUB).add(Cr.OP_SPLIT).add(Cr.OP_DROP),t.add(Cr.OP_OVER),t.add(mf(52)).add(Cr.OP_RIGHT).add(mf(8)).add(Cr.OP_LEFT),t.add(Cr.OP_BIN2NUM).add(mf(e)).add(Cr.OP_SUB),t.add(mf(8)).add(Cr.OP_NUM2BIN),t.add(Cr.OP_SWAP).add(Cr.OP_CAT),t.add(Cr.OP_HASH256),t.add(Cr.OP_SWAP),fS.extractHashOutputs(t),t.add(Cr.OP_EQUAL),t}jM.exports={pelsCovenant:g$}});var pS=T((Efe,KM)=>{"use strict";g();var m$=ei(),v$=sr(),y$=ut(),zM=Le(),dS=To(),Kt=Pr(),vf=dS.scriptNum;function $m(e){return e instanceof m$?e.toPublicKey().toBuffer():e instanceof v$?e.toBuffer():e}function b$(){return{name:"single-key",commit:function(e){return zM.sha256ripemd160($m(e))},emit:function(e){return e.add(Kt.OP_OVER).add(Kt.OP_HASH160).add(Kt.OP_EQUALVERIFY),e.add(Kt.OP_CHECKSIGVERIFY),e},unlockArgs:function(e,t,r,i,n){var o=dS.signInput(e,n,t,r,i);return[o,n.toPublicKey().toBuffer()]}}}function hS(e,t){var r=t.length;if(e<1||e>r||r<1||r>16)throw new Error("multisig requires 1 <= m <= n <= 16");var i=new y$().add(Kt["OP_"+e]);return t.forEach(function(n){i.add(f.Buffer.from(n))}),i.add(Kt["OP_"+r]).add(Kt.OP_CHECKMULTISIG),i.toBuffer()}function _$(e,t){if(typeof t!="number"||!Number.isInteger(t))throw new Error("multisig(m, nKeys): nKeys is the NUMBER of keys, not the keys themselves"+(Array.isArray(t)?" \u2014 pass "+t.length+" instead of the array":""));if(typeof e!="number"||!Number.isInteger(e))throw new Error("multisig(m, nKeys): m must be an integer");if(e<1||e>t||t<1||t>16)throw new Error("multisig requires 1 <= m <= n <= 16");return{name:e+"-of-"+t+"-multisig",m:e,n:t,commit:function(r){if(r.length!==t)throw new Error("expected "+t+" public keys");return zM.sha256ripemd160(hS(e,r.map($m)))},emit:function(r){r.add(Kt.OP_OVER).add(Kt.OP_HASH160).add(Kt.OP_EQUALVERIFY),r.add(vf(1)).add(Kt.OP_SPLIT).add(Kt.OP_NIP),r.add(Kt.OP_SIZE).add(vf(2)).add(Kt.OP_SUB).add(Kt.OP_SPLIT).add(Kt.OP_DROP);for(var i=0;i<this.n;i++)r.add(vf(34)).add(Kt.OP_SPLIT),r.add(Kt.OP_SWAP).add(vf(1)).add(Kt.OP_SPLIT).add(Kt.OP_NIP),r.add(Kt.OP_TOALTSTACK);for(r.add(Kt.OP_DROP),r.add(vf(this.m)),i=0;i<this.n;i++)r.add(Kt.OP_FROMALTSTACK);return r.add(vf(this.n)),r.add(Kt.OP_CHECKMULTISIGVERIFY),r},unlockArgs:function(r,i,n,o,a){var s=a.keys;if(s.length!==t)throw new Error("expected "+t+" public keys in signer.keys");var u=hS(e,s.map($m)),c=s.map($m).map(function(d){return d.toString("hex")}),l=a.signWith.map(function(d){var v=c.indexOf(d.toPublicKey().toBuffer().toString("hex"));if(v<0)throw new Error("signWith key is not in the committed key set");return{idx:v,priv:d}}).sort(function(d,v){return v.idx-d.idx}).slice(0,e);if(l.length<e)throw new Error("need at least "+e+" signing keys");var p=l.map(function(d){return dS.signInput(r,d.priv,i,n,o)});return[Kt.OP_0].concat(p).concat([u])}}}function w$(e){if(!e||typeof e.emit!="function"||typeof e.unlockArgs!="function"||typeof e.commit!="function")throw new Error("predicate authorizer needs { commit, emit, unlockArgs } functions");return{name:e.name||"predicate",commit:e.commit,emit:e.emit,unlockArgs:e.unlockArgs}}KM.exports={singleKey:b$,multisig:_$,predicate:w$,redeemScript:hS}});var mS=T((Ofe,JM)=>{"use strict";g();var S$=Ke(),Mh=gf(),gS=To(),Dh=pS(),Xm=ut(),Re=Pr(),Ro=gS.scriptNum;function GM(e,t){var r=f.Buffer.isBuffer(e)?e:t.commit(e);if(r.length!==20)throw new Error("owner commitment must be 20 bytes (HASH160)");return r}function VM(e,t){return t.length?e.add(f.Buffer.from(t)):e.add(Re.OP_0)}function WM(e,t){return e.add(Re.OP_DUP),Mh.pushTxCore(e),e.add(Re.OP_VERIFY),Mh.assertSighashAll(e),e.add(Re.OP_DUP).add(Ro(52)).add(Re.OP_RIGHT).add(Ro(8)).add(Re.OP_LEFT).add(Re.OP_TOALTSTACK),e.add(Re.OP_DUP),Mh.extractHashOutputs(e),e.add(Re.OP_TOALTSTACK),e.add(Ro(104)).add(Re.OP_SPLIT).add(Re.OP_NIP).add(Re.OP_SIZE).add(Ro(52)).add(Re.OP_SUB).add(Re.OP_SPLIT).add(Re.OP_DROP),e.add(Re.OP_DUP).add(Ro(4)).add(Ro(20)).add(Re.OP_SUBSTR),e.add(Re.OP_SWAP).add(Re.OP_TOALTSTACK),t.emit(e),e.add(Re.OP_FROMALTSTACK),e}function YM(e){return e.add(Ro(4)).add(Re.OP_SPLIT).add(Ro(20)).add(Re.OP_SPLIT).add(Re.OP_NIP),e.add(Re.OP_TOALTSTACK),e.add(Re.OP_SWAP).add(Re.OP_CAT),e.add(Re.OP_FROMALTSTACK).add(Re.OP_CAT),e}function ZM(e){var t=e.toBuffer().length;if(t<=252||t>65535)throw new Error("token script length must use a 3-byte varint (253..65535); got "+t);return e}function E$(e,t,r){r=r||Dh.singleKey();var i=new Xm;return i.add(GM(t,r)),i.add(Re.OP_DROP),WM(i,r),YM(i),i.add(Re.OP_FROMALTSTACK),i.add(Re.OP_SWAP),i.add(Re.OP_FROMALTSTACK),i.add(Re.OP_BIN2NUM).add(Ro(e)).add(Re.OP_SUB).add(Ro(8)).add(Re.OP_NUM2BIN),i.add(Re.OP_SWAP).add(Re.OP_CAT),i.add(Re.OP_HASH256),i.add(Re.OP_EQUAL),ZM(i)}function $M(e,t){t=t||Dh.singleKey();var r=new Xm;return r.add(GM(e,t)),r.add(Re.OP_DROP),WM(r,t),YM(r),r.add(Re.OP_CAT),r.add(Re.OP_SWAP).add(Re.OP_CAT),r.add(Re.OP_CAT),r.add(Re.OP_FROMALTSTACK),r.add(Re.OP_FROMALTSTACK).add(Re.OP_DROP),r.add(Re.OP_SWAP).add(Re.OP_HASH256).add(Re.OP_EQUAL),ZM(r)}function x$(e){return Dh.singleKey().commit(e)}function O$(e,t,r,i,n,o){o=o||{};var a=o.auth||Dh.singleKey(),s=o.inputIndex||0;if(t.length!==20)throw new Error("newOwnerHash must be 20 bytes (HASH160)");if(i<=1&&!o.allowLowValue)throw new Error("unlockTransfer: single-output token sets output = input - fee, which burns a "+i+"-sat UTXO (e.g. a 1-sat ordinal). Use Token.transferOrdinal / ownershipTokenMulti to preserve the satoshi.");Mh.grind(r,s,n,i,o.grind);var u=gS.rawPreimage(r,s,n,i),c=a.unlockArgs(r,s,n,i,e),l=new Xm().add(f.Buffer.from(t));return c.forEach(function(p){l.add(p)}),l.add(f.Buffer.from(u)),l}function XM(e,t,r,i,n,o,a){a=a||{};var s=a.auth||Dh.singleKey(),u=a.inputIndex||0;if(t.length!==20)throw new Error("newOwnerHash must be 20 bytes (HASH160)");if(!o||o.tokenValue==null||o.tokenValue.length!==8)throw new Error("layout.tokenValue must be the 8-byte LE value of the token output");Mh.grind(r,u,n,i,a.grind);var c=gS.rawPreimage(r,u,n,i),l=s.unlockArgs(r,u,n,i,e),p=new Xm;return VM(p,o.before||f.Buffer.alloc(0)),VM(p,o.after||f.Buffer.alloc(0)),p.add(f.Buffer.from(o.tokenValue)),p.add(f.Buffer.from(t)),l.forEach(function(d){p.add(d)}),p.add(f.Buffer.from(c)),p}function I$(e,t){return $M(e,t)}function A$(e,t,r,i,n,o){o=o||{},i==null&&(i=1);var a=o.tokenIndex||0,s=r.outputs||[],u=s[a];if(!u)throw new Error("transferOrdinal: spend has no output at tokenIndex "+a);if(u.satoshis!==i)throw new Error("transferOrdinal: token output value ("+u.satoshis+" sat) must equal the ordinal value ("+i+" sat) to avoid burning the inscription");function c(v){return v.toBufferWriter().toBuffer()}var l=f.Buffer.concat(s.slice(0,a).map(c)),p=f.Buffer.concat(s.slice(a+1).map(c)),d=new S$(i).toBuffer({endian:"little",size:8});return XM(e,t,r,i,n,{before:l,after:p,tokenValue:d},o)}JM.exports={ownershipToken:E$,ownershipTokenMulti:$M,ordinalLock:I$,ownerId:x$,unlockTransfer:O$,unlockTransferMulti:XM,transferOrdinal:A$}});var SS=T((Afe,QM)=>{"use strict";g();var Jm=gf(),T$=lS(),P$=mS(),_S=To(),vS=ut(),ur=Pr(),yS=zt(),yf=_S.scriptNum,bS=5e8,R$=f.Buffer.from([255,255,255,255]),k$=f.Buffer.from([0]);function B$(e,t){return e instanceof yS.Output?e:e instanceof vS?new yS.Output({script:e,satoshis:t}):_S.p2pkhOutput(e,t)}function N$(e,t,r,i,n,o){o=o||5e4;for(var a=0;a<o;a++){e.nLockTime=n+a;var s=_S.rawPreimage(e,t,r,i);if(Jm.sFromPreimage(s))return s}throw new Error("covenant grind failed after "+o+" tries")}function Ea(){if(!(this instanceof Ea))return new Ea;this._outputs=[],this._minLockTime=null}Ea.prototype.payTo=function(e,t){return this._outputs.push(B$(e,t)),this};Ea.prototype.lockUntil=function(e){if(!Number.isInteger(e)||e<1||e>4294967295)throw new Error("lockUntil: expected an integer in 1..4294967295, got "+e+' (nLockTime 0 means "no lock" \u2014 consensus treats such a transaction as final)');return this._minLockTime=e,this};Ea.prototype.outputs=function(){return this._outputs.map(function(e){return new yS.Output(e.toObject())})};Ea.prototype.describe=function(){var e=[];if(this._outputs.forEach(function(r,i){e.push("output["+i+"] = "+r.satoshis+" sat to "+r.script.toASM().slice(0,24)+"...")}),this._minLockTime!==null){var t=this._minLockTime<bS?"block height":"unix time";e.push("nLockTime >= "+this._minLockTime+" as a "+t),e.push("this input is non-final (nSequence != 0xffffffff)")}return"spend allowed iff: "+e.join(" AND ")};Ea.prototype.compile=function(){if(this._outputs.length===0&&this._minLockTime===null)throw new Error("empty policy: add at least one constraint (payTo / lockUntil)");var e=this,t=new vS().add(ur.OP_DUP);if(Jm.pushTxCore(t),t.add(ur.OP_VERIFY),this._outputs.length){var r=Jm.hashOutputs(this._outputs);t.add(ur.OP_DUP),Jm.extractHashOutputs(t),t.add(f.Buffer.from(r)).add(ur.OP_EQUALVERIFY)}return this._minLockTime!==null&&(t.add(ur.OP_DUP),t.add(yf(44)).add(ur.OP_RIGHT).add(yf(4)).add(ur.OP_LEFT),t.add(R$).add(ur.OP_EQUAL).add(ur.OP_NOT).add(ur.OP_VERIFY),t.add(ur.OP_DUP),t.add(yf(8)).add(ur.OP_RIGHT).add(yf(4)).add(ur.OP_LEFT),t.add(k$).add(ur.OP_CAT).add(ur.OP_BIN2NUM),this._minLockTime<bS&&t.add(ur.OP_DUP).add(yf(bS)).add(ur.OP_LESSTHAN).add(ur.OP_VERIFY),t.add(yf(this._minLockTime)).add(ur.OP_GREATERTHANOREQUAL).add(ur.OP_VERIFY)),t.add(ur.OP_DROP).add(ur.OP_1),{lock:t,outputs:e.outputs(),describe:function(){return e.describe()},unlock:function(i,n,o){o=o||0;var a=e._minLockTime===null?0:e._minLockTime;return e._minLockTime!==null&&(i.inputs[o].sequenceNumber=4294967294),new vS().add(N$(i,o,t,n,a))}}};function wS(){return new Ea}wS.perpetual=function(e){return T$.pelsCovenant(e)};wS.token=function(e,t){return P$.ownershipToken(e,t)};QM.exports={policy:wS,Policy:Ea}});var nD=T((Pfe,iD)=>{"use strict";g();var C$=hn(),L$=Ke(),M$=zt(),D$=Pr(),H$=To();function tD(e){if(e===0)return"OP_0";if(e>=1&&e<=75)return"PUSH("+e+")";if(e===76)return"OP_PUSHDATA1";if(e===77)return"OP_PUSHDATA2";if(e===78)return"OP_PUSHDATA4";try{return D$.fromNumber(e).toString()}catch{return"0x"+e.toString(16)}}function eD(e,t){t=t||16;var r=f.Buffer.from(e).toString("hex");return r.length<=t*2?r||"0":r.slice(0,t*2)+"...("+e.length+"B)"}function q$(e,t,r){r=r||{};var i=new C$,n=[];i.stepListener=function(a,s,u){n.push({phase:i.script===t?"lock":"unlock",op:tD(a.opcode&&typeof a.opcode.toNumber=="function"?a.opcode.toNumber():a.opcode.num),stack:s.map(function(c){return eD(c)}),altstack:u.map(function(c){return eD(c)})})};var o=i.verify(e,t,r.tx||new M$,r.inputIndex||0,typeof r.flags=="number"?r.flags:H$.flags(),new L$(r.satoshis||0));return{ok:o,err:i.errstr||"",steps:n}}function rD(e){var t=[],r=null;return e.steps.forEach(function(i,n){i.phase!==r&&(t.push("-- "+i.phase+" script --"),r=i.phase);var o=i.stack.length?i.stack.join(" | "):"(empty)",a=i.altstack.length?" alt:["+i.altstack.join(" | ")+"]":"";t.push(String(n).padStart(3)+" "+i.op.padEnd(16)+" -> ["+o+"]"+a)}),t.push((e.ok?"VALID":"INVALID")+(e.err?" ("+e.err+")":"")),t.join(`
|
|
97
97
|
`)}function U$(e){return console.log(rD(e)),e}iD.exports={trace:q$,format:rD,print:U$,opLabel:tD}});var sD=T((kfe,aD)=>{"use strict";g();var F$=Le(),oD=zt(),j$=Ni(),z$=ut(),Q={Covenant:qL(),Preimage:Ao(),SIGHASH:KL(),Builder:YL(),UTXOGenerator:oM(),ScriptTester:uM(),CovenantBuilder:Zw().CovenantBuilder,CovenantTemplates:Zw().CovenantTemplates,OpcodeMap:Gw(),ScriptUtils:gM(),StackExaminer:vM(),ScriptInterpreter:SM(),CovenantHelpers:To(),Locks:NM(),PushTx:gf(),PELS:lS(),Token:mS(),Authorizers:pS(),DSL:SS(),Policy:SS().Policy,Debugger:nD()};Q.policy=Q.DSL.policy;Q.trace=function(e,t,r){return Q.Debugger.trace(e,t,r)};Q.verifyScript=function(e,t,r){return Q.CovenantHelpers.verify(e,t,r)};Q.perpetualCovenant=function(e){return Q.PELS.pelsCovenant(e)};Q.ownershipToken=function(e,t,r){return Q.Token.ownershipToken(e,t,r)};Q.valueCovenant=function(e){return Q.PushTx.valueCovenant(e)};Q.ordinalLock=function(e,t){return Q.Token.ordinalLock(e,t)};Q.transferOrdinal=function(e,t,r,i,n,o){return Q.Token.transferOrdinal(e,t,r,i,n,o)};Q.createCovenant=function(e,t){return new Q.Covenant(e,t)};Q.extractPreimage=function(e,t){return new Q.Preimage(e,t)};Q.analyzeSIGHASH=function(e){return new Q.SIGHASH(e)};Q.buildCovenant=function(e,t){return new Q.Builder(e,t)};Q.createUTXOGenerator=function(e){return new Q.UTXOGenerator(e)};Q.createTestEnvironment=function(e){return Q.UTXOGenerator.createTestEnvironment(e)};Q.testScript=function(e,t,r){return Q.ScriptTester.test(e,t,r)};Q.testCovenant=function(e,t,r){return Q.ScriptTester.testCovenant(e,t,r)};Q.testFieldExtraction=function(e,t,r){return Q.ScriptTester.testFieldExtraction(e,t,r)};Q.debugScript=function(e,t){var r=new Q.ScriptTester(t);return r.debug(e)};Q.explainZeroHashes=function(){return Q.SIGHASH.explainZeroMystery()};Q.getAllSIGHASHTypes=function(){return Q.SIGHASH.getAllTypes()};Q.demonstrateAllSIGHASH=function(){return Q.SIGHASH.generateAllDemonstrations()};Q.createCovenantBuilder=function(){return new Q.CovenantBuilder};Q.createValueLockCovenant=function(e){return Q.CovenantTemplates.valueLock(e)};Q.createHashLockCovenant=function(e){return Q.CovenantTemplates.hashLock(e)};Q.createComplexValidationCovenant=function(e){return Q.CovenantTemplates.complexValidation(e)};Q.getOpcodeMap=function(){return Q.OpcodeMap.opcodeMap};Q.simulateScript=function(e,t){return Q.OpcodeMap.utils.simulate(e,t)};Q.createASMFromJS=function(e){return Q.OpcodeMap.utils.createASM(e)};Q.scriptToASM=function(e){return Q.ScriptUtils.scriptToASM(e)};Q.asmToScript=function(e){return Q.ScriptUtils.asmToScript(e)};Q.asmToHex=function(e){return Q.ScriptUtils.asmToHex(e)};Q.hexToASM=function(e){return Q.ScriptUtils.hexToASM(e)};Q.scriptToHex=function(e){return Q.ScriptUtils.scriptToHex(e)};Q.validateASM=function(e){return Q.ScriptUtils.validateASM(e)};Q.validateScript=function(e){return Q.ScriptUtils.validateScript(e)};Q.estimateScriptSize=function(e){return Q.ScriptUtils.estimateScriptSize(e)};Q.optimizeScript=function(e){return Q.ScriptUtils.optimizeScript(e)};Q.compareScripts=function(e,t){return Q.ScriptUtils.compareScripts(e,t)};Q.explainScript=function(e){return Q.ScriptUtils.explainScript(e)};Q.scriptMetrics=function(e){return Q.ScriptUtils.scriptMetrics(e)};Q.analyzeComplexity=function(e){return Q.ScriptUtils.analyzeComplexity(e)};Q.findOptimizations=function(e){return Q.ScriptUtils.findOptimizations(e)};Q.covenantToEnglish=function(e){return Q.ScriptUtils.covenantToEnglish(e)};Q.batchTestScripts=function(e,t){return Q.ScriptUtils.batchTestScripts(e,t)};Q.examineStack=function(e,t){return Q.StackExaminer.runScript(e,t)};Q.debugScriptExecution=function(e,t,r){return r=r||{},r.stepMode?Q.ScriptInterpreter.stepThroughScript(Q.ScriptInterpreter.parseScript(e+" "+t),new oD,!0):Q.ScriptInterpreter.runFullEvaluation(Q.ScriptInterpreter.parseScript(e),Q.ScriptInterpreter.parseScript(t),new oD)};Q.parseScript=function(e){return Q.ScriptInterpreter.parseScript(e)};Q.printStack=function(e,t){return Q.ScriptInterpreter.printStack(e,t)};Q.createQuickCovenant=function(e,t){let r=Q.createCovenantBuilder();switch(e){case"value_lock":return r.comment(`Value lock: minimum ${t.value} satoshis`).extractField("value").push(t.value).greaterThanOrEqual().verify().build();case"hash_lock":return r.comment(`Hash lock: requires preimage of ${t.hash}`).push("secret_placeholder").sha256().push(t.hash).equalVerify().build();case"time_lock":return r.comment(`Time lock: requires nLockTime > ${t.timestamp}`).extractField("nLockTime").push(t.timestamp).greaterThan().verify().build();case"multi_condition":let i=r.comment("Multi-condition covenant");return t.conditions.forEach(n=>{switch(n.type){case"value":i=i.extractField("value").push(n.value).greaterThanOrEqual().verify();break;case"hash":i=i.push("secret_placeholder").sha256().push(n.hash).equalVerify();break;case"time":i=i.extractField("nLockTime").push(n.timestamp).greaterThan().verify();break}}),i.build();default:throw new Error(`Unknown covenant type: ${e}`)}};Q.completeCovenantFlow=function(e,t,r){var i=new Q.Covenant(e);return i.completeFlow(t,r)};Q.getEducationalResources=function(){return{zeroHashMystery:Q.SIGHASH.explainZeroMystery(),sighashTypes:Q.SIGHASH.getAllTypes(),exampleDemonstrations:Q.SIGHASH.generateAllDemonstrations()}};Q.utils={};Q.utils.reconstructP2pkhScript=function(e){return z$.buildPublicKeyHashOut(e).toHex()};Q.utils.createCovenantAddress=function(e){var t=F$.sha256ripemd160(e.toBuffer());return j$.fromScriptHash(t)};Q.utils.decodeCompactSize=function(e,t){return Q.Preimage.decodeCompactSize(e,t)};Q.version=eb();Q.description="Smart Contract Framework for Bitcoin SV";Q.features={BIP143_PREIMAGE:!0,COMPACT_SIZE_VARINT:!0,BIDIRECTIONAL_EXTRACTION:!0,SIGHASH_DETECTION:!0,ZERO_HASH_WARNINGS:!0,MULTI_FIELD_VALIDATION:!0,REAL_UTXO_GENERATION:!0,SCRIPT_TESTING:!0,LOCAL_VERIFICATION:!0,JAVASCRIPT_TO_SCRIPT:!0,OPCODE_MAPPING:!0,COVENANT_BUILDER:!0,SCRIPT_ANALYSIS:!0,SCRIPT_OPTIMIZATION:!0,SCRIPT_CONVERSION:!0,BATCH_TESTING:!0,QUICK_COVENANTS:!0,SCRIPT_EXPLANATIONS:!0,STACK_EXAMINATION:!0,SCRIPT_DEBUGGING:!0,STEP_BY_STEP_EXECUTION:!0,INTERACTIVE_DEBUGGING:!0};Q.interpretScript=Q.debugScriptExecution;Q.getScriptMetrics=Q.scriptMetrics;aD.exports=Q});var uD=T((Nfe,Hh)=>{"use strict";g();var Qm=function(){var e=typeof b.default<"u"&&b.default.env&&b.default.env.BSV_DEBUG||typeof window<"u"&&window.BSV_DEBUG;e&&console.log.apply(console,arguments)},xa={MEMORY:"memory",SESSION:"session",LOCAL:"local"};function Ii(e){e=e||{},this.options={storage:e.storage||xa.MEMORY,storageKey:e.storageKey||"smartledger-utxos",autoSave:e.autoSave!==!1,maxUTXOs:e.maxUTXOs||1e3};var t=[xa.MEMORY,xa.SESSION,xa.LOCAL];if(t.indexOf(this.options.storage)===-1)throw new Error("Invalid storage type: "+this.options.storage);this.utxos=new Map,this.addressIndex=new Map,this.spentUTXOs=new Map,this.metadata={totalUTXOs:0,totalValue:0,createdAt:new Date().toISOString(),lastModified:new Date().toISOString()},this.loadFromStorage()}Ii.prototype.getStorage=function(){return this.options.storage===xa.SESSION?typeof sessionStorage<"u"?sessionStorage:null:this.options.storage===xa.LOCAL&&typeof localStorage<"u"?localStorage:null};Ii.prototype.loadFromStorage=function(){var e=this.getStorage();if(e)try{var t=e.getItem(this.options.storageKey);if(!t)return;var r=JSON.parse(t);if(!r.utxos)return;var i=this;r.utxos.forEach(function(n){var o=n.txid+":"+n.vout;i.utxos.set(o,n),i.addressIndex.has(n.address)||i.addressIndex.set(n.address,new Set),i.addressIndex.get(n.address).add(o)}),r.metadata&&(this.metadata=r.metadata),Qm("\u2705 BrowserUTXOManager: Loaded "+this.utxos.size+" UTXOs from "+this.options.storage+" storage")}catch(n){console.error("Failed to load UTXOs from storage:",n)}};Ii.prototype.saveToStorage=function(){if(this.options.storage!==xa.MEMORY){var e=this.getStorage();if(e)try{var t={utxos:Array.from(this.utxos.values()),metadata:this.metadata,version:"1.0.0",timestamp:new Date().toISOString()};e.setItem(this.options.storageKey,JSON.stringify(t)),Qm("\u{1F4BE} BrowserUTXOManager: Saved "+this.utxos.size+" UTXOs to "+this.options.storage+" storage")}catch(r){console.error("Failed to save UTXOs to storage:",r)}}};Ii.prototype.addUTXO=function(e){if(!e||!e.txid||typeof e.vout!="number")throw new Error("Invalid UTXO: missing txid or vout");var t=e.txid+":"+e.vout;if(this.utxos.has(t))return Qm("\u26A0\uFE0F UTXO already exists: "+t),!1;var r={txid:e.txid,vout:e.vout,address:e.address||"",satoshis:e.satoshis||0,script:e.script||"",status:"available",addedAt:new Date().toISOString()};return this.utxos.set(t,r),r.address&&(this.addressIndex.has(r.address)||this.addressIndex.set(r.address,new Set),this.addressIndex.get(r.address).add(t)),this.updateMetadata(),this.options.autoSave&&this.saveToStorage(),!0};Ii.prototype.getUTXOsForAddress=function(e){var t=this.addressIndex.get(e);if(!t)return[];var r=[],i=this;return t.forEach(function(n){var o=i.utxos.get(n);o&&o.status==="available"&&r.push(o)}),r};Ii.prototype.getBalance=function(e){var t=this.getUTXOsForAddress(e);return t.reduce(function(r,i){return r+(i.satoshis||0)},0)};Ii.prototype.spendUTXOs=function(e,t){t=t||"browser-spend";for(var r=[],i=0;i<e.length;i++){var n=e[i],o=n.txid+":"+n.vout,a=this.utxos.get(o);a&&a.status==="available"&&(a.status="spent",a.spentAt=new Date().toISOString(),a.spentInTx=t,this.spentUTXOs.set(o,{txid:a.txid,vout:a.vout,spentInTx:t,spentAt:a.spentAt}),r.push(a))}return this.updateMetadata(),this.options.autoSave&&this.saveToStorage(),r};Ii.prototype.getUTXO=function(e,t){var r=e+":"+t,i=this.utxos.get(r);return{exists:!!i,utxo:i,status:i?i.status:"not-found"}};Ii.prototype.createMockUTXOs=function(e,t,r){t=t||5,r=r||1e5;for(var i=[],n=0;n<t;n++){for(var o="",a=0;a<64;a++)o+=Math.floor(Math.random()*16).toString(16);var s={txid:o,vout:n,address:e,satoshis:r+Math.floor(Math.random()*1e4),script:"",status:"available"};this.addUTXO(s),i.push(s)}return i};Ii.prototype.getStats=function(){var e=0,t=0,r=0;return this.utxos.forEach(function(i){e+=i.satoshis||0,i.status==="available"?t++:i.status==="spent"&&r++}),{totalUTXOs:this.utxos.size,totalAvailable:t,totalSpent:r,totalValue:e,totalAddresses:this.addressIndex.size,storageType:this.options.storage,metadata:this.metadata}};Ii.prototype.updateMetadata=function(){var e=this.getStats();this.metadata.totalUTXOs=e.totalUTXOs,this.metadata.totalValue=e.totalValue,this.metadata.lastModified=new Date().toISOString()};Ii.prototype.exportData=function(){return JSON.stringify({utxos:Array.from(this.utxos.values()),metadata:this.metadata,version:"1.0.0",exportedAt:new Date().toISOString()})};Ii.prototype.importData=function(e,t){t=t||!1;try{var r=JSON.parse(e);if(t||(this.utxos.clear(),this.addressIndex.clear(),this.spentUTXOs.clear()),r.utxos&&Array.isArray(r.utxos)){var i=this;r.utxos.forEach(function(n){i.addUTXO(n)})}return Qm("\u2705 BrowserUTXOManager: Imported "+(r.utxos&&r.utxos.length||0)+" UTXOs"),!0}catch(n){return console.error("Failed to import UTXO data:",n),!1}};typeof Hh<"u"&&Hh.exports?(Hh.exports=Ii,Hh.exports.STORAGE_TYPES=xa):typeof window<"u"&&(window.BrowserUTXOManager=Ii,window.BrowserUTXOManager.STORAGE_TYPES=xa)});var fD=T((Lfe,cD)=>{"use strict";g();var ES=class{constructor(t,r={}){this.bsv=t,this.options={difficulty:r.difficulty||1,blockTime:r.blockTime||1e4,validateScripts:r.validateScripts!==!1,logLevel:r.logLevel||"info",...r},this.currentBlock={height:0,transactions:[],timestamp:Date.now()},this.mempool=[]}acceptTransaction(t){try{return this.options.validateScripts&&!this.validateTransactionSignatures(t)?(this.log("warn","\u274C Transaction rejected: Invalid signatures"),!1):(this.mempool.push(t),this.log("info",`\u2705 Transaction accepted into mempool: ${t.id||"unknown"}`),!0)}catch(r){return this.log("error",`\u274C Transaction rejected: ${r.message}`),!1}}validateTransactionSignatures(t){try{let r=t.verify();return this.log("debug",`\u{1F4CA} Transaction verification result: ${r}`),r===!0}catch(r){return this.log("warn",`\u26A0\uFE0F Signature validation error: ${r.message}`),!1}}mineBlock(t=10){let r=this.mempool.splice(0,t),i={height:this.currentBlock.height+1,timestamp:Date.now(),transactions:r,transactionCount:r.length,previousBlockHash:this.currentBlock.hash||"0000000000000000000000000000000000000000000000000000000000000000"},n=JSON.stringify({height:i.height,timestamp:i.timestamp,previousBlockHash:i.previousBlockHash,transactions:r.map(o=>o.id||o.toString())});return i.hash=this.bsv.crypto.Hash.sha256(f.Buffer.from(n)).toString("hex"),this.currentBlock=i,this.log("info",`\u26CF\uFE0F Mined block ${i.height} with ${r.length} transactions`),this.log("debug",`\u{1F4E6} Block hash: ${i.hash}`),i}getMempoolStats(){return{transactionCount:this.mempool.length,transactions:this.mempool.map(t=>({id:t.id||"unknown",size:t.toBuffer?t.toBuffer().length:0,inputs:t.inputs?t.inputs.length:0,outputs:t.outputs?t.outputs.length:0}))}}getBlockchainStats(){return{currentHeight:this.currentBlock.height,currentBlockHash:this.currentBlock.hash,currentBlockTimestamp:this.currentBlock.timestamp,mempoolSize:this.mempool.length,difficulty:this.options.difficulty,blockTime:this.options.blockTime}}reset(){this.currentBlock={height:0,transactions:[],timestamp:Date.now()},this.mempool=[],this.log("info","\u{1F504} Miner reset to genesis state")}log(t,r){let i={error:0,warn:1,info:2,debug:3},n=i[this.options.logLevel]||2;if(i[t]<=n){let o=new Date().toISOString();console.log(`[${o}] [${t.toUpperCase()}] ${r}`)}}};cD.exports=ES});var pD=T((Dfe,dD)=>{g();var lD=mi(),bf=hn(),ko=gt(),hD=Ke(),K$=zt(),Zi=Pr(),vu=ut(),_f=class{static createSignature(t,r,i,n,o,a=null){a=a||ko.SIGHASH_ALL|ko.SIGHASH_FORKID;let s=lD.sign(t,r,a,i,n,new hD(o));return f.Buffer.concat([s.toDER(),f.Buffer.from([a])])}static createMultisigScript(t,r){let i=new vu().add(Zi[`OP_${t}`]);for(let n of r)i=i.add(n.toBuffer());return i.add(Zi[`OP_${r.length}`]).add(Zi.OP_CHECKMULTISIG)}static createMultisigUnlocking(t){let r=new vu().add(Zi.OP_0);for(let i of t)r=r.add(i);return r}static createConditionalScript(t,r=null){let i=new vu().add(Zi.OP_IF).add(t.toBuffer());return r&&(i=i.add(Zi.OP_ELSE).add(r.toBuffer())),i.add(Zi.OP_ENDIF)}static createP2PKHScript(t){return new vu().add(Zi.OP_DUP).add(Zi.OP_HASH160).add(t.toAddress().hashBuffer).add(Zi.OP_EQUALVERIFY).add(Zi.OP_CHECKSIG)}static createP2PKHUnlocking(t,r){return new vu().add(t).add(r.toBuffer())}static getPreimage(t,r,i,n,o=null){return o=o||ko.SIGHASH_ALL|ko.SIGHASH_FORKID,lD.sighash(t,o,r,i,new hD(n))}static createDataScript(t){return typeof t=="string"&&(t=f.Buffer.from(t,"utf8")),new vu().add(t)}static createOpReturnScript(t){return typeof t=="string"&&(t=f.Buffer.from(t,"utf8")),new vu().add(Zi.OP_FALSE).add(Zi.OP_RETURN).add(t)}static validateTransaction(t){try{return t.verify()}catch(r){return console.error("Transaction validation error:",r.message),!1}}static validateScript(t,r,i,n){try{return new bf().verify(t,r,i,n,bf.SCRIPT_VERIFY_P2SH|bf.SCRIPT_VERIFY_STRICTENC|bf.SCRIPT_ENABLE_SIGHASH_FORKID|bf.SCRIPT_ENABLE_MAGNETIC_OPCODES|bf.SCRIPT_ENABLE_MONOLITH_OPCODES)}catch(o){return console.error("Script validation error:",o.message),!1}}static createLowFeeTransaction(t,r,i=10){let n=new K$().feePerKb(i);for(let o of t)n=n.from(o);for(let o of r)n=n.to(o.address,o.satoshis);return n}};_f.SIGHASH_ALL=ko.SIGHASH_ALL|ko.SIGHASH_FORKID;_f.SIGHASH_NONE=ko.SIGHASH_NONE|ko.SIGHASH_FORKID;_f.SIGHASH_SINGLE=ko.SIGHASH_SINGLE|ko.SIGHASH_FORKID;dD.exports=_f});var ev=T((qfe,_D)=>{"use strict";g();var Oa=ut(),Kn=Pr(),gD=Ni(),V$=gi(),mD=f.Buffer.from("ord","utf8");function vD(e){if(e===null)return"null";if(e===void 0)return"undefined";if(Array.isArray(e))return"an array";var t=typeof e;return(t==="object"?"an ":"a ")+t}function xS(e,t){if(f.Buffer.isBuffer(e))return e;if(typeof e=="string")return f.Buffer.from(e,"utf8");throw new Error(t+" must be a string or Buffer, got "+vD(e))}var G$=["data","body","payload","text","message"];function W$(e){var t=e.lock!=null,r=e.address!=null;if(t&&r)throw new Error("buildInscription accepts `lock` or `address`, not both \u2014 they name different owners and one would be silently ignored");if(t){var i;if(e.lock instanceof Oa)i=e.lock;else if(f.Buffer.isBuffer(e.lock))i=Oa.fromBuffer(e.lock);else if(typeof e.lock=="string")i=Oa.fromHex(e.lock);else throw new Error("lock must be a Script, Buffer, or hex string, got "+vD(e.lock));if(!i.chunks.length&&!e.allowEmptyLock)throw new Error("lock is empty: the inscription would carry no locking script at all and the ordinal would be spendable by anyone. Pass a real lock, or { allowEmptyLock: true } if you are appending this envelope to your own script");return i}if(r){var n=e.address instanceof gD?e.address:gD.fromString(String(e.address));return Oa.buildPublicKeyHashOut(n)}throw new Error("buildInscription requires an address or a lock script")}var Y$=[0,1,2,3,5,7,9,11],Z$=0,$$=1;function X$(e,t){if(t>=1&&t<=16)return e.add(Kn.OP_1-1+t);for(var r=[],i=t;i>0;)r.push(i&255),i=Math.floor(i/256);return r[r.length-1]&128&&r.push(0),e.add(f.Buffer.from(r))}function J$(e,t){if(!Number.isSafeInteger(e)||e<0)throw new Error("field tag must be a non-negative integer, got "+JSON.stringify(e));if(e===Z$)throw new Error("field tag 0 opens the inscription body and cannot carry a field: anything pushed after it becomes part of the content");if(e===$$)throw new Error("field tag 1 is the content type; pass `contentType` instead of a field, or the inscription declares it twice");if(e%2===0&&Y$.indexOf(e)===-1&&!t)throw new Error("field tag "+e+" is an unrecognized even tag. The Ordinals spec requires such an inscription to be treated as unbound \u2014 it would be indexed without a location, permanently, and nothing local would report it. Use an odd tag, or pass { allowUnknownEvenFields: true } if you have established that every indexer you care about recognises "+e+".")}function Q$(e){var t=e.fields;if(t==null)return[];if(typeof t!="object"||Array.isArray(t)||f.Buffer.isBuffer(t))throw new Error("fields must be an object of tag numbers to values, e.g. { 5: metadata }");return Object.keys(t).filter(function(r){return t[r]!=null}).map(function(r){var i=Number(r);J$(i,e.allowUnknownEvenFields);var n=xS(t[r],"field "+i);if(!n.length)throw new Error("field "+i+" has an empty value; omit the field instead of inscribing a zero-length one permanently");return[i,n]}).sort(function(r,i){return r[0]-i[0]})}function yD(e){e=e||{};var t=W$(e);if(e.content==null){var r=G$.filter(function(s){return e[s]!=null})[0];throw new Error("buildInscription requires `content`"+(r?" \u2014 received `"+r+"`, which is not read":"")+". Omitting it would inscribe an empty payload; pass content: '' if that is intended")}var i=xS(e.content,"content"),n;if(e.contentType==null){if(f.Buffer.isBuffer(e.content))throw new Error("contentType is required when content is a Buffer (e.g. 'image/png', 'application/octet-stream') \u2014 it cannot be inferred from bytes");n=f.Buffer.from("text/plain","utf8")}else if(n=xS(e.contentType,"contentType"),!n.length)throw new Error("contentType must not be empty");var o=Q$(e),a=Oa.fromBuffer(t.toBuffer());return a.add(Kn.OP_FALSE),a.add(Kn.OP_IF),a.add(mD),a.add(Kn.OP_1),a.add(n),o.forEach(function(s){X$(a,s[0]),a.add(s[1])}),a.add(Kn.OP_0),a.add(i),a.add(Kn.OP_ENDIF),a}function qh(e,t){return e&&e.opcodenum===t&&e.buf==null}function bD(e){for(var t=e instanceof Oa?e:f.Buffer.isBuffer(e)?Oa.fromBuffer(e):Oa.fromHex(e),r=t.chunks,i=-1,n=0;n+2<r.length;n++)if(qh(r[n],Kn.OP_FALSE)&&qh(r[n+1],Kn.OP_IF)&&r[n+2].buf&&r[n+2].buf.equals(mD)){i=n;break}if(i===-1)return null;for(var o=f.Buffer.alloc(0),a=f.Buffer.alloc(0),s=r.length,u=i+3;u<r.length;u++){var c=r[u];if(qh(c,Kn.OP_ENDIF)){s=u;break}qh(c,Kn.OP_1)&&r[u+1]&&r[u+1].buf?(o=r[u+1].buf,u++):qh(c,Kn.OP_0)&&r[u+1]&&r[u+1].buf&&(a=r[u+1].buf,u++)}for(var l=new Oa,p=0;p<i;p++)l.chunks.push(r[p]);for(var d=s+1;d<r.length;d++)l.chunks.push(r[d]);return{contentType:o.toString("utf8"),content:a,contentText:a.toString("utf8"),lock:l}}function eX(e){try{return bD(e)!==null}catch{return!1}}function tX(e){e=e||{};var t=e.satoshis!=null?e.satoshis:1;if(typeof t!="number"||!Number.isInteger(t)||t<1)throw new Error("satoshis must be a positive integer (1 for a standard 1Sat ordinal)");return new V$({script:yD(e),satoshis:t})}_D.exports={buildInscription:yD,parseInscription:bD,isInscription:eX,createInscriptionOutput:tX}});var PD=T((Ffe,TD)=>{"use strict";g();var Sf=gf(),OS=To(),ED=ev(),Bo=ut(),Vt=Pr(),IS=Ni(),rX=sr(),iX=Le(),xD=zt(),nX=ho(),ms=gi(),OD=lo(),iv=Sf.SIGHASH_ALL_ANYONECANPAY_FORKID;function wD(e,t){return t&&t.length?e.add(f.Buffer.from(t)):e.add(Vt.OP_0)}function tv(e){return e.toBufferWriter().toBuffer()}function Ef(e,t){if(typeof e!="number"||!isFinite(e)||e<0||Math.floor(e)!==e)throw new Error(t+" must be a non-negative integer number of satoshis (got "+e+")");return e}function ov(e){return e instanceof Bo?e:f.Buffer.isBuffer(e)?Bo.fromBuffer(e):Bo.fromHex(e)}function ID(e){return e instanceof IS?e:e&&typeof e.toAddress=="function"?e.toAddress():IS.fromString(String(e))}function oX(e){if(f.Buffer.isBuffer(e)){if(e.length!==20)throw new Error("seller pubkeyhash buffer must be 20 bytes (HASH160)");return e}return e instanceof rX?iX.sha256ripemd160(e.toBuffer()):ID(e).hashBuffer}function xf(e,t){return Ef(t,"payment price"),new ms({script:Bo.buildPublicKeyHashOut(ID(e)),satoshis:t})}function rv(e){if(e instanceof ms)return e;if(f.Buffer.isBuffer(e))return ms.fromBufferReader(new OD(e));var t=e.payTo!=null?e.payTo:e.address,r=e.satoshis!=null?e.satoshis:e.price;if(t==null||r==null)throw new Error("payment spec needs {address|payTo, satoshis|price}");return xf(t,r)}function aX(e){if(e.payOutputs){if(!e.payOutputs.length)throw new Error("payOutputs must be a non-empty array");return e.payOutputs.map(rv)}if(e.payOutput!=null)return[rv(e.payOutput)];if(e.price!=null){var t=e.payTo!=null?e.payTo:e.seller,r=t instanceof ms?t:xf(t,e.price),i=[r];return e.royalties&&e.royalties.forEach(function(n){i.push(rv(n))}),i}throw new Error("buildOrdLock requires a price, a payOutput, or payOutputs")}function sX(e){return f.Buffer.concat(e.map(tv))}function av(e){if(e=e||{},e.seller==null)throw new Error("buildOrdLock requires a seller");var t=oX(e.seller),r=sX(aX(e)),i=new Bo;if(i.add(Vt.OP_IF),i.add(Vt.OP_DUP).add(Vt.OP_HASH160),i.add(f.Buffer.from(t)).add(Vt.OP_EQUALVERIFY).add(Vt.OP_CHECKSIG),i.add(Vt.OP_ELSE),i.add(Vt.OP_DUP),Sf.pushTxCore(i,{sighashType:iv}),i.add(Vt.OP_VERIFY),Sf.assertSighashType(i,iv),Sf.extractHashOutputs(i),i.add(Vt.OP_TOALTSTACK),i.add(f.Buffer.from(r)).add(Vt.OP_CAT),i.add(Vt.OP_SWAP).add(Vt.OP_CAT),i.add(Vt.OP_HASH256),i.add(Vt.OP_FROMALTSTACK).add(Vt.OP_EQUAL),i.add(Vt.OP_ENDIF),e.inscription){var n=ED.buildInscription({lock:new Bo,allowEmptyLock:!0,contentType:e.inscription.contentType,content:e.inscription.content});n.chunks.forEach(function(o){i.chunks.push(o)})}return i}function wf(e,t){return e&&e.opcodenum===t&&e.buf==null}function SD(e){for(var t=new OD(e),r=[];!t.eof();)r.push(ms.fromBufferReader(t));return r}function sv(e,t){var r=t&&t.network;try{for(var i=ov(e),n=i.chunks,o=0,a=-1,s=-1,u=-1,c=0;c<n.length;c++)if(wf(n[c],Vt.OP_IF))o===0&&(a=c),o++;else if(wf(n[c],Vt.OP_ELSE)&&o===1)s=c;else if(wf(n[c],Vt.OP_ENDIF)&&(o--,o===0)){u=c;break}if(a===-1||s===-1||u===-1)return null;for(var l=null,p=a+1;p<s;p++)if(n[p].buf&&n[p].buf.length===20){l=n[p].buf;break}if(!l)return null;for(var d=null,v=s+1;v<u;v++)wf(n[v],Vt.OP_TOALTSTACK)&&n[v+1]&&n[v+1].buf&&wf(n[v+2],Vt.OP_CAT)&&wf(n[v+3],Vt.OP_SWAP)&&(d=n[v+1].buf);if(!d)return null;var _=SD(d).map(function(z){var A=null;try{z.script.isPublicKeyHashOut()&&(A=z.script.toAddress(r).toString())}catch{}return{satoshis:z.satoshis,script:z.script,address:A}}),I=_.reduce(function(z,A){return z+A.satoshis},0),R=null,k=ED.parseInscription(i);k&&(R={contentType:k.contentType,content:k.content,contentText:k.contentText});var q=av({seller:l,payOutputs:SD(d),inscription:k?{contentType:k.contentType,content:k.content}:void 0});return q.toHex()!==i.toHex()?null:{seller:{pubKeyHash:l,address:IS.fromPublicKeyHash(l,r).toString()},payOutputs:_,payBlob:d,totalPrice:I,inscription:R}}catch{return null}}function uX(e,t){return sv(e,t)!==null}function cX(e){e=e||{};var t=e.satoshis!=null?e.satoshis:1;return new ms({script:av(e),satoshis:t})}function AD(e){e=e||{};var t=e.spend,r=e.lockingScript;if(!t||!r)throw new Error("purchase requires { spend, lockingScript }");var i=e.inputIndex||0,n=e.payoutIndex!=null?e.payoutIndex:1,o=e.satoshis!=null?e.satoshis:1,a=t.outputs||[],s=e.parsed||sv(r),u=e.payoutCount!=null?e.payoutCount:s?s.payOutputs.length:1;if(n+u>a.length)throw new Error("purchase: spend has fewer outputs than the pinned block requires (need "+(n+u)+", have "+a.length+")");if(e.validate!==!1&&s){var c=f.Buffer.concat(a.slice(n,n+u).map(tv));if(!c.equals(s.payBlob))throw new Error("purchase: outputs ["+n+".."+(n+u-1)+"] do not match the listing payment \u2014 the seller (or a royalty/fee payee) would not be paid")}var l=f.Buffer.concat(a.slice(0,n).map(tv)),p=f.Buffer.concat(a.slice(n+u).map(tv)),d=Object.assign({sighashType:iv},e.grind||{}),v=Sf.grind(t,i,r,o,d),_=new Bo;return wD(_,p),wD(_,l),_.add(f.Buffer.from(v.preimage)),_.add(Vt.OP_FALSE),t.inputs[i].setScript(_),_}function fX(e){e=e||{};var t=e.privateKey,r=e.spend,i=e.lockingScript;if(!t||!r||!i)throw new Error("cancel requires { privateKey, spend, lockingScript }");var n=e.inputIndex||0,o=e.satoshis!=null?e.satoshis:1,a=e.sighashType!=null?e.sighashType:OS.SIGHASH,s=OS.signInput(r,t,n,i,o,a),u=new Bo;return u.add(f.Buffer.from(s)),u.add(t.toPublicKey().toBuffer()),u.add(Vt.OP_TRUE),r.inputs[n].setScript(u),u}function nv(e,t,r,i){e.addInput(new nX({prevTxId:t.txid||t.prevTxId,outputIndex:t.outputIndex!=null?t.outputIndex:t.vout,script:Bo.empty()}),ov(r),i)}function AS(e,t,r){Ef(r.satoshis,"input "+t+" satoshis");var i=ov(r.script),n=OS.signInput(e,r.privateKey,t,i,r.satoshis,Sf.SIGHASH_ALL_FORKID),o=new Bo;o.add(f.Buffer.from(n)),o.add(r.privateKey.toPublicKey().toBuffer()),e.inputs[t].setScript(o)}function lX(e){e=e||{};var t=e.ordinal;if(!t||!t.script||!t.privateKey)throw new Error("buildListingTx requires ordinal { script, privateKey, txid, outputIndex }");var r=Ef(t.satoshis!=null?t.satoshis:1,"ordinal satoshis"),i=av(e),n=e.funding||[],o=e.fee!=null?e.fee:500,a=n.reduce(function(c,l){return c+Ef(l.satoshis,"funding satoshis")},0),s=a-o;if(s<0)throw new Error("buildListingTx: insufficient funding \u2014 need "+o+" sat fee, funded "+a);var u=new xD;return nv(u,t,t.script,r),n.forEach(function(c){nv(u,c,c.script,c.satoshis)}),u.addOutput(new ms({script:i,satoshis:r})),s>0&&u.addOutput(xf(e.changeAddress||t.privateKey.toAddress(),s)),AS(u,0,{script:t.script,privateKey:t.privateKey,satoshis:r}),n.forEach(function(c,l){AS(u,1+l,c)}),{tx:u,listingScript:i,listingOutpoint:{txid:u.hash,outputIndex:0}}}function hX(e){e=e||{};var t=e.listing;if(!t||!t.script)throw new Error("buildPurchaseTx requires listing.script");if(!e.ordinalDestination)throw new Error("buildPurchaseTx requires ordinalDestination");if(!e.funding||!e.funding.length)throw new Error("buildPurchaseTx requires funding coins");var r=ov(t.script),i=sv(r);if(!i)throw new Error("buildPurchaseTx: listing.script is not a parseable OrdLock");var n=Ef(t.satoshis!=null?t.satoshis:1,"listing satoshis"),o=e.payOutputs?e.payOutputs.map(rv):i.payOutputs.map(function(p){return new ms({script:p.script,satoshis:p.satoshis})}),a=o.reduce(function(p,d){return p+d.satoshis},0),s=e.fee!=null?e.fee:500,u=e.funding.reduce(function(p,d){return p+Ef(d.satoshis,"funding satoshis")},0),c=u-a-s;if(c<0)throw new Error("buildPurchaseTx: insufficient funding \u2014 need "+(a+s)+" sat (payments "+a+" + fee "+s+"), funded "+u);var l=new xD;return nv(l,t,r,n),e.funding.forEach(function(p){nv(l,p,p.script,p.satoshis)}),l.addOutput(xf(e.ordinalDestination,n)),o.forEach(function(p){l.addOutput(p)}),c>0&&l.addOutput(xf(e.changeAddress||e.ordinalDestination,c)),AD({spend:l,lockingScript:r,parsed:i,satoshis:n,inputIndex:0,payoutIndex:1,payoutCount:o.length,grind:e.grind}),e.funding.forEach(function(p,d){AS(l,1+d,p)}),l}TD.exports={ORDLOCK_SIGHASH:iv,buildOrdLock:av,parseOrdLock:sv,isOrdLock:uX,listInscriptionOutput:cX,payOutputFor:xf,purchase:AD,cancel:fX,buildListingTx:lX,buildPurchaseTx:hX}});var YD=T((zfe,WD)=>{"use strict";g();var RD=ev(),dX=ut(),pX=gi(),kD="application/bsv-20",TS=18,uv="18446744073709551615";function BD(e){return typeof e=="string"&&/^\d+$/.test(e)}function ND(e){return e.length>uv.length||e.length===uv.length&&e>uv}function CD(e,t){var r;if(typeof e=="number"){if(!Number.isInteger(e)||e<0)throw new Error(t+" must be a non-negative integer");if(e>Number.MAX_SAFE_INTEGER)throw new Error(t+" exceeds Number.MAX_SAFE_INTEGER and would lose precision \u2014 pass it as a string");r=String(e)}else if(BD(e))r=e.replace(/^0+(?=\d)/,"");else throw new Error(t+" must be a non-negative integer (string or number)");if(ND(r))throw new Error(t+" exceeds the uint64 maximum ("+uv+")");return r}function Uh(e,t){var r=CD(e,t);if(!/[1-9]/.test(r))throw new Error(t+" must be greater than zero");return r}function LD(e){if(typeof e!="string"||!e.length)throw new Error("tick is required");if(f.Buffer.byteLength(e,"utf8")>4)throw new Error("tick must be 1\u20134 UTF-8 bytes");return e}function PS(e){var t=typeof e=="string"?Number(e):e;if(!Number.isInteger(t)||t<0||t>TS)throw new Error("dec must be an integer 0\u2026"+TS);return String(t)}var RS=/^[0-9a-fA-F]{64}_\d+$/;function kS(e){if(typeof e!="string"||!RS.test(e))throw new Error('id must be "<txid>_<vout>" (64-hex txid, underscore, output index)');return e}function BS(e,t){if(typeof e!="string"){var r=e===null?"null":Array.isArray(e)?"an array":(typeof e=="object"?"an ":"a ")+typeof e;throw new Error(t+" must be a string, got "+r)}if(!e.length)throw new Error(t+" must not be empty");return e}function MD(e){if(BS(e,"icon"),!RS.test(e))throw new Error('icon must be an outpoint reference "<txid>_<vout>" (64-hex txid, underscore, output index)');return e}function yu(e,t){return t=t||{},RD.buildInscription({lock:t.lock,address:t.address,contentType:t.contentType||kD,content:JSON.stringify(e)})}function DD(e){e=e||{};var t={p:"bsv-20",op:"deploy",tick:LD(e.tick),max:Uh(e.max,"max")};return e.lim!=null&&(t.lim=CD(e.lim,"lim")),e.dec!=null&&(t.dec=PS(e.dec)),yu(t,e)}function HD(e,t,r){var i=t.tick!=null,n=t.id!=null;if(i&&n)throw new Error(r+" names a token by `tick` (v1) or `id` (BSV-21), not both");if(!i&&!n)throw new Error(r+" requires `tick` (v1) or `id` (BSV-21)");return n?e.id=kS(t.id):e.tick=LD(t.tick),e}function qD(e,t){if(e.amt!=null)throw new Error(t+" must not carry an amt \u2014 the specification forbids it, and a payload that does is discarded")}function UD(e){e=e||{};var t={p:"bsv-20",op:"mint"};return HD(t,e,"mint"),t.amt=Uh(e.amt,"amt"),yu(t,e)}function FD(e){e=e||{};var t={p:"bsv-20",op:"transfer",amt:Uh(e.amt,"amt")};return HD(t,e,"transfer"),yu(t,e)}function jD(e){if(e=e||{},e.tick!=null)throw new Error("burn is a BSV-21 operation and names its token by `id` (<txid>_<vout>), not `tick`");var t={p:"bsv-20",op:"burn",id:kS(e.id),amt:Uh(e.amt,"amt")};return yu(t,e)}function zD(e){e=e||{},qD(e,"deploy+auth");var t={p:"bsv-20",op:"deploy+auth"};return e.dec!=null&&(t.dec=PS(e.dec)),e.sym!=null&&(t.sym=BS(e.sym,"sym")),e.icon!=null&&(t.icon=MD(e.icon)),yu(t,e)}function KD(e){e=e||{},qD(e,"auth");var t={p:"bsv-20",op:"auth",id:kS(e.id)};return yu(t,e)}function VD(e){e=e||{};var t={p:"bsv-20",op:"deploy+mint",amt:Uh(e.amt,"amt")};return e.dec!=null&&(t.dec=PS(e.dec)),e.sym!=null&&(t.sym=BS(e.sym,"sym")),e.icon!=null&&(t.icon=MD(e.icon)),yu(t,e)}function bu(e,t){return new pX({script:e,satoshis:t??1})}function gX(e){return bu(DD(e),e&&e.satoshis)}function mX(e){return bu(UD(e),e&&e.satoshis)}function vX(e){return bu(FD(e),e&&e.satoshis)}function yX(e){return bu(VD(e),e&&e.satoshis)}function bX(e){return bu(jD(e),e&&e.satoshis)}function _X(e){return bu(zD(e),e&&e.satoshis)}function wX(e){return bu(KD(e),e&&e.satoshis)}function SX(e){if(e&&typeof e=="object"&&!f.Buffer.isBuffer(e)&&!(e instanceof dX)||typeof e=="string"&&e.trim()[0]==="{")return e;var t=RD.parseInscription(e);return t?t.contentText:null}var EX={deploy:{need:["tick","max"]},mint:{need:["amt"],tickOrId:!0},transfer:{need:["amt"],tickOrId:!0},"deploy+mint":{need:["amt"]},"deploy+auth":{need:[],noAmt:!0},auth:{need:["id"],noAmt:!0},burn:{need:["id","amt"]}};function xX(e){var t=typeof e=="number"?Number.isInteger(e)&&e>=0?String(e):null:BD(e)?e:null;return t==null?!1:!ND(t.replace(/^0+(?=\d)/,""))}function OX(e){if(!e||e.p!=="bsv-20"||typeof e.op!="string")return!1;var t=EX[e.op];if(!t)return!1;for(var r=0;r<t.need.length;r++)if(e[t.need[r]]==null)return!1;if(t.tickOrId&&e.tick==null==(e.id==null)||t.noAmt&&e.amt!=null||e.tick!=null&&(typeof e.tick!="string"||!e.tick.length||f.Buffer.byteLength(e.tick,"utf8")>4)||e.id!=null&&(typeof e.id!="string"||!RS.test(e.id)))return!1;for(var i=["amt","max","lim"],n=0;n<i.length;n++)if(e[i[n]]!=null&&!xX(e[i[n]]))return!1;if(e.dec!=null){var o=typeof e.dec=="string"?Number(e.dec):e.dec;if(!Number.isInteger(o)||o<0||o>TS)return!1}return!0}function GD(e){try{var t=SX(e);if(t==null)return null;var r=typeof t=="object"?t:JSON.parse(t);return OX(r)?r:null}catch{return null}}function IX(e){return GD(e)!==null}WD.exports={CONTENT_TYPE:kD,buildDeploy:DD,buildMint:UD,buildTransfer:FD,buildDeployMint:VD,buildBurn:jD,buildDeployAuth:zD,buildAuth:KD,createDeployOutput:gX,createMintOutput:mX,createTransferOutput:vX,createDeployMintOutput:yX,createBurnOutput:bX,createDeployAuthOutput:_X,createAuthOutput:wX,parseBsv20:GD,isBsv20:IX}});var $D=T((Vfe,ZD)=>{"use strict";g();var Fh=ev(),No=PD(),AX=YD();function TX(e){if(!Array.isArray(e)||!e.length)throw new Error("batchInscriptionOutputs requires a non-empty array of items");return e.map(function(t){return Fh.createInscriptionOutput(t)})}ZD.exports={buildInscription:Fh.buildInscription,parseInscription:Fh.parseInscription,isInscription:Fh.isInscription,createInscriptionOutput:Fh.createInscriptionOutput,batchInscriptionOutputs:TX,ORDLOCK_SIGHASH:No.ORDLOCK_SIGHASH,buildOrdLock:No.buildOrdLock,parseOrdLock:No.parseOrdLock,isOrdLock:No.isOrdLock,listInscriptionOutput:No.listInscriptionOutput,payOutputFor:No.payOutputFor,purchaseOrdLock:No.purchase,cancelOrdLock:No.cancel,buildListingTx:No.buildListingTx,buildPurchaseTx:No.buildPurchaseTx,BSV20:AX}});var cv=T((Yfe,QD)=>{"use strict";g();var PX=gt(),XD=dn(),NS=sr(),jh=ei(),JD=Le(),bn=Ie(),Wfe=pi();function Ot(e){return this instanceof Ot?(this.options=e||{},this.network=this.options.network||"mainnet",this.registry=this.options.registry||null,this):new Ot(e)}Ot.fromPublicKey=function(e,t){t=t||{},typeof e=="string"&&(e=NS.fromString(e)),bn.checkArgument(e instanceof NS,"Invalid public key");var r=e.toString("hex"),i=t.network||"mainnet",n=t.path||"",o="did:smartledger:"+r;return i!=="mainnet"&&(o+=":"+i),n&&(o+=":"+n),o};Ot.fromPrivateKey=function(e,t){return typeof e=="string"&&(e=jh.fromWIF(e)),bn.checkArgument(e instanceof jh,"Invalid private key"),Ot.fromPublicKey(e.toPublicKey(),t)};Ot.parseDID=function(e){if(bn.checkArgument(typeof e=="string","DID must be a string"),!e.startsWith("did:smartledger:"))throw new Error("Invalid SmartLedger DID format");var t=e.split(":");if(t.length<3)throw new Error("Invalid DID format");var r={method:"smartledger",identifier:t[2],network:"mainnet",path:""};return t.length>3&&t[3]!==""&&(r.network=t[3]),t.length>4&&(r.path=t.slice(4).join(":")),r};Ot.isValidDID=function(e){try{var t=Ot.parseDID(e);return!(!/^[0-9a-fA-F]{66}$/.test(t.identifier)&&!/^[0-9a-fA-F]{130}$/.test(t.identifier)||!["mainnet","testnet","regtest"].includes(t.network))}catch{return!1}};Ot.getPublicKey=function(e){var t=Ot.parseDID(e);return NS.fromString(t.identifier)};Ot.createDocument=function(e,t){t=t||{},bn.checkArgument(Ot.isValidDID(e),"Invalid DID");var r=Ot.getPublicKey(e),i=e+"#keys-1",n={"@context":["https://www.w3.org/ns/did/v1","https://w3id.org/security/suites/secp256k1-2019/v1"],id:e,verificationMethod:[{id:i,type:"EcdsaSecp256k1VerificationKey2019",controller:e,publicKeyHex:r.toString("hex")}],authentication:[i],assertionMethod:[i],keyAgreement:[i],capabilityInvocation:[i],capabilityDelegation:[i]};return t.services&&Array.isArray(t.services)&&(n.service=t.services),t.verificationMethods&&(n.verificationMethod=n.verificationMethod.concat(t.verificationMethods)),t.created&&(n.created=t.created),t.updated&&(n.updated=t.updated),n};Ot.resolve=async function(e,t){t=t||{};try{bn.checkArgument(Ot.isValidDID(e),"Invalid DID");var r=Ot.createDocument(e,t);return{"@context":"https://w3id.org/did-resolution/v1",didDocument:r,didResolutionMetadata:{contentType:"application/did+ld+json",retrieved:new Date().toISOString()},didDocumentMetadata:{method:{published:!0,recoveryCommitment:null,updateCommitment:null}}}}catch(i){return{"@context":"https://w3id.org/did-resolution/v1",didDocument:null,didResolutionMetadata:{error:"notFound",errorMessage:i.message},didDocumentMetadata:{}}}};Ot.verifyOwnership=function(e,t,r){try{var i=Ot.getPublicKey(e),n=JD.sha256(f.Buffer.isBuffer(r)?r:f.Buffer.from(r,"utf8")),o=PX.fromString(t),a=new XD;return a.hashbuf=n,a.pubkey=i,a.sig=o,a.verify()===!0}catch{return!1}};Ot.signMessage=function(e,t){bn.checkArgument(t instanceof jh,"Invalid private key");var r=JD.sha256(f.Buffer.isBuffer(e)?e:f.Buffer.from(e,"utf8")),i=new XD;return i.hashbuf=r,i.privkey=t,i.pubkey=t.toPublicKey(),i.sign().toString()};Ot.createProofOfOwnership=function(e,t){bn.checkArgument(e instanceof jh,"Invalid private key"),bn.checkArgument(typeof t=="string","Challenge must be a string");var r=Ot.fromPrivateKey(e),i=new Date().toISOString(),n=t+":"+i+":"+r,o=Ot.signMessage(n,e);return{type:"EcdsaSecp256k1Signature2019",created:i,verificationMethod:r+"#keys-1",proofPurpose:"authentication",challenge:t,jws:o}};Ot.verifyProofOfOwnership=function(e,t){try{bn.checkArgument(e&&typeof e=="object","Invalid proof object"),bn.checkArgument(typeof t=="string","DID must be a string");var r=e.challenge+":"+e.created+":"+t;return Ot.verifyOwnership(t,e.jws,r)}catch{return!1}};Ot.createDIDURL=function(e,t){return bn.checkArgument(typeof e=="string","DID must be a string"),bn.checkArgument(typeof t=="string","Fragment must be a string"),e+"#"+t};Ot.generateTestDID=function(e){e=e||{};var t=new jh,r=Ot.fromPrivateKey(t,e),i=Ot.createDocument(r,e);return{did:r,privateKey:t.toWIF(),publicKey:t.toPublicKey().toString("hex"),document:i}};QD.exports=Ot});var fv=T((Jfe,r6)=>{"use strict";g();var RX=Ki(),kX=cv(),e6=ei(),vs=Le(),t6=dn(),$fe=gt(),ys=Ie(),BX=Vc(),Xfe=at();function Ut(e,t){return this instanceof Ut?(typeof e=="string"&&(e=e6.fromWIF(e)),ys.checkArgument(e instanceof e6,"Invalid private key"),this.privateKey=e,this.publicKey=e.toPublicKey(),this.options=t||{},this.did=kX.fromPrivateKey(e,this.options),this):new Ut(e,t)}Ut._sortValue=function(e){return Array.isArray(e)?e.map(function(t){return Ut._sortValue(t)}):e!==null&&typeof e=="object"?Object.keys(e).sort().reduce(function(t,r){return t[r]=Ut._sortValue(e[r]),t},{}):e};Ut._canonicalizeJSON=function(e){return JSON.stringify(Ut._sortValue(e))};Ut._canonicalizeJCS=function(e){return BX.stringify(e)};Ut._hashCredential=function(e,t){var r=t===Ut.CANONICALIZATION.LEGACY?Ut._canonicalizeJSON(e):Ut._canonicalizeJCS(e);return vs.sha256(f.Buffer.from(r,"utf8"))};Ut.CANONICALIZATION={JCS:"jcs",LEGACY:"legacy"};Ut.prototype.createCredential=function(e,t){t=t||{},ys.checkArgument(e&&typeof e=="object","Invalid credential subject");var r=new Date().toISOString(),i=t.id||"urn:uuid:"+this._generateUUID(),n={"@context":["https://www.w3.org/2018/credentials/v1"],id:i,type:["VerifiableCredential"],issuer:this.did,issuanceDate:r,credentialSubject:e};return t.type&&(Array.isArray(t.type)?n.type=n.type.concat(t.type):n.type.push(t.type)),t.context&&(Array.isArray(t.context)?n["@context"]=n["@context"].concat(t.context):n["@context"].push(t.context)),t.expirationDate&&(n.expirationDate=t.expirationDate),t.termsOfUse&&(n.termsOfUse=t.termsOfUse),t.evidence&&(n.evidence=t.evidence),t.refreshService&&(n.refreshService=t.refreshService),n};Ut.prototype.signCredential=function(e,t){t=t||{},ys.checkArgument(e&&typeof e=="object","Invalid credential");var r=JSON.parse(JSON.stringify(e));delete r.proof;var i=Ut._hashCredential(r),n=new t6;n.hashbuf=i,n.privkey=this.privateKey,n.pubkey=this.publicKey,n.sign();var o=n.sig,a=this._createJWSSignature(i,o),s={type:"EcdsaSecp256k1Signature2019",created:new Date().toISOString(),verificationMethod:this.did+"#keys-1",proofPurpose:t.proofPurpose||"assertionMethod",jws:a};t.challenge&&(s.challenge=t.challenge),t.domain&&(s.domain=t.domain);var u=JSON.parse(JSON.stringify(r));return u.proof=s,u.rootHash=i.toString("hex"),u};Ut.prototype._createJWSSignature=function(e,t){var r={alg:"ES256K",typ:"JWT"},i=f.Buffer.from(JSON.stringify(r)).toString("base64url"),n=e.toString("base64url"),o=t.toDER().toString("base64url");return i+".."+o};Ut.prototype.createEmailCredential=function(e,t){t=t||{},ys.checkArgument(typeof e=="string"&&e.includes("@"),"Invalid email address");var r={id:t.subjectId||"did:smartledger:"+vs.sha256(f.Buffer.from(e)).toString("hex"),email:e,verified:!0,verificationMethod:"email_verification",verificationTimestamp:new Date().toISOString()},i={type:"EmailVerifiedCredential",context:"https://smartledger.technology/contexts/email/v1",...t},n=this.createCredential(r,i);return this.signCredential(n,t)};Ut.prototype.createAgeCredential=function(e,t,r){r=r||{},ys.checkArgument(typeof e=="number"&&e>0,"Invalid age");var i={id:r.subjectId||"urn:uuid:"+this._generateUUID(),ageOver:e,verified:!0,verificationMethod:"age_verification"};t&&(i.birthDateHash=vs.sha256(f.Buffer.from(t.toISOString())).toString("hex"));var n={type:"AgeVerifiedCredential",context:"https://smartledger.technology/contexts/age/v1",...r},o=this.createCredential(i,n);return this.signCredential(o,r)};Ut.prototype.createKYCCredential=function(e,t){t=t||{},ys.checkArgument(e&&typeof e=="object","Invalid KYC data");var r={id:t.subjectId||"urn:uuid:"+this._generateUUID(),kycLevel:e.level||"basic",verified:!0,verificationMethod:"kyc_verification",verificationTimestamp:new Date().toISOString(),verifyingAuthority:e.authority||this.did};e.firstName&&(r.firstNameHash=vs.sha256(f.Buffer.from(e.firstName)).toString("hex")),e.lastName&&(r.lastNameHash=vs.sha256(f.Buffer.from(e.lastName)).toString("hex")),e.ssn&&(r.ssnHash=vs.sha256(f.Buffer.from(e.ssn)).toString("hex"));var i={type:"KYCVerifiedCredential",context:"https://smartledger.technology/contexts/kyc/v1",...t},n=this.createCredential(r,i);return this.signCredential(n,t)};Ut.prototype.createOrganizationCredential=function(e,t){t=t||{},ys.checkArgument(e&&typeof e=="object","Invalid organization data");var r={id:t.subjectId||"did:smartledger:org:"+vs.sha256(f.Buffer.from(e.name||"")).toString("hex"),name:e.name,type:e.type||"Organization",verified:!0,verificationMethod:"organization_verification",verificationTimestamp:new Date().toISOString()};e.taxId&&(r.taxIdHash=vs.sha256(f.Buffer.from(e.taxId)).toString("hex")),e.incorporationState&&(r.incorporationState=e.incorporationState),e.industry&&(r.industry=e.industry);var i={type:"OrganizationCredential",context:"https://smartledger.technology/contexts/organization/v1",...t},n=this.createCredential(r,i);return this.signCredential(n,t)};Ut.prototype._generateUUID=function(){var e=RX.getRandomBuffer(16);e[6]=e[6]&15|64,e[8]=e[8]&63|128;var t=e.toString("hex");return[t.substring(0,8),t.substring(8,12),t.substring(12,16),t.substring(16,20),t.substring(20,32)].join("-")};Ut.prototype.createPresentation=function(e,t){t=t||{},ys.checkArgument(Array.isArray(e),"Credentials must be an array");var r={"@context":["https://www.w3.org/2018/credentials/v1"],type:["VerifiablePresentation"],id:t.id||"urn:uuid:"+this._generateUUID(),holder:this.did,verifiableCredential:e};t.context&&(Array.isArray(t.context)?r["@context"]=r["@context"].concat(t.context):r["@context"].push(t.context));var i=Ut._hashCredential(r),n=new t6;n.hashbuf=i,n.privkey=this.privateKey,n.pubkey=this.publicKey,n.sign();var o=n.sig,a=this._createJWSSignature(i,o),s={type:"EcdsaSecp256k1Signature2019",created:new Date().toISOString(),verificationMethod:this.did+"#keys-1",proofPurpose:"authentication",jws:a};return t.challenge&&(s.challenge=t.challenge),t.domain&&(s.domain=t.domain),r.proof=s,r};Ut.prototype.getIssuerInfo=function(){return{did:this.did,publicKey:this.publicKey.toString("hex"),verificationMethod:this.did+"#keys-1"}};r6.exports=Ut});var a6=T((rle,o6)=>{"use strict";g();var lv=cv(),Ia=fv(),ele=sr(),tle=Le(),i6=dn(),NX=gt(),n6=Ie();function St(e){return this instanceof St?(this.options=e||{},this.trustedIssuers=this.options.trustedIssuers||[],this):new St(e)}St.verifyCredential=async function(e,t){t=t||{};try{n6.checkArgument(e&&typeof e=="object","Invalid credential");var r={valid:!1,errors:[],warnings:[],checks:{structure:!1,signature:!1,issuer:!1,temporal:!1,schema:!1}},i=St._validateStructure(e);r.checks.structure=i.valid,i.valid||(r.errors=r.errors.concat(i.errors));var n=await St._verifySignature(e);r.checks.signature=n.valid,n.valid?(r.issuerDID=n.issuerDID,r.verificationMethod=n.verificationMethod):r.errors=r.errors.concat(n.errors);var o=await St._validateIssuer(e,t);r.checks.issuer=o.valid,o.valid||(r.errors=r.errors.concat(o.errors)),o.warnings&&(r.warnings=r.warnings.concat(o.warnings));var a=St._validateTemporal(e);if(r.checks.temporal=a.valid,a.valid||(r.errors=r.errors.concat(a.errors)),a.warnings&&(r.warnings=r.warnings.concat(a.warnings)),t.schema){var s=St._validateSchema(e,t.schema);r.checks.schema=s.valid,s.valid||(r.errors=r.errors.concat(s.errors))}else r.checks.schema=!0;return r.valid=Object.values(r.checks).every(u=>u===!0),r}catch(u){return{valid:!1,errors:["Verification failed: "+u.message],warnings:[],checks:{structure:!1,signature:!1,issuer:!1,temporal:!1,schema:!1}}}};St.verifyPresentation=async function(e,t){t=t||{};try{n6.checkArgument(e&&typeof e=="object","Invalid presentation");var r={valid:!1,errors:[],warnings:[],credentialResults:[],presentationValid:!1};if(!e.type||!e.type.includes("VerifiablePresentation"))return r.errors.push("Invalid presentation type"),r;if(!e.holder)return r.errors.push("Missing presentation holder"),r;var i=await St._verifyPresentationSignature(e);if(r.presentationValid=i.valid,i.valid||(r.errors=r.errors.concat(i.errors)),e.verifiableCredential&&Array.isArray(e.verifiableCredential))for(var n=0;n<e.verifiableCredential.length;n++){var o=e.verifiableCredential[n],a=await St.verifyCredential(o,t);r.credentialResults.push({index:n,result:a}),a.valid||r.errors.push("Credential "+n+" is invalid")}var s=r.credentialResults.every(u=>u.result.valid);return r.valid=r.presentationValid&&s,r}catch(u){return{valid:!1,errors:["Presentation verification failed: "+u.message],warnings:[],credentialResults:[],presentationValid:!1}}};St._validateStructure=function(e){var t=[];return e["@context"]?Array.isArray(e["@context"])?e["@context"].includes("https://www.w3.org/2018/credentials/v1")||t.push("Missing required W3C credentials context"):t.push("@context must be an array"):t.push("Missing @context"),e.type?Array.isArray(e.type)?e.type.includes("VerifiableCredential")||t.push("Must include VerifiableCredential type"):t.push("type must be an array"):t.push("Missing type"),e.issuer||t.push("Missing issuer"),e.issuanceDate||t.push("Missing issuanceDate"),e.credentialSubject||t.push("Missing credentialSubject"),e.proof||t.push("Missing proof"),{valid:t.length===0,errors:t}};St._normalizeDID=function(e){var t=e&&typeof e=="object"?e.id:e;return typeof t!="string"||t.length===0?null:t.split("#")[0]};St._verifySignature=async function(e){try{var t=e.proof;if(!t)return{valid:!1,errors:["Missing proof"]};if(t.type!=="EcdsaSecp256k1Signature2019")return{valid:!1,errors:["Unsupported proof type: "+t.type]};if(!t.verificationMethod)return{valid:!1,errors:["Missing verification method"]};if(!t.jws)return{valid:!1,errors:["Missing JWS signature"]};var r=t.verificationMethod,i=r.split("#")[0],n=St._normalizeDID(e.issuer);if(!n)return{valid:!1,errors:["Missing or invalid credential issuer"]};if(n!==i)return{valid:!1,errors:["Verification method DID ("+i+") does not match credential issuer ("+n+")"]};var o=lv.getPublicKey(i),a=JSON.parse(JSON.stringify(e));delete a.proof,delete a.rootHash;var s=St._parseJWSSignature(t.jws),u=[Ia.CANONICALIZATION.JCS,Ia.CANONICALIZATION.LEGACY].some(function(c){var l=new i6;return l.hashbuf=Ia._hashCredential(a,c),l.pubkey=o,l.sig=s,l.verify()===!0});return u?{valid:!0,issuerDID:i,verificationMethod:r}:{valid:!1,errors:["Signature verification failed"]}}catch(c){return{valid:!1,errors:["Signature verification error: "+c.message]}}};St._parseJWSSignature=function(e){var t=e.split(".");if(t.length!==3)throw new Error("Invalid JWS format");var r=t[2],i=f.Buffer.from(r,"base64url");return NX.fromDER(i)};St._verifyPresentationSignature=async function(e){try{var t=e.proof;if(!t)return{valid:!1,errors:["Missing presentation proof"]};var r=e.holder,i=lv.getPublicKey(r),n=JSON.parse(JSON.stringify(e));delete n.proof;var o=St._parseJWSSignature(t.jws),a=[Ia.CANONICALIZATION.JCS,Ia.CANONICALIZATION.LEGACY].some(function(s){var u=new i6;return u.hashbuf=Ia._hashCredential(n,s),u.pubkey=i,u.sig=o,u.verify()===!0});return{valid:a,errors:a?[]:["Presentation signature verification failed"]}}catch(s){return{valid:!1,errors:["Presentation signature error: "+s.message]}}};St._validateIssuer=async function(e,t){var r=[],i=[];try{var n=e.issuer;if(!lv.isValidDID(n))return r.push("Invalid issuer DID format"),{valid:!1,errors:r};var o=await lv.resolve(n);if(!o.didDocument)return r.push("Unable to resolve issuer DID"),{valid:!1,errors:r};if(t.trustedIssuers&&Array.isArray(t.trustedIssuers)){var a=St._normalizeDID(n),s=t.trustedIssuers.map(function(u){return St._normalizeDID(u)}).filter(Boolean);if(!a||s.indexOf(a)===-1)return r.push("Issuer not in trusted list"),{valid:!1,errors:r,warnings:i}}return{valid:r.length===0,errors:r,warnings:i}}catch(u){return{valid:!1,errors:["Issuer validation error: "+u.message],warnings:i}}};St._validateTemporal=function(e){var t=[],r=[],i=new Date;if(e.issuanceDate){var n=new Date(e.issuanceDate);isNaN(n.getTime())?t.push("Invalid issuanceDate format"):n>i&&t.push("Credential issued in the future")}if(e.expirationDate){var o=new Date(e.expirationDate);isNaN(o.getTime())?t.push("Invalid expirationDate format"):o<=i?t.push("Credential has expired"):o<=new Date(i.getTime()+1440*60*1e3)&&r.push("Credential expires within 24 hours")}return{valid:t.length===0,errors:t,warnings:r}};St._validateSchema=function(e,t){var r=[];if(t.requiredFields&&t.requiredFields.forEach(function(n){St._getNestedProperty(e,n)||r.push("Missing required field: "+n)}),t.requiredTypes){var i=t.requiredTypes.some(function(n){return e.type&&e.type.includes(n)});i||r.push("Missing required credential type")}return{valid:r.length===0,errors:r}};St._getNestedProperty=function(e,t){return t.split(".").reduce(function(r,i){return r&&r[i]},e)};St.verifyCredentialHash=function(e){try{if(!e.rootHash)return!1;var t=JSON.parse(JSON.stringify(e));delete t.proof,delete t.rootHash;var r=f.Buffer.from(e.rootHash,"hex");return[Ia.CANONICALIZATION.JCS,Ia.CANONICALIZATION.LEGACY].some(function(i){return f.Buffer.compare(Ia._hashCredential(t,i),r)===0})}catch{return!1}};St.extractClaims=function(e){try{var t={issuer:e.issuer,subject:e.credentialSubject.id||"unknown",types:e.type||[],issuanceDate:e.issuanceDate,expirationDate:e.expirationDate,claims:{}};return Object.keys(e.credentialSubject).forEach(function(r){r!=="id"&&(t.claims[r]=e.credentialSubject[r])}),t}catch{return null}};St.createReport=function(e){var t=[];return t.push("=== Credential Verification Report ==="),t.push("Overall Status: "+(e.valid?"VALID":"INVALID")),t.push(""),t.push("Verification Checks:"),Object.keys(e.checks).forEach(function(r){var i=e.checks[r]?"\u2713":"\u2717";t.push(" "+i+" "+r.charAt(0).toUpperCase()+r.slice(1))}),t.push(""),e.errors.length>0&&(t.push("Errors:"),e.errors.forEach(function(r){t.push(" \u2022 "+r)}),t.push("")),e.warnings.length>0&&(t.push("Warnings:"),e.warnings.forEach(function(r){t.push(" \u2022 "+r)}),t.push("")),e.issuerDID&&t.push("Issuer: "+e.issuerDID),e.verificationMethod&&t.push("Verification Method: "+e.verificationMethod),t.join(`
|
|
98
|
-
`)};o6.exports=St});var u6=T((ole,s6)=>{"use strict";g();var hv=Ki(),CX=fv(),Ai=Le(),nle=Ke(),ai=Ie(),LX=Vc();function $t(e){return this instanceof $t?(this.options=e||{},this):new $t(e)}$t.createMerkleTree=function(e,t){ai.checkArgument(e&&typeof e=="object","Invalid credential");var r=$t._extractFields(e),i=t||hv.getRandomBuffer(32).toString("hex"),n=r.map(function(a,s){var u=Ai.sha256(f.Buffer.from(i+":"+s+":"+a.path,"utf8")).toString("hex"),c=a.path+":"+JSON.stringify(a.value)+":"+u;return{path:a.path,value:a.value,hash:Ai.sha256(f.Buffer.from(c,"utf8")).toString("hex"),salt:u}}),o=$t._buildMerkleTree(n.map(a=>a.hash));return{salt:i,leaves:n,tree:o,root:o[o.length-1][0]}};$t.generateSelectiveProof=function(e,t,r){ai.checkArgument(e&&typeof e=="object","Invalid credential"),typeof t=="string"&&(t=[t]),ai.checkArgument(Array.isArray(t),"Disclose paths must be array");var i=$t.createMerkleTree(e,r),n=[],o=[];return t.forEach(function(a){var s=i.leaves.find(l=>l.path===a);if(s){n.push(s);var u=i.leaves.findIndex(l=>l.path===a),c=$t._generateMerkleProof(i.tree,u);o.push({path:a,leafIndex:u,proof:c})}}),{type:"SelectiveDisclosureProof",created:new Date().toISOString(),proofPurpose:"selectiveDisclosure",verificationMethod:e.proof?e.proof.verificationMethod:null,credentialRoot:i.root,credentialHash:e.rootHash||CX._hashCredential(e).toString("hex"),disclosedFields:n.map(function(a){return{path:a.path,value:a.value,hash:a.hash,salt:a.salt}}),merkleProofs:o}};$t.verifySelectiveProof=function(e,t){try{ai.checkArgument(e&&typeof e=="object","Invalid proof"),ai.checkArgument(typeof t=="string","Expected root must be string");for(var r={valid:!1,errors:[],verifiedFields:[]},i=0;i<e.disclosedFields.length;i++){var n=e.disclosedFields[i],o=e.merkleProofs.find(c=>c.path===n.path);if(!o){r.errors.push("Missing Merkle proof for field: "+n.path);continue}if(typeof n.salt!="string"||!n.salt){r.errors.push("Missing per-field salt for: "+n.path);continue}var a=n.path+":"+JSON.stringify(n.value)+":"+n.salt,s=Ai.sha256(f.Buffer.from(a,"utf8")).toString("hex");if(s!==n.hash){r.errors.push("Field hash mismatch for: "+n.path);continue}var u=$t._verifyMerkleProof(n.hash,o.proof,t);if(!u){r.errors.push("Invalid Merkle proof for: "+n.path);continue}r.verifiedFields.push({path:n.path,value:n.value,verified:!0})}return r.valid=r.errors.length===0&&r.verifiedFields.length>0,r}catch(c){return{valid:!1,errors:["Proof verification failed: "+c.message],verifiedFields:[]}}};$t.generateAgeProof=function(e,t,r){ai.checkArgument(e instanceof Date,"Birth date must be Date object"),ai.checkArgument(typeof t=="number","Minimum age must be number"),r=r||hv.getRandomBuffer(32).toString("hex");var i=new Date,n=Math.floor((i-e)/(365.25*24*60*60*1e3));if(n<t)throw new Error("Age requirement not met");var o=e.toISOString().split("T")[0],a=Ai.sha256(f.Buffer.from(o+":"+r,"utf8")).toString("hex"),s={minimumAge:t,ageAttestation:n>=t,timestamp:i.toISOString(),salt:r},u=Ai.sha256(f.Buffer.from(JSON.stringify(s),"utf8")).toString("hex");return{type:"AgeProof",created:new Date().toISOString(),proofPurpose:"ageVerification",minimumAge:t,meetsRequirement:!0,birthDateCommitment:a,ageProofHash:u,challengeResponse:$t._generateAgeChallenge(e,t,r),opening:{birthDate:o,salt:r}}};$t.verifyAgeProof=function(e,t,r){try{if(ai.checkArgument(e&&typeof e=="object","Invalid proof"),ai.checkArgument(typeof t=="number","Required age must be number"),e.type!=="AgeProof"||e.minimumAge!==t||!r||typeof r!="object")return!1;var i=r.birthDate;if(typeof i=="string"&&(i=new Date(i)),!(i instanceof Date)||isNaN(i.getTime())||typeof r.salt!="string")return!1;var n=i.toISOString().split("T")[0],o=Ai.sha256(f.Buffer.from(n+":"+r.salt,"utf8")).toString("hex");if(o!==e.birthDateCommitment)return!1;var a=Math.floor((Date.now()-i.getTime())/(365.25*24*60*60*1e3));return a>=t}catch{return!1}};$t.generateRangeProof=function(e,t,r,i){ai.checkArgument(typeof e=="number","Value must be number"),ai.checkArgument(typeof t=="number","Min must be number"),ai.checkArgument(typeof r=="number","Max must be number"),ai.checkArgument(e>=t&&e<=r,"Value not in range"),i=i||hv.getRandomBuffer(32).toString("hex");var n=Ai.sha256(f.Buffer.from(e.toString()+":"+i,"utf8")).toString("hex"),o={min:t,max:r,inRange:!0,timestamp:new Date().toISOString(),salt:i},a=Ai.sha256(f.Buffer.from(JSON.stringify(o),"utf8")).toString("hex");return{type:"RangeProof",created:new Date().toISOString(),proofPurpose:"rangeVerification",range:{min:t,max:r},valueCommitment:n,proofHash:a,inRange:!0,opening:{value:e,salt:i}}};$t.verifyRangeProof=function(e,t,r,i){try{if(ai.checkArgument(e&&typeof e=="object","Invalid proof"),e.type!=="RangeProof"||!e.range||e.range.min!==t||e.range.max!==r||!i||typeof i!="object"||typeof i.value!="number"||typeof i.salt!="string")return!1;var n=Ai.sha256(f.Buffer.from(i.value.toString()+":"+i.salt,"utf8")).toString("hex");return n!==e.valueCommitment?!1:i.value>=t&&i.value<=r}catch{return!1}};$t._extractFields=function(e,t){t=t||"";var r=[];return Object.keys(e).forEach(function(i){var n=t?t+"."+i:i,o=e[i];o&&typeof o=="object"&&!Array.isArray(o)&&!(o instanceof Date)?r=r.concat($t._extractFields(o,n)):r.push({path:n,value:o})}),r};$t._buildMerkleTree=function(e){if(e.length===0)throw new Error("Cannot build tree from empty leaves");for(var t=[e];t[t.length-1].length>1;){for(var r=t[t.length-1],i=[],n=0;n<r.length;n+=2){var o=r[n],a=n+1<r.length?r[n+1]:o,s=o+a,u=Ai.sha256(f.Buffer.from(s,"hex")).toString("hex");i.push(u)}t.push(i)}return t};$t._generateMerkleProof=function(e,t){for(var r=[],i=t,n=0;n<e.length-1;n++){var o=e[n],a=i%2===0,s=a?i+1:i-1;s<o.length&&r.push({hash:o[s],isLeft:!a}),i=Math.floor(i/2)}return r};$t._verifyMerkleProof=function(e,t,r){for(var i=e,n=0;n<t.length;n++){var o=t[n],a=o.isLeft?o.hash+i:i+o.hash;i=Ai.sha256(f.Buffer.from(a,"hex")).toString("hex")}return i===r};$t._generateAgeChallenge=function(e,t,r){var i=Ai.sha256(f.Buffer.from(e.toISOString()+t+r,"utf8"));return i.toString("hex")};function zh(e,t){var r=t||"value",i=typeof e;if(!(e===null||i==="boolean"||i==="string"))if(i==="number"){if(!isFinite(e))throw new Error(r+" must be a finite number")}else if(Array.isArray(e))for(var n=0;n<e.length;n++){if(e[n]===void 0)throw new Error(r+"["+n+"] is undefined");zh(e[n],r+"["+n+"]")}else if(i==="object"){if(Object.getPrototypeOf(e)!==Object.prototype&&Object.getPrototypeOf(e)!==null)throw new Error(r+" must be a plain object");for(var o=Object.keys(e),a=0;a<o.length;a++){if(e[o[a]]===void 0)throw new Error(r+"."+o[a]+" is undefined");zh(e[o[a]],r+"."+o[a])}}else throw new Error(r+" is not a permitted type: "+i);return LX.stringify(e)}$t.generateMembershipProof=function(e,t,r){ai.checkArgument(Array.isArray(e),"Set must be array");var i=e.map(function(s,u){return zh(s,"set["+u+"]")}),n=zh(t);ai.checkArgument(i.indexOf(n)!==-1,"Value not in set"),r=r||hv.getRandomBuffer(32).toString("hex");var o=i.map(function(s){return Ai.sha256(f.Buffer.from(s+":"+r,"utf8")).toString("hex")}),a=Ai.sha256(f.Buffer.from(n+":"+r,"utf8")).toString("hex");return{type:"MembershipProof",created:new Date().toISOString(),proofPurpose:"membershipVerification",setCommitments:o,valueCommitment:a,isMember:!0,salt:r}};$t.verifyMembershipProof=function(e,t,r){try{if(ai.checkArgument(e&&typeof e=="object","Invalid proof"),e.type!=="MembershipProof"||!Array.isArray(e.setCommitments)||!Array.isArray(r)||r.length===0||!t||typeof t!="object"||typeof t.salt!="string"||!("value"in t))return!1;var i=function(a,s){return Ai.sha256(f.Buffer.from(zh(a,s)+":"+t.salt,"utf8")).toString("hex")},n=r.map(function(a,s){return i(a,"set["+s+"]")});if(n.length!==e.setCommitments.length)return!1;for(var o=0;o<n.length;o++)if(n[o]!==e.setCommitments[o])return!1;return i(t.value,"opening.value")!==e.valueCommitment?!1:n.indexOf(e.valueCommitment)!==-1}catch{return!1}};s6.exports=$t});var p6=T((ule,d6)=>{"use strict";g();var MX=vh(),DX=mw(),CS=zt(),HX=ut(),Kh=ei(),sle=Ni(),Vh=Le(),c6=mm(),bs=Ie();function Lr(e,t){return this instanceof Lr?(typeof e=="string"&&(e=Kh.fromWIF(e)),e!==null?(bs.checkArgument(e instanceof Kh,"Invalid private key"),this.privateKey=e,this.address=e.toAddress()):(this.privateKey=null,this.address=null),this.options=t||{},this.network=this.options.network||"mainnet",this.PROTOCOL_ID="SMARTLEDGER.ATTEST",this.VERSION=1,this):new Lr(e,t)}Lr.prototype.anchorCredential=async function(e,t,r){t=t||{},typeof e=="string"&&(e=f.Buffer.from(e,"hex")),bs.checkArgument(f.Buffer.isBuffer(e),"Invalid credential hash"),bs.checkArgument(e.length===32,"Hash must be 32 bytes");var i=this._createAnchorPayload("CREDENTIAL",e,t),n=await this._createAnchorTransaction(i,r);return{txid:n.hash,transaction:n,anchorHash:e.toString("hex"),metadata:t,timestamp:new Date().toISOString(),blockchainProof:{protocol:this.PROTOCOL_ID,version:this.VERSION,type:"CREDENTIAL"}}};Lr.prototype.anchorBatch=async function(e,t,r){t=t||{},bs.checkArgument(Array.isArray(e),"Credential hashes must be array"),bs.checkArgument(e.length>0,"Must provide at least one hash");var i=this._createMerkleRoot(e),n=this._createAnchorPayload("BATCH",i,{...t,batchSize:e.length,merkleRoot:i.toString("hex")}),o=await this._createAnchorTransaction(n,r);return{txid:o.hash,transaction:o,merkleRoot:i.toString("hex"),batchSize:e.length,credentialHashes:e.map(a=>f.Buffer.isBuffer(a)?a.toString("hex"):a),metadata:t,timestamp:new Date().toISOString(),blockchainProof:{protocol:this.PROTOCOL_ID,version:this.VERSION,type:"BATCH"}}};Lr.prototype.registerDID=async function(e,t,r){bs.checkArgument(typeof e=="string","DID must be string"),bs.checkArgument(t&&typeof t=="object","Invalid DID document");var i=Vh.sha256(f.Buffer.from(JSON.stringify(t),"utf8")),n=this._createAnchorPayload("DID_REG",i,{did:e,operation:"create",documentHash:i.toString("hex")}),o=await this._createAnchorTransaction(n,r);return{txid:o.hash,transaction:o,did:e,documentHash:i.toString("hex"),timestamp:new Date().toISOString(),blockchainProof:{protocol:this.PROTOCOL_ID,version:this.VERSION,type:"DID_REG"}}};Lr.prototype.revokeCredential=async function(e,t,r){bs.checkArgument(typeof e=="string","Credential ID must be string"),t=t||"unspecified";var i={credentialId:e,reason:t,timestamp:new Date().toISOString(),issuer:this.address.toString()},n=Vh.sha256(f.Buffer.from(JSON.stringify(i),"utf8")),o=this._createAnchorPayload("REVOKE",n,{credentialId:e,reason:t}),a=await this._createAnchorTransaction(o,r);return{txid:a.hash,transaction:a,credentialId:e,reason:t,revocationHash:n.toString("hex"),timestamp:new Date().toISOString(),blockchainProof:{protocol:this.PROTOCOL_ID,version:this.VERSION,type:"REVOKE"}}};var qX=["bn","privateKey","privkey","privKey","wif","privateJwk","xpriv","xprv","mnemonic"],UX=["d","seed","secret","key"];function f6(e){if(typeof e!="string"||e.length<50||e.length>53)return!1;try{return Kh.fromWIF(e),!0}catch{return!1}}function l6(e){if(typeof e!="string"||!/^(xprv|tprv)/.test(e))return!1;try{return MX.fromString(e),!0}catch{return!1}}function h6(e){if(typeof e!="string")return!1;var t=e.trim().split(/\s+/);if([12,15,18,21,24].indexOf(t.length)===-1)return!1;try{return DX.isValid(e.trim())}catch{return!1}}function FX(e){if(typeof e!="string"||!/^[0-9a-fA-F]{64}$/.test(e))return!1;try{return Kh.fromHex(e),!0}catch{return!1}}function jX(e){return f6(e)||l6(e)||h6(e)}function zX(e,t){var r=[];if(t&&typeof t.toWIF=="function")try{r=[t.toWIF(),t.toString(),t.bn&&t.bn.toString(16)].filter(function(a){return typeof a=="string"&&a.length}).map(function(a){return a.toLowerCase()})}catch{r=[]}function i(a,s){throw new Error("Refusing to anchor: "+(a||"metadata")+" "+s+", and anchor metadata is published in the OP_RETURN where it is permanent and public.")}function n(a,s){r.length&&r.indexOf(a.toLowerCase())!==-1&&i(s,"is this anchor's own private key"),f6(a)&&i(s,"is a WIF private key"),l6(a)&&i(s,"is an extended private key"),h6(a)&&i(s,"is a BIP39 mnemonic phrase")}function o(a,s,u){if(typeof a=="string"){n(a,s);return}if(!(!a||typeof a!="object"||u>6)){if(typeof a.toWIF=="function"&&a.bn&&i(s,"is a PrivateKey"),Array.isArray(a)){a.forEach(function(c,l){o(c,(s||"metadata")+"["+l+"]",u+1)});return}Object.keys(a).forEach(function(c){var l=a[c],p=s?s+"."+c:c;if(l!=null&&typeof l!="object"){var d=String(l);qX.indexOf(c)!==-1&&i(p,"is a field that holds key material"),UX.indexOf(c)!==-1&&(jX(d)||FX(d))&&i(p,"holds something that decodes as a private key")}o(l,p,u+1)})}}o(e,"",0)}Lr.prototype._createAnchorPayload=function(e,t,r){var i=Math.floor(Date.now()/1e3);zX(r,this.privateKey);var n=f.Buffer.concat([f.Buffer.from(this.PROTOCOL_ID,"utf8"),f.Buffer.from([this.VERSION]),f.Buffer.from(e.padEnd(10,"\0"),"utf8"),f.Buffer.from([i>>24,i>>16,i>>8,i]),t,f.Buffer.from(JSON.stringify(r),"utf8")]);return n};Lr.prototype._createAnchorTransaction=async function(e,t){if(!t||t.length===0)throw new Error("UTXOs required for anchor transaction");var r=200+e.length,i=this.options.feeRate||1,n=r*i,o=t.reduce((c,l)=>c+l.satoshis,0);if(o<n)throw new Error("Insufficient funds for anchor transaction");var a=new CS;t.forEach(c=>{a.from(c)});var s=HX.buildDataOut(e);a.addOutput(new CS.Output({script:s,satoshis:0}));var u=o-n;return u>546&&a.to(this.address,u),a.sign(this.privateKey),a};Lr.prototype._createMerkleRoot=function(e){if(e.length===0)throw new Error("Cannot create Merkle root from empty array");for(var t=e.map(u=>f.Buffer.isBuffer(u)?u:f.Buffer.from(u,"hex"));t.length>1;){for(var r=[],i=0;i<t.length;i+=2){var n=t[i],o=i+1<t.length?t[i+1]:n,a=f.Buffer.concat([n,o]),s=Vh.sha256(a);r.push(s)}t=r}return t[0]};Lr.parseAnchorData=function(e){if(!f.Buffer.isBuffer(e))throw new Error("Data must be Buffer");if(e.length<50)throw new Error("Data too short for SmartLedger anchor");var t=0,r=18,i=e.slice(t,t+r).toString("utf8");if(t+=r,i!=="SMARTLEDGER.ATTEST")throw new Error("Invalid protocol identifier");var n=e[t];t+=1;var o=e.slice(t,t+10).toString("utf8").replace(/\0/g,"");t+=10;var a=e[t]<<24|e[t+1]<<16|e[t+2]<<8|e[t+3];t+=4;var s=e.slice(t,t+32);t+=32;var u=e.slice(t),c={};try{c=JSON.parse(u.toString("utf8"))}catch{}return{protocol:i,version:n,type:o,timestamp:new Date(a*1e3),hash:s.toString("hex"),metadata:c}};Lr.verifyAnchor=async function(e,t,r){if(r=r||{},!e||!t)throw new Error("verifyAnchor requires both txid and expectedHash");if(r.spvProof&&(r.header||r.headerChain)&&r.rawTx)return Lr._verifyAnchorSPV(e,t,r);if(typeof r.chainProvider!="function")throw new Error("verifyAnchor needs either a trustless SPV proof \u2014 { spvProof: { index, nodes }, header, rawTx } \u2014 or a trusted options.chainProvider(txid) returning { confirmations, blockHeight, opReturns }. Refusing to fabricate a result.");var i=r.minConfirmations!=null?r.minConfirmations:1,n=await r.chainProvider(e),o=n&&n.confirmations||0,a=n&&n.opReturns||[],s=String(t).toLowerCase(),u=a.some(function(l){return String(l).toLowerCase().indexOf(s)!==-1}),c=o>=i&&u;return{verified:c,txid:e,hash:t,committed:u,confirmations:o,blockHeight:n&&n.blockHeight||null,timestamp:new Date().toISOString(),proof:{type:"blockchain_anchor",protocol:"SMARTLEDGER.ATTEST",network:r.network||"mainnet"}}};Lr._verifyAnchorSPV=function(e,t,r){var i=r.spvProof||{},n=null,o=r.header;r.headerChain&&(n=c6.verifyHeaderChain(r.headerChain,{requirePow:r.requirePow!==!1,powLimit:r.powLimit,trustedHash:r.trustedHash}),o=r.headerChain[0]);var a=c6.verifyTxInclusion({txid:e,index:i.index,nodes:i.nodes,header:o,requirePow:r.requirePow!==!1,powLimit:r.powLimit,minWork:r.minWork}),s=f.Buffer.isBuffer(r.rawTx)?r.rawTx:f.Buffer.from(r.rawTx,"hex"),u=f.Buffer.from(Vh.sha256sha256(s)).reverse().toString("hex"),c=u.toLowerCase()===String(e).toLowerCase(),l=c&&Lr._rawTxCommitsTo(s,t),p=n?n.count:r.header?1:0,d=r.minConfirmations!=null?r.minConfirmations:1,v=n?n.valid:!0,_=p>=d;return{verified:a.valid&&c&&l&&v&&_,chainVerified:a.valid,committed:l,txidBound:c,powValid:a.powValid,confirmations:p,headerChainValid:n?n.valid:null,headerChainReason:n&&n.reason||null,tipHash:n?n.tipHash:null,txid:e,hash:t,blockHash:a.blockHash,merkleRoot:a.merkleRoot,timestamp:new Date().toISOString(),proof:{type:n?"spv_merkle_inclusion_with_confirmations":"spv_merkle_inclusion",protocol:"SMARTLEDGER.ATTEST",network:r.network||"mainnet"}}};Lr._rawTxCommitsTo=function(e,t){var r=String(t).toLowerCase(),i;try{i=new CS(e)}catch{return!1}return i.outputs.some(function(n){var o=n.script;if(!o||!o.chunks||!o.chunks.length)return!1;var a=o.chunks[0].opcodenum===106||o.chunks[0].opcodenum===0&&o.chunks[1]&&o.chunks[1].opcodenum===106;return a?o.chunks.some(function(s){return s.buf&&s.buf.toString("hex").toLowerCase().indexOf(r)!==-1}):!1})};Lr.getCostEstimate=function(e,t){t=t||{};var r=t.feeRate||1,i=200,n=32,o=e*(i+n)*r,a=(i+e*n)*r;return{individual:{totalCost:o,costPerHash:i*r,transactions:e},batch:{totalCost:a,costPerHash:Math.ceil(a/e),transactions:1},savings:{absolute:o-a,percentage:Math.round((o-a)/o*100)}}};Lr.createUTXO=function(e,t,r,i){return{txid:e,outputIndex:t,satoshis:r,script:i}};Lr.generateTestData=function(){var e=new Kh,t=new Lr(e),r=Vh.sha256(f.Buffer.from("test credential data")),i={issuer:"did:smartledger:test",type:"EmailVerifiedCredential",environment:"test"};return{privateKey:e.toWIF(),address:e.toAddress().toString(),credentialHash:r.toString("hex"),metadata:i,anchor:t}};d6.exports=Lr});var m6=T((fle,g6)=>{"use strict";g();var LS=Ie(),Gh={EmailVerifiedCredential:{"@context":["https://www.w3.org/2018/credentials/v1","https://smartledger.technology/contexts/email/v1"],type:["VerifiableCredential","EmailVerifiedCredential"],requiredFields:["credentialSubject.email","credentialSubject.verified"],properties:{credentialSubject:{type:"object",required:["email","verified"],properties:{email:{type:"string",format:"email"},verified:{type:"boolean"},verificationMethod:{type:"string"},verificationTimestamp:{type:"string",format:"date-time"}}}}},AgeVerifiedCredential:{"@context":["https://www.w3.org/2018/credentials/v1","https://smartledger.technology/contexts/age/v1"],type:["VerifiableCredential","AgeVerifiedCredential"],requiredFields:["credentialSubject.ageOver","credentialSubject.verified"],properties:{credentialSubject:{type:"object",required:["ageOver","verified"],properties:{ageOver:{type:"number",minimum:0,maximum:150},verified:{type:"boolean"},birthDateHash:{type:"string",pattern:"^[a-fA-F0-9]{64}$"},verificationMethod:{type:"string"}}}}},KYCVerifiedCredential:{"@context":["https://www.w3.org/2018/credentials/v1","https://smartledger.technology/contexts/kyc/v1"],type:["VerifiableCredential","KYCVerifiedCredential"],requiredFields:["credentialSubject.kycLevel","credentialSubject.verified","credentialSubject.verifyingAuthority"],properties:{credentialSubject:{type:"object",required:["kycLevel","verified","verifyingAuthority"],properties:{kycLevel:{type:"string",enum:["basic","enhanced","premium","institutional"]},verified:{type:"boolean"},verifyingAuthority:{type:"string"},verificationTimestamp:{type:"string",format:"date-time"},firstNameHash:{type:"string",pattern:"^[a-fA-F0-9]{64}$"},lastNameHash:{type:"string",pattern:"^[a-fA-F0-9]{64}$"},ssnHash:{type:"string",pattern:"^[a-fA-F0-9]{64}$"}}}}},OrganizationCredential:{"@context":["https://www.w3.org/2018/credentials/v1","https://smartledger.technology/contexts/organization/v1"],type:["VerifiableCredential","OrganizationCredential"],requiredFields:["credentialSubject.name","credentialSubject.type","credentialSubject.verified"],properties:{credentialSubject:{type:"object",required:["name","type","verified"],properties:{name:{type:"string"},type:{type:"string",enum:["Corporation","LLC","Partnership","NGO","Government","Other"]},verified:{type:"boolean"},taxIdHash:{type:"string",pattern:"^[a-fA-F0-9]{64}$"},incorporationState:{type:"string"},industry:{type:"string"},verificationMethod:{type:"string"},verificationTimestamp:{type:"string",format:"date-time"}}}}},SSNVerifiedCredential:{"@context":["https://www.w3.org/2018/credentials/v1","https://smartledger.technology/contexts/ssn/v1"],type:["VerifiableCredential","SSNVerifiedCredential"],requiredFields:["credentialSubject.ssnHash","credentialSubject.verified","credentialSubject.verifyingAuthority"],properties:{credentialSubject:{type:"object",required:["ssnHash","verified","verifyingAuthority"],properties:{ssnHash:{type:"string",pattern:"^[a-fA-F0-9]{64}$"},verified:{type:"boolean"},verifyingAuthority:{type:"string"},verificationTimestamp:{type:"string",format:"date-time"},issuingState:{type:"string"}}}}},EducationalCredential:{"@context":["https://www.w3.org/2018/credentials/v1","https://smartledger.technology/contexts/education/v1"],type:["VerifiableCredential","EducationalCredential"],requiredFields:["credentialSubject.degree","credentialSubject.institution","credentialSubject.graduationDate"],properties:{credentialSubject:{type:"object",required:["degree","institution","graduationDate"],properties:{degree:{type:"string"},institution:{type:"string"},graduationDate:{type:"string",format:"date"},gpa:{type:"number",minimum:0,maximum:4},major:{type:"string"},honors:{type:"array",items:{type:"string"}}}}}},ProfessionalLicenseCredential:{"@context":["https://www.w3.org/2018/credentials/v1","https://smartledger.technology/contexts/license/v1"],type:["VerifiableCredential","ProfessionalLicenseCredential"],requiredFields:["credentialSubject.licenseType","credentialSubject.licenseNumber","credentialSubject.issuingAuthority","credentialSubject.isValid"],properties:{credentialSubject:{type:"object",required:["licenseType","licenseNumber","issuingAuthority","isValid"],properties:{licenseType:{type:"string"},licenseNumber:{type:"string"},issuingAuthority:{type:"string"},issuingState:{type:"string"},isValid:{type:"boolean"},issueDate:{type:"string",format:"date"},expirationDate:{type:"string",format:"date"}}}}}},KX={getSchema:function(e){return Gh[e]||null},getAllSchemas:function(){return Gh},validate:function(e,t){try{LS.checkArgument(e&&typeof e=="object","Invalid credential");var r;if(typeof t=="string"){if(r=Gh[t],!r)return{valid:!1,errors:["Unknown schema type: "+t]}}else if(typeof t=="object")r=t;else return{valid:!1,errors:["Invalid schema parameter"]};var i=[],n=[];return this._validateCredentialStructure(e,i),this._validateCredentialTypes(e,r,i),this._validateRequiredFields(e,r,i),this._validateFieldProperties(e,r,i,n),{valid:i.length===0,errors:i,warnings:n}}catch(o){return{valid:!1,errors:["Schema validation error: "+o.message]}}},_validateCredentialStructure:function(e,t){e["@context"]||t.push("Missing @context"),e.type||t.push("Missing type"),e.issuer||t.push("Missing issuer"),e.issuanceDate||t.push("Missing issuanceDate"),e.credentialSubject||t.push("Missing credentialSubject")},_validateCredentialTypes:function(e,t,r){if(!Array.isArray(e.type)){r.push("Credential type must be array");return}if(t.type&&Array.isArray(t.type))for(var i=0;i<t.type.length;i++)e.type.includes(t.type[i])||r.push("Missing required type: "+t.type[i])},_validateRequiredFields:function(e,t,r){if(t.requiredFields&&Array.isArray(t.requiredFields))for(var i=0;i<t.requiredFields.length;i++){var n=t.requiredFields[i],o=this._getNestedProperty(e,n);o==null&&r.push("Missing required field: "+n)}},_validateFieldProperties:function(e,t,r,i){t.properties&&t.properties.credentialSubject&&this._validateObjectProperties(e.credentialSubject,t.properties.credentialSubject,"credentialSubject",r,i)},_validateObjectProperties:function(e,t,r,i,n){!e||typeof e!="object"||t.properties&&Object.keys(t.properties).forEach(function(o){var a=e[o],s=t.properties[o],u=r+"."+o;a!=null&&this._validateProperty(a,s,u,i,n)}.bind(this))},_validateProperty:function(e,t,r,i,n){if(t.type){var o=Array.isArray(e)?"array":typeof e;if(o!==t.type){i.push("Invalid type for "+r+": expected "+t.type+", got "+o);return}}if(t.type==="string"&&(t.format==="email"&&!this._isValidEmail(e)&&i.push("Invalid email format for "+r),t.format==="date"&&!this._isValidDate(e)&&i.push("Invalid date format for "+r),t.format==="date-time"&&!this._isValidDateTime(e)&&i.push("Invalid date-time format for "+r),t.pattern&&!new RegExp(t.pattern).test(e)&&i.push("Value does not match pattern for "+r),t.enum&&!t.enum.includes(e)&&i.push("Invalid enum value for "+r+": "+e)),t.type==="number"&&(t.minimum!==void 0&&e<t.minimum&&i.push("Value below minimum for "+r+": "+e+" < "+t.minimum),t.maximum!==void 0&&e>t.maximum&&i.push("Value above maximum for "+r+": "+e+" > "+t.maximum)),t.type==="array"&&t.items)for(var a=0;a<e.length;a++)this._validateProperty(e[a],t.items,r+"["+a+"]",i,n)},_getNestedProperty:function(e,t){return t.split(".").reduce(function(r,i){return r&&r[i]},e)},_isValidEmail:function(e){var t=/^[^\s@]+@[^\s@]+\.[^\s@]+$/;return t.test(e)},_isValidDate:function(e){var t=new Date(e);return!isNaN(t.getTime())&&e.match(/^\d{4}-\d{2}-\d{2}$/)},_isValidDateTime:function(e){var t=new Date(e);return!isNaN(t.getTime())},addSchema:function(e,t){LS.checkArgument(typeof e=="string","Schema name must be string"),LS.checkArgument(t&&typeof t=="object","Invalid schema definition"),Gh[e]=t},createTemplate:function(e){var t=Gh[e];if(!t)throw new Error("Unknown credential type: "+e);var r={"@context":t["@context"]||["https://www.w3.org/2018/credentials/v1"],type:t.type||["VerifiableCredential"],issuer:"did:smartledger:ISSUER_DID_HERE",issuanceDate:new Date().toISOString(),credentialSubject:this._createSubjectTemplate(t.properties?t.properties.credentialSubject:{})};return r},_createSubjectTemplate:function(e){var t={id:"SUBJECT_ID_HERE"};return e.properties&&Object.keys(e.properties).forEach(function(r){var i=e.properties[r];t[r]=this._getDefaultValue(i)}.bind(this)),t},_getDefaultValue:function(e){switch(e.type){case"string":return e.enum?e.enum[0]:e.format==="email"?"example@example.com":e.format==="date"?"2023-01-01":e.format==="date-time"?new Date().toISOString():"PLACEHOLDER_STRING";case"number":return e.minimum||0;case"boolean":return!0;case"array":return[];case"object":return{};default:return null}}};g6.exports=KX});var y6=T((hle,v6)=>{"use strict";g();var VX=cv(),Of=fv(),GX=a6(),WX=u6(),Wh=p6(),YX=m6();function tt(e){if(!(this instanceof tt))return new tt(e);e=e||{},this.didResolver=VX,this.attestationVerifier=GX,this.zkProver=WX,this.schemaValidator=YX,this._attestationSignerOptions=e.attestationSigner||{},this._anchorOptions=e.anchor||{}}tt.prototype.createDID=function(e){return this.didResolver.fromPublicKey(e)};tt.prototype.resolveDID=function(e){return this.didResolver.resolve(e)};tt.prototype.verifyDIDOwnership=function(e,t){return this.didResolver.verifyOwnership(e,t)};tt.prototype.createEmailCredential=function(e,t,r,i){var n=new Of(i,this._attestationSignerOptions);return n.createEmailCredential(r,{issuerDID:e,subjectId:t})};tt.prototype.createAgeCredential=function(e,t,r,i,n){var o=new Of(n,this._attestationSignerOptions);return o.createAgeCredential(r,i,{issuerDID:e,subjectId:t})};tt.prototype.createKYCCredential=function(e,t,r,i,n){var o=new Of(n,this._attestationSignerOptions),a=Object.assign({level:r},i);return o.createKYCCredential(a,{issuerDID:e,subjectId:t})};tt.prototype.createOrganizationCredential=function(e,t,r,i){var n=new Of(i,this._attestationSignerOptions);return n.createOrganizationCredential(r,{issuerDID:e,subjectId:t})};tt.prototype.createPresentation=function(e,t,r,i){var n=new Of(r,this._attestationSignerOptions);return n.createPresentation(e,t,r,i)};tt.prototype.signCredential=function(e,t){var r=new Of(t,this._attestationSignerOptions);return r.signCredential(e,t)};tt.prototype.verifyCredential=function(e,t){return this.attestationVerifier.verifyCredential(e,t)};tt.prototype.verifyPresentation=function(e,t){return this.attestationVerifier.verifyPresentation(e,t)};tt.prototype.extractClaims=function(e){return this.attestationVerifier.extractClaims(e)};tt.prototype.generateSelectiveProof=function(e,t,r){return this.zkProver.generateSelectiveProof(e,t,r)};tt.prototype.verifySelectiveProof=function(e,t){return this.zkProver.verifySelectiveProof(e,t)};tt.prototype.generateAgeProof=function(e,t,r){var i=new Date("1995-06-15");return this.zkProver.generateAgeProof(i,t,r)};tt.prototype.verifyAgeProof=function(e,t,r){return this.zkProver.verifyAgeProof(e,t,r)};tt.prototype.generateRangeProof=function(e,t,r,i){return this.zkProver.generateRangeProof(e,t,r,i)};tt.prototype.verifyRangeProof=function(e,t,r){return this.zkProver.verifyRangeProof(e,t,r)};tt.prototype.generateMembershipProof=function(e,t,r){return this.zkProver.generateMembershipProof(e,t,r)};tt.prototype.verifyMembershipProof=function(e,t){return this.zkProver.verifyMembershipProof(e,t)};function dv(e){return Array.isArray(e)?{metadata:void 0,utxos:e}:(e=e||{},{metadata:e.metadata,utxos:e.utxos})}tt.prototype.anchorCredential=function(e,t,r){var i=new Wh(t,this._anchorOptions),n=dv(r);return i.anchorCredential(e,n.metadata,n.utxos)};tt.prototype.anchorBatch=function(e,t,r){var i=new Wh(t,this._anchorOptions),n=dv(r);return i.anchorBatch(e,n.metadata,n.utxos)};tt.prototype.registerDID=function(e,t,r,i){var n=new Wh(r,this._anchorOptions);return n.registerDID(e,t,dv(i).utxos)};tt.prototype.revokeCredential=function(e,t,r,i){var n=new Wh(r,this._anchorOptions);return n.revokeCredential(e,t,dv(i).utxos)};tt.prototype.queryAnchoredData=function(e){var t=new Wh(null,this._anchorOptions);return t.queryAnchoredData(e)};tt.prototype.validateCredential=function(e,t){return this.schemaValidator.validate(e,t)};tt.prototype.getSchema=function(e){return this.schemaValidator.getSchema(e)};tt.prototype.getAllSchemas=function(){return this.schemaValidator.getAllSchemas()};tt.prototype.addSchema=function(e,t){return this.schemaValidator.addSchema(e,t)};tt.prototype.createTemplate=function(e){return this.schemaValidator.createTemplate(e)};tt.prototype.generateNonce=function(e){e=e||32;var t=nr();return t.randomBytes(e).toString("hex")};tt.prototype.hashData=function(e,t){var r=nr(),i=r.createHash("sha256");return i.update(e),t&&i.update(t),i.digest("hex")};tt.prototype.getVersion=function(){return"1.0.0"};tt.prototype.getInfo=function(){return{name:"SmartLedger BSV Global Digital Attestation Framework",version:this.getVersion(),description:"W3C-compliant verifiable credentials with DID resolution, zero-knowledge proofs, and blockchain anchoring",components:{didResolver:"DID Resolution and Management",attestationSigner:"Verifiable Credential Creation",attestationVerifier:"Credential and Presentation Verification",zkProver:"Zero-Knowledge Proof Generation and Verification",anchor:"Blockchain Anchoring and Timestamping",schemaValidator:"W3C VC Schema Validation"},standards:["W3C Verifiable Credentials Data Model v1.1","W3C Decentralized Identifiers (DIDs) v1.0","RFC 7515 JSON Web Signature (JWS)","BSV Blockchain Protocol"]}};v6.exports=tt});var _6=T((ple,b6)=>{"use strict";g();var pv=nr();async function ZX(e){e=e||{};var t=e.alg||"ES256",r=e.kid||"key-"+Date.now();if(t!=="ES256"&&t!=="ES256K")throw new Error("Invalid algorithm. Must be ES256 or ES256K");var i;t==="ES256"?i=pv.generateKeyPairSync("ec",{namedCurve:"P-256",publicKeyEncoding:{type:"spki",format:"pem"},privateKeyEncoding:{type:"pkcs8",format:"pem"}}):i=pv.generateKeyPairSync("ec",{namedCurve:"secp256k1",publicKeyEncoding:{type:"spki",format:"pem"},privateKeyEncoding:{type:"pkcs8",format:"pem"}});var n=pv.createPublicKey(i.publicKey).export({format:"jwk"}),o=pv.createPrivateKey(i.privateKey).export({format:"jwk"});return n.kid=r,n.alg=t,n.use="sig",n.kty="EC",o.kid=r,o.alg=t,o.use="sig",o.kty="EC",{privateJwk:o,publicJwk:n,kid:r,alg:t}}var Yh=["authentication","assertionMethod","keyAgreement","capabilityInvocation","capabilityDelegation"],$X=["authentication","assertionMethod"];function MS(e){var t=e.relationships||$X;if(!Array.isArray(t)||t.length===0)throw new Error("relationships must be a non-empty array of DID Core verification relationships");return t.forEach(function(r){if(Yh.indexOf(r)===-1)throw new Error("unknown verification relationship: "+r+" (expected one of "+Yh.join(", ")+")")}),t}function XX(e){if(!e.domain)throw new Error("domain is required");var t=e.domain,r="did:web:"+t.replace(/:/g,"%3A"),i=[],n=[],o=[];if(e.p256){var a={id:r+"#"+e.p256.kid,type:"JsonWebKey2020",controller:r,publicKeyJwk:e.p256.jwk};i.push(a),n.push(MS(e.p256)),o.push(e.p256.jwk)}if(e.k1){var s={id:r+"#"+e.k1.kid,type:"JsonWebKey2020",controller:r,publicKeyJwk:e.k1.jwk};i.push(s),n.push(MS(e.k1)),o.push(e.k1.jwk)}if(i.length===0)throw new Error("At least one key (p256 or k1) must be provided");var u={"@context":["https://www.w3.org/ns/did/v1","https://w3id.org/security/suites/jws-2020/v1"],id:r,verificationMethod:i};Yh.forEach(function(l){var p=i.filter(function(d,v){return n[v].indexOf(l)!==-1}).map(function(d){return d.id});p.length&&(u[l]=p)}),e.controllerName&&(u.controller=e.controllerName);var c={keys:o};return{did:r,didDocument:u,jwks:c}}function JX(e){if(!e.domain||!e.newKey)throw new Error("domain and newKey are required");var t=e.domain,r="did:web:"+t.replace(/:/g,"%3A"),i=e.keepOldForDays||30,n={id:r+"#"+e.newKey.kid,type:"JsonWebKey2020",controller:r,publicKeyJwk:e.newKey.jwk},o=MS(e.newKey),a=e.currentDocument||null,s={"@context":["https://www.w3.org/ns/did/v1","https://w3id.org/security/suites/jws-2020/v1"],id:r,verificationMethod:[n]};if(Yh.forEach(function(l){o.indexOf(l)!==-1?s[l]=[n.id]:a&&Array.isArray(a[l])&&a[l].length&&(s[l]=a[l].slice())}),a&&Array.isArray(a.verificationMethod)){var u={};Yh.forEach(function(l){(s[l]||[]).forEach(function(p){u[p]=!0})}),a.verificationMethod.forEach(function(l){u[l.id]&&l.id!==n.id&&s.verificationMethod.push(l)})}s.rotationInfo={rotatedAt:new Date().toISOString(),gracePeriodDays:i};var c={keys:[e.newKey.jwk]};return{didDocument:s,jwks:c}}b6.exports={generateIssuerKeys:ZX,buildDidWebDocuments:XX,rotateIssuerKey:JX}});var DS=T((mle,w6)=>{"use strict";g();var Zh=nr(),$h={ES256:"P-256",ES256K:"secp256k1"},QX=["ES256","ES256K"];function gv(e){return e.toString("base64").replace(/\+/g,"-").replace(/\//g,"_").replace(/=/g,"")}function mv(e){for(e=e.replace(/-/g,"+").replace(/_/g,"/");e.length%4;)e+="=";return f.Buffer.from(e,"base64")}async function eJ(e){if(!e.issuerDid||!e.subjectId||!e.credentialSubject||!e.privateJwk)throw new Error("issuerDid, subjectId, credentialSubject, and privateJwk are required");var t=e.alg||"ES256";if(!$h[t])throw new Error("Unsupported algorithm: "+t);if(e.privateJwk.crv&&e.privateJwk.crv!==$h[t])throw new Error("Key curve "+e.privateJwk.crv+" does not match alg "+t);var r=e.kid||e.privateJwk.kid,i=e.types||["VerifiableCredential"],n=e.expSeconds||365*24*60*60,o=Math.floor(Date.now()/1e3),a=new Date().toISOString(),s={"@context":["https://www.w3.org/2018/credentials/v1"],type:i,issuer:e.issuerDid,issuanceDate:a,credentialSubject:Object.assign({id:e.subjectId},e.credentialSubject)},u={iss:e.issuerDid,sub:e.subjectId,iat:o,exp:o+n,vc:s},c={alg:t,typ:"JWT",kid:r},l=gv(f.Buffer.from(JSON.stringify(c))),p=gv(f.Buffer.from(JSON.stringify(u))),d=l+"."+p,v=Zh.createPrivateKey({key:e.privateJwk,format:"jwk"}),_=Zh.sign("sha256",f.Buffer.from(d),{key:v,dsaEncoding:"ieee-p1363"}),I=gv(_),R=d+"."+I;return{jwt:R}}async function tJ(e,t){t=t||{};try{if(typeof e!="string")return{valid:!1,error:"Invalid JWT format"};var r=e.split(".");if(r.length!==3)return{valid:!1,error:"Invalid JWT format"};var i=r[0],n=r[1],o=r[2],a=JSON.parse(mv(i).toString()),s=JSON.parse(mv(n).toString()),u=mv(o),c=t.allowedAlgs||QX;if(!a.alg||c.indexOf(a.alg)===-1||!$h[a.alg])return{valid:!1,error:"Algorithm not allowed: "+a.alg,header:a,payload:s};var l=Math.floor(Date.now()/1e3),p=t.clockToleranceSec||60;if(t.requireExpiration&&!s.exp)return{valid:!1,error:"JWT missing required exp claim",header:a,payload:s};if(s.exp&&s.exp<l-p)return{valid:!1,error:"JWT expired",header:a,payload:s};if(s.nbf&&s.nbf>l+p)return{valid:!1,error:"JWT not yet valid",header:a,payload:s};if(t.expectedIssuerDid&&s.iss!==t.expectedIssuerDid)return{valid:!1,error:"Unexpected issuer",header:a,payload:s};var d;if(t.didResolver){var v=await t.didResolver(s.iss);if(!v||!v.jwks||!v.jwks.keys)return{valid:!1,error:"Failed to resolve issuer DID",header:a,payload:s};var _=v.jwks.keys.find(function(q){return q.kid===a.kid});if(!_)return{valid:!1,error:"Key not found in JWKS",header:a,payload:s};d=_}else return{valid:!1,error:"DID resolver required for verification",header:a,payload:s};if(d.crv&&d.crv!==$h[a.alg])return{valid:!1,error:"Key curve does not match algorithm",header:a,payload:s};var I=i+"."+n,R=Zh.createPublicKey({key:d,format:"jwk"}),k=Zh.verify("sha256",f.Buffer.from(I),{key:R,dsaEncoding:"ieee-p1363"},u);if(!k&&t.allowLegacyDER)try{k=Zh.verify("sha256",f.Buffer.from(I),{key:R,dsaEncoding:"der"},u)}catch{k=!1}return k?{valid:!0,header:a,payload:s}:{valid:!1,error:"Invalid signature",header:a,payload:s}}catch(q){return{valid:!1,error:q.message||"Verification failed"}}}w6.exports={issueVcJwt:eJ,verifyVcJwt:tJ,base64UrlEncode:gv,base64UrlDecode:mv,ALG_TO_CRV:$h}});var E6=T((yle,S6)=>{"use strict";g();function rJ(){this.input=null,this.next_in=0,this.avail_in=0,this.total_in=0,this.output=null,this.next_out=0,this.avail_out=0,this.total_out=0,this.msg="",this.state=null,this.data_type=2,this.adler=0}S6.exports=rJ});var Xh=T(Ti=>{"use strict";g();var iJ=typeof Uint8Array<"u"&&typeof Uint16Array<"u"&&typeof Int32Array<"u";function nJ(e,t){return Object.prototype.hasOwnProperty.call(e,t)}Ti.assign=function(e){for(var t=Array.prototype.slice.call(arguments,1);t.length;){var r=t.shift();if(r){if(typeof r!="object")throw new TypeError(r+"must be non-object");for(var i in r)nJ(r,i)&&(e[i]=r[i])}}return e};Ti.shrinkBuf=function(e,t){return e.length===t?e:e.subarray?e.subarray(0,t):(e.length=t,e)};var oJ={arraySet:function(e,t,r,i,n){if(t.subarray&&e.subarray){e.set(t.subarray(r,r+i),n);return}for(var o=0;o<i;o++)e[n+o]=t[r+o]},flattenChunks:function(e){var t,r,i,n,o,a;for(i=0,t=0,r=e.length;t<r;t++)i+=e[t].length;for(a=new Uint8Array(i),n=0,t=0,r=e.length;t<r;t++)o=e[t],a.set(o,n),n+=o.length;return a}},aJ={arraySet:function(e,t,r,i,n){for(var o=0;o<i;o++)e[n+o]=t[r+o]},flattenChunks:function(e){return[].concat.apply([],e)}};Ti.setTyped=function(e){e?(Ti.Buf8=Uint8Array,Ti.Buf16=Uint16Array,Ti.Buf32=Int32Array,Ti.assign(Ti,oJ)):(Ti.Buf8=Array,Ti.Buf16=Array,Ti.Buf32=Array,Ti.assign(Ti,aJ))};Ti.setTyped(iJ)});var G6=T(Tf=>{"use strict";g();var sJ=Xh(),uJ=4,x6=0,O6=1,cJ=2;function Af(e){for(var t=e.length;--t>=0;)e[t]=0}var fJ=0,k6=1,lJ=2,hJ=3,dJ=258,KS=29,id=256,Qh=id+1+KS,If=30,VS=19,B6=2*Qh+1,_u=15,HS=16,pJ=7,GS=256,N6=16,C6=17,L6=18,jS=[0,0,0,0,0,0,0,0,1,1,1,1,2,2,2,2,3,3,3,3,4,4,4,4,5,5,5,5,0],vv=[0,0,0,0,1,1,2,2,3,3,4,4,5,5,6,6,7,7,8,8,9,9,10,10,11,11,12,12,13,13],gJ=[0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,2,3,7],M6=[16,17,18,0,8,7,9,6,10,5,11,4,12,3,13,2,14,1,15],mJ=512,Aa=new Array((Qh+2)*2);Af(Aa);var Jh=new Array(If*2);Af(Jh);var ed=new Array(mJ);Af(ed);var td=new Array(dJ-hJ+1);Af(td);var WS=new Array(KS);Af(WS);var yv=new Array(If);Af(yv);function qS(e,t,r,i,n){this.static_tree=e,this.extra_bits=t,this.extra_base=r,this.elems=i,this.max_length=n,this.has_stree=e&&e.length}var D6,H6,q6;function US(e,t){this.dyn_tree=e,this.max_code=0,this.stat_desc=t}function U6(e){return e<256?ed[e]:ed[256+(e>>>7)]}function rd(e,t){e.pending_buf[e.pending++]=t&255,e.pending_buf[e.pending++]=t>>>8&255}function Ui(e,t,r){e.bi_valid>HS-r?(e.bi_buf|=t<<e.bi_valid&65535,rd(e,e.bi_buf),e.bi_buf=t>>HS-e.bi_valid,e.bi_valid+=r-HS):(e.bi_buf|=t<<e.bi_valid&65535,e.bi_valid+=r)}function Co(e,t,r){Ui(e,r[t*2],r[t*2+1])}function F6(e,t){var r=0;do r|=e&1,e>>>=1,r<<=1;while(--t>0);return r>>>1}function vJ(e){e.bi_valid===16?(rd(e,e.bi_buf),e.bi_buf=0,e.bi_valid=0):e.bi_valid>=8&&(e.pending_buf[e.pending++]=e.bi_buf&255,e.bi_buf>>=8,e.bi_valid-=8)}function yJ(e,t){var r=t.dyn_tree,i=t.max_code,n=t.stat_desc.static_tree,o=t.stat_desc.has_stree,a=t.stat_desc.extra_bits,s=t.stat_desc.extra_base,u=t.stat_desc.max_length,c,l,p,d,v,_,I=0;for(d=0;d<=_u;d++)e.bl_count[d]=0;for(r[e.heap[e.heap_max]*2+1]=0,c=e.heap_max+1;c<B6;c++)l=e.heap[c],d=r[r[l*2+1]*2+1]+1,d>u&&(d=u,I++),r[l*2+1]=d,!(l>i)&&(e.bl_count[d]++,v=0,l>=s&&(v=a[l-s]),_=r[l*2],e.opt_len+=_*(d+v),o&&(e.static_len+=_*(n[l*2+1]+v)));if(I!==0){do{for(d=u-1;e.bl_count[d]===0;)d--;e.bl_count[d]--,e.bl_count[d+1]+=2,e.bl_count[u]--,I-=2}while(I>0);for(d=u;d!==0;d--)for(l=e.bl_count[d];l!==0;)p=e.heap[--c],!(p>i)&&(r[p*2+1]!==d&&(e.opt_len+=(d-r[p*2+1])*r[p*2],r[p*2+1]=d),l--)}}function j6(e,t,r){var i=new Array(_u+1),n=0,o,a;for(o=1;o<=_u;o++)i[o]=n=n+r[o-1]<<1;for(a=0;a<=t;a++){var s=e[a*2+1];s!==0&&(e[a*2]=F6(i[s]++,s))}}function bJ(){var e,t,r,i,n,o=new Array(_u+1);for(r=0,i=0;i<KS-1;i++)for(WS[i]=r,e=0;e<1<<jS[i];e++)td[r++]=i;for(td[r-1]=i,n=0,i=0;i<16;i++)for(yv[i]=n,e=0;e<1<<vv[i];e++)ed[n++]=i;for(n>>=7;i<If;i++)for(yv[i]=n<<7,e=0;e<1<<vv[i]-7;e++)ed[256+n++]=i;for(t=0;t<=_u;t++)o[t]=0;for(e=0;e<=143;)Aa[e*2+1]=8,e++,o[8]++;for(;e<=255;)Aa[e*2+1]=9,e++,o[9]++;for(;e<=279;)Aa[e*2+1]=7,e++,o[7]++;for(;e<=287;)Aa[e*2+1]=8,e++,o[8]++;for(j6(Aa,Qh+1,o),e=0;e<If;e++)Jh[e*2+1]=5,Jh[e*2]=F6(e,5);D6=new qS(Aa,jS,id+1,Qh,_u),H6=new qS(Jh,vv,0,If,_u),q6=new qS(new Array(0),gJ,0,VS,pJ)}function z6(e){var t;for(t=0;t<Qh;t++)e.dyn_ltree[t*2]=0;for(t=0;t<If;t++)e.dyn_dtree[t*2]=0;for(t=0;t<VS;t++)e.bl_tree[t*2]=0;e.dyn_ltree[GS*2]=1,e.opt_len=e.static_len=0,e.last_lit=e.matches=0}function K6(e){e.bi_valid>8?rd(e,e.bi_buf):e.bi_valid>0&&(e.pending_buf[e.pending++]=e.bi_buf),e.bi_buf=0,e.bi_valid=0}function _J(e,t,r,i){K6(e),i&&(rd(e,r),rd(e,~r)),sJ.arraySet(e.pending_buf,e.window,t,r,e.pending),e.pending+=r}function I6(e,t,r,i){var n=t*2,o=r*2;return e[n]<e[o]||e[n]===e[o]&&i[t]<=i[r]}function FS(e,t,r){for(var i=e.heap[r],n=r<<1;n<=e.heap_len&&(n<e.heap_len&&I6(t,e.heap[n+1],e.heap[n],e.depth)&&n++,!I6(t,i,e.heap[n],e.depth));)e.heap[r]=e.heap[n],r=n,n<<=1;e.heap[r]=i}function A6(e,t,r){var i,n,o=0,a,s;if(e.last_lit!==0)do i=e.pending_buf[e.d_buf+o*2]<<8|e.pending_buf[e.d_buf+o*2+1],n=e.pending_buf[e.l_buf+o],o++,i===0?Co(e,n,t):(a=td[n],Co(e,a+id+1,t),s=jS[a],s!==0&&(n-=WS[a],Ui(e,n,s)),i--,a=U6(i),Co(e,a,r),s=vv[a],s!==0&&(i-=yv[a],Ui(e,i,s)));while(o<e.last_lit);Co(e,GS,t)}function zS(e,t){var r=t.dyn_tree,i=t.stat_desc.static_tree,n=t.stat_desc.has_stree,o=t.stat_desc.elems,a,s,u=-1,c;for(e.heap_len=0,e.heap_max=B6,a=0;a<o;a++)r[a*2]!==0?(e.heap[++e.heap_len]=u=a,e.depth[a]=0):r[a*2+1]=0;for(;e.heap_len<2;)c=e.heap[++e.heap_len]=u<2?++u:0,r[c*2]=1,e.depth[c]=0,e.opt_len--,n&&(e.static_len-=i[c*2+1]);for(t.max_code=u,a=e.heap_len>>1;a>=1;a--)FS(e,r,a);c=o;do a=e.heap[1],e.heap[1]=e.heap[e.heap_len--],FS(e,r,1),s=e.heap[1],e.heap[--e.heap_max]=a,e.heap[--e.heap_max]=s,r[c*2]=r[a*2]+r[s*2],e.depth[c]=(e.depth[a]>=e.depth[s]?e.depth[a]:e.depth[s])+1,r[a*2+1]=r[s*2+1]=c,e.heap[1]=c++,FS(e,r,1);while(e.heap_len>=2);e.heap[--e.heap_max]=e.heap[1],yJ(e,t),j6(r,u,e.bl_count)}function T6(e,t,r){var i,n=-1,o,a=t[1],s=0,u=7,c=4;for(a===0&&(u=138,c=3),t[(r+1)*2+1]=65535,i=0;i<=r;i++)o=a,a=t[(i+1)*2+1],!(++s<u&&o===a)&&(s<c?e.bl_tree[o*2]+=s:o!==0?(o!==n&&e.bl_tree[o*2]++,e.bl_tree[N6*2]++):s<=10?e.bl_tree[C6*2]++:e.bl_tree[L6*2]++,s=0,n=o,a===0?(u=138,c=3):o===a?(u=6,c=3):(u=7,c=4))}function P6(e,t,r){var i,n=-1,o,a=t[1],s=0,u=7,c=4;for(a===0&&(u=138,c=3),i=0;i<=r;i++)if(o=a,a=t[(i+1)*2+1],!(++s<u&&o===a)){if(s<c)do Co(e,o,e.bl_tree);while(--s!==0);else o!==0?(o!==n&&(Co(e,o,e.bl_tree),s--),Co(e,N6,e.bl_tree),Ui(e,s-3,2)):s<=10?(Co(e,C6,e.bl_tree),Ui(e,s-3,3)):(Co(e,L6,e.bl_tree),Ui(e,s-11,7));s=0,n=o,a===0?(u=138,c=3):o===a?(u=6,c=3):(u=7,c=4)}}function wJ(e){var t;for(T6(e,e.dyn_ltree,e.l_desc.max_code),T6(e,e.dyn_dtree,e.d_desc.max_code),zS(e,e.bl_desc),t=VS-1;t>=3&&e.bl_tree[M6[t]*2+1]===0;t--);return e.opt_len+=3*(t+1)+5+5+4,t}function SJ(e,t,r,i){var n;for(Ui(e,t-257,5),Ui(e,r-1,5),Ui(e,i-4,4),n=0;n<i;n++)Ui(e,e.bl_tree[M6[n]*2+1],3);P6(e,e.dyn_ltree,t-1),P6(e,e.dyn_dtree,r-1)}function EJ(e){var t=4093624447,r;for(r=0;r<=31;r++,t>>>=1)if(t&1&&e.dyn_ltree[r*2]!==0)return x6;if(e.dyn_ltree[18]!==0||e.dyn_ltree[20]!==0||e.dyn_ltree[26]!==0)return O6;for(r=32;r<id;r++)if(e.dyn_ltree[r*2]!==0)return O6;return x6}var R6=!1;function xJ(e){R6||(bJ(),R6=!0),e.l_desc=new US(e.dyn_ltree,D6),e.d_desc=new US(e.dyn_dtree,H6),e.bl_desc=new US(e.bl_tree,q6),e.bi_buf=0,e.bi_valid=0,z6(e)}function V6(e,t,r,i){Ui(e,(fJ<<1)+(i?1:0),3),_J(e,t,r,!0)}function OJ(e){Ui(e,k6<<1,3),Co(e,GS,Aa),vJ(e)}function IJ(e,t,r,i){var n,o,a=0;e.level>0?(e.strm.data_type===cJ&&(e.strm.data_type=EJ(e)),zS(e,e.l_desc),zS(e,e.d_desc),a=wJ(e),n=e.opt_len+3+7>>>3,o=e.static_len+3+7>>>3,o<=n&&(n=o)):n=o=r+5,r+4<=n&&t!==-1?V6(e,t,r,i):e.strategy===uJ||o===n?(Ui(e,(k6<<1)+(i?1:0),3),A6(e,Aa,Jh)):(Ui(e,(lJ<<1)+(i?1:0),3),SJ(e,e.l_desc.max_code+1,e.d_desc.max_code+1,a+1),A6(e,e.dyn_ltree,e.dyn_dtree)),z6(e),i&&K6(e)}function AJ(e,t,r){return e.pending_buf[e.d_buf+e.last_lit*2]=t>>>8&255,e.pending_buf[e.d_buf+e.last_lit*2+1]=t&255,e.pending_buf[e.l_buf+e.last_lit]=r&255,e.last_lit++,t===0?e.dyn_ltree[r*2]++:(e.matches++,t--,e.dyn_ltree[(td[r]+id+1)*2]++,e.dyn_dtree[U6(t)*2]++),e.last_lit===e.lit_bufsize-1}Tf._tr_init=xJ;Tf._tr_stored_block=V6;Tf._tr_flush_block=IJ;Tf._tr_tally=AJ;Tf._tr_align=OJ});var YS=T((xle,W6)=>{"use strict";g();function TJ(e,t,r,i){for(var n=e&65535|0,o=e>>>16&65535|0,a=0;r!==0;){a=r>2e3?2e3:r,r-=a;do n=n+t[i++]|0,o=o+n|0;while(--a);n%=65521,o%=65521}return n|o<<16|0}W6.exports=TJ});var ZS=T((Ile,Y6)=>{"use strict";g();function PJ(){for(var e,t=[],r=0;r<256;r++){e=r;for(var i=0;i<8;i++)e=e&1?3988292384^e>>>1:e>>>1;t[r]=e}return t}var RJ=PJ();function kJ(e,t,r,i){var n=RJ,o=i+r;e^=-1;for(var a=i;a<o;a++)e=e>>>8^n[(e^t[a])&255];return e^-1}Y6.exports=kJ});var $6=T((Tle,Z6)=>{"use strict";g();Z6.exports={2:"need dictionary",1:"stream end",0:"","-1":"file error","-2":"stream error","-3":"data error","-4":"insufficient memory","-5":"buffer error","-6":"incompatible version"}});var o3=T(Do=>{"use strict";g();var Pi=Xh(),_n=G6(),e3=YS(),_s=ZS(),BJ=$6(),xu=0,NJ=1,CJ=3,Os=4,X6=5,Mo=0,J6=1,wn=-2,LJ=-3,$S=-5,MJ=-1,DJ=1,bv=2,HJ=3,qJ=4,UJ=0,FJ=2,Ev=8,jJ=9,zJ=15,KJ=8,VJ=29,GJ=256,JS=GJ+1+VJ,WJ=30,YJ=19,ZJ=2*JS+1,$J=15,ct=3,Es=258,Vn=Es+ct+1,XJ=32,xv=42,QS=69,_v=73,wv=91,Sv=103,wu=113,od=666,Gr=1,ad=2,Su=3,kf=4,JJ=3;function xs(e,t){return e.msg=BJ[t],t}function Q6(e){return(e<<1)-(e>4?9:0)}function Ss(e){for(var t=e.length;--t>=0;)e[t]=0}function ws(e){var t=e.state,r=t.pending;r>e.avail_out&&(r=e.avail_out),r!==0&&(Pi.arraySet(e.output,t.pending_buf,t.pending_out,r,e.next_out),e.next_out+=r,t.pending_out+=r,e.total_out+=r,e.avail_out-=r,t.pending-=r,t.pending===0&&(t.pending_out=0))}function si(e,t){_n._tr_flush_block(e,e.block_start>=0?e.block_start:-1,e.strstart-e.block_start,t),e.block_start=e.strstart,ws(e.strm)}function mt(e,t){e.pending_buf[e.pending++]=t}function nd(e,t){e.pending_buf[e.pending++]=t>>>8&255,e.pending_buf[e.pending++]=t&255}function QJ(e,t,r,i){var n=e.avail_in;return n>i&&(n=i),n===0?0:(e.avail_in-=n,Pi.arraySet(t,e.input,e.next_in,n,r),e.state.wrap===1?e.adler=e3(e.adler,t,n,r):e.state.wrap===2&&(e.adler=_s(e.adler,t,n,r)),e.next_in+=n,e.total_in+=n,n)}function t3(e,t){var r=e.max_chain_length,i=e.strstart,n,o,a=e.prev_length,s=e.nice_match,u=e.strstart>e.w_size-Vn?e.strstart-(e.w_size-Vn):0,c=e.window,l=e.w_mask,p=e.prev,d=e.strstart+Es,v=c[i+a-1],_=c[i+a];e.prev_length>=e.good_match&&(r>>=2),s>e.lookahead&&(s=e.lookahead);do if(n=t,!(c[n+a]!==_||c[n+a-1]!==v||c[n]!==c[i]||c[++n]!==c[i+1])){i+=2,n++;do;while(c[++i]===c[++n]&&c[++i]===c[++n]&&c[++i]===c[++n]&&c[++i]===c[++n]&&c[++i]===c[++n]&&c[++i]===c[++n]&&c[++i]===c[++n]&&c[++i]===c[++n]&&i<d);if(o=Es-(d-i),i=d-Es,o>a){if(e.match_start=t,a=o,o>=s)break;v=c[i+a-1],_=c[i+a]}}while((t=p[t&l])>u&&--r!==0);return a<=e.lookahead?a:e.lookahead}function Eu(e){var t=e.w_size,r,i,n,o,a;do{if(o=e.window_size-e.lookahead-e.strstart,e.strstart>=t+(t-Vn)){Pi.arraySet(e.window,e.window,t,t,0),e.match_start-=t,e.strstart-=t,e.block_start-=t,i=e.hash_size,r=i;do n=e.head[--r],e.head[r]=n>=t?n-t:0;while(--i);i=t,r=i;do n=e.prev[--r],e.prev[r]=n>=t?n-t:0;while(--i);o+=t}if(e.strm.avail_in===0)break;if(i=QJ(e.strm,e.window,e.strstart+e.lookahead,o),e.lookahead+=i,e.lookahead+e.insert>=ct)for(a=e.strstart-e.insert,e.ins_h=e.window[a],e.ins_h=(e.ins_h<<e.hash_shift^e.window[a+1])&e.hash_mask;e.insert&&(e.ins_h=(e.ins_h<<e.hash_shift^e.window[a+ct-1])&e.hash_mask,e.prev[a&e.w_mask]=e.head[e.ins_h],e.head[e.ins_h]=a,a++,e.insert--,!(e.lookahead+e.insert<ct)););}while(e.lookahead<Vn&&e.strm.avail_in!==0)}function eQ(e,t){var r=65535;for(r>e.pending_buf_size-5&&(r=e.pending_buf_size-5);;){if(e.lookahead<=1){if(Eu(e),e.lookahead===0&&t===xu)return Gr;if(e.lookahead===0)break}e.strstart+=e.lookahead,e.lookahead=0;var i=e.block_start+r;if((e.strstart===0||e.strstart>=i)&&(e.lookahead=e.strstart-i,e.strstart=i,si(e,!1),e.strm.avail_out===0)||e.strstart-e.block_start>=e.w_size-Vn&&(si(e,!1),e.strm.avail_out===0))return Gr}return e.insert=0,t===Os?(si(e,!0),e.strm.avail_out===0?Su:kf):(e.strstart>e.block_start&&(si(e,!1),e.strm.avail_out===0),Gr)}function XS(e,t){for(var r,i;;){if(e.lookahead<Vn){if(Eu(e),e.lookahead<Vn&&t===xu)return Gr;if(e.lookahead===0)break}if(r=0,e.lookahead>=ct&&(e.ins_h=(e.ins_h<<e.hash_shift^e.window[e.strstart+ct-1])&e.hash_mask,r=e.prev[e.strstart&e.w_mask]=e.head[e.ins_h],e.head[e.ins_h]=e.strstart),r!==0&&e.strstart-r<=e.w_size-Vn&&(e.match_length=t3(e,r)),e.match_length>=ct)if(i=_n._tr_tally(e,e.strstart-e.match_start,e.match_length-ct),e.lookahead-=e.match_length,e.match_length<=e.max_lazy_match&&e.lookahead>=ct){e.match_length--;do e.strstart++,e.ins_h=(e.ins_h<<e.hash_shift^e.window[e.strstart+ct-1])&e.hash_mask,r=e.prev[e.strstart&e.w_mask]=e.head[e.ins_h],e.head[e.ins_h]=e.strstart;while(--e.match_length!==0);e.strstart++}else e.strstart+=e.match_length,e.match_length=0,e.ins_h=e.window[e.strstart],e.ins_h=(e.ins_h<<e.hash_shift^e.window[e.strstart+1])&e.hash_mask;else i=_n._tr_tally(e,0,e.window[e.strstart]),e.lookahead--,e.strstart++;if(i&&(si(e,!1),e.strm.avail_out===0))return Gr}return e.insert=e.strstart<ct-1?e.strstart:ct-1,t===Os?(si(e,!0),e.strm.avail_out===0?Su:kf):e.last_lit&&(si(e,!1),e.strm.avail_out===0)?Gr:ad}function Pf(e,t){for(var r,i,n;;){if(e.lookahead<Vn){if(Eu(e),e.lookahead<Vn&&t===xu)return Gr;if(e.lookahead===0)break}if(r=0,e.lookahead>=ct&&(e.ins_h=(e.ins_h<<e.hash_shift^e.window[e.strstart+ct-1])&e.hash_mask,r=e.prev[e.strstart&e.w_mask]=e.head[e.ins_h],e.head[e.ins_h]=e.strstart),e.prev_length=e.match_length,e.prev_match=e.match_start,e.match_length=ct-1,r!==0&&e.prev_length<e.max_lazy_match&&e.strstart-r<=e.w_size-Vn&&(e.match_length=t3(e,r),e.match_length<=5&&(e.strategy===DJ||e.match_length===ct&&e.strstart-e.match_start>4096)&&(e.match_length=ct-1)),e.prev_length>=ct&&e.match_length<=e.prev_length){n=e.strstart+e.lookahead-ct,i=_n._tr_tally(e,e.strstart-1-e.prev_match,e.prev_length-ct),e.lookahead-=e.prev_length-1,e.prev_length-=2;do++e.strstart<=n&&(e.ins_h=(e.ins_h<<e.hash_shift^e.window[e.strstart+ct-1])&e.hash_mask,r=e.prev[e.strstart&e.w_mask]=e.head[e.ins_h],e.head[e.ins_h]=e.strstart);while(--e.prev_length!==0);if(e.match_available=0,e.match_length=ct-1,e.strstart++,i&&(si(e,!1),e.strm.avail_out===0))return Gr}else if(e.match_available){if(i=_n._tr_tally(e,0,e.window[e.strstart-1]),i&&si(e,!1),e.strstart++,e.lookahead--,e.strm.avail_out===0)return Gr}else e.match_available=1,e.strstart++,e.lookahead--}return e.match_available&&(i=_n._tr_tally(e,0,e.window[e.strstart-1]),e.match_available=0),e.insert=e.strstart<ct-1?e.strstart:ct-1,t===Os?(si(e,!0),e.strm.avail_out===0?Su:kf):e.last_lit&&(si(e,!1),e.strm.avail_out===0)?Gr:ad}function tQ(e,t){for(var r,i,n,o,a=e.window;;){if(e.lookahead<=Es){if(Eu(e),e.lookahead<=Es&&t===xu)return Gr;if(e.lookahead===0)break}if(e.match_length=0,e.lookahead>=ct&&e.strstart>0&&(n=e.strstart-1,i=a[n],i===a[++n]&&i===a[++n]&&i===a[++n])){o=e.strstart+Es;do;while(i===a[++n]&&i===a[++n]&&i===a[++n]&&i===a[++n]&&i===a[++n]&&i===a[++n]&&i===a[++n]&&i===a[++n]&&n<o);e.match_length=Es-(o-n),e.match_length>e.lookahead&&(e.match_length=e.lookahead)}if(e.match_length>=ct?(r=_n._tr_tally(e,1,e.match_length-ct),e.lookahead-=e.match_length,e.strstart+=e.match_length,e.match_length=0):(r=_n._tr_tally(e,0,e.window[e.strstart]),e.lookahead--,e.strstart++),r&&(si(e,!1),e.strm.avail_out===0))return Gr}return e.insert=0,t===Os?(si(e,!0),e.strm.avail_out===0?Su:kf):e.last_lit&&(si(e,!1),e.strm.avail_out===0)?Gr:ad}function rQ(e,t){for(var r;;){if(e.lookahead===0&&(Eu(e),e.lookahead===0)){if(t===xu)return Gr;break}if(e.match_length=0,r=_n._tr_tally(e,0,e.window[e.strstart]),e.lookahead--,e.strstart++,r&&(si(e,!1),e.strm.avail_out===0))return Gr}return e.insert=0,t===Os?(si(e,!0),e.strm.avail_out===0?Su:kf):e.last_lit&&(si(e,!1),e.strm.avail_out===0)?Gr:ad}function Lo(e,t,r,i,n){this.good_length=e,this.max_lazy=t,this.nice_length=r,this.max_chain=i,this.func=n}var Rf;Rf=[new Lo(0,0,0,0,eQ),new Lo(4,4,8,4,XS),new Lo(4,5,16,8,XS),new Lo(4,6,32,32,XS),new Lo(4,4,16,16,Pf),new Lo(8,16,32,32,Pf),new Lo(8,16,128,128,Pf),new Lo(8,32,128,256,Pf),new Lo(32,128,258,1024,Pf),new Lo(32,258,258,4096,Pf)];function iQ(e){e.window_size=2*e.w_size,Ss(e.head),e.max_lazy_match=Rf[e.level].max_lazy,e.good_match=Rf[e.level].good_length,e.nice_match=Rf[e.level].nice_length,e.max_chain_length=Rf[e.level].max_chain,e.strstart=0,e.block_start=0,e.lookahead=0,e.insert=0,e.match_length=e.prev_length=ct-1,e.match_available=0,e.ins_h=0}function nQ(){this.strm=null,this.status=0,this.pending_buf=null,this.pending_buf_size=0,this.pending_out=0,this.pending=0,this.wrap=0,this.gzhead=null,this.gzindex=0,this.method=Ev,this.last_flush=-1,this.w_size=0,this.w_bits=0,this.w_mask=0,this.window=null,this.window_size=0,this.prev=null,this.head=null,this.ins_h=0,this.hash_size=0,this.hash_bits=0,this.hash_mask=0,this.hash_shift=0,this.block_start=0,this.match_length=0,this.prev_match=0,this.match_available=0,this.strstart=0,this.match_start=0,this.lookahead=0,this.prev_length=0,this.max_chain_length=0,this.max_lazy_match=0,this.level=0,this.strategy=0,this.good_match=0,this.nice_match=0,this.dyn_ltree=new Pi.Buf16(ZJ*2),this.dyn_dtree=new Pi.Buf16((2*WJ+1)*2),this.bl_tree=new Pi.Buf16((2*YJ+1)*2),Ss(this.dyn_ltree),Ss(this.dyn_dtree),Ss(this.bl_tree),this.l_desc=null,this.d_desc=null,this.bl_desc=null,this.bl_count=new Pi.Buf16($J+1),this.heap=new Pi.Buf16(2*JS+1),Ss(this.heap),this.heap_len=0,this.heap_max=0,this.depth=new Pi.Buf16(2*JS+1),Ss(this.depth),this.l_buf=0,this.lit_bufsize=0,this.last_lit=0,this.d_buf=0,this.opt_len=0,this.static_len=0,this.matches=0,this.insert=0,this.bi_buf=0,this.bi_valid=0}function r3(e){var t;return!e||!e.state?xs(e,wn):(e.total_in=e.total_out=0,e.data_type=FJ,t=e.state,t.pending=0,t.pending_out=0,t.wrap<0&&(t.wrap=-t.wrap),t.status=t.wrap?xv:wu,e.adler=t.wrap===2?0:1,t.last_flush=xu,_n._tr_init(t),Mo)}function i3(e){var t=r3(e);return t===Mo&&iQ(e.state),t}function oQ(e,t){return!e||!e.state||e.state.wrap!==2?wn:(e.state.gzhead=t,Mo)}function n3(e,t,r,i,n,o){if(!e)return wn;var a=1;if(t===MJ&&(t=6),i<0?(a=0,i=-i):i>15&&(a=2,i-=16),n<1||n>jJ||r!==Ev||i<8||i>15||t<0||t>9||o<0||o>qJ)return xs(e,wn);i===8&&(i=9);var s=new nQ;return e.state=s,s.strm=e,s.wrap=a,s.gzhead=null,s.w_bits=i,s.w_size=1<<s.w_bits,s.w_mask=s.w_size-1,s.hash_bits=n+7,s.hash_size=1<<s.hash_bits,s.hash_mask=s.hash_size-1,s.hash_shift=~~((s.hash_bits+ct-1)/ct),s.window=new Pi.Buf8(s.w_size*2),s.head=new Pi.Buf16(s.hash_size),s.prev=new Pi.Buf16(s.w_size),s.lit_bufsize=1<<n+6,s.pending_buf_size=s.lit_bufsize*4,s.pending_buf=new Pi.Buf8(s.pending_buf_size),s.d_buf=1*s.lit_bufsize,s.l_buf=3*s.lit_bufsize,s.level=t,s.strategy=o,s.method=r,i3(e)}function aQ(e,t){return n3(e,t,Ev,zJ,KJ,UJ)}function sQ(e,t){var r,i,n,o;if(!e||!e.state||t>X6||t<0)return e?xs(e,wn):wn;if(i=e.state,!e.output||!e.input&&e.avail_in!==0||i.status===od&&t!==Os)return xs(e,e.avail_out===0?$S:wn);if(i.strm=e,r=i.last_flush,i.last_flush=t,i.status===xv)if(i.wrap===2)e.adler=0,mt(i,31),mt(i,139),mt(i,8),i.gzhead?(mt(i,(i.gzhead.text?1:0)+(i.gzhead.hcrc?2:0)+(i.gzhead.extra?4:0)+(i.gzhead.name?8:0)+(i.gzhead.comment?16:0)),mt(i,i.gzhead.time&255),mt(i,i.gzhead.time>>8&255),mt(i,i.gzhead.time>>16&255),mt(i,i.gzhead.time>>24&255),mt(i,i.level===9?2:i.strategy>=bv||i.level<2?4:0),mt(i,i.gzhead.os&255),i.gzhead.extra&&i.gzhead.extra.length&&(mt(i,i.gzhead.extra.length&255),mt(i,i.gzhead.extra.length>>8&255)),i.gzhead.hcrc&&(e.adler=_s(e.adler,i.pending_buf,i.pending,0)),i.gzindex=0,i.status=QS):(mt(i,0),mt(i,0),mt(i,0),mt(i,0),mt(i,0),mt(i,i.level===9?2:i.strategy>=bv||i.level<2?4:0),mt(i,JJ),i.status=wu);else{var a=Ev+(i.w_bits-8<<4)<<8,s=-1;i.strategy>=bv||i.level<2?s=0:i.level<6?s=1:i.level===6?s=2:s=3,a|=s<<6,i.strstart!==0&&(a|=XJ),a+=31-a%31,i.status=wu,nd(i,a),i.strstart!==0&&(nd(i,e.adler>>>16),nd(i,e.adler&65535)),e.adler=1}if(i.status===QS)if(i.gzhead.extra){for(n=i.pending;i.gzindex<(i.gzhead.extra.length&65535)&&!(i.pending===i.pending_buf_size&&(i.gzhead.hcrc&&i.pending>n&&(e.adler=_s(e.adler,i.pending_buf,i.pending-n,n)),ws(e),n=i.pending,i.pending===i.pending_buf_size));)mt(i,i.gzhead.extra[i.gzindex]&255),i.gzindex++;i.gzhead.hcrc&&i.pending>n&&(e.adler=_s(e.adler,i.pending_buf,i.pending-n,n)),i.gzindex===i.gzhead.extra.length&&(i.gzindex=0,i.status=_v)}else i.status=_v;if(i.status===_v)if(i.gzhead.name){n=i.pending;do{if(i.pending===i.pending_buf_size&&(i.gzhead.hcrc&&i.pending>n&&(e.adler=_s(e.adler,i.pending_buf,i.pending-n,n)),ws(e),n=i.pending,i.pending===i.pending_buf_size)){o=1;break}i.gzindex<i.gzhead.name.length?o=i.gzhead.name.charCodeAt(i.gzindex++)&255:o=0,mt(i,o)}while(o!==0);i.gzhead.hcrc&&i.pending>n&&(e.adler=_s(e.adler,i.pending_buf,i.pending-n,n)),o===0&&(i.gzindex=0,i.status=wv)}else i.status=wv;if(i.status===wv)if(i.gzhead.comment){n=i.pending;do{if(i.pending===i.pending_buf_size&&(i.gzhead.hcrc&&i.pending>n&&(e.adler=_s(e.adler,i.pending_buf,i.pending-n,n)),ws(e),n=i.pending,i.pending===i.pending_buf_size)){o=1;break}i.gzindex<i.gzhead.comment.length?o=i.gzhead.comment.charCodeAt(i.gzindex++)&255:o=0,mt(i,o)}while(o!==0);i.gzhead.hcrc&&i.pending>n&&(e.adler=_s(e.adler,i.pending_buf,i.pending-n,n)),o===0&&(i.status=Sv)}else i.status=Sv;if(i.status===Sv&&(i.gzhead.hcrc?(i.pending+2>i.pending_buf_size&&ws(e),i.pending+2<=i.pending_buf_size&&(mt(i,e.adler&255),mt(i,e.adler>>8&255),e.adler=0,i.status=wu)):i.status=wu),i.pending!==0){if(ws(e),e.avail_out===0)return i.last_flush=-1,Mo}else if(e.avail_in===0&&Q6(t)<=Q6(r)&&t!==Os)return xs(e,$S);if(i.status===od&&e.avail_in!==0)return xs(e,$S);if(e.avail_in!==0||i.lookahead!==0||t!==xu&&i.status!==od){var u=i.strategy===bv?rQ(i,t):i.strategy===HJ?tQ(i,t):Rf[i.level].func(i,t);if((u===Su||u===kf)&&(i.status=od),u===Gr||u===Su)return e.avail_out===0&&(i.last_flush=-1),Mo;if(u===ad&&(t===NJ?_n._tr_align(i):t!==X6&&(_n._tr_stored_block(i,0,0,!1),t===CJ&&(Ss(i.head),i.lookahead===0&&(i.strstart=0,i.block_start=0,i.insert=0))),ws(e),e.avail_out===0))return i.last_flush=-1,Mo}return t!==Os?Mo:i.wrap<=0?J6:(i.wrap===2?(mt(i,e.adler&255),mt(i,e.adler>>8&255),mt(i,e.adler>>16&255),mt(i,e.adler>>24&255),mt(i,e.total_in&255),mt(i,e.total_in>>8&255),mt(i,e.total_in>>16&255),mt(i,e.total_in>>24&255)):(nd(i,e.adler>>>16),nd(i,e.adler&65535)),ws(e),i.wrap>0&&(i.wrap=-i.wrap),i.pending!==0?Mo:J6)}function uQ(e){var t;return!e||!e.state?wn:(t=e.state.status,t!==xv&&t!==QS&&t!==_v&&t!==wv&&t!==Sv&&t!==wu&&t!==od?xs(e,wn):(e.state=null,t===wu?xs(e,LJ):Mo))}function cQ(e,t){var r=t.length,i,n,o,a,s,u,c,l;if(!e||!e.state||(i=e.state,a=i.wrap,a===2||a===1&&i.status!==xv||i.lookahead))return wn;for(a===1&&(e.adler=e3(e.adler,t,r,0)),i.wrap=0,r>=i.w_size&&(a===0&&(Ss(i.head),i.strstart=0,i.block_start=0,i.insert=0),l=new Pi.Buf8(i.w_size),Pi.arraySet(l,t,r-i.w_size,i.w_size,0),t=l,r=i.w_size),s=e.avail_in,u=e.next_in,c=e.input,e.avail_in=r,e.next_in=0,e.input=t,Eu(i);i.lookahead>=ct;){n=i.strstart,o=i.lookahead-(ct-1);do i.ins_h=(i.ins_h<<i.hash_shift^i.window[n+ct-1])&i.hash_mask,i.prev[n&i.w_mask]=i.head[i.ins_h],i.head[i.ins_h]=n,n++;while(--o);i.strstart=n,i.lookahead=ct-1,Eu(i)}return i.strstart+=i.lookahead,i.block_start=i.strstart,i.insert=i.lookahead,i.lookahead=0,i.match_length=i.prev_length=ct-1,i.match_available=0,e.next_in=u,e.input=c,e.avail_in=s,i.wrap=a,Mo}Do.deflateInit=aQ;Do.deflateInit2=n3;Do.deflateReset=i3;Do.deflateResetKeep=r3;Do.deflateSetHeader=oQ;Do.deflate=sQ;Do.deflateEnd=uQ;Do.deflateSetDictionary=cQ;Do.deflateInfo="pako deflate (from Nodeca project)"});var s3=T((Ble,a3)=>{"use strict";g();var Ov=30,fQ=12;a3.exports=function(t,r){var i,n,o,a,s,u,c,l,p,d,v,_,I,R,k,q,z,A,B,M,F,V,Y,E,h;i=t.state,n=t.next_in,E=t.input,o=n+(t.avail_in-5),a=t.next_out,h=t.output,s=a-(r-t.avail_out),u=a+(t.avail_out-257),c=i.dmax,l=i.wsize,p=i.whave,d=i.wnext,v=i.window,_=i.hold,I=i.bits,R=i.lencode,k=i.distcode,q=(1<<i.lenbits)-1,z=(1<<i.distbits)-1;e:do{I<15&&(_+=E[n++]<<I,I+=8,_+=E[n++]<<I,I+=8),A=R[_&q];t:for(;;){if(B=A>>>24,_>>>=B,I-=B,B=A>>>16&255,B===0)h[a++]=A&65535;else if(B&16){M=A&65535,B&=15,B&&(I<B&&(_+=E[n++]<<I,I+=8),M+=_&(1<<B)-1,_>>>=B,I-=B),I<15&&(_+=E[n++]<<I,I+=8,_+=E[n++]<<I,I+=8),A=k[_&z];r:for(;;){if(B=A>>>24,_>>>=B,I-=B,B=A>>>16&255,B&16){if(F=A&65535,B&=15,I<B&&(_+=E[n++]<<I,I+=8,I<B&&(_+=E[n++]<<I,I+=8)),F+=_&(1<<B)-1,F>c){t.msg="invalid distance too far back",i.mode=Ov;break e}if(_>>>=B,I-=B,B=a-s,F>B){if(B=F-B,B>p&&i.sane){t.msg="invalid distance too far back",i.mode=Ov;break e}if(V=0,Y=v,d===0){if(V+=l-B,B<M){M-=B;do h[a++]=v[V++];while(--B);V=a-F,Y=h}}else if(d<B){if(V+=l+d-B,B-=d,B<M){M-=B;do h[a++]=v[V++];while(--B);if(V=0,d<M){B=d,M-=B;do h[a++]=v[V++];while(--B);V=a-F,Y=h}}}else if(V+=d-B,B<M){M-=B;do h[a++]=v[V++];while(--B);V=a-F,Y=h}for(;M>2;)h[a++]=Y[V++],h[a++]=Y[V++],h[a++]=Y[V++],M-=3;M&&(h[a++]=Y[V++],M>1&&(h[a++]=Y[V++]))}else{V=a-F;do h[a++]=h[V++],h[a++]=h[V++],h[a++]=h[V++],M-=3;while(M>2);M&&(h[a++]=h[V++],M>1&&(h[a++]=h[V++]))}}else if((B&64)===0){A=k[(A&65535)+(_&(1<<B)-1)];continue r}else{t.msg="invalid distance code",i.mode=Ov;break e}break}}else if((B&64)===0){A=R[(A&65535)+(_&(1<<B)-1)];continue t}else if(B&32){i.mode=fQ;break e}else{t.msg="invalid literal/length code",i.mode=Ov;break e}break}}while(n<o&&a<u);M=I>>3,n-=M,I-=M<<3,_&=(1<<I)-1,t.next_in=n,t.next_out=a,t.avail_in=n<o?5+(o-n):5-(n-o),t.avail_out=a<u?257+(u-a):257-(a-u),i.hold=_,i.bits=I}});var p3=T((Cle,d3)=>{"use strict";g();var u3=Xh(),Bf=15,c3=852,f3=592,l3=0,eE=1,h3=2,lQ=[3,4,5,6,7,8,9,10,11,13,15,17,19,23,27,31,35,43,51,59,67,83,99,115,131,163,195,227,258,0,0],hQ=[16,16,16,16,16,16,16,16,17,17,17,17,18,18,18,18,19,19,19,19,20,20,20,20,21,21,21,21,16,72,78],dQ=[1,2,3,4,5,7,9,13,17,25,33,49,65,97,129,193,257,385,513,769,1025,1537,2049,3073,4097,6145,8193,12289,16385,24577,0,0],pQ=[16,16,16,16,17,17,18,18,19,19,20,20,21,21,22,22,23,23,24,24,25,25,26,26,27,27,28,28,29,29,64,64];d3.exports=function(t,r,i,n,o,a,s,u){var c=u.bits,l=0,p=0,d=0,v=0,_=0,I=0,R=0,k=0,q=0,z=0,A,B,M,F,V,Y=null,E=0,h,y=new u3.Buf16(Bf+1),w=new u3.Buf16(Bf+1),S=null,O=0,C,D,P;for(l=0;l<=Bf;l++)y[l]=0;for(p=0;p<n;p++)y[r[i+p]]++;for(_=c,v=Bf;v>=1&&y[v]===0;v--);if(_>v&&(_=v),v===0)return o[a++]=1<<24|64<<16|0,o[a++]=1<<24|64<<16|0,u.bits=1,0;for(d=1;d<v&&y[d]===0;d++);for(_<d&&(_=d),k=1,l=1;l<=Bf;l++)if(k<<=1,k-=y[l],k<0)return-1;if(k>0&&(t===l3||v!==1))return-1;for(w[1]=0,l=1;l<Bf;l++)w[l+1]=w[l]+y[l];for(p=0;p<n;p++)r[i+p]!==0&&(s[w[r[i+p]]++]=p);if(t===l3?(Y=S=s,h=19):t===eE?(Y=lQ,E-=257,S=hQ,O-=257,h=256):(Y=dQ,S=pQ,h=-1),z=0,p=0,l=d,V=a,I=_,R=0,M=-1,q=1<<_,F=q-1,t===eE&&q>c3||t===h3&&q>f3)return 1;for(;;){C=l-R,s[p]<h?(D=0,P=s[p]):s[p]>h?(D=S[O+s[p]],P=Y[E+s[p]]):(D=96,P=0),A=1<<l-R,B=1<<I,d=B;do B-=A,o[V+(z>>R)+B]=C<<24|D<<16|P|0;while(B!==0);for(A=1<<l-1;z&A;)A>>=1;if(A!==0?(z&=A-1,z+=A):z=0,p++,--y[l]===0){if(l===v)break;l=r[i+s[p]]}if(l>_&&(z&F)!==M){for(R===0&&(R=_),V+=d,I=l-R,k=1<<I;I+R<v&&(k-=y[I+R],!(k<=0));)I++,k<<=1;if(q+=1<<I,t===eE&&q>c3||t===h3&&q>f3)return 1;M=z&F,o[M]=_<<24|I<<16|V-a|0}}return z!==0&&(o[V+z]=l-R<<24|64<<16|0),u.bits=_,0}});var Z3=T(Gn=>{"use strict";g();var $i=Xh(),aE=YS(),Ho=ZS(),gQ=s3(),sd=p3(),mQ=0,U3=1,F3=2,g3=4,vQ=5,Iv=6,Ou=0,yQ=1,bQ=2,Sn=-2,j3=-3,sE=-4,_Q=-5,m3=8,z3=1,v3=2,y3=3,b3=4,_3=5,w3=6,S3=7,E3=8,x3=9,O3=10,Pv=11,Ta=12,tE=13,I3=14,rE=15,A3=16,T3=17,P3=18,R3=19,Av=20,Tv=21,k3=22,B3=23,N3=24,C3=25,L3=26,iE=27,M3=28,D3=29,Xt=30,uE=31,wQ=32,SQ=852,EQ=592,xQ=15,OQ=xQ;function H3(e){return(e>>>24&255)+(e>>>8&65280)+((e&65280)<<8)+((e&255)<<24)}function IQ(){this.mode=0,this.last=!1,this.wrap=0,this.havedict=!1,this.flags=0,this.dmax=0,this.check=0,this.total=0,this.head=null,this.wbits=0,this.wsize=0,this.whave=0,this.wnext=0,this.window=null,this.hold=0,this.bits=0,this.length=0,this.offset=0,this.extra=0,this.lencode=null,this.distcode=null,this.lenbits=0,this.distbits=0,this.ncode=0,this.nlen=0,this.ndist=0,this.have=0,this.next=null,this.lens=new $i.Buf16(320),this.work=new $i.Buf16(288),this.lendyn=null,this.distdyn=null,this.sane=0,this.back=0,this.was=0}function K3(e){var t;return!e||!e.state?Sn:(t=e.state,e.total_in=e.total_out=t.total=0,e.msg="",t.wrap&&(e.adler=t.wrap&1),t.mode=z3,t.last=0,t.havedict=0,t.dmax=32768,t.head=null,t.hold=0,t.bits=0,t.lencode=t.lendyn=new $i.Buf32(SQ),t.distcode=t.distdyn=new $i.Buf32(EQ),t.sane=1,t.back=-1,Ou)}function V3(e){var t;return!e||!e.state?Sn:(t=e.state,t.wsize=0,t.whave=0,t.wnext=0,K3(e))}function G3(e,t){var r,i;return!e||!e.state||(i=e.state,t<0?(r=0,t=-t):(r=(t>>4)+1,t<48&&(t&=15)),t&&(t<8||t>15))?Sn:(i.window!==null&&i.wbits!==t&&(i.window=null),i.wrap=r,i.wbits=t,V3(e))}function W3(e,t){var r,i;return e?(i=new IQ,e.state=i,i.window=null,r=G3(e,t),r!==Ou&&(e.state=null),r):Sn}function AQ(e){return W3(e,OQ)}var q3=!0,nE,oE;function TQ(e){if(q3){var t;for(nE=new $i.Buf32(512),oE=new $i.Buf32(32),t=0;t<144;)e.lens[t++]=8;for(;t<256;)e.lens[t++]=9;for(;t<280;)e.lens[t++]=7;for(;t<288;)e.lens[t++]=8;for(sd(U3,e.lens,0,288,nE,0,e.work,{bits:9}),t=0;t<32;)e.lens[t++]=5;sd(F3,e.lens,0,32,oE,0,e.work,{bits:5}),q3=!1}e.lencode=nE,e.lenbits=9,e.distcode=oE,e.distbits=5}function Y3(e,t,r,i){var n,o=e.state;return o.window===null&&(o.wsize=1<<o.wbits,o.wnext=0,o.whave=0,o.window=new $i.Buf8(o.wsize)),i>=o.wsize?($i.arraySet(o.window,t,r-o.wsize,o.wsize,0),o.wnext=0,o.whave=o.wsize):(n=o.wsize-o.wnext,n>i&&(n=i),$i.arraySet(o.window,t,r-i,n,o.wnext),i-=n,i?($i.arraySet(o.window,t,r-i,i,0),o.wnext=i,o.whave=o.wsize):(o.wnext+=n,o.wnext===o.wsize&&(o.wnext=0),o.whave<o.wsize&&(o.whave+=n))),0}function PQ(e,t){var r,i,n,o,a,s,u,c,l,p,d,v,_,I,R=0,k,q,z,A,B,M,F,V,Y=new $i.Buf8(4),E,h,y=[16,17,18,0,8,7,9,6,10,5,11,4,12,3,13,2,14,1,15];if(!e||!e.state||!e.output||!e.input&&e.avail_in!==0)return Sn;r=e.state,r.mode===Ta&&(r.mode=tE),a=e.next_out,n=e.output,u=e.avail_out,o=e.next_in,i=e.input,s=e.avail_in,c=r.hold,l=r.bits,p=s,d=u,V=Ou;e:for(;;)switch(r.mode){case z3:if(r.wrap===0){r.mode=tE;break}for(;l<16;){if(s===0)break e;s--,c+=i[o++]<<l,l+=8}if(r.wrap&2&&c===35615){r.check=0,Y[0]=c&255,Y[1]=c>>>8&255,r.check=Ho(r.check,Y,2,0),c=0,l=0,r.mode=v3;break}if(r.flags=0,r.head&&(r.head.done=!1),!(r.wrap&1)||(((c&255)<<8)+(c>>8))%31){e.msg="incorrect header check",r.mode=Xt;break}if((c&15)!==m3){e.msg="unknown compression method",r.mode=Xt;break}if(c>>>=4,l-=4,F=(c&15)+8,r.wbits===0)r.wbits=F;else if(F>r.wbits){e.msg="invalid window size",r.mode=Xt;break}r.dmax=1<<F,e.adler=r.check=1,r.mode=c&512?O3:Ta,c=0,l=0;break;case v3:for(;l<16;){if(s===0)break e;s--,c+=i[o++]<<l,l+=8}if(r.flags=c,(r.flags&255)!==m3){e.msg="unknown compression method",r.mode=Xt;break}if(r.flags&57344){e.msg="unknown header flags set",r.mode=Xt;break}r.head&&(r.head.text=c>>8&1),r.flags&512&&(Y[0]=c&255,Y[1]=c>>>8&255,r.check=Ho(r.check,Y,2,0)),c=0,l=0,r.mode=y3;case y3:for(;l<32;){if(s===0)break e;s--,c+=i[o++]<<l,l+=8}r.head&&(r.head.time=c),r.flags&512&&(Y[0]=c&255,Y[1]=c>>>8&255,Y[2]=c>>>16&255,Y[3]=c>>>24&255,r.check=Ho(r.check,Y,4,0)),c=0,l=0,r.mode=b3;case b3:for(;l<16;){if(s===0)break e;s--,c+=i[o++]<<l,l+=8}r.head&&(r.head.xflags=c&255,r.head.os=c>>8),r.flags&512&&(Y[0]=c&255,Y[1]=c>>>8&255,r.check=Ho(r.check,Y,2,0)),c=0,l=0,r.mode=_3;case _3:if(r.flags&1024){for(;l<16;){if(s===0)break e;s--,c+=i[o++]<<l,l+=8}r.length=c,r.head&&(r.head.extra_len=c),r.flags&512&&(Y[0]=c&255,Y[1]=c>>>8&255,r.check=Ho(r.check,Y,2,0)),c=0,l=0}else r.head&&(r.head.extra=null);r.mode=w3;case w3:if(r.flags&1024&&(v=r.length,v>s&&(v=s),v&&(r.head&&(F=r.head.extra_len-r.length,r.head.extra||(r.head.extra=new Array(r.head.extra_len)),$i.arraySet(r.head.extra,i,o,v,F)),r.flags&512&&(r.check=Ho(r.check,i,v,o)),s-=v,o+=v,r.length-=v),r.length))break e;r.length=0,r.mode=S3;case S3:if(r.flags&2048){if(s===0)break e;v=0;do F=i[o+v++],r.head&&F&&r.length<65536&&(r.head.name+=String.fromCharCode(F));while(F&&v<s);if(r.flags&512&&(r.check=Ho(r.check,i,v,o)),s-=v,o+=v,F)break e}else r.head&&(r.head.name=null);r.length=0,r.mode=E3;case E3:if(r.flags&4096){if(s===0)break e;v=0;do F=i[o+v++],r.head&&F&&r.length<65536&&(r.head.comment+=String.fromCharCode(F));while(F&&v<s);if(r.flags&512&&(r.check=Ho(r.check,i,v,o)),s-=v,o+=v,F)break e}else r.head&&(r.head.comment=null);r.mode=x3;case x3:if(r.flags&512){for(;l<16;){if(s===0)break e;s--,c+=i[o++]<<l,l+=8}if(c!==(r.check&65535)){e.msg="header crc mismatch",r.mode=Xt;break}c=0,l=0}r.head&&(r.head.hcrc=r.flags>>9&1,r.head.done=!0),e.adler=r.check=0,r.mode=Ta;break;case O3:for(;l<32;){if(s===0)break e;s--,c+=i[o++]<<l,l+=8}e.adler=r.check=H3(c),c=0,l=0,r.mode=Pv;case Pv:if(r.havedict===0)return e.next_out=a,e.avail_out=u,e.next_in=o,e.avail_in=s,r.hold=c,r.bits=l,bQ;e.adler=r.check=1,r.mode=Ta;case Ta:if(t===vQ||t===Iv)break e;case tE:if(r.last){c>>>=l&7,l-=l&7,r.mode=iE;break}for(;l<3;){if(s===0)break e;s--,c+=i[o++]<<l,l+=8}switch(r.last=c&1,c>>>=1,l-=1,c&3){case 0:r.mode=I3;break;case 1:if(TQ(r),r.mode=Av,t===Iv){c>>>=2,l-=2;break e}break;case 2:r.mode=T3;break;case 3:e.msg="invalid block type",r.mode=Xt}c>>>=2,l-=2;break;case I3:for(c>>>=l&7,l-=l&7;l<32;){if(s===0)break e;s--,c+=i[o++]<<l,l+=8}if((c&65535)!==(c>>>16^65535)){e.msg="invalid stored block lengths",r.mode=Xt;break}if(r.length=c&65535,c=0,l=0,r.mode=rE,t===Iv)break e;case rE:r.mode=A3;case A3:if(v=r.length,v){if(v>s&&(v=s),v>u&&(v=u),v===0)break e;$i.arraySet(n,i,o,v,a),s-=v,o+=v,u-=v,a+=v,r.length-=v;break}r.mode=Ta;break;case T3:for(;l<14;){if(s===0)break e;s--,c+=i[o++]<<l,l+=8}if(r.nlen=(c&31)+257,c>>>=5,l-=5,r.ndist=(c&31)+1,c>>>=5,l-=5,r.ncode=(c&15)+4,c>>>=4,l-=4,r.nlen>286||r.ndist>30){e.msg="too many length or distance symbols",r.mode=Xt;break}r.have=0,r.mode=P3;case P3:for(;r.have<r.ncode;){for(;l<3;){if(s===0)break e;s--,c+=i[o++]<<l,l+=8}r.lens[y[r.have++]]=c&7,c>>>=3,l-=3}for(;r.have<19;)r.lens[y[r.have++]]=0;if(r.lencode=r.lendyn,r.lenbits=7,E={bits:r.lenbits},V=sd(mQ,r.lens,0,19,r.lencode,0,r.work,E),r.lenbits=E.bits,V){e.msg="invalid code lengths set",r.mode=Xt;break}r.have=0,r.mode=R3;case R3:for(;r.have<r.nlen+r.ndist;){for(;R=r.lencode[c&(1<<r.lenbits)-1],k=R>>>24,q=R>>>16&255,z=R&65535,!(k<=l);){if(s===0)break e;s--,c+=i[o++]<<l,l+=8}if(z<16)c>>>=k,l-=k,r.lens[r.have++]=z;else{if(z===16){for(h=k+2;l<h;){if(s===0)break e;s--,c+=i[o++]<<l,l+=8}if(c>>>=k,l-=k,r.have===0){e.msg="invalid bit length repeat",r.mode=Xt;break}F=r.lens[r.have-1],v=3+(c&3),c>>>=2,l-=2}else if(z===17){for(h=k+3;l<h;){if(s===0)break e;s--,c+=i[o++]<<l,l+=8}c>>>=k,l-=k,F=0,v=3+(c&7),c>>>=3,l-=3}else{for(h=k+7;l<h;){if(s===0)break e;s--,c+=i[o++]<<l,l+=8}c>>>=k,l-=k,F=0,v=11+(c&127),c>>>=7,l-=7}if(r.have+v>r.nlen+r.ndist){e.msg="invalid bit length repeat",r.mode=Xt;break}for(;v--;)r.lens[r.have++]=F}}if(r.mode===Xt)break;if(r.lens[256]===0){e.msg="invalid code -- missing end-of-block",r.mode=Xt;break}if(r.lenbits=9,E={bits:r.lenbits},V=sd(U3,r.lens,0,r.nlen,r.lencode,0,r.work,E),r.lenbits=E.bits,V){e.msg="invalid literal/lengths set",r.mode=Xt;break}if(r.distbits=6,r.distcode=r.distdyn,E={bits:r.distbits},V=sd(F3,r.lens,r.nlen,r.ndist,r.distcode,0,r.work,E),r.distbits=E.bits,V){e.msg="invalid distances set",r.mode=Xt;break}if(r.mode=Av,t===Iv)break e;case Av:r.mode=Tv;case Tv:if(s>=6&&u>=258){e.next_out=a,e.avail_out=u,e.next_in=o,e.avail_in=s,r.hold=c,r.bits=l,gQ(e,d),a=e.next_out,n=e.output,u=e.avail_out,o=e.next_in,i=e.input,s=e.avail_in,c=r.hold,l=r.bits,r.mode===Ta&&(r.back=-1);break}for(r.back=0;R=r.lencode[c&(1<<r.lenbits)-1],k=R>>>24,q=R>>>16&255,z=R&65535,!(k<=l);){if(s===0)break e;s--,c+=i[o++]<<l,l+=8}if(q&&(q&240)===0){for(A=k,B=q,M=z;R=r.lencode[M+((c&(1<<A+B)-1)>>A)],k=R>>>24,q=R>>>16&255,z=R&65535,!(A+k<=l);){if(s===0)break e;s--,c+=i[o++]<<l,l+=8}c>>>=A,l-=A,r.back+=A}if(c>>>=k,l-=k,r.back+=k,r.length=z,q===0){r.mode=L3;break}if(q&32){r.back=-1,r.mode=Ta;break}if(q&64){e.msg="invalid literal/length code",r.mode=Xt;break}r.extra=q&15,r.mode=k3;case k3:if(r.extra){for(h=r.extra;l<h;){if(s===0)break e;s--,c+=i[o++]<<l,l+=8}r.length+=c&(1<<r.extra)-1,c>>>=r.extra,l-=r.extra,r.back+=r.extra}r.was=r.length,r.mode=B3;case B3:for(;R=r.distcode[c&(1<<r.distbits)-1],k=R>>>24,q=R>>>16&255,z=R&65535,!(k<=l);){if(s===0)break e;s--,c+=i[o++]<<l,l+=8}if((q&240)===0){for(A=k,B=q,M=z;R=r.distcode[M+((c&(1<<A+B)-1)>>A)],k=R>>>24,q=R>>>16&255,z=R&65535,!(A+k<=l);){if(s===0)break e;s--,c+=i[o++]<<l,l+=8}c>>>=A,l-=A,r.back+=A}if(c>>>=k,l-=k,r.back+=k,q&64){e.msg="invalid distance code",r.mode=Xt;break}r.offset=z,r.extra=q&15,r.mode=N3;case N3:if(r.extra){for(h=r.extra;l<h;){if(s===0)break e;s--,c+=i[o++]<<l,l+=8}r.offset+=c&(1<<r.extra)-1,c>>>=r.extra,l-=r.extra,r.back+=r.extra}if(r.offset>r.dmax){e.msg="invalid distance too far back",r.mode=Xt;break}r.mode=C3;case C3:if(u===0)break e;if(v=d-u,r.offset>v){if(v=r.offset-v,v>r.whave&&r.sane){e.msg="invalid distance too far back",r.mode=Xt;break}v>r.wnext?(v-=r.wnext,_=r.wsize-v):_=r.wnext-v,v>r.length&&(v=r.length),I=r.window}else I=n,_=a-r.offset,v=r.length;v>u&&(v=u),u-=v,r.length-=v;do n[a++]=I[_++];while(--v);r.length===0&&(r.mode=Tv);break;case L3:if(u===0)break e;n[a++]=r.length,u--,r.mode=Tv;break;case iE:if(r.wrap){for(;l<32;){if(s===0)break e;s--,c|=i[o++]<<l,l+=8}if(d-=u,e.total_out+=d,r.total+=d,d&&(e.adler=r.check=r.flags?Ho(r.check,n,d,a-d):aE(r.check,n,d,a-d)),d=u,(r.flags?c:H3(c))!==r.check){e.msg="incorrect data check",r.mode=Xt;break}c=0,l=0}r.mode=M3;case M3:if(r.wrap&&r.flags){for(;l<32;){if(s===0)break e;s--,c+=i[o++]<<l,l+=8}if(c!==(r.total&4294967295)){e.msg="incorrect length check",r.mode=Xt;break}c=0,l=0}r.mode=D3;case D3:V=yQ;break e;case Xt:V=j3;break e;case uE:return sE;case wQ:default:return Sn}return e.next_out=a,e.avail_out=u,e.next_in=o,e.avail_in=s,r.hold=c,r.bits=l,(r.wsize||d!==e.avail_out&&r.mode<Xt&&(r.mode<iE||t!==g3))&&Y3(e,e.output,e.next_out,d-e.avail_out)?(r.mode=uE,sE):(p-=e.avail_in,d-=e.avail_out,e.total_in+=p,e.total_out+=d,r.total+=d,r.wrap&&d&&(e.adler=r.check=r.flags?Ho(r.check,n,d,e.next_out-d):aE(r.check,n,d,e.next_out-d)),e.data_type=r.bits+(r.last?64:0)+(r.mode===Ta?128:0)+(r.mode===Av||r.mode===rE?256:0),(p===0&&d===0||t===g3)&&V===Ou&&(V=_Q),V)}function RQ(e){if(!e||!e.state)return Sn;var t=e.state;return t.window&&(t.window=null),e.state=null,Ou}function kQ(e,t){var r;return!e||!e.state||(r=e.state,(r.wrap&2)===0)?Sn:(r.head=t,t.done=!1,Ou)}function BQ(e,t){var r=t.length,i,n,o;return!e||!e.state||(i=e.state,i.wrap!==0&&i.mode!==Pv)?Sn:i.mode===Pv&&(n=1,n=aE(n,t,r,0),n!==i.check)?j3:(o=Y3(e,t,r,r),o?(i.mode=uE,sE):(i.havedict=1,Ou))}Gn.inflateReset=V3;Gn.inflateReset2=G3;Gn.inflateResetKeep=K3;Gn.inflateInit=AQ;Gn.inflateInit2=W3;Gn.inflate=PQ;Gn.inflateEnd=RQ;Gn.inflateGetHeader=kQ;Gn.inflateSetDictionary=BQ;Gn.inflateInfo="pako inflate (from Nodeca project)"});var X3=T((Hle,$3)=>{"use strict";g();$3.exports={Z_NO_FLUSH:0,Z_PARTIAL_FLUSH:1,Z_SYNC_FLUSH:2,Z_FULL_FLUSH:3,Z_FINISH:4,Z_BLOCK:5,Z_TREES:6,Z_OK:0,Z_STREAM_END:1,Z_NEED_DICT:2,Z_ERRNO:-1,Z_STREAM_ERROR:-2,Z_DATA_ERROR:-3,Z_BUF_ERROR:-5,Z_NO_COMPRESSION:0,Z_BEST_SPEED:1,Z_BEST_COMPRESSION:9,Z_DEFAULT_COMPRESSION:-1,Z_FILTERED:1,Z_HUFFMAN_ONLY:2,Z_RLE:3,Z_FIXED:4,Z_DEFAULT_STRATEGY:0,Z_BINARY:0,Z_TEXT:1,Z_UNKNOWN:2,Z_DEFLATED:8}});var Q3=T(fe=>{"use strict";g();var Xi=fa(),NQ=E6(),ud=o3(),Iu=Z3(),J3=X3();for(cE in J3)fe[cE]=J3[cE];var cE;fe.NONE=0;fe.DEFLATE=1;fe.INFLATE=2;fe.GZIP=3;fe.GUNZIP=4;fe.DEFLATERAW=5;fe.INFLATERAW=6;fe.UNZIP=7;var CQ=31,LQ=139;function _i(e){if(typeof e!="number"||e<fe.DEFLATE||e>fe.UNZIP)throw new TypeError("Bad argument");this.dictionary=null,this.err=0,this.flush=0,this.init_done=!1,this.level=0,this.memLevel=0,this.mode=e,this.strategy=0,this.windowBits=0,this.write_in_progress=!1,this.pending_close=!1,this.gzip_id_bytes_read=0}_i.prototype.close=function(){if(this.write_in_progress){this.pending_close=!0;return}this.pending_close=!1,Xi(this.init_done,"close before init"),Xi(this.mode<=fe.UNZIP),this.mode===fe.DEFLATE||this.mode===fe.GZIP||this.mode===fe.DEFLATERAW?ud.deflateEnd(this.strm):(this.mode===fe.INFLATE||this.mode===fe.GUNZIP||this.mode===fe.INFLATERAW||this.mode===fe.UNZIP)&&Iu.inflateEnd(this.strm),this.mode=fe.NONE,this.dictionary=null};_i.prototype.write=function(e,t,r,i,n,o,a){return this._write(!0,e,t,r,i,n,o,a)};_i.prototype.writeSync=function(e,t,r,i,n,o,a){return this._write(!1,e,t,r,i,n,o,a)};_i.prototype._write=function(e,t,r,i,n,o,a,s){if(Xi.equal(arguments.length,8),Xi(this.init_done,"write before init"),Xi(this.mode!==fe.NONE,"already finalized"),Xi.equal(!1,this.write_in_progress,"write already in progress"),Xi.equal(!1,this.pending_close,"close is pending"),this.write_in_progress=!0,Xi.equal(!1,t===void 0,"must provide flush value"),this.write_in_progress=!0,t!==fe.Z_NO_FLUSH&&t!==fe.Z_PARTIAL_FLUSH&&t!==fe.Z_SYNC_FLUSH&&t!==fe.Z_FULL_FLUSH&&t!==fe.Z_FINISH&&t!==fe.Z_BLOCK)throw new Error("Invalid flush value");if(r==null&&(r=f.Buffer.alloc(0),n=0,i=0),this.strm.avail_in=n,this.strm.input=r,this.strm.next_in=i,this.strm.avail_out=s,this.strm.output=o,this.strm.next_out=a,this.flush=t,!e)return this._process(),this._checkError()?this._afterSync():void 0;var u=this;return b.default.nextTick(function(){u._process(),u._after()}),this};_i.prototype._afterSync=function(){var e=this.strm.avail_out,t=this.strm.avail_in;return this.write_in_progress=!1,[t,e]};_i.prototype._process=function(){var e=null;switch(this.mode){case fe.DEFLATE:case fe.GZIP:case fe.DEFLATERAW:this.err=ud.deflate(this.strm,this.flush);break;case fe.UNZIP:switch(this.strm.avail_in>0&&(e=this.strm.next_in),this.gzip_id_bytes_read){case 0:if(e===null)break;if(this.strm.input[e]===CQ){if(this.gzip_id_bytes_read=1,e++,this.strm.avail_in===1)break}else{this.mode=fe.INFLATE;break}case 1:if(e===null)break;this.strm.input[e]===LQ?(this.gzip_id_bytes_read=2,this.mode=fe.GUNZIP):this.mode=fe.INFLATE;break;default:throw new Error("invalid number of gzip magic number bytes read")}case fe.INFLATE:case fe.GUNZIP:case fe.INFLATERAW:for(this.err=Iu.inflate(this.strm,this.flush),this.err===fe.Z_NEED_DICT&&this.dictionary&&(this.err=Iu.inflateSetDictionary(this.strm,this.dictionary),this.err===fe.Z_OK?this.err=Iu.inflate(this.strm,this.flush):this.err===fe.Z_DATA_ERROR&&(this.err=fe.Z_NEED_DICT));this.strm.avail_in>0&&this.mode===fe.GUNZIP&&this.err===fe.Z_STREAM_END&&this.strm.next_in[0]!==0;)this.reset(),this.err=Iu.inflate(this.strm,this.flush);break;default:throw new Error("Unknown mode "+this.mode)}};_i.prototype._checkError=function(){switch(this.err){case fe.Z_OK:case fe.Z_BUF_ERROR:if(this.strm.avail_out!==0&&this.flush===fe.Z_FINISH)return this._error("unexpected end of file"),!1;break;case fe.Z_STREAM_END:break;case fe.Z_NEED_DICT:return this.dictionary==null?this._error("Missing dictionary"):this._error("Bad dictionary"),!1;default:return this._error("Zlib error"),!1}return!0};_i.prototype._after=function(){if(this._checkError()){var e=this.strm.avail_out,t=this.strm.avail_in;this.write_in_progress=!1,this.callback(t,e),this.pending_close&&this.close()}};_i.prototype._error=function(e){this.strm.msg&&(e=this.strm.msg),this.onerror(e,this.err),this.write_in_progress=!1,this.pending_close&&this.close()};_i.prototype.init=function(e,t,r,i,n){Xi(arguments.length===4||arguments.length===5,"init(windowBits, level, memLevel, strategy, [dictionary])"),Xi(e>=8&&e<=15,"invalid windowBits"),Xi(t>=-1&&t<=9,"invalid compression level"),Xi(r>=1&&r<=9,"invalid memlevel"),Xi(i===fe.Z_FILTERED||i===fe.Z_HUFFMAN_ONLY||i===fe.Z_RLE||i===fe.Z_FIXED||i===fe.Z_DEFAULT_STRATEGY,"invalid strategy"),this._init(t,e,r,i,n),this._setDictionary()};_i.prototype.params=function(){throw new Error("deflateParams Not supported")};_i.prototype.reset=function(){this._reset(),this._setDictionary()};_i.prototype._init=function(e,t,r,i,n){switch(this.level=e,this.windowBits=t,this.memLevel=r,this.strategy=i,this.flush=fe.Z_NO_FLUSH,this.err=fe.Z_OK,(this.mode===fe.GZIP||this.mode===fe.GUNZIP)&&(this.windowBits+=16),this.mode===fe.UNZIP&&(this.windowBits+=32),(this.mode===fe.DEFLATERAW||this.mode===fe.INFLATERAW)&&(this.windowBits=-1*this.windowBits),this.strm=new NQ,this.mode){case fe.DEFLATE:case fe.GZIP:case fe.DEFLATERAW:this.err=ud.deflateInit2(this.strm,this.level,fe.Z_DEFLATED,this.windowBits,this.memLevel,this.strategy);break;case fe.INFLATE:case fe.GUNZIP:case fe.INFLATERAW:case fe.UNZIP:this.err=Iu.inflateInit2(this.strm,this.windowBits);break;default:throw new Error("Unknown mode "+this.mode)}this.err!==fe.Z_OK&&this._error("Init error"),this.dictionary=n,this.write_in_progress=!1,this.init_done=!0};_i.prototype._setDictionary=function(){if(this.dictionary!=null){switch(this.err=fe.Z_OK,this.mode){case fe.DEFLATE:case fe.DEFLATERAW:this.err=ud.deflateSetDictionary(this.strm,this.dictionary);break;default:break}this.err!==fe.Z_OK&&this._error("Failed to set dictionary")}};_i.prototype._reset=function(){switch(this.err=fe.Z_OK,this.mode){case fe.DEFLATE:case fe.DEFLATERAW:case fe.GZIP:this.err=ud.deflateReset(this.strm);break;case fe.INFLATE:case fe.INFLATERAW:case fe.GUNZIP:this.err=Iu.inflateReset(this.strm);break;default:break}this.err!==fe.Z_OK&&this._error("Failed to reset stream")};fe.Zlib=_i});var hE=T(Se=>{"use strict";g();var qo=rr().Buffer,iH=gp().Transform,De=Q3(),Is=nn(),cd=fa().ok,lE=rr().kMaxLength,nH="Cannot create final Buffer. It would be larger than 0x"+lE.toString(16)+" bytes";De.Z_MIN_WINDOWBITS=8;De.Z_MAX_WINDOWBITS=15;De.Z_DEFAULT_WINDOWBITS=15;De.Z_MIN_CHUNK=64;De.Z_MAX_CHUNK=1/0;De.Z_DEFAULT_CHUNK=16*1024;De.Z_MIN_MEMLEVEL=1;De.Z_MAX_MEMLEVEL=9;De.Z_DEFAULT_MEMLEVEL=8;De.Z_MIN_LEVEL=-1;De.Z_MAX_LEVEL=9;De.Z_DEFAULT_LEVEL=De.Z_DEFAULT_COMPRESSION;var eH=Object.keys(De);for(Rv=0;Rv<eH.length;Rv++)kv=eH[Rv],kv.match(/^Z/)&&Object.defineProperty(Se,kv,{enumerable:!0,value:De[kv],writable:!1});var kv,Rv,Nv={Z_OK:De.Z_OK,Z_STREAM_END:De.Z_STREAM_END,Z_NEED_DICT:De.Z_NEED_DICT,Z_ERRNO:De.Z_ERRNO,Z_STREAM_ERROR:De.Z_STREAM_ERROR,Z_DATA_ERROR:De.Z_DATA_ERROR,Z_MEM_ERROR:De.Z_MEM_ERROR,Z_BUF_ERROR:De.Z_BUF_ERROR,Z_VERSION_ERROR:De.Z_VERSION_ERROR},tH=Object.keys(Nv);for(Bv=0;Bv<tH.length;Bv++)fE=tH[Bv],Nv[Nv[fE]]=fE;var fE,Bv;Object.defineProperty(Se,"codes",{enumerable:!0,value:Object.freeze(Nv),writable:!1});Se.Deflate=Au;Se.Inflate=Tu;Se.Gzip=Pu;Se.Gunzip=Ru;Se.DeflateRaw=ku;Se.InflateRaw=Bu;Se.Unzip=Nu;Se.createDeflate=function(e){return new Au(e)};Se.createInflate=function(e){return new Tu(e)};Se.createDeflateRaw=function(e){return new ku(e)};Se.createInflateRaw=function(e){return new Bu(e)};Se.createGzip=function(e){return new Pu(e)};Se.createGunzip=function(e){return new Ru(e)};Se.createUnzip=function(e){return new Nu(e)};Se.deflate=function(e,t,r){return typeof t=="function"&&(r=t,t={}),Cu(new Au(t),e,r)};Se.deflateSync=function(e,t){return Lu(new Au(t),e)};Se.gzip=function(e,t,r){return typeof t=="function"&&(r=t,t={}),Cu(new Pu(t),e,r)};Se.gzipSync=function(e,t){return Lu(new Pu(t),e)};Se.deflateRaw=function(e,t,r){return typeof t=="function"&&(r=t,t={}),Cu(new ku(t),e,r)};Se.deflateRawSync=function(e,t){return Lu(new ku(t),e)};Se.unzip=function(e,t,r){return typeof t=="function"&&(r=t,t={}),Cu(new Nu(t),e,r)};Se.unzipSync=function(e,t){return Lu(new Nu(t),e)};Se.inflate=function(e,t,r){return typeof t=="function"&&(r=t,t={}),Cu(new Tu(t),e,r)};Se.inflateSync=function(e,t){return Lu(new Tu(t),e)};Se.gunzip=function(e,t,r){return typeof t=="function"&&(r=t,t={}),Cu(new Ru(t),e,r)};Se.gunzipSync=function(e,t){return Lu(new Ru(t),e)};Se.inflateRaw=function(e,t,r){return typeof t=="function"&&(r=t,t={}),Cu(new Bu(t),e,r)};Se.inflateRawSync=function(e,t){return Lu(new Bu(t),e)};function Cu(e,t,r){var i=[],n=0;e.on("error",a),e.on("end",s),e.end(t),o();function o(){for(var u;(u=e.read())!==null;)i.push(u),n+=u.length;e.once("readable",o)}function a(u){e.removeListener("end",s),e.removeListener("readable",o),r(u)}function s(){var u,c=null;n>=lE?c=new RangeError(nH):u=qo.concat(i,n),i=[],e.close(),r(c,u)}}function Lu(e,t){if(typeof t=="string"&&(t=qo.from(t)),!qo.isBuffer(t))throw new TypeError("Not a string or buffer");var r=e._finishFlushFlag;return e._processChunk(t,r)}function Au(e){if(!(this instanceof Au))return new Au(e);cr.call(this,e,De.DEFLATE)}function Tu(e){if(!(this instanceof Tu))return new Tu(e);cr.call(this,e,De.INFLATE)}function Pu(e){if(!(this instanceof Pu))return new Pu(e);cr.call(this,e,De.GZIP)}function Ru(e){if(!(this instanceof Ru))return new Ru(e);cr.call(this,e,De.GUNZIP)}function ku(e){if(!(this instanceof ku))return new ku(e);cr.call(this,e,De.DEFLATERAW)}function Bu(e){if(!(this instanceof Bu))return new Bu(e);cr.call(this,e,De.INFLATERAW)}function Nu(e){if(!(this instanceof Nu))return new Nu(e);cr.call(this,e,De.UNZIP)}function rH(e){return e===De.Z_NO_FLUSH||e===De.Z_PARTIAL_FLUSH||e===De.Z_SYNC_FLUSH||e===De.Z_FULL_FLUSH||e===De.Z_FINISH||e===De.Z_BLOCK}function cr(e,t){var r=this;if(this._opts=e=e||{},this._chunkSize=e.chunkSize||Se.Z_DEFAULT_CHUNK,iH.call(this,e),e.flush&&!rH(e.flush))throw new Error("Invalid flush flag: "+e.flush);if(e.finishFlush&&!rH(e.finishFlush))throw new Error("Invalid flush flag: "+e.finishFlush);if(this._flushFlag=e.flush||De.Z_NO_FLUSH,this._finishFlushFlag=typeof e.finishFlush<"u"?e.finishFlush:De.Z_FINISH,e.chunkSize&&(e.chunkSize<Se.Z_MIN_CHUNK||e.chunkSize>Se.Z_MAX_CHUNK))throw new Error("Invalid chunk size: "+e.chunkSize);if(e.windowBits&&(e.windowBits<Se.Z_MIN_WINDOWBITS||e.windowBits>Se.Z_MAX_WINDOWBITS))throw new Error("Invalid windowBits: "+e.windowBits);if(e.level&&(e.level<Se.Z_MIN_LEVEL||e.level>Se.Z_MAX_LEVEL))throw new Error("Invalid compression level: "+e.level);if(e.memLevel&&(e.memLevel<Se.Z_MIN_MEMLEVEL||e.memLevel>Se.Z_MAX_MEMLEVEL))throw new Error("Invalid memLevel: "+e.memLevel);if(e.strategy&&e.strategy!=Se.Z_FILTERED&&e.strategy!=Se.Z_HUFFMAN_ONLY&&e.strategy!=Se.Z_RLE&&e.strategy!=Se.Z_FIXED&&e.strategy!=Se.Z_DEFAULT_STRATEGY)throw new Error("Invalid strategy: "+e.strategy);if(e.dictionary&&!qo.isBuffer(e.dictionary))throw new Error("Invalid dictionary: it should be a Buffer instance");this._handle=new De.Zlib(t);var i=this;this._hadError=!1,this._handle.onerror=function(a,s){Cv(i),i._hadError=!0;var u=new Error(a);u.errno=s,u.code=Se.codes[s],i.emit("error",u)};var n=Se.Z_DEFAULT_COMPRESSION;typeof e.level=="number"&&(n=e.level);var o=Se.Z_DEFAULT_STRATEGY;typeof e.strategy=="number"&&(o=e.strategy),this._handle.init(e.windowBits||Se.Z_DEFAULT_WINDOWBITS,n,e.memLevel||Se.Z_DEFAULT_MEMLEVEL,o,e.dictionary),this._buffer=qo.allocUnsafe(this._chunkSize),this._offset=0,this._level=n,this._strategy=o,this.once("end",this.close),Object.defineProperty(this,"_closed",{get:function(){return!r._handle},configurable:!0,enumerable:!0})}Is.inherits(cr,iH);cr.prototype.params=function(e,t,r){if(e<Se.Z_MIN_LEVEL||e>Se.Z_MAX_LEVEL)throw new RangeError("Invalid compression level: "+e);if(t!=Se.Z_FILTERED&&t!=Se.Z_HUFFMAN_ONLY&&t!=Se.Z_RLE&&t!=Se.Z_FIXED&&t!=Se.Z_DEFAULT_STRATEGY)throw new TypeError("Invalid strategy: "+t);if(this._level!==e||this._strategy!==t){var i=this;this.flush(De.Z_SYNC_FLUSH,function(){cd(i._handle,"zlib binding closed"),i._handle.params(e,t),i._hadError||(i._level=e,i._strategy=t,r&&r())})}else b.default.nextTick(r)};cr.prototype.reset=function(){return cd(this._handle,"zlib binding closed"),this._handle.reset()};cr.prototype._flush=function(e){this._transform(qo.alloc(0),"",e)};cr.prototype.flush=function(e,t){var r=this,i=this._writableState;(typeof e=="function"||e===void 0&&!t)&&(t=e,e=De.Z_FULL_FLUSH),i.ended?t&&b.default.nextTick(t):i.ending?t&&this.once("end",t):i.needDrain?t&&this.once("drain",function(){return r.flush(e,t)}):(this._flushFlag=e,this.write(qo.alloc(0),"",t))};cr.prototype.close=function(e){Cv(this,e),b.default.nextTick(MQ,this)};function Cv(e,t){t&&b.default.nextTick(t),e._handle&&(e._handle.close(),e._handle=null)}function MQ(e){e.emit("close")}cr.prototype._transform=function(e,t,r){var i,n=this._writableState,o=n.ending||n.ended,a=o&&(!e||n.length===e.length);if(e!==null&&!qo.isBuffer(e))return r(new Error("invalid input"));if(!this._handle)return r(new Error("zlib binding closed"));a?i=this._finishFlushFlag:(i=this._flushFlag,e.length>=n.length&&(this._flushFlag=this._opts.flush||De.Z_NO_FLUSH)),this._processChunk(e,i,r)};cr.prototype._processChunk=function(e,t,r){var i=e&&e.length,n=this._chunkSize-this._offset,o=0,a=this,s=typeof r=="function";if(!s){var u=[],c=0,l;this.on("error",function(I){l=I}),cd(this._handle,"zlib binding closed");do var p=this._handle.writeSync(t,e,o,i,this._buffer,this._offset,n);while(!this._hadError&&_(p[0],p[1]));if(this._hadError)throw l;if(c>=lE)throw Cv(this),new RangeError(nH);var d=qo.concat(u,c);return Cv(this),d}cd(this._handle,"zlib binding closed");var v=this._handle.write(t,e,o,i,this._buffer,this._offset,n);v.buffer=e,v.callback=_;function _(I,R){if(this&&(this.buffer=null,this.callback=null),!a._hadError){var k=n-R;if(cd(k>=0,"have should not go down"),k>0){var q=a._buffer.slice(a._offset,a._offset+k);a._offset+=k,s?a.push(q):(u.push(q),c+=q.length)}if((R===0||a._offset>=a._chunkSize)&&(n=a._chunkSize,a._offset=0,a._buffer=qo.allocUnsafe(a._chunkSize)),R===0){if(o+=i-I,i=I,!s)return!0;var z=a._handle.write(t,e,o,i,a._buffer,a._offset,a._chunkSize);z.callback=_,z.buffer=e;return}if(!s)return!1;r()}}};Is.inherits(Au,cr);Is.inherits(Tu,cr);Is.inherits(Pu,cr);Is.inherits(Ru,cr);Is.inherits(ku,cr);Is.inherits(Bu,cr);Is.inherits(Nu,cr)});var cH=T((Vle,uH)=>{"use strict";g();var dE=DS(),Kle=nr(),oH=hE(),DQ=8*1024*1024;function aH(e,t){var r=t&&t.maxDecompressedBytes||DQ;return oH.gunzipSync(f.Buffer.from(e,"base64"),{maxOutputLength:r})}async function sH(e,t){if(!t.expectedIssuerDid)throw new Error("expectedIssuerDid is required to verify a status list (issuer pinning); refusing to read revocation state from an unpinned/unverified JWT");var r=t.didResolver;if(!r){var i=t.issuerJwks||(t.issuerPublicJwk?{keys:[t.issuerPublicJwk]}:null);if(!i)throw new Error("Provide params.didResolver, params.issuerJwks, or params.issuerPublicJwk to verify the status list signature");r=async function(){return{jwks:i}}}var n=await dE.verifyVcJwt(e,{didResolver:r,expectedIssuerDid:t.expectedIssuerDid,allowedAlgs:t.allowedAlgs,allowLegacyDER:t.allowLegacyDER,clockToleranceSec:t.clockToleranceSec});if(!n.valid)throw new Error("Status list signature verification failed: "+(n.error||"invalid signature"));return n.payload}async function HQ(e){if(!e.issuerDid||!e.privateJwk)throw new Error("issuerDid and privateJwk are required");var t=e.listId||e.issuerDid+"/status/"+Date.now(),r=e.listSize||1e5,i=Math.ceil(r/8),n=f.Buffer.alloc(i,0),o=hE(),a=o.gzipSync(n),s=a.toString("base64"),u={"@context":["https://www.w3.org/2018/credentials/v1","https://w3id.org/vc/status-list/2021/v1"],type:["VerifiableCredential","StatusList2021Credential"],issuer:e.issuerDid,issuanceDate:new Date().toISOString(),credentialSubject:{id:t,type:"StatusList2021",statusPurpose:"revocation",encodedList:s}},c=await dE.issueVcJwt({issuerDid:e.issuerDid,subjectId:t,types:["VerifiableCredential","StatusList2021Credential"],credentialSubject:u.credentialSubject,privateJwk:e.privateJwk,alg:e.privateJwk.alg||"ES256"});return{listVcJwt:c.jwt,listId:t}}async function qQ(e){if(!e.listVcJwt||e.index===void 0||!e.status||!e.privateJwk)throw new Error("listVcJwt, index, status, and privateJwk are required");if(e.status==="suspended")throw new Error("status 'suspended' is not supported by this list: its statusPurpose is 'revocation', and suspension would be written to the same bit and read back as 'revoked'. Maintain a separate list for suspension until statusPurpose is configurable.");var t=await sH(e.listVcJwt,e),r=t.vc.credentialSubject.encodedList,i=aH(r,e),n=Math.floor(e.index/8),o=e.index%8;if(n>=i.length)throw new Error("Index out of range");var a=e.status==="revoked"?1:0;a===1?i[n]|=1<<o:i[n]&=~(1<<o);var s=oH.gzipSync(i),u=s.toString("base64"),c={id:t.vc.credentialSubject.id,type:"StatusList2021",statusPurpose:"revocation",encodedList:u},l=await dE.issueVcJwt({issuerDid:t.iss,subjectId:t.vc.credentialSubject.id,types:["VerifiableCredential","StatusList2021Credential"],credentialSubject:c,privateJwk:e.privateJwk,alg:e.privateJwk.alg||"ES256"});return{listVcJwt:l.jwt}}async function UQ(e){if(!e.listVcJwt||e.index===void 0)throw new Error("listVcJwt and index are required");var t=await sH(e.listVcJwt,e),r=t.vc.credentialSubject.encodedList,i=aH(r,e),n=Math.floor(e.index/8),o=e.index%8;if(n>=i.length)throw new Error("Index out of range");var a=i[n]>>o&1;return a===1?"revoked":"valid"}uH.exports={createStatusList:HQ,updateStatusList:qQ,getCredentialStatusEntry:UQ}});var hH=T((Wle,lH)=>{"use strict";g();var FQ=nr();function fH(e){var t;if(typeof e=="string")t=f.Buffer.from(e,"utf8");else if(f.Buffer.isBuffer(e))t=e;else if(e instanceof Uint8Array)t=f.Buffer.from(e);else throw new Error("Data must be string, Buffer, or Uint8Array");return FQ.createHash("sha256").update(t).digest("hex")}function jQ(e){if(!e.kind||!e.hash||!e.issuerDid)throw new Error("kind, hash, and issuerDid are required");var t=["VC_ANCHOR_SHA256","STATUSLIST_SHA256","PRESENTATION_SHA256"];if(t.indexOf(e.kind)===-1)throw new Error("Invalid kind. Must be one of: "+t.join(", "));if(!/^[a-fA-F0-9]{64}$/.test(e.hash))throw new Error("Invalid hash format. Must be 64 hex characters");var r={protocol:"SmartLedger",version:"1.0",type:e.kind,hash:e.hash,issuer:e.issuerDid,timestamp:e.issuedAt||new Date().toISOString()};return{json:JSON.stringify(r)}}function zQ(e,t){var r=fH(e);return r===t}function KQ(e){try{var t=JSON.parse(e);if(t.protocol!=="SmartLedger")return{valid:!1,error:"Invalid protocol"};var r=["VC_ANCHOR_SHA256","STATUSLIST_SHA256","PRESENTATION_SHA256"];return r.indexOf(t.type)===-1?{valid:!1,error:"Invalid anchor type"}:/^[a-fA-F0-9]{64}$/.test(t.hash)?{valid:!0,protocol:t.protocol,version:t.version,type:t.type,hash:t.hash,issuer:t.issuer,timestamp:t.timestamp}:{valid:!1,error:"Invalid hash format"}}catch(i){return{valid:!1,error:"Failed to parse anchor payload: "+i.message}}}lH.exports={sha256Hex:fH,buildAnchorPayload:jQ,verifyAnchorHash:zQ,parseAnchorPayload:KQ}});var fd=T((Zle,pH)=>{"use strict";g();var dH=Ki();function VQ(){var e=dH.getRandomBuffer(16);e[6]=e[6]&15|64,e[8]=e[8]&63|128;var t=e.toString("hex");return[t.substring(0,8),t.substring(8,12),t.substring(12,16),t.substring(16,20),t.substring(20,32)].join("-")}function GQ(e){return dH.getRandomBuffer(Math.ceil(e/2)).toString("hex").substring(0,e)}pH.exports={uuid4:VQ,randomHex:GQ}});var bH=T((Jle,yH)=>{"use strict";g();var ld=sr(),pE=Le(),gE=dn(),gH=gt(),mE=ei(),Mr=Ie(),Xle=at(),WQ=fd();function mH(e,t){if(t=t||{},t.issuerPublicKey)return t.issuerPublicKey instanceof ld?t.issuerPublicKey:ld.fromString(t.issuerPublicKey);var r=e&&e.issuer;if(typeof r!="string")return null;try{var i=r.split("#")[0].split(":")[2];return i?ld.fromString(i):null}catch{return null}}var Nf={PROPERTY_TITLE:"PropertyTitle",VEHICLE_TITLE:"VehicleTitle",INTELLECTUAL_PROPERTY:"IntellectualProperty",MUSIC_LICENSE:"MusicLicense",SOFTWARE_LICENSE:"SoftwareLicense",FINANCIAL_INSTRUMENT:"FinancialInstrument",PROMISSORY_NOTE:"PromissoryNote",BOND:"Bond",EQUITY_SHARE:"EquityShare",PROFESSIONAL_LICENSE:"ProfessionalLicense",REGULATORY_PERMIT:"RegulatoryPermit",ACCESS_RIGHT:"AccessRight",VOTING_RIGHT:"VotingRight",ROYALTY_RIGHT:"RoyaltyRight",USAGE_RIGHT:"UsageRight"},vH={create:function(e,t,r,i,n,o){o=o||{},Mr.checkArgument(typeof e=="string","Right type must be string"),Mr.checkArgument(typeof t=="string","Issuer DID must be string"),Mr.checkArgument(typeof r=="string","Subject DID must be string"),Mr.checkArgument(i&&typeof i=="object","Claim must be object");var a=Object.values(Nf);Mr.checkArgument(a.includes(e),"Invalid right type: "+e);var s={"@context":["https://www.w3.org/2018/credentials/v1","https://smartledger.technology/contexts/ltp/v1"],id:"urn:uuid:"+this._generateUUID(),type:["VerifiableCredential","LegalRightToken",e],issuer:t,issuanceDate:new Date().toISOString(),credentialSubject:{id:r,rightType:e,claim:i,jurisdiction:o.jurisdiction||"US",purpose:o.purpose||"legal_right",validFrom:o.validFrom||new Date().toISOString(),validUntil:o.validUntil||null,transferable:o.transferable!==!1,revocable:o.revocable!==!1}};return o.metadata&&(s.credentialSubject.metadata=o.metadata),s},prepareRightToken:function(e,t,r,i,n,o){o=o||{},Mr.checkArgument(typeof e=="string","Right type must be string"),Mr.checkArgument(typeof t=="string","Issuer DID must be string"),Mr.checkArgument(typeof r=="string","Subject DID must be string"),Mr.checkArgument(i&&typeof i=="object","Claim must be object"),Mr.checkArgument(n instanceof mE,"Invalid issuer private key");var a=Object.values(Nf);Mr.checkArgument(a.includes(e),"Invalid right type: "+e);try{var s=this.create(e,t,r,i,n,o),u=this._signToken(s,n);return{success:!0,rightToken:u,tokenHash:u.tokenHash,metadata:{type:e,issuer:t,subject:r,transferable:s.credentialSubject.transferable,revocable:s.credentialSubject.revocable,jurisdiction:s.credentialSubject.jurisdiction},externalOperations:{storeToken:{endpoint:"POST /rights/tokens",data:{token:u,metadata:{type:e,issuer:t,subject:r,transferable:s.credentialSubject.transferable,revocable:s.credentialSubject.revocable,jurisdiction:s.credentialSubject.jurisdiction}}},indexToken:{endpoint:"POST /rights/index",data:{tokenId:u.id,tokenHash:u.tokenHash,type:e,issuer:t,subject:r,issuedAt:u.issuanceDate}},notifyParties:{endpoint:"POST /notifications/right-issued",data:{tokenId:u.id,issuer:t,subject:r,rightType:e}}}}}catch(c){return{success:!1,error:c.message}}},prepareRightTokenVerification:function(e,t){t=t||{};try{var r=[],i=[];this._validateTokenStructure(e,r),this._verifyTokenSignature(e,r,t),this._validateTokenTemporal(e,r,i),this._validateRightType(e,r),t.requireJurisdiction&&this._validateJurisdiction(e,t.allowedJurisdictions,r);var n={valid:r.length===0,errors:r,warnings:i,issuerDID:e.issuer,subjectDID:e.credentialSubject?e.credentialSubject.id:null,rightType:e.credentialSubject?e.credentialSubject.rightType:null,transferable:e.credentialSubject?e.credentialSubject.transferable:null,revocable:e.credentialSubject?e.credentialSubject.revocable:null,verifiedAt:new Date().toISOString()};return{success:!0,verification:n,externalOperations:{recordVerification:{endpoint:"POST /rights/verification-record",data:{tokenId:e.id,result:n.valid,errors:r,warnings:i,verifiedAt:n.verifiedAt}},auditVerification:{endpoint:"POST /audit/right-verification",data:{tokenId:e.id,rightType:n.rightType,issuer:n.issuerDID,subject:n.subjectDID,result:n.valid,verifiedAt:n.verifiedAt}},updateTokenStatus:n.valid?{endpoint:"PUT /rights/tokens/"+e.id+"/status",data:{status:"VERIFIED",verifiedAt:n.verifiedAt}}:null}}}catch(o){return{success:!1,error:"Verification preparation failed: "+o.message}}},prepareRightTokenTransfer:function(e,t,r,i){i=i||{},Mr.checkArgument(e&&typeof e=="object","Invalid token"),Mr.checkArgument(typeof t=="string","New owner DID must be string"),Mr.checkArgument(r instanceof mE,"Invalid current owner key");try{var n=this.prepareRightTokenVerification(e,{});if(!n.success||!n.verification.valid)return{success:!1,error:"Cannot transfer invalid token: "+n.verification.errors.join(", ")};if(!e.credentialSubject.transferable)return{success:!1,error:"Token is not transferable"};var o=e.credentialSubject&&e.credentialSubject.id,a=mH({issuer:o},{issuerPublicKey:i.currentOwnerPublicKey});if(!a)return{success:!1,error:"Cannot resolve current owner public key from token.credentialSubject.id; pass options.currentOwnerPublicKey"};if(r.toPublicKey().toString()!==a.toString())return{success:!1,error:"Unauthorized transfer: signing key does not match the current owner"};var s={"@context":["https://www.w3.org/2018/credentials/v1","https://smartledger.technology/contexts/ltp/v1"],id:"urn:uuid:"+this._generateUUID(),type:["VerifiableCredential","LegalRightTransfer"],issuer:e.credentialSubject.id,issuanceDate:new Date().toISOString(),credentialSubject:{id:t,originalToken:e.id,transferFrom:e.credentialSubject.id,transferTo:t,transferDate:new Date().toISOString(),transferReason:i.reason||"ownership_transfer",consideration:i.consideration||null}},u=this._signToken(s,r),c=JSON.parse(JSON.stringify(e));c.id="urn:uuid:"+this._generateUUID(),c.issuanceDate=new Date().toISOString(),c.credentialSubject.id=t,c.credentialSubject.transferHistory=c.credentialSubject.transferHistory||[],c.credentialSubject.transferHistory.push({transferId:u.id,transferDate:u.issuanceDate,from:e.credentialSubject.id,to:t}),delete c.proof;var l=this._signToken(c,r);return{success:!0,newToken:l,transferProof:u,transferId:u.id,externalOperations:{recordTransfer:{endpoint:"POST /rights/transfers",data:{originalTokenId:e.id,newTokenId:l.id,transferProof:u,fromOwner:e.credentialSubject.id,toOwner:t,transferDate:u.issuanceDate}},updateOwnership:{endpoint:"PUT /rights/tokens/"+e.id+"/ownership",data:{newOwner:t,transferId:u.id,transferDate:u.issuanceDate,previousOwner:e.credentialSubject.id}},notifyParties:{endpoint:"POST /notifications/right-transferred",data:{originalTokenId:e.id,newTokenId:l.id,fromOwner:e.credentialSubject.id,toOwner:t,rightType:e.credentialSubject.rightType}},auditTransfer:{endpoint:"POST /audit/right-transfer",data:{originalTokenId:e.id,newTokenId:l.id,transferId:u.id,fromOwner:e.credentialSubject.id,toOwner:t,transferredAt:u.issuanceDate}}}}}catch(p){return{success:!1,error:p.message}}},prepareObligationToken:function(e,t,r,i){Mr.checkArgument(e&&typeof e=="object","Invalid right token"),Mr.checkArgument(typeof t=="string","Obligor DID must be string"),Mr.checkArgument(r&&typeof r=="object","Obligation must be object"),Mr.checkArgument(i instanceof mE,"Invalid issuer key");try{var n={"@context":["https://www.w3.org/2018/credentials/v1","https://smartledger.technology/contexts/ltp/v1"],id:"urn:uuid:"+this._generateUUID(),type:["VerifiableCredential","LegalObligationToken"],issuer:e.issuer,issuanceDate:new Date().toISOString(),credentialSubject:{id:t,obligationType:"correlative_obligation",correlativeRight:e.id,rightHolder:e.credentialSubject.id,obligation:r,jurisdiction:e.credentialSubject.jurisdiction,purpose:e.credentialSubject.purpose}},o=this._signToken(n,i);return{success:!0,obligationToken:o,correlativeRight:e.id,externalOperations:{storeObligation:{endpoint:"POST /obligations/tokens",data:{obligationToken:o,correlativeRightId:e.id,obligor:t,rightHolder:e.credentialSubject.id}},linkToRight:{endpoint:"POST /rights/tokens/"+e.id+"/obligations",data:{obligationId:o.id,obligor:t,obligationType:"correlative_obligation"}},notifyObligor:{endpoint:"POST /notifications/obligation-created",data:{obligationId:o.id,obligor:t,rightHolder:e.credentialSubject.id,correlativeRight:e.id}}}}}catch(a){return{success:!1,error:a.message}}},prepareRightTypeValidation:function(e){Mr.checkArgument(typeof e=="string","Right type must be string");var t=Object.values(Nf),r=t.includes(e);return{success:!0,validation:{type:e,valid:r,availableTypes:t,category:this._categorizeRightType(e),description:this._getRightTypeDescription(e)},externalOperations:{validateType:{endpoint:"POST /rights/validate-type",data:{type:e,valid:r}}}}},_categorizeRightType:function(e){var t={PropertyTitle:"PROPERTY_RIGHT",VehicleTitle:"PROPERTY_RIGHT",IntellectualProperty:"IP_RIGHT",MusicLicense:"IP_RIGHT",SoftwareLicense:"IP_RIGHT",FinancialInstrument:"FINANCIAL_RIGHT",PromissoryNote:"FINANCIAL_RIGHT",Bond:"FINANCIAL_RIGHT",EquityShare:"FINANCIAL_RIGHT",ProfessionalLicense:"LICENSE_RIGHT",RegulatoryPermit:"LICENSE_RIGHT",AccessRight:"ACCESS_RIGHT",VotingRight:"GOVERNANCE_RIGHT",RoyaltyRight:"IP_RIGHT",UsageRight:"ACCESS_RIGHT"};return t[e]||"UNKNOWN"},_getRightTypeDescription:function(e){var t={PropertyTitle:"Legal ownership of real estate property",VehicleTitle:"Legal ownership of motor vehicle",IntellectualProperty:"Rights to intellectual property assets",MusicLicense:"License for music performance and usage",SoftwareLicense:"License for software usage and distribution",FinancialInstrument:"Rights related to financial instruments",PromissoryNote:"Promise to pay a specified amount",Bond:"Debt security representing loan",EquityShare:"Ownership stake in company",ProfessionalLicense:"License for professional practice",RegulatoryPermit:"Permit for regulated activities",AccessRight:"Right to access resources or locations",VotingRight:"Right to participate in governance",RoyaltyRight:"Right to receive royalty payments",UsageRight:"Right to use specific assets or services"};return t[e]||"Unknown right type"},getRightTypes:function(){return Nf},verifyToken:function(e,t){var r=[];try{if(Mr.checkArgument(e&&typeof e=="object","Invalid token"),!e.proof||!e.proof.jws)return r.push("Missing signature proof"),{valid:!1,errors:r};var i=t instanceof ld?t:ld.fromString(t),n=this._canonicalizeToken(e),o=pE.sha256(f.Buffer.from(n));if(e.tokenHash&&e.tokenHash!==o.toString("hex"))return r.push("Token hash mismatch"),{valid:!1,errors:r};var a=e.proof.jws.split(".");if(a.length!==3||!a[2])return r.push("Malformed JWS"),{valid:!1,errors:r};var s=gH.fromDER(f.Buffer.from(a[2],"base64url")),u=new gE;return u.hashbuf=o,u.sig=s,u.pubkey=i,u.verify()||r.push("Signature verification failed"),{valid:r.length===0,errors:r,tokenHash:o.toString("hex"),verifiedAt:new Date().toISOString()}}catch(c){return r.push(c.message),{valid:!1,errors:r}}},_signToken:function(e,t){var r=this._canonicalizeToken(e),i=pE.sha256(f.Buffer.from(r)),n=new gE;n.hashbuf=i,n.privkey=t,n.pubkey=t.toPublicKey(),n.sign();var o=n.sig,a={type:"EcdsaSecp256k1Signature2019",created:new Date().toISOString(),verificationMethod:"did:smartledger:"+t.toPublicKey().toString()+"#keys-1",proofPurpose:"assertionMethod",jws:this._createJWS(i,o)},s=JSON.parse(JSON.stringify(e));return s.proof=a,s.tokenHash=i.toString("hex"),s},_createJWS:function(e,t){var r={alg:"ES256K",typ:"JWT"},i=f.Buffer.from(JSON.stringify(r)).toString("base64url"),n=t.toDER().toString("base64url");return i+".."+n},_canonicalizeToken:function(e){var t=JSON.parse(JSON.stringify(e));return delete t.proof,delete t.tokenHash,JSON.stringify(this._sortObjectKeys(t))},_sortObjectKeys:function(e){if(Array.isArray(e))return e.map(this._sortObjectKeys.bind(this));if(e!==null&&typeof e=="object"){var t={};return Object.keys(e).sort().forEach(function(r){t[r]=this._sortObjectKeys(e[r])}.bind(this)),t}return e},_validateTokenStructure:function(e,t){e["@context"]||t.push("Missing @context"),e.id||t.push("Missing id"),(!e.type||!Array.isArray(e.type))&&t.push("Missing or invalid type"),e.issuer||t.push("Missing issuer"),e.issuanceDate||t.push("Missing issuanceDate"),e.credentialSubject||t.push("Missing credentialSubject"),e.proof||t.push("Missing proof")},_verifyTokenSignature:function(e,t,r){try{if(!e.proof||!e.proof.jws){t.push("Missing signature proof");return}var i=this._canonicalizeToken(e),n=pE.sha256(f.Buffer.from(i));if(e.tokenHash&&e.tokenHash!==n.toString("hex")){t.push("Token hash mismatch");return}var o=mH(e,r);if(!o){t.push("Signature not verified: issuer public key could not be resolved from token.issuer; pass options.issuerPublicKey");return}var a=e.proof.jws.split(".");if(a.length!==3||!a[2]){t.push("Malformed JWS");return}var s=gH.fromDER(f.Buffer.from(a[2],"base64url")),u=new gE;u.hashbuf=n,u.sig=s,u.pubkey=o,u.verify()!==!0&&t.push("Signature verification failed")}catch(c){t.push("Signature verification failed: "+c.message)}},_validateTokenTemporal:function(e,t,r){var i=new Date,n=new Date(e.issuanceDate);if(n>i&&t.push("Token issued in the future"),e.credentialSubject.validFrom){var o=new Date(e.credentialSubject.validFrom);i<o&&r.push("Token not yet valid")}if(e.credentialSubject.validUntil){var a=new Date(e.credentialSubject.validUntil);i>a&&t.push("Token expired")}},_validateRightType:function(e,t){if(!e.credentialSubject.rightType){t.push("Missing rightType");return}var r=Object.values(Nf);r.includes(e.credentialSubject.rightType)||t.push("Invalid right type: "+e.credentialSubject.rightType)},_validateJurisdiction:function(e,t,r){if(!e.credentialSubject.jurisdiction){r.push("Missing jurisdiction");return}t&&Array.isArray(t)&&(t.includes(e.credentialSubject.jurisdiction)||r.push("Jurisdiction not allowed: "+e.credentialSubject.jurisdiction))},_generateUUID:function(){return WQ.uuid4()}};vH.RightTypes=Nf;yH.exports=vH});var wH=T((ehe,_H)=>{"use strict";g();var Cf=Le(),Fi=Ie(),YQ=fd(),ZQ=Vc(),$Q=ts(),Mu={PropertyTitle:{title:"Property Title",description:"Real estate property ownership title",type:"object",required:["propertyId","address","ownershipType"],properties:{propertyId:{type:"string",description:"Unique property identifier"},address:{type:"object",required:["street","city","state","country"],properties:{street:{type:"string"},city:{type:"string"},state:{type:"string"},country:{type:"string"},postalCode:{type:"string"}}},ownershipType:{type:"string",enum:["fee_simple","leasehold","joint_tenancy","tenancy_in_common"]},titleNumber:{type:"string"},registeredDate:{type:"string",format:"date-time"},legalDescription:{type:"string"},encumbrances:{type:"array",items:{type:"object",properties:{type:{type:"string"},amount:{type:"number"},description:{type:"string"}}}}}},VehicleTitle:{title:"Vehicle Title",description:"Motor vehicle ownership title",type:"object",required:["vin","make","model","year"],properties:{vin:{type:"string",pattern:"^[A-HJ-NPR-Z0-9]{17}$",description:"Vehicle Identification Number"},make:{type:"string"},model:{type:"string"},year:{type:"integer",minimum:1900,maximum:2030},titleNumber:{type:"string"},registeredState:{type:"string"},mileage:{type:"integer",minimum:0},color:{type:"string"},fuelType:{type:"string",enum:["gasoline","diesel","electric","hybrid","other"]},liens:{type:"array",items:{type:"object",properties:{lienholderName:{type:"string"},lienAmount:{type:"number"},lienDate:{type:"string",format:"date"}}}}}},PromissoryNote:{title:"Promissory Note",description:"Legal promise to pay a specified amount",type:"object",required:["principal","interestRate","maturityDate","borrower","lender"],properties:{principalAmount:{type:"number",minimum:0,description:"Principal amount in base currency units"},currency:{type:"string",default:"USD"},interestRate:{type:"number",minimum:0,maximum:100,description:"Annual interest rate percentage"},maturityDate:{type:"string",format:"date",description:"Date when principal and interest are due"},payee:{type:"string",description:"DID of the payee (creditor)"},payor:{type:"string",description:"DID of the payor (debtor)"},paymentSchedule:{type:"string",enum:["lump_sum","monthly","quarterly","annually"]},collateral:{type:"array",items:{type:"object",properties:{description:{type:"string"},value:{type:"number"},type:{type:"string"}}}},defaultProvisions:{type:"string"},governingLaw:{type:"string"}}},IntellectualProperty:{title:"Intellectual Property",description:"Intellectual property rights and licensing",type:"object",required:["ipType","title","registrationNumber"],properties:{ipType:{type:"string",enum:["patent","trademark","copyright","trade_secret"]},title:{type:"string"},creator:{type:"string",description:"Creator DID"},registrationNumber:{type:"string"},registrationDate:{type:"string",format:"date"},expirationDate:{type:"string",format:"date"},jurisdiction:{type:"string"},description:{type:"string"},claims:{type:"array",items:{type:"string"}},priorArt:{type:"array",items:{type:"object",properties:{reference:{type:"string"},date:{type:"string",format:"date"},relevance:{type:"string"}}}}}},ProfessionalLicense:{title:"Professional License",description:"Professional practice license or certification",type:"object",required:["licenseType","licenseNumber","issuingAuthority","expirationDate"],properties:{licenseType:{type:"string"},licenseNumber:{type:"string"},issuingAuthority:{type:"string"},licensee:{type:"string",description:"Licensee DID"},issueDate:{type:"string",format:"date"},expirationDate:{type:"string",format:"date"},renewalDate:{type:"string",format:"date"},jurisdiction:{type:"string"},scope:{type:"string"},restrictions:{type:"array",items:{type:"string"}},continuing_education:{type:"object",properties:{hours_required:{type:"integer"},deadline:{type:"string",format:"date"},completed_hours:{type:"integer"}}}}},MusicLicense:{title:"Music License",description:"Music performance and usage licensing",type:"object",required:["songTitle","artist","licenseType","royaltyRate"],properties:{workTitle:{type:"string"},composer:{type:"string",description:"Composer DID"},performer:{type:"string",description:"Performer DID"},licenseType:{type:"string",enum:["mechanical","performance","synchronization","master_use"]},territory:{type:"string"},duration:{type:"string"},royaltyRate:{type:"number",minimum:0,maximum:100},advancePayment:{type:"number",minimum:0},exclusivity:{type:"boolean"},mediaTypes:{type:"array",items:{type:"string",enum:["cd","vinyl","digital","streaming","broadcast","film","tv"]}},usage_restrictions:{type:"string"},copyrightNotice:{type:"string"}}}},XQ={prepareClaimValidation:function(e,t){try{Fi.checkArgument(e&&typeof e=="object","Invalid claim"),Fi.checkArgument(typeof t=="string","Schema name must be string");var r=Mu[t];if(!r)return{success:!1,error:"Unknown schema: "+t};var i=[],n=[];this._validateObject(e,r,"",i,n);var o={valid:i.length===0,errors:i,warnings:n,schema:t,claimHash:Cf.sha256(f.Buffer.from(this._canonicalizeWith(e,this.CANONICALIZATION.LEGACY))).toString("hex"),canonical:this._canonicalizeWith(e,this.CANONICALIZATION.LEGACY)};return{success:!0,validation:o,claim:e,schema:r,externalOperations:{store:{endpoint:"POST /claims/validate",data:{claim:e,validation:o,schema:t}},index:{endpoint:"POST /claims/index",data:{claimHash:o.claimHash,schemaName:t,valid:o.valid}}}}}catch(a){return{success:!1,error:"Validation preparation failed: "+a.message}}},prepareClaimAttestation:function(e,t,r){try{Fi.checkArgument(e&&typeof e=="object","Invalid claim"),Fi.checkArgument(typeof t=="string","Schema name must be string"),Fi.checkArgument(r&&typeof r=="object","Invalid attestor");var i=this.prepareClaimValidation(e,t);if(!i.success||!i.validation.valid)return{success:!1,error:"Cannot attest invalid claim",validation:i};var n={type:"LTP_CLAIM_ATTESTATION",claimHash:i.validation.claimHash,schemaName:t,attestor:{did:r.did||r.id,name:r.name||"Unknown",authority:r.authority||null,jurisdiction:r.jurisdiction||null},attestedAt:new Date().toISOString(),confidence:r.confidence||100,evidence:r.evidence||null,notes:r.notes||null},o=Cf.sha256(f.Buffer.from(this._canonicalizeWith(n,this.CANONICALIZATION.LEGACY))).toString("hex");return n.attestationHash=o,{success:!0,attestation:n,claim:e,validation:i.validation,externalOperations:{storeAttestation:{endpoint:"POST /claims/"+i.validation.claimHash+"/attestations",data:n},notifyStakeholders:{endpoint:"POST /notifications/claim-attested",data:{claimHash:i.validation.claimHash,attestorDid:n.attestor.did,attestationHash:o}}}}}catch(a){return{success:!1,error:"Attestation preparation failed: "+a.message}}},prepareClaimDispute:function(e,t,r){try{Fi.checkArgument(typeof e=="string","Claim hash must be string"),Fi.checkArgument(t&&typeof t=="object","Invalid disputant"),Fi.checkArgument(r&&typeof r=="object","Invalid dispute");var i={type:"LTP_CLAIM_DISPUTE",claimHash:e,disputant:{did:t.did||t.id,name:t.name||"Unknown",jurisdiction:t.jurisdiction||null},dispute:{reason:r.reason||"UNSPECIFIED",category:r.category||"ACCURACY",description:r.description||"",evidence:r.evidence||null,requestedAction:r.requestedAction||"REVIEW"},disputedAt:new Date().toISOString(),status:"FILED",priority:r.priority||"NORMAL"},n=Cf.sha256(f.Buffer.from(this._canonicalizeWith(i,this.CANONICALIZATION.LEGACY))).toString("hex");return i.disputeHash=n,{success:!0,dispute:i,disputeId:this._generateDisputeId(e),externalOperations:{fileDispute:{endpoint:"POST /claims/"+e+"/disputes",data:i},notifyStakeholders:{endpoint:"POST /notifications/claim-disputed",data:{claimHash:e,disputantDid:i.disputant.did,disputeHash:n}},escalate:{endpoint:"POST /disputes/escalate",data:{disputeHash:n,priority:i.priority}}}}}catch(o){return{success:!1,error:"Dispute preparation failed: "+o.message}}},prepareBulkClaimValidation:function(e,t){try{Fi.checkArgument(Array.isArray(e),"Claims must be array"),Fi.checkArgument(typeof t=="string","Schema name must be string");var r=[],i=[],n=0;e.forEach(function(s,u){try{var c=this.prepareClaimValidation(s,t);c.success&&c.validation.valid&&n++,r.push({index:u,result:c})}catch(l){i.push({index:u,error:l.message})}}.bind(this));var o=this._generateBatchId(),a=Cf.sha256(f.Buffer.from(JSON.stringify(r.map(s=>s.result.validation.claimHash)))).toString("hex");return{success:!0,batchId:o,batchHash:a,totalClaims:e.length,validClaims:n,invalidClaims:e.length-n,validations:r,errors:i,externalOperations:{storeBatch:{endpoint:"POST /claims/batch-validate",data:{batchId:o,batchHash:a,schemaName:t,validations:r}},generateReport:{endpoint:"POST /reports/bulk-validation",data:{batchId:o,summary:{total:e.length,valid:n,invalid:e.length-n}}}}}}catch(s){return{success:!1,error:"Bulk validation preparation failed: "+s.message}}},CANONICALIZATION:{JCS:"jcs",LEGACY:"legacy"},canonicalize:function(e,t){return this._canonicalizeWith(e,this._resolveCanonicalization(t,"LTP.Claim.canonicalize"))},hash:function(e,t){var r=this._canonicalizeWith(e,this._resolveCanonicalization(t,"LTP.Claim.hash"));return Cf.sha256(f.Buffer.from(r)).toString("hex")},_canonicalizeWith:function(e,t){if(Fi.checkArgument(e&&typeof e=="object","Invalid claim"),t===this.CANONICALIZATION.JCS)return ZQ.stringify(e);var r=this._sortObjectKeys(e);return JSON.stringify(r)},_resolveCanonicalization:function(e,t){return e===void 0?($Q({what:t+"() without a canonicalization argument",since:"9.2.0",removeIn:"10.0.0",use:t+"(claim, bsv.LTP.Claim.CANONICALIZATION.JCS)",why:"the default sorted-key form is not RFC 8785, so other implementations compute a different claim hash"}),this.CANONICALIZATION.LEGACY):(Fi.checkArgument(e===this.CANONICALIZATION.JCS||e===this.CANONICALIZATION.LEGACY,"Unknown canonicalization: "+e+". Expected 'jcs' or 'legacy' (bsv.LTP.Claim.CANONICALIZATION)"),e)},prepareClaimTemplate:function(e,t){t=t||{};try{var r=Mu[e];if(!r)return{success:!1,error:"Unknown schema: "+e};var i=this._createTemplateFromSchema(r),n=this._generateFormStructure(r);return{success:!0,schemaName:e,template:i,schema:r,formStructure:n,validation:{required:r.required||[],patterns:this._extractPatterns(r),enums:this._extractEnums(r)},externalOperations:{generateForm:{endpoint:"POST /forms/generate",data:{schemaName:e,formStructure:n,template:i}},saveTemplate:{endpoint:"POST /templates/claim",data:{schemaName:e,template:i,customizations:t.customizations||{}}}}}}catch(o){return{success:!1,error:"Template preparation failed: "+o.message}}},getSchemas:function(){return Mu},getSchemaNames:function(){return Object.keys(Mu)},getSchema:function(e){return Mu[e]||null},addSchema:function(e,t){Fi.checkArgument(typeof e=="string","Schema name must be string"),Fi.checkArgument(t&&typeof t=="object","Invalid schema"),Mu[e]=t},createTemplate:function(e){var t=Mu[e];if(!t)throw new Error("Unknown schema: "+e);return this._createTemplateFromSchema(t)},_generateDisputeId:function(e){var t="dispute_"+e+"_"+Date.now();return Cf.sha256(f.Buffer.from(t)).toString("hex").substring(0,16)},_generateBatchId:function(){return YQ.randomHex(16)},_generateFormStructure:function(e){var t={type:"form",title:e.title||"Legal Claim Form",description:e.description||"",fields:[]};return e.properties&&Object.keys(e.properties).forEach(function(r){var i=e.properties[r],n={name:r,label:this._humanizeFieldName(r),type:this._mapSchemaTypeToFormType(i),required:e.required&&e.required.includes(r),validation:this._extractFieldValidation(i)};i.enum&&(n.options=i.enum.map(function(o){return{value:o,label:this._humanizeValue(o)}}.bind(this))),t.fields.push(n)}.bind(this)),t},_extractPatterns:function(e){var t={};return e.properties&&Object.keys(e.properties).forEach(function(r){var i=e.properties[r];i.pattern&&(t[r]=i.pattern)}),t},_extractEnums:function(e){var t={};return e.properties&&Object.keys(e.properties).forEach(function(r){var i=e.properties[r];i.enum&&(t[r]=i.enum)}),t},_mapSchemaTypeToFormType:function(e){switch(e.type){case"string":return e.enum?"select":e.format==="date"?"date":e.format==="date-time"?"datetime":"text";case"number":case"integer":return"number";case"boolean":return"checkbox";case"array":return"list";case"object":return"fieldset";default:return"text"}},_extractFieldValidation:function(e){var t={};return e.pattern&&(t.pattern=e.pattern),e.minimum!==void 0&&(t.min=e.minimum),e.maximum!==void 0&&(t.max=e.maximum),e.format&&(t.format=e.format),t},_humanizeFieldName:function(e){return e.replace(/([A-Z])/g," $1").replace(/^./,function(t){return t.toUpperCase()}).replace(/_/g," ")},_humanizeValue:function(e){return e.replace(/_/g," ").replace(/\b\w/g,function(t){return t.toUpperCase()})},_validateObject:function(e,t,r,i,n){t.type==="object"?(t.required&&Array.isArray(t.required)&&t.required.forEach(function(o){e.hasOwnProperty(o)||i.push("Missing required field: "+this._getFieldPath(r,o))}.bind(this)),t.properties&&Object.keys(e).forEach(function(o){var a=this._getFieldPath(r,o),s=t.properties[o];s?this._validateValue(e[o],s,a,i,n):n.push("Unknown field: "+a)}.bind(this))):this._validateValue(e,t,r,i,n)},_validateValue:function(e,t,r,i,n){if(t.type){var o=Array.isArray(e)?"array":typeof e;if(o!==t.type){i.push("Invalid type for "+r+": expected "+t.type+", got "+o);return}}if(t.type==="string"&&(t.pattern&&!new RegExp(t.pattern).test(e)&&i.push("Value does not match pattern for "+r),t.enum&&!t.enum.includes(e)&&i.push("Invalid enum value for "+r+": "+e),t.format==="date"&&!this._isValidDate(e)&&i.push("Invalid date format for "+r),t.format==="date-time"&&!this._isValidDateTime(e)&&i.push("Invalid date-time format for "+r)),(t.type==="number"||t.type==="integer")&&(t.minimum!==void 0&&e<t.minimum&&i.push("Value below minimum for "+r+": "+e+" < "+t.minimum),t.maximum!==void 0&&e>t.maximum&&i.push("Value above maximum for "+r+": "+e+" > "+t.maximum),t.type==="integer"&&!Number.isInteger(e)&&i.push("Value must be integer for "+r)),t.type==="array"&&t.items)for(var a=0;a<e.length;a++)this._validateValue(e[a],t.items,r+"["+a+"]",i,n);t.type==="object"&&this._validateObject(e,t,r,i,n)},_sortObjectKeys:function(e){if(Array.isArray(e))return e.map(this._sortObjectKeys.bind(this));if(e!==null&&typeof e=="object"){var t={};return Object.keys(e).sort().forEach(function(r){t[r]=this._sortObjectKeys(e[r])}.bind(this)),t}return e},_createTemplateFromSchema:function(e){if(e.type==="object"){var t={};return e.properties&&Object.keys(e.properties).forEach(function(r){var i=e.properties[r];t[r]=this._getDefaultValue(i)}.bind(this)),t}return this._getDefaultValue(e)},_getDefaultValue:function(e){if(e.default!==void 0)return e.default;switch(e.type){case"string":return e.enum?e.enum[0]:e.format==="date"?"2023-01-01":e.format==="date-time"?new Date().toISOString():"PLACEHOLDER_STRING";case"number":case"integer":return e.minimum||0;case"boolean":return!1;case"array":return[];case"object":return this._createTemplateFromSchema(e);default:return null}},_getFieldPath:function(e,t){return e?e+"."+t:t},_isValidDate:function(e){var t=new Date(e);return!isNaN(t.getTime())&&e.match(/^\d{4}-\d{2}-\d{2}$/)},_isValidDateTime:function(e){var t=new Date(e);return!isNaN(t.getTime())}};_H.exports=XQ});var EH=T((rhe,SH)=>{"use strict";g();var hd=Le(),Lf=Ie(),JQ={prepareTokenCommitment:function(e,t){t=t||{},Lf.checkArgument(e&&typeof e=="object","Invalid token");try{var r=this._createCommitment(e,t),i=this._formatOpReturn(r,t),n=this._createTxTemplate(i,t);return{success:!0,commitment:r,opReturnData:i,txTemplate:n,preparedAt:new Date().toISOString(),metadata:{tokenId:e.id,purpose:t.purpose||"legal_token_anchor",version:"LTP.v1"}}}catch(o){return{success:!1,error:o.message}}},prepareBatchCommitment:function(e,t){t=t||{},Lf.checkArgument(Array.isArray(e),"Tokens must be array");try{var r=this._createBatchCommitment(e,t),i=this._formatOpReturn(r,t),n=this._createTxTemplate(i,t);return{success:!0,batchCommitment:r,opReturnData:i,txTemplate:n,tokenCount:e.length,preparedAt:new Date().toISOString(),metadata:{purpose:t.purpose||"legal_token_batch_anchor",version:"LTP.v1"}}}catch(o){return{success:!1,error:o.message}}},verifyTokenAnchor:function(e,t,r){Lf.checkArgument(e&&typeof e=="object","Invalid token"),Lf.checkArgument(typeof t=="string","Transaction ID must be string");try{var i=this._createCommitment(e,{}),n=this._extractOpReturn(r);if(!n)return{valid:!1,error:"No OP_RETURN data found in transaction"};var o=this._verifyCommitment(i,n);return{valid:o,chainVerified:!1,txid:t,commitment:i,anchorData:n,verifiedAt:new Date().toISOString()}}catch(a){return{valid:!1,error:a.message}}},formatRevocation:function(e,t){Lf.checkArgument(typeof e=="string","Token ID must be string"),Lf.checkArgument(t&&typeof t=="object","Invalid revocation data");try{var r={type:"LTP_REVOCATION",tokenId:e,reason:t.reason||"UNSPECIFIED",revokedBy:t.revokedBy||"UNKNOWN",revokedAt:new Date().toISOString(),effectiveDate:t.effectiveDate||new Date().toISOString(),legalBasis:t.legalBasis||null,evidence:t.evidence||null},i=hd.sha256(f.Buffer.from(JSON.stringify(r))).toString("hex");return{success:!0,revocation:r,revocationHash:i,opReturnData:this._formatOpReturn({hash:i,type:"REVOCATION"},{})}}catch(n){return{success:!1,error:n.message}}},_createCommitment:function(e,t){var r=this._canonicalizeToken(e),i={type:"LTP_TOKEN",tokenHash:hd.sha256(f.Buffer.from(r)).toString("hex"),tokenId:e.id,timestamp:new Date().toISOString(),purpose:t.purpose||"legal_token"},n=hd.sha256(f.Buffer.from(JSON.stringify(i))).toString("hex");return{hash:n,data:i,canonical:r}},_createBatchCommitment:function(e,t){var r=[],i=[];e.forEach(function(s){var u=this._createCommitment(s,t);r.push(u.hash),i.push(s.id)}.bind(this));var n=this._createMerkleRoot(r),o={type:"LTP_BATCH",merkleRoot:n,tokenCount:e.length,tokenIds:i,timestamp:new Date().toISOString(),purpose:t.purpose||"batch_anchor"},a=hd.sha256(f.Buffer.from(JSON.stringify(o))).toString("hex");return{hash:a,data:o,merkleRoot:n,tokenHashes:r}},_formatOpReturn:function(e,t){var r=t.prefix||"LTP.v1",i=e.hash;return{prefix:r,data:i,full:r+"."+i,bytes:f.Buffer.from(r+"."+i,"utf8"),size:f.Buffer.from(r+"."+i,"utf8").length}},_createTxTemplate:function(e,t){try{var r={version:1,inputs:[],outputs:[{satoshis:0,script:"OP_RETURN "+e.data}],locktime:0};return t.feeOutput&&r.outputs.push(t.feeOutput),{template:r,opReturn:e,estimatedSize:this._estimateSize(r),instructions:{step1:"Add input UTXOs to cover fees",step2:"Add change output if needed",step3:"Sign transaction with appropriate keys",step4:"Broadcast to BSV network"}}}catch(i){throw new Error("Failed to create transaction template: "+i.message)}},_extractOpReturn:function(e){try{if(!e||!e.outputs)return null;for(var t=0;t<e.outputs.length;t++){var r=e.outputs[t];if(r.script&&r.script.startsWith("OP_RETURN")){var i=r.script.replace("OP_RETURN ","");return{raw:i,decoded:f.Buffer.from(i,"hex").toString("utf8")}}}return null}catch{return null}},_verifyCommitment:function(e,t){try{return!t||!t.decoded?!1:t.decoded.includes(e.hash)}catch{return!1}},_canonicalizeToken:function(e){var t=JSON.parse(JSON.stringify(e));return delete t.proof,delete t.tokenHash,delete t.anchorTx,delete t.anchorBlock,JSON.stringify(this._sortObjectKeys(t))},_createMerkleRoot:function(e){if(e.length===0)return null;if(e.length===1)return e[0];for(var t=e.slice();t.length>1;){for(var r=[],i=0;i<t.length;i+=2){var n=t[i],o=t[i+1]||n,a=f.Buffer.concat([f.Buffer.from(n,"hex"),f.Buffer.from(o,"hex")]),s=hd.sha256(a).toString("hex");r.push(s)}t=r}return t[0]},_estimateSize:function(e){var t=10,r=e.outputs.length*34,i=148;return{base:t+r,withOneInput:t+r+i,bytesPerInput:i}},_sortObjectKeys:function(e){if(Array.isArray(e))return e.map(this._sortObjectKeys.bind(this));if(e!==null&&typeof e=="object"){var t={};return Object.keys(e).sort().forEach(function(r){t[r]=this._sortObjectKeys(e[r])}.bind(this)),t}return e}};SH.exports=JQ});var IH=T((nhe,OH)=>{"use strict";g();var QQ=sr(),Wn=Le(),xH=dn(),eee=gt(),tee=ei(),Ri=Ie(),ree={prepareSignatureProof:function(e,t,r){r=r||{},Ri.checkArgument(e&&typeof e=="object","Invalid token"),Ri.checkArgument(t instanceof tee,"Invalid private key");try{var i=this._canonicalizeForSigning(e),n=Wn.sha256(f.Buffer.from(i)),o=new xH;o.hashbuf=n,o.privkey=t,o.pubkey=t.toPublicKey(),o.sign();var a=o.sig,s={type:"EcdsaSecp256k1Signature2019",created:new Date().toISOString(),verificationMethod:"did:smartledger:"+t.toPublicKey().toString()+"#keys-1",proofPurpose:r.purpose||"assertionMethod",jws:this._createJWS(n,a),proofValue:a.toDER().toString("hex")};return{success:!0,proof:s,tokenHash:n.toString("hex"),canonical:i,signingKey:{publicKey:t.toPublicKey().toString(),keyId:"did:smartledger:"+t.toPublicKey().toString()+"#keys-1"},externalOperations:{storeProof:{endpoint:"POST /proofs/signature",data:{tokenHash:n.toString("hex"),proof:s,signingKey:t.toPublicKey().toString()}},verifyProof:{endpoint:"POST /proofs/verify-signature",data:{tokenHash:n.toString("hex"),signature:a.toDER().toString("hex"),publicKey:t.toPublicKey().toString()}}}}}catch(u){return{success:!1,error:u.message}}},prepareSignatureVerification:function(e,t){try{if(Ri.checkArgument(e&&typeof e=="object","Invalid token"),Ri.checkArgument(typeof t=="string","Public key must be string"),!e.proof)return{success:!1,error:"No proof found in token"};var r=this._canonicalizeForSigning(e),i=Wn.sha256(f.Buffer.from(r)),n=eee.fromDER(f.Buffer.from(e.proof.proofValue,"hex")),o={tokenHash:i.toString("hex"),signature:n.toDER().toString("hex"),publicKey:t,proof:e.proof,canonical:r},a=new xH;a.hashbuf=i,a.sig=n,a.pubkey=QQ.fromString(t);var s=a.verify()===!0;return{success:!0,verification:{valid:s,tokenHash:i.toString("hex"),signatureValid:s,publicKey:t,verifiedAt:new Date().toISOString()},verificationData:o,externalOperations:{recordVerification:{endpoint:"POST /proofs/verification-record",data:{tokenHash:i.toString("hex"),result:s,publicKey:t,verifiedAt:new Date().toISOString()}},auditVerification:{endpoint:"POST /audit/proof-verification",data:{tokenId:e.id,proofType:e.proof.type,result:s,verifier:t}}}}}catch(u){return{success:!1,error:u.message}}},prepareSelectiveDisclosure:function(e,t,r){Ri.checkArgument(e&&typeof e=="object","Invalid token"),Ri.checkArgument(Array.isArray(t),"Revealed fields must be array"),Ri.checkArgument(typeof r=="string","Nonce must be string");try{var i=this._createFieldCommitments(e,r),n=this._createMerkleTree(i),o=[],a=[];t.forEach(function(u){var c=this._getNestedValue(e,u),l=this._findFieldCommitment(i,u);if(l){o.push({path:u,value:c,commitment:l.hash,salt:l.salt});var p=this._generateMerkleProof(n,l.index);a.push({path:u,leafIndex:l.index,proof:p})}}.bind(this));var s={type:"LegalTokenSelectiveDisclosure",created:new Date().toISOString(),proofPurpose:"selectiveDisclosure",verificationMethod:e.proof?e.proof.verificationMethod:null,nonce:r,merkleRoot:n.root,disclosures:o,merkleProofs:a,totalFields:i.length};return{success:!0,proof:s,hiddenFieldCount:i.length-o.length,revealedFieldCount:o.length,externalOperations:{storeDisclosure:{endpoint:"POST /proofs/selective-disclosure",data:{tokenId:e.id,proof:s,merkleRoot:n.root}},verifyDisclosure:{endpoint:"POST /proofs/verify-disclosure",data:{proof:s,expectedNonce:r}},auditDisclosure:{endpoint:"POST /audit/selective-disclosure",data:{tokenId:e.id,revealedFields:t,totalFields:i.length,disclosedAt:new Date().toISOString()}}}}}catch(u){return{success:!1,error:u.message}}},prepareSelectiveDisclosureVerification:function(e,t){try{if(Ri.checkArgument(e&&typeof e=="object","Invalid proof"),Ri.checkArgument(typeof t=="string","Expected nonce must be string"),e.nonce!==t)return{success:!1,error:"Nonce mismatch"};var r=[],i=[];e.disclosures.forEach(function(o,a){var s=e.merkleProofs[a],u=this._hashField(o.path,o.value,o.salt);if(u!==o.commitment){i.push("Invalid commitment for field: "+o.path);return}var c=this._verifyMerkleProof(o.commitment,s.leafIndex,s.proof,e.merkleRoot);c?r.push({path:o.path,value:o.value,verified:!0}):i.push("Invalid Merkle proof for field: "+o.path)}.bind(this));var n={valid:i.length===0,errors:i,disclosures:r,merkleRoot:e.merkleRoot,totalFields:e.totalFields,verifiedAt:new Date().toISOString()};return{success:!0,verification:n,externalOperations:{recordVerification:{endpoint:"POST /proofs/disclosure-verification",data:{proofId:e.id||"unknown",result:n.valid,verifiedFields:r.length,totalFields:e.totalFields,verifiedAt:n.verifiedAt}},auditVerification:{endpoint:"POST /audit/disclosure-verification",data:{merkleRoot:e.merkleRoot,disclosuresVerified:r.length,errors:i.length,result:n.valid}}}}}catch(o){return{success:!1,error:o.message}}},prepareLegalValidityProof:function(e,t,r){Ri.checkArgument(e&&typeof e=="object","Invalid token"),Ri.checkArgument(t&&typeof t=="object","Invalid jurisdiction"),Ri.checkArgument(typeof r=="string","Nonce must be string");try{var i=t.requirements||[],n=[],o=!0;i.forEach(function(s){var u=this._checkLegalRequirement(e,s);n.push(u),u.satisfied||(o=!1)}.bind(this));var a={type:"LegalValidityProof",created:new Date().toISOString(),proofPurpose:"legalValidity",jurisdiction:t.code,nonce:r,valid:o,checks:n,complianceHash:this._hashCompliance(e,t,r)};return{success:!0,proof:a,valid:o,complianceReport:{jurisdiction:t.code,totalRequirements:i.length,satisfiedRequirements:n.filter(s=>s.satisfied).length,failedRequirements:n.filter(s=>!s.satisfied).length,overallCompliance:o},externalOperations:{submitCompliance:{endpoint:"POST /compliance/legal-validity",data:{tokenId:e.id,jurisdiction:t.code,proof:a,complianceReport:{jurisdiction:t.code,totalRequirements:i.length,satisfiedRequirements:n.filter(s=>s.satisfied).length,failedRequirements:n.filter(s=>!s.satisfied).length,overallCompliance:o}}},auditCompliance:{endpoint:"POST /audit/compliance-check",data:{tokenId:e.id,jurisdiction:t.code,result:o,checkedAt:new Date().toISOString(),requirements:n}},notifyRegulator:o?null:{endpoint:"POST /notifications/compliance-failure",data:{tokenId:e.id,jurisdiction:t.code,failedRequirements:n.filter(s=>!s.satisfied)}}}}}catch(s){return{success:!1,error:s.message}}},prepareZeroKnowledgeProof:function(e,t,r){Ri.checkArgument(e&&typeof e=="object","Invalid token"),Ri.checkArgument(t&&typeof t=="object","Invalid statement"),Ri.checkArgument(typeof r=="string","Nonce must be string");try{var i=Wn.sha256(f.Buffer.from(this._canonicalizeForSigning(e)+r)).toString("hex"),n={type:"LegalTokenZKProof",created:new Date().toISOString(),proofPurpose:"zeroKnowledge",statement:{claim:t.claim||"UNSPECIFIED",predicate:t.predicate||"SATISFIES",threshold:t.threshold||null},commitment:i,nonce:r,proofData:this._generateZKProofData(e,t,r)};return{success:!0,proof:n,commitment:i,externalOperations:{storeZKProof:{endpoint:"POST /proofs/zero-knowledge",data:{tokenId:e.id,proof:n,statement:t}},verifyZKProof:{endpoint:"POST /proofs/verify-zk",data:{proof:n,expectedNonce:r}},auditZKProof:{endpoint:"POST /audit/zk-proof",data:{tokenId:e.id,statement:t.claim,proofGenerated:new Date().toISOString()}}}}}catch(o){return{success:!1,error:o.message}}},_generateZKProofData:function(e,t,r){var i={challenge:Wn.sha256(f.Buffer.from(t.claim+r)).toString("hex"),response:Wn.sha256(f.Buffer.from(this._canonicalizeForSigning(e)+t.claim)).toString("hex"),witness:Wn.sha256(f.Buffer.from(r+e.id+t.predicate)).toString("hex")};return i},_createJWS:function(e,t){var r={alg:"ES256K",typ:"JWT"},i=f.Buffer.from(JSON.stringify(r)).toString("base64url"),n=e.toString("base64url"),o=t.toDER().toString("base64url");return i+".."+o},_canonicalizeForSigning:function(e){var t=JSON.parse(JSON.stringify(e));delete t.proof,delete t.tokenHash;var r=this._sortObjectKeys(t);return JSON.stringify(r)},_createFieldCommitments:function(e,t){var r=[],i=0;return this._traverseObject(e,"",function(n,o){if(n!=="proof"&&n!=="tokenHash"){var a=Wn.sha256(f.Buffer.from(t+n+i)).toString("hex"),s=this._hashField(n,o,a);r.push({path:n,value:o,salt:a,hash:s,index:i}),i++}}.bind(this)),r},_hashField:function(e,t,r){var i=e+":"+JSON.stringify(t)+":"+r;return Wn.sha256(f.Buffer.from(i)).toString("hex")},_createMerkleTree:function(e){var t=e.map(function(l){return l.hash});if(t.length===0)return{root:null,levels:[]};for(var r=[t],i=t;i.length>1;){for(var n=[],o=0;o<i.length;o+=2){var a=i[o],s=i[o+1]||a,u=f.Buffer.concat([f.Buffer.from(a,"hex"),f.Buffer.from(s,"hex")]),c=Wn.sha256(u).toString("hex");n.push(c)}r.push(n),i=n}return{root:i[0],levels:r}},_generateMerkleProof:function(e,t){for(var r=[],i=t,n=0;n<e.levels.length-1;n++){var o=e.levels[n],a=i%2===0,s=a?i+1:i-1;s<o.length&&r.push({hash:o[s],isLeft:!a}),i=Math.floor(i/2)}return r},_verifyMerkleProof:function(e,t,r,i){for(var n=e,o=t,a=0;a<r.length;a++){var s=r[a],u=o%2===0,c;s.isLeft?c=f.Buffer.concat([f.Buffer.from(s.hash,"hex"),f.Buffer.from(n,"hex")]):c=f.Buffer.concat([f.Buffer.from(n,"hex"),f.Buffer.from(s.hash,"hex")]),n=Wn.sha256(c).toString("hex"),o=Math.floor(o/2)}return n===i},_traverseObject:function(e,t,r){Array.isArray(e)?e.forEach(function(i,n){var o=t+"["+n+"]";this._traverseObject(i,o,r)}.bind(this)):e!==null&&typeof e=="object"?Object.keys(e).forEach(function(i){var n=t?t+"."+i:i;this._traverseObject(e[i],n,r)}.bind(this)):r(t,e)},_getNestedValue:function(e,t){return t.split(".").reduce(function(r,i){return r&&r[i]},e)},_findFieldCommitment:function(e,t){return e.find(function(r){return r.path===t})},_checkLegalRequirement:function(e,t){switch(t.type){case"field_present":var r=this._getNestedValue(e,t.field);return{requirement:t.type,field:t.field,satisfied:r!=null};case"field_value":var r=this._getNestedValue(e,t.field);return{requirement:t.type,field:t.field,satisfied:r===t.expectedValue};case"temporal_validity":var i=new Date,n=new Date(e.issuanceDate);return{requirement:t.type,satisfied:n<=i};default:return{requirement:t.type,satisfied:!1,error:"Unknown requirement type"}}},_hashCompliance:function(e,t,r){var i={tokenId:e.id,jurisdiction:t.code,nonce:r,timestamp:new Date().toISOString()};return Wn.sha256(f.Buffer.from(JSON.stringify(i))).toString("hex")},_sortObjectKeys:function(e){if(Array.isArray(e))return e.map(this._sortObjectKeys.bind(this));if(e!==null&&typeof e=="object"){var t={};return Object.keys(e).sort().forEach(function(r){t[r]=this._sortObjectKeys(e[r])}.bind(this)),t}return e}};OH.exports=ree});var PH=T((uhe,TH)=>{"use strict";g();var dd=Le(),ahe=Ni(),she=zt(),ji=Ie(),AH=fd(),iee={prepareRegistry:function(e){e=e||{},ji.checkArgument(typeof e=="object","Config must be object");var t={id:e.id||this._generateRegistryId(),name:e.name||"Legal Token Registry",jurisdiction:e.jurisdiction||"GLOBAL",authority:e.authority||null,created:new Date().toISOString(),version:"1.0.0",config:{allowPublicRegistration:e.allowPublicRegistration||!1,requireApproval:e.requireApproval||!0,enableRevocation:e.enableRevocation!==!1,enableAuditTrail:e.enableAuditTrail!==!1,retentionPeriod:e.retentionPeriod||"7Y",complianceLevel:e.complianceLevel||"STANDARD"},dataStructure:{tokens:"Map<tokenId, registrationRecord>",revocations:"Map<tokenId, revocationRecord>",auditLog:"Array<auditEntry>",statistics:{totalTokens:0,activeTokens:0,revokedTokens:0,registrations:0}},externalStorage:{required:!0,type:"database_or_blockchain",endpoints:{store:"POST /registry/{id}/tokens",retrieve:"GET /registry/{id}/tokens/{tokenId}",search:"GET /registry/{id}/search",revoke:"POST /registry/{id}/revocations"}}},r=this._prepareAuditEntry({action:"REGISTRY_CREATED",actor:e.authority,timestamp:t.created,metadata:{jurisdiction:t.jurisdiction,config:t.config}});return{success:!0,registry:t,initialAudit:r,instructions:{step1:"Store registry configuration in external system",step2:"Initialize token storage with provided data structure",step3:"Set up audit logging with provided templates",step4:"Configure external endpoints for registry operations"}}},prepareTokenRegistration:function(e,t,r){r=r||{},ji.checkArgument(e&&typeof e=="object","Invalid token"),ji.checkArgument(t&&typeof t=="object","Invalid registry config");try{var i=this._validateTokenForRegistration(e,t);if(!i.valid)return{success:!1,error:"Token validation failed: "+i.error};var n={tokenId:e.id,tokenHash:this._hashToken(e),token:e,status:t.requireApproval?"PENDING":"ACTIVE",registeredBy:r.registeredBy||"UNKNOWN",registeredAt:new Date().toISOString(),approvedBy:null,approvedAt:null,metadata:r.metadata||{},compliance:{jurisdiction:e.jurisdiction||t.jurisdiction,level:this._calculateComplianceLevel(e),checks:i.checks||[]}},o=this._prepareAuditEntry({action:"TOKEN_REGISTERED",actor:r.registeredBy,tokenId:e.id,timestamp:n.registeredAt,metadata:{status:n.status,tokenType:e.type,compliance:n.compliance}});return{success:!0,registrationRecord:n,auditEntry:o,registrationId:this._generateRegistrationId(e.id),validation:i,externalOperations:{store:{endpoint:"POST /registry/"+t.id+"/tokens",data:n},audit:{endpoint:"POST /registry/"+t.id+"/audit",data:o}}}}catch(a){return{success:!1,error:a.message}}},prepareTokenApproval:function(e,t,r){try{ji.checkArgument(typeof e=="string","Token ID must be string"),ji.checkArgument(typeof t=="string","Approver must be string"),ji.checkArgument(r&&typeof r=="object","Invalid registry config");var i={tokenId:e,status:"ACTIVE",approvedBy:t,approvedAt:new Date().toISOString()},n=this._prepareAuditEntry({action:"TOKEN_APPROVED",actor:t,tokenId:e,timestamp:i.approvedAt});return{success:!0,approvalData:i,auditEntry:n,externalOperations:{update:{endpoint:"PUT /registry/"+r.id+"/tokens/"+e+"/status",data:i},audit:{endpoint:"POST /registry/"+r.id+"/audit",data:n}}}}catch(o){return{success:!1,error:o.message}}},prepareTokenRevocation:function(e,t,r){try{if(ji.checkArgument(typeof e=="string","Token ID must be string"),ji.checkArgument(t&&typeof t=="object","Invalid revocation"),ji.checkArgument(r&&typeof r=="object","Invalid registry config"),!r.enableRevocation)return{success:!1,error:"Revocation is disabled for this registry"};var i={tokenId:e,reason:t.reason||"UNSPECIFIED",revokedBy:t.revokedBy||"UNKNOWN",revokedAt:new Date().toISOString(),effectiveDate:t.effectiveDate||new Date().toISOString(),legalBasis:t.legalBasis||null,evidence:t.evidence||null,revocationHash:this._generateRevocationHash(e,t)},n={tokenId:e,status:"REVOKED",revokedAt:i.revokedAt,revocationReason:i.reason},o=this._prepareAuditEntry({action:"TOKEN_REVOKED",actor:t.revokedBy,tokenId:e,timestamp:i.revokedAt,metadata:{reason:i.reason,legalBasis:i.legalBasis}});return{success:!0,revocationRecord:i,statusUpdate:n,auditEntry:o,revocationId:this._generateRevocationId(e),externalOperations:{storeRevocation:{endpoint:"POST /registry/"+r.id+"/revocations",data:i},updateStatus:{endpoint:"PUT /registry/"+r.id+"/tokens/"+e+"/status",data:n},audit:{endpoint:"POST /registry/"+r.id+"/audit",data:o}}}}catch(a){return{success:!1,error:a.message}}},prepareTokenStatusQuery:function(e,t){try{return ji.checkArgument(typeof e=="string","Token ID must be string"),ji.checkArgument(t&&typeof t=="object","Invalid registry config"),{success:!0,query:{tokenId:e,registryId:t.id},externalOperations:{retrieve:{endpoint:"GET /registry/"+t.id+"/tokens/"+e,method:"GET"},checkRevocation:{endpoint:"GET /registry/"+t.id+"/revocations/"+e,method:"GET"}},expectedResponse:{found:"boolean",status:"string (PENDING|ACTIVE|REVOKED)",registeredAt:"ISO datetime",registeredBy:"string",approvedAt:"ISO datetime or null",approvedBy:"string or null",revokedAt:"ISO datetime or null",revocationReason:"string or null",compliance:"object",revocation:"object or null"}}}catch(r){return{success:!1,error:r.message}}},prepareTokenSearch:function(e,t){e=e||{};try{ji.checkArgument(t&&typeof t=="object","Invalid registry config");var r=[];e.status&&r.push("status="+encodeURIComponent(e.status)),e.type&&r.push("type="+encodeURIComponent(e.type)),e.registeredBy&&r.push("registeredBy="+encodeURIComponent(e.registeredBy)),e.jurisdiction&&r.push("jurisdiction="+encodeURIComponent(e.jurisdiction)),e.dateFrom&&r.push("dateFrom="+encodeURIComponent(e.dateFrom)),e.dateTo&&r.push("dateTo="+encodeURIComponent(e.dateTo)),e.includeTokens&&r.push("includeTokens=true"),e.sortBy&&r.push("sortBy="+encodeURIComponent(e.sortBy)),e.sortOrder&&r.push("sortOrder="+encodeURIComponent(e.sortOrder));var i=e.offset||0,n=e.limit||100;r.push("offset="+i),r.push("limit="+n);var o=r.length>0?"?"+r.join("&"):"";return{success:!0,searchCriteria:e,externalOperations:{search:{endpoint:"GET /registry/"+t.id+"/search"+o,method:"GET"}},expectedResponse:{success:"boolean",results:"Array<tokenRecord>",totalCount:"number",totalRegistrations:"number",offset:"number",limit:"number",hasMore:"boolean"}}}catch(a){return{success:!1,error:a.message}}},prepareStatisticsQuery:function(e){return ji.checkArgument(e&&typeof e=="object","Invalid registry config"),{success:!0,query:{registryId:e.id},externalOperations:{getStatistics:{endpoint:"GET /registry/"+e.id+"/statistics",method:"GET"}},expectedResponse:{id:"string",name:"string",jurisdiction:"string",created:"ISO datetime",statistics:{totalTokens:"number",activeTokens:"number",revokedTokens:"number",registrations:"number"},auditEntries:"number",lastActivity:"ISO datetime"}}},prepareAuditLogQuery:function(e,t){if(t=t||{},ji.checkArgument(e&&typeof e=="object","Invalid registry config"),!e.enableAuditTrail)return{success:!1,error:"Audit trail is disabled"};var r=[];t.action&&r.push("action="+encodeURIComponent(t.action)),t.actor&&r.push("actor="+encodeURIComponent(t.actor)),t.tokenId&&r.push("tokenId="+encodeURIComponent(t.tokenId)),t.dateFrom&&r.push("dateFrom="+encodeURIComponent(t.dateFrom)),t.dateTo&&r.push("dateTo="+encodeURIComponent(t.dateTo));var i=t.offset||0,n=t.limit||100;r.push("offset="+i),r.push("limit="+n);var o=r.length>0?"?"+r.join("&"):"";return{success:!0,auditOptions:t,externalOperations:{getAuditLog:{endpoint:"GET /registry/"+e.id+"/audit"+o,method:"GET"}},expectedResponse:{success:"boolean",entries:"Array<auditEntry>",totalEntries:"number",offset:"number",limit:"number",hasMore:"boolean"}}},_generateRegistryId:function(){return"reg_"+AH.randomHex(16)},_generateRegistrationId:function(e){var t="reg_"+e+"_"+Date.now();return dd.sha256(f.Buffer.from(t)).toString("hex").substring(0,16)},_generateRevocationId:function(e){var t="rev_"+e+"_"+Date.now();return dd.sha256(f.Buffer.from(t)).toString("hex").substring(0,16)},_hashToken:function(e){var t=JSON.parse(JSON.stringify(e));return delete t.proof,delete t.tokenHash,dd.sha256(f.Buffer.from(JSON.stringify(t))).toString("hex")},_generateRevocationHash:function(e,t){var r=e+(t.reason||"")+(t.revokedBy||"")+Date.now();return dd.sha256(f.Buffer.from(r)).toString("hex")},_validateTokenForRegistration:function(e,t){var r=[],i=!0;return e.id?r.push({field:"id",valid:!0}):(r.push({field:"id",valid:!1,error:"Missing token ID"}),i=!1),e.type?r.push({field:"type",valid:!0}):(r.push({field:"type",valid:!1,error:"Missing token type"}),i=!1),e.issuanceDate?r.push({field:"issuanceDate",valid:!0}):(r.push({field:"issuanceDate",valid:!1,error:"Missing issuance date"}),i=!1),e.proof?r.push({field:"proof",valid:!0}):(r.push({field:"proof",valid:!1,error:"Missing cryptographic proof"}),i=!1),{valid:i,checks:r}},_calculateComplianceLevel:function(e){var t="BASIC";return e.proof&&e.proof.type&&(t="STANDARD"),e.jurisdiction&&e.legalBasis&&(t="ENHANCED"),e.attestations&&e.attestations.length>0&&(t="PREMIUM"),t},_prepareAuditEntry:function(e){var t={id:this._generateAuditId(),action:e.action,actor:e.actor||"SYSTEM",tokenId:e.tokenId||null,timestamp:e.timestamp||new Date().toISOString(),metadata:e.metadata||{},hash:this._generateAuditHash(e)};return t},_generateAuditId:function(){return"audit_"+AH.randomHex(32)},_generateAuditHash:function(e){var t=(e.action||"")+(e.actor||"")+(e.tokenId||"")+(e.timestamp||"");return dd.sha256(f.Buffer.from(t)).toString("hex").substring(0,16)}};TH.exports=iee});var NH=T((fhe,BH)=>{"use strict";g();var vE=sr(),yE=Le(),RH=dn(),nee=gt(),kH=ei(),Ji=Ie(),oee=fd();function aee(e,t){if(t=t||{},t.issuerPublicKey)return t.issuerPublicKey instanceof vE?t.issuerPublicKey:vE.fromString(t.issuerPublicKey);var r=e&&e.issuer;if(typeof r!="string")return null;try{var i=r.split("#")[0].split(":")[2];return i?vE.fromString(i):null}catch{return null}}var Lv={CORRELATIVE_OBLIGATION:"CorrelativeObligation",CONTRACTUAL_OBLIGATION:"ContractualObligation",PAYMENT_OBLIGATION:"PaymentObligation",DELIVERY_OBLIGATION:"DeliveryObligation",PERFORMANCE_OBLIGATION:"PerformanceObligation",MAINTENANCE_OBLIGATION:"MaintenanceObligation",COMPLIANCE_OBLIGATION:"ComplianceObligation",REPORTING_OBLIGATION:"ReportingObligation",CONFIDENTIALITY_OBLIGATION:"ConfidentialityObligation",NON_COMPETE_OBLIGATION:"NonCompeteObligation",INDEMNIFICATION_OBLIGATION:"IndemnificationObligation",WARRANTY_OBLIGATION:"WarrantyObligation",SUPPORT_OBLIGATION:"SupportObligation",REGULATORY_OBLIGATION:"RegulatoryObligation",FIDUCIARY_OBLIGATION:"FiduciaryObligation"},Mf={CRITICAL:"CRITICAL",HIGH:"HIGH",MEDIUM:"MEDIUM",LOW:"LOW",DEFERRED:"DEFERRED"},zi={PENDING:"PENDING",ACTIVE:"ACTIVE",IN_PROGRESS:"IN_PROGRESS",COMPLETED:"COMPLETED",OVERDUE:"OVERDUE",BREACHED:"BREACHED",WAIVED:"WAIVED",TERMINATED:"TERMINATED"},Mv={prepareObligationToken:function(e,t,r,i,n,o){o=o||{},Ji.checkArgument(typeof e=="string","Obligation type must be string"),Ji.checkArgument(typeof t=="string","Issuer DID must be string"),Ji.checkArgument(typeof r=="string","Obligor DID must be string"),Ji.checkArgument(i&&typeof i=="object","Obligation must be object"),Ji.checkArgument(n instanceof kH,"Invalid issuer private key");var a=Object.values(Lv);Ji.checkArgument(a.includes(e),"Invalid obligation type: "+e);try{var s={"@context":["https://www.w3.org/2018/credentials/v1","https://smartledger.technology/contexts/ltp/v1"],id:"urn:uuid:"+this._generateUUID(),type:["VerifiableCredential","LegalObligationToken",e],issuer:t,issuanceDate:new Date().toISOString(),credentialSubject:{id:r,obligationType:e,obligation:i,jurisdiction:o.jurisdiction||"US",priority:o.priority||Mf.MEDIUM,status:zi.PENDING,dueDate:o.dueDate||null,effectiveDate:o.effectiveDate||new Date().toISOString(),expirationDate:o.expirationDate||null,correlativeRight:o.correlativeRight||null,rightHolder:o.rightHolder||null,enforceable:o.enforceable!==!1,penalties:o.penalties||null,remedies:o.remedies||null}};o.metadata&&(s.credentialSubject.metadata=o.metadata);var u=this._signToken(s,n);return{success:!0,obligationToken:u,tokenHash:u.tokenHash,metadata:{type:e,issuer:t,obligor:r,priority:s.credentialSubject.priority,status:s.credentialSubject.status,jurisdiction:s.credentialSubject.jurisdiction,dueDate:s.credentialSubject.dueDate,correlativeRight:s.credentialSubject.correlativeRight},externalOperations:{storeToken:{endpoint:"POST /obligations/tokens",data:{token:u,metadata:{type:e,issuer:t,obligor:r,priority:s.credentialSubject.priority,status:s.credentialSubject.status,jurisdiction:s.credentialSubject.jurisdiction,dueDate:s.credentialSubject.dueDate,correlativeRight:s.credentialSubject.correlativeRight}}},indexToken:{endpoint:"POST /obligations/index",data:{tokenId:u.id,tokenHash:u.tokenHash,type:e,issuer:t,obligor:r,issuedAt:u.issuanceDate,dueDate:s.credentialSubject.dueDate,priority:s.credentialSubject.priority}},notifyObligor:{endpoint:"POST /notifications/obligation-issued",data:{tokenId:u.id,issuer:t,obligor:r,obligationType:e,dueDate:s.credentialSubject.dueDate,priority:s.credentialSubject.priority}},scheduleReminders:s.credentialSubject.dueDate?{endpoint:"POST /obligations/schedule-reminders",data:{tokenId:u.id,obligor:r,dueDate:s.credentialSubject.dueDate,reminderSchedule:o.reminderSchedule||["7d","3d","1d"]}}:null}}}catch(c){return{success:!1,error:c.message}}},prepareObligationVerification:function(e,t){t=t||{};try{var r=[],i=[];this._validateTokenStructure(e,r),this._verifyTokenSignature(e,r,t),this._validateTokenTemporal(e,r,i),this._validateObligationType(e,r),this._validateObligationStatus(e,r,i),this._validateObligationPriority(e,i);var n={valid:r.length===0,errors:r,warnings:i,issuerDID:e.issuer,obligorDID:e.credentialSubject?e.credentialSubject.id:null,obligationType:e.credentialSubject?e.credentialSubject.obligationType:null,status:e.credentialSubject?e.credentialSubject.status:null,priority:e.credentialSubject?e.credentialSubject.priority:null,isOverdue:this._checkIfOverdue(e),verifiedAt:new Date().toISOString()};return{success:!0,verification:n,externalOperations:{recordVerification:{endpoint:"POST /obligations/verification-record",data:{tokenId:e.id,result:n.valid,errors:r,warnings:i,verifiedAt:n.verifiedAt,isOverdue:n.isOverdue}},auditVerification:{endpoint:"POST /audit/obligation-verification",data:{tokenId:e.id,obligationType:n.obligationType,issuer:n.issuerDID,obligor:n.obligorDID,result:n.valid,verifiedAt:n.verifiedAt}},updateStatus:n.isOverdue&&e.credentialSubject.status===zi.ACTIVE?{endpoint:"PUT /obligations/tokens/"+e.id+"/status",data:{status:zi.OVERDUE,updatedAt:n.verifiedAt,reason:"Due date passed"}}:null}}}catch(o){return{success:!1,error:"Verification preparation failed: "+o.message}}},prepareObligationFulfillment:function(e,t,r,i){i=i||{},Ji.checkArgument(e&&typeof e=="object","Invalid token"),Ji.checkArgument(t&&typeof t=="object","Invalid fulfillment"),Ji.checkArgument(r instanceof kH,"Invalid obligor key");try{var n=this.prepareObligationVerification(e,{});if(!n.success||!n.verification.valid)return{success:!1,error:"Cannot fulfill invalid obligation: "+n.verification.errors.join(", ")};if(e.credentialSubject.status===zi.COMPLETED)return{success:!1,error:"Obligation already fulfilled"};if(e.credentialSubject.status===zi.TERMINATED)return{success:!1,error:"Obligation has been terminated"};var o={"@context":["https://www.w3.org/2018/credentials/v1","https://smartledger.technology/contexts/ltp/v1"],id:"urn:uuid:"+this._generateUUID(),type:["VerifiableCredential","ObligationFulfillment"],issuer:e.credentialSubject.id,issuanceDate:new Date().toISOString(),credentialSubject:{id:e.id,fulfillmentType:t.type||"FULL_FULFILLMENT",fulfillmentDate:new Date().toISOString(),evidence:t.evidence||null,description:t.description||"",completionPercentage:t.completionPercentage||100,attestations:t.attestations||[],notes:t.notes||null}},a=this._signToken(o,r),s=o.credentialSubject.completionPercentage>=100?zi.COMPLETED:zi.IN_PROGRESS;return{success:!0,fulfillmentRecord:a,newStatus:s,fulfillmentId:a.id,externalOperations:{recordFulfillment:{endpoint:"POST /obligations/fulfillments",data:{obligationId:e.id,fulfillmentRecord:a,obligor:e.credentialSubject.id,fulfillmentDate:o.credentialSubject.fulfillmentDate,completionPercentage:o.credentialSubject.completionPercentage}},updateStatus:{endpoint:"PUT /obligations/tokens/"+e.id+"/status",data:{status:s,fulfillmentId:a.id,updatedAt:o.credentialSubject.fulfillmentDate,completionPercentage:o.credentialSubject.completionPercentage}},notifyRightHolder:e.credentialSubject.rightHolder?{endpoint:"POST /notifications/obligation-fulfilled",data:{obligationId:e.id,fulfillmentId:a.id,obligor:e.credentialSubject.id,rightHolder:e.credentialSubject.rightHolder,completionPercentage:o.credentialSubject.completionPercentage,newStatus:s}}:null,auditFulfillment:{endpoint:"POST /audit/obligation-fulfillment",data:{obligationId:e.id,fulfillmentId:a.id,obligor:e.credentialSubject.id,fulfilledAt:o.credentialSubject.fulfillmentDate,completionPercentage:o.credentialSubject.completionPercentage}}}}}catch(u){return{success:!1,error:u.message}}},prepareObligationBreachAssessment:function(e,t,r){Ji.checkArgument(e&&typeof e=="object","Invalid token"),Ji.checkArgument(t&&typeof t=="object","Invalid breach details"),Ji.checkArgument(r&&typeof r=="object","Invalid assessor");try{var i={"@context":["https://www.w3.org/2018/credentials/v1","https://smartledger.technology/contexts/ltp/v1"],id:"urn:uuid:"+this._generateUUID(),type:["VerifiableCredential","ObligationBreachAssessment"],issuer:r.did||r.id,issuanceDate:new Date().toISOString(),credentialSubject:{id:e.id,breachType:t.type||"MATERIAL_BREACH",breachDate:t.date||new Date().toISOString(),description:t.description||"",severity:t.severity||"MODERATE",evidence:t.evidence||[],assessor:{did:r.did||r.id,name:r.name||"Unknown",authority:r.authority||null,jurisdiction:r.jurisdiction||null},damages:t.damages||null,recommendedRemedies:t.recommendedRemedies||[],assessmentDate:new Date().toISOString()}},n=yE.sha256(f.Buffer.from(JSON.stringify(i))).toString("hex");return i.credentialSubject.assessmentHash=n,{success:!0,breachAssessment:i,breachId:i.id,severity:t.severity||"MODERATE",externalOperations:{recordBreach:{endpoint:"POST /obligations/breaches",data:{obligationId:e.id,breachAssessment:i,obligor:e.credentialSubject.id,rightHolder:e.credentialSubject.rightHolder,breachDate:t.date||new Date().toISOString(),severity:t.severity||"MODERATE"}},updateStatus:{endpoint:"PUT /obligations/tokens/"+e.id+"/status",data:{status:zi.BREACHED,breachId:i.id,breachDate:t.date||new Date().toISOString(),updatedAt:new Date().toISOString()}},notifyParties:{endpoint:"POST /notifications/obligation-breached",data:{obligationId:e.id,breachId:i.id,obligor:e.credentialSubject.id,rightHolder:e.credentialSubject.rightHolder,breachType:t.type||"MATERIAL_BREACH",severity:t.severity||"MODERATE"}},escalateBreach:t.severity==="CRITICAL"?{endpoint:"POST /legal/escalate-breach",data:{obligationId:e.id,breachId:i.id,severity:t.severity,jurisdiction:e.credentialSubject.jurisdiction}}:null,auditBreach:{endpoint:"POST /audit/obligation-breach",data:{obligationId:e.id,breachId:i.id,obligor:e.credentialSubject.id,assessedAt:i.credentialSubject.assessmentDate,severity:t.severity||"MODERATE"}}}}}catch(o){return{success:!1,error:o.message}}},prepareObligationMonitoringReport:function(e,t){t=t||{},Ji.checkArgument(Array.isArray(e),"Obligations must be array");try{var r={reportId:"rpt_"+this._generateUUID(),generatedAt:new Date().toISOString(),criteria:t,summary:{totalObligations:e.length,byStatus:{},byPriority:{},byType:{},overdue:0,dueSoon:0,completed:0},obligations:[],alerts:[],recommendations:[]},i=new Date,n=new Date(i.getTime()+10080*60*1e3);return e.forEach(function(o){var a={id:o.id,type:o.credentialSubject.obligationType,status:o.credentialSubject.status,priority:o.credentialSubject.priority,obligor:o.credentialSubject.id,dueDate:o.credentialSubject.dueDate,isOverdue:this._checkIfOverdue(o),isDueSoon:!1};if(o.credentialSubject.dueDate){var s=new Date(o.credentialSubject.dueDate);a.isDueSoon=s<=n&&s>i}r.summary.byStatus[a.status]=(r.summary.byStatus[a.status]||0)+1,r.summary.byPriority[a.priority]=(r.summary.byPriority[a.priority]||0)+1,r.summary.byType[a.type]=(r.summary.byType[a.type]||0)+1,a.isOverdue&&r.summary.overdue++,a.isDueSoon&&r.summary.dueSoon++,a.status===zi.COMPLETED&&r.summary.completed++,a.isOverdue&&a.priority===Mf.CRITICAL&&r.alerts.push({type:"CRITICAL_OVERDUE",obligationId:o.id,message:"Critical obligation is overdue",priority:"HIGH"}),a.isDueSoon&&a.priority===Mf.HIGH&&r.alerts.push({type:"HIGH_PRIORITY_DUE_SOON",obligationId:o.id,message:"High priority obligation due soon",priority:"MEDIUM"}),r.obligations.push(a)}.bind(this)),r.summary.overdue>0&&r.recommendations.push({type:"OVERDUE_MANAGEMENT",message:"Consider prioritizing overdue obligations",count:r.summary.overdue}),r.summary.dueSoon>5&&r.recommendations.push({type:"WORKLOAD_MANAGEMENT",message:"High number of obligations due soon - consider workload distribution",count:r.summary.dueSoon}),{success:!0,report:r,externalOperations:{storeReport:{endpoint:"POST /obligations/monitoring-reports",data:{report:r,generatedAt:r.generatedAt}},sendAlerts:r.alerts.length>0?{endpoint:"POST /notifications/obligation-alerts",data:{reportId:r.reportId,alerts:r.alerts,summary:r.summary}}:null,updateDashboard:{endpoint:"PUT /dashboard/obligation-metrics",data:{summary:r.summary,lastUpdated:r.generatedAt}}}}}catch(o){return{success:!1,error:o.message}}},getObligationTypes:function(){return Lv},getObligationPriority:function(){return Mf},getObligationStatus:function(){return zi},_signToken:function(e,t){var r=this._canonicalizeToken(e),i=yE.sha256(f.Buffer.from(r)),n=new RH;n.hashbuf=i,n.privkey=t,n.pubkey=t.toPublicKey(),n.sign();var o=n.sig,a={type:"EcdsaSecp256k1Signature2019",created:new Date().toISOString(),verificationMethod:"did:smartledger:"+t.toPublicKey().toString()+"#keys-1",proofPurpose:"assertionMethod",jws:this._createJWS(i,o)},s=JSON.parse(JSON.stringify(e));return s.proof=a,s.tokenHash=i.toString("hex"),s},_createJWS:function(e,t){var r={alg:"ES256K",typ:"JWT"},i=f.Buffer.from(JSON.stringify(r)).toString("base64url"),n=e.toString("base64url"),o=t.toDER().toString("base64url");return i+".."+o},_canonicalizeToken:function(e){var t=JSON.parse(JSON.stringify(e));return delete t.proof,delete t.tokenHash,JSON.stringify(this._sortObjectKeys(t))},_sortObjectKeys:function(e){if(Array.isArray(e))return e.map(this._sortObjectKeys.bind(this));if(e!==null&&typeof e=="object"){var t={};return Object.keys(e).sort().forEach(function(r){t[r]=this._sortObjectKeys(e[r])}.bind(this)),t}return e},_validateTokenStructure:function(e,t){e["@context"]||t.push("Missing @context"),e.id||t.push("Missing id"),(!e.type||!Array.isArray(e.type))&&t.push("Missing or invalid type"),e.issuer||t.push("Missing issuer"),e.issuanceDate||t.push("Missing issuanceDate"),e.credentialSubject||t.push("Missing credentialSubject"),e.proof||t.push("Missing proof")},_verifyTokenSignature:function(e,t,r){try{if(!e.proof||!e.proof.jws){t.push("Missing signature proof");return}var i=this._canonicalizeToken(e),n=yE.sha256(f.Buffer.from(i));if(e.tokenHash&&e.tokenHash!==n.toString("hex")){t.push("Token hash mismatch");return}var o=aee(e,r);if(!o){t.push("Signature not verified: issuer public key could not be resolved from token.issuer; pass options.issuerPublicKey");return}var a=e.proof.jws.split(".");if(a.length!==3||!a[2]){t.push("Malformed JWS");return}var s=nee.fromDER(f.Buffer.from(a[2],"base64url")),u=new RH;u.hashbuf=n,u.sig=s,u.pubkey=o,u.verify()!==!0&&t.push("Signature verification failed")}catch(c){t.push("Signature verification failed: "+c.message)}},_validateTokenTemporal:function(e,t,r){var i=new Date,n=new Date(e.issuanceDate);if(n>i&&t.push("Token issued in the future"),e.credentialSubject.effectiveDate){var o=new Date(e.credentialSubject.effectiveDate);i<o&&r.push("Obligation not yet effective")}if(e.credentialSubject.expirationDate){var a=new Date(e.credentialSubject.expirationDate);i>a&&t.push("Obligation expired")}},_validateObligationType:function(e,t){if(!e.credentialSubject.obligationType){t.push("Missing obligationType");return}var r=Object.values(Lv);r.includes(e.credentialSubject.obligationType)||t.push("Invalid obligation type: "+e.credentialSubject.obligationType)},_validateObligationStatus:function(e,t,r){if(!e.credentialSubject.status){t.push("Missing status");return}var i=Object.values(zi);i.includes(e.credentialSubject.status)||t.push("Invalid obligation status: "+e.credentialSubject.status),this._checkIfOverdue(e)&&e.credentialSubject.status===zi.ACTIVE&&r.push("Obligation is overdue but status is still ACTIVE")},_validateObligationPriority:function(e,t){if(e.credentialSubject.priority){var r=Object.values(Mf);r.includes(e.credentialSubject.priority)||t.push("Invalid obligation priority: "+e.credentialSubject.priority)}},_checkIfOverdue:function(e){if(!e.credentialSubject.dueDate)return!1;var t=new Date,r=new Date(e.credentialSubject.dueDate);return t>r&&e.credentialSubject.status!==zi.COMPLETED},_generateUUID:function(){return oee.uuid4()}};Mv.ObligationTypes=Lv;Mv.ObligationPriority=Mf;Mv.ObligationStatus=zi;BH.exports=Mv});var LH=T((hhe,CH)=>{"use strict";g();var Du=bH(),Dv=wH(),pd=EH(),bE=IH(),Uo=PH(),see=NH(),_E=ei(),Qi=Ie(),lt=function(e){return this instanceof lt?(this.config=e||{},this.registry=null,this.config.registry&&(this.registry=Uo.createRegistry(this.config.registry)),this):new lt(e)};lt.prototype.createRightToken=function(e,t,r){Qi.checkArgument(e&&typeof e=="object","Invalid right data"),Qi.checkArgument(t instanceof _E,"Invalid private key"),r=r||{};try{var i=Du.create(e.type,e.owner,e.owner,e,t,r);if(!i)return{success:!1,error:"Failed to create token"};if(r.addProof!==!1&&(i=Du._signToken(i,t)),r.anchor){var n=pd.anchorToken(i,r.anchor);n.success&&(i.anchorTx=n.txid,i.anchorBlock=n.blockHeight)}if(this.registry&&r.register!==!1){var o=Uo.registerToken(this.registry,i,{registeredBy:r.registeredBy||"SYSTEM"});o.success&&(i.registrationId=o.registrationId,i.registrationStatus=o.status)}return{success:!0,token:i,type:"LegalRightToken"}}catch(a){return{success:!1,error:a.message}}};lt.prototype.validateClaim=function(e,t){return Dv.validate(e,t)};lt.prototype.createSelectiveDisclosure=function(e,t,r){return bE.prepareSelectiveDisclosure(e,t,r)};lt.prototype.verifyToken=function(e,t){return!e||!e.proof?{valid:!1,error:"No proof found in token"}:Du.verifyToken(e,t)};lt.prototype.transferRight=function(e,t,r,i){Qi.checkArgument(e&&typeof e=="object","Invalid token"),Qi.checkArgument(typeof t=="string","New owner must be string"),Qi.checkArgument(r instanceof _E,"Invalid owner key"),i=i||{};try{var n=this.verifyToken(e,r.toPublicKey().toString());if(!n.valid)return{success:!1,error:"Invalid token or ownership proof"};var o=Du.prepareRightTokenTransfer(e,t,r,i);if(!o.success)return{success:!1,error:o.error};var a=o.newToken,s=o.transferProof;if(i.anchor){var u=pd.anchorToken(a,i.anchor);u.success&&(a.transferAnchorTx=u.txid)}if(this.registry){var c=Uo.registerToken(this.registry,a,{registeredBy:i.registeredBy||t,metadata:{transferFrom:e.owner,transferTo:t,originalTokenId:e.id}});c.success&&(a.registrationId=c.registrationId)}return{success:!0,token:a,transferId:s.id,transferredAt:s.issuanceDate,transferProof:s}}catch(l){return{success:!1,error:l.message}}};lt.prototype.createObligation=function(e,t,r){Qi.checkArgument(e&&typeof e=="object","Invalid right token"),Qi.checkArgument(t&&typeof t=="object","Invalid obligation data"),Qi.checkArgument(r instanceof _E,"Invalid private key");try{var i=Du.prepareObligationToken(e,t.obligor,t,r);return i.success?{success:!0,obligation:i.obligationToken,rightTokenId:e.id}:{success:!1,error:i.error}}catch(n){return{success:!1,error:n.message}}};lt.prototype.revokeToken=function(e,t,r){return Qi.checkArgument(typeof e=="string","Token ID must be string"),Qi.checkArgument(t&&typeof t=="object","Invalid revocation data"),Qi.checkArgument(typeof r=="string","Authority must be string"),this.registry?Uo.revokeToken(this.registry,e,{reason:t.reason,revokedBy:r,legalBasis:t.legalBasis,evidence:t.evidence}):{success:!1,error:"No registry available for revocation"}};lt.prototype.checkTokenStatus=function(e){return Qi.checkArgument(typeof e=="string","Token ID must be string"),this.registry?Uo.checkTokenStatus(this.registry,e):{found:!1,error:"No registry available"}};lt.prototype.searchTokens=function(e){return this.registry?Uo.searchTokens(this.registry,e):{success:!1,error:"No registry available"}};lt.prototype.getRegistryStats=function(){return this.registry?Uo.getStatistics(this.registry):{error:"No registry available"}};lt.prototype.createLegalValidityProof=function(e,t,r){return bE.prepareLegalValidityProof(e,t,r)};lt.prototype.anchorTokenBatch=function(e,t){return pd.anchorBatch(e,t)};lt.prototype.verifyAnchor=function(e,t){return pd.verifyAnchor(e,t)};lt.prototype.getRightTypes=function(){return Du.getRightTypes()};lt.prototype.getClaimSchemas=function(){return Dv.getSchemas()};lt.prototype.createRegistry=function(e){return this.registry=Uo.createRegistry(e),this.registry};lt.prototype.setRegistry=function(e){Qi.checkArgument(e&&typeof e=="object","Invalid registry"),this.registry=e};lt.create=function(e){return new lt(e)};lt.createRightToken=function(e,t,r){var i=new lt;return i.createRightToken(e,t,r)};lt.validateClaim=function(e,t){return Dv.validate(e,t)};lt.verifyToken=function(e,t){var r=new lt;return r.verifyToken(e,t)};lt.createRegistry=function(e){return Uo.createRegistry(e)};lt.Right=Du;lt.Claim=Dv;lt.Anchor=pd;lt.Proof=bE;lt.Registry=Uo;lt.Obligation=see;CH.exports=lt});var Om=T((phe,DH)=>{"use strict";g();var H=DH.exports;H.deps=H.deps||{};H.deps._=at();H.deps.Buffer=typeof f.Buffer<"u"?f.Buffer:null;var MH=pc();H.deps.bs58={encode:MH.encode,decode:MH.decode};if(typeof window>"u")H.deps.bnjs=qp();else try{H.deps.bnjs=qp()}catch{}H.version="v"+eb();H.versionGuard=function(e){if(e!==void 0){var t=`
|
|
98
|
+
`)};o6.exports=St});var u6=T((ole,s6)=>{"use strict";g();var hv=Ki(),CX=fv(),Ai=Le(),nle=Ke(),ai=Ie(),LX=Vc();function $t(e){return this instanceof $t?(this.options=e||{},this):new $t(e)}$t.createMerkleTree=function(e,t){ai.checkArgument(e&&typeof e=="object","Invalid credential");var r=$t._extractFields(e),i=t||hv.getRandomBuffer(32).toString("hex"),n=r.map(function(a,s){var u=Ai.sha256(f.Buffer.from(i+":"+s+":"+a.path,"utf8")).toString("hex"),c=a.path+":"+JSON.stringify(a.value)+":"+u;return{path:a.path,value:a.value,hash:Ai.sha256(f.Buffer.from(c,"utf8")).toString("hex"),salt:u}}),o=$t._buildMerkleTree(n.map(a=>a.hash));return{salt:i,leaves:n,tree:o,root:o[o.length-1][0]}};$t.generateSelectiveProof=function(e,t,r){ai.checkArgument(e&&typeof e=="object","Invalid credential"),typeof t=="string"&&(t=[t]),ai.checkArgument(Array.isArray(t),"Disclose paths must be array");var i=$t.createMerkleTree(e,r),n=[],o=[];return t.forEach(function(a){var s=i.leaves.find(l=>l.path===a);if(s){n.push(s);var u=i.leaves.findIndex(l=>l.path===a),c=$t._generateMerkleProof(i.tree,u);o.push({path:a,leafIndex:u,proof:c})}}),{type:"SelectiveDisclosureProof",created:new Date().toISOString(),proofPurpose:"selectiveDisclosure",verificationMethod:e.proof?e.proof.verificationMethod:null,credentialRoot:i.root,credentialHash:e.rootHash||CX._hashCredential(e).toString("hex"),disclosedFields:n.map(function(a){return{path:a.path,value:a.value,hash:a.hash,salt:a.salt}}),merkleProofs:o}};$t.verifySelectiveProof=function(e,t){try{ai.checkArgument(e&&typeof e=="object","Invalid proof"),ai.checkArgument(typeof t=="string","Expected root must be string");for(var r={valid:!1,errors:[],verifiedFields:[]},i=0;i<e.disclosedFields.length;i++){var n=e.disclosedFields[i],o=e.merkleProofs.find(c=>c.path===n.path);if(!o){r.errors.push("Missing Merkle proof for field: "+n.path);continue}if(typeof n.salt!="string"||!n.salt){r.errors.push("Missing per-field salt for: "+n.path);continue}var a=n.path+":"+JSON.stringify(n.value)+":"+n.salt,s=Ai.sha256(f.Buffer.from(a,"utf8")).toString("hex");if(s!==n.hash){r.errors.push("Field hash mismatch for: "+n.path);continue}var u=$t._verifyMerkleProof(n.hash,o.proof,t);if(!u){r.errors.push("Invalid Merkle proof for: "+n.path);continue}r.verifiedFields.push({path:n.path,value:n.value,verified:!0})}return r.valid=r.errors.length===0&&r.verifiedFields.length>0,r}catch(c){return{valid:!1,errors:["Proof verification failed: "+c.message],verifiedFields:[]}}};$t.generateAgeProof=function(e,t,r){ai.checkArgument(e instanceof Date,"Birth date must be Date object"),ai.checkArgument(typeof t=="number","Minimum age must be number"),r=r||hv.getRandomBuffer(32).toString("hex");var i=new Date,n=Math.floor((i-e)/(365.25*24*60*60*1e3));if(n<t)throw new Error("Age requirement not met");var o=e.toISOString().split("T")[0],a=Ai.sha256(f.Buffer.from(o+":"+r,"utf8")).toString("hex"),s={minimumAge:t,ageAttestation:n>=t,timestamp:i.toISOString(),salt:r},u=Ai.sha256(f.Buffer.from(JSON.stringify(s),"utf8")).toString("hex");return{type:"AgeProof",created:new Date().toISOString(),proofPurpose:"ageVerification",minimumAge:t,meetsRequirement:!0,birthDateCommitment:a,ageProofHash:u,challengeResponse:$t._generateAgeChallenge(e,t,r),opening:{birthDate:o,salt:r}}};$t.verifyAgeProof=function(e,t,r){try{if(ai.checkArgument(e&&typeof e=="object","Invalid proof"),ai.checkArgument(typeof t=="number","Required age must be number"),e.type!=="AgeProof"||e.minimumAge!==t||!r||typeof r!="object")return!1;var i=r.birthDate;if(typeof i=="string"&&(i=new Date(i)),!(i instanceof Date)||isNaN(i.getTime())||typeof r.salt!="string")return!1;var n=i.toISOString().split("T")[0],o=Ai.sha256(f.Buffer.from(n+":"+r.salt,"utf8")).toString("hex");if(o!==e.birthDateCommitment)return!1;var a=Math.floor((Date.now()-i.getTime())/(365.25*24*60*60*1e3));return a>=t}catch{return!1}};$t.generateRangeProof=function(e,t,r,i){ai.checkArgument(typeof e=="number","Value must be number"),ai.checkArgument(typeof t=="number","Min must be number"),ai.checkArgument(typeof r=="number","Max must be number"),ai.checkArgument(e>=t&&e<=r,"Value not in range"),i=i||hv.getRandomBuffer(32).toString("hex");var n=Ai.sha256(f.Buffer.from(e.toString()+":"+i,"utf8")).toString("hex"),o={min:t,max:r,inRange:!0,timestamp:new Date().toISOString(),salt:i},a=Ai.sha256(f.Buffer.from(JSON.stringify(o),"utf8")).toString("hex");return{type:"RangeProof",created:new Date().toISOString(),proofPurpose:"rangeVerification",range:{min:t,max:r},valueCommitment:n,proofHash:a,inRange:!0,opening:{value:e,salt:i}}};$t.verifyRangeProof=function(e,t,r,i){try{if(ai.checkArgument(e&&typeof e=="object","Invalid proof"),e.type!=="RangeProof"||!e.range||e.range.min!==t||e.range.max!==r||!i||typeof i!="object"||typeof i.value!="number"||typeof i.salt!="string")return!1;var n=Ai.sha256(f.Buffer.from(i.value.toString()+":"+i.salt,"utf8")).toString("hex");return n!==e.valueCommitment?!1:i.value>=t&&i.value<=r}catch{return!1}};$t._extractFields=function(e,t){t=t||"";var r=[];return Object.keys(e).forEach(function(i){var n=t?t+"."+i:i,o=e[i];o&&typeof o=="object"&&!Array.isArray(o)&&!(o instanceof Date)?r=r.concat($t._extractFields(o,n)):r.push({path:n,value:o})}),r};$t._buildMerkleTree=function(e){if(e.length===0)throw new Error("Cannot build tree from empty leaves");for(var t=[e];t[t.length-1].length>1;){for(var r=t[t.length-1],i=[],n=0;n<r.length;n+=2){var o=r[n],a=n+1<r.length?r[n+1]:o,s=o+a,u=Ai.sha256(f.Buffer.from(s,"hex")).toString("hex");i.push(u)}t.push(i)}return t};$t._generateMerkleProof=function(e,t){for(var r=[],i=t,n=0;n<e.length-1;n++){var o=e[n],a=i%2===0,s=a?i+1:i-1;s<o.length&&r.push({hash:o[s],isLeft:!a}),i=Math.floor(i/2)}return r};$t._verifyMerkleProof=function(e,t,r){for(var i=e,n=0;n<t.length;n++){var o=t[n],a=o.isLeft?o.hash+i:i+o.hash;i=Ai.sha256(f.Buffer.from(a,"hex")).toString("hex")}return i===r};$t._generateAgeChallenge=function(e,t,r){var i=Ai.sha256(f.Buffer.from(e.toISOString()+t+r,"utf8"));return i.toString("hex")};function zh(e,t){var r=t||"value",i=typeof e;if(!(e===null||i==="boolean"||i==="string"))if(i==="number"){if(!isFinite(e))throw new Error(r+" must be a finite number")}else if(Array.isArray(e))for(var n=0;n<e.length;n++){if(e[n]===void 0)throw new Error(r+"["+n+"] is undefined");zh(e[n],r+"["+n+"]")}else if(i==="object"){if(Object.getPrototypeOf(e)!==Object.prototype&&Object.getPrototypeOf(e)!==null)throw new Error(r+" must be a plain object");for(var o=Object.keys(e),a=0;a<o.length;a++){if(e[o[a]]===void 0)throw new Error(r+"."+o[a]+" is undefined");zh(e[o[a]],r+"."+o[a])}}else throw new Error(r+" is not a permitted type: "+i);return LX.stringify(e)}$t.generateMembershipProof=function(e,t,r){ai.checkArgument(Array.isArray(e),"Set must be array");var i=e.map(function(s,u){return zh(s,"set["+u+"]")}),n=zh(t);ai.checkArgument(i.indexOf(n)!==-1,"Value not in set"),r=r||hv.getRandomBuffer(32).toString("hex");var o=i.map(function(s){return Ai.sha256(f.Buffer.from(s+":"+r,"utf8")).toString("hex")}),a=Ai.sha256(f.Buffer.from(n+":"+r,"utf8")).toString("hex");return{type:"MembershipProof",created:new Date().toISOString(),proofPurpose:"membershipVerification",setCommitments:o,valueCommitment:a,isMember:!0,salt:r}};$t.verifyMembershipProof=function(e,t,r){try{if(ai.checkArgument(e&&typeof e=="object","Invalid proof"),e.type!=="MembershipProof"||!Array.isArray(e.setCommitments)||!Array.isArray(r)||r.length===0||!t||typeof t!="object"||typeof t.salt!="string"||!("value"in t))return!1;var i=function(a,s){return Ai.sha256(f.Buffer.from(zh(a,s)+":"+t.salt,"utf8")).toString("hex")},n=r.map(function(a,s){return i(a,"set["+s+"]")});if(n.length!==e.setCommitments.length)return!1;for(var o=0;o<n.length;o++)if(n[o]!==e.setCommitments[o])return!1;return i(t.value,"opening.value")!==e.valueCommitment?!1:n.indexOf(e.valueCommitment)!==-1}catch{return!1}};s6.exports=$t});var p6=T((ule,d6)=>{"use strict";g();var MX=vh(),DX=mw(),CS=zt(),HX=ut(),Kh=ei(),sle=Ni(),Vh=Le(),c6=mm(),bs=Ie();function Lr(e,t){return this instanceof Lr?(typeof e=="string"&&(e=Kh.fromWIF(e)),e!==null?(bs.checkArgument(e instanceof Kh,"Invalid private key"),this.privateKey=e,this.address=e.toAddress()):(this.privateKey=null,this.address=null),this.options=t||{},this.network=this.options.network||"mainnet",this.PROTOCOL_ID="SMARTLEDGER.ATTEST",this.VERSION=1,this):new Lr(e,t)}Lr.prototype.anchorCredential=async function(e,t,r){t=t||{},typeof e=="string"&&(e=f.Buffer.from(e,"hex")),bs.checkArgument(f.Buffer.isBuffer(e),"Invalid credential hash"),bs.checkArgument(e.length===32,"Hash must be 32 bytes");var i=this._createAnchorPayload("CREDENTIAL",e,t),n=await this._createAnchorTransaction(i,r);return{txid:n.hash,transaction:n,anchorHash:e.toString("hex"),metadata:t,timestamp:new Date().toISOString(),blockchainProof:{protocol:this.PROTOCOL_ID,version:this.VERSION,type:"CREDENTIAL"}}};Lr.prototype.anchorBatch=async function(e,t,r){t=t||{},bs.checkArgument(Array.isArray(e),"Credential hashes must be array"),bs.checkArgument(e.length>0,"Must provide at least one hash");var i=this._createMerkleRoot(e),n=this._createAnchorPayload("BATCH",i,{...t,batchSize:e.length,merkleRoot:i.toString("hex")}),o=await this._createAnchorTransaction(n,r);return{txid:o.hash,transaction:o,merkleRoot:i.toString("hex"),batchSize:e.length,credentialHashes:e.map(a=>f.Buffer.isBuffer(a)?a.toString("hex"):a),metadata:t,timestamp:new Date().toISOString(),blockchainProof:{protocol:this.PROTOCOL_ID,version:this.VERSION,type:"BATCH"}}};Lr.prototype.registerDID=async function(e,t,r){bs.checkArgument(typeof e=="string","DID must be string"),bs.checkArgument(t&&typeof t=="object","Invalid DID document");var i=Vh.sha256(f.Buffer.from(JSON.stringify(t),"utf8")),n=this._createAnchorPayload("DID_REG",i,{did:e,operation:"create",documentHash:i.toString("hex")}),o=await this._createAnchorTransaction(n,r);return{txid:o.hash,transaction:o,did:e,documentHash:i.toString("hex"),timestamp:new Date().toISOString(),blockchainProof:{protocol:this.PROTOCOL_ID,version:this.VERSION,type:"DID_REG"}}};Lr.prototype.revokeCredential=async function(e,t,r){bs.checkArgument(typeof e=="string","Credential ID must be string"),t=t||"unspecified";var i={credentialId:e,reason:t,timestamp:new Date().toISOString(),issuer:this.address.toString()},n=Vh.sha256(f.Buffer.from(JSON.stringify(i),"utf8")),o=this._createAnchorPayload("REVOKE",n,{credentialId:e,reason:t}),a=await this._createAnchorTransaction(o,r);return{txid:a.hash,transaction:a,credentialId:e,reason:t,revocationHash:n.toString("hex"),timestamp:new Date().toISOString(),blockchainProof:{protocol:this.PROTOCOL_ID,version:this.VERSION,type:"REVOKE"}}};var qX=["bn","privateKey","privkey","privKey","wif","privateJwk","xpriv","xprv","mnemonic"],UX=["d","seed","secret","key"];function f6(e){if(typeof e!="string"||e.length<50||e.length>53)return!1;try{return Kh.fromWIF(e),!0}catch{return!1}}function l6(e){if(typeof e!="string"||!/^(xprv|tprv)/.test(e))return!1;try{return MX.fromString(e),!0}catch{return!1}}function h6(e){if(typeof e!="string")return!1;var t=e.trim().split(/\s+/);if([12,15,18,21,24].indexOf(t.length)===-1)return!1;try{return DX.isValid(e.trim())}catch{return!1}}function FX(e){if(typeof e!="string"||!/^[0-9a-fA-F]{64}$/.test(e))return!1;try{return Kh.fromHex(e),!0}catch{return!1}}function jX(e){return f6(e)||l6(e)||h6(e)}function zX(e,t){var r=[];if(t&&typeof t.toWIF=="function")try{r=[t.toWIF(),t.toString(),t.bn&&t.bn.toString(16)].filter(function(a){return typeof a=="string"&&a.length}).map(function(a){return a.toLowerCase()})}catch{r=[]}function i(a,s){throw new Error("Refusing to anchor: "+(a||"metadata")+" "+s+", and anchor metadata is published in the OP_RETURN where it is permanent and public.")}function n(a,s){r.length&&r.indexOf(a.toLowerCase())!==-1&&i(s,"is this anchor's own private key"),f6(a)&&i(s,"is a WIF private key"),l6(a)&&i(s,"is an extended private key"),h6(a)&&i(s,"is a BIP39 mnemonic phrase")}function o(a,s,u){if(typeof a=="string"){n(a,s);return}if(!(!a||typeof a!="object"||u>6)){if(typeof a.toWIF=="function"&&a.bn&&i(s,"is a PrivateKey"),Array.isArray(a)){a.forEach(function(c,l){o(c,(s||"metadata")+"["+l+"]",u+1)});return}Object.keys(a).forEach(function(c){var l=a[c],p=s?s+"."+c:c;if(l!=null&&typeof l!="object"){var d=String(l);qX.indexOf(c)!==-1&&i(p,"is a field that holds key material"),UX.indexOf(c)!==-1&&(jX(d)||FX(d))&&i(p,"holds something that decodes as a private key")}o(l,p,u+1)})}}o(e,"",0)}Lr.prototype._createAnchorPayload=function(e,t,r){var i=Math.floor(Date.now()/1e3);zX(r,this.privateKey);var n=f.Buffer.concat([f.Buffer.from(this.PROTOCOL_ID,"utf8"),f.Buffer.from([this.VERSION]),f.Buffer.from(e.padEnd(10,"\0"),"utf8"),f.Buffer.from([i>>24,i>>16,i>>8,i]),t,f.Buffer.from(JSON.stringify(r),"utf8")]);return n};Lr.prototype._createAnchorTransaction=async function(e,t){if(!t||t.length===0)throw new Error("UTXOs required for anchor transaction");var r=200+e.length,i=this.options.feeRate||1,n=r*i,o=t.reduce((c,l)=>c+l.satoshis,0);if(o<n)throw new Error("Insufficient funds for anchor transaction");var a=new CS;t.forEach(c=>{a.from(c)});var s=HX.buildDataOut(e);a.addOutput(new CS.Output({script:s,satoshis:0}));var u=o-n;return u>546&&a.to(this.address,u),a.sign(this.privateKey),a};Lr.prototype._createMerkleRoot=function(e){if(e.length===0)throw new Error("Cannot create Merkle root from empty array");for(var t=e.map(u=>f.Buffer.isBuffer(u)?u:f.Buffer.from(u,"hex"));t.length>1;){for(var r=[],i=0;i<t.length;i+=2){var n=t[i],o=i+1<t.length?t[i+1]:n,a=f.Buffer.concat([n,o]),s=Vh.sha256(a);r.push(s)}t=r}return t[0]};Lr.parseAnchorData=function(e){if(!f.Buffer.isBuffer(e))throw new Error("Data must be Buffer");if(e.length<50)throw new Error("Data too short for SmartLedger anchor");var t=0,r=18,i=e.slice(t,t+r).toString("utf8");if(t+=r,i!=="SMARTLEDGER.ATTEST")throw new Error("Invalid protocol identifier");var n=e[t];t+=1;var o=e.slice(t,t+10).toString("utf8").replace(/\0/g,"");t+=10;var a=e[t]<<24|e[t+1]<<16|e[t+2]<<8|e[t+3];t+=4;var s=e.slice(t,t+32);t+=32;var u=e.slice(t),c={};try{c=JSON.parse(u.toString("utf8"))}catch{}return{protocol:i,version:n,type:o,timestamp:new Date(a*1e3),hash:s.toString("hex"),metadata:c}};Lr.verifyAnchor=async function(e,t,r){if(r=r||{},!e||!t)throw new Error("verifyAnchor requires both txid and expectedHash");if(r.spvProof&&(r.header||r.headerChain)&&r.rawTx)return Lr._verifyAnchorSPV(e,t,r);if(typeof r.chainProvider!="function")throw new Error("verifyAnchor needs either a trustless SPV proof \u2014 { spvProof: { index, nodes }, header, rawTx } \u2014 or a trusted options.chainProvider(txid) returning { confirmations, blockHeight, opReturns }. Refusing to fabricate a result.");var i=r.minConfirmations!=null?r.minConfirmations:1,n=await r.chainProvider(e),o=n&&n.confirmations||0,a=n&&n.opReturns||[],s=String(t).toLowerCase(),u=a.some(function(l){return String(l).toLowerCase().indexOf(s)!==-1}),c=o>=i&&u;return{verified:c,txid:e,hash:t,committed:u,confirmations:o,blockHeight:n&&n.blockHeight||null,timestamp:new Date().toISOString(),proof:{type:"blockchain_anchor",protocol:"SMARTLEDGER.ATTEST",network:r.network||"mainnet"}}};Lr._verifyAnchorSPV=function(e,t,r){var i=r.spvProof||{},n=null,o=r.header;r.headerChain&&(n=c6.verifyHeaderChain(r.headerChain,{requirePow:r.requirePow!==!1,powLimit:r.powLimit,trustedHash:r.trustedHash}),o=r.headerChain[0]);var a=c6.verifyTxInclusion({txid:e,index:i.index,nodes:i.nodes,header:o,requirePow:r.requirePow!==!1,powLimit:r.powLimit,minWork:r.minWork}),s=f.Buffer.isBuffer(r.rawTx)?r.rawTx:f.Buffer.from(r.rawTx,"hex"),u=f.Buffer.from(Vh.sha256sha256(s)).reverse().toString("hex"),c=u.toLowerCase()===String(e).toLowerCase(),l=c&&Lr._rawTxCommitsTo(s,t),p=n?n.count:r.header?1:0,d=r.minConfirmations!=null?r.minConfirmations:1,v=n?n.valid:!0,_=p>=d;return{verified:a.valid&&c&&l&&v&&_,chainVerified:a.valid,committed:l,txidBound:c,powValid:a.powValid,confirmations:p,headerChainValid:n?n.valid:null,headerChainReason:n&&n.reason||null,tipHash:n?n.tipHash:null,txid:e,hash:t,blockHash:a.blockHash,merkleRoot:a.merkleRoot,timestamp:new Date().toISOString(),proof:{type:n?"spv_merkle_inclusion_with_confirmations":"spv_merkle_inclusion",protocol:"SMARTLEDGER.ATTEST",network:r.network||"mainnet"}}};Lr._rawTxCommitsTo=function(e,t){var r=String(t).toLowerCase(),i;try{i=new CS(e)}catch{return!1}return i.outputs.some(function(n){var o=n.script;if(!o||!o.chunks||!o.chunks.length)return!1;var a=o.chunks[0].opcodenum===106||o.chunks[0].opcodenum===0&&o.chunks[1]&&o.chunks[1].opcodenum===106;return a?o.chunks.some(function(s){return s.buf&&s.buf.toString("hex").toLowerCase().indexOf(r)!==-1}):!1})};Lr.getCostEstimate=function(e,t){t=t||{};var r=t.feeRate||1,i=200,n=32,o=e*(i+n)*r,a=(i+e*n)*r;return{individual:{totalCost:o,costPerHash:i*r,transactions:e},batch:{totalCost:a,costPerHash:Math.ceil(a/e),transactions:1},savings:{absolute:o-a,percentage:Math.round((o-a)/o*100)}}};Lr.createUTXO=function(e,t,r,i){return{txid:e,outputIndex:t,satoshis:r,script:i}};Lr.generateTestData=function(){var e=new Kh,t=new Lr(e),r=Vh.sha256(f.Buffer.from("test credential data")),i={issuer:"did:smartledger:test",type:"EmailVerifiedCredential",environment:"test"};return{privateKey:e.toWIF(),address:e.toAddress().toString(),credentialHash:r.toString("hex"),metadata:i,anchor:t}};d6.exports=Lr});var m6=T((fle,g6)=>{"use strict";g();var LS=Ie(),Gh={EmailVerifiedCredential:{"@context":["https://www.w3.org/2018/credentials/v1","https://smartledger.technology/contexts/email/v1"],type:["VerifiableCredential","EmailVerifiedCredential"],requiredFields:["credentialSubject.email","credentialSubject.verified"],properties:{credentialSubject:{type:"object",required:["email","verified"],properties:{email:{type:"string",format:"email"},verified:{type:"boolean"},verificationMethod:{type:"string"},verificationTimestamp:{type:"string",format:"date-time"}}}}},AgeVerifiedCredential:{"@context":["https://www.w3.org/2018/credentials/v1","https://smartledger.technology/contexts/age/v1"],type:["VerifiableCredential","AgeVerifiedCredential"],requiredFields:["credentialSubject.ageOver","credentialSubject.verified"],properties:{credentialSubject:{type:"object",required:["ageOver","verified"],properties:{ageOver:{type:"number",minimum:0,maximum:150},verified:{type:"boolean"},birthDateHash:{type:"string",pattern:"^[a-fA-F0-9]{64}$"},verificationMethod:{type:"string"}}}}},KYCVerifiedCredential:{"@context":["https://www.w3.org/2018/credentials/v1","https://smartledger.technology/contexts/kyc/v1"],type:["VerifiableCredential","KYCVerifiedCredential"],requiredFields:["credentialSubject.kycLevel","credentialSubject.verified","credentialSubject.verifyingAuthority"],properties:{credentialSubject:{type:"object",required:["kycLevel","verified","verifyingAuthority"],properties:{kycLevel:{type:"string",enum:["basic","enhanced","premium","institutional"]},verified:{type:"boolean"},verifyingAuthority:{type:"string"},verificationTimestamp:{type:"string",format:"date-time"},firstNameHash:{type:"string",pattern:"^[a-fA-F0-9]{64}$"},lastNameHash:{type:"string",pattern:"^[a-fA-F0-9]{64}$"},ssnHash:{type:"string",pattern:"^[a-fA-F0-9]{64}$"}}}}},OrganizationCredential:{"@context":["https://www.w3.org/2018/credentials/v1","https://smartledger.technology/contexts/organization/v1"],type:["VerifiableCredential","OrganizationCredential"],requiredFields:["credentialSubject.name","credentialSubject.type","credentialSubject.verified"],properties:{credentialSubject:{type:"object",required:["name","type","verified"],properties:{name:{type:"string"},type:{type:"string",enum:["Corporation","LLC","Partnership","NGO","Government","Other"]},verified:{type:"boolean"},taxIdHash:{type:"string",pattern:"^[a-fA-F0-9]{64}$"},incorporationState:{type:"string"},industry:{type:"string"},verificationMethod:{type:"string"},verificationTimestamp:{type:"string",format:"date-time"}}}}},SSNVerifiedCredential:{"@context":["https://www.w3.org/2018/credentials/v1","https://smartledger.technology/contexts/ssn/v1"],type:["VerifiableCredential","SSNVerifiedCredential"],requiredFields:["credentialSubject.ssnHash","credentialSubject.verified","credentialSubject.verifyingAuthority"],properties:{credentialSubject:{type:"object",required:["ssnHash","verified","verifyingAuthority"],properties:{ssnHash:{type:"string",pattern:"^[a-fA-F0-9]{64}$"},verified:{type:"boolean"},verifyingAuthority:{type:"string"},verificationTimestamp:{type:"string",format:"date-time"},issuingState:{type:"string"}}}}},EducationalCredential:{"@context":["https://www.w3.org/2018/credentials/v1","https://smartledger.technology/contexts/education/v1"],type:["VerifiableCredential","EducationalCredential"],requiredFields:["credentialSubject.degree","credentialSubject.institution","credentialSubject.graduationDate"],properties:{credentialSubject:{type:"object",required:["degree","institution","graduationDate"],properties:{degree:{type:"string"},institution:{type:"string"},graduationDate:{type:"string",format:"date"},gpa:{type:"number",minimum:0,maximum:4},major:{type:"string"},honors:{type:"array",items:{type:"string"}}}}}},ProfessionalLicenseCredential:{"@context":["https://www.w3.org/2018/credentials/v1","https://smartledger.technology/contexts/license/v1"],type:["VerifiableCredential","ProfessionalLicenseCredential"],requiredFields:["credentialSubject.licenseType","credentialSubject.licenseNumber","credentialSubject.issuingAuthority","credentialSubject.isValid"],properties:{credentialSubject:{type:"object",required:["licenseType","licenseNumber","issuingAuthority","isValid"],properties:{licenseType:{type:"string"},licenseNumber:{type:"string"},issuingAuthority:{type:"string"},issuingState:{type:"string"},isValid:{type:"boolean"},issueDate:{type:"string",format:"date"},expirationDate:{type:"string",format:"date"}}}}}},KX={getSchema:function(e){return Gh[e]||null},getAllSchemas:function(){return Gh},validate:function(e,t){try{LS.checkArgument(e&&typeof e=="object","Invalid credential");var r;if(typeof t=="string"){if(r=Gh[t],!r)return{valid:!1,errors:["Unknown schema type: "+t]}}else if(typeof t=="object")r=t;else return{valid:!1,errors:["Invalid schema parameter"]};var i=[],n=[];return this._validateCredentialStructure(e,i),this._validateCredentialTypes(e,r,i),this._validateRequiredFields(e,r,i),this._validateFieldProperties(e,r,i,n),{valid:i.length===0,errors:i,warnings:n}}catch(o){return{valid:!1,errors:["Schema validation error: "+o.message]}}},_validateCredentialStructure:function(e,t){e["@context"]||t.push("Missing @context"),e.type||t.push("Missing type"),e.issuer||t.push("Missing issuer"),e.issuanceDate||t.push("Missing issuanceDate"),e.credentialSubject||t.push("Missing credentialSubject")},_validateCredentialTypes:function(e,t,r){if(!Array.isArray(e.type)){r.push("Credential type must be array");return}if(t.type&&Array.isArray(t.type))for(var i=0;i<t.type.length;i++)e.type.includes(t.type[i])||r.push("Missing required type: "+t.type[i])},_validateRequiredFields:function(e,t,r){if(t.requiredFields&&Array.isArray(t.requiredFields))for(var i=0;i<t.requiredFields.length;i++){var n=t.requiredFields[i],o=this._getNestedProperty(e,n);o==null&&r.push("Missing required field: "+n)}},_validateFieldProperties:function(e,t,r,i){t.properties&&t.properties.credentialSubject&&this._validateObjectProperties(e.credentialSubject,t.properties.credentialSubject,"credentialSubject",r,i)},_validateObjectProperties:function(e,t,r,i,n){!e||typeof e!="object"||t.properties&&Object.keys(t.properties).forEach(function(o){var a=e[o],s=t.properties[o],u=r+"."+o;a!=null&&this._validateProperty(a,s,u,i,n)}.bind(this))},_validateProperty:function(e,t,r,i,n){if(t.type){var o=Array.isArray(e)?"array":typeof e;if(o!==t.type){i.push("Invalid type for "+r+": expected "+t.type+", got "+o);return}}if(t.type==="string"&&(t.format==="email"&&!this._isValidEmail(e)&&i.push("Invalid email format for "+r),t.format==="date"&&!this._isValidDate(e)&&i.push("Invalid date format for "+r),t.format==="date-time"&&!this._isValidDateTime(e)&&i.push("Invalid date-time format for "+r),t.pattern&&!new RegExp(t.pattern).test(e)&&i.push("Value does not match pattern for "+r),t.enum&&!t.enum.includes(e)&&i.push("Invalid enum value for "+r+": "+e)),t.type==="number"&&(t.minimum!==void 0&&e<t.minimum&&i.push("Value below minimum for "+r+": "+e+" < "+t.minimum),t.maximum!==void 0&&e>t.maximum&&i.push("Value above maximum for "+r+": "+e+" > "+t.maximum)),t.type==="array"&&t.items)for(var a=0;a<e.length;a++)this._validateProperty(e[a],t.items,r+"["+a+"]",i,n)},_getNestedProperty:function(e,t){return t.split(".").reduce(function(r,i){return r&&r[i]},e)},_isValidEmail:function(e){var t=/^[^\s@]+@[^\s@]+\.[^\s@]+$/;return t.test(e)},_isValidDate:function(e){var t=new Date(e);return!isNaN(t.getTime())&&e.match(/^\d{4}-\d{2}-\d{2}$/)},_isValidDateTime:function(e){var t=new Date(e);return!isNaN(t.getTime())},addSchema:function(e,t){LS.checkArgument(typeof e=="string","Schema name must be string"),LS.checkArgument(t&&typeof t=="object","Invalid schema definition"),Gh[e]=t},createTemplate:function(e){var t=Gh[e];if(!t)throw new Error("Unknown credential type: "+e);var r={"@context":t["@context"]||["https://www.w3.org/2018/credentials/v1"],type:t.type||["VerifiableCredential"],issuer:"did:smartledger:ISSUER_DID_HERE",issuanceDate:new Date().toISOString(),credentialSubject:this._createSubjectTemplate(t.properties?t.properties.credentialSubject:{})};return r},_createSubjectTemplate:function(e){var t={id:"SUBJECT_ID_HERE"};return e.properties&&Object.keys(e.properties).forEach(function(r){var i=e.properties[r];t[r]=this._getDefaultValue(i)}.bind(this)),t},_getDefaultValue:function(e){switch(e.type){case"string":return e.enum?e.enum[0]:e.format==="email"?"example@example.com":e.format==="date"?"2023-01-01":e.format==="date-time"?new Date().toISOString():"PLACEHOLDER_STRING";case"number":return e.minimum||0;case"boolean":return!0;case"array":return[];case"object":return{};default:return null}}};g6.exports=KX});var y6=T((hle,v6)=>{"use strict";g();var VX=cv(),Of=fv(),GX=a6(),WX=u6(),Wh=p6(),YX=m6();function tt(e){if(!(this instanceof tt))return new tt(e);e=e||{},this.didResolver=VX,this.attestationVerifier=GX,this.zkProver=WX,this.schemaValidator=YX,this._attestationSignerOptions=e.attestationSigner||{},this._anchorOptions=e.anchor||{}}tt.prototype.createDID=function(e){return this.didResolver.fromPublicKey(e)};tt.prototype.resolveDID=function(e){return this.didResolver.resolve(e)};tt.prototype.verifyDIDOwnership=function(e,t){return this.didResolver.verifyOwnership(e,t)};tt.prototype.createEmailCredential=function(e,t,r,i){var n=new Of(i,this._attestationSignerOptions);return n.createEmailCredential(r,{issuerDID:e,subjectId:t})};tt.prototype.createAgeCredential=function(e,t,r,i,n){var o=new Of(n,this._attestationSignerOptions);return o.createAgeCredential(r,i,{issuerDID:e,subjectId:t})};tt.prototype.createKYCCredential=function(e,t,r,i,n){var o=new Of(n,this._attestationSignerOptions),a=Object.assign({level:r},i);return o.createKYCCredential(a,{issuerDID:e,subjectId:t})};tt.prototype.createOrganizationCredential=function(e,t,r,i){var n=new Of(i,this._attestationSignerOptions);return n.createOrganizationCredential(r,{issuerDID:e,subjectId:t})};tt.prototype.createPresentation=function(e,t,r,i){var n=new Of(r,this._attestationSignerOptions);return n.createPresentation(e,t,r,i)};tt.prototype.signCredential=function(e,t){var r=new Of(t,this._attestationSignerOptions);return r.signCredential(e,t)};tt.prototype.verifyCredential=function(e,t){return this.attestationVerifier.verifyCredential(e,t)};tt.prototype.verifyPresentation=function(e,t){return this.attestationVerifier.verifyPresentation(e,t)};tt.prototype.extractClaims=function(e){return this.attestationVerifier.extractClaims(e)};tt.prototype.generateSelectiveProof=function(e,t,r){return this.zkProver.generateSelectiveProof(e,t,r)};tt.prototype.verifySelectiveProof=function(e,t){return this.zkProver.verifySelectiveProof(e,t)};tt.prototype.generateAgeProof=function(e,t,r){var i=new Date("1995-06-15");return this.zkProver.generateAgeProof(i,t,r)};tt.prototype.verifyAgeProof=function(e,t,r){return this.zkProver.verifyAgeProof(e,t,r)};tt.prototype.generateRangeProof=function(e,t,r,i){return this.zkProver.generateRangeProof(e,t,r,i)};tt.prototype.verifyRangeProof=function(e,t,r,i){return this.zkProver.verifyRangeProof(e,t,r,i)};tt.prototype.generateMembershipProof=function(e,t,r){return this.zkProver.generateMembershipProof(e,t,r)};tt.prototype.verifyMembershipProof=function(e,t,r){return this.zkProver.verifyMembershipProof(e,t,r)};function dv(e){return Array.isArray(e)?{metadata:void 0,utxos:e}:(e=e||{},{metadata:e.metadata,utxos:e.utxos})}tt.prototype.anchorCredential=function(e,t,r){var i=new Wh(t,this._anchorOptions),n=dv(r);return i.anchorCredential(e,n.metadata,n.utxos)};tt.prototype.anchorBatch=function(e,t,r){var i=new Wh(t,this._anchorOptions),n=dv(r);return i.anchorBatch(e,n.metadata,n.utxos)};tt.prototype.registerDID=function(e,t,r,i){var n=new Wh(r,this._anchorOptions);return n.registerDID(e,t,dv(i).utxos)};tt.prototype.revokeCredential=function(e,t,r,i){var n=new Wh(r,this._anchorOptions);return n.revokeCredential(e,t,dv(i).utxos)};tt.prototype.queryAnchoredData=function(e){var t=new Wh(null,this._anchorOptions);return t.queryAnchoredData(e)};tt.prototype.validateCredential=function(e,t){return this.schemaValidator.validate(e,t)};tt.prototype.getSchema=function(e){return this.schemaValidator.getSchema(e)};tt.prototype.getAllSchemas=function(){return this.schemaValidator.getAllSchemas()};tt.prototype.addSchema=function(e,t){return this.schemaValidator.addSchema(e,t)};tt.prototype.createTemplate=function(e){return this.schemaValidator.createTemplate(e)};tt.prototype.generateNonce=function(e){e=e||32;var t=nr();return t.randomBytes(e).toString("hex")};tt.prototype.hashData=function(e,t){var r=nr(),i=r.createHash("sha256");return i.update(e),t&&i.update(t),i.digest("hex")};tt.prototype.getVersion=function(){return"1.0.0"};tt.prototype.getInfo=function(){return{name:"SmartLedger BSV Global Digital Attestation Framework",version:this.getVersion(),description:"W3C-compliant verifiable credentials with DID resolution, zero-knowledge proofs, and blockchain anchoring",components:{didResolver:"DID Resolution and Management",attestationSigner:"Verifiable Credential Creation",attestationVerifier:"Credential and Presentation Verification",zkProver:"Zero-Knowledge Proof Generation and Verification",anchor:"Blockchain Anchoring and Timestamping",schemaValidator:"W3C VC Schema Validation"},standards:["W3C Verifiable Credentials Data Model v1.1","W3C Decentralized Identifiers (DIDs) v1.0","RFC 7515 JSON Web Signature (JWS)","BSV Blockchain Protocol"]}};v6.exports=tt});var _6=T((ple,b6)=>{"use strict";g();var pv=nr();async function ZX(e){e=e||{};var t=e.alg||"ES256",r=e.kid||"key-"+Date.now();if(t!=="ES256"&&t!=="ES256K")throw new Error("Invalid algorithm. Must be ES256 or ES256K");var i;t==="ES256"?i=pv.generateKeyPairSync("ec",{namedCurve:"P-256",publicKeyEncoding:{type:"spki",format:"pem"},privateKeyEncoding:{type:"pkcs8",format:"pem"}}):i=pv.generateKeyPairSync("ec",{namedCurve:"secp256k1",publicKeyEncoding:{type:"spki",format:"pem"},privateKeyEncoding:{type:"pkcs8",format:"pem"}});var n=pv.createPublicKey(i.publicKey).export({format:"jwk"}),o=pv.createPrivateKey(i.privateKey).export({format:"jwk"});return n.kid=r,n.alg=t,n.use="sig",n.kty="EC",o.kid=r,o.alg=t,o.use="sig",o.kty="EC",{privateJwk:o,publicJwk:n,kid:r,alg:t}}var Yh=["authentication","assertionMethod","keyAgreement","capabilityInvocation","capabilityDelegation"],$X=["authentication","assertionMethod"];function MS(e){var t=e.relationships||$X;if(!Array.isArray(t)||t.length===0)throw new Error("relationships must be a non-empty array of DID Core verification relationships");return t.forEach(function(r){if(Yh.indexOf(r)===-1)throw new Error("unknown verification relationship: "+r+" (expected one of "+Yh.join(", ")+")")}),t}function XX(e){if(!e.domain)throw new Error("domain is required");var t=e.domain,r="did:web:"+t.replace(/:/g,"%3A"),i=[],n=[],o=[];if(e.p256){var a={id:r+"#"+e.p256.kid,type:"JsonWebKey2020",controller:r,publicKeyJwk:e.p256.jwk};i.push(a),n.push(MS(e.p256)),o.push(e.p256.jwk)}if(e.k1){var s={id:r+"#"+e.k1.kid,type:"JsonWebKey2020",controller:r,publicKeyJwk:e.k1.jwk};i.push(s),n.push(MS(e.k1)),o.push(e.k1.jwk)}if(i.length===0)throw new Error("At least one key (p256 or k1) must be provided");var u={"@context":["https://www.w3.org/ns/did/v1","https://w3id.org/security/suites/jws-2020/v1"],id:r,verificationMethod:i};Yh.forEach(function(l){var p=i.filter(function(d,v){return n[v].indexOf(l)!==-1}).map(function(d){return d.id});p.length&&(u[l]=p)}),e.controllerName&&(u.controller=e.controllerName);var c={keys:o};return{did:r,didDocument:u,jwks:c}}function JX(e){if(!e.domain||!e.newKey)throw new Error("domain and newKey are required");var t=e.domain,r="did:web:"+t.replace(/:/g,"%3A"),i=e.keepOldForDays||30,n={id:r+"#"+e.newKey.kid,type:"JsonWebKey2020",controller:r,publicKeyJwk:e.newKey.jwk},o=MS(e.newKey),a=e.currentDocument||null,s={"@context":["https://www.w3.org/ns/did/v1","https://w3id.org/security/suites/jws-2020/v1"],id:r,verificationMethod:[n]};if(Yh.forEach(function(l){o.indexOf(l)!==-1?s[l]=[n.id]:a&&Array.isArray(a[l])&&a[l].length&&(s[l]=a[l].slice())}),a&&Array.isArray(a.verificationMethod)){var u={};Yh.forEach(function(l){(s[l]||[]).forEach(function(p){u[p]=!0})}),a.verificationMethod.forEach(function(l){u[l.id]&&l.id!==n.id&&s.verificationMethod.push(l)})}s.rotationInfo={rotatedAt:new Date().toISOString(),gracePeriodDays:i};var c={keys:[e.newKey.jwk]};return{didDocument:s,jwks:c}}b6.exports={generateIssuerKeys:ZX,buildDidWebDocuments:XX,rotateIssuerKey:JX}});var DS=T((mle,w6)=>{"use strict";g();var Zh=nr(),$h={ES256:"P-256",ES256K:"secp256k1"},QX=["ES256","ES256K"];function gv(e){return e.toString("base64").replace(/\+/g,"-").replace(/\//g,"_").replace(/=/g,"")}function mv(e){for(e=e.replace(/-/g,"+").replace(/_/g,"/");e.length%4;)e+="=";return f.Buffer.from(e,"base64")}async function eJ(e){if(!e.issuerDid||!e.subjectId||!e.credentialSubject||!e.privateJwk)throw new Error("issuerDid, subjectId, credentialSubject, and privateJwk are required");var t=e.alg||"ES256";if(!$h[t])throw new Error("Unsupported algorithm: "+t);if(e.privateJwk.crv&&e.privateJwk.crv!==$h[t])throw new Error("Key curve "+e.privateJwk.crv+" does not match alg "+t);var r=e.kid||e.privateJwk.kid,i=e.types||["VerifiableCredential"],n=e.expSeconds||365*24*60*60,o=Math.floor(Date.now()/1e3),a=new Date().toISOString(),s={"@context":["https://www.w3.org/2018/credentials/v1"],type:i,issuer:e.issuerDid,issuanceDate:a,credentialSubject:Object.assign({id:e.subjectId},e.credentialSubject)},u={iss:e.issuerDid,sub:e.subjectId,iat:o,exp:o+n,vc:s},c={alg:t,typ:"JWT",kid:r},l=gv(f.Buffer.from(JSON.stringify(c))),p=gv(f.Buffer.from(JSON.stringify(u))),d=l+"."+p,v=Zh.createPrivateKey({key:e.privateJwk,format:"jwk"}),_=Zh.sign("sha256",f.Buffer.from(d),{key:v,dsaEncoding:"ieee-p1363"}),I=gv(_),R=d+"."+I;return{jwt:R}}async function tJ(e,t){t=t||{};try{if(typeof e!="string")return{valid:!1,error:"Invalid JWT format"};var r=e.split(".");if(r.length!==3)return{valid:!1,error:"Invalid JWT format"};var i=r[0],n=r[1],o=r[2],a=JSON.parse(mv(i).toString()),s=JSON.parse(mv(n).toString()),u=mv(o),c=t.allowedAlgs||QX;if(!a.alg||c.indexOf(a.alg)===-1||!$h[a.alg])return{valid:!1,error:"Algorithm not allowed: "+a.alg,header:a,payload:s};var l=Math.floor(Date.now()/1e3),p=t.clockToleranceSec||60;if(t.requireExpiration&&!s.exp)return{valid:!1,error:"JWT missing required exp claim",header:a,payload:s};if(s.exp&&s.exp<l-p)return{valid:!1,error:"JWT expired",header:a,payload:s};if(s.nbf&&s.nbf>l+p)return{valid:!1,error:"JWT not yet valid",header:a,payload:s};if(t.expectedIssuerDid&&s.iss!==t.expectedIssuerDid)return{valid:!1,error:"Unexpected issuer",header:a,payload:s};var d;if(t.didResolver){var v=await t.didResolver(s.iss);if(!v||!v.jwks||!v.jwks.keys)return{valid:!1,error:"Failed to resolve issuer DID",header:a,payload:s};var _=v.jwks.keys.find(function(q){return q.kid===a.kid});if(!_)return{valid:!1,error:"Key not found in JWKS",header:a,payload:s};d=_}else return{valid:!1,error:"DID resolver required for verification",header:a,payload:s};if(d.crv&&d.crv!==$h[a.alg])return{valid:!1,error:"Key curve does not match algorithm",header:a,payload:s};var I=i+"."+n,R=Zh.createPublicKey({key:d,format:"jwk"}),k=Zh.verify("sha256",f.Buffer.from(I),{key:R,dsaEncoding:"ieee-p1363"},u);if(!k&&t.allowLegacyDER)try{k=Zh.verify("sha256",f.Buffer.from(I),{key:R,dsaEncoding:"der"},u)}catch{k=!1}return k?{valid:!0,header:a,payload:s}:{valid:!1,error:"Invalid signature",header:a,payload:s}}catch(q){return{valid:!1,error:q.message||"Verification failed"}}}w6.exports={issueVcJwt:eJ,verifyVcJwt:tJ,base64UrlEncode:gv,base64UrlDecode:mv,ALG_TO_CRV:$h}});var E6=T((yle,S6)=>{"use strict";g();function rJ(){this.input=null,this.next_in=0,this.avail_in=0,this.total_in=0,this.output=null,this.next_out=0,this.avail_out=0,this.total_out=0,this.msg="",this.state=null,this.data_type=2,this.adler=0}S6.exports=rJ});var Xh=T(Ti=>{"use strict";g();var iJ=typeof Uint8Array<"u"&&typeof Uint16Array<"u"&&typeof Int32Array<"u";function nJ(e,t){return Object.prototype.hasOwnProperty.call(e,t)}Ti.assign=function(e){for(var t=Array.prototype.slice.call(arguments,1);t.length;){var r=t.shift();if(r){if(typeof r!="object")throw new TypeError(r+"must be non-object");for(var i in r)nJ(r,i)&&(e[i]=r[i])}}return e};Ti.shrinkBuf=function(e,t){return e.length===t?e:e.subarray?e.subarray(0,t):(e.length=t,e)};var oJ={arraySet:function(e,t,r,i,n){if(t.subarray&&e.subarray){e.set(t.subarray(r,r+i),n);return}for(var o=0;o<i;o++)e[n+o]=t[r+o]},flattenChunks:function(e){var t,r,i,n,o,a;for(i=0,t=0,r=e.length;t<r;t++)i+=e[t].length;for(a=new Uint8Array(i),n=0,t=0,r=e.length;t<r;t++)o=e[t],a.set(o,n),n+=o.length;return a}},aJ={arraySet:function(e,t,r,i,n){for(var o=0;o<i;o++)e[n+o]=t[r+o]},flattenChunks:function(e){return[].concat.apply([],e)}};Ti.setTyped=function(e){e?(Ti.Buf8=Uint8Array,Ti.Buf16=Uint16Array,Ti.Buf32=Int32Array,Ti.assign(Ti,oJ)):(Ti.Buf8=Array,Ti.Buf16=Array,Ti.Buf32=Array,Ti.assign(Ti,aJ))};Ti.setTyped(iJ)});var G6=T(Tf=>{"use strict";g();var sJ=Xh(),uJ=4,x6=0,O6=1,cJ=2;function Af(e){for(var t=e.length;--t>=0;)e[t]=0}var fJ=0,k6=1,lJ=2,hJ=3,dJ=258,KS=29,id=256,Qh=id+1+KS,If=30,VS=19,B6=2*Qh+1,_u=15,HS=16,pJ=7,GS=256,N6=16,C6=17,L6=18,jS=[0,0,0,0,0,0,0,0,1,1,1,1,2,2,2,2,3,3,3,3,4,4,4,4,5,5,5,5,0],vv=[0,0,0,0,1,1,2,2,3,3,4,4,5,5,6,6,7,7,8,8,9,9,10,10,11,11,12,12,13,13],gJ=[0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,2,3,7],M6=[16,17,18,0,8,7,9,6,10,5,11,4,12,3,13,2,14,1,15],mJ=512,Aa=new Array((Qh+2)*2);Af(Aa);var Jh=new Array(If*2);Af(Jh);var ed=new Array(mJ);Af(ed);var td=new Array(dJ-hJ+1);Af(td);var WS=new Array(KS);Af(WS);var yv=new Array(If);Af(yv);function qS(e,t,r,i,n){this.static_tree=e,this.extra_bits=t,this.extra_base=r,this.elems=i,this.max_length=n,this.has_stree=e&&e.length}var D6,H6,q6;function US(e,t){this.dyn_tree=e,this.max_code=0,this.stat_desc=t}function U6(e){return e<256?ed[e]:ed[256+(e>>>7)]}function rd(e,t){e.pending_buf[e.pending++]=t&255,e.pending_buf[e.pending++]=t>>>8&255}function Ui(e,t,r){e.bi_valid>HS-r?(e.bi_buf|=t<<e.bi_valid&65535,rd(e,e.bi_buf),e.bi_buf=t>>HS-e.bi_valid,e.bi_valid+=r-HS):(e.bi_buf|=t<<e.bi_valid&65535,e.bi_valid+=r)}function Co(e,t,r){Ui(e,r[t*2],r[t*2+1])}function F6(e,t){var r=0;do r|=e&1,e>>>=1,r<<=1;while(--t>0);return r>>>1}function vJ(e){e.bi_valid===16?(rd(e,e.bi_buf),e.bi_buf=0,e.bi_valid=0):e.bi_valid>=8&&(e.pending_buf[e.pending++]=e.bi_buf&255,e.bi_buf>>=8,e.bi_valid-=8)}function yJ(e,t){var r=t.dyn_tree,i=t.max_code,n=t.stat_desc.static_tree,o=t.stat_desc.has_stree,a=t.stat_desc.extra_bits,s=t.stat_desc.extra_base,u=t.stat_desc.max_length,c,l,p,d,v,_,I=0;for(d=0;d<=_u;d++)e.bl_count[d]=0;for(r[e.heap[e.heap_max]*2+1]=0,c=e.heap_max+1;c<B6;c++)l=e.heap[c],d=r[r[l*2+1]*2+1]+1,d>u&&(d=u,I++),r[l*2+1]=d,!(l>i)&&(e.bl_count[d]++,v=0,l>=s&&(v=a[l-s]),_=r[l*2],e.opt_len+=_*(d+v),o&&(e.static_len+=_*(n[l*2+1]+v)));if(I!==0){do{for(d=u-1;e.bl_count[d]===0;)d--;e.bl_count[d]--,e.bl_count[d+1]+=2,e.bl_count[u]--,I-=2}while(I>0);for(d=u;d!==0;d--)for(l=e.bl_count[d];l!==0;)p=e.heap[--c],!(p>i)&&(r[p*2+1]!==d&&(e.opt_len+=(d-r[p*2+1])*r[p*2],r[p*2+1]=d),l--)}}function j6(e,t,r){var i=new Array(_u+1),n=0,o,a;for(o=1;o<=_u;o++)i[o]=n=n+r[o-1]<<1;for(a=0;a<=t;a++){var s=e[a*2+1];s!==0&&(e[a*2]=F6(i[s]++,s))}}function bJ(){var e,t,r,i,n,o=new Array(_u+1);for(r=0,i=0;i<KS-1;i++)for(WS[i]=r,e=0;e<1<<jS[i];e++)td[r++]=i;for(td[r-1]=i,n=0,i=0;i<16;i++)for(yv[i]=n,e=0;e<1<<vv[i];e++)ed[n++]=i;for(n>>=7;i<If;i++)for(yv[i]=n<<7,e=0;e<1<<vv[i]-7;e++)ed[256+n++]=i;for(t=0;t<=_u;t++)o[t]=0;for(e=0;e<=143;)Aa[e*2+1]=8,e++,o[8]++;for(;e<=255;)Aa[e*2+1]=9,e++,o[9]++;for(;e<=279;)Aa[e*2+1]=7,e++,o[7]++;for(;e<=287;)Aa[e*2+1]=8,e++,o[8]++;for(j6(Aa,Qh+1,o),e=0;e<If;e++)Jh[e*2+1]=5,Jh[e*2]=F6(e,5);D6=new qS(Aa,jS,id+1,Qh,_u),H6=new qS(Jh,vv,0,If,_u),q6=new qS(new Array(0),gJ,0,VS,pJ)}function z6(e){var t;for(t=0;t<Qh;t++)e.dyn_ltree[t*2]=0;for(t=0;t<If;t++)e.dyn_dtree[t*2]=0;for(t=0;t<VS;t++)e.bl_tree[t*2]=0;e.dyn_ltree[GS*2]=1,e.opt_len=e.static_len=0,e.last_lit=e.matches=0}function K6(e){e.bi_valid>8?rd(e,e.bi_buf):e.bi_valid>0&&(e.pending_buf[e.pending++]=e.bi_buf),e.bi_buf=0,e.bi_valid=0}function _J(e,t,r,i){K6(e),i&&(rd(e,r),rd(e,~r)),sJ.arraySet(e.pending_buf,e.window,t,r,e.pending),e.pending+=r}function I6(e,t,r,i){var n=t*2,o=r*2;return e[n]<e[o]||e[n]===e[o]&&i[t]<=i[r]}function FS(e,t,r){for(var i=e.heap[r],n=r<<1;n<=e.heap_len&&(n<e.heap_len&&I6(t,e.heap[n+1],e.heap[n],e.depth)&&n++,!I6(t,i,e.heap[n],e.depth));)e.heap[r]=e.heap[n],r=n,n<<=1;e.heap[r]=i}function A6(e,t,r){var i,n,o=0,a,s;if(e.last_lit!==0)do i=e.pending_buf[e.d_buf+o*2]<<8|e.pending_buf[e.d_buf+o*2+1],n=e.pending_buf[e.l_buf+o],o++,i===0?Co(e,n,t):(a=td[n],Co(e,a+id+1,t),s=jS[a],s!==0&&(n-=WS[a],Ui(e,n,s)),i--,a=U6(i),Co(e,a,r),s=vv[a],s!==0&&(i-=yv[a],Ui(e,i,s)));while(o<e.last_lit);Co(e,GS,t)}function zS(e,t){var r=t.dyn_tree,i=t.stat_desc.static_tree,n=t.stat_desc.has_stree,o=t.stat_desc.elems,a,s,u=-1,c;for(e.heap_len=0,e.heap_max=B6,a=0;a<o;a++)r[a*2]!==0?(e.heap[++e.heap_len]=u=a,e.depth[a]=0):r[a*2+1]=0;for(;e.heap_len<2;)c=e.heap[++e.heap_len]=u<2?++u:0,r[c*2]=1,e.depth[c]=0,e.opt_len--,n&&(e.static_len-=i[c*2+1]);for(t.max_code=u,a=e.heap_len>>1;a>=1;a--)FS(e,r,a);c=o;do a=e.heap[1],e.heap[1]=e.heap[e.heap_len--],FS(e,r,1),s=e.heap[1],e.heap[--e.heap_max]=a,e.heap[--e.heap_max]=s,r[c*2]=r[a*2]+r[s*2],e.depth[c]=(e.depth[a]>=e.depth[s]?e.depth[a]:e.depth[s])+1,r[a*2+1]=r[s*2+1]=c,e.heap[1]=c++,FS(e,r,1);while(e.heap_len>=2);e.heap[--e.heap_max]=e.heap[1],yJ(e,t),j6(r,u,e.bl_count)}function T6(e,t,r){var i,n=-1,o,a=t[1],s=0,u=7,c=4;for(a===0&&(u=138,c=3),t[(r+1)*2+1]=65535,i=0;i<=r;i++)o=a,a=t[(i+1)*2+1],!(++s<u&&o===a)&&(s<c?e.bl_tree[o*2]+=s:o!==0?(o!==n&&e.bl_tree[o*2]++,e.bl_tree[N6*2]++):s<=10?e.bl_tree[C6*2]++:e.bl_tree[L6*2]++,s=0,n=o,a===0?(u=138,c=3):o===a?(u=6,c=3):(u=7,c=4))}function P6(e,t,r){var i,n=-1,o,a=t[1],s=0,u=7,c=4;for(a===0&&(u=138,c=3),i=0;i<=r;i++)if(o=a,a=t[(i+1)*2+1],!(++s<u&&o===a)){if(s<c)do Co(e,o,e.bl_tree);while(--s!==0);else o!==0?(o!==n&&(Co(e,o,e.bl_tree),s--),Co(e,N6,e.bl_tree),Ui(e,s-3,2)):s<=10?(Co(e,C6,e.bl_tree),Ui(e,s-3,3)):(Co(e,L6,e.bl_tree),Ui(e,s-11,7));s=0,n=o,a===0?(u=138,c=3):o===a?(u=6,c=3):(u=7,c=4)}}function wJ(e){var t;for(T6(e,e.dyn_ltree,e.l_desc.max_code),T6(e,e.dyn_dtree,e.d_desc.max_code),zS(e,e.bl_desc),t=VS-1;t>=3&&e.bl_tree[M6[t]*2+1]===0;t--);return e.opt_len+=3*(t+1)+5+5+4,t}function SJ(e,t,r,i){var n;for(Ui(e,t-257,5),Ui(e,r-1,5),Ui(e,i-4,4),n=0;n<i;n++)Ui(e,e.bl_tree[M6[n]*2+1],3);P6(e,e.dyn_ltree,t-1),P6(e,e.dyn_dtree,r-1)}function EJ(e){var t=4093624447,r;for(r=0;r<=31;r++,t>>>=1)if(t&1&&e.dyn_ltree[r*2]!==0)return x6;if(e.dyn_ltree[18]!==0||e.dyn_ltree[20]!==0||e.dyn_ltree[26]!==0)return O6;for(r=32;r<id;r++)if(e.dyn_ltree[r*2]!==0)return O6;return x6}var R6=!1;function xJ(e){R6||(bJ(),R6=!0),e.l_desc=new US(e.dyn_ltree,D6),e.d_desc=new US(e.dyn_dtree,H6),e.bl_desc=new US(e.bl_tree,q6),e.bi_buf=0,e.bi_valid=0,z6(e)}function V6(e,t,r,i){Ui(e,(fJ<<1)+(i?1:0),3),_J(e,t,r,!0)}function OJ(e){Ui(e,k6<<1,3),Co(e,GS,Aa),vJ(e)}function IJ(e,t,r,i){var n,o,a=0;e.level>0?(e.strm.data_type===cJ&&(e.strm.data_type=EJ(e)),zS(e,e.l_desc),zS(e,e.d_desc),a=wJ(e),n=e.opt_len+3+7>>>3,o=e.static_len+3+7>>>3,o<=n&&(n=o)):n=o=r+5,r+4<=n&&t!==-1?V6(e,t,r,i):e.strategy===uJ||o===n?(Ui(e,(k6<<1)+(i?1:0),3),A6(e,Aa,Jh)):(Ui(e,(lJ<<1)+(i?1:0),3),SJ(e,e.l_desc.max_code+1,e.d_desc.max_code+1,a+1),A6(e,e.dyn_ltree,e.dyn_dtree)),z6(e),i&&K6(e)}function AJ(e,t,r){return e.pending_buf[e.d_buf+e.last_lit*2]=t>>>8&255,e.pending_buf[e.d_buf+e.last_lit*2+1]=t&255,e.pending_buf[e.l_buf+e.last_lit]=r&255,e.last_lit++,t===0?e.dyn_ltree[r*2]++:(e.matches++,t--,e.dyn_ltree[(td[r]+id+1)*2]++,e.dyn_dtree[U6(t)*2]++),e.last_lit===e.lit_bufsize-1}Tf._tr_init=xJ;Tf._tr_stored_block=V6;Tf._tr_flush_block=IJ;Tf._tr_tally=AJ;Tf._tr_align=OJ});var YS=T((xle,W6)=>{"use strict";g();function TJ(e,t,r,i){for(var n=e&65535|0,o=e>>>16&65535|0,a=0;r!==0;){a=r>2e3?2e3:r,r-=a;do n=n+t[i++]|0,o=o+n|0;while(--a);n%=65521,o%=65521}return n|o<<16|0}W6.exports=TJ});var ZS=T((Ile,Y6)=>{"use strict";g();function PJ(){for(var e,t=[],r=0;r<256;r++){e=r;for(var i=0;i<8;i++)e=e&1?3988292384^e>>>1:e>>>1;t[r]=e}return t}var RJ=PJ();function kJ(e,t,r,i){var n=RJ,o=i+r;e^=-1;for(var a=i;a<o;a++)e=e>>>8^n[(e^t[a])&255];return e^-1}Y6.exports=kJ});var $6=T((Tle,Z6)=>{"use strict";g();Z6.exports={2:"need dictionary",1:"stream end",0:"","-1":"file error","-2":"stream error","-3":"data error","-4":"insufficient memory","-5":"buffer error","-6":"incompatible version"}});var o3=T(Do=>{"use strict";g();var Pi=Xh(),_n=G6(),e3=YS(),_s=ZS(),BJ=$6(),xu=0,NJ=1,CJ=3,Os=4,X6=5,Mo=0,J6=1,wn=-2,LJ=-3,$S=-5,MJ=-1,DJ=1,bv=2,HJ=3,qJ=4,UJ=0,FJ=2,Ev=8,jJ=9,zJ=15,KJ=8,VJ=29,GJ=256,JS=GJ+1+VJ,WJ=30,YJ=19,ZJ=2*JS+1,$J=15,ct=3,Es=258,Vn=Es+ct+1,XJ=32,xv=42,QS=69,_v=73,wv=91,Sv=103,wu=113,od=666,Gr=1,ad=2,Su=3,kf=4,JJ=3;function xs(e,t){return e.msg=BJ[t],t}function Q6(e){return(e<<1)-(e>4?9:0)}function Ss(e){for(var t=e.length;--t>=0;)e[t]=0}function ws(e){var t=e.state,r=t.pending;r>e.avail_out&&(r=e.avail_out),r!==0&&(Pi.arraySet(e.output,t.pending_buf,t.pending_out,r,e.next_out),e.next_out+=r,t.pending_out+=r,e.total_out+=r,e.avail_out-=r,t.pending-=r,t.pending===0&&(t.pending_out=0))}function si(e,t){_n._tr_flush_block(e,e.block_start>=0?e.block_start:-1,e.strstart-e.block_start,t),e.block_start=e.strstart,ws(e.strm)}function mt(e,t){e.pending_buf[e.pending++]=t}function nd(e,t){e.pending_buf[e.pending++]=t>>>8&255,e.pending_buf[e.pending++]=t&255}function QJ(e,t,r,i){var n=e.avail_in;return n>i&&(n=i),n===0?0:(e.avail_in-=n,Pi.arraySet(t,e.input,e.next_in,n,r),e.state.wrap===1?e.adler=e3(e.adler,t,n,r):e.state.wrap===2&&(e.adler=_s(e.adler,t,n,r)),e.next_in+=n,e.total_in+=n,n)}function t3(e,t){var r=e.max_chain_length,i=e.strstart,n,o,a=e.prev_length,s=e.nice_match,u=e.strstart>e.w_size-Vn?e.strstart-(e.w_size-Vn):0,c=e.window,l=e.w_mask,p=e.prev,d=e.strstart+Es,v=c[i+a-1],_=c[i+a];e.prev_length>=e.good_match&&(r>>=2),s>e.lookahead&&(s=e.lookahead);do if(n=t,!(c[n+a]!==_||c[n+a-1]!==v||c[n]!==c[i]||c[++n]!==c[i+1])){i+=2,n++;do;while(c[++i]===c[++n]&&c[++i]===c[++n]&&c[++i]===c[++n]&&c[++i]===c[++n]&&c[++i]===c[++n]&&c[++i]===c[++n]&&c[++i]===c[++n]&&c[++i]===c[++n]&&i<d);if(o=Es-(d-i),i=d-Es,o>a){if(e.match_start=t,a=o,o>=s)break;v=c[i+a-1],_=c[i+a]}}while((t=p[t&l])>u&&--r!==0);return a<=e.lookahead?a:e.lookahead}function Eu(e){var t=e.w_size,r,i,n,o,a;do{if(o=e.window_size-e.lookahead-e.strstart,e.strstart>=t+(t-Vn)){Pi.arraySet(e.window,e.window,t,t,0),e.match_start-=t,e.strstart-=t,e.block_start-=t,i=e.hash_size,r=i;do n=e.head[--r],e.head[r]=n>=t?n-t:0;while(--i);i=t,r=i;do n=e.prev[--r],e.prev[r]=n>=t?n-t:0;while(--i);o+=t}if(e.strm.avail_in===0)break;if(i=QJ(e.strm,e.window,e.strstart+e.lookahead,o),e.lookahead+=i,e.lookahead+e.insert>=ct)for(a=e.strstart-e.insert,e.ins_h=e.window[a],e.ins_h=(e.ins_h<<e.hash_shift^e.window[a+1])&e.hash_mask;e.insert&&(e.ins_h=(e.ins_h<<e.hash_shift^e.window[a+ct-1])&e.hash_mask,e.prev[a&e.w_mask]=e.head[e.ins_h],e.head[e.ins_h]=a,a++,e.insert--,!(e.lookahead+e.insert<ct)););}while(e.lookahead<Vn&&e.strm.avail_in!==0)}function eQ(e,t){var r=65535;for(r>e.pending_buf_size-5&&(r=e.pending_buf_size-5);;){if(e.lookahead<=1){if(Eu(e),e.lookahead===0&&t===xu)return Gr;if(e.lookahead===0)break}e.strstart+=e.lookahead,e.lookahead=0;var i=e.block_start+r;if((e.strstart===0||e.strstart>=i)&&(e.lookahead=e.strstart-i,e.strstart=i,si(e,!1),e.strm.avail_out===0)||e.strstart-e.block_start>=e.w_size-Vn&&(si(e,!1),e.strm.avail_out===0))return Gr}return e.insert=0,t===Os?(si(e,!0),e.strm.avail_out===0?Su:kf):(e.strstart>e.block_start&&(si(e,!1),e.strm.avail_out===0),Gr)}function XS(e,t){for(var r,i;;){if(e.lookahead<Vn){if(Eu(e),e.lookahead<Vn&&t===xu)return Gr;if(e.lookahead===0)break}if(r=0,e.lookahead>=ct&&(e.ins_h=(e.ins_h<<e.hash_shift^e.window[e.strstart+ct-1])&e.hash_mask,r=e.prev[e.strstart&e.w_mask]=e.head[e.ins_h],e.head[e.ins_h]=e.strstart),r!==0&&e.strstart-r<=e.w_size-Vn&&(e.match_length=t3(e,r)),e.match_length>=ct)if(i=_n._tr_tally(e,e.strstart-e.match_start,e.match_length-ct),e.lookahead-=e.match_length,e.match_length<=e.max_lazy_match&&e.lookahead>=ct){e.match_length--;do e.strstart++,e.ins_h=(e.ins_h<<e.hash_shift^e.window[e.strstart+ct-1])&e.hash_mask,r=e.prev[e.strstart&e.w_mask]=e.head[e.ins_h],e.head[e.ins_h]=e.strstart;while(--e.match_length!==0);e.strstart++}else e.strstart+=e.match_length,e.match_length=0,e.ins_h=e.window[e.strstart],e.ins_h=(e.ins_h<<e.hash_shift^e.window[e.strstart+1])&e.hash_mask;else i=_n._tr_tally(e,0,e.window[e.strstart]),e.lookahead--,e.strstart++;if(i&&(si(e,!1),e.strm.avail_out===0))return Gr}return e.insert=e.strstart<ct-1?e.strstart:ct-1,t===Os?(si(e,!0),e.strm.avail_out===0?Su:kf):e.last_lit&&(si(e,!1),e.strm.avail_out===0)?Gr:ad}function Pf(e,t){for(var r,i,n;;){if(e.lookahead<Vn){if(Eu(e),e.lookahead<Vn&&t===xu)return Gr;if(e.lookahead===0)break}if(r=0,e.lookahead>=ct&&(e.ins_h=(e.ins_h<<e.hash_shift^e.window[e.strstart+ct-1])&e.hash_mask,r=e.prev[e.strstart&e.w_mask]=e.head[e.ins_h],e.head[e.ins_h]=e.strstart),e.prev_length=e.match_length,e.prev_match=e.match_start,e.match_length=ct-1,r!==0&&e.prev_length<e.max_lazy_match&&e.strstart-r<=e.w_size-Vn&&(e.match_length=t3(e,r),e.match_length<=5&&(e.strategy===DJ||e.match_length===ct&&e.strstart-e.match_start>4096)&&(e.match_length=ct-1)),e.prev_length>=ct&&e.match_length<=e.prev_length){n=e.strstart+e.lookahead-ct,i=_n._tr_tally(e,e.strstart-1-e.prev_match,e.prev_length-ct),e.lookahead-=e.prev_length-1,e.prev_length-=2;do++e.strstart<=n&&(e.ins_h=(e.ins_h<<e.hash_shift^e.window[e.strstart+ct-1])&e.hash_mask,r=e.prev[e.strstart&e.w_mask]=e.head[e.ins_h],e.head[e.ins_h]=e.strstart);while(--e.prev_length!==0);if(e.match_available=0,e.match_length=ct-1,e.strstart++,i&&(si(e,!1),e.strm.avail_out===0))return Gr}else if(e.match_available){if(i=_n._tr_tally(e,0,e.window[e.strstart-1]),i&&si(e,!1),e.strstart++,e.lookahead--,e.strm.avail_out===0)return Gr}else e.match_available=1,e.strstart++,e.lookahead--}return e.match_available&&(i=_n._tr_tally(e,0,e.window[e.strstart-1]),e.match_available=0),e.insert=e.strstart<ct-1?e.strstart:ct-1,t===Os?(si(e,!0),e.strm.avail_out===0?Su:kf):e.last_lit&&(si(e,!1),e.strm.avail_out===0)?Gr:ad}function tQ(e,t){for(var r,i,n,o,a=e.window;;){if(e.lookahead<=Es){if(Eu(e),e.lookahead<=Es&&t===xu)return Gr;if(e.lookahead===0)break}if(e.match_length=0,e.lookahead>=ct&&e.strstart>0&&(n=e.strstart-1,i=a[n],i===a[++n]&&i===a[++n]&&i===a[++n])){o=e.strstart+Es;do;while(i===a[++n]&&i===a[++n]&&i===a[++n]&&i===a[++n]&&i===a[++n]&&i===a[++n]&&i===a[++n]&&i===a[++n]&&n<o);e.match_length=Es-(o-n),e.match_length>e.lookahead&&(e.match_length=e.lookahead)}if(e.match_length>=ct?(r=_n._tr_tally(e,1,e.match_length-ct),e.lookahead-=e.match_length,e.strstart+=e.match_length,e.match_length=0):(r=_n._tr_tally(e,0,e.window[e.strstart]),e.lookahead--,e.strstart++),r&&(si(e,!1),e.strm.avail_out===0))return Gr}return e.insert=0,t===Os?(si(e,!0),e.strm.avail_out===0?Su:kf):e.last_lit&&(si(e,!1),e.strm.avail_out===0)?Gr:ad}function rQ(e,t){for(var r;;){if(e.lookahead===0&&(Eu(e),e.lookahead===0)){if(t===xu)return Gr;break}if(e.match_length=0,r=_n._tr_tally(e,0,e.window[e.strstart]),e.lookahead--,e.strstart++,r&&(si(e,!1),e.strm.avail_out===0))return Gr}return e.insert=0,t===Os?(si(e,!0),e.strm.avail_out===0?Su:kf):e.last_lit&&(si(e,!1),e.strm.avail_out===0)?Gr:ad}function Lo(e,t,r,i,n){this.good_length=e,this.max_lazy=t,this.nice_length=r,this.max_chain=i,this.func=n}var Rf;Rf=[new Lo(0,0,0,0,eQ),new Lo(4,4,8,4,XS),new Lo(4,5,16,8,XS),new Lo(4,6,32,32,XS),new Lo(4,4,16,16,Pf),new Lo(8,16,32,32,Pf),new Lo(8,16,128,128,Pf),new Lo(8,32,128,256,Pf),new Lo(32,128,258,1024,Pf),new Lo(32,258,258,4096,Pf)];function iQ(e){e.window_size=2*e.w_size,Ss(e.head),e.max_lazy_match=Rf[e.level].max_lazy,e.good_match=Rf[e.level].good_length,e.nice_match=Rf[e.level].nice_length,e.max_chain_length=Rf[e.level].max_chain,e.strstart=0,e.block_start=0,e.lookahead=0,e.insert=0,e.match_length=e.prev_length=ct-1,e.match_available=0,e.ins_h=0}function nQ(){this.strm=null,this.status=0,this.pending_buf=null,this.pending_buf_size=0,this.pending_out=0,this.pending=0,this.wrap=0,this.gzhead=null,this.gzindex=0,this.method=Ev,this.last_flush=-1,this.w_size=0,this.w_bits=0,this.w_mask=0,this.window=null,this.window_size=0,this.prev=null,this.head=null,this.ins_h=0,this.hash_size=0,this.hash_bits=0,this.hash_mask=0,this.hash_shift=0,this.block_start=0,this.match_length=0,this.prev_match=0,this.match_available=0,this.strstart=0,this.match_start=0,this.lookahead=0,this.prev_length=0,this.max_chain_length=0,this.max_lazy_match=0,this.level=0,this.strategy=0,this.good_match=0,this.nice_match=0,this.dyn_ltree=new Pi.Buf16(ZJ*2),this.dyn_dtree=new Pi.Buf16((2*WJ+1)*2),this.bl_tree=new Pi.Buf16((2*YJ+1)*2),Ss(this.dyn_ltree),Ss(this.dyn_dtree),Ss(this.bl_tree),this.l_desc=null,this.d_desc=null,this.bl_desc=null,this.bl_count=new Pi.Buf16($J+1),this.heap=new Pi.Buf16(2*JS+1),Ss(this.heap),this.heap_len=0,this.heap_max=0,this.depth=new Pi.Buf16(2*JS+1),Ss(this.depth),this.l_buf=0,this.lit_bufsize=0,this.last_lit=0,this.d_buf=0,this.opt_len=0,this.static_len=0,this.matches=0,this.insert=0,this.bi_buf=0,this.bi_valid=0}function r3(e){var t;return!e||!e.state?xs(e,wn):(e.total_in=e.total_out=0,e.data_type=FJ,t=e.state,t.pending=0,t.pending_out=0,t.wrap<0&&(t.wrap=-t.wrap),t.status=t.wrap?xv:wu,e.adler=t.wrap===2?0:1,t.last_flush=xu,_n._tr_init(t),Mo)}function i3(e){var t=r3(e);return t===Mo&&iQ(e.state),t}function oQ(e,t){return!e||!e.state||e.state.wrap!==2?wn:(e.state.gzhead=t,Mo)}function n3(e,t,r,i,n,o){if(!e)return wn;var a=1;if(t===MJ&&(t=6),i<0?(a=0,i=-i):i>15&&(a=2,i-=16),n<1||n>jJ||r!==Ev||i<8||i>15||t<0||t>9||o<0||o>qJ)return xs(e,wn);i===8&&(i=9);var s=new nQ;return e.state=s,s.strm=e,s.wrap=a,s.gzhead=null,s.w_bits=i,s.w_size=1<<s.w_bits,s.w_mask=s.w_size-1,s.hash_bits=n+7,s.hash_size=1<<s.hash_bits,s.hash_mask=s.hash_size-1,s.hash_shift=~~((s.hash_bits+ct-1)/ct),s.window=new Pi.Buf8(s.w_size*2),s.head=new Pi.Buf16(s.hash_size),s.prev=new Pi.Buf16(s.w_size),s.lit_bufsize=1<<n+6,s.pending_buf_size=s.lit_bufsize*4,s.pending_buf=new Pi.Buf8(s.pending_buf_size),s.d_buf=1*s.lit_bufsize,s.l_buf=3*s.lit_bufsize,s.level=t,s.strategy=o,s.method=r,i3(e)}function aQ(e,t){return n3(e,t,Ev,zJ,KJ,UJ)}function sQ(e,t){var r,i,n,o;if(!e||!e.state||t>X6||t<0)return e?xs(e,wn):wn;if(i=e.state,!e.output||!e.input&&e.avail_in!==0||i.status===od&&t!==Os)return xs(e,e.avail_out===0?$S:wn);if(i.strm=e,r=i.last_flush,i.last_flush=t,i.status===xv)if(i.wrap===2)e.adler=0,mt(i,31),mt(i,139),mt(i,8),i.gzhead?(mt(i,(i.gzhead.text?1:0)+(i.gzhead.hcrc?2:0)+(i.gzhead.extra?4:0)+(i.gzhead.name?8:0)+(i.gzhead.comment?16:0)),mt(i,i.gzhead.time&255),mt(i,i.gzhead.time>>8&255),mt(i,i.gzhead.time>>16&255),mt(i,i.gzhead.time>>24&255),mt(i,i.level===9?2:i.strategy>=bv||i.level<2?4:0),mt(i,i.gzhead.os&255),i.gzhead.extra&&i.gzhead.extra.length&&(mt(i,i.gzhead.extra.length&255),mt(i,i.gzhead.extra.length>>8&255)),i.gzhead.hcrc&&(e.adler=_s(e.adler,i.pending_buf,i.pending,0)),i.gzindex=0,i.status=QS):(mt(i,0),mt(i,0),mt(i,0),mt(i,0),mt(i,0),mt(i,i.level===9?2:i.strategy>=bv||i.level<2?4:0),mt(i,JJ),i.status=wu);else{var a=Ev+(i.w_bits-8<<4)<<8,s=-1;i.strategy>=bv||i.level<2?s=0:i.level<6?s=1:i.level===6?s=2:s=3,a|=s<<6,i.strstart!==0&&(a|=XJ),a+=31-a%31,i.status=wu,nd(i,a),i.strstart!==0&&(nd(i,e.adler>>>16),nd(i,e.adler&65535)),e.adler=1}if(i.status===QS)if(i.gzhead.extra){for(n=i.pending;i.gzindex<(i.gzhead.extra.length&65535)&&!(i.pending===i.pending_buf_size&&(i.gzhead.hcrc&&i.pending>n&&(e.adler=_s(e.adler,i.pending_buf,i.pending-n,n)),ws(e),n=i.pending,i.pending===i.pending_buf_size));)mt(i,i.gzhead.extra[i.gzindex]&255),i.gzindex++;i.gzhead.hcrc&&i.pending>n&&(e.adler=_s(e.adler,i.pending_buf,i.pending-n,n)),i.gzindex===i.gzhead.extra.length&&(i.gzindex=0,i.status=_v)}else i.status=_v;if(i.status===_v)if(i.gzhead.name){n=i.pending;do{if(i.pending===i.pending_buf_size&&(i.gzhead.hcrc&&i.pending>n&&(e.adler=_s(e.adler,i.pending_buf,i.pending-n,n)),ws(e),n=i.pending,i.pending===i.pending_buf_size)){o=1;break}i.gzindex<i.gzhead.name.length?o=i.gzhead.name.charCodeAt(i.gzindex++)&255:o=0,mt(i,o)}while(o!==0);i.gzhead.hcrc&&i.pending>n&&(e.adler=_s(e.adler,i.pending_buf,i.pending-n,n)),o===0&&(i.gzindex=0,i.status=wv)}else i.status=wv;if(i.status===wv)if(i.gzhead.comment){n=i.pending;do{if(i.pending===i.pending_buf_size&&(i.gzhead.hcrc&&i.pending>n&&(e.adler=_s(e.adler,i.pending_buf,i.pending-n,n)),ws(e),n=i.pending,i.pending===i.pending_buf_size)){o=1;break}i.gzindex<i.gzhead.comment.length?o=i.gzhead.comment.charCodeAt(i.gzindex++)&255:o=0,mt(i,o)}while(o!==0);i.gzhead.hcrc&&i.pending>n&&(e.adler=_s(e.adler,i.pending_buf,i.pending-n,n)),o===0&&(i.status=Sv)}else i.status=Sv;if(i.status===Sv&&(i.gzhead.hcrc?(i.pending+2>i.pending_buf_size&&ws(e),i.pending+2<=i.pending_buf_size&&(mt(i,e.adler&255),mt(i,e.adler>>8&255),e.adler=0,i.status=wu)):i.status=wu),i.pending!==0){if(ws(e),e.avail_out===0)return i.last_flush=-1,Mo}else if(e.avail_in===0&&Q6(t)<=Q6(r)&&t!==Os)return xs(e,$S);if(i.status===od&&e.avail_in!==0)return xs(e,$S);if(e.avail_in!==0||i.lookahead!==0||t!==xu&&i.status!==od){var u=i.strategy===bv?rQ(i,t):i.strategy===HJ?tQ(i,t):Rf[i.level].func(i,t);if((u===Su||u===kf)&&(i.status=od),u===Gr||u===Su)return e.avail_out===0&&(i.last_flush=-1),Mo;if(u===ad&&(t===NJ?_n._tr_align(i):t!==X6&&(_n._tr_stored_block(i,0,0,!1),t===CJ&&(Ss(i.head),i.lookahead===0&&(i.strstart=0,i.block_start=0,i.insert=0))),ws(e),e.avail_out===0))return i.last_flush=-1,Mo}return t!==Os?Mo:i.wrap<=0?J6:(i.wrap===2?(mt(i,e.adler&255),mt(i,e.adler>>8&255),mt(i,e.adler>>16&255),mt(i,e.adler>>24&255),mt(i,e.total_in&255),mt(i,e.total_in>>8&255),mt(i,e.total_in>>16&255),mt(i,e.total_in>>24&255)):(nd(i,e.adler>>>16),nd(i,e.adler&65535)),ws(e),i.wrap>0&&(i.wrap=-i.wrap),i.pending!==0?Mo:J6)}function uQ(e){var t;return!e||!e.state?wn:(t=e.state.status,t!==xv&&t!==QS&&t!==_v&&t!==wv&&t!==Sv&&t!==wu&&t!==od?xs(e,wn):(e.state=null,t===wu?xs(e,LJ):Mo))}function cQ(e,t){var r=t.length,i,n,o,a,s,u,c,l;if(!e||!e.state||(i=e.state,a=i.wrap,a===2||a===1&&i.status!==xv||i.lookahead))return wn;for(a===1&&(e.adler=e3(e.adler,t,r,0)),i.wrap=0,r>=i.w_size&&(a===0&&(Ss(i.head),i.strstart=0,i.block_start=0,i.insert=0),l=new Pi.Buf8(i.w_size),Pi.arraySet(l,t,r-i.w_size,i.w_size,0),t=l,r=i.w_size),s=e.avail_in,u=e.next_in,c=e.input,e.avail_in=r,e.next_in=0,e.input=t,Eu(i);i.lookahead>=ct;){n=i.strstart,o=i.lookahead-(ct-1);do i.ins_h=(i.ins_h<<i.hash_shift^i.window[n+ct-1])&i.hash_mask,i.prev[n&i.w_mask]=i.head[i.ins_h],i.head[i.ins_h]=n,n++;while(--o);i.strstart=n,i.lookahead=ct-1,Eu(i)}return i.strstart+=i.lookahead,i.block_start=i.strstart,i.insert=i.lookahead,i.lookahead=0,i.match_length=i.prev_length=ct-1,i.match_available=0,e.next_in=u,e.input=c,e.avail_in=s,i.wrap=a,Mo}Do.deflateInit=aQ;Do.deflateInit2=n3;Do.deflateReset=i3;Do.deflateResetKeep=r3;Do.deflateSetHeader=oQ;Do.deflate=sQ;Do.deflateEnd=uQ;Do.deflateSetDictionary=cQ;Do.deflateInfo="pako deflate (from Nodeca project)"});var s3=T((Ble,a3)=>{"use strict";g();var Ov=30,fQ=12;a3.exports=function(t,r){var i,n,o,a,s,u,c,l,p,d,v,_,I,R,k,q,z,A,B,M,F,V,Y,E,h;i=t.state,n=t.next_in,E=t.input,o=n+(t.avail_in-5),a=t.next_out,h=t.output,s=a-(r-t.avail_out),u=a+(t.avail_out-257),c=i.dmax,l=i.wsize,p=i.whave,d=i.wnext,v=i.window,_=i.hold,I=i.bits,R=i.lencode,k=i.distcode,q=(1<<i.lenbits)-1,z=(1<<i.distbits)-1;e:do{I<15&&(_+=E[n++]<<I,I+=8,_+=E[n++]<<I,I+=8),A=R[_&q];t:for(;;){if(B=A>>>24,_>>>=B,I-=B,B=A>>>16&255,B===0)h[a++]=A&65535;else if(B&16){M=A&65535,B&=15,B&&(I<B&&(_+=E[n++]<<I,I+=8),M+=_&(1<<B)-1,_>>>=B,I-=B),I<15&&(_+=E[n++]<<I,I+=8,_+=E[n++]<<I,I+=8),A=k[_&z];r:for(;;){if(B=A>>>24,_>>>=B,I-=B,B=A>>>16&255,B&16){if(F=A&65535,B&=15,I<B&&(_+=E[n++]<<I,I+=8,I<B&&(_+=E[n++]<<I,I+=8)),F+=_&(1<<B)-1,F>c){t.msg="invalid distance too far back",i.mode=Ov;break e}if(_>>>=B,I-=B,B=a-s,F>B){if(B=F-B,B>p&&i.sane){t.msg="invalid distance too far back",i.mode=Ov;break e}if(V=0,Y=v,d===0){if(V+=l-B,B<M){M-=B;do h[a++]=v[V++];while(--B);V=a-F,Y=h}}else if(d<B){if(V+=l+d-B,B-=d,B<M){M-=B;do h[a++]=v[V++];while(--B);if(V=0,d<M){B=d,M-=B;do h[a++]=v[V++];while(--B);V=a-F,Y=h}}}else if(V+=d-B,B<M){M-=B;do h[a++]=v[V++];while(--B);V=a-F,Y=h}for(;M>2;)h[a++]=Y[V++],h[a++]=Y[V++],h[a++]=Y[V++],M-=3;M&&(h[a++]=Y[V++],M>1&&(h[a++]=Y[V++]))}else{V=a-F;do h[a++]=h[V++],h[a++]=h[V++],h[a++]=h[V++],M-=3;while(M>2);M&&(h[a++]=h[V++],M>1&&(h[a++]=h[V++]))}}else if((B&64)===0){A=k[(A&65535)+(_&(1<<B)-1)];continue r}else{t.msg="invalid distance code",i.mode=Ov;break e}break}}else if((B&64)===0){A=R[(A&65535)+(_&(1<<B)-1)];continue t}else if(B&32){i.mode=fQ;break e}else{t.msg="invalid literal/length code",i.mode=Ov;break e}break}}while(n<o&&a<u);M=I>>3,n-=M,I-=M<<3,_&=(1<<I)-1,t.next_in=n,t.next_out=a,t.avail_in=n<o?5+(o-n):5-(n-o),t.avail_out=a<u?257+(u-a):257-(a-u),i.hold=_,i.bits=I}});var p3=T((Cle,d3)=>{"use strict";g();var u3=Xh(),Bf=15,c3=852,f3=592,l3=0,eE=1,h3=2,lQ=[3,4,5,6,7,8,9,10,11,13,15,17,19,23,27,31,35,43,51,59,67,83,99,115,131,163,195,227,258,0,0],hQ=[16,16,16,16,16,16,16,16,17,17,17,17,18,18,18,18,19,19,19,19,20,20,20,20,21,21,21,21,16,72,78],dQ=[1,2,3,4,5,7,9,13,17,25,33,49,65,97,129,193,257,385,513,769,1025,1537,2049,3073,4097,6145,8193,12289,16385,24577,0,0],pQ=[16,16,16,16,17,17,18,18,19,19,20,20,21,21,22,22,23,23,24,24,25,25,26,26,27,27,28,28,29,29,64,64];d3.exports=function(t,r,i,n,o,a,s,u){var c=u.bits,l=0,p=0,d=0,v=0,_=0,I=0,R=0,k=0,q=0,z=0,A,B,M,F,V,Y=null,E=0,h,y=new u3.Buf16(Bf+1),w=new u3.Buf16(Bf+1),S=null,O=0,C,D,P;for(l=0;l<=Bf;l++)y[l]=0;for(p=0;p<n;p++)y[r[i+p]]++;for(_=c,v=Bf;v>=1&&y[v]===0;v--);if(_>v&&(_=v),v===0)return o[a++]=1<<24|64<<16|0,o[a++]=1<<24|64<<16|0,u.bits=1,0;for(d=1;d<v&&y[d]===0;d++);for(_<d&&(_=d),k=1,l=1;l<=Bf;l++)if(k<<=1,k-=y[l],k<0)return-1;if(k>0&&(t===l3||v!==1))return-1;for(w[1]=0,l=1;l<Bf;l++)w[l+1]=w[l]+y[l];for(p=0;p<n;p++)r[i+p]!==0&&(s[w[r[i+p]]++]=p);if(t===l3?(Y=S=s,h=19):t===eE?(Y=lQ,E-=257,S=hQ,O-=257,h=256):(Y=dQ,S=pQ,h=-1),z=0,p=0,l=d,V=a,I=_,R=0,M=-1,q=1<<_,F=q-1,t===eE&&q>c3||t===h3&&q>f3)return 1;for(;;){C=l-R,s[p]<h?(D=0,P=s[p]):s[p]>h?(D=S[O+s[p]],P=Y[E+s[p]]):(D=96,P=0),A=1<<l-R,B=1<<I,d=B;do B-=A,o[V+(z>>R)+B]=C<<24|D<<16|P|0;while(B!==0);for(A=1<<l-1;z&A;)A>>=1;if(A!==0?(z&=A-1,z+=A):z=0,p++,--y[l]===0){if(l===v)break;l=r[i+s[p]]}if(l>_&&(z&F)!==M){for(R===0&&(R=_),V+=d,I=l-R,k=1<<I;I+R<v&&(k-=y[I+R],!(k<=0));)I++,k<<=1;if(q+=1<<I,t===eE&&q>c3||t===h3&&q>f3)return 1;M=z&F,o[M]=_<<24|I<<16|V-a|0}}return z!==0&&(o[V+z]=l-R<<24|64<<16|0),u.bits=_,0}});var Z3=T(Gn=>{"use strict";g();var $i=Xh(),aE=YS(),Ho=ZS(),gQ=s3(),sd=p3(),mQ=0,U3=1,F3=2,g3=4,vQ=5,Iv=6,Ou=0,yQ=1,bQ=2,Sn=-2,j3=-3,sE=-4,_Q=-5,m3=8,z3=1,v3=2,y3=3,b3=4,_3=5,w3=6,S3=7,E3=8,x3=9,O3=10,Pv=11,Ta=12,tE=13,I3=14,rE=15,A3=16,T3=17,P3=18,R3=19,Av=20,Tv=21,k3=22,B3=23,N3=24,C3=25,L3=26,iE=27,M3=28,D3=29,Xt=30,uE=31,wQ=32,SQ=852,EQ=592,xQ=15,OQ=xQ;function H3(e){return(e>>>24&255)+(e>>>8&65280)+((e&65280)<<8)+((e&255)<<24)}function IQ(){this.mode=0,this.last=!1,this.wrap=0,this.havedict=!1,this.flags=0,this.dmax=0,this.check=0,this.total=0,this.head=null,this.wbits=0,this.wsize=0,this.whave=0,this.wnext=0,this.window=null,this.hold=0,this.bits=0,this.length=0,this.offset=0,this.extra=0,this.lencode=null,this.distcode=null,this.lenbits=0,this.distbits=0,this.ncode=0,this.nlen=0,this.ndist=0,this.have=0,this.next=null,this.lens=new $i.Buf16(320),this.work=new $i.Buf16(288),this.lendyn=null,this.distdyn=null,this.sane=0,this.back=0,this.was=0}function K3(e){var t;return!e||!e.state?Sn:(t=e.state,e.total_in=e.total_out=t.total=0,e.msg="",t.wrap&&(e.adler=t.wrap&1),t.mode=z3,t.last=0,t.havedict=0,t.dmax=32768,t.head=null,t.hold=0,t.bits=0,t.lencode=t.lendyn=new $i.Buf32(SQ),t.distcode=t.distdyn=new $i.Buf32(EQ),t.sane=1,t.back=-1,Ou)}function V3(e){var t;return!e||!e.state?Sn:(t=e.state,t.wsize=0,t.whave=0,t.wnext=0,K3(e))}function G3(e,t){var r,i;return!e||!e.state||(i=e.state,t<0?(r=0,t=-t):(r=(t>>4)+1,t<48&&(t&=15)),t&&(t<8||t>15))?Sn:(i.window!==null&&i.wbits!==t&&(i.window=null),i.wrap=r,i.wbits=t,V3(e))}function W3(e,t){var r,i;return e?(i=new IQ,e.state=i,i.window=null,r=G3(e,t),r!==Ou&&(e.state=null),r):Sn}function AQ(e){return W3(e,OQ)}var q3=!0,nE,oE;function TQ(e){if(q3){var t;for(nE=new $i.Buf32(512),oE=new $i.Buf32(32),t=0;t<144;)e.lens[t++]=8;for(;t<256;)e.lens[t++]=9;for(;t<280;)e.lens[t++]=7;for(;t<288;)e.lens[t++]=8;for(sd(U3,e.lens,0,288,nE,0,e.work,{bits:9}),t=0;t<32;)e.lens[t++]=5;sd(F3,e.lens,0,32,oE,0,e.work,{bits:5}),q3=!1}e.lencode=nE,e.lenbits=9,e.distcode=oE,e.distbits=5}function Y3(e,t,r,i){var n,o=e.state;return o.window===null&&(o.wsize=1<<o.wbits,o.wnext=0,o.whave=0,o.window=new $i.Buf8(o.wsize)),i>=o.wsize?($i.arraySet(o.window,t,r-o.wsize,o.wsize,0),o.wnext=0,o.whave=o.wsize):(n=o.wsize-o.wnext,n>i&&(n=i),$i.arraySet(o.window,t,r-i,n,o.wnext),i-=n,i?($i.arraySet(o.window,t,r-i,i,0),o.wnext=i,o.whave=o.wsize):(o.wnext+=n,o.wnext===o.wsize&&(o.wnext=0),o.whave<o.wsize&&(o.whave+=n))),0}function PQ(e,t){var r,i,n,o,a,s,u,c,l,p,d,v,_,I,R=0,k,q,z,A,B,M,F,V,Y=new $i.Buf8(4),E,h,y=[16,17,18,0,8,7,9,6,10,5,11,4,12,3,13,2,14,1,15];if(!e||!e.state||!e.output||!e.input&&e.avail_in!==0)return Sn;r=e.state,r.mode===Ta&&(r.mode=tE),a=e.next_out,n=e.output,u=e.avail_out,o=e.next_in,i=e.input,s=e.avail_in,c=r.hold,l=r.bits,p=s,d=u,V=Ou;e:for(;;)switch(r.mode){case z3:if(r.wrap===0){r.mode=tE;break}for(;l<16;){if(s===0)break e;s--,c+=i[o++]<<l,l+=8}if(r.wrap&2&&c===35615){r.check=0,Y[0]=c&255,Y[1]=c>>>8&255,r.check=Ho(r.check,Y,2,0),c=0,l=0,r.mode=v3;break}if(r.flags=0,r.head&&(r.head.done=!1),!(r.wrap&1)||(((c&255)<<8)+(c>>8))%31){e.msg="incorrect header check",r.mode=Xt;break}if((c&15)!==m3){e.msg="unknown compression method",r.mode=Xt;break}if(c>>>=4,l-=4,F=(c&15)+8,r.wbits===0)r.wbits=F;else if(F>r.wbits){e.msg="invalid window size",r.mode=Xt;break}r.dmax=1<<F,e.adler=r.check=1,r.mode=c&512?O3:Ta,c=0,l=0;break;case v3:for(;l<16;){if(s===0)break e;s--,c+=i[o++]<<l,l+=8}if(r.flags=c,(r.flags&255)!==m3){e.msg="unknown compression method",r.mode=Xt;break}if(r.flags&57344){e.msg="unknown header flags set",r.mode=Xt;break}r.head&&(r.head.text=c>>8&1),r.flags&512&&(Y[0]=c&255,Y[1]=c>>>8&255,r.check=Ho(r.check,Y,2,0)),c=0,l=0,r.mode=y3;case y3:for(;l<32;){if(s===0)break e;s--,c+=i[o++]<<l,l+=8}r.head&&(r.head.time=c),r.flags&512&&(Y[0]=c&255,Y[1]=c>>>8&255,Y[2]=c>>>16&255,Y[3]=c>>>24&255,r.check=Ho(r.check,Y,4,0)),c=0,l=0,r.mode=b3;case b3:for(;l<16;){if(s===0)break e;s--,c+=i[o++]<<l,l+=8}r.head&&(r.head.xflags=c&255,r.head.os=c>>8),r.flags&512&&(Y[0]=c&255,Y[1]=c>>>8&255,r.check=Ho(r.check,Y,2,0)),c=0,l=0,r.mode=_3;case _3:if(r.flags&1024){for(;l<16;){if(s===0)break e;s--,c+=i[o++]<<l,l+=8}r.length=c,r.head&&(r.head.extra_len=c),r.flags&512&&(Y[0]=c&255,Y[1]=c>>>8&255,r.check=Ho(r.check,Y,2,0)),c=0,l=0}else r.head&&(r.head.extra=null);r.mode=w3;case w3:if(r.flags&1024&&(v=r.length,v>s&&(v=s),v&&(r.head&&(F=r.head.extra_len-r.length,r.head.extra||(r.head.extra=new Array(r.head.extra_len)),$i.arraySet(r.head.extra,i,o,v,F)),r.flags&512&&(r.check=Ho(r.check,i,v,o)),s-=v,o+=v,r.length-=v),r.length))break e;r.length=0,r.mode=S3;case S3:if(r.flags&2048){if(s===0)break e;v=0;do F=i[o+v++],r.head&&F&&r.length<65536&&(r.head.name+=String.fromCharCode(F));while(F&&v<s);if(r.flags&512&&(r.check=Ho(r.check,i,v,o)),s-=v,o+=v,F)break e}else r.head&&(r.head.name=null);r.length=0,r.mode=E3;case E3:if(r.flags&4096){if(s===0)break e;v=0;do F=i[o+v++],r.head&&F&&r.length<65536&&(r.head.comment+=String.fromCharCode(F));while(F&&v<s);if(r.flags&512&&(r.check=Ho(r.check,i,v,o)),s-=v,o+=v,F)break e}else r.head&&(r.head.comment=null);r.mode=x3;case x3:if(r.flags&512){for(;l<16;){if(s===0)break e;s--,c+=i[o++]<<l,l+=8}if(c!==(r.check&65535)){e.msg="header crc mismatch",r.mode=Xt;break}c=0,l=0}r.head&&(r.head.hcrc=r.flags>>9&1,r.head.done=!0),e.adler=r.check=0,r.mode=Ta;break;case O3:for(;l<32;){if(s===0)break e;s--,c+=i[o++]<<l,l+=8}e.adler=r.check=H3(c),c=0,l=0,r.mode=Pv;case Pv:if(r.havedict===0)return e.next_out=a,e.avail_out=u,e.next_in=o,e.avail_in=s,r.hold=c,r.bits=l,bQ;e.adler=r.check=1,r.mode=Ta;case Ta:if(t===vQ||t===Iv)break e;case tE:if(r.last){c>>>=l&7,l-=l&7,r.mode=iE;break}for(;l<3;){if(s===0)break e;s--,c+=i[o++]<<l,l+=8}switch(r.last=c&1,c>>>=1,l-=1,c&3){case 0:r.mode=I3;break;case 1:if(TQ(r),r.mode=Av,t===Iv){c>>>=2,l-=2;break e}break;case 2:r.mode=T3;break;case 3:e.msg="invalid block type",r.mode=Xt}c>>>=2,l-=2;break;case I3:for(c>>>=l&7,l-=l&7;l<32;){if(s===0)break e;s--,c+=i[o++]<<l,l+=8}if((c&65535)!==(c>>>16^65535)){e.msg="invalid stored block lengths",r.mode=Xt;break}if(r.length=c&65535,c=0,l=0,r.mode=rE,t===Iv)break e;case rE:r.mode=A3;case A3:if(v=r.length,v){if(v>s&&(v=s),v>u&&(v=u),v===0)break e;$i.arraySet(n,i,o,v,a),s-=v,o+=v,u-=v,a+=v,r.length-=v;break}r.mode=Ta;break;case T3:for(;l<14;){if(s===0)break e;s--,c+=i[o++]<<l,l+=8}if(r.nlen=(c&31)+257,c>>>=5,l-=5,r.ndist=(c&31)+1,c>>>=5,l-=5,r.ncode=(c&15)+4,c>>>=4,l-=4,r.nlen>286||r.ndist>30){e.msg="too many length or distance symbols",r.mode=Xt;break}r.have=0,r.mode=P3;case P3:for(;r.have<r.ncode;){for(;l<3;){if(s===0)break e;s--,c+=i[o++]<<l,l+=8}r.lens[y[r.have++]]=c&7,c>>>=3,l-=3}for(;r.have<19;)r.lens[y[r.have++]]=0;if(r.lencode=r.lendyn,r.lenbits=7,E={bits:r.lenbits},V=sd(mQ,r.lens,0,19,r.lencode,0,r.work,E),r.lenbits=E.bits,V){e.msg="invalid code lengths set",r.mode=Xt;break}r.have=0,r.mode=R3;case R3:for(;r.have<r.nlen+r.ndist;){for(;R=r.lencode[c&(1<<r.lenbits)-1],k=R>>>24,q=R>>>16&255,z=R&65535,!(k<=l);){if(s===0)break e;s--,c+=i[o++]<<l,l+=8}if(z<16)c>>>=k,l-=k,r.lens[r.have++]=z;else{if(z===16){for(h=k+2;l<h;){if(s===0)break e;s--,c+=i[o++]<<l,l+=8}if(c>>>=k,l-=k,r.have===0){e.msg="invalid bit length repeat",r.mode=Xt;break}F=r.lens[r.have-1],v=3+(c&3),c>>>=2,l-=2}else if(z===17){for(h=k+3;l<h;){if(s===0)break e;s--,c+=i[o++]<<l,l+=8}c>>>=k,l-=k,F=0,v=3+(c&7),c>>>=3,l-=3}else{for(h=k+7;l<h;){if(s===0)break e;s--,c+=i[o++]<<l,l+=8}c>>>=k,l-=k,F=0,v=11+(c&127),c>>>=7,l-=7}if(r.have+v>r.nlen+r.ndist){e.msg="invalid bit length repeat",r.mode=Xt;break}for(;v--;)r.lens[r.have++]=F}}if(r.mode===Xt)break;if(r.lens[256]===0){e.msg="invalid code -- missing end-of-block",r.mode=Xt;break}if(r.lenbits=9,E={bits:r.lenbits},V=sd(U3,r.lens,0,r.nlen,r.lencode,0,r.work,E),r.lenbits=E.bits,V){e.msg="invalid literal/lengths set",r.mode=Xt;break}if(r.distbits=6,r.distcode=r.distdyn,E={bits:r.distbits},V=sd(F3,r.lens,r.nlen,r.ndist,r.distcode,0,r.work,E),r.distbits=E.bits,V){e.msg="invalid distances set",r.mode=Xt;break}if(r.mode=Av,t===Iv)break e;case Av:r.mode=Tv;case Tv:if(s>=6&&u>=258){e.next_out=a,e.avail_out=u,e.next_in=o,e.avail_in=s,r.hold=c,r.bits=l,gQ(e,d),a=e.next_out,n=e.output,u=e.avail_out,o=e.next_in,i=e.input,s=e.avail_in,c=r.hold,l=r.bits,r.mode===Ta&&(r.back=-1);break}for(r.back=0;R=r.lencode[c&(1<<r.lenbits)-1],k=R>>>24,q=R>>>16&255,z=R&65535,!(k<=l);){if(s===0)break e;s--,c+=i[o++]<<l,l+=8}if(q&&(q&240)===0){for(A=k,B=q,M=z;R=r.lencode[M+((c&(1<<A+B)-1)>>A)],k=R>>>24,q=R>>>16&255,z=R&65535,!(A+k<=l);){if(s===0)break e;s--,c+=i[o++]<<l,l+=8}c>>>=A,l-=A,r.back+=A}if(c>>>=k,l-=k,r.back+=k,r.length=z,q===0){r.mode=L3;break}if(q&32){r.back=-1,r.mode=Ta;break}if(q&64){e.msg="invalid literal/length code",r.mode=Xt;break}r.extra=q&15,r.mode=k3;case k3:if(r.extra){for(h=r.extra;l<h;){if(s===0)break e;s--,c+=i[o++]<<l,l+=8}r.length+=c&(1<<r.extra)-1,c>>>=r.extra,l-=r.extra,r.back+=r.extra}r.was=r.length,r.mode=B3;case B3:for(;R=r.distcode[c&(1<<r.distbits)-1],k=R>>>24,q=R>>>16&255,z=R&65535,!(k<=l);){if(s===0)break e;s--,c+=i[o++]<<l,l+=8}if((q&240)===0){for(A=k,B=q,M=z;R=r.distcode[M+((c&(1<<A+B)-1)>>A)],k=R>>>24,q=R>>>16&255,z=R&65535,!(A+k<=l);){if(s===0)break e;s--,c+=i[o++]<<l,l+=8}c>>>=A,l-=A,r.back+=A}if(c>>>=k,l-=k,r.back+=k,q&64){e.msg="invalid distance code",r.mode=Xt;break}r.offset=z,r.extra=q&15,r.mode=N3;case N3:if(r.extra){for(h=r.extra;l<h;){if(s===0)break e;s--,c+=i[o++]<<l,l+=8}r.offset+=c&(1<<r.extra)-1,c>>>=r.extra,l-=r.extra,r.back+=r.extra}if(r.offset>r.dmax){e.msg="invalid distance too far back",r.mode=Xt;break}r.mode=C3;case C3:if(u===0)break e;if(v=d-u,r.offset>v){if(v=r.offset-v,v>r.whave&&r.sane){e.msg="invalid distance too far back",r.mode=Xt;break}v>r.wnext?(v-=r.wnext,_=r.wsize-v):_=r.wnext-v,v>r.length&&(v=r.length),I=r.window}else I=n,_=a-r.offset,v=r.length;v>u&&(v=u),u-=v,r.length-=v;do n[a++]=I[_++];while(--v);r.length===0&&(r.mode=Tv);break;case L3:if(u===0)break e;n[a++]=r.length,u--,r.mode=Tv;break;case iE:if(r.wrap){for(;l<32;){if(s===0)break e;s--,c|=i[o++]<<l,l+=8}if(d-=u,e.total_out+=d,r.total+=d,d&&(e.adler=r.check=r.flags?Ho(r.check,n,d,a-d):aE(r.check,n,d,a-d)),d=u,(r.flags?c:H3(c))!==r.check){e.msg="incorrect data check",r.mode=Xt;break}c=0,l=0}r.mode=M3;case M3:if(r.wrap&&r.flags){for(;l<32;){if(s===0)break e;s--,c+=i[o++]<<l,l+=8}if(c!==(r.total&4294967295)){e.msg="incorrect length check",r.mode=Xt;break}c=0,l=0}r.mode=D3;case D3:V=yQ;break e;case Xt:V=j3;break e;case uE:return sE;case wQ:default:return Sn}return e.next_out=a,e.avail_out=u,e.next_in=o,e.avail_in=s,r.hold=c,r.bits=l,(r.wsize||d!==e.avail_out&&r.mode<Xt&&(r.mode<iE||t!==g3))&&Y3(e,e.output,e.next_out,d-e.avail_out)?(r.mode=uE,sE):(p-=e.avail_in,d-=e.avail_out,e.total_in+=p,e.total_out+=d,r.total+=d,r.wrap&&d&&(e.adler=r.check=r.flags?Ho(r.check,n,d,e.next_out-d):aE(r.check,n,d,e.next_out-d)),e.data_type=r.bits+(r.last?64:0)+(r.mode===Ta?128:0)+(r.mode===Av||r.mode===rE?256:0),(p===0&&d===0||t===g3)&&V===Ou&&(V=_Q),V)}function RQ(e){if(!e||!e.state)return Sn;var t=e.state;return t.window&&(t.window=null),e.state=null,Ou}function kQ(e,t){var r;return!e||!e.state||(r=e.state,(r.wrap&2)===0)?Sn:(r.head=t,t.done=!1,Ou)}function BQ(e,t){var r=t.length,i,n,o;return!e||!e.state||(i=e.state,i.wrap!==0&&i.mode!==Pv)?Sn:i.mode===Pv&&(n=1,n=aE(n,t,r,0),n!==i.check)?j3:(o=Y3(e,t,r,r),o?(i.mode=uE,sE):(i.havedict=1,Ou))}Gn.inflateReset=V3;Gn.inflateReset2=G3;Gn.inflateResetKeep=K3;Gn.inflateInit=AQ;Gn.inflateInit2=W3;Gn.inflate=PQ;Gn.inflateEnd=RQ;Gn.inflateGetHeader=kQ;Gn.inflateSetDictionary=BQ;Gn.inflateInfo="pako inflate (from Nodeca project)"});var X3=T((Hle,$3)=>{"use strict";g();$3.exports={Z_NO_FLUSH:0,Z_PARTIAL_FLUSH:1,Z_SYNC_FLUSH:2,Z_FULL_FLUSH:3,Z_FINISH:4,Z_BLOCK:5,Z_TREES:6,Z_OK:0,Z_STREAM_END:1,Z_NEED_DICT:2,Z_ERRNO:-1,Z_STREAM_ERROR:-2,Z_DATA_ERROR:-3,Z_BUF_ERROR:-5,Z_NO_COMPRESSION:0,Z_BEST_SPEED:1,Z_BEST_COMPRESSION:9,Z_DEFAULT_COMPRESSION:-1,Z_FILTERED:1,Z_HUFFMAN_ONLY:2,Z_RLE:3,Z_FIXED:4,Z_DEFAULT_STRATEGY:0,Z_BINARY:0,Z_TEXT:1,Z_UNKNOWN:2,Z_DEFLATED:8}});var Q3=T(fe=>{"use strict";g();var Xi=fa(),NQ=E6(),ud=o3(),Iu=Z3(),J3=X3();for(cE in J3)fe[cE]=J3[cE];var cE;fe.NONE=0;fe.DEFLATE=1;fe.INFLATE=2;fe.GZIP=3;fe.GUNZIP=4;fe.DEFLATERAW=5;fe.INFLATERAW=6;fe.UNZIP=7;var CQ=31,LQ=139;function _i(e){if(typeof e!="number"||e<fe.DEFLATE||e>fe.UNZIP)throw new TypeError("Bad argument");this.dictionary=null,this.err=0,this.flush=0,this.init_done=!1,this.level=0,this.memLevel=0,this.mode=e,this.strategy=0,this.windowBits=0,this.write_in_progress=!1,this.pending_close=!1,this.gzip_id_bytes_read=0}_i.prototype.close=function(){if(this.write_in_progress){this.pending_close=!0;return}this.pending_close=!1,Xi(this.init_done,"close before init"),Xi(this.mode<=fe.UNZIP),this.mode===fe.DEFLATE||this.mode===fe.GZIP||this.mode===fe.DEFLATERAW?ud.deflateEnd(this.strm):(this.mode===fe.INFLATE||this.mode===fe.GUNZIP||this.mode===fe.INFLATERAW||this.mode===fe.UNZIP)&&Iu.inflateEnd(this.strm),this.mode=fe.NONE,this.dictionary=null};_i.prototype.write=function(e,t,r,i,n,o,a){return this._write(!0,e,t,r,i,n,o,a)};_i.prototype.writeSync=function(e,t,r,i,n,o,a){return this._write(!1,e,t,r,i,n,o,a)};_i.prototype._write=function(e,t,r,i,n,o,a,s){if(Xi.equal(arguments.length,8),Xi(this.init_done,"write before init"),Xi(this.mode!==fe.NONE,"already finalized"),Xi.equal(!1,this.write_in_progress,"write already in progress"),Xi.equal(!1,this.pending_close,"close is pending"),this.write_in_progress=!0,Xi.equal(!1,t===void 0,"must provide flush value"),this.write_in_progress=!0,t!==fe.Z_NO_FLUSH&&t!==fe.Z_PARTIAL_FLUSH&&t!==fe.Z_SYNC_FLUSH&&t!==fe.Z_FULL_FLUSH&&t!==fe.Z_FINISH&&t!==fe.Z_BLOCK)throw new Error("Invalid flush value");if(r==null&&(r=f.Buffer.alloc(0),n=0,i=0),this.strm.avail_in=n,this.strm.input=r,this.strm.next_in=i,this.strm.avail_out=s,this.strm.output=o,this.strm.next_out=a,this.flush=t,!e)return this._process(),this._checkError()?this._afterSync():void 0;var u=this;return b.default.nextTick(function(){u._process(),u._after()}),this};_i.prototype._afterSync=function(){var e=this.strm.avail_out,t=this.strm.avail_in;return this.write_in_progress=!1,[t,e]};_i.prototype._process=function(){var e=null;switch(this.mode){case fe.DEFLATE:case fe.GZIP:case fe.DEFLATERAW:this.err=ud.deflate(this.strm,this.flush);break;case fe.UNZIP:switch(this.strm.avail_in>0&&(e=this.strm.next_in),this.gzip_id_bytes_read){case 0:if(e===null)break;if(this.strm.input[e]===CQ){if(this.gzip_id_bytes_read=1,e++,this.strm.avail_in===1)break}else{this.mode=fe.INFLATE;break}case 1:if(e===null)break;this.strm.input[e]===LQ?(this.gzip_id_bytes_read=2,this.mode=fe.GUNZIP):this.mode=fe.INFLATE;break;default:throw new Error("invalid number of gzip magic number bytes read")}case fe.INFLATE:case fe.GUNZIP:case fe.INFLATERAW:for(this.err=Iu.inflate(this.strm,this.flush),this.err===fe.Z_NEED_DICT&&this.dictionary&&(this.err=Iu.inflateSetDictionary(this.strm,this.dictionary),this.err===fe.Z_OK?this.err=Iu.inflate(this.strm,this.flush):this.err===fe.Z_DATA_ERROR&&(this.err=fe.Z_NEED_DICT));this.strm.avail_in>0&&this.mode===fe.GUNZIP&&this.err===fe.Z_STREAM_END&&this.strm.next_in[0]!==0;)this.reset(),this.err=Iu.inflate(this.strm,this.flush);break;default:throw new Error("Unknown mode "+this.mode)}};_i.prototype._checkError=function(){switch(this.err){case fe.Z_OK:case fe.Z_BUF_ERROR:if(this.strm.avail_out!==0&&this.flush===fe.Z_FINISH)return this._error("unexpected end of file"),!1;break;case fe.Z_STREAM_END:break;case fe.Z_NEED_DICT:return this.dictionary==null?this._error("Missing dictionary"):this._error("Bad dictionary"),!1;default:return this._error("Zlib error"),!1}return!0};_i.prototype._after=function(){if(this._checkError()){var e=this.strm.avail_out,t=this.strm.avail_in;this.write_in_progress=!1,this.callback(t,e),this.pending_close&&this.close()}};_i.prototype._error=function(e){this.strm.msg&&(e=this.strm.msg),this.onerror(e,this.err),this.write_in_progress=!1,this.pending_close&&this.close()};_i.prototype.init=function(e,t,r,i,n){Xi(arguments.length===4||arguments.length===5,"init(windowBits, level, memLevel, strategy, [dictionary])"),Xi(e>=8&&e<=15,"invalid windowBits"),Xi(t>=-1&&t<=9,"invalid compression level"),Xi(r>=1&&r<=9,"invalid memlevel"),Xi(i===fe.Z_FILTERED||i===fe.Z_HUFFMAN_ONLY||i===fe.Z_RLE||i===fe.Z_FIXED||i===fe.Z_DEFAULT_STRATEGY,"invalid strategy"),this._init(t,e,r,i,n),this._setDictionary()};_i.prototype.params=function(){throw new Error("deflateParams Not supported")};_i.prototype.reset=function(){this._reset(),this._setDictionary()};_i.prototype._init=function(e,t,r,i,n){switch(this.level=e,this.windowBits=t,this.memLevel=r,this.strategy=i,this.flush=fe.Z_NO_FLUSH,this.err=fe.Z_OK,(this.mode===fe.GZIP||this.mode===fe.GUNZIP)&&(this.windowBits+=16),this.mode===fe.UNZIP&&(this.windowBits+=32),(this.mode===fe.DEFLATERAW||this.mode===fe.INFLATERAW)&&(this.windowBits=-1*this.windowBits),this.strm=new NQ,this.mode){case fe.DEFLATE:case fe.GZIP:case fe.DEFLATERAW:this.err=ud.deflateInit2(this.strm,this.level,fe.Z_DEFLATED,this.windowBits,this.memLevel,this.strategy);break;case fe.INFLATE:case fe.GUNZIP:case fe.INFLATERAW:case fe.UNZIP:this.err=Iu.inflateInit2(this.strm,this.windowBits);break;default:throw new Error("Unknown mode "+this.mode)}this.err!==fe.Z_OK&&this._error("Init error"),this.dictionary=n,this.write_in_progress=!1,this.init_done=!0};_i.prototype._setDictionary=function(){if(this.dictionary!=null){switch(this.err=fe.Z_OK,this.mode){case fe.DEFLATE:case fe.DEFLATERAW:this.err=ud.deflateSetDictionary(this.strm,this.dictionary);break;default:break}this.err!==fe.Z_OK&&this._error("Failed to set dictionary")}};_i.prototype._reset=function(){switch(this.err=fe.Z_OK,this.mode){case fe.DEFLATE:case fe.DEFLATERAW:case fe.GZIP:this.err=ud.deflateReset(this.strm);break;case fe.INFLATE:case fe.INFLATERAW:case fe.GUNZIP:this.err=Iu.inflateReset(this.strm);break;default:break}this.err!==fe.Z_OK&&this._error("Failed to reset stream")};fe.Zlib=_i});var hE=T(Se=>{"use strict";g();var qo=rr().Buffer,iH=gp().Transform,De=Q3(),Is=nn(),cd=fa().ok,lE=rr().kMaxLength,nH="Cannot create final Buffer. It would be larger than 0x"+lE.toString(16)+" bytes";De.Z_MIN_WINDOWBITS=8;De.Z_MAX_WINDOWBITS=15;De.Z_DEFAULT_WINDOWBITS=15;De.Z_MIN_CHUNK=64;De.Z_MAX_CHUNK=1/0;De.Z_DEFAULT_CHUNK=16*1024;De.Z_MIN_MEMLEVEL=1;De.Z_MAX_MEMLEVEL=9;De.Z_DEFAULT_MEMLEVEL=8;De.Z_MIN_LEVEL=-1;De.Z_MAX_LEVEL=9;De.Z_DEFAULT_LEVEL=De.Z_DEFAULT_COMPRESSION;var eH=Object.keys(De);for(Rv=0;Rv<eH.length;Rv++)kv=eH[Rv],kv.match(/^Z/)&&Object.defineProperty(Se,kv,{enumerable:!0,value:De[kv],writable:!1});var kv,Rv,Nv={Z_OK:De.Z_OK,Z_STREAM_END:De.Z_STREAM_END,Z_NEED_DICT:De.Z_NEED_DICT,Z_ERRNO:De.Z_ERRNO,Z_STREAM_ERROR:De.Z_STREAM_ERROR,Z_DATA_ERROR:De.Z_DATA_ERROR,Z_MEM_ERROR:De.Z_MEM_ERROR,Z_BUF_ERROR:De.Z_BUF_ERROR,Z_VERSION_ERROR:De.Z_VERSION_ERROR},tH=Object.keys(Nv);for(Bv=0;Bv<tH.length;Bv++)fE=tH[Bv],Nv[Nv[fE]]=fE;var fE,Bv;Object.defineProperty(Se,"codes",{enumerable:!0,value:Object.freeze(Nv),writable:!1});Se.Deflate=Au;Se.Inflate=Tu;Se.Gzip=Pu;Se.Gunzip=Ru;Se.DeflateRaw=ku;Se.InflateRaw=Bu;Se.Unzip=Nu;Se.createDeflate=function(e){return new Au(e)};Se.createInflate=function(e){return new Tu(e)};Se.createDeflateRaw=function(e){return new ku(e)};Se.createInflateRaw=function(e){return new Bu(e)};Se.createGzip=function(e){return new Pu(e)};Se.createGunzip=function(e){return new Ru(e)};Se.createUnzip=function(e){return new Nu(e)};Se.deflate=function(e,t,r){return typeof t=="function"&&(r=t,t={}),Cu(new Au(t),e,r)};Se.deflateSync=function(e,t){return Lu(new Au(t),e)};Se.gzip=function(e,t,r){return typeof t=="function"&&(r=t,t={}),Cu(new Pu(t),e,r)};Se.gzipSync=function(e,t){return Lu(new Pu(t),e)};Se.deflateRaw=function(e,t,r){return typeof t=="function"&&(r=t,t={}),Cu(new ku(t),e,r)};Se.deflateRawSync=function(e,t){return Lu(new ku(t),e)};Se.unzip=function(e,t,r){return typeof t=="function"&&(r=t,t={}),Cu(new Nu(t),e,r)};Se.unzipSync=function(e,t){return Lu(new Nu(t),e)};Se.inflate=function(e,t,r){return typeof t=="function"&&(r=t,t={}),Cu(new Tu(t),e,r)};Se.inflateSync=function(e,t){return Lu(new Tu(t),e)};Se.gunzip=function(e,t,r){return typeof t=="function"&&(r=t,t={}),Cu(new Ru(t),e,r)};Se.gunzipSync=function(e,t){return Lu(new Ru(t),e)};Se.inflateRaw=function(e,t,r){return typeof t=="function"&&(r=t,t={}),Cu(new Bu(t),e,r)};Se.inflateRawSync=function(e,t){return Lu(new Bu(t),e)};function Cu(e,t,r){var i=[],n=0;e.on("error",a),e.on("end",s),e.end(t),o();function o(){for(var u;(u=e.read())!==null;)i.push(u),n+=u.length;e.once("readable",o)}function a(u){e.removeListener("end",s),e.removeListener("readable",o),r(u)}function s(){var u,c=null;n>=lE?c=new RangeError(nH):u=qo.concat(i,n),i=[],e.close(),r(c,u)}}function Lu(e,t){if(typeof t=="string"&&(t=qo.from(t)),!qo.isBuffer(t))throw new TypeError("Not a string or buffer");var r=e._finishFlushFlag;return e._processChunk(t,r)}function Au(e){if(!(this instanceof Au))return new Au(e);cr.call(this,e,De.DEFLATE)}function Tu(e){if(!(this instanceof Tu))return new Tu(e);cr.call(this,e,De.INFLATE)}function Pu(e){if(!(this instanceof Pu))return new Pu(e);cr.call(this,e,De.GZIP)}function Ru(e){if(!(this instanceof Ru))return new Ru(e);cr.call(this,e,De.GUNZIP)}function ku(e){if(!(this instanceof ku))return new ku(e);cr.call(this,e,De.DEFLATERAW)}function Bu(e){if(!(this instanceof Bu))return new Bu(e);cr.call(this,e,De.INFLATERAW)}function Nu(e){if(!(this instanceof Nu))return new Nu(e);cr.call(this,e,De.UNZIP)}function rH(e){return e===De.Z_NO_FLUSH||e===De.Z_PARTIAL_FLUSH||e===De.Z_SYNC_FLUSH||e===De.Z_FULL_FLUSH||e===De.Z_FINISH||e===De.Z_BLOCK}function cr(e,t){var r=this;if(this._opts=e=e||{},this._chunkSize=e.chunkSize||Se.Z_DEFAULT_CHUNK,iH.call(this,e),e.flush&&!rH(e.flush))throw new Error("Invalid flush flag: "+e.flush);if(e.finishFlush&&!rH(e.finishFlush))throw new Error("Invalid flush flag: "+e.finishFlush);if(this._flushFlag=e.flush||De.Z_NO_FLUSH,this._finishFlushFlag=typeof e.finishFlush<"u"?e.finishFlush:De.Z_FINISH,e.chunkSize&&(e.chunkSize<Se.Z_MIN_CHUNK||e.chunkSize>Se.Z_MAX_CHUNK))throw new Error("Invalid chunk size: "+e.chunkSize);if(e.windowBits&&(e.windowBits<Se.Z_MIN_WINDOWBITS||e.windowBits>Se.Z_MAX_WINDOWBITS))throw new Error("Invalid windowBits: "+e.windowBits);if(e.level&&(e.level<Se.Z_MIN_LEVEL||e.level>Se.Z_MAX_LEVEL))throw new Error("Invalid compression level: "+e.level);if(e.memLevel&&(e.memLevel<Se.Z_MIN_MEMLEVEL||e.memLevel>Se.Z_MAX_MEMLEVEL))throw new Error("Invalid memLevel: "+e.memLevel);if(e.strategy&&e.strategy!=Se.Z_FILTERED&&e.strategy!=Se.Z_HUFFMAN_ONLY&&e.strategy!=Se.Z_RLE&&e.strategy!=Se.Z_FIXED&&e.strategy!=Se.Z_DEFAULT_STRATEGY)throw new Error("Invalid strategy: "+e.strategy);if(e.dictionary&&!qo.isBuffer(e.dictionary))throw new Error("Invalid dictionary: it should be a Buffer instance");this._handle=new De.Zlib(t);var i=this;this._hadError=!1,this._handle.onerror=function(a,s){Cv(i),i._hadError=!0;var u=new Error(a);u.errno=s,u.code=Se.codes[s],i.emit("error",u)};var n=Se.Z_DEFAULT_COMPRESSION;typeof e.level=="number"&&(n=e.level);var o=Se.Z_DEFAULT_STRATEGY;typeof e.strategy=="number"&&(o=e.strategy),this._handle.init(e.windowBits||Se.Z_DEFAULT_WINDOWBITS,n,e.memLevel||Se.Z_DEFAULT_MEMLEVEL,o,e.dictionary),this._buffer=qo.allocUnsafe(this._chunkSize),this._offset=0,this._level=n,this._strategy=o,this.once("end",this.close),Object.defineProperty(this,"_closed",{get:function(){return!r._handle},configurable:!0,enumerable:!0})}Is.inherits(cr,iH);cr.prototype.params=function(e,t,r){if(e<Se.Z_MIN_LEVEL||e>Se.Z_MAX_LEVEL)throw new RangeError("Invalid compression level: "+e);if(t!=Se.Z_FILTERED&&t!=Se.Z_HUFFMAN_ONLY&&t!=Se.Z_RLE&&t!=Se.Z_FIXED&&t!=Se.Z_DEFAULT_STRATEGY)throw new TypeError("Invalid strategy: "+t);if(this._level!==e||this._strategy!==t){var i=this;this.flush(De.Z_SYNC_FLUSH,function(){cd(i._handle,"zlib binding closed"),i._handle.params(e,t),i._hadError||(i._level=e,i._strategy=t,r&&r())})}else b.default.nextTick(r)};cr.prototype.reset=function(){return cd(this._handle,"zlib binding closed"),this._handle.reset()};cr.prototype._flush=function(e){this._transform(qo.alloc(0),"",e)};cr.prototype.flush=function(e,t){var r=this,i=this._writableState;(typeof e=="function"||e===void 0&&!t)&&(t=e,e=De.Z_FULL_FLUSH),i.ended?t&&b.default.nextTick(t):i.ending?t&&this.once("end",t):i.needDrain?t&&this.once("drain",function(){return r.flush(e,t)}):(this._flushFlag=e,this.write(qo.alloc(0),"",t))};cr.prototype.close=function(e){Cv(this,e),b.default.nextTick(MQ,this)};function Cv(e,t){t&&b.default.nextTick(t),e._handle&&(e._handle.close(),e._handle=null)}function MQ(e){e.emit("close")}cr.prototype._transform=function(e,t,r){var i,n=this._writableState,o=n.ending||n.ended,a=o&&(!e||n.length===e.length);if(e!==null&&!qo.isBuffer(e))return r(new Error("invalid input"));if(!this._handle)return r(new Error("zlib binding closed"));a?i=this._finishFlushFlag:(i=this._flushFlag,e.length>=n.length&&(this._flushFlag=this._opts.flush||De.Z_NO_FLUSH)),this._processChunk(e,i,r)};cr.prototype._processChunk=function(e,t,r){var i=e&&e.length,n=this._chunkSize-this._offset,o=0,a=this,s=typeof r=="function";if(!s){var u=[],c=0,l;this.on("error",function(I){l=I}),cd(this._handle,"zlib binding closed");do var p=this._handle.writeSync(t,e,o,i,this._buffer,this._offset,n);while(!this._hadError&&_(p[0],p[1]));if(this._hadError)throw l;if(c>=lE)throw Cv(this),new RangeError(nH);var d=qo.concat(u,c);return Cv(this),d}cd(this._handle,"zlib binding closed");var v=this._handle.write(t,e,o,i,this._buffer,this._offset,n);v.buffer=e,v.callback=_;function _(I,R){if(this&&(this.buffer=null,this.callback=null),!a._hadError){var k=n-R;if(cd(k>=0,"have should not go down"),k>0){var q=a._buffer.slice(a._offset,a._offset+k);a._offset+=k,s?a.push(q):(u.push(q),c+=q.length)}if((R===0||a._offset>=a._chunkSize)&&(n=a._chunkSize,a._offset=0,a._buffer=qo.allocUnsafe(a._chunkSize)),R===0){if(o+=i-I,i=I,!s)return!0;var z=a._handle.write(t,e,o,i,a._buffer,a._offset,a._chunkSize);z.callback=_,z.buffer=e;return}if(!s)return!1;r()}}};Is.inherits(Au,cr);Is.inherits(Tu,cr);Is.inherits(Pu,cr);Is.inherits(Ru,cr);Is.inherits(ku,cr);Is.inherits(Bu,cr);Is.inherits(Nu,cr)});var cH=T((Vle,uH)=>{"use strict";g();var dE=DS(),Kle=nr(),oH=hE(),DQ=8*1024*1024;function aH(e,t){var r=t&&t.maxDecompressedBytes||DQ;return oH.gunzipSync(f.Buffer.from(e,"base64"),{maxOutputLength:r})}async function sH(e,t){if(!t.expectedIssuerDid)throw new Error("expectedIssuerDid is required to verify a status list (issuer pinning); refusing to read revocation state from an unpinned/unverified JWT");var r=t.didResolver;if(!r){var i=t.issuerJwks||(t.issuerPublicJwk?{keys:[t.issuerPublicJwk]}:null);if(!i)throw new Error("Provide params.didResolver, params.issuerJwks, or params.issuerPublicJwk to verify the status list signature");r=async function(){return{jwks:i}}}var n=await dE.verifyVcJwt(e,{didResolver:r,expectedIssuerDid:t.expectedIssuerDid,allowedAlgs:t.allowedAlgs,allowLegacyDER:t.allowLegacyDER,clockToleranceSec:t.clockToleranceSec});if(!n.valid)throw new Error("Status list signature verification failed: "+(n.error||"invalid signature"));return n.payload}async function HQ(e){if(!e.issuerDid||!e.privateJwk)throw new Error("issuerDid and privateJwk are required");var t=e.listId||e.issuerDid+"/status/"+Date.now(),r=e.listSize||1e5,i=Math.ceil(r/8),n=f.Buffer.alloc(i,0),o=hE(),a=o.gzipSync(n),s=a.toString("base64"),u={"@context":["https://www.w3.org/2018/credentials/v1","https://w3id.org/vc/status-list/2021/v1"],type:["VerifiableCredential","StatusList2021Credential"],issuer:e.issuerDid,issuanceDate:new Date().toISOString(),credentialSubject:{id:t,type:"StatusList2021",statusPurpose:"revocation",encodedList:s}},c=await dE.issueVcJwt({issuerDid:e.issuerDid,subjectId:t,types:["VerifiableCredential","StatusList2021Credential"],credentialSubject:u.credentialSubject,privateJwk:e.privateJwk,alg:e.privateJwk.alg||"ES256"});return{listVcJwt:c.jwt,listId:t}}async function qQ(e){if(!e.listVcJwt||e.index===void 0||!e.status||!e.privateJwk)throw new Error("listVcJwt, index, status, and privateJwk are required");if(e.status==="suspended")throw new Error("status 'suspended' is not supported by this list: its statusPurpose is 'revocation', and suspension would be written to the same bit and read back as 'revoked'. Maintain a separate list for suspension until statusPurpose is configurable.");var t=await sH(e.listVcJwt,e),r=t.vc.credentialSubject.encodedList,i=aH(r,e),n=Math.floor(e.index/8),o=e.index%8;if(n>=i.length)throw new Error("Index out of range");var a=e.status==="revoked"?1:0;a===1?i[n]|=1<<o:i[n]&=~(1<<o);var s=oH.gzipSync(i),u=s.toString("base64"),c={id:t.vc.credentialSubject.id,type:"StatusList2021",statusPurpose:"revocation",encodedList:u},l=await dE.issueVcJwt({issuerDid:t.iss,subjectId:t.vc.credentialSubject.id,types:["VerifiableCredential","StatusList2021Credential"],credentialSubject:c,privateJwk:e.privateJwk,alg:e.privateJwk.alg||"ES256"});return{listVcJwt:l.jwt}}async function UQ(e){if(!e.listVcJwt||e.index===void 0)throw new Error("listVcJwt and index are required");var t=await sH(e.listVcJwt,e),r=t.vc.credentialSubject.encodedList,i=aH(r,e),n=Math.floor(e.index/8),o=e.index%8;if(n>=i.length)throw new Error("Index out of range");var a=i[n]>>o&1;return a===1?"revoked":"valid"}uH.exports={createStatusList:HQ,updateStatusList:qQ,getCredentialStatusEntry:UQ}});var hH=T((Wle,lH)=>{"use strict";g();var FQ=nr();function fH(e){var t;if(typeof e=="string")t=f.Buffer.from(e,"utf8");else if(f.Buffer.isBuffer(e))t=e;else if(e instanceof Uint8Array)t=f.Buffer.from(e);else throw new Error("Data must be string, Buffer, or Uint8Array");return FQ.createHash("sha256").update(t).digest("hex")}function jQ(e){if(!e.kind||!e.hash||!e.issuerDid)throw new Error("kind, hash, and issuerDid are required");var t=["VC_ANCHOR_SHA256","STATUSLIST_SHA256","PRESENTATION_SHA256"];if(t.indexOf(e.kind)===-1)throw new Error("Invalid kind. Must be one of: "+t.join(", "));if(!/^[a-fA-F0-9]{64}$/.test(e.hash))throw new Error("Invalid hash format. Must be 64 hex characters");var r={protocol:"SmartLedger",version:"1.0",type:e.kind,hash:e.hash,issuer:e.issuerDid,timestamp:e.issuedAt||new Date().toISOString()};return{json:JSON.stringify(r)}}function zQ(e,t){var r=fH(e);return r===t}function KQ(e){try{var t=JSON.parse(e);if(t.protocol!=="SmartLedger")return{valid:!1,error:"Invalid protocol"};var r=["VC_ANCHOR_SHA256","STATUSLIST_SHA256","PRESENTATION_SHA256"];return r.indexOf(t.type)===-1?{valid:!1,error:"Invalid anchor type"}:/^[a-fA-F0-9]{64}$/.test(t.hash)?{valid:!0,protocol:t.protocol,version:t.version,type:t.type,hash:t.hash,issuer:t.issuer,timestamp:t.timestamp}:{valid:!1,error:"Invalid hash format"}}catch(i){return{valid:!1,error:"Failed to parse anchor payload: "+i.message}}}lH.exports={sha256Hex:fH,buildAnchorPayload:jQ,verifyAnchorHash:zQ,parseAnchorPayload:KQ}});var fd=T((Zle,pH)=>{"use strict";g();var dH=Ki();function VQ(){var e=dH.getRandomBuffer(16);e[6]=e[6]&15|64,e[8]=e[8]&63|128;var t=e.toString("hex");return[t.substring(0,8),t.substring(8,12),t.substring(12,16),t.substring(16,20),t.substring(20,32)].join("-")}function GQ(e){return dH.getRandomBuffer(Math.ceil(e/2)).toString("hex").substring(0,e)}pH.exports={uuid4:VQ,randomHex:GQ}});var bH=T((Jle,yH)=>{"use strict";g();var ld=sr(),pE=Le(),gE=dn(),gH=gt(),mE=ei(),Mr=Ie(),Xle=at(),WQ=fd();function mH(e,t){if(t=t||{},t.issuerPublicKey)return t.issuerPublicKey instanceof ld?t.issuerPublicKey:ld.fromString(t.issuerPublicKey);var r=e&&e.issuer;if(typeof r!="string")return null;try{var i=r.split("#")[0].split(":")[2];return i?ld.fromString(i):null}catch{return null}}var Nf={PROPERTY_TITLE:"PropertyTitle",VEHICLE_TITLE:"VehicleTitle",INTELLECTUAL_PROPERTY:"IntellectualProperty",MUSIC_LICENSE:"MusicLicense",SOFTWARE_LICENSE:"SoftwareLicense",FINANCIAL_INSTRUMENT:"FinancialInstrument",PROMISSORY_NOTE:"PromissoryNote",BOND:"Bond",EQUITY_SHARE:"EquityShare",PROFESSIONAL_LICENSE:"ProfessionalLicense",REGULATORY_PERMIT:"RegulatoryPermit",ACCESS_RIGHT:"AccessRight",VOTING_RIGHT:"VotingRight",ROYALTY_RIGHT:"RoyaltyRight",USAGE_RIGHT:"UsageRight"},vH={create:function(e,t,r,i,n,o){o=o||{},Mr.checkArgument(typeof e=="string","Right type must be string"),Mr.checkArgument(typeof t=="string","Issuer DID must be string"),Mr.checkArgument(typeof r=="string","Subject DID must be string"),Mr.checkArgument(i&&typeof i=="object","Claim must be object");var a=Object.values(Nf);Mr.checkArgument(a.includes(e),"Invalid right type: "+e);var s={"@context":["https://www.w3.org/2018/credentials/v1","https://smartledger.technology/contexts/ltp/v1"],id:"urn:uuid:"+this._generateUUID(),type:["VerifiableCredential","LegalRightToken",e],issuer:t,issuanceDate:new Date().toISOString(),credentialSubject:{id:r,rightType:e,claim:i,jurisdiction:o.jurisdiction||"US",purpose:o.purpose||"legal_right",validFrom:o.validFrom||new Date().toISOString(),validUntil:o.validUntil||null,transferable:o.transferable!==!1,revocable:o.revocable!==!1}};return o.metadata&&(s.credentialSubject.metadata=o.metadata),s},prepareRightToken:function(e,t,r,i,n,o){o=o||{},Mr.checkArgument(typeof e=="string","Right type must be string"),Mr.checkArgument(typeof t=="string","Issuer DID must be string"),Mr.checkArgument(typeof r=="string","Subject DID must be string"),Mr.checkArgument(i&&typeof i=="object","Claim must be object"),Mr.checkArgument(n instanceof mE,"Invalid issuer private key");var a=Object.values(Nf);Mr.checkArgument(a.includes(e),"Invalid right type: "+e);try{var s=this.create(e,t,r,i,n,o),u=this._signToken(s,n);return{success:!0,rightToken:u,tokenHash:u.tokenHash,metadata:{type:e,issuer:t,subject:r,transferable:s.credentialSubject.transferable,revocable:s.credentialSubject.revocable,jurisdiction:s.credentialSubject.jurisdiction},externalOperations:{storeToken:{endpoint:"POST /rights/tokens",data:{token:u,metadata:{type:e,issuer:t,subject:r,transferable:s.credentialSubject.transferable,revocable:s.credentialSubject.revocable,jurisdiction:s.credentialSubject.jurisdiction}}},indexToken:{endpoint:"POST /rights/index",data:{tokenId:u.id,tokenHash:u.tokenHash,type:e,issuer:t,subject:r,issuedAt:u.issuanceDate}},notifyParties:{endpoint:"POST /notifications/right-issued",data:{tokenId:u.id,issuer:t,subject:r,rightType:e}}}}}catch(c){return{success:!1,error:c.message}}},prepareRightTokenVerification:function(e,t){t=t||{};try{var r=[],i=[];this._validateTokenStructure(e,r),this._verifyTokenSignature(e,r,t),this._validateTokenTemporal(e,r,i),this._validateRightType(e,r),t.requireJurisdiction&&this._validateJurisdiction(e,t.allowedJurisdictions,r);var n={valid:r.length===0,errors:r,warnings:i,issuerDID:e.issuer,subjectDID:e.credentialSubject?e.credentialSubject.id:null,rightType:e.credentialSubject?e.credentialSubject.rightType:null,transferable:e.credentialSubject?e.credentialSubject.transferable:null,revocable:e.credentialSubject?e.credentialSubject.revocable:null,verifiedAt:new Date().toISOString()};return{success:!0,verification:n,externalOperations:{recordVerification:{endpoint:"POST /rights/verification-record",data:{tokenId:e.id,result:n.valid,errors:r,warnings:i,verifiedAt:n.verifiedAt}},auditVerification:{endpoint:"POST /audit/right-verification",data:{tokenId:e.id,rightType:n.rightType,issuer:n.issuerDID,subject:n.subjectDID,result:n.valid,verifiedAt:n.verifiedAt}},updateTokenStatus:n.valid?{endpoint:"PUT /rights/tokens/"+e.id+"/status",data:{status:"VERIFIED",verifiedAt:n.verifiedAt}}:null}}}catch(o){return{success:!1,error:"Verification preparation failed: "+o.message}}},prepareRightTokenTransfer:function(e,t,r,i){i=i||{},Mr.checkArgument(e&&typeof e=="object","Invalid token"),Mr.checkArgument(typeof t=="string","New owner DID must be string"),Mr.checkArgument(r instanceof mE,"Invalid current owner key");try{var n=this.prepareRightTokenVerification(e,{});if(!n.success||!n.verification.valid)return{success:!1,error:"Cannot transfer invalid token: "+n.verification.errors.join(", ")};if(!e.credentialSubject.transferable)return{success:!1,error:"Token is not transferable"};var o=e.credentialSubject&&e.credentialSubject.id,a=mH({issuer:o},{issuerPublicKey:i.currentOwnerPublicKey});if(!a)return{success:!1,error:"Cannot resolve current owner public key from token.credentialSubject.id; pass options.currentOwnerPublicKey"};if(r.toPublicKey().toString()!==a.toString())return{success:!1,error:"Unauthorized transfer: signing key does not match the current owner"};var s={"@context":["https://www.w3.org/2018/credentials/v1","https://smartledger.technology/contexts/ltp/v1"],id:"urn:uuid:"+this._generateUUID(),type:["VerifiableCredential","LegalRightTransfer"],issuer:e.credentialSubject.id,issuanceDate:new Date().toISOString(),credentialSubject:{id:t,originalToken:e.id,transferFrom:e.credentialSubject.id,transferTo:t,transferDate:new Date().toISOString(),transferReason:i.reason||"ownership_transfer",consideration:i.consideration||null}},u=this._signToken(s,r),c=JSON.parse(JSON.stringify(e));c.id="urn:uuid:"+this._generateUUID(),c.issuanceDate=new Date().toISOString(),c.credentialSubject.id=t,c.credentialSubject.transferHistory=c.credentialSubject.transferHistory||[],c.credentialSubject.transferHistory.push({transferId:u.id,transferDate:u.issuanceDate,from:e.credentialSubject.id,to:t}),delete c.proof;var l=this._signToken(c,r);return{success:!0,newToken:l,transferProof:u,transferId:u.id,externalOperations:{recordTransfer:{endpoint:"POST /rights/transfers",data:{originalTokenId:e.id,newTokenId:l.id,transferProof:u,fromOwner:e.credentialSubject.id,toOwner:t,transferDate:u.issuanceDate}},updateOwnership:{endpoint:"PUT /rights/tokens/"+e.id+"/ownership",data:{newOwner:t,transferId:u.id,transferDate:u.issuanceDate,previousOwner:e.credentialSubject.id}},notifyParties:{endpoint:"POST /notifications/right-transferred",data:{originalTokenId:e.id,newTokenId:l.id,fromOwner:e.credentialSubject.id,toOwner:t,rightType:e.credentialSubject.rightType}},auditTransfer:{endpoint:"POST /audit/right-transfer",data:{originalTokenId:e.id,newTokenId:l.id,transferId:u.id,fromOwner:e.credentialSubject.id,toOwner:t,transferredAt:u.issuanceDate}}}}}catch(p){return{success:!1,error:p.message}}},prepareObligationToken:function(e,t,r,i){Mr.checkArgument(e&&typeof e=="object","Invalid right token"),Mr.checkArgument(typeof t=="string","Obligor DID must be string"),Mr.checkArgument(r&&typeof r=="object","Obligation must be object"),Mr.checkArgument(i instanceof mE,"Invalid issuer key");try{var n={"@context":["https://www.w3.org/2018/credentials/v1","https://smartledger.technology/contexts/ltp/v1"],id:"urn:uuid:"+this._generateUUID(),type:["VerifiableCredential","LegalObligationToken"],issuer:e.issuer,issuanceDate:new Date().toISOString(),credentialSubject:{id:t,obligationType:"correlative_obligation",correlativeRight:e.id,rightHolder:e.credentialSubject.id,obligation:r,jurisdiction:e.credentialSubject.jurisdiction,purpose:e.credentialSubject.purpose}},o=this._signToken(n,i);return{success:!0,obligationToken:o,correlativeRight:e.id,externalOperations:{storeObligation:{endpoint:"POST /obligations/tokens",data:{obligationToken:o,correlativeRightId:e.id,obligor:t,rightHolder:e.credentialSubject.id}},linkToRight:{endpoint:"POST /rights/tokens/"+e.id+"/obligations",data:{obligationId:o.id,obligor:t,obligationType:"correlative_obligation"}},notifyObligor:{endpoint:"POST /notifications/obligation-created",data:{obligationId:o.id,obligor:t,rightHolder:e.credentialSubject.id,correlativeRight:e.id}}}}}catch(a){return{success:!1,error:a.message}}},prepareRightTypeValidation:function(e){Mr.checkArgument(typeof e=="string","Right type must be string");var t=Object.values(Nf),r=t.includes(e);return{success:!0,validation:{type:e,valid:r,availableTypes:t,category:this._categorizeRightType(e),description:this._getRightTypeDescription(e)},externalOperations:{validateType:{endpoint:"POST /rights/validate-type",data:{type:e,valid:r}}}}},_categorizeRightType:function(e){var t={PropertyTitle:"PROPERTY_RIGHT",VehicleTitle:"PROPERTY_RIGHT",IntellectualProperty:"IP_RIGHT",MusicLicense:"IP_RIGHT",SoftwareLicense:"IP_RIGHT",FinancialInstrument:"FINANCIAL_RIGHT",PromissoryNote:"FINANCIAL_RIGHT",Bond:"FINANCIAL_RIGHT",EquityShare:"FINANCIAL_RIGHT",ProfessionalLicense:"LICENSE_RIGHT",RegulatoryPermit:"LICENSE_RIGHT",AccessRight:"ACCESS_RIGHT",VotingRight:"GOVERNANCE_RIGHT",RoyaltyRight:"IP_RIGHT",UsageRight:"ACCESS_RIGHT"};return t[e]||"UNKNOWN"},_getRightTypeDescription:function(e){var t={PropertyTitle:"Legal ownership of real estate property",VehicleTitle:"Legal ownership of motor vehicle",IntellectualProperty:"Rights to intellectual property assets",MusicLicense:"License for music performance and usage",SoftwareLicense:"License for software usage and distribution",FinancialInstrument:"Rights related to financial instruments",PromissoryNote:"Promise to pay a specified amount",Bond:"Debt security representing loan",EquityShare:"Ownership stake in company",ProfessionalLicense:"License for professional practice",RegulatoryPermit:"Permit for regulated activities",AccessRight:"Right to access resources or locations",VotingRight:"Right to participate in governance",RoyaltyRight:"Right to receive royalty payments",UsageRight:"Right to use specific assets or services"};return t[e]||"Unknown right type"},getRightTypes:function(){return Nf},verifyToken:function(e,t){var r=[];try{if(Mr.checkArgument(e&&typeof e=="object","Invalid token"),!e.proof||!e.proof.jws)return r.push("Missing signature proof"),{valid:!1,errors:r};var i=t instanceof ld?t:ld.fromString(t),n=this._canonicalizeToken(e),o=pE.sha256(f.Buffer.from(n));if(e.tokenHash&&e.tokenHash!==o.toString("hex"))return r.push("Token hash mismatch"),{valid:!1,errors:r};var a=e.proof.jws.split(".");if(a.length!==3||!a[2])return r.push("Malformed JWS"),{valid:!1,errors:r};var s=gH.fromDER(f.Buffer.from(a[2],"base64url")),u=new gE;return u.hashbuf=o,u.sig=s,u.pubkey=i,u.verify()||r.push("Signature verification failed"),{valid:r.length===0,errors:r,tokenHash:o.toString("hex"),verifiedAt:new Date().toISOString()}}catch(c){return r.push(c.message),{valid:!1,errors:r}}},_signToken:function(e,t){var r=this._canonicalizeToken(e),i=pE.sha256(f.Buffer.from(r)),n=new gE;n.hashbuf=i,n.privkey=t,n.pubkey=t.toPublicKey(),n.sign();var o=n.sig,a={type:"EcdsaSecp256k1Signature2019",created:new Date().toISOString(),verificationMethod:"did:smartledger:"+t.toPublicKey().toString()+"#keys-1",proofPurpose:"assertionMethod",jws:this._createJWS(i,o)},s=JSON.parse(JSON.stringify(e));return s.proof=a,s.tokenHash=i.toString("hex"),s},_createJWS:function(e,t){var r={alg:"ES256K",typ:"JWT"},i=f.Buffer.from(JSON.stringify(r)).toString("base64url"),n=t.toDER().toString("base64url");return i+".."+n},_canonicalizeToken:function(e){var t=JSON.parse(JSON.stringify(e));return delete t.proof,delete t.tokenHash,JSON.stringify(this._sortObjectKeys(t))},_sortObjectKeys:function(e){if(Array.isArray(e))return e.map(this._sortObjectKeys.bind(this));if(e!==null&&typeof e=="object"){var t={};return Object.keys(e).sort().forEach(function(r){t[r]=this._sortObjectKeys(e[r])}.bind(this)),t}return e},_validateTokenStructure:function(e,t){e["@context"]||t.push("Missing @context"),e.id||t.push("Missing id"),(!e.type||!Array.isArray(e.type))&&t.push("Missing or invalid type"),e.issuer||t.push("Missing issuer"),e.issuanceDate||t.push("Missing issuanceDate"),e.credentialSubject||t.push("Missing credentialSubject"),e.proof||t.push("Missing proof")},_verifyTokenSignature:function(e,t,r){try{if(!e.proof||!e.proof.jws){t.push("Missing signature proof");return}var i=this._canonicalizeToken(e),n=pE.sha256(f.Buffer.from(i));if(e.tokenHash&&e.tokenHash!==n.toString("hex")){t.push("Token hash mismatch");return}var o=mH(e,r);if(!o){t.push("Signature not verified: issuer public key could not be resolved from token.issuer; pass options.issuerPublicKey");return}var a=e.proof.jws.split(".");if(a.length!==3||!a[2]){t.push("Malformed JWS");return}var s=gH.fromDER(f.Buffer.from(a[2],"base64url")),u=new gE;u.hashbuf=n,u.sig=s,u.pubkey=o,u.verify()!==!0&&t.push("Signature verification failed")}catch(c){t.push("Signature verification failed: "+c.message)}},_validateTokenTemporal:function(e,t,r){var i=new Date,n=new Date(e.issuanceDate);if(n>i&&t.push("Token issued in the future"),e.credentialSubject.validFrom){var o=new Date(e.credentialSubject.validFrom);i<o&&r.push("Token not yet valid")}if(e.credentialSubject.validUntil){var a=new Date(e.credentialSubject.validUntil);i>a&&t.push("Token expired")}},_validateRightType:function(e,t){if(!e.credentialSubject.rightType){t.push("Missing rightType");return}var r=Object.values(Nf);r.includes(e.credentialSubject.rightType)||t.push("Invalid right type: "+e.credentialSubject.rightType)},_validateJurisdiction:function(e,t,r){if(!e.credentialSubject.jurisdiction){r.push("Missing jurisdiction");return}t&&Array.isArray(t)&&(t.includes(e.credentialSubject.jurisdiction)||r.push("Jurisdiction not allowed: "+e.credentialSubject.jurisdiction))},_generateUUID:function(){return WQ.uuid4()}};vH.RightTypes=Nf;yH.exports=vH});var wH=T((ehe,_H)=>{"use strict";g();var Cf=Le(),Fi=Ie(),YQ=fd(),ZQ=Vc(),$Q=ts(),Mu={PropertyTitle:{title:"Property Title",description:"Real estate property ownership title",type:"object",required:["propertyId","address","ownershipType"],properties:{propertyId:{type:"string",description:"Unique property identifier"},address:{type:"object",required:["street","city","state","country"],properties:{street:{type:"string"},city:{type:"string"},state:{type:"string"},country:{type:"string"},postalCode:{type:"string"}}},ownershipType:{type:"string",enum:["fee_simple","leasehold","joint_tenancy","tenancy_in_common"]},titleNumber:{type:"string"},registeredDate:{type:"string",format:"date-time"},legalDescription:{type:"string"},encumbrances:{type:"array",items:{type:"object",properties:{type:{type:"string"},amount:{type:"number"},description:{type:"string"}}}}}},VehicleTitle:{title:"Vehicle Title",description:"Motor vehicle ownership title",type:"object",required:["vin","make","model","year"],properties:{vin:{type:"string",pattern:"^[A-HJ-NPR-Z0-9]{17}$",description:"Vehicle Identification Number"},make:{type:"string"},model:{type:"string"},year:{type:"integer",minimum:1900,maximum:2030},titleNumber:{type:"string"},registeredState:{type:"string"},mileage:{type:"integer",minimum:0},color:{type:"string"},fuelType:{type:"string",enum:["gasoline","diesel","electric","hybrid","other"]},liens:{type:"array",items:{type:"object",properties:{lienholderName:{type:"string"},lienAmount:{type:"number"},lienDate:{type:"string",format:"date"}}}}}},PromissoryNote:{title:"Promissory Note",description:"Legal promise to pay a specified amount",type:"object",required:["principal","interestRate","maturityDate","borrower","lender"],properties:{principalAmount:{type:"number",minimum:0,description:"Principal amount in base currency units"},currency:{type:"string",default:"USD"},interestRate:{type:"number",minimum:0,maximum:100,description:"Annual interest rate percentage"},maturityDate:{type:"string",format:"date",description:"Date when principal and interest are due"},payee:{type:"string",description:"DID of the payee (creditor)"},payor:{type:"string",description:"DID of the payor (debtor)"},paymentSchedule:{type:"string",enum:["lump_sum","monthly","quarterly","annually"]},collateral:{type:"array",items:{type:"object",properties:{description:{type:"string"},value:{type:"number"},type:{type:"string"}}}},defaultProvisions:{type:"string"},governingLaw:{type:"string"}}},IntellectualProperty:{title:"Intellectual Property",description:"Intellectual property rights and licensing",type:"object",required:["ipType","title","registrationNumber"],properties:{ipType:{type:"string",enum:["patent","trademark","copyright","trade_secret"]},title:{type:"string"},creator:{type:"string",description:"Creator DID"},registrationNumber:{type:"string"},registrationDate:{type:"string",format:"date"},expirationDate:{type:"string",format:"date"},jurisdiction:{type:"string"},description:{type:"string"},claims:{type:"array",items:{type:"string"}},priorArt:{type:"array",items:{type:"object",properties:{reference:{type:"string"},date:{type:"string",format:"date"},relevance:{type:"string"}}}}}},ProfessionalLicense:{title:"Professional License",description:"Professional practice license or certification",type:"object",required:["licenseType","licenseNumber","issuingAuthority","expirationDate"],properties:{licenseType:{type:"string"},licenseNumber:{type:"string"},issuingAuthority:{type:"string"},licensee:{type:"string",description:"Licensee DID"},issueDate:{type:"string",format:"date"},expirationDate:{type:"string",format:"date"},renewalDate:{type:"string",format:"date"},jurisdiction:{type:"string"},scope:{type:"string"},restrictions:{type:"array",items:{type:"string"}},continuing_education:{type:"object",properties:{hours_required:{type:"integer"},deadline:{type:"string",format:"date"},completed_hours:{type:"integer"}}}}},MusicLicense:{title:"Music License",description:"Music performance and usage licensing",type:"object",required:["songTitle","artist","licenseType","royaltyRate"],properties:{workTitle:{type:"string"},composer:{type:"string",description:"Composer DID"},performer:{type:"string",description:"Performer DID"},licenseType:{type:"string",enum:["mechanical","performance","synchronization","master_use"]},territory:{type:"string"},duration:{type:"string"},royaltyRate:{type:"number",minimum:0,maximum:100},advancePayment:{type:"number",minimum:0},exclusivity:{type:"boolean"},mediaTypes:{type:"array",items:{type:"string",enum:["cd","vinyl","digital","streaming","broadcast","film","tv"]}},usage_restrictions:{type:"string"},copyrightNotice:{type:"string"}}}},XQ={prepareClaimValidation:function(e,t){try{Fi.checkArgument(e&&typeof e=="object","Invalid claim"),Fi.checkArgument(typeof t=="string","Schema name must be string");var r=Mu[t];if(!r)return{success:!1,error:"Unknown schema: "+t};var i=[],n=[];this._validateObject(e,r,"",i,n);var o={valid:i.length===0,errors:i,warnings:n,schema:t,claimHash:Cf.sha256(f.Buffer.from(this._canonicalizeWith(e,this.CANONICALIZATION.LEGACY))).toString("hex"),canonical:this._canonicalizeWith(e,this.CANONICALIZATION.LEGACY)};return{success:!0,validation:o,claim:e,schema:r,externalOperations:{store:{endpoint:"POST /claims/validate",data:{claim:e,validation:o,schema:t}},index:{endpoint:"POST /claims/index",data:{claimHash:o.claimHash,schemaName:t,valid:o.valid}}}}}catch(a){return{success:!1,error:"Validation preparation failed: "+a.message}}},prepareClaimAttestation:function(e,t,r){try{Fi.checkArgument(e&&typeof e=="object","Invalid claim"),Fi.checkArgument(typeof t=="string","Schema name must be string"),Fi.checkArgument(r&&typeof r=="object","Invalid attestor");var i=this.prepareClaimValidation(e,t);if(!i.success||!i.validation.valid)return{success:!1,error:"Cannot attest invalid claim",validation:i};var n={type:"LTP_CLAIM_ATTESTATION",claimHash:i.validation.claimHash,schemaName:t,attestor:{did:r.did||r.id,name:r.name||"Unknown",authority:r.authority||null,jurisdiction:r.jurisdiction||null},attestedAt:new Date().toISOString(),confidence:r.confidence||100,evidence:r.evidence||null,notes:r.notes||null},o=Cf.sha256(f.Buffer.from(this._canonicalizeWith(n,this.CANONICALIZATION.LEGACY))).toString("hex");return n.attestationHash=o,{success:!0,attestation:n,claim:e,validation:i.validation,externalOperations:{storeAttestation:{endpoint:"POST /claims/"+i.validation.claimHash+"/attestations",data:n},notifyStakeholders:{endpoint:"POST /notifications/claim-attested",data:{claimHash:i.validation.claimHash,attestorDid:n.attestor.did,attestationHash:o}}}}}catch(a){return{success:!1,error:"Attestation preparation failed: "+a.message}}},prepareClaimDispute:function(e,t,r){try{Fi.checkArgument(typeof e=="string","Claim hash must be string"),Fi.checkArgument(t&&typeof t=="object","Invalid disputant"),Fi.checkArgument(r&&typeof r=="object","Invalid dispute");var i={type:"LTP_CLAIM_DISPUTE",claimHash:e,disputant:{did:t.did||t.id,name:t.name||"Unknown",jurisdiction:t.jurisdiction||null},dispute:{reason:r.reason||"UNSPECIFIED",category:r.category||"ACCURACY",description:r.description||"",evidence:r.evidence||null,requestedAction:r.requestedAction||"REVIEW"},disputedAt:new Date().toISOString(),status:"FILED",priority:r.priority||"NORMAL"},n=Cf.sha256(f.Buffer.from(this._canonicalizeWith(i,this.CANONICALIZATION.LEGACY))).toString("hex");return i.disputeHash=n,{success:!0,dispute:i,disputeId:this._generateDisputeId(e),externalOperations:{fileDispute:{endpoint:"POST /claims/"+e+"/disputes",data:i},notifyStakeholders:{endpoint:"POST /notifications/claim-disputed",data:{claimHash:e,disputantDid:i.disputant.did,disputeHash:n}},escalate:{endpoint:"POST /disputes/escalate",data:{disputeHash:n,priority:i.priority}}}}}catch(o){return{success:!1,error:"Dispute preparation failed: "+o.message}}},prepareBulkClaimValidation:function(e,t){try{Fi.checkArgument(Array.isArray(e),"Claims must be array"),Fi.checkArgument(typeof t=="string","Schema name must be string");var r=[],i=[],n=0;e.forEach(function(s,u){try{var c=this.prepareClaimValidation(s,t);c.success&&c.validation.valid&&n++,r.push({index:u,result:c})}catch(l){i.push({index:u,error:l.message})}}.bind(this));var o=this._generateBatchId(),a=Cf.sha256(f.Buffer.from(JSON.stringify(r.map(s=>s.result.validation.claimHash)))).toString("hex");return{success:!0,batchId:o,batchHash:a,totalClaims:e.length,validClaims:n,invalidClaims:e.length-n,validations:r,errors:i,externalOperations:{storeBatch:{endpoint:"POST /claims/batch-validate",data:{batchId:o,batchHash:a,schemaName:t,validations:r}},generateReport:{endpoint:"POST /reports/bulk-validation",data:{batchId:o,summary:{total:e.length,valid:n,invalid:e.length-n}}}}}}catch(s){return{success:!1,error:"Bulk validation preparation failed: "+s.message}}},CANONICALIZATION:{JCS:"jcs",LEGACY:"legacy"},canonicalize:function(e,t){return this._canonicalizeWith(e,this._resolveCanonicalization(t,"LTP.Claim.canonicalize"))},hash:function(e,t){var r=this._canonicalizeWith(e,this._resolveCanonicalization(t,"LTP.Claim.hash"));return Cf.sha256(f.Buffer.from(r)).toString("hex")},_canonicalizeWith:function(e,t){if(Fi.checkArgument(e&&typeof e=="object","Invalid claim"),t===this.CANONICALIZATION.JCS)return ZQ.stringify(e);var r=this._sortObjectKeys(e);return JSON.stringify(r)},_resolveCanonicalization:function(e,t){return e===void 0?($Q({what:t+"() without a canonicalization argument",since:"9.2.0",removeIn:"10.0.0",use:t+"(claim, bsv.LTP.Claim.CANONICALIZATION.JCS)",why:"the default sorted-key form is not RFC 8785, so other implementations compute a different claim hash"}),this.CANONICALIZATION.LEGACY):(Fi.checkArgument(e===this.CANONICALIZATION.JCS||e===this.CANONICALIZATION.LEGACY,"Unknown canonicalization: "+e+". Expected 'jcs' or 'legacy' (bsv.LTP.Claim.CANONICALIZATION)"),e)},prepareClaimTemplate:function(e,t){t=t||{};try{var r=Mu[e];if(!r)return{success:!1,error:"Unknown schema: "+e};var i=this._createTemplateFromSchema(r),n=this._generateFormStructure(r);return{success:!0,schemaName:e,template:i,schema:r,formStructure:n,validation:{required:r.required||[],patterns:this._extractPatterns(r),enums:this._extractEnums(r)},externalOperations:{generateForm:{endpoint:"POST /forms/generate",data:{schemaName:e,formStructure:n,template:i}},saveTemplate:{endpoint:"POST /templates/claim",data:{schemaName:e,template:i,customizations:t.customizations||{}}}}}}catch(o){return{success:!1,error:"Template preparation failed: "+o.message}}},getSchemas:function(){return Mu},getSchemaNames:function(){return Object.keys(Mu)},getSchema:function(e){return Mu[e]||null},addSchema:function(e,t){Fi.checkArgument(typeof e=="string","Schema name must be string"),Fi.checkArgument(t&&typeof t=="object","Invalid schema"),Mu[e]=t},createTemplate:function(e){var t=Mu[e];if(!t)throw new Error("Unknown schema: "+e);return this._createTemplateFromSchema(t)},_generateDisputeId:function(e){var t="dispute_"+e+"_"+Date.now();return Cf.sha256(f.Buffer.from(t)).toString("hex").substring(0,16)},_generateBatchId:function(){return YQ.randomHex(16)},_generateFormStructure:function(e){var t={type:"form",title:e.title||"Legal Claim Form",description:e.description||"",fields:[]};return e.properties&&Object.keys(e.properties).forEach(function(r){var i=e.properties[r],n={name:r,label:this._humanizeFieldName(r),type:this._mapSchemaTypeToFormType(i),required:e.required&&e.required.includes(r),validation:this._extractFieldValidation(i)};i.enum&&(n.options=i.enum.map(function(o){return{value:o,label:this._humanizeValue(o)}}.bind(this))),t.fields.push(n)}.bind(this)),t},_extractPatterns:function(e){var t={};return e.properties&&Object.keys(e.properties).forEach(function(r){var i=e.properties[r];i.pattern&&(t[r]=i.pattern)}),t},_extractEnums:function(e){var t={};return e.properties&&Object.keys(e.properties).forEach(function(r){var i=e.properties[r];i.enum&&(t[r]=i.enum)}),t},_mapSchemaTypeToFormType:function(e){switch(e.type){case"string":return e.enum?"select":e.format==="date"?"date":e.format==="date-time"?"datetime":"text";case"number":case"integer":return"number";case"boolean":return"checkbox";case"array":return"list";case"object":return"fieldset";default:return"text"}},_extractFieldValidation:function(e){var t={};return e.pattern&&(t.pattern=e.pattern),e.minimum!==void 0&&(t.min=e.minimum),e.maximum!==void 0&&(t.max=e.maximum),e.format&&(t.format=e.format),t},_humanizeFieldName:function(e){return e.replace(/([A-Z])/g," $1").replace(/^./,function(t){return t.toUpperCase()}).replace(/_/g," ")},_humanizeValue:function(e){return e.replace(/_/g," ").replace(/\b\w/g,function(t){return t.toUpperCase()})},_validateObject:function(e,t,r,i,n){t.type==="object"?(t.required&&Array.isArray(t.required)&&t.required.forEach(function(o){e.hasOwnProperty(o)||i.push("Missing required field: "+this._getFieldPath(r,o))}.bind(this)),t.properties&&Object.keys(e).forEach(function(o){var a=this._getFieldPath(r,o),s=t.properties[o];s?this._validateValue(e[o],s,a,i,n):n.push("Unknown field: "+a)}.bind(this))):this._validateValue(e,t,r,i,n)},_validateValue:function(e,t,r,i,n){if(t.type){var o=Array.isArray(e)?"array":typeof e;if(o!==t.type){i.push("Invalid type for "+r+": expected "+t.type+", got "+o);return}}if(t.type==="string"&&(t.pattern&&!new RegExp(t.pattern).test(e)&&i.push("Value does not match pattern for "+r),t.enum&&!t.enum.includes(e)&&i.push("Invalid enum value for "+r+": "+e),t.format==="date"&&!this._isValidDate(e)&&i.push("Invalid date format for "+r),t.format==="date-time"&&!this._isValidDateTime(e)&&i.push("Invalid date-time format for "+r)),(t.type==="number"||t.type==="integer")&&(t.minimum!==void 0&&e<t.minimum&&i.push("Value below minimum for "+r+": "+e+" < "+t.minimum),t.maximum!==void 0&&e>t.maximum&&i.push("Value above maximum for "+r+": "+e+" > "+t.maximum),t.type==="integer"&&!Number.isInteger(e)&&i.push("Value must be integer for "+r)),t.type==="array"&&t.items)for(var a=0;a<e.length;a++)this._validateValue(e[a],t.items,r+"["+a+"]",i,n);t.type==="object"&&this._validateObject(e,t,r,i,n)},_sortObjectKeys:function(e){if(Array.isArray(e))return e.map(this._sortObjectKeys.bind(this));if(e!==null&&typeof e=="object"){var t={};return Object.keys(e).sort().forEach(function(r){t[r]=this._sortObjectKeys(e[r])}.bind(this)),t}return e},_createTemplateFromSchema:function(e){if(e.type==="object"){var t={};return e.properties&&Object.keys(e.properties).forEach(function(r){var i=e.properties[r];t[r]=this._getDefaultValue(i)}.bind(this)),t}return this._getDefaultValue(e)},_getDefaultValue:function(e){if(e.default!==void 0)return e.default;switch(e.type){case"string":return e.enum?e.enum[0]:e.format==="date"?"2023-01-01":e.format==="date-time"?new Date().toISOString():"PLACEHOLDER_STRING";case"number":case"integer":return e.minimum||0;case"boolean":return!1;case"array":return[];case"object":return this._createTemplateFromSchema(e);default:return null}},_getFieldPath:function(e,t){return e?e+"."+t:t},_isValidDate:function(e){var t=new Date(e);return!isNaN(t.getTime())&&e.match(/^\d{4}-\d{2}-\d{2}$/)},_isValidDateTime:function(e){var t=new Date(e);return!isNaN(t.getTime())}};_H.exports=XQ});var EH=T((rhe,SH)=>{"use strict";g();var hd=Le(),Lf=Ie(),JQ={prepareTokenCommitment:function(e,t){t=t||{},Lf.checkArgument(e&&typeof e=="object","Invalid token");try{var r=this._createCommitment(e,t),i=this._formatOpReturn(r,t),n=this._createTxTemplate(i,t);return{success:!0,commitment:r,opReturnData:i,txTemplate:n,preparedAt:new Date().toISOString(),metadata:{tokenId:e.id,purpose:t.purpose||"legal_token_anchor",version:"LTP.v1"}}}catch(o){return{success:!1,error:o.message}}},prepareBatchCommitment:function(e,t){t=t||{},Lf.checkArgument(Array.isArray(e),"Tokens must be array");try{var r=this._createBatchCommitment(e,t),i=this._formatOpReturn(r,t),n=this._createTxTemplate(i,t);return{success:!0,batchCommitment:r,opReturnData:i,txTemplate:n,tokenCount:e.length,preparedAt:new Date().toISOString(),metadata:{purpose:t.purpose||"legal_token_batch_anchor",version:"LTP.v1"}}}catch(o){return{success:!1,error:o.message}}},verifyTokenAnchor:function(e,t,r){Lf.checkArgument(e&&typeof e=="object","Invalid token"),Lf.checkArgument(typeof t=="string","Transaction ID must be string");try{var i=this._createCommitment(e,{}),n=this._extractOpReturn(r);if(!n)return{valid:!1,error:"No OP_RETURN data found in transaction"};var o=this._verifyCommitment(i,n);return{valid:o,chainVerified:!1,txid:t,commitment:i,anchorData:n,verifiedAt:new Date().toISOString()}}catch(a){return{valid:!1,error:a.message}}},formatRevocation:function(e,t){Lf.checkArgument(typeof e=="string","Token ID must be string"),Lf.checkArgument(t&&typeof t=="object","Invalid revocation data");try{var r={type:"LTP_REVOCATION",tokenId:e,reason:t.reason||"UNSPECIFIED",revokedBy:t.revokedBy||"UNKNOWN",revokedAt:new Date().toISOString(),effectiveDate:t.effectiveDate||new Date().toISOString(),legalBasis:t.legalBasis||null,evidence:t.evidence||null},i=hd.sha256(f.Buffer.from(JSON.stringify(r))).toString("hex");return{success:!0,revocation:r,revocationHash:i,opReturnData:this._formatOpReturn({hash:i,type:"REVOCATION"},{})}}catch(n){return{success:!1,error:n.message}}},_createCommitment:function(e,t){var r=this._canonicalizeToken(e),i={type:"LTP_TOKEN",tokenHash:hd.sha256(f.Buffer.from(r)).toString("hex"),tokenId:e.id,timestamp:new Date().toISOString(),purpose:t.purpose||"legal_token"},n=hd.sha256(f.Buffer.from(JSON.stringify(i))).toString("hex");return{hash:n,data:i,canonical:r}},_createBatchCommitment:function(e,t){var r=[],i=[];e.forEach(function(s){var u=this._createCommitment(s,t);r.push(u.hash),i.push(s.id)}.bind(this));var n=this._createMerkleRoot(r),o={type:"LTP_BATCH",merkleRoot:n,tokenCount:e.length,tokenIds:i,timestamp:new Date().toISOString(),purpose:t.purpose||"batch_anchor"},a=hd.sha256(f.Buffer.from(JSON.stringify(o))).toString("hex");return{hash:a,data:o,merkleRoot:n,tokenHashes:r}},_formatOpReturn:function(e,t){var r=t.prefix||"LTP.v1",i=e.hash;return{prefix:r,data:i,full:r+"."+i,bytes:f.Buffer.from(r+"."+i,"utf8"),size:f.Buffer.from(r+"."+i,"utf8").length}},_createTxTemplate:function(e,t){try{var r={version:1,inputs:[],outputs:[{satoshis:0,script:"OP_RETURN "+e.data}],locktime:0};return t.feeOutput&&r.outputs.push(t.feeOutput),{template:r,opReturn:e,estimatedSize:this._estimateSize(r),instructions:{step1:"Add input UTXOs to cover fees",step2:"Add change output if needed",step3:"Sign transaction with appropriate keys",step4:"Broadcast to BSV network"}}}catch(i){throw new Error("Failed to create transaction template: "+i.message)}},_extractOpReturn:function(e){try{if(!e||!e.outputs)return null;for(var t=0;t<e.outputs.length;t++){var r=e.outputs[t];if(r.script&&r.script.startsWith("OP_RETURN")){var i=r.script.replace("OP_RETURN ","");return{raw:i,decoded:f.Buffer.from(i,"hex").toString("utf8")}}}return null}catch{return null}},_verifyCommitment:function(e,t){try{return!t||!t.decoded?!1:t.decoded.includes(e.hash)}catch{return!1}},_canonicalizeToken:function(e){var t=JSON.parse(JSON.stringify(e));return delete t.proof,delete t.tokenHash,delete t.anchorTx,delete t.anchorBlock,JSON.stringify(this._sortObjectKeys(t))},_createMerkleRoot:function(e){if(e.length===0)return null;if(e.length===1)return e[0];for(var t=e.slice();t.length>1;){for(var r=[],i=0;i<t.length;i+=2){var n=t[i],o=t[i+1]||n,a=f.Buffer.concat([f.Buffer.from(n,"hex"),f.Buffer.from(o,"hex")]),s=hd.sha256(a).toString("hex");r.push(s)}t=r}return t[0]},_estimateSize:function(e){var t=10,r=e.outputs.length*34,i=148;return{base:t+r,withOneInput:t+r+i,bytesPerInput:i}},_sortObjectKeys:function(e){if(Array.isArray(e))return e.map(this._sortObjectKeys.bind(this));if(e!==null&&typeof e=="object"){var t={};return Object.keys(e).sort().forEach(function(r){t[r]=this._sortObjectKeys(e[r])}.bind(this)),t}return e}};SH.exports=JQ});var IH=T((nhe,OH)=>{"use strict";g();var QQ=sr(),Wn=Le(),xH=dn(),eee=gt(),tee=ei(),Ri=Ie(),ree={prepareSignatureProof:function(e,t,r){r=r||{},Ri.checkArgument(e&&typeof e=="object","Invalid token"),Ri.checkArgument(t instanceof tee,"Invalid private key");try{var i=this._canonicalizeForSigning(e),n=Wn.sha256(f.Buffer.from(i)),o=new xH;o.hashbuf=n,o.privkey=t,o.pubkey=t.toPublicKey(),o.sign();var a=o.sig,s={type:"EcdsaSecp256k1Signature2019",created:new Date().toISOString(),verificationMethod:"did:smartledger:"+t.toPublicKey().toString()+"#keys-1",proofPurpose:r.purpose||"assertionMethod",jws:this._createJWS(n,a),proofValue:a.toDER().toString("hex")};return{success:!0,proof:s,tokenHash:n.toString("hex"),canonical:i,signingKey:{publicKey:t.toPublicKey().toString(),keyId:"did:smartledger:"+t.toPublicKey().toString()+"#keys-1"},externalOperations:{storeProof:{endpoint:"POST /proofs/signature",data:{tokenHash:n.toString("hex"),proof:s,signingKey:t.toPublicKey().toString()}},verifyProof:{endpoint:"POST /proofs/verify-signature",data:{tokenHash:n.toString("hex"),signature:a.toDER().toString("hex"),publicKey:t.toPublicKey().toString()}}}}}catch(u){return{success:!1,error:u.message}}},prepareSignatureVerification:function(e,t){try{if(Ri.checkArgument(e&&typeof e=="object","Invalid token"),Ri.checkArgument(typeof t=="string","Public key must be string"),!e.proof)return{success:!1,error:"No proof found in token"};var r=this._canonicalizeForSigning(e),i=Wn.sha256(f.Buffer.from(r)),n=eee.fromDER(f.Buffer.from(e.proof.proofValue,"hex")),o={tokenHash:i.toString("hex"),signature:n.toDER().toString("hex"),publicKey:t,proof:e.proof,canonical:r},a=new xH;a.hashbuf=i,a.sig=n,a.pubkey=QQ.fromString(t);var s=a.verify()===!0;return{success:!0,verification:{valid:s,tokenHash:i.toString("hex"),signatureValid:s,publicKey:t,verifiedAt:new Date().toISOString()},verificationData:o,externalOperations:{recordVerification:{endpoint:"POST /proofs/verification-record",data:{tokenHash:i.toString("hex"),result:s,publicKey:t,verifiedAt:new Date().toISOString()}},auditVerification:{endpoint:"POST /audit/proof-verification",data:{tokenId:e.id,proofType:e.proof.type,result:s,verifier:t}}}}}catch(u){return{success:!1,error:u.message}}},prepareSelectiveDisclosure:function(e,t,r){Ri.checkArgument(e&&typeof e=="object","Invalid token"),Ri.checkArgument(Array.isArray(t),"Revealed fields must be array"),Ri.checkArgument(typeof r=="string","Nonce must be string");try{var i=this._createFieldCommitments(e,r),n=this._createMerkleTree(i),o=[],a=[];t.forEach(function(u){var c=this._getNestedValue(e,u),l=this._findFieldCommitment(i,u);if(l){o.push({path:u,value:c,commitment:l.hash,salt:l.salt});var p=this._generateMerkleProof(n,l.index);a.push({path:u,leafIndex:l.index,proof:p})}}.bind(this));var s={type:"LegalTokenSelectiveDisclosure",created:new Date().toISOString(),proofPurpose:"selectiveDisclosure",verificationMethod:e.proof?e.proof.verificationMethod:null,nonce:r,merkleRoot:n.root,disclosures:o,merkleProofs:a,totalFields:i.length};return{success:!0,proof:s,hiddenFieldCount:i.length-o.length,revealedFieldCount:o.length,externalOperations:{storeDisclosure:{endpoint:"POST /proofs/selective-disclosure",data:{tokenId:e.id,proof:s,merkleRoot:n.root}},verifyDisclosure:{endpoint:"POST /proofs/verify-disclosure",data:{proof:s,expectedNonce:r}},auditDisclosure:{endpoint:"POST /audit/selective-disclosure",data:{tokenId:e.id,revealedFields:t,totalFields:i.length,disclosedAt:new Date().toISOString()}}}}}catch(u){return{success:!1,error:u.message}}},prepareSelectiveDisclosureVerification:function(e,t){try{if(Ri.checkArgument(e&&typeof e=="object","Invalid proof"),Ri.checkArgument(typeof t=="string","Expected nonce must be string"),e.nonce!==t)return{success:!1,error:"Nonce mismatch"};var r=[],i=[];e.disclosures.forEach(function(o,a){var s=e.merkleProofs[a],u=this._hashField(o.path,o.value,o.salt);if(u!==o.commitment){i.push("Invalid commitment for field: "+o.path);return}var c=this._verifyMerkleProof(o.commitment,s.leafIndex,s.proof,e.merkleRoot);c?r.push({path:o.path,value:o.value,verified:!0}):i.push("Invalid Merkle proof for field: "+o.path)}.bind(this));var n={valid:i.length===0,errors:i,disclosures:r,merkleRoot:e.merkleRoot,totalFields:e.totalFields,verifiedAt:new Date().toISOString()};return{success:!0,verification:n,externalOperations:{recordVerification:{endpoint:"POST /proofs/disclosure-verification",data:{proofId:e.id||"unknown",result:n.valid,verifiedFields:r.length,totalFields:e.totalFields,verifiedAt:n.verifiedAt}},auditVerification:{endpoint:"POST /audit/disclosure-verification",data:{merkleRoot:e.merkleRoot,disclosuresVerified:r.length,errors:i.length,result:n.valid}}}}}catch(o){return{success:!1,error:o.message}}},prepareLegalValidityProof:function(e,t,r){Ri.checkArgument(e&&typeof e=="object","Invalid token"),Ri.checkArgument(t&&typeof t=="object","Invalid jurisdiction"),Ri.checkArgument(typeof r=="string","Nonce must be string");try{var i=t.requirements||[],n=[],o=!0;i.forEach(function(s){var u=this._checkLegalRequirement(e,s);n.push(u),u.satisfied||(o=!1)}.bind(this));var a={type:"LegalValidityProof",created:new Date().toISOString(),proofPurpose:"legalValidity",jurisdiction:t.code,nonce:r,valid:o,checks:n,complianceHash:this._hashCompliance(e,t,r)};return{success:!0,proof:a,valid:o,complianceReport:{jurisdiction:t.code,totalRequirements:i.length,satisfiedRequirements:n.filter(s=>s.satisfied).length,failedRequirements:n.filter(s=>!s.satisfied).length,overallCompliance:o},externalOperations:{submitCompliance:{endpoint:"POST /compliance/legal-validity",data:{tokenId:e.id,jurisdiction:t.code,proof:a,complianceReport:{jurisdiction:t.code,totalRequirements:i.length,satisfiedRequirements:n.filter(s=>s.satisfied).length,failedRequirements:n.filter(s=>!s.satisfied).length,overallCompliance:o}}},auditCompliance:{endpoint:"POST /audit/compliance-check",data:{tokenId:e.id,jurisdiction:t.code,result:o,checkedAt:new Date().toISOString(),requirements:n}},notifyRegulator:o?null:{endpoint:"POST /notifications/compliance-failure",data:{tokenId:e.id,jurisdiction:t.code,failedRequirements:n.filter(s=>!s.satisfied)}}}}}catch(s){return{success:!1,error:s.message}}},prepareZeroKnowledgeProof:function(e,t,r){Ri.checkArgument(e&&typeof e=="object","Invalid token"),Ri.checkArgument(t&&typeof t=="object","Invalid statement"),Ri.checkArgument(typeof r=="string","Nonce must be string");try{var i=Wn.sha256(f.Buffer.from(this._canonicalizeForSigning(e)+r)).toString("hex"),n={type:"LegalTokenZKProof",created:new Date().toISOString(),proofPurpose:"zeroKnowledge",statement:{claim:t.claim||"UNSPECIFIED",predicate:t.predicate||"SATISFIES",threshold:t.threshold||null},commitment:i,nonce:r,proofData:this._generateZKProofData(e,t,r)};return{success:!0,proof:n,commitment:i,externalOperations:{storeZKProof:{endpoint:"POST /proofs/zero-knowledge",data:{tokenId:e.id,proof:n,statement:t}},verifyZKProof:{endpoint:"POST /proofs/verify-zk",data:{proof:n,expectedNonce:r}},auditZKProof:{endpoint:"POST /audit/zk-proof",data:{tokenId:e.id,statement:t.claim,proofGenerated:new Date().toISOString()}}}}}catch(o){return{success:!1,error:o.message}}},_generateZKProofData:function(e,t,r){var i={challenge:Wn.sha256(f.Buffer.from(t.claim+r)).toString("hex"),response:Wn.sha256(f.Buffer.from(this._canonicalizeForSigning(e)+t.claim)).toString("hex"),witness:Wn.sha256(f.Buffer.from(r+e.id+t.predicate)).toString("hex")};return i},_createJWS:function(e,t){var r={alg:"ES256K",typ:"JWT"},i=f.Buffer.from(JSON.stringify(r)).toString("base64url"),n=e.toString("base64url"),o=t.toDER().toString("base64url");return i+".."+o},_canonicalizeForSigning:function(e){var t=JSON.parse(JSON.stringify(e));delete t.proof,delete t.tokenHash;var r=this._sortObjectKeys(t);return JSON.stringify(r)},_createFieldCommitments:function(e,t){var r=[],i=0;return this._traverseObject(e,"",function(n,o){if(n!=="proof"&&n!=="tokenHash"){var a=Wn.sha256(f.Buffer.from(t+n+i)).toString("hex"),s=this._hashField(n,o,a);r.push({path:n,value:o,salt:a,hash:s,index:i}),i++}}.bind(this)),r},_hashField:function(e,t,r){var i=e+":"+JSON.stringify(t)+":"+r;return Wn.sha256(f.Buffer.from(i)).toString("hex")},_createMerkleTree:function(e){var t=e.map(function(l){return l.hash});if(t.length===0)return{root:null,levels:[]};for(var r=[t],i=t;i.length>1;){for(var n=[],o=0;o<i.length;o+=2){var a=i[o],s=i[o+1]||a,u=f.Buffer.concat([f.Buffer.from(a,"hex"),f.Buffer.from(s,"hex")]),c=Wn.sha256(u).toString("hex");n.push(c)}r.push(n),i=n}return{root:i[0],levels:r}},_generateMerkleProof:function(e,t){for(var r=[],i=t,n=0;n<e.levels.length-1;n++){var o=e.levels[n],a=i%2===0,s=a?i+1:i-1;s<o.length&&r.push({hash:o[s],isLeft:!a}),i=Math.floor(i/2)}return r},_verifyMerkleProof:function(e,t,r,i){for(var n=e,o=t,a=0;a<r.length;a++){var s=r[a],u=o%2===0,c;s.isLeft?c=f.Buffer.concat([f.Buffer.from(s.hash,"hex"),f.Buffer.from(n,"hex")]):c=f.Buffer.concat([f.Buffer.from(n,"hex"),f.Buffer.from(s.hash,"hex")]),n=Wn.sha256(c).toString("hex"),o=Math.floor(o/2)}return n===i},_traverseObject:function(e,t,r){Array.isArray(e)?e.forEach(function(i,n){var o=t+"["+n+"]";this._traverseObject(i,o,r)}.bind(this)):e!==null&&typeof e=="object"?Object.keys(e).forEach(function(i){var n=t?t+"."+i:i;this._traverseObject(e[i],n,r)}.bind(this)):r(t,e)},_getNestedValue:function(e,t){return t.split(".").reduce(function(r,i){return r&&r[i]},e)},_findFieldCommitment:function(e,t){return e.find(function(r){return r.path===t})},_checkLegalRequirement:function(e,t){switch(t.type){case"field_present":var r=this._getNestedValue(e,t.field);return{requirement:t.type,field:t.field,satisfied:r!=null};case"field_value":var r=this._getNestedValue(e,t.field);return{requirement:t.type,field:t.field,satisfied:r===t.expectedValue};case"temporal_validity":var i=new Date,n=new Date(e.issuanceDate);return{requirement:t.type,satisfied:n<=i};default:return{requirement:t.type,satisfied:!1,error:"Unknown requirement type"}}},_hashCompliance:function(e,t,r){var i={tokenId:e.id,jurisdiction:t.code,nonce:r,timestamp:new Date().toISOString()};return Wn.sha256(f.Buffer.from(JSON.stringify(i))).toString("hex")},_sortObjectKeys:function(e){if(Array.isArray(e))return e.map(this._sortObjectKeys.bind(this));if(e!==null&&typeof e=="object"){var t={};return Object.keys(e).sort().forEach(function(r){t[r]=this._sortObjectKeys(e[r])}.bind(this)),t}return e}};OH.exports=ree});var PH=T((uhe,TH)=>{"use strict";g();var dd=Le(),ahe=Ni(),she=zt(),ji=Ie(),AH=fd(),iee={prepareRegistry:function(e){e=e||{},ji.checkArgument(typeof e=="object","Config must be object");var t={id:e.id||this._generateRegistryId(),name:e.name||"Legal Token Registry",jurisdiction:e.jurisdiction||"GLOBAL",authority:e.authority||null,created:new Date().toISOString(),version:"1.0.0",config:{allowPublicRegistration:e.allowPublicRegistration||!1,requireApproval:e.requireApproval||!0,enableRevocation:e.enableRevocation!==!1,enableAuditTrail:e.enableAuditTrail!==!1,retentionPeriod:e.retentionPeriod||"7Y",complianceLevel:e.complianceLevel||"STANDARD"},dataStructure:{tokens:"Map<tokenId, registrationRecord>",revocations:"Map<tokenId, revocationRecord>",auditLog:"Array<auditEntry>",statistics:{totalTokens:0,activeTokens:0,revokedTokens:0,registrations:0}},externalStorage:{required:!0,type:"database_or_blockchain",endpoints:{store:"POST /registry/{id}/tokens",retrieve:"GET /registry/{id}/tokens/{tokenId}",search:"GET /registry/{id}/search",revoke:"POST /registry/{id}/revocations"}}},r=this._prepareAuditEntry({action:"REGISTRY_CREATED",actor:e.authority,timestamp:t.created,metadata:{jurisdiction:t.jurisdiction,config:t.config}});return{success:!0,registry:t,initialAudit:r,instructions:{step1:"Store registry configuration in external system",step2:"Initialize token storage with provided data structure",step3:"Set up audit logging with provided templates",step4:"Configure external endpoints for registry operations"}}},prepareTokenRegistration:function(e,t,r){r=r||{},ji.checkArgument(e&&typeof e=="object","Invalid token"),ji.checkArgument(t&&typeof t=="object","Invalid registry config");try{var i=this._validateTokenForRegistration(e,t);if(!i.valid)return{success:!1,error:"Token validation failed: "+i.error};var n={tokenId:e.id,tokenHash:this._hashToken(e),token:e,status:t.requireApproval?"PENDING":"ACTIVE",registeredBy:r.registeredBy||"UNKNOWN",registeredAt:new Date().toISOString(),approvedBy:null,approvedAt:null,metadata:r.metadata||{},compliance:{jurisdiction:e.jurisdiction||t.jurisdiction,level:this._calculateComplianceLevel(e),checks:i.checks||[]}},o=this._prepareAuditEntry({action:"TOKEN_REGISTERED",actor:r.registeredBy,tokenId:e.id,timestamp:n.registeredAt,metadata:{status:n.status,tokenType:e.type,compliance:n.compliance}});return{success:!0,registrationRecord:n,auditEntry:o,registrationId:this._generateRegistrationId(e.id),validation:i,externalOperations:{store:{endpoint:"POST /registry/"+t.id+"/tokens",data:n},audit:{endpoint:"POST /registry/"+t.id+"/audit",data:o}}}}catch(a){return{success:!1,error:a.message}}},prepareTokenApproval:function(e,t,r){try{ji.checkArgument(typeof e=="string","Token ID must be string"),ji.checkArgument(typeof t=="string","Approver must be string"),ji.checkArgument(r&&typeof r=="object","Invalid registry config");var i={tokenId:e,status:"ACTIVE",approvedBy:t,approvedAt:new Date().toISOString()},n=this._prepareAuditEntry({action:"TOKEN_APPROVED",actor:t,tokenId:e,timestamp:i.approvedAt});return{success:!0,approvalData:i,auditEntry:n,externalOperations:{update:{endpoint:"PUT /registry/"+r.id+"/tokens/"+e+"/status",data:i},audit:{endpoint:"POST /registry/"+r.id+"/audit",data:n}}}}catch(o){return{success:!1,error:o.message}}},prepareTokenRevocation:function(e,t,r){try{if(ji.checkArgument(typeof e=="string","Token ID must be string"),ji.checkArgument(t&&typeof t=="object","Invalid revocation"),ji.checkArgument(r&&typeof r=="object","Invalid registry config"),!r.enableRevocation)return{success:!1,error:"Revocation is disabled for this registry"};var i={tokenId:e,reason:t.reason||"UNSPECIFIED",revokedBy:t.revokedBy||"UNKNOWN",revokedAt:new Date().toISOString(),effectiveDate:t.effectiveDate||new Date().toISOString(),legalBasis:t.legalBasis||null,evidence:t.evidence||null,revocationHash:this._generateRevocationHash(e,t)},n={tokenId:e,status:"REVOKED",revokedAt:i.revokedAt,revocationReason:i.reason},o=this._prepareAuditEntry({action:"TOKEN_REVOKED",actor:t.revokedBy,tokenId:e,timestamp:i.revokedAt,metadata:{reason:i.reason,legalBasis:i.legalBasis}});return{success:!0,revocationRecord:i,statusUpdate:n,auditEntry:o,revocationId:this._generateRevocationId(e),externalOperations:{storeRevocation:{endpoint:"POST /registry/"+r.id+"/revocations",data:i},updateStatus:{endpoint:"PUT /registry/"+r.id+"/tokens/"+e+"/status",data:n},audit:{endpoint:"POST /registry/"+r.id+"/audit",data:o}}}}catch(a){return{success:!1,error:a.message}}},prepareTokenStatusQuery:function(e,t){try{return ji.checkArgument(typeof e=="string","Token ID must be string"),ji.checkArgument(t&&typeof t=="object","Invalid registry config"),{success:!0,query:{tokenId:e,registryId:t.id},externalOperations:{retrieve:{endpoint:"GET /registry/"+t.id+"/tokens/"+e,method:"GET"},checkRevocation:{endpoint:"GET /registry/"+t.id+"/revocations/"+e,method:"GET"}},expectedResponse:{found:"boolean",status:"string (PENDING|ACTIVE|REVOKED)",registeredAt:"ISO datetime",registeredBy:"string",approvedAt:"ISO datetime or null",approvedBy:"string or null",revokedAt:"ISO datetime or null",revocationReason:"string or null",compliance:"object",revocation:"object or null"}}}catch(r){return{success:!1,error:r.message}}},prepareTokenSearch:function(e,t){e=e||{};try{ji.checkArgument(t&&typeof t=="object","Invalid registry config");var r=[];e.status&&r.push("status="+encodeURIComponent(e.status)),e.type&&r.push("type="+encodeURIComponent(e.type)),e.registeredBy&&r.push("registeredBy="+encodeURIComponent(e.registeredBy)),e.jurisdiction&&r.push("jurisdiction="+encodeURIComponent(e.jurisdiction)),e.dateFrom&&r.push("dateFrom="+encodeURIComponent(e.dateFrom)),e.dateTo&&r.push("dateTo="+encodeURIComponent(e.dateTo)),e.includeTokens&&r.push("includeTokens=true"),e.sortBy&&r.push("sortBy="+encodeURIComponent(e.sortBy)),e.sortOrder&&r.push("sortOrder="+encodeURIComponent(e.sortOrder));var i=e.offset||0,n=e.limit||100;r.push("offset="+i),r.push("limit="+n);var o=r.length>0?"?"+r.join("&"):"";return{success:!0,searchCriteria:e,externalOperations:{search:{endpoint:"GET /registry/"+t.id+"/search"+o,method:"GET"}},expectedResponse:{success:"boolean",results:"Array<tokenRecord>",totalCount:"number",totalRegistrations:"number",offset:"number",limit:"number",hasMore:"boolean"}}}catch(a){return{success:!1,error:a.message}}},prepareStatisticsQuery:function(e){return ji.checkArgument(e&&typeof e=="object","Invalid registry config"),{success:!0,query:{registryId:e.id},externalOperations:{getStatistics:{endpoint:"GET /registry/"+e.id+"/statistics",method:"GET"}},expectedResponse:{id:"string",name:"string",jurisdiction:"string",created:"ISO datetime",statistics:{totalTokens:"number",activeTokens:"number",revokedTokens:"number",registrations:"number"},auditEntries:"number",lastActivity:"ISO datetime"}}},prepareAuditLogQuery:function(e,t){if(t=t||{},ji.checkArgument(e&&typeof e=="object","Invalid registry config"),!e.enableAuditTrail)return{success:!1,error:"Audit trail is disabled"};var r=[];t.action&&r.push("action="+encodeURIComponent(t.action)),t.actor&&r.push("actor="+encodeURIComponent(t.actor)),t.tokenId&&r.push("tokenId="+encodeURIComponent(t.tokenId)),t.dateFrom&&r.push("dateFrom="+encodeURIComponent(t.dateFrom)),t.dateTo&&r.push("dateTo="+encodeURIComponent(t.dateTo));var i=t.offset||0,n=t.limit||100;r.push("offset="+i),r.push("limit="+n);var o=r.length>0?"?"+r.join("&"):"";return{success:!0,auditOptions:t,externalOperations:{getAuditLog:{endpoint:"GET /registry/"+e.id+"/audit"+o,method:"GET"}},expectedResponse:{success:"boolean",entries:"Array<auditEntry>",totalEntries:"number",offset:"number",limit:"number",hasMore:"boolean"}}},_generateRegistryId:function(){return"reg_"+AH.randomHex(16)},_generateRegistrationId:function(e){var t="reg_"+e+"_"+Date.now();return dd.sha256(f.Buffer.from(t)).toString("hex").substring(0,16)},_generateRevocationId:function(e){var t="rev_"+e+"_"+Date.now();return dd.sha256(f.Buffer.from(t)).toString("hex").substring(0,16)},_hashToken:function(e){var t=JSON.parse(JSON.stringify(e));return delete t.proof,delete t.tokenHash,dd.sha256(f.Buffer.from(JSON.stringify(t))).toString("hex")},_generateRevocationHash:function(e,t){var r=e+(t.reason||"")+(t.revokedBy||"")+Date.now();return dd.sha256(f.Buffer.from(r)).toString("hex")},_validateTokenForRegistration:function(e,t){var r=[],i=!0;return e.id?r.push({field:"id",valid:!0}):(r.push({field:"id",valid:!1,error:"Missing token ID"}),i=!1),e.type?r.push({field:"type",valid:!0}):(r.push({field:"type",valid:!1,error:"Missing token type"}),i=!1),e.issuanceDate?r.push({field:"issuanceDate",valid:!0}):(r.push({field:"issuanceDate",valid:!1,error:"Missing issuance date"}),i=!1),e.proof?r.push({field:"proof",valid:!0}):(r.push({field:"proof",valid:!1,error:"Missing cryptographic proof"}),i=!1),{valid:i,checks:r}},_calculateComplianceLevel:function(e){var t="BASIC";return e.proof&&e.proof.type&&(t="STANDARD"),e.jurisdiction&&e.legalBasis&&(t="ENHANCED"),e.attestations&&e.attestations.length>0&&(t="PREMIUM"),t},_prepareAuditEntry:function(e){var t={id:this._generateAuditId(),action:e.action,actor:e.actor||"SYSTEM",tokenId:e.tokenId||null,timestamp:e.timestamp||new Date().toISOString(),metadata:e.metadata||{},hash:this._generateAuditHash(e)};return t},_generateAuditId:function(){return"audit_"+AH.randomHex(32)},_generateAuditHash:function(e){var t=(e.action||"")+(e.actor||"")+(e.tokenId||"")+(e.timestamp||"");return dd.sha256(f.Buffer.from(t)).toString("hex").substring(0,16)}};TH.exports=iee});var NH=T((fhe,BH)=>{"use strict";g();var vE=sr(),yE=Le(),RH=dn(),nee=gt(),kH=ei(),Ji=Ie(),oee=fd();function aee(e,t){if(t=t||{},t.issuerPublicKey)return t.issuerPublicKey instanceof vE?t.issuerPublicKey:vE.fromString(t.issuerPublicKey);var r=e&&e.issuer;if(typeof r!="string")return null;try{var i=r.split("#")[0].split(":")[2];return i?vE.fromString(i):null}catch{return null}}var Lv={CORRELATIVE_OBLIGATION:"CorrelativeObligation",CONTRACTUAL_OBLIGATION:"ContractualObligation",PAYMENT_OBLIGATION:"PaymentObligation",DELIVERY_OBLIGATION:"DeliveryObligation",PERFORMANCE_OBLIGATION:"PerformanceObligation",MAINTENANCE_OBLIGATION:"MaintenanceObligation",COMPLIANCE_OBLIGATION:"ComplianceObligation",REPORTING_OBLIGATION:"ReportingObligation",CONFIDENTIALITY_OBLIGATION:"ConfidentialityObligation",NON_COMPETE_OBLIGATION:"NonCompeteObligation",INDEMNIFICATION_OBLIGATION:"IndemnificationObligation",WARRANTY_OBLIGATION:"WarrantyObligation",SUPPORT_OBLIGATION:"SupportObligation",REGULATORY_OBLIGATION:"RegulatoryObligation",FIDUCIARY_OBLIGATION:"FiduciaryObligation"},Mf={CRITICAL:"CRITICAL",HIGH:"HIGH",MEDIUM:"MEDIUM",LOW:"LOW",DEFERRED:"DEFERRED"},zi={PENDING:"PENDING",ACTIVE:"ACTIVE",IN_PROGRESS:"IN_PROGRESS",COMPLETED:"COMPLETED",OVERDUE:"OVERDUE",BREACHED:"BREACHED",WAIVED:"WAIVED",TERMINATED:"TERMINATED"},Mv={prepareObligationToken:function(e,t,r,i,n,o){o=o||{},Ji.checkArgument(typeof e=="string","Obligation type must be string"),Ji.checkArgument(typeof t=="string","Issuer DID must be string"),Ji.checkArgument(typeof r=="string","Obligor DID must be string"),Ji.checkArgument(i&&typeof i=="object","Obligation must be object"),Ji.checkArgument(n instanceof kH,"Invalid issuer private key");var a=Object.values(Lv);Ji.checkArgument(a.includes(e),"Invalid obligation type: "+e);try{var s={"@context":["https://www.w3.org/2018/credentials/v1","https://smartledger.technology/contexts/ltp/v1"],id:"urn:uuid:"+this._generateUUID(),type:["VerifiableCredential","LegalObligationToken",e],issuer:t,issuanceDate:new Date().toISOString(),credentialSubject:{id:r,obligationType:e,obligation:i,jurisdiction:o.jurisdiction||"US",priority:o.priority||Mf.MEDIUM,status:zi.PENDING,dueDate:o.dueDate||null,effectiveDate:o.effectiveDate||new Date().toISOString(),expirationDate:o.expirationDate||null,correlativeRight:o.correlativeRight||null,rightHolder:o.rightHolder||null,enforceable:o.enforceable!==!1,penalties:o.penalties||null,remedies:o.remedies||null}};o.metadata&&(s.credentialSubject.metadata=o.metadata);var u=this._signToken(s,n);return{success:!0,obligationToken:u,tokenHash:u.tokenHash,metadata:{type:e,issuer:t,obligor:r,priority:s.credentialSubject.priority,status:s.credentialSubject.status,jurisdiction:s.credentialSubject.jurisdiction,dueDate:s.credentialSubject.dueDate,correlativeRight:s.credentialSubject.correlativeRight},externalOperations:{storeToken:{endpoint:"POST /obligations/tokens",data:{token:u,metadata:{type:e,issuer:t,obligor:r,priority:s.credentialSubject.priority,status:s.credentialSubject.status,jurisdiction:s.credentialSubject.jurisdiction,dueDate:s.credentialSubject.dueDate,correlativeRight:s.credentialSubject.correlativeRight}}},indexToken:{endpoint:"POST /obligations/index",data:{tokenId:u.id,tokenHash:u.tokenHash,type:e,issuer:t,obligor:r,issuedAt:u.issuanceDate,dueDate:s.credentialSubject.dueDate,priority:s.credentialSubject.priority}},notifyObligor:{endpoint:"POST /notifications/obligation-issued",data:{tokenId:u.id,issuer:t,obligor:r,obligationType:e,dueDate:s.credentialSubject.dueDate,priority:s.credentialSubject.priority}},scheduleReminders:s.credentialSubject.dueDate?{endpoint:"POST /obligations/schedule-reminders",data:{tokenId:u.id,obligor:r,dueDate:s.credentialSubject.dueDate,reminderSchedule:o.reminderSchedule||["7d","3d","1d"]}}:null}}}catch(c){return{success:!1,error:c.message}}},prepareObligationVerification:function(e,t){t=t||{};try{var r=[],i=[];this._validateTokenStructure(e,r),this._verifyTokenSignature(e,r,t),this._validateTokenTemporal(e,r,i),this._validateObligationType(e,r),this._validateObligationStatus(e,r,i),this._validateObligationPriority(e,i);var n={valid:r.length===0,errors:r,warnings:i,issuerDID:e.issuer,obligorDID:e.credentialSubject?e.credentialSubject.id:null,obligationType:e.credentialSubject?e.credentialSubject.obligationType:null,status:e.credentialSubject?e.credentialSubject.status:null,priority:e.credentialSubject?e.credentialSubject.priority:null,isOverdue:this._checkIfOverdue(e),verifiedAt:new Date().toISOString()};return{success:!0,verification:n,externalOperations:{recordVerification:{endpoint:"POST /obligations/verification-record",data:{tokenId:e.id,result:n.valid,errors:r,warnings:i,verifiedAt:n.verifiedAt,isOverdue:n.isOverdue}},auditVerification:{endpoint:"POST /audit/obligation-verification",data:{tokenId:e.id,obligationType:n.obligationType,issuer:n.issuerDID,obligor:n.obligorDID,result:n.valid,verifiedAt:n.verifiedAt}},updateStatus:n.isOverdue&&e.credentialSubject.status===zi.ACTIVE?{endpoint:"PUT /obligations/tokens/"+e.id+"/status",data:{status:zi.OVERDUE,updatedAt:n.verifiedAt,reason:"Due date passed"}}:null}}}catch(o){return{success:!1,error:"Verification preparation failed: "+o.message}}},prepareObligationFulfillment:function(e,t,r,i){i=i||{},Ji.checkArgument(e&&typeof e=="object","Invalid token"),Ji.checkArgument(t&&typeof t=="object","Invalid fulfillment"),Ji.checkArgument(r instanceof kH,"Invalid obligor key");try{var n=this.prepareObligationVerification(e,{});if(!n.success||!n.verification.valid)return{success:!1,error:"Cannot fulfill invalid obligation: "+n.verification.errors.join(", ")};if(e.credentialSubject.status===zi.COMPLETED)return{success:!1,error:"Obligation already fulfilled"};if(e.credentialSubject.status===zi.TERMINATED)return{success:!1,error:"Obligation has been terminated"};var o={"@context":["https://www.w3.org/2018/credentials/v1","https://smartledger.technology/contexts/ltp/v1"],id:"urn:uuid:"+this._generateUUID(),type:["VerifiableCredential","ObligationFulfillment"],issuer:e.credentialSubject.id,issuanceDate:new Date().toISOString(),credentialSubject:{id:e.id,fulfillmentType:t.type||"FULL_FULFILLMENT",fulfillmentDate:new Date().toISOString(),evidence:t.evidence||null,description:t.description||"",completionPercentage:t.completionPercentage||100,attestations:t.attestations||[],notes:t.notes||null}},a=this._signToken(o,r),s=o.credentialSubject.completionPercentage>=100?zi.COMPLETED:zi.IN_PROGRESS;return{success:!0,fulfillmentRecord:a,newStatus:s,fulfillmentId:a.id,externalOperations:{recordFulfillment:{endpoint:"POST /obligations/fulfillments",data:{obligationId:e.id,fulfillmentRecord:a,obligor:e.credentialSubject.id,fulfillmentDate:o.credentialSubject.fulfillmentDate,completionPercentage:o.credentialSubject.completionPercentage}},updateStatus:{endpoint:"PUT /obligations/tokens/"+e.id+"/status",data:{status:s,fulfillmentId:a.id,updatedAt:o.credentialSubject.fulfillmentDate,completionPercentage:o.credentialSubject.completionPercentage}},notifyRightHolder:e.credentialSubject.rightHolder?{endpoint:"POST /notifications/obligation-fulfilled",data:{obligationId:e.id,fulfillmentId:a.id,obligor:e.credentialSubject.id,rightHolder:e.credentialSubject.rightHolder,completionPercentage:o.credentialSubject.completionPercentage,newStatus:s}}:null,auditFulfillment:{endpoint:"POST /audit/obligation-fulfillment",data:{obligationId:e.id,fulfillmentId:a.id,obligor:e.credentialSubject.id,fulfilledAt:o.credentialSubject.fulfillmentDate,completionPercentage:o.credentialSubject.completionPercentage}}}}}catch(u){return{success:!1,error:u.message}}},prepareObligationBreachAssessment:function(e,t,r){Ji.checkArgument(e&&typeof e=="object","Invalid token"),Ji.checkArgument(t&&typeof t=="object","Invalid breach details"),Ji.checkArgument(r&&typeof r=="object","Invalid assessor");try{var i={"@context":["https://www.w3.org/2018/credentials/v1","https://smartledger.technology/contexts/ltp/v1"],id:"urn:uuid:"+this._generateUUID(),type:["VerifiableCredential","ObligationBreachAssessment"],issuer:r.did||r.id,issuanceDate:new Date().toISOString(),credentialSubject:{id:e.id,breachType:t.type||"MATERIAL_BREACH",breachDate:t.date||new Date().toISOString(),description:t.description||"",severity:t.severity||"MODERATE",evidence:t.evidence||[],assessor:{did:r.did||r.id,name:r.name||"Unknown",authority:r.authority||null,jurisdiction:r.jurisdiction||null},damages:t.damages||null,recommendedRemedies:t.recommendedRemedies||[],assessmentDate:new Date().toISOString()}},n=yE.sha256(f.Buffer.from(JSON.stringify(i))).toString("hex");return i.credentialSubject.assessmentHash=n,{success:!0,breachAssessment:i,breachId:i.id,severity:t.severity||"MODERATE",externalOperations:{recordBreach:{endpoint:"POST /obligations/breaches",data:{obligationId:e.id,breachAssessment:i,obligor:e.credentialSubject.id,rightHolder:e.credentialSubject.rightHolder,breachDate:t.date||new Date().toISOString(),severity:t.severity||"MODERATE"}},updateStatus:{endpoint:"PUT /obligations/tokens/"+e.id+"/status",data:{status:zi.BREACHED,breachId:i.id,breachDate:t.date||new Date().toISOString(),updatedAt:new Date().toISOString()}},notifyParties:{endpoint:"POST /notifications/obligation-breached",data:{obligationId:e.id,breachId:i.id,obligor:e.credentialSubject.id,rightHolder:e.credentialSubject.rightHolder,breachType:t.type||"MATERIAL_BREACH",severity:t.severity||"MODERATE"}},escalateBreach:t.severity==="CRITICAL"?{endpoint:"POST /legal/escalate-breach",data:{obligationId:e.id,breachId:i.id,severity:t.severity,jurisdiction:e.credentialSubject.jurisdiction}}:null,auditBreach:{endpoint:"POST /audit/obligation-breach",data:{obligationId:e.id,breachId:i.id,obligor:e.credentialSubject.id,assessedAt:i.credentialSubject.assessmentDate,severity:t.severity||"MODERATE"}}}}}catch(o){return{success:!1,error:o.message}}},prepareObligationMonitoringReport:function(e,t){t=t||{},Ji.checkArgument(Array.isArray(e),"Obligations must be array");try{var r={reportId:"rpt_"+this._generateUUID(),generatedAt:new Date().toISOString(),criteria:t,summary:{totalObligations:e.length,byStatus:{},byPriority:{},byType:{},overdue:0,dueSoon:0,completed:0},obligations:[],alerts:[],recommendations:[]},i=new Date,n=new Date(i.getTime()+10080*60*1e3);return e.forEach(function(o){var a={id:o.id,type:o.credentialSubject.obligationType,status:o.credentialSubject.status,priority:o.credentialSubject.priority,obligor:o.credentialSubject.id,dueDate:o.credentialSubject.dueDate,isOverdue:this._checkIfOverdue(o),isDueSoon:!1};if(o.credentialSubject.dueDate){var s=new Date(o.credentialSubject.dueDate);a.isDueSoon=s<=n&&s>i}r.summary.byStatus[a.status]=(r.summary.byStatus[a.status]||0)+1,r.summary.byPriority[a.priority]=(r.summary.byPriority[a.priority]||0)+1,r.summary.byType[a.type]=(r.summary.byType[a.type]||0)+1,a.isOverdue&&r.summary.overdue++,a.isDueSoon&&r.summary.dueSoon++,a.status===zi.COMPLETED&&r.summary.completed++,a.isOverdue&&a.priority===Mf.CRITICAL&&r.alerts.push({type:"CRITICAL_OVERDUE",obligationId:o.id,message:"Critical obligation is overdue",priority:"HIGH"}),a.isDueSoon&&a.priority===Mf.HIGH&&r.alerts.push({type:"HIGH_PRIORITY_DUE_SOON",obligationId:o.id,message:"High priority obligation due soon",priority:"MEDIUM"}),r.obligations.push(a)}.bind(this)),r.summary.overdue>0&&r.recommendations.push({type:"OVERDUE_MANAGEMENT",message:"Consider prioritizing overdue obligations",count:r.summary.overdue}),r.summary.dueSoon>5&&r.recommendations.push({type:"WORKLOAD_MANAGEMENT",message:"High number of obligations due soon - consider workload distribution",count:r.summary.dueSoon}),{success:!0,report:r,externalOperations:{storeReport:{endpoint:"POST /obligations/monitoring-reports",data:{report:r,generatedAt:r.generatedAt}},sendAlerts:r.alerts.length>0?{endpoint:"POST /notifications/obligation-alerts",data:{reportId:r.reportId,alerts:r.alerts,summary:r.summary}}:null,updateDashboard:{endpoint:"PUT /dashboard/obligation-metrics",data:{summary:r.summary,lastUpdated:r.generatedAt}}}}}catch(o){return{success:!1,error:o.message}}},getObligationTypes:function(){return Lv},getObligationPriority:function(){return Mf},getObligationStatus:function(){return zi},_signToken:function(e,t){var r=this._canonicalizeToken(e),i=yE.sha256(f.Buffer.from(r)),n=new RH;n.hashbuf=i,n.privkey=t,n.pubkey=t.toPublicKey(),n.sign();var o=n.sig,a={type:"EcdsaSecp256k1Signature2019",created:new Date().toISOString(),verificationMethod:"did:smartledger:"+t.toPublicKey().toString()+"#keys-1",proofPurpose:"assertionMethod",jws:this._createJWS(i,o)},s=JSON.parse(JSON.stringify(e));return s.proof=a,s.tokenHash=i.toString("hex"),s},_createJWS:function(e,t){var r={alg:"ES256K",typ:"JWT"},i=f.Buffer.from(JSON.stringify(r)).toString("base64url"),n=e.toString("base64url"),o=t.toDER().toString("base64url");return i+".."+o},_canonicalizeToken:function(e){var t=JSON.parse(JSON.stringify(e));return delete t.proof,delete t.tokenHash,JSON.stringify(this._sortObjectKeys(t))},_sortObjectKeys:function(e){if(Array.isArray(e))return e.map(this._sortObjectKeys.bind(this));if(e!==null&&typeof e=="object"){var t={};return Object.keys(e).sort().forEach(function(r){t[r]=this._sortObjectKeys(e[r])}.bind(this)),t}return e},_validateTokenStructure:function(e,t){e["@context"]||t.push("Missing @context"),e.id||t.push("Missing id"),(!e.type||!Array.isArray(e.type))&&t.push("Missing or invalid type"),e.issuer||t.push("Missing issuer"),e.issuanceDate||t.push("Missing issuanceDate"),e.credentialSubject||t.push("Missing credentialSubject"),e.proof||t.push("Missing proof")},_verifyTokenSignature:function(e,t,r){try{if(!e.proof||!e.proof.jws){t.push("Missing signature proof");return}var i=this._canonicalizeToken(e),n=yE.sha256(f.Buffer.from(i));if(e.tokenHash&&e.tokenHash!==n.toString("hex")){t.push("Token hash mismatch");return}var o=aee(e,r);if(!o){t.push("Signature not verified: issuer public key could not be resolved from token.issuer; pass options.issuerPublicKey");return}var a=e.proof.jws.split(".");if(a.length!==3||!a[2]){t.push("Malformed JWS");return}var s=nee.fromDER(f.Buffer.from(a[2],"base64url")),u=new RH;u.hashbuf=n,u.sig=s,u.pubkey=o,u.verify()!==!0&&t.push("Signature verification failed")}catch(c){t.push("Signature verification failed: "+c.message)}},_validateTokenTemporal:function(e,t,r){var i=new Date,n=new Date(e.issuanceDate);if(n>i&&t.push("Token issued in the future"),e.credentialSubject.effectiveDate){var o=new Date(e.credentialSubject.effectiveDate);i<o&&r.push("Obligation not yet effective")}if(e.credentialSubject.expirationDate){var a=new Date(e.credentialSubject.expirationDate);i>a&&t.push("Obligation expired")}},_validateObligationType:function(e,t){if(!e.credentialSubject.obligationType){t.push("Missing obligationType");return}var r=Object.values(Lv);r.includes(e.credentialSubject.obligationType)||t.push("Invalid obligation type: "+e.credentialSubject.obligationType)},_validateObligationStatus:function(e,t,r){if(!e.credentialSubject.status){t.push("Missing status");return}var i=Object.values(zi);i.includes(e.credentialSubject.status)||t.push("Invalid obligation status: "+e.credentialSubject.status),this._checkIfOverdue(e)&&e.credentialSubject.status===zi.ACTIVE&&r.push("Obligation is overdue but status is still ACTIVE")},_validateObligationPriority:function(e,t){if(e.credentialSubject.priority){var r=Object.values(Mf);r.includes(e.credentialSubject.priority)||t.push("Invalid obligation priority: "+e.credentialSubject.priority)}},_checkIfOverdue:function(e){if(!e.credentialSubject.dueDate)return!1;var t=new Date,r=new Date(e.credentialSubject.dueDate);return t>r&&e.credentialSubject.status!==zi.COMPLETED},_generateUUID:function(){return oee.uuid4()}};Mv.ObligationTypes=Lv;Mv.ObligationPriority=Mf;Mv.ObligationStatus=zi;BH.exports=Mv});var LH=T((hhe,CH)=>{"use strict";g();var Du=bH(),Dv=wH(),pd=EH(),bE=IH(),Uo=PH(),see=NH(),_E=ei(),Qi=Ie(),lt=function(e){return this instanceof lt?(this.config=e||{},this.registry=null,this.config.registry&&(this.registry=Uo.createRegistry(this.config.registry)),this):new lt(e)};lt.prototype.createRightToken=function(e,t,r){Qi.checkArgument(e&&typeof e=="object","Invalid right data"),Qi.checkArgument(t instanceof _E,"Invalid private key"),r=r||{};try{var i=Du.create(e.type,e.owner,e.owner,e,t,r);if(!i)return{success:!1,error:"Failed to create token"};if(r.addProof!==!1&&(i=Du._signToken(i,t)),r.anchor){var n=pd.anchorToken(i,r.anchor);n.success&&(i.anchorTx=n.txid,i.anchorBlock=n.blockHeight)}if(this.registry&&r.register!==!1){var o=Uo.registerToken(this.registry,i,{registeredBy:r.registeredBy||"SYSTEM"});o.success&&(i.registrationId=o.registrationId,i.registrationStatus=o.status)}return{success:!0,token:i,type:"LegalRightToken"}}catch(a){return{success:!1,error:a.message}}};lt.prototype.validateClaim=function(e,t){return Dv.validate(e,t)};lt.prototype.createSelectiveDisclosure=function(e,t,r){return bE.prepareSelectiveDisclosure(e,t,r)};lt.prototype.verifyToken=function(e,t){return!e||!e.proof?{valid:!1,error:"No proof found in token"}:Du.verifyToken(e,t)};lt.prototype.transferRight=function(e,t,r,i){Qi.checkArgument(e&&typeof e=="object","Invalid token"),Qi.checkArgument(typeof t=="string","New owner must be string"),Qi.checkArgument(r instanceof _E,"Invalid owner key"),i=i||{};try{var n=this.verifyToken(e,r.toPublicKey().toString());if(!n.valid)return{success:!1,error:"Invalid token or ownership proof"};var o=Du.prepareRightTokenTransfer(e,t,r,i);if(!o.success)return{success:!1,error:o.error};var a=o.newToken,s=o.transferProof;if(i.anchor){var u=pd.anchorToken(a,i.anchor);u.success&&(a.transferAnchorTx=u.txid)}if(this.registry){var c=Uo.registerToken(this.registry,a,{registeredBy:i.registeredBy||t,metadata:{transferFrom:e.owner,transferTo:t,originalTokenId:e.id}});c.success&&(a.registrationId=c.registrationId)}return{success:!0,token:a,transferId:s.id,transferredAt:s.issuanceDate,transferProof:s}}catch(l){return{success:!1,error:l.message}}};lt.prototype.createObligation=function(e,t,r){Qi.checkArgument(e&&typeof e=="object","Invalid right token"),Qi.checkArgument(t&&typeof t=="object","Invalid obligation data"),Qi.checkArgument(r instanceof _E,"Invalid private key");try{var i=Du.prepareObligationToken(e,t.obligor,t,r);return i.success?{success:!0,obligation:i.obligationToken,rightTokenId:e.id}:{success:!1,error:i.error}}catch(n){return{success:!1,error:n.message}}};lt.prototype.revokeToken=function(e,t,r){return Qi.checkArgument(typeof e=="string","Token ID must be string"),Qi.checkArgument(t&&typeof t=="object","Invalid revocation data"),Qi.checkArgument(typeof r=="string","Authority must be string"),this.registry?Uo.revokeToken(this.registry,e,{reason:t.reason,revokedBy:r,legalBasis:t.legalBasis,evidence:t.evidence}):{success:!1,error:"No registry available for revocation"}};lt.prototype.checkTokenStatus=function(e){return Qi.checkArgument(typeof e=="string","Token ID must be string"),this.registry?Uo.checkTokenStatus(this.registry,e):{found:!1,error:"No registry available"}};lt.prototype.searchTokens=function(e){return this.registry?Uo.searchTokens(this.registry,e):{success:!1,error:"No registry available"}};lt.prototype.getRegistryStats=function(){return this.registry?Uo.getStatistics(this.registry):{error:"No registry available"}};lt.prototype.createLegalValidityProof=function(e,t,r){return bE.prepareLegalValidityProof(e,t,r)};lt.prototype.anchorTokenBatch=function(e,t){return pd.anchorBatch(e,t)};lt.prototype.verifyAnchor=function(e,t){return pd.verifyAnchor(e,t)};lt.prototype.getRightTypes=function(){return Du.getRightTypes()};lt.prototype.getClaimSchemas=function(){return Dv.getSchemas()};lt.prototype.createRegistry=function(e){return this.registry=Uo.createRegistry(e),this.registry};lt.prototype.setRegistry=function(e){Qi.checkArgument(e&&typeof e=="object","Invalid registry"),this.registry=e};lt.create=function(e){return new lt(e)};lt.createRightToken=function(e,t,r){var i=new lt;return i.createRightToken(e,t,r)};lt.validateClaim=function(e,t){return Dv.validate(e,t)};lt.verifyToken=function(e,t){var r=new lt;return r.verifyToken(e,t)};lt.createRegistry=function(e){return Uo.createRegistry(e)};lt.Right=Du;lt.Claim=Dv;lt.Anchor=pd;lt.Proof=bE;lt.Registry=Uo;lt.Obligation=see;CH.exports=lt});var Om=T((phe,DH)=>{"use strict";g();var H=DH.exports;H.deps=H.deps||{};H.deps._=at();H.deps.Buffer=typeof f.Buffer<"u"?f.Buffer:null;var MH=pc();H.deps.bs58={encode:MH.encode,decode:MH.decode};if(typeof window>"u")H.deps.bnjs=qp();else try{H.deps.bnjs=qp()}catch{}H.version="v"+eb();H.versionGuard=function(e){if(e!==void 0){var t=`
|
|
99
99
|
More than one instance of bsv found.
|
|
100
100
|
Please make sure to require bsv and check that submodules do
|
|
101
101
|
not also include their own bsv dependency.`;console.warn(t)}};H.versionGuard(globalThis._bsv);globalThis._bsv=H.version;H.isHardened=!0;H.hardenedBy="SmartLedger";H.baseVersion="v1.5.6";H.securityFeatures=["canonical-signatures","malleability-protection","enhanced-validation","audited-noble-curves","fail-closed-verification"];H.crypto={};H.crypto.BN=Ke();H.crypto.ECDSA=dn();H.crypto.Hash=Le();H.crypto.Random=Ki();H.crypto.Point=un();H.crypto.Signature=gt();H.crypto.Shamir=M_();H.crypto.SmartVerify=um();H.crypto.EllipticFixed=cm();H.encoding={};H.encoding.Base58=pc();H.encoding.Base58Check=Pc();H.encoding.BufferReader=lo();H.encoding.BufferWriter=Nn();H.encoding.Varint=Cc();H.util={};H.util.js=ni();H.util.preconditions=Ie();H.util.deprecate=ts();H.errors=pi();H.Address=Ni();H.Block=wN();H.MerkleBlock=V_();H.BlockHeader=zc();H.SPV=mm();H.NotaryHash=aC();H.HDPrivateKey=vh();H.HDPublicKey=hw();H.Networks=ca();H.Opcode=Pr();H.PrivateKey=ei();H.PublicKey=sr();H.Script=ut();H.Transaction=zt();H.Input=zt().Input;H.Output=zt().Output;H.UnspentOutput=zt().UnspentOutput;H.Message=xC();H.Mnemonic=mw();H.ECIES=RL();H.Signature=gt();H.Shamir=M_();H.SmartLedger={version:H.version,hardenedBy:H.hardenedBy,baseVersion:H.baseVersion,securityFeatures:H.securityFeatures,SmartVerify:um(),EllipticFixed:cm()};H.SmartVerify=um();H.EllipticFixed=cm();try{H.SmartContract=sD()}catch(e){typeof window>"u"&&console.warn("SmartContract module not available:",e.message)}try{H.BrowserUTXOManager=uD()}catch(e){typeof window>"u"&&console.warn("[bsv] BrowserUTXOManager failed to load:",e.message)}if(typeof window>"u"&&typeof Wr=="function")try{H.SmartMiner=fD(),H.CustomScriptHelper=pD()}catch{}H.Ordinals=$D();H.GDAF=y6();try{H.DIDWeb=_6()}catch(e){typeof window>"u"&&console.warn("[bsv] DIDWeb module failed to load:",e.message)}try{H.VcJwt=DS()}catch(e){typeof window>"u"&&console.warn("[bsv] VcJwt module failed to load:",e.message)}try{H.StatusList=cH()}catch(e){typeof window>"u"&&console.warn("[bsv] StatusList module failed to load:",e.message)}try{H.Anchor=hH()}catch(e){typeof window>"u"&&console.warn("[bsv] Anchor module failed to load:",e.message)}H.createDID=function(e){var t=new H.GDAF;return t.createDID(e)};H.resolveDID=function(e){var t=new H.GDAF;return t.resolveDID(e)};H.createEmailCredential=function(e,t,r,i){var n=new H.GDAF;return n.createEmailCredential(e,t,r,i)};H.createAgeCredential=function(e,t,r,i,n){var o=new H.GDAF;return o.createAgeCredential(e,t,r,i,n)};H.createKYCCredential=function(e,t,r,i,n){var o=new H.GDAF;return o.createKYCCredential(e,t,r,i,n)};H.verifyCredential=function(e,t){var r=new H.GDAF;return r.verifyCredential(e,t)};H.validateCredential=function(e,t){var r=new H.GDAF;return r.validateCredential(e,t)};H.generateSelectiveProof=function(e,t,r){var i=new H.GDAF;return i.generateSelectiveProof(e,t,r)};H.generateAgeProof=function(e,t,r){var i=new H.GDAF;return i.generateAgeProof(e,t,r)};H.verifyAgeProof=function(e,t,r){var i=new H.GDAF;return i.verifyAgeProof(e,t,r)};H.createPresentation=function(e,t,r,i){var n=new H.GDAF;return n.createPresentation(e,t,r,i)};H.getCredentialSchemas=function(){var e=new H.GDAF;return e.getAllSchemas()};H.createCredentialTemplate=function(e){var t=new H.GDAF;return t.createTemplate(e)};H.LTP=LH();H.JCS=Vc();H.prepareRightToken=function(e,t,r,i,n,o){return H.LTP.Right.prepareRightToken(e,t,r,i,n,o)};H.prepareRightTokenVerification=function(e,t){return H.LTP.Right.prepareRightTokenVerification(e,t)};H.prepareRightTokenTransfer=function(e,t,r,i){return H.LTP.Right.prepareRightTokenTransfer(e,t,r,i)};H.prepareRightTypeValidation=function(e){return H.LTP.Right.prepareRightTypeValidation(e)};H.prepareObligationToken=function(e,t,r,i,n,o){return H.LTP.Obligation.prepareObligationToken(e,t,r,i,n,o)};H.prepareObligationVerification=function(e,t){return H.LTP.Obligation.prepareObligationVerification(e,t)};H.prepareObligationFulfillment=function(e,t,r,i){return H.LTP.Obligation.prepareObligationFulfillment(e,t,r,i)};H.prepareObligationBreachAssessment=function(e,t,r){return H.LTP.Obligation.prepareObligationBreachAssessment(e,t,r)};H.prepareObligationMonitoringReport=function(e,t){return H.LTP.Obligation.prepareObligationMonitoringReport(e,t)};H.prepareClaimValidation=function(e,t){return H.LTP.Claim.prepareClaimValidation(e,t)};H.prepareClaimAttestation=function(e,t,r){return H.LTP.Claim.prepareClaimAttestation(e,t,r)};H.prepareClaimDispute=function(e,t,r){return H.LTP.Claim.prepareClaimDispute(e,t,r)};H.prepareBulkClaimValidation=function(e,t){return H.LTP.Claim.prepareBulkClaimValidation(e,t)};H.prepareClaimTemplate=function(e,t){return H.LTP.Claim.prepareClaimTemplate(e,t)};H.prepareSignatureProof=function(e,t,r){return H.LTP.Proof.prepareSignatureProof(e,t,r)};H.prepareSignatureVerification=function(e,t){return H.LTP.Proof.prepareSignatureVerification(e,t)};H.prepareSelectiveDisclosure=function(e,t,r){return H.LTP.Proof.prepareSelectiveDisclosure(e,t,r)};H.prepareSelectiveDisclosureVerification=function(e,t){return H.LTP.Proof.prepareSelectiveDisclosureVerification(e,t)};H.prepareLegalValidityProof=function(e,t,r){return H.LTP.Proof.prepareLegalValidityProof(e,t,r)};H.prepareZeroKnowledgeProof=function(e,t,r){return H.LTP.Proof.prepareZeroKnowledgeProof(e,t,r)};H.prepareRegistry=function(e){return H.LTP.Registry.prepareRegistry(e)};H.prepareTokenRegistration=function(e,t,r){return H.LTP.Registry.prepareTokenRegistration(e,t,r)};H.prepareTokenApproval=function(e,t,r){return H.LTP.Registry.prepareTokenApproval(e,t,r)};H.prepareTokenRevocation=function(e,t,r){return H.LTP.Registry.prepareTokenRevocation(e,t,r)};H.prepareTokenStatusQuery=function(e,t){return H.LTP.Registry.prepareTokenStatusQuery(e,t)};H.prepareTokenSearch=function(e,t){return H.LTP.Registry.prepareTokenSearch(e,t)};H.prepareStatisticsQuery=function(e){return H.LTP.Registry.prepareStatisticsQuery(e)};H.prepareAuditLogQuery=function(e,t){return H.LTP.Registry.prepareAuditLogQuery(e,t)};H.prepareTokenCommitment=function(e,t){return H.LTP.Anchor.prepareTokenCommitment(e,t)};H.prepareBatchCommitment=function(e,t){return H.LTP.Anchor.prepareBatchCommitment(e,t)};H.verifyTokenAnchor=function(e,t,r){return H.LTP.Anchor.verifyTokenAnchor(e,t,r)};H.formatRevocation=function(e,t){return H.LTP.Anchor.formatRevocation(e,t)};H.createRightToken=function(e,t,r){var i=new H.LTP;return i.createRightToken(e,t,r)};H.verifyLegalToken=function(e,t){var r=new H.LTP;return r.verifyToken(e,t)};H.validateLegalClaim=function(e,t){var r=new H.LTP;return r.validateClaim(e,t)};H.createSelectiveDisclosure=function(e,t,r){var i=new H.LTP;return i.createSelectiveDisclosure(e,t,r)};H.createLegalRegistry=function(e){return H.LTP.Registry.prepareRegistry(e)};H.createLegalValidityProof=function(e,t,r){var i=new H.LTP;return i.createLegalValidityProof(e,t,r)};H.getRightTypes=function(){return H.LTP.Right.getRightTypes()};H.getObligationTypes=function(){return H.LTP.Obligation.getObligationTypes()};H.getObligationPriority=function(){return H.LTP.Obligation.getObligationPriority()};H.getObligationStatus=function(){return H.LTP.Obligation.getObligationStatus()};H.getClaimSchemas=function(){return H.LTP.Claim.getSchemas()};H.getClaimSchemaNames=function(){return H.LTP.Claim.getSchemaNames()};H.getClaimSchema=function(e){return H.LTP.Claim.getSchema(e)};H.createClaimTemplate=function(e){return H.LTP.Claim.createTemplate(e)};H.canonicalizeClaim=function(e,t){return H.LTP.Claim.canonicalize(e,t)};H.hashClaim=function(e,t){return H.LTP.Claim.hash(e,t)};H.addCustomClaimSchema=function(e,t){return H.LTP.Claim.addSchema(e,t)};H.Transaction.sighash=mi()});var uee=T((vhe,HH)=>{g();HH.exports=Om()});return uee();})();
|