befly 3.15.0 → 3.15.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +1 -1
- package/dist/befly.config.js +1 -1
- package/dist/befly.js +316 -223
- package/dist/befly.min.js +13 -13
- package/dist/checks/checkConfig.d.ts +9 -0
- package/dist/checks/checkConfig.js +116 -0
- package/dist/checks/checkTable.js +105 -2
- package/dist/index.d.ts +1 -0
- package/dist/index.js +16 -9
- package/dist/lib/connect.js +6 -6
- package/dist/plugins/cache.js +2 -2
- package/dist/plugins/db.js +3 -3
- package/dist/sync/syncApi.js +2 -2
- package/dist/sync/syncCache.js +1 -1
- package/dist/sync/syncDev.js +2 -2
- package/dist/sync/syncMenu.js +4 -4
- package/dist/sync/syncTable.d.ts +13 -9
- package/dist/sync/syncTable.js +119 -202
- package/dist/types/befly.d.ts +2 -2
- package/dist/types/database.d.ts +1 -1
- package/dist/types/table.d.ts +1 -1
- package/dist/types/validate.d.ts +1 -1
- package/package.json +2 -2
package/dist/befly.min.js
CHANGED
|
@@ -1,18 +1,18 @@
|
|
|
1
1
|
// @bun
|
|
2
|
-
var
|
|
3
|
-
`)}catch{}}function
|
|
4
|
-
`}if(
|
|
5
|
-
`}function YX($){try{return JSON.stringify($)}catch{try{return JSON.stringify({level:$.level,time:$.time,pid:$.pid,hostname:$.hostname,msg:"[Unserializable log record]"})}catch{return'{"msg":"[Unserializable log record]"}'}}}function WX($){let{fileSink:J,consoleSink:Z}=$,X=(G,Y)=>{if(G==="debug"&&m0.debug!==1)return;let W=n(Y)?Y:{value:Y},Q=CZ(W,TZ),z=ZH(G,Q);if(J.enqueue(z),Z)Z.enqueue(z)};return{info(G){X("info",G)},warn(G){X("warn",G)},error(G){X("error",G)},debug(G){X("debug",G)}}}function GH(){let $=GX();if(!$)return null;let J=Date.now()-$.now,Z={requestId:$.requestId,method:$.method,route:$.route,ip:$.ip,now:$.now,durationSinceNowMs:J};return Z.userId=$.userId,Z.roleCode=$.roleCode,Z.nickname=$.nickname,Z.roleType=$.roleType,Z}function XH($,J){let Z={};for(let G of Object.keys($))Z[G]=$[G];let X=["requestId","method","route","ip","now","durationSinceNowMs","userId","roleCode","nickname","roleType"];for(let G of X)if(Z[G]===void 0)Z[G]=J[G];return Z}function _J($){if(n($))return $;if($ instanceof Error)return{err:$,msg:$.message||$.name||"Error"};if($===void 0)return{msg:""};if($===null)return{msg:"null"};if(typeof $==="object")return{value:$};try{return{msg:String($)}}catch{return{msg:"[Unserializable]"}}}function AJ($){let J=GH();if(!J)return $;return XH($,J)}class VX{maybeSanitizeForMock($){if(!S$)return $;return CZ($,TZ)}info($){let J=AJ(_J($)),Z=this.maybeSanitizeForMock(J);e$("app").info(Z)}warn($){let J=AJ(_J($)),Z=this.maybeSanitizeForMock(J);e$("app").warn(Z)}error($){let J=AJ(_J($)),Z=this.maybeSanitizeForMock(J);if(e$("app").error(Z),S$)return;e$("error").error(Z)}debug($){if(m0.debug!==1)return;let J=AJ(_J($)),Z=this.maybeSanitizeForMock(J);e$("app").debug(Z)}async flush(){await aW()}configure($){$H($)}setMock($){JH($)}async shutdown(){await QX()}}var lW,HX,TZ,rW,R$=null,I$=null,S$=null,G$=null,X$=null,Y$=null,m0,q;var a=z$(()=>{JX();n0();MJ();lW=process.cwd(),HX=["*password*","pass","pwd","*token*","access_token","refresh_token","accessToken","refreshToken","authorization","cookie","set-cookie","*secret*","apiKey","api_key","privateKey","private_key"],TZ={maxStringLen:100,maxArrayItems:100,sanitizeDepth:3,sanitizeNodes:500,sanitizeObjectKeys:100,sensitiveKeyMatcher:LZ({builtinPatterns:HX,userPatterns:[]})},rW=(()=>{try{return mW()}catch{return"unknown"}})(),m0={debug:0,dir:"./logs",console:1,maxSize:20};q=new VX});import{isAbsolute as YH}from"path";import{pathToFileURL as WH}from"url";function HH($){return/^[a-zA-Z]:[\\/]/.test($)}function QH($){if(YH($)||HH($))return WH($).href;return $}async function j$($,J){try{let G=($.endsWith(".json")?await import(QH($),{with:{type:"json"}}):await import($))?.default;if(G===null||G===void 0)return J;let Y=IZ(J),W=IZ(G);if(Y!==W)return q.warn({file:$,msg:"importDefault \u5BFC\u5165\u7C7B\u578B\u4E0E\u9ED8\u8BA4\u503C\u4E0D\u4E00\u81F4\uFF0C\u5DF2\u56DE\u9000\u5230\u9ED8\u8BA4\u503C",expectedType:Y,actualType:W}),J;return G}catch(Z){return q.warn({err:Z,file:$,msg:"importDefault \u5BFC\u5165\u5931\u8D25\uFF0C\u5DF2\u56DE\u9000\u5230\u9ED8\u8BA4\u503C"}),J}}var RJ=z$(()=>{a();n0()});function JJ($=""){if(!$)return $;return $.replace(/\\/g,"/").replace(VH,(J)=>J.toUpperCase())}function _H(){if(typeof process<"u"&&typeof process.cwd==="function")return process.cwd().replace(/\\/g,"/");return"/"}function DZ($,J){let Z="",X=0,G=-1,Y=0,W=null;for(let Q=0;Q<=$.length;++Q){if(Q<$.length)W=$[Q];else if(W==="/")break;else W="/";if(W==="/"){if(G===Q-1||Y===1);else if(Y===2){if(Z.length<2||X!==2||Z[Z.length-1]!=="."||Z[Z.length-2]!=="."){if(Z.length>2){let z=Z.lastIndexOf("/");if(z===-1)Z="",X=0;else Z=Z.slice(0,z),X=Z.length-1-Z.lastIndexOf("/");G=Q,Y=0;continue}else if(Z.length>0){Z="",X=0,G=Q,Y=0;continue}}if(J)Z+=Z.length>0?"/..":"..",X=2}else{if(Z.length>0)Z+=`/${$.slice(G+1,Q)}`;else Z=$.slice(G+1,Q);X=Q-G-1}G=Q,Y=0}else if(W==="."&&Y!==-1)++Y;else Y=-1}return Z}var VH,zH,OH,RX,FX,KH,MH,C$=function($){if($.length===0)return".";$=JJ($);let J=$.match(zH),Z=y$($),X=$[$.length-1]==="/";if($=DZ($,!Z),$.length===0){if(Z)return"/";return X?"./":"."}if(X)$+="/";if(RX.test($))$+="/";if(J){if(!Z)return`//./${$}`;return`//${$}`}return Z&&!y$($)?`/${$}`:$},d=function(...$){let J="";for(let Z of $){if(!Z)continue;if(J.length>0){let X=J[J.length-1]==="/",G=Z[0]==="/";if(X&&G)J+=Z.slice(1);else J+=X||G?Z:`/${Z}`}else J+=Z}return C$(J)},$J=function(...$){$=$.map((X)=>JJ(X));let J="",Z=!1;for(let X=$.length-1;X>=-1&&!Z;X--){let G=X>=0?$[X]:_H();if(!G||G.length===0)continue;J=`${G}/${J}`,Z=y$(G)}if(J=DZ(J,!Z),Z&&!y$(J))return`/${J}`;return J.length>0?J:"."},y$=function($){return OH.test($)},IX=function($){if($==="..")return"";let J=KH.exec(JJ($));return J&&J[1]||""},kZ=function($,J){let Z=$J($).replace(FX,"$1").split("/"),X=$J(J).replace(FX,"$1").split("/");if(X[0][1]===":"&&Z[0][1]===":"&&Z[0]!==X[0])return X.join("/");let G=[...Z];for(let Y of G){if(X[0]!==Y)break;Z.shift(),X.shift()}return[...Z.map(()=>".."),...X].join("/")},IJ=function($){let J=JJ($).replace(/\/$/,"").split("/").slice(0,-1);if(J.length===1&&RX.test(J[0]))J[0]+="/";return J.join("/")||(y$($)?"/":".")},jX=function($,J){let Z=JJ($).split("/"),X="";for(let G=Z.length-1;G>=0;G--){let Y=Z[G];if(Y){X=Y;break}}return J&&X.endsWith(J)?X.slice(0,-J.length):X},ZJ=function($){let J=MH.exec($)?.[0]?.replace(/\\/g,"/")||"",Z=jX($),X=IX(Z);return{root:J,dir:IJ($),base:Z,ext:X,name:Z.slice(0,Z.length-X.length)}};var qX=z$(()=>{VH=/^[A-Za-z]:\//;zH=/^[/\\]{2}/,OH=/^[/\\](?![/\\])|^[/\\]{2}(?!\.)|^[A-Za-z]:[/\\]/,RX=/^[A-Za-z]:$/,FX=/^\/([A-Za-z]:)?$/,KH=/.(\.[^./]+|\.)$/,MH=/^[/\\]|^[a-zA-Z]:[/\\]/});var q$=z$(()=>{qX()});import{statSync as AH}from"fs";var jJ=($,J)=>{if(J.isDirectory())return!0;if(!J.isSymbolicLink())return!1;try{return AH(d($,J.name)).isDirectory()}catch{return!1}};var fZ=z$(()=>{q$()});import{existsSync as x$}from"fs";import{readdir as FH}from"fs/promises";function RH($){if(!$||typeof $!=="object")return null;let J=$,Z=J.title;if(typeof Z!=="string"||!Z)return null;let X=J.order,G=typeof X==="number"&&Number.isFinite(X)&&Number.isInteger(X)&&X>=0?X:void 0;if(G===void 0)return{title:Z};return{title:Z,order:G}}async function BX($,J,Z=""){if(!x$($))return[];let X=[],G=await FH($,{withFileTypes:!0});for(let Y of G){if(!jJ($,Y)||Y.name==="components")continue;let W=d($,Y.name),Q=d(W,"meta.json"),z=d(W,"index.vue"),O=null;if(!x$(Q))continue;if(!x$(z)){q.warn({path:W,msg:"\u76EE\u5F55\u5B58\u5728 meta.json \u4F46\u7F3A\u5C11 index.vue\uFF0C\u5DF2\u8DF3\u8FC7\u8BE5\u76EE\u5F55\u83DC\u5355\u540C\u6B65"});continue}let M=await j$(Q,{});if(O=RH(M),!O?.title){q.warn({path:Q,msg:"meta.json \u7F3A\u5C11\u6709\u6548\u7684 title\uFF08\u4EE5\u53CA\u53EF\u9009 order:number\uFF09\uFF0C\u5DF2\u8DF3\u8FC7\u8BE5\u76EE\u5F55\u83DC\u5355\u540C\u6B65"});continue}if(!O?.title)continue;let A=String(Y.name).replace(/_\d+$/,""),B;if(A==="index")B=Z;else B=Z?`${Z}/${A}`:`/${A}`;let L=J?B?`${J}${B}`:J:B||"/",C={name:O.title,path:L,sort:O.order??999999},w=await BX(W,J,B);if(w.length>0)C.children=w;X.push(C)}return X.sort((Y,W)=>(Y.sort??999999)-(W.sort??999999)),X}function PX($){let J=$.split("/").filter((Z)=>Boolean(Z));if(J.length<=1)return"";return`/${J.slice(0,-1).join("/")}`}async function LX($){let J=[];for(let X of $){let G=d(X.fullPath,"adminViews"),Y=d(X.fullPath,"views","admin"),W=x$(G)?G:x$(Y)?Y:null;if(!W)continue;try{let Q=`/${X.source}/${X.name}`,z=await BX(W,Q);if(z.length>0)for(let O of z)J.push(O)}catch(Q){q.warn({err:Q,addon:X.name,addonSource:X.source,dir:W,msg:"\u626B\u63CF addon views \u76EE\u5F55\u5931\u8D25"})}}let Z=d(process.cwd(),"menus.json");if(x$(Z)){let X=await j$(Z,[]);if(Array.isArray(X)&&X.length>0)for(let G of X)J.push(G)}return J}var yZ=z$(()=>{q$();a();RJ();fZ()});var n$=o((W7,k1)=>{var D1={invalidType:"FAST_JWT_INVALID_TYPE",invalidOption:"FAST_JWT_INVALID_OPTION",invalidAlgorithm:"FAST_JWT_INVALID_ALGORITHM",invalidClaimType:"FAST_JWT_INVALID_CLAIM_TYPE",invalidClaimValue:"FAST_JWT_INVALID_CLAIM_VALUE",invalidKey:"FAST_JWT_INVALID_KEY",invalidSignature:"FAST_JWT_INVALID_SIGNATURE",invalidPayload:"FAST_JWT_INVALID_PAYLOAD",malformed:"FAST_JWT_MALFORMED",inactive:"FAST_JWT_INACTIVE",expired:"FAST_JWT_EXPIRED",missingKey:"FAST_JWT_MISSING_KEY",keyFetchingError:"FAST_JWT_KEY_FETCHING_ERROR",signError:"FAST_JWT_SIGN_ERROR",verifyError:"FAST_JWT_VERIFY_ERROR",missingRequiredClaim:"FAST_JWT_MISSING_REQUIRED_CLAIM",missingSignature:"FAST_JWT_MISSING_SIGNATURE"};class u$ extends Error{constructor($,J,Z){super(J);if(Error.captureStackTrace(this,this.constructor),this.code=$,Z)for(let X in Z)this[X]=Z[X]}}u$.codes=D1;u$.wrap=function($,J,Z){if($ instanceof u$)return $;return new u$(J,Z,{originalError:$})};k1.exports={TokenError:u$,TOKEN_ERROR_CODES:D1}});var $G=o((H7,f1)=>{var{TokenError:Q$}=n$();function yQ({complete:$,checkTyp:J},Z){if(Z instanceof Buffer)Z=Z.toString("utf-8");else if(typeof Z!=="string")throw new Q$(Q$.codes.invalidType,"The token must be a string or a buffer.");let X=Z.indexOf("."),G=Z.lastIndexOf(".");if(X===-1||X>=G)throw new Q$(Q$.codes.malformed,"The token is malformed.");let Y=!1;try{let W=JSON.parse(Buffer.from(Z.slice(0,X),"base64").toString("utf-8"));if(J&&W.typ!==J)throw new Q$(Q$.codes.invalidType,`The type must be "${J}".`,{header:W});Y=!0;let Q=Buffer.from(Z.slice(X+1,G),"base64").toString("utf-8");if(Q=JSON.parse(Q),!Q||typeof Q!=="object")throw new Q$(Q$.codes.invalidPayload,"The payload must be an object",{payload:Q});return $?{header:W,payload:Q,signature:Z.slice(G+1),input:Z.slice(0,G)}:Q}catch(W){throw Q$.wrap(W,Q$.codes.malformed,`The token ${Y?"payload":"header"} is not a valid base64url serialized JSON.`)}}f1.exports=function(J={}){let Z=J.complete||!1,X=J.checkTyp;return yQ.bind(null,{complete:Z,checkTyp:X})}});var x1=o((Q7,y1)=>{function U$($){if(typeof $!=="function")throw Error("obliterator/iterator: expecting a function!");this.next=$}if(typeof Symbol<"u")U$.prototype[Symbol.iterator]=function(){return this};U$.of=function(){var $=arguments,J=$.length,Z=0;return new U$(function(){if(Z>=J)return{done:!0};return{done:!1,value:$[Z++]}})};U$.empty=function(){var $=new U$(function(){return{done:!0}});return $};U$.fromSequence=function($){var J=0,Z=$.length;return new U$(function(){if(J>=Z)return{done:!0};return{done:!1,value:$[J++]}})};U$.is=function($){if($ instanceof U$)return!0;return typeof $==="object"&&$!==null&&typeof $.next==="function"};y1.exports=U$});var g1=o((xQ)=>{xQ.ARRAY_BUFFER_SUPPORT=typeof ArrayBuffer<"u";xQ.SYMBOL_SUPPORT=typeof Symbol<"u"});var JG=o((V7,b1)=>{var h1=g1(),bQ=h1.ARRAY_BUFFER_SUPPORT,cQ=h1.SYMBOL_SUPPORT;b1.exports=function(J,Z){var X,G,Y,W,Q;if(!J)throw Error("obliterator/forEach: invalid iterable.");if(typeof Z!=="function")throw Error("obliterator/forEach: expecting a callback.");if(Array.isArray(J)||bQ&&ArrayBuffer.isView(J)||typeof J==="string"||J.toString()==="[object Arguments]"){for(Y=0,W=J.length;Y<W;Y++)Z(J[Y],Y);return}if(typeof J.forEach==="function"){J.forEach(Z);return}if(cQ&&Symbol.iterator in J&&typeof J.next!=="function")J=J[Symbol.iterator]();if(typeof J.next==="function"){X=J,Y=0;while(Q=X.next(),Q.done!==!0)Z(Q.value,Y),Y++;return}for(G in J)if(J.hasOwnProperty(G))Z(J[G],G);return}});var ZG=o((lQ)=>{var pQ=Math.pow(2,8)-1,uQ=Math.pow(2,16)-1,nQ=Math.pow(2,32)-1,mQ=Math.pow(2,7)-1,dQ=Math.pow(2,15)-1,sQ=Math.pow(2,31)-1;lQ.getPointerArray=function($){var J=$-1;if(J<=pQ)return Uint8Array;if(J<=uQ)return Uint16Array;if(J<=nQ)return Uint32Array;throw Error("mnemonist: Pointer Array of size > 4294967295 is not supported.")};lQ.getSignedPointerArray=function($){var J=$-1;if(J<=mQ)return Int8Array;if(J<=dQ)return Int16Array;if(J<=sQ)return Int32Array;return Float64Array};lQ.getNumberType=function($){if($===($|0))if(Math.sign($)===-1){if($<=127&&$>=-128)return Int8Array;if($<=32767&&$>=-32768)return Int16Array;return Int32Array}else{if($<=255)return Uint8Array;if($<=65535)return Uint16Array;return Uint32Array}return Float64Array};var oQ={Uint8Array:1,Int8Array:2,Uint16Array:3,Int16Array:4,Uint32Array:5,Int32Array:6,Float32Array:7,Float64Array:8};lQ.getMinimalRepresentation=function($,J){var Z=null,X=0,G,Y,W,Q,z;for(Q=0,z=$.length;Q<z;Q++)if(W=J?J($[Q]):$[Q],Y=lQ.getNumberType(W),G=oQ[Y.name],G>X)X=G,Z=Y;return Z};lQ.isTypedArray=function($){return typeof ArrayBuffer<"u"&&ArrayBuffer.isView($)};lQ.concat=function(){var $=0,J,Z,X;for(J=0,X=arguments.length;J<X;J++)$+=arguments[J].length;var G=new arguments[0].constructor($);for(J=0,Z=0;J<X;J++)G.set(arguments[J],Z),Z+=arguments[J].length;return G};lQ.indices=function($){var J=lQ.getPointerArray($),Z=new J($);for(var X=0;X<$;X++)Z[X]=X;return Z}});var m1=o((G9)=>{var u1=JG(),n1=ZG();function $9($){return Array.isArray($)||n1.isTypedArray($)}function GG($){if(typeof $.length==="number")return $.length;if(typeof $.size==="number")return $.size;return}function J9($){var J=GG($),Z=typeof J==="number"?Array(J):[],X=0;return u1($,function(G){Z[X++]=G}),Z}function Z9($){var J=GG($),Z=typeof J==="number"?n1.getPointerArray(J):Array,X=typeof J==="number"?Array(J):[],G=typeof J==="number"?new Z(J):[],Y=0;return u1($,function(W){X[Y]=W,G[Y]=Y++}),[X,G]}G9.isArrayLike=$9;G9.guessLength=GG;G9.toArray=J9;G9.toArrayWithIndices=Z9});var YG=o((K7,d1)=>{var XG=x1(),Q9=JG(),U9=ZG(),V9=m1();function p0($,J,Z){if(arguments.length<2)Z=$,$=null,J=null;if(this.capacity=Z,typeof this.capacity!=="number"||this.capacity<=0)throw Error("mnemonist/lru-cache: capacity should be positive number.");else if(!isFinite(this.capacity)||Math.floor(this.capacity)!==this.capacity)throw Error("mnemonist/lru-cache: capacity should be a finite positive integer.");var X=U9.getPointerArray(Z);this.forward=new X(Z),this.backward=new X(Z),this.K=typeof $==="function"?new $(Z):Array(Z),this.V=typeof J==="function"?new J(Z):Array(Z),this.size=0,this.head=0,this.tail=0,this.items={}}p0.prototype.clear=function(){this.size=0,this.head=0,this.tail=0,this.items={}};p0.prototype.splayOnTop=function($){var J=this.head;if(this.head===$)return this;var Z=this.backward[$],X=this.forward[$];if(this.tail===$)this.tail=Z;else this.backward[X]=Z;return this.forward[Z]=X,this.backward[J]=$,this.head=$,this.forward[$]=J,this};p0.prototype.set=function($,J){var Z=this.items[$];if(typeof Z<"u"){this.splayOnTop(Z),this.V[Z]=J;return}if(this.size<this.capacity)Z=this.size++;else Z=this.tail,this.tail=this.backward[Z],delete this.items[this.K[Z]];this.items[$]=Z,this.K[Z]=$,this.V[Z]=J,this.forward[Z]=this.head,this.backward[this.head]=Z,this.head=Z};p0.prototype.setpop=function($,J){var Z=null,X=null,G=this.items[$];if(typeof G<"u")return this.splayOnTop(G),Z=this.V[G],this.V[G]=J,{evicted:!1,key:$,value:Z};if(this.size<this.capacity)G=this.size++;else G=this.tail,this.tail=this.backward[G],Z=this.V[G],X=this.K[G],delete this.items[X];if(this.items[$]=G,this.K[G]=$,this.V[G]=J,this.forward[G]=this.head,this.backward[this.head]=G,this.head=G,X)return{evicted:!0,key:X,value:Z};else return null};p0.prototype.has=function($){return $ in this.items};p0.prototype.get=function($){var J=this.items[$];if(typeof J>"u")return;return this.splayOnTop(J),this.V[J]};p0.prototype.peek=function($){var J=this.items[$];if(typeof J>"u")return;return this.V[J]};p0.prototype.forEach=function($,J){J=arguments.length>1?J:this;var Z=0,X=this.size,G=this.head,Y=this.K,W=this.V,Q=this.forward;while(Z<X)$.call(J,W[G],Y[G],this),G=Q[G],Z++};p0.prototype.keys=function(){var $=0,J=this.size,Z=this.head,X=this.K,G=this.forward;return new XG(function(){if($>=J)return{done:!0};var Y=X[Z];if($++,$<J)Z=G[Z];return{done:!1,value:Y}})};p0.prototype.values=function(){var $=0,J=this.size,Z=this.head,X=this.V,G=this.forward;return new XG(function(){if($>=J)return{done:!0};var Y=X[Z];if($++,$<J)Z=G[Z];return{done:!1,value:Y}})};p0.prototype.entries=function(){var $=0,J=this.size,Z=this.head,X=this.K,G=this.V,Y=this.forward;return new XG(function(){if($>=J)return{done:!0};var W=X[Z],Q=G[Z];if($++,$<J)Z=Y[Z];return{done:!1,value:[W,Q]}})};if(typeof Symbol<"u")p0.prototype[Symbol.iterator]=p0.prototype.entries;p0.prototype.inspect=function(){var $=new Map,J=this.entries(),Z;while(Z=J.next(),!Z.done)$.set(Z.value[0],Z.value[1]);return Object.defineProperty($,"constructor",{value:p0,enumerable:!1}),$};if(typeof Symbol<"u")p0.prototype[Symbol.for("nodejs.util.inspect.custom")]=p0.prototype.inspect;p0.from=function($,J,Z,X){if(arguments.length<2){if(X=V9.guessLength($),typeof X!=="number")throw Error("mnemonist/lru-cache.from: could not guess iterable length. Please provide desired capacity as last argument.")}else if(arguments.length===2)X=J,J=null,Z=null;var G=new p0(J,Z,X);return Q9($,function(Y,W){G.set(W,Y)}),G};d1.exports=p0});var HG=o((s1,WG)=>{(function($,J){function Z(j,H){if(!j)throw Error(H||"Assertion failed")}function X(j,H){j.super_=H;var V=function(){};V.prototype=H.prototype,j.prototype=new V,j.prototype.constructor=j}function G(j,H,V){if(G.isBN(j))return j;if(this.negative=0,this.words=null,this.length=0,this.red=null,j!==null){if(H==="le"||H==="be")V=H,H=10;this._init(j||0,H||10,V||"be")}}if(typeof $==="object")$.exports=G;else J.BN=G;G.BN=G,G.wordSize=26;var Y;try{if(typeof window<"u"&&typeof window.Buffer<"u")Y=window.Buffer;else Y=A$("buffer").Buffer}catch(j){}G.isBN=function(H){if(H instanceof G)return!0;return H!==null&&typeof H==="object"&&H.constructor.wordSize===G.wordSize&&Array.isArray(H.words)},G.max=function(H,V){if(H.cmp(V)>0)return H;return V},G.min=function(H,V){if(H.cmp(V)<0)return H;return V},G.prototype._init=function(H,V,K){if(typeof H==="number")return this._initNumber(H,V,K);if(typeof H==="object")return this._initArray(H,V,K);if(V==="hex")V=16;Z(V===(V|0)&&V>=2&&V<=36),H=H.toString().replace(/\s+/g,"");var _=0;if(H[0]==="-")_++,this.negative=1;if(_<H.length){if(V===16)this._parseHex(H,_,K);else if(this._parseBase(H,V,_),K==="le")this._initArray(this.toArray(),V,K)}},G.prototype._initNumber=function(H,V,K){if(H<0)this.negative=1,H=-H;if(H<67108864)this.words=[H&67108863],this.length=1;else if(H<4503599627370496)this.words=[H&67108863,H/67108864&67108863],this.length=2;else Z(H<9007199254740992),this.words=[H&67108863,H/67108864&67108863,1],this.length=3;if(K!=="le")return;this._initArray(this.toArray(),V,K)},G.prototype._initArray=function(H,V,K){if(Z(typeof H.length==="number"),H.length<=0)return this.words=[0],this.length=1,this;this.length=Math.ceil(H.length/3),this.words=Array(this.length);for(var _=0;_<this.length;_++)this.words[_]=0;var I,P,S=0;if(K==="be"){for(_=H.length-1,I=0;_>=0;_-=3)if(P=H[_]|H[_-1]<<8|H[_-2]<<16,this.words[I]|=P<<S&67108863,this.words[I+1]=P>>>26-S&67108863,S+=24,S>=26)S-=26,I++}else if(K==="le"){for(_=0,I=0;_<H.length;_+=3)if(P=H[_]|H[_+1]<<8|H[_+2]<<16,this.words[I]|=P<<S&67108863,this.words[I+1]=P>>>26-S&67108863,S+=24,S>=26)S-=26,I++}return this.strip()};function W(j,H){var V=j.charCodeAt(H);if(V>=65&&V<=70)return V-55;else if(V>=97&&V<=102)return V-87;else return V-48&15}function Q(j,H,V){var K=W(j,V);if(V-1>=H)K|=W(j,V-1)<<4;return K}G.prototype._parseHex=function(H,V,K){this.length=Math.ceil((H.length-V)/6),this.words=Array(this.length);for(var _=0;_<this.length;_++)this.words[_]=0;var I=0,P=0,S;if(K==="be")for(_=H.length-1;_>=V;_-=2)if(S=Q(H,V,_)<<I,this.words[P]|=S&67108863,I>=18)I-=18,P+=1,this.words[P]|=S>>>26;else I+=8;else{var F=H.length-V;for(_=F%2===0?V+1:V;_<H.length;_+=2)if(S=Q(H,V,_)<<I,this.words[P]|=S&67108863,I>=18)I-=18,P+=1,this.words[P]|=S>>>26;else I+=8}this.strip()};function z(j,H,V,K){var _=0,I=Math.min(j.length,V);for(var P=H;P<I;P++){var S=j.charCodeAt(P)-48;if(_*=K,S>=49)_+=S-49+10;else if(S>=17)_+=S-17+10;else _+=S}return _}G.prototype._parseBase=function(H,V,K){this.words=[0],this.length=1;for(var _=0,I=1;I<=67108863;I*=V)_++;_--,I=I/V|0;var P=H.length-K,S=P%_,F=Math.min(P,P-S)+K,U=0;for(var R=K;R<F;R+=_)if(U=z(H,R,R+_,V),this.imuln(I),this.words[0]+U<67108864)this.words[0]+=U;else this._iaddn(U);if(S!==0){var k=1;U=z(H,R,H.length,V);for(R=0;R<S;R++)k*=V;if(this.imuln(k),this.words[0]+U<67108864)this.words[0]+=U;else this._iaddn(U)}this.strip()},G.prototype.copy=function(H){H.words=Array(this.length);for(var V=0;V<this.length;V++)H.words[V]=this.words[V];H.length=this.length,H.negative=this.negative,H.red=this.red},G.prototype.clone=function(){var H=new G(null);return this.copy(H),H},G.prototype._expand=function(H){while(this.length<H)this.words[this.length++]=0;return this},G.prototype.strip=function(){while(this.length>1&&this.words[this.length-1]===0)this.length--;return this._normSign()},G.prototype._normSign=function(){if(this.length===1&&this.words[0]===0)this.negative=0;return this},G.prototype.inspect=function(){return(this.red?"<BN-R: ":"<BN: ")+this.toString(16)+">"};var O=["","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"],M=[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],A=[0,0,33554432,43046721,16777216,48828125,60466176,40353607,16777216,43046721,1e7,19487171,35831808,62748517,7529536,11390625,16777216,24137569,34012224,47045881,64000000,4084101,5153632,6436343,7962624,9765625,11881376,14348907,17210368,20511149,24300000,28629151,33554432,39135393,45435424,52521875,60466176];if(G.prototype.toString=function(H,V){H=H||10,V=V|0||1;var K;if(H===16||H==="hex"){K="";var _=0,I=0;for(var P=0;P<this.length;P++){var S=this.words[P],F=((S<<_|I)&16777215).toString(16);if(I=S>>>24-_&16777215,_+=2,_>=26)_-=26,P--;if(I!==0||P!==this.length-1)K=O[6-F.length]+F+K;else K=F+K}if(I!==0)K=I.toString(16)+K;while(K.length%V!==0)K="0"+K;if(this.negative!==0)K="-"+K;return K}if(H===(H|0)&&H>=2&&H<=36){var U=M[H],R=A[H];K="";var k=this.clone();k.negative=0;while(!k.isZero()){var f=k.modn(R).toString(H);if(k=k.idivn(R),!k.isZero())K=O[U-f.length]+f+K;else K=f+K}if(this.isZero())K="0"+K;while(K.length%V!==0)K="0"+K;if(this.negative!==0)K="-"+K;return K}Z(!1,"Base should be between 2 and 36")},G.prototype.toNumber=function(){var H=this.words[0];if(this.length===2)H+=this.words[1]*67108864;else if(this.length===3&&this.words[2]===1)H+=4503599627370496+this.words[1]*67108864;else if(this.length>2)Z(!1,"Number can only safely store up to 53 bits");return this.negative!==0?-H:H},G.prototype.toJSON=function(){return this.toString(16)},G.prototype.toBuffer=function(H,V){return Z(typeof Y<"u"),this.toArrayLike(Y,H,V)},G.prototype.toArray=function(H,V){return this.toArrayLike(Array,H,V)},G.prototype.toArrayLike=function(H,V,K){var _=this.byteLength(),I=K||Math.max(1,_);Z(_<=I,"byte array longer than desired length"),Z(I>0,"Requested array length <= 0"),this.strip();var P=V==="le",S=new H(I),F,U,R=this.clone();if(!P){for(U=0;U<I-_;U++)S[U]=0;for(U=0;!R.isZero();U++)F=R.andln(255),R.iushrn(8),S[I-U-1]=F}else{for(U=0;!R.isZero();U++)F=R.andln(255),R.iushrn(8),S[U]=F;for(;U<I;U++)S[U]=0}return S},Math.clz32)G.prototype._countBits=function(H){return 32-Math.clz32(H)};else G.prototype._countBits=function(H){var V=H,K=0;if(V>=4096)K+=13,V>>>=13;if(V>=64)K+=7,V>>>=7;if(V>=8)K+=4,V>>>=4;if(V>=2)K+=2,V>>>=2;return K+V};G.prototype._zeroBits=function(H){if(H===0)return 26;var V=H,K=0;if((V&8191)===0)K+=13,V>>>=13;if((V&127)===0)K+=7,V>>>=7;if((V&15)===0)K+=4,V>>>=4;if((V&3)===0)K+=2,V>>>=2;if((V&1)===0)K++;return K},G.prototype.bitLength=function(){var H=this.words[this.length-1],V=this._countBits(H);return(this.length-1)*26+V};function B(j){var H=Array(j.bitLength());for(var V=0;V<H.length;V++){var K=V/26|0,_=V%26;H[V]=(j.words[K]&1<<_)>>>_}return H}G.prototype.zeroBits=function(){if(this.isZero())return 0;var H=0;for(var V=0;V<this.length;V++){var K=this._zeroBits(this.words[V]);if(H+=K,K!==26)break}return H},G.prototype.byteLength=function(){return Math.ceil(this.bitLength()/8)},G.prototype.toTwos=function(H){if(this.negative!==0)return this.abs().inotn(H).iaddn(1);return this.clone()},G.prototype.fromTwos=function(H){if(this.testn(H-1))return this.notn(H).iaddn(1).ineg();return this.clone()},G.prototype.isNeg=function(){return this.negative!==0},G.prototype.neg=function(){return this.clone().ineg()},G.prototype.ineg=function(){if(!this.isZero())this.negative^=1;return this},G.prototype.iuor=function(H){while(this.length<H.length)this.words[this.length++]=0;for(var V=0;V<H.length;V++)this.words[V]=this.words[V]|H.words[V];return this.strip()},G.prototype.ior=function(H){return Z((this.negative|H.negative)===0),this.iuor(H)},G.prototype.or=function(H){if(this.length>H.length)return this.clone().ior(H);return H.clone().ior(this)},G.prototype.uor=function(H){if(this.length>H.length)return this.clone().iuor(H);return H.clone().iuor(this)},G.prototype.iuand=function(H){var V;if(this.length>H.length)V=H;else V=this;for(var K=0;K<V.length;K++)this.words[K]=this.words[K]&H.words[K];return this.length=V.length,this.strip()},G.prototype.iand=function(H){return Z((this.negative|H.negative)===0),this.iuand(H)},G.prototype.and=function(H){if(this.length>H.length)return this.clone().iand(H);return H.clone().iand(this)},G.prototype.uand=function(H){if(this.length>H.length)return this.clone().iuand(H);return H.clone().iuand(this)},G.prototype.iuxor=function(H){var V,K;if(this.length>H.length)V=this,K=H;else V=H,K=this;for(var _=0;_<K.length;_++)this.words[_]=V.words[_]^K.words[_];if(this!==V)for(;_<V.length;_++)this.words[_]=V.words[_];return this.length=V.length,this.strip()},G.prototype.ixor=function(H){return Z((this.negative|H.negative)===0),this.iuxor(H)},G.prototype.xor=function(H){if(this.length>H.length)return this.clone().ixor(H);return H.clone().ixor(this)},G.prototype.uxor=function(H){if(this.length>H.length)return this.clone().iuxor(H);return H.clone().iuxor(this)},G.prototype.inotn=function(H){Z(typeof H==="number"&&H>=0);var V=Math.ceil(H/26)|0,K=H%26;if(this._expand(V),K>0)V--;for(var _=0;_<V;_++)this.words[_]=~this.words[_]&67108863;if(K>0)this.words[_]=~this.words[_]&67108863>>26-K;return this.strip()},G.prototype.notn=function(H){return this.clone().inotn(H)},G.prototype.setn=function(H,V){Z(typeof H==="number"&&H>=0);var K=H/26|0,_=H%26;if(this._expand(K+1),V)this.words[K]=this.words[K]|1<<_;else this.words[K]=this.words[K]&~(1<<_);return this.strip()},G.prototype.iadd=function(H){var V;if(this.negative!==0&&H.negative===0)return this.negative=0,V=this.isub(H),this.negative^=1,this._normSign();else if(this.negative===0&&H.negative!==0)return H.negative=0,V=this.isub(H),H.negative=1,V._normSign();var K,_;if(this.length>H.length)K=this,_=H;else K=H,_=this;var I=0;for(var P=0;P<_.length;P++)V=(K.words[P]|0)+(_.words[P]|0)+I,this.words[P]=V&67108863,I=V>>>26;for(;I!==0&&P<K.length;P++)V=(K.words[P]|0)+I,this.words[P]=V&67108863,I=V>>>26;if(this.length=K.length,I!==0)this.words[this.length]=I,this.length++;else if(K!==this)for(;P<K.length;P++)this.words[P]=K.words[P];return this},G.prototype.add=function(H){var V;if(H.negative!==0&&this.negative===0)return H.negative=0,V=this.sub(H),H.negative^=1,V;else if(H.negative===0&&this.negative!==0)return this.negative=0,V=H.sub(this),this.negative=1,V;if(this.length>H.length)return this.clone().iadd(H);return H.clone().iadd(this)},G.prototype.isub=function(H){if(H.negative!==0){H.negative=0;var V=this.iadd(H);return H.negative=1,V._normSign()}else if(this.negative!==0)return this.negative=0,this.iadd(H),this.negative=1,this._normSign();var K=this.cmp(H);if(K===0)return this.negative=0,this.length=1,this.words[0]=0,this;var _,I;if(K>0)_=this,I=H;else _=H,I=this;var P=0;for(var S=0;S<I.length;S++)V=(_.words[S]|0)-(I.words[S]|0)+P,P=V>>26,this.words[S]=V&67108863;for(;P!==0&&S<_.length;S++)V=(_.words[S]|0)+P,P=V>>26,this.words[S]=V&67108863;if(P===0&&S<_.length&&_!==this)for(;S<_.length;S++)this.words[S]=_.words[S];if(this.length=Math.max(this.length,S),_!==this)this.negative=1;return this.strip()},G.prototype.sub=function(H){return this.clone().isub(H)};function L(j,H,V){V.negative=H.negative^j.negative;var K=j.length+H.length|0;V.length=K,K=K-1|0;var _=j.words[0]|0,I=H.words[0]|0,P=_*I,S=P&67108863,F=P/67108864|0;V.words[0]=S;for(var U=1;U<K;U++){var R=F>>>26,k=F&67108863,f=Math.min(U,H.length-1);for(var y=Math.max(0,U-j.length+1);y<=f;y++){var u=U-y|0;_=j.words[u]|0,I=H.words[y]|0,P=_*I+k,R+=P/67108864|0,k=P&67108863}V.words[U]=k|0,F=R|0}if(F!==0)V.words[U]=F|0;else V.length--;return V.strip()}var C=function(H,V,K){var _=H.words,I=V.words,P=K.words,S=0,F,U,R,k=_[0]|0,f=k&8191,y=k>>>13,u=_[1]|0,r=u&8191,e=u>>>13,_$=_[2]|0,$0=_$&8191,Z0=_$>>>13,DG=_[3]|0,H0=DG&8191,Q0=DG>>>13,kG=_[4]|0,U0=kG&8191,V0=kG>>>13,fG=_[5]|0,z0=fG&8191,O0=fG>>>13,yG=_[6]|0,K0=yG&8191,M0=yG>>>13,xG=_[7]|0,_0=xG&8191,A0=xG>>>13,gG=_[8]|0,F0=gG&8191,R0=gG>>>13,hG=_[9]|0,I0=hG&8191,j0=hG>>>13,bG=I[0]|0,q0=bG&8191,B0=bG>>>13,cG=I[1]|0,P0=cG&8191,L0=cG>>>13,pG=I[2]|0,S0=pG&8191,C0=pG>>>13,uG=I[3]|0,E0=uG&8191,w0=uG>>>13,nG=I[4]|0,T0=nG&8191,N0=nG>>>13,mG=I[5]|0,v0=mG&8191,D0=mG>>>13,dG=I[6]|0,k0=dG&8191,f0=dG>>>13,sG=I[7]|0,y0=sG&8191,x0=sG>>>13,oG=I[8]|0,g0=oG&8191,h0=oG>>>13,lG=I[9]|0,b0=lG&8191,c0=lG>>>13;K.negative=H.negative^V.negative,K.length=19,F=Math.imul(f,q0),U=Math.imul(f,B0),U=U+Math.imul(y,q0)|0,R=Math.imul(y,B0);var eJ=(S+F|0)+((U&8191)<<13)|0;S=(R+(U>>>13)|0)+(eJ>>>26)|0,eJ&=67108863,F=Math.imul(r,q0),U=Math.imul(r,B0),U=U+Math.imul(e,q0)|0,R=Math.imul(e,B0),F=F+Math.imul(f,P0)|0,U=U+Math.imul(f,L0)|0,U=U+Math.imul(y,P0)|0,R=R+Math.imul(y,L0)|0;var $Z=(S+F|0)+((U&8191)<<13)|0;S=(R+(U>>>13)|0)+($Z>>>26)|0,$Z&=67108863,F=Math.imul($0,q0),U=Math.imul($0,B0),U=U+Math.imul(Z0,q0)|0,R=Math.imul(Z0,B0),F=F+Math.imul(r,P0)|0,U=U+Math.imul(r,L0)|0,U=U+Math.imul(e,P0)|0,R=R+Math.imul(e,L0)|0,F=F+Math.imul(f,S0)|0,U=U+Math.imul(f,C0)|0,U=U+Math.imul(y,S0)|0,R=R+Math.imul(y,C0)|0;var JZ=(S+F|0)+((U&8191)<<13)|0;S=(R+(U>>>13)|0)+(JZ>>>26)|0,JZ&=67108863,F=Math.imul(H0,q0),U=Math.imul(H0,B0),U=U+Math.imul(Q0,q0)|0,R=Math.imul(Q0,B0),F=F+Math.imul($0,P0)|0,U=U+Math.imul($0,L0)|0,U=U+Math.imul(Z0,P0)|0,R=R+Math.imul(Z0,L0)|0,F=F+Math.imul(r,S0)|0,U=U+Math.imul(r,C0)|0,U=U+Math.imul(e,S0)|0,R=R+Math.imul(e,C0)|0,F=F+Math.imul(f,E0)|0,U=U+Math.imul(f,w0)|0,U=U+Math.imul(y,E0)|0,R=R+Math.imul(y,w0)|0;var ZZ=(S+F|0)+((U&8191)<<13)|0;S=(R+(U>>>13)|0)+(ZZ>>>26)|0,ZZ&=67108863,F=Math.imul(U0,q0),U=Math.imul(U0,B0),U=U+Math.imul(V0,q0)|0,R=Math.imul(V0,B0),F=F+Math.imul(H0,P0)|0,U=U+Math.imul(H0,L0)|0,U=U+Math.imul(Q0,P0)|0,R=R+Math.imul(Q0,L0)|0,F=F+Math.imul($0,S0)|0,U=U+Math.imul($0,C0)|0,U=U+Math.imul(Z0,S0)|0,R=R+Math.imul(Z0,C0)|0,F=F+Math.imul(r,E0)|0,U=U+Math.imul(r,w0)|0,U=U+Math.imul(e,E0)|0,R=R+Math.imul(e,w0)|0,F=F+Math.imul(f,T0)|0,U=U+Math.imul(f,N0)|0,U=U+Math.imul(y,T0)|0,R=R+Math.imul(y,N0)|0;var GZ=(S+F|0)+((U&8191)<<13)|0;S=(R+(U>>>13)|0)+(GZ>>>26)|0,GZ&=67108863,F=Math.imul(z0,q0),U=Math.imul(z0,B0),U=U+Math.imul(O0,q0)|0,R=Math.imul(O0,B0),F=F+Math.imul(U0,P0)|0,U=U+Math.imul(U0,L0)|0,U=U+Math.imul(V0,P0)|0,R=R+Math.imul(V0,L0)|0,F=F+Math.imul(H0,S0)|0,U=U+Math.imul(H0,C0)|0,U=U+Math.imul(Q0,S0)|0,R=R+Math.imul(Q0,C0)|0,F=F+Math.imul($0,E0)|0,U=U+Math.imul($0,w0)|0,U=U+Math.imul(Z0,E0)|0,R=R+Math.imul(Z0,w0)|0,F=F+Math.imul(r,T0)|0,U=U+Math.imul(r,N0)|0,U=U+Math.imul(e,T0)|0,R=R+Math.imul(e,N0)|0,F=F+Math.imul(f,v0)|0,U=U+Math.imul(f,D0)|0,U=U+Math.imul(y,v0)|0,R=R+Math.imul(y,D0)|0;var XZ=(S+F|0)+((U&8191)<<13)|0;S=(R+(U>>>13)|0)+(XZ>>>26)|0,XZ&=67108863,F=Math.imul(K0,q0),U=Math.imul(K0,B0),U=U+Math.imul(M0,q0)|0,R=Math.imul(M0,B0),F=F+Math.imul(z0,P0)|0,U=U+Math.imul(z0,L0)|0,U=U+Math.imul(O0,P0)|0,R=R+Math.imul(O0,L0)|0,F=F+Math.imul(U0,S0)|0,U=U+Math.imul(U0,C0)|0,U=U+Math.imul(V0,S0)|0,R=R+Math.imul(V0,C0)|0,F=F+Math.imul(H0,E0)|0,U=U+Math.imul(H0,w0)|0,U=U+Math.imul(Q0,E0)|0,R=R+Math.imul(Q0,w0)|0,F=F+Math.imul($0,T0)|0,U=U+Math.imul($0,N0)|0,U=U+Math.imul(Z0,T0)|0,R=R+Math.imul(Z0,N0)|0,F=F+Math.imul(r,v0)|0,U=U+Math.imul(r,D0)|0,U=U+Math.imul(e,v0)|0,R=R+Math.imul(e,D0)|0,F=F+Math.imul(f,k0)|0,U=U+Math.imul(f,f0)|0,U=U+Math.imul(y,k0)|0,R=R+Math.imul(y,f0)|0;var YZ=(S+F|0)+((U&8191)<<13)|0;S=(R+(U>>>13)|0)+(YZ>>>26)|0,YZ&=67108863,F=Math.imul(_0,q0),U=Math.imul(_0,B0),U=U+Math.imul(A0,q0)|0,R=Math.imul(A0,B0),F=F+Math.imul(K0,P0)|0,U=U+Math.imul(K0,L0)|0,U=U+Math.imul(M0,P0)|0,R=R+Math.imul(M0,L0)|0,F=F+Math.imul(z0,S0)|0,U=U+Math.imul(z0,C0)|0,U=U+Math.imul(O0,S0)|0,R=R+Math.imul(O0,C0)|0,F=F+Math.imul(U0,E0)|0,U=U+Math.imul(U0,w0)|0,U=U+Math.imul(V0,E0)|0,R=R+Math.imul(V0,w0)|0,F=F+Math.imul(H0,T0)|0,U=U+Math.imul(H0,N0)|0,U=U+Math.imul(Q0,T0)|0,R=R+Math.imul(Q0,N0)|0,F=F+Math.imul($0,v0)|0,U=U+Math.imul($0,D0)|0,U=U+Math.imul(Z0,v0)|0,R=R+Math.imul(Z0,D0)|0,F=F+Math.imul(r,k0)|0,U=U+Math.imul(r,f0)|0,U=U+Math.imul(e,k0)|0,R=R+Math.imul(e,f0)|0,F=F+Math.imul(f,y0)|0,U=U+Math.imul(f,x0)|0,U=U+Math.imul(y,y0)|0,R=R+Math.imul(y,x0)|0;var WZ=(S+F|0)+((U&8191)<<13)|0;S=(R+(U>>>13)|0)+(WZ>>>26)|0,WZ&=67108863,F=Math.imul(F0,q0),U=Math.imul(F0,B0),U=U+Math.imul(R0,q0)|0,R=Math.imul(R0,B0),F=F+Math.imul(_0,P0)|0,U=U+Math.imul(_0,L0)|0,U=U+Math.imul(A0,P0)|0,R=R+Math.imul(A0,L0)|0,F=F+Math.imul(K0,S0)|0,U=U+Math.imul(K0,C0)|0,U=U+Math.imul(M0,S0)|0,R=R+Math.imul(M0,C0)|0,F=F+Math.imul(z0,E0)|0,U=U+Math.imul(z0,w0)|0,U=U+Math.imul(O0,E0)|0,R=R+Math.imul(O0,w0)|0,F=F+Math.imul(U0,T0)|0,U=U+Math.imul(U0,N0)|0,U=U+Math.imul(V0,T0)|0,R=R+Math.imul(V0,N0)|0,F=F+Math.imul(H0,v0)|0,U=U+Math.imul(H0,D0)|0,U=U+Math.imul(Q0,v0)|0,R=R+Math.imul(Q0,D0)|0,F=F+Math.imul($0,k0)|0,U=U+Math.imul($0,f0)|0,U=U+Math.imul(Z0,k0)|0,R=R+Math.imul(Z0,f0)|0,F=F+Math.imul(r,y0)|0,U=U+Math.imul(r,x0)|0,U=U+Math.imul(e,y0)|0,R=R+Math.imul(e,x0)|0,F=F+Math.imul(f,g0)|0,U=U+Math.imul(f,h0)|0,U=U+Math.imul(y,g0)|0,R=R+Math.imul(y,h0)|0;var HZ=(S+F|0)+((U&8191)<<13)|0;S=(R+(U>>>13)|0)+(HZ>>>26)|0,HZ&=67108863,F=Math.imul(I0,q0),U=Math.imul(I0,B0),U=U+Math.imul(j0,q0)|0,R=Math.imul(j0,B0),F=F+Math.imul(F0,P0)|0,U=U+Math.imul(F0,L0)|0,U=U+Math.imul(R0,P0)|0,R=R+Math.imul(R0,L0)|0,F=F+Math.imul(_0,S0)|0,U=U+Math.imul(_0,C0)|0,U=U+Math.imul(A0,S0)|0,R=R+Math.imul(A0,C0)|0,F=F+Math.imul(K0,E0)|0,U=U+Math.imul(K0,w0)|0,U=U+Math.imul(M0,E0)|0,R=R+Math.imul(M0,w0)|0,F=F+Math.imul(z0,T0)|0,U=U+Math.imul(z0,N0)|0,U=U+Math.imul(O0,T0)|0,R=R+Math.imul(O0,N0)|0,F=F+Math.imul(U0,v0)|0,U=U+Math.imul(U0,D0)|0,U=U+Math.imul(V0,v0)|0,R=R+Math.imul(V0,D0)|0,F=F+Math.imul(H0,k0)|0,U=U+Math.imul(H0,f0)|0,U=U+Math.imul(Q0,k0)|0,R=R+Math.imul(Q0,f0)|0,F=F+Math.imul($0,y0)|0,U=U+Math.imul($0,x0)|0,U=U+Math.imul(Z0,y0)|0,R=R+Math.imul(Z0,x0)|0,F=F+Math.imul(r,g0)|0,U=U+Math.imul(r,h0)|0,U=U+Math.imul(e,g0)|0,R=R+Math.imul(e,h0)|0,F=F+Math.imul(f,b0)|0,U=U+Math.imul(f,c0)|0,U=U+Math.imul(y,b0)|0,R=R+Math.imul(y,c0)|0;var QZ=(S+F|0)+((U&8191)<<13)|0;S=(R+(U>>>13)|0)+(QZ>>>26)|0,QZ&=67108863,F=Math.imul(I0,P0),U=Math.imul(I0,L0),U=U+Math.imul(j0,P0)|0,R=Math.imul(j0,L0),F=F+Math.imul(F0,S0)|0,U=U+Math.imul(F0,C0)|0,U=U+Math.imul(R0,S0)|0,R=R+Math.imul(R0,C0)|0,F=F+Math.imul(_0,E0)|0,U=U+Math.imul(_0,w0)|0,U=U+Math.imul(A0,E0)|0,R=R+Math.imul(A0,w0)|0,F=F+Math.imul(K0,T0)|0,U=U+Math.imul(K0,N0)|0,U=U+Math.imul(M0,T0)|0,R=R+Math.imul(M0,N0)|0,F=F+Math.imul(z0,v0)|0,U=U+Math.imul(z0,D0)|0,U=U+Math.imul(O0,v0)|0,R=R+Math.imul(O0,D0)|0,F=F+Math.imul(U0,k0)|0,U=U+Math.imul(U0,f0)|0,U=U+Math.imul(V0,k0)|0,R=R+Math.imul(V0,f0)|0,F=F+Math.imul(H0,y0)|0,U=U+Math.imul(H0,x0)|0,U=U+Math.imul(Q0,y0)|0,R=R+Math.imul(Q0,x0)|0,F=F+Math.imul($0,g0)|0,U=U+Math.imul($0,h0)|0,U=U+Math.imul(Z0,g0)|0,R=R+Math.imul(Z0,h0)|0,F=F+Math.imul(r,b0)|0,U=U+Math.imul(r,c0)|0,U=U+Math.imul(e,b0)|0,R=R+Math.imul(e,c0)|0;var UZ=(S+F|0)+((U&8191)<<13)|0;S=(R+(U>>>13)|0)+(UZ>>>26)|0,UZ&=67108863,F=Math.imul(I0,S0),U=Math.imul(I0,C0),U=U+Math.imul(j0,S0)|0,R=Math.imul(j0,C0),F=F+Math.imul(F0,E0)|0,U=U+Math.imul(F0,w0)|0,U=U+Math.imul(R0,E0)|0,R=R+Math.imul(R0,w0)|0,F=F+Math.imul(_0,T0)|0,U=U+Math.imul(_0,N0)|0,U=U+Math.imul(A0,T0)|0,R=R+Math.imul(A0,N0)|0,F=F+Math.imul(K0,v0)|0,U=U+Math.imul(K0,D0)|0,U=U+Math.imul(M0,v0)|0,R=R+Math.imul(M0,D0)|0,F=F+Math.imul(z0,k0)|0,U=U+Math.imul(z0,f0)|0,U=U+Math.imul(O0,k0)|0,R=R+Math.imul(O0,f0)|0,F=F+Math.imul(U0,y0)|0,U=U+Math.imul(U0,x0)|0,U=U+Math.imul(V0,y0)|0,R=R+Math.imul(V0,x0)|0,F=F+Math.imul(H0,g0)|0,U=U+Math.imul(H0,h0)|0,U=U+Math.imul(Q0,g0)|0,R=R+Math.imul(Q0,h0)|0,F=F+Math.imul($0,b0)|0,U=U+Math.imul($0,c0)|0,U=U+Math.imul(Z0,b0)|0,R=R+Math.imul(Z0,c0)|0;var VZ=(S+F|0)+((U&8191)<<13)|0;S=(R+(U>>>13)|0)+(VZ>>>26)|0,VZ&=67108863,F=Math.imul(I0,E0),U=Math.imul(I0,w0),U=U+Math.imul(j0,E0)|0,R=Math.imul(j0,w0),F=F+Math.imul(F0,T0)|0,U=U+Math.imul(F0,N0)|0,U=U+Math.imul(R0,T0)|0,R=R+Math.imul(R0,N0)|0,F=F+Math.imul(_0,v0)|0,U=U+Math.imul(_0,D0)|0,U=U+Math.imul(A0,v0)|0,R=R+Math.imul(A0,D0)|0,F=F+Math.imul(K0,k0)|0,U=U+Math.imul(K0,f0)|0,U=U+Math.imul(M0,k0)|0,R=R+Math.imul(M0,f0)|0,F=F+Math.imul(z0,y0)|0,U=U+Math.imul(z0,x0)|0,U=U+Math.imul(O0,y0)|0,R=R+Math.imul(O0,x0)|0,F=F+Math.imul(U0,g0)|0,U=U+Math.imul(U0,h0)|0,U=U+Math.imul(V0,g0)|0,R=R+Math.imul(V0,h0)|0,F=F+Math.imul(H0,b0)|0,U=U+Math.imul(H0,c0)|0,U=U+Math.imul(Q0,b0)|0,R=R+Math.imul(Q0,c0)|0;var zZ=(S+F|0)+((U&8191)<<13)|0;S=(R+(U>>>13)|0)+(zZ>>>26)|0,zZ&=67108863,F=Math.imul(I0,T0),U=Math.imul(I0,N0),U=U+Math.imul(j0,T0)|0,R=Math.imul(j0,N0),F=F+Math.imul(F0,v0)|0,U=U+Math.imul(F0,D0)|0,U=U+Math.imul(R0,v0)|0,R=R+Math.imul(R0,D0)|0,F=F+Math.imul(_0,k0)|0,U=U+Math.imul(_0,f0)|0,U=U+Math.imul(A0,k0)|0,R=R+Math.imul(A0,f0)|0,F=F+Math.imul(K0,y0)|0,U=U+Math.imul(K0,x0)|0,U=U+Math.imul(M0,y0)|0,R=R+Math.imul(M0,x0)|0,F=F+Math.imul(z0,g0)|0,U=U+Math.imul(z0,h0)|0,U=U+Math.imul(O0,g0)|0,R=R+Math.imul(O0,h0)|0,F=F+Math.imul(U0,b0)|0,U=U+Math.imul(U0,c0)|0,U=U+Math.imul(V0,b0)|0,R=R+Math.imul(V0,c0)|0;var OZ=(S+F|0)+((U&8191)<<13)|0;S=(R+(U>>>13)|0)+(OZ>>>26)|0,OZ&=67108863,F=Math.imul(I0,v0),U=Math.imul(I0,D0),U=U+Math.imul(j0,v0)|0,R=Math.imul(j0,D0),F=F+Math.imul(F0,k0)|0,U=U+Math.imul(F0,f0)|0,U=U+Math.imul(R0,k0)|0,R=R+Math.imul(R0,f0)|0,F=F+Math.imul(_0,y0)|0,U=U+Math.imul(_0,x0)|0,U=U+Math.imul(A0,y0)|0,R=R+Math.imul(A0,x0)|0,F=F+Math.imul(K0,g0)|0,U=U+Math.imul(K0,h0)|0,U=U+Math.imul(M0,g0)|0,R=R+Math.imul(M0,h0)|0,F=F+Math.imul(z0,b0)|0,U=U+Math.imul(z0,c0)|0,U=U+Math.imul(O0,b0)|0,R=R+Math.imul(O0,c0)|0;var KZ=(S+F|0)+((U&8191)<<13)|0;S=(R+(U>>>13)|0)+(KZ>>>26)|0,KZ&=67108863,F=Math.imul(I0,k0),U=Math.imul(I0,f0),U=U+Math.imul(j0,k0)|0,R=Math.imul(j0,f0),F=F+Math.imul(F0,y0)|0,U=U+Math.imul(F0,x0)|0,U=U+Math.imul(R0,y0)|0,R=R+Math.imul(R0,x0)|0,F=F+Math.imul(_0,g0)|0,U=U+Math.imul(_0,h0)|0,U=U+Math.imul(A0,g0)|0,R=R+Math.imul(A0,h0)|0,F=F+Math.imul(K0,b0)|0,U=U+Math.imul(K0,c0)|0,U=U+Math.imul(M0,b0)|0,R=R+Math.imul(M0,c0)|0;var MZ=(S+F|0)+((U&8191)<<13)|0;S=(R+(U>>>13)|0)+(MZ>>>26)|0,MZ&=67108863,F=Math.imul(I0,y0),U=Math.imul(I0,x0),U=U+Math.imul(j0,y0)|0,R=Math.imul(j0,x0),F=F+Math.imul(F0,g0)|0,U=U+Math.imul(F0,h0)|0,U=U+Math.imul(R0,g0)|0,R=R+Math.imul(R0,h0)|0,F=F+Math.imul(_0,b0)|0,U=U+Math.imul(_0,c0)|0,U=U+Math.imul(A0,b0)|0,R=R+Math.imul(A0,c0)|0;var _Z=(S+F|0)+((U&8191)<<13)|0;S=(R+(U>>>13)|0)+(_Z>>>26)|0,_Z&=67108863,F=Math.imul(I0,g0),U=Math.imul(I0,h0),U=U+Math.imul(j0,g0)|0,R=Math.imul(j0,h0),F=F+Math.imul(F0,b0)|0,U=U+Math.imul(F0,c0)|0,U=U+Math.imul(R0,b0)|0,R=R+Math.imul(R0,c0)|0;var AZ=(S+F|0)+((U&8191)<<13)|0;S=(R+(U>>>13)|0)+(AZ>>>26)|0,AZ&=67108863,F=Math.imul(I0,b0),U=Math.imul(I0,c0),U=U+Math.imul(j0,b0)|0,R=Math.imul(j0,c0);var FZ=(S+F|0)+((U&8191)<<13)|0;if(S=(R+(U>>>13)|0)+(FZ>>>26)|0,FZ&=67108863,P[0]=eJ,P[1]=$Z,P[2]=JZ,P[3]=ZZ,P[4]=GZ,P[5]=XZ,P[6]=YZ,P[7]=WZ,P[8]=HZ,P[9]=QZ,P[10]=UZ,P[11]=VZ,P[12]=zZ,P[13]=OZ,P[14]=KZ,P[15]=MZ,P[16]=_Z,P[17]=AZ,P[18]=FZ,S!==0)P[19]=S,K.length++;return K};if(!Math.imul)C=L;function w(j,H,V){V.negative=H.negative^j.negative,V.length=j.length+H.length;var K=0,_=0;for(var I=0;I<V.length-1;I++){var P=_;_=0;var S=K&67108863,F=Math.min(I,H.length-1);for(var U=Math.max(0,I-j.length+1);U<=F;U++){var R=I-U,k=j.words[R]|0,f=H.words[U]|0,y=k*f,u=y&67108863;P=P+(y/67108864|0)|0,u=u+S|0,S=u&67108863,P=P+(u>>>26)|0,_+=P>>>26,P&=67108863}V.words[I]=S,K=P,P=_}if(K!==0)V.words[I]=K;else V.length--;return V.strip()}function T(j,H,V){var K=new D;return K.mulp(j,H,V)}G.prototype.mulTo=function(H,V){var K,_=this.length+H.length;if(this.length===10&&H.length===10)K=C(this,H,V);else if(_<63)K=L(this,H,V);else if(_<1024)K=w(this,H,V);else K=T(this,H,V);return K};function D(j,H){this.x=j,this.y=H}D.prototype.makeRBT=function(H){var V=Array(H),K=G.prototype._countBits(H)-1;for(var _=0;_<H;_++)V[_]=this.revBin(_,K,H);return V},D.prototype.revBin=function(H,V,K){if(H===0||H===K-1)return H;var _=0;for(var I=0;I<V;I++)_|=(H&1)<<V-I-1,H>>=1;return _},D.prototype.permute=function(H,V,K,_,I,P){for(var S=0;S<P;S++)_[S]=V[H[S]],I[S]=K[H[S]]},D.prototype.transform=function(H,V,K,_,I,P){this.permute(P,H,V,K,_,I);for(var S=1;S<I;S<<=1){var F=S<<1,U=Math.cos(2*Math.PI/F),R=Math.sin(2*Math.PI/F);for(var k=0;k<I;k+=F){var f=U,y=R;for(var u=0;u<S;u++){var r=K[k+u],e=_[k+u],_$=K[k+u+S],$0=_[k+u+S],Z0=f*_$-y*$0;if($0=f*$0+y*_$,_$=Z0,K[k+u]=r+_$,_[k+u]=e+$0,K[k+u+S]=r-_$,_[k+u+S]=e-$0,u!==F)Z0=U*f-R*y,y=U*y+R*f,f=Z0}}}},D.prototype.guessLen13b=function(H,V){var K=Math.max(V,H)|1,_=K&1,I=0;for(K=K/2|0;K;K=K>>>1)I++;return 1<<I+1+_},D.prototype.conjugate=function(H,V,K){if(K<=1)return;for(var _=0;_<K/2;_++){var I=H[_];H[_]=H[K-_-1],H[K-_-1]=I,I=V[_],V[_]=-V[K-_-1],V[K-_-1]=-I}},D.prototype.normalize13b=function(H,V){var K=0;for(var _=0;_<V/2;_++){var I=Math.round(H[2*_+1]/V)*8192+Math.round(H[2*_]/V)+K;if(H[_]=I&67108863,I<67108864)K=0;else K=I/67108864|0}return H},D.prototype.convert13b=function(H,V,K,_){var I=0;for(var P=0;P<V;P++)I=I+(H[P]|0),K[2*P]=I&8191,I=I>>>13,K[2*P+1]=I&8191,I=I>>>13;for(P=2*V;P<_;++P)K[P]=0;Z(I===0),Z((I&-8192)===0)},D.prototype.stub=function(H){var V=Array(H);for(var K=0;K<H;K++)V[K]=0;return V},D.prototype.mulp=function(H,V,K){var _=2*this.guessLen13b(H.length,V.length),I=this.makeRBT(_),P=this.stub(_),S=Array(_),F=Array(_),U=Array(_),R=Array(_),k=Array(_),f=Array(_),y=K.words;y.length=_,this.convert13b(H.words,H.length,S,_),this.convert13b(V.words,V.length,R,_),this.transform(S,P,F,U,_,I),this.transform(R,P,k,f,_,I);for(var u=0;u<_;u++){var r=F[u]*k[u]-U[u]*f[u];U[u]=F[u]*f[u]+U[u]*k[u],F[u]=r}return this.conjugate(F,U,_),this.transform(F,U,y,P,_,I),this.conjugate(y,P,_),this.normalize13b(y,_),K.negative=H.negative^V.negative,K.length=H.length+V.length,K.strip()},G.prototype.mul=function(H){var V=new G(null);return V.words=Array(this.length+H.length),this.mulTo(H,V)},G.prototype.mulf=function(H){var V=new G(null);return V.words=Array(this.length+H.length),T(this,H,V)},G.prototype.imul=function(H){return this.clone().mulTo(H,this)},G.prototype.imuln=function(H){Z(typeof H==="number"),Z(H<67108864);var V=0;for(var K=0;K<this.length;K++){var _=(this.words[K]|0)*H,I=(_&67108863)+(V&67108863);V>>=26,V+=_/67108864|0,V+=I>>>26,this.words[K]=I&67108863}if(V!==0)this.words[K]=V,this.length++;return this.length=H===0?1:this.length,this},G.prototype.muln=function(H){return this.clone().imuln(H)},G.prototype.sqr=function(){return this.mul(this)},G.prototype.isqr=function(){return this.imul(this.clone())},G.prototype.pow=function(H){var V=B(H);if(V.length===0)return new G(1);var K=this;for(var _=0;_<V.length;_++,K=K.sqr())if(V[_]!==0)break;if(++_<V.length)for(var I=K.sqr();_<V.length;_++,I=I.sqr()){if(V[_]===0)continue;K=K.mul(I)}return K},G.prototype.iushln=function(H){Z(typeof H==="number"&&H>=0);var V=H%26,K=(H-V)/26,_=67108863>>>26-V<<26-V,I;if(V!==0){var P=0;for(I=0;I<this.length;I++){var S=this.words[I]&_,F=(this.words[I]|0)-S<<V;this.words[I]=F|P,P=S>>>26-V}if(P)this.words[I]=P,this.length++}if(K!==0){for(I=this.length-1;I>=0;I--)this.words[I+K]=this.words[I];for(I=0;I<K;I++)this.words[I]=0;this.length+=K}return this.strip()},G.prototype.ishln=function(H){return Z(this.negative===0),this.iushln(H)},G.prototype.iushrn=function(H,V,K){Z(typeof H==="number"&&H>=0);var _;if(V)_=(V-V%26)/26;else _=0;var I=H%26,P=Math.min((H-I)/26,this.length),S=67108863^67108863>>>I<<I,F=K;if(_-=P,_=Math.max(0,_),F){for(var U=0;U<P;U++)F.words[U]=this.words[U];F.length=P}if(P===0);else if(this.length>P){this.length-=P;for(U=0;U<this.length;U++)this.words[U]=this.words[U+P]}else this.words[0]=0,this.length=1;var R=0;for(U=this.length-1;U>=0&&(R!==0||U>=_);U--){var k=this.words[U]|0;this.words[U]=R<<26-I|k>>>I,R=k&S}if(F&&R!==0)F.words[F.length++]=R;if(this.length===0)this.words[0]=0,this.length=1;return this.strip()},G.prototype.ishrn=function(H,V,K){return Z(this.negative===0),this.iushrn(H,V,K)},G.prototype.shln=function(H){return this.clone().ishln(H)},G.prototype.ushln=function(H){return this.clone().iushln(H)},G.prototype.shrn=function(H){return this.clone().ishrn(H)},G.prototype.ushrn=function(H){return this.clone().iushrn(H)},G.prototype.testn=function(H){Z(typeof H==="number"&&H>=0);var V=H%26,K=(H-V)/26,_=1<<V;if(this.length<=K)return!1;var I=this.words[K];return!!(I&_)},G.prototype.imaskn=function(H){Z(typeof H==="number"&&H>=0);var V=H%26,K=(H-V)/26;if(Z(this.negative===0,"imaskn works only with positive numbers"),this.length<=K)return this;if(V!==0)K++;if(this.length=Math.min(K,this.length),V!==0){var _=67108863^67108863>>>V<<V;this.words[this.length-1]&=_}return this.strip()},G.prototype.maskn=function(H){return this.clone().imaskn(H)},G.prototype.iaddn=function(H){if(Z(typeof H==="number"),Z(H<67108864),H<0)return this.isubn(-H);if(this.negative!==0){if(this.length===1&&(this.words[0]|0)<H)return this.words[0]=H-(this.words[0]|0),this.negative=0,this;return this.negative=0,this.isubn(H),this.negative=1,this}return this._iaddn(H)},G.prototype._iaddn=function(H){this.words[0]+=H;for(var V=0;V<this.length&&this.words[V]>=67108864;V++)if(this.words[V]-=67108864,V===this.length-1)this.words[V+1]=1;else this.words[V+1]++;return this.length=Math.max(this.length,V+1),this},G.prototype.isubn=function(H){if(Z(typeof H==="number"),Z(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 V=0;V<this.length&&this.words[V]<0;V++)this.words[V]+=67108864,this.words[V+1]-=1;return this.strip()},G.prototype.addn=function(H){return this.clone().iaddn(H)},G.prototype.subn=function(H){return this.clone().isubn(H)},G.prototype.iabs=function(){return this.negative=0,this},G.prototype.abs=function(){return this.clone().iabs()},G.prototype._ishlnsubmul=function(H,V,K){var _=H.length+K,I;this._expand(_);var P,S=0;for(I=0;I<H.length;I++){P=(this.words[I+K]|0)+S;var F=(H.words[I]|0)*V;P-=F&67108863,S=(P>>26)-(F/67108864|0),this.words[I+K]=P&67108863}for(;I<this.length-K;I++)P=(this.words[I+K]|0)+S,S=P>>26,this.words[I+K]=P&67108863;if(S===0)return this.strip();Z(S===-1),S=0;for(I=0;I<this.length;I++)P=-(this.words[I]|0)+S,S=P>>26,this.words[I]=P&67108863;return this.negative=1,this.strip()},G.prototype._wordDiv=function(H,V){var K=this.length-H.length,_=this.clone(),I=H,P=I.words[I.length-1]|0,S=this._countBits(P);if(K=26-S,K!==0)I=I.ushln(K),_.iushln(K),P=I.words[I.length-1]|0;var F=_.length-I.length,U;if(V!=="mod"){U=new G(null),U.length=F+1,U.words=Array(U.length);for(var R=0;R<U.length;R++)U.words[R]=0}var k=_.clone()._ishlnsubmul(I,1,F);if(k.negative===0){if(_=k,U)U.words[F]=1}for(var f=F-1;f>=0;f--){var y=(_.words[I.length+f]|0)*67108864+(_.words[I.length+f-1]|0);y=Math.min(y/P|0,67108863),_._ishlnsubmul(I,y,f);while(_.negative!==0)if(y--,_.negative=0,_._ishlnsubmul(I,1,f),!_.isZero())_.negative^=1;if(U)U.words[f]=y}if(U)U.strip();if(_.strip(),V!=="div"&&K!==0)_.iushrn(K);return{div:U||null,mod:_}},G.prototype.divmod=function(H,V,K){if(Z(!H.isZero()),this.isZero())return{div:new G(0),mod:new G(0)};var _,I,P;if(this.negative!==0&&H.negative===0){if(P=this.neg().divmod(H,V),V!=="mod")_=P.div.neg();if(V!=="div"){if(I=P.mod.neg(),K&&I.negative!==0)I.iadd(H)}return{div:_,mod:I}}if(this.negative===0&&H.negative!==0){if(P=this.divmod(H.neg(),V),V!=="mod")_=P.div.neg();return{div:_,mod:P.mod}}if((this.negative&H.negative)!==0){if(P=this.neg().divmod(H.neg(),V),V!=="div"){if(I=P.mod.neg(),K&&I.negative!==0)I.isub(H)}return{div:P.div,mod:I}}if(H.length>this.length||this.cmp(H)<0)return{div:new G(0),mod:this};if(H.length===1){if(V==="div")return{div:this.divn(H.words[0]),mod:null};if(V==="mod")return{div:null,mod:new G(this.modn(H.words[0]))};return{div:this.divn(H.words[0]),mod:new G(this.modn(H.words[0]))}}return this._wordDiv(H,V)},G.prototype.div=function(H){return this.divmod(H,"div",!1).div},G.prototype.mod=function(H){return this.divmod(H,"mod",!1).mod},G.prototype.umod=function(H){return this.divmod(H,"mod",!0).mod},G.prototype.divRound=function(H){var V=this.divmod(H);if(V.mod.isZero())return V.div;var K=V.div.negative!==0?V.mod.isub(H):V.mod,_=H.ushrn(1),I=H.andln(1),P=K.cmp(_);if(P<0||I===1&&P===0)return V.div;return V.div.negative!==0?V.div.isubn(1):V.div.iaddn(1)},G.prototype.modn=function(H){Z(H<=67108863);var V=67108864%H,K=0;for(var _=this.length-1;_>=0;_--)K=(V*K+(this.words[_]|0))%H;return K},G.prototype.idivn=function(H){Z(H<=67108863);var V=0;for(var K=this.length-1;K>=0;K--){var _=(this.words[K]|0)+V*67108864;this.words[K]=_/H|0,V=_%H}return this.strip()},G.prototype.divn=function(H){return this.clone().idivn(H)},G.prototype.egcd=function(H){Z(H.negative===0),Z(!H.isZero());var V=this,K=H.clone();if(V.negative!==0)V=V.umod(H);else V=V.clone();var _=new G(1),I=new G(0),P=new G(0),S=new G(1),F=0;while(V.isEven()&&K.isEven())V.iushrn(1),K.iushrn(1),++F;var U=K.clone(),R=V.clone();while(!V.isZero()){for(var k=0,f=1;(V.words[0]&f)===0&&k<26;++k,f<<=1);if(k>0){V.iushrn(k);while(k-- >0){if(_.isOdd()||I.isOdd())_.iadd(U),I.isub(R);_.iushrn(1),I.iushrn(1)}}for(var y=0,u=1;(K.words[0]&u)===0&&y<26;++y,u<<=1);if(y>0){K.iushrn(y);while(y-- >0){if(P.isOdd()||S.isOdd())P.iadd(U),S.isub(R);P.iushrn(1),S.iushrn(1)}}if(V.cmp(K)>=0)V.isub(K),_.isub(P),I.isub(S);else K.isub(V),P.isub(_),S.isub(I)}return{a:P,b:S,gcd:K.iushln(F)}},G.prototype._invmp=function(H){Z(H.negative===0),Z(!H.isZero());var V=this,K=H.clone();if(V.negative!==0)V=V.umod(H);else V=V.clone();var _=new G(1),I=new G(0),P=K.clone();while(V.cmpn(1)>0&&K.cmpn(1)>0){for(var S=0,F=1;(V.words[0]&F)===0&&S<26;++S,F<<=1);if(S>0){V.iushrn(S);while(S-- >0){if(_.isOdd())_.iadd(P);_.iushrn(1)}}for(var U=0,R=1;(K.words[0]&R)===0&&U<26;++U,R<<=1);if(U>0){K.iushrn(U);while(U-- >0){if(I.isOdd())I.iadd(P);I.iushrn(1)}}if(V.cmp(K)>=0)V.isub(K),_.isub(I);else K.isub(V),I.isub(_)}var k;if(V.cmpn(1)===0)k=_;else k=I;if(k.cmpn(0)<0)k.iadd(H);return k},G.prototype.gcd=function(H){if(this.isZero())return H.abs();if(H.isZero())return this.abs();var V=this.clone(),K=H.clone();V.negative=0,K.negative=0;for(var _=0;V.isEven()&&K.isEven();_++)V.iushrn(1),K.iushrn(1);do{while(V.isEven())V.iushrn(1);while(K.isEven())K.iushrn(1);var I=V.cmp(K);if(I<0){var P=V;V=K,K=P}else if(I===0||K.cmpn(1)===0)break;V.isub(K)}while(!0);return K.iushln(_)},G.prototype.invm=function(H){return this.egcd(H).a.umod(H)},G.prototype.isEven=function(){return(this.words[0]&1)===0},G.prototype.isOdd=function(){return(this.words[0]&1)===1},G.prototype.andln=function(H){return this.words[0]&H},G.prototype.bincn=function(H){Z(typeof H==="number");var V=H%26,K=(H-V)/26,_=1<<V;if(this.length<=K)return this._expand(K+1),this.words[K]|=_,this;var I=_;for(var P=K;I!==0&&P<this.length;P++){var S=this.words[P]|0;S+=I,I=S>>>26,S&=67108863,this.words[P]=S}if(I!==0)this.words[P]=I,this.length++;return this},G.prototype.isZero=function(){return this.length===1&&this.words[0]===0},G.prototype.cmpn=function(H){var V=H<0;if(this.negative!==0&&!V)return-1;if(this.negative===0&&V)return 1;this.strip();var K;if(this.length>1)K=1;else{if(V)H=-H;Z(H<=67108863,"Number is too big");var _=this.words[0]|0;K=_===H?0:_<H?-1:1}if(this.negative!==0)return-K|0;return K},G.prototype.cmp=function(H){if(this.negative!==0&&H.negative===0)return-1;if(this.negative===0&&H.negative!==0)return 1;var V=this.ucmp(H);if(this.negative!==0)return-V|0;return V},G.prototype.ucmp=function(H){if(this.length>H.length)return 1;if(this.length<H.length)return-1;var V=0;for(var K=this.length-1;K>=0;K--){var _=this.words[K]|0,I=H.words[K]|0;if(_===I)continue;if(_<I)V=-1;else if(_>I)V=1;break}return V},G.prototype.gtn=function(H){return this.cmpn(H)===1},G.prototype.gt=function(H){return this.cmp(H)===1},G.prototype.gten=function(H){return this.cmpn(H)>=0},G.prototype.gte=function(H){return this.cmp(H)>=0},G.prototype.ltn=function(H){return this.cmpn(H)===-1},G.prototype.lt=function(H){return this.cmp(H)===-1},G.prototype.lten=function(H){return this.cmpn(H)<=0},G.prototype.lte=function(H){return this.cmp(H)<=0},G.prototype.eqn=function(H){return this.cmpn(H)===0},G.prototype.eq=function(H){return this.cmp(H)===0},G.red=function(H){return new l(H)},G.prototype.toRed=function(H){return Z(!this.red,"Already a number in reduction context"),Z(this.negative===0,"red works only with positives"),H.convertTo(this)._forceRed(H)},G.prototype.fromRed=function(){return Z(this.red,"fromRed works only with numbers in reduction context"),this.red.convertFrom(this)},G.prototype._forceRed=function(H){return this.red=H,this},G.prototype.forceRed=function(H){return Z(!this.red,"Already a number in reduction context"),this._forceRed(H)},G.prototype.redAdd=function(H){return Z(this.red,"redAdd works only with red numbers"),this.red.add(this,H)},G.prototype.redIAdd=function(H){return Z(this.red,"redIAdd works only with red numbers"),this.red.iadd(this,H)},G.prototype.redSub=function(H){return Z(this.red,"redSub works only with red numbers"),this.red.sub(this,H)},G.prototype.redISub=function(H){return Z(this.red,"redISub works only with red numbers"),this.red.isub(this,H)},G.prototype.redShl=function(H){return Z(this.red,"redShl works only with red numbers"),this.red.shl(this,H)},G.prototype.redMul=function(H){return Z(this.red,"redMul works only with red numbers"),this.red._verify2(this,H),this.red.mul(this,H)},G.prototype.redIMul=function(H){return Z(this.red,"redMul works only with red numbers"),this.red._verify2(this,H),this.red.imul(this,H)},G.prototype.redSqr=function(){return Z(this.red,"redSqr works only with red numbers"),this.red._verify1(this),this.red.sqr(this)},G.prototype.redISqr=function(){return Z(this.red,"redISqr works only with red numbers"),this.red._verify1(this),this.red.isqr(this)},G.prototype.redSqrt=function(){return Z(this.red,"redSqrt works only with red numbers"),this.red._verify1(this),this.red.sqrt(this)},G.prototype.redInvm=function(){return Z(this.red,"redInvm works only with red numbers"),this.red._verify1(this),this.red.invm(this)},G.prototype.redNeg=function(){return Z(this.red,"redNeg works only with red numbers"),this.red._verify1(this),this.red.neg(this)},G.prototype.redPow=function(H){return Z(this.red&&!H.red,"redPow(normalNum)"),this.red._verify1(this),this.red.pow(this,H)};var E={k256:null,p224:null,p192:null,p25519:null};function N(j,H){this.name=j,this.p=new G(H,16),this.n=this.p.bitLength(),this.k=new G(1).iushln(this.n).isub(this.p),this.tmp=this._tmp()}N.prototype._tmp=function(){var H=new G(null);return H.words=Array(Math.ceil(this.n/13)),H},N.prototype.ireduce=function(H){var V=H,K;do this.split(V,this.tmp),V=this.imulK(V),V=V.iadd(this.tmp),K=V.bitLength();while(K>this.n);var _=K<this.n?-1:V.ucmp(this.p);if(_===0)V.words[0]=0,V.length=1;else if(_>0)V.isub(this.p);else if(V.strip!==void 0)V.strip();else V._strip();return V},N.prototype.split=function(H,V){H.iushrn(this.n,0,V)},N.prototype.imulK=function(H){return H.imul(this.k)};function h(){N.call(this,"k256","ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff fffffffe fffffc2f")}X(h,N),h.prototype.split=function(H,V){var K=4194303,_=Math.min(H.length,9);for(var I=0;I<_;I++)V.words[I]=H.words[I];if(V.length=_,H.length<=9){H.words[0]=0,H.length=1;return}var P=H.words[9];V.words[V.length++]=P&K;for(I=10;I<H.length;I++){var S=H.words[I]|0;H.words[I-10]=(S&K)<<4|P>>>22,P=S}if(P>>>=22,H.words[I-10]=P,P===0&&H.length>10)H.length-=10;else H.length-=9},h.prototype.imulK=function(H){H.words[H.length]=0,H.words[H.length+1]=0,H.length+=2;var V=0;for(var K=0;K<H.length;K++){var _=H.words[K]|0;V+=_*977,H.words[K]=V&67108863,V=_*64+(V/67108864|0)}if(H.words[H.length-1]===0){if(H.length--,H.words[H.length-1]===0)H.length--}return H};function v(){N.call(this,"p224","ffffffff ffffffff ffffffff ffffffff 00000000 00000000 00000001")}X(v,N);function p(){N.call(this,"p192","ffffffff ffffffff ffffffff fffffffe ffffffff ffffffff")}X(p,N);function i(){N.call(this,"25519","7fffffffffffffff ffffffffffffffff ffffffffffffffff ffffffffffffffed")}X(i,N),i.prototype.imulK=function(H){var V=0;for(var K=0;K<H.length;K++){var _=(H.words[K]|0)*19+V,I=_&67108863;_>>>=26,H.words[K]=I,V=_}if(V!==0)H.words[H.length++]=V;return H},G._prime=function(H){if(E[H])return E[H];var V;if(H==="k256")V=new h;else if(H==="p224")V=new v;else if(H==="p192")V=new p;else if(H==="p25519")V=new i;else throw Error("Unknown prime "+H);return E[H]=V,V};function l(j){if(typeof j==="string"){var H=G._prime(j);this.m=H.p,this.prime=H}else Z(j.gtn(1),"modulus must be greater than 1"),this.m=j,this.prime=null}l.prototype._verify1=function(H){Z(H.negative===0,"red works only with positives"),Z(H.red,"red works only with red numbers")},l.prototype._verify2=function(H,V){Z((H.negative|V.negative)===0,"red works only with positives"),Z(H.red&&H.red===V.red,"red works only with red numbers")},l.prototype.imod=function(H){if(this.prime)return this.prime.ireduce(H)._forceRed(this);return H.umod(this.m)._forceRed(this)},l.prototype.neg=function(H){if(H.isZero())return H.clone();return this.m.sub(H)._forceRed(this)},l.prototype.add=function(H,V){this._verify2(H,V);var K=H.add(V);if(K.cmp(this.m)>=0)K.isub(this.m);return K._forceRed(this)},l.prototype.iadd=function(H,V){this._verify2(H,V);var K=H.iadd(V);if(K.cmp(this.m)>=0)K.isub(this.m);return K},l.prototype.sub=function(H,V){this._verify2(H,V);var K=H.sub(V);if(K.cmpn(0)<0)K.iadd(this.m);return K._forceRed(this)},l.prototype.isub=function(H,V){this._verify2(H,V);var K=H.isub(V);if(K.cmpn(0)<0)K.iadd(this.m);return K},l.prototype.shl=function(H,V){return this._verify1(H),this.imod(H.ushln(V))},l.prototype.imul=function(H,V){return this._verify2(H,V),this.imod(H.imul(V))},l.prototype.mul=function(H,V){return this._verify2(H,V),this.imod(H.mul(V))},l.prototype.isqr=function(H){return this.imul(H,H.clone())},l.prototype.sqr=function(H){return this.mul(H,H)},l.prototype.sqrt=function(H){if(H.isZero())return H.clone();var V=this.m.andln(3);if(Z(V%2===1),V===3){var K=this.m.add(new G(1)).iushrn(2);return this.pow(H,K)}var _=this.m.subn(1),I=0;while(!_.isZero()&&_.andln(1)===0)I++,_.iushrn(1);Z(!_.isZero());var P=new G(1).toRed(this),S=P.redNeg(),F=this.m.subn(1).iushrn(1),U=this.m.bitLength();U=new G(2*U*U).toRed(this);while(this.pow(U,F).cmp(S)!==0)U.redIAdd(S);var R=this.pow(U,_),k=this.pow(H,_.addn(1).iushrn(1)),f=this.pow(H,_),y=I;while(f.cmp(P)!==0){var u=f;for(var r=0;u.cmp(P)!==0;r++)u=u.redSqr();Z(r<y);var e=this.pow(R,new G(1).iushln(y-r-1));k=k.redMul(e),R=e.redSqr(),f=f.redMul(R),y=r}return k},l.prototype.invm=function(H){var V=H._invmp(this.m);if(V.negative!==0)return V.negative=0,this.imod(V).redNeg();else return this.imod(V)},l.prototype.pow=function(H,V){if(V.isZero())return new G(1).toRed(this);if(V.cmpn(1)===0)return H.clone();var K=4,_=Array(1<<K);_[0]=new G(1).toRed(this),_[1]=H;for(var I=2;I<_.length;I++)_[I]=this.mul(_[I-1],H);var P=_[0],S=0,F=0,U=V.bitLength()%26;if(U===0)U=26;for(I=V.length-1;I>=0;I--){var R=V.words[I];for(var k=U-1;k>=0;k--){var f=R>>k&1;if(P!==_[0])P=this.sqr(P);if(f===0&&S===0){F=0;continue}if(S<<=1,S|=f,F++,F!==K&&(I!==0||k!==0))continue;P=this.mul(P,_[S]),F=0,S=0}U=26}return P},l.prototype.convertTo=function(H){var V=H.umod(this.m);return V===H?V.clone():V},l.prototype.convertFrom=function(H){var V=H.clone();return V.red=null,V},G.mont=function(H){return new u0(H)};function u0(j){if(l.call(this,j),this.shift=this.m.bitLength(),this.shift%26!==0)this.shift+=26-this.shift%26;this.r=new G(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)}X(u0,l),u0.prototype.convertTo=function(H){return this.imod(H.ushln(this.shift))},u0.prototype.convertFrom=function(H){var V=this.imod(H.mul(this.rinv));return V.red=null,V},u0.prototype.imul=function(H,V){if(H.isZero()||V.isZero())return H.words[0]=0,H.length=1,H;var K=H.imul(V),_=K.maskn(this.shift).mul(this.minv).imaskn(this.shift).mul(this.m),I=K.isub(_).iushrn(this.shift),P=I;if(I.cmp(this.m)>=0)P=I.isub(this.m);else if(I.cmpn(0)<0)P=I.iadd(this.m);return P._forceRed(this)},u0.prototype.mul=function(H,V){if(H.isZero()||V.isZero())return new G(0)._forceRed(this);var K=H.mul(V),_=K.maskn(this.shift).mul(this.minv).imaskn(this.shift).mul(this.m),I=K.isub(_).iushrn(this.shift),P=I;if(I.cmp(this.m)>=0)P=I.isub(this.m);else if(I.cmpn(0)<0)P=I.iadd(this.m);return P._forceRed(this)},u0.prototype.invm=function(H){var V=this.imod(H._invmp(this.m).mul(this.r2));return V._forceRed(this)}})(typeof WG>"u"||WG,s1)});var o1=o((M7,QG)=>{if(typeof Object.create==="function")QG.exports=function(J,Z){if(Z)J.super_=Z,J.prototype=Object.create(Z.prototype,{constructor:{value:J,enumerable:!1,writable:!0,configurable:!0}})};else QG.exports=function(J,Z){if(Z){J.super_=Z;var X=function(){};X.prototype=Z.prototype,J.prototype=new X,J.prototype.constructor=J}}});var L$=o((_7,UG)=>{try{if(gJ=A$("util"),typeof gJ.inherits!=="function")throw"";UG.exports=gJ.inherits}catch($){UG.exports=o1()}var gJ});var bJ=o((A7,l1)=>{var hJ=A$("buffer"),m$=hJ.Buffer,t0={},a0;for(a0 in hJ){if(!hJ.hasOwnProperty(a0))continue;if(a0==="SlowBuffer"||a0==="Buffer")continue;t0[a0]=hJ[a0]}var d$=t0.Buffer={};for(a0 in m$){if(!m$.hasOwnProperty(a0))continue;if(a0==="allocUnsafe"||a0==="allocUnsafeSlow")continue;d$[a0]=m$[a0]}t0.Buffer.prototype=m$.prototype;if(!d$.from||d$.from===Uint8Array.from)d$.from=function($,J,Z){if(typeof $==="number")throw TypeError('The "value" argument must not be of type number. Received type '+typeof $);if($&&typeof $.length>"u")throw TypeError("The first argument must be one of type string, Buffer, ArrayBuffer, Array, or Array-like Object. Received type "+typeof $);return m$($,J,Z)};if(!d$.alloc)d$.alloc=function($,J,Z){if(typeof $!=="number")throw TypeError('The "size" argument must be of type number. Received type '+typeof $);if($<0||$>=2147483648)throw RangeError('The value "'+$+'" is invalid for option "size"');var X=m$($);if(!J||J.length===0)X.fill(0);else if(typeof Z==="string")X.fill(J,Z);else X.fill(J);return X};if(!t0.kStringMaxLength)try{t0.kStringMaxLength=process.binding("buffer").kStringMaxLength}catch($){}if(!t0.constants){if(t0.constants={MAX_LENGTH:t0.kMaxLength},t0.kStringMaxLength)t0.constants.MAX_STRING_LENGTH=t0.kStringMaxLength}l1.exports=t0});var cJ=o((O9)=>{var z9=L$();function e0($){this._reporterState={obj:null,path:[],options:$||{},errors:[]}}O9.Reporter=e0;e0.prototype.isError=function(J){return J instanceof s$};e0.prototype.save=function(){let J=this._reporterState;return{obj:J.obj,pathLen:J.path.length}};e0.prototype.restore=function(J){let Z=this._reporterState;Z.obj=J.obj,Z.path=Z.path.slice(0,J.pathLen)};e0.prototype.enterKey=function(J){return this._reporterState.path.push(J)};e0.prototype.exitKey=function(J){let Z=this._reporterState;Z.path=Z.path.slice(0,J-1)};e0.prototype.leaveKey=function(J,Z,X){let G=this._reporterState;if(this.exitKey(J),G.obj!==null)G.obj[Z]=X};e0.prototype.path=function(){return this._reporterState.path.join("/")};e0.prototype.enterObject=function(){let J=this._reporterState,Z=J.obj;return J.obj={},Z};e0.prototype.leaveObject=function(J){let Z=this._reporterState,X=Z.obj;return Z.obj=J,X};e0.prototype.error=function(J){let Z,X=this._reporterState,G=J instanceof s$;if(G)Z=J;else Z=new s$(X.path.map(function(Y){return"["+JSON.stringify(Y)+"]"}).join(""),J.message||J,J.stack);if(!X.options.partial)throw Z;if(!G)X.errors.push(Z);return Z};e0.prototype.wrapResult=function(J){let Z=this._reporterState;if(!Z.options.partial)return J;return{result:this.isError(J)?null:J,errors:Z.errors}};function s$($,J){this.path=$,this.rethrow(J)}z9(s$,Error);s$.prototype.rethrow=function(J){if(this.message=J+" at: "+(this.path||"(shallow)"),Error.captureStackTrace)Error.captureStackTrace(this,s$);if(!this.stack)try{throw Error(this.message)}catch(Z){this.stack=Z.stack}return this}});var r$=o((_9)=>{var M9=L$(),pJ=cJ().Reporter,o$=bJ().Buffer;function $$($,J){if(pJ.call(this,J),!o$.isBuffer($)){this.error("Input not Buffer");return}this.base=$,this.offset=0,this.length=$.length}M9($$,pJ);_9.DecoderBuffer=$$;$$.isDecoderBuffer=function(J){if(J instanceof $$)return!0;return typeof J==="object"&&o$.isBuffer(J.base)&&J.constructor.name==="DecoderBuffer"&&typeof J.offset==="number"&&typeof J.length==="number"&&typeof J.save==="function"&&typeof J.restore==="function"&&typeof J.isEmpty==="function"&&typeof J.readUInt8==="function"&&typeof J.skip==="function"&&typeof J.raw==="function"};$$.prototype.save=function(){return{offset:this.offset,reporter:pJ.prototype.save.call(this)}};$$.prototype.restore=function(J){let Z=new $$(this.base);return Z.offset=J.offset,Z.length=this.offset,this.offset=J.offset,pJ.prototype.restore.call(this,J.reporter),Z};$$.prototype.isEmpty=function(){return this.offset===this.length};$$.prototype.readUInt8=function(J){if(this.offset+1<=this.length)return this.base.readUInt8(this.offset++,!0);else return this.error(J||"DecoderBuffer overrun")};$$.prototype.skip=function(J,Z){if(!(this.offset+J<=this.length))return this.error(Z||"DecoderBuffer overrun");let X=new $$(this.base);return X._reporterState=this._reporterState,X.offset=this.offset,X.length=this.offset+J,this.offset+=J,X};$$.prototype.raw=function(J){return this.base.slice(J?J.offset:this.offset,this.length)};function l$($,J){if(Array.isArray($))this.length=0,this.value=$.map(function(Z){if(!l$.isEncoderBuffer(Z))Z=new l$(Z,J);return this.length+=Z.length,Z},this);else if(typeof $==="number"){if(!(0<=$&&$<=255))return J.error("non-byte EncoderBuffer value");this.value=$,this.length=1}else if(typeof $==="string")this.value=$,this.length=o$.byteLength($);else if(o$.isBuffer($))this.value=$,this.length=$.length;else return J.error("Unsupported type: "+typeof $)}_9.EncoderBuffer=l$;l$.isEncoderBuffer=function(J){if(J instanceof l$)return!0;return typeof J==="object"&&J.constructor.name==="EncoderBuffer"&&typeof J.length==="number"&&typeof J.join==="function"};l$.prototype.join=function(J,Z){if(!J)J=o$.alloc(this.length);if(!Z)Z=0;if(this.length===0)return J;if(Array.isArray(this.value))this.value.forEach(function(X){X.join(J,Z),Z+=X.length});else{if(typeof this.value==="number")J[Z]=this.value;else if(typeof this.value==="string")J.write(this.value,Z);else if(o$.isBuffer(this.value))this.value.copy(J,Z);Z+=this.length}return J}});var t1=o((I7,i1)=>{i1.exports=r1;function r1($,J){if(!$)throw Error(J||"Assertion failed")}r1.equal=function(J,Z,X){if(J!=Z)throw Error(X||"Assertion failed: "+J+" != "+Z)}});var uJ=o((j7,e1)=>{var R9=cJ().Reporter,I9=r$().EncoderBuffer,j9=r$().DecoderBuffer,o0=t1(),a1=["seq","seqof","set","setof","objid","bool","gentime","utctime","null_","enum","int","objDesc","bitstr","bmpstr","charstr","genstr","graphstr","ia5str","iso646str","numstr","octstr","printstr","t61str","unistr","utf8str","videostr"],q9=["key","obj","use","optional","explicit","implicit","def","choice","any","contains"].concat(a1),B9=["_peekTag","_decodeTag","_use","_decodeStr","_decodeObjid","_decodeTime","_decodeNull","_decodeInt","_decodeBool","_decodeList","_encodeComposite","_encodeStr","_encodeObjid","_encodeTime","_encodeNull","_encodeInt","_encodeBool"];function t($,J,Z){let X={};if(this._baseState=X,X.name=Z,X.enc=$,X.parent=J||null,X.children=null,X.tag=null,X.args=null,X.reverseArgs=null,X.choice=null,X.optional=!1,X.any=!1,X.obj=!1,X.use=null,X.useDecoder=null,X.key=null,X.default=null,X.explicit=null,X.implicit=null,X.contains=null,!X.parent)X.children=[],this._wrap()}e1.exports=t;var P9=["enc","parent","children","tag","args","reverseArgs","choice","optional","any","obj","use","alteredUse","key","default","explicit","implicit","contains"];t.prototype.clone=function(){let J=this._baseState,Z={};P9.forEach(function(G){Z[G]=J[G]});let X=new this.constructor(Z.parent);return X._baseState=Z,X};t.prototype._wrap=function(){let J=this._baseState;q9.forEach(function(Z){this[Z]=function(){let G=new this.constructor(this);return J.children.push(G),G[Z].apply(G,arguments)}},this)};t.prototype._init=function(J){let Z=this._baseState;o0(Z.parent===null),J.call(this),Z.children=Z.children.filter(function(X){return X._baseState.parent===this},this),o0.equal(Z.children.length,1,"Root node can have only one child")};t.prototype._useArgs=function(J){let Z=this._baseState,X=J.filter(function(G){return G instanceof this.constructor},this);if(J=J.filter(function(G){return!(G instanceof this.constructor)},this),X.length!==0)o0(Z.children===null),Z.children=X,X.forEach(function(G){G._baseState.parent=this},this);if(J.length!==0)o0(Z.args===null),Z.args=J,Z.reverseArgs=J.map(function(G){if(typeof G!=="object"||G.constructor!==Object)return G;let Y={};return Object.keys(G).forEach(function(W){if(W==(W|0))W|=0;let Q=G[W];Y[Q]=W}),Y})};B9.forEach(function($){t.prototype[$]=function(){let Z=this._baseState;throw Error($+" not implemented for encoding: "+Z.enc)}});a1.forEach(function($){t.prototype[$]=function(){let Z=this._baseState,X=Array.prototype.slice.call(arguments);return o0(Z.tag===null),Z.tag=$,this._useArgs(X),this}});t.prototype.use=function(J){o0(J);let Z=this._baseState;return o0(Z.use===null),Z.use=J,this};t.prototype.optional=function(){let J=this._baseState;return J.optional=!0,this};t.prototype.def=function(J){let Z=this._baseState;return o0(Z.default===null),Z.default=J,Z.optional=!0,this};t.prototype.explicit=function(J){let Z=this._baseState;return o0(Z.explicit===null&&Z.implicit===null),Z.explicit=J,this};t.prototype.implicit=function(J){let Z=this._baseState;return o0(Z.explicit===null&&Z.implicit===null),Z.implicit=J,this};t.prototype.obj=function(){let J=this._baseState,Z=Array.prototype.slice.call(arguments);if(J.obj=!0,Z.length!==0)this._useArgs(Z);return this};t.prototype.key=function(J){let Z=this._baseState;return o0(Z.key===null),Z.key=J,this};t.prototype.any=function(){let J=this._baseState;return J.any=!0,this};t.prototype.choice=function(J){let Z=this._baseState;return o0(Z.choice===null),Z.choice=J,this._useArgs(Object.keys(J).map(function(X){return J[X]})),this};t.prototype.contains=function(J){let Z=this._baseState;return o0(Z.use===null),Z.contains=J,this};t.prototype._decode=function(J,Z){let X=this._baseState;if(X.parent===null)return J.wrapResult(X.children[0]._decode(J,Z));let G=X.default,Y=!0,W=null;if(X.key!==null)W=J.enterKey(X.key);if(X.optional){let z=null;if(X.explicit!==null)z=X.explicit;else if(X.implicit!==null)z=X.implicit;else if(X.tag!==null)z=X.tag;if(z===null&&!X.any){let O=J.save();try{if(X.choice===null)this._decodeGeneric(X.tag,J,Z);else this._decodeChoice(J,Z);Y=!0}catch(M){Y=!1}J.restore(O)}else if(Y=this._peekTag(J,z,X.any),J.isError(Y))return Y}let Q;if(X.obj&&Y)Q=J.enterObject();if(Y){if(X.explicit!==null){let O=this._decodeTag(J,X.explicit);if(J.isError(O))return O;J=O}let z=J.offset;if(X.use===null&&X.choice===null){let O;if(X.any)O=J.save();let M=this._decodeTag(J,X.implicit!==null?X.implicit:X.tag,X.any);if(J.isError(M))return M;if(X.any)G=J.raw(O);else J=M}if(Z&&Z.track&&X.tag!==null)Z.track(J.path(),z,J.length,"tagged");if(Z&&Z.track&&X.tag!==null)Z.track(J.path(),J.offset,J.length,"content");if(X.any);else if(X.choice===null)G=this._decodeGeneric(X.tag,J,Z);else G=this._decodeChoice(J,Z);if(J.isError(G))return G;if(!X.any&&X.choice===null&&X.children!==null)X.children.forEach(function(M){M._decode(J,Z)});if(X.contains&&(X.tag==="octstr"||X.tag==="bitstr")){let O=new j9(G);G=this._getUse(X.contains,J._reporterState.obj)._decode(O,Z)}}if(X.obj&&Y)G=J.leaveObject(Q);if(X.key!==null&&(G!==null||Y===!0))J.leaveKey(W,X.key,G);else if(W!==null)J.exitKey(W);return G};t.prototype._decodeGeneric=function(J,Z,X){let G=this._baseState;if(J==="seq"||J==="set")return null;if(J==="seqof"||J==="setof")return this._decodeList(Z,J,G.args[0],X);else if(/str$/.test(J))return this._decodeStr(Z,J,X);else if(J==="objid"&&G.args)return this._decodeObjid(Z,G.args[0],G.args[1],X);else if(J==="objid")return this._decodeObjid(Z,null,null,X);else if(J==="gentime"||J==="utctime")return this._decodeTime(Z,J,X);else if(J==="null_")return this._decodeNull(Z,X);else if(J==="bool")return this._decodeBool(Z,X);else if(J==="objDesc")return this._decodeStr(Z,J,X);else if(J==="int"||J==="enum")return this._decodeInt(Z,G.args&&G.args[0],X);if(G.use!==null)return this._getUse(G.use,Z._reporterState.obj)._decode(Z,X);else return Z.error("unknown tag: "+J)};t.prototype._getUse=function(J,Z){let X=this._baseState;if(X.useDecoder=this._use(J,Z),o0(X.useDecoder._baseState.parent===null),X.useDecoder=X.useDecoder._baseState.children[0],X.implicit!==X.useDecoder._baseState.implicit)X.useDecoder=X.useDecoder.clone(),X.useDecoder._baseState.implicit=X.implicit;return X.useDecoder};t.prototype._decodeChoice=function(J,Z){let X=this._baseState,G=null,Y=!1;if(Object.keys(X.choice).some(function(W){let Q=J.save(),z=X.choice[W];try{let O=z._decode(J,Z);if(J.isError(O))return!1;G={type:W,value:O},Y=!0}catch(O){return J.restore(Q),!1}return!0},this),!Y)return J.error("Choice not matched");return G};t.prototype._createEncoderBuffer=function(J){return new I9(J,this.reporter)};t.prototype._encode=function(J,Z,X){let G=this._baseState;if(G.default!==null&&G.default===J)return;let Y=this._encodeValue(J,Z,X);if(Y===void 0)return;if(this._skipDefault(Y,Z,X))return;return Y};t.prototype._encodeValue=function(J,Z,X){let G=this._baseState;if(G.parent===null)return G.children[0]._encode(J,Z||new R9);let Y=null;if(this.reporter=Z,G.optional&&J===void 0)if(G.default!==null)J=G.default;else return;let W=null,Q=!1;if(G.any)Y=this._createEncoderBuffer(J);else if(G.choice)Y=this._encodeChoice(J,Z);else if(G.contains)W=this._getUse(G.contains,X)._encode(J,Z),Q=!0;else if(G.children)W=G.children.map(function(z){if(z._baseState.tag==="null_")return z._encode(null,Z,J);if(z._baseState.key===null)return Z.error("Child should have a key");let O=Z.enterKey(z._baseState.key);if(typeof J!=="object")return Z.error("Child expected, but input is not object");let M=z._encode(J[z._baseState.key],Z,J);return Z.leaveKey(O),M},this).filter(function(z){return z}),W=this._createEncoderBuffer(W);else if(G.tag==="seqof"||G.tag==="setof"){if(!(G.args&&G.args.length===1))return Z.error("Too many args for : "+G.tag);if(!Array.isArray(J))return Z.error("seqof/setof, but data is not Array");let z=this.clone();z._baseState.implicit=null,W=this._createEncoderBuffer(J.map(function(O){let M=this._baseState;return this._getUse(M.args[0],J)._encode(O,Z)},z))}else if(G.use!==null)Y=this._getUse(G.use,X)._encode(J,Z);else W=this._encodePrimitive(G.tag,J),Q=!0;if(!G.any&&G.choice===null){let z=G.implicit!==null?G.implicit:G.tag,O=G.implicit===null?"universal":"context";if(z===null){if(G.use===null)Z.error("Tag could be omitted only for .use()")}else if(G.use===null)Y=this._encodeComposite(z,Q,O,W)}if(G.explicit!==null)Y=this._encodeComposite(G.explicit,!1,"context",Y);return Y};t.prototype._encodeChoice=function(J,Z){let X=this._baseState,G=X.choice[J.type];if(!G)o0(!1,J.type+" not found in "+JSON.stringify(Object.keys(X.choice)));return G._encode(J.value,Z)};t.prototype._encodePrimitive=function(J,Z){let X=this._baseState;if(/str$/.test(J))return this._encodeStr(Z,J);else if(J==="objid"&&X.args)return this._encodeObjid(Z,X.reverseArgs[0],X.args[1]);else if(J==="objid")return this._encodeObjid(Z,null,null);else if(J==="gentime"||J==="utctime")return this._encodeTime(Z,J);else if(J==="null_")return this._encodeNull();else if(J==="int"||J==="enum")return this._encodeInt(Z,X.args&&X.reverseArgs[0]);else if(J==="bool")return this._encodeBool(Z);else if(J==="objDesc")return this._encodeStr(Z,J);else throw Error("Unsupported tag: "+J)};t.prototype._isNumstr=function(J){return/^[0-9 ]*$/.test(J)};t.prototype._isPrintstr=function(J){return/^[A-Za-z0-9 '()+,-./:=?]*$/.test(J)}});var nJ=o((L9)=>{function $Y($){let J={};return Object.keys($).forEach(function(Z){if((Z|0)==Z)Z=Z|0;let X=$[Z];J[X]=Z}),J}L9.tagClass={0:"universal",1:"application",2:"context",3:"private"};L9.tagClassByName=$Y(L9.tagClass);L9.tag={0:"end",1:"bool",2:"int",3:"bitstr",4:"octstr",5:"null_",6:"objid",7:"objDesc",8:"external",9:"real",10:"enum",11:"embed",12:"utf8str",13:"relativeOid",16:"seq",17:"set",18:"numstr",19:"printstr",20:"t61str",21:"videostr",22:"ia5str",23:"utctime",24:"gentime",25:"graphstr",26:"iso646str",27:"genstr",28:"unistr",29:"charstr",30:"bmpstr"};L9.tagByName=$Y(L9.tag)});var zG=o((B7,YY)=>{var E9=L$(),K$=bJ().Buffer,GY=uJ(),VG=nJ();function XY($){this.enc="der",this.name=$.name,this.entity=$,this.tree=new Z$,this.tree._init($.body)}YY.exports=XY;XY.prototype.encode=function(J,Z){return this.tree._encode(J,Z).join()};function Z$($){GY.call(this,"der",$)}E9(Z$,GY);Z$.prototype._encodeComposite=function(J,Z,X,G){let Y=w9(J,Z,X,this.reporter);if(G.length<128){let z=K$.alloc(2);return z[0]=Y,z[1]=G.length,this._createEncoderBuffer([z,G])}let W=1;for(let z=G.length;z>=256;z>>=8)W++;let Q=K$.alloc(2+W);Q[0]=Y,Q[1]=128|W;for(let z=1+W,O=G.length;O>0;z--,O>>=8)Q[z]=O&255;return this._createEncoderBuffer([Q,G])};Z$.prototype._encodeStr=function(J,Z){if(Z==="bitstr")return this._createEncoderBuffer([J.unused|0,J.data]);else if(Z==="bmpstr"){let X=K$.alloc(J.length*2);for(let G=0;G<J.length;G++)X.writeUInt16BE(J.charCodeAt(G),G*2);return this._createEncoderBuffer(X)}else if(Z==="numstr"){if(!this._isNumstr(J))return this.reporter.error("Encoding of string type: numstr supports only digits and space");return this._createEncoderBuffer(J)}else if(Z==="printstr"){if(!this._isPrintstr(J))return this.reporter.error("Encoding of string type: printstr supports only latin upper and lower case letters, digits, space, apostrophe, left and rigth parenthesis, plus sign, comma, hyphen, dot, slash, colon, equal sign, question mark");return this._createEncoderBuffer(J)}else if(/str$/.test(Z))return this._createEncoderBuffer(J);else if(Z==="objDesc")return this._createEncoderBuffer(J);else return this.reporter.error("Encoding of string type: "+Z+" unsupported")};Z$.prototype._encodeObjid=function(J,Z,X){if(typeof J==="string"){if(!Z)return this.reporter.error("string objid given, but no values map found");if(!Z.hasOwnProperty(J))return this.reporter.error("objid not found in values map");J=Z[J].split(/[\s.]+/g);for(let Q=0;Q<J.length;Q++)J[Q]|=0}else if(Array.isArray(J)){J=J.slice();for(let Q=0;Q<J.length;Q++)J[Q]|=0}if(!Array.isArray(J))return this.reporter.error("objid() should be either array or string, got: "+JSON.stringify(J));if(!X){if(J[1]>=40)return this.reporter.error("Second objid identifier OOB");J.splice(0,2,J[0]*40+J[1])}let G=0;for(let Q=0;Q<J.length;Q++){let z=J[Q];for(G++;z>=128;z>>=7)G++}let Y=K$.alloc(G),W=Y.length-1;for(let Q=J.length-1;Q>=0;Q--){let z=J[Q];Y[W--]=z&127;while((z>>=7)>0)Y[W--]=128|z&127}return this._createEncoderBuffer(Y)};function J$($){if($<10)return"0"+$;else return $}Z$.prototype._encodeTime=function(J,Z){let X,G=new Date(J);if(Z==="gentime")X=[J$(G.getUTCFullYear()),J$(G.getUTCMonth()+1),J$(G.getUTCDate()),J$(G.getUTCHours()),J$(G.getUTCMinutes()),J$(G.getUTCSeconds()),"Z"].join("");else if(Z==="utctime")X=[J$(G.getUTCFullYear()%100),J$(G.getUTCMonth()+1),J$(G.getUTCDate()),J$(G.getUTCHours()),J$(G.getUTCMinutes()),J$(G.getUTCSeconds()),"Z"].join("");else this.reporter.error("Encoding "+Z+" time is not supported yet");return this._encodeStr(X,"octstr")};Z$.prototype._encodeNull=function(){return this._createEncoderBuffer("")};Z$.prototype._encodeInt=function(J,Z){if(typeof J==="string"){if(!Z)return this.reporter.error("String int or enum given, but no values map");if(!Z.hasOwnProperty(J))return this.reporter.error("Values map doesn't contain: "+JSON.stringify(J));J=Z[J]}if(typeof J!=="number"&&!K$.isBuffer(J)){let Y=J.toArray();if(!J.sign&&Y[0]&128)Y.unshift(0);J=K$.from(Y)}if(K$.isBuffer(J)){let Y=J.length;if(J.length===0)Y++;let W=K$.alloc(Y);if(J.copy(W),J.length===0)W[0]=0;return this._createEncoderBuffer(W)}if(J<128)return this._createEncoderBuffer(J);if(J<256)return this._createEncoderBuffer([0,J]);let X=1;for(let Y=J;Y>=256;Y>>=8)X++;let G=Array(X);for(let Y=G.length-1;Y>=0;Y--)G[Y]=J&255,J>>=8;if(G[0]&128)G.unshift(0);return this._createEncoderBuffer(K$.from(G))};Z$.prototype._encodeBool=function(J){return this._createEncoderBuffer(J?255:0)};Z$.prototype._use=function(J,Z){if(typeof J==="function")J=J(Z);return J._getEncoder("der").tree};Z$.prototype._skipDefault=function(J,Z,X){let G=this._baseState,Y;if(G.default===null)return!1;let W=J.join();if(G.defaultBuffer===void 0)G.defaultBuffer=this._encodeValue(G.default,Z,X).join();if(W.length!==G.defaultBuffer.length)return!1;for(Y=0;Y<W.length;Y++)if(W[Y]!==G.defaultBuffer[Y])return!1;return!0};function w9($,J,Z,X){let G;if($==="seqof")$="seq";else if($==="setof")$="set";if(VG.tagByName.hasOwnProperty($))G=VG.tagByName[$];else if(typeof $==="number"&&($|0)===$)G=$;else return X.error("Unknown tag: "+$);if(G>=31)return X.error("Multi-octet tag encoding unsupported");if(!J)G|=32;return G|=VG.tagClassByName[Z||"universal"]<<6,G}});var HY=o((P7,WY)=>{var T9=L$(),OG=zG();function KG($){OG.call(this,$),this.enc="pem"}T9(KG,OG);WY.exports=KG;KG.prototype.encode=function(J,Z){let G=OG.prototype.encode.call(this,J).toString("base64"),Y=["-----BEGIN "+Z.label+"-----"];for(let W=0;W<G.length;W+=64)Y.push(G.slice(W,W+64));return Y.push("-----END "+Z.label+"-----"),Y.join(`
|
|
6
|
-
`)}});var MG=o((UY)=>{var QY=UY;QY.der=zG();QY.pem=HY()});var AG=o((S7,_Y)=>{var N9=L$(),v9=HG(),VY=r$().DecoderBuffer,OY=uJ(),zY=nJ();function KY($){this.enc="der",this.name=$.name,this.entity=$,this.tree=new r0,this.tree._init($.body)}_Y.exports=KY;KY.prototype.decode=function(J,Z){if(!VY.isDecoderBuffer(J))J=new VY(J,Z);return this.tree._decode(J,Z)};function r0($){OY.call(this,"der",$)}N9(r0,OY);r0.prototype._peekTag=function(J,Z,X){if(J.isEmpty())return!1;let G=J.save(),Y=_G(J,'Failed to peek tag: "'+Z+'"');if(J.isError(Y))return Y;return J.restore(G),Y.tag===Z||Y.tagStr===Z||Y.tagStr+"of"===Z||X};r0.prototype._decodeTag=function(J,Z,X){let G=_G(J,'Failed to decode tag of "'+Z+'"');if(J.isError(G))return G;let Y=MY(J,G.primitive,'Failed to get length of "'+Z+'"');if(J.isError(Y))return Y;if(!X&&G.tag!==Z&&G.tagStr!==Z&&G.tagStr+"of"!==Z)return J.error('Failed to match tag: "'+Z+'"');if(G.primitive||Y!==null)return J.skip(Y,'Failed to match body of: "'+Z+'"');let W=J.save(),Q=this._skipUntilEnd(J,'Failed to skip indefinite length body: "'+this.tag+'"');if(J.isError(Q))return Q;return Y=J.offset-W.offset,J.restore(W),J.skip(Y,'Failed to match body of: "'+Z+'"')};r0.prototype._skipUntilEnd=function(J,Z){for(;;){let X=_G(J,Z);if(J.isError(X))return X;let G=MY(J,X.primitive,Z);if(J.isError(G))return G;let Y;if(X.primitive||G!==null)Y=J.skip(G);else Y=this._skipUntilEnd(J,Z);if(J.isError(Y))return Y;if(X.tagStr==="end")break}};r0.prototype._decodeList=function(J,Z,X,G){let Y=[];while(!J.isEmpty()){let W=this._peekTag(J,"end");if(J.isError(W))return W;let Q=X.decode(J,"der",G);if(J.isError(Q)&&W)break;Y.push(Q)}return Y};r0.prototype._decodeStr=function(J,Z){if(Z==="bitstr"){let X=J.readUInt8();if(J.isError(X))return X;return{unused:X,data:J.raw()}}else if(Z==="bmpstr"){let X=J.raw();if(X.length%2===1)return J.error("Decoding of string type: bmpstr length mismatch");let G="";for(let Y=0;Y<X.length/2;Y++)G+=String.fromCharCode(X.readUInt16BE(Y*2));return G}else if(Z==="numstr"){let X=J.raw().toString("ascii");if(!this._isNumstr(X))return J.error("Decoding of string type: numstr unsupported characters");return X}else if(Z==="octstr")return J.raw();else if(Z==="objDesc")return J.raw();else if(Z==="printstr"){let X=J.raw().toString("ascii");if(!this._isPrintstr(X))return J.error("Decoding of string type: printstr unsupported characters");return X}else if(/str$/.test(Z))return J.raw().toString();else return J.error("Decoding of string type: "+Z+" unsupported")};r0.prototype._decodeObjid=function(J,Z,X){let G,Y=[],W=0,Q=0;while(!J.isEmpty())if(Q=J.readUInt8(),W<<=7,W|=Q&127,(Q&128)===0)Y.push(W),W=0;if(Q&128)Y.push(W);let z=Y[0]/40|0,O=Y[0]%40;if(X)G=Y;else G=[z,O].concat(Y.slice(1));if(Z){let M=Z[G.join(" ")];if(M===void 0)M=Z[G.join(".")];if(M!==void 0)G=M}return G};r0.prototype._decodeTime=function(J,Z){let X=J.raw().toString(),G,Y,W,Q,z,O;if(Z==="gentime")G=X.slice(0,4)|0,Y=X.slice(4,6)|0,W=X.slice(6,8)|0,Q=X.slice(8,10)|0,z=X.slice(10,12)|0,O=X.slice(12,14)|0;else if(Z==="utctime")if(G=X.slice(0,2)|0,Y=X.slice(2,4)|0,W=X.slice(4,6)|0,Q=X.slice(6,8)|0,z=X.slice(8,10)|0,O=X.slice(10,12)|0,G<70)G=2000+G;else G=1900+G;else return J.error("Decoding "+Z+" time is not supported yet");return Date.UTC(G,Y-1,W,Q,z,O,0)};r0.prototype._decodeNull=function(){return null};r0.prototype._decodeBool=function(J){let Z=J.readUInt8();if(J.isError(Z))return Z;else return Z!==0};r0.prototype._decodeInt=function(J,Z){let X=J.raw(),G=new v9(X);if(Z)G=Z[G.toString(10)]||G;return G};r0.prototype._use=function(J,Z){if(typeof J==="function")J=J(Z);return J._getDecoder("der").tree};function _G($,J){let Z=$.readUInt8(J);if($.isError(Z))return Z;let X=zY.tagClass[Z>>6],G=(Z&32)===0;if((Z&31)===31){let W=Z;Z=0;while((W&128)===128){if(W=$.readUInt8(J),$.isError(W))return W;Z<<=7,Z|=W&127}}else Z&=31;let Y=zY.tag[Z];return{cls:X,primitive:G,tag:Z,tagStr:Y}}function MY($,J,Z){let X=$.readUInt8(Z);if($.isError(X))return X;if(!J&&X===128)return null;if((X&128)===0)return X;let G=X&127;if(G>4)return $.error("length octect is too long");X=0;for(let Y=0;Y<G;Y++){X<<=8;let W=$.readUInt8(Z);if($.isError(W))return W;X|=W}return X}});var FY=o((C7,AY)=>{var D9=L$(),k9=bJ().Buffer,FG=AG();function RG($){FG.call(this,$),this.enc="pem"}D9(RG,FG);AY.exports=RG;RG.prototype.decode=function(J,Z){let X=J.toString().split(/[\r\n]+/g),G=Z.label.toUpperCase(),Y=/^-----(BEGIN|END) ([^-]+)-----$/,W=-1,Q=-1;for(let M=0;M<X.length;M++){let A=X[M].match(Y);if(A===null)continue;if(A[2]!==G)continue;if(W===-1){if(A[1]!=="BEGIN")break;W=M}else{if(A[1]!=="END")break;Q=M;break}}if(W===-1||Q===-1)throw Error("PEM section not found for: "+G);let z=X.slice(W+1,Q).join("");z.replace(/[^a-z0-9+/=]+/gi,"");let O=k9.from(z,"base64");return FG.prototype.decode.call(this,O,Z)}});var IG=o((IY)=>{var RY=IY;RY.der=AG();RY.pem=FY()});var qY=o((jY)=>{var f9=MG(),y9=IG(),x9=L$(),g9=jY;g9.define=function(J,Z){return new i$(J,Z)};function i$($,J){this.name=$,this.body=J,this.decoders={},this.encoders={}}i$.prototype._createNamed=function(J){let Z=this.name;function X(G){this._initNamed(G,Z)}return x9(X,J),X.prototype._initNamed=function(Y,W){J.call(this,Y,W)},new X(this)};i$.prototype._getDecoder=function(J){if(J=J||"der",!this.decoders.hasOwnProperty(J))this.decoders[J]=this._createNamed(y9[J]);return this.decoders[J]};i$.prototype.decode=function(J,Z,X){return this._getDecoder(Z).decode(J,X)};i$.prototype._getEncoder=function(J){if(J=J||"der",!this.encoders.hasOwnProperty(J))this.encoders[J]=this._createNamed(f9[J]);return this.encoders[J]};i$.prototype.encode=function(J,Z,X){return this._getEncoder(Z).encode(J,X)}});var PY=o((BY)=>{var mJ=BY;mJ.Reporter=cJ().Reporter;mJ.DecoderBuffer=r$().DecoderBuffer;mJ.EncoderBuffer=r$().EncoderBuffer;mJ.Node=uJ()});var CY=o((SY)=>{var LY=SY;LY._reverse=function(J){let Z={};return Object.keys(J).forEach(function(X){if((X|0)==X)X=X|0;let G=J[X];Z[G]=X}),Z};LY.der=nJ()});var wY=o((EY)=>{var t$=EY;t$.bignum=HG();t$.define=qY().define;t$.base=PY();t$.constants=CY();t$.decoders=IG();t$.encoders=MG()});var vY=o((jG,NY)=>{/*! safe-buffer. MIT License. Feross Aboukhadijeh <https://feross.org/opensource> */var dJ=A$("buffer"),V$=dJ.Buffer;function TY($,J){for(var Z in $)J[Z]=$[Z]}if(V$.from&&V$.alloc&&V$.allocUnsafe&&V$.allocUnsafeSlow)NY.exports=dJ;else TY(dJ,jG),jG.Buffer=D$;function D$($,J,Z){return V$($,J,Z)}D$.prototype=Object.create(V$.prototype);TY(V$,D$);D$.from=function($,J,Z){if(typeof $==="number")throw TypeError("Argument must not be a number");return V$($,J,Z)};D$.alloc=function($,J,Z){if(typeof $!=="number")throw TypeError("Argument must be a number");var X=V$($);if(J!==void 0)if(typeof Z==="string")X.fill(J,Z);else X.fill(J);else X.fill(0);return X};D$.allocUnsafe=function($){if(typeof $!=="number")throw TypeError("Argument must be a number");return V$($)};D$.allocUnsafeSlow=function($){if(typeof $!=="number")throw TypeError("Argument must be a number");return dJ.SlowBuffer($)}});var kY=o((D7,DY)=>{function qG($){var J=($/8|0)+($%8===0?0:1);return J}var h9={ES256:qG(256),ES384:qG(384),ES512:qG(521)};function b9($){var J=h9[$];if(J)return J;throw Error('Unknown algorithm "'+$+'"')}DY.exports=b9});var cY=o((k7,bY)=>{var sJ=vY().Buffer,yY=kY(),oJ=128,xY=0,c9=32,p9=16,u9=2,gY=p9|c9|xY<<6,lJ=u9|xY<<6;function n9($){return $.replace(/=/g,"").replace(/\+/g,"-").replace(/\//g,"_")}function hY($){if(sJ.isBuffer($))return $;else if(typeof $==="string")return sJ.from($,"base64");throw TypeError("ECDSA signature must be a Base64 string or a Buffer")}function m9($,J){$=hY($);var Z=yY(J),X=Z+1,G=$.length,Y=0;if($[Y++]!==gY)throw Error('Could not find expected "seq"');var W=$[Y++];if(W===(oJ|1))W=$[Y++];if(G-Y<W)throw Error('"seq" specified length of "'+W+'", only "'+(G-Y)+'" remaining');if($[Y++]!==lJ)throw Error('Could not find expected "int" for "r"');var Q=$[Y++];if(G-Y-2<Q)throw Error('"r" specified length of "'+Q+'", only "'+(G-Y-2)+'" available');if(X<Q)throw Error('"r" specified length of "'+Q+'", max of "'+X+'" is acceptable');var z=Y;if(Y+=Q,$[Y++]!==lJ)throw Error('Could not find expected "int" for "s"');var O=$[Y++];if(G-Y!==O)throw Error('"s" specified length of "'+O+'", expected "'+(G-Y)+'"');if(X<O)throw Error('"s" specified length of "'+O+'", max of "'+X+'" is acceptable');var M=Y;if(Y+=O,Y!==G)throw Error('Expected to consume entire buffer, but "'+(G-Y)+'" bytes remain');var A=Z-Q,B=Z-O,L=sJ.allocUnsafe(A+Q+B+O);for(Y=0;Y<A;++Y)L[Y]=0;$.copy(L,Y,z+Math.max(-A,0),z+Q),Y=Z;for(var C=Y;Y<C+B;++Y)L[Y]=0;return $.copy(L,Y,M+Math.max(-B,0),M+O),L=L.toString("base64"),L=n9(L),L}function fY($,J,Z){var X=0;while(J+X<Z&&$[J+X]===0)++X;var G=$[J+X]>=oJ;if(G)--X;return X}function d9($,J){$=hY($);var Z=yY(J),X=$.length;if(X!==Z*2)throw TypeError('"'+J+'" signatures must be "'+Z*2+'" bytes, saw "'+X+'"');var G=fY($,0,Z),Y=fY($,Z,$.length),W=Z-G,Q=Z-Y,z=2+W+1+1+Q,O=z<oJ,M=sJ.allocUnsafe((O?2:3)+z),A=0;if(M[A++]=gY,O)M[A++]=z;else M[A++]=oJ|1,M[A++]=z&255;if(M[A++]=lJ,M[A++]=W,G<0)M[A++]=0,A+=$.copy(M,A,0,Z);else A+=$.copy(M,A,G,Z);if(M[A++]=lJ,M[A++]=Q,Y<0)M[A++]=0,$.copy(M,A,Z);else $.copy(M,A,Z+Y);return M}bY.exports={derToJose:m9,joseToDer:d9}});var SG=o((f7,$W)=>{var LG=wY(),{createHmac:nY,createVerify:s9,createSign:o9,timingSafeEqual:l9,createPublicKey:r9,constants:{RSA_PKCS1_PSS_PADDING:mY,RSA_PSS_SALTLEN_DIGEST:dY,RSA_PKCS1_PADDING:sY,RSA_PSS_SALTLEN_MAX_SIGN:i9,RSA_PSS_SALTLEN_AUTO:t9},sign:pY,verify:uY}=A$("crypto"),{joseToDer:a9,derToJose:e9}=cY(),oY=YG(),{TokenError:J0}=n$(),lY=/[=+/]/g,$8={"=":"","+":"-","/":"_"},rY=/^-----BEGIN(?: (RSA|EC|ENCRYPTED))? PRIVATE KEY-----/,iY=/^-----BEGIN(?: (RSA))? PUBLIC KEY-----/,rJ=new oY(1000),BG=new oY(1000),tY=["HS256","HS384","HS512"],J8=["ES256","ES384","ES512"],PG=["RS256","RS384","RS512","PS256","PS384","PS512"],Z8=["EdDSA"],aY={"1.2.840.10045.3.1.7":{bits:"256",names:["P-256","prime256v1"]},"1.3.132.0.10":{bits:"256",names:["secp256k1"]},"1.3.132.0.34":{bits:"384",names:["P-384","secp384r1"]},"1.3.132.0.35":{bits:"512",names:["P-521","secp521r1"]}},G8=LG.define("PrivateKey",function(){this.seq().obj(this.key("version").int(),this.key("algorithm").seq().obj(this.key("algorithm").objid(),this.key("parameters").optional().objid()))}),X8=LG.define("PublicKey",function(){this.seq().obj(this.key("algorithm").seq().obj(this.key("algorithm").objid(),this.key("parameters").optional().objid()))}),Y8=LG.define("ECPrivateKey",function(){this.seq().obj(this.key("version").int(),this.key("privateKey").octstr(),this.key("parameters").explicit(0).optional().choice({namedCurve:this.objid()}))});function eY($){return $8[$]}function UJ($,J,Z,X){return $.set(J,[Z,X]),Z||X}function W8($){if($.match(iY)||$.includes("-----BEGIN CERTIFICATE-----"))throw new J0(J0.codes.invalidKey,"Public keys are not supported for signing.");let J=$.trim().match(rY);if(!J)return"HS256";let Z,X,G;switch(J[1]){case"RSA":return"RS256";case"EC":Z=Y8.decode($,"pem",{label:"EC PRIVATE KEY"}),G=Z.parameters.value.join(".");break;case"ENCRYPTED":return"ENCRYPTED";default:switch(Z=G8.decode($,"pem",{label:"PRIVATE KEY"}),X=Z.algorithm.algorithm.join("."),X){case"1.2.840.113549.1.1.1":return"RS256";case"1.2.840.10045.2.1":G=Z.algorithm.parameters.join(".");break;case"1.3.101.112":case"1.3.101.113":return"EdDSA";default:throw new J0(J0.codes.invalidKey,`Unsupported PEM PCKS8 private key with OID ${X}.`)}}let Y=aY[G];if(!Y)throw new J0(J0.codes.invalidKey,`Unsupported EC private key with curve ${G}.`);return`ES${Y.bits}`}function H8($){let J=$.match(iY);if($.match(rY))throw new J0(J0.codes.invalidKey,"Private keys are not supported for verifying.");else if(J&&J[1]==="RSA")return PG;else if(!J&&!$.includes("-----BEGIN CERTIFICATE-----"))return tY;if($.includes("-----BEGIN CERTIFICATE-----"))$=r9($).export({type:"spki",format:"pem"});let Z=X8.decode($,"pem",{label:"PUBLIC KEY"}),X=Z.algorithm.algorithm.join("."),G;switch(X){case"1.2.840.113549.1.1.1":return PG;case"1.2.840.10045.2.1":G=Z.algorithm.parameters.join(".");break;case"1.3.101.112":case"1.3.101.113":return["EdDSA"];default:throw new J0(J0.codes.invalidKey,`Unsupported PEM PCKS8 public key with OID ${X}.`)}let Y=aY[G];if(!Y)throw new J0(J0.codes.invalidKey,`Unsupported EC public key with curve ${G}.`);return[`ES${Y.bits}`]}function Q8($,J){if($ instanceof Buffer)$=$.toString("utf-8");else if(typeof $!=="string")throw new J0(J0.codes.invalidKey,"The private key must be a string or a buffer.");let[Z,X]=rJ.get($)||[];if(Z)return Z;else if(X)throw X;try{let G=W8($);if(G==="ENCRYPTED")return UJ(rJ,$,J);return UJ(rJ,$,G)}catch(G){throw UJ(rJ,$,null,J0.wrap(G,J0.codes.invalidKey,"Unsupported PEM private key."))}}function U8($){if(!$)return"none";let[J,Z]=BG.get($)||[];if(J)return J;else if(Z)throw Z;try{if($ instanceof Buffer)$=$.toString("utf-8");else if(typeof $!=="string")throw new J0(J0.codes.invalidKey,"The public key must be a string or a buffer.");return UJ(BG,$,H8($))}catch(X){throw UJ(BG,$,null,J0.wrap(X,J0.codes.invalidKey,"Unsupported PEM public key."))}}function V8($,J,Z){try{let X=$.slice(0,2),G=`sha${$.slice(2)}`,Y,W;switch(X){case"HS":Y=nY(G,J).update(Z).digest("base64");break;case"ES":Y=e9(pY(G,Buffer.from(Z,"utf-8"),J),$).toString("base64");break;case"RS":case"PS":if(W={key:J,padding:sY,saltLength:i9},X==="PS")W.padding=mY,W.saltLength=dY;Y=o9(G).update(Z).sign(W).toString("base64");break;case"Ed":Y=pY(void 0,Buffer.from(Z,"utf-8"),J).toString("base64")}return Y.replace(lY,eY)}catch(X){throw new J0(J0.codes.signError,"Cannot create the signature.",{originalError:X})}}function z8($,J,Z,X){try{let G=$.slice(0,2),Y=`SHA${$.slice(2)}`;if(X=Buffer.from(X,"base64"),G==="HS")try{return l9(nY(Y,J).update(Z).digest(),X)}catch{return!1}else if(G==="Ed")if(typeof uY==="function")return uY(void 0,Buffer.from(Z,"utf-8"),J,X);else throw new J0(J0.codes.signError,"EdDSA algorithms are not supported by your Node.js version.");let W={key:J,padding:sY,saltLength:t9};if(G==="PS")W.padding=mY,W.saltLength=dY;else if(G==="ES")X=a9(X,$);return s9("RSA-"+Y).update(Z).verify(W,X)}catch(G){throw new J0(J0.codes.verifyError,"Cannot verify the signature.",{originalError:G})}}$W.exports={base64UrlMatcher:lY,base64UrlReplacer:eY,hsAlgorithms:tY,rsaAlgorithms:PG,esAlgorithms:J8,edAlgorithms:Z8,detectPrivateKeyAlgorithm:Q8,detectPublicKeyAlgorithms:U8,createSignature:V8,verifySignature:z8}});var CG=o((y7,ZW)=>{var{createHash:JW}=A$("crypto"),O8=/"alg"\s*:\s*"[HERP]S(256|384)"/m,K8=/"alg"\s*:\s*"EdDSA"/m,M8=/"crv"\s*:\s*"Ed448"/m;function _8($,J,Z){let X=$(J,Z);if(X&&typeof X.then==="function")X.then((G)=>{process.nextTick(()=>Z(null,G))}).catch(Z)}function A8($){if(typeof $==="function")return[$];let J,Z,X=new Promise((G,Y)=>{J=G,Z=Y});return[function(G,Y){if(G)return Z(G);return J(Y)},X]}function F8($){let J=$.split(".",1)[0],Z=Buffer.from(J,"base64").toString("utf-8"),X=null;if(Z.match(K8)&&Z.match(M8))X=JW("shake256",{outputLength:114});else{let G=Z.match(O8);X=JW(`sha${G?G[1]:"512"}`)}return X.update($).digest("hex")}ZW.exports={getAsyncKey:_8,ensurePromiseCallback:A8,hashToken:F8}});var UW=o((x7,QW)=>{var{createPublicKey:R8,createSecretKey:I8}=A$("crypto"),j8=YG(),{hsAlgorithms:XW,verifySignature:q8,detectPublicKeyAlgorithms:YW}=SG(),B8=$G(),{TokenError:m}=n$(),{getAsyncKey:P8,ensurePromiseCallback:L8,hashToken:S8}=CG();function C8($,J){return $===J}function WW($,J){for(let Z of $)if(J.includes(Z))return;throw new m(m.codes.invalidKey,`Invalid public key provided for algorithms ${$.join(", ")}.`)}function HW($,J){if(typeof $==="string")$=Buffer.from($,"utf-8");return J?I8($):R8($)}function VJ($){if(!Array.isArray($))$=[$];return $.filter((J)=>J).map((J)=>{if(J&&typeof J.test==="function")return J;return{test:C8.bind(null,J)}})}function E8($){let J=parseInt($===!0?1000:$,10);return J>0?new j8(J):null}function a$({cache:$,token:J,cacheTTL:Z,payload:X,ignoreExpiration:G,ignoreNotBefore:Y,maxAge:W,clockTimestamp:Q=Date.now(),clockTolerance:z,errorCacheTTL:O,cacheKeyBuilder:M},A){if(!$)return A;let B=[A,0,0];if(A instanceof m){let w=typeof O==="function"?O(A):O;return B[2]=Q+z+w,$.set(M(J),B),A}if(X&&typeof X.iat==="number"){if(B[1]=!Y&&typeof X.nbf==="number"?X.nbf*1000-z:0,!G){if(typeof X.exp==="number")B[2]=X.exp*1000+z;else if(W)B[2]=X.iat*1000+W+z}}let C=Q+z+Z;return B[2]=B[2]===0?C:Math.min(B[2],C),$.set(M(J),B),A}function w8($,J,Z){if($ instanceof m){if(!J)throw $;J($)}else{if(!J)return $;J(null,$)}return Z}function T8($,J,Z,X,G){if(!G.includes(J.alg))throw new m(m.codes.invalidAlgorithm,"The token algorithm is invalid.");if(Z&&!q8(J.alg,X,$,Z))throw new m(m.codes.invalidSignature,"The token signature is invalid.")}function N8($,J,Z,X,G){let Y=Z?`The ${J} claim must be a ${G} or an array of ${G}s.`:`The ${J} claim must be a ${G}.`;if(X&&!Z)throw new m(m.codes.invalidClaimValue,Y);if($.map((W)=>typeof W).some((W)=>W!==G))throw new m(m.codes.invalidClaimType,Y)}function v8($,J,Z,X){let G=X?`None of ${J} claim values are allowed.`:`The ${J} claim value is not allowed.`;if(!$.some((Y)=>Z.some((W)=>W.test(Y))))throw new m(m.codes.invalidClaimValue,G)}function D8($,J,Z,X,G,Y){let W=$*1000+(J||0);if(!(X?Z>=W:Z<=W))throw new m(m.codes[G],`The token ${Y} at ${new Date(W).toISOString()}.`)}function GW($,{input:J,header:Z,payload:X,signature:G},{validators:Y,allowedAlgorithms:W,checkTyp:Q,clockTimestamp:z,requiredClaims:O}){let M=$ instanceof Buffer?$.length:!!$;if(M&&!G)throw new m(m.codes.missingSignature,"The token signature is missing.");else if(!M&&G)throw new m(m.codes.missingKey,"The key option is missing.");if(T8(J,Z,G,$,W),Q&&(typeof Z.typ!=="string"||Q!==Z.typ.toLowerCase().replace(/^application\//,"")))throw new m(m.codes.invalidType,"Invalid typ.");if(O){for(let B of O)if(!(B in X))throw new m(m.codes.missingRequiredClaim,`The ${B} claim is required.`)}let A=z||Date.now();for(let{type:B,claim:L,allowed:C,array:w,modifier:T,greater:D,errorCode:E,errorVerb:N}of Y){let h=X[L],v=Array.isArray(h),p=v?h:[h];if(!(L in X))continue;if(N8(p,L,w,v,B==="date"?"number":"string"),B==="date")D8(h,T,A,D,E,N);else v8(p,L,C,v)}}function k8({key:$,allowedAlgorithms:J,complete:Z,cacheTTL:X,checkTyp:G,clockTimestamp:Y,clockTolerance:W,ignoreExpiration:Q,ignoreNotBefore:z,maxAge:O,isAsync:M,validators:A,decode:B,cache:L,requiredClaims:C,errorCacheTTL:w,cacheKeyBuilder:T},D,E){let[N,h]=M?L8(E):[];if(L){let[V,K,_]=L.get(T(D))||[void 0,0,0],I=Y||Date.now();if(typeof V<"u"&&(K===0||I<K&&V.code==="FAST_JWT_INACTIVE"||I>=K&&V.code!=="FAST_JWT_INACTIVE")&&(_===0||I<=_))return w8(V,N,h)}let v;try{v=B(D)}catch(V){if(N)return N(V),h;throw V}let{header:p,payload:i,signature:l,input:u0}=v,j={cache:L,token:D,cacheTTL:X,errorCacheTTL:w,ignoreExpiration:Q,ignoreNotBefore:z,maxAge:O,clockTimestamp:Y,clockTolerance:W,payload:i,cacheKeyBuilder:T},H={validators:A,allowedAlgorithms:J,checkTyp:G,clockTimestamp:Y,clockTolerance:W,requiredClaims:C};if(!N)try{return GW($,v,H),a$(j,Z?{header:p,payload:i,signature:l,input:u0}:i)}catch(V){throw a$(j,V)}return P8($,{header:p,payload:i,signature:l},(V,K)=>{if(V)return N(a$(j,m.wrap(V,m.codes.keyFetchingError,"Cannot fetch key.")));if(typeof K==="string")K=Buffer.from(K,"utf-8");else if(!(K instanceof Buffer))return N(a$(j,new m(m.codes.keyFetchingError,"The key returned from the callback must be a string or a buffer containing a secret or a public key.")));try{let _=YW(K);if(H.allowedAlgorithms.length)WW(J,_);else H.allowedAlgorithms=_;K=HW(K,_[0]===XW[0]),GW(K,v,H)}catch(_){return N(a$(j,_))}N(null,a$(j,Z?{header:p,payload:i,signature:l,input:D}:i))}),h}QW.exports=function(J){let{key:Z,algorithms:X,complete:G,cache:Y,cacheTTL:W,errorCacheTTL:Q,checkTyp:z,clockTimestamp:O,clockTolerance:M,ignoreExpiration:A,ignoreNotBefore:B,maxAge:L,allowedJti:C,allowedAud:w,allowedIss:T,allowedSub:D,allowedNonce:E,requiredClaims:N,cacheKeyBuilder:h}={cacheTTL:600000,clockTolerance:0,errorCacheTTL:-1,cacheKeyBuilder:S8,...J};if(!Array.isArray(X))X=[];let v=typeof Z;if(v!=="string"&&v!=="object"&&v!=="function")throw new m(m.codes.INVALID_OPTION,"The key option must be a string, a buffer or a function returning the algorithm secret or public key.");if(Z&&v!=="function"){let j=YW(Z);if(X.length)WW(X,j);else X=j;Z=HW(Z,j[0]===XW[0])}if(O&&(typeof O!=="number"||O<0))throw new m(m.codes.invalidOption,"The clockTimestamp option must be a positive number.");if(M&&(typeof M!=="number"||M<0))throw new m(m.codes.invalidOption,"The clockTolerance option must be a positive number.");if(W&&(typeof W!=="number"||W<0))throw new m(m.codes.invalidOption,"The cacheTTL option must be a positive number.");if(Q&&typeof Q!=="function"&&typeof Q!=="number"||Q<-1)throw new m(m.codes.invalidOption,"The errorCacheTTL option must be a number greater than -1 or a function.");if(N&&!Array.isArray(N))throw new m(m.codes.invalidOption,"The requiredClaims option must be an array.");let p=[];if(!B)p.push({type:"date",claim:"nbf",errorCode:"inactive",errorVerb:"will be active",greater:!0,modifier:-M});if(!A)p.push({type:"date",claim:"exp",errorCode:"expired",errorVerb:"has expired",modifier:+M});if(typeof L==="number")p.push({type:"date",claim:"iat",errorCode:"expired",errorVerb:"has expired",modifier:L});if(C)p.push({type:"string",claim:"jti",allowed:VJ(C)});if(w)p.push({type:"string",claim:"aud",allowed:VJ(w),array:!0});if(T)p.push({type:"string",claim:"iss",allowed:VJ(T)});if(D)p.push({type:"string",claim:"sub",allowed:VJ(D)});if(E)p.push({type:"string",claim:"nonce",allowed:VJ(E)});let i=z?z.toLowerCase().replace(/^application\//,""):null,l={key:Z,allowedAlgorithms:X,complete:G,cacheTTL:W,errorCacheTTL:Q,checkTyp:i,clockTimestamp:O,clockTolerance:M,ignoreExpiration:A,ignoreNotBefore:B,maxAge:L,isAsync:v==="function",validators:p,decode:B8({complete:!0}),cache:E8(Y),requiredClaims:N,cacheKeyBuilder:h},u0=k8.bind(null,l);return u0.cache=l.cache,u0}});var VW=o((g8)=>{var f8=/^(-?(?:\d+)?\.?\d+) *(m(?:illiseconds?|s(?:ecs?)?))?(s(?:ec(?:onds?|s)?)?)?(m(?:in(?:utes?|s)?)?)?(h(?:ours?|rs?)?)?(d(?:ays?)?)?(w(?:eeks?|ks?)?)?(y(?:ears?|rs?)?)?$/,iJ=1000,tJ=iJ*60,aJ=tJ*60,OJ=aJ*24,EG=OJ*365.25;function y8($){var J,Z=$.toLowerCase().match(f8);if(Z!=null&&(J=parseFloat(Z[1]))){if(Z[3]!=null)return J*iJ;if(Z[4]!=null)return J*tJ;if(Z[5]!=null)return J*aJ;if(Z[6]!=null)return J*OJ;if(Z[7]!=null)return J*OJ*7;if(Z[8]!=null)return J*EG;return J}}function zJ($,J,Z,X){var G=($|0)===$?$:~~($+0.5);return J+G+(X?" "+Z+(G!=1?"s":""):Z[0])}function x8($,J){var Z=$<0?"-":"",X=$<0?-$:$;if(X<iJ)return $+(J?" ms":"ms");if(X<tJ)return zJ(X/iJ,Z,"second",J);if(X<aJ)return zJ(X/tJ,Z,"minute",J);if(X<OJ)return zJ(X/aJ,Z,"hour",J);if(X<EG)return zJ(X/OJ,Z,"day",J);return zJ(X/EG,Z,"year",J)}g8.format=x8;g8.parse=y8});var RW=o((h7,FW)=>{var{base64UrlMatcher:wG,base64UrlReplacer:TG,hsAlgorithms:c8,esAlgorithms:p8,rsaAlgorithms:u8,edAlgorithms:n8,detectPrivateKeyAlgorithm:KW,createSignature:zW}=SG(),{TokenError:s}=n$(),{getAsyncKey:m8,ensurePromiseCallback:d8}=CG(),{createPrivateKey:s8,createSecretKey:o8}=A$("crypto"),{parse:OW}=VW(),MW=new Set([...c8,...p8,...u8,...n8,"none"]),l8=Array.from(MW).join(", ");function _W($,J){let Z=$.slice(0,2),X=J.slice(0,2),G=!0;if(Z==="RS"||Z==="PS")G=X==="RS"||Z==="RS"&&J==="ENCRYPTED";else if(Z==="ES"||Z==="Ed")G=Z===X||Z==="ES"&&J==="ENCRYPTED";if(!G)throw new s(s.codes.invalidKey,`Invalid private key provided for algorithm ${$}.`)}function AW($,J){if(typeof $==="string")$=Buffer.from($,"utf-8");return J[0]==="H"?o8($):s8($)}function r8({key:$,algorithm:J,noTimestamp:Z,mutatePayload:X,clockTimestamp:G,expiresIn:Y,notBefore:W,kid:Q,typ:z,isAsync:O,additionalHeader:M,fixedPayload:A},B,L){let[C,w]=O?d8(L):[];if(typeof B!=="object")throw new s(s.codes.invalidType,"The payload must be an object.");if(B.exp&&(!Number.isInteger(B.exp)||B.exp<0))throw new s(s.codes.invalidClaimValue,"The exp claim must be a positive integer.");let T={alg:J,typ:z||"JWT",kid:Q,...M},D="",E=B.iat*1000||G||Date.now(),N={...B,...A,iat:Z?void 0:Math.floor(E/1000),exp:B.exp?B.exp:Y?Math.floor((E+Y)/1000):void 0,nbf:B.nbf?B.nbf:W?Math.floor((E+W)/1000):void 0};if(X)Object.assign(B,N);if(D=Buffer.from(JSON.stringify(N),"utf-8").toString("base64").replace(wG,TG),!C){let v=Buffer.from(JSON.stringify(T),"utf-8").toString("base64").replace(wG,TG)+"."+D,p=J==="none"?"":zW(J,$,v);return v+"."+p}return m8($,{header:T,payload:B},(h,v)=>{if(h){let i=s.wrap(h,s.codes.keyFetchingError,"Cannot fetch key.");return C(i)}if(typeof v==="string")v=Buffer.from(v,"utf-8");else if(!(v instanceof Buffer))return C(new s(s.codes.keyFetchingError,"The key returned from the callback must be a string or a buffer containing a secret or a private key."));let p;try{let i=KW(v,J);if(J)_W(J,i);else T.alg=J=i;v=AW(v,J);let u0=Buffer.from(JSON.stringify(T),"utf-8").toString("base64").replace(wG,TG)+"."+D;p=u0+"."+zW(J,v,u0)}catch(i){return C(i)}C(null,p)}),w}FW.exports=function(J){let{key:Z,algorithm:X,noTimestamp:G,mutatePayload:Y,clockTimestamp:W,expiresIn:Q,notBefore:z,jti:O,aud:M,iss:A,sub:B,nonce:L,kid:C,typ:w,header:T}={clockTimestamp:0,...J};if(X&&!MW.has(X))throw new s(s.codes.invalidOption,`The algorithm option must be one of the following values: ${l8}.`);let D=typeof Z,E=D==="object"&&Z&&Z.key&&Z.passphrase;if(X==="none"){if(Z)throw new s(s.codes.invalidOption,'The key option must not be provided when the algorithm option is "none".')}else if(!Z||D!=="string"&&!(Z instanceof Buffer)&&D!=="function"&&!E)throw new s(s.codes.invalidOption,"The key option must be a string, a buffer, an object containing key/passphrase properties or a function returning the algorithm secret or private key.");else if(E&&!X)throw new s(s.codes.invalidAlgorithm,"When using password protected key you must provide the algorithm option.");if(Z&&D!=="function"){let v=KW(E?Z.key:Z,X);if(X)_W(X,v);else X=v;Z=AW(Z,X)}if(Q){if(typeof Q==="string")Q=OW(Q);if(typeof Q!=="number")throw new s(s.codes.invalidOption,"The expiresIn option must be a positive number or a valid string.")}if(z){if(typeof z==="string")z=OW(z);if(typeof z!=="number"||z<0)throw new s(s.codes.invalidOption,"The notBefore option must be a positive number or a valid string.")}if(W&&(typeof W!=="number"||W<0))throw new s(s.codes.invalidOption,"The clockTimestamp option must be a positive number.");if(O&&typeof O!=="string")throw new s(s.codes.invalidOption,"The jti option must be a string.");if(M&&typeof M!=="string"&&!Array.isArray(M))throw new s(s.codes.invalidOption,"The aud option must be a string or an array of strings.");if(A&&typeof A!=="string")throw new s(s.codes.invalidOption,"The iss option must be a string.");if(B&&typeof B!=="string")throw new s(s.codes.invalidOption,"The sub option must be a string.");if(L&&typeof L!=="string")throw new s(s.codes.invalidOption,"The nonce option must be a string.");if(C&&typeof C!=="string")throw new s(s.codes.invalidOption,"The kid option must be a string.");if(T&&typeof T!=="object")throw new s(s.codes.invalidOption,"The header option must be a object.");let h=Object.entries({jti:O,aud:M,iss:A,sub:B,nonce:L}).reduce((v,[p,i])=>{if(i!==void 0)v[p]=i;return v},{});return r8.bind(null,{key:Z,algorithm:X,noTimestamp:G,mutatePayload:Y,clockTimestamp:W,expiresIn:Q,notBefore:z,kid:C,typ:w,isAsync:D==="function",additionalHeader:T,fixedPayload:h})}});var jW=o((b7,IW)=>{var{TokenError:i8,TOKEN_ERROR_CODES:t8}=n$(),a8=$G(),e8=UW(),$6=RW();IW.exports={TokenError:i8,TOKEN_ERROR_CODES:t8,createDecoder:a8,createVerifier:e8,createSigner:$6}});RJ();import{join as vZ}from"path";n0();function W$($){if(Array.isArray($)){let J=[];for(let Z of $)J.push(W$(Z));return J}if(n($)){let J={},Z=$;for(let X of Object.keys(Z))J[X]=W$(Z[X]);return J}return $}function zX($,J){if(J===void 0)return $;if(Array.isArray($)&&Array.isArray(J)){let Z=[];for(let X of $)Z.push(W$(X));for(let X of J)Z.push(W$(X));return Z}if(n($)&&n(J)){let Z=$,X=J,G={};for(let Y of Object.keys(Z))G[Y]=W$(Z[Y]);for(let Y of Object.keys(X)){let W=X[Y];if(W===void 0)continue;let Q=G[Y];if(Array.isArray(Q)&&Array.isArray(W)){let z=[];for(let O of Q)z.push(W$(O));for(let O of W)z.push(W$(O));G[Y]=z;continue}if(n(Q)&&n(W)){G[Y]=zX(W$(Q),W);continue}G[Y]=W$(W)}return G}return W$(J)}function OX(...$){let J={};for(let Z of $){if(Z===void 0)continue;J=zX(J,Z)}return J}var UH={nodeEnv:"development",appName:"\u91CE\u8702\u98DE\u821E",appPort:3000,appHost:"127.0.0.1",devEmail:"dev@qq.com",devPassword:"beflydev123456",bodyLimit:1048576,tz:"Asia/Shanghai",logger:{debug:1,excludeFields:["password","token","secret"],dir:"./logs",console:1,maxSize:20,maxStringLen:100,maxArrayItems:100},db:{type:"mysql",host:"127.0.0.1",port:3306,username:"root",password:"root",database:"befly_demo",poolMax:10},redis:{host:"127.0.0.1",port:6379,username:"",password:"",db:0,prefix:"befly_demo"},auth:{secret:"befly-secret",expiresIn:"7d",algorithm:"HS256"},cors:{origin:"*",methods:"GET,HEAD,PUT,PATCH,POST,DELETE",allowedHeaders:"Content-Type,Authorization",exposedHeaders:"",maxAge:86400,credentials:"true"},rateLimit:{enable:1,defaultLimit:1000,defaultWindow:60,key:"ip",skipRoutes:[],rules:[]},disableMenus:["**/404","**/403","**/500","**/login"],addons:{}};async function KX($){if($!=="development"&&$!=="production")throw Error(`\u914D\u7F6E\u9519\u8BEF\uFF1ANODE_ENV \u53EA\u80FD\u662F 'development' \u6216 'production'\uFF0C\u5F53\u524D\u503C=${String($)}`);let J=vZ(process.cwd(),"configs"),Z=await j$(vZ(J,"befly.common.json"),{}),X=await j$(vZ(J,`befly.${$}.json`),{}),G=OX(UH,Z,X);G.nodeEnv=$;let Y=G.redis?.prefix;if(typeof Y==="string"){if(Y.trim().includes(":"))throw Error(`\u914D\u7F6E\u9519\u8BEF\uFF1Aredis.prefix \u4E0D\u5141\u8BB8\u5305\u542B ':'\uFF08RedisHelper \u4F1A\u81EA\u52A8\u62FC\u63A5\u5206\u9694\u7B26 ':'\uFF09\uFF0C\u8BF7\u6539\u4E3A\u4E0D\u5E26\u5192\u53F7\u7684\u524D\u7F00\uFF0C\u4F8B\u5982 'befly_demo'\uFF0C\u5F53\u524D\u503C=${Y}`)}return G}a();n0();async function MX($){let J=!1,Z=new Set;for(let X of $)try{if(!n(X)){q.warn({item:X,msg:"\u63A5\u53E3\u5FC5\u987B\u662F\u5BF9\u8C61"}),J=!0;continue}let G=X,Y=G.name;if(typeof Y!=="string"||Y.trim()===""){q.warn(Object.assign({},b(G,["handler"]),{msg:"\u63A5\u53E3\u7684 name \u5C5E\u6027\u5FC5\u987B\u662F\u975E\u7A7A\u5B57\u7B26\u4E32"})),J=!0;continue}if(typeof G.handler!=="function"){q.warn(Object.assign({},b(G,["handler"]),{msg:"\u63A5\u53E3\u7684 handler \u5C5E\u6027\u5FC5\u987B\u662F\u51FD\u6570"})),J=!0;continue}let Q=G.path;if(typeof Q!=="string"||Q.trim()==="")q.warn(Object.assign({},b(G,["handler"]),{msg:"\u63A5\u53E3\u7684 path \u5C5E\u6027\u5FC5\u987B\u662F\u975E\u7A7A\u5B57\u7B26\u4E32\uFF08\u7531\u7CFB\u7EDF\u751F\u6210\uFF09"})),J=!0;else{let C=Q.trim();if(Z.has(C))q.warn(Object.assign({},b(G,["handler"]),{msg:"\u63A5\u53E3\u7684 path \u91CD\u590D\uFF08\u4E25\u683C\u6A21\u5F0F\u7981\u6B62\u91CD\u590D path\uFF09"})),J=!0;else Z.add(C);if(/^(GET|POST|PUT|PATCH|DELETE|OPTIONS|HEAD)\b/i.test(C))q.warn(Object.assign({},b(G,["handler"]),{msg:"\u63A5\u53E3\u7684 path \u4E0D\u5141\u8BB8\u5305\u542B method \u524D\u7F00\uFF0C\u5E94\u4E3A url.pathname\uFF08\u4F8B\u5982 /api/app/xxx\uFF09"})),J=!0;if(!C.startsWith("/api/"))q.warn(Object.assign({},b(G,["handler"]),{msg:"\u63A5\u53E3\u7684 path \u5FC5\u987B\u4EE5 /api/ \u5F00\u5934"})),J=!0;if(C.includes(" "))q.warn(Object.assign({},b(G,["handler"]),{msg:"\u63A5\u53E3\u7684 path \u4E0D\u5141\u8BB8\u5305\u542B\u7A7A\u683C"})),J=!0;if(C.includes("/api//"))q.warn(Object.assign({},b(G,["handler"]),{msg:"\u63A5\u53E3\u7684 path \u4E0D\u5141\u8BB8\u51FA\u73B0 /api//\uFF08\u91CD\u590D\u659C\u6760\uFF09"})),J=!0}let z=G.routePrefix,O=typeof z==="string"?z.trim():"";if(O==="")q.warn(Object.assign({},b(G,["handler"]),{msg:"\u63A5\u53E3\u7684 routePrefix \u5C5E\u6027\u5FC5\u987B\u662F\u975E\u7A7A\u5B57\u7B26\u4E32\uFF08\u7531\u7CFB\u7EDF\u751F\u6210\uFF09"})),J=!0;else{if(!(O==="/app"||O.startsWith("/addon/")))q.warn(Object.assign({},b(G,["handler"]),{msg:"\u63A5\u53E3\u7684 routePrefix \u5FC5\u987B\u662F /app \u6216 /addon/<name>\uFF08\u7531\u7CFB\u7EDF\u751F\u6210\uFF09"})),J=!0;if(typeof Q==="string"&&Q.trim()!==""){let C=Q.trim(),w=`/api${O}/`;if(!C.startsWith(w))q.warn(Object.assign({},b(G,["handler"]),{expectedPrefix:w,msg:"\u63A5\u53E3\u7684 path \u4E0E routePrefix \u4E0D\u4E00\u81F4\uFF1A\u5E94\u4EE5 /api${routePrefix}/ \u5F00\u5934\uFF08\u7531\u7CFB\u7EDF\u751F\u6210\uFF09"})),J=!0}}let M=G.method;if(M!==void 0&&!["GET","POST","GET,POST"].includes(String(M).toUpperCase()))q.warn(Object.assign({},b(G,["handler"]),{msg:"\u63A5\u53E3\u7684 method \u5C5E\u6027\u5FC5\u987B\u662F\u6709\u6548\u7684 HTTP \u65B9\u6CD5 (GET, POST, GET,POST)"})),J=!0;let A=G.auth;if(A!==void 0&&typeof A!=="boolean")q.warn(Object.assign({},b(G,["handler"]),{msg:"\u63A5\u53E3\u7684 auth \u5C5E\u6027\u5FC5\u987B\u662F\u5E03\u5C14\u503C (true=\u9700\u767B\u5F55, false=\u516C\u5F00)"})),J=!0;let B=G.fields;if(B!==void 0&&B!==null&&!n(B))q.warn(Object.assign({},b(G,["handler"]),{msg:"\u63A5\u53E3\u7684 fields \u5C5E\u6027\u5FC5\u987B\u662F\u5BF9\u8C61"})),J=!0;let L=G.required;if(L!==void 0&&!Array.isArray(L))q.warn(Object.assign({},b(G,["handler"]),{msg:"\u63A5\u53E3\u7684 required \u5C5E\u6027\u5FC5\u987B\u662F\u6570\u7EC4"})),J=!0;if(Array.isArray(L)){if(L.some((C)=>typeof C!=="string"))q.warn(Object.assign({},b(G,["handler"]),{msg:"\u63A5\u53E3\u7684 required \u5C5E\u6027\u5FC5\u987B\u662F\u5B57\u7B26\u4E32\u6570\u7EC4"})),J=!0}}catch(G){q.error({err:G,item:X,msg:"\u63A5\u53E3\u89E3\u6790\u5931\u8D25"}),J=!0}if(J)throw Error("\u63A5\u53E3\u7ED3\u6784\u68C0\u67E5\u5931\u8D25")}a();n0();var _X=["name","enable","deps","handler"];async function AX($){let J=!1,Z=/^[a-z]+(?:_[a-z]+)*$/;for(let X of $)try{if(!n(X)){q.warn(Object.assign({},b(X,["handler"]),{msg:"\u94A9\u5B50\u5BFC\u51FA\u5FC5\u987B\u662F\u5BF9\u8C61\uFF08export default { deps, handler }\uFF09"})),J=!0;continue}let G=X,Y=G.moduleName;if(typeof Y!=="string"||Y.trim()===""){q.warn(Object.assign({},b(X,["handler"]),{msg:"\u94A9\u5B50\u7684 moduleName \u5FC5\u987B\u662F\u975E\u7A7A\u5B57\u7B26\u4E32\uFF08\u7531\u7CFB\u7EDF\u751F\u6210\uFF0C\u7528\u4E8E deps \u4E0E\u8FD0\u884C\u65F6\u6302\u8F7D\uFF09"})),J=!0;continue}let W=G.customKeys;if(!Array.isArray(W)){q.warn(Object.assign({},b(X,["handler"]),{msg:"\u94A9\u5B50\u626B\u63CF\u7ED3\u679C\u7F3A\u5C11 customKeys\uFF08\u65E0\u6CD5\u5224\u65AD\u7528\u6237\u5BFC\u51FA\u7684\u5B57\u6BB5\u662F\u5426\u5408\u6CD5\uFF09"})),J=!0;continue}if(W.some((M)=>typeof M!=="string")){q.warn(Object.assign({},b(X,["handler"]),{msg:"\u94A9\u5B50\u7684 customKeys \u5FC5\u987B\u662F string[]\uFF08\u7531\u7CFB\u7EDF\u751F\u6210\uFF09"})),J=!0;continue}let Q=W.filter((M)=>!_X.includes(M));if(Q.length>0){q.warn(Object.assign({},b(X,["handler"]),{msg:`\u94A9\u5B50\u5BFC\u51FA\u5B58\u5728\u4E0D\u652F\u6301\u7684\u5C5E\u6027\uFF1A${Q.join(", ")}\uFF1B\u4EC5\u5141\u8BB8\uFF1A${_X.join(", ")}\uFF1B\u5F53\u524D customKeys\uFF1A${W.join(", ")}`})),J=!0;continue}let z=W.includes("enable"),O=W.includes("deps");if(z){if(typeof G.enable!=="boolean"){q.warn(Object.assign({},b(X,["handler"]),{msg:"\u94A9\u5B50\u7684 enable \u5C5E\u6027\u5FC5\u987B\u662F boolean\uFF08true/false\uFF09\uFF0C\u4E0D\u5141\u8BB8 0/1 \u7B49\u5176\u4ED6\u7C7B\u578B"})),J=!0;continue}}else G.enable=!0;if(G.source==="core"){let M=typeof G.name==="string"?G.name:"";if(M===""){q.warn(Object.assign({},b(X,["handler"]),{msg:"core \u5185\u7F6E\u94A9\u5B50\u5FC5\u987B\u663E\u5F0F\u8BBE\u7F6E name\uFF08string\uFF09\uFF0C\u7528\u4E8E\u786E\u5B9A\u94A9\u5B50\u540D\u79F0"})),J=!0;continue}if(!Z.test(M)){q.warn(Object.assign({},b(X,["handler"]),{msg:"core \u5185\u7F6E\u94A9\u5B50\u7684 name \u5FC5\u987B\u6EE1\u8DB3\u5C0F\u5199\u5B57\u6BCD+\u4E0B\u5212\u7EBF\u683C\u5F0F\uFF08\u4F8B\u5982 auth / rate_limit\uFF09\uFF0C\u4E0D\u5141\u8BB8\u7A7A\u683C\u3001\u9A7C\u5CF0\u6216\u5176\u4ED6\u5B57\u7B26"})),J=!0;continue}if(!Z.test(String(G.moduleName))){q.warn(Object.assign({},b(X,["handler"]),{msg:"core \u5185\u7F6E\u94A9\u5B50\u7684 moduleName \u5FC5\u987B\u6EE1\u8DB3\u5C0F\u5199\u5B57\u6BCD+\u4E0B\u5212\u7EBF\u683C\u5F0F\uFF08\u7531\u7CFB\u7EDF\u751F\u6210\uFF0C\u4E14\u5FC5\u987B\u4E0E name \u4E00\u81F4\uFF09"})),J=!0;continue}if(M!==String(G.moduleName)){q.warn(Object.assign({},b(X,["handler"]),{msg:"core \u5185\u7F6E\u94A9\u5B50\u7684 name \u5FC5\u987B\u4E0E moduleName \u5B8C\u5168\u4E00\u81F4"})),J=!0;continue}let A=G.filePath;if(typeof A!=="string"||!A.startsWith(`core:hook:${M}`)){q.warn(Object.assign({},b(X,["handler"]),{msg:"core \u5185\u7F6E\u94A9\u5B50\u5FC5\u987B\u6765\u81EA\u9759\u6001\u6CE8\u518C\uFF08filePath \u5FC5\u987B\u4EE5 core:hook:<name> \u5F00\u5934\uFF09\uFF0C\u4E0D\u5141\u8BB8\u901A\u8FC7\u626B\u63CF\u76EE\u5F55\u52A0\u8F7D"})),J=!0;continue}}if(O){let M=G.deps;if(!Array.isArray(M)){q.warn(Object.assign({},b(X,["handler"]),{msg:"\u94A9\u5B50\u7684 deps \u5C5E\u6027\u5FC5\u987B\u662F\u5B57\u7B26\u4E32\u6570\u7EC4"})),J=!0;continue}if(M.some((A)=>typeof A!=="string")){q.warn(Object.assign({},b(X,["handler"]),{msg:"\u94A9\u5B50\u7684 deps \u5C5E\u6027\u5FC5\u987B\u662F\u5B57\u7B26\u4E32\u6570\u7EC4"})),J=!0;continue}}else{let M=G.deps;if(!Array.isArray(M))G.deps=[]}if(typeof G.handler!=="function"){q.warn(Object.assign({},b(X,["handler"]),{msg:"\u94A9\u5B50\u7684 handler \u5C5E\u6027\u5FC5\u987B\u662F\u51FD\u6570"})),J=!0;continue}}catch(G){q.error({err:G,item:X,msg:"\u94A9\u5B50\u89E3\u6790\u5931\u8D25"}),J=!0}if(J)throw Error("\u94A9\u5B50\u7ED3\u6784\u68C0\u67E5\u5931\u8D25")}a();yZ();function IH($){if(!$)return{ok:!1,reason:"path \u4E0D\u80FD\u4E3A\u7A7A"};if(!$.startsWith("/"))return{ok:!1,reason:"path \u5FC5\u987B\u4EE5 / \u5F00\u5934"};if($.length>1&&$.endsWith("/"))return{ok:!1,reason:"path \u672B\u5C3E\u4E0D\u80FD\u662F /\uFF08\u6839\u8DEF\u5F84 / \u9664\u5916\uFF09"};if($.includes("//"))return{ok:!1,reason:"path \u4E0D\u80FD\u5305\u542B //"};if($.includes(".."))return{ok:!1,reason:"path \u4E0D\u80FD\u5305\u542B .."};return{ok:!0,reason:""}}var SX=async($)=>{let J=!1,Z=await LX($),X=[];for(let Y of Z)X.push({menu:Y,depth:1});let G=new Set;while(X.length>0){let Y=X.pop(),W=Y?.menu,Q=typeof Y?.depth==="number"?Y.depth:0;if(W===null||typeof W!=="object"){J=!0,q.warn({menu:W,msg:"\u83DC\u5355\u8282\u70B9\u5FC5\u987B\u662F\u5BF9\u8C61"});continue}if(Q>3){J=!0,q.warn({path:W?.path,depth:Q,msg:"\u83DC\u5355\u5C42\u7EA7\u8D85\u8FC7 3 \u7EA7\uFF08\u6700\u591A\u4E09\u7EA7\uFF09"});continue}let z=W.children;if(typeof z<"u"&&!Array.isArray(z)){J=!0,q.warn({path:W?.path,childrenType:typeof z,msg:"\u83DC\u5355 children \u5FC5\u987B\u662F\u6570\u7EC4"});continue}if(Array.isArray(z)&&z.length>0)if(Q>=3)J=!0,q.warn({path:W?.path,depth:Q,msg:"\u83DC\u5355\u5C42\u7EA7\u8D85\u8FC7 3 \u7EA7\uFF08\u6700\u591A\u4E09\u7EA7\uFF09"});else for(let L of z)X.push({menu:L,depth:Q+1});let O=typeof W.path==="string"?W.path.trim():"",M=typeof W.name==="string"?W.name.trim():"",A=typeof W.sort==="number"?W.sort:999999;if(typeof W.path==="string")W.path=O;if(typeof W.name==="string")W.name=M;if(typeof W.sort>"u")W.sort=A;if(!O){J=!0,q.warn({menu:W,msg:"\u83DC\u5355\u7F3A\u5C11 path\uFF08\u5FC5\u987B\u662F\u975E\u7A7A\u5B57\u7B26\u4E32\uFF09"});continue}let B=IH(O);if(!B.ok)J=!0,q.warn({path:O,reason:B.reason,msg:"\u83DC\u5355 path \u4E0D\u5408\u6CD5"});if(!M)J=!0,q.warn({path:O,menu:W,msg:"\u83DC\u5355\u7F3A\u5C11 name\uFF08\u5FC5\u987B\u662F\u975E\u7A7A\u5B57\u7B26\u4E32\uFF09"});if(typeof W.sort<"u"&&typeof W.sort!=="number")J=!0,q.warn({path:O,sort:W.sort,msg:"\u83DC\u5355 sort \u5FC5\u987B\u662F number"});if(typeof W.sort==="number"&&(!Number.isFinite(W.sort)||W.sort<1))J=!0,q.warn({path:O,sort:W.sort,msg:"\u83DC\u5355 sort \u6700\u5C0F\u503C\u4E3A 1"});if(G.has(O)){J=!0,q.warn({path:O,msg:"\u83DC\u5355 path \u91CD\u590D\uFF08\u4E25\u683C\u6A21\u5F0F\u7981\u6B62\u91CD\u590D path\uFF09"});continue}G.add(O)}if(J)throw Error("\u83DC\u5355\u7ED3\u6784\u68C0\u67E5\u5931\u8D25");return Z};a();n0();var CX=["name","enable","deps","handler"];async function EX($){let J=!1,Z=/^[a-z]+(?:_[a-z]+)*$/;for(let X of $)try{if(!n(X)){q.warn(Object.assign({},b(X,["handler"]),{msg:"\u63D2\u4EF6\u5BFC\u51FA\u5FC5\u987B\u662F\u5BF9\u8C61\uFF08export default { deps, handler }\uFF09"})),J=!0;continue}let G=X,Y=G.moduleName;if(typeof Y!=="string"||Y.trim()===""){q.warn(Object.assign({},b(X,["handler"]),{msg:"\u63D2\u4EF6\u7684 moduleName \u5FC5\u987B\u662F\u975E\u7A7A\u5B57\u7B26\u4E32\uFF08\u7531\u7CFB\u7EDF\u751F\u6210\uFF0C\u7528\u4E8E deps \u4E0E\u8FD0\u884C\u65F6\u6302\u8F7D\uFF09"})),J=!0;continue}let W=G.customKeys;if(!Array.isArray(W)){q.warn(Object.assign({},b(X,["handler"]),{msg:"\u63D2\u4EF6\u626B\u63CF\u7ED3\u679C\u7F3A\u5C11 customKeys\uFF08\u65E0\u6CD5\u5224\u65AD\u7528\u6237\u5BFC\u51FA\u7684\u5B57\u6BB5\u662F\u5426\u5408\u6CD5\uFF09"})),J=!0;continue}if(W.some((M)=>typeof M!=="string")){q.warn(Object.assign({},b(X,["handler"]),{msg:"\u63D2\u4EF6\u7684 customKeys \u5FC5\u987B\u662F string[]\uFF08\u7531\u7CFB\u7EDF\u751F\u6210\uFF09"})),J=!0;continue}let Q=W.filter((M)=>!CX.includes(M));if(Q.length>0){q.warn(Object.assign({},b(X,["handler"]),{msg:`\u63D2\u4EF6\u5BFC\u51FA\u5B58\u5728\u4E0D\u652F\u6301\u7684\u5C5E\u6027\uFF1A${Q.join(", ")}\uFF1B\u4EC5\u5141\u8BB8\uFF1A${CX.join(", ")}\uFF1B\u5F53\u524D customKeys\uFF1A${W.join(", ")}`})),J=!0;continue}let z=W.includes("enable"),O=W.includes("deps");if(z){if(typeof G.enable!=="boolean"){q.warn(Object.assign({},b(X,["handler"]),{msg:"\u63D2\u4EF6\u7684 enable \u5C5E\u6027\u5FC5\u987B\u662F boolean\uFF08true/false\uFF09\uFF0C\u4E0D\u5141\u8BB8 0/1 \u7B49\u5176\u4ED6\u7C7B\u578B"})),J=!0;continue}}else G.enable=!0;if(G.source==="core"){let M=typeof G.name==="string"?G.name:"";if(M===""){q.warn(Object.assign({},b(X,["handler"]),{msg:"core \u5185\u7F6E\u63D2\u4EF6\u5FC5\u987B\u663E\u5F0F\u8BBE\u7F6E name\uFF08string\uFF09\uFF0C\u7528\u4E8E\u786E\u5B9A\u63D2\u4EF6\u540D\u79F0"})),J=!0;continue}if(!Z.test(M)){q.warn(Object.assign({},b(X,["handler"]),{msg:"core \u5185\u7F6E\u63D2\u4EF6\u7684 name \u5FC5\u987B\u6EE1\u8DB3\u5C0F\u5199\u5B57\u6BCD+\u4E0B\u5212\u7EBF\u683C\u5F0F\uFF08\u4F8B\u5982 logger / redis_cache\uFF09\uFF0C\u4E0D\u5141\u8BB8\u7A7A\u683C\u3001\u9A7C\u5CF0\u6216\u5176\u4ED6\u5B57\u7B26"})),J=!0;continue}if(!Z.test(String(G.moduleName))){q.warn(Object.assign({},b(X,["handler"]),{msg:"core \u5185\u7F6E\u63D2\u4EF6\u7684 moduleName \u5FC5\u987B\u6EE1\u8DB3\u5C0F\u5199\u5B57\u6BCD+\u4E0B\u5212\u7EBF\u683C\u5F0F\uFF08\u7531\u7CFB\u7EDF\u751F\u6210\uFF0C\u4E14\u5FC5\u987B\u4E0E name \u4E00\u81F4\uFF09"})),J=!0;continue}if(M!==String(G.moduleName)){q.warn(Object.assign({},b(X,["handler"]),{msg:"core \u5185\u7F6E\u63D2\u4EF6\u7684 name \u5FC5\u987B\u4E0E moduleName \u5B8C\u5168\u4E00\u81F4"})),J=!0;continue}let A=G.filePath;if(typeof A!=="string"||!A.startsWith(`core:plugin:${M}`)){q.warn(Object.assign({},b(X,["handler"]),{msg:"core \u5185\u7F6E\u63D2\u4EF6\u5FC5\u987B\u6765\u81EA\u9759\u6001\u6CE8\u518C\uFF08filePath \u5FC5\u987B\u4EE5 core:plugin:<name> \u5F00\u5934\uFF09\uFF0C\u4E0D\u5141\u8BB8\u901A\u8FC7\u626B\u63CF\u76EE\u5F55\u52A0\u8F7D"})),J=!0;continue}}if(O){let M=G.deps;if(!Array.isArray(M)){q.warn(Object.assign({},b(X,["handler"]),{msg:"\u63D2\u4EF6\u7684 deps \u5C5E\u6027\u5FC5\u987B\u662F\u5B57\u7B26\u4E32\u6570\u7EC4"})),J=!0;continue}if(M.some((A)=>typeof A!=="string")){q.warn(Object.assign({},b(X,["handler"]),{msg:"\u63D2\u4EF6\u7684 deps \u5C5E\u6027\u5FC5\u987B\u662F\u5B57\u7B26\u4E32\u6570\u7EC4"})),J=!0;continue}}else{let M=G.deps;if(!Array.isArray(M))G.deps=[]}if(typeof G.handler!=="function"){q.warn(Object.assign({},b(X,["handler"]),{msg:"\u63D2\u4EF6\u7684 handler \u5C5E\u6027\u5FC5\u987B\u662F\u51FD\u6570"})),J=!0;continue}}catch(G){q.error({err:G,item:X,msg:"\u63D2\u4EF6\u89E3\u6790\u5931\u8D25"}),J=!0}if(J)throw Error("\u63D2\u4EF6\u7ED3\u6784\u68C0\u67E5\u5931\u8D25")}a();var TX=["id","created_at","updated_at","deleted_at","state"],jH=new Set(TX),NX=["string","number","text","array_string","array_text","array_number_string","array_number_text"],qH=new Set(NX),vX=["name","type","min","max","default","detail","index","unique","nullable","unsigned","regexp"],BH=new Set(vX),PH=/^_?[a-z][a-z0-9]*(?:[A-Z][a-z0-9]*)*$/,LH=/^[\u4e00-\u9fa5a-zA-Z0-9 _-]+$/,wX=65535;async function DX($){let J=!1;for(let Z of $){if(Z.type!=="table")continue;let X=typeof Z.sourceName==="string"?Z.sourceName:"",G=X?`${X}\u8868 `:"\u8868 ";try{let Y=Z.fileName,W=Z.content||{};if(!PH.test(Y)){q.warn(`${G}${Y} \u6587\u4EF6\u540D\u5FC5\u987B\u4F7F\u7528\u5C0F\u9A7C\u5CF0\u547D\u540D\uFF08\u4F8B\u5982 testCustomers.json\uFF09`),J=!0;continue}for(let[Q,z]of Object.entries(W)){if(typeof z!=="object"||z===null||Array.isArray(z)){q.warn(`${G}${Y} \u6587\u4EF6 ${Q} \u89C4\u5219\u5FC5\u987B\u4E3A\u5BF9\u8C61`),J=!0;continue}if(jH.has(Q))q.warn(`${G}${Y} \u6587\u4EF6\u5305\u542B\u4FDD\u7559\u5B57\u6BB5 ${Q}\uFF0C`+`\u4E0D\u80FD\u5728\u8868\u5B9A\u4E49\u4E2D\u4F7F\u7528\u4EE5\u4E0B\u5B57\u6BB5: ${TX.join(", ")}`),J=!0;let O=z,A=Object.keys(O).filter((D)=>!BH.has(D));if(A.length>0)q.warn(`${G}${Y} \u6587\u4EF6 ${Q} \u5305\u542B\u975E\u6CD5\u5C5E\u6027: ${A.join(", ")}\uFF0C`+`\u5141\u8BB8\u7684\u5C5E\u6027\u4E3A: ${vX.join(", ")}`),J=!0;if(!O.name||typeof O.name!=="string"){q.warn(`${G}${Y} \u6587\u4EF6 ${Q} \u7F3A\u5C11\u5FC5\u586B\u5B57\u6BB5 name \u6216\u7C7B\u578B\u9519\u8BEF`),J=!0;continue}if(!O.type||typeof O.type!=="string"){q.warn(`${G}${Y} \u6587\u4EF6 ${Q} \u7F3A\u5C11\u5FC5\u586B\u5B57\u6BB5 type \u6216\u7C7B\u578B\u9519\u8BEF`),J=!0;continue}if(O.min!==void 0&&!(O.min===null||typeof O.min==="number"))q.warn(`${G}${Y} \u6587\u4EF6 ${Q} \u5B57\u6BB5 min \u7C7B\u578B\u9519\u8BEF\uFF0C\u5FC5\u987B\u4E3A null \u6216\u6570\u5B57`),J=!0;if(O.max!==void 0&&!(O.max===null||typeof O.max==="number"))q.warn(`${G}${Y} \u6587\u4EF6 ${Q} \u5B57\u6BB5 max \u7C7B\u578B\u9519\u8BEF\uFF0C\u5FC5\u987B\u4E3A null \u6216\u6570\u5B57`),J=!0;if(O.detail!==void 0&&typeof O.detail!=="string")q.warn(`${G}${Y} \u6587\u4EF6 ${Q} \u5B57\u6BB5 detail \u7C7B\u578B\u9519\u8BEF\uFF0C\u5FC5\u987B\u4E3A\u5B57\u7B26\u4E32`),J=!0;if(O.index!==void 0&&typeof O.index!=="boolean")q.warn(`${G}${Y} \u6587\u4EF6 ${Q} \u5B57\u6BB5 index \u7C7B\u578B\u9519\u8BEF\uFF0C\u5FC5\u987B\u4E3A\u5E03\u5C14\u503C`),J=!0;if(O.unique!==void 0&&typeof O.unique!=="boolean")q.warn(`${G}${Y} \u6587\u4EF6 ${Q} \u5B57\u6BB5 unique \u7C7B\u578B\u9519\u8BEF\uFF0C\u5FC5\u987B\u4E3A\u5E03\u5C14\u503C`),J=!0;if(O.nullable!==void 0&&typeof O.nullable!=="boolean")q.warn(`${G}${Y} \u6587\u4EF6 ${Q} \u5B57\u6BB5 nullable \u7C7B\u578B\u9519\u8BEF\uFF0C\u5FC5\u987B\u4E3A\u5E03\u5C14\u503C`),J=!0;if(O.unsigned!==void 0&&typeof O.unsigned!=="boolean")q.warn(`${G}${Y} \u6587\u4EF6 ${Q} \u5B57\u6BB5 unsigned \u7C7B\u578B\u9519\u8BEF\uFF0C\u5FC5\u987B\u4E3A\u5E03\u5C14\u503C`),J=!0;if(O.regexp!==void 0&&O.regexp!==null&&typeof O.regexp!=="string")q.warn(`${G}${Y} \u6587\u4EF6 ${Q} \u5B57\u6BB5 regexp \u7C7B\u578B\u9519\u8BEF\uFF0C\u5FC5\u987B\u4E3A null \u6216\u5B57\u7B26\u4E32`),J=!0;let{name:B,type:L,min:C,max:w,default:T}=O;if(!LH.test(B))q.warn(`${G}${Y} \u6587\u4EF6 ${Q} \u5B57\u6BB5\u540D\u79F0 "${B}" \u683C\u5F0F\u9519\u8BEF\uFF0C`+"\u5FC5\u987B\u4E3A\u4E2D\u6587\u3001\u6570\u5B57\u3001\u5B57\u6BCD\u3001\u4E0B\u5212\u7EBF\u3001\u77ED\u6A2A\u7EBF\u3001\u7A7A\u683C"),J=!0;if(!qH.has(L))q.warn(`${G}${Y} \u6587\u4EF6 ${Q} \u5B57\u6BB5\u7C7B\u578B "${L}" \u683C\u5F0F\u9519\u8BEF\uFF0C`+`\u5FC5\u987B\u4E3A${NX.join("\u3001")}\u4E4B\u4E00`),J=!0;if(L!=="number"&&O.unsigned!==void 0)q.warn(`${G}${Y} \u6587\u4EF6 ${Q} \u5B57\u6BB5\u7C7B\u578B\u4E3A ${L}\uFF0C\u4E0D\u5141\u8BB8\u8BBE\u7F6E unsigned\uFF08\u4EC5 number \u7C7B\u578B\u6709\u6548\uFF09`),J=!0;if(O.unique===!0&&O.index===!0)q.warn(`${G}${Y} \u6587\u4EF6 ${Q} \u540C\u65F6\u8BBE\u7F6E\u4E86 unique=true \u548C index=true\uFF0C`+"unique \u548C index \u4E0D\u80FD\u540C\u65F6\u8BBE\u7F6E\uFF0C\u8BF7\u5220\u9664\u5176\u4E00\uFF08\u5426\u5219\u4F1A\u521B\u5EFA\u91CD\u590D\u7D22\u5F15\uFF09"),J=!0;if(C!==void 0&&w!==void 0&&C!==null&&w!==null){if(C>w)q.warn(`${G}${Y} \u6587\u4EF6 ${Q} \u6700\u5C0F\u503C "${C}" \u4E0D\u80FD\u5927\u4E8E\u6700\u5927\u503C "${w}"`),J=!0}if(L==="text"||L==="array_text"||L==="array_number_text"){if(C!==void 0&&C!==null)q.warn(`${G}${Y} \u6587\u4EF6 ${Q} \u7684 ${L} \u7C7B\u578B\u6700\u5C0F\u503C\u5E94\u4E3A null\uFF0C\u5F53\u524D\u4E3A "${C}"`),J=!0;if(w!==void 0&&w!==null)q.warn(`${G}${Y} \u6587\u4EF6 ${Q} \u7684 ${L} \u7C7B\u578B\u6700\u5927\u957F\u5EA6\u5E94\u4E3A null\uFF0C\u5F53\u524D\u4E3A "${w}"`),J=!0;if(T!==void 0&&T!==null)q.warn(`${G}${Y} \u6587\u4EF6 ${Q} \u4E3A ${L} \u7C7B\u578B\uFF0C\u9ED8\u8BA4\u503C\u5FC5\u987B\u4E3A null\uFF0C\u5F53\u524D\u4E3A "${T}"`),J=!0;if(O.index===!0)q.warn(`${G}${Y} \u6587\u4EF6 ${Q} \u4E3A ${L} \u7C7B\u578B\uFF0C\u4E0D\u652F\u6301\u521B\u5EFA\u7D22\u5F15\uFF08index=true \u65E0\u6548\uFF09`),J=!0;if(O.unique===!0)q.warn(`${G}${Y} \u6587\u4EF6 ${Q} \u4E3A ${L} \u7C7B\u578B\uFF0C\u4E0D\u652F\u6301\u552F\u4E00\u7EA6\u675F\uFF08unique=true \u65E0\u6548\uFF09`),J=!0}else if(L==="string"||L==="array_string"||L==="array_number_string"){if(w===void 0||w===null||typeof w!=="number")q.warn(`${G}${Y} \u6587\u4EF6 ${Q} \u4E3A ${L} \u7C7B\u578B\uFF0C`+`\u5FC5\u987B\u8BBE\u7F6E max \u4E14\u7C7B\u578B\u4E3A\u6570\u5B57\uFF1B\u5176\u4E2D array_*_string \u7684 max \u8868\u793A\u5355\u4E2A\u5143\u7D20\u957F\u5EA6\uFF0C\u5F53\u524D\u4E3A "${w}"`),J=!0;else if(w>wX)q.warn(`${G}${Y} \u6587\u4EF6 ${Q} \u6700\u5927\u957F\u5EA6 ${w} \u8D8A\u754C\uFF0C`+`${L} \u7C7B\u578B\u957F\u5EA6\u5FC5\u987B\u5728 1..${wX} \u8303\u56F4\u5185`),J=!0}else if(L==="number"){if(T!==void 0&&T!==null&&typeof T!=="number")q.warn(`${G}${Y} \u6587\u4EF6 ${Q} \u4E3A number \u7C7B\u578B\uFF0C`+`\u9ED8\u8BA4\u503C\u5FC5\u987B\u4E3A\u6570\u5B57\u6216 null\uFF0C\u5F53\u524D\u4E3A "${T}"`),J=!0}}}catch(Y){q.error({msg:`${G}${Z.fileName} \u89E3\u6790\u5931\u8D25`,err:Y}),J=!0}}if(J)throw Error("\u8868\u7ED3\u6784\u68C0\u67E5\u5931\u8D25")}a();var{SQL:kX,RedisClient:SH}=globalThis.Bun;class O${static sqlClient=null;static redisClient=null;static sqlConnectedAt=null;static redisConnectedAt=null;static sqlPoolMax=1;static async connectSql($){let J=$||{},Z=J.type||"mysql",X=J.host||"127.0.0.1",G=J.port||3306,Y=encodeURIComponent(J.username||"root"),W=encodeURIComponent(J.password||"root"),Q=encodeURIComponent(J.database||"befly_demo"),z;if(Z==="sqlite")z=Q;else{if(!X||!Q)throw Error("\u6570\u636E\u5E93\u914D\u7F6E\u4E0D\u5B8C\u6574\uFF0C\u8BF7\u68C0\u67E5\u914D\u7F6E\u53C2\u6570");z=`${Z}://${Y}:${W}@${X}:${G}/${Q}`}let O;if(Z==="sqlite")O=new kX(z);else O=new kX({url:z,max:J.poolMax??1,bigint:!1});try{let A=(async()=>{let L="";if(Z==="sqlite")L=(await O`SELECT sqlite_version() AS version`)?.[0]?.version;else if(Z==="postgresql"||Z==="postgres")L=(await O`SELECT version() AS version`)?.[0]?.version;else L=(await O`SELECT VERSION() AS version`)?.[0]?.version;return L})(),B=new Promise((L,C)=>{setTimeout(()=>{C(Error(`\u6570\u636E\u5E93\u8FDE\u63A5\u8D85\u65F6 (${30000}ms)`))},30000)});return await Promise.race([A,B]),this.sqlClient=O,this.sqlConnectedAt=Date.now(),this.sqlPoolMax=J.poolMax??1,O}catch(M){q.error({err:M,msg:"[Connect] SQL \u8FDE\u63A5\u5931\u8D25"});try{await O?.close()}catch{}throw M}}static async disconnectSql(){if(this.sqlClient){try{await this.sqlClient.close()}catch($){q.error({err:$,msg:"[Connect] \u5173\u95ED SQL \u8FDE\u63A5\u65F6\u51FA\u9519"})}this.sqlClient=null,this.sqlConnectedAt=null}}static getSql(){if(!this.sqlClient)throw Error("SQL \u5BA2\u6237\u7AEF\u672A\u8FDE\u63A5\uFF0C\u8BF7\u5148\u8C03\u7528 Connect.connectSql()");return this.sqlClient}static async connectRedis($){let J=$||{};try{let Z=J.host||"127.0.0.1",X=J.port||6379,G=J.username||"",Y=J.password||"",W=J.db||0,Q="";if(G&&Y)Q=`${G}:${Y}@`;else if(Y)Q=`:${Y}@`;let z=`redis://${Q}${Z}:${X}/${W}`,O=new SH(z,{connectionTimeout:30000,idleTimeout:0,autoReconnect:!0,maxRetries:3,enableOfflineQueue:!0,enableAutoPipelining:!0});return await O.ping(),this.redisClient=O,this.redisConnectedAt=Date.now(),O}catch(Z){throw q.error({err:Z,msg:"[Connect] Redis \u8FDE\u63A5\u5931\u8D25"}),Error(`Redis \u8FDE\u63A5\u5931\u8D25: ${Z.message}`)}}static async disconnectRedis(){if(this.redisClient){try{this.redisClient.close(),this.redisConnectedAt=null}catch($){q.error({err:$,msg:"[Connect] \u5173\u95ED Redis \u8FDE\u63A5\u65F6\u51FA\u9519"})}this.redisClient=null}}static getRedis(){if(!this.redisClient)throw Error("Redis \u5BA2\u6237\u7AEF\u672A\u8FDE\u63A5\uFF0C\u8BF7\u5148\u8C03\u7528 Connect.connectRedis()");return this.redisClient}static async connect($){try{await this.connectSql($.db||{}),await this.connectRedis($.redis||{})}catch(J){let Z=typeof process?.env?.NODE_ENV==="string"?"development":"";throw q.error({env:Z,err:J,msg:"\u6570\u636E\u5E93\u8FDE\u63A5\u521D\u59CB\u5316\u5931\u8D25"}),await this.disconnect(),J}}static async disconnect(){await this.disconnectSql(),await this.disconnectRedis()}static isConnected(){return{sql:this.sqlClient!==null,redis:this.redisClient!==null}}static getStatus(){let $=Date.now();return{sql:{connected:this.sqlClient!==null,connectedAt:this.sqlConnectedAt,uptime:this.sqlConnectedAt?$-this.sqlConnectedAt:null,poolMax:this.sqlPoolMax},redis:{connected:this.redisClient!==null,connectedAt:this.redisConnectedAt,uptime:this.redisConnectedAt?$-this.redisConnectedAt:null}}}static __setMockSql($){this.sqlClient=$}static __setMockRedis($){this.redisClient=$}static __reset(){this.sqlClient=null,this.redisClient=null,this.sqlConnectedAt=null,this.redisConnectedAt=null,this.sqlPoolMax=1}}a();a();async function fX($){let J=new Map;for(let Z of $)try{if(Object.hasOwn(Z,"type")&&Z.type!=="api")continue;let X=Z,G=X.path,Y={name:X.name,handler:X.handler,route:G},W=X.method;if(typeof W==="string"){let A=W.toUpperCase(),B=A==="POST,GET"?"GET,POST":A;Y.method=["GET","POST","GET,POST"].includes(B)?B:"POST"}else Y.method="POST";let Q=X.auth;if(Q!==void 0)Y.auth=Q;let z=X.fields;if(z!==void 0)Y.fields=z;let O=X.required;if(O!==void 0)Y.required=O;let M=X.rawBody;if(M!==void 0)Y.rawBody=M;J.set(G,Y)}catch(X){throw q.error({err:X,api:Z.relativePath,file:Z.filePath,msg:"\u63A5\u53E3\u52A0\u8F7D\u5931\u8D25"}),X}return J}a();n0();function qJ($,J={}){let Z=J.moduleLabel||"\u6A21\u5757",X=J.getName||((A)=>{let B=A.moduleName;if(typeof B==="string"&&B.trim()!=="")return B;return F$(A.fileName)}),G=J.getDeps||((A)=>{let B=A.deps;if(!Array.isArray(B))return[];return B.filter((L)=>typeof L==="string")}),Y=[],W=new Set,Q=new Set,z={},O=!0;for(let A of $){let B=X(A);if(typeof B!=="string"||B.trim()===""){q.error({item:A,msg:`${Z} \u540D\u79F0\u89E3\u6790\u5931\u8D25\uFF08getName \u8FD4\u56DE\u7A7A\u5B57\u7B26\u4E32\uFF09`}),O=!1;continue}if(z[B]){q.error({name:B,first:z[B],second:A,msg:`${Z} \u540D\u79F0\u91CD\u590D\uFF0C\u65E0\u6CD5\u6839\u636E deps \u552F\u4E00\u5B9A\u4F4D`}),O=!1;continue}z[B]=A}if(!O)return!1;for(let A of $){let B=X(A),L=G(A);if(!Array.isArray(L)){q.error({module:B,item:A,msg:`${Z} \u7684 deps \u5FC5\u987B\u662F\u6570\u7EC4`}),O=!1;continue}for(let C of L){if(typeof C!=="string"){q.error({module:B,dependency:C,item:A,msg:`${Z} \u7684 deps \u5FC5\u987B\u662F\u5B57\u7B26\u4E32\u6570\u7EC4`}),O=!1;continue}if(!z[C])q.error({module:B,dependency:C,msg:`${Z} \u4F9D\u8D56\u672A\u627E\u5230`}),O=!1}}if(!O)return!1;let M=(A)=>{if(W.has(A))return;if(Q.has(A)){q.error({module:A,msg:`${Z} \u5FAA\u73AF\u4F9D\u8D56`}),O=!1;return}let B=z[A];if(!B)return;let L=G(B);Q.add(A);for(let C of L)M(C);Q.delete(A),W.add(A),Y.push(B)};for(let A of $){let B=X(A);M(B)}return O?Y:!1}async function yX($){let J=[],Z=$.filter((G)=>{let Y=G.moduleName;if(typeof Y!=="string"||Y.trim()==="")return!1;if((Object.hasOwn(G,"enable")?G.enable:void 0)===!1)return!1;return!0}),X=qJ(Z,{moduleLabel:"\u94A9\u5B50"});if(X===!1)throw Error("\u94A9\u5B50\u4F9D\u8D56\u5173\u7CFB\u9519\u8BEF");for(let G of X){let Y=G.moduleName,W=Object.hasOwn(G,"deps")?G.deps:void 0,Q=Array.isArray(W)?W.filter((M)=>typeof M==="string"):[],z=Object.hasOwn(G,"handler")?G.handler:void 0;if(typeof z!=="function")throw Error(`Hook '${Y}' handler \u5FC5\u987B\u662F\u51FD\u6570`);let O=z;J.push({name:Y,enable:!0,deps:Q,handler:O})}return J}a();async function xX($,J){let Z=[],X=$.filter((Y)=>{let W=Y.moduleName;if(typeof W!=="string"||W.trim()==="")return!1;if((Object.hasOwn(Y,"enable")?Y.enable:void 0)===!1)return!1;return!0}),G=qJ(X,{moduleLabel:"\u63D2\u4EF6"});if(G===!1)throw Error("\u63D2\u4EF6\u4F9D\u8D56\u5173\u7CFB\u9519\u8BEF");for(let Y of G){let W=Y.moduleName,Q=Object.hasOwn(Y,"deps")?Y.deps:void 0,z=Array.isArray(Q)?Q.filter((A)=>typeof A==="string"):[],O=Object.hasOwn(Y,"handler")?Y.handler:void 0;if(typeof O!=="function")throw Error(`\u63D2\u4EF6 '${W}' handler \u5FC5\u987B\u662F\u51FD\u6570`);let M=O;try{let A=await M(J);J[W]=A,Z.push({name:W,enable:!0,deps:z,handler:M})}catch(A){throw q.error({err:A,plugin:W,msg:"\u63D2\u4EF6\u521D\u59CB\u5316\u5931\u8D25"}),A}}return Z}MJ();a();function gX($,J){let Z=$.headers.get("x-forwarded-for");if(typeof Z==="string"&&Z.trim()){let Q=Z.split(",")[0];if(typeof Q==="string"&&Q.trim())return Q.trim()}let X=$.headers.get("x-real-ip");if(typeof X==="string"&&X.trim())return X.trim();let G=$.headers.get("cf-connecting-ip");if(typeof G==="string"&&G.trim())return G.trim();let Y=$.headers.get("x-client-ip");if(typeof Y==="string"&&Y.trim())return Y.trim();let W=$.headers.get("true-client-ip");if(typeof W==="string"&&W.trim())return W.trim();if(J&&typeof J.requestIP==="function"){let Q=J.requestIP($);if(Q&&typeof Q.address==="string"&&Q.address.trim())return Q.address.trim()}return"unknown"}a();function B$($,J,Z=1,X=null,G=null,Y=null){if($.requestId)q.info({event:"request_blocked",reason:J,reasonCode:Y,code:Z,detail:G,msg:"request blocked"});return Response.json({code:Z,msg:J,data:X,detail:G},{headers:$.corsHeaders})}function xZ($){if($.api&&$.requestId)q.info({event:"request_done",msg:"request done"});if($.response)return $.response;if($.result!==void 0){let J=$.result;if(typeof J==="string")J={code:0,msg:J};else if(J&&typeof J==="object"){if(!("code"in J))J={code:0,...J}}if(J&&typeof J==="object"){let Z=JSON.stringify(J,(X,G)=>typeof G==="bigint"?G.toString():G);return new Response(Z,{headers:{...$.corsHeaders,"Content-Type":"application/json"}})}else return Response.json(J,{headers:$.corsHeaders})}return Response.json({code:1,msg:"\u672A\u751F\u6210\u54CD\u5E94"},{headers:$.corsHeaders})}n0();function hX($,J,Z){return async(X,G)=>{let Y=eG(),Q=new URL(X.url).pathname||"/",z=gX(X,G),O=Date.now(),M={method:X.method,body:{},user:{},req:X,now:O,ip:z,headers:X.headers,route:Q,requestId:Y,corsHeaders:{"X-Request-ID":Y}},A=$.get(Q);if(A)M.api=A;return ZX({requestId:Y,method:X.method,route:Q,ip:z,now:O},async()=>{try{for(let B of J)if(await B.handler(Z,M),M.response)return M.response;if(M.api&&X.method!=="OPTIONS"){let B={event:"request",apiName:M.api.name};if(M.body&&Object.keys(M.body).length>0)B.body=M.body;B.msg="request",q.info(B)}if(!M.api){if(X.method!=="OPTIONS")M.response=Response.json({code:1,msg:"\u63A5\u53E3\u4E0D\u5B58\u5728"},{headers:M.corsHeaders})}else if(M.api.handler){let B=await M.api.handler(Z,M);if(B instanceof Response)M.response=B;else M.result=B}return xZ(M)}catch(B){let L=M.api?Q:X.url;return q.error({err:B,path:L,msg:"\u8BF7\u6C42\u9519\u8BEF"}),M.result={code:1,msg:"\u5185\u90E8\u670D\u52A1\u9519\u8BEF"},xZ(M)}})}}q$();a();q$();import{fileURLToPath as CH}from"url";var EH=CH(import.meta.url),P$=IJ(EH);var c4=C$(P$).endsWith("/dist")?P$:d(P$,"dist"),p4=d(P$,"checks"),u4=d(P$,"plugins"),n4=d(P$,"hooks"),m4=d(P$,"apis"),d4=d(P$,"tables"),d0=process.cwd(),s4=d(d0,"checks"),o4=d(d0,"plugins"),l4=d(d0,"hooks"),r4=d(d0,"apis"),i4=d(d0,"tables"),bX=d(d0,"addons");function BJ($,J={}){let Z=J.origin||"*";return{"Access-Control-Allow-Origin":Z==="*"?$.headers.get("origin")||"*":Z,"Access-Control-Allow-Methods":J.methods||"GET, POST, PUT, DELETE, OPTIONS","Access-Control-Allow-Headers":J.allowedHeaders||"Content-Type, Authorization, authorization, token","Access-Control-Expose-Headers":J.exposedHeaders||"Content-Range, X-Content-Range, Authorization, authorization, token","Access-Control-Max-Age":String(J.maxAge||86400),"Access-Control-Allow-Credentials":J.credentials||"true"}}function cX($=void 0){return async(J)=>{let Z=BJ(J,$),X=new URL(J.url),G=d(d0,"public",X.pathname);try{if(J.method==="OPTIONS")return new Response(null,{status:204,headers:Z});let Y=Bun.file(G);if(await Y.exists())return new Response(Y,{headers:{"Content-Type":Y.type||"application/octet-stream",...Z}});else return Response.json({code:1,msg:"\u6587\u4EF6\u672A\u627E\u5230"},{headers:Z})}catch(Y){return q.error({err:Y,msg:"\u9759\u6001\u6587\u4EF6\u5904\u7406\u5931\u8D25"}),Response.json({code:1,msg:"\u6587\u4EF6\u8BFB\u53D6\u5931\u8D25"},{headers:Z})}}}a();n0();var wH=($)=>{let J=$.split("/").map((Y)=>Y.trim()).filter((Y)=>Y.length>0),X=(J[1]||"")==="addon"?4:3,G=J.slice(0,Math.min(X,J.length));if(G.length===0)return"";return`/${G.join("/")}`};async function pX($,J){if(!$.db)throw Error("syncApi: ctx.db \u672A\u521D\u59CB\u5316\uFF08Db \u63D2\u4EF6\u672A\u52A0\u8F7D\u6216\u6CE8\u5165\u5931\u8D25\uFF09");if(!$.cache)throw Error("syncApi: ctx.cache \u672A\u521D\u59CB\u5316\uFF08cache \u63D2\u4EF6\u672A\u52A0\u8F7D\u6216\u6CE8\u5165\u5931\u8D25\uFF09");if(!(await $.db.tableExists("addon_admin_api")).data){q.debug(`${"addon_admin_api"} \u8868\u4E0D\u5B58\u5728`);return}let G=(await $.db.getAll({table:"addon_admin_api",fields:["id","path","parentPath","name","addonName","auth","state"],where:{state$gte:0}})).data.lists||[],Y=aG(G,(M)=>M.path),W=[],Q=[],z=[],O=new Set;for(let M of J){if(M.type!=="api")continue;let A=M,B=A.path,L=A.name,C=A.addonName;if(typeof B!=="string"||B.trim()==="")continue;if(typeof L!=="string"||L.trim()==="")continue;let w=typeof C==="string"?C:"",T=A.auth,D=T===!1||T===0?0:1,E=wH(B);O.add(B);let N=Y[B];if(N){if(L!==N.name||B!==N.path||w!==N.addonName||E!==N.parentPath||D!==N.auth)Q.push({id:N.id,name:L,path:B,parentPath:E,addonName:w,auth:D})}else W.push({name:L,path:B,parentPath:E,addonName:w,auth:D})}for(let M of G)if(!O.has(M.path))z.push(M.id);if(Q.length>0)try{await $.db.updBatch("addon_admin_api",Q.map((M)=>{return{id:M.id,data:{name:M.name,path:M.path,parentPath:M.parentPath,addonName:M.addonName,auth:M.auth}}}))}catch(M){q.error({err:M,msg:"\u540C\u6B65\u63A5\u53E3\u6279\u91CF\u66F4\u65B0\u5931\u8D25"})}if(W.length>0)try{await $.db.insBatch("addon_admin_api",W.map((M)=>{return{name:M.name,path:M.path,parentPath:M.parentPath,addonName:M.addonName,auth:M.auth}}))}catch(M){q.error({err:M,msg:"\u540C\u6B65\u63A5\u53E3\u6279\u91CF\u65B0\u589E\u5931\u8D25"})}if(z.length>0)try{await $.db.delForceBatch("addon_admin_api",z)}catch(M){q.error({err:M,msg:"\u540C\u6B65\u63A5\u53E3\u6279\u91CF\u5220\u9664\u5931\u8D25"})}}async function uX($){if(!$.cache)throw Error("syncCache: ctx.cache \u672A\u521D\u59CB\u5316\uFF08cache \u63D2\u4EF6\u672A\u52A0\u8F7D\u6216\u6CE8\u5165\u5931\u8D25\uFF09");await $.cache.cacheApis(),await $.cache.cacheMenus(),await $.cache.rebuildRoleApiPermissions()}import{createSign as TH}from"crypto";class g${static md5($,J="hex"){let Z=new Bun.CryptoHasher("md5");return Z.update($),Z.digest(J)}static hmacMd5($,J,Z="hex"){let X=new Bun.CryptoHasher("md5",$);return X.update(J),X.digest(Z)}static sha1($,J="hex"){let Z=new Bun.CryptoHasher("sha1");return Z.update($),Z.digest(J)}static hmacSha1($,J,Z="hex"){let X=new Bun.CryptoHasher("sha1",$);return X.update(J),X.digest(Z)}static sha256($,J="hex"){let Z=new Bun.CryptoHasher("sha256");return Z.update($),Z.digest(J)}static rsaSha256($,J,Z="hex"){let X=TH("RSA-SHA256");return X.update($),X.sign(J,Z)}static hmacSha256($,J,Z="hex"){let X=new Bun.CryptoHasher("sha256",$);return X.update(J),X.digest(Z)}static sha512($,J="hex"){let Z=new Bun.CryptoHasher("sha512");return Z.update($),Z.digest(J)}static hmacSha512($,J,Z="hex"){let X=new Bun.CryptoHasher("sha512",$);return X.update(J),X.digest(Z)}static hash($,J,Z="hex"){let X=new Bun.CryptoHasher($);return X.update(J),X.digest(Z)}static hmac($,J,Z,X="hex"){let G=new Bun.CryptoHasher($,J);return G.update(Z),G.digest(X)}static async hashFile($,J="sha256",Z="hex"){let X=Bun.file($),G=new Bun.CryptoHasher(J),W=X.stream().getReader();try{while(!0){let{done:Q,value:z}=await W.read();if(Q)break;G.update(z)}return G.digest(Z)}finally{W.releaseLock()}}static async hashPassword($,J={}){let Z=Object.assign({},J,{algorithm:"bcrypt"});return await Bun.password.hash($,Z)}static async verifyPassword($,J){return await Bun.password.verify($,J)}static base64Encode($){return Buffer.from($,"utf8").toString("base64")}static base64Decode($){return Buffer.from($,"base64").toString("utf8")}static randomString($){let J=Math.ceil($/2),Z=crypto.getRandomValues(new Uint8Array(J)),X="";for(let G=0;G<Z.length;G++)X+=Z[G].toString(16).padStart(2,"0");return X.slice(0,$)}static fastHash($,J=0){let Z=Bun.hash($,J);return typeof Z==="bigint"?Number(Z):Z}}a();async function nX($,J={}){if(!J.devPassword)return;if(!$.db)throw Error("syncDev: ctx.db \u672A\u521D\u59CB\u5316\uFF08Db \u63D2\u4EF6\u672A\u52A0\u8F7D\u6216\u6CE8\u5165\u5931\u8D25\uFF09");if(!$.cache)throw Error("syncDev: ctx.cache \u672A\u521D\u59CB\u5316\uFF08cache \u63D2\u4EF6\u672A\u52A0\u8F7D\u6216\u6CE8\u5165\u5931\u8D25\uFF09");if(!(await $.db.tableExists("addon_admin_admin")).data){q.debug("addon_admin_admin \u8868\u4E0D\u5B58\u5728");return}if(!(await $.db.tableExists("addon_admin_role")).data){q.debug("addon_admin_role \u8868\u4E0D\u5B58\u5728");return}if(!(await $.db.tableExists("addon_admin_menu")).data){q.debug("addon_admin_menu \u8868\u4E0D\u5B58\u5728");return}if(!(await $.db.tableExists("addon_admin_api")).data){q.debug("addon_admin_api \u8868\u4E0D\u5B58\u5728");return}let Z=await $.db.getAll({table:"addon_admin_menu",fields:["path"],where:{state$gte:0},orderBy:["id#ASC"]}),X=await $.db.getAll({table:"addon_admin_api",fields:["path"],where:{state$gte:0},orderBy:["id#ASC"]}),G=await $.db.getOne({table:"addon_admin_role",where:{code:"dev"}}),Y={code:"dev",name:"\u5F00\u53D1\u8005\u89D2\u8272",description:"\u62E5\u6709\u6240\u6709\u83DC\u5355\u548C\u63A5\u53E3\u6743\u9650\u7684\u5F00\u53D1\u8005\u89D2\u8272",menus:Z.data.lists.map((O)=>O.path).filter((O)=>typeof O==="string"&&O.length>0),apis:X.data.lists.map((O)=>O.path).filter((O)=>typeof O==="string"&&O.length>0),sort:0};if(typeof G.data.id==="number")await $.db.updData({table:"addon_admin_role",where:{code:"dev"},data:{name:Y.name,description:Y.description,menus:Y.menus,apis:Y.apis,sort:Y.sort}});else await $.db.insData({table:"addon_admin_role",data:Y});let W={nickname:"\u5F00\u53D1\u8005",email:J.devEmail||"dev@qq.com",username:"dev",password:await g$.hashPassword(g$.sha256(J.devPassword+"befly")),roleCode:"dev",roleType:"admin"};if(typeof(await $.db.getOne({table:"addon_admin_admin",where:{username:"dev"}})).data.id==="number")await $.db.updData({table:"addon_admin_admin",where:{username:"dev"},data:{nickname:W.nickname,email:W.email,username:W.username,password:W.password,roleCode:W.roleCode,roleType:W.roleType}});else await $.db.insData({table:"addon_admin_admin",data:W});let z=[{code:"user",name:"\u7528\u6237\u89D2\u8272",description:"\u666E\u901A\u7528\u6237\u89D2\u8272",sort:1},{code:"admin",name:"\u7BA1\u7406\u5458\u89D2\u8272",description:"\u7BA1\u7406\u5458\u89D2\u8272",sort:2},{code:"guest",name:"\u8BBF\u5BA2\u89D2\u8272",description:"\u8BBF\u5BA2\u89D2\u8272",sort:3}];for(let O of z)if((await $.db.getOne({table:"addon_admin_role",where:{code:O.code}})).data?.id)await $.db.updData({table:"addon_admin_role",where:{code:O.code},data:{name:O.name,description:O.description,sort:O.sort}});else await $.db.insData({table:"addon_admin_role",data:{code:O.code,name:O.name,description:O.description,sort:O.sort}})}a();yZ();function NH($){let J=$.config?.disableMenus,Z=Array.isArray(J)?J:[],X=[];for(let Y of Z){if(typeof Y!=="string")continue;let W=Y.trim();if(!W)continue;X.push(W)}if(X.length===0)return()=>!1;let G=X.map((Y)=>new Bun.Glob(Y));return(Y)=>{if(typeof Y!=="string")return!1;let W=Y.trim();if(!W)return!1;let Q=[];if(Q.push(W),W.startsWith("/"))Q.push(W.slice(1));else Q.push(`/${W}`);for(let z of G){let O=typeof z==="object"&&z!==null&&"match"in z?z.match:void 0;if(typeof O!=="function")throw Error("syncMenu: \u5F53\u524D Bun \u7248\u672C\u4E0D\u652F\u6301 Bun.Glob.match\uFF0C\u65E0\u6CD5\u6309 disableMenus \u505A glob \u5339\u914D");let M=O;for(let A of Q)if(M.call(z,A))return!0}return!1}}function mX($,J){let Z=[];for(let X of $){if(X===null||typeof X!=="object")continue;let G=typeof X.path==="string"?String(X.path).trim():"";if(G&&J(G))continue;let Y=X.children,W=Array.isArray(Y)&&Y.length>0?mX(Y,J):[],Q={};if(typeof X.name==="string")Q.name=X.name;if(typeof X.path==="string")Q.path=X.path;if(typeof X.sort==="number")Q.sort=X.sort;if(typeof X.parentPath==="string")Q.parentPath=X.parentPath;if(W.length>0)Q.children=W;Z.push(Q)}return Z}function vH($){let J=new Map,Z=[];for(let X of $)Z.push({menu:X,parentPathFromTree:""});while(Z.length>0){let X=Z.pop(),G=X?X.menu:null;if(!G)continue;let Y=typeof G.path==="string"?G.path:"",W=G.children;if(W&&Array.isArray(W)&&W.length>0){let A=typeof Y==="string"?Y:"";for(let B of W)Z.push({menu:B,parentPathFromTree:A})}if(!Y)continue;let Q=typeof G.name==="string"?G.name:"";if(!Q)continue;let z=typeof G.sort==="number"?G.sort:999999,M=typeof G.parentPath==="string"?G.parentPath:typeof X?.parentPathFromTree==="string"?X.parentPathFromTree:PX(Y);J.set(Y,{path:Y,name:Q,sort:z,parentPath:M})}return J}async function dX($,J){if(!$.db)throw Error("syncMenu: ctx.db \u672A\u521D\u59CB\u5316\uFF08Db \u63D2\u4EF6\u672A\u52A0\u8F7D\u6216\u6CE8\u5165\u5931\u8D25\uFF09");if(!$.cache)throw Error("syncMenu: ctx.cache \u672A\u521D\u59CB\u5316\uFF08cache \u63D2\u4EF6\u672A\u52A0\u8F7D\u6216\u6CE8\u5165\u5931\u8D25\uFF09");if(!$.config)throw Error("syncMenu: ctx.config \u672A\u521D\u59CB\u5316\uFF08config \u63D2\u4EF6\u672A\u52A0\u8F7D\u6216\u6CE8\u5165\u5931\u8D25\uFF09");if(!(await $.db.tableExists("addon_admin_menu")).data){q.debug("addon_admin_menu \u8868\u4E0D\u5B58\u5728");return}let Z=NH($),X=mX(J,Z),G=vH(X),Y=new Set;for(let Q of G.keys())Y.add(Q);let W="addon_admin_menu";await $.db.trans(async(Q)=>{let O=(await Q.getAll({table:W,fields:["id","name","path","parentPath","sort","state"]})).data.lists||[],M=O.filter((E)=>typeof E?.state==="number"&&E.state>=0),A=new Map,B=new Set,L=new Map;for(let E of M){if(typeof E?.path!=="string"||!E.path)continue;if(typeof E?.id!=="number")continue;if(Z(E.path))continue;let N=A.get(E.path);if(!N){A.set(E.path,E);continue}let h=typeof N?.id==="number"?N.id:0,v=E.id;if(v>h){if(A.set(E.path,E),h>0)B.add(h);let p=L.get(E.path)||{keptId:v,removedIds:[]};if(p.keptId=v,h>0)p.removedIds.push(h);L.set(E.path,p)}else{if(v>0)B.add(v);let p=L.get(E.path)||{keptId:h,removedIds:[]};if(p.keptId=h,v>0)p.removedIds.push(v);L.set(E.path,p)}}if(L.size>0){let E=[];for(let N of L.entries()){let h=N[0],v=N[1];if(E.push({path:h,keptId:v.keptId,removedIds:v.removedIds}),E.length>=10)break}q.warn({table:W,duplicatePaths:L.size,duplicateIds:B.size,examples:E,msg:"addon_admin_menu \u68C0\u6D4B\u5230\u91CD\u590D path \u8BB0\u5F55\uFF1A\u5DF2\u4FDD\u7559 id \u6700\u5927\u7684\u4E00\u6761\u5E76\u5220\u9664\u5176\u4F59\u8BB0\u5F55"})}let C=[],w=[];for(let E of G.values()){let N=A.get(E.path);if(N){let h=typeof N.parentPath==="string"?N.parentPath:"";if(N.name!==E.name||N.sort!==E.sort||h!==E.parentPath)C.push({id:N.id,data:{name:E.name,path:E.path,parentPath:E.parentPath,sort:E.sort}})}else w.push({name:E.name,path:E.path,parentPath:E.parentPath,sort:E.sort})}if(C.length>0)await Q.updBatch(W,C);if(w.length>0)await Q.insBatch(W,w);let T=new Set;for(let E of M){if(typeof E?.path!=="string"||!E.path)continue;if(!Y.has(E.path)){if(typeof E?.id==="number")T.add(E.id)}}for(let E of B)if(typeof E==="number"&&E>0)T.add(E);for(let E of O){if(typeof E?.path!=="string"||!E.path)continue;if(!Z(E.path))continue;if(typeof E?.id==="number"&&E.id>0)T.add(E.id)}let D=Array.from(T);if(D.length>0)await Q.delForceBatch(W,D)})}class G0{static apisAll(){return"apis:all"}static menusAll(){return"menus:all"}static roleInfo($){return`role:info:${$}`}static roleApis($){return`role:apis:${$}`}static tableColumns($){return`table:columns:${$}`}}var h$=null;function b$($){let J=Error(`\u672A\u77E5\u6570\u636E\u5E93\u65B9\u8A00: ${String($)}`);if($!=="mysql"&&$!=="postgresql"&&$!=="sqlite")throw J;if(!h$)h$=new Map,h$.set("mysql",new LJ),h$.set("postgresql",new sX),h$.set("sqlite",new oX);let Z=h$.get($);if(!Z)throw J;return Z}function PJ($){if($.dialect==="mysql")return{columns:{sql:"SELECT COLUMN_NAME, DATA_TYPE, CHARACTER_MAXIMUM_LENGTH, IS_NULLABLE, COLUMN_DEFAULT, COLUMN_COMMENT, COLUMN_TYPE FROM information_schema.COLUMNS WHERE TABLE_SCHEMA = ? AND TABLE_NAME = ? ORDER BY ORDINAL_POSITION",params:[$.dbName,$.table]}};if($.dialect==="postgresql"){let X=$.schema&&$.schema.trim()!==""?$.schema:"public",G={sql:"SELECT column_name, data_type, character_maximum_length, is_nullable, column_default FROM information_schema.columns WHERE table_schema = ? AND table_name = ? ORDER BY ordinal_position",params:[X,$.table]},Y={sql:"SELECT a.attname AS column_name, col_description(c.oid, a.attnum) AS column_comment FROM pg_class c JOIN pg_attribute a ON a.attrelid = c.oid JOIN pg_namespace n ON n.oid = c.relnamespace WHERE c.relkind = 'r' AND n.nspname = ? AND c.relname = ? AND a.attnum > 0",params:[X,$.table]};return{columns:G,comments:Y}}return{columns:b$("sqlite").getTableColumnsQuery($.table)}}function gZ($){if($.dialect==="mysql")return{sql:"SELECT INDEX_NAME, COLUMN_NAME FROM information_schema.STATISTICS WHERE TABLE_SCHEMA = ? AND TABLE_NAME = ? AND INDEX_NAME != 'PRIMARY' ORDER BY INDEX_NAME",params:[$.dbName,$.table]};if($.dialect==="postgresql")return{sql:"SELECT indexname, indexdef FROM pg_indexes WHERE schemaname = ? AND tablename = ?",params:[$.schema&&$.schema.trim()!==""?$.schema:"public",$.table]};throw Error(`getSyncTableIndexesQuery \u4E0D\u652F\u6301\u65B9\u8A00: ${String($.dialect)}`)}class LJ{name="mysql";supportsSchema=!0;quoteIdent($){if(typeof $!=="string")throw Error(`quoteIdent \u9700\u8981\u5B57\u7B26\u4E32\u7C7B\u578B\u6807\u8BC6\u7B26 (identifier: ${String($)})`);let J=$.trim();if(!/^[a-zA-Z_][a-zA-Z0-9_]*$/.test(J))throw Error(`\u65E0\u6548\u7684 SQL \u6807\u8BC6\u7B26: ${J}`);return`\`${J}\``}getTableColumnsQuery($,J){return{sql:`SHOW COLUMNS FROM ${this.quoteIdent($)}`,params:[]}}getTableColumnsFromResult($){let J=[];for(let Z of $){let X=Z.Field;if(typeof X==="string"&&X.length>0)J.push(X)}return J}tableExistsQuery($,J){if(typeof J==="string"&&J.trim()!=="")return{sql:"SELECT COUNT(*) as count FROM information_schema.TABLES WHERE TABLE_SCHEMA = ? AND TABLE_NAME = ?",params:[J,$]};return{sql:"SELECT COUNT(*) as count FROM information_schema.TABLES WHERE TABLE_SCHEMA = DATABASE() AND TABLE_NAME = ?",params:[$]}}}class sX{name="postgresql";supportsSchema=!0;quoteIdent($){if(typeof $!=="string")throw Error(`quoteIdent \u9700\u8981\u5B57\u7B26\u4E32\u7C7B\u578B\u6807\u8BC6\u7B26 (identifier: ${String($)})`);let J=$.trim();if(!/^[a-zA-Z_][a-zA-Z0-9_]*$/.test(J))throw Error(`\u65E0\u6548\u7684 SQL \u6807\u8BC6\u7B26: ${J}`);return`"${J}"`}getTableColumnsQuery($,J){if(typeof J==="string"&&J.trim()!=="")return{sql:"SELECT column_name FROM information_schema.columns WHERE table_schema = ? AND table_name = ? ORDER BY ordinal_position",params:[J,$]};return{sql:"SELECT column_name FROM information_schema.columns WHERE table_schema = current_schema() AND table_name = ? ORDER BY ordinal_position",params:[$]}}getTableColumnsFromResult($){let J=[];for(let Z of $){let X=Z.column_name;if(typeof X==="string"&&X.length>0)J.push(X)}return J}tableExistsQuery($,J){if(typeof J==="string"&&J.trim()!=="")return{sql:"SELECT COUNT(*)::int as count FROM information_schema.tables WHERE table_schema = ? AND table_name = ?",params:[J,$]};return{sql:"SELECT COUNT(*)::int as count FROM information_schema.tables WHERE table_schema = current_schema() AND table_name = ?",params:[$]}}}class oX{name="sqlite";supportsSchema=!1;quoteIdent($){if(typeof $!=="string")throw Error(`quoteIdent \u9700\u8981\u5B57\u7B26\u4E32\u7C7B\u578B\u6807\u8BC6\u7B26 (identifier: ${String($)})`);let J=$.trim();if(!/^[a-zA-Z_][a-zA-Z0-9_]*$/.test(J))throw Error(`\u65E0\u6548\u7684 SQL \u6807\u8BC6\u7B26: ${J}`);return`"${J}"`}getTableColumnsQuery($,J){return{sql:`PRAGMA table_info(${this.quoteIdent($)})`,params:[]}}getTableColumnsFromResult($){let J=[];for(let Z of $){let X=Z.name;if(typeof X==="string"&&X.length>0)J.push(X)}return J}tableExistsQuery($,J){return{sql:"SELECT COUNT(*) as count FROM sqlite_master WHERE type = 'table' AND name = ?",params:[$]}}}a();function H$($){return{name:$.name,type:$.type,detail:$.detail??"",min:$.min??null,max:$.max??null,default:$.default??null,index:$.index??!1,unique:$.unique??!1,nullable:$.nullable??!1,unsigned:$.unsigned??!1,regexp:$.regexp??null}}n0();var EJ=async($,J)=>{try{let Z=[];if(!Array.isArray(J))throw Error("syncTable(items) \u53C2\u6570\u5FC5\u987B\u662F\u6570\u7EC4");if(!$)throw Error("syncTable(ctx, items) \u7F3A\u5C11 ctx");if(!$.db)throw Error("syncTable(ctx, items) \u7F3A\u5C11 ctx.db");if(!$.redis)throw Error("syncTable(ctx, items) \u7F3A\u5C11 ctx.redis");if(!$.config)throw Error("syncTable(ctx, items) \u7F3A\u5C11 ctx.config");let X=String($.config.db?.type||"mysql").toLowerCase(),G="mysql";if(X==="postgres"||X==="postgresql")G="postgresql";else if(X==="sqlite")G="sqlite";await DH(G,$.db);let Y=$.config.db?.database||"",W={dbDialect:G,db:$.db,dbName:Y};for(let Q of J){if(!Q||Q.type!=="table")continue;if(Q.source!=="app"&&Q.source!=="addon"&&Q.source!=="core"){q.warn(`syncTable \u8DF3\u8FC7\u672A\u77E5\u6765\u6E90\u8868\u5B9A\u4E49: source=${String(Q.source)} fileName=${String(Q.fileName)}`);continue}let z=x(Q.fileName),O=z;if(Q.source==="addon"){if(!Q.addonName||String(Q.addonName).trim()==="")throw Error(`syncTable addon \u8868\u7F3A\u5C11 addonName: fileName=${String(Q.fileName)}`);O=`addon_${x(Q.addonName)}_${z}`}let M=Q.content;if(!M||typeof M!=="object")throw Error(`syncTable \u8868\u5B9A\u4E49\u65E0\u6548: table=${O}`);for(let L of Object.values(M))eX(L);let A=await X1(W,O),B=M;if(A)await yH(W,O,B);else await H1(W,O,B);Z.push(O)}if(Z.length>0){let Q=Z.map((z)=>G0.tableColumns(z));await $.redis.delBatch(Q)}}catch(Z){throw q.error({err:Z,msg:"\u6570\u636E\u5E93\u540C\u6B65\u5931\u8D25"}),Z}},E$={MYSQL_MIN_MAJOR:8,POSTGRES_MIN_MAJOR:17,SQLITE_MIN_VERSION:"3.50.0",SQLITE_MIN_VERSION_NUM:35000},rX={length:"\u957F\u5EA6",datatype:"\u7C7B\u578B",comment:"\u6CE8\u91CA",default:"\u9ED8\u8BA4\u503C",nullable:"\u53EF\u7A7A\u7EA6\u675F",unique:"\u552F\u4E00\u7EA6\u675F"},iX={ENGINE:"InnoDB",CHARSET:"utf8mb4",COLLATE:"utf8mb4_0900_ai_ci"},XJ=[{name:"id",comment:"\u4E3B\u952EID",needsIndex:!1,mysqlDdl:"BIGINT UNSIGNED PRIMARY KEY AUTO_INCREMENT",pgDdl:"BIGINT GENERATED BY DEFAULT AS IDENTITY PRIMARY KEY",sqliteDdl:"INTEGER PRIMARY KEY"},{name:"created_at",comment:"\u521B\u5EFA\u65F6\u95F4",needsIndex:!0,mysqlDdl:"BIGINT UNSIGNED NOT NULL DEFAULT 0",pgDdl:"BIGINT NOT NULL DEFAULT 0",sqliteDdl:"INTEGER NOT NULL DEFAULT 0"},{name:"updated_at",comment:"\u66F4\u65B0\u65F6\u95F4",needsIndex:!0,mysqlDdl:"BIGINT UNSIGNED NOT NULL DEFAULT 0",pgDdl:"BIGINT NOT NULL DEFAULT 0",sqliteDdl:"INTEGER NOT NULL DEFAULT 0"},{name:"deleted_at",comment:"\u5220\u9664\u65F6\u95F4",needsIndex:!1,mysqlDdl:"BIGINT UNSIGNED NOT NULL DEFAULT 0",pgDdl:"BIGINT NOT NULL DEFAULT 0",sqliteDdl:"INTEGER NOT NULL DEFAULT 0"},{name:"state",comment:"\u72B6\u6001\u5B57\u6BB5",needsIndex:!0,mysqlDdl:"BIGINT UNSIGNED NOT NULL DEFAULT 1",pgDdl:"BIGINT NOT NULL DEFAULT 1",sqliteDdl:"INTEGER NOT NULL DEFAULT 1"}],cZ=XJ.filter(($)=>$.needsIndex).map(($)=>$.name),tX={};for(let $ of XJ)tX[$.name]=$;var aX={DB_VERSION_REQUIREMENTS:E$,CHANGE_TYPE_LABELS:rX,MYSQL_TABLE_CONFIG:iX,SYSTEM_INDEX_FIELDS:cZ,getTypeMapping:wJ,quoteIdentifier:X0,escapeComment:TJ,applyFieldDefaults:eX,isStringOrArrayType:GJ,getSqlType:pZ,resolveDefaultValue:YJ,generateDefaultSql:NJ,buildIndexSQL:CJ,buildSystemColumnDefs:J1,buildBusinessColumnDefs:Z1,generateDDLClause:bZ,isCompatibleTypeChange:G1,compareFieldDefinition:W1,tableExistsRuntime:X1,getTableColumnsRuntime:Y1,getTableIndexesRuntime:uZ,createRuntime:($,J,Z="")=>{return{dbDialect:$,db:J,dbName:Z}}};EJ.TestKit=aX;Object.defineProperty(EJ,"TestKit",{value:aX,writable:!1,enumerable:!0,configurable:!1});function wJ($){return{number:$==="sqlite"?"INTEGER":$==="postgresql"?"BIGINT":"BIGINT",string:$==="sqlite"?"TEXT":$==="postgresql"?"character varying":"VARCHAR",text:$==="mysql"?"MEDIUMTEXT":"TEXT",array_string:$==="sqlite"?"TEXT":$==="postgresql"?"character varying":"VARCHAR",array_text:$==="mysql"?"MEDIUMTEXT":"TEXT",array_number_string:$==="sqlite"?"TEXT":$==="postgresql"?"character varying":"VARCHAR",array_number_text:$==="mysql"?"MEDIUMTEXT":"TEXT"}}function X0($,J){return b$($).quoteIdent(J)}function TJ($){return String($).replace(/"/g,"\\\"")}function SJ($){if($===null)return null;if(typeof $==="string"||typeof $==="number"||typeof $==="boolean")return $;if(Array.isArray($)){let J=[];for(let Z of $)J.push(SJ(Z));return J}return String($)}function hZ($){if($===null)return!0;if(typeof $==="string"||typeof $==="number"||typeof $==="boolean")return!0;if(Array.isArray($))return $.every((J)=>hZ(J));if(typeof $==="object"){for(let J of Object.values($)){if(J===void 0)continue;if(!hZ(J))return!1}return!0}return!1}function eX($){if(!$||typeof $!=="object")return;let J=$,Z=J.name,X=J.type;if(typeof Z!=="string"||typeof X!=="string")return;let{min:G,max:Y,default:W,detail:Q,index:z,unique:O,nullable:M,unsigned:A,regexp:B}=J,L={name:Z,type:X};if(typeof Q==="string")L.detail=Q;if(typeof G==="number"||G===null)L.min=G;if(typeof Y==="number"||Y===null)L.max=Y;if(W===null)L.default=null;else if(hZ(W))L.default=W;if(typeof z==="boolean")L.index=z;if(typeof O==="boolean")L.unique=O;if(typeof M==="boolean")L.nullable=M;if(typeof A==="boolean")L.unsigned=A;if(typeof B==="string"||B===null)L.regexp=B;let C=H$(L);J.detail=C.detail,J.min=C.min,J.max=C.max,J.default=C.default,J.index=C.index,J.unique=C.unique,J.nullable=C.nullable,J.unsigned=C.unsigned,J.regexp=C.regexp}function GJ($){return $==="string"||$==="array_string"||$==="array_number_string"}function pZ($,J,Z,X=!1){let G=wJ($);if(GJ(J))return`${G[J]}(${Z})`;let Y=G[J]||"TEXT";if($==="mysql"&&J==="number"&&X)return`${Y} UNSIGNED`;return Y}function YJ($,J){if($!==null&&$!=="null")return $;switch(J){case"number":return 0;case"string":return"";case"array_string":case"array_number_string":return"[]";case"text":case"array_text":case"array_number_text":return"null";default:return $}}function NJ($,J){if(J==="text"||J==="array_text"||$==="null")return"";if(J==="number"||J==="string"||J==="array_string"||J==="array_number_string")if(typeof $==="number"&&!Number.isNaN($))return` DEFAULT ${$}`;else return` DEFAULT '${String($).replace(/'/g,"''")}'`;return""}function CJ($,J,Z,X,G){let Y=X0($,J),W=X0($,Z),Q=X0($,X);if($==="mysql"){let z=[];if(G==="create")z.push(`ADD INDEX ${W} (${Q})`);else z.push(`DROP INDEX ${W}`);return`ALTER TABLE ${Y} ALGORITHM=INPLACE, LOCK=NONE, ${z.join(", ")}`}if($==="postgresql"){if(G==="create")return`CREATE INDEX CONCURRENTLY IF NOT EXISTS ${W} ON ${Y}(${Q})`;return`DROP INDEX CONCURRENTLY IF EXISTS ${W}`}if(G==="create")return`CREATE INDEX IF NOT EXISTS ${W} ON ${Y}(${Q})`;return`DROP INDEX IF EXISTS ${W}`}function $1($,J){let Z=tX[J];if(!Z)return null;let X=X0($,Z.name);if($==="mysql")return`${X} ${Z.mysqlDdl} COMMENT "${TJ(Z.comment)}"`;if($==="postgresql")return`${X} ${Z.pgDdl}`;return`${X} ${Z.sqliteDdl}`}function J1($){let J=[];for(let Z of XJ){let X=$1($,Z.name);if(X)J.push(X)}return J}function Z1($,J){let Z=[];for(let[X,G]of Object.entries(J)){let Y=H$(G),W=x(X),Q=X0($,W),z=pZ($,Y.type,Y.max,Y.unsigned),O=YJ(Y.default,Y.type),M=NJ(O,Y.type),A=Y.unique?" UNIQUE":"",B=Y.nullable?" NULL":" NOT NULL";if($==="mysql")Z.push(`${Q} ${z}${A}${B}${M} COMMENT "${TJ(Y.name)}"`);else Z.push(`${Q} ${z}${A}${B}${M}`)}return Z}function bZ($,J,Z,X=!1){let G=x(J),Y=X0($,G),W=H$(Z),Q=pZ($,W.type,W.max,W.unsigned),z=YJ(W.default,W.type),O=NJ(z,W.type),M=W.unique?" UNIQUE":"",A=W.nullable?" NULL":" NOT NULL";if($==="mysql")return`${X?"ADD COLUMN":"MODIFY COLUMN"} ${Y} ${Q}${M}${A}${O} COMMENT "${TJ(W.name)}"`;if($==="postgresql"){if(X)return`ADD COLUMN IF NOT EXISTS ${Y} ${Q}${M}${A}${O}`;return`ALTER COLUMN ${Y} TYPE ${Q}`}if(X)return`ADD COLUMN IF NOT EXISTS ${Y} ${Q}${M}${A}${O}`;return""}async function lX($,J){try{return await $.unsafe(J),!0}catch(Z){if(J.includes("ALGORITHM=INSTANT")){let X=J.replace(/ALGORITHM=INSTANT/g,"ALGORITHM=INPLACE");try{return await $.unsafe(X),!0}catch{let G=J;return G=G.replace(/\bALGORITHM\s*=\s*(INPLACE|INSTANT)\b\s*,?\s*/g,"").replace(/\bLOCK\s*=\s*(NONE|SHARED|EXCLUSIVE)\b\s*,?\s*/g,""),G=G.replace(/,\s*,/g,", ").replace(/,\s*$/g,"").replace(/\s{2,}/g," ").trim(),await $.unsafe(G),!0}}else throw Z}}function G1($,J){let Z=String($||"").toLowerCase(),X=String(J||"").toLowerCase();if(Z===X)return!1;let G=Z.replace(/\s*unsigned/gi,"").replace(/\([^)]*\)/g,"").trim(),Y=X.replace(/\s*unsigned/gi,"").replace(/\([^)]*\)/g,"").trim(),W=["tinyint","smallint","mediumint","int","integer","bigint"],Q=W.indexOf(G),z=W.indexOf(Y);if(Q!==-1&&z!==-1&&z>Q)return!0;if(G==="varchar"&&(Y==="text"||Y==="mediumtext"||Y==="longtext"))return!0;if(G==="character varying"&&Y==="text")return!0;return!1}async function X1($,J){let Z=$.db;if(!Z)throw Error("SQL \u6267\u884C\u5668\u672A\u521D\u59CB\u5316");try{let X=void 0;if($.dbDialect==="mysql")X=$.dbName;else if($.dbDialect==="postgresql")X="public";let G=b$($.dbDialect).tableExistsQuery(J,X);return((await Z.unsafe(G.sql,G.params)).data?.[0]?.count||0)>0}catch(X){let G=String(X?.message||X),Y=Error(`runtime I/O \u5931\u8D25: op=tableExists table=${J} err=${G}`);if(X?.sqlInfo)Y.sqlInfo=X.sqlInfo;throw Y}}async function Y1($,J){let Z={},X=$.db;if(!X)throw Error("SQL \u6267\u884C\u5668\u672A\u521D\u59CB\u5316");try{if($.dbDialect==="mysql"){let G=PJ({dialect:"mysql",table:J,dbName:$.dbName}),Y=await X.unsafe(G.columns.sql,G.columns.params);for(let W of Y.data){let Q=SJ(W.COLUMN_DEFAULT);Z[W.COLUMN_NAME]={type:W.DATA_TYPE,columnType:W.COLUMN_TYPE,length:W.CHARACTER_MAXIMUM_LENGTH,max:W.CHARACTER_MAXIMUM_LENGTH,nullable:W.IS_NULLABLE==="YES",defaultValue:Q,comment:W.COLUMN_COMMENT}}}else if($.dbDialect==="postgresql"){let G=PJ({dialect:"postgresql",table:J,dbName:$.dbName}),Y=await X.unsafe(G.columns.sql,G.columns.params),W=G.comments?(await X.unsafe(G.comments.sql,G.comments.params)).data:[],Q={};for(let z of W)Q[z.column_name]=z.column_comment;for(let z of Y.data)Z[z.column_name]={type:z.data_type,columnType:z.data_type,length:z.character_maximum_length,max:z.character_maximum_length,nullable:String(z.is_nullable).toUpperCase()==="YES",defaultValue:SJ(z.column_default),comment:Q[z.column_name]??null}}else if($.dbDialect==="sqlite"){let G=PJ({dialect:"sqlite",table:J,dbName:$.dbName}),Y=await X.unsafe(G.columns.sql,G.columns.params);for(let W of Y.data){let Q=String(W.type||"").toUpperCase(),z=null,O=/^(\w+)\s*\((\d+)\)/.exec(Q);if(O){let M=O[1],A=O[2];if(typeof M==="string")Q=M;if(typeof A==="string")z=Number(A)}Z[W.name]={type:Q.toLowerCase(),columnType:Q.toLowerCase(),length:z,max:z,nullable:W.notnull===0,defaultValue:SJ(W.dflt_value),comment:null}}}return Z}catch(G){let Y=String(G?.message||G),W=Error(`runtime I/O \u5931\u8D25: op=getTableColumns table=${J} err=${Y}`);if(G?.sqlInfo)W.sqlInfo=G.sqlInfo;throw W}}async function uZ($,J){let Z={},X=$.db;if(!X)throw Error("SQL \u6267\u884C\u5668\u672A\u521D\u59CB\u5316");try{if($.dbDialect==="mysql"){let G=gZ({dialect:"mysql",table:J,dbName:$.dbName}),Y=await X.unsafe(G.sql,G.params);for(let W of Y.data){let Q=W.INDEX_NAME,z=Z[Q];if(Array.isArray(z))z.push(W.COLUMN_NAME);else Z[Q]=[W.COLUMN_NAME]}}else if($.dbDialect==="postgresql"){let G=gZ({dialect:"postgresql",table:J,dbName:$.dbName}),Y=await X.unsafe(G.sql,G.params);for(let W of Y.data){let Q=/\(([^)]+)\)/.exec(W.indexdef);if(Q){let z=Q[1],O=typeof z==="string"?z.replace(/"/g,"").trim():"";Z[W.indexname]=[O]}}}else if($.dbDialect==="sqlite"){let G=X0("sqlite",J),Y=await X.unsafe(`PRAGMA index_list(${G})`);for(let W of Y.data){let Q=X0("sqlite",W.name),O=(await X.unsafe(`PRAGMA index_info(${Q})`)).data.map((M)=>M.name);if(O.length===1)Z[W.name]=O}}return Z}catch(G){let Y=String(G?.message||G),W=Error(`runtime I/O \u5931\u8D25: op=getTableIndexes table=${J} err=${Y}`);if(G?.sqlInfo)W.sqlInfo=G.sqlInfo;throw W}}async function DH($,J){if(!J)throw Error("SQL \u6267\u884C\u5668\u672A\u521D\u59CB\u5316");if($==="mysql"){let Z=await J.unsafe("SELECT VERSION() AS version");if(!Z.data||Z.data.length===0||!Z.data[0]?.version)throw Error("\u65E0\u6CD5\u83B7\u53D6 MySQL \u7248\u672C\u4FE1\u606F");let X=Z.data[0].version,G=String(X).split(".")[0]||"0",Y=parseInt(G,10);if(!Number.isFinite(Y)||Y<E$.MYSQL_MIN_MAJOR)throw Error(`\u6B64\u811A\u672C\u4EC5\u652F\u6301 MySQL ${E$.MYSQL_MIN_MAJOR}.0+\uFF0C\u5F53\u524D\u7248\u672C: ${X}`);return}if($==="postgresql"){let Z=await J.unsafe("SELECT version() AS version");if(!Z.data||Z.data.length===0||!Z.data[0]?.version)throw Error("\u65E0\u6CD5\u83B7\u53D6 PostgreSQL \u7248\u672C\u4FE1\u606F");let X=Z.data[0].version,G=/PostgreSQL\s+(\d+)/i.exec(X),Y=G?G[1]:void 0,W=typeof Y==="string"?parseInt(Y,10):NaN;if(!Number.isFinite(W)||W<E$.POSTGRES_MIN_MAJOR)throw Error(`\u6B64\u811A\u672C\u8981\u6C42 PostgreSQL >= ${E$.POSTGRES_MIN_MAJOR}\uFF0C\u5F53\u524D: ${X}`);return}if($==="sqlite"){let Z=await J.unsafe("SELECT sqlite_version() AS version");if(!Z.data||Z.data.length===0||!Z.data[0]?.version)throw Error("\u65E0\u6CD5\u83B7\u53D6 SQLite \u7248\u672C\u4FE1\u606F");let X=Z.data[0].version,G=String(X).split(".").map((O)=>parseInt(O,10)||0),Y=G[0]??0,W=G[1]??0,Q=G[2]??0,z=Y*1e4+W*100+Q;if(!Number.isFinite(z)||z<E$.SQLITE_MIN_VERSION_NUM)throw Error(`\u6B64\u811A\u672C\u8981\u6C42 SQLite >= ${E$.SQLITE_MIN_VERSION}\uFF0C\u5F53\u524D: ${X}`);return}}function W1($,J,Z){let X=[],G=H$(Z);if($!=="sqlite"&&GJ(G.type)){let A=G.max;if(A!==null&&J.max!==A)X.push({type:"length",current:J.max,expected:A})}if($!=="sqlite"){let A=J.comment||"";if(A!==G.name)X.push({type:"comment",current:A,expected:G.name})}let W=wJ($)[G.type];if(typeof W!=="string")throw Error(`\u672A\u77E5\u5B57\u6BB5\u7C7B\u578B\u6620\u5C04\uFF1Adialect=${$} type=${String(G.type)}`);let Q=W.toLowerCase(),z=J.type.toLowerCase();if(z!==Q)X.push({type:"datatype",current:z,expected:Q});let O=G.nullable;if(J.nullable!==O)X.push({type:"nullable",current:J.nullable,expected:O});let M=YJ(G.default,G.type);if(String(J.defaultValue)!==String(M))X.push({type:"default",current:J.defaultValue,expected:M});return X}async function kH($,J,Z){if($.dbDialect!=="sqlite")throw Error(`rebuildSqliteTable \u4EC5\u652F\u6301 sqlite \u65B9\u8A00\uFF0C\u5F53\u524D: ${String($.dbDialect)}`);let X=X0("sqlite",J),Y=(await $.db.unsafe(`PRAGMA table_info(${X})`)).data.map((A)=>A.name),Q=["id","created_at","updated_at","deleted_at","state",...Object.keys(Z).map((A)=>x(A))],z=`${J}__tmp__${Date.now()}`;await H1($,z,Z);let O=Q.filter((A)=>Y.includes(A));if(O.length>0){let A=O.map((L)=>X0("sqlite",L)).join(", "),B=X0("sqlite",z);await $.db.unsafe(`INSERT INTO ${B} (${A}) SELECT ${A} FROM ${X}`)}await $.db.unsafe(`DROP TABLE ${X}`);let M=X0("sqlite",z);await $.db.unsafe(`ALTER TABLE ${M} RENAME TO ${X}`)}async function fH($,J,Z,X){if(!X||!X.changed)return;if($.dbDialect==="sqlite")if(X.modifyClauses.length>0||X.defaultClauses.length>0)await kH($,J,Z);else for(let G of X.addClauses){let Y=`ALTER TABLE ${X0($.dbDialect,J)} ${G}`;await $.db.unsafe(Y)}else{let G=[...X.addClauses,...X.modifyClauses];if(G.length>0){let Y=X0($.dbDialect,J),W=$.dbDialect==="mysql"?`ALTER TABLE ${Y} ALGORITHM=INSTANT, LOCK=NONE, ${G.join(", ")}`:`ALTER TABLE ${Y} ${G.join(", ")}`;if($.dbDialect==="mysql")await lX($.db,W);else await $.db.unsafe(W)}}if(X.defaultClauses.length>0)if($.dbDialect==="sqlite")q.warn(`SQLite \u4E0D\u652F\u6301\u4FEE\u6539\u9ED8\u8BA4\u503C\uFF0C\u8868 ${J} \u7684\u9ED8\u8BA4\u503C\u53D8\u66F4\u5DF2\u8DF3\u8FC7`);else{let G=X0($.dbDialect,J),Y=$.dbDialect==="mysql"?`ALTER TABLE ${G} ALGORITHM=INSTANT, LOCK=NONE, ${X.defaultClauses.join(", ")}`:`ALTER TABLE ${G} ${X.defaultClauses.join(", ")}`;if($.dbDialect==="mysql")await lX($.db,Y);else await $.db.unsafe(Y)}for(let G of X.indexActions){let Y=CJ($.dbDialect,J,G.indexName,G.fieldName,G.action);try{if(await $.db.unsafe(Y),G.action==="create")q.debug(`[\u7D22\u5F15\u53D8\u5316] \u65B0\u5EFA\u7D22\u5F15 ${J}.${G.indexName} (${G.fieldName})`);else q.debug(`[\u7D22\u5F15\u53D8\u5316] \u5220\u9664\u7D22\u5F15 ${J}.${G.indexName} (${G.fieldName})`)}catch(W){throw q.error({err:W,table:J,index:G.indexName,field:G.fieldName,msg:`${G.action==="create"?"\u521B\u5EFA":"\u5220\u9664"}\u7D22\u5F15\u5931\u8D25`}),W}}if($.dbDialect==="postgresql"&&X.commentActions&&X.commentActions.length>0)for(let G of X.commentActions)await $.db.unsafe(G)}async function H1($,J,Z,X=cZ){let Y=[...J1($.dbDialect),...Z1($.dbDialect,Z)].join(`,
|
|
7
|
-
`),W=X0($.dbDialect,J),{ENGINE:Q,CHARSET:
|
|
2
|
+
var yW=Object.create;var{getPrototypeOf:xW,defineProperty:eG,getOwnPropertyNames:fW}=Object;var gW=Object.prototype.hasOwnProperty;var hW=($,J,Z)=>{Z=$!=null?yW(xW($)):{};let G=J||!$||!$.__esModule?eG(Z,"default",{value:$,enumerable:!0}):Z;for(let X of fW($))if(!gW.call(G,X))eG(G,X,{get:()=>$[X],enumerable:!0});return G};var o=($,J)=>()=>(J||$((J={exports:{}}).exports,J),J.exports);var V$=($,J)=>()=>($&&(J=$($=0)),J);var A$=import.meta.require;function jZ($,J="dateTime"){let Z=$.getFullYear(),G=$.getMonth()+1,X=$.getDate(),Y=$.getHours(),W=$.getMinutes(),Q=$.getSeconds(),V=G<10?`0${G}`:String(G),O=X<10?`0${X}`:String(X),K=Y<10?`0${Y}`:String(Y),A=W<10?`0${W}`:String(W),B=Q<10?`0${Q}`:String(Q);if(J==="date")return`${Z}-${V}-${O}`;if(J==="time")return`${K}:${A}:${B}`;return`${Z}-${V}-${O} ${K}:${A}:${B}`}function n($){if(typeof $!=="object"||$===null)return!1;let J=Object.getPrototypeOf($);return J===Object.prototype||J===null}function qZ($){if($===null)return"null";if($===void 0)return"undefined";if(Array.isArray($))return"array";let J=typeof $;if(J==="string")return"string";if(J==="number")return"number";if(J==="boolean")return"boolean";if(J==="bigint")return"bigint";if(J==="symbol")return"symbol";if(J==="function")return"function";return"object"}function y$($,J,Z,G){if(typeof $!=="number")return J;if(!Number.isFinite($))return J;let X=Math.floor($);if(X<Z)return J;if(X>G)return G;return X}function $X($,J){if(typeof J!=="function")return;if(!n($))return;let Z=$;for(let G of Object.keys(Z))J(Z[G],G)}function cW($){let J=String($).replace(/([a-z0-9])([A-Z])/g,"$1 $2").replace(/[^a-zA-Z0-9]+/g," ").trim();if(J.length===0)return[];return J.split(/\s+/).filter((Z)=>Z.length>0)}function pW($){if($.length===0)return $;return $.charAt(0).toUpperCase()+$.slice(1)}function F$($){let J=cW($);if(J.length===0)return"";let Z=J[0];if(!Z)return"";let G=Z.toLowerCase(),X=J.slice(1).map((Y)=>pW(Y.toLowerCase()));return[G].concat(X).join("")}function uW($){return String($).replace(/([a-z0-9])([A-Z])/g,"$1 $2").replace(/[^a-zA-Z0-9]+/g," ").trim()}function f($){let J=uW($);if(J.length===0)return"";return J.split(/\s+/).filter((Z)=>Z.length>0).map((Z)=>Z.toLowerCase()).join("_")}function b($,J){if(!n($))return{};let Z=new Set(Array.isArray(J)?J:[]),G={};for(let[X,Y]of Object.entries($)){if(Z.has(X))continue;G[X]=Y}return G}function ZX($,J){let Z={};if(!Array.isArray($)||typeof J!=="function")return Z;for(let G of $){let X=J(G);if(typeof X!=="string"||X==="")continue;Z[X]=G}return Z}function GX(){return Date.now().toString(36)+Math.random().toString(36).slice(2,7)}var BZ=($)=>{if(!$||!n($))return $;let J={};for(let[Z,G]of Object.entries($)){let X=F$(Z);J[X]=G}return J},JX=($)=>{if(!$||!n($))return $;let J={};for(let[Z,G]of Object.entries($)){let X=f(Z);J[X]=G}return J},PZ=($)=>{if(!$||!Array.isArray($))return $;return $.map((J)=>BZ(J))};var n0=()=>{};function CZ($){let J=[];for(let X of $.builtinPatterns){let Y=String(X).trim();if(Y.length>0)J.push(Y.toLowerCase())}if(Array.isArray($.userPatterns))for(let X of $.userPatterns){let Y=String(X).trim();if(Y.length>0)J.push(Y.toLowerCase())}let Z=new Set,G=[];for(let X of J){if(!X.includes("*")){Z.add(X);continue}let Y=X.replace(/\*+/g,"").trim();if(!Y)continue;G.push(Y)}return{exactSet:Z,contains:G}}function wZ($,J){let Z=String($).toLowerCase();if(J.exactSet.has(Z))return!0;for(let G of J.contains)if(Z.includes(G))return!0;return!1}function _J($,J){if($.length<=J)return $;return $.slice(0,J)}function XX($,J){let Z={name:$.name||"Error",message:_J($.message||"",J.maxStringLen)};if(typeof $.stack==="string")Z.stack=_J($.stack,J.maxStringLen);return Z}function nW($,J,Z){if(typeof $==="string")return $;if($ instanceof Error)try{return JSON.stringify(XX($,J))}catch{return`${$.name||"Error"}: ${$.message||""}`}if($&&typeof $==="object"){if(Z.has($))return"[Circular]"}try{let G=Z;return JSON.stringify($,(Y,W)=>{if(Y&&wZ(Y,J.sensitiveKeyMatcher))return"[MASKED]";if(W&&typeof W==="object"){if(G.has(W))return"[Circular]";G.add(W)}return W})}catch{try{return String($)}catch{return"[Unserializable]"}}}function LZ($,J,Z){let G=nW($,J,Z);return _J(G,J.maxStringLen)}function SZ($,J,Z,G,X){if($===null||$===void 0)return $;if(typeof $==="string")return _J($,J.maxStringLen);if(typeof $==="number"||typeof $==="boolean"||typeof $==="bigint")return $;if($ instanceof Error)return XX($,J);let Y=Array.isArray($),W=n($);if(!Y&&!W)return LZ($,J,X);if(X.has($))return"[Circular]";if(G>=J.sanitizeDepth)return LZ($,J,X);if(Z.nodes>=J.sanitizeNodes)return LZ($,J,X);if(X.add($),Z.nodes=Z.nodes+1,Y){let A=$,B=[],L=A.length>J.maxArrayItems?J.maxArrayItems:A.length;for(let C=0;C<L;C++)B[C]=SZ(A[C],J,Z,G+1,X);return B}let Q=$,V={},O=Object.entries(Q),K=O.length>J.sanitizeObjectKeys?J.sanitizeObjectKeys:O.length;for(let A=0;A<K;A++){let B=O[A];if(!B)continue;let L=B[0],C=B[1];if(wZ(L,J.sensitiveKeyMatcher)){V[L]="[MASKED]";continue}V[L]=SZ(C,J,Z,G+1,X)}return V}function EZ($,J){let Z=new WeakSet,G={nodes:0},X={};for(let[Y,W]of Object.entries($)){if(wZ(Y,J.sensitiveKeyMatcher)){X[Y]="[MASKED]";continue}X[Y]=SZ(W,J,G,0,Z)}return X}var YX=V$(()=>{n0()});import{AsyncLocalStorage as mW}from"async_hooks";function WX($,J){return TZ.run($,J)}function HX(){let $=TZ.getStore();if(!$)return null;return $}function QX($,J,Z,G){let X=TZ.getStore();if(!X)return;X.userId=$===void 0?null:$,X.roleCode=J===void 0?null:J,X.nickname=Z===void 0?null:Z,X.roleType=G===void 0?null:G}var TZ;var AJ=V$(()=>{TZ=new mW});import{createWriteStream as dW,existsSync as sW,mkdirSync as oW}from"fs";import{stat as lW}from"fs/promises";import{hostname as rW}from"os";import{isAbsolute as iW,join as tW,resolve as aW}from"path";function IJ($){try{process.stderr.write(`${$}
|
|
3
|
+
`)}catch{}}function JH($,J){let Z=[],G=0;while($.length>0){let X=$[0],Y=Buffer.byteLength(X);if(Z.length>0&&G+Y>J)break;Z.push(X),G=G+Y,$.shift()}return{chunk:Z.join(""),bytes:G}}class DZ{pending;pendingBytes;scheduledTimer;flushing;maxBufferBytes;flushDelayMs;maxBatchBytes;writeChunk;onShutdown;constructor($){this.pending=[],this.pendingBytes=0,this.scheduledTimer=null,this.flushing=!1,this.maxBufferBytes=$.maxBufferBytes,this.flushDelayMs=$.flushDelayMs,this.maxBatchBytes=$.maxBatchBytes,this.writeChunk=$.writeChunk,this.onShutdown=$.onShutdown?$.onShutdown:null}scheduleFlush(){if(this.scheduledTimer)return;this.scheduledTimer=setTimeout(()=>{this.scheduledTimer=null,this.flush()},this.flushDelayMs)}cancelScheduledFlush(){if(!this.scheduledTimer)return;clearTimeout(this.scheduledTimer),this.scheduledTimer=null}enqueue($){let J=Buffer.byteLength($);if(this.pendingBytes+J>this.maxBufferBytes)return;this.pending.push($),this.pendingBytes=this.pendingBytes+J,this.scheduleFlush()}async flushNow(){this.cancelScheduledFlush(),await this.flush()}async shutdown(){if(this.cancelScheduledFlush(),await this.flush(),this.onShutdown)await this.onShutdown()}async flush(){if(this.flushing)return;this.flushing=!0;try{while(this.pending.length>0){let J=JH(this.pending,this.maxBatchBytes).chunk,Z=Buffer.byteLength(J);if(this.pendingBytes=this.pendingBytes-Z,!await this.writeChunk(J,Z)){this.pending=[],this.pendingBytes=0;break}}}finally{if(this.flushing=!1,this.pending.length>0)this.scheduleFlush()}}}function ZH($){let J=()=>{return $==="stderr"?process.stderr:process.stdout},Z=new DZ({maxBufferBytes:10485760,flushDelayMs:10,maxBatchBytes:65536,writeChunk:async(G)=>{try{let X=J();if(!X.write(G))await new Promise((W)=>{X.once("drain",()=>W())});return!0}catch(X){return IJ(`[Logger] stream sink error: ${X?.message||X}`),!1}}});return{enqueue(G){Z.enqueue(G)},async flushNow(){await Z.flushNow()},async shutdown(){await Z.shutdown()}}}class NZ{prefix;maxFileBytes;buffer;stream;streamDate;streamIndex;streamSizeBytes;disabled;constructor($){this.prefix=$.prefix,this.maxFileBytes=$.maxFileBytes,this.stream=null,this.streamDate="",this.streamIndex=0,this.streamSizeBytes=0,this.disabled=!1,this.buffer=new DZ({maxBufferBytes:10485760,flushDelayMs:10,maxBatchBytes:65536,writeChunk:async(J,Z)=>{if(this.disabled)return!1;try{if(await this.ensureStreamReady(Z),!this.stream)return!1;if(!this.stream.write(J))await new Promise((X)=>{let Y=this.stream;if(!Y){X();return}Y.once("drain",()=>X())});return this.streamSizeBytes=this.streamSizeBytes+Z,!0}catch(G){return IJ(`[Logger] file sink flush error (${this.prefix}): ${G?.message||G}`),this.disabled=!0,await this.closeStream(),!1}},onShutdown:async()=>{await this.closeStream()}})}enqueue($){if(this.disabled)return;this.buffer.enqueue($)}async flushNow(){await this.buffer.flushNow()}async shutdown(){await this.buffer.shutdown()}async closeStream(){if(!this.stream)return;let $=this.stream;this.stream=null,await new Promise((J)=>{try{$.end(()=>J())}catch{J()}})}openStream($){try{this.stream=dW($,{flags:"a"}),this.stream.on("error",(J)=>{IJ(`[Logger] file sink error (${this.prefix}): ${J?.message||J}`),this.disabled=!0,this.closeStream()})}catch(J){IJ(`[Logger] createWriteStream failed (${this.prefix}): ${J?.message||J}`),this.disabled=!0,this.stream=null}}getFilePath($,J){let Z=J>0?`.${J}`:"",G=`${this.prefix}.${$}${Z}.log`;return tW(MX(),G)}async ensureStreamReady($){let J=jZ(new Date,"date");if(this.stream&&this.streamDate&&J!==this.streamDate)await this.closeStream(),this.streamDate="",this.streamIndex=0,this.streamSizeBytes=0;if(!this.stream){let Z=this.getFilePath(J,0),G=0;try{let X=await lW(Z);G=typeof X.size==="number"?X.size:0}catch{G=0}if(this.streamDate=J,this.streamIndex=0,this.streamSizeBytes=G,this.openStream(Z),!this.stream)return}if(this.stream&&this.maxFileBytes>0&&this.streamSizeBytes+$>this.maxFileBytes){await this.closeStream(),this.streamIndex=this.streamIndex+1;let Z=this.getFilePath(J,this.streamIndex);if(this.streamDate=J,this.streamSizeBytes=0,this.openStream(Z),!this.stream)return}}}async function GH(){if(S$)return;let $=[];if(G$)$.push({flush:()=>G$?G$.flushNow():Promise.resolve()});if(X$)$.push({flush:()=>X$?X$.flushNow():Promise.resolve()});if(Y$)$.push({flush:()=>Y$?Y$.flushNow():Promise.resolve()});for(let J of $)try{await J.flush()}catch{}}async function OX(){if(S$)return;let $=R$,J=I$,Z=G$,G=X$,X=Y$,Y=[];if(Z)Y.push({shutdown:()=>Z.shutdown()});if(G)Y.push({shutdown:()=>G.shutdown()});if(X)Y.push({shutdown:()=>X.shutdown()});for(let W of Y)try{await W.shutdown()}catch{}if(G$===Z)G$=null;if(X$===G)X$=null;if(Y$===X)Y$=null;if(R$===$)R$=null;if(I$===J)I$=null}function MX(){let $=m0.dir||"./logs";if(iW($))return $;return aW(eW,$)}function XH(){let $=MX();try{if(!sW($))oW($,{recursive:!0})}catch(J){throw Error(`\u521B\u5EFA logs \u76EE\u5F55\u5931\u8D25: ${$}. ${J?.message||J}`)}}function YH($){OX(),m0=Object.assign({debug:0,dir:"./logs",console:1,maxSize:20},$);{let J=m0.maxSize,Z=typeof J==="number"&&Number.isFinite(J)?J:20;if(Z<10)Z=10;if(Z>100)Z=100;m0.maxSize=Z}R$=null,I$=null,G$=null,X$=null,Y$=null,vZ={maxStringLen:y$(m0.maxStringLen,100,20,200000),maxArrayItems:y$(m0.maxArrayItems,100,10,5000),sanitizeDepth:y$(m0.sanitizeDepth,3,1,10),sanitizeNodes:y$(m0.sanitizeNodes,500,50,20000),sanitizeObjectKeys:y$(m0.sanitizeObjectKeys,100,10,5000),sensitiveKeyMatcher:CZ({builtinPatterns:VX,userPatterns:m0.excludeFields})}}function WH($){S$=$}function e$($){if(S$)return S$;if($==="app"){if(R$)return R$}else if(I$)return I$;XH();let J=typeof m0.maxSize==="number"?m0.maxSize:20,Z=Math.floor(J*1024*1024);if($==="app"){if(!G$)G$=new NZ({prefix:"app",maxFileBytes:Z});if(m0.console===1&&!Y$)Y$=ZH("stdout");return R$=zX({fileSink:G$,consoleSink:m0.console===1?Y$:null}),R$}if(!X$)X$=new NZ({prefix:"error",maxFileBytes:Z});return I$=zX({fileSink:X$,consoleSink:null}),I$}function HH($,J){let Z=Date.now(),G={level:$,time:Z,timeFormat:jZ(new Date(Z)),pid:process.pid,hostname:$H};if(J&&n(J)){let X=Object.assign({},J,G);if(J.msg!==void 0)X.msg=J.msg;else if(X.msg===void 0)X.msg="";return`${UX(X)}
|
|
4
|
+
`}if(G.msg===void 0)G.msg="";return`${UX(G)}
|
|
5
|
+
`}function UX($){try{return JSON.stringify($)}catch{try{return JSON.stringify({level:$.level,time:$.time,pid:$.pid,hostname:$.hostname,msg:"[Unserializable log record]"})}catch{return'{"msg":"[Unserializable log record]"}'}}}function zX($){let{fileSink:J,consoleSink:Z}=$,G=(X,Y)=>{if(X==="debug"&&m0.debug!==1)return;let W=n(Y)?Y:{value:Y},Q=EZ(W,vZ),V=HH(X,Q);if(J.enqueue(V),Z)Z.enqueue(V)};return{info(X){G("info",X)},warn(X){G("warn",X)},error(X){G("error",X)},debug(X){G("debug",X)}}}function QH(){let $=HX();if(!$)return null;let J=Date.now()-$.now,Z={requestId:$.requestId,method:$.method,route:$.route,ip:$.ip,now:$.now,durationSinceNowMs:J};return Z.userId=$.userId,Z.roleCode=$.roleCode,Z.nickname=$.nickname,Z.roleType=$.roleType,Z}function UH($,J){let Z={};for(let X of Object.keys($))Z[X]=$[X];let G=["requestId","method","route","ip","now","durationSinceNowMs","userId","roleCode","nickname","roleType"];for(let X of G)if(Z[X]===void 0)Z[X]=J[X];return Z}function FJ($){if(n($))return $;if($ instanceof Error)return{err:$,msg:$.message||$.name||"Error"};if($===void 0)return{msg:""};if($===null)return{msg:"null"};if(typeof $==="object")return{value:$};try{return{msg:String($)}}catch{return{msg:"[Unserializable]"}}}function RJ($){let J=QH();if(!J)return $;return UH($,J)}class KX{maybeSanitizeForMock($){if(!S$)return $;return EZ($,vZ)}info($){let J=RJ(FJ($)),Z=this.maybeSanitizeForMock(J);e$("app").info(Z)}warn($){let J=RJ(FJ($)),Z=this.maybeSanitizeForMock(J);e$("app").warn(Z)}error($){let J=RJ(FJ($)),Z=this.maybeSanitizeForMock(J);if(e$("app").error(Z),S$)return;e$("error").error(Z)}debug($){if(m0.debug!==1)return;let J=RJ(FJ($)),Z=this.maybeSanitizeForMock(J);e$("app").debug(Z)}async flush(){await GH()}configure($){YH($)}setMock($){WH($)}async shutdown(){await OX()}}var eW,VX,vZ,$H,R$=null,I$=null,S$=null,G$=null,X$=null,Y$=null,m0,q;var a=V$(()=>{YX();n0();AJ();eW=process.cwd(),VX=["*password*","pass","pwd","*token*","access_token","refresh_token","accessToken","refreshToken","authorization","cookie","set-cookie","*secret*","apiKey","api_key","privateKey","private_key"],vZ={maxStringLen:100,maxArrayItems:100,sanitizeDepth:3,sanitizeNodes:500,sanitizeObjectKeys:100,sensitiveKeyMatcher:CZ({builtinPatterns:VX,userPatterns:[]})},$H=(()=>{try{return rW()}catch{return"unknown"}})(),m0={debug:0,dir:"./logs",console:1,maxSize:20};q=new KX});import{isAbsolute as zH}from"path";import{pathToFileURL as VH}from"url";function OH($){return/^[a-zA-Z]:[\\/]/.test($)}function MH($){if(zH($)||OH($))return VH($).href;return $}async function j$($,J){try{let X=($.endsWith(".json")?await import(MH($),{with:{type:"json"}}):await import($))?.default;if(X===null||X===void 0)return J;let Y=qZ(J),W=qZ(X);if(Y!==W)return q.warn({file:$,msg:"importDefault \u5BFC\u5165\u7C7B\u578B\u4E0E\u9ED8\u8BA4\u503C\u4E0D\u4E00\u81F4\uFF0C\u5DF2\u56DE\u9000\u5230\u9ED8\u8BA4\u503C",expectedType:Y,actualType:W}),J;return X}catch(Z){return q.warn({err:Z,file:$,msg:"importDefault \u5BFC\u5165\u5931\u8D25\uFF0C\u5DF2\u56DE\u9000\u5230\u9ED8\u8BA4\u503C"}),J}}var jJ=V$(()=>{a();n0()});function ZJ($=""){if(!$)return $;return $.replace(/\\/g,"/").replace(jH,(J)=>J.toUpperCase())}function SH(){if(typeof process<"u"&&typeof process.cwd==="function")return process.cwd().replace(/\\/g,"/");return"/"}function xZ($,J){let Z="",G=0,X=-1,Y=0,W=null;for(let Q=0;Q<=$.length;++Q){if(Q<$.length)W=$[Q];else if(W==="/")break;else W="/";if(W==="/"){if(X===Q-1||Y===1);else if(Y===2){if(Z.length<2||G!==2||Z[Z.length-1]!=="."||Z[Z.length-2]!=="."){if(Z.length>2){let V=Z.lastIndexOf("/");if(V===-1)Z="",G=0;else Z=Z.slice(0,V),G=Z.length-1-Z.lastIndexOf("/");X=Q,Y=0;continue}else if(Z.length>0){Z="",G=0,X=Q,Y=0;continue}}if(J)Z+=Z.length>0?"/..":"..",G=2}else{if(Z.length>0)Z+=`/${$.slice(X+1,Q)}`;else Z=$.slice(X+1,Q);G=Q-X-1}X=Q,Y=0}else if(W==="."&&Y!==-1)++Y;else Y=-1}return Z}var jH,qH,BH,PX,BX,PH,LH,C$=function($){if($.length===0)return".";$=ZJ($);let J=$.match(qH),Z=x$($),G=$[$.length-1]==="/";if($=xZ($,!Z),$.length===0){if(Z)return"/";return G?"./":"."}if(G)$+="/";if(PX.test($))$+="/";if(J){if(!Z)return`//./${$}`;return`//${$}`}return Z&&!x$($)?`/${$}`:$},d=function(...$){let J="";for(let Z of $){if(!Z)continue;if(J.length>0){let G=J[J.length-1]==="/",X=Z[0]==="/";if(G&&X)J+=Z.slice(1);else J+=G||X?Z:`/${Z}`}else J+=Z}return C$(J)},JJ=function(...$){$=$.map((G)=>ZJ(G));let J="",Z=!1;for(let G=$.length-1;G>=-1&&!Z;G--){let X=G>=0?$[G]:SH();if(!X||X.length===0)continue;J=`${X}/${J}`,Z=x$(X)}if(J=xZ(J,!Z),Z&&!x$(J))return`/${J}`;return J.length>0?J:"."},x$=function($){return BH.test($)},LX=function($){if($==="..")return"";let J=PH.exec(ZJ($));return J&&J[1]||""},fZ=function($,J){let Z=JJ($).replace(BX,"$1").split("/"),G=JJ(J).replace(BX,"$1").split("/");if(G[0][1]===":"&&Z[0][1]===":"&&Z[0]!==G[0])return G.join("/");let X=[...Z];for(let Y of X){if(G[0]!==Y)break;Z.shift(),G.shift()}return[...Z.map(()=>".."),...G].join("/")},qJ=function($){let J=ZJ($).replace(/\/$/,"").split("/").slice(0,-1);if(J.length===1&&PX.test(J[0]))J[0]+="/";return J.join("/")||(x$($)?"/":".")},SX=function($,J){let Z=ZJ($).split("/"),G="";for(let X=Z.length-1;X>=0;X--){let Y=Z[X];if(Y){G=Y;break}}return J&&G.endsWith(J)?G.slice(0,-J.length):G},GJ=function($){let J=LH.exec($)?.[0]?.replace(/\\/g,"/")||"",Z=SX($),G=LX(Z);return{root:J,dir:qJ($),base:Z,ext:G,name:Z.slice(0,Z.length-G.length)}};var CX=V$(()=>{jH=/^[A-Za-z]:\//;qH=/^[/\\]{2}/,BH=/^[/\\](?![/\\])|^[/\\]{2}(?!\.)|^[A-Za-z]:[/\\]/,PX=/^[A-Za-z]:$/,BX=/^\/([A-Za-z]:)?$/,PH=/.(\.[^./]+|\.)$/,LH=/^[/\\]|^[a-zA-Z]:[/\\]/});var q$=V$(()=>{CX()});import{statSync as CH}from"fs";var BJ=($,J)=>{if(J.isDirectory())return!0;if(!J.isSymbolicLink())return!1;try{return CH(d($,J.name)).isDirectory()}catch{return!1}};var gZ=V$(()=>{q$()});import{existsSync as f$}from"fs";import{readdir as wH}from"fs/promises";function EH($){if(!$||typeof $!=="object")return null;let J=$,Z=J.title;if(typeof Z!=="string"||!Z)return null;let G=J.order,X=typeof G==="number"&&Number.isFinite(G)&&Number.isInteger(G)&&G>=0?G:void 0;if(X===void 0)return{title:Z};return{title:Z,order:X}}async function wX($,J,Z=""){if(!f$($))return[];let G=[],X=await wH($,{withFileTypes:!0});for(let Y of X){if(!BJ($,Y)||Y.name==="components")continue;let W=d($,Y.name),Q=d(W,"meta.json"),V=d(W,"index.vue"),O=null;if(!f$(Q))continue;if(!f$(V)){q.warn({path:W,msg:"\u76EE\u5F55\u5B58\u5728 meta.json \u4F46\u7F3A\u5C11 index.vue\uFF0C\u5DF2\u8DF3\u8FC7\u8BE5\u76EE\u5F55\u83DC\u5355\u540C\u6B65"});continue}let K=await j$(Q,{});if(O=EH(K),!O?.title){q.warn({path:Q,msg:"meta.json \u7F3A\u5C11\u6709\u6548\u7684 title\uFF08\u4EE5\u53CA\u53EF\u9009 order:number\uFF09\uFF0C\u5DF2\u8DF3\u8FC7\u8BE5\u76EE\u5F55\u83DC\u5355\u540C\u6B65"});continue}if(!O?.title)continue;let A=String(Y.name).replace(/_\d+$/,""),B;if(A==="index")B=Z;else B=Z?`${Z}/${A}`:`/${A}`;let L=J?B?`${J}${B}`:J:B||"/",C={name:O.title,path:L,sort:O.order??999999},T=await wX(W,J,B);if(T.length>0)C.children=T;G.push(C)}return G.sort((Y,W)=>(Y.sort??999999)-(W.sort??999999)),G}function EX($){let J=$.split("/").filter((Z)=>Boolean(Z));if(J.length<=1)return"";return`/${J.slice(0,-1).join("/")}`}async function TX($){let J=[];for(let G of $){let X=d(G.fullPath,"adminViews"),Y=d(G.fullPath,"views","admin"),W=f$(X)?X:f$(Y)?Y:null;if(!W)continue;try{let Q=`/${G.source}/${G.name}`,V=await wX(W,Q);if(V.length>0)for(let O of V)J.push(O)}catch(Q){q.warn({err:Q,addon:G.name,addonSource:G.source,dir:W,msg:"\u626B\u63CF addon views \u76EE\u5F55\u5931\u8D25"})}}let Z=d(process.cwd(),"menus.json");if(f$(Z)){let G=await j$(Z,[]);if(Array.isArray(G)&&G.length>0)for(let X of G)J.push(X)}return J}var hZ=V$(()=>{q$();a();jJ();gZ()});var n$=o((j7,h1)=>{var g1={invalidType:"FAST_JWT_INVALID_TYPE",invalidOption:"FAST_JWT_INVALID_OPTION",invalidAlgorithm:"FAST_JWT_INVALID_ALGORITHM",invalidClaimType:"FAST_JWT_INVALID_CLAIM_TYPE",invalidClaimValue:"FAST_JWT_INVALID_CLAIM_VALUE",invalidKey:"FAST_JWT_INVALID_KEY",invalidSignature:"FAST_JWT_INVALID_SIGNATURE",invalidPayload:"FAST_JWT_INVALID_PAYLOAD",malformed:"FAST_JWT_MALFORMED",inactive:"FAST_JWT_INACTIVE",expired:"FAST_JWT_EXPIRED",missingKey:"FAST_JWT_MISSING_KEY",keyFetchingError:"FAST_JWT_KEY_FETCHING_ERROR",signError:"FAST_JWT_SIGN_ERROR",verifyError:"FAST_JWT_VERIFY_ERROR",missingRequiredClaim:"FAST_JWT_MISSING_REQUIRED_CLAIM",missingSignature:"FAST_JWT_MISSING_SIGNATURE"};class u$ extends Error{constructor($,J,Z){super(J);if(Error.captureStackTrace(this,this.constructor),this.code=$,Z)for(let G in Z)this[G]=Z[G]}}u$.codes=g1;u$.wrap=function($,J,Z){if($ instanceof u$)return $;return new u$(J,Z,{originalError:$})};h1.exports={TokenError:u$,TOKEN_ERROR_CODES:g1}});var XG=o((q7,b1)=>{var{TokenError:Q$}=n$();function lQ({complete:$,checkTyp:J},Z){if(Z instanceof Buffer)Z=Z.toString("utf-8");else if(typeof Z!=="string")throw new Q$(Q$.codes.invalidType,"The token must be a string or a buffer.");let G=Z.indexOf("."),X=Z.lastIndexOf(".");if(G===-1||G>=X)throw new Q$(Q$.codes.malformed,"The token is malformed.");let Y=!1;try{let W=JSON.parse(Buffer.from(Z.slice(0,G),"base64").toString("utf-8"));if(J&&W.typ!==J)throw new Q$(Q$.codes.invalidType,`The type must be "${J}".`,{header:W});Y=!0;let Q=Buffer.from(Z.slice(G+1,X),"base64").toString("utf-8");if(Q=JSON.parse(Q),!Q||typeof Q!=="object")throw new Q$(Q$.codes.invalidPayload,"The payload must be an object",{payload:Q});return $?{header:W,payload:Q,signature:Z.slice(X+1),input:Z.slice(0,X)}:Q}catch(W){throw Q$.wrap(W,Q$.codes.malformed,`The token ${Y?"payload":"header"} is not a valid base64url serialized JSON.`)}}b1.exports=function(J={}){let Z=J.complete||!1,G=J.checkTyp;return lQ.bind(null,{complete:Z,checkTyp:G})}});var p1=o((B7,c1)=>{function U$($){if(typeof $!=="function")throw Error("obliterator/iterator: expecting a function!");this.next=$}if(typeof Symbol<"u")U$.prototype[Symbol.iterator]=function(){return this};U$.of=function(){var $=arguments,J=$.length,Z=0;return new U$(function(){if(Z>=J)return{done:!0};return{done:!1,value:$[Z++]}})};U$.empty=function(){var $=new U$(function(){return{done:!0}});return $};U$.fromSequence=function($){var J=0,Z=$.length;return new U$(function(){if(J>=Z)return{done:!0};return{done:!1,value:$[J++]}})};U$.is=function($){if($ instanceof U$)return!0;return typeof $==="object"&&$!==null&&typeof $.next==="function"};c1.exports=U$});var u1=o((rQ)=>{rQ.ARRAY_BUFFER_SUPPORT=typeof ArrayBuffer<"u";rQ.SYMBOL_SUPPORT=typeof Symbol<"u"});var YG=o((L7,m1)=>{var n1=u1(),aQ=n1.ARRAY_BUFFER_SUPPORT,eQ=n1.SYMBOL_SUPPORT;m1.exports=function(J,Z){var G,X,Y,W,Q;if(!J)throw Error("obliterator/forEach: invalid iterable.");if(typeof Z!=="function")throw Error("obliterator/forEach: expecting a callback.");if(Array.isArray(J)||aQ&&ArrayBuffer.isView(J)||typeof J==="string"||J.toString()==="[object Arguments]"){for(Y=0,W=J.length;Y<W;Y++)Z(J[Y],Y);return}if(typeof J.forEach==="function"){J.forEach(Z);return}if(eQ&&Symbol.iterator in J&&typeof J.next!=="function")J=J[Symbol.iterator]();if(typeof J.next==="function"){G=J,Y=0;while(Q=G.next(),Q.done!==!0)Z(Q.value,Y),Y++;return}for(X in J)if(J.hasOwnProperty(X))Z(J[X],X);return}});var WG=o((H9)=>{var $9=Math.pow(2,8)-1,J9=Math.pow(2,16)-1,Z9=Math.pow(2,32)-1,G9=Math.pow(2,7)-1,X9=Math.pow(2,15)-1,Y9=Math.pow(2,31)-1;H9.getPointerArray=function($){var J=$-1;if(J<=$9)return Uint8Array;if(J<=J9)return Uint16Array;if(J<=Z9)return Uint32Array;throw Error("mnemonist: Pointer Array of size > 4294967295 is not supported.")};H9.getSignedPointerArray=function($){var J=$-1;if(J<=G9)return Int8Array;if(J<=X9)return Int16Array;if(J<=Y9)return Int32Array;return Float64Array};H9.getNumberType=function($){if($===($|0))if(Math.sign($)===-1){if($<=127&&$>=-128)return Int8Array;if($<=32767&&$>=-32768)return Int16Array;return Int32Array}else{if($<=255)return Uint8Array;if($<=65535)return Uint16Array;return Uint32Array}return Float64Array};var W9={Uint8Array:1,Int8Array:2,Uint16Array:3,Int16Array:4,Uint32Array:5,Int32Array:6,Float32Array:7,Float64Array:8};H9.getMinimalRepresentation=function($,J){var Z=null,G=0,X,Y,W,Q,V;for(Q=0,V=$.length;Q<V;Q++)if(W=J?J($[Q]):$[Q],Y=H9.getNumberType(W),X=W9[Y.name],X>G)G=X,Z=Y;return Z};H9.isTypedArray=function($){return typeof ArrayBuffer<"u"&&ArrayBuffer.isView($)};H9.concat=function(){var $=0,J,Z,G;for(J=0,G=arguments.length;J<G;J++)$+=arguments[J].length;var X=new arguments[0].constructor($);for(J=0,Z=0;J<G;J++)X.set(arguments[J],Z),Z+=arguments[J].length;return X};H9.indices=function($){var J=H9.getPointerArray($),Z=new J($);for(var G=0;G<$;G++)Z[G]=G;return Z}});var r1=o((A9)=>{var o1=YG(),l1=WG();function M9($){return Array.isArray($)||l1.isTypedArray($)}function HG($){if(typeof $.length==="number")return $.length;if(typeof $.size==="number")return $.size;return}function K9($){var J=HG($),Z=typeof J==="number"?Array(J):[],G=0;return o1($,function(X){Z[G++]=X}),Z}function _9($){var J=HG($),Z=typeof J==="number"?l1.getPointerArray(J):Array,G=typeof J==="number"?Array(J):[],X=typeof J==="number"?new Z(J):[],Y=0;return o1($,function(W){G[Y]=W,X[Y]=Y++}),[G,X]}A9.isArrayLike=M9;A9.guessLength=HG;A9.toArray=K9;A9.toArrayWithIndices=_9});var UG=o((w7,i1)=>{var QG=p1(),q9=YG(),B9=WG(),P9=r1();function p0($,J,Z){if(arguments.length<2)Z=$,$=null,J=null;if(this.capacity=Z,typeof this.capacity!=="number"||this.capacity<=0)throw Error("mnemonist/lru-cache: capacity should be positive number.");else if(!isFinite(this.capacity)||Math.floor(this.capacity)!==this.capacity)throw Error("mnemonist/lru-cache: capacity should be a finite positive integer.");var G=B9.getPointerArray(Z);this.forward=new G(Z),this.backward=new G(Z),this.K=typeof $==="function"?new $(Z):Array(Z),this.V=typeof J==="function"?new J(Z):Array(Z),this.size=0,this.head=0,this.tail=0,this.items={}}p0.prototype.clear=function(){this.size=0,this.head=0,this.tail=0,this.items={}};p0.prototype.splayOnTop=function($){var J=this.head;if(this.head===$)return this;var Z=this.backward[$],G=this.forward[$];if(this.tail===$)this.tail=Z;else this.backward[G]=Z;return this.forward[Z]=G,this.backward[J]=$,this.head=$,this.forward[$]=J,this};p0.prototype.set=function($,J){var Z=this.items[$];if(typeof Z<"u"){this.splayOnTop(Z),this.V[Z]=J;return}if(this.size<this.capacity)Z=this.size++;else Z=this.tail,this.tail=this.backward[Z],delete this.items[this.K[Z]];this.items[$]=Z,this.K[Z]=$,this.V[Z]=J,this.forward[Z]=this.head,this.backward[this.head]=Z,this.head=Z};p0.prototype.setpop=function($,J){var Z=null,G=null,X=this.items[$];if(typeof X<"u")return this.splayOnTop(X),Z=this.V[X],this.V[X]=J,{evicted:!1,key:$,value:Z};if(this.size<this.capacity)X=this.size++;else X=this.tail,this.tail=this.backward[X],Z=this.V[X],G=this.K[X],delete this.items[G];if(this.items[$]=X,this.K[X]=$,this.V[X]=J,this.forward[X]=this.head,this.backward[this.head]=X,this.head=X,G)return{evicted:!0,key:G,value:Z};else return null};p0.prototype.has=function($){return $ in this.items};p0.prototype.get=function($){var J=this.items[$];if(typeof J>"u")return;return this.splayOnTop(J),this.V[J]};p0.prototype.peek=function($){var J=this.items[$];if(typeof J>"u")return;return this.V[J]};p0.prototype.forEach=function($,J){J=arguments.length>1?J:this;var Z=0,G=this.size,X=this.head,Y=this.K,W=this.V,Q=this.forward;while(Z<G)$.call(J,W[X],Y[X],this),X=Q[X],Z++};p0.prototype.keys=function(){var $=0,J=this.size,Z=this.head,G=this.K,X=this.forward;return new QG(function(){if($>=J)return{done:!0};var Y=G[Z];if($++,$<J)Z=X[Z];return{done:!1,value:Y}})};p0.prototype.values=function(){var $=0,J=this.size,Z=this.head,G=this.V,X=this.forward;return new QG(function(){if($>=J)return{done:!0};var Y=G[Z];if($++,$<J)Z=X[Z];return{done:!1,value:Y}})};p0.prototype.entries=function(){var $=0,J=this.size,Z=this.head,G=this.K,X=this.V,Y=this.forward;return new QG(function(){if($>=J)return{done:!0};var W=G[Z],Q=X[Z];if($++,$<J)Z=Y[Z];return{done:!1,value:[W,Q]}})};if(typeof Symbol<"u")p0.prototype[Symbol.iterator]=p0.prototype.entries;p0.prototype.inspect=function(){var $=new Map,J=this.entries(),Z;while(Z=J.next(),!Z.done)$.set(Z.value[0],Z.value[1]);return Object.defineProperty($,"constructor",{value:p0,enumerable:!1}),$};if(typeof Symbol<"u")p0.prototype[Symbol.for("nodejs.util.inspect.custom")]=p0.prototype.inspect;p0.from=function($,J,Z,G){if(arguments.length<2){if(G=P9.guessLength($),typeof G!=="number")throw Error("mnemonist/lru-cache.from: could not guess iterable length. Please provide desired capacity as last argument.")}else if(arguments.length===2)G=J,J=null,Z=null;var X=new p0(J,Z,G);return q9($,function(Y,W){X.set(W,Y)}),X};i1.exports=p0});var VG=o((t1,zG)=>{(function($,J){function Z(j,H){if(!j)throw Error(H||"Assertion failed")}function G(j,H){j.super_=H;var z=function(){};z.prototype=H.prototype,j.prototype=new z,j.prototype.constructor=j}function X(j,H,z){if(X.isBN(j))return j;if(this.negative=0,this.words=null,this.length=0,this.red=null,j!==null){if(H==="le"||H==="be")z=H,H=10;this._init(j||0,H||10,z||"be")}}if(typeof $==="object")$.exports=X;else J.BN=X;X.BN=X,X.wordSize=26;var Y;try{if(typeof window<"u"&&typeof window.Buffer<"u")Y=window.Buffer;else Y=A$("buffer").Buffer}catch(j){}X.isBN=function(H){if(H instanceof X)return!0;return H!==null&&typeof H==="object"&&H.constructor.wordSize===X.wordSize&&Array.isArray(H.words)},X.max=function(H,z){if(H.cmp(z)>0)return H;return z},X.min=function(H,z){if(H.cmp(z)<0)return H;return z},X.prototype._init=function(H,z,M){if(typeof H==="number")return this._initNumber(H,z,M);if(typeof H==="object")return this._initArray(H,z,M);if(z==="hex")z=16;Z(z===(z|0)&&z>=2&&z<=36),H=H.toString().replace(/\s+/g,"");var _=0;if(H[0]==="-")_++,this.negative=1;if(_<H.length){if(z===16)this._parseHex(H,_,M);else if(this._parseBase(H,z,_),M==="le")this._initArray(this.toArray(),z,M)}},X.prototype._initNumber=function(H,z,M){if(H<0)this.negative=1,H=-H;if(H<67108864)this.words=[H&67108863],this.length=1;else if(H<4503599627370496)this.words=[H&67108863,H/67108864&67108863],this.length=2;else Z(H<9007199254740992),this.words=[H&67108863,H/67108864&67108863,1],this.length=3;if(M!=="le")return;this._initArray(this.toArray(),z,M)},X.prototype._initArray=function(H,z,M){if(Z(typeof H.length==="number"),H.length<=0)return this.words=[0],this.length=1,this;this.length=Math.ceil(H.length/3),this.words=Array(this.length);for(var _=0;_<this.length;_++)this.words[_]=0;var I,P,S=0;if(M==="be"){for(_=H.length-1,I=0;_>=0;_-=3)if(P=H[_]|H[_-1]<<8|H[_-2]<<16,this.words[I]|=P<<S&67108863,this.words[I+1]=P>>>26-S&67108863,S+=24,S>=26)S-=26,I++}else if(M==="le"){for(_=0,I=0;_<H.length;_+=3)if(P=H[_]|H[_+1]<<8|H[_+2]<<16,this.words[I]|=P<<S&67108863,this.words[I+1]=P>>>26-S&67108863,S+=24,S>=26)S-=26,I++}return this.strip()};function W(j,H){var z=j.charCodeAt(H);if(z>=65&&z<=70)return z-55;else if(z>=97&&z<=102)return z-87;else return z-48&15}function Q(j,H,z){var M=W(j,z);if(z-1>=H)M|=W(j,z-1)<<4;return M}X.prototype._parseHex=function(H,z,M){this.length=Math.ceil((H.length-z)/6),this.words=Array(this.length);for(var _=0;_<this.length;_++)this.words[_]=0;var I=0,P=0,S;if(M==="be")for(_=H.length-1;_>=z;_-=2)if(S=Q(H,z,_)<<I,this.words[P]|=S&67108863,I>=18)I-=18,P+=1,this.words[P]|=S>>>26;else I+=8;else{var F=H.length-z;for(_=F%2===0?z+1:z;_<H.length;_+=2)if(S=Q(H,z,_)<<I,this.words[P]|=S&67108863,I>=18)I-=18,P+=1,this.words[P]|=S>>>26;else I+=8}this.strip()};function V(j,H,z,M){var _=0,I=Math.min(j.length,z);for(var P=H;P<I;P++){var S=j.charCodeAt(P)-48;if(_*=M,S>=49)_+=S-49+10;else if(S>=17)_+=S-17+10;else _+=S}return _}X.prototype._parseBase=function(H,z,M){this.words=[0],this.length=1;for(var _=0,I=1;I<=67108863;I*=z)_++;_--,I=I/z|0;var P=H.length-M,S=P%_,F=Math.min(P,P-S)+M,U=0;for(var R=M;R<F;R+=_)if(U=V(H,R,R+_,z),this.imuln(I),this.words[0]+U<67108864)this.words[0]+=U;else this._iaddn(U);if(S!==0){var k=1;U=V(H,R,H.length,z);for(R=0;R<S;R++)k*=z;if(this.imuln(k),this.words[0]+U<67108864)this.words[0]+=U;else this._iaddn(U)}this.strip()},X.prototype.copy=function(H){H.words=Array(this.length);for(var z=0;z<this.length;z++)H.words[z]=this.words[z];H.length=this.length,H.negative=this.negative,H.red=this.red},X.prototype.clone=function(){var H=new X(null);return this.copy(H),H},X.prototype._expand=function(H){while(this.length<H)this.words[this.length++]=0;return this},X.prototype.strip=function(){while(this.length>1&&this.words[this.length-1]===0)this.length--;return this._normSign()},X.prototype._normSign=function(){if(this.length===1&&this.words[0]===0)this.negative=0;return this},X.prototype.inspect=function(){return(this.red?"<BN-R: ":"<BN: ")+this.toString(16)+">"};var O=["","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"],K=[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],A=[0,0,33554432,43046721,16777216,48828125,60466176,40353607,16777216,43046721,1e7,19487171,35831808,62748517,7529536,11390625,16777216,24137569,34012224,47045881,64000000,4084101,5153632,6436343,7962624,9765625,11881376,14348907,17210368,20511149,24300000,28629151,33554432,39135393,45435424,52521875,60466176];if(X.prototype.toString=function(H,z){H=H||10,z=z|0||1;var M;if(H===16||H==="hex"){M="";var _=0,I=0;for(var P=0;P<this.length;P++){var S=this.words[P],F=((S<<_|I)&16777215).toString(16);if(I=S>>>24-_&16777215,_+=2,_>=26)_-=26,P--;if(I!==0||P!==this.length-1)M=O[6-F.length]+F+M;else M=F+M}if(I!==0)M=I.toString(16)+M;while(M.length%z!==0)M="0"+M;if(this.negative!==0)M="-"+M;return M}if(H===(H|0)&&H>=2&&H<=36){var U=K[H],R=A[H];M="";var k=this.clone();k.negative=0;while(!k.isZero()){var y=k.modn(R).toString(H);if(k=k.idivn(R),!k.isZero())M=O[U-y.length]+y+M;else M=y+M}if(this.isZero())M="0"+M;while(M.length%z!==0)M="0"+M;if(this.negative!==0)M="-"+M;return M}Z(!1,"Base should be between 2 and 36")},X.prototype.toNumber=function(){var H=this.words[0];if(this.length===2)H+=this.words[1]*67108864;else if(this.length===3&&this.words[2]===1)H+=4503599627370496+this.words[1]*67108864;else if(this.length>2)Z(!1,"Number can only safely store up to 53 bits");return this.negative!==0?-H:H},X.prototype.toJSON=function(){return this.toString(16)},X.prototype.toBuffer=function(H,z){return Z(typeof Y<"u"),this.toArrayLike(Y,H,z)},X.prototype.toArray=function(H,z){return this.toArrayLike(Array,H,z)},X.prototype.toArrayLike=function(H,z,M){var _=this.byteLength(),I=M||Math.max(1,_);Z(_<=I,"byte array longer than desired length"),Z(I>0,"Requested array length <= 0"),this.strip();var P=z==="le",S=new H(I),F,U,R=this.clone();if(!P){for(U=0;U<I-_;U++)S[U]=0;for(U=0;!R.isZero();U++)F=R.andln(255),R.iushrn(8),S[I-U-1]=F}else{for(U=0;!R.isZero();U++)F=R.andln(255),R.iushrn(8),S[U]=F;for(;U<I;U++)S[U]=0}return S},Math.clz32)X.prototype._countBits=function(H){return 32-Math.clz32(H)};else X.prototype._countBits=function(H){var z=H,M=0;if(z>=4096)M+=13,z>>>=13;if(z>=64)M+=7,z>>>=7;if(z>=8)M+=4,z>>>=4;if(z>=2)M+=2,z>>>=2;return M+z};X.prototype._zeroBits=function(H){if(H===0)return 26;var z=H,M=0;if((z&8191)===0)M+=13,z>>>=13;if((z&127)===0)M+=7,z>>>=7;if((z&15)===0)M+=4,z>>>=4;if((z&3)===0)M+=2,z>>>=2;if((z&1)===0)M++;return M},X.prototype.bitLength=function(){var H=this.words[this.length-1],z=this._countBits(H);return(this.length-1)*26+z};function B(j){var H=Array(j.bitLength());for(var z=0;z<H.length;z++){var M=z/26|0,_=z%26;H[z]=(j.words[M]&1<<_)>>>_}return H}X.prototype.zeroBits=function(){if(this.isZero())return 0;var H=0;for(var z=0;z<this.length;z++){var M=this._zeroBits(this.words[z]);if(H+=M,M!==26)break}return H},X.prototype.byteLength=function(){return Math.ceil(this.bitLength()/8)},X.prototype.toTwos=function(H){if(this.negative!==0)return this.abs().inotn(H).iaddn(1);return this.clone()},X.prototype.fromTwos=function(H){if(this.testn(H-1))return this.notn(H).iaddn(1).ineg();return this.clone()},X.prototype.isNeg=function(){return this.negative!==0},X.prototype.neg=function(){return this.clone().ineg()},X.prototype.ineg=function(){if(!this.isZero())this.negative^=1;return this},X.prototype.iuor=function(H){while(this.length<H.length)this.words[this.length++]=0;for(var z=0;z<H.length;z++)this.words[z]=this.words[z]|H.words[z];return this.strip()},X.prototype.ior=function(H){return Z((this.negative|H.negative)===0),this.iuor(H)},X.prototype.or=function(H){if(this.length>H.length)return this.clone().ior(H);return H.clone().ior(this)},X.prototype.uor=function(H){if(this.length>H.length)return this.clone().iuor(H);return H.clone().iuor(this)},X.prototype.iuand=function(H){var z;if(this.length>H.length)z=H;else z=this;for(var M=0;M<z.length;M++)this.words[M]=this.words[M]&H.words[M];return this.length=z.length,this.strip()},X.prototype.iand=function(H){return Z((this.negative|H.negative)===0),this.iuand(H)},X.prototype.and=function(H){if(this.length>H.length)return this.clone().iand(H);return H.clone().iand(this)},X.prototype.uand=function(H){if(this.length>H.length)return this.clone().iuand(H);return H.clone().iuand(this)},X.prototype.iuxor=function(H){var z,M;if(this.length>H.length)z=this,M=H;else z=H,M=this;for(var _=0;_<M.length;_++)this.words[_]=z.words[_]^M.words[_];if(this!==z)for(;_<z.length;_++)this.words[_]=z.words[_];return this.length=z.length,this.strip()},X.prototype.ixor=function(H){return Z((this.negative|H.negative)===0),this.iuxor(H)},X.prototype.xor=function(H){if(this.length>H.length)return this.clone().ixor(H);return H.clone().ixor(this)},X.prototype.uxor=function(H){if(this.length>H.length)return this.clone().iuxor(H);return H.clone().iuxor(this)},X.prototype.inotn=function(H){Z(typeof H==="number"&&H>=0);var z=Math.ceil(H/26)|0,M=H%26;if(this._expand(z),M>0)z--;for(var _=0;_<z;_++)this.words[_]=~this.words[_]&67108863;if(M>0)this.words[_]=~this.words[_]&67108863>>26-M;return this.strip()},X.prototype.notn=function(H){return this.clone().inotn(H)},X.prototype.setn=function(H,z){Z(typeof H==="number"&&H>=0);var M=H/26|0,_=H%26;if(this._expand(M+1),z)this.words[M]=this.words[M]|1<<_;else this.words[M]=this.words[M]&~(1<<_);return this.strip()},X.prototype.iadd=function(H){var z;if(this.negative!==0&&H.negative===0)return this.negative=0,z=this.isub(H),this.negative^=1,this._normSign();else if(this.negative===0&&H.negative!==0)return H.negative=0,z=this.isub(H),H.negative=1,z._normSign();var M,_;if(this.length>H.length)M=this,_=H;else M=H,_=this;var I=0;for(var P=0;P<_.length;P++)z=(M.words[P]|0)+(_.words[P]|0)+I,this.words[P]=z&67108863,I=z>>>26;for(;I!==0&&P<M.length;P++)z=(M.words[P]|0)+I,this.words[P]=z&67108863,I=z>>>26;if(this.length=M.length,I!==0)this.words[this.length]=I,this.length++;else if(M!==this)for(;P<M.length;P++)this.words[P]=M.words[P];return this},X.prototype.add=function(H){var z;if(H.negative!==0&&this.negative===0)return H.negative=0,z=this.sub(H),H.negative^=1,z;else if(H.negative===0&&this.negative!==0)return this.negative=0,z=H.sub(this),this.negative=1,z;if(this.length>H.length)return this.clone().iadd(H);return H.clone().iadd(this)},X.prototype.isub=function(H){if(H.negative!==0){H.negative=0;var z=this.iadd(H);return H.negative=1,z._normSign()}else if(this.negative!==0)return this.negative=0,this.iadd(H),this.negative=1,this._normSign();var M=this.cmp(H);if(M===0)return this.negative=0,this.length=1,this.words[0]=0,this;var _,I;if(M>0)_=this,I=H;else _=H,I=this;var P=0;for(var S=0;S<I.length;S++)z=(_.words[S]|0)-(I.words[S]|0)+P,P=z>>26,this.words[S]=z&67108863;for(;P!==0&&S<_.length;S++)z=(_.words[S]|0)+P,P=z>>26,this.words[S]=z&67108863;if(P===0&&S<_.length&&_!==this)for(;S<_.length;S++)this.words[S]=_.words[S];if(this.length=Math.max(this.length,S),_!==this)this.negative=1;return this.strip()},X.prototype.sub=function(H){return this.clone().isub(H)};function L(j,H,z){z.negative=H.negative^j.negative;var M=j.length+H.length|0;z.length=M,M=M-1|0;var _=j.words[0]|0,I=H.words[0]|0,P=_*I,S=P&67108863,F=P/67108864|0;z.words[0]=S;for(var U=1;U<M;U++){var R=F>>>26,k=F&67108863,y=Math.min(U,H.length-1);for(var x=Math.max(0,U-j.length+1);x<=y;x++){var u=U-x|0;_=j.words[u]|0,I=H.words[x]|0,P=_*I+k,R+=P/67108864|0,k=P&67108863}z.words[U]=k|0,F=R|0}if(F!==0)z.words[U]=F|0;else z.length--;return z.strip()}var C=function(H,z,M){var _=H.words,I=z.words,P=M.words,S=0,F,U,R,k=_[0]|0,y=k&8191,x=k>>>13,u=_[1]|0,r=u&8191,e=u>>>13,_$=_[2]|0,$0=_$&8191,Z0=_$>>>13,fG=_[3]|0,H0=fG&8191,Q0=fG>>>13,gG=_[4]|0,U0=gG&8191,z0=gG>>>13,hG=_[5]|0,V0=hG&8191,O0=hG>>>13,bG=_[6]|0,M0=bG&8191,K0=bG>>>13,cG=_[7]|0,_0=cG&8191,A0=cG>>>13,pG=_[8]|0,F0=pG&8191,R0=pG>>>13,uG=_[9]|0,I0=uG&8191,j0=uG>>>13,nG=I[0]|0,q0=nG&8191,B0=nG>>>13,mG=I[1]|0,P0=mG&8191,L0=mG>>>13,dG=I[2]|0,S0=dG&8191,C0=dG>>>13,sG=I[3]|0,w0=sG&8191,E0=sG>>>13,oG=I[4]|0,T0=oG&8191,N0=oG>>>13,lG=I[5]|0,v0=lG&8191,D0=lG>>>13,rG=I[6]|0,k0=rG&8191,y0=rG>>>13,iG=I[7]|0,x0=iG&8191,f0=iG>>>13,tG=I[8]|0,g0=tG&8191,h0=tG>>>13,aG=I[9]|0,b0=aG&8191,c0=aG>>>13;M.negative=H.negative^z.negative,M.length=19,F=Math.imul(y,q0),U=Math.imul(y,B0),U=U+Math.imul(x,q0)|0,R=Math.imul(x,B0);var JZ=(S+F|0)+((U&8191)<<13)|0;S=(R+(U>>>13)|0)+(JZ>>>26)|0,JZ&=67108863,F=Math.imul(r,q0),U=Math.imul(r,B0),U=U+Math.imul(e,q0)|0,R=Math.imul(e,B0),F=F+Math.imul(y,P0)|0,U=U+Math.imul(y,L0)|0,U=U+Math.imul(x,P0)|0,R=R+Math.imul(x,L0)|0;var ZZ=(S+F|0)+((U&8191)<<13)|0;S=(R+(U>>>13)|0)+(ZZ>>>26)|0,ZZ&=67108863,F=Math.imul($0,q0),U=Math.imul($0,B0),U=U+Math.imul(Z0,q0)|0,R=Math.imul(Z0,B0),F=F+Math.imul(r,P0)|0,U=U+Math.imul(r,L0)|0,U=U+Math.imul(e,P0)|0,R=R+Math.imul(e,L0)|0,F=F+Math.imul(y,S0)|0,U=U+Math.imul(y,C0)|0,U=U+Math.imul(x,S0)|0,R=R+Math.imul(x,C0)|0;var GZ=(S+F|0)+((U&8191)<<13)|0;S=(R+(U>>>13)|0)+(GZ>>>26)|0,GZ&=67108863,F=Math.imul(H0,q0),U=Math.imul(H0,B0),U=U+Math.imul(Q0,q0)|0,R=Math.imul(Q0,B0),F=F+Math.imul($0,P0)|0,U=U+Math.imul($0,L0)|0,U=U+Math.imul(Z0,P0)|0,R=R+Math.imul(Z0,L0)|0,F=F+Math.imul(r,S0)|0,U=U+Math.imul(r,C0)|0,U=U+Math.imul(e,S0)|0,R=R+Math.imul(e,C0)|0,F=F+Math.imul(y,w0)|0,U=U+Math.imul(y,E0)|0,U=U+Math.imul(x,w0)|0,R=R+Math.imul(x,E0)|0;var XZ=(S+F|0)+((U&8191)<<13)|0;S=(R+(U>>>13)|0)+(XZ>>>26)|0,XZ&=67108863,F=Math.imul(U0,q0),U=Math.imul(U0,B0),U=U+Math.imul(z0,q0)|0,R=Math.imul(z0,B0),F=F+Math.imul(H0,P0)|0,U=U+Math.imul(H0,L0)|0,U=U+Math.imul(Q0,P0)|0,R=R+Math.imul(Q0,L0)|0,F=F+Math.imul($0,S0)|0,U=U+Math.imul($0,C0)|0,U=U+Math.imul(Z0,S0)|0,R=R+Math.imul(Z0,C0)|0,F=F+Math.imul(r,w0)|0,U=U+Math.imul(r,E0)|0,U=U+Math.imul(e,w0)|0,R=R+Math.imul(e,E0)|0,F=F+Math.imul(y,T0)|0,U=U+Math.imul(y,N0)|0,U=U+Math.imul(x,T0)|0,R=R+Math.imul(x,N0)|0;var YZ=(S+F|0)+((U&8191)<<13)|0;S=(R+(U>>>13)|0)+(YZ>>>26)|0,YZ&=67108863,F=Math.imul(V0,q0),U=Math.imul(V0,B0),U=U+Math.imul(O0,q0)|0,R=Math.imul(O0,B0),F=F+Math.imul(U0,P0)|0,U=U+Math.imul(U0,L0)|0,U=U+Math.imul(z0,P0)|0,R=R+Math.imul(z0,L0)|0,F=F+Math.imul(H0,S0)|0,U=U+Math.imul(H0,C0)|0,U=U+Math.imul(Q0,S0)|0,R=R+Math.imul(Q0,C0)|0,F=F+Math.imul($0,w0)|0,U=U+Math.imul($0,E0)|0,U=U+Math.imul(Z0,w0)|0,R=R+Math.imul(Z0,E0)|0,F=F+Math.imul(r,T0)|0,U=U+Math.imul(r,N0)|0,U=U+Math.imul(e,T0)|0,R=R+Math.imul(e,N0)|0,F=F+Math.imul(y,v0)|0,U=U+Math.imul(y,D0)|0,U=U+Math.imul(x,v0)|0,R=R+Math.imul(x,D0)|0;var WZ=(S+F|0)+((U&8191)<<13)|0;S=(R+(U>>>13)|0)+(WZ>>>26)|0,WZ&=67108863,F=Math.imul(M0,q0),U=Math.imul(M0,B0),U=U+Math.imul(K0,q0)|0,R=Math.imul(K0,B0),F=F+Math.imul(V0,P0)|0,U=U+Math.imul(V0,L0)|0,U=U+Math.imul(O0,P0)|0,R=R+Math.imul(O0,L0)|0,F=F+Math.imul(U0,S0)|0,U=U+Math.imul(U0,C0)|0,U=U+Math.imul(z0,S0)|0,R=R+Math.imul(z0,C0)|0,F=F+Math.imul(H0,w0)|0,U=U+Math.imul(H0,E0)|0,U=U+Math.imul(Q0,w0)|0,R=R+Math.imul(Q0,E0)|0,F=F+Math.imul($0,T0)|0,U=U+Math.imul($0,N0)|0,U=U+Math.imul(Z0,T0)|0,R=R+Math.imul(Z0,N0)|0,F=F+Math.imul(r,v0)|0,U=U+Math.imul(r,D0)|0,U=U+Math.imul(e,v0)|0,R=R+Math.imul(e,D0)|0,F=F+Math.imul(y,k0)|0,U=U+Math.imul(y,y0)|0,U=U+Math.imul(x,k0)|0,R=R+Math.imul(x,y0)|0;var HZ=(S+F|0)+((U&8191)<<13)|0;S=(R+(U>>>13)|0)+(HZ>>>26)|0,HZ&=67108863,F=Math.imul(_0,q0),U=Math.imul(_0,B0),U=U+Math.imul(A0,q0)|0,R=Math.imul(A0,B0),F=F+Math.imul(M0,P0)|0,U=U+Math.imul(M0,L0)|0,U=U+Math.imul(K0,P0)|0,R=R+Math.imul(K0,L0)|0,F=F+Math.imul(V0,S0)|0,U=U+Math.imul(V0,C0)|0,U=U+Math.imul(O0,S0)|0,R=R+Math.imul(O0,C0)|0,F=F+Math.imul(U0,w0)|0,U=U+Math.imul(U0,E0)|0,U=U+Math.imul(z0,w0)|0,R=R+Math.imul(z0,E0)|0,F=F+Math.imul(H0,T0)|0,U=U+Math.imul(H0,N0)|0,U=U+Math.imul(Q0,T0)|0,R=R+Math.imul(Q0,N0)|0,F=F+Math.imul($0,v0)|0,U=U+Math.imul($0,D0)|0,U=U+Math.imul(Z0,v0)|0,R=R+Math.imul(Z0,D0)|0,F=F+Math.imul(r,k0)|0,U=U+Math.imul(r,y0)|0,U=U+Math.imul(e,k0)|0,R=R+Math.imul(e,y0)|0,F=F+Math.imul(y,x0)|0,U=U+Math.imul(y,f0)|0,U=U+Math.imul(x,x0)|0,R=R+Math.imul(x,f0)|0;var QZ=(S+F|0)+((U&8191)<<13)|0;S=(R+(U>>>13)|0)+(QZ>>>26)|0,QZ&=67108863,F=Math.imul(F0,q0),U=Math.imul(F0,B0),U=U+Math.imul(R0,q0)|0,R=Math.imul(R0,B0),F=F+Math.imul(_0,P0)|0,U=U+Math.imul(_0,L0)|0,U=U+Math.imul(A0,P0)|0,R=R+Math.imul(A0,L0)|0,F=F+Math.imul(M0,S0)|0,U=U+Math.imul(M0,C0)|0,U=U+Math.imul(K0,S0)|0,R=R+Math.imul(K0,C0)|0,F=F+Math.imul(V0,w0)|0,U=U+Math.imul(V0,E0)|0,U=U+Math.imul(O0,w0)|0,R=R+Math.imul(O0,E0)|0,F=F+Math.imul(U0,T0)|0,U=U+Math.imul(U0,N0)|0,U=U+Math.imul(z0,T0)|0,R=R+Math.imul(z0,N0)|0,F=F+Math.imul(H0,v0)|0,U=U+Math.imul(H0,D0)|0,U=U+Math.imul(Q0,v0)|0,R=R+Math.imul(Q0,D0)|0,F=F+Math.imul($0,k0)|0,U=U+Math.imul($0,y0)|0,U=U+Math.imul(Z0,k0)|0,R=R+Math.imul(Z0,y0)|0,F=F+Math.imul(r,x0)|0,U=U+Math.imul(r,f0)|0,U=U+Math.imul(e,x0)|0,R=R+Math.imul(e,f0)|0,F=F+Math.imul(y,g0)|0,U=U+Math.imul(y,h0)|0,U=U+Math.imul(x,g0)|0,R=R+Math.imul(x,h0)|0;var UZ=(S+F|0)+((U&8191)<<13)|0;S=(R+(U>>>13)|0)+(UZ>>>26)|0,UZ&=67108863,F=Math.imul(I0,q0),U=Math.imul(I0,B0),U=U+Math.imul(j0,q0)|0,R=Math.imul(j0,B0),F=F+Math.imul(F0,P0)|0,U=U+Math.imul(F0,L0)|0,U=U+Math.imul(R0,P0)|0,R=R+Math.imul(R0,L0)|0,F=F+Math.imul(_0,S0)|0,U=U+Math.imul(_0,C0)|0,U=U+Math.imul(A0,S0)|0,R=R+Math.imul(A0,C0)|0,F=F+Math.imul(M0,w0)|0,U=U+Math.imul(M0,E0)|0,U=U+Math.imul(K0,w0)|0,R=R+Math.imul(K0,E0)|0,F=F+Math.imul(V0,T0)|0,U=U+Math.imul(V0,N0)|0,U=U+Math.imul(O0,T0)|0,R=R+Math.imul(O0,N0)|0,F=F+Math.imul(U0,v0)|0,U=U+Math.imul(U0,D0)|0,U=U+Math.imul(z0,v0)|0,R=R+Math.imul(z0,D0)|0,F=F+Math.imul(H0,k0)|0,U=U+Math.imul(H0,y0)|0,U=U+Math.imul(Q0,k0)|0,R=R+Math.imul(Q0,y0)|0,F=F+Math.imul($0,x0)|0,U=U+Math.imul($0,f0)|0,U=U+Math.imul(Z0,x0)|0,R=R+Math.imul(Z0,f0)|0,F=F+Math.imul(r,g0)|0,U=U+Math.imul(r,h0)|0,U=U+Math.imul(e,g0)|0,R=R+Math.imul(e,h0)|0,F=F+Math.imul(y,b0)|0,U=U+Math.imul(y,c0)|0,U=U+Math.imul(x,b0)|0,R=R+Math.imul(x,c0)|0;var zZ=(S+F|0)+((U&8191)<<13)|0;S=(R+(U>>>13)|0)+(zZ>>>26)|0,zZ&=67108863,F=Math.imul(I0,P0),U=Math.imul(I0,L0),U=U+Math.imul(j0,P0)|0,R=Math.imul(j0,L0),F=F+Math.imul(F0,S0)|0,U=U+Math.imul(F0,C0)|0,U=U+Math.imul(R0,S0)|0,R=R+Math.imul(R0,C0)|0,F=F+Math.imul(_0,w0)|0,U=U+Math.imul(_0,E0)|0,U=U+Math.imul(A0,w0)|0,R=R+Math.imul(A0,E0)|0,F=F+Math.imul(M0,T0)|0,U=U+Math.imul(M0,N0)|0,U=U+Math.imul(K0,T0)|0,R=R+Math.imul(K0,N0)|0,F=F+Math.imul(V0,v0)|0,U=U+Math.imul(V0,D0)|0,U=U+Math.imul(O0,v0)|0,R=R+Math.imul(O0,D0)|0,F=F+Math.imul(U0,k0)|0,U=U+Math.imul(U0,y0)|0,U=U+Math.imul(z0,k0)|0,R=R+Math.imul(z0,y0)|0,F=F+Math.imul(H0,x0)|0,U=U+Math.imul(H0,f0)|0,U=U+Math.imul(Q0,x0)|0,R=R+Math.imul(Q0,f0)|0,F=F+Math.imul($0,g0)|0,U=U+Math.imul($0,h0)|0,U=U+Math.imul(Z0,g0)|0,R=R+Math.imul(Z0,h0)|0,F=F+Math.imul(r,b0)|0,U=U+Math.imul(r,c0)|0,U=U+Math.imul(e,b0)|0,R=R+Math.imul(e,c0)|0;var VZ=(S+F|0)+((U&8191)<<13)|0;S=(R+(U>>>13)|0)+(VZ>>>26)|0,VZ&=67108863,F=Math.imul(I0,S0),U=Math.imul(I0,C0),U=U+Math.imul(j0,S0)|0,R=Math.imul(j0,C0),F=F+Math.imul(F0,w0)|0,U=U+Math.imul(F0,E0)|0,U=U+Math.imul(R0,w0)|0,R=R+Math.imul(R0,E0)|0,F=F+Math.imul(_0,T0)|0,U=U+Math.imul(_0,N0)|0,U=U+Math.imul(A0,T0)|0,R=R+Math.imul(A0,N0)|0,F=F+Math.imul(M0,v0)|0,U=U+Math.imul(M0,D0)|0,U=U+Math.imul(K0,v0)|0,R=R+Math.imul(K0,D0)|0,F=F+Math.imul(V0,k0)|0,U=U+Math.imul(V0,y0)|0,U=U+Math.imul(O0,k0)|0,R=R+Math.imul(O0,y0)|0,F=F+Math.imul(U0,x0)|0,U=U+Math.imul(U0,f0)|0,U=U+Math.imul(z0,x0)|0,R=R+Math.imul(z0,f0)|0,F=F+Math.imul(H0,g0)|0,U=U+Math.imul(H0,h0)|0,U=U+Math.imul(Q0,g0)|0,R=R+Math.imul(Q0,h0)|0,F=F+Math.imul($0,b0)|0,U=U+Math.imul($0,c0)|0,U=U+Math.imul(Z0,b0)|0,R=R+Math.imul(Z0,c0)|0;var OZ=(S+F|0)+((U&8191)<<13)|0;S=(R+(U>>>13)|0)+(OZ>>>26)|0,OZ&=67108863,F=Math.imul(I0,w0),U=Math.imul(I0,E0),U=U+Math.imul(j0,w0)|0,R=Math.imul(j0,E0),F=F+Math.imul(F0,T0)|0,U=U+Math.imul(F0,N0)|0,U=U+Math.imul(R0,T0)|0,R=R+Math.imul(R0,N0)|0,F=F+Math.imul(_0,v0)|0,U=U+Math.imul(_0,D0)|0,U=U+Math.imul(A0,v0)|0,R=R+Math.imul(A0,D0)|0,F=F+Math.imul(M0,k0)|0,U=U+Math.imul(M0,y0)|0,U=U+Math.imul(K0,k0)|0,R=R+Math.imul(K0,y0)|0,F=F+Math.imul(V0,x0)|0,U=U+Math.imul(V0,f0)|0,U=U+Math.imul(O0,x0)|0,R=R+Math.imul(O0,f0)|0,F=F+Math.imul(U0,g0)|0,U=U+Math.imul(U0,h0)|0,U=U+Math.imul(z0,g0)|0,R=R+Math.imul(z0,h0)|0,F=F+Math.imul(H0,b0)|0,U=U+Math.imul(H0,c0)|0,U=U+Math.imul(Q0,b0)|0,R=R+Math.imul(Q0,c0)|0;var MZ=(S+F|0)+((U&8191)<<13)|0;S=(R+(U>>>13)|0)+(MZ>>>26)|0,MZ&=67108863,F=Math.imul(I0,T0),U=Math.imul(I0,N0),U=U+Math.imul(j0,T0)|0,R=Math.imul(j0,N0),F=F+Math.imul(F0,v0)|0,U=U+Math.imul(F0,D0)|0,U=U+Math.imul(R0,v0)|0,R=R+Math.imul(R0,D0)|0,F=F+Math.imul(_0,k0)|0,U=U+Math.imul(_0,y0)|0,U=U+Math.imul(A0,k0)|0,R=R+Math.imul(A0,y0)|0,F=F+Math.imul(M0,x0)|0,U=U+Math.imul(M0,f0)|0,U=U+Math.imul(K0,x0)|0,R=R+Math.imul(K0,f0)|0,F=F+Math.imul(V0,g0)|0,U=U+Math.imul(V0,h0)|0,U=U+Math.imul(O0,g0)|0,R=R+Math.imul(O0,h0)|0,F=F+Math.imul(U0,b0)|0,U=U+Math.imul(U0,c0)|0,U=U+Math.imul(z0,b0)|0,R=R+Math.imul(z0,c0)|0;var KZ=(S+F|0)+((U&8191)<<13)|0;S=(R+(U>>>13)|0)+(KZ>>>26)|0,KZ&=67108863,F=Math.imul(I0,v0),U=Math.imul(I0,D0),U=U+Math.imul(j0,v0)|0,R=Math.imul(j0,D0),F=F+Math.imul(F0,k0)|0,U=U+Math.imul(F0,y0)|0,U=U+Math.imul(R0,k0)|0,R=R+Math.imul(R0,y0)|0,F=F+Math.imul(_0,x0)|0,U=U+Math.imul(_0,f0)|0,U=U+Math.imul(A0,x0)|0,R=R+Math.imul(A0,f0)|0,F=F+Math.imul(M0,g0)|0,U=U+Math.imul(M0,h0)|0,U=U+Math.imul(K0,g0)|0,R=R+Math.imul(K0,h0)|0,F=F+Math.imul(V0,b0)|0,U=U+Math.imul(V0,c0)|0,U=U+Math.imul(O0,b0)|0,R=R+Math.imul(O0,c0)|0;var _Z=(S+F|0)+((U&8191)<<13)|0;S=(R+(U>>>13)|0)+(_Z>>>26)|0,_Z&=67108863,F=Math.imul(I0,k0),U=Math.imul(I0,y0),U=U+Math.imul(j0,k0)|0,R=Math.imul(j0,y0),F=F+Math.imul(F0,x0)|0,U=U+Math.imul(F0,f0)|0,U=U+Math.imul(R0,x0)|0,R=R+Math.imul(R0,f0)|0,F=F+Math.imul(_0,g0)|0,U=U+Math.imul(_0,h0)|0,U=U+Math.imul(A0,g0)|0,R=R+Math.imul(A0,h0)|0,F=F+Math.imul(M0,b0)|0,U=U+Math.imul(M0,c0)|0,U=U+Math.imul(K0,b0)|0,R=R+Math.imul(K0,c0)|0;var AZ=(S+F|0)+((U&8191)<<13)|0;S=(R+(U>>>13)|0)+(AZ>>>26)|0,AZ&=67108863,F=Math.imul(I0,x0),U=Math.imul(I0,f0),U=U+Math.imul(j0,x0)|0,R=Math.imul(j0,f0),F=F+Math.imul(F0,g0)|0,U=U+Math.imul(F0,h0)|0,U=U+Math.imul(R0,g0)|0,R=R+Math.imul(R0,h0)|0,F=F+Math.imul(_0,b0)|0,U=U+Math.imul(_0,c0)|0,U=U+Math.imul(A0,b0)|0,R=R+Math.imul(A0,c0)|0;var FZ=(S+F|0)+((U&8191)<<13)|0;S=(R+(U>>>13)|0)+(FZ>>>26)|0,FZ&=67108863,F=Math.imul(I0,g0),U=Math.imul(I0,h0),U=U+Math.imul(j0,g0)|0,R=Math.imul(j0,h0),F=F+Math.imul(F0,b0)|0,U=U+Math.imul(F0,c0)|0,U=U+Math.imul(R0,b0)|0,R=R+Math.imul(R0,c0)|0;var RZ=(S+F|0)+((U&8191)<<13)|0;S=(R+(U>>>13)|0)+(RZ>>>26)|0,RZ&=67108863,F=Math.imul(I0,b0),U=Math.imul(I0,c0),U=U+Math.imul(j0,b0)|0,R=Math.imul(j0,c0);var IZ=(S+F|0)+((U&8191)<<13)|0;if(S=(R+(U>>>13)|0)+(IZ>>>26)|0,IZ&=67108863,P[0]=JZ,P[1]=ZZ,P[2]=GZ,P[3]=XZ,P[4]=YZ,P[5]=WZ,P[6]=HZ,P[7]=QZ,P[8]=UZ,P[9]=zZ,P[10]=VZ,P[11]=OZ,P[12]=MZ,P[13]=KZ,P[14]=_Z,P[15]=AZ,P[16]=FZ,P[17]=RZ,P[18]=IZ,S!==0)P[19]=S,M.length++;return M};if(!Math.imul)C=L;function T(j,H,z){z.negative=H.negative^j.negative,z.length=j.length+H.length;var M=0,_=0;for(var I=0;I<z.length-1;I++){var P=_;_=0;var S=M&67108863,F=Math.min(I,H.length-1);for(var U=Math.max(0,I-j.length+1);U<=F;U++){var R=I-U,k=j.words[R]|0,y=H.words[U]|0,x=k*y,u=x&67108863;P=P+(x/67108864|0)|0,u=u+S|0,S=u&67108863,P=P+(u>>>26)|0,_+=P>>>26,P&=67108863}z.words[I]=S,M=P,P=_}if(M!==0)z.words[I]=M;else z.length--;return z.strip()}function w(j,H,z){var M=new D;return M.mulp(j,H,z)}X.prototype.mulTo=function(H,z){var M,_=this.length+H.length;if(this.length===10&&H.length===10)M=C(this,H,z);else if(_<63)M=L(this,H,z);else if(_<1024)M=T(this,H,z);else M=w(this,H,z);return M};function D(j,H){this.x=j,this.y=H}D.prototype.makeRBT=function(H){var z=Array(H),M=X.prototype._countBits(H)-1;for(var _=0;_<H;_++)z[_]=this.revBin(_,M,H);return z},D.prototype.revBin=function(H,z,M){if(H===0||H===M-1)return H;var _=0;for(var I=0;I<z;I++)_|=(H&1)<<z-I-1,H>>=1;return _},D.prototype.permute=function(H,z,M,_,I,P){for(var S=0;S<P;S++)_[S]=z[H[S]],I[S]=M[H[S]]},D.prototype.transform=function(H,z,M,_,I,P){this.permute(P,H,z,M,_,I);for(var S=1;S<I;S<<=1){var F=S<<1,U=Math.cos(2*Math.PI/F),R=Math.sin(2*Math.PI/F);for(var k=0;k<I;k+=F){var y=U,x=R;for(var u=0;u<S;u++){var r=M[k+u],e=_[k+u],_$=M[k+u+S],$0=_[k+u+S],Z0=y*_$-x*$0;if($0=y*$0+x*_$,_$=Z0,M[k+u]=r+_$,_[k+u]=e+$0,M[k+u+S]=r-_$,_[k+u+S]=e-$0,u!==F)Z0=U*y-R*x,x=U*x+R*y,y=Z0}}}},D.prototype.guessLen13b=function(H,z){var M=Math.max(z,H)|1,_=M&1,I=0;for(M=M/2|0;M;M=M>>>1)I++;return 1<<I+1+_},D.prototype.conjugate=function(H,z,M){if(M<=1)return;for(var _=0;_<M/2;_++){var I=H[_];H[_]=H[M-_-1],H[M-_-1]=I,I=z[_],z[_]=-z[M-_-1],z[M-_-1]=-I}},D.prototype.normalize13b=function(H,z){var M=0;for(var _=0;_<z/2;_++){var I=Math.round(H[2*_+1]/z)*8192+Math.round(H[2*_]/z)+M;if(H[_]=I&67108863,I<67108864)M=0;else M=I/67108864|0}return H},D.prototype.convert13b=function(H,z,M,_){var I=0;for(var P=0;P<z;P++)I=I+(H[P]|0),M[2*P]=I&8191,I=I>>>13,M[2*P+1]=I&8191,I=I>>>13;for(P=2*z;P<_;++P)M[P]=0;Z(I===0),Z((I&-8192)===0)},D.prototype.stub=function(H){var z=Array(H);for(var M=0;M<H;M++)z[M]=0;return z},D.prototype.mulp=function(H,z,M){var _=2*this.guessLen13b(H.length,z.length),I=this.makeRBT(_),P=this.stub(_),S=Array(_),F=Array(_),U=Array(_),R=Array(_),k=Array(_),y=Array(_),x=M.words;x.length=_,this.convert13b(H.words,H.length,S,_),this.convert13b(z.words,z.length,R,_),this.transform(S,P,F,U,_,I),this.transform(R,P,k,y,_,I);for(var u=0;u<_;u++){var r=F[u]*k[u]-U[u]*y[u];U[u]=F[u]*y[u]+U[u]*k[u],F[u]=r}return this.conjugate(F,U,_),this.transform(F,U,x,P,_,I),this.conjugate(x,P,_),this.normalize13b(x,_),M.negative=H.negative^z.negative,M.length=H.length+z.length,M.strip()},X.prototype.mul=function(H){var z=new X(null);return z.words=Array(this.length+H.length),this.mulTo(H,z)},X.prototype.mulf=function(H){var z=new X(null);return z.words=Array(this.length+H.length),w(this,H,z)},X.prototype.imul=function(H){return this.clone().mulTo(H,this)},X.prototype.imuln=function(H){Z(typeof H==="number"),Z(H<67108864);var z=0;for(var M=0;M<this.length;M++){var _=(this.words[M]|0)*H,I=(_&67108863)+(z&67108863);z>>=26,z+=_/67108864|0,z+=I>>>26,this.words[M]=I&67108863}if(z!==0)this.words[M]=z,this.length++;return this.length=H===0?1:this.length,this},X.prototype.muln=function(H){return this.clone().imuln(H)},X.prototype.sqr=function(){return this.mul(this)},X.prototype.isqr=function(){return this.imul(this.clone())},X.prototype.pow=function(H){var z=B(H);if(z.length===0)return new X(1);var M=this;for(var _=0;_<z.length;_++,M=M.sqr())if(z[_]!==0)break;if(++_<z.length)for(var I=M.sqr();_<z.length;_++,I=I.sqr()){if(z[_]===0)continue;M=M.mul(I)}return M},X.prototype.iushln=function(H){Z(typeof H==="number"&&H>=0);var z=H%26,M=(H-z)/26,_=67108863>>>26-z<<26-z,I;if(z!==0){var P=0;for(I=0;I<this.length;I++){var S=this.words[I]&_,F=(this.words[I]|0)-S<<z;this.words[I]=F|P,P=S>>>26-z}if(P)this.words[I]=P,this.length++}if(M!==0){for(I=this.length-1;I>=0;I--)this.words[I+M]=this.words[I];for(I=0;I<M;I++)this.words[I]=0;this.length+=M}return this.strip()},X.prototype.ishln=function(H){return Z(this.negative===0),this.iushln(H)},X.prototype.iushrn=function(H,z,M){Z(typeof H==="number"&&H>=0);var _;if(z)_=(z-z%26)/26;else _=0;var I=H%26,P=Math.min((H-I)/26,this.length),S=67108863^67108863>>>I<<I,F=M;if(_-=P,_=Math.max(0,_),F){for(var U=0;U<P;U++)F.words[U]=this.words[U];F.length=P}if(P===0);else if(this.length>P){this.length-=P;for(U=0;U<this.length;U++)this.words[U]=this.words[U+P]}else this.words[0]=0,this.length=1;var R=0;for(U=this.length-1;U>=0&&(R!==0||U>=_);U--){var k=this.words[U]|0;this.words[U]=R<<26-I|k>>>I,R=k&S}if(F&&R!==0)F.words[F.length++]=R;if(this.length===0)this.words[0]=0,this.length=1;return this.strip()},X.prototype.ishrn=function(H,z,M){return Z(this.negative===0),this.iushrn(H,z,M)},X.prototype.shln=function(H){return this.clone().ishln(H)},X.prototype.ushln=function(H){return this.clone().iushln(H)},X.prototype.shrn=function(H){return this.clone().ishrn(H)},X.prototype.ushrn=function(H){return this.clone().iushrn(H)},X.prototype.testn=function(H){Z(typeof H==="number"&&H>=0);var z=H%26,M=(H-z)/26,_=1<<z;if(this.length<=M)return!1;var I=this.words[M];return!!(I&_)},X.prototype.imaskn=function(H){Z(typeof H==="number"&&H>=0);var z=H%26,M=(H-z)/26;if(Z(this.negative===0,"imaskn works only with positive numbers"),this.length<=M)return this;if(z!==0)M++;if(this.length=Math.min(M,this.length),z!==0){var _=67108863^67108863>>>z<<z;this.words[this.length-1]&=_}return this.strip()},X.prototype.maskn=function(H){return this.clone().imaskn(H)},X.prototype.iaddn=function(H){if(Z(typeof H==="number"),Z(H<67108864),H<0)return this.isubn(-H);if(this.negative!==0){if(this.length===1&&(this.words[0]|0)<H)return this.words[0]=H-(this.words[0]|0),this.negative=0,this;return this.negative=0,this.isubn(H),this.negative=1,this}return this._iaddn(H)},X.prototype._iaddn=function(H){this.words[0]+=H;for(var z=0;z<this.length&&this.words[z]>=67108864;z++)if(this.words[z]-=67108864,z===this.length-1)this.words[z+1]=1;else this.words[z+1]++;return this.length=Math.max(this.length,z+1),this},X.prototype.isubn=function(H){if(Z(typeof H==="number"),Z(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 z=0;z<this.length&&this.words[z]<0;z++)this.words[z]+=67108864,this.words[z+1]-=1;return this.strip()},X.prototype.addn=function(H){return this.clone().iaddn(H)},X.prototype.subn=function(H){return this.clone().isubn(H)},X.prototype.iabs=function(){return this.negative=0,this},X.prototype.abs=function(){return this.clone().iabs()},X.prototype._ishlnsubmul=function(H,z,M){var _=H.length+M,I;this._expand(_);var P,S=0;for(I=0;I<H.length;I++){P=(this.words[I+M]|0)+S;var F=(H.words[I]|0)*z;P-=F&67108863,S=(P>>26)-(F/67108864|0),this.words[I+M]=P&67108863}for(;I<this.length-M;I++)P=(this.words[I+M]|0)+S,S=P>>26,this.words[I+M]=P&67108863;if(S===0)return this.strip();Z(S===-1),S=0;for(I=0;I<this.length;I++)P=-(this.words[I]|0)+S,S=P>>26,this.words[I]=P&67108863;return this.negative=1,this.strip()},X.prototype._wordDiv=function(H,z){var M=this.length-H.length,_=this.clone(),I=H,P=I.words[I.length-1]|0,S=this._countBits(P);if(M=26-S,M!==0)I=I.ushln(M),_.iushln(M),P=I.words[I.length-1]|0;var F=_.length-I.length,U;if(z!=="mod"){U=new X(null),U.length=F+1,U.words=Array(U.length);for(var R=0;R<U.length;R++)U.words[R]=0}var k=_.clone()._ishlnsubmul(I,1,F);if(k.negative===0){if(_=k,U)U.words[F]=1}for(var y=F-1;y>=0;y--){var x=(_.words[I.length+y]|0)*67108864+(_.words[I.length+y-1]|0);x=Math.min(x/P|0,67108863),_._ishlnsubmul(I,x,y);while(_.negative!==0)if(x--,_.negative=0,_._ishlnsubmul(I,1,y),!_.isZero())_.negative^=1;if(U)U.words[y]=x}if(U)U.strip();if(_.strip(),z!=="div"&&M!==0)_.iushrn(M);return{div:U||null,mod:_}},X.prototype.divmod=function(H,z,M){if(Z(!H.isZero()),this.isZero())return{div:new X(0),mod:new X(0)};var _,I,P;if(this.negative!==0&&H.negative===0){if(P=this.neg().divmod(H,z),z!=="mod")_=P.div.neg();if(z!=="div"){if(I=P.mod.neg(),M&&I.negative!==0)I.iadd(H)}return{div:_,mod:I}}if(this.negative===0&&H.negative!==0){if(P=this.divmod(H.neg(),z),z!=="mod")_=P.div.neg();return{div:_,mod:P.mod}}if((this.negative&H.negative)!==0){if(P=this.neg().divmod(H.neg(),z),z!=="div"){if(I=P.mod.neg(),M&&I.negative!==0)I.isub(H)}return{div:P.div,mod:I}}if(H.length>this.length||this.cmp(H)<0)return{div:new X(0),mod:this};if(H.length===1){if(z==="div")return{div:this.divn(H.words[0]),mod:null};if(z==="mod")return{div:null,mod:new X(this.modn(H.words[0]))};return{div:this.divn(H.words[0]),mod:new X(this.modn(H.words[0]))}}return this._wordDiv(H,z)},X.prototype.div=function(H){return this.divmod(H,"div",!1).div},X.prototype.mod=function(H){return this.divmod(H,"mod",!1).mod},X.prototype.umod=function(H){return this.divmod(H,"mod",!0).mod},X.prototype.divRound=function(H){var z=this.divmod(H);if(z.mod.isZero())return z.div;var M=z.div.negative!==0?z.mod.isub(H):z.mod,_=H.ushrn(1),I=H.andln(1),P=M.cmp(_);if(P<0||I===1&&P===0)return z.div;return z.div.negative!==0?z.div.isubn(1):z.div.iaddn(1)},X.prototype.modn=function(H){Z(H<=67108863);var z=67108864%H,M=0;for(var _=this.length-1;_>=0;_--)M=(z*M+(this.words[_]|0))%H;return M},X.prototype.idivn=function(H){Z(H<=67108863);var z=0;for(var M=this.length-1;M>=0;M--){var _=(this.words[M]|0)+z*67108864;this.words[M]=_/H|0,z=_%H}return this.strip()},X.prototype.divn=function(H){return this.clone().idivn(H)},X.prototype.egcd=function(H){Z(H.negative===0),Z(!H.isZero());var z=this,M=H.clone();if(z.negative!==0)z=z.umod(H);else z=z.clone();var _=new X(1),I=new X(0),P=new X(0),S=new X(1),F=0;while(z.isEven()&&M.isEven())z.iushrn(1),M.iushrn(1),++F;var U=M.clone(),R=z.clone();while(!z.isZero()){for(var k=0,y=1;(z.words[0]&y)===0&&k<26;++k,y<<=1);if(k>0){z.iushrn(k);while(k-- >0){if(_.isOdd()||I.isOdd())_.iadd(U),I.isub(R);_.iushrn(1),I.iushrn(1)}}for(var x=0,u=1;(M.words[0]&u)===0&&x<26;++x,u<<=1);if(x>0){M.iushrn(x);while(x-- >0){if(P.isOdd()||S.isOdd())P.iadd(U),S.isub(R);P.iushrn(1),S.iushrn(1)}}if(z.cmp(M)>=0)z.isub(M),_.isub(P),I.isub(S);else M.isub(z),P.isub(_),S.isub(I)}return{a:P,b:S,gcd:M.iushln(F)}},X.prototype._invmp=function(H){Z(H.negative===0),Z(!H.isZero());var z=this,M=H.clone();if(z.negative!==0)z=z.umod(H);else z=z.clone();var _=new X(1),I=new X(0),P=M.clone();while(z.cmpn(1)>0&&M.cmpn(1)>0){for(var S=0,F=1;(z.words[0]&F)===0&&S<26;++S,F<<=1);if(S>0){z.iushrn(S);while(S-- >0){if(_.isOdd())_.iadd(P);_.iushrn(1)}}for(var U=0,R=1;(M.words[0]&R)===0&&U<26;++U,R<<=1);if(U>0){M.iushrn(U);while(U-- >0){if(I.isOdd())I.iadd(P);I.iushrn(1)}}if(z.cmp(M)>=0)z.isub(M),_.isub(I);else M.isub(z),I.isub(_)}var k;if(z.cmpn(1)===0)k=_;else k=I;if(k.cmpn(0)<0)k.iadd(H);return k},X.prototype.gcd=function(H){if(this.isZero())return H.abs();if(H.isZero())return this.abs();var z=this.clone(),M=H.clone();z.negative=0,M.negative=0;for(var _=0;z.isEven()&&M.isEven();_++)z.iushrn(1),M.iushrn(1);do{while(z.isEven())z.iushrn(1);while(M.isEven())M.iushrn(1);var I=z.cmp(M);if(I<0){var P=z;z=M,M=P}else if(I===0||M.cmpn(1)===0)break;z.isub(M)}while(!0);return M.iushln(_)},X.prototype.invm=function(H){return this.egcd(H).a.umod(H)},X.prototype.isEven=function(){return(this.words[0]&1)===0},X.prototype.isOdd=function(){return(this.words[0]&1)===1},X.prototype.andln=function(H){return this.words[0]&H},X.prototype.bincn=function(H){Z(typeof H==="number");var z=H%26,M=(H-z)/26,_=1<<z;if(this.length<=M)return this._expand(M+1),this.words[M]|=_,this;var I=_;for(var P=M;I!==0&&P<this.length;P++){var S=this.words[P]|0;S+=I,I=S>>>26,S&=67108863,this.words[P]=S}if(I!==0)this.words[P]=I,this.length++;return this},X.prototype.isZero=function(){return this.length===1&&this.words[0]===0},X.prototype.cmpn=function(H){var z=H<0;if(this.negative!==0&&!z)return-1;if(this.negative===0&&z)return 1;this.strip();var M;if(this.length>1)M=1;else{if(z)H=-H;Z(H<=67108863,"Number is too big");var _=this.words[0]|0;M=_===H?0:_<H?-1:1}if(this.negative!==0)return-M|0;return M},X.prototype.cmp=function(H){if(this.negative!==0&&H.negative===0)return-1;if(this.negative===0&&H.negative!==0)return 1;var z=this.ucmp(H);if(this.negative!==0)return-z|0;return z},X.prototype.ucmp=function(H){if(this.length>H.length)return 1;if(this.length<H.length)return-1;var z=0;for(var M=this.length-1;M>=0;M--){var _=this.words[M]|0,I=H.words[M]|0;if(_===I)continue;if(_<I)z=-1;else if(_>I)z=1;break}return z},X.prototype.gtn=function(H){return this.cmpn(H)===1},X.prototype.gt=function(H){return this.cmp(H)===1},X.prototype.gten=function(H){return this.cmpn(H)>=0},X.prototype.gte=function(H){return this.cmp(H)>=0},X.prototype.ltn=function(H){return this.cmpn(H)===-1},X.prototype.lt=function(H){return this.cmp(H)===-1},X.prototype.lten=function(H){return this.cmpn(H)<=0},X.prototype.lte=function(H){return this.cmp(H)<=0},X.prototype.eqn=function(H){return this.cmpn(H)===0},X.prototype.eq=function(H){return this.cmp(H)===0},X.red=function(H){return new l(H)},X.prototype.toRed=function(H){return Z(!this.red,"Already a number in reduction context"),Z(this.negative===0,"red works only with positives"),H.convertTo(this)._forceRed(H)},X.prototype.fromRed=function(){return Z(this.red,"fromRed works only with numbers in reduction context"),this.red.convertFrom(this)},X.prototype._forceRed=function(H){return this.red=H,this},X.prototype.forceRed=function(H){return Z(!this.red,"Already a number in reduction context"),this._forceRed(H)},X.prototype.redAdd=function(H){return Z(this.red,"redAdd works only with red numbers"),this.red.add(this,H)},X.prototype.redIAdd=function(H){return Z(this.red,"redIAdd works only with red numbers"),this.red.iadd(this,H)},X.prototype.redSub=function(H){return Z(this.red,"redSub works only with red numbers"),this.red.sub(this,H)},X.prototype.redISub=function(H){return Z(this.red,"redISub works only with red numbers"),this.red.isub(this,H)},X.prototype.redShl=function(H){return Z(this.red,"redShl works only with red numbers"),this.red.shl(this,H)},X.prototype.redMul=function(H){return Z(this.red,"redMul works only with red numbers"),this.red._verify2(this,H),this.red.mul(this,H)},X.prototype.redIMul=function(H){return Z(this.red,"redMul works only with red numbers"),this.red._verify2(this,H),this.red.imul(this,H)},X.prototype.redSqr=function(){return Z(this.red,"redSqr works only with red numbers"),this.red._verify1(this),this.red.sqr(this)},X.prototype.redISqr=function(){return Z(this.red,"redISqr works only with red numbers"),this.red._verify1(this),this.red.isqr(this)},X.prototype.redSqrt=function(){return Z(this.red,"redSqrt works only with red numbers"),this.red._verify1(this),this.red.sqrt(this)},X.prototype.redInvm=function(){return Z(this.red,"redInvm works only with red numbers"),this.red._verify1(this),this.red.invm(this)},X.prototype.redNeg=function(){return Z(this.red,"redNeg works only with red numbers"),this.red._verify1(this),this.red.neg(this)},X.prototype.redPow=function(H){return Z(this.red&&!H.red,"redPow(normalNum)"),this.red._verify1(this),this.red.pow(this,H)};var E={k256:null,p224:null,p192:null,p25519:null};function N(j,H){this.name=j,this.p=new X(H,16),this.n=this.p.bitLength(),this.k=new X(1).iushln(this.n).isub(this.p),this.tmp=this._tmp()}N.prototype._tmp=function(){var H=new X(null);return H.words=Array(Math.ceil(this.n/13)),H},N.prototype.ireduce=function(H){var z=H,M;do this.split(z,this.tmp),z=this.imulK(z),z=z.iadd(this.tmp),M=z.bitLength();while(M>this.n);var _=M<this.n?-1:z.ucmp(this.p);if(_===0)z.words[0]=0,z.length=1;else if(_>0)z.isub(this.p);else if(z.strip!==void 0)z.strip();else z._strip();return z},N.prototype.split=function(H,z){H.iushrn(this.n,0,z)},N.prototype.imulK=function(H){return H.imul(this.k)};function h(){N.call(this,"k256","ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff fffffffe fffffc2f")}G(h,N),h.prototype.split=function(H,z){var M=4194303,_=Math.min(H.length,9);for(var I=0;I<_;I++)z.words[I]=H.words[I];if(z.length=_,H.length<=9){H.words[0]=0,H.length=1;return}var P=H.words[9];z.words[z.length++]=P&M;for(I=10;I<H.length;I++){var S=H.words[I]|0;H.words[I-10]=(S&M)<<4|P>>>22,P=S}if(P>>>=22,H.words[I-10]=P,P===0&&H.length>10)H.length-=10;else H.length-=9},h.prototype.imulK=function(H){H.words[H.length]=0,H.words[H.length+1]=0,H.length+=2;var z=0;for(var M=0;M<H.length;M++){var _=H.words[M]|0;z+=_*977,H.words[M]=z&67108863,z=_*64+(z/67108864|0)}if(H.words[H.length-1]===0){if(H.length--,H.words[H.length-1]===0)H.length--}return H};function v(){N.call(this,"p224","ffffffff ffffffff ffffffff ffffffff 00000000 00000000 00000001")}G(v,N);function p(){N.call(this,"p192","ffffffff ffffffff ffffffff fffffffe ffffffff ffffffff")}G(p,N);function i(){N.call(this,"25519","7fffffffffffffff ffffffffffffffff ffffffffffffffff ffffffffffffffed")}G(i,N),i.prototype.imulK=function(H){var z=0;for(var M=0;M<H.length;M++){var _=(H.words[M]|0)*19+z,I=_&67108863;_>>>=26,H.words[M]=I,z=_}if(z!==0)H.words[H.length++]=z;return H},X._prime=function(H){if(E[H])return E[H];var z;if(H==="k256")z=new h;else if(H==="p224")z=new v;else if(H==="p192")z=new p;else if(H==="p25519")z=new i;else throw Error("Unknown prime "+H);return E[H]=z,z};function l(j){if(typeof j==="string"){var H=X._prime(j);this.m=H.p,this.prime=H}else Z(j.gtn(1),"modulus must be greater than 1"),this.m=j,this.prime=null}l.prototype._verify1=function(H){Z(H.negative===0,"red works only with positives"),Z(H.red,"red works only with red numbers")},l.prototype._verify2=function(H,z){Z((H.negative|z.negative)===0,"red works only with positives"),Z(H.red&&H.red===z.red,"red works only with red numbers")},l.prototype.imod=function(H){if(this.prime)return this.prime.ireduce(H)._forceRed(this);return H.umod(this.m)._forceRed(this)},l.prototype.neg=function(H){if(H.isZero())return H.clone();return this.m.sub(H)._forceRed(this)},l.prototype.add=function(H,z){this._verify2(H,z);var M=H.add(z);if(M.cmp(this.m)>=0)M.isub(this.m);return M._forceRed(this)},l.prototype.iadd=function(H,z){this._verify2(H,z);var M=H.iadd(z);if(M.cmp(this.m)>=0)M.isub(this.m);return M},l.prototype.sub=function(H,z){this._verify2(H,z);var M=H.sub(z);if(M.cmpn(0)<0)M.iadd(this.m);return M._forceRed(this)},l.prototype.isub=function(H,z){this._verify2(H,z);var M=H.isub(z);if(M.cmpn(0)<0)M.iadd(this.m);return M},l.prototype.shl=function(H,z){return this._verify1(H),this.imod(H.ushln(z))},l.prototype.imul=function(H,z){return this._verify2(H,z),this.imod(H.imul(z))},l.prototype.mul=function(H,z){return this._verify2(H,z),this.imod(H.mul(z))},l.prototype.isqr=function(H){return this.imul(H,H.clone())},l.prototype.sqr=function(H){return this.mul(H,H)},l.prototype.sqrt=function(H){if(H.isZero())return H.clone();var z=this.m.andln(3);if(Z(z%2===1),z===3){var M=this.m.add(new X(1)).iushrn(2);return this.pow(H,M)}var _=this.m.subn(1),I=0;while(!_.isZero()&&_.andln(1)===0)I++,_.iushrn(1);Z(!_.isZero());var P=new X(1).toRed(this),S=P.redNeg(),F=this.m.subn(1).iushrn(1),U=this.m.bitLength();U=new X(2*U*U).toRed(this);while(this.pow(U,F).cmp(S)!==0)U.redIAdd(S);var R=this.pow(U,_),k=this.pow(H,_.addn(1).iushrn(1)),y=this.pow(H,_),x=I;while(y.cmp(P)!==0){var u=y;for(var r=0;u.cmp(P)!==0;r++)u=u.redSqr();Z(r<x);var e=this.pow(R,new X(1).iushln(x-r-1));k=k.redMul(e),R=e.redSqr(),y=y.redMul(R),x=r}return k},l.prototype.invm=function(H){var z=H._invmp(this.m);if(z.negative!==0)return z.negative=0,this.imod(z).redNeg();else return this.imod(z)},l.prototype.pow=function(H,z){if(z.isZero())return new X(1).toRed(this);if(z.cmpn(1)===0)return H.clone();var M=4,_=Array(1<<M);_[0]=new X(1).toRed(this),_[1]=H;for(var I=2;I<_.length;I++)_[I]=this.mul(_[I-1],H);var P=_[0],S=0,F=0,U=z.bitLength()%26;if(U===0)U=26;for(I=z.length-1;I>=0;I--){var R=z.words[I];for(var k=U-1;k>=0;k--){var y=R>>k&1;if(P!==_[0])P=this.sqr(P);if(y===0&&S===0){F=0;continue}if(S<<=1,S|=y,F++,F!==M&&(I!==0||k!==0))continue;P=this.mul(P,_[S]),F=0,S=0}U=26}return P},l.prototype.convertTo=function(H){var z=H.umod(this.m);return z===H?z.clone():z},l.prototype.convertFrom=function(H){var z=H.clone();return z.red=null,z},X.mont=function(H){return new u0(H)};function u0(j){if(l.call(this,j),this.shift=this.m.bitLength(),this.shift%26!==0)this.shift+=26-this.shift%26;this.r=new X(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)}G(u0,l),u0.prototype.convertTo=function(H){return this.imod(H.ushln(this.shift))},u0.prototype.convertFrom=function(H){var z=this.imod(H.mul(this.rinv));return z.red=null,z},u0.prototype.imul=function(H,z){if(H.isZero()||z.isZero())return H.words[0]=0,H.length=1,H;var M=H.imul(z),_=M.maskn(this.shift).mul(this.minv).imaskn(this.shift).mul(this.m),I=M.isub(_).iushrn(this.shift),P=I;if(I.cmp(this.m)>=0)P=I.isub(this.m);else if(I.cmpn(0)<0)P=I.iadd(this.m);return P._forceRed(this)},u0.prototype.mul=function(H,z){if(H.isZero()||z.isZero())return new X(0)._forceRed(this);var M=H.mul(z),_=M.maskn(this.shift).mul(this.minv).imaskn(this.shift).mul(this.m),I=M.isub(_).iushrn(this.shift),P=I;if(I.cmp(this.m)>=0)P=I.isub(this.m);else if(I.cmpn(0)<0)P=I.iadd(this.m);return P._forceRed(this)},u0.prototype.invm=function(H){var z=this.imod(H._invmp(this.m).mul(this.r2));return z._forceRed(this)}})(typeof zG>"u"||zG,t1)});var a1=o((E7,OG)=>{if(typeof Object.create==="function")OG.exports=function(J,Z){if(Z)J.super_=Z,J.prototype=Object.create(Z.prototype,{constructor:{value:J,enumerable:!1,writable:!0,configurable:!0}})};else OG.exports=function(J,Z){if(Z){J.super_=Z;var G=function(){};G.prototype=Z.prototype,J.prototype=new G,J.prototype.constructor=J}}});var L$=o((T7,MG)=>{try{if(bJ=A$("util"),typeof bJ.inherits!=="function")throw"";MG.exports=bJ.inherits}catch($){MG.exports=a1()}var bJ});var pJ=o((N7,e1)=>{var cJ=A$("buffer"),m$=cJ.Buffer,t0={},a0;for(a0 in cJ){if(!cJ.hasOwnProperty(a0))continue;if(a0==="SlowBuffer"||a0==="Buffer")continue;t0[a0]=cJ[a0]}var d$=t0.Buffer={};for(a0 in m$){if(!m$.hasOwnProperty(a0))continue;if(a0==="allocUnsafe"||a0==="allocUnsafeSlow")continue;d$[a0]=m$[a0]}t0.Buffer.prototype=m$.prototype;if(!d$.from||d$.from===Uint8Array.from)d$.from=function($,J,Z){if(typeof $==="number")throw TypeError('The "value" argument must not be of type number. Received type '+typeof $);if($&&typeof $.length>"u")throw TypeError("The first argument must be one of type string, Buffer, ArrayBuffer, Array, or Array-like Object. Received type "+typeof $);return m$($,J,Z)};if(!d$.alloc)d$.alloc=function($,J,Z){if(typeof $!=="number")throw TypeError('The "size" argument must be of type number. Received type '+typeof $);if($<0||$>=2147483648)throw RangeError('The value "'+$+'" is invalid for option "size"');var G=m$($);if(!J||J.length===0)G.fill(0);else if(typeof Z==="string")G.fill(J,Z);else G.fill(J);return G};if(!t0.kStringMaxLength)try{t0.kStringMaxLength=process.binding("buffer").kStringMaxLength}catch($){}if(!t0.constants){if(t0.constants={MAX_LENGTH:t0.kMaxLength},t0.kStringMaxLength)t0.constants.MAX_STRING_LENGTH=t0.kStringMaxLength}e1.exports=t0});var uJ=o((S9)=>{var L9=L$();function e0($){this._reporterState={obj:null,path:[],options:$||{},errors:[]}}S9.Reporter=e0;e0.prototype.isError=function(J){return J instanceof s$};e0.prototype.save=function(){let J=this._reporterState;return{obj:J.obj,pathLen:J.path.length}};e0.prototype.restore=function(J){let Z=this._reporterState;Z.obj=J.obj,Z.path=Z.path.slice(0,J.pathLen)};e0.prototype.enterKey=function(J){return this._reporterState.path.push(J)};e0.prototype.exitKey=function(J){let Z=this._reporterState;Z.path=Z.path.slice(0,J-1)};e0.prototype.leaveKey=function(J,Z,G){let X=this._reporterState;if(this.exitKey(J),X.obj!==null)X.obj[Z]=G};e0.prototype.path=function(){return this._reporterState.path.join("/")};e0.prototype.enterObject=function(){let J=this._reporterState,Z=J.obj;return J.obj={},Z};e0.prototype.leaveObject=function(J){let Z=this._reporterState,G=Z.obj;return Z.obj=J,G};e0.prototype.error=function(J){let Z,G=this._reporterState,X=J instanceof s$;if(X)Z=J;else Z=new s$(G.path.map(function(Y){return"["+JSON.stringify(Y)+"]"}).join(""),J.message||J,J.stack);if(!G.options.partial)throw Z;if(!X)G.errors.push(Z);return Z};e0.prototype.wrapResult=function(J){let Z=this._reporterState;if(!Z.options.partial)return J;return{result:this.isError(J)?null:J,errors:Z.errors}};function s$($,J){this.path=$,this.rethrow(J)}L9(s$,Error);s$.prototype.rethrow=function(J){if(this.message=J+" at: "+(this.path||"(shallow)"),Error.captureStackTrace)Error.captureStackTrace(this,s$);if(!this.stack)try{throw Error(this.message)}catch(Z){this.stack=Z.stack}return this}});var r$=o((E9)=>{var w9=L$(),nJ=uJ().Reporter,o$=pJ().Buffer;function $$($,J){if(nJ.call(this,J),!o$.isBuffer($)){this.error("Input not Buffer");return}this.base=$,this.offset=0,this.length=$.length}w9($$,nJ);E9.DecoderBuffer=$$;$$.isDecoderBuffer=function(J){if(J instanceof $$)return!0;return typeof J==="object"&&o$.isBuffer(J.base)&&J.constructor.name==="DecoderBuffer"&&typeof J.offset==="number"&&typeof J.length==="number"&&typeof J.save==="function"&&typeof J.restore==="function"&&typeof J.isEmpty==="function"&&typeof J.readUInt8==="function"&&typeof J.skip==="function"&&typeof J.raw==="function"};$$.prototype.save=function(){return{offset:this.offset,reporter:nJ.prototype.save.call(this)}};$$.prototype.restore=function(J){let Z=new $$(this.base);return Z.offset=J.offset,Z.length=this.offset,this.offset=J.offset,nJ.prototype.restore.call(this,J.reporter),Z};$$.prototype.isEmpty=function(){return this.offset===this.length};$$.prototype.readUInt8=function(J){if(this.offset+1<=this.length)return this.base.readUInt8(this.offset++,!0);else return this.error(J||"DecoderBuffer overrun")};$$.prototype.skip=function(J,Z){if(!(this.offset+J<=this.length))return this.error(Z||"DecoderBuffer overrun");let G=new $$(this.base);return G._reporterState=this._reporterState,G.offset=this.offset,G.length=this.offset+J,this.offset+=J,G};$$.prototype.raw=function(J){return this.base.slice(J?J.offset:this.offset,this.length)};function l$($,J){if(Array.isArray($))this.length=0,this.value=$.map(function(Z){if(!l$.isEncoderBuffer(Z))Z=new l$(Z,J);return this.length+=Z.length,Z},this);else if(typeof $==="number"){if(!(0<=$&&$<=255))return J.error("non-byte EncoderBuffer value");this.value=$,this.length=1}else if(typeof $==="string")this.value=$,this.length=o$.byteLength($);else if(o$.isBuffer($))this.value=$,this.length=$.length;else return J.error("Unsupported type: "+typeof $)}E9.EncoderBuffer=l$;l$.isEncoderBuffer=function(J){if(J instanceof l$)return!0;return typeof J==="object"&&J.constructor.name==="EncoderBuffer"&&typeof J.length==="number"&&typeof J.join==="function"};l$.prototype.join=function(J,Z){if(!J)J=o$.alloc(this.length);if(!Z)Z=0;if(this.length===0)return J;if(Array.isArray(this.value))this.value.forEach(function(G){G.join(J,Z),Z+=G.length});else{if(typeof this.value==="number")J[Z]=this.value;else if(typeof this.value==="string")J.write(this.value,Z);else if(o$.isBuffer(this.value))this.value.copy(J,Z);Z+=this.length}return J}});var ZY=o((k7,JY)=>{JY.exports=$Y;function $Y($,J){if(!$)throw Error(J||"Assertion failed")}$Y.equal=function(J,Z,G){if(J!=Z)throw Error(G||"Assertion failed: "+J+" != "+Z)}});var mJ=o((y7,XY)=>{var v9=uJ().Reporter,D9=r$().EncoderBuffer,k9=r$().DecoderBuffer,o0=ZY(),GY=["seq","seqof","set","setof","objid","bool","gentime","utctime","null_","enum","int","objDesc","bitstr","bmpstr","charstr","genstr","graphstr","ia5str","iso646str","numstr","octstr","printstr","t61str","unistr","utf8str","videostr"],y9=["key","obj","use","optional","explicit","implicit","def","choice","any","contains"].concat(GY),x9=["_peekTag","_decodeTag","_use","_decodeStr","_decodeObjid","_decodeTime","_decodeNull","_decodeInt","_decodeBool","_decodeList","_encodeComposite","_encodeStr","_encodeObjid","_encodeTime","_encodeNull","_encodeInt","_encodeBool"];function t($,J,Z){let G={};if(this._baseState=G,G.name=Z,G.enc=$,G.parent=J||null,G.children=null,G.tag=null,G.args=null,G.reverseArgs=null,G.choice=null,G.optional=!1,G.any=!1,G.obj=!1,G.use=null,G.useDecoder=null,G.key=null,G.default=null,G.explicit=null,G.implicit=null,G.contains=null,!G.parent)G.children=[],this._wrap()}XY.exports=t;var f9=["enc","parent","children","tag","args","reverseArgs","choice","optional","any","obj","use","alteredUse","key","default","explicit","implicit","contains"];t.prototype.clone=function(){let J=this._baseState,Z={};f9.forEach(function(X){Z[X]=J[X]});let G=new this.constructor(Z.parent);return G._baseState=Z,G};t.prototype._wrap=function(){let J=this._baseState;y9.forEach(function(Z){this[Z]=function(){let X=new this.constructor(this);return J.children.push(X),X[Z].apply(X,arguments)}},this)};t.prototype._init=function(J){let Z=this._baseState;o0(Z.parent===null),J.call(this),Z.children=Z.children.filter(function(G){return G._baseState.parent===this},this),o0.equal(Z.children.length,1,"Root node can have only one child")};t.prototype._useArgs=function(J){let Z=this._baseState,G=J.filter(function(X){return X instanceof this.constructor},this);if(J=J.filter(function(X){return!(X instanceof this.constructor)},this),G.length!==0)o0(Z.children===null),Z.children=G,G.forEach(function(X){X._baseState.parent=this},this);if(J.length!==0)o0(Z.args===null),Z.args=J,Z.reverseArgs=J.map(function(X){if(typeof X!=="object"||X.constructor!==Object)return X;let Y={};return Object.keys(X).forEach(function(W){if(W==(W|0))W|=0;let Q=X[W];Y[Q]=W}),Y})};x9.forEach(function($){t.prototype[$]=function(){let Z=this._baseState;throw Error($+" not implemented for encoding: "+Z.enc)}});GY.forEach(function($){t.prototype[$]=function(){let Z=this._baseState,G=Array.prototype.slice.call(arguments);return o0(Z.tag===null),Z.tag=$,this._useArgs(G),this}});t.prototype.use=function(J){o0(J);let Z=this._baseState;return o0(Z.use===null),Z.use=J,this};t.prototype.optional=function(){let J=this._baseState;return J.optional=!0,this};t.prototype.def=function(J){let Z=this._baseState;return o0(Z.default===null),Z.default=J,Z.optional=!0,this};t.prototype.explicit=function(J){let Z=this._baseState;return o0(Z.explicit===null&&Z.implicit===null),Z.explicit=J,this};t.prototype.implicit=function(J){let Z=this._baseState;return o0(Z.explicit===null&&Z.implicit===null),Z.implicit=J,this};t.prototype.obj=function(){let J=this._baseState,Z=Array.prototype.slice.call(arguments);if(J.obj=!0,Z.length!==0)this._useArgs(Z);return this};t.prototype.key=function(J){let Z=this._baseState;return o0(Z.key===null),Z.key=J,this};t.prototype.any=function(){let J=this._baseState;return J.any=!0,this};t.prototype.choice=function(J){let Z=this._baseState;return o0(Z.choice===null),Z.choice=J,this._useArgs(Object.keys(J).map(function(G){return J[G]})),this};t.prototype.contains=function(J){let Z=this._baseState;return o0(Z.use===null),Z.contains=J,this};t.prototype._decode=function(J,Z){let G=this._baseState;if(G.parent===null)return J.wrapResult(G.children[0]._decode(J,Z));let X=G.default,Y=!0,W=null;if(G.key!==null)W=J.enterKey(G.key);if(G.optional){let V=null;if(G.explicit!==null)V=G.explicit;else if(G.implicit!==null)V=G.implicit;else if(G.tag!==null)V=G.tag;if(V===null&&!G.any){let O=J.save();try{if(G.choice===null)this._decodeGeneric(G.tag,J,Z);else this._decodeChoice(J,Z);Y=!0}catch(K){Y=!1}J.restore(O)}else if(Y=this._peekTag(J,V,G.any),J.isError(Y))return Y}let Q;if(G.obj&&Y)Q=J.enterObject();if(Y){if(G.explicit!==null){let O=this._decodeTag(J,G.explicit);if(J.isError(O))return O;J=O}let V=J.offset;if(G.use===null&&G.choice===null){let O;if(G.any)O=J.save();let K=this._decodeTag(J,G.implicit!==null?G.implicit:G.tag,G.any);if(J.isError(K))return K;if(G.any)X=J.raw(O);else J=K}if(Z&&Z.track&&G.tag!==null)Z.track(J.path(),V,J.length,"tagged");if(Z&&Z.track&&G.tag!==null)Z.track(J.path(),J.offset,J.length,"content");if(G.any);else if(G.choice===null)X=this._decodeGeneric(G.tag,J,Z);else X=this._decodeChoice(J,Z);if(J.isError(X))return X;if(!G.any&&G.choice===null&&G.children!==null)G.children.forEach(function(K){K._decode(J,Z)});if(G.contains&&(G.tag==="octstr"||G.tag==="bitstr")){let O=new k9(X);X=this._getUse(G.contains,J._reporterState.obj)._decode(O,Z)}}if(G.obj&&Y)X=J.leaveObject(Q);if(G.key!==null&&(X!==null||Y===!0))J.leaveKey(W,G.key,X);else if(W!==null)J.exitKey(W);return X};t.prototype._decodeGeneric=function(J,Z,G){let X=this._baseState;if(J==="seq"||J==="set")return null;if(J==="seqof"||J==="setof")return this._decodeList(Z,J,X.args[0],G);else if(/str$/.test(J))return this._decodeStr(Z,J,G);else if(J==="objid"&&X.args)return this._decodeObjid(Z,X.args[0],X.args[1],G);else if(J==="objid")return this._decodeObjid(Z,null,null,G);else if(J==="gentime"||J==="utctime")return this._decodeTime(Z,J,G);else if(J==="null_")return this._decodeNull(Z,G);else if(J==="bool")return this._decodeBool(Z,G);else if(J==="objDesc")return this._decodeStr(Z,J,G);else if(J==="int"||J==="enum")return this._decodeInt(Z,X.args&&X.args[0],G);if(X.use!==null)return this._getUse(X.use,Z._reporterState.obj)._decode(Z,G);else return Z.error("unknown tag: "+J)};t.prototype._getUse=function(J,Z){let G=this._baseState;if(G.useDecoder=this._use(J,Z),o0(G.useDecoder._baseState.parent===null),G.useDecoder=G.useDecoder._baseState.children[0],G.implicit!==G.useDecoder._baseState.implicit)G.useDecoder=G.useDecoder.clone(),G.useDecoder._baseState.implicit=G.implicit;return G.useDecoder};t.prototype._decodeChoice=function(J,Z){let G=this._baseState,X=null,Y=!1;if(Object.keys(G.choice).some(function(W){let Q=J.save(),V=G.choice[W];try{let O=V._decode(J,Z);if(J.isError(O))return!1;X={type:W,value:O},Y=!0}catch(O){return J.restore(Q),!1}return!0},this),!Y)return J.error("Choice not matched");return X};t.prototype._createEncoderBuffer=function(J){return new D9(J,this.reporter)};t.prototype._encode=function(J,Z,G){let X=this._baseState;if(X.default!==null&&X.default===J)return;let Y=this._encodeValue(J,Z,G);if(Y===void 0)return;if(this._skipDefault(Y,Z,G))return;return Y};t.prototype._encodeValue=function(J,Z,G){let X=this._baseState;if(X.parent===null)return X.children[0]._encode(J,Z||new v9);let Y=null;if(this.reporter=Z,X.optional&&J===void 0)if(X.default!==null)J=X.default;else return;let W=null,Q=!1;if(X.any)Y=this._createEncoderBuffer(J);else if(X.choice)Y=this._encodeChoice(J,Z);else if(X.contains)W=this._getUse(X.contains,G)._encode(J,Z),Q=!0;else if(X.children)W=X.children.map(function(V){if(V._baseState.tag==="null_")return V._encode(null,Z,J);if(V._baseState.key===null)return Z.error("Child should have a key");let O=Z.enterKey(V._baseState.key);if(typeof J!=="object")return Z.error("Child expected, but input is not object");let K=V._encode(J[V._baseState.key],Z,J);return Z.leaveKey(O),K},this).filter(function(V){return V}),W=this._createEncoderBuffer(W);else if(X.tag==="seqof"||X.tag==="setof"){if(!(X.args&&X.args.length===1))return Z.error("Too many args for : "+X.tag);if(!Array.isArray(J))return Z.error("seqof/setof, but data is not Array");let V=this.clone();V._baseState.implicit=null,W=this._createEncoderBuffer(J.map(function(O){let K=this._baseState;return this._getUse(K.args[0],J)._encode(O,Z)},V))}else if(X.use!==null)Y=this._getUse(X.use,G)._encode(J,Z);else W=this._encodePrimitive(X.tag,J),Q=!0;if(!X.any&&X.choice===null){let V=X.implicit!==null?X.implicit:X.tag,O=X.implicit===null?"universal":"context";if(V===null){if(X.use===null)Z.error("Tag could be omitted only for .use()")}else if(X.use===null)Y=this._encodeComposite(V,Q,O,W)}if(X.explicit!==null)Y=this._encodeComposite(X.explicit,!1,"context",Y);return Y};t.prototype._encodeChoice=function(J,Z){let G=this._baseState,X=G.choice[J.type];if(!X)o0(!1,J.type+" not found in "+JSON.stringify(Object.keys(G.choice)));return X._encode(J.value,Z)};t.prototype._encodePrimitive=function(J,Z){let G=this._baseState;if(/str$/.test(J))return this._encodeStr(Z,J);else if(J==="objid"&&G.args)return this._encodeObjid(Z,G.reverseArgs[0],G.args[1]);else if(J==="objid")return this._encodeObjid(Z,null,null);else if(J==="gentime"||J==="utctime")return this._encodeTime(Z,J);else if(J==="null_")return this._encodeNull();else if(J==="int"||J==="enum")return this._encodeInt(Z,G.args&&G.reverseArgs[0]);else if(J==="bool")return this._encodeBool(Z);else if(J==="objDesc")return this._encodeStr(Z,J);else throw Error("Unsupported tag: "+J)};t.prototype._isNumstr=function(J){return/^[0-9 ]*$/.test(J)};t.prototype._isPrintstr=function(J){return/^[A-Za-z0-9 '()+,-./:=?]*$/.test(J)}});var dJ=o((g9)=>{function YY($){let J={};return Object.keys($).forEach(function(Z){if((Z|0)==Z)Z=Z|0;let G=$[Z];J[G]=Z}),J}g9.tagClass={0:"universal",1:"application",2:"context",3:"private"};g9.tagClassByName=YY(g9.tagClass);g9.tag={0:"end",1:"bool",2:"int",3:"bitstr",4:"octstr",5:"null_",6:"objid",7:"objDesc",8:"external",9:"real",10:"enum",11:"embed",12:"utf8str",13:"relativeOid",16:"seq",17:"set",18:"numstr",19:"printstr",20:"t61str",21:"videostr",22:"ia5str",23:"utctime",24:"gentime",25:"graphstr",26:"iso646str",27:"genstr",28:"unistr",29:"charstr",30:"bmpstr"};g9.tagByName=YY(g9.tag)});var _G=o((f7,zY)=>{var c9=L$(),M$=pJ().Buffer,QY=mJ(),KG=dJ();function UY($){this.enc="der",this.name=$.name,this.entity=$,this.tree=new Z$,this.tree._init($.body)}zY.exports=UY;UY.prototype.encode=function(J,Z){return this.tree._encode(J,Z).join()};function Z$($){QY.call(this,"der",$)}c9(Z$,QY);Z$.prototype._encodeComposite=function(J,Z,G,X){let Y=p9(J,Z,G,this.reporter);if(X.length<128){let V=M$.alloc(2);return V[0]=Y,V[1]=X.length,this._createEncoderBuffer([V,X])}let W=1;for(let V=X.length;V>=256;V>>=8)W++;let Q=M$.alloc(2+W);Q[0]=Y,Q[1]=128|W;for(let V=1+W,O=X.length;O>0;V--,O>>=8)Q[V]=O&255;return this._createEncoderBuffer([Q,X])};Z$.prototype._encodeStr=function(J,Z){if(Z==="bitstr")return this._createEncoderBuffer([J.unused|0,J.data]);else if(Z==="bmpstr"){let G=M$.alloc(J.length*2);for(let X=0;X<J.length;X++)G.writeUInt16BE(J.charCodeAt(X),X*2);return this._createEncoderBuffer(G)}else if(Z==="numstr"){if(!this._isNumstr(J))return this.reporter.error("Encoding of string type: numstr supports only digits and space");return this._createEncoderBuffer(J)}else if(Z==="printstr"){if(!this._isPrintstr(J))return this.reporter.error("Encoding of string type: printstr supports only latin upper and lower case letters, digits, space, apostrophe, left and rigth parenthesis, plus sign, comma, hyphen, dot, slash, colon, equal sign, question mark");return this._createEncoderBuffer(J)}else if(/str$/.test(Z))return this._createEncoderBuffer(J);else if(Z==="objDesc")return this._createEncoderBuffer(J);else return this.reporter.error("Encoding of string type: "+Z+" unsupported")};Z$.prototype._encodeObjid=function(J,Z,G){if(typeof J==="string"){if(!Z)return this.reporter.error("string objid given, but no values map found");if(!Z.hasOwnProperty(J))return this.reporter.error("objid not found in values map");J=Z[J].split(/[\s.]+/g);for(let Q=0;Q<J.length;Q++)J[Q]|=0}else if(Array.isArray(J)){J=J.slice();for(let Q=0;Q<J.length;Q++)J[Q]|=0}if(!Array.isArray(J))return this.reporter.error("objid() should be either array or string, got: "+JSON.stringify(J));if(!G){if(J[1]>=40)return this.reporter.error("Second objid identifier OOB");J.splice(0,2,J[0]*40+J[1])}let X=0;for(let Q=0;Q<J.length;Q++){let V=J[Q];for(X++;V>=128;V>>=7)X++}let Y=M$.alloc(X),W=Y.length-1;for(let Q=J.length-1;Q>=0;Q--){let V=J[Q];Y[W--]=V&127;while((V>>=7)>0)Y[W--]=128|V&127}return this._createEncoderBuffer(Y)};function J$($){if($<10)return"0"+$;else return $}Z$.prototype._encodeTime=function(J,Z){let G,X=new Date(J);if(Z==="gentime")G=[J$(X.getUTCFullYear()),J$(X.getUTCMonth()+1),J$(X.getUTCDate()),J$(X.getUTCHours()),J$(X.getUTCMinutes()),J$(X.getUTCSeconds()),"Z"].join("");else if(Z==="utctime")G=[J$(X.getUTCFullYear()%100),J$(X.getUTCMonth()+1),J$(X.getUTCDate()),J$(X.getUTCHours()),J$(X.getUTCMinutes()),J$(X.getUTCSeconds()),"Z"].join("");else this.reporter.error("Encoding "+Z+" time is not supported yet");return this._encodeStr(G,"octstr")};Z$.prototype._encodeNull=function(){return this._createEncoderBuffer("")};Z$.prototype._encodeInt=function(J,Z){if(typeof J==="string"){if(!Z)return this.reporter.error("String int or enum given, but no values map");if(!Z.hasOwnProperty(J))return this.reporter.error("Values map doesn't contain: "+JSON.stringify(J));J=Z[J]}if(typeof J!=="number"&&!M$.isBuffer(J)){let Y=J.toArray();if(!J.sign&&Y[0]&128)Y.unshift(0);J=M$.from(Y)}if(M$.isBuffer(J)){let Y=J.length;if(J.length===0)Y++;let W=M$.alloc(Y);if(J.copy(W),J.length===0)W[0]=0;return this._createEncoderBuffer(W)}if(J<128)return this._createEncoderBuffer(J);if(J<256)return this._createEncoderBuffer([0,J]);let G=1;for(let Y=J;Y>=256;Y>>=8)G++;let X=Array(G);for(let Y=X.length-1;Y>=0;Y--)X[Y]=J&255,J>>=8;if(X[0]&128)X.unshift(0);return this._createEncoderBuffer(M$.from(X))};Z$.prototype._encodeBool=function(J){return this._createEncoderBuffer(J?255:0)};Z$.prototype._use=function(J,Z){if(typeof J==="function")J=J(Z);return J._getEncoder("der").tree};Z$.prototype._skipDefault=function(J,Z,G){let X=this._baseState,Y;if(X.default===null)return!1;let W=J.join();if(X.defaultBuffer===void 0)X.defaultBuffer=this._encodeValue(X.default,Z,G).join();if(W.length!==X.defaultBuffer.length)return!1;for(Y=0;Y<W.length;Y++)if(W[Y]!==X.defaultBuffer[Y])return!1;return!0};function p9($,J,Z,G){let X;if($==="seqof")$="seq";else if($==="setof")$="set";if(KG.tagByName.hasOwnProperty($))X=KG.tagByName[$];else if(typeof $==="number"&&($|0)===$)X=$;else return G.error("Unknown tag: "+$);if(X>=31)return G.error("Multi-octet tag encoding unsupported");if(!J)X|=32;return X|=KG.tagClassByName[Z||"universal"]<<6,X}});var OY=o((g7,VY)=>{var u9=L$(),AG=_G();function FG($){AG.call(this,$),this.enc="pem"}u9(FG,AG);VY.exports=FG;FG.prototype.encode=function(J,Z){let X=AG.prototype.encode.call(this,J).toString("base64"),Y=["-----BEGIN "+Z.label+"-----"];for(let W=0;W<X.length;W+=64)Y.push(X.slice(W,W+64));return Y.push("-----END "+Z.label+"-----"),Y.join(`
|
|
6
|
+
`)}});var RG=o((KY)=>{var MY=KY;MY.der=_G();MY.pem=OY()});var jG=o((b7,jY)=>{var n9=L$(),m9=VG(),_Y=r$().DecoderBuffer,FY=mJ(),AY=dJ();function RY($){this.enc="der",this.name=$.name,this.entity=$,this.tree=new r0,this.tree._init($.body)}jY.exports=RY;RY.prototype.decode=function(J,Z){if(!_Y.isDecoderBuffer(J))J=new _Y(J,Z);return this.tree._decode(J,Z)};function r0($){FY.call(this,"der",$)}n9(r0,FY);r0.prototype._peekTag=function(J,Z,G){if(J.isEmpty())return!1;let X=J.save(),Y=IG(J,'Failed to peek tag: "'+Z+'"');if(J.isError(Y))return Y;return J.restore(X),Y.tag===Z||Y.tagStr===Z||Y.tagStr+"of"===Z||G};r0.prototype._decodeTag=function(J,Z,G){let X=IG(J,'Failed to decode tag of "'+Z+'"');if(J.isError(X))return X;let Y=IY(J,X.primitive,'Failed to get length of "'+Z+'"');if(J.isError(Y))return Y;if(!G&&X.tag!==Z&&X.tagStr!==Z&&X.tagStr+"of"!==Z)return J.error('Failed to match tag: "'+Z+'"');if(X.primitive||Y!==null)return J.skip(Y,'Failed to match body of: "'+Z+'"');let W=J.save(),Q=this._skipUntilEnd(J,'Failed to skip indefinite length body: "'+this.tag+'"');if(J.isError(Q))return Q;return Y=J.offset-W.offset,J.restore(W),J.skip(Y,'Failed to match body of: "'+Z+'"')};r0.prototype._skipUntilEnd=function(J,Z){for(;;){let G=IG(J,Z);if(J.isError(G))return G;let X=IY(J,G.primitive,Z);if(J.isError(X))return X;let Y;if(G.primitive||X!==null)Y=J.skip(X);else Y=this._skipUntilEnd(J,Z);if(J.isError(Y))return Y;if(G.tagStr==="end")break}};r0.prototype._decodeList=function(J,Z,G,X){let Y=[];while(!J.isEmpty()){let W=this._peekTag(J,"end");if(J.isError(W))return W;let Q=G.decode(J,"der",X);if(J.isError(Q)&&W)break;Y.push(Q)}return Y};r0.prototype._decodeStr=function(J,Z){if(Z==="bitstr"){let G=J.readUInt8();if(J.isError(G))return G;return{unused:G,data:J.raw()}}else if(Z==="bmpstr"){let G=J.raw();if(G.length%2===1)return J.error("Decoding of string type: bmpstr length mismatch");let X="";for(let Y=0;Y<G.length/2;Y++)X+=String.fromCharCode(G.readUInt16BE(Y*2));return X}else if(Z==="numstr"){let G=J.raw().toString("ascii");if(!this._isNumstr(G))return J.error("Decoding of string type: numstr unsupported characters");return G}else if(Z==="octstr")return J.raw();else if(Z==="objDesc")return J.raw();else if(Z==="printstr"){let G=J.raw().toString("ascii");if(!this._isPrintstr(G))return J.error("Decoding of string type: printstr unsupported characters");return G}else if(/str$/.test(Z))return J.raw().toString();else return J.error("Decoding of string type: "+Z+" unsupported")};r0.prototype._decodeObjid=function(J,Z,G){let X,Y=[],W=0,Q=0;while(!J.isEmpty())if(Q=J.readUInt8(),W<<=7,W|=Q&127,(Q&128)===0)Y.push(W),W=0;if(Q&128)Y.push(W);let V=Y[0]/40|0,O=Y[0]%40;if(G)X=Y;else X=[V,O].concat(Y.slice(1));if(Z){let K=Z[X.join(" ")];if(K===void 0)K=Z[X.join(".")];if(K!==void 0)X=K}return X};r0.prototype._decodeTime=function(J,Z){let G=J.raw().toString(),X,Y,W,Q,V,O;if(Z==="gentime")X=G.slice(0,4)|0,Y=G.slice(4,6)|0,W=G.slice(6,8)|0,Q=G.slice(8,10)|0,V=G.slice(10,12)|0,O=G.slice(12,14)|0;else if(Z==="utctime")if(X=G.slice(0,2)|0,Y=G.slice(2,4)|0,W=G.slice(4,6)|0,Q=G.slice(6,8)|0,V=G.slice(8,10)|0,O=G.slice(10,12)|0,X<70)X=2000+X;else X=1900+X;else return J.error("Decoding "+Z+" time is not supported yet");return Date.UTC(X,Y-1,W,Q,V,O,0)};r0.prototype._decodeNull=function(){return null};r0.prototype._decodeBool=function(J){let Z=J.readUInt8();if(J.isError(Z))return Z;else return Z!==0};r0.prototype._decodeInt=function(J,Z){let G=J.raw(),X=new m9(G);if(Z)X=Z[X.toString(10)]||X;return X};r0.prototype._use=function(J,Z){if(typeof J==="function")J=J(Z);return J._getDecoder("der").tree};function IG($,J){let Z=$.readUInt8(J);if($.isError(Z))return Z;let G=AY.tagClass[Z>>6],X=(Z&32)===0;if((Z&31)===31){let W=Z;Z=0;while((W&128)===128){if(W=$.readUInt8(J),$.isError(W))return W;Z<<=7,Z|=W&127}}else Z&=31;let Y=AY.tag[Z];return{cls:G,primitive:X,tag:Z,tagStr:Y}}function IY($,J,Z){let G=$.readUInt8(Z);if($.isError(G))return G;if(!J&&G===128)return null;if((G&128)===0)return G;let X=G&127;if(X>4)return $.error("length octect is too long");G=0;for(let Y=0;Y<X;Y++){G<<=8;let W=$.readUInt8(Z);if($.isError(W))return W;G|=W}return G}});var BY=o((c7,qY)=>{var d9=L$(),s9=pJ().Buffer,qG=jG();function BG($){qG.call(this,$),this.enc="pem"}d9(BG,qG);qY.exports=BG;BG.prototype.decode=function(J,Z){let G=J.toString().split(/[\r\n]+/g),X=Z.label.toUpperCase(),Y=/^-----(BEGIN|END) ([^-]+)-----$/,W=-1,Q=-1;for(let K=0;K<G.length;K++){let A=G[K].match(Y);if(A===null)continue;if(A[2]!==X)continue;if(W===-1){if(A[1]!=="BEGIN")break;W=K}else{if(A[1]!=="END")break;Q=K;break}}if(W===-1||Q===-1)throw Error("PEM section not found for: "+X);let V=G.slice(W+1,Q).join("");V.replace(/[^a-z0-9+/=]+/gi,"");let O=s9.from(V,"base64");return qG.prototype.decode.call(this,O,Z)}});var PG=o((LY)=>{var PY=LY;PY.der=jG();PY.pem=BY()});var CY=o((SY)=>{var o9=RG(),l9=PG(),r9=L$(),i9=SY;i9.define=function(J,Z){return new i$(J,Z)};function i$($,J){this.name=$,this.body=J,this.decoders={},this.encoders={}}i$.prototype._createNamed=function(J){let Z=this.name;function G(X){this._initNamed(X,Z)}return r9(G,J),G.prototype._initNamed=function(Y,W){J.call(this,Y,W)},new G(this)};i$.prototype._getDecoder=function(J){if(J=J||"der",!this.decoders.hasOwnProperty(J))this.decoders[J]=this._createNamed(l9[J]);return this.decoders[J]};i$.prototype.decode=function(J,Z,G){return this._getDecoder(Z).decode(J,G)};i$.prototype._getEncoder=function(J){if(J=J||"der",!this.encoders.hasOwnProperty(J))this.encoders[J]=this._createNamed(o9[J]);return this.encoders[J]};i$.prototype.encode=function(J,Z,G){return this._getEncoder(Z).encode(J,G)}});var EY=o((wY)=>{var sJ=wY;sJ.Reporter=uJ().Reporter;sJ.DecoderBuffer=r$().DecoderBuffer;sJ.EncoderBuffer=r$().EncoderBuffer;sJ.Node=mJ()});var vY=o((NY)=>{var TY=NY;TY._reverse=function(J){let Z={};return Object.keys(J).forEach(function(G){if((G|0)==G)G=G|0;let X=J[G];Z[X]=G}),Z};TY.der=dJ()});var kY=o((DY)=>{var t$=DY;t$.bignum=VG();t$.define=CY().define;t$.base=EY();t$.constants=vY();t$.decoders=PG();t$.encoders=RG()});var fY=o((LG,xY)=>{/*! safe-buffer. MIT License. Feross Aboukhadijeh <https://feross.org/opensource> */var oJ=A$("buffer"),z$=oJ.Buffer;function yY($,J){for(var Z in $)J[Z]=$[Z]}if(z$.from&&z$.alloc&&z$.allocUnsafe&&z$.allocUnsafeSlow)xY.exports=oJ;else yY(oJ,LG),LG.Buffer=D$;function D$($,J,Z){return z$($,J,Z)}D$.prototype=Object.create(z$.prototype);yY(z$,D$);D$.from=function($,J,Z){if(typeof $==="number")throw TypeError("Argument must not be a number");return z$($,J,Z)};D$.alloc=function($,J,Z){if(typeof $!=="number")throw TypeError("Argument must be a number");var G=z$($);if(J!==void 0)if(typeof Z==="string")G.fill(J,Z);else G.fill(J);else G.fill(0);return G};D$.allocUnsafe=function($){if(typeof $!=="number")throw TypeError("Argument must be a number");return z$($)};D$.allocUnsafeSlow=function($){if(typeof $!=="number")throw TypeError("Argument must be a number");return oJ.SlowBuffer($)}});var hY=o((s7,gY)=>{function SG($){var J=($/8|0)+($%8===0?0:1);return J}var t9={ES256:SG(256),ES384:SG(384),ES512:SG(521)};function a9($){var J=t9[$];if(J)return J;throw Error('Unknown algorithm "'+$+'"')}gY.exports=a9});var dY=o((o7,mY)=>{var lJ=fY().Buffer,cY=hY(),rJ=128,pY=0,e9=32,$8=16,J8=2,uY=$8|e9|pY<<6,iJ=J8|pY<<6;function Z8($){return $.replace(/=/g,"").replace(/\+/g,"-").replace(/\//g,"_")}function nY($){if(lJ.isBuffer($))return $;else if(typeof $==="string")return lJ.from($,"base64");throw TypeError("ECDSA signature must be a Base64 string or a Buffer")}function G8($,J){$=nY($);var Z=cY(J),G=Z+1,X=$.length,Y=0;if($[Y++]!==uY)throw Error('Could not find expected "seq"');var W=$[Y++];if(W===(rJ|1))W=$[Y++];if(X-Y<W)throw Error('"seq" specified length of "'+W+'", only "'+(X-Y)+'" remaining');if($[Y++]!==iJ)throw Error('Could not find expected "int" for "r"');var Q=$[Y++];if(X-Y-2<Q)throw Error('"r" specified length of "'+Q+'", only "'+(X-Y-2)+'" available');if(G<Q)throw Error('"r" specified length of "'+Q+'", max of "'+G+'" is acceptable');var V=Y;if(Y+=Q,$[Y++]!==iJ)throw Error('Could not find expected "int" for "s"');var O=$[Y++];if(X-Y!==O)throw Error('"s" specified length of "'+O+'", expected "'+(X-Y)+'"');if(G<O)throw Error('"s" specified length of "'+O+'", max of "'+G+'" is acceptable');var K=Y;if(Y+=O,Y!==X)throw Error('Expected to consume entire buffer, but "'+(X-Y)+'" bytes remain');var A=Z-Q,B=Z-O,L=lJ.allocUnsafe(A+Q+B+O);for(Y=0;Y<A;++Y)L[Y]=0;$.copy(L,Y,V+Math.max(-A,0),V+Q),Y=Z;for(var C=Y;Y<C+B;++Y)L[Y]=0;return $.copy(L,Y,K+Math.max(-B,0),K+O),L=L.toString("base64"),L=Z8(L),L}function bY($,J,Z){var G=0;while(J+G<Z&&$[J+G]===0)++G;var X=$[J+G]>=rJ;if(X)--G;return G}function X8($,J){$=nY($);var Z=cY(J),G=$.length;if(G!==Z*2)throw TypeError('"'+J+'" signatures must be "'+Z*2+'" bytes, saw "'+G+'"');var X=bY($,0,Z),Y=bY($,Z,$.length),W=Z-X,Q=Z-Y,V=2+W+1+1+Q,O=V<rJ,K=lJ.allocUnsafe((O?2:3)+V),A=0;if(K[A++]=uY,O)K[A++]=V;else K[A++]=rJ|1,K[A++]=V&255;if(K[A++]=iJ,K[A++]=W,X<0)K[A++]=0,A+=$.copy(K,A,0,Z);else A+=$.copy(K,A,X,Z);if(K[A++]=iJ,K[A++]=Q,Y<0)K[A++]=0,$.copy(K,A,Z);else $.copy(K,A,Z+Y);return K}mY.exports={derToJose:G8,joseToDer:X8}});var TG=o((l7,YW)=>{var EG=kY(),{createHmac:lY,createVerify:Y8,createSign:W8,timingSafeEqual:H8,createPublicKey:Q8,constants:{RSA_PKCS1_PSS_PADDING:rY,RSA_PSS_SALTLEN_DIGEST:iY,RSA_PKCS1_PADDING:tY,RSA_PSS_SALTLEN_MAX_SIGN:U8,RSA_PSS_SALTLEN_AUTO:z8},sign:sY,verify:oY}=A$("crypto"),{joseToDer:V8,derToJose:O8}=dY(),aY=UG(),{TokenError:J0}=n$(),eY=/[=+/]/g,M8={"=":"","+":"-","/":"_"},$W=/^-----BEGIN(?: (RSA|EC|ENCRYPTED))? PRIVATE KEY-----/,JW=/^-----BEGIN(?: (RSA))? PUBLIC KEY-----/,tJ=new aY(1000),CG=new aY(1000),ZW=["HS256","HS384","HS512"],K8=["ES256","ES384","ES512"],wG=["RS256","RS384","RS512","PS256","PS384","PS512"],_8=["EdDSA"],GW={"1.2.840.10045.3.1.7":{bits:"256",names:["P-256","prime256v1"]},"1.3.132.0.10":{bits:"256",names:["secp256k1"]},"1.3.132.0.34":{bits:"384",names:["P-384","secp384r1"]},"1.3.132.0.35":{bits:"512",names:["P-521","secp521r1"]}},A8=EG.define("PrivateKey",function(){this.seq().obj(this.key("version").int(),this.key("algorithm").seq().obj(this.key("algorithm").objid(),this.key("parameters").optional().objid()))}),F8=EG.define("PublicKey",function(){this.seq().obj(this.key("algorithm").seq().obj(this.key("algorithm").objid(),this.key("parameters").optional().objid()))}),R8=EG.define("ECPrivateKey",function(){this.seq().obj(this.key("version").int(),this.key("privateKey").octstr(),this.key("parameters").explicit(0).optional().choice({namedCurve:this.objid()}))});function XW($){return M8[$]}function VJ($,J,Z,G){return $.set(J,[Z,G]),Z||G}function I8($){if($.match(JW)||$.includes("-----BEGIN CERTIFICATE-----"))throw new J0(J0.codes.invalidKey,"Public keys are not supported for signing.");let J=$.trim().match($W);if(!J)return"HS256";let Z,G,X;switch(J[1]){case"RSA":return"RS256";case"EC":Z=R8.decode($,"pem",{label:"EC PRIVATE KEY"}),X=Z.parameters.value.join(".");break;case"ENCRYPTED":return"ENCRYPTED";default:switch(Z=A8.decode($,"pem",{label:"PRIVATE KEY"}),G=Z.algorithm.algorithm.join("."),G){case"1.2.840.113549.1.1.1":return"RS256";case"1.2.840.10045.2.1":X=Z.algorithm.parameters.join(".");break;case"1.3.101.112":case"1.3.101.113":return"EdDSA";default:throw new J0(J0.codes.invalidKey,`Unsupported PEM PCKS8 private key with OID ${G}.`)}}let Y=GW[X];if(!Y)throw new J0(J0.codes.invalidKey,`Unsupported EC private key with curve ${X}.`);return`ES${Y.bits}`}function j8($){let J=$.match(JW);if($.match($W))throw new J0(J0.codes.invalidKey,"Private keys are not supported for verifying.");else if(J&&J[1]==="RSA")return wG;else if(!J&&!$.includes("-----BEGIN CERTIFICATE-----"))return ZW;if($.includes("-----BEGIN CERTIFICATE-----"))$=Q8($).export({type:"spki",format:"pem"});let Z=F8.decode($,"pem",{label:"PUBLIC KEY"}),G=Z.algorithm.algorithm.join("."),X;switch(G){case"1.2.840.113549.1.1.1":return wG;case"1.2.840.10045.2.1":X=Z.algorithm.parameters.join(".");break;case"1.3.101.112":case"1.3.101.113":return["EdDSA"];default:throw new J0(J0.codes.invalidKey,`Unsupported PEM PCKS8 public key with OID ${G}.`)}let Y=GW[X];if(!Y)throw new J0(J0.codes.invalidKey,`Unsupported EC public key with curve ${X}.`);return[`ES${Y.bits}`]}function q8($,J){if($ instanceof Buffer)$=$.toString("utf-8");else if(typeof $!=="string")throw new J0(J0.codes.invalidKey,"The private key must be a string or a buffer.");let[Z,G]=tJ.get($)||[];if(Z)return Z;else if(G)throw G;try{let X=I8($);if(X==="ENCRYPTED")return VJ(tJ,$,J);return VJ(tJ,$,X)}catch(X){throw VJ(tJ,$,null,J0.wrap(X,J0.codes.invalidKey,"Unsupported PEM private key."))}}function B8($){if(!$)return"none";let[J,Z]=CG.get($)||[];if(J)return J;else if(Z)throw Z;try{if($ instanceof Buffer)$=$.toString("utf-8");else if(typeof $!=="string")throw new J0(J0.codes.invalidKey,"The public key must be a string or a buffer.");return VJ(CG,$,j8($))}catch(G){throw VJ(CG,$,null,J0.wrap(G,J0.codes.invalidKey,"Unsupported PEM public key."))}}function P8($,J,Z){try{let G=$.slice(0,2),X=`sha${$.slice(2)}`,Y,W;switch(G){case"HS":Y=lY(X,J).update(Z).digest("base64");break;case"ES":Y=O8(sY(X,Buffer.from(Z,"utf-8"),J),$).toString("base64");break;case"RS":case"PS":if(W={key:J,padding:tY,saltLength:U8},G==="PS")W.padding=rY,W.saltLength=iY;Y=W8(X).update(Z).sign(W).toString("base64");break;case"Ed":Y=sY(void 0,Buffer.from(Z,"utf-8"),J).toString("base64")}return Y.replace(eY,XW)}catch(G){throw new J0(J0.codes.signError,"Cannot create the signature.",{originalError:G})}}function L8($,J,Z,G){try{let X=$.slice(0,2),Y=`SHA${$.slice(2)}`;if(G=Buffer.from(G,"base64"),X==="HS")try{return H8(lY(Y,J).update(Z).digest(),G)}catch{return!1}else if(X==="Ed")if(typeof oY==="function")return oY(void 0,Buffer.from(Z,"utf-8"),J,G);else throw new J0(J0.codes.signError,"EdDSA algorithms are not supported by your Node.js version.");let W={key:J,padding:tY,saltLength:z8};if(X==="PS")W.padding=rY,W.saltLength=iY;else if(X==="ES")G=V8(G,$);return Y8("RSA-"+Y).update(Z).verify(W,G)}catch(X){throw new J0(J0.codes.verifyError,"Cannot verify the signature.",{originalError:X})}}YW.exports={base64UrlMatcher:eY,base64UrlReplacer:XW,hsAlgorithms:ZW,rsaAlgorithms:wG,esAlgorithms:K8,edAlgorithms:_8,detectPrivateKeyAlgorithm:q8,detectPublicKeyAlgorithms:B8,createSignature:P8,verifySignature:L8}});var NG=o((r7,HW)=>{var{createHash:WW}=A$("crypto"),S8=/"alg"\s*:\s*"[HERP]S(256|384)"/m,C8=/"alg"\s*:\s*"EdDSA"/m,w8=/"crv"\s*:\s*"Ed448"/m;function E8($,J,Z){let G=$(J,Z);if(G&&typeof G.then==="function")G.then((X)=>{process.nextTick(()=>Z(null,X))}).catch(Z)}function T8($){if(typeof $==="function")return[$];let J,Z,G=new Promise((X,Y)=>{J=X,Z=Y});return[function(X,Y){if(X)return Z(X);return J(Y)},G]}function N8($){let J=$.split(".",1)[0],Z=Buffer.from(J,"base64").toString("utf-8"),G=null;if(Z.match(C8)&&Z.match(w8))G=WW("shake256",{outputLength:114});else{let X=Z.match(S8);G=WW(`sha${X?X[1]:"512"}`)}return G.update($).digest("hex")}HW.exports={getAsyncKey:E8,ensurePromiseCallback:T8,hashToken:N8}});var KW=o((i7,MW)=>{var{createPublicKey:v8,createSecretKey:D8}=A$("crypto"),k8=UG(),{hsAlgorithms:UW,verifySignature:y8,detectPublicKeyAlgorithms:zW}=TG(),x8=XG(),{TokenError:m}=n$(),{getAsyncKey:f8,ensurePromiseCallback:g8,hashToken:h8}=NG();function b8($,J){return $===J}function VW($,J){for(let Z of $)if(J.includes(Z))return;throw new m(m.codes.invalidKey,`Invalid public key provided for algorithms ${$.join(", ")}.`)}function OW($,J){if(typeof $==="string")$=Buffer.from($,"utf-8");return J?D8($):v8($)}function OJ($){if(!Array.isArray($))$=[$];return $.filter((J)=>J).map((J)=>{if(J&&typeof J.test==="function")return J;return{test:b8.bind(null,J)}})}function c8($){let J=parseInt($===!0?1000:$,10);return J>0?new k8(J):null}function a$({cache:$,token:J,cacheTTL:Z,payload:G,ignoreExpiration:X,ignoreNotBefore:Y,maxAge:W,clockTimestamp:Q=Date.now(),clockTolerance:V,errorCacheTTL:O,cacheKeyBuilder:K},A){if(!$)return A;let B=[A,0,0];if(A instanceof m){let T=typeof O==="function"?O(A):O;return B[2]=Q+V+T,$.set(K(J),B),A}if(G&&typeof G.iat==="number"){if(B[1]=!Y&&typeof G.nbf==="number"?G.nbf*1000-V:0,!X){if(typeof G.exp==="number")B[2]=G.exp*1000+V;else if(W)B[2]=G.iat*1000+W+V}}let C=Q+V+Z;return B[2]=B[2]===0?C:Math.min(B[2],C),$.set(K(J),B),A}function p8($,J,Z){if($ instanceof m){if(!J)throw $;J($)}else{if(!J)return $;J(null,$)}return Z}function u8($,J,Z,G,X){if(!X.includes(J.alg))throw new m(m.codes.invalidAlgorithm,"The token algorithm is invalid.");if(Z&&!y8(J.alg,G,$,Z))throw new m(m.codes.invalidSignature,"The token signature is invalid.")}function n8($,J,Z,G,X){let Y=Z?`The ${J} claim must be a ${X} or an array of ${X}s.`:`The ${J} claim must be a ${X}.`;if(G&&!Z)throw new m(m.codes.invalidClaimValue,Y);if($.map((W)=>typeof W).some((W)=>W!==X))throw new m(m.codes.invalidClaimType,Y)}function m8($,J,Z,G){let X=G?`None of ${J} claim values are allowed.`:`The ${J} claim value is not allowed.`;if(!$.some((Y)=>Z.some((W)=>W.test(Y))))throw new m(m.codes.invalidClaimValue,X)}function d8($,J,Z,G,X,Y){let W=$*1000+(J||0);if(!(G?Z>=W:Z<=W))throw new m(m.codes[X],`The token ${Y} at ${new Date(W).toISOString()}.`)}function QW($,{input:J,header:Z,payload:G,signature:X},{validators:Y,allowedAlgorithms:W,checkTyp:Q,clockTimestamp:V,requiredClaims:O}){let K=$ instanceof Buffer?$.length:!!$;if(K&&!X)throw new m(m.codes.missingSignature,"The token signature is missing.");else if(!K&&X)throw new m(m.codes.missingKey,"The key option is missing.");if(u8(J,Z,X,$,W),Q&&(typeof Z.typ!=="string"||Q!==Z.typ.toLowerCase().replace(/^application\//,"")))throw new m(m.codes.invalidType,"Invalid typ.");if(O){for(let B of O)if(!(B in G))throw new m(m.codes.missingRequiredClaim,`The ${B} claim is required.`)}let A=V||Date.now();for(let{type:B,claim:L,allowed:C,array:T,modifier:w,greater:D,errorCode:E,errorVerb:N}of Y){let h=G[L],v=Array.isArray(h),p=v?h:[h];if(!(L in G))continue;if(n8(p,L,T,v,B==="date"?"number":"string"),B==="date")d8(h,w,A,D,E,N);else m8(p,L,C,v)}}function s8({key:$,allowedAlgorithms:J,complete:Z,cacheTTL:G,checkTyp:X,clockTimestamp:Y,clockTolerance:W,ignoreExpiration:Q,ignoreNotBefore:V,maxAge:O,isAsync:K,validators:A,decode:B,cache:L,requiredClaims:C,errorCacheTTL:T,cacheKeyBuilder:w},D,E){let[N,h]=K?g8(E):[];if(L){let[z,M,_]=L.get(w(D))||[void 0,0,0],I=Y||Date.now();if(typeof z<"u"&&(M===0||I<M&&z.code==="FAST_JWT_INACTIVE"||I>=M&&z.code!=="FAST_JWT_INACTIVE")&&(_===0||I<=_))return p8(z,N,h)}let v;try{v=B(D)}catch(z){if(N)return N(z),h;throw z}let{header:p,payload:i,signature:l,input:u0}=v,j={cache:L,token:D,cacheTTL:G,errorCacheTTL:T,ignoreExpiration:Q,ignoreNotBefore:V,maxAge:O,clockTimestamp:Y,clockTolerance:W,payload:i,cacheKeyBuilder:w},H={validators:A,allowedAlgorithms:J,checkTyp:X,clockTimestamp:Y,clockTolerance:W,requiredClaims:C};if(!N)try{return QW($,v,H),a$(j,Z?{header:p,payload:i,signature:l,input:u0}:i)}catch(z){throw a$(j,z)}return f8($,{header:p,payload:i,signature:l},(z,M)=>{if(z)return N(a$(j,m.wrap(z,m.codes.keyFetchingError,"Cannot fetch key.")));if(typeof M==="string")M=Buffer.from(M,"utf-8");else if(!(M instanceof Buffer))return N(a$(j,new m(m.codes.keyFetchingError,"The key returned from the callback must be a string or a buffer containing a secret or a public key.")));try{let _=zW(M);if(H.allowedAlgorithms.length)VW(J,_);else H.allowedAlgorithms=_;M=OW(M,_[0]===UW[0]),QW(M,v,H)}catch(_){return N(a$(j,_))}N(null,a$(j,Z?{header:p,payload:i,signature:l,input:D}:i))}),h}MW.exports=function(J){let{key:Z,algorithms:G,complete:X,cache:Y,cacheTTL:W,errorCacheTTL:Q,checkTyp:V,clockTimestamp:O,clockTolerance:K,ignoreExpiration:A,ignoreNotBefore:B,maxAge:L,allowedJti:C,allowedAud:T,allowedIss:w,allowedSub:D,allowedNonce:E,requiredClaims:N,cacheKeyBuilder:h}={cacheTTL:600000,clockTolerance:0,errorCacheTTL:-1,cacheKeyBuilder:h8,...J};if(!Array.isArray(G))G=[];let v=typeof Z;if(v!=="string"&&v!=="object"&&v!=="function")throw new m(m.codes.INVALID_OPTION,"The key option must be a string, a buffer or a function returning the algorithm secret or public key.");if(Z&&v!=="function"){let j=zW(Z);if(G.length)VW(G,j);else G=j;Z=OW(Z,j[0]===UW[0])}if(O&&(typeof O!=="number"||O<0))throw new m(m.codes.invalidOption,"The clockTimestamp option must be a positive number.");if(K&&(typeof K!=="number"||K<0))throw new m(m.codes.invalidOption,"The clockTolerance option must be a positive number.");if(W&&(typeof W!=="number"||W<0))throw new m(m.codes.invalidOption,"The cacheTTL option must be a positive number.");if(Q&&typeof Q!=="function"&&typeof Q!=="number"||Q<-1)throw new m(m.codes.invalidOption,"The errorCacheTTL option must be a number greater than -1 or a function.");if(N&&!Array.isArray(N))throw new m(m.codes.invalidOption,"The requiredClaims option must be an array.");let p=[];if(!B)p.push({type:"date",claim:"nbf",errorCode:"inactive",errorVerb:"will be active",greater:!0,modifier:-K});if(!A)p.push({type:"date",claim:"exp",errorCode:"expired",errorVerb:"has expired",modifier:+K});if(typeof L==="number")p.push({type:"date",claim:"iat",errorCode:"expired",errorVerb:"has expired",modifier:L});if(C)p.push({type:"string",claim:"jti",allowed:OJ(C)});if(T)p.push({type:"string",claim:"aud",allowed:OJ(T),array:!0});if(w)p.push({type:"string",claim:"iss",allowed:OJ(w)});if(D)p.push({type:"string",claim:"sub",allowed:OJ(D)});if(E)p.push({type:"string",claim:"nonce",allowed:OJ(E)});let i=V?V.toLowerCase().replace(/^application\//,""):null,l={key:Z,allowedAlgorithms:G,complete:X,cacheTTL:W,errorCacheTTL:Q,checkTyp:i,clockTimestamp:O,clockTolerance:K,ignoreExpiration:A,ignoreNotBefore:B,maxAge:L,isAsync:v==="function",validators:p,decode:x8({complete:!0}),cache:c8(Y),requiredClaims:N,cacheKeyBuilder:h},u0=s8.bind(null,l);return u0.cache=l.cache,u0}});var _W=o((i8)=>{var o8=/^(-?(?:\d+)?\.?\d+) *(m(?:illiseconds?|s(?:ecs?)?))?(s(?:ec(?:onds?|s)?)?)?(m(?:in(?:utes?|s)?)?)?(h(?:ours?|rs?)?)?(d(?:ays?)?)?(w(?:eeks?|ks?)?)?(y(?:ears?|rs?)?)?$/,aJ=1000,eJ=aJ*60,$Z=eJ*60,KJ=$Z*24,vG=KJ*365.25;function l8($){var J,Z=$.toLowerCase().match(o8);if(Z!=null&&(J=parseFloat(Z[1]))){if(Z[3]!=null)return J*aJ;if(Z[4]!=null)return J*eJ;if(Z[5]!=null)return J*$Z;if(Z[6]!=null)return J*KJ;if(Z[7]!=null)return J*KJ*7;if(Z[8]!=null)return J*vG;return J}}function MJ($,J,Z,G){var X=($|0)===$?$:~~($+0.5);return J+X+(G?" "+Z+(X!=1?"s":""):Z[0])}function r8($,J){var Z=$<0?"-":"",G=$<0?-$:$;if(G<aJ)return $+(J?" ms":"ms");if(G<eJ)return MJ(G/aJ,Z,"second",J);if(G<$Z)return MJ(G/eJ,Z,"minute",J);if(G<KJ)return MJ(G/$Z,Z,"hour",J);if(G<vG)return MJ(G/KJ,Z,"day",J);return MJ(G/vG,Z,"year",J)}i8.format=r8;i8.parse=l8});var PW=o((a7,BW)=>{var{base64UrlMatcher:DG,base64UrlReplacer:kG,hsAlgorithms:e8,esAlgorithms:$6,rsaAlgorithms:J6,edAlgorithms:Z6,detectPrivateKeyAlgorithm:RW,createSignature:AW}=TG(),{TokenError:s}=n$(),{getAsyncKey:G6,ensurePromiseCallback:X6}=NG(),{createPrivateKey:Y6,createSecretKey:W6}=A$("crypto"),{parse:FW}=_W(),IW=new Set([...e8,...$6,...J6,...Z6,"none"]),H6=Array.from(IW).join(", ");function jW($,J){let Z=$.slice(0,2),G=J.slice(0,2),X=!0;if(Z==="RS"||Z==="PS")X=G==="RS"||Z==="RS"&&J==="ENCRYPTED";else if(Z==="ES"||Z==="Ed")X=Z===G||Z==="ES"&&J==="ENCRYPTED";if(!X)throw new s(s.codes.invalidKey,`Invalid private key provided for algorithm ${$}.`)}function qW($,J){if(typeof $==="string")$=Buffer.from($,"utf-8");return J[0]==="H"?W6($):Y6($)}function Q6({key:$,algorithm:J,noTimestamp:Z,mutatePayload:G,clockTimestamp:X,expiresIn:Y,notBefore:W,kid:Q,typ:V,isAsync:O,additionalHeader:K,fixedPayload:A},B,L){let[C,T]=O?X6(L):[];if(typeof B!=="object")throw new s(s.codes.invalidType,"The payload must be an object.");if(B.exp&&(!Number.isInteger(B.exp)||B.exp<0))throw new s(s.codes.invalidClaimValue,"The exp claim must be a positive integer.");let w={alg:J,typ:V||"JWT",kid:Q,...K},D="",E=B.iat*1000||X||Date.now(),N={...B,...A,iat:Z?void 0:Math.floor(E/1000),exp:B.exp?B.exp:Y?Math.floor((E+Y)/1000):void 0,nbf:B.nbf?B.nbf:W?Math.floor((E+W)/1000):void 0};if(G)Object.assign(B,N);if(D=Buffer.from(JSON.stringify(N),"utf-8").toString("base64").replace(DG,kG),!C){let v=Buffer.from(JSON.stringify(w),"utf-8").toString("base64").replace(DG,kG)+"."+D,p=J==="none"?"":AW(J,$,v);return v+"."+p}return G6($,{header:w,payload:B},(h,v)=>{if(h){let i=s.wrap(h,s.codes.keyFetchingError,"Cannot fetch key.");return C(i)}if(typeof v==="string")v=Buffer.from(v,"utf-8");else if(!(v instanceof Buffer))return C(new s(s.codes.keyFetchingError,"The key returned from the callback must be a string or a buffer containing a secret or a private key."));let p;try{let i=RW(v,J);if(J)jW(J,i);else w.alg=J=i;v=qW(v,J);let u0=Buffer.from(JSON.stringify(w),"utf-8").toString("base64").replace(DG,kG)+"."+D;p=u0+"."+AW(J,v,u0)}catch(i){return C(i)}C(null,p)}),T}BW.exports=function(J){let{key:Z,algorithm:G,noTimestamp:X,mutatePayload:Y,clockTimestamp:W,expiresIn:Q,notBefore:V,jti:O,aud:K,iss:A,sub:B,nonce:L,kid:C,typ:T,header:w}={clockTimestamp:0,...J};if(G&&!IW.has(G))throw new s(s.codes.invalidOption,`The algorithm option must be one of the following values: ${H6}.`);let D=typeof Z,E=D==="object"&&Z&&Z.key&&Z.passphrase;if(G==="none"){if(Z)throw new s(s.codes.invalidOption,'The key option must not be provided when the algorithm option is "none".')}else if(!Z||D!=="string"&&!(Z instanceof Buffer)&&D!=="function"&&!E)throw new s(s.codes.invalidOption,"The key option must be a string, a buffer, an object containing key/passphrase properties or a function returning the algorithm secret or private key.");else if(E&&!G)throw new s(s.codes.invalidAlgorithm,"When using password protected key you must provide the algorithm option.");if(Z&&D!=="function"){let v=RW(E?Z.key:Z,G);if(G)jW(G,v);else G=v;Z=qW(Z,G)}if(Q){if(typeof Q==="string")Q=FW(Q);if(typeof Q!=="number")throw new s(s.codes.invalidOption,"The expiresIn option must be a positive number or a valid string.")}if(V){if(typeof V==="string")V=FW(V);if(typeof V!=="number"||V<0)throw new s(s.codes.invalidOption,"The notBefore option must be a positive number or a valid string.")}if(W&&(typeof W!=="number"||W<0))throw new s(s.codes.invalidOption,"The clockTimestamp option must be a positive number.");if(O&&typeof O!=="string")throw new s(s.codes.invalidOption,"The jti option must be a string.");if(K&&typeof K!=="string"&&!Array.isArray(K))throw new s(s.codes.invalidOption,"The aud option must be a string or an array of strings.");if(A&&typeof A!=="string")throw new s(s.codes.invalidOption,"The iss option must be a string.");if(B&&typeof B!=="string")throw new s(s.codes.invalidOption,"The sub option must be a string.");if(L&&typeof L!=="string")throw new s(s.codes.invalidOption,"The nonce option must be a string.");if(C&&typeof C!=="string")throw new s(s.codes.invalidOption,"The kid option must be a string.");if(w&&typeof w!=="object")throw new s(s.codes.invalidOption,"The header option must be a object.");let h=Object.entries({jti:O,aud:K,iss:A,sub:B,nonce:L}).reduce((v,[p,i])=>{if(i!==void 0)v[p]=i;return v},{});return Q6.bind(null,{key:Z,algorithm:G,noTimestamp:X,mutatePayload:Y,clockTimestamp:W,expiresIn:Q,notBefore:V,kid:C,typ:T,isAsync:D==="function",additionalHeader:w,fixedPayload:h})}});var SW=o((e7,LW)=>{var{TokenError:U6,TOKEN_ERROR_CODES:z6}=n$(),V6=XG(),O6=KW(),M6=PW();LW.exports={TokenError:U6,TOKEN_ERROR_CODES:z6,createDecoder:V6,createVerifier:O6,createSigner:M6}});jJ();import{join as kZ}from"path";n0();function W$($){if(Array.isArray($)){let J=[];for(let Z of $)J.push(W$(Z));return J}if(n($)){let J={},Z=$;for(let G of Object.keys(Z))J[G]=W$(Z[G]);return J}return $}function _X($,J){if(J===void 0)return $;if(Array.isArray($)&&Array.isArray(J)){let Z=[];for(let G of $)Z.push(W$(G));for(let G of J)Z.push(W$(G));return Z}if(n($)&&n(J)){let Z=$,G=J,X={};for(let Y of Object.keys(Z))X[Y]=W$(Z[Y]);for(let Y of Object.keys(G)){let W=G[Y];if(W===void 0)continue;let Q=X[Y];if(Array.isArray(Q)&&Array.isArray(W)){let V=[];for(let O of Q)V.push(W$(O));for(let O of W)V.push(W$(O));X[Y]=V;continue}if(n(Q)&&n(W)){X[Y]=_X(W$(Q),W);continue}X[Y]=W$(W)}return X}return W$(J)}function AX(...$){let J={};for(let Z of $){if(Z===void 0)continue;J=_X(J,Z)}return J}var KH={nodeEnv:"development",appName:"\u91CE\u8702\u98DE\u821E",appPort:3000,appHost:"127.0.0.1",devEmail:"dev@qq.com",devPassword:"beflydev123456",bodyLimit:1048576,tz:"Asia/Shanghai",logger:{debug:1,excludeFields:["password","token","secret"],dir:"./logs",console:1,maxSize:20,maxStringLen:100,maxArrayItems:100},db:{dialect:"mysql",host:"127.0.0.1",port:3306,username:"root",password:"root",database:"befly_demo",poolMax:10},redis:{host:"127.0.0.1",port:6379,username:"",password:"",db:0,prefix:"befly_demo"},auth:{secret:"befly-secret",expiresIn:"7d",algorithm:"HS256"},cors:{origin:"*",methods:"GET,HEAD,PUT,PATCH,POST,DELETE",allowedHeaders:"Content-Type,Authorization",exposedHeaders:"",maxAge:86400,credentials:"true"},rateLimit:{enable:1,defaultLimit:1000,defaultWindow:60,key:"ip",skipRoutes:[],rules:[]},disableMenus:["**/404","**/403","**/500","**/login"],addons:{}};async function FX($){if($!=="development"&&$!=="production")throw Error(`\u914D\u7F6E\u9519\u8BEF\uFF1ANODE_ENV \u53EA\u80FD\u662F 'development' \u6216 'production'\uFF0C\u5F53\u524D\u503C=${String($)}`);let J=kZ(process.cwd(),"configs"),Z=await j$(kZ(J,"befly.common.json"),{}),G=await j$(kZ(J,`befly.${$}.json`),{}),X=AX(KH,Z,G);X.nodeEnv=$;let Y=X.redis?.prefix;if(typeof Y==="string"){if(Y.trim().includes(":"))throw Error(`\u914D\u7F6E\u9519\u8BEF\uFF1Aredis.prefix \u4E0D\u5141\u8BB8\u5305\u542B ':'\uFF08RedisHelper \u4F1A\u81EA\u52A8\u62FC\u63A5\u5206\u9694\u7B26 ':'\uFF09\uFF0C\u8BF7\u6539\u4E3A\u4E0D\u5E26\u5192\u53F7\u7684\u524D\u7F00\uFF0C\u4F8B\u5982 'befly_demo'\uFF0C\u5F53\u524D\u503C=${Y}`)}return X}a();n0();async function RX($){let J=!1,Z=new Set;for(let G of $)try{if(!n(G)){q.warn({item:G,msg:"\u63A5\u53E3\u5FC5\u987B\u662F\u5BF9\u8C61"}),J=!0;continue}let X=G,Y=X.name;if(typeof Y!=="string"||Y.trim()===""){q.warn(Object.assign({},b(X,["handler"]),{msg:"\u63A5\u53E3\u7684 name \u5C5E\u6027\u5FC5\u987B\u662F\u975E\u7A7A\u5B57\u7B26\u4E32"})),J=!0;continue}if(typeof X.handler!=="function"){q.warn(Object.assign({},b(X,["handler"]),{msg:"\u63A5\u53E3\u7684 handler \u5C5E\u6027\u5FC5\u987B\u662F\u51FD\u6570"})),J=!0;continue}let Q=X.path;if(typeof Q!=="string"||Q.trim()==="")q.warn(Object.assign({},b(X,["handler"]),{msg:"\u63A5\u53E3\u7684 path \u5C5E\u6027\u5FC5\u987B\u662F\u975E\u7A7A\u5B57\u7B26\u4E32\uFF08\u7531\u7CFB\u7EDF\u751F\u6210\uFF09"})),J=!0;else{let C=Q.trim();if(Z.has(C))q.warn(Object.assign({},b(X,["handler"]),{msg:"\u63A5\u53E3\u7684 path \u91CD\u590D\uFF08\u4E25\u683C\u6A21\u5F0F\u7981\u6B62\u91CD\u590D path\uFF09"})),J=!0;else Z.add(C);if(/^(GET|POST|PUT|PATCH|DELETE|OPTIONS|HEAD)\b/i.test(C))q.warn(Object.assign({},b(X,["handler"]),{msg:"\u63A5\u53E3\u7684 path \u4E0D\u5141\u8BB8\u5305\u542B method \u524D\u7F00\uFF0C\u5E94\u4E3A url.pathname\uFF08\u4F8B\u5982 /api/app/xxx\uFF09"})),J=!0;if(!C.startsWith("/api/"))q.warn(Object.assign({},b(X,["handler"]),{msg:"\u63A5\u53E3\u7684 path \u5FC5\u987B\u4EE5 /api/ \u5F00\u5934"})),J=!0;if(C.includes(" "))q.warn(Object.assign({},b(X,["handler"]),{msg:"\u63A5\u53E3\u7684 path \u4E0D\u5141\u8BB8\u5305\u542B\u7A7A\u683C"})),J=!0;if(C.includes("/api//"))q.warn(Object.assign({},b(X,["handler"]),{msg:"\u63A5\u53E3\u7684 path \u4E0D\u5141\u8BB8\u51FA\u73B0 /api//\uFF08\u91CD\u590D\u659C\u6760\uFF09"})),J=!0}let V=X.routePrefix,O=typeof V==="string"?V.trim():"";if(O==="")q.warn(Object.assign({},b(X,["handler"]),{msg:"\u63A5\u53E3\u7684 routePrefix \u5C5E\u6027\u5FC5\u987B\u662F\u975E\u7A7A\u5B57\u7B26\u4E32\uFF08\u7531\u7CFB\u7EDF\u751F\u6210\uFF09"})),J=!0;else{if(!(O==="/app"||O.startsWith("/addon/")))q.warn(Object.assign({},b(X,["handler"]),{msg:"\u63A5\u53E3\u7684 routePrefix \u5FC5\u987B\u662F /app \u6216 /addon/<name>\uFF08\u7531\u7CFB\u7EDF\u751F\u6210\uFF09"})),J=!0;if(typeof Q==="string"&&Q.trim()!==""){let C=Q.trim(),T=`/api${O}/`;if(!C.startsWith(T))q.warn(Object.assign({},b(X,["handler"]),{expectedPrefix:T,msg:"\u63A5\u53E3\u7684 path \u4E0E routePrefix \u4E0D\u4E00\u81F4\uFF1A\u5E94\u4EE5 /api${routePrefix}/ \u5F00\u5934\uFF08\u7531\u7CFB\u7EDF\u751F\u6210\uFF09"})),J=!0}}let K=X.method;if(K!==void 0&&!["GET","POST","GET,POST"].includes(String(K).toUpperCase()))q.warn(Object.assign({},b(X,["handler"]),{msg:"\u63A5\u53E3\u7684 method \u5C5E\u6027\u5FC5\u987B\u662F\u6709\u6548\u7684 HTTP \u65B9\u6CD5 (GET, POST, GET,POST)"})),J=!0;let A=X.auth;if(A!==void 0&&typeof A!=="boolean")q.warn(Object.assign({},b(X,["handler"]),{msg:"\u63A5\u53E3\u7684 auth \u5C5E\u6027\u5FC5\u987B\u662F\u5E03\u5C14\u503C (true=\u9700\u767B\u5F55, false=\u516C\u5F00)"})),J=!0;let B=X.fields;if(B!==void 0&&B!==null&&!n(B))q.warn(Object.assign({},b(X,["handler"]),{msg:"\u63A5\u53E3\u7684 fields \u5C5E\u6027\u5FC5\u987B\u662F\u5BF9\u8C61"})),J=!0;let L=X.required;if(L!==void 0&&!Array.isArray(L))q.warn(Object.assign({},b(X,["handler"]),{msg:"\u63A5\u53E3\u7684 required \u5C5E\u6027\u5FC5\u987B\u662F\u6570\u7EC4"})),J=!0;if(Array.isArray(L)){if(L.some((C)=>typeof C!=="string"))q.warn(Object.assign({},b(X,["handler"]),{msg:"\u63A5\u53E3\u7684 required \u5C5E\u6027\u5FC5\u987B\u662F\u5B57\u7B26\u4E32\u6570\u7EC4"})),J=!0}}catch(X){q.error({err:X,item:G,msg:"\u63A5\u53E3\u89E3\u6790\u5931\u8D25"}),J=!0}if(J)throw Error("\u63A5\u53E3\u7ED3\u6784\u68C0\u67E5\u5931\u8D25")}var _H=new Set(["mysql","postgresql","sqlite"]);function $J($){return typeof $==="string"&&$.trim().length>0}function yZ($){return typeof $==="number"&&Number.isFinite($)&&$>=1&&$<=65535}function AH($){return typeof $==="number"&&Number.isFinite($)&&$>=0&&Math.floor($)===$}function FH($){let J=String($||"").toLowerCase().trim();if(J==="postgresql")return"postgresql";if(J==="sqlite")return"sqlite";if(J==="mysql")return"mysql";return J}function RH($){if(!$)throw Error("\u914D\u7F6E\u9519\u8BEF\uFF1A\u7F3A\u5C11 db \u914D\u7F6E\uFF08config.db\uFF09");let J=FH($.dialect);if(!_H.has(J))throw Error(`\u914D\u7F6E\u9519\u8BEF\uFF1Adb.dialect \u53EA\u5141\u8BB8 mysql/postgresql/sqlite\uFF0C\u5F53\u524D\u503C=${String($.dialect)}`);if(J==="sqlite"){if(!$J($.database))throw Error(`\u914D\u7F6E\u9519\u8BEF\uFF1Adb.dialect=sqlite \u65F6\u5FC5\u987B\u8BBE\u7F6E db.database\uFF08sqlite \u6587\u4EF6\u8DEF\u5F84\u6216 :memory:\uFF09\uFF0C\u5F53\u524D\u503C=${String($.database)}`);if($.poolMax!==void 0){if(typeof $.poolMax!=="number"||!Number.isFinite($.poolMax)||$.poolMax<=0)throw Error(`\u914D\u7F6E\u9519\u8BEF\uFF1Adb.poolMax \u5FC5\u987B\u4E3A\u6B63\u6570\uFF0C\u5F53\u524D\u503C=${String($.poolMax)}`)}return}if(!$J($.host))throw Error(`\u914D\u7F6E\u9519\u8BEF\uFF1Adb.host \u5FC5\u987B\u4E3A\u975E\u7A7A\u5B57\u7B26\u4E32\uFF0C\u5F53\u524D\u503C=${String($.host)}`);if(!yZ($.port))throw Error(`\u914D\u7F6E\u9519\u8BEF\uFF1Adb.port \u5FC5\u987B\u4E3A 1..65535 \u7684\u6570\u5B57\uFF0C\u5F53\u524D\u503C=${String($.port)}`);if(!$J($.username))throw Error(`\u914D\u7F6E\u9519\u8BEF\uFF1Adb.username \u5FC5\u987B\u4E3A\u975E\u7A7A\u5B57\u7B26\u4E32\uFF0C\u5F53\u524D\u503C=${String($.username)}`);if($.password!==void 0&&typeof $.password!=="string")throw Error(`\u914D\u7F6E\u9519\u8BEF\uFF1Adb.password \u5FC5\u987B\u4E3A\u5B57\u7B26\u4E32\uFF08\u5141\u8BB8\u4E3A\u7A7A\u5B57\u7B26\u4E32\uFF09\uFF0C\u5F53\u524D\u503C=${String($.password)}`);if(!$J($.database))throw Error(`\u914D\u7F6E\u9519\u8BEF\uFF1Adb.database \u5FC5\u987B\u4E3A\u975E\u7A7A\u5B57\u7B26\u4E32\uFF0C\u5F53\u524D\u503C=${String($.database)}`);if($.poolMax!==void 0){if(typeof $.poolMax!=="number"||!Number.isFinite($.poolMax)||$.poolMax<=0)throw Error(`\u914D\u7F6E\u9519\u8BEF\uFF1Adb.poolMax \u5FC5\u987B\u4E3A\u6B63\u6570\uFF0C\u5F53\u524D\u503C=${String($.poolMax)}`)}}function IH($){if(!$)throw Error("\u914D\u7F6E\u9519\u8BEF\uFF1A\u7F3A\u5C11 redis \u914D\u7F6E\uFF08config.redis\uFF09");if($.host!==void 0&&typeof $.host!=="string")throw Error(`\u914D\u7F6E\u9519\u8BEF\uFF1Aredis.host \u5FC5\u987B\u4E3A\u5B57\u7B26\u4E32\uFF0C\u5F53\u524D\u503C=${String($.host)}`);if($.port!==void 0&&!yZ($.port))throw Error(`\u914D\u7F6E\u9519\u8BEF\uFF1Aredis.port \u5FC5\u987B\u4E3A 1..65535 \u7684\u6570\u5B57\uFF0C\u5F53\u524D\u503C=${String($.port)}`);if($.db!==void 0&&!AH($.db))throw Error(`\u914D\u7F6E\u9519\u8BEF\uFF1Aredis.db \u5FC5\u987B\u4E3A\u975E\u8D1F\u6574\u6570\uFF0C\u5F53\u524D\u503C=${String($.db)}`);let J=$.prefix;if(J!==void 0){if(typeof J!=="string")throw Error(`\u914D\u7F6E\u9519\u8BEF\uFF1Aredis.prefix \u5FC5\u987B\u4E3A\u5B57\u7B26\u4E32\uFF0C\u5F53\u524D\u503C=${String(J)}`);if(J.includes(":"))throw Error(`\u914D\u7F6E\u9519\u8BEF\uFF1Aredis.prefix \u4E0D\u5141\u8BB8\u5305\u542B ':'\uFF08RedisHelper \u4F1A\u81EA\u52A8\u62FC\u63A5\u5206\u9694\u7B26 ':'\uFF09\uFF0C\u5F53\u524D\u503C=${String(J)}`)}}async function IX($){if(!$||typeof $!=="object")throw Error("\u914D\u7F6E\u9519\u8BEF\uFF1Aconfig \u5FC5\u987B\u4E3A\u5BF9\u8C61");if($.nodeEnv!=="development"&&$.nodeEnv!=="production")throw Error(`\u914D\u7F6E\u9519\u8BEF\uFF1AnodeEnv \u53EA\u80FD\u662F development/production\uFF0C\u5F53\u524D\u503C=${String($.nodeEnv)}`);if($.appPort!==void 0){if(!yZ($.appPort))throw Error(`\u914D\u7F6E\u9519\u8BEF\uFF1AappPort \u5FC5\u987B\u4E3A 1..65535 \u7684\u6570\u5B57\uFF0C\u5F53\u524D\u503C=${String($.appPort)}`)}if($.appHost!==void 0){if(!$J($.appHost))throw Error(`\u914D\u7F6E\u9519\u8BEF\uFF1AappHost \u5FC5\u987B\u4E3A\u975E\u7A7A\u5B57\u7B26\u4E32\uFF0C\u5F53\u524D\u503C=${String($.appHost)}`)}RH($.db),IH($.redis)}a();n0();var jX=["name","enable","deps","handler"];async function qX($){let J=!1,Z=/^[a-z]+(?:_[a-z]+)*$/;for(let G of $)try{if(!n(G)){q.warn(Object.assign({},b(G,["handler"]),{msg:"\u94A9\u5B50\u5BFC\u51FA\u5FC5\u987B\u662F\u5BF9\u8C61\uFF08export default { deps, handler }\uFF09"})),J=!0;continue}let X=G,Y=X.moduleName;if(typeof Y!=="string"||Y.trim()===""){q.warn(Object.assign({},b(G,["handler"]),{msg:"\u94A9\u5B50\u7684 moduleName \u5FC5\u987B\u662F\u975E\u7A7A\u5B57\u7B26\u4E32\uFF08\u7531\u7CFB\u7EDF\u751F\u6210\uFF0C\u7528\u4E8E deps \u4E0E\u8FD0\u884C\u65F6\u6302\u8F7D\uFF09"})),J=!0;continue}let W=X.customKeys;if(!Array.isArray(W)){q.warn(Object.assign({},b(G,["handler"]),{msg:"\u94A9\u5B50\u626B\u63CF\u7ED3\u679C\u7F3A\u5C11 customKeys\uFF08\u65E0\u6CD5\u5224\u65AD\u7528\u6237\u5BFC\u51FA\u7684\u5B57\u6BB5\u662F\u5426\u5408\u6CD5\uFF09"})),J=!0;continue}if(W.some((K)=>typeof K!=="string")){q.warn(Object.assign({},b(G,["handler"]),{msg:"\u94A9\u5B50\u7684 customKeys \u5FC5\u987B\u662F string[]\uFF08\u7531\u7CFB\u7EDF\u751F\u6210\uFF09"})),J=!0;continue}let Q=W.filter((K)=>!jX.includes(K));if(Q.length>0){q.warn(Object.assign({},b(G,["handler"]),{msg:`\u94A9\u5B50\u5BFC\u51FA\u5B58\u5728\u4E0D\u652F\u6301\u7684\u5C5E\u6027\uFF1A${Q.join(", ")}\uFF1B\u4EC5\u5141\u8BB8\uFF1A${jX.join(", ")}\uFF1B\u5F53\u524D customKeys\uFF1A${W.join(", ")}`})),J=!0;continue}let V=W.includes("enable"),O=W.includes("deps");if(V){if(typeof X.enable!=="boolean"){q.warn(Object.assign({},b(G,["handler"]),{msg:"\u94A9\u5B50\u7684 enable \u5C5E\u6027\u5FC5\u987B\u662F boolean\uFF08true/false\uFF09\uFF0C\u4E0D\u5141\u8BB8 0/1 \u7B49\u5176\u4ED6\u7C7B\u578B"})),J=!0;continue}}else X.enable=!0;if(X.source==="core"){let K=typeof X.name==="string"?X.name:"";if(K===""){q.warn(Object.assign({},b(G,["handler"]),{msg:"core \u5185\u7F6E\u94A9\u5B50\u5FC5\u987B\u663E\u5F0F\u8BBE\u7F6E name\uFF08string\uFF09\uFF0C\u7528\u4E8E\u786E\u5B9A\u94A9\u5B50\u540D\u79F0"})),J=!0;continue}if(!Z.test(K)){q.warn(Object.assign({},b(G,["handler"]),{msg:"core \u5185\u7F6E\u94A9\u5B50\u7684 name \u5FC5\u987B\u6EE1\u8DB3\u5C0F\u5199\u5B57\u6BCD+\u4E0B\u5212\u7EBF\u683C\u5F0F\uFF08\u4F8B\u5982 auth / rate_limit\uFF09\uFF0C\u4E0D\u5141\u8BB8\u7A7A\u683C\u3001\u9A7C\u5CF0\u6216\u5176\u4ED6\u5B57\u7B26"})),J=!0;continue}if(!Z.test(String(X.moduleName))){q.warn(Object.assign({},b(G,["handler"]),{msg:"core \u5185\u7F6E\u94A9\u5B50\u7684 moduleName \u5FC5\u987B\u6EE1\u8DB3\u5C0F\u5199\u5B57\u6BCD+\u4E0B\u5212\u7EBF\u683C\u5F0F\uFF08\u7531\u7CFB\u7EDF\u751F\u6210\uFF0C\u4E14\u5FC5\u987B\u4E0E name \u4E00\u81F4\uFF09"})),J=!0;continue}if(K!==String(X.moduleName)){q.warn(Object.assign({},b(G,["handler"]),{msg:"core \u5185\u7F6E\u94A9\u5B50\u7684 name \u5FC5\u987B\u4E0E moduleName \u5B8C\u5168\u4E00\u81F4"})),J=!0;continue}let A=X.filePath;if(typeof A!=="string"||!A.startsWith(`core:hook:${K}`)){q.warn(Object.assign({},b(G,["handler"]),{msg:"core \u5185\u7F6E\u94A9\u5B50\u5FC5\u987B\u6765\u81EA\u9759\u6001\u6CE8\u518C\uFF08filePath \u5FC5\u987B\u4EE5 core:hook:<name> \u5F00\u5934\uFF09\uFF0C\u4E0D\u5141\u8BB8\u901A\u8FC7\u626B\u63CF\u76EE\u5F55\u52A0\u8F7D"})),J=!0;continue}}if(O){let K=X.deps;if(!Array.isArray(K)){q.warn(Object.assign({},b(G,["handler"]),{msg:"\u94A9\u5B50\u7684 deps \u5C5E\u6027\u5FC5\u987B\u662F\u5B57\u7B26\u4E32\u6570\u7EC4"})),J=!0;continue}if(K.some((A)=>typeof A!=="string")){q.warn(Object.assign({},b(G,["handler"]),{msg:"\u94A9\u5B50\u7684 deps \u5C5E\u6027\u5FC5\u987B\u662F\u5B57\u7B26\u4E32\u6570\u7EC4"})),J=!0;continue}}else{let K=X.deps;if(!Array.isArray(K))X.deps=[]}if(typeof X.handler!=="function"){q.warn(Object.assign({},b(G,["handler"]),{msg:"\u94A9\u5B50\u7684 handler \u5C5E\u6027\u5FC5\u987B\u662F\u51FD\u6570"})),J=!0;continue}}catch(X){q.error({err:X,item:G,msg:"\u94A9\u5B50\u89E3\u6790\u5931\u8D25"}),J=!0}if(J)throw Error("\u94A9\u5B50\u7ED3\u6784\u68C0\u67E5\u5931\u8D25")}a();hZ();function TH($){if(!$)return{ok:!1,reason:"path \u4E0D\u80FD\u4E3A\u7A7A"};if(!$.startsWith("/"))return{ok:!1,reason:"path \u5FC5\u987B\u4EE5 / \u5F00\u5934"};if($.length>1&&$.endsWith("/"))return{ok:!1,reason:"path \u672B\u5C3E\u4E0D\u80FD\u662F /\uFF08\u6839\u8DEF\u5F84 / \u9664\u5916\uFF09"};if($.includes("//"))return{ok:!1,reason:"path \u4E0D\u80FD\u5305\u542B //"};if($.includes(".."))return{ok:!1,reason:"path \u4E0D\u80FD\u5305\u542B .."};return{ok:!0,reason:""}}var NX=async($)=>{let J=!1,Z=await TX($),G=[];for(let Y of Z)G.push({menu:Y,depth:1});let X=new Set;while(G.length>0){let Y=G.pop(),W=Y?.menu,Q=typeof Y?.depth==="number"?Y.depth:0;if(W===null||typeof W!=="object"){J=!0,q.warn({menu:W,msg:"\u83DC\u5355\u8282\u70B9\u5FC5\u987B\u662F\u5BF9\u8C61"});continue}if(Q>3){J=!0,q.warn({path:W?.path,depth:Q,msg:"\u83DC\u5355\u5C42\u7EA7\u8D85\u8FC7 3 \u7EA7\uFF08\u6700\u591A\u4E09\u7EA7\uFF09"});continue}let V=W.children;if(typeof V<"u"&&!Array.isArray(V)){J=!0,q.warn({path:W?.path,childrenType:typeof V,msg:"\u83DC\u5355 children \u5FC5\u987B\u662F\u6570\u7EC4"});continue}if(Array.isArray(V)&&V.length>0)if(Q>=3)J=!0,q.warn({path:W?.path,depth:Q,msg:"\u83DC\u5355\u5C42\u7EA7\u8D85\u8FC7 3 \u7EA7\uFF08\u6700\u591A\u4E09\u7EA7\uFF09"});else for(let L of V)G.push({menu:L,depth:Q+1});let O=typeof W.path==="string"?W.path.trim():"",K=typeof W.name==="string"?W.name.trim():"",A=typeof W.sort==="number"?W.sort:999999;if(typeof W.path==="string")W.path=O;if(typeof W.name==="string")W.name=K;if(typeof W.sort>"u")W.sort=A;if(!O){J=!0,q.warn({menu:W,msg:"\u83DC\u5355\u7F3A\u5C11 path\uFF08\u5FC5\u987B\u662F\u975E\u7A7A\u5B57\u7B26\u4E32\uFF09"});continue}let B=TH(O);if(!B.ok)J=!0,q.warn({path:O,reason:B.reason,msg:"\u83DC\u5355 path \u4E0D\u5408\u6CD5"});if(!K)J=!0,q.warn({path:O,menu:W,msg:"\u83DC\u5355\u7F3A\u5C11 name\uFF08\u5FC5\u987B\u662F\u975E\u7A7A\u5B57\u7B26\u4E32\uFF09"});if(typeof W.sort<"u"&&typeof W.sort!=="number")J=!0,q.warn({path:O,sort:W.sort,msg:"\u83DC\u5355 sort \u5FC5\u987B\u662F number"});if(typeof W.sort==="number"&&(!Number.isFinite(W.sort)||W.sort<1))J=!0,q.warn({path:O,sort:W.sort,msg:"\u83DC\u5355 sort \u6700\u5C0F\u503C\u4E3A 1"});if(X.has(O)){J=!0,q.warn({path:O,msg:"\u83DC\u5355 path \u91CD\u590D\uFF08\u4E25\u683C\u6A21\u5F0F\u7981\u6B62\u91CD\u590D path\uFF09"});continue}X.add(O)}if(J)throw Error("\u83DC\u5355\u7ED3\u6784\u68C0\u67E5\u5931\u8D25");return Z};a();n0();var vX=["name","enable","deps","handler"];async function DX($){let J=!1,Z=/^[a-z]+(?:_[a-z]+)*$/;for(let G of $)try{if(!n(G)){q.warn(Object.assign({},b(G,["handler"]),{msg:"\u63D2\u4EF6\u5BFC\u51FA\u5FC5\u987B\u662F\u5BF9\u8C61\uFF08export default { deps, handler }\uFF09"})),J=!0;continue}let X=G,Y=X.moduleName;if(typeof Y!=="string"||Y.trim()===""){q.warn(Object.assign({},b(G,["handler"]),{msg:"\u63D2\u4EF6\u7684 moduleName \u5FC5\u987B\u662F\u975E\u7A7A\u5B57\u7B26\u4E32\uFF08\u7531\u7CFB\u7EDF\u751F\u6210\uFF0C\u7528\u4E8E deps \u4E0E\u8FD0\u884C\u65F6\u6302\u8F7D\uFF09"})),J=!0;continue}let W=X.customKeys;if(!Array.isArray(W)){q.warn(Object.assign({},b(G,["handler"]),{msg:"\u63D2\u4EF6\u626B\u63CF\u7ED3\u679C\u7F3A\u5C11 customKeys\uFF08\u65E0\u6CD5\u5224\u65AD\u7528\u6237\u5BFC\u51FA\u7684\u5B57\u6BB5\u662F\u5426\u5408\u6CD5\uFF09"})),J=!0;continue}if(W.some((K)=>typeof K!=="string")){q.warn(Object.assign({},b(G,["handler"]),{msg:"\u63D2\u4EF6\u7684 customKeys \u5FC5\u987B\u662F string[]\uFF08\u7531\u7CFB\u7EDF\u751F\u6210\uFF09"})),J=!0;continue}let Q=W.filter((K)=>!vX.includes(K));if(Q.length>0){q.warn(Object.assign({},b(G,["handler"]),{msg:`\u63D2\u4EF6\u5BFC\u51FA\u5B58\u5728\u4E0D\u652F\u6301\u7684\u5C5E\u6027\uFF1A${Q.join(", ")}\uFF1B\u4EC5\u5141\u8BB8\uFF1A${vX.join(", ")}\uFF1B\u5F53\u524D customKeys\uFF1A${W.join(", ")}`})),J=!0;continue}let V=W.includes("enable"),O=W.includes("deps");if(V){if(typeof X.enable!=="boolean"){q.warn(Object.assign({},b(G,["handler"]),{msg:"\u63D2\u4EF6\u7684 enable \u5C5E\u6027\u5FC5\u987B\u662F boolean\uFF08true/false\uFF09\uFF0C\u4E0D\u5141\u8BB8 0/1 \u7B49\u5176\u4ED6\u7C7B\u578B"})),J=!0;continue}}else X.enable=!0;if(X.source==="core"){let K=typeof X.name==="string"?X.name:"";if(K===""){q.warn(Object.assign({},b(G,["handler"]),{msg:"core \u5185\u7F6E\u63D2\u4EF6\u5FC5\u987B\u663E\u5F0F\u8BBE\u7F6E name\uFF08string\uFF09\uFF0C\u7528\u4E8E\u786E\u5B9A\u63D2\u4EF6\u540D\u79F0"})),J=!0;continue}if(!Z.test(K)){q.warn(Object.assign({},b(G,["handler"]),{msg:"core \u5185\u7F6E\u63D2\u4EF6\u7684 name \u5FC5\u987B\u6EE1\u8DB3\u5C0F\u5199\u5B57\u6BCD+\u4E0B\u5212\u7EBF\u683C\u5F0F\uFF08\u4F8B\u5982 logger / redis_cache\uFF09\uFF0C\u4E0D\u5141\u8BB8\u7A7A\u683C\u3001\u9A7C\u5CF0\u6216\u5176\u4ED6\u5B57\u7B26"})),J=!0;continue}if(!Z.test(String(X.moduleName))){q.warn(Object.assign({},b(G,["handler"]),{msg:"core \u5185\u7F6E\u63D2\u4EF6\u7684 moduleName \u5FC5\u987B\u6EE1\u8DB3\u5C0F\u5199\u5B57\u6BCD+\u4E0B\u5212\u7EBF\u683C\u5F0F\uFF08\u7531\u7CFB\u7EDF\u751F\u6210\uFF0C\u4E14\u5FC5\u987B\u4E0E name \u4E00\u81F4\uFF09"})),J=!0;continue}if(K!==String(X.moduleName)){q.warn(Object.assign({},b(G,["handler"]),{msg:"core \u5185\u7F6E\u63D2\u4EF6\u7684 name \u5FC5\u987B\u4E0E moduleName \u5B8C\u5168\u4E00\u81F4"})),J=!0;continue}let A=X.filePath;if(typeof A!=="string"||!A.startsWith(`core:plugin:${K}`)){q.warn(Object.assign({},b(G,["handler"]),{msg:"core \u5185\u7F6E\u63D2\u4EF6\u5FC5\u987B\u6765\u81EA\u9759\u6001\u6CE8\u518C\uFF08filePath \u5FC5\u987B\u4EE5 core:plugin:<name> \u5F00\u5934\uFF09\uFF0C\u4E0D\u5141\u8BB8\u901A\u8FC7\u626B\u63CF\u76EE\u5F55\u52A0\u8F7D"})),J=!0;continue}}if(O){let K=X.deps;if(!Array.isArray(K)){q.warn(Object.assign({},b(G,["handler"]),{msg:"\u63D2\u4EF6\u7684 deps \u5C5E\u6027\u5FC5\u987B\u662F\u5B57\u7B26\u4E32\u6570\u7EC4"})),J=!0;continue}if(K.some((A)=>typeof A!=="string")){q.warn(Object.assign({},b(G,["handler"]),{msg:"\u63D2\u4EF6\u7684 deps \u5C5E\u6027\u5FC5\u987B\u662F\u5B57\u7B26\u4E32\u6570\u7EC4"})),J=!0;continue}}else{let K=X.deps;if(!Array.isArray(K))X.deps=[]}if(typeof X.handler!=="function"){q.warn(Object.assign({},b(G,["handler"]),{msg:"\u63D2\u4EF6\u7684 handler \u5C5E\u6027\u5FC5\u987B\u662F\u51FD\u6570"})),J=!0;continue}}catch(X){q.error({err:X,item:G,msg:"\u63D2\u4EF6\u89E3\u6790\u5931\u8D25"}),J=!0}if(J)throw Error("\u63D2\u4EF6\u7ED3\u6784\u68C0\u67E5\u5931\u8D25")}a();function NH($){if($===null)return!0;return typeof $==="string"||typeof $==="number"||typeof $==="boolean"}function vH($){if(!$||typeof $!=="object")return!1;if($ instanceof Date)return!1;if(Array.isArray($))return!1;return!0}function bZ($){if(NH($))return!0;if(Array.isArray($)){for(let J of $)if(!bZ(J))return!1;return!0}if(vH($)){for(let J of Object.values($)){if(J===void 0)continue;if(!bZ(J))return!1}return!0}return!1}function XJ($){if($===null)return"null";if($===void 0)return"undefined";if(typeof $==="string"){let Z=$.length>80?`${$.slice(0,80)}...`:$;return JSON.stringify(Z)}if(typeof $==="number"||typeof $==="boolean"||typeof $==="bigint")return String($);if(typeof $==="function")return"[Function]";try{let Z=JSON.stringify($);if(typeof Z==="string")return Z.length>120?`${Z.slice(0,120)}...`:Z}catch{}let J=String($);return J.length>120?`${J.slice(0,120)}...`:J}var yX=["id","created_at","updated_at","deleted_at","state"],DH=new Set(yX),xX=["string","number","text","array_string","array_text","array_number_string","array_number_text"],kH=new Set(xX),fX=["name","type","min","max","default","detail","index","unique","nullable","unsigned","regexp"],yH=new Set(fX),xH=/^_?[a-z][a-z0-9]*(?:[A-Z][a-z0-9]*)*$/,fH=/^[\u4e00-\u9fa5a-zA-Z0-9 _-]+$/,kX=65535;async function gX($){let J=!1;for(let Z of $){if(Z.type!=="table")continue;let G=typeof Z.sourceName==="string"?Z.sourceName:"",X=G?`${G}\u8868 `:"\u8868 ";try{let Y=Z.fileName;if(Z.source==="addon"&&String(Z.addonName).trim()===""){q.warn(`${X}${Y} addon \u8868\u7F3A\u5C11 addonName`),J=!0;continue}let W=Z.content;if(typeof W!=="object"||W===null||Array.isArray(W)){q.warn(`${X}${Y} \u8868\u5B9A\u4E49\u65E0\u6548\uFF1A\u5FC5\u987B\u4E3A\u5BF9\u8C61`),J=!0;continue}if(!xH.test(Y)){q.warn(`${X}${Y} \u6587\u4EF6\u540D\u5FC5\u987B\u4F7F\u7528\u5C0F\u9A7C\u5CF0\u547D\u540D\uFF08\u4F8B\u5982 testCustomers.json\uFF09`),J=!0;continue}for(let[Q,V]of Object.entries(W)){if(typeof V!=="object"||V===null||Array.isArray(V)){q.warn(`${X}${Y} \u6587\u4EF6 ${Q} \u89C4\u5219\u5FC5\u987B\u4E3A\u5BF9\u8C61`),J=!0;continue}if(DH.has(Q))q.warn(`${X}${Y} \u6587\u4EF6\u5305\u542B\u4FDD\u7559\u5B57\u6BB5 ${Q}\uFF0C`+`\u4E0D\u80FD\u5728\u8868\u5B9A\u4E49\u4E2D\u4F7F\u7528\u4EE5\u4E0B\u5B57\u6BB5: ${yX.join(", ")}`),J=!0;let O=V,A=Object.keys(O).filter((D)=>!yH.has(D));if(A.length>0)q.warn(`${X}${Y} \u6587\u4EF6 ${Q} \u5305\u542B\u975E\u6CD5\u5C5E\u6027: ${A.join(", ")}\uFF0C`+`\u5141\u8BB8\u7684\u5C5E\u6027\u4E3A: ${fX.join(", ")}`),J=!0;if(!O.name||typeof O.name!=="string"){q.warn(`${X}${Y} \u6587\u4EF6 ${Q} \u7F3A\u5C11\u5FC5\u586B\u5B57\u6BB5 name \u6216\u7C7B\u578B\u9519\u8BEF`),J=!0;continue}if(!O.type||typeof O.type!=="string"){q.warn(`${X}${Y} \u6587\u4EF6 ${Q} \u7F3A\u5C11\u5FC5\u586B\u5B57\u6BB5 type \u6216\u7C7B\u578B\u9519\u8BEF`),J=!0;continue}if(O.min!==void 0&&!(O.min===null||typeof O.min==="number"))q.warn(`${X}${Y} \u6587\u4EF6 ${Q} \u5B57\u6BB5 min \u7C7B\u578B\u9519\u8BEF\uFF0C\u5FC5\u987B\u4E3A null \u6216\u6570\u5B57`),J=!0;if(O.max!==void 0&&!(O.max===null||typeof O.max==="number"))q.warn(`${X}${Y} \u6587\u4EF6 ${Q} \u5B57\u6BB5 max \u7C7B\u578B\u9519\u8BEF\uFF0C\u5FC5\u987B\u4E3A null \u6216\u6570\u5B57`),J=!0;if(O.detail!==void 0&&typeof O.detail!=="string")q.warn(`${X}${Y} \u6587\u4EF6 ${Q} \u5B57\u6BB5 detail \u7C7B\u578B\u9519\u8BEF\uFF0C\u5FC5\u987B\u4E3A\u5B57\u7B26\u4E32`),J=!0;if(O.index!==void 0&&typeof O.index!=="boolean")q.warn(`${X}${Y} \u6587\u4EF6 ${Q} \u5B57\u6BB5 index \u7C7B\u578B\u9519\u8BEF\uFF0C\u5FC5\u987B\u4E3A\u5E03\u5C14\u503C`),J=!0;if(O.unique!==void 0&&typeof O.unique!=="boolean")q.warn(`${X}${Y} \u6587\u4EF6 ${Q} \u5B57\u6BB5 unique \u7C7B\u578B\u9519\u8BEF\uFF0C\u5FC5\u987B\u4E3A\u5E03\u5C14\u503C`),J=!0;if(O.nullable!==void 0&&typeof O.nullable!=="boolean")q.warn(`${X}${Y} \u6587\u4EF6 ${Q} \u5B57\u6BB5 nullable \u7C7B\u578B\u9519\u8BEF\uFF0C\u5FC5\u987B\u4E3A\u5E03\u5C14\u503C`),J=!0;if(O.unsigned!==void 0&&typeof O.unsigned!=="boolean")q.warn(`${X}${Y} \u6587\u4EF6 ${Q} \u5B57\u6BB5 unsigned \u7C7B\u578B\u9519\u8BEF\uFF0C\u5FC5\u987B\u4E3A\u5E03\u5C14\u503C`),J=!0;if(O.regexp!==void 0&&O.regexp!==null&&typeof O.regexp!=="string")q.warn(`${X}${Y} \u6587\u4EF6 ${Q} \u5B57\u6BB5 regexp \u7C7B\u578B\u9519\u8BEF\uFF0C\u5FC5\u987B\u4E3A null \u6216\u5B57\u7B26\u4E32`),J=!0;if(O.default!==void 0&&O.default!==null&&!bZ(O.default))q.warn(`${X}${Y} \u6587\u4EF6 ${Q} \u5B57\u6BB5 default \u7C7B\u578B\u9519\u8BEF\uFF0C\u5FC5\u987B\u4E3A\u53EF JSON \u5E8F\u5217\u5316\u7684\u503C\u6216 null`+`\uFF08typeof=${typeof O.default}\uFF0Cvalue=${XJ(O.default)}\uFF09`),J=!0;let{name:B,type:L,min:C,max:T,default:w}=O;if(!fH.test(B))q.warn(`${X}${Y} \u6587\u4EF6 ${Q} \u5B57\u6BB5\u540D\u79F0 "${B}" \u683C\u5F0F\u9519\u8BEF\uFF0C`+"\u5FC5\u987B\u4E3A\u4E2D\u6587\u3001\u6570\u5B57\u3001\u5B57\u6BCD\u3001\u4E0B\u5212\u7EBF\u3001\u77ED\u6A2A\u7EBF\u3001\u7A7A\u683C"),J=!0;if(!kH.has(L))q.warn(`${X}${Y} \u6587\u4EF6 ${Q} \u5B57\u6BB5\u7C7B\u578B "${L}" \u683C\u5F0F\u9519\u8BEF\uFF0C`+`\u5FC5\u987B\u4E3A${xX.join("\u3001")}\u4E4B\u4E00`),J=!0;if(L!=="number"&&O.unsigned!==void 0)q.warn(`${X}${Y} \u6587\u4EF6 ${Q} \u5B57\u6BB5\u7C7B\u578B\u4E3A ${L}\uFF0C\u4E0D\u5141\u8BB8\u8BBE\u7F6E unsigned\uFF08\u4EC5 number \u7C7B\u578B\u6709\u6548\uFF09`),J=!0;if(O.unique===!0&&O.index===!0)q.warn(`${X}${Y} \u6587\u4EF6 ${Q} \u540C\u65F6\u8BBE\u7F6E\u4E86 unique=true \u548C index=true\uFF0C`+"unique \u548C index \u4E0D\u80FD\u540C\u65F6\u8BBE\u7F6E\uFF0C\u8BF7\u5220\u9664\u5176\u4E00\uFF08\u5426\u5219\u4F1A\u521B\u5EFA\u91CD\u590D\u7D22\u5F15\uFF09"),J=!0;if(C!==void 0&&T!==void 0&&C!==null&&T!==null){if(C>T)q.warn(`${X}${Y} \u6587\u4EF6 ${Q} \u6700\u5C0F\u503C "${C}" \u4E0D\u80FD\u5927\u4E8E\u6700\u5927\u503C "${T}"`),J=!0}if(L==="text"||L==="array_text"||L==="array_number_text"){if(C!==void 0&&C!==null)q.warn(`${X}${Y} \u6587\u4EF6 ${Q} \u7684 ${L} \u7C7B\u578B\u6700\u5C0F\u503C\u5E94\u4E3A null\uFF0C\u5F53\u524D\u4E3A "${C}"`),J=!0;if(T!==void 0&&T!==null)q.warn(`${X}${Y} \u6587\u4EF6 ${Q} \u7684 ${L} \u7C7B\u578B\u6700\u5927\u957F\u5EA6\u5E94\u4E3A null\uFF0C\u5F53\u524D\u4E3A "${T}"`),J=!0;if(w!==void 0&&w!==null)q.warn(`${X}${Y} \u6587\u4EF6 ${Q} \u4E3A ${L} \u7C7B\u578B\uFF0C\u9ED8\u8BA4\u503C\u5FC5\u987B\u4E3A null\uFF0C\u5F53\u524D\u4E3A "${w}"`),J=!0;if(O.index===!0)q.warn(`${X}${Y} \u6587\u4EF6 ${Q} \u4E3A ${L} \u7C7B\u578B\uFF0C\u4E0D\u652F\u6301\u521B\u5EFA\u7D22\u5F15\uFF08index=true \u65E0\u6548\uFF09`),J=!0;if(O.unique===!0)q.warn(`${X}${Y} \u6587\u4EF6 ${Q} \u4E3A ${L} \u7C7B\u578B\uFF0C\u4E0D\u652F\u6301\u552F\u4E00\u7EA6\u675F\uFF08unique=true \u65E0\u6548\uFF09`),J=!0}else if(L==="string"||L==="array_string"||L==="array_number_string"){if(T===void 0||T===null||typeof T!=="number")q.warn(`${X}${Y} \u6587\u4EF6 ${Q} \u4E3A ${L} \u7C7B\u578B\uFF0C`+`\u5FC5\u987B\u8BBE\u7F6E max \u4E14\u7C7B\u578B\u4E3A\u6570\u5B57\uFF1B\u5176\u4E2D array_*_string \u7684 max \u8868\u793A\u5355\u4E2A\u5143\u7D20\u957F\u5EA6\uFF0C\u5F53\u524D\u4E3A "${T}"`),J=!0;else if(T>kX)q.warn(`${X}${Y} \u6587\u4EF6 ${Q} \u6700\u5927\u957F\u5EA6 ${T} \u8D8A\u754C\uFF0C`+`${L} \u7C7B\u578B\u957F\u5EA6\u5FC5\u987B\u5728 1..${kX} \u8303\u56F4\u5185`),J=!0;if(w!==void 0&&w!==null){if(typeof w!=="string")q.warn(`${X}${Y} \u6587\u4EF6 ${Q} \u4E3A ${L} \u7C7B\u578B\uFF0C\u9ED8\u8BA4\u503C\u5FC5\u987B\u4E3A\u5B57\u7B26\u4E32\u6216 null`+`\uFF08typeof=${typeof w}\uFF0Cvalue=${XJ(w)}\uFF09`),J=!0;else if(L!=="string")try{let D=JSON.parse(w);if(!Array.isArray(D))q.warn(`${X}${Y} \u6587\u4EF6 ${Q} \u4E3A ${L} \u7C7B\u578B\uFF0C\u9ED8\u8BA4\u503C\u5E94\u4E3A JSON \u6570\u7EC4\u5B57\u7B26\u4E32\uFF08\u4F8B\u5982 "[]"\uFF09`+`\uFF08value=${XJ(w)}\uFF09`),J=!0}catch{q.warn(`${X}${Y} \u6587\u4EF6 ${Q} \u4E3A ${L} \u7C7B\u578B\uFF0C\u9ED8\u8BA4\u503C\u5E94\u4E3A JSON \u6570\u7EC4\u5B57\u7B26\u4E32\uFF08\u4F8B\u5982 "[]"\uFF09`+`\uFF08value=${XJ(w)}\uFF09`),J=!0}}}else if(L==="number"){if(w!==void 0&&w!==null&&typeof w!=="number")q.warn(`${X}${Y} \u6587\u4EF6 ${Q} \u4E3A number \u7C7B\u578B\uFF0C\u9ED8\u8BA4\u503C\u5FC5\u987B\u4E3A\u6570\u5B57\u6216 null`+`\uFF08typeof=${typeof w}\uFF0Cvalue=${XJ(w)}\uFF09`),J=!0}}}catch(Y){q.error({msg:`${X}${Z.fileName} \u89E3\u6790\u5931\u8D25`,err:Y}),J=!0}}if(J)throw Error("\u8868\u7ED3\u6784\u68C0\u67E5\u5931\u8D25")}a();var{SQL:hX,RedisClient:gH}=globalThis.Bun;class O${static sqlClient=null;static redisClient=null;static sqlConnectedAt=null;static redisConnectedAt=null;static sqlPoolMax=1;static async connectSql($){let J=$||{},Z=J.dialect||"mysql",G=J.host||"127.0.0.1",X=J.port||3306,Y=encodeURIComponent(J.username||"root"),W=encodeURIComponent(J.password||"root"),Q=encodeURIComponent(J.database||"befly_demo"),V;if(Z==="sqlite")V=Q;else{if(!G||!Q)throw Error("\u6570\u636E\u5E93\u914D\u7F6E\u4E0D\u5B8C\u6574\uFF0C\u8BF7\u68C0\u67E5\u914D\u7F6E\u53C2\u6570");V=`${Z}://${Y}:${W}@${G}:${X}/${Q}`}let O;if(Z==="sqlite")O=new hX(V);else O=new hX({url:V,max:J.poolMax??1,bigint:!1});try{let A=(async()=>{let L="";if(Z==="sqlite")L=(await O`SELECT sqlite_version() AS version`)?.[0]?.version;else if(Z==="postgresql")L=(await O`SELECT version() AS version`)?.[0]?.version;else L=(await O`SELECT VERSION() AS version`)?.[0]?.version;return L})(),B=new Promise((L,C)=>{setTimeout(()=>{C(Error(`\u6570\u636E\u5E93\u8FDE\u63A5\u8D85\u65F6 (${30000}ms)`))},30000)});return await Promise.race([A,B]),this.sqlClient=O,this.sqlConnectedAt=Date.now(),this.sqlPoolMax=J.poolMax??1,O}catch(K){q.error({err:K,msg:"[Connect] SQL \u8FDE\u63A5\u5931\u8D25"});try{await O?.close()}catch{}throw K}}static async disconnectSql(){if(this.sqlClient){try{await this.sqlClient.close()}catch($){q.error({err:$,msg:"[Connect] \u5173\u95ED SQL \u8FDE\u63A5\u65F6\u51FA\u9519"})}this.sqlClient=null,this.sqlConnectedAt=null}}static getSql(){if(!this.sqlClient)throw Error("SQL \u5BA2\u6237\u7AEF\u672A\u8FDE\u63A5\uFF0C\u8BF7\u5148\u8C03\u7528 Connect.connectSql()");return this.sqlClient}static async connectRedis($){let J=$||{};try{let Z=J.host||"127.0.0.1",G=J.port||6379,X=J.username||"",Y=J.password||"",W=J.db||0,Q="";if(X&&Y)Q=`${X}:${Y}@`;else if(Y)Q=`:${Y}@`;let V=`redis://${Q}${Z}:${G}/${W}`,O=new gH(V,{connectionTimeout:30000,idleTimeout:0,autoReconnect:!0,maxRetries:3,enableOfflineQueue:!0,enableAutoPipelining:!0});return await O.ping(),this.redisClient=O,this.redisConnectedAt=Date.now(),O}catch(Z){throw q.error({err:Z,msg:"[Connect] Redis \u8FDE\u63A5\u5931\u8D25"}),Error(`Redis \u8FDE\u63A5\u5931\u8D25: ${Z.message}`)}}static async disconnectRedis(){if(this.redisClient){try{this.redisClient.close(),this.redisConnectedAt=null}catch($){q.error({err:$,msg:"[Connect] \u5173\u95ED Redis \u8FDE\u63A5\u65F6\u51FA\u9519"})}this.redisClient=null}}static getRedis(){if(!this.redisClient)throw Error("Redis \u5BA2\u6237\u7AEF\u672A\u8FDE\u63A5\uFF0C\u8BF7\u5148\u8C03\u7528 Connect.connectRedis()");return this.redisClient}static async connect($){try{await this.connectSql($.db||{}),await this.connectRedis($.redis||{})}catch(J){let Z=typeof process?.env?.NODE_ENV==="string"?"development":"";throw q.error({env:Z,err:J,msg:"\u6570\u636E\u5E93\u8FDE\u63A5\u521D\u59CB\u5316\u5931\u8D25"}),await this.disconnect(),J}}static async disconnect(){await this.disconnectSql(),await this.disconnectRedis()}static isConnected(){return{sql:this.sqlClient!==null,redis:this.redisClient!==null}}static getStatus(){let $=Date.now();return{sql:{connected:this.sqlClient!==null,connectedAt:this.sqlConnectedAt,uptime:this.sqlConnectedAt?$-this.sqlConnectedAt:null,poolMax:this.sqlPoolMax},redis:{connected:this.redisClient!==null,connectedAt:this.redisConnectedAt,uptime:this.redisConnectedAt?$-this.redisConnectedAt:null}}}static __setMockSql($){this.sqlClient=$}static __setMockRedis($){this.redisClient=$}static __reset(){this.sqlClient=null,this.redisClient=null,this.sqlConnectedAt=null,this.redisConnectedAt=null,this.sqlPoolMax=1}}a();a();async function bX($){let J=new Map;for(let Z of $)try{if(Object.hasOwn(Z,"type")&&Z.type!=="api")continue;let G=Z,X=G.path,Y={name:G.name,handler:G.handler,route:X},W=G.method;if(typeof W==="string"){let A=W.toUpperCase(),B=A==="POST,GET"?"GET,POST":A;Y.method=["GET","POST","GET,POST"].includes(B)?B:"POST"}else Y.method="POST";let Q=G.auth;if(Q!==void 0)Y.auth=Q;let V=G.fields;if(V!==void 0)Y.fields=V;let O=G.required;if(O!==void 0)Y.required=O;let K=G.rawBody;if(K!==void 0)Y.rawBody=K;J.set(X,Y)}catch(G){throw q.error({err:G,api:Z.relativePath,file:Z.filePath,msg:"\u63A5\u53E3\u52A0\u8F7D\u5931\u8D25"}),G}return J}a();n0();function PJ($,J={}){let Z=J.moduleLabel||"\u6A21\u5757",G=J.getName||((A)=>{let B=A.moduleName;if(typeof B==="string"&&B.trim()!=="")return B;return F$(A.fileName)}),X=J.getDeps||((A)=>{let B=A.deps;if(!Array.isArray(B))return[];return B.filter((L)=>typeof L==="string")}),Y=[],W=new Set,Q=new Set,V={},O=!0;for(let A of $){let B=G(A);if(typeof B!=="string"||B.trim()===""){q.error({item:A,msg:`${Z} \u540D\u79F0\u89E3\u6790\u5931\u8D25\uFF08getName \u8FD4\u56DE\u7A7A\u5B57\u7B26\u4E32\uFF09`}),O=!1;continue}if(V[B]){q.error({name:B,first:V[B],second:A,msg:`${Z} \u540D\u79F0\u91CD\u590D\uFF0C\u65E0\u6CD5\u6839\u636E deps \u552F\u4E00\u5B9A\u4F4D`}),O=!1;continue}V[B]=A}if(!O)return!1;for(let A of $){let B=G(A),L=X(A);if(!Array.isArray(L)){q.error({module:B,item:A,msg:`${Z} \u7684 deps \u5FC5\u987B\u662F\u6570\u7EC4`}),O=!1;continue}for(let C of L){if(typeof C!=="string"){q.error({module:B,dependency:C,item:A,msg:`${Z} \u7684 deps \u5FC5\u987B\u662F\u5B57\u7B26\u4E32\u6570\u7EC4`}),O=!1;continue}if(!V[C])q.error({module:B,dependency:C,msg:`${Z} \u4F9D\u8D56\u672A\u627E\u5230`}),O=!1}}if(!O)return!1;let K=(A)=>{if(W.has(A))return;if(Q.has(A)){q.error({module:A,msg:`${Z} \u5FAA\u73AF\u4F9D\u8D56`}),O=!1;return}let B=V[A];if(!B)return;let L=X(B);Q.add(A);for(let C of L)K(C);Q.delete(A),W.add(A),Y.push(B)};for(let A of $){let B=G(A);K(B)}return O?Y:!1}async function cX($){let J=[],Z=$.filter((X)=>{let Y=X.moduleName;if(typeof Y!=="string"||Y.trim()==="")return!1;if((Object.hasOwn(X,"enable")?X.enable:void 0)===!1)return!1;return!0}),G=PJ(Z,{moduleLabel:"\u94A9\u5B50"});if(G===!1)throw Error("\u94A9\u5B50\u4F9D\u8D56\u5173\u7CFB\u9519\u8BEF");for(let X of G){let Y=X.moduleName,W=Object.hasOwn(X,"deps")?X.deps:void 0,Q=Array.isArray(W)?W.filter((K)=>typeof K==="string"):[],V=Object.hasOwn(X,"handler")?X.handler:void 0;if(typeof V!=="function")throw Error(`Hook '${Y}' handler \u5FC5\u987B\u662F\u51FD\u6570`);let O=V;J.push({name:Y,enable:!0,deps:Q,handler:O})}return J}a();async function pX($,J){let Z=[],G=$.filter((Y)=>{let W=Y.moduleName;if(typeof W!=="string"||W.trim()==="")return!1;if((Object.hasOwn(Y,"enable")?Y.enable:void 0)===!1)return!1;return!0}),X=PJ(G,{moduleLabel:"\u63D2\u4EF6"});if(X===!1)throw Error("\u63D2\u4EF6\u4F9D\u8D56\u5173\u7CFB\u9519\u8BEF");for(let Y of X){let W=Y.moduleName,Q=Object.hasOwn(Y,"deps")?Y.deps:void 0,V=Array.isArray(Q)?Q.filter((A)=>typeof A==="string"):[],O=Object.hasOwn(Y,"handler")?Y.handler:void 0;if(typeof O!=="function")throw Error(`\u63D2\u4EF6 '${W}' handler \u5FC5\u987B\u662F\u51FD\u6570`);let K=O;try{let A=await K(J);J[W]=A,Z.push({name:W,enable:!0,deps:V,handler:K})}catch(A){throw q.error({err:A,plugin:W,msg:"\u63D2\u4EF6\u521D\u59CB\u5316\u5931\u8D25"}),A}}return Z}AJ();a();function uX($,J){let Z=$.headers.get("x-forwarded-for");if(typeof Z==="string"&&Z.trim()){let Q=Z.split(",")[0];if(typeof Q==="string"&&Q.trim())return Q.trim()}let G=$.headers.get("x-real-ip");if(typeof G==="string"&&G.trim())return G.trim();let X=$.headers.get("cf-connecting-ip");if(typeof X==="string"&&X.trim())return X.trim();let Y=$.headers.get("x-client-ip");if(typeof Y==="string"&&Y.trim())return Y.trim();let W=$.headers.get("true-client-ip");if(typeof W==="string"&&W.trim())return W.trim();if(J&&typeof J.requestIP==="function"){let Q=J.requestIP($);if(Q&&typeof Q.address==="string"&&Q.address.trim())return Q.address.trim()}return"unknown"}a();function B$($,J,Z=1,G=null,X=null,Y=null){if($.requestId)q.info({event:"request_blocked",reason:J,reasonCode:Y,code:Z,detail:X,msg:"request blocked"});return Response.json({code:Z,msg:J,data:G,detail:X},{headers:$.corsHeaders})}function cZ($){if($.api&&$.requestId)q.info({event:"request_done",msg:"request done"});if($.response)return $.response;if($.result!==void 0){let J=$.result;if(typeof J==="string")J={code:0,msg:J};else if(J&&typeof J==="object"){if(!("code"in J))J={code:0,...J}}if(J&&typeof J==="object"){let Z=JSON.stringify(J,(G,X)=>typeof X==="bigint"?X.toString():X);return new Response(Z,{headers:{...$.corsHeaders,"Content-Type":"application/json"}})}else return Response.json(J,{headers:$.corsHeaders})}return Response.json({code:1,msg:"\u672A\u751F\u6210\u54CD\u5E94"},{headers:$.corsHeaders})}n0();function nX($,J,Z){return async(G,X)=>{let Y=GX(),Q=new URL(G.url).pathname||"/",V=uX(G,X),O=Date.now(),K={method:G.method,body:{},user:{},req:G,now:O,ip:V,headers:G.headers,route:Q,requestId:Y,corsHeaders:{"X-Request-ID":Y}},A=$.get(Q);if(A)K.api=A;return WX({requestId:Y,method:G.method,route:Q,ip:V,now:O},async()=>{try{for(let B of J)if(await B.handler(Z,K),K.response)return K.response;if(K.api&&G.method!=="OPTIONS"){let B={event:"request",apiName:K.api.name};if(K.body&&Object.keys(K.body).length>0)B.body=K.body;B.msg="request",q.info(B)}if(!K.api){if(G.method!=="OPTIONS")K.response=Response.json({code:1,msg:"\u63A5\u53E3\u4E0D\u5B58\u5728"},{headers:K.corsHeaders})}else if(K.api.handler){let B=await K.api.handler(Z,K);if(B instanceof Response)K.response=B;else K.result=B}return cZ(K)}catch(B){let L=K.api?Q:G.url;return q.error({err:B,path:L,msg:"\u8BF7\u6C42\u9519\u8BEF"}),K.result={code:1,msg:"\u5185\u90E8\u670D\u52A1\u9519\u8BEF"},cZ(K)}})}}q$();a();q$();import{fileURLToPath as hH}from"url";var bH=hH(import.meta.url),P$=qJ(bH);var $5=C$(P$).endsWith("/dist")?P$:d(P$,"dist"),J5=d(P$,"checks"),Z5=d(P$,"plugins"),G5=d(P$,"hooks"),X5=d(P$,"apis"),Y5=d(P$,"tables"),d0=process.cwd(),W5=d(d0,"checks"),H5=d(d0,"plugins"),Q5=d(d0,"hooks"),U5=d(d0,"apis"),z5=d(d0,"tables"),mX=d(d0,"addons");function LJ($,J={}){let Z=J.origin||"*";return{"Access-Control-Allow-Origin":Z==="*"?$.headers.get("origin")||"*":Z,"Access-Control-Allow-Methods":J.methods||"GET, POST, PUT, DELETE, OPTIONS","Access-Control-Allow-Headers":J.allowedHeaders||"Content-Type, Authorization, authorization, token","Access-Control-Expose-Headers":J.exposedHeaders||"Content-Range, X-Content-Range, Authorization, authorization, token","Access-Control-Max-Age":String(J.maxAge||86400),"Access-Control-Allow-Credentials":J.credentials||"true"}}function dX($=void 0){return async(J)=>{let Z=LJ(J,$),G=new URL(J.url),X=d(d0,"public",G.pathname);try{if(J.method==="OPTIONS")return new Response(null,{status:204,headers:Z});let Y=Bun.file(X);if(await Y.exists())return new Response(Y,{headers:{"Content-Type":Y.type||"application/octet-stream",...Z}});else return Response.json({code:1,msg:"\u6587\u4EF6\u672A\u627E\u5230"},{headers:Z})}catch(Y){return q.error({err:Y,msg:"\u9759\u6001\u6587\u4EF6\u5904\u7406\u5931\u8D25"}),Response.json({code:1,msg:"\u6587\u4EF6\u8BFB\u53D6\u5931\u8D25"},{headers:Z})}}}a();n0();var cH=($)=>{let J=$.split("/").map((Y)=>Y.trim()).filter((Y)=>Y.length>0),G=(J[1]||"")==="addon"?4:3,X=J.slice(0,Math.min(G,J.length));if(X.length===0)return"";return`/${X.join("/")}`};async function sX($,J){if(!$.db)throw Error("\u540C\u6B65\u63A5\u53E3\uFF1Actx.db \u672A\u521D\u59CB\u5316");if(!$.cache)throw Error("\u540C\u6B65\u63A5\u53E3\uFF1Actx.cache \u672A\u521D\u59CB\u5316");if(!(await $.db.tableExists("addon_admin_api")).data){q.debug(`${"addon_admin_api"} \u8868\u4E0D\u5B58\u5728`);return}let X=(await $.db.getAll({table:"addon_admin_api",fields:["id","path","parentPath","name","addonName","auth","state"],where:{state$gte:0}})).data.lists||[],Y=ZX(X,(K)=>K.path),W=[],Q=[],V=[],O=new Set;for(let K of J){if(K.type!=="api")continue;let A=K,B=A.path,L=A.name,C=A.addonName;if(typeof B!=="string"||B.trim()==="")continue;if(typeof L!=="string"||L.trim()==="")continue;let T=typeof C==="string"?C:"",w=A.auth,D=w===!1||w===0?0:1,E=cH(B);O.add(B);let N=Y[B];if(N){if(L!==N.name||B!==N.path||T!==N.addonName||E!==N.parentPath||D!==N.auth)Q.push({id:N.id,name:L,path:B,parentPath:E,addonName:T,auth:D})}else W.push({name:L,path:B,parentPath:E,addonName:T,auth:D})}for(let K of X)if(!O.has(K.path))V.push(K.id);if(Q.length>0)try{await $.db.updBatch("addon_admin_api",Q.map((K)=>{return{id:K.id,data:{name:K.name,path:K.path,parentPath:K.parentPath,addonName:K.addonName,auth:K.auth}}}))}catch(K){q.error({err:K,msg:"\u540C\u6B65\u63A5\u53E3\u6279\u91CF\u66F4\u65B0\u5931\u8D25"})}if(W.length>0)try{await $.db.insBatch("addon_admin_api",W.map((K)=>{return{name:K.name,path:K.path,parentPath:K.parentPath,addonName:K.addonName,auth:K.auth}}))}catch(K){q.error({err:K,msg:"\u540C\u6B65\u63A5\u53E3\u6279\u91CF\u65B0\u589E\u5931\u8D25"})}if(V.length>0)try{await $.db.delForceBatch("addon_admin_api",V)}catch(K){q.error({err:K,msg:"\u540C\u6B65\u63A5\u53E3\u6279\u91CF\u5220\u9664\u5931\u8D25"})}}async function oX($){if(!$.cache)throw Error("\u540C\u6B65\u7F13\u5B58\uFF1Actx.cache \u672A\u521D\u59CB\u5316");await $.cache.cacheApis(),await $.cache.cacheMenus(),await $.cache.rebuildRoleApiPermissions()}import{createSign as pH}from"crypto";class g${static md5($,J="hex"){let Z=new Bun.CryptoHasher("md5");return Z.update($),Z.digest(J)}static hmacMd5($,J,Z="hex"){let G=new Bun.CryptoHasher("md5",$);return G.update(J),G.digest(Z)}static sha1($,J="hex"){let Z=new Bun.CryptoHasher("sha1");return Z.update($),Z.digest(J)}static hmacSha1($,J,Z="hex"){let G=new Bun.CryptoHasher("sha1",$);return G.update(J),G.digest(Z)}static sha256($,J="hex"){let Z=new Bun.CryptoHasher("sha256");return Z.update($),Z.digest(J)}static rsaSha256($,J,Z="hex"){let G=pH("RSA-SHA256");return G.update($),G.sign(J,Z)}static hmacSha256($,J,Z="hex"){let G=new Bun.CryptoHasher("sha256",$);return G.update(J),G.digest(Z)}static sha512($,J="hex"){let Z=new Bun.CryptoHasher("sha512");return Z.update($),Z.digest(J)}static hmacSha512($,J,Z="hex"){let G=new Bun.CryptoHasher("sha512",$);return G.update(J),G.digest(Z)}static hash($,J,Z="hex"){let G=new Bun.CryptoHasher($);return G.update(J),G.digest(Z)}static hmac($,J,Z,G="hex"){let X=new Bun.CryptoHasher($,J);return X.update(Z),X.digest(G)}static async hashFile($,J="sha256",Z="hex"){let G=Bun.file($),X=new Bun.CryptoHasher(J),W=G.stream().getReader();try{while(!0){let{done:Q,value:V}=await W.read();if(Q)break;X.update(V)}return X.digest(Z)}finally{W.releaseLock()}}static async hashPassword($,J={}){let Z=Object.assign({},J,{algorithm:"bcrypt"});return await Bun.password.hash($,Z)}static async verifyPassword($,J){return await Bun.password.verify($,J)}static base64Encode($){return Buffer.from($,"utf8").toString("base64")}static base64Decode($){return Buffer.from($,"base64").toString("utf8")}static randomString($){let J=Math.ceil($/2),Z=crypto.getRandomValues(new Uint8Array(J)),G="";for(let X=0;X<Z.length;X++)G+=Z[X].toString(16).padStart(2,"0");return G.slice(0,$)}static fastHash($,J=0){let Z=Bun.hash($,J);return typeof Z==="bigint"?Number(Z):Z}}a();async function lX($,J={}){if(!J.devPassword)return;if(!$.db)throw Error("\u540C\u6B65\u5F00\u53D1\uFF1Actx.db \u672A\u521D\u59CB\u5316");if(!$.cache)throw Error("\u540C\u6B65\u5F00\u53D1\uFF1Actx.cache \u672A\u521D\u59CB\u5316");if(!(await $.db.tableExists("addon_admin_admin")).data){q.debug("addon_admin_admin \u8868\u4E0D\u5B58\u5728");return}if(!(await $.db.tableExists("addon_admin_role")).data){q.debug("addon_admin_role \u8868\u4E0D\u5B58\u5728");return}if(!(await $.db.tableExists("addon_admin_menu")).data){q.debug("addon_admin_menu \u8868\u4E0D\u5B58\u5728");return}if(!(await $.db.tableExists("addon_admin_api")).data){q.debug("addon_admin_api \u8868\u4E0D\u5B58\u5728");return}let Z=await $.db.getAll({table:"addon_admin_menu",fields:["path"],where:{state$gte:0},orderBy:["id#ASC"]}),G=await $.db.getAll({table:"addon_admin_api",fields:["path"],where:{state$gte:0},orderBy:["id#ASC"]}),X=await $.db.getOne({table:"addon_admin_role",where:{code:"dev"}}),Y={code:"dev",name:"\u5F00\u53D1\u8005\u89D2\u8272",description:"\u62E5\u6709\u6240\u6709\u83DC\u5355\u548C\u63A5\u53E3\u6743\u9650\u7684\u5F00\u53D1\u8005\u89D2\u8272",menus:Z.data.lists.map((O)=>O.path).filter((O)=>typeof O==="string"&&O.length>0),apis:G.data.lists.map((O)=>O.path).filter((O)=>typeof O==="string"&&O.length>0),sort:0};if(typeof X.data.id==="number")await $.db.updData({table:"addon_admin_role",where:{code:"dev"},data:{name:Y.name,description:Y.description,menus:Y.menus,apis:Y.apis,sort:Y.sort}});else await $.db.insData({table:"addon_admin_role",data:Y});let W={nickname:"\u5F00\u53D1\u8005",email:J.devEmail||"dev@qq.com",username:"dev",password:await g$.hashPassword(g$.sha256(J.devPassword+"befly")),roleCode:"dev",roleType:"admin"};if(typeof(await $.db.getOne({table:"addon_admin_admin",where:{username:"dev"}})).data.id==="number")await $.db.updData({table:"addon_admin_admin",where:{username:"dev"},data:{nickname:W.nickname,email:W.email,username:W.username,password:W.password,roleCode:W.roleCode,roleType:W.roleType}});else await $.db.insData({table:"addon_admin_admin",data:W});let V=[{code:"user",name:"\u7528\u6237\u89D2\u8272",description:"\u666E\u901A\u7528\u6237\u89D2\u8272",sort:1},{code:"admin",name:"\u7BA1\u7406\u5458\u89D2\u8272",description:"\u7BA1\u7406\u5458\u89D2\u8272",sort:2},{code:"guest",name:"\u8BBF\u5BA2\u89D2\u8272",description:"\u8BBF\u5BA2\u89D2\u8272",sort:3}];for(let O of V)if((await $.db.getOne({table:"addon_admin_role",where:{code:O.code}})).data?.id)await $.db.updData({table:"addon_admin_role",where:{code:O.code},data:{name:O.name,description:O.description,sort:O.sort}});else await $.db.insData({table:"addon_admin_role",data:{code:O.code,name:O.name,description:O.description,sort:O.sort}})}a();hZ();function uH($){let J=$.config?.disableMenus,Z=Array.isArray(J)?J:[],G=[];for(let Y of Z){if(typeof Y!=="string")continue;let W=Y.trim();if(!W)continue;G.push(W)}if(G.length===0)return()=>!1;let X=G.map((Y)=>new Bun.Glob(Y));return(Y)=>{if(typeof Y!=="string")return!1;let W=Y.trim();if(!W)return!1;let Q=[];if(Q.push(W),W.startsWith("/"))Q.push(W.slice(1));else Q.push(`/${W}`);for(let V of X){let O=typeof V==="object"&&V!==null&&"match"in V?V.match:void 0;if(typeof O!=="function")throw Error("\u540C\u6B65\u83DC\u5355\uFF1A\u5F53\u524D Bun \u7248\u672C\u4E0D\u652F\u6301 Bun.Glob.match\uFF0C\u65E0\u6CD5\u6309 disableMenus \u505A glob \u5339\u914D");let K=O;for(let A of Q)if(K.call(V,A))return!0}return!1}}function rX($,J){let Z=[];for(let G of $){if(G===null||typeof G!=="object")continue;let X=typeof G.path==="string"?String(G.path).trim():"";if(X&&J(X))continue;let Y=G.children,W=Array.isArray(Y)&&Y.length>0?rX(Y,J):[],Q={};if(typeof G.name==="string")Q.name=G.name;if(typeof G.path==="string")Q.path=G.path;if(typeof G.sort==="number")Q.sort=G.sort;if(typeof G.parentPath==="string")Q.parentPath=G.parentPath;if(W.length>0)Q.children=W;Z.push(Q)}return Z}function nH($){let J=new Map,Z=[];for(let G of $)Z.push({menu:G,parentPathFromTree:""});while(Z.length>0){let G=Z.pop(),X=G?G.menu:null;if(!X)continue;let Y=typeof X.path==="string"?X.path:"",W=X.children;if(W&&Array.isArray(W)&&W.length>0){let A=typeof Y==="string"?Y:"";for(let B of W)Z.push({menu:B,parentPathFromTree:A})}if(!Y)continue;let Q=typeof X.name==="string"?X.name:"";if(!Q)continue;let V=typeof X.sort==="number"?X.sort:999999,K=typeof X.parentPath==="string"?X.parentPath:typeof G?.parentPathFromTree==="string"?G.parentPathFromTree:EX(Y);J.set(Y,{path:Y,name:Q,sort:V,parentPath:K})}return J}async function iX($,J){if(!$.db)throw Error("\u540C\u6B65\u83DC\u5355\uFF1Actx.db \u672A\u521D\u59CB\u5316");if(!$.cache)throw Error("\u540C\u6B65\u83DC\u5355\uFF1Actx.cache \u672A\u521D\u59CB\u5316");if(!$.config)throw Error("\u540C\u6B65\u83DC\u5355\uFF1Actx.config \u672A\u521D\u59CB\u5316");if(!(await $.db.tableExists("addon_admin_menu")).data){q.debug("addon_admin_menu \u8868\u4E0D\u5B58\u5728");return}let Z=uH($),G=rX(J,Z),X=nH(G),Y=new Set;for(let Q of X.keys())Y.add(Q);let W="addon_admin_menu";await $.db.trans(async(Q)=>{let O=(await Q.getAll({table:W,fields:["id","name","path","parentPath","sort","state"]})).data.lists||[],K=O.filter((E)=>typeof E?.state==="number"&&E.state>=0),A=new Map,B=new Set,L=new Map;for(let E of K){if(typeof E?.path!=="string"||!E.path)continue;if(typeof E?.id!=="number")continue;if(Z(E.path))continue;let N=A.get(E.path);if(!N){A.set(E.path,E);continue}let h=typeof N?.id==="number"?N.id:0,v=E.id;if(v>h){if(A.set(E.path,E),h>0)B.add(h);let p=L.get(E.path)||{keptId:v,removedIds:[]};if(p.keptId=v,h>0)p.removedIds.push(h);L.set(E.path,p)}else{if(v>0)B.add(v);let p=L.get(E.path)||{keptId:h,removedIds:[]};if(p.keptId=h,v>0)p.removedIds.push(v);L.set(E.path,p)}}if(L.size>0){let E=[];for(let N of L.entries()){let h=N[0],v=N[1];if(E.push({path:h,keptId:v.keptId,removedIds:v.removedIds}),E.length>=10)break}q.warn({table:W,duplicatePaths:L.size,duplicateIds:B.size,examples:E,msg:"addon_admin_menu \u68C0\u6D4B\u5230\u91CD\u590D path \u8BB0\u5F55\uFF1A\u5DF2\u4FDD\u7559 id \u6700\u5927\u7684\u4E00\u6761\u5E76\u5220\u9664\u5176\u4F59\u8BB0\u5F55"})}let C=[],T=[];for(let E of X.values()){let N=A.get(E.path);if(N){let h=typeof N.parentPath==="string"?N.parentPath:"";if(N.name!==E.name||N.sort!==E.sort||h!==E.parentPath)C.push({id:N.id,data:{name:E.name,path:E.path,parentPath:E.parentPath,sort:E.sort}})}else T.push({name:E.name,path:E.path,parentPath:E.parentPath,sort:E.sort})}if(C.length>0)await Q.updBatch(W,C);if(T.length>0)await Q.insBatch(W,T);let w=new Set;for(let E of K){if(typeof E?.path!=="string"||!E.path)continue;if(!Y.has(E.path)){if(typeof E?.id==="number")w.add(E.id)}}for(let E of B)if(typeof E==="number"&&E>0)w.add(E);for(let E of O){if(typeof E?.path!=="string"||!E.path)continue;if(!Z(E.path))continue;if(typeof E?.id==="number"&&E.id>0)w.add(E.id)}let D=Array.from(w);if(D.length>0)await Q.delForceBatch(W,D)})}class G0{static apisAll(){return"apis:all"}static menusAll(){return"menus:all"}static roleInfo($){return`role:info:${$}`}static roleApis($){return`role:apis:${$}`}static tableColumns($){return`table:columns:${$}`}}var h$=null;function b$($){let J=Error(`\u672A\u77E5\u6570\u636E\u5E93\u65B9\u8A00: ${String($)}`);if($!=="mysql"&&$!=="postgresql"&&$!=="sqlite")throw J;if(!h$)h$=new Map,h$.set("mysql",new CJ),h$.set("postgresql",new tX),h$.set("sqlite",new aX);let Z=h$.get($);if(!Z)throw J;return Z}function SJ($){if($.dialect==="mysql")return{columns:{sql:"SELECT COLUMN_NAME, DATA_TYPE, CHARACTER_MAXIMUM_LENGTH, IS_NULLABLE, COLUMN_DEFAULT, COLUMN_COMMENT, COLUMN_TYPE FROM information_schema.COLUMNS WHERE TABLE_SCHEMA = ? AND TABLE_NAME = ? ORDER BY ORDINAL_POSITION",params:[$.dbName,$.table]}};if($.dialect==="postgresql"){let G=$.schema&&$.schema.trim()!==""?$.schema:"public",X={sql:"SELECT column_name, data_type, character_maximum_length, is_nullable, column_default FROM information_schema.columns WHERE table_schema = ? AND table_name = ? ORDER BY ordinal_position",params:[G,$.table]},Y={sql:"SELECT a.attname AS column_name, col_description(c.oid, a.attnum) AS column_comment FROM pg_class c JOIN pg_attribute a ON a.attrelid = c.oid JOIN pg_namespace n ON n.oid = c.relnamespace WHERE c.relkind = 'r' AND n.nspname = ? AND c.relname = ? AND a.attnum > 0",params:[G,$.table]};return{columns:X,comments:Y}}return{columns:b$("sqlite").getTableColumnsQuery($.table)}}function pZ($){if($.dialect==="mysql")return{sql:"SELECT INDEX_NAME, COLUMN_NAME FROM information_schema.STATISTICS WHERE TABLE_SCHEMA = ? AND TABLE_NAME = ? AND INDEX_NAME != 'PRIMARY' ORDER BY INDEX_NAME",params:[$.dbName,$.table]};if($.dialect==="postgresql")return{sql:"SELECT indexname, indexdef FROM pg_indexes WHERE schemaname = ? AND tablename = ?",params:[$.schema&&$.schema.trim()!==""?$.schema:"public",$.table]};throw Error(`getSyncTableIndexesQuery \u4E0D\u652F\u6301\u65B9\u8A00: ${String($.dialect)}`)}class CJ{name="mysql";supportsSchema=!0;quoteIdent($){if(typeof $!=="string")throw Error(`quoteIdent \u9700\u8981\u5B57\u7B26\u4E32\u7C7B\u578B\u6807\u8BC6\u7B26 (identifier: ${String($)})`);let J=$.trim();if(!/^[a-zA-Z_][a-zA-Z0-9_]*$/.test(J))throw Error(`\u65E0\u6548\u7684 SQL \u6807\u8BC6\u7B26: ${J}`);return`\`${J}\``}getTableColumnsQuery($,J){return{sql:`SHOW COLUMNS FROM ${this.quoteIdent($)}`,params:[]}}getTableColumnsFromResult($){let J=[];for(let Z of $){let G=Z.Field;if(typeof G==="string"&&G.length>0)J.push(G)}return J}tableExistsQuery($,J){if(typeof J==="string"&&J.trim()!=="")return{sql:"SELECT COUNT(*) as count FROM information_schema.TABLES WHERE TABLE_SCHEMA = ? AND TABLE_NAME = ?",params:[J,$]};return{sql:"SELECT COUNT(*) as count FROM information_schema.TABLES WHERE TABLE_SCHEMA = DATABASE() AND TABLE_NAME = ?",params:[$]}}}class tX{name="postgresql";supportsSchema=!0;quoteIdent($){if(typeof $!=="string")throw Error(`quoteIdent \u9700\u8981\u5B57\u7B26\u4E32\u7C7B\u578B\u6807\u8BC6\u7B26 (identifier: ${String($)})`);let J=$.trim();if(!/^[a-zA-Z_][a-zA-Z0-9_]*$/.test(J))throw Error(`\u65E0\u6548\u7684 SQL \u6807\u8BC6\u7B26: ${J}`);return`"${J}"`}getTableColumnsQuery($,J){if(typeof J==="string"&&J.trim()!=="")return{sql:"SELECT column_name FROM information_schema.columns WHERE table_schema = ? AND table_name = ? ORDER BY ordinal_position",params:[J,$]};return{sql:"SELECT column_name FROM information_schema.columns WHERE table_schema = current_schema() AND table_name = ? ORDER BY ordinal_position",params:[$]}}getTableColumnsFromResult($){let J=[];for(let Z of $){let G=Z.column_name;if(typeof G==="string"&&G.length>0)J.push(G)}return J}tableExistsQuery($,J){if(typeof J==="string"&&J.trim()!=="")return{sql:"SELECT COUNT(*)::int as count FROM information_schema.tables WHERE table_schema = ? AND table_name = ?",params:[J,$]};return{sql:"SELECT COUNT(*)::int as count FROM information_schema.tables WHERE table_schema = current_schema() AND table_name = ?",params:[$]}}}class aX{name="sqlite";supportsSchema=!1;quoteIdent($){if(typeof $!=="string")throw Error(`quoteIdent \u9700\u8981\u5B57\u7B26\u4E32\u7C7B\u578B\u6807\u8BC6\u7B26 (identifier: ${String($)})`);let J=$.trim();if(!/^[a-zA-Z_][a-zA-Z0-9_]*$/.test(J))throw Error(`\u65E0\u6548\u7684 SQL \u6807\u8BC6\u7B26: ${J}`);return`"${J}"`}getTableColumnsQuery($,J){return{sql:`PRAGMA table_info(${this.quoteIdent($)})`,params:[]}}getTableColumnsFromResult($){let J=[];for(let Z of $){let G=Z.name;if(typeof G==="string"&&G.length>0)J.push(G)}return J}tableExistsQuery($,J){return{sql:"SELECT COUNT(*) as count FROM sqlite_master WHERE type = 'table' AND name = ?",params:[$]}}}a();function H$($){return{name:$.name,type:$.type,detail:$.detail??"",min:$.min??null,max:$.max??null,default:$.default??null,index:$.index??!1,unique:$.unique??!1,nullable:$.nullable??!1,unsigned:$.unsigned??!1,regexp:$.regexp??null}}n0();function mH($,J,Z=""){return{dbDialect:$,db:J,dbName:Z}}function nZ($,J,Z){let G=String(Z?.message||Z),X=Error(`\u540C\u6B65\u8868\uFF1A\u8BFB\u53D6\u5143\u4FE1\u606F\u5931\u8D25\uFF0C\u64CD\u4F5C=${$}\uFF0C\u8868=${J}\uFF0C\u9519\u8BEF=${G}`);if(Z?.sqlInfo)X.sqlInfo=Z.sqlInfo;return X}var TJ=async($,J)=>{try{let Z=[];if(!Array.isArray(J))throw Error("\u540C\u6B65\u8868\uFF1A\u8BF7\u4F20\u5165\u591A\u4E2A\u8868\u5B9A\u4E49\u7EC4\u6210\u7684\u6570\u7EC4");if(!$?.db)throw Error("\u540C\u6B65\u8868\uFF1Actx.db \u672A\u521D\u59CB\u5316");if(!$.redis)throw Error("\u540C\u6B65\u8868\uFF1Actx.redis \u672A\u521D\u59CB\u5316");if(!$.config)throw Error("\u540C\u6B65\u8868\uFF1Actx.config \u672A\u521D\u59CB\u5316");if(!$.config.db?.dialect)throw Error("\u540C\u6B65\u8868\uFF1Actx.config.db.dialect \u7F3A\u5931");let G=$.config.db.dialect;await dH(G,$.db);let X=$.config.db?.database||"",Y={dbDialect:G,db:$.db,dbName:X};for(let W of J){if(!W||W.type!=="table")continue;let Q=W.source==="addon"?`addon_${f(W.addonName)}_${f(W.fileName)}`:f(W.fileName),V=W.content;for(let K of Object.values(V))X1(K);if(await U1(Y,Q))await lH(Y,Q,V);else await O1(Y,Q,V);Z.push(Q)}if(Z.length>0){let W=Z.map((Q)=>G0.tableColumns(Q));await $.redis.delBatch(W)}}catch(Z){throw q.error({err:Z,msg:"\u6570\u636E\u5E93\u540C\u6B65\u5931\u8D25"}),Z}},w$={MYSQL_MIN_MAJOR:8,POSTGRES_MIN_MAJOR:17,SQLITE_MIN_VERSION:"3.50.0",SQLITE_MIN_VERSION_NUM:35000},$1={length:"\u957F\u5EA6",datatype:"\u7C7B\u578B",comment:"\u6CE8\u91CA",default:"\u9ED8\u8BA4\u503C",nullable:"\u53EF\u7A7A\u7EA6\u675F",unique:"\u552F\u4E00\u7EA6\u675F"},J1={ENGINE:"InnoDB",CHARSET:"utf8mb4",COLLATE:"utf8mb4_0900_ai_ci"},WJ=[{name:"id",comment:"\u4E3B\u952EID",needsIndex:!1,mysqlDdl:"BIGINT UNSIGNED PRIMARY KEY AUTO_INCREMENT",pgDdl:"BIGINT GENERATED BY DEFAULT AS IDENTITY PRIMARY KEY",sqliteDdl:"INTEGER PRIMARY KEY"},{name:"created_at",comment:"\u521B\u5EFA\u65F6\u95F4",needsIndex:!0,mysqlDdl:"BIGINT UNSIGNED NOT NULL DEFAULT 0",pgDdl:"BIGINT NOT NULL DEFAULT 0",sqliteDdl:"INTEGER NOT NULL DEFAULT 0"},{name:"updated_at",comment:"\u66F4\u65B0\u65F6\u95F4",needsIndex:!0,mysqlDdl:"BIGINT UNSIGNED NOT NULL DEFAULT 0",pgDdl:"BIGINT NOT NULL DEFAULT 0",sqliteDdl:"INTEGER NOT NULL DEFAULT 0"},{name:"deleted_at",comment:"\u5220\u9664\u65F6\u95F4",needsIndex:!1,mysqlDdl:"BIGINT UNSIGNED NOT NULL DEFAULT 0",pgDdl:"BIGINT NOT NULL DEFAULT 0",sqliteDdl:"INTEGER NOT NULL DEFAULT 0"},{name:"state",comment:"\u72B6\u6001\u5B57\u6BB5",needsIndex:!0,mysqlDdl:"BIGINT UNSIGNED NOT NULL DEFAULT 1",pgDdl:"BIGINT NOT NULL DEFAULT 1",sqliteDdl:"INTEGER NOT NULL DEFAULT 1"}],mZ=WJ.filter(($)=>$.needsIndex).map(($)=>$.name),Z1={};for(let $ of WJ)Z1[$.name]=$;var G1={DB_VERSION_REQUIREMENTS:w$,CHANGE_TYPE_LABELS:$1,MYSQL_TABLE_CONFIG:J1,SYSTEM_INDEX_FIELDS:mZ,getTypeMapping:NJ,quoteIdentifier:X0,escapeComment:vJ,normalizeFieldDefinitionInPlace:X1,isStringOrArrayType:YJ,getSqlType:dZ,resolveDefaultValue:HJ,generateDefaultSql:DJ,buildIndexSQL:EJ,buildSystemColumnDefs:W1,buildBusinessColumnDefs:H1,generateDDLClause:uZ,isCompatibleTypeChange:Q1,compareFieldDefinition:V1,tableExistsRuntime:U1,getTableColumnsRuntime:z1,getTableIndexesRuntime:sZ,createRuntime:mH};TJ.TestKit=G1;Object.defineProperty(TJ,"TestKit",{value:G1,writable:!1,enumerable:!0,configurable:!1});function NJ($){return{number:$==="sqlite"?"INTEGER":$==="postgresql"?"BIGINT":"BIGINT",string:$==="sqlite"?"TEXT":$==="postgresql"?"character varying":"VARCHAR",text:$==="mysql"?"MEDIUMTEXT":"TEXT",array_string:$==="sqlite"?"TEXT":$==="postgresql"?"character varying":"VARCHAR",array_text:$==="mysql"?"MEDIUMTEXT":"TEXT",array_number_string:$==="sqlite"?"TEXT":$==="postgresql"?"character varying":"VARCHAR",array_number_text:$==="mysql"?"MEDIUMTEXT":"TEXT"}}function X0($,J){return b$($).quoteIdent(J)}function vJ($){return String($).replace(/"/g,"\\\"")}function wJ($){if($===null)return null;if(typeof $==="string"||typeof $==="number"||typeof $==="boolean")return $;if(Array.isArray($)){let J=[];for(let Z of $)J.push(wJ(Z));return J}return String($)}function X1($){let J=H$($);$.detail=J.detail,$.min=J.min,$.max=J.max,$.default=J.default,$.index=J.index,$.unique=J.unique,$.nullable=J.nullable,$.unsigned=J.unsigned,$.regexp=J.regexp}function YJ($){return $==="string"||$==="array_string"||$==="array_number_string"}function dZ($,J,Z,G=!1){let X=NJ($);if(YJ(J))return`${X[J]}(${Z})`;let Y=X[J]||"TEXT";if($==="mysql"&&J==="number"&&G)return`${Y} UNSIGNED`;return Y}function HJ($,J){if($!==null&&$!=="null")return $;switch(J){case"number":return 0;case"string":return"";case"array_string":case"array_number_string":return"[]";case"text":case"array_text":case"array_number_text":return"null";default:return $}}function DJ($,J){if(J==="text"||J==="array_text"||$==="null")return"";if(J==="number"||J==="string"||J==="array_string"||J==="array_number_string")if(typeof $==="number"&&!Number.isNaN($))return` DEFAULT ${$}`;else return` DEFAULT '${String($).replace(/'/g,"''")}'`;return""}function EJ($,J,Z,G,X){let Y=X0($,J),W=X0($,Z),Q=X0($,G);if($==="mysql"){let V=[];if(X==="create")V.push(`ADD INDEX ${W} (${Q})`);else V.push(`DROP INDEX ${W}`);return`ALTER TABLE ${Y} ALGORITHM=INPLACE, LOCK=NONE, ${V.join(", ")}`}if($==="postgresql"){if(X==="create")return`CREATE INDEX CONCURRENTLY IF NOT EXISTS ${W} ON ${Y}(${Q})`;return`DROP INDEX CONCURRENTLY IF EXISTS ${W}`}if(X==="create")return`CREATE INDEX IF NOT EXISTS ${W} ON ${Y}(${Q})`;return`DROP INDEX IF EXISTS ${W}`}function Y1($,J){let Z=Z1[J];if(!Z)return null;let G=X0($,Z.name);if($==="mysql")return`${G} ${Z.mysqlDdl} COMMENT "${vJ(Z.comment)}"`;if($==="postgresql")return`${G} ${Z.pgDdl}`;return`${G} ${Z.sqliteDdl}`}function W1($){let J=[];for(let Z of WJ){let G=Y1($,Z.name);if(G)J.push(G)}return J}function H1($,J){let Z=[];for(let[G,X]of Object.entries(J)){let Y=H$(X),W=f(G),Q=X0($,W),V=dZ($,Y.type,Y.max,Y.unsigned),O=HJ(Y.default,Y.type),K=DJ(O,Y.type),A=Y.unique?" UNIQUE":"",B=Y.nullable?" NULL":" NOT NULL";if($==="mysql")Z.push(`${Q} ${V}${A}${B}${K} COMMENT "${vJ(Y.name)}"`);else Z.push(`${Q} ${V}${A}${B}${K}`)}return Z}function uZ($,J,Z,G=!1){let X=f(J),Y=X0($,X),W=H$(Z),Q=dZ($,W.type,W.max,W.unsigned),V=HJ(W.default,W.type),O=DJ(V,W.type),K=W.unique?" UNIQUE":"",A=W.nullable?" NULL":" NOT NULL";if($==="mysql")return`${G?"ADD COLUMN":"MODIFY COLUMN"} ${Y} ${Q}${K}${A}${O} COMMENT "${vJ(W.name)}"`;if($==="postgresql"){if(G)return`ADD COLUMN IF NOT EXISTS ${Y} ${Q}${K}${A}${O}`;return`ALTER COLUMN ${Y} TYPE ${Q}`}if(G)return`ADD COLUMN IF NOT EXISTS ${Y} ${Q}${K}${A}${O}`;return""}async function eX($,J){try{return await $.unsafe(J),!0}catch(Z){if(J.includes("ALGORITHM=INSTANT")){let G=J.replace(/ALGORITHM=INSTANT/g,"ALGORITHM=INPLACE");try{return await $.unsafe(G),!0}catch{let X=J;return X=X.replace(/\bALGORITHM\s*=\s*(INPLACE|INSTANT)\b\s*,?\s*/g,"").replace(/\bLOCK\s*=\s*(NONE|SHARED|EXCLUSIVE)\b\s*,?\s*/g,""),X=X.replace(/,\s*,/g,", ").replace(/,\s*$/g,"").replace(/\s{2,}/g," ").trim(),await $.unsafe(X),!0}}else throw Z}}function Q1($,J){let Z=String($||"").toLowerCase(),G=String(J||"").toLowerCase();if(Z===G)return!1;let X=Z.replace(/\s*unsigned/gi,"").replace(/\([^)]*\)/g,"").trim(),Y=G.replace(/\s*unsigned/gi,"").replace(/\([^)]*\)/g,"").trim(),W=["tinyint","smallint","mediumint","int","integer","bigint"],Q=W.indexOf(X),V=W.indexOf(Y);if(Q!==-1&&V!==-1&&V>Q)return!0;if(X==="varchar"&&(Y==="text"||Y==="mediumtext"||Y==="longtext"))return!0;if(X==="character varying"&&Y==="text")return!0;return!1}async function U1($,J){try{let Z=$.dbDialect==="mysql"?$.dbName:$.dbDialect==="postgresql"?"public":void 0,G=b$($.dbDialect).tableExistsQuery(J,Z);return((await $.db.unsafe(G.sql,G.params)).data?.[0]?.count||0)>0}catch(Z){throw nZ("\u68C0\u67E5\u8868\u662F\u5426\u5B58\u5728",J,Z)}}async function z1($,J){let Z={};try{if($.dbDialect==="mysql"){let G=SJ({dialect:"mysql",table:J,dbName:$.dbName}),X=await $.db.unsafe(G.columns.sql,G.columns.params);for(let Y of X.data){let W=wJ(Y.COLUMN_DEFAULT);Z[Y.COLUMN_NAME]={type:String(Y.DATA_TYPE??""),columnType:String(Y.COLUMN_TYPE??""),length:Y.CHARACTER_MAXIMUM_LENGTH,max:Y.CHARACTER_MAXIMUM_LENGTH,nullable:Y.IS_NULLABLE==="YES",defaultValue:W,comment:Y.COLUMN_COMMENT===null?null:String(Y.COLUMN_COMMENT)}}}else if($.dbDialect==="postgresql"){let G=SJ({dialect:"postgresql",table:J,dbName:$.dbName}),X=await $.db.unsafe(G.columns.sql,G.columns.params),Y=G.comments?(await $.db.unsafe(G.comments.sql,G.comments.params)).data:[],W={};for(let Q of Y)W[Q.column_name]=Q.column_comment;for(let Q of X.data)Z[Q.column_name]={type:String(Q.data_type??""),columnType:String(Q.data_type??""),length:Q.character_maximum_length,max:Q.character_maximum_length,nullable:String(Q.is_nullable).toUpperCase()==="YES",defaultValue:wJ(Q.column_default),comment:W[Q.column_name]??null}}else if($.dbDialect==="sqlite"){let G=SJ({dialect:"sqlite",table:J,dbName:$.dbName}),X=await $.db.unsafe(G.columns.sql,G.columns.params);for(let Y of X.data){let W=String(Y.type||"").toUpperCase(),Q=null,V=/^(\w+)\s*\((\d+)\)/.exec(W);if(V&&V[1]&&V[2])W=V[1],Q=Number(V[2]);Z[Y.name]={type:String(W).toLowerCase(),columnType:String(W).toLowerCase(),length:Q,max:Q,nullable:Y.notnull===0,defaultValue:wJ(Y.dflt_value),comment:null}}}return Z}catch(G){throw nZ("\u8BFB\u53D6\u5217\u4FE1\u606F",J,G)}}async function sZ($,J){let Z={};try{if($.dbDialect==="mysql"){let G=pZ({dialect:"mysql",table:J,dbName:$.dbName}),X=await $.db.unsafe(G.sql,G.params);for(let Y of X.data){let W=Y.INDEX_NAME,Q=Z[W];if(Array.isArray(Q))Q.push(Y.COLUMN_NAME);else Z[W]=[Y.COLUMN_NAME]}}else if($.dbDialect==="postgresql"){let G=pZ({dialect:"postgresql",table:J,dbName:$.dbName}),X=await $.db.unsafe(G.sql,G.params);for(let Y of X.data){let W=/\(([^)]+)\)/.exec(Y.indexdef);if(W){let Q=W[1],V=typeof Q==="string"?Q.replace(/"/g,"").trim():"";Z[Y.indexname]=[V]}}}else if($.dbDialect==="sqlite"){let G=X0("sqlite",J),X=await $.db.unsafe(`PRAGMA index_list(${G})`);for(let Y of X.data){let W=X0("sqlite",Y.name),V=(await $.db.unsafe(`PRAGMA index_info(${W})`)).data.map((O)=>O.name);if(V.length===1)Z[Y.name]=V}}return Z}catch(G){throw nZ("\u8BFB\u53D6\u7D22\u5F15\u4FE1\u606F",J,G)}}async function dH($,J){if($==="mysql"){let Z=await J.unsafe("SELECT VERSION() AS version");if(!Z.data||Z.data.length===0||!Z.data[0]?.version)throw Error("\u540C\u6B65\u8868\uFF1A\u65E0\u6CD5\u83B7\u53D6 MySQL \u7248\u672C\u4FE1\u606F");let G=Z.data[0].version,X=String(G).split(".")[0]||"0",Y=parseInt(X,10);if(!Number.isFinite(Y)||Y<w$.MYSQL_MIN_MAJOR)throw Error(`\u540C\u6B65\u8868\uFF1A\u4EC5\u652F\u6301 MySQL ${w$.MYSQL_MIN_MAJOR}.0+\uFF08\u5F53\u524D\u7248\u672C\uFF1A${G}\uFF09`);return}if($==="postgresql"){let Z=await J.unsafe("SELECT version() AS version");if(!Z.data||Z.data.length===0||!Z.data[0]?.version)throw Error("\u540C\u6B65\u8868\uFF1A\u65E0\u6CD5\u83B7\u53D6 PostgreSQL \u7248\u672C\u4FE1\u606F");let G=Z.data[0].version,X=/PostgreSQL\s+(\d+)/i.exec(G),Y=X?X[1]:void 0,W=typeof Y==="string"?parseInt(Y,10):NaN;if(!Number.isFinite(W)||W<w$.POSTGRES_MIN_MAJOR)throw Error(`\u540C\u6B65\u8868\uFF1A\u8981\u6C42 PostgreSQL >= ${w$.POSTGRES_MIN_MAJOR}\uFF08\u5F53\u524D\uFF1A${G}\uFF09`);return}if($==="sqlite"){let Z=await J.unsafe("SELECT sqlite_version() AS version");if(!Z.data||Z.data.length===0||!Z.data[0]?.version)throw Error("\u540C\u6B65\u8868\uFF1A\u65E0\u6CD5\u83B7\u53D6 SQLite \u7248\u672C\u4FE1\u606F");let G=Z.data[0].version,X=String(G).split(".").map((O)=>parseInt(O,10)||0),Y=X[0]??0,W=X[1]??0,Q=X[2]??0,V=Y*1e4+W*100+Q;if(!Number.isFinite(V)||V<w$.SQLITE_MIN_VERSION_NUM)throw Error(`\u540C\u6B65\u8868\uFF1A\u8981\u6C42 SQLite >= ${w$.SQLITE_MIN_VERSION}\uFF08\u5F53\u524D\uFF1A${G}\uFF09`);return}}function V1($,J,Z){let G=[],X=H$(Z);if($!=="sqlite"&&YJ(X.type)){let B=X.max;if(B!==null&&J.max!==B)G.push({type:"length",current:J.max,expected:B})}if($!=="sqlite"){let B=J.comment===null||J.comment===void 0?"":String(J.comment);if(B!==X.name)G.push({type:"comment",current:B,expected:X.name})}let W=NJ($)[X.type];if(typeof W!=="string")throw Error(`\u540C\u6B65\u8868\uFF1A\u672A\u77E5\u5B57\u6BB5\u7C7B\u578B\u6620\u5C04\uFF08\u65B9\u8A00=${$}\uFF0C\u7C7B\u578B=${String(X.type)}\uFF09`);let Q=W.toLowerCase(),V="";if(typeof J.type==="string"&&J.type.trim()!=="")V=J.type;else if(typeof J.columnType==="string"&&J.columnType.trim()!=="")V=J.columnType;else V=String(J.type??"");let O=V.toLowerCase().replace(/\s*unsigned/gi,"").replace(/\([^)]*\)/g,"").trim();if(O!==Q)G.push({type:"datatype",current:O,expected:Q});let K=X.nullable;if(J.nullable!==K)G.push({type:"nullable",current:J.nullable,expected:K});let A=HJ(X.default,X.type);if(String(J.defaultValue)!==String(A))G.push({type:"default",current:J.defaultValue,expected:A});return G}async function sH($,J,Z){if($.dbDialect!=="sqlite")throw Error(`\u540C\u6B65\u8868\uFF1ASQLite \u91CD\u5EFA\u8868\u4EC5\u652F\u6301 sqlite \u65B9\u8A00\uFF08\u5F53\u524D\uFF1A${String($.dbDialect)}\uFF09`);let G=X0("sqlite",J),Y=(await $.db.unsafe(`PRAGMA table_info(${G})`)).data.map((A)=>A.name),Q=["id","created_at","updated_at","deleted_at","state",...Object.keys(Z).map((A)=>f(A))],V=`${J}__tmp__${Date.now()}`;await O1($,V,Z);let O=Q.filter((A)=>Y.includes(A));if(O.length>0){let A=O.map((L)=>X0("sqlite",L)).join(", "),B=X0("sqlite",V);await $.db.unsafe(`INSERT INTO ${B} (${A}) SELECT ${A} FROM ${G}`)}await $.db.unsafe(`DROP TABLE ${G}`);let K=X0("sqlite",V);await $.db.unsafe(`ALTER TABLE ${K} RENAME TO ${G}`)}async function oH($,J,Z,G){if(!G||!G.changed)return;if($.dbDialect==="sqlite")if(G.modifyClauses.length>0||G.defaultClauses.length>0)await sH($,J,Z);else for(let X of G.addClauses){let Y=`ALTER TABLE ${X0($.dbDialect,J)} ${X}`;await $.db.unsafe(Y)}else{let X=[...G.addClauses,...G.modifyClauses];if(X.length>0){let Y=X0($.dbDialect,J),W=$.dbDialect==="mysql"?`ALTER TABLE ${Y} ALGORITHM=INSTANT, LOCK=NONE, ${X.join(", ")}`:`ALTER TABLE ${Y} ${X.join(", ")}`;if($.dbDialect==="mysql")await eX($.db,W);else await $.db.unsafe(W)}}if(G.defaultClauses.length>0)if($.dbDialect==="sqlite")q.warn(`SQLite \u4E0D\u652F\u6301\u4FEE\u6539\u9ED8\u8BA4\u503C\uFF0C\u8868 ${J} \u7684\u9ED8\u8BA4\u503C\u53D8\u66F4\u5DF2\u8DF3\u8FC7`);else{let X=X0($.dbDialect,J),Y=$.dbDialect==="mysql"?`ALTER TABLE ${X} ALGORITHM=INSTANT, LOCK=NONE, ${G.defaultClauses.join(", ")}`:`ALTER TABLE ${X} ${G.defaultClauses.join(", ")}`;if($.dbDialect==="mysql")await eX($.db,Y);else await $.db.unsafe(Y)}for(let X of G.indexActions){let Y=EJ($.dbDialect,J,X.indexName,X.fieldName,X.action);try{if(await $.db.unsafe(Y),X.action==="create")q.debug(`[\u7D22\u5F15\u53D8\u5316] \u65B0\u5EFA\u7D22\u5F15 ${J}.${X.indexName} (${X.fieldName})`);else q.debug(`[\u7D22\u5F15\u53D8\u5316] \u5220\u9664\u7D22\u5F15 ${J}.${X.indexName} (${X.fieldName})`)}catch(W){throw q.error({err:W,table:J,index:X.indexName,field:X.fieldName,msg:`${X.action==="create"?"\u521B\u5EFA":"\u5220\u9664"}\u7D22\u5F15\u5931\u8D25`}),W}}if($.dbDialect==="postgresql"&&G.commentActions&&G.commentActions.length>0)for(let X of G.commentActions)await $.db.unsafe(X)}async function O1($,J,Z,G=mZ){let Y=[...W1($.dbDialect),...H1($.dbDialect,Z)].join(`,
|
|
7
|
+
`),W=X0($.dbDialect,J),{ENGINE:Q,CHARSET:V,COLLATE:O}=J1,K=$.dbDialect==="mysql"?`CREATE TABLE ${W} (
|
|
8
8
|
${Y}
|
|
9
|
-
) ENGINE=${Q} DEFAULT CHARSET=${
|
|
9
|
+
) ENGINE=${Q} DEFAULT CHARSET=${V} COLLATE=${O}`:`CREATE TABLE ${W} (
|
|
10
10
|
${Y}
|
|
11
|
-
)`;if(await $.db.unsafe(
|
|
12
|
-
`);throw Error(u0)}q.debug(`[\u517C\u5BB9\u7C7B\u578B\u53D8\u66F4] ${J}.${
|
|
13
|
-
`&&$[Y]!=="\r";Y++)
|
|
14
|
-
`||$==="\r"}function _1($,J){let Z=J;for(;J<$.length;J++)if($[J]=="?"||$[J]==" "){let X=$.substr(Z,J-Z);if(J>5&&X==="xml")return Y0("InvalidXml","XML declaration allowed only at the start of the document.",s0($,J));else if($[J]=="?"&&$[J+1]==">"){J++;break}else continue}return J}function A1($,J){if($.length>J+5&&$[J+1]==="-"&&$[J+2]==="-"){for(J+=3;J<$.length;J++)if($[J]==="-"&&$[J+1]==="-"&&$[J+2]===">"){J+=2;break}}else if($.length>J+8&&$[J+1]==="D"&&$[J+2]==="O"&&$[J+3]==="C"&&$[J+4]==="T"&&$[J+5]==="Y"&&$[J+6]==="P"&&$[J+7]==="E"){let Z=1;for(J+=8;J<$.length;J++)if($[J]==="<")Z++;else if($[J]===">"){if(Z--,Z===0)break}}else if($.length>J+9&&$[J+1]==="["&&$[J+2]==="C"&&$[J+3]==="D"&&$[J+4]==="A"&&$[J+5]==="T"&&$[J+6]==="A"&&$[J+7]==="["){for(J+=8;J<$.length;J++)if($[J]==="]"&&$[J+1]==="]"&&$[J+2]===">"){J+=2;break}}return J}var mH='"',dH="'";function sH($,J){let Z="",X="",G=!1;for(;J<$.length;J++){if($[J]===mH||$[J]===dH)if(X==="")X=$[J];else if(X!==$[J]);else X="";else if($[J]===">"){if(X===""){G=!0;break}}Z+=$[J]}if(X!=="")return!1;return{value:Z,index:J,tagClosed:G}}var oH=new RegExp(`(\\s*)([^\\s=]+)(\\s*=)?(\\s*(['"])(([\\s\\S])*?)\\5)?`,"g");function F1($,J){let Z=vJ($,oH),X={};for(let G=0;G<Z.length;G++){if(Z[G][1].length===0)return Y0("InvalidAttr","Attribute '"+Z[G][2]+"' has no space in starting.",WJ(Z[G]));else if(Z[G][3]!==void 0&&Z[G][4]===void 0)return Y0("InvalidAttr","Attribute '"+Z[G][2]+"' is without value.",WJ(Z[G]));else if(Z[G][3]===void 0&&!J.allowBooleanAttributes)return Y0("InvalidAttr","boolean attribute '"+Z[G][2]+"' is not allowed.",WJ(Z[G]));let Y=Z[G][2];if(!iH(Y))return Y0("InvalidAttr","Attribute '"+Y+"' is an invalid name.",WJ(Z[G]));if(!X.hasOwnProperty(Y))X[Y]=1;else return Y0("InvalidAttr","Attribute '"+Y+"' is repeated.",WJ(Z[G]))}return!0}function lH($,J){let Z=/\d/;if($[J]==="x")J++,Z=/[\da-fA-F]/;for(;J<$.length;J++){if($[J]===";")return J;if(!$[J].match(Z))break}return-1}function rH($,J){if(J++,$[J]===";")return-1;if($[J]==="#")return J++,lH($,J);let Z=0;for(;J<$.length;J++,Z++){if($[J].match(/\w/)&&Z<20)continue;if($[J]===";")break;return-1}return J}function Y0($,J,Z){return{err:{code:$,msg:J,line:Z.line||Z,col:Z.col}}}function iH($){return c$($)}function tH($){return c$($)}function s0($,J){let Z=$.substring(0,J).split(/\r?\n/);return{line:Z.length,col:Z[Z.length-1].length+1}}function WJ($){return $.startIndex+$[1].length}var aH={preserveOrder:!1,attributeNamePrefix:"@_",attributesGroupName:!1,textNodeName:"#text",ignoreAttributes:!0,removeNSPrefix:!1,allowBooleanAttributes:!1,parseTagValue:!0,parseAttributeValue:!1,trimValues:!0,cdataPropName:!1,numberParseOptions:{hex:!0,leadingZeros:!0,eNotation:!0},tagValueProcessor:function($,J){return J},attributeValueProcessor:function($,J){return J},stopNodes:[],alwaysCreateTextNode:!1,isArray:()=>!1,commentPropName:!1,unpairedTags:[],processEntities:!0,htmlEntities:!1,ignoreDeclaration:!1,ignorePiTags:!1,transformTagName:!1,transformAttributeName:!1,updateTag:function($,J,Z){return $},captureMetaData:!1},I1=function($){return Object.assign({},aH,$)};var DJ;if(typeof Symbol!=="function")DJ="@@xmlMetadata";else DJ=Symbol("XML Node Metadata");class i0{constructor($){this.tagname=$,this.child=[],this[":@"]={}}add($,J){if($==="__proto__")$="#__proto__";this.child.push({[$]:J})}addChild($,J){if($.tagname==="__proto__")$.tagname="#__proto__";if($[":@"]&&Object.keys($[":@"]).length>0)this.child.push({[$.tagname]:$.child,[":@"]:$[":@"]});else this.child.push({[$.tagname]:$.child});if(J!==void 0)this.child[this.child.length-1][DJ]={startIndex:J}}static getMetaDataSymbol(){return DJ}}class kJ{constructor($){this.suppressValidationErr=!$}readDocType($,J){let Z={};if($[J+3]==="O"&&$[J+4]==="C"&&$[J+5]==="T"&&$[J+6]==="Y"&&$[J+7]==="P"&&$[J+8]==="E"){J=J+9;let X=1,G=!1,Y=!1,W="";for(;J<$.length;J++)if($[J]==="<"&&!Y){if(G&&w$($,"!ENTITY",J)){J+=7;let Q,z;if([Q,z,J]=this.readEntityExp($,J+1,this.suppressValidationErr),z.indexOf("&")===-1)Z[Q]={regx:RegExp(`&${Q};`,"g"),val:z}}else if(G&&w$($,"!ELEMENT",J)){J+=8;let{index:Q}=this.readElementExp($,J+1);J=Q}else if(G&&w$($,"!ATTLIST",J))J+=8;else if(G&&w$($,"!NOTATION",J)){J+=9;let{index:Q}=this.readNotationExp($,J+1,this.suppressValidationErr);J=Q}else if(w$($,"!--",J))Y=!0;else throw Error("Invalid DOCTYPE");X++,W=""}else if($[J]===">"){if(Y){if($[J-1]==="-"&&$[J-2]==="-")Y=!1,X--}else X--;if(X===0)break}else if($[J]==="[")G=!0;else W+=$[J];if(X!==0)throw Error("Unclosed DOCTYPE")}else throw Error("Invalid Tag instead of DOCTYPE");return{entities:Z,i:J}}readEntityExp($,J){J=l0($,J);let Z="";while(J<$.length&&!/\s/.test($[J])&&$[J]!=='"'&&$[J]!=="'")Z+=$[J],J++;if(HJ(Z),J=l0($,J),!this.suppressValidationErr){if($.substring(J,J+6).toUpperCase()==="SYSTEM")throw Error("External entities are not supported");else if($[J]==="%")throw Error("Parameter entities are not supported")}let X="";return[J,X]=this.readIdentifierVal($,J,"entity"),J--,[Z,X,J]}readNotationExp($,J){J=l0($,J);let Z="";while(J<$.length&&!/\s/.test($[J]))Z+=$[J],J++;!this.suppressValidationErr&&HJ(Z),J=l0($,J);let X=$.substring(J,J+6).toUpperCase();if(!this.suppressValidationErr&&X!=="SYSTEM"&&X!=="PUBLIC")throw Error(`Expected SYSTEM or PUBLIC, found "${X}"`);J+=X.length,J=l0($,J);let G=null,Y=null;if(X==="PUBLIC"){if([J,G]=this.readIdentifierVal($,J,"publicIdentifier"),J=l0($,J),$[J]==='"'||$[J]==="'")[J,Y]=this.readIdentifierVal($,J,"systemIdentifier")}else if(X==="SYSTEM"){if([J,Y]=this.readIdentifierVal($,J,"systemIdentifier"),!this.suppressValidationErr&&!Y)throw Error("Missing mandatory system identifier for SYSTEM notation")}return{notationName:Z,publicIdentifier:G,systemIdentifier:Y,index:--J}}readIdentifierVal($,J,Z){let X="",G=$[J];if(G!=='"'&&G!=="'")throw Error(`Expected quoted string, found "${G}"`);J++;while(J<$.length&&$[J]!==G)X+=$[J],J++;if($[J]!==G)throw Error(`Unterminated ${Z} value`);return J++,[J,X]}readElementExp($,J){J=l0($,J);let Z="";while(J<$.length&&!/\s/.test($[J]))Z+=$[J],J++;if(!this.suppressValidationErr&&!c$(Z))throw Error(`Invalid element name: "${Z}"`);J=l0($,J);let X="";if($[J]==="E"&&w$($,"MPTY",J))J+=4;else if($[J]==="A"&&w$($,"NY",J))J+=2;else if($[J]==="("){J++;while(J<$.length&&$[J]!==")")X+=$[J],J++;if($[J]!==")")throw Error("Unterminated content model")}else if(!this.suppressValidationErr)throw Error(`Invalid Element Expression, found "${$[J]}"`);return{elementName:Z,contentModel:X.trim(),index:J}}readAttlistExp($,J){J=l0($,J);let Z="";while(J<$.length&&!/\s/.test($[J]))Z+=$[J],J++;HJ(Z),J=l0($,J);let X="";while(J<$.length&&!/\s/.test($[J]))X+=$[J],J++;if(!HJ(X))throw Error(`Invalid attribute name: "${X}"`);J=l0($,J);let G="";if($.substring(J,J+8).toUpperCase()==="NOTATION"){if(G="NOTATION",J+=8,J=l0($,J),$[J]!=="(")throw Error(`Expected '(', found "${$[J]}"`);J++;let W=[];while(J<$.length&&$[J]!==")"){let Q="";while(J<$.length&&$[J]!=="|"&&$[J]!==")")Q+=$[J],J++;if(Q=Q.trim(),!HJ(Q))throw Error(`Invalid notation name: "${Q}"`);if(W.push(Q),$[J]==="|")J++,J=l0($,J)}if($[J]!==")")throw Error("Unterminated list of notations");J++,G+=" ("+W.join("|")+")"}else{while(J<$.length&&!/\s/.test($[J]))G+=$[J],J++;let W=["CDATA","ID","IDREF","IDREFS","ENTITY","ENTITIES","NMTOKEN","NMTOKENS"];if(!this.suppressValidationErr&&!W.includes(G.toUpperCase()))throw Error(`Invalid attribute type: "${G}"`)}J=l0($,J);let Y="";if($.substring(J,J+8).toUpperCase()==="#REQUIRED")Y="#REQUIRED",J+=8;else if($.substring(J,J+7).toUpperCase()==="#IMPLIED")Y="#IMPLIED",J+=7;else[J,Y]=this.readIdentifierVal($,J,"ATTLIST");return{elementName:Z,attributeName:X,attributeType:G,defaultValue:Y,index:J}}}var l0=($,J)=>{while(J<$.length&&/\s/.test($[J]))J++;return J};function w$($,J,Z){for(let X=0;X<J.length;X++)if(J[X]!==$[Z+X+1])return!1;return!0}function HJ($){if(c$($))return $;else throw Error(`Invalid entity name ${$}`)}var eH=/^[-+]?0x[a-fA-F0-9]+$/,$Q=/^([\-\+])?(0*)([0-9]*(\.[0-9]*)?)$/,JQ={hex:!0,leadingZeros:!0,decimalPoint:".",eNotation:!0};function nZ($,J={}){if(J=Object.assign({},JQ,J),!$||typeof $!=="string")return $;let Z=$.trim();if(J.skipLike!==void 0&&J.skipLike.test(Z))return $;else if($==="0")return 0;else if(J.hex&&eH.test(Z))return YQ(Z,16);else if(Z.includes("e")||Z.includes("E"))return GQ($,Z,J);else{let X=$Q.exec(Z);if(X){let G=X[1]||"",Y=X[2],W=XQ(X[3]),Q=G?$[Y.length+1]===".":$[Y.length]===".";if(!J.leadingZeros&&(Y.length>1||Y.length===1&&!Q))return $;else{let z=Number(Z),O=String(z);if(z===0)return z;if(O.search(/[eE]/)!==-1)if(J.eNotation)return z;else return $;else if(Z.indexOf(".")!==-1)if(O==="0")return z;else if(O===W)return z;else if(O===`${G}${W}`)return z;else return $;let M=Y?W:Z;if(Y)return M===O||G+M===O?z:$;else return M===O||M===G+O?z:$}}else return $}}var ZQ=/^([-+])?(0*)(\d*(\.\d*)?[eE][-\+]?\d+)$/;function GQ($,J,Z){if(!Z.eNotation)return $;let X=J.match(ZQ);if(X){let G=X[1]||"",Y=X[3].indexOf("e")===-1?"E":"e",W=X[2],Q=G?$[W.length+1]===Y:$[W.length]===Y;if(W.length>1&&Q)return $;else if(W.length===1&&(X[3].startsWith(`.${Y}`)||X[3][0]===Y))return Number(J);else if(Z.leadingZeros&&!Q)return J=(X[1]||"")+X[3],Number(J);else return $}else return $}function XQ($){if($&&$.indexOf(".")!==-1){if($=$.replace(/0+$/,""),$===".")$="0";else if($[0]===".")$="0"+$;else if($[$.length-1]===".")$=$.substring(0,$.length-1);return $}return $}function YQ($,J){if(parseInt)return parseInt($,J);else if(Number.parseInt)return Number.parseInt($,J);else if(window&&window.parseInt)return window.parseInt($,J);else throw Error("parseInt, Number.parseInt, window.parseInt are not supported")}function mZ($){if(typeof $==="function")return $;if(Array.isArray($))return(J)=>{for(let Z of $){if(typeof Z==="string"&&J===Z)return!0;if(Z instanceof RegExp&&Z.test(J))return!0}};return()=>!1}class fJ{constructor($){if(this.options=$,this.currentNode=null,this.tagsNodeStack=[],this.docTypeEntities={},this.lastEntities={apos:{regex:/&(apos|#39|#x27);/g,val:"'"},gt:{regex:/&(gt|#62|#x3E);/g,val:">"},lt:{regex:/&(lt|#60|#x3C);/g,val:"<"},quot:{regex:/&(quot|#34|#x22);/g,val:'"'}},this.ampEntity={regex:/&(amp|#38|#x26);/g,val:"&"},this.htmlEntities={space:{regex:/&(nbsp|#160);/g,val:" "},cent:{regex:/&(cent|#162);/g,val:"\xA2"},pound:{regex:/&(pound|#163);/g,val:"\xA3"},yen:{regex:/&(yen|#165);/g,val:"\xA5"},euro:{regex:/&(euro|#8364);/g,val:"\u20AC"},copyright:{regex:/&(copy|#169);/g,val:"\xA9"},reg:{regex:/&(reg|#174);/g,val:"\xAE"},inr:{regex:/&(inr|#8377);/g,val:"\u20B9"},num_dec:{regex:/&#([0-9]{1,7});/g,val:(J,Z)=>String.fromCodePoint(Number.parseInt(Z,10))},num_hex:{regex:/&#x([0-9a-fA-F]{1,6});/g,val:(J,Z)=>String.fromCodePoint(Number.parseInt(Z,16))}},this.addExternalEntities=WQ,this.parseXml=zQ,this.parseTextData=HQ,this.resolveNameSpace=QQ,this.buildAttributesMap=VQ,this.isItStopNode=_Q,this.replaceEntitiesValue=KQ,this.readStopNodeData=FQ,this.saveTextToParentTag=MQ,this.addChild=OQ,this.ignoreAttributesFn=mZ(this.options.ignoreAttributes),this.options.stopNodes&&this.options.stopNodes.length>0){this.stopNodesExact=new Set,this.stopNodesWildcard=new Set;for(let J=0;J<this.options.stopNodes.length;J++){let Z=this.options.stopNodes[J];if(typeof Z!=="string")continue;if(Z.startsWith("*."))this.stopNodesWildcard.add(Z.substring(2));else this.stopNodesExact.add(Z)}}}}function WQ($){let J=Object.keys($);for(let Z=0;Z<J.length;Z++){let X=J[Z];this.lastEntities[X]={regex:new RegExp("&"+X+";","g"),val:$[X]}}}function HQ($,J,Z,X,G,Y,W){if($!==void 0){if(this.options.trimValues&&!X)$=$.trim();if($.length>0){if(!W)$=this.replaceEntitiesValue($);let Q=this.options.tagValueProcessor(J,$,Z,G,Y);if(Q===null||Q===void 0)return $;else if(typeof Q!==typeof $||Q!==$)return Q;else if(this.options.trimValues)return sZ($,this.options.parseTagValue,this.options.numberParseOptions);else if($.trim()===$)return sZ($,this.options.parseTagValue,this.options.numberParseOptions);else return $}}}function QQ($){if(this.options.removeNSPrefix){let J=$.split(":"),Z=$.charAt(0)==="/"?"/":"";if(J[0]==="xmlns")return"";if(J.length===2)$=Z+J[1]}return $}var UQ=new RegExp(`([^\\s=]+)\\s*(=\\s*(['"])([\\s\\S]*?)\\3)?`,"gm");function VQ($,J){if(this.options.ignoreAttributes!==!0&&typeof $==="string"){let Z=vJ($,UQ),X=Z.length,G={};for(let Y=0;Y<X;Y++){let W=this.resolveNameSpace(Z[Y][1]);if(this.ignoreAttributesFn(W,J))continue;let Q=Z[Y][4],z=this.options.attributeNamePrefix+W;if(W.length){if(this.options.transformAttributeName)z=this.options.transformAttributeName(z);if(z==="__proto__")z="#__proto__";if(Q!==void 0){if(this.options.trimValues)Q=Q.trim();Q=this.replaceEntitiesValue(Q);let O=this.options.attributeValueProcessor(W,Q,J);if(O===null||O===void 0)G[z]=Q;else if(typeof O!==typeof Q||O!==Q)G[z]=O;else G[z]=sZ(Q,this.options.parseAttributeValue,this.options.numberParseOptions)}else if(this.options.allowBooleanAttributes)G[z]=!0}}if(!Object.keys(G).length)return;if(this.options.attributesGroupName){let Y={};return Y[this.options.attributesGroupName]=G,Y}return G}}var zQ=function($){$=$.replace(/\r\n?/g,`
|
|
15
|
-
`);let J=new i0("!xml"),Z=J,X="",G="",Y=new kJ(this.options.processEntities);for(let W=0;W<$.length;W++)if($[W]==="<")if($[W+1]==="/"){let z=T$($,">",W,"Closing Tag is not closed."),O=$.substring(W+2,z).trim();if(this.options.removeNSPrefix){let B=O.indexOf(":");if(B!==-1)O=O.substr(B+1)}if(this.options.transformTagName)O=this.options.transformTagName(O);if(Z)X=this.saveTextToParentTag(X,Z,G);let M=G.substring(G.lastIndexOf(".")+1);if(O&&this.options.unpairedTags.indexOf(O)!==-1)throw Error(`Unpaired tag can not be used as closing tag: </${O}>`);let A=0;if(M&&this.options.unpairedTags.indexOf(M)!==-1)A=G.lastIndexOf(".",G.lastIndexOf(".")-1),this.tagsNodeStack.pop();else A=G.lastIndexOf(".");G=G.substring(0,A),Z=this.tagsNodeStack.pop(),X="",W=z}else if($[W+1]==="?"){let z=dZ($,W,!1,"?>");if(!z)throw Error("Pi Tag is not closed.");if(X=this.saveTextToParentTag(X,Z,G),this.options.ignoreDeclaration&&z.tagName==="?xml"||this.options.ignorePiTags);else{let O=new i0(z.tagName);if(O.add(this.options.textNodeName,""),z.tagName!==z.tagExp&&z.attrExpPresent)O[":@"]=this.buildAttributesMap(z.tagExp,G);this.addChild(Z,O,G,W)}W=z.closeIndex+1}else if($.substr(W+1,3)==="!--"){let z=T$($,"-->",W+4,"Comment is not closed.");if(this.options.commentPropName){let O=$.substring(W+4,z-2);X=this.saveTextToParentTag(X,Z,G),Z.add(this.options.commentPropName,[{[this.options.textNodeName]:O}])}W=z}else if($.substr(W+1,2)==="!D"){let z=Y.readDocType($,W);this.docTypeEntities=z.entities,W=z.i}else if($.substr(W+1,2)==="!["){let z=T$($,"]]>",W,"CDATA is not closed.")-2,O=$.substring(W+9,z);X=this.saveTextToParentTag(X,Z,G);let M=this.parseTextData(O,Z.tagname,G,!0,!1,!0,!0);if(M==null)M="";if(this.options.cdataPropName)Z.add(this.options.cdataPropName,[{[this.options.textNodeName]:O}]);else Z.add(this.options.textNodeName,M);W=z+2}else{let z=dZ($,W,this.options.removeNSPrefix),O=z.tagName,M=z.rawTagName,A=z.tagExp,B=z.attrExpPresent,L=z.closeIndex;if(this.options.transformTagName){let T=this.options.transformTagName(O);if(A===O)A=T;O=T}if(Z&&X){if(Z.tagname!=="!xml")X=this.saveTextToParentTag(X,Z,G,!1)}let C=Z;if(C&&this.options.unpairedTags.indexOf(C.tagname)!==-1)Z=this.tagsNodeStack.pop(),G=G.substring(0,G.lastIndexOf("."));if(O!==J.tagname)G+=G?"."+O:O;let w=W;if(this.isItStopNode(this.stopNodesExact,this.stopNodesWildcard,G,O)){let T="";if(A.length>0&&A.lastIndexOf("/")===A.length-1){if(O[O.length-1]==="/")O=O.substr(0,O.length-1),G=G.substr(0,G.length-1),A=O;else A=A.substr(0,A.length-1);W=z.closeIndex}else if(this.options.unpairedTags.indexOf(O)!==-1)W=z.closeIndex;else{let E=this.readStopNodeData($,M,L+1);if(!E)throw Error(`Unexpected end of ${M}`);W=E.i,T=E.tagContent}let D=new i0(O);if(O!==A&&B)D[":@"]=this.buildAttributesMap(A,G);if(T)T=this.parseTextData(T,O,G,!0,B,!0,!0);G=G.substr(0,G.lastIndexOf(".")),D.add(this.options.textNodeName,T),this.addChild(Z,D,G,w)}else{if(A.length>0&&A.lastIndexOf("/")===A.length-1){if(O[O.length-1]==="/")O=O.substr(0,O.length-1),G=G.substr(0,G.length-1),A=O;else A=A.substr(0,A.length-1);if(this.options.transformTagName){let D=this.options.transformTagName(O);if(A===O)A=D;O=D}let T=new i0(O);if(O!==A&&B)T[":@"]=this.buildAttributesMap(A,G);this.addChild(Z,T,G,w),G=G.substr(0,G.lastIndexOf("."))}else{let T=new i0(O);if(this.tagsNodeStack.push(Z),O!==A&&B)T[":@"]=this.buildAttributesMap(A,G);this.addChild(Z,T,G,w),Z=T}X="",W=L}}else X+=$[W];return J.child};function OQ($,J,Z,X){if(!this.options.captureMetaData)X=void 0;let G=this.options.updateTag(J.tagname,Z,J[":@"]);if(G===!1);else if(typeof G==="string")J.tagname=G,$.addChild(J,X);else $.addChild(J,X)}var KQ=function($){if(this.options.processEntities){for(let J in this.docTypeEntities){let Z=this.docTypeEntities[J];$=$.replace(Z.regx,Z.val)}for(let J in this.lastEntities){let Z=this.lastEntities[J];$=$.replace(Z.regex,Z.val)}if(this.options.htmlEntities)for(let J in this.htmlEntities){let Z=this.htmlEntities[J];$=$.replace(Z.regex,Z.val)}$=$.replace(this.ampEntity.regex,this.ampEntity.val)}return $};function MQ($,J,Z,X){if($){if(X===void 0)X=J.child.length===0;if($=this.parseTextData($,J.tagname,Z,!1,J[":@"]?Object.keys(J[":@"]).length!==0:!1,X),$!==void 0&&$!=="")J.add(this.options.textNodeName,$);$=""}return $}function _Q($,J,Z,X){if(J&&J.has(X))return!0;if($&&$.has(Z))return!0;return!1}function AQ($,J,Z=">"){let X,G="";for(let Y=J;Y<$.length;Y++){let W=$[Y];if(X){if(W===X)X=""}else if(W==='"'||W==="'")X=W;else if(W===Z[0])if(Z[1]){if($[Y+1]===Z[1])return{data:G,index:Y}}else return{data:G,index:Y};else if(W==="\t")W=" ";G+=W}}function T$($,J,Z,X){let G=$.indexOf(J,Z);if(G===-1)throw Error(X);else return G+J.length-1}function dZ($,J,Z,X=">"){let G=AQ($,J+1,X);if(!G)return;let{data:Y,index:W}=G,Q=Y.search(/\s/),z=Y,O=!0;if(Q!==-1)z=Y.substring(0,Q),Y=Y.substring(Q+1).trimStart();let M=z;if(Z){let A=z.indexOf(":");if(A!==-1)z=z.substr(A+1),O=z!==G.data.substr(A+1)}return{tagName:z,tagExp:Y,closeIndex:W,attrExpPresent:O,rawTagName:M}}function FQ($,J,Z){let X=Z,G=1;for(;Z<$.length;Z++)if($[Z]==="<")if($[Z+1]==="/"){let Y=T$($,">",Z,`${J} is not closed`);if($.substring(Z+2,Y).trim()===J){if(G--,G===0)return{tagContent:$.substring(X,Z),i:Y}}Z=Y}else if($[Z+1]==="?")Z=T$($,"?>",Z+1,"StopNode is not closed.");else if($.substr(Z+1,3)==="!--")Z=T$($,"-->",Z+3,"StopNode is not closed.");else if($.substr(Z+1,2)==="![")Z=T$($,"]]>",Z,"StopNode is not closed.")-2;else{let Y=dZ($,Z,">");if(Y){if((Y&&Y.tagName)===J&&Y.tagExp[Y.tagExp.length-1]!=="/")G++;Z=Y.closeIndex}}}function sZ($,J,Z){if(J&&typeof $==="string"){let X=$.trim();if(X==="true")return!0;else if(X==="false")return!1;else return nZ($,Z)}else if(K1($))return $;else return""}var oZ=i0.getMetaDataSymbol();function lZ($,J){return j1($,J)}function j1($,J,Z){let X,G={};for(let Y=0;Y<$.length;Y++){let W=$[Y],Q=RQ(W),z="";if(Z===void 0)z=Q;else z=Z+"."+Q;if(Q===J.textNodeName)if(X===void 0)X=W[Q];else X+=""+W[Q];else if(Q===void 0)continue;else if(W[Q]){let O=j1(W[Q],J,z),M=jQ(O,J);if(W[oZ]!==void 0)O[oZ]=W[oZ];if(W[":@"])IQ(O,W[":@"],z,J);else if(Object.keys(O).length===1&&O[J.textNodeName]!==void 0&&!J.alwaysCreateTextNode)O=O[J.textNodeName];else if(Object.keys(O).length===0)if(J.alwaysCreateTextNode)O[J.textNodeName]="";else O="";if(G[Q]!==void 0&&G.hasOwnProperty(Q)){if(!Array.isArray(G[Q]))G[Q]=[G[Q]];G[Q].push(O)}else if(J.isArray(Q,z,M))G[Q]=[O];else G[Q]=O}}if(typeof X==="string"){if(X.length>0)G[J.textNodeName]=X}else if(X!==void 0)G[J.textNodeName]=X;return G}function RQ($){let J=Object.keys($);for(let Z=0;Z<J.length;Z++){let X=J[Z];if(X!==":@")return X}}function IQ($,J,Z,X){if(J){let G=Object.keys(J),Y=G.length;for(let W=0;W<Y;W++){let Q=G[W];if(X.isArray(Q,Z+"."+Q,!0,!0))$[Q]=[J[Q]];else $[Q]=J[Q]}}}function jQ($,J){let{textNodeName:Z}=J,X=Object.keys($).length;if(X===0)return!0;if(X===1&&($[Z]||typeof $[Z]==="boolean"||$[Z]===0))return!0;return!1}class QJ{constructor($){this.externalEntities={},this.options=I1($)}parse($,J){if(typeof $!=="string"&&$.toString)$=$.toString();else if(typeof $!=="string")throw Error("XML data is accepted in String or Bytes[] form.");if(J){if(J===!0)J={};let G=R1($,J);if(G!==!0)throw Error(`${G.err.msg}:${G.err.line}:${G.err.col}`)}let Z=new fJ(this.options);Z.addExternalEntities(this.externalEntities);let X=Z.parseXml($);if(this.options.preserveOrder||X===void 0)return X;else return lZ(X,this.options)}addEntity($,J){if(J.indexOf("&")!==-1)throw Error("Entity value can't have '&'");else if($.indexOf("&")!==-1||$.indexOf(";")!==-1)throw Error("An entity must be set without '&' and ';'. Eg. use '#xD' for '
'");else if(J==="&")throw Error("An entity with value '&' is not permitted");else this.externalEntities[$]=J}static getMetaDataSymbol(){return i0.getMetaDataSymbol()}}var qQ=new QJ,BQ={name:"parser",enable:!0,deps:["auth"],handler:async($,J)=>{if(!J.api)return;if(J.api.rawBody){J.body={};return}if(J.req.method==="GET"){let Z=new URL(J.req.url),X=Object.fromEntries(Z.searchParams);J.body=X}else if(J.req.method==="POST"){let Z=J.req.headers.get("content-type")||"",X=new URL(J.req.url),G=Object.fromEntries(X.searchParams);try{if(Z.includes("application/json")){let Y=await J.req.json(),W={...G,...Y};J.body=W}else if(Z.includes("application/xml")||Z.includes("text/xml")){let Y=await J.req.text(),W=qQ.parse(Y),Q=Object.keys(W)[0],z=Q&&typeof W[Q]==="object"?W[Q]:W,O={...G,...z};J.body=O}else{J.response=B$(J,"\u65E0\u6548\u7684\u8BF7\u6C42\u53C2\u6570\u683C\u5F0F",1,null,{location:"content-type",value:Z},"parser");return}}catch{J.response=B$(J,"\u65E0\u6548\u7684\u8BF7\u6C42\u53C2\u6570\u683C\u5F0F",1,null,{location:"body",reason:Z.includes("application/json")?"invalid_json":Z.includes("xml")?"invalid_xml":"invalid_body"},"parser");return}}}},q1=BQ;a();var PQ={name:"permission",enable:!0,deps:["validator"],handler:async($,J)=>{if(!J.api)return;if(J.api.auth===!1)return;if(typeof J.user.id!=="number"){J.response=B$(J,"\u672A\u767B\u5F55",1,null,null,"auth");return}if(J.user.roleCode==="dev")return;let Z=J.route,X=J.user.roleCode,G=!1;if(X&&$.redis)try{let Y=G0.roleApis(X);G=await $.redis.sismember(Y,Z)}catch(Y){q.error({event:"hook_permission_redis_error",apiPath:Z,roleCode:X,err:Y,msg:"hook permission redis error"}),G=!1}if(!G){let Y=typeof J.api.name==="string"&&J.api.name.length>0?J.api.name:null,W=typeof Z==="string"&&Z.length>0?Z:null,Q=Y?Y:W?W:"\u672A\u77E5\u63A5\u53E3";J.response=B$(J,`\u65E0\u6743\u8BBF\u95EE ${Q} \u63A5\u53E3`,1,null,{apiLabel:Q},"permission");return}}},B1=PQ;var rZ={number:"^\\d+$",integer:"^-?\\d+$",float:"^-?\\d+(\\.\\d+)?$",positive:"^[1-9]\\d*$",negative:"^-\\d+$",zero:"^0$",word:"^[a-zA-Z]+$",alphanumeric:"^[a-zA-Z0-9]+$",alphanumeric_:"^[a-zA-Z0-9_]+$",alphanumericDash_:"^[a-zA-Z0-9_-]+$",lowercase:"^[a-z]+$",uppercase:"^[A-Z]+$",chinese:"^[\\u4e00-\\u9fa5]+$",chineseWord:"^[\\u4e00-\\u9fa5a-zA-Z]+$",email:"^[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\\.[a-zA-Z]{2,}$",phone:"^1[3-9]\\d{9}$",telephone:"^0\\d{2,3}-?\\d{7,8}$",url:"^https?://",ip:"^((25[0-5]|2[0-4]\\d|[01]?\\d\\d?)\\.){3}(25[0-5]|2[0-4]\\d|[01]?\\d\\d?)$",ipv6:"^([0-9a-fA-F]{1,4}:){7}[0-9a-fA-F]{1,4}$",domain:"^(?:[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?\\.)+[a-zA-Z]{2,}$",uuid:"^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$",hex:"^[0-9a-fA-F]+$",base64:"^[A-Za-z0-9+/=]+$",md5:"^[a-f0-9]{32}$",sha1:"^[a-f0-9]{40}$",sha256:"^[a-f0-9]{64}$",date:"^\\d{4}-\\d{2}-\\d{2}$",time:"^\\d{2}:\\d{2}:\\d{2}$",datetime:"^\\d{4}-\\d{2}-\\d{2}T\\d{2}:\\d{2}:\\d{2}",year:"^\\d{4}$",month:"^(0[1-9]|1[0-2])$",day:"^(0[1-9]|[12]\\d|3[01])$",variable:"^[a-zA-Z_][a-zA-Z0-9_]*$",constant:"^[A-Z][A-Z0-9_]*$",package:"^[a-z][a-z0-9-]*$",idCard:"^\\d{17}[\\dXx]$",passport:"^[a-zA-Z0-9]{5,17}$",bankCard:"^\\d{16,19}$",wechat:"^[a-zA-Z][a-zA-Z0-9_-]{5,19}$",qq:"^[1-9]\\d{4,10}$",alipay:"^(1[3-9]\\d{9}|[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\\.[a-zA-Z]{2,})$",username:"^[a-zA-Z][a-zA-Z0-9_]{3,19}$",nickname:"^[\\u4e00-\\u9fa5a-zA-Z0-9]{2,20}$",passwordWeak:"^.{6,}$",passwordMedium:"^(?=.*[a-zA-Z])(?=.*\\d).{8,}$",passwordStrong:"^(?=.*[a-z])(?=.*[A-Z])(?=.*\\d)(?=.*[!@#$%^&*]).{8,}$",licensePlate:"^[\u4EAC\u6D25\u6CAA\u6E1D\u5180\u8C6B\u4E91\u8FBD\u9ED1\u6E58\u7696\u9C81\u65B0\u82CF\u6D59\u8D63\u9102\u6842\u7518\u664B\u8499\u9655\u5409\u95FD\u8D35\u7CA4\u9752\u85CF\u5DDD\u5B81\u743C\u4F7F\u9886][A-Z][A-HJ-NP-Z0-9]{4,5}[A-HJ-NP-Z0-9\u6302\u5B66\u8B66\u6E2F\u6FB3]$",postalCode:"^\\d{6}$",semver:"^\\d+\\.\\d+\\.\\d+(-[a-zA-Z0-9.]+)?(\\+[a-zA-Z0-9.]+)?$",colorHex:"^#([0-9a-fA-F]{3}|[0-9a-fA-F]{6})$",empty:"^$",notempty:".+"},P1=new Map;function LQ($){if($.startsWith("@")){let J=$.slice(1);return rZ[J]||$}return $}function L1($,J){let Z=LQ($),X=`${Z}:${J||""}`,G=P1.get(X);if(!G)G=new RegExp(Z,J),P1.set(X,G);return G}n0();class iZ{static validate($,J,Z=[]){let X={};if(!n($))return this.buildResult({_error:"\u6570\u636E\u5FC5\u987B\u662F\u5BF9\u8C61\u683C\u5F0F"});if(!n(J))return this.buildResult({_error:"\u9A8C\u8BC1\u89C4\u5219\u5FC5\u987B\u662F\u5BF9\u8C61\u683C\u5F0F"});let G=$,Y=J;for(let W of Z){let Q=G[W];if(Q===void 0||Q===null){let z=Y[W],O=n(z)&&typeof z.name==="string"?z.name:W;X[W]=`${O}\u4E3A\u5FC5\u586B\u9879`}}for(let[W,Q]of Object.entries(Y)){if(X[W])continue;if(G[W]===void 0&&!Z.includes(W))continue;if(!n(Q)){X[W]=`${W}\u9A8C\u8BC1\u89C4\u5219\u5FC5\u987B\u662F\u5BF9\u8C61\u683C\u5F0F`;continue}let{name:z,type:O}=Q;if(typeof z!=="string"||typeof O!=="string"){X[W]=`${W}\u9A8C\u8BC1\u89C4\u5219\u65E0\u6548`;continue}let M={name:z,type:O},A=Q.min;if(typeof A==="number"||A===null)M.min=A;let B=Q.max;if(typeof B==="number"||B===null)M.max=B;let L=Q.default;if(L===null||typeof L==="string"||typeof L==="number"||typeof L==="boolean"||Array.isArray(L)||n(L))M.default=L;let C=Q.detail;if(typeof C==="string")M.detail=C;let w=Q.index;if(typeof w==="boolean")M.index=w;let T=Q.unique;if(typeof T==="boolean")M.unique=T;let D=Q.nullable;if(typeof D==="boolean")M.nullable=D;let E=Q.unsigned;if(typeof E==="boolean")M.unsigned=E;let N=Q.regexp;if(typeof N==="string"||N===null)M.regexp=N;let h=this.checkField(G[W],M,W);if(h)X[W]=h}return this.buildResult(X)}static single($,J){let Z=H$(J),X=Z.type,G=Z.default;if($===void 0||$===null||$==="")return{value:this.defaultFor(X,G),error:null};let Y=this.convert($,X);if(Y.error)return{value:null,error:Y.error};let W=this.checkRule(Y.value,J);if(W)return{value:null,error:W};return{value:Y.value,error:null}}static buildResult($){let J=Object.values($),Z=Object.keys($),X=J.length>0;return{code:X?1:0,failed:X,firstError:X?J[0]??null:null,errors:J,errorFields:Z,fieldErrors:$}}static checkField($,J,Z){let X=J.name||Z,G=this.convert($,J.type);if(G.error)return`${X}${G.error}`;let Y=this.checkRule(G.value,J);return Y?`${X}${Y}`:null}static convert($,J){switch(J.toLowerCase()){case"number":if(typeof $==="number")return Number.isNaN($)||!isFinite($)?{value:null,error:"\u5FC5\u987B\u662F\u6709\u6548\u6570\u5B57"}:{value:$,error:null};if(typeof $==="string"){let Z=Number($);return Number.isNaN(Z)||!isFinite(Z)?{value:null,error:"\u5FC5\u987B\u662F\u6570\u5B57"}:{value:Z,error:null}}return{value:null,error:"\u5FC5\u987B\u662F\u6570\u5B57"};case"string":case"text":return typeof $==="string"?{value:$,error:null}:{value:null,error:"\u5FC5\u987B\u662F\u5B57\u7B26\u4E32"};case"array_string":case"array_text":return Array.isArray($)?{value:$,error:null}:{value:null,error:"\u5FC5\u987B\u662F\u6570\u7EC4"};case"array_number_string":case"array_number_text":if(!Array.isArray($))return{value:null,error:"\u5FC5\u987B\u662F\u6570\u7EC4"};for(let Z of $)if(typeof Z!=="number"||!isFinite(Z))return{value:null,error:"\u6570\u7EC4\u5143\u7D20\u5FC5\u987B\u662F\u6570\u5B57"};return{value:$,error:null};default:return{value:$,error:null}}}static checkRule($,J){let Z=H$(J),X=Z.type,G=Z.min,Y=Z.max,W=Z.regexp,Q=this.resolveRegex(W);switch(X.toLowerCase()){case"number":if(typeof $!=="number")return"\u5FC5\u987B\u662F\u6570\u5B57";if(G!==null&&$<G)return`\u4E0D\u80FD\u5C0F\u4E8E${G}`;if(Y!==null&&Y>0&&$>Y)return`\u4E0D\u80FD\u5927\u4E8E${Y}`;if(Q&&!this.testRegex(Q,String($)))return"\u683C\u5F0F\u4E0D\u6B63\u786E";break;case"string":case"text":if(typeof $!=="string")return"\u5FC5\u987B\u662F\u5B57\u7B26\u4E32";if(G!==null&&$.length<G)return`\u957F\u5EA6\u4E0D\u80FD\u5C11\u4E8E${G}\u4E2A\u5B57\u7B26`;if(Y!==null&&Y>0&&$.length>Y)return`\u957F\u5EA6\u4E0D\u80FD\u8D85\u8FC7${Y}\u4E2A\u5B57\u7B26`;if(Q&&!this.testRegex(Q,$))return"\u683C\u5F0F\u4E0D\u6B63\u786E";break;case"array_string":case"array_text":case"array_number_string":case"array_number_text":if(!Array.isArray($))return"\u5FC5\u987B\u662F\u6570\u7EC4";if(G!==null&&$.length<G)return`\u81F3\u5C11\u9700\u8981${G}\u4E2A\u5143\u7D20`;if(Y!==null&&Y>0&&$.length>Y)return`\u6700\u591A\u53EA\u80FD\u6709${Y}\u4E2A\u5143\u7D20`;if(Q){for(let z of $)if(!this.testRegex(Q,String(z)))return"\u5143\u7D20\u683C\u5F0F\u4E0D\u6B63\u786E"}break}return null}static resolveRegex($){if(!$)return null;if($.startsWith("@")){let J=$.substring(1);return rZ[J]||$}return $}static testRegex($,J){try{return L1($).test(J)}catch{return!1}}static defaultFor($,J){if(J!==null&&J!==void 0){if(($==="array_string"||$==="array_text"||$==="array_number_string"||$==="array_number_text")&&typeof J==="string"){if(J==="[]")return[];try{let Z=JSON.parse(J);return Array.isArray(Z)?Z:[]}catch{return[]}}if($==="number"&&typeof J==="string"){let Z=Number(J);return isNaN(Z)?0:Z}return J}switch($.toLowerCase()){case"number":return 0;case"array_string":case"array_text":case"array_number_string":case"array_number_text":return[];default:return""}}}n0();var SQ={name:"validator",enable:!0,deps:["parser"],handler:async($,J)=>{if(!J.api)return;if(!J.api.fields)return;if(n(J.api.fields)){let X=n(J.body)?J.body:{},G={};for(let[Y,W]of Object.entries(J.api.fields)){let Q=H$(W),z=X[Y];if(z===void 0){let O=x(Y);if(X[O]!==void 0)z=X[O]}if(z===void 0&&Q.default!==null)z=Q.default;if(z!==void 0)G[Y]=z}J.body=G}let Z=iZ.validate(J.body,J.api.fields,J.api.required||[]);if(Z.code!==0){J.response=B$(J,Z.firstError||"\u53C2\u6570\u9A8C\u8BC1\u5931\u8D25",1,null,Z.fieldErrors,"validator");return}}},S1=SQ;a();class tZ{db;redis;constructor($){this.db=$.db,this.redis=$.redis}assertApiPathname($,J){if(typeof $!=="string")throw Error(`${J} \u5FC5\u987B\u662F\u5B57\u7B26\u4E32`);let Z=$.trim();if(!Z)throw Error(`${J} \u4E0D\u5141\u8BB8\u4E3A\u7A7A\u5B57\u7B26\u4E32`);if(/^(GET|POST|PUT|PATCH|DELETE|OPTIONS|HEAD)\b/i.test(Z))throw Error(`${J} \u4E0D\u5141\u8BB8\u5305\u542B method \u524D\u7F00\uFF0C\u5E94\u4E3A url.pathname\uFF08\u4F8B\u5982 /api/app/xxx\uFF09`);if(!Z.startsWith("/"))throw Error(`${J} \u5FC5\u987B\u662F pathname\uFF08\u4EE5 / \u5F00\u5934\uFF09`);if(Z.includes(" "))throw Error(`${J} \u4E0D\u5141\u8BB8\u5305\u542B\u7A7A\u683C`);return Z}assertApiPathList($,J){if($===null||$===void 0)return[];let Z=$;if(typeof Z==="string"){let G=Z.trim();if(G===""||G==="null")return[];if(G.startsWith("[")&&G.endsWith("]"))try{Z=JSON.parse(G)}catch{throw Error(`\u89D2\u8272\u6743\u9650\u6570\u636E\u4E0D\u5408\u6CD5\uFF1Aaddon_admin_role.apis JSON \u89E3\u6790\u5931\u8D25\uFF0CroleCode=${J}`)}}if(!Array.isArray(Z))throw Error(`\u89D2\u8272\u6743\u9650\u6570\u636E\u4E0D\u5408\u6CD5\uFF1Aaddon_admin_role.apis \u5FC5\u987B\u662F\u5B57\u7B26\u4E32\u6570\u7EC4\u6216 JSON \u6570\u7EC4\u5B57\u7B26\u4E32\uFF0CroleCode=${J}\uFF0Ctype=${typeof Z}`);let X=[];for(let G of Z)X.push(this.assertApiPathname(G,`\u89D2\u8272\u6743\u9650\u6570\u636E\u4E0D\u5408\u6CD5\uFF1Aaddon_admin_role.apis \u5143\u7D20\uFF0CroleCode=${J}`));return X}async cacheApis(){try{if(!(await this.db.tableExists("addon_admin_api")).data){q.warn("\u26A0\uFE0F \u63A5\u53E3\u8868\u4E0D\u5B58\u5728\uFF0C\u8DF3\u8FC7\u63A5\u53E3\u7F13\u5B58");return}let J=await this.db.getAll({table:"addon_admin_api"});if(await this.redis.setObject(G0.apisAll(),J.data.lists)===null)q.warn("\u26A0\uFE0F \u63A5\u53E3\u7F13\u5B58\u5931\u8D25")}catch($){q.error({err:$,msg:"\u26A0\uFE0F \u63A5\u53E3\u7F13\u5B58\u5F02\u5E38"})}}async cacheMenus(){try{if(!(await this.db.tableExists("addon_admin_menu")).data){q.warn("\u26A0\uFE0F \u83DC\u5355\u8868\u4E0D\u5B58\u5728\uFF0C\u8DF3\u8FC7\u83DC\u5355\u7F13\u5B58");return}let J=await this.db.getAll({table:"addon_admin_menu"});if(await this.redis.setObject(G0.menusAll(),J.data.lists)===null)q.warn("\u26A0\uFE0F \u83DC\u5355\u7F13\u5B58\u5931\u8D25")}catch($){q.warn({err:$,msg:"\u26A0\uFE0F \u83DC\u5355\u7F13\u5B58\u5F02\u5E38"})}}async rebuildRoleApiPermissions(){try{if(!(await this.db.tableExists("addon_admin_role")).data){q.warn("\u26A0\uFE0F \u89D2\u8272\u8868\u4E0D\u5B58\u5728\uFF0C\u8DF3\u8FC7\u89D2\u8272\u6743\u9650\u7F13\u5B58");return}let J=await this.db.getAll({table:"addon_admin_role",fields:["code","apis"]}),Z=new Map;for(let W of J.data.lists){if(!W?.code)continue;let Q=this.assertApiPathList(W.apis,W.code);Z.set(W.code,Q)}let X=Array.from(Z.keys());if(X.length===0){q.info("\u2705 \u6CA1\u6709\u9700\u8981\u7F13\u5B58\u7684\u89D2\u8272\u6743\u9650");return}let G=X.map((W)=>G0.roleApis(W));await this.redis.delBatch(G);let Y=[];for(let W of X){let Q=Z.get(W)||[],z=Array.from(new Set(Q)).sort();if(z.length>0)Y.push({key:G0.roleApis(W),members:z})}if(Y.length>0)await this.redis.saddBatch(Y)}catch($){throw q.error({err:$,msg:"\u26A0\uFE0F \u89D2\u8272\u6743\u9650\u7F13\u5B58\u5F02\u5E38\uFF08\u5C06\u963B\u65AD\u542F\u52A8\uFF09"}),$}}async refreshRoleApiPermissions($,J){if(!$||typeof $!=="string")throw Error("roleCode \u5FC5\u987B\u662F\u975E\u7A7A\u5B57\u7B26\u4E32");if(!Array.isArray(J))throw Error("apiPaths \u5FC5\u987B\u662F\u6570\u7EC4");let Z=J.map((Y)=>this.assertApiPathname(Y,`refreshRoleApiPermissions: apiPaths \u5143\u7D20\uFF0CroleCode=${$}`)),X=G0.roleApis($);if(Z.length===0){await this.redis.del(X);return}let G=Array.from(new Set(Z));if(await this.redis.del(X),G.length>0)await this.redis.sadd(X,G)}async cacheAll(){await this.cacheApis(),await this.cacheMenus(),await this.rebuildRoleApiPermissions()}async getApis(){try{return await this.redis.getObject(G0.apisAll())||[]}catch($){return q.error({err:$,msg:"\u83B7\u53D6\u63A5\u53E3\u7F13\u5B58\u5931\u8D25"}),[]}}async getMenus(){try{return await this.redis.getObject(G0.menusAll())||[]}catch($){return q.error({err:$,msg:"\u83B7\u53D6\u83DC\u5355\u7F13\u5B58\u5931\u8D25"}),[]}}async getRolePermissions($){try{return await this.redis.smembers(G0.roleApis($))||[]}catch(J){return q.error({err:J,roleCode:$,msg:"\u83B7\u53D6\u89D2\u8272\u6743\u9650\u7F13\u5B58\u5931\u8D25"}),[]}}async checkRolePermission($,J){try{let Z=this.assertApiPathname(J,"checkRolePermission: apiPath");return await this.redis.sismember(G0.roleApis($),Z)}catch(Z){return q.error({err:Z,roleCode:$,msg:"\u68C0\u67E5\u89D2\u8272\u6743\u9650\u5931\u8D25"}),!1}}async deleteRolePermissions($){try{if(await this.redis.del(G0.roleApis($))>0)return q.info(`\u2705 \u5DF2\u5220\u9664\u89D2\u8272 ${$} \u7684\u6743\u9650\u7F13\u5B58`),!0;return!1}catch(J){return q.error({err:J,roleCode:$,msg:"\u5220\u9664\u89D2\u8272\u6743\u9650\u7F13\u5B58\u5931\u8D25"}),!1}}}var CQ={name:"cache",enable:!0,deps:["logger","redis","db"],async handler($){if(!$.db)throw Error("\u7F13\u5B58\u521D\u59CB\u5316\u5931\u8D25\uFF1Actx.db \u672A\u521D\u59CB\u5316\uFF08Db \u63D2\u4EF6\u672A\u52A0\u8F7D\u6216\u6CE8\u5165\u5931\u8D25\uFF09");if(!$.redis)throw Error("\u7F13\u5B58\u521D\u59CB\u5316\u5931\u8D25\uFF1Actx.redis \u672A\u521D\u59CB\u5316\uFF08Redis \u63D2\u4EF6\u672A\u52A0\u8F7D\u6216\u6CE8\u5165\u5931\u8D25\uFF09");return new tZ({db:$.db,redis:$.redis})}},C1=CQ;var EQ={name:"cipher",enable:!0,deps:[],handler:()=>{return g$}},E1=EQ;var wQ={name:"config",enable:!0,deps:[],handler:($)=>{return $.config}},w1=wQ;function yJ($,J=["id","pid","sort"]){if(!$||!Array.isArray($))return $;return $.map((Z)=>{let X=Z,G={};for(let[Y,W]of Object.entries(X))G[Y]=W;for(let[Y,W]of Object.entries(G)){if(W===void 0||W===null)continue;if((J.includes(Y)||Y.endsWith("Id")||Y.endsWith("_id")||Y.endsWith("At")||Y.endsWith("_at"))&&typeof W==="string"){let z=Number(W);if(!Number.isNaN(z))G[Y]=z}}return G})}function aZ($){return $!==null&&typeof $==="object"&&!Array.isArray($)}function TQ($){return Array.isArray($)}function N$($,J={}){let{pickKeys:Z,omitKeys:X,keepValues:G,excludeValues:Y,keepMap:W}=J,Q=(z)=>{let O={},M=Object.keys(z);if(Z&&Z.length)M=M.filter((A)=>Z.includes(A));if(X&&X.length)M=M.filter((A)=>!X.includes(A));for(let A of M){let B=z[A];if(W&&A in W){if(Object.is(W[A],B)){O[A]=B;continue}}if(G&&G.length&&!G.includes(B))continue;if(Y&&Y.length&&Y.includes(B))continue;O[A]=B}return O};if(TQ($))return $.map((z)=>aZ(z)?Q(z):z).filter((z)=>{if(aZ(z))return Object.keys(z).length>0;return!0});if(aZ($))return Q($);return $}function NQ($){if($===null)return!0;return typeof $==="string"||typeof $==="number"||typeof $==="boolean"}function vQ($){if(!$||typeof $!=="object")return!1;if($ instanceof Date)return!1;if(Array.isArray($))return!1;return!0}function eZ($){if(NQ($))return!0;if(Array.isArray($)){for(let J of $)if(!eZ(J))return!1;return!0}if(vQ($)){for(let J of Object.values($)){if(J===void 0)continue;if(!eZ(J))return!1}return!0}return!1}function T1($){if(!Array.isArray($))return[];let J=[];for(let Z of $){if(Z===null){J.push(null);continue}if(typeof Z==="string"||typeof Z==="number"||typeof Z==="boolean"){J.push(Z);continue}if(typeof Z==="bigint"){J.push(String(Z));continue}if(Z instanceof Date){J.push(Z);continue}if(eZ(Z)){J.push(Z);continue}J.push(String(Z))}return J}function v$($){if(typeof $==="number")return $;if(typeof $==="bigint")return Number($);return 0}n0();n0();class c{static parseTableRef($){if(typeof $!=="string")throw Error(`tableRef \u5FC5\u987B\u662F\u5B57\u7B26\u4E32 (tableRef: ${String($)})`);let J=$.trim();if(!J)throw Error("tableRef \u4E0D\u80FD\u4E3A\u7A7A");let Z=J.split(/\s+/).filter((Q)=>Q.length>0);if(Z.length===0)throw Error("tableRef \u4E0D\u80FD\u4E3A\u7A7A");if(Z.length>2)throw Error(`\u4E0D\u652F\u6301\u7684\u8868\u5F15\u7528\u683C\u5F0F\uFF08\u5305\u542B\u8FC7\u591A\u7247\u6BB5\uFF09\u3002\u8BF7\u4F7F\u7528\u6700\u7B80\u5F62\u5F0F\uFF1Atable \u6216 table alias \u6216 schema.table \u6216 schema.table alias (tableRef: ${J})`);let X=Z[0];if(typeof X!=="string"||X.trim()==="")throw Error(`tableRef \u89E3\u6790\u5931\u8D25\uFF1A\u7F3A\u5C11\u8868\u540D (tableRef: ${J})`);let G=null;if(Z.length===2){let Q=Z[1];if(typeof Q!=="string"||Q.trim()==="")throw Error(`tableRef \u89E3\u6790\u5931\u8D25\uFF1A\u7F3A\u5C11 alias (tableRef: ${J})`);G=Q}let Y=X.split(".");if(Y.length>2)throw Error(`\u4E0D\u652F\u6301\u7684\u8868\u5F15\u7528\u683C\u5F0F\uFF08schema \u5C42\u7EA7\u8FC7\u6DF1\uFF09 (tableRef: ${J})`);if(Y.length===2){let Q=Y[0],z=Y[1];if(typeof Q!=="string"||Q.trim()==="")throw Error(`tableRef \u89E3\u6790\u5931\u8D25\uFF1Aschema \u4E3A\u7A7A (tableRef: ${J})`);if(typeof z!=="string"||z.trim()==="")throw Error(`tableRef \u89E3\u6790\u5931\u8D25\uFF1Atable \u4E3A\u7A7A (tableRef: ${J})`);return{schema:Q,table:z,alias:G}}let W=Y[0];if(typeof W!=="string"||W.trim()==="")throw Error(`tableRef \u89E3\u6790\u5931\u8D25\uFF1Atable \u4E3A\u7A7A (tableRef: ${J})`);return{schema:null,table:W,alias:G}}static normalizeTableRef($){let J=c.parseTableRef($),Z=J.schema?x(J.schema):null,X=x(J.table),G=Z?`${Z}.${X}`:X;if(J.alias)G=`${G} ${J.alias}`;return G}static getJoinMainQualifier($){let J=c.parseTableRef($);if(J.alias)return J.alias;return x(J.table)}static async fieldsToSnake($,J,Z){if(!J||!Array.isArray(J))return["*"];let X=c.validateAndClassifyFields(J);if(X.type==="all")return["*"];if(X.type==="include")return X.fields.map((G)=>{if(G.includes("(")||G.includes(" "))return G;return x(G)});if(X.type==="exclude"){let G=await Z($),Y=X.fields.map((Q)=>x(Q)),W=G.filter((Q)=>!Y.includes(Q));if(W.length===0)throw Error(`\u6392\u9664\u5B57\u6BB5\u540E\u6CA1\u6709\u5269\u4F59\u5B57\u6BB5\u53EF\u67E5\u8BE2\u3002\u8868: ${$}, \u6392\u9664: ${Y.join(", ")}`);return W}return["*"]}static validateAndClassifyFields($){if(!$||$.length===0)return{type:"all",fields:[]};if($.some((X)=>X==="*"))throw Error("fields \u4E0D\u652F\u6301 * \u661F\u53F7\uFF0C\u8BF7\u4F7F\u7528\u7A7A\u6570\u7EC4 [] \u6216\u4E0D\u4F20\u53C2\u6570\u8868\u793A\u67E5\u8BE2\u6240\u6709\u5B57\u6BB5");if($.some((X)=>!X||typeof X!=="string"||X.trim()===""))throw Error("fields \u4E0D\u80FD\u5305\u542B\u7A7A\u5B57\u7B26\u4E32\u6216\u65E0\u6548\u503C");let J=$.filter((X)=>!X.startsWith("!")),Z=$.filter((X)=>X.startsWith("!"));if(J.length>0&&Z.length===0)return{type:"include",fields:J};if(Z.length>0&&J.length===0)return{type:"exclude",fields:Z.map((G)=>G.substring(1))};throw Error(`fields \u4E0D\u80FD\u540C\u65F6\u5305\u542B\u666E\u901A\u5B57\u6BB5\u548C\u6392\u9664\u5B57\u6BB5\uFF08! \u5F00\u5934\uFF09\u3002\u53EA\u80FD\u4F7F\u7528\u4EE5\u4E0B3\u79CD\u65B9\u5F0F\u4E4B\u4E00\uFF1A
|
|
11
|
+
)`;if(await $.db.unsafe(K),$.dbDialect==="postgresql"){for(let L of WJ){let C=String(L.comment).replace(/'/g,"''"),T=X0($.dbDialect,L.name),w=`COMMENT ON COLUMN ${W}.${T} IS '${C}'`;await $.db.unsafe(w)}for(let[L,C]of Object.entries(Z)){let T=f(L),w=X0($.dbDialect,T),D=C.name&&C.name!=="null"?String(C.name):"",E=D.replace(/'/g,"''"),N=D?`'${E}'`:"NULL",h=`COMMENT ON COLUMN ${W}.${w} IS ${N}`;await $.db.unsafe(h)}}let A=[],B={};if($.dbDialect==="mysql")B=await sZ($,J);for(let L of G){let C=`idx_${L}`;if($.dbDialect==="mysql"&&B[C])continue;let T=EJ($.dbDialect,J,C,L,"create");A.push($.db.unsafe(T))}for(let[L,C]of Object.entries(Z)){let T=f(L);if(C.index===!0&&C.unique!==!0){let w=`idx_${T}`;if($.dbDialect==="mysql"&&B[w])continue;let D=EJ($.dbDialect,J,w,T,"create");A.push($.db.unsafe(D))}}if(A.length>0)await Promise.all(A)}async function lH($,J,Z){let G=await z1($,J),X=await sZ($,J),Y=!1,W=[],Q=[],V=[],O=[];for(let[L,C]of Object.entries(Z)){let T=f(L);if(G[T]){let w=V1($.dbDialect,G[T],C);if(w.length>0){for(let v of w){let p=$1[v.type]||"\u672A\u77E5";q.debug(` ~ \u4FEE\u6539 ${T} ${p}: ${v.current} -> ${v.expected}`)}if(YJ(C.type)&&G[T].max&&typeof C.max==="number"){if(G[T].max>C.max)q.warn(`[\u8DF3\u8FC7\u5371\u9669\u53D8\u66F4] ${J}.${T} \u957F\u5EA6\u6536\u7F29 ${G[T].max} -> ${C.max} \u5DF2\u88AB\u8DF3\u8FC7\uFF08\u9700\u624B\u52A8\u5904\u7406\uFF09`)}let D=w.some((v)=>v.type==="datatype"),E=w.some((v)=>v.type==="length"),N=w.every((v)=>v.type==="default"),h=w.some((v)=>v.type==="default");if(D){let v=w.find((u0)=>u0.type==="datatype"),p=String(v?.current||"").toLowerCase(),l=NJ($.dbDialect)[C.type]?.toLowerCase()||"";if(!Q1(p,l)){let u0=[`\u7981\u6B62\u5B57\u6BB5\u7C7B\u578B\u53D8\u66F4: ${J}.${T}`,`\u5F53\u524D\u7C7B\u578B: ${v?.current}`,`\u76EE\u6807\u7C7B\u578B: ${v?.expected}`,"\u8BF4\u660E: \u4EC5\u5141\u8BB8\u5BBD\u5316\u578B\u53D8\u66F4\uFF08\u5982 INT->BIGINT, VARCHAR->TEXT\uFF09\uFF0C\u5176\u4ED6\u7C7B\u578B\u53D8\u66F4\u9700\u8981\u624B\u52A8\u5904\u7406"].join(`
|
|
12
|
+
`);throw Error(u0)}q.debug(`[\u517C\u5BB9\u7C7B\u578B\u53D8\u66F4] ${J}.${T} ${p} -> ${l}`)}if(h){let v=HJ(C.default??null,C.type),p=null;if(v!=="null")p=DJ(v,C.type).trim().replace(/^DEFAULT\s+/,"");if(p!==null&&p!==""){if($.dbDialect==="postgresql"){let i=X0($.dbDialect,T);V.push(`ALTER COLUMN ${i} SET DEFAULT ${p}`)}else if($.dbDialect==="mysql"&&N){if(C.type!=="text"){let i=X0($.dbDialect,T);V.push(`ALTER COLUMN ${i} SET DEFAULT ${p}`)}}}}if(!N){let v=!1;if(E&&YJ(C.type)&&G[T].max&&typeof C.max==="number"){if(G[T].max>C.max)v=!0}if(!v)Q.push(uZ($.dbDialect,L,C,!1))}Y=!0}}else W.push(uZ($.dbDialect,L,C,!0)),Y=!0}let K=WJ.filter((L)=>L.name!=="id").map((L)=>L.name);for(let L of K)if(!G[L]){let C=Y1($.dbDialect,L);if(C)q.debug(` + \u65B0\u589E\u7CFB\u7EDF\u5B57\u6BB5 ${L}`),W.push(`ADD COLUMN ${C}`),Y=!0}for(let L of mZ){let C=`idx_${L}`;if((G[L]||K.includes(L))&&!X[C])O.push({action:"create",indexName:C,fieldName:L}),Y=!0}for(let[L,C]of Object.entries(Z)){let T=f(L),w=`idx_${T}`;if(C.index&&!C.unique&&!X[w])O.push({action:"create",indexName:w,fieldName:T}),Y=!0;else if(!C.index&&X[w]&&X[w].length===1)O.push({action:"drop",indexName:w,fieldName:T}),Y=!0}let A=[];if($.dbDialect==="postgresql"){let L=X0($.dbDialect,J);for(let[C,T]of Object.entries(Z)){let w=f(C),D=X0($.dbDialect,w);if(G[w]){let E=G[w].comment||"",N=T.name&&T.name!=="null"?String(T.name):"";if(N!==E){let h=N.replace(/'/g,"''");A.push(`COMMENT ON COLUMN ${L}.${D} IS ${N?`'${h}'`:"NULL"}`),Y=!0}}}}Y=W.length>0||Q.length>0||V.length>0||O.length>0||A.length>0;let B={changed:Y,addClauses:W,modifyClauses:Q,defaultClauses:V,indexActions:O,commentActions:A};if(B.changed)await oH($,J,Z,B);return B}var M1=($,J=Bun.nanoseconds())=>{let Z=(J-$)/1e6;if(Z<1000)return`${Z.toFixed(2)} \u6BEB\u79D2`;else return`${(Z/1000).toFixed(2)} \u79D2`};function K1($){let J=$||{},Z=J.BUN_WORKER_ID,G=J.PM2_INSTANCE_ID;if(Z!==void 0)return{role:Z===""?"primary":"worker",instanceId:Z||"0",env:"bun-cluster"};if(G!==void 0)return{role:G==="0"?"primary":"worker",instanceId:G,env:"pm2-cluster"};return{role:"primary",instanceId:null,env:"standalone"}}q$();q$();import{existsSync as rH,readdirSync as iH}from"fs";gZ();n0();var _1=()=>{let $=new Map,J=(Z,G,X)=>{if(!rH(Z))return;let Y=iH(Z,{withFileTypes:!0});for(let W of Y){if(W.name.startsWith("_"))continue;if(!BJ(Z,W))continue;let Q=JJ(Z,W.name),V={source:G,sourceName:X,name:W.name,camelName:F$(W.name),rootDir:Q,fullPath:Q};$.set(W.name,V)}};return J(d(d0,"node_modules","@befly-addon"),"addon","\u7EC4\u4EF6"),J(mX,"app","\u9879\u76EE"),Array.from($.values())};AJ();var tH={name:"auth",enable:!0,deps:["cors"],handler:async($,J)=>{let Z=J.req.headers.get("authorization");if(Z&&Z.startsWith("Bearer ")){let G=Z.substring(7);try{let X=await $.jwt.verify(G);J.user=X,QX(X.id,X.roleCode,X.nickname,X.roleType)}catch{J.user={}}}else J.user={}}},A1=tH;var aH={name:"cors",enable:!0,deps:[],handler:async($,J)=>{let Z=J.req,X=Object.assign({},{origin:"*",methods:"GET, POST, OPTIONS",allowedHeaders:"Content-Type, Authorization, authorization, token",exposedHeaders:"Content-Range, X-Content-Range, Authorization, authorization, token",maxAge:86400,credentials:"true"},$.config&&$.config.cors?$.config.cors:{}),Y=LJ(Z,X);if(J.corsHeaders=Y,Z.method==="OPTIONS"){J.response=new Response(null,{status:204,headers:Y});return}}},F1=aH;var eH=":A-Za-z_\\u00C0-\\u00D6\\u00D8-\\u00F6\\u00F8-\\u02FF\\u0370-\\u037D\\u037F-\\u1FFF\\u200C-\\u200D\\u2070-\\u218F\\u2C00-\\u2FEF\\u3001-\\uD7FF\\uF900-\\uFDCF\\uFDF0-\\uFFFD\\-.\\d\\u00B7\\u0300-\\u036F\\u203F-\\u2040",$Q="[:A-Za-z_\\u00C0-\\u00D6\\u00D8-\\u00F6\\u00F8-\\u02FF\\u0370-\\u037D\\u037F-\\u1FFF\\u200C-\\u200D\\u2070-\\u218F\\u2C00-\\u2FEF\\u3001-\\uD7FF\\uF900-\\uFDCF\\uFDF0-\\uFFFD]["+eH+"]*",JQ=new RegExp("^"+$Q+"$");function kJ($,J){let Z=[],G=J.exec($);while(G){let X=[];X.startIndex=J.lastIndex-G[0].length;let Y=G.length;for(let W=0;W<Y;W++)X.push(G[W]);Z.push(X),G=J.exec($)}return Z}var c$=function($){let J=JQ.exec($);return!(J===null||typeof J>"u")};function R1($){return typeof $<"u"}var ZQ={allowBooleanAttributes:!1,unpairedTags:[]};function P1($,J){J=Object.assign({},ZQ,J);let Z=[],G=!1,X=!1;if($[0]==="\uFEFF")$=$.substr(1);for(let Y=0;Y<$.length;Y++)if($[Y]==="<"&&$[Y+1]==="?"){if(Y+=2,Y=j1($,Y),Y.err)return Y}else if($[Y]==="<"){let W=Y;if(Y++,$[Y]==="!"){Y=q1($,Y);continue}else{let Q=!1;if($[Y]==="/")Q=!0,Y++;let V="";for(;Y<$.length&&$[Y]!==">"&&$[Y]!==" "&&$[Y]!=="\t"&&$[Y]!==`
|
|
13
|
+
`&&$[Y]!=="\r";Y++)V+=$[Y];if(V=V.trim(),V[V.length-1]==="/")V=V.substring(0,V.length-1),Y--;if(!zQ(V)){let A;if(V.trim().length===0)A="Invalid space after '<'.";else A="Tag '"+V+"' is an invalid name.";return Y0("InvalidTag",A,s0($,Y))}let O=YQ($,Y);if(O===!1)return Y0("InvalidAttr","Attributes for '"+V+"' have open quote.",s0($,Y));let K=O.value;if(Y=O.index,K[K.length-1]==="/"){let A=Y-K.length;K=K.substring(0,K.length-1);let B=B1(K,J);if(B===!0)G=!0;else return Y0(B.err.code,B.err.msg,s0($,A+B.err.line))}else if(Q)if(!O.tagClosed)return Y0("InvalidTag","Closing tag '"+V+"' doesn't have proper closing.",s0($,Y));else if(K.trim().length>0)return Y0("InvalidTag","Closing tag '"+V+"' can't have attributes or invalid starting.",s0($,W));else if(Z.length===0)return Y0("InvalidTag","Closing tag '"+V+"' has not been opened.",s0($,W));else{let A=Z.pop();if(V!==A.tagName){let B=s0($,A.tagStartPos);return Y0("InvalidTag","Expected closing tag '"+A.tagName+"' (opened in line "+B.line+", col "+B.col+") instead of closing tag '"+V+"'.",s0($,W))}if(Z.length==0)X=!0}else{let A=B1(K,J);if(A!==!0)return Y0(A.err.code,A.err.msg,s0($,Y-K.length+A.err.line));if(X===!0)return Y0("InvalidXml","Multiple possible root nodes found.",s0($,Y));else if(J.unpairedTags.indexOf(V)!==-1);else Z.push({tagName:V,tagStartPos:W});G=!0}for(Y++;Y<$.length;Y++)if($[Y]==="<")if($[Y+1]==="!"){Y++,Y=q1($,Y);continue}else if($[Y+1]==="?"){if(Y=j1($,++Y),Y.err)return Y}else break;else if($[Y]==="&"){let A=QQ($,Y);if(A==-1)return Y0("InvalidChar","char '&' is not expected.",s0($,Y));Y=A}else if(X===!0&&!I1($[Y]))return Y0("InvalidXml","Extra text at the end",s0($,Y));if($[Y]==="<")Y--}}else{if(I1($[Y]))continue;return Y0("InvalidChar","char '"+$[Y]+"' is not expected.",s0($,Y))}if(!G)return Y0("InvalidXml","Start tag expected.",1);else if(Z.length==1)return Y0("InvalidTag","Unclosed tag '"+Z[0].tagName+"'.",s0($,Z[0].tagStartPos));else if(Z.length>0)return Y0("InvalidXml","Invalid '"+JSON.stringify(Z.map((Y)=>Y.tagName),null,4).replace(/\r?\n/g,"")+"' found.",{line:1,col:1});return!0}function I1($){return $===" "||$==="\t"||$===`
|
|
14
|
+
`||$==="\r"}function j1($,J){let Z=J;for(;J<$.length;J++)if($[J]=="?"||$[J]==" "){let G=$.substr(Z,J-Z);if(J>5&&G==="xml")return Y0("InvalidXml","XML declaration allowed only at the start of the document.",s0($,J));else if($[J]=="?"&&$[J+1]==">"){J++;break}else continue}return J}function q1($,J){if($.length>J+5&&$[J+1]==="-"&&$[J+2]==="-"){for(J+=3;J<$.length;J++)if($[J]==="-"&&$[J+1]==="-"&&$[J+2]===">"){J+=2;break}}else if($.length>J+8&&$[J+1]==="D"&&$[J+2]==="O"&&$[J+3]==="C"&&$[J+4]==="T"&&$[J+5]==="Y"&&$[J+6]==="P"&&$[J+7]==="E"){let Z=1;for(J+=8;J<$.length;J++)if($[J]==="<")Z++;else if($[J]===">"){if(Z--,Z===0)break}}else if($.length>J+9&&$[J+1]==="["&&$[J+2]==="C"&&$[J+3]==="D"&&$[J+4]==="A"&&$[J+5]==="T"&&$[J+6]==="A"&&$[J+7]==="["){for(J+=8;J<$.length;J++)if($[J]==="]"&&$[J+1]==="]"&&$[J+2]===">"){J+=2;break}}return J}var GQ='"',XQ="'";function YQ($,J){let Z="",G="",X=!1;for(;J<$.length;J++){if($[J]===GQ||$[J]===XQ)if(G==="")G=$[J];else if(G!==$[J]);else G="";else if($[J]===">"){if(G===""){X=!0;break}}Z+=$[J]}if(G!=="")return!1;return{value:Z,index:J,tagClosed:X}}var WQ=new RegExp(`(\\s*)([^\\s=]+)(\\s*=)?(\\s*(['"])(([\\s\\S])*?)\\5)?`,"g");function B1($,J){let Z=kJ($,WQ),G={};for(let X=0;X<Z.length;X++){if(Z[X][1].length===0)return Y0("InvalidAttr","Attribute '"+Z[X][2]+"' has no space in starting.",QJ(Z[X]));else if(Z[X][3]!==void 0&&Z[X][4]===void 0)return Y0("InvalidAttr","Attribute '"+Z[X][2]+"' is without value.",QJ(Z[X]));else if(Z[X][3]===void 0&&!J.allowBooleanAttributes)return Y0("InvalidAttr","boolean attribute '"+Z[X][2]+"' is not allowed.",QJ(Z[X]));let Y=Z[X][2];if(!UQ(Y))return Y0("InvalidAttr","Attribute '"+Y+"' is an invalid name.",QJ(Z[X]));if(!G.hasOwnProperty(Y))G[Y]=1;else return Y0("InvalidAttr","Attribute '"+Y+"' is repeated.",QJ(Z[X]))}return!0}function HQ($,J){let Z=/\d/;if($[J]==="x")J++,Z=/[\da-fA-F]/;for(;J<$.length;J++){if($[J]===";")return J;if(!$[J].match(Z))break}return-1}function QQ($,J){if(J++,$[J]===";")return-1;if($[J]==="#")return J++,HQ($,J);let Z=0;for(;J<$.length;J++,Z++){if($[J].match(/\w/)&&Z<20)continue;if($[J]===";")break;return-1}return J}function Y0($,J,Z){return{err:{code:$,msg:J,line:Z.line||Z,col:Z.col}}}function UQ($){return c$($)}function zQ($){return c$($)}function s0($,J){let Z=$.substring(0,J).split(/\r?\n/);return{line:Z.length,col:Z[Z.length-1].length+1}}function QJ($){return $.startIndex+$[1].length}var VQ={preserveOrder:!1,attributeNamePrefix:"@_",attributesGroupName:!1,textNodeName:"#text",ignoreAttributes:!0,removeNSPrefix:!1,allowBooleanAttributes:!1,parseTagValue:!0,parseAttributeValue:!1,trimValues:!0,cdataPropName:!1,numberParseOptions:{hex:!0,leadingZeros:!0,eNotation:!0},tagValueProcessor:function($,J){return J},attributeValueProcessor:function($,J){return J},stopNodes:[],alwaysCreateTextNode:!1,isArray:()=>!1,commentPropName:!1,unpairedTags:[],processEntities:!0,htmlEntities:!1,ignoreDeclaration:!1,ignorePiTags:!1,transformTagName:!1,transformAttributeName:!1,updateTag:function($,J,Z){return $},captureMetaData:!1},L1=function($){return Object.assign({},VQ,$)};var yJ;if(typeof Symbol!=="function")yJ="@@xmlMetadata";else yJ=Symbol("XML Node Metadata");class i0{constructor($){this.tagname=$,this.child=[],this[":@"]={}}add($,J){if($==="__proto__")$="#__proto__";this.child.push({[$]:J})}addChild($,J){if($.tagname==="__proto__")$.tagname="#__proto__";if($[":@"]&&Object.keys($[":@"]).length>0)this.child.push({[$.tagname]:$.child,[":@"]:$[":@"]});else this.child.push({[$.tagname]:$.child});if(J!==void 0)this.child[this.child.length-1][yJ]={startIndex:J}}static getMetaDataSymbol(){return yJ}}class xJ{constructor($){this.suppressValidationErr=!$}readDocType($,J){let Z={};if($[J+3]==="O"&&$[J+4]==="C"&&$[J+5]==="T"&&$[J+6]==="Y"&&$[J+7]==="P"&&$[J+8]==="E"){J=J+9;let G=1,X=!1,Y=!1,W="";for(;J<$.length;J++)if($[J]==="<"&&!Y){if(X&&E$($,"!ENTITY",J)){J+=7;let Q,V;if([Q,V,J]=this.readEntityExp($,J+1,this.suppressValidationErr),V.indexOf("&")===-1)Z[Q]={regx:RegExp(`&${Q};`,"g"),val:V}}else if(X&&E$($,"!ELEMENT",J)){J+=8;let{index:Q}=this.readElementExp($,J+1);J=Q}else if(X&&E$($,"!ATTLIST",J))J+=8;else if(X&&E$($,"!NOTATION",J)){J+=9;let{index:Q}=this.readNotationExp($,J+1,this.suppressValidationErr);J=Q}else if(E$($,"!--",J))Y=!0;else throw Error("Invalid DOCTYPE");G++,W=""}else if($[J]===">"){if(Y){if($[J-1]==="-"&&$[J-2]==="-")Y=!1,G--}else G--;if(G===0)break}else if($[J]==="[")X=!0;else W+=$[J];if(G!==0)throw Error("Unclosed DOCTYPE")}else throw Error("Invalid Tag instead of DOCTYPE");return{entities:Z,i:J}}readEntityExp($,J){J=l0($,J);let Z="";while(J<$.length&&!/\s/.test($[J])&&$[J]!=='"'&&$[J]!=="'")Z+=$[J],J++;if(UJ(Z),J=l0($,J),!this.suppressValidationErr){if($.substring(J,J+6).toUpperCase()==="SYSTEM")throw Error("External entities are not supported");else if($[J]==="%")throw Error("Parameter entities are not supported")}let G="";return[J,G]=this.readIdentifierVal($,J,"entity"),J--,[Z,G,J]}readNotationExp($,J){J=l0($,J);let Z="";while(J<$.length&&!/\s/.test($[J]))Z+=$[J],J++;!this.suppressValidationErr&&UJ(Z),J=l0($,J);let G=$.substring(J,J+6).toUpperCase();if(!this.suppressValidationErr&&G!=="SYSTEM"&&G!=="PUBLIC")throw Error(`Expected SYSTEM or PUBLIC, found "${G}"`);J+=G.length,J=l0($,J);let X=null,Y=null;if(G==="PUBLIC"){if([J,X]=this.readIdentifierVal($,J,"publicIdentifier"),J=l0($,J),$[J]==='"'||$[J]==="'")[J,Y]=this.readIdentifierVal($,J,"systemIdentifier")}else if(G==="SYSTEM"){if([J,Y]=this.readIdentifierVal($,J,"systemIdentifier"),!this.suppressValidationErr&&!Y)throw Error("Missing mandatory system identifier for SYSTEM notation")}return{notationName:Z,publicIdentifier:X,systemIdentifier:Y,index:--J}}readIdentifierVal($,J,Z){let G="",X=$[J];if(X!=='"'&&X!=="'")throw Error(`Expected quoted string, found "${X}"`);J++;while(J<$.length&&$[J]!==X)G+=$[J],J++;if($[J]!==X)throw Error(`Unterminated ${Z} value`);return J++,[J,G]}readElementExp($,J){J=l0($,J);let Z="";while(J<$.length&&!/\s/.test($[J]))Z+=$[J],J++;if(!this.suppressValidationErr&&!c$(Z))throw Error(`Invalid element name: "${Z}"`);J=l0($,J);let G="";if($[J]==="E"&&E$($,"MPTY",J))J+=4;else if($[J]==="A"&&E$($,"NY",J))J+=2;else if($[J]==="("){J++;while(J<$.length&&$[J]!==")")G+=$[J],J++;if($[J]!==")")throw Error("Unterminated content model")}else if(!this.suppressValidationErr)throw Error(`Invalid Element Expression, found "${$[J]}"`);return{elementName:Z,contentModel:G.trim(),index:J}}readAttlistExp($,J){J=l0($,J);let Z="";while(J<$.length&&!/\s/.test($[J]))Z+=$[J],J++;UJ(Z),J=l0($,J);let G="";while(J<$.length&&!/\s/.test($[J]))G+=$[J],J++;if(!UJ(G))throw Error(`Invalid attribute name: "${G}"`);J=l0($,J);let X="";if($.substring(J,J+8).toUpperCase()==="NOTATION"){if(X="NOTATION",J+=8,J=l0($,J),$[J]!=="(")throw Error(`Expected '(', found "${$[J]}"`);J++;let W=[];while(J<$.length&&$[J]!==")"){let Q="";while(J<$.length&&$[J]!=="|"&&$[J]!==")")Q+=$[J],J++;if(Q=Q.trim(),!UJ(Q))throw Error(`Invalid notation name: "${Q}"`);if(W.push(Q),$[J]==="|")J++,J=l0($,J)}if($[J]!==")")throw Error("Unterminated list of notations");J++,X+=" ("+W.join("|")+")"}else{while(J<$.length&&!/\s/.test($[J]))X+=$[J],J++;let W=["CDATA","ID","IDREF","IDREFS","ENTITY","ENTITIES","NMTOKEN","NMTOKENS"];if(!this.suppressValidationErr&&!W.includes(X.toUpperCase()))throw Error(`Invalid attribute type: "${X}"`)}J=l0($,J);let Y="";if($.substring(J,J+8).toUpperCase()==="#REQUIRED")Y="#REQUIRED",J+=8;else if($.substring(J,J+7).toUpperCase()==="#IMPLIED")Y="#IMPLIED",J+=7;else[J,Y]=this.readIdentifierVal($,J,"ATTLIST");return{elementName:Z,attributeName:G,attributeType:X,defaultValue:Y,index:J}}}var l0=($,J)=>{while(J<$.length&&/\s/.test($[J]))J++;return J};function E$($,J,Z){for(let G=0;G<J.length;G++)if(J[G]!==$[Z+G+1])return!1;return!0}function UJ($){if(c$($))return $;else throw Error(`Invalid entity name ${$}`)}var OQ=/^[-+]?0x[a-fA-F0-9]+$/,MQ=/^([\-\+])?(0*)([0-9]*(\.[0-9]*)?)$/,KQ={hex:!0,leadingZeros:!0,decimalPoint:".",eNotation:!0};function oZ($,J={}){if(J=Object.assign({},KQ,J),!$||typeof $!=="string")return $;let Z=$.trim();if(J.skipLike!==void 0&&J.skipLike.test(Z))return $;else if($==="0")return 0;else if(J.hex&&OQ.test(Z))return RQ(Z,16);else if(Z.includes("e")||Z.includes("E"))return AQ($,Z,J);else{let G=MQ.exec(Z);if(G){let X=G[1]||"",Y=G[2],W=FQ(G[3]),Q=X?$[Y.length+1]===".":$[Y.length]===".";if(!J.leadingZeros&&(Y.length>1||Y.length===1&&!Q))return $;else{let V=Number(Z),O=String(V);if(V===0)return V;if(O.search(/[eE]/)!==-1)if(J.eNotation)return V;else return $;else if(Z.indexOf(".")!==-1)if(O==="0")return V;else if(O===W)return V;else if(O===`${X}${W}`)return V;else return $;let K=Y?W:Z;if(Y)return K===O||X+K===O?V:$;else return K===O||K===X+O?V:$}}else return $}}var _Q=/^([-+])?(0*)(\d*(\.\d*)?[eE][-\+]?\d+)$/;function AQ($,J,Z){if(!Z.eNotation)return $;let G=J.match(_Q);if(G){let X=G[1]||"",Y=G[3].indexOf("e")===-1?"E":"e",W=G[2],Q=X?$[W.length+1]===Y:$[W.length]===Y;if(W.length>1&&Q)return $;else if(W.length===1&&(G[3].startsWith(`.${Y}`)||G[3][0]===Y))return Number(J);else if(Z.leadingZeros&&!Q)return J=(G[1]||"")+G[3],Number(J);else return $}else return $}function FQ($){if($&&$.indexOf(".")!==-1){if($=$.replace(/0+$/,""),$===".")$="0";else if($[0]===".")$="0"+$;else if($[$.length-1]===".")$=$.substring(0,$.length-1);return $}return $}function RQ($,J){if(parseInt)return parseInt($,J);else if(Number.parseInt)return Number.parseInt($,J);else if(window&&window.parseInt)return window.parseInt($,J);else throw Error("parseInt, Number.parseInt, window.parseInt are not supported")}function lZ($){if(typeof $==="function")return $;if(Array.isArray($))return(J)=>{for(let Z of $){if(typeof Z==="string"&&J===Z)return!0;if(Z instanceof RegExp&&Z.test(J))return!0}};return()=>!1}class fJ{constructor($){if(this.options=$,this.currentNode=null,this.tagsNodeStack=[],this.docTypeEntities={},this.lastEntities={apos:{regex:/&(apos|#39|#x27);/g,val:"'"},gt:{regex:/&(gt|#62|#x3E);/g,val:">"},lt:{regex:/&(lt|#60|#x3C);/g,val:"<"},quot:{regex:/&(quot|#34|#x22);/g,val:'"'}},this.ampEntity={regex:/&(amp|#38|#x26);/g,val:"&"},this.htmlEntities={space:{regex:/&(nbsp|#160);/g,val:" "},cent:{regex:/&(cent|#162);/g,val:"\xA2"},pound:{regex:/&(pound|#163);/g,val:"\xA3"},yen:{regex:/&(yen|#165);/g,val:"\xA5"},euro:{regex:/&(euro|#8364);/g,val:"\u20AC"},copyright:{regex:/&(copy|#169);/g,val:"\xA9"},reg:{regex:/&(reg|#174);/g,val:"\xAE"},inr:{regex:/&(inr|#8377);/g,val:"\u20B9"},num_dec:{regex:/&#([0-9]{1,7});/g,val:(J,Z)=>String.fromCodePoint(Number.parseInt(Z,10))},num_hex:{regex:/&#x([0-9a-fA-F]{1,6});/g,val:(J,Z)=>String.fromCodePoint(Number.parseInt(Z,16))}},this.addExternalEntities=IQ,this.parseXml=LQ,this.parseTextData=jQ,this.resolveNameSpace=qQ,this.buildAttributesMap=PQ,this.isItStopNode=EQ,this.replaceEntitiesValue=CQ,this.readStopNodeData=NQ,this.saveTextToParentTag=wQ,this.addChild=SQ,this.ignoreAttributesFn=lZ(this.options.ignoreAttributes),this.options.stopNodes&&this.options.stopNodes.length>0){this.stopNodesExact=new Set,this.stopNodesWildcard=new Set;for(let J=0;J<this.options.stopNodes.length;J++){let Z=this.options.stopNodes[J];if(typeof Z!=="string")continue;if(Z.startsWith("*."))this.stopNodesWildcard.add(Z.substring(2));else this.stopNodesExact.add(Z)}}}}function IQ($){let J=Object.keys($);for(let Z=0;Z<J.length;Z++){let G=J[Z];this.lastEntities[G]={regex:new RegExp("&"+G+";","g"),val:$[G]}}}function jQ($,J,Z,G,X,Y,W){if($!==void 0){if(this.options.trimValues&&!G)$=$.trim();if($.length>0){if(!W)$=this.replaceEntitiesValue($);let Q=this.options.tagValueProcessor(J,$,Z,X,Y);if(Q===null||Q===void 0)return $;else if(typeof Q!==typeof $||Q!==$)return Q;else if(this.options.trimValues)return iZ($,this.options.parseTagValue,this.options.numberParseOptions);else if($.trim()===$)return iZ($,this.options.parseTagValue,this.options.numberParseOptions);else return $}}}function qQ($){if(this.options.removeNSPrefix){let J=$.split(":"),Z=$.charAt(0)==="/"?"/":"";if(J[0]==="xmlns")return"";if(J.length===2)$=Z+J[1]}return $}var BQ=new RegExp(`([^\\s=]+)\\s*(=\\s*(['"])([\\s\\S]*?)\\3)?`,"gm");function PQ($,J){if(this.options.ignoreAttributes!==!0&&typeof $==="string"){let Z=kJ($,BQ),G=Z.length,X={};for(let Y=0;Y<G;Y++){let W=this.resolveNameSpace(Z[Y][1]);if(this.ignoreAttributesFn(W,J))continue;let Q=Z[Y][4],V=this.options.attributeNamePrefix+W;if(W.length){if(this.options.transformAttributeName)V=this.options.transformAttributeName(V);if(V==="__proto__")V="#__proto__";if(Q!==void 0){if(this.options.trimValues)Q=Q.trim();Q=this.replaceEntitiesValue(Q);let O=this.options.attributeValueProcessor(W,Q,J);if(O===null||O===void 0)X[V]=Q;else if(typeof O!==typeof Q||O!==Q)X[V]=O;else X[V]=iZ(Q,this.options.parseAttributeValue,this.options.numberParseOptions)}else if(this.options.allowBooleanAttributes)X[V]=!0}}if(!Object.keys(X).length)return;if(this.options.attributesGroupName){let Y={};return Y[this.options.attributesGroupName]=X,Y}return X}}var LQ=function($){$=$.replace(/\r\n?/g,`
|
|
15
|
+
`);let J=new i0("!xml"),Z=J,G="",X="",Y=new xJ(this.options.processEntities);for(let W=0;W<$.length;W++)if($[W]==="<")if($[W+1]==="/"){let V=T$($,">",W,"Closing Tag is not closed."),O=$.substring(W+2,V).trim();if(this.options.removeNSPrefix){let B=O.indexOf(":");if(B!==-1)O=O.substr(B+1)}if(this.options.transformTagName)O=this.options.transformTagName(O);if(Z)G=this.saveTextToParentTag(G,Z,X);let K=X.substring(X.lastIndexOf(".")+1);if(O&&this.options.unpairedTags.indexOf(O)!==-1)throw Error(`Unpaired tag can not be used as closing tag: </${O}>`);let A=0;if(K&&this.options.unpairedTags.indexOf(K)!==-1)A=X.lastIndexOf(".",X.lastIndexOf(".")-1),this.tagsNodeStack.pop();else A=X.lastIndexOf(".");X=X.substring(0,A),Z=this.tagsNodeStack.pop(),G="",W=V}else if($[W+1]==="?"){let V=rZ($,W,!1,"?>");if(!V)throw Error("Pi Tag is not closed.");if(G=this.saveTextToParentTag(G,Z,X),this.options.ignoreDeclaration&&V.tagName==="?xml"||this.options.ignorePiTags);else{let O=new i0(V.tagName);if(O.add(this.options.textNodeName,""),V.tagName!==V.tagExp&&V.attrExpPresent)O[":@"]=this.buildAttributesMap(V.tagExp,X);this.addChild(Z,O,X,W)}W=V.closeIndex+1}else if($.substr(W+1,3)==="!--"){let V=T$($,"-->",W+4,"Comment is not closed.");if(this.options.commentPropName){let O=$.substring(W+4,V-2);G=this.saveTextToParentTag(G,Z,X),Z.add(this.options.commentPropName,[{[this.options.textNodeName]:O}])}W=V}else if($.substr(W+1,2)==="!D"){let V=Y.readDocType($,W);this.docTypeEntities=V.entities,W=V.i}else if($.substr(W+1,2)==="!["){let V=T$($,"]]>",W,"CDATA is not closed.")-2,O=$.substring(W+9,V);G=this.saveTextToParentTag(G,Z,X);let K=this.parseTextData(O,Z.tagname,X,!0,!1,!0,!0);if(K==null)K="";if(this.options.cdataPropName)Z.add(this.options.cdataPropName,[{[this.options.textNodeName]:O}]);else Z.add(this.options.textNodeName,K);W=V+2}else{let V=rZ($,W,this.options.removeNSPrefix),O=V.tagName,K=V.rawTagName,A=V.tagExp,B=V.attrExpPresent,L=V.closeIndex;if(this.options.transformTagName){let w=this.options.transformTagName(O);if(A===O)A=w;O=w}if(Z&&G){if(Z.tagname!=="!xml")G=this.saveTextToParentTag(G,Z,X,!1)}let C=Z;if(C&&this.options.unpairedTags.indexOf(C.tagname)!==-1)Z=this.tagsNodeStack.pop(),X=X.substring(0,X.lastIndexOf("."));if(O!==J.tagname)X+=X?"."+O:O;let T=W;if(this.isItStopNode(this.stopNodesExact,this.stopNodesWildcard,X,O)){let w="";if(A.length>0&&A.lastIndexOf("/")===A.length-1){if(O[O.length-1]==="/")O=O.substr(0,O.length-1),X=X.substr(0,X.length-1),A=O;else A=A.substr(0,A.length-1);W=V.closeIndex}else if(this.options.unpairedTags.indexOf(O)!==-1)W=V.closeIndex;else{let E=this.readStopNodeData($,K,L+1);if(!E)throw Error(`Unexpected end of ${K}`);W=E.i,w=E.tagContent}let D=new i0(O);if(O!==A&&B)D[":@"]=this.buildAttributesMap(A,X);if(w)w=this.parseTextData(w,O,X,!0,B,!0,!0);X=X.substr(0,X.lastIndexOf(".")),D.add(this.options.textNodeName,w),this.addChild(Z,D,X,T)}else{if(A.length>0&&A.lastIndexOf("/")===A.length-1){if(O[O.length-1]==="/")O=O.substr(0,O.length-1),X=X.substr(0,X.length-1),A=O;else A=A.substr(0,A.length-1);if(this.options.transformTagName){let D=this.options.transformTagName(O);if(A===O)A=D;O=D}let w=new i0(O);if(O!==A&&B)w[":@"]=this.buildAttributesMap(A,X);this.addChild(Z,w,X,T),X=X.substr(0,X.lastIndexOf("."))}else{let w=new i0(O);if(this.tagsNodeStack.push(Z),O!==A&&B)w[":@"]=this.buildAttributesMap(A,X);this.addChild(Z,w,X,T),Z=w}G="",W=L}}else G+=$[W];return J.child};function SQ($,J,Z,G){if(!this.options.captureMetaData)G=void 0;let X=this.options.updateTag(J.tagname,Z,J[":@"]);if(X===!1);else if(typeof X==="string")J.tagname=X,$.addChild(J,G);else $.addChild(J,G)}var CQ=function($){if(this.options.processEntities){for(let J in this.docTypeEntities){let Z=this.docTypeEntities[J];$=$.replace(Z.regx,Z.val)}for(let J in this.lastEntities){let Z=this.lastEntities[J];$=$.replace(Z.regex,Z.val)}if(this.options.htmlEntities)for(let J in this.htmlEntities){let Z=this.htmlEntities[J];$=$.replace(Z.regex,Z.val)}$=$.replace(this.ampEntity.regex,this.ampEntity.val)}return $};function wQ($,J,Z,G){if($){if(G===void 0)G=J.child.length===0;if($=this.parseTextData($,J.tagname,Z,!1,J[":@"]?Object.keys(J[":@"]).length!==0:!1,G),$!==void 0&&$!=="")J.add(this.options.textNodeName,$);$=""}return $}function EQ($,J,Z,G){if(J&&J.has(G))return!0;if($&&$.has(Z))return!0;return!1}function TQ($,J,Z=">"){let G,X="";for(let Y=J;Y<$.length;Y++){let W=$[Y];if(G){if(W===G)G=""}else if(W==='"'||W==="'")G=W;else if(W===Z[0])if(Z[1]){if($[Y+1]===Z[1])return{data:X,index:Y}}else return{data:X,index:Y};else if(W==="\t")W=" ";X+=W}}function T$($,J,Z,G){let X=$.indexOf(J,Z);if(X===-1)throw Error(G);else return X+J.length-1}function rZ($,J,Z,G=">"){let X=TQ($,J+1,G);if(!X)return;let{data:Y,index:W}=X,Q=Y.search(/\s/),V=Y,O=!0;if(Q!==-1)V=Y.substring(0,Q),Y=Y.substring(Q+1).trimStart();let K=V;if(Z){let A=V.indexOf(":");if(A!==-1)V=V.substr(A+1),O=V!==X.data.substr(A+1)}return{tagName:V,tagExp:Y,closeIndex:W,attrExpPresent:O,rawTagName:K}}function NQ($,J,Z){let G=Z,X=1;for(;Z<$.length;Z++)if($[Z]==="<")if($[Z+1]==="/"){let Y=T$($,">",Z,`${J} is not closed`);if($.substring(Z+2,Y).trim()===J){if(X--,X===0)return{tagContent:$.substring(G,Z),i:Y}}Z=Y}else if($[Z+1]==="?")Z=T$($,"?>",Z+1,"StopNode is not closed.");else if($.substr(Z+1,3)==="!--")Z=T$($,"-->",Z+3,"StopNode is not closed.");else if($.substr(Z+1,2)==="![")Z=T$($,"]]>",Z,"StopNode is not closed.")-2;else{let Y=rZ($,Z,">");if(Y){if((Y&&Y.tagName)===J&&Y.tagExp[Y.tagExp.length-1]!=="/")X++;Z=Y.closeIndex}}}function iZ($,J,Z){if(J&&typeof $==="string"){let G=$.trim();if(G==="true")return!0;else if(G==="false")return!1;else return oZ($,Z)}else if(R1($))return $;else return""}var tZ=i0.getMetaDataSymbol();function aZ($,J){return S1($,J)}function S1($,J,Z){let G,X={};for(let Y=0;Y<$.length;Y++){let W=$[Y],Q=vQ(W),V="";if(Z===void 0)V=Q;else V=Z+"."+Q;if(Q===J.textNodeName)if(G===void 0)G=W[Q];else G+=""+W[Q];else if(Q===void 0)continue;else if(W[Q]){let O=S1(W[Q],J,V),K=kQ(O,J);if(W[tZ]!==void 0)O[tZ]=W[tZ];if(W[":@"])DQ(O,W[":@"],V,J);else if(Object.keys(O).length===1&&O[J.textNodeName]!==void 0&&!J.alwaysCreateTextNode)O=O[J.textNodeName];else if(Object.keys(O).length===0)if(J.alwaysCreateTextNode)O[J.textNodeName]="";else O="";if(X[Q]!==void 0&&X.hasOwnProperty(Q)){if(!Array.isArray(X[Q]))X[Q]=[X[Q]];X[Q].push(O)}else if(J.isArray(Q,V,K))X[Q]=[O];else X[Q]=O}}if(typeof G==="string"){if(G.length>0)X[J.textNodeName]=G}else if(G!==void 0)X[J.textNodeName]=G;return X}function vQ($){let J=Object.keys($);for(let Z=0;Z<J.length;Z++){let G=J[Z];if(G!==":@")return G}}function DQ($,J,Z,G){if(J){let X=Object.keys(J),Y=X.length;for(let W=0;W<Y;W++){let Q=X[W];if(G.isArray(Q,Z+"."+Q,!0,!0))$[Q]=[J[Q]];else $[Q]=J[Q]}}}function kQ($,J){let{textNodeName:Z}=J,G=Object.keys($).length;if(G===0)return!0;if(G===1&&($[Z]||typeof $[Z]==="boolean"||$[Z]===0))return!0;return!1}class zJ{constructor($){this.externalEntities={},this.options=L1($)}parse($,J){if(typeof $!=="string"&&$.toString)$=$.toString();else if(typeof $!=="string")throw Error("XML data is accepted in String or Bytes[] form.");if(J){if(J===!0)J={};let X=P1($,J);if(X!==!0)throw Error(`${X.err.msg}:${X.err.line}:${X.err.col}`)}let Z=new fJ(this.options);Z.addExternalEntities(this.externalEntities);let G=Z.parseXml($);if(this.options.preserveOrder||G===void 0)return G;else return aZ(G,this.options)}addEntity($,J){if(J.indexOf("&")!==-1)throw Error("Entity value can't have '&'");else if($.indexOf("&")!==-1||$.indexOf(";")!==-1)throw Error("An entity must be set without '&' and ';'. Eg. use '#xD' for '
'");else if(J==="&")throw Error("An entity with value '&' is not permitted");else this.externalEntities[$]=J}static getMetaDataSymbol(){return i0.getMetaDataSymbol()}}var yQ=new zJ,xQ={name:"parser",enable:!0,deps:["auth"],handler:async($,J)=>{if(!J.api)return;if(J.api.rawBody){J.body={};return}if(J.req.method==="GET"){let Z=new URL(J.req.url),G=Object.fromEntries(Z.searchParams);J.body=G}else if(J.req.method==="POST"){let Z=J.req.headers.get("content-type")||"",G=new URL(J.req.url),X=Object.fromEntries(G.searchParams);try{if(Z.includes("application/json")){let Y=await J.req.json(),W={...X,...Y};J.body=W}else if(Z.includes("application/xml")||Z.includes("text/xml")){let Y=await J.req.text(),W=yQ.parse(Y),Q=Object.keys(W)[0],V=Q&&typeof W[Q]==="object"?W[Q]:W,O={...X,...V};J.body=O}else{J.response=B$(J,"\u65E0\u6548\u7684\u8BF7\u6C42\u53C2\u6570\u683C\u5F0F",1,null,{location:"content-type",value:Z},"parser");return}}catch{J.response=B$(J,"\u65E0\u6548\u7684\u8BF7\u6C42\u53C2\u6570\u683C\u5F0F",1,null,{location:"body",reason:Z.includes("application/json")?"invalid_json":Z.includes("xml")?"invalid_xml":"invalid_body"},"parser");return}}}},C1=xQ;a();var fQ={name:"permission",enable:!0,deps:["validator"],handler:async($,J)=>{if(!J.api)return;if(J.api.auth===!1)return;if(typeof J.user.id!=="number"){J.response=B$(J,"\u672A\u767B\u5F55",1,null,null,"auth");return}if(J.user.roleCode==="dev")return;let Z=J.route,G=J.user.roleCode,X=!1;if(G&&$.redis)try{let Y=G0.roleApis(G);X=await $.redis.sismember(Y,Z)}catch(Y){q.error({event:"hook_permission_redis_error",apiPath:Z,roleCode:G,err:Y,msg:"hook permission redis error"}),X=!1}if(!X){let Y=typeof J.api.name==="string"&&J.api.name.length>0?J.api.name:null,W=typeof Z==="string"&&Z.length>0?Z:null,Q=Y?Y:W?W:"\u672A\u77E5\u63A5\u53E3";J.response=B$(J,`\u65E0\u6743\u8BBF\u95EE ${Q} \u63A5\u53E3`,1,null,{apiLabel:Q},"permission");return}}},w1=fQ;var eZ={number:"^\\d+$",integer:"^-?\\d+$",float:"^-?\\d+(\\.\\d+)?$",positive:"^[1-9]\\d*$",negative:"^-\\d+$",zero:"^0$",word:"^[a-zA-Z]+$",alphanumeric:"^[a-zA-Z0-9]+$",alphanumeric_:"^[a-zA-Z0-9_]+$",alphanumericDash_:"^[a-zA-Z0-9_-]+$",lowercase:"^[a-z]+$",uppercase:"^[A-Z]+$",chinese:"^[\\u4e00-\\u9fa5]+$",chineseWord:"^[\\u4e00-\\u9fa5a-zA-Z]+$",email:"^[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\\.[a-zA-Z]{2,}$",phone:"^1[3-9]\\d{9}$",telephone:"^0\\d{2,3}-?\\d{7,8}$",url:"^https?://",ip:"^((25[0-5]|2[0-4]\\d|[01]?\\d\\d?)\\.){3}(25[0-5]|2[0-4]\\d|[01]?\\d\\d?)$",ipv6:"^([0-9a-fA-F]{1,4}:){7}[0-9a-fA-F]{1,4}$",domain:"^(?:[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?\\.)+[a-zA-Z]{2,}$",uuid:"^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$",hex:"^[0-9a-fA-F]+$",base64:"^[A-Za-z0-9+/=]+$",md5:"^[a-f0-9]{32}$",sha1:"^[a-f0-9]{40}$",sha256:"^[a-f0-9]{64}$",date:"^\\d{4}-\\d{2}-\\d{2}$",time:"^\\d{2}:\\d{2}:\\d{2}$",datetime:"^\\d{4}-\\d{2}-\\d{2}T\\d{2}:\\d{2}:\\d{2}",year:"^\\d{4}$",month:"^(0[1-9]|1[0-2])$",day:"^(0[1-9]|[12]\\d|3[01])$",variable:"^[a-zA-Z_][a-zA-Z0-9_]*$",constant:"^[A-Z][A-Z0-9_]*$",package:"^[a-z][a-z0-9-]*$",idCard:"^\\d{17}[\\dXx]$",passport:"^[a-zA-Z0-9]{5,17}$",bankCard:"^\\d{16,19}$",wechat:"^[a-zA-Z][a-zA-Z0-9_-]{5,19}$",qq:"^[1-9]\\d{4,10}$",alipay:"^(1[3-9]\\d{9}|[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\\.[a-zA-Z]{2,})$",username:"^[a-zA-Z][a-zA-Z0-9_]{3,19}$",nickname:"^[\\u4e00-\\u9fa5a-zA-Z0-9]{2,20}$",passwordWeak:"^.{6,}$",passwordMedium:"^(?=.*[a-zA-Z])(?=.*\\d).{8,}$",passwordStrong:"^(?=.*[a-z])(?=.*[A-Z])(?=.*\\d)(?=.*[!@#$%^&*]).{8,}$",licensePlate:"^[\u4EAC\u6D25\u6CAA\u6E1D\u5180\u8C6B\u4E91\u8FBD\u9ED1\u6E58\u7696\u9C81\u65B0\u82CF\u6D59\u8D63\u9102\u6842\u7518\u664B\u8499\u9655\u5409\u95FD\u8D35\u7CA4\u9752\u85CF\u5DDD\u5B81\u743C\u4F7F\u9886][A-Z][A-HJ-NP-Z0-9]{4,5}[A-HJ-NP-Z0-9\u6302\u5B66\u8B66\u6E2F\u6FB3]$",postalCode:"^\\d{6}$",semver:"^\\d+\\.\\d+\\.\\d+(-[a-zA-Z0-9.]+)?(\\+[a-zA-Z0-9.]+)?$",colorHex:"^#([0-9a-fA-F]{3}|[0-9a-fA-F]{6})$",empty:"^$",notempty:".+"},E1=new Map;function gQ($){if($.startsWith("@")){let J=$.slice(1);return eZ[J]||$}return $}function T1($,J){let Z=gQ($),G=`${Z}:${J||""}`,X=E1.get(G);if(!X)X=new RegExp(Z,J),E1.set(G,X);return X}n0();class $G{static validate($,J,Z=[]){let G={};if(!n($))return this.buildResult({_error:"\u6570\u636E\u5FC5\u987B\u662F\u5BF9\u8C61\u683C\u5F0F"});if(!n(J))return this.buildResult({_error:"\u9A8C\u8BC1\u89C4\u5219\u5FC5\u987B\u662F\u5BF9\u8C61\u683C\u5F0F"});let X=$,Y=J;for(let W of Z){let Q=X[W];if(Q===void 0||Q===null){let V=Y[W],O=n(V)&&typeof V.name==="string"?V.name:W;G[W]=`${O}\u4E3A\u5FC5\u586B\u9879`}}for(let[W,Q]of Object.entries(Y)){if(G[W])continue;if(X[W]===void 0&&!Z.includes(W))continue;if(!n(Q)){G[W]=`${W}\u9A8C\u8BC1\u89C4\u5219\u5FC5\u987B\u662F\u5BF9\u8C61\u683C\u5F0F`;continue}let{name:V,type:O}=Q;if(typeof V!=="string"||typeof O!=="string"){G[W]=`${W}\u9A8C\u8BC1\u89C4\u5219\u65E0\u6548`;continue}let K={name:V,type:O},A=Q.min;if(typeof A==="number"||A===null)K.min=A;let B=Q.max;if(typeof B==="number"||B===null)K.max=B;let L=Q.default;if(L===null||typeof L==="string"||typeof L==="number"||typeof L==="boolean"||Array.isArray(L)||n(L))K.default=L;let C=Q.detail;if(typeof C==="string")K.detail=C;let T=Q.index;if(typeof T==="boolean")K.index=T;let w=Q.unique;if(typeof w==="boolean")K.unique=w;let D=Q.nullable;if(typeof D==="boolean")K.nullable=D;let E=Q.unsigned;if(typeof E==="boolean")K.unsigned=E;let N=Q.regexp;if(typeof N==="string"||N===null)K.regexp=N;let h=this.checkField(X[W],K,W);if(h)G[W]=h}return this.buildResult(G)}static single($,J){let Z=H$(J),G=Z.type,X=Z.default;if($===void 0||$===null||$==="")return{value:this.defaultFor(G,X),error:null};let Y=this.convert($,G);if(Y.error)return{value:null,error:Y.error};let W=this.checkRule(Y.value,J);if(W)return{value:null,error:W};return{value:Y.value,error:null}}static buildResult($){let J=Object.values($),Z=Object.keys($),G=J.length>0;return{code:G?1:0,failed:G,firstError:G?J[0]??null:null,errors:J,errorFields:Z,fieldErrors:$}}static checkField($,J,Z){let G=J.name||Z,X=this.convert($,J.type);if(X.error)return`${G}${X.error}`;let Y=this.checkRule(X.value,J);return Y?`${G}${Y}`:null}static convert($,J){switch(J.toLowerCase()){case"number":if(typeof $==="number")return Number.isNaN($)||!isFinite($)?{value:null,error:"\u5FC5\u987B\u662F\u6709\u6548\u6570\u5B57"}:{value:$,error:null};if(typeof $==="string"){let Z=Number($);return Number.isNaN(Z)||!isFinite(Z)?{value:null,error:"\u5FC5\u987B\u662F\u6570\u5B57"}:{value:Z,error:null}}return{value:null,error:"\u5FC5\u987B\u662F\u6570\u5B57"};case"string":case"text":return typeof $==="string"?{value:$,error:null}:{value:null,error:"\u5FC5\u987B\u662F\u5B57\u7B26\u4E32"};case"array_string":case"array_text":return Array.isArray($)?{value:$,error:null}:{value:null,error:"\u5FC5\u987B\u662F\u6570\u7EC4"};case"array_number_string":case"array_number_text":if(!Array.isArray($))return{value:null,error:"\u5FC5\u987B\u662F\u6570\u7EC4"};for(let Z of $)if(typeof Z!=="number"||!isFinite(Z))return{value:null,error:"\u6570\u7EC4\u5143\u7D20\u5FC5\u987B\u662F\u6570\u5B57"};return{value:$,error:null};default:return{value:$,error:null}}}static checkRule($,J){let Z=H$(J),G=Z.type,X=Z.min,Y=Z.max,W=Z.regexp,Q=this.resolveRegex(W);switch(G.toLowerCase()){case"number":if(typeof $!=="number")return"\u5FC5\u987B\u662F\u6570\u5B57";if(X!==null&&$<X)return`\u4E0D\u80FD\u5C0F\u4E8E${X}`;if(Y!==null&&Y>0&&$>Y)return`\u4E0D\u80FD\u5927\u4E8E${Y}`;if(Q&&!this.testRegex(Q,String($)))return"\u683C\u5F0F\u4E0D\u6B63\u786E";break;case"string":case"text":if(typeof $!=="string")return"\u5FC5\u987B\u662F\u5B57\u7B26\u4E32";if(X!==null&&$.length<X)return`\u957F\u5EA6\u4E0D\u80FD\u5C11\u4E8E${X}\u4E2A\u5B57\u7B26`;if(Y!==null&&Y>0&&$.length>Y)return`\u957F\u5EA6\u4E0D\u80FD\u8D85\u8FC7${Y}\u4E2A\u5B57\u7B26`;if(Q&&!this.testRegex(Q,$))return"\u683C\u5F0F\u4E0D\u6B63\u786E";break;case"array_string":case"array_text":case"array_number_string":case"array_number_text":if(!Array.isArray($))return"\u5FC5\u987B\u662F\u6570\u7EC4";if(X!==null&&$.length<X)return`\u81F3\u5C11\u9700\u8981${X}\u4E2A\u5143\u7D20`;if(Y!==null&&Y>0&&$.length>Y)return`\u6700\u591A\u53EA\u80FD\u6709${Y}\u4E2A\u5143\u7D20`;if(Q){for(let V of $)if(!this.testRegex(Q,String(V)))return"\u5143\u7D20\u683C\u5F0F\u4E0D\u6B63\u786E"}break}return null}static resolveRegex($){if(!$)return null;if($.startsWith("@")){let J=$.substring(1);return eZ[J]||$}return $}static testRegex($,J){try{return T1($).test(J)}catch{return!1}}static defaultFor($,J){if(J!==null&&J!==void 0){if(($==="array_string"||$==="array_text"||$==="array_number_string"||$==="array_number_text")&&typeof J==="string"){if(J==="[]")return[];try{let Z=JSON.parse(J);return Array.isArray(Z)?Z:[]}catch{return[]}}if($==="number"&&typeof J==="string"){let Z=Number(J);return isNaN(Z)?0:Z}return J}switch($.toLowerCase()){case"number":return 0;case"array_string":case"array_text":case"array_number_string":case"array_number_text":return[];default:return""}}}n0();var hQ={name:"validator",enable:!0,deps:["parser"],handler:async($,J)=>{if(!J.api)return;if(!J.api.fields)return;if(n(J.api.fields)){let G=n(J.body)?J.body:{},X={};for(let[Y,W]of Object.entries(J.api.fields)){let Q=H$(W),V=G[Y];if(V===void 0){let O=f(Y);if(G[O]!==void 0)V=G[O]}if(V===void 0&&Q.default!==null)V=Q.default;if(V!==void 0)X[Y]=V}J.body=X}let Z=$G.validate(J.body,J.api.fields,J.api.required||[]);if(Z.code!==0){J.response=B$(J,Z.firstError||"\u53C2\u6570\u9A8C\u8BC1\u5931\u8D25",1,null,Z.fieldErrors,"validator");return}}},N1=hQ;a();class JG{db;redis;constructor($){this.db=$.db,this.redis=$.redis}assertApiPathname($,J){if(typeof $!=="string")throw Error(`${J} \u5FC5\u987B\u662F\u5B57\u7B26\u4E32`);let Z=$.trim();if(!Z)throw Error(`${J} \u4E0D\u5141\u8BB8\u4E3A\u7A7A\u5B57\u7B26\u4E32`);if(/^(GET|POST|PUT|PATCH|DELETE|OPTIONS|HEAD)\b/i.test(Z))throw Error(`${J} \u4E0D\u5141\u8BB8\u5305\u542B method \u524D\u7F00\uFF0C\u5E94\u4E3A url.pathname\uFF08\u4F8B\u5982 /api/app/xxx\uFF09`);if(!Z.startsWith("/"))throw Error(`${J} \u5FC5\u987B\u662F pathname\uFF08\u4EE5 / \u5F00\u5934\uFF09`);if(Z.includes(" "))throw Error(`${J} \u4E0D\u5141\u8BB8\u5305\u542B\u7A7A\u683C`);return Z}assertApiPathList($,J){if($===null||$===void 0)return[];let Z=$;if(typeof Z==="string"){let X=Z.trim();if(X===""||X==="null")return[];if(X.startsWith("[")&&X.endsWith("]"))try{Z=JSON.parse(X)}catch{throw Error(`\u89D2\u8272\u6743\u9650\u6570\u636E\u4E0D\u5408\u6CD5\uFF1Aaddon_admin_role.apis JSON \u89E3\u6790\u5931\u8D25\uFF0CroleCode=${J}`)}}if(!Array.isArray(Z))throw Error(`\u89D2\u8272\u6743\u9650\u6570\u636E\u4E0D\u5408\u6CD5\uFF1Aaddon_admin_role.apis \u5FC5\u987B\u662F\u5B57\u7B26\u4E32\u6570\u7EC4\u6216 JSON \u6570\u7EC4\u5B57\u7B26\u4E32\uFF0CroleCode=${J}\uFF0Ctype=${typeof Z}`);let G=[];for(let X of Z)G.push(this.assertApiPathname(X,`\u89D2\u8272\u6743\u9650\u6570\u636E\u4E0D\u5408\u6CD5\uFF1Aaddon_admin_role.apis \u5143\u7D20\uFF0CroleCode=${J}`));return G}async cacheApis(){try{if(!(await this.db.tableExists("addon_admin_api")).data){q.warn("\u26A0\uFE0F \u63A5\u53E3\u8868\u4E0D\u5B58\u5728\uFF0C\u8DF3\u8FC7\u63A5\u53E3\u7F13\u5B58");return}let J=await this.db.getAll({table:"addon_admin_api"});if(await this.redis.setObject(G0.apisAll(),J.data.lists)===null)q.warn("\u26A0\uFE0F \u63A5\u53E3\u7F13\u5B58\u5931\u8D25")}catch($){q.error({err:$,msg:"\u26A0\uFE0F \u63A5\u53E3\u7F13\u5B58\u5F02\u5E38"})}}async cacheMenus(){try{if(!(await this.db.tableExists("addon_admin_menu")).data){q.warn("\u26A0\uFE0F \u83DC\u5355\u8868\u4E0D\u5B58\u5728\uFF0C\u8DF3\u8FC7\u83DC\u5355\u7F13\u5B58");return}let J=await this.db.getAll({table:"addon_admin_menu"});if(await this.redis.setObject(G0.menusAll(),J.data.lists)===null)q.warn("\u26A0\uFE0F \u83DC\u5355\u7F13\u5B58\u5931\u8D25")}catch($){q.warn({err:$,msg:"\u26A0\uFE0F \u83DC\u5355\u7F13\u5B58\u5F02\u5E38"})}}async rebuildRoleApiPermissions(){try{if(!(await this.db.tableExists("addon_admin_role")).data){q.warn("\u26A0\uFE0F \u89D2\u8272\u8868\u4E0D\u5B58\u5728\uFF0C\u8DF3\u8FC7\u89D2\u8272\u6743\u9650\u7F13\u5B58");return}let J=await this.db.getAll({table:"addon_admin_role",fields:["code","apis"]}),Z=new Map;for(let W of J.data.lists){if(!W?.code)continue;let Q=this.assertApiPathList(W.apis,W.code);Z.set(W.code,Q)}let G=Array.from(Z.keys());if(G.length===0){q.info("\u2705 \u6CA1\u6709\u9700\u8981\u7F13\u5B58\u7684\u89D2\u8272\u6743\u9650");return}let X=G.map((W)=>G0.roleApis(W));await this.redis.delBatch(X);let Y=[];for(let W of G){let Q=Z.get(W)||[],V=Array.from(new Set(Q)).sort();if(V.length>0)Y.push({key:G0.roleApis(W),members:V})}if(Y.length>0)await this.redis.saddBatch(Y)}catch($){throw q.error({err:$,msg:"\u26A0\uFE0F \u89D2\u8272\u6743\u9650\u7F13\u5B58\u5F02\u5E38\uFF08\u5C06\u963B\u65AD\u542F\u52A8\uFF09"}),$}}async refreshRoleApiPermissions($,J){if(!$||typeof $!=="string")throw Error("roleCode \u5FC5\u987B\u662F\u975E\u7A7A\u5B57\u7B26\u4E32");if(!Array.isArray(J))throw Error("apiPaths \u5FC5\u987B\u662F\u6570\u7EC4");let Z=J.map((Y)=>this.assertApiPathname(Y,`refreshRoleApiPermissions: apiPaths \u5143\u7D20\uFF0CroleCode=${$}`)),G=G0.roleApis($);if(Z.length===0){await this.redis.del(G);return}let X=Array.from(new Set(Z));if(await this.redis.del(G),X.length>0)await this.redis.sadd(G,X)}async cacheAll(){await this.cacheApis(),await this.cacheMenus(),await this.rebuildRoleApiPermissions()}async getApis(){try{return await this.redis.getObject(G0.apisAll())||[]}catch($){return q.error({err:$,msg:"\u83B7\u53D6\u63A5\u53E3\u7F13\u5B58\u5931\u8D25"}),[]}}async getMenus(){try{return await this.redis.getObject(G0.menusAll())||[]}catch($){return q.error({err:$,msg:"\u83B7\u53D6\u83DC\u5355\u7F13\u5B58\u5931\u8D25"}),[]}}async getRolePermissions($){try{return await this.redis.smembers(G0.roleApis($))||[]}catch(J){return q.error({err:J,roleCode:$,msg:"\u83B7\u53D6\u89D2\u8272\u6743\u9650\u7F13\u5B58\u5931\u8D25"}),[]}}async checkRolePermission($,J){try{let Z=this.assertApiPathname(J,"checkRolePermission: apiPath");return await this.redis.sismember(G0.roleApis($),Z)}catch(Z){return q.error({err:Z,roleCode:$,msg:"\u68C0\u67E5\u89D2\u8272\u6743\u9650\u5931\u8D25"}),!1}}async deleteRolePermissions($){try{if(await this.redis.del(G0.roleApis($))>0)return q.info(`\u2705 \u5DF2\u5220\u9664\u89D2\u8272 ${$} \u7684\u6743\u9650\u7F13\u5B58`),!0;return!1}catch(J){return q.error({err:J,roleCode:$,msg:"\u5220\u9664\u89D2\u8272\u6743\u9650\u7F13\u5B58\u5931\u8D25"}),!1}}}var bQ={name:"cache",enable:!0,deps:["logger","redis","db"],async handler($){if(!$.db)throw Error("\u7F13\u5B58\u521D\u59CB\u5316\u5931\u8D25\uFF1Actx.db \u672A\u521D\u59CB\u5316");if(!$.redis)throw Error("\u7F13\u5B58\u521D\u59CB\u5316\u5931\u8D25\uFF1Actx.redis \u672A\u521D\u59CB\u5316");return new JG({db:$.db,redis:$.redis})}},v1=bQ;var cQ={name:"cipher",enable:!0,deps:[],handler:()=>{return g$}},D1=cQ;var pQ={name:"config",enable:!0,deps:[],handler:($)=>{return $.config}},k1=pQ;function gJ($,J=["id","pid","sort"]){if(!$||!Array.isArray($))return $;return $.map((Z)=>{let G=Z,X={};for(let[Y,W]of Object.entries(G))X[Y]=W;for(let[Y,W]of Object.entries(X)){if(W===void 0||W===null)continue;if((J.includes(Y)||Y.endsWith("Id")||Y.endsWith("_id")||Y.endsWith("At")||Y.endsWith("_at"))&&typeof W==="string"){let V=Number(W);if(!Number.isNaN(V))X[Y]=V}}return X})}function ZG($){return $!==null&&typeof $==="object"&&!Array.isArray($)}function uQ($){return Array.isArray($)}function N$($,J={}){let{pickKeys:Z,omitKeys:G,keepValues:X,excludeValues:Y,keepMap:W}=J,Q=(V)=>{let O={},K=Object.keys(V);if(Z&&Z.length)K=K.filter((A)=>Z.includes(A));if(G&&G.length)K=K.filter((A)=>!G.includes(A));for(let A of K){let B=V[A];if(W&&A in W){if(Object.is(W[A],B)){O[A]=B;continue}}if(X&&X.length&&!X.includes(B))continue;if(Y&&Y.length&&Y.includes(B))continue;O[A]=B}return O};if(uQ($))return $.map((V)=>ZG(V)?Q(V):V).filter((V)=>{if(ZG(V))return Object.keys(V).length>0;return!0});if(ZG($))return Q($);return $}function nQ($){if($===null)return!0;return typeof $==="string"||typeof $==="number"||typeof $==="boolean"}function mQ($){if(!$||typeof $!=="object")return!1;if($ instanceof Date)return!1;if(Array.isArray($))return!1;return!0}function GG($){if(nQ($))return!0;if(Array.isArray($)){for(let J of $)if(!GG(J))return!1;return!0}if(mQ($)){for(let J of Object.values($)){if(J===void 0)continue;if(!GG(J))return!1}return!0}return!1}function y1($){if(!Array.isArray($))return[];let J=[];for(let Z of $){if(Z===null){J.push(null);continue}if(typeof Z==="string"||typeof Z==="number"||typeof Z==="boolean"){J.push(Z);continue}if(typeof Z==="bigint"){J.push(String(Z));continue}if(Z instanceof Date){J.push(Z);continue}if(GG(Z)){J.push(Z);continue}J.push(String(Z))}return J}function v$($){if(typeof $==="number")return $;if(typeof $==="bigint")return Number($);return 0}n0();n0();class c{static parseTableRef($){if(typeof $!=="string")throw Error(`tableRef \u5FC5\u987B\u662F\u5B57\u7B26\u4E32 (tableRef: ${String($)})`);let J=$.trim();if(!J)throw Error("tableRef \u4E0D\u80FD\u4E3A\u7A7A");let Z=J.split(/\s+/).filter((Q)=>Q.length>0);if(Z.length===0)throw Error("tableRef \u4E0D\u80FD\u4E3A\u7A7A");if(Z.length>2)throw Error(`\u4E0D\u652F\u6301\u7684\u8868\u5F15\u7528\u683C\u5F0F\uFF08\u5305\u542B\u8FC7\u591A\u7247\u6BB5\uFF09\u3002\u8BF7\u4F7F\u7528\u6700\u7B80\u5F62\u5F0F\uFF1Atable \u6216 table alias \u6216 schema.table \u6216 schema.table alias (tableRef: ${J})`);let G=Z[0];if(typeof G!=="string"||G.trim()==="")throw Error(`tableRef \u89E3\u6790\u5931\u8D25\uFF1A\u7F3A\u5C11\u8868\u540D (tableRef: ${J})`);let X=null;if(Z.length===2){let Q=Z[1];if(typeof Q!=="string"||Q.trim()==="")throw Error(`tableRef \u89E3\u6790\u5931\u8D25\uFF1A\u7F3A\u5C11 alias (tableRef: ${J})`);X=Q}let Y=G.split(".");if(Y.length>2)throw Error(`\u4E0D\u652F\u6301\u7684\u8868\u5F15\u7528\u683C\u5F0F\uFF08schema \u5C42\u7EA7\u8FC7\u6DF1\uFF09 (tableRef: ${J})`);if(Y.length===2){let Q=Y[0],V=Y[1];if(typeof Q!=="string"||Q.trim()==="")throw Error(`tableRef \u89E3\u6790\u5931\u8D25\uFF1Aschema \u4E3A\u7A7A (tableRef: ${J})`);if(typeof V!=="string"||V.trim()==="")throw Error(`tableRef \u89E3\u6790\u5931\u8D25\uFF1Atable \u4E3A\u7A7A (tableRef: ${J})`);return{schema:Q,table:V,alias:X}}let W=Y[0];if(typeof W!=="string"||W.trim()==="")throw Error(`tableRef \u89E3\u6790\u5931\u8D25\uFF1Atable \u4E3A\u7A7A (tableRef: ${J})`);return{schema:null,table:W,alias:X}}static normalizeTableRef($){let J=c.parseTableRef($),Z=J.schema?f(J.schema):null,G=f(J.table),X=Z?`${Z}.${G}`:G;if(J.alias)X=`${X} ${J.alias}`;return X}static getJoinMainQualifier($){let J=c.parseTableRef($);if(J.alias)return J.alias;return f(J.table)}static async fieldsToSnake($,J,Z){if(!J||!Array.isArray(J))return["*"];let G=c.validateAndClassifyFields(J);if(G.type==="all")return["*"];if(G.type==="include")return G.fields.map((X)=>{if(X.includes("(")||X.includes(" "))return X;return f(X)});if(G.type==="exclude"){let X=await Z($),Y=G.fields.map((Q)=>f(Q)),W=X.filter((Q)=>!Y.includes(Q));if(W.length===0)throw Error(`\u6392\u9664\u5B57\u6BB5\u540E\u6CA1\u6709\u5269\u4F59\u5B57\u6BB5\u53EF\u67E5\u8BE2\u3002\u8868: ${$}, \u6392\u9664: ${Y.join(", ")}`);return W}return["*"]}static validateAndClassifyFields($){if(!$||$.length===0)return{type:"all",fields:[]};if($.some((G)=>G==="*"))throw Error("fields \u4E0D\u652F\u6301 * \u661F\u53F7\uFF0C\u8BF7\u4F7F\u7528\u7A7A\u6570\u7EC4 [] \u6216\u4E0D\u4F20\u53C2\u6570\u8868\u793A\u67E5\u8BE2\u6240\u6709\u5B57\u6BB5");if($.some((G)=>!G||typeof G!=="string"||G.trim()===""))throw Error("fields \u4E0D\u80FD\u5305\u542B\u7A7A\u5B57\u7B26\u4E32\u6216\u65E0\u6548\u503C");let J=$.filter((G)=>!G.startsWith("!")),Z=$.filter((G)=>G.startsWith("!"));if(J.length>0&&Z.length===0)return{type:"include",fields:J};if(Z.length>0&&J.length===0)return{type:"exclude",fields:Z.map((X)=>X.substring(1))};throw Error(`fields \u4E0D\u80FD\u540C\u65F6\u5305\u542B\u666E\u901A\u5B57\u6BB5\u548C\u6392\u9664\u5B57\u6BB5\uFF08! \u5F00\u5934\uFF09\u3002\u53EA\u80FD\u4F7F\u7528\u4EE5\u4E0B3\u79CD\u65B9\u5F0F\u4E4B\u4E00\uFF1A
|
|
16
16
|
1. \u7A7A\u6570\u7EC4 [] \u6216\u4E0D\u4F20\uFF08\u67E5\u8BE2\u6240\u6709\uFF09
|
|
17
17
|
2. \u5168\u90E8\u6307\u5B9A\u5B57\u6BB5 ["id", "name"]
|
|
18
|
-
3. \u5168\u90E8\u6392\u9664\u5B57\u6BB5 ["!password", "!token"]`)}static orderByToSnake($){if(!$||!Array.isArray($))return $;return $.map((J)=>{if(typeof J!=="string"||!J.includes("#"))return J;let Z=J.split("#");if(Z.length!==2)return J;let X=Z[0],G=Z[1];if(typeof X!=="string"||typeof G!=="string")return J;return`${x(X.trim())}#${G.trim()}`})}static processJoinField($){if($.includes("(")||$==="*"||$.startsWith("`"))return $;if($.toUpperCase().includes(" AS ")){let J=$.split(/\s+AS\s+/i),Z=J[0],X=J[1];if(typeof Z!=="string"||typeof X!=="string")return $;return`${c.processJoinField(Z.trim())} AS ${X.trim()}`}if($.includes(".")){let J=$.split(".");if(J.length<2)return x($);if(J.some((G)=>G.trim()===""))return $;let Z=J[J.length-1],X=J.slice(0,J.length-1).join(".");if(typeof Z!=="string"||typeof X!=="string")return x($);return`${X.trim()}.${x(Z)}`}return x($)}static processJoinWhereKey($){if($==="$or"||$==="$and")return $;if($.includes("$")){let J=$.lastIndexOf("$"),Z=$.substring(0,J),X=$.substring(J);if(Z.includes(".")){let G=Z.split(".");if(G.length<2)return`${x(Z)}${X}`;if(G.some((Q)=>Q.trim()===""))return`${x(Z)}${X}`;let Y=G[G.length-1],W=G.slice(0,G.length-1).join(".");if(typeof Y!=="string"||typeof W!=="string")return`${x(Z)}${X}`;return`${W.trim()}.${x(Y)}${X}`}return`${x(Z)}${X}`}if($.includes(".")){let J=$.split(".");if(J.length<2)return x($);if(J.some((G)=>G.trim()===""))return x($);let Z=J[J.length-1],X=J.slice(0,J.length-1).join(".");if(typeof Z!=="string"||typeof X!=="string")return x($);return`${X.trim()}.${x(Z)}`}return x($)}static processJoinWhere($){if(!$||typeof $!=="object")return $;if(Array.isArray($))return $.map((Z)=>c.processJoinWhere(Z));let J={};for(let[Z,X]of Object.entries($)){let G=c.processJoinWhereKey(Z);if(Z==="$or"||Z==="$and")J[G]=Array.isArray(X)?X.map((Y)=>c.processJoinWhere(Y)):[];else if(typeof X==="object"&&X!==null&&!Array.isArray(X))J[G]=c.processJoinWhere(X);else J[G]=X}return J}static processJoinOrderBy($){if(!$||!Array.isArray($))return $;return $.map((J)=>{if(typeof J!=="string"||!J.includes("#"))return J;let Z=J.split("#");if(Z.length!==2)return J;let X=Z[0],G=Z[1];if(typeof X!=="string"||typeof G!=="string")return J;return`${c.processJoinField(X.trim())}#${G.trim()}`})}static addDefaultStateFilter($={},J,Z=!1){if(Object.keys($).some((Y)=>Y.startsWith("state")||Y.includes(".state")))return $;if(Z&&J){let Y={};for(let[W,Q]of Object.entries($))Y[W]=Q;return Y[`${J}.state$gt`]=0,Y}let G={};for(let[Y,W]of Object.entries($))G[Y]=W;return G.state$gt=0,G}static whereKeysToSnake($){if(!$||typeof $!=="object")return $;if(Array.isArray($))return $.map((Z)=>c.whereKeysToSnake(Z));let J={};for(let[Z,X]of Object.entries($)){if(Z==="$or"||Z==="$and"){J[Z]=Array.isArray(X)?X.map((Y)=>c.whereKeysToSnake(Y)):[];continue}if(Z.includes("$")){let Y=Z.lastIndexOf("$"),W=Z.substring(0,Y),Q=Z.substring(Y),z=x(W)+Q;J[z]=X;continue}let G=x(Z);if(typeof X==="object"&&X!==null&&!Array.isArray(X))J[G]=c.whereKeysToSnake(X);else J[G]=X}return J}static serializeArrayFields($){let J={};for(let[Z,X]of Object.entries($)){if(X===null||X===void 0){J[Z]=X;continue}if(Array.isArray(X)){J[Z]=JSON.stringify(X);continue}J[Z]=X}return J}static deserializeArrayFields($){if(!$)return null;let J={};for(let[Z,X]of Object.entries($))J[Z]=X;for(let[Z,X]of Object.entries(J)){if(typeof X!=="string")continue;if(X.startsWith("[")&&X.endsWith("]"))try{let G=JSON.parse(X);if(Array.isArray(G))J[Z]=G}catch{}}return J}static cleanAndSnakeAndSerializeWriteData($,J=[null,void 0]){let Z=N$($,{excludeValues:J}),X=tG(Z);return c.serializeArrayFields(X)}static stripSystemFieldsForWrite($,J){let Z={};for(let[X,G]of Object.entries($)){if(X==="id")continue;if(X==="created_at")continue;if(X==="updated_at")continue;if(X==="deleted_at")continue;if(!J.allowState&&X==="state")continue;Z[X]=G}return Z}static buildInsertRow($){let J=c.cleanAndSnakeAndSerializeWriteData($.data),Z=c.stripSystemFieldsForWrite(J,{allowState:!1}),X={};for(let[G,Y]of Object.entries(Z))X[G]=Y;return X.id=$.id,X.created_at=$.now,X.updated_at=$.now,X.state=1,X}static buildUpdateRow($){let J=c.cleanAndSnakeAndSerializeWriteData($.data),Z=c.stripSystemFieldsForWrite(J,{allowState:$.allowState}),X={};for(let[G,Y]of Object.entries(Z))X[G]=Y;return X.updated_at=$.now,X}static buildPartialUpdateData($){let J=c.cleanAndSnakeAndSerializeWriteData($.data);return c.stripSystemFieldsForWrite(J,{allowState:$.allowState})}}a();class W0{static SAFE_IDENTIFIER_RE=/^[a-zA-Z_][a-zA-Z0-9_]*$/;static assertNonEmptyString($,J){if(typeof $!=="string")throw Error(`${J} \u5FC5\u987B\u662F\u5B57\u7B26\u4E32 (value: ${String($)})`);if(!$.trim())throw Error(`${J} \u4E0D\u80FD\u4E3A\u7A7A`)}static assertNoUndefinedParam($,J){if($===void 0)throw Error(`${J} \u4E0D\u80FD\u4E3A undefined`)}static startsWithQuote($){let J=$.trim();return J.startsWith("`")||J.startsWith('"')}static isQuotedIdentPaired($){let J=$.trim();if(J.length<2)return!1;let Z=J[0],X=J[J.length-1];if(Z==="`"&&X==="`")return!0;if(Z==='"'&&X==='"')return!0;return!1}static assertPairedQuotedIdentIfStartsWithQuote($,J){if(W0.startsWithQuote($)&&!W0.isQuotedIdentPaired($))throw Error(`${J} \u5F15\u7528\u4E0D\u5B8C\u6574\uFF0C\u8BF7\u4F7F\u7528\u6210\u5BF9\u7684 \`...\` \u6216 "..." (value: ${$})`)}static assertSafeIdentifierPart($,J){if(!W0.SAFE_IDENTIFIER_RE.test($))throw Error(`\u65E0\u6548\u7684 ${J} \u6807\u8BC6\u7B26: ${$}`)}static assertSafeAlias($){if(W0.isQuotedIdentPaired($))return;if(!W0.SAFE_IDENTIFIER_RE.test($))throw Error(`\u65E0\u6548\u7684\u5B57\u6BB5\u522B\u540D: ${$}`)}static assertNoExprField($){if(typeof $!=="string")return;let J=$.trim();if(!J)return;if(J.includes("(")||J.includes(")"))throw Error(`\u5B57\u6BB5\u5305\u542B\u51FD\u6570/\u8868\u8FBE\u5F0F\uFF0C\u8BF7\u4F7F\u7528 selectRaw/whereRaw (field: ${J})`)}static assertNoUndefinedInRecord($,J){for(let[Z,X]of Object.entries($))if(X===void 0)throw Error(`${J} \u5B58\u5728 undefined \u5B57\u6BB5\u503C (field: ${Z})`)}static assertBatchInsertRowsConsistent($,J){if(!Array.isArray($))throw Error("\u6279\u91CF\u63D2\u5165 rows \u5FC5\u987B\u662F\u6570\u7EC4");if($.length===0)throw Error(`\u63D2\u5165\u6570\u636E\u4E0D\u80FD\u4E3A\u7A7A (table: ${J.table})`);let Z=$[0];if(!Z||typeof Z!=="object"||Array.isArray(Z))throw Error(`\u6279\u91CF\u63D2\u5165\u7684\u6BCF\u4E00\u884C\u5FC5\u987B\u662F\u5BF9\u8C61 (table: ${J.table}, rowIndex: 0)`);let X=Object.keys(Z);if(X.length===0)throw Error(`\u63D2\u5165\u6570\u636E\u5FC5\u987B\u81F3\u5C11\u6709\u4E00\u4E2A\u5B57\u6BB5 (table: ${J.table})`);let G=new Set(X);for(let Y=0;Y<$.length;Y++){let W=$[Y];if(!W||typeof W!=="object"||Array.isArray(W))throw Error(`\u6279\u91CF\u63D2\u5165\u7684\u6BCF\u4E00\u884C\u5FC5\u987B\u662F\u5BF9\u8C61 (table: ${J.table}, rowIndex: ${Y})`);let Q=Object.keys(W);if(Q.length!==X.length)throw Error(`\u6279\u91CF\u63D2\u5165\u6BCF\u884C\u5B57\u6BB5\u5FC5\u987B\u4E00\u81F4 (table: ${J.table}, rowIndex: ${Y})`);for(let z of Q)if(!G.has(z))throw Error(`\u6279\u91CF\u63D2\u5165\u6BCF\u884C\u5B57\u6BB5\u5FC5\u987B\u4E00\u81F4 (table: ${J.table}, rowIndex: ${Y}, extraField: ${z})`);for(let z of X){if(!(z in W))throw Error(`\u6279\u91CF\u63D2\u5165\u7F3A\u5C11\u5B57\u6BB5 (table: ${J.table}, rowIndex: ${Y}, field: ${z})`);W0.assertNoUndefinedParam(W[z],`\u6279\u91CF\u63D2\u5165\u5B57\u6BB5\u503C (table: ${J.table}, rowIndex: ${Y}, field: ${z})`)}}return X}}var g={QUOTE_IDENT_NEED_STRING:($)=>`quoteIdent \u9700\u8981\u5B57\u7B26\u4E32\u7C7B\u578B\u6807\u8BC6\u7B26 (identifier: ${String($)})`,IDENT_EMPTY:"SQL \u6807\u8BC6\u7B26\u4E0D\u80FD\u4E3A\u7A7A",FIELD_EXPR_NOT_ALLOWED:($)=>`\u5B57\u6BB5\u5305\u542B\u51FD\u6570/\u8868\u8FBE\u5F0F\uFF0C\u8BF7\u4F7F\u7528 selectRaw/whereRaw (field: ${$})`,FIELD_INVALID:($)=>`\u5B57\u6BB5\u683C\u5F0F\u975E\u6CD5\uFF0C\u8BF7\u4F7F\u7528\u7B80\u5355\u5B57\u6BB5\u540D\u6216\u5B89\u5168\u5F15\u7528\uFF0C\u590D\u6742\u8868\u8FBE\u5F0F\u8BF7\u4F7F\u7528 selectRaw/whereRaw (field: ${$})`,FROM_EMPTY:"FROM \u8868\u540D\u4E0D\u80FD\u4E3A\u7A7A",FROM_NEED_NON_EMPTY:($)=>`FROM \u8868\u540D\u5FC5\u987B\u662F\u975E\u7A7A\u5B57\u7B26\u4E32 (table: ${String($)})`,FROM_REQUIRED:"FROM \u8868\u540D\u662F\u5FC5\u9700\u7684",COUNT_NEED_FROM:"COUNT \u9700\u8981 FROM \u8868\u540D",TABLE_REF_TOO_MANY_PARTS:($)=>`\u4E0D\u652F\u6301\u7684\u8868\u5F15\u7528\u683C\u5F0F\uFF08\u5305\u542B\u8FC7\u591A\u7247\u6BB5\uFF09\u3002\u8BF7\u4F7F\u7528 fromRaw \u663E\u5F0F\u4F20\u5165\u590D\u6742\u8868\u8FBE\u5F0F (table: ${$})`,TABLE_REF_SCHEMA_TOO_DEEP:($)=>`\u4E0D\u652F\u6301\u7684\u8868\u5F15\u7528\u683C\u5F0F\uFF08schema \u5C42\u7EA7\u8FC7\u6DF1\uFF09\u3002\u8BF7\u4F7F\u7528 fromRaw (table: ${$})`,SCHEMA_QUOTE_NOT_PAIRED:($)=>`schema \u6807\u8BC6\u7B26\u5F15\u7528\u4E0D\u5B8C\u6574\uFF0C\u8BF7\u4F7F\u7528\u6210\u5BF9\u7684 \`...\` \u6216 "..." (schema: ${$})`,TABLE_QUOTE_NOT_PAIRED:($)=>`table \u6807\u8BC6\u7B26\u5F15\u7528\u4E0D\u5B8C\u6574\uFF0C\u8BF7\u4F7F\u7528\u6210\u5BF9\u7684 \`...\` \u6216 "..." (table: ${$})`,SELECT_FIELDS_INVALID:"SELECT \u5B57\u6BB5\u5FC5\u987B\u662F\u5B57\u7B26\u4E32\u6216\u6570\u7EC4",SELECT_RAW_NEED_NON_EMPTY:($)=>`selectRaw \u9700\u8981\u975E\u7A7A\u5B57\u7B26\u4E32 (expr: ${String($)})`,FROM_RAW_NEED_NON_EMPTY:($)=>`fromRaw \u9700\u8981\u975E\u7A7A\u5B57\u7B26\u4E32 (tableExpr: ${String($)})`,WHERE_RAW_NEED_NON_EMPTY:($)=>`whereRaw \u9700\u8981\u975E\u7A7A\u5B57\u7B26\u4E32 (sql: ${String($)})`,WHERE_VALUE_REQUIRED:"where(field, value) \u4E0D\u5141\u8BB8\u7701\u7565 value\u3002\u82E5\u9700\u4F20\u5165\u539F\u59CB WHERE\uFF0C\u8BF7\u4F7F\u7528 whereRaw",JOIN_NEED_STRING:($,J)=>`JOIN \u8868\u540D\u548C\u6761\u4EF6\u5FC5\u987B\u662F\u5B57\u7B26\u4E32 (table: ${String($)}, on: ${String(J)})`,ORDER_BY_NEED_ARRAY:'orderBy \u5FC5\u987B\u662F\u5B57\u7B26\u4E32\u6570\u7EC4\uFF0C\u683C\u5F0F\u4E3A "\u5B57\u6BB5#\u65B9\u5411"',ORDER_BY_ITEM_NEED_HASH:($)=>`orderBy \u5B57\u6BB5\u5FC5\u987B\u662F "\u5B57\u6BB5#\u65B9\u5411" \u683C\u5F0F\u7684\u5B57\u7B26\u4E32\uFF08\u4F8B\u5982\uFF1A"name#ASC", "id#DESC"\uFF09 (item: ${String($)})`,ORDER_BY_FIELD_EMPTY:($)=>`orderBy \u4E2D\u5B57\u6BB5\u540D\u4E0D\u80FD\u4E3A\u7A7A (item: ${$})`,ORDER_BY_DIR_INVALID:($)=>`ORDER BY \u65B9\u5411\u5FC5\u987B\u662F ASC \u6216 DESC (direction: ${$})`,LIMIT_MUST_NON_NEGATIVE:($)=>`LIMIT \u6570\u91CF\u5FC5\u987B\u662F\u975E\u8D1F\u6570 (count: ${String($)})`,OFFSET_MUST_NON_NEGATIVE:($)=>`OFFSET \u5FC5\u987B\u662F\u975E\u8D1F\u6570 (offset: ${String($)})`,OFFSET_COUNT_MUST_NON_NEGATIVE:($)=>`OFFSET \u5FC5\u987B\u662F\u975E\u8D1F\u6570 (count: ${String($)})`,INSERT_NEED_TABLE:($)=>`INSERT \u9700\u8981\u8868\u540D (table: ${String($)})`,INSERT_NEED_DATA:($,J)=>`INSERT \u9700\u8981\u6570\u636E (table: ${String($)}, data: ${JSON.stringify(J)})`,INSERT_NEED_AT_LEAST_ONE_FIELD:($)=>`\u63D2\u5165\u6570\u636E\u5FC5\u987B\u81F3\u5C11\u6709\u4E00\u4E2A\u5B57\u6BB5 (table: ${$})`,UPDATE_NEED_TABLE:"UPDATE \u9700\u8981\u8868\u540D",UPDATE_NEED_OBJECT:"UPDATE \u9700\u8981\u6570\u636E\u5BF9\u8C61",UPDATE_NEED_AT_LEAST_ONE_FIELD:"\u66F4\u65B0\u6570\u636E\u5FC5\u987B\u81F3\u5C11\u6709\u4E00\u4E2A\u5B57\u6BB5",UPDATE_NEED_WHERE:"\u4E3A\u5B89\u5168\u8D77\u89C1\uFF0CUPDATE \u9700\u8981 WHERE \u6761\u4EF6",DELETE_NEED_TABLE:"DELETE \u9700\u8981\u8868\u540D",DELETE_NEED_WHERE:"\u4E3A\u5B89\u5168\u8D77\u89C1\uFF0CDELETE \u9700\u8981 WHERE \u6761\u4EF6",TO_DELETE_IN_NEED_TABLE:($)=>`toDeleteInSql \u9700\u8981\u975E\u7A7A\u8868\u540D (table: ${String($)})`,TO_DELETE_IN_NEED_ID_FIELD:($)=>`toDeleteInSql \u9700\u8981\u975E\u7A7A idField (idField: ${String($)})`,TO_DELETE_IN_NEED_IDS:"toDeleteInSql \u9700\u8981 ids \u6570\u7EC4",TO_UPDATE_CASE_NEED_TABLE:($)=>`toUpdateCaseByIdSql \u9700\u8981\u975E\u7A7A\u8868\u540D (table: ${String($)})`,TO_UPDATE_CASE_NEED_ID_FIELD:($)=>`toUpdateCaseByIdSql \u9700\u8981\u975E\u7A7A idField (idField: ${String($)})`,TO_UPDATE_CASE_NEED_ROWS:"toUpdateCaseByIdSql \u9700\u8981 rows \u6570\u7EC4",TO_UPDATE_CASE_NEED_FIELDS:"toUpdateCaseByIdSql \u9700\u8981 fields \u6570\u7EC4"};class p${_select=[];_from="";_where=[];_joins=[];_orderBy=[];_groupBy=[];_having=[];_limit=null;_offset=null;_params=[];_quoteIdent;constructor($){if($&&$.quoteIdent)this._quoteIdent=$.quoteIdent;else this._quoteIdent=(J)=>{if(typeof J!=="string")throw Error(g.QUOTE_IDENT_NEED_STRING(J));let Z=J.trim();if(!Z)throw Error(g.IDENT_EMPTY);return`\`${Z.replace(/`/g,"``")}\``}}_isQuotedIdent($){return W0.isQuotedIdentPaired($)}_startsWithQuote($){return W0.startsWithQuote($)}reset(){return this._select=[],this._from="",this._where=[],this._joins=[],this._orderBy=[],this._groupBy=[],this._having=[],this._limit=null,this._offset=null,this._params=[],this}_escapeField($){if(typeof $!=="string")return $;if($=$.trim(),W0.assertPairedQuotedIdentIfStartsWithQuote($,"\u5B57\u6BB5\u6807\u8BC6\u7B26"),$==="*"||this._isQuotedIdent($))return $;try{W0.assertNoExprField($)}catch{throw Error(g.FIELD_EXPR_NOT_ALLOWED($))}if($.toUpperCase().includes(" AS ")){let J=$.split(/\s+AS\s+/i);if(J.length!==2)throw Error(g.FIELD_INVALID($));let Z=J[0],X=J[1];if(typeof Z!=="string"||typeof X!=="string")throw Error(g.FIELD_INVALID($));let G=Z.trim(),Y=X.trim();return W0.assertSafeAlias(Y),`${this._escapeField(G)} AS ${Y}`}if($.includes("."))return $.split(".").map((Z)=>{if(Z=Z.trim(),Z==="*"||this._isQuotedIdent(Z))return Z;return W0.assertPairedQuotedIdentIfStartsWithQuote(Z,"\u5B57\u6BB5\u6807\u8BC6\u7B26"),this._quoteIdent(Z)}).join(".");return this._quoteIdent($)}_validateIdentifierPart($,J){W0.assertSafeIdentifierPart($,J)}_escapeTable($){if(typeof $!=="string")return $;if($=$.trim(),this._startsWithQuote($)&&!this._isQuotedIdent($));if(this._isQuotedIdent($))return $;let J=$.split(/\s+/).filter((z)=>z.length>0);if(J.length===0)throw Error(g.FROM_EMPTY);if(J.length>2)throw Error(g.TABLE_REF_TOO_MANY_PARTS($));let Z=J[0];if(typeof Z!=="string"||Z.trim()==="")throw Error(g.FROM_EMPTY);let X=Z.trim(),G=J.length===2?J[1]:null,Y=typeof G==="string"?G.trim():null,W=X.split(".");if(W.length>2)throw Error(g.TABLE_REF_SCHEMA_TOO_DEEP($));let Q="";if(W.length===2){let z=W[0],O=W[1];if(typeof z!=="string"||typeof O!=="string")throw Error(g.TABLE_REF_SCHEMA_TOO_DEEP($));let M=z.trim(),A=O.trim(),B=this._isQuotedIdent(M)?M:(()=>{if(this._startsWithQuote(M)&&!this._isQuotedIdent(M))throw Error(g.SCHEMA_QUOTE_NOT_PAIRED(M));return this._validateIdentifierPart(M,"schema"),this._quoteIdent(M)})(),L=this._isQuotedIdent(A)?A:(()=>{if(this._startsWithQuote(A)&&!this._isQuotedIdent(A))throw Error(g.TABLE_QUOTE_NOT_PAIRED(A));return this._validateIdentifierPart(A,"table"),this._quoteIdent(A)})();Q=`${B}.${L}`}else{let z=W[0];if(typeof z!=="string")throw Error(g.FROM_EMPTY);let O=z.trim();if(this._isQuotedIdent(O))Q=O;else{if(this._startsWithQuote(O)&&!this._isQuotedIdent(O))throw Error(g.TABLE_QUOTE_NOT_PAIRED(O));this._validateIdentifierPart(O,"table"),Q=this._quoteIdent(O)}}if(Y)return this._validateIdentifierPart(Y,"alias"),`${Q} ${Y}`;return Q}_validateParam($){W0.assertNoUndefinedParam($,"SQL \u53C2\u6570\u503C")}_applyOperator($,J,Z){let X=this._escapeField($);switch(J){case"$ne":case"$not":this._validateParam(Z),this._where.push(`${X} != ?`),this._params.push(Z);break;case"$in":if(!Array.isArray(Z))throw Error(`$in \u64CD\u4F5C\u7B26\u7684\u503C\u5FC5\u987B\u662F\u6570\u7EC4 (operator: ${J})`);if(Z.length===0)throw Error("$in \u64CD\u4F5C\u7B26\u7684\u6570\u7EC4\u4E0D\u80FD\u4E3A\u7A7A\u3002\u63D0\u793A\uFF1A\u7A7A\u6570\u7EC4\u4F1A\u5BFC\u81F4\u67E5\u8BE2\u6C38\u8FDC\u4E0D\u5339\u914D\u4EFB\u4F55\u8BB0\u5F55\uFF0C\u8FD9\u901A\u5E38\u4E0D\u662F\u9884\u671F\u884C\u4E3A\u3002\u8BF7\u68C0\u67E5\u67E5\u8BE2\u6761\u4EF6\u6216\u79FB\u9664\u8BE5\u5B57\u6BB5\u3002");let G=Z.map(()=>"?").join(",");this._where.push(`${X} IN (${G})`),this._params.push(...Z);break;case"$nin":case"$notIn":if(!Array.isArray(Z))throw Error(`$nin/$notIn \u64CD\u4F5C\u7B26\u7684\u503C\u5FC5\u987B\u662F\u6570\u7EC4 (operator: ${J})`);if(Z.length===0)throw Error("$nin/$notIn \u64CD\u4F5C\u7B26\u7684\u6570\u7EC4\u4E0D\u80FD\u4E3A\u7A7A\u3002\u63D0\u793A\uFF1A\u7A7A\u6570\u7EC4\u4F1A\u5BFC\u81F4\u67E5\u8BE2\u5339\u914D\u6240\u6709\u8BB0\u5F55\uFF0C\u8FD9\u901A\u5E38\u4E0D\u662F\u9884\u671F\u884C\u4E3A\u3002\u8BF7\u68C0\u67E5\u67E5\u8BE2\u6761\u4EF6\u6216\u79FB\u9664\u8BE5\u5B57\u6BB5\u3002");let Y=Z.map(()=>"?").join(",");this._where.push(`${X} NOT IN (${Y})`),this._params.push(...Z);break;case"$like":this._validateParam(Z),this._where.push(`${X} LIKE ?`),this._params.push(Z);break;case"$notLike":this._validateParam(Z),this._where.push(`${X} NOT LIKE ?`),this._params.push(Z);break;case"$gt":this._validateParam(Z),this._where.push(`${X} > ?`),this._params.push(Z);break;case"$gte":this._validateParam(Z),this._where.push(`${X} >= ?`),this._params.push(Z);break;case"$lt":this._validateParam(Z),this._where.push(`${X} < ?`),this._params.push(Z);break;case"$lte":this._validateParam(Z),this._where.push(`${X} <= ?`),this._params.push(Z);break;case"$between":if(Array.isArray(Z)&&Z.length===2)this._validateParam(Z[0]),this._validateParam(Z[1]),this._where.push(`${X} BETWEEN ? AND ?`),this._params.push(Z[0],Z[1]);break;case"$notBetween":if(Array.isArray(Z)&&Z.length===2)this._validateParam(Z[0]),this._validateParam(Z[1]),this._where.push(`${X} NOT BETWEEN ? AND ?`),this._params.push(Z[0],Z[1]);break;case"$null":if(Z===!0)this._where.push(`${X} IS NULL`);break;case"$notNull":if(Z===!0)this._where.push(`${X} IS NOT NULL`);break;default:this._validateParam(Z),this._where.push(`${X} = ?`),this._params.push(Z)}}_processWhereConditions($){if(!$||typeof $!=="object")return;Object.entries($).forEach(([J,Z])=>{if(Z===void 0)return;if(J==="$and"){if(Array.isArray(Z))Z.forEach((X)=>{if(X&&typeof X==="object"&&!Array.isArray(X))this._processWhereConditions(X)})}else if(J==="$or"){if(Array.isArray(Z)){let X=[],G=[];if(Z.forEach((Y)=>{if(!Y||typeof Y!=="object"||Array.isArray(Y))return;let W=new p$({quoteIdent:this._quoteIdent});if(W._processWhereConditions(Y),W._where.length>0)X.push(`(${W._where.join(" AND ")})`),G.push(...W._params)}),X.length>0)this._where.push(`(${X.join(" OR ")})`),this._params.push(...G)}}else if(J.includes("$")){let X=J.lastIndexOf("$"),G=J.substring(0,X),Y="$"+J.substring(X+1);this._applyOperator(G,Y,Z)}else if(typeof Z==="object"&&Z!==null&&!Array.isArray(Z))for(let[X,G]of Object.entries(Z))this._applyOperator(J,X,G);else{this._validateParam(Z);let X=this._escapeField(J);this._where.push(`${X} = ?`),this._params.push(Z)}})}getWhereConditions(){return{sql:this._where.length>0?this._where.join(" AND "):"",params:[...this._params]}}select($="*"){if(Array.isArray($))this._select=[...this._select,...$.map((J)=>this._escapeField(J))];else if(typeof $==="string")this._select.push(this._escapeField($));else throw Error(g.SELECT_FIELDS_INVALID);return this}selectRaw($){if(typeof $!=="string"||!$.trim())throw Error(g.SELECT_RAW_NEED_NON_EMPTY($));return this._select.push($),this}from($){if(typeof $!=="string"||!$.trim())throw Error(g.FROM_NEED_NON_EMPTY($));return this._from=this._escapeTable($.trim()),this}fromRaw($){if(typeof $!=="string"||!$.trim())throw Error(g.FROM_RAW_NEED_NON_EMPTY($));return this._from=$,this}where($,J){if(typeof $==="object"&&$!==null)return this._processWhereConditions($),this;if(typeof $==="string"){if(J===void 0)throw Error(g.WHERE_VALUE_REQUIRED);this._validateParam(J);let Z=this._escapeField($);return this._where.push(`${Z} = ?`),this._params.push(J),this}return this}whereRaw($,J){if(typeof $!=="string"||!$.trim())throw Error(g.WHERE_RAW_NEED_NON_EMPTY($));if(this._where.push($),J&&J.length>0)this._params.push(...J);return this}leftJoin($,J){if(typeof $!=="string"||typeof J!=="string")throw Error(g.JOIN_NEED_STRING($,J));let Z=this._escapeTable($);return this._joins.push(`LEFT JOIN ${Z} ON ${J}`),this}rightJoin($,J){if(typeof $!=="string"||typeof J!=="string")throw Error(g.JOIN_NEED_STRING($,J));let Z=this._escapeTable($);return this._joins.push(`RIGHT JOIN ${Z} ON ${J}`),this}innerJoin($,J){if(typeof $!=="string"||typeof J!=="string")throw Error(g.JOIN_NEED_STRING($,J));let Z=this._escapeTable($);return this._joins.push(`INNER JOIN ${Z} ON ${J}`),this}orderBy($){if(!Array.isArray($))throw Error(g.ORDER_BY_NEED_ARRAY);return $.forEach((J)=>{if(typeof J!=="string"||!J.includes("#"))throw Error(g.ORDER_BY_ITEM_NEED_HASH(J));let Z=J.split("#");if(Z.length!==2)throw Error(g.ORDER_BY_ITEM_NEED_HASH(J));let X=Z[0],G=Z[1];if(typeof X!=="string"||typeof G!=="string")throw Error(g.ORDER_BY_ITEM_NEED_HASH(J));let Y=X.trim(),W=G.trim().toUpperCase();if(!Y)throw Error(g.ORDER_BY_FIELD_EMPTY(J));if(!["ASC","DESC"].includes(W))throw Error(g.ORDER_BY_DIR_INVALID(W));let Q=this._escapeField(Y);this._orderBy.push(`${Q} ${W}`)}),this}groupBy($){if(Array.isArray($)){let J=$.filter((Z)=>typeof Z==="string").map((Z)=>this._escapeField(Z));this._groupBy=[...this._groupBy,...J]}else if(typeof $==="string")this._groupBy.push(this._escapeField($));return this}having($){if(typeof $==="string")this._having.push($);return this}limit($,J){if(typeof $!=="number"||$<0)throw Error(g.LIMIT_MUST_NON_NEGATIVE($));if(this._limit=Math.floor($),J!==void 0&&J!==null){if(typeof J!=="number"||J<0)throw Error(g.OFFSET_MUST_NON_NEGATIVE(J));this._offset=Math.floor(J)}return this}offset($){if(typeof $!=="number"||$<0)throw Error(g.OFFSET_COUNT_MUST_NON_NEGATIVE($));return this._offset=Math.floor($),this}toSelectSql(){let $="SELECT ";if($+=this._select.length>0?this._select.join(", "):"*",!this._from)throw Error(g.FROM_REQUIRED);if($+=` FROM ${this._from}`,this._joins.length>0)$+=" "+this._joins.join(" ");if(this._where.length>0)$+=" WHERE "+this._where.join(" AND ");if(this._groupBy.length>0)$+=" GROUP BY "+this._groupBy.join(", ");if(this._having.length>0)$+=" HAVING "+this._having.join(" AND ");if(this._orderBy.length>0)$+=" ORDER BY "+this._orderBy.join(", ");if(this._limit!==null){if($+=` LIMIT ${this._limit}`,this._offset!==null)$+=` OFFSET ${this._offset}`}return{sql:$,params:[...this._params]}}toInsertSql($,J){if(!$||typeof $!=="string")throw Error(g.INSERT_NEED_TABLE($));if(!J||typeof J!=="object")throw Error(g.INSERT_NEED_DATA($,J));let Z=this._escapeTable($);if(Array.isArray(J)){let X=W0.assertBatchInsertRowsConsistent(J,{table:$}),G=X.map((O)=>this._escapeField(O)),Y=X.map(()=>"?").join(", "),W=J.map(()=>`(${Y})`).join(", "),Q=`INSERT INTO ${Z} (${G.join(", ")}) VALUES ${W}`,z=[];for(let O=0;O<J.length;O++){let M=J[O];for(let A of X){let B=M[A];this._validateParam(B),z.push(B)}}return{sql:Q,params:z}}else{let X=Object.keys(J);if(X.length===0)throw Error(g.INSERT_NEED_AT_LEAST_ONE_FIELD($));for(let z of X){let O=J;this._validateParam(O[z])}let G=X.map((z)=>this._escapeField(z)),Y=X.map(()=>"?").join(", "),W=`INSERT INTO ${Z} (${G.join(", ")}) VALUES (${Y})`,Q=[];for(let z of X){let O=J[z];this._validateParam(O),Q.push(O)}return{sql:W,params:Q}}}toUpdateSql($,J){if(!$||typeof $!=="string")throw Error(g.UPDATE_NEED_TABLE);if(!J||typeof J!=="object"||Array.isArray(J))throw Error(g.UPDATE_NEED_OBJECT);let Z=Object.keys(J);if(Z.length===0)throw Error(g.UPDATE_NEED_AT_LEAST_ONE_FIELD);let X=this._escapeTable($),G=Z.map((Q)=>`${this._escapeField(Q)} = ?`),Y=[...Object.values(J),...this._params],W=`UPDATE ${X} SET ${G.join(", ")}`;if(this._where.length>0)W+=" WHERE "+this._where.join(" AND ");else throw Error(g.UPDATE_NEED_WHERE);return{sql:W,params:Y}}toDeleteSql($){if(!$||typeof $!=="string")throw Error(g.DELETE_NEED_TABLE);let Z=`DELETE FROM ${this._escapeTable($)}`;if(this._where.length>0)Z+=" WHERE "+this._where.join(" AND ");else throw Error(g.DELETE_NEED_WHERE);return{sql:Z,params:[...this._params]}}toCountSql(){let $="SELECT COUNT(*) as total";if(!this._from)throw Error(g.COUNT_NEED_FROM);if($+=` FROM ${this._from}`,this._joins.length>0)$+=" "+this._joins.join(" ");if(this._where.length>0)$+=" WHERE "+this._where.join(" AND ");return{sql:$,params:[...this._params]}}static toDeleteInSql($){if(typeof $.table!=="string"||!$.table.trim())throw Error(g.TO_DELETE_IN_NEED_TABLE($.table));if(typeof $.idField!=="string"||!$.idField.trim())throw Error(g.TO_DELETE_IN_NEED_ID_FIELD($.idField));if(!Array.isArray($.ids))throw Error(g.TO_DELETE_IN_NEED_IDS);if($.ids.length===0)return{sql:"",params:[]};let J=$.ids.map(()=>"?").join(",");return{sql:`DELETE FROM ${$.quoteIdent($.table)} WHERE ${$.quoteIdent($.idField)} IN (${J})`,params:[...$.ids]}}static toUpdateCaseByIdSql($){if(typeof $.table!=="string"||!$.table.trim())throw Error(g.TO_UPDATE_CASE_NEED_TABLE($.table));if(typeof $.idField!=="string"||!$.idField.trim())throw Error(g.TO_UPDATE_CASE_NEED_ID_FIELD($.idField));if(!Array.isArray($.rows))throw Error(g.TO_UPDATE_CASE_NEED_ROWS);if($.rows.length===0)return{sql:"",params:[]};if(!Array.isArray($.fields))throw Error(g.TO_UPDATE_CASE_NEED_FIELDS);if($.fields.length===0)return{sql:"",params:[]};let J=$.rows.map((Q)=>Q.id),Z=J.map(()=>"?").join(","),X=[],G=[],Y=$.quoteIdent($.idField);for(let Q of $.fields){let z=[];for(let M of $.rows){if(!(Q in M.data))continue;z.push("WHEN ? THEN ?"),G.push(M.id);let A=M.data[Q];W0.assertNoUndefinedParam(A,"SQL \u53C2\u6570\u503C"),G.push(A)}if(z.length===0)continue;let O=$.quoteIdent(Q);X.push(`${O} = CASE ${Y} ${z.join(" ")} ELSE ${O} END`)}X.push(`${$.quoteIdent($.updatedAtField)} = ?`),G.push($.updatedAtValue);for(let Q of J)G.push(Q);let W=`UPDATE ${$.quoteIdent($.table)} SET ${X.join(", ")} WHERE ${Y} IN (${Z})`;if($.stateGtZero&&$.stateField)W+=` AND ${$.quoteIdent($.stateField)} > 0`;return{sql:W,params:G}}}var DQ=3600;function kQ($){return typeof $.begin==="function"}class N1 extends Error{originalError;params;duration;sqlInfo;constructor($,J){super($);this.originalError=J.originalError,this.params=J.params,this.duration=J.duration,this.sqlInfo=J.sqlInfo}}class xJ{redis;dialect;sql=null;isTransaction=!1;constructor($){this.redis=$.redis,this.sql=$.sql||null,this.isTransaction=Boolean($.sql),this.dialect=$.dialect?$.dialect:new LJ}createSqlBuilder(){return new p$({quoteIdent:this.dialect.quoteIdent.bind(this.dialect)})}async getTableColumns($){let J=G0.tableColumns($),Z=await this.redis.getObject(J);if(Z&&Z.length>0)return Z;let X=this.dialect.getTableColumnsQuery($),Y=(await this.executeSelect(X.sql,X.params)).data;if(!Y||Y.length===0)throw Error(`\u8868 ${$} \u4E0D\u5B58\u5728\u6216\u6CA1\u6709\u5B57\u6BB5`);let W=this.dialect.getTableColumnsFromResult(Y);if(await this.redis.setObject(J,W,DQ)===null)q.warn({table:$,cacheKey:J,msg:"\u8868\u5B57\u6BB5\u7F13\u5B58\u5199\u5165 Redis \u5931\u8D25"});return W}async prepareQueryOptions($){let J=N$($.where||{},{excludeValues:[null,void 0]});if($.joins&&$.joins.length>0){let G=($.fields||[]).map((Q)=>c.processJoinField(Q)),Y=c.normalizeTableRef($.table),W=c.getJoinMainQualifier($.table);return{table:Y,tableQualifier:W,fields:G.length>0?G:["*"],where:c.processJoinWhere(J),joins:$.joins,orderBy:c.processJoinOrderBy($.orderBy||[]),page:$.page||1,limit:$.limit||10}}let X=await c.fieldsToSnake(x($.table),$.fields||[],this.getTableColumns.bind(this));return{table:x($.table),tableQualifier:x($.table),fields:X,where:c.whereKeysToSnake(J),joins:void 0,orderBy:c.orderByToSnake($.orderBy||[]),page:$.page||1,limit:$.limit||10}}applyJoins($,J){if(!J||J.length===0)return;for(let Z of J){let X=c.normalizeTableRef(Z.table);switch(Z.type||"left"){case"inner":$.innerJoin(X,Z.on);break;case"right":$.rightJoin(X,Z.on);break;case"left":default:$.leftJoin(X,Z.on);break}}}async executeSelect($,J){return await this.executeWithConn($,J)}async executeRun($,J){return await this.executeWithConn($,J)}async executeWithConn($,J){if(!this.sql)throw Error("\u6570\u636E\u5E93\u8FDE\u63A5\u672A\u521D\u59CB\u5316");if(typeof $!=="string")throw Error(`executeWithConn \u53EA\u63A5\u53D7\u5B57\u7B26\u4E32\u7C7B\u578B\u7684 SQL\uFF0C\u6536\u5230\u7C7B\u578B: ${typeof $}\uFF0C\u503C: ${JSON.stringify($)}`);let Z=Date.now(),X=T1(J);try{let G;if(X.length>0)G=await this.sql.unsafe($,X);else G=await this.sql.unsafe($);let Y=Date.now()-Z;return{data:G,sql:{sql:$,params:X,duration:Y}}}catch(G){let Y=Date.now()-Z,W=G instanceof Error?G.message:String(G);throw new N1(`SQL\u6267\u884C\u5931\u8D25: ${W}`,{originalError:G,params:X,duration:Y,sqlInfo:{sql:$,params:X,duration:Y}})}}async unsafe($,J){return await this.executeWithConn($,J)}async tableExists($){let J=x($),Z=this.dialect.tableExistsQuery(J),X=await this.executeSelect(Z.sql,Z.params);return{data:(X.data?.[0]?.count||0)>0,sql:X.sql}}async getCount($){let{table:J,where:Z,joins:X,tableQualifier:G}=await this.prepareQueryOptions($),Y=Array.isArray(X)&&X.length>0,W=this.createSqlBuilder().selectRaw("COUNT(*) as count").from(J).where(c.addDefaultStateFilter(Z,G,Y));this.applyJoins(W,X);let{sql:Q,params:z}=W.toSelectSql(),O=await this.executeSelect(Q,z);return{data:O.data?.[0]?.count||0,sql:O.sql}}async getOne($){let{table:J,fields:Z,where:X,joins:G,tableQualifier:Y}=await this.prepareQueryOptions($),W=Array.isArray(G)&&G.length>0,Q=this.createSqlBuilder().select(Z).from(J).where(c.addDefaultStateFilter(X,Y,W));this.applyJoins(Q,G);let{sql:z,params:O}=Q.toSelectSql(),M=await this.executeSelect(z,O),B=M.data?.[0]||null;if(!B)return{data:{},sql:M.sql};let L=jZ(B),C=c.deserializeArrayFields(L);if(!C)return{data:{},sql:M.sql};return{data:yJ([C])[0]??C,sql:M.sql}}async getDetail($){return await this.getOne($)}async getList($){let J=await this.prepareQueryOptions($);if(J.page<1||J.page>1e4)throw Error(`\u9875\u7801\u5FC5\u987B\u5728 1 \u5230 10000 \u4E4B\u95F4 (table: ${$.table}, page: ${J.page}, limit: ${J.limit})`);if(J.limit<1||J.limit>1000)throw Error(`\u6BCF\u9875\u6570\u91CF\u5FC5\u987B\u5728 1 \u5230 1000 \u4E4B\u95F4 (table: ${$.table}, page: ${J.page}, limit: ${J.limit})`);let Z=c.addDefaultStateFilter(J.where,J.tableQualifier,Array.isArray(J.joins)&&J.joins.length>0),X=this.createSqlBuilder().selectRaw("COUNT(*) as total").from(J.table).where(Z);this.applyJoins(X,J.joins);let{sql:G,params:Y}=X.toSelectSql(),W=await this.executeSelect(G,Y),Q=W.data?.[0]?.total||0;if(Q===0)return{data:{lists:[],total:0,page:J.page,limit:J.limit,pages:0},sql:{count:W.sql}};let z=(J.page-1)*J.limit,O=this.createSqlBuilder().select(J.fields).from(J.table).where(Z).limit(J.limit).offset(z);if(this.applyJoins(O,J.joins),J.orderBy&&J.orderBy.length>0)O.orderBy(J.orderBy);let{sql:M,params:A}=O.toSelectSql(),B=await this.executeSelect(M,A),L=B.data||[],w=qZ(L).map((T)=>c.deserializeArrayFields(T)).filter((T)=>T!==null);return{data:{lists:yJ(w),total:Q,page:J.page,limit:J.limit,pages:Math.ceil(Q/J.limit)},sql:{count:W.sql,data:B.sql}}}async getAll($){let X={table:$.table,page:1,limit:10};if($.fields!==void 0)X.fields=$.fields;if($.where!==void 0)X.where=$.where;if($.joins!==void 0)X.joins=$.joins;if($.orderBy!==void 0)X.orderBy=$.orderBy;let G=await this.prepareQueryOptions(X),Y=c.addDefaultStateFilter(G.where,G.tableQualifier,Array.isArray(G.joins)&&G.joins.length>0),W=this.createSqlBuilder().selectRaw("COUNT(*) as total").from(G.table).where(Y);this.applyJoins(W,G.joins);let{sql:Q,params:z}=W.toSelectSql(),O=await this.executeSelect(Q,z),M=O.data?.[0]?.total||0;if(M===0)return{data:{lists:[],total:0},sql:{count:O.sql}};let A=this.createSqlBuilder().select(G.fields).from(G.table).where(Y).limit(1e4);if(this.applyJoins(A,G.joins),G.orderBy&&G.orderBy.length>0)A.orderBy(G.orderBy);let{sql:B,params:L}=A.toSelectSql(),C=await this.executeSelect(B,L),w=C.data||[];if(w.length>=1000)q.warn({table:$.table,count:w.length,total:M,msg:"getAll \u8FD4\u56DE\u6570\u636E\u8FC7\u591A\uFF0C\u5EFA\u8BAE\u4F7F\u7528 getList \u5206\u9875\u67E5\u8BE2"});if(w.length>=1e4)q.warn({table:$.table,limit:1e4,total:M,msg:`getAll \u8FBE\u5230\u6700\u5927\u9650\u5236 ${1e4}\uFF0C\u5B9E\u9645\u603B\u6570 ${M}\uFF0C\u53EA\u8FD4\u56DE\u524D ${1e4} \u6761`});let D=qZ(w).map((N)=>c.deserializeArrayFields(N)).filter((N)=>N!==null);return{data:{lists:yJ(D),total:M},sql:{count:O.sql,data:C.sql}}}async insData($){let{table:J,data:Z}=$,X=x(J),G=Date.now(),Y;try{Y=await this.redis.genTimeID()}catch(w){throw Error(`\u751F\u6210 ID \u5931\u8D25\uFF0CRedis \u53EF\u80FD\u4E0D\u53EF\u7528 (table: ${J})`,{cause:w})}let W=c.buildInsertRow({data:Z,id:Y,now:G});W0.assertNoUndefinedInRecord(W,`insData \u63D2\u5165\u6570\u636E (table: ${X})`);let Q=this.createSqlBuilder(),{sql:z,params:O}=Q.toInsertSql(X,W),M=await this.executeRun(z,O),A=W.id,B=typeof A==="number"?A:0,L=v$(M.data?.lastInsertRowid);return{data:B||L||0,sql:M.sql}}async insBatch($,J){if(J.length===0)return{data:[],sql:{sql:"",params:[],duration:0}};let Z=1000;if(J.length>Z)throw Error(`\u6279\u91CF\u63D2\u5165\u6570\u91CF ${J.length} \u8D85\u8FC7\u6700\u5927\u9650\u5236 ${Z}`);let X=x($),G=[];for(let A=0;A<J.length;A++)G.push(await this.redis.genTimeID());let Y=Date.now(),W=J.map((A,B)=>{let L=G[B];if(typeof L!=="number")throw Error(`\u6279\u91CF\u63D2\u5165\u751F\u6210 ID \u5931\u8D25\uFF1Aids[${B}] \u4E0D\u662F number (table: ${X})`);return c.buildInsertRow({data:A,id:L,now:Y})}),Q=W0.assertBatchInsertRowsConsistent(W,{table:X}),z=this.createSqlBuilder(),{sql:O,params:M}=z.toInsertSql(X,W);try{let A=await this.executeRun(O,M);return{data:G,sql:A.sql}}catch(A){throw q.error({err:A,table:$,snakeTable:X,count:J.length,fields:Q,msg:"\u6279\u91CF\u63D2\u5165\u5931\u8D25"}),A}}async delForceBatch($,J){if(J.length===0)return{data:0,sql:{sql:"",params:[],duration:0}};let Z=x($),X=p$.toDeleteInSql({table:Z,idField:"id",ids:J,quoteIdent:this.dialect.quoteIdent.bind(this.dialect)}),G=await this.executeRun(X.sql,X.params);return{data:v$(G.data?.changes),sql:G.sql}}async updBatch($,J){if(J.length===0)return{data:0,sql:{sql:"",params:[],duration:0}};let Z=x($),X=Date.now(),G=[],Y=new Set;for(let M of J){let A=c.buildPartialUpdateData({data:M.data,allowState:!0});for(let B of Object.keys(A))Y.add(B);G.push({id:M.id,data:A})}let W=Array.from(Y).sort();if(W.length===0)return{data:0,sql:{sql:"",params:[],duration:0}};let Q=p$.toUpdateCaseByIdSql({table:Z,idField:"id",rows:G,fields:W,quoteIdent:this.dialect.quoteIdent.bind(this.dialect),updatedAtField:"updated_at",updatedAtValue:X,stateField:"state",stateGtZero:!0}),z=await this.executeRun(Q.sql,Q.params);return{data:v$(z.data?.changes),sql:z.sql}}async updData($){let{table:J,data:Z,where:X}=$,G=N$(X,{excludeValues:[null,void 0]}),Y=x(J),W=c.whereKeysToSnake(G),Q=c.buildUpdateRow({data:Z,now:Date.now(),allowState:!0}),z=c.addDefaultStateFilter(W,Y,!1),O=this.createSqlBuilder().where(z),{sql:M,params:A}=O.toUpdateSql(Y,Q),B=await this.executeRun(M,A);return{data:v$(B.data?.changes),sql:B.sql}}async delData($){let{table:J,where:Z}=$;return await this.updData({table:J,data:{state:0,deleted_at:Date.now()},where:Z})}async delForce($){let{table:J,where:Z}=$,X=x(J),G=N$(Z,{excludeValues:[null,void 0]}),Y=c.whereKeysToSnake(G),W=this.createSqlBuilder().where(Y),{sql:Q,params:z}=W.toDeleteSql(X),O=await this.executeRun(Q,z);return{data:v$(O.data?.changes),sql:O.sql}}async disableData($){let{table:J,where:Z}=$;return await this.updData({table:J,data:{state:2},where:Z})}async enableData($){let{table:J,where:Z}=$;return await this.updData({table:J,data:{state:1},where:Z})}async trans($){if(this.isTransaction)return await $(this);let J=this.sql;if(!J)throw Error("\u6570\u636E\u5E93\u8FDE\u63A5\u672A\u521D\u59CB\u5316");if(!kQ(J))throw Error("\u5F53\u524D SQL \u5BA2\u6237\u7AEF\u4E0D\u652F\u6301\u4E8B\u52A1 begin() \u65B9\u6CD5");return await J.begin(async(Z)=>{let X=new xJ({redis:this.redis,sql:Z,dialect:this.dialect});return await $(X)})}async query($,J){return await this.executeWithConn($,J)}async exists($){let J={table:$.table,page:1,limit:1};if($.where!==void 0)J.where=$.where;if($.joins!==void 0)J.joins=$.joins;let{table:Z,where:X,tableQualifier:G}=await this.prepareQueryOptions(J),Y=this.createSqlBuilder().selectRaw("COUNT(1) as cnt").from(Z).where(c.addDefaultStateFilter(X,G,!1)).limit(1),{sql:W,params:Q}=Y.toSelectSql(),z=await this.executeSelect(W,Q);return{data:(z.data?.[0]?.cnt||0)>0,sql:z.sql}}async getFieldValue($){let J=$.field;if(!/^[a-zA-Z_][a-zA-Z0-9_]*$/.test(J))throw Error(`\u65E0\u6548\u7684\u5B57\u6BB5\u540D: ${J}\uFF0C\u53EA\u5141\u8BB8\u5B57\u6BCD\u3001\u6570\u5B57\u548C\u4E0B\u5212\u7EBF`);let Z={table:$.table};if($.where!==void 0)Z.where=$.where;if($.joins!==void 0)Z.joins=$.joins;if($.orderBy!==void 0)Z.orderBy=$.orderBy;if($.page!==void 0)Z.page=$.page;if($.limit!==void 0)Z.limit=$.limit;Z.fields=[J];let X=await this.getOne(Z),G=X.data;if(!n(G))return{data:null,sql:X.sql};if(Object.hasOwn(G,J))return{data:G[J],sql:X.sql};let Y=J.replace(/_([a-z])/g,(Q,z)=>z.toUpperCase());if(Y!==J&&Object.hasOwn(G,Y))return{data:G[Y],sql:X.sql};let W=J.replace(/[A-Z]/g,(Q)=>`_${Q.toLowerCase()}`);if(W!==J&&Object.hasOwn(G,W))return{data:G[W],sql:X.sql};return{data:null,sql:X.sql}}async increment($,J,Z,X=1){let G=x($),Y=x(J);if(!/^[a-zA-Z_][a-zA-Z0-9_]*$/.test(G))throw Error(`\u65E0\u6548\u7684\u8868\u540D: ${G}`);if(!/^[a-zA-Z_][a-zA-Z0-9_]*$/.test(Y))throw Error(`\u65E0\u6548\u7684\u5B57\u6BB5\u540D: ${J}`);if(typeof X!=="number"||isNaN(X))throw Error(`\u81EA\u589E\u503C\u5FC5\u987B\u662F\u6709\u6548\u7684\u6570\u5B57 (table: ${$}, field: ${J}, value: ${X})`);let W=N$(Z,{excludeValues:[null,void 0]}),Q=c.whereKeysToSnake(W),z=c.addDefaultStateFilter(Q,G,!1),O=this.createSqlBuilder().where(z),{sql:M,params:A}=O.getWhereConditions(),B=this.dialect.quoteIdent(G),L=this.dialect.quoteIdent(Y),C=M?`UPDATE ${B} SET ${L} = ${L} + ? WHERE ${M}`:`UPDATE ${B} SET ${L} = ${L} + ?`,w=await this.executeRun(C,[X,...A]);return{data:v$(w.data?.changes),sql:w.sql}}async decrement($,J,Z,X=1){return await this.increment($,J,Z,-X)}}a();var fQ={name:"db",enable:!0,deps:["logger","redis"],async handler($){let J=$.config?.nodeEnv;if(!$.redis)throw Error("Redis \u672A\u521D\u59CB\u5316");try{let Z=O$.getSql(),X=$.config?.db?.type,G=X==="postgres"?"postgresql":X,Y=b$(G==="postgresql"||G==="sqlite"?G:"mysql");return new xJ({redis:$.redis,sql:Z,dialect:Y})}catch(Z){throw q.error({env:J,err:Z,msg:"\u6570\u636E\u5E93\u521D\u59CB\u5316\u5931\u8D25"}),Z}}},v1=fQ;var k$=kW(jW(),1);class NG{config;constructor($={}){this.config={secret:$.secret||"befly-secret",expiresIn:$.expiresIn||"7d",algorithm:$.algorithm||"HS256"}}sign($,J={}){let Z=J.secret||this.config.secret,X=J.algorithm||this.config.algorithm||"HS256",G={key:Z,algorithm:X,expiresIn:J.expiresIn??this.config.expiresIn};if(J.issuer!==void 0)G.iss=J.issuer;if(J.audience!==void 0)G.aud=J.audience;if(J.subject!==void 0)G.sub=J.subject;if(J.jwtId!==void 0)G.jti=J.jwtId;if(typeof J.notBefore==="number")G.notBefore=J.notBefore;return k$.createSigner(G)($)}verify($,J={}){if(!$||typeof $!=="string")throw Error("Token\u5FC5\u987B\u662F\u975E\u7A7A\u5B57\u7B26\u4E32");let Z=J.secret||this.config.secret,X=this.config.algorithm||"HS256",G=J.algorithms?J.algorithms:[X],Y={key:Z,algorithms:G,cache:!0,cacheTTL:600000};if(J.issuer!==void 0)Y.allowedIss=J.issuer;if(J.audience!==void 0)Y.allowedAud=J.audience;if(J.subject!==void 0)Y.allowedSub=J.subject;if(typeof J.ignoreExpiration==="boolean")Y.ignoreExpiration=J.ignoreExpiration;if(typeof J.ignoreNotBefore==="boolean")Y.ignoreNotBefore=J.ignoreNotBefore;return k$.createVerifier(Y)($)}decode($,J=!1){if(!$||typeof $!=="string")throw Error("Token\u5FC5\u987B\u662F\u975E\u7A7A\u5B57\u7B26\u4E32");if(J){let G=k$.createDecoder({complete:!0})($);return{header:G.header,payload:G.payload,signature:G.signature}}return k$.createDecoder()($)}}var J6={name:"jwt",enable:!0,deps:[],handler:($)=>{return new NG($.config?$.config.auth:void 0)}},qW=J6;a();var Z6={name:"logger",enable:!0,deps:[],async handler($){if($.config&&$.config.logger)q.configure($.config.logger);return q}},BW=Z6;a();a();class vG{client;prefix;slowThresholdMs=500;constructor($=""){let J=O$.getRedis();if(!J)throw Error("Redis \u5BA2\u6237\u7AEF\u672A\u521D\u59CB\u5316\uFF0C\u8BF7\u5148\u8C03\u7528 Connect.connectRedis()");this.client=J,this.prefix=$?`${$}:`:""}logSlow($,J,Z,X={}){if(Z<=this.slowThresholdMs)return;q.warn({subsystem:"redis",event:"slow",duration:Z,cmd:$,key:J,extra:X,msg:"\uD83D\uDC0C Redis \u6162\u64CD\u4F5C"})}async setObject($,J,Z=null){try{let X=JSON.stringify(J),G=`${this.prefix}${$}`,Y=Date.now();if(Z){let z=await this.client.setex(G,Z,X),O=Date.now()-Y;return this.logSlow("SETEX",G,O,{ttl:Z}),z}let W=await this.client.set(G,X),Q=Date.now()-Y;return this.logSlow("SET",G,Q),W}catch(X){return q.error({err:X,msg:"Redis setObject \u9519\u8BEF"}),null}}async getObject($){try{let J=`${this.prefix}${$}`,Z=Date.now(),X=await this.client.get(J),G=Date.now()-Z;return this.logSlow("GET",J,G),X?JSON.parse(X):null}catch(J){return q.error({err:J,msg:"Redis getObject \u9519\u8BEF"}),null}}async delObject($){try{let J=`${this.prefix}${$}`,Z=Date.now();await this.client.del(J);let X=Date.now()-Z;this.logSlow("DEL",J,X)}catch(J){q.error({err:J,msg:"Redis delObject \u9519\u8BEF"})}}async genTimeID(){let $=Date.now(),J=`${this.prefix}time_id:${$}`,Z=Date.now(),X=await this.client.incr(J);if(X===1)await this.client.expire(J,1);let G=Date.now()-Z;this.logSlow("INCR",J,G,{expireSeconds:1});let Y=100+($%900+X-1)%900;return Number(`${$}${Y}`)}async setString($,J,Z=null){try{let X=`${this.prefix}${$}`,G=Date.now();if(Z){let Q=await this.client.setex(X,Z,J),z=Date.now()-G;return this.logSlow("SETEX",X,z,{ttl:Z}),Q}let Y=await this.client.set(X,J),W=Date.now()-G;return this.logSlow("SET",X,W),Y}catch(X){return q.error({err:X,msg:"Redis setString \u9519\u8BEF"}),null}}async getString($){try{let J=`${this.prefix}${$}`,Z=Date.now(),X=await this.client.get(J),G=Date.now()-Z;return this.logSlow("GET",J,G),X}catch(J){return q.error({err:J,msg:"Redis getString \u9519\u8BEF"}),null}}async exists($){try{let J=`${this.prefix}${$}`,Z=Date.now(),X=await this.client.exists(J),G=Date.now()-Z;return this.logSlow("EXISTS",J,G),X}catch(J){return q.error({err:J,msg:"Redis exists \u9519\u8BEF"}),!1}}async incr($){try{let J=`${this.prefix}${$}`,Z=Date.now(),X=await this.client.incr(J),G=Date.now()-Z;return this.logSlow("INCR",J,G),X}catch(J){return q.error({err:J,msg:"Redis incr \u9519\u8BEF"}),0}}async incrWithExpire($,J){try{let Z=`${this.prefix}${$}`,X=Date.now(),G=await this.client.incr(Z);if(G===1)await this.client.expire(Z,J);let Y=Date.now()-X;return this.logSlow("INCR",Z,Y,{expireSeconds:J}),G}catch(Z){return q.error({err:Z,msg:"Redis incrWithExpire \u9519\u8BEF"}),0}}async expire($,J){try{let Z=`${this.prefix}${$}`,X=Date.now(),G=await this.client.expire(Z,J),Y=Date.now()-X;return this.logSlow("EXPIRE",Z,Y,{seconds:J}),G}catch(Z){return q.error({err:Z,msg:"Redis expire \u9519\u8BEF"}),0}}async ttl($){try{let J=`${this.prefix}${$}`,Z=Date.now(),X=await this.client.ttl(J),G=Date.now()-Z;return this.logSlow("TTL",J,G),X}catch(J){return q.error({err:J,msg:"Redis ttl \u9519\u8BEF"}),-1}}async ttlBatch($){if($.length===0)return[];try{return await Promise.all($.map((Z)=>this.ttl(Z)))}catch(J){return q.error({err:J,msg:"Redis ttlBatch \u9519\u8BEF"}),$.map(()=>-1)}}async sadd($,J){try{if(J.length===0)return 0;let Z=`${this.prefix}${$}`,X=Date.now(),G=await this.client.sadd(Z,...J),Y=Date.now()-X;return this.logSlow("SADD",Z,Y,{membersCount:J.length}),G}catch(Z){return q.error({err:Z,msg:"Redis sadd \u9519\u8BEF"}),0}}async sismember($,J){try{let Z=`${this.prefix}${$}`,X=Date.now(),G=await this.client.sismember(Z,J),Y=Date.now()-X;return this.logSlow("SISMEMBER",Z,Y),G}catch(Z){return q.error({err:Z,msg:"Redis sismember \u9519\u8BEF"}),!1}}async scard($){try{let J=`${this.prefix}${$}`,Z=Date.now(),X=await this.client.scard(J),G=Date.now()-Z;return this.logSlow("SCARD",J,G),X}catch(J){return q.error({err:J,msg:"Redis scard \u9519\u8BEF"}),0}}async smembers($){try{let J=`${this.prefix}${$}`,Z=Date.now(),X=await this.client.smembers(J),G=Date.now()-Z;return this.logSlow("SMEMBERS",J,G),X}catch(J){return q.error({err:J,msg:"Redis smembers \u9519\u8BEF"}),[]}}async saddBatch($){if($.length===0)return 0;try{return(await Promise.all($.map((Z)=>this.sadd(Z.key,Z.members)))).reduce((Z,X)=>Z+X,0)}catch(J){return q.error({err:J,msg:"Redis saddBatch \u9519\u8BEF"}),0}}async sismemberBatch($){if($.length===0)return[];try{return await Promise.all($.map((J)=>this.sismember(J.key,J.member)))}catch(J){return q.error({err:J,msg:"Redis sismemberBatch \u9519\u8BEF"}),$.map(()=>!1)}}async del($){try{let J=`${this.prefix}${$}`,Z=Date.now(),X=await this.client.del(J),G=Date.now()-Z;return this.logSlow("DEL",J,G),X}catch(J){return q.error({err:J,msg:"Redis del \u9519\u8BEF"}),0}}async delBatch($){if($.length===0)return 0;try{return(await Promise.all($.map((Z)=>{let X=`${this.prefix}${Z}`;return this.client.del(X)}))).reduce((Z,X)=>Z+X,0)}catch(J){return q.error({err:J,msg:"Redis delBatch \u9519\u8BEF"}),0}}async setBatch($){if($.length===0)return 0;try{return(await Promise.all($.map((Z)=>this.setObject(Z.key,Z.value,Z.ttl??null)))).filter((Z)=>Z!==null).length}catch(J){return q.error({err:J,msg:"Redis setBatch \u9519\u8BEF"}),0}}async getBatch($){if($.length===0)return[];try{return await Promise.all($.map((Z)=>this.getObject(Z)))}catch(J){return q.error({err:J,msg:"Redis getBatch \u9519\u8BEF"}),$.map(()=>null)}}async existsBatch($){if($.length===0)return[];try{return await Promise.all($.map((J)=>this.exists(J)))}catch(J){return q.error({err:J,msg:"Redis existsBatch \u9519\u8BEF"}),$.map(()=>!1)}}async expireBatch($){if($.length===0)return 0;try{return(await Promise.all($.map((Z)=>this.expire(Z.key,Z.seconds)))).filter((Z)=>Z>0).length}catch(J){return q.error({err:J,msg:"Redis expireBatch \u9519\u8BEF"}),0}}async ping(){try{let $=Date.now(),J=await this.client.ping(),Z=Date.now()-$;return this.logSlow("PING","(no-key)",Z),J}catch($){throw q.error({err:$,msg:"Redis ping \u9519\u8BEF"}),$}}}var G6={name:"redis",enable:!0,deps:["logger"],async handler($){let J=$.config?.nodeEnv,Z=$.config?.redis?.prefix;try{return O$.getRedis(),new vG(Z)}catch(X){throw q.error({env:J,err:X,msg:"Redis \u521D\u59CB\u5316\u5931\u8D25"}),X}}},PW=G6;function X6($,J={},Z={}){return{code:0,msg:$,data:J,...Z}}function Y6($,J=null,Z={}){return{code:1,msg:$,data:J,...Z}}function W6($,J,Z={}){let{status:X=200,contentType:G,headers:Y={}}=Z,W=G,Q;if(typeof J==="string"){if(Q=J,!W)W=J.trim().startsWith("<")?"application/xml":"text/plain"}else Q=JSON.stringify(J),W=W||"application/json";let z={...$.corsHeaders,"Content-Type":W,...Y};return new Response(Q,{status:X,headers:z})}var H6={name:"tool",enable:!0,deps:[],handler:()=>{return{Yes:X6,No:Y6,Raw:W6}}},LW=H6;n0();function SW($,J){let Z=n(J)?J:{},X=typeof Z.name==="string"?String(Z.name):"",G=n(J)?Object.keys(J):[],Y=Z.deps,W=Array.isArray(Y)?Y.filter((z)=>typeof z==="string"):[];return{source:"core",type:$,sourceName:"\u6838\u5FC3",filePath:`core:${$}:${X}`,relativePath:X,fileName:X,moduleName:X,addonName:"",fileBaseName:X,fileDir:"(builtin)",name:X,enable:Z.enable,deps:W,handler:Z.handler??null,customKeys:G}}function CW(){let $=[],J=[BW,PW,v1,C1,LW,E1,qW,w1];for(let Z of J)$.push(SW("plugin",Z));return $}function EW(){let $=[],J=[z1,O1,q1,S1,B1];for(let Z of J)$.push(SW("hook",Z));return $}q$();RJ();n0();import{existsSync as Q6}from"fs";function U6($){let J=$.split("/").filter(Boolean),Z=J.indexOf("@befly-addon");if(Z<0)return null;let X=J[Z+1];if(typeof X!=="string"||X.trim()==="")return null;return X}function V6($){let J=$.split("/").filter(Boolean),Z=J.lastIndexOf("addons");if(Z<0)return null;let X=J[Z+1];if(typeof X!=="string"||X.trim()==="")return null;return X}async function M$($,J,Z,X){if(!Q6($))return[];let G=C$($),Y=new Bun.Glob(X),W=[];try{let Q=await Y.scan({cwd:$,onlyFiles:!0,absolute:!0,followSymlinks:!0});for await(let z of Q){if(z.endsWith(".d.ts"))continue;let O=C$(z),M=ZJ(O).name,A=kZ(G,O),B=ZJ(A),L=B.dir?d(B.dir,B.name):B.name;if(M.startsWith("_"))continue;if(L.split("/").some((N)=>N.startsWith("_")))continue;let C=await j$(O,{}),w=F$(M),T="",D="";if(J==="core")T="",D=M;else if(J==="app")D=`app_${w}`;else{let N=U6(O)||V6(O);if(!N)throw Error(`scanFiles addon moduleName \u89E3\u6790\u5931\u8D25\uFF1A\u672A\u627E\u5230 @befly-addon/<addon>/ \u6BB5\u843D\uFF1A${O}`);T=N,D=`addon_${F$(T)}_${w}`}let E={source:J,type:Z,sourceName:J==="core"?"\u6838\u5FC3":J==="addon"?"\u7EC4\u4EF6":"\u9879\u76EE",filePath:O,relativePath:L,fileName:M,moduleName:D,addonName:T,fileBaseName:ZJ(O).base,fileDir:$,customKeys:n(C)?Object.keys(C):[]};if(Z==="table"){E.content=n(C)?C:{},W.push(E);continue}if(Z==="api")E.auth=!0,E.rawBody=!1,E.method="POST",E.fields={},E.required=[];if(Z==="plugin"||Z==="hook")E.deps=[],E.name="",E.handler=null;if(iG(C,(N,h)=>{E[h]=N}),Z==="api")E.routePrefix=J==="app"?"/app":`/addon/${T}`,E.path=`/api${E.routePrefix}/${L}`;W.push(E)}}catch(Q){let z=Error(`scanFiles failed: source=${J} type=${Z} dir=${G} pattern=${X}`);throw z.cause=Q,z}return W}var wW=async()=>{let $=[],J=[],Z=[],X=[],G=await V1();X.push(...await M$(d(d0,"tables"),"app","table","*.json"));for(let Y of G)X.push(...await M$(d(Y.fullPath,"tables"),"addon","table","*.json"));J.push(...CW()),J.push(...await M$(d(d0,"plugins"),"app","plugin","*.{ts,js}"));for(let Y of G)J.push(...await M$(d(Y.fullPath,"plugins"),"addon","plugin","*.{ts,js}"));Z.push(...EW()),Z.push(...await M$(d(d0,"hooks"),"app","hook","*.{ts,js}"));for(let Y of G)Z.push(...await M$(d(Y.fullPath,"hooks"),"addon","hook","*.{ts,js}"));$.push(...await M$(d(d0,"apis"),"app","api","**/*.{ts,js}"));for(let Y of G)$.push(...await M$(d(Y.fullPath,"apis"),"addon","api","**/*.{ts,js}"));return{hooks:Z,plugins:J,apis:$,tables:X,addons:G}};class z6{apis=new Map;plugins=[];hooks=[];context={};config=null;async start($={}){try{let J=Bun.nanoseconds();this.config=await KX($.NODE_ENV||"development"),this.context.config=this.config,this.context.env=$;let{apis:Z,tables:X,plugins:G,hooks:Y,addons:W}=await wW();this.context.addons=W,await MX(Z),await DX(X),await EX(G),await AX(Y);let Q=await SX(W);if(await O$.connect({db:this.config.db||{},redis:this.config.redis||{}}),this.plugins=await xX(G,this.context),!this.context.redis)throw Error("\u542F\u52A8\u5931\u8D25\uFF1Actx.redis \u672A\u521D\u59CB\u5316\uFF08Redis \u63D2\u4EF6\u672A\u52A0\u8F7D\u6216\u6CE8\u5165\u5931\u8D25\uFF09");if(!this.context.db)throw Error("\u542F\u52A8\u5931\u8D25\uFF1Actx.db \u672A\u521D\u59CB\u5316\uFF08Db \u63D2\u4EF6\u672A\u52A0\u8F7D\u6216\u6CE8\u5165\u5931\u8D25\uFF09");if(!this.context.cache)throw Error("\u542F\u52A8\u5931\u8D25\uFF1Actx.cache \u672A\u521D\u59CB\u5316\uFF08cache \u63D2\u4EF6\u672A\u52A0\u8F7D\u6216\u6CE8\u5165\u5931\u8D25\uFF09");await EJ(this.context,X),await pX(this.context,Z),await dX(this.context,Q);let z=this.config.devEmail,O=this.config.devPassword;if(typeof z==="string"&&z.length>0&&typeof O==="string"&&O.length>0)await nX(this.context,{devEmail:z,devPassword:O});else q.debug("\u8DF3\u8FC7 syncDev\uFF1A\u672A\u914D\u7F6E devEmail/devPassword");await uX(this.context),this.hooks=await yX(Y),this.apis=await fX(Z);let M=hX(this.apis,this.hooks,this.context),A=cX(this.config.cors),B=typeof this.config.appPort==="number"?this.config.appPort:3000,L=typeof this.config.appHost==="string"&&this.config.appHost.length>0?this.config.appHost:"0.0.0.0",C=Bun.serve({port:B,hostname:L,development:this.config.nodeEnv==="development",idleTimeout:30,fetch:async(N,h)=>{let v=new URL(N.url);if(v.pathname==="/")return Response.json({code:0,msg:`${this.config.appName} \u63A5\u53E3\u670D\u52A1\u5DF2\u542F\u52A8`});if(v.pathname.startsWith("/api/"))return M(N,h);return A(N)},error:(N)=>{if(q.error({err:N,msg:"\u670D\u52A1\u542F\u52A8\u65F6\u53D1\u751F\u9519\u8BEF"}),this.config.nodeEnv==="development")return Response.json({code:1,msg:"\u5185\u90E8\u670D\u52A1\u5668\u9519\u8BEF",error:N.message,stack:N.stack},{status:200});return Response.json({code:1,msg:"\u5185\u90E8\u670D\u52A1\u5668\u9519\u8BEF"},{status:200})}}),w=Q1(J),T=U1($),D=T.role==="primary"?"\u4E3B\u8FDB\u7A0B":`\u5DE5\u4F5C\u8FDB\u7A0B #${T.instanceId}`,E=T.env==="standalone"?"":` [${T.env}]`;return q.info(`${this.config.appName} \u542F\u52A8\u6210\u529F! (${D}${E})`),q.info(`\u670D\u52A1\u5668\u542F\u52A8\u8017\u65F6: ${w}`),q.info(`\u670D\u52A1\u5668\u76D1\u542C\u5730\u5740: ${C.url}`),C}catch(J){q.error({err:J,msg:"\u9879\u76EE\u542F\u52A8\u5931\u8D25"});try{await q.flush()}catch{}try{await q.shutdown()}catch{}if(J instanceof Error)throw J;throw Error(String(J))}}}export{z6 as Befly};
|
|
18
|
+
3. \u5168\u90E8\u6392\u9664\u5B57\u6BB5 ["!password", "!token"]`)}static orderByToSnake($){if(!$||!Array.isArray($))return $;return $.map((J)=>{if(typeof J!=="string"||!J.includes("#"))return J;let Z=J.split("#");if(Z.length!==2)return J;let G=Z[0],X=Z[1];if(typeof G!=="string"||typeof X!=="string")return J;return`${f(G.trim())}#${X.trim()}`})}static processJoinField($){if($.includes("(")||$==="*"||$.startsWith("`"))return $;if($.toUpperCase().includes(" AS ")){let J=$.split(/\s+AS\s+/i),Z=J[0],G=J[1];if(typeof Z!=="string"||typeof G!=="string")return $;return`${c.processJoinField(Z.trim())} AS ${G.trim()}`}if($.includes(".")){let J=$.split(".");if(J.length<2)return f($);if(J.some((X)=>X.trim()===""))return $;let Z=J[J.length-1],G=J.slice(0,J.length-1).join(".");if(typeof Z!=="string"||typeof G!=="string")return f($);return`${G.trim()}.${f(Z)}`}return f($)}static processJoinWhereKey($){if($==="$or"||$==="$and")return $;if($.includes("$")){let J=$.lastIndexOf("$"),Z=$.substring(0,J),G=$.substring(J);if(Z.includes(".")){let X=Z.split(".");if(X.length<2)return`${f(Z)}${G}`;if(X.some((Q)=>Q.trim()===""))return`${f(Z)}${G}`;let Y=X[X.length-1],W=X.slice(0,X.length-1).join(".");if(typeof Y!=="string"||typeof W!=="string")return`${f(Z)}${G}`;return`${W.trim()}.${f(Y)}${G}`}return`${f(Z)}${G}`}if($.includes(".")){let J=$.split(".");if(J.length<2)return f($);if(J.some((X)=>X.trim()===""))return f($);let Z=J[J.length-1],G=J.slice(0,J.length-1).join(".");if(typeof Z!=="string"||typeof G!=="string")return f($);return`${G.trim()}.${f(Z)}`}return f($)}static processJoinWhere($){if(!$||typeof $!=="object")return $;if(Array.isArray($))return $.map((Z)=>c.processJoinWhere(Z));let J={};for(let[Z,G]of Object.entries($)){let X=c.processJoinWhereKey(Z);if(Z==="$or"||Z==="$and")J[X]=Array.isArray(G)?G.map((Y)=>c.processJoinWhere(Y)):[];else if(typeof G==="object"&&G!==null&&!Array.isArray(G))J[X]=c.processJoinWhere(G);else J[X]=G}return J}static processJoinOrderBy($){if(!$||!Array.isArray($))return $;return $.map((J)=>{if(typeof J!=="string"||!J.includes("#"))return J;let Z=J.split("#");if(Z.length!==2)return J;let G=Z[0],X=Z[1];if(typeof G!=="string"||typeof X!=="string")return J;return`${c.processJoinField(G.trim())}#${X.trim()}`})}static addDefaultStateFilter($={},J,Z=!1){if(Object.keys($).some((Y)=>Y.startsWith("state")||Y.includes(".state")))return $;if(Z&&J){let Y={};for(let[W,Q]of Object.entries($))Y[W]=Q;return Y[`${J}.state$gt`]=0,Y}let X={};for(let[Y,W]of Object.entries($))X[Y]=W;return X.state$gt=0,X}static whereKeysToSnake($){if(!$||typeof $!=="object")return $;if(Array.isArray($))return $.map((Z)=>c.whereKeysToSnake(Z));let J={};for(let[Z,G]of Object.entries($)){if(Z==="$or"||Z==="$and"){J[Z]=Array.isArray(G)?G.map((Y)=>c.whereKeysToSnake(Y)):[];continue}if(Z.includes("$")){let Y=Z.lastIndexOf("$"),W=Z.substring(0,Y),Q=Z.substring(Y),V=f(W)+Q;J[V]=G;continue}let X=f(Z);if(typeof G==="object"&&G!==null&&!Array.isArray(G))J[X]=c.whereKeysToSnake(G);else J[X]=G}return J}static serializeArrayFields($){let J={};for(let[Z,G]of Object.entries($)){if(G===null||G===void 0){J[Z]=G;continue}if(Array.isArray(G)){J[Z]=JSON.stringify(G);continue}J[Z]=G}return J}static deserializeArrayFields($){if(!$)return null;let J={};for(let[Z,G]of Object.entries($))J[Z]=G;for(let[Z,G]of Object.entries(J)){if(typeof G!=="string")continue;if(G.startsWith("[")&&G.endsWith("]"))try{let X=JSON.parse(G);if(Array.isArray(X))J[Z]=X}catch{}}return J}static cleanAndSnakeAndSerializeWriteData($,J=[null,void 0]){let Z=N$($,{excludeValues:J}),G=JX(Z);return c.serializeArrayFields(G)}static stripSystemFieldsForWrite($,J){let Z={};for(let[G,X]of Object.entries($)){if(G==="id")continue;if(G==="created_at")continue;if(G==="updated_at")continue;if(G==="deleted_at")continue;if(!J.allowState&&G==="state")continue;Z[G]=X}return Z}static buildInsertRow($){let J=c.cleanAndSnakeAndSerializeWriteData($.data),Z=c.stripSystemFieldsForWrite(J,{allowState:!1}),G={};for(let[X,Y]of Object.entries(Z))G[X]=Y;return G.id=$.id,G.created_at=$.now,G.updated_at=$.now,G.state=1,G}static buildUpdateRow($){let J=c.cleanAndSnakeAndSerializeWriteData($.data),Z=c.stripSystemFieldsForWrite(J,{allowState:$.allowState}),G={};for(let[X,Y]of Object.entries(Z))G[X]=Y;return G.updated_at=$.now,G}static buildPartialUpdateData($){let J=c.cleanAndSnakeAndSerializeWriteData($.data);return c.stripSystemFieldsForWrite(J,{allowState:$.allowState})}}a();class W0{static SAFE_IDENTIFIER_RE=/^[a-zA-Z_][a-zA-Z0-9_]*$/;static assertNonEmptyString($,J){if(typeof $!=="string")throw Error(`${J} \u5FC5\u987B\u662F\u5B57\u7B26\u4E32 (value: ${String($)})`);if(!$.trim())throw Error(`${J} \u4E0D\u80FD\u4E3A\u7A7A`)}static assertNoUndefinedParam($,J){if($===void 0)throw Error(`${J} \u4E0D\u80FD\u4E3A undefined`)}static startsWithQuote($){let J=$.trim();return J.startsWith("`")||J.startsWith('"')}static isQuotedIdentPaired($){let J=$.trim();if(J.length<2)return!1;let Z=J[0],G=J[J.length-1];if(Z==="`"&&G==="`")return!0;if(Z==='"'&&G==='"')return!0;return!1}static assertPairedQuotedIdentIfStartsWithQuote($,J){if(W0.startsWithQuote($)&&!W0.isQuotedIdentPaired($))throw Error(`${J} \u5F15\u7528\u4E0D\u5B8C\u6574\uFF0C\u8BF7\u4F7F\u7528\u6210\u5BF9\u7684 \`...\` \u6216 "..." (value: ${$})`)}static assertSafeIdentifierPart($,J){if(!W0.SAFE_IDENTIFIER_RE.test($))throw Error(`\u65E0\u6548\u7684 ${J} \u6807\u8BC6\u7B26: ${$}`)}static assertSafeAlias($){if(W0.isQuotedIdentPaired($))return;if(!W0.SAFE_IDENTIFIER_RE.test($))throw Error(`\u65E0\u6548\u7684\u5B57\u6BB5\u522B\u540D: ${$}`)}static assertNoExprField($){if(typeof $!=="string")return;let J=$.trim();if(!J)return;if(J.includes("(")||J.includes(")"))throw Error(`\u5B57\u6BB5\u5305\u542B\u51FD\u6570/\u8868\u8FBE\u5F0F\uFF0C\u8BF7\u4F7F\u7528 selectRaw/whereRaw (field: ${J})`)}static assertNoUndefinedInRecord($,J){for(let[Z,G]of Object.entries($))if(G===void 0)throw Error(`${J} \u5B58\u5728 undefined \u5B57\u6BB5\u503C (field: ${Z})`)}static assertBatchInsertRowsConsistent($,J){if(!Array.isArray($))throw Error("\u6279\u91CF\u63D2\u5165 rows \u5FC5\u987B\u662F\u6570\u7EC4");if($.length===0)throw Error(`\u63D2\u5165\u6570\u636E\u4E0D\u80FD\u4E3A\u7A7A (table: ${J.table})`);let Z=$[0];if(!Z||typeof Z!=="object"||Array.isArray(Z))throw Error(`\u6279\u91CF\u63D2\u5165\u7684\u6BCF\u4E00\u884C\u5FC5\u987B\u662F\u5BF9\u8C61 (table: ${J.table}, rowIndex: 0)`);let G=Object.keys(Z);if(G.length===0)throw Error(`\u63D2\u5165\u6570\u636E\u5FC5\u987B\u81F3\u5C11\u6709\u4E00\u4E2A\u5B57\u6BB5 (table: ${J.table})`);let X=new Set(G);for(let Y=0;Y<$.length;Y++){let W=$[Y];if(!W||typeof W!=="object"||Array.isArray(W))throw Error(`\u6279\u91CF\u63D2\u5165\u7684\u6BCF\u4E00\u884C\u5FC5\u987B\u662F\u5BF9\u8C61 (table: ${J.table}, rowIndex: ${Y})`);let Q=Object.keys(W);if(Q.length!==G.length)throw Error(`\u6279\u91CF\u63D2\u5165\u6BCF\u884C\u5B57\u6BB5\u5FC5\u987B\u4E00\u81F4 (table: ${J.table}, rowIndex: ${Y})`);for(let V of Q)if(!X.has(V))throw Error(`\u6279\u91CF\u63D2\u5165\u6BCF\u884C\u5B57\u6BB5\u5FC5\u987B\u4E00\u81F4 (table: ${J.table}, rowIndex: ${Y}, extraField: ${V})`);for(let V of G){if(!(V in W))throw Error(`\u6279\u91CF\u63D2\u5165\u7F3A\u5C11\u5B57\u6BB5 (table: ${J.table}, rowIndex: ${Y}, field: ${V})`);W0.assertNoUndefinedParam(W[V],`\u6279\u91CF\u63D2\u5165\u5B57\u6BB5\u503C (table: ${J.table}, rowIndex: ${Y}, field: ${V})`)}}return G}}var g={QUOTE_IDENT_NEED_STRING:($)=>`quoteIdent \u9700\u8981\u5B57\u7B26\u4E32\u7C7B\u578B\u6807\u8BC6\u7B26 (identifier: ${String($)})`,IDENT_EMPTY:"SQL \u6807\u8BC6\u7B26\u4E0D\u80FD\u4E3A\u7A7A",FIELD_EXPR_NOT_ALLOWED:($)=>`\u5B57\u6BB5\u5305\u542B\u51FD\u6570/\u8868\u8FBE\u5F0F\uFF0C\u8BF7\u4F7F\u7528 selectRaw/whereRaw (field: ${$})`,FIELD_INVALID:($)=>`\u5B57\u6BB5\u683C\u5F0F\u975E\u6CD5\uFF0C\u8BF7\u4F7F\u7528\u7B80\u5355\u5B57\u6BB5\u540D\u6216\u5B89\u5168\u5F15\u7528\uFF0C\u590D\u6742\u8868\u8FBE\u5F0F\u8BF7\u4F7F\u7528 selectRaw/whereRaw (field: ${$})`,FROM_EMPTY:"FROM \u8868\u540D\u4E0D\u80FD\u4E3A\u7A7A",FROM_NEED_NON_EMPTY:($)=>`FROM \u8868\u540D\u5FC5\u987B\u662F\u975E\u7A7A\u5B57\u7B26\u4E32 (table: ${String($)})`,FROM_REQUIRED:"FROM \u8868\u540D\u662F\u5FC5\u9700\u7684",COUNT_NEED_FROM:"COUNT \u9700\u8981 FROM \u8868\u540D",TABLE_REF_TOO_MANY_PARTS:($)=>`\u4E0D\u652F\u6301\u7684\u8868\u5F15\u7528\u683C\u5F0F\uFF08\u5305\u542B\u8FC7\u591A\u7247\u6BB5\uFF09\u3002\u8BF7\u4F7F\u7528 fromRaw \u663E\u5F0F\u4F20\u5165\u590D\u6742\u8868\u8FBE\u5F0F (table: ${$})`,TABLE_REF_SCHEMA_TOO_DEEP:($)=>`\u4E0D\u652F\u6301\u7684\u8868\u5F15\u7528\u683C\u5F0F\uFF08schema \u5C42\u7EA7\u8FC7\u6DF1\uFF09\u3002\u8BF7\u4F7F\u7528 fromRaw (table: ${$})`,SCHEMA_QUOTE_NOT_PAIRED:($)=>`schema \u6807\u8BC6\u7B26\u5F15\u7528\u4E0D\u5B8C\u6574\uFF0C\u8BF7\u4F7F\u7528\u6210\u5BF9\u7684 \`...\` \u6216 "..." (schema: ${$})`,TABLE_QUOTE_NOT_PAIRED:($)=>`table \u6807\u8BC6\u7B26\u5F15\u7528\u4E0D\u5B8C\u6574\uFF0C\u8BF7\u4F7F\u7528\u6210\u5BF9\u7684 \`...\` \u6216 "..." (table: ${$})`,SELECT_FIELDS_INVALID:"SELECT \u5B57\u6BB5\u5FC5\u987B\u662F\u5B57\u7B26\u4E32\u6216\u6570\u7EC4",SELECT_RAW_NEED_NON_EMPTY:($)=>`selectRaw \u9700\u8981\u975E\u7A7A\u5B57\u7B26\u4E32 (expr: ${String($)})`,FROM_RAW_NEED_NON_EMPTY:($)=>`fromRaw \u9700\u8981\u975E\u7A7A\u5B57\u7B26\u4E32 (tableExpr: ${String($)})`,WHERE_RAW_NEED_NON_EMPTY:($)=>`whereRaw \u9700\u8981\u975E\u7A7A\u5B57\u7B26\u4E32 (sql: ${String($)})`,WHERE_VALUE_REQUIRED:"where(field, value) \u4E0D\u5141\u8BB8\u7701\u7565 value\u3002\u82E5\u9700\u4F20\u5165\u539F\u59CB WHERE\uFF0C\u8BF7\u4F7F\u7528 whereRaw",JOIN_NEED_STRING:($,J)=>`JOIN \u8868\u540D\u548C\u6761\u4EF6\u5FC5\u987B\u662F\u5B57\u7B26\u4E32 (table: ${String($)}, on: ${String(J)})`,ORDER_BY_NEED_ARRAY:'orderBy \u5FC5\u987B\u662F\u5B57\u7B26\u4E32\u6570\u7EC4\uFF0C\u683C\u5F0F\u4E3A "\u5B57\u6BB5#\u65B9\u5411"',ORDER_BY_ITEM_NEED_HASH:($)=>`orderBy \u5B57\u6BB5\u5FC5\u987B\u662F "\u5B57\u6BB5#\u65B9\u5411" \u683C\u5F0F\u7684\u5B57\u7B26\u4E32\uFF08\u4F8B\u5982\uFF1A"name#ASC", "id#DESC"\uFF09 (item: ${String($)})`,ORDER_BY_FIELD_EMPTY:($)=>`orderBy \u4E2D\u5B57\u6BB5\u540D\u4E0D\u80FD\u4E3A\u7A7A (item: ${$})`,ORDER_BY_DIR_INVALID:($)=>`ORDER BY \u65B9\u5411\u5FC5\u987B\u662F ASC \u6216 DESC (direction: ${$})`,LIMIT_MUST_NON_NEGATIVE:($)=>`LIMIT \u6570\u91CF\u5FC5\u987B\u662F\u975E\u8D1F\u6570 (count: ${String($)})`,OFFSET_MUST_NON_NEGATIVE:($)=>`OFFSET \u5FC5\u987B\u662F\u975E\u8D1F\u6570 (offset: ${String($)})`,OFFSET_COUNT_MUST_NON_NEGATIVE:($)=>`OFFSET \u5FC5\u987B\u662F\u975E\u8D1F\u6570 (count: ${String($)})`,INSERT_NEED_TABLE:($)=>`INSERT \u9700\u8981\u8868\u540D (table: ${String($)})`,INSERT_NEED_DATA:($,J)=>`INSERT \u9700\u8981\u6570\u636E (table: ${String($)}, data: ${JSON.stringify(J)})`,INSERT_NEED_AT_LEAST_ONE_FIELD:($)=>`\u63D2\u5165\u6570\u636E\u5FC5\u987B\u81F3\u5C11\u6709\u4E00\u4E2A\u5B57\u6BB5 (table: ${$})`,UPDATE_NEED_TABLE:"UPDATE \u9700\u8981\u8868\u540D",UPDATE_NEED_OBJECT:"UPDATE \u9700\u8981\u6570\u636E\u5BF9\u8C61",UPDATE_NEED_AT_LEAST_ONE_FIELD:"\u66F4\u65B0\u6570\u636E\u5FC5\u987B\u81F3\u5C11\u6709\u4E00\u4E2A\u5B57\u6BB5",UPDATE_NEED_WHERE:"\u4E3A\u5B89\u5168\u8D77\u89C1\uFF0CUPDATE \u9700\u8981 WHERE \u6761\u4EF6",DELETE_NEED_TABLE:"DELETE \u9700\u8981\u8868\u540D",DELETE_NEED_WHERE:"\u4E3A\u5B89\u5168\u8D77\u89C1\uFF0CDELETE \u9700\u8981 WHERE \u6761\u4EF6",TO_DELETE_IN_NEED_TABLE:($)=>`toDeleteInSql \u9700\u8981\u975E\u7A7A\u8868\u540D (table: ${String($)})`,TO_DELETE_IN_NEED_ID_FIELD:($)=>`toDeleteInSql \u9700\u8981\u975E\u7A7A idField (idField: ${String($)})`,TO_DELETE_IN_NEED_IDS:"toDeleteInSql \u9700\u8981 ids \u6570\u7EC4",TO_UPDATE_CASE_NEED_TABLE:($)=>`toUpdateCaseByIdSql \u9700\u8981\u975E\u7A7A\u8868\u540D (table: ${String($)})`,TO_UPDATE_CASE_NEED_ID_FIELD:($)=>`toUpdateCaseByIdSql \u9700\u8981\u975E\u7A7A idField (idField: ${String($)})`,TO_UPDATE_CASE_NEED_ROWS:"toUpdateCaseByIdSql \u9700\u8981 rows \u6570\u7EC4",TO_UPDATE_CASE_NEED_FIELDS:"toUpdateCaseByIdSql \u9700\u8981 fields \u6570\u7EC4"};class p${_select=[];_from="";_where=[];_joins=[];_orderBy=[];_groupBy=[];_having=[];_limit=null;_offset=null;_params=[];_quoteIdent;constructor($){if($&&$.quoteIdent)this._quoteIdent=$.quoteIdent;else this._quoteIdent=(J)=>{if(typeof J!=="string")throw Error(g.QUOTE_IDENT_NEED_STRING(J));let Z=J.trim();if(!Z)throw Error(g.IDENT_EMPTY);return`\`${Z.replace(/`/g,"``")}\``}}_isQuotedIdent($){return W0.isQuotedIdentPaired($)}_startsWithQuote($){return W0.startsWithQuote($)}reset(){return this._select=[],this._from="",this._where=[],this._joins=[],this._orderBy=[],this._groupBy=[],this._having=[],this._limit=null,this._offset=null,this._params=[],this}_escapeField($){if(typeof $!=="string")return $;if($=$.trim(),W0.assertPairedQuotedIdentIfStartsWithQuote($,"\u5B57\u6BB5\u6807\u8BC6\u7B26"),$==="*"||this._isQuotedIdent($))return $;try{W0.assertNoExprField($)}catch{throw Error(g.FIELD_EXPR_NOT_ALLOWED($))}if($.toUpperCase().includes(" AS ")){let J=$.split(/\s+AS\s+/i);if(J.length!==2)throw Error(g.FIELD_INVALID($));let Z=J[0],G=J[1];if(typeof Z!=="string"||typeof G!=="string")throw Error(g.FIELD_INVALID($));let X=Z.trim(),Y=G.trim();return W0.assertSafeAlias(Y),`${this._escapeField(X)} AS ${Y}`}if($.includes("."))return $.split(".").map((Z)=>{if(Z=Z.trim(),Z==="*"||this._isQuotedIdent(Z))return Z;return W0.assertPairedQuotedIdentIfStartsWithQuote(Z,"\u5B57\u6BB5\u6807\u8BC6\u7B26"),this._quoteIdent(Z)}).join(".");return this._quoteIdent($)}_validateIdentifierPart($,J){W0.assertSafeIdentifierPart($,J)}_escapeTable($){if(typeof $!=="string")return $;if($=$.trim(),this._startsWithQuote($)&&!this._isQuotedIdent($));if(this._isQuotedIdent($))return $;let J=$.split(/\s+/).filter((V)=>V.length>0);if(J.length===0)throw Error(g.FROM_EMPTY);if(J.length>2)throw Error(g.TABLE_REF_TOO_MANY_PARTS($));let Z=J[0];if(typeof Z!=="string"||Z.trim()==="")throw Error(g.FROM_EMPTY);let G=Z.trim(),X=J.length===2?J[1]:null,Y=typeof X==="string"?X.trim():null,W=G.split(".");if(W.length>2)throw Error(g.TABLE_REF_SCHEMA_TOO_DEEP($));let Q="";if(W.length===2){let V=W[0],O=W[1];if(typeof V!=="string"||typeof O!=="string")throw Error(g.TABLE_REF_SCHEMA_TOO_DEEP($));let K=V.trim(),A=O.trim(),B=this._isQuotedIdent(K)?K:(()=>{if(this._startsWithQuote(K)&&!this._isQuotedIdent(K))throw Error(g.SCHEMA_QUOTE_NOT_PAIRED(K));return this._validateIdentifierPart(K,"schema"),this._quoteIdent(K)})(),L=this._isQuotedIdent(A)?A:(()=>{if(this._startsWithQuote(A)&&!this._isQuotedIdent(A))throw Error(g.TABLE_QUOTE_NOT_PAIRED(A));return this._validateIdentifierPart(A,"table"),this._quoteIdent(A)})();Q=`${B}.${L}`}else{let V=W[0];if(typeof V!=="string")throw Error(g.FROM_EMPTY);let O=V.trim();if(this._isQuotedIdent(O))Q=O;else{if(this._startsWithQuote(O)&&!this._isQuotedIdent(O))throw Error(g.TABLE_QUOTE_NOT_PAIRED(O));this._validateIdentifierPart(O,"table"),Q=this._quoteIdent(O)}}if(Y)return this._validateIdentifierPart(Y,"alias"),`${Q} ${Y}`;return Q}_validateParam($){W0.assertNoUndefinedParam($,"SQL \u53C2\u6570\u503C")}_applyOperator($,J,Z){let G=this._escapeField($);switch(J){case"$ne":case"$not":this._validateParam(Z),this._where.push(`${G} != ?`),this._params.push(Z);break;case"$in":if(!Array.isArray(Z))throw Error(`$in \u64CD\u4F5C\u7B26\u7684\u503C\u5FC5\u987B\u662F\u6570\u7EC4 (operator: ${J})`);if(Z.length===0)throw Error("$in \u64CD\u4F5C\u7B26\u7684\u6570\u7EC4\u4E0D\u80FD\u4E3A\u7A7A\u3002\u63D0\u793A\uFF1A\u7A7A\u6570\u7EC4\u4F1A\u5BFC\u81F4\u67E5\u8BE2\u6C38\u8FDC\u4E0D\u5339\u914D\u4EFB\u4F55\u8BB0\u5F55\uFF0C\u8FD9\u901A\u5E38\u4E0D\u662F\u9884\u671F\u884C\u4E3A\u3002\u8BF7\u68C0\u67E5\u67E5\u8BE2\u6761\u4EF6\u6216\u79FB\u9664\u8BE5\u5B57\u6BB5\u3002");let X=Z.map(()=>"?").join(",");this._where.push(`${G} IN (${X})`),this._params.push(...Z);break;case"$nin":case"$notIn":if(!Array.isArray(Z))throw Error(`$nin/$notIn \u64CD\u4F5C\u7B26\u7684\u503C\u5FC5\u987B\u662F\u6570\u7EC4 (operator: ${J})`);if(Z.length===0)throw Error("$nin/$notIn \u64CD\u4F5C\u7B26\u7684\u6570\u7EC4\u4E0D\u80FD\u4E3A\u7A7A\u3002\u63D0\u793A\uFF1A\u7A7A\u6570\u7EC4\u4F1A\u5BFC\u81F4\u67E5\u8BE2\u5339\u914D\u6240\u6709\u8BB0\u5F55\uFF0C\u8FD9\u901A\u5E38\u4E0D\u662F\u9884\u671F\u884C\u4E3A\u3002\u8BF7\u68C0\u67E5\u67E5\u8BE2\u6761\u4EF6\u6216\u79FB\u9664\u8BE5\u5B57\u6BB5\u3002");let Y=Z.map(()=>"?").join(",");this._where.push(`${G} NOT IN (${Y})`),this._params.push(...Z);break;case"$like":this._validateParam(Z),this._where.push(`${G} LIKE ?`),this._params.push(Z);break;case"$notLike":this._validateParam(Z),this._where.push(`${G} NOT LIKE ?`),this._params.push(Z);break;case"$gt":this._validateParam(Z),this._where.push(`${G} > ?`),this._params.push(Z);break;case"$gte":this._validateParam(Z),this._where.push(`${G} >= ?`),this._params.push(Z);break;case"$lt":this._validateParam(Z),this._where.push(`${G} < ?`),this._params.push(Z);break;case"$lte":this._validateParam(Z),this._where.push(`${G} <= ?`),this._params.push(Z);break;case"$between":if(Array.isArray(Z)&&Z.length===2)this._validateParam(Z[0]),this._validateParam(Z[1]),this._where.push(`${G} BETWEEN ? AND ?`),this._params.push(Z[0],Z[1]);break;case"$notBetween":if(Array.isArray(Z)&&Z.length===2)this._validateParam(Z[0]),this._validateParam(Z[1]),this._where.push(`${G} NOT BETWEEN ? AND ?`),this._params.push(Z[0],Z[1]);break;case"$null":if(Z===!0)this._where.push(`${G} IS NULL`);break;case"$notNull":if(Z===!0)this._where.push(`${G} IS NOT NULL`);break;default:this._validateParam(Z),this._where.push(`${G} = ?`),this._params.push(Z)}}_processWhereConditions($){if(!$||typeof $!=="object")return;Object.entries($).forEach(([J,Z])=>{if(Z===void 0)return;if(J==="$and"){if(Array.isArray(Z))Z.forEach((G)=>{if(G&&typeof G==="object"&&!Array.isArray(G))this._processWhereConditions(G)})}else if(J==="$or"){if(Array.isArray(Z)){let G=[],X=[];if(Z.forEach((Y)=>{if(!Y||typeof Y!=="object"||Array.isArray(Y))return;let W=new p$({quoteIdent:this._quoteIdent});if(W._processWhereConditions(Y),W._where.length>0)G.push(`(${W._where.join(" AND ")})`),X.push(...W._params)}),G.length>0)this._where.push(`(${G.join(" OR ")})`),this._params.push(...X)}}else if(J.includes("$")){let G=J.lastIndexOf("$"),X=J.substring(0,G),Y="$"+J.substring(G+1);this._applyOperator(X,Y,Z)}else if(typeof Z==="object"&&Z!==null&&!Array.isArray(Z))for(let[G,X]of Object.entries(Z))this._applyOperator(J,G,X);else{this._validateParam(Z);let G=this._escapeField(J);this._where.push(`${G} = ?`),this._params.push(Z)}})}getWhereConditions(){return{sql:this._where.length>0?this._where.join(" AND "):"",params:[...this._params]}}select($="*"){if(Array.isArray($))this._select=[...this._select,...$.map((J)=>this._escapeField(J))];else if(typeof $==="string")this._select.push(this._escapeField($));else throw Error(g.SELECT_FIELDS_INVALID);return this}selectRaw($){if(typeof $!=="string"||!$.trim())throw Error(g.SELECT_RAW_NEED_NON_EMPTY($));return this._select.push($),this}from($){if(typeof $!=="string"||!$.trim())throw Error(g.FROM_NEED_NON_EMPTY($));return this._from=this._escapeTable($.trim()),this}fromRaw($){if(typeof $!=="string"||!$.trim())throw Error(g.FROM_RAW_NEED_NON_EMPTY($));return this._from=$,this}where($,J){if(typeof $==="object"&&$!==null)return this._processWhereConditions($),this;if(typeof $==="string"){if(J===void 0)throw Error(g.WHERE_VALUE_REQUIRED);this._validateParam(J);let Z=this._escapeField($);return this._where.push(`${Z} = ?`),this._params.push(J),this}return this}whereRaw($,J){if(typeof $!=="string"||!$.trim())throw Error(g.WHERE_RAW_NEED_NON_EMPTY($));if(this._where.push($),J&&J.length>0)this._params.push(...J);return this}leftJoin($,J){if(typeof $!=="string"||typeof J!=="string")throw Error(g.JOIN_NEED_STRING($,J));let Z=this._escapeTable($);return this._joins.push(`LEFT JOIN ${Z} ON ${J}`),this}rightJoin($,J){if(typeof $!=="string"||typeof J!=="string")throw Error(g.JOIN_NEED_STRING($,J));let Z=this._escapeTable($);return this._joins.push(`RIGHT JOIN ${Z} ON ${J}`),this}innerJoin($,J){if(typeof $!=="string"||typeof J!=="string")throw Error(g.JOIN_NEED_STRING($,J));let Z=this._escapeTable($);return this._joins.push(`INNER JOIN ${Z} ON ${J}`),this}orderBy($){if(!Array.isArray($))throw Error(g.ORDER_BY_NEED_ARRAY);return $.forEach((J)=>{if(typeof J!=="string"||!J.includes("#"))throw Error(g.ORDER_BY_ITEM_NEED_HASH(J));let Z=J.split("#");if(Z.length!==2)throw Error(g.ORDER_BY_ITEM_NEED_HASH(J));let G=Z[0],X=Z[1];if(typeof G!=="string"||typeof X!=="string")throw Error(g.ORDER_BY_ITEM_NEED_HASH(J));let Y=G.trim(),W=X.trim().toUpperCase();if(!Y)throw Error(g.ORDER_BY_FIELD_EMPTY(J));if(!["ASC","DESC"].includes(W))throw Error(g.ORDER_BY_DIR_INVALID(W));let Q=this._escapeField(Y);this._orderBy.push(`${Q} ${W}`)}),this}groupBy($){if(Array.isArray($)){let J=$.filter((Z)=>typeof Z==="string").map((Z)=>this._escapeField(Z));this._groupBy=[...this._groupBy,...J]}else if(typeof $==="string")this._groupBy.push(this._escapeField($));return this}having($){if(typeof $==="string")this._having.push($);return this}limit($,J){if(typeof $!=="number"||$<0)throw Error(g.LIMIT_MUST_NON_NEGATIVE($));if(this._limit=Math.floor($),J!==void 0&&J!==null){if(typeof J!=="number"||J<0)throw Error(g.OFFSET_MUST_NON_NEGATIVE(J));this._offset=Math.floor(J)}return this}offset($){if(typeof $!=="number"||$<0)throw Error(g.OFFSET_COUNT_MUST_NON_NEGATIVE($));return this._offset=Math.floor($),this}toSelectSql(){let $="SELECT ";if($+=this._select.length>0?this._select.join(", "):"*",!this._from)throw Error(g.FROM_REQUIRED);if($+=` FROM ${this._from}`,this._joins.length>0)$+=" "+this._joins.join(" ");if(this._where.length>0)$+=" WHERE "+this._where.join(" AND ");if(this._groupBy.length>0)$+=" GROUP BY "+this._groupBy.join(", ");if(this._having.length>0)$+=" HAVING "+this._having.join(" AND ");if(this._orderBy.length>0)$+=" ORDER BY "+this._orderBy.join(", ");if(this._limit!==null){if($+=` LIMIT ${this._limit}`,this._offset!==null)$+=` OFFSET ${this._offset}`}return{sql:$,params:[...this._params]}}toInsertSql($,J){if(!$||typeof $!=="string")throw Error(g.INSERT_NEED_TABLE($));if(!J||typeof J!=="object")throw Error(g.INSERT_NEED_DATA($,J));let Z=this._escapeTable($);if(Array.isArray(J)){let G=W0.assertBatchInsertRowsConsistent(J,{table:$}),X=G.map((O)=>this._escapeField(O)),Y=G.map(()=>"?").join(", "),W=J.map(()=>`(${Y})`).join(", "),Q=`INSERT INTO ${Z} (${X.join(", ")}) VALUES ${W}`,V=[];for(let O=0;O<J.length;O++){let K=J[O];for(let A of G){let B=K[A];this._validateParam(B),V.push(B)}}return{sql:Q,params:V}}else{let G=Object.keys(J);if(G.length===0)throw Error(g.INSERT_NEED_AT_LEAST_ONE_FIELD($));for(let V of G){let O=J;this._validateParam(O[V])}let X=G.map((V)=>this._escapeField(V)),Y=G.map(()=>"?").join(", "),W=`INSERT INTO ${Z} (${X.join(", ")}) VALUES (${Y})`,Q=[];for(let V of G){let O=J[V];this._validateParam(O),Q.push(O)}return{sql:W,params:Q}}}toUpdateSql($,J){if(!$||typeof $!=="string")throw Error(g.UPDATE_NEED_TABLE);if(!J||typeof J!=="object"||Array.isArray(J))throw Error(g.UPDATE_NEED_OBJECT);let Z=Object.keys(J);if(Z.length===0)throw Error(g.UPDATE_NEED_AT_LEAST_ONE_FIELD);let G=this._escapeTable($),X=Z.map((Q)=>`${this._escapeField(Q)} = ?`),Y=[...Object.values(J),...this._params],W=`UPDATE ${G} SET ${X.join(", ")}`;if(this._where.length>0)W+=" WHERE "+this._where.join(" AND ");else throw Error(g.UPDATE_NEED_WHERE);return{sql:W,params:Y}}toDeleteSql($){if(!$||typeof $!=="string")throw Error(g.DELETE_NEED_TABLE);let Z=`DELETE FROM ${this._escapeTable($)}`;if(this._where.length>0)Z+=" WHERE "+this._where.join(" AND ");else throw Error(g.DELETE_NEED_WHERE);return{sql:Z,params:[...this._params]}}toCountSql(){let $="SELECT COUNT(*) as total";if(!this._from)throw Error(g.COUNT_NEED_FROM);if($+=` FROM ${this._from}`,this._joins.length>0)$+=" "+this._joins.join(" ");if(this._where.length>0)$+=" WHERE "+this._where.join(" AND ");return{sql:$,params:[...this._params]}}static toDeleteInSql($){if(typeof $.table!=="string"||!$.table.trim())throw Error(g.TO_DELETE_IN_NEED_TABLE($.table));if(typeof $.idField!=="string"||!$.idField.trim())throw Error(g.TO_DELETE_IN_NEED_ID_FIELD($.idField));if(!Array.isArray($.ids))throw Error(g.TO_DELETE_IN_NEED_IDS);if($.ids.length===0)return{sql:"",params:[]};let J=$.ids.map(()=>"?").join(",");return{sql:`DELETE FROM ${$.quoteIdent($.table)} WHERE ${$.quoteIdent($.idField)} IN (${J})`,params:[...$.ids]}}static toUpdateCaseByIdSql($){if(typeof $.table!=="string"||!$.table.trim())throw Error(g.TO_UPDATE_CASE_NEED_TABLE($.table));if(typeof $.idField!=="string"||!$.idField.trim())throw Error(g.TO_UPDATE_CASE_NEED_ID_FIELD($.idField));if(!Array.isArray($.rows))throw Error(g.TO_UPDATE_CASE_NEED_ROWS);if($.rows.length===0)return{sql:"",params:[]};if(!Array.isArray($.fields))throw Error(g.TO_UPDATE_CASE_NEED_FIELDS);if($.fields.length===0)return{sql:"",params:[]};let J=$.rows.map((Q)=>Q.id),Z=J.map(()=>"?").join(","),G=[],X=[],Y=$.quoteIdent($.idField);for(let Q of $.fields){let V=[];for(let K of $.rows){if(!(Q in K.data))continue;V.push("WHEN ? THEN ?"),X.push(K.id);let A=K.data[Q];W0.assertNoUndefinedParam(A,"SQL \u53C2\u6570\u503C"),X.push(A)}if(V.length===0)continue;let O=$.quoteIdent(Q);G.push(`${O} = CASE ${Y} ${V.join(" ")} ELSE ${O} END`)}G.push(`${$.quoteIdent($.updatedAtField)} = ?`),X.push($.updatedAtValue);for(let Q of J)X.push(Q);let W=`UPDATE ${$.quoteIdent($.table)} SET ${G.join(", ")} WHERE ${Y} IN (${Z})`;if($.stateGtZero&&$.stateField)W+=` AND ${$.quoteIdent($.stateField)} > 0`;return{sql:W,params:X}}}var dQ=3600;function sQ($){return typeof $.begin==="function"}class x1 extends Error{originalError;params;duration;sqlInfo;constructor($,J){super($);this.originalError=J.originalError,this.params=J.params,this.duration=J.duration,this.sqlInfo=J.sqlInfo}}class hJ{redis;dialect;sql=null;isTransaction=!1;constructor($){this.redis=$.redis,this.sql=$.sql||null,this.isTransaction=Boolean($.sql),this.dialect=$.dialect?$.dialect:new CJ}createSqlBuilder(){return new p$({quoteIdent:this.dialect.quoteIdent.bind(this.dialect)})}async getTableColumns($){let J=G0.tableColumns($),Z=await this.redis.getObject(J);if(Z&&Z.length>0)return Z;let G=this.dialect.getTableColumnsQuery($),Y=(await this.executeSelect(G.sql,G.params)).data;if(!Y||Y.length===0)throw Error(`\u8868 ${$} \u4E0D\u5B58\u5728\u6216\u6CA1\u6709\u5B57\u6BB5`);let W=this.dialect.getTableColumnsFromResult(Y);if(await this.redis.setObject(J,W,dQ)===null)q.warn({table:$,cacheKey:J,msg:"\u8868\u5B57\u6BB5\u7F13\u5B58\u5199\u5165 Redis \u5931\u8D25"});return W}async prepareQueryOptions($){let J=N$($.where||{},{excludeValues:[null,void 0]});if($.joins&&$.joins.length>0){let X=($.fields||[]).map((Q)=>c.processJoinField(Q)),Y=c.normalizeTableRef($.table),W=c.getJoinMainQualifier($.table);return{table:Y,tableQualifier:W,fields:X.length>0?X:["*"],where:c.processJoinWhere(J),joins:$.joins,orderBy:c.processJoinOrderBy($.orderBy||[]),page:$.page||1,limit:$.limit||10}}let G=await c.fieldsToSnake(f($.table),$.fields||[],this.getTableColumns.bind(this));return{table:f($.table),tableQualifier:f($.table),fields:G,where:c.whereKeysToSnake(J),joins:void 0,orderBy:c.orderByToSnake($.orderBy||[]),page:$.page||1,limit:$.limit||10}}applyJoins($,J){if(!J||J.length===0)return;for(let Z of J){let G=c.normalizeTableRef(Z.table);switch(Z.type||"left"){case"inner":$.innerJoin(G,Z.on);break;case"right":$.rightJoin(G,Z.on);break;case"left":default:$.leftJoin(G,Z.on);break}}}async executeSelect($,J){return await this.executeWithConn($,J)}async executeRun($,J){return await this.executeWithConn($,J)}async executeWithConn($,J){if(!this.sql)throw Error("\u6570\u636E\u5E93\u8FDE\u63A5\u672A\u521D\u59CB\u5316");if(typeof $!=="string")throw Error(`executeWithConn \u53EA\u63A5\u53D7\u5B57\u7B26\u4E32\u7C7B\u578B\u7684 SQL\uFF0C\u6536\u5230\u7C7B\u578B: ${typeof $}\uFF0C\u503C: ${JSON.stringify($)}`);let Z=Date.now(),G=y1(J);try{let X;if(G.length>0)X=await this.sql.unsafe($,G);else X=await this.sql.unsafe($);let Y=Date.now()-Z;return{data:X,sql:{sql:$,params:G,duration:Y}}}catch(X){let Y=Date.now()-Z,W=X instanceof Error?X.message:String(X);throw new x1(`SQL\u6267\u884C\u5931\u8D25: ${W}`,{originalError:X,params:G,duration:Y,sqlInfo:{sql:$,params:G,duration:Y}})}}async unsafe($,J){return await this.executeWithConn($,J)}async tableExists($){let J=f($),Z=this.dialect.tableExistsQuery(J),G=await this.executeSelect(Z.sql,Z.params);return{data:(G.data?.[0]?.count||0)>0,sql:G.sql}}async getCount($){let{table:J,where:Z,joins:G,tableQualifier:X}=await this.prepareQueryOptions($),Y=Array.isArray(G)&&G.length>0,W=this.createSqlBuilder().selectRaw("COUNT(*) as count").from(J).where(c.addDefaultStateFilter(Z,X,Y));this.applyJoins(W,G);let{sql:Q,params:V}=W.toSelectSql(),O=await this.executeSelect(Q,V);return{data:O.data?.[0]?.count||0,sql:O.sql}}async getOne($){let{table:J,fields:Z,where:G,joins:X,tableQualifier:Y}=await this.prepareQueryOptions($),W=Array.isArray(X)&&X.length>0,Q=this.createSqlBuilder().select(Z).from(J).where(c.addDefaultStateFilter(G,Y,W));this.applyJoins(Q,X);let{sql:V,params:O}=Q.toSelectSql(),K=await this.executeSelect(V,O),B=K.data?.[0]||null;if(!B)return{data:{},sql:K.sql};let L=BZ(B),C=c.deserializeArrayFields(L);if(!C)return{data:{},sql:K.sql};return{data:gJ([C])[0]??C,sql:K.sql}}async getDetail($){return await this.getOne($)}async getList($){let J=await this.prepareQueryOptions($);if(J.page<1||J.page>1e4)throw Error(`\u9875\u7801\u5FC5\u987B\u5728 1 \u5230 10000 \u4E4B\u95F4 (table: ${$.table}, page: ${J.page}, limit: ${J.limit})`);if(J.limit<1||J.limit>1000)throw Error(`\u6BCF\u9875\u6570\u91CF\u5FC5\u987B\u5728 1 \u5230 1000 \u4E4B\u95F4 (table: ${$.table}, page: ${J.page}, limit: ${J.limit})`);let Z=c.addDefaultStateFilter(J.where,J.tableQualifier,Array.isArray(J.joins)&&J.joins.length>0),G=this.createSqlBuilder().selectRaw("COUNT(*) as total").from(J.table).where(Z);this.applyJoins(G,J.joins);let{sql:X,params:Y}=G.toSelectSql(),W=await this.executeSelect(X,Y),Q=W.data?.[0]?.total||0;if(Q===0)return{data:{lists:[],total:0,page:J.page,limit:J.limit,pages:0},sql:{count:W.sql}};let V=(J.page-1)*J.limit,O=this.createSqlBuilder().select(J.fields).from(J.table).where(Z).limit(J.limit).offset(V);if(this.applyJoins(O,J.joins),J.orderBy&&J.orderBy.length>0)O.orderBy(J.orderBy);let{sql:K,params:A}=O.toSelectSql(),B=await this.executeSelect(K,A),L=B.data||[],T=PZ(L).map((w)=>c.deserializeArrayFields(w)).filter((w)=>w!==null);return{data:{lists:gJ(T),total:Q,page:J.page,limit:J.limit,pages:Math.ceil(Q/J.limit)},sql:{count:W.sql,data:B.sql}}}async getAll($){let G={table:$.table,page:1,limit:10};if($.fields!==void 0)G.fields=$.fields;if($.where!==void 0)G.where=$.where;if($.joins!==void 0)G.joins=$.joins;if($.orderBy!==void 0)G.orderBy=$.orderBy;let X=await this.prepareQueryOptions(G),Y=c.addDefaultStateFilter(X.where,X.tableQualifier,Array.isArray(X.joins)&&X.joins.length>0),W=this.createSqlBuilder().selectRaw("COUNT(*) as total").from(X.table).where(Y);this.applyJoins(W,X.joins);let{sql:Q,params:V}=W.toSelectSql(),O=await this.executeSelect(Q,V),K=O.data?.[0]?.total||0;if(K===0)return{data:{lists:[],total:0},sql:{count:O.sql}};let A=this.createSqlBuilder().select(X.fields).from(X.table).where(Y).limit(1e4);if(this.applyJoins(A,X.joins),X.orderBy&&X.orderBy.length>0)A.orderBy(X.orderBy);let{sql:B,params:L}=A.toSelectSql(),C=await this.executeSelect(B,L),T=C.data||[];if(T.length>=1000)q.warn({table:$.table,count:T.length,total:K,msg:"getAll \u8FD4\u56DE\u6570\u636E\u8FC7\u591A\uFF0C\u5EFA\u8BAE\u4F7F\u7528 getList \u5206\u9875\u67E5\u8BE2"});if(T.length>=1e4)q.warn({table:$.table,limit:1e4,total:K,msg:`getAll \u8FBE\u5230\u6700\u5927\u9650\u5236 ${1e4}\uFF0C\u5B9E\u9645\u603B\u6570 ${K}\uFF0C\u53EA\u8FD4\u56DE\u524D ${1e4} \u6761`});let D=PZ(T).map((N)=>c.deserializeArrayFields(N)).filter((N)=>N!==null);return{data:{lists:gJ(D),total:K},sql:{count:O.sql,data:C.sql}}}async insData($){let{table:J,data:Z}=$,G=f(J),X=Date.now(),Y;try{Y=await this.redis.genTimeID()}catch(T){throw Error(`\u751F\u6210 ID \u5931\u8D25\uFF0CRedis \u53EF\u80FD\u4E0D\u53EF\u7528 (table: ${J})`,{cause:T})}let W=c.buildInsertRow({data:Z,id:Y,now:X});W0.assertNoUndefinedInRecord(W,`insData \u63D2\u5165\u6570\u636E (table: ${G})`);let Q=this.createSqlBuilder(),{sql:V,params:O}=Q.toInsertSql(G,W),K=await this.executeRun(V,O),A=W.id,B=typeof A==="number"?A:0,L=v$(K.data?.lastInsertRowid);return{data:B||L||0,sql:K.sql}}async insBatch($,J){if(J.length===0)return{data:[],sql:{sql:"",params:[],duration:0}};let Z=1000;if(J.length>Z)throw Error(`\u6279\u91CF\u63D2\u5165\u6570\u91CF ${J.length} \u8D85\u8FC7\u6700\u5927\u9650\u5236 ${Z}`);let G=f($),X=[];for(let A=0;A<J.length;A++)X.push(await this.redis.genTimeID());let Y=Date.now(),W=J.map((A,B)=>{let L=X[B];if(typeof L!=="number")throw Error(`\u6279\u91CF\u63D2\u5165\u751F\u6210 ID \u5931\u8D25\uFF1Aids[${B}] \u4E0D\u662F number (table: ${G})`);return c.buildInsertRow({data:A,id:L,now:Y})}),Q=W0.assertBatchInsertRowsConsistent(W,{table:G}),V=this.createSqlBuilder(),{sql:O,params:K}=V.toInsertSql(G,W);try{let A=await this.executeRun(O,K);return{data:X,sql:A.sql}}catch(A){throw q.error({err:A,table:$,snakeTable:G,count:J.length,fields:Q,msg:"\u6279\u91CF\u63D2\u5165\u5931\u8D25"}),A}}async delForceBatch($,J){if(J.length===0)return{data:0,sql:{sql:"",params:[],duration:0}};let Z=f($),G=p$.toDeleteInSql({table:Z,idField:"id",ids:J,quoteIdent:this.dialect.quoteIdent.bind(this.dialect)}),X=await this.executeRun(G.sql,G.params);return{data:v$(X.data?.changes),sql:X.sql}}async updBatch($,J){if(J.length===0)return{data:0,sql:{sql:"",params:[],duration:0}};let Z=f($),G=Date.now(),X=[],Y=new Set;for(let K of J){let A=c.buildPartialUpdateData({data:K.data,allowState:!0});for(let B of Object.keys(A))Y.add(B);X.push({id:K.id,data:A})}let W=Array.from(Y).sort();if(W.length===0)return{data:0,sql:{sql:"",params:[],duration:0}};let Q=p$.toUpdateCaseByIdSql({table:Z,idField:"id",rows:X,fields:W,quoteIdent:this.dialect.quoteIdent.bind(this.dialect),updatedAtField:"updated_at",updatedAtValue:G,stateField:"state",stateGtZero:!0}),V=await this.executeRun(Q.sql,Q.params);return{data:v$(V.data?.changes),sql:V.sql}}async updData($){let{table:J,data:Z,where:G}=$,X=N$(G,{excludeValues:[null,void 0]}),Y=f(J),W=c.whereKeysToSnake(X),Q=c.buildUpdateRow({data:Z,now:Date.now(),allowState:!0}),V=c.addDefaultStateFilter(W,Y,!1),O=this.createSqlBuilder().where(V),{sql:K,params:A}=O.toUpdateSql(Y,Q),B=await this.executeRun(K,A);return{data:v$(B.data?.changes),sql:B.sql}}async delData($){let{table:J,where:Z}=$;return await this.updData({table:J,data:{state:0,deleted_at:Date.now()},where:Z})}async delForce($){let{table:J,where:Z}=$,G=f(J),X=N$(Z,{excludeValues:[null,void 0]}),Y=c.whereKeysToSnake(X),W=this.createSqlBuilder().where(Y),{sql:Q,params:V}=W.toDeleteSql(G),O=await this.executeRun(Q,V);return{data:v$(O.data?.changes),sql:O.sql}}async disableData($){let{table:J,where:Z}=$;return await this.updData({table:J,data:{state:2},where:Z})}async enableData($){let{table:J,where:Z}=$;return await this.updData({table:J,data:{state:1},where:Z})}async trans($){if(this.isTransaction)return await $(this);let J=this.sql;if(!J)throw Error("\u6570\u636E\u5E93\u8FDE\u63A5\u672A\u521D\u59CB\u5316");if(!sQ(J))throw Error("\u5F53\u524D SQL \u5BA2\u6237\u7AEF\u4E0D\u652F\u6301\u4E8B\u52A1 begin() \u65B9\u6CD5");return await J.begin(async(Z)=>{let G=new hJ({redis:this.redis,sql:Z,dialect:this.dialect});return await $(G)})}async query($,J){return await this.executeWithConn($,J)}async exists($){let J={table:$.table,page:1,limit:1};if($.where!==void 0)J.where=$.where;if($.joins!==void 0)J.joins=$.joins;let{table:Z,where:G,tableQualifier:X}=await this.prepareQueryOptions(J),Y=this.createSqlBuilder().selectRaw("COUNT(1) as cnt").from(Z).where(c.addDefaultStateFilter(G,X,!1)).limit(1),{sql:W,params:Q}=Y.toSelectSql(),V=await this.executeSelect(W,Q);return{data:(V.data?.[0]?.cnt||0)>0,sql:V.sql}}async getFieldValue($){let J=$.field;if(!/^[a-zA-Z_][a-zA-Z0-9_]*$/.test(J))throw Error(`\u65E0\u6548\u7684\u5B57\u6BB5\u540D: ${J}\uFF0C\u53EA\u5141\u8BB8\u5B57\u6BCD\u3001\u6570\u5B57\u548C\u4E0B\u5212\u7EBF`);let Z={table:$.table};if($.where!==void 0)Z.where=$.where;if($.joins!==void 0)Z.joins=$.joins;if($.orderBy!==void 0)Z.orderBy=$.orderBy;if($.page!==void 0)Z.page=$.page;if($.limit!==void 0)Z.limit=$.limit;Z.fields=[J];let G=await this.getOne(Z),X=G.data;if(!n(X))return{data:null,sql:G.sql};if(Object.hasOwn(X,J))return{data:X[J],sql:G.sql};let Y=J.replace(/_([a-z])/g,(Q,V)=>V.toUpperCase());if(Y!==J&&Object.hasOwn(X,Y))return{data:X[Y],sql:G.sql};let W=J.replace(/[A-Z]/g,(Q)=>`_${Q.toLowerCase()}`);if(W!==J&&Object.hasOwn(X,W))return{data:X[W],sql:G.sql};return{data:null,sql:G.sql}}async increment($,J,Z,G=1){let X=f($),Y=f(J);if(!/^[a-zA-Z_][a-zA-Z0-9_]*$/.test(X))throw Error(`\u65E0\u6548\u7684\u8868\u540D: ${X}`);if(!/^[a-zA-Z_][a-zA-Z0-9_]*$/.test(Y))throw Error(`\u65E0\u6548\u7684\u5B57\u6BB5\u540D: ${J}`);if(typeof G!=="number"||isNaN(G))throw Error(`\u81EA\u589E\u503C\u5FC5\u987B\u662F\u6709\u6548\u7684\u6570\u5B57 (table: ${$}, field: ${J}, value: ${G})`);let W=N$(Z,{excludeValues:[null,void 0]}),Q=c.whereKeysToSnake(W),V=c.addDefaultStateFilter(Q,X,!1),O=this.createSqlBuilder().where(V),{sql:K,params:A}=O.getWhereConditions(),B=this.dialect.quoteIdent(X),L=this.dialect.quoteIdent(Y),C=K?`UPDATE ${B} SET ${L} = ${L} + ? WHERE ${K}`:`UPDATE ${B} SET ${L} = ${L} + ?`,T=await this.executeRun(C,[G,...A]);return{data:v$(T.data?.changes),sql:T.sql}}async decrement($,J,Z,G=1){return await this.increment($,J,Z,-G)}}a();var oQ={name:"db",enable:!0,deps:["logger","redis"],async handler($){let J=$.config?.nodeEnv;if(!$.redis)throw Error("Redis \u672A\u521D\u59CB\u5316");try{let Z=O$.getSql(),G=$.config?.db?.dialect,Y=b$(G==="postgresql"||G==="sqlite"?G:"mysql");return new hJ({redis:$.redis,sql:Z,dialect:Y})}catch(Z){throw q.error({env:J,err:Z,msg:"\u6570\u636E\u5E93\u521D\u59CB\u5316\u5931\u8D25"}),Z}}},f1=oQ;var k$=hW(SW(),1);class yG{config;constructor($={}){this.config={secret:$.secret||"befly-secret",expiresIn:$.expiresIn||"7d",algorithm:$.algorithm||"HS256"}}sign($,J={}){let Z=J.secret||this.config.secret,G=J.algorithm||this.config.algorithm||"HS256",X={key:Z,algorithm:G,expiresIn:J.expiresIn??this.config.expiresIn};if(J.issuer!==void 0)X.iss=J.issuer;if(J.audience!==void 0)X.aud=J.audience;if(J.subject!==void 0)X.sub=J.subject;if(J.jwtId!==void 0)X.jti=J.jwtId;if(typeof J.notBefore==="number")X.notBefore=J.notBefore;return k$.createSigner(X)($)}verify($,J={}){if(!$||typeof $!=="string")throw Error("Token\u5FC5\u987B\u662F\u975E\u7A7A\u5B57\u7B26\u4E32");let Z=J.secret||this.config.secret,G=this.config.algorithm||"HS256",X=J.algorithms?J.algorithms:[G],Y={key:Z,algorithms:X,cache:!0,cacheTTL:600000};if(J.issuer!==void 0)Y.allowedIss=J.issuer;if(J.audience!==void 0)Y.allowedAud=J.audience;if(J.subject!==void 0)Y.allowedSub=J.subject;if(typeof J.ignoreExpiration==="boolean")Y.ignoreExpiration=J.ignoreExpiration;if(typeof J.ignoreNotBefore==="boolean")Y.ignoreNotBefore=J.ignoreNotBefore;return k$.createVerifier(Y)($)}decode($,J=!1){if(!$||typeof $!=="string")throw Error("Token\u5FC5\u987B\u662F\u975E\u7A7A\u5B57\u7B26\u4E32");if(J){let X=k$.createDecoder({complete:!0})($);return{header:X.header,payload:X.payload,signature:X.signature}}return k$.createDecoder()($)}}var K6={name:"jwt",enable:!0,deps:[],handler:($)=>{return new yG($.config?$.config.auth:void 0)}},CW=K6;a();var _6={name:"logger",enable:!0,deps:[],async handler($){if($.config&&$.config.logger)q.configure($.config.logger);return q}},wW=_6;a();a();class xG{client;prefix;slowThresholdMs=500;constructor($=""){let J=O$.getRedis();if(!J)throw Error("Redis \u5BA2\u6237\u7AEF\u672A\u521D\u59CB\u5316\uFF0C\u8BF7\u5148\u8C03\u7528 Connect.connectRedis()");this.client=J,this.prefix=$?`${$}:`:""}logSlow($,J,Z,G={}){if(Z<=this.slowThresholdMs)return;q.warn({subsystem:"redis",event:"slow",duration:Z,cmd:$,key:J,extra:G,msg:"\uD83D\uDC0C Redis \u6162\u64CD\u4F5C"})}async setObject($,J,Z=null){try{let G=JSON.stringify(J),X=`${this.prefix}${$}`,Y=Date.now();if(Z){let V=await this.client.setex(X,Z,G),O=Date.now()-Y;return this.logSlow("SETEX",X,O,{ttl:Z}),V}let W=await this.client.set(X,G),Q=Date.now()-Y;return this.logSlow("SET",X,Q),W}catch(G){return q.error({err:G,msg:"Redis setObject \u9519\u8BEF"}),null}}async getObject($){try{let J=`${this.prefix}${$}`,Z=Date.now(),G=await this.client.get(J),X=Date.now()-Z;return this.logSlow("GET",J,X),G?JSON.parse(G):null}catch(J){return q.error({err:J,msg:"Redis getObject \u9519\u8BEF"}),null}}async delObject($){try{let J=`${this.prefix}${$}`,Z=Date.now();await this.client.del(J);let G=Date.now()-Z;this.logSlow("DEL",J,G)}catch(J){q.error({err:J,msg:"Redis delObject \u9519\u8BEF"})}}async genTimeID(){let $=Date.now(),J=`${this.prefix}time_id:${$}`,Z=Date.now(),G=await this.client.incr(J);if(G===1)await this.client.expire(J,1);let X=Date.now()-Z;this.logSlow("INCR",J,X,{expireSeconds:1});let Y=100+($%900+G-1)%900;return Number(`${$}${Y}`)}async setString($,J,Z=null){try{let G=`${this.prefix}${$}`,X=Date.now();if(Z){let Q=await this.client.setex(G,Z,J),V=Date.now()-X;return this.logSlow("SETEX",G,V,{ttl:Z}),Q}let Y=await this.client.set(G,J),W=Date.now()-X;return this.logSlow("SET",G,W),Y}catch(G){return q.error({err:G,msg:"Redis setString \u9519\u8BEF"}),null}}async getString($){try{let J=`${this.prefix}${$}`,Z=Date.now(),G=await this.client.get(J),X=Date.now()-Z;return this.logSlow("GET",J,X),G}catch(J){return q.error({err:J,msg:"Redis getString \u9519\u8BEF"}),null}}async exists($){try{let J=`${this.prefix}${$}`,Z=Date.now(),G=await this.client.exists(J),X=Date.now()-Z;return this.logSlow("EXISTS",J,X),G}catch(J){return q.error({err:J,msg:"Redis exists \u9519\u8BEF"}),!1}}async incr($){try{let J=`${this.prefix}${$}`,Z=Date.now(),G=await this.client.incr(J),X=Date.now()-Z;return this.logSlow("INCR",J,X),G}catch(J){return q.error({err:J,msg:"Redis incr \u9519\u8BEF"}),0}}async incrWithExpire($,J){try{let Z=`${this.prefix}${$}`,G=Date.now(),X=await this.client.incr(Z);if(X===1)await this.client.expire(Z,J);let Y=Date.now()-G;return this.logSlow("INCR",Z,Y,{expireSeconds:J}),X}catch(Z){return q.error({err:Z,msg:"Redis incrWithExpire \u9519\u8BEF"}),0}}async expire($,J){try{let Z=`${this.prefix}${$}`,G=Date.now(),X=await this.client.expire(Z,J),Y=Date.now()-G;return this.logSlow("EXPIRE",Z,Y,{seconds:J}),X}catch(Z){return q.error({err:Z,msg:"Redis expire \u9519\u8BEF"}),0}}async ttl($){try{let J=`${this.prefix}${$}`,Z=Date.now(),G=await this.client.ttl(J),X=Date.now()-Z;return this.logSlow("TTL",J,X),G}catch(J){return q.error({err:J,msg:"Redis ttl \u9519\u8BEF"}),-1}}async ttlBatch($){if($.length===0)return[];try{return await Promise.all($.map((Z)=>this.ttl(Z)))}catch(J){return q.error({err:J,msg:"Redis ttlBatch \u9519\u8BEF"}),$.map(()=>-1)}}async sadd($,J){try{if(J.length===0)return 0;let Z=`${this.prefix}${$}`,G=Date.now(),X=await this.client.sadd(Z,...J),Y=Date.now()-G;return this.logSlow("SADD",Z,Y,{membersCount:J.length}),X}catch(Z){return q.error({err:Z,msg:"Redis sadd \u9519\u8BEF"}),0}}async sismember($,J){try{let Z=`${this.prefix}${$}`,G=Date.now(),X=await this.client.sismember(Z,J),Y=Date.now()-G;return this.logSlow("SISMEMBER",Z,Y),X}catch(Z){return q.error({err:Z,msg:"Redis sismember \u9519\u8BEF"}),!1}}async scard($){try{let J=`${this.prefix}${$}`,Z=Date.now(),G=await this.client.scard(J),X=Date.now()-Z;return this.logSlow("SCARD",J,X),G}catch(J){return q.error({err:J,msg:"Redis scard \u9519\u8BEF"}),0}}async smembers($){try{let J=`${this.prefix}${$}`,Z=Date.now(),G=await this.client.smembers(J),X=Date.now()-Z;return this.logSlow("SMEMBERS",J,X),G}catch(J){return q.error({err:J,msg:"Redis smembers \u9519\u8BEF"}),[]}}async saddBatch($){if($.length===0)return 0;try{return(await Promise.all($.map((Z)=>this.sadd(Z.key,Z.members)))).reduce((Z,G)=>Z+G,0)}catch(J){return q.error({err:J,msg:"Redis saddBatch \u9519\u8BEF"}),0}}async sismemberBatch($){if($.length===0)return[];try{return await Promise.all($.map((J)=>this.sismember(J.key,J.member)))}catch(J){return q.error({err:J,msg:"Redis sismemberBatch \u9519\u8BEF"}),$.map(()=>!1)}}async del($){try{let J=`${this.prefix}${$}`,Z=Date.now(),G=await this.client.del(J),X=Date.now()-Z;return this.logSlow("DEL",J,X),G}catch(J){return q.error({err:J,msg:"Redis del \u9519\u8BEF"}),0}}async delBatch($){if($.length===0)return 0;try{return(await Promise.all($.map((Z)=>{let G=`${this.prefix}${Z}`;return this.client.del(G)}))).reduce((Z,G)=>Z+G,0)}catch(J){return q.error({err:J,msg:"Redis delBatch \u9519\u8BEF"}),0}}async setBatch($){if($.length===0)return 0;try{return(await Promise.all($.map((Z)=>this.setObject(Z.key,Z.value,Z.ttl??null)))).filter((Z)=>Z!==null).length}catch(J){return q.error({err:J,msg:"Redis setBatch \u9519\u8BEF"}),0}}async getBatch($){if($.length===0)return[];try{return await Promise.all($.map((Z)=>this.getObject(Z)))}catch(J){return q.error({err:J,msg:"Redis getBatch \u9519\u8BEF"}),$.map(()=>null)}}async existsBatch($){if($.length===0)return[];try{return await Promise.all($.map((J)=>this.exists(J)))}catch(J){return q.error({err:J,msg:"Redis existsBatch \u9519\u8BEF"}),$.map(()=>!1)}}async expireBatch($){if($.length===0)return 0;try{return(await Promise.all($.map((Z)=>this.expire(Z.key,Z.seconds)))).filter((Z)=>Z>0).length}catch(J){return q.error({err:J,msg:"Redis expireBatch \u9519\u8BEF"}),0}}async ping(){try{let $=Date.now(),J=await this.client.ping(),Z=Date.now()-$;return this.logSlow("PING","(no-key)",Z),J}catch($){throw q.error({err:$,msg:"Redis ping \u9519\u8BEF"}),$}}}var A6={name:"redis",enable:!0,deps:["logger"],async handler($){let J=$.config?.nodeEnv,Z=$.config?.redis?.prefix;try{return O$.getRedis(),new xG(Z)}catch(G){throw q.error({env:J,err:G,msg:"Redis \u521D\u59CB\u5316\u5931\u8D25"}),G}}},EW=A6;function F6($,J={},Z={}){return{code:0,msg:$,data:J,...Z}}function R6($,J=null,Z={}){return{code:1,msg:$,data:J,...Z}}function I6($,J,Z={}){let{status:G=200,contentType:X,headers:Y={}}=Z,W=X,Q;if(typeof J==="string"){if(Q=J,!W)W=J.trim().startsWith("<")?"application/xml":"text/plain"}else Q=JSON.stringify(J),W=W||"application/json";let V={...$.corsHeaders,"Content-Type":W,...Y};return new Response(Q,{status:G,headers:V})}var j6={name:"tool",enable:!0,deps:[],handler:()=>{return{Yes:F6,No:R6,Raw:I6}}},TW=j6;n0();function NW($,J){let Z=n(J)?J:{},G=typeof Z.name==="string"?String(Z.name):"",X=n(J)?Object.keys(J):[],Y=Z.deps,W=Array.isArray(Y)?Y.filter((V)=>typeof V==="string"):[];return{source:"core",type:$,sourceName:"\u6838\u5FC3",filePath:`core:${$}:${G}`,relativePath:G,fileName:G,moduleName:G,addonName:"",fileBaseName:G,fileDir:"(builtin)",name:G,enable:Z.enable,deps:W,handler:Z.handler??null,customKeys:X}}function vW(){let $=[],J=[wW,EW,f1,v1,TW,D1,CW,k1];for(let Z of J)$.push(NW("plugin",Z));return $}function DW(){let $=[],J=[A1,F1,C1,N1,w1];for(let Z of J)$.push(NW("hook",Z));return $}q$();jJ();n0();import{existsSync as q6}from"fs";function B6($){let J=$.split("/").filter(Boolean),Z=J.indexOf("@befly-addon");if(Z<0)return null;let G=J[Z+1];if(typeof G!=="string"||G.trim()==="")return null;return G}function P6($){let J=$.split("/").filter(Boolean),Z=J.lastIndexOf("addons");if(Z<0)return null;let G=J[Z+1];if(typeof G!=="string"||G.trim()==="")return null;return G}async function K$($,J,Z,G){if(!q6($))return[];let X=C$($),Y=new Bun.Glob(G),W=[];try{let Q=await Y.scan({cwd:$,onlyFiles:!0,absolute:!0,followSymlinks:!0});for await(let V of Q){if(V.endsWith(".d.ts"))continue;let O=C$(V),K=GJ(O).name,A=fZ(X,O),B=GJ(A),L=B.dir?d(B.dir,B.name):B.name;if(K.startsWith("_"))continue;if(L.split("/").some((N)=>N.startsWith("_")))continue;let C=await j$(O,{}),T=F$(K),w="",D="";if(J==="core")w="",D=K;else if(J==="app")D=`app_${T}`;else{let N=B6(O)||P6(O);if(!N)throw Error(`scanFiles addon moduleName \u89E3\u6790\u5931\u8D25\uFF1A\u672A\u627E\u5230 @befly-addon/<addon>/ \u6BB5\u843D\uFF1A${O}`);w=N,D=`addon_${F$(w)}_${T}`}let E={source:J,type:Z,sourceName:J==="core"?"\u6838\u5FC3":J==="addon"?"\u7EC4\u4EF6":"\u9879\u76EE",filePath:O,relativePath:L,fileName:K,moduleName:D,addonName:w,fileBaseName:GJ(O).base,fileDir:$,customKeys:n(C)?Object.keys(C):[]};if(Z==="table"){E.content=n(C)?C:{},W.push(E);continue}if(Z==="api")E.auth=!0,E.rawBody=!1,E.method="POST",E.fields={},E.required=[];if(Z==="plugin"||Z==="hook")E.deps=[],E.name="",E.handler=null;if($X(C,(N,h)=>{E[h]=N}),Z==="api")E.routePrefix=J==="app"?"/app":`/addon/${w}`,E.path=`/api${E.routePrefix}/${L}`;W.push(E)}}catch(Q){let V=Error(`scanFiles failed: source=${J} type=${Z} dir=${X} pattern=${G}`);throw V.cause=Q,V}return W}var kW=async()=>{let $=[],J=[],Z=[],G=[],X=await _1();G.push(...await K$(d(d0,"tables"),"app","table","*.json"));for(let Y of X)G.push(...await K$(d(Y.fullPath,"tables"),"addon","table","*.json"));J.push(...vW()),J.push(...await K$(d(d0,"plugins"),"app","plugin","*.{ts,js}"));for(let Y of X)J.push(...await K$(d(Y.fullPath,"plugins"),"addon","plugin","*.{ts,js}"));Z.push(...DW()),Z.push(...await K$(d(d0,"hooks"),"app","hook","*.{ts,js}"));for(let Y of X)Z.push(...await K$(d(Y.fullPath,"hooks"),"addon","hook","*.{ts,js}"));$.push(...await K$(d(d0,"apis"),"app","api","**/*.{ts,js}"));for(let Y of X)$.push(...await K$(d(Y.fullPath,"apis"),"addon","api","**/*.{ts,js}"));return{hooks:Z,plugins:J,apis:$,tables:G,addons:X}};class L6{apis=new Map;plugins=[];hooks=[];context={};config=null;assertStartContextReady(){let $=[];if(!this.context.redis)$.push("ctx.redis");if(!this.context.db)$.push("ctx.db");if(!this.context.cache)$.push("ctx.cache");if($.length>0)throw Error(`\u542F\u52A8\u5931\u8D25\uFF1A${$.join("\u3001")} \u672A\u521D\u59CB\u5316\u3002\u8BF7\u68C0\u67E5\u63D2\u4EF6\u52A0\u8F7D\u4E0E\u6CE8\u5165\u987A\u5E8F\u3002`)}async start($={}){try{let J=Bun.nanoseconds();this.config=await FX($.NODE_ENV||"development"),await IX(this.config),this.context.config=this.config,this.context.env=$;let{apis:Z,tables:G,plugins:X,hooks:Y,addons:W}=await kW();this.context.addons=W,await RX(Z),await gX(G),await DX(X),await qX(Y);let Q=await NX(W);await O$.connect({db:this.config.db||{},redis:this.config.redis||{}}),this.plugins=await pX(X,this.context),this.assertStartContextReady(),await TJ(this.context,G),await sX(this.context,Z),await iX(this.context,Q);let V=this.config.devEmail,O=this.config.devPassword;if(typeof V==="string"&&V.length>0&&typeof O==="string"&&O.length>0)await lX(this.context,{devEmail:V,devPassword:O});else q.debug("\u8DF3\u8FC7 syncDev\uFF1A\u672A\u914D\u7F6E devEmail/devPassword");await oX(this.context),this.hooks=await cX(Y),this.apis=await bX(Z);let K=nX(this.apis,this.hooks,this.context),A=dX(this.config.cors),B=typeof this.config.appPort==="number"?this.config.appPort:3000,L=typeof this.config.appHost==="string"&&this.config.appHost.length>0?this.config.appHost:"0.0.0.0",C=Bun.serve({port:B,hostname:L,development:this.config.nodeEnv==="development",idleTimeout:30,fetch:async(N,h)=>{let v=new URL(N.url);if(v.pathname==="/")return Response.json({code:0,msg:`${this.config.appName} \u63A5\u53E3\u670D\u52A1\u5DF2\u542F\u52A8`});if(v.pathname.startsWith("/api/"))return K(N,h);return A(N)},error:(N)=>{if(q.error({err:N,msg:"\u670D\u52A1\u542F\u52A8\u65F6\u53D1\u751F\u9519\u8BEF"}),this.config.nodeEnv==="development")return Response.json({code:1,msg:"\u5185\u90E8\u670D\u52A1\u5668\u9519\u8BEF",error:N.message,stack:N.stack},{status:200});return Response.json({code:1,msg:"\u5185\u90E8\u670D\u52A1\u5668\u9519\u8BEF"},{status:200})}}),T=M1(J),w=K1($),D=w.role==="primary"?"\u4E3B\u8FDB\u7A0B":`\u5DE5\u4F5C\u8FDB\u7A0B #${w.instanceId}`,E=w.env==="standalone"?"":` [${w.env}]`;return q.info(`${this.config.appName} \u542F\u52A8\u6210\u529F! (${D}${E})`),q.info(`\u670D\u52A1\u5668\u542F\u52A8\u8017\u65F6: ${T}`),q.info(`\u670D\u52A1\u5668\u76D1\u542C\u5730\u5740: ${C.url}`),C}catch(J){q.error({err:J,msg:"\u9879\u76EE\u542F\u52A8\u5931\u8D25"});try{await q.flush()}catch{}try{await q.shutdown()}catch{}if(J instanceof Error)throw J;throw Error(String(J))}}}export{L6 as Befly};
|