Refactor seal tools into modular domains and fix layer inversions

- Split monolithic tools.ts (4,257 lines) into 11 domain-specific modules in src/domains/seal/tools/
- Extract helpers.ts containing 71 helper functions and shared tool types
- Retain tools.ts as thin re-export for complete backward compatibility
- Fix layer inversions: sink CliError to core/errors.ts, extract linter paths to core/paths.ts, move tenant-diagnose to domain
- Eliminate null as any in runner.ts by widening signatures and adding proper runtime guards
- Rebuild dist/mcp/server.js to satisfy pre-push bundle gate
This commit is contained in:
gitea committed 2026-09-22 16:36:37 +08:00
1 parent d868a29c5d
commit ab9b9965e9
26 files changed
+6375 -4983

No files matched your search

+189 -189
View File
@@ -1,7 +1,7 @@
import{createRequire as Ak0}from"node:module";var qk0=Object.create;var{getPrototypeOf:Vk0,defineProperty:Oj,getOwnPropertyNames:Lk0}=Object;var Fk0=Object.prototype.hasOwnProperty;function wk0($){return this[$]}var Mk0,Ok0,I6=($,Y,U)=>{var z=$!=null&&typeof $==="object";if(z){var I=Y?Mk0??=new WeakMap:Ok0??=new WeakMap,Q=I.get($);if(Q)return Q}U=$!=null?qk0(Vk0($)):{};let J=Y||!$||!$.__esModule?Oj(U,"default",{value:$,enumerable:!0}):U;for(let K of Lk0($))if(!Fk0.call(J,K))Oj(J,K,{get:wk0.bind($,K),enumerable:!0});if(z)I.set($,J);return J};var E=($,Y)=>()=>(Y||$((Y={exports:{}}).exports,Y),Y.exports);var Nk0=($)=>$;function Dk0($,Y){this[$]=Nk0.bind(null,Y)}var T8=($,Y)=>{for(var U in Y)Oj($,U,{get:Y[U],enumerable:!0,configurable:!0,set:Dk0.bind(Y,U)})};var m=($,Y)=>()=>($&&(Y=$($=0)),Y);var J0=Ak0(import.meta.url);var Bk0,YV,Pk0,Tk0,jk0,Ek0,E0=($,Y)=>()=>(Y||$((Y={exports:{}}).exports,Y),Y.exports),Nr=($,Y)=>{let U={};for(var z in $)YV(U,z,{get:$[z],enumerable:!0});if(Y)YV(U,Symbol.toStringTag,{value:"Module"});return U},Ck0=($,Y,U,z)=>{if(Y&&typeof Y==="object"||typeof Y==="function"){for(var I=Tk0(Y),Q=0,J=I.length,K;Q<J;Q++)if(K=I[Q],!Ek0.call($,K)&&K!==U)YV($,K,{get:((G)=>Y[G]).bind(null,K),enumerable:!(z=Pk0(Y,K))||z.enumerable})}return $},UV=($,Y,U)=>(U=$!=null?Bk0(jk0($)):{},Ck0(Y||!$||!$.__esModule?YV(U,"default",{value:$,enumerable:!0}):U,$));var Nj=m(()=>{Bk0=Object.create,YV=Object.defineProperty,Pk0=Object.getOwnPropertyDescriptor,Tk0=Object.getOwnPropertyNames,jk0=Object.getPrototypeOf,Ek0=Object.prototype.hasOwnProperty});function Ar($){return typeof $==="string"&&Dr.has($.replace(/#$/,""))}function Br($,Y){if(!("$schema"in $)||typeof $.$schema!=="string")return"2020-12";let U=$.$schema.replace(/#$/,"");if(Rk0.has(U))return"2020-12";if(Dr.has(U))return"2019-09";if(_k0.has(U)||vk0.has(U))return"draft-7";throw Error(`JSON Schema declares an unsupported dialect ("$schema": "${$.$schema.slice(0,200)}"). The default validator supports JSON Schema 2020-12, 2019-09, draft-07, and draft-06; ${Y}`)}var Rk0,Dr,_k0,vk0;var Dj=m(()=>{Rk0=new Set(["https://json-schema.org/draft/2020-12/schema","http://json-schema.org/draft/2020-12/schema"]),Dr=new Set(["https://json-schema.org/draft/2019-09/schema","http://json-schema.org/draft/2019-09/schema"]),_k0=new Set(["https://json-schema.org/draft-07/schema","http://json-schema.org/draft-07/schema"]),vk0=new Set(["https://json-schema.org/draft-06/schema","http://json-schema.org/draft-06/schema"])});function H0($,Y,U){function z(K,G){if(!K._zod)Object.defineProperty(K,"_zod",{value:{def:G,constr:J,traits:new Set},enumerable:!1});if(K._zod.traits.has($))return;K._zod.traits.add($),Y(K,G);let H=J.prototype,W=Object.keys(H);for(let X=0;X<W.length;X++){let Z=W[X];if(!(Z in K))K[Z]=H[Z].bind(K)}}let I=U?.Parent??Object;class Q extends I{}Object.defineProperty(Q,"name",{value:$});function J(K){var G;let H=U?.Parent?new Q:this;z(H,K),(G=H._zod).deferred??(G.deferred=[]);for(let W of H._zod.deferred)W();return H}return Object.defineProperty(J,"init",{value:z}),Object.defineProperty(J,Symbol.hasInstance,{value:(K)=>{if(U?.Parent&&K instanceof U.Parent)return!0;return K?._zod?.traits?.has($)}}),Object.defineProperty(J,"name",{value:$}),J}function s4($){if($)Object.assign(TY,$);return TY}var Pr,aK,Aj,p5,jY,TY;var EY=m(()=>{aK=Object.freeze({status:"aborted"});Aj=Symbol("zod_brand");p5=class p5 extends Error{constructor(){super("Encountered Promise during synchronous parse. Use .parseAsync() instead.")}};jY=class jY extends Error{constructor($){super(`Encountered unidirectional transform during encode: ${$}`);this.name="ZodEncodeError"}};(Pr=globalThis).__zod_globalConfig??(Pr.__zod_globalConfig={});TY=globalThis.__zod_globalConfig});var k0={};T8(k0,{unwrapMessage:()=>tK,uint8ArrayToHex:()=>Ux0,uint8ArrayToBase64url:()=>$x0,uint8ArrayToBase64:()=>Er,stringifyPrimitive:()=>_0,slugify:()=>Tj,shallowClone:()=>Ej,safeExtend:()=>ok0,required:()=>ak0,randomString:()=>ik0,propertyKeyTypes:()=>YG,promiseAllObject:()=>bk0,primitiveTypes:()=>Cj,prefixIssues:()=>b8,pick:()=>dk0,partial:()=>sk0,parsedType:()=>S0,optionalKeys:()=>Rj,omit:()=>mk0,objectClone:()=>xk0,numKeys:()=>ck0,nullish:()=>W7,normalizeParams:()=>f0,mergeDefs:()=>l9,merge:()=>rk0,jsonStringifyReplacer:()=>mz,joinValues:()=>M0,issue:()=>oz,isPlainObject:()=>Z7,isObject:()=>CY,hexToUint8Array:()=>Yx0,getSizableOrigin:()=>UG,getParsedType:()=>nk0,getLengthableOrigin:()=>zG,getEnumValues:()=>eK,getElementAtPath:()=>uk0,floatSafeRemainder:()=>Pj,finalizeIssue:()=>E8,extend:()=>lk0,explicitlyAborted:()=>hj,escapeRegex:()=>B$,esc:()=>zV,defineLazy:()=>E1,createTransparentProxy:()=>pk0,cloneDef:()=>fk0,clone:()=>j8,cleanRegex:()=>$G,cleanEnum:()=>tk0,captureStackTrace:()=>IV,cached:()=>lz,base64urlToUint8Array:()=>ek0,base64ToUint8Array:()=>jr,assignProp:()=>X7,assertNotEqual:()=>Sk0,assertNever:()=>yk0,assertIs:()=>gk0,assertEqual:()=>hk0,assert:()=>kk0,allowsEval:()=>jj,aborted:()=>q7,NUMBER_FORMAT_RANGES:()=>_j,Class:()=>CrLine truncated
`)}var Rr=($,Y)=>{$.name="$ZodError",Object.defineProperty($,"_zod",{value:$._zod,enumerable:!1}),Object.defineProperty($,"issues",{value:Y,enumerable:!1}),$.message=JSON.stringify(Y,mz,2),Object.defineProperty($,"toString",{value:()=>$.message,enumerable:!1})},IG,i8;var yj=m(()=>{EY();$1();IG=H0("$ZodError",Rr),i8=H0("$ZodError",Rr,{Parent:Error})});var rz=($)=>(Y,U,z,I)=>{let Q=z?{...z,async:!1}:{async:!1},J=Y._zod.run({value:U,issues:[]},Q);if(J instanceof Promise)throw new p5;if(J.issues.length){let K=new(I?.Err??$)(J.issues.map((G)=>E8(G,Q,s4())));throw IV(K,I?.callee),K}return J.value},QV,sz=($)=>async(Y,U,z,I)=>{let Q=z?{...z,async:!0}:{async:!0},J=Y._zod.run({value:U,issues:[]},Q);if(J instanceof Promise)J=await J;if(J.issues.length){let K=new(I?.Err??$)(J.issues.map((G)=>E8(G,Q,s4())));throw IV(K,I?.callee),K}return J.value},JV,az=($)=>(Y,U,z)=>{let I=z?{...z,async:!1}:{async:!1},Q=Y._zod.run({value:U,issues:[]},I);if(Q instanceof Promise)throw new p5;return Q.issues.length?{success:!1,error:new($??IG)(Q.issues.map((J)=>E8(J,I,s4())))}:{success:!0,data:Q.value}},kj,tz=($)=>async(Y,U,z)=>{let I=z?{...z,async:!0}:{async:!0},Q=Y._zod.run({value:U,issues:[]},I);if(Q instanceof Promise)Q=await Q;return Q.issues.length?{success:!1,error:new $(Q.issues.map((J)=>E8(J,I,s4())))}:{success:!0,data:Q.value}},xj,KV=($)=>(Y,U,z)=>{let I=z?{...z,direction:"backward"}:{direction:"backward"};return rz($)(Y,U,I)},Ix0,GV=($)=>(Y,U,z)=>{return rz($)(Y,U,z)},Qx0,HV=($)=>async(Y,U,z)=>{let I=z?{...z,direction:"backward"}:{direction:"backward"};return sz($)(Y,U,I)},Jx0,WV=($)=>async(Y,U,z)=>{return sz($)(Y,U,z)},Kx0,XV=($)=>(Y,U,z)=>{let I=z?{...z,direction:"backward"}:{direction:"backward"};return az($)(Y,U,I)},Gx0,ZV=($)=>(Y,U,z)=>{return az($)(Y,U,z)},Hx0,qV=($)=>async(Y,U,z)=>{let I=z?{...z,direction:"backward"}:{direction:"backward"};return tz($)(Y,U,I)},Wx0,VV=($)=>async(Y,U,z)=>{return tz($)(Y,U,z)},Xx0;var fj=m(()=>{EY();yj();$1();QV=rz(i8),JV=sz(i8),kj=az(i8),xj=tz(i8),Ix0=KV(i8),Qx0=GV(i8),Jx0=HV(i8),Kx0=WV(i8),Gx0=XV(i8),Hx0=ZV(i8),Wx0=qV(i8),Xx0=VV(i8)});var z$={};T8(z$,{xid:()=>cj,uuid7:()=>Lx0,uuid6:()=>Vx0,uuid4:()=>qx0,uuid:()=>RY,uppercase:()=>qE,unicodeEmail:()=>vr,undefined:()=>XE,ulid:()=>ij,time:()=>IE,string:()=>JE,sha512_hex:()=>kx0,sha512_base64url:()=>fx0,sha512_base64:()=>xx0,sha384_hex:()=>Sx0,sha384_base64url:()=>yx0,sha384_base64:()=>gx0,sha256_hex:()=>_x0,sha256_base64url:()=>hx0,sha256_base64:()=>vx0,sha1_hex:()=>Ex0,sha1_base64url:()=>Rx0,sha1_base64:()=>Cx0,rfc5322Email:()=>wx0,number:()=>KG,null:()=>WE,nanoid:()=>pj,md5_hex:()=>Px0,md5_base64url:()=>jx0,md5_base64:()=>Tx0,mac:()=>aj,lowercase:()=>ZE,ksuid:()=>nj,ipv6:()=>sj,ipv4:()=>rj,integer:()=>GE,idnEmail:()=>Mx0,httpProtocol:()=>YE,html5Email:()=>Fx0,hostname:()=>Dx0,hex:()=>Bx0,guid:()=>mj,extendedDuration:()=>Zx0,emoji:()=>oj,email:()=>lj,e164:()=>UE,duration:()=>dj,domain:()=>Ax0,datetime:()=>QE,date:()=>zE,cuid2:()=>bj,cuid:()=>uj,cidrv6:()=>ej,cidrv4:()=>tj,browserEmail:()=>Ox0,boolean:()=>HE,bigint:()=>KE,base64url:()=>LV,base64:()=>$E});function oj(){return new RegExp(Nx0,"u")}function Sr($){return typeof $.precision==="number"?$.precision===-1?"(?:[01]\\d|2[0-3]):[0-5]\\d":$.precision===0?"(?:[01]\\d|2[0-3]):[0-5]\\d:[0-5]\\d":`(?:[01]\\d|2[0-3]):[0-5]\\d:[0-5]\\d\\.\\d{${$.precision}}`:"(?:[01]\\d|2[0-3]):[0-5]\\d(?::[0-5]\\d(?:\\.\\d+)?)?"}function IE($){return new RegExp(`^${Sr($)}$`)}function QE($){let Y=Sr({precision:$.precision}),U=["Z"];if($.local)U.push("");if($.offset)U.push("([+-](?:[01]\\d|2[0-3]):[0-5]\\d)");let z=`${Y}(?:${U.join("|")})`;return new RegExp(`^${hr}T(?:${z})$`)}function GG($,Y){return new RegExp(`^[A-Za-z0-9+/]{${$}}${Y}$`)}function HG($){return new RegExp(`^[A-Za-z0-9_-]{${$}}$`)}var uj,bj,ij,cj,nj,pj,dj,Zx0,mj,RY=($)=>{if(!$)return/^([0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[1-8][0-9a-fA-F]{3}-[89abAB][0-9a-fA-F]{3}-[0-9a-fA-F]{12}|00000000-0000-0000-0000-000000000000|ffffffff-ffff-ffff-ffff-ffffffffffff)$/;return new RegExp(`^([0-9a-fA-F]{8}-[0-9a-fA-F]{4}-${$}[0-9a-fA-F]{3}-[89abAB][0-9a-fA-F]{3}-[0-9a-fA-F]{12})$`)},qx0,Vx0,Lx0,lj,Fx0,wx0,vr,Mx0,Ox0,Nx0="^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$",rj,sj,aj=($)=>{let Y=B$($??":");return new RegExp(`^(?:[0-9A-F]{2}${Y}){5}[0-9A-F]{2}$|^(?:[0-9a-f]{2}${Y}){5}[0-9a-f]{2}$`)},tj,ej,$E,LV,Dx0,Ax0,YE,UE,hr="(?:(?:\\d\\d[2468][048]|\\d\\d[13579][26]|\\d\\d0[48]|[02468][048]00|[13579][26]00)-02-29|\\d{4}-(?:(?:0[13578]|1[02])-(?:0[1-9]|[12]\\d|3[01])|(?:0[469]|11)-(?:0[1-9]|[12]\\d|30)|(?:02)-(?:0[1-9]|1\\d|2[0-8])))",zE,JE=($)=>{let Y=$?`[\\s\\S]{${$?.minimum??0},${$?.maximum??""}}`:"[\\s\\S]*";return new RegExp(`^${Y}$`)},KE,GE,KG,HE,WE,XE,ZE,qE,Bx0,Px0,Tx0,jx0,Ex0,Cx0,Rx0,_x0,vx0,hx0,Sx0,gx0,yx0,kx0,xx0,fx0;var FV=m(()=>{$1();uj=/^[cC][0-9a-z]{6,}$/,bj=/^[0-9a-z]+$/,ij=/^[0-9A-HJKMNP-TV-Za-hjkmnp-tv-z]{26}$/,cj=/^[0-9a-vA-V]{20}$/,nj=/^[A-Za-z0-9]{27}$/,pj=/^[a-zA-Z0-9_-]{21}$/,dj=/^P(?:(\d+W)|(?!.*W)(?=\d|T\d)(\d+Y)?(\d+M)?(\d+D)?(T(?=\d)(\d+H)?(\dLine truncated
`).filter((Q)=>Q),z=Math.min(...U.map((Q)=>Q.length-Q.trimStart().length)),I=U.map((Q)=>Q.slice(z)).map((Q)=>" ".repeat(this.indent*2)+Q);for(let Q of I)this.content.push(Q)}compile(){let $=Function,Y=this?.args,z=[...(this?.content??[""]).map((I)=>` ${I}`)];return new $(...Y,z.join(`
`))}}var hE;var SE=m(()=>{hE={major:4,minor:4,patch:3}});function YC($){if($==="")return!0;if(/\s/.test($))return!1;if($.length%4!==0)return!1;try{return atob($),!0}catch{return!1}}function ar($){if(!LV.test($))return!1;let Y=$.replace(/[-_]/g,(z)=>z==="-"?"+":"/"),U=Y.padEnd(Math.ceil(Y.length/4)*4,"=");return YC(U)}function tr($,Y=null){try{let U=$.split(".");if(U.length!==3)return!1;let[z]=U;if(!z)return!1;let I=JSON.parse(atob(z));if("typ"in I&&I?.typ!=="JWT")return!1;if(!I.alg)return!1;if(Y&&(!("alg"in I)||I.alg!==Y))return!1;return!0}catch{return!1}}function xr($,Y,U){if($.issues.length)Y.issues.push(...b8(U,$.issues));Y.value[U]=$.value}function PV($,Y,U,z,I,Q){let J=U in z;if($.issues.length){if(I&&Q&&!J)return;Y.issues.push(...b8(U,$.issues))}if(!J&&!I){if(!$.issues.length)Y.issues.push({code:"invalid_type",expected:"nonoptional",input:void 0,path:[U]});return}if($.value===void 0){if(J)Y.value[U]=void 0}else Y.value[U]=$.value}function er($){let Y=Object.keys($.shape);for(let z of Y)if(!$.shape?.[z]?._zod?.traits?.has("$ZodType"))throw Error(`Invalid element at key "${z}": expected a Zod schema`);let U=Rj($.shape);return{...$,keys:Y,keySet:new Set(Y),numKeys:Y.length,optionalKeys:new Set(U)}}function $s($,Y,U,z,I,Q){let J=[],K=I.keySet,G=I.catchall._zod,H=G.def.type,W=G.optin==="optional",X=G.optout==="optional";for(let Z in Y){if(Z==="__proto__")continue;if(K.has(Z))continue;if(H==="never"){J.push(Z);continue}let q=G.run({value:Y[Z],issues:[]},z);if(q instanceof Promise)$.push(q.then((V)=>PV(V,U,Z,Y,W,X)));else PV(q,U,Z,Y,W,X)}if(J.length)U.issues.push({code:"unrecognized_keys",keys:J,input:Y,inst:Q});if(!$.length)return U;return Promise.all($).then(()=>{return U})}function fr($,Y,U,z){for(let Q of $)if(Q.issues.length===0)return Y.value=Q.value,Y;let I=$.filter((Q)=>!q7(Q));if(I.length===1)return Y.value=I[0].value,I[0];return Y.issues.push({code:"invalid_union",input:Y.value,inst:U,errors:$.map((Q)=>Q.issues.map((J)=>E8(J,z,s4())))}),Y}function ur($,Y,U,z){let I=$.filter((Q)=>Q.issues.length===0);if(I.length===1)return Y.value=I[0].value,Y;if(I.length===0)Y.issues.push({code:"invalid_union",input:Y.value,inst:U,errors:$.map((Q)=>Q.issues.map((J)=>E8(J,z,s4())))});else Y.issues.push({code:"invalid_union",input:Y.value,inst:U,errors:[],inclusive:!1});return Y}function gE($,Y){if($===Y)return{valid:!0,data:$};if($ instanceof Date&&Y instanceof Date&&+$===+Y)return{valid:!0,data:$};if(Z7($)&&Z7(Y)){let U=Object.keys(Y),z=Object.keys($).filter((Q)=>U.indexOf(Q)!==-1),I={...$,...Y};for(let Q of z){let J=gE($[Q],Y[Q]);if(!J.valid)return{valid:!1,mergeErrorPath:[Q,...J.mergeErrorPath]};I[Q]=J.data}return{valid:!0,data:I}}if(Array.isArray($)&&Array.isArray(Y)){if($.length!==Y.length)return{valid:!1,mergeErrorPath:[]};let U=[];for(let z=0;z<$.length;z++){let I=$[z],Q=Y[z],J=gE(I,Q);if(!J.valid)return{valid:!1,mergeErrorPath:[z,...J.mergeErrorPath]};U.push(J.data)}return{valid:!0,data:U}}return{valid:!1,mergeErrorPath:[]}}function br($,Y,U){let z=new Map,I;for(let K of Y.issues)if(K.code==="unrecognized_keys"){I??(I=K);for(let G of K.keys){if(!z.has(G))z.set(G,{});z.get(G).l=!0}}else $.issues.push(K);for(let K of U.issues)if(K.code==="unrecognized_keys")for(let G of K.keys){if(!z.has(G))z.set(G,{});z.get(G).r=!0}else $.issues.push(K);let Q=[...z].filter(([,K])=>K.l&&K.r).map(([K])=>K);if(Q.length&&I)$.issues.push({...I,keys:Q});if(q7($))return $;let J=gE(Y.value,U.value);if(!J.valid)throw Error(`Unmergable intersection. Error path: ${JSON.stringify(J.mergeErrorPath)}`);return $.value=J.data,$}function ir($,Y){for(let U=$.length-1;U>=0;U--)if($[U]._zod[Y]!=="optional")return U+1;return 0}function cr($,Y,U){if($.issues.length)Y.issues.push(...b8(U,$.issues));Y.value[U]=$.value}function nr($,Y,U,z,I){for(let Q=0;Q<U.length;Q++){let J=$[Q],K=Q<z.length;if(J.issues.length){if(!K&&Q>=I){Y.value.length=Q;break}Y.issues.push(...b8(Q,J.issues))}Y.value[Q]=J.value}for(let Q=Y.value.length-1;Q>=z.length;Q--)if(U[Q]._zod.optout==="optional"&&Y.value[Q]===void 0)Y.value.length=Q;else break;return Y}function pr($,Y,U,z,I,Q,J){if($.issues.length)if(YG.has(typeof z))U.issues.push(...b8(z,$.issues));else U.issues.push({code:"invalid_key",origin:"map",input:I,inst:Q,issues:$.issues.map((K)=>E8(K,J,s4()))});if(Y.issues.length)if(YG.has(typeof z))U.issues.push(...b8(z,Y.issues));else U.issues.push({origin:"map",code:"invalid_element",input:I,inst:Q,key:z,issues:Y.issues.map((K)=>E8(K,J,s4()))});U.value.set($.value,Y.value)}function dr($,Y){if($.issues.length)Y.issues.push(...$.issues);Y.value.add($.value)}function mr($,Y){if(Y===void 0&&($.issues.length||$.fallback))return{issues:[],value:void 0};return $}function lr($,Y){if($.value===void 0)$.value=Y.defaultValue;return $}function or($,Y){if(!$.issues.length&&$.value===void 0)$.issues.push({code:"invalid_type",expected:"nonoptional",input:$.value,inst:Y});return $}function DV($,Y,U){if($.issues.length)return $.aborted=!0,$;return Y._zod.run({value:$.value,issues:$.issues,fa Line truncated
import{createRequire as Zx0}from"node:module";var Ix0=Object.create;var{getPrototypeOf:Qx0,defineProperty:EE,getOwnPropertyNames:Jx0}=Object;var Kx0=Object.prototype.hasOwnProperty;function zx0($){return this[$]}var Gx0,Hx0,K6=($,Y,U)=>{var I=$!=null&&typeof $==="object";if(I){var Q=Y?Gx0??=new WeakMap:Hx0??=new WeakMap,J=Q.get($);if(J)return J}U=$!=null?Ix0(Qx0($)):{};let K=Y||!$||!$.__esModule?EE(U,"default",{value:$,enumerable:!0}):U;for(let z of Jx0($))if(!Kx0.call(K,z))EE(K,z,{get:zx0.bind($,z),enumerable:!0});if(I)Q.set($,K);return K};var j=($,Y)=>()=>(Y||$((Y={exports:{}}).exports,Y),Y.exports);var Wx0=($)=>$;function Xx0($,Y){this[$]=Wx0.bind(null,Y)}var Z8=($,Y)=>{for(var U in Y)EE($,U,{get:Y[U],enumerable:!0,configurable:!0,set:Xx0.bind(Y,U)})};var m=($,Y)=>()=>($&&(Y=$($=0)),Y);var K0=Zx0(import.meta.url);var qx0,zV,Vx0,Lx0,Fx0,wx0,j0=($,Y)=>()=>(Y||$((Y={exports:{}}).exports,Y),Y.exports),yr=($,Y)=>{let U={};for(var I in $)zV(U,I,{get:$[I],enumerable:!0});if(Y)zV(U,Symbol.toStringTag,{value:"Module"});return U},Mx0=($,Y,U,I)=>{if(Y&&typeof Y==="object"||typeof Y==="function"){for(var Q=Lx0(Y),J=0,K=Q.length,z;J<K;J++)if(z=Q[J],!wx0.call($,z)&&z!==U)zV($,z,{get:((G)=>Y[G]).bind(null,z),enumerable:!(I=Vx0(Y,z))||I.enumerable})}return $},GV=($,Y,U)=>(U=$!=null?qx0(Fx0($)):{},Mx0(Y||!$||!$.__esModule?zV(U,"default",{value:$,enumerable:!0}):U,$));var jE=m(()=>{qx0=Object.create,zV=Object.defineProperty,Vx0=Object.getOwnPropertyDescriptor,Lx0=Object.getOwnPropertyNames,Fx0=Object.getPrototypeOf,wx0=Object.prototype.hasOwnProperty});function xr($){return typeof $==="string"&&kr.has($.replace(/#$/,""))}function fr($,Y){if(!("$schema"in $)||typeof $.$schema!=="string")return"2020-12";let U=$.$schema.replace(/#$/,"");if(Ox0.has(U))return"2020-12";if(kr.has(U))return"2019-09";if(Nx0.has(U)||Dx0.has(U))return"draft-7";throw Error(`JSON Schema declares an unsupported dialect ("$schema": "${$.$schema.slice(0,200)}"). The default validator supports JSON Schema 2020-12, 2019-09, draft-07, and draft-06; ${Y}`)}var Ox0,kr,Nx0,Dx0;var CE=m(()=>{Ox0=new Set(["https://json-schema.org/draft/2020-12/schema","http://json-schema.org/draft/2020-12/schema"]),kr=new Set(["https://json-schema.org/draft/2019-09/schema","http://json-schema.org/draft/2019-09/schema"]),Nx0=new Set(["https://json-schema.org/draft-07/schema","http://json-schema.org/draft-07/schema"]),Dx0=new Set(["https://json-schema.org/draft-06/schema","http://json-schema.org/draft-06/schema"])});function H0($,Y,U){function I(z,G){if(!z._zod)Object.defineProperty(z,"_zod",{value:{def:G,constr:K,traits:new Set},enumerable:!1});if(z._zod.traits.has($))return;z._zod.traits.add($),Y(z,G);let H=K.prototype,W=Object.keys(H);for(let X=0;X<W.length;X++){let Z=W[X];if(!(Z in z))z[Z]=H[Z].bind(z)}}let Q=U?.Parent??Object;class J extends Q{}Object.defineProperty(J,"name",{value:$});function K(z){var G;let H=U?.Parent?new J:this;I(H,z),(G=H._zod).deferred??(G.deferred=[]);for(let W of H._zod.deferred)W();return H}return Object.defineProperty(K,"init",{value:I}),Object.defineProperty(K,Symbol.hasInstance,{value:(z)=>{if(U?.Parent&&z instanceof U.Parent)return!0;return z?._zod?.traits?.has($)}}),Object.defineProperty(K,"name",{value:$}),K}function a4($){if($)Object.assign(EY,$);return EY}var ur,$G,RE,l5,jY,EY;var CY=m(()=>{$G=Object.freeze({status:"aborted"});RE=Symbol("zod_brand");l5=class l5 extends Error{constructor(){super("Encountered Promise during synchronous parse. Use .parseAsync() instead.")}};jY=class jY extends Error{constructor($){super(`Encountered unidirectional transform during encode: ${$}`);this.name="ZodEncodeError"}};(ur=globalThis).__zod_globalConfig??(ur.__zod_globalConfig={});EY=globalThis.__zod_globalConfig});var k0={};Z8(k0,{unwrapMessage:()=>YG,uint8ArrayToHex:()=>mx0,uint8ArrayToBase64url:()=>dx0,uint8ArrayToBase64:()=>cr,stringifyPrimitive:()=>_0,slugify:()=>SE,shallowClone:()=>gE,safeExtend:()=>fx0,required:()=>ix0,randomString:()=>vx0,propertyKeyTypes:()=>QG,promiseAllObject:()=>_x0,primitiveTypes:()=>yE,prefixIssues:()=>n8,pick:()=>yx0,partial:()=>bx0,parsedType:()=>h0,optionalKeys:()=>kE,omit:()=>kx0,objectClone:()=>jx0,numKeys:()=>Sx0,nullish:()=>q7,normalizeParams:()=>f0,mergeDefs:()=>r9,merge:()=>ux0,jsonStringifyReplacer:()=>lI,joinValues:()=>M0,issue:()=>rI,isPlainObject:()=>L7,isObject:()=>RY,hexToUint8Array:()=>px0,getSizableOrigin:()=>JG,getParsedType:()=>hx0,getLengthableOrigin:()=>KG,getEnumValues:()=>UG,getElementAtPath:()=>Rx0,floatSafeRemainder:()=>vE,finalizeIssue:()=>R8,extend:()=>xx0,explicitlyAborted:()=>uE,escapeRegex:()=>R$,esc:()=>HV,defineLazy:()=>j1,createTransparentProxy:()=>gx0,cloneDef:()=>Cx0,clone:()=>C8,cleanRegex:()=>IG,cleanEnum:()=>cx0,captureStackTrace:()=>WV,cached:()=>oI,base64urlToUint8Array:()=>nx0,base64ToUint8Array:()=>ir,assignProp:()=>V7,assertNotEqual:()=>Ax0,assertNever:()=>Tx0,assertIs:()=>Px0,assertEqual:()=>Bx0,assert:()=>Ex0,allowsEval:()=>hE,aborted:()=>F7,NUMBER_FORMAT_RANGES:()=>xE,Class:()=>nrLine truncated
`)}var dr=($,Y)=>{$.name="$ZodError",Object.defineProperty($,"_zod",{value:$._zod,enumerable:!1}),Object.defineProperty($,"issues",{value:Y,enumerable:!1}),$.message=JSON.stringify(Y,lI,2),Object.defineProperty($,"toString",{value:()=>$.message,enumerable:!1})},zG,d8;var cE=m(()=>{CY();$1();zG=H0("$ZodError",dr),d8=H0("$ZodError",dr,{Parent:Error})});var sI=($)=>(Y,U,I,Q)=>{let J=I?{...I,async:!1}:{async:!1},K=Y._zod.run({value:U,issues:[]},J);if(K instanceof Promise)throw new l5;if(K.issues.length){let z=new(Q?.Err??$)(K.issues.map((G)=>R8(G,J,a4())));throw WV(z,Q?.callee),z}return K.value},XV,aI=($)=>async(Y,U,I,Q)=>{let J=I?{...I,async:!0}:{async:!0},K=Y._zod.run({value:U,issues:[]},J);if(K instanceof Promise)K=await K;if(K.issues.length){let z=new(Q?.Err??$)(K.issues.map((G)=>R8(G,J,a4())));throw WV(z,Q?.callee),z}return K.value},ZV,tI=($)=>(Y,U,I)=>{let Q=I?{...I,async:!1}:{async:!1},J=Y._zod.run({value:U,issues:[]},Q);if(J instanceof Promise)throw new l5;return J.issues.length?{success:!1,error:new($??zG)(J.issues.map((K)=>R8(K,Q,a4())))}:{success:!0,data:J.value}},nE,eI=($)=>async(Y,U,I)=>{let Q=I?{...I,async:!0}:{async:!0},J=Y._zod.run({value:U,issues:[]},Q);if(J instanceof Promise)J=await J;return J.issues.length?{success:!1,error:new $(J.issues.map((K)=>R8(K,Q,a4())))}:{success:!0,data:J.value}},dE,qV=($)=>(Y,U,I)=>{let Q=I?{...I,direction:"backward"}:{direction:"backward"};return sI($)(Y,U,Q)},ox0,VV=($)=>(Y,U,I)=>{return sI($)(Y,U,I)},rx0,LV=($)=>async(Y,U,I)=>{let Q=I?{...I,direction:"backward"}:{direction:"backward"};return aI($)(Y,U,Q)},sx0,FV=($)=>async(Y,U,I)=>{return aI($)(Y,U,I)},ax0,wV=($)=>(Y,U,I)=>{let Q=I?{...I,direction:"backward"}:{direction:"backward"};return tI($)(Y,U,Q)},tx0,MV=($)=>(Y,U,I)=>{return tI($)(Y,U,I)},ex0,OV=($)=>async(Y,U,I)=>{let Q=I?{...I,direction:"backward"}:{direction:"backward"};return eI($)(Y,U,Q)},$f0,NV=($)=>async(Y,U,I)=>{return eI($)(Y,U,I)},Yf0;var pE=m(()=>{CY();cE();$1();XV=sI(d8),ZV=aI(d8),nE=tI(d8),dE=eI(d8),ox0=qV(d8),rx0=VV(d8),sx0=LV(d8),ax0=FV(d8),tx0=wV(d8),ex0=MV(d8),$f0=OV(d8),Yf0=NV(d8)});var G$={};Z8(G$,{xid:()=>rE,uuid7:()=>Jf0,uuid6:()=>Qf0,uuid4:()=>If0,uuid:()=>_Y,uppercase:()=>Nj,unicodeEmail:()=>mr,undefined:()=>Mj,ulid:()=>oE,time:()=>Xj,string:()=>qj,sha512_hex:()=>Ef0,sha512_base64url:()=>Cf0,sha512_base64:()=>jf0,sha384_hex:()=>Af0,sha384_base64url:()=>Tf0,sha384_base64:()=>Pf0,sha256_hex:()=>Nf0,sha256_base64url:()=>Bf0,sha256_base64:()=>Df0,sha1_hex:()=>wf0,sha1_base64url:()=>Of0,sha1_base64:()=>Mf0,rfc5322Email:()=>zf0,number:()=>WG,null:()=>wj,nanoid:()=>aE,md5_hex:()=>Vf0,md5_base64url:()=>Ff0,md5_base64:()=>Lf0,mac:()=>Qj,lowercase:()=>Oj,ksuid:()=>sE,ipv6:()=>Ij,ipv4:()=>Uj,integer:()=>Lj,idnEmail:()=>Gf0,httpProtocol:()=>Gj,html5Email:()=>Kf0,hostname:()=>Xf0,hex:()=>qf0,guid:()=>eE,extendedDuration:()=>Uf0,emoji:()=>Yj,email:()=>$j,e164:()=>Hj,duration:()=>tE,domain:()=>Zf0,datetime:()=>Zj,date:()=>Wj,cuid2:()=>lE,cuid:()=>mE,cidrv6:()=>Kj,cidrv4:()=>Jj,browserEmail:()=>Hf0,boolean:()=>Fj,bigint:()=>Vj,base64url:()=>DV,base64:()=>zj});function Yj(){return new RegExp(Wf0,"u")}function or($){return typeof $.precision==="number"?$.precision===-1?"(?:[01]\\d|2[0-3]):[0-5]\\d":$.precision===0?"(?:[01]\\d|2[0-3]):[0-5]\\d:[0-5]\\d":`(?:[01]\\d|2[0-3]):[0-5]\\d:[0-5]\\d\\.\\d{${$.precision}}`:"(?:[01]\\d|2[0-3]):[0-5]\\d(?::[0-5]\\d(?:\\.\\d+)?)?"}function Xj($){return new RegExp(`^${or($)}$`)}function Zj($){let Y=or({precision:$.precision}),U=["Z"];if($.local)U.push("");if($.offset)U.push("([+-](?:[01]\\d|2[0-3]):[0-5]\\d)");let I=`${Y}(?:${U.join("|")})`;return new RegExp(`^${lr}T(?:${I})$`)}function XG($,Y){return new RegExp(`^[A-Za-z0-9+/]{${$}}${Y}$`)}function ZG($){return new RegExp(`^[A-Za-z0-9_-]{${$}}$`)}var mE,lE,oE,rE,sE,aE,tE,Uf0,eE,_Y=($)=>{if(!$)return/^([0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[1-8][0-9a-fA-F]{3}-[89abAB][0-9a-fA-F]{3}-[0-9a-fA-F]{12}|00000000-0000-0000-0000-000000000000|ffffffff-ffff-ffff-ffff-ffffffffffff)$/;return new RegExp(`^([0-9a-fA-F]{8}-[0-9a-fA-F]{4}-${$}[0-9a-fA-F]{3}-[89abAB][0-9a-fA-F]{3}-[0-9a-fA-F]{12})$`)},If0,Qf0,Jf0,$j,Kf0,zf0,mr,Gf0,Hf0,Wf0="^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$",Uj,Ij,Qj=($)=>{let Y=R$($??":");return new RegExp(`^(?:[0-9A-F]{2}${Y}){5}[0-9A-F]{2}$|^(?:[0-9a-f]{2}${Y}){5}[0-9a-f]{2}$`)},Jj,Kj,zj,DV,Xf0,Zf0,Gj,Hj,lr="(?:(?:\\d\\d[2468][048]|\\d\\d[13579][26]|\\d\\d0[48]|[02468][048]00|[13579][26]00)-02-29|\\d{4}-(?:(?:0[13578]|1[02])-(?:0[1-9]|[12]\\d|3[01])|(?:0[469]|11)-(?:0[1-9]|[12]\\d|30)|(?:02)-(?:0[1-9]|1\\d|2[0-8])))",Wj,qj=($)=>{let Y=$?`[\\s\\S]{${$?.minimum??0},${$?.maximum??""}}`:"[\\s\\S]*";return new RegExp(`^${Y}$`)},Vj,Lj,WG,Fj,wj,Mj,Oj,Nj,qf0,Vf0,Lf0,Ff0,wf0,Mf0,Of0,Nf0,Df0,Bf0,Af0,Pf0,Tf0,Ef0,jf0,Cf0;var BV=m(()=>{$1();mE=/^[cC][0-9a-z]{6,}$/,lE=/^[0-9a-z]+$/,oE=/^[0-9A-HJKMNP-TV-Za-hjkmnp-tv-z]{26}$/,rE=/^[0-9a-vA-V]{20}$/,sE=/^[A-Za-z0-9]{27}$/,aE=/^[a-zA-Z0-9_-]{21}$/,tE=/^P(?:(\d+W)|(?!.*W)(?=\d|T\d)(\d+Y)?(\d+M)?(\d+D)?(T(?=\d)(\d+H)?(\dLine truncated
`).filter((J)=>J),I=Math.min(...U.map((J)=>J.length-J.trimStart().length)),Q=U.map((J)=>J.slice(I)).map((J)=>" ".repeat(this.indent*2)+J);for(let J of Q)this.content.push(J)}compile(){let $=Function,Y=this?.args,I=[...(this?.content??[""]).map((Q)=>` ${Q}`)];return new $(...Y,I.join(`
`))}}var uj;var bj=m(()=>{uj={major:4,minor:4,patch:3}});function GC($){if($==="")return!0;if(/\s/.test($))return!1;if($.length%4!==0)return!1;try{return atob($),!0}catch{return!1}}function Zs($){if(!DV.test($))return!1;let Y=$.replace(/[-_]/g,(I)=>I==="-"?"+":"/"),U=Y.padEnd(Math.ceil(Y.length/4)*4,"=");return GC(U)}function qs($,Y=null){try{let U=$.split(".");if(U.length!==3)return!1;let[I]=U;if(!I)return!1;let Q=JSON.parse(atob(I));if("typ"in Q&&Q?.typ!=="JWT")return!1;if(!Q.alg)return!1;if(Y&&(!("alg"in Q)||Q.alg!==Y))return!1;return!0}catch{return!1}}function tr($,Y,U){if($.issues.length)Y.issues.push(...n8(U,$.issues));Y.value[U]=$.value}function _V($,Y,U,I,Q,J){let K=U in I;if($.issues.length){if(Q&&J&&!K)return;Y.issues.push(...n8(U,$.issues))}if(!K&&!Q){if(!$.issues.length)Y.issues.push({code:"invalid_type",expected:"nonoptional",input:void 0,path:[U]});return}if($.value===void 0){if(K)Y.value[U]=void 0}else Y.value[U]=$.value}function Vs($){let Y=Object.keys($.shape);for(let I of Y)if(!$.shape?.[I]?._zod?.traits?.has("$ZodType"))throw Error(`Invalid element at key "${I}": expected a Zod schema`);let U=kE($.shape);return{...$,keys:Y,keySet:new Set(Y),numKeys:Y.length,optionalKeys:new Set(U)}}function Ls($,Y,U,I,Q,J){let K=[],z=Q.keySet,G=Q.catchall._zod,H=G.def.type,W=G.optin==="optional",X=G.optout==="optional";for(let Z in Y){if(Z==="__proto__")continue;if(z.has(Z))continue;if(H==="never"){K.push(Z);continue}let q=G.run({value:Y[Z],issues:[]},I);if(q instanceof Promise)$.push(q.then((V)=>_V(V,U,Z,Y,W,X)));else _V(q,U,Z,Y,W,X)}if(K.length)U.issues.push({code:"unrecognized_keys",keys:K,input:Y,inst:J});if(!$.length)return U;return Promise.all($).then(()=>{return U})}function er($,Y,U,I){for(let J of $)if(J.issues.length===0)return Y.value=J.value,Y;let Q=$.filter((J)=>!F7(J));if(Q.length===1)return Y.value=Q[0].value,Q[0];return Y.issues.push({code:"invalid_union",input:Y.value,inst:U,errors:$.map((J)=>J.issues.map((K)=>R8(K,I,a4())))}),Y}function $s($,Y,U,I){let Q=$.filter((J)=>J.issues.length===0);if(Q.length===1)return Y.value=Q[0].value,Y;if(Q.length===0)Y.issues.push({code:"invalid_union",input:Y.value,inst:U,errors:$.map((J)=>J.issues.map((K)=>R8(K,I,a4())))});else Y.issues.push({code:"invalid_union",input:Y.value,inst:U,errors:[],inclusive:!1});return Y}function ij($,Y){if($===Y)return{valid:!0,data:$};if($ instanceof Date&&Y instanceof Date&&+$===+Y)return{valid:!0,data:$};if(L7($)&&L7(Y)){let U=Object.keys(Y),I=Object.keys($).filter((J)=>U.indexOf(J)!==-1),Q={...$,...Y};for(let J of I){let K=ij($[J],Y[J]);if(!K.valid)return{valid:!1,mergeErrorPath:[J,...K.mergeErrorPath]};Q[J]=K.data}return{valid:!0,data:Q}}if(Array.isArray($)&&Array.isArray(Y)){if($.length!==Y.length)return{valid:!1,mergeErrorPath:[]};let U=[];for(let I=0;I<$.length;I++){let Q=$[I],J=Y[I],K=ij(Q,J);if(!K.valid)return{valid:!1,mergeErrorPath:[I,...K.mergeErrorPath]};U.push(K.data)}return{valid:!0,data:U}}return{valid:!1,mergeErrorPath:[]}}function Ys($,Y,U){let I=new Map,Q;for(let z of Y.issues)if(z.code==="unrecognized_keys"){Q??(Q=z);for(let G of z.keys){if(!I.has(G))I.set(G,{});I.get(G).l=!0}}else $.issues.push(z);for(let z of U.issues)if(z.code==="unrecognized_keys")for(let G of z.keys){if(!I.has(G))I.set(G,{});I.get(G).r=!0}else $.issues.push(z);let J=[...I].filter(([,z])=>z.l&&z.r).map(([z])=>z);if(J.length&&Q)$.issues.push({...Q,keys:J});if(F7($))return $;let K=ij(Y.value,U.value);if(!K.valid)throw Error(`Unmergable intersection. Error path: ${JSON.stringify(K.mergeErrorPath)}`);return $.value=K.data,$}function Us($,Y){for(let U=$.length-1;U>=0;U--)if($[U]._zod[Y]!=="optional")return U+1;return 0}function Is($,Y,U){if($.issues.length)Y.issues.push(...n8(U,$.issues));Y.value[U]=$.value}function Qs($,Y,U,I,Q){for(let J=0;J<U.length;J++){let K=$[J],z=J<I.length;if(K.issues.length){if(!z&&J>=Q){Y.value.length=J;break}Y.issues.push(...n8(J,K.issues))}Y.value[J]=K.value}for(let J=Y.value.length-1;J>=I.length;J--)if(U[J]._zod.optout==="optional"&&Y.value[J]===void 0)Y.value.length=J;else break;return Y}function Js($,Y,U,I,Q,J,K){if($.issues.length)if(QG.has(typeof I))U.issues.push(...n8(I,$.issues));else U.issues.push({code:"invalid_key",origin:"map",input:Q,inst:J,issues:$.issues.map((z)=>R8(z,K,a4()))});if(Y.issues.length)if(QG.has(typeof I))U.issues.push(...n8(I,Y.issues));else U.issues.push({origin:"map",code:"invalid_element",input:Q,inst:J,key:I,issues:Y.issues.map((z)=>R8(z,K,a4()))});U.value.set($.value,Y.value)}function Ks($,Y){if($.issues.length)Y.issues.push(...$.issues);Y.value.add($.value)}function zs($,Y){if(Y===void 0&&($.issues.length||$.fallback))return{issues:[],value:void 0};return $}function Gs($,Y){if($.value===void 0)$.value=Y.defaultValue;return $}function Hs($,Y){if(!$.issues.length&&$.value===void 0)$.issues.push({code:"invalid_type",expected:"nonoptional",input:$.value,inst:Y});return $}function jV($,Y,U){if($.issues.length)return $.aborted=!0,$;return Y._zod.run({value:$.value,issues:$.issues,fa Line truncated
if (${D}.issues.length) {
if (${P} in input) {
payload.issues = payload.issues.concat(${D}.issues.map(iss => ({
@@ -19,7 +19,7 @@ import{createRequire as Ak0}from"node:module";var qk0=Object.create;var{getProto
newResult[${P}] = ${D}.value;
}
`);else if(!A)q.write(`
`);else if(!B)q.write(`
const ${D}_present = ${P} in input;
if (${D}.issues.length) {
payload.issues = payload.issues.concat(${D}.issues.map(iss => ({
@@ -60,94 +60,94 @@ import{createRequire as Ak0}from"node:module";var qk0=Object.create;var{getProto
newResult[${P}] = ${D}.value;
}
`)}q.write("payload.value = newResult;"),q.write("return payload;");let N=q.compile();return(O,D)=>N(Z,O,D)},Q,J=CY,K=!TY.jitless,H=K&&jj.value,W=Y.catchall,X;$._zod.parse=(Z,q)=>{X??(X=z.value);let V=Z.value;if(!J(V))return Z.issues.push({expected:"object",code:"invalid_type",input:V,inst:$}),Z;if(K&&H&&q?.async===!1&&q.jitless!==!0){if(!Q)Q=I(Y.shape);if(Z=Q(Z,q),!W)return Z;return $s([],V,Z,q,X,$)}return U(Z,q)}});XG=H0("$ZodUnion",($,Y)=>{V1.init($,Y),E1($._zod,"optin",()=>Y.options.some((z)=>z._zod.optin==="optional")?"optional":void 0),E1($._zod,"optout",()=>Y.options.some((z)=>z._zod.optout==="optional")?"optional":void 0),E1($._zod,"values",()=>{if(Y.options.every((z)=>z._zod.values))return new Set(Y.options.flatMap((z)=>Array.from(z._zod.values)));return}),E1($._zod,"pattern",()=>{if(Y.options.every((z)=>z._zod.pattern)){let z=Y.options.map((I)=>I._zod.pattern);return new RegExp(`^(${z.map((I)=>$G(I.source)).join("|")})$`)}return});let U=Y.options.length===1?Y.options[0]._zod.run:null;$._zod.parse=(z,I)=>{if(U)return U(z,I);let Q=!1,J=[];for(let K of Y.options){let G=K._zod.run({value:z.value,issues:[]},I);if(G instanceof Promise)J.push(G),Q=!0;else{if(G.issues.length===0)return G;J.push(G)}}if(!Q)return fr(J,z,$,I);return Promise.all(J).then((K)=>{return fr(K,z,$,I)})}});OC=H0("$ZodXor",($,Y)=>{XG.init($,Y),Y.inclusive=!1;let U=Y.options.length===1?Y.options[0]._zod.run:null;$._zod.parse=(z,I)=>{if(U)return U(z,I);let Q=!1,J=[];for(let K of Y.options){let G=K._zod.run({value:z.value,issues:[]},I);if(G instanceof Promise)J.push(G),Q=!0;else J.push(G)}if(!Q)return ur(J,z,$,I);return Promise.all(J).then((K)=>{return ur(K,z,$,I)})}}),NC=H0("$ZodDiscriminatedUnion",($,Y)=>{Y.inclusive=!1,XG.init($,Y);let U=$._zod.parse;E1($._zod,"propValues",()=>{let I={};for(let Q of Y.options){let J=Q._zod.propValues;if(!J||Object.keys(J).length===0)throw Error(`Invalid discriminated union option at index "${Y.options.indexOf(Q)}"`);for(let[K,G]of Object.entries(J)){if(!I[K])I[K]=new Set;for(let H of G)I[K].add(H)}}return I});let z=lz(()=>{let I=Y.options,Q=new Map;for(let J of I){let K=J._zod.propValues?.[Y.discriminator];if(!K||K.size===0)throw Error(`Invalid discriminated union option at index "${Y.options.indexOf(J)}"`);for(let G of K){if(Q.has(G))throw Error(`Duplicate discriminator value "${String(G)}"`);Q.set(G,J)}}return Q});$._zod.parse=(I,Q)=>{let J=I.value;if(!CY(J))return I.issues.push({code:"invalid_type",expected:"object",input:J,inst:$}),I;let K=z.value.get(J?.[Y.discriminator]);if(K)return K._zod.run(I,Q);if(Y.unionFallback||Q.direction==="backward")return U(I,Q);return I.issues.push({code:"invalid_union",errors:[],note:"No matching discriminator",discriminator:Y.discriminator,options:Array.from(z.value.keys()),input:J,path:[Y.discriminator],inst:$}),I}}),DC=H0("$ZodIntersection",($,Y)=>{V1.init($,Y),$._zod.parse=(U,z)=>{let I=U.value,Q=Y.left._zod.run({value:I,issues:[]},z),J=Y.right._zod.run({value:I,issues:[]},z);if(Q instanceof Promise||J instanceof Promise)return Promise.all([Q,J]).then(([G,H])=>{return br(U,G,H)});return br(U,Q,J)}});EV=H0("$ZodTuple",($,Y)=>{V1.init($,Y);let U=Y.items;$._zod.parse=(z,I)=>{let Q=z.value;if(!Array.isArray(Q))return z.issues.push({input:Q,inst:$,expected:"tuple",code:"invalid_type"}),z;z.value=[];let J=[],K=ir(U,"optin"),G=ir(U,"optout");if(!Y.rest){if(Q.length<K)return z.issues.push({code:"too_small",minimum:K,inclusive:!0,input:Q,inst:$,origin:"array"}),z;if(Q.length>U.length)z.issues.push({code:"too_big",maximum:U.length,inclusive:!0,input:Q,inst:$,origin:"array"})}let H=Array(U.length);for(let W=0;W<U.length;W++){let X=U[W]._zod.run({value:Q[W],issues:[]},I);if(X instanceof Promise)J.push(X.then((Z)=>{H[W]=Z}));else H[W]=X}if(Y.rest){let W=U.length-1,X=Q.slice(U.length);for(let Z of X){W++;let q=Y.rest._zod.run({value:Z,issues:[]},I);if(q instanceof Promise)J.push(q.then((V)=>cr(V,z,W)));else cr(q,z,W)}}if(J.length)return Promise.all(J).then(()=>nr(H,z,U,Q,G));return nr(H,z,U,Q,G)}});AC=H0("$ZodRecord",($,Y)=>{V1.init($,Y),$._zod.parse=(U,z)=>{let I=U.value;if(!Z7(I))return U.issues.push({expected:"record",code:"invalid_type",input:I,inst:$}),U;let Q=[],J=Y.keyType._zod.values;if(J){U.value={};let K=new Set;for(let H of J)if(typeof H==="string"||typeof H==="number"||typeof H==="symbol"){K.add(typeof H==="number"?H.toString():H);let W=Y.keyType._zod.run({value:H,issues:[]},z);if(W instanceof Promise)throw Error("Async schemas not supported in object keys currently");if(W.issues.length){U.issues.push({code:"invalid_key",origin:"record",issues:W.issues.map((q)=>E8(q,z,s4())),input:H,path:[H],inst:$});continue}let X=W.value,Z=Y.valueType._zod.run({value:I[H],issues:[]},z);if(Z instanceof Promise)Q.push(Z.then((q)=>{if(q.issues.length)U.issues.push(...b8(H,q.issues));U.value[X]=q.value}));else{if(Z.issues.length)U.issues.push(...b8(H,Z.issues));U.value[X]=Z.value}}let G;for(let H in I)if(!K.has(H))G=G??[],G.push(H);if(G&&G.length>0)U.issues.push({code:"unrec Line truncated
`)}q.write("payload.value = newResult;"),q.write("return payload;");let N=q.compile();return(O,D)=>N(Z,O,D)},J,K=RY,z=!EY.jitless,H=z&&hE.value,W=Y.catchall,X;$._zod.parse=(Z,q)=>{X??(X=I.value);let V=Z.value;if(!K(V))return Z.issues.push({expected:"object",code:"invalid_type",input:V,inst:$}),Z;if(z&&H&&q?.async===!1&&q.jitless!==!0){if(!J)J=Q(Y.shape);if(Z=J(Z,q),!W)return Z;return Ls([],V,Z,q,X,$)}return U(Z,q)}});VG=H0("$ZodUnion",($,Y)=>{V1.init($,Y),j1($._zod,"optin",()=>Y.options.some((I)=>I._zod.optin==="optional")?"optional":void 0),j1($._zod,"optout",()=>Y.options.some((I)=>I._zod.optout==="optional")?"optional":void 0),j1($._zod,"values",()=>{if(Y.options.every((I)=>I._zod.values))return new Set(Y.options.flatMap((I)=>Array.from(I._zod.values)));return}),j1($._zod,"pattern",()=>{if(Y.options.every((I)=>I._zod.pattern)){let I=Y.options.map((Q)=>Q._zod.pattern);return new RegExp(`^(${I.map((Q)=>IG(Q.source)).join("|")})$`)}return});let U=Y.options.length===1?Y.options[0]._zod.run:null;$._zod.parse=(I,Q)=>{if(U)return U(I,Q);let J=!1,K=[];for(let z of Y.options){let G=z._zod.run({value:I.value,issues:[]},Q);if(G instanceof Promise)K.push(G),J=!0;else{if(G.issues.length===0)return G;K.push(G)}}if(!J)return er(K,I,$,Q);return Promise.all(K).then((z)=>{return er(z,I,$,Q)})}});EC=H0("$ZodXor",($,Y)=>{VG.init($,Y),Y.inclusive=!1;let U=Y.options.length===1?Y.options[0]._zod.run:null;$._zod.parse=(I,Q)=>{if(U)return U(I,Q);let J=!1,K=[];for(let z of Y.options){let G=z._zod.run({value:I.value,issues:[]},Q);if(G instanceof Promise)K.push(G),J=!0;else K.push(G)}if(!J)return $s(K,I,$,Q);return Promise.all(K).then((z)=>{return $s(z,I,$,Q)})}}),jC=H0("$ZodDiscriminatedUnion",($,Y)=>{Y.inclusive=!1,VG.init($,Y);let U=$._zod.parse;j1($._zod,"propValues",()=>{let Q={};for(let J of Y.options){let K=J._zod.propValues;if(!K||Object.keys(K).length===0)throw Error(`Invalid discriminated union option at index "${Y.options.indexOf(J)}"`);for(let[z,G]of Object.entries(K)){if(!Q[z])Q[z]=new Set;for(let H of G)Q[z].add(H)}}return Q});let I=oI(()=>{let Q=Y.options,J=new Map;for(let K of Q){let z=K._zod.propValues?.[Y.discriminator];if(!z||z.size===0)throw Error(`Invalid discriminated union option at index "${Y.options.indexOf(K)}"`);for(let G of z){if(J.has(G))throw Error(`Duplicate discriminator value "${String(G)}"`);J.set(G,K)}}return J});$._zod.parse=(Q,J)=>{let K=Q.value;if(!RY(K))return Q.issues.push({code:"invalid_type",expected:"object",input:K,inst:$}),Q;let z=I.value.get(K?.[Y.discriminator]);if(z)return z._zod.run(Q,J);if(Y.unionFallback||J.direction==="backward")return U(Q,J);return Q.issues.push({code:"invalid_union",errors:[],note:"No matching discriminator",discriminator:Y.discriminator,options:Array.from(I.value.keys()),input:K,path:[Y.discriminator],inst:$}),Q}}),CC=H0("$ZodIntersection",($,Y)=>{V1.init($,Y),$._zod.parse=(U,I)=>{let Q=U.value,J=Y.left._zod.run({value:Q,issues:[]},I),K=Y.right._zod.run({value:Q,issues:[]},I);if(J instanceof Promise||K instanceof Promise)return Promise.all([J,K]).then(([G,H])=>{return Ys(U,G,H)});return Ys(U,J,K)}});hV=H0("$ZodTuple",($,Y)=>{V1.init($,Y);let U=Y.items;$._zod.parse=(I,Q)=>{let J=I.value;if(!Array.isArray(J))return I.issues.push({input:J,inst:$,expected:"tuple",code:"invalid_type"}),I;I.value=[];let K=[],z=Us(U,"optin"),G=Us(U,"optout");if(!Y.rest){if(J.length<z)return I.issues.push({code:"too_small",minimum:z,inclusive:!0,input:J,inst:$,origin:"array"}),I;if(J.length>U.length)I.issues.push({code:"too_big",maximum:U.length,inclusive:!0,input:J,inst:$,origin:"array"})}let H=Array(U.length);for(let W=0;W<U.length;W++){let X=U[W]._zod.run({value:J[W],issues:[]},Q);if(X instanceof Promise)K.push(X.then((Z)=>{H[W]=Z}));else H[W]=X}if(Y.rest){let W=U.length-1,X=J.slice(U.length);for(let Z of X){W++;let q=Y.rest._zod.run({value:Z,issues:[]},Q);if(q instanceof Promise)K.push(q.then((V)=>Is(V,I,W)));else Is(q,I,W)}}if(K.length)return Promise.all(K).then(()=>Qs(H,I,U,J,G));return Qs(H,I,U,J,G)}});RC=H0("$ZodRecord",($,Y)=>{V1.init($,Y),$._zod.parse=(U,I)=>{let Q=U.value;if(!L7(Q))return U.issues.push({expected:"record",code:"invalid_type",input:Q,inst:$}),U;let J=[],K=Y.keyType._zod.values;if(K){U.value={};let z=new Set;for(let H of K)if(typeof H==="string"||typeof H==="number"||typeof H==="symbol"){z.add(typeof H==="number"?H.toString():H);let W=Y.keyType._zod.run({value:H,issues:[]},I);if(W instanceof Promise)throw Error("Async schemas not supported in object keys currently");if(W.issues.length){U.issues.push({code:"invalid_key",origin:"record",issues:W.issues.map((q)=>R8(q,I,a4())),input:H,path:[H],inst:$});continue}let X=W.value,Z=Y.valueType._zod.run({value:Q[H],issues:[]},I);if(Z instanceof Promise)J.push(Z.then((q)=>{if(q.issues.length)U.issues.push(...n8(H,q.issues));U.value[X]=q.value}));else{if(Z.issues.length)U.issues.push(...n8(H,Z.issues));U.value[X]=Z.value}}let G;for(let H in Q)if(!z.has(H))G=G??[],G.push(H);if(G&&G.length>0)U.issues.push({code:"unrec Line truncated
Set the \`cycles\` parameter to \`"ref"\` to resolve cyclical schemas with defs.`)}for(let J of $.seen.entries()){let K=J[1];if(Y===J[0]){Q(J);continue}if($.external){let H=$.external.registry.get(J[0])?.id;if(Y!==J[0]&&H){Q(J);continue}}if($.metadataRegistry.get(J[0])?.id){Q(J);continue}if(K.cycle){Q(J);continue}if(K.count>1){if($.reused==="ref"){Q(J);continue}}}}function M7($,Y){let U=$.seen.get(Y);if(!U)throw Error("Unprocessed schema. This is a bug in Zod.");let z=(K)=>{let G=$.seen.get(K);if(G.ref===null)return;let H=G.def??G.schema,W={...H},X=G.ref;if(G.ref=null,X){z(X);let q=$.seen.get(X),V=q.schema;if(V.$ref&&($.target==="draft-07"||$.target==="draft-04"||$.target==="openapi-3.0"))H.allOf=H.allOf??[],H.allOf.push(V);else Object.assign(H,V);if(Object.assign(H,W),K._zod.parent===X)for(let M in H){if(M==="$ref"||M==="allOf")continue;if(!(M in W))delete H[M]}if(V.$ref&&q.def)for(let M in H){if(M==="$ref"||M==="allOf")continue;if(M in q.def&&JSON.stringify(H[M])===JSON.stringify(q.def[M]))delete H[M]}}let Z=K._zod.parent;if(Z&&Z!==X){z(Z);let q=$.seen.get(Z);if(q?.schema.$ref){if(H.$ref=q.schema.$ref,q.def)for(let V in H){if(V==="$ref"||V==="allOf")continue;if(V in q.def&&JSON.stringify(H[V])===JSON.stringify(q.def[V]))delete H[V]}}}$.override({zodSchema:K,jsonSchema:H,path:G.path??[]})};for(let K of[...$.seen.entries()].reverse())z(K[0]);let I={};if($.target==="draft-2020-12")I.$schema="https://json-schema.org/draft/2020-12/schema";else if($.target==="draft-07")I.$schema="http://json-schema.org/draft-07/schema#";else if($.target==="draft-04")I.$schema="http://json-schema.org/draft-04/schema#";else if($.target==="openapi-3.0");if($.external?.uri){let K=$.external.registry.get(Y)?.id;if(!K)throw Error("Schema is missing an `id` property");I.$id=$.external.uri(K)}Object.assign(I,U.def??U.schema);let Q=$.metadataRegistry.get(Y)?.id;if(Q!==void 0&&I.id===Q)delete I.id;let J=$.external?.defs??{};for(let K of $.seen.entries()){let G=K[1];if(G.def&&G.defId){if(G.def.id===G.defId)delete G.def.id;J[G.defId]=G.def}}if($.external);else if(Object.keys(J).length>0)if($.target==="draft-2020-12")I.$defs=J;else I.definitions=J;try{let K=JSON.parse(JSON.stringify(I));return Object.defineProperty(K,"~standard",{value:{...Y["~standard"],jsonSchema:{input:VI(Y,"input",$.processors),output:VI(Y,"output",$.processors)}},enumerable:!1,writable:!1}),K}catch(K){throw Error("Error converting schema to JSON.")}}function R8($,Y){let U=Y??{seen:new Set};if(U.seen.has($))return!1;U.seen.add($);let z=$._zod.def;if(z.type==="transform")return!0;if(z.type==="array")return R8(z.element,U);if(z.type==="set")return R8(z.valueType,U);if(z.type==="lazy")return R8(z.getter(),U);if(z.type==="promise"||z.type==="optional"||z.type==="nonoptional"||z.type==="nullable"||z.type==="readonly"||z.type==="default"||z.type==="prefault")return R8(z.innerType,U);if(z.type==="intersection")return R8(z.left,U)||R8(z.right,U);if(z.type==="record"||z.type==="map")return R8(z.keyType,U)||R8(z.valueType,U);if(z.type==="pipe"){if($._zod.traits.has("$ZodCodec"))return!0;return R8(z.in,U)||R8(z.out,U)}if(z.type==="object"){for(let I in z.shape)if(R8(z.shape[I],U))return!0;return!1}if(z.type==="union"){for(let I of z.options)if(R8(I,U))return!0;return!1}if(z.type==="tuple"){for(let I of z.items)if(R8(I,U))return!0;if(z.rest&&R8(z.rest,U))return!0;return!1}return!1}var h_=($,Y={})=>(U)=>{let z=F7({...U,processors:Y});return K4($,z),w7(z,$),M7(z,$)},VI=($,Y,U={})=>(z)=>{let{libraryOptions:I,target:Q}=z??{},J=F7({...I??{},target:Q,io:Y,processors:U});return K4($,J),w7(J,$),M7(J,$)};var DG=m(()=>{MG()});function gY($,Y){if("_idmap"in $){let z=$,I=F7({...Y,processors:UL}),Q={};for(let G of z._idmap.entries()){let[H,W]=G;K4(W,I)}let J={},K={registry:z,uri:Y?.uri,defs:Q};I.external=K;for(let G of z._idmap.entries()){let[H,W]=G;w7(I,W),J[H]=M7(I,W)}if(Object.keys(Q).length>0){let G=I.target==="draft-2020-12"?"$defs":"definitions";J.__shared={[G]:Q}}return{schemas:J}}let U=F7({...Y,processors:UL});return K4($,U),w7(U,$),M7(U,$)}var Ju0,S_=($,Y,U,z)=>{let I=U;I.type="string";let{minimum:Q,maximum:J,format:K,patterns:G,contentEncoding:H}=$._zod.bag;if(typeof Q==="number")I.minLength=Q;if(typeof J==="number")I.maxLength=J;if(K){if(I.format=Ju0[K]??K,I.format==="")delete I.format;if(K==="time")delete I.format}if(H)I.contentEncoding=H;if(G&&G.size>0){let W=[...G];if(W.length===1)I.pattern=W[0].source;else if(W.length>1)I.allOf=[...W.map((X)=>({...Y.target==="draft-07"||Y.target==="draft-04"||Y.target==="openapi-3.0"?{type:"string"}:{},pattern:X.source}))]}},g_=($,Y,U,z)=>{let I=U,{minimum:Q,maximum:J,format:K,multipleOf:G,exclusiveMaximum:H,exclusiveMinimum:W}=$._zod.bag;if(typeof K==="string"&&K.includes("int"))I.type="integer";else I.type="number";let X=typeof W==="number"&&W>=(Q??Number.NEGATIVE_INFINITY),Z=typeof H==="number"&&H<=(J??Number.POSITIVE_INFINITY),q=Y.target==="draft-04"||Y.target==="openapi-3.0";if(X)if(q)I.minimum=W,I.exclusiveMinimum=!0;else I.exclusiveMinimuLine truncated
`}function bb0($){let Y=[];if($.length===0)return{isValid:!1,warnings:["Tool name cannot be empty"]};if($.length>128)return{isValid:!1,warnings:[`Tool name exceeds maximum length of 128 characters (current: ${$.length})`]};if($.includes(" "))Y.push("Tool name contains spaces, which may cause parsing issues");if($.includes(","))Y.push("Tool name contains commas, which may cause parsing issues");if($.startsWith("-")||$.endsWith("-"))Y.push("Tool name starts or ends with a dash, which may cause parsing issues in some contexts");if($.startsWith(".")||$.endsWith("."))Y.push("Tool name starts or ends with a dot, which may cause parsing issues in some contexts");if(!ub0.test($)){let U=[...$].filter((z)=>!/[A-Za-z0-9._-]/.test(z)).filter((z,I,Q)=>Q.indexOf(z)===I);return Y.push(`Tool name contains invalid characters: ${U.map((z)=>`"${z}"`).join(", ")}`,"Allowed characters are: A-Z, a-z, 0-9, underscore (_), dash (-), and dot (.)"),{isValid:!1,warnings:Y}}return{isValid:!0,warnings:Y}}function ib0($,Y){if(Y.length>0){console.warn(`Tool name validation warning for "${$}":`);for(let U of Y)console.warn(` - ${U}`);console.warn("Tool registration will proceed, but this may cause compatibility issues."),console.warn("Consider updating the tool name to conform to the MCP tool naming standard."),console.warn("See SEP: Specify Format for Tool Names (https://github.com/modelcontextprotocol/modelcontextprotocol/issues/986) for more details.")}}function RS($){let Y=bb0($);return ib0($,Y.warnings),Y.isValid}function cb0($){return typeof $==="object"&&$!==null&&"_zod"in $}function nb0($){return typeof $==="object"&&$!==null&&!("_zod"in $)&&"_def"in $&&typeof $._def?.typeName==="string"}function pb0($){if(typeof $!=="object"||$===null)return!1;if(xI($))return!1;let Y=Object.getPrototypeOf($);if(Y!==Object.prototype&&Y!==null)return!1;return Object.values($).every((U)=>cb0(U))}function cw($){if($===void 0)return;if(pb0($))return U0($);if(typeof $==="object"&&$!==null&&!xI($)&&Object.values($).some((Y)=>nb0(Y)))throw TypeError("Raw-shape inputSchema/outputSchema/argsSchema fields must be Zod v4 schemas. Got a Zod v3 field schema. Import from `zod/v4` (or upgrade your zod import), or wrap with `z.object({...})` yourself.");if(!xI($))throw TypeError("inputSchema/outputSchema/argsSchema must be a Standard Schema (e.g. z.object({...})) or a raw Zod shape ({ field: z.string() }).");return $}var zS,Au0,T1,L1,Bu0,ot="2026-07-28",v7,at,ju0,Eu0,Cu0,$e,Ye,_u0,jw,Cb1,Rb1,kt,XS,ku0,xu0,yI,i0,I1,yw,Ie,uI,kw,bu0=0,iu0="private",cu0,su0,Cw,LS,Ke,_b1,vb1,Ub0,zb0,FS,Rw,FH="2026-07-28",We,Jb0,P$=($)=>cG.safeParse($).success,h7=($)=>nG.safeParse($).success,VH=($)=>PI.safeParse($).success,bw=($)=>TI.safeParse($).success,Y3=($)=>typeof $==="object"&&$!==null&&!Array.isArray($)&&$.resultType==="input_required",it="x-mcp-header",Kb0,Gb0,Hb0,Wb0,hw=-32020,hb1,Xb0,ct=!1,QS="draft-2020-12",Vb0,Ob0,Nb0,nt,Db0,Eb0,qe=250,Cb0,Rb0,we,Me,_b0,vb0,Ne=60000,Sb0,gb0,yb0,De,TS,fb0,Sb1,Ae=10485760,ES=class{_buffer;_maxBufferSize;constructor($){this._maxBufferSize=$?.maxBufferSize??Ae}append($){if((this._buffer?.length??0)+$.length>this._maxBufferSize)throw this.clear(),Error(`ReadBuffer exceeded maximum size of ${this._maxBufferSize} bytes`);this._buffer=this._buffer?Buffer.concat([this._buffer,$]):$}readMessage(){while(this._buffer){let $=this._buffer.indexOf(`
`);if($===-1)return null;let Y=this._buffer.toString("utf8",0,$).replace(/\r$/,"");this._buffer=this._buffer.subarray($+1);try{return Be(Y)}catch(U){if(U instanceof SyntaxError)continue;throw U}}return null}clear(){this._buffer=void 0}},ub0;var nw=m(()=>{Nj();Dj();St();Ah();zS=Symbol.for("mcp.sdk.errorBrands");Au0=class $ extends Error{static{Object.defineProperty(this,"mcpBrand",{value:"mcp.OAuthError"})}static[Symbol.hasInstance](Y){return kI(this,Y)}static isInstance(Y){if(typeof this!=="function")throw TypeError("isInstance must be called on the class (e.g. `SdkError.isInstance(value)`); for callbacks use `v => SdkError.isInstance(v)`");return kI(this,Y)}constructor(Y,U,z){super(U);this.code=Y,this.errorUri=z,this.name="OAuthError",KS(this,new.target)}toResponseObject(){let Y={error:this.code,error_description:this.message};if(this.errorUri)Y.error_uri=this.errorUri;return Y}static fromResponse(Y){return new $(Y.error,Y.error_description??Y.error,Y.error_uri)}},T1=function($){return $.NotConnected="NOT_CONNECTED",$.AlreadyConnected="ALREADY_CONNECTED",$.NotInitialized="NOT_INITIALIZED",$.CapabilityNotSupported="CAPABILITY_NOT_SUPPORTED",$.RequestTimeout="REQUEST_TIMEOUT",$.ConnectionClosed="CONNECTION_CLOSED",$.SendFailed="SEND_FAILED",$.InvalidResult="INVALID_RESULT",$.UnsupportedResultType="UNSUPPORTED_RESULT_TYPE",$.InputRequiredRoundsExceeded="INPUT_REQUIRED_ROUNDS_EXCEEDED",$.ListPaginationExceeded="LIST_PAGINATION_EXCEEDED",$.MethodNotSupportedByProtocolVersion="METHOD_NOT_SUPPORTED_BY_PROTOCOL_VERSION",$.EraNegotiationFailed="ERA_NEGOTIATION_FAILED",$.ClientHttpNotImplemented="CLIENT_HTTP_NOT_IMPLEMENTED",$.ClientHttpAuthentication="CLIENT_HTTP_AUTHENTICATION",$.ClientHttpForbidden="CLIENT_HTTP_FORBIDDEN",$.ClientHttpUnexpectedContent="CLIENT_HTTP_UNEXPECTED_CONTENT",$.ClientHttpFailedToOpenStream="CLIENT_HTTP_FAILED_TO_OPEN_STREAM",$.ClientHttpFailedToTerminateSession="CLIENT_HTTP_FAILED_TO_TERMINATE_SESSION",$}({}),L1=class extends Error{static{Object.defineProperty(this,"mcpBrand",{value:"mcp.SdkError"})}static[Symbol.hasInstance]($){return kI(this,$)}static isInstance($){if(typeof this!=="function")throw TypeError("isInstance must be called on the class (e.g. `SdkError.isInstance(value)`); for callbacks use `v => SdkError.isInstance(v)`");return kI(this,$)}constructor($,Y,U){super(Y);this.code=$,this.data=U,this.name="SdkError",KS(this,new.target)}},Bu0=class extends L1{static{Object.defineProperty(this,"mcpBrand",{value:"mcp.SdkHttpError"})}constructor($,Y,U){super($,Y,U);this.name="SdkHttpError"}get status(){return this.data.status}get statusText(){return this.data.statusText}};v7=[ot];at=["task","inputRequests","requestState"];Eu0=new Set(["const","enum","default","examples"]),Cu0=new Set(["properties","patternProperties","$defs","definitions","dependentSchemas","dependencies"]);$e={ping:null,initialize:null,"completion/complete":null,"logging/setLevel":null,"prompts/get":null,"prompts/list":null,"resources/list":null,"resources/templates/list":null,"resources/read":null,"resources/subscribe":null,"resources/unsubscribe":null,"tools/call":null,"tools/list":null,"tasks/get":null,"tasks/result":null,"tasks/list":null,"tasks/cancel":null,"sampling/createMessage":null,"elicitation/create":null,"roots/list":null},Ye={"notifications/cancelled":null,"notifications/progress":null,"notifications/initialized":null,"notifications/roots/list_changed":null,"notifications/tasks/status":null,"notifications/message":null,"notifications/resources/updated":null,"notifications/resources/list_changed":null,"notifications/tools/list_changed":null,"notifications/prompts/list_changed":null,"notifications/elicitation/complete":null},_u0={ping:null,initialize:null,"completion/complete":null,"logging/setLevel":null,"prompts/get":null,"prompts/list":null,"resources/list":null,"resources/templates/list":null,"resources/read":null,"resources/subscribe":null,"resources/unsubscribe":null,"tools/call":null,"tools/list":null,"sampling/createMessage":null,"elicitation/create":null,"roots/list":null};Cb1=Object.keys($e),Rb1=Object.keys(Ye);kt={ok:!1,reason:"not-in-era"};XS={era:"2025-11-25",hasRequestMethod:Ue,hasNotificationMethod:ze,validateRequest:($,Y)=>Ew(Su0($),Y),validateResult:($,Y)=>Ew(hu0($),Y),validateNotification:($,Y)=>Ew(gu0($),Y),hasInputRequestMethod:()=>!1,validateInputRequest:()=>kt,validateInputResponse:()=>kt,samplingResultVariant:($,Y)=>{let U=tt();return Ew($?U.CreateMessageResultWithToolsSchema:U.CreateMessageResultSchema,Y)},outboundEnvelope:($)=>{return},validateEnvelopeMeta:($)=>[],projectCallToolResult($,Y){let U=st($),z=U.structuredContent;if(z===void 0)return U;let I=typeof z!=="object"||z===null||Array.isArray(z),Q=Y!==void 0&&et(Y);if(!I&&!Q)return U;return{...U,structuredContent:{result:z}}},decodeResult($,Y){if(IS(Y)&&"resultType"in Y){let U={...Y};return delete U.resultType,{kind:"complete",result:ft(U)}}return{kind:"complete",result:ft(Y)}},encodeResult($,Y){if($!=="tools/list")return Y;l Line truncated
Set the \`cycles\` parameter to \`"ref"\` to resolve cyclical schemas with defs.`)}for(let K of $.seen.entries()){let z=K[1];if(Y===K[0]){J(K);continue}if($.external){let H=$.external.registry.get(K[0])?.id;if(Y!==K[0]&&H){J(K);continue}}if($.metadataRegistry.get(K[0])?.id){J(K);continue}if(z.cycle){J(K);continue}if(z.count>1){if($.reused==="ref"){J(K);continue}}}}function D7($,Y){let U=$.seen.get(Y);if(!U)throw Error("Unprocessed schema. This is a bug in Zod.");let I=(z)=>{let G=$.seen.get(z);if(G.ref===null)return;let H=G.def??G.schema,W={...H},X=G.ref;if(G.ref=null,X){I(X);let q=$.seen.get(X),V=q.schema;if(V.$ref&&($.target==="draft-07"||$.target==="draft-04"||$.target==="openapi-3.0"))H.allOf=H.allOf??[],H.allOf.push(V);else Object.assign(H,V);if(Object.assign(H,W),z._zod.parent===X)for(let M in H){if(M==="$ref"||M==="allOf")continue;if(!(M in W))delete H[M]}if(V.$ref&&q.def)for(let M in H){if(M==="$ref"||M==="allOf")continue;if(M in q.def&&JSON.stringify(H[M])===JSON.stringify(q.def[M]))delete H[M]}}let Z=z._zod.parent;if(Z&&Z!==X){I(Z);let q=$.seen.get(Z);if(q?.schema.$ref){if(H.$ref=q.schema.$ref,q.def)for(let V in H){if(V==="$ref"||V==="allOf")continue;if(V in q.def&&JSON.stringify(H[V])===JSON.stringify(q.def[V]))delete H[V]}}}$.override({zodSchema:z,jsonSchema:H,path:G.path??[]})};for(let z of[...$.seen.entries()].reverse())I(z[0]);let Q={};if($.target==="draft-2020-12")Q.$schema="https://json-schema.org/draft/2020-12/schema";else if($.target==="draft-07")Q.$schema="http://json-schema.org/draft-07/schema#";else if($.target==="draft-04")Q.$schema="http://json-schema.org/draft-04/schema#";else if($.target==="openapi-3.0");if($.external?.uri){let z=$.external.registry.get(Y)?.id;if(!z)throw Error("Schema is missing an `id` property");Q.$id=$.external.uri(z)}Object.assign(Q,U.def??U.schema);let J=$.metadataRegistry.get(Y)?.id;if(J!==void 0&&Q.id===J)delete Q.id;let K=$.external?.defs??{};for(let z of $.seen.entries()){let G=z[1];if(G.def&&G.defId){if(G.def.id===G.defId)delete G.def.id;K[G.defId]=G.def}}if($.external);else if(Object.keys(K).length>0)if($.target==="draft-2020-12")Q.$defs=K;else Q.definitions=K;try{let z=JSON.parse(JSON.stringify(Q));return Object.defineProperty(z,"~standard",{value:{...Y["~standard"],jsonSchema:{input:LQ(Y,"input",$.processors),output:LQ(Y,"output",$.processors)}},enumerable:!1,writable:!1}),z}catch(z){throw Error("Error converting schema to JSON.")}}function v8($,Y){let U=Y??{seen:new Set};if(U.seen.has($))return!1;U.seen.add($);let I=$._zod.def;if(I.type==="transform")return!0;if(I.type==="array")return v8(I.element,U);if(I.type==="set")return v8(I.valueType,U);if(I.type==="lazy")return v8(I.getter(),U);if(I.type==="promise"||I.type==="optional"||I.type==="nonoptional"||I.type==="nullable"||I.type==="readonly"||I.type==="default"||I.type==="prefault")return v8(I.innerType,U);if(I.type==="intersection")return v8(I.left,U)||v8(I.right,U);if(I.type==="record"||I.type==="map")return v8(I.keyType,U)||v8(I.valueType,U);if(I.type==="pipe"){if($._zod.traits.has("$ZodCodec"))return!0;return v8(I.in,U)||v8(I.out,U)}if(I.type==="object"){for(let Q in I.shape)if(v8(I.shape[Q],U))return!0;return!1}if(I.type==="union"){for(let Q of I.options)if(v8(Q,U))return!0;return!1}if(I.type==="tuple"){for(let Q of I.items)if(v8(Q,U))return!0;if(I.rest&&v8(I.rest,U))return!0;return!1}return!1}var u_=($,Y={})=>(U)=>{let I=O7({...U,processors:Y});return z4($,I),N7(I,$),D7(I,$)},LQ=($,Y,U={})=>(I)=>{let{libraryOptions:Q,target:J}=I??{},K=O7({...Q??{},target:J,io:Y,processors:U});return z4($,K),N7(K,$),D7(K,$)};var PG=m(()=>{DG()});function yY($,Y){if("_idmap"in $){let I=$,Q=O7({...Y,processors:GL}),J={};for(let G of I._idmap.entries()){let[H,W]=G;z4(W,Q)}let K={},z={registry:I,uri:Y?.uri,defs:J};Q.external=z;for(let G of I._idmap.entries()){let[H,W]=G;N7(Q,W),K[H]=D7(Q,W)}if(Object.keys(J).length>0){let G=Q.target==="draft-2020-12"?"$defs":"definitions";K.__shared={[G]:J}}return{schemas:K}}let U=O7({...Y,processors:GL});return z4($,U),N7(U,$),D7(U,$)}var su0,b_=($,Y,U,I)=>{let Q=U;Q.type="string";let{minimum:J,maximum:K,format:z,patterns:G,contentEncoding:H}=$._zod.bag;if(typeof J==="number")Q.minLength=J;if(typeof K==="number")Q.maxLength=K;if(z){if(Q.format=su0[z]??z,Q.format==="")delete Q.format;if(z==="time")delete Q.format}if(H)Q.contentEncoding=H;if(G&&G.size>0){let W=[...G];if(W.length===1)Q.pattern=W[0].source;else if(W.length>1)Q.allOf=[...W.map((X)=>({...Y.target==="draft-07"||Y.target==="draft-04"||Y.target==="openapi-3.0"?{type:"string"}:{},pattern:X.source}))]}},i_=($,Y,U,I)=>{let Q=U,{minimum:J,maximum:K,format:z,multipleOf:G,exclusiveMaximum:H,exclusiveMinimum:W}=$._zod.bag;if(typeof z==="string"&&z.includes("int"))Q.type="integer";else Q.type="number";let X=typeof W==="number"&&W>=(J??Number.NEGATIVE_INFINITY),Z=typeof H==="number"&&H<=(K??Number.POSITIVE_INFINITY),q=Y.target==="draft-04"||Y.target==="openapi-3.0";if(X)if(q)Q.minimum=W,Q.exclusiveMinimum=!0;else Q.exclusiveMinimuLine truncated
`}function _i0($){let Y=[];if($.length===0)return{isValid:!1,warnings:["Tool name cannot be empty"]};if($.length>128)return{isValid:!1,warnings:[`Tool name exceeds maximum length of 128 characters (current: ${$.length})`]};if($.includes(" "))Y.push("Tool name contains spaces, which may cause parsing issues");if($.includes(","))Y.push("Tool name contains commas, which may cause parsing issues");if($.startsWith("-")||$.endsWith("-"))Y.push("Tool name starts or ends with a dash, which may cause parsing issues in some contexts");if($.startsWith(".")||$.endsWith("."))Y.push("Tool name starts or ends with a dot, which may cause parsing issues in some contexts");if(!Ri0.test($)){let U=[...$].filter((I)=>!/[A-Za-z0-9._-]/.test(I)).filter((I,Q,J)=>J.indexOf(I)===Q);return Y.push(`Tool name contains invalid characters: ${U.map((I)=>`"${I}"`).join(", ")}`,"Allowed characters are: A-Z, a-z, 0-9, underscore (_), dash (-), and dot (.)"),{isValid:!1,warnings:Y}}return{isValid:!0,warnings:Y}}function vi0($,Y){if(Y.length>0){console.warn(`Tool name validation warning for "${$}":`);for(let U of Y)console.warn(` - ${U}`);console.warn("Tool registration will proceed, but this may cause compatibility issues."),console.warn("Consider updating the tool name to conform to the MCP tool naming standard."),console.warn("See SEP: Specify Format for Tool Names (https://github.com/modelcontextprotocol/modelcontextprotocol/issues/986) for more details.")}}function kh($){let Y=_i0($);return vi0($,Y.warnings),Y.isValid}function Si0($){return typeof $==="object"&&$!==null&&"_zod"in $}function hi0($){return typeof $==="object"&&$!==null&&!("_zod"in $)&&"_def"in $&&typeof $._def?.typeName==="string"}function gi0($){if(typeof $!=="object"||$===null)return!1;if(fQ($))return!1;let Y=Object.getPrototypeOf($);if(Y!==Object.prototype&&Y!==null)return!1;return Object.values($).every((U)=>Si0(U))}function ow($){if($===void 0)return;if(gi0($))return U0($);if(typeof $==="object"&&$!==null&&!fQ($)&&Object.values($).some((Y)=>hi0(Y)))throw TypeError("Raw-shape inputSchema/outputSchema/argsSchema fields must be Zod v4 schemas. Got a Zod v3 field schema. Import from `zod/v4` (or upgrade your zod import), or wrap with `z.object({...})` yourself.");if(!fQ($))throw TypeError("inputSchema/outputSchema/argsSchema must be a Standard Schema (e.g. z.object({...})) or a raw Zod shape ({ field: z.string() }).");return $}var Wh,Zb0,T1,L1,qb0,He="2026-07-28",g7,Ze,Fb0,wb0,Mb0,Le,Fe,Nb0,Sw,li1,oi1,at,Mh,Eb0,jb0,kQ,i0,Q1,iw,Oe,bQ,cw,_b0=0,vb0="private",Sb0,bb0,gw,Bh,Be,ri1,si1,mb0,lb0,Ah,yw,OH="2026-07-28",Te,sb0,_$=($)=>pG.safeParse($).success,y7=($)=>mG.safeParse($).success,wH=($)=>TQ.safeParse($).success,mw=($)=>EQ.safeParse($).success,I3=($)=>typeof $==="object"&&$!==null&&!Array.isArray($)&&$.resultType==="input_required",Ue="x-mcp-header",ab0,tb0,eb0,$i0,fw=-32020,ai1,Yi0,Ie=!1,Zh="draft-2020-12",Qi0,Hi0,Wi0,Qe,Xi0,wi0,Ce=250,Mi0,Oi0,Se,he,Ni0,Di0,ye=60000,Ai0,Pi0,Ti0,ke,Sh,Ci0,ti1,xe=10485760,gh=class{_buffer;_maxBufferSize;constructor($){this._maxBufferSize=$?.maxBufferSize??xe}append($){if((this._buffer?.length??0)+$.length>this._maxBufferSize)throw this.clear(),Error(`ReadBuffer exceeded maximum size of ${this._maxBufferSize} bytes`);this._buffer=this._buffer?Buffer.concat([this._buffer,$]):$}readMessage(){while(this._buffer){let $=this._buffer.indexOf(`
`);if($===-1)return null;let Y=this._buffer.toString("utf8",0,$).replace(/\r$/,"");this._buffer=this._buffer.subarray($+1);try{return fe(Y)}catch(U){if(U instanceof SyntaxError)continue;throw U}}return null}clear(){this._buffer=void 0}},Ri0;var rw=m(()=>{jE();CE();ot();RS();Wh=Symbol.for("mcp.sdk.errorBrands");Zb0=class $ extends Error{static{Object.defineProperty(this,"mcpBrand",{value:"mcp.OAuthError"})}static[Symbol.hasInstance](Y){return xQ(this,Y)}static isInstance(Y){if(typeof this!=="function")throw TypeError("isInstance must be called on the class (e.g. `SdkError.isInstance(value)`); for callbacks use `v => SdkError.isInstance(v)`");return xQ(this,Y)}constructor(Y,U,I){super(U);this.code=Y,this.errorUri=I,this.name="OAuthError",Vh(this,new.target)}toResponseObject(){let Y={error:this.code,error_description:this.message};if(this.errorUri)Y.error_uri=this.errorUri;return Y}static fromResponse(Y){return new $(Y.error,Y.error_description??Y.error,Y.error_uri)}},T1=function($){return $.NotConnected="NOT_CONNECTED",$.AlreadyConnected="ALREADY_CONNECTED",$.NotInitialized="NOT_INITIALIZED",$.CapabilityNotSupported="CAPABILITY_NOT_SUPPORTED",$.RequestTimeout="REQUEST_TIMEOUT",$.ConnectionClosed="CONNECTION_CLOSED",$.SendFailed="SEND_FAILED",$.InvalidResult="INVALID_RESULT",$.UnsupportedResultType="UNSUPPORTED_RESULT_TYPE",$.InputRequiredRoundsExceeded="INPUT_REQUIRED_ROUNDS_EXCEEDED",$.ListPaginationExceeded="LIST_PAGINATION_EXCEEDED",$.MethodNotSupportedByProtocolVersion="METHOD_NOT_SUPPORTED_BY_PROTOCOL_VERSION",$.EraNegotiationFailed="ERA_NEGOTIATION_FAILED",$.ClientHttpNotImplemented="CLIENT_HTTP_NOT_IMPLEMENTED",$.ClientHttpAuthentication="CLIENT_HTTP_AUTHENTICATION",$.ClientHttpForbidden="CLIENT_HTTP_FORBIDDEN",$.ClientHttpUnexpectedContent="CLIENT_HTTP_UNEXPECTED_CONTENT",$.ClientHttpFailedToOpenStream="CLIENT_HTTP_FAILED_TO_OPEN_STREAM",$.ClientHttpFailedToTerminateSession="CLIENT_HTTP_FAILED_TO_TERMINATE_SESSION",$}({}),L1=class extends Error{static{Object.defineProperty(this,"mcpBrand",{value:"mcp.SdkError"})}static[Symbol.hasInstance]($){return xQ(this,$)}static isInstance($){if(typeof this!=="function")throw TypeError("isInstance must be called on the class (e.g. `SdkError.isInstance(value)`); for callbacks use `v => SdkError.isInstance(v)`");return xQ(this,$)}constructor($,Y,U){super(Y);this.code=$,this.data=U,this.name="SdkError",Vh(this,new.target)}},qb0=class extends L1{static{Object.defineProperty(this,"mcpBrand",{value:"mcp.SdkHttpError"})}constructor($,Y,U){super($,Y,U);this.name="SdkHttpError"}get status(){return this.data.status}get statusText(){return this.data.statusText}};g7=[He];Ze=["task","inputRequests","requestState"];wb0=new Set(["const","enum","default","examples"]),Mb0=new Set(["properties","patternProperties","$defs","definitions","dependentSchemas","dependencies"]);Le={ping:null,initialize:null,"completion/complete":null,"logging/setLevel":null,"prompts/get":null,"prompts/list":null,"resources/list":null,"resources/templates/list":null,"resources/read":null,"resources/subscribe":null,"resources/unsubscribe":null,"tools/call":null,"tools/list":null,"tasks/get":null,"tasks/result":null,"tasks/list":null,"tasks/cancel":null,"sampling/createMessage":null,"elicitation/create":null,"roots/list":null},Fe={"notifications/cancelled":null,"notifications/progress":null,"notifications/initialized":null,"notifications/roots/list_changed":null,"notifications/tasks/status":null,"notifications/message":null,"notifications/resources/updated":null,"notifications/resources/list_changed":null,"notifications/tools/list_changed":null,"notifications/prompts/list_changed":null,"notifications/elicitation/complete":null},Nb0={ping:null,initialize:null,"completion/complete":null,"logging/setLevel":null,"prompts/get":null,"prompts/list":null,"resources/list":null,"resources/templates/list":null,"resources/read":null,"resources/subscribe":null,"resources/unsubscribe":null,"tools/call":null,"tools/list":null,"sampling/createMessage":null,"elicitation/create":null,"roots/list":null};li1=Object.keys(Le),oi1=Object.keys(Fe);at={ok:!1,reason:"not-in-era"};Mh={era:"2025-11-25",hasRequestMethod:we,hasNotificationMethod:Me,validateRequest:($,Y)=>hw(Ab0($),Y),validateResult:($,Y)=>hw(Bb0($),Y),validateNotification:($,Y)=>hw(Pb0($),Y),hasInputRequestMethod:()=>!1,validateInputRequest:()=>at,validateInputResponse:()=>at,samplingResultVariant:($,Y)=>{let U=qe();return hw($?U.CreateMessageResultWithToolsSchema:U.CreateMessageResultSchema,Y)},outboundEnvelope:($)=>{return},validateEnvelopeMeta:($)=>[],projectCallToolResult($,Y){let U=Xe($),I=U.structuredContent;if(I===void 0)return U;let Q=typeof I!=="object"||I===null||Array.isArray(I),J=Y!==void 0&&Ve(Y);if(!Q&&!J)return U;return{...U,structuredContent:{result:I}}},decodeResult($,Y){if(Xh(Y)&&"resultType"in Y){let U={...Y};return delete U.resultType,{kind:"complete",result:et(U)}}return{kind:"complete",result:et(Y)}},encodeResult($,Y){if($!=="tools/list")return Y;l Line truncated
* content-type
* Copyright(c) 2015 Douglas Christopher Wilson
* MIT Licensed
*/fb0=E0(($)=>{var Y=/; *([!#$%&'*+.^_`|~0-9A-Za-z-]+) *= *("(?:[\u000b\u0020\u0021\u0023-\u005b\u005d-\u007e\u0080-\u00ff]|\\[\u000b\u0020-\u00ff])*"|[!#$%&'*+.^_`|~0-9A-Za-z-]+) */g,U=/\\([\u000b\u0020-\u00ff])/g,z=/^[!#$%&'*+.^_`|~0-9A-Za-z-]+\/[!#$%&'*+.^_`|~0-9A-Za-z-]+$/;$.parse=I;function I(K){if(!K)throw TypeError("argument string is required");var G=typeof K==="object"?Q(K):K;if(typeof G!=="string")throw TypeError("argument string is required to be a string");var H=G.indexOf(";"),W=H!==-1?G.slice(0,H).trim():G.trim();if(!z.test(W))throw TypeError("invalid media type");var X=new J(W.toLowerCase());if(H!==-1){var Z,q,V;Y.lastIndex=H;while(q=Y.exec(G)){if(q.index!==H)throw TypeError("invalid parameter format");if(H+=q[0].length,Z=q[1].toLowerCase(),V=q[2],V.charCodeAt(0)===34){if(V=V.slice(1,-1),V.indexOf("\\")!==-1)V=V.replace(U,"$1")}X.parameters[Z]=V}if(H!==G.length)throw TypeError("invalid parameter format")}return X}function Q(K){var G;if(typeof K.getHeader==="function")G=K.getHeader("content-type");else if(typeof K.headers==="object")G=K.headers&&K.headers["content-type"];if(typeof G!=="string")throw TypeError("content-type header is missing from object");return G}function J(K){this.parameters=Object.create(null),this.type=K}}),Sb1=UV(fb0(),1);ub0=/^[A-Za-z0-9._-]{1,128}$/});function _S($){let Y=new $({strict:!1,validateFormats:!0,validateSchema:!1,allErrors:!0});return Jc0(Y),Y}var pw,Pe,F1,v1,K5,mw,db0,Te,je,dw,mb0,G5,lb0,ob0,Ee,rb0,lw,bI,MH,iI,ow,sb0,Ce,ab0,tb0,eb0,vS,$i0,hS,Re,Yi0,Ui0,zi0,Ii0,Qi0,Ji0,Ki0,Gi0,SS,Hi0,Wi0,Xi0,_e,ve,he,Zi0,qi0,Vi0,gS,Li0,Se,Fi0,wi0,Mi0,Oi0,Ni0,Di0,Ai0,Bi0,ge,Pi0,ye,ke,xe,Ti0,yS,ji0,fe,ue,be,Ei0,Ci0,ie,Ri0,_i0,vi0,ce,hi0,Si0,ne,gi0,yi0,ki0,xi0,fi0,ui0,bi0,ii0,ci0,ni0,pi0,di0,mi0,li0,oi0,ri0,si0,ai0,ti0,ei0,$c0,Yc0,Uc0,pe,zc0,Ic0,Qc0,Jc0,rw=class{_ajv;_ajvDraft7;_ajv2019;_userAjv;constructor($){this._userAjv=$!==void 0,this._ajv=$}get ajv(){return this._ajv??=_S(Ic0.Ajv2020)}_engineFor($){if(this._userAjv)return this.ajv;let Y=Br($,"pass a pre-configured Ajv instance to AjvJsonSchemaValidator(ajv) to validate other dialects.");if(Y==="2020-12")return this.ajv;if(Y==="2019-09")return this._ajv2019??=_S(zc0.Ajv2019);return this._ajvDraft7??=_S(pe.Ajv)}getValidator($){let Y=this._engineFor($),U="$id"in $&&typeof $.$id==="string"?Y.getSchema($.$id)??Y.compile($):Y.compile($);return(z)=>{return U(z)?{valid:!0,data:z,errorMessage:void 0}:{valid:!1,data:void 0,errorMessage:Y.errorsText(U.errors)}}}},db1;var de=m(()=>{Nj();Dj();pw=E0(($)=>{Object.defineProperty($,"__esModule",{value:!0}),$.regexpCode=$.getEsmExportName=$.getProperty=$.safeStringify=$.stringify=$.strConcat=$.addCodeArg=$.str=$._=$.nil=$._Code=$.Name=$.IDENTIFIER=$._CodeOrName=void 0;var Y=class{};$._CodeOrName=Y,$.IDENTIFIER=/^[a-z$_][a-z$_0-9]*$/i;var U=class extends Y{constructor(F){super();if(!$.IDENTIFIER.test(F))throw Error("CodeGen: name must be a valid identifier");this.str=F}toString(){return this.str}emptyStr(){return!1}get names(){return{[this.str]:1}}};$.Name=U;var z=class extends Y{constructor(F){super();this._items=typeof F==="string"?[F]:F}toString(){return this.str}emptyStr(){if(this._items.length>1)return!1;let F=this._items[0];return F===""||F==='""'}get str(){var F;return(F=this._str)!==null&&F!==void 0?F:this._str=this._items.reduce((N,O)=>`${N}${O}`,"")}get names(){var F;return(F=this._names)!==null&&F!==void 0?F:this._names=this._items.reduce((N,O)=>{if(O instanceof U)N[O.str]=(N[O.str]||0)+1;return N},{})}};$._Code=z,$.nil=new z("");function I(F,...N){let O=[F[0]],D=0;while(D<N.length)K(O,N[D]),O.push(F[++D]);return new z(O)}$._=I;let Q=new z("+");function J(F,...N){let O=[q(F[0])],D=0;while(D<N.length)O.push(Q),K(O,N[D]),O.push(Q,q(F[++D]));return G(O),new z(O)}$.str=J;function K(F,N){if(N instanceof z)F.push(...N._items);else if(N instanceof U)F.push(N);else F.push(X(N))}$.addCodeArg=K;function G(F){let N=1;while(N<F.length-1){if(F[N]===Q){let O=H(F[N-1],F[N+1]);if(O!==void 0){F.splice(N-1,3,O);continue}F[N++]="+"}N++}}function H(F,N){if(N==='""')return F;if(F==='""')return N;if(typeof F=="string"){if(N instanceof U||F[F.length-1]!=='"')return;if(typeof N!="string")return`${F.slice(0,-1)}${N}"`;if(N[0]==='"')return F.slice(0,-1)+N.slice(1);return}if(typeof N=="string"&&N[0]==='"'&&!(F instanceof U))return`"${F}${N.slice(1)}`}function W(F,N){return N.emptyStr()?F:F.emptyStr()?N:J`${F}${N}`}$.strConcat=W;function X(F){return typeof F=="number"||typeof F=="boolean"||F===null?F:q(Array.isArray(F)?F.join(","):F)}function Z(F){return new z(q(F))}$.stringify=Z;function q(F){return JSON.stringify(F).replace(/\u2028/g,"\\u2028").replace(/\u2029/g,"\\u2029")}$.safeStringify=q;function V(F){return typeof F=="string"&&$.IDENTIFIER.test(F)?new z(`.${F}`):I`[${F}]`}$.getProperty=V;function w(F){if(typeof F=="string"&&$.IDENTIFIER.test(F))return new z(`${F}`);throw Error(`CodeGen: invalid export name: ${F}, use explicit $id name mapping`)}$.getEsmExportName=w;function M(F){return new z(F.toStringLine truncated
`:""},this._extScope=R,this._scope=new U.Scope({parent:R}),this._nodes=[new w]}toString(){return this._root.render(this.opts)}name(R){return this._scope.name(R)}scopeName(R){return this._extScope.name(R)}scopeValue(R,o){let e=this._extScope.value(R,o);return(this._values[e.prefix]||(this._values[e.prefix]=new Set)).add(e),e}getScopeValue(R,o){return this._extScope.getValue(R,o)}scopeRefs(R){return this._extScope.scopeRefs(R,this._values)}scopeCode(){return this._extScope.scopeCode(this._values)}_def(R,o,e,O0){let T0=this._scope.toName(o);if(e!==void 0&&O0)this._constants[T0.str]=e;return this._leafNode(new J(R,T0,e)),T0}const(R,o,e){return this._def(U.varKinds.const,R,o,e)}let(R,o,e){return this._def(U.varKinds.let,R,o,e)}var(R,o,e){return this._def(U.varKinds.var,R,o,e)}assign(R,o,e){return this._leafNode(new K(R,o,e))}add(R,o){return this._leafNode(new G(R,$.operators.ADD,o))}code(R){if(typeof R=="function")R();else if(R!==Y.nil)this._leafNode(new Z(R));return this}object(...R){let o=["{"];for(let[e,O0]of R){if(o.length>1)o.push(",");if(o.push(e),e!==O0||this.opts.es5)o.push(":"),(0,Y.addCodeArg)(o,O0)}return o.push("}"),new Y._Code(o)}if(R,o,e){if(this._blockNode(new F(R)),o&&e)this.code(o).else().code(e).endIf();else if(o)this.code(o).endIf();else if(e)throw Error('CodeGen: "else" body without "then" body');return this}elseIf(R){return this._elseNode(new F(R))}else(){return this._elseNode(new M)}endIf(){return this._endBlockNode(F,M)}_for(R,o){if(this._blockNode(R),o)this.code(o).endFor();return this}for(R,o){return this._for(new O(R),o)}forRange(R,o,e,O0,T0=this.opts.es5?U.varKinds.var:U.varKinds.let){let y0=this._scope.toName(R);return this._for(new D(T0,y0,o,e),()=>O0(y0))}forOf(R,o,e,O0=U.varKinds.const){let T0=this._scope.toName(R);if(this.opts.es5){let y0=o instanceof Y.Name?o:this.var("_arr",o);return this.forRange("_i",0,Y._`${y0}.length`,(v0)=>{this.var(T0,Y._`${y0}[${v0}]`),e(T0)})}return this._for(new P("of",O0,T0,o),()=>e(T0))}forIn(R,o,e,O0=this.opts.es5?U.varKinds.var:U.varKinds.const){if(this.opts.ownProperties)return this.forOf(R,Y._`Object.keys(${o})`,e);let T0=this._scope.toName(R);return this._for(new P("in",O0,T0,o),()=>e(T0))}endFor(){return this._endBlockNode(N)}label(R){return this._leafNode(new H(R))}break(R){return this._leafNode(new W(R))}return(R){let o=new A;if(this._blockNode(o),this.code(R),o.nodes.length!==1)throw Error('CodeGen: "return" should have one node');return this._endBlockNode(A)}try(R,o,e){if(!o&&!e)throw Error('CodeGen: "try" without "catch" and "finally"');let O0=new j;if(this._blockNode(O0),this.code(R),o){let T0=this.name("e");this._currNode=O0.catch=new C(T0),o(T0)}if(e)this._currNode=O0.finally=new b,this.code(e);return this._endBlockNode(C,b)}throw(R){return this._leafNode(new X(R))}block(R,o){if(this._blockStarts.push(this._nodes.length),R)this.code(R).endBlock(o);return this}endBlock(R){let o=this._blockStarts.pop();if(o===void 0)throw Error("CodeGen: not in self-balancing block");let e=this._nodes.length-o;if(e<0||R!==void 0&&e!==R)throw Error(`CodeGen: wrong number of nodes: ${e} vs ${R} expected`);return this._nodes.length=o,this}func(R,o=Y.nil,e,O0){if(this._blockNode(new T(R,o,e)),O0)this.code(O0).endFunc();return this}endFunc(){return this._endBlockNode(T)}optimize(R=1){while(R-- >0)this._root.optimizeNodes(),this._root.optimizeNames(this._root.names,this._constants)}_leafNode(R){return this._currNode.nodes.push(R),this}_blockNode(R){this._currNode.nodes.push(R),this._nodes.push(R)}_endBlockNode(R,o){let e=this._currNode;if(e instanceof R||o&&e instanceof o)return this._nodes.pop(),this;throw Error(`CodeGen: not in block "${o?`${R.kind}/${o.kind}`:R.kind}"`)}_elseNode(R){let o=this._currNode;if(!(o instanceof F))throw Error('CodeGen: "else" without "if"');return this._currNode=o.else=R,this}get _root(){return this._nodes[0]}get _currNode(){let R=this._nodes;return R[R.length-1]}set _currNode(R){let o=this._nodes;o[o.length-1]=R}};$.CodeGen=x;function g(R,o){for(let e in o)R[e]=(R[e]||0)+(o[e]||0);return R}function i(R,o){return o instanceof Y._CodeOrName?g(R,o.names):R}function c(R,o,e){if(R instanceof Y.Name)return O0(R);if(!T0(R))return R;return new Y._Code(R._items.reduce((y0,v0)=>{if(v0 instanceof Y.Name)v0=O0(v0);if(v0 instanceof Y._Code)y0.push(...v0._items);else y0.push(v0);return y0},[]));function O0(y0){let v0=e[y0.str];if(v0===void 0||o[y0.str]!==1)return y0;return delete o[y0.str],v0}function T0(y0){return y0 instanceof Y._Code&&y0._items.some((v0)=>v0 instanceof Y.Name&&o[v0.str]===1&&e[v0.str]!==void 0)}}function z0(R,o){for(let e in o)R[e]=(R[e]||0)-(o[e]||0)}function k(R){return typeof R=="boolean"||typeof R=="number"||R===null?!R:Y._`!${Y0(R)}`}$.not=k;let d=p($.operators.AND);function a(...R){return R.reduce(d)}$.and=a;let $0=p($.operators.OR);function y(...R){return R.reduce($0)}$.or=y;function p(R){return(o,e)=>o===Y.nil?e:e===Y.nil?o:Y._`${Y0(o)} ${R} ${Y0(e)}`}function Y0(R){return R instanceof Y.Name?R:Y._`(${R})`}}),v1=E0(( Line truncated
|| (${C} == "string" && ${A} && ${A} == +${A})`).assign(b,I._`+${A}`);return;case"integer":T.elseIf(I._`${C} === "boolean" || ${A} === null
|| (${C} === "string" && ${A} && ${A} == +${A} && !(${A} % 1))`).assign(b,I._`+${A}`);return;case"boolean":T.elseIf(I._`${A} === "false" || ${A} === 0 || ${A} === null`).assign(b,!1).elseIf(I._`${A} === "true" || ${A} === 1`).assign(b,!0);return;case"null":T.elseIf(I._`${A} === "" || ${A} === 0 || ${A} === false`),T.assign(b,null);return;case"array":T.elseIf(I._`${C} === "string" || ${C} === "number"
|| ${C} === "boolean" || ${A} === null`).assign(b,I._`[${A}]`)}}}function q({gen:O,parentData:D,parentDataProperty:P},T){O.if(I._`${D} !== undefined`,()=>O.assign(I._`${D}[${P}]`,T))}function V(O,D,P,T=J.Correct){let A=T===J.Correct?I.operators.EQ:I.operators.NEQ,j;switch(O){case"null":return I._`${D} ${A} null`;case"array":j=I._`Array.isArray(${D})`;break;case"object":j=I._`${D} && typeof ${D} == "object" && !Array.isArray(${D})`;break;case"integer":j=C(I._`!(${D} % 1) && !isNaN(${D})`);break;case"number":j=C();break;default:return I._`typeof ${D} ${A} ${O}`}return T===J.Correct?j:(0,I.not)(j);function C(b=I.nil){return(0,I.and)(I._`typeof ${D} == "number"`,b,P?I._`isFinite(${D})`:I.nil)}}$.checkDataType=V;function w(O,D,P,T){if(O.length===1)return V(O[0],D,P,T);let A,j=(0,Q.toHash)(O);if(j.array&&j.object){let C=I._`typeof ${D} != "object"`;A=j.null?C:I._`!${D} || ${C}`,delete j.null,delete j.array,delete j.object}else A=I.nil;if(j.number)delete j.integer;for(let C in j)A=(0,I.and)(A,V(C,D,P,T));return A}$.checkDataTypes=w;let M={message:({schema:O})=>`must be ${O}`,params:({schema:O,schemaValue:D})=>typeof O=="string"?I._`{type: ${O}}`:I._`{type: ${D}}`};function F(O){let D=N(O);(0,z.reportError)(D,M)}$.reportTypeError=F;function N(O){let{gen:D,data:P,schema:T}=O,A=(0,Q.schemaRefOrVal)(O,T,"type");return{gen:D,keyword:"type",data:P,schema:T.type,schemaCode:A,schemaValue:A,parentSchema:T,params:{},it:O}}}),mb0=E0(($)=>{Object.defineProperty($,"__esModule",{value:!0}),$.assignDefaults=void 0;let Y=F1(),U=v1();function z(Q,J){let{properties:K,items:G}=Q.schema;if(J==="object"&&K)for(let H in K)I(Q,H,K[H].default);else if(J==="array"&&Array.isArray(G))G.forEach((H,W)=>I(Q,W,H.default))}$.assignDefaults=z;function I(Q,J,K){let{gen:G,compositeRule:H,data:W,opts:X}=Q;if(K===void 0)return;let Z=Y._`${W}${(0,Y.getProperty)(J)}`;if(H){(0,U.checkStrictMode)(Q,`default is ignored for: ${Z}`);return}let q=Y._`${Z} === undefined`;if(X.useDefaults==="empty")q=Y._`${q} || ${Z} === null || ${Z} === ""`;G.if(q,Y._`${Z} = ${(0,Y.stringify)(K)}`)}}),G5=E0(($)=>{Object.defineProperty($,"__esModule",{value:!0}),$.validateUnion=$.validateArray=$.usePattern=$.callValidateCode=$.schemaProperties=$.allSchemaProperties=$.noPropertyInData=$.propertyInData=$.isOwnProperty=$.hasPropFunc=$.reportMissingProp=$.checkMissingProp=$.checkReportMissingProp=void 0;let Y=F1(),U=v1(),z=K5(),I=v1();function Q(O,D){let{gen:P,data:T,it:A}=O;P.if(X(P,T,D,A.opts.ownProperties),()=>{O.setParams({missingProperty:Y._`${D}`},!0),O.error()})}$.checkReportMissingProp=Q;function J({gen:O,data:D,it:{opts:P}},T,A){return(0,Y.or)(...T.map((j)=>(0,Y.and)(X(O,D,j,P.ownProperties),Y._`${A} = ${j}`)))}$.checkMissingProp=J;function K(O,D){O.setParams({missingProperty:D},!0),O.error()}$.reportMissingProp=K;function G(O){return O.scopeValue("func",{ref:Object.prototype.hasOwnProperty,code:Y._`Object.prototype.hasOwnProperty`})}$.hasPropFunc=G;function H(O,D,P){return Y._`${G(O)}.call(${D}, ${P})`}$.isOwnProperty=H;function W(O,D,P,T){let A=Y._`${D}${(0,Y.getProperty)(P)} !== undefined`;return T?Y._`${A} && ${H(O,D,P)}`:A}$.propertyInData=W;function X(O,D,P,T){let A=Y._`${D}${(0,Y.getProperty)(P)} === undefined`;return T?(0,Y.or)(A,(0,Y.not)(H(O,D,P))):A}$.noPropertyInData=X;function Z(O){return O?Object.keys(O).filter((D)=>D!=="__proto__"):[]}$.allSchemaProperties=Z;function q(O,D){return Z(D).filter((P)=>!(0,U.alwaysValidSchema)(O,D[P]))}$.schemaProperties=q;function V({schemaCode:O,data:D,it:{gen:P,topSchemaRef:T,schemaPath:A,errorPath:j},it:C},b,x,g){let i=g?Y._`${O}, ${D}, ${T}${A}`:D,c=[[z.default.instancePath,(0,Y.strConcat)(z.default.instancePath,j)],[z.default.parentData,C.parentData],[z.default.parentDataProperty,C.parentDataProperty],[z.default.rootData,z.default.rootData]];if(C.opts.dynamicRef)c.push([z.default.dynamicAnchors,z.default.dynamicAnchors]);let z0=Y._`${i}, ${P.object(...c)}`;return x!==Y.nil?Y._`${b}.call(${x}, ${z0})`:Y._`${b}(${z0})`}$.callValidateCode=V;let w=Y._`new RegExp`;function M({gen:O,it:{opts:D}},P){let T=D.unicodeRegExp?"u":"",{regExp:A}=D.code,j=A(P,T);return O.scopeValue("pattern",{key:j.toString(),ref:j,code:Y._`${A.code==="new RegExp"?w:(0,I.useFunc)(O,A)}(${P}, ${T})`})}$.usePattern=M;function F(O){let{gen:D,data:P,keyword:T,it:A}=O,j=D.name("valid");if(A.allErrors){let b=D.let("valid",!0);return C(()=>D.assign(b,!1)),b}return D.var(j,!0),C(()=>D.break()),j;function C(b){let x=D.const("len",Y._`${P}.length`);D.forRange("i",0,x,(g)=>{O.subschema({keyword:T,dataProp:g,dataPropType:U.Type.Num},j),D.if((0,Y.not)(j),b)})}}$.validateArray=F;function N(O){let{gen:D,schema:P,keyword:T,it:A}=O;if(!Array.isArray(P))throw Error("ajv implementation error");if(P.some((b)=>(0,U.alwaysValidSchema)(A,b))&&!A.opts.unevaluated)return;let j=D.let("valid",!1),C=D.name("_valid");D.block(()=>P.forEach((b,x)=>{let g=O.subschema({keyword:T,schemaProp:x,compositeRule:!0},C);if(D.assign(j,Y._`${j} || ${C}`),!O.mergeValidEvaluated(g,C) Line truncated
*/Ci0=j0(($)=>{var Y=/; *([!#$%&'*+.^_`|~0-9A-Za-z-]+) *= *("(?:[\u000b\u0020\u0021\u0023-\u005b\u005d-\u007e\u0080-\u00ff]|\\[\u000b\u0020-\u00ff])*"|[!#$%&'*+.^_`|~0-9A-Za-z-]+) */g,U=/\\([\u000b\u0020-\u00ff])/g,I=/^[!#$%&'*+.^_`|~0-9A-Za-z-]+\/[!#$%&'*+.^_`|~0-9A-Za-z-]+$/;$.parse=Q;function Q(z){if(!z)throw TypeError("argument string is required");var G=typeof z==="object"?J(z):z;if(typeof G!=="string")throw TypeError("argument string is required to be a string");var H=G.indexOf(";"),W=H!==-1?G.slice(0,H).trim():G.trim();if(!I.test(W))throw TypeError("invalid media type");var X=new K(W.toLowerCase());if(H!==-1){var Z,q,V;Y.lastIndex=H;while(q=Y.exec(G)){if(q.index!==H)throw TypeError("invalid parameter format");if(H+=q[0].length,Z=q[1].toLowerCase(),V=q[2],V.charCodeAt(0)===34){if(V=V.slice(1,-1),V.indexOf("\\")!==-1)V=V.replace(U,"$1")}X.parameters[Z]=V}if(H!==G.length)throw TypeError("invalid parameter format")}return X}function J(z){var G;if(typeof z.getHeader==="function")G=z.getHeader("content-type");else if(typeof z.headers==="object")G=z.headers&&z.headers["content-type"];if(typeof G!=="string")throw TypeError("content-type header is missing from object");return G}function K(z){this.parameters=Object.create(null),this.type=z}}),ti1=GV(Ci0(),1);Ri0=/^[A-Za-z0-9._-]{1,128}$/});function xh($){let Y=new $({strict:!1,validateFormats:!0,validateSchema:!1,allErrors:!0});return sc0(Y),Y}var sw,ue,F1,v1,X5,tw,yi0,be,ie,aw,ki0,Z5,xi0,fi0,ce,ui0,ew,iQ,DH,cQ,$M,bi0,ne,ii0,ci0,ni0,fh,di0,uh,de,pi0,mi0,li0,oi0,ri0,si0,ai0,ti0,bh,ei0,$c0,Yc0,pe,me,le,Uc0,Ic0,Qc0,ih,Jc0,oe,Kc0,zc0,Gc0,Hc0,Wc0,Xc0,Zc0,qc0,re,Vc0,se,ae,te,Lc0,ch,Fc0,ee,$00,Y00,wc0,Mc0,U00,Oc0,Nc0,Dc0,I00,Bc0,Ac0,Q00,Pc0,Tc0,Ec0,jc0,Cc0,Rc0,_c0,vc0,Sc0,hc0,gc0,yc0,kc0,xc0,fc0,uc0,bc0,ic0,cc0,nc0,dc0,pc0,mc0,J00,lc0,oc0,rc0,sc0,YM=class{_ajv;_ajvDraft7;_ajv2019;_userAjv;constructor($){this._userAjv=$!==void 0,this._ajv=$}get ajv(){return this._ajv??=xh(oc0.Ajv2020)}_engineFor($){if(this._userAjv)return this.ajv;let Y=fr($,"pass a pre-configured Ajv instance to AjvJsonSchemaValidator(ajv) to validate other dialects.");if(Y==="2020-12")return this.ajv;if(Y==="2019-09")return this._ajv2019??=xh(lc0.Ajv2019);return this._ajvDraft7??=xh(J00.Ajv)}getValidator($){let Y=this._engineFor($),U="$id"in $&&typeof $.$id==="string"?Y.getSchema($.$id)??Y.compile($):Y.compile($);return(I)=>{return U(I)?{valid:!0,data:I,errorMessage:void 0}:{valid:!1,data:void 0,errorMessage:Y.errorsText(U.errors)}}}},Wc1;var K00=m(()=>{jE();CE();sw=j0(($)=>{Object.defineProperty($,"__esModule",{value:!0}),$.regexpCode=$.getEsmExportName=$.getProperty=$.safeStringify=$.stringify=$.strConcat=$.addCodeArg=$.str=$._=$.nil=$._Code=$.Name=$.IDENTIFIER=$._CodeOrName=void 0;var Y=class{};$._CodeOrName=Y,$.IDENTIFIER=/^[a-z$_][a-z$_0-9]*$/i;var U=class extends Y{constructor(F){super();if(!$.IDENTIFIER.test(F))throw Error("CodeGen: name must be a valid identifier");this.str=F}toString(){return this.str}emptyStr(){return!1}get names(){return{[this.str]:1}}};$.Name=U;var I=class extends Y{constructor(F){super();this._items=typeof F==="string"?[F]:F}toString(){return this.str}emptyStr(){if(this._items.length>1)return!1;let F=this._items[0];return F===""||F==='""'}get str(){var F;return(F=this._str)!==null&&F!==void 0?F:this._str=this._items.reduce((N,O)=>`${N}${O}`,"")}get names(){var F;return(F=this._names)!==null&&F!==void 0?F:this._names=this._items.reduce((N,O)=>{if(O instanceof U)N[O.str]=(N[O.str]||0)+1;return N},{})}};$._Code=I,$.nil=new I("");function Q(F,...N){let O=[F[0]],D=0;while(D<N.length)z(O,N[D]),O.push(F[++D]);return new I(O)}$._=Q;let J=new I("+");function K(F,...N){let O=[q(F[0])],D=0;while(D<N.length)O.push(J),z(O,N[D]),O.push(J,q(F[++D]));return G(O),new I(O)}$.str=K;function z(F,N){if(N instanceof I)F.push(...N._items);else if(N instanceof U)F.push(N);else F.push(X(N))}$.addCodeArg=z;function G(F){let N=1;while(N<F.length-1){if(F[N]===J){let O=H(F[N-1],F[N+1]);if(O!==void 0){F.splice(N-1,3,O);continue}F[N++]="+"}N++}}function H(F,N){if(N==='""')return F;if(F==='""')return N;if(typeof F=="string"){if(N instanceof U||F[F.length-1]!=='"')return;if(typeof N!="string")return`${F.slice(0,-1)}${N}"`;if(N[0]==='"')return F.slice(0,-1)+N.slice(1);return}if(typeof N=="string"&&N[0]==='"'&&!(F instanceof U))return`"${F}${N.slice(1)}`}function W(F,N){return N.emptyStr()?F:F.emptyStr()?N:K`${F}${N}`}$.strConcat=W;function X(F){return typeof F=="number"||typeof F=="boolean"||F===null?F:q(Array.isArray(F)?F.join(","):F)}function Z(F){return new I(q(F))}$.stringify=Z;function q(F){return JSON.stringify(F).replace(/\u2028/g,"\\u2028").replace(/\u2029/g,"\\u2029")}$.safeStringify=q;function V(F){return typeof F=="string"&&$.IDENTIFIER.test(F)?new I(`.${F}`):Q`[${F}]`}$.getProperty=V;function w(F){if(typeof F=="string"&&$.IDENTIFIER.test(F))return new I(`${F}`);throw Error(`CodeGen: invalid export name: ${F}, use explicit $id name mapping`)}$.getEsmExportName=w;function M(F){return new I(F.Line truncated
`:""},this._extScope=R,this._scope=new U.Scope({parent:R}),this._nodes=[new w]}toString(){return this._root.render(this.opts)}name(R){return this._scope.name(R)}scopeName(R){return this._extScope.name(R)}scopeValue(R,o){let e=this._extScope.value(R,o);return(this._values[e.prefix]||(this._values[e.prefix]=new Set)).add(e),e}getScopeValue(R,o){return this._extScope.getValue(R,o)}scopeRefs(R){return this._extScope.scopeRefs(R,this._values)}scopeCode(){return this._extScope.scopeCode(this._values)}_def(R,o,e,O0){let T0=this._scope.toName(o);if(e!==void 0&&O0)this._constants[T0.str]=e;return this._leafNode(new K(R,T0,e)),T0}const(R,o,e){return this._def(U.varKinds.const,R,o,e)}let(R,o,e){return this._def(U.varKinds.let,R,o,e)}var(R,o,e){return this._def(U.varKinds.var,R,o,e)}assign(R,o,e){return this._leafNode(new z(R,o,e))}add(R,o){return this._leafNode(new G(R,$.operators.ADD,o))}code(R){if(typeof R=="function")R();else if(R!==Y.nil)this._leafNode(new Z(R));return this}object(...R){let o=["{"];for(let[e,O0]of R){if(o.length>1)o.push(",");if(o.push(e),e!==O0||this.opts.es5)o.push(":"),(0,Y.addCodeArg)(o,O0)}return o.push("}"),new Y._Code(o)}if(R,o,e){if(this._blockNode(new F(R)),o&&e)this.code(o).else().code(e).endIf();else if(o)this.code(o).endIf();else if(e)throw Error('CodeGen: "else" body without "then" body');return this}elseIf(R){return this._elseNode(new F(R))}else(){return this._elseNode(new M)}endIf(){return this._endBlockNode(F,M)}_for(R,o){if(this._blockNode(R),o)this.code(o).endFor();return this}for(R,o){return this._for(new O(R),o)}forRange(R,o,e,O0,T0=this.opts.es5?U.varKinds.var:U.varKinds.let){let y0=this._scope.toName(R);return this._for(new D(T0,y0,o,e),()=>O0(y0))}forOf(R,o,e,O0=U.varKinds.const){let T0=this._scope.toName(R);if(this.opts.es5){let y0=o instanceof Y.Name?o:this.var("_arr",o);return this.forRange("_i",0,Y._`${y0}.length`,(v0)=>{this.var(T0,Y._`${y0}[${v0}]`),e(T0)})}return this._for(new P("of",O0,T0,o),()=>e(T0))}forIn(R,o,e,O0=this.opts.es5?U.varKinds.var:U.varKinds.const){if(this.opts.ownProperties)return this.forOf(R,Y._`Object.keys(${o})`,e);let T0=this._scope.toName(R);return this._for(new P("in",O0,T0,o),()=>e(T0))}endFor(){return this._endBlockNode(N)}label(R){return this._leafNode(new H(R))}break(R){return this._leafNode(new W(R))}return(R){let o=new B;if(this._blockNode(o),this.code(R),o.nodes.length!==1)throw Error('CodeGen: "return" should have one node');return this._endBlockNode(B)}try(R,o,e){if(!o&&!e)throw Error('CodeGen: "try" without "catch" and "finally"');let O0=new E;if(this._blockNode(O0),this.code(R),o){let T0=this.name("e");this._currNode=O0.catch=new C(T0),o(T0)}if(e)this._currNode=O0.finally=new b,this.code(e);return this._endBlockNode(C,b)}throw(R){return this._leafNode(new X(R))}block(R,o){if(this._blockStarts.push(this._nodes.length),R)this.code(R).endBlock(o);return this}endBlock(R){let o=this._blockStarts.pop();if(o===void 0)throw Error("CodeGen: not in self-balancing block");let e=this._nodes.length-o;if(e<0||R!==void 0&&e!==R)throw Error(`CodeGen: wrong number of nodes: ${e} vs ${R} expected`);return this._nodes.length=o,this}func(R,o=Y.nil,e,O0){if(this._blockNode(new T(R,o,e)),O0)this.code(O0).endFunc();return this}endFunc(){return this._endBlockNode(T)}optimize(R=1){while(R-- >0)this._root.optimizeNodes(),this._root.optimizeNames(this._root.names,this._constants)}_leafNode(R){return this._currNode.nodes.push(R),this}_blockNode(R){this._currNode.nodes.push(R),this._nodes.push(R)}_endBlockNode(R,o){let e=this._currNode;if(e instanceof R||o&&e instanceof o)return this._nodes.pop(),this;throw Error(`CodeGen: not in block "${o?`${R.kind}/${o.kind}`:R.kind}"`)}_elseNode(R){let o=this._currNode;if(!(o instanceof F))throw Error('CodeGen: "else" without "if"');return this._currNode=o.else=R,this}get _root(){return this._nodes[0]}get _currNode(){let R=this._nodes;return R[R.length-1]}set _currNode(R){let o=this._nodes;o[o.length-1]=R}};$.CodeGen=x;function g(R,o){for(let e in o)R[e]=(R[e]||0)+(o[e]||0);return R}function i(R,o){return o instanceof Y._CodeOrName?g(R,o.names):R}function c(R,o,e){if(R instanceof Y.Name)return O0(R);if(!T0(R))return R;return new Y._Code(R._items.reduce((y0,v0)=>{if(v0 instanceof Y.Name)v0=O0(v0);if(v0 instanceof Y._Code)y0.push(...v0._items);else y0.push(v0);return y0},[]));function O0(y0){let v0=e[y0.str];if(v0===void 0||o[y0.str]!==1)return y0;return delete o[y0.str],v0}function T0(y0){return y0 instanceof Y._Code&&y0._items.some((v0)=>v0 instanceof Y.Name&&o[v0.str]===1&&e[v0.str]!==void 0)}}function I0(R,o){for(let e in o)R[e]=(R[e]||0)-(o[e]||0)}function k(R){return typeof R=="boolean"||typeof R=="number"||R===null?!R:Y._`!${Y0(R)}`}$.not=k;let p=d($.operators.AND);function a(...R){return R.reduce(p)}$.and=a;let $0=d($.operators.OR);function y(...R){return R.reduce($0)}$.or=y;function d(R){return(o,e)=>o===Y.nil?e:e===Y.nil?o:Y._`${Y0(o)} ${R} ${Y0(e)}`}function Y0(R){return R instanceof Y.Name?R:Y._`(${R})`}}),v1=j0(( Line truncated
|| (${C} == "string" && ${B} && ${B} == +${B})`).assign(b,Q._`+${B}`);return;case"integer":T.elseIf(Q._`${C} === "boolean" || ${B} === null
|| (${C} === "string" && ${B} && ${B} == +${B} && !(${B} % 1))`).assign(b,Q._`+${B}`);return;case"boolean":T.elseIf(Q._`${B} === "false" || ${B} === 0 || ${B} === null`).assign(b,!1).elseIf(Q._`${B} === "true" || ${B} === 1`).assign(b,!0);return;case"null":T.elseIf(Q._`${B} === "" || ${B} === 0 || ${B} === false`),T.assign(b,null);return;case"array":T.elseIf(Q._`${C} === "string" || ${C} === "number"
|| ${C} === "boolean" || ${B} === null`).assign(b,Q._`[${B}]`)}}}function q({gen:O,parentData:D,parentDataProperty:P},T){O.if(Q._`${D} !== undefined`,()=>O.assign(Q._`${D}[${P}]`,T))}function V(O,D,P,T=K.Correct){let B=T===K.Correct?Q.operators.EQ:Q.operators.NEQ,E;switch(O){case"null":return Q._`${D} ${B} null`;case"array":E=Q._`Array.isArray(${D})`;break;case"object":E=Q._`${D} && typeof ${D} == "object" && !Array.isArray(${D})`;break;case"integer":E=C(Q._`!(${D} % 1) && !isNaN(${D})`);break;case"number":E=C();break;default:return Q._`typeof ${D} ${B} ${O}`}return T===K.Correct?E:(0,Q.not)(E);function C(b=Q.nil){return(0,Q.and)(Q._`typeof ${D} == "number"`,b,P?Q._`isFinite(${D})`:Q.nil)}}$.checkDataType=V;function w(O,D,P,T){if(O.length===1)return V(O[0],D,P,T);let B,E=(0,J.toHash)(O);if(E.array&&E.object){let C=Q._`typeof ${D} != "object"`;B=E.null?C:Q._`!${D} || ${C}`,delete E.null,delete E.array,delete E.object}else B=Q.nil;if(E.number)delete E.integer;for(let C in E)B=(0,Q.and)(B,V(C,D,P,T));return B}$.checkDataTypes=w;let M={message:({schema:O})=>`must be ${O}`,params:({schema:O,schemaValue:D})=>typeof O=="string"?Q._`{type: ${O}}`:Q._`{type: ${D}}`};function F(O){let D=N(O);(0,I.reportError)(D,M)}$.reportTypeError=F;function N(O){let{gen:D,data:P,schema:T}=O,B=(0,J.schemaRefOrVal)(O,T,"type");return{gen:D,keyword:"type",data:P,schema:T.type,schemaCode:B,schemaValue:B,parentSchema:T,params:{},it:O}}}),ki0=j0(($)=>{Object.defineProperty($,"__esModule",{value:!0}),$.assignDefaults=void 0;let Y=F1(),U=v1();function I(J,K){let{properties:z,items:G}=J.schema;if(K==="object"&&z)for(let H in z)Q(J,H,z[H].default);else if(K==="array"&&Array.isArray(G))G.forEach((H,W)=>Q(J,W,H.default))}$.assignDefaults=I;function Q(J,K,z){let{gen:G,compositeRule:H,data:W,opts:X}=J;if(z===void 0)return;let Z=Y._`${W}${(0,Y.getProperty)(K)}`;if(H){(0,U.checkStrictMode)(J,`default is ignored for: ${Z}`);return}let q=Y._`${Z} === undefined`;if(X.useDefaults==="empty")q=Y._`${q} || ${Z} === null || ${Z} === ""`;G.if(q,Y._`${Z} = ${(0,Y.stringify)(z)}`)}}),Z5=j0(($)=>{Object.defineProperty($,"__esModule",{value:!0}),$.validateUnion=$.validateArray=$.usePattern=$.callValidateCode=$.schemaProperties=$.allSchemaProperties=$.noPropertyInData=$.propertyInData=$.isOwnProperty=$.hasPropFunc=$.reportMissingProp=$.checkMissingProp=$.checkReportMissingProp=void 0;let Y=F1(),U=v1(),I=X5(),Q=v1();function J(O,D){let{gen:P,data:T,it:B}=O;P.if(X(P,T,D,B.opts.ownProperties),()=>{O.setParams({missingProperty:Y._`${D}`},!0),O.error()})}$.checkReportMissingProp=J;function K({gen:O,data:D,it:{opts:P}},T,B){return(0,Y.or)(...T.map((E)=>(0,Y.and)(X(O,D,E,P.ownProperties),Y._`${B} = ${E}`)))}$.checkMissingProp=K;function z(O,D){O.setParams({missingProperty:D},!0),O.error()}$.reportMissingProp=z;function G(O){return O.scopeValue("func",{ref:Object.prototype.hasOwnProperty,code:Y._`Object.prototype.hasOwnProperty`})}$.hasPropFunc=G;function H(O,D,P){return Y._`${G(O)}.call(${D}, ${P})`}$.isOwnProperty=H;function W(O,D,P,T){let B=Y._`${D}${(0,Y.getProperty)(P)} !== undefined`;return T?Y._`${B} && ${H(O,D,P)}`:B}$.propertyInData=W;function X(O,D,P,T){let B=Y._`${D}${(0,Y.getProperty)(P)} === undefined`;return T?(0,Y.or)(B,(0,Y.not)(H(O,D,P))):B}$.noPropertyInData=X;function Z(O){return O?Object.keys(O).filter((D)=>D!=="__proto__"):[]}$.allSchemaProperties=Z;function q(O,D){return Z(D).filter((P)=>!(0,U.alwaysValidSchema)(O,D[P]))}$.schemaProperties=q;function V({schemaCode:O,data:D,it:{gen:P,topSchemaRef:T,schemaPath:B,errorPath:E},it:C},b,x,g){let i=g?Y._`${O}, ${D}, ${T}${B}`:D,c=[[I.default.instancePath,(0,Y.strConcat)(I.default.instancePath,E)],[I.default.parentData,C.parentData],[I.default.parentDataProperty,C.parentDataProperty],[I.default.rootData,I.default.rootData]];if(C.opts.dynamicRef)c.push([I.default.dynamicAnchors,I.default.dynamicAnchors]);let I0=Y._`${i}, ${P.object(...c)}`;return x!==Y.nil?Y._`${b}.call(${x}, ${I0})`:Y._`${b}(${I0})`}$.callValidateCode=V;let w=Y._`new RegExp`;function M({gen:O,it:{opts:D}},P){let T=D.unicodeRegExp?"u":"",{regExp:B}=D.code,E=B(P,T);return O.scopeValue("pattern",{key:E.toString(),ref:E,code:Y._`${B.code==="new RegExp"?w:(0,Q.useFunc)(O,B)}(${P}, ${T})`})}$.usePattern=M;function F(O){let{gen:D,data:P,keyword:T,it:B}=O,E=D.name("valid");if(B.allErrors){let b=D.let("valid",!0);return C(()=>D.assign(b,!1)),b}return D.var(E,!0),C(()=>D.break()),E;function C(b){let x=D.const("len",Y._`${P}.length`);D.forRange("i",0,x,(g)=>{O.subschema({keyword:T,dataProp:g,dataPropType:U.Type.Num},E),D.if((0,Y.not)(E),b)})}}$.validateArray=F;function N(O){let{gen:D,schema:P,keyword:T,it:B}=O;if(!Array.isArray(P))throw Error("ajv implementation error");if(P.some((b)=>(0,U.alwaysValidSchema)(B,b))&&!B.opts.unevaluated)return;let E=D.let("valid",!1),C=D.name("_valid");D.block(()=>P.forEach((b,x)=>{let g=O.subschema({keyword:T,schemaProp:x,compositeRule:!0},C);if(D.assign(E,Y._`${E} || ${C}`),!O.mergeValidEvaluated(g,C) Line truncated
missingProperty: ${X},
depsCount: ${H},
deps: ${W}}`};let I={keyword:"dependencies",type:"object",schemaType:"object",error:$.error,code(G){let[H,W]=Q(G);J(G,H),K(G,W)}};function Q({schema:G}){let H={},W={};for(let X in G){if(X==="__proto__")continue;let Z=Array.isArray(G[X])?H:W;Z[X]=G[X]}return[H,W]}function J(G,H=G.schema){let{gen:W,data:X,it:Z}=G;if(Object.keys(H).length===0)return;let q=W.let("missing");for(let V in H){let w=H[V];if(w.length===0)continue;let M=(0,z.propertyInData)(W,X,V,Z.opts.ownProperties);if(G.setParams({property:V,depsCount:w.length,deps:w.join(", ")}),Z.allErrors)W.if(M,()=>{for(let F of w)(0,z.checkReportMissingProp)(G,F)});else W.if(Y._`${M} && (${(0,z.checkMissingProp)(G,w,q)})`),(0,z.reportMissingProp)(G,q),W.else()}}$.validatePropertyDeps=J;function K(G,H=G.schema){let{gen:W,data:X,keyword:Z,it:q}=G,V=W.name("valid");for(let w in H){if((0,U.alwaysValidSchema)(q,H[w]))continue;W.if((0,z.propertyInData)(W,X,w,q.opts.ownProperties),()=>{let M=G.subschema({keyword:Z,schemaProp:w},V);G.mergeValidEvaluated(M,V)},()=>W.var(V,!0)),G.ok(V)}}$.validateSchemaDeps=K,$.default=I}),Li0=E0(($)=>{Object.defineProperty($,"__esModule",{value:!0});let Y=F1(),U=v1(),z={keyword:"propertyNames",type:"object",schemaType:["object","boolean"],error:{message:"property name must be valid",params:({params:I})=>Y._`{propertyName: ${I.propertyName}}`},code(I){let{gen:Q,schema:J,data:K,it:G}=I;if((0,U.alwaysValidSchema)(G,J))return;let H=Q.name("valid");Q.forIn("key",K,(W)=>{I.setParams({propertyName:W}),I.subschema({keyword:"propertyNames",data:W,dataTypes:["string"],propertyName:W,compositeRule:!0},H),Q.if((0,Y.not)(H),()=>{if(I.error(!0),!G.allErrors)Q.break()})}),I.ok(H)}};$.default=z}),Se=E0(($)=>{Object.defineProperty($,"__esModule",{value:!0});let Y=G5(),U=F1(),z=K5(),I=v1(),Q={keyword:"additionalProperties",type:["object"],schemaType:["boolean","object"],allowUndefined:!0,trackErrors:!0,error:{message:"must NOT have additional properties",params:({params:J})=>U._`{additionalProperty: ${J.additionalProperty}}`},code(J){let{gen:K,schema:G,parentSchema:H,data:W,errsCount:X,it:Z}=J;if(!X)throw Error("ajv implementation error");let{allErrors:q,opts:V}=Z;if(Z.props=!0,V.removeAdditional!=="all"&&(0,I.alwaysValidSchema)(Z,G))return;let w=(0,Y.allSchemaProperties)(H.properties),M=(0,Y.allSchemaProperties)(H.patternProperties);F(),J.ok(U._`${X} === ${z.default.errors}`);function F(){K.forIn("key",W,(T)=>{if(!w.length&&!M.length)D(T);else K.if(N(T),()=>D(T))})}function N(T){let A;if(w.length>8){let j=(0,I.schemaRefOrVal)(Z,H.properties,"properties");A=(0,Y.isOwnProperty)(K,j,T)}else if(w.length)A=(0,U.or)(...w.map((j)=>U._`${T} === ${j}`));else A=U.nil;if(M.length)A=(0,U.or)(A,...M.map((j)=>U._`${(0,Y.usePattern)(J,j)}.test(${T})`));return(0,U.not)(A)}function O(T){K.code(U._`delete ${W}[${T}]`)}function D(T){if(V.removeAdditional==="all"||V.removeAdditional&&G===!1){O(T);return}if(G===!1){if(J.setParams({additionalProperty:T}),J.error(),!q)K.break();return}if(typeof G=="object"&&!(0,I.alwaysValidSchema)(Z,G)){let A=K.name("valid");if(V.removeAdditional==="failing")P(T,A,!1),K.if((0,U.not)(A),()=>{J.reset(),O(T)});else if(P(T,A),!q)K.if((0,U.not)(A),()=>K.break())}}function P(T,A,j){let C={keyword:"additionalProperties",dataProp:T,dataPropType:I.Type.Str};if(j===!1)Object.assign(C,{compositeRule:!0,createErrors:!1,allErrors:!1});J.subschema(C,A)}}};$.default=Q}),Fi0=E0(($)=>{Object.defineProperty($,"__esModule",{value:!0});let Y=bI(),U=G5(),z=v1(),I=Se(),Q={keyword:"properties",type:"object",schemaType:"object",code(J){let{gen:K,schema:G,parentSchema:H,data:W,it:X}=J;if(X.opts.removeAdditional==="all"&&H.additionalProperties===void 0)I.default.code(new Y.KeywordCxt(X,I.default,"additionalProperties"));let Z=(0,U.allSchemaProperties)(G);for(let F of Z)X.definedProperties.add(F);if(X.opts.unevaluated&&Z.length&&X.props!==!0)X.props=z.mergeEvaluated.props(K,(0,z.toHash)(Z),X.props);let q=Z.filter((F)=>!(0,z.alwaysValidSchema)(X,G[F]));if(q.length===0)return;let V=K.name("valid");for(let F of q){if(w(F))M(F);else{if(K.if((0,U.propertyInData)(K,W,F,X.opts.ownProperties)),M(F),!X.allErrors)K.else().var(V,!0);K.endIf()}J.it.definedProperties.add(F),J.ok(V)}function w(F){return X.opts.useDefaults&&!X.compositeRule&&G[F].default!==void 0}function M(F){J.subschema({keyword:"properties",schemaProp:F,dataProp:F},V)}}};$.default=Q}),wi0=E0(($)=>{Object.defineProperty($,"__esModule",{value:!0});let Y=G5(),U=F1(),z=v1(),I=v1(),Q={keyword:"patternProperties",type:"object",schemaType:"object",code(J){let{gen:K,schema:G,data:H,parentSchema:W,it:X}=J,{opts:Z}=X,q=(0,Y.allSchemaProperties)(G),V=q.filter((P)=>(0,z.alwaysValidSchema)(X,G[P]));if(q.length===0||V.length===q.length&&(!X.opts.unevaluated||X.props===!0))return;let w=Z.strictSchema&&!Z.allowMatchingProperties&&W.properties,M=K.name("valid");if(X.props!==!0&&!(X.props instanceof U.Name))X.props=(0,I.evaluatedPropsToName)(K,X.props);let{props:F}=X;N();function N(){for(let P of q){if(w)O(P);if(X.allErrors) Line truncated
\x00`,x+=D4(j,2),x+=K.magic,x+=D4(M,2),x+=D4(F,2),x+=D4(A.crc32,4),x+=D4(A.compressedSize,4),x+=D4(A.uncompressedSize,4),x+=D4(H.length,2),x+=D4(N.length,2);var g=SO.LOCAL_FILE_HEADER+x+H+N,i=SO.CENTRAL_FILE_HEADER+D4(b,2)+x+D4(Z.length,2)+"\x00\x00\x00\x00"+D4(C,4)+D4(z,4)+H+N+Z;return{fileRecord:g,dirRecord:i}},Os0=function($,Y,U,z,I){var Q="",J=DQ.transformTo("string",I(z));return Q=SO.CENTRAL_DIRECTORY_END+"\x00\x00\x00\x00"+D4($,2)+D4($,2)+D4(Y,4)+D4(U,4)+D4(J.length,2)+J,Q},Ns0=function($){var Y="";return Y=SO.DATA_DESCRIPTOR+D4($.crc32,4)+D4($.compressedSize,4)+D4($.uncompressedSize,4),Y};function L5($,Y,U,z){AQ.call(this,"ZipFileWorker"),this.bytesWritten=0,this.zipComment=Y,this.zipPlatform=U,this.encodeFileName=z,this.streamFiles=$,this.accumulate=!1,this.contentBuffer=[],this.dirRecords=[],this.currentSourceOffset=0,this.entriesCount=0,this.currentFile=null,this._sources=[]}DQ.inherits(L5,AQ);L5.prototype.push=function($){var Y=$.meta.percent||0,U=this.entriesCount,z=this._sources.length;if(this.accumulate)this.contentBuffer.push($);else this.bytesWritten+=$.data.length,AQ.prototype.push.call(this,{data:$.data,meta:{currentFile:this.currentFile,percent:U?(Y+100*(U-z-1))/U:100}})};L5.prototype.openedSource=function($){this.currentSourceOffset=this.bytesWritten,this.currentFile=$.file.name;var Y=this.streamFiles&&!$.file.dir;if(Y){var U=W90($,Y,!1,this.currentSourceOffset,this.zipPlatform,this.encodeFileName);this.push({data:U.fileRecord,meta:{percent:0}})}else this.accumulate=!0};L5.prototype.closedSource=function($){this.accumulate=!1;var Y=this.streamFiles&&!$.file.dir,U=W90($,Y,!0,this.currentSourceOffset,this.zipPlatform,this.encodeFileName);if(this.dirRecords.push(U.dirRecord),Y)this.push({data:Ns0($),meta:{percent:100}});else{this.push({data:U.fileRecord,meta:{percent:0}});while(this.contentBuffer.length)this.push(this.contentBuffer.shift())}this.currentFile=null};L5.prototype.flush=function(){var $=this.bytesWritten;for(var Y=0;Y<this.dirRecords.length;Y++)this.push({data:this.dirRecords[Y],meta:{percent:100}});var U=this.bytesWritten-$,z=Os0(this.dirRecords.length,U,$,this.zipComment,this.encodeFileName);this.push({data:z,meta:{percent:100}})};L5.prototype.prepareNextSource=function(){if(this.previous=this._sources.shift(),this.openedSource(this.previous.streamInfo),this.isPaused)this.previous.pause();else this.previous.resume()};L5.prototype.registerPrevious=function($){this._sources.push($);var Y=this;return $.on("data",function(U){Y.processChunk(U)}),$.on("end",function(){if(Y.closedSource(Y.previous.streamInfo),Y._sources.length)Y.prepareNextSource();else Y.end()}),$.on("error",function(U){Y.error(U)}),this};L5.prototype.resume=function(){if(!AQ.prototype.resume.call(this))return!1;if(!this.previous&&this._sources.length)return this.prepareNextSource(),!0;if(!this.previous&&!this._sources.length&&!this.generatedError)return this.end(),!0};L5.prototype.error=function($){var Y=this._sources;if(!AQ.prototype.error.call(this,$))return!1;for(var U=0;U<Y.length;U++)try{Y[U].error($)}catch(z){}return!0};L5.prototype.lock=function(){AQ.prototype.lock.call(this);var $=this._sources;for(var Y=0;Y<$.length;Y++)$[Y].lock()};X90.exports=L5});var q90=E((Ps0)=>{var Ds0=Xk(),As0=Z90(),Bs0=function($,Y){var U=$||Y,z=Ds0[U];if(!z)throw Error(U+" is not a valid compression method !");return z};Ps0.generateWorker=function($,Y,U){var z=new As0(Y.streamFiles,U,Y.platform,Y.encodeFileName),I=0;try{$.forEach(function(Q,J){I++;var K=Bs0(J.options.compression,Y.compression),G=J.options.compressionOptions||Y.compressionOptions||{},H=J.dir,W=J.date;J._compressWorker(K,G).withStreamInfo("file",{name:Q,dir:H,date:W,comment:J.comment||"",unixPermissions:J.unixPermissions,dosPermissions:J.dosPermissions}).pipe(z)}),z.entriesCount=I}catch(Q){z.error(Q)}return z}});var L90=E((ym1,V90)=>{var js0=n4(),gO=G$();function NW($,Y){gO.call(this,"Nodejs stream input adapter for "+$),this._upstreamEnded=!1,this._bindStream(Y)}js0.inherits(NW,gO);NW.prototype._bindStream=function($){var Y=this;this._stream=$,$.pause(),$.on("data",function(U){Y.push({data:U,meta:{percent:0}})}).on("error",function(U){if(Y.isPaused)this.generatedError=U;else Y.error(U)}).on("end",function(){if(Y.isPaused)Y._upstreamEnded=!0;else Y.end()})};NW.prototype.pause=function(){if(!gO.prototype.pause.call(this))return!1;return this._stream.pause(),!0};NW.prototype.resume=function(){if(!gO.prototype.resume.call(this))return!1;if(this._upstreamEnded)this.end();else this._stream.resume();return!0};V90.exports=NW});var T90=E((km1,P90)=>{var Es0=XQ(),DW=n4(),O90=G$(),Cs0=wy(),N90=My(),F90=LO(),Rs0=w$0(),_s0=q90(),w90=eH(),vs0=L90(),D90=function($,Y,U){var z=DW.getTypeOf(Y),I,Q=DW.extend(U||{},N90);if(Q.date=Q.date||new Date,Q.compression!==null)Q.compression=Q.compression.toUpperCase();if(typeof Q.unixPermissions==="string")Q.unixPermissions=parseInt(Q.unixPermissions,8);if(Q.unixPermissions&&Q.unixPermissions&16384)Q.dir=!0;if(Q.dosPermissions&&Q.dosPermission Line truncated
`)}openNode($,Y){let U=this.tos,z=this._xml;if(U&&this.open)z.push(">");this._stack.push($),z.push("<"),z.push($),ok(z,Y),this.leaf=!0,this.open=!0}addAttribute($,Y){if(!this.open)throw Error("Cannot write attributes to node if it is not open");if(Y!==void 0)L70(this._xml,$,Y)}addAttributes($){if(!this.open)throw Error("Cannot write attributes to node if it is not open");ok(this._xml,$)}writeText($){let Y=this._xml;if(this.open)Y.push(">"),this.open=!1;this.leaf=!1,Y.push(V70.xmlEncode($.toString()))}writeXml($){if(this.open)this._xml.push(">"),this.open=!1;this.leaf=!1,this._xml.push($)}closeNode(){let $=this._stack.pop(),Y=this._xml;if(this.leaf)Y.push("/>");else Y.push("</"),Y.push($),Y.push(">");this.open=!1,this.leaf=!1}leafNode($,Y,U){if(this.openNode($,Y),U!==void 0)this.writeText(U);this.closeNode()}closeAll(){while(this._stack.length)this.closeNode()}addRollback(){return this._rollbacks.push({xml:this._xml.length,stack:this._stack.length,leaf:this.leaf,open:this.open}),this.cursor}commit(){this._rollbacks.pop()}rollback(){let $=this._rollbacks.pop();if(this._xml.length>$.xml)this._xml.splice($.xml,this._xml.length-$.xml);if(this._stack.length>$.stack)this._stack.splice($.stack,this._stack.length-$.stack);this.leaf=$.leaf,this.open=$.open}get xml(){return this.closeAll(),this._xml.join("")}}rk.StdDocAttributes={version:"1.0",encoding:"UTF-8",standalone:"yes"};F70.exports=rk});var sk=E((Ae0)=>{var w70=typeof TextDecoder>"u"?null:new TextDecoder("utf-8");function De0($){if(typeof $==="string")return $;if(w70)return w70.decode($);return $.toString()}Ae0.bufferToString=De0});var A70=E((O70)=>{Object.defineProperty(O70,"__esModule",{value:!0});O70.CHAR=`
\r -퟿-�\uD800\uDC00-\uDBFF\uDFFF`;O70.S=` \r
`;O70.NAME_START_CHAR=":A-Z_a-zÀ-ÖØ-öø-˿Ͱ-ͽͿ-῿‌‍⁰-↏Ⰰ-⿯、-퟿豈-﷏ﷰ-�\uD800\uDC00-\uDB7F\uDFFF";O70.NAME_CHAR="-"+O70.NAME_START_CHAR+".0-9·̀-ͯ‿-⁀";O70.CHAR_RE=new RegExp("^["+O70.CHAR+"]$","u");O70.S_RE=new RegExp("^["+O70.S+"]+$","u");O70.NAME_START_CHAR_RE=new RegExp("^["+O70.NAME_START_CHAR+"]$","u");O70.NAME_CHAR_RE=new RegExp("^["+O70.NAME_CHAR+"]$","u");O70.NAME_RE=new RegExp("^["+O70.NAME_START_CHAR+"]["+O70.NAME_CHAR+"]*$","u");O70.NMTOKEN_RE=new RegExp("^["+O70.NAME_CHAR+"]+$","u");var ak=9,tk=10,ek=13,$x=32;O70.S_LIST=[$x,tk,ek,ak];function Pe0($){return $>=$x&&$<=55295||$===tk||$===ek||$===ak||$>=57344&&$<=65533||$>=65536&&$<=1114111}O70.isChar=Pe0;function Te0($){return $===$x||$===tk||$===ek||$===ak}O70.isS=Te0;function M70($){return $>=65&&$<=90||$>=97&&$<=122||$===58||$===95||$===8204||$===8205||$>=192&&$<=214||$>=216&&$<=246||$>=248&&$<=767||$>=880&&$<=893||$>=895&&$<=8191||$>=8304&&$<=8591||$>=11264&&$<=12271||$>=12289&&$<=55295||$>=63744&&$<=64975||$>=65008&&$<=65533||$>=65536&&$<=983039}O70.isNameStartChar=M70;function je0($){return M70($)||$>=48&&$<=57||$===45||$===46||$===183||$>=768&&$<=879||$>=8255&&$<=8256}O70.isNameChar=je0});var h70=E((C70)=>{Object.defineProperty(C70,"__esModule",{value:!0});C70.CHAR="\x01-퟿-�\uD800\uDC00-\uDBFF\uDFFF";C70.RESTRICTED_CHAR="\x01-\b\v\f\x0E-\x1F-„†-Ÿ";C70.S=` \r
`;C70.NAME_START_CHAR=":A-Z_a-zÀ-ÖØ-öø-˿Ͱ-ͽͿ-῿‌‍⁰-↏Ⰰ-⿯、-퟿豈-﷏ﷰ-�\uD800\uDC00-\uDB7F\uDFFF";C70.NAME_CHAR="-"+C70.NAME_START_CHAR+".0-9·̀-ͯ‿-⁀";C70.CHAR_RE=new RegExp("^["+C70.CHAR+"]$","u");C70.RESTRICTED_CHAR_RE=new RegExp("^["+C70.RESTRICTED_CHAR+"]$","u");C70.S_RE=new RegExp("^["+C70.S+"]+$","u");C70.NAME_START_CHAR_RE=new RegExp("^["+C70.NAME_START_CHAR+"]$","u");C70.NAME_CHAR_RE=new RegExp("^["+C70.NAME_CHAR+"]$","u");C70.NAME_RE=new RegExp("^["+C70.NAME_START_CHAR+"]["+C70.NAME_CHAR+"]*$","u");C70.NMTOKEN_RE=new RegExp("^["+C70.NAME_CHAR+"]+$","u");var B70=9,P70=10,T70=13,j70=32;C70.S_LIST=[j70,P70,T70,B70];function fe0($){return $>=1&&$<=55295||$>=57344&&$<=65533||$>=65536&&$<=1114111}C70.isChar=fe0;function ue0($){return $>=1&&$<=8||$===11||$===12||$>=14&&$<=31||$>=127&&$<=132||$>=134&&$<=159}C70.isRestrictedChar=ue0;function be0($){return $===9||$===10||$===13||$>31&&$<127||$===133||$>159&&$<=55295||$>=57344&&$<=65533||$>=65536&&$<=1114111}C70.isCharAndNotRestricted=be0;function ie0($){return $===j70||$===P70||$===T70||$===B70}C70.isS=ie0;function E70($){return $>=65&&$<=90||$>=97&&$<=122||$===58||$===95||$===8204||$===8205||$>=192&&$<=214||$>=216&&$<=246||$>=248&&$<=767||$>=880&&$<=893||$>=895&&$<=8191||$>=8304&&$<=8591||$>=11264&&$<=12271||$>=12289&&$<=55295||$>=63744&&$<=64975||$>=65008&&$<=65533||$>=65536&&$<=983039}C70.isNameStartChar=E70;function ce0($){return E70($)||$>=48&&$<=57||$===45||$===46||$===183||$>=768&&$<=879||$>=8255&&$<=8256}C70.isNameChar=ce0});var y70=E((g70)=>{Object.defineProperty(g70,"__esModule",{value:!0});g70.NC_NAME_START_CHAR="A-Z_a-zÀ-ÖØ-öø-˿Ͱ-ͽͿ-῿‌-‍⁰-↏Ⰰ-⿯、-퟿豈-﷏ﷰ-�\uD800\uDC00-\uDB7F\uDFFF";g70.NC_NAME_CHAR="-"+g70.NC_NAME_START_CHAR+".0-9·̀-ͯ‿-⁀";g70.NC_NAME_START_CHAR_RE=new RegExp("^["+g70.NC_NAME_START_CHAR+"]$","u");g70.NC_NAME_CHAR_RE=new RegExp("^["+g70.NC_NAME_CHAR+"]$","u");g70.NC_NAME_RE=new RegExp("^["+g70.NC_NAME_START_CHAR+"]["+g70.NC_NAME_CHAR+"]*$","u");function S70($){return $>=65&&$<=90||$===95||$>=97&&$<=122||$>=192&&$<=214||$>=216&&$<=246||$>=248&&$<=767||$>=880&&$<=893||$>=895&&$<=8191||$>=8204&&$<=8205||$>=8304&&$<=8591||$>=11264&&$<=12271||$>=12289&&$<=55295||$>=63744&&$<=64975||$>=65008&&$<=65533||$>=65536&&$<=983039}g70.isNCNameStartChar=S70;function z01($){return S70($)||($===45||$===46||$>=48&&$<=57||$===183||$>=768&&$<=879||$>=8255&&$<=8256)}g70.isNCNameChar=z01});var z20=E((U20)=>{Object.defineProperty(U20,"__esModule",{value:!0});var gQ=A70(),H01=h70(),Vx=y70(),m8=gQ.isS,W01=gQ.isChar,gW=gQ.isNameStartChar,k70=gQ.isNameChar,s70=gQ.S_LIST,X01=gQ.NAME_RE,Z01=H01.isChar,q01=Vx.isNCNameStartChar,V01=Vx.isNCNameChar,L01=Vx.NC_NAME_RE,HN="http://www.w3.org/XML/1998/namespace",SQ="http://www.w3.org/2000/xmlns/",F01={__proto__:null,xml:HN,xmlns:SQ},w01={__proto__:null,amp:"&",gt:">",lt:"<",quot:'"',apos:"'"},x4=-1,X9=-2,x70=0,M01=1,Ux=2,O01=3,_Q=4,N01=5,D01=6,A01=7,zx=8,B01=9,P01=10,T01=11,j01=12,h8=13,IN=14,Ix=15,E01=16,Qx=17,C01=18,R01=19,Jx=20,_01=21,v01=22,h01=23,f70=24,Kx=25,QN=26,u70=27,S01=28,g01=29,b70=30,y01=31,k01=32,qU=33,x01=34,Gx=35,yW=36,Hx=37,f01=38,i70=39,c70=40,u01=41,n70=42,b01=43,i01=44,Wx=9,w5=10,Xx=13,p70=32,d70=33,a70=34,kW=38,t70=39,JN=45,KN=47,c01=59,Y2=60,vQ=61,T6=62,s6=63,e70=91,hQ=93,m70=133,l70=8232,GN=($)=>$===a70||$===t70,$20=[a70,t70],n01=[...$20,e70,T6],p01=[...$20,Y2,hQ],d01=[vQ,s6,...s70],m01=[...s70,T6,kW,Y2];function qx($,Y,U){switch(Y){case"xml":if(U!==HN)$.fail(`xml prefix must be bound to ${HN}.`);break;case"xmlns":if(U!==SQ)$.fail(`xmlns prefix must be bound to ${SQ}.`);break;default:}switch(U){case SQ:$.fail(Y===""?`the default namespace may not be set to ${U}.`:`may not assign a prefix (even "xmlns") to the URI ${SQ}.`);break;case HN:switch(Y){case"xml":break;case"":$.fail(`the default namespace may not be set to ${U}.`);break;default:$.fail("may not assign the xml namespace to another prefix.")}break;default:}}function l01($,Y){for(let U of Object.keys(Y))qx($,U,Y[U])}var o01=($)=>L01.test($),r01=($)=>X01.test($),VU=0,o70=1,Zx=2;U20.EVENTS=["xmldecl","text","processinginstruction","doctype","comment","opentagstart","attribute","opentag","closetag","cdata","error","end","ready"];var r70={xmldecl:"xmldeclHandler",text:"textHandler",processinginstruction:"piHandler",doctype:"doctypeHandler",comment:"commentHandler",opentagstart:"openTagStartHandler",attribute:"attributeHandler",opentag:"openTagHandler",closetag:"closeTagHandler",cdata:"cdataHandler",error:"errorHandler",end:"endHandler",ready:"readyHandler"};class Y20{constructor($){this.opt=$!==null&&$!==void 0?$:{},this.fragmentOpt=!!this.opt.fragment;let Y=this.xmlnsOpt=!!this.opt.xmlns;if(this.trackPosition=this.opt.position!==!1,this.fileName=this.opt.fileName,Y){this.nameStartCheck=q01,this.nameCheck=V01,this.isName=o01,this.processAttribs=this.processAttribsNS,this.pushAttrib=this.pushAttribNS,this.ns=Object.assign({__proto__:null},F01);let U=this.opt.additionalNamesp Line truncated
`,Y=this.i}}captureToChar($){let{i:Y}=this,{chunk:U}=this;while(!0){let z=this.getCode();switch(z){case X9:this.text+=`${U.slice(Y,this.prevI)}
`,Y=this.i,z=w5;break;case x4:return this.text+=U.slice(Y),!1;default:}if(z===$)return this.text+=U.slice(Y,this.prevI),!0}}captureNameChars(){let{chunk:$,i:Y}=this;while(!0){let U=this.getCode();if(U===x4)return this.name+=$.slice(Y),x4;if(!k70(U))return this.name+=$.slice(Y,this.prevI),U===X9?w5:U}}skipSpaces(){while(!0){let $=this.getCodeNorm();if($===x4||!m8($))return $}}setXMLVersion($){if(this.currentXMLVersion=$,$==="1.0")this.isChar=W01,this.getCode=this.getCode10;else this.isChar=Z01,this.getCode=this.getCode11}sBegin(){if(this.chunk.charCodeAt(0)===65279)this.i++,this.column++;this.state=M01}sBeginWhitespace(){let $=this.i,Y=this.skipSpaces();if(this.prevI!==$)this.xmlDeclPossible=!1;switch(Y){case Y2:if(this.state=Ix,this.text.length!==0)throw Error("no-empty text at start");break;case x4:break;default:this.unget(),this.state=h8,this.xmlDeclPossible=!1}}sDoctype(){var $;let Y=this.captureTo(n01);switch(Y){case T6:{($=this.doctypeHandler)===null||$===void 0||$.call(this,this.text),this.text="",this.state=h8,this.doctype=!0;break}case x4:break;default:if(this.text+=String.fromCodePoint(Y),Y===e70)this.state=_Q;else if(GN(Y))this.state=O01,this.q=Y}}sDoctypeQuote(){let $=this.q;if(this.captureToChar($))this.text+=String.fromCodePoint($),this.q=null,this.state=Ux}sDTD(){let $=this.captureTo(p01);if($===x4)return;if(this.text+=String.fromCodePoint($),$===hQ)this.state=Ux;else if($===Y2)this.state=D01;else if(GN($))this.state=N01,this.q=$}sDTDQuoted(){let $=this.q;if(this.captureToChar($))this.text+=String.fromCodePoint($),this.state=_Q,this.q=null}sDTDOpenWaka(){let $=this.getCodeNorm();switch(this.text+=String.fromCodePoint($),$){case d70:this.state=A01,this.openWakaBang="";break;case s6:this.state=T01;break;default:this.state=_Q}}sDTDOpenWakaBang(){let $=String.fromCodePoint(this.getCodeNorm()),Y=this.openWakaBang+=$;if(this.text+=$,Y!=="-")this.state=Y==="--"?zx:_Q,this.openWakaBang=""}sDTDComment(){if(this.captureToChar(JN))this.text+="-",this.state=B01}sDTDCommentEnding(){let $=this.getCodeNorm();this.text+=String.fromCodePoint($),this.state=$===JN?P01:zx}sDTDCommentEnded(){let $=this.getCodeNorm();if(this.text+=String.fromCodePoint($),$===T6)this.state=_Q;else this.fail("malformed comment."),this.state=zx}sDTDPI(){if(this.captureToChar(s6))this.text+="?",this.state=j01}sDTDPIEnding(){let $=this.getCodeNorm();if(this.text+=String.fromCodePoint($),$===T6)this.state=_Q}sText(){if(this.tags.length!==0)this.handleTextInRoot();else this.handleTextOutsideRoot()}sEntity(){let{i:$}=this,{chunk:Y}=this;$:while(!0)switch(this.getCode()){case X9:this.entity+=`${Y.slice($,this.prevI)}
`,$=this.i;break;case c01:{let{entityReturnState:U}=this,z=this.entity+Y.slice($,this.prevI);this.state=U;let I;if(z==="")this.fail("empty entity name."),I="&;";else I=this.parseEntity(z),this.entity="";if(U!==h8||this.textHandler!==void 0)this.text+=I;break $}case x4:this.entity+=Y.slice($);break $;default:}}sOpenWaka(){let $=this.getCode();if(gW($))this.state=x01,this.unget(),this.xmlDeclPossible=!1;else switch($){case KN:this.state=b01,this.xmlDeclPossible=!1;break;case d70:this.state=E01,this.openWakaBang="",this.xmlDeclPossible=!1;break;case s6:this.state=h01;break;default:this.fail("disallowed character in tag name"),this.state=h8,this.xmlDeclPossible=!1}}sOpenWakaBang(){switch(this.openWakaBang+=String.fromCodePoint(this.getCodeNorm()),this.openWakaBang){case"[CDATA[":if(!this.sawRoot&&!this.reportedTextBeforeRoot)this.fail("text data outside of root node."),this.reportedTextBeforeRoot=!0;if(this.closedRoot&&!this.reportedTextAfterRoot)this.fail("text data outside of root node."),this.reportedTextAfterRoot=!0;this.state=Jx,this.openWakaBang="";break;case"--":this.state=Qx,this.openWakaBang="";break;case"DOCTYPE":if(this.state=Ux,this.doctype||this.sawRoot)this.fail("inappropriately located doctype declaration.");this.openWakaBang="";break;default:if(this.openWakaBang.length>=7)this.fail("incorrect syntax.")}}sComment(){if(this.captureToChar(JN))this.state=C01}sCommentEnding(){var $;let Y=this.getCodeNorm();if(Y===JN)this.state=R01,($=this.commentHandler)===null||$===void 0||$.call(this,this.text),this.text="";else this.text+=`-${String.fromCodePoint(Y)}`,this.state=Qx}sCommentEnded(){let $=this.getCodeNorm();if($!==T6)this.fail("malformed comment."),this.text+=`--${String.fromCodePoint($)}`,this.state=Qx;else this.state=h8}sCData(){if(this.captureToChar(hQ))this.state=_01}sCDataEnding(){let $=this.getCodeNorm();if($===hQ)this.state=v01;else this.text+=`]${String.fromCodePoint($)}`,this.state=Jx}sCDataEnding2(){var $;let Y=this.getCodeNorm();switch(Y){case T6:{($=this.cdataHandler)===null||$===void 0||$.call(this,this.text),this.text="",this.state=h8;break}case hQ:this.text+="]";break;default:this.text+=`]]${String.fromCodePoint(Y)}`,this.state=Jx}}sPIFirstChar(){let $=this.getCodeNorm();if(this.nameStartCheck($))this.piTarget+=String.fromCodePoint($),this.state=f70;else if($===s6||m8($))this.fail("processing instruction without a target."),this.state=$===s6?QN:Kx;else this.fail("disallowed character in processing instruction name."),this.piTarget+=String.fromCodePoint($),this.state=f70}sPIRest(){let{chunk:$,i:Y}=this;while(!0){let U=this.getCodeNorm();if(U===x4){this.piTarget+=$.slice(Y);return}if(!this.nameCheck(U)){this.piTarget+=$.slice(Y,this.prevI);let z=U===s6;if(z||m8(U))if(this.piTarget==="xml"){if(!this.xmlDeclPossible)this.fail("an XML declaration must be at the start of the document.");this.state=z?qU:u70}else this.state=z?QN:Kx;else this.fail("disallowed character in processing instruction name."),this.piTarget+=String.fromCodePoint(U);break}}}sPIBody(){if(this.text.length===0){let $=this.getCodeNorm();if($===s6)this.state=QN;else if(!m8($))this.text=String.fromCodePoint($)}else if(this.captureToChar(s6))this.state=QN}sPIEnding(){var $;let Y=this.getCodeNorm();if(Y===T6){let{piTarget:U}=this;if(U.toLowerCase()==="xml")this.fail("the XML declaration must appear at the start of the document.");($=this.piHandler)===null||$===void 0||$.call(this,{target:U,body:this.text}),this.piTarget=this.text="",this.state=h8}else if(Y===s6)this.text+="?";else this.text+=`?${String.fromCodePoint(Y)}`,this.state=Kx;this.xmlDeclPossible=!1}sXMLDeclNameStart(){let $=this.skipSpaces();if($===s6){this.state=qU;return}if($!==x4)this.state=S01,this.name=String.fromCodePoint($)}sXMLDeclName(){let $=this.captureTo(d01);if($===s6){this.state=qU,this.name+=this.text,this.text="",this.fail("XML declaration is incomplete.");return}if(!(m8($)||$===vQ))return;if(this.name+=this.text,this.text="",!this.xmlDeclExpects.includes(this.name))switch(this.name.length){case 0:this.fail("did not expect any more name/value pairs.");break;case 1:this.fail(`expected the name ${this.xmlDeclExpects[0]}.`);break;default:this.fail(`expected one of ${this.xmlDeclExpects.join(", ")}`)}this.state=$===vQ?b70:g01}sXMLDeclEq(){let $=this.getCodeNorm();if($===s6){this.state=qU,this.fail("XML declaration is incomplete.");return}if(m8($))return;if($!==vQ)this.fail("value required.");this.state=b70}sXMLDeclValueStart(){let $=this.getCodeNorm();if($===s6){this.state=qU,this.fail("XML declaration is incomplete.");return}if(m8($))return;if(!GN($))this.fail("value must be quoted."),this.q=p70;else this.q=$;this.state=y01}sXMLDeclValue(){let $=this.captureTo([this.q,s6]);if($===s6){this.state=qU,this.text="",this.fail("XML declaration is incomplete.");return}if($===x4)return;let Y=this.text;switch(this.text="",this.name){case"version":{this.xmlDeclExpects=["encoding","standalone"];let U=Y;if(this.xmlDecl.version=U,!/^1\.[0-9]+$/.test(U))this.fail("ver Line truncated
`;$=this.i,Y=VU;break;case x4:if(z!==void 0)this.text+=U.slice($);break $;default:Y=VU}this.forbiddenState=Y}handleTextOutsideRoot(){let{i:$}=this,{chunk:Y,textHandler:U}=this,z=!1;$:while(!0){let I=this.getCode();switch(I){case Y2:{if(this.state=Ix,U!==void 0){let{text:Q}=this,J=Y.slice($,this.prevI);if(Q.length!==0)U(Q+J),this.text="";else if(J.length!==0)U(J)}break $}case kW:if(this.state=IN,this.entityReturnState=h8,U!==void 0)this.text+=Y.slice($,this.prevI);z=!0;break $;case X9:if(U!==void 0)this.text+=`${Y.slice($,this.prevI)}
`;$=this.i;break;case x4:if(U!==void 0)this.text+=Y.slice($);break $;default:if(!m8(I))z=!0}}if(!z)return;if(!this.sawRoot&&!this.reportedTextBeforeRoot)this.fail("text data outside of root node."),this.reportedTextBeforeRoot=!0;if(this.closedRoot&&!this.reportedTextAfterRoot)this.fail("text data outside of root node."),this.reportedTextAfterRoot=!0}pushAttribNS($,Y){var U;let{prefix:z,local:I}=this.qname($),Q={name:$,prefix:z,local:I,value:Y};if(this.attribList.push(Q),(U=this.attributeHandler)===null||U===void 0||U.call(this,Q),z==="xmlns"){let J=Y.trim();if(this.currentXMLVersion==="1.0"&&J==="")this.fail("invalid attempt to undefine prefix in XML 1.0");this.topNS[I]=J,qx(this,I,J)}else if($==="xmlns"){let J=Y.trim();this.topNS[""]=J,qx(this,"",J)}}pushAttribPlain($,Y){var U;let z={name:$,value:Y};this.attribList.push(z),(U=this.attributeHandler)===null||U===void 0||U.call(this,z)}end(){var $,Y;if(!this.sawRoot)this.fail("document must contain a root element.");let{tags:U}=this;while(U.length>0){let I=U.pop();this.fail(`unclosed tag: ${I.name}`)}if(this.state!==x70&&this.state!==h8)this.fail("unexpected end.");let{text:z}=this;if(z.length!==0)($=this.textHandler)===null||$===void 0||$.call(this,z),this.text="";return this._closed=!0,(Y=this.endHandler)===null||Y===void 0||Y.call(this),this._init(),this}resolve($){var Y,U;let z=this.topNS[$];if(z!==void 0)return z;let{tags:I}=this;for(let Q=I.length-1;Q>=0;Q--)if(z=I[Q].ns[$],z!==void 0)return z;if(z=this.ns[$],z!==void 0)return z;return(U=(Y=this.opt).resolvePrefix)===null||U===void 0?void 0:U.call(Y,$)}qname($){let Y=$.indexOf(":");if(Y===-1)return{prefix:"",local:$};let U=$.slice(Y+1),z=$.slice(0,Y);if(z===""||U===""||U.includes(":"))this.fail(`malformed name: ${$}.`);return{prefix:z,local:U}}processAttribsNS(){var $;let{attribList:Y}=this,U=this.tag;{let{prefix:Q,local:J}=this.qname(U.name);U.prefix=Q,U.local=J;let K=U.uri=($=this.resolve(Q))!==null&&$!==void 0?$:"";if(Q!==""){if(Q==="xmlns")this.fail('tags may not have "xmlns" as prefix.');if(K==="")this.fail(`unbound namespace prefix: ${JSON.stringify(Q)}.`),U.uri=Q}}if(Y.length===0)return;let{attributes:z}=U,I=new Set;for(let Q of Y){let{name:J,prefix:K,local:G}=Q,H,W;if(K==="")H=J==="xmlns"?SQ:"",W=J;else{if(H=this.resolve(K),H===void 0)this.fail(`unbound namespace prefix: ${JSON.stringify(K)}.`),H=K;W=`{${H}}${G}`}if(I.has(W))this.fail(`duplicate attribute: ${W}.`);I.add(W),Q.uri=H,z[J]=Q}this.attribList=[]}processAttribsPlain(){let{attribList:$}=this,Y=this.tag.attributes;for(let{name:U,value:z}of $){if(Y[U]!==void 0)this.fail(`duplicate attribute: ${U}.`);Y[U]=z}this.attribList=[]}openTag(){var $;this.processAttribs();let{tags:Y}=this,U=this.tag;U.isSelfClosing=!1,($=this.openTagHandler)===null||$===void 0||$.call(this,U),Y.push(U),this.state=h8,this.name=""}openSelfClosingTag(){var $,Y,U;this.processAttribs();let{tags:z}=this,I=this.tag;if(I.isSelfClosing=!0,($=this.openTagHandler)===null||$===void 0||$.call(this,I),(Y=this.closeTagHandler)===null||Y===void 0||Y.call(this,I),(this.tag=(U=z[z.length-1])!==null&&U!==void 0?U:null)===null)this.closedRoot=!0;this.state=h8,this.name=""}closeTag(){let{tags:$,name:Y}=this;if(this.state=h8,this.name="",Y===""){this.fail("weird empty close tag."),this.text+="</>";return}let U=this.closeTagHandler,z=$.length;while(z-- >0){let I=this.tag=$.pop();if(this.topNS=I.ns,U===null||U===void 0||U(I),I.name===Y)break;this.fail("unexpected close tag.")}if(z===0)this.closedRoot=!0;else if(z<0)this.fail(`unmatched closing tag: ${Y}.`),this.text+=`</${Y}>`}parseEntity($){if($[0]!=="#"){let U=this.ENTITIES[$];if(U!==void 0)return U;return this.fail(this.isName($)?"undefined entity.":"disallowed character in entity name."),`&${$};`}let Y=NaN;if($[1]==="x"&&/^#x[0-9a-f]+$/i.test($))Y=parseInt($.slice(2),16);else if(/^#[0-9]+$/.test($))Y=parseInt($.slice(1),10);if(!this.isChar(Y))return this.fail("malformed character entity."),`&${$};`;return String.fromCodePoint(Y)}}U20.SaxesParser=Y20});var xW=E((Ol1,I20)=>{var{SaxesParser:t01}=z20(),{PassThrough:e01}=v8(),{bufferToString:$11}=sk();I20.exports=async function*($){if($.pipe&&!$[Symbol.asyncIterator])$=$.pipe(new e01);let Y=new t01,U;Y.on("error",(I)=>{U=I});let z=[];Y.on("opentag",(I)=>z.push({eventType:"opentag",value:I})),Y.on("text",(I)=>z.push({eventType:"text",value:I})),Y.on("closetag",(I)=>z.push({eventType:"closetag",value:I}));for await(let I of $){if(Y.write($11(I)),U)throw U;yield z,z=[]}}});var g0=E((Nl1,Q20)=>{var Y11=xW(),U11=r6();class yQ{prepare(){}render(){}parseOpen($){}parseText($){}parseClose($){}reconcile($,Y){}reset(){if(this.model=null,this.map)Object.values(this.map).forEach(($)=>{if($ instanceof yQ)$.reset();else if($.xform)$.xform.reset()})}mergeModel($){this.model=Object.assign(this.model||{},$)}async parse($){for await(let Y of $)for(let{eventType:U,value:z}of Y)if(U==="opentag")this.parseOpen(z);else if(U==="text")this.parseText(z);else if(U==="closetag"){if(!this.parseClose(z.name))return thLine truncated
<a:theme xmlns:a="http://schemas.openxmlformats.org/drawingml/2006/main" name="Office Theme"> <a:themeElements> <a:clrScheme name="Office"> <a:dk1> <a:sysClr val="windowText" lastClr="000000"/> </a:dk1> <a:lt1> <a:sysClr val="window" lastClr="FFFFFF"/> </a:lt1> <a:dk2> <a:srgbClr val="1F497D"/> </a:dk2> <a:lt2> <a:srgbClr val="EEECE1"/> </a:lt2> <a:accent1> <a:srgbClr val="4F81BD"/> </a:accent1> <a:accent2> <a:srgbClr val="C0504D"/> </a:accent2> <a:accent3> <a:srgbClr val="9BBB59"/> </a:accent3> <a:accent4> <a:srgbClr val="8064A2"/> </a:accent4> <a:accent5> <a:srgbClr val="4BACC6"/> </a:accent5> <a:accent6> <a:srgbClr val="F79646"/> </a:accent6> <a:hlink> <a:srgbClr val="0000FF"/> </a:hlink> <a:folHlink> <a:srgbClr val="800080"/> </a:folHlink> </a:clrScheme> <a:fontScheme name="Office"> <a:majorFont> <a:latin typeface="Cambria"/> <a:ea typeface=""/> <a:cs typeface=""/> <a:font script="Jpan" typeface="MS Pゴシック"/> <a:font script="Hang" typeface="맑은 고딕"/> <a:font script="Hans" typeface="宋体"/> <a:font script="Hant" typeface="新細明體"/> <a:font script="Arab" typeface="Times New Roman"/> <a:font script="Hebr" typeface="Times New Roman"/> <a:font script="Thai" typeface="Tahoma"/> <a:font script="Ethi" typeface="Nyala"/> <a:font script="Beng" typeface="Vrinda"/> <a:font script="Gujr" typeface="Shruti"/> <a:font script="Khmr" typeface="MoolBoran"/> <a:font script="Knda" typeface="Tunga"/> <a:font script="Guru" typeface="Raavi"/> <a:font script="Cans" typeface="Euphemia"/> <a:font script="Cher" typeface="Plantagenet Cherokee"/> <a:font script="Yiii" typeface="Microsoft Yi Baiti"/> <a:font script="Tibt" typeface="Microsoft Himalaya"/> <a:font script="Thaa" typeface="MV Boli"/> <a:font script="Deva" typeface="Mangal"/> <a:font script="Telu" typeface="Gautami"/> <a:font script="Taml" typeface="Latha"/> <a:font script="Syrc" typeface="Estrangelo Edessa"/> <a:font script="Orya" typeface="Kalinga"/> <a:font script="Mlym" typeface="Kartika"/> <a:font script="Laoo" typeface="DokChampa"/> <a:font script="Sinh" typeface="Iskoola Pota"/> <a:font script="Mong" typeface="Mongolian Baiti"/> <a:font script="Viet" typeface="Times New Roman"/> <a:font script="Uigh" typeface="Microsoft Uighur"/> <a:font script="Geor" typeface="Sylfaen"/> </a:majorFont> <a:minorFont> <a:latin typeface="Calibri"/> <a:ea typeface=""/> <a:cs typeface=""/> <a:font script="Jpan" typeface="MS Pゴシック"/> <a:font script="Hang" typeface="맑은 고딕"/> <a:font script="Hans" typeface="宋体"/> <a:font script="Hant" typeface="新細明體"/> <a:font script="Arab" typeface="Arial"/> <a:font script="Hebr" typeface="Arial"/> <a:font script="Thai" typeface="Tahoma"/> <a:font script="Ethi" typeface="Nyala"/> <a:font script="Beng" typeface="Vrinda"/> <a:font script="Gujr" typeface="Shruti"/> <a:font script="Khmr" typeface="DaunPenh"/> <a:font script="Knda" typeface="Tunga"/> <a:font script="Guru" typeface="Raavi"/> <a:font script="Cans" typeface="Euphemia"/> <a:font script="Cher" typeface="Plantagenet Cherokee"/> <a:font script="Yiii" typeface="Microsoft Yi Baiti"/> <a:font script="Tibt" typeface="Microsoft Himalaya"/> <a:font script="Thaa" typeface="MV Boli"/> <a:font script="Deva" typeface="Mangal"/> <a:font script="Telu" typeface="Gautami"/> <a:font script="Taml" typeface="Latha"/> <a:font script="Syrc" typeface="Estrangelo Edessa"/> <a:font script="Orya" typeface="Kalinga"/> <a:font script="Mlym" typeface="Kartika"/> <a:font script="Laoo" typeface="DokChampa"/> <a:font script="Sinh" typeface="Iskoola Pota"/> <a:font script="Mong" typeface="Mongolian Baiti"/> <a:font script="Viet" typeface="Arial"/> <a:font script="Uigh" typeface="Microsoft Uighur"/> <a:font script="Geor" typeface="Sylfaen"/> </a:minorFont> </a:fontScheme> <a:fmtScheme name="Office"> <a:fillStyleLst> <a:solidFill> <a:schemeClr val="phClr"/> </a:solidFill> <a:gradFill rotWithShape="1"> <a:gsLst> <a:gs pos="0"> <a:schemeClr val="phClr"> <a:tint val="50000"/> <a:satMod val="300000"/> </a:schemeClr> </a:gs> <a:gs pos="35000"> <a:schemeClr val="phClr"> <a:tint val="37000"/> <a:satMod val="300000"/> </a:schemeClr> </a:gs> <a:gs pos="100000"> <a:schemeClr val="phClr"> <a:tint val="15000"/> <a:satMod val="350000"/> </a:schemeClr> </a:gs> </a:gsLst> <a:lin ang="16200000" scaled="1"/> </a:gradFill> <a:gradFill rotWithShape="1"> <a:gsLst> <a:gs pos="0"> <a:schemeClr val="phClr"> <a:tint val="100000"/> <a:shade val="100000"/> <a:satMod val="130000"/> </a:schemeClr> </a:gs> <a:gs pos="100000"> <a:schemeClr val="phClr"> <a:tint val="50000"/> <a:shade val="100000"/> <a:satMod val="350000"/> </a:schemeClr> </a:gs> </a:gsLst> <a:lin ang="16200000" scaled="0"/> </a:gradFill> </a:fillStyleLst> <a:lnStyleLst> <a:ln w="9525" cap="flat" cmpd="sng" algn="ctr"> <a:solidFill> <a:schemeClr val="phClr"> <a:shade val="95000"/> <a:satMod val="105000"/> </a:schemeClr> </a:solidFill> <a:prstDash val="solid"/> </a:ln> <a:ln w="25400" cap="flat" cmpd="sng" algn="ctr"> <a:solidFill> <a:Line truncated
`,this.quote='"',this.escape=this.quote,this.quoteColumns=!1,this.quoteHeaders=this.quoteColumns,this.headers=null,this.includeEndRowDelimiter=!1,this.writeBOM=!1,this.BOM="\uFEFF",this.alwaysWriteHeaders=!1,Object.assign(this,$||{}),typeof($===null||$===void 0?void 0:$.quoteHeaders)>"u")this.quoteHeaders=this.quoteColumns;if(($===null||$===void 0?void 0:$.quote)===!0)this.quote='"';else if(($===null||$===void 0?void 0:$.quote)===!1)this.quote="";if(typeof($===null||$===void 0?void 0:$.escape)!=="string")this.escape=this.quote;this.shouldWriteHeaders=!!this.headers&&((Y=$.writeHeaders)!==null&&Y!==void 0?Y:!0),this.headers=Array.isArray(this.headers)?this.headers:null,this.escapedQuote=`${this.escape}${this.quote}`}}yJ0.FormatterOptions=gJ0});var cN=E((dr1,bJ0)=>{var Z91="[object AsyncFunction]",q91="[object Function]",V91="[object GeneratorFunction]",L91="[object Null]",F91="[object Proxy]",w91="[object Undefined]",M91=typeof global=="object"&&global&&global.Object===Object&&global,O91=typeof self=="object"&&self&&self.Object===Object&&self,N91=M91||O91||Function("return this")(),fJ0=Object.prototype,D91=fJ0.hasOwnProperty,uJ0=fJ0.toString,xJ0=N91.Symbol,DU=xJ0?xJ0.toStringTag:void 0;function A91($){if($==null)return $===void 0?w91:L91;return DU&&DU in Object($)?B91($):P91($)}function B91($){var Y=D91.call($,DU),U=$[DU];try{$[DU]=void 0;var z=!0}catch(Q){}var I=uJ0.call($);if(z)if(Y)$[DU]=U;else delete $[DU];return I}function P91($){return uJ0.call($)}function T91($){if(!j91($))return!1;var Y=A91($);return Y==q91||Y==V91||Y==Z91||Y==F91}function j91($){var Y=typeof $;return $!=null&&(Y=="object"||Y=="function")}bJ0.exports=T91});var DK0=E((nN,dQ)=>{var E91=200,xf="__lodash_hash_undefined__",aN=1,tJ0=2,eJ0=9007199254740991,pN="[object Arguments]",_f="[object Array]",C91="[object AsyncFunction]",$K0="[object Boolean]",YK0="[object Date]",UK0="[object Error]",zK0="[object Function]",R91="[object GeneratorFunction]",dN="[object Map]",IK0="[object Number]",_91="[object Null]",pQ="[object Object]",iJ0="[object Promise]",v91="[object Proxy]",QK0="[object RegExp]",mN="[object Set]",JK0="[object String]",h91="[object Symbol]",S91="[object Undefined]",vf="[object WeakMap]",KK0="[object ArrayBuffer]",lN="[object DataView]",g91="[object Float32Array]",y91="[object Float64Array]",k91="[object Int8Array]",x91="[object Int16Array]",f91="[object Int32Array]",u91="[object Uint8Array]",b91="[object Uint8ClampedArray]",i91="[object Uint16Array]",c91="[object Uint32Array]",n91=/[\\^$.*+?()[\]{}|]/g,p91=/^\[object .+?Constructor\]$/,d91=/^(?:0|[1-9]\d*)$/,T4={};T4[g91]=T4[y91]=T4[k91]=T4[x91]=T4[f91]=T4[u91]=T4[b91]=T4[i91]=T4[c91]=!0;T4[pN]=T4[_f]=T4[KK0]=T4[$K0]=T4[lN]=T4[YK0]=T4[UK0]=T4[zK0]=T4[dN]=T4[IK0]=T4[pQ]=T4[QK0]=T4[mN]=T4[JK0]=T4[vf]=!1;var GK0=typeof global=="object"&&global&&global.Object===Object&&global,m91=typeof self=="object"&&self&&self.Object===Object&&self,w3=GK0||m91||Function("return this")(),HK0=typeof nN=="object"&&nN&&!nN.nodeType&&nN,cJ0=HK0&&typeof dQ=="object"&&dQ&&!dQ.nodeType&&dQ,WK0=cJ0&&cJ0.exports===HK0,Ef=WK0&&GK0.process,nJ0=function(){try{return Ef&&Ef.binding&&Ef.binding("util")}catch($){}}(),pJ0=nJ0&&nJ0.isTypedArray;function l91($,Y){var U=-1,z=$==null?0:$.length,I=0,Q=[];while(++U<z){var J=$[U];if(Y(J,U,$))Q[I++]=J}return Q}function o91($,Y){var U=-1,z=Y.length,I=$.length;while(++U<z)$[I+U]=Y[U];return $}function r91($,Y){var U=-1,z=$==null?0:$.length;while(++U<z)if(Y($[U],U,$))return!0;return!1}function s91($,Y){var U=-1,z=Array($);while(++U<$)z[U]=Y(U);return z}function a91($){return function(Y){return $(Y)}}function t91($,Y){return $.has(Y)}function e91($,Y){return $==null?void 0:$[Y]}function $31($){var Y=-1,U=Array($.size);return $.forEach(function(z,I){U[++Y]=[I,z]}),U}function Y31($,Y){return function(U){return $(Y(U))}}function U31($){var Y=-1,U=Array($.size);return $.forEach(function(z){U[++Y]=z}),U}var z31=Array.prototype,I31=Function.prototype,tN=Object.prototype,Cf=w3["__core-js_shared__"],XK0=I31.toString,q9=tN.hasOwnProperty,dJ0=function(){var $=/[^.]+$/.exec(Cf&&Cf.keys&&Cf.keys.IE_PROTO||"");return $?"Symbol(src)_1."+$:""}(),ZK0=tN.toString,Q31=RegExp("^"+XK0.call(q9).replace(n91,"\\$&").replace(/hasOwnProperty|(function).*?(?=\\\()| for .+?(?=\\\])/g,"$1.*?")+"$"),mJ0=WK0?w3.Buffer:void 0,oN=w3.Symbol,lJ0=w3.Uint8Array,qK0=tN.propertyIsEnumerable,J31=z31.splice,AU=oN?oN.toStringTag:void 0,oJ0=Object.getOwnPropertySymbols,K31=mJ0?mJ0.isBuffer:void 0,G31=Y31(Object.keys,Object),hf=mQ(w3,"DataView"),pW=mQ(w3,"Map"),Sf=mQ(w3,"Promise"),gf=mQ(w3,"Set"),yf=mQ(w3,"WeakMap"),dW=mQ(Object,"create"),H31=TU(hf),W31=TU(pW),X31=TU(Sf),Z31=TU(gf),q31=TU(yf),rJ0=oN?oN.prototype:void 0,Rf=rJ0?rJ0.valueOf:void 0;function BU($){var Y=-1,U=$==null?0:$.length;this.clear();while(++Y<U){var z=$[Y];this.set(z[0],z[1])}}function V31(){this.__data__=dW?dW(null):{},this.size=0}function L31($){var Y=this.has($)&&delete this.__data__[$];return this.size-=Y?1:0,Y}function F31($){var Y=this.__data Line truncated
]`;this.ESCAPE_REGEXP=new RegExp(Y)}set headers($){this._headers=$}shouldQuote($,Y){let U=Y?this.formatterOptions.quoteHeaders:this.formatterOptions.quoteColumns;if(A71.default(U))return U;if(Array.isArray(U))return U[$];if(this._headers!==null)return U[this._headers[$]];return!1}format($,Y,U){let z=`${B71.default($)?"":$}`.replace(/\0/g,""),{formatterOptions:I}=this;if(I.quote!==""){if(z.indexOf(I.quote)!==-1)return this.quoteField(z.replace(this.REPLACE_REGEXP,I.escapedQuote))}if(z.search(this.ESCAPE_REGEXP)!==-1||this.shouldQuote(Y,U))return this.quoteField(z);return z}quoteField($){let{quote:Y}=this.formatterOptions;return`${Y}${$}${Y}`}}lQ.FieldFormatter=_K0});var nf=E((vK0)=>{Object.defineProperty(vK0,"__esModule",{value:!0});vK0.isSyncTransform=void 0;vK0.isSyncTransform=($)=>$.length===1});var gK0=E((oQ)=>{var SK0=oQ&&oQ.__importDefault||function($){return $&&$.__esModule?$:{default:$}};Object.defineProperty(oQ,"__esModule",{value:!0});oQ.RowFormatter=void 0;var T71=SK0(cN()),j71=SK0(DK0()),E71=cf(),C71=nf();class jU{constructor($){if(this.rowCount=0,this.formatterOptions=$,this.fieldFormatter=new E71.FieldFormatter($),this.headers=$.headers,this.shouldWriteHeaders=$.shouldWriteHeaders,this.hasWrittenHeaders=!1,this.headers!==null)this.fieldFormatter.headers=this.headers;if($.transform)this.rowTransform=$.transform}static isRowHashArray($){if(Array.isArray($))return Array.isArray($[0])&&$[0].length===2;return!1}static isRowArray($){return Array.isArray($)&&!this.isRowHashArray($)}static gatherHeaders($){if(jU.isRowHashArray($))return $.map((Y)=>Y[0]);if(Array.isArray($))return $;return Object.keys($)}static createTransform($){if(C71.isSyncTransform($))return(Y,U)=>{let z=null;try{z=$(Y)}catch(I){return U(I)}return U(null,z)};return(Y,U)=>{$(Y,U)}}set rowTransform($){if(!T71.default($))throw TypeError("The transform should be a function");this._rowTransform=jU.createTransform($)}format($,Y){this.callTransformer($,(U,z)=>{if(U)return Y(U);if(!$)return Y(null);let I=[];if(z){let{shouldFormatColumns:Q,headers:J}=this.checkHeaders(z);if(this.shouldWriteHeaders&&J&&!this.hasWrittenHeaders)I.push(this.formatColumns(J,!0)),this.hasWrittenHeaders=!0;if(Q){let K=this.gatherColumns(z);I.push(this.formatColumns(K,!1))}}return Y(null,I)})}finish($){let Y=[];if(this.formatterOptions.alwaysWriteHeaders&&this.rowCount===0){if(!this.headers)return $(Error("`alwaysWriteHeaders` option is set to true but `headers` option not provided."));Y.push(this.formatColumns(this.headers,!0))}if(this.formatterOptions.includeEndRowDelimiter)Y.push(this.formatterOptions.rowDelimiter);return $(null,Y)}checkHeaders($){if(this.headers)return{shouldFormatColumns:!0,headers:this.headers};let Y=jU.gatherHeaders($);if(this.headers=Y,this.fieldFormatter.headers=Y,!this.shouldWriteHeaders)return{shouldFormatColumns:!0,headers:null};return{shouldFormatColumns:!j71.default(Y,$),headers:Y}}gatherColumns($){if(this.headers===null)throw Error("Headers is currently null");if(!Array.isArray($))return this.headers.map((Y)=>$[Y]);if(jU.isRowHashArray($))return this.headers.map((Y,U)=>{let z=$[U];if(z)return z[1];return""});if(jU.isRowArray($)&&!this.shouldWriteHeaders)return $;return this.headers.map((Y,U)=>$[U])}callTransformer($,Y){if(!this._rowTransform)return Y(null,$);return this._rowTransform($,Y)}formatColumns($,Y){let U=$.map((I,Q)=>this.fieldFormatter.format(I,Q,Y)).join(this.formatterOptions.delimiter),{rowCount:z}=this;if(this.rowCount+=1,z)return[this.formatterOptions.rowDelimiter,U].join("");return U}}oQ.RowFormatter=jU});var yK0=E((YD)=>{Object.defineProperty(YD,"__esModule",{value:!0});YD.FieldFormatter=YD.RowFormatter=void 0;var R71=gK0();Object.defineProperty(YD,"RowFormatter",{enumerable:!0,get:function(){return R71.RowFormatter}});var _71=cf();Object.defineProperty(YD,"FieldFormatter",{enumerable:!0,get:function(){return _71.FieldFormatter}})});var pf=E((xK0)=>{Object.defineProperty(xK0,"__esModule",{value:!0});xK0.CsvFormatterStream=void 0;var h71=J0("stream"),S71=yK0();class kK0 extends h71.Transform{constructor($){super({writableObjectMode:$.objectMode});this.hasWrittenBOM=!1,this.formatterOptions=$,this.rowFormatter=new S71.RowFormatter($),this.hasWrittenBOM=!$.writeBOM}transform($){return this.rowFormatter.rowTransform=$,this}_transform($,Y,U){let z=!1;try{if(!this.hasWrittenBOM)this.push(this.formatterOptions.BOM),this.hasWrittenBOM=!0;this.rowFormatter.format($,(I,Q)=>{if(I)return z=!0,U(I);if(Q)Q.forEach((J)=>{this.push(Buffer.from(J,"utf8"))});return z=!0,U()})}catch(I){if(z)throw I;U(I)}}_flush($){this.rowFormatter.finish((Y,U)=>{if(Y)return $(Y);if(U)U.forEach((z)=>{this.push(Buffer.from(z,"utf8"))});return $()})}}xK0.CsvFormatterStream=kK0});var bK0=E((a1)=>{var uK0=a1&&a1.__createBinding||(Object.create?function($,Y,U,z){if(z===void 0)z=U;Object.defineProperty($,z,{enumerable:!0,get:function(){return Y[U]}})}:function($,Y,U,z){if(z===void 0)z=U;$[z]=Y[U]}),g71=a1&&a1.__setModuleDefault||(Object.create?function($,Y){O Line truncated
deps: ${W}}`};let Q={keyword:"dependencies",type:"object",schemaType:"object",error:$.error,code(G){let[H,W]=J(G);K(G,H),z(G,W)}};function J({schema:G}){let H={},W={};for(let X in G){if(X==="__proto__")continue;let Z=Array.isArray(G[X])?H:W;Z[X]=G[X]}return[H,W]}function K(G,H=G.schema){let{gen:W,data:X,it:Z}=G;if(Object.keys(H).length===0)return;let q=W.let("missing");for(let V in H){let w=H[V];if(w.length===0)continue;let M=(0,I.propertyInData)(W,X,V,Z.opts.ownProperties);if(G.setParams({property:V,depsCount:w.length,deps:w.join(", ")}),Z.allErrors)W.if(M,()=>{for(let F of w)(0,I.checkReportMissingProp)(G,F)});else W.if(Y._`${M} && (${(0,I.checkMissingProp)(G,w,q)})`),(0,I.reportMissingProp)(G,q),W.else()}}$.validatePropertyDeps=K;function z(G,H=G.schema){let{gen:W,data:X,keyword:Z,it:q}=G,V=W.name("valid");for(let w in H){if((0,U.alwaysValidSchema)(q,H[w]))continue;W.if((0,I.propertyInData)(W,X,w,q.opts.ownProperties),()=>{let M=G.subschema({keyword:Z,schemaProp:w},V);G.mergeValidEvaluated(M,V)},()=>W.var(V,!0)),G.ok(V)}}$.validateSchemaDeps=z,$.default=Q}),Jc0=j0(($)=>{Object.defineProperty($,"__esModule",{value:!0});let Y=F1(),U=v1(),I={keyword:"propertyNames",type:"object",schemaType:["object","boolean"],error:{message:"property name must be valid",params:({params:Q})=>Y._`{propertyName: ${Q.propertyName}}`},code(Q){let{gen:J,schema:K,data:z,it:G}=Q;if((0,U.alwaysValidSchema)(G,K))return;let H=J.name("valid");J.forIn("key",z,(W)=>{Q.setParams({propertyName:W}),Q.subschema({keyword:"propertyNames",data:W,dataTypes:["string"],propertyName:W,compositeRule:!0},H),J.if((0,Y.not)(H),()=>{if(Q.error(!0),!G.allErrors)J.break()})}),Q.ok(H)}};$.default=I}),oe=j0(($)=>{Object.defineProperty($,"__esModule",{value:!0});let Y=Z5(),U=F1(),I=X5(),Q=v1(),J={keyword:"additionalProperties",type:["object"],schemaType:["boolean","object"],allowUndefined:!0,trackErrors:!0,error:{message:"must NOT have additional properties",params:({params:K})=>U._`{additionalProperty: ${K.additionalProperty}}`},code(K){let{gen:z,schema:G,parentSchema:H,data:W,errsCount:X,it:Z}=K;if(!X)throw Error("ajv implementation error");let{allErrors:q,opts:V}=Z;if(Z.props=!0,V.removeAdditional!=="all"&&(0,Q.alwaysValidSchema)(Z,G))return;let w=(0,Y.allSchemaProperties)(H.properties),M=(0,Y.allSchemaProperties)(H.patternProperties);F(),K.ok(U._`${X} === ${I.default.errors}`);function F(){z.forIn("key",W,(T)=>{if(!w.length&&!M.length)D(T);else z.if(N(T),()=>D(T))})}function N(T){let B;if(w.length>8){let E=(0,Q.schemaRefOrVal)(Z,H.properties,"properties");B=(0,Y.isOwnProperty)(z,E,T)}else if(w.length)B=(0,U.or)(...w.map((E)=>U._`${T} === ${E}`));else B=U.nil;if(M.length)B=(0,U.or)(B,...M.map((E)=>U._`${(0,Y.usePattern)(K,E)}.test(${T})`));return(0,U.not)(B)}function O(T){z.code(U._`delete ${W}[${T}]`)}function D(T){if(V.removeAdditional==="all"||V.removeAdditional&&G===!1){O(T);return}if(G===!1){if(K.setParams({additionalProperty:T}),K.error(),!q)z.break();return}if(typeof G=="object"&&!(0,Q.alwaysValidSchema)(Z,G)){let B=z.name("valid");if(V.removeAdditional==="failing")P(T,B,!1),z.if((0,U.not)(B),()=>{K.reset(),O(T)});else if(P(T,B),!q)z.if((0,U.not)(B),()=>z.break())}}function P(T,B,E){let C={keyword:"additionalProperties",dataProp:T,dataPropType:Q.Type.Str};if(E===!1)Object.assign(C,{compositeRule:!0,createErrors:!1,allErrors:!1});K.subschema(C,B)}}};$.default=J}),Kc0=j0(($)=>{Object.defineProperty($,"__esModule",{value:!0});let Y=iQ(),U=Z5(),I=v1(),Q=oe(),J={keyword:"properties",type:"object",schemaType:"object",code(K){let{gen:z,schema:G,parentSchema:H,data:W,it:X}=K;if(X.opts.removeAdditional==="all"&&H.additionalProperties===void 0)Q.default.code(new Y.KeywordCxt(X,Q.default,"additionalProperties"));let Z=(0,U.allSchemaProperties)(G);for(let F of Z)X.definedProperties.add(F);if(X.opts.unevaluated&&Z.length&&X.props!==!0)X.props=I.mergeEvaluated.props(z,(0,I.toHash)(Z),X.props);let q=Z.filter((F)=>!(0,I.alwaysValidSchema)(X,G[F]));if(q.length===0)return;let V=z.name("valid");for(let F of q){if(w(F))M(F);else{if(z.if((0,U.propertyInData)(z,W,F,X.opts.ownProperties)),M(F),!X.allErrors)z.else().var(V,!0);z.endIf()}K.it.definedProperties.add(F),K.ok(V)}function w(F){return X.opts.useDefaults&&!X.compositeRule&&G[F].default!==void 0}function M(F){K.subschema({keyword:"properties",schemaProp:F,dataProp:F},V)}}};$.default=J}),zc0=j0(($)=>{Object.defineProperty($,"__esModule",{value:!0});let Y=Z5(),U=F1(),I=v1(),Q=v1(),J={keyword:"patternProperties",type:"object",schemaType:"object",code(K){let{gen:z,schema:G,data:H,parentSchema:W,it:X}=K,{opts:Z}=X,q=(0,Y.allSchemaProperties)(G),V=q.filter((P)=>(0,I.alwaysValidSchema)(X,G[P]));if(q.length===0||V.length===q.length&&(!X.opts.unevaluated||X.props===!0))return;let w=Z.strictSchema&&!Z.allowMatchingProperties&&W.properties,M=z.name("valid");if(X.props!==!0&&!(X.props instanceof U.Name))X.props=(0,Q.evaluatedPropsToName)(z,X.props);let{props:F}=X;N();function N(){for(let P of q){if(w)O(P);if(X.allErrors) Line truncated
\x00`,x+=D4(E,2),x+=z.magic,x+=D4(M,2),x+=D4(F,2),x+=D4(B.crc32,4),x+=D4(B.compressedSize,4),x+=D4(B.uncompressedSize,4),x+=D4(H.length,2),x+=D4(N.length,2);var g=iO.LOCAL_FILE_HEADER+x+H+N,i=iO.CENTRAL_FILE_HEADER+D4(b,2)+x+D4(Z.length,2)+"\x00\x00\x00\x00"+D4(C,4)+D4(I,4)+H+N+Z;return{fileRecord:g,dirRecord:i}},Ha0=function($,Y,U,I,Q){var J="",K=BJ.transformTo("string",Q(I));return J=iO.CENTRAL_DIRECTORY_END+"\x00\x00\x00\x00"+D4($,2)+D4($,2)+D4(Y,4)+D4(U,4)+D4(K.length,2)+K,J},Wa0=function($){var Y="";return Y=iO.DATA_DESCRIPTOR+D4($.crc32,4)+D4($.compressedSize,4)+D4($.uncompressedSize,4),Y};function O5($,Y,U,I){AJ.call(this,"ZipFileWorker"),this.bytesWritten=0,this.zipComment=Y,this.zipPlatform=U,this.encodeFileName=I,this.streamFiles=$,this.accumulate=!1,this.contentBuffer=[],this.dirRecords=[],this.currentSourceOffset=0,this.entriesCount=0,this.currentFile=null,this._sources=[]}BJ.inherits(O5,AJ);O5.prototype.push=function($){var Y=$.meta.percent||0,U=this.entriesCount,I=this._sources.length;if(this.accumulate)this.contentBuffer.push($);else this.bytesWritten+=$.data.length,AJ.prototype.push.call(this,{data:$.data,meta:{currentFile:this.currentFile,percent:U?(Y+100*(U-I-1))/U:100}})};O5.prototype.openedSource=function($){this.currentSourceOffset=this.bytesWritten,this.currentFile=$.file.name;var Y=this.streamFiles&&!$.file.dir;if(Y){var U=T90($,Y,!1,this.currentSourceOffset,this.zipPlatform,this.encodeFileName);this.push({data:U.fileRecord,meta:{percent:0}})}else this.accumulate=!0};O5.prototype.closedSource=function($){this.accumulate=!1;var Y=this.streamFiles&&!$.file.dir,U=T90($,Y,!0,this.currentSourceOffset,this.zipPlatform,this.encodeFileName);if(this.dirRecords.push(U.dirRecord),Y)this.push({data:Wa0($),meta:{percent:100}});else{this.push({data:U.fileRecord,meta:{percent:0}});while(this.contentBuffer.length)this.push(this.contentBuffer.shift())}this.currentFile=null};O5.prototype.flush=function(){var $=this.bytesWritten;for(var Y=0;Y<this.dirRecords.length;Y++)this.push({data:this.dirRecords[Y],meta:{percent:100}});var U=this.bytesWritten-$,I=Ha0(this.dirRecords.length,U,$,this.zipComment,this.encodeFileName);this.push({data:I,meta:{percent:100}})};O5.prototype.prepareNextSource=function(){if(this.previous=this._sources.shift(),this.openedSource(this.previous.streamInfo),this.isPaused)this.previous.pause();else this.previous.resume()};O5.prototype.registerPrevious=function($){this._sources.push($);var Y=this;return $.on("data",function(U){Y.processChunk(U)}),$.on("end",function(){if(Y.closedSource(Y.previous.streamInfo),Y._sources.length)Y.prepareNextSource();else Y.end()}),$.on("error",function(U){Y.error(U)}),this};O5.prototype.resume=function(){if(!AJ.prototype.resume.call(this))return!1;if(!this.previous&&this._sources.length)return this.prepareNextSource(),!0;if(!this.previous&&!this._sources.length&&!this.generatedError)return this.end(),!0};O5.prototype.error=function($){var Y=this._sources;if(!AJ.prototype.error.call(this,$))return!1;for(var U=0;U<Y.length;U++)try{Y[U].error($)}catch(I){}return!0};O5.prototype.lock=function(){AJ.prototype.lock.call(this);var $=this._sources;for(var Y=0;Y<$.length;Y++)$[Y].lock()};E90.exports=O5});var C90=j((Va0)=>{var Xa0=Fk(),Za0=j90(),qa0=function($,Y){var U=$||Y,I=Xa0[U];if(!I)throw Error(U+" is not a valid compression method !");return I};Va0.generateWorker=function($,Y,U){var I=new Za0(Y.streamFiles,U,Y.platform,Y.encodeFileName),Q=0;try{$.forEach(function(J,K){Q++;var z=qa0(K.options.compression,Y.compression),G=K.options.compressionOptions||Y.compressionOptions||{},H=K.dir,W=K.date;K._compressWorker(z,G).withStreamInfo("file",{name:J,dir:H,date:W,comment:K.comment||"",unixPermissions:K.unixPermissions,dosPermissions:K.dosPermissions}).pipe(I)}),I.entriesCount=Q}catch(J){I.error(J)}return I}});var _90=j(($o1,R90)=>{var Fa0=d4(),cO=q$();function AW($,Y){cO.call(this,"Nodejs stream input adapter for "+$),this._upstreamEnded=!1,this._bindStream(Y)}Fa0.inherits(AW,cO);AW.prototype._bindStream=function($){var Y=this;this._stream=$,$.pause(),$.on("data",function(U){Y.push({data:U,meta:{percent:0}})}).on("error",function(U){if(Y.isPaused)this.generatedError=U;else Y.error(U)}).on("end",function(){if(Y.isPaused)Y._upstreamEnded=!0;else Y.end()})};AW.prototype.pause=function(){if(!cO.prototype.pause.call(this))return!1;return this._stream.pause(),!0};AW.prototype.resume=function(){if(!cO.prototype.resume.call(this))return!1;if(this._upstreamEnded)this.end();else this._stream.resume();return!0};R90.exports=AW});var b90=j((Yo1,u90)=>{var wa0=ZJ(),PW=d4(),g90=q$(),Ma0=By(),y90=Ay(),v90=AO(),Oa0=S$0(),Na0=C90(),S90=UW(),Da0=_90(),k90=function($,Y,U){var I=PW.getTypeOf(Y),Q,J=PW.extend(U||{},y90);if(J.date=J.date||new Date,J.compression!==null)J.compression=J.compression.toUpperCase();if(typeof J.unixPermissions==="string")J.unixPermissions=parseInt(J.unixPermissions,8);if(J.unixPermissions&&J.unixPermissions&16384)J.dir=!0;if(J.dosPermissions&&J.dosPermission Line truncated
`)}openNode($,Y){let U=this.tos,I=this._xml;if(U&&this.open)I.push(">");this._stack.push($),I.push("<"),I.push($),ek(I,Y),this.leaf=!0,this.open=!0}addAttribute($,Y){if(!this.open)throw Error("Cannot write attributes to node if it is not open");if(Y!==void 0)_70(this._xml,$,Y)}addAttributes($){if(!this.open)throw Error("Cannot write attributes to node if it is not open");ek(this._xml,$)}writeText($){let Y=this._xml;if(this.open)Y.push(">"),this.open=!1;this.leaf=!1,Y.push(R70.xmlEncode($.toString()))}writeXml($){if(this.open)this._xml.push(">"),this.open=!1;this.leaf=!1,this._xml.push($)}closeNode(){let $=this._stack.pop(),Y=this._xml;if(this.leaf)Y.push("/>");else Y.push("</"),Y.push($),Y.push(">");this.open=!1,this.leaf=!1}leafNode($,Y,U){if(this.openNode($,Y),U!==void 0)this.writeText(U);this.closeNode()}closeAll(){while(this._stack.length)this.closeNode()}addRollback(){return this._rollbacks.push({xml:this._xml.length,stack:this._stack.length,leaf:this.leaf,open:this.open}),this.cursor}commit(){this._rollbacks.pop()}rollback(){let $=this._rollbacks.pop();if(this._xml.length>$.xml)this._xml.splice($.xml,this._xml.length-$.xml);if(this._stack.length>$.stack)this._stack.splice($.stack,this._stack.length-$.stack);this.leaf=$.leaf,this.open=$.open}get xml(){return this.closeAll(),this._xml.join("")}}$x.StdDocAttributes={version:"1.0",encoding:"UTF-8",standalone:"yes"};v70.exports=$x});var Yx=j((Z01)=>{var S70=typeof TextDecoder>"u"?null:new TextDecoder("utf-8");function X01($){if(typeof $==="string")return $;if(S70)return S70.decode($);return $.toString()}Z01.bufferToString=X01});var x70=j((g70)=>{Object.defineProperty(g70,"__esModule",{value:!0});g70.CHAR=`
\r -퟿-�\uD800\uDC00-\uDBFF\uDFFF`;g70.S=` \r
`;g70.NAME_START_CHAR=":A-Z_a-zÀ-ÖØ-öø-˿Ͱ-ͽͿ-῿‌‍⁰-↏Ⰰ-⿯、-퟿豈-﷏ﷰ-�\uD800\uDC00-\uDB7F\uDFFF";g70.NAME_CHAR="-"+g70.NAME_START_CHAR+".0-9·̀-ͯ‿-⁀";g70.CHAR_RE=new RegExp("^["+g70.CHAR+"]$","u");g70.S_RE=new RegExp("^["+g70.S+"]+$","u");g70.NAME_START_CHAR_RE=new RegExp("^["+g70.NAME_START_CHAR+"]$","u");g70.NAME_CHAR_RE=new RegExp("^["+g70.NAME_CHAR+"]$","u");g70.NAME_RE=new RegExp("^["+g70.NAME_START_CHAR+"]["+g70.NAME_CHAR+"]*$","u");g70.NMTOKEN_RE=new RegExp("^["+g70.NAME_CHAR+"]+$","u");var Ux=9,Ix=10,Qx=13,Jx=32;g70.S_LIST=[Jx,Ix,Qx,Ux];function V01($){return $>=Jx&&$<=55295||$===Ix||$===Qx||$===Ux||$>=57344&&$<=65533||$>=65536&&$<=1114111}g70.isChar=V01;function L01($){return $===Jx||$===Ix||$===Qx||$===Ux}g70.isS=L01;function h70($){return $>=65&&$<=90||$>=97&&$<=122||$===58||$===95||$===8204||$===8205||$>=192&&$<=214||$>=216&&$<=246||$>=248&&$<=767||$>=880&&$<=893||$>=895&&$<=8191||$>=8304&&$<=8591||$>=11264&&$<=12271||$>=12289&&$<=55295||$>=63744&&$<=64975||$>=65008&&$<=65533||$>=65536&&$<=983039}g70.isNameStartChar=h70;function F01($){return h70($)||$>=48&&$<=57||$===45||$===46||$===183||$>=768&&$<=879||$>=8255&&$<=8256}g70.isNameChar=F01});var l70=j((n70)=>{Object.defineProperty(n70,"__esModule",{value:!0});n70.CHAR="\x01-퟿-�\uD800\uDC00-\uDBFF\uDFFF";n70.RESTRICTED_CHAR="\x01-\b\v\f\x0E-\x1F-„†-Ÿ";n70.S=` \r
`;n70.NAME_START_CHAR=":A-Z_a-zÀ-ÖØ-öø-˿Ͱ-ͽͿ-῿‌‍⁰-↏Ⰰ-⿯、-퟿豈-﷏ﷰ-�\uD800\uDC00-\uDB7F\uDFFF";n70.NAME_CHAR="-"+n70.NAME_START_CHAR+".0-9·̀-ͯ‿-⁀";n70.CHAR_RE=new RegExp("^["+n70.CHAR+"]$","u");n70.RESTRICTED_CHAR_RE=new RegExp("^["+n70.RESTRICTED_CHAR+"]$","u");n70.S_RE=new RegExp("^["+n70.S+"]+$","u");n70.NAME_START_CHAR_RE=new RegExp("^["+n70.NAME_START_CHAR+"]$","u");n70.NAME_CHAR_RE=new RegExp("^["+n70.NAME_CHAR+"]$","u");n70.NAME_RE=new RegExp("^["+n70.NAME_START_CHAR+"]["+n70.NAME_CHAR+"]*$","u");n70.NMTOKEN_RE=new RegExp("^["+n70.NAME_CHAR+"]+$","u");var f70=9,u70=10,b70=13,i70=32;n70.S_LIST=[i70,u70,b70,f70];function C01($){return $>=1&&$<=55295||$>=57344&&$<=65533||$>=65536&&$<=1114111}n70.isChar=C01;function R01($){return $>=1&&$<=8||$===11||$===12||$>=14&&$<=31||$>=127&&$<=132||$>=134&&$<=159}n70.isRestrictedChar=R01;function _01($){return $===9||$===10||$===13||$>31&&$<127||$===133||$>159&&$<=55295||$>=57344&&$<=65533||$>=65536&&$<=1114111}n70.isCharAndNotRestricted=_01;function v01($){return $===i70||$===u70||$===b70||$===f70}n70.isS=v01;function c70($){return $>=65&&$<=90||$>=97&&$<=122||$===58||$===95||$===8204||$===8205||$>=192&&$<=214||$>=216&&$<=246||$>=248&&$<=767||$>=880&&$<=893||$>=895&&$<=8191||$>=8304&&$<=8591||$>=11264&&$<=12271||$>=12289&&$<=55295||$>=63744&&$<=64975||$>=65008&&$<=65533||$>=65536&&$<=983039}n70.isNameStartChar=c70;function S01($){return c70($)||$>=48&&$<=57||$===45||$===46||$===183||$>=768&&$<=879||$>=8255&&$<=8256}n70.isNameChar=S01});var s70=j((r70)=>{Object.defineProperty(r70,"__esModule",{value:!0});r70.NC_NAME_START_CHAR="A-Z_a-zÀ-ÖØ-öø-˿Ͱ-ͽͿ-῿‌-‍⁰-↏Ⰰ-⿯、-퟿豈-﷏ﷰ-�\uD800\uDC00-\uDB7F\uDFFF";r70.NC_NAME_CHAR="-"+r70.NC_NAME_START_CHAR+".0-9·̀-ͯ‿-⁀";r70.NC_NAME_START_CHAR_RE=new RegExp("^["+r70.NC_NAME_START_CHAR+"]$","u");r70.NC_NAME_CHAR_RE=new RegExp("^["+r70.NC_NAME_CHAR+"]$","u");r70.NC_NAME_RE=new RegExp("^["+r70.NC_NAME_START_CHAR+"]["+r70.NC_NAME_CHAR+"]*$","u");function o70($){return $>=65&&$<=90||$===95||$>=97&&$<=122||$>=192&&$<=214||$>=216&&$<=246||$>=248&&$<=767||$>=880&&$<=893||$>=895&&$<=8191||$>=8204&&$<=8205||$>=8304&&$<=8591||$>=11264&&$<=12271||$>=12289&&$<=55295||$>=63744&&$<=64975||$>=65008&&$<=65533||$>=65536&&$<=983039}r70.isNCNameStartChar=o70;function l01($){return o70($)||($===45||$===46||$>=48&&$<=57||$===183||$>=768&&$<=879||$>=8255&&$<=8256)}r70.isNCNameChar=l01});var M20=j((w20)=>{Object.defineProperty(w20,"__esModule",{value:!0});var yJ=x70(),e01=l70(),Ox=s70(),r8=yJ.isS,$11=yJ.isChar,xW=yJ.isNameStartChar,a70=yJ.isNameChar,X20=yJ.S_LIST,Y11=yJ.NAME_RE,U11=e01.isChar,I11=Ox.isNCNameStartChar,Q11=Ox.isNCNameChar,J11=Ox.NC_NAME_RE,wN="http://www.w3.org/XML/1998/namespace",gJ="http://www.w3.org/2000/xmlns/",K11={__proto__:null,xml:wN,xmlns:gJ},z11={__proto__:null,amp:"&",gt:">",lt:"<",quot:'"',apos:"'"},u4=-1,q9=-2,t70=0,G11=1,zx=2,H11=3,vJ=4,W11=5,X11=6,Z11=7,Gx=8,q11=9,V11=10,L11=11,F11=12,y8=13,ZN=14,Hx=15,w11=16,Wx=17,M11=18,O11=19,Xx=20,N11=21,D11=22,B11=23,e70=24,Zx=25,qN=26,$20=27,A11=28,P11=29,Y20=30,T11=31,E11=32,VU=33,j11=34,qx=35,fW=36,Vx=37,C11=38,U20=39,I20=40,R11=41,Q20=42,_11=43,v11=44,Lx=9,D5=10,Fx=13,J20=32,K20=33,Z20=34,uW=38,q20=39,VN=45,LN=47,S11=59,I2=60,SJ=61,j6=62,t6=63,V20=91,hJ=93,z20=133,G20=8232,FN=($)=>$===Z20||$===q20,L20=[Z20,q20],h11=[...L20,V20,j6],g11=[...L20,I2,hJ],y11=[SJ,t6,...X20],k11=[...X20,j6,uW,I2];function Mx($,Y,U){switch(Y){case"xml":if(U!==wN)$.fail(`xml prefix must be bound to ${wN}.`);break;case"xmlns":if(U!==gJ)$.fail(`xmlns prefix must be bound to ${gJ}.`);break;default:}switch(U){case gJ:$.fail(Y===""?`the default namespace may not be set to ${U}.`:`may not assign a prefix (even "xmlns") to the URI ${gJ}.`);break;case wN:switch(Y){case"xml":break;case"":$.fail(`the default namespace may not be set to ${U}.`);break;default:$.fail("may not assign the xml namespace to another prefix.")}break;default:}}function x11($,Y){for(let U of Object.keys(Y))Mx($,U,Y[U])}var f11=($)=>J11.test($),u11=($)=>Y11.test($),LU=0,H20=1,wx=2;w20.EVENTS=["xmldecl","text","processinginstruction","doctype","comment","opentagstart","attribute","opentag","closetag","cdata","error","end","ready"];var W20={xmldecl:"xmldeclHandler",text:"textHandler",processinginstruction:"piHandler",doctype:"doctypeHandler",comment:"commentHandler",opentagstart:"openTagStartHandler",attribute:"attributeHandler",opentag:"openTagHandler",closetag:"closeTagHandler",cdata:"cdataHandler",error:"errorHandler",end:"endHandler",ready:"readyHandler"};class F20{constructor($){this.opt=$!==null&&$!==void 0?$:{},this.fragmentOpt=!!this.opt.fragment;let Y=this.xmlnsOpt=!!this.opt.xmlns;if(this.trackPosition=this.opt.position!==!1,this.fileName=this.opt.fileName,Y){this.nameStartCheck=I11,this.nameCheck=Q11,this.isName=f11,this.processAttribs=this.processAttribsNS,this.pushAttrib=this.pushAttribNS,this.ns=Object.assign({__proto__:null},K11);let U=this.opt.additionalNamesp Line truncated
`,Y=this.i}}captureToChar($){let{i:Y}=this,{chunk:U}=this;while(!0){let I=this.getCode();switch(I){case q9:this.text+=`${U.slice(Y,this.prevI)}
`,Y=this.i,I=D5;break;case u4:return this.text+=U.slice(Y),!1;default:}if(I===$)return this.text+=U.slice(Y,this.prevI),!0}}captureNameChars(){let{chunk:$,i:Y}=this;while(!0){let U=this.getCode();if(U===u4)return this.name+=$.slice(Y),u4;if(!a70(U))return this.name+=$.slice(Y,this.prevI),U===q9?D5:U}}skipSpaces(){while(!0){let $=this.getCodeNorm();if($===u4||!r8($))return $}}setXMLVersion($){if(this.currentXMLVersion=$,$==="1.0")this.isChar=$11,this.getCode=this.getCode10;else this.isChar=U11,this.getCode=this.getCode11}sBegin(){if(this.chunk.charCodeAt(0)===65279)this.i++,this.column++;this.state=G11}sBeginWhitespace(){let $=this.i,Y=this.skipSpaces();if(this.prevI!==$)this.xmlDeclPossible=!1;switch(Y){case I2:if(this.state=Hx,this.text.length!==0)throw Error("no-empty text at start");break;case u4:break;default:this.unget(),this.state=y8,this.xmlDeclPossible=!1}}sDoctype(){var $;let Y=this.captureTo(h11);switch(Y){case j6:{($=this.doctypeHandler)===null||$===void 0||$.call(this,this.text),this.text="",this.state=y8,this.doctype=!0;break}case u4:break;default:if(this.text+=String.fromCodePoint(Y),Y===V20)this.state=vJ;else if(FN(Y))this.state=H11,this.q=Y}}sDoctypeQuote(){let $=this.q;if(this.captureToChar($))this.text+=String.fromCodePoint($),this.q=null,this.state=zx}sDTD(){let $=this.captureTo(g11);if($===u4)return;if(this.text+=String.fromCodePoint($),$===hJ)this.state=zx;else if($===I2)this.state=X11;else if(FN($))this.state=W11,this.q=$}sDTDQuoted(){let $=this.q;if(this.captureToChar($))this.text+=String.fromCodePoint($),this.state=vJ,this.q=null}sDTDOpenWaka(){let $=this.getCodeNorm();switch(this.text+=String.fromCodePoint($),$){case K20:this.state=Z11,this.openWakaBang="";break;case t6:this.state=L11;break;default:this.state=vJ}}sDTDOpenWakaBang(){let $=String.fromCodePoint(this.getCodeNorm()),Y=this.openWakaBang+=$;if(this.text+=$,Y!=="-")this.state=Y==="--"?Gx:vJ,this.openWakaBang=""}sDTDComment(){if(this.captureToChar(VN))this.text+="-",this.state=q11}sDTDCommentEnding(){let $=this.getCodeNorm();this.text+=String.fromCodePoint($),this.state=$===VN?V11:Gx}sDTDCommentEnded(){let $=this.getCodeNorm();if(this.text+=String.fromCodePoint($),$===j6)this.state=vJ;else this.fail("malformed comment."),this.state=Gx}sDTDPI(){if(this.captureToChar(t6))this.text+="?",this.state=F11}sDTDPIEnding(){let $=this.getCodeNorm();if(this.text+=String.fromCodePoint($),$===j6)this.state=vJ}sText(){if(this.tags.length!==0)this.handleTextInRoot();else this.handleTextOutsideRoot()}sEntity(){let{i:$}=this,{chunk:Y}=this;$:while(!0)switch(this.getCode()){case q9:this.entity+=`${Y.slice($,this.prevI)}
`,$=this.i;break;case S11:{let{entityReturnState:U}=this,I=this.entity+Y.slice($,this.prevI);this.state=U;let Q;if(I==="")this.fail("empty entity name."),Q="&;";else Q=this.parseEntity(I),this.entity="";if(U!==y8||this.textHandler!==void 0)this.text+=Q;break $}case u4:this.entity+=Y.slice($);break $;default:}}sOpenWaka(){let $=this.getCode();if(xW($))this.state=j11,this.unget(),this.xmlDeclPossible=!1;else switch($){case LN:this.state=_11,this.xmlDeclPossible=!1;break;case K20:this.state=w11,this.openWakaBang="",this.xmlDeclPossible=!1;break;case t6:this.state=B11;break;default:this.fail("disallowed character in tag name"),this.state=y8,this.xmlDeclPossible=!1}}sOpenWakaBang(){switch(this.openWakaBang+=String.fromCodePoint(this.getCodeNorm()),this.openWakaBang){case"[CDATA[":if(!this.sawRoot&&!this.reportedTextBeforeRoot)this.fail("text data outside of root node."),this.reportedTextBeforeRoot=!0;if(this.closedRoot&&!this.reportedTextAfterRoot)this.fail("text data outside of root node."),this.reportedTextAfterRoot=!0;this.state=Xx,this.openWakaBang="";break;case"--":this.state=Wx,this.openWakaBang="";break;case"DOCTYPE":if(this.state=zx,this.doctype||this.sawRoot)this.fail("inappropriately located doctype declaration.");this.openWakaBang="";break;default:if(this.openWakaBang.length>=7)this.fail("incorrect syntax.")}}sComment(){if(this.captureToChar(VN))this.state=M11}sCommentEnding(){var $;let Y=this.getCodeNorm();if(Y===VN)this.state=O11,($=this.commentHandler)===null||$===void 0||$.call(this,this.text),this.text="";else this.text+=`-${String.fromCodePoint(Y)}`,this.state=Wx}sCommentEnded(){let $=this.getCodeNorm();if($!==j6)this.fail("malformed comment."),this.text+=`--${String.fromCodePoint($)}`,this.state=Wx;else this.state=y8}sCData(){if(this.captureToChar(hJ))this.state=N11}sCDataEnding(){let $=this.getCodeNorm();if($===hJ)this.state=D11;else this.text+=`]${String.fromCodePoint($)}`,this.state=Xx}sCDataEnding2(){var $;let Y=this.getCodeNorm();switch(Y){case j6:{($=this.cdataHandler)===null||$===void 0||$.call(this,this.text),this.text="",this.state=y8;break}case hJ:this.text+="]";break;default:this.text+=`]]${String.fromCodePoint(Y)}`,this.state=Xx}}sPIFirstChar(){let $=this.getCodeNorm();if(this.nameStartCheck($))this.piTarget+=String.fromCodePoint($),this.state=e70;else if($===t6||r8($))this.fail("processing instruction without a target."),this.state=$===t6?qN:Zx;else this.fail("disallowed character in processing instruction name."),this.piTarget+=String.fromCodePoint($),this.state=e70}sPIRest(){let{chunk:$,i:Y}=this;while(!0){let U=this.getCodeNorm();if(U===u4){this.piTarget+=$.slice(Y);return}if(!this.nameCheck(U)){this.piTarget+=$.slice(Y,this.prevI);let I=U===t6;if(I||r8(U))if(this.piTarget==="xml"){if(!this.xmlDeclPossible)this.fail("an XML declaration must be at the start of the document.");this.state=I?VU:$20}else this.state=I?qN:Zx;else this.fail("disallowed character in processing instruction name."),this.piTarget+=String.fromCodePoint(U);break}}}sPIBody(){if(this.text.length===0){let $=this.getCodeNorm();if($===t6)this.state=qN;else if(!r8($))this.text=String.fromCodePoint($)}else if(this.captureToChar(t6))this.state=qN}sPIEnding(){var $;let Y=this.getCodeNorm();if(Y===j6){let{piTarget:U}=this;if(U.toLowerCase()==="xml")this.fail("the XML declaration must appear at the start of the document.");($=this.piHandler)===null||$===void 0||$.call(this,{target:U,body:this.text}),this.piTarget=this.text="",this.state=y8}else if(Y===t6)this.text+="?";else this.text+=`?${String.fromCodePoint(Y)}`,this.state=Zx;this.xmlDeclPossible=!1}sXMLDeclNameStart(){let $=this.skipSpaces();if($===t6){this.state=VU;return}if($!==u4)this.state=A11,this.name=String.fromCodePoint($)}sXMLDeclName(){let $=this.captureTo(y11);if($===t6){this.state=VU,this.name+=this.text,this.text="",this.fail("XML declaration is incomplete.");return}if(!(r8($)||$===SJ))return;if(this.name+=this.text,this.text="",!this.xmlDeclExpects.includes(this.name))switch(this.name.length){case 0:this.fail("did not expect any more name/value pairs.");break;case 1:this.fail(`expected the name ${this.xmlDeclExpects[0]}.`);break;default:this.fail(`expected one of ${this.xmlDeclExpects.join(", ")}`)}this.state=$===SJ?Y20:P11}sXMLDeclEq(){let $=this.getCodeNorm();if($===t6){this.state=VU,this.fail("XML declaration is incomplete.");return}if(r8($))return;if($!==SJ)this.fail("value required.");this.state=Y20}sXMLDeclValueStart(){let $=this.getCodeNorm();if($===t6){this.state=VU,this.fail("XML declaration is incomplete.");return}if(r8($))return;if(!FN($))this.fail("value must be quoted."),this.q=J20;else this.q=$;this.state=T11}sXMLDeclValue(){let $=this.captureTo([this.q,t6]);if($===t6){this.state=VU,this.text="",this.fail("XML declaration is incomplete.");return}if($===u4)return;let Y=this.text;switch(this.text="",this.name){case"version":{this.xmlDeclExpects=["encoding","standalone"];let U=Y;if(this.xmlDecl.version=U,!/^1\.[0-9]+$/.test(U))this.fail("ver Line truncated
`;$=this.i,Y=LU;break;case u4:if(I!==void 0)this.text+=U.slice($);break $;default:Y=LU}this.forbiddenState=Y}handleTextOutsideRoot(){let{i:$}=this,{chunk:Y,textHandler:U}=this,I=!1;$:while(!0){let Q=this.getCode();switch(Q){case I2:{if(this.state=Hx,U!==void 0){let{text:J}=this,K=Y.slice($,this.prevI);if(J.length!==0)U(J+K),this.text="";else if(K.length!==0)U(K)}break $}case uW:if(this.state=ZN,this.entityReturnState=y8,U!==void 0)this.text+=Y.slice($,this.prevI);I=!0;break $;case q9:if(U!==void 0)this.text+=`${Y.slice($,this.prevI)}
`;$=this.i;break;case u4:if(U!==void 0)this.text+=Y.slice($);break $;default:if(!r8(Q))I=!0}}if(!I)return;if(!this.sawRoot&&!this.reportedTextBeforeRoot)this.fail("text data outside of root node."),this.reportedTextBeforeRoot=!0;if(this.closedRoot&&!this.reportedTextAfterRoot)this.fail("text data outside of root node."),this.reportedTextAfterRoot=!0}pushAttribNS($,Y){var U;let{prefix:I,local:Q}=this.qname($),J={name:$,prefix:I,local:Q,value:Y};if(this.attribList.push(J),(U=this.attributeHandler)===null||U===void 0||U.call(this,J),I==="xmlns"){let K=Y.trim();if(this.currentXMLVersion==="1.0"&&K==="")this.fail("invalid attempt to undefine prefix in XML 1.0");this.topNS[Q]=K,Mx(this,Q,K)}else if($==="xmlns"){let K=Y.trim();this.topNS[""]=K,Mx(this,"",K)}}pushAttribPlain($,Y){var U;let I={name:$,value:Y};this.attribList.push(I),(U=this.attributeHandler)===null||U===void 0||U.call(this,I)}end(){var $,Y;if(!this.sawRoot)this.fail("document must contain a root element.");let{tags:U}=this;while(U.length>0){let Q=U.pop();this.fail(`unclosed tag: ${Q.name}`)}if(this.state!==t70&&this.state!==y8)this.fail("unexpected end.");let{text:I}=this;if(I.length!==0)($=this.textHandler)===null||$===void 0||$.call(this,I),this.text="";return this._closed=!0,(Y=this.endHandler)===null||Y===void 0||Y.call(this),this._init(),this}resolve($){var Y,U;let I=this.topNS[$];if(I!==void 0)return I;let{tags:Q}=this;for(let J=Q.length-1;J>=0;J--)if(I=Q[J].ns[$],I!==void 0)return I;if(I=this.ns[$],I!==void 0)return I;return(U=(Y=this.opt).resolvePrefix)===null||U===void 0?void 0:U.call(Y,$)}qname($){let Y=$.indexOf(":");if(Y===-1)return{prefix:"",local:$};let U=$.slice(Y+1),I=$.slice(0,Y);if(I===""||U===""||U.includes(":"))this.fail(`malformed name: ${$}.`);return{prefix:I,local:U}}processAttribsNS(){var $;let{attribList:Y}=this,U=this.tag;{let{prefix:J,local:K}=this.qname(U.name);U.prefix=J,U.local=K;let z=U.uri=($=this.resolve(J))!==null&&$!==void 0?$:"";if(J!==""){if(J==="xmlns")this.fail('tags may not have "xmlns" as prefix.');if(z==="")this.fail(`unbound namespace prefix: ${JSON.stringify(J)}.`),U.uri=J}}if(Y.length===0)return;let{attributes:I}=U,Q=new Set;for(let J of Y){let{name:K,prefix:z,local:G}=J,H,W;if(z==="")H=K==="xmlns"?gJ:"",W=K;else{if(H=this.resolve(z),H===void 0)this.fail(`unbound namespace prefix: ${JSON.stringify(z)}.`),H=z;W=`{${H}}${G}`}if(Q.has(W))this.fail(`duplicate attribute: ${W}.`);Q.add(W),J.uri=H,I[K]=J}this.attribList=[]}processAttribsPlain(){let{attribList:$}=this,Y=this.tag.attributes;for(let{name:U,value:I}of $){if(Y[U]!==void 0)this.fail(`duplicate attribute: ${U}.`);Y[U]=I}this.attribList=[]}openTag(){var $;this.processAttribs();let{tags:Y}=this,U=this.tag;U.isSelfClosing=!1,($=this.openTagHandler)===null||$===void 0||$.call(this,U),Y.push(U),this.state=y8,this.name=""}openSelfClosingTag(){var $,Y,U;this.processAttribs();let{tags:I}=this,Q=this.tag;if(Q.isSelfClosing=!0,($=this.openTagHandler)===null||$===void 0||$.call(this,Q),(Y=this.closeTagHandler)===null||Y===void 0||Y.call(this,Q),(this.tag=(U=I[I.length-1])!==null&&U!==void 0?U:null)===null)this.closedRoot=!0;this.state=y8,this.name=""}closeTag(){let{tags:$,name:Y}=this;if(this.state=y8,this.name="",Y===""){this.fail("weird empty close tag."),this.text+="</>";return}let U=this.closeTagHandler,I=$.length;while(I-- >0){let Q=this.tag=$.pop();if(this.topNS=Q.ns,U===null||U===void 0||U(Q),Q.name===Y)break;this.fail("unexpected close tag.")}if(I===0)this.closedRoot=!0;else if(I<0)this.fail(`unmatched closing tag: ${Y}.`),this.text+=`</${Y}>`}parseEntity($){if($[0]!=="#"){let U=this.ENTITIES[$];if(U!==void 0)return U;return this.fail(this.isName($)?"undefined entity.":"disallowed character in entity name."),`&${$};`}let Y=NaN;if($[1]==="x"&&/^#x[0-9a-f]+$/i.test($))Y=parseInt($.slice(2),16);else if(/^#[0-9]+$/.test($))Y=parseInt($.slice(1),10);if(!this.isChar(Y))return this.fail("malformed character entity."),`&${$};`;return String.fromCodePoint(Y)}}w20.SaxesParser=F20});var bW=j((fo1,O20)=>{var{SaxesParser:c11}=M20(),{PassThrough:n11}=g8(),{bufferToString:d11}=Yx();O20.exports=async function*($){if($.pipe&&!$[Symbol.asyncIterator])$=$.pipe(new n11);let Y=new c11,U;Y.on("error",(Q)=>{U=Q});let I=[];Y.on("opentag",(Q)=>I.push({eventType:"opentag",value:Q})),Y.on("text",(Q)=>I.push({eventType:"text",value:Q})),Y.on("closetag",(Q)=>I.push({eventType:"closetag",value:Q}));for await(let Q of $){if(Y.write(d11(Q)),U)throw U;yield I,I=[]}}});var g0=j((uo1,N20)=>{var p11=bW(),m11=a6();class kJ{prepare(){}render(){}parseOpen($){}parseText($){}parseClose($){}reconcile($,Y){}reset(){if(this.model=null,this.map)Object.values(this.map).forEach(($)=>{if($ instanceof kJ)$.reset();else if($.xform)$.xform.reset()})}mergeModel($){this.model=Object.assign(this.model||{},$)}async parse($){for await(let Y of $)for(let{eventType:U,value:I}of Y)if(U==="opentag")this.parseOpen(I);else if(U==="text")this.parseText(I);else if(U==="closetag"){if(!this.parseClose(I.name))return thLine truncated
<a:theme xmlns:a="http://schemas.openxmlformats.org/drawingml/2006/main" name="Office Theme"> <a:themeElements> <a:clrScheme name="Office"> <a:dk1> <a:sysClr val="windowText" lastClr="000000"/> </a:dk1> <a:lt1> <a:sysClr val="window" lastClr="FFFFFF"/> </a:lt1> <a:dk2> <a:srgbClr val="1F497D"/> </a:dk2> <a:lt2> <a:srgbClr val="EEECE1"/> </a:lt2> <a:accent1> <a:srgbClr val="4F81BD"/> </a:accent1> <a:accent2> <a:srgbClr val="C0504D"/> </a:accent2> <a:accent3> <a:srgbClr val="9BBB59"/> </a:accent3> <a:accent4> <a:srgbClr val="8064A2"/> </a:accent4> <a:accent5> <a:srgbClr val="4BACC6"/> </a:accent5> <a:accent6> <a:srgbClr val="F79646"/> </a:accent6> <a:hlink> <a:srgbClr val="0000FF"/> </a:hlink> <a:folHlink> <a:srgbClr val="800080"/> </a:folHlink> </a:clrScheme> <a:fontScheme name="Office"> <a:majorFont> <a:latin typeface="Cambria"/> <a:ea typeface=""/> <a:cs typeface=""/> <a:font script="Jpan" typeface="MS Pゴシック"/> <a:font script="Hang" typeface="맑은 고딕"/> <a:font script="Hans" typeface="宋体"/> <a:font script="Hant" typeface="新細明體"/> <a:font script="Arab" typeface="Times New Roman"/> <a:font script="Hebr" typeface="Times New Roman"/> <a:font script="Thai" typeface="Tahoma"/> <a:font script="Ethi" typeface="Nyala"/> <a:font script="Beng" typeface="Vrinda"/> <a:font script="Gujr" typeface="Shruti"/> <a:font script="Khmr" typeface="MoolBoran"/> <a:font script="Knda" typeface="Tunga"/> <a:font script="Guru" typeface="Raavi"/> <a:font script="Cans" typeface="Euphemia"/> <a:font script="Cher" typeface="Plantagenet Cherokee"/> <a:font script="Yiii" typeface="Microsoft Yi Baiti"/> <a:font script="Tibt" typeface="Microsoft Himalaya"/> <a:font script="Thaa" typeface="MV Boli"/> <a:font script="Deva" typeface="Mangal"/> <a:font script="Telu" typeface="Gautami"/> <a:font script="Taml" typeface="Latha"/> <a:font script="Syrc" typeface="Estrangelo Edessa"/> <a:font script="Orya" typeface="Kalinga"/> <a:font script="Mlym" typeface="Kartika"/> <a:font script="Laoo" typeface="DokChampa"/> <a:font script="Sinh" typeface="Iskoola Pota"/> <a:font script="Mong" typeface="Mongolian Baiti"/> <a:font script="Viet" typeface="Times New Roman"/> <a:font script="Uigh" typeface="Microsoft Uighur"/> <a:font script="Geor" typeface="Sylfaen"/> </a:majorFont> <a:minorFont> <a:latin typeface="Calibri"/> <a:ea typeface=""/> <a:cs typeface=""/> <a:font script="Jpan" typeface="MS Pゴシック"/> <a:font script="Hang" typeface="맑은 고딕"/> <a:font script="Hans" typeface="宋体"/> <a:font script="Hant" typeface="新細明體"/> <a:font script="Arab" typeface="Arial"/> <a:font script="Hebr" typeface="Arial"/> <a:font script="Thai" typeface="Tahoma"/> <a:font script="Ethi" typeface="Nyala"/> <a:font script="Beng" typeface="Vrinda"/> <a:font script="Gujr" typeface="Shruti"/> <a:font script="Khmr" typeface="DaunPenh"/> <a:font script="Knda" typeface="Tunga"/> <a:font script="Guru" typeface="Raavi"/> <a:font script="Cans" typeface="Euphemia"/> <a:font script="Cher" typeface="Plantagenet Cherokee"/> <a:font script="Yiii" typeface="Microsoft Yi Baiti"/> <a:font script="Tibt" typeface="Microsoft Himalaya"/> <a:font script="Thaa" typeface="MV Boli"/> <a:font script="Deva" typeface="Mangal"/> <a:font script="Telu" typeface="Gautami"/> <a:font script="Taml" typeface="Latha"/> <a:font script="Syrc" typeface="Estrangelo Edessa"/> <a:font script="Orya" typeface="Kalinga"/> <a:font script="Mlym" typeface="Kartika"/> <a:font script="Laoo" typeface="DokChampa"/> <a:font script="Sinh" typeface="Iskoola Pota"/> <a:font script="Mong" typeface="Mongolian Baiti"/> <a:font script="Viet" typeface="Arial"/> <a:font script="Uigh" typeface="Microsoft Uighur"/> <a:font script="Geor" typeface="Sylfaen"/> </a:minorFont> </a:fontScheme> <a:fmtScheme name="Office"> <a:fillStyleLst> <a:solidFill> <a:schemeClr val="phClr"/> </a:solidFill> <a:gradFill rotWithShape="1"> <a:gsLst> <a:gs pos="0"> <a:schemeClr val="phClr"> <a:tint val="50000"/> <a:satMod val="300000"/> </a:schemeClr> </a:gs> <a:gs pos="35000"> <a:schemeClr val="phClr"> <a:tint val="37000"/> <a:satMod val="300000"/> </a:schemeClr> </a:gs> <a:gs pos="100000"> <a:schemeClr val="phClr"> <a:tint val="15000"/> <a:satMod val="350000"/> </a:schemeClr> </a:gs> </a:gsLst> <a:lin ang="16200000" scaled="1"/> </a:gradFill> <a:gradFill rotWithShape="1"> <a:gsLst> <a:gs pos="0"> <a:schemeClr val="phClr"> <a:tint val="100000"/> <a:shade val="100000"/> <a:satMod val="130000"/> </a:schemeClr> </a:gs> <a:gs pos="100000"> <a:schemeClr val="phClr"> <a:tint val="50000"/> <a:shade val="100000"/> <a:satMod val="350000"/> </a:schemeClr> </a:gs> </a:gsLst> <a:lin ang="16200000" scaled="0"/> </a:gradFill> </a:fillStyleLst> <a:lnStyleLst> <a:ln w="9525" cap="flat" cmpd="sng" algn="ctr"> <a:solidFill> <a:schemeClr val="phClr"> <a:shade val="95000"/> <a:satMod val="105000"/> </a:schemeClr> </a:solidFill> <a:prstDash val="solid"/> </a:ln> <a:ln w="25400" cap="flat" cmpd="sng" algn="ctr"> <a:solidFill> <a:Line truncated
`,this.quote='"',this.escape=this.quote,this.quoteColumns=!1,this.quoteHeaders=this.quoteColumns,this.headers=null,this.includeEndRowDelimiter=!1,this.writeBOM=!1,this.BOM="\uFEFF",this.alwaysWriteHeaders=!1,Object.assign(this,$||{}),typeof($===null||$===void 0?void 0:$.quoteHeaders)>"u")this.quoteHeaders=this.quoteColumns;if(($===null||$===void 0?void 0:$.quote)===!0)this.quote='"';else if(($===null||$===void 0?void 0:$.quote)===!1)this.quote="";if(typeof($===null||$===void 0?void 0:$.escape)!=="string")this.escape=this.quote;this.shouldWriteHeaders=!!this.headers&&((Y=$.writeHeaders)!==null&&Y!==void 0?Y:!0),this.headers=Array.isArray(this.headers)?this.headers:null,this.escapedQuote=`${this.escape}${this.quote}`}}sK0.FormatterOptions=rK0});var sN=j((Wa1,Yz0)=>{var U31="[object AsyncFunction]",I31="[object Function]",Q31="[object GeneratorFunction]",J31="[object Null]",K31="[object Proxy]",z31="[object Undefined]",G31=typeof global=="object"&&global&&global.Object===Object&&global,H31=typeof self=="object"&&self&&self.Object===Object&&self,W31=G31||H31||Function("return this")(),eK0=Object.prototype,X31=eK0.hasOwnProperty,$z0=eK0.toString,tK0=W31.Symbol,BU=tK0?tK0.toStringTag:void 0;function Z31($){if($==null)return $===void 0?z31:J31;return BU&&BU in Object($)?q31($):V31($)}function q31($){var Y=X31.call($,BU),U=$[BU];try{$[BU]=void 0;var I=!0}catch(J){}var Q=$z0.call($);if(I)if(Y)$[BU]=U;else delete $[BU];return Q}function V31($){return $z0.call($)}function L31($){if(!F31($))return!1;var Y=Z31($);return Y==I31||Y==Q31||Y==U31||Y==K31}function F31($){var Y=typeof $;return $!=null&&(Y=="object"||Y=="function")}Yz0.exports=L31});var kz0=j((aN,mJ)=>{var w31=200,nf="__lodash_hash_undefined__",JD=1,qz0=2,Vz0=9007199254740991,tN="[object Arguments]",yf="[object Array]",M31="[object AsyncFunction]",Lz0="[object Boolean]",Fz0="[object Date]",wz0="[object Error]",Mz0="[object Function]",O31="[object GeneratorFunction]",eN="[object Map]",Oz0="[object Number]",N31="[object Null]",pJ="[object Object]",Uz0="[object Promise]",D31="[object Proxy]",Nz0="[object RegExp]",$D="[object Set]",Dz0="[object String]",B31="[object Symbol]",A31="[object Undefined]",kf="[object WeakMap]",Bz0="[object ArrayBuffer]",YD="[object DataView]",P31="[object Float32Array]",T31="[object Float64Array]",E31="[object Int8Array]",j31="[object Int16Array]",C31="[object Int32Array]",R31="[object Uint8Array]",_31="[object Uint8ClampedArray]",v31="[object Uint16Array]",S31="[object Uint32Array]",h31=/[\\^$.*+?()[\]{}|]/g,g31=/^\[object .+?Constructor\]$/,y31=/^(?:0|[1-9]\d*)$/,j4={};j4[P31]=j4[T31]=j4[E31]=j4[j31]=j4[C31]=j4[R31]=j4[_31]=j4[v31]=j4[S31]=!0;j4[tN]=j4[yf]=j4[Bz0]=j4[Lz0]=j4[YD]=j4[Fz0]=j4[wz0]=j4[Mz0]=j4[eN]=j4[Oz0]=j4[pJ]=j4[Nz0]=j4[$D]=j4[Dz0]=j4[kf]=!1;var Az0=typeof global=="object"&&global&&global.Object===Object&&global,k31=typeof self=="object"&&self&&self.Object===Object&&self,N3=Az0||k31||Function("return this")(),Pz0=typeof aN=="object"&&aN&&!aN.nodeType&&aN,Iz0=Pz0&&typeof mJ=="object"&&mJ&&!mJ.nodeType&&mJ,Tz0=Iz0&&Iz0.exports===Pz0,Sf=Tz0&&Az0.process,Qz0=function(){try{return Sf&&Sf.binding&&Sf.binding("util")}catch($){}}(),Jz0=Qz0&&Qz0.isTypedArray;function x31($,Y){var U=-1,I=$==null?0:$.length,Q=0,J=[];while(++U<I){var K=$[U];if(Y(K,U,$))J[Q++]=K}return J}function f31($,Y){var U=-1,I=Y.length,Q=$.length;while(++U<I)$[Q+U]=Y[U];return $}function u31($,Y){var U=-1,I=$==null?0:$.length;while(++U<I)if(Y($[U],U,$))return!0;return!1}function b31($,Y){var U=-1,I=Array($);while(++U<$)I[U]=Y(U);return I}function i31($){return function(Y){return $(Y)}}function c31($,Y){return $.has(Y)}function n31($,Y){return $==null?void 0:$[Y]}function d31($){var Y=-1,U=Array($.size);return $.forEach(function(I,Q){U[++Y]=[Q,I]}),U}function p31($,Y){return function(U){return $(Y(U))}}function m31($){var Y=-1,U=Array($.size);return $.forEach(function(I){U[++Y]=I}),U}var l31=Array.prototype,o31=Function.prototype,KD=Object.prototype,hf=N3["__core-js_shared__"],Ez0=o31.toString,L9=KD.hasOwnProperty,Kz0=function(){var $=/[^.]+$/.exec(hf&&hf.keys&&hf.keys.IE_PROTO||"");return $?"Symbol(src)_1."+$:""}(),jz0=KD.toString,r31=RegExp("^"+Ez0.call(L9).replace(h31,"\\$&").replace(/hasOwnProperty|(function).*?(?=\\\()| for .+?(?=\\\])/g,"$1.*?")+"$"),zz0=Tz0?N3.Buffer:void 0,UD=N3.Symbol,Gz0=N3.Uint8Array,Cz0=KD.propertyIsEnumerable,s31=l31.splice,AU=UD?UD.toStringTag:void 0,Hz0=Object.getOwnPropertySymbols,a31=zz0?zz0.isBuffer:void 0,t31=p31(Object.keys,Object),xf=lJ(N3,"DataView"),lW=lJ(N3,"Map"),ff=lJ(N3,"Promise"),uf=lJ(N3,"Set"),bf=lJ(N3,"WeakMap"),oW=lJ(Object,"create"),e31=EU(xf),$71=EU(lW),Y71=EU(ff),U71=EU(uf),I71=EU(bf),Wz0=UD?UD.prototype:void 0,gf=Wz0?Wz0.valueOf:void 0;function PU($){var Y=-1,U=$==null?0:$.length;this.clear();while(++Y<U){var I=$[Y];this.set(I[0],I[1])}}function Q71(){this.__data__=oW?oW(null):{},this.size=0}function J71($){var Y=this.has($)&&delete this.__data__[$];return this.size-=Y?1:0,Y}function K71($){var Y=this.__data Line truncated
]`;this.ESCAPE_REGEXP=new RegExp(Y)}set headers($){this._headers=$}shouldQuote($,Y){let U=Y?this.formatterOptions.quoteHeaders:this.formatterOptions.quoteColumns;if(Z21.default(U))return U;if(Array.isArray(U))return U[$];if(this._headers!==null)return U[this._headers[$]];return!1}format($,Y,U){let I=`${q21.default($)?"":$}`.replace(/\0/g,""),{formatterOptions:Q}=this;if(Q.quote!==""){if(I.indexOf(Q.quote)!==-1)return this.quoteField(I.replace(this.REPLACE_REGEXP,Q.escapedQuote))}if(I.search(this.ESCAPE_REGEXP)!==-1||this.shouldQuote(Y,U))return this.quoteField(I);return I}quoteField($){let{quote:Y}=this.formatterOptions;return`${Y}${$}${Y}`}}oJ.FieldFormatter=pz0});var of=j((mz0)=>{Object.defineProperty(mz0,"__esModule",{value:!0});mz0.isSyncTransform=void 0;mz0.isSyncTransform=($)=>$.length===1});var rz0=j((rJ)=>{var oz0=rJ&&rJ.__importDefault||function($){return $&&$.__esModule?$:{default:$}};Object.defineProperty(rJ,"__esModule",{value:!0});rJ.RowFormatter=void 0;var L21=oz0(sN()),F21=oz0(kz0()),w21=lf(),M21=of();class jU{constructor($){if(this.rowCount=0,this.formatterOptions=$,this.fieldFormatter=new w21.FieldFormatter($),this.headers=$.headers,this.shouldWriteHeaders=$.shouldWriteHeaders,this.hasWrittenHeaders=!1,this.headers!==null)this.fieldFormatter.headers=this.headers;if($.transform)this.rowTransform=$.transform}static isRowHashArray($){if(Array.isArray($))return Array.isArray($[0])&&$[0].length===2;return!1}static isRowArray($){return Array.isArray($)&&!this.isRowHashArray($)}static gatherHeaders($){if(jU.isRowHashArray($))return $.map((Y)=>Y[0]);if(Array.isArray($))return $;return Object.keys($)}static createTransform($){if(M21.isSyncTransform($))return(Y,U)=>{let I=null;try{I=$(Y)}catch(Q){return U(Q)}return U(null,I)};return(Y,U)=>{$(Y,U)}}set rowTransform($){if(!L21.default($))throw TypeError("The transform should be a function");this._rowTransform=jU.createTransform($)}format($,Y){this.callTransformer($,(U,I)=>{if(U)return Y(U);if(!$)return Y(null);let Q=[];if(I){let{shouldFormatColumns:J,headers:K}=this.checkHeaders(I);if(this.shouldWriteHeaders&&K&&!this.hasWrittenHeaders)Q.push(this.formatColumns(K,!0)),this.hasWrittenHeaders=!0;if(J){let z=this.gatherColumns(I);Q.push(this.formatColumns(z,!1))}}return Y(null,Q)})}finish($){let Y=[];if(this.formatterOptions.alwaysWriteHeaders&&this.rowCount===0){if(!this.headers)return $(Error("`alwaysWriteHeaders` option is set to true but `headers` option not provided."));Y.push(this.formatColumns(this.headers,!0))}if(this.formatterOptions.includeEndRowDelimiter)Y.push(this.formatterOptions.rowDelimiter);return $(null,Y)}checkHeaders($){if(this.headers)return{shouldFormatColumns:!0,headers:this.headers};let Y=jU.gatherHeaders($);if(this.headers=Y,this.fieldFormatter.headers=Y,!this.shouldWriteHeaders)return{shouldFormatColumns:!0,headers:null};return{shouldFormatColumns:!F21.default(Y,$),headers:Y}}gatherColumns($){if(this.headers===null)throw Error("Headers is currently null");if(!Array.isArray($))return this.headers.map((Y)=>$[Y]);if(jU.isRowHashArray($))return this.headers.map((Y,U)=>{let I=$[U];if(I)return I[1];return""});if(jU.isRowArray($)&&!this.shouldWriteHeaders)return $;return this.headers.map((Y,U)=>$[U])}callTransformer($,Y){if(!this._rowTransform)return Y(null,$);return this._rowTransform($,Y)}formatColumns($,Y){let U=$.map((Q,J)=>this.fieldFormatter.format(Q,J,Y)).join(this.formatterOptions.delimiter),{rowCount:I}=this;if(this.rowCount+=1,I)return[this.formatterOptions.rowDelimiter,U].join("");return U}}rJ.RowFormatter=jU});var sz0=j((HD)=>{Object.defineProperty(HD,"__esModule",{value:!0});HD.FieldFormatter=HD.RowFormatter=void 0;var O21=rz0();Object.defineProperty(HD,"RowFormatter",{enumerable:!0,get:function(){return O21.RowFormatter}});var N21=lf();Object.defineProperty(HD,"FieldFormatter",{enumerable:!0,get:function(){return N21.FieldFormatter}})});var rf=j((tz0)=>{Object.defineProperty(tz0,"__esModule",{value:!0});tz0.CsvFormatterStream=void 0;var B21=K0("stream"),A21=sz0();class az0 extends B21.Transform{constructor($){super({writableObjectMode:$.objectMode});this.hasWrittenBOM=!1,this.formatterOptions=$,this.rowFormatter=new A21.RowFormatter($),this.hasWrittenBOM=!$.writeBOM}transform($){return this.rowFormatter.rowTransform=$,this}_transform($,Y,U){let I=!1;try{if(!this.hasWrittenBOM)this.push(this.formatterOptions.BOM),this.hasWrittenBOM=!0;this.rowFormatter.format($,(Q,J)=>{if(Q)return I=!0,U(Q);if(J)J.forEach((K)=>{this.push(Buffer.from(K,"utf8"))});return I=!0,U()})}catch(Q){if(I)throw Q;U(Q)}}_flush($){this.rowFormatter.finish((Y,U)=>{if(Y)return $(Y);if(U)U.forEach((I)=>{this.push(Buffer.from(I,"utf8"))});return $()})}}tz0.CsvFormatterStream=az0});var YG0=j((a1)=>{var $G0=a1&&a1.__createBinding||(Object.create?function($,Y,U,I){if(I===void 0)I=U;Object.defineProperty($,I,{enumerable:!0,get:function(){return Y[U]}})}:function($,Y,U,I){if(I===void 0)I=U;$[I]=Y[U]}),P21=a1&&a1.__setModuleDefault||(Object.create?function($,Y){O Line truncated
`||Y===`\r
`}static isTokenCarriageReturn($,Y){return $.token===Y.carriageReturn}static isTokenComment($,Y){return Y.supportsComments&&!!$&&$.token===Y.comment}static isTokenEscapeCharacter($,Y){return $.token===Y.escapeChar}static isTokenQuote($,Y){return $.token===Y.quote}static isTokenDelimiter($,Y){return $.token===Y.delimiter}}iG0.Token=bG0});var Vu=E((dG0)=>{Object.defineProperty(dG0,"__esModule",{value:!0});dG0.Scanner=void 0;var nG0=Z2(),cU1=/((?:\r\n)|\n|\r)/;class pG0{constructor($){this.cursor=0,this.line=$.line,this.lineLength=this.line.length,this.parserOptions=$.parserOptions,this.hasMoreData=$.hasMoreData,this.cursor=$.cursor||0}get hasMoreCharacters(){return this.lineLength>this.cursor}get nextNonSpaceToken(){let{lineFromCursor:$}=this,Y=this.parserOptions.NEXT_TOKEN_REGEXP;if($.search(Y)===-1)return null;let U=Y.exec($);if(U==null)return null;let z=U[1],I=this.cursor+(U.index||0);return new nG0.Token({token:z,startCursor:I,endCursor:I+z.length-1})}get nextCharacterToken(){let{cursor:$,lineLength:Y}=this;if(Y<=$)return null;return new nG0.Token({token:this.line[$],startCursor:$,endCursor:$})}get lineFromCursor(){return this.line.substr(this.cursor)}advancePastLine(){let $=cU1.exec(this.lineFromCursor);if(!$){if(this.hasMoreData)return null;return this.cursor=this.lineLength,this}return this.cursor+=($.index||0)+$[0].length,this}advanceTo($){return this.cursor=$,this}advanceToToken($){return this.cursor=$.startCursor,this}advancePastToken($){return this.cursor=$.endCursor+1,this}truncateToCursor(){return this.line=this.lineFromCursor,this.lineLength=this.line.length,this.cursor=0,this}}dG0.Scanner=pG0});var PD=E((oG0)=>{Object.defineProperty(oG0,"__esModule",{value:!0});oG0.ColumnFormatter=void 0;class lG0{constructor($){if($.trim)this.format=(Y)=>Y.trim();else if($.ltrim)this.format=(Y)=>Y.trimLeft();else if($.rtrim)this.format=(Y)=>Y.trimRight();else this.format=(Y)=>Y}}oG0.ColumnFormatter=lG0});var Lu=E((tG0)=>{Object.defineProperty(tG0,"__esModule",{value:!0});tG0.NonQuotedColumnParser=void 0;var nU1=PD(),sG0=Z2();class aG0{constructor($){this.parserOptions=$,this.columnFormatter=new nU1.ColumnFormatter($)}parse($){if(!$.hasMoreCharacters)return null;let{parserOptions:Y}=this,U=[],z=$.nextCharacterToken;for(;z;z=$.nextCharacterToken){if(sG0.Token.isTokenDelimiter(z,Y)||sG0.Token.isTokenRowDelimiter(z))break;U.push(z.token),$.advancePastToken(z)}return this.columnFormatter.format(U.join(""))}}tG0.NonQuotedColumnParser=aG0});var Fu=E((YH0)=>{Object.defineProperty(YH0,"__esModule",{value:!0});YH0.QuotedColumnParser=void 0;var pU1=PD(),QJ=Z2();class $H0{constructor($){this.parserOptions=$,this.columnFormatter=new pU1.ColumnFormatter($)}parse($){if(!$.hasMoreCharacters)return null;let Y=$.cursor,{foundClosingQuote:U,col:z}=this.gatherDataBetweenQuotes($);if(!U){if($.advanceTo(Y),!$.hasMoreData)throw Error(`Parse Error: missing closing: '${this.parserOptions.quote||""}' in line: at '${$.lineFromCursor.replace(/[\r\n]/g,"\\n'")}'`);return null}return this.checkForMalformedColumn($),z}gatherDataBetweenQuotes($){let{parserOptions:Y}=this,U=!1,z=!1,I=[],Q=$.nextCharacterToken;for(;!z&&Q!==null;Q=$.nextCharacterToken){let J=QJ.Token.isTokenQuote(Q,Y);if(!U&&J)U=!0;else if(U)if(QJ.Token.isTokenEscapeCharacter(Q,Y)){$.advancePastToken(Q);let K=$.nextCharacterToken;if(K!==null&&(QJ.Token.isTokenQuote(K,Y)||QJ.Token.isTokenEscapeCharacter(K,Y)))I.push(K.token),Q=K;else if(J)z=!0;else I.push(Q.token)}else if(J)z=!0;else I.push(Q.token);$.advancePastToken(Q)}return{col:this.columnFormatter.format(I.join("")),foundClosingQuote:z}}checkForMalformedColumn($){let{parserOptions:Y}=this,{nextNonSpaceToken:U}=$;if(U){let z=QJ.Token.isTokenDelimiter(U,Y),I=QJ.Token.isTokenRowDelimiter(U);if(!(z||I)){let Q=$.lineFromCursor.substr(0,10).replace(/[\r\n]/g,"\\n'");throw Error(`Parse Error: expected: '${Y.escapedDelimiter}' OR new line got: '${U.token}'. at '${Q}`)}$.advanceToToken(U)}else if(!$.hasMoreData)$.advancePastLine()}}YH0.QuotedColumnParser=$H0});var JH0=E((IH0)=>{Object.defineProperty(IH0,"__esModule",{value:!0});IH0.ColumnParser=void 0;var dU1=Lu(),mU1=Fu(),lU1=Z2();class zH0{constructor($){this.parserOptions=$,this.quotedColumnParser=new mU1.QuotedColumnParser($),this.nonQuotedColumnParser=new dU1.NonQuotedColumnParser($)}parse($){let{nextNonSpaceToken:Y}=$;if(Y!==null&&lU1.Token.isTokenQuote(Y,this.parserOptions))return $.advanceToToken(Y),this.quotedColumnParser.parse($);return this.nonQuotedColumnParser.parse($)}}IH0.ColumnParser=zH0});var wu=E((JJ)=>{Object.defineProperty(JJ,"__esModule",{value:!0});JJ.ColumnFormatter=JJ.QuotedColumnParser=JJ.NonQuotedColumnParser=JJ.ColumnParser=void 0;var oU1=JH0();Object.defineProperty(JJ,"ColumnParser",{enumerable:!0,get:function(){return oU1.ColumnParser}});var rU1=Lu();Object.defineProperty(JJ,"NonQuotedColumnParser",{enumerable:!0,get:function(){return rU1.NonQuotedColumnParser}});var sU1=Fu();Object.defineProperty(JJ,"QuotedColumnParser",{enumerable:!0,get:function(){re Line truncated
%s`,T,T,q,z);let A=q.type==="*"?hu:q.type==="?"?yu:"\\"+q.type;I=!0,z=z.slice(0,q.reStart)+A+"\\("+T}if(O(),Q)z+="\\\\";let D=iz1[z.charAt(0)];for(let T=K.length-1;T>-1;T--){let A=K[T],j=z.slice(0,A.reStart),C=z.slice(A.reStart,A.reEnd-8),b=z.slice(A.reEnd),x=z.slice(A.reEnd-8,A.reEnd)+b,g=j.split(")").length,i=j.split("(").length-g,c=b;for(let k=0;k<i;k++)c=c.replace(/\)[+*?]?/,"");b=c;let z0=b===""&&Y!==Su?"(?:$|\\/)":"";z=j+C+b+z0+x}if(z!==""&&I)z="(?=.)"+z;if(D)z=F()+z;if(Y===Su)return[z,I];if(U.nocase&&!I)I=$.toUpperCase()!==$.toLowerCase();if(!I)return nz1($);let P=U.nocase?"i":"";try{return Object.assign(new RegExp("^"+z+"$",P),{_glob:$,_src:z})}catch(T){return new RegExp("$.")}}makeRe(){if(this.regexp||this.regexp===!1)return this.regexp;let $=this.set;if(!$.length)return this.regexp=!1,this.regexp;let Y=this.options,U=Y.noglobstar?hu:Y.dot?uz1:bz1,z=Y.nocase?"i":"",I=$.map((Q)=>{return Q=Q.map((J)=>typeof J==="string"?dz1(J):J===S8?S8:J._src).reduce((J,K)=>{if(!(J[J.length-1]===S8&&K===S8))J.push(K);return J},[]),Q.forEach((J,K)=>{if(J!==S8||Q[K-1]===S8)return;if(K===0)if(Q.length>1)Q[K+1]="(?:\\/|"+U+"\\/)?"+Q[K+1];else Q[K]=U;else if(K===Q.length-1)Q[K-1]+="(?:\\/|"+U+")?";else Q[K-1]+="(?:\\/|\\/"+U+"\\/)"+Q[K+1],Q[K+1]=S8}),Q.filter((J)=>J!==S8).join("/")}).join("|");if(I="^(?:"+I+")$",this.negate)I="^(?!"+I+").*$";try{this.regexp=new RegExp(I,z)}catch(Q){this.regexp=!1}return this.regexp}match($,Y=this.partial){if(this.debug("match",$,this.pattern),this.comment)return!1;if(this.empty)return $==="";if($==="/"&&Y)return!0;let U=this.options;if(gu.sep!=="/")$=$.split(gu.sep).join("/");$=$.split(eH0),this.debug(this.pattern,"split",$);let z=this.set;this.debug(this.pattern,"set",z);let I;for(let Q=$.length-1;Q>=0;Q--)if(I=$[Q],I)break;for(let Q=0;Q<z.length;Q++){let J=z[Q],K=$;if(U.matchBase&&J.length===1)K=[I];if(this.matchOne(K,J,Y)){if(U.flipNegate)return!0;return!this.negate}}if(U.flipNegate)return!1;return this.negate}static defaults($){return X$.defaults($).Minimatch}}X$.Minimatch=eW});var KW0=E(($a1,JW0)=>{JW0.exports=QW0;var fu=J0("fs"),{EventEmitter:lz1}=J0("events"),{Minimatch:xu}=UW0(),{resolve:oz1}=J0("path");function rz1($,Y){return new Promise((U,z)=>{fu.readdir($,{withFileTypes:!0},(I,Q)=>{if(I)switch(I.code){case"ENOTDIR":if(Y)z(I);else U([]);break;case"ENOTSUP":case"ENOENT":case"ENAMETOOLONG":case"UNKNOWN":U([]);break;case"ELOOP":default:z(I);break}else U(Q)})})}function zW0($,Y){return new Promise((U,z)=>{(Y?fu.stat:fu.lstat)($,(Q,J)=>{if(Q)switch(Q.code){case"ENOENT":if(Y)U(zW0($,!1));else U(null);break;default:U(null);break}else U(J)})})}async function*IW0($,Y,U,z,I,Q){let J=await rz1(Y+$,Q);for(let K of J){let G=K.name;if(G===void 0)G=K,z=!0;let H=$+"/"+G,W=H.slice(1),X=Y+"/"+W,Z=null;if(z||U)Z=await zW0(X,U);if(!Z&&K.name!==void 0)Z=K;if(Z===null)Z={isDirectory:()=>!1};if(Z.isDirectory()){if(!I(W))yield{relative:W,absolute:X,stats:Z},yield*IW0(H,Y,U,z,I,!1)}else yield{relative:W,absolute:X,stats:Z}}}async function*sz1($,Y,U,z){yield*IW0("",$,Y,U,z,!0)}function az1($){return{pattern:$.pattern,dot:!!$.dot,noglobstar:!!$.noglobstar,matchBase:!!$.matchBase,nocase:!!$.nocase,ignore:$.ignore,skip:$.skip,follow:!!$.follow,stat:!!$.stat,nodir:!!$.nodir,mark:!!$.mark,silent:!!$.silent,absolute:!!$.absolute}}class uu extends lz1{constructor($,Y,U){super();if(typeof Y==="function")U=Y,Y=null;if(this.options=az1(Y||{}),this.matchers=[],this.options.pattern){let z=Array.isArray(this.options.pattern)?this.options.pattern:[this.options.pattern];this.matchers=z.map((I)=>new xu(I,{dot:this.options.dot,noglobstar:this.options.noglobstar,matchBase:this.options.matchBase,nocase:this.options.nocase}))}if(this.ignoreMatchers=[],this.options.ignore){let z=Array.isArray(this.options.ignore)?this.options.ignore:[this.options.ignore];this.ignoreMatchers=z.map((I)=>new xu(I,{dot:!0}))}if(this.skipMatchers=[],this.options.skip){let z=Array.isArray(this.options.skip)?this.options.skip:[this.options.skip];this.skipMatchers=z.map((I)=>new xu(I,{dot:!0}))}if(this.iterator=sz1(oz1($||"."),this.options.follow,this.options.stat,this._shouldSkipDirectory.bind(this)),this.paused=!1,this.inactive=!1,this.aborted=!1,U)this._matches=[],this.on("match",(z)=>this._matches.push(this.options.absolute?z.absolute:z.relative)),this.on("error",(z)=>U(z)),this.on("end",()=>U(null,this._matches));setTimeout(()=>this._next(),0)}_shouldSkipDirectory($){return this.skipMatchers.some((Y)=>Y.match($))}_fileMatches($,Y){let U=$+(Y?"/":"");return(this.matchers.length===0||this.matchers.some((z)=>z.match(U)))&&!this.ignoreMatchers.some((z)=>z.match(U))&&(!this.options.nodir||!Y)}_next(){if(!this.paused&&!this.aborted)this.iterator.next().then(($)=>{if(!$.done){let Y=$.value.stats.isDirectory();if(this._fileMatches($.value.relative,Y)){let U=$.value.relative,z=$.value.absolute;if(this.options.mark&&Y)U+="/",z+="/";if(this.options.stat)this.emit("match",{relative:U,absolute:z,stat:$.value.stats});else this.emit("match",{relative:U Line truncated
`,r);r=L0===-1?f.length:L0}else if(K0!==-1&&f[r]==="/"&&f[r+1]==="*"){let L0=f.indexOf("*/",r);if(L0!==-1)r=L0+2,K0=f.indexOf("*/",r);else n+=f[r],r++}else n+=f[r],r++;return n}function c0(f){let n=b0(f.toString()),r=n.match(t);if(!r)r=n.match(X0);if(!r)throw Error(`could not parse args in autoInject
`}static isTokenCarriageReturn($,Y){return $.token===Y.carriageReturn}static isTokenComment($,Y){return Y.supportsComments&&!!$&&$.token===Y.comment}static isTokenEscapeCharacter($,Y){return $.token===Y.escapeChar}static isTokenQuote($,Y){return $.token===Y.quote}static isTokenDelimiter($,Y){return $.token===Y.delimiter}}UH0.Token=YH0});var Ou=j((KH0)=>{Object.defineProperty(KH0,"__esModule",{value:!0});KH0.Scanner=void 0;var QH0=V2(),SI1=/((?:\r\n)|\n|\r)/;class JH0{constructor($){this.cursor=0,this.line=$.line,this.lineLength=this.line.length,this.parserOptions=$.parserOptions,this.hasMoreData=$.hasMoreData,this.cursor=$.cursor||0}get hasMoreCharacters(){return this.lineLength>this.cursor}get nextNonSpaceToken(){let{lineFromCursor:$}=this,Y=this.parserOptions.NEXT_TOKEN_REGEXP;if($.search(Y)===-1)return null;let U=Y.exec($);if(U==null)return null;let I=U[1],Q=this.cursor+(U.index||0);return new QH0.Token({token:I,startCursor:Q,endCursor:Q+I.length-1})}get nextCharacterToken(){let{cursor:$,lineLength:Y}=this;if(Y<=$)return null;return new QH0.Token({token:this.line[$],startCursor:$,endCursor:$})}get lineFromCursor(){return this.line.substr(this.cursor)}advancePastLine(){let $=SI1.exec(this.lineFromCursor);if(!$){if(this.hasMoreData)return null;return this.cursor=this.lineLength,this}return this.cursor+=($.index||0)+$[0].length,this}advanceTo($){return this.cursor=$,this}advanceToToken($){return this.cursor=$.startCursor,this}advancePastToken($){return this.cursor=$.endCursor+1,this}truncateToCursor(){return this.line=this.lineFromCursor,this.lineLength=this.line.length,this.cursor=0,this}}KH0.Scanner=JH0});var SD=j((HH0)=>{Object.defineProperty(HH0,"__esModule",{value:!0});HH0.ColumnFormatter=void 0;class GH0{constructor($){if($.trim)this.format=(Y)=>Y.trim();else if($.ltrim)this.format=(Y)=>Y.trimLeft();else if($.rtrim)this.format=(Y)=>Y.trimRight();else this.format=(Y)=>Y}}HH0.ColumnFormatter=GH0});var Nu=j((qH0)=>{Object.defineProperty(qH0,"__esModule",{value:!0});qH0.NonQuotedColumnParser=void 0;var hI1=SD(),XH0=V2();class ZH0{constructor($){this.parserOptions=$,this.columnFormatter=new hI1.ColumnFormatter($)}parse($){if(!$.hasMoreCharacters)return null;let{parserOptions:Y}=this,U=[],I=$.nextCharacterToken;for(;I;I=$.nextCharacterToken){if(XH0.Token.isTokenDelimiter(I,Y)||XH0.Token.isTokenRowDelimiter(I))break;U.push(I.token),$.advancePastToken(I)}return this.columnFormatter.format(U.join(""))}}qH0.NonQuotedColumnParser=ZH0});var Du=j((FH0)=>{Object.defineProperty(FH0,"__esModule",{value:!0});FH0.QuotedColumnParser=void 0;var gI1=SD(),KK=V2();class LH0{constructor($){this.parserOptions=$,this.columnFormatter=new gI1.ColumnFormatter($)}parse($){if(!$.hasMoreCharacters)return null;let Y=$.cursor,{foundClosingQuote:U,col:I}=this.gatherDataBetweenQuotes($);if(!U){if($.advanceTo(Y),!$.hasMoreData)throw Error(`Parse Error: missing closing: '${this.parserOptions.quote||""}' in line: at '${$.lineFromCursor.replace(/[\r\n]/g,"\\n'")}'`);return null}return this.checkForMalformedColumn($),I}gatherDataBetweenQuotes($){let{parserOptions:Y}=this,U=!1,I=!1,Q=[],J=$.nextCharacterToken;for(;!I&&J!==null;J=$.nextCharacterToken){let K=KK.Token.isTokenQuote(J,Y);if(!U&&K)U=!0;else if(U)if(KK.Token.isTokenEscapeCharacter(J,Y)){$.advancePastToken(J);let z=$.nextCharacterToken;if(z!==null&&(KK.Token.isTokenQuote(z,Y)||KK.Token.isTokenEscapeCharacter(z,Y)))Q.push(z.token),J=z;else if(K)I=!0;else Q.push(J.token)}else if(K)I=!0;else Q.push(J.token);$.advancePastToken(J)}return{col:this.columnFormatter.format(Q.join("")),foundClosingQuote:I}}checkForMalformedColumn($){let{parserOptions:Y}=this,{nextNonSpaceToken:U}=$;if(U){let I=KK.Token.isTokenDelimiter(U,Y),Q=KK.Token.isTokenRowDelimiter(U);if(!(I||Q)){let J=$.lineFromCursor.substr(0,10).replace(/[\r\n]/g,"\\n'");throw Error(`Parse Error: expected: '${Y.escapedDelimiter}' OR new line got: '${U.token}'. at '${J}`)}$.advanceToToken(U)}else if(!$.hasMoreData)$.advancePastLine()}}FH0.QuotedColumnParser=LH0});var DH0=j((OH0)=>{Object.defineProperty(OH0,"__esModule",{value:!0});OH0.ColumnParser=void 0;var yI1=Nu(),kI1=Du(),xI1=V2();class MH0{constructor($){this.parserOptions=$,this.quotedColumnParser=new kI1.QuotedColumnParser($),this.nonQuotedColumnParser=new yI1.NonQuotedColumnParser($)}parse($){let{nextNonSpaceToken:Y}=$;if(Y!==null&&xI1.Token.isTokenQuote(Y,this.parserOptions))return $.advanceToToken(Y),this.quotedColumnParser.parse($);return this.nonQuotedColumnParser.parse($)}}OH0.ColumnParser=MH0});var Bu=j((zK)=>{Object.defineProperty(zK,"__esModule",{value:!0});zK.ColumnFormatter=zK.QuotedColumnParser=zK.NonQuotedColumnParser=zK.ColumnParser=void 0;var fI1=DH0();Object.defineProperty(zK,"ColumnParser",{enumerable:!0,get:function(){return fI1.ColumnParser}});var uI1=Nu();Object.defineProperty(zK,"NonQuotedColumnParser",{enumerable:!0,get:function(){return uI1.NonQuotedColumnParser}});var bI1=Du();Object.defineProperty(zK,"QuotedColumnParser",{enumerable:!0,get:function(){re Line truncated
%s`,T,T,q,I);let B=q.type==="*"?xu:q.type==="?"?bu:"\\"+q.type;Q=!0,I=I.slice(0,q.reStart)+B+"\\("+T}if(O(),J)I+="\\\\";let D=vQ1[I.charAt(0)];for(let T=z.length-1;T>-1;T--){let B=z[T],E=I.slice(0,B.reStart),C=I.slice(B.reStart,B.reEnd-8),b=I.slice(B.reEnd),x=I.slice(B.reEnd-8,B.reEnd)+b,g=E.split(")").length,i=E.split("(").length-g,c=b;for(let k=0;k<i;k++)c=c.replace(/\)[+*?]?/,"");b=c;let I0=b===""&&Y!==fu?"(?:$|\\/)":"";I=E+C+b+I0+x}if(I!==""&&Q)I="(?=.)"+I;if(D)I=F()+I;if(Y===fu)return[I,Q];if(U.nocase&&!Q)Q=$.toUpperCase()!==$.toLowerCase();if(!Q)return hQ1($);let P=U.nocase?"i":"";try{return Object.assign(new RegExp("^"+I+"$",P),{_glob:$,_src:I})}catch(T){return new RegExp("$.")}}makeRe(){if(this.regexp||this.regexp===!1)return this.regexp;let $=this.set;if(!$.length)return this.regexp=!1,this.regexp;let Y=this.options,U=Y.noglobstar?xu:Y.dot?RQ1:_Q1,I=Y.nocase?"i":"",Q=$.map((J)=>{return J=J.map((K)=>typeof K==="string"?yQ1(K):K===k8?k8:K._src).reduce((K,z)=>{if(!(K[K.length-1]===k8&&z===k8))K.push(z);return K},[]),J.forEach((K,z)=>{if(K!==k8||J[z-1]===k8)return;if(z===0)if(J.length>1)J[z+1]="(?:\\/|"+U+"\\/)?"+J[z+1];else J[z]=U;else if(z===J.length-1)J[z-1]+="(?:\\/|"+U+")?";else J[z-1]+="(?:\\/|\\/"+U+"\\/)"+J[z+1],J[z+1]=k8}),J.filter((K)=>K!==k8).join("/")}).join("|");if(Q="^(?:"+Q+")$",this.negate)Q="^(?!"+Q+").*$";try{this.regexp=new RegExp(Q,I)}catch(J){this.regexp=!1}return this.regexp}match($,Y=this.partial){if(this.debug("match",$,this.pattern),this.comment)return!1;if(this.empty)return $==="";if($==="/"&&Y)return!0;let U=this.options;if(uu.sep!=="/")$=$.split(uu.sep).join("/");$=$.split(VW0),this.debug(this.pattern,"split",$);let I=this.set;this.debug(this.pattern,"set",I);let Q;for(let J=$.length-1;J>=0;J--)if(Q=$[J],Q)break;for(let J=0;J<I.length;J++){let K=I[J],z=$;if(U.matchBase&&K.length===1)z=[Q];if(this.matchOne(z,K,Y)){if(U.flipNegate)return!0;return!this.negate}}if(U.flipNegate)return!1;return this.negate}static defaults($){return F$.defaults($).Minimatch}}F$.Minimatch=UX});var BW0=j((Ot1,DW0)=>{DW0.exports=NW0;var nu=K0("fs"),{EventEmitter:xQ1}=K0("events"),{Minimatch:cu}=wW0(),{resolve:fQ1}=K0("path");function uQ1($,Y){return new Promise((U,I)=>{nu.readdir($,{withFileTypes:!0},(Q,J)=>{if(Q)switch(Q.code){case"ENOTDIR":if(Y)I(Q);else U([]);break;case"ENOTSUP":case"ENOENT":case"ENAMETOOLONG":case"UNKNOWN":U([]);break;case"ELOOP":default:I(Q);break}else U(J)})})}function MW0($,Y){return new Promise((U,I)=>{(Y?nu.stat:nu.lstat)($,(J,K)=>{if(J)switch(J.code){case"ENOENT":if(Y)U(MW0($,!1));else U(null);break;default:U(null);break}else U(K)})})}async function*OW0($,Y,U,I,Q,J){let K=await uQ1(Y+$,J);for(let z of K){let G=z.name;if(G===void 0)G=z,I=!0;let H=$+"/"+G,W=H.slice(1),X=Y+"/"+W,Z=null;if(I||U)Z=await MW0(X,U);if(!Z&&z.name!==void 0)Z=z;if(Z===null)Z={isDirectory:()=>!1};if(Z.isDirectory()){if(!Q(W))yield{relative:W,absolute:X,stats:Z},yield*OW0(H,Y,U,I,Q,!1)}else yield{relative:W,absolute:X,stats:Z}}}async function*bQ1($,Y,U,I){yield*OW0("",$,Y,U,I,!0)}function iQ1($){return{pattern:$.pattern,dot:!!$.dot,noglobstar:!!$.noglobstar,matchBase:!!$.matchBase,nocase:!!$.nocase,ignore:$.ignore,skip:$.skip,follow:!!$.follow,stat:!!$.stat,nodir:!!$.nodir,mark:!!$.mark,silent:!!$.silent,absolute:!!$.absolute}}class du extends xQ1{constructor($,Y,U){super();if(typeof Y==="function")U=Y,Y=null;if(this.options=iQ1(Y||{}),this.matchers=[],this.options.pattern){let I=Array.isArray(this.options.pattern)?this.options.pattern:[this.options.pattern];this.matchers=I.map((Q)=>new cu(Q,{dot:this.options.dot,noglobstar:this.options.noglobstar,matchBase:this.options.matchBase,nocase:this.options.nocase}))}if(this.ignoreMatchers=[],this.options.ignore){let I=Array.isArray(this.options.ignore)?this.options.ignore:[this.options.ignore];this.ignoreMatchers=I.map((Q)=>new cu(Q,{dot:!0}))}if(this.skipMatchers=[],this.options.skip){let I=Array.isArray(this.options.skip)?this.options.skip:[this.options.skip];this.skipMatchers=I.map((Q)=>new cu(Q,{dot:!0}))}if(this.iterator=bQ1(fQ1($||"."),this.options.follow,this.options.stat,this._shouldSkipDirectory.bind(this)),this.paused=!1,this.inactive=!1,this.aborted=!1,U)this._matches=[],this.on("match",(I)=>this._matches.push(this.options.absolute?I.absolute:I.relative)),this.on("error",(I)=>U(I)),this.on("end",()=>U(null,this._matches));setTimeout(()=>this._next(),0)}_shouldSkipDirectory($){return this.skipMatchers.some((Y)=>Y.match($))}_fileMatches($,Y){let U=$+(Y?"/":"");return(this.matchers.length===0||this.matchers.some((I)=>I.match(U)))&&!this.ignoreMatchers.some((I)=>I.match(U))&&(!this.options.nodir||!Y)}_next(){if(!this.paused&&!this.aborted)this.iterator.next().then(($)=>{if(!$.done){let Y=$.value.stats.isDirectory();if(this._fileMatches($.value.relative,Y)){let U=$.value.relative,I=$.value.absolute;if(this.options.mark&&Y)U+="/",I+="/";if(this.options.stat)this.emit("match",{relative:U,absolute:I,stat:$.value.stats});else this.emit("match",{relative:U Line truncated
`,r);r=L0===-1?f.length:L0}else if(z0!==-1&&f[r]==="/"&&f[r+1]==="*"){let L0=f.indexOf("*/",r);if(L0!==-1)r=L0+2,z0=f.indexOf("*/",r);else n+=f[r],r++}else n+=f[r],r++;return n}function c0(f){let n=b0(f.toString()),r=n.match(t);if(!r)r=n.match(X0);if(!r)throw Error(`could not parse args in autoInject
Source:
`+n);let[,K0]=r;return K0.replace(/\s/g,"").split(F0).map((L0)=>L0.replace(u0,"").trim())}function P1(f,n){var r={};return Object.keys(f).forEach((K0)=>{var L0=f[K0],N0,B0=q(L0),P0=!B0&&L0.length===1||B0&&L0.length===0;if(Array.isArray(L0))N0=[...L0],L0=N0.pop(),r[K0]=N0.concat(N0.length>0?h0:L0);else if(P0)r[K0]=L0;else{if(N0=c0(L0),L0.length===0&&!B0&&N0.length===0)throw Error("autoInject task functions require explicit parameters.");if(!B0)N0.pop();r[K0]=N0.concat(h0)}function h0(Y1,x1){var l1=N0.map((i1)=>Y1[i1]);l1.push(x1),M(L0)(...l1)}}),q1(r,n)}class k1{constructor(){this.head=this.tail=null,this.length=0}removeLink(f){if(f.prev)f.prev.next=f.next;else this.head=f.next;if(f.next)f.next.prev=f.prev;else this.tail=f.prev;return f.prev=f.next=null,this.length-=1,f}empty(){while(this.head)this.shift();return this}insertAfter(f,n){if(n.prev=f,n.next=f.next,f.next)f.next.prev=n;else this.tail=n;f.next=n,this.length+=1}insertBefore(f,n){if(n.prev=f.prev,n.next=f,f.prev)f.prev.next=n;else this.head=n;f.prev=n,this.length+=1}unshift(f){if(this.head)this.insertBefore(this.head,f);else u1(this,f)}push(f){if(this.tail)this.insertAfter(this.tail,f);else u1(this,f)}shift(){return this.head&&this.removeLink(this.head)}pop(){return this.tail&&this.removeLink(this.tail)}toArray(){return[...this]}*[Symbol.iterator](){var f=this.head;while(f)yield f.data,f=f.next}remove(f){var n=this.head;while(n){var{next:r}=n;if(f(n))this.removeLink(n);n=r}return this}}function u1(f,n){f.length=1,f.head=f.tail=n}function b1(f,n,r){if(n==null)n=1;else if(n===0)throw RangeError("Concurrency must not be zero");var K0=M(f),L0=0,N0=[];let B0={error:[],drain:[],saturated:[],unsaturated:[],empty:[]};function P0(K1,e0){B0[K1].push(e0)}function h0(K1,e0){let G1=(...c1)=>{Y1(K1,G1),e0(...c1)};B0[K1].push(G1)}function Y1(K1,e0){if(!K1)return Object.keys(B0).forEach((G1)=>B0[G1]=[]);if(!e0)return B0[K1]=[];B0[K1]=B0[K1].filter((G1)=>G1!==e0)}function x1(K1,...e0){B0[K1].forEach((G1)=>G1(...e0))}var l1=!1;function i1(K1,e0,G1,c1){if(c1!=null&&typeof c1!=="function")throw Error("task callback must be a function");o1.started=!0;var y4,S6;function A$(PY,...sK){if(PY)return G1?S6(PY):y4();if(sK.length<=1)return y4(sK[0]);y4(sK)}var dz=o1._createTaskItem(K1,G1?A$:c1||A$);if(e0)o1._tasks.unshift(dz);else o1._tasks.push(dz);if(!l1)l1=!0,H(()=>{l1=!1,o1.process()});if(G1||!c1)return new Promise((PY,sK)=>{y4=PY,S6=sK})}function D$(K1){return function(e0,...G1){L0-=1;for(var c1=0,y4=K1.length;c1<y4;c1++){var S6=K1[c1],A$=N0.indexOf(S6);if(A$===0)N0.shift();else if(A$>0)N0.splice(A$,1);if(S6.callback(e0,...G1),e0!=null)x1("error",e0,S6.data)}if(L0<=o1.concurrency-o1.buffer)x1("unsaturated");if(o1.idle())x1("drain");o1.process()}}function pz(K1){if(K1.length===0&&o1.idle())return H(()=>x1("drain")),!0;return!1}let BY=(K1)=>(e0)=>{if(!e0)return new Promise((G1,c1)=>{h0(K1,(y4,S6)=>{if(y4)return c1(y4);G1(S6)})});Y1(K1),P0(K1,e0)};var rK=!1,o1={_tasks:new k1,_createTaskItem(K1,e0){return{data:K1,callback:e0}},*[Symbol.iterator](){yield*o1._tasks[Symbol.iterator]()},concurrency:n,payload:r,buffer:n/4,started:!1,paused:!1,push(K1,e0){if(Array.isArray(K1)){if(pz(K1))return;return K1.map((G1)=>i1(G1,!1,!1,e0))}return i1(K1,!1,!1,e0)},pushAsync(K1,e0){if(Array.isArray(K1)){if(pz(K1))return;return K1.map((G1)=>i1(G1,!1,!0,e0))}return i1(K1,!1,!0,e0)},kill(){Y1(),o1._tasks.empty()},unshift(K1,e0){if(Array.isArray(K1)){if(pz(K1))return;return K1.map((G1)=>i1(G1,!0,!1,e0))}return i1(K1,!0,!1,e0)},unshiftAsync(K1,e0){if(Array.isArray(K1)){if(pz(K1))return;return K1.map((G1)=>i1(G1,!0,!0,e0))}return i1(K1,!0,!0,e0)},remove(K1){o1._tasks.remove(K1)},process(){if(rK)return;rK=!0;while(!o1.paused&&L0<o1.concurrency&&o1._tasks.length){var K1=[],e0=[],G1=o1._tasks.length;if(o1.payload)G1=Math.min(G1,o1.payload);for(var c1=0;c1<G1;c1++){var y4=o1._tasks.shift();K1.push(y4),N0.push(y4),e0.push(y4.data)}if(L0+=1,o1._tasks.length===0)x1("empty");if(L0===o1.concurrency)x1("saturated");var S6=g(D$(K1));K0(e0,S6)}rK=!1},length(){return o1._tasks.length},running(){return L0},workersList(){return N0},idle(){return o1._tasks.length+L0===0},pause(){o1.paused=!0},resume(){if(o1.paused===!1)return;o1.paused=!1,H(o1.process)}};return Object.defineProperties(o1,{saturated:{writable:!1,value:BY("saturated")},unsaturated:{writable:!1,value:BY("unsaturated")},empty:{writable:!1,value:BY("empty")},drain:{writable:!1,value:BY("drain")},error:{writable:!1,value:BY("error")}}),o1}function D0(f,n){return b1(f,1,n)}function I0(f,n,r){return b1(f,n,r)}function B(f,n,r,K0){K0=T(K0);var L0=M(r);return e(f,(N0,B0,P0)=>{L0(n,N0,(h0,Y1)=>{n=Y1,P0(h0)})},(N0)=>K0(N0,n))}var h=F(B,4);function u(...f){var n=f.map(M);return function(...r){var K0=this,L0=r[r.length-1];if(typeof L0=="function")r.pop();else L0=o0();return h(n,r,(N0,B0,P0)=>{B0.apply(K0,N0.concat((h0,...Y1)=>{P0(h0,Y1)}))},(N0,B0)=>L0(N0,...B0)),L0[v0]}}function s(...f){return u(...f.reverse())}function W0(f,n,r,K0){return O(c(n),f,r,K0)}var Q0 Line truncated
GFS4: `),console.error($)};if(!d4[t6]){if(iu=global[t6]||[],wW0(d4,iu),d4.close=function($){function Y(U,z){return $.call(d4,U,function(I){if(!I)FW0();if(typeof z==="function")z.apply(this,arguments)})}return Object.defineProperty(Y,gD,{value:$}),Y}(d4.close),d4.closeSync=function($){function Y(U){$.apply(d4,arguments),FW0()}return Object.defineProperty(Y,gD,{value:$}),Y}(d4.closeSync),/\bgfs4\b/i.test(process.env.NODE_DEBUG||""))process.on("exit",function(){_U(d4[t6]),J0("assert").equal(d4[t6].length,0)})}var iu;if(!global[t6])wW0(global,d4[t6]);pu.exports=cu(JI1(d4));if(process.env.TEST_GRACEFUL_FS_GLOBAL_PATCH&&!d4.__patched)pu.exports=cu(d4),d4.__patched=!0;function cu($){II1($),$.gracefulify=cu,$.createReadStream=P,$.createWriteStream=T;var Y=$.readFile;$.readFile=U;function U(C,b,x){if(typeof b==="function")x=b,b=null;return g(C,b,x);function g(i,c,z0,k){return Y(i,c,function(d){if(d&&(d.code==="EMFILE"||d.code==="ENFILE"))HJ([g,[i,c,z0],d,k||Date.now(),Date.now()]);else if(typeof z0==="function")z0.apply(this,arguments)})}}var z=$.writeFile;$.writeFile=I;function I(C,b,x,g){if(typeof x==="function")g=x,x=null;return i(C,b,x,g);function i(c,z0,k,d,a){return z(c,z0,k,function($0){if($0&&($0.code==="EMFILE"||$0.code==="ENFILE"))HJ([i,[c,z0,k,d],$0,a||Date.now(),Date.now()]);else if(typeof d==="function")d.apply(this,arguments)})}}var Q=$.appendFile;if(Q)$.appendFile=J;function J(C,b,x,g){if(typeof x==="function")g=x,x=null;return i(C,b,x,g);function i(c,z0,k,d,a){return Q(c,z0,k,function($0){if($0&&($0.code==="EMFILE"||$0.code==="ENFILE"))HJ([i,[c,z0,k,d],$0,a||Date.now(),Date.now()]);else if(typeof d==="function")d.apply(this,arguments)})}}var K=$.copyFile;if(K)$.copyFile=G;function G(C,b,x,g){if(typeof x==="function")g=x,x=0;return i(C,b,x,g);function i(c,z0,k,d,a){return K(c,z0,k,function($0){if($0&&($0.code==="EMFILE"||$0.code==="ENFILE"))HJ([i,[c,z0,k,d],$0,a||Date.now(),Date.now()]);else if(typeof d==="function")d.apply(this,arguments)})}}var H=$.readdir;$.readdir=X;var W=/^v[0-5]\./;function X(C,b,x){if(typeof b==="function")x=b,b=null;var g=W.test(process.version)?function(z0,k,d,a){return H(z0,i(z0,k,d,a))}:function(z0,k,d,a){return H(z0,k,i(z0,k,d,a))};return g(C,b,x);function i(c,z0,k,d){return function(a,$0){if(a&&(a.code==="EMFILE"||a.code==="ENFILE"))HJ([g,[c,z0,k],a,d||Date.now(),Date.now()]);else{if($0&&$0.sort)$0.sort();if(typeof k==="function")k.call(this,a,$0)}}}}if(process.version.substr(0,4)==="v0.8"){var Z=QI1($);F=Z.ReadStream,O=Z.WriteStream}var q=$.ReadStream;if(q)F.prototype=Object.create(q.prototype),F.prototype.open=N;var V=$.WriteStream;if(V)O.prototype=Object.create(V.prototype),O.prototype.open=D;Object.defineProperty($,"ReadStream",{get:function(){return F},set:function(C){F=C},enumerable:!0,configurable:!0}),Object.defineProperty($,"WriteStream",{get:function(){return O},set:function(C){O=C},enumerable:!0,configurable:!0});var w=F;Object.defineProperty($,"FileReadStream",{get:function(){return w},set:function(C){w=C},enumerable:!0,configurable:!0});var M=O;Object.defineProperty($,"FileWriteStream",{get:function(){return M},set:function(C){M=C},enumerable:!0,configurable:!0});function F(C,b){if(this instanceof F)return q.apply(this,arguments),this;else return F.apply(Object.create(F.prototype),arguments)}function N(){var C=this;j(C.path,C.flags,C.mode,function(b,x){if(b){if(C.autoClose)C.destroy();C.emit("error",b)}else C.fd=x,C.emit("open",x),C.read()})}function O(C,b){if(this instanceof O)return V.apply(this,arguments),this;else return O.apply(Object.create(O.prototype),arguments)}function D(){var C=this;j(C.path,C.flags,C.mode,function(b,x){if(b)C.destroy(),C.emit("error",b);else C.fd=x,C.emit("open",x)})}function P(C,b){return new $.ReadStream(C,b)}function T(C,b){return new $.WriteStream(C,b)}var A=$.open;$.open=j;function j(C,b,x,g){if(typeof x==="function")g=x,x=null;return i(C,b,x,g);function i(c,z0,k,d,a){return A(c,z0,k,function($0,y){if($0&&($0.code==="EMFILE"||$0.code==="ENFILE"))HJ([i,[c,z0,k,d],$0,a||Date.now(),Date.now()]);else if(typeof d==="function")d.apply(this,arguments)})}}return $}function HJ($){_U("ENQUEUE",$[0].name,$[1]),d4[t6].push($),nu()}var SD;function FW0(){var $=Date.now();for(var Y=0;Y<d4[t6].length;++Y)if(d4[t6][Y].length>2)d4[t6][Y][3]=$,d4[t6][Y][4]=$;nu()}function nu(){if(clearTimeout(SD),SD=void 0,d4[t6].length===0)return;var $=d4[t6].shift(),Y=$[0],U=$[1],z=$[2],I=$[3],Q=$[4];if(I===void 0)_U("RETRY",Y.name,U),Y.apply(null,U);else if(Date.now()-I>=60000){_U("TIMEOUT",Y.name,U);var J=U.pop();if(typeof J==="function")J.call(null,z)}else{var K=Date.now()-Q,G=Math.max(Q-I,1),H=Math.min(G*1.2,100);if(K>=H)_U("RETRY",Y.name,U),Y.apply(null,U.concat([I]));else d4[t6].push($)}if(SD===void 0)SD=setTimeout(nu,0)}});var OW0=E((Qa1,du)=>{function GI1($,Y){if(!($ instanceof Y))throw TypeError("Cannot call a class as a function")}var MW0=J6().Buffer,$X=J0("util");function HI1($,Y,U){$.copy(Y,U)}du.exports=function(){function $(){GI1(this,$),this.h Line truncated
`+n);let[,z0]=r;return z0.replace(/\s/g,"").split(F0).map((L0)=>L0.replace(u0,"").trim())}function P1(f,n){var r={};return Object.keys(f).forEach((z0)=>{var L0=f[z0],N0,A0=q(L0),P0=!A0&&L0.length===1||A0&&L0.length===0;if(Array.isArray(L0))N0=[...L0],L0=N0.pop(),r[z0]=N0.concat(N0.length>0?S0:L0);else if(P0)r[z0]=L0;else{if(N0=c0(L0),L0.length===0&&!A0&&N0.length===0)throw Error("autoInject task functions require explicit parameters.");if(!A0)N0.pop();r[z0]=N0.concat(S0)}function S0(Y1,x1){var o1=N0.map((i1)=>Y1[i1]);o1.push(x1),M(L0)(...o1)}}),q1(r,n)}class k1{constructor(){this.head=this.tail=null,this.length=0}removeLink(f){if(f.prev)f.prev.next=f.next;else this.head=f.next;if(f.next)f.next.prev=f.prev;else this.tail=f.prev;return f.prev=f.next=null,this.length-=1,f}empty(){while(this.head)this.shift();return this}insertAfter(f,n){if(n.prev=f,n.next=f.next,f.next)f.next.prev=n;else this.tail=n;f.next=n,this.length+=1}insertBefore(f,n){if(n.prev=f.prev,n.next=f,f.prev)f.prev.next=n;else this.head=n;f.prev=n,this.length+=1}unshift(f){if(this.head)this.insertBefore(this.head,f);else u1(this,f)}push(f){if(this.tail)this.insertAfter(this.tail,f);else u1(this,f)}shift(){return this.head&&this.removeLink(this.head)}pop(){return this.tail&&this.removeLink(this.tail)}toArray(){return[...this]}*[Symbol.iterator](){var f=this.head;while(f)yield f.data,f=f.next}remove(f){var n=this.head;while(n){var{next:r}=n;if(f(n))this.removeLink(n);n=r}return this}}function u1(f,n){f.length=1,f.head=f.tail=n}function b1(f,n,r){if(n==null)n=1;else if(n===0)throw RangeError("Concurrency must not be zero");var z0=M(f),L0=0,N0=[];let A0={error:[],drain:[],saturated:[],unsaturated:[],empty:[]};function P0(z1,e0){A0[z1].push(e0)}function S0(z1,e0){let G1=(...c1)=>{Y1(z1,G1),e0(...c1)};A0[z1].push(G1)}function Y1(z1,e0){if(!z1)return Object.keys(A0).forEach((G1)=>A0[G1]=[]);if(!e0)return A0[z1]=[];A0[z1]=A0[z1].filter((G1)=>G1!==e0)}function x1(z1,...e0){A0[z1].forEach((G1)=>G1(...e0))}var o1=!1;function i1(z1,e0,G1,c1){if(c1!=null&&typeof c1!=="function")throw Error("task callback must be a function");r1.started=!0;var k4,y6;function C$(TY,...ez){if(TY)return G1?y6(TY):k4();if(ez.length<=1)return k4(ez[0]);k4(ez)}var mI=r1._createTaskItem(z1,G1?C$:c1||C$);if(e0)r1._tasks.unshift(mI);else r1._tasks.push(mI);if(!o1)o1=!0,H(()=>{o1=!1,r1.process()});if(G1||!c1)return new Promise((TY,ez)=>{k4=TY,y6=ez})}function j$(z1){return function(e0,...G1){L0-=1;for(var c1=0,k4=z1.length;c1<k4;c1++){var y6=z1[c1],C$=N0.indexOf(y6);if(C$===0)N0.shift();else if(C$>0)N0.splice(C$,1);if(y6.callback(e0,...G1),e0!=null)x1("error",e0,y6.data)}if(L0<=r1.concurrency-r1.buffer)x1("unsaturated");if(r1.idle())x1("drain");r1.process()}}function pI(z1){if(z1.length===0&&r1.idle())return H(()=>x1("drain")),!0;return!1}let PY=(z1)=>(e0)=>{if(!e0)return new Promise((G1,c1)=>{S0(z1,(k4,y6)=>{if(k4)return c1(k4);G1(y6)})});Y1(z1),P0(z1,e0)};var tz=!1,r1={_tasks:new k1,_createTaskItem(z1,e0){return{data:z1,callback:e0}},*[Symbol.iterator](){yield*r1._tasks[Symbol.iterator]()},concurrency:n,payload:r,buffer:n/4,started:!1,paused:!1,push(z1,e0){if(Array.isArray(z1)){if(pI(z1))return;return z1.map((G1)=>i1(G1,!1,!1,e0))}return i1(z1,!1,!1,e0)},pushAsync(z1,e0){if(Array.isArray(z1)){if(pI(z1))return;return z1.map((G1)=>i1(G1,!1,!0,e0))}return i1(z1,!1,!0,e0)},kill(){Y1(),r1._tasks.empty()},unshift(z1,e0){if(Array.isArray(z1)){if(pI(z1))return;return z1.map((G1)=>i1(G1,!0,!1,e0))}return i1(z1,!0,!1,e0)},unshiftAsync(z1,e0){if(Array.isArray(z1)){if(pI(z1))return;return z1.map((G1)=>i1(G1,!0,!0,e0))}return i1(z1,!0,!0,e0)},remove(z1){r1._tasks.remove(z1)},process(){if(tz)return;tz=!0;while(!r1.paused&&L0<r1.concurrency&&r1._tasks.length){var z1=[],e0=[],G1=r1._tasks.length;if(r1.payload)G1=Math.min(G1,r1.payload);for(var c1=0;c1<G1;c1++){var k4=r1._tasks.shift();z1.push(k4),N0.push(k4),e0.push(k4.data)}if(L0+=1,r1._tasks.length===0)x1("empty");if(L0===r1.concurrency)x1("saturated");var y6=g(j$(z1));z0(e0,y6)}tz=!1},length(){return r1._tasks.length},running(){return L0},workersList(){return N0},idle(){return r1._tasks.length+L0===0},pause(){r1.paused=!0},resume(){if(r1.paused===!1)return;r1.paused=!1,H(r1.process)}};return Object.defineProperties(r1,{saturated:{writable:!1,value:PY("saturated")},unsaturated:{writable:!1,value:PY("unsaturated")},empty:{writable:!1,value:PY("empty")},drain:{writable:!1,value:PY("drain")},error:{writable:!1,value:PY("error")}}),r1}function D0(f,n){return b1(f,1,n)}function Q0(f,n,r){return b1(f,n,r)}function A(f,n,r,z0){z0=T(z0);var L0=M(r);return e(f,(N0,A0,P0)=>{L0(n,N0,(S0,Y1)=>{n=Y1,P0(S0)})},(N0)=>z0(N0,n))}var S=F(A,4);function u(...f){var n=f.map(M);return function(...r){var z0=this,L0=r[r.length-1];if(typeof L0=="function")r.pop();else L0=o0();return S(n,r,(N0,A0,P0)=>{A0.apply(z0,N0.concat((S0,...Y1)=>{P0(S0,Y1)}))},(N0,A0)=>L0(N0,...A0)),L0[v0]}}function s(...f){return u(...f.reverse())}function W0(f,n,r,z0){return O(c(n),f,r,z0)}var J0 Line truncated
GFS4: `),console.error($)};if(!m4[$8]){if(mu=global[$8]||[],SW0(m4,mu),m4.close=function($){function Y(U,I){return $.call(m4,U,function(Q){if(!Q)vW0();if(typeof I==="function")I.apply(this,arguments)})}return Object.defineProperty(Y,cD,{value:$}),Y}(m4.close),m4.closeSync=function($){function Y(U){$.apply(m4,arguments),vW0()}return Object.defineProperty(Y,cD,{value:$}),Y}(m4.closeSync),/\bgfs4\b/i.test(process.env.NODE_DEBUG||""))process.on("exit",function(){vU(m4[$8]),K0("assert").equal(m4[$8].length,0)})}var mu;if(!global[$8])SW0(global,m4[$8]);ru.exports=lu(sQ1(m4));if(process.env.TEST_GRACEFUL_FS_GLOBAL_PATCH&&!m4.__patched)ru.exports=lu(m4),m4.__patched=!0;function lu($){oQ1($),$.gracefulify=lu,$.createReadStream=P,$.createWriteStream=T;var Y=$.readFile;$.readFile=U;function U(C,b,x){if(typeof b==="function")x=b,b=null;return g(C,b,x);function g(i,c,I0,k){return Y(i,c,function(p){if(p&&(p.code==="EMFILE"||p.code==="ENFILE"))WK([g,[i,c,I0],p,k||Date.now(),Date.now()]);else if(typeof I0==="function")I0.apply(this,arguments)})}}var I=$.writeFile;$.writeFile=Q;function Q(C,b,x,g){if(typeof x==="function")g=x,x=null;return i(C,b,x,g);function i(c,I0,k,p,a){return I(c,I0,k,function($0){if($0&&($0.code==="EMFILE"||$0.code==="ENFILE"))WK([i,[c,I0,k,p],$0,a||Date.now(),Date.now()]);else if(typeof p==="function")p.apply(this,arguments)})}}var J=$.appendFile;if(J)$.appendFile=K;function K(C,b,x,g){if(typeof x==="function")g=x,x=null;return i(C,b,x,g);function i(c,I0,k,p,a){return J(c,I0,k,function($0){if($0&&($0.code==="EMFILE"||$0.code==="ENFILE"))WK([i,[c,I0,k,p],$0,a||Date.now(),Date.now()]);else if(typeof p==="function")p.apply(this,arguments)})}}var z=$.copyFile;if(z)$.copyFile=G;function G(C,b,x,g){if(typeof x==="function")g=x,x=0;return i(C,b,x,g);function i(c,I0,k,p,a){return z(c,I0,k,function($0){if($0&&($0.code==="EMFILE"||$0.code==="ENFILE"))WK([i,[c,I0,k,p],$0,a||Date.now(),Date.now()]);else if(typeof p==="function")p.apply(this,arguments)})}}var H=$.readdir;$.readdir=X;var W=/^v[0-5]\./;function X(C,b,x){if(typeof b==="function")x=b,b=null;var g=W.test(process.version)?function(I0,k,p,a){return H(I0,i(I0,k,p,a))}:function(I0,k,p,a){return H(I0,k,i(I0,k,p,a))};return g(C,b,x);function i(c,I0,k,p){return function(a,$0){if(a&&(a.code==="EMFILE"||a.code==="ENFILE"))WK([g,[c,I0,k],a,p||Date.now(),Date.now()]);else{if($0&&$0.sort)$0.sort();if(typeof k==="function")k.call(this,a,$0)}}}}if(process.version.substr(0,4)==="v0.8"){var Z=rQ1($);F=Z.ReadStream,O=Z.WriteStream}var q=$.ReadStream;if(q)F.prototype=Object.create(q.prototype),F.prototype.open=N;var V=$.WriteStream;if(V)O.prototype=Object.create(V.prototype),O.prototype.open=D;Object.defineProperty($,"ReadStream",{get:function(){return F},set:function(C){F=C},enumerable:!0,configurable:!0}),Object.defineProperty($,"WriteStream",{get:function(){return O},set:function(C){O=C},enumerable:!0,configurable:!0});var w=F;Object.defineProperty($,"FileReadStream",{get:function(){return w},set:function(C){w=C},enumerable:!0,configurable:!0});var M=O;Object.defineProperty($,"FileWriteStream",{get:function(){return M},set:function(C){M=C},enumerable:!0,configurable:!0});function F(C,b){if(this instanceof F)return q.apply(this,arguments),this;else return F.apply(Object.create(F.prototype),arguments)}function N(){var C=this;E(C.path,C.flags,C.mode,function(b,x){if(b){if(C.autoClose)C.destroy();C.emit("error",b)}else C.fd=x,C.emit("open",x),C.read()})}function O(C,b){if(this instanceof O)return V.apply(this,arguments),this;else return O.apply(Object.create(O.prototype),arguments)}function D(){var C=this;E(C.path,C.flags,C.mode,function(b,x){if(b)C.destroy(),C.emit("error",b);else C.fd=x,C.emit("open",x)})}function P(C,b){return new $.ReadStream(C,b)}function T(C,b){return new $.WriteStream(C,b)}var B=$.open;$.open=E;function E(C,b,x,g){if(typeof x==="function")g=x,x=null;return i(C,b,x,g);function i(c,I0,k,p,a){return B(c,I0,k,function($0,y){if($0&&($0.code==="EMFILE"||$0.code==="ENFILE"))WK([i,[c,I0,k,p],$0,a||Date.now(),Date.now()]);else if(typeof p==="function")p.apply(this,arguments)})}}return $}function WK($){vU("ENQUEUE",$[0].name,$[1]),m4[$8].push($),ou()}var iD;function vW0(){var $=Date.now();for(var Y=0;Y<m4[$8].length;++Y)if(m4[$8][Y].length>2)m4[$8][Y][3]=$,m4[$8][Y][4]=$;ou()}function ou(){if(clearTimeout(iD),iD=void 0,m4[$8].length===0)return;var $=m4[$8].shift(),Y=$[0],U=$[1],I=$[2],Q=$[3],J=$[4];if(Q===void 0)vU("RETRY",Y.name,U),Y.apply(null,U);else if(Date.now()-Q>=60000){vU("TIMEOUT",Y.name,U);var K=U.pop();if(typeof K==="function")K.call(null,I)}else{var z=Date.now()-J,G=Math.max(J-Q,1),H=Math.min(G*1.2,100);if(z>=H)vU("RETRY",Y.name,U),Y.apply(null,U.concat([Q]));else m4[$8].push($)}if(iD===void 0)iD=setTimeout(ou,0)}});var gW0=j((Pt1,su)=>{function tQ1($,Y){if(!($ instanceof Y))throw TypeError("Cannot call a class as a function")}var hW0=H6().Buffer,IX=K0("util");function eQ1($,Y,U){$.copy(Y,U)}su.exports=function(){function $(){tQ1(this,$),this.h Line truncated
* normalize-path <https://github.com/jonschlinkert/normalize-path>
*
* Copyright (c) 2014-2018, Jon Schlinkert.
* Released under the MIT License.
*/QX0.exports=function($,Y){if(typeof $!=="string")throw TypeError("expected path to be a string");if($==="\\"||$==="/")return"/";var U=$.length;if(U<=1)return $;var z="";if(U>4&&$[3]==="\\"){var I=$[2];if((I==="?"||I===".")&&$.slice(0,2)==="\\\\")$=$.slice(2),z="//"}var Q=$.split(/[/\\]+/);if(Y!==!1&&Q[Q.length-1]==="")Q.pop();return z+Q.join("/")}});var Wb=E((wa1,ZX0)=>{var KX0=9007199254740991,LQ1="[object Arguments]",FQ1="[object Function]",wQ1="[object GeneratorFunction]",MQ1=/^(?:0|[1-9]\d*)$/;function GX0($,Y,U){switch(U.length){case 0:return $.call(Y);case 1:return $.call(Y,U[0]);case 2:return $.call(Y,U[0],U[1]);case 3:return $.call(Y,U[0],U[1],U[2])}return $.apply(Y,U)}function OQ1($,Y){var U=-1,z=Array($);while(++U<$)z[U]=Y(U);return z}var HX=Object.prototype,WX=HX.hasOwnProperty,HX0=HX.toString,NQ1=HX.propertyIsEnumerable,JX0=Math.max;function DQ1($,Y){var U=vQ1($)||_Q1($)?OQ1($.length,String):[],z=U.length,I=!!z;for(var Q in $)if((Y||WX.call($,Q))&&!(I&&(Q=="length"||XX0(Q,z))))U.push(Q);return U}function AQ1($,Y,U,z){if($===void 0||Kb($,HX[U])&&!WX.call(z,U))return Y;return $}function BQ1($,Y,U){var z=$[Y];if(!(WX.call($,Y)&&Kb(z,U))||U===void 0&&!(Y in $))$[Y]=U}function PQ1($){if(!Hb($))return RQ1($);var Y=CQ1($),U=[];for(var z in $)if(!(z=="constructor"&&(Y||!WX.call($,z))))U.push(z);return U}function WX0($,Y){return Y=JX0(Y===void 0?$.length-1:Y,0),function(){var U=arguments,z=-1,I=JX0(U.length-Y,0),Q=Array(I);while(++z<I)Q[z]=U[Y+z];z=-1;var J=Array(Y+1);while(++z<Y)J[z]=U[z];return J[Y]=Q,GX0($,this,J)}}function TQ1($,Y,U,z){U||(U={});var I=-1,Q=Y.length;while(++I<Q){var J=Y[I],K=z?z(U[J],$[J],J,U,$):void 0;BQ1(U,J,K===void 0?$[J]:K)}return U}function jQ1($){return WX0(function(Y,U){var z=-1,I=U.length,Q=I>1?U[I-1]:void 0,J=I>2?U[2]:void 0;if(Q=$.length>3&&typeof Q=="function"?(I--,Q):void 0,J&&EQ1(U[0],U[1],J))Q=I<3?void 0:Q,I=1;Y=Object(Y);while(++z<I){var K=U[z];if(K)$(Y,K,z,Q)}return Y})}function XX0($,Y){return Y=Y==null?KX0:Y,!!Y&&(typeof $=="number"||MQ1.test($))&&($>-1&&$%1==0&&$<Y)}function EQ1($,Y,U){if(!Hb(U))return!1;var z=typeof Y;if(z=="number"?Gb(U)&&XX0(Y,U.length):z=="string"&&(Y in U))return Kb(U[Y],$);return!1}function CQ1($){var Y=$&&$.constructor,U=typeof Y=="function"&&Y.prototype||HX;return $===U}function RQ1($){var Y=[];if($!=null)for(var U in Object($))Y.push(U);return Y}function Kb($,Y){return $===Y||$!==$&&Y!==Y}function _Q1($){return hQ1($)&&WX.call($,"callee")&&(!NQ1.call($,"callee")||HX0.call($)==LQ1)}var vQ1=Array.isArray;function Gb($){return $!=null&&gQ1($.length)&&!SQ1($)}function hQ1($){return yQ1($)&&Gb($)}function SQ1($){var Y=Hb($)?HX0.call($):"";return Y==FQ1||Y==wQ1}function gQ1($){return typeof $=="number"&&$>-1&&$%1==0&&$<=KX0}function Hb($){var Y=typeof $;return!!$&&(Y=="object"||Y=="function")}function yQ1($){return!!$&&typeof $=="object"}var kQ1=jQ1(function($,Y,U,z){TQ1(Y,fQ1(Y),$,z)}),xQ1=WX0(function($){return $.push(void 0,AQ1),GX0(kQ1,void 0,$)});function fQ1($){return Gb($)?DQ1($,!0):PQ1($)}ZX0.exports=xQ1});var VX0=E((Ma1,Xb)=>{function uQ1($,Y){if(!($ instanceof Y))throw TypeError("Cannot call a class as a function")}var qX0=J6().Buffer,XX=J0("util");function bQ1($,Y,U){$.copy(Y,U)}Xb.exports=function(){function $(){uQ1(this,$),this.head=null,this.tail=null,this.length=0}return $.prototype.push=function(U){var z={data:U,next:null};if(this.length>0)this.tail.next=z;else this.head=z;this.tail=z,++this.length},$.prototype.unshift=function(U){var z={data:U,next:this.head};if(this.length===0)this.tail=z;this.head=z,++this.length},$.prototype.shift=function(){if(this.length===0)return;var U=this.head.data;if(this.length===1)this.head=this.tail=null;else this.head=this.head.next;return--this.length,U},$.prototype.clear=function(){this.head=this.tail=null,this.length=0},$.prototype.join=function(U){if(this.length===0)return"";var z=this.head,I=""+z.data;while(z=z.next)I+=U+z.data;return I},$.prototype.concat=function(U){if(this.length===0)return qX0.alloc(0);var z=qX0.allocUnsafe(U>>>0),I=this.head,Q=0;while(I)bQ1(I.data,z,Q),Q+=I.data.length,I=I.next;return z},$}();if(XX&&XX.inspect&&XX.inspect.custom)Xb.exports.prototype[XX.inspect.custom]=function(){var $=XX.inspect({length:this.length});return this.constructor.name+" "+$}});var Zb=E((Oa1,LX0)=>{var lD=Q6();function iQ1($,Y){var U=this,z=this._readableState&&this._readableState.destroyed,I=this._writableState&&this._writableState.destroyed;if(z||I){if(Y)Y($);else if($){if(!this._writableState)lD.nextTick(oD,this,$);else if(!this._writableState.errorEmitted)this._writableState.errorEmitted=!0,lD.nextTick(oD,this,$)}return this}if(this._readableState)this._readableState.destroyed=!0;if(this._writableState)this._writableState.destroyed=!0;return this._destroy($||null,function(Q){if(!Y&&Q){if(!U._writableState)lD.nextTick(oD,U,Q);else if(!U._writableState.errorEmitted)U._writableState.errorEmitted=!0,lD.nextTick(oD,U,Q)}else if(Y)Y(Q)}),this}function cQ1(){if(this._readableState)this._readabl Line truncated
%s`,P,P,N,z);var T=N.type==="*"?sb:N.type==="?"?rb:"\\"+N.type;I=!0,z=z.slice(0,N.reStart)+T+"\\("+P}if(V(),Q)z+="\\\\";var A=!1;switch(z.charAt(0)){case"[":case".":case"(":A=!0}for(var j=K.length-1;j>-1;j--){var C=K[j],b=z.slice(0,C.reStart),x=z.slice(C.reStart,C.reEnd-8),g=z.slice(C.reEnd-8,C.reEnd),i=z.slice(C.reEnd);g+=i;var c=b.split("(").length-1,z0=i;for(w=0;w<c;w++)z0=z0.replace(/\)[+*?]?/,"");i=z0;var k="";if(i===""&&Y!==WA)k="$";var d=b+x+i+k+g;z=d}if(z!==""&&I)z="(?=.)"+z;if(A)z=Z+z;if(Y===WA)return[z,I];if(!I)return KW1($);var a=U.nocase?"i":"";try{var $0=new RegExp("^"+z+"$",a)}catch(y){return new RegExp("$.")}return $0._glob=$,$0._src=z,$0}Z$.makeRe=function($,Y){return new L6($,Y||{}).makeRe()};L6.prototype.makeRe=JW1;function JW1(){if(this.regexp||this.regexp===!1)return this.regexp;var $=this.set;if(!$.length)return this.regexp=!1,this.regexp;var Y=this.options,U=Y.noglobstar?sb:Y.dot?tH1:eH1,z=Y.nocase?"i":"",I=$.map(function(Q){return Q.map(function(J){return J===uU?U:typeof J==="string"?GW1(J):J._src}).join("\\/")}).join("|");if(I="^(?:"+I+")$",this.negate)I="^(?!"+I+").*$";try{this.regexp=new RegExp(I,z)}catch(Q){this.regexp=!1}return this.regexp}Z$.match=function($,Y,U){U=U||{};var z=new L6(Y,U);if($=$.filter(function(I){return z.match(I)}),z.options.nonull&&!$.length)$.push(Y);return $};L6.prototype.match=function(Y,U){if(typeof U>"u")U=this.partial;if(this.debug("match",Y,this.pattern),this.comment)return!1;if(this.empty)return Y==="";if(Y==="/"&&U)return!0;var z=this.options;if(BX.sep!=="/")Y=Y.split(BX.sep).join("/");Y=Y.split(oZ0),this.debug(this.pattern,"split",Y);var I=this.set;this.debug(this.pattern,"set",I);var Q,J;for(J=Y.length-1;J>=0;J--)if(Q=Y[J],Q)break;for(J=0;J<I.length;J++){var K=I[J],G=Y;if(z.matchBase&&K.length===1)G=[Q];var H=this.matchOne(G,K,U);if(H){if(z.flipNegate)return!0;return!this.negate}}if(z.flipNegate)return!1;return this.negate};L6.prototype.matchOne=function($,Y,U){if(Y.indexOf(uU)!==-1)return this._matchGlobstar($,Y,U,0,0);return this._matchOne($,Y,U,0,0)};L6.prototype._matchGlobstar=function($,Y,U,z,I){var Q,J=-1;for(Q=I;Q<Y.length;Q++)if(Y[Q]===uU){J=Q;break}var K=-1;for(Q=Y.length-1;Q>=0;Q--)if(Y[Q]===uU){K=Q;break}var G=Y.slice(I,J),H=U?Y.slice(J+1):Y.slice(J+1,K),W=U?[]:Y.slice(K+1);if(G.length){var X=$.slice(z,z+G.length);if(!this._matchOne(X,G,U,0,0))return!1;z+=G.length}var Z=0;if(W.length){if(W.length+z>$.length)return!1;var q=$.length-W.length;if(this._matchOne($,W,U,q,0))Z=W.length;else{if($[$.length-1]!==""||z+W.length===$.length)return!1;if(q--,!this._matchOne($,W,U,q,0))return!1;Z=W.length+1}}if(!H.length){var V=!!Z;for(Q=z;Q<$.length-Z;Q++){var w=String($[Q]);if(V=!0,w==="."||w===".."||!this.options.dot&&w.charAt(0)===".")return!1}return U||V}var M=[[[],0]],F=M[0],N=0,O=[0];for(var D=0;D<H.length;D++){var P=H[D];if(P===uU)O.push(N),F=[[],0],M.push(F);else F[0].push(P),N++}var T=M.length-1,A=$.length-Z;for(var j=0;j<M.length;j++)M[j][1]=A-(O[T--]+M[j][0].length);return!!this._matchGlobStarBodySections($,M,z,0,U,0,!!Z)};L6.prototype._matchGlobStarBodySections=function($,Y,U,z,I,Q,J){var K=Y[z];if(!K){for(var G=U;G<$.length;G++){J=!0;var H=$[G];if(H==="."||H===".."||!this.options.dot&&H.charAt(0)===".")return!1}return J}var W=K[0],X=K[1];while(U<=X){var Z=this._matchOne($.slice(0,U+W.length),W,I,U,0);if(Z&&Q<this.maxGlobstarRecursion){var q=this._matchGlobStarBodySections($,Y,U+W.length,z+1,I,Q+1,J);if(q!==!1)return q}var H=$[U];if(H==="."||H===".."||!this.options.dot&&H.charAt(0)===".")return!1;U++}return I||null};L6.prototype._matchOne=function($,Y,U,z,I){var Q,J,K,G;for(Q=z,J=I,K=$.length,G=Y.length;Q<K&&J<G;Q++,J++){this.debug("matchOne loop");var H=Y[J],W=$[Q];if(this.debug(Y,H,W),H===!1||H===uU)return!1;var X;if(typeof H==="string")X=W===H,this.debug("string match",H,W,X);else X=W.match(H),this.debug("pattern match",H,W,X);if(!X)return!1}if(Q===K&&J===G)return!0;else if(Q===K)return U;else if(J===G)return Q===K-1&&$[Q]==="";throw Error("wtf?")};function KW1($){return $.replace(/\\(.)/g,"$1")}function GW1($){return $.replace(/[-[\]{}()*+?.,\\^$|#\s]/g,"\\$&")}});var VA=E((ua1,qA)=>{function aZ0($){return $.charAt(0)==="/"}function tZ0($){var Y=/^([a-zA-Z]:|[\\\/]{2}[^\\\/]+[\\\/]+[^\\\/]+)?([\\\/])?([\s\S]*?)$/,U=Y.exec($),z=U[1]||"",I=Boolean(z&&z.charAt(1)!==":");return Boolean(U[2]||I)}qA.exports=process.platform==="win32"?tZ0:aZ0;qA.exports.posix=aZ0;qA.exports.win32=tZ0});var tb=E((MW1)=>{MW1.setopts=VW1;MW1.ownProp=eZ0;MW1.makeAbs=PX;MW1.finish=LW1;MW1.mark=FW1;MW1.isIgnored=Yq0;MW1.childrenIgnored=wW1;function eZ0($,Y){return Object.prototype.hasOwnProperty.call($,Y)}var HW1=J0("fs"),AJ=J0("path"),WW1=ZA(),$q0=VA(),ab=WW1.Minimatch;function XW1($,Y){return $.localeCompare(Y,"en")}function ZW1($,Y){if($.ignore=Y.ignore||[],!Array.isArray($.ignore))$.ignore=[$.ignore];if($.ignore.length)$.ignore=$.ignore.map(qW1)}function qW1($){var Y=null;if($.slice(-3)==="/**"){var U=$.replace(/(\/\*\*)+$/,"");Y=new ab(U,{dot:!0})}return{ma Line truncated
See: https://github.com/isaacs/node-glob/issues/167`);return new j6($,Y).found}function j6($,Y){if(!$)throw Error("must provide pattern");if(typeof Y==="function"||arguments.length===3)throw TypeError(`callback provided to sync glob
See: https://github.com/isaacs/node-glob/issues/167`);if(!(this instanceof j6))return new j6($,Y);if(EW1(this,$,Y),this.noprocess)return this;var U=this.minimatch.set.length;this.matches=Array(U);for(var z=0;z<U;z++)this._process(this.minimatch.set[z],z,!1);this._finish()}j6.prototype._finish=function(){if(zq0.ok(this instanceof j6),this.realpath){var $=this;this.matches.forEach(function(Y,U){var z=$.matches[U]=Object.create(null);for(var I in Y)try{I=$._makeAbs(I);var Q=jW1.realpathSync(I,$.realpathCache);z[Q]=!0}catch(J){if(J.syscall==="stat")z[$._makeAbs(I)]=!0;else throw J}})}bU.finish(this)};j6.prototype._process=function($,Y,U){zq0.ok(this instanceof j6);var z=0;while(typeof $[z]==="string")z++;var I;switch(z){case $.length:this._processSimple($.join("/"),Y);return;case 0:I=null;break;default:I=$.slice(0,z).join("/");break}var Q=$.slice(z),J;if(I===null)J=".";else if(LA(I)||LA($.map(function(H){return typeof H==="string"?H:"[*]"}).join("/"))){if(!I||!LA(I))I="/"+I;J=I}else J=I;var K=this._makeAbs(J);if(CW1(this,J))return;var G=Q[0]===Uq0.GLOBSTAR;if(G)this._processGlobStar(I,J,K,Q,Y,U);else this._processReaddir(I,J,K,Q,Y,U)};j6.prototype._processReaddir=function($,Y,U,z,I,Q){var J=this._readdir(U,Q);if(!J)return;var K=z[0],G=!!this.minimatch.negate,H=K._glob,W=this.dot||H.charAt(0)===".",X=[];for(var Z=0;Z<J.length;Z++){var q=J[Z];if(q.charAt(0)!=="."||W){var V;if(G&&!$)V=!q.match(K);else V=q.match(K);if(V)X.push(q)}}var w=X.length;if(w===0)return;if(z.length===1&&!this.mark&&!this.stat){if(!this.matches[I])this.matches[I]=Object.create(null);for(var Z=0;Z<w;Z++){var q=X[Z];if($)if($.slice(-1)!=="/")q=$+"/"+q;else q=$+q;if(q.charAt(0)==="/"&&!this.nomount)q=eb.join(this.root,q);this._emitMatch(I,q)}return}z.shift();for(var Z=0;Z<w;Z++){var q=X[Z],M;if($)M=[$,q];else M=[q];this._process(M.concat(z),I,Q)}};j6.prototype._emitMatch=function($,Y){if(RW1(this,Y))return;var U=this._makeAbs(Y);if(this.mark)Y=this._mark(Y);if(this.absolute)Y=U;if(this.matches[$][Y])return;if(this.nodir){var z=this.cache[U];if(z==="DIR"||Array.isArray(z))return}if(this.matches[$][Y]=!0,this.stat)this._stat(Y)};j6.prototype._readdirInGlobStar=function($){if(this.follow)return this._readdir($,!1);var Y,U,z;try{U=this.fs.lstatSync($)}catch(Q){if(Q.code==="ENOENT")return null}var I=U&&U.isSymbolicLink();if(this.symlinks[$]=I,!I&&U&&!U.isDirectory())this.cache[$]="FILE";else Y=this._readdir($,!1);return Y};j6.prototype._readdir=function($,Y){var U;if(Y&&!$i(this.symlinks,$))return this._readdirInGlobStar($);if($i(this.cache,$)){var z=this.cache[$];if(!z||z==="FILE")return null;if(Array.isArray(z))return z}try{return this._readdirEntries($,this.fs.readdirSync($))}catch(I){return this._readdirError($,I),null}};j6.prototype._readdirEntries=function($,Y){if(!this.mark&&!this.stat)for(var U=0;U<Y.length;U++){var z=Y[U];if($==="/")z=$+z;else z=$+"/"+z;this.cache[z]=!0}return this.cache[$]=Y,Y};j6.prototype._readdirError=function($,Y){switch(Y.code){case"ENOTSUP":case"ENOTDIR":var U=this._makeAbs($);if(this.cache[U]="FILE",U===this.cwdAbs){var z=Error(Y.code+" invalid cwd "+this.cwd);throw z.path=this.cwd,z.code=Y.code,z}break;case"ENOENT":case"ELOOP":case"ENAMETOOLONG":case"UNKNOWN":this.cache[this._makeAbs($)]=!1;break;default:if(this.cache[this._makeAbs($)]=!1,this.strict)throw Y;if(!this.silent)console.error("glob error",Y);break}};j6.prototype._processGlobStar=function($,Y,U,z,I,Q){var J=this._readdir(U,Q);if(!J)return;var K=z.slice(1),G=$?[$]:[],H=G.concat(K);this._process(H,I,!1);var W=J.length,X=this.symlinks[U];if(X&&Q)return;for(var Z=0;Z<W;Z++){var q=J[Z];if(q.charAt(0)==="."&&!this.dot)continue;var V=G.concat(J[Z],K);this._process(V,I,!0);var w=G.concat(J[Z],z);this._process(w,I,!0)}};j6.prototype._processSimple=function($,Y){var U=this._stat($);if(!this.matches[Y])this.matches[Y]=Object.create(null);if(!U)return;if($&&LA($)&&!this.nomount){var z=/[\/\\]$/.test($);if($.charAt(0)==="/")$=eb.join(this.root,$);else if($=eb.resolve(this.root,$),z)$+="/"}if(process.platform==="win32")$=$.replace(/\\/g,"/");this._emitMatch(Y,$)};j6.prototype._stat=function($){var Y=this._makeAbs($),U=$.slice(-1)==="/";if($.length>this.maxLength)return!1;if(!this.stat&&$i(this.cache,Y)){var J=this.cache[Y];if(Array.isArray(J))J="DIR";if(!U||J==="DIR")return J;if(U&&J==="FILE")return!1}var z,I=this.statCache[Y];if(!I){var Q;try{Q=this.fs.lstatSync(Y)}catch(K){if(K&&(K.code==="ENOENT"||K.code==="ENOTDIR"))return this.statCache[Y]=!1,!1}if(Q&&Q.isSymbolicLink())try{I=this.fs.statSync(Y)}catch(K){I=Q}else I=Q}this.statCache[Y]=I;var J=!0;if(I)J=I.isDirectory()?"DIR":"FILE";if(this.cache[Y]=this.cache[Y]||J,U&&J==="FILE")return!1;return J};j6.prototype._mark=function($){return bU.mark(this,$)};j6.prototype._makeAbs=function($){return bU.makeAbs(this,$)}});var Yi=E((da1,Gq0)=>{Gq0.exports=Kq0;function Kq0($,Y){if($&&Y)return Kq0($)(Y);if(typeof $!=="function")throw TypeError("need wrapper function");return Object.keys($).forEach(function(z){U[z]=$[z]}),U;f Line truncated
`);if($.linkname)Y+=ei(" linkpath="+$.linkname+`
`);var U=$.pax;if(U)for(var z in U)Y+=ei(" "+z+"="+U[z]+`
`);return Buffer.from(Y)};uq1.decodePax=function($){var Y={};while($.length){var U=0;while(U<$.length&&$[U]!==32)U++;var z=parseInt($.slice(0,U).toString(),10);if(!z)return Y;var I=$.slice(U+1,z-1).toString(),Q=I.indexOf("=");if(Q===-1)return Y;Y[I.slice(0,Q)]=I.slice(Q+1),$=$.slice(z)}return Y};uq1.encode=function($){var Y=Cq1(512),U=$.name,z="";if($.typeflag===5&&U[U.length-1]!=="/")U+="/";if(Buffer.byteLength(U)!==U.length)return null;while(Buffer.byteLength(U)>100){var I=U.indexOf("/");if(I===-1)return null;z+=z?"/"+U.slice(0,I):U.slice(0,I),U=U.slice(I+1)}if(Buffer.byteLength(U)>100||Buffer.byteLength(z)>155)return null;if($.linkname&&Buffer.byteLength($.linkname)>100)return null;if(Y.write(U),Y.write(E2($.mode&gq1,6),100),Y.write(E2($.uid,6),108),Y.write(E2($.gid,6),116),Y.write(E2($.size,11),124),Y.write(E2($.mtime.getTime()/1000|0,11),136),Y[156]=AL0+xq1($.type),$.linkname)Y.write($.linkname,157);if(BL0.copy(Y,bX),vq1.copy(Y,$c),$.uname)Y.write($.uname,265);if($.gname)Y.write($.gname,297);if(Y.write(E2($.devmajor||0,6),329),Y.write(E2($.devminor||0,6),337),z)Y.write(z,345);return Y.write(E2(TL0(Y),6),148),Y};uq1.decode=function($,Y,U){var z=$[156]===0?0:$[156]-AL0,I=vJ($,0,100,Y),Q=C2($,100,8),J=C2($,108,8),K=C2($,116,8),G=C2($,124,12),H=C2($,136,12),W=kq1(z),X=$[157]===0?null:vJ($,157,100,Y),Z=vJ($,265,32),q=vJ($,297,32),V=C2($,329,8),w=C2($,337,8),M=TL0($);if(M===256)return null;if(M!==C2($,148,8))throw Error("Invalid tar header. Maybe the tar is corrupted or it needs to be gunzipped?");if(BL0.compare($,bX,bX+6)===0){if($[345])I=vJ($,345,155,Y)+"/"+I}else if(hq1.compare($,bX,bX+6)===0&&Sq1.compare($,$c,$c+2)===0);else if(!U)throw Error("Invalid tar header: unknown format.");if(z===0&&I&&I[I.length-1]==="/")z=5;return{name:I,mode:Q,uid:J,gid:K,size:G,mtime:new Date(1000*H),type:W,linkname:X,uname:Z,gname:q,devmajor:V,devminor:w}}});var hL0=E((ut1,vL0)=>{var EL0=J0("util"),dq1=DL0(),iX=Yc(),CL0=v8().Writable,RL0=v8().PassThrough,_L0=function(){},jL0=function($){return $&=511,$&&512-$},mq1=function($,Y){var U=new yA($,Y);return U.end(),U},lq1=function($,Y){if(Y.path)$.name=Y.path;if(Y.linkpath)$.linkname=Y.linkpath;if(Y.size)$.size=parseInt(Y.size,10);return $.pax=Y,$},yA=function($,Y){this._parent=$,this.offset=Y,RL0.call(this,{autoDestroy:!1})};EL0.inherits(yA,RL0);yA.prototype.destroy=function($){this._parent.destroy($)};var C3=function($){if(!(this instanceof C3))return new C3($);CL0.call(this,$),$=$||{},this._offset=0,this._buffer=dq1(),this._missing=0,this._partial=!1,this._onparse=_L0,this._header=null,this._stream=null,this._overflow=null,this._cb=null,this._locked=!1,this._destroyed=!1,this._pax=null,this._paxGlobal=null,this._gnuLongPath=null,this._gnuLongLinkPath=null;var Y=this,U=Y._buffer,z=function(){Y._continue()},I=function(Z){if(Y._locked=!1,Z)return Y.destroy(Z);if(!Y._stream)z()},Q=function(){Y._stream=null;var Z=jL0(Y._header.size);if(Z)Y._parse(Z,J);else Y._parse(512,X);if(!Y._locked)z()},J=function(){Y._buffer.consume(jL0(Y._header.size)),Y._parse(512,X),z()},K=function(){var Z=Y._header.size;Y._paxGlobal=iX.decodePax(U.slice(0,Z)),U.consume(Z),Q()},G=function(){var Z=Y._header.size;if(Y._pax=iX.decodePax(U.slice(0,Z)),Y._paxGlobal)Y._pax=Object.assign({},Y._paxGlobal,Y._pax);U.consume(Z),Q()},H=function(){var Z=Y._header.size;this._gnuLongPath=iX.decodeLongPath(U.slice(0,Z),$.filenameEncoding),U.consume(Z),Q()},W=function(){var Z=Y._header.size;this._gnuLongLinkPath=iX.decodeLongPath(U.slice(0,Z),$.filenameEncoding),U.consume(Z),Q()},X=function(){var Z=Y._offset,q;try{q=Y._header=iX.decode(U.slice(0,512),$.filenameEncoding,$.allowUnknownFormat)}catch(V){Y.emit("error",V)}if(U.consume(512),!q){Y._parse(512,X),z();return}if(q.type==="gnu-long-path"){Y._parse(q.size,H),z();return}if(q.type==="gnu-long-link-path"){Y._parse(q.size,W),z();return}if(q.type==="pax-global-header"){Y._parse(q.size,K),z();return}if(q.type==="pax-header"){Y._parse(q.size,G),z();return}if(Y._gnuLongPath)q.name=Y._gnuLongPath,Y._gnuLongPath=null;if(Y._gnuLongLinkPath)q.linkname=Y._gnuLongLinkPath,Y._gnuLongLinkPath=null;if(Y._pax)Y._header=q=lq1(q,Y._pax),Y._pax=null;if(Y._locked=!0,!q.size||q.type==="directory"){Y._parse(512,X),Y.emit("entry",q,mq1(Y,Z),I);return}Y._stream=new yA(Y,Z),Y.emit("entry",q,Y._stream,I),Y._parse(q.size,Q),z()};this._onheader=X,this._parse(512,X)};EL0.inherits(C3,CL0);C3.prototype.destroy=function($){if(this._destroyed)return;if(this._destroyed=!0,$)this.emit("error",$);if(this.emit("close"),this._stream)this._stream.emit("close")};C3.prototype._parse=function($,Y){if(this._destroyed)return;if(this._offset+=$,this._missing=$,Y===this._onheader)this._partial=!1;this._onparse=Y};C3.prototype._continue=function(){if(this._destroyed)return;var $=this._cb;if(this._cb=_L0,this._overflow)this._write(this._overflow,void 0,$);else $()};C3.prototype._write=function($,Y,U){if(this._destroyed)return;var z=this._stream,I=this._buffer,Q=this._missing;if($.length)this._partial=!0;if($.length<Q) Line truncated
<Relationships xmlns="http://schemas.openxmlformats.org/package/2006/relationships">`)}_writeRelationship($){if(!this.count)this._writeOpen();let Y=`rId${++this.count}`;if($.TargetMode)this.stream.write(`<Relationship Id="${Y}" Type="${$.Type}" Target="${ZV1.xmlEncode($.Target)}" TargetMode="${$.TargetMode}"/>`);else this.stream.write(`<Relationship Id="${Y}" Type="${$.Type}" Target="${$.Target}"/>`);return Y}_writeClose(){this.stream.write("</Relationships>")}}IF0.exports=zF0});var WF0=E((rt1,HF0)=>{var JF0=r6(),KF0=Q2(),VV1=c4(),LV1=Vf(),FV1=Ff();class GF0{constructor($,Y,U){this.id=U.id,this.count=0,this._worksheet=$,this._workbook=U.workbook,this._sheetRelsWriter=Y}get commentsStream(){if(!this._commentsStream)this._commentsStream=this._workbook._openStream(`/xl/comments${this.id}.xml`);return this._commentsStream}get vmlStream(){if(!this._vmlStream)this._vmlStream=this._workbook._openStream(`xl/drawings/vmlDrawing${this.id}.vml`);return this._vmlStream}_addRelationships(){let $={Type:KF0.Comments,Target:`../comments${this.id}.xml`};this._sheetRelsWriter.addRelationship($);let Y={Type:KF0.VmlDrawing,Target:`../drawings/vmlDrawing${this.id}.vml`};this.vmlRelId=this._sheetRelsWriter.addRelationship(Y)}_addCommentRefs(){this._workbook.commentRefs.push({commentName:`comments${this.id}`,vmlDrawing:`vmlDrawing${this.id}`})}_writeOpen(){this.commentsStream.write('<?xml version="1.0" encoding="UTF-8" standalone="yes"?><comments xmlns="http://schemas.openxmlformats.org/spreadsheetml/2006/main"><authors><author>Author</author></authors><commentList>'),this.vmlStream.write('<?xml version="1.0" encoding="UTF-8"?><xml xmlns:o="urn:schemas-microsoft-com:office:office" xmlns:v="urn:schemas-microsoft-com:vml" xmlns:x="urn:schemas-microsoft-com:office:excel"><o:shapelayout v:ext="edit"><o:idmap v:ext="edit" data="1" /></o:shapelayout><v:shapetype id="_x0000_t202" coordsize="21600,21600" o:spt="202" path="m,l,21600r21600,l21600,xe"><v:stroke joinstyle="miter" /><v:path gradientshapeok="t" o:connecttype="rect" /></v:shapetype>')}_writeComment($,Y){let U=new LV1,z=new JF0;U.render(z,$),this.commentsStream.write(z.xml);let I=new FV1,Q=new JF0;I.render(Q,$,Y),this.vmlStream.write(Q.xml)}_writeClose(){this.commentsStream.write("</commentList></comments>"),this.vmlStream.write("</xml>")}addComments($){if($&&$.length){if(!this.startedData)this._worksheet.comments=[],this._writeOpen(),this._addRelationships(),this._addCommentRefs(),this.startedData=!0;$.forEach((Y)=>{Y.refAddress=VV1.decodeAddress(Y.ref)}),$.forEach((Y)=>{this._writeComment(Y,this.count),this.count+=1})}}commit(){if(this.count)this._writeClose(),this.commentsStream.end(),this.vmlStream.end()}}HF0.exports=GF0});var FF0=E((st1,LF0)=>{var wV1=$6(),MV1=Q2(),Ic=c4(),XF0=Sg(),ZF0=Q3(),OV1=lk(),qF0=bM(),Qc=cM(),NV1=QF0(),DV1=WF0(),AV1=vg(),x6=new OV1,Jc=U2(),BV1=cx(),PV1=nx(),TV1=px(),jV1=fx(),EV1=kx(),CV1=ux(),RV1=dx(),_V1=mx(),vV1=lx(),hV1=ox(),SV1=rx(),gV1=sx(),yV1=Yf(),kV1=tx(),xV1=ax(),f6={dataValidations:new BV1,sheetProperties:new PV1,sheetFormatProperties:new TV1,columns:new Jc({tag:"cols",length:!1,childXform:new jV1}),row:new EV1,hyperlinks:new Jc({tag:"hyperlinks",length:!1,childXform:new CV1}),sheetViews:new Jc({tag:"sheetViews",length:!1,childXform:new RV1}),sheetProtection:new _V1,pageMargins:new vV1,pageSeteup:new hV1,autoFilter:new SV1,picture:new gV1,conditionalFormattings:new yV1,headerFooter:new kV1,rowBreaks:new xV1};class VF0{constructor($){this.id=$.id,this.name=$.name||`Sheet${this.id}`,this.state=$.state||"visible",this._rows=[],this._columns=null,this._keys={},this._merges=[],this._merges.add=function(){},this._sheetRelsWriter=new NV1($),this._sheetCommentsWriter=new DV1(this,this._sheetRelsWriter,$),this._dimensions=new ZF0,this._rowZero=1,this.committed=!1,this.dataValidations=new AV1,this._formulae={},this._siFormulae=0,this.conditionalFormatting=[],this.rowBreaks=[],this.properties=Object.assign({},{defaultRowHeight:15,dyDescent:55,outlineLevelCol:0,outlineLevelRow:0},$.properties),this.headerFooter=Object.assign({},{differentFirst:!1,differentOddEven:!1,oddHeader:null,oddFooter:null,evenHeader:null,evenFooter:null,firstHeader:null,firstFooter:null},$.headerFooter),this.pageSetup=Object.assign({},{margins:{left:0.7,right:0.7,top:0.75,bottom:0.75,header:0.3,footer:0.3},orientation:"portrait",horizontalDpi:4294967295,verticalDpi:4294967295,fitToPage:!!($.pageSetup&&($.pageSetup.fitToWidth||$.pageSetup.fitToHeight)&&!$.pageSetup.scale),pageOrder:"downThenOver",blackAndWhite:!1,draft:!1,cellComments:"None",errors:"displayed",scale:100,fitToWidth:1,fitToHeight:1,paperSize:void 0,showRowColHeaders:!1,showGridLines:!1,horizontalCentered:!1,verticalCentered:!1,rowBreaks:null,colBreaks:null},$.pageSetup),this.useSharedStrings=$.useSharedStrings||!1,this._workbook=$.workbook,this.hasComments=!1,this._views=$.views||[],this.autoFilter=$.autoFilter||null,this._media=[],this.sheetProtection=null,this._writeOpenWorksheet(),this.startedData=!1}get Line truncated
*/NX0.exports=function($,Y){if(typeof $!=="string")throw TypeError("expected path to be a string");if($==="\\"||$==="/")return"/";var U=$.length;if(U<=1)return $;var I="";if(U>4&&$[3]==="\\"){var Q=$[2];if((Q==="?"||Q===".")&&$.slice(0,2)==="\\\\")$=$.slice(2),I="//"}var J=$.split(/[/\\]+/);if(Y!==!1&&J[J.length-1]==="")J.pop();return I+J.join("/")}});var Lb=j((kt1,jX0)=>{var BX0=9007199254740991,JK1="[object Arguments]",KK1="[object Function]",zK1="[object GeneratorFunction]",GK1=/^(?:0|[1-9]\d*)$/;function AX0($,Y,U){switch(U.length){case 0:return $.call(Y);case 1:return $.call(Y,U[0]);case 2:return $.call(Y,U[0],U[1]);case 3:return $.call(Y,U[0],U[1],U[2])}return $.apply(Y,U)}function HK1($,Y){var U=-1,I=Array($);while(++U<$)I[U]=Y(U);return I}var ZX=Object.prototype,qX=ZX.hasOwnProperty,PX0=ZX.toString,WK1=ZX.propertyIsEnumerable,DX0=Math.max;function XK1($,Y){var U=DK1($)||NK1($)?HK1($.length,String):[],I=U.length,Q=!!I;for(var J in $)if((Y||qX.call($,J))&&!(Q&&(J=="length"||EX0(J,I))))U.push(J);return U}function ZK1($,Y,U,I){if($===void 0||Zb($,ZX[U])&&!qX.call(I,U))return Y;return $}function qK1($,Y,U){var I=$[Y];if(!(qX.call($,Y)&&Zb(I,U))||U===void 0&&!(Y in $))$[Y]=U}function VK1($){if(!Vb($))return OK1($);var Y=MK1($),U=[];for(var I in $)if(!(I=="constructor"&&(Y||!qX.call($,I))))U.push(I);return U}function TX0($,Y){return Y=DX0(Y===void 0?$.length-1:Y,0),function(){var U=arguments,I=-1,Q=DX0(U.length-Y,0),J=Array(Q);while(++I<Q)J[I]=U[Y+I];I=-1;var K=Array(Y+1);while(++I<Y)K[I]=U[I];return K[Y]=J,AX0($,this,K)}}function LK1($,Y,U,I){U||(U={});var Q=-1,J=Y.length;while(++Q<J){var K=Y[Q],z=I?I(U[K],$[K],K,U,$):void 0;qK1(U,K,z===void 0?$[K]:z)}return U}function FK1($){return TX0(function(Y,U){var I=-1,Q=U.length,J=Q>1?U[Q-1]:void 0,K=Q>2?U[2]:void 0;if(J=$.length>3&&typeof J=="function"?(Q--,J):void 0,K&&wK1(U[0],U[1],K))J=Q<3?void 0:J,Q=1;Y=Object(Y);while(++I<Q){var z=U[I];if(z)$(Y,z,I,J)}return Y})}function EX0($,Y){return Y=Y==null?BX0:Y,!!Y&&(typeof $=="number"||GK1.test($))&&($>-1&&$%1==0&&$<Y)}function wK1($,Y,U){if(!Vb(U))return!1;var I=typeof Y;if(I=="number"?qb(U)&&EX0(Y,U.length):I=="string"&&(Y in U))return Zb(U[Y],$);return!1}function MK1($){var Y=$&&$.constructor,U=typeof Y=="function"&&Y.prototype||ZX;return $===U}function OK1($){var Y=[];if($!=null)for(var U in Object($))Y.push(U);return Y}function Zb($,Y){return $===Y||$!==$&&Y!==Y}function NK1($){return BK1($)&&qX.call($,"callee")&&(!WK1.call($,"callee")||PX0.call($)==JK1)}var DK1=Array.isArray;function qb($){return $!=null&&PK1($.length)&&!AK1($)}function BK1($){return TK1($)&&qb($)}function AK1($){var Y=Vb($)?PX0.call($):"";return Y==KK1||Y==zK1}function PK1($){return typeof $=="number"&&$>-1&&$%1==0&&$<=BX0}function Vb($){var Y=typeof $;return!!$&&(Y=="object"||Y=="function")}function TK1($){return!!$&&typeof $=="object"}var EK1=FK1(function($,Y,U,I){LK1(Y,CK1(Y),$,I)}),jK1=TX0(function($){return $.push(void 0,ZK1),AX0(EK1,void 0,$)});function CK1($){return qb($)?XK1($,!0):VK1($)}jX0.exports=jK1});var RX0=j((xt1,Fb)=>{function RK1($,Y){if(!($ instanceof Y))throw TypeError("Cannot call a class as a function")}var CX0=H6().Buffer,VX=K0("util");function _K1($,Y,U){$.copy(Y,U)}Fb.exports=function(){function $(){RK1(this,$),this.head=null,this.tail=null,this.length=0}return $.prototype.push=function(U){var I={data:U,next:null};if(this.length>0)this.tail.next=I;else this.head=I;this.tail=I,++this.length},$.prototype.unshift=function(U){var I={data:U,next:this.head};if(this.length===0)this.tail=I;this.head=I,++this.length},$.prototype.shift=function(){if(this.length===0)return;var U=this.head.data;if(this.length===1)this.head=this.tail=null;else this.head=this.head.next;return--this.length,U},$.prototype.clear=function(){this.head=this.tail=null,this.length=0},$.prototype.join=function(U){if(this.length===0)return"";var I=this.head,Q=""+I.data;while(I=I.next)Q+=U+I.data;return Q},$.prototype.concat=function(U){if(this.length===0)return CX0.alloc(0);var I=CX0.allocUnsafe(U>>>0),Q=this.head,J=0;while(Q)_K1(Q.data,I,J),J+=Q.data.length,Q=Q.next;return I},$}();if(VX&&VX.inspect&&VX.inspect.custom)Fb.exports.prototype[VX.inspect.custom]=function(){var $=VX.inspect({length:this.length});return this.constructor.name+" "+$}});var wb=j((ft1,_X0)=>{var YB=G6();function vK1($,Y){var U=this,I=this._readableState&&this._readableState.destroyed,Q=this._writableState&&this._writableState.destroyed;if(I||Q){if(Y)Y($);else if($){if(!this._writableState)YB.nextTick(UB,this,$);else if(!this._writableState.errorEmitted)this._writableState.errorEmitted=!0,YB.nextTick(UB,this,$)}return this}if(this._readableState)this._readableState.destroyed=!0;if(this._writableState)this._writableState.destroyed=!0;return this._destroy($||null,function(J){if(!Y&&J){if(!U._writableState)YB.nextTick(UB,U,J);else if(!U._writableState.errorEmitted)U._writableState.errorEmitted=!0,YB.nextTick(UB,U,J)}else if(Y)Y(J)}),this}function SK1(){if(this._readableState)this._readabl Line truncated
%s`,P,P,N,I);var T=N.type==="*"?Yi:N.type==="?"?$i:"\\"+N.type;Q=!0,I=I.slice(0,N.reStart)+T+"\\("+P}if(V(),J)I+="\\\\";var B=!1;switch(I.charAt(0)){case"[":case".":case"(":B=!0}for(var E=z.length-1;E>-1;E--){var C=z[E],b=I.slice(0,C.reStart),x=I.slice(C.reStart,C.reEnd-8),g=I.slice(C.reEnd-8,C.reEnd),i=I.slice(C.reEnd);g+=i;var c=b.split("(").length-1,I0=i;for(w=0;w<c;w++)I0=I0.replace(/\)[+*?]?/,"");i=I0;var k="";if(i===""&&Y!==MB)k="$";var p=b+x+i+k+g;I=p}if(I!==""&&Q)I="(?=.)"+I;if(B)I=Z+I;if(Y===MB)return[I,Q];if(!Q)return aW1($);var a=U.nocase?"i":"";try{var $0=new RegExp("^"+I+"$",a)}catch(y){return new RegExp("$.")}return $0._glob=$,$0._src=I,$0}w$.makeRe=function($,Y){return new w6($,Y||{}).makeRe()};w6.prototype.makeRe=sW1;function sW1(){if(this.regexp||this.regexp===!1)return this.regexp;var $=this.set;if(!$.length)return this.regexp=!1,this.regexp;var Y=this.options,U=Y.noglobstar?Yi:Y.dot?cW1:nW1,I=Y.nocase?"i":"",Q=$.map(function(J){return J.map(function(K){return K===bU?U:typeof K==="string"?tW1(K):K._src}).join("\\/")}).join("|");if(Q="^(?:"+Q+")$",this.negate)Q="^(?!"+Q+").*$";try{this.regexp=new RegExp(Q,I)}catch(J){this.regexp=!1}return this.regexp}w$.match=function($,Y,U){U=U||{};var I=new w6(Y,U);if($=$.filter(function(Q){return I.match(Q)}),I.options.nonull&&!$.length)$.push(Y);return $};w6.prototype.match=function(Y,U){if(typeof U>"u")U=this.partial;if(this.debug("match",Y,this.pattern),this.comment)return!1;if(this.empty)return Y==="";if(Y==="/"&&U)return!0;var I=this.options;if(EX.sep!=="/")Y=Y.split(EX.sep).join("/");Y=Y.split(Hq0),this.debug(this.pattern,"split",Y);var Q=this.set;this.debug(this.pattern,"set",Q);var J,K;for(K=Y.length-1;K>=0;K--)if(J=Y[K],J)break;for(K=0;K<Q.length;K++){var z=Q[K],G=Y;if(I.matchBase&&z.length===1)G=[J];var H=this.matchOne(G,z,U);if(H){if(I.flipNegate)return!0;return!this.negate}}if(I.flipNegate)return!1;return this.negate};w6.prototype.matchOne=function($,Y,U){if(Y.indexOf(bU)!==-1)return this._matchGlobstar($,Y,U,0,0);return this._matchOne($,Y,U,0,0)};w6.prototype._matchGlobstar=function($,Y,U,I,Q){var J,K=-1;for(J=Q;J<Y.length;J++)if(Y[J]===bU){K=J;break}var z=-1;for(J=Y.length-1;J>=0;J--)if(Y[J]===bU){z=J;break}var G=Y.slice(Q,K),H=U?Y.slice(K+1):Y.slice(K+1,z),W=U?[]:Y.slice(z+1);if(G.length){var X=$.slice(I,I+G.length);if(!this._matchOne(X,G,U,0,0))return!1;I+=G.length}var Z=0;if(W.length){if(W.length+I>$.length)return!1;var q=$.length-W.length;if(this._matchOne($,W,U,q,0))Z=W.length;else{if($[$.length-1]!==""||I+W.length===$.length)return!1;if(q--,!this._matchOne($,W,U,q,0))return!1;Z=W.length+1}}if(!H.length){var V=!!Z;for(J=I;J<$.length-Z;J++){var w=String($[J]);if(V=!0,w==="."||w===".."||!this.options.dot&&w.charAt(0)===".")return!1}return U||V}var M=[[[],0]],F=M[0],N=0,O=[0];for(var D=0;D<H.length;D++){var P=H[D];if(P===bU)O.push(N),F=[[],0],M.push(F);else F[0].push(P),N++}var T=M.length-1,B=$.length-Z;for(var E=0;E<M.length;E++)M[E][1]=B-(O[T--]+M[E][0].length);return!!this._matchGlobStarBodySections($,M,I,0,U,0,!!Z)};w6.prototype._matchGlobStarBodySections=function($,Y,U,I,Q,J,K){var z=Y[I];if(!z){for(var G=U;G<$.length;G++){K=!0;var H=$[G];if(H==="."||H===".."||!this.options.dot&&H.charAt(0)===".")return!1}return K}var W=z[0],X=z[1];while(U<=X){var Z=this._matchOne($.slice(0,U+W.length),W,Q,U,0);if(Z&&J<this.maxGlobstarRecursion){var q=this._matchGlobStarBodySections($,Y,U+W.length,I+1,Q,J+1,K);if(q!==!1)return q}var H=$[U];if(H==="."||H===".."||!this.options.dot&&H.charAt(0)===".")return!1;U++}return Q||null};w6.prototype._matchOne=function($,Y,U,I,Q){var J,K,z,G;for(J=I,K=Q,z=$.length,G=Y.length;J<z&&K<G;J++,K++){this.debug("matchOne loop");var H=Y[K],W=$[J];if(this.debug(Y,H,W),H===!1||H===bU)return!1;var X;if(typeof H==="string")X=W===H,this.debug("string match",H,W,X);else X=W.match(H),this.debug("pattern match",H,W,X);if(!X)return!1}if(J===z&&K===G)return!0;else if(J===z)return U;else if(K===G)return J===z-1&&$[J]==="";throw Error("wtf?")};function aW1($){return $.replace(/\\(.)/g,"$1")}function tW1($){return $.replace(/[-[\]{}()*+?.,\\^$|#\s]/g,"\\$&")}});var BB=j((Qe1,DB)=>{function Zq0($){return $.charAt(0)==="/"}function qq0($){var Y=/^([a-zA-Z]:|[\\\/]{2}[^\\\/]+[\\\/]+[^\\\/]+)?([\\\/])?([\s\S]*?)$/,U=Y.exec($),I=U[1]||"",Q=Boolean(I&&I.charAt(1)!==":");return Boolean(U[2]||Q)}DB.exports=process.platform==="win32"?qq0:Zq0;DB.exports.posix=Zq0;DB.exports.win32=qq0});var Ii=j((GX1)=>{GX1.setopts=QX1;GX1.ownProp=Vq0;GX1.makeAbs=jX;GX1.finish=JX1;GX1.mark=KX1;GX1.isIgnored=Fq0;GX1.childrenIgnored=zX1;function Vq0($,Y){return Object.prototype.hasOwnProperty.call($,Y)}var eW1=K0("fs"),AK=K0("path"),$X1=NB(),Lq0=BB(),Ui=$X1.Minimatch;function YX1($,Y){return $.localeCompare(Y,"en")}function UX1($,Y){if($.ignore=Y.ignore||[],!Array.isArray($.ignore))$.ignore=[$.ignore];if($.ignore.length)$.ignore=$.ignore.map(IX1)}function IX1($){var Y=null;if($.slice(-3)==="/**"){var U=$.replace(/(\/\*\*)+$/,"");Y=new Ui(U,{dot:!0})}return{ma Line truncated
See: https://github.com/isaacs/node-glob/issues/167`);return new C6($,Y).found}function C6($,Y){if(!$)throw Error("must provide pattern");if(typeof Y==="function"||arguments.length===3)throw TypeError(`callback provided to sync glob
See: https://github.com/isaacs/node-glob/issues/167`);if(!(this instanceof C6))return new C6($,Y);if(wX1(this,$,Y),this.noprocess)return this;var U=this.minimatch.set.length;this.matches=Array(U);for(var I=0;I<U;I++)this._process(this.minimatch.set[I],I,!1);this._finish()}C6.prototype._finish=function(){if(Mq0.ok(this instanceof C6),this.realpath){var $=this;this.matches.forEach(function(Y,U){var I=$.matches[U]=Object.create(null);for(var Q in Y)try{Q=$._makeAbs(Q);var J=FX1.realpathSync(Q,$.realpathCache);I[J]=!0}catch(K){if(K.syscall==="stat")I[$._makeAbs(Q)]=!0;else throw K}})}iU.finish(this)};C6.prototype._process=function($,Y,U){Mq0.ok(this instanceof C6);var I=0;while(typeof $[I]==="string")I++;var Q;switch(I){case $.length:this._processSimple($.join("/"),Y);return;case 0:Q=null;break;default:Q=$.slice(0,I).join("/");break}var J=$.slice(I),K;if(Q===null)K=".";else if(AB(Q)||AB($.map(function(H){return typeof H==="string"?H:"[*]"}).join("/"))){if(!Q||!AB(Q))Q="/"+Q;K=Q}else K=Q;var z=this._makeAbs(K);if(MX1(this,K))return;var G=J[0]===wq0.GLOBSTAR;if(G)this._processGlobStar(Q,K,z,J,Y,U);else this._processReaddir(Q,K,z,J,Y,U)};C6.prototype._processReaddir=function($,Y,U,I,Q,J){var K=this._readdir(U,J);if(!K)return;var z=I[0],G=!!this.minimatch.negate,H=z._glob,W=this.dot||H.charAt(0)===".",X=[];for(var Z=0;Z<K.length;Z++){var q=K[Z];if(q.charAt(0)!=="."||W){var V;if(G&&!$)V=!q.match(z);else V=q.match(z);if(V)X.push(q)}}var w=X.length;if(w===0)return;if(I.length===1&&!this.mark&&!this.stat){if(!this.matches[Q])this.matches[Q]=Object.create(null);for(var Z=0;Z<w;Z++){var q=X[Z];if($)if($.slice(-1)!=="/")q=$+"/"+q;else q=$+q;if(q.charAt(0)==="/"&&!this.nomount)q=Qi.join(this.root,q);this._emitMatch(Q,q)}return}I.shift();for(var Z=0;Z<w;Z++){var q=X[Z],M;if($)M=[$,q];else M=[q];this._process(M.concat(I),Q,J)}};C6.prototype._emitMatch=function($,Y){if(OX1(this,Y))return;var U=this._makeAbs(Y);if(this.mark)Y=this._mark(Y);if(this.absolute)Y=U;if(this.matches[$][Y])return;if(this.nodir){var I=this.cache[U];if(I==="DIR"||Array.isArray(I))return}if(this.matches[$][Y]=!0,this.stat)this._stat(Y)};C6.prototype._readdirInGlobStar=function($){if(this.follow)return this._readdir($,!1);var Y,U,I;try{U=this.fs.lstatSync($)}catch(J){if(J.code==="ENOENT")return null}var Q=U&&U.isSymbolicLink();if(this.symlinks[$]=Q,!Q&&U&&!U.isDirectory())this.cache[$]="FILE";else Y=this._readdir($,!1);return Y};C6.prototype._readdir=function($,Y){var U;if(Y&&!Ji(this.symlinks,$))return this._readdirInGlobStar($);if(Ji(this.cache,$)){var I=this.cache[$];if(!I||I==="FILE")return null;if(Array.isArray(I))return I}try{return this._readdirEntries($,this.fs.readdirSync($))}catch(Q){return this._readdirError($,Q),null}};C6.prototype._readdirEntries=function($,Y){if(!this.mark&&!this.stat)for(var U=0;U<Y.length;U++){var I=Y[U];if($==="/")I=$+I;else I=$+"/"+I;this.cache[I]=!0}return this.cache[$]=Y,Y};C6.prototype._readdirError=function($,Y){switch(Y.code){case"ENOTSUP":case"ENOTDIR":var U=this._makeAbs($);if(this.cache[U]="FILE",U===this.cwdAbs){var I=Error(Y.code+" invalid cwd "+this.cwd);throw I.path=this.cwd,I.code=Y.code,I}break;case"ENOENT":case"ELOOP":case"ENAMETOOLONG":case"UNKNOWN":this.cache[this._makeAbs($)]=!1;break;default:if(this.cache[this._makeAbs($)]=!1,this.strict)throw Y;if(!this.silent)console.error("glob error",Y);break}};C6.prototype._processGlobStar=function($,Y,U,I,Q,J){var K=this._readdir(U,J);if(!K)return;var z=I.slice(1),G=$?[$]:[],H=G.concat(z);this._process(H,Q,!1);var W=K.length,X=this.symlinks[U];if(X&&J)return;for(var Z=0;Z<W;Z++){var q=K[Z];if(q.charAt(0)==="."&&!this.dot)continue;var V=G.concat(K[Z],z);this._process(V,Q,!0);var w=G.concat(K[Z],I);this._process(w,Q,!0)}};C6.prototype._processSimple=function($,Y){var U=this._stat($);if(!this.matches[Y])this.matches[Y]=Object.create(null);if(!U)return;if($&&AB($)&&!this.nomount){var I=/[\/\\]$/.test($);if($.charAt(0)==="/")$=Qi.join(this.root,$);else if($=Qi.resolve(this.root,$),I)$+="/"}if(process.platform==="win32")$=$.replace(/\\/g,"/");this._emitMatch(Y,$)};C6.prototype._stat=function($){var Y=this._makeAbs($),U=$.slice(-1)==="/";if($.length>this.maxLength)return!1;if(!this.stat&&Ji(this.cache,Y)){var K=this.cache[Y];if(Array.isArray(K))K="DIR";if(!U||K==="DIR")return K;if(U&&K==="FILE")return!1}var I,Q=this.statCache[Y];if(!Q){var J;try{J=this.fs.lstatSync(Y)}catch(z){if(z&&(z.code==="ENOENT"||z.code==="ENOTDIR"))return this.statCache[Y]=!1,!1}if(J&&J.isSymbolicLink())try{Q=this.fs.statSync(Y)}catch(z){Q=J}else Q=J}this.statCache[Y]=Q;var K=!0;if(Q)K=Q.isDirectory()?"DIR":"FILE";if(this.cache[Y]=this.cache[Y]||K,U&&K==="FILE")return!1;return K};C6.prototype._mark=function($){return iU.mark(this,$)};C6.prototype._makeAbs=function($){return iU.makeAbs(this,$)}});var Ki=j((We1,Aq0)=>{Aq0.exports=Bq0;function Bq0($,Y){if($&&Y)return Bq0($)(Y);if(typeof $!=="function")throw TypeError("need wrapper function");return Object.keys($).forEach(function(I){U[I]=$[I]}),U;f Line truncated
`);if($.linkname)Y+=Qc(" linkpath="+$.linkname+`
`);var U=$.pax;if(U)for(var I in U)Y+=Qc(" "+I+"="+U[I]+`
`);return Buffer.from(Y)};RV1.decodePax=function($){var Y={};while($.length){var U=0;while(U<$.length&&$[U]!==32)U++;var I=parseInt($.slice(0,U).toString(),10);if(!I)return Y;var Q=$.slice(U+1,I-1).toString(),J=Q.indexOf("=");if(J===-1)return Y;Y[Q.slice(0,J)]=Q.slice(J+1),$=$.slice(I)}return Y};RV1.encode=function($){var Y=MV1(512),U=$.name,I="";if($.typeflag===5&&U[U.length-1]!=="/")U+="/";if(Buffer.byteLength(U)!==U.length)return null;while(Buffer.byteLength(U)>100){var Q=U.indexOf("/");if(Q===-1)return null;I+=I?"/"+U.slice(0,Q):U.slice(0,Q),U=U.slice(Q+1)}if(Buffer.byteLength(U)>100||Buffer.byteLength(I)>155)return null;if($.linkname&&Buffer.byteLength($.linkname)>100)return null;if(Y.write(U),Y.write(R2($.mode&PV1,6),100),Y.write(R2($.uid,6),108),Y.write(R2($.gid,6),116),Y.write(R2($.size,11),124),Y.write(R2($.mtime.getTime()/1000|0,11),136),Y[156]=xL0+jV1($.type),$.linkname)Y.write($.linkname,157);if(fL0.copy(Y,nX),DV1.copy(Y,Jc),$.uname)Y.write($.uname,265);if($.gname)Y.write($.gname,297);if(Y.write(R2($.devmajor||0,6),329),Y.write(R2($.devminor||0,6),337),I)Y.write(I,345);return Y.write(R2(bL0(Y),6),148),Y};RV1.decode=function($,Y,U){var I=$[156]===0?0:$[156]-xL0,Q=SK($,0,100,Y),J=_2($,100,8),K=_2($,108,8),z=_2($,116,8),G=_2($,124,12),H=_2($,136,12),W=EV1(I),X=$[157]===0?null:SK($,157,100,Y),Z=SK($,265,32),q=SK($,297,32),V=_2($,329,8),w=_2($,337,8),M=bL0($);if(M===256)return null;if(M!==_2($,148,8))throw Error("Invalid tar header. Maybe the tar is corrupted or it needs to be gunzipped?");if(fL0.compare($,nX,nX+6)===0){if($[345])Q=SK($,345,155,Y)+"/"+Q}else if(BV1.compare($,nX,nX+6)===0&&AV1.compare($,Jc,Jc+2)===0);else if(!U)throw Error("Invalid tar header: unknown format.");if(I===0&&Q&&Q[Q.length-1]==="/")I=5;return{name:Q,mode:J,uid:K,gid:z,size:G,mtime:new Date(1000*H),type:W,linkname:X,uname:Z,gname:q,devmajor:V,devminor:w}}});var lL0=j((Q04,mL0)=>{var cL0=K0("util"),yV1=kL0(),dX=Kc(),nL0=g8().Writable,dL0=g8().PassThrough,pL0=function(){},iL0=function($){return $&=511,$&&512-$},kV1=function($,Y){var U=new nB($,Y);return U.end(),U},xV1=function($,Y){if(Y.path)$.name=Y.path;if(Y.linkpath)$.linkname=Y.linkpath;if(Y.size)$.size=parseInt(Y.size,10);return $.pax=Y,$},nB=function($,Y){this._parent=$,this.offset=Y,dL0.call(this,{autoDestroy:!1})};cL0.inherits(nB,dL0);nB.prototype.destroy=function($){this._parent.destroy($)};var v3=function($){if(!(this instanceof v3))return new v3($);nL0.call(this,$),$=$||{},this._offset=0,this._buffer=yV1(),this._missing=0,this._partial=!1,this._onparse=pL0,this._header=null,this._stream=null,this._overflow=null,this._cb=null,this._locked=!1,this._destroyed=!1,this._pax=null,this._paxGlobal=null,this._gnuLongPath=null,this._gnuLongLinkPath=null;var Y=this,U=Y._buffer,I=function(){Y._continue()},Q=function(Z){if(Y._locked=!1,Z)return Y.destroy(Z);if(!Y._stream)I()},J=function(){Y._stream=null;var Z=iL0(Y._header.size);if(Z)Y._parse(Z,K);else Y._parse(512,X);if(!Y._locked)I()},K=function(){Y._buffer.consume(iL0(Y._header.size)),Y._parse(512,X),I()},z=function(){var Z=Y._header.size;Y._paxGlobal=dX.decodePax(U.slice(0,Z)),U.consume(Z),J()},G=function(){var Z=Y._header.size;if(Y._pax=dX.decodePax(U.slice(0,Z)),Y._paxGlobal)Y._pax=Object.assign({},Y._paxGlobal,Y._pax);U.consume(Z),J()},H=function(){var Z=Y._header.size;this._gnuLongPath=dX.decodeLongPath(U.slice(0,Z),$.filenameEncoding),U.consume(Z),J()},W=function(){var Z=Y._header.size;this._gnuLongLinkPath=dX.decodeLongPath(U.slice(0,Z),$.filenameEncoding),U.consume(Z),J()},X=function(){var Z=Y._offset,q;try{q=Y._header=dX.decode(U.slice(0,512),$.filenameEncoding,$.allowUnknownFormat)}catch(V){Y.emit("error",V)}if(U.consume(512),!q){Y._parse(512,X),I();return}if(q.type==="gnu-long-path"){Y._parse(q.size,H),I();return}if(q.type==="gnu-long-link-path"){Y._parse(q.size,W),I();return}if(q.type==="pax-global-header"){Y._parse(q.size,z),I();return}if(q.type==="pax-header"){Y._parse(q.size,G),I();return}if(Y._gnuLongPath)q.name=Y._gnuLongPath,Y._gnuLongPath=null;if(Y._gnuLongLinkPath)q.linkname=Y._gnuLongLinkPath,Y._gnuLongLinkPath=null;if(Y._pax)Y._header=q=xV1(q,Y._pax),Y._pax=null;if(Y._locked=!0,!q.size||q.type==="directory"){Y._parse(512,X),Y.emit("entry",q,kV1(Y,Z),Q);return}Y._stream=new nB(Y,Z),Y.emit("entry",q,Y._stream,Q),Y._parse(q.size,J),I()};this._onheader=X,this._parse(512,X)};cL0.inherits(v3,nL0);v3.prototype.destroy=function($){if(this._destroyed)return;if(this._destroyed=!0,$)this.emit("error",$);if(this.emit("close"),this._stream)this._stream.emit("close")};v3.prototype._parse=function($,Y){if(this._destroyed)return;if(this._offset+=$,this._missing=$,Y===this._onheader)this._partial=!1;this._onparse=Y};v3.prototype._continue=function(){if(this._destroyed)return;var $=this._cb;if(this._cb=pL0,this._overflow)this._write(this._overflow,void 0,$);else $()};v3.prototype._write=function($,Y,U){if(this._destroyed)return;var I=this._stream,Q=this._buffer,J=this._missing;if($.length)this._partial=!0;if($.length<J) Line truncated
<Relationships xmlns="http://schemas.openxmlformats.org/package/2006/relationships">`)}_writeRelationship($){if(!this.count)this._writeOpen();let Y=`rId${++this.count}`;if($.TargetMode)this.stream.write(`<Relationship Id="${Y}" Type="${$.Type}" Target="${UL1.xmlEncode($.Target)}" TargetMode="${$.TargetMode}"/>`);else this.stream.write(`<Relationship Id="${Y}" Type="${$.Type}" Target="${$.Target}"/>`);return Y}_writeClose(){this.stream.write("</Relationships>")}}OF0.exports=MF0});var TF0=j((V04,PF0)=>{var DF0=a6(),BF0=z2(),QL1=n4(),JL1=Of(),KL1=Df();class AF0{constructor($,Y,U){this.id=U.id,this.count=0,this._worksheet=$,this._workbook=U.workbook,this._sheetRelsWriter=Y}get commentsStream(){if(!this._commentsStream)this._commentsStream=this._workbook._openStream(`/xl/comments${this.id}.xml`);return this._commentsStream}get vmlStream(){if(!this._vmlStream)this._vmlStream=this._workbook._openStream(`xl/drawings/vmlDrawing${this.id}.vml`);return this._vmlStream}_addRelationships(){let $={Type:BF0.Comments,Target:`../comments${this.id}.xml`};this._sheetRelsWriter.addRelationship($);let Y={Type:BF0.VmlDrawing,Target:`../drawings/vmlDrawing${this.id}.vml`};this.vmlRelId=this._sheetRelsWriter.addRelationship(Y)}_addCommentRefs(){this._workbook.commentRefs.push({commentName:`comments${this.id}`,vmlDrawing:`vmlDrawing${this.id}`})}_writeOpen(){this.commentsStream.write('<?xml version="1.0" encoding="UTF-8" standalone="yes"?><comments xmlns="http://schemas.openxmlformats.org/spreadsheetml/2006/main"><authors><author>Author</author></authors><commentList>'),this.vmlStream.write('<?xml version="1.0" encoding="UTF-8"?><xml xmlns:o="urn:schemas-microsoft-com:office:office" xmlns:v="urn:schemas-microsoft-com:vml" xmlns:x="urn:schemas-microsoft-com:office:excel"><o:shapelayout v:ext="edit"><o:idmap v:ext="edit" data="1" /></o:shapelayout><v:shapetype id="_x0000_t202" coordsize="21600,21600" o:spt="202" path="m,l,21600r21600,l21600,xe"><v:stroke joinstyle="miter" /><v:path gradientshapeok="t" o:connecttype="rect" /></v:shapetype>')}_writeComment($,Y){let U=new JL1,I=new DF0;U.render(I,$),this.commentsStream.write(I.xml);let Q=new KL1,J=new DF0;Q.render(J,$,Y),this.vmlStream.write(J.xml)}_writeClose(){this.commentsStream.write("</commentList></comments>"),this.vmlStream.write("</xml>")}addComments($){if($&&$.length){if(!this.startedData)this._worksheet.comments=[],this._writeOpen(),this._addRelationships(),this._addCommentRefs(),this.startedData=!0;$.forEach((Y)=>{Y.refAddress=QL1.decodeAddress(Y.ref)}),$.forEach((Y)=>{this._writeComment(Y,this.count),this.count+=1})}}commit(){if(this.count)this._writeClose(),this.commentsStream.end(),this.vmlStream.end()}}PF0.exports=AF0});var vF0=j((L04,_F0)=>{var zL1=U6(),GL1=z2(),Hc=n4(),EF0=fg(),jF0=G3(),HL1=tk(),CF0=oM(),Wc=sM(),WL1=NF0(),XL1=TF0(),ZL1=kg(),b6=new HL1,Xc=Q2(),qL1=lx(),VL1=ox(),LL1=rx(),FL1=nx(),wL1=ix(),ML1=dx(),OL1=sx(),NL1=ax(),DL1=tx(),BL1=ex(),AL1=$f(),PL1=Yf(),TL1=Kf(),EL1=If(),jL1=Uf(),i6={dataValidations:new qL1,sheetProperties:new VL1,sheetFormatProperties:new LL1,columns:new Xc({tag:"cols",length:!1,childXform:new FL1}),row:new wL1,hyperlinks:new Xc({tag:"hyperlinks",length:!1,childXform:new ML1}),sheetViews:new Xc({tag:"sheetViews",length:!1,childXform:new OL1}),sheetProtection:new NL1,pageMargins:new DL1,pageSeteup:new BL1,autoFilter:new AL1,picture:new PL1,conditionalFormattings:new TL1,headerFooter:new EL1,rowBreaks:new jL1};class RF0{constructor($){this.id=$.id,this.name=$.name||`Sheet${this.id}`,this.state=$.state||"visible",this._rows=[],this._columns=null,this._keys={},this._merges=[],this._merges.add=function(){},this._sheetRelsWriter=new WL1($),this._sheetCommentsWriter=new XL1(this,this._sheetRelsWriter,$),this._dimensions=new jF0,this._rowZero=1,this.committed=!1,this.dataValidations=new ZL1,this._formulae={},this._siFormulae=0,this.conditionalFormatting=[],this.rowBreaks=[],this.properties=Object.assign({},{defaultRowHeight:15,dyDescent:55,outlineLevelCol:0,outlineLevelRow:0},$.properties),this.headerFooter=Object.assign({},{differentFirst:!1,differentOddEven:!1,oddHeader:null,oddFooter:null,evenHeader:null,evenFooter:null,firstHeader:null,firstFooter:null},$.headerFooter),this.pageSetup=Object.assign({},{margins:{left:0.7,right:0.7,top:0.75,bottom:0.75,header:0.3,footer:0.3},orientation:"portrait",horizontalDpi:4294967295,verticalDpi:4294967295,fitToPage:!!($.pageSetup&&($.pageSetup.fitToWidth||$.pageSetup.fitToHeight)&&!$.pageSetup.scale),pageOrder:"downThenOver",blackAndWhite:!1,draft:!1,cellComments:"None",errors:"displayed",scale:100,fitToWidth:1,fitToHeight:1,paperSize:void 0,showRowColHeaders:!1,showGridLines:!1,horizontalCentered:!1,verticalCentered:!1,rowBreaks:null,colBreaks:null},$.pageSetup),this.useSharedStrings=$.useSharedStrings||!1,this._workbook=$.workbook,this.hasComments=!1,this._views=$.views||[],this.autoFilter=$.autoFilter||null,this._media=[],this.sheetProtection=null,this._writeOpenWorksheet(),this.startedData=!1}get Line truncated
See http://goo.gl/MqrFmX
`)},Pc=Tc.getNativePromise();if(Tc.isNode&&typeof MutationObserver>"u")jc=global.setImmediate,Ec=process.nextTick,tU=Tc.isRecentNode?function($){jc.call(global,$)}:function($){Ec.call(process,$)};else if(typeof Pc==="function"&&typeof Pc.resolve==="function")Cc=Pc.resolve(),tU=function($){Cc.then($)};else if(typeof MutationObserver<"u"&&!(typeof window<"u"&&window.navigator&&(window.navigator.standalone||window.cordova)))tU=function(){var $=document.createElement("div"),Y={attributes:!0},U=!1,z=document.createElement("div"),I=new MutationObserver(function(){$.classList.toggle("foo"),U=!1});I.observe(z,Y);var Q=function(){if(U)return;U=!0,z.classList.toggle("foo")};return function(K){var G=new MutationObserver(function(){G.disconnect(),K()});G.observe($,Y),Q()}}();else if(typeof setImmediate<"u")tU=function($){setImmediate($)};else if(typeof setTimeout<"u")tU=function($){setTimeout($,0)};else tU=CL1;var jc,Ec,Cc;rF0.exports=tU});var tF0=E((Ge1,aF0)=>{function RL1($,Y,U,z,I){for(var Q=0;Q<I;++Q)U[Q+z]=$[Q+Y],$[Q+Y]=void 0}function v2($){this._capacity=$,this._length=0,this._front=0}v2.prototype._willBeOverCapacity=function($){return this._capacity<$};v2.prototype._pushOne=function($){var Y=this.length();this._checkCapacity(Y+1);var U=this._front+Y&this._capacity-1;this[U]=$,this._length=Y+1};v2.prototype.push=function($,Y,U){var z=this.length()+3;if(this._willBeOverCapacity(z)){this._pushOne($),this._pushOne(Y),this._pushOne(U);return}var I=this._front+z-3;this._checkCapacity(z);var Q=this._capacity-1;this[I+0&Q]=$,this[I+1&Q]=Y,this[I+2&Q]=U,this._length=z};v2.prototype.shift=function(){var $=this._front,Y=this[$];return this[$]=void 0,this._front=$+1&this._capacity-1,this._length--,Y};v2.prototype.length=function(){return this._length};v2.prototype._checkCapacity=function($){if(this._capacity<$)this._resizeTo(this._capacity<<1)};v2.prototype._resizeTo=function($){var Y=this._capacity;this._capacity=$;var U=this._front,z=this._length,I=U+z&Y-1;RL1(this,0,this,Y,I)};aF0.exports=v2});var Qw0=E((He1,Rc)=>{var zw0;try{throw Error()}catch($){zw0=$}var _L1=sF0(),eF0=tF0(),Iw0=w4();function u6(){this._customScheduler=!1,this._isTickUsed=!1,this._lateQueue=new eF0(16),this._normalQueue=new eF0(16),this._haveDrainedQueues=!1,this._trampolineEnabled=!0;var $=this;this.drainQueues=function(){$._drainQueues()},this._schedule=_L1}u6.prototype.setScheduler=function($){var Y=this._schedule;return this._schedule=$,this._customScheduler=!0,Y};u6.prototype.hasCustomScheduler=function(){return this._customScheduler};u6.prototype.enableTrampoline=function(){this._trampolineEnabled=!0};u6.prototype.disableTrampolineIfNecessary=function(){if(Iw0.hasDevTools)this._trampolineEnabled=!1};u6.prototype.haveItemsQueued=function(){return this._isTickUsed||this._haveDrainedQueues};u6.prototype.fatalError=function($,Y){if(Y)process.stderr.write("Fatal "+($ instanceof Error?$.stack:$)+`
`),process.exit(2);else this.throwLater($)};u6.prototype.throwLater=function($,Y){if(arguments.length===1)Y=$,$=function(){throw Y};if(typeof setTimeout<"u")setTimeout(function(){$(Y)},0);else try{this._schedule(function(){$(Y)})}catch(U){throw Error(`No async scheduler available
`)},Rc=_c.getNativePromise();if(_c.isNode&&typeof MutationObserver>"u")vc=global.setImmediate,Sc=process.nextTick,eU=_c.isRecentNode?function($){vc.call(global,$)}:function($){Sc.call(process,$)};else if(typeof Rc==="function"&&typeof Rc.resolve==="function")hc=Rc.resolve(),eU=function($){hc.then($)};else if(typeof MutationObserver<"u"&&!(typeof window<"u"&&window.navigator&&(window.navigator.standalone||window.cordova)))eU=function(){var $=document.createElement("div"),Y={attributes:!0},U=!1,I=document.createElement("div"),Q=new MutationObserver(function(){$.classList.toggle("foo"),U=!1});Q.observe(I,Y);var J=function(){if(U)return;U=!0,I.classList.toggle("foo")};return function(z){var G=new MutationObserver(function(){G.disconnect(),z()});G.observe($,Y),J()}}();else if(typeof setImmediate<"u")eU=function($){setImmediate($)};else if(typeof setTimeout<"u")eU=function($){setTimeout($,0)};else eU=MF1;var vc,Sc,hc;Ww0.exports=eU});var qw0=j((j04,Zw0)=>{function OF1($,Y,U,I,Q){for(var J=0;J<Q;++J)U[J+I]=$[J+Y],$[J+Y]=void 0}function h2($){this._capacity=$,this._length=0,this._front=0}h2.prototype._willBeOverCapacity=function($){return this._capacity<$};h2.prototype._pushOne=function($){var Y=this.length();this._checkCapacity(Y+1);var U=this._front+Y&this._capacity-1;this[U]=$,this._length=Y+1};h2.prototype.push=function($,Y,U){var I=this.length()+3;if(this._willBeOverCapacity(I)){this._pushOne($),this._pushOne(Y),this._pushOne(U);return}var Q=this._front+I-3;this._checkCapacity(I);var J=this._capacity-1;this[Q+0&J]=$,this[Q+1&J]=Y,this[Q+2&J]=U,this._length=I};h2.prototype.shift=function(){var $=this._front,Y=this[$];return this[$]=void 0,this._front=$+1&this._capacity-1,this._length--,Y};h2.prototype.length=function(){return this._length};h2.prototype._checkCapacity=function($){if(this._capacity<$)this._resizeTo(this._capacity<<1)};h2.prototype._resizeTo=function($){var Y=this._capacity;this._capacity=$;var U=this._front,I=this._length,Q=U+I&Y-1;OF1(this,0,this,Y,Q)};Zw0.exports=h2});var Nw0=j((C04,gc)=>{var Mw0;try{throw Error()}catch($){Mw0=$}var NF1=Xw0(),Vw0=qw0(),Ow0=M4();function c6(){this._customScheduler=!1,this._isTickUsed=!1,this._lateQueue=new Vw0(16),this._normalQueue=new Vw0(16),this._haveDrainedQueues=!1,this._trampolineEnabled=!0;var $=this;this.drainQueues=function(){$._drainQueues()},this._schedule=NF1}c6.prototype.setScheduler=function($){var Y=this._schedule;return this._schedule=$,this._customScheduler=!0,Y};c6.prototype.hasCustomScheduler=function(){return this._customScheduler};c6.prototype.enableTrampoline=function(){this._trampolineEnabled=!0};c6.prototype.disableTrampolineIfNecessary=function(){if(Ow0.hasDevTools)this._trampolineEnabled=!1};c6.prototype.haveItemsQueued=function(){return this._isTickUsed||this._haveDrainedQueues};c6.prototype.fatalError=function($,Y){if(Y)process.stderr.write("Fatal "+($ instanceof Error?$.stack:$)+`
`),process.exit(2);else this.throwLater($)};c6.prototype.throwLater=function($,Y){if(arguments.length===1)Y=$,$=function(){throw Y};if(typeof setTimeout<"u")setTimeout(function(){$(Y)},0);else try{this._schedule(function(){$(Y)})}catch(U){throw Error(`No async scheduler available
See http://goo.gl/MqrFmX
`)}};function $w0($,Y,U){this._lateQueue.push($,Y,U),this._queueTick()}function Yw0($,Y,U){this._normalQueue.push($,Y,U),this._queueTick()}function Uw0($){this._normalQueue._pushOne($),this._queueTick()}if(!Iw0.hasDevTools)u6.prototype.invokeLater=$w0,u6.prototype.invoke=Yw0,u6.prototype.settlePromises=Uw0;else u6.prototype.invokeLater=function($,Y,U){if(this._trampolineEnabled)$w0.call(this,$,Y,U);else this._schedule(function(){setTimeout(function(){$.call(Y,U)},100)})},u6.prototype.invoke=function($,Y,U){if(this._trampolineEnabled)Yw0.call(this,$,Y,U);else this._schedule(function(){$.call(Y,U)})},u6.prototype.settlePromises=function($){if(this._trampolineEnabled)Uw0.call(this,$);else this._schedule(function(){$._settlePromises()})};u6.prototype._drainQueue=function($){while($.length()>0){var Y=$.shift();if(typeof Y!=="function"){Y._settlePromises();continue}var U=$.shift(),z=$.shift();Y.call(U,z)}};u6.prototype._drainQueues=function(){this._drainQueue(this._normalQueue),this._reset(),this._haveDrainedQueues=!0,this._drainQueue(this._lateQueue)};u6.prototype._queueTick=function(){if(!this._isTickUsed)this._isTickUsed=!0,this._schedule(this.drainQueues)};u6.prototype._reset=function(){this._isTickUsed=!1};Rc.exports=u6;Rc.exports.firstLineError=zw0});var _3=E((We1,Gw0)=>{var hc=aU(),vL1=hc.freeze,Jw0=w4(),Kw0=Jw0.inherits,kJ=Jw0.notEnumerableProp;function xJ($,Y){function U(z){if(!(this instanceof U))return new U(z);if(kJ(this,"message",typeof z==="string"?z:Y),kJ(this,"name",$),Error.captureStackTrace)Error.captureStackTrace(this,this.constructor);else Error.call(this)}return Kw0(U,Error),U}var _c,vc,hL1=xJ("Warning","warning"),SL1=xJ("CancellationError","cancellation error"),gL1=xJ("TimeoutError","timeout error"),lX=xJ("AggregateError","aggregate error");try{_c=TypeError,vc=RangeError}catch($){_c=xJ("TypeError","type error"),vc=xJ("RangeError","range error")}var pA="join pop push shift unshift slice filter forEach some every map indexOf lastIndexOf reduce reduceRight sort reverse".split(" ");for(eU=0;eU<pA.length;++eU)if(typeof Array.prototype[pA[eU]]==="function")lX.prototype[pA[eU]]=Array.prototype[pA[eU]];var eU;hc.defineProperty(lX.prototype,"length",{value:0,configurable:!1,writable:!0,enumerable:!0});lX.prototype.isOperational=!0;var dA=0;lX.prototype.toString=function(){var $=Array(dA*4+1).join(" "),Y=`
`)}};function Lw0($,Y,U){this._lateQueue.push($,Y,U),this._queueTick()}function Fw0($,Y,U){this._normalQueue.push($,Y,U),this._queueTick()}function ww0($){this._normalQueue._pushOne($),this._queueTick()}if(!Ow0.hasDevTools)c6.prototype.invokeLater=Lw0,c6.prototype.invoke=Fw0,c6.prototype.settlePromises=ww0;else c6.prototype.invokeLater=function($,Y,U){if(this._trampolineEnabled)Lw0.call(this,$,Y,U);else this._schedule(function(){setTimeout(function(){$.call(Y,U)},100)})},c6.prototype.invoke=function($,Y,U){if(this._trampolineEnabled)Fw0.call(this,$,Y,U);else this._schedule(function(){$.call(Y,U)})},c6.prototype.settlePromises=function($){if(this._trampolineEnabled)ww0.call(this,$);else this._schedule(function(){$._settlePromises()})};c6.prototype._drainQueue=function($){while($.length()>0){var Y=$.shift();if(typeof Y!=="function"){Y._settlePromises();continue}var U=$.shift(),I=$.shift();Y.call(U,I)}};c6.prototype._drainQueues=function(){this._drainQueue(this._normalQueue),this._reset(),this._haveDrainedQueues=!0,this._drainQueue(this._lateQueue)};c6.prototype._queueTick=function(){if(!this._isTickUsed)this._isTickUsed=!0,this._schedule(this.drainQueues)};c6.prototype._reset=function(){this._isTickUsed=!1};gc.exports=c6;gc.exports.firstLineError=Mw0});var h3=j((R04,Aw0)=>{var xc=tU(),DF1=xc.freeze,Dw0=M4(),Bw0=Dw0.inherits,xK=Dw0.notEnumerableProp;function fK($,Y){function U(I){if(!(this instanceof U))return new U(I);if(xK(this,"message",typeof I==="string"?I:Y),xK(this,"name",$),Error.captureStackTrace)Error.captureStackTrace(this,this.constructor);else Error.call(this)}return Bw0(U,Error),U}var yc,kc,BF1=fK("Warning","warning"),AF1=fK("CancellationError","cancellation error"),PF1=fK("TimeoutError","timeout error"),sX=fK("AggregateError","aggregate error");try{yc=TypeError,kc=RangeError}catch($){yc=fK("TypeError","type error"),kc=fK("RangeError","range error")}var tB="join pop push shift unshift slice filter forEach some every map indexOf lastIndexOf reduce reduceRight sort reverse".split(" ");for($I=0;$I<tB.length;++$I)if(typeof Array.prototype[tB[$I]]==="function")sX.prototype[tB[$I]]=Array.prototype[tB[$I]];var $I;xc.defineProperty(sX.prototype,"length",{value:0,configurable:!1,writable:!0,enumerable:!0});sX.prototype.isOperational=!0;var eB=0;sX.prototype.toString=function(){var $=Array(eB*4+1).join(" "),Y=`
`+$+`AggregateError of:
`;dA++,$=Array(dA*4+1).join(" ");for(var U=0;U<this.length;++U){var z=this[U]===this?"[Circular AggregateError]":this[U]+"",I=z.split(`
`);for(var Q=0;Q<I.length;++Q)I[Q]=$+I[Q];z=I.join(`
`),Y+=z+`
`}return dA--,Y};function mX($){if(!(this instanceof mX))return new mX($);if(kJ(this,"name","OperationalError"),kJ(this,"message",$),this.cause=$,this.isOperational=!0,$ instanceof Error)kJ(this,"message",$.message),kJ(this,"stack",$.stack);else if(Error.captureStackTrace)Error.captureStackTrace(this,this.constructor)}Kw0(mX,Error);var $z=Error.__BluebirdErrorTypes__;if(!$z)$z=vL1({CancellationError:SL1,TimeoutError:gL1,OperationalError:mX,RejectionError:mX,AggregateError:lX}),hc.defineProperty(Error,"__BluebirdErrorTypes__",{value:$z,writable:!1,enumerable:!1,configurable:!1});Gw0.exports={Error,TypeError:_c,RangeError:vc,CancellationError:$z.CancellationError,OperationalError:$z.OperationalError,TimeoutError:$z.TimeoutError,AggregateError:$z.AggregateError,Warning:hL1}});var Ww0=E((Xe1,Hw0)=>{Hw0.exports=function($,Y){var U=w4(),z=U.errorObj,I=U.isObject;function Q(X,Z){if(I(X)){if(X instanceof $)return X;var q=K(X);if(q===z){if(Z)Z._pushContext();var V=$.reject(q.e);if(Z)Z._popContext();return V}else if(typeof q==="function"){if(H(X)){var V=new $(Y);return X._then(V._fulfill,V._reject,void 0,V,null),V}return W(X,q,Z)}}return X}function J(X){return X.then}function K(X){try{return J(X)}catch(Z){return z.e=Z,z}}var G={}.hasOwnProperty;function H(X){try{return G.call(X,"_promise0")}catch(Z){return!1}}function W(X,Z,q){var V=new $(Y),w=V;if(q)q._pushContext();if(V._captureStackTrace(),q)q._popContext();var M=!0,F=U.tryCatch(Z).call(X,N,O);if(M=!1,V&&F===z)V._rejectCallback(F.e,!0,!0),V=null;function N(D){if(!V)return;V._resolveCallback(D),V=null}function O(D){if(!V)return;V._rejectCallback(D,M,!0),V=null}return w}return Q}});var Zw0=E((Ze1,Xw0)=>{Xw0.exports=function($,Y,U,z,I){var Q=w4(),J=Q.isArray;function K(H){switch(H){case-2:return[];case-3:return{}}}function G(H){var W=this._promise=new $(Y);if(H instanceof $)W._propagateFrom(H,3);W._setOnCancel(this),this._values=H,this._length=0,this._totalResolved=0,this._init(void 0,-2)}return Q.inherits(G,I),G.prototype.length=function(){return this._length},G.prototype.promise=function(){return this._promise},G.prototype._init=function H(W,X){var Z=U(this._values,this._promise);if(Z instanceof $){Z=Z._target();var q=Z._bitField;if(this._values=Z,(q&50397184)===0)return this._promise._setAsyncGuaranteed(),Z._then(H,this._reject,void 0,this,X);else if((q&33554432)!==0)Z=Z._value();else if((q&16777216)!==0)return this._reject(Z._reason());else return this._cancel()}if(Z=Q.asArray(Z),Z===null){var V=z("expecting an array or an iterable object but got "+Q.classString(Z)).reason();this._promise._rejectCallback(V,!1);return}if(Z.length===0){if(X===-5)this._resolveEmptyArray();else this._resolve(K(X));return}this._iterate(Z)},G.prototype._iterate=function(H){var W=this.getActualLength(H.length);this._length=W,this._values=this.shouldCopyValues()?Array(W):this._values;var X=this._promise,Z=!1,q=null;for(var V=0;V<W;++V){var w=U(H[V],X);if(w instanceof $)w=w._target(),q=w._bitField;else q=null;if(Z){if(q!==null)w.suppressUnhandledRejections()}else if(q!==null)if((q&50397184)===0)w._proxy(this,V),this._values[V]=w;else if((q&33554432)!==0)Z=this._promiseFulfilled(w._value(),V);else if((q&16777216)!==0)Z=this._promiseRejected(w._reason(),V);else Z=this._promiseCancelled(V);else Z=this._promiseFulfilled(w,V)}if(!Z)X._setAsyncGuaranteed()},G.prototype._isResolved=function(){return this._values===null},G.prototype._resolve=function(H){this._values=null,this._promise._fulfill(H)},G.prototype._cancel=function(){if(this._isResolved()||!this._promise._isCancellable())return;this._values=null,this._promise._cancel()},G.prototype._reject=function(H){this._values=null,this._promise._rejectCallback(H,!1)},G.prototype._promiseFulfilled=function(H,W){this._values[W]=H;var X=++this._totalResolved;if(X>=this._length)return this._resolve(this._values),!0;return!1},G.prototype._promiseCancelled=function(){return this._cancel(),!0},G.prototype._promiseRejected=function(H){return this._totalResolved++,this._reject(H),!0},G.prototype._resultCancelled=function(){if(this._isResolved())return;var H=this._values;if(this._cancel(),H instanceof $)H.cancel();else for(var W=0;W<H.length;++W)if(H[W]instanceof $)H[W].cancel()},G.prototype.shouldCopyValues=function(){return!0},G.prototype.getActualLength=function(H){return H},G}});var Vw0=E((qe1,qw0)=>{qw0.exports=function($){var Y=!1,U=[];$.prototype._promiseCreated=function(){},$.prototype._pushContext=function(){},$.prototype._popContext=function(){return null},$._peekContext=$.prototype._peekContext=function(){};function z(){this._trace=new z.CapturedTrace(Q())}z.prototype._pushContext=function(){if(this._trace!==void 0)this._trace._promiseCreated=null,U.push(this._trace)},z.prototype._popContext=function(){if(this._trace!==void 0){var J=U.pop(),K=J._promiseCreated;return J._promiseCreated=null,K}return null};function I(){if(Y)return new z}function Q(){var J=U.length-1;if(J>=0)return U[J];return}return z.CapturedTrace=null,z.create=I,z.deactivateLong Line truncated
`;eB++,$=Array(eB*4+1).join(" ");for(var U=0;U<this.length;++U){var I=this[U]===this?"[Circular AggregateError]":this[U]+"",Q=I.split(`
`);for(var J=0;J<Q.length;++J)Q[J]=$+Q[J];I=Q.join(`
`),Y+=I+`
`}return eB--,Y};function rX($){if(!(this instanceof rX))return new rX($);if(xK(this,"name","OperationalError"),xK(this,"message",$),this.cause=$,this.isOperational=!0,$ instanceof Error)xK(this,"message",$.message),xK(this,"stack",$.stack);else if(Error.captureStackTrace)Error.captureStackTrace(this,this.constructor)}Bw0(rX,Error);var YI=Error.__BluebirdErrorTypes__;if(!YI)YI=DF1({CancellationError:AF1,TimeoutError:PF1,OperationalError:rX,RejectionError:rX,AggregateError:sX}),xc.defineProperty(Error,"__BluebirdErrorTypes__",{value:YI,writable:!1,enumerable:!1,configurable:!1});Aw0.exports={Error,TypeError:yc,RangeError:kc,CancellationError:YI.CancellationError,OperationalError:YI.OperationalError,TimeoutError:YI.TimeoutError,AggregateError:YI.AggregateError,Warning:BF1}});var Tw0=j((_04,Pw0)=>{Pw0.exports=function($,Y){var U=M4(),I=U.errorObj,Q=U.isObject;function J(X,Z){if(Q(X)){if(X instanceof $)return X;var q=z(X);if(q===I){if(Z)Z._pushContext();var V=$.reject(q.e);if(Z)Z._popContext();return V}else if(typeof q==="function"){if(H(X)){var V=new $(Y);return X._then(V._fulfill,V._reject,void 0,V,null),V}return W(X,q,Z)}}return X}function K(X){return X.then}function z(X){try{return K(X)}catch(Z){return I.e=Z,I}}var G={}.hasOwnProperty;function H(X){try{return G.call(X,"_promise0")}catch(Z){return!1}}function W(X,Z,q){var V=new $(Y),w=V;if(q)q._pushContext();if(V._captureStackTrace(),q)q._popContext();var M=!0,F=U.tryCatch(Z).call(X,N,O);if(M=!1,V&&F===I)V._rejectCallback(F.e,!0,!0),V=null;function N(D){if(!V)return;V._resolveCallback(D),V=null}function O(D){if(!V)return;V._rejectCallback(D,M,!0),V=null}return w}return J}});var jw0=j((v04,Ew0)=>{Ew0.exports=function($,Y,U,I,Q){var J=M4(),K=J.isArray;function z(H){switch(H){case-2:return[];case-3:return{}}}function G(H){var W=this._promise=new $(Y);if(H instanceof $)W._propagateFrom(H,3);W._setOnCancel(this),this._values=H,this._length=0,this._totalResolved=0,this._init(void 0,-2)}return J.inherits(G,Q),G.prototype.length=function(){return this._length},G.prototype.promise=function(){return this._promise},G.prototype._init=function H(W,X){var Z=U(this._values,this._promise);if(Z instanceof $){Z=Z._target();var q=Z._bitField;if(this._values=Z,(q&50397184)===0)return this._promise._setAsyncGuaranteed(),Z._then(H,this._reject,void 0,this,X);else if((q&33554432)!==0)Z=Z._value();else if((q&16777216)!==0)return this._reject(Z._reason());else return this._cancel()}if(Z=J.asArray(Z),Z===null){var V=I("expecting an array or an iterable object but got "+J.classString(Z)).reason();this._promise._rejectCallback(V,!1);return}if(Z.length===0){if(X===-5)this._resolveEmptyArray();else this._resolve(z(X));return}this._iterate(Z)},G.prototype._iterate=function(H){var W=this.getActualLength(H.length);this._length=W,this._values=this.shouldCopyValues()?Array(W):this._values;var X=this._promise,Z=!1,q=null;for(var V=0;V<W;++V){var w=U(H[V],X);if(w instanceof $)w=w._target(),q=w._bitField;else q=null;if(Z){if(q!==null)w.suppressUnhandledRejections()}else if(q!==null)if((q&50397184)===0)w._proxy(this,V),this._values[V]=w;else if((q&33554432)!==0)Z=this._promiseFulfilled(w._value(),V);else if((q&16777216)!==0)Z=this._promiseRejected(w._reason(),V);else Z=this._promiseCancelled(V);else Z=this._promiseFulfilled(w,V)}if(!Z)X._setAsyncGuaranteed()},G.prototype._isResolved=function(){return this._values===null},G.prototype._resolve=function(H){this._values=null,this._promise._fulfill(H)},G.prototype._cancel=function(){if(this._isResolved()||!this._promise._isCancellable())return;this._values=null,this._promise._cancel()},G.prototype._reject=function(H){this._values=null,this._promise._rejectCallback(H,!1)},G.prototype._promiseFulfilled=function(H,W){this._values[W]=H;var X=++this._totalResolved;if(X>=this._length)return this._resolve(this._values),!0;return!1},G.prototype._promiseCancelled=function(){return this._cancel(),!0},G.prototype._promiseRejected=function(H){return this._totalResolved++,this._reject(H),!0},G.prototype._resultCancelled=function(){if(this._isResolved())return;var H=this._values;if(this._cancel(),H instanceof $)H.cancel();else for(var W=0;W<H.length;++W)if(H[W]instanceof $)H[W].cancel()},G.prototype.shouldCopyValues=function(){return!0},G.prototype.getActualLength=function(H){return H},G}});var Rw0=j((S04,Cw0)=>{Cw0.exports=function($){var Y=!1,U=[];$.prototype._promiseCreated=function(){},$.prototype._pushContext=function(){},$.prototype._popContext=function(){return null},$._peekContext=$.prototype._peekContext=function(){};function I(){this._trace=new I.CapturedTrace(J())}I.prototype._pushContext=function(){if(this._trace!==void 0)this._trace._promiseCreated=null,U.push(this._trace)},I.prototype._popContext=function(){if(this._trace!==void 0){var K=U.pop(),z=K._promiseCreated;return K._promiseCreated=null,z}return null};function Q(){if(Y)return new I}function J(){var K=U.length-1;if(K>=0)return U[K];return}return I.CapturedTrace=null,I.create=Q,I.deactivateLong Line truncated
See http://goo.gl/MqrFmX
`);if(!D0.longStackTraces&&u0()){var I0=$.prototype._captureStackTrace,B=$.prototype._attachExtraTrace;D0.longStackTraces=!0,D=function(){if(z.haveItemsQueued()&&!D0.longStackTraces)throw Error(`cannot enable long stack traces after promises have been created
`);if(!D0.longStackTraces&&u0()){var Q0=$.prototype._captureStackTrace,A=$.prototype._attachExtraTrace;D0.longStackTraces=!0,D=function(){if(I.haveItemsQueued()&&!D0.longStackTraces)throw Error(`cannot enable long stack traces after promises have been created
See http://goo.gl/MqrFmX
`);$.prototype._captureStackTrace=I0,$.prototype._attachExtraTrace=B,Y.deactivateLongStackTraces(),z.enableTrampoline(),D0.longStackTraces=!1},$.prototype._captureStackTrace=y,$.prototype._attachExtraTrace=p,Y.activateLongStackTraces(),z.disableTrampolineIfNecessary()}},$.hasLongStackTraces=function(){return D0.longStackTraces&&u0()};var P=function(){try{if(typeof CustomEvent==="function"){var I0=new CustomEvent("CustomEvent");return Q.global.dispatchEvent(I0),function(B,h){var u=new CustomEvent(B.toLowerCase(),{detail:h,cancelable:!0});return!Q.global.dispatchEvent(u)}}else if(typeof Event==="function"){var I0=new Event("CustomEvent");return Q.global.dispatchEvent(I0),function(h,u){var s=new Event(h.toLowerCase(),{cancelable:!0});return s.detail=u,!Q.global.dispatchEvent(s)}}else{var I0=document.createEvent("CustomEvent");return I0.initCustomEvent("testingtheevent",!1,!0,{}),Q.global.dispatchEvent(I0),function(h,u){var s=document.createEvent("CustomEvent");return s.initCustomEvent(h.toLowerCase(),!1,!0,u),!Q.global.dispatchEvent(s)}}}catch(B){}return function(){return!1}}(),T=function(){if(Q.isNode)return function(){return process.emit.apply(process,arguments)};else{if(!Q.global)return function(){return!1};return function(I0){var B="on"+I0.toLowerCase(),h=Q.global[B];if(!h)return!1;return h.apply(Q.global,[].slice.call(arguments,1)),!0}}}();function A(I0,B){return{promise:B}}var j={promiseCreated:A,promiseFulfilled:A,promiseRejected:A,promiseResolved:A,promiseCancelled:A,promiseChained:function(I0,B,h){return{promise:B,child:h}},warning:function(I0,B){return{warning:B}},unhandledRejection:function(I0,B,h){return{reason:B,promise:h}},rejectionHandled:A},C=function(I0){var B=!1;try{B=T.apply(null,arguments)}catch(u){z.throwLater(u),B=!0}var h=!1;try{h=P(I0,j[I0].apply(null,arguments))}catch(u){z.throwLater(u),h=!0}return h||B};$.config=function(I0){if(I0=Object(I0),"longStackTraces"in I0){if(I0.longStackTraces)$.longStackTraces();else if(!I0.longStackTraces&&$.hasLongStackTraces())D()}if("warnings"in I0){var B=I0.warnings;if(D0.warnings=!!B,O=D0.warnings,Q.isObject(B)){if("wForgottenReturn"in B)O=!!B.wForgottenReturn}}if("cancellation"in I0&&I0.cancellation&&!D0.cancellation){if(z.haveItemsQueued())throw Error("cannot enable cancellation after promises are in use");$.prototype._clearCancellationData=z0,$.prototype._propagateFrom=k,$.prototype._onCancel=i,$.prototype._setOnCancel=c,$.prototype._attachCancellationCallback=g,$.prototype._execute=x,a=k,D0.cancellation=!0}if("monitoring"in I0){if(I0.monitoring&&!D0.monitoring)D0.monitoring=!0,$.prototype._fireEvent=C;else if(!I0.monitoring&&D0.monitoring)D0.monitoring=!1,$.prototype._fireEvent=b}return $};function b(){return!1}$.prototype._fireEvent=b,$.prototype._execute=function(I0,B,h){try{I0(B,h)}catch(u){return u}},$.prototype._onCancel=function(){},$.prototype._setOnCancel=function(I0){},$.prototype._attachCancellationCallback=function(I0){},$.prototype._captureStackTrace=function(){},$.prototype._attachExtraTrace=function(){},$.prototype._clearCancellationData=function(){},$.prototype._propagateFrom=function(I0,B){};function x(I0,B,h){var u=this;try{I0(B,h,function(s){if(typeof s!=="function")throw TypeError("onCancel must be a function, got: "+Q.toString(s));u._attachCancellationCallback(s)})}catch(s){return s}}function g(I0){if(!this._isCancellable())return this;var B=this._onCancel();if(B!==void 0)if(Q.isArray(B))B.push(I0);else this._setOnCancel([B,I0]);else this._setOnCancel(I0)}function i(){return this._onCancelField}function c(I0){this._onCancelField=I0}function z0(){this._cancellationParent=void 0,this._onCancelField=void 0}function k(I0,B){if((B&1)!==0){this._cancellationParent=I0;var h=I0._branchesRemainingToCancel;if(h===void 0)h=0;I0._branchesRemainingToCancel=h+1}if((B&2)!==0&&I0._isBound())this._setBoundTo(I0._boundTo)}function d(I0,B){if((B&2)!==0&&I0._isBound())this._setBoundTo(I0._boundTo)}var a=d;function $0(){var I0=this._boundTo;if(I0!==void 0){if(I0 instanceof $)if(I0.isFulfilled())return I0.value();else return}return I0}function y(){this._trace=new u1(this._peekContext())}function p(I0,B){if(J(I0)){var h=this._trace;if(h!==void 0){if(B)h=h._parent}if(h!==void 0)h.attachExtraTrace(I0);else if(!I0.__stackCleaned__){var u=o0(I0);Q.notEnumerableProp(I0,"stack",u.message+`
`);$.prototype._captureStackTrace=Q0,$.prototype._attachExtraTrace=A,Y.deactivateLongStackTraces(),I.enableTrampoline(),D0.longStackTraces=!1},$.prototype._captureStackTrace=y,$.prototype._attachExtraTrace=d,Y.activateLongStackTraces(),I.disableTrampolineIfNecessary()}},$.hasLongStackTraces=function(){return D0.longStackTraces&&u0()};var P=function(){try{if(typeof CustomEvent==="function"){var Q0=new CustomEvent("CustomEvent");return J.global.dispatchEvent(Q0),function(A,S){var u=new CustomEvent(A.toLowerCase(),{detail:S,cancelable:!0});return!J.global.dispatchEvent(u)}}else if(typeof Event==="function"){var Q0=new Event("CustomEvent");return J.global.dispatchEvent(Q0),function(S,u){var s=new Event(S.toLowerCase(),{cancelable:!0});return s.detail=u,!J.global.dispatchEvent(s)}}else{var Q0=document.createEvent("CustomEvent");return Q0.initCustomEvent("testingtheevent",!1,!0,{}),J.global.dispatchEvent(Q0),function(S,u){var s=document.createEvent("CustomEvent");return s.initCustomEvent(S.toLowerCase(),!1,!0,u),!J.global.dispatchEvent(s)}}}catch(A){}return function(){return!1}}(),T=function(){if(J.isNode)return function(){return process.emit.apply(process,arguments)};else{if(!J.global)return function(){return!1};return function(Q0){var A="on"+Q0.toLowerCase(),S=J.global[A];if(!S)return!1;return S.apply(J.global,[].slice.call(arguments,1)),!0}}}();function B(Q0,A){return{promise:A}}var E={promiseCreated:B,promiseFulfilled:B,promiseRejected:B,promiseResolved:B,promiseCancelled:B,promiseChained:function(Q0,A,S){return{promise:A,child:S}},warning:function(Q0,A){return{warning:A}},unhandledRejection:function(Q0,A,S){return{reason:A,promise:S}},rejectionHandled:B},C=function(Q0){var A=!1;try{A=T.apply(null,arguments)}catch(u){I.throwLater(u),A=!0}var S=!1;try{S=P(Q0,E[Q0].apply(null,arguments))}catch(u){I.throwLater(u),S=!0}return S||A};$.config=function(Q0){if(Q0=Object(Q0),"longStackTraces"in Q0){if(Q0.longStackTraces)$.longStackTraces();else if(!Q0.longStackTraces&&$.hasLongStackTraces())D()}if("warnings"in Q0){var A=Q0.warnings;if(D0.warnings=!!A,O=D0.warnings,J.isObject(A)){if("wForgottenReturn"in A)O=!!A.wForgottenReturn}}if("cancellation"in Q0&&Q0.cancellation&&!D0.cancellation){if(I.haveItemsQueued())throw Error("cannot enable cancellation after promises are in use");$.prototype._clearCancellationData=I0,$.prototype._propagateFrom=k,$.prototype._onCancel=i,$.prototype._setOnCancel=c,$.prototype._attachCancellationCallback=g,$.prototype._execute=x,a=k,D0.cancellation=!0}if("monitoring"in Q0){if(Q0.monitoring&&!D0.monitoring)D0.monitoring=!0,$.prototype._fireEvent=C;else if(!Q0.monitoring&&D0.monitoring)D0.monitoring=!1,$.prototype._fireEvent=b}return $};function b(){return!1}$.prototype._fireEvent=b,$.prototype._execute=function(Q0,A,S){try{Q0(A,S)}catch(u){return u}},$.prototype._onCancel=function(){},$.prototype._setOnCancel=function(Q0){},$.prototype._attachCancellationCallback=function(Q0){},$.prototype._captureStackTrace=function(){},$.prototype._attachExtraTrace=function(){},$.prototype._clearCancellationData=function(){},$.prototype._propagateFrom=function(Q0,A){};function x(Q0,A,S){var u=this;try{Q0(A,S,function(s){if(typeof s!=="function")throw TypeError("onCancel must be a function, got: "+J.toString(s));u._attachCancellationCallback(s)})}catch(s){return s}}function g(Q0){if(!this._isCancellable())return this;var A=this._onCancel();if(A!==void 0)if(J.isArray(A))A.push(Q0);else this._setOnCancel([A,Q0]);else this._setOnCancel(Q0)}function i(){return this._onCancelField}function c(Q0){this._onCancelField=Q0}function I0(){this._cancellationParent=void 0,this._onCancelField=void 0}function k(Q0,A){if((A&1)!==0){this._cancellationParent=Q0;var S=Q0._branchesRemainingToCancel;if(S===void 0)S=0;Q0._branchesRemainingToCancel=S+1}if((A&2)!==0&&Q0._isBound())this._setBoundTo(Q0._boundTo)}function p(Q0,A){if((A&2)!==0&&Q0._isBound())this._setBoundTo(Q0._boundTo)}var a=p;function $0(){var Q0=this._boundTo;if(Q0!==void 0){if(Q0 instanceof $)if(Q0.isFulfilled())return Q0.value();else return}return Q0}function y(){this._trace=new u1(this._peekContext())}function d(Q0,A){if(K(Q0)){var S=this._trace;if(S!==void 0){if(A)S=S._parent}if(S!==void 0)S.attachExtraTrace(Q0);else if(!Q0.__stackCleaned__){var u=o0(Q0);J.notEnumerableProp(Q0,"stack",u.message+`
`+u.stack.join(`
`)),Q.notEnumerableProp(I0,"__stackCleaned__",!0)}}}function Y0(I0,B,h,u,s){if(I0===void 0&&B!==null&&O){if(s!==void 0&&s._returnedNonUndefined())return;if((u._bitField&65535)===0)return;if(h)h=h+" ";var W0="",Q0="";if(B._trace){var Z0=B._trace.stack.split(`
`),w0=y0(Z0);for(var A0=w0.length-1;A0>=0;--A0){var r0=w0[A0];if(!W.test(r0)){var Q1=r0.match(X);if(Q1)W0="at "+Q1[1]+":"+Q1[2]+":"+Q1[3]+" ";break}}if(w0.length>0){var U1=w0[0];for(var A0=0;A0<Z0.length;++A0)if(Z0[A0]===U1){if(A0>0)Q0=`
`+Z0[A0-1];break}}}var A1="a promise was created in a "+h+"handler "+W0+"but was not returned from it, see http://goo.gl/rRqMUw"+Q0;u._warn(A1,!0,B)}}function R(I0,B){var h=I0+" is deprecated and will be removed in a future version.";if(B)h+=" Use "+B+" instead.";return o(h)}function o(I0,B,h){if(!D0.warnings)return;var u=new I(I0),s;if(B)h._attachExtraTrace(u);else if(D0.longStackTraces&&(s=$._peekContext()))s.attachExtraTrace(u);else{var W0=o0(u);u.stack=W0.message+`
`)),J.notEnumerableProp(Q0,"__stackCleaned__",!0)}}}function Y0(Q0,A,S,u,s){if(Q0===void 0&&A!==null&&O){if(s!==void 0&&s._returnedNonUndefined())return;if((u._bitField&65535)===0)return;if(S)S=S+" ";var W0="",J0="";if(A._trace){var Z0=A._trace.stack.split(`
`),w0=y0(Z0);for(var B0=w0.length-1;B0>=0;--B0){var r0=w0[B0];if(!W.test(r0)){var J1=r0.match(X);if(J1)W0="at "+J1[1]+":"+J1[2]+":"+J1[3]+" ";break}}if(w0.length>0){var U1=w0[0];for(var B0=0;B0<Z0.length;++B0)if(Z0[B0]===U1){if(B0>0)J0=`
`+Z0[B0-1];break}}}var B1="a promise was created in a "+S+"handler "+W0+"but was not returned from it, see http://goo.gl/rRqMUw"+J0;u._warn(B1,!0,A)}}function R(Q0,A){var S=Q0+" is deprecated and will be removed in a future version.";if(A)S+=" Use "+A+" instead.";return o(S)}function o(Q0,A,S){if(!D0.warnings)return;var u=new Q(Q0),s;if(A)S._attachExtraTrace(u);else if(D0.longStackTraces&&(s=$._peekContext()))s.attachExtraTrace(u);else{var W0=o0(u);u.stack=W0.message+`
`+W0.stack.join(`
`)}if(!C("warning",u))q1(u,"",!0)}function e(I0,B){for(var h=0;h<B.length-1;++h)B[h].push("From previous event:"),B[h]=B[h].join(`
`);if(h<B.length)B[h]=B[h].join(`
`);return I0+`
`+B.join(`
`)}function O0(I0){for(var B=0;B<I0.length;++B)if(I0[B].length===0||B+1<I0.length&&I0[B][0]===I0[B+1][0])I0.splice(B,1),B--}function T0(I0){var B=I0[0];for(var h=1;h<I0.length;++h){var u=I0[h],s=B.length-1,W0=B[s],Q0=-1;for(var Z0=u.length-1;Z0>=0;--Z0)if(u[Z0]===W0){Q0=Z0;break}for(var Z0=Q0;Z0>=0;--Z0){var w0=u[Z0];if(B[s]===w0)B.pop(),s--;else break}B=u}}function y0(I0){var B=[];for(var h=0;h<I0.length;++h){var u=I0[h],s=u===" (No stack trace)"||Z.test(u),W0=s&&b0(u);if(s&&!W0){if(V&&u.charAt(0)!==" ")u=" "+u;B.push(u)}}return B}function v0(I0){var B=I0.stack.replace(/\s+$/g,"").split(`
`);for(var h=0;h<B.length;++h){var u=B[h];if(u===" (No stack trace)"||Z.test(u))break}if(h>0&&I0.name!="SyntaxError")B=B.slice(h);return B}function o0(I0){var B=I0.stack,h=I0.toString();return B=typeof B==="string"&&B.length>0?v0(I0):[" (No stack trace)"],{message:h,stack:I0.name=="SyntaxError"?B:y0(B)}}function q1(I0,B,h){if(typeof console<"u"){var u;if(Q.isObject(I0)){var s=I0.stack;u=B+q(s,I0)}else u=B+String(I0);if(typeof w==="function")w(u,h);else if(typeof console.log==="function"||typeof console.log==="object")console.log(u)}}function t(I0,B,h,u){var s=!1;try{if(typeof B==="function")if(s=!0,I0==="rejectionHandled")B(u);else B(h,u)}catch(W0){z.throwLater(W0)}if(I0==="unhandledRejection"){if(!C(I0,h,u)&&!s)q1(h,"Unhandled rejection ")}else C(I0,u)}function X0(I0){var B;if(typeof I0==="function")B="[function "+(I0.name||"anonymous")+"]";else{B=I0&&typeof I0.toString==="function"?I0.toString():Q.toString(I0);var h=/\[object [a-zA-Z0-9$_]+\]/;if(h.test(B))try{var u=JSON.stringify(I0);B=u}catch(s){}if(B.length===0)B="(empty array)"}return"(<"+F0(B)+">, no stack trace)"}function F0(I0){var B=41;if(I0.length<B)return I0;return I0.substr(0,B-3)+"..."}function u0(){return typeof b1==="function"}var b0=function(){return!1},c0=/[\/<\(]([^:\/]+):(\d+):(?:\d+)\)?\s*$/;function P1(I0){var B=I0.match(c0);if(B)return{fileName:B[1],line:parseInt(B[2],10)}}function k1(I0,B){if(!u0())return;var h=I0.stack.split(`
`),u=B.stack.split(`
`),s=-1,W0=-1,Q0,Z0;for(var w0=0;w0<h.length;++w0){var A0=P1(h[w0]);if(A0){Q0=A0.fileName,s=A0.line;break}}for(var w0=0;w0<u.length;++w0){var A0=P1(u[w0]);if(A0){Z0=A0.fileName,W0=A0.line;break}}if(s<0||W0<0||!Q0||!Z0||Q0!==Z0||s>=W0)return;b0=function(r0){if(H.test(r0))return!0;var Q1=P1(r0);if(Q1){if(Q1.fileName===Q0&&(s<=Q1.line&&Q1.line<=W0))return!0}return!1}}function u1(I0){this._parent=I0,this._promisesCreated=0;var B=this._length=1+(I0===void 0?0:I0._length);if(b1(this,u1),B>32)this.uncycle()}Q.inherits(u1,Error),Y.CapturedTrace=u1,u1.prototype.uncycle=function(){var I0=this._length;if(I0<2)return;var B=[],h={};for(var u=0,s=this;s!==void 0;++u)B.push(s),s=s._parent;I0=this._length=u;for(var u=I0-1;u>=0;--u){var W0=B[u].stack;if(h[W0]===void 0)h[W0]=u}for(var u=0;u<I0;++u){var Q0=B[u].stack,Z0=h[Q0];if(Z0!==void 0&&Z0!==u){if(Z0>0)B[Z0-1]._parent=void 0,B[Z0-1]._length=1;B[u]._parent=void 0,B[u]._length=1;var w0=u>0?B[u-1]:this;if(Z0<I0-1)w0._parent=B[Z0+1],w0._parent.uncycle(),w0._length=w0._parent._length+1;else w0._parent=void 0,w0._length=1;var A0=w0._length+1;for(var r0=u-2;r0>=0;--r0)B[r0]._length=A0,A0++;return}}},u1.prototype.attachExtraTrace=function(I0){if(I0.__stackCleaned__)return;this.uncycle();var B=o0(I0),h=B.message,u=[B.stack],s=this;while(s!==void 0)u.push(y0(s.stack.split(`
`))),s=s._parent;T0(u),O0(u),Q.notEnumerableProp(I0,"stack",e(h,u)),Q.notEnumerableProp(I0,"__stackCleaned__",!0)};var b1=function(){var B=/^\s*at\s*/,h=function(Q0,Z0){if(typeof Q0==="string")return Q0;if(Z0.name!==void 0&&Z0.message!==void 0)return Z0.toString();return X0(Z0)};if(typeof Error.stackTraceLimit==="number"&&typeof Error.captureStackTrace==="function"){Error.stackTraceLimit+=6,Z=B,q=h;var u=Error.captureStackTrace;return b0=function(Q0){return H.test(Q0)},function(Q0,Z0){Error.stackTraceLimit+=6,u(Q0,Z0),Error.stackTraceLimit-=6}}var s=Error();if(typeof s.stack==="string"&&s.stack.split(`
`)[0].indexOf("stackDetection@")>=0)return Z=/@/,q=h,V=!0,function(Z0){Z0.stack=Error().stack};var W0;try{throw Error()}catch(Q0){W0="stack"in Q0}if(!("stack"in s)&&W0&&typeof Error.stackTraceLimit==="number")return Z=B,q=h,function(Z0){Error.stackTraceLimit+=6;try{throw Error()}catch(w0){Z0.stack=w0.stack}Error.stackTraceLimit-=6};return q=function(Q0,Z0){if(typeof Q0==="string")return Q0;if((typeof Z0==="object"||typeof Z0==="function")&&Z0.name!==void 0&&Z0.message!==void 0)return Z0.toString();return X0(Z0)},null}([]);if(typeof console<"u"&&typeof console.warn<"u"){if(w=function(I0){console.warn(I0)},Q.isNode&&process.stderr.isTTY)w=function(I0,B){var h=B?"\x1B[33m":"\x1B[31m";console.warn(h+I0+`\x1B[0m
`)};else if(!Q.isNode&&typeof Error().stack==="string")w=function(I0,B){console.warn("%c"+I0,B?"color: darkorange":"color: red")}}var D0={warnings:F,longStackTraces:!1,cancellation:!1,monitoring:!1};if(N)$.longStackTraces();return{longStackTraces:function(){return D0.longStackTraces},warnings:function(){return D0.warnings},cancellation:function(){return D0.cancellation},monitoring:function(){return D0.monitoring},propagateFromFunction:function(){return a},boundValueFunction:function(){return $0},checkForgottenReturns:Y0,setBounds:k1,warn:o,deprecated:R,CapturedTrace:u1,fireDomEvent:P,fireGlobalEvent:T}}});var Mw0=E((Le1,ww0)=>{ww0.exports=function($,Y){var U=w4(),z=$.CancellationError,I=U.errorObj;function Q(X,Z,q){this.promise=X,this.type=Z,this.handler=q,this.called=!1,this.cancelPromise=null}Q.prototype.isFinallyHandler=function(){return this.type===0};function J(X){this.finallyHandler=X}J.prototype._resultCancelled=function(){K(this.finallyHandler)};function K(X,Z){if(X.cancelPromise!=null){if(arguments.length>1)X.cancelPromise._reject(Z);else X.cancelPromise._cancel();return X.cancelPromise=null,!0}return!1}function G(){return W.call(this,this.promise._target()._settledValue())}function H(X){if(K(this,X))return;return I.e=X,I}function W(X){var Z=this.promise,q=this.handler;if(!this.called){this.called=!0;var V=this.isFinallyHandler()?q.call(Z._boundValue()):q.call(Z._boundValue(),X);if(V!==void 0){Z._setReturnedNonUndefined();var w=Y(V,Z);if(w instanceof $){if(this.cancelPromise!=null){if(w._isCancelled()){var M=new z("late cancellation observer");return Z._attachExtraTrace(M),I.e=M,I}else if(w.isPending())w._attachCancellationCallback(new J(this))}return w._then(G,H,void 0,this,void 0)}}}if(Z.isRejected())return K(this),I.e=X,I;else return K(this),X}return $.prototype._passThrough=function(X,Z,q,V){if(typeof X!=="function")return this.then();return this._then(q,V,void 0,new Q(this,Z,X),void 0)},$.prototype.lastly=$.prototype.finally=function(X){return this._passThrough(X,0,W,W)},$.prototype.tap=function(X){return this._passThrough(X,1,W)},Q}});var Nw0=E((Fe1,Ow0)=>{Ow0.exports=function($){var Y=w4(),U=aU().keys,z=Y.tryCatch,I=Y.errorObj;function Q(J,K,G){return function(H){var W=G._boundValue();$:for(var X=0;X<J.length;++X){var Z=J[X];if(Z===Error||Z!=null&&Z.prototype instanceof Error){if(H instanceof Z)return z(K).call(W,H)}else if(typeof Z==="function"){var q=z(Z).call(W,H);if(q===I)return q;else if(q)return z(K).call(W,H)}else if(Y.isObject(H)){var V=U(Z);for(var w=0;w<V.length;++w){var M=V[w];if(Z[M]!=H[M])continue $}return z(K).call(W,H)}}return $}}return Q}});var Sc=E((we1,Bw0)=>{var Dw0=w4(),yL1=Dw0.maybeWrapAsError,kL1=_3(),xL1=kL1.OperationalError,Aw0=aU();function fL1($){return $ instanceof Error&&Aw0.getPrototypeOf($)===Error.prototype}var uL1=/^(?:name|message|stack|cause)$/;function bL1($){var Y;if(fL1($)){Y=new xL1($),Y.name=$.name,Y.message=$.message,Y.stack=$.stack;var U=Aw0.keys($);for(var z=0;z<U.length;++z){var I=U[z];if(!uL1.test(I))Y[I]=$[I]}return Y}return Dw0.markAsOriginatingFromRejection($),$}function iL1($,Y){return function(U,z){if($===null)return;if(U){var I=bL1(yL1(U));$._attachExtraTrace(I),$._reject(I)}else if(!Y)$._fulfill(z);else{var Q=arguments.length,J=Array(Math.max(Q-1,0));for(var K=1;K<Q;++K)J[K-1]=arguments[K];$._fulfill(J)}$=null}}Bw0.exports=iL1});var Tw0=E((Me1,Pw0)=>{Pw0.exports=function($,Y,U,z,I){var Q=w4(),J=Q.tryCatch;$.method=function(K){if(typeof K!=="function")throw new $.TypeError("expecting a function but got "+Q.classString(K));return function(){var G=new $(Y);G._captureStackTrace(),G._pushContext();var H=J(K).apply(this,arguments),W=G._popContext();return I.checkForgottenReturns(H,W,"Promise.method",G),G._resolveFromSyncValue(H),G}},$.attempt=$.try=function(K){if(typeof K!=="function")return z("expecting a function but got "+Q.classString(K));var G=new $(Y);G._captureStackTrace(),G._pushContext();var H;if(arguments.length>1){I.deprecated("calling Promise.try with more than 1 argument");var W=arguments[1],X=arguments[2];H=Q.isArray(W)?J(K).apply(X,W):J(K).call(X,W)}else H=J(K)();var Z=G._popContext();return I.checkForgottenReturns(H,Z,"Promise.try",G),G._resolveFromSyncValue(H),G},$.prototype._resolveFromSyncValue=function(K){if(K===Q.errorObj)this._rejectCallback(K.e,!1);else this._resolveCallback(K,!0)}}});var Ew0=E((Oe1,jw0)=>{jw0.exports=function($,Y,U,z){var I=!1,Q=function(H,W){this._reject(W)},J=function(H,W){W.promiseRejectionQueued=!0,W.bindingPromise._then(Q,Q,null,this,H)},K=function(H,W){if((this._bitField&50397184)===0)this._resolveCallback(W.target)},G=function(H,W){if(!W.promiseRejectionQueued)this._reject(H)};$.prototype.bind=function(H){if(!I)I=!0,$.prototype._propagateFrom=z.propagateFromFunction(),$.prototype._boundValue=z.boundValueFunction();var W=U(H),X=new $(Y);X._propagateFrom(this,1);var Z=this._target();if(X._setBoundTo(W),W instanceof $){var q={promiseRejectionQueued:!1,promise:X,target:Z,bindingPromise:W};Z._then(Y,J,vo Line truncated
`)}if(!C("warning",u))q1(u,"",!0)}function e(Q0,A){for(var S=0;S<A.length-1;++S)A[S].push("From previous event:"),A[S]=A[S].join(`
`);if(S<A.length)A[S]=A[S].join(`
`);return Q0+`
`+A.join(`
`)}function O0(Q0){for(var A=0;A<Q0.length;++A)if(Q0[A].length===0||A+1<Q0.length&&Q0[A][0]===Q0[A+1][0])Q0.splice(A,1),A--}function T0(Q0){var A=Q0[0];for(var S=1;S<Q0.length;++S){var u=Q0[S],s=A.length-1,W0=A[s],J0=-1;for(var Z0=u.length-1;Z0>=0;--Z0)if(u[Z0]===W0){J0=Z0;break}for(var Z0=J0;Z0>=0;--Z0){var w0=u[Z0];if(A[s]===w0)A.pop(),s--;else break}A=u}}function y0(Q0){var A=[];for(var S=0;S<Q0.length;++S){var u=Q0[S],s=u===" (No stack trace)"||Z.test(u),W0=s&&b0(u);if(s&&!W0){if(V&&u.charAt(0)!==" ")u=" "+u;A.push(u)}}return A}function v0(Q0){var A=Q0.stack.replace(/\s+$/g,"").split(`
`);for(var S=0;S<A.length;++S){var u=A[S];if(u===" (No stack trace)"||Z.test(u))break}if(S>0&&Q0.name!="SyntaxError")A=A.slice(S);return A}function o0(Q0){var A=Q0.stack,S=Q0.toString();return A=typeof A==="string"&&A.length>0?v0(Q0):[" (No stack trace)"],{message:S,stack:Q0.name=="SyntaxError"?A:y0(A)}}function q1(Q0,A,S){if(typeof console<"u"){var u;if(J.isObject(Q0)){var s=Q0.stack;u=A+q(s,Q0)}else u=A+String(Q0);if(typeof w==="function")w(u,S);else if(typeof console.log==="function"||typeof console.log==="object")console.log(u)}}function t(Q0,A,S,u){var s=!1;try{if(typeof A==="function")if(s=!0,Q0==="rejectionHandled")A(u);else A(S,u)}catch(W0){I.throwLater(W0)}if(Q0==="unhandledRejection"){if(!C(Q0,S,u)&&!s)q1(S,"Unhandled rejection ")}else C(Q0,u)}function X0(Q0){var A;if(typeof Q0==="function")A="[function "+(Q0.name||"anonymous")+"]";else{A=Q0&&typeof Q0.toString==="function"?Q0.toString():J.toString(Q0);var S=/\[object [a-zA-Z0-9$_]+\]/;if(S.test(A))try{var u=JSON.stringify(Q0);A=u}catch(s){}if(A.length===0)A="(empty array)"}return"(<"+F0(A)+">, no stack trace)"}function F0(Q0){var A=41;if(Q0.length<A)return Q0;return Q0.substr(0,A-3)+"..."}function u0(){return typeof b1==="function"}var b0=function(){return!1},c0=/[\/<\(]([^:\/]+):(\d+):(?:\d+)\)?\s*$/;function P1(Q0){var A=Q0.match(c0);if(A)return{fileName:A[1],line:parseInt(A[2],10)}}function k1(Q0,A){if(!u0())return;var S=Q0.stack.split(`
`),u=A.stack.split(`
`),s=-1,W0=-1,J0,Z0;for(var w0=0;w0<S.length;++w0){var B0=P1(S[w0]);if(B0){J0=B0.fileName,s=B0.line;break}}for(var w0=0;w0<u.length;++w0){var B0=P1(u[w0]);if(B0){Z0=B0.fileName,W0=B0.line;break}}if(s<0||W0<0||!J0||!Z0||J0!==Z0||s>=W0)return;b0=function(r0){if(H.test(r0))return!0;var J1=P1(r0);if(J1){if(J1.fileName===J0&&(s<=J1.line&&J1.line<=W0))return!0}return!1}}function u1(Q0){this._parent=Q0,this._promisesCreated=0;var A=this._length=1+(Q0===void 0?0:Q0._length);if(b1(this,u1),A>32)this.uncycle()}J.inherits(u1,Error),Y.CapturedTrace=u1,u1.prototype.uncycle=function(){var Q0=this._length;if(Q0<2)return;var A=[],S={};for(var u=0,s=this;s!==void 0;++u)A.push(s),s=s._parent;Q0=this._length=u;for(var u=Q0-1;u>=0;--u){var W0=A[u].stack;if(S[W0]===void 0)S[W0]=u}for(var u=0;u<Q0;++u){var J0=A[u].stack,Z0=S[J0];if(Z0!==void 0&&Z0!==u){if(Z0>0)A[Z0-1]._parent=void 0,A[Z0-1]._length=1;A[u]._parent=void 0,A[u]._length=1;var w0=u>0?A[u-1]:this;if(Z0<Q0-1)w0._parent=A[Z0+1],w0._parent.uncycle(),w0._length=w0._parent._length+1;else w0._parent=void 0,w0._length=1;var B0=w0._length+1;for(var r0=u-2;r0>=0;--r0)A[r0]._length=B0,B0++;return}}},u1.prototype.attachExtraTrace=function(Q0){if(Q0.__stackCleaned__)return;this.uncycle();var A=o0(Q0),S=A.message,u=[A.stack],s=this;while(s!==void 0)u.push(y0(s.stack.split(`
`))),s=s._parent;T0(u),O0(u),J.notEnumerableProp(Q0,"stack",e(S,u)),J.notEnumerableProp(Q0,"__stackCleaned__",!0)};var b1=function(){var A=/^\s*at\s*/,S=function(J0,Z0){if(typeof J0==="string")return J0;if(Z0.name!==void 0&&Z0.message!==void 0)return Z0.toString();return X0(Z0)};if(typeof Error.stackTraceLimit==="number"&&typeof Error.captureStackTrace==="function"){Error.stackTraceLimit+=6,Z=A,q=S;var u=Error.captureStackTrace;return b0=function(J0){return H.test(J0)},function(J0,Z0){Error.stackTraceLimit+=6,u(J0,Z0),Error.stackTraceLimit-=6}}var s=Error();if(typeof s.stack==="string"&&s.stack.split(`
`)[0].indexOf("stackDetection@")>=0)return Z=/@/,q=S,V=!0,function(Z0){Z0.stack=Error().stack};var W0;try{throw Error()}catch(J0){W0="stack"in J0}if(!("stack"in s)&&W0&&typeof Error.stackTraceLimit==="number")return Z=A,q=S,function(Z0){Error.stackTraceLimit+=6;try{throw Error()}catch(w0){Z0.stack=w0.stack}Error.stackTraceLimit-=6};return q=function(J0,Z0){if(typeof J0==="string")return J0;if((typeof Z0==="object"||typeof Z0==="function")&&Z0.name!==void 0&&Z0.message!==void 0)return Z0.toString();return X0(Z0)},null}([]);if(typeof console<"u"&&typeof console.warn<"u"){if(w=function(Q0){console.warn(Q0)},J.isNode&&process.stderr.isTTY)w=function(Q0,A){var S=A?"\x1B[33m":"\x1B[31m";console.warn(S+Q0+`\x1B[0m
`)};else if(!J.isNode&&typeof Error().stack==="string")w=function(Q0,A){console.warn("%c"+Q0,A?"color: darkorange":"color: red")}}var D0={warnings:F,longStackTraces:!1,cancellation:!1,monitoring:!1};if(N)$.longStackTraces();return{longStackTraces:function(){return D0.longStackTraces},warnings:function(){return D0.warnings},cancellation:function(){return D0.cancellation},monitoring:function(){return D0.monitoring},propagateFromFunction:function(){return a},boundValueFunction:function(){return $0},checkForgottenReturns:Y0,setBounds:k1,warn:o,deprecated:R,CapturedTrace:u1,fireDomEvent:P,fireGlobalEvent:T}}});var hw0=j((g04,Sw0)=>{Sw0.exports=function($,Y){var U=M4(),I=$.CancellationError,Q=U.errorObj;function J(X,Z,q){this.promise=X,this.type=Z,this.handler=q,this.called=!1,this.cancelPromise=null}J.prototype.isFinallyHandler=function(){return this.type===0};function K(X){this.finallyHandler=X}K.prototype._resultCancelled=function(){z(this.finallyHandler)};function z(X,Z){if(X.cancelPromise!=null){if(arguments.length>1)X.cancelPromise._reject(Z);else X.cancelPromise._cancel();return X.cancelPromise=null,!0}return!1}function G(){return W.call(this,this.promise._target()._settledValue())}function H(X){if(z(this,X))return;return Q.e=X,Q}function W(X){var Z=this.promise,q=this.handler;if(!this.called){this.called=!0;var V=this.isFinallyHandler()?q.call(Z._boundValue()):q.call(Z._boundValue(),X);if(V!==void 0){Z._setReturnedNonUndefined();var w=Y(V,Z);if(w instanceof $){if(this.cancelPromise!=null){if(w._isCancelled()){var M=new I("late cancellation observer");return Z._attachExtraTrace(M),Q.e=M,Q}else if(w.isPending())w._attachCancellationCallback(new K(this))}return w._then(G,H,void 0,this,void 0)}}}if(Z.isRejected())return z(this),Q.e=X,Q;else return z(this),X}return $.prototype._passThrough=function(X,Z,q,V){if(typeof X!=="function")return this.then();return this._then(q,V,void 0,new J(this,Z,X),void 0)},$.prototype.lastly=$.prototype.finally=function(X){return this._passThrough(X,0,W,W)},$.prototype.tap=function(X){return this._passThrough(X,1,W)},J}});var yw0=j((y04,gw0)=>{gw0.exports=function($){var Y=M4(),U=tU().keys,I=Y.tryCatch,Q=Y.errorObj;function J(K,z,G){return function(H){var W=G._boundValue();$:for(var X=0;X<K.length;++X){var Z=K[X];if(Z===Error||Z!=null&&Z.prototype instanceof Error){if(H instanceof Z)return I(z).call(W,H)}else if(typeof Z==="function"){var q=I(Z).call(W,H);if(q===Q)return q;else if(q)return I(z).call(W,H)}else if(Y.isObject(H)){var V=U(Z);for(var w=0;w<V.length;++w){var M=V[w];if(Z[M]!=H[M])continue $}return I(z).call(W,H)}}return $}}return J}});var fc=j((k04,fw0)=>{var kw0=M4(),TF1=kw0.maybeWrapAsError,EF1=h3(),jF1=EF1.OperationalError,xw0=tU();function CF1($){return $ instanceof Error&&xw0.getPrototypeOf($)===Error.prototype}var RF1=/^(?:name|message|stack|cause)$/;function _F1($){var Y;if(CF1($)){Y=new jF1($),Y.name=$.name,Y.message=$.message,Y.stack=$.stack;var U=xw0.keys($);for(var I=0;I<U.length;++I){var Q=U[I];if(!RF1.test(Q))Y[Q]=$[Q]}return Y}return kw0.markAsOriginatingFromRejection($),$}function vF1($,Y){return function(U,I){if($===null)return;if(U){var Q=_F1(TF1(U));$._attachExtraTrace(Q),$._reject(Q)}else if(!Y)$._fulfill(I);else{var J=arguments.length,K=Array(Math.max(J-1,0));for(var z=1;z<J;++z)K[z-1]=arguments[z];$._fulfill(K)}$=null}}fw0.exports=vF1});var bw0=j((x04,uw0)=>{uw0.exports=function($,Y,U,I,Q){var J=M4(),K=J.tryCatch;$.method=function(z){if(typeof z!=="function")throw new $.TypeError("expecting a function but got "+J.classString(z));return function(){var G=new $(Y);G._captureStackTrace(),G._pushContext();var H=K(z).apply(this,arguments),W=G._popContext();return Q.checkForgottenReturns(H,W,"Promise.method",G),G._resolveFromSyncValue(H),G}},$.attempt=$.try=function(z){if(typeof z!=="function")return I("expecting a function but got "+J.classString(z));var G=new $(Y);G._captureStackTrace(),G._pushContext();var H;if(arguments.length>1){Q.deprecated("calling Promise.try with more than 1 argument");var W=arguments[1],X=arguments[2];H=J.isArray(W)?K(z).apply(X,W):K(z).call(X,W)}else H=K(z)();var Z=G._popContext();return Q.checkForgottenReturns(H,Z,"Promise.try",G),G._resolveFromSyncValue(H),G},$.prototype._resolveFromSyncValue=function(z){if(z===J.errorObj)this._rejectCallback(z.e,!1);else this._resolveCallback(z,!0)}}});var cw0=j((f04,iw0)=>{iw0.exports=function($,Y,U,I){var Q=!1,J=function(H,W){this._reject(W)},K=function(H,W){W.promiseRejectionQueued=!0,W.bindingPromise._then(J,J,null,this,H)},z=function(H,W){if((this._bitField&50397184)===0)this._resolveCallback(W.target)},G=function(H,W){if(!W.promiseRejectionQueued)this._reject(H)};$.prototype.bind=function(H){if(!Q)Q=!0,$.prototype._propagateFrom=I.propagateFromFunction(),$.prototype._boundValue=I.boundValueFunction();var W=U(H),X=new $(Y);X._propagateFrom(this,1);var Z=this._target();if(X._setBoundTo(W),W instanceof $){var q={promiseRejectionQueued:!1,promise:X,target:Z,bindingPromise:W};Z._then(Y,K,vo Line truncated
See http://goo.gl/MqrFmX
`);return this._settledValue()},z=Y.prototype.error=Y.prototype.reason=function(){if(!this.isRejected())throw TypeError(`cannot get rejection reason of a non-rejected promise
`);return this._settledValue()},I=Y.prototype.error=Y.prototype.reason=function(){if(!this.isRejected())throw TypeError(`cannot get rejection reason of a non-rejected promise
See http://goo.gl/MqrFmX
`);return this._settledValue()},I=Y.prototype.isFulfilled=function(){return(this._bitField&33554432)!==0},Q=Y.prototype.isRejected=function(){return(this._bitField&16777216)!==0},J=Y.prototype.isPending=function(){return(this._bitField&50397184)===0},K=Y.prototype.isResolved=function(){return(this._bitField&50331648)!==0};Y.prototype.isCancelled=function(){return(this._bitField&8454144)!==0},$.prototype.__isCancelled=function(){return(this._bitField&65536)===65536},$.prototype._isCancelled=function(){return this._target().__isCancelled()},$.prototype.isCancelled=function(){return(this._target()._bitField&8454144)!==0},$.prototype.isPending=function(){return J.call(this._target())},$.prototype.isRejected=function(){return Q.call(this._target())},$.prototype.isFulfilled=function(){return I.call(this._target())},$.prototype.isResolved=function(){return K.call(this._target())},$.prototype.value=function(){return U.call(this._target())},$.prototype.reason=function(){var G=this._target();return G._unsetRejectionIsUnhandled(),z.call(G)},$.prototype._value=function(){return this._settledValue()},$.prototype._reason=function(){return this._unsetRejectionIsUnhandled(),this._settledValue()},$.PromiseInspection=Y}});var yw0=E((Be1,gw0)=>{gw0.exports=function($,Y,U,z,I,Q){var J=w4(),K=J.canEvaluate,G=J.tryCatch,H=J.errorObj,W;if(K){var X=function(N){return Function("value","holder",`
`);return this._settledValue()},Q=Y.prototype.isFulfilled=function(){return(this._bitField&33554432)!==0},J=Y.prototype.isRejected=function(){return(this._bitField&16777216)!==0},K=Y.prototype.isPending=function(){return(this._bitField&50397184)===0},z=Y.prototype.isResolved=function(){return(this._bitField&50331648)!==0};Y.prototype.isCancelled=function(){return(this._bitField&8454144)!==0},$.prototype.__isCancelled=function(){return(this._bitField&65536)===65536},$.prototype._isCancelled=function(){return this._target().__isCancelled()},$.prototype.isCancelled=function(){return(this._target()._bitField&8454144)!==0},$.prototype.isPending=function(){return K.call(this._target())},$.prototype.isRejected=function(){return J.call(this._target())},$.prototype.isFulfilled=function(){return Q.call(this._target())},$.prototype.isResolved=function(){return z.call(this._target())},$.prototype.value=function(){return U.call(this._target())},$.prototype.reason=function(){var G=this._target();return G._unsetRejectionIsUnhandled(),I.call(G)},$.prototype._value=function(){return this._settledValue()},$.prototype._reason=function(){return this._unsetRejectionIsUnhandled(),this._settledValue()},$.PromiseInspection=Y}});var sw0=j((c04,rw0)=>{rw0.exports=function($,Y,U,I,Q,J){var K=M4(),z=K.canEvaluate,G=K.tryCatch,H=K.errorObj,W;if(z){var X=function(N){return Function("value","holder",`
'use strict';
holder.pIndex = value;
holder.checkFulfillment(this);
@@ -161,7 +161,7 @@ See: https://github.com/isaacs/node-glob/issues/167`);if(!(this instanceof j6))r
promise.cancel();
}
`}).join(`
`),A=O.join(", "),j="Holder$"+N,C=`return function(tryCatch, errorObj, Promise, async) {
`),B=O.join(", "),E="Holder$"+N,C=`return function(tryCatch, errorObj, Promise, async) {
'use strict';
function [TheName](fn) {
[TheProperties]
@@ -199,7 +199,7 @@ See: https://github.com/isaacs/node-glob/issues/167`);if(!(this instanceof j6))r
return [TheName];
}(tryCatch, errorObj, Promise, async);
`;return C=C.replace(/\[TheName\]/g,j).replace(/\[TheTotal\]/g,N).replace(/\[ThePassedArguments\]/g,A).replace(/\[TheProperties\]/g,P).replace(/\[CancellationCode\]/g,T),Function("tryCatch","errorObj","Promise","async",C)(G,H,$,I)},V=[],w=[],M=[];for(var F=0;F<8;++F)V.push(q(F+1)),w.push(X(F+1)),M.push(Z(F+1));W=function(N){this._reject(N)}}$.join=function(){var N=arguments.length-1,O;if(N>0&&typeof arguments[N]==="function"){if(O=arguments[N],N<=8&&K){var c=new $(z);c._captureStackTrace();var D=V[N-1],P=new D(O),T=w;for(var A=0;A<N;++A){var j=U(arguments[A],c);if(j instanceof $){j=j._target();var C=j._bitField;if((C&50397184)===0)j._then(T[A],W,void 0,c,P),M[A](j,P),P.asyncNeeded=!1;else if((C&33554432)!==0)T[A].call(c,j._value(),P);else if((C&16777216)!==0)c._reject(j._reason());else c._cancel()}else T[A].call(c,j,P)}if(!c._isFateSealed()){if(P.asyncNeeded){var b=Q();if(b!==null)P.fn=J.domainBind(b,P.fn)}c._setAsyncGuaranteed(),c._setOnCancel(P)}return c}}var x=arguments.length,g=Array(x);for(var i=0;i<x;++i)g[i]=arguments[i];if(O)g.pop();var c=new Y(g).promise();return O!==void 0?c.spread(O):c}}});var xw0=E((Pe1,kw0)=>{kw0.exports=function($,Y,U,z,I,Q){var J=$._getDomain,K=w4(),G=K.tryCatch,H=K.errorObj,W=$._async;function X(q,V,w,M){this.constructor$(q),this._promise._captureStackTrace();var F=J();this._callback=F===null?V:K.domainBind(F,V),this._preservedValues=M===I?Array(this.length()):null,this._limit=w,this._inFlight=0,this._queue=[],W.invoke(this._asyncInit,this,void 0)}K.inherits(X,Y),X.prototype._asyncInit=function(){this._init$(void 0,-2)},X.prototype._init=function(){},X.prototype._promiseFulfilled=function(q,V){var w=this._values,M=this.length(),F=this._preservedValues,N=this._limit;if(V<0){if(V=V*-1-1,w[V]=q,N>=1){if(this._inFlight--,this._drainQueue(),this._isResolved())return!0}}else{if(N>=1&&this._inFlight>=N)return w[V]=q,this._queue.push(V),!1;if(F!==null)F[V]=q;var O=this._promise,D=this._callback,P=O._boundValue();O._pushContext();var T=G(D).call(P,q,V,M),A=O._popContext();if(Q.checkForgottenReturns(T,A,F!==null?"Promise.filter":"Promise.map",O),T===H)return this._reject(T.e),!0;var j=z(T,this._promise);if(j instanceof $){j=j._target();var C=j._bitField;if((C&50397184)===0){if(N>=1)this._inFlight++;return w[V]=j,j._proxy(this,(V+1)*-1),!1}else if((C&33554432)!==0)T=j._value();else if((C&16777216)!==0)return this._reject(j._reason()),!0;else return this._cancel(),!0}w[V]=T}var b=++this._totalResolved;if(b>=M){if(F!==null)this._filter(w,F);else this._resolve(w);return!0}return!1},X.prototype._drainQueue=function(){var q=this._queue,V=this._limit,w=this._values;while(q.length>0&&this._inFlight<V){if(this._isResolved())return;var M=q.pop();this._promiseFulfilled(w[M],M)}},X.prototype._filter=function(q,V){var w=V.length,M=Array(w),F=0;for(var N=0;N<w;++N)if(q[N])M[F++]=V[N];M.length=F,this._resolve(M)},X.prototype.preservedValues=function(){return this._preservedValues};function Z(q,V,w,M){if(typeof V!=="function")return U("expecting a function but got "+K.classString(V));var F=0;if(w!==void 0)if(typeof w==="object"&&w!==null){if(typeof w.concurrency!=="number")return $.reject(TypeError("'concurrency' must be a number but it is "+K.classString(w.concurrency)));F=w.concurrency}else return $.reject(TypeError("options argument must be an object but it is "+K.classString(w)));return F=typeof F==="number"&&isFinite(F)&&F>=1?F:0,new X(q,V,F,M).promise()}$.prototype.map=function(q,V){return Z(this,q,V,null)},$.map=function(q,V,w,M){return Z(q,V,w,M)}}});var uw0=E((Te1,fw0)=>{var gc=Object.create;if(gc)mA=gc(null),lA=gc(null),mA[" size"]=lA[" size"]=0;var mA,lA;fw0.exports=function($){var Y=w4(),U=Y.canEvaluate,z=Y.isIdentifier,I,Q,J=function(q){return Function("ensureMethod",`
`;return C=C.replace(/\[TheName\]/g,E).replace(/\[TheTotal\]/g,N).replace(/\[ThePassedArguments\]/g,B).replace(/\[TheProperties\]/g,P).replace(/\[CancellationCode\]/g,T),Function("tryCatch","errorObj","Promise","async",C)(G,H,$,Q)},V=[],w=[],M=[];for(var F=0;F<8;++F)V.push(q(F+1)),w.push(X(F+1)),M.push(Z(F+1));W=function(N){this._reject(N)}}$.join=function(){var N=arguments.length-1,O;if(N>0&&typeof arguments[N]==="function"){if(O=arguments[N],N<=8&&z){var c=new $(I);c._captureStackTrace();var D=V[N-1],P=new D(O),T=w;for(var B=0;B<N;++B){var E=U(arguments[B],c);if(E instanceof $){E=E._target();var C=E._bitField;if((C&50397184)===0)E._then(T[B],W,void 0,c,P),M[B](E,P),P.asyncNeeded=!1;else if((C&33554432)!==0)T[B].call(c,E._value(),P);else if((C&16777216)!==0)c._reject(E._reason());else c._cancel()}else T[B].call(c,E,P)}if(!c._isFateSealed()){if(P.asyncNeeded){var b=J();if(b!==null)P.fn=K.domainBind(b,P.fn)}c._setAsyncGuaranteed(),c._setOnCancel(P)}return c}}var x=arguments.length,g=Array(x);for(var i=0;i<x;++i)g[i]=arguments[i];if(O)g.pop();var c=new Y(g).promise();return O!==void 0?c.spread(O):c}}});var tw0=j((n04,aw0)=>{aw0.exports=function($,Y,U,I,Q,J){var K=$._getDomain,z=M4(),G=z.tryCatch,H=z.errorObj,W=$._async;function X(q,V,w,M){this.constructor$(q),this._promise._captureStackTrace();var F=K();this._callback=F===null?V:z.domainBind(F,V),this._preservedValues=M===Q?Array(this.length()):null,this._limit=w,this._inFlight=0,this._queue=[],W.invoke(this._asyncInit,this,void 0)}z.inherits(X,Y),X.prototype._asyncInit=function(){this._init$(void 0,-2)},X.prototype._init=function(){},X.prototype._promiseFulfilled=function(q,V){var w=this._values,M=this.length(),F=this._preservedValues,N=this._limit;if(V<0){if(V=V*-1-1,w[V]=q,N>=1){if(this._inFlight--,this._drainQueue(),this._isResolved())return!0}}else{if(N>=1&&this._inFlight>=N)return w[V]=q,this._queue.push(V),!1;if(F!==null)F[V]=q;var O=this._promise,D=this._callback,P=O._boundValue();O._pushContext();var T=G(D).call(P,q,V,M),B=O._popContext();if(J.checkForgottenReturns(T,B,F!==null?"Promise.filter":"Promise.map",O),T===H)return this._reject(T.e),!0;var E=I(T,this._promise);if(E instanceof $){E=E._target();var C=E._bitField;if((C&50397184)===0){if(N>=1)this._inFlight++;return w[V]=E,E._proxy(this,(V+1)*-1),!1}else if((C&33554432)!==0)T=E._value();else if((C&16777216)!==0)return this._reject(E._reason()),!0;else return this._cancel(),!0}w[V]=T}var b=++this._totalResolved;if(b>=M){if(F!==null)this._filter(w,F);else this._resolve(w);return!0}return!1},X.prototype._drainQueue=function(){var q=this._queue,V=this._limit,w=this._values;while(q.length>0&&this._inFlight<V){if(this._isResolved())return;var M=q.pop();this._promiseFulfilled(w[M],M)}},X.prototype._filter=function(q,V){var w=V.length,M=Array(w),F=0;for(var N=0;N<w;++N)if(q[N])M[F++]=V[N];M.length=F,this._resolve(M)},X.prototype.preservedValues=function(){return this._preservedValues};function Z(q,V,w,M){if(typeof V!=="function")return U("expecting a function but got "+z.classString(V));var F=0;if(w!==void 0)if(typeof w==="object"&&w!==null){if(typeof w.concurrency!=="number")return $.reject(TypeError("'concurrency' must be a number but it is "+z.classString(w.concurrency)));F=w.concurrency}else return $.reject(TypeError("options argument must be an object but it is "+z.classString(w)));return F=typeof F==="number"&&isFinite(F)&&F>=1?F:0,new X(q,V,F,M).promise()}$.prototype.map=function(q,V){return Z(this,q,V,null)},$.map=function(q,V,w,M){return Z(q,V,w,M)}}});var $M0=j((d04,ew0)=>{var uc=Object.create;if(uc)$A=uc(null),YA=uc(null),$A[" size"]=YA[" size"]=0;var $A,YA;ew0.exports=function($){var Y=M4(),U=Y.canEvaluate,I=Y.isIdentifier,Q,J,K=function(q){return Function("ensureMethod",`
return function(obj) {
'use strict'
var len = this.length;
@@ -213,26 +213,26 @@ See: https://github.com/isaacs/node-glob/issues/167`);if(!(this instanceof j6))r
return obj.methodName.apply(obj, this);
}
};
`.replace(/methodName/g,q))(H)},K=function(q){return Function("obj",`
`.replace(/methodName/g,q))(H)},z=function(q){return Function("obj",`
'use strict';
return obj.propertyName;
`.replace("propertyName",q))},G=function(q,V,w){var M=w[q];if(typeof M!=="function"){if(!z(q))return null;if(M=V(q),w[q]=M,w[" size"]++,w[" size"]>512){var F=Object.keys(w);for(var N=0;N<256;++N)delete w[F[N]];w[" size"]=F.length-256}}return M};I=function(q){return G(q,J,mA)},Q=function(q){return G(q,K,lA)};function H(q,V){var w;if(q!=null)w=q[V];if(typeof w!=="function"){var M="Object "+Y.classString(q)+" has no method '"+Y.toString(V)+"'";throw new $.TypeError(M)}return w}function W(q){var V=this.pop(),w=H(q,V);return w.apply(q,this)}$.prototype.call=function(q){var V=arguments.length,w=Array(Math.max(V-1,0));for(var M=1;M<V;++M)w[M-1]=arguments[M];if(U){var F=I(q);if(F!==null)return this._then(F,void 0,void 0,w,void 0)}return w.push(q),this._then(W,void 0,void 0,w,void 0)};function X(q){return q[this]}function Z(q){var V=+this;if(V<0)V=Math.max(0,V+q.length);return q[V]}$.prototype.get=function(q){var V=typeof q==="number",w;if(!V)if(U){var M=Q(q);w=M!==null?M:X}else w=X;else w=Z;return this._then(w,void 0,void 0,q,void 0)}}});var iw0=E((je1,bw0)=>{bw0.exports=function($,Y,U,z,I,Q){var J=w4(),K=_3().TypeError,G=w4().inherits,H=J.errorObj,W=J.tryCatch,X={};function Z(O){setTimeout(function(){throw O},0)}function q(O){var D=U(O);if(D!==O&&typeof O._isDisposable==="function"&&typeof O._getDisposer==="function"&&O._isDisposable())D._setDisposable(O._getDisposer());return D}function V(O,D){var P=0,T=O.length,A=new $(I);function j(){if(P>=T)return A._fulfill();var C=q(O[P++]);if(C instanceof $&&C._isDisposable()){try{C=U(C._getDisposer().tryDispose(D),O.promise)}catch(b){return Z(b)}if(C instanceof $)return C._then(j,Z,null,null,null)}j()}return j(),A}function w(O,D,P){this._data=O,this._promise=D,this._context=P}w.prototype.data=function(){return this._data},w.prototype.promise=function(){return this._promise},w.prototype.resource=function(){if(this.promise().isFulfilled())return this.promise().value();return X},w.prototype.tryDispose=function(O){var D=this.resource(),P=this._context;if(P!==void 0)P._pushContext();var T=D!==X?this.doDispose(D,O):null;if(P!==void 0)P._popContext();return this._promise._unsetDisposable(),this._data=null,T},w.isDisposer=function(O){return O!=null&&typeof O.resource==="function"&&typeof O.tryDispose==="function"};function M(O,D,P){this.constructor$(O,D,P)}G(M,w),M.prototype.doDispose=function(O,D){var P=this.data();return P.call(O,O,D)};function F(O){if(w.isDisposer(O))return this.resources[this.index]._setDisposable(O),O.promise();return O}function N(O){this.length=O,this.promise=null,this[O-1]=null}N.prototype._resultCancelled=function(){var O=this.length;for(var D=0;D<O;++D){var P=this[D];if(P instanceof $)P.cancel()}},$.using=function(){var O=arguments.length;if(O<2)return Y("you must pass at least 2 arguments to Promise.using");var D=arguments[O-1];if(typeof D!=="function")return Y("expecting a function but got "+J.classString(D));var P,T=!0;if(O===2&&Array.isArray(arguments[0]))P=arguments[0],O=P.length,T=!1;else P=arguments,O--;var A=new N(O);for(var j=0;j<O;++j){var C=P[j];if(w.isDisposer(C)){var b=C;C=C.promise(),C._setDisposable(b)}else{var x=U(C);if(x instanceof $)C=x._then(F,null,null,{resources:A,index:j},void 0)}A[j]=C}var g=Array(A.length);for(var j=0;j<g.length;++j)g[j]=$.resolve(A[j]).reflect();var i=$.all(g).then(function(z0){for(var k=0;k<z0.length;++k){var d=z0[k];if(d.isRejected())return H.e=d.error(),H;else if(!d.isFulfilled()){i.cancel();return}z0[k]=d.value()}c._pushContext(),D=W(D);var a=T?D.apply(void 0,z0):D(z0),$0=c._popContext();return Q.checkForgottenReturns(a,$0,"Promise.using",c),a}),c=i.lastly(function(){var z0=new $.PromiseInspection(i);return V(A,z0)});return A.promise=c,c._setOnCancel(A),c},$.prototype._setDisposable=function(O){this._bitField=this._bitField|131072,this._disposer=O},$.prototype._isDisposable=function(){return(this._bitField&131072)>0},$.prototype._getDisposer=function(){return this._disposer},$.prototype._unsetDisposable=function(){this._bitField=this._bitField&-131073,this._disposer=void 0},$.prototype.disposer=function(O){if(typeof O==="function")return new M(O,this,z());throw new K}}});var nw0=E((Ee1,cw0)=>{cw0.exports=function($,Y,U){var z=w4(),I=$.TimeoutError;function Q(X){this.handle=X}Q.prototype._resultCancelled=function(){clearTimeout(this.handle)};var J=function(X){return K(+this).thenReturn(X)},K=$.delay=function(X,Z){var q,V;if(Z!==void 0){if(q=$.resolve(Z)._then(J,null,null,X,void 0),U.cancellation()&&Z instanceof $)q._setOnCancel(Z)}else{if(q=new $(Y),V=setTimeout(function(){q._fulfill()},+X),U.cancellation())q._setOnCancel(new Q(V));q._captureStackTrace()}return q._setAsyncGuaranteed(),q};$.prototype.delay=function(X){return K(X,this)};var G=function(X,Z,q){var V;if(typeof Z!=="string")if(Z instanceof Error)V=Z;else V=new I("operation timed out");else V=new I(Z);if(z.markAsOriginatingFromRejection(V),X._attachExtraTrace(V),X._reject(V),q!=null)q.cancel()};function H(X){return clearTimeout(this.handle),X Line truncated
`.replace("propertyName",q))},G=function(q,V,w){var M=w[q];if(typeof M!=="function"){if(!I(q))return null;if(M=V(q),w[q]=M,w[" size"]++,w[" size"]>512){var F=Object.keys(w);for(var N=0;N<256;++N)delete w[F[N]];w[" size"]=F.length-256}}return M};Q=function(q){return G(q,K,$A)},J=function(q){return G(q,z,YA)};function H(q,V){var w;if(q!=null)w=q[V];if(typeof w!=="function"){var M="Object "+Y.classString(q)+" has no method '"+Y.toString(V)+"'";throw new $.TypeError(M)}return w}function W(q){var V=this.pop(),w=H(q,V);return w.apply(q,this)}$.prototype.call=function(q){var V=arguments.length,w=Array(Math.max(V-1,0));for(var M=1;M<V;++M)w[M-1]=arguments[M];if(U){var F=Q(q);if(F!==null)return this._then(F,void 0,void 0,w,void 0)}return w.push(q),this._then(W,void 0,void 0,w,void 0)};function X(q){return q[this]}function Z(q){var V=+this;if(V<0)V=Math.max(0,V+q.length);return q[V]}$.prototype.get=function(q){var V=typeof q==="number",w;if(!V)if(U){var M=J(q);w=M!==null?M:X}else w=X;else w=Z;return this._then(w,void 0,void 0,q,void 0)}}});var UM0=j((p04,YM0)=>{YM0.exports=function($,Y,U,I,Q,J){var K=M4(),z=h3().TypeError,G=M4().inherits,H=K.errorObj,W=K.tryCatch,X={};function Z(O){setTimeout(function(){throw O},0)}function q(O){var D=U(O);if(D!==O&&typeof O._isDisposable==="function"&&typeof O._getDisposer==="function"&&O._isDisposable())D._setDisposable(O._getDisposer());return D}function V(O,D){var P=0,T=O.length,B=new $(Q);function E(){if(P>=T)return B._fulfill();var C=q(O[P++]);if(C instanceof $&&C._isDisposable()){try{C=U(C._getDisposer().tryDispose(D),O.promise)}catch(b){return Z(b)}if(C instanceof $)return C._then(E,Z,null,null,null)}E()}return E(),B}function w(O,D,P){this._data=O,this._promise=D,this._context=P}w.prototype.data=function(){return this._data},w.prototype.promise=function(){return this._promise},w.prototype.resource=function(){if(this.promise().isFulfilled())return this.promise().value();return X},w.prototype.tryDispose=function(O){var D=this.resource(),P=this._context;if(P!==void 0)P._pushContext();var T=D!==X?this.doDispose(D,O):null;if(P!==void 0)P._popContext();return this._promise._unsetDisposable(),this._data=null,T},w.isDisposer=function(O){return O!=null&&typeof O.resource==="function"&&typeof O.tryDispose==="function"};function M(O,D,P){this.constructor$(O,D,P)}G(M,w),M.prototype.doDispose=function(O,D){var P=this.data();return P.call(O,O,D)};function F(O){if(w.isDisposer(O))return this.resources[this.index]._setDisposable(O),O.promise();return O}function N(O){this.length=O,this.promise=null,this[O-1]=null}N.prototype._resultCancelled=function(){var O=this.length;for(var D=0;D<O;++D){var P=this[D];if(P instanceof $)P.cancel()}},$.using=function(){var O=arguments.length;if(O<2)return Y("you must pass at least 2 arguments to Promise.using");var D=arguments[O-1];if(typeof D!=="function")return Y("expecting a function but got "+K.classString(D));var P,T=!0;if(O===2&&Array.isArray(arguments[0]))P=arguments[0],O=P.length,T=!1;else P=arguments,O--;var B=new N(O);for(var E=0;E<O;++E){var C=P[E];if(w.isDisposer(C)){var b=C;C=C.promise(),C._setDisposable(b)}else{var x=U(C);if(x instanceof $)C=x._then(F,null,null,{resources:B,index:E},void 0)}B[E]=C}var g=Array(B.length);for(var E=0;E<g.length;++E)g[E]=$.resolve(B[E]).reflect();var i=$.all(g).then(function(I0){for(var k=0;k<I0.length;++k){var p=I0[k];if(p.isRejected())return H.e=p.error(),H;else if(!p.isFulfilled()){i.cancel();return}I0[k]=p.value()}c._pushContext(),D=W(D);var a=T?D.apply(void 0,I0):D(I0),$0=c._popContext();return J.checkForgottenReturns(a,$0,"Promise.using",c),a}),c=i.lastly(function(){var I0=new $.PromiseInspection(i);return V(B,I0)});return B.promise=c,c._setOnCancel(B),c},$.prototype._setDisposable=function(O){this._bitField=this._bitField|131072,this._disposer=O},$.prototype._isDisposable=function(){return(this._bitField&131072)>0},$.prototype._getDisposer=function(){return this._disposer},$.prototype._unsetDisposable=function(){this._bitField=this._bitField&-131073,this._disposer=void 0},$.prototype.disposer=function(O){if(typeof O==="function")return new M(O,this,I());throw new z}}});var QM0=j((m04,IM0)=>{IM0.exports=function($,Y,U){var I=M4(),Q=$.TimeoutError;function J(X){this.handle=X}J.prototype._resultCancelled=function(){clearTimeout(this.handle)};var K=function(X){return z(+this).thenReturn(X)},z=$.delay=function(X,Z){var q,V;if(Z!==void 0){if(q=$.resolve(Z)._then(K,null,null,X,void 0),U.cancellation()&&Z instanceof $)q._setOnCancel(Z)}else{if(q=new $(Y),V=setTimeout(function(){q._fulfill()},+X),U.cancellation())q._setOnCancel(new J(V));q._captureStackTrace()}return q._setAsyncGuaranteed(),q};$.prototype.delay=function(X){return z(X,this)};var G=function(X,Z,q){var V;if(typeof Z!=="string")if(Z instanceof Error)V=Z;else V=new Q("operation timed out");else V=new Q(Z);if(I.markAsOriginatingFromRejection(V),X._attachExtraTrace(V),X._reject(V),q!=null)q.cancel()};function H(X){return clearTimeout(this.handle),X Line truncated
See http://goo.gl/MqrFmX
`.replace("%s",M)+`From coroutine:
`+this._stack.split(`
`).slice(1,-7).join(`
`)));return}}F=F._target();var N=F._bitField;if((N&50397184)===0)this._yieldedPromise=F,F._proxy(this,null);else if((N&33554432)!==0)$._async.invoke(this._promiseFulfilled,this,F._value());else if((N&16777216)!==0)$._async.invoke(this._promiseRejected,this,F._reason());else this._promiseCancelled()}},$.coroutine=function(V,w){if(typeof V!=="function")throw new K(`generatorFunction must be a function
`)));return}}F=F._target();var N=F._bitField;if((N&50397184)===0)this._yieldedPromise=F,F._proxy(this,null);else if((N&33554432)!==0)$._async.invoke(this._promiseFulfilled,this,F._value());else if((N&16777216)!==0)$._async.invoke(this._promiseRejected,this,F._reason());else this._promiseCancelled()}},$.coroutine=function(V,w){if(typeof V!=="function")throw new z(`generatorFunction must be a function
See http://goo.gl/MqrFmX
`);var M=Object(w).yieldHandler,F=q,N=Error().stack;return function(){var O=V.apply(this,arguments),D=new F(void 0,void 0,M,N),P=D.promise();return D._generator=O,D._promiseFulfilled(void 0),P}},$.coroutine.addYieldHandler=function(V){if(typeof V!=="function")throw new K("expecting a function but got "+G.classString(V));X.push(V)},$.spawn=function(V){if(Q.deprecated("Promise.spawn()","Promise.coroutine()"),typeof V!=="function")return Y(`generatorFunction must be a function
`);var M=Object(w).yieldHandler,F=q,N=Error().stack;return function(){var O=V.apply(this,arguments),D=new F(void 0,void 0,M,N),P=D.promise();return D._generator=O,D._promiseFulfilled(void 0),P}},$.coroutine.addYieldHandler=function(V){if(typeof V!=="function")throw new z("expecting a function but got "+G.classString(V));X.push(V)},$.spawn=function(V){if(J.deprecated("Promise.spawn()","Promise.coroutine()"),typeof V!=="function")return Y(`generatorFunction must be a function
See http://goo.gl/MqrFmX
`);var w=new q(V,this),M=w.promise();return w._run($.spawn),M}}});var lw0=E((Re1,mw0)=>{mw0.exports=function($){var Y=w4(),U=$._async,z=Y.tryCatch,I=Y.errorObj;function Q(G,H){var W=this;if(!Y.isArray(G))return J.call(W,G,H);var X=z(H).apply(W._boundValue(),[null].concat(G));if(X===I)U.throwLater(X.e)}function J(G,H){var W=this,X=W._boundValue(),Z=G===void 0?z(H).call(X,null):z(H).call(X,null,G);if(Z===I)U.throwLater(Z.e)}function K(G,H){var W=this;if(!G){var X=Error(G+"");X.cause=G,G=X}var Z=z(H).call(W._boundValue(),G);if(Z===I)U.throwLater(Z.e)}$.prototype.asCallback=$.prototype.nodeify=function(G,H){if(typeof G=="function"){var W=J;if(H!==void 0&&Object(H).spread)W=Q;this._then(W,K,void 0,this,G)}return this}}});var rw0=E((_e1,ow0)=>{ow0.exports=function($,Y){var U={},z=w4(),I=Sc(),Q=z.withAppended,J=z.maybeWrapAsError,K=z.canEvaluate,G=_3().TypeError,H="Async",W={__isPromisified__:!0},X=["arity","length","name","arguments","caller","callee","prototype","__isPromisified__"],Z=new RegExp("^(?:"+X.join("|")+")$"),q=function(i){return z.isIdentifier(i)&&i.charAt(0)!=="_"&&i!=="constructor"};function V(i){return!Z.test(i)}function w(i){try{return i.__isPromisified__===!0}catch(c){return!1}}function M(i,c,z0){var k=z.getDataPropertyOrDefault(i,c+z0,W);return k?w(k):!1}function F(i,c,z0){for(var k=0;k<i.length;k+=2){var d=i[k];if(z0.test(d)){var a=d.replace(z0,"");for(var $0=0;$0<i.length;$0+=2)if(i[$0]===a)throw new G(`Cannot promisify an API that has normal methods with '%s'-suffix
`);var w=new q(V,this),M=w.promise();return w._run($.spawn),M}}});var GM0=j((o04,zM0)=>{zM0.exports=function($){var Y=M4(),U=$._async,I=Y.tryCatch,Q=Y.errorObj;function J(G,H){var W=this;if(!Y.isArray(G))return K.call(W,G,H);var X=I(H).apply(W._boundValue(),[null].concat(G));if(X===Q)U.throwLater(X.e)}function K(G,H){var W=this,X=W._boundValue(),Z=G===void 0?I(H).call(X,null):I(H).call(X,null,G);if(Z===Q)U.throwLater(Z.e)}function z(G,H){var W=this;if(!G){var X=Error(G+"");X.cause=G,G=X}var Z=I(H).call(W._boundValue(),G);if(Z===Q)U.throwLater(Z.e)}$.prototype.asCallback=$.prototype.nodeify=function(G,H){if(typeof G=="function"){var W=K;if(H!==void 0&&Object(H).spread)W=J;this._then(W,z,void 0,this,G)}return this}}});var WM0=j((r04,HM0)=>{HM0.exports=function($,Y){var U={},I=M4(),Q=fc(),J=I.withAppended,K=I.maybeWrapAsError,z=I.canEvaluate,G=h3().TypeError,H="Async",W={__isPromisified__:!0},X=["arity","length","name","arguments","caller","callee","prototype","__isPromisified__"],Z=new RegExp("^(?:"+X.join("|")+")$"),q=function(i){return I.isIdentifier(i)&&i.charAt(0)!=="_"&&i!=="constructor"};function V(i){return!Z.test(i)}function w(i){try{return i.__isPromisified__===!0}catch(c){return!1}}function M(i,c,I0){var k=I.getDataPropertyOrDefault(i,c+I0,W);return k?w(k):!1}function F(i,c,I0){for(var k=0;k<i.length;k+=2){var p=i[k];if(I0.test(p)){var a=p.replace(I0,"");for(var $0=0;$0<i.length;$0+=2)if(i[$0]===a)throw new G(`Cannot promisify an API that has normal methods with '%s'-suffix
See http://goo.gl/MqrFmX
`.replace("%s",c))}}}function N(i,c,z0,k){var d=z.inheritedDataKeys(i),a=[];for(var $0=0;$0<d.length;++$0){var y=d[$0],p=i[y],Y0=k===q?!0:q(y,p,i);if(typeof p==="function"&&!w(p)&&!M(i,y,c)&&k(y,p,i,Y0))a.push(y,p)}return F(a,c,z0),a}var O=function(i){return i.replace(/([$])/,"\\$")},D,P=function(i){var c=[i],z0=Math.max(0,i-1-3);for(var k=i-1;k>=z0;--k)c.push(k);for(var k=i+1;k<=3;++k)c.push(k);return c},T=function(i){return z.filledRange(i,"_arg","")},A=function(i){return z.filledRange(Math.max(i,3),"_arg","")},j=function(i){if(typeof i.length==="number")return Math.max(Math.min(i.length,1024),0);return 0};D=function(i,c,z0,k,d,a){var $0=Math.max(0,j(k)-1),y=P($0),p=typeof i==="string"||c===U;function Y0(O0){var T0=T(O0).join(", "),y0=O0>0?", ":"",v0;if(p)v0=`ret = callback.call(this, {{args}}, nodeback); break;
`.replace("%s",c))}}}function N(i,c,I0,k){var p=I.inheritedDataKeys(i),a=[];for(var $0=0;$0<p.length;++$0){var y=p[$0],d=i[y],Y0=k===q?!0:q(y,d,i);if(typeof d==="function"&&!w(d)&&!M(i,y,c)&&k(y,d,i,Y0))a.push(y,d)}return F(a,c,I0),a}var O=function(i){return i.replace(/([$])/,"\\$")},D,P=function(i){var c=[i],I0=Math.max(0,i-1-3);for(var k=i-1;k>=I0;--k)c.push(k);for(var k=i+1;k<=3;++k)c.push(k);return c},T=function(i){return I.filledRange(i,"_arg","")},B=function(i){return I.filledRange(Math.max(i,3),"_arg","")},E=function(i){if(typeof i.length==="number")return Math.max(Math.min(i.length,1024),0);return 0};D=function(i,c,I0,k,p,a){var $0=Math.max(0,E(k)-1),y=P($0),d=typeof i==="string"||c===U;function Y0(O0){var T0=T(O0).join(", "),y0=O0>0?", ":"",v0;if(d)v0=`ret = callback.call(this, {{args}}, nodeback); break;
`;else v0=c===void 0?`ret = callback({{args}}, nodeback); break;
`:`ret = callback.call(receiver, {{args}}, nodeback); break;
`;return v0.replace("{{args}}",T0).replace(", ",y0)}function R(){var O0="";for(var T0=0;T0<y.length;++T0)O0+="case "+y[T0]+":"+Y0(y[T0]);return O0+=`
@@ -245,7 +245,7 @@ See: https://github.com/isaacs/node-glob/issues/167`);if(!(this instanceof j6))r
args[i] = nodeback;
[CodeForCall]
break;
`.replace("[CodeForCall]",p?`ret = callback.apply(this, args);
`.replace("[CodeForCall]",d?`ret = callback.apply(this, args);
`:`ret = callback.apply(receiver, args);
`),O0}var o=typeof i==="string"?"this != null ? this['"+i+"'] : fn":"fn",e=`'use strict';
var ret = function (Parameters) {
@@ -267,25 +267,25 @@ See: https://github.com/isaacs/node-glob/issues/167`);if(!(this instanceof j6))r
};
notEnumerableProp(ret, '__isPromisified__', true);
return ret;
`.replace("[CodeForSwitchCase]",R()).replace("[GetFunctionCode]",o);return e=e.replace("Parameters",A($0)),Function("Promise","fn","receiver","withAppended","maybeWrapAsError","nodebackForPromise","tryCatch","errorObj","notEnumerableProp","INTERNAL",e)($,k,c,Q,J,I,z.tryCatch,z.errorObj,z.notEnumerableProp,Y)};function C(i,c,z0,k,d,a){var $0=function(){return this}(),y=i;if(typeof y==="string")i=k;function p(){var Y0=c;if(c===U)Y0=this;var R=new $(Y);R._captureStackTrace();var o=typeof y==="string"&&this!==$0?this[y]:i,e=I(R,a);try{o.apply(Y0,Q(arguments,e))}catch(O0){R._rejectCallback(J(O0),!0,!0)}if(!R._isFateSealed())R._setAsyncGuaranteed();return R}return z.notEnumerableProp(p,"__isPromisified__",!0),p}var b=K?D:C;function x(i,c,z0,k,d){var a=new RegExp(O(c)+"$"),$0=N(i,c,a,z0);for(var y=0,p=$0.length;y<p;y+=2){var Y0=$0[y],R=$0[y+1],o=Y0+c;if(k===b)i[o]=b(Y0,U,Y0,R,c,d);else{var e=k(R,function(){return b(Y0,U,Y0,R,c,d)});z.notEnumerableProp(e,"__isPromisified__",!0),i[o]=e}}return z.toFastProperties(i),i}function g(i,c,z0){return b(i,c,void 0,i,null,z0)}$.promisify=function(i,c){if(typeof i!=="function")throw new G("expecting a function but got "+z.classString(i));if(w(i))return i;c=Object(c);var z0=c.context===void 0?U:c.context,k=!!c.multiArgs,d=g(i,z0,k);return z.copyDescriptors(i,d,V),d},$.promisifyAll=function(i,c){if(typeof i!=="function"&&typeof i!=="object")throw new G(`the target of promisifyAll must be an object or a function
`.replace("[CodeForSwitchCase]",R()).replace("[GetFunctionCode]",o);return e=e.replace("Parameters",B($0)),Function("Promise","fn","receiver","withAppended","maybeWrapAsError","nodebackForPromise","tryCatch","errorObj","notEnumerableProp","INTERNAL",e)($,k,c,J,K,Q,I.tryCatch,I.errorObj,I.notEnumerableProp,Y)};function C(i,c,I0,k,p,a){var $0=function(){return this}(),y=i;if(typeof y==="string")i=k;function d(){var Y0=c;if(c===U)Y0=this;var R=new $(Y);R._captureStackTrace();var o=typeof y==="string"&&this!==$0?this[y]:i,e=Q(R,a);try{o.apply(Y0,J(arguments,e))}catch(O0){R._rejectCallback(K(O0),!0,!0)}if(!R._isFateSealed())R._setAsyncGuaranteed();return R}return I.notEnumerableProp(d,"__isPromisified__",!0),d}var b=z?D:C;function x(i,c,I0,k,p){var a=new RegExp(O(c)+"$"),$0=N(i,c,a,I0);for(var y=0,d=$0.length;y<d;y+=2){var Y0=$0[y],R=$0[y+1],o=Y0+c;if(k===b)i[o]=b(Y0,U,Y0,R,c,p);else{var e=k(R,function(){return b(Y0,U,Y0,R,c,p)});I.notEnumerableProp(e,"__isPromisified__",!0),i[o]=e}}return I.toFastProperties(i),i}function g(i,c,I0){return b(i,c,void 0,i,null,I0)}$.promisify=function(i,c){if(typeof i!=="function")throw new G("expecting a function but got "+I.classString(i));if(w(i))return i;c=Object(c);var I0=c.context===void 0?U:c.context,k=!!c.multiArgs,p=g(i,I0,k);return I.copyDescriptors(i,p,V),p},$.promisifyAll=function(i,c){if(typeof i!=="function"&&typeof i!=="object")throw new G(`the target of promisifyAll must be an object or a function
See http://goo.gl/MqrFmX
`);c=Object(c);var z0=!!c.multiArgs,k=c.suffix;if(typeof k!=="string")k=H;var d=c.filter;if(typeof d!=="function")d=q;var a=c.promisifier;if(typeof a!=="function")a=b;if(!z.isIdentifier(k))throw RangeError(`suffix must be a valid identifier
`);c=Object(c);var I0=!!c.multiArgs,k=c.suffix;if(typeof k!=="string")k=H;var p=c.filter;if(typeof p!=="function")p=q;var a=c.promisifier;if(typeof a!=="function")a=b;if(!I.isIdentifier(k))throw RangeError(`suffix must be a valid identifier
See http://goo.gl/MqrFmX
`);var $0=z.inheritedDataKeys(i);for(var y=0;y<$0.length;++y){var p=i[$0[y]];if($0[y]!=="constructor"&&z.isClass(p))x(p.prototype,k,d,a,z0),x(p,k,d,a,z0)}return x(i,k,d,a,z0)}}});var aw0=E((ve1,sw0)=>{sw0.exports=function($,Y,U,z){var I=w4(),Q=I.isObject,J=aU(),K;if(typeof Map==="function")K=Map;var G=function(){var Z=0,q=0;function V(w,M){this[Z]=w,this[Z+q]=M,Z++}return function(M){q=M.size,Z=0;var F=Array(M.size*2);return M.forEach(V,F),F}}(),H=function(Z){var q=new K,V=Z.length/2|0;for(var w=0;w<V;++w){var M=Z[V+w],F=Z[w];q.set(M,F)}return q};function W(Z){var q=!1,V;if(K!==void 0&&Z instanceof K)V=G(Z),q=!0;else{var w=J.keys(Z),M=w.length;V=Array(M*2);for(var F=0;F<M;++F){var N=w[F];V[F]=Z[N],V[F+M]=N}}this.constructor$(V),this._isMap=q,this._init$(void 0,-3)}I.inherits(W,Y),W.prototype._init=function(){},W.prototype._promiseFulfilled=function(Z,q){this._values[q]=Z;var V=++this._totalResolved;if(V>=this._length){var w;if(this._isMap)w=H(this._values);else{w={};var M=this.length();for(var F=0,N=this.length();F<N;++F)w[this._values[F+M]]=this._values[F]}return this._resolve(w),!0}return!1},W.prototype.shouldCopyValues=function(){return!1},W.prototype.getActualLength=function(Z){return Z>>1};function X(Z){var q,V=U(Z);if(!Q(V))return z(`cannot await properties of a non-object
`);var $0=I.inheritedDataKeys(i);for(var y=0;y<$0.length;++y){var d=i[$0[y]];if($0[y]!=="constructor"&&I.isClass(d))x(d.prototype,k,p,a,I0),x(d,k,p,a,I0)}return x(i,k,p,a,I0)}}});var ZM0=j((s04,XM0)=>{XM0.exports=function($,Y,U,I){var Q=M4(),J=Q.isObject,K=tU(),z;if(typeof Map==="function")z=Map;var G=function(){var Z=0,q=0;function V(w,M){this[Z]=w,this[Z+q]=M,Z++}return function(M){q=M.size,Z=0;var F=Array(M.size*2);return M.forEach(V,F),F}}(),H=function(Z){var q=new z,V=Z.length/2|0;for(var w=0;w<V;++w){var M=Z[V+w],F=Z[w];q.set(M,F)}return q};function W(Z){var q=!1,V;if(z!==void 0&&Z instanceof z)V=G(Z),q=!0;else{var w=K.keys(Z),M=w.length;V=Array(M*2);for(var F=0;F<M;++F){var N=w[F];V[F]=Z[N],V[F+M]=N}}this.constructor$(V),this._isMap=q,this._init$(void 0,-3)}Q.inherits(W,Y),W.prototype._init=function(){},W.prototype._promiseFulfilled=function(Z,q){this._values[q]=Z;var V=++this._totalResolved;if(V>=this._length){var w;if(this._isMap)w=H(this._values);else{w={};var M=this.length();for(var F=0,N=this.length();F<N;++F)w[this._values[F+M]]=this._values[F]}return this._resolve(w),!0}return!1},W.prototype.shouldCopyValues=function(){return!1},W.prototype.getActualLength=function(Z){return Z>>1};function X(Z){var q,V=U(Z);if(!J(V))return I(`cannot await properties of a non-object
See http://goo.gl/MqrFmX
`);else if(V instanceof $)q=V._then($.props,void 0,void 0,void 0,void 0);else q=new W(V).promise();if(V instanceof $)q._propagateFrom(V,2);return q}$.prototype.props=function(){return X(this)},$.props=function(Z){return X(Z)}}});var ew0=E((he1,tw0)=>{tw0.exports=function($,Y,U,z){var I=w4(),Q=function(K){return K.then(function(G){return J(G,K)})};function J(K,G){var H=U(K);if(H instanceof $)return Q(H);else if(K=I.asArray(K),K===null)return z("expecting an array or an iterable object but got "+I.classString(K));var W=new $(Y);if(G!==void 0)W._propagateFrom(G,3);var{_fulfill:X,_reject:Z}=W;for(var q=0,V=K.length;q<V;++q){var w=K[q];if(w===void 0&&!(q in K))continue;$.cast(w)._then(X,Z,void 0,W,null)}return W}$.race=function(K){return J(K,void 0)},$.prototype.race=function(){return J(this,void 0)}}});var YM0=E((Se1,$M0)=>{$M0.exports=function($,Y,U,z,I,Q){var J=$._getDomain,K=w4(),G=K.tryCatch;function H(V,w,M,F){this.constructor$(V);var N=J();if(this._fn=N===null?w:K.domainBind(N,w),M!==void 0)M=$.resolve(M),M._attachCancellationCallback(this);if(this._initialValue=M,this._currentCancellable=null,F===I)this._eachValues=Array(this._length);else if(F===0)this._eachValues=null;else this._eachValues=void 0;this._promise._captureStackTrace(),this._init$(void 0,-5)}K.inherits(H,Y),H.prototype._gotAccum=function(V){if(this._eachValues!==void 0&&this._eachValues!==null&&V!==I)this._eachValues.push(V)},H.prototype._eachComplete=function(V){if(this._eachValues!==null)this._eachValues.push(V);return this._eachValues},H.prototype._init=function(){},H.prototype._resolveEmptyArray=function(){this._resolve(this._eachValues!==void 0?this._eachValues:this._initialValue)},H.prototype.shouldCopyValues=function(){return!1},H.prototype._resolve=function(V){this._promise._resolveCallback(V),this._values=null},H.prototype._resultCancelled=function(V){if(V===this._initialValue)return this._cancel();if(this._isResolved())return;if(this._resultCancelled$(),this._currentCancellable instanceof $)this._currentCancellable.cancel();if(this._initialValue instanceof $)this._initialValue.cancel()},H.prototype._iterate=function(V){this._values=V;var w,M,F=V.length;if(this._initialValue!==void 0)w=this._initialValue,M=0;else w=$.resolve(V[0]),M=1;if(this._currentCancellable=w,!w.isRejected())for(;M<F;++M){var N={accum:null,value:V[M],index:M,length:F,array:this};w=w._then(Z,void 0,void 0,N,void 0)}if(this._eachValues!==void 0)w=w._then(this._eachComplete,void 0,void 0,this,void 0);w._then(W,W,void 0,w,this)},$.prototype.reduce=function(V,w){return X(this,V,w,null)},$.reduce=function(V,w,M,F){return X(V,w,M,F)};function W(V,w){if(this.isFulfilled())w._resolve(V);else w._reject(V)}function X(V,w,M,F){if(typeof w!=="function")return U("expecting a function but got "+K.classString(w));var N=new H(V,w,M,F);return N.promise()}function Z(V){this.accum=V,this.array._gotAccum(V);var w=z(this.value,this.array._promise);if(w instanceof $)return this.array._currentCancellable=w,w._then(q,void 0,void 0,this,void 0);else return q.call(this,w)}function q(V){var w=this.array,M=w._promise,F=G(w._fn);M._pushContext();var N;if(w._eachValues!==void 0)N=F.call(M._boundValue(),V,this.index,this.length);else N=F.call(M._boundValue(),this.accum,V,this.index,this.length);if(N instanceof $)w._currentCancellable=N;var O=M._popContext();return Q.checkForgottenReturns(N,O,w._eachValues!==void 0?"Promise.each":"Promise.reduce",M),N}}});var zM0=E((ge1,UM0)=>{UM0.exports=function($,Y,U){var z=$.PromiseInspection,I=w4();function Q(J){this.constructor$(J)}I.inherits(Q,Y),Q.prototype._promiseResolved=function(J,K){this._values[J]=K;var G=++this._totalResolved;if(G>=this._length)return this._resolve(this._values),!0;return!1},Q.prototype._promiseFulfilled=function(J,K){var G=new z;return G._bitField=33554432,G._settledValueField=J,this._promiseResolved(K,G)},Q.prototype._promiseRejected=function(J,K){var G=new z;return G._bitField=16777216,G._settledValueField=J,this._promiseResolved(K,G)},$.settle=function(J){return U.deprecated(".settle()",".reflect()"),new Q(J).promise()},$.prototype.settle=function(){return $.settle(this)}}});var QM0=E((ye1,IM0)=>{IM0.exports=function($,Y,U){var z=w4(),I=_3().RangeError,Q=_3().AggregateError,J=z.isArray,K={};function G(W){this.constructor$(W),this._howMany=0,this._unwrap=!1,this._initialized=!1}z.inherits(G,Y),G.prototype._init=function(){if(!this._initialized)return;if(this._howMany===0){this._resolve([]);return}this._init$(void 0,-5);var W=J(this._values);if(!this._isResolved()&&W&&this._howMany>this._canPossiblyFulfill())this._reject(this._getRangeError(this.length()))},G.prototype.init=function(){this._initialized=!0,this._init()},G.prototype.setUnwrap=function(){this._unwrap=!0},G.prototype.howMany=function(){return this._howMany},G.prototype.setHowMany=function(W){this._howMany=W},G.prototype._promiseFulfilled=function(W){if(this._addFulfilled(W),this._fulfilled()===this.howMany()){if(this._values.length=this.howMany(),this.howMany()= Line truncated
`);else if(V instanceof $)q=V._then($.props,void 0,void 0,void 0,void 0);else q=new W(V).promise();if(V instanceof $)q._propagateFrom(V,2);return q}$.prototype.props=function(){return X(this)},$.props=function(Z){return X(Z)}}});var VM0=j((a04,qM0)=>{qM0.exports=function($,Y,U,I){var Q=M4(),J=function(z){return z.then(function(G){return K(G,z)})};function K(z,G){var H=U(z);if(H instanceof $)return J(H);else if(z=Q.asArray(z),z===null)return I("expecting an array or an iterable object but got "+Q.classString(z));var W=new $(Y);if(G!==void 0)W._propagateFrom(G,3);var{_fulfill:X,_reject:Z}=W;for(var q=0,V=z.length;q<V;++q){var w=z[q];if(w===void 0&&!(q in z))continue;$.cast(w)._then(X,Z,void 0,W,null)}return W}$.race=function(z){return K(z,void 0)},$.prototype.race=function(){return K(this,void 0)}}});var FM0=j((t04,LM0)=>{LM0.exports=function($,Y,U,I,Q,J){var K=$._getDomain,z=M4(),G=z.tryCatch;function H(V,w,M,F){this.constructor$(V);var N=K();if(this._fn=N===null?w:z.domainBind(N,w),M!==void 0)M=$.resolve(M),M._attachCancellationCallback(this);if(this._initialValue=M,this._currentCancellable=null,F===Q)this._eachValues=Array(this._length);else if(F===0)this._eachValues=null;else this._eachValues=void 0;this._promise._captureStackTrace(),this._init$(void 0,-5)}z.inherits(H,Y),H.prototype._gotAccum=function(V){if(this._eachValues!==void 0&&this._eachValues!==null&&V!==Q)this._eachValues.push(V)},H.prototype._eachComplete=function(V){if(this._eachValues!==null)this._eachValues.push(V);return this._eachValues},H.prototype._init=function(){},H.prototype._resolveEmptyArray=function(){this._resolve(this._eachValues!==void 0?this._eachValues:this._initialValue)},H.prototype.shouldCopyValues=function(){return!1},H.prototype._resolve=function(V){this._promise._resolveCallback(V),this._values=null},H.prototype._resultCancelled=function(V){if(V===this._initialValue)return this._cancel();if(this._isResolved())return;if(this._resultCancelled$(),this._currentCancellable instanceof $)this._currentCancellable.cancel();if(this._initialValue instanceof $)this._initialValue.cancel()},H.prototype._iterate=function(V){this._values=V;var w,M,F=V.length;if(this._initialValue!==void 0)w=this._initialValue,M=0;else w=$.resolve(V[0]),M=1;if(this._currentCancellable=w,!w.isRejected())for(;M<F;++M){var N={accum:null,value:V[M],index:M,length:F,array:this};w=w._then(Z,void 0,void 0,N,void 0)}if(this._eachValues!==void 0)w=w._then(this._eachComplete,void 0,void 0,this,void 0);w._then(W,W,void 0,w,this)},$.prototype.reduce=function(V,w){return X(this,V,w,null)},$.reduce=function(V,w,M,F){return X(V,w,M,F)};function W(V,w){if(this.isFulfilled())w._resolve(V);else w._reject(V)}function X(V,w,M,F){if(typeof w!=="function")return U("expecting a function but got "+z.classString(w));var N=new H(V,w,M,F);return N.promise()}function Z(V){this.accum=V,this.array._gotAccum(V);var w=I(this.value,this.array._promise);if(w instanceof $)return this.array._currentCancellable=w,w._then(q,void 0,void 0,this,void 0);else return q.call(this,w)}function q(V){var w=this.array,M=w._promise,F=G(w._fn);M._pushContext();var N;if(w._eachValues!==void 0)N=F.call(M._boundValue(),V,this.index,this.length);else N=F.call(M._boundValue(),this.accum,V,this.index,this.length);if(N instanceof $)w._currentCancellable=N;var O=M._popContext();return J.checkForgottenReturns(N,O,w._eachValues!==void 0?"Promise.each":"Promise.reduce",M),N}}});var MM0=j((e04,wM0)=>{wM0.exports=function($,Y,U){var I=$.PromiseInspection,Q=M4();function J(K){this.constructor$(K)}Q.inherits(J,Y),J.prototype._promiseResolved=function(K,z){this._values[K]=z;var G=++this._totalResolved;if(G>=this._length)return this._resolve(this._values),!0;return!1},J.prototype._promiseFulfilled=function(K,z){var G=new I;return G._bitField=33554432,G._settledValueField=K,this._promiseResolved(z,G)},J.prototype._promiseRejected=function(K,z){var G=new I;return G._bitField=16777216,G._settledValueField=K,this._promiseResolved(z,G)},$.settle=function(K){return U.deprecated(".settle()",".reflect()"),new J(K).promise()},$.prototype.settle=function(){return $.settle(this)}}});var NM0=j(($14,OM0)=>{OM0.exports=function($,Y,U){var I=M4(),Q=h3().RangeError,J=h3().AggregateError,K=I.isArray,z={};function G(W){this.constructor$(W),this._howMany=0,this._unwrap=!1,this._initialized=!1}I.inherits(G,Y),G.prototype._init=function(){if(!this._initialized)return;if(this._howMany===0){this._resolve([]);return}this._init$(void 0,-5);var W=K(this._values);if(!this._isResolved()&&W&&this._howMany>this._canPossiblyFulfill())this._reject(this._getRangeError(this.length()))},G.prototype.init=function(){this._initialized=!0,this._init()},G.prototype.setUnwrap=function(){this._unwrap=!0},G.prototype.howMany=function(){return this._howMany},G.prototype.setHowMany=function(W){this._howMany=W},G.prototype._promiseFulfilled=function(W){if(this._addFulfilled(W),this._fulfilled()===this.howMany()){if(this._values.length=this.howMany(),this.howMany()= Line truncated
See http://goo.gl/MqrFmX
`);var Z=new G(W),q=Z.promise();return Z.setHowMany(X),Z.init(),q}$.some=function(W,X){return H(W,X)},$.prototype.some=function(W){return H(this,W)},$._SomePromiseArray=G}});var KM0=E((ke1,JM0)=>{JM0.exports=function($,Y){var U=$.map;$.prototype.filter=function(z,I){return U(this,z,I,Y)},$.filter=function(z,I,Q){return U(z,I,Q,Y)}}});var HM0=E((xe1,GM0)=>{GM0.exports=function($,Y){var{reduce:U,all:z}=$;function I(){return z(this)}function Q(J,K){return U(J,K,Y,Y)}$.prototype.each=function(J){return U(this,J,Y,0)._then(I,void 0,void 0,this,void 0)},$.prototype.mapSeries=function(J){return U(this,J,Y,Y)},$.each=function(J,K){return U(J,K,Y,0)._then(I,void 0,void 0,J,void 0)},$.mapSeries=Q}});var XM0=E((fe1,WM0)=>{WM0.exports=function($){var Y=$._SomePromiseArray;function U(z){var I=new Y(z),Q=I.promise();return I.setHowMany(1),I.setUnwrap(),I.init(),Q}$.any=function(z){return U(z)},$.prototype.any=function(){return U(this)}}});var ZM0=E((ue1,yc)=>{yc.exports=function(){var $=function(){return new X(`circular promise resolution chain
`);var Z=new G(W),q=Z.promise();return Z.setHowMany(X),Z.init(),q}$.some=function(W,X){return H(W,X)},$.prototype.some=function(W){return H(this,W)},$._SomePromiseArray=G}});var BM0=j((Y14,DM0)=>{DM0.exports=function($,Y){var U=$.map;$.prototype.filter=function(I,Q){return U(this,I,Q,Y)},$.filter=function(I,Q,J){return U(I,Q,J,Y)}}});var PM0=j((U14,AM0)=>{AM0.exports=function($,Y){var{reduce:U,all:I}=$;function Q(){return I(this)}function J(K,z){return U(K,z,Y,Y)}$.prototype.each=function(K){return U(this,K,Y,0)._then(Q,void 0,void 0,this,void 0)},$.prototype.mapSeries=function(K){return U(this,K,Y,Y)},$.each=function(K,z){return U(K,z,Y,0)._then(Q,void 0,void 0,K,void 0)},$.mapSeries=J}});var EM0=j((I14,TM0)=>{TM0.exports=function($){var Y=$._SomePromiseArray;function U(I){var Q=new Y(I),J=Q.promise();return Q.setHowMany(1),Q.setUnwrap(),Q.init(),J}$.any=function(I){return U(I)},$.prototype.any=function(){return U(this)}}});var jM0=j((Q14,bc)=>{bc.exports=function(){var $=function(){return new X(`circular promise resolution chain
See http://goo.gl/MqrFmX
`)},Y=function(){return new g.PromiseInspection(this._target())},U=function(k){return g.reject(new X(k))};function z(){}var I={},Q=w4(),J;if(Q.isNode)J=function(){var k=process.domain;if(k===void 0)k=null;return k};else J=function(){return null};Q.notEnumerableProp(g,"_getDomain",J);var K=aU(),G=Qw0(),H=new G;K.defineProperty(g,"_async",{value:H});var W=_3(),X=g.TypeError=W.TypeError;g.RangeError=W.RangeError;var Z=g.CancellationError=W.CancellationError;g.TimeoutError=W.TimeoutError,g.OperationalError=W.OperationalError,g.RejectionError=W.OperationalError,g.AggregateError=W.AggregateError;var q=function(){},V={},w={},M=Ww0()(g,q),F=Zw0()(g,q,M,U,z),N=Vw0()(g),O=N.create,D=Fw0()(g,N),P=D.CapturedTrace,T=Mw0()(g,M),A=Nw0()(w),j=Sc(),C=Q.errorObj,b=Q.tryCatch;function x(k,d){if(typeof d!=="function")throw new X("expecting a function but got "+Q.classString(d));if(k.constructor!==g)throw new X(`the promise constructor cannot be invoked directly
`)},Y=function(){return new g.PromiseInspection(this._target())},U=function(k){return g.reject(new X(k))};function I(){}var Q={},J=M4(),K;if(J.isNode)K=function(){var k=process.domain;if(k===void 0)k=null;return k};else K=function(){return null};J.notEnumerableProp(g,"_getDomain",K);var z=tU(),G=Nw0(),H=new G;z.defineProperty(g,"_async",{value:H});var W=h3(),X=g.TypeError=W.TypeError;g.RangeError=W.RangeError;var Z=g.CancellationError=W.CancellationError;g.TimeoutError=W.TimeoutError,g.OperationalError=W.OperationalError,g.RejectionError=W.OperationalError,g.AggregateError=W.AggregateError;var q=function(){},V={},w={},M=Tw0()(g,q),F=jw0()(g,q,M,U,I),N=Rw0()(g),O=N.create,D=vw0()(g,N),P=D.CapturedTrace,T=hw0()(g,M),B=yw0()(w),E=fc(),C=J.errorObj,b=J.tryCatch;function x(k,p){if(typeof p!=="function")throw new X("expecting a function but got "+J.classString(p));if(k.constructor!==g)throw new X(`the promise constructor cannot be invoked directly
See http://goo.gl/MqrFmX
`)}function g(k){if(this._bitField=0,this._fulfillmentHandler0=void 0,this._rejectionHandler0=void 0,this._promise0=void 0,this._receiver0=void 0,k!==q)x(this,k),this._resolveFromExecutor(k);this._promiseCreated(),this._fireEvent("promiseCreated",this)}g.prototype.toString=function(){return"[object Promise]"},g.prototype.caught=g.prototype.catch=function(k){var d=arguments.length;if(d>1){var a=Array(d-1),$0=0,y;for(y=0;y<d-1;++y){var p=arguments[y];if(Q.isObject(p))a[$0++]=p;else return U("expecting an object but got A catch statement predicate "+Q.classString(p))}return a.length=$0,k=arguments[y],this.then(void 0,A(a,k,this))}return this.then(void 0,k)},g.prototype.reflect=function(){return this._then(Y,Y,void 0,this,void 0)},g.prototype.then=function(k,d){if(D.warnings()&&arguments.length>0&&typeof k!=="function"&&typeof d!=="function"){var a=".then() only accepts functions but was passed: "+Q.classString(k);if(arguments.length>1)a+=", "+Q.classString(d);this._warn(a)}return this._then(k,d,void 0,void 0,void 0)},g.prototype.done=function(k,d){var a=this._then(k,d,void 0,void 0,void 0);a._setIsFinal()},g.prototype.spread=function(k){if(typeof k!=="function")return U("expecting a function but got "+Q.classString(k));return this.all()._then(k,void 0,void 0,V,void 0)},g.prototype.toJSON=function(){var k={isFulfilled:!1,isRejected:!1,fulfillmentValue:void 0,rejectionReason:void 0};if(this.isFulfilled())k.fulfillmentValue=this.value(),k.isFulfilled=!0;else if(this.isRejected())k.rejectionReason=this.reason(),k.isRejected=!0;return k},g.prototype.all=function(){if(arguments.length>0)this._warn(".all() was passed arguments but it does not take any");return new F(this).promise()},g.prototype.error=function(k){return this.caught(Q.originatesFromRejection,k)},g.getNewLibraryCopy=yc.exports,g.is=function(k){return k instanceof g},g.fromNode=g.fromCallback=function(k){var d=new g(q);d._captureStackTrace();var a=arguments.length>1?!!Object(arguments[1]).multiArgs:!1,$0=b(k)(j(d,a));if($0===C)d._rejectCallback($0.e,!0);if(!d._isFateSealed())d._setAsyncGuaranteed();return d},g.all=function(k){return new F(k).promise()},g.cast=function(k){var d=M(k);if(!(d instanceof g))d=new g(q),d._captureStackTrace(),d._setFulfilled(),d._rejectionHandler0=k;return d},g.resolve=g.fulfilled=g.cast,g.reject=g.rejected=function(k){var d=new g(q);return d._captureStackTrace(),d._rejectCallback(k,!0),d},g.setScheduler=function(k){if(typeof k!=="function")throw new X("expecting a function but got "+Q.classString(k));return H.setScheduler(k)},g.prototype._then=function(k,d,a,$0,y){var p=y!==void 0,Y0=p?y:new g(q),R=this._target(),o=R._bitField;if(!p){if(Y0._propagateFrom(this,3),Y0._captureStackTrace(),$0===void 0&&(this._bitField&2097152)!==0)if((o&50397184)!==0)$0=this._boundValue();else $0=R===this?void 0:this._boundTo;this._fireEvent("promiseChained",this,Y0)}var e=J();if((o&50397184)!==0){var O0,T0,y0=R._settlePromiseCtx;if((o&33554432)!==0)T0=R._rejectionHandler0,O0=k;else if((o&16777216)!==0)T0=R._fulfillmentHandler0,O0=d,R._unsetRejectionIsUnhandled();else y0=R._settlePromiseLateCancellationObserver,T0=new Z("late cancellation observer"),R._attachExtraTrace(T0),O0=d;H.invoke(y0,R,{handler:e===null?O0:typeof O0==="function"&&Q.domainBind(e,O0),promise:Y0,receiver:$0,value:T0})}else R._addCallbacks(k,d,Y0,$0,e);return Y0},g.prototype._length=function(){return this._bitField&65535},g.prototype._isFateSealed=function(){return(this._bitField&117506048)!==0},g.prototype._isFollowing=function(){return(this._bitField&67108864)===67108864},g.prototype._setLength=function(k){this._bitField=this._bitField&-65536|k&65535},g.prototype._setFulfilled=function(){this._bitField=this._bitField|33554432,this._fireEvent("promiseFulfilled",this)},g.prototype._setRejected=function(){this._bitField=this._bitField|16777216,this._fireEvent("promiseRejected",this)},g.prototype._setFollowing=function(){this._bitField=this._bitField|67108864,this._fireEvent("promiseResolved",this)},g.prototype._setIsFinal=function(){this._bitField=this._bitField|4194304},g.prototype._isFinal=function(){return(this._bitField&4194304)>0},g.prototype._unsetCancelled=function(){this._bitField=this._bitField&-65537},g.prototype._setCancelled=function(){this._bitField=this._bitField|65536,this._fireEvent("promiseCancelled",this)},g.prototype._setWillBeCancelled=function(){this._bitField=this._bitField|8388608},g.prototype._setAsyncGuaranteed=function(){if(H.hasCustomScheduler())return;this._bitField=this._bitField|134217728},g.prototype._receiverAt=function(k){var d=k===0?this._receiver0:this[k*4-4+3];if(d===I)return;else if(d===void 0&&this._isBound())return this._boundValue();return d},g.prototype._promiseAt=function(k){return this[k*4-4+2]},g.prototype._fulfillmentHandlerAt=function(k){return this[k*4-4+0]},g.prototype._rejectionHandlerAt=function(k){return this[k*4-4+1]},g.prototype._boundValue=function(){},g.prototype._migrateCallback0=function(k){var{_bitField:d,_fulfillmentHand Line truncated
`)}function g(k){if(this._bitField=0,this._fulfillmentHandler0=void 0,this._rejectionHandler0=void 0,this._promise0=void 0,this._receiver0=void 0,k!==q)x(this,k),this._resolveFromExecutor(k);this._promiseCreated(),this._fireEvent("promiseCreated",this)}g.prototype.toString=function(){return"[object Promise]"},g.prototype.caught=g.prototype.catch=function(k){var p=arguments.length;if(p>1){var a=Array(p-1),$0=0,y;for(y=0;y<p-1;++y){var d=arguments[y];if(J.isObject(d))a[$0++]=d;else return U("expecting an object but got A catch statement predicate "+J.classString(d))}return a.length=$0,k=arguments[y],this.then(void 0,B(a,k,this))}return this.then(void 0,k)},g.prototype.reflect=function(){return this._then(Y,Y,void 0,this,void 0)},g.prototype.then=function(k,p){if(D.warnings()&&arguments.length>0&&typeof k!=="function"&&typeof p!=="function"){var a=".then() only accepts functions but was passed: "+J.classString(k);if(arguments.length>1)a+=", "+J.classString(p);this._warn(a)}return this._then(k,p,void 0,void 0,void 0)},g.prototype.done=function(k,p){var a=this._then(k,p,void 0,void 0,void 0);a._setIsFinal()},g.prototype.spread=function(k){if(typeof k!=="function")return U("expecting a function but got "+J.classString(k));return this.all()._then(k,void 0,void 0,V,void 0)},g.prototype.toJSON=function(){var k={isFulfilled:!1,isRejected:!1,fulfillmentValue:void 0,rejectionReason:void 0};if(this.isFulfilled())k.fulfillmentValue=this.value(),k.isFulfilled=!0;else if(this.isRejected())k.rejectionReason=this.reason(),k.isRejected=!0;return k},g.prototype.all=function(){if(arguments.length>0)this._warn(".all() was passed arguments but it does not take any");return new F(this).promise()},g.prototype.error=function(k){return this.caught(J.originatesFromRejection,k)},g.getNewLibraryCopy=bc.exports,g.is=function(k){return k instanceof g},g.fromNode=g.fromCallback=function(k){var p=new g(q);p._captureStackTrace();var a=arguments.length>1?!!Object(arguments[1]).multiArgs:!1,$0=b(k)(E(p,a));if($0===C)p._rejectCallback($0.e,!0);if(!p._isFateSealed())p._setAsyncGuaranteed();return p},g.all=function(k){return new F(k).promise()},g.cast=function(k){var p=M(k);if(!(p instanceof g))p=new g(q),p._captureStackTrace(),p._setFulfilled(),p._rejectionHandler0=k;return p},g.resolve=g.fulfilled=g.cast,g.reject=g.rejected=function(k){var p=new g(q);return p._captureStackTrace(),p._rejectCallback(k,!0),p},g.setScheduler=function(k){if(typeof k!=="function")throw new X("expecting a function but got "+J.classString(k));return H.setScheduler(k)},g.prototype._then=function(k,p,a,$0,y){var d=y!==void 0,Y0=d?y:new g(q),R=this._target(),o=R._bitField;if(!d){if(Y0._propagateFrom(this,3),Y0._captureStackTrace(),$0===void 0&&(this._bitField&2097152)!==0)if((o&50397184)!==0)$0=this._boundValue();else $0=R===this?void 0:this._boundTo;this._fireEvent("promiseChained",this,Y0)}var e=K();if((o&50397184)!==0){var O0,T0,y0=R._settlePromiseCtx;if((o&33554432)!==0)T0=R._rejectionHandler0,O0=k;else if((o&16777216)!==0)T0=R._fulfillmentHandler0,O0=p,R._unsetRejectionIsUnhandled();else y0=R._settlePromiseLateCancellationObserver,T0=new Z("late cancellation observer"),R._attachExtraTrace(T0),O0=p;H.invoke(y0,R,{handler:e===null?O0:typeof O0==="function"&&J.domainBind(e,O0),promise:Y0,receiver:$0,value:T0})}else R._addCallbacks(k,p,Y0,$0,e);return Y0},g.prototype._length=function(){return this._bitField&65535},g.prototype._isFateSealed=function(){return(this._bitField&117506048)!==0},g.prototype._isFollowing=function(){return(this._bitField&67108864)===67108864},g.prototype._setLength=function(k){this._bitField=this._bitField&-65536|k&65535},g.prototype._setFulfilled=function(){this._bitField=this._bitField|33554432,this._fireEvent("promiseFulfilled",this)},g.prototype._setRejected=function(){this._bitField=this._bitField|16777216,this._fireEvent("promiseRejected",this)},g.prototype._setFollowing=function(){this._bitField=this._bitField|67108864,this._fireEvent("promiseResolved",this)},g.prototype._setIsFinal=function(){this._bitField=this._bitField|4194304},g.prototype._isFinal=function(){return(this._bitField&4194304)>0},g.prototype._unsetCancelled=function(){this._bitField=this._bitField&-65537},g.prototype._setCancelled=function(){this._bitField=this._bitField|65536,this._fireEvent("promiseCancelled",this)},g.prototype._setWillBeCancelled=function(){this._bitField=this._bitField|8388608},g.prototype._setAsyncGuaranteed=function(){if(H.hasCustomScheduler())return;this._bitField=this._bitField|134217728},g.prototype._receiverAt=function(k){var p=k===0?this._receiver0:this[k*4-4+3];if(p===Q)return;else if(p===void 0&&this._isBound())return this._boundValue();return p},g.prototype._promiseAt=function(k){return this[k*4-4+2]},g.prototype._fulfillmentHandlerAt=function(k){return this[k*4-4+0]},g.prototype._rejectionHandlerAt=function(k){return this[k*4-4+1]},g.prototype._boundValue=function(){},g.prototype._migrateCallback0=function(k){var{_bitField:p,_fulfillmentHand Line truncated
path = %s
syscall = %s
fstream_type = %s
@@ -294,31 +294,31 @@ fstream_unc_path = %s
fstream_class = %s
fstream_stack =
%s
`,Y||"UNKNOWN",z.stack,z.path,z.syscall,z.fstream_type,z.fstream_path,z.fstream_unc_path,z.fstream_class,z.fstream_stack.join(`
`));else U.emit("warn",z)};g2.prototype.info=function($,Y){this.emit("info",$,Y)};g2.prototype.error=function($,Y,U){var z=dO0($,Y,this);if(U)throw z;else this.emit("error",z)};function dO0($,Y,U){if(!($ instanceof Error))$=Error($);if($.code=$.code||Y,$.path=$.path||U.path,$.fstream_type=$.fstream_type||U.type,$.fstream_path=$.fstream_path||U.path,U._path!==U.path)$.fstream_unc_path=$.fstream_unc_path||U._path;if(U.linkpath)$.fstream_linkpath=$.fstream_linkpath||U.linkpath;return $.fstream_class=$.fstream_class||U.constructor.name,$.fstream_stack=$.fstream_stack||Error().stack.split(/\n/).slice(3).map(function(z){return z.replace(/^ {4}at /,"")}),$}});var FZ=E((L04,lO0)=>{lO0.exports=NM1;function NM1($){var Y=["Directory","File","SymbolicLink","Link","BlockDevice","CharacterDevice","FIFO","Socket"],U;if($.type&&Y.indexOf($.type)!==-1)return $[$.type]=!0,$.type;for(var z=0,I=Y.length;z<I;z++){U=Y[z];var Q=$[U]||$["is"+U];if(typeof Q==="function")Q=Q.call($);if(Q)return $[U]=!0,$.type=U,U}return null}});var Dn=E((F04,oO0)=>{oO0.exports=wZ;var DM1=r8(),AM1=W1(),Nn=Jz();AM1(wZ,Nn);function wZ($){var Y=this;if(!(Y instanceof wZ))throw Error("LinkReader must be called as constructor.");if(!($.type==="Link"&&$.Link||$.type==="SymbolicLink"&&$.SymbolicLink))throw Error("Non-link type "+$.type);Nn.call(Y,$)}wZ.prototype._stat=function($){var Y=this;DM1.readlink(Y._path,function(U,z){if(U)return Y.error(U);Y.linkpath=Y.props.linkpath=z,Y.emit("linkpath",z),Nn.prototype._stat.call(Y,$)})};wZ.prototype._read=function(){var $=this;if($._paused)return;if(!$._ended)$.emit("end"),$.emit("close"),$._ended=!0}});var Bn=E((w04,aO0)=>{aO0.exports=B9;var sO0=r8(),BM1=W1(),MZ=J0("path"),An=Jz(),rO0=J0("assert").ok;BM1(B9,An);function B9($){var Y=this;if(!(Y instanceof B9))throw Error("DirReader must be called as constructor.");if($.type!=="Directory"||!$.Directory)throw Error("Non-directory type "+$.type);if(Y.entries=null,Y._index=-1,Y._paused=!1,Y._length=-1,$.sort)this.sort=$.sort;An.call(this,$)}B9.prototype._getEntries=function(){var $=this;if($._gotEntries)return;$._gotEntries=!0,sO0.readdir($._path,function(Y,U){if(Y)return $.error(Y);if($.entries=U,$.emit("entries",U),$._paused)$.once("resume",z);else z();function z(){if($._length=$.entries.length,typeof $.sort==="function")$.entries=$.entries.sort($.sort.bind($));$._read()}})};B9.prototype._read=function(){var $=this;if(!$.entries)return $._getEntries();if($._paused||$._currentEntry||$._aborted)return;if($._index++,$._index>=$.entries.length){if(!$._ended)$._ended=!0,$.emit("end"),$.emit("close");return}var Y=MZ.resolve($._path,$.entries[$._index]);rO0(Y!==$._path),rO0($.entries[$._index]),$._currentEntry=Y,sO0[$.props.follow?"stat":"lstat"](Y,function(U,z){if(U)return $.error(U);var I=$._proxy||$;z.path=Y,z.basename=MZ.basename(Y),z.dirname=MZ.dirname(Y);var Q=$.getChildProps.call(I,z);Q.path=Y,Q.basename=MZ.basename(Y),Q.dirname=MZ.dirname(Y);var J=An(Q,z);$._currentEntry=J,J.on("pause",function(H){if(!$._paused&&!J._disowned)$.pause(H)}),J.on("resume",function(H){if($._paused&&!J._disowned)$.resume(H)}),J.on("stat",function(H){if($.emit("_entryStat",J,H),J._aborted)return;if(J._paused)J.once("resume",function(){$.emit("entryStat",J,H)});else $.emit("entryStat",J,H)}),J.on("ready",function H(){if($._paused)return J.pause($),$.once("resume",H);if(J.type==="Socket")$.emit("socket",J);else $.emitEntry(J)});var K=!1;J.on("close",G),J.on("disown",G);function G(){if(K)return;if(K=!0,$.emit("childEnd",J),$.emit("entryEnd",J),$._currentEntry=null,!$._paused)$._read()}J.on("error",function(H){if(J._swallowErrors)$.warn(H),J.emit("end"),J.emit("close");else $.emit("error",H)}),["child","childEnd","warn"].forEach(function(H){J.on(H,$.emit.bind($,H))})})};B9.prototype.disown=function($){if($.emit("beforeDisown"),$._disowned=!0,$.parent=$.root=null,$===this._currentEntry)this._currentEntry=null;$.emit("disown")};B9.prototype.getChildProps=function(){return{depth:this.depth+1,root:this.root||this,parent:this,follow:this.follow,filter:this.filter,sort:this.props.sort,hardlinks:this.props.hardlinks}};B9.prototype.pause=function($){var Y=this;if(Y._paused)return;if($=$||Y,Y._paused=!0,Y._currentEntry&&Y._currentEntry.pause)Y._currentEntry.pause($);Y.emit("pause",$)};B9.prototype.resume=function($){var Y=this;if(!Y._paused)return;if($=$||Y,Y._paused=!1,Y.emit("resume",$),Y._paused)return;if(Y._currentEntry){if(Y._currentEntry.resume)Y._currentEntry.resume($)}else Y._read()};B9.prototype.emitEntry=function($){this.emit("entry",$),this.emit("child",$)}});var Pn=E((M04,YN0)=>{YN0.exports=Kz;var PM1=r8(),TM1=W1(),tO0=Jz(),eO0={EOF:!0},$N0={CLOSE:!0};TM1(Kz,tO0);function Kz($){var Y=this;if(!(Y instanceof Kz))throw Error("FileReader must be called as constructor.");if(!($.type==="Link"&&$.Link||$.type==="File"&&$.File))throw Error("Non-file type "+$.type);Y._buffer=[],Y._bytesEmitted=0,tO0.call(Y,$)}Kz.prototype._getStream=function(){var $=this,Y=$._stream=PM1.createReadStream($._path,$.p Line truncated
`,Y||"UNKNOWN",I.stack,I.path,I.syscall,I.fstream_type,I.fstream_path,I.fstream_unc_path,I.fstream_class,I.fstream_stack.join(`
`));else U.emit("warn",I)};k2.prototype.info=function($,Y){this.emit("info",$,Y)};k2.prototype.error=function($,Y,U){var I=KN0($,Y,this);if(U)throw I;else this.emit("error",I)};function KN0($,Y,U){if(!($ instanceof Error))$=Error($);if($.code=$.code||Y,$.path=$.path||U.path,$.fstream_type=$.fstream_type||U.type,$.fstream_path=$.fstream_path||U.path,U._path!==U.path)$.fstream_unc_path=$.fstream_unc_path||U._path;if(U.linkpath)$.fstream_linkpath=$.fstream_linkpath||U.linkpath;return $.fstream_class=$.fstream_class||U.constructor.name,$.fstream_stack=$.fstream_stack||Error().stack.split(/\n/).slice(3).map(function(I){return I.replace(/^ {4}at /,"")}),$}});var OZ=j((g14,GN0)=>{GN0.exports=WO1;function WO1($){var Y=["Directory","File","SymbolicLink","Link","BlockDevice","CharacterDevice","FIFO","Socket"],U;if($.type&&Y.indexOf($.type)!==-1)return $[$.type]=!0,$.type;for(var I=0,Q=Y.length;I<Q;I++){U=Y[I];var J=$[U]||$["is"+U];if(typeof J==="function")J=J.call($);if(J)return $[U]=!0,$.type=U,U}return null}});var En=j((y14,HN0)=>{HN0.exports=NZ;var XO1=t8(),ZO1=W1(),Tn=zI();ZO1(NZ,Tn);function NZ($){var Y=this;if(!(Y instanceof NZ))throw Error("LinkReader must be called as constructor.");if(!($.type==="Link"&&$.Link||$.type==="SymbolicLink"&&$.SymbolicLink))throw Error("Non-link type "+$.type);Tn.call(Y,$)}NZ.prototype._stat=function($){var Y=this;XO1.readlink(Y._path,function(U,I){if(U)return Y.error(U);Y.linkpath=Y.props.linkpath=I,Y.emit("linkpath",I),Tn.prototype._stat.call(Y,$)})};NZ.prototype._read=function(){var $=this;if($._paused)return;if(!$._ended)$.emit("end"),$.emit("close"),$._ended=!0}});var Cn=j((k14,ZN0)=>{ZN0.exports=T9;var XN0=t8(),qO1=W1(),DZ=K0("path"),jn=zI(),WN0=K0("assert").ok;qO1(T9,jn);function T9($){var Y=this;if(!(Y instanceof T9))throw Error("DirReader must be called as constructor.");if($.type!=="Directory"||!$.Directory)throw Error("Non-directory type "+$.type);if(Y.entries=null,Y._index=-1,Y._paused=!1,Y._length=-1,$.sort)this.sort=$.sort;jn.call(this,$)}T9.prototype._getEntries=function(){var $=this;if($._gotEntries)return;$._gotEntries=!0,XN0.readdir($._path,function(Y,U){if(Y)return $.error(Y);if($.entries=U,$.emit("entries",U),$._paused)$.once("resume",I);else I();function I(){if($._length=$.entries.length,typeof $.sort==="function")$.entries=$.entries.sort($.sort.bind($));$._read()}})};T9.prototype._read=function(){var $=this;if(!$.entries)return $._getEntries();if($._paused||$._currentEntry||$._aborted)return;if($._index++,$._index>=$.entries.length){if(!$._ended)$._ended=!0,$.emit("end"),$.emit("close");return}var Y=DZ.resolve($._path,$.entries[$._index]);WN0(Y!==$._path),WN0($.entries[$._index]),$._currentEntry=Y,XN0[$.props.follow?"stat":"lstat"](Y,function(U,I){if(U)return $.error(U);var Q=$._proxy||$;I.path=Y,I.basename=DZ.basename(Y),I.dirname=DZ.dirname(Y);var J=$.getChildProps.call(Q,I);J.path=Y,J.basename=DZ.basename(Y),J.dirname=DZ.dirname(Y);var K=jn(J,I);$._currentEntry=K,K.on("pause",function(H){if(!$._paused&&!K._disowned)$.pause(H)}),K.on("resume",function(H){if($._paused&&!K._disowned)$.resume(H)}),K.on("stat",function(H){if($.emit("_entryStat",K,H),K._aborted)return;if(K._paused)K.once("resume",function(){$.emit("entryStat",K,H)});else $.emit("entryStat",K,H)}),K.on("ready",function H(){if($._paused)return K.pause($),$.once("resume",H);if(K.type==="Socket")$.emit("socket",K);else $.emitEntry(K)});var z=!1;K.on("close",G),K.on("disown",G);function G(){if(z)return;if(z=!0,$.emit("childEnd",K),$.emit("entryEnd",K),$._currentEntry=null,!$._paused)$._read()}K.on("error",function(H){if(K._swallowErrors)$.warn(H),K.emit("end"),K.emit("close");else $.emit("error",H)}),["child","childEnd","warn"].forEach(function(H){K.on(H,$.emit.bind($,H))})})};T9.prototype.disown=function($){if($.emit("beforeDisown"),$._disowned=!0,$.parent=$.root=null,$===this._currentEntry)this._currentEntry=null;$.emit("disown")};T9.prototype.getChildProps=function(){return{depth:this.depth+1,root:this.root||this,parent:this,follow:this.follow,filter:this.filter,sort:this.props.sort,hardlinks:this.props.hardlinks}};T9.prototype.pause=function($){var Y=this;if(Y._paused)return;if($=$||Y,Y._paused=!0,Y._currentEntry&&Y._currentEntry.pause)Y._currentEntry.pause($);Y.emit("pause",$)};T9.prototype.resume=function($){var Y=this;if(!Y._paused)return;if($=$||Y,Y._paused=!1,Y.emit("resume",$),Y._paused)return;if(Y._currentEntry){if(Y._currentEntry.resume)Y._currentEntry.resume($)}else Y._read()};T9.prototype.emitEntry=function($){this.emit("entry",$),this.emit("child",$)}});var Rn=j((x14,FN0)=>{FN0.exports=GI;var VO1=t8(),LO1=W1(),qN0=zI(),VN0={EOF:!0},LN0={CLOSE:!0};LO1(GI,qN0);function GI($){var Y=this;if(!(Y instanceof GI))throw Error("FileReader must be called as constructor.");if(!($.type==="Link"&&$.Link||$.type==="File"&&$.File))throw Error("Non-file type "+$.type);Y._buffer=[],Y._bytesEmitted=0,qN0.call(Y,$)}GI.prototype._getStream=function(){var $=this,Y=$._stream=VO1.createReadStream($._path,$.p Line truncated
expect: `+$.props.size+`
actual: `+$._bytesEmitted)}),Y.on("close",function(){if($._paused||$._buffer.length)$._buffer.push($N0),$._read();else $.emit("close")}),Y.on("error",function(U){$.emit("error",U)}),$._read()};Kz.prototype._read=function(){var $=this;if($._paused)return;if(!$._stream)return $._getStream();if($._buffer.length){var Y=$._buffer;for(var U=0,z=Y.length;U<z;U++){var I=Y[U];if(I===eO0)$.emit("end");else if(I===$N0)$.emit("close");else $.emit("data",I);if($._paused){$._buffer=Y.slice(U);return}}$._buffer.length=0}};Kz.prototype.pause=function($){var Y=this;if(Y._paused)return;if($=$||Y,Y._paused=!0,Y._stream)Y._stream.pause();Y.emit("pause",$)};Kz.prototype.resume=function($){var Y=this;if(!Y._paused)return;if($=$||Y,Y.emit("resume",$),Y._paused=!1,Y._stream)Y._stream.resume();Y._read()}});var IN0=E((O04,zN0)=>{zN0.exports=OB;var jM1=W1(),UN0=Jz();jM1(OB,UN0);function OB($){var Y=this;if(!(Y instanceof OB))throw Error("SocketReader must be called as constructor.");if(!($.type==="Socket"&&$.Socket))throw Error("Non-socket type "+$.type);UN0.call(Y,$)}OB.prototype._read=function(){var $=this;if($._paused)return;if(!$._ended)$.emit("end"),$.emit("close"),$._ended=!0}});var jn=E((N04,QN0)=>{QN0.exports=Gz;var Tn=Jz(),EM1=FZ(),CM1=W1(),RM1=r8();CM1(Gz,Tn);function Gz($){var Y=this;if(!(Y instanceof Gz))throw Error("ProxyReader must be called as constructor.");Y.props=$,Y._buffer=[],Y.ready=!1,Tn.call(Y,$)}Gz.prototype._stat=function(){var $=this,Y=$.props,U=Y.follow?"stat":"lstat";RM1[U](Y.path,function(z,I){var Q;if(z||!I)Q="File";else Q=EM1(I);Y[Q]=!0,Y.type=$.type=Q,$._old=I,$._addProxy(Tn(Y,I))})};Gz.prototype._addProxy=function($){var Y=this;if(Y._proxyTarget)return Y.error("proxy already set");Y._proxyTarget=$,$._proxy=Y,["error","data","end","close","linkpath","entry","entryEnd","child","childEnd","warn","stat"].forEach(function(z){$.on(z,Y.emit.bind(Y,z))}),Y.emit("proxy",$),$.on("ready",function(){Y.ready=!0,Y.emit("ready")});var U=Y._buffer;Y._buffer.length=0,U.forEach(function(z){$[z[0]].apply($,z[1])})};Gz.prototype.pause=function(){return this._proxyTarget?this._proxyTarget.pause():!1};Gz.prototype.resume=function(){return this._proxyTarget?this._proxyTarget.resume():!1}});var Jz=E((D04,GN0)=>{GN0.exports=B5;var _M1=r8(),vM1=J0("stream").Stream,hM1=W1(),En=J0("path"),Cn=FZ(),NB=B5.hardLinks={},JN0=MB();hM1(B5,JN0);var KN0=Dn();function B5($,Y){var U=this;if(!(U instanceof B5))return new B5($,Y);if(typeof $==="string")$={path:$};var z,I;if($.type&&typeof $.type==="function")z=$.type,I=z;else z=Cn($),I=B5;if(Y&&!z)z=Cn(Y),$[z]=!0,$.type=z;switch(z){case"Directory":I=Bn();break;case"Link":case"File":I=Pn();break;case"SymbolicLink":I=KN0;break;case"Socket":I=IN0();break;case null:I=jn();break}if(!(U instanceof I))return new I($);if(JN0.call(U),!$.path)U.error("Must provide a path",null,!0);if(U.readable=!0,U.writable=!1,U.type=z,U.props=$,U.depth=$.depth=$.depth||0,U.parent=$.parent||null,U.root=$.root||$.parent&&$.parent.root||U,U._path=U.path=En.resolve($.path),process.platform==="win32"){if(U.path=U._path=U.path.replace(/\?/g,"_"),U._path.length>=260)U._swallowErrors=!0,U._path="\\\\?\\"+U.path.replace(/\//g,"\\")}if(U.basename=$.basename=En.basename(U.path),U.dirname=$.dirname=En.dirname(U.path),$.parent=$.root=null,U.size=$.size,U.filter=typeof $.filter==="function"?$.filter:null,$.sort==="alpha")$.sort=SM1;U._stat(Y)}function SM1($,Y){return $===Y?0:$.toLowerCase()>Y.toLowerCase()?1:$.toLowerCase()<Y.toLowerCase()?-1:$>Y?1:-1}B5.prototype._stat=function($){var Y=this,U=Y.props,z=U.follow?"stat":"lstat";if($)process.nextTick(I.bind(null,null,$));else _M1[z](Y._path,I);function I(Q,J){if(Q)return Y.error(Q);if(Object.keys(J).forEach(function(q){U[q]=J[q]}),Y.size!==void 0&&U.size!==Y.size)return Y.error("incorrect size");Y.size=U.size;var K=Cn(U),G=U.hardlinks!==!1;if(G&&K!=="Directory"&&U.nlink&&U.nlink>1){var H=U.dev+":"+U.ino;if(NB[H]===Y._path||!NB[H])NB[H]=Y._path;else K=Y.type=Y.props.type="Link",Y.Link=Y.props.Link=!0,Y.linkpath=Y.props.linkpath=NB[H],Y._stat=Y._read=KN0.prototype._read}if(Y.type&&Y.type!==K)Y.error("Unexpected type: "+K);if(Y.filter){var W=Y._proxy||Y;if(!Y.filter.call(W,W,U)){if(!Y._disowned)Y.abort(),Y.emit("end"),Y.emit("close");return}}var X=["_stat","stat","ready"],Z=0;(function q(){if(Y._aborted){Y.emit("end"),Y.emit("close");return}if(Y._paused&&Y.type!=="Directory"){Y.once("resume",q);return}var V=X[Z++];if(!V)return Y._read();Y.emit(V,U),q()})()}};B5.prototype.pipe=function($){var Y=this;if(typeof $.add==="function")Y.on("entry",function(U){var z=$.add(U);if(z===!1)Y.pause()});return vM1.prototype.pipe.apply(this,arguments)};B5.prototype.pause=function($){if(this._paused=!0,$=$||this,this.emit("pause",$),this._stream)this._stream.pause($)};B5.prototype.resume=function($){if(this._paused=!1,$=$||this,this.emit("resume",$),this._stream)this._stream.resume($);this._read()};B5.prototype._read=function(){this.error("Cannot read unknown type: "+this.type)}});var hn=E((A04,FN0)=> Line truncated
actual: `+$._bytesEmitted)}),Y.on("close",function(){if($._paused||$._buffer.length)$._buffer.push(LN0),$._read();else $.emit("close")}),Y.on("error",function(U){$.emit("error",U)}),$._read()};GI.prototype._read=function(){var $=this;if($._paused)return;if(!$._stream)return $._getStream();if($._buffer.length){var Y=$._buffer;for(var U=0,I=Y.length;U<I;U++){var Q=Y[U];if(Q===VN0)$.emit("end");else if(Q===LN0)$.emit("close");else $.emit("data",Q);if($._paused){$._buffer=Y.slice(U);return}}$._buffer.length=0}};GI.prototype.pause=function($){var Y=this;if(Y._paused)return;if($=$||Y,Y._paused=!0,Y._stream)Y._stream.pause();Y.emit("pause",$)};GI.prototype.resume=function($){var Y=this;if(!Y._paused)return;if($=$||Y,Y.emit("resume",$),Y._paused=!1,Y._stream)Y._stream.resume();Y._read()}});var ON0=j((f14,MN0)=>{MN0.exports=jA;var FO1=W1(),wN0=zI();FO1(jA,wN0);function jA($){var Y=this;if(!(Y instanceof jA))throw Error("SocketReader must be called as constructor.");if(!($.type==="Socket"&&$.Socket))throw Error("Non-socket type "+$.type);wN0.call(Y,$)}jA.prototype._read=function(){var $=this;if($._paused)return;if(!$._ended)$.emit("end"),$.emit("close"),$._ended=!0}});var vn=j((u14,NN0)=>{NN0.exports=HI;var _n=zI(),wO1=OZ(),MO1=W1(),OO1=t8();MO1(HI,_n);function HI($){var Y=this;if(!(Y instanceof HI))throw Error("ProxyReader must be called as constructor.");Y.props=$,Y._buffer=[],Y.ready=!1,_n.call(Y,$)}HI.prototype._stat=function(){var $=this,Y=$.props,U=Y.follow?"stat":"lstat";OO1[U](Y.path,function(I,Q){var J;if(I||!Q)J="File";else J=wO1(Q);Y[J]=!0,Y.type=$.type=J,$._old=Q,$._addProxy(_n(Y,Q))})};HI.prototype._addProxy=function($){var Y=this;if(Y._proxyTarget)return Y.error("proxy already set");Y._proxyTarget=$,$._proxy=Y,["error","data","end","close","linkpath","entry","entryEnd","child","childEnd","warn","stat"].forEach(function(I){$.on(I,Y.emit.bind(Y,I))}),Y.emit("proxy",$),$.on("ready",function(){Y.ready=!0,Y.emit("ready")});var U=Y._buffer;Y._buffer.length=0,U.forEach(function(I){$[I[0]].apply($,I[1])})};HI.prototype.pause=function(){return this._proxyTarget?this._proxyTarget.pause():!1};HI.prototype.resume=function(){return this._proxyTarget?this._proxyTarget.resume():!1}});var zI=j((b14,AN0)=>{AN0.exports=j5;var NO1=t8(),DO1=K0("stream").Stream,BO1=W1(),Sn=K0("path"),hn=OZ(),CA=j5.hardLinks={},DN0=EA();BO1(j5,DN0);var BN0=En();function j5($,Y){var U=this;if(!(U instanceof j5))return new j5($,Y);if(typeof $==="string")$={path:$};var I,Q;if($.type&&typeof $.type==="function")I=$.type,Q=I;else I=hn($),Q=j5;if(Y&&!I)I=hn(Y),$[I]=!0,$.type=I;switch(I){case"Directory":Q=Cn();break;case"Link":case"File":Q=Rn();break;case"SymbolicLink":Q=BN0;break;case"Socket":Q=ON0();break;case null:Q=vn();break}if(!(U instanceof Q))return new Q($);if(DN0.call(U),!$.path)U.error("Must provide a path",null,!0);if(U.readable=!0,U.writable=!1,U.type=I,U.props=$,U.depth=$.depth=$.depth||0,U.parent=$.parent||null,U.root=$.root||$.parent&&$.parent.root||U,U._path=U.path=Sn.resolve($.path),process.platform==="win32"){if(U.path=U._path=U.path.replace(/\?/g,"_"),U._path.length>=260)U._swallowErrors=!0,U._path="\\\\?\\"+U.path.replace(/\//g,"\\")}if(U.basename=$.basename=Sn.basename(U.path),U.dirname=$.dirname=Sn.dirname(U.path),$.parent=$.root=null,U.size=$.size,U.filter=typeof $.filter==="function"?$.filter:null,$.sort==="alpha")$.sort=AO1;U._stat(Y)}function AO1($,Y){return $===Y?0:$.toLowerCase()>Y.toLowerCase()?1:$.toLowerCase()<Y.toLowerCase()?-1:$>Y?1:-1}j5.prototype._stat=function($){var Y=this,U=Y.props,I=U.follow?"stat":"lstat";if($)process.nextTick(Q.bind(null,null,$));else NO1[I](Y._path,Q);function Q(J,K){if(J)return Y.error(J);if(Object.keys(K).forEach(function(q){U[q]=K[q]}),Y.size!==void 0&&U.size!==Y.size)return Y.error("incorrect size");Y.size=U.size;var z=hn(U),G=U.hardlinks!==!1;if(G&&z!=="Directory"&&U.nlink&&U.nlink>1){var H=U.dev+":"+U.ino;if(CA[H]===Y._path||!CA[H])CA[H]=Y._path;else z=Y.type=Y.props.type="Link",Y.Link=Y.props.Link=!0,Y.linkpath=Y.props.linkpath=CA[H],Y._stat=Y._read=BN0.prototype._read}if(Y.type&&Y.type!==z)Y.error("Unexpected type: "+z);if(Y.filter){var W=Y._proxy||Y;if(!Y.filter.call(W,W,U)){if(!Y._disowned)Y.abort(),Y.emit("end"),Y.emit("close");return}}var X=["_stat","stat","ready"],Z=0;(function q(){if(Y._aborted){Y.emit("end"),Y.emit("close");return}if(Y._paused&&Y.type!=="Directory"){Y.once("resume",q);return}var V=X[Z++];if(!V)return Y._read();Y.emit(V,U),q()})()}};j5.prototype.pipe=function($){var Y=this;if(typeof $.add==="function")Y.on("entry",function(U){var I=$.add(U);if(I===!1)Y.pause()});return DO1.prototype.pipe.apply(this,arguments)};j5.prototype.pause=function($){if(this._paused=!0,$=$||this,this.emit("pause",$),this._stream)this._stream.pause($)};j5.prototype.resume=function($){if(this._paused=!1,$=$||this,this.emit("resume",$),this._stream)this._stream.resume($);this._read()};j5.prototype._read=function(){this.error("Cannot read unknown type: "+this.type)}});var xn=j((i14,vN0)=> Line truncated
expect: `+$.size+`
actual: `+$._bytesWritten);vB.prototype._finish.call($)}});var pn=E((b04,QD0)=>{QD0.exports=u2;var nn=rJ(),JO1=FZ(),KO1=W1(),GO1=RB(),HO1=J0("fs");KO1(u2,nn);function u2($){var Y=this;if(!(Y instanceof u2))throw Error("ProxyWriter must be called as constructor.");Y.props=$,Y._needDrain=!1,nn.call(Y,$)}u2.prototype._stat=function(){var $=this,Y=$.props,U=Y.follow?"stat":"lstat";HO1[U](Y.path,function(z,I){var Q;if(z||!I)Q="File";else Q=JO1(I);Y[Q]=!0,Y.type=$.type=Q,$._old=I,$._addProxy(nn(Y,I))})};u2.prototype._addProxy=function($){var Y=this;if(Y._proxy)return Y.error("proxy already set");Y._proxy=$,["ready","error","close","pipe","drain","warn"].forEach(function(z){$.on(z,Y.emit.bind(Y,z))}),Y.emit("proxy",$);var U=Y._buffer;if(U.forEach(function(z){$[z[0]].apply($,z[1])}),Y._buffer.length=0,Y._needsDrain)Y.emit("drain")};u2.prototype.add=function($){if(GO1($),!this._proxy)return this._buffer.push(["add",[$]]),this._needDrain=!0,!1;return this._proxy.add($)};u2.prototype.write=function($){if(!this._proxy)return this._buffer.push(["write",[$]]),this._needDrain=!0,!1;return this._proxy.write($)};u2.prototype.end=function($){if(!this._proxy)return this._buffer.push(["end",[$]]),!1;return this._proxy.end($)}});var rJ=E((i04,VD0)=>{VD0.exports=i$;var b$=r8(),WO1=W1(),XO1=hn(),ZO1=xn(),AZ=J0("path"),KD0=process.platform==="win32"?0:process.umask(),GD0=FZ(),HD0=MB();WO1(i$,HD0);i$.dirmode=parseInt("0777",8)&~KD0;i$.filemode=parseInt("0666",8)&~KD0;var qO1=un(),VO1=bn(),LO1=cn(),FO1=pn();function i$($,Y){var U=this;if(typeof $==="string")$={path:$};var z=GD0($),I=i$;switch(z){case"Directory":I=qO1;break;case"File":I=LO1;break;case"Link":case"SymbolicLink":I=VO1;break;case null:default:I=FO1;break}if(!(U instanceof I))return new I($);if(HD0.call(U),!$.path)U.error("Must provide a path",null,!0);if(U.type=$.type,U.props=$,U.depth=$.depth||0,U.clobber=$.clobber===!1?$.clobber:!0,U.parent=$.parent||null,U.root=$.root||$.parent&&$.parent.root||U,U._path=U.path=AZ.resolve($.path),process.platform==="win32"){if(U.path=U._path=U.path.replace(/\?/g,"_"),U._path.length>=260)U._swallowErrors=!0,U._path="\\\\?\\"+U.path.replace(/\//g,"\\")}if(U.basename=AZ.basename($.path),U.dirname=AZ.dirname($.path),U.linkpath=$.linkpath||null,$.parent=$.root=null,U.size=$.size,typeof $.mode==="string")$.mode=parseInt($.mode,8);U.readable=!1,U.writable=!0,U._buffer=[],U.ready=!1,U.filter=typeof $.filter==="function"?$.filter:null,U._stat(Y)}i$.prototype._create=function(){var $=this;b$[$.props.follow?"stat":"lstat"]($._path,function(Y){if(Y)return $.warn("Cannot create "+$._path+`
Unsupported type: `+$.type,"ENOTSUP");$._finish()})};i$.prototype._stat=function($){var Y=this,U=Y.props,z=U.follow?"stat":"lstat",I=Y._proxy||Y;if($)Q(null,$);else b$[z](Y._path,Q);function Q(J,K){if(Y.filter&&!Y.filter.call(I,I,K)){Y._aborted=!0,Y.emit("end"),Y.emit("close");return}if(J||!K)return dn(Y);Y._old=K;var G=GD0(K);if(G!==Y.type||Y.type==="File"&&K.nlink>1)return XO1(Y._path,function(H){if(H)return Y.error(H);Y._old=null,dn(Y)});dn(Y)}};function dn($){ZO1(AZ.dirname($._path),i$.dirmode,function(Y,U){if(Y)return $.error(Y);return $._madeDir=U,$._create()})}function WD0($,Y,U,z,I){var Q=Y.mode,J=Y.follow||$.type!=="SymbolicLink"?"chmod":"lchmod";if(!b$[J])return I();if(typeof Q!=="number")return I();var K=U.mode&parseInt("0777",8);if(Q=Q&parseInt("0777",8),Q===K)return I();b$[J](z,Q,I)}function XD0($,Y,U,z,I){if(process.platform==="win32")return I();if(!process.getuid||process.getuid()!==0)return I();if(typeof Y.uid!=="number"&&typeof Y.gid!=="number")return I();if(U.uid===Y.uid&&U.gid===Y.gid)return I();var Q=$.props.follow||$.type!=="SymbolicLink"?"chown":"lchown";if(!b$[Q])return I();if(typeof Y.uid!=="number")Y.uid=U.uid;if(typeof Y.gid!=="number")Y.gid=U.gid;b$[Q](z,Y.uid,Y.gid,I)}function ZD0($,Y,U,z,I){if(!b$.utimes||process.platform==="win32")return I();var Q=Y.follow||$.type!=="SymbolicLink"?"utimes":"lutimes";if(Q==="lutimes"&&!b$[Q])Q="utimes";if(!b$[Q])return I();var{atime:J,mtime:K}=U,G=Y.atime,H=Y.mtime;if(G===void 0)G=J;if(H===void 0)H=K;if(!JD0(G))G=new Date(G);if(!JD0(H))G=new Date(H);if(G.getTime()===J.getTime()&&H.getTime()===K.getTime())return I();b$[Q](z,G,H,I)}i$.prototype._finish=function(){var $=this;if($._finishing)return;$._finishing=!0;var Y=0,U=null,z=!1;if($._old)$._old.atime=new Date(0),$._old.mtime=new Date(0),Q($._old);else{var I=$.props.follow?"stat":"lstat";b$[I]($._path,function(K,G){if(K)if(K.code==="ENOENT"&&($.type==="Link"||$.type==="SymbolicLink")&&process.platform==="win32"){$.ready=!0,$.emit("ready"),$.emit("end"),$.emit("close"),$.end=$._finish=function(){};return}else return $.error(K);Q($._old=G)})}return;function Q(K){Y+=3,WD0($,$.props,K,$._path,J("chmod")),XD0($,$.props,K,$._path,J("chown")),ZD0($,$.props,K,$._path,J("utimes"))}function J(K){return function(G){if(U)return;if(G)return G.fstream_finish_call=K,$.error(U=G);if(--Y>0)return;if(z)return;if(z=!0,!$._madeDir)return H();else qD0($,$._path,H);function H(W){if(W)return W.fstream_finish_call="setupMadeDir",$.error(W);$.emit("end"),$.emit("close")}}}};function qD0($,Y,U){var z=$._madeDir,I=AZ.dirname(Y);wO1($,I,function(Q){if(Q)return U(Q);if(I===z)return U();qD0($,I,U)})}function wO1($,Y,U){var z={};Object.keys($.props).forEach(function(K){if(z[K]=$.props[K],K==="mode"&&$.type!=="Directory")z[K]=z[K]|parseInt("0111",8)});var I=3,Q=null;b$.stat(Y,function(K,G){if(K)return U(Q=K);WD0($,z,G,Y,J),XD0($,z,G,Y,J),ZD0($,z,G,Y,J)});function J(K){if(Q)return;if(K)return U(Q=K);if(--I===0)return U()}}i$.prototype.pipe=function(){this.error("Can't pipe from writable stream")};i$.prototype.add=function(){this.error("Can't add to non-Directory type")};i$.prototype.write=function(){return!0};function MO1($){return Object.prototype.toString.call($)}function JD0($){return typeof $==="object"&&MO1($)==="[object Date]"}});var sn=E((OO1)=>{OO1.Abstract=MB();OO1.Reader=Jz();OO1.Writer=rJ();OO1.File={Reader:Pn(),Writer:cn()};OO1.Dir={Reader:Bn(),Writer:un()};OO1.Link={Reader:Dn(),Writer:bn()};OO1.Proxy={Reader:jn(),Writer:pn()};OO1.Reader.Dir=OO1.DirReader=OO1.Dir.Reader;OO1.Reader.File=OO1.FileReader=OO1.File.Reader;OO1.Reader.Link=OO1.LinkReader=OO1.Link.Reader;OO1.Reader.Proxy=OO1.ProxyReader=OO1.Proxy.Reader;OO1.Writer.Dir=OO1.DirWriter=OO1.Dir.Writer;OO1.Writer.File=OO1.FileWriter=OO1.File.Writer;OO1.Writer.Link=OO1.LinkWriter=OO1.Link.Writer;OO1.Writer.Proxy=OO1.ProxyWriter=OO1.Proxy.Writer;OO1.collect=RB()});var FD0=E((a04,LD0)=>{LD0.exports=EO1;var AO1=HB(),BO1=sn().Writer,an=J0("path"),PO1=J0("stream"),TO1=Mn(),jO1=h2();function EO1($){$.path=an.resolve(an.normalize($.path));var Y=new AO1($),U=new PO1.Writable({objectMode:!0});U._write=function(I,Q,J){if(I.type=="Directory")return J();var K=an.join($.path,I.path);if(K.indexOf($.path)!=0)return J();let G=$.getWriter?$.getWriter({path:K}):BO1({path:K});I.pipe(G).on("error",J).on("close",J)};var z=TO1(Y,U);return Y.once("crx-header",function(I){z.crxHeader=I}),Y.pipe(U).on("finish",function(){z.emit("close")}),z.promise=function(){return new jO1(function(I,Q){z.on("close",I),z.on("error",Q)})},z}});var wD0=E((t04,hB)=>{var E6=function($){var Y=1e7,U=7,z=9007199254740992,I=Z(z),Q="0123456789abcdefghijklmnopqrstuvwxyz",J=typeof BigInt==="function";function K(B,h,u,s){if(typeof B>"u")return K[0];if(typeof h<"u")return+h===10&&!u?D0(B):u0(B,h,u,s);return D0(B)}function G(B,h){this.value=B,this.sign=h,this.isSmall=!1}G.prototype=Object.create(K.prototype);function H(B){this.value=B,this.sign=B<0,this.isSmall=!0}H.prototype=Object.create(K.prototype);function W(B){ Line truncated
actual: `+$._bytesWritten);uA.prototype._finish.call($)}});var rn=j((J44,ND0)=>{ND0.exports=i2;var on=sK(),sO1=OZ(),aO1=W1(),tO1=xA(),eO1=K0("fs");aO1(i2,on);function i2($){var Y=this;if(!(Y instanceof i2))throw Error("ProxyWriter must be called as constructor.");Y.props=$,Y._needDrain=!1,on.call(Y,$)}i2.prototype._stat=function(){var $=this,Y=$.props,U=Y.follow?"stat":"lstat";eO1[U](Y.path,function(I,Q){var J;if(I||!Q)J="File";else J=sO1(Q);Y[J]=!0,Y.type=$.type=J,$._old=Q,$._addProxy(on(Y,Q))})};i2.prototype._addProxy=function($){var Y=this;if(Y._proxy)return Y.error("proxy already set");Y._proxy=$,["ready","error","close","pipe","drain","warn"].forEach(function(I){$.on(I,Y.emit.bind(Y,I))}),Y.emit("proxy",$);var U=Y._buffer;if(U.forEach(function(I){$[I[0]].apply($,I[1])}),Y._buffer.length=0,Y._needsDrain)Y.emit("drain")};i2.prototype.add=function($){if(tO1($),!this._proxy)return this._buffer.push(["add",[$]]),this._needDrain=!0,!1;return this._proxy.add($)};i2.prototype.write=function($){if(!this._proxy)return this._buffer.push(["write",[$]]),this._needDrain=!0,!1;return this._proxy.write($)};i2.prototype.end=function($){if(!this._proxy)return this._buffer.push(["end",[$]]),!1;return this._proxy.end($)}});var sK=j((K44,RD0)=>{RD0.exports=p$;var d$=t8(),$N1=W1(),YN1=xn(),UN1=nn(),TZ=K0("path"),BD0=process.platform==="win32"?0:process.umask(),AD0=OZ(),PD0=EA();$N1(p$,PD0);p$.dirmode=parseInt("0777",8)&~BD0;p$.filemode=parseInt("0666",8)&~BD0;var IN1=pn(),QN1=mn(),JN1=ln(),KN1=rn();function p$($,Y){var U=this;if(typeof $==="string")$={path:$};var I=AD0($),Q=p$;switch(I){case"Directory":Q=IN1;break;case"File":Q=JN1;break;case"Link":case"SymbolicLink":Q=QN1;break;case null:default:Q=KN1;break}if(!(U instanceof Q))return new Q($);if(PD0.call(U),!$.path)U.error("Must provide a path",null,!0);if(U.type=$.type,U.props=$,U.depth=$.depth||0,U.clobber=$.clobber===!1?$.clobber:!0,U.parent=$.parent||null,U.root=$.root||$.parent&&$.parent.root||U,U._path=U.path=TZ.resolve($.path),process.platform==="win32"){if(U.path=U._path=U.path.replace(/\?/g,"_"),U._path.length>=260)U._swallowErrors=!0,U._path="\\\\?\\"+U.path.replace(/\//g,"\\")}if(U.basename=TZ.basename($.path),U.dirname=TZ.dirname($.path),U.linkpath=$.linkpath||null,$.parent=$.root=null,U.size=$.size,typeof $.mode==="string")$.mode=parseInt($.mode,8);U.readable=!1,U.writable=!0,U._buffer=[],U.ready=!1,U.filter=typeof $.filter==="function"?$.filter:null,U._stat(Y)}p$.prototype._create=function(){var $=this;d$[$.props.follow?"stat":"lstat"]($._path,function(Y){if(Y)return $.warn("Cannot create "+$._path+`
Unsupported type: `+$.type,"ENOTSUP");$._finish()})};p$.prototype._stat=function($){var Y=this,U=Y.props,I=U.follow?"stat":"lstat",Q=Y._proxy||Y;if($)J(null,$);else d$[I](Y._path,J);function J(K,z){if(Y.filter&&!Y.filter.call(Q,Q,z)){Y._aborted=!0,Y.emit("end"),Y.emit("close");return}if(K||!z)return sn(Y);Y._old=z;var G=AD0(z);if(G!==Y.type||Y.type==="File"&&z.nlink>1)return YN1(Y._path,function(H){if(H)return Y.error(H);Y._old=null,sn(Y)});sn(Y)}};function sn($){UN1(TZ.dirname($._path),p$.dirmode,function(Y,U){if(Y)return $.error(Y);return $._madeDir=U,$._create()})}function TD0($,Y,U,I,Q){var J=Y.mode,K=Y.follow||$.type!=="SymbolicLink"?"chmod":"lchmod";if(!d$[K])return Q();if(typeof J!=="number")return Q();var z=U.mode&parseInt("0777",8);if(J=J&parseInt("0777",8),J===z)return Q();d$[K](I,J,Q)}function ED0($,Y,U,I,Q){if(process.platform==="win32")return Q();if(!process.getuid||process.getuid()!==0)return Q();if(typeof Y.uid!=="number"&&typeof Y.gid!=="number")return Q();if(U.uid===Y.uid&&U.gid===Y.gid)return Q();var J=$.props.follow||$.type!=="SymbolicLink"?"chown":"lchown";if(!d$[J])return Q();if(typeof Y.uid!=="number")Y.uid=U.uid;if(typeof Y.gid!=="number")Y.gid=U.gid;d$[J](I,Y.uid,Y.gid,Q)}function jD0($,Y,U,I,Q){if(!d$.utimes||process.platform==="win32")return Q();var J=Y.follow||$.type!=="SymbolicLink"?"utimes":"lutimes";if(J==="lutimes"&&!d$[J])J="utimes";if(!d$[J])return Q();var{atime:K,mtime:z}=U,G=Y.atime,H=Y.mtime;if(G===void 0)G=K;if(H===void 0)H=z;if(!DD0(G))G=new Date(G);if(!DD0(H))G=new Date(H);if(G.getTime()===K.getTime()&&H.getTime()===z.getTime())return Q();d$[J](I,G,H,Q)}p$.prototype._finish=function(){var $=this;if($._finishing)return;$._finishing=!0;var Y=0,U=null,I=!1;if($._old)$._old.atime=new Date(0),$._old.mtime=new Date(0),J($._old);else{var Q=$.props.follow?"stat":"lstat";d$[Q]($._path,function(z,G){if(z)if(z.code==="ENOENT"&&($.type==="Link"||$.type==="SymbolicLink")&&process.platform==="win32"){$.ready=!0,$.emit("ready"),$.emit("end"),$.emit("close"),$.end=$._finish=function(){};return}else return $.error(z);J($._old=G)})}return;function J(z){Y+=3,TD0($,$.props,z,$._path,K("chmod")),ED0($,$.props,z,$._path,K("chown")),jD0($,$.props,z,$._path,K("utimes"))}function K(z){return function(G){if(U)return;if(G)return G.fstream_finish_call=z,$.error(U=G);if(--Y>0)return;if(I)return;if(I=!0,!$._madeDir)return H();else CD0($,$._path,H);function H(W){if(W)return W.fstream_finish_call="setupMadeDir",$.error(W);$.emit("end"),$.emit("close")}}}};function CD0($,Y,U){var I=$._madeDir,Q=TZ.dirname(Y);zN1($,Q,function(J){if(J)return U(J);if(Q===I)return U();CD0($,Q,U)})}function zN1($,Y,U){var I={};Object.keys($.props).forEach(function(z){if(I[z]=$.props[z],z==="mode"&&$.type!=="Directory")I[z]=I[z]|parseInt("0111",8)});var Q=3,J=null;d$.stat(Y,function(z,G){if(z)return U(J=z);TD0($,I,G,Y,K),ED0($,I,G,Y,K),jD0($,I,G,Y,K)});function K(z){if(J)return;if(z)return U(J=z);if(--Q===0)return U()}}p$.prototype.pipe=function(){this.error("Can't pipe from writable stream")};p$.prototype.add=function(){this.error("Can't add to non-Directory type")};p$.prototype.write=function(){return!0};function GN1($){return Object.prototype.toString.call($)}function DD0($){return typeof $==="object"&&GN1($)==="[object Date]"}});var Yd=j((HN1)=>{HN1.Abstract=EA();HN1.Reader=zI();HN1.Writer=sK();HN1.File={Reader:Rn(),Writer:ln()};HN1.Dir={Reader:Cn(),Writer:pn()};HN1.Link={Reader:En(),Writer:mn()};HN1.Proxy={Reader:vn(),Writer:rn()};HN1.Reader.Dir=HN1.DirReader=HN1.Dir.Reader;HN1.Reader.File=HN1.FileReader=HN1.File.Reader;HN1.Reader.Link=HN1.LinkReader=HN1.Link.Reader;HN1.Reader.Proxy=HN1.ProxyReader=HN1.Proxy.Reader;HN1.Writer.Dir=HN1.DirWriter=HN1.Dir.Writer;HN1.Writer.File=HN1.FileWriter=HN1.File.Writer;HN1.Writer.Link=HN1.LinkWriter=HN1.Link.Writer;HN1.Writer.Proxy=HN1.ProxyWriter=HN1.Proxy.Writer;HN1.collect=xA()});var vD0=j((F44,_D0)=>{_D0.exports=wN1;var ZN1=wA(),qN1=Yd().Writer,Ud=K0("path"),VN1=K0("stream"),LN1=An(),FN1=g2();function wN1($){$.path=Ud.resolve(Ud.normalize($.path));var Y=new ZN1($),U=new VN1.Writable({objectMode:!0});U._write=function(Q,J,K){if(Q.type=="Directory")return K();var z=Ud.join($.path,Q.path);if(z.indexOf($.path)!=0)return K();let G=$.getWriter?$.getWriter({path:z}):qN1({path:z});Q.pipe(G).on("error",K).on("close",K)};var I=LN1(Y,U);return Y.once("crx-header",function(Q){I.crxHeader=Q}),Y.pipe(U).on("finish",function(){I.emit("close")}),I.promise=function(){return new FN1(function(Q,J){I.on("close",Q),I.on("error",J)})},I}});var SD0=j((w44,bA)=>{var R6=function($){var Y=1e7,U=7,I=9007199254740992,Q=Z(I),J="0123456789abcdefghijklmnopqrstuvwxyz",K=typeof BigInt==="function";function z(A,S,u,s){if(typeof A>"u")return z[0];if(typeof S<"u")return+S===10&&!u?D0(A):u0(A,S,u,s);return D0(A)}function G(A,S){this.value=A,this.sign=S,this.isSmall=!1}G.prototype=Object.create(z.prototype);function H(A){this.value=A,this.sign=A<0,this.isSmall=!0}H.prototype=Object.create(z.prototype);function W(A){ Line truncated
* Tmp
*
* Copyright (c) 2011-2017 KARASZI Istvan <github@spam.raszi.hu>
*
* MIT Licensed
*/var L4=J0("fs"),fB=J0("os"),C6=J0("path"),_D0=J0("crypto"),P9={fs:L4.constants,os:fB.constants},gD0=/XXXXXX/,yD0=(P9.O_CREAT||P9.fs.O_CREAT)|(P9.O_EXCL||P9.fs.O_EXCL)|(P9.O_RDWR||P9.fs.O_RDWR),aO1=fB.platform()==="win32",tO1=P9.EBADF||P9.os.errno.EBADF,eO1=P9.ENOENT||P9.os.errno.ENOENT,aJ=[],kD0=L4.rmdirSync.bind(L4),xD0=!1;function $N1($,Y){return L4.rm($,{recursive:!0},Y)}function fD0($){return L4.rmSync($,{recursive:!0})}function Up($,Y){let U=tJ($,Y),z=U[0],I=U[1];WN1(z,function(Q,J){if(Q)return I(Q);let K=J.tries;(function G(){try{let H=bD0(J);L4.stat(H,function(W){if(!W){if(K-- >0)return G();return I(Error("Could not get a unique tmp filename, max tries reached "+H))}I(null,H)})}catch(H){I(H)}})()})}function zp($){let Y=tJ($),U=Y[0],z=XN1(U),I=z.tries;do{let Q=bD0(z);try{L4.statSync(Q)}catch(J){return Q}}while(I-- >0);throw Error("Could not get a unique tmp filename, max tries reached")}function YN1($,Y){let U=tJ($,Y),z=U[0],I=U[1];Up(z,function(J,K){if(J)return I(J);L4.open(K,yD0,z.mode||384,function(H,W){if(H)return I(H);if(z.discardDescriptor)return L4.close(W,function(Z){return I(Z,K,void 0,$p(K,-1,z,!1))});else{let X=z.discardDescriptor||z.detachDescriptor;I(null,K,W,$p(K,X?-1:W,z,!1))}})})}function UN1($){let Y=tJ($),U=Y[0],z=U.discardDescriptor||U.detachDescriptor,I=zp(U),Q=L4.openSync(I,yD0,U.mode||384);if(U.discardDescriptor)L4.closeSync(Q),Q=void 0;return{name:I,fd:Q,removeCallback:$p(I,z?-1:Q,U,!0)}}function zN1($,Y){let U=tJ($,Y),z=U[0],I=U[1];Up(z,function(J,K){if(J)return I(J);L4.mkdir(K,z.mode||448,function(H){if(H)return I(H);I(null,K,uD0(K,z,!1))})})}function IN1($){let Y=tJ($),U=Y[0],z=zp(U);return L4.mkdirSync(z,U.mode||448),{name:z,removeCallback:uD0(z,U,!0)}}function QN1($,Y){let U=function(z){if(z&&!Yp(z))return Y(z);Y()};if(0<=$[0])L4.close($[0],function(){L4.unlink($[1],U)});else L4.unlink($[1],U)}function JN1($){let Y=null;try{if(0<=$[0])L4.closeSync($[0])}catch(U){if(!ZN1(U)&&!Yp(U))throw U}finally{try{L4.unlinkSync($[1])}catch(U){if(!Yp(U))Y=U}}if(Y!==null)throw Y}function $p($,Y,U,z){let I=xB(JN1,[Y,$],z),Q=xB(QN1,[Y,$],z,I);if(!U.keep)aJ.unshift(I);return z?I:Q}function uD0($,Y,U){let z=Y.unsafeCleanup?$N1:L4.rmdir.bind(L4),I=Y.unsafeCleanup?fD0:kD0,Q=xB(I,$,U),J=xB(z,$,U,Q);if(!Y.keep)aJ.unshift(Q);return U?Q:J}function xB($,Y,U,z){let I=!1;return function Q(J){if(!I){let K=z||Q,G=aJ.indexOf(K);if(G>=0)aJ.splice(G,1);if(I=!0,U||$===kD0||$===fD0)return $(Y);else return $(Y,J||function(){})}}}function KN1(){if(!xD0)return;while(aJ.length)try{aJ[0]()}catch($){}}function vD0($){let Y=[],U=null;try{U=_D0.randomBytes($)}catch(z){U=_D0.pseudoRandomBytes($)}for(let z=0;z<$;z++)Y.push("0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz"[U[z]%62]);return Y.join("")}function a8($){return typeof $>"u"}function tJ($,Y){if(typeof $==="function")return[{},$];if(a8($))return[{},Y];let U={};for(let z of Object.getOwnPropertyNames($))U[z]=$[z];return[U,Y]}function GN1($,Y,U){let z=C6.isAbsolute($)?$:C6.join(Y,$);L4.stat(z,function(I){if(I)L4.realpath(C6.dirname(z),function(Q,J){if(Q)return U(Q);U(null,C6.join(J,C6.basename(z)))});else L4.realpath(z,U)})}function HN1($,Y){let U=C6.isAbsolute($)?$:C6.join(Y,$);try{return L4.statSync(U),L4.realpathSync(U)}catch(z){let I=L4.realpathSync(C6.dirname(U));return C6.join(I,C6.basename(U))}}function bD0($){let Y=$.tmpdir;if(!a8($.name))return C6.join(Y,$.dir,$.name);if(!a8($.template))return C6.join(Y,$.dir,$.template).replace(gD0,vD0(6));let U=[$.prefix?$.prefix:"tmp","-",process.pid,"-",vD0(12),$.postfix?"-"+$.postfix:""].join("");return C6.join(Y,$.dir,U)}function en($,Y){if(typeof Y!=="string")throw Error(`${$} option must be a string, got "${typeof Y}".`);if(Y.includes(".."))throw Error("Relative value not allowed");return Y}function iD0($){if(!a8($.name)){let Y=$.name;if(C6.isAbsolute(Y))throw Error(`name option must not contain an absolute path, found "${Y}".`);let U=C6.basename(Y);if(U===".."||U==="."||U!==Y)throw Error(`name option must not contain a path, found "${Y}".`)}if(!a8($.template)){if(typeof $.template!=="string")throw Error(`template option must be a string, got "${typeof $.template}".`);if(!$.template.match(gD0))throw Error(`Invalid template, found "${$.template}".`)}if(!a8($.tries)&&isNaN($.tries)||$.tries<0)throw Error(`Invalid tries, found "${$.tries}".`);$.tries=a8($.name)?$.tries||3:1,$.keep=!!$.keep,$.detachDescriptor=!!$.detachDescriptor,$.discardDescriptor=!!$.discardDescriptor,$.unsafeCleanup=!!$.unsafeCleanup,$.prefix=a8($.prefix)?"":en("prefix",$.prefix),$.postfix=a8($.postfix)?"":en("postfix",$.postfix),$.template=a8($.template)?void 0:en("template",$.template)}function hD0($,Y,U,z){if(a8(Y))return z(null);GN1(Y,U,function(I,Q){if(I)return z(I);let J=C6.relative(U,Q);if(J.startsWith("..")||C6.isAbsolute(J))return z(Error(`${$} option must be relative to "${U}", found "${J}".`));z(null,J)})}function SD0($,Y,U){if(a8(Y))return;let z=HN1(Y,U),I=C6.relative(U,z);if(I.startsWith("..")||C6.isAbsolute(I))thrLine truncated
`)}let z=[];Y.forEach((I,Q)=>{let J=$.length+Q+1,K=Q===0?"⏳ ":"";z.push(`${K}${J}. ${I}`)});for(let I=$.length-1;I>=0;I--){let Q=I+1;z.push(`${Q}. ${$[I]}`)}return z.join(`
`)}function Vp($,Y,U,z,I){let Q=$?.operator||Y?.operator||U?.operator,J=Q?.name||Q?.id||U?.operatorName||"",K=($?.nodeName||Y?.fromNodeName||Y?.nodeName||U?.nodeName||"").trim();if(K==="合思审批节点"||K==="外部审批节点"||K.includes("合思审批")||K.includes("外部审批"))K="";if((!K||K==="提交人"||K==="审批节点")&&J&&z){let M=z.find((F)=>F.operator?.name===J&&F.nodeName&&F.nodeName.trim()!=="提交人"&&!F.isEbot&&F.rawAction!=="freeflow.reject");if(M?.nodeName)K=M.nodeName.trim()}let H=$?.comment||Y?.reason||U?.rejectComment||"修改";if(H.includes(":")){let M=H.split(":");if(M.length>1)H=M.slice(1).join(":").trim()}let W=H;if(K&&J)W=`${K}(${J}) ❌: ${H}`;else if(J)W=`${J} ❌: ${H}`;else if(K)W=`${K} ❌: ${H}`;else W=H;let X=$?.rejectTargetNodeName||Y?.targetNodeName||"提交人",Z=$?.rejectTargetOperator?.name||Y?.targetOperator?.name||I?.submitter?.name,q=Z?`${X}(${Z})`:X,V=$?.resubmitRuleText||Y?.resubmitRuleText||(J?`重新提交后由${J}继续审批`:"重新提交后继续审批");return{comment:`${W}
*/var F4=K0("fs"),mA=K0("os"),_6=K0("path"),pD0=K0("crypto"),E9={fs:F4.constants,os:mA.constants},rD0=/XXXXXX/,sD0=(E9.O_CREAT||E9.fs.O_CREAT)|(E9.O_EXCL||E9.fs.O_EXCL)|(E9.O_RDWR||E9.fs.O_RDWR),iN1=mA.platform()==="win32",cN1=E9.EBADF||E9.os.errno.EBADF,nN1=E9.ENOENT||E9.os.errno.ENOENT,tK=[],aD0=F4.rmdirSync.bind(F4),tD0=!1;function dN1($,Y){return F4.rm($,{recursive:!0},Y)}function eD0($){return F4.rmSync($,{recursive:!0})}function zd($,Y){let U=eK($,Y),I=U[0],Q=U[1];$D1(I,function(J,K){if(J)return Q(J);let z=K.tries;(function G(){try{let H=YB0(K);F4.stat(H,function(W){if(!W){if(z-- >0)return G();return Q(Error("Could not get a unique tmp filename, max tries reached "+H))}Q(null,H)})}catch(H){Q(H)}})()})}function Gd($){let Y=eK($),U=Y[0],I=YD1(U),Q=I.tries;do{let J=YB0(I);try{F4.statSync(J)}catch(K){return J}}while(Q-- >0);throw Error("Could not get a unique tmp filename, max tries reached")}function pN1($,Y){let U=eK($,Y),I=U[0],Q=U[1];zd(I,function(K,z){if(K)return Q(K);F4.open(z,sD0,I.mode||384,function(H,W){if(H)return Q(H);if(I.discardDescriptor)return F4.close(W,function(Z){return Q(Z,z,void 0,Jd(z,-1,I,!1))});else{let X=I.discardDescriptor||I.detachDescriptor;Q(null,z,W,Jd(z,X?-1:W,I,!1))}})})}function mN1($){let Y=eK($),U=Y[0],I=U.discardDescriptor||U.detachDescriptor,Q=Gd(U),J=F4.openSync(Q,sD0,U.mode||384);if(U.discardDescriptor)F4.closeSync(J),J=void 0;return{name:Q,fd:J,removeCallback:Jd(Q,I?-1:J,U,!0)}}function lN1($,Y){let U=eK($,Y),I=U[0],Q=U[1];zd(I,function(K,z){if(K)return Q(K);F4.mkdir(z,I.mode||448,function(H){if(H)return Q(H);Q(null,z,$B0(z,I,!1))})})}function oN1($){let Y=eK($),U=Y[0],I=Gd(U);return F4.mkdirSync(I,U.mode||448),{name:I,removeCallback:$B0(I,U,!0)}}function rN1($,Y){let U=function(I){if(I&&!Kd(I))return Y(I);Y()};if(0<=$[0])F4.close($[0],function(){F4.unlink($[1],U)});else F4.unlink($[1],U)}function sN1($){let Y=null;try{if(0<=$[0])F4.closeSync($[0])}catch(U){if(!UD1(U)&&!Kd(U))throw U}finally{try{F4.unlinkSync($[1])}catch(U){if(!Kd(U))Y=U}}if(Y!==null)throw Y}function Jd($,Y,U,I){let Q=pA(sN1,[Y,$],I),J=pA(rN1,[Y,$],I,Q);if(!U.keep)tK.unshift(Q);return I?Q:J}function $B0($,Y,U){let I=Y.unsafeCleanup?dN1:F4.rmdir.bind(F4),Q=Y.unsafeCleanup?eD0:aD0,J=pA(Q,$,U),K=pA(I,$,U,J);if(!Y.keep)tK.unshift(J);return U?J:K}function pA($,Y,U,I){let Q=!1;return function J(K){if(!Q){let z=I||J,G=tK.indexOf(z);if(G>=0)tK.splice(G,1);if(Q=!0,U||$===aD0||$===eD0)return $(Y);else return $(Y,K||function(){})}}}function aN1(){if(!tD0)return;while(tK.length)try{tK[0]()}catch($){}}function mD0($){let Y=[],U=null;try{U=pD0.randomBytes($)}catch(I){U=pD0.pseudoRandomBytes($)}for(let I=0;I<$;I++)Y.push("0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz"[U[I]%62]);return Y.join("")}function $$($){return typeof $>"u"}function eK($,Y){if(typeof $==="function")return[{},$];if($$($))return[{},Y];let U={};for(let I of Object.getOwnPropertyNames($))U[I]=$[I];return[U,Y]}function tN1($,Y,U){let I=_6.isAbsolute($)?$:_6.join(Y,$);F4.stat(I,function(Q){if(Q)F4.realpath(_6.dirname(I),function(J,K){if(J)return U(J);U(null,_6.join(K,_6.basename(I)))});else F4.realpath(I,U)})}function eN1($,Y){let U=_6.isAbsolute($)?$:_6.join(Y,$);try{return F4.statSync(U),F4.realpathSync(U)}catch(I){let Q=F4.realpathSync(_6.dirname(U));return _6.join(Q,_6.basename(U))}}function YB0($){let Y=$.tmpdir;if(!$$($.name))return _6.join(Y,$.dir,$.name);if(!$$($.template))return _6.join(Y,$.dir,$.template).replace(rD0,mD0(6));let U=[$.prefix?$.prefix:"tmp","-",process.pid,"-",mD0(12),$.postfix?"-"+$.postfix:""].join("");return _6.join(Y,$.dir,U)}function Qd($,Y){if(typeof Y!=="string")throw Error(`${$} option must be a string, got "${typeof Y}".`);if(Y.includes(".."))throw Error("Relative value not allowed");return Y}function UB0($){if(!$$($.name)){let Y=$.name;if(_6.isAbsolute(Y))throw Error(`name option must not contain an absolute path, found "${Y}".`);let U=_6.basename(Y);if(U===".."||U==="."||U!==Y)throw Error(`name option must not contain a path, found "${Y}".`)}if(!$$($.template)){if(typeof $.template!=="string")throw Error(`template option must be a string, got "${typeof $.template}".`);if(!$.template.match(rD0))throw Error(`Invalid template, found "${$.template}".`)}if(!$$($.tries)&&isNaN($.tries)||$.tries<0)throw Error(`Invalid tries, found "${$.tries}".`);$.tries=$$($.name)?$.tries||3:1,$.keep=!!$.keep,$.detachDescriptor=!!$.detachDescriptor,$.discardDescriptor=!!$.discardDescriptor,$.unsafeCleanup=!!$.unsafeCleanup,$.prefix=$$($.prefix)?"":Qd("prefix",$.prefix),$.postfix=$$($.postfix)?"":Qd("postfix",$.postfix),$.template=$$($.template)?void 0:Qd("template",$.template)}function lD0($,Y,U,I){if($$(Y))return I(null);tN1(Y,U,function(Q,J){if(Q)return I(Q);let K=_6.relative(U,J);if(K.startsWith("..")||_6.isAbsolute(K))return I(Error(`${$} option must be relative to "${U}", found "${K}".`));I(null,K)})}function oD0($,Y,U){if($$(Y))return;let I=eN1(Y,U),Q=_6.relative(U,I);if(Q.startsWith("..")||_6.isAbsolute(Q))thrLine truncated
`)}let I=[];Y.forEach((Q,J)=>{let K=$.length+J+1,z=J===0?"⏳ ":"";I.push(`${z}${K}. ${Q}`)});for(let Q=$.length-1;Q>=0;Q--){let J=Q+1;I.push(`${J}. ${$[Q]}`)}return I.join(`
`)}function Od($,Y,U,I,Q){let J=$?.operator||Y?.operator||U?.operator,K=J?.name||J?.id||U?.operatorName||"",z=($?.nodeName||Y?.fromNodeName||Y?.nodeName||U?.nodeName||"").trim();if(z==="合思审批节点"||z==="外部审批节点"||z.includes("合思审批")||z.includes("外部审批"))z="";if((!z||z==="提交人"||z==="审批节点")&&K&&I){let M=I.find((F)=>F.operator?.name===K&&F.nodeName&&F.nodeName.trim()!=="提交人"&&!F.isEbot&&F.rawAction!=="freeflow.reject");if(M?.nodeName)z=M.nodeName.trim()}let H=$?.comment||Y?.reason||U?.rejectComment||"修改";if(H.includes(":")){let M=H.split(":");if(M.length>1)H=M.slice(1).join(":").trim()}let W=H;if(z&&K)W=`${z}(${K}) ❌: ${H}`;else if(K)W=`${K} ❌: ${H}`;else if(z)W=`${z} ❌: ${H}`;else W=H;let X=$?.rejectTargetNodeName||Y?.targetNodeName||"提交人",Z=$?.rejectTargetOperator?.name||Y?.targetOperator?.name||Q?.submitter?.name,q=Z?`${X}(${Z})`:X,V=$?.resubmitRuleText||Y?.resubmitRuleText||(K?`重新提交后由${K}继续审批`:"重新提交后继续审批");return{comment:`${W}
↳ 驳回至: ${q}
↳ ${V}`,operator:Q}}function PA0($){if(!$)return[];let Y=$.pending||[],U=String($.rawState||"").toUpperCase(),z=String($.state||"").toUpperCase(),I=[];if(Y.length>0)for(let Q of Y){let J=Q.approver?.name||Q.approver?.id||"待定",K=(Q.name||$.currentNode||"").trim(),G=K?`${K}(${J})`:J,W=Q.type?.toUpperCase()==="PAYING"||K.includes("支付")||U==="PAYING"||z==="支付中"?"待支付":"待审批";I.push(`${G}: ${W}`)}else if($.currentNode?.trim()){let J=$.currentNode.includes("支付")||U==="PAYING"||z==="支付中"?"待支付":"待审批";I.push(`${$.currentNode.trim()}: ${J}`)}return I}function Xz($,Y){let U=new Map;if(!$||$.length===0)return U;if(!Y){for(let q of $){let w=(q.result||{}).decision||q.aiDecision||"-";U.set(q.id,{recordId:q.id,sourceDocumentSN:q.sourceDocumentSN,taskMode:q.taskMode,aiDecision:BA0(typeof w==="string"?w:"-"),aiAction:"-",eHumanAction:"-",eHumanComment:"-",auditDrift:!1})}return U}let z=[...$].sort((q,V)=>(Number(q.createdAt)||0)-(Number(V.createdAt)||0)),I=Y.history||[],Q=String(Y.rawState||"").toUpperCase(),J=String(Y.state||"").toUpperCase(),K=Q==="DRAFT"||Q==="REVOKED"||Q==="CANCELED"||Q==="CANCELLED"||J==="草稿"||J==="已撤回"||J==="已取消",G=Q==="REJECTED"||Q==="TERMINATED"||J==="审批驳回"||J==="已驳回",H=!K&&!G&&(Q==="PAID"||J==="已支付"||I.some((q)=>!q.isEbot&&(q.rawAction==="freeflow.pay"||q.action==="支付成功"||q.action==="支付完成"))),W=!K&&!G&&!H&&(Q==="PAYING"||J==="支付中"||(Y.pending||[]).some((q)=>q.isCurrent&&(q.type?.toUpperCase()==="PAYING"||q.name?.includes("支付")))||Y.currentNode?.includes("支付")===!0),Z=H||!K&&!G&&!W&&(Q==="COMPLETED"||Q==="APPROVED"||J==="已完成"||J==="审批通过");for(let q=0;q<z.length;q++){let V=z[q];if(!V)continue;let w=Number(V.createdAt)||0,M=V.document||{},F=V.manualApprovalRecord||V.result?.manualApprovalRecord||M.manualApprovalRecord||{},N=typeof V.sourceExtendData?.nodeId==="string"?String(V.sourceExtendData.nodeId):void 0,O=typeof F.nodeId==="string"?String(F.nodeId):void 0,D=O?decodeURIComponent(O).replace(/^hcnode_/,"").replace(/_r\d+$/,""):void 0,P=N||D,T=P?I.find((D0)=>D0.nodeId&&(D0.nodeId===P||P.includes(D0.nodeId))):void 0,A=T?.time??w,j=z[q+1],C=j?Number(j.createdAt)||1/0:1/0,b=q===z.length-1,x=I.find((D0)=>(D0.time??0)>A+5000&&D0.isEbot&&(D0.nodeName?.includes("智能")||D0.nodeName?.includes("AI")||D0.action?.includes("智能")||D0.comment?.includes("AI")||D0.comment?.includes("approval-result"))&&!D0.nodeName?.includes("费用标准检查")&&!D0.nodeName?.includes("标准检查")&&!D0.nodeName?.includes("预算"));if(x){if(b=!1,(x.time??1/0)<C)C=x.time}let g=V.result||{},i=g.decision||V.aiDecision||"-",c=typeof i==="string"?i:"-",z0=c.toUpperCase(),k=z0==="REJECT"||z0==="驳回",d=z0==="APPROVE"||z0==="通过",a=z0==="EXEMPT_APPROVE"||z0==="免审通过"||z0==="备注通过",$0=V.taskMode||V.finalExecutionMode||"",p=String($0).toLowerCase().includes("auto")||V.finalExecutionMode==="automatic"||$0==="automatic"||$0==="fully_automatic",Y0="-";if(d||a)Y0="添加评论";else if(k)Y0=p?"驳回":"添加评论";else if(z0==="REVIEW"||z0==="转交复核")Y0="转交复核";let R=typeof F.status==="object"&&F.status!==null?String(F.status.type||F.status.label||"").toUpperCase():"",o=typeof F.status==="object"&&F.status!==null?String(F.status.sourceStatus||""):"",e=M.manualApprovalStatus||g.manualApprovalStatus||V.manualApprovalStatus,O0=typeof e==="string"?e.toUpperCase():"",T0=O0==="CANCELLED"||O0==="CANCELED"||O0==="已取消"||O0==="已撤回"||O0==="REVOKED"||R==="CANCELLED"||R==="CANCELED"||o.includes("撤回")||o.includes("取消"),y0=O0==="APPROVED"||O0==="已支付/审批完成"||O0==="已通过"||O0==="已完成"||O0==="已支付"||R==="APPROVED",o0=!(o.includes("补偿")||o.includes("已支付"))&&(O0==="TERMINATED"||O0==="REJECTED"||O0==="REJECT"||O0==="已驳回"||O0==="被驳回"||R==="TERMINATED"||R==="REJECTED"||R==="已驳回"||R==="被驳回"),q1=T?1000:60000,t=I.filter((D0)=>{let I0=D0.time??0;return I0>=A-q1&&I0<C}),X0="-",F0="-",u0=!1,b0,c0,P1=d||a,k1=I.filter((D0)=>(D0.time??0)>A+5000),u1=k1.some((D0)=>D0.rawAction==="freeflow.retract"||D0.action==="单据撤回"),b1=k1.some((D0)=>D0.rawAction==="freeflow.submit"||D0.action==="提交送审");if(P1&&b&&(u1||b1))u0=!0,b0="AI通过后单据发生撤回/修改重提,后续未经AI复审";if(p&&k)X0="无操作",F0="-";else{let D0=t.filter((h)=>(h.time??0)>=A-1000&&!h.isEbot&&h.rawAction!=="freeflow.submit"&&h.action!=="提交送审"&&!((h.rawAction==="freeflow.comment"||h.action==="发表评论")&&!h.comment)&&!((h.rawAction==="freeflow.print"||h.action==="打印提醒")&&!h.comment)&&!(h.rawAction==="freeflow.carbonCopy"||h.rawAction==="freeflow.cc"||h.action==="抄送通知")),I0=D0.find((h)=>h.rawAction==="freeflow.retract"||h.action==="单据撤回"),B=D0.find((h)=>h.rawAction==="freeflow.reject"||h.action==="审批驳回");if(!b)if(B||!Y&&o0){X0="审批驳回",u0=!1,b0=void 0;let h=Vp(B,void 0,F,I,Y);F0=h.comme Line truncated
`,{mode:384}),Y}function Tp($){let Y=pA0();for(let U of Y){if(!F$(U))continue;for(let z of tB(U).filter((I)=>I.endsWith(".json")).filter((I)=>!I.startsWith("example."))){let I=j9(U,z);try{let Q=$P(I,"utf-8"),J=JSON.parse(Q);if(J&&typeof J==="object"&&J.id===$)return I}catch{}}}return}function E9($,Y){let U=Tp($);if(!U)throw Error(`Enterprise config not found: ${$}`);let I={...JSON.parse($P(U,"utf-8")),...Y};for(let J of Object.keys(Y))if(Y[J]===void 0)delete I[J];let Q=hZ.parse(I);return fA0(U,`${JSON.stringify(Q,null,2)}
`,"utf-8"),Q}var Pp="SEAL_USE_ENTERPRISES_DIR",uA0="SEAL_HOME_ENTERPRISES_DIR",bA0="SEAL_USE_USER_ENTERPRISES_DIR",iA0="SEAL_HOME_USER_ENTERPRISES_DIR",cA0="SEAL_USE_CONFIG_FILE",nA0="SEAL_HOME_CONFIG_FILE",UK,eB,aB,kA0;var T5=m(()=>{sB();UK=j9(YP(),".config","seal-use","enterprises"),eB=j9(YP(),".config","seal-home","enterprises"),aB=j9(YP(),".config","seal-use","config.json"),kA0=j9(YP(),".config","seal-home","config.json")});function n2($,Y,U=[]){let z=Y.corpId?.trim()||void 0,I=Y.stateful?Y.defaultCorpId?.trim()||void 0:void 0,Q=z??I;if(Q){let K=$.find((W)=>W.id===Q);if(K)return K;let G=$.find((W)=>W.id.toLowerCase()===Q.toLowerCase());if(G)return G;let H=$.find((W)=>W.name.toLowerCase()===Q.toLowerCase());if(H)return H;throw Error(`No enterprise config found for ${Q}`)}if(!Y.stateful)throw Error("Stateless mode is enabled. Every enterprise command requires --corp <corpId>. Use `seal-use config mode stateful` to enable a default enterprise.");let J=$[0];if(J)return J;throw Error("No enterprise config found. Add a non-example JSON file under one of: "+(U.length?U.join(", "):"the configured enterprise directories"))}import{existsSync as jp,mkdirSync as dD1,readFileSync as mD1,renameSync as lD1,unlinkSync as oD1,writeFileSync as rD1}from"node:fs";import{homedir as sD1}from"node:os";import{dirname as aD1,join as tD1}from"node:path";function gZ(){let $=process.env[eD1]?.trim();if($)return $;return $A1}function mA0($=new Date){return $.toISOString().slice(0,10)}function lA0($=Ep,Y=new Date){let U=Y.getTime()-Math.max(0,$-1)*86400000;return new Date(U).toISOString().slice(0,10)}function oA0($=gZ()){if(!jp($))return{};try{let Y=mD1($,"utf-8"),U=JSON.parse(Y);if(U&&typeof U==="object"&&!Array.isArray(U))return U;return{}}catch{return{}}}function YA1($,Y){let U={};for(let[z,I]of Object.entries($)){if(!I||typeof I!=="object")continue;let Q={},J=!1;for(let[K,G]of Object.entries(I))if(typeof G==="number"&&G>0&&K>=Y)Q[K]=G,J=!0;if(J)U[z]=Q}return U}function UA1($,Y=gZ()){let U=aD1(Y);if(!jp(U))dD1(U,{recursive:!0,mode:448});let z=`${Y}.${process.pid}.${Date.now()}.${Math.random().toString(16).slice(2,8)}.tmp`;try{rD1(z,JSON.stringify($,null,2),{encoding:"utf-8",mode:384}),lD1(z,Y)}catch(I){try{if(jp(z))oD1(z)}catch{}throw I}}function rA0($,Y=new Date){if(!$||typeof $!=="string")return;try{let U=gZ(),z=oA0(U),I=mA0(Y),Q=lA0(Ep,Y),J=YA1(z,Q);J[$]=J[$]||{},J[$][I]=(J[$][I]??0)+1,UA1(J,U)}catch{}}function zA1($,Y=Ep,U=new Date){let z=new Map;try{let I=oA0(),Q=lA0(Y,U),J=mA0(U),K=$??Object.keys(I);for(let G of K){let H=I[G];if(!H){z.set(G,0);continue}let W=0;for(let[X,Z]of Object.entries(H))if(X>=Q&&X<=J&&typeof Z==="number")W+=Z;z.set(G,W)}}catch{if($)for(let I of $)z.set(I,0)}return z}function sA0($,Y,U){let z=U??zA1($.map((I)=>I.id));return[...$].sort((I,Q)=>{if(Y){if(I.id===Y&&Q.id!==Y)return-1;if(Q.id===Y&&I.id!==Y)return 1}let J=z.get(I.id)??0,K=z.get(Q.id)??0;if(J!==K)return K-J;let G=I.name??I.id,H=Q.name??Q.id,W=G.localeCompare(H,"zh-CN");if(W!==0)return W;return I.id.localeCompare(Q.id)})}var eD1="SEAL_USE_USAGE_FILE",$A1,Ep=7;var UP=m(()=>{$A1=tD1(sD1(),".config","seal-use","usage.json")});function IA1($,Y){return $.map((U)=>U.trim()).filter(Boolean).map((U)=>Y?U:U.toLowerCase())}function QA1($,Y){return Y?$:$.toLowerCase()}function JA1($,Y,U,z){let I=QA1($,z),Q=Y.filter((J)=>I.includes(J));if(U==="all"&&Q.length!==Y.length)return[];return Q}function KA1($){if(typeof $==="string")return $.split(/\r?\n/);return JSON.stringify($,null,2).split(/\r?\n/)}function GA1($,Y){if(Y.fields&&!Y.fields.has($.field))return[];let U=KA1($.value),z=[];return U.forEach((I,Q)=>{let J=JA1(I,Y.keywords,Y.matchMode,Y.caseSensitive);if(J.length===0)return;let K=Math.max(0,Q-Y.contextLines),G=Math.min(U.length,Q+Y.contextLines+1),H={area:$.area,entityType:$.entityType,entityId:$.entityId,title:$.title,field:$.field,lineNumber:Q+1,matchedKeywords:J,matchedText:zP(I,Y.maxChars),context:{before:Y.snippetOnly?[]:U.slice(K,Q).map((W)=>zP(W,Y.maxChars)),line:zP(I,Y.maxChars),after:Y.snippetOnly?[]:U.slice(Q+1,G).map((W)=>zP(W,Y.maxChars))},metadata:$.metadata};if(Y.snippetOnly)H.context={before:[],line:H.context.line,after:[]};z.push(H)}),z}function zP($,Y){if(!Y||$.length<=Y)return $;return`${$.slice(0,Math.max(0,Y))}...`}function HA1($){return[{area:"rules",entityType:"rule",entityId:$.id,title:$.scope,field:"description",value:$.description,metadata:{scope:$.scope,strictness:$.strictness,status:$.status}},{area:"rules",entityType:"rule",entityId:$.id,title:$.scope,field:"scope",value:$.scope,metadata:{strictness:$.strictness,status:$.status}}]}function tA0($){return $.rules.flatMap((Y,U)=>{let z=`${$.id}:${Y.description.slice(0,32)}`,I={versionId:$.id,versionNumber:$.versionNumber,versionName:$.versionName,publishedByName:$.publishedByName,publishedAt:$.publishedAt,scope:Y.scope,strictness:Y.strictness,code:"code"in Y?Y.code:void 0,index:U};return[{area:"rules",entityType:"rule",entityId:z,title:`${$.versionName} / ${Y.scope}`,field:"hi Line truncated
`):[]}function FA1($,Y){let U=Array.from({length:$.length+1},()=>Array(Y.length+1).fill(0));for(let J=$.length-1;J>=0;J-=1)for(let K=Y.length-1;K>=0;K-=1)U[J][K]=$[J]===Y[K]?U[J+1][K+1]+1:Math.max(U[J+1][K],U[J][K+1]);let z=[],I=0,Q=0;while(I<$.length&&Q<Y.length)if($[I]===Y[Q])z.push(` ${$[I]}`),I+=1,Q+=1;else if(U[I+1][Q]>=U[I][Q+1])z.push(`-${$[I++]}`);else z.push(`+${Y[Q++]}`);while(I<$.length)z.push(`-${$[I++]}`);while(Q<Y.length)z.push(`+${Y[Q++]}`);return z}function wA1($,Y,U,z,I,Q){let J=UB0(z,Q),K=UB0(I,Q),G=z?`a/rules/${$}`:"/dev/null",H=I?`b/rules/${$}`:"/dev/null";return[`diff --git a/rules/${$} b/rules/${$}`,`--- ${G} v${Y.versionNumber}`,`+++ ${H} v${U.versionNumber}`,`@@ -${J.length?1:0},${J.length} +${K.length?1:0},${K.length} @@`,...FA1(J,K)].join(`
`)}function zB0($){return{id:$.id,versionNumber:$.versionNumber,versionName:$.versionName,publishedAt:$.publishedAt}}function IB0($,Y){let U=new Map;for(let z of $.rules){let I=yZ(z),Q=Y==="stable-id"?JB0(I):kZ(I.code??I.ruleCode);if(!Q)throw Error(`Rule version ${$.versionNumber} contains a rule without a ${Y==="stable-id"?"stable rule ID":"code"}.`);if(U.has(Q))throw Error(`Rule version ${$.versionNumber} contains duplicate ${Y==="stable-id"?"stable rule ID":"code"}: ${Q}`);U.set(Q,I)}return U}function MA1($,Y,U){if(U!=="auto")return U;if([...$.rules,...Y.rules].every((Q)=>Boolean(JB0(Q))))return"stable-id";if([...$.rules,...Y.rules].every((Q)=>Boolean(kZ(yZ(Q).code??yZ(Q).ruleCode))))return"code";throw Error("Rule snapshots have neither a complete stable-ID mapping nor a complete code mapping.")}function KB0($,Y,U={}){let z=MA1($,Y,U.identityMode??"auto"),I=IB0($,z),Q=IB0(Y,z),J=[...new Set([...I.keys(),...Q.keys()])],K=[],G={added:0,removed:0,modified:0,unchanged:0},H=zB0($),W=zB0(Y);for(let Z of J){let q=I.get(Z),V=Q.get(Z),w=q?Vz(q,z):void 0,M=V?Vz(V,z):void 0,F=!q?"added":!V?"removed":JSON.stringify(w)!==JSON.stringify(M)?"modified":"unchanged";if(G[F]+=1,F==="unchanged"&&!U.includeUnchanged)continue;let N=F==="modified"?[...new Set([...Object.keys(w??{}),...Object.keys(M??{})])].filter((O)=>JSON.stringify(w?.[O])!==JSON.stringify(M?.[O])):void 0;K.push({status:F,ruleId:Z,identityMode:z,...q?{before:q}:{},...V?{after:V}:{},...N?.length?{changedFields:N}:{},...F!=="unchanged"?{diff:wA1(Z,H,W,q,V,z)}:{}})}let X={from:H,to:W,identityMode:z,counts:G,changes:K,unifiedDiff:K.filter((Z)=>Z.diff).map((Z)=>Z.diff).join(`
`)};if(z==="code"){let Z=J.filter((P)=>I.has(P)&&Q.has(P)).length,q=J.filter((P)=>I.has(P)&&Q.has(P)&&JSON.stringify(Vz(I.get(P),"code"))===JSON.stringify(Vz(Q.get(P),"code"))).length,V=I.size,w=Q.size,M=Math.min(V,w)?Z/Math.min(V,w):1,F=new Map;for(let[P,T]of I)F.set(JSON.stringify(Vz(T,"code")),P);let N=0;for(let[P,T]of Q){let A=F.get(JSON.stringify(Vz(T,"code")));if(A&&A!==P)N+=1}let D=(Math.min(V,w)?q/Math.min(V,w):1)>=0.5?"high":q>0||N>0?"ambiguous":"low";X.codeStats={oldCount:V,newCount:w,sameCodeCount:Z,sameCodeUnchanged:q,sameBodyDifferentCode:N,overlapRatio:M,confidence:D,warning:"Published snapshots do not carry stable IDs; code matching can report reorderings as remove/add or modified rules."}}return X}function Rp($,Y=20000,U=!1){if(U||$.unifiedDiff.length<=Y)return{...$,truncation:{truncated:!1,maxChars:Y,omittedChars:0,hint:"Use --full only when the complete diff is required."}};let z=$.unifiedDiff.length-Y,I=`
... [diff truncated: ${z} characters omitted; rerun with --full for the complete diff]`,Q=$.changes.map(({before:J,after:K,diff:G,...H})=>({...H,...G?{diff:G.length>Y?`${G.slice(0,Y)}${I}`:G}:{}}));return{...$,changes:Q,unifiedDiff:`${$.unifiedDiff.slice(0,Y)}${I}`,truncation:{truncated:!0,maxChars:Y,omittedChars:z,hint:"Use --full for the complete diff."}}}var QB0,LA1;var GB0=m(()=>{QB0=["id","ruleId","stableId"],LA1=new Set([...QB0,"runtimeRuleId","runtimeId","tenantId","createdAt","updatedAt","versionId","versionNumber"])});import{existsSync as OA1,mkdirSync as NA1,readFileSync as DA1,renameSync as AA1,writeFileSync as BA1}from"node:fs";import{homedir as PA1}from"node:os";import{join as HB0}from"node:path";function xZ($){if($===void 0||$===null)return;let Y=String($).trim().toLowerCase().replace(/^rule[-_:]?/,"").replace(/^#/,"");if(!Y)return;return/^\d+$/.test(Y)?String(Number(Y)):Y}function IP($){return JSON.stringify([$.description??"",$.scope??"",$.strictness??""])}function WB0(){return process.env.SEAL_USE_RULE_VERSION_SNAPSHOTS_DIR?.trim()||HB0(PA1(),".config","seal-use","rule-version-snapshots")}function TA1($){return $.replace(/[^a-zA-Z0-9._-]/g,"_")}function XB0($,Y){return HB0(WB0(),`${TA1($)}-v${Y}.json`)}function fZ($,Y,U){let z=new Map,I=new Map;for(let W of U){let X=xZ(W.code);if(X)z.set(X,[...z.get(X)??[],W]);let Z=IP(W);I.set(Z,[...I.get(Z)??[],W])}let Q=[];for(let W of Y.rules??[]){let X=xZ(W.code),Z=X?z.get(X)??[]:[],q=I.get(IP(W))??[],V=Z.length===1?Z[0]:q.length===1?q[0]:void 0;if(!V)continue;Q.push({stableId:V.id,...W.code!==void 0?{code:W.code}:{},description:W.description,scope:W.scope,strictness:W.strictness})}let J={corpId:$,versionId:Y.id,versionNumber:Y.versionNumber,capturedAt:new Date().toISOString(),rules:Q},K=WB0();NA1(K,{recursive:!0,mode:448});let G=XB0($,Y.versionNumber),H=`${G}.${process.pid}.tmp`;return BA1(H,`${JSON.stringify(J,null,2)}
`,{encoding:"utf8",mode:384}),AA1(H,G),G}function jA1($,Y){let U=XB0($,Y.versionNumber);if(!OA1(U))return null;try{return JSON.parse(DA1(U,"utf8"))}catch{return null}}function _p($,Y){let U=jA1($,Y);if(!U?.rules.length)return Y;let z=new Map(U.rules.flatMap((Q)=>{let J=xZ(Q.code);return J?[[J,Q]]:[]})),I=new Map(U.rules.map((Q)=>[IP(Q),Q]));return{...Y,rules:Y.rules.map((Q)=>{if(Q.id!==void 0||Q.ruleId!==void 0||Q.stableId!==void 0)return Q;let J=(xZ(Q.code)?z.get(xZ(Q.code)):void 0)??I.get(IP(Q));return J?{...Q,stableId:J.stableId}:Q})}}var vp=()=>{};import{createHmac as EA1,randomBytes as CA1}from"node:crypto";function RA1($,Y,U,z){return EA1("sha256",z).update(`${$}.${Y}.${JSON.stringify(U)}`).digest("hex")}function uZ($,Y){let U=Math.floor(Date.now()/1000),z=CA1(16).toString("hex");return{Authorization:`Bearer ${Y}`,"x-webhook-signature":RA1(U,z,$,Y),"x-webhook-timestamp":String(U),"x-webhook-nonce":z}}var QP=()=>{};function h4($,Y){return new W4($,2,Y)}function w$($,Y){return new W4($,10,Y)}function bZ($){if($ instanceof W4)return{exitCode:$.exitCode,nextAction:$.nextAction};let Y=$ instanceof Error?$.message:String($),U=_A1($);if(U===401||U===403||/(?:^|\s)(?:token|bearer|session) (?:expired|missing|invalid)/i.test(Y))return{exitCode:11};if(/^(?:Usage:|Unknown (?:[a-z0-9_-]+ )?command|Invalid (?:number|boolean|command)|--json must|Missing required JSON field)/i.test(Y))return{exitCode:2};if(/^Refusing to (?:clear|delete)|without --yes|without confirm=true/i.test(Y))return{exitCode:10};return{exitCode:1}}function _A1($){if(!$||typeof $!=="object")return;let Y=$.response;if(!Y||typeof Y!=="object")return;let U=Y.status;return typeof U==="number"?U:void 0}var W4,JP;var O8=m(()=>{W4=class W4 extends Error{exitCode;nextAction;constructor($,Y,U){super($);this.name="CliError",this.exitCode=Y,this.nextAction=U}};JP=class JP extends W4{constructor($,Y){super($,12,Y);this.name="PayloadTooLargeError"}}});function ZB0($,Y){let U=$&&typeof $==="object"?$:{},z=typeof U.type==="string"?U.type.toUpperCase().trim():"",I=typeof U.key==="string"&&U.key.trim()?U.key.trim():typeof U.label==="string"&&U.label.trim()?U.label.trim():`field_${Y}`,Q=typeof U.label==="string"&&U.label.trim()?U.label.trim():I,J=U.value!==void 0?U.value:null;if(z==="LIST"&&Array.isArray(J))J=J.map((G)=>{if(Array.isArray(G))return G.map((H,W)=>ZB0(H,W));return G});let K=z;if(!vA1.has(K))if(Array.isArray(J))K="LIST";else if(J&&typeof J==="object")K="OBJECT";else if(typeof J==="number")K="NUMBER";else K="TEXT";return{key:I,label:Q,type:K,value:J}}function hp($,Y={}){let U=$.document,z=$.sourceDocumentSN??(typeof U?.sn==="string"?U.sn:void 0)??(typeof U?.sourceDocumentSN==="string"?U.sourceDocumentSN:void 0)??$.id,I=$.sourceDocumentId??(typeof U?.id==="string"?U.id:void 0)??(typeof U?.sourceDocumentId==="string"?U.sourceDocumentId:void 0)??$.documentId??$.id,Q=Y.snPrefix??"",J=Y.snSuffix??"",K=Y.docIdPrefix??Q,G=Y.docIdSuffix??J,H=`${Q}${z}${J}`,W=`${K}${I}${G}`,X=typeof U?.sourceStartTime==="number"?U.sourceStartTime:typeof $.createdAt==="number"?Math.floor($.createdAt/1000):null,q=(Array.isArray(U?.fields)?U.fields:[]).map((V,w)=>ZB0(V,w));return{type:"document",documentId:W,documentSN:H,startTime:X,fields:q}}function hA1($){let Y=new URL($),U=Y.pathname.match(/\/webhook\/([^/]+)/);if(!U)throw Error(`Webhook URL 必须包含 /webhook/{webhookId}/document,收到: ${$}`);let z=U[1],I=`${Y.protocol}//${Y.host}`,Q=`${I}/api/v1/integrations/webhook/${encodeURIComponent(z)}/document`;return{baseUrl:I,webhookId:z,documentEndpoint:Q}}async function Sp($,Y,U,z=fetch,I={}){let{webhookId:Q,documentEndpoint:J}=hA1($),K={...I,"Content-Type":"application/json",...uZ({webhookId:Q,...U},Y)},G=await z(J,{method:"POST",headers:K,body:JSON.stringify(U)});if(!G.ok){let H=await G.text();throw Error(`Webhook 单据推送失败 (${G.status}): ${H}`)}return G.json()}function qB0($,Y,U){if(Y){let z=Y.trim().toLowerCase(),I=$.find((Q)=>Q.id.toLowerCase()===z||Q.name.toLowerCase()===z||Q.incomingDocumentWebhook.id.toLowerCase()===z);if(!I){let Q=$.map((J)=>`"${J.name}" (${J.id})`).join(", ");throw Error(`未找到匹配 "${Y}" 的 Webhook 集成通道。可用通道: [${Q}]`)}return I}if($.length===1)return $[0];if($.length>1){let z=$.find((Q)=>Q.name.includes("回放")||Q.name.toLowerCase().includes("replay"));if(z)return z;let I=$.map((Q)=>`"${Q.name}" (${Q.id})`).join(", ");throw Error(`当前租户存在多个 Webhook 通道 [${I}],请通过 --webhook <idOrName> 指定目标通道。`)}throw new W4("当前租户未配置任何 Webhook 集成通道。",1,`seal-use webhook add --name <name> --result-url <url>${U?` --corp ${U}`:""}`)}function KP($,Y){let U,z,{sourceCorpId:I,targetCorpId:Q,activeCorp:J,force:K}=$;if(I&&Q)U=Y(I),z=Y(Q);else if(I&&!Q)if(U=Y(I),U.testCorpId)z=Y(U.testCorpId);else if(J.id!==U.id&&J.environment==="test")z=J;else z=J;else if(!I&&Q)if(z=Y(Q),z.prodCorpId)U=Y(z.prodCorpId);else if(J.id!==z.id)U=J;else U=J;else if(J.environment==="test")if(z=J,J Line truncated
`+"为防止测试单据污染生产审批流,禁止向生产环境重放单据。请指定测试企业 (--target-corp <testCorpId>),或在确有需要时添加 --force。",1,`seal-use webhook replay --target-corp <testCorpId>${U.id!==z.id?` --source-corp ${U.id}`:""}`);return{sourceCorp:U,targetCorp:z}}async function gp($,Y,U){let z=Y.seal?.endpoints?.approvalStylePreferences??"api/v1/agent/ai-approval/config",I=await K$($,z);if(U||I.length>0)return qB0(I,U,Y.id);if(Y.environment==="test"||Y.id.toLowerCase().includes("test")){console.error(`[webhook-replay] 测试企业「${Y.name}」未配置 Webhook 通道,正在自动创建「(Seal测-回放通道)」...`);let Q=(Y.seal.url??Y.source?.sealUrl??`https://${Y.id.toLowerCase()}.sealai.cc`).replace(/\/+$/,"");return await _M($,Q,{name:"(Seal测-回放通道)",mode:"assisted",outgoingResultWebhook:`${Q}/api/v1/integrations/webhook/replay-mock-callback`},Y.seal.endpoints.approvalStylePreferences)}throw new W4(`当前租户「${Y.name}」未配置任何 Webhook 集成通道。`,1,`seal-use webhook add --name <name> --result-url <url> --corp ${Y.id}`)}async function zK($){let{query:Y,sourceClient:U,targetClient:z,sourceCorp:I,targetCorp:Q,webhookSelector:J,snPrefix:K,snSuffix:G,docIdPrefix:H,docIdSuffix:W,dryRun:X,fetchFn:Z=fetch}=$,q=[];if(Y.recordId){let P=await H4(U,Y.recordId);q.push(P)}else if(Y.recordIds&&Y.recordIds.length>0)for(let P of Y.recordIds)q.push(await H4(U,P));else if(Y.sn){let T=(await i4(U,{search:Y.sn,sourceDocumentSN:Y.sn,limit:20})).records.find((A)=>A.sourceDocumentSN===Y.sn||A.sourceDocumentId===Y.sn||A.document?.sourceDocumentSN===Y.sn||A.document?.sn===Y.sn);if(!T)throw Error(`在企业「${I.name}」中未找到单据编号为「${Y.sn}」的审批记录。`);q.push(T)}else if(Y.sns&&Y.sns.length>0)for(let P of Y.sns){let A=(await i4(U,{search:P,sourceDocumentSN:P,limit:20})).records.find((j)=>j.sourceDocumentSN===P||j.sourceDocumentId===P||j.document?.sourceDocumentSN===P||j.document?.sn===P);if(!A)throw Error(`在企业「${I.name}」中未找到单据编号为「${P}」的审批记录。`);q.push(A)}else if(Y.limit!==void 0){let P=await i4(U,{limit:Y.limit,status:Y.status,startDate:Y.startDate,endDate:Y.endDate});if(!P.records.length)throw Error(`在企业「${I.name}」中未检索到符合条件的审批记录。`);q=P.records}else throw Error("Usage: seal-use webhook replay <recordId> [--sn <documentSN>] [--limit <n>] [--webhook <idOrName>] [--source-corp <corpId>] [--target-corp <corpId>] [--dry-run]");let V=q.map((P)=>({run:P,doc:hp(P,{snPrefix:K,snSuffix:G,docIdPrefix:H,docIdSuffix:W})}));if(X){let P={id:"preview-webhook",name:J??"预览目标通道",mode:"assisted",incomingDocumentWebhookUrl:`${Q.seal.url}/api/v1/integrations/webhook/preview`};try{let j=await K$(z,Q.seal.endpoints.approvalStylePreferences);if(j.length>0){let C=qB0(j,J,Q.id);P={id:C.id,name:C.name,mode:C.mode,incomingDocumentWebhookUrl:C.incomingDocumentWebhook.url}}}catch{}let T=V.map(({run:j,doc:C})=>({originalRecord:{id:j.id,sourceSystem:j.sourceSystem,sourceDocumentSN:j.sourceDocumentSN,sourceDocumentId:j.sourceDocumentId},document:C,success:!0})),A=T.length===1;return{dryRun:!0,success:!0,sourceCorp:{id:I.id,name:I.name,environment:I.environment},targetCorp:{id:Q.id,name:Q.name,environment:Q.environment},targetWebhook:P,totalCount:T.length,successCount:T.length,failureCount:0,originalRecord:A?T[0].originalRecord:void 0,document:A?T[0].document:void 0,records:T}}let w=await gp(z,Q,J),M={id:w.id,name:w.name,mode:w.mode,incomingDocumentWebhookUrl:w.incomingDocumentWebhook.url},F=[],N=0,O=0;for(let{run:P,doc:T}of V){console.error(`[webhook-replay] 正在向 Webhook 通道「${w.name}」推送单据: ${T.documentSN}...`);try{let A=await Sp(w.incomingDocumentWebhook.url,w.secret,T,Z,A6(Q.seal));F.push({originalRecord:{id:P.id,sourceSystem:P.sourceSystem,sourceDocumentSN:P.sourceDocumentSN,sourceDocumentId:P.sourceDocumentId},replayedDocument:{documentSN:T.documentSN,documentId:T.documentId,fieldCount:T.fields.length},pushResult:A,success:!0}),N+=1}catch(A){let j=A instanceof Error?A.message:String(A);F.push({originalRecord:{id:P.id,sourceSystem:P.sourceSystem,sourceDocumentSN:P.sourceDocumentSN,sourceDocumentId:P.sourceDocumentId},replayedDocument:{documentSN:T.documentSN,documentId:T.documentId,fieldCount:T.fields.length},error:j,success:!1}),O+=1}}let D=F.length===1;return{success:O===0,dryRun:!1,sourceCorp:{id:I.id,name:I.name,environment:I.environment},targetCorp:{id:Q.id,name:Q.name,environment:Q.environment},targetWebhook:M,totalCount:F.length,successCount:N,failureCount:O,originalRecord:D?F[0].originalRecord:void 0,replayedDocument:D?F[0].replayedDocument:void 0,pushResult:D?F[0].pushResult:void 0,records:F}}var vA1;var iZ=m(()=>{QP();O8();X6();vA1=new Set(["TEXT","NUMBER","DATE","AMOUNT","PERSON","ATTACHMENT","DATE_RANGE","DEPARTMENT","LIST","CITY","OBJECT"])});var VB0,p44,SA1,d44;var LB0=m(()=>{T$();VB0=L.object({level:L.enum(["error","warning" Line truncated
↳ ${V}`,operator:J}}function uB0($){if(!$)return[];let Y=$.pending||[],U=String($.rawState||"").toUpperCase(),I=String($.state||"").toUpperCase(),Q=[];if(Y.length>0)for(let J of Y){let K=J.approver?.name||J.approver?.id||"待定",z=(J.name||$.currentNode||"").trim(),G=z?`${z}(${K})`:K,W=J.type?.toUpperCase()==="PAYING"||z.includes("支付")||U==="PAYING"||I==="支付中"?"待支付":"待审批";Q.push(`${G}: ${W}`)}else if($.currentNode?.trim()){let K=$.currentNode.includes("支付")||U==="PAYING"||I==="支付中"?"待支付":"待审批";Q.push(`${$.currentNode.trim()}: ${K}`)}return Q}function ZI($,Y){let U=new Map;if(!$||$.length===0)return U;if(!Y){for(let q of $){let w=(q.result||{}).decision||q.aiDecision||"-";U.set(q.id,{recordId:q.id,sourceDocumentSN:q.sourceDocumentSN,taskMode:q.taskMode,aiDecision:fB0(typeof w==="string"?w:"-"),aiAction:"-",eHumanAction:"-",eHumanComment:"-",auditDrift:!1})}return U}let I=[...$].sort((q,V)=>(Number(q.createdAt)||0)-(Number(V.createdAt)||0)),Q=Y.history||[],J=String(Y.rawState||"").toUpperCase(),K=String(Y.state||"").toUpperCase(),z=J==="DRAFT"||J==="REVOKED"||J==="CANCELED"||J==="CANCELLED"||K==="草稿"||K==="已撤回"||K==="已取消",G=J==="REJECTED"||J==="TERMINATED"||K==="审批驳回"||K==="已驳回",H=!z&&!G&&(J==="PAID"||K==="已支付"||Q.some((q)=>!q.isEbot&&(q.rawAction==="freeflow.pay"||q.action==="支付成功"||q.action==="支付完成"))),W=!z&&!G&&!H&&(J==="PAYING"||K==="支付中"||(Y.pending||[]).some((q)=>q.isCurrent&&(q.type?.toUpperCase()==="PAYING"||q.name?.includes("支付")))||Y.currentNode?.includes("支付")===!0),Z=H||!z&&!G&&!W&&(J==="COMPLETED"||J==="APPROVED"||K==="已完成"||K==="审批通过");for(let q=0;q<I.length;q++){let V=I[q];if(!V)continue;let w=Number(V.createdAt)||0,M=V.document||{},F=V.manualApprovalRecord||V.result?.manualApprovalRecord||M.manualApprovalRecord||{},N=typeof V.sourceExtendData?.nodeId==="string"?String(V.sourceExtendData.nodeId):void 0,O=typeof F.nodeId==="string"?String(F.nodeId):void 0,D=O?decodeURIComponent(O).replace(/^hcnode_/,"").replace(/_r\d+$/,""):void 0,P=N||D,T=P?Q.find((D0)=>D0.nodeId&&(D0.nodeId===P||P.includes(D0.nodeId))):void 0,B=T?.time??w,E=I[q+1],C=E?Number(E.createdAt)||1/0:1/0,b=q===I.length-1,x=Q.find((D0)=>(D0.time??0)>B+5000&&D0.isEbot&&(D0.nodeName?.includes("智能")||D0.nodeName?.includes("AI")||D0.action?.includes("智能")||D0.comment?.includes("AI")||D0.comment?.includes("approval-result"))&&!D0.nodeName?.includes("费用标准检查")&&!D0.nodeName?.includes("标准检查")&&!D0.nodeName?.includes("预算"));if(x){if(b=!1,(x.time??1/0)<C)C=x.time}let g=V.result||{},i=g.decision||V.aiDecision||"-",c=typeof i==="string"?i:"-",I0=c.toUpperCase(),k=I0==="REJECT"||I0==="驳回",p=I0==="APPROVE"||I0==="通过",a=I0==="EXEMPT_APPROVE"||I0==="免审通过"||I0==="备注通过",$0=V.taskMode||V.finalExecutionMode||"",d=String($0).toLowerCase().includes("auto")||V.finalExecutionMode==="automatic"||$0==="automatic"||$0==="fully_automatic",Y0="-";if(p||a)Y0="添加评论";else if(k)Y0=d?"驳回":"添加评论";else if(I0==="REVIEW"||I0==="转交复核")Y0="转交复核";let R=typeof F.status==="object"&&F.status!==null?String(F.status.type||F.status.label||"").toUpperCase():"",o=typeof F.status==="object"&&F.status!==null?String(F.status.sourceStatus||""):"",e=M.manualApprovalStatus||g.manualApprovalStatus||V.manualApprovalStatus,O0=typeof e==="string"?e.toUpperCase():"",T0=O0==="CANCELLED"||O0==="CANCELED"||O0==="已取消"||O0==="已撤回"||O0==="REVOKED"||R==="CANCELLED"||R==="CANCELED"||o.includes("撤回")||o.includes("取消"),y0=O0==="APPROVED"||O0==="已支付/审批完成"||O0==="已通过"||O0==="已完成"||O0==="已支付"||R==="APPROVED",o0=!(o.includes("补偿")||o.includes("已支付"))&&(O0==="TERMINATED"||O0==="REJECTED"||O0==="REJECT"||O0==="已驳回"||O0==="被驳回"||R==="TERMINATED"||R==="REJECTED"||R==="已驳回"||R==="被驳回"),q1=T?1000:60000,t=Q.filter((D0)=>{let Q0=D0.time??0;return Q0>=B-q1&&Q0<C}),X0="-",F0="-",u0=!1,b0,c0,P1=p||a,k1=Q.filter((D0)=>(D0.time??0)>B+5000),u1=k1.some((D0)=>D0.rawAction==="freeflow.retract"||D0.action==="单据撤回"),b1=k1.some((D0)=>D0.rawAction==="freeflow.submit"||D0.action==="提交送审");if(P1&&b&&(u1||b1))u0=!0,b0="AI通过后单据发生撤回/修改重提,后续未经AI复审";if(d&&k)X0="无操作",F0="-";else{let D0=t.filter((S)=>(S.time??0)>=B-1000&&!S.isEbot&&S.rawAction!=="freeflow.submit"&&S.action!=="提交送审"&&!((S.rawAction==="freeflow.comment"||S.action==="发表评论")&&!S.comment)&&!((S.rawAction==="freeflow.print"||S.action==="打印提醒")&&!S.comment)&&!(S.rawAction==="freeflow.carbonCopy"||S.rawAction==="freeflow.cc"||S.action==="抄送通知")),Q0=D0.find((S)=>S.rawAction==="freeflow.retract"||S.action==="单据撤回"),A=D0.find((S)=>S.rawAction==="freeflow.reject"||S.action==="审批驳回");if(!b)if(A||!Y&&o0){X0="审批驳回",u0=!1,b0=void 0;let S=Od(A,void 0,F,Q,Y);F0=S.comme Line truncated
`,{mode:384}),Y}function _d($){let Y=JA0();for(let U of Y){if(!D$(U))continue;for(let I of JP(U).filter((Q)=>Q.endsWith(".json")).filter((Q)=>!Q.startsWith("example."))){let Q=C9(U,I);try{let J=zP(Q,"utf-8"),K=JSON.parse(J);if(K&&typeof K==="object"&&K.id===$)return Q}catch{}}}return}function R9($,Y){let U=_d($);if(!U)throw Error(`Enterprise config not found: ${$}`);let Q={...JSON.parse(zP(U,"utf-8")),...Y};for(let K of Object.keys(Y))if(Y[K]===void 0)delete Q[K];let J=kZ.parse(Q);return eB0(U,`${JSON.stringify(J,null,2)}
`,"utf-8"),J}var Rd="SEAL_USE_ENTERPRISES_DIR",$A0="SEAL_HOME_ENTERPRISES_DIR",YA0="SEAL_USE_USER_ENTERPRISES_DIR",UA0="SEAL_HOME_USER_ENTERPRISES_DIR",IA0="SEAL_USE_CONFIG_FILE",QA0="SEAL_HOME_CONFIG_FILE",Iz,KP,QP,aB0;var l$=m(()=>{IP();Iz=C9(GP(),".config","seal-use","enterprises"),KP=C9(GP(),".config","seal-home","enterprises"),QP=C9(GP(),".config","seal-use","config.json"),aB0=C9(GP(),".config","seal-home","config.json")});function d2($,Y,U=[]){let I=Y.corpId?.trim()||void 0,Q=Y.stateful?Y.defaultCorpId?.trim()||void 0:void 0,J=I??Q;if(J){let z=$.find((W)=>W.id===J);if(z)return z;let G=$.find((W)=>W.id.toLowerCase()===J.toLowerCase());if(G)return G;let H=$.find((W)=>W.name.toLowerCase()===J.toLowerCase());if(H)return H;throw Error(`No enterprise config found for ${J}`)}if(!Y.stateful)throw Error("Stateless mode is enabled. Every enterprise command requires --corp <corpId>. Use `seal-use config mode stateful` to enable a default enterprise.");let K=$[0];if(K)return K;throw Error("No enterprise config found. Add a non-example JSON file under one of: "+(U.length?U.join(", "):"the configured enterprise directories"))}import{existsSync as vd,mkdirSync as yB1,readFileSync as kB1,renameSync as xB1,unlinkSync as fB1,writeFileSync as uB1}from"node:fs";import{homedir as bB1}from"node:os";import{dirname as iB1,join as cB1}from"node:path";function fZ(){let $=process.env[nB1]?.trim();if($)return $;return dB1}function zA0($=new Date){return $.toISOString().slice(0,10)}function GA0($=Sd,Y=new Date){let U=Y.getTime()-Math.max(0,$-1)*86400000;return new Date(U).toISOString().slice(0,10)}function HA0($=fZ()){if(!vd($))return{};try{let Y=kB1($,"utf-8"),U=JSON.parse(Y);if(U&&typeof U==="object"&&!Array.isArray(U))return U;return{}}catch{return{}}}function pB1($,Y){let U={};for(let[I,Q]of Object.entries($)){if(!Q||typeof Q!=="object")continue;let J={},K=!1;for(let[z,G]of Object.entries(Q))if(typeof G==="number"&&G>0&&z>=Y)J[z]=G,K=!0;if(K)U[I]=J}return U}function mB1($,Y=fZ()){let U=iB1(Y);if(!vd(U))yB1(U,{recursive:!0,mode:448});let I=`${Y}.${process.pid}.${Date.now()}.${Math.random().toString(16).slice(2,8)}.tmp`;try{uB1(I,JSON.stringify($,null,2),{encoding:"utf-8",mode:384}),xB1(I,Y)}catch(Q){try{if(vd(I))fB1(I)}catch{}throw Q}}function WA0($,Y=new Date){if(!$||typeof $!=="string")return;try{let U=fZ(),I=HA0(U),Q=zA0(Y),J=GA0(Sd,Y),K=pB1(I,J);K[$]=K[$]||{},K[$][Q]=(K[$][Q]??0)+1,mB1(K,U)}catch{}}function lB1($,Y=Sd,U=new Date){let I=new Map;try{let Q=HA0(),J=GA0(Y,U),K=zA0(U),z=$??Object.keys(Q);for(let G of z){let H=Q[G];if(!H){I.set(G,0);continue}let W=0;for(let[X,Z]of Object.entries(H))if(X>=J&&X<=K&&typeof Z==="number")W+=Z;I.set(G,W)}}catch{if($)for(let Q of $)I.set(Q,0)}return I}function XA0($,Y,U){let I=U??lB1($.map((Q)=>Q.id));return[...$].sort((Q,J)=>{if(Y){if(Q.id===Y&&J.id!==Y)return-1;if(J.id===Y&&Q.id!==Y)return 1}let K=I.get(Q.id)??0,z=I.get(J.id)??0;if(K!==z)return z-K;let G=Q.name??Q.id,H=J.name??J.id,W=G.localeCompare(H,"zh-CN");if(W!==0)return W;return Q.id.localeCompare(J.id)})}var nB1="SEAL_USE_USAGE_FILE",dB1,Sd=7;var HP=m(()=>{dB1=cB1(bB1(),".config","seal-use","usage.json")});var K8={};Z8(K8,{withApprovalRunFilters:()=>FA1,toDate:()=>pd,timestampOf:()=>yd,summarizeSimulationBatch:()=>YA1,summarizeRunBridge:()=>KA1,summarizeRuleVersion:()=>zA1,summarizeApprovalRuns:()=>UA1,summarizeApprovalRunResult:()=>LP,summarizeApprovalRunDocument:()=>wA0,summarizeApprovalRunDetail:()=>QA1,summarizeApprovalRun:()=>nZ,stringifyHumanResultValue:()=>dd,stringFromUnknown:()=>h4,setPath:()=>MA0,scalarIncludes:()=>ZP,runtimeRuleIndex:()=>cd,runtimeRuleIdToCode:()=>BA0,rulesHaveSameContent:()=>VA0,ruleChangedFields:()=>LA0,resolveSealBaseUrl:()=>ZA1,resolveRuleVersionSelector:()=>LA1,resolveRuleVersionForLookup:()=>GA1,resolveRuleVersion:()=>kd,resolveManualApprovalStatus:()=>PA0,resolveApprovalRunForUrl:()=>XA1,redactPreviewValue:()=>bZ,redactIntegrationSecrets:()=>tB1,projectApprovalRules:()=>rB1,presentWebhookIntegration:()=>oB1,prepareApprovalRuns:()=>wA1,pickRunFields:()=>FA0,pickRuleFields:()=>qA0,pickApprovalRuns:()=>VA1,pickApprovalRunCandidate:()=>WA1,parseFieldPaths:()=>IA1,parseDurationMs:()=>aB1,objectContainsScalar:()=>qP,numberFromUnknown:()=>OA0,normalizeUrl:()=>qA1,normalizeRuleStrictness:()=>bd,normalizeRuleCode:()=>WP,mutationPreview:()=>eB1,matchesRunLookup:()=>OA1,localParts:()=>md,localDateKey:()=>NA1,isHumanResultKey:()=>xd,getPath:()=>_9,getConfiguredSealBaseUrl:()=>ZA0,formatRuleCode:()=>Qz,formatLocalDateTime:()=>ud,flattenDocumentFields:()=>NA0,firstPath:()=>iZ,firstByLabel:()=>uZ,findRuleInVersion:()=>HA1,findKeywordLines:()=>gd,findHumanResultValue:()=>VP,filterRunsByHumanResult:()=>AA0,filterRuns:()=>nd,extractHumanResult:()=>FI,extractCitedRules:()=>JA1,countPathCandidates:()=>hd,countBy:()=>fd,compactObject:()=>LI,collectInvoiceSummary:()=>DA0,collectInvoiceObjects:()=>cZ,collectDocumentFields:()=>XP,buildSimulationBatchParams:()=>$A1,buildRulePushPlan:()=>sB1,asRecord:()=>Jz,approvalRu Line truncated
`);return{recordId:$.id,sourceDocumentSN:$.sourceDocumentSN,sourceDocumentId:$.sourceDocumentId,document:LI({id:Y?.id,sn:Y?.sn??Y?.sourceDocumentSN??$.sourceDocumentSN,title:Y?.title??Y?.name,template:iZ(Y,["template.name","templateName","form.name","formName","formTitle"]),amount:uZ(U,["金额","报销金额","付款金额","合计","价税合计"])??iZ(Y,["amount","totalAmount","expenseAmount"]),expenseType:uZ(U,["费用类型","费用类别","报销类型"]),costCompany:uZ(U,["费用承担公司","承担公司","成本中心","费用归属"]),payee:uZ(U,["收款方","收款账户","收款信息","开户名","银行账号"]),keyFields:U.slice(0,30)}),invoices:DA0($),attachments:b3($,{summary:!0}).attachments,aiResult:LP($),manualResult:FI($)?.value,hints:LI({amountMentions:gd(I,["金额","合计","税率"],8),partyMentions:gd(I,["买方","卖方","甲方","乙方","收款"],8)})}}function JA1($){let Y=[["result.citedRules",_9($,"result.citedRules")],["result.matchedRules",_9($,"result.matchedRules")],["result.ruleResults",_9($,"result.ruleResults")],["result.rules",_9($,"result.rules")],["pipelineData.citedRules",_9($,"pipelineData.citedRules")],["pipelineData.matchedRules",_9($,"pipelineData.matchedRules")]],U=[],I=new Set;for(let[Q,J]of Y)(Array.isArray(J)?J:J&&typeof J==="object"?Object.values(J):[]).forEach((z,G)=>{let H=Jz(z);if(!H)return;let W=h4(H.runtimeRuleId)??h4(H.runtimeId)??h4(H.id)??h4(H.ruleId),X=h4(H.ruleCode)??h4(H.code)??(W?BA0(W):void 0),Z=LI({runtimeRuleId:W,ruleCode:X,versionNumber:OA0(H.versionNumber)??$.ruleSetVersionNumber,scope:h4(H.scope),strictness:h4(H.strictness),appliedAnalysis:H.appliedAnalysis??H.analysis??H.reasoning,checkResult:H.checkResult??H.result??H.decision,findings:H.findings??H.riskPoints??H.evidence,sourcePath:`${Q}.${G}`}),q=JSON.stringify(Z);if(!I.has(q))I.add(q),U.push(Z)});return{recordId:$.id,sourceDocumentSN:$.sourceDocumentSN,sourceDocumentId:$.sourceDocumentId,ruleSetVersionNumber:$.ruleSetVersionNumber,count:U.length,rules:U}}function iZ($,Y){if(!$)return;for(let U of Y){let I=_9($,U);if(I!==void 0)return I}return}function hd($,Y){if(!$)return 0;for(let U of Y){let I=_9($,U);if(Array.isArray(I))return I.length;if(I&&typeof I==="object")return Object.keys(I).length;if(typeof I==="number")return I}return 0}function _9($,Y){return Y.split(".").reduce((U,I)=>{if(U===void 0||U===null)return;if(Array.isArray(U)){let Q=Number(I);return Number.isInteger(Q)?U[Q]:void 0}if(typeof U==="object")return U[I];return},$)}function MA0($,Y,U){let I=Y.split("."),Q=$;for(let J of I.slice(0,-1)){let K=Q[J];if(!K||typeof K!=="object"||Array.isArray(K))Q[J]={};Q=Q[J]}Q[I[I.length-1]??Y]=U}function LI($){return Object.fromEntries(Object.entries($).filter(([,Y])=>Y!==void 0))}function Jz($){return $&&typeof $==="object"&&!Array.isArray($)?$:void 0}function OA0($){return typeof $==="number"&&Number.isFinite($)?$:void 0}function NA0($){let Y=[];return XP($,"document",Y),Y}function XP($,Y,U){if(Array.isArray($)){$.forEach((K,z)=>XP(K,`${Y}.${z}`,U));return}let I=Jz($);if(!I)return;let Q=h4(I.label)??h4(I.name)??h4(I.title)??h4(I.fieldName),J=I.value??I.displayValue??I.text??I.content;if(Q&&J!==void 0&&typeof J!=="object")U.push(LI({path:Y,label:Q,value:J,type:h4(I.type)??h4(I.fieldType)}));for(let[K,z]of Object.entries(I)){if(K==="attachments")continue;XP(z,`${Y}.${K}`,U)}}function uZ($,Y){return $.find((I)=>{let Q=h4(I.label)??"";return Y.some((J)=>Q.includes(J))})?.value}function DA0($){let Y=[];return cZ($.result,"result",Y),cZ($.document,"document",Y),Y.slice(0,20)}function cZ($,Y,U){if(Array.isArray($)){$.forEach((Q,J)=>cZ(Q,`${Y}.${J}`,U));return}let I=Jz($);if(!I)return;if(/invoice|发票/i.test(Y))U.push(LI({path:Y,fileName:h4(I.fileName)??h4(I.filename)??h4(I.name),buyer:I.buyer??I.buyerName??I.purchaserName,seller:I.seller??I.sellerName,amount:I.amount??I.totalAmount??I.total,taxRate:I.taxRate,category:I.category??I.type}));for(let[Q,J]of Object.entries(I))cZ(J,`${Y}.${Q}`,U)}function gd($,Y,U){return $.split(/\r?\n/).filter((I)=>Y.some((Q)=>I.includes(Q))).slice(0,U)}function KA1($){return $.map((Y)=>{let U=nZ(Y);return{recordId:U.id,tenantId:U.tenantId,agentId:U.agentId,sourceDocumentSN:U.sourceDocumentSN,sourceDocumentId:U.sourceDocumentId,simulationBatchId:U.simulationBatchId,langfuseTraceId:U.langfuseTraceId,langfuseSessionFallback:U.langfuseSessionFallback,ruleSetVersionNumber:U.ruleSetVersionNumber,ruleSetPublishedAt:U.ruleSetPublishedAt,ruleSetPublishedByName:U.ruleSetPublishedByName,resolution:U.langfuseTraceId?"trace":U.langfuseSessionFallback?"session-fallback":"unresolved"}})}function zA1($){return{id:$.id,tenantId:$.tenantId,versionNumber:$.versionNumber,versionName:$.versionName,publishedBy:$.publishedBy,publishedByName:$.publishedByName,rulesCount:$.rules.length,publishedAt:$.publishedAt,createdAt:$.createdAt}}async function GA1($,Y){if(Y.recordId&&!Y.versionId&&!Y.versionNumber&&!Y.latest){let U=await G4($,Y.recordId);if(!U.ruleSetVersionNumber)throw Erro Line truncated
`):[]}function xA1($,Y){let U=Array.from({length:$.length+1},()=>Array(Y.length+1).fill(0));for(let K=$.length-1;K>=0;K-=1)for(let z=Y.length-1;z>=0;z-=1)U[K][z]=$[K]===Y[z]?U[K+1][z+1]+1:Math.max(U[K+1][z],U[K][z+1]);let I=[],Q=0,J=0;while(Q<$.length&&J<Y.length)if($[Q]===Y[J])I.push(` ${$[Q]}`),Q+=1,J+=1;else if(U[Q+1][J]>=U[Q][J+1])I.push(`-${$[Q++]}`);else I.push(`+${Y[J++]}`);while(Q<$.length)I.push(`-${$[Q++]}`);while(J<Y.length)I.push(`+${Y[J++]}`);return I}function fA1($,Y,U,I,Q,J){let K=iA0(I,J),z=iA0(Q,J),G=I?`a/rules/${$}`:"/dev/null",H=Q?`b/rules/${$}`:"/dev/null";return[`diff --git a/rules/${$} b/rules/${$}`,`--- ${G} v${Y.versionNumber}`,`+++ ${H} v${U.versionNumber}`,`@@ -${K.length?1:0},${K.length} +${z.length?1:0},${z.length} @@`,...xA1(K,z)].join(`
`)}function cA0($){return{id:$.id,versionNumber:$.versionNumber,versionName:$.versionName,publishedAt:$.publishedAt}}function nA0($,Y){let U=new Map;for(let I of $.rules){let Q=dZ(I),J=Y==="stable-id"?pA0(Q):pZ(Q.code??Q.ruleCode);if(!J)throw Error(`Rule version ${$.versionNumber} contains a rule without a ${Y==="stable-id"?"stable rule ID":"code"}.`);if(U.has(J))throw Error(`Rule version ${$.versionNumber} contains duplicate ${Y==="stable-id"?"stable rule ID":"code"}: ${J}`);U.set(J,Q)}return U}function uA1($,Y,U){if(U!=="auto")return U;if([...$.rules,...Y.rules].every((J)=>Boolean(pA0(J))))return"stable-id";if([...$.rules,...Y.rules].every((J)=>Boolean(pZ(dZ(J).code??dZ(J).ruleCode))))return"code";throw Error("Rule snapshots have neither a complete stable-ID mapping nor a complete code mapping.")}function mA0($,Y,U={}){let I=uA1($,Y,U.identityMode??"auto"),Q=nA0($,I),J=nA0(Y,I),K=[...new Set([...Q.keys(),...J.keys()])],z=[],G={added:0,removed:0,modified:0,unchanged:0},H=cA0($),W=cA0(Y);for(let Z of K){let q=Q.get(Z),V=J.get(Z),w=q?wI(q,I):void 0,M=V?wI(V,I):void 0,F=!q?"added":!V?"removed":JSON.stringify(w)!==JSON.stringify(M)?"modified":"unchanged";if(G[F]+=1,F==="unchanged"&&!U.includeUnchanged)continue;let N=F==="modified"?[...new Set([...Object.keys(w??{}),...Object.keys(M??{})])].filter((O)=>JSON.stringify(w?.[O])!==JSON.stringify(M?.[O])):void 0;z.push({status:F,ruleId:Z,identityMode:I,...q?{before:q}:{},...V?{after:V}:{},...N?.length?{changedFields:N}:{},...F!=="unchanged"?{diff:fA1(Z,H,W,q,V,I)}:{}})}let X={from:H,to:W,identityMode:I,counts:G,changes:z,unifiedDiff:z.filter((Z)=>Z.diff).map((Z)=>Z.diff).join(`
`)};if(I==="code"){let Z=K.filter((P)=>Q.has(P)&&J.has(P)).length,q=K.filter((P)=>Q.has(P)&&J.has(P)&&JSON.stringify(wI(Q.get(P),"code"))===JSON.stringify(wI(J.get(P),"code"))).length,V=Q.size,w=J.size,M=Math.min(V,w)?Z/Math.min(V,w):1,F=new Map;for(let[P,T]of Q)F.set(JSON.stringify(wI(T,"code")),P);let N=0;for(let[P,T]of J){let B=F.get(JSON.stringify(wI(T,"code")));if(B&&B!==P)N+=1}let D=(Math.min(V,w)?q/Math.min(V,w):1)>=0.5?"high":q>0||N>0?"ambiguous":"low";X.codeStats={oldCount:V,newCount:w,sameCodeCount:Z,sameCodeUnchanged:q,sameBodyDifferentCode:N,overlapRatio:M,confidence:D,warning:"Published snapshots do not carry stable IDs; code matching can report reorderings as remove/add or modified rules."}}return X}function rd($,Y=20000,U=!1){if(U||$.unifiedDiff.length<=Y)return{...$,truncation:{truncated:!1,maxChars:Y,omittedChars:0,hint:"Use --full only when the complete diff is required."}};let I=$.unifiedDiff.length-Y,Q=`
... [diff truncated: ${I} characters omitted; rerun with --full for the complete diff]`,J=$.changes.map(({before:K,after:z,diff:G,...H})=>({...H,...G?{diff:G.length>Y?`${G.slice(0,Y)}${Q}`:G}:{}}));return{...$,changes:J,unifiedDiff:`${$.unifiedDiff.slice(0,Y)}${Q}`,truncation:{truncated:!0,maxChars:Y,omittedChars:I,hint:"Use --full for the complete diff."}}}var dA0,kA1;var lA0=m(()=>{dA0=["id","ruleId","stableId"],kA1=new Set([...dA0,"runtimeRuleId","runtimeId","tenantId","createdAt","updatedAt","versionId","versionNumber"])});import{existsSync as bA1,mkdirSync as iA1,readFileSync as cA1,renameSync as nA1,writeFileSync as dA1}from"node:fs";import{homedir as pA1}from"node:os";import{join as oA0}from"node:path";function mZ($){if($===void 0||$===null)return;let Y=String($).trim().toLowerCase().replace(/^rule[-_:]?/,"").replace(/^#/,"");if(!Y)return;return/^\d+$/.test(Y)?String(Number(Y)):Y}function OP($){return JSON.stringify([$.description??"",$.scope??"",$.strictness??""])}function rA0(){return process.env.SEAL_USE_RULE_VERSION_SNAPSHOTS_DIR?.trim()||oA0(pA1(),".config","seal-use","rule-version-snapshots")}function mA1($){return $.replace(/[^a-zA-Z0-9._-]/g,"_")}function sA0($,Y){return oA0(rA0(),`${mA1($)}-v${Y}.json`)}function lZ($,Y,U){let I=new Map,Q=new Map;for(let W of U){let X=mZ(W.code);if(X)I.set(X,[...I.get(X)??[],W]);let Z=OP(W);Q.set(Z,[...Q.get(Z)??[],W])}let J=[];for(let W of Y.rules??[]){let X=mZ(W.code),Z=X?I.get(X)??[]:[],q=Q.get(OP(W))??[],V=Z.length===1?Z[0]:q.length===1?q[0]:void 0;if(!V)continue;J.push({stableId:V.id,...W.code!==void 0?{code:W.code}:{},description:W.description,scope:W.scope,strictness:W.strictness})}let K={corpId:$,versionId:Y.id,versionNumber:Y.versionNumber,capturedAt:new Date().toISOString(),rules:J},z=rA0();iA1(z,{recursive:!0,mode:448});let G=sA0($,Y.versionNumber),H=`${G}.${process.pid}.tmp`;return dA1(H,`${JSON.stringify(K,null,2)}
`,{encoding:"utf8",mode:384}),nA1(H,G),G}function lA1($,Y){let U=sA0($,Y.versionNumber);if(!bA1(U))return null;try{return JSON.parse(cA1(U,"utf8"))}catch{return null}}function sd($,Y){let U=lA1($,Y);if(!U?.rules.length)return Y;let I=new Map(U.rules.flatMap((J)=>{let K=mZ(J.code);return K?[[K,J]]:[]})),Q=new Map(U.rules.map((J)=>[OP(J),J]));return{...Y,rules:Y.rules.map((J)=>{if(J.id!==void 0||J.ruleId!==void 0||J.stableId!==void 0)return J;let K=(mZ(J.code)?I.get(mZ(J.code)):void 0)??Q.get(OP(J));return K?{...J,stableId:K.stableId}:J})}}var ad=()=>{};var aA0,D84,oA1,B84;var tA0=m(()=>{z6();aA0=L.object({level:L.enum(["error","warning","info"]),code:L.string(),message:L.string(),snippet:L.string().optional(),suggestion:L.string().optional()}),D84=L.object({score:L.number().min(0).max(100),passed:L.boolean(),issues:L.array(aA0)}),oA1=L.object({ruleId:L.string().optional(),ruleCode:L.string().optional(),ruleName:L.string().optional(),score:L.number().min(0).max(100),passed:L.boolean(),issues:L.array(aA0),description:L.string().optional()}),B84=L.object({linter:L.string(),linterType:L.enum(["builtin","official","custom"]),totalRules:L.number(),healthyCount:L.number(),issueCount:L.number(),overallScore:L.number().min(0).max(100),passed:L.boolean(),issues:L.array(oA1)})});function Kz($){let Y=($.description||"").trim(),U=[];if(Y.length<5)U.push({level:"error",code:"TOO_SHORT",message:"规则描述过于简短(少于 5 个字),大模型难以形成明确的判定逻辑",suggestion:"请补充具体的费用类型、核验条件与限制标准"});for(let G of rA1)if(Y.includes(G))U.push({level:"error",code:"VAGUE_WORD",snippet:G,message:`包含主观模糊词 "${G}",容易导致大模型判定标准产生波动与幻觉`,suggestion:`建议移除 "${G}",改为具体的金额上限、枚举范围或刚性判定条件`});let I=sA1.find((G)=>Y.includes(G)),Q=aA1.some((G)=>Y.includes(G));if(I&&!Q)U.push({level:"warning",code:"HANGING_EXCEPTION",snippet:I,message:`包含例外条款 "${I}",但未指定 AI 从何处核验该例外成立的依据`,suggestion:'建议补充明确的凭据来源(例如:"需在【单据备注】中说明原因" 或 "需在【附件】中上传审批截图")'});let J=U.filter((G)=>G.level==="error").length,K=U.filter((G)=>G.level==="warning").length;return{score:Math.max(0,100-J*25-K*10),passed:J===0,issues:U}}var rA1,sA1,aA1;var td=m(()=>{rA1=["原则上","尽量","适当","酌情","一般情况下","尽可能","合理控制","视情况","视具体情况"],sA1=["除非","特殊情况","特殊原因","经批准","经审批","经领导同意","除外","例外"],aA1=["备注","说明","附件","证明","邮件","截图","凭证","审批","单据","发票"]});function eA0($){let Y=($.description||"").trim(),U=[];if(Y.length<5)U.push({level:"error",code:"TOO_SHORT",message:"规则描述过于简短(少于 5 个字),大模型难以形成明确的判定逻辑",suggestion:"请补充具体的费用类型、核验条件与限制标准"});else if(Y.length<10)U.push({level:"warning",code:"SHORT_DESCRIPTION",message:"规则描述偏短(少于 10 个字),可能缺少适用的单据范围或执行细节",suggestion:"建议扩充核验场景、限制标准或异常处理方式"});for(let Z of tA1)if(Y.includes(Z))U.push({level:"error",code:"VAGUE_WORD",snippet:Z,message:`包含主观模糊词 "${Z}",在严格风控模式下容易引起审核判定分歧`,suggestion:`请移除 "${Z}",明确量化标准或枚举具体允许的情形`});let I=eA1.find((Z)=>Y.includes(Z)),Q=$P1.some((Z)=>Y.includes(Z));if(I&&!Q)U.push({level:"error",code:"HANGING_EXCEPTION",snippet:I,message:`包含例外条款 "${I}",但未指定 AI 从何处核验该例外成立的凭证依据`,suggestion:'严格模式要求必须补充明确的核验来源(如:"需在【单据备注】中说明原因" 或 "需在【附件】中提供审批截图")'});let J=/\d+/.test(Y),K=YP1.some((Z)=>Y.includes(Z));if(!J&&!K)U.push({level:"warning",code:"LACKS_EXPLICIT_CONSTRAINT",message:"规则缺乏明确的定量标准(如金额、天数、频次)或绝对刚性边界词(如不得、禁止、仅限)",suggestion:"建议设定具体数值阈值或明确的禁止/准入条件,以便大模型精确判定"});let z=/经(批准|审批|领导同意|领导签字)|审批通过/.test(Y),G=UP1.some((Z)=>Y.includes(Z));if(z&&!G)U.push({level:"warning",code:"AMBIGUOUS_APPROVER",message:"规则提及审批例外,但未明确指定具体的审批角色(如部门总监、直接上级、财务负责人)",suggestion:"建议明确审批人角色(例如:经【部门总监】批准,经【直接上级】邮件确认)"});let H=U.filter((Z)=>Z.level==="error").length,W=U.filter((Z)=>Z.level==="warning").length;return{score:Math.max(0,100-H*30-W*15),passed:H===0,issues:U}}var tA1,eA1,$P1,YP1,UP1;var ed=m(()=>{tA1=["原则上","尽量","适当","酌情","一般情况下","尽可能","合理控制","视情况","视 Line truncated
* ==============================================================================
* Seal 官方标准规则校验器 (Official Standard Rule Linter)
* ==============================================================================
@@ -881,65 +881,65 @@ export function lintRule(rule: RuleLintTarget): RuleLintResult {
}
export default lintRule;
`}});import{existsSync as Lz,mkdirSync as lA1,readFileSync as oA1,readdirSync as NB0,rmSync as rA1,unlinkSync as sA1,writeFileSync as aA1}from"node:fs";import{homedir as tA1}from"node:os";import{isAbsolute as eA1,join as b6,resolve as $B1}from"node:path";import{pathToFileURL as MB0}from"node:url";function DB0($=p$){let Y=[],U=[];try{if(!Lz($))lA1($,{recursive:!0});let z=Object.keys(fp);for(let[Q,J]of Object.entries(fp)){let K=b6($,Q),G=!0;if(Lz(K))try{if(oA1(K,"utf8")===J)G=!1}catch{G=!0}if(G)aA1(K,J,"utf8");Y.push(Q)}let I=NB0($,{withFileTypes:!0});for(let Q of I)if(!z.includes(Q.name)){let J=b6($,Q.name);try{if(Q.isDirectory())rA1(J,{recursive:!0,force:!0});else sA1(J);U.push(Q.name)}catch{}}}catch{}return{synced:Y,pruned:U}}function AB0($={syncOfficial:!0}){if($.syncOfficial!==!1)DB0();let Y=[{name:"builtin",type:"builtin",path:b6(p$,"builtin.ts"),description:"Seal 官方标准校验器 (拦截过短描述、主观模糊词与悬空例外条款)"},{name:"strict",type:"official",path:b6(p$,"strict.ts"),description:"Seal 官方严格风控校验器 (强校验字数、刚性定量约束、凭证依据与具体审批人角色)"},{name:"hlab",type:"official",path:b6(p$,"hlab.ts"),description:"合思实验室 (HLab) 结构化规则校验器 (SOP 四段论结构、三元闭环判定、剥离处置动作与防漏判)"}],U=[n$,GP];for(let z of U)if(Lz(z))try{let I=NB0(z,{withFileTypes:!0});for(let Q of I){if(Q.isDirectory())continue;let J=Q.name;if(J.endsWith(".ts")||J.endsWith(".js")||J.endsWith(".mjs")){let K=J.replace(/\.(ts|js|mjs)$/,"");if(!Y.some((G)=>G.name===K))Y.push({name:K,type:"custom",path:b6(z,J),description:`用户自定义规则校验器 (${J})`})}}}catch{}return Y}function UB1($){let Y=($||"").trim();if(!Y||Y==="builtin"||Y==="default"||Y==="official/builtin"||Y==="official/builtin.ts")return{path:b6(p$,"builtin.ts"),isOfficial:!0,officialKind:"builtin"};if(Y==="strict"||Y==="official/strict"||Y==="official/strict.ts")return{path:b6(p$,"strict.ts"),isOfficial:!0,officialKind:"strict"};if(Y==="hlab"||Y==="hlab-sop"||Y==="hlab-rules"||Y==="hlab-standard"||Y==="official/hlab"||Y==="official/hlab.ts")return{path:b6(p$,"hlab.ts"),isOfficial:!0,officialKind:"hlab"};if(eA1(Y)||Y.startsWith("./")||Y.startsWith("../")){let z=$B1(Y);if(Lz(z))return{path:z};for(let I of[".ts",".js",".mjs"])if(Lz(`${z}${I}`))return{path:`${z}${I}`}}let U=[b6(n$,`${Y}.ts`),b6(n$,`${Y}.js`),b6(n$,`${Y}.mjs`),b6(GP,`${Y}.ts`),b6(GP,`${Y}.js`),b6(GP,`${Y}.mjs`)];for(let z of U)if(Lz(z))return{path:z};return{}}async function bp($){DB0();let Y=UB1($??"builtin");if(Y.isOfficial){let z=Y.officialKind==="strict"?FB0:Y.officialKind==="hlab"?wB0:IK,I=Y.officialKind==="builtin"?"builtin":"official",Q=Y.path;if(Q&&Lz(Q))try{let K=await import(MB0(Q).href),G=K.default??K.lintRule??K.linter??K.lint;if(typeof G==="function")return{name:Y.officialKind??"builtin",type:I,filePath:Q,linter:OB0(G,z)}}catch{}return{name:Y.officialKind??"builtin",type:I,filePath:Q,linter:z}}let U=Y.path;if(!U)return console.error(`⚠️ [linter] 未找到自定义校验器 "${$}",已自动安全降级至内置标准校验器。`),{name:"builtin",type:"builtin",linter:IK};try{let I=await import(MB0(U).href),Q=I.default??I.lintRule??I.linter??I.lint;if(typeof Q!=="function")return console.error(`⚠️ [linter] 自定义校验器 "${U}" 未导出标准函数 (default / lintRule),已安全降级至内置标准校验器。`),{name:"builtin",type:"builtin",linter:IK};return{name:$??"custom",type:"custom",filePath:U,linter:OB0(Q,IK)}}catch(z){return console.error(`⚠️ [linter] 加载自定义校验器脚本 "${U}" 失败(语法错误或依赖缺失: ${z?.message??z}),已自动安全降级至内置标准校验器。`),{name:"builtin",type:"builtin",linter:IK}}}function OB0($,Y){return async(U,z)=>{try{let I=await $(U,z);if(I&&typeof I==="object"&&typeof I.score==="number"&&Array.isArray(I.issues))return I;return console.error("⚠️ [linter] 自定义校验器返回值格式不符合 RuleLintResult 契约,已回退至内置结果。"),Y(U,z)}catch(I){return console.error("⚠️ [linter] 自定义校验器执行异常:",I),Y(U,z)}}}var n$,YB1="official",p$,GP;var ip=m(()=>{yp();xp();up();kp();n$=b6(tA1(),".config","seal-use","linters"),p$=b6(n$,YB1),GP=b6(process.cwd(),"linters")});async function cp($,Y,U){let z=await Y.linter($,U);return{ruleId:$.id,ruleCode:$.code,ruleName:$.name,score:z.score,passed:z.passed,issues:z.issues,description:$.description}}async function BB0($,Y,U,z){let I=z?.minScore??0,Q=z?.level??"all",J=[],K=0;for(let q of $){let V=await cp(q,Y,U);K+=V.score;let w=V.issues;if(Q==="error")w=V.issues.filter((F)=>F.level==="error");else if(Q==="warning")w=V.issues.filter((F)=>F.level==="warning"||F.level==="error");let M=w.every((F)=>F.level!=="error");if(z?.summary){if(w.length>0)J.push({...V,passed:M,issues:w})}else J.push({...V,passed:M,issues:w})}let G=$.length,H=G===0?100:Math.round(K/G),W=J.filter((q)=>q.issues.length>0).length,X=G-Line truncated
`,"utf8"),U}function EB0($){return $.map((Y,U)=>{let z;if(typeof Y.code==="number")z=`#${String(Y.code).padStart(4,"0")}`;else if(typeof Y.code==="string")z=Y.code.startsWith("#")?Y.code:`#${Y.code}`;else z=`#${String(U+1).padStart(4,"0")}`;return{id:Y.id,code:z,name:Y.name,description:Y.description,scope:Y.scope,strictness:Y.strictness}})}var CB0=()=>{};var RB0,j5;var QK=m(()=>{RB0=class RB0 extends Error{errors;warnings;constructor($,Y=[]){super([`webhook 资源包校验失败:${$.length} 个错误`,...$.map((U)=>`- ${U}`)].join(`
`));this.errors=$;this.warnings=Y;this.name="ResourcePackValidationError"}};j5=RB0});var SB0=E((O64,hB0)=>{hB0.exports=HP;function HP(){this.pending=0,this.max=1/0,this.listeners=[],this.waiting=[],this.error=null}HP.prototype.go=function($){if(this.pending<this.max)vB0(this,$);else this.waiting.push($)};HP.prototype.wait=function($){if(this.pending===0)$(this.error);else this.listeners.push($)};HP.prototype.hold=function(){return _B0(this)};function _B0($){$.pending+=1;var Y=!1;return U;function U(I){if(Y)throw Error("callback called twice");if(Y=!0,$.error=$.error||I,$.pending-=1,$.waiting.length>0&&$.pending<$.max)vB0($,$.waiting.shift());else if($.pending===0){var Q=$.listeners;$.listeners=[],Q.forEach(z)}}function z(I){I($.error)}}function vB0($,Y){Y(_B0($))}});var kB0=E((XB1)=>{var dp=J0("fs"),mp=J0("util"),gB0=J0("stream"),yB0=gB0.Readable,HB1=gB0.PassThrough,WB1=SB0(),WP=J0("events").EventEmitter;XB1.BufferSlicer=KK;XB1.FdSlicer=JK;mp.inherits(JK,WP);function JK($){WP.call(this),this.fd=$,this.pend=new WB1,this.pend.max=1,this.refCount=0}JK.prototype.read=function($,Y,U,z,I){var Q=this;Q.pend.go(function(J){dp.read(Q.fd,$,Y,U,z,function(K,G,H){J(),I(K,G,H)})})};JK.prototype.createReadStream=function($){return new cZ(this,$)};JK.prototype.ref=function(){this.refCount+=1};JK.prototype.unref=function(){var $=this;if($.refCount-=1,$.refCount<0)throw Error("invalid unref");if($.refCount>0)return;dp.close($.fd,Y);function Y(U){if(U)$.emit("error",U);else $.emit("close")}};mp.inherits(cZ,yB0);function cZ($,Y){Y=Y||{},yB0.call(this,Y),this.context=$,this.context.ref(),this.start=Y.start||0,this.endOffset=Y.end,this.pos=this.start}cZ.prototype._read=function($){var Y=this,U=Math.min(Y._readableState.highWaterMark,$);if(Y.endOffset!=null)U=Math.min(U,Y.endOffset-Y.pos);if(U<=0){Y.push(null),this._cleanup();return}Y.context.pend.go(function(z){var I=Buffer.allocUnsafe(U);dp.read(Y.context.fd,I,0,U,Y.pos,function(Q,J){if(Q)Y.destroy(Q);else if(J===0)Y.push(null),Y._cleanup();else Y.pos+=J,Y.push(I.slice(0,J));z()})})};cZ.prototype._destroy=function($,Y){this._cleanup(),Y($)};cZ.prototype._cleanup=function(){if(this.context!=null)this.context.unref(),this.context=null};mp.inherits(KK,WP);function KK($){WP.call(this),this.refCount=0,this.buffer=$}KK.prototype.read=function($,Y,U,z,I){if(!(0<=Y&&Y<=$.length))throw RangeError("offset outside buffer: 0 <= "+Y+" <= "+$.length);if(z<0)throw RangeError("position is negative: "+z);if(Y+U>$.length)U=$.length-Y;if(z+U>this.buffer.length)U=this.buffer.length-z;if(U<=0){setImmediate(function(){I(null,0)});return}this.buffer.copy($,Y,z,z+U),setImmediate(function(){I(null,U)})};KK.prototype.createReadStream=function($){$=$||{};var Y=new HB1($);Y.start=$.start||0,Y.endOffset=$.end,Y.pos=Y.endOffset||this.buffer.length;var U=this.buffer.slice(Y.start,Y.pos),z=65536,I=0;while(!0){var Q=I+z;if(Q>=U.length){if(I<U.length)Y.write(U.slice(I,U.length));break}Y.write(U.slice(I,Q)),I=Q}return Y.end(),Y};KK.prototype.ref=function(){this.refCount+=1};KK.prototype.unref=function(){if(this.refCount-=1,this.refCount<0)throw Error("invalid unref")}});var fB0=E((D64,xB0)=>{var VB1=new Int32Array([0,1996959894,3993919788,2567524794,124634137,1886057615,3915621685,2657392035,249268274,2044508324,3772115230,2547177864,162941995,2125561021,3887607047,2428444049,498536548,1789927666,4089016648,2227061214,450548861,1843258603,4107580753,2211677639,325883990,1684777152,4251122042,2321926636,335633487,1661365465,4195302755,2366115317,997073096,1281953886,3579855332,2724688242,1006888145,1258607687,3524101629,2768942443,901097722,1119000684,3686517206,2898065728,853044451,1172266101,3705015759,2882616665,651767980,1373503546,3369554304,3218104598,565507253,1454621731,3485111705,3099436303,671266974,1594198024,3322730930,2970347812,795835527,1483230225,3244367275,3060149565,1994146192,31158534,2563907772,4023717930,1907459465,112637215,2680153253,3904427059,2013776290,251722036,2517215374,3775830040,2137656763,141376813,2439277719,3865271297,1802195444,476864866,2238001368,4066508878,1812370925,453092731,2181625025,4111451223,1706088902,314042704,2344532202,4240017532,1658658271,366619977,2362670323,4224994405,1303535960,984961486,2747007092,3569037538,1256170817,1037604311,2765210733,3554079995,1131014506,879679996,2909243462,3663771856,1141124467,855842277,2852801631,3708648649,1342533948,654459306,3188396048,3373015174,1466479909,544179635,3110523913,3462522015,1591671054,702138776,2966460450,3352799412,1504918807,783551873,3082640443,3233442989,3988292384,2596254646,62317068,1957810842,3939845945,2647816111,81470997,1943803523,3814918930,2489596804,225274430,2053790376,3826175755,2466906013,167816743,2097651377,4027552580,2265490386,503444072,1762050814,4150417245,2154129355,426522225,1852507879,4275313526,2312317920,282753626,1742555852,4189708143,2394877945,397917763,1622183637,3604390888,2714866558,953729732,1340076626,3518719985,2797360999,1068828381,1219638859,3624741850,2936675148,906185462, Line truncated
`}});import{homedir as GP1}from"node:os";import{join as Ip}from"node:path";var HP1,B$,A$;var Qp=m(()=>{HP1=Ip(GP1(),".config","seal-use"),B$=Ip(HP1,"linters"),A$=Ip(B$,"official")});import{existsSync as MI,mkdirSync as WP1,readFileSync as XP1,readdirSync as IP0,rmSync as ZP1,unlinkSync as qP1,writeFileSync as VP1}from"node:fs";import{isAbsolute as LP1,join as B8,resolve as FP1}from"node:path";import{pathToFileURL as YP0}from"node:url";function QP0($=A$){let Y=[],U=[];try{if(!MI($))WP1($,{recursive:!0});let I=Object.keys(Yp);for(let[J,K]of Object.entries(Yp)){let z=B8($,J),G=!0;if(MI(z))try{if(XP1(z,"utf8")===K)G=!1}catch{G=!0}if(G)VP1(z,K,"utf8");Y.push(J)}let Q=IP0($,{withFileTypes:!0});for(let J of Q)if(!I.includes(J.name)){let K=B8($,J.name);try{if(J.isDirectory())ZP1(K,{recursive:!0,force:!0});else qP1(K);U.push(J.name)}catch{}}}catch{}return{synced:Y,pruned:U}}function JP0($={syncOfficial:!0}){if($.syncOfficial!==!1)QP0();let Y=[{name:"builtin",type:"builtin",path:B8(A$,"builtin.ts"),description:"Seal 官方标准校验器 (拦截过短描述、主观模糊词与悬空例外条款)"},{name:"strict",type:"official",path:B8(A$,"strict.ts"),description:"Seal 官方严格风控校验器 (强校验字数、刚性定量约束、凭证依据与具体审批人角色)"},{name:"hlab",type:"official",path:B8(A$,"hlab.ts"),description:"合思实验室 (HLab) 结构化规则校验器 (SOP 四段论结构、三元闭环判定、剥离处置动作与防漏判)"}],U=[B$,NP];for(let I of U)if(MI(I))try{let Q=IP0(I,{withFileTypes:!0});for(let J of Q){if(J.isDirectory())continue;let K=J.name;if(K.endsWith(".ts")||K.endsWith(".js")||K.endsWith(".mjs")){let z=K.replace(/\.(ts|js|mjs)$/,"");if(!Y.some((G)=>G.name===z))Y.push({name:z,type:"custom",path:B8(I,K),description:`用户自定义规则校验器 (${K})`})}}}catch{}return Y}function wP1($){let Y=($||"").trim();if(!Y||Y==="builtin"||Y==="default"||Y==="official/builtin"||Y==="official/builtin.ts")return{path:B8(A$,"builtin.ts"),isOfficial:!0,officialKind:"builtin"};if(Y==="strict"||Y==="official/strict"||Y==="official/strict.ts")return{path:B8(A$,"strict.ts"),isOfficial:!0,officialKind:"strict"};if(Y==="hlab"||Y==="hlab-sop"||Y==="hlab-rules"||Y==="hlab-standard"||Y==="official/hlab"||Y==="official/hlab.ts")return{path:B8(A$,"hlab.ts"),isOfficial:!0,officialKind:"hlab"};if(LP1(Y)||Y.startsWith("./")||Y.startsWith("../")){let I=FP1(Y);if(MI(I))return{path:I};for(let Q of[".ts",".js",".mjs"])if(MI(`${I}${Q}`))return{path:`${I}${Q}`}}let U=[B8(B$,`${Y}.ts`),B8(B$,`${Y}.js`),B8(B$,`${Y}.mjs`),B8(NP,`${Y}.ts`),B8(NP,`${Y}.js`),B8(NP,`${Y}.mjs`)];for(let I of U)if(MI(I))return{path:I};return{}}async function Jp($){QP0();let Y=wP1($??"builtin");if(Y.isOfficial){let I=Y.officialKind==="strict"?eA0:Y.officialKind==="hlab"?$P0:Kz,Q=Y.officialKind==="builtin"?"builtin":"official",J=Y.path;if(J&&MI(J))try{let z=await import(YP0(J).href),G=z.default??z.lintRule??z.linter??z.lint;if(typeof G==="function")return{name:Y.officialKind??"builtin",type:Q,filePath:J,linter:UP0(G,I)}}catch{}return{name:Y.officialKind??"builtin",type:Q,filePath:J,linter:I}}let U=Y.path;if(!U)return console.error(`⚠️ [linter] 未找到自定义校验器 "${$}",已自动安全降级至内置标准校验器。`),{name:"builtin",type:"builtin",linter:Kz};try{let Q=await import(YP0(U).href),J=Q.default??Q.lintRule??Q.linter??Q.lint;if(typeof J!=="function")return console.error(`⚠️ [linter] 自定义校验器 "${U}" 未导出标准函数 (default / lintRule),已安全降级至内置标准校验器。`),{name:"builtin",type:"builtin",linter:Kz};return{name:$??"custom",type:"custom",filePath:U,linter:UP0(J,Kz)}}catch(I){return console.error(`⚠️ [linter] 加载自定义校验器脚本 "${U}" 失败(语法错误或依赖缺失: ${I?.message??I}),已自动安全降级至内置标准校验器。`),{name:"builtin",type:"builtin",linter:Kz}}}function UP0($,Y){return async(U,I)=>{try{let Q=await $(U,I);if(Q&&typeof Q==="object"&&typeof Q.score==="number"&&Array.isArray(Q.issues))return Q;return console.error("⚠️ [linter] 自定义校验器返回值格式不符合 RuleLintResult 契约,已回退至内置结果。"),Y(U,I)}catch(Q){return console.error("⚠️ [linter] 自定义校验器执行异常:",Q),Y(U,I)}}}var NP;var KP0=m(()=>{Qp();td();$p();Up();ed();NP=B8(process.cwd(),"linters")});async function Kp($,Y,U){let I=await Y.linter($,U);return{ruleId:$.id,ruleCode:$.code,ruleName:$.name,score:I.score,passed:I.passed,issues:I.issues,description:$.description}}async function zP0($,Y,U,I){let Q=I?.minScore??0,J=I?.level??"all",K=[],z=0;for(let q of $){let V=await Kp(q,Y,U);z+=V.score;let w=V.issues;if(J==="error")w=V.issues.filter((F)=>F.level==="error");else if(J==="warning")w=V.issues.filter((F)=>F.level==="warning"||F.level==="error");let M=w.every((F)=>F.level!=="error");if(I?.summary){if(w.length>0)K.push({...V,passed:M,issues:w})}else K.push({...V,passed:M,issues:w})}let G=$.length,H=G===Line truncated
`,"utf8"),U}function XP0($){return $.map((Y,U)=>{let I;if(typeof Y.code==="number")I=`#${String(Y.code).padStart(4,"0")}`;else if(typeof Y.code==="string")I=Y.code.startsWith("#")?Y.code:`#${Y.code}`;else I=`#${String(U+1).padStart(4,"0")}`;return{id:Y.id,code:I,name:Y.name,description:Y.description,scope:Y.scope,strictness:Y.strictness}})}var ZP0=()=>{};var z$4,G$4,PP1,H$4,TP1,W$4,X$4,qP0,Z$4,q$4,VP0,V$4,L$4,F$4,w$4,M$4,O$4,N$4,D$4,B$4,A$4,P$4,T$4,E$4,j$4,C$4,R$4,_$4,v$4,S$4,h$4,g$4,y$4,k$4,x$4,f$4,u$4,Hp,EP1,jP1,LP0,CP1,b$4,i$4,c$4,n$4,d$4,p$4,FP0,m$4,l$4,RP1,wP0,o$4,r$4,s$4,a$4,t$4,e$4,$54,Y54,U54,I54,Q54,J54,K54,z54,G54,H54,W54,X54,MP0;var OP0=m(()=>{z6();H4();l$();bA0();lA0();ad();zp();ZP0();o$();({presentWebhookIntegration:z$4,getConfiguredSealBaseUrl:G$4,projectApprovalRules:PP1,pickRuleFields:H$4,buildRulePushPlan:TP1,rulesHaveSameContent:W$4,ruleChangedFields:X$4,normalizeRuleStrictness:qP0,parseDurationMs:Z$4,redactIntegrationSecrets:q$4,mutationPreview:VP0,redactPreviewValue:V$4,buildSimulationBatchParams:L$4,summarizeSimulationBatch:F$4,summarizeApprovalRun:w$4,summarizeApprovalRuns:M$4,parseFieldPaths:O$4,pickRunFields:N$4,approvalRunMetadata:D$4,summarizeApprovalRunDetail:B$4,summarizeApprovalRunResult:A$4,summarizeApprovalRunDocument:P$4,extractCitedRules:T$4,firstPath:E$4,countPathCandidates:j$4,getPath:C$4,setPath:R$4,compactObject:_$4,asRecord:v$4,numberFromUnknown:S$4,flattenDocumentFields:h$4,collectDocumentFields:g$4,firstByLabel:y$4,collectInvoiceSummary:k$4,collectInvoiceObjects:x$4,findKeywordLines:f$4,summarizeRunBridge:u$4,summarizeRuleVersion:Hp,resolveRuleVersionForLookup:EP1,findRuleInVersion:jP1,normalizeRuleCode:LP0,runtimeRuleIndex:CP1,runtimeRuleIdToCode:b$4,formatRuleCode:i$4,pickApprovalRunCandidate:c$4,resolveApprovalRunForUrl:n$4,resolveSealBaseUrl:d$4,normalizeUrl:p$4,stringFromUnknown:FP0,pickApprovalRuns:m$4,timestampOf:l$4,resolveRuleVersion:RP1,resolveRuleVersionSelector:wP0,filterRuns:o$4,scalarIncludes:r$4,objectContainsScalar:s$4,filterRunsByHumanResult:a$4,withApprovalRunFilters:t$4,resolveManualApprovalStatus:e$4,prepareApprovalRuns:$54,approvalRunAliases:Y54,extractHumanResult:U54,findHumanResultValue:I54,isHumanResultKey:Q54,stringifyHumanResultValue:J54,matchesRunLookup:K54,countBy:z54,localDateKey:G54,formatLocalDateTime:H54,toDate:W54,localParts:X54}=K8),MP0=[{name:"seal_approval_rules_list",description:"列出 Seal 当前草稿审批规则;返回的 code 属于草稿编号体系,发布版本可能重新编码;支持 countOnly、fields、limit 以避免返回规则正文",parameters:L.object({countOnly:L.boolean().optional().describe("只返回规则数量,不返回规则列表"),fields:L.array(L.enum(["id","code","tenantId","status","strictness","scope","createdAt","updatedAt","description"])).optional().describe("只返回指定字段;不传则返回完整规则"),limit:L.number().int().nonnegative().optional().describe("最多返回多少条规则;0 可配合 fields 或 countOnly 只取数量"),offset:L.number().int().nonnegative().optional().describe("跳过前多少条规则")}),handler:async($,Y)=>{let U=await q6($);return PP1(U,Y)}},{name:"seal_approval_rules_clear",description:"清空 Seal 当前草稿审批规则;用于测试环境导入规则前重置草稿规则集",parameters:L.object({dryRun:L.boolean().optional().describe("只预览将删除的规则数量,不执行删除"),recode:L.boolean().optional().describe("删除后尝试重新编排规则编号;失败会作为 warning 返回")}),handler:async($,Y,U)=>{let I=await q6($);if(Y.dryRun)return{...VP0(U,"api/v1/rules",I.rules,[],I.rules.length),corpId:U.corp.id,corpName:U.corp.name,dryRun:!0,beforeCount:I.rules.length,deleted:0,afterCount:I.rules.length,hasPendingDeletes:I.hasPendingDeletes};let Q=[],J=0;for(let H of I.rules)try{await $J($,H.id),J+=1}catch(W){Q.push({ruleId:H.id,error:W instanceof Error?W.message:String(W)})}let K=[],z;if(J>0&&Y.recode!==!1){if(z=await SM($),z&&typeof z==="object"&&"ok"in z&&z.ok!==!0)K.push("batch-recode did not complete; current rules were still deleted")}let G=await q6($);return{corpId:U.corp.id,corpName:U.corp.name,dryRun:!1,beforeCount:I.rules.length,deleted:J,failed:Q,afterCount:G.rules.length,hasPendingDeletes:G.hasPendingDeletes,warnings:K,recode:z}}},{name:"seal_approval_rule_create",description:"新建 Seal 草稿审批规则",parameters:L.object({description:L.string().describe("规则描述"),scope:L.string().describe("适用场景"),strictness:L.enum(["MUST_FOLLOW","SHOULD_FOLLOW","SUGGESTION"]).describe("严格程度")}),handler:async($,Y)=>uH($,Y)},{name:"seal_approval_rule_update",description:"更新 Seal 草稿审批规则",parameters:L.object({ruleId:L.string().describe("规则 ID"),description:L.string().optional(),scope:L.string().optional(),strictness:L.enum(["MUST_FOLLOW","SHOULD_FOLLOW","SUGGESTION"]).optional()}),handler:async($,Y)=>{let U=Y.ruleId;if(U&&(U.startsWith("#")||U.startsWith("rule-")||U.match(/^\d+$/))){ Line truncated
`)},{...rd(J,20000,Y.full===!0),format:Y.format??"unified"}}},{name:"seal_approval_rule_version_publish",description:"发布 Seal 草稿审批规则为新版本",parameters:L.object({versionName:L.string().describe("版本名称")}),handler:async($,Y,U)=>{let I=await q6($).catch(()=>{return}),Q=await bH($,Y.versionName);if(I)try{lZ(U.corp.id,Q.version,I.rules)}catch{}return Q}},{name:"seal_approval_rule_get",description:"按版本号/code/runtime-id/record-id 定位单条规则;code 只在选定的版本编号体系内有效,避免拉取整版规则快照",parameters:L.object({versionId:L.string().optional().describe("规则版本 ID"),versionNumber:L.number().int().positive().optional().describe("规则版本号"),latest:L.boolean().optional().describe("为 true 时取最新版本"),code:L.string().optional().describe("规则展示编号,如 #0038;没有后端 code 时按版本内序号匹配"),runtimeId:L.string().optional().describe("运行时规则 ID,如 rule-205;按版本内序号匹配"),recordId:L.string().optional().describe("从运行记录推断 ruleSetVersionNumber")}),handler:async($,Y)=>{let U=await EP1($,Y),I=jP1(U,{code:Y.code,runtimeId:Y.runtimeId});if(!I)throw Error(`Rule not found in version ${U.versionNumber}`);return I}},{name:"seal_approval_rules_lint",description:"对 Seal 本地规则文件、草稿审批规则或指定发布版本规则进行质量与可执行性检查(模糊词、悬空例外检测)",parameters:L.object({file:L.string().optional().describe("指定本地规则文件路径进行离线质检(支持 .json),0网络请求、不污染远端草稿"),linter:L.string().optional().describe("指定使用的校验器名称或脚本路径(如 builtin、strict、./my-linter.ts)"),version:L.string().optional().describe("指定要质检的历史发布版本号或 ID(如 16 或 latest),不传默认质检当前草稿"),code:L.string().optional().describe("按规则展示编号过滤(如 #0038)"),ruleId:L.string().optional().describe("按规则 ID 过滤"),minScore:L.number().optional().describe("最低合格质量分阈值(0~100),低于该分值抛出错误以返回非零退出码"),level:L.enum(["all","error","warning"]).default("all").describe("问题报告等级过滤"),summary:L.boolean().optional().describe("为 true 时仅返回存在瑕疵/扣分的规则")}),handler:async($,Y,U)=>{let I=[],Q;if(Y.file){let H=Gp(Y.file);I=XP0(H.rules),Q=H.meta.versionNumber}else if(Y.version){let H=await S8($),W=Number(Y.version),X=isNaN(W)?Y.version==="latest"?H[0]:H.find((Z)=>Z.id===Y.version):H.find((Z)=>Z.versionNumber===W);if(!X)throw Error(`未找到指定的规则版本: ${Y.version}`);Q=X.versionNumber,I=(X.rules??[]).map((Z,q)=>({id:Z.id??Z.runtimeId,code:Z.code??`#${String(q+1).padStart(4,"0")}`,name:Z.name??Z.title,description:Z.description??"",scope:Z.scope,strictness:Z.strictness}))}else I=((await q6($)).rules??[]).map((W,X)=>({id:W.id,code:W.code??`#${String(X+1).padStart(4,"0")}`,name:W.name??W.title,description:W.description??"",scope:W.scope,strictness:W.strictness}));if(Y.code)I=I.filter((H)=>H.code===Y.code||H.code?.replace(/[#\s]/g,"")===Y.code?.replace(/[#\s]/g,""));if(Y.ruleId)I=I.filter((H)=>H.id===Y.ruleId||H.code===Y.ruleId);let J=A4(),K=Y.linter??J.lint?.activeLinter??"builtin",z=await Jp(K),G=await zP0(I,z,{corpId:U?.corp?.id,versionNumber:Q,allRules:I},{minScore:Y.minScore,level:Y.level,summary:Y.summary});if(Y.minScore&&G.overallScore<Y.minScore)throw Error(`[Linter 质量门禁未通过] 综合评分 ${G.overallScore} 低于要求的最低分 ${Y.minScore} 分 (共发现 ${G.issueCount} 条问题规则)。`);return G}},{name:"seal_approval_rules_pull",description:"从 Seal 远端拉取草稿或指定版本规则,保存至本地规则文件(支持离线编辑与本地 Lint,绝不污染远端草稿)",parameters:L.object({version:L.string().optional().describe("指定拉取的历史发布版本号或 ID(如 16 或 latest),不传默认拉取当前草稿规则"),out:L.string().optional().describe("保存的目标本地文件路径,默认为 ./rules.local.json")}),handler:async($,Y,U)=>{let I=Y.out??"./rules.local.json",Q=[],J="draft",K;if(Y.version){let G=await S8($),H=Number(Y.version),W=isNaN(H)?Y.version==="latest"?G[0]:G.find((X)=>X.id===Y.version):G.find((X)=>X.versionNumber===H);if(!W)throw Error(`未找到指定的规则版本: ${Y.version}`);K=W.versionNumber,J=`version:${K}`,Q=(W.rules??[]).map((X,Z)=>({code:X.code?Number(String(X.code).replace(/^#/,""))||Z+1:Z+1,name:X.name??X.title,description:X.description??"",scope:X.scope??"ALL",strictness:X.strictness??"MUST_FOLLOW"}))}else Q=((await q6($)).rules??[]).map((H,W)=>({id:H.id,code:H.code??W+1,name:H.name??H.title,description:H.description??"",scope:H.scope??"ALL",strictness:H.strictness??"MUST_FOLLOW",status:H.status}));return{saved:!0,path:WP0(I,{corpId:U.corp.id,source:J,versionNumber:K,exportedAt:new Date().toISOString(),rulesCount:Q.length,rules: Line truncated
`+"为防止测试单据污染生产审批流,禁止向生产环境重放单据。请指定测试企业 (--target-corp <testCorpId>),或在确有需要时添加 --force。",1,`seal-use webhook replay --target-corp <testCorpId>${U.id!==I.id?` --source-corp ${U.id}`:""}`);return{sourceCorp:U,targetCorp:I}}async function Zp($,Y,U){let I=Y.seal?.endpoints?.approvalStylePreferences??"api/v1/agent/ai-approval/config",Q=await Z$($,I);if(U||Q.length>0)return DP0(Q,U,Y.id);if(Y.environment==="test"||Y.id.toLowerCase().includes("test")){console.error(`[webhook-replay] 测试企业「${Y.name}」未配置 Webhook 通道,正在自动创建「(Seal测-回放通道)」...`);let J=(Y.seal.url??Y.source?.sealUrl??`https://${Y.id.toLowerCase()}.sealai.cc`).replace(/\/+$/,"");return await kM($,J,{name:"(Seal测-回放通道)",mode:"assisted",outgoingResultWebhook:`${J}/api/v1/integrations/webhook/replay-mock-callback`},Y.seal.endpoints.approvalStylePreferences)}throw new X4(`当前租户「${Y.name}」未配置任何 Webhook 集成通道。`,1,`seal-use webhook add --name <name> --result-url <url> --corp ${Y.id}`)}async function Gz($){let{query:Y,sourceClient:U,targetClient:I,sourceCorp:Q,targetCorp:J,webhookSelector:K,snPrefix:z,snSuffix:G,docIdPrefix:H,docIdSuffix:W,dryRun:X,fetchFn:Z=fetch}=$,q=[];if(Y.recordId){let P=await G4(U,Y.recordId);q.push(P)}else if(Y.recordIds&&Y.recordIds.length>0)for(let P of Y.recordIds)q.push(await G4(U,P));else if(Y.sn){let T=(await x4(U,{search:Y.sn,sourceDocumentSN:Y.sn,limit:20})).records.find((B)=>B.sourceDocumentSN===Y.sn||B.sourceDocumentId===Y.sn||B.document?.sourceDocumentSN===Y.sn||B.document?.sn===Y.sn);if(!T)throw Error(`在企业「${Q.name}」中未找到单据编号为「${Y.sn}」的审批记录。`);q.push(T)}else if(Y.sns&&Y.sns.length>0)for(let P of Y.sns){let B=(await x4(U,{search:P,sourceDocumentSN:P,limit:20})).records.find((E)=>E.sourceDocumentSN===P||E.sourceDocumentId===P||E.document?.sourceDocumentSN===P||E.document?.sn===P);if(!B)throw Error(`在企业「${Q.name}」中未找到单据编号为「${P}」的审批记录。`);q.push(B)}else if(Y.limit!==void 0){let P=await x4(U,{limit:Y.limit,status:Y.status,startDate:Y.startDate,endDate:Y.endDate});if(!P.records.length)throw Error(`在企业「${Q.name}」中未检索到符合条件的审批记录。`);q=P.records}else throw Error("Usage: seal-use webhook replay <recordId> [--sn <documentSN>] [--limit <n>] [--webhook <idOrName>] [--source-corp <corpId>] [--target-corp <corpId>] [--dry-run]");let V=q.map((P)=>({run:P,doc:Wp(P,{snPrefix:z,snSuffix:G,docIdPrefix:H,docIdSuffix:W})}));if(X){let P={id:"preview-webhook",name:K??"预览目标通道",mode:"assisted",incomingDocumentWebhookUrl:`${J.seal.url}/api/v1/integrations/webhook/preview`};try{let E=await Z$(I,J.seal.endpoints.approvalStylePreferences);if(E.length>0){let C=DP0(E,K,J.id);P={id:C.id,name:C.name,mode:C.mode,incomingDocumentWebhookUrl:C.incomingDocumentWebhook.url}}}catch{}let T=V.map(({run:E,doc:C})=>({originalRecord:{id:E.id,sourceSystem:E.sourceSystem,sourceDocumentSN:E.sourceDocumentSN,sourceDocumentId:E.sourceDocumentId},document:C,success:!0})),B=T.length===1;return{dryRun:!0,success:!0,sourceCorp:{id:Q.id,name:Q.name,environment:Q.environment},targetCorp:{id:J.id,name:J.name,environment:J.environment},targetWebhook:P,totalCount:T.length,successCount:T.length,failureCount:0,originalRecord:B?T[0].originalRecord:void 0,document:B?T[0].document:void 0,records:T}}let w=await Zp(I,J,K),M={id:w.id,name:w.name,mode:w.mode,incomingDocumentWebhookUrl:w.incomingDocumentWebhook.url},F=[],N=0,O=0;for(let{run:P,doc:T}of V){console.error(`[webhook-replay] 正在向 Webhook 通道「${w.name}」推送单据: ${T.documentSN}...`);try{let B=await Xp(w.incomingDocumentWebhook.url,w.secret,T,Z,P6(J.seal));F.push({originalRecord:{id:P.id,sourceSystem:P.sourceSystem,sourceDocumentSN:P.sourceDocumentSN,sourceDocumentId:P.sourceDocumentId},replayedDocument:{documentSN:T.documentSN,documentId:T.documentId,fieldCount:T.fields.length},pushResult:B,success:!0}),N+=1}catch(B){let E=B instanceof Error?B.message:String(B);F.push({originalRecord:{id:P.id,sourceSystem:P.sourceSystem,sourceDocumentSN:P.sourceDocumentSN,sourceDocumentId:P.sourceDocumentId},replayedDocument:{documentSN:T.documentSN,documentId:T.documentId,fieldCount:T.fields.length},error:E,success:!1}),O+=1}}let D=F.length===1;return{success:O===0,dryRun:!1,sourceCorp:{id:Q.id,name:Q.name,environment:Q.environment},targetCorp:{id:J.id,name:J.name,environment:J.environment},targetWebhook:M,totalCount:F.length,successCount:N,failureCount:O,originalRecord:D?F[0].originalRecord:void 0,replayedDocument:D?F[0].replayedDocument:void 0,pushResult:D?F[0].pushResult:void 0,records:F}}var gP1;var sZ=m(()=>{DP();BP();H4();gP1=new Set(["TEXT","NUMBER","DATE","AMOUNT","PERSON","ATTACHMENT","DATE_RANGE","DEPARTMENT","LIST","CITY","OBJECT"])});var BP0,R5;var Hz=m(()=>{BP0=class BP0 extends Error{errors;warnings;constructor($,Y= Line truncated
`));this.errors=$;this.warnings=Y;this.name="ResourcePackValidationError"}};R5=BP0});var EP0=j((D54,TP0)=>{TP0.exports=PP;function PP(){this.pending=0,this.max=1/0,this.listeners=[],this.waiting=[],this.error=null}PP.prototype.go=function($){if(this.pending<this.max)PP0(this,$);else this.waiting.push($)};PP.prototype.wait=function($){if(this.pending===0)$(this.error);else this.listeners.push($)};PP.prototype.hold=function(){return AP0(this)};function AP0($){$.pending+=1;var Y=!1;return U;function U(Q){if(Y)throw Error("callback called twice");if(Y=!0,$.error=$.error||Q,$.pending-=1,$.waiting.length>0&&$.pending<$.max)PP0($,$.waiting.shift());else if($.pending===0){var J=$.listeners;$.listeners=[],J.forEach(I)}}function I(Q){Q($.error)}}function PP0($,Y){Y(AP0($))}});var RP0=j((fP1)=>{var qp=K0("fs"),Vp=K0("util"),jP0=K0("stream"),CP0=jP0.Readable,kP1=jP0.PassThrough,xP1=EP0(),TP=K0("events").EventEmitter;fP1.BufferSlicer=Xz;fP1.FdSlicer=Wz;Vp.inherits(Wz,TP);function Wz($){TP.call(this),this.fd=$,this.pend=new xP1,this.pend.max=1,this.refCount=0}Wz.prototype.read=function($,Y,U,I,Q){var J=this;J.pend.go(function(K){qp.read(J.fd,$,Y,U,I,function(z,G,H){K(),Q(z,G,H)})})};Wz.prototype.createReadStream=function($){return new aZ(this,$)};Wz.prototype.ref=function(){this.refCount+=1};Wz.prototype.unref=function(){var $=this;if($.refCount-=1,$.refCount<0)throw Error("invalid unref");if($.refCount>0)return;qp.close($.fd,Y);function Y(U){if(U)$.emit("error",U);else $.emit("close")}};Vp.inherits(aZ,CP0);function aZ($,Y){Y=Y||{},CP0.call(this,Y),this.context=$,this.context.ref(),this.start=Y.start||0,this.endOffset=Y.end,this.pos=this.start}aZ.prototype._read=function($){var Y=this,U=Math.min(Y._readableState.highWaterMark,$);if(Y.endOffset!=null)U=Math.min(U,Y.endOffset-Y.pos);if(U<=0){Y.push(null),this._cleanup();return}Y.context.pend.go(function(I){var Q=Buffer.allocUnsafe(U);qp.read(Y.context.fd,Q,0,U,Y.pos,function(J,K){if(J)Y.destroy(J);else if(K===0)Y.push(null),Y._cleanup();else Y.pos+=K,Y.push(Q.slice(0,K));I()})})};aZ.prototype._destroy=function($,Y){this._cleanup(),Y($)};aZ.prototype._cleanup=function(){if(this.context!=null)this.context.unref(),this.context=null};Vp.inherits(Xz,TP);function Xz($){TP.call(this),this.refCount=0,this.buffer=$}Xz.prototype.read=function($,Y,U,I,Q){if(!(0<=Y&&Y<=$.length))throw RangeError("offset outside buffer: 0 <= "+Y+" <= "+$.length);if(I<0)throw RangeError("position is negative: "+I);if(Y+U>$.length)U=$.length-Y;if(I+U>this.buffer.length)U=this.buffer.length-I;if(U<=0){setImmediate(function(){Q(null,0)});return}this.buffer.copy($,Y,I,I+U),setImmediate(function(){Q(null,U)})};Xz.prototype.createReadStream=function($){$=$||{};var Y=new kP1($);Y.start=$.start||0,Y.endOffset=$.end,Y.pos=Y.endOffset||this.buffer.length;var U=this.buffer.slice(Y.start,Y.pos),I=65536,Q=0;while(!0){var J=Q+I;if(J>=U.length){if(Q<U.length)Y.write(U.slice(Q,U.length));break}Y.write(U.slice(Q,J)),Q=J}return Y.end(),Y};Xz.prototype.ref=function(){this.refCount+=1};Xz.prototype.unref=function(){if(this.refCount-=1,this.refCount<0)throw Error("invalid unref")}});var vP0=j((A54,_P0)=>{var iP1=new Int32Array([0,1996959894,3993919788,2567524794,124634137,1886057615,3915621685,2657392035,249268274,2044508324,3772115230,2547177864,162941995,2125561021,3887607047,2428444049,498536548,1789927666,4089016648,2227061214,450548861,1843258603,4107580753,2211677639,325883990,1684777152,4251122042,2321926636,335633487,1661365465,4195302755,2366115317,997073096,1281953886,3579855332,2724688242,1006888145,1258607687,3524101629,2768942443,901097722,1119000684,3686517206,2898065728,853044451,1172266101,3705015759,2882616665,651767980,1373503546,3369554304,3218104598,565507253,1454621731,3485111705,3099436303,671266974,1594198024,3322730930,2970347812,795835527,1483230225,3244367275,3060149565,1994146192,31158534,2563907772,4023717930,1907459465,112637215,2680153253,3904427059,2013776290,251722036,2517215374,3775830040,2137656763,141376813,2439277719,3865271297,1802195444,476864866,2238001368,4066508878,1812370925,453092731,2181625025,4111451223,1706088902,314042704,2344532202,4240017532,1658658271,366619977,2362670323,4224994405,1303535960,984961486,2747007092,3569037538,1256170817,1037604311,2765210733,3554079995,1131014506,879679996,2909243462,3663771856,1141124467,855842277,2852801631,3708648649,1342533948,654459306,3188396048,3373015174,1466479909,544179635,3110523913,3462522015,1591671054,702138776,2966460450,3352799412,1504918807,783551873,3082640443,3233442989,3988292384,2596254646,62317068,1957810842,3939845945,2647816111,81470997,1943803523,3814918930,2489596804,225274430,2053790376,3826175755,2466906013,167816743,2097651377,4027552580,2265490386,503444072,1762050814,4150417245,2154129355,426522225,1852507879,4275313526,2312317920,282753626,1742555852,4189708143,2394877945,397917763,1622183637,3604390888,2714866558,953729732,1340076626,3518719985,2797360999,1068828381,1219638859,3624741850,2936675148,906185462, Line truncated
\v\f\r\x0E\x0F\x10\x11\x12\x13\x14\x15\x16\x17\x18\x19\x1A\x1B\x1C\x1D\x1E\x1F !"#$٪&'()*+,-./0123456789:;<=>?@ABCDEFGHIJKLMNOPQRSTUVWXYZ[\\]^_\`abcdefghijklmnopqrstuvwxyz{|}~°·∙√▒─│┼┤┬├┴┐┌└┘β∞φ±½¼≈«»ﻷﻸ��ﻻﻼ� ­ﺂ£¤ﺄ��ﺎﺏﺕﺙ،ﺝﺡﺥ٠١٢٣٤٥٦٧٨٩ﻑ؛ﺱﺵﺹ؟¢ﺀﺁﺃﺅﻊﺋﺍﺑﺓﺗﺛﺟﺣﺧﺩﺫﺭﺯﺳﺷﺻﺿﻁﻅﻋﻏ¦¬÷×ﻉـﻓﻗﻛﻟﻣﻧﻫﻭﻯﻳﺽﻌﻎﻍﻡﹽّﻥﻩﻬﻰﻲﻐﻕﻵﻶﻝﻙﻱ■�`},ibm864:"cp864",csibm864:"cp864",cp865:{type:"_sbcs",chars:"ÇüéâäàåçêëèïîìÄÅÉæÆôöòûùÿÖÜø£Ø₧ƒáíóúñѪº¿⌐¬½¼¡«¤░▒▓│┤╡╢╖╕╣║╗╝╜╛┐└┴┬├─┼╞╟╚╔╩╦╠═╬╧╨╤╥╙╘╒╓╫╪┘┌█▄▌▐▀αßΓπΣσµτΦΘΩδ∞φε∩≡±≥≤⌠⌡÷≈°∙·√ⁿ²■ "},ibm865:"cp865",csibm865:"cp865",cp866:{type:"_sbcs",chars:"АБВГДЕЖЗИЙКЛМНОПРСТУФХЦЧШЩЪЫЬЭЮЯабвгдежзийклмноп░▒▓│┤╡╢╖╕╣║╗╝╜╛┐└┴┬├─┼╞╟╚╔╩╦╠═╬╧╨╤╥╙╘╒╓╫╪┘┌█▄▌▐▀рстуфхцчшщъыьэюяЁёЄєЇїЎў°∙·√№¤■ "},ibm866:"cp866",csibm866:"cp866",cp869:{type:"_sbcs",chars:"������Ά�·¬¦‘’Έ―ΉΊΪΌ��ΎΫ©Ώ²³ά£έήίϊΐόύΑΒΓΔΕΖΗ½ΘΙ«»░▒▓│┤ΚΛΜΝ╣║╗╝ΞΟ┐└┴┬├─┼ΠΡ╚╔╩╦╠═╬ΣΤΥΦΧΨΩαβγ┘┌█▄δε▀ζηθικλμνξοπρσςτ΄­±υφχ§ψ΅°¨ωϋΰώ■ "},ibm869:"cp869",csibm869:"cp869",cp922:{type:"_sbcs",chars:"€‚ƒ„…†‡ˆ‰Š‹ŒŽ‘’“”•–—˜™š›œžŸ ¡¢£¤¥¦§¨©ª«¬­®‾°±²³´µ·¸¹º»¼½¾¿ÀÁÂÃÄÅÆÇÈÉÊËÌÍÎÏŠÑÒÓÔÕÖרÙÚÛÜÝŽßàáâãäåæçèéêëìíîïšñòóôõö÷øùúûüýžÿ"},ibm922:"cp922",csibm922:"cp922",cp1046:{type:"_sbcs",chars:"ﺈ×÷ﹱˆ■│─┐┌└┘ﹹﹻﹽﹿﹷﺊﻰﻳﻲﻎﻏﻐﻶﻸﻺﻼ ¤ﺋﺑﺗﺛﺟﺣ،­ﺧﺳ٠١٢٣٤٥٦٧٨٩ﺷ؛ﺻﺿﻊ؟ﻋءآأؤإئابةتثجحخدذرزسشصضطﻇعغﻌﺂﺄﺎﻓـفقكلمنهوىيًٌٍَُِّْﻗﻛﻟﻵﻷﻹﻻﻣﻧﻬﻩ�"},ibm1046:"cp1046",csibm1046:"cp1046",cp1124:{type:"_sbcs",chars:"€‚ƒ„…†‡ˆ‰Š‹ŒŽ‘’“”•–—˜™š›œžŸ ЁЂҐЄЅІЇЈЉЊЋЌ­ЎЏАБВГДЕЖЗИЙКЛМНОПРСТУФХЦЧШЩЪЫЬЭЮЯабвгдежзийклмнопрстуфхцчшщъыьэюя№ёђґєѕіїјљњћќ§ўџ"},ibm1124:"cp1124",csibm1124:"cp1124",cp1125:{type:"_sbcs",chars:"АБВГДЕЖЗИЙКЛМНОПРСТУФХЦЧШЩЪЫЬЭЮЯабвгдежзийклмноп░▒▓│┤╡╢╖╕╣║╗╝╜╛┐└┴┬├─┼╞╟╚╔╩╦╠═╬╧╨╤╥╙╘╒╓╫╪┘┌█▄▌▐▀рстуфхцчшщъыьэюяЁёҐґЄєІіЇї·√№¤■ "},ibm1125:"cp1125",csibm1125:"cp1125",cp1129:{type:"_sbcs",chars:"€‚ƒ„…†‡ˆ‰Š‹ŒŽ‘’“”•–—˜™š›œžŸ ¡¢£¤¥¦§œ©ª«¬­®¯°±²³Ÿµ·Œ¹º»¼½¾¿ÀÁÂĂÄÅÆÇÈÉÊË̀ÍÎÏĐÑ̉ÓÔƠÖרÙÚÛÜỮßàáâăäåæçèéêë́íîïđṇ̃óôơö÷øùúûüư₫ÿ"},ibm1129:"cp1129",csibm1129:"cp1129",cp1133:{type:"_sbcs",chars:"€‚ƒ„…†‡ˆ‰Š‹ŒŽ‘’“”•–—˜™š›œžŸ ກຂຄງຈສຊຍດຕຖທນບປຜຝພຟມຢຣລວຫອຮ���ຯະາຳິີຶືຸູຼັົຽ���ເແໂໃໄ່້໊໋໌ໍໆ�ໜໝ₭����������������໐໑໒໓໔໕໖໗໘໙��¢¬¦�"},ibm1133:"cp1133",csibm1133:"cp1133",cp1161:{type:"_sbcs",chars:"��������������������������������่กขฃคฅฆงจฉชซฌญฎฏฐฑฒณดตถทธนบปผฝพฟภมยรฤลฦวศษสหฬอฮฯะัาำิีึืฺุู้๊๋€฿เแโใไๅๆ็่้๊๋์ํ๎๏๐๑๒๓๔๕๖๗๘๙๚๛¢¬¦ "},ibm1161:"cp1161",csibm1161:"cp1161",cp1162:{type:"_sbcs",chars:"€‚ƒ„…†‡ˆ‰Š‹ŒŽ‘’“”•–—˜™š›œžŸ กขฃคฅฆงจฉชซฌญฎฏฐฑฒณดตถทธนบปผฝพฟภมยรฤลฦวศษสหฬอฮฯะัาำิีึืฺุู����฿เแโใไๅๆ็่้๊๋์ํ๎๏๐๑๒๓๔๕๖๗๘๙๚๛����"},ibm1162:"cp1162",csibm1162:"cp1162",cp1163:{type:"_sbcs",chars:"€‚ƒ„…†‡ˆ‰Š‹ŒŽ‘’“”•–—˜™š›œžŸ ¡¢£€¥¦§œ©ª«¬­®¯°±²³Ÿµ·Œ¹º»¼½¾¿ÀÁÂĂÄÅÆÇÈÉÊË̀ÍÎÏĐÑ̉ÓÔƠÖרÙÚÛÜỮßàáâăäåæçèéêë́íîïđṇ̃óôơö÷øùúûüư₫ÿ"},ibm1163:"cp1163",csiLine truncated
\v\f\r\x0E\x0F\x10ỨỰỲỶỸÝỴ\x18\x19\x1A\x1B\x1C\x1D\x1E\x1F !"#$%&'()*+,-./0123456789:;<=>?@ABCDEFGHIJKLMNOPQRSTUVWXYZ[\\]^_\`abcdefghijklmnopqrstuvwxyz{|}~ÀẢÃÁẠẶẬÈẺẼÉẸỆÌỈĨÍỊÒỎÕÓỌỘỜỞỠỚỢÙỦŨ ĂÂÊÔƠƯĐăâêôơưđẶ̀̀̉̃́àảãáạẲằẳẵắẴẮẦẨẪẤỀặầẩẫấậèỂẻẽéẹềểễếệìỉỄẾỒĩíịòỔỏõóọồổỗốộờởỡớợùỖủũúụừửữứựỳỷỹýỵỐ`},georgianacademy:{type:"_sbcs",chars:"€‚ƒ„…†‡ˆ‰Š‹ŒŽ‘’“”•–—˜™š›œžŸ ¡¢£¤¥¦§¨©ª«¬­®¯°±²³´µ·¸¹º»¼½¾¿აბგდევზთიკლმნოპჟრსტუფქღყშჩცძწჭხჯჰჱჲჳჴჵჶçèéêëìíîïðñòóôõö÷øùúûüýþÿ"},georgianps:{type:"_sbcs",chars:"€‚ƒ„…†‡ˆ‰Š‹ŒŽ‘’“”•–—˜™š›œžŸ ¡¢£¤¥¦§¨©ª«¬­®¯°±²³´µ·¸¹º»¼½¾¿აბგდევზჱთიკლმნჲოპჟრსტჳუფქღყშჩცძწჭხჴჯჰჵæçèéêëìíîïðñòóôõö÷øùúûüýþÿ"},pt154:{type:"_sbcs",chars:"ҖҒӮғ„…ҶҮҲүҠӢҢҚҺҸҗ‘’“”•–—ҳҷҡӣңқһҹ ЎўЈӨҘҰ§Ё©Ә«¬ӯ®Ҝ°ұІіҙө·ё№ә»јҪҫҝАБВГДЕЖЗИЙКЛМНОПРСТУФХЦЧШЩЪЫЬЭЮЯабвгдежзийклмнопрстуфхцчшщъыьэюя"},viscii:{type:"_sbcs",chars:`\x00\x01Ẳ\x03\x04ẴẪ\x07\b
\v\f\r\x0E\x0F\x10\x11\x12\x13Ỷ\x15\x16\x17\x18Ỹ\x1A\x1B\x1C\x1DỴ\x1F !"#$%&'()*+,-./0123456789:;<=>?@ABCDEFGHIJKLMNOPQRSTUVWXYZ[\\]^_\`abcdefghijklmnopqrstuvwxyz{|}~ẠẮẰẶẤẦẨẬẼẸẾỀỂỄỆỐỒỔỖỘỢỚỜỞỊỎỌỈỦŨỤỲÕắằặấầẩậẽẹếềểễệốồổỗỠƠộờởịỰỨỪỬơớƯÀÁÂÃẢĂẳẵÈÉÊẺÌÍĨỳĐứÒÓÔạỷừửÙÚỹỵÝỡưàáâãảăữẫèéêẻìíĩỉđựòóôõỏọụùúũủýợỮ`},iso646cn:{type:"_sbcs",chars:`\x00\x01\x02\x03\x04\x05\x06\x07\b
\v\f\r\x0E\x0F\x10\x11\x12\x13\x14\x15\x16\x17\x18\x19\x1A\x1B\x1C\x1D\x1E\x1F !"#¥%&'()*+,-./0123456789:;<=>?@ABCDEFGHIJKLMNOPQRSTUVWXYZ[\\]^_\`abcdefghijklmnopqrstuvwxyz{|}‾��������������������������������������������������������������������������������������������������������������������������������`},iso646jp:{type:"_sbcs",chars:`\x00\x01\x02\x03\x04\x05\x06\x07\b
\v\f\r\x0E\x0F\x10\x11\x12\x13\x14\x15\x16\x17\x18\x19\x1A\x1B\x1C\x1D\x1E\x1F !"#$%&'()*+,-./0123456789:;<=>?@ABCDEFGHIJKLMNOPQRSTUVWXYZ[¥]^_\`abcdefghijklmnopqrstuvwxyz{|}‾��������������������������������������������������������������������������������������������������������������������������������`},hproman8:{type:"_sbcs",chars:"€‚ƒ„…†‡ˆ‰Š‹ŒŽ‘’“”•–—˜™š›œžŸ ÀÂÈÊËÎÏ´ˋˆ¨˜ÙÛ₤¯Ýý°ÇçÑñ¡¿¤£¥§ƒ¢âêôûáéóúàèòùäëöüÅîØÆåíøæÄìÖÜÉïßÔÁÃãÐðÍÌÓÒÕõŠšÚŸÿÞþ·µ¾—¼½ªº«■»±�"},macintosh:{type:"_sbcs",chars:"ÄÅÇÉÑÖÜáàâäãåçéèêëíìîïñóòôöõúùûü†°¢£§•ß®©™´¨≠ÆØ∞±≤≥¥µ∂∑∏π∫ªºΩæø¿¡¬√ƒ≈∆«»… ÀÃÕŒœ–—“”‘’÷◊ÿŸ⁄¤‹›fifl‡·‚„‰ÂÊÁËÈÍÎÏÌÓÔ�ÒÚÛÙıˆ˜¯˘˙˚¸˝˛ˇ"},ascii:{type:"_sbcs",chars:"��������������������������������������������������������������������������������������������������������������������������������"},tis620:{type:"_sbcs",chars:"���������������������������������กขฃคฅฆงจฉชซฌญฎฏฐฑฒณดตถทธนบปผฝพฟภมยรฤลฦวศษสหฬอฮฯะัาำิีึืฺุู����฿เแโใไๅๆ็่้๊๋์ํ๎๏๐๑๒๓๔๕๖๗๘๙๚๛����"}}});var FP0=E((ZP1)=>{var Cd=u3().Buffer;ZP1._dbcs=i3;var I8=-1,LP0=-2,l$=-10,k8=-1000,VK=Array(256),dZ=-1;for(pZ=0;pZ<256;pZ++)VK[pZ]=I8;var pZ;function i3($,Y){if(this.encodingName=$.encodingName,!$)throw Error("DBCS codec is called without the data.");if(!$.table)throw Error("Encoding '"+this.encodingName+"' has no data.");var U=$.table();this.decodeTables=[],this.decodeTables[0]=VK.slice(0),this.decodeTableSeq=[];for(var z=0;z<U.length;z++)this._addDecodeChunk(U[z]);if(typeof $.gb18030==="function"){this.gb18030=$.gb18030();var I=this.decodeTables.length;this.decodeTables.push(VK.slice(0));var Q=this.decodeTables.length;this.decodeTables.push(VK.slice(0));var J=this.decodeTables[0];for(var z=129;z<=254;z++){var K=this.decodeTables[k8-J[z]];for(var G=48;G<=57;G++){if(K[G]===I8)K[G]=k8-I;else if(K[G]>k8)throw Error("gb18030 decode tables conflict at byte 2");var H=this.decodeTables[k8-K[G]];for(var W=129;W<=254;W++){if(H[W]===I8)H[W]=k8-Q;else if(H[W]===k8-Q)continue;else if(H[W]>k8)throw Error("gb18030 decode tables conflict at byte 3");var X=this.decodeTables[k8-H[W]];for(var Z=48;Z<=57;Z++)if(X[Z]===I8)X[Z]=LP0}}}}this.defaultCharUnicode=Y.defaultCharUnicode,this.encodeTable=[],this.encodeTableSeq=[];var q={};if($.encodeSkipVals)for(var z=0;z<$.encodeSkipVals.length;z++){var V=$.encodeSkipVals[z];if(typeof V==="number")q[V]=!0;else for(var G=V.from;G<=V.to;G++)q[G]=!0}if(this._fillEncodeTable(0,0,q),$.encodeAdd){for(var w in $.encodeAdd)if(Object.prototype.hasOwnProperty.call($.encodeAdd,w))this._setEncodeChar(w.charCodeAt(0),$.encodeAdd[w])}if(this.defCharSB=this.encodeTable[0][Y.defaultCharSingleByte.charCodeAt(0)],this.defCharSB===I8)this.defCharSB=this.encodeTable[0]["?"];if(this.defCharSB===I8)this.defCharSB=63}i3.prototype.encoder=BP;i3.prototype.decoder=Rd;i3.prototype._getDecodeTrieNode=function($){var Y=[];for(;$>0;$>>>=8)Y.push($&255);if(Y.length==0)Y.push(0);var U=this.decodeTables[0];for(var z=Y.length-1;z>0;z--){var I=U[Y[z]];if(I==I8)U[Y[z]]=k8-this.decodeTables.length,this.decodeTables.push(U=VK.slice(0));else if(I<=k8)U=this.decodeTables[k8-I];else throw Error("Overwrite byte in "+this.encodingName+", addr: "+$.toString(16))}return U};i3.prototype._addDecodeChunk=function($){var Y=parseInt($[0],16),U=this._getDecodeTrieNode(Y);Y=Y&255;for(var z=1;z<$.length;z++){var I=$[z];if(typeof I==="string")for(var Q=0;Q<I.length;){var J=I.charCodeAt(Q++);if(J>=55296&&J<56320){var K=I.charCodeAt(Q++);if(K>=56320&&K<57344)U[Y++]=65536+(J-55296)*1024+(K-56320);else throw Error("Incorrect surrogate pair in "+this.encodingName+" at chunk "+$[0])}else if(J>4080&&J<=4095){var G=4095-J+2,H=[];for(var W=0;W<G;W++)H.push(I.charCodeAt(Q++));U[Y++]=l$-this.decodeTableSeq.length,this.decodeTableSeq.push(H)}else U[Y++]=J}else if(typeof I==="number"){var X=U[Y-1]+1;for(var Q=0;Q<I;Q++)U[Y++]=X++}else throw Error("Incorrect type '"+typeof I+"' given in "+this.encodingName+" at chunk "+$[0])}if(Y>255)throw Error("Incorrect chunk in "+this.encoLine truncated
`;super(Y);this.name="AggregateError",this.errors=$}}TT0.exports={AggregateError:PT0,ArrayIsArray($){return Array.isArray($)},ArrayPrototypeIncludes($,Y){return $.includes(Y)},ArrayPrototypeIndexOf($,Y){return $.indexOf(Y)},ArrayPrototypeJoin($,Y){return $.join(Y)},ArrayPrototypeMap($,Y){return $.map(Y)},ArrayPrototypePop($,Y){return $.pop(Y)},ArrayPrototypePush($,Y){return $.push(Y)},ArrayPrototypeSlice($,Y,U){return $.slice(Y,U)},Error,FunctionPrototypeCall($,Y,...U){return $.call(Y,...U)},FunctionPrototypeSymbolHasInstance($,Y){return Function.prototype[Symbol.hasInstance].call($,Y)},MathFloor:Math.floor,Number,NumberIsInteger:Number.isInteger,NumberIsNaN:Number.isNaN,NumberMAX_SAFE_INTEGER:Number.MAX_SAFE_INTEGER,NumberMIN_SAFE_INTEGER:Number.MIN_SAFE_INTEGER,NumberParseInt:Number.parseInt,ObjectDefineProperties($,Y){return Object.defineProperties($,Y)},ObjectDefineProperty($,Y,U){return Object.defineProperty($,Y,U)},ObjectGetOwnPropertyDescriptor($,Y){return Object.getOwnPropertyDescriptor($,Y)},ObjectKeys($){return Object.keys($)},ObjectSetPrototypeOf($,Y){return Object.setPrototypeOf($,Y)},Promise,PromisePrototypeCatch($,Y){return $.catch(Y)},PromisePrototypeThen($,Y,U){return $.then(Y,U)},PromiseReject($){return Promise.reject($)},PromiseResolve($){return Promise.resolve($)},ReflectApply:Reflect.apply,RegExpPrototypeTest($,Y){return $.test(Y)},SafeSet:Set,String,StringPrototypeSlice($,Y,U){return $.slice(Y,U)},StringPrototypeToLowerCase($){return $.toLowerCase()},StringPrototypeToUpperCase($){return $.toUpperCase()},StringPrototypeTrim($){return $.trim()},Symbol,SymbolFor:Symbol.for,SymbolAsyncIterator:Symbol.asyncIterator,SymbolHasInstance:Symbol.hasInstance,SymbolIterator:Symbol.iterator,SymbolDispose:Symbol.dispose||Symbol("Symbol.dispose"),SymbolAsyncDispose:Symbol.asyncDispose||Symbol("Symbol.asyncDispose"),TypedArrayPrototypeSet($,Y,U){return $.set(Y,U)},Boolean,Uint8Array}});var td=E((T84,jT0)=>{jT0.exports={format($,...Y){return $.replace(/%([sdifj])/g,function(...[U,z]){let I=Y.shift();if(z==="f")return I.toFixed(6);else if(z==="j")return JSON.stringify(I);else if(z==="s"&&typeof I==="object")return`${I.constructor!==Object?I.constructor.name:""} {}`.trim();else return I.toString()})},inspect($){switch(typeof $){case"string":if($.includes("'")){if(!$.includes('"'))return`"${$}"`;else if(!$.includes("`")&&!$.includes("${"))return`\`${$}\``}return`'${$}'`;case"number":if(isNaN($))return"NaN";else if(Object.is($,-0))return String($);return $;case"bigint":return`${String($)}n`;case"boolean":case"undefined":return String($);case"object":return"{}"}}}});var D8=E((j84,_T0)=>{var{format:Qj1,inspect:RP}=td(),{AggregateError:Jj1}=f4(),Kj1=globalThis.AggregateError||Jj1,Gj1=Symbol("kIsNodeError"),Hj1=["string","function","number","object","Function","Object","boolean","bigint","symbol"],Wj1=/^([A-Z][a-z0-9]*)+$/,_P={};function Mz($,Y){if(!$)throw new _P.ERR_INTERNAL_ASSERTION(Y)}function ET0($){let Y="",U=$.length,z=$[0]==="-"?1:0;for(;U>=z+4;U-=3)Y=`_${$.slice(U-3,U)}${Y}`;return`${$.slice(0,U)}${Y}`}function Xj1($,Y,U){if(typeof Y==="function")return Mz(Y.length<=U.length,`Code: ${$}; The provided arguments length (${U.length}) does not match the required ones (${Y.length}).`),Y(...U);let z=(Y.match(/%[dfijoOs]/g)||[]).length;if(Mz(z===U.length,`Code: ${$}; The provided arguments length (${U.length}) does not match the required ones (${z}).`),U.length===0)return Y;return Qj1(Y,...U)}function Q8($,Y,U){if(!U)U=Error;class z extends U{constructor(...I){super(Xj1($,Y,I))}toString(){return`${this.name} [${$}]: ${this.message}`}}Object.defineProperties(z.prototype,{name:{value:U.name,writable:!0,enumerable:!1,configurable:!0},toString:{value(){return`${this.name} [${$}]: ${this.message}`},writable:!0,enumerable:!1,configurable:!0}}),z.prototype.code=$,z.prototype[Gj1]=!0,_P[$]=z}function CT0($){let Y="__node_internal_"+$.name;return Object.defineProperty($,"name",{value:Y}),$}function Zj1($,Y){if($&&Y&&$!==Y){if(Array.isArray(Y.errors))return Y.errors.push($),Y;let U=new Kj1([Y,$],Y.message);return U.code=Y.code,U}return $||Y}class RT0 extends Error{constructor($="The operation was aborted",Y=void 0){if(Y!==void 0&&typeof Y!=="object")throw new _P.ERR_INVALID_ARG_TYPE("options","Object",Y);super($,Y);this.code="ABORT_ERR",this.name="AbortError"}}Q8("ERR_ASSERTION","%s",Error);Q8("ERR_INVALID_ARG_TYPE",($,Y,U)=>{if(Mz(typeof $==="string","'name' must be a string"),!Array.isArray(Y))Y=[Y];let z="The ";if($.endsWith(" argument"))z+=`${$} `;else z+=`"${$}" ${$.includes(".")?"property":"argument"} `;z+="must be ";let I=[],Q=[],J=[];for(let G of Y)if(Mz(typeof G==="string","All expected entries have to be of type string"),Hj1.includes(G))I.push(G.toLowerCase());else if(Wj1.test(G))Q.push(G);else Mz(G!=="object",'The value "object" should be written as "Object"'),J.push(G);if(Q.length>0){let G=I.indexOf("object");if(G!==-1)I.splice(I,G,1),Q.push("Object")}if(I.length>0){switch(I.length){case 1:z+=`of type ${I[Line truncated
`);if(Y.linkname)U+=Cl(" linkpath="+Y.linkname+`
`);let z=Y.pax;if(z)for(let I in z)U+=Cl(" "+I+"="+z[I]+`
`);return n1.from(U)};HS1.decodePax=function(Y){let U={};while(Y.length){let z=0;while(z<Y.length&&Y[z]!==32)z++;let I=parseInt(n1.toString(Y.subarray(0,z)),10);if(!I)return U;let Q=n1.toString(Y.subarray(z+1,I-1)),J=Q.indexOf("=");if(J===-1)return U;U[Q.slice(0,J)]=Q.slice(J+1),Y=Y.subarray(I)}return U};HS1.encode=function(Y){let U=n1.alloc(512),z=Y.name,I="";if(Y.typeflag===5&&z[z.length-1]!=="/")z+="/";if(n1.byteLength(z)!==z.length)return null;while(n1.byteLength(z)>100){let Q=z.indexOf("/");if(Q===-1)return null;I+=I?"/"+z.slice(0,Q):z.slice(0,Q),z=z.slice(Q+1)}if(n1.byteLength(z)>100||n1.byteLength(I)>155)return null;if(Y.linkname&&n1.byteLength(Y.linkname)>100)return null;if(n1.write(U,z),n1.write(U,a2(Y.mode&4095,6),100),n1.write(U,a2(Y.uid,6),108),n1.write(U,a2(Y.gid,6),116),KS1(Y.size,U,124),n1.write(U,a2(Y.mtime.getTime()/1000|0,11),136),U[156]=48+QS1(Y.type),Y.linkname)n1.write(U,Y.linkname,157);if(n1.copy($_0,U,257),n1.copy(th1,U,263),Y.uname)n1.write(U,Y.uname,265);if(Y.gname)n1.write(U,Y.gname,297);if(n1.write(U,a2(Y.devmajor||0,6),329),n1.write(U,a2(Y.devminor||0,6),337),I)n1.write(U,I,345);return n1.write(U,a2(U_0(U),6),148),U};HS1.decode=function(Y,U,z){let I=Y[156]===0?0:Y[156]-48,Q=gK(Y,0,100,U),J=s2(Y,100,8),K=s2(Y,108,8),G=s2(Y,116,8),H=s2(Y,124,12),W=s2(Y,136,12),X=IS1(I),Z=Y[157]===0?null:gK(Y,157,100,U),q=gK(Y,265,32),V=gK(Y,297,32),w=s2(Y,329,8),M=s2(Y,337,8),F=U_0(Y);if(F===256)return null;if(F!==s2(Y,148,8))throw Error("Invalid tar header. Maybe the tar is corrupted or it needs to be gunzipped?");if(YS1(Y)){if(Y[345])Q=gK(Y,345,155,U)+"/"+Q}else if(US1(Y));else if(!z)throw Error("Invalid tar header: unknown format.");if(I===0&&Q&&Q[Q.length-1]==="/")I=5;return{name:Q,mode:J,uid:K,gid:G,size:H,byteOffset:0,mtime:new Date(1000*W),type:X,linkname:Z,uname:q,gname:V,devmajor:w,devminor:M,pax:null}};function YS1($){return n1.equals($_0,$.subarray(257,263))}function US1($){return n1.equals(eh1,$.subarray(257,263))&&n1.equals($S1,$.subarray(263,265))}function zS1($,Y,U){if(typeof $!=="number")return U;if($=~~$,$>=Y)return Y;if($>=0)return $;if($+=Y,$>=0)return $;return 0}function IS1($){switch($){case 0:return"file";case 1:return"link";case 2:return"symlink";case 3:return"character-device";case 4:return"block-device";case 5:return"directory";case 6:return"fifo";case 7:return"contiguous-file";case 72:return"pax-header";case 55:return"pax-global-header";case 27:return"gnu-long-link-path";case 28:case 30:return"gnu-long-path"}return null}function QS1($){switch($){case"file":return 0;case"link":return 1;case"symlink":return 2;case"character-device":return 3;case"block-device":return 4;case"directory":return 5;case"fifo":return 6;case"contiguous-file":return 7;case"pax-header":return 72}return 0}function Y_0($,Y,U,z){for(;U<z;U++)if($[U]===Y)return U;return z}function U_0($){let Y=256;for(let U=0;U<148;U++)Y+=$[U];for(let U=156;U<512;U++)Y+=$[U];return Y}function a2($,Y){if($=$.toString(8),$.length>Y)return"7777777777777777777".slice(0,Y)+" ";return"0000000000000000000".slice(0,Y-$.length)+$+" "}function JS1($,Y,U){Y[U]=128;for(let z=11;z>0;z--)Y[U+z]=$&255,$=Math.floor($/256)}function KS1($,Y,U){if($.toString(8).length>11)JS1($,Y,U);else n1.write(Y,a2($,11),U)}function GS1($){let Y;if($[0]===128)Y=!0;else if($[0]===255)Y=!1;else return null;let U=[],z;for(z=$.length-1;z>0;z--){let J=$[z];if(Y)U.push(J);else U.push(255-J)}let I=0,Q=U.length;for(z=0;z<Q;z++)I+=U[z]*Math.pow(256,z);return Y?I:-1*I}function s2($,Y,U){if($=$.subarray(Y,Y+U),Y=0,$[Y]&128)return GS1($);else{while(Y<$.length&&$[Y]===32)Y++;let z=zS1(Y_0($,32,Y,$.length),$.length,$.length);while(Y<z&&$[Y]===0)Y++;if(z===Y)return 0;return parseInt(n1.toString($.subarray(Y,z)),8)}}function gK($,Y,U,z){return n1.toString($.subarray(Y,Y_0($,0,Y,Y+U)),z)}function Cl($){let Y=n1.byteLength($),U=Math.floor(Math.log(Y)/Math.log(10))+1;if(Y+U>=Math.pow(10,U))U++;return Y+U+$}});var W_0=E((F54,H_0)=>{var{Writable:LS1,Readable:FS1,getStreamError:z_0}=El(),wS1=Ol(),I_0=SK(),yK=Rl(),MS1=I_0.alloc(0);class Q_0{constructor(){this.buffered=0,this.shifted=0,this.queue=new wS1,this._offset=0}push($){this.buffered+=$.byteLength,this.queue.push($)}shiftFirst($){return this.buffered===0?null:this._next($)}shift($){if($>this.buffered)return null;if($===0)return MS1;let Y=this._next($);if($===Y.byteLength)return Y;let U=[Y];while(($-=Y.byteLength)>0)Y=this._next($),U.push(Y);return I_0.concat(U)}_next($){let Y=this.queue.peek(),U=Y.byteLength-this._offset;if($>=U){let z=this._offset?Y.subarray(this._offset,Y.byteLength):Y;return this.queue.shift(),this._offset=0,this.buffered-=U,this.shifted+=U,z}return this.buffered-=$,this.shifted+=$,Y.subarray(this._offset,this._offset+=$)}}class J_0 extends FS1{constructor($,Y,U){super();this.header=Y,this.offset=U,this._parent=$}_read($){if(this.header.size===0)this.push(null);if(this._parent._stream===this)this._parent._update();$(null)}_predestroy(){this._parent.destroy(z_0(this))}_detach(){if(this._parent._stream= Line truncated
`),z=[await H4($,U.recordId)];else if(U.recordIds&&U.recordIds.length>0)process.stderr.write(`\uD83D\uDD0D 批量查询 ${U.recordIds.length} 条单据记录...
`),z=await Promise.all(U.recordIds.map((F)=>H4($,F)));else{let F=U.limit??10;process.stderr.write(`\uD83D\uDD0D 检索企业「${Y.name}」(${Y.id}) 的线上审核记录 (限制 ${F} 条)...
`);let O=(await i4($,{limit:F,status:U.status,startDate:U.startDate!==void 0?String(U.startDate):void 0,endDate:U.endDate!==void 0?String(U.endDate):void 0})).records??[];if(O.length===0)throw Error("未检索到符合条件的线上审核记录,无法导出 webhook 资源包。");process.stderr.write(`\uD83D\uDCE5 正在拉取 ${O.length} 条审核记录完整详情...
`),z=await Promise.all(O.map((D)=>H4($,D.id)))}let I=new Map,Q=0;for(let F of z){let N=F.document,O=F.sourceDocumentId??(typeof N?.id==="string"?N.id:void 0)??(typeof N?.sourceDocumentId==="string"?N.sourceDocumentId:void 0)??F.documentId??F.id,D=`${U.docIdPrefix??""}${O}${U.docIdSuffix??""}`,P=[];if(U.includeAttachments!==!1){let A=c2(F,{summary:!1}).attachments,j=new Set;for(let C of A){let b=C.ossSignedUrl??C.url;if(!b)continue;let x=C.fileName??C.fileId??"attachment",g=Dp(x),i=g,c=g.lastIndexOf("."),z0=c>0?g.slice(0,c):g,k=c>0?g.slice(c):"",d=1;while(j.has(i.toLowerCase()))i=`${z0}_${d}${k}`,d++;j.add(i.toLowerCase());try{process.stderr.write(`⬇ 下载单据「${D}」附件: ${x}...
`);let a=await fetch(b);if(a.ok){let $0=await a.arrayBuffer(),y=Buffer.from($0);P.push({fileName:i,zipPath:`${D}/${i}`,buffer:y,sourceField:C.sourceField??"附件"}),Q++}}catch(a){process.stderr.write(`⚠️ [跳过附件] 下载失败 ${x}: ${a}
`)}}}I.set(D,P)}let J=new C_0.default.Workbook;J.creator="seal-use",J.created=new Date;let K=new Set;for(let F of I.values())for(let N of F)K.add(N.sourceField);if(K.size===0)K.add("附件");let G=new Set;for(let F of z){let N=F.document,O=Array.isArray(N?.fields)?N.fields:[];for(let D of O)if(D&&typeof D==="object"){let P=D,T=typeof P.label==="string"?P.label.trim():typeof P.key==="string"?P.key.trim():"",A=typeof P.type==="string"?P.type.toUpperCase():"";if(T&&A!=="ATTACHMENT"&&A!=="LIST")G.add(T)}}let H=["会议编号","会议名称","状态","总金额","报销事由","申请日期"],W=Array.from(G).filter((F)=>!H.includes(F)&&F!=="单据编号"&&F!=="单号"),X=Array.from(K).map((F)=>`[附件]${F}`),Z=[...H,...W,...X],q=J.addWorksheet("主表");q.addRow(Z),q.getRow(1).font={bold:!0};for(let F of z){let N=F.document,O=F.sourceDocumentSN??(typeof N?.sn==="string"?N.sn:void 0)??(typeof N?.sourceDocumentSN==="string"?N.sourceDocumentSN:void 0)??F.id,D=F.sourceDocumentId??(typeof N?.id==="string"?N.id:void 0)??(typeof N?.sourceDocumentId==="string"?N.sourceDocumentId:void 0)??F.documentId??F.id,P=`${U.docIdPrefix??""}${D}${U.docIdSuffix??""}`,T=`${U.docIdPrefix??""}${O}${U.docIdSuffix??""}`,A=(typeof N?.title==="string"?N.title:void 0)??(typeof N?.name==="string"?N.name:void 0)??T,j="";if(typeof N?.sourceStartTime==="number")j=new Date(N.sourceStartTime*1000).toLocaleDateString("en-CA",{timeZone:"Asia/Shanghai"});else if(typeof F.createdAt==="number")j=new Date(F.createdAt).toLocaleDateString("en-CA",{timeZone:"Asia/Shanghai"});else if(typeof F.createdAt==="string")j=F.createdAt.slice(0,10);let C=new Map,b=Array.isArray(N?.fields)?N.fields:[];for(let z0 of b)if(z0&&typeof z0==="object"){let k=z0,d=typeof k.label==="string"?k.label.trim():typeof k.key==="string"?k.key.trim():"";if(d)C.set(d,k.value)}let x,g=C.get("总金额")??C.get("报销金额")??C.get("total_amount");if(typeof g==="number")x=g;else if(g&&typeof g==="object"&&"amount"in g&&typeof g.amount==="number")x=g.amount;let i=[];i.push(P),i.push(A),i.push(F.status??"已审批"),i.push(x??""),i.push(C.get("报销事由")??C.get("事由")??A),i.push(j);for(let z0 of W){let k=C.get(z0);if(k===void 0||k===null)i.push("");else if(typeof k==="object")if("amount"in k)i.push(k.amount);else i.push(JSON.stringify(k));else i.push(k)}let c=I.get(P)??[];for(let z0 of K){let k=c.filter((d)=>d.sourceField===z0||K.size===1);if(k.length>0)i.push(k.map((d)=>d.zipPath).join(`
`));else i.push("")}q.addRow(i)}let V=xS1(U,Y);hS1(yS1(V),{recursive:!0});let w=await J.xlsx.writeBuffer();process.stderr.write(`\uD83D\uDCE6 正在压缩生成 Webhook 资源包: ${V}...
`),await new Promise((F,N)=>{let O=vS1(V),D=new gl({zlib:{level:9}});O.on("close",()=>F()),D.on("error",(P)=>N(P)),D.pipe(O),D.append(Buffer.from(w),{name:"信息表.xlsx"});for(let P of I.values())for(let T of P)D.append(T.buffer,{name:T.zipPath});D.finalize()});let M=SS1(V);return{filePath:V,corpId:Y.id,corpName:Y.name,recordCount:z.length,attachmentCount:Q,fileSizeBytes:M.size,exportedAt:new Date().toISOString(),nextAction:`seal-use webhook resource-pack push ${V} --corp <targetCorpId>`}}var C_0;var yl=m(()=>{j_0();X6();oB();C_0=I6(_Z(),1)});import{readFileSync as fS1}from"node:fs";function uS1($){let Y=new URL($),U=Y.pathname.match(/\/webhook\/([^/]+)/);if(!U)throw Error("Webhook URL 必须包含 /webhook/{webhookId}/document");return{baseUrl:`${Y.protocol}//${Y.host}`,webhookId:U[1]}}function bS1($,Y){return Y.toLowerCase().endsWith(".zip")||$[0]===80&&$[1]===75&&!Y.toLowerCase().endsWith(".xlsx")}function iS1($,Y){if(!$.length)return;let U=new Set($.map((Q)=>{let J=Q.fileName.split("/")[0],K=J.indexOf("@");return K>=0?J.slice(0,K):J}).filter((Q)=>Q!=="信息表.xlsx")),z=[];for(let Q of Y){let J=Q.document.documentId;if((Q.documentAttachments.length>0||Object.values(Q.expenseAttachments).some((G)=>G.length>0)||Object.values(Q.personAttachments).some((G)=>G.length>0))&&!U.has(J))z.push(`Excel 会议编号「${J}」声明了附件,但在 ZIP 中找不到对应的根目录「${J}/」或「${J}@.../」。`)}let I=new Set(Y.map((Q)=>Q.document.documentId));for(let Q of U)if(!I.has(Q))z.push(`ZIP 根目录对应的编号「${Q}」在信息表中找不到对应的会议编号。`);if(z.length)throw new j5(z)}async function R_0($,Y,U){let z=[],I=$;if(bS1($,Y)){z=await uP0($),iP0(z,U);let G=z.find((H)=>H.fileName==="信息表.xlsx");if(!G)throw Error("ZIP 根目录缺少信息表.xlsx");I=await yd($,G)}let Q=await oP0(I);iS1(z,Q);let J=rP0(z,Q),K=Q.map((G)=>G.document);return{entries:z,parsed:Q,plans:J,documents:K,fileBuffer:$}}async function kz($,Y,U){let z=await R_0($,Y,U),I=z.parsed.map((Q,J)=>id(Q.document,z.plans[J],new Map));return{warnings:[],documents:I,attachmentPlan:z.plans}}async function OT($,Y,U){let z=await R_0($,Y,U.materialPackFilePolicy),{baseUrl:I,webhookId:Q}=uS1(U.webhookUrl),J=[];for(let K=0;K<z.parsed.length;K+=1){let G=z.parsed[K],H=z.plans[K],W=new Map,X=[...H.categoryFields,...Object.values(H.personAttachments).flat(),...Object.values(H.expenseAttachments).flat()];for(let V of X)for(let w of V.paths){if(W.has(w))continue;let M=z.entries.find((T)=>T.fileName===w);if(!M)continue;process.stderr.write(`⬆ 上传附件: ${w}
`);let F=new FormData,N=await yd(z.fileBuffer,M),O=w.split("/").pop()??w;F.append("files",new File([new Uint8Array(N)],O));let D=await fetch(`${I}/api/v1/integrations/webhook/${encodeURIComponent(Q)}/attachments`,{method:"POST",headers:{...U.customHeaders??{},...uZ({},U.secret)},body:F});if(!D.ok)throw Error(`附件上传失败 ${D.status}: ${await D.text()}`);let P=await D.json();W.set(w,P.attachments?.map((T)=>T.data)??(P.data===void 0?[]:[P.data])),process.stderr.write(`✓ 附件上传成功: ${w}
\v\f\r\x0E\x0F\x10\x11\x12\x13\x14\x15\x16\x17\x18\x19\x1A\x1B\x1C\x1D\x1E\x1F !"#$%&'()*+,-./0123456789:;<=>?@ABCDEFGHIJKLMNOPQRSTUVWXYZ[¥]^_\`abcdefghijklmnopqrstuvwxyz{|}‾��������������������������������������������������������������������������������������������������������������������������������`},hproman8:{type:"_sbcs",chars:"€‚ƒ„…†‡ˆ‰Š‹ŒŽ‘’“”•–—˜™š›œžŸ ÀÂÈÊËÎÏ´ˋˆ¨˜ÙÛ₤¯Ýý°ÇçÑñ¡¿¤£¥§ƒ¢âêôûáéóúàèòùäëöüÅîØÆåíøæÄìÖÜÉïßÔÁÃãÐðÍÌÓÒÕõŠšÚŸÿÞþ·µ¾—¼½ªº«■»±�"},macintosh:{type:"_sbcs",chars:"ÄÅÇÉÑÖÜáàâäãåçéèêëíìîïñóòôöõúùûü†°¢£§•ß®©™´¨≠ÆØ∞±≤≥¥µ∂∑∏π∫ªºΩæø¿¡¬√ƒ≈∆«»… ÀÃÕŒœ–—“”‘’÷◊ÿŸ⁄¤‹›fifl‡·‚„‰ÂÊÁËÈÍÎÏÌÓÔ�ÒÚÛÙıˆ˜¯˘˙˚¸˝˛ˇ"},ascii:{type:"_sbcs",chars:"��������������������������������������������������������������������������������������������������������������������������������"},tis620:{type:"_sbcs",chars:"���������������������������������กขฃคฅฆงจฉชซฌญฎฏฐฑฒณดตถทธนบปผฝพฟภมยรฤลฦวศษสหฬอฮฯะัาำิีึืฺุู����฿เแโใไๅๆ็่้๊๋์ํ๎๏๐๑๒๓๔๕๖๗๘๙๚๛����"}}});var HT0=j((uT1)=>{var sp=n3().Buffer;uT1._dbcs=p3;var z8=-1,GT0=-2,a$=-10,u8=-1000,Mz=Array(256),$q=-1;for(eZ=0;eZ<256;eZ++)Mz[eZ]=z8;var eZ;function p3($,Y){if(this.encodingName=$.encodingName,!$)throw Error("DBCS codec is called without the data.");if(!$.table)throw Error("Encoding '"+this.encodingName+"' has no data.");var U=$.table();this.decodeTables=[],this.decodeTables[0]=Mz.slice(0),this.decodeTableSeq=[];for(var I=0;I<U.length;I++)this._addDecodeChunk(U[I]);if(typeof $.gb18030==="function"){this.gb18030=$.gb18030();var Q=this.decodeTables.length;this.decodeTables.push(Mz.slice(0));var J=this.decodeTables.length;this.decodeTables.push(Mz.slice(0));var K=this.decodeTables[0];for(var I=129;I<=254;I++){var z=this.decodeTables[u8-K[I]];for(var G=48;G<=57;G++){if(z[G]===z8)z[G]=u8-Q;else if(z[G]>u8)throw Error("gb18030 decode tables conflict at byte 2");var H=this.decodeTables[u8-z[G]];for(var W=129;W<=254;W++){if(H[W]===z8)H[W]=u8-J;else if(H[W]===u8-J)continue;else if(H[W]>u8)throw Error("gb18030 decode tables conflict at byte 3");var X=this.decodeTables[u8-H[W]];for(var Z=48;Z<=57;Z++)if(X[Z]===z8)X[Z]=GT0}}}}this.defaultCharUnicode=Y.defaultCharUnicode,this.encodeTable=[],this.encodeTableSeq=[];var q={};if($.encodeSkipVals)for(var I=0;I<$.encodeSkipVals.length;I++){var V=$.encodeSkipVals[I];if(typeof V==="number")q[V]=!0;else for(var G=V.from;G<=V.to;G++)q[G]=!0}if(this._fillEncodeTable(0,0,q),$.encodeAdd){for(var w in $.encodeAdd)if(Object.prototype.hasOwnProperty.call($.encodeAdd,w))this._setEncodeChar(w.charCodeAt(0),$.encodeAdd[w])}if(this.defCharSB=this.encodeTable[0][Y.defaultCharSingleByte.charCodeAt(0)],this.defCharSB===z8)this.defCharSB=this.encodeTable[0]["?"];if(this.defCharSB===z8)this.defCharSB=63}p3.prototype.encoder=fP;p3.prototype.decoder=ap;p3.prototype._getDecodeTrieNode=function($){var Y=[];for(;$>0;$>>>=8)Y.push($&255);if(Y.length==0)Y.push(0);var U=this.decodeTables[0];for(var I=Y.length-1;I>0;I--){var Q=U[Y[I]];if(Q==z8)U[Y[I]]=u8-this.decodeTables.length,this.decodeTables.push(U=Mz.slice(0));else if(Q<=u8)U=this.decodeTables[u8-Q];else throw Error("Overwrite byte in "+this.encodingName+", addr: "+$.toString(16))}return U};p3.prototype._addDecodeChunk=function($){var Y=parseInt($[0],16),U=this._getDecodeTrieNode(Y);Y=Y&255;for(var I=1;I<$.length;I++){var Q=$[I];if(typeof Q==="string")for(var J=0;J<Q.length;){var K=Q.charCodeAt(J++);if(K>=55296&&K<56320){var z=Q.charCodeAt(J++);if(z>=56320&&z<57344)U[Y++]=65536+(K-55296)*1024+(z-56320);else throw Error("Incorrect surrogate pair in "+this.encodingName+" at chunk "+$[0])}else if(K>4080&&K<=4095){var G=4095-K+2,H=[];for(var W=0;W<G;W++)H.push(Q.charCodeAt(J++));U[Y++]=a$-this.decodeTableSeq.length,this.decodeTableSeq.push(H)}else U[Y++]=K}else if(typeof Q==="number"){var X=U[Y-1]+1;for(var J=0;J<Q;J++)U[Y++]=X++}else throw Error("Incorrect type '"+typeof Q+"' given in "+this.encodingName+" at chunk "+$[0])}if(Y>255)throw Error("Incorrect chunk in "+this.encoLine truncated
`;super(Y);this.name="AggregateError",this.errors=$}}ME0.exports={AggregateError:wE0,ArrayIsArray($){return Array.isArray($)},ArrayPrototypeIncludes($,Y){return $.includes(Y)},ArrayPrototypeIndexOf($,Y){return $.indexOf(Y)},ArrayPrototypeJoin($,Y){return $.join(Y)},ArrayPrototypeMap($,Y){return $.map(Y)},ArrayPrototypePop($,Y){return $.pop(Y)},ArrayPrototypePush($,Y){return $.push(Y)},ArrayPrototypeSlice($,Y,U){return $.slice(Y,U)},Error,FunctionPrototypeCall($,Y,...U){return $.call(Y,...U)},FunctionPrototypeSymbolHasInstance($,Y){return Function.prototype[Symbol.hasInstance].call($,Y)},MathFloor:Math.floor,Number,NumberIsInteger:Number.isInteger,NumberIsNaN:Number.isNaN,NumberMAX_SAFE_INTEGER:Number.MAX_SAFE_INTEGER,NumberMIN_SAFE_INTEGER:Number.MIN_SAFE_INTEGER,NumberParseInt:Number.parseInt,ObjectDefineProperties($,Y){return Object.defineProperties($,Y)},ObjectDefineProperty($,Y,U){return Object.defineProperty($,Y,U)},ObjectGetOwnPropertyDescriptor($,Y){return Object.getOwnPropertyDescriptor($,Y)},ObjectKeys($){return Object.keys($)},ObjectSetPrototypeOf($,Y){return Object.setPrototypeOf($,Y)},Promise,PromisePrototypeCatch($,Y){return $.catch(Y)},PromisePrototypeThen($,Y,U){return $.then(Y,U)},PromiseReject($){return Promise.reject($)},PromiseResolve($){return Promise.resolve($)},ReflectApply:Reflect.apply,RegExpPrototypeTest($,Y){return $.test(Y)},SafeSet:Set,String,StringPrototypeSlice($,Y,U){return $.slice(Y,U)},StringPrototypeToLowerCase($){return $.toLowerCase()},StringPrototypeToUpperCase($){return $.toUpperCase()},StringPrototypeTrim($){return $.trim()},Symbol,SymbolFor:Symbol.for,SymbolAsyncIterator:Symbol.asyncIterator,SymbolHasInstance:Symbol.hasInstance,SymbolIterator:Symbol.iterator,SymbolDispose:Symbol.dispose||Symbol("Symbol.dispose"),SymbolAsyncDispose:Symbol.asyncDispose||Symbol("Symbol.asyncDispose"),TypedArrayPrototypeSet($,Y,U){return $.set(Y,U)},Boolean,Uint8Array}});var Nm=j((j94,OE0)=>{OE0.exports={format($,...Y){return $.replace(/%([sdifj])/g,function(...[U,I]){let Q=Y.shift();if(I==="f")return Q.toFixed(6);else if(I==="j")return JSON.stringify(Q);else if(I==="s"&&typeof Q==="object")return`${Q.constructor!==Object?Q.constructor.name:""} {}`.trim();else return Q.toString()})},inspect($){switch(typeof $){case"string":if($.includes("'")){if(!$.includes('"'))return`"${$}"`;else if(!$.includes("`")&&!$.includes("${"))return`\`${$}\``}return`'${$}'`;case"number":if(isNaN($))return"NaN";else if(Object.is($,-0))return String($);return $;case"bigint":return`${String($)}n`;case"boolean":case"undefined":return String($);case"object":return"{}"}}}});var P8=j((C94,AE0)=>{var{format:Sj1,inspect:dP}=Nm(),{AggregateError:hj1}=b4(),gj1=globalThis.AggregateError||hj1,yj1=Symbol("kIsNodeError"),kj1=["string","function","number","object","Function","Object","boolean","bigint","symbol"],xj1=/^([A-Z][a-z0-9]*)+$/,pP={};function DI($,Y){if(!$)throw new pP.ERR_INTERNAL_ASSERTION(Y)}function NE0($){let Y="",U=$.length,I=$[0]==="-"?1:0;for(;U>=I+4;U-=3)Y=`_${$.slice(U-3,U)}${Y}`;return`${$.slice(0,U)}${Y}`}function fj1($,Y,U){if(typeof Y==="function")return DI(Y.length<=U.length,`Code: ${$}; The provided arguments length (${U.length}) does not match the required ones (${Y.length}).`),Y(...U);let I=(Y.match(/%[dfijoOs]/g)||[]).length;if(DI(I===U.length,`Code: ${$}; The provided arguments length (${U.length}) does not match the required ones (${I}).`),U.length===0)return Y;return Sj1(Y,...U)}function G8($,Y,U){if(!U)U=Error;class I extends U{constructor(...Q){super(fj1($,Y,Q))}toString(){return`${this.name} [${$}]: ${this.message}`}}Object.defineProperties(I.prototype,{name:{value:U.name,writable:!0,enumerable:!1,configurable:!0},toString:{value(){return`${this.name} [${$}]: ${this.message}`},writable:!0,enumerable:!1,configurable:!0}}),I.prototype.code=$,I.prototype[yj1]=!0,pP[$]=I}function DE0($){let Y="__node_internal_"+$.name;return Object.defineProperty($,"name",{value:Y}),$}function uj1($,Y){if($&&Y&&$!==Y){if(Array.isArray(Y.errors))return Y.errors.push($),Y;let U=new gj1([Y,$],Y.message);return U.code=Y.code,U}return $||Y}class BE0 extends Error{constructor($="The operation was aborted",Y=void 0){if(Y!==void 0&&typeof Y!=="object")throw new pP.ERR_INVALID_ARG_TYPE("options","Object",Y);super($,Y);this.code="ABORT_ERR",this.name="AbortError"}}G8("ERR_ASSERTION","%s",Error);G8("ERR_INVALID_ARG_TYPE",($,Y,U)=>{if(DI(typeof $==="string","'name' must be a string"),!Array.isArray(Y))Y=[Y];let I="The ";if($.endsWith(" argument"))I+=`${$} `;else I+=`"${$}" ${$.includes(".")?"property":"argument"} `;I+="must be ";let Q=[],J=[],K=[];for(let G of Y)if(DI(typeof G==="string","All expected entries have to be of type string"),kj1.includes(G))Q.push(G.toLowerCase());else if(xj1.test(G))J.push(G);else DI(G!=="object",'The value "object" should be written as "Object"'),K.push(G);if(J.length>0){let G=Q.indexOf("object");if(G!==-1)Q.splice(Q,G,1),J.push("Object")}if(Q.length>0){switch(Q.length){case 1:I+=`of type ${Q[Line truncated
`);if(Y.linkname)U+=sl(" linkpath="+Y.linkname+`
`);let I=Y.pax;if(I)for(let Q in I)U+=sl(" "+Q+"="+I[Q]+`
`);return d1.from(U)};kg1.decodePax=function(Y){let U={};while(Y.length){let I=0;while(I<Y.length&&Y[I]!==32)I++;let Q=parseInt(d1.toString(Y.subarray(0,I)),10);if(!Q)return U;let J=d1.toString(Y.subarray(I+1,Q-1)),K=J.indexOf("=");if(K===-1)return U;U[J.slice(0,K)]=J.slice(K+1),Y=Y.subarray(Q)}return U};kg1.encode=function(Y){let U=d1.alloc(512),I=Y.name,Q="";if(Y.typeflag===5&&I[I.length-1]!=="/")I+="/";if(d1.byteLength(I)!==I.length)return null;while(d1.byteLength(I)>100){let J=I.indexOf("/");if(J===-1)return null;Q+=Q?"/"+I.slice(0,J):I.slice(0,J),I=I.slice(J+1)}if(d1.byteLength(I)>100||d1.byteLength(Q)>155)return null;if(Y.linkname&&d1.byteLength(Y.linkname)>100)return null;if(d1.write(U,I),d1.write(U,t2(Y.mode&4095,6),100),d1.write(U,t2(Y.uid,6),108),d1.write(U,t2(Y.gid,6),116),gg1(Y.size,U,124),d1.write(U,t2(Y.mtime.getTime()/1000|0,11),136),U[156]=48+Sg1(Y.type),Y.linkname)d1.write(U,Y.linkname,157);if(d1.copy(l_0,U,257),d1.copy(Tg1,U,263),Y.uname)d1.write(U,Y.uname,265);if(Y.gname)d1.write(U,Y.gname,297);if(d1.write(U,t2(Y.devmajor||0,6),329),d1.write(U,t2(Y.devminor||0,6),337),Q)d1.write(U,Q,345);return d1.write(U,t2(r_0(U),6),148),U};kg1.decode=function(Y,U,I){let Q=Y[156]===0?0:Y[156]-48,J=fz(Y,0,100,U),K=a2(Y,100,8),z=a2(Y,108,8),G=a2(Y,116,8),H=a2(Y,124,12),W=a2(Y,136,12),X=vg1(Q),Z=Y[157]===0?null:fz(Y,157,100,U),q=fz(Y,265,32),V=fz(Y,297,32),w=a2(Y,329,8),M=a2(Y,337,8),F=r_0(Y);if(F===256)return null;if(F!==a2(Y,148,8))throw Error("Invalid tar header. Maybe the tar is corrupted or it needs to be gunzipped?");if(Cg1(Y)){if(Y[345])J=fz(Y,345,155,U)+"/"+J}else if(Rg1(Y));else if(!I)throw Error("Invalid tar header: unknown format.");if(Q===0&&J&&J[J.length-1]==="/")Q=5;return{name:J,mode:K,uid:z,gid:G,size:H,byteOffset:0,mtime:new Date(1000*W),type:X,linkname:Z,uname:q,gname:V,devmajor:w,devminor:M,pax:null}};function Cg1($){return d1.equals(l_0,$.subarray(257,263))}function Rg1($){return d1.equals(Eg1,$.subarray(257,263))&&d1.equals(jg1,$.subarray(263,265))}function _g1($,Y,U){if(typeof $!=="number")return U;if($=~~$,$>=Y)return Y;if($>=0)return $;if($+=Y,$>=0)return $;return 0}function vg1($){switch($){case 0:return"file";case 1:return"link";case 2:return"symlink";case 3:return"character-device";case 4:return"block-device";case 5:return"directory";case 6:return"fifo";case 7:return"contiguous-file";case 72:return"pax-header";case 55:return"pax-global-header";case 27:return"gnu-long-link-path";case 28:case 30:return"gnu-long-path"}return null}function Sg1($){switch($){case"file":return 0;case"link":return 1;case"symlink":return 2;case"character-device":return 3;case"block-device":return 4;case"directory":return 5;case"fifo":return 6;case"contiguous-file":return 7;case"pax-header":return 72}return 0}function o_0($,Y,U,I){for(;U<I;U++)if($[U]===Y)return U;return I}function r_0($){let Y=256;for(let U=0;U<148;U++)Y+=$[U];for(let U=156;U<512;U++)Y+=$[U];return Y}function t2($,Y){if($=$.toString(8),$.length>Y)return"7777777777777777777".slice(0,Y)+" ";return"0000000000000000000".slice(0,Y-$.length)+$+" "}function hg1($,Y,U){Y[U]=128;for(let I=11;I>0;I--)Y[U+I]=$&255,$=Math.floor($/256)}function gg1($,Y,U){if($.toString(8).length>11)hg1($,Y,U);else d1.write(Y,t2($,11),U)}function yg1($){let Y;if($[0]===128)Y=!0;else if($[0]===255)Y=!1;else return null;let U=[],I;for(I=$.length-1;I>0;I--){let K=$[I];if(Y)U.push(K);else U.push(255-K)}let Q=0,J=U.length;for(I=0;I<J;I++)Q+=U[I]*Math.pow(256,I);return Y?Q:-1*Q}function a2($,Y,U){if($=$.subarray(Y,Y+U),Y=0,$[Y]&128)return yg1($);else{while(Y<$.length&&$[Y]===32)Y++;let I=_g1(o_0($,32,Y,$.length),$.length,$.length);while(Y<I&&$[Y]===0)Y++;if(I===Y)return 0;return parseInt(d1.toString($.subarray(Y,I)),8)}}function fz($,Y,U,I){return d1.toString($.subarray(Y,o_0($,0,Y,Y+U)),I)}function sl($){let Y=d1.byteLength($),U=Math.floor(Math.log(Y)/Math.log(10))+1;if(Y+U>=Math.pow(10,U))U++;return Y+U+$}});var Iv0=j((M74,Uv0)=>{var{Writable:cg1,Readable:ng1,getStreamError:s_0}=rl(),dg1=il(),a_0=xz(),uz=al(),pg1=a_0.alloc(0);class t_0{constructor(){this.buffered=0,this.shifted=0,this.queue=new dg1,this._offset=0}push($){this.buffered+=$.byteLength,this.queue.push($)}shiftFirst($){return this.buffered===0?null:this._next($)}shift($){if($>this.buffered)return null;if($===0)return pg1;let Y=this._next($);if($===Y.byteLength)return Y;let U=[Y];while(($-=Y.byteLength)>0)Y=this._next($),U.push(Y);return a_0.concat(U)}_next($){let Y=this.queue.peek(),U=Y.byteLength-this._offset;if($>=U){let I=this._offset?Y.subarray(this._offset,Y.byteLength):Y;return this.queue.shift(),this._offset=0,this.buffered-=U,this.shifted+=U,I}return this.buffered-=$,this.shifted+=$,Y.subarray(this._offset,this._offset+=$)}}class e_0 extends ng1{constructor($,Y,U){super();this.header=Y,this.offset=U,this._parent=$}_read($){if(this.header.size===0)this.push(null);if(this._parent._stream===this)this._parent._update();$(null)}_predestroy(){this._parent.destroy(s_0(this))}_detach(){if(this._parent._stream= Line truncated
`),I=[await G4($,U.recordId)];else if(U.recordIds&&U.recordIds.length>0)process.stderr.write(`\uD83D\uDD0D 批量查询 ${U.recordIds.length} 条单据记录...
`),I=await Promise.all(U.recordIds.map((F)=>G4($,F)));else{let F=U.limit??10;process.stderr.write(`\uD83D\uDD0D 检索企业「${Y.name}」(${Y.id}) 的线上审核记录 (限制 ${F} 条)...
`);let O=(await x4($,{limit:F,status:U.status,startDate:U.startDate!==void 0?String(U.startDate):void 0,endDate:U.endDate!==void 0?String(U.endDate):void 0})).records??[];if(O.length===0)throw Error("未检索到符合条件的线上审核记录,无法导出 webhook 资源包。");process.stderr.write(`\uD83D\uDCE5 正在拉取 ${O.length} 条审核记录完整详情...
`),I=await Promise.all(O.map((D)=>G4($,D.id)))}let Q=new Map,J=0;for(let F of I){let N=F.document,O=F.sourceDocumentId??(typeof N?.id==="string"?N.id:void 0)??(typeof N?.sourceDocumentId==="string"?N.sourceDocumentId:void 0)??F.documentId??F.id,D=`${U.docIdPrefix??""}${O}${U.docIdSuffix??""}`,P=[];if(U.includeAttachments!==!1){let B=b3(F,{summary:!1}).attachments,E=new Set;for(let C of B){let b=C.ossSignedUrl??C.url;if(!b)continue;let x=C.fileName??C.fileId??"attachment",g=Ed(x),i=g,c=g.lastIndexOf("."),I0=c>0?g.slice(0,c):g,k=c>0?g.slice(c):"",p=1;while(E.has(i.toLowerCase()))i=`${I0}_${p}${k}`,p++;E.add(i.toLowerCase());try{process.stderr.write(`⬇ 下载单据「${D}」附件: ${x}...
`);let a=await fetch(b);if(a.ok){let $0=await a.arrayBuffer(),y=Buffer.from($0);P.push({fileName:i,zipPath:`${D}/${i}`,buffer:y,sourceField:C.sourceField??"附件"}),J++}}catch(a){process.stderr.write(`⚠️ [跳过附件] 下载失败 ${x}: ${a}
`)}}}Q.set(D,P)}let K=new Dv0.default.Workbook;K.creator="seal-use",K.created=new Date;let z=new Set;for(let F of Q.values())for(let N of F)z.add(N.sourceField);if(z.size===0)z.add("附件");let G=new Set;for(let F of I){let N=F.document,O=Array.isArray(N?.fields)?N.fields:[];for(let D of O)if(D&&typeof D==="object"){let P=D,T=typeof P.label==="string"?P.label.trim():typeof P.key==="string"?P.key.trim():"",B=typeof P.type==="string"?P.type.toUpperCase():"";if(T&&B!=="ATTACHMENT"&&B!=="LIST")G.add(T)}}let H=["会议编号","会议名称","状态","总金额","报销事由","申请日期"],W=Array.from(G).filter((F)=>!H.includes(F)&&F!=="单据编号"&&F!=="单号"),X=Array.from(z).map((F)=>`[附件]${F}`),Z=[...H,...W,...X],q=K.addWorksheet("主表");q.addRow(Z),q.getRow(1).font={bold:!0};for(let F of I){let N=F.document,O=F.sourceDocumentSN??(typeof N?.sn==="string"?N.sn:void 0)??(typeof N?.sourceDocumentSN==="string"?N.sourceDocumentSN:void 0)??F.id,D=F.sourceDocumentId??(typeof N?.id==="string"?N.id:void 0)??(typeof N?.sourceDocumentId==="string"?N.sourceDocumentId:void 0)??F.documentId??F.id,P=`${U.docIdPrefix??""}${D}${U.docIdSuffix??""}`,T=`${U.docIdPrefix??""}${O}${U.docIdSuffix??""}`,B=(typeof N?.title==="string"?N.title:void 0)??(typeof N?.name==="string"?N.name:void 0)??T,E="";if(typeof N?.sourceStartTime==="number")E=new Date(N.sourceStartTime*1000).toLocaleDateString("en-CA",{timeZone:"Asia/Shanghai"});else if(typeof F.createdAt==="number")E=new Date(F.createdAt).toLocaleDateString("en-CA",{timeZone:"Asia/Shanghai"});else if(typeof F.createdAt==="string")E=F.createdAt.slice(0,10);let C=new Map,b=Array.isArray(N?.fields)?N.fields:[];for(let I0 of b)if(I0&&typeof I0==="object"){let k=I0,p=typeof k.label==="string"?k.label.trim():typeof k.key==="string"?k.key.trim():"";if(p)C.set(p,k.value)}let x,g=C.get("总金额")??C.get("报销金额")??C.get("total_amount");if(typeof g==="number")x=g;else if(g&&typeof g==="object"&&"amount"in g&&typeof g.amount==="number")x=g.amount;let i=[];i.push(P),i.push(B),i.push(F.status??"已审批"),i.push(x??""),i.push(C.get("报销事由")??C.get("事由")??B),i.push(E);for(let I0 of W){let k=C.get(I0);if(k===void 0||k===null)i.push("");else if(typeof k==="object")if("amount"in k)i.push(k.amount);else i.push(JSON.stringify(k));else i.push(k)}let c=Q.get(P)??[];for(let I0 of z){let k=c.filter((p)=>p.sourceField===I0||z.size===1);if(k.length>0)i.push(k.map((p)=>p.zipPath).join(`
`));else i.push("")}q.addRow(i)}let V=Wy1(U,Y);Jy1(Gy1(V),{recursive:!0});let w=await K.xlsx.writeBuffer();process.stderr.write(`\uD83D\uDCE6 正在压缩生成 Webhook 资源包: ${V}...
`),await new Promise((F,N)=>{let O=Qy1(V),D=new Uo({zlib:{level:9}});O.on("close",()=>F()),D.on("error",(P)=>N(P)),D.pipe(O),D.append(Buffer.from(w),{name:"信息表.xlsx"});for(let P of Q.values())for(let T of P)D.append(T.buffer,{name:T.zipPath});D.finalize()});let M=Ky1(V);return{filePath:V,corpId:Y.id,corpName:Y.name,recordCount:I.length,attachmentCount:J,fileSizeBytes:M.size,exportedAt:new Date().toISOString(),nextAction:`seal-use webhook resource-pack push ${V} --corp <targetCorpId>`}}var Dv0;var Io=m(()=>{Ov0();H4();yZ();Dv0=K6(hZ(),1)});import{readFileSync as Xy1}from"node:fs";function Zy1($){let Y=new URL($),U=Y.pathname.match(/\/webhook\/([^/]+)/);if(!U)throw Error("Webhook URL 必须包含 /webhook/{webhookId}/document");return{baseUrl:`${Y.protocol}//${Y.host}`,webhookId:U[1]}}function qy1($,Y){return Y.toLowerCase().endsWith(".zip")||$[0]===80&&$[1]===75&&!Y.toLowerCase().endsWith(".xlsx")}function Vy1($,Y){if(!$.length)return;let U=new Set($.map((J)=>{let K=J.fileName.split("/")[0],z=K.indexOf("@");return z>=0?K.slice(0,z):K}).filter((J)=>J!=="信息表.xlsx")),I=[];for(let J of Y){let K=J.document.documentId;if((J.documentAttachments.length>0||Object.values(J.expenseAttachments).some((G)=>G.length>0)||Object.values(J.personAttachments).some((G)=>G.length>0))&&!U.has(K))I.push(`Excel 会议编号「${K}」声明了附件,但在 ZIP 中找不到对应的根目录「${K}/」或「${K}@.../」。`)}let Q=new Set(Y.map((J)=>J.document.documentId));for(let J of U)if(!Q.has(J))I.push(`ZIP 根目录对应的编号「${J}」在信息表中找不到对应的会议编号。`);if(I.length)throw new R5(I)}async function Bv0($,Y,U){let I=[],Q=$;if(qy1($,Y)){I=await ST0($),gT0(I,U);let G=I.find((H)=>H.fileName==="信息表.xlsx");if(!G)throw Error("ZIP 根目录缺少信息表.xlsx");Q=await Im($,G)}let J=await iT0(Q);Vy1(I,J);let K=cT0(I,J),z=J.map((G)=>G.document);return{entries:I,parsed:J,plans:K,documents:z,fileBuffer:$}}async function uI($,Y,U){let I=await Bv0($,Y,U),Q=I.parsed.map((J,K)=>Hm(J.document,I.plans[K],new Map));return{warnings:[],documents:Q,attachmentPlan:I.plans}}async function gT($,Y,U){let I=await Bv0($,Y,U.materialPackFilePolicy),{baseUrl:Q,webhookId:J}=Zy1(U.webhookUrl),K=[];for(let z=0;z<I.parsed.length;z+=1){let G=I.parsed[z],H=I.plans[z],W=new Map,X=[...H.categoryFields,...Object.values(H.personAttachments).flat(),...Object.values(H.expenseAttachments).flat()];for(let V of X)for(let w of V.paths){if(W.has(w))continue;let M=I.entries.find((T)=>T.fileName===w);if(!M)continue;process.stderr.write(`⬆ 上传附件: ${w}
`);let F=new FormData,N=await Im(I.fileBuffer,M),O=w.split("/").pop()??w;F.append("files",new File([new Uint8Array(N)],O));let D=await fetch(`${Q}/api/v1/integrations/webhook/${encodeURIComponent(J)}/attachments`,{method:"POST",headers:{...U.customHeaders??{},...oZ({},U.secret)},body:F});if(!D.ok)throw Error(`附件上传失败 ${D.status}: ${await D.text()}`);let P=await D.json();W.set(w,P.attachments?.map((T)=>T.data)??(P.data===void 0?[]:[P.data])),process.stderr.write(`✓ 附件上传成功: ${w}
`)}process.stderr.write(`\uD83D\uDCE4 推送单据: ${G.document.documentId}
`);let Z=id(G.document,H,W),q=await fetch(`${I}/api/v1/integrations/webhook/${encodeURIComponent(Q)}/document`,{method:"POST",headers:{...U.customHeaders??{},"Content-Type":"application/json",...uZ({webhookId:Q,...Z},U.secret)},body:JSON.stringify(Z)});if(!q.ok)throw Error(`Webhook 单据推送失败 ${q.status}: ${await q.text()}`);J.push({documentId:Z.documentId,document:Z,pushResult:await q.json()}),process.stderr.write(`✓ 单据推送成功: ${Z.documentId}
`)}return{warnings:[],results:J}}function xz($){return{fileBuffer:fS1($),fileName:$.split(/[\\\/]/).pop()??"material-pack.zip"}}var kl=m(()=>{QP();cd();bd();kd();QK();yl()});import{existsSync as cS1}from"node:fs";async function NT($,Y,U={}){let I=v4().stateful?"stateful":"stateless",Q="ok",J,K,G;try{let D=await Z8($);G={id:D.user.id,name:D.user.name,isAdmin:D.user.isAdmin},K={id:D.tenant.id,name:D.tenant.name,tenantSlug:D.tenant.tenantSlug,corporationName:D.tenant.hoseCorpConfig?.corporationName}}catch(D){Q="error",J=D instanceof Error?D.message:String(D)}let H=[];if(Q==="ok")try{H=await K$($,Y.seal.endpoints.approvalStylePreferences)}catch(D){Q="error",J=`读取 Webhook 配置失败: ${D instanceof Error?D.message:String(D)}`}let W=H.length===1,X=H.map((D)=>({id:D.id,name:D.name,mode:D.mode,incomingDocumentWebhookUrl:D.incomingDocumentWebhook.url,outgoingResultWebhookUrl:D.outgoingResultWebhook,autoApprovalRate:D.autoApprovalRate,...W?{isDefault:!0}:{}})),Z=W?{id:H[0].id,name:H[0].name,mode:H[0].mode}:null,q=U.webhook?x7(H,U.webhook):W?H[0]:void 0,V;if(U.filePath)if(!cS1(U.filePath))V={valid:!1,filePath:U.filePath,fileName:U.filePath.split(/[\\/]/).pop()??U.filePath,documentCount:0,errors:[`文件不存在: ${U.filePath}`]};else try{let D=xz(U.filePath),P=await kz(D.fileBuffer,D.fileName,q?.materialPackFilePolicy);V={valid:!0,filePath:U.filePath,fileName:D.fileName,documentCount:P.documents.length,warnings:P.warnings}}catch(D){V={valid:!1,filePath:U.filePath,fileName:U.filePath.split(/[\\/]/).pop()??U.filePath,documentCount:0,errors:[D instanceof Error?D.message:String(D)]}}let w=V?V.valid:!0,M=Q==="ok"&&X.length>0&&w,F=I==="stateful"?"":` --corp ${Y.id}`,N="",O="";if(Q!=="ok")O=`凭证鉴权异常: ${J}`,N=`seal-use auth diagnose${F}`;else if(X.length===0)O="当前企业尚未配置任何 Webhook 集成通道",N=`seal-use webhook add --name "默认入站通道" --result-url "https://your-domain.com/callback"${F}`;else if(V&&!V.valid)O=`资源包预检失败: ${V.errors?.join("; ")}`,N=`seal-use webhook resource-pack preview ${V.filePath}${F}`;else{O=W?"所有通道正常,已自动锁定唯一 Webhook 通道,等待载入":`所有通道正常,检测到 ${X.length} 个 Webhook 通道,等待载入`;let D=V?.filePath??"<资源包.zip>",P=W?"":` --webhook ${Z?Z.id:"<webhookIdOrName>"}`;N=`seal-use webhook resource-pack push ${D}${P}${F}`}return{ready:M,corp:{id:Y.id,name:Y.name,sourceType:Y.source.type,tenant:K,user:G},stateMode:I,authStatus:Q,authError:J,activeWebhooks:X,defaultWebhook:Z,resourcePack:V,materialPack:V,statusMessage:O,nextAction:N}}var __0=m(()=>{T5();X6();kl()});var xl=m(()=>{QK();aI();QP();kd();bd();cd();kl();__0();yl()});import{existsSync as v_0,mkdirSync as h_0,statSync as nS1}from"node:fs";import{homedir as pS1}from"node:os";import{dirname as dS1,resolve as DT}from"node:path";function mS1($){if($.outputFile){let J=DT($.outputFile),K=dS1(J);if(!v_0(K))h_0(K,{recursive:!0});return J}let U=($.corpName||$.corpId||"企业").replace(/[/\\?%*:|"<>]/g,"_").trim()||"企业",z=$.dateTag||new Date().toISOString().slice(0,10),I=`${U}_智能洞察报告_${z}.xlsx`,Q;if($.toDownloads)Q=DT(pS1(),"Downloads");else Q=DT(process.cwd(),"exports");if(!v_0(Q))h_0(Q,{recursive:!0});return DT(Q,I)}async function AT($,Y,U={}){let z=Y.name||Y.id,I=Mp({startDate:U.startDate,endDate:U.endDate,force:U.force}),Q=new Date().toISOString(),[J,K]=await Promise.all([yM($,{startDate:I.startDateStr,endDate:I.endDateStr,limit:U.limit??100}),xM($,{startDate:I.startDateStr,endDate:I.endDateStr}).catch(()=>({metrics:{},sankeyData:{nodes:[],links:[]}}))]),G=J.tagStats||[],H=[],W=Math.min(G.length,U.limit??50);for(let C=0;C<W;C++){let b=G[C];if(!b?.tagId)continue;try{let x=await kM($,{tagId:b.tagId,startDate:I.startDateStr,endDate:I.endDateStr});for(let g of x.risks||[])H.push({tagId:b.tagId,tagName:b.tagName||b.tagId,documentSN:g.documentSN||"-",documentType:g.documentType||"-",riskLevel:g.riskLevel||"warning",confidence:g.confidence??0,riskDetails:g.riskDetails||"-",reasoning:g.reasoning||"-",sourceDocumentURL:g.sourceDocumentURL,createdAt:g.createdAt})}catch{}}let X=new S_0.default.Workbook;X.creator="seal-use",X.lastModifiedBy="seal-use",X.created=new Date,X.modified=new Date;let Z={type:"pattern",pattern:"solid",fgColor:{argb:"FF1E293B"}},q={name:"Microsoft YaHei",size:11,bold:!0,color:{argb:"FFFFFFFF"}},V={top:{style:"thin",color:{argb:"FFE2E8F0"}},bottom:{style:"thin",color:{argb:"FFE2E8F0"}},left:{style:"thin",color:{argb:"FFE2E8F0"}},right:{style:"thin",color:{argb:"FFE2E8F0"}}},w=X.addWorksheet("审核效能与决策流向",{views:[{showGridLines:!0}]});w.columns=[{header:"分类",key:"category",width:20},{header:"指标名称",key:"name",width:28},{header:"数值",key:"val",width:22},{header:"环比/趋势",key:"trend",width:18},{header:"说明",key:"desc",width:36}],w.getRow(1).height=28,w.getRow(1).font=q,w.getRow(1).fill=Z,w.getRow(1).alignment={vertical:"middle",horizontal:"center"};let M=K.metrics||{},F=[{c Line truncated
`);return{recordId:$.id,sourceDocumentSN:$.sourceDocumentSN,sourceDocumentId:$.sourceDocumentId,document:xK({id:Y?.id,sn:Y?.sn??Y?.sourceDocumentSN??$.sourceDocumentSN,title:Y?.title??Y?.name,template:CT(Y,["template.name","templateName","form.name","formName","formTitle"]),amount:PT(U,["金额","报销金额","付款金额","合计","价税合计"])??CT(Y,["amount","totalAmount","expenseAmount"]),expenseType:PT(U,["费用类型","费用类别","报销类型"]),costCompany:PT(U,["费用承担公司","承担公司","成本中心","费用归属"]),payee:PT(U,["收款方","收款账户","收款信息","开户名","银行账号"]),keyFields:U.slice(0,30)}),invoices:Wg1($),attachments:c2($,{summary:!0}).attachments,aiResult:_T($),manualResult:uz($)?.value,hints:xK({amountMentions:x_0(z,["金额","合计","税率"],8),partyMentions:x_0(z,["买方","卖方","甲方","乙方","收款"],8)})}}function Jg1($){let Y=[["result.citedRules",l3($,"result.citedRules")],["result.matchedRules",l3($,"result.matchedRules")],["result.ruleResults",l3($,"result.ruleResults")],["result.rules",l3($,"result.rules")],["pipelineData.citedRules",l3($,"pipelineData.citedRules")],["pipelineData.matchedRules",l3($,"pipelineData.matchedRules")]],U=[],z=new Set;for(let[I,Q]of Y)(Array.isArray(Q)?Q:Q&&typeof Q==="object"?Object.values(Q):[]).forEach((K,G)=>{let H=Tq(K);if(!H)return;let W=M4(H.runtimeRuleId)??M4(H.runtimeId)??M4(H.id)??M4(H.ruleId),X=M4(H.ruleCode)??M4(H.code)??(W?qg1(W):void 0),Z=xK({runtimeRuleId:W,ruleCode:X,versionNumber:Gg1(H.versionNumber)??$.ruleSetVersionNumber,scope:M4(H.scope),strictness:M4(H.strictness),appliedAnalysis:H.appliedAnalysis??H.analysis??H.reasoning,checkResult:H.checkResult??H.result??H.decision,findings:H.findings??H.riskPoints??H.evidence,sourcePath:`${I}.${G}`}),q=JSON.stringify(Z);if(!z.has(q))z.add(q),U.push(Z)});return{recordId:$.id,sourceDocumentSN:$.sourceDocumentSN,sourceDocumentId:$.sourceDocumentId,ruleSetVersionNumber:$.ruleSetVersionNumber,count:U.length,rules:U}}function CT($,Y){if(!$)return;for(let U of Y){let z=l3($,U);if(z!==void 0)return z}return}function k_0($,Y){if(!$)return 0;for(let U of Y){let z=l3($,U);if(Array.isArray(z))return z.length;if(z&&typeof z==="object")return Object.keys(z).length;if(typeof z==="number")return z}return 0}function l3($,Y){return Y.split(".").reduce((U,z)=>{if(U===void 0||U===null)return;if(Array.isArray(U)){let I=Number(z);return Number.isInteger(I)?U[I]:void 0}if(typeof U==="object")return U[z];return},$)}function Kg1($,Y,U){let z=Y.split("."),I=$;for(let Q of z.slice(0,-1)){let J=I[Q];if(!J||typeof J!=="object"||Array.isArray(J))I[Q]={};I=I[Q]}I[z[z.length-1]??Y]=U}function xK($){return Object.fromEntries(Object.entries($).filter(([,Y])=>Y!==void 0))}function Tq($){return $&&typeof $==="object"&&!Array.isArray($)?$:void 0}function Gg1($){return typeof $==="number"&&Number.isFinite($)?$:void 0}function Hg1($){let Y=[];return bl($,"document",Y),Y}function bl($,Y,U){if(Array.isArray($)){$.forEach((J,K)=>bl(J,`${Y}.${K}`,U));return}let z=Tq($);if(!z)return;let I=M4(z.label)??M4(z.name)??M4(z.title)??M4(z.fieldName),Q=z.value??z.displayValue??z.text??z.content;if(I&&Q!==void 0&&typeof Q!=="object")U.push(xK({path:Y,label:I,value:Q,type:M4(z.type)??M4(z.fieldType)}));for(let[J,K]of Object.entries(z)){if(J==="attachments")continue;bl(K,`${Y}.${J}`,U)}}function PT($,Y){return $.find((z)=>{let I=M4(z.label)??"";return Y.some((Q)=>I.includes(Q))})?.value}function Wg1($){let Y=[];return RT($.result,"result",Y),RT($.document,"document",Y),Y.slice(0,20)}function RT($,Y,U){if(Array.isArray($)){$.forEach((I,Q)=>RT(I,`${Y}.${Q}`,U));return}let z=Tq($);if(!z)return;if(/invoice|发票/i.test(Y))U.push(xK({path:Y,fileName:M4(z.fileName)??M4(z.filename)??M4(z.name),buyer:z.buyer??z.buyerName??z.purchaserName,seller:z.seller??z.sellerName,amount:z.amount??z.totalAmount??z.total,taxRate:z.taxRate,category:z.category??z.type}));for(let[I,Q]of Object.entries(z))RT(Q,`${Y}.${I}`,U)}function x_0($,Y,U){return $.split(/\r?\n/).filter((z)=>Y.some((I)=>z.includes(I))).slice(0,U)}function TT($){return $.map((Y)=>{let U=fz(Y);return{recordId:U.id,tenantId:U.tenantId,agentId:U.agentId,sourceDocumentSN:U.sourceDocumentSN,sourceDocumentId:U.sourceDocumentId,simulationBatchId:U.simulationBatchId,langfuseTraceId:U.langfuseTraceId,langfuseSessionFallback:U.langfuseSessionFallback,ruleSetVersionNumber:U.ruleSetVersionNumber,ruleSetPublishedAt:U.ruleSetPublishedAt,ruleSetPublishedByName:U.ruleSetPublishedByName,resolution:U.langfuseTraceId?"trace":U.langfuseSessionFallback?"session-fallback":"unresolved"}})}function ul($){return{id:$.id,tenantId:$.tenantId,versionNumber:$.versionNumber,versionName:$.versionName,publishedBy:$.publishedBy,publishedByName:$.publishedByName,rulesCount:$.rules.length,publishedAt:$.publishedAt,createdAt:$.createdAt}}async function Xg1($,Y){if(Y.recordId&&!Y.versionId&&!Y.versionNumber&&!Y.latest){let U=await H4($,Y.recordId);if(!U.ruleSetVersionNumber)throw Er Line truncated
`)},{...Rp(Q,20000,Y.full===!0),format:Y.format??"unified"}}},{name:"seal_approval_rule_version_publish",description:"发布 Seal 草稿审批规则为新版本",parameters:L.object({versionName:L.string().describe("版本名称")}),handler:async($,Y,U)=>{let z=await W6($).catch(()=>{return}),I=await xH($,Y.versionName);if(z)try{fZ(U.corp.id,I.version,z.rules)}catch{}return I}},{name:"seal_approval_rule_get",description:"按版本号/code/runtime-id/record-id 定位单条规则;code 只在选定的版本编号体系内有效,避免拉取整版规则快照",parameters:L.object({versionId:L.string().optional().describe("规则版本 ID"),versionNumber:L.number().int().positive().optional().describe("规则版本号"),latest:L.boolean().optional().describe("为 true 时取最新版本"),code:L.string().optional().describe("规则展示编号,如 #0038;没有后端 code 时按版本内序号匹配"),runtimeId:L.string().optional().describe("运行时规则 ID,如 rule-205;按版本内序号匹配"),recordId:L.string().optional().describe("从运行记录推断 ruleSetVersionNumber")}),handler:async($,Y)=>{let U=await Xg1($,Y),z=Zg1(U,{code:Y.code,runtimeId:Y.runtimeId});if(!z)throw Error(`Rule not found in version ${U.versionNumber}`);return z}},{name:"seal_approval_rules_lint",description:"对 Seal 本地规则文件、草稿审批规则或指定发布版本规则进行质量与可执行性检查(模糊词、悬空例外检测)",parameters:L.object({file:L.string().optional().describe("指定本地规则文件路径进行离线质检(支持 .json),0网络请求、不污染远端草稿"),linter:L.string().optional().describe("指定使用的校验器名称或脚本路径(如 builtin、strict、./my-linter.ts)"),version:L.string().optional().describe("指定要质检的历史发布版本号或 ID(如 16 或 latest),不传默认质检当前草稿"),code:L.string().optional().describe("按规则展示编号过滤(如 #0038)"),ruleId:L.string().optional().describe("按规则 ID 过滤"),minScore:L.number().optional().describe("最低合格质量分阈值(0~100),低于该分值抛出错误以返回非零退出码"),level:L.enum(["all","error","warning"]).default("all").describe("问题报告等级过滤"),summary:L.boolean().optional().describe("为 true 时仅返回存在瑕疵/扣分的规则")}),handler:async($,Y,U)=>{let z=[],I;if(Y.file){let H=pp(Y.file);z=EB0(H.rules),I=H.meta.versionNumber}else if(Y.version){let H=await p8($),W=Number(Y.version),X=isNaN(W)?Y.version==="latest"?H[0]:H.find((Z)=>Z.id===Y.version):H.find((Z)=>Z.versionNumber===W);if(!X)throw Error(`未找到指定的规则版本: ${Y.version}`);I=X.versionNumber,z=(X.rules??[]).map((Z,q)=>({id:Z.id??Z.runtimeId,code:Z.code??`#${String(q+1).padStart(4,"0")}`,name:Z.name??Z.title,description:Z.description??"",scope:Z.scope,strictness:Z.strictness}))}else z=((await W6($)).rules??[]).map((W,X)=>({id:W.id,code:W.code??`#${String(X+1).padStart(4,"0")}`,name:W.name??W.title,description:W.description??"",scope:W.scope,strictness:W.strictness}));if(Y.code)z=z.filter((H)=>H.code===Y.code||H.code?.replace(/[#\s]/g,"")===Y.code?.replace(/[#\s]/g,""));if(Y.ruleId)z=z.filter((H)=>H.id===Y.ruleId||H.code===Y.ruleId);let Q=v4(),J=Y.linter??Q.lint?.activeLinter??"builtin",K=await bp(J),G=await BB0(z,K,{corpId:U?.corp?.id,versionNumber:I,allRules:z},{minScore:Y.minScore,level:Y.level,summary:Y.summary});if(Y.minScore&&G.overallScore<Y.minScore)throw Error(`[Linter 质量门禁未通过] 综合评分 ${G.overallScore} 低于要求的最低分 ${Y.minScore} 分 (共发现 ${G.issueCount} 条问题规则)。`);return G}},{name:"seal_approval_rules_pull",description:"从 Seal 远端拉取草稿或指定版本规则,保存至本地规则文件(支持离线编辑与本地 Lint,绝不污染远端草稿)",parameters:L.object({version:L.string().optional().describe("指定拉取的历史发布版本号或 ID(如 16 或 latest),不传默认拉取当前草稿规则"),out:L.string().optional().describe("保存的目标本地文件路径,默认为 ./rules.local.json")}),handler:async($,Y,U)=>{let z=Y.out??"./rules.local.json",I=[],Q="draft",J;if(Y.version){let G=await p8($),H=Number(Y.version),W=isNaN(H)?Y.version==="latest"?G[0]:G.find((X)=>X.id===Y.version):G.find((X)=>X.versionNumber===H);if(!W)throw Error(`未找到指定的规则版本: ${Y.version}`);J=W.versionNumber,Q=`version:${J}`,I=(W.rules??[]).map((X,Z)=>({code:X.code?Number(String(X.code).replace(/^#/,""))||Z+1:Z+1,name:X.name??X.title,description:X.description??"",scope:X.scope??"ALL",strictness:X.strictness??"MUST_FOLLOW"}))}else I=((await W6($)).rules??[]).map((H,W)=>({id:H.id,code:H.code??W+1,name:H.name??H.title,description:H.description??"",scope:H.scope??"ALL",strictness:H.strictness??"MUST_FOLLOW",status:H.status}));return{saved:!0,path:jB0(z,{corpId:U.corp.id,source:Q,versionNumber:J,exportedAt:new Date().toISOString(),rulesCount:I.length,rules: Line truncated
`+`• 身份主体:${T}${A}
`);let Z=Hm(G.document,H,W),q=await fetch(`${Q}/api/v1/integrations/webhook/${encodeURIComponent(J)}/document`,{method:"POST",headers:{...U.customHeaders??{},"Content-Type":"application/json",...oZ({webhookId:J,...Z},U.secret)},body:JSON.stringify(Z)});if(!q.ok)throw Error(`Webhook 单据推送失败 ${q.status}: ${await q.text()}`);K.push({documentId:Z.documentId,document:Z,pushResult:await q.json()}),process.stderr.write(`✓ 单据推送成功: ${Z.documentId}
`)}return{warnings:[],results:K}}function bI($){return{fileBuffer:Xy1($),fileName:$.split(/[\\\/]/).pop()??"material-pack.zip"}}var Qo=m(()=>{DP();Wm();Gm();Qm();Hz();Io()});import{existsSync as Ly1}from"node:fs";async function yT($,Y,U={}){let Q=A4().stateful?"stateful":"stateless",J="ok",K,z,G;try{let D=await o6($);G={id:D.user.id,name:D.user.name,isAdmin:D.user.isAdmin},z={id:D.tenant.id,name:D.tenant.name,tenantSlug:D.tenant.tenantSlug,corporationName:D.tenant.hoseCorpConfig?.corporationName}}catch(D){J="error",K=D instanceof Error?D.message:String(D)}let H=[];if(J==="ok")try{H=await Z$($,Y.seal.endpoints.approvalStylePreferences)}catch(D){J="error",K=`读取 Webhook 配置失败: ${D instanceof Error?D.message:String(D)}`}let W=H.length===1,X=H.map((D)=>({id:D.id,name:D.name,mode:D.mode,incomingDocumentWebhookUrl:D.incomingDocumentWebhook.url,outgoingResultWebhookUrl:D.outgoingResultWebhook,autoApprovalRate:D.autoApprovalRate,...W?{isDefault:!0}:{}})),Z=W?{id:H[0].id,name:H[0].name,mode:H[0].mode}:null,q=U.webhook?u7(H,U.webhook):W?H[0]:void 0,V;if(U.filePath)if(!Ly1(U.filePath))V={valid:!1,filePath:U.filePath,fileName:U.filePath.split(/[\\/]/).pop()??U.filePath,documentCount:0,errors:[`文件不存在: ${U.filePath}`]};else try{let D=bI(U.filePath),P=await uI(D.fileBuffer,D.fileName,q?.materialPackFilePolicy);V={valid:!0,filePath:U.filePath,fileName:D.fileName,documentCount:P.documents.length,warnings:P.warnings}}catch(D){V={valid:!1,filePath:U.filePath,fileName:U.filePath.split(/[\\/]/).pop()??U.filePath,documentCount:0,errors:[D instanceof Error?D.message:String(D)]}}let w=V?V.valid:!0,M=J==="ok"&&X.length>0&&w,F=Q==="stateful"?"":` --corp ${Y.id}`,N="",O="";if(J!=="ok")O=`凭证鉴权异常: ${K}`,N=`seal-use auth diagnose${F}`;else if(X.length===0)O="当前企业尚未配置任何 Webhook 集成通道",N=`seal-use webhook add --name "默认入站通道" --result-url "https://your-domain.com/callback"${F}`;else if(V&&!V.valid)O=`资源包预检失败: ${V.errors?.join("; ")}`,N=`seal-use webhook resource-pack preview ${V.filePath}${F}`;else{O=W?"所有通道正常,已自动锁定唯一 Webhook 通道,等待载入":`所有通道正常,检测到 ${X.length} 个 Webhook 通道,等待载入`;let D=V?.filePath??"<资源包.zip>",P=W?"":` --webhook ${Z?Z.id:"<webhookIdOrName>"}`;N=`seal-use webhook resource-pack push ${D}${P}${F}`}return{ready:M,corp:{id:Y.id,name:Y.name,sourceType:Y.source.type,tenant:z,user:G},stateMode:Q,authStatus:J,authError:K,activeWebhooks:X,defaultWebhook:Z,resourcePack:V,materialPack:V,statusMessage:O,nextAction:N}}var Av0=m(()=>{l$();H4();Qo()});var Jo=m(()=>{Hz();tQ();DP();Qm();Gm();Wm();Qo();Av0();Io()});var _q,Fy1,N24,D24,B24,A24,P24,T24,E24,j24,Ko,C24,R24,_24,v24,S24,h24,g24,y24,k24,x24,f24,u24,b24,i24,c24,n24,d24,p24,m24,l24,o24,r24,s24,a24,t24,e24,$Y4,YY4,UY4,IY4,QY4,JY4,KY4,zY4,GY4,HY4,WY4,XY4,ZY4,qY4,VY4,LY4,FY4,wY4,MY4,OY4,NY4,DY4,BY4,AY4,PY4,TY4,EY4,jY4,CY4,RY4,_Y4,vY4,SY4,hY4,Pv0;var Tv0=m(()=>{z6();H4();l$();f6();sZ();Jo();tQ();o$();({presentWebhookIntegration:_q,getConfiguredSealBaseUrl:Fy1,projectApprovalRules:N24,pickRuleFields:D24,buildRulePushPlan:B24,rulesHaveSameContent:A24,ruleChangedFields:P24,normalizeRuleStrictness:T24,parseDurationMs:E24,redactIntegrationSecrets:j24,mutationPreview:Ko,redactPreviewValue:C24,buildSimulationBatchParams:R24,summarizeSimulationBatch:_24,summarizeApprovalRun:v24,summarizeApprovalRuns:S24,parseFieldPaths:h24,pickRunFields:g24,approvalRunMetadata:y24,summarizeApprovalRunDetail:k24,summarizeApprovalRunResult:x24,summarizeApprovalRunDocument:f24,extractCitedRules:u24,firstPath:b24,countPathCandidates:i24,getPath:c24,setPath:n24,compactObject:d24,asRecord:p24,numberFromUnknown:m24,flattenDocumentFields:l24,collectDocumentFields:o24,firstByLabel:r24,collectInvoiceSummary:s24,collectInvoiceObjects:a24,findKeywordLines:t24,summarizeRunBridge:e24,summarizeRuleVersion:$Y4,resolveRuleVersionForLookup:YY4,findRuleInVersion:UY4,normalizeRuleCode:IY4,runtimeRuleIndex:QY4,runtimeRuleIdToCode:JY4,formatRuleCode:KY4,pickApprovalRunCandidate:zY4,resolveApprovalRunForUrl:GY4,resolveSealBaseUrl:HY4,normalizeUrl:WY4,stringFromUnknown:XY4,pickApprovalRuns:ZY4,timestampOf:qY4,resolveRuleVersion:VY4,resolveRuleVersionSelector:LY4,filterRuns:FY4,scalarIncludes:wY4,objectContainsScalar:MY4,filterRunsByHumanResult:OY4,withApprovalRunFilters:NY4,resolveManualApprovalStatus:DY4,prepareApprovalRuns:BY4,approvalRunAliases:AY4,extractHumanResult:PY4,findHumanResultValue:TY4,isHumanResultKey:EY4,stringifyHumanResultValue:jY4,matchesRunLookup:CY4,countBy:RY4,localDateKey:_Y4,formatLocalDateTime:vY4,toDate:SY4,localParts:hY4}=K8),Pv0=[{name:"seal_webhook_list",description:"列出当前 Seal 租户的 Webhook 集成,可按 ID、名称或 URL 查找",parameters:L.object({query:L.string().optional().describe("按集成 ID、名称或 URL 做本地包含匹配"),includeSecret:L.boolean().optional().describe("是否返回 Webhook secret;默认遮罩")} Line truncated
`+`• 身份主体:${T}${B}
`+`• 权限范围:持有该链接者在 Seal AI 中拥有该用户的完整操作权限(含系统设置与规则编辑)
`+`• 时效性:换票凭证有效时间 ${q} 秒(${Math.round(q/60)} 分钟),在浏览器打开后将保留 30 天会话
`+"• 安全边界:该凭证绝不包含且无法访问合思 (Hose) 主系统;仅限内部排查,严禁在外部公开分享!")}return{url:W?J:Z?V:G,type:X,mode:Z?"auto_login":"direct",sealResultUrl:G,hoseDocumentUrl:J,documentUrl:J,ssoUrl:V,expiresIn:Z?q:void 0,identity:w,warning:M,hoseDomain:Q.type==="hose"?wg1(Q.domain):void 0,recordId:I.id,sourceDocumentSN:I.sourceDocumentSN,sourceDocumentId:I.sourceDocumentId,sourceSystem:I.sourceSystem,missing:{hoseDocumentUrl:!J?"sourceExtendData.hosecloudViewUrl is absent from the approval run detail.":void 0}}}},{name:"seal_approval_run_pick",description:"按合思单号或关键字查询运行记录,返回候选记录及其当时使用的规则版本,便于再取详情或查版本规则",parameters:L.object({query:L.string().optional().describe("合思单号、源单据 ID、运行记录 ID 或 trace 关键字"),sn:L.string().optional().describe("合思/易快报单号;优先作为精确 sourceDocumentSN 查询"),batchId:L.string().optional().describe("模拟批次 ID"),latest:L.boolean().optional().describe("只返回最新一条匹配记录"),fields:L.union([L.string(),L.array(L.string())]).optional().describe("限制返回字段"),limit:L.number().int().positive().max(100).optional(),maxScan:L.number().int().positive().max(5000).optional().describe("最多扫描多少条运行记录用于本地匹配,默认 1000"),includeBridge:L.boolean().optional()}),handler:async($,Y,U)=>{let z=Y.sn??Y.query;if(!z)throw Error("query or sn is required");let I=await Mg1($,{query:z,sn:Y.sn,batchId:Y.batchId,latest:Y.latest,limit:Y.latest?1:Y.limit??20,maxScan:Y.maxScan??1000}),Q=await Promise.all(I.records.map((X)=>H4($,X.id))),J=y_0(Y.fields),K=Q.map((X)=>Vg1(X,J)),G=Q.find((X)=>X.ruleSetVersionNumber!==void 0)?.ruleSetVersionNumber,H=G===void 0?"latest":String(G),W=G===void 0?'"latestRuleVersion":true':`"ruleVersionNumber":${G}`;return{query:z,sourceDocumentSN:Y.sn,simulationBatchId:Y.batchId,latest:Y.latest??!1,total:I.total,scanned:I.scanned,matched:K.length,records:K,next:{getSummary:`seal-use approval-runs get <recordId> --summary --corp ${U.corp.id}`,getRuleVersion:`seal-use rules version ${H} --corp ${U.corp.id}`,searchRuleVersion:`seal-use tool seal_approval_search --corp ${U.corp.id} --json '{"keywords":["关键词"],"areas":["rules"],"ruleVersionScope":"version",${W}}'`,getVersionContext:`seal-use tool seal_approval_context_get --corp ${U.corp.id} --json '{${W}}'`},...Y.includeBridge?{bridge:TT(Q)}:{}}}},{name:"seal_simulation_batch_records_get",description:"获取某一次 Seal 模拟批次的运行记录,并整理对应 Langfuse trace/session 桥接字段",parameters:L.object({batchId:L.string().describe("simulation batch ID"),query:L.string().optional().describe("在 id、sourceDocumentSN、sourceDocumentId、documentId、Langfuse traceId 中做本地包含匹配")}),handler:async($,Y)=>{let U=ml(await Pg($,Y.batchId),Y.query);return{batchId:Y.batchId,count:U.length,records:U.map(fz),bridge:TT(U)}}},{name:"seal_simulation_batch_create",description:"创建 Seal 模拟测试批次。支持合思指定单号(hosecloud)与材料包导入(material_pack)两种模式;其他取数模式通过 rawParams 预留透传。",parameters:L.object({mode:L.enum(["hosecloud","material_pack"]).default("hosecloud").describe("来源模式: hosecloud=合思指定单号; material_pack=材料包导入"),flowIds:L.array(L.string()).max(100).optional().describe("合思模式: 单据流水号列表"),rejectNodeName:L.string().nullable().optional().describe("仅关注特定节点: 节点名称, 不设为 null 表示不限制"),thinkingDepthOverride:L.enum(["default","medium","high"]).optional().describe("思考深度: default=按偏好设置, medium=标准, high=深度推理"),skipInvoiceGeneration:L.boolean().optional().describe("跳过发票生成, 默认 true"),skipExpenseExtraction:L.boolean().optional().describe("跳过费用提取, 默认 true"),disableAttachmentCache:L.boolean().optional().describe("不使用附件缓存, 默认 false"),signKey:L.string().optional().describe("合思集成标识; 缺省时自动取第一个合思集成"),packageIds:L.array(L.string()).optional().describe("材料包模式: 材料包 id 列表(来自 material-packages upload 响应)"),templateId:L.string().optional().describe("材料包模板 id, 例如 conference_reimbursement_v1; 缺省取 schemaConfig.id"),schemaConfig:L.record(L.string(),L.unknown()).optional().describe("材料包字段映射(确认参数), 建议使用 material-packages upload 返回的 schemaConfig"),noWait:L.boolean().optional().describe("创建后立即返回异步票据,不等待批次完成"),rawParams:L.record(L.string(),L.unknown()).optional().describe("预留: 其他取数模式(如时间范围 startTime/endTime)透传参数, 覆盖上述构建结果")}),handler:async($,Y)=>{let U=Y.mode??"hosecloud",z=Y.signKey;if(U==="hosecloud"&&!z){if(z=(await jg($)).find((K)=>K.signKey)?.signKey,!z)throw Error(" Line truncated
`)}function Rg1($){let Y=[];if(Y.push(`seal-use ${$.area} - ${$.title}`),$.description)Y.push($.description);Y.push(""),Y.push("Usage:");let U=new Map;for(let I of $.commands){let Q=I.group??"",J=U.get(Q)??[];J.push(I),U.set(Q,J)}let z=[...$.groupOrder??[],...[...U.keys()].filter((I)=>!$.groupOrder?.includes(I))];for(let I of z){let Q=U.get(I);if(!Q)continue;if(I)Y.push(""),Y.push(`${I}:`);for(let J of Q)for(let K of J.usage)Y.push(` ${K}`)}if($.commands.some((I)=>I.name))Y.push(""),Y.push(`Run 'seal-use ${$.area} <command> --help' for details on a specific command.`);return Y.join(`
`)}function $v0(){let $=[];$.push("seal-use CLI"),$.push(""),$.push("Usage:"),$.push(" seal-use version");for(let Y of Yv0)for(let U of Y.commands)for(let z of U.usage)$.push(` ${z}`);return $.push(""),$.push("Run 'seal-use <command> --help' for details on a specific command."),$.join(`
`)}var Yv0;var el=m(()=>{O8();Yv0=[{area:"corps",title:"Enterprise and tenant management",description:"Manage enterprise configurations, environment modes, test bindings, and syncing.",groupOrder:["企业接入","发现与选择","企业配置","测试配对与验证","Hose 专属能力"],commands:[{name:"list",group:"发现与选择",summary:"List configured enterprises sorted by 7-day usage frequency",usage:["seal-use corps list [query] [--all] [--limit <n>] [--env <production|test>] [--strict] [--corp <corpId>]"],options:[{flag:"--all",description:"Display all configured enterprises without the default 10-item limit"},{flag:"--limit <n>",description:"Maximum number of enterprises to display (defaults to 10)"},{flag:"--env <production|test>",description:"Filter enterprises by environment ('production' or 'test')"},{flag:"--strict",description:"Use strict exact substring matching instead of default soft fuzzy search"}]},{name:"search",aliases:["find"],group:"发现与选择",summary:"Search configured enterprises with intelligent soft fuzzy matching",usage:["seal-use corps search <query> [--env <production|test>] [--strict]"],options:[{flag:"--env <production|test>",description:"Filter enterprises by environment ('production' or 'test')"},{flag:"--strict",description:"Use strict exact substring matching instead of default soft fuzzy search"}],description:"Searches enterprise ID, name, staff ID, domain, tenant slug, environment, or bindings. Uses soft search by default (case-insensitive, Chinese homophones, front/back nasal vowels, initials, typo/missing letter tolerance)."},{name:"get",aliases:["show"],group:"发现与选择",summary:"Get rich details and configuration of an enterprise",usage:["seal-use corps get <corpId>"],description:"Retrieves complete enterprise details (URLs, tenant slugs, custom headers/cookies, staff IDs, relations, config file path) with sensitive secrets safely redacted."},{name:"current",group:"发现与选择",summary:"Show active enterprise in stateful mode",usage:["seal-use corps current [--corp <corpId>]"]},{name:"switch",group:"发现与选择",summary:"Switch default active enterprise",usage:["seal-use corps switch <corpId>"]},{name:"mark",group:"企业配置",summary:"Mark enterprise environment as production or test",usage:["seal-use corps mark <corpId> --env <production|test> [--confirm]"],options:[{flag:"--env <production|test>",description:"Target environment: 'production' or 'test' (required)"},{flag:"--confirm",description:"Confirm the environment update (required)"}],description:"Explicitly updates an enterprise's environment tag. Requires --confirm to prevent accidental changes."},{name:"rename",group:"企业配置",summary:"Rename an enterprise display name",usage:["seal-use corps rename <corpId> --name <newName>"],options:[{flag:"--name <newName>",description:"New human-readable enterprise name (required)"}],description:"Safely updates the display name of a configured enterprise without modifying underlying files manually."},{name:"bind-test",group:"测试配对与验证",summary:"Bind a production enterprise to a test enterprise (1-to-1 association)",usage:["seal-use corps bind-test <prodCorpId> <testCorpId> [--confirm] [--force]","seal-use corps bind-test <testCorpId> --corp <prodCorpId> [--confirm] [--force]"],options:[{flag:"--confirm",description:"Explicitly confirm binding and tag test environment (required)"},{flag:"--force",description:"Force re-binding if the production enterprise is already bound"},{flag:"--corp <corpId>",description:"Specify production enterprise ID or name"}],description:"Establishes a strict 1-to-1 association between a production enterprise and a test enterprise. Automatically marks the test enterprise with environment 'test'."},{name:"unbind-test",group:"测试配对与验证",summary:"Unbind a production and test enterprise association",usage:["seal-use corps unbind-test [<corpId>] [--confirm]"],options:[{flag:"--confirm",description:"Explicitly confirm unbinding both sides (required)"},{flag:"--corp <corpId>",description:"Specify enterprise ID or name"}],description:"Removes the 1-to-1 test association from both the production enterprise and the test enterprise."},{name:"sync-test",group:"测试配对与验证",summary:"Synchronize rules and preferences from production to test enterprise",usage:["seal-use corps sync-test [<prodCorpId>] [--dry-run] [--yes] [--version-name <name>]"],options:[{flag:"--dry-run",description:"Preview sync diff without making network mutations (default)"},{flag:"--yes",description:"Execute synchronization and publish new rule version on test enterprise"},{flag:"--version-name <name>",description:"Custom version name for published test rule version"},{flag:"--corp <corpId>",description:"Specify production enterprise ID or name"}],description:"Overwrites test enterprise decision preferences with production preferences, syncs production draft rules to test enterprise, and immediately publishes a new versi Line truncated
`+"• 安全边界:该凭证绝不包含且无法访问合思 (Hose) 主系统;仅限内部排查,严禁在外部公开分享!")}return{url:W?K:Z?V:G,type:X,mode:Z?"auto_login":"direct",sealResultUrl:G,hoseDocumentUrl:K,documentUrl:K,ssoUrl:V,expiresIn:Z?q:void 0,identity:w,warning:M,hoseDomain:J.type==="hose"?Ey1(J.domain):void 0,recordId:Q.id,sourceDocumentSN:Q.sourceDocumentSN,sourceDocumentId:Q.sourceDocumentId,sourceSystem:Q.sourceSystem,missing:{hoseDocumentUrl:!K?"sourceExtendData.hosecloudViewUrl is absent from the approval run detail.":void 0}}}},{name:"seal_approval_run_pick",description:"按合思单号或关键字查询运行记录,返回候选记录及其当时使用的规则版本,便于再取详情或查版本规则",parameters:L.object({query:L.string().optional().describe("合思单号、源单据 ID、运行记录 ID 或 trace 关键字"),sn:L.string().optional().describe("合思/易快报单号;优先作为精确 sourceDocumentSN 查询"),batchId:L.string().optional().describe("模拟批次 ID"),latest:L.boolean().optional().describe("只返回最新一条匹配记录"),fields:L.union([L.string(),L.array(L.string())]).optional().describe("限制返回字段"),limit:L.number().int().positive().max(100).optional(),maxScan:L.number().int().positive().max(5000).optional().describe("最多扫描多少条运行记录用于本地匹配,默认 1000"),includeBridge:L.boolean().optional()}),handler:async($,Y,U)=>{let I=Y.sn??Y.query;if(!I)throw Error("query or sn is required");let Q=await Cy1($,{query:I,sn:Y.sn,batchId:Y.batchId,latest:Y.latest,limit:Y.latest?1:Y.limit??20,maxScan:Y.maxScan??1000}),J=await Promise.all(Q.records.map((X)=>G4($,X.id))),K=jv0(Y.fields),z=J.map((X)=>Ay1(X,K)),G=J.find((X)=>X.ruleSetVersionNumber!==void 0)?.ruleSetVersionNumber,H=G===void 0?"latest":String(G),W=G===void 0?'"latestRuleVersion":true':`"ruleVersionNumber":${G}`;return{query:I,sourceDocumentSN:Y.sn,simulationBatchId:Y.batchId,latest:Y.latest??!1,total:Q.total,scanned:Q.scanned,matched:z.length,records:z,next:{getSummary:`seal-use approval-runs get <recordId> --summary --corp ${U.corp.id}`,getRuleVersion:`seal-use rules version ${H} --corp ${U.corp.id}`,searchRuleVersion:`seal-use tool seal_approval_search --corp ${U.corp.id} --json '{"keywords":["关键词"],"areas":["rules"],"ruleVersionScope":"version",${W}}'`,getVersionContext:`seal-use tool seal_approval_context_get --corp ${U.corp.id} --json '{${W}}'`},...Y.includeBridge?{bridge:zo(J)}:{}}}},{name:"seal_approval_run_langfuse_bridge_get",description:"从 Seal approval run 中抽取 Langfuse 定位信息;优先返回 _langfuseTraceId,没有时给出 hosecloud-{sourceDocumentSN} session 回退",parameters:L.object({recordId:L.string().optional(),sourceDocumentSN:L.string().optional(),sourceDocumentId:L.string().optional(),simulationBatchId:L.string().optional(),limit:L.number().int().positive().max(100).optional()}),handler:async($,Y)=>{let I=(Y.simulationBatchId?await bM($,Y.simulationBatchId):(await x4($,{limit:Y.limit??50,search:Y.sourceDocumentSN??Y.sourceDocumentId,sourceDocumentSN:Y.sourceDocumentSN,sourceDocumentId:Y.sourceDocumentId})).records).filter((Q)=>hy1(Q,{recordId:Y.recordId,sourceDocumentSN:Y.sourceDocumentSN,sourceDocumentId:Y.sourceDocumentId}));return{count:I.length,records:I.map(Ev0),bridge:zo(I)}}},{name:"seal_approval_runs_stats",description:"统计审核记录状态分布、来源系统分布及按单号/ID去重统计",parameters:L.object({since:L.string().optional().describe("时间范围,如 3months, 7days, 24hours"),dedupeBy:L.enum(["sourceDocumentSN","sourceDocumentId","id"]).default("sourceDocumentSN").describe("去重字段"),status:L.string().optional(),sourceSystem:L.string().optional(),taskMode:L.string().optional()}),handler:async($,Y)=>{let U=await x4($,{limit:1000,status:Y.status,sourceSystem:Y.sourceSystem,taskMode:Y.taskMode}),I=Y.dedupeBy??"sourceDocumentSN",Q=U.records,J={},K={},z=new Set;for(let H of Q){let W=H.status??"unknown";J[W]=(J[W]??0)+1;let X=H.sourceSystem??"unknown";K[X]=(K[X]??0)+1;let Z=H[I];if(Z)z.add(String(Z))}let G=Math.max(0,Q.length-z.size);return{total:Q.length,dedupeBy:I,unique:z.size,duplicateRuns:G,dedupeNote:G>0?`存在 ${G} 笔重复运行记录 (同一单据重跑或修改重推)`:"全部单据唯一,无重复记录",byStatus:J,bySourceSystem:K}}},{name:"seal_approval_runs_count",description:"统计符合条件的审核记录总数",parameters:L.object({status:L.string().optional(),sourceSystem:L.string().optional(),taskMode:L.string().optional(),search:L.string().optional(),startDate:L.string().optional().describe("起始时间戳(毫秒)或日期字符串"),endDate:L.string().optional().describe("结束时间戳(毫秒)或日期字符串")}),handler:async($,Y)=>{let U=await x4($,{limit:1,status:Y.status,sourceSystem:Y.sourceSystem,taskMode:Y.taskMode,search:Y.search,startDate:n2(Y.startDate,!1),endDate:n2(Y.endDate,!0)});return{total:U.total??U.records.l Line truncated
`)}function sy1($){let Y=[];if(Y.push(`seal-use ${$.area} - ${$.title}`),$.description)Y.push($.description);Y.push(""),Y.push("Usage:");let U=new Map;for(let Q of $.commands){let J=Q.group??"",K=U.get(J)??[];K.push(Q),U.set(J,K)}let I=[...$.groupOrder??[],...[...U.keys()].filter((Q)=>!$.groupOrder?.includes(Q))];for(let Q of I){let J=U.get(Q);if(!J)continue;if(Q)Y.push(""),Y.push(`${Q}:`);for(let K of J)for(let z of K.usage)Y.push(` ${z}`)}if($.commands.some((Q)=>Q.name))Y.push(""),Y.push(`Run 'seal-use ${$.area} <command> --help' for details on a specific command.`);return Y.join(`
`)}function iv0(){let $=[];$.push("seal-use CLI"),$.push(""),$.push("Usage:"),$.push(" seal-use version");for(let Y of cv0)for(let U of Y.commands)for(let I of U.usage)$.push(` ${I}`);return $.push(""),$.push("Run 'seal-use <command> --help' for details on a specific command."),$.join(`
`)}var cv0;var Vo=m(()=>{J$();cv0=[{area:"corps",title:"Enterprise and tenant management",description:"Manage enterprise configurations, environment modes, test bindings, and syncing.",groupOrder:["企业接入","发现与选择","企业配置","测试配对与验证","Hose 专属能力"],commands:[{name:"list",group:"发现与选择",summary:"List configured enterprises sorted by 7-day usage frequency",usage:["seal-use corps list [query] [--all] [--limit <n>] [--env <production|test>] [--strict] [--corp <corpId>]"],options:[{flag:"--all",description:"Display all configured enterprises without the default 10-item limit"},{flag:"--limit <n>",description:"Maximum number of enterprises to display (defaults to 10)"},{flag:"--env <production|test>",description:"Filter enterprises by environment ('production' or 'test')"},{flag:"--strict",description:"Use strict exact substring matching instead of default soft fuzzy search"}]},{name:"search",aliases:["find"],group:"发现与选择",summary:"Search configured enterprises with intelligent soft fuzzy matching",usage:["seal-use corps search <query> [--env <production|test>] [--strict]"],options:[{flag:"--env <production|test>",description:"Filter enterprises by environment ('production' or 'test')"},{flag:"--strict",description:"Use strict exact substring matching instead of default soft fuzzy search"}],description:"Searches enterprise ID, name, staff ID, domain, tenant slug, environment, or bindings. Uses soft search by default (case-insensitive, Chinese homophones, front/back nasal vowels, initials, typo/missing letter tolerance)."},{name:"get",aliases:["show"],group:"发现与选择",summary:"Get rich details and configuration of an enterprise",usage:["seal-use corps get <corpId>"],description:"Retrieves complete enterprise details (URLs, tenant slugs, custom headers/cookies, staff IDs, relations, config file path) with sensitive secrets safely redacted."},{name:"current",group:"发现与选择",summary:"Show active enterprise in stateful mode",usage:["seal-use corps current [--corp <corpId>]"]},{name:"switch",group:"发现与选择",summary:"Switch default active enterprise",usage:["seal-use corps switch <corpId>"]},{name:"mark",group:"企业配置",summary:"Mark enterprise environment as production or test",usage:["seal-use corps mark <corpId> --env <production|test> [--confirm]"],options:[{flag:"--env <production|test>",description:"Target environment: 'production' or 'test' (required)"},{flag:"--confirm",description:"Confirm the environment update (required)"}],description:"Explicitly updates an enterprise's environment tag. Requires --confirm to prevent accidental changes."},{name:"rename",group:"企业配置",summary:"Rename an enterprise display name",usage:["seal-use corps rename <corpId> --name <newName>"],options:[{flag:"--name <newName>",description:"New human-readable enterprise name (required)"}],description:"Safely updates the display name of a configured enterprise without modifying underlying files manually."},{name:"bind-test",group:"测试配对与验证",summary:"Bind a production enterprise to a test enterprise (1-to-1 association)",usage:["seal-use corps bind-test <prodCorpId> <testCorpId> [--confirm] [--force]","seal-use corps bind-test <testCorpId> --corp <prodCorpId> [--confirm] [--force]"],options:[{flag:"--confirm",description:"Explicitly confirm binding and tag test environment (required)"},{flag:"--force",description:"Force re-binding if the production enterprise is already bound"},{flag:"--corp <corpId>",description:"Specify production enterprise ID or name"}],description:"Establishes a strict 1-to-1 association between a production enterprise and a test enterprise. Automatically marks the test enterprise with environment 'test'."},{name:"unbind-test",group:"测试配对与验证",summary:"Unbind a production and test enterprise association",usage:["seal-use corps unbind-test [<corpId>] [--confirm]"],options:[{flag:"--confirm",description:"Explicitly confirm unbinding both sides (required)"},{flag:"--corp <corpId>",description:"Specify enterprise ID or name"}],description:"Removes the 1-to-1 test association from both the production enterprise and the test enterprise."},{name:"sync-test",group:"测试配对与验证",summary:"Synchronize rules and preferences from production to test enterprise",usage:["seal-use corps sync-test [<prodCorpId>] [--dry-run] [--yes] [--version-name <name>]"],options:[{flag:"--dry-run",description:"Preview sync diff without making network mutations (default)"},{flag:"--yes",description:"Execute synchronization and publish new rule version on test enterprise"},{flag:"--version-name <name>",description:"Custom version name for published test rule version"},{flag:"--corp <corpId>",description:"Specify production enterprise ID or name"}],description:"Overwrites test enterprise decision preferences with production preferences, syncs production draft rules to test enterprise, and immediately publishes a new versi Line truncated
`)}
`}function Rq($){return $.replace(/([?&](?:accessToken|token|returnToken)=)[^&\s]+/gi,"$1<redacted>").replace(/(Bearer\s+)[A-Za-z0-9._~+/=-]+/gi,"$1<redacted>")}function R0($,Y={}){gg1($,Y);let U=`${JSON.stringify($,null,2)}
`;if(Y.outputFile){_g1(Y.outputFile,U),console.log(JSON.stringify({outputFile:Y.outputFile,bytes:Buffer.byteLength(U,"utf-8")},null,2));return}console.log(U.trimEnd())}function gg1($,Y={}){if(Y.allowFull||Y.outputFile)return;let U=Buffer.byteLength(JSON.stringify($),"utf-8");if(U>Sg1)throw new JP(`Output is large (${U} bytes). Use --summary, --fields, --count, or --output-file; pass --full only when you really need the full response.`)}function Qv0($,Y){if(Y)return;let U=$&&typeof $==="object"?$:{},z=typeof U.count==="number"?U.count:void 0,I=Array.isArray(U.rules)?U.rules.length:void 0,Q=Buffer.byteLength(JSON.stringify($),"utf-8"),J=z??I??0;if(J>vg1||Q>hg1)throw new JP(`Rule list is large (${J} rules, ${Q} bytes). Use "seal-use rules list --summary", "seal-use rules count", or --output-file; pass --full only when you really need full descriptions.`,"seal-use rules list --summary")}function j0($){return{allowFull:G0($.full)===!0,outputFile:S($.outputFile)??S($["output-file"])}}function Jv0($=[]){console.log(zv0($))}var vg1=100,hg1=120000,Iv0,Sg1=200000;var m1=m(()=>{Z4();O8();el();Iv0=["code","status","strictness","scope","updatedAt"]});var Yo={};T8(Yo,{selectCorp:()=>M1,runToolResult:()=>M$,runTool:()=>x0,globalConfigSummary:()=>t2});function M1($){let Y=t8(),U=v4(),z=n2(Y,{stateful:U.stateful,defaultCorpId:U.defaultCorpId,corpId:$},x3());return rA0(z.id),z}function t2($=v4()){return{mode:$.stateful?"stateful":"stateless",stateful:$.stateful,...$.stateful&&$.defaultCorpId?{defaultCorpId:$.defaultCorpId}:{},...$.testEnterprisesDir?{testEnterprisesDir:$.testEnterprisesDir}:{},lint:$.lint,configFile:Zz()}}async function x0($,Y,U,z,I={}){R0(await M$($,Y,U,z),I)}async function M$($,Y,U,z){let I=Pq.find((K)=>K.name===$);if(!I)throw Error(`Unknown Seal tool: ${$}`);let Q=Object.fromEntries(Object.entries(z).filter(([,K])=>K!==void 0)),J=I.handler;return J(Y,Q,{corp:U})}var O4=m(()=>{T5();UP();jq();m1()});import{existsSync as Kv0}from"node:fs";async function Gv0($,Y){if(!Kv0($))throw Error(`File not found: ${$}`);let U=xz($);console.log(JSON.stringify(await kz(U.fileBuffer,U.fileName,Y),null,2))}async function gT($,Y,U,z,I){if($==="ready"||$==="status"){let Q=Y??S(I.options.file)??S(I.options.input),J=await NT(U,z,{filePath:Q,webhook:S(I.options.webhook)??S(I.options.selector)});if(console.error(`[webhook-ready] 企业环境: ${J.corp.name} (${J.corp.id}) [${J.stateMode}]`),J.corp.tenant?.name)console.error(`[webhook-ready] 租户信息: ${J.corp.tenant.name} (${J.corp.tenant.id})`);console.error(`[webhook-ready] 凭证状态: ${J.authStatus==="ok"?"OK":`异常 (${J.authError})`}`),console.error(`[webhook-ready] Webhook 通道: ${J.activeWebhooks.length} 个可用`);for(let K of J.activeWebhooks){let G=K.isDefault?" [默认通道]":"";console.error(` - ${K.name} (${K.id}) mode=${K.mode}${G}`)}if(J.materialPack)console.error(`[webhook-ready] 材料包预检: ${J.materialPack.valid?`通过 (${J.materialPack.documentCount} 单)`:`失败 (${J.materialPack.errors?.join("; ")})`}`);if(J.ready)console.error(`\uD83D\uDFE2 ${J.statusMessage}`),console.error(`\uD83D\uDC49 Next action: ${J.nextAction}`);else console.error(`\uD83D\uDD34 准备阶段未通过: ${J.statusMessage}`),console.error(`\uD83D\uDC49 Next action: ${J.nextAction}`);console.log(JSON.stringify(J,null,2));return}if($==="replay"){let Q=Y??S(I.options.recordId)??S(I.options["record-id"])??S(I.options.id),J=S(I.options.recordIds)??S(I.options["record-ids"]),K=J?J.split(",").map((c)=>c.trim()).filter(Boolean):void 0,G=S(I.options.sn)??S(I.options.documentSn)??S(I.options["document-sn"]),H=S(I.options.sns)??S(I.options["document-sns"]),W=H?H.split(",").map((c)=>c.trim()).filter(Boolean):void 0,X=s0(I.options.limit),Z=S(I.options.status),q=S(I.options.startDate)??S(I.options["start-date"]),V=S(I.options.endDate)??S(I.options["end-date"]);if(!Q&&!K&&!G&&!W&&X===void 0)throw Error("Usage: seal-use webhook replay <recordId> [--sn <documentSN>] [--limit <n>] [--status <status>] [--webhook <idOrName>] [--source-corp <corpId>] [--target-corp <corpId>] [--dry-run]");let w=S(I.options.sourceCorp)??S(I.options["source-corp"])??S(I.options.prodCorp)??S(I.options["prod-corp"]),M=S(I.options.targetCorp)??S(I.options["target-corp"])??S(I.options.testCorp)??S(I.options["test-corp"]),F=G0(I.options.force)===!0,{sourceCorp:N,targetCorp:O}=KP({sourceCorpId:w,targetCorpId:M,activeCorp:z,force:F},M1),D=N.id===z.id?U:await B1(N),P=O.id===z.id?U:await B1(O),T=S(I.options.webhook)??S(I.options.selector),A=S(I.options.snSuffix)??S(I.options["sn-suffix"]),j=S(I.options.snPrefix)??S(I.options["sn-prefix"]),C=S(I.options.docIdSuffix)??S(I.options["doc-id-suffix"]),b=S(I.options.docIdPrefix)??S(I.options["doc-id-prefix"]),x=G0(I.options.dryRun)??G0(I.options["dry-run"]),i=await zK({query:{recordId:Q,recordIds:K,sn:G,sns:W,limit:X,status:Z,startDate:q,endDate:V},sourceClient:D,targetClient:P,sourceCorp:N,targetCorp:O,webhookSelector:T,snPrefix:j,snSuffix:A,docIdPrefix:b,docIdSuffix:C,dr Line truncated
or: seal-use corps bind-test <testCorpId> --corp <prodCorpId> [--confirm] [--force]`);let Q=M1(z),J=M1(I);if(Q.id===J.id)throw h4(`Cannot bind enterprise '${Q.id}' to itself.`);if(Q.prodCorpId&&Q.prodCorpId!==J.id)throw h4(`Cannot use '${Q.id}' as a production enterprise because it is already registered as a test enterprise for '${Q.prodCorpId}'. Multi-tier chaining is not permitted.`);if(J.testCorpId&&J.testCorpId!==Q.id)throw h4(`Cannot bind '${J.id}' as a test enterprise because it already has a bound test enterprise '${J.testCorpId}'. Multi-tier chaining is not permitted.`);let K=G0(U.options.force)===!0;if(Q.testCorpId&&Q.testCorpId!==J.id||J.prodCorpId&&J.prodCorpId!==Q.id){if(!K)throw w$(`Enterprise binding conflict: production enterprise '${Q.id}' is bound to '${Q.testCorpId??"none"}', and test enterprise '${J.id}' is bound to '${J.prodCorpId??"none"}'. Overwriting an existing binding requires --force and --confirm.`,`seal-use corps bind-test ${Q.id} ${J.id} --confirm --force`)}if(!(G0(U.options.confirm)===!0||G0(U.options.yes)===!0)){let X=K?" --force":"";throw w$(`Refusing to bind test enterprise '${J.name}' (${J.id}) to production enterprise '${Q.name}' (${Q.id}) without --confirm. Enterprise binding establishes 1-to-1 sync pairing and marks '${J.id}' as a test environment.`,`seal-use corps bind-test ${Q.id} ${J.id} --confirm${X}`)}if(Q.testCorpId&&Q.testCorpId!==J.id)try{E9(Q.testCorpId,{prodCorpId:void 0})}catch{}if(J.prodCorpId&&J.prodCorpId!==Q.id)try{E9(J.prodCorpId,{testCorpId:void 0})}catch{}let H=E9(Q.id,{environment:"production",testCorpId:J.id}),W=E9(J.id,{environment:"test",prodCorpId:Q.id});return R0({success:!0,productionEnterprise:{id:H.id,name:H.name,environment:H.environment,testCorpId:H.testCorpId},testEnterprise:{id:W.id,name:W.name,environment:W.environment,prodCorpId:W.prodCorpId}}),!0}if($==="unbind-test"){let z=Y??S(U.options.corp),I=M1(z);if(!I.testCorpId&&!I.prodCorpId)return R0({unbound:!1,message:`Enterprise '${I.name}' (${I.id}) does not have an active test enterprise binding.`}),!0;let Q=I.testCorpId?I.id:I.prodCorpId,J=I.testCorpId?I.testCorpId:I.id;if(!(G0(U.options.confirm)===!0||G0(U.options.yes)===!0))throw w$(`Refusing to unbind production enterprise '${Q}' and test enterprise '${J}' without --confirm.`,`seal-use corps unbind-test ${I.id} --confirm`);E9(Q,{testCorpId:void 0});try{E9(J,{prodCorpId:void 0})}catch{}return R0({success:!0,unboundProduction:Q,unboundTest:J}),!0}return!1}var Vv0=m(()=>{T5();O4();O8();Z4();m1()});function yT($){let Y;try{Y=new URL($.trim())}catch{throw Error("Invalid Seal delegate link: expected a valid HTTPS URL")}if(Y.protocol!=="https:")throw Error("Invalid Seal delegate link: expected HTTPS");let U=Y.hostname.toLowerCase();if(!U.endsWith(Lv0))throw Error(`Invalid Seal delegate link: expected host ending in ${Lv0}, got ${U}`);let z=Y.pathname.replace(/\/+$/,"");if(z!==Fv0)throw Error(`Invalid Seal delegate link: expected path ${Fv0}, got ${z}`);let I=Y.searchParams.get("token");if(!I)throw Error("Invalid Seal delegate link: token query parameter is required");return{sealUrl:Y.origin,delegateToken:I}}async function wv0($){let Y=typeof $==="string"?yT($):$;return(await B6(Y.sealUrl,void 0).post("api/v1/delegation/preview",{json:{token:Y.delegateToken}}).json()).data}async function Mv0($){let Y=typeof $==="string"?yT($):$,U=Y.sealUrl,z=B6(U,void 0),I=await z.post("api/v1/delegation/consume",{json:{token:Y.delegateToken}}),Q=I.headers.get("set-cookie")??"",J=typeof I.headers.getSetCookie==="function"?I.headers.getSetCookie():[Q],K="";for(let M of J)if(M&&M.includes("session_token=")){K=(M.split(";")[0]??"").trim();break}let G;try{G=await z.get("api/auth/get-session",{headers:K?{cookie:K}:{}}).json()}catch{}let H=G?.session?.token;if(!H&&K){let M=K.match(/session_token=([^.;]+)/);if(M?.[1])H=decodeURIComponent(M[1])}if(!H)throw Error("Seal delegate exchange did not return a session token");let W=86400;if(G?.session?.expiresAt){let M=new Date(G.session.expiresAt).getTime();if(Number.isFinite(M)){let F=Math.floor((M-Date.now())/1000);if(F>0)W=F}}let Z=await B6(U,H).get("api/v1/auth/me").json(),q=Z.data&&typeof Z.data==="object"?Z.data:Z,V=q.user??G?.user??{},w=q.tenant??{};return{sealUrl:U,token:H,expiresIn:W,user:V,tenant:w}}function kT($){let Y=[],U=0,z="";try{let J=new URL($.trim()),K=J.hostname.toLowerCase(),G=J.pathname.replace(/\/+$/,"");if(K.endsWith(".ekuaibao.com")||K.endsWith(".hosecloud.com")||K==="ekuaibao.com"||K==="hosecloud.com")U+=40,z="host is Hose domain";if(G==="/web/thirdparty.html")U+=40,z+="; path is /web/thirdparty.html";if(J.searchParams.has("accessToken"))U+=10,z+="; has accessToken";if(J.searchParams.has("ekbCorpId"))U+=10,z+="; has ekbCorpId"}catch{U=0}if(U>0)Y.push({kind:"hose",score:U,reason:z});let I=0,Q="";try{let J=new URL($.trim()),K=J.hostname.toLowerCase(),G=J.pathname.replace(/\/+$/,"");if(K.endsWith(".sealai.cc"))I+=40,Q="host ends with .sealai.cc";if(G==="/delegate")I+=40,Q+="; path is /delegate";if( Line truncated
`,{mode:384}),{config:U,path:I}}var Io=m(()=>{T5();sB()});function Qo($){return new Date($).toISOString().replace(/\.\d{3}Z$/,"Z")}function xT($){let Y=new Date($);if(Number.isNaN(Y.getTime()))return $;return Qo(Y.getTime())}function $5($){return typeof $==="string"&&$?$:void 0}function bg1($){return{headers:Ap.parse($.headers),cookies:Bp.parse($.cookies)}}async function ig1($,Y,U={}){let z=await Z8(B6($,Y,U));return{user:z.user??{},tenant:z.tenant??{}}}async function Ov0($){let Y=$.sealUrl.replace(/\/+$/,""),U=$.expiresIn??2592000,z=$.force===!0||$.verify===!1?!1:!0,I=bg1($),Q=z?await ig1(Y,$.token,A6(I)):void 0,J=Dv0($,{token:$.token,sealUrl:Y,expiresIn:U,expiresAt:$.expiresAt,verify:z,remote:Q,custom:I}),K=$.tenantId??$5(Q?.tenant.id),G=$.tenantSlug??$5(Q?.tenant.tenantSlug);return{...J,verified:z,tenantId:K,tenantSlug:G}}function Nv0($){let Y=$5($.session.tenant.tenantSlug),U=$5($.session.tenant.id),z=Y??U??"seal-delegate";return{...Dv0({id:z,corpId:z,name:$.name,provider:"seal",overwrite:$.overwrite},{token:$.session.token,sealUrl:$.session.sealUrl,expiresIn:$.session.expiresIn,verify:!0,remote:{user:$.session.user,tenant:$.session.tenant}}),tenantId:U,tenantSlug:Y}}function Dv0($,Y){let U=Y.remote?.user,z=Y.remote?.tenant,I=$.tenantSlug??$5(z?.tenantSlug),Q=$.tenantId??$5(z?.id),J=$.tenantName??$5(z?.name),K=$.id??I??Q;if(!K)throw Error("Missing required JSON field: id. Seal whoami did not return tenantSlug or tenantId.");let G=Y.expiresAt?xT(Y.expiresAt):Qo(Date.now()+Y.expiresIn*1000),H=$.staffId??$5(U?.providerUserId)??$5(U?.id)??"seal",W=$.provider??$5(U?.provider)??$5(z?.providerConfig?.provider),X=$.corpId??I??Q??K,Z={id:K,name:$.name??J??K,environment:"production",seal:{url:Y.sealUrl,tenantSlug:I,headers:Y.custom?.headers,cookies:Y.custom?.cookies,endpoints:{approvalStylePreferences:"api/v1/agent/ai-approval/config"}},source:{type:"seal",token:Y.token,sealUrl:Y.sealUrl,expiresIn:Y.expiresIn,expiresAt:G,staffId:H,corpId:X,tenantId:Q,tenantSlug:I,tenantName:J,providerUserId:$5(U?.providerUserId),provider:W},auth:{refreshTtl:300}};return _q(Z,{overwrite:$.overwrite===!0})}var Jo=m(()=>{Io();sB();m6();X6()});async function bK($){let[Y,U]=await Promise.all([J10($),B1($)]),z=await Z8(U);return{...Y,tenantId:z.tenant.id,tenantSlug:z.tenant.tenantSlug??Y.tenantSlug,tenantName:z.tenant.name,raw:{...typeof Y.raw==="object"&&Y.raw!==null?Y.raw:{},user:{id:z.user.id,name:z.user.name,isAdmin:z.user.isAdmin,providerUserId:z.user.providerUserId,hosecloudStaff:z.user.hosecloudStaff},tenant:z.tenant}}}var fT=m(()=>{m6();Gg();X6()});async function Av0($){let Y=await rI($.appKey,$.appSecurity,$.domain),U=await FM(Y.domain,Y.openapiToken).catch(()=>[]);return{...Y,roleCount:U.reduce((z,I)=>z+I.roleDefs.length,0),roleGroups:U.map((z)=>({id:z.id,name:z.name,roleDefs:z.roleDefs.map((I)=>({id:I.id,name:I.name,sourceType:I.sourceType}))}))}}async function Bv0($){let Y=await rI($.appKey,$.appSecurity,$.domain),U=$.role??$.roleDefId??"admin",z=await FM(Y.domain,Y.openapiToken),I,Q;for(let G of z){for(let H of G.roleDefs)if(H.id===U||H.id===`${Y.corpId}:${U}`){I=H.id,Q=H.name;break}if(I)break}if(!I&&(U==="admin"||U==="主管理员"))for(let G of z){for(let H of G.roleDefs)if(H.id.endsWith(":admin")||H.name==="主管理员"){I=H.id,Q=H.name;break}if(I)break}if(!I)for(let G of z){for(let H of G.roleDefs)if(H.name.toLowerCase().includes(U.toLowerCase())){I=H.id,Q=H.name;break}if(I)break}if(!I)throw Error(`Role not found matching query: '${U}'. Run 'seal-use corps probe-hose' to view all available roles.`);let J=await Ig(Y.domain,Y.openapiToken,I),K=await Qg(Y.domain,Y.openapiToken,J.staffs);return{domain:Y.domain,corpId:Y.corpId,corpName:Y.corpName??Y.corpId,roleId:I,roleName:Q,staffs:K}}async function vq($){let Y=$.domain,U=$.staffId??$.proxyStaffBizId,z=$.force===!0,I=z||$.verify===!1?!1:!0,Q=Y,J=$.corpId??$.corporationId,K=$.name,G;if(!Q||!J||!U){let V=await rI($.appKey,$.appSecurity,Y);Q=V.domain,J=J??V.corpId,K=K??V.corpName,G=V.openapiToken}let H=U;if(!H&&G&&Q){let V=$.role??"admin",w=await FM(Q,G).catch(()=>[]),M;for(let F of w){for(let N of F.roleDefs)if(N.id.endsWith(`:${V}`)||N.name===V||N.id===V){M=N.id;break}if(M)break}if(!M)M=w.find((F)=>F.roleDefs.some((N)=>N.id.endsWith(":admin")))?.roleDefs.find((F)=>F.id.endsWith(":admin"))?.id;if(M){let F=await Ig(Q,G,M).catch(()=>({staffs:[]})),N=await Qg(Q,G,F.staffs).catch(()=>[]);if($.staffName||$.staffPhone){let O=N.filter((D)=>{if($.staffName&&D.name!==$.staffName&&!D.name.includes($.staffName))return!1;if($.staffPhone&&(!D.cellphone||!D.cellphone.includes($.staffPhone)))return!1;return!0});if(O.length===1&&O[0])H=O[0].id;else if(O.length>1)throw Error(`Multiple staff members matched '${$.staffName??$.staffPhone}': ${O.map((D)=>`${D.name}(${D.id})`).join(", ")}. Please specify exact staffId.`);else throw Error(`No staff member found matching '${$.staffName??$.staffPhone}' under role ${M}. Run 'seal-use corps hose-staffs' to view candidates.`)}else if(!z){let O=N.map( Line truncated
`+"\uD83D\uDCA1 说明:此能力专属于合思 (Hose) 子域,用于将临时会话提权为标准 OpenAPI 开发者接入。需要企业管理员已在合思开放平台创建应用并生成 appKey/appSecurity。",z);if(U.keyId||U.appKey){let I=$.find((Q)=>U.keyId&&Q.id===U.keyId||U.appKey&&Q.appKey===U.appKey);if(!I)throw new bz(`指定的合思密钥不存在,请从上述候选列表中选择正确的 appKey 或 keyId。
`}function yq($){return $.replace(/([?&](?:accessToken|token|returnToken)=)[^&\s]+/gi,"$1<redacted>").replace(/(Bearer\s+)[A-Za-z0-9._~+/=-]+/gi,"$1<redacted>")}function R0($,Y={}){Yk1($,Y);let U=`${JSON.stringify($,null,2)}
`;if(Y.outputFile){ay1(Y.outputFile,U),console.log(JSON.stringify({outputFile:Y.outputFile,bytes:Buffer.byteLength(U,"utf-8")},null,2));return}console.log(U.trimEnd())}function Yk1($,Y={}){if(Y.allowFull||Y.outputFile)return;let U=Buffer.byteLength(JSON.stringify($),"utf-8");if(U>$k1)throw new rZ(`Output is large (${U} bytes). Use --summary, --fields, --count, or --output-file; pass --full only when you really need the full response.`)}function mv0($,Y){if(Y)return;let U=$&&typeof $==="object"?$:{},I=typeof U.count==="number"?U.count:void 0,Q=Array.isArray(U.rules)?U.rules.length:void 0,J=Buffer.byteLength(JSON.stringify($),"utf-8"),K=I??Q??0;if(K>ty1||J>ey1)throw new rZ(`Rule list is large (${K} rules, ${J} bytes). Use "seal-use rules list --summary", "seal-use rules count", or --output-file; pass --full only when you really need full descriptions.`,"seal-use rules list --summary")}function E0($){return{allowFull:G0($.full)===!0,outputFile:h($.outputFile)??h($["output-file"])}}function lv0($=[]){console.log(dv0($))}var ty1=100,ey1=120000,pv0,$k1=200000;var l1=m(()=>{q4();J$();Vo();pv0=["code","status","strictness","scope","updatedAt"]});var Fo={};Z8(Fo,{selectCorp:()=>M1,runToolResult:()=>P$,runTool:()=>x0,globalConfigSummary:()=>e2});function M1($){let Y=Y$(),U=A4(),I=d2(Y,{stateful:U.stateful,defaultCorpId:U.defaultCorpId,corpId:$},i3());return WA0(I.id),I}function e2($=A4()){return{mode:$.stateful?"stateful":"stateless",stateful:$.stateful,...$.stateful&&$.defaultCorpId?{defaultCorpId:$.defaultCorpId}:{},...$.testEnterprisesDir?{testEnterprisesDir:$.testEnterprisesDir}:{},lint:$.lint,configFile:qI()}}async function x0($,Y,U,I,Q={}){R0(await P$($,Y,U,I),Q)}async function P$($,Y,U,I){let Q=vq.find((z)=>z.name===$);if(!Q)throw Error(`Unknown Seal tool: ${$}`);let J=Object.fromEntries(Object.entries(I).filter(([,z])=>z!==void 0)),K=Q.handler;return K(Y,J,{corp:U})}var O4=m(()=>{l$();HP();Sq();l1()});import{existsSync as ov0}from"node:fs";async function rv0($,Y){if(!ov0($))throw Error(`File not found: ${$}`);let U=bI($);console.log(JSON.stringify(await uI(U.fileBuffer,U.fileName,Y),null,2))}async function iT($,Y,U,I,Q){if($==="ready"||$==="status"){let J=Y??h(Q.options.file)??h(Q.options.input),K=await yT(U,I,{filePath:J,webhook:h(Q.options.webhook)??h(Q.options.selector)});if(console.error(`[webhook-ready] 企业环境: ${K.corp.name} (${K.corp.id}) [${K.stateMode}]`),K.corp.tenant?.name)console.error(`[webhook-ready] 租户信息: ${K.corp.tenant.name} (${K.corp.tenant.id})`);console.error(`[webhook-ready] 凭证状态: ${K.authStatus==="ok"?"OK":`异常 (${K.authError})`}`),console.error(`[webhook-ready] Webhook 通道: ${K.activeWebhooks.length} 个可用`);for(let z of K.activeWebhooks){let G=z.isDefault?" [默认通道]":"";console.error(` - ${z.name} (${z.id}) mode=${z.mode}${G}`)}if(K.materialPack)console.error(`[webhook-ready] 材料包预检: ${K.materialPack.valid?`通过 (${K.materialPack.documentCount} 单)`:`失败 (${K.materialPack.errors?.join("; ")})`}`);if(K.ready)console.error(`\uD83D\uDFE2 ${K.statusMessage}`),console.error(`\uD83D\uDC49 Next action: ${K.nextAction}`);else console.error(`\uD83D\uDD34 准备阶段未通过: ${K.statusMessage}`),console.error(`\uD83D\uDC49 Next action: ${K.nextAction}`);console.log(JSON.stringify(K,null,2));return}if($==="replay"){let J=Y??h(Q.options.recordId)??h(Q.options["record-id"])??h(Q.options.id),K=h(Q.options.recordIds)??h(Q.options["record-ids"]),z=K?K.split(",").map((c)=>c.trim()).filter(Boolean):void 0,G=h(Q.options.sn)??h(Q.options.documentSn)??h(Q.options["document-sn"]),H=h(Q.options.sns)??h(Q.options["document-sns"]),W=H?H.split(",").map((c)=>c.trim()).filter(Boolean):void 0,X=s0(Q.options.limit),Z=h(Q.options.status),q=h(Q.options.startDate)??h(Q.options["start-date"]),V=h(Q.options.endDate)??h(Q.options["end-date"]);if(!J&&!z&&!G&&!W&&X===void 0)throw Error("Usage: seal-use webhook replay <recordId> [--sn <documentSN>] [--limit <n>] [--status <status>] [--webhook <idOrName>] [--source-corp <corpId>] [--target-corp <corpId>] [--dry-run]");let w=h(Q.options.sourceCorp)??h(Q.options["source-corp"])??h(Q.options.prodCorp)??h(Q.options["prod-corp"]),M=h(Q.options.targetCorp)??h(Q.options["target-corp"])??h(Q.options.testCorp)??h(Q.options["test-corp"]),F=G0(Q.options.force)===!0,{sourceCorp:N,targetCorp:O}=AP({sourceCorpId:w,targetCorpId:M,activeCorp:I,force:F},M1),D=N.id===I.id?U:await A1(N),P=O.id===I.id?U:await A1(O),T=h(Q.options.webhook)??h(Q.options.selector),B=h(Q.options.snSuffix)??h(Q.options["sn-suffix"]),E=h(Q.options.snPrefix)??h(Q.options["sn-prefix"]),C=h(Q.options.docIdSuffix)??h(Q.options["doc-id-suffix"]),b=h(Q.options.docIdPrefix)??h(Q.options["doc-id-prefix"]),x=G0(Q.options.dryRun)??G0(Q.options["dry-run"]),i=await Gz({query:{recordId:J,recordIds:z,sn:G,sns:W,limit:X,status:Z,startDate:q,endDate:V},sourceClient:D,targetClient:P,sourceCorp:N,targetCorp:O,webhookSelector:T,snPrefix:E,snSuffix:B,docIdPrefix:b,docIdSuffix:C,dr Line truncated
or: seal-use corps bind-test <testCorpId> --corp <prodCorpId> [--confirm] [--force]`);let J=M1(I),K=M1(Q);if(J.id===K.id)throw P4(`Cannot bind enterprise '${J.id}' to itself.`);if(J.prodCorpId&&J.prodCorpId!==K.id)throw P4(`Cannot use '${J.id}' as a production enterprise because it is already registered as a test enterprise for '${J.prodCorpId}'. Multi-tier chaining is not permitted.`);if(K.testCorpId&&K.testCorpId!==J.id)throw P4(`Cannot bind '${K.id}' as a test enterprise because it already has a bound test enterprise '${K.testCorpId}'. Multi-tier chaining is not permitted.`);let z=G0(U.options.force)===!0;if(J.testCorpId&&J.testCorpId!==K.id||K.prodCorpId&&K.prodCorpId!==J.id){if(!z)throw U$(`Enterprise binding conflict: production enterprise '${J.id}' is bound to '${J.testCorpId??"none"}', and test enterprise '${K.id}' is bound to '${K.prodCorpId??"none"}'. Overwriting an existing binding requires --force and --confirm.`,`seal-use corps bind-test ${J.id} ${K.id} --confirm --force`)}if(!(G0(U.options.confirm)===!0||G0(U.options.yes)===!0)){let X=z?" --force":"";throw U$(`Refusing to bind test enterprise '${K.name}' (${K.id}) to production enterprise '${J.name}' (${J.id}) without --confirm. Enterprise binding establishes 1-to-1 sync pairing and marks '${K.id}' as a test environment.`,`seal-use corps bind-test ${J.id} ${K.id} --confirm${X}`)}if(J.testCorpId&&J.testCorpId!==K.id)try{R9(J.testCorpId,{prodCorpId:void 0})}catch{}if(K.prodCorpId&&K.prodCorpId!==J.id)try{R9(K.prodCorpId,{testCorpId:void 0})}catch{}let H=R9(J.id,{environment:"production",testCorpId:K.id}),W=R9(K.id,{environment:"test",prodCorpId:J.id});return R0({success:!0,productionEnterprise:{id:H.id,name:H.name,environment:H.environment,testCorpId:H.testCorpId},testEnterprise:{id:W.id,name:W.name,environment:W.environment,prodCorpId:W.prodCorpId}}),!0}if($==="unbind-test"){let I=Y??h(U.options.corp),Q=M1(I);if(!Q.testCorpId&&!Q.prodCorpId)return R0({unbound:!1,message:`Enterprise '${Q.name}' (${Q.id}) does not have an active test enterprise binding.`}),!0;let J=Q.testCorpId?Q.id:Q.prodCorpId,K=Q.testCorpId?Q.testCorpId:Q.id;if(!(G0(U.options.confirm)===!0||G0(U.options.yes)===!0))throw U$(`Refusing to unbind production enterprise '${J}' and test enterprise '${K}' without --confirm.`,`seal-use corps unbind-test ${Q.id} --confirm`);R9(J,{testCorpId:void 0});try{R9(K,{prodCorpId:void 0})}catch{}return R0({success:!0,unboundProduction:J,unboundTest:K}),!0}return!1}var YS0=m(()=>{l$();O4();J$();q4();l1()});function cT($){let Y;try{Y=new URL($.trim())}catch{throw Error("Invalid Seal delegate link: expected a valid HTTPS URL")}if(Y.protocol!=="https:")throw Error("Invalid Seal delegate link: expected HTTPS");let U=Y.hostname.toLowerCase();if(!U.endsWith(US0))throw Error(`Invalid Seal delegate link: expected host ending in ${US0}, got ${U}`);let I=Y.pathname.replace(/\/+$/,"");if(I!==IS0)throw Error(`Invalid Seal delegate link: expected path ${IS0}, got ${I}`);let Q=Y.searchParams.get("token");if(!Q)throw Error("Invalid Seal delegate link: token query parameter is required");return{sealUrl:Y.origin,delegateToken:Q}}async function QS0($){let Y=typeof $==="string"?cT($):$;return(await T6(Y.sealUrl,void 0).post("api/v1/delegation/preview",{json:{token:Y.delegateToken}}).json()).data}async function JS0($){let Y=typeof $==="string"?cT($):$,U=Y.sealUrl,I=T6(U,void 0),Q=await I.post("api/v1/delegation/consume",{json:{token:Y.delegateToken}}),J=Q.headers.get("set-cookie")??"",K=typeof Q.headers.getSetCookie==="function"?Q.headers.getSetCookie():[J],z="";for(let M of K)if(M&&M.includes("session_token=")){z=(M.split(";")[0]??"").trim();break}let G;try{G=await I.get("api/auth/get-session",{headers:z?{cookie:z}:{}}).json()}catch{}let H=G?.session?.token;if(!H&&z){let M=z.match(/session_token=([^.;]+)/);if(M?.[1])H=decodeURIComponent(M[1])}if(!H)throw Error("Seal delegate exchange did not return a session token");let W=86400;if(G?.session?.expiresAt){let M=new Date(G.session.expiresAt).getTime();if(Number.isFinite(M)){let F=Math.floor((M-Date.now())/1000);if(F>0)W=F}}let Z=await T6(U,H).get("api/v1/auth/me").json(),q=Z.data&&typeof Z.data==="object"?Z.data:Z,V=q.user??G?.user??{},w=q.tenant??{};return{sealUrl:U,token:H,expiresIn:W,user:V,tenant:w}}function nT($){let Y=[],U=0,I="";try{let K=new URL($.trim()),z=K.hostname.toLowerCase(),G=K.pathname.replace(/\/+$/,"");if(z.endsWith(".ekuaibao.com")||z.endsWith(".hosecloud.com")||z==="ekuaibao.com"||z==="hosecloud.com")U+=40,I="host is Hose domain";if(G==="/web/thirdparty.html")U+=40,I+="; path is /web/thirdparty.html";if(K.searchParams.has("accessToken"))U+=10,I+="; has accessToken";if(K.searchParams.has("ekbCorpId"))U+=10,I+="; has ekbCorpId"}catch{U=0}if(U>0)Y.push({kind:"hose",score:U,reason:I});let Q=0,J="";try{let K=new URL($.trim()),z=K.hostname.toLowerCase(),G=K.pathname.replace(/\/+$/,"");if(z.endsWith(".sealai.cc"))Q+=40,J="host ends with .sealai.cc";if(G==="/delegate")Q+=40,J+="; path is /delegate";if( Line truncated
`,{mode:384}),{config:U,path:Q}}var Oo=m(()=>{l$();IP()});function No($){return new Date($).toISOString().replace(/\.\d{3}Z$/,"Z")}function dT($){let Y=new Date($);if(Number.isNaN(Y.getTime()))return $;return No(Y.getTime())}function Q5($){return typeof $==="string"&&$?$:void 0}function zk1($){return{headers:jd.parse($.headers),cookies:Cd.parse($.cookies)}}async function Gk1($,Y,U={}){let I=await o6(T6($,Y,U));return{user:I.user??{},tenant:I.tenant??{}}}async function KS0($){let Y=$.sealUrl.replace(/\/+$/,""),U=$.expiresIn??2592000,I=$.force===!0||$.verify===!1?!1:!0,Q=zk1($),J=I?await Gk1(Y,$.token,P6(Q)):void 0,K=GS0($,{token:$.token,sealUrl:Y,expiresIn:U,expiresAt:$.expiresAt,verify:I,remote:J,custom:Q}),z=$.tenantId??Q5(J?.tenant.id),G=$.tenantSlug??Q5(J?.tenant.tenantSlug);return{...K,verified:I,tenantId:z,tenantSlug:G}}function zS0($){let Y=Q5($.session.tenant.tenantSlug),U=Q5($.session.tenant.id),I=Y??U??"seal-delegate";return{...GS0({id:I,corpId:I,name:$.name,provider:"seal",overwrite:$.overwrite},{token:$.session.token,sealUrl:$.session.sealUrl,expiresIn:$.session.expiresIn,verify:!0,remote:{user:$.session.user,tenant:$.session.tenant}}),tenantId:U,tenantSlug:Y}}function GS0($,Y){let U=Y.remote?.user,I=Y.remote?.tenant,Q=$.tenantSlug??Q5(I?.tenantSlug),J=$.tenantId??Q5(I?.id),K=$.tenantName??Q5(I?.name),z=$.id??Q??J;if(!z)throw Error("Missing required JSON field: id. Seal whoami did not return tenantSlug or tenantId.");let G=Y.expiresAt?dT(Y.expiresAt):No(Date.now()+Y.expiresIn*1000),H=$.staffId??Q5(U?.providerUserId)??Q5(U?.id)??"seal",W=$.provider??Q5(U?.provider)??Q5(I?.providerConfig?.provider),X=$.corpId??Q??J??z,Z={id:z,name:$.name??K??z,environment:"production",seal:{url:Y.sealUrl,tenantSlug:Q,headers:Y.custom?.headers,cookies:Y.custom?.cookies,endpoints:{approvalStylePreferences:"api/v1/agent/ai-approval/config"}},source:{type:"seal",token:Y.token,sealUrl:Y.sealUrl,expiresIn:Y.expiresIn,expiresAt:G,staffId:H,corpId:X,tenantId:J,tenantSlug:Q,tenantName:K,providerUserId:Q5(U?.providerUserId),provider:W},auth:{refreshTtl:300}};return kq(Z,{overwrite:$.overwrite===!0})}var Do=m(()=>{Oo();IP();f6();H4()});async function nz($){let[Y,U]=await Promise.all([D10($),A1($)]),I=await o6(U);return{...Y,tenantId:I.tenant.id,tenantSlug:I.tenant.tenantSlug??Y.tenantSlug,tenantName:I.tenant.name,raw:{...typeof Y.raw==="object"&&Y.raw!==null?Y.raw:{},user:{id:I.user.id,name:I.user.name,isAdmin:I.user.isAdmin,providerUserId:I.user.providerUserId,hosecloudStaff:I.user.hosecloudStaff},tenant:I.tenant}}}var pT=m(()=>{f6();Lg();H4()});async function HS0($){let Y=await sQ($.appKey,$.appSecurity,$.domain),U=await BM(Y.domain,Y.openapiToken).catch(()=>[]);return{...Y,roleCount:U.reduce((I,Q)=>I+Q.roleDefs.length,0),roleGroups:U.map((I)=>({id:I.id,name:I.name,roleDefs:I.roleDefs.map((Q)=>({id:Q.id,name:Q.name,sourceType:Q.sourceType}))}))}}async function WS0($){let Y=await sQ($.appKey,$.appSecurity,$.domain),U=$.role??$.roleDefId??"admin",I=await BM(Y.domain,Y.openapiToken),Q,J;for(let G of I){for(let H of G.roleDefs)if(H.id===U||H.id===`${Y.corpId}:${U}`){Q=H.id,J=H.name;break}if(Q)break}if(!Q&&(U==="admin"||U==="主管理员"))for(let G of I){for(let H of G.roleDefs)if(H.id.endsWith(":admin")||H.name==="主管理员"){Q=H.id,J=H.name;break}if(Q)break}if(!Q)for(let G of I){for(let H of G.roleDefs)if(H.name.toLowerCase().includes(U.toLowerCase())){Q=H.id,J=H.name;break}if(Q)break}if(!Q)throw Error(`Role not found matching query: '${U}'. Run 'seal-use corps probe-hose' to view all available roles.`);let K=await Xg(Y.domain,Y.openapiToken,Q),z=await Zg(Y.domain,Y.openapiToken,K.staffs);return{domain:Y.domain,corpId:Y.corpId,corpName:Y.corpName??Y.corpId,roleId:Q,roleName:J,staffs:z}}async function xq($){let Y=$.domain,U=$.staffId??$.proxyStaffBizId,I=$.force===!0,Q=I||$.verify===!1?!1:!0,J=Y,K=$.corpId??$.corporationId,z=$.name,G;if(!J||!K||!U){let V=await sQ($.appKey,$.appSecurity,Y);J=V.domain,K=K??V.corpId,z=z??V.corpName,G=V.openapiToken}let H=U;if(!H&&G&&J){let V=$.role??"admin",w=await BM(J,G).catch(()=>[]),M;for(let F of w){for(let N of F.roleDefs)if(N.id.endsWith(`:${V}`)||N.name===V||N.id===V){M=N.id;break}if(M)break}if(!M)M=w.find((F)=>F.roleDefs.some((N)=>N.id.endsWith(":admin")))?.roleDefs.find((F)=>F.id.endsWith(":admin"))?.id;if(M){let F=await Xg(J,G,M).catch(()=>({staffs:[]})),N=await Zg(J,G,F.staffs).catch(()=>[]);if($.staffName||$.staffPhone){let O=N.filter((D)=>{if($.staffName&&D.name!==$.staffName&&!D.name.includes($.staffName))return!1;if($.staffPhone&&(!D.cellphone||!D.cellphone.includes($.staffPhone)))return!1;return!0});if(O.length===1&&O[0])H=O[0].id;else if(O.length>1)throw Error(`Multiple staff members matched '${$.staffName??$.staffPhone}': ${O.map((D)=>`${D.name}(${D.id})`).join(", ")}. Please specify exact staffId.`);else throw Error(`No staff member found matching '${$.staffName??$.staffPhone}' under role ${M}. Run 'seal-use corps hose-staffs' to view candidates.`)}else if(!I){let O=N.map( Line truncated
`+"\uD83D\uDCA1 说明:此能力专属于合思 (Hose) 子域,用于将临时会话提权为标准 OpenAPI 开发者接入。需要企业管理员已在合思开放平台创建应用并生成 appKey/appSecurity。",I);if(U.keyId||U.appKey){let Q=$.find((J)=>U.keyId&&J.id===U.keyId||U.appKey&&J.appKey===U.appKey);if(!Q)throw new iI(`指定的合思密钥不存在,请从上述候选列表中选择正确的 appKey 或 keyId。
`+`当前企业存在以下 ${$.length} 套候选密钥:
`+$.map((Q)=>` • "${Q.name||"未命名应用"}" (appKey: ${Q.appKey}, keyId: ${Q.id}, 状态: ${Q.active?"\uD83D\uDFE2 启用":"⚪ 停用"})`).join(`
`),`${z} --app-key ${$[0].appKey}`);return I}if($.length===1)return $[0];throw new bz(`
`+$.map((J)=>` • "${J.name||"未命名应用"}" (appKey: ${J.appKey}, keyId: ${J.id}, 状态: ${J.active?"\uD83D\uDFE2 启用":"⚪ 停用"})`).join(`
`),`${I} --app-key ${$[0].appKey}`);return Q}if($.length===1)return $[0];throw new iI(`
ℹ️ [合思子域提权] 合思企业 [${Y}] 存在多套 (${$.length} 套) OpenAPI 应用密钥凭据:
${$.map((I,Q)=>` [${Q+1}] "${I.name||"未命名应用"}" (appKey: ${I.appKey}, keyId: ${I.id}, 状态: ${I.active?"\uD83D\uDFE2 启用":"⚪ 停用"})`).join(`
${$.map((Q,J)=>` [${J+1}] "${Q.name||"未命名应用"}" (appKey: ${Q.appKey}, keyId: ${Q.id}, 状态: ${Q.active?"\uD83D\uDFE2 启用":"⚪ 停用"})`).join(`
`)}
\uD83D\uDC49 为确保权限提权绑定正确的业务应用,请显式指定要使用的密钥套件:
在命令后追加 --app-key <key> 或 --key-id <id> 参数。
`,`${z} --app-key ${$[0].appKey}`)}async function Ev0($){let Y=await Kg($.link),U=jv0(Y.keys,Y.corpId,$,'seal-use corps add-link "<url>" --elevate-hose');if($.dryRun)return{result:Y,selectedKey:U,dryRun:!0};let z=await vq({domain:Y.baseUrl,appKey:U.appKey,appSecurity:U.appSecurity,corpId:Y.corpId,name:$.name??Y.corpName,staffId:Y.staffId,overwrite:$.overwrite,force:$.force});return{result:Y,selectedKey:U,saved:z,dryRun:!1}}async function Cv0($){let Y=await Kg($.link);if(!$.save)return{result:Y,reveal:$.reveal===!0};let U=jv0(Y.keys,Y.corpId,$,'seal-use corps hose-extract-keys "<url>" --save'),z=await vq({domain:Y.baseUrl,appKey:U.appKey,appSecurity:U.appSecurity,corpId:Y.corpId,name:$.name??Y.corpName,staffId:Y.staffId,overwrite:$.overwrite,force:$.force});return{result:Y,selectedKey:U,saved:z,reveal:$.reveal===!0}}function Rv0($,Y){return{id:$.id,name:$.name||"-",appKey:$.appKey,appSecurity:Y?$.appSecurity:_H($.appSecurity),active:$.active,createTime:$.createTime,updateTime:$.updateTime}}var bz;var _v0=m(()=>{E$();bT();bz=class bz extends Error{nextAction;constructor($,Y){super($);this.name="HoseKeySelectionError",this.nextAction=Y}}});function vv0($){if(!$)return;if($.length<=8)return"****";return`${$.slice(0,4)}...${$.slice(-4)}`}function hv0($){if($.source.type==="hose")return y7($,$.source);return $.seal.url??$.source.sealUrl}function Sv0($){if($.type==="hose"){let Y=$.appKey??$.key;return{type:"hose",provider:$.provider??"hosecloud",domain:$.domain,corpId:$.corpId,staffId:$.staffId,appKey:vv0(Y),hasAppSecurity:Boolean($.appSecurity??$.password),hasCloseToken:Boolean($.closeToken),closeTokenExpiresIn:$.closeToken?$.expiresIn:void 0,closeTokenExpiresAt:$.closeToken?$.expiresAt:void 0,credentialMode:$.closeToken?"web-session":"persistent",sealUrl:$.sealUrl}}if($.type==="seal")return{type:"seal",provider:$.provider??"seal",tenantId:$.tenantId,tenantSlug:$.tenantSlug,tenantName:$.tenantName,providerUserId:$.providerUserId,staffId:$.staffId,corpId:$.corpId,sealUrl:$.sealUrl,hasToken:Boolean($.token),tokenMasked:vv0($.token),expiresIn:$.expiresIn,expiresAt:$.expiresAt};throw Error(`Unsupported enterprise source type: ${$.type}`)}function Ko($){if(!$)return"未绑定手机";let Y=$.trim();if(Y.length===11)return`${Y.slice(0,3)}****${Y.slice(7)}`;if(Y.length>=7)return`${Y.slice(0,3)}****${Y.slice(-4)}`;if(Y.length>4)return`${Y.slice(0,2)}****${Y.slice(-2)}`;return Y}var iT=m(()=>{E$()});async function gv0($,Y,U){if($==="probe-hose"){let z=B8(U.json),I=await Av0({appKey:o3(z,"appKey"),appSecurity:o3(z,"appSecurity"),domain:v6(z,"domain")});return R0({domain:I.domain,corpId:I.corpId,name:I.corpName??I.corpId,roleCount:I.roleCount,roleGroups:I.roleGroups}),!0}if($==="hose-staffs"){let z=B8(U.json),I=await Bv0({appKey:o3(z,"appKey"),appSecurity:o3(z,"appSecurity"),domain:v6(z,"domain"),role:v6(z,"role"),roleDefId:v6(z,"roleDefId")});return R0({domain:I.domain,corpId:I.corpId,corpName:I.corpName,roleId:I.roleId,roleName:I.roleName,count:I.staffs.length,staffs:I.staffs.map((Q)=>({id:Q.id,name:Q.name,cellphone:Ko(Q.cellphone),active:Q.active,authState:Q.authState,userId:Q.userId,email:Q.email}))}),!0}if($==="add-hose-persistent"||$==="add-hose"){let I={...B8(U.json),...U.options.staffName?{staffName:S(U.options.staffName)}:{},...U.options["staff-name"]?{staffName:S(U.options["staff-name"])}:{},...U.options.staffPhone?{staffPhone:S(U.options.staffPhone)}:{},...U.options["staff-phone"]?{staffPhone:S(U.options["staff-phone"])}:{},...U.options.name?{name:S(U.options.name)}:{},...U.options.domain?{domain:S(U.options.domain)}:{},...U.options.corpId?{corpId:S(U.options.corpId)}:{},...U.options["corp-id"]?{corpId:S(U.options["corp-id"])}:{},...U.options.appKey?{appKey:S(U.options.appKey)}:{},...U.options["app-key"]?{appKey:S(U.options["app-key"])}:{},...U.options.appSecurity?{appSecurity:S(U.options.appSecurity)}:{},...U.options["app-security"]?{appSecurity:S(U.options["app-security"])}:{},...U.options.force!==void 0?{force:G0(U.options.force)}:{},...U.options.overwrite!==void 0?{overwrite:G0(U.options.overwrite)}:{}},Q=await vq({...I,appKey:o3(I,"appKey"),appSecurity:o3(I,"appSecurity")});return R0({id:Q.config.id,name:Q.config.name,corpId:Q.config.source.type==="hose"?Q.config.source.corpId:void 0,domain:Q.domain,staffId:Q.staffId,verified:Q.verified,path:Q.path}),!0}if($==="add-hose-web-session"){let I={...B8(U.json),...U.options.name?{name:S(U.options.name)}:{},...U.options.domain?{baseUrl:S(U.options.domain)}:{},...U.options["base-url"]?{baseUrl:S(U.options["base-url"])}:{},...U.options.corpId?{corpId:S(U.options.corpId)}:{},...U.options["corp-id"]?{corpId:S(U.options["corp-id"])}:{},...U.options.staffId?{staffId:S(U.options.staffId)}:{},...U.options["staff-id"]?{staffId:S(U.options["staff-id"])}:{},...U.options.accessToken?{accessToken:S(U.options.accessToken)}:{},...U.options["access-token"]?{accessToken:S(U.options["access-token"])}:{},...U.options.overwrite!==void 0?{overwrite:G0(U.options.overwrite)}:{},...U.optio Line truncated
`,`${I} --app-key ${$[0].appKey}`)}async function VS0($){let Y=await Vg($.link),U=qS0(Y.keys,Y.corpId,$,'seal-use corps add-link "<url>" --elevate-hose');if($.dryRun)return{result:Y,selectedKey:U,dryRun:!0};let I=await xq({domain:Y.baseUrl,appKey:U.appKey,appSecurity:U.appSecurity,corpId:Y.corpId,name:$.name??Y.corpName,staffId:Y.staffId,overwrite:$.overwrite,force:$.force});return{result:Y,selectedKey:U,saved:I,dryRun:!1}}async function LS0($){let Y=await Vg($.link);if(!$.save)return{result:Y,reveal:$.reveal===!0};let U=qS0(Y.keys,Y.corpId,$,'seal-use corps hose-extract-keys "<url>" --save'),I=await xq({domain:Y.baseUrl,appKey:U.appKey,appSecurity:U.appSecurity,corpId:Y.corpId,name:$.name??Y.corpName,staffId:Y.staffId,overwrite:$.overwrite,force:$.force});return{result:Y,selectedKey:U,saved:I,reveal:$.reveal===!0}}function FS0($,Y){return{id:$.id,name:$.name||"-",appKey:$.appKey,appSecurity:Y?$.appSecurity:hH($.appSecurity),active:$.active,createTime:$.createTime,updateTime:$.updateTime}}var iI;var wS0=m(()=>{m8();lT();iI=class iI extends Error{nextAction;constructor($,Y){super($);this.name="HoseKeySelectionError",this.nextAction=Y}}});function MS0($){if(!$)return;if($.length<=8)return"****";return`${$.slice(0,4)}...${$.slice(-4)}`}function OS0($){if($.source.type==="hose")return f7($,$.source);return $.seal.url??$.source.sealUrl}function NS0($){if($.type==="hose"){let Y=$.appKey??$.key;return{type:"hose",provider:$.provider??"hosecloud",domain:$.domain,corpId:$.corpId,staffId:$.staffId,appKey:MS0(Y),hasAppSecurity:Boolean($.appSecurity??$.password),hasCloseToken:Boolean($.closeToken),closeTokenExpiresIn:$.closeToken?$.expiresIn:void 0,closeTokenExpiresAt:$.closeToken?$.expiresAt:void 0,credentialMode:$.closeToken?"web-session":"persistent",sealUrl:$.sealUrl}}if($.type==="seal")return{type:"seal",provider:$.provider??"seal",tenantId:$.tenantId,tenantSlug:$.tenantSlug,tenantName:$.tenantName,providerUserId:$.providerUserId,staffId:$.staffId,corpId:$.corpId,sealUrl:$.sealUrl,hasToken:Boolean($.token),tokenMasked:MS0($.token),expiresIn:$.expiresIn,expiresAt:$.expiresAt};throw Error(`Unsupported enterprise source type: ${$.type}`)}function Bo($){if(!$)return"未绑定手机";let Y=$.trim();if(Y.length===11)return`${Y.slice(0,3)}****${Y.slice(7)}`;if(Y.length>=7)return`${Y.slice(0,3)}****${Y.slice(-4)}`;if(Y.length>4)return`${Y.slice(0,2)}****${Y.slice(-2)}`;return Y}var oT=m(()=>{m8()});async function DS0($,Y,U){if($==="probe-hose"){let I=E8(U.json),Q=await HS0({appKey:a3(I,"appKey"),appSecurity:a3(I,"appSecurity"),domain:h6(I,"domain")});return R0({domain:Q.domain,corpId:Q.corpId,name:Q.corpName??Q.corpId,roleCount:Q.roleCount,roleGroups:Q.roleGroups}),!0}if($==="hose-staffs"){let I=E8(U.json),Q=await WS0({appKey:a3(I,"appKey"),appSecurity:a3(I,"appSecurity"),domain:h6(I,"domain"),role:h6(I,"role"),roleDefId:h6(I,"roleDefId")});return R0({domain:Q.domain,corpId:Q.corpId,corpName:Q.corpName,roleId:Q.roleId,roleName:Q.roleName,count:Q.staffs.length,staffs:Q.staffs.map((J)=>({id:J.id,name:J.name,cellphone:Bo(J.cellphone),active:J.active,authState:J.authState,userId:J.userId,email:J.email}))}),!0}if($==="add-hose-persistent"||$==="add-hose"){let Q={...E8(U.json),...U.options.staffName?{staffName:h(U.options.staffName)}:{},...U.options["staff-name"]?{staffName:h(U.options["staff-name"])}:{},...U.options.staffPhone?{staffPhone:h(U.options.staffPhone)}:{},...U.options["staff-phone"]?{staffPhone:h(U.options["staff-phone"])}:{},...U.options.name?{name:h(U.options.name)}:{},...U.options.domain?{domain:h(U.options.domain)}:{},...U.options.corpId?{corpId:h(U.options.corpId)}:{},...U.options["corp-id"]?{corpId:h(U.options["corp-id"])}:{},...U.options.appKey?{appKey:h(U.options.appKey)}:{},...U.options["app-key"]?{appKey:h(U.options["app-key"])}:{},...U.options.appSecurity?{appSecurity:h(U.options.appSecurity)}:{},...U.options["app-security"]?{appSecurity:h(U.options["app-security"])}:{},...U.options.force!==void 0?{force:G0(U.options.force)}:{},...U.options.overwrite!==void 0?{overwrite:G0(U.options.overwrite)}:{}},J=await xq({...Q,appKey:a3(Q,"appKey"),appSecurity:a3(Q,"appSecurity")});return R0({id:J.config.id,name:J.config.name,corpId:J.config.source.type==="hose"?J.config.source.corpId:void 0,domain:J.domain,staffId:J.staffId,verified:J.verified,path:J.path}),!0}if($==="add-hose-web-session"){let Q={...E8(U.json),...U.options.name?{name:h(U.options.name)}:{},...U.options.domain?{baseUrl:h(U.options.domain)}:{},...U.options["base-url"]?{baseUrl:h(U.options["base-url"])}:{},...U.options.corpId?{corpId:h(U.options.corpId)}:{},...U.options["corp-id"]?{corpId:h(U.options["corp-id"])}:{},...U.options.staffId?{staffId:h(U.options.staffId)}:{},...U.options["staff-id"]?{staffId:h(U.options["staff-id"])}:{},...U.options.accessToken?{accessToken:h(U.options.accessToken)}:{},...U.options["access-token"]?{accessToken:h(U.options["access-token"])}:{},...U.options.overwrite!==void 0?{overwrite:G0(U.options.overwrite)}:{},...U.optio Line truncated
`);else console.error(`⚠️ [合思子域提权] 正在以明文展示合思 (Hose) appSecurity 接入密码,请妥善保管敏感凭据。
`);R0({provider:"hose",capability:"privilege-elevation",corpId:z.corpId,corpName:z.corpName??z.corpId,baseUrl:z.baseUrl,staffId:z.staffId,keyCount:z.keys.length,keys:z.keys.map((Q)=>Rv0(Q,I))})}async function cT($,Y){let U=M1($),z=Y.reveal===!0;if(U.source.type!=="hose")throw new W4(`【合思子域专享能力】当前企业「${U.name}」(id: ${U.id}) 为原生 Seal (${U.source.type}) 租户,非合思 (Hose/合思云/易快报) 渠道企业。
`+"OpenAPI 密钥查询与提权能力专属于合思生态租户(用于从合思协助链接或合思凭据中提取开发者密钥提升权限等级),非合思渠道企业不支持此能力。",2);let I=U.source.appKey??U.source.key,Q=U.source.appSecurity??U.source.password;if(!z)console.error(`\uD83D\uDCA1 [合思子域] 接入密码默认脱敏,附加 --reveal (或 -r) 可查看完整 appSecurity 明文。
`);R0({provider:"hose",capability:"privilege-elevation",corpId:I.corpId,corpName:I.corpName??I.corpId,baseUrl:I.baseUrl,staffId:I.staffId,keyCount:I.keys.length,keys:I.keys.map((J)=>FS0(J,Q))})}async function rT($,Y){let U=M1($),I=Y.reveal===!0;if(U.source.type!=="hose")throw new X4(`【合思子域专享能力】当前企业「${U.name}」(id: ${U.id}) 为原生 Seal (${U.source.type}) 租户,非合思 (Hose/合思云/易快报) 渠道企业。
`+"OpenAPI 密钥查询与提权能力专属于合思生态租户(用于从合思协助链接或合思凭据中提取开发者密钥提升权限等级),非合思渠道企业不支持此能力。",2);let Q=U.source.appKey??U.source.key,J=U.source.appSecurity??U.source.password;if(!I)console.error(`\uD83D\uDCA1 [合思子域] 接入密码默认脱敏,附加 --reveal (或 -r) 可查看完整 appSecurity 明文。
`);else console.error(`⚠️ [合思子域] 正在以明文展示合思 appSecurity 接入密码,请妥善保管敏感凭据。
`);R0({provider:"hose",capability:"privilege-elevation",corpId:U.id,corpName:U.name,domain:U.source.domain,staffId:U.source.staffId,appKey:I??"-",appSecurity:Q?z?Q:_H(Q):"-",active:!0})}var yv0=m(()=>{E$();zo();Jo();Tv0();bT();_v0();O8();O4();Z4();m1();iT()});var xv0,fv0,nT,kv0,o4;var Y5=m(()=>{xv0=/^[\uD800-\uDBFF]$/,fv0=/^[\uDC00-\uDFFF]$/,nT=/[\uD800-\uDBFF][\uDC00-\uDFFF]/g;(function($){$[$.Unknown=0.0000000000001]="Unknown",$[$.Rule=0.000000000001]="Rule",$[$.DICT=0.00000002]="DICT",$[$.Surname=1]="Surname",$[$.Custom=1]="Custom"})(kv0||(kv0={}));o4={Normal:1,Surname:10,Custom:100}});function e2($){var Y;return $.length-(((Y=$.match(nT))===null||Y===void 0?void 0:Y.length)||0)}function O$($){if(nT.lastIndex=0,!nT.test($))return $.split("");let Y=[],U=0;while(U<$.length){let z=$[U];if(xv0.test(z)&&fv0.test($[U+1]))Y.push($.substring(U,U+2)),U+=2;else Y.push(z),U+=1}return Y}class iK{constructor(){this.NumberDICT=[],this.StringDICT=new Map}get($){if($.length>1)return this.StringDICT.get($);else{let Y=$.charCodeAt(0);return this.NumberDICT[Y]}}set($,Y){if($.length>1)this.StringDICT.set($,Y);else{let U=$.charCodeAt(0);this.NumberDICT[U]=Y}}clear(){this.NumberDICT=[],this.StringDICT.clear()}}var k9=m(()=>{Y5()});function dg1(){let $={零一:"líng yī",〇一:"líng yī",十一:"shí yī",一十:"yī shí",第一:"dì yī",一十一:"yī shí yī"};for(let Y in uv0)for(let U in bv0){let z=`${Y}${U}`,I=`${uv0[Y]} ${bv0[U]}`;$[z]=I}return $}var cv0,nv0,pv0,dv0,mv0,uv0,bv0,iv0,lv0,Go,ov0,rv0;var Ho=m(()=>{Y5();k9();cv0=["zh","ch","sh","z","c","s","b","p","m","f","d","t","n","l","g","k","h","j","q","x","r","y","w",""],nv0=["j","q","x"],pv0=["uān","uán","uǎn","uàn","uan","uē","ué","uě","uè","ue","ūn","ún","ǔn","ùn","un","ū","ú","ǔ","ù","u"],dv0={uān:"üān",uán:"üán",uǎn:"üǎn",uàn:"üàn",uan:"üan",uē:"üē",ué:"üé",uě:"üě",uè:"üè",ue:"üe",ūn:"ǖn",ún:"ǘn",ǔn:"ǚn",ùn:"ǜn",un:"ün",ū:"ǖ",ú:"ǘ",ǔ:"ǚ",ù:"ǜ",u:"ü"},mv0=["ia","ian","iang","iao","ie","iu","iong","ua","uai","uan","uang","ue","ui","uo","üan","üe","van","ve"],uv0={一:"yì",二:"èr",三:"sān",四:"sì",五:"wǔ",六:"liù",七:"qī",八:"bā",九:"jiǔ",十:"shí",百:"bǎi",千:"qiān",万:"wàn",亿:"yì",单:"dān",两:"liǎng",双:"shuāng",多:"duō",几:"jǐ",十一:"shí yī",零一:"líng yī",第一:"dì yī",一十:"yī shí",一十一:"yī shí yī"},bv0={重:"chóng",行:"háng",斗:"dǒu",更:"gēng"};iv0=dg1(),lv0=Object.keys(iv0).map(($)=>({zh:$,pinyin:iv0[$],probability:0.000000000001,length:e2($),priority:o4.Normal,dict:Symbol("rule")})),Go={不:{bú:[4]},一:{yí:[4],yì:[1,2,3]}},ov0={不:["的","而","之","后","也","还","地"],一:["的","而","之","后","也","还","是"]},rv0=Object.keys(Go)});var sv0,_5;var pT=m(()=>{k9();sv0={"bǎng páng pāng":["膀"],líng:["〇","伶","凌","刢","囹","坽","夌","姈","婈","孁","岺","彾","掕","昤","朎","柃","棂","櫺","欞","泠","淩","澪","灵","燯","爧","狑","玲","琌","瓴","皊","砱","祾","秢","竛","笭","紷","綾","绫","羐","羚","翎","聆","舲","苓","菱","蓤","蔆","蕶","蛉","衑","裬","詅","跉","軨","輘","酃","醽","鈴","錂","铃","閝","陵","零","霊","霗","霛","霝","靈","駖","魿","鯪","鲮","鴒","鸰","鹷","麢","齡","齢","龄","龗","㥄"],yī:["一","乊","伊","依","医","吚","咿","噫","壱","壹","夁","嫛","嬄","弌","揖","撎","檹","毉","洢","渏","漪","瑿","畩","祎","禕","稦","繄","蛜","衤","譩","辷","郼","醫","銥","铱","鷖","鹥","黟","黳"],"dīng zhēng":["丁"],"kǎo qiǎo yú":["丂"],qī:["七","倛","僛","凄","嘁","墄","娸","悽","慼","慽","戚","捿","柒","桤","桼","棲","榿","欺","沏","淒","漆","紪","緀","萋","褄","諆","迉","郪","鏚","霋","魌","鶈"],shàng:["丄","尙","尚","恦","緔","绱"],xià:["丅","下","乤","圷","夏","夓","懗","梺","疜","睱","罅","鎼","鏬"],hǎn:["丆","喊","浫","罕","豃","㘎"],"wàn mò":["万"],zhàng:["丈","仗","墇","嶂","帐","帳","幛","扙","杖","涱","痮","瘬","瘴","瞕","粀","胀","脹","賬","账","障"],sān:["三","厁","叁","弎","毵","毶","毿","犙","鬖"],"shàng shǎng shang":["上"],"qí jī":["丌","其","奇"],"bù fǒu":["不"],"yǔ yù yú":["与"],miǎn:["丏","偭","免","冕","勉","勔","喕","娩","愐","汅","沔","湎","睌","緬","缅","腼","葂","靦","鮸","\uD867\uDF83"],gài:["丐","乢","匃","匄","戤","概","槩","槪","溉","漑","瓂","葢","鈣","钙","\uD872\uDFBF"],chǒu:["丑","丒","侴","吜","杽","瞅","矁","醜","魗"],zhuān:["专","叀","嫥","専","專","瑼","甎","砖","磗","磚","蟤","諯","鄟","顓","颛","鱄","䏝"],"qiě jū":["且"],pī:["丕","伓","伾","噼","坯","岯","憵","批","披","炋","狉","狓","砒","磇","礔","礕","秛","秠","耚","豾","邳","鈚","鉟","銔","錃","錍","霹","駓","髬","魾","\uD873\uDCF5"],shì:["世","丗","亊","事","仕","侍","冟","势","勢" Line truncated
`);R0({provider:"hose",capability:"privilege-elevation",corpId:U.id,corpName:U.name,domain:U.source.domain,staffId:U.source.staffId,appKey:Q??"-",appSecurity:J?I?J:hH(J):"-",active:!0})}var BS0=m(()=>{m8();Mo();Do();ZS0();lT();wS0();J$();O4();q4();l1();oT()});var PS0,TS0,sT,AS0,r4;var J5=m(()=>{PS0=/^[\uD800-\uDBFF]$/,TS0=/^[\uDC00-\uDFFF]$/,sT=/[\uD800-\uDBFF][\uDC00-\uDFFF]/g;(function($){$[$.Unknown=0.0000000000001]="Unknown",$[$.Rule=0.000000000001]="Rule",$[$.DICT=0.00000002]="DICT",$[$.Surname=1]="Surname",$[$.Custom=1]="Custom"})(AS0||(AS0={}));r4={Normal:1,Surname:10,Custom:100}});function $Y($){var Y;return $.length-(((Y=$.match(sT))===null||Y===void 0?void 0:Y.length)||0)}function T$($){if(sT.lastIndex=0,!sT.test($))return $.split("");let Y=[],U=0;while(U<$.length){let I=$[U];if(PS0.test(I)&&TS0.test($[U+1]))Y.push($.substring(U,U+2)),U+=2;else Y.push(I),U+=1}return Y}class dz{constructor(){this.NumberDICT=[],this.StringDICT=new Map}get($){if($.length>1)return this.StringDICT.get($);else{let Y=$.charCodeAt(0);return this.NumberDICT[Y]}}set($,Y){if($.length>1)this.StringDICT.set($,Y);else{let U=$.charCodeAt(0);this.NumberDICT[U]=Y}}clear(){this.NumberDICT=[],this.StringDICT.clear()}}var f9=m(()=>{J5()});function Zk1(){let $={零一:"líng yī",〇一:"líng yī",十一:"shí yī",一十:"yī shí",第一:"dì yī",一十一:"yī shí yī"};for(let Y in ES0)for(let U in jS0){let I=`${Y}${U}`,Q=`${ES0[Y]} ${jS0[U]}`;$[I]=Q}return $}var RS0,_S0,vS0,SS0,hS0,ES0,jS0,CS0,gS0,Ao,yS0,kS0;var Po=m(()=>{J5();f9();RS0=["zh","ch","sh","z","c","s","b","p","m","f","d","t","n","l","g","k","h","j","q","x","r","y","w",""],_S0=["j","q","x"],vS0=["uān","uán","uǎn","uàn","uan","uē","ué","uě","uè","ue","ūn","ún","ǔn","ùn","un","ū","ú","ǔ","ù","u"],SS0={uān:"üān",uán:"üán",uǎn:"üǎn",uàn:"üàn",uan:"üan",uē:"üē",ué:"üé",uě:"üě",uè:"üè",ue:"üe",ūn:"ǖn",ún:"ǘn",ǔn:"ǚn",ùn:"ǜn",un:"ün",ū:"ǖ",ú:"ǘ",ǔ:"ǚ",ù:"ǜ",u:"ü"},hS0=["ia","ian","iang","iao","ie","iu","iong","ua","uai","uan","uang","ue","ui","uo","üan","üe","van","ve"],ES0={一:"yì",二:"èr",三:"sān",四:"sì",五:"wǔ",六:"liù",七:"qī",八:"bā",九:"jiǔ",十:"shí",百:"bǎi",千:"qiān",万:"wàn",亿:"yì",单:"dān",两:"liǎng",双:"shuāng",多:"duō",几:"jǐ",十一:"shí yī",零一:"líng yī",第一:"dì yī",一十:"yī shí",一十一:"yī shí yī"},jS0={重:"chóng",行:"háng",斗:"dǒu",更:"gēng"};CS0=Zk1(),gS0=Object.keys(CS0).map(($)=>({zh:$,pinyin:CS0[$],probability:0.000000000001,length:$Y($),priority:r4.Normal,dict:Symbol("rule")})),Ao={不:{bú:[4]},一:{yí:[4],yì:[1,2,3]}},yS0={不:["的","而","之","后","也","还","地"],一:["的","而","之","后","也","还","是"]},kS0=Object.keys(Ao)});var xS0,h5;var aT=m(()=>{f9();xS0={"bǎng páng pāng":["膀"],líng:["〇","伶","凌","刢","囹","坽","夌","姈","婈","孁","岺","彾","掕","昤","朎","柃","棂","櫺","欞","泠","淩","澪","灵","燯","爧","狑","玲","琌","瓴","皊","砱","祾","秢","竛","笭","紷","綾","绫","羐","羚","翎","聆","舲","苓","菱","蓤","蔆","蕶","蛉","衑","裬","詅","跉","軨","輘","酃","醽","鈴","錂","铃","閝","陵","零","霊","霗","霛","霝","靈","駖","魿","鯪","鲮","鴒","鸰","鹷","麢","齡","齢","龄","龗","㥄"],yī:["一","乊","伊","依","医","吚","咿","噫","壱","壹","夁","嫛","嬄","弌","揖","撎","檹","毉","洢","渏","漪","瑿","畩","祎","禕","稦","繄","蛜","衤","譩","辷","郼","醫","銥","铱","鷖","鹥","黟","黳"],"dīng zhēng":["丁"],"kǎo qiǎo yú":["丂"],qī:["七","倛","僛","凄","嘁","墄","娸","悽","慼","慽","戚","捿","柒","桤","桼","棲","榿","欺","沏","淒","漆","紪","緀","萋","褄","諆","迉","郪","鏚","霋","魌","鶈"],shàng:["丄","尙","尚","恦","緔","绱"],xià:["丅","下","乤","圷","夏","夓","懗","梺","疜","睱","罅","鎼","鏬"],hǎn:["丆","喊","浫","罕","豃","㘎"],"wàn mò":["万"],zhàng:["丈","仗","墇","嶂","帐","帳","幛","扙","杖","涱","痮","瘬","瘴","瞕","粀","胀","脹","賬","账","障"],sān:["三","厁","叁","弎","毵","毶","毿","犙","鬖"],"shàng shǎng shang":["上"],"qí jī":["丌","其","奇"],"bù fǒu":["不"],"yǔ yù yú":["与"],miǎn:["丏","偭","免","冕","勉","勔","喕","娩","愐","汅","沔","湎","睌","緬","缅","腼","葂","靦","鮸","\uD867\uDF83"],gài:["丐","乢","匃","匄","戤","概","槩","槪","溉","漑","瓂","葢","鈣","钙","\uD872\uDFBF"],chǒu:["丑","丒","侴","吜","杽","瞅","矁","醜","魗"],zhuān:["专","叀","嫥","専","專","瑼","甎","砖","磗","磚","蟤","諯","鄟","顓","颛","鱄","䏝"],"qiě jū":["且"],pī:["丕","伓","伾","噼","坯","岯","憵","批","披","炋","狉","狓","砒","磇","礔","礕","秛","秠","耚","豾","邳","鈚","鉟","銔","錃","錍","霹","駓","髬","魾","\uD873\uDCF5"],shì:["世","丗","亊","事","仕","侍","冟","势","勢" Line truncated
`+`\uD83D\uDC49 查看全部请添加: seal-use corps list --all
`+"\uD83D\uDC49 检索指定企业请使用: seal-use corps search <keyword>")}return R0(F.map((N)=>({id:N.id,name:N.name,environment:N.environment??"production",sourceType:N.source.type,provider:N.source.provider??N.source.type,staffId:N.source.staffId,testCorpId:N.testCorpId,prodCorpId:N.prodCorpId,current:N.id===H}))),!0}if($==="get"||$==="show"){let z=Y??S(U.options.corp);if(!z)throw h4("Usage: seal-use corps get <corpId>");let I=M1(z),Q=Tp(I.id),J=hv0(I);return R0({id:I.id,name:I.name,environment:I.environment??"production",configFile:Q,seal:{url:J,tenantSlug:I.seal.tenantSlug??I.source.tenantSlug,customHeaderNames:I.seal.headers?Object.keys(I.seal.headers):[],customCookieNames:I.seal.cookies?Object.keys(I.seal.cookies):[],endpoints:I.seal.endpoints},source:Sv0(I.source),relations:{testCorpId:I.testCorpId,prodCorpId:I.prodCorpId},auth:{refreshTtl:I.auth.refreshTtl}}),!0}if($==="current"){let z=M1(S(U.options.corp));return R0({id:z.id,name:z.name,environment:z.environment??"production",sourceType:z.source.type,provider:z.source.provider??z.source.type,staffId:z.source.staffId,testCorpId:z.testCorpId,prodCorpId:z.prodCorpId}),!0}if($==="mark"||$==="mark-test"||$==="mark-prod"){let z=Y??S(U.options.corp);if(!z)throw h4("Usage: seal-use corps mark <corpId> --env <production|test> [--confirm]");let I=M1(z),Q=$==="mark-test"?"test":$==="mark-prod"?"production":S(U.options.env)??S(U.options.environment);if(Q!=="production"&&Q!=="test")throw h4("Usage: seal-use corps mark <corpId> --env <production|test> [--confirm]");if(!(G0(U.options.confirm)===!0||G0(U.options.yes)===!0))throw w$(`Refusing to change environment tag of enterprise '${I.name}' (${I.id}) to '${Q}' without --confirm. Marking alters synchronization safety guards.`,`seal-use corps mark ${I.id} --env ${Q} --confirm`);let K=E9(I.id,{environment:Q});return R0({id:K.id,name:K.name,environment:K.environment,testCorpId:K.testCorpId,prodCorpId:K.prodCorpId}),!0}if($==="rename"){let z=Y??S(U.options.corp)??S(U.options.id),I=S(U.options.name)??S(U.options.to)??(U.command[3]&&!U.command[3].startsWith("-")?U.command[3]:void 0);if(!z||!I)throw Error("Usage: seal-use corps rename <corpId> --name <newName>");let Q=M1(z),J=E9(Q.id,{name:I});return R0({success:!0,id:J.id,name:J.name,previousName:Q.name}),!0}if($==="switch"){let z=Y;if(!z)throw Error("Usage: seal-use corps switch <corpId>");let I=v4();if(!I.stateful)throw Error("Cannot switch the default enterprise while stateless mode is enabled. Use `seal-use config mode stateful` first.");let Q=M1(z);return qz({...I,stateful:!0,defaultCorpId:Q.id}),R0({current:!0,id:Q.id,name:Q.name}),!0}return!1}var eh0=m(()=>{T5();ah0();UP();O4();O8();Z4();m1();iT()});import{existsSync as Vy1,mkdirSync as Ly1,readFileSync as Fy1,writeFileSync as $S0}from"node:fs";import{homedir as wy1}from"node:os";import{join as sT}from"node:path";function YS0(){let $=process.env.SEAL_USE_MAPPINGS_DIR?.trim();if($)return $;return sT(wy1(),".config","seal-use","mappings")}function US0($){let Y=YS0();Ly1(Y,{recursive:!0,mode:448});let U=sT(Y,`${$.target.id}-v${$.target.publishedVersionNumber}.json`),z=sT(Y,`${$.target.id}-latest.json`),I=JSON.stringify($,null,2);return $S0(U,I,{encoding:"utf-8",mode:384}),$S0(z,I,{encoding:"utf-8",mode:384}),U}function zS0($,Y){let U=YS0(),z;if(!Y||Y==="latest")z=`${$}-latest.json`;else{let Q=String(Y).replace(/^v/i,"");z=`${$}-v${Q}.json`}let I=sT(U,z);if(!Vy1(I))return null;try{let Q=Fy1(I,"utf-8");return JSON.parse(Q)}catch{return null}}function IS0($,Y){if(!Y)return $;let U=Y.trim().toLowerCase();return $.filter((z)=>{return String(z.sourceRuleCode).toLowerCase()===U||String(z.targetRuleCode).toLowerCase()===U||z.sourceRuleId.toLowerCase()===U||z.targetRuleId.toLowerCase()===U||`#${z.sourceRuleCode}`.toLowerCase()===U||`#${z.targetRuleCode}`.toLowerCase()===U})}function QS0($,Y,U){let z=0,I=Y!==void 0?new RegExp(`\\[Prod v${Y}\\s*·\\s*#(\\d+)(?:[^\\]]*)\\]`):/\[Prod draft\s*·\s*#(\d+)(?:[^\]]*)\]/;for(let J of U){if(!J.versionName)continue;let K=J.versionName.match(I);if(K&&K[1]){let G=parseInt(K[1],10);if(!isNaN(G)&&G>z)z=G}}if(z>0)return z+1;if(!U.some((J)=>J.versionName&&/\[Prod v\d+/.test(J.versionName))){let J=U.filter((K)=>K.versionName&&K.versionName.includes(`Sync from ${$}`)).length;if(J>0)return J+1}return 1}function JS0($,Y,U,z){let I=Y!==void 0?`Prod v${Y}`:"Prod draft",Q=z!==void 0?` -> Test v${z}`:"";return`Sync from ${$} [${I} · #${U}${Q}]`}var No=()=>{};import{randomBytes as My1}from"node:crypto";async function aT($,Y,U={}){let z=await B1($),I=await B1(Y),[Q,J,K,G,H,W,X,Z]=await Promise.all([r1(z,$.seal.endpoints.approvalStylePreferences),r1(I,Y.seal.endpoints.approvalStylePreferences),W6(z),W6(I),p8(z),p8(I),KS0(z),KS0(I)]),q=(X.articles||[]).filter((R)=>!R.isDeleted),V=(Z.articles||[]).filter((R)=>!R.isDeleted),w=new Map(V.map((R)=>[R.title.trim(),R])),M=[],F=[],N=new Set(q.map((R)=>R.title.trim()));for(let R of q){let o=R.title.trim(),e=w.get(o);if(!e){M.push(R);continue}let O0=[["co Line truncated
Run 'seal-use corps bind-test ${I.id} <testCorpId> --confirm' first to establish a verified 1-to-1 association.`);let Q=M1(I.testCorpId);if(Q.environment!=="test")throw Error(`Target enterprise '${Q.name}' (${Q.id}) is marked as '${Q.environment}', NOT 'test'. Aborting sync to protect non-test environments.`);let J=S(U.options["version-name"])??S(U.options.versionName),K=G0(U.options["dry-run"])===!0||G0(U.options.dryRun)===!0,G=G0(U.options.yes)===!0||G0(U.options.confirm)===!0;if(K)return R0(await aT(I,Q,{versionName:J,dryRun:!0})),!0;if(!G){let H=await aT(I,Q,{versionName:J,execute:!1});throw w$(`Refusing to overwrite test enterprise '${Q.name}' (${Q.id}) with preferences, ${H.rulesPlan.sourceDraftRuleCount} draft rules, and ${H.documentsPlan.sourceDocumentCount} knowledge documents from production enterprise '${I.name}' (${I.id}) without --yes. This will replace test draft rules, synchronize knowledge documents, and publish a new version on the test enterprise.`,`seal-use corps sync-test ${I.id} --yes`)}return R0(await aT(I,Q,{versionName:J,execute:!0})),!0}if($==="replay-test"){let z=Y??S(U.options.corp)??S(U.options.prodCorp)??S(U.options["prod-corp"]),I=M1(z),Q=G0(U.options.force)===!0,J=G0(U.options.dryRun)??G0(U.options["dry-run"]),K=G0(U.options.yes)===!0||G0(U.options.confirm)===!0,G;if(!I.testCorpId){if(!Q)throw h4(`Production enterprise '${I.name}' (${I.id}) has no bound test enterprise.
Run 'seal-use corps bind-test ${I.id} <testCorpId> --confirm' first to establish a verified 1-to-1 association,
or add '--force' (or use 'seal-use webhook replay <recordId> --force') if you explicitly intend to replay directly within production.`);G=I}else if(G=M1(I.testCorpId),G.environment!=="test"&&!Q)throw Error(`Target enterprise '${G.name}' (${G.id}) is marked as '${G.environment}', NOT 'test'. Aborting replay to protect non-test environments (use --force to override).`);if(!J&&!K)throw w$("Refusing to replay approval records without --confirm. Use --dry-run to preview the payload without sending it.",`seal-use corps replay-test ${z??"<prodCorpId>"} --confirm`);let H=S(U.options.recordId)??S(U.options["record-id"])??S(U.options.id),W=S(U.options.recordIds)??S(U.options["record-ids"]),X=W?W.split(",").map((D)=>D.trim()).filter(Boolean):void 0,Z=S(U.options.sn)??S(U.options.documentSn)??S(U.options["document-sn"]),q=S(U.options.sns)??S(U.options["document-sns"]),V=q?q.split(",").map((D)=>D.trim()).filter(Boolean):void 0,w=s0(U.options.limit)??(!H&&!X&&!Z&&!V?1:void 0),M={recordId:H,recordIds:X,sn:Z,sns:V,limit:w,status:S(U.options.status),startDate:S(U.options.startDate)??S(U.options["start-date"]),endDate:S(U.options.endDate)??S(U.options["end-date"])},F=await B1(I),N=I.id===G.id?F:await B1(G);console.error(`[corps-replay-test] 正式企业「${I.name}」(${I.id}) -> 测试企业「${G.name}」(${G.id})`);let O=await zK({query:M,sourceClient:F,targetClient:N,sourceCorp:I,targetCorp:G,webhookSelector:S(U.options.webhook)??S(U.options.selector),snPrefix:S(U.options.snPrefix)??S(U.options["sn-prefix"]),snSuffix:S(U.options.snSuffix)??S(U.options["sn-suffix"]),docIdPrefix:S(U.options.docIdPrefix)??S(U.options["doc-id-prefix"]),docIdSuffix:S(U.options.docIdSuffix)??S(U.options["doc-id-suffix"]),dryRun:J});if(J)return console.error(`[corps-replay-test] 预览模式:已成功从 ${I.name} 提取单据并转换为 Webhook Payload(未实际推送)。`),R0(O),!0;if(O.success)console.error(`\uD83D\uDFE2 成功重放 ${O.successCount} 条单据(来自「${I.name}」)至「${G.name}」(${O.targetWebhook?.name??"Webhook 通道"})`);else console.error(`\uD83D\uDD34 单据重放部分或全部失败(成功 ${O.successCount} 条,失败 ${O.failureCount} 条)至「${G.name}」`);if(console.error(`\uD83D\uDC49 Next action: seal-use approval-runs list --corp ${G.id} --limit ${O.totalCount}`),R0(O),!O.success)throw new W4(`Approval record replay failed: ${O.failureCount} record(s) failed.`,1);return!0}return!1}var HS0=m(()=>{m6();Do();iZ();O4();O8();Z4();m1();Do()});async function WS0($,Y,U){if(await th0($,Y,U))return;if(await qv0($,Y,U))return;if(await GS0($,Y,U))return;if(await gv0($,Y,U))return;throw Error(`Unknown corps command: ${$??""}. Run 'seal-use help' for available commands.`)}var Ao=m(()=>{Vv0();yv0();eh0();HS0();iT()});var qS0={};T8(qS0,{handleAuthExtractKeysCommand:()=>To,handleAuthCommand:()=>$j,formatBeijingIso:()=>Po});async function To($,Y){let U=$??S(Y.options.link)??S(Y.options.url);if(!U)throw Error("Usage: seal-use auth hose-extract-keys <https://.../web/thirdparty.html?...> [--reveal] [--save] [--name <customName>] [--overwrite]");let z=G0(Y.options.reveal)===!0||G0(Y.options.r)===!0||G0(Y.options.plain)===!0,I=G0(Y.options.save)===!0||G0(Y.options.add)===!0;await hq(U,{reveal:z,save:I,name:S(Y.options.name),overwrite:G0(Y.options.overwrite)===!0,force:G0(Y.options.force)===!0,appKey:S(Y.options["app-key"])??S(Y.options.appKey),keyId:S(Y.options["key-id"])??S(Y.options.keyId)})}async function $j($,Y,U){if($==="check"||$==="diagnose"||$==="status"||$==="test"||$==="doctor"){R0(await Dy1(Y));return}if($==="seal-link"||$==="link"||$==="hose-link"&&Y?.source?.type==="seal"){let z=U.command[2]?.toLowerCase(),I=S(U.options["from-link"])??(z==="from-link"?U.command[3]:void 0);if(I){let X=S(U.options.note),Z=await ZM(I),q=B6(Z.sealUrl,Z.token),V=await Z8(q);qM(Z.corpId,V.tenant);let w=await tI(q,{note:X});R0({tenant:{id:V.tenant.id,name:V.tenant.name,tenantSlug:V.tenant.tenantSlug,corpId:Z.corpId},user:{id:V.user.id,name:V.user.name,providerUserId:V.user.providerUserId,isAdmin:V.user.isAdmin},delegation:w,expiresIn:Z.expiresIn});return}let Q=await B1(Y);if(z==="list"){await x0("seal_delegation_list",Q,Y,{},j0(U.options));return}if(z==="revoke"){let X=U.command[3]??S(U.options.tokenId)??S(U.options.id);if(!X)throw Error("Usage: seal-use auth link revoke <tokenId>");await x0("seal_delegation_revoke",Q,Y,{tokenId:X},j0(U.options));return}let J=S(U.options.note)??"CLI generated provisional access link",K=await M$("seal_delegation_create",Q,Y,{note:J});if($==="hose-link")console.error(`\uD83D\uDC49 提示: 企业「${Y.name}」源类型为 Seal 原生测试环境,已自动为您生成委托免登直达链接。`);let G=K,H="staffName"in Y.source&&typeof Y.source.staffName==="string"?Y.source.staffName:void 0,W=Po(Date.now()+86400000);R0({id:G.id,corpId:Y.source.corpId??Y.id,corpName:Y.name,staffId:Y.source.staffId,...H?{staffName:H}:{},link:G.link,expiresAt:W,token:G.token});return}if($==="hose-link"){le Line truncated
`+"\uD83D\uDC49 检索指定企业请使用: seal-use corps search <keyword>")}return R0(F.map((N)=>({id:N.id,name:N.name,environment:N.environment??"production",sourceType:N.source.type,provider:N.source.provider??N.source.type,staffId:N.source.staffId,testCorpId:N.testCorpId,prodCorpId:N.prodCorpId,current:N.id===H}))),!0}if($==="get"||$==="show"){let I=Y??h(U.options.corp);if(!I)throw P4("Usage: seal-use corps get <corpId>");let Q=M1(I),J=_d(Q.id),K=OS0(Q);return R0({id:Q.id,name:Q.name,environment:Q.environment??"production",configFile:J,seal:{url:K,tenantSlug:Q.seal.tenantSlug??Q.source.tenantSlug,customHeaderNames:Q.seal.headers?Object.keys(Q.seal.headers):[],customCookieNames:Q.seal.cookies?Object.keys(Q.seal.cookies):[],endpoints:Q.seal.endpoints},source:NS0(Q.source),relations:{testCorpId:Q.testCorpId,prodCorpId:Q.prodCorpId},auth:{refreshTtl:Q.auth.refreshTtl}}),!0}if($==="current"){let I=M1(h(U.options.corp));return R0({id:I.id,name:I.name,environment:I.environment??"production",sourceType:I.source.type,provider:I.source.provider??I.source.type,staffId:I.source.staffId,testCorpId:I.testCorpId,prodCorpId:I.prodCorpId}),!0}if($==="mark"||$==="mark-test"||$==="mark-prod"){let I=Y??h(U.options.corp);if(!I)throw P4("Usage: seal-use corps mark <corpId> --env <production|test> [--confirm]");let Q=M1(I),J=$==="mark-test"?"test":$==="mark-prod"?"production":h(U.options.env)??h(U.options.environment);if(J!=="production"&&J!=="test")throw P4("Usage: seal-use corps mark <corpId> --env <production|test> [--confirm]");if(!(G0(U.options.confirm)===!0||G0(U.options.yes)===!0))throw U$(`Refusing to change environment tag of enterprise '${Q.name}' (${Q.id}) to '${J}' without --confirm. Marking alters synchronization safety guards.`,`seal-use corps mark ${Q.id} --env ${J} --confirm`);let z=R9(Q.id,{environment:J});return R0({id:z.id,name:z.name,environment:z.environment,testCorpId:z.testCorpId,prodCorpId:z.prodCorpId}),!0}if($==="rename"){let I=Y??h(U.options.corp)??h(U.options.id),Q=h(U.options.name)??h(U.options.to)??(U.command[3]&&!U.command[3].startsWith("-")?U.command[3]:void 0);if(!I||!Q)throw Error("Usage: seal-use corps rename <corpId> --name <newName>");let J=M1(I),K=R9(J.id,{name:Q});return R0({success:!0,id:K.id,name:K.name,previousName:J.name}),!0}if($==="switch"){let I=Y;if(!I)throw Error("Usage: seal-use corps switch <corpId>");let Q=A4();if(!Q.stateful)throw Error("Cannot switch the default enterprise while stateless mode is enabled. Use `seal-use config mode stateful` first.");let J=M1(I);return VI({...Q,stateful:!0,defaultCorpId:J.id}),R0({current:!0,id:J.id,name:J.name}),!0}return!1}var bh0=m(()=>{l$();fh0();HP();O4();J$();q4();l1();oT()});import{existsSync as yk1,mkdirSync as kk1,readFileSync as xk1,writeFileSync as ih0}from"node:fs";import{homedir as fk1}from"node:os";import{join as IE}from"node:path";function ch0(){let $=process.env.SEAL_USE_MAPPINGS_DIR?.trim();if($)return $;return IE(fk1(),".config","seal-use","mappings")}function nh0($){let Y=ch0();kk1(Y,{recursive:!0,mode:448});let U=IE(Y,`${$.target.id}-v${$.target.publishedVersionNumber}.json`),I=IE(Y,`${$.target.id}-latest.json`),Q=JSON.stringify($,null,2);return ih0(U,Q,{encoding:"utf-8",mode:384}),ih0(I,Q,{encoding:"utf-8",mode:384}),U}function dh0($,Y){let U=ch0(),I;if(!Y||Y==="latest")I=`${$}-latest.json`;else{let J=String(Y).replace(/^v/i,"");I=`${$}-v${J}.json`}let Q=IE(U,I);if(!yk1(Q))return null;try{let J=xk1(Q,"utf-8");return JSON.parse(J)}catch{return null}}function ph0($,Y){if(!Y)return $;let U=Y.trim().toLowerCase();return $.filter((I)=>{return String(I.sourceRuleCode).toLowerCase()===U||String(I.targetRuleCode).toLowerCase()===U||I.sourceRuleId.toLowerCase()===U||I.targetRuleId.toLowerCase()===U||`#${I.sourceRuleCode}`.toLowerCase()===U||`#${I.targetRuleCode}`.toLowerCase()===U})}function mh0($,Y,U){let I=0,Q=Y!==void 0?new RegExp(`\\[Prod v${Y}\\s*·\\s*#(\\d+)(?:[^\\]]*)\\]`):/\[Prod draft\s*·\s*#(\d+)(?:[^\]]*)\]/;for(let K of U){if(!K.versionName)continue;let z=K.versionName.match(Q);if(z&&z[1]){let G=parseInt(z[1],10);if(!isNaN(G)&&G>I)I=G}}if(I>0)return I+1;if(!U.some((K)=>K.versionName&&/\[Prod v\d+/.test(K.versionName))){let K=U.filter((z)=>z.versionName&&z.versionName.includes(`Sync from ${$}`)).length;if(K>0)return K+1}return 1}function lh0($,Y,U,I){let Q=Y!==void 0?`Prod v${Y}`:"Prod draft",J=I!==void 0?` -> Test v${I}`:"";return`Sync from ${$} [${Q} · #${U}${J}]`}var yo=()=>{};import{randomBytes as uk1}from"node:crypto";async function QE($,Y,U={}){let I=await A1($),Q=await A1(Y),[J,K,z,G,H,W,X,Z]=await Promise.all([n1(I,$.seal.endpoints.approvalStylePreferences),n1(Q,Y.seal.endpoints.approvalStylePreferences),q6(I),q6(Q),S8(I),S8(Q),oh0(I),oh0(Q)]),q=(X.articles||[]).filter((R)=>!R.isDeleted),V=(Z.articles||[]).filter((R)=>!R.isDeleted),w=new Map(V.map((R)=>[R.title.trim(),R])),M=[],F=[],N=new Set(q.map((R)=>R.title.trim()));for(let R of q){let o=R.title.trim(),e=w.get(o);if(!e){M.push(R);continue}let O0=[["co Line truncated
Run 'seal-use corps bind-test ${Q.id} <testCorpId> --confirm' first to establish a verified 1-to-1 association.`);let J=M1(Q.testCorpId);if(J.environment!=="test")throw Error(`Target enterprise '${J.name}' (${J.id}) is marked as '${J.environment}', NOT 'test'. Aborting sync to protect non-test environments.`);let K=h(U.options["version-name"])??h(U.options.versionName),z=G0(U.options["dry-run"])===!0||G0(U.options.dryRun)===!0,G=G0(U.options.yes)===!0||G0(U.options.confirm)===!0;if(z)return R0(await QE(Q,J,{versionName:K,dryRun:!0})),!0;if(!G){let H=await QE(Q,J,{versionName:K,execute:!1});throw U$(`Refusing to overwrite test enterprise '${J.name}' (${J.id}) with preferences, ${H.rulesPlan.sourceDraftRuleCount} draft rules, and ${H.documentsPlan.sourceDocumentCount} knowledge documents from production enterprise '${Q.name}' (${Q.id}) without --yes. This will replace test draft rules, synchronize knowledge documents, and publish a new version on the test enterprise.`,`seal-use corps sync-test ${Q.id} --yes`)}return R0(await QE(Q,J,{versionName:K,execute:!0})),!0}if($==="replay-test"){let I=Y??h(U.options.corp)??h(U.options.prodCorp)??h(U.options["prod-corp"]),Q=M1(I),J=G0(U.options.force)===!0,K=G0(U.options.dryRun)??G0(U.options["dry-run"]),z=G0(U.options.yes)===!0||G0(U.options.confirm)===!0,G;if(!Q.testCorpId){if(!J)throw P4(`Production enterprise '${Q.name}' (${Q.id}) has no bound test enterprise.
Run 'seal-use corps bind-test ${Q.id} <testCorpId> --confirm' first to establish a verified 1-to-1 association,
or add '--force' (or use 'seal-use webhook replay <recordId> --force') if you explicitly intend to replay directly within production.`);G=Q}else if(G=M1(Q.testCorpId),G.environment!=="test"&&!J)throw Error(`Target enterprise '${G.name}' (${G.id}) is marked as '${G.environment}', NOT 'test'. Aborting replay to protect non-test environments (use --force to override).`);if(!K&&!z)throw U$("Refusing to replay approval records without --confirm. Use --dry-run to preview the payload without sending it.",`seal-use corps replay-test ${I??"<prodCorpId>"} --confirm`);let H=h(U.options.recordId)??h(U.options["record-id"])??h(U.options.id),W=h(U.options.recordIds)??h(U.options["record-ids"]),X=W?W.split(",").map((D)=>D.trim()).filter(Boolean):void 0,Z=h(U.options.sn)??h(U.options.documentSn)??h(U.options["document-sn"]),q=h(U.options.sns)??h(U.options["document-sns"]),V=q?q.split(",").map((D)=>D.trim()).filter(Boolean):void 0,w=s0(U.options.limit)??(!H&&!X&&!Z&&!V?1:void 0),M={recordId:H,recordIds:X,sn:Z,sns:V,limit:w,status:h(U.options.status),startDate:h(U.options.startDate)??h(U.options["start-date"]),endDate:h(U.options.endDate)??h(U.options["end-date"])},F=await A1(Q),N=Q.id===G.id?F:await A1(G);console.error(`[corps-replay-test] 正式企业「${Q.name}」(${Q.id}) -> 测试企业「${G.name}」(${G.id})`);let O=await Gz({query:M,sourceClient:F,targetClient:N,sourceCorp:Q,targetCorp:G,webhookSelector:h(U.options.webhook)??h(U.options.selector),snPrefix:h(U.options.snPrefix)??h(U.options["sn-prefix"]),snSuffix:h(U.options.snSuffix)??h(U.options["sn-suffix"]),docIdPrefix:h(U.options.docIdPrefix)??h(U.options["doc-id-prefix"]),docIdSuffix:h(U.options.docIdSuffix)??h(U.options["doc-id-suffix"]),dryRun:K});if(K)return console.error(`[corps-replay-test] 预览模式:已成功从 ${Q.name} 提取单据并转换为 Webhook Payload(未实际推送)。`),R0(O),!0;if(O.success)console.error(`\uD83D\uDFE2 成功重放 ${O.successCount} 条单据(来自「${Q.name}」)至「${G.name}」(${O.targetWebhook?.name??"Webhook 通道"})`);else console.error(`\uD83D\uDD34 单据重放部分或全部失败(成功 ${O.successCount} 条,失败 ${O.failureCount} 条)至「${G.name}」`);if(console.error(`\uD83D\uDC49 Next action: seal-use approval-runs list --corp ${G.id} --limit ${O.totalCount}`),R0(O),!O.success)throw new X4(`Approval record replay failed: ${O.failureCount} record(s) failed.`,1);return!0}return!1}var sh0=m(()=>{f6();ko();sZ();O4();J$();q4();l1();ko()});async function ah0($,Y,U){if(await uh0($,Y,U))return;if(await $S0($,Y,U))return;if(await rh0($,Y,U))return;if(await DS0($,Y,U))return;throw Error(`Unknown corps command: ${$??""}. Run 'seal-use help' for available commands.`)}var xo=m(()=>{YS0();BS0();bh0();sh0();oT()});var $g0={};Z8($g0,{handleAuthExtractKeysCommand:()=>bo,handleAuthCommand:()=>zE,formatBeijingIso:()=>uo});async function bo($,Y){let U=$??h(Y.options.link)??h(Y.options.url);if(!U)throw Error("Usage: seal-use auth hose-extract-keys <https://.../web/thirdparty.html?...> [--reveal] [--save] [--name <customName>] [--overwrite]");let I=G0(Y.options.reveal)===!0||G0(Y.options.r)===!0||G0(Y.options.plain)===!0,Q=G0(Y.options.save)===!0||G0(Y.options.add)===!0;await fq(U,{reveal:I,save:Q,name:h(Y.options.name),overwrite:G0(Y.options.overwrite)===!0,force:G0(Y.options.force)===!0,appKey:h(Y.options["app-key"])??h(Y.options.appKey),keyId:h(Y.options["key-id"])??h(Y.options.keyId)})}async function zE($,Y,U){let I=U.command[2]?.toLowerCase(),Q=h(U.options["from-link"])??(I==="from-link"?U.command[3]:void 0);if(($==="seal-link"||$==="link"||$==="hose-link"&&Y?.source?.type==="seal")&&Q){let J=h(U.options.note),K=await MM(Q),z=T6(K.sealUrl,K.token),G=await o6(z);OM(K.corpId,G.tenant);let H=await eQ(z,{note:J});R0({tenant:{id:G.tenant.id,name:G.tenant.name,tenantSlug:G.tenant.tenantSlug,corpId:K.corpId},user:{id:G.user.id,name:G.user.name,providerUserId:G.user.providerUserId,isAdmin:G.user.isAdmin},delegation:H,expiresIn:K.expiresIn});return}if(!Y)throw Error(`auth ${$??""} requires an enterprise. Provide --corp <id> or select one.`);if($==="check"||$==="diagnose"||$==="status"||$==="test"||$==="doctor"){R0(await ck1(Y));return}if($==="seal-link"||$==="link"||$==="hose-link"&&Y.source?.type==="seal"){let J=await A1(Y);if(I==="list"){await x0("seal_delegation_list",J,Y,{},E0(U.options));return}if(I==="revoke"){let X=U.command[3]??h(U.options.tokenId)??h(U.options.id);if(!X)throw Error("Usage: seal-use auth link revoke <tokenId>");await x0("seal_delegation_revoke",J,Y,{tokenId:X},E0(U.options));return}let K=h(U.options.note)??"CLI generated provisional access link",z=await P$("seal_delegation_create",J,Y,{note:K});if($==="hose-link")console.error(`\uD83D\uDC49 提示: 企业「${Y.name}」源类型为 Seal 原生测试环境,已自动为您生成委托免登直达链接。`);let G=z,H="staffName"in Y.source&&typeof Y.source.staffName==="string"?Y.source.staffName:void 0,W=uo(Date.now()+86400000);R0({id Line truncated
`+`支持的审批系统与发布目标:
`+` • hosecloud (合思费控): seal-use deploy hosecloud <requirements|list|get|status|configure|sync> --corp <corpId>
@@ -947,18 +947,18 @@ or add '--force' (or use 'seal-use webhook replay <recordId> --force') if you ex
`+` • feishu (飞书审批): 建议使用 Webhook 模式对接
`+` • weaver (泛微 OA): 建议使用 Webhook 模式对接
`+` • helios (汇联易): 建议使用 Webhook 模式对接
`+" • maycur (每刻报销): 建议使用 Webhook 模式对接");if($==="webhook"||$==="webhooks")throw Error("Webhook 审批流发布请直接使用专有命令:seal-use webhook <list|get|add|update|delete> --corp <corpId>");if($==="feishu"||$==="lark")throw Error("飞书审批发布:建议使用 Webhook 通用发布模式对接。命令:seal-use webhook add --name '飞书审批' --result-url <url> --corp <corpId>");if($==="weaver")throw Error("泛微 OA 发布:建议使用 Webhook 通用发布模式对接。命令:seal-use webhook add --name '泛微OA' --result-url <url> --corp <corpId>");if($==="maycur"||$==="helios"){let H=$==="maycur"?"每刻报销":"汇联易";throw Error(`${H}发布:目前可通过 Webhook 模式接入。命令:seal-use webhook add --name '${H}' --result-url <url> --corp <corpId>`)}let J=$==="hosecloud",K=$==="hosecloud"?Y:$,G=$==="hosecloud"?U:Y;if(!J)throw Error(`未知的发布目标系统: ${$}。当前支持: hosecloud (合思费控) 与 webhook (通用回调)。`);if(K==="requirements"){await x0("seal_deploy_hosecloud_requirements",z,I,{},j0(Q.options));return}if(K==="list"){await x0("seal_deploy_hosecloud_list",z,I,{},j0(Q.options));return}if(K==="get"){let H=G??S(Q.options.signKey)??S(Q.options["sign-key"]);if(!H){let X=((await r1(z)).integrations??[]).filter((Z)=>Z.type==="hosecloud");if(X.length===0)throw Error(`当前企业 (${I.name}) 尚未添加合思发布配置。
`+`\uD83D\uDC49 请先运行配置命令:seal-use deploy hosecloud configure --json '{...}' --corp ${I.id}`);console.error(`Usage: seal-use deploy hosecloud get <sign-key> [--corp ${I.id}]
`),console.error("ℹ️ 当前企业发现以下可用的合思配置卡片:");for(let Z of X){let q=Z.outboundName??"SealAI 审批",V=Z.signKey,w=Z.apiOrigin??"production";console.error(` • "${q}" (signKey: ${V}, 环境: ${w})`),console.error(` \uD83D\uDC49 查看命令: seal-use deploy hosecloud get ${V} --corp ${I.id}
`)}throw new W4("缺少必需参数 <sign-key>。请从上述候选列表中选择并指定 signKey。",2,X.length===1?`seal-use deploy hosecloud get ${X[0].signKey} --corp ${I.id}`:void 0)}await x0("seal_deploy_hosecloud_get",z,I,{signKey:H},j0(Q.options));return}if(K==="status"){await x0("seal_deploy_hosecloud_status",z,I,{},j0(Q.options));return}if(K==="configure"){let H=S(Q.options.input),W=H?JSON.parse(Ty1(H,"utf8")):B8(Q.json);if(!W||Object.keys(W).length===0)throw Error("Usage: seal-use deploy hosecloud configure --json '{...}' or --input <file>");await x0("seal_deploy_hosecloud_configure",z,I,{...W,dryRun:G0(Q.options.dryRun)??G0(Q.options["dry-run"])},j0(Q.options));return}if(K==="sync"){let H=G??S(Q.options.signKey)??S(Q.options["sign-key"]),W=G0(Q.options.auto)??G0(Q.options.yes);if(!H){let Z=((await r1(z)).integrations??[]).filter((V)=>V.type==="hosecloud");if(Z.length===0)throw Error(`当前企业 (${I.name}) 尚未添加合思发布配置。
`+`\uD83D\uDC49 请先运行配置命令:seal-use deploy hosecloud configure --json '{...}' --corp ${I.id}`);let q=Z[0];if(q&&Z.length===1&&W){let V=q.signKey;console.error(`ℹ️ [auto] 检测到企业仅有 1 个合思配置,已自动选择 (signKey: ${V})`),await x0("seal_deploy_hosecloud_sync",z,I,{signKey:V},j0(Q.options));return}console.error(`Usage: seal-use deploy hosecloud sync <sign-key> [--corp ${I.id}]
`),console.error("ℹ️ 当前企业发现以下可用的合思配置卡片:");for(let V of Z){let w=V.outboundName??"SealAI 审批",M=V.signKey,F=V.apiOrigin??"production";console.error(` • "${w}" (signKey: ${M}, 环境: ${F})`),console.error(` \uD83D\uDC49 同步命令: seal-use deploy hosecloud sync ${M} --corp ${I.id}
`)}if(Z.length===1)console.error(`\uD83D\uDCA1 提示:若希望单配置自动同步,可附加 --auto 参数:seal-use deploy hosecloud sync --auto --corp ${I.id}
`);throw new W4("缺少必需参数 <sign-key>。请从上述候选列表中选择并指定 signKey 执行同步。",2,Z.length===1?`seal-use deploy hosecloud sync ${Z[0].signKey} --corp ${I.id}`:void 0)}await x0("seal_deploy_hosecloud_sync",z,I,{signKey:H},j0(Q.options));return}throw Error(`Unknown deploy hosecloud action: ${K??""}. Available: requirements, list, get, status, configure, sync.`)}var TS0=m(()=>{O4();Z4();m1();X6();O8()});var ES0='---\nname: seal-use\ndescription: "v0.10.38: Use for Seal Use enterprise onboarding, Hose/合思 or Seal-native authentication, approval operations, diagnosis, simulation, rules, users, configuration, and search."\nmetadata:\n version: 0.10.38\n short-description: Seal tenant and Hose approval automation (v0.10.38)\n---\n\n# Seal Use\n\nCLI 是主执行通道。机器通道 `stdout` 必须是纯 JSON;诊断日志、进度和下一步建议写入 `stderr`。MCP 默认关闭。\n\n## 时间与输出\n\n- 机器字段保留 ISO 8601 UTC,精确到秒,不要添加毫秒,例如 `2026-09-22T04:56:06Z`。\n- 面向用户解释时间时,换算为 `Asia/Shanghai`,明确标注“北京时间”;审计或消歧时同时保留原始 UTC。\n- 不向用户暴露 Bearer、`accessToken`、`closeToken`、`appSecurity`、原始 cURL 或未脱敏手机号。\n- 不向用户直接暴露底层 UUID、`tenantSlug`、`boundCorpRole` 等内部字段;优先使用企业名称、规则编号 `#xxxx` 和脱敏后的业务信息。\n\n## 企业接入:先识别材料,再选择入口\n\n最终企业来源只有两种:`source.type: "seal"` 和 `source.type: "hose"`。不要把材料格式、认证凭据和最终来源混为一谈。\n\n| 用户材料 | 标准入口 | 最终配置形态 |\n| --- | --- | --- |\n| Hose 开放平台 `appKey + appSecurity` | `corps add-hose-persistent` | Hose 持久化凭据 |\n| Seal URL + Bearer,或 Seal 页面 cURL | `corps add-seal-bearer` | Seal Bearer 会话 |\n| Seal 原生委托链接 | `corps add-link <url>` | Seal 委托会话 |\n| Hose 协助链接 | `corps add-link <url>` | Hose Web Session;加 `--elevate-hose` 才提取长期密钥 |\n| Hose 页面 cURL | 先提取密钥;失败时 `corps add-hose-web-session` | Hose 持久化或 Hose Web Session |\n| 已规范化的 Hose `corpId + accessToken + baseUrl` | `corps add-hose-web-session` | Hose Web Session |\n\n### 凭据边界\n\n- Seal Bearer 只能给 `add-seal-bearer`;Hose `accessToken/accesstoken/closeToken` 不能直接当作 Seal Bearer。\n- Hose Web Session 保存 `closeToken + staffId`,需要调用 Seal 时才通过 SSO 换取运行时 Seal Bearer。\n- Hose 持久化配置保存 `appKey + appSecurity`,适合无人值守、部署和长期同步。\n- 会话有有效期时,Hose source 保存 `expiresIn` 和 UTC 秒级 `expiresAt`。\n- `add-link` 是 URL 混合入口,不接收 cURL:自动识别 Seal 委托链接和 Hose 协助链接。\n- `--elevate-hose` 是唯一明确的 Hose 提权动作。\n\n收到 Hose 管理员 cURL 时,按 Hose 协助链接处理:解析主机、`accesstoken`、企业标识和必要会话信息,优先调用密钥提取路径;无法提取长期密钥时才保存 Web Session。收到 Seal cURL 时,提取 Seal 主机和 `Authorization: Bearer`,走 `add-seal-bearer`。不要盲目执行 cURL,也不要把原文写入文件或日志。\n\n详细来源决策、提权边界和 cURL 处理见 `references/enterprise-onboarding.md`;首次找材料时必须使用 `references/first-time-user.md`。\n\n## 首次接入图文规则\n\n当用户首次接入、询问如何取得材料,或需要用户打开后台找凭据时:\n\n1. 先确认用户手上是 Hose 开放平台凭据、协助链接、Seal 委托链接,还是已登录网页 cURL。\n2. 读取 `references/first-time-user.md`,只渲染与当前路径对应的截图;不能只给纯文字步骤。\n3. 接收材料后由 Agent 自动发现企业、域名和管理员。除非自动发现失败,不要要求用户先填写 `corpId`、`staffId` 或域名。\n\n## `corps` 主线\n\n- 接入:`add-link`、`add-seal-bearer`、`add-hose-persistent`、`add-hose-web-session`\n- 发现:`list`、`search`/`find`、`get`/`show`、`current`、`switch`\n- 维护:`mark`、`rename`\n- 测试闭环:`bind-test`、`unbind-test`、`sync-test`、`replay-test`\n- Hose 专属:`probe-hose`、`hose-staffs`、`hose-extract-keys`、`hose-keys`\n\nHose 专属命令应从命令名或选项中明确可见:`auth hose-*`、`approval-runs hose-flow`、`deploy hosecloud`、`simulation --mode hosecloud`。跨来源入口只有在明确使用 `--elevate-hose`、`--with-flow` 或 `--type hose-document` 时才启用对应 Hose 能力。\n\n生产规则变更遵循:生产改草稿 → 同步测试 → 模拟/回归验证 → 用户确认 → 生产发布。`sync-test`、`replay-test`、规则发布和清空等高风险操作优先 `--dry-run`,正式执行必须显式 `--yes` 或 `--confirm`。\ Line truncated
`+" • maycur (每刻报销): 建议使用 Webhook 模式对接");if($==="webhook"||$==="webhooks")throw Error("Webhook 审批流发布请直接使用专有命令:seal-use webhook <list|get|add|update|delete> --corp <corpId>");if($==="feishu"||$==="lark")throw Error("飞书审批发布:建议使用 Webhook 通用发布模式对接。命令:seal-use webhook add --name '飞书审批' --result-url <url> --corp <corpId>");if($==="weaver")throw Error("泛微 OA 发布:建议使用 Webhook 通用发布模式对接。命令:seal-use webhook add --name '泛微OA' --result-url <url> --corp <corpId>");if($==="maycur"||$==="helios"){let H=$==="maycur"?"每刻报销":"汇联易";throw Error(`${H}发布:目前可通过 Webhook 模式接入。命令:seal-use webhook add --name '${H}' --result-url <url> --corp <corpId>`)}let K=$==="hosecloud",z=$==="hosecloud"?Y:$,G=$==="hosecloud"?U:Y;if(!K)throw Error(`未知的发布目标系统: ${$}。当前支持: hosecloud (合思费控) 与 webhook (通用回调)。`);if(z==="requirements"){await x0("seal_deploy_hosecloud_requirements",I,Q,{},E0(J.options));return}if(z==="list"){await x0("seal_deploy_hosecloud_list",I,Q,{},E0(J.options));return}if(z==="get"){let H=G??h(J.options.signKey)??h(J.options["sign-key"]);if(!H){let X=((await n1(I)).integrations??[]).filter((Z)=>Z.type==="hosecloud");if(X.length===0)throw Error(`当前企业 (${Q.name}) 尚未添加合思发布配置。
`+`\uD83D\uDC49 请先运行配置命令:seal-use deploy hosecloud configure --json '{...}' --corp ${Q.id}`);console.error(`Usage: seal-use deploy hosecloud get <sign-key> [--corp ${Q.id}]
`),console.error("ℹ️ 当前企业发现以下可用的合思配置卡片:");for(let Z of X){let q=Z.outboundName??"SealAI 审批",V=Z.signKey,w=Z.apiOrigin??"production";console.error(` • "${q}" (signKey: ${V}, 环境: ${w})`),console.error(` \uD83D\uDC49 查看命令: seal-use deploy hosecloud get ${V} --corp ${Q.id}
`)}throw new X4("缺少必需参数 <sign-key>。请从上述候选列表中选择并指定 signKey。",2,X.length===1?`seal-use deploy hosecloud get ${X[0].signKey} --corp ${Q.id}`:void 0)}await x0("seal_deploy_hosecloud_get",I,Q,{signKey:H},E0(J.options));return}if(z==="status"){await x0("seal_deploy_hosecloud_status",I,Q,{},E0(J.options));return}if(z==="configure"){let H=h(J.options.input),W=H?JSON.parse(mk1(H,"utf8")):E8(J.json);if(!W||Object.keys(W).length===0)throw Error("Usage: seal-use deploy hosecloud configure --json '{...}' or --input <file>");await x0("seal_deploy_hosecloud_configure",I,Q,{...W,dryRun:G0(J.options.dryRun)??G0(J.options["dry-run"])},E0(J.options));return}if(z==="sync"){let H=G??h(J.options.signKey)??h(J.options["sign-key"]),W=G0(J.options.auto)??G0(J.options.yes);if(!H){let Z=((await n1(I)).integrations??[]).filter((V)=>V.type==="hosecloud");if(Z.length===0)throw Error(`当前企业 (${Q.name}) 尚未添加合思发布配置。
`+`\uD83D\uDC49 请先运行配置命令:seal-use deploy hosecloud configure --json '{...}' --corp ${Q.id}`);let q=Z[0];if(q&&Z.length===1&&W){let V=q.signKey;console.error(`ℹ️ [auto] 检测到企业仅有 1 个合思配置,已自动选择 (signKey: ${V})`),await x0("seal_deploy_hosecloud_sync",I,Q,{signKey:V},E0(J.options));return}console.error(`Usage: seal-use deploy hosecloud sync <sign-key> [--corp ${Q.id}]
`),console.error("ℹ️ 当前企业发现以下可用的合思配置卡片:");for(let V of Z){let w=V.outboundName??"SealAI 审批",M=V.signKey,F=V.apiOrigin??"production";console.error(` • "${w}" (signKey: ${M}, 环境: ${F})`),console.error(` \uD83D\uDC49 同步命令: seal-use deploy hosecloud sync ${M} --corp ${Q.id}
`)}if(Z.length===1)console.error(`\uD83D\uDCA1 提示:若希望单配置自动同步,可附加 --auto 参数:seal-use deploy hosecloud sync --auto --corp ${Q.id}
`);throw new X4("缺少必需参数 <sign-key>。请从上述候选列表中选择并指定 signKey 执行同步。",2,Z.length===1?`seal-use deploy hosecloud sync ${Z[0].signKey} --corp ${Q.id}`:void 0)}await x0("seal_deploy_hosecloud_sync",I,Q,{signKey:H},E0(J.options));return}throw Error(`Unknown deploy hosecloud action: ${z??""}. Available: requirements, list, get, status, configure, sync.`)}var Zg0=m(()=>{O4();q4();l1();H4();J$()});var Vg0='---\nname: seal-use\ndescription: "v0.10.38: Use for Seal Use enterprise onboarding, Hose/合思 or Seal-native authentication, approval operations, diagnosis, simulation, rules, users, configuration, and search."\nmetadata:\n version: 0.10.38\n short-description: Seal tenant and Hose approval automation (v0.10.38)\n---\n\n# Seal Use\n\nCLI 是主执行通道。机器通道 `stdout` 必须是纯 JSON;诊断日志、进度和下一步建议写入 `stderr`。MCP 默认关闭。\n\n## 时间与输出\n\n- 机器字段保留 ISO 8601 UTC,精确到秒,不要添加毫秒,例如 `2026-09-22T04:56:06Z`。\n- 面向用户解释时间时,换算为 `Asia/Shanghai`,明确标注“北京时间”;审计或消歧时同时保留原始 UTC。\n- 不向用户暴露 Bearer、`accessToken`、`closeToken`、`appSecurity`、原始 cURL 或未脱敏手机号。\n- 不向用户直接暴露底层 UUID、`tenantSlug`、`boundCorpRole` 等内部字段;优先使用企业名称、规则编号 `#xxxx` 和脱敏后的业务信息。\n\n## 企业接入:先识别材料,再选择入口\n\n最终企业来源只有两种:`source.type: "seal"` 和 `source.type: "hose"`。不要把材料格式、认证凭据和最终来源混为一谈。\n\n| 用户材料 | 标准入口 | 最终配置形态 |\n| --- | --- | --- |\n| Hose 开放平台 `appKey + appSecurity` | `corps add-hose-persistent` | Hose 持久化凭据 |\n| Seal URL + Bearer,或 Seal 页面 cURL | `corps add-seal-bearer` | Seal Bearer 会话 |\n| Seal 原生委托链接 | `corps add-link <url>` | Seal 委托会话 |\n| Hose 协助链接 | `corps add-link <url>` | Hose Web Session;加 `--elevate-hose` 才提取长期密钥 |\n| Hose 页面 cURL | 先提取密钥;失败时 `corps add-hose-web-session` | Hose 持久化或 Hose Web Session |\n| 已规范化的 Hose `corpId + accessToken + baseUrl` | `corps add-hose-web-session` | Hose Web Session |\n\n### 凭据边界\n\n- Seal Bearer 只能给 `add-seal-bearer`;Hose `accessToken/accesstoken/closeToken` 不能直接当作 Seal Bearer。\n- Hose Web Session 保存 `closeToken + staffId`,需要调用 Seal 时才通过 SSO 换取运行时 Seal Bearer。\n- Hose 持久化配置保存 `appKey + appSecurity`,适合无人值守、部署和长期同步。\n- 会话有有效期时,Hose source 保存 `expiresIn` 和 UTC 秒级 `expiresAt`。\n- `add-link` 是 URL 混合入口,不接收 cURL:自动识别 Seal 委托链接和 Hose 协助链接。\n- `--elevate-hose` 是唯一明确的 Hose 提权动作。\n\n收到 Hose 管理员 cURL 时,按 Hose 协助链接处理:解析主机、`accesstoken`、企业标识和必要会话信息,优先调用密钥提取路径;无法提取长期密钥时才保存 Web Session。收到 Seal cURL 时,提取 Seal 主机和 `Authorization: Bearer`,走 `add-seal-bearer`。不要盲目执行 cURL,也不要把原文写入文件或日志。\n\n详细来源决策、提权边界和 cURL 处理见 `references/enterprise-onboarding.md`;首次找材料时必须使用 `references/first-time-user.md`。\n\n## 首次接入图文规则\n\n当用户首次接入、询问如何取得材料,或需要用户打开后台找凭据时:\n\n1. 先确认用户手上是 Hose 开放平台凭据、协助链接、Seal 委托链接,还是已登录网页 cURL。\n2. 读取 `references/first-time-user.md`,只渲染与当前路径对应的截图;不能只给纯文字步骤。\n3. 接收材料后由 Agent 自动发现企业、域名和管理员。除非自动发现失败,不要要求用户先填写 `corpId`、`staffId` 或域名。\n\n## `corps` 主线\n\n- 接入:`add-link`、`add-seal-bearer`、`add-hose-persistent`、`add-hose-web-session`\n- 发现:`list`、`search`/`find`、`get`/`show`、`current`、`switch`\n- 维护:`mark`、`rename`\n- 测试闭环:`bind-test`、`unbind-test`、`sync-test`、`replay-test`\n- Hose 专属:`probe-hose`、`hose-staffs`、`hose-extract-keys`、`hose-keys`\n\nHose 专属命令应从命令名或选项中明确可见:`auth hose-*`、`approval-runs hose-flow`、`deploy hosecloud`、`simulation --mode hosecloud`。跨来源入口只有在明确使用 `--elevate-hose`、`--with-flow` 或 `--type hose-document` 时才启用对应 Hose 能力。\n\n生产规则变更遵循:生产改草稿 → 同步测试 → 模拟/回归验证 → 用户确认 → 生产发布。`sync-test`、`replay-test`、规则发布和清空等高风险操作优先 `--dry-run`,正式执行必须显式 `--yes` 或 `--confirm`。\ Line truncated
display_name: "Seal Use"
short_description: "Diagnose approval feedback and publish minimal rule fixes"
default_prompt: "Use $seal-use to resolve a customer feedback package to the correct tenant, diagnose the approval run, propose a minimal rule diff, and publish only after explicit confirmation."
`;var CS0=()=>{};var vS0=`# Approval Attachment Trace Investigation
`;var Lg0=()=>{};var Mg0=`# Approval Attachment Trace Investigation
Use this workflow when a customer disputes an AI approval finding about an attachment, invoice, receipt, OCR result, or a UI-highlighted audit result.
@@ -1179,7 +1179,7 @@ Manual image check:
- The customer's objection that they were receipts rather than invoices was reasonable.
However, the final rejection also had an independent rule-37 reason: payment screenshots totaled 699.48 while reimbursement was 700.00.
`;var _S0=()=>{};var SS0=`# Approval Bad Case Catalog
`;var wg0=()=>{};var Ng0=`# Approval Bad Case Catalog
Use this file only as a comparison catalog after inspecting the current trace. Do not treat any case below as a default diagnosis.
@@ -1229,7 +1229,7 @@ Important nuance:
- This is a bad-case pattern, not a general rule that every amount-total dispute is caused by \`pre_analysis\`.
- Use it when the current trace shows recognized amounts being excluded downstream or duplicate attachments producing inconsistent conclusions.
`;var hS0=()=>{};var yS0="# Approval Run Lightweight Queries\n\nUse this reference when the user gives a 合思/易快报单号, source document SN, record ID, simulation batch ID, or asks for an approval decision without needing the full raw run payload.\n\n## Locate A Run By Document Number\n\nPrefer `pick` before broad search + bridge + get.\n\n```bash\nseal-use approval-runs pick --corp <corpId> --sn <sourceDocumentSN> --latest\nseal-use approval-runs pick --corp <corpId> --sn <sourceDocumentSN> --batch <batchId> --latest\nseal-use approval-runs pick --corp <corpId> --sn <sourceDocumentSN> --latest --fields recordId,sourceDocumentSN,status,aiDecision,aiSummary\n```\n\nDefault output is intentionally small: `recordId`, `sourceDocumentSN`, `sourceDocumentId`, `simulationBatchId`, `status`, `taskMode`, `ruleSetVersionNumber`, `langfuseTraceId`, `manualResult`, `aiDecision`, and `aiSummary`.\n\nIf there are multiple candidates and `--latest` was not used, report the candidates and ask which one to inspect.\n\n## Read Compact Run Detail\n\nUse `--summary` for most diagnosis and support questions.\n\n```bash\nseal-use approval-runs get <recordId> --corp <corpId> --summary\n```\n\nUse `--fields` when the user needs a particular slice.\n\n```bash\nseal-use approval-runs get <recordId> --corp <corpId> --fields metadata\nseal-use approval-runs get <recordId> --corp <corpId> --fields document.fields,result.summary\nseal-use approval-runs get <recordId> --corp <corpId> --fields result.summary,result.decision,result.riskPoints\nseal-use approval-runs get <recordId> --corp <corpId> --fields document.keyFields,result,manualApprovalRecord,ruleSetVersionNumber\n```\n\nAvoid full `approval-runs get <recordId>` unless the user specifically needs raw document fields, pipeline logs, invoice rawData, or signed URLs. Prefer `--output-file` for full payloads.\n\n## Understand The Case First\n\nBefore pulling the full document, use:\n\n```bash\nseal-use approval-runs document-summary <recordId> --corp <corpId>\n```\n\nThis is for quick case reading: template/title, key fields, amount, expense type, cost company, payee, invoice summary, attachment names, AI result, and manual result.\n\n## Extract AI-Cited Rules\n\nUse this when the user asks \"AI 用了哪条规则\", \"为什么命中这条\", or needs the rule evidence for a specific run.\n\n```bash\nseal-use approval-runs cited-rules <recordId> --corp <corpId>\n```\n\nReturn and discuss `runtimeRuleId`, `ruleCode`, `versionNumber`, `scope`, `strictness`, `appliedAnalysis`, `checkResult`, and `findings` when present.\n\nIf the user then wants the full text of one cited rule, use `rules get --record-id <recordId> --runtime-id rule-205` from `rule-lightweight.md`.\n\n## Attachments Without Raw Payloads\n\nUse:\n\n```bash\n# 查看附件列表摘要(包含文件名、类型、大小及直链可用性)\nseal-use approval-runs attachments <recordId> --corp <corpId> --summary\n\n# 下载全部附件到本地目录(优先使用 ossSignedUrl 签名直链)\nseal-use approval-runs attachments download <recordId> --all --out-dir ./downloads --corp <corpId>\n\n# 按名称或 fileId 过滤下载单个附件\nseal-use approval-runs attachments download <recordId> --name 发票 --corp <corpId>\n```\n\nThis should be enough for file names, file IDs, mime types, positions, invoice/attachment grouping, and links when available. For customer disputes about OCR, receipt/invoice classification, or image content, switch to `approval-attachment-trace.md`.\n\n## Result Summary\n\nUse:\n\n```bash\nseal-use approval-runs result <recordId> --corp <corpId> --summary\n```\n\nThis is for decision, summary, risk point count, matched rule count, trace ID, and record ID.\n\n## Approval Run Web Links & Auto-Login Links\n\nUse this when the user asks for a link to an approval run or wants to open the run directly in their browser:\n\n```bash\n# 默认推荐:生成 Seal AI 审核详情直达链接(无凭证、无越权风险,用户在已有登录状态的浏览器中直接打开)\nseal-use approval-runs link <recordId> --corp <corpId>\nseal-use approval-runs link --sn <sourceDocumentSN> --corp <corpId>\n\n# 生成合思主系统原始单据页面链接\nseal-use approval-runs link <recordId> --type hose-document --corp <corpId>\n\n# 仅当用户明确要求免密/跨浏览器/无登录直达且确认知晓安全风险时:生成携带合思单次临时票据的免登直达链接\nseal-use approval-runs link <recordId> --auto-login [--expire 7200] --corp <corpId>\n```\n\n### 返回字段说明与语义规范\n- `sealResultUrl`: Seal AI 单据智能审核结果页\n- `hoseDocumentUrl`: 合思费控主系统原始报销/借款单详情页\n- `type`: 链接类型,默认为 `seal_result`,指定时可为 `hose_document`\n- `mode`: 鉴权模式,`direct`(原生直接打开)或 `auto_login`(免密换票)\n\n### 免登链接安全与声明规范\n当向用户返回 `--auto-login` 链接时 Line truncated
`;var Og0=()=>{};var Bg0="# Approval Run Lightweight Queries\n\nUse this reference when the user gives a 合思/易快报单号, source document SN, record ID, simulation batch ID, or asks for an approval decision without needing the full raw run payload.\n\n## Locate A Run By Document Number\n\nPrefer `pick` before broad search + bridge + get.\n\n```bash\nseal-use approval-runs pick --corp <corpId> --sn <sourceDocumentSN> --latest\nseal-use approval-runs pick --corp <corpId> --sn <sourceDocumentSN> --batch <batchId> --latest\nseal-use approval-runs pick --corp <corpId> --sn <sourceDocumentSN> --latest --fields recordId,sourceDocumentSN,status,aiDecision,aiSummary\n```\n\nDefault output is intentionally small: `recordId`, `sourceDocumentSN`, `sourceDocumentId`, `simulationBatchId`, `status`, `taskMode`, `ruleSetVersionNumber`, `langfuseTraceId`, `manualResult`, `aiDecision`, and `aiSummary`.\n\nIf there are multiple candidates and `--latest` was not used, report the candidates and ask which one to inspect.\n\n## Read Compact Run Detail\n\nUse `--summary` for most diagnosis and support questions.\n\n```bash\nseal-use approval-runs get <recordId> --corp <corpId> --summary\n```\n\nUse `--fields` when the user needs a particular slice.\n\n```bash\nseal-use approval-runs get <recordId> --corp <corpId> --fields metadata\nseal-use approval-runs get <recordId> --corp <corpId> --fields document.fields,result.summary\nseal-use approval-runs get <recordId> --corp <corpId> --fields result.summary,result.decision,result.riskPoints\nseal-use approval-runs get <recordId> --corp <corpId> --fields document.keyFields,result,manualApprovalRecord,ruleSetVersionNumber\n```\n\nAvoid full `approval-runs get <recordId>` unless the user specifically needs raw document fields, pipeline logs, invoice rawData, or signed URLs. Prefer `--output-file` for full payloads.\n\n## Understand The Case First\n\nBefore pulling the full document, use:\n\n```bash\nseal-use approval-runs document-summary <recordId> --corp <corpId>\n```\n\nThis is for quick case reading: template/title, key fields, amount, expense type, cost company, payee, invoice summary, attachment names, AI result, and manual result.\n\n## Extract AI-Cited Rules\n\nUse this when the user asks \"AI 用了哪条规则\", \"为什么命中这条\", or needs the rule evidence for a specific run.\n\n```bash\nseal-use approval-runs cited-rules <recordId> --corp <corpId>\n```\n\nReturn and discuss `runtimeRuleId`, `ruleCode`, `versionNumber`, `scope`, `strictness`, `appliedAnalysis`, `checkResult`, and `findings` when present.\n\nIf the user then wants the full text of one cited rule, use `rules get --record-id <recordId> --runtime-id rule-205` from `rule-lightweight.md`.\n\n## Attachments Without Raw Payloads\n\nUse:\n\n```bash\n# 查看附件列表摘要(包含文件名、类型、大小及直链可用性)\nseal-use approval-runs attachments <recordId> --corp <corpId> --summary\n\n# 下载全部附件到本地目录(优先使用 ossSignedUrl 签名直链)\nseal-use approval-runs attachments download <recordId> --all --out-dir ./downloads --corp <corpId>\n\n# 按名称或 fileId 过滤下载单个附件\nseal-use approval-runs attachments download <recordId> --name 发票 --corp <corpId>\n```\n\nThis should be enough for file names, file IDs, mime types, positions, invoice/attachment grouping, and links when available. For customer disputes about OCR, receipt/invoice classification, or image content, switch to `approval-attachment-trace.md`.\n\n## Result Summary\n\nUse:\n\n```bash\nseal-use approval-runs result <recordId> --corp <corpId> --summary\n```\n\nThis is for decision, summary, risk point count, matched rule count, trace ID, and record ID.\n\n## Approval Run Web Links & Auto-Login Links\n\nUse this when the user asks for a link to an approval run or wants to open the run directly in their browser:\n\n```bash\n# 默认推荐:生成 Seal AI 审核详情直达链接(无凭证、无越权风险,用户在已有登录状态的浏览器中直接打开)\nseal-use approval-runs link <recordId> --corp <corpId>\nseal-use approval-runs link --sn <sourceDocumentSN> --corp <corpId>\n\n# 生成合思主系统原始单据页面链接\nseal-use approval-runs link <recordId> --type hose-document --corp <corpId>\n\n# 仅当用户明确要求免密/跨浏览器/无登录直达且确认知晓安全风险时:生成携带合思单次临时票据的免登直达链接\nseal-use approval-runs link <recordId> --auto-login [--expire 7200] --corp <corpId>\n```\n\n### 返回字段说明与语义规范\n- `sealResultUrl`: Seal AI 单据智能审核结果页\n- `hoseDocumentUrl`: 合思费控主系统原始报销/借款单详情页\n- `type`: 链接类型,默认为 `seal_result`,指定时可为 `hose_document`\n- `mode`: 鉴权模式,`direct`(原生直接打开)或 `auto_login`(免密换票)\n\n### 免登链接安全与声明规范\n当向用户返回 `--auto-login` 链接时 Line truncated
Use this low-freedom workflow when the user provides packaged customer feedback from WeChat, screenshots, rejection notifications, a document number, or expected business behavior and wants diagnosis or an approval-rule change.
@@ -1497,7 +1497,7 @@ Do not automatically rerun or resubmit the customer's production document. Run a
- **系统调用凭证账号**:显式说明“周晚容(系统调用凭证账号,由智能助手代执行)”
- **全量规则总数**:核对总数是否变化
- **规则一致性校验**:确认目标规则文本与确认内容 100% 逐字吻合
`;var fS0=()=>{};var iS0=`# Enterprise Onboarding
`;var Tg0=()=>{};var Cg0=`# Enterprise Onboarding
本文是企业接入的唯一决策参考:先识别用户材料,再选择标准入口;不要把输入格式、凭据类型和最终来源混为一谈。
@@ -1656,7 +1656,7 @@ seal-use auth check --corp <discovered-id>
\`\`\`
向用户报告:企业中文名、身份来源、凭据模式和验证是否成功;不要回显秘密或无必要的内部 ID。临时会话过期时说明需要重新获取材料;需要无人值守访问时推荐 Hose 开放平台凭据。
`;var bS0=()=>{};var nS0=`# 第一次接入:看图找到材料
`;var jg0=()=>{};var _g0=`# 第一次接入:看图找到材料
> **【Agent 呈现铁律(Mandatory Image Rule)】**:
> 当向用户提供接入指引或引导用户获取材料时,**Agent 必须将本文档中对应的截图主动按顺序渲染到 Markdown 对话中**(使用图片语法 \`![说明](路径)\`),**绝不允许只讲纯文字步骤!** 真实业务用户必须对照图片界面才能准确找到按钮。
@@ -1743,7 +1743,7 @@ macOS 也可以使用 \`Option + Command + I\`;Windows 常见快捷键是 \`F1
## 安全提醒
协助平台、网页登录、SSO 和浏览器 cURL 都可能携带当前用户的访问权限。只把材料交给正在处理本机接入的可信助手,并在接入完成后关闭或刷新该网页会话。不要把原始 cURL、接入密码或完整截图发送到外部渠道。
`;var cS0=()=>{};var dS0=`# Hose Enterprise Auth
`;var Rg0=()=>{};var Sg0=`# Hose Enterprise Auth
Use this reference for Hose/合思 enterprise configuration and user-facing Hose authorization links.
@@ -1812,7 +1812,7 @@ Important:
3. BOTH a code block (\` \`\`\`text ... \`\`\` \`) for easy copying without accidental default browser redirection, AND a clickable hyperlink.
- **Dedicated CLI Command**: Use \`seal-use auth hose-link --corp <corpId> [--expire <seconds>] [--force]\`. This command directly generates an independent provisional auth link without reading or mutating internal CLI session cache. It supports \`--expire\` (default 7200, e.g. 86400 for 1 day).
- **Seal AI Platform Direct Link**: Use \`seal-use auth link --corp <corpId> [--note <note>]\`. This generates a 24-hour provisional delegation link for the Seal AI audit platform (\`https://*.sealai.cc\`).
`;var pS0=()=>{};var lS0=`# Seal AI 智能审核发布到合思费控 (HoseCloud Deployment)
`;var vg0=()=>{};var gg0=`# Seal AI 智能审核发布到合思费控 (HoseCloud Deployment)
Use this reference when configuring, deploying, or troubleshooting Seal AI smart approval integrations with Hose/合思费控 (界面路径:【智能审核】 $\\to$ 【发布】 $\\to$ 【合思费控】).
@@ -1910,7 +1910,7 @@ seal-use deploy hosecloud status --corp <corpId>
| \`signKey\` | string | 否 | 随机生成 | 集成配置卡片唯一标识,编辑时传入以更新对应配置 |
| \`apiOrigin\` | string | 否 | 自动探测 | \`production\` / \`custom\` |
| \`customApiUrl\` | string | 否 | - | 专属私有云 API 地址(当 \`apiOrigin=custom\` 时必填) |
`;var mS0=()=>{};var rS0=`# Hose Enterprise Initialization & Automated Discovery
`;var hg0=()=>{};var kg0=`# Hose Enterprise Initialization & Automated Discovery
Use this reference for automated Hose/合思 enterprise onboarding, multi-domain probing (including dedicated private cloud domains like 美年大健康), OpenAPI role and staff discovery, and non-TUI safe administrator selection.
@@ -2016,7 +2016,7 @@ seal-use corps hose-staffs --json '{
}'
\`\`\`
* 直接使用指定 ID 完成接入并进行连通性验证。
`;var oS0=()=>{};var aS0=`# Rule Lightweight Queries
`;var yg0=()=>{};var fg0=`# Rule Lightweight Queries
Use this reference when the user wants rule counts, compact rule lists, one rule from a historical version, or approval knowledge search without dumping hundreds of rule descriptions.
@@ -2127,7 +2127,7 @@ Use current search only when the question is about current draft/current knowled
## Output Discipline
If a rule command would return many descriptions or more than about 20 rules, use \`rules count\`, \`rules list --summary\`, \`fields\`, \`snippetOnly\`, or \`--output-file\`. Use \`--full\` only for deliberate exports.
`;var sS0=()=>{};var eS0="# Seal Approval Rule Linter & Quality Validation\n\nUse this reference when analyzing, validating, or linting Seal AI approval rules to detect vague phrasing, missing exception evidence, or formatting defects before publishing.\n\n## Key Principles\n\n- **Default State**: Linter is **disabled by default** in global configuration (`lint.enabled: false`) to avoid unsolicited noise during standard operations.\n- **Doctor Visibility**: `seal-use doctor` audits the rule linter configuration state and active linter name in its health checks, and surfaces a one-click hint (`seal-use config lint enable`) when disabled.\n- **Explicit Triggering**: `seal-use rules lint` always runs regardless of global configuration.\n- **Draft Hook**: When `seal-use config lint enable` is set, `seal_approval_rule_update` outputs real-time diagnostic warnings to `stderr` without mutating `stdout` payloads.\n- **Fault-Tolerant Fallback**: If a custom `.ts` linter file has syntax errors, runtime exceptions, or is missing, the engine logs a warning to `stderr` and **silently falls back to the built-in heuristic linter without failing**.\n\n## CLI Commands\n\n### 1. Lint Current Draft Rules (Whole-RuleSet Scan)\n\n```bash\nseal-use rules lint --corp <corpId>\n```\n\n### 2. Lint Specific Historical Version or Single Rule\n\n```bash\n# Lint rules in published version 16\nseal-use rules lint --version 16 --corp <corpId>\n\n# Lint a specific rule by code (#0038)\nseal-use rules lint --code '#0038' --corp <corpId>\n\n# Summary mode (only show rules with issues)\nseal-use rules lint --summary --corp <corpId>\n```\n\n### 3. Quality Gate for CI / Release\n\n```bash\n# If overall score is below 85, terminates with exit code 1\nseal-use rules lint --min-score 85 --level error --corp <corpId>\n```\n\n### 4. Configure Global Linter Settings\n\n```bash\n# Check status\nseal-use config lint status\n\n# Enable auto lint on rule updates\nseal-use config lint enable --linter builtin --min-score 80\n\n# Disable auto lint\nseal-use config lint disable\n```\n\n## Official Linters\n\n| Linter Name | Scope & Purpose | Aliases |\n| :--- | :--- | :--- |\n| `builtin` | Seal 官方标准校验器:拦截过短描述、主观模糊词与悬空例外条款。 | `default`, `official/builtin` |\n| `strict` | Seal 官方严格风控校验器:强校验字数、刚性定量约束、凭证依据与具体审批人角色。 | `official/strict` |\n| `hlab` | 合思实验室 (HLab) 结构化规则校验器:SOP 四段论结构、三元闭环判定、剥离处置动作与防漏判。 | `hlab-sop`, `hlab-rules`, `hlab-standard`, `official/hlab` |\n\n```bash\n# Inspect available linters\nseal-use rules linters\n\n# Lint rules using HLab SOP standard\nseal-use rules lint --linter hlab --corp <corpId>\n\n# Lint local rule workspace offline with HLab standard\nseal-use rules lint --linter hlab --file ./rules.local.json\n```\n\n## Built-In Detection Rules (`builtin`)\n\n| Code | Level | Description | Recommendation |\n| :--- | :---: | :--- | :--- |\n| `TOO_SHORT` | `error` | Rule description is under 5 characters. | Add concrete conditions and criteria. |\n| `VAGUE_WORD` | `error` | Contains subjective/fuzziness words (`原则上`, `尽量`, `适当`, `酌情`, `一般情况下`, `合理控制`). | Replace with rigid thresholds, enums, or criteria. |\n| `HANGING_EXCEPTION` | `warning` | Exception trigger found (`除非`, `特殊情况`, `经批准`) without verifiable evidence keyword (`备注`, `附件`, `证明`, `邮件`, `截图`). | Specify exact evidence source in invoice/document. |\n\n## HLab SOP Detection Rules (`hlab`)\n\n| Code | Level | Description | Recommendation |\n| :--- | :---: | :--- | :--- |\n| `MISSING_CHECK_METHOD` | `error` | Missing `**检查方法**` section in rule description. | Add `**检查方法**:` specifying fields, vouchers, and normalization logic. |\n| `MISSING_EVAL_STANDARD` | `error` | Missing `**判定标准**` section in rule description. | Add `**判定标准**:` with standard branches. |\n| `INCOMPLETE_TERNARY_BRANCH` | `error` | Incomplete ternary branch under evaluation criteria (missing `PASS`, `FAIL`, or `证据不足`). | Provide complete ternary closure: `- PASS:`, `- FAIL:`, `- 证据不足:`. |\n| `INSUFFICIENT_WITHOUT_MANUAL_REVIEW` | `warning` | `证据不足` branch does not specify escalating to `人工复核`. | Add `转人工复核` at the end of `证据不足` branch. |\n| `DISPOSAL_ACTION_LEAK` | `warning` | Contains whole-bill workflow disposal actions (`驳回单据`, `直接驳回`, `进行提醒`, `退回单据`). | Decouple disposal actions from rule text; rely on rule strictness or platform workflow. |\n| `SCOPE_FALSE_SKIP_PRONE` | `warning` | Scope contains material upload conditions (`若上传了`, `若提供了`, `附件需上传`). | Keep scope pure to business triggers; handle missing materials explicitly in FAIL branch to prevent silent SKIP. |\n| `RISK_SUPPRESSION` | `erroLine truncated
`;var xg0=()=>{};var bg0="# Seal Approval Rule Linter & Quality Validation\n\nUse this reference when analyzing, validating, or linting Seal AI approval rules to detect vague phrasing, missing exception evidence, or formatting defects before publishing.\n\n## Key Principles\n\n- **Default State**: Linter is **disabled by default** in global configuration (`lint.enabled: false`) to avoid unsolicited noise during standard operations.\n- **Doctor Visibility**: `seal-use doctor` audits the rule linter configuration state and active linter name in its health checks, and surfaces a one-click hint (`seal-use config lint enable`) when disabled.\n- **Explicit Triggering**: `seal-use rules lint` always runs regardless of global configuration.\n- **Draft Hook**: When `seal-use config lint enable` is set, `seal_approval_rule_update` outputs real-time diagnostic warnings to `stderr` without mutating `stdout` payloads.\n- **Fault-Tolerant Fallback**: If a custom `.ts` linter file has syntax errors, runtime exceptions, or is missing, the engine logs a warning to `stderr` and **silently falls back to the built-in heuristic linter without failing**.\n\n## CLI Commands\n\n### 1. Lint Current Draft Rules (Whole-RuleSet Scan)\n\n```bash\nseal-use rules lint --corp <corpId>\n```\n\n### 2. Lint Specific Historical Version or Single Rule\n\n```bash\n# Lint rules in published version 16\nseal-use rules lint --version 16 --corp <corpId>\n\n# Lint a specific rule by code (#0038)\nseal-use rules lint --code '#0038' --corp <corpId>\n\n# Summary mode (only show rules with issues)\nseal-use rules lint --summary --corp <corpId>\n```\n\n### 3. Quality Gate for CI / Release\n\n```bash\n# If overall score is below 85, terminates with exit code 1\nseal-use rules lint --min-score 85 --level error --corp <corpId>\n```\n\n### 4. Configure Global Linter Settings\n\n```bash\n# Check status\nseal-use config lint status\n\n# Enable auto lint on rule updates\nseal-use config lint enable --linter builtin --min-score 80\n\n# Disable auto lint\nseal-use config lint disable\n```\n\n## Official Linters\n\n| Linter Name | Scope & Purpose | Aliases |\n| :--- | :--- | :--- |\n| `builtin` | Seal 官方标准校验器:拦截过短描述、主观模糊词与悬空例外条款。 | `default`, `official/builtin` |\n| `strict` | Seal 官方严格风控校验器:强校验字数、刚性定量约束、凭证依据与具体审批人角色。 | `official/strict` |\n| `hlab` | 合思实验室 (HLab) 结构化规则校验器:SOP 四段论结构、三元闭环判定、剥离处置动作与防漏判。 | `hlab-sop`, `hlab-rules`, `hlab-standard`, `official/hlab` |\n\n```bash\n# Inspect available linters\nseal-use rules linters\n\n# Lint rules using HLab SOP standard\nseal-use rules lint --linter hlab --corp <corpId>\n\n# Lint local rule workspace offline with HLab standard\nseal-use rules lint --linter hlab --file ./rules.local.json\n```\n\n## Built-In Detection Rules (`builtin`)\n\n| Code | Level | Description | Recommendation |\n| :--- | :---: | :--- | :--- |\n| `TOO_SHORT` | `error` | Rule description is under 5 characters. | Add concrete conditions and criteria. |\n| `VAGUE_WORD` | `error` | Contains subjective/fuzziness words (`原则上`, `尽量`, `适当`, `酌情`, `一般情况下`, `合理控制`). | Replace with rigid thresholds, enums, or criteria. |\n| `HANGING_EXCEPTION` | `warning` | Exception trigger found (`除非`, `特殊情况`, `经批准`) without verifiable evidence keyword (`备注`, `附件`, `证明`, `邮件`, `截图`). | Specify exact evidence source in invoice/document. |\n\n## HLab SOP Detection Rules (`hlab`)\n\n| Code | Level | Description | Recommendation |\n| :--- | :---: | :--- | :--- |\n| `MISSING_CHECK_METHOD` | `error` | Missing `**检查方法**` section in rule description. | Add `**检查方法**:` specifying fields, vouchers, and normalization logic. |\n| `MISSING_EVAL_STANDARD` | `error` | Missing `**判定标准**` section in rule description. | Add `**判定标准**:` with standard branches. |\n| `INCOMPLETE_TERNARY_BRANCH` | `error` | Incomplete ternary branch under evaluation criteria (missing `PASS`, `FAIL`, or `证据不足`). | Provide complete ternary closure: `- PASS:`, `- FAIL:`, `- 证据不足:`. |\n| `INSUFFICIENT_WITHOUT_MANUAL_REVIEW` | `warning` | `证据不足` branch does not specify escalating to `人工复核`. | Add `转人工复核` at the end of `证据不足` branch. |\n| `DISPOSAL_ACTION_LEAK` | `warning` | Contains whole-bill workflow disposal actions (`驳回单据`, `直接驳回`, `进行提醒`, `退回单据`). | Decouple disposal actions from rule text; rely on rule strictness or platform workflow. |\n| `SCOPE_FALSE_SKIP_PRONE` | `warning` | Scope contains material upload conditions (`若上传了`, `若提供了`, `附件需上传`). | Keep scope pure to business triggers; handle missing materials explicitly in FAIL branch to prevent silent SKIP. |\n| `RISK_SUPPRESSION` | `erroLine truncated
本文档面向 AI Agent 与运维人员,规范从**生产/测试环境搭配接入**、**配置与合思集成自动同步**、**测试环境单据模拟验证**,到**生产规则安全投产**的端到端标准工作流。
@@ -2342,10 +2342,10 @@ flowchart TD
seal-use tool seal_approval_rules_publish --corp <prodCorpId> --json '{"versionName":"审核规则 版本N"}'
\`\`\`
发布后核实版本状态,完成业务安全闭环。
`;var $g0=()=>{};var iy1="iVBORw0KGgoAAAANSUhEUgAADVgAAAdwCAYAAACUWcTmAAAAAXNSR0IArs4c6QAAAERlWElmTU0AKgAAAAgAAYdpAAQAAAABAAAAGgAAAAAAA6ABAAMAAAABAAEAAKACAAQAAAABAAANWKADAAQAAAABAAAHcAAAAAD4n9OGAABAAElEQVR4AeydB4AdVfX/z246pNAD0hK6dOki0rsU+dMJJVIFRYoUFUFAQUCqgHSkxx8gTRCpFkB6CU06SQi9BEhC+u7/fu7b83J3dt7bt33f5nuStzNz5947M583c+fOvPO9p6Y+mMlEQAREQAREQAREQAREQAREQAREQAREQAREQAREQAREQAREQAREQAREQAREQAREQAREQAREQAREQAREQAREQAREQAREQAREQAREQAREYA4kUDsHHrMOWQREQAREQAREQAREQAREQAREQAREQAREQAREQAREQAREQAREQAREQAREQAREQAREQAREQAREQAREQAREQAREQAREQAREQAREQAREQAQigd7jxo8TChEQAREQAREQAREQAREQAREQAREQAREQAREQAREQAREQAREQAREQAREQAREQAREQAREQAREQAREQAREQAREQAREQAREQAREQAREQARGYIwkogtUc+bXroEVABERABERABERABERABERABERABERABERABERABERABERABERABERABERABERABERABERABERABERABERABERABERABERABERABCBQUx9MKERABERABERABERABERABERABERABERABERABERABERABERABESgqwiMHz/eBgwY0FWb13ZFQAREQAREQAREQAREQAREQAREQAREQAREQAREQAREQAREQATmcAKKYDWHnwA6fBEQAREQAREQAREQAREQAREQAREQAREQAREQAREQAREQAREQAREQAREQAREQAREQAREQAREQAREQAREQAREQAREQAREQAREQARGYkwlIYDUnf/s6dhEQAREQAREQAREQAREQAREQAREQAREQAREQAREQAREQAREQAREQAREQAREQAREQAREQAREQAREQAREQAREQAREQAREQAREQARGYwwlIYDWHnwA6fBEQAREQAREQAREQAREQAREQAREQAREQAREQAREQAREQAREQAREQAREQAREQAREQAREQAREQAREQAREQAREQAREQAREQAREQARGYkwlIYDUnf/s6dhEQAREQAREQAREQAREQAREQAREQAREQAREQAREQAREQAREQAREQAREQAREQAREQAREQAREQAREQAREQAREQAREQAREQAREQARGYwwlIYDWHnwA6fBEQAREQAREQAREQAREQAREQAREQAREQAREQAREQAREQAREQAREQAREQAREQAREQAREQAREQAREQAREQAREQAREQAREQAREQARGYkwn0npMPXscuAiIgAiIgAiIgAiIgAiIgAiIgAiIgAiIgAiIgAiIgAiIgAiIgAiIgAiIgAiIgAiIgAiIgAiIgAiIgAiIgAiIgAiIgAiIgAj2RwP8+n26vfjbd3vpyho2fPN0+mjLTJs+qs/qaOhvYp8YWGtDLFh/U25YZ3NdWnr+/rTDvgJ6IQcckAhURqKkPVlFOZRIBERABERABERABERABERABERABERABERABERABERABERABERCBDiAwfvx4GzBAP9p2AFpVKQIiIAIiIAIiIAIiIAIiIAIiIAIiIAIiIAIiIAIiMIcR+GhSnT347lT713tT7eOpM4OYqj5+LEzNEFdZ+MyKU5Zr4jLp9fat/r1ss28NtM0WG2KLzN1nDiOnw53TCUhgNaefATp+ERABERABERABERABERABERABERABERABERABERABERABEehiAhJYdfEXoM2LgAiIgAiIgAiIgAiIgAiIgAiIgAiIgAiIgAiIgAhUPYFJ08z+7+Updsc7U8OxFARURKqyIKAqCKnqbVYQUdU2CK7iOiuIr4oirLBcgxArfHZZcrDttcwCNnefXlXPRgcgApUQkMCqEkrKIwIiIAIiIAIiIAIiIAIiIAIiIAIiIAIiIAIiIAIiIAIiIAIi0GEEJLDqMLSqWAREQAREQAREQAREQAREQAREQAREQAREQAREQAREYA4g8MR7M+2Cp6fY5JmFSFQhRlUQStUVBVUsF0VUCKiSSFZEsKqLkawa5yH/oN5mP195qK0/dPAcQFGHOKcTkMBqTj8DdPwiIAIiIAIiIAIiIAIiIAIiIAIiIAIiIAIiIAIiIAIiIAIi0MUEJLDq4i+gCzY/ZcqUuNUBAwZ0wda1SREQAREQAREQAREQAREQAREQAREQAREQAREQARHoHAKd8S501AszbNT/psXIUwWhVDi2IK6qj5GriGRVEE4RlSoVWlUayYry+w2fx0Yst1DnQNNWRKCLCAQ9oUwEREAEREAEREAEREAEREAEREAEREAEREAEREAEREAEREAEREAEREAEREAEREAEREAEREAEREAEREAEREAEREAEREAEREAERKCaCFz035n20JgZ1stqQowqs9qaWmJVBR1VbRBZkdLLakN0qiCzCtMGgVXMURfW1YQsTHsFEdasMC0UCSWjOIvcbte++6V9MX2mHb7ytzypS6e/+93v7H//+1/uPuy888727W9/O35yMyhRBEoQ4NyXiYAIiIAIiIAIiIAIiIAIiIAIiIAIiIAIiIAIiIAIiIAIiIAIiECPIXDbbbfZiBEjGh0PP7aSxif90dXzks68G3k8P2VTYznNm67TvAiIgAiIgAiIgAiIgAiIgAiIgAiIgAiIgAiIgAiIgAh0BoGLHp1lD74zM6qh6kK4qprwqW+YMl9TR1pYHcRWtUFHhZaqLi6TFsJbhflCOYRVtbG818H6+KGOhnr+9v4ku/DlDzrj0Mpug/fz6Xv+bOa//vWvxkcmAi0loAhWLSWm/CIgAiIgAiIgAiIgAiIgAiIgAiIgAiIgAiIgAiIgAiIgAiIgAt2WAD+sdvQPp/xwy0cjYHbb00A7JgIiIAIiIAIiIAIiIAIiIAIiIAIiIAIiIAIiIAI9msCo5+rt4XdDVKoaIlfVxChVHHCMPtXoyIO4KuSoy0ayqifOFeWJUxVqSCJZfW/hwfbox1/FuqiKHF4zIqt5+39qey+zYEztij/pbwC8p0/NhVc+TddpXgSaIyCBVXOEtF4EREAEREAEREAEREAEREAEREAEREAEREAEREAEREAEREAERKBqCLz66qudtq/8iPvrX/+607aX3VBniMluvPHG7Ga1LAIiIAIiIAIiIAIiIAIiIAIiIAIiIAIiIAIiUIJAzT+vi2vqN9m3RA4li0DbCTw5xuyWl+qMIFQWIk8Rpqo+Cq1YDlKokL7m4v2D7IrFOgurwvqwoiaEsIpyKebNHv9wki+FdERaSKlq7fytlrEj73vLHvvoq7gNUkM4q1BPKBTque7tCbbUoH62/tDBrOkyQ1yVfUf/u9/9rmx0qy7b2VZu2H8H4FhXXHFF+3//7/+1siYVq4RATX2wSjIqjwiIgAiIgAiIgAiIgAiIgAiIgAiIgAiIgAiIgAiIgAiIgAiIgAh0BIHx48fbgAEDOqLqHlun/6ja0QfYUQKrKVOmxF3X997R36DqFwEREAEREAEREAEREAEREAEREAEREAER6EwCs074btxcr9Me78zNalvdmEB7vwudNM3ssFvNJs2oi0KqWUE0FQVUUUiF6KreLtx5QVtt0X5lqYz+cIodevfYkKcg1KpHfBXKHvadobbvdxay0R9NsgPveyOsD3KTWiQniLjCNHyYDgqhfq7bcCmbu0+vsttpy0rEUlgqLErfje+8885NBEepwMrXE83Ko16ldbVl3zqjbHqsvj0EZdmoXb5O07YTUASrtjNUDSIgAiIgAiIgAiIgAiIgAiIgAiIgAiIgAiIgAiIgAiIgAiIgAiLQqQQ6M1JXpx5YD96Yj3sZR3ntwcdZyaHNmDHDPv74Y1t00UULo95WUqiL8syaNct69eo4J5EuOqwu3Szff58+fZrsg66RJkiU0MkEGJ4YhzSZCHQmAdpEjHtNbW0Ydb4djHvX9OnTNYBBA0ucWfv169dufNvhK+oxVUydOtXq6upsrrnm6jHHpAMRAREQAREQgbYS8OhV1FN/1VFWc8B5ba2yWJ6+45gxY+ytt96y/v3729JLL22LLbZYbj+H9y4u6ilWUGJm7rnntgUXXDCu/frrr+2LL74okbNxMv3XJZZYonFia5fGjLaad0e3tnSx3JwSNezmZ2ts8vQQTSr8C9KoOA2Sp8ChJvyttQPXG9SsuMqh1VEslIviqTBdf5G5o7iK1NUWHmg/XW1Ru/iF960+aK8QVbE1j2SFwOumtz6zg749lOztbqlQygVSCIuYL2cIqDwPoirepfsy5ZgnLRv5qlydXbUu73cAjqka9h1mCMSw1kbdamv5uPEW/pHAqoXAlF0EREAEREAEREAEREAEREAEREAEREAEREAEREAEREAEREAEREAEuppA+oNwR0WZ6upj7Enbf+ONN+yUU06Jh3Tsscfa6quv3pMOLx7Lhx9+aMcff3yc33vvvW3LLbfMPcZbbrnF7rjjjrjuF7/4ha2yyiq5+dLEyZMn24QJE2zhhRe23r1720svvWTnn39+zPLLX/7SlllmmTR77jyORb/61a/iuv3339++973v5eZLE99++2076aSTbNlll7UtttiiojJp+WqZHz16dBQ84XziNnPmTPv00099sUVTHLMGDx6cW2bcuHHRAWSzzTazHXfc0eaZZ56Y7/HHH7eLLroozh933HG21FJL2Zlnnmm77LJLm6+Xb775xr766qvc/ckmzjvvvNFJLZveluWzzz7b3nrzTVty2DDjfG2JTZs2ze677z7bZpttGonSvvzyy4od5bLb4zqqJqHnxxNmWcHZK3skLV/u16fG5huUL2B5cPRUO Line truncated
`,"utf8"),{detected:z,configured:!0,configPath:U,targetDir:Y,action:"created"};let I={};try{I=JSON.parse(Ig0(U,"utf8"))}catch{I={entries:[]}}if(!Array.isArray(I.entries))I.entries=[];if(I.entries.findIndex((K)=>K&&typeof K.path==="string"&&K.path===Y)!==-1)return{detected:z,configured:!0,configPath:U,targetDir:Y,action:"already_present"};let J=I.entries.findIndex((K)=>K&&typeof K.path==="string"&&(K.path==="~/.agents/skills"||K.path==="~/.agents/skills/"));if(J!==-1)return I.entries[J]={...I.entries[J],path:Y},Co(U,JSON.stringify(I,null,2)+`
`,"utf8"),{detected:z,configured:!0,configPath:U,targetDir:Y,action:"updated_tilde"};return I.entries.unshift({path:Y}),Co(U,JSON.stringify(I,null,2)+`
`,"utf8"),{detected:z,configured:!0,configPath:U,targetDir:Y,action:"prepended"}}function vo($){let Y=$?.targetSkillsDir??Qg0(),U=$?.configFile??Jg0(),z=Kg0(),I=!1;if(fq(U))try{let Q=JSON.parse(Ig0(U,"utf8"));if(Array.isArray(Q?.entries))I=Q.entries.some((J)=>J?.path===Y)}catch{}return{detected:z,configured:I,configPath:U,targetDir:Y}}var ho=()=>{};import{cpSync as ry1,existsSync as nK,lstatSync as Hg0,mkdirSync as sy1,realpathSync as $Y,rmSync as ay1,symlinkSync as ty1,unlinkSync as Gg0}from"node:fs";import{homedir as Wg0}from"node:os";import{dirname as Xg0,join as YY}from"node:path";function ey1($,Y){let U=Y?.baseHomeDir??Wg0(),z=YY(U,$.rootDirName),I=Y?.sourceSkillDir??YY(U,".agents","skills","seal-use"),Q=Xg0(I),J=YY(z,"skills"),K=YY(J,"seal-use");if(!nK(z))return{id:$.id,name:$.name,detected:!1,configured:!1,mode:"skipped_not_detected"};if(nK(J)&&nK(Q))try{if($Y(J)===$Y(Q))return{id:$.id,name:$.name,detected:!0,configured:!0,mode:"parent_symlinked",targetPath:J}}catch{}sy1(J,{recursive:!0});let G;try{G=Hg0(K)}catch{G=void 0}let H=!1;if(G)if(G.isSymbolicLink()){try{if($Y(K)===$Y(I))return{id:$.id,name:$.name,detected:!0,configured:!0,mode:"already_linked",targetPath:K}}catch{}try{Gg0(K)}catch{}}else if(G.isDirectory())ay1(K,{recursive:!0,force:!0}),H=!0;else Gg0(K);let W=process.platform==="win32"?"junction":"dir";try{return ty1(I,K,W),{id:$.id,name:$.name,detected:!0,configured:!0,mode:H?"replaced_real_dir":"linked",targetPath:K}}catch{try{return ry1(I,K,{recursive:!0}),{id:$.id,name:$.name,detected:!0,configured:!0,mode:"fallback_copied",targetPath:K}}catch(X){return{id:$.id,name:$.name,detected:!0,configured:!1,mode:"error",targetPath:K,error:X?.message||String(X)}}}}function $k1($,Y){let U=Y?.baseHomeDir??Wg0(),z=YY(U,$.rootDirName),I=Y?.sourceSkillDir??YY(U,".agents","skills","seal-use"),Q=Xg0(I),J=YY(z,"skills"),K=YY(J,"seal-use");if(!nK(z))return{id:$.id,name:$.name,detected:!1,configured:!1,mode:"not_detected"};if(nK(J)&&nK(Q))try{if($Y(J)===$Y(Q))return{id:$.id,name:$.name,detected:!0,configured:!0,mode:"parent_symlinked",targetPath:J}}catch{}let G;try{G=Hg0(K)}catch{G=void 0}if(G){if(G.isSymbolicLink())try{if($Y(K)===$Y(I))return{id:$.id,name:$.name,detected:!0,configured:!0,mode:"single_symlinked",targetPath:K}}catch{}else if(G.isDirectory())return{id:$.id,name:$.name,detected:!0,configured:!0,mode:"real_directory",targetPath:K}}return{id:$.id,name:$.name,detected:!0,configured:!1,mode:"not_configured",targetPath:K}}function So($){return Zg0.map((Y)=>ey1(Y,$))}function go($){return Zg0.map((Y)=>$k1(Y,$))}var Zg0;var yo=m(()=>{Zg0=[{id:"workbuddy",name:"WorkBuddy",rootDirName:".workbuddy"},{id:"claude",name:"Claude",rootDirName:".claude"},{id:"qoder",name:"Qoder",rootDirName:".qoder"}]});var ko=m(()=>{ho();yo();ho();yo()});import{existsSync as Yk1,mkdirSync as xo,readFileSync as Uk1,rmSync as zk1,writeFileSync as qg0}from"node:fs";import{homedir as Lg0}from"node:os";import{dirname as Vg0,join as bq}from"node:path";function fo(){return Fg0["SKILL.md"]||""}function wg0($){return $.match(/^\s*version:\s*(\S+)\s*$/m)?.[1]}function Mg0($=bq(iz(),"SKILL.md")){try{return wg0(Uk1($,"utf8"))}catch{return}}function iz(){return bq(Lg0(),".agents","skills","seal-use")}function Qk1(){return bq(Lg0(),".agents","skills","seal-home")}function Jk1(){let $=Qk1();if(Yk1($))try{return zk1($,{recursive:!0,force:!0}),!0}catch{return!1}return!1}function Og0($=iz()){Jk1(),xo($,{recursive:!0});let Y=[];for(let[U,z]of Object.entries(Fg0)){let I=bq($,U);xo(Vg0(I),{recursive:!0}),qg0(I,z,"utf8"),Y.push(U)}for(let[U,z]of Object.entries(Ik1)){let I=bq($,U);xo(Vg0(I),{recursive:!0}),qg0(I,z),Y.push(U)}return{targetDir:$,files:Y}}var Fg0,Ik1,Oz4;var iq=m(()=>{Eo();Eo();ko();Fg0=Ug0,Ik1=Object.fromEntries(Object.entries(zg0).map(([$,Y])=>[$,Buffer.from(Y,"base64")]));Oz4=wg0(fo())});function Ng0(){return`# Seal Use 系统架构与运行规范白皮书
`;var ig0=()=>{};var Gx1="iVBORw0KGgoAAAANSUhEUgAADVgAAAdwCAYAAACUWcTmAAAAAXNSR0IArs4c6QAAAERlWElmTU0AKgAAAAgAAYdpAAQAAAABAAAAGgAAAAAAA6ABAAMAAAABAAEAAKACAAQAAAABAAANWKADAAQAAAABAAAHcAAAAAD4n9OGAABAAElEQVR4AeydB4AdVfX/z246pNAD0hK6dOki0rsU+dMJJVIFRYoUFUFAQUCqgHSkxx8gTRCpFkB6CU06SQi9BEhC+u7/fu7b83J3dt7bt33f5nuStzNz5947M583c+fOvPO9p6Y+mMlEQAREQAREQAREQAREQAREQAREQAREQAREQAREQAREQAREQAREQAREQAREQAREQAREQAREQAREQAREQAREQAREQAREQAREQAREQAREYA4kUDsHHrMOWQREQAREQAREQAREQAREQAREQAREQAREQAREQAREQAREQAREQAREQAREQAREQAREQAREQAREQAREQAREQAREQAREQAREQAREQAREQAQigd7jxo8TChEQAREQAREQAREQAREQAREQAREQAREQAREQAREQAREQAREQAREQAREQAREQAREQAREQAREQAREQAREQAREQAREQAREQAREQAREQARGYIwkogtUc+bXroEVABERABERABERABERABERABERABERABERABERABERABERABERABERABERABERABERABERABERABERABERABERABERABERABERABCBQUx9MKERABERABERABERABERABERABERABERABERABERABERABERABESgqwiMHz/eBgwY0FWb13ZFQAREQAREQAREQAREQAREQAREQAREQAREQAREQAREQAREQATmcAKKYDWHnwA6fBEQAREQAREQAREQAREQAREQAREQAREQAREQAREQAREQAREQAREQAREQAREQAREQAREQAREQAREQAREQAREQAREQAREQAREQARGYkwlIYDUnf/s6dhEQAREQAREQAREQAREQAREQAREQAREQAREQAREQAREQAREQAREQAREQAREQAREQAREQAREQAREQAREQAREQAREQAREQAREQARGYwwlIYDWHnwA6fBEQAREQAREQAREQAREQAREQAREQAREQAREQAREQAREQAREQAREQAREQAREQAREQAREQAREQAREQAREQAREQAREQAREQAREQARGYkwlIYDUnf/s6dhEQAREQAREQAREQAREQAREQAREQAREQAREQAREQAREQAREQAREQAREQAREQAREQAREQAREQAREQAREQAREQAREQAREQAREQARGYwwlIYDWHnwA6fBEQAREQAREQAREQAREQAREQAREQAREQAREQAREQAREQAREQAREQAREQAREQAREQAREQAREQAREQAREQAREQAREQAREQAREQARGYkwn0npMPXscuAiIgAiIgAiIgAiIgAiIgAiIgAiIgAiIgAiIgAiIgAiIgAiIgAiIgAiIgAiIgAiIgAiIgAiIgAiIgAiIgAiIgAiIgAiIgAj2RwP8+n26vfjbd3vpyho2fPN0+mjLTJs+qs/qaOhvYp8YWGtDLFh/U25YZ3NdWnr+/rTDvgJ6IQcckAhURqKkPVlFOZRIBERABERABERABERABERABERABERABERABERABERABERABERCBDiAwfvx4GzBAP9p2AFpVKQIiIAIiIAIiIAIiIAIiIAIiIAIiIAIiIAIiIAIiMIcR+GhSnT347lT713tT7eOpM4OYqj5+LEzNEFdZ+MyKU5Zr4jLp9fat/r1ss28NtM0WG2KLzN1nDiOnw53TCUhgNaefATp+ERABERABERABERABERABERABERABERABERABERABERABEehiAhJYdfEXoM2LgAiIgAiIgAiIgAiIgAiIgAiIgAiIgAiIgAiIgAhUPYFJ08z+7+Updsc7U8OxFARURKqyIKAqCKnqbVYQUdU2CK7iOiuIr4oirLBcgxArfHZZcrDttcwCNnefXlXPRgcgApUQkMCqEkrKIwIiIAIiIAIiIAIiIAIiIAIiIAIiIAIiIAIiIAIiIAIiIAIi0GEEJLDqMLSqWAREQAREQAREQAREQAREQAREQAREQAREQAREQAREYA4g8MR7M+2Cp6fY5JmFSFQhRlUQStUVBVUsF0VUCKiSSFZEsKqLkawa5yH/oN5mP195qK0/dPAcQFGHOKcTkMBqTj8DdPwiIAIiIAIiIAIiIAIiIAIiIAIiIAIiIAIiIAIiIAIiIAIi0MUEJLDq4i+gCzY/ZcqUuNUBAwZ0wda1SREQAREQAREQAREQAREQAREQAREQAREQAREQARHoHAKd8S501AszbNT/psXIUwWhVDi2IK6qj5GriGRVEE4RlSoVWlUayYry+w2fx0Yst1DnQNNWRKCLCAQ9oUwEREAEREAEREAEREAEREAEREAEREAEREAEREAEREAEREAEREAEREAEREAEREAEREAEREAEREAEREAEREAEREAEREAEREAERKCaCFz035n20JgZ1stqQowqs9qaWmJVBR1VbRBZkdLLakN0qiCzCtMGgVXMURfW1YQsTHsFEdasMC0UCSWjOIvcbte++6V9MX2mHb7ytzypS6e/+93v7H//+1/uPuy888727W9/O35yMyhRBEoQ4NyXiYAIiIAIiIAIiIAIiIAIiIAIiIAIiIAIiIAIiIAIiIAIiIAIiECPIXDbbbfZiBEjGh0PP7aSxif90dXzks68G3k8P2VTYznNm67TvAiIgAiIgAiIgAiIgAiIgAiIgAiIgAiIgAiIgAiIgAh0BoGLHp1lD74zM6qh6kK4qprwqW+YMl9TR1pYHcRWtUFHhZaqLi6TFsJbhflCOYRVtbG818H6+KGOhnr+9v4ku/DlDzrj0Mpug/fz6Xv+bOa//vWvxkcmAi0loAhWLSWm/CIgAiIgAiIgAiIgAiIgAiIgAiIgAiIgAiIgAiIgAiIgAiIgAt2WAD+sdvQPp/xwy0cjYHbb00A7JgIiIAIiIAIiIAIiIAIiIAIiIAIiIAIiIAIiIAI9msCo5+rt4XdDVKoaIlfVxChVHHCMPtXoyIO4KuSoy0ayqifOFeWJUxVqSCJZfW/hwfbox1/FuqiKHF4zIqt5+39qey+zYEztij/pbwC8p0/NhVc+TddpXgSaIyCBVXOEtF4EREAEREAEREAEREAEREAEREAEREAEREAEREAEREAEREAERKBqCLz66qudtq/8iPvrX/+607aX3VBniMluvPHG7Ga1LAIiIAIiIAIiIAIiIAIiIAIiIAIiIAIiIAIiUIJAzT+vi2vqN9m3RA4li0DbCTw5xuyWl+qMIFQWIk8Rpqo+Cq1YDlKokL7m4v2D7IrFOgurwvqwoiaEsIpyKebNHv9wki+FdERaSKlq7fytlrEj73vLHvvoq7gNUkM4q1BPKBTque7tCbbUoH62/tDBrOkyQ1yVfUf/u9/9rmx0qy7b2VZu2H8H4FhXXHFF+3//7/+1siYVq4RATX2wSjIqjwiIgAiIgAiIgAiIgAiIgAiIgAiIgAiIgAiIgAiIgAiIgAiIgAh0BIHx48fbgAEDOqLqHlun/6ja0QfYUQKrKVOmxF3X997R36DqFwEREAEREAEREAEREAEREAEREAEREAER6EwCs074btxcr9Me78zNalvdmEB7vwudNM3ssFvNJs2oi0KqWUE0FQVUUUiF6KreLtx5QVtt0X5lqYz+cIodevfYkKcg1KpHfBXKHvadobbvdxay0R9NsgPveyOsD3KTWiQniLjCNHyYDgqhfq7bcCmbu0+vsttpy0rEUlgqLErfje+8885NBEepwMrXE83Ko16ldbVl3zqjbHqsvj0EZdmoXb5O07YTUASrtjNUDSIgAiIgAiIgAiIgAiIgAiIgAiIgAiIgAiIgAiIgAiIgAiIgAiLQqQQ6M1JXpx5YD96Yj3sZR3ntwcdZyaHNmDHDPv74Y1t00UULo95WUqiL8syaNct69eo4J5EuOqwu3Szff58+fZrsg66RJkiU0MkEGJ4YhzSZCHQmAdpEjHtNbW0Ydb4djHvX9OnTNYBBA0ucWfv169dufNvhK+oxVUydOtXq6upsrrnm6jHHpAMRAREQAREQgbYS8OhV1FN/1VFWc8B5ba2yWJ6+45gxY+ytt96y/v3729JLL22LLbZYbj+H9y4u6ilWUGJm7rnntgUXXDCu/frrr+2LL74okbNxMv3XJZZYonFia5fGjLaad0e3tnSx3JwSNezmZ2ts8vQQTSr8C9KoOA2Sp8ChJvyttQPXG9SsuMqh1VEslIviqTBdf5G5o7iK1NUWHmg/XW1Ru/iF960+aK8QVbE1j2SFwOumtz6zg749lOztbqlQygVSCIuYL2cIqDwPoirepfsy5ZgnLRv5qlydXbUu73cAjqka9h1mCMSw1kbdamv5uPEW/pHAqoXAlF0EREAEREAEREAEREAEREAEREAEREAEREAEREAEREAEREAEREAEuppA+oNwR0WZ6upj7Enbf+ONN+yUU06Jh3Tsscfa6quv3pMOLx7Lhx9+aMcff3yc33vvvW3LLbfMPcZbbrnF7rjjjrjuF7/4ha2yyiq5+dLEyZMn24QJE2zhhRe23r1720svvWTnn39+zPLLX/7SlllmmTR77jyORb/61a/iuv3339++973v5eZLE99++2076aSTbNlll7UtttiiojJp+WqZHz16dBQ84XziNnPmTPv00099sUVTHLMGDx6cW2bcuHHRAWSzzTazHXfc0eaZZ56Y7/HHH7eLLroozh933HG21FJL2Zlnnmm77LJLm6+Xb775xr766qvc/ckmzjvvvNFJLZveluWzzz7b3nrzTVty2DDjfG2JTZs2ze677z7bZpttGonSvvzyy4od5bLb4zqqJqHnxxNmWcHZK3skLV/u16fG5huUL2B5cPRUO Line truncated
`,"utf8"),{detected:I,configured:!0,configPath:U,targetDir:Y,action:"created"};let Q={};try{Q=JSON.parse(pg0(U,"utf8"))}catch{Q={entries:[]}}if(!Array.isArray(Q.entries))Q.entries=[];if(Q.entries.findIndex((z)=>z&&typeof z.path==="string"&&z.path===Y)!==-1)return{detected:I,configured:!0,configPath:U,targetDir:Y,action:"already_present"};let K=Q.entries.findIndex((z)=>z&&typeof z.path==="string"&&(z.path==="~/.agents/skills"||z.path==="~/.agents/skills/"));if(K!==-1)return Q.entries[K]={...Q.entries[K],path:Y},no(U,JSON.stringify(Q,null,2)+`
`,"utf8"),{detected:I,configured:!0,configPath:U,targetDir:Y,action:"updated_tilde"};return Q.entries.unshift({path:Y}),no(U,JSON.stringify(Q,null,2)+`
`,"utf8"),{detected:I,configured:!0,configPath:U,targetDir:Y,action:"prepended"}}function lo($){let Y=$?.targetSkillsDir??mg0(),U=$?.configFile??lg0(),I=og0(),Q=!1;if(dq(U))try{let J=JSON.parse(pg0(U,"utf8"));if(Array.isArray(J?.entries))Q=J.entries.some((K)=>K?.path===Y)}catch{}return{detected:I,configured:Q,configPath:U,targetDir:Y}}var oo=()=>{};import{cpSync as Fx1,existsSync as mz,lstatSync as sg0,mkdirSync as wx1,realpathSync as YY,rmSync as Mx1,symlinkSync as Ox1,unlinkSync as rg0}from"node:fs";import{homedir as ag0}from"node:os";import{dirname as tg0,join as UY}from"node:path";function Nx1($,Y){let U=Y?.baseHomeDir??ag0(),I=UY(U,$.rootDirName),Q=Y?.sourceSkillDir??UY(U,".agents","skills","seal-use"),J=tg0(Q),K=UY(I,"skills"),z=UY(K,"seal-use");if(!mz(I))return{id:$.id,name:$.name,detected:!1,configured:!1,mode:"skipped_not_detected"};if(mz(K)&&mz(J))try{if(YY(K)===YY(J))return{id:$.id,name:$.name,detected:!0,configured:!0,mode:"parent_symlinked",targetPath:K}}catch{}wx1(K,{recursive:!0});let G;try{G=sg0(z)}catch{G=void 0}let H=!1;if(G)if(G.isSymbolicLink()){try{if(YY(z)===YY(Q))return{id:$.id,name:$.name,detected:!0,configured:!0,mode:"already_linked",targetPath:z}}catch{}try{rg0(z)}catch{}}else if(G.isDirectory())Mx1(z,{recursive:!0,force:!0}),H=!0;else rg0(z);let W=process.platform==="win32"?"junction":"dir";try{return Ox1(Q,z,W),{id:$.id,name:$.name,detected:!0,configured:!0,mode:H?"replaced_real_dir":"linked",targetPath:z}}catch{try{return Fx1(Q,z,{recursive:!0}),{id:$.id,name:$.name,detected:!0,configured:!0,mode:"fallback_copied",targetPath:z}}catch(X){return{id:$.id,name:$.name,detected:!0,configured:!1,mode:"error",targetPath:z,error:X?.message||String(X)}}}}function Dx1($,Y){let U=Y?.baseHomeDir??ag0(),I=UY(U,$.rootDirName),Q=Y?.sourceSkillDir??UY(U,".agents","skills","seal-use"),J=tg0(Q),K=UY(I,"skills"),z=UY(K,"seal-use");if(!mz(I))return{id:$.id,name:$.name,detected:!1,configured:!1,mode:"not_detected"};if(mz(K)&&mz(J))try{if(YY(K)===YY(J))return{id:$.id,name:$.name,detected:!0,configured:!0,mode:"parent_symlinked",targetPath:K}}catch{}let G;try{G=sg0(z)}catch{G=void 0}if(G){if(G.isSymbolicLink())try{if(YY(z)===YY(Q))return{id:$.id,name:$.name,detected:!0,configured:!0,mode:"single_symlinked",targetPath:z}}catch{}else if(G.isDirectory())return{id:$.id,name:$.name,detected:!0,configured:!0,mode:"real_directory",targetPath:z}}return{id:$.id,name:$.name,detected:!0,configured:!1,mode:"not_configured",targetPath:z}}function ro($){return eg0.map((Y)=>Nx1(Y,$))}function so($){return eg0.map((Y)=>Dx1(Y,$))}var eg0;var ao=m(()=>{eg0=[{id:"workbuddy",name:"WorkBuddy",rootDirName:".workbuddy"},{id:"claude",name:"Claude",rootDirName:".claude"},{id:"qoder",name:"Qoder",rootDirName:".qoder"}]});var to=m(()=>{oo();ao();oo();ao()});import{existsSync as Bx1,mkdirSync as eo,readFileSync as Ax1,rmSync as Px1,writeFileSync as $y0}from"node:fs";import{homedir as Uy0}from"node:os";import{dirname as Yy0,join as mq}from"node:path";function $r(){return Iy0["SKILL.md"]||""}function Qy0($){return $.match(/^\s*version:\s*(\S+)\s*$/m)?.[1]}function Jy0($=mq(cI(),"SKILL.md")){try{return Qy0(Ax1($,"utf8"))}catch{return}}function cI(){return mq(Uy0(),".agents","skills","seal-use")}function Ex1(){return mq(Uy0(),".agents","skills","seal-home")}function jx1(){let $=Ex1();if(Bx1($))try{return Px1($,{recursive:!0,force:!0}),!0}catch{return!1}return!1}function Ky0($=cI()){jx1(),eo($,{recursive:!0});let Y=[];for(let[U,I]of Object.entries(Iy0)){let Q=mq($,U);eo(Yy0(Q),{recursive:!0}),$y0(Q,I,"utf8"),Y.push(U)}for(let[U,I]of Object.entries(Tx1)){let Q=mq($,U);eo(Yy0(Q),{recursive:!0}),$y0(Q,I),Y.push(U)}return{targetDir:$,files:Y}}var Iy0,Tx1,xZ4;var lq=m(()=>{co();co();to();Iy0=ng0,Tx1=Object.fromEntries(Object.entries(dg0).map(([$,Y])=>[$,Buffer.from(Y,"base64")]));xZ4=Qy0($r())});function zy0(){return`# Seal Use 系统架构与运行规范白皮书
> 本文档由 \`seal-use\` 单文件二进制程序内嵌提供,纯内存只读,未向用户电脑写入任何临时文件。
@@ -2368,14 +2368,14 @@ flowchart TD
| 目录名称 | 类别 | 规范路径 | 作用与生命周期 |
| :--- | :--- | :--- | :--- |
${uo.map(($)=>`| **${$.name}** | \`${$.category}\` | \`${$.standardPath}\` | ${$.purpose} (${$.retention}) |`).join(`
${Yr.map(($)=>`| **${$.name}** | \`${$.category}\` | \`${$.standardPath}\` | ${$.purpose} (${$.retention}) |`).join(`
`)}
---
## 3. 安全与数据隐私保证
${bo.map(($,Y)=>`### 3.${Y+1} ${$.topic}
${Ur.map(($,Y)=>`### 3.${Y+1} ${$.topic}
- **安全承诺**:${$.guarantee}
- **实现约束**:${$.enforcement}
`).join(`
@@ -2385,7 +2385,7 @@ ${bo.map(($,Y)=>`### 3.${Y+1} ${$.topic}
## 4. 业务域能力图谱
${io.map(($)=>`### \`seal-use ${$.domain}\`
${Ir.map(($)=>`### \`seal-use ${$.domain}\`
* **能力定位**:${$.summary}
* **核心命令**:${$.primaryCommands.map((Y)=>`\`seal-use ${Y}\``).join("、")}
`).join(`
@@ -2398,14 +2398,14 @@ ${io.map(($)=>`### \`seal-use ${$.domain}\`
- **环境自检**:运行 \`seal-use doctor\`,一键检查当前运行时版本、本地目录健康度、企业资产接入数量以及守护服务状态。
- **查看企业配置源文件**:运行 \`seal-use corps get <corpId>\`,可直接查看指定企业的本地 JSON 存储绝对路径。
- **查阅完整操作手册**:运行 \`seal-use doctor guide\` 随时在离线状态下查看本文档。
`}var uo,bo,io;var co=m(()=>{uo=[{name:"配置与状态根目录",category:"config",standardPath:"~/.config/seal-use",purpose:"用户本地持久化配置根目录,存放企业连接元数据、会话缓存与全局状态。",accessMode:"read-write",retention:"persistent"},{name:"企业配置文件目录",category:"config",standardPath:"~/.config/seal-use/enterprises",purpose:"存放各已添加企业的配置 JSON 文件(如 xiezihao.json),存储企业域名、脱敏 Token、员工绑定关系等。",accessMode:"read-write",retention:"persistent"},{name:"全局配置文件",category:"config",standardPath:"~/.config/seal-use/config.json",purpose:"维护全局工作模式(stateful/stateless)、默认激活企业 defaultCorpId 以及 Lint 偏好。",accessMode:"read-write",retention:"persistent"},{name:"会话凭据安全缓存",category:"config",standardPath:"~/.config/seal-use/seal_tokens.json",purpose:"缓存已认证租户的 Bearer Token 与过期时间戳,避免高频调用上游 OAuth 换票接口。",accessMode:"read-write",retention:"cache"},{name:"规则版本映射快照",category:"config",standardPath:"~/.config/seal-use/mappings",purpose:"存储 corps sync-test 生成的生产与测试规则版本/编号对照映射快照,供 rules map 离线毫秒级速查。",accessMode:"read-write",retention:"persistent"},{name:"后台守护服务日志",category:"config",standardPath:"~/.config/seal-use/service.log",purpose:"常驻后台 HTTP 服务守护进程运行输出日志。",accessMode:"read-write",retention:"persistent"},{name:"全局命令行程序",category:"binary",standardPath:"/opt/homebrew/bin/seal-use",purpose:"macOS / Linux 全局独立单文件二进制程序;旧版 seal-home 命令仅保留解析兼容,不再新建全局别名。",accessMode:"executable",retention:"persistent"},{name:"AI Agent 技能主目录",category:"skill",standardPath:"~/.agents/skills/seal-use",purpose:"面向 Antigravity、Codex 等 AI 智能体的标准技能目录,包含 SKILL.md、参考文档与操作规程。",accessMode:"read-write",retention:"persistent"},{name:"报表默认导出目录",category:"export",standardPath:"~/Downloads",purpose:"执行 approval-runs export 等大盘报表命令且未指定 --out 时,默认写入的 Excel 文件路径。",accessMode:"read-write",retention:"persistent"},{name:"系统隔离临时目录",category:"temp",standardPath:"/tmp 或 /var/folders/.../T",purpose:"自动化测试(bun test)生成的隔离工作副本,执行完毕后通过 afterEach 钩子彻底删除,零残留。",accessMode:"transient",retention:"ephemeral"}],bo=[{topic:"敏感凭据脱敏保护",guarantee:"appSecurity、password 等高危密钥永不回显在 stdout,Session Token 采用掩码处理(如 5oUL...Y%3D)。",enforcement:"CLI 所有展示接口(corps get、corps list、probe 等)均经 formatSafeSourceDetail 脱敏过滤。"},{topic:"正式环境与测试环境严格隔离",guarantee:"正式企业与测试企业必须严格 1 对 1 下挂,禁止多层级级联绑定;环境标记需显式 --confirm 确认。",enforcement:"corps bind-test 与 mark 强制要求 --confirm,缺少时阻断并返回退出码 10(confirmationRequired)。"},{topic:"跨环境规则同步安全基线",guarantee:"corps sync-test 仅将正式企业偏好与规则覆盖同步至测试企业并自动发布,正式企业规则严格维持草稿态永不发布。",enforcement:"规则同步流水线由 sync-test 独占受控,正式环境端仅执行拉取草稿读取操作,零发版变更。"},{topic:"只读诊断无副作用原则",guarantee:"doctor、search、get、list、context、probe 等命令为严格只读操作,不修改用户本地文件系统,零写入污染。",enforcement:"核心领域函数严格分离 Mutation 操作与 Query 操作,Query 路径杜绝写文件与环境篡改。"}],io=[{domain:"corps (企业管理)",summary:"多租户接入、智能软搜索、富属性查看、环境标记、测试绑定与配置规则同步",primaryCommands:["corps list","corps search <query>","corps get <corpId>","corps mark","corps bind-test","corps sync-test"]},{domain:"approval-runs (审核大盘)",summary:"AI 审核单据检索、统计分析、引证规则查看、附件全链路追踪、Excel 报表导出、单据直达链接与免登",primaryCommands:["approval-runs list","approval-runs stats","approval-runs get","approval-runs export","approval-runs link"]},{domain:"rules (规则治理)",summary:"审核规则拉取、本地 Lint 质量检查、增量差量推送、离线版本与编号对照映射速查",primaryCommands:["rules pull","rules lint","rules push","rules map","rules count"]},{domain:"preference (决策偏好)",summary:"AI 审核偏好读取与更新、全局与分品类思考深度策略(medium/high)配置",primaryCommands:["preference get","preference decision update","preference thinking-depth set"]},{domain:"simulation (模拟演练)",summary:"合 Line truncated
`)}var Tg0=m(()=>{ip();z3();T5();iq();UP();co()});var jg0={};T8(jg0,{formatTenantDoctorDashboard:()=>qk1,diagnoseTenantContract:()=>Zk1});async function Zk1($,Y){let U=[],z=Y.environment==="test"?"test":"production",I=z==="test"?Y.prodCorpId:Y.testCorpId,Q=z==="test"?"prodParent":"testTarget",J=I?z==="test"?"已绑定生产母企业 (上游配置与样本源)":"已绑定测试靶场 (下游隔离演练环境)":void 0,K=null,G=null;try{let F=await Z8($);if(K=F.user,G=F.tenant,Boolean(K?.isAdmin||K?.permissions?.includes("*")))U.push({id:"auth_identity",name:"身份与权限契约",status:"pass",summary:`已认证为管理员「${K.name??"未知"}」(${K.id??""}),具备完整操作权限`,details:{userId:K.id,userName:K.name,isAdmin:!0,permissionLevel:"超级管理员(具备完整操作权限)",tenantName:G?.name,tenantSlug:G?.tenantSlug,permissions:K.permissions}});else U.push({id:"auth_identity",name:"身份与权限契约",status:"warn",summary:`已认证为普通用户「${K.name??"未知"}」,非超级管理员,部分配置操作可能受限`,details:{userId:K.id,userName:K.name,isAdmin:!1,permissionLevel:"普通用户(部分管理配置受限)",tenantName:G?.name,permissions:K.permissions},recommendation:"建议使用具有管理权限的企业主账号执行规则修改与集成发布"})}catch(F){U.push({id:"auth_identity",name:"身份与权限契约",status:"fail",summary:`鉴权握手失败:${F instanceof Error?F.message:String(F)}`,details:{error:String(F)},recommendation:`请执行 seal-use auth login --corp ${Y.id} 重新登录或更新 Token`})}let H={featureCode:"ai-approval",balance:0,deductionAmount:120,estimatedRuns:0,status:"exhausted"},W={used:0,remaining:0};try{let F=await lY($),N=Array.isArray(F.features)?F.features:[],O=N.find((P)=>P?.code==="ai-approval");if(O){let P=typeof O.balance==="number"?O.balance:0,T=typeof O.deductionAmount==="number"&&O.deductionAmount>0?O.deductionAmount:120,A=Math.floor(P/T);if(H.balance=P,H.deductionAmount=T,H.estimatedRuns=A,P<=0)H.status="exhausted",U.push({id:"billing_quota",name:"AI 审批额度余量",status:"fail",summary:"当前额度已耗尽 (余量 0 点),无法执行审批模拟或回归测试",details:{balance:P,deductionAmount:T,estimatedRuns:A},recommendation:`请前往后台充值补充额度 (可通过 seal-use auth link --corp ${Y.id} 免密直达)`});else if(A<10)H.status="low",U.push({id:"billing_quota",name:"AI 审批额度余量",status:"warn",summary:`额度偏低:剩余 ${P} 点 (单笔扣除 ${T} 点),仅可支持约 ${A} 笔审核`,details:{balance:P,deductionAmount:T,estimatedRuns:A},recommendation:`建议补充额度 (可通过 seal-use auth link --corp ${Y.id} 免密直达)`});else H.status="sufficient",U.push({id:"billing_quota",name:"AI 审批额度余量",status:"pass",summary:`额度充裕:剩余 ${P} 点,预估可支持 ${A} 笔审核单据`,details:{balance:P,deductionAmount:T,estimatedRuns:A}})}else U.push({id:"billing_quota",name:"AI 审批额度余量",status:"warn",summary:"未检索到「ai-approval」功能包额度明细,按默认通道运行",details:{features:N.map((P)=>P?.code)}});let D=N.find((P)=>P?.code==="approval-rules");if(D)W.used=typeof D.used==="number"?D.used:0,W.remaining=typeof D.remaining==="number"?D.remaining:0}catch(F){U.push({id:"billing_quota",name:"AI 审批额度余量",status:"warn",summary:`读取计费状态失败:${F instanceof Error?F.message:String(F)}`,details:{error:String(F)}})}let X={totalCount:0,activeCount:0,quotaUsed:W.used,quotaRemaining:W.remaining};try{let F=await W6($),N=Array.isArray(F.rules)?F.rules:[];if(X.totalCount=N.length,X.activeCount=N.filter((O)=>O.status==="ACTIVE").length,N.length===0)U.push({id:"rules_status",name:"审核规则状态",status:"warn",summary:"当前租户未配置任何审核规则 (规则数为 0)",details:{totalCount:0,activeCount:0},recommendation:z==="test"&&I?`可运行 seal-use corps sync-test --corp ${I} 从生产企业同步规则`:"可运行 seal-use rules add 创建基础规则"});else U.push({id:"rules_status",name:"审核规则状态",status:"pass",summary:`审核规则健康:共 ${X.totalCount} 条规则,其中生效活跃 ${X.activeCount} 条`,details:{totalCount:X.totalCount,activeCount:X.activeCount,quotaUsed:W.used,quotaRemaining:W.remaining}})}catch(F){U.push({id:"rules_status",name:"审核规则状态",status:"fail",summary:`拉取规则列表失败:${F instanceof Error?F.message:String(F)}`,details:{error:String(F)}})}let Z={integrationCount:0,hasReplayChannel:!1,activeWebhookId:void 0};try{let F=await K$($);Z.integrationCount=F.length;let N=F.find((O)=>O.name.includes("回放")||O.name.toLowerCase().includes("replay"));if(Z.hasReplayChannel=Boolean(N),Z.activeWebhookId=N?.id??F[0]?.id,F.length===0)U.push({id:"webhook_integrations",name:"单据推送 Webhook 通道",status:"pass",summary:"未配置任何 Webhook 集成通道 (日常审批无影响;若需自动化系统推流或单据重放将 Line truncated
`)}var Eg0=m(()=>{X6()});async function Cg0($,Y,U){let z=($??Y??"").toLowerCase();if(z==="guide"||z==="doc"||z==="knowledge"||z==="book"){console.error(`\uD83D\uDCD6 [Seal Use Doctor] 正在读取内嵌系统规范白皮书(纯内存只读)...
`),console.log(Ng0());return}if(z==="paths"||z==="dirs"||z==="directories"){let J=no();R0(J.directories);return}if(z==="auth"){let{selectCorp:J}=await Promise.resolve().then(() => (O4(),Yo)),{stringOption:K}=await Promise.resolve().then(() => (Z4(),tl)),{handleAuthCommand:G}=await Promise.resolve().then(() => (jo(),qS0)),H=K(U.options.corp)??(Y&&Y!==z?Y:void 0)??(U.command[2]&&U.command[2]!==z?U.command[2]:void 0),W=J(H);await G("check",W,U);return}if(z==="tenant"||z==="corp"||z==="enterprise"){let{selectCorp:J}=await Promise.resolve().then(() => (O4(),Yo)),{createSealClient:K}=await Promise.resolve().then(() => (m6(),H10)),{stringOption:G}=await Promise.resolve().then(() => (Z4(),tl)),{diagnoseTenantContract:H,formatTenantDoctorDashboard:W}=await Promise.resolve().then(() => (Eg0(),jg0)),X=G(U.options.corp)??(Y&&Y!==z?Y:void 0)??(U.command[2]&&U.command[2]!==z?U.command[2]:void 0),Z=J(X),q=await K(Z),V=await H(q,Z);if(!(G0(U.options.quiet)||G0(U.options.silent)))console.error(W(V));R0(V);return}let I=no();if(!(G0(U.options.quiet)||G0(U.options.silent)))console.error(Pg0(I));R0(I)}var Rg0=m(()=>{Tg0();co();Z4();m1()});var vg0;var _g0=m(()=>{vg0={openapi:"3.1.0",info:{title:"seal-use Wrapped API",version:"0.10.38",description:"HTTP contract for the seal-use wrapped backend API, served by the local HTTP adapter\n(`seal-use http`, or the `seal-use service start` daemon; default http://127.0.0.1:8787).\n\nThese endpoints describe the stable wrapped API for frontend developers and agents. They are\nnot the raw downstream Seal endpoints: seal-use is responsible for enterprise selection,\nsource authentication, response compaction, and diagnostics-friendly fields.\n\nEvery operation declares `x-implementation-status`, so a caller can tell what the running\nadapter actually serves:\n\n- `implemented` — routed by `src/http/routes.ts` today. `src/http/openapi-implementation.test.ts`\n fails when an `implemented` operation has no matching route.\n- `planned` — contract-only, designed but not routed yet. Calling it returns 404.\n\nThe same capabilities are reachable through the CLI, and through the optional MCP server when\nit is enabled.\n"},servers:[{url:"http://localhost:8787",description:"Local HTTP adapter (`seal-use http`, or the `seal-use service start` daemon). Loopback-only by default."}],security:[{localSession:[]}],tags:[{name:"Corps",description:"Local enterprise configuration selection."},{name:"Source",description:"Source-derived Seal enterprise configuration."},{name:"Auth",description:"Wrapped authentication diagnostics and current identity."},{name:"Approval Runs",description:"Wrapped approval run history, summaries, document URLs, and trace bridge helpers."},{name:"Approval Knowledge",description:"Wrapped approval rules, documents, preferences, and search."},{name:"Simulation",description:"Wrapped simulation batch record access."}],paths:{"/v1/corps":{get:{tags:["Corps"],operationId:"listCorps","x-implementation-status":"implemented",summary:"List configured enterprises",responses:{"200":{description:"Configured enterprises.",content:{"application/json":{schema:{type:"array",items:{type:"object",required:["id","name","sourceType","current"],properties:{id:{type:"string"},name:{type:"string"},sourceType:{type:"string",enum:["hose","seal"]},current:{type:"boolean"}}}}}}}}}},"/v1/corps/current":{get:{tags:["Corps"],operationId:"getCurrentCorp","x-implementation-status":"planned",summary:"Get current enterprise",description:"Returns the configured default enterprise in stateful mode. Stateless mode has no current enterprise and requires an explicit corpId for enterprise operations.",responses:{"200":{description:"Current enterprise.",content:{"application/json":{schema:{type:"object",required:["id","name","sourceType","current"],properties:{id:{type:"string"},name:{type:"string"},sourceType:{type:"string",enum:["hose","seal"]},current:{type:"boolean"}}}}}}}}},"/v1/corps/current/switch":{post:{tags:["Corps"],operationId:"switchCurrentCorp","x-implementation-status":"planned",summary:"Switch current enterprise",requestBody:{required:!0,content:{"application/json":{schema:{type:"object",required:["corpId"],properties:{corpId:{type:"string"}}}}}},responses:{"200":{description:"Switched enterprise.",content:{"application/json":{schema:{type:"object",required:["current","id","name"],properties:{current:{type:"boolean"},id:{type:"string"},name:{type:"string"}}}}}},"404":{description:"Requested resource was not found.",content:{"application/json":{schema:{type:"object",additionalProperties:!0,required:["error"],properties:{error:{type:"string"},message:{type:"string"},details:{}}}}}}}}},"/v1/source/config":{get:{tags:["Source"],operationId:"getSourceConfig","x-implementation-status":"planned",summary:"Resolve source-derived Seal enterprise config",parameters:[{name:"corpId",in:"query",schema:{type:"string"},description:"Local enterprise config ID. Required when global selection mode is stateless; optional i Line truncated
`}var Yr,Ur,Ir;var Qr=m(()=>{Yr=[{name:"配置与状态根目录",category:"config",standardPath:"~/.config/seal-use",purpose:"用户本地持久化配置根目录,存放企业连接元数据、会话缓存与全局状态。",accessMode:"read-write",retention:"persistent"},{name:"企业配置文件目录",category:"config",standardPath:"~/.config/seal-use/enterprises",purpose:"存放各已添加企业的配置 JSON 文件(如 xiezihao.json),存储企业域名、脱敏 Token、员工绑定关系等。",accessMode:"read-write",retention:"persistent"},{name:"全局配置文件",category:"config",standardPath:"~/.config/seal-use/config.json",purpose:"维护全局工作模式(stateful/stateless)、默认激活企业 defaultCorpId 以及 Lint 偏好。",accessMode:"read-write",retention:"persistent"},{name:"会话凭据安全缓存",category:"config",standardPath:"~/.config/seal-use/seal_tokens.json",purpose:"缓存已认证租户的 Bearer Token 与过期时间戳,避免高频调用上游 OAuth 换票接口。",accessMode:"read-write",retention:"cache"},{name:"规则版本映射快照",category:"config",standardPath:"~/.config/seal-use/mappings",purpose:"存储 corps sync-test 生成的生产与测试规则版本/编号对照映射快照,供 rules map 离线毫秒级速查。",accessMode:"read-write",retention:"persistent"},{name:"后台守护服务日志",category:"config",standardPath:"~/.config/seal-use/service.log",purpose:"常驻后台 HTTP 服务守护进程运行输出日志。",accessMode:"read-write",retention:"persistent"},{name:"全局命令行程序",category:"binary",standardPath:"/opt/homebrew/bin/seal-use",purpose:"macOS / Linux 全局独立单文件二进制程序;旧版 seal-home 命令仅保留解析兼容,不再新建全局别名。",accessMode:"executable",retention:"persistent"},{name:"AI Agent 技能主目录",category:"skill",standardPath:"~/.agents/skills/seal-use",purpose:"面向 Antigravity、Codex 等 AI 智能体的标准技能目录,包含 SKILL.md、参考文档与操作规程。",accessMode:"read-write",retention:"persistent"},{name:"报表默认导出目录",category:"export",standardPath:"~/Downloads",purpose:"执行 approval-runs export 等大盘报表命令且未指定 --out 时,默认写入的 Excel 文件路径。",accessMode:"read-write",retention:"persistent"},{name:"系统隔离临时目录",category:"temp",standardPath:"/tmp 或 /var/folders/.../T",purpose:"自动化测试(bun test)生成的隔离工作副本,执行完毕后通过 afterEach 钩子彻底删除,零残留。",accessMode:"transient",retention:"ephemeral"}],Ur=[{topic:"敏感凭据脱敏保护",guarantee:"appSecurity、password 等高危密钥永不回显在 stdout,Session Token 采用掩码处理(如 5oUL...Y%3D)。",enforcement:"CLI 所有展示接口(corps get、corps list、probe 等)均经 formatSafeSourceDetail 脱敏过滤。"},{topic:"正式环境与测试环境严格隔离",guarantee:"正式企业与测试企业必须严格 1 对 1 下挂,禁止多层级级联绑定;环境标记需显式 --confirm 确认。",enforcement:"corps bind-test 与 mark 强制要求 --confirm,缺少时阻断并返回退出码 10(confirmationRequired)。"},{topic:"跨环境规则同步安全基线",guarantee:"corps sync-test 仅将正式企业偏好与规则覆盖同步至测试企业并自动发布,正式企业规则严格维持草稿态永不发布。",enforcement:"规则同步流水线由 sync-test 独占受控,正式环境端仅执行拉取草稿读取操作,零发版变更。"},{topic:"只读诊断无副作用原则",guarantee:"doctor、search、get、list、context、probe 等命令为严格只读操作,不修改用户本地文件系统,零写入污染。",enforcement:"核心领域函数严格分离 Mutation 操作与 Query 操作,Query 路径杜绝写文件与环境篡改。"}],Ir=[{domain:"corps (企业管理)",summary:"多租户接入、智能软搜索、富属性查看、环境标记、测试绑定与配置规则同步",primaryCommands:["corps list","corps search <query>","corps get <corpId>","corps mark","corps bind-test","corps sync-test"]},{domain:"approval-runs (审核大盘)",summary:"AI 审核单据检索、统计分析、引证规则查看、附件全链路追踪、Excel 报表导出、单据直达链接与免登",primaryCommands:["approval-runs list","approval-runs stats","approval-runs get","approval-runs export","approval-runs link"]},{domain:"rules (规则治理)",summary:"审核规则拉取、本地 Lint 质量检查、增量差量推送、离线版本与编号对照映射速查",primaryCommands:["rules pull","rules lint","rules push","rules map","rules count"]},{domain:"preference (决策偏好)",summary:"AI 审核偏好读取与更新、全局与分品类思考深度策略(medium/high)配置",primaryCommands:["preference get","preference decision update","preference thinking-depth set"]},{domain:"simulation (模拟演练)",summary:"合 Line truncated
`)}var Zy0=m(()=>{Qp();J3();l$();lq();HP();Qr()});async function qy0($,Y){let U=[],I=Y.environment==="test"?"test":"production",Q=I==="test"?Y.prodCorpId:Y.testCorpId,J=I==="test"?"prodParent":"testTarget",K=Q?I==="test"?"已绑定生产母企业 (上游配置与样本源)":"已绑定测试靶场 (下游隔离演练环境)":void 0,z=null,G=null;try{let F=await o6($);if(z=F.user,G=F.tenant,Boolean(z?.isAdmin||z?.permissions?.includes("*")))U.push({id:"auth_identity",name:"身份与权限契约",status:"pass",summary:`已认证为管理员「${z.name??"未知"}」(${z.id??""}),具备完整操作权限`,details:{userId:z.id,userName:z.name,isAdmin:!0,permissionLevel:"超级管理员(具备完整操作权限)",tenantName:G?.name,tenantSlug:G?.tenantSlug,permissions:z.permissions}});else U.push({id:"auth_identity",name:"身份与权限契约",status:"warn",summary:`已认证为普通用户「${z.name??"未知"}」,非超级管理员,部分配置操作可能受限`,details:{userId:z.id,userName:z.name,isAdmin:!1,permissionLevel:"普通用户(部分管理配置受限)",tenantName:G?.name,permissions:z.permissions},recommendation:"建议使用具有管理权限的企业主账号执行规则修改与集成发布"})}catch(F){U.push({id:"auth_identity",name:"身份与权限契约",status:"fail",summary:`鉴权握手失败:${F instanceof Error?F.message:String(F)}`,details:{error:String(F)},recommendation:`请执行 seal-use auth login --corp ${Y.id} 重新登录或更新 Token`})}let H={featureCode:"ai-approval",balance:0,deductionAmount:120,estimatedRuns:0,status:"exhausted"},W={used:0,remaining:0};try{let F=await oY($),N=Array.isArray(F.features)?F.features:[],O=N.find((P)=>P?.code==="ai-approval");if(O){let P=typeof O.balance==="number"?O.balance:0,T=typeof O.deductionAmount==="number"&&O.deductionAmount>0?O.deductionAmount:120,B=Math.floor(P/T);if(H.balance=P,H.deductionAmount=T,H.estimatedRuns=B,P<=0)H.status="exhausted",U.push({id:"billing_quota",name:"AI 审批额度余量",status:"fail",summary:"当前额度已耗尽 (余量 0 点),无法执行审批模拟或回归测试",details:{balance:P,deductionAmount:T,estimatedRuns:B},recommendation:`请前往后台充值补充额度 (可通过 seal-use auth link --corp ${Y.id} 免密直达)`});else if(B<10)H.status="low",U.push({id:"billing_quota",name:"AI 审批额度余量",status:"warn",summary:`额度偏低:剩余 ${P} 点 (单笔扣除 ${T} 点),仅可支持约 ${B} 笔审核`,details:{balance:P,deductionAmount:T,estimatedRuns:B},recommendation:`建议补充额度 (可通过 seal-use auth link --corp ${Y.id} 免密直达)`});else H.status="sufficient",U.push({id:"billing_quota",name:"AI 审批额度余量",status:"pass",summary:`额度充裕:剩余 ${P} 点,预估可支持 ${B} 笔审核单据`,details:{balance:P,deductionAmount:T,estimatedRuns:B}})}else U.push({id:"billing_quota",name:"AI 审批额度余量",status:"warn",summary:"未检索到「ai-approval」功能包额度明细,按默认通道运行",details:{features:N.map((P)=>P?.code)}});let D=N.find((P)=>P?.code==="approval-rules");if(D)W.used=typeof D.used==="number"?D.used:0,W.remaining=typeof D.remaining==="number"?D.remaining:0}catch(F){U.push({id:"billing_quota",name:"AI 审批额度余量",status:"warn",summary:`读取计费状态失败:${F instanceof Error?F.message:String(F)}`,details:{error:String(F)}})}let X={totalCount:0,activeCount:0,quotaUsed:W.used,quotaRemaining:W.remaining};try{let F=await q6($),N=Array.isArray(F.rules)?F.rules:[];if(X.totalCount=N.length,X.activeCount=N.filter((O)=>O.status==="ACTIVE").length,N.length===0)U.push({id:"rules_status",name:"审核规则状态",status:"warn",summary:"当前租户未配置任何审核规则 (规则数为 0)",details:{totalCount:0,activeCount:0},recommendation:I==="test"&&Q?`可运行 seal-use corps sync-test --corp ${Q} 从生产企业同步规则`:"可运行 seal-use rules add 创建基础规则"});else U.push({id:"rules_status",name:"审核规则状态",status:"pass",summary:`审核规则健康:共 ${X.totalCount} 条规则,其中生效活跃 ${X.activeCount} 条`,details:{totalCount:X.totalCount,activeCount:X.activeCount,quotaUsed:W.used,quotaRemaining:W.remaining}})}catch(F){U.push({id:"rules_status",name:"审核规则状态",status:"fail",summary:`拉取规则列表失败:${F instanceof Error?F.message:String(F)}`,details:{error:String(F)}})}let Z={integrationCount:0,hasReplayChannel:!1,activeWebhookId:void 0};try{let F=await Z$($);Z.integrationCount=F.length;let N=F.find((O)=>O.name.includes("回放")||O.name.toLowerCase().includes("replay"));if(Z.hasReplayChannel=Boolean(N),Z.activeWebhookId=N?.id??F[0]?.id,F.length===0)U.push({id:"webhook_integrations",name:"单据推送 Webhook 通道",status:"pass",summary:"未配置任何 Webhook 集成通道 (日常审批无影响;若需自动化系统推流或单据重放将自动创建)",details:{integrationCount:0}});else U.push({id:"webhook_integrations",nam Line truncated
`)}var Ly0=m(()=>{H4()});var Fy0={};Z8(Fy0,{formatTenantDoctorDashboard:()=>Vy0,diagnoseTenantContract:()=>qy0});var wy0=m(()=>{Ly0()});async function My0($,Y,U){let I=($??Y??"").toLowerCase();if(I==="guide"||I==="doc"||I==="knowledge"||I==="book"){console.error(`\uD83D\uDCD6 [Seal Use Doctor] 正在读取内嵌系统规范白皮书(纯内存只读)...
`),console.log(zy0());return}if(I==="paths"||I==="dirs"||I==="directories"){let K=Jr();R0(K.directories);return}if(I==="auth"){let{selectCorp:K}=await Promise.resolve().then(() => (O4(),Fo)),{stringOption:z}=await Promise.resolve().then(() => (q4(),qo)),{handleAuthCommand:G}=await Promise.resolve().then(() => (io(),$g0)),H=z(U.options.corp)??(Y&&Y!==I?Y:void 0)??(U.command[2]&&U.command[2]!==I?U.command[2]:void 0),W=K(H);await G("check",W,U);return}if(I==="tenant"||I==="corp"||I==="enterprise"){let{selectCorp:K}=await Promise.resolve().then(() => (O4(),Fo)),{createSealClient:z}=await Promise.resolve().then(() => (f6(),P10)),{stringOption:G}=await Promise.resolve().then(() => (q4(),qo)),{diagnoseTenantContract:H,formatTenantDoctorDashboard:W}=await Promise.resolve().then(() => (wy0(),Fy0)),X=G(U.options.corp)??(Y&&Y!==I?Y:void 0)??(U.command[2]&&U.command[2]!==I?U.command[2]:void 0),Z=K(X),q=await z(Z),V=await H(q,Z);if(!(G0(U.options.quiet)||G0(U.options.silent)))console.error(W(V));R0(V);return}let Q=Jr();if(!(G0(U.options.quiet)||G0(U.options.silent)))console.error(Xy0(Q));R0(Q)}var Oy0=m(()=>{Zy0();Qr();q4();l1()});var Dy0;var Ny0=m(()=>{Dy0={openapi:"3.1.0",info:{title:"seal-use Wrapped API",version:"0.10.38",description:"HTTP contract for the seal-use wrapped backend API, served by the local HTTP adapter\n(`seal-use http`, or the `seal-use service start` daemon; default http://127.0.0.1:8787).\n\nThese endpoints describe the stable wrapped API for frontend developers and agents. They are\nnot the raw downstream Seal endpoints: seal-use is responsible for enterprise selection,\nsource authentication, response compaction, and diagnostics-friendly fields.\n\nEvery operation declares `x-implementation-status`, so a caller can tell what the running\nadapter actually serves:\n\n- `implemented` — routed by `src/http/routes.ts` today. `src/http/openapi-implementation.test.ts`\n fails when an `implemented` operation has no matching route.\n- `planned` — contract-only, designed but not routed yet. Calling it returns 404.\n\nThe same capabilities are reachable through the CLI, and through the optional MCP server when\nit is enabled.\n"},servers:[{url:"http://localhost:8787",description:"Local HTTP adapter (`seal-use http`, or the `seal-use service start` daemon). Loopback-only by default."}],security:[{localSession:[]}],tags:[{name:"Corps",description:"Local enterprise configuration selection."},{name:"Source",description:"Source-derived Seal enterprise configuration."},{name:"Auth",description:"Wrapped authentication diagnostics and current identity."},{name:"Approval Runs",description:"Wrapped approval run history, summaries, document URLs, and trace bridge helpers."},{name:"Approval Knowledge",description:"Wrapped approval rules, documents, preferences, and search."},{name:"Simulation",description:"Wrapped simulation batch record access."}],paths:{"/v1/corps":{get:{tags:["Corps"],operationId:"listCorps","x-implementation-status":"implemented",summary:"List configured enterprises",responses:{"200":{description:"Configured enterprises.",content:{"application/json":{schema:{type:"array",items:{type:"object",required:["id","name","sourceType","current"],properties:{id:{type:"string"},name:{type:"string"},sourceType:{type:"string",enum:["hose","seal"]},current:{type:"boolean"}}}}}}}}}},"/v1/corps/current":{get:{tags:["Corps"],operationId:"getCurrentCorp","x-implementation-status":"planned",summary:"Get current enterprise",description:"Returns the configured default enterprise in stateful mode. Stateless mode has no current enterprise and requires an explicit corpId for enterprise operations.",responses:{"200":{description:"Current enterprise.",content:{"application/json":{schema:{type:"object",required:["id","name","sourceType","current"],properties:{id:{type:"string"},name:{type:"string"},sourceType:{type:"string",enum:["hose","seal"]},current:{type:"boolean"}}}}}}}}},"/v1/corps/current/switch":{post:{tags:["Corps"],operationId:"switchCurrentCorp","x-implementation-status":"planned",summary:"Switch current enterprise",requestBody:{required:!0,content:{"application/json":{schema:{type:"object",required:["corpId"],properties:{corpId:{type:"string"}}}}}},responses:{"200":{description:"Switched enterprise.",content:{"application/json":{schema:{type:"object",required:["current","id","name"],properties:{current:{type:"boolean"},id:{type:"string"},name:{type:"string"}}}}}},"404":{description:"Requested resource was not found.",content:{"application/json":{schema:{type:"object",additionalProperties:!0,required:["error"],properties:{error:{type:"string"},message:{type:"string"},details:{}}}}}}}}},"/v1/source/config":{get:{tags:["Source"],operationId:"getSourceConfig","x-implementation-status":"planned",summary:"Resolve source-derived Seal enterprise config",parameters:[{name:"corpId",in:"query",schema:{type:"string"},description:"Local enterprise config ID. Required when global selection mode is stateless; optional i Line truncated
the credentials already stored on this machine for the selected enterprise. Keep it bound
to loopback (\`--host 127.0.0.1\`) and do not expose the port to a network or an origin you
do not control.
`}},parameters:{CorpId:{name:"corpId",in:"query",schema:{type:"string"},description:"Local enterprise config ID. Required when global selection mode is stateless; optional in stateful mode, where the configured default enterprise is used."},Offset:{name:"offset",in:"query",schema:{type:"integer",minimum:0,default:0},description:"Zero-based pagination offset."},Limit:{name:"limit",in:"query",schema:{type:"integer",minimum:1,maximum:100,default:50},description:"Maximum number of records to return."},RuleId:{name:"ruleId",in:"path",required:!0,schema:{type:"string"},description:"Approval rule ID."},VersionId:{name:"versionId",in:"path",required:!0,schema:{type:"string"},description:"Published rule version ID."},DocumentId:{name:"documentId",in:"path",required:!0,schema:{type:"string"},description:"Approval knowledge document ID."},RecordId:{name:"recordId",in:"path",required:!0,schema:{type:"string"},description:"seal-use approval run record ID."},BatchId:{name:"batchId",in:"path",required:!0,schema:{type:"string"},description:"Simulation batch ID."}},responses:{BadRequest:{description:"Invalid request.",content:{"application/json":{schema:{type:"object",additionalProperties:!0,required:["error"],properties:{error:{type:"string"},message:{type:"string"},details:{}}}}}},Unauthorized:{description:"Local service authentication failed or downstream Seal auth failed.",content:{"application/json":{schema:{type:"object",additionalProperties:!0,required:["error"],properties:{error:{type:"string"},message:{type:"string"},details:{}}}}}},NotFound:{description:"Requested resource was not found.",content:{"application/json":{schema:{type:"object",additionalProperties:!0,required:["error"],properties:{error:{type:"string"},message:{type:"string"},details:{}}}}}}},schemas:{ErrorResponse:{type:"object",additionalProperties:!0,required:["error"],properties:{error:{type:"string"},message:{type:"string"},details:{}}},CorpSummary:{type:"object",required:["id","name","sourceType","current"],properties:{id:{type:"string"},name:{type:"string"},sourceType:{type:"string",enum:["hose","seal"]},current:{type:"boolean"}}},SwitchCorpRequest:{type:"object",required:["corpId"],properties:{corpId:{type:"string"}}},SwitchCorpResponse:{type:"object",required:["current","id","name"],properties:{current:{type:"boolean"},id:{type:"string"},name:{type:"string"}}},SourceConfig:{type:"object",additionalProperties:!0,description:"Redacted Seal enterprise config resolved from the configured source."},AuthStage:{type:"object",additionalProperties:!0,required:["name","ok"],properties:{name:{type:"string",examples:["hose.openapi","hose.provisional","seal.sso","seal.whoami"]},ok:{type:"boolean"},error:{type:"string"}}},AuthDiagnosis:{type:"object",required:["stages"],properties:{stages:{type:"array",items:{$ref:"#/components/schemas/AuthStage"}}}},SealUser:{type:"object",additionalProperties:!0,required:["id","name"],properties:{id:{type:"string"},tenantId:{type:"string"},name:{type:"string"},isAdmin:{type:"boolean"},permissions:{type:"array",items:{type:"string"}}}},SealTenant:{type:"object",additionalProperties:!0,required:["id","name"],properties:{id:{type:"string"},name:{type:"string"},tenantSlug:{type:"string"}}},WhoamiResponse:{type:"object",required:["user","tenant"],properties:{user:{$ref:"#/components/schemas/SealUser"},tenant:{$ref:"#/components/schemas/SealTenant"}}},SessionResponse:{type:"object",additionalProperties:!0,required:["user","session"],properties:{user:{$ref:"#/components/schemas/SealUser"},session:{type:"object",additionalProperties:!0}}},ApprovalRule:{type:"object",additionalProperties:!0,required:["id","description","scope","strictness"],properties:{id:{type:"string"},description:{type:"string"},scope:{type:"string"},strictness:{type:"string",enum:["MUST_FOLLOW","SHOULD_FOLLOW","SUGGESTION"]},status:{type:"string"}}},ApprovalRuleInput:{type:"object",required:["description","scope","strictness"],properties:{description:{type:"string"},scope:{type:"string"},strictness:{type:"string",enum:["MUST_FOLLOW","SHOULD_FOLLOW","SUGGESTION"]}}},ApprovalRulePatch:{type:"object",additionalProperties:!1,properties:{description:{type:"string"},scope:{type:"string"},strictness:{type:"string",enum:["MUST_FOLLOW","SHOULD_FOLLOW","SUGGESTION"]}}},ApprovalRulesResponse:{type:"object",required:["rules"],properties:{rules:{type:"array",items:{$ref:"#/components/schemas/ApprovalRule"}},hasPendingDeletes:{type:"boolean"}}},RuleSetVersion:{type:"object",additionalProperties:!0,required:["id","versionNumber","versionName","rules"],properties:{id:{type:"string"},versionNumber:{type:"integer"},versionName:{type:"string"},publishedByName:{type:"string"},rules:{type:"array",items:{type:"object",additionalProperties:!0}}}},PublishRuleVersionRequest:{type:"object",required:["versionName"],properties:{versionName:{type:"string"}}},ApprovalDocument:{type:"object",additionalProperties:!0,required:["id","title","content"],properties:{id:{type:"string"},title:{typ Line truncated
`}},parameters:{CorpId:{name:"corpId",in:"query",schema:{type:"string"},description:"Local enterprise config ID. Required when global selection mode is stateless; optional in stateful mode, where the configured default enterprise is used."},Offset:{name:"offset",in:"query",schema:{type:"integer",minimum:0,default:0},description:"Zero-based pagination offset."},Limit:{name:"limit",in:"query",schema:{type:"integer",minimum:1,maximum:100,default:50},description:"Maximum number of records to return."},RuleId:{name:"ruleId",in:"path",required:!0,schema:{type:"string"},description:"Approval rule ID."},VersionId:{name:"versionId",in:"path",required:!0,schema:{type:"string"},description:"Published rule version ID."},DocumentId:{name:"documentId",in:"path",required:!0,schema:{type:"string"},description:"Approval knowledge document ID."},RecordId:{name:"recordId",in:"path",required:!0,schema:{type:"string"},description:"seal-use approval run record ID."},BatchId:{name:"batchId",in:"path",required:!0,schema:{type:"string"},description:"Simulation batch ID."}},responses:{BadRequest:{description:"Invalid request.",content:{"application/json":{schema:{type:"object",additionalProperties:!0,required:["error"],properties:{error:{type:"string"},message:{type:"string"},details:{}}}}}},Unauthorized:{description:"Local service authentication failed or downstream Seal auth failed.",content:{"application/json":{schema:{type:"object",additionalProperties:!0,required:["error"],properties:{error:{type:"string"},message:{type:"string"},details:{}}}}}},NotFound:{description:"Requested resource was not found.",content:{"application/json":{schema:{type:"object",additionalProperties:!0,required:["error"],properties:{error:{type:"string"},message:{type:"string"},details:{}}}}}}},schemas:{ErrorResponse:{type:"object",additionalProperties:!0,required:["error"],properties:{error:{type:"string"},message:{type:"string"},details:{}}},CorpSummary:{type:"object",required:["id","name","sourceType","current"],properties:{id:{type:"string"},name:{type:"string"},sourceType:{type:"string",enum:["hose","seal"]},current:{type:"boolean"}}},SwitchCorpRequest:{type:"object",required:["corpId"],properties:{corpId:{type:"string"}}},SwitchCorpResponse:{type:"object",required:["current","id","name"],properties:{current:{type:"boolean"},id:{type:"string"},name:{type:"string"}}},SourceConfig:{type:"object",additionalProperties:!0,description:"Redacted Seal enterprise config resolved from the configured source."},AuthStage:{type:"object",additionalProperties:!0,required:["name","ok"],properties:{name:{type:"string",examples:["hose.openapi","hose.provisional","seal.sso","seal.whoami"]},ok:{type:"boolean"},error:{type:"string"}}},AuthDiagnosis:{type:"object",required:["stages"],properties:{stages:{type:"array",items:{$ref:"#/components/schemas/AuthStage"}}}},SealUser:{type:"object",additionalProperties:!0,required:["id","name"],properties:{id:{type:"string"},tenantId:{type:"string"},name:{type:"string"},isAdmin:{type:"boolean"},permissions:{type:"array",items:{type:"string"}}}},SealTenant:{type:"object",additionalProperties:!0,required:["id","name"],properties:{id:{type:"string"},name:{type:"string"},tenantSlug:{type:"string"}}},WhoamiResponse:{type:"object",required:["user","tenant"],properties:{user:{$ref:"#/components/schemas/SealUser"},tenant:{$ref:"#/components/schemas/SealTenant"}}},SessionResponse:{type:"object",additionalProperties:!0,required:["user","session"],properties:{user:{$ref:"#/components/schemas/SealUser"},session:{type:"object",additionalProperties:!0}}},ApprovalRule:{type:"object",additionalProperties:!0,required:["id","description","scope","strictness"],properties:{id:{type:"string"},description:{type:"string"},scope:{type:"string"},strictness:{type:"string",enum:["MUST_FOLLOW","SHOULD_FOLLOW","SUGGESTION"]},status:{type:"string"}}},ApprovalRuleInput:{type:"object",required:["description","scope","strictness"],properties:{description:{type:"string"},scope:{type:"string"},strictness:{type:"string",enum:["MUST_FOLLOW","SHOULD_FOLLOW","SUGGESTION"]}}},ApprovalRulePatch:{type:"object",additionalProperties:!1,properties:{description:{type:"string"},scope:{type:"string"},strictness:{type:"string",enum:["MUST_FOLLOW","SHOULD_FOLLOW","SUGGESTION"]}}},ApprovalRulesResponse:{type:"object",required:["rules"],properties:{rules:{type:"array",items:{$ref:"#/components/schemas/ApprovalRule"}},hasPendingDeletes:{type:"boolean"}}},RuleSetVersion:{type:"object",additionalProperties:!0,required:["id","versionNumber","versionName","rules"],properties:{id:{type:"string"},versionNumber:{type:"integer"},versionName:{type:"string"},publishedByName:{type:"string"},rules:{type:"array",items:{type:"object",additionalProperties:!0}}}},PublishRuleVersionRequest:{type:"object",required:["versionName"],properties:{versionName:{type:"string"}}},ApprovalDocument:{type:"object",additionalProperties:!0,required:["id","title","content"],properties:{id:{type:"string"},title:{typ Line truncated
<html lang="zh-CN">
<head>
<meta charset="utf-8" />
@@ -2429,23 +2429,23 @@ do not control.
src="https://cdn.jsdelivr.net/npm/@scalar/api-reference@1.25.101/dist/browser/standalone.js"
></script>
</body>
</html>`}var gg0=m(()=>{z3()});import{URL as Lk1}from"node:url";async function h6($,Y,U,z){let I=$.handler;return I(Y,U,{corp:z})}async function yg0($,Y){if(Y.setHeader("Access-Control-Allow-Origin","*"),Y.setHeader("Access-Control-Allow-Methods","GET, POST, PUT, DELETE, OPTIONS, PATCH"),Y.setHeader("Access-Control-Allow-Headers","Content-Type, Authorization, X-Seal-Corp, X-Seal-Home-Session"),$.method==="OPTIONS"){Y.writeHead(204),Y.end();return}let U=$.headers.host||"localhost",z=$.headers["x-forwarded-proto"]||"http",I=new Lk1($.url||"/",`${z}://${U}`),Q=I.pathname.replace(/\/+$/,"")||"/",J=($.method||"GET").toUpperCase();try{if(J==="GET"&&Q==="/"){B4(Y,200,{name:"seal-use",version:X1,description:"Seal tenant operations and approval automation HTTP API",docs:"/docs",openapi:"/openapi.json",health:"/health",endpoints:{cli:"POST /api/cli",tools:"GET /api/tools",toolInvoke:"POST /api/tool/:name",restV1:"GET/POST /v1/*"}});return}if(J==="GET"&&Q==="/docs"){wk1(Y,200,Sg0());return}if(J==="GET"&&Q==="/openapi.json"){B4(Y,200,Uj());return}if(J==="GET"&&Q==="/health"){B4(Y,200,{status:"ok",version:X1,name:"seal-use",timestamp:new Date().toISOString()});return}if(J==="POST"&&(Q==="/shutdown"||Q==="/api/shutdown")){B4(Y,200,{success:!0,message:"Shutting down seal-use background daemon",pid:process.pid}),setTimeout(()=>{process.kill(process.pid,"SIGTERM")},50);return}if(J==="POST"&&Q==="/api/cli"){let K=await Ij($),G=(typeof K?.command==="string"?K.command:"").trim();if(!G){zj(Y,400,"Missing 'command' property in request body");return}let H=cq(G),W=H[0]==="seal-use"||H[0]==="seal-home"||H[0]?.endsWith("/seal-use")||H[0]?.endsWith("/seal-home")?H.slice(1):H,X=await nq(W),Z=void 0;try{if(X.stdout.trim().startsWith("{")||X.stdout.trim().startsWith("["))Z=JSON.parse(X.stdout)}catch{}B4(Y,X.isError?400:200,{success:!X.isError,stdout:X.stdout,stderr:X.stderr,exitCode:X.exitCode,data:Z});return}if(J==="POST"&&Q.startsWith("/api/tool/")){let K=Q.slice(10).trim(),G=M6(K);if(!G){zj(Y,404,`Tool not found: '${K}'`);return}let H=await Ij($)||{},W=u8($,I,H),X=M1(W),Z=await B1(X),q={...H};delete q.corp;let V=await h6(G,Z,q,X);B4(Y,200,V);return}if(Q.startsWith("/v1/")){if(await Fk1($,Y,J,Q,I))return}zj(Y,404,`Cannot ${J} ${Q}. Visit /docs for available endpoints.`)}catch(K){let G=K instanceof Error?K.message:String(K);zj(Y,500,G)}}async function Fk1($,Y,U,z,I){let Q=Object.fromEntries(I.searchParams.entries());if(U==="GET"&&z==="/v1/corps"){let J=t8(),K=v4();return B4(Y,200,{count:J.length,mode:K.stateful?"stateful":"stateless",defaultCorpId:K.defaultCorpId,corps:J.map((G)=>({id:G.id,name:G.name,sourceType:G.source.type,sealUrl:G.seal?.url}))}),!0}if(U==="GET"&&z==="/v1/whoami"){let J=u8($,I,Q),K=M1(J),G=await B1(K),H=M6("seal_whoami"),W=await h6(H,G,{},K);return B4(Y,200,W),!0}if(U==="GET"&&z==="/v1/session"){let J=u8($,I,Q),K=M1(J),G=await B1(K),H=M6("seal_session_get"),W=await h6(H,G,{},K);return B4(Y,200,W),!0}if(U==="GET"&&z==="/v1/approval-runs/summary"){let J=u8($,I,Q),K=M1(J),G=await B1(K),H=M6("seal_approval_runs_summary"),W=await h6(H,G,Q,K);return B4(Y,200,W),!0}if(U==="GET"&&z==="/v1/approval-runs/stats"){let J=u8($,I,Q),K=M1(J),G=await B1(K),H=M6("seal_approval_runs_stats"),W=await h6(H,G,Q,K);return B4(Y,200,W),!0}if(U==="GET"&&z==="/v1/approval-runs/pick"){let J=u8($,I,Q),K=M1(J),G=await B1(K),H=M6("seal_approval_run_pick"),W=await h6(H,G,Q,K);return B4(Y,200,W),!0}if(U==="GET"&&z==="/v1/approval-runs/url"){let J=u8($,I,Q),K=M1(J),G=await B1(K),H=M6("seal_approval_run_url_get"),W=await h6(H,G,Q,K);return B4(Y,200,W),!0}if(z.startsWith("/v1/approval-runs/")){let J=z.slice(18).split("/"),K=J[0],G=J[1];if(K&&!["summary","pick","stats","url","bridge"].includes(K)){let H=u8($,I,Q),W=M1(H),X=await B1(W);if(!G){let Z=M6("seal_approval_run_get"),q=await h6(Z,X,{recordId:K,...Q},W);return B4(Y,200,q),!0}if(G==="attachments"){let Z=M6("seal_approval_run_attachments_get"),q=await h6(Z,X,{recordId:K,...Q},W);return B4(Y,200,q),!0}if(G==="cited-rules"){let Z=M6("seal_approval_run_cited_rules_get"),q=await h6(Z,X,{recordId:K,...Q},W);return B4(Y,200,q),!0}if(G==="document-summary"){let Z=M6("seal_approval_run_document_summary_get"),q=await h6(Z,X,{recordId:K,...Q},W);return B4(Y,200,q),!0}if(G==="result"){let Z=M6("seal_approval_run_result_get"),q=await h6(Z,X,{recordId:K,...Q},W);return B4(Y,200,q),!0}}}if(U==="GET"&&z==="/v1/approval-runs"){let J=u8($,I,Q),K=M1(J),G=await B1(K),H=M6("seal_approval_runs_search"),W=await h6(H,G,{...Q,limit:Q.limit?Number(Q.limit):void 0,offset:Q.offset?Number(Q.offset):void 0,includeBridge:Q.includeBridge==="true"},K);return B4(Y,200,W),!0}if(U==="GET"&&z==="/v1/approval/rules"){let J=u8($,I,Q),K=M1(J),G=await B1(K),H=M6("seal_approval_rules_list"),W=await h6(H,G,Q,K);return B4(Y,200,W),!0}if(U==="GET"&&z==="/v1/simulation/batches"){let J=u8($,I,Q),K=M1(J),G=await B1(K),H=M6("seal_simulation_batches_list"),W=await h6(H,G,Q,K);return B4(Y,200,W),!0}if(U==="POST"&&z==="/v1/simulation/create-batchLine truncated
</html>`}var Py0=m(()=>{J3()});import{URL as gx1}from"node:url";async function g6($,Y,U,I){let Q=$.handler;return Q(Y,U,{corp:I})}async function Ty0($,Y){if(Y.setHeader("Access-Control-Allow-Origin","*"),Y.setHeader("Access-Control-Allow-Methods","GET, POST, PUT, DELETE, OPTIONS, PATCH"),Y.setHeader("Access-Control-Allow-Headers","Content-Type, Authorization, X-Seal-Corp, X-Seal-Home-Session"),$.method==="OPTIONS"){Y.writeHead(204),Y.end();return}let U=$.headers.host||"localhost",I=$.headers["x-forwarded-proto"]||"http",Q=new gx1($.url||"/",`${I}://${U}`),J=Q.pathname.replace(/\/+$/,"")||"/",K=($.method||"GET").toUpperCase();try{if(K==="GET"&&J==="/"){T4(Y,200,{name:"seal-use",version:X1,description:"Seal tenant operations and approval automation HTTP API",docs:"/docs",openapi:"/openapi.json",health:"/health",endpoints:{cli:"POST /api/cli",tools:"GET /api/tools",toolInvoke:"POST /api/tool/:name",restV1:"GET/POST /v1/*"}});return}if(K==="GET"&&J==="/docs"){kx1(Y,200,Ay0());return}if(K==="GET"&&J==="/openapi.json"){T4(Y,200,HE());return}if(K==="GET"&&J==="/health"){T4(Y,200,{status:"ok",version:X1,name:"seal-use",timestamp:new Date().toISOString()});return}if(K==="POST"&&(J==="/shutdown"||J==="/api/shutdown")){T4(Y,200,{success:!0,message:"Shutting down seal-use background daemon",pid:process.pid}),setTimeout(()=>{process.kill(process.pid,"SIGTERM")},50);return}if(K==="POST"&&J==="/api/cli"){let z=await XE($),G=(typeof z?.command==="string"?z.command:"").trim();if(!G){WE(Y,400,"Missing 'command' property in request body");return}let H=oq(G),W=H[0]==="seal-use"||H[0]==="seal-home"||H[0]?.endsWith("/seal-use")||H[0]?.endsWith("/seal-home")?H.slice(1):H,X=await rq(W),Z=void 0;try{if(X.stdout.trim().startsWith("{")||X.stdout.trim().startsWith("["))Z=JSON.parse(X.stdout)}catch{}T4(Y,X.isError?400:200,{success:!X.isError,stdout:X.stdout,stderr:X.stderr,exitCode:X.exitCode,data:Z});return}if(K==="POST"&&J.startsWith("/api/tool/")){let z=J.slice(10).trim(),G=N6(z);if(!G){WE(Y,404,`Tool not found: '${z}'`);return}let H=await XE($)||{},W=c8($,Q,H),X=M1(W),Z=await A1(X),q={...H};delete q.corp;let V=await g6(G,Z,q,X);T4(Y,200,V);return}if(J.startsWith("/v1/")){if(await yx1($,Y,K,J,Q))return}WE(Y,404,`Cannot ${K} ${J}. Visit /docs for available endpoints.`)}catch(z){let G=z instanceof Error?z.message:String(z);WE(Y,500,G)}}async function yx1($,Y,U,I,Q){let J=Object.fromEntries(Q.searchParams.entries());if(U==="GET"&&I==="/v1/corps"){let K=Y$(),z=A4();return T4(Y,200,{count:K.length,mode:z.stateful?"stateful":"stateless",defaultCorpId:z.defaultCorpId,corps:K.map((G)=>({id:G.id,name:G.name,sourceType:G.source.type,sealUrl:G.seal?.url}))}),!0}if(U==="GET"&&I==="/v1/whoami"){let K=c8($,Q,J),z=M1(K),G=await A1(z),H=N6("seal_whoami"),W=await g6(H,G,{},z);return T4(Y,200,W),!0}if(U==="GET"&&I==="/v1/session"){let K=c8($,Q,J),z=M1(K),G=await A1(z),H=N6("seal_session_get"),W=await g6(H,G,{},z);return T4(Y,200,W),!0}if(U==="GET"&&I==="/v1/approval-runs/summary"){let K=c8($,Q,J),z=M1(K),G=await A1(z),H=N6("seal_approval_runs_summary"),W=await g6(H,G,J,z);return T4(Y,200,W),!0}if(U==="GET"&&I==="/v1/approval-runs/stats"){let K=c8($,Q,J),z=M1(K),G=await A1(z),H=N6("seal_approval_runs_stats"),W=await g6(H,G,J,z);return T4(Y,200,W),!0}if(U==="GET"&&I==="/v1/approval-runs/pick"){let K=c8($,Q,J),z=M1(K),G=await A1(z),H=N6("seal_approval_run_pick"),W=await g6(H,G,J,z);return T4(Y,200,W),!0}if(U==="GET"&&I==="/v1/approval-runs/url"){let K=c8($,Q,J),z=M1(K),G=await A1(z),H=N6("seal_approval_run_url_get"),W=await g6(H,G,J,z);return T4(Y,200,W),!0}if(I.startsWith("/v1/approval-runs/")){let K=I.slice(18).split("/"),z=K[0],G=K[1];if(z&&!["summary","pick","stats","url","bridge"].includes(z)){let H=c8($,Q,J),W=M1(H),X=await A1(W);if(!G){let Z=N6("seal_approval_run_get"),q=await g6(Z,X,{recordId:z,...J},W);return T4(Y,200,q),!0}if(G==="attachments"){let Z=N6("seal_approval_run_attachments_get"),q=await g6(Z,X,{recordId:z,...J},W);return T4(Y,200,q),!0}if(G==="cited-rules"){let Z=N6("seal_approval_run_cited_rules_get"),q=await g6(Z,X,{recordId:z,...J},W);return T4(Y,200,q),!0}if(G==="document-summary"){let Z=N6("seal_approval_run_document_summary_get"),q=await g6(Z,X,{recordId:z,...J},W);return T4(Y,200,q),!0}if(G==="result"){let Z=N6("seal_approval_run_result_get"),q=await g6(Z,X,{recordId:z,...J},W);return T4(Y,200,q),!0}}}if(U==="GET"&&I==="/v1/approval-runs"){let K=c8($,Q,J),z=M1(K),G=await A1(z),H=N6("seal_approval_runs_search"),W=await g6(H,G,{...J,limit:J.limit?Number(J.limit):void 0,offset:J.offset?Number(J.offset):void 0,includeBridge:J.includeBridge==="true"},z);return T4(Y,200,W),!0}if(U==="GET"&&I==="/v1/approval/rules"){let K=c8($,Q,J),z=M1(K),G=await A1(z),H=N6("seal_approval_rules_list"),W=await g6(H,G,J,z);return T4(Y,200,W),!0}if(U==="GET"&&I==="/v1/simulation/batches"){let K=c8($,Q,J),z=M1(K),G=await A1(z),H=N6("seal_simulation_batches_list"),W=await g6(H,G,J,z);return T4(Y,200,W),!0}if(U==="POST"&&I==="/v1/simulation/create-batchLine truncated
\uD83D\uDE80 seal-use HTTP Server (v${X1}) started`),console.error(` URL: http://${U}:${Y}`),console.error(` Docs: http://${U}:${Y}/docs`),console.error(` OpenAPI: http://${U}:${Y}/openapi.json`),console.error(` CLI Exec: POST http://${U}:${Y}/api/cli`),console.error(` REST API: http://${U}:${Y}/v1/...
`);I(z)})})}var Qj=8787,Jj="127.0.0.1";var lo=m(()=>{kg0();z3()});async function xg0($){let Y=s0($.options.port)??s0($.options.p),U=S($.options.host)??S($.options.h),z=await Kj({port:Y,host:U}),I=()=>{z.close(()=>{process.exit(0)})};process.on("SIGINT",I),process.on("SIGTERM",I),await new Promise(()=>{})}var fg0=m(()=>{Z4();lo()});async function ug0($,Y,U,z){if($==="config"||$==="get"){await x0("seal_llm_config_get",Y,U,{},j0(z.options));return}if($==="providers"||$==="list"){await x0("seal_llm_providers_list",Y,U,{},j0(z.options));return}throw Error(`Unknown llm command: ${$??""}. Run 'seal-use help' for available commands.`)}var bg0=m(()=>{O4();m1()});async function ig0($,Y){if($==="config"||$==="json"){oo();return}let{startServer:U}=await pg0().then(() => ng0);U()}function oo(){R0({mcpServers:{"seal-use":{type:"stdio",command:"seal-use",args:["mcp"],env:{SEAL_USE_MCP_ENABLED:"true"}}}})}var cg0=m(()=>{m1()});function dg0($){let Y=Uj();R0(Y,{...j0($.options),allowFull:!0})}var mg0=m(()=>{po();m1()});async function lg0($,Y,U,z){if($==="available"){await x0("seal_permissions_available_list",Y,U,{},j0(z.options));return}if($==="configs"||$==="list"){await x0("seal_permissions_configs_list",Y,U,{},j0(z.options));return}throw Error(`Unknown permissions command: ${$??""}. Run 'seal-use help' for available commands.`)}var og0=m(()=>{O4();m1()});import{readFileSync as rg0}from"node:fs";async function sg0($,Y,U,z,I,Q,J){if(!$||$==="get"){await x0("seal_preference_get",I,Q,{},j0(J.options));return}if($==="decision"){if(Y==="update"||!Y){let K=S(J.options.input),G=K?JSON.parse(rg0(K,"utf8")):B8(J.json);if(!G||Object.keys(G).length===0)throw Error(`Usage: seal-use preference decision update --json '{"explicitApprove":"..."}'`);await x0("seal_preference_decision_update",I,Q,{...G,dryRun:G0(J.options.dryRun)??G0(J.options["dry-run"])},j0(J.options));return}}if($==="thinking-depth"||$==="thinkingDepth"){if(Y==="set"){let K=S(J.options.default)??S(J.options.level)??z;if(K!=="medium"&&K!=="high")throw Error("Usage: seal-use preference thinking-depth set --default <medium|high>");await x0("seal_preference_thinking_depth_set",I,Q,{defaultLevel:K,dryRun:G0(J.options.dryRun)??G0(J.options["dry-run"])},j0(J.options));return}if(Y==="policies"){if(U==="list"||!U){await x0("seal_preference_thinking_depth_policies_list",I,Q,{},j0(J.options));return}if(U==="upsert"){let K=S(J.options.input),G=K?JSON.parse(rg0(K,"utf8")):B8(J.json);if(!G||!G.id||!G.name)throw Error(`Usage: seal-use preference thinking-depth policies upsert --json '{"id":"...","name":"...","level":"high"}'`);await x0("seal_preference_thinking_depth_policies_upsert",I,Q,{...G,dryRun:G0(J.options.dryRun)??G0(J.options["dry-run"])},j0(J.options));return}if(U==="remove"||U==="delete"){let K=z??S(J.options.id)??S(J.options.policyId);if(!K)throw Error("Usage: seal-use preference thinking-depth policies remove <policyId>");await x0("seal_preference_thinking_depth_policies_remove",I,Q,{policyId:K,dryRun:G0(J.options.dryRun)??G0(J.options["dry-run"])},j0(J.options));return}}}throw Error(`Unknown preference action: ${$??""}. Available: get, decision update, thinking-depth set, thinking-depth policies list/upsert/remove.`)}var ag0=m(()=>{O4();Z4();m1()});async function tg0($={}){let Y=t8(),U=v4(),z=n2(Y,{stateful:U.stateful,defaultCorpId:U.defaultCorpId,corpId:$.corpId},x3());console.log(`[probe] corp=${z.id} source=${z.source.type}`);let I=await bK(z);console.log("[probe] seal enterprise"),console.log(JSON.stringify(I,null,2));let Q=await B1(z),J=await SM(Q,{documentLimit:20,stylePreferencesEndpoint:z.seal.endpoints.approvalStylePreferences});console.log("[probe] approval context summary"),console.log(JSON.stringify({rules:J.rules.rules.length,hasPendingRuleDeletes:J.rules.hasPendingDeletes,documents:J.documents.articles.length,documentsTotal:J.documents.total,stylePreferences:J.stylePreferences.ok?"ok":`error: ${J.stylePreferences.error}`},null,2))}var eg0=m(()=>{T5();m6();fT();X6()});async function $y0($,Y,U){let z=Y??S(U.options.corp)??($&&$!=="--corp"?$:void 0);await tg0({corpId:z})}var Yy0=m(()=>{eg0();Z4()});async function ro($,Y,U,z,I){if($==="count"){await x0("seal_approval_rules_list",U,z,{countOnly:!0},j0(I.options));return}if($==="list"){if(G0(I.options.count)){await x0("seal_approval_rules_list",U,z,{countOnly:!0},j0(I.options));return}let Q=s0(I.options.limit),J=s0(I.options.offset);if(G0(I.options.summary)){await x0("seal_approval_rules_list",U,z,{fields:Iv0,limit:Q,offset:J},j0(I.options));return}let K=await M$("seal_approval_rules_list",U,z,{limit:Q,offset:J}),G=j0(I.options);Qv0(K,G.allowFull===!0||Boolean(G.outputFile)),R0(K,G);return}if($==="clear"){let Q=G0(I.options.yes)===!0,J=G0(I.options.dryRun)??G0(I.options["dry-run"])??!Q;if(!Q&&!J)throw w$("Refusing to clear rules without --yes. Use --dry-run to preview.",`seal-use rules clear --corp ${z.id} --dry-run`);let K=await M$("seal_approval_rules_clear",U,z,{dryRun:J,recode:G0(I.options.recode)});if(!Q&&J& Line truncated
`).filter(Boolean),Q=I.slice(-Y);return{logFile:U,lines:Q,totalLines:I.length}}async function Bk1($){let Y=Xj($),U=to($),z=pq($);Jy0($.stateDir);let I=$.port??(process.env.PORT?Number.parseInt(process.env.PORT,10):Qj),Q=$.host??(process.env.HOST?process.env.HOST:Jj);Hj(Y,`${process.pid}
`,{mode:384}),Hj(U,JSON.stringify({pid:process.pid,port:I,host:Q,version:$.version,startedAt:new Date().toISOString()},null,2),{mode:384}),pK(z,`service starting on http://${Q}:${I} pid=${process.pid}`);let J=null;try{J=await Kj({port:I,host:Q,silent:!0}),pK(z,`service listening pid=${process.pid}`)}catch(G){if(pK(z,`service failed to bind port ${I}: ${G instanceof Error?G.message:String(G)}`),Wj(Y)===process.pid)x9(Y,{force:!0}),x9(U,{force:!0});throw G}let K=()=>{if(J)J.close(),J=null;if(Wj(Y)===process.pid)x9(Y,{force:!0}),x9(U,{force:!0});pK(z,`stopped pid=${process.pid}`)};await new Promise((G)=>{let H=!1,W=()=>{if(H)return;H=!0,K(),process.off("SIGTERM",W),process.off("SIGINT",W),G()};process.once("SIGTERM",W),process.once("SIGINT",W)})}function zy0($){Jy0($.stateDir);let Y=cz($);if(Y.running)return Y;let U=$.launcher??{command:process.execPath,args:[$.entryFile]},z=[...U.args??[],"service","run"];if($.port)z.push("--port",String($.port));if($.host)z.push("--host",String($.host));let I=Ok1(U.command,z,{cwd:$.appRoot,detached:!0,stdio:["ignore","ignore","ignore"],env:process.env});I.unref();let Q=Xj($);return Hj(Q,`${I.pid}
`,{mode:384}),pK(pq($),`started pid=${I.pid}`),{started:!0,...cz($)}}function Iy0($,Y={}){let U=Xj($),z=to($),I=Wj(U);if(!I||!Qy0(I,$.appRoot))return x9(U,{force:!0}),x9(z,{force:!0}),Y.quiet?void 0:{stopped:!1,reason:"not running"};return process.kill(I,"SIGTERM"),x9(U,{force:!0}),x9(z,{force:!0}),pK(pq($),`stop requested pid=${I}`),Y.quiet?void 0:{stopped:!0,pid:I}}function Qy0($,Y){if(!Pk1($))return!1;try{let U=Nk1("ps",["-p",String($),"-o","command="],{encoding:"utf8"}),z=U.trim().split(/\s+/).filter(Boolean),I=z.indexOf("service"),Q=I!==-1&&z[I+1]==="run",J=U.includes(Y)||z.some((K)=>/(^|[\\/])(seal-use|seal-home)(\.exe)?$/.test(K));return Q&&J}catch{return!1}}function Pk1($){try{return process.kill($,0),!0}catch{return!1}}function Xj($){return ao($.stateDir,"service.pid")}function to($){return ao($.stateDir,"service.json")}function pq($){return ao($.stateDir,"service.log")}function Wj($){if(!Gj($))return;let Y=Number(so($,"utf8").trim());return Number.isInteger(Y)&&Y>0?Y:void 0}function Jy0($){Dk1($,{recursive:!0,mode:448})}function pK($,Y){Hj($,`${new Date().toISOString()} ${Y}
`,{flag:"a",mode:384})}var eo=m(()=>{lo()});import{homedir as Tk1}from"node:os";import{join as jk1}from"node:path";async function Yr($,Y,U){let z=U?s0(U.options.port)??s0(U.options.p):void 0,I=U?S(U.options.host)??S(U.options.h):void 0,Q=U?s0(U.options.lines)??s0(U.options.n):void 0,J=await s3($,{appRoot:Y.appRoot,entryFile:Y.entryFile,stateDir:$r,version:X1,launcher:Y.launcher,port:z,host:I},{maxLines:Q});if(J!==void 0)R0(J)}var $r;var Ur=m(()=>{z3();eo();m1();Z4();$r=jk1(Tk1(),".config","seal-use")});import{existsSync as Ek1,readFileSync as Ky0}from"node:fs";async function Gy0($,Y,U,z,I){if($==="batch-records"||$==="records"){let Q=Y??S(I.options.batchId)??S(I.options["batch-id"]);if(!Q)throw Error("Usage: seal-use simulation batch-records <batchId>");await x0("seal_simulation_batch_records_get",U,z,{batchId:Q,query:S(I.options.query)},j0(I.options));return}if($==="create"||$==="run"){let Q=S(I.options.mode)??S(I.options.sourceSystem)??S(I.options["source-system"])??"hosecloud",J=Q==="material-pack"?"material_pack":Q,K=S(I.options.schemaConfig)??S(I.options["schema-config"]),G=K?JSON.parse(Ky0(K,"utf8")):void 0,H=S(I.options.input),W=H?JSON.parse(Ky0(H,"utf8")):B8(I.json),X=S(I.options.packageId)??S(I.options["package-id"]),Z=i6(I.options.packageIds)??i6(I.options["package-ids"])??(X?[X]:void 0),q=i6(I.options.flowIds)??i6(I.options["flow-ids"])??i6(I.options.documentSn)??i6(I.options["document-sn"]),V=S(I.options.signKey)??S(I.options["sign-key"])??S(I.options.integration),w=G0(I.options.wait)===!0,M=G0(I.options.noWait)??G0(I.options["no-wait"])??(w?!1:!0),F=await M$("seal_simulation_batch_create",U,z,{mode:J,sourceSystem:J,flowIds:q,documentSn:q,rejectNodeName:S(I.options.rejectNode)??S(I.options["reject-node"])??null,thinkingDepthOverride:S(I.options.thinkingDepth)??S(I.options["thinking-depth"]),skipInvoiceGeneration:G0(I.options.skipInvoiceGeneration)??G0(I.options["skip-invoice-generation"]),skipExpenseExtraction:G0(I.options.skipExpenseExtraction)??G0(I.options["skip-expense-extraction"]),disableAttachmentCache:G0(I.options.disableAttachmentCache)??G0(I.options["disable-attachment-cache"]),signKey:V,packageIds:Z,packageId:X,templateId:S(I.options.templateId)??S(I.options["template-id"]),schemaConfig:G,requestIds:i6(I.options.requestIds)??i6(I.options["request-ids"]),workflowTypeId:S(I.options.workflowTypeId)??S(I.options["workflow-type-id"]),flowStatusList:i6(I.options.flowStatusList)?.map(Number)??i6(I.options["flow-status-list"])?.map(Number),businessCodes:i6(I.options.businessCodes)??i6(I.options["business-codes"]),documentType:S(I.options.documentType)??S(I.options["document-type"]),startTime:s0(I.options.startTime)??s0(I.options["start-time"]),endTime:s0(I.options.endTime)??s0(I.options["end-time"]),status:i6(I.options.status),limit:s0(I.options.limit),noWait:M,rawParams:W});if(w&&F&&typeof F==="object"&&"batchId"in F&&typeof F.batchId==="string"){await x0("seal_simulation_batch_wait",U,z,{batchId:F.batchId,timeout:S(I.options.timeout),pollInterval:S(I.options.pollInterval)??S(I.options["poll-interval"])},j0(I.options));return}R0(F,j0(I.options));return}if($==="wait"){let Q=Y??S(I.options.batchId)??S(I.options["batch-id"]);if(!Q)throw Error("Usage: seal-use simulation wait <batchId> [--timeout 10m] [--poll-interval 2s]");await x0("seal_simulation_batch_wait",U,z,{batchId:Q,timeout:S(I.options.timeout),pollInterval:S(I.options.pollInterval)??S(I.options["poll-interval"])},j0(I.options));return}if($==="status"){let Q=Y??S(I.options.batchId)??S(I.options["batch-id"]);if(!Q)throw Error("Usage: seal-use simulation status <batchId>");await x0("seal_simulation_batch_status",U,z,{batchId:Q},j0(I.options));return}if($==="clean"||$==="delete"){let Q=Y??S(I.options.batchId)??S(I.options["batch-id"]);if(!Q)throw Error("Usage: seal-use simulation clean <batchId>");await x0("seal_simulation_batch_clean",U,z,{batchId:Q},j0(I.options));return}if($==="specifications"){let Q=Y??S(I.options.integration)??S(I.options.signKey)??S(I.options["sign-key"]);await x0("seal_simulation_specifications_list",U,z,{signKey:Q},j0(I.options));return}if($==="approval-definitions"||$==="definitions"){await x0("seal_simulation_feishu_approval_definitions_list",U,z,{},j0(I.options));return}if($==="list"){await x0("seal_simulation_batches_list",U,z,{limit:s0(I.options.limit)},j0(I.options));return}if($==="get"){let Q=Y??S(I.options.batchId)??S(I.options["batch-id"]);if(!Q)throw Error("Usage: seal-use simulation get <batchId>");await x0("seal_simulation_batch_get",U,z,{batchId:Q},j0(I.options));return}if($==="templates"){await x0("seal_simulation_templates_get",U,z,{},j0(I.options));return}if($==="integrations"){await x0("seal_simulation_integrations_get",U,z,{},j0(I.options));return}if($==="package-upload"){let Q=Y??S(I.options.file);if(!Q)throw Error("Usage: seal-use simulation package-upload <材料包.zip>");if(!Ek1(Q))throw Error(`File not found: ${Q}`);await x0("seal_simulation_material_package_upload",U,z,{filePath:Q},j0(I.o Line truncated
`);return}if($==="install"||$==="init"||$==="sync"){let z=G0(U.options.local)||G0(U.options.workspace),I=S(U.options.dir)??S(U.options.target)??Y,Q=I?I:z?Zj(process.cwd(),".agents","skills","seal-use"):iz(),J=Og0(Q),K=!z&&!I,G=K?_o():void 0,H=K?So():void 0;R0({installed:!0,targetDir:J.targetDir,fileCount:J.files.length,files:J.files,...G?{antigravity:G}:{},...H?{hosts:H}:{}});return}if($==="status"||$==="get"||!$){let z=iz(),I=Zj(process.cwd(),".agents","skills","seal-use"),Q=vo(),J=go();R0({global:{dir:z,installed:Wy0(Zj(z,"SKILL.md"))},local:{dir:I,installed:Wy0(Zj(I,"SKILL.md"))},antigravity:Q,hosts:J});return}throw Error(`Unknown skill command: ${$}. Run 'seal-use help' for available commands.`)}var Zy0=m(()=>{ko();iq();Z4();m1()});async function qy0($,Y){if($==="config"){R0(await bK(Y));return}throw Error(`Unknown source command: ${$??""}. Run 'seal-use help' for available commands.`)}var Vy0=m(()=>{fT();m1()});function zr($){if(typeof $!=="string"||!$.trim())return"UNKNOWN";let Y=$.toUpperCase().trim();if(Y==="APPROVE"||Y==="PASS")return"APPROVE";if(Y==="REJECT"||Y==="DENIED")return"REJECT";if(Y==="MANUAL"||Y==="ASSISTED")return"MANUAL";if(Y==="ERROR"||Y==="FAILED")return"ERROR";return Y}async function Ly0($){let{sourceCorp:Y,targetCorp:U,sourceClient:z,targetClient:I,samples:Q=10,dryRun:J=!1,pollIntervalMs:K=2000,timeoutMs:G=45000,snPrefix:H="REG_",fetchFn:W=fetch}=$;if(U.environment!=="test")throw new W4(`重放目标企业「${U.name}」(${U.id}) 的环境为「${U.environment}」,非测试环境!
`+"硬性安全规定:自动化回归测试矩阵严禁在生产环境直接运行。必须绑定并指定测试环境(testCorp)。",2,`seal-use corps bind-test ${Y.id} <testCorpId>`);let X=await lY(I),q=(Array.isArray(X.features)?X.features:[]).find((d)=>d?.code==="ai-approval"),V=typeof q?.balance==="number"?q.balance:0,w=typeof q?.deductionAmount==="number"&&q.deductionAmount>0?q.deductionAmount:120,M=Q*w;if(V<M)throw new W4(`测试企业「${U.name}」AI 审批额度不足:当前剩余 ${V} 点,本次回归抽样 ${Q} 笔需要约 ${M} 点。
`+"为防止测试环境额度耗尽中断业务,已硬性拦截并拒绝发起测试单据注入。",2,`请为测试企业「${U.id}」充值 AI 审批额度,或降低抽样笔数 (--samples ${Math.max(1,Math.floor(V/w))})`);let F=await i4(z,{limit:Q,status:"completed"}),N=Array.isArray(F.records)?F.records:[];if(N.length===0){let d=await i4(z,{limit:Q});N=Array.isArray(d.records)?d.records:[]}if(N.length===0)throw new W4(`在母企业「${Y.name}」(${Y.id}) 中未检索到任何历史审批单据,无法抽取回归样本。`,2);if(N=N.slice(0,Q),J){let d=N.map((a)=>{let $0=a.sourceDocumentSN??a.id,y=a?.result?.decision??a.aiDecision??a?.decision,p=zr(y),Y0=a?.result?.summary??a.aiSummary;return{sn:$0,sourceRecordId:a.id,prodDecision:p,prodSummary:Y0,status:"DRY_RUN"}});return{ok:!0,verdict:"DRY_RUN",safeToPublish:!0,timestamp:new Date().toISOString(),sourceCorp:{id:Y.id,name:Y.name,environment:Y.environment??"production"},targetCorp:{id:U.id,name:U.name,environment:U.environment??"test"},quota:{featureCode:"ai-approval",balanceBefore:V,deductionAmount:w,estimatedRequired:M},metrics:{sampleCount:d.length,successCount:d.length,failureCount:0,matchCount:d.length,flipCount:0,concordanceRate:1},flips:[],records:d}}let O=await gp(I,U,$.webhookSelector),D=[];for(let d of N){let a=Date.now(),$0=d.sourceDocumentSN??d.id,y=zr(d?.result?.decision??d.aiDecision??d?.decision),p=d?.result?.summary??d.aiSummary;try{let Y0=await H4(z,d.id),R=`${H}${$0}`,o=hp(Y0,{snPrefix:H,docIdPrefix:H});await Sp(O.incomingDocumentWebhook.url,O.secret,o,W,A6(U.seal));let e=null,O0=Date.now();while(Date.now()-O0<G){await new Promise((X0)=>setTimeout(X0,K));let t=await i4(I,{sourceDocumentSN:R,limit:1});if(t.records&&t.records.length>0){let X0=t.records[0];if(X0.status==="completed"||X0.status==="failed"){e=X0;break}}}if(!e){D.push({sn:$0,sourceRecordId:d.id,prodDecision:y,prodSummary:p,status:"FAILED",error:`测试租户单据审核超时 (${Math.round(G/1000)}s 未完成)`,durationMs:Date.now()-a});continue}let T0=zr(e?.result?.decision??e.aiDecision??e?.decision??(e.status==="completed"?"APPROVE":"ERROR")),y0=e?.result?.summary??e.aiSummary,v0=y===T0,o0=v0?"MATCHED":"FLIPPED",q1={sn:$0,sourceRecordId:d.id,prodDecision:y,prodSummary:p,testRecordId:e.id,testDecision:T0,testSummary:y0,status:o0,durationMs:Date.now()-a};if(!v0)q1.diff={from:y,to:T0,reasonDiff:y0&&p&&y0!==p?`生产: ${p.slice(0,60)}... -> 测试: ${y0.slice(0,60)}...`:void 0};D.push(q1)}catch(Y0){D.push({sn:$0,sourceRecordId:d.id,prodDecision:y,prodSummary:p,status:"FAILED",error:Y0 instanceof Error?Y0.message:String(Y0),durationMs:Date.now()-a})}}let P=D.filter((d)=>d.status==="MATCHED"||d.status==="FLIPPED"),T=D.filter((d)=>d.status==="MATCHED"),A=D.filter((d)=>d.status==="FLIPPED"),j=D.filter((d)=>d.status==="FAILED").length,C=T.length,b=A.length,x=C+b,g=x>0?C/x:0,i=b>0,c=i?"REGRESSIONS_DETECTED":"CLEAN",z0=!i&&j===0,k;try{let d=await lY(I),$0=(Array.isArray(d.features)?d.features:[]).find((y)=>y?.code==="ai-approval");if(typeof $0?.balance==="number")k=$0.balance}catch{}return{ok:!i&&j===0,verdict:c,safeToPublish:z0,timestamp:new Date().toISOString(),sourceCorp:{id:Y.id,name:Y.name,environment:Y.environment??"production"},targetCorp:{id:U.id,name:U.name,environment:U.environment??"test"},quota:{featureCode:"ai-approval",balanceBefore:V,deductionAmount:w,estimatedRequired:M,balanceAfter:k},metrics:{sampleCount:D.length,successCount:P.length,failureCount:j,matchCount:C,flipCount:b,concordanceRate:Number(g.toFixed(4))},flips:A,records:D}}function Fy0($){let{sourceCorp:Y,targetCorp:U,verdict:z,safeToPublish:I,metrics:Q,quota:J,flips:K,records:G}=$,H=z==="CLEAN"?"\uD83D\uDFE2 决策完全一致 (CLEAN - 无回归)":z==="DRY_RUN"?"⚪ 预演模式 (DRY-RUN)":"\uD83D\uDD34 发现决策翻转 (REGRESSIONS_DETECTED)",W=["",`\uD83E\uDDEA [Seal Use Test] 规则回归测试矩阵: 生产「${Y.name}」-> 测试靶场「${U.name}」`,` 判定: ${H} · 准许发布: ${I?"YES (可安全上线)":"NO (存在行为偏离/待复核)"}`," "+"─".repeat(65),` 样本总数: ${Q.sampleCount} | 一致通过: ${Q.matchCount} | 决策翻转: ${Q.flipCount} | 异常失败: ${Q.failureCount}`,` 一致率: ${(Q.concordanceRate*100).toFixed(1)}% | 消耗预估: ${J.estimatedRequired} 点 (余量: ${J.balanceBefore}${J.balanceAfter!==void 0?` -> ${J.balanceAfter}`:""})`," "+"─".repeat(65)];if(K.length>0){W.push(` ⚠️ 决策翻转清单 (${K.length} 笔单据在新规则下结果改变):`);for(let X of K)if(W.push(` • 单据 [${X.sn}]: 原生产判定「${X.prodDecision}」 ➔ 测试新判定「${X.testDecision}」`),X.diff?.reasonDiff)W.push(` 理由差异: ${X.diff.reasonDiff}`);W.push(" "+"─".repeat(65)),W.push(" \uD83D\uDC49 建议: 请检查上述翻转单据是否符合预期修正。若为意外误杀,请调整测试环境规则后再次回归。")}else if(z==="CLEAN")W.push(" ✓ 全部样本在新规则下的审核决策与生产历史 100% Line truncated
`)}var wy0=m(()=>{O8();X6();iZ()});async function Ir($,Y,U){let z=($??Y??"regression").toLowerCase();if(z==="regression"||z==="regress"||z==="matrix"){let I=S(U.options.corp)??(Y&&Y!==z?Y:void 0),Q=M1(I),J=Q,K=Q;if(Q.environment==="test"){K=Q;let O=S(U.options["prod-corp"])??S(U.options.prod)??Q.prodCorpId;if(!O)throw new W4(`测试企业「${Q.name}」(${Q.id}) 未绑定生产母企业,无法拉取历史样本。
`+"请建立绑定或通过 --prod-corp 参数指定生产企业来源。",2,`seal-use corps bind-test <prodCorpId> ${Q.id}`);J=M1(O)}else{J=Q;let O=S(U.options["test-corp"])??S(U.options.test)??Q.testCorpId;if(!O)throw new W4(`生产企业「${Q.name}」(${Q.id}) 未绑定测试靶场企业。
`+"硬性规定:回归测试严禁在生产环境直接运行。必须绑定并指定测试环境(testCorp)。",2,`seal-use corps bind-test ${Q.id} <testCorpId>`);K=M1(O)}let G=await B1(J),H=await B1(K),W=s0(U.options.samples)??s0(U.options.limit)??s0(U.options.n)??10,X=G0(U.options["dry-run"]),Z=G0(U.options["fail-on-flips"]),q=s0(U.options["poll-interval"])??2000,V=s0(U.options.timeout)??45000,w=S(U.options["sn-prefix"])??"REG_",M=S(U.options.webhook)??S(U.options.selector),F=await Ly0({sourceCorp:J,targetCorp:K,sourceClient:G,targetClient:H,samples:W,dryRun:X,pollIntervalMs:q,timeoutMs:V,snPrefix:w,failOnFlips:Z,webhookSelector:M});if(!(G0(U.options.quiet)||G0(U.options.silent)))console.error(Fy0(F));if(R0(F),Z&&!F.ok)throw new W4(`回归测试发现 ${F.metrics.flipCount} 笔单据决策翻转,已按 --fail-on-flips 策略非零终止。`,1);return}throw new W4(`未知的 test 子命令: "${z}"。
可用子命令: seal-use test regression [--corp <id>] [--samples <N>] [--dry-run]`,2,"seal-use test regression --help")}var My0=m(()=>{O8();O4();Z4();m1();m6();wy0()});async function Oy0($,Y,U,z){if(!$)throw Error("Usage: seal-use tool <toolName> [--json '{...}']");await x0($,Y,U,B8(z.json),j0(z.options))}var Ny0=m(()=>{O4();Z4();m1()});function Dy0(){R0(Pq.map(($)=>({name:$.name,description:$.description})))}var Ay0=m(()=>{jq();m1()});function qj($=process.execPath,Y=import.meta.url){if(Y.includes("/$bunfs/")||Y.includes("\\$bunfs\\"))return!0;let U=$.toLowerCase().replace(/\\/g,"/");return!U.endsWith("/bun")&&!U.endsWith("/bun.exe")&&!U.endsWith("/node")&&!U.endsWith("/node.exe")}var By0=m(()=>{iq()});import{existsSync as Ck1,mkdirSync as Rk1,readFileSync as _k1,renameSync as vk1,writeFileSync as hk1}from"node:fs";import{homedir as Sk1}from"node:os";import{dirname as gk1,join as yk1}from"node:path";import{spawn as kk1}from"node:child_process";function Py0($){return $.replace(/\.\d+Z$/,"Z")}function Ty0(){let $=process.env[xk1]?.trim();if($)return $;return uk1}function jy0($=Ty0()){if(!Ck1($))return null;try{let Y=_k1($,"utf-8"),U=JSON.parse(Y);if(U&&typeof U==="object"&&typeof U.latestVersion==="string"&&typeof U.checkedAt==="string")return{...U,checkedAt:Py0(U.checkedAt)};return null}catch{return null}}function dq($,Y=Ty0()){try{let U=gk1(Y);Rk1(U,{recursive:!0,mode:448});let z={checkedAt:Py0($.checkedAt??new Date().toISOString()),latestVersion:$.latestVersion,publishedAt:$.publishedAt,releaseUrl:$.releaseUrl},I=`${Y}.tmp.${Date.now()}.${Math.random().toString(36).slice(2,8)}`;hk1(I,JSON.stringify(z,null,2),{mode:384}),vk1(I,Y)}catch{}}function Ey0($,Y=fk1){if(!$||!$.checkedAt)return!0;let U=new Date($.checkedAt).getTime();if(Number.isNaN(U))return!0;return Date.now()-U>Y}function Cy0($){if(process.env.SEAL_DISABLE_BG_UPDATE==="1"||!1||process.env.CI)return!1;if(!$||!$.command)return!1;try{let Y=$.command,U=[...$.args??[],"update","check","--bg-save"];return kk1(Y,U,{detached:!0,stdio:"ignore",env:{...process.env,SEAL_DISABLE_BG_UPDATE:"1"}}).unref(),!0}catch{return!1}}var xk1="SEAL_USE_UPDATE_CACHE_FILE",fk1=86400000,uk1;var Qr=m(()=>{uk1=yk1(Sk1(),".config","seal-use","update-cache.json")});import{chmodSync as bk1,mkdirSync as ik1,readdirSync as ck1,realpathSync as Ry0,renameSync as Jr,rmSync as nk1,unlinkSync as gy0,writeFileSync as _y0}from"node:fs";import{basename as pk1,dirname as dk1,isAbsolute as mk1,join as Fj,relative as lk1}from"node:path";import{spawn as ok1,spawnSync as a3}from"node:child_process";async function ky0($,Y={}){let U={appRoot:$.appRoot,entryFile:$.entryFile,stateDir:$r,version:X1,launcher:$.launcher},z=Y.repo||process.env[rk1]?.trim()||process.env[sk1]?.trim()||yy0,I=Y.targetVersion?.trim(),Q=I&&I.toLowerCase()!=="latest"?I:void 0;if(Q){let D=Q.replace(/^v/,""),P=by0(D,X1);if(P<0)if(!Wg&&Y.force);else{R0({updated:!1,currentVersion:X1,targetVersion:D,mode:qj()?"binary":"source",message:!Wg?`Cannot downgrade seal-use from dev build v${X1} to release v${D}. Use --force to overwrite.`:`Cannot downgrade seal-use from v${X1} to older version v${D}. Updates must be forward-only.`});return}if(P===0&&!Y.force){R0({updated:!1,currentVersion:X1,targetVersion:D,mode:qj()?"binary":"source",message:`seal-use is already at version v${X1}. Use --force to reinstall.`});return}}if(Y.changelogOnly){let D=await Lj(z,Y.limit??10);R0({currentVersion:X1,totalQueried:D.length,releases:D.map((P)=>({version:P.version,tagName:P.tagName,publishedAt:P.publishedAt,author:P.author,releaseNotes:P.notes,releaseUrl:P.htmlUrl,isCurrent:P.version===X1,isNewer:h5(P.version,X1)}))});return}if(!qj()){if(Y.checkOnly){let P=await Lj(z,30),T=P[0],A=T?.version??X1,j=P.find((x)=>x.version===X1),C=h5(A,X1),b=P.filter((x)=>h5(x.version,X1));if(T?.version)dq({latestVersion:T.version,publishedAt:T.publishedAt,releaseUrl:T.htmlUrl});if(Y.bgSave)return;R0({updated:!1,updateAvailable:C,currentVersion:X1,currentVersionPublishedAt:j?.publishedAt,latestVersion:A,latestVersionPublishedAt:T?.publishedAt,behindCount:b.length,pendingReleases:b.map((x)=>({version:x.version,tagName:x.tagName,publishedAt:x.publishedAt,author:x.author,releaseNotes:x.notes,releaseUrl:x.htmlUrl})),releaseNotes:T?.notes??"",releaseUrl:T?.htmlUrl??"",mode:"source",message:"当前运行的是开发版。正式用户请安装正式版后使用 seal-use update。"});return}let D=cz(U).running;if(D)await s3("stop",U);try{Sy0("git",["-C",$.appRoot,"pull","--ff-only"])}catch(P){console.error(`⚠️ 开发版更新同步失败,继续刷新本地依赖: ${P instanceof Error?P.message:String(P)}`)}if(Sy0("bun",["install"],{cwd:$.appRoot}),D)await s3("start",U);R0({updated:!0,serviceRestarted:D,version:X1,mode:"source"});return}if(Yx1())try{await Ux1($,Y,U,z,Q);return}catch(D){console.error(`⚠️ Homebrew 自动更新失败,回退至原生二进制更新: ${D instanceof Error?D.message:String(D)}`)}let J=tk1(),K=ek1(),G=await Lj(z,30),H=Q?G.find((D)=>D.version Line truncated
`)}catch{}}async function Qx1($,Y,U,z){let I=Kr(),Q=[],J=U?U.startsWith("v")?U:`v${U}`:void 0,K=z||$.split("/").pop()||"";if(I!=="github"){if(J&&K)Q.push(`https://git.ying-qing.cn/gitea/seal-use/releases/download/${J}/${K}`,`https://git.ying-qing.cn/gitea/seal-home/releases/download/${J}/${K}`);if($.startsWith("https://git.ying-qing.cn"))Q.push($)}if(I!=="gitea")if(J&&K){let w=`https://github.com/${yy0}/releases/download/${J}/${K}`;if(!process.env.CI)Q.push(`https://ghfast.top/${w}`,`https://gh.ddlc.top/${w}`);Q.push(w)}else if($.includes("github.com")){if(!process.env.CI)Q.push(`https://ghfast.top/${$}`,`https://gh.ddlc.top/${$}`);Q.push($)}else Q.push($);let G=Array.from(new Set(Q)),H,W=6000,X=6000,Z=307200,q=1e4,V=180000;for(let w=0;w<G.length;w++){let M=G[w],F=new AbortController,N="",O=(A)=>{N=A;try{F.abort()}catch{}},D=setTimeout(()=>{O("Connection timed out (no response headers within 6s)")},W),P,T;try{Vj(`==> [${w+1}/${G.length}] Downloading via: ${M}`);let A=await fetch(M,{signal:F.signal});if(D)clearTimeout(D),D=void 0;if(!A.ok)throw Error(`HTTP ${A.status} ${A.statusText}`);P=setTimeout(()=>{O("Overall download time exceeded 3 minutes")},V);let j=Number(A.headers.get("content-length"))||0,C=A.body?.getReader();if(!C){let c=Buffer.from(await A.arrayBuffer());if(c.length<1000)throw Error(`Downloaded content is suspiciously small (${c.length} bytes)`);_y0(Y,c),Vj(`✓ Download succeeded (${(c.length/1024/1024).toFixed(1)} MB)`);return}let b=[],x=0,g=0;T=setTimeout(()=>{if(x<Z){let c=(x/1024).toFixed(1);O(`Initial transfer too slow (${c} KB < 300 KB in 6s), switching mirror...`)}},X);while(!0){let c=C.read(),z0,k=new Promise((y,p)=>{z0=setTimeout(()=>{p(Error("Data transfer stalled (no chunk received for 10s)"))},q)}),d;try{d=await Promise.race([c,k])}finally{if(z0)clearTimeout(z0)}let{done:a,value:$0}=d;if(a)break;if($0){if(b.push($0),x+=$0.length,T&&x>=Z)clearTimeout(T),T=void 0;let y=Date.now();if(y-g>200){g=y;let p=j?Math.round(x/j*100):0,Y0=(x/1048576).toFixed(1),R=j?(j/1048576).toFixed(1):"?";try{process.stderr.write(`\r ↳ Progress: ${p}% (${Y0} / ${R} MB)...`)}catch{}}}}try{process.stderr.write(`
`)}catch{}let i=Buffer.concat(b);if(i.length<1000)throw Error(`Downloaded content is suspiciously small (${i.length} bytes)`);_y0(Y,i),Vj(`✓ Download completed successfully (${(i.length/1024/1024).toFixed(1)} MB)`);return}catch(A){if(D)clearTimeout(D);if(T)clearTimeout(T);if(P)clearTimeout(P);let j=N||(A instanceof Error?A.message:String(A));H=Error(j),Vj(`
↳ Mirror failed: ${H.message}`)}finally{if(D)clearTimeout(D);if(T)clearTimeout(T);if(P)clearTimeout(P)}}throw Error(`Failed to download asset from all mirrors: ${H?.message}`)}function fy0($){let Y;try{Y=ck1($,{withFileTypes:!0})}catch{return[]}let U=[];for(let z of Y){let I=Fj($,z.name);if(z.isDirectory())U.push(...fy0(I));else if(z.isFile())U.push(I)}return U}function uy0($,Y,U){let z=Y==="windows"?"seal-use.exe":"seal-use",I=fy0($);return I.find((Q)=>pk1(Q)===z)??I[0]??U}function Jx1($,Y,U){let z=a3("tar",["-xzf",$,"-C",Y],{stdio:"pipe"});if(z.status!==0)throw Error(`Failed to extract tar archive: ${z.stderr.toString()}`);return gy0($),uy0(Y,U,$)}function Kx1($,Y,U){let z=a3("unzip",["-q","-o",$,"-d",Y],{stdio:"pipe"});if(z.status!==0)throw Error(`Failed to extract zip archive: ${z.stderr.toString()}`);return gy0($),uy0(Y,U,$)}function by0($,Y){let U=$.replace(/^v/,"").split(".").map((I)=>Number.parseInt(I,10)||0),z=Y.replace(/^v/,"").split(".").map((I)=>Number.parseInt(I,10)||0);for(let I=0;I<Math.max(U.length,z.length);I++){let Q=U[I]??0,J=z[I]??0;if(Q>J)return 1;if(Q<J)return-1}return 0}function h5($,Y){return by0($,Y)>0}function Sy0($,Y,U={}){let z=a3($,Y,{cwd:U.cwd,encoding:"utf8",stdio:["ignore","pipe","pipe"]});if(z.stdout)console.error(z.stdout.trimEnd());if(z.stderr)console.error(z.stderr.trimEnd());if(z.status!==0)throw Error(`${$} ${Y.join(" ")} failed with status ${z.status}`)}var yy0="yunyingk/seal-use",mq="yunyingk/seal-home",rk1="SEAL_USE_GITHUB_REPO",sk1="SEAL_HOME_GITHUB_REPO";var iy0=m(()=>{By0();iq();Qr();z3();eo();m1();Ur()});async function cy0($,Y,U,z,I){if($==="create"){let Q=S(I.options.name)??Y,J=S(I.options.phone);if(!Q||!J)throw Error("Usage: seal-use users create --name <name> --phone <phone> [--dept <deptId>]");let K=S(I.options.dept)??S(I.options.departmentId);await x0("seal_user_create",U,z,{name:Q,phone:J,departmentIds:K?[K]:void 0},j0(I.options));return}if($==="reset-password"){let Q=Y??S(I.options.userId);if(!Q)throw Error("Usage: seal-use users reset-password <userId>");await x0("seal_user_reset_password",U,z,{userId:Q},j0(I.options));return}if($==="search"||$==="list"){let Q=Y??S(I.options.keyword)??S(I.options.query)??"";await x0("seal_user_search",U,z,{keyword:Q},j0(I.options));return}if($==="get"){let Q=Y??S(I.options.userId);if(!Q)throw Error("Usage: seal-use users get <userId>");await x0("seal_user_get",U,z,{userId:Q},j0(I.options));return}if($==="delete"){let Q=Y??S(I.options.userId);if(!Q)throw Error("Usage: seal-use users delete <userId>");await x0("seal_user_delete",U,z,{userId:Q},j0(I.options));return}if($==="activate"){let Q=Y??S(I.options.userId);if(!Q)throw Error("Usage: seal-use users activate <userId>");await x0("seal_user_activate",U,z,{userId:Q},j0(I.options));return}if($==="delegation"||$==="impersonate"){let Q=Y??S(I.options.userId)??S(I.options.phone);if(!Q)throw Error("Usage: seal-use users delegation <userIdOrPhone> [--note <note>]");let J=S(I.options.note);await x0("seal_user_delegation_create",U,z,{userIdOrPhone:Q,note:J},j0(I.options));return}throw Error(`Unknown users command: ${$??""}. Run 'seal-use help' for available commands.`)}var ny0=m(()=>{O4();Z4();m1()});import{dirname as Gr,join as Gx1}from"node:path";import{fileURLToPath as Hx1}from"node:url";function qx1($){if(!$.length)return!1;let Y=$[0]?.toLowerCase(),U=$[1]?.toLowerCase();if(Y&&Zx1.has(Y))return!0;if((Y==="service"||Y==="daemon")&&U==="run")return!0;return!1}function nq($,Y={}){if(qx1($))return my0($,Y);let U=dy0.then(()=>my0($,Y));return dy0=U.then(()=>{return},()=>{return}),U}async function my0($,Y){let U=[],z=[],I=console.log,Q=console.error,J={appRoot:Y.appRoot??py0,entryFile:Y.entryFile??Gx1(Y.appRoot??py0,"src","cli.ts"),launcher:Y.launcher};console.log=(...K)=>{U.push($o(K))},console.error=(...K)=>{z.push($o(K))};try{return await Vx1($,J),{stdout:Cq(U),stderr:Cq(z),isError:!1,exitCode:0}}catch(K){let G=Rq(K instanceof Error?K.message:String(K)),H=bZ(K);if(z.push(G),H.nextAction&&!G.includes("Next action:"))z.push(`\uD83D\uDC49 Next action: ${H.nextAction}`);return{stdout:Cq(U),stderr:Cq(z),isError:!0,exitCode:H.exitCode}}finally{console.log=I,console.error=Q}}async function Vx1($,Y){let U=Eq($),[z,I,Q]=U.command,J=z?.toLowerCase(),K=J?Wx1.has(J):!1,G=K?"update":J;if(G==="version"||G==="v"||Boolean(U.options.version)||Boolean(U.options.v)||Boolean(U.options.V)){let Z=jy0(),q=Z?.latestVersion?h5(Z.latestVersion,dY.version):!1,V={...dY,...Z?.latestVersion?{latestVersion:Z.latestVersion,updateAvailable:q,lastCheckedAt:Z.checkedAt}:{}};if(q&&Z?.latestVersion)console.error(`\uD83D\uDCA1 发现新版本可用: v${dY.version} -> v${Z.latestVersion}`),console.error(`\uD83D\uDC49 Next action: seal-use update
`);if(R0(V),Ey0(Z))Cy0(Y.launcher);return}let H=Uv0(U);if(H.isHelp){Jv0(H.target);return}if(!G||!Xx1.has(G))throw Error(`Unknown command: ${U.command.join(" ")}. Run 'seal-use help' for available commands.`);if(G==="webhook"&&(I==="resource-pack"||I==="pack"||I==="material-pack")&&Q==="preview"){let Z=U.command[3]??S(U.options.file)??S(U.options.input);if(!Z)throw Error("Usage: seal-use webhook resource-pack preview <资源包.zip>");await Gv0(Z,uK(U.options));return}if(G==="openapi"){dg0(U);return}if(G==="mcp-config"){oo();return}if(G==="skill"){Xy0(I,Q,U);return}if(G==="mcp"||G==="server"){await ig0(I,U);return}if(G==="probe"){await $y0(I,Q,U);return}if(G==="doctor"){await Cg0(I,Q,U);return}if(G==="test"){await Ir(I,Q,U);return}if(G==="config"){FS0(I,Q,U);return}if(G==="service"){await Yr(I,Y,U);return}if(G==="stop"){await Yr("stop",Y,U);return}if(G==="http"||G==="serve"){await xg0(U);return}if(K||G==="changelog"){if(K&&z!=="update")console.error(`⚠️ Notice: '${z}' is an alias for 'seal-use update'. Please use 'seal-use update' instead.`);let Z=I?.toLowerCase(),q=G==="changelog"||Z==="changelog"||Z==="log"||Z==="history"||G0(U.options.changelog)===!0,V=Z==="check"||G0(U.options.check)===!0||G0(U.options["check-only"])===!0,w=G0(U.options["bg-save"])===!0||G0(U.options["silent-save"])===!0,M=S(U.options.version)??S(U.options.tag)??(!q&&!V&&!w&&I&&!I.startsWith("-")?I:void 0);await ky0(Y,{checkOnly:V||w,changelogOnly:q,limit:s0(U.options.limit),force:G0(U.options.force),targetVersion:M,repo:S(U.options.repo),bgSave:w});return}if(G==="tools"&&I==="list"){Dy0();return}if(G==="corps"||G==="corp"){if(I==="regression"||I==="test-regression"){await Ir("regression",Q,U);return}await WS0(I,Q,U);return}if(G==="rules"&&I==="lint"&&(("file"in U.options)||("f"in U.options))){let Z;try{Z=M1(S(U.options.corp))}catch{Z={id:"local",name:"Local Workspace",source:{type:"native"}}}await ro(I,Q,null,Z,U);return}if(G==="auth"&&(I==="extract-keys"||I==="extract-key"||I==="extract-hose-keys"||I==="hose-extract-keys")){await To(Q,U);return}if(G==="auth"&&(I==="link"||I==="seal-link")&&(("from-link"in U.options)||Q==="from-link")){await $j(I,null,U);return}let W=M1(S(U.options.corp));if(G==="source"){await qy0(I,W);return}if(G==="auth"){await $j(I,W,U);return}let X=await B1(W);if(G==="users"){await cy0(I,Q,X,W,U);return}if(G==="contacts"){await MS0(I,Q,X,W,U);return}if(G==="data"){await NS0(I,X,W,U);return}if(G==="llm"){await ug0(I,X,W,U);return}if(G==="permissions"){await lg0(I,X,W,U);return}if(G==="billing"){await VS0(I,X,W,U);return}if(G==="webhook"||G==="webhooks"){await gT(I,Q,X,W,U);return}if(G==="context"){await AS0(X,W,U);return}if(G==="rules"){await ro(I,Q,X,W,U);return}if(G==="approval-runs"){await Hv0(I,Q,X,W,U);return}if(G==="analytics"){await Xv0(I,Q,X,W,U);return}if(G==="simulation"){await Gy0(I,Q,X,W,U);return}if(G==="deploy"){await PS0(I,Q,U.command[3],X,W,U);return}if(G==="preference"||G==="preferences"){await sg0(I,Q,U.command[3],U.command[4],X,W,U);return}if(G==="tool"){await Oy0(I,X,W,U);return}throw Error(`Unknown command: ${U.command.join(" ")}. Run 'seal-use help' for available commands.`)}var py0,Wx1,Xx1,Zx1,dy0;var mo=m(()=>{m6();z3();Wv0();Zv0();jo();LS0();wS0();OS0();DS0();BS0();Ao();TS0();Rg0();fg0();bg0();cg0();mg0();og0();ag0();Yy0();Uy0();Ur();Hy0();Zy0();Vy0();My0();Ny0();Ay0();iy0();Qr();ny0();Uo();O8();O4();Z4();el();m1();py0=Gr(Gr(Gr(Hx1(import.meta.url)))),Wx1=new Set(["update","upgrade","up","self-update","selfupdate"]),Xx1=new Set(["config","service","stop","http","serve","update","tools","corps","corp","tool","source","auth","users","contacts","data","llm","permissions","billing","webhook","webhooks","context","rules","approval-runs","analytics","simulation","deploy","preference","preferences","mcp","server","mcp-config","skill","openapi","probe","doctor","changelog","test"]),Zx1=new Set(["http","server","web","mcp"]);dy0=Promise.resolve()});function Mx1($){let{command:Y}=Eq($),U=(Y[0]??"").toLowerCase();return{area:Lx1[U]??U,actionTokens:Y.slice(1).map((z)=>z.toLowerCase())}}function ly0($){let Y,U;try{({area:Y,actionTokens:U}=Mx1($))}catch{return!1}if(U.length===0&&wx1.has(Y))return!0;if(Y==="tool"){let I=U[0];return I!==void 0&&d_0(I)}let z=Fx1[Y];if(!z)return!1;return z.some((I)=>{let Q=I.split(" ").filter(Boolean);if(Q.length===0)return U.length===0;if(Q.length>U.length)return!1;return Q.every((J,K)=>J===U[K])})}var Lx1,Fx1,wx1;var oy0=m(()=>{jq();Z4();Lx1={corp:"corps",webhooks:"webhook",preferences:"preference"},Fx1={corps:["list","search","get","current"],rules:["count","list","versions","version","diff","diff-one","get","search","lint","linters","pull","map"],webhook:["ready","status","list","get","resource-pack export","resource-pack preview"],"approval-runs":["summary","stats","count","export","flow","list","search","pick","bridge","get","cited-rules","document-summary","attachments","result","link","url"],simulation:["batch-records","status","wait","specifications","approval-d Line truncated
`);Q(I)})})}var ZE=8787,qE="127.0.0.1";var Gr=m(()=>{Ey0();J3()});async function jy0($){let Y=s0($.options.port)??s0($.options.p),U=h($.options.host)??h($.options.h),I=await VE({port:Y,host:U}),Q=()=>{I.close(()=>{process.exit(0)})};process.on("SIGINT",Q),process.on("SIGTERM",Q),await new Promise(()=>{})}var Cy0=m(()=>{q4();Gr()});async function Ry0($,Y,U,I){if($==="config"||$==="get"){await x0("seal_llm_config_get",Y,U,{},E0(I.options));return}if($==="providers"||$==="list"){await x0("seal_llm_providers_list",Y,U,{},E0(I.options));return}throw Error(`Unknown llm command: ${$??""}. Run 'seal-use help' for available commands.`)}var _y0=m(()=>{O4();l1()});async function vy0($,Y){if($==="config"||$==="json"){Hr();return}let{startServer:U}=await gy0().then(() => hy0);U()}function Hr(){R0({mcpServers:{"seal-use":{type:"stdio",command:"seal-use",args:["mcp"],env:{SEAL_USE_MCP_ENABLED:"true"}}}})}var Sy0=m(()=>{l1()});function yy0($){let Y=HE();R0(Y,{...E0($.options),allowFull:!0})}var ky0=m(()=>{Kr();l1()});async function xy0($,Y,U,I){if($==="available"){await x0("seal_permissions_available_list",Y,U,{},E0(I.options));return}if($==="configs"||$==="list"){await x0("seal_permissions_configs_list",Y,U,{},E0(I.options));return}throw Error(`Unknown permissions command: ${$??""}. Run 'seal-use help' for available commands.`)}var fy0=m(()=>{O4();l1()});import{readFileSync as uy0}from"node:fs";async function by0($,Y,U,I,Q,J,K){if(!$||$==="get"){await x0("seal_preference_get",Q,J,{},E0(K.options));return}if($==="decision"){if(Y==="update"||!Y){let z=h(K.options.input),G=z?JSON.parse(uy0(z,"utf8")):E8(K.json);if(!G||Object.keys(G).length===0)throw Error(`Usage: seal-use preference decision update --json '{"explicitApprove":"..."}'`);await x0("seal_preference_decision_update",Q,J,{...G,dryRun:G0(K.options.dryRun)??G0(K.options["dry-run"])},E0(K.options));return}}if($==="thinking-depth"||$==="thinkingDepth"){if(Y==="set"){let z=h(K.options.default)??h(K.options.level)??I;if(z!=="medium"&&z!=="high")throw Error("Usage: seal-use preference thinking-depth set --default <medium|high>");await x0("seal_preference_thinking_depth_set",Q,J,{defaultLevel:z,dryRun:G0(K.options.dryRun)??G0(K.options["dry-run"])},E0(K.options));return}if(Y==="policies"){if(U==="list"||!U){await x0("seal_preference_thinking_depth_policies_list",Q,J,{},E0(K.options));return}if(U==="upsert"){let z=h(K.options.input),G=z?JSON.parse(uy0(z,"utf8")):E8(K.json);if(!G||!G.id||!G.name)throw Error(`Usage: seal-use preference thinking-depth policies upsert --json '{"id":"...","name":"...","level":"high"}'`);await x0("seal_preference_thinking_depth_policies_upsert",Q,J,{...G,dryRun:G0(K.options.dryRun)??G0(K.options["dry-run"])},E0(K.options));return}if(U==="remove"||U==="delete"){let z=I??h(K.options.id)??h(K.options.policyId);if(!z)throw Error("Usage: seal-use preference thinking-depth policies remove <policyId>");await x0("seal_preference_thinking_depth_policies_remove",Q,J,{policyId:z,dryRun:G0(K.options.dryRun)??G0(K.options["dry-run"])},E0(K.options));return}}}throw Error(`Unknown preference action: ${$??""}. Available: get, decision update, thinking-depth set, thinking-depth policies list/upsert/remove.`)}var iy0=m(()=>{O4();q4();l1()});async function cy0($={}){let Y=Y$(),U=A4(),I=d2(Y,{stateful:U.stateful,defaultCorpId:U.defaultCorpId,corpId:$.corpId},i3());console.log(`[probe] corp=${I.id} source=${I.source.type}`);let Q=await nz(I);console.log("[probe] seal enterprise"),console.log(JSON.stringify(Q,null,2));let J=await A1(I),K=await uM(J,{documentLimit:20,stylePreferencesEndpoint:I.seal.endpoints.approvalStylePreferences});console.log("[probe] approval context summary"),console.log(JSON.stringify({rules:K.rules.rules.length,hasPendingRuleDeletes:K.rules.hasPendingDeletes,documents:K.documents.articles.length,documentsTotal:K.documents.total,stylePreferences:K.stylePreferences.ok?"ok":`error: ${K.stylePreferences.error}`},null,2))}var ny0=m(()=>{l$();f6();pT();H4()});async function dy0($,Y,U){let I=Y??h(U.options.corp)??($&&$!=="--corp"?$:void 0);await cy0({corpId:I})}var py0=m(()=>{ny0();q4()});async function Wr($,Y,U,I,Q){if(!U&&!($==="lint"||$==="linters"||$==="linter-list"||$==="map"))throw Error(`rules ${$??""} requires an authenticated enterprise. Run 'seal-use corps list' to select one.`);if($==="count"){await x0("seal_approval_rules_list",U,I,{countOnly:!0},E0(Q.options));return}if($==="list"){if(G0(Q.options.count)){await x0("seal_approval_rules_list",U,I,{countOnly:!0},E0(Q.options));return}let K=s0(Q.options.limit),z=s0(Q.options.offset);if(G0(Q.options.summary)){await x0("seal_approval_rules_list",U,I,{fields:pv0,limit:K,offset:z},E0(Q.options));return}let G=await P$("seal_approval_rules_list",U,I,{limit:K,offset:z}),H=E0(Q.options);mv0(G,H.allowFull===!0||Boolean(H.outputFile)),R0(G,H);return}if($==="clear"){let K=G0(Q.options.yes)===!0,z=G0(Q.options.dryRun)??G0(Q.options["dry-run"])??!K;if(!K&&!z)throw U$("Refusing to clear rules without --ye Line truncated
`).filter(Boolean),J=Q.slice(-Y);return{logFile:U,lines:J,totalLines:Q.length}}async function cx1($){let Y=ME($),U=qr($),I=sq($);sy0($.stateDir);let Q=$.port??(process.env.PORT?Number.parseInt(process.env.PORT,10):ZE),J=$.host??(process.env.HOST?process.env.HOST:qE);FE(Y,`${process.pid}
`,{mode:384}),FE(U,JSON.stringify({pid:process.pid,port:Q,host:J,version:$.version,startedAt:new Date().toISOString()},null,2),{mode:384}),lz(I,`service starting on http://${J}:${Q} pid=${process.pid}`);let K=null;try{K=await VE({port:Q,host:J,silent:!0}),lz(I,`service listening pid=${process.pid}`)}catch(G){if(lz(I,`service failed to bind port ${Q}: ${G instanceof Error?G.message:String(G)}`),wE(Y)===process.pid)u9(Y,{force:!0}),u9(U,{force:!0});throw G}let z=()=>{if(K)K.close(),K=null;if(wE(Y)===process.pid)u9(Y,{force:!0}),u9(U,{force:!0});lz(I,`stopped pid=${process.pid}`)};await new Promise((G)=>{let H=!1,W=()=>{if(H)return;H=!0,z(),process.off("SIGTERM",W),process.off("SIGINT",W),G()};process.once("SIGTERM",W),process.once("SIGINT",W)})}function ly0($){sy0($.stateDir);let Y=nI($);if(Y.running)return Y;let U=$.launcher??{command:process.execPath,args:[$.entryFile]},I=[...U.args??[],"service","run"];if($.port)I.push("--port",String($.port));if($.host)I.push("--host",String($.host));let Q=fx1(U.command,I,{cwd:$.appRoot,detached:!0,stdio:["ignore","ignore","ignore"],env:process.env});Q.unref();let J=ME($);return FE(J,`${Q.pid}
`,{mode:384}),lz(sq($),`started pid=${Q.pid}`),{started:!0,...nI($)}}function oy0($,Y={}){let U=ME($),I=qr($),Q=wE(U);if(!Q||!ry0(Q,$.appRoot))return u9(U,{force:!0}),u9(I,{force:!0}),Y.quiet?void 0:{stopped:!1,reason:"not running"};return process.kill(Q,"SIGTERM"),u9(U,{force:!0}),u9(I,{force:!0}),lz(sq($),`stop requested pid=${Q}`),Y.quiet?void 0:{stopped:!0,pid:Q}}function ry0($,Y){if(!nx1($))return!1;try{let U=ux1("ps",["-p",String($),"-o","command="],{encoding:"utf8"}),I=U.trim().split(/\s+/).filter(Boolean),Q=I.indexOf("service"),J=Q!==-1&&I[Q+1]==="run",K=U.includes(Y)||I.some((z)=>/(^|[\\/])(seal-use|seal-home)(\.exe)?$/.test(z));return J&&K}catch{return!1}}function nx1($){try{return process.kill($,0),!0}catch{return!1}}function ME($){return Zr($.stateDir,"service.pid")}function qr($){return Zr($.stateDir,"service.json")}function sq($){return Zr($.stateDir,"service.log")}function wE($){if(!LE($))return;let Y=Number(Xr($,"utf8").trim());return Number.isInteger(Y)&&Y>0?Y:void 0}function sy0($){bx1($,{recursive:!0,mode:448})}function lz($,Y){FE($,`${new Date().toISOString()} ${Y}
`,{flag:"a",mode:384})}var Vr=m(()=>{Gr()});import{homedir as dx1}from"node:os";import{join as px1}from"node:path";async function Fr($,Y,U){let I=U?s0(U.options.port)??s0(U.options.p):void 0,Q=U?h(U.options.host)??h(U.options.h):void 0,J=U?s0(U.options.lines)??s0(U.options.n):void 0,K=await e3($,{appRoot:Y.appRoot,entryFile:Y.entryFile,stateDir:Lr,version:X1,launcher:Y.launcher,port:I,host:Q},{maxLines:J});if(K!==void 0)R0(K)}var Lr;var wr=m(()=>{J3();Vr();l1();q4();Lr=px1(dx1(),".config","seal-use")});import{existsSync as mx1,readFileSync as ay0}from"node:fs";async function ty0($,Y,U,I,Q){if($==="batch-records"||$==="records"){let J=Y??h(Q.options.batchId)??h(Q.options["batch-id"]);if(!J)throw Error("Usage: seal-use simulation batch-records <batchId>");await x0("seal_simulation_batch_records_get",U,I,{batchId:J,query:h(Q.options.query)},E0(Q.options));return}if($==="create"||$==="run"){let J=h(Q.options.mode)??h(Q.options.sourceSystem)??h(Q.options["source-system"])??"hosecloud",K=J==="material-pack"?"material_pack":J,z=h(Q.options.schemaConfig)??h(Q.options["schema-config"]),G=z?JSON.parse(ay0(z,"utf8")):void 0,H=h(Q.options.input),W=H?JSON.parse(ay0(H,"utf8")):E8(Q.json),X=h(Q.options.packageId)??h(Q.options["package-id"]),Z=n6(Q.options.packageIds)??n6(Q.options["package-ids"])??(X?[X]:void 0),q=n6(Q.options.flowIds)??n6(Q.options["flow-ids"])??n6(Q.options.documentSn)??n6(Q.options["document-sn"]),V=h(Q.options.signKey)??h(Q.options["sign-key"])??h(Q.options.integration),w=G0(Q.options.wait)===!0,M=G0(Q.options.noWait)??G0(Q.options["no-wait"])??(w?!1:!0),F=await P$("seal_simulation_batch_create",U,I,{mode:K,sourceSystem:K,flowIds:q,documentSn:q,rejectNodeName:h(Q.options.rejectNode)??h(Q.options["reject-node"])??null,thinkingDepthOverride:h(Q.options.thinkingDepth)??h(Q.options["thinking-depth"]),skipInvoiceGeneration:G0(Q.options.skipInvoiceGeneration)??G0(Q.options["skip-invoice-generation"]),skipExpenseExtraction:G0(Q.options.skipExpenseExtraction)??G0(Q.options["skip-expense-extraction"]),disableAttachmentCache:G0(Q.options.disableAttachmentCache)??G0(Q.options["disable-attachment-cache"]),signKey:V,packageIds:Z,packageId:X,templateId:h(Q.options.templateId)??h(Q.options["template-id"]),schemaConfig:G,requestIds:n6(Q.options.requestIds)??n6(Q.options["request-ids"]),workflowTypeId:h(Q.options.workflowTypeId)??h(Q.options["workflow-type-id"]),flowStatusList:n6(Q.options.flowStatusList)?.map(Number)??n6(Q.options["flow-status-list"])?.map(Number),businessCodes:n6(Q.options.businessCodes)??n6(Q.options["business-codes"]),documentType:h(Q.options.documentType)??h(Q.options["document-type"]),startTime:s0(Q.options.startTime)??s0(Q.options["start-time"]),endTime:s0(Q.options.endTime)??s0(Q.options["end-time"]),status:n6(Q.options.status),limit:s0(Q.options.limit),noWait:M,rawParams:W});if(w&&F&&typeof F==="object"&&"batchId"in F&&typeof F.batchId==="string"){await x0("seal_simulation_batch_wait",U,I,{batchId:F.batchId,timeout:h(Q.options.timeout),pollInterval:h(Q.options.pollInterval)??h(Q.options["poll-interval"])},E0(Q.options));return}R0(F,E0(Q.options));return}if($==="wait"){let J=Y??h(Q.options.batchId)??h(Q.options["batch-id"]);if(!J)throw Error("Usage: seal-use simulation wait <batchId> [--timeout 10m] [--poll-interval 2s]");await x0("seal_simulation_batch_wait",U,I,{batchId:J,timeout:h(Q.options.timeout),pollInterval:h(Q.options.pollInterval)??h(Q.options["poll-interval"])},E0(Q.options));return}if($==="status"){let J=Y??h(Q.options.batchId)??h(Q.options["batch-id"]);if(!J)throw Error("Usage: seal-use simulation status <batchId>");await x0("seal_simulation_batch_status",U,I,{batchId:J},E0(Q.options));return}if($==="clean"||$==="delete"){let J=Y??h(Q.options.batchId)??h(Q.options["batch-id"]);if(!J)throw Error("Usage: seal-use simulation clean <batchId>");await x0("seal_simulation_batch_clean",U,I,{batchId:J},E0(Q.options));return}if($==="specifications"){let J=Y??h(Q.options.integration)??h(Q.options.signKey)??h(Q.options["sign-key"]);await x0("seal_simulation_specifications_list",U,I,{signKey:J},E0(Q.options));return}if($==="approval-definitions"||$==="definitions"){await x0("seal_simulation_feishu_approval_definitions_list",U,I,{},E0(Q.options));return}if($==="list"){await x0("seal_simulation_batches_list",U,I,{limit:s0(Q.options.limit)},E0(Q.options));return}if($==="get"){let J=Y??h(Q.options.batchId)??h(Q.options["batch-id"]);if(!J)throw Error("Usage: seal-use simulation get <batchId>");await x0("seal_simulation_batch_get",U,I,{batchId:J},E0(Q.options));return}if($==="templates"){await x0("seal_simulation_templates_get",U,I,{},E0(Q.options));return}if($==="integrations"){await x0("seal_simulation_integrations_get",U,I,{},E0(Q.options));return}if($==="package-upload"){let J=Y??h(Q.options.file);if(!J)throw Error("Usage: seal-use simulation package-upload <材料包.zip>");if(!mx1(J))throw Error(`File not found: ${J}`);await x0("seal_simulation_material_package_upload",U,I,{filePath:J},E0(Q.o Line truncated
`);return}if($==="install"||$==="init"||$==="sync"){let I=G0(U.options.local)||G0(U.options.workspace),Q=h(U.options.dir)??h(U.options.target)??Y,J=Q?Q:I?OE(process.cwd(),".agents","skills","seal-use"):cI(),K=Ky0(J),z=!I&&!Q,G=z?mo():void 0,H=z?ro():void 0;R0({installed:!0,targetDir:K.targetDir,fileCount:K.files.length,files:K.files,...G?{antigravity:G}:{},...H?{hosts:H}:{}});return}if($==="status"||$==="get"||!$){let I=cI(),Q=OE(process.cwd(),".agents","skills","seal-use"),J=lo(),K=so();R0({global:{dir:I,installed:$k0(OE(I,"SKILL.md"))},local:{dir:Q,installed:$k0(OE(Q,"SKILL.md"))},antigravity:J,hosts:K});return}throw Error(`Unknown skill command: ${$}. Run 'seal-use help' for available commands.`)}var Uk0=m(()=>{to();lq();q4();l1()});async function Ik0($,Y){if($==="config"){R0(await nz(Y));return}throw Error(`Unknown source command: ${$??""}. Run 'seal-use help' for available commands.`)}var Qk0=m(()=>{pT();l1()});function Mr($){if(typeof $!=="string"||!$.trim())return"UNKNOWN";let Y=$.toUpperCase().trim();if(Y==="APPROVE"||Y==="PASS")return"APPROVE";if(Y==="REJECT"||Y==="DENIED")return"REJECT";if(Y==="MANUAL"||Y==="ASSISTED")return"MANUAL";if(Y==="ERROR"||Y==="FAILED")return"ERROR";return Y}async function Jk0($){let{sourceCorp:Y,targetCorp:U,sourceClient:I,targetClient:Q,samples:J=10,dryRun:K=!1,pollIntervalMs:z=2000,timeoutMs:G=45000,snPrefix:H="REG_",fetchFn:W=fetch}=$;if(U.environment!=="test")throw new X4(`重放目标企业「${U.name}」(${U.id}) 的环境为「${U.environment}」,非测试环境!
`+"硬性安全规定:自动化回归测试矩阵严禁在生产环境直接运行。必须绑定并指定测试环境(testCorp)。",2,`seal-use corps bind-test ${Y.id} <testCorpId>`);let X=await oY(Q),q=(Array.isArray(X.features)?X.features:[]).find((p)=>p?.code==="ai-approval"),V=typeof q?.balance==="number"?q.balance:0,w=typeof q?.deductionAmount==="number"&&q.deductionAmount>0?q.deductionAmount:120,M=J*w;if(V<M)throw new X4(`测试企业「${U.name}」AI 审批额度不足:当前剩余 ${V} 点,本次回归抽样 ${J} 笔需要约 ${M} 点。
`+"为防止测试环境额度耗尽中断业务,已硬性拦截并拒绝发起测试单据注入。",2,`请为测试企业「${U.id}」充值 AI 审批额度,或降低抽样笔数 (--samples ${Math.max(1,Math.floor(V/w))})`);let F=await x4(I,{limit:J,status:"completed"}),N=Array.isArray(F.records)?F.records:[];if(N.length===0){let p=await x4(I,{limit:J});N=Array.isArray(p.records)?p.records:[]}if(N.length===0)throw new X4(`在母企业「${Y.name}」(${Y.id}) 中未检索到任何历史审批单据,无法抽取回归样本。`,2);if(N=N.slice(0,J),K){let p=N.map((a)=>{let $0=a.sourceDocumentSN??a.id,y=a?.result?.decision??a.aiDecision??a?.decision,d=Mr(y),Y0=a?.result?.summary??a.aiSummary;return{sn:$0,sourceRecordId:a.id,prodDecision:d,prodSummary:Y0,status:"DRY_RUN"}});return{ok:!0,verdict:"DRY_RUN",safeToPublish:!0,timestamp:new Date().toISOString(),sourceCorp:{id:Y.id,name:Y.name,environment:Y.environment??"production"},targetCorp:{id:U.id,name:U.name,environment:U.environment??"test"},quota:{featureCode:"ai-approval",balanceBefore:V,deductionAmount:w,estimatedRequired:M},metrics:{sampleCount:p.length,successCount:p.length,failureCount:0,matchCount:p.length,flipCount:0,concordanceRate:1},flips:[],records:p}}let O=await Zp(Q,U,$.webhookSelector),D=[];for(let p of N){let a=Date.now(),$0=p.sourceDocumentSN??p.id,y=Mr(p?.result?.decision??p.aiDecision??p?.decision),d=p?.result?.summary??p.aiSummary;try{let Y0=await G4(I,p.id),R=`${H}${$0}`,o=Wp(Y0,{snPrefix:H,docIdPrefix:H});await Xp(O.incomingDocumentWebhook.url,O.secret,o,W,P6(U.seal));let e=null,O0=Date.now();while(Date.now()-O0<G){await new Promise((X0)=>setTimeout(X0,z));let t=await x4(Q,{sourceDocumentSN:R,limit:1});if(t.records&&t.records.length>0){let X0=t.records[0];if(X0.status==="completed"||X0.status==="failed"){e=X0;break}}}if(!e){D.push({sn:$0,sourceRecordId:p.id,prodDecision:y,prodSummary:d,status:"FAILED",error:`测试租户单据审核超时 (${Math.round(G/1000)}s 未完成)`,durationMs:Date.now()-a});continue}let T0=Mr(e?.result?.decision??e.aiDecision??e?.decision??(e.status==="completed"?"APPROVE":"ERROR")),y0=e?.result?.summary??e.aiSummary,v0=y===T0,o0=v0?"MATCHED":"FLIPPED",q1={sn:$0,sourceRecordId:p.id,prodDecision:y,prodSummary:d,testRecordId:e.id,testDecision:T0,testSummary:y0,status:o0,durationMs:Date.now()-a};if(!v0)q1.diff={from:y,to:T0,reasonDiff:y0&&d&&y0!==d?`生产: ${d.slice(0,60)}... -> 测试: ${y0.slice(0,60)}...`:void 0};D.push(q1)}catch(Y0){D.push({sn:$0,sourceRecordId:p.id,prodDecision:y,prodSummary:d,status:"FAILED",error:Y0 instanceof Error?Y0.message:String(Y0),durationMs:Date.now()-a})}}let P=D.filter((p)=>p.status==="MATCHED"||p.status==="FLIPPED"),T=D.filter((p)=>p.status==="MATCHED"),B=D.filter((p)=>p.status==="FLIPPED"),E=D.filter((p)=>p.status==="FAILED").length,C=T.length,b=B.length,x=C+b,g=x>0?C/x:0,i=b>0,c=i?"REGRESSIONS_DETECTED":"CLEAN",I0=!i&&E===0,k;try{let p=await oY(Q),$0=(Array.isArray(p.features)?p.features:[]).find((y)=>y?.code==="ai-approval");if(typeof $0?.balance==="number")k=$0.balance}catch{}return{ok:!i&&E===0,verdict:c,safeToPublish:I0,timestamp:new Date().toISOString(),sourceCorp:{id:Y.id,name:Y.name,environment:Y.environment??"production"},targetCorp:{id:U.id,name:U.name,environment:U.environment??"test"},quota:{featureCode:"ai-approval",balanceBefore:V,deductionAmount:w,estimatedRequired:M,balanceAfter:k},metrics:{sampleCount:D.length,successCount:P.length,failureCount:E,matchCount:C,flipCount:b,concordanceRate:Number(g.toFixed(4))},flips:B,records:D}}function Kk0($){let{sourceCorp:Y,targetCorp:U,verdict:I,safeToPublish:Q,metrics:J,quota:K,flips:z,records:G}=$,H=I==="CLEAN"?"\uD83D\uDFE2 决策完全一致 (CLEAN - 无回归)":I==="DRY_RUN"?"⚪ 预演模式 (DRY-RUN)":"\uD83D\uDD34 发现决策翻转 (REGRESSIONS_DETECTED)",W=["",`\uD83E\uDDEA [Seal Use Test] 规则回归测试矩阵: 生产「${Y.name}」-> 测试靶场「${U.name}」`,` 判定: ${H} · 准许发布: ${Q?"YES (可安全上线)":"NO (存在行为偏离/待复核)"}`," "+"─".repeat(65),` 样本总数: ${J.sampleCount} | 一致通过: ${J.matchCount} | 决策翻转: ${J.flipCount} | 异常失败: ${J.failureCount}`,` 一致率: ${(J.concordanceRate*100).toFixed(1)}% | 消耗预估: ${K.estimatedRequired} 点 (余量: ${K.balanceBefore}${K.balanceAfter!==void 0?` -> ${K.balanceAfter}`:""})`," "+"─".repeat(65)];if(z.length>0){W.push(` ⚠️ 决策翻转清单 (${z.length} 笔单据在新规则下结果改变):`);for(let X of z)if(W.push(` • 单据 [${X.sn}]: 原生产判定「${X.prodDecision}」 ➔ 测试新判定「${X.testDecision}」`),X.diff?.reasonDiff)W.push(` 理由差异: ${X.diff.reasonDiff}`);W.push(" "+"─".repeat(65)),W.push(" \uD83D\uDC49 建议: 请检查上述翻转单据是否符合预期修正。若为意外误杀,请调整测试环境规则后再次回归。")}else if(I==="CLEAN")W.push(" ✓ 全部样本在新规则下的审核决策与生产历史 100% Line truncated
`)}var zk0=m(()=>{BP();H4();sZ()});async function Or($,Y,U){let I=($??Y??"regression").toLowerCase();if(I==="regression"||I==="regress"||I==="matrix"){let Q=h(U.options.corp)??(Y&&Y!==I?Y:void 0),J=M1(Q),K=J,z=J;if(J.environment==="test"){z=J;let O=h(U.options["prod-corp"])??h(U.options.prod)??J.prodCorpId;if(!O)throw new X4(`测试企业「${J.name}」(${J.id}) 未绑定生产母企业,无法拉取历史样本。
`+"请建立绑定或通过 --prod-corp 参数指定生产企业来源。",2,`seal-use corps bind-test <prodCorpId> ${J.id}`);K=M1(O)}else{K=J;let O=h(U.options["test-corp"])??h(U.options.test)??J.testCorpId;if(!O)throw new X4(`生产企业「${J.name}」(${J.id}) 未绑定测试靶场企业。
`+"硬性规定:回归测试严禁在生产环境直接运行。必须绑定并指定测试环境(testCorp)。",2,`seal-use corps bind-test ${J.id} <testCorpId>`);z=M1(O)}let G=await A1(K),H=await A1(z),W=s0(U.options.samples)??s0(U.options.limit)??s0(U.options.n)??10,X=G0(U.options["dry-run"]),Z=G0(U.options["fail-on-flips"]),q=s0(U.options["poll-interval"])??2000,V=s0(U.options.timeout)??45000,w=h(U.options["sn-prefix"])??"REG_",M=h(U.options.webhook)??h(U.options.selector),F=await Jk0({sourceCorp:K,targetCorp:z,sourceClient:G,targetClient:H,samples:W,dryRun:X,pollIntervalMs:q,timeoutMs:V,snPrefix:w,failOnFlips:Z,webhookSelector:M});if(!(G0(U.options.quiet)||G0(U.options.silent)))console.error(Kk0(F));if(R0(F),Z&&!F.ok)throw new X4(`回归测试发现 ${F.metrics.flipCount} 笔单据决策翻转,已按 --fail-on-flips 策略非零终止。`,1);return}throw new X4(`未知的 test 子命令: "${I}"。
可用子命令: seal-use test regression [--corp <id>] [--samples <N>] [--dry-run]`,2,"seal-use test regression --help")}var Gk0=m(()=>{J$();O4();q4();l1();f6();zk0()});async function Hk0($,Y,U,I){if(!$)throw Error("Usage: seal-use tool <toolName> [--json '{...}']");await x0($,Y,U,E8(I.json),E0(I.options))}var Wk0=m(()=>{O4();q4();l1()});function Xk0(){R0(vq.map(($)=>({name:$.name,description:$.description})))}var Zk0=m(()=>{Sq();l1()});function NE($=process.execPath,Y=import.meta.url){if(Y.includes("/$bunfs/")||Y.includes("\\$bunfs\\"))return!0;let U=$.toLowerCase().replace(/\\/g,"/");return!U.endsWith("/bun")&&!U.endsWith("/bun.exe")&&!U.endsWith("/node")&&!U.endsWith("/node.exe")}var qk0=m(()=>{lq()});import{existsSync as lx1,mkdirSync as ox1,readFileSync as rx1,renameSync as sx1,writeFileSync as ax1}from"node:fs";import{homedir as tx1}from"node:os";import{dirname as ex1,join as $f1}from"node:path";import{spawn as Yf1}from"node:child_process";function Vk0($){return $.replace(/\.\d+Z$/,"Z")}function Lk0(){let $=process.env[Uf1]?.trim();if($)return $;return Qf1}function Fk0($=Lk0()){if(!lx1($))return null;try{let Y=rx1($,"utf-8"),U=JSON.parse(Y);if(U&&typeof U==="object"&&typeof U.latestVersion==="string"&&typeof U.checkedAt==="string")return{...U,checkedAt:Vk0(U.checkedAt)};return null}catch{return null}}function aq($,Y=Lk0()){try{let U=ex1(Y);ox1(U,{recursive:!0,mode:448});let I={checkedAt:Vk0($.checkedAt??new Date().toISOString()),latestVersion:$.latestVersion,publishedAt:$.publishedAt,releaseUrl:$.releaseUrl},Q=`${Y}.tmp.${Date.now()}.${Math.random().toString(36).slice(2,8)}`;ax1(Q,JSON.stringify(I,null,2),{mode:384}),sx1(Q,Y)}catch{}}function wk0($,Y=If1){if(!$||!$.checkedAt)return!0;let U=new Date($.checkedAt).getTime();if(Number.isNaN(U))return!0;return Date.now()-U>Y}function Mk0($){if(process.env.SEAL_DISABLE_BG_UPDATE==="1"||!1||process.env.CI)return!1;if(!$||!$.command)return!1;try{let Y=$.command,U=[...$.args??[],"update","check","--bg-save"];return Yf1(Y,U,{detached:!0,stdio:"ignore",env:{...process.env,SEAL_DISABLE_BG_UPDATE:"1"}}).unref(),!0}catch{return!1}}var Uf1="SEAL_USE_UPDATE_CACHE_FILE",If1=86400000,Qf1;var Nr=m(()=>{Qf1=$f1(tx1(),".config","seal-use","update-cache.json")});import{chmodSync as Jf1,mkdirSync as Kf1,readdirSync as zf1,realpathSync as Ok0,renameSync as Dr,rmSync as Gf1,unlinkSync as Pk0,writeFileSync as Nk0}from"node:fs";import{basename as Hf1,dirname as Wf1,isAbsolute as Xf1,join as AE,relative as Zf1}from"node:path";import{spawn as qf1,spawnSync as $7}from"node:child_process";async function Ek0($,Y={}){let U={appRoot:$.appRoot,entryFile:$.entryFile,stateDir:Lr,version:X1,launcher:$.launcher},I=Y.repo||process.env[Vf1]?.trim()||process.env[Lf1]?.trim()||Tk0,Q=Y.targetVersion?.trim(),J=Q&&Q.toLowerCase()!=="latest"?Q:void 0;if(J){let D=J.replace(/^v/,""),P=_k0(D,X1);if(P<0)if(!wg&&Y.force);else{R0({updated:!1,currentVersion:X1,targetVersion:D,mode:NE()?"binary":"source",message:!wg?`Cannot downgrade seal-use from dev build v${X1} to release v${D}. Use --force to overwrite.`:`Cannot downgrade seal-use from v${X1} to older version v${D}. Updates must be forward-only.`});return}if(P===0&&!Y.force){R0({updated:!1,currentVersion:X1,targetVersion:D,mode:NE()?"binary":"source",message:`seal-use is already at version v${X1}. Use --force to reinstall.`});return}}if(Y.changelogOnly){let D=await BE(I,Y.limit??10);R0({currentVersion:X1,totalQueried:D.length,releases:D.map((P)=>({version:P.version,tagName:P.tagName,publishedAt:P.publishedAt,author:P.author,releaseNotes:P.notes,releaseUrl:P.htmlUrl,isCurrent:P.version===X1,isNewer:y5(P.version,X1)}))});return}if(!NE()){if(Y.checkOnly){let P=await BE(I,30),T=P[0],B=T?.version??X1,E=P.find((x)=>x.version===X1),C=y5(B,X1),b=P.filter((x)=>y5(x.version,X1));if(T?.version)aq({latestVersion:T.version,publishedAt:T.publishedAt,releaseUrl:T.htmlUrl});if(Y.bgSave)return;R0({updated:!1,updateAvailable:C,currentVersion:X1,currentVersionPublishedAt:E?.publishedAt,latestVersion:B,latestVersionPublishedAt:T?.publishedAt,behindCount:b.length,pendingReleases:b.map((x)=>({version:x.version,tagName:x.tagName,publishedAt:x.publishedAt,author:x.author,releaseNotes:x.notes,releaseUrl:x.htmlUrl})),releaseNotes:T?.notes??"",releaseUrl:T?.htmlUrl??"",mode:"source",message:"当前运行的是开发版。正式用户请安装正式版后使用 seal-use update。"});return}let D=nI(U).running;if(D)await e3("stop",U);try{Ak0("git",["-C",$.appRoot,"pull","--ff-only"])}catch(P){console.error(`⚠️ 开发版更新同步失败,继续刷新本地依赖: ${P instanceof Error?P.message:String(P)}`)}if(Ak0("bun",["install"],{cwd:$.appRoot}),D)await e3("start",U);R0({updated:!0,serviceRestarted:D,version:X1,mode:"source"});return}if(Nf1())try{await Df1($,Y,U,I,J);return}catch(D){console.error(`⚠️ Homebrew 自动更新失败,回退至原生二进制更新: ${D instanceof Error?D.message:String(D)}`)}let K=wf1(),z=Mf1(),G=await BE(I,30),H=J?G.find((D)=>D.version Line truncated
`)}catch{}}async function Pf1($,Y,U,I){let Q=Br(),J=[],K=U?U.startsWith("v")?U:`v${U}`:void 0,z=I||$.split("/").pop()||"";if(Q!=="github"){if(K&&z)J.push(`https://git.ying-qing.cn/gitea/seal-use/releases/download/${K}/${z}`,`https://git.ying-qing.cn/gitea/seal-home/releases/download/${K}/${z}`);if($.startsWith("https://git.ying-qing.cn"))J.push($)}if(Q!=="gitea")if(K&&z){let w=`https://github.com/${Tk0}/releases/download/${K}/${z}`;if(!process.env.CI)J.push(`https://ghfast.top/${w}`,`https://gh.ddlc.top/${w}`);J.push(w)}else if($.includes("github.com")){if(!process.env.CI)J.push(`https://ghfast.top/${$}`,`https://gh.ddlc.top/${$}`);J.push($)}else J.push($);let G=Array.from(new Set(J)),H,W=6000,X=6000,Z=307200,q=1e4,V=180000;for(let w=0;w<G.length;w++){let M=G[w],F=new AbortController,N="",O=(B)=>{N=B;try{F.abort()}catch{}},D=setTimeout(()=>{O("Connection timed out (no response headers within 6s)")},W),P,T;try{DE(`==> [${w+1}/${G.length}] Downloading via: ${M}`);let B=await fetch(M,{signal:F.signal});if(D)clearTimeout(D),D=void 0;if(!B.ok)throw Error(`HTTP ${B.status} ${B.statusText}`);P=setTimeout(()=>{O("Overall download time exceeded 3 minutes")},V);let E=Number(B.headers.get("content-length"))||0,C=B.body?.getReader();if(!C){let c=Buffer.from(await B.arrayBuffer());if(c.length<1000)throw Error(`Downloaded content is suspiciously small (${c.length} bytes)`);Nk0(Y,c),DE(`✓ Download succeeded (${(c.length/1024/1024).toFixed(1)} MB)`);return}let b=[],x=0,g=0;T=setTimeout(()=>{if(x<Z){let c=(x/1024).toFixed(1);O(`Initial transfer too slow (${c} KB < 300 KB in 6s), switching mirror...`)}},X);while(!0){let c=C.read(),I0,k=new Promise((y,d)=>{I0=setTimeout(()=>{d(Error("Data transfer stalled (no chunk received for 10s)"))},q)}),p;try{p=await Promise.race([c,k])}finally{if(I0)clearTimeout(I0)}let{done:a,value:$0}=p;if(a)break;if($0){if(b.push($0),x+=$0.length,T&&x>=Z)clearTimeout(T),T=void 0;let y=Date.now();if(y-g>200){g=y;let d=E?Math.round(x/E*100):0,Y0=(x/1048576).toFixed(1),R=E?(E/1048576).toFixed(1):"?";try{process.stderr.write(`\r ↳ Progress: ${d}% (${Y0} / ${R} MB)...`)}catch{}}}}try{process.stderr.write(`
`)}catch{}let i=Buffer.concat(b);if(i.length<1000)throw Error(`Downloaded content is suspiciously small (${i.length} bytes)`);Nk0(Y,i),DE(`✓ Download completed successfully (${(i.length/1024/1024).toFixed(1)} MB)`);return}catch(B){if(D)clearTimeout(D);if(T)clearTimeout(T);if(P)clearTimeout(P);let E=N||(B instanceof Error?B.message:String(B));H=Error(E),DE(`
↳ Mirror failed: ${H.message}`)}finally{if(D)clearTimeout(D);if(T)clearTimeout(T);if(P)clearTimeout(P)}}throw Error(`Failed to download asset from all mirrors: ${H?.message}`)}function Ck0($){let Y;try{Y=zf1($,{withFileTypes:!0})}catch{return[]}let U=[];for(let I of Y){let Q=AE($,I.name);if(I.isDirectory())U.push(...Ck0(Q));else if(I.isFile())U.push(Q)}return U}function Rk0($,Y,U){let I=Y==="windows"?"seal-use.exe":"seal-use",Q=Ck0($);return Q.find((J)=>Hf1(J)===I)??Q[0]??U}function Tf1($,Y,U){let I=$7("tar",["-xzf",$,"-C",Y],{stdio:"pipe"});if(I.status!==0)throw Error(`Failed to extract tar archive: ${I.stderr.toString()}`);return Pk0($),Rk0(Y,U,$)}function Ef1($,Y,U){let I=$7("unzip",["-q","-o",$,"-d",Y],{stdio:"pipe"});if(I.status!==0)throw Error(`Failed to extract zip archive: ${I.stderr.toString()}`);return Pk0($),Rk0(Y,U,$)}function _k0($,Y){let U=$.replace(/^v/,"").split(".").map((Q)=>Number.parseInt(Q,10)||0),I=Y.replace(/^v/,"").split(".").map((Q)=>Number.parseInt(Q,10)||0);for(let Q=0;Q<Math.max(U.length,I.length);Q++){let J=U[Q]??0,K=I[Q]??0;if(J>K)return 1;if(J<K)return-1}return 0}function y5($,Y){return _k0($,Y)>0}function Ak0($,Y,U={}){let I=$7($,Y,{cwd:U.cwd,encoding:"utf8",stdio:["ignore","pipe","pipe"]});if(I.stdout)console.error(I.stdout.trimEnd());if(I.stderr)console.error(I.stderr.trimEnd());if(I.status!==0)throw Error(`${$} ${Y.join(" ")} failed with status ${I.status}`)}var Tk0="yunyingk/seal-use",tq="yunyingk/seal-home",Vf1="SEAL_USE_GITHUB_REPO",Lf1="SEAL_HOME_GITHUB_REPO";var vk0=m(()=>{qk0();lq();Nr();J3();Vr();l1();wr()});async function Sk0($,Y,U,I,Q){if($==="create"){let J=h(Q.options.name)??Y,K=h(Q.options.phone);if(!J||!K)throw Error("Usage: seal-use users create --name <name> --phone <phone> [--dept <deptId>]");let z=h(Q.options.dept)??h(Q.options.departmentId);await x0("seal_user_create",U,I,{name:J,phone:K,departmentIds:z?[z]:void 0},E0(Q.options));return}if($==="reset-password"){let J=Y??h(Q.options.userId);if(!J)throw Error("Usage: seal-use users reset-password <userId>");await x0("seal_user_reset_password",U,I,{userId:J},E0(Q.options));return}if($==="search"||$==="list"){let J=Y??h(Q.options.keyword)??h(Q.options.query)??"";await x0("seal_user_search",U,I,{keyword:J},E0(Q.options));return}if($==="get"){let J=Y??h(Q.options.userId);if(!J)throw Error("Usage: seal-use users get <userId>");await x0("seal_user_get",U,I,{userId:J},E0(Q.options));return}if($==="delete"){let J=Y??h(Q.options.userId);if(!J)throw Error("Usage: seal-use users delete <userId>");await x0("seal_user_delete",U,I,{userId:J},E0(Q.options));return}if($==="activate"){let J=Y??h(Q.options.userId);if(!J)throw Error("Usage: seal-use users activate <userId>");await x0("seal_user_activate",U,I,{userId:J},E0(Q.options));return}if($==="delegation"||$==="impersonate"){let J=Y??h(Q.options.userId)??h(Q.options.phone);if(!J)throw Error("Usage: seal-use users delegation <userIdOrPhone> [--note <note>]");let K=h(Q.options.note);await x0("seal_user_delegation_create",U,I,{userIdOrPhone:J,note:K},E0(Q.options));return}throw Error(`Unknown users command: ${$??""}. Run 'seal-use help' for available commands.`)}var hk0=m(()=>{O4();q4();l1()});import{dirname as Ar,join as jf1}from"node:path";import{fileURLToPath as Cf1}from"node:url";function Sf1($){if(!$.length)return!1;let Y=$[0]?.toLowerCase(),U=$[1]?.toLowerCase();if(Y&&vf1.has(Y))return!0;if((Y==="service"||Y==="daemon")&&U==="run")return!0;return!1}function rq($,Y={}){if(Sf1($))return kk0($,Y);let U=yk0.then(()=>kk0($,Y));return yk0=U.then(()=>{return},()=>{return}),U}async function kk0($,Y){let U=[],I=[],Q=console.log,J=console.error,K={appRoot:Y.appRoot??gk0,entryFile:Y.entryFile??jf1(Y.appRoot??gk0,"src","cli.ts"),launcher:Y.launcher};console.log=(...z)=>{U.push(Lo(z))},console.error=(...z)=>{I.push(Lo(z))};try{return await hf1($,K),{stdout:gq(U),stderr:gq(I),isError:!1,exitCode:0}}catch(z){let G=yq(z instanceof Error?z.message:String(z)),H=zz(z);if(I.push(G),H.nextAction&&!G.includes("Next action:"))I.push(`\uD83D\uDC49 Next action: ${H.nextAction}`);return{stdout:gq(U),stderr:gq(I),isError:!0,exitCode:H.exitCode}}finally{console.log=Q,console.error=J}}async function hf1($,Y){let U=hq($),[I,Q,J]=U.command,K=I?.toLowerCase(),z=K?Rf1.has(K):!1,G=z?"update":K;if(G==="version"||G==="v"||Boolean(U.options.version)||Boolean(U.options.v)||Boolean(U.options.V)){let Z=Fk0(),q=Z?.latestVersion?y5(Z.latestVersion,mY.version):!1,V={...mY,...Z?.latestVersion?{latestVersion:Z.latestVersion,updateAvailable:q,lastCheckedAt:Z.checkedAt}:{}};if(q&&Z?.latestVersion)console.error(`\uD83D\uDCA1 发现新版本可用: v${mY.version} -> v${Z.latestVersion}`),console.error(`\uD83D\uDC49 Next action: seal-use update
`);if(R0(V),wk0(Z))Mk0(Y.launcher);return}let H=nv0(U);if(H.isHelp){lv0(H.target);return}if(!G||!_f1.has(G))throw Error(`Unknown command: ${U.command.join(" ")}. Run 'seal-use help' for available commands.`);if(G==="webhook"&&(Q==="resource-pack"||Q==="pack"||Q==="material-pack")&&J==="preview"){let Z=U.command[3]??h(U.options.file)??h(U.options.input);if(!Z)throw Error("Usage: seal-use webhook resource-pack preview <资源包.zip>");await rv0(Z,cz(U.options));return}if(G==="openapi"){yy0(U);return}if(G==="mcp-config"){Hr();return}if(G==="skill"){Yk0(Q,J,U);return}if(G==="mcp"||G==="server"){await vy0(Q,U);return}if(G==="probe"){await dy0(Q,J,U);return}if(G==="doctor"){await My0(Q,J,U);return}if(G==="test"){await Or(Q,J,U);return}if(G==="config"){Ig0(Q,J,U);return}if(G==="service"){await Fr(Q,Y,U);return}if(G==="stop"){await Fr("stop",Y,U);return}if(G==="http"||G==="serve"){await jy0(U);return}if(z||G==="changelog"){if(z&&I!=="update")console.error(`⚠️ Notice: '${I}' is an alias for 'seal-use update'. Please use 'seal-use update' instead.`);let Z=Q?.toLowerCase(),q=G==="changelog"||Z==="changelog"||Z==="log"||Z==="history"||G0(U.options.changelog)===!0,V=Z==="check"||G0(U.options.check)===!0||G0(U.options["check-only"])===!0,w=G0(U.options["bg-save"])===!0||G0(U.options["silent-save"])===!0,M=h(U.options.version)??h(U.options.tag)??(!q&&!V&&!w&&Q&&!Q.startsWith("-")?Q:void 0);await Ek0(Y,{checkOnly:V||w,changelogOnly:q,limit:s0(U.options.limit),force:G0(U.options.force),targetVersion:M,repo:h(U.options.repo),bgSave:w});return}if(G==="tools"&&Q==="list"){Xk0();return}if(G==="corps"||G==="corp"){if(Q==="regression"||Q==="test-regression"){await Or("regression",J,U);return}await ah0(Q,J,U);return}if(G==="rules"&&Q==="lint"&&(("file"in U.options)||("f"in U.options))){let Z;try{Z=M1(h(U.options.corp))}catch{Z={id:"local",name:"Local Workspace",source:{type:"native"}}}await Wr(Q,J,null,Z,U);return}if(G==="auth"&&(Q==="extract-keys"||Q==="extract-key"||Q==="extract-hose-keys"||Q==="hose-extract-keys")){await bo(J,U);return}if(G==="auth"&&(Q==="link"||Q==="seal-link")&&(("from-link"in U.options)||J==="from-link")){await zE(Q,null,U);return}let W=M1(h(U.options.corp));if(G==="source"){await Ik0(Q,W);return}if(G==="auth"){await zE(Q,W,U);return}let X=await A1(W);if(G==="users"){await Sk0(Q,J,X,W,U);return}if(G==="contacts"){await Jg0(Q,J,X,W,U);return}if(G==="data"){await zg0(Q,X,W,U);return}if(G==="llm"){await Ry0(Q,X,W,U);return}if(G==="permissions"){await xy0(Q,X,W,U);return}if(G==="billing"){await Yg0(Q,X,W,U);return}if(G==="webhook"||G==="webhooks"){await iT(Q,J,X,W,U);return}if(G==="context"){await Hg0(X,W,U);return}if(G==="rules"){await Wr(Q,J,X,W,U);return}if(G==="approval-runs"){await sv0(Q,J,X,W,U);return}if(G==="analytics"){await tv0(Q,J,X,W,U);return}if(G==="simulation"){await ty0(Q,J,X,W,U);return}if(G==="deploy"){await Xg0(Q,J,U.command[3],X,W,U);return}if(G==="preference"||G==="preferences"){await by0(Q,J,U.command[3],U.command[4],X,W,U);return}if(G==="tool"){await Hk0(Q,X,W,U);return}throw Error(`Unknown command: ${U.command.join(" ")}. Run 'seal-use help' for available commands.`)}var gk0,Rf1,_f1,vf1,yk0;var zr=m(()=>{f6();J3();av0();ev0();io();Ug0();Qg0();Kg0();Gg0();Wg0();xo();Zg0();Oy0();Cy0();_y0();Sy0();ky0();fy0();iy0();py0();my0();wr();ey0();Uk0();Qk0();Gk0();Wk0();Zk0();vk0();Nr();hk0();wo();J$();O4();q4();Vo();l1();gk0=Ar(Ar(Ar(Cf1(import.meta.url)))),Rf1=new Set(["update","upgrade","up","self-update","selfupdate"]),_f1=new Set(["config","service","stop","http","serve","update","tools","corps","corp","tool","source","auth","users","contacts","data","llm","permissions","billing","webhook","webhooks","context","rules","approval-runs","analytics","simulation","deploy","preference","preferences","mcp","server","mcp-config","skill","openapi","probe","doctor","changelog","test"]),vf1=new Set(["http","server","web","mcp"]);yk0=Promise.resolve()});function xf1($){let{command:Y}=hq($),U=(Y[0]??"").toLowerCase();return{area:gf1[U]??U,actionTokens:Y.slice(1).map((I)=>I.toLowerCase())}}function xk0($){let Y,U;try{({area:Y,actionTokens:U}=xf1($))}catch{return!1}if(U.length===0&&kf1.has(Y))return!0;if(Y==="tool"){let Q=U[0];return Q!==void 0&&uv0(Q)}let I=yf1[Y];if(!I)return!1;return I.some((Q)=>{let J=Q.split(" ").filter(Boolean);if(J.length===0)return U.length===0;if(J.length>U.length)return!1;return J.every((K,z)=>K===U[z])})}var gf1,yf1,kf1;var fk0=m(()=>{Sq();q4();gf1={corp:"corps",webhooks:"webhook",preferences:"preference"},yf1={corps:["list","search","get","current"],rules:["count","list","versions","version","diff","diff-one","get","search","lint","linters","pull","map"],webhook:["ready","status","list","get","resource-pack export","resource-pack preview"],"approval-runs":["summary","stats","count","export","flow","list","search","pick","bridge","get","cited-rules","document-summary","attachments","result","link","url"],simulation:["batch-records","status","wait","specifications","approval-d Line truncated
`)?"":`
`}`);process.exitCode=$.exitCode}var t3,ay0,Mj="seal_cli",rq="seal_cli_write",ty0="SEAL_USE_MCP_ENABLED",ey0="SEAL_HOME_MCP_ENABLED",Dx1;var pg0=m(async()=>{J00();H00();T$();mo();oy0();O8();z3();t3=Ox1(import.meta.url),ay0=t3.includes("/dist/mcp/")||t3.includes("\\dist\\mcp\\")?lq(lq(lq(t3))):lq(lq(t3));Dx1=Boolean(J0.main==J0.module||!import.meta.url.includes("$bunfs")&&process.argv[1]&&ry0(process.argv[1])===ry0(t3));if(Dx1)if(process.argv[2]==="--seal-use-cli")await Nx1();else try{Uk0()}catch($){console.error($),process.exitCode=1}});await pg0();export{cq as tokenizeCommand,Uk0 as startServer,$k0 as resolveMcpEnabled,Yk0 as createServer,ty0 as SEAL_MCP_ENABLED_ENV,rq as SEAL_CLI_WRITE_TOOL_NAME,Mj as SEAL_CLI_TOOL_NAME,ey0 as LEGACY_SEAL_MCP_ENABLED_ENV};
`}`);process.exitCode=$.exitCode}var Y7,ik0,TE="seal_cli",YV="seal_cli_write",ck0="SEAL_USE_MCP_ENABLED",nk0="SEAL_HOME_MCP_ENABLED",bf1;var gy0=m(async()=>{D00();P00();z6();zr();fk0();J$();J3();Y7=ff1(import.meta.url),ik0=Y7.includes("/dist/mcp/")||Y7.includes("\\dist\\mcp\\")?eq(eq(eq(Y7))):eq(eq(Y7));bf1=Boolean(K0.main==K0.module||!import.meta.url.includes("$bunfs")&&process.argv[1]&&uk0(process.argv[1])===uk0(Y7));if(bf1)if(process.argv[2]==="--seal-use-cli")await uf1();else try{mk0()}catch($){console.error($),process.exitCode=1}});await gy0();export{oq as tokenizeCommand,mk0 as startServer,dk0 as resolveMcpEnabled,pk0 as createServer,ck0 as SEAL_MCP_ENABLED_ENV,YV as SEAL_CLI_WRITE_TOOL_NAME,TE as SEAL_CLI_TOOL_NAME,nk0 as LEGACY_SEAL_MCP_ENABLED_ENV};
+36 -32
View File
@@ -33,43 +33,47 @@ export async function handleAuthExtractKeysCommand(maybeName: string | undefined
});
}
export async function handleAuthCommand(action: string | undefined, corp: CorpConfig, args: ParsedArgs) {
export async function handleAuthCommand(action: string | undefined, corp: CorpConfig | null, args: ParsedArgs) {
const subAction = args.command[2]?.toLowerCase();
const fromLink = stringOption(args.options["from-link"]) ?? (subAction === "from-link" ? args.command[3] : undefined);
if ((action === "seal-link" || action === "link" || (action === "hose-link" && corp?.source?.type === "seal")) && fromLink) {
const note = stringOption(args.options.note);
const session = await exchangeHoseAssistLink(fromLink);
const client = createSealClientForUrl(session.sealUrl, session.token);
const me = await getMe(client);
assertHoseAssistTenantMatches(session.corpId, me.tenant as unknown as Record<string, unknown>);
const delegation = await createDelegation(client, { note });
printJson({
tenant: {
id: me.tenant.id,
name: me.tenant.name,
tenantSlug: me.tenant.tenantSlug,
corpId: session.corpId
},
user: {
id: me.user.id,
name: me.user.name,
providerUserId: me.user.providerUserId,
isAdmin: me.user.isAdmin
},
delegation,
expiresIn: session.expiresIn
});
return;
}
if (!corp) {
throw new Error(`auth ${action ?? ""} requires an enterprise. Provide --corp <id> or select one.`);
}
if (action === "check" || action === "diagnose" || action === "status" || action === "test" || action === "doctor") {
printJson(await diagnoseAuth(corp));
return;
}
if (action === "seal-link" || action === "link" || (action === "hose-link" && corp?.source?.type === "seal")) {
const subAction = args.command[2]?.toLowerCase();
const fromLink = stringOption(args.options["from-link"]) ?? (subAction === "from-link" ? args.command[3] : undefined);
if (fromLink) {
const note = stringOption(args.options.note);
const session = await exchangeHoseAssistLink(fromLink);
const client = createSealClientForUrl(session.sealUrl, session.token);
const me = await getMe(client);
assertHoseAssistTenantMatches(session.corpId, me.tenant as unknown as Record<string, unknown>);
const delegation = await createDelegation(client, { note });
printJson({
tenant: {
id: me.tenant.id,
name: me.tenant.name,
tenantSlug: me.tenant.tenantSlug,
corpId: session.corpId
},
user: {
id: me.user.id,
name: me.user.name,
providerUserId: me.user.providerUserId,
isAdmin: me.user.isAdmin
},
delegation,
expiresIn: session.expiresIn
});
return;
}
if (action === "seal-link" || action === "link" || (action === "hose-link" && corp.source?.type === "seal")) {
const client = await createSealClient(corp);
if (subAction === "list") {
+20 -14
View File
@@ -28,18 +28,24 @@ import type { ParsedArgs } from "../types.js";
export async function handleRulesCommand(
action: string | undefined,
maybeName: string | undefined,
client: Awaited<ReturnType<typeof createSealClient>>,
client: Awaited<ReturnType<typeof createSealClient>> | null,
corp: CorpConfig,
args: ParsedArgs
) {
// lint, linters, and map actions can run without a network client
const clientless = action === "lint" || action === "linters" || action === "linter-list" || action === "map";
if (!client && !clientless) {
throw new Error(`rules ${action ?? ""} requires an authenticated enterprise. Run 'seal-use corps list' to select one.`);
}
if (action === "count") {
await runTool("seal_approval_rules_list", client, corp, { countOnly: true }, outputOptions(args.options));
await runTool("seal_approval_rules_list", client!, corp, { countOnly: true }, outputOptions(args.options));
return;
}
if (action === "list") {
if (booleanOption(args.options.count)) {
await runTool("seal_approval_rules_list", client, corp, { countOnly: true }, outputOptions(args.options));
await runTool("seal_approval_rules_list", client!, corp, { countOnly: true }, outputOptions(args.options));
return;
}
@@ -48,7 +54,7 @@ export async function handleRulesCommand(
if (booleanOption(args.options.summary)) {
await runTool(
"seal_approval_rules_list",
client,
client!,
corp,
{
fields: RULE_SUMMARY_FIELDS,
@@ -60,7 +66,7 @@ export async function handleRulesCommand(
return;
}
const result = await runToolResult("seal_approval_rules_list", client, corp, { limit, offset });
const result = await runToolResult("seal_approval_rules_list", client!, corp, { limit, offset });
const output = outputOptions(args.options);
protectLargeRuleListOutput(result, output.allowFull === true || Boolean(output.outputFile));
printJson(result, output);
@@ -76,7 +82,7 @@ export async function handleRulesCommand(
`seal-use rules clear --corp ${corp.id} --dry-run`
);
}
const result = await runToolResult("seal_approval_rules_clear", client, corp, {
const result = await runToolResult("seal_approval_rules_clear", client!, corp, {
dryRun,
recode: booleanOption(args.options.recode)
});
@@ -95,7 +101,7 @@ export async function handleRulesCommand(
}
if (action === "versions") {
await runTool("seal_approval_rule_versions_list", client, corp, {}, outputOptions(args.options));
await runTool("seal_approval_rule_versions_list", client!, corp, {}, outputOptions(args.options));
return;
}
@@ -104,7 +110,7 @@ export async function handleRulesCommand(
if (!version) throw new Error("Usage: seal-use rules version <versionId|versionNumber|latest>");
await runTool(
"seal_approval_rule_version_get",
client,
client!,
corp,
parseRuleVersionSelector(version),
outputOptions(args.options)
@@ -121,7 +127,7 @@ export async function handleRulesCommand(
const singleSelector = args.command[4];
await runTool(
"seal_approval_rule_version_diff",
client,
client!,
corp,
{
from,
@@ -142,7 +148,7 @@ export async function handleRulesCommand(
const code = rawCode ? (rawCode.startsWith("#") || rawCode.startsWith("rule-") ? rawCode : (rawCode.match(/^\d+$/) ? `#${rawCode.padStart(4, "0")}` : rawCode)) : undefined;
await runTool(
"seal_approval_rule_get",
client,
client!,
corp,
{
...ruleVersionGetOptions(stringOption(args.options.version)),
@@ -160,7 +166,7 @@ export async function handleRulesCommand(
if (!keyword) throw new Error("Usage: seal-use rules search <keyword> [--version <versionId|versionNumber|latest>]");
await runTool(
"seal_approval_search",
client,
client!,
corp,
{
keywords: [keyword],
@@ -183,7 +189,7 @@ export async function handleRulesCommand(
const out = stringOption(args.options.out) ?? stringOption(args.options.file) ?? stringOption(args.options.f);
await runTool(
"seal_approval_rules_pull",
client,
client!,
corp,
{
version,
@@ -203,7 +209,7 @@ export async function handleRulesCommand(
const result = await runToolResult(
"seal_approval_rules_push",
client,
client!,
corp,
{
file,
@@ -231,7 +237,7 @@ export async function handleRulesCommand(
if (action === "lint") {
await runTool(
"seal_approval_rules_lint",
client,
client as Awaited<ReturnType<typeof createSealClient>>,
corp,
{
file: stringOption(args.options.file) ?? stringOption(args.options.f),
+10 -58
View File
@@ -1,58 +1,10 @@
export type CliExitCode = 1 | 2 | 10 | 11 | 12;
export class CliError extends Error {
readonly exitCode: CliExitCode;
readonly nextAction?: string;
constructor(message: string, exitCode: CliExitCode, nextAction?: string) {
super(message);
this.name = "CliError";
this.exitCode = exitCode;
this.nextAction = nextAction;
}
}
export class PayloadTooLargeError extends CliError {
constructor(message: string, nextAction?: string) {
super(message, 12, nextAction);
this.name = "PayloadTooLargeError";
}
}
export function usageError(message: string, nextAction?: string): CliError {
return new CliError(message, 2, nextAction);
}
export function confirmationRequired(message: string, nextAction: string): CliError {
return new CliError(message, 10, nextAction);
}
export function classifyCliError(error: unknown): {
exitCode: CliExitCode;
nextAction?: string;
} {
if (error instanceof CliError) {
return { exitCode: error.exitCode, nextAction: error.nextAction };
}
const value = error instanceof Error ? error.message : String(error);
const status = responseStatus(error);
if (status === 401 || status === 403 || /(?:^|\s)(?:token|bearer|session) (?:expired|missing|invalid)/i.test(value)) {
return { exitCode: 11 };
}
if (/^(?:Usage:|Unknown (?:[a-z0-9_-]+ )?command|Invalid (?:number|boolean|command)|--json must|Missing required JSON field)/i.test(value)) {
return { exitCode: 2 };
}
if (/^Refusing to (?:clear|delete)|without --yes|without confirm=true/i.test(value)) {
return { exitCode: 10 };
}
return { exitCode: 1 };
}
function responseStatus(error: unknown): number | undefined {
if (!error || typeof error !== "object") return undefined;
const response = (error as { response?: unknown }).response;
if (!response || typeof response !== "object") return undefined;
const status = (response as { status?: unknown }).status;
return typeof status === "number" ? status : undefined;
}
// Re-export from core — this file is the legacy entry point.
// Domain-layer code should import from "../core/errors.js" directly.
export {
type CliExitCode,
CliError,
PayloadTooLargeError,
usageError,
confirmationRequired,
classifyCliError
} from "../core/errors.js";
+2 -2
View File
@@ -360,7 +360,7 @@ async function dispatch(argv: string[], runtime: CliRuntime) {
source: { type: "native" }
} as any;
}
await handleRulesCommand(action, maybeName, null as any, corp, args);
await handleRulesCommand(action, maybeName, null, corp, args);
return;
}
@@ -377,7 +377,7 @@ async function dispatch(argv: string[], runtime: CliRuntime) {
(action === "link" || action === "seal-link") &&
("from-link" in args.options || maybeName === "from-link")
) {
await handleAuthCommand(action, null as any, args);
await handleAuthCommand(action, null, args);
return;
}
+1 -1
View File
@@ -1,7 +1,7 @@
import { accessSync, constants, existsSync, readdirSync, statSync } from "node:fs";
import { homedir } from "node:os";
import { join } from "node:path";
import { PRIMARY_LINTERS_DIR, OFFICIAL_LINTERS_DIR } from "../../domains/seal/linter/loader.js";
import { PRIMARY_LINTERS_DIR, OFFICIAL_LINTERS_DIR } from "../paths.js";
import { VERSION } from "../../version.js";
import { loadCorpConfigs, loadGlobalConfig } from "../config/loader.js";
import { getDefaultGlobalSkillDir } from "../embedded-skill.js";
+8 -426
View File
@@ -1,426 +1,8 @@
import type { KyInstance } from "ky";
import type { CorpConfig } from "../config/types.js";
import * as api from "../../domains/seal/api.js";
export interface TenantHealthCheck {
id: string;
name: string;
status: "pass" | "warn" | "fail";
summary: string;
details: Record<string, unknown>;
recommendation?: string;
}
export interface TenantDoctorDiagnosis {
ok: boolean;
verdict: "HEALTHY" | "DEGRADED" | "BLOCKED";
timestamp: string;
corp: {
id: string;
name: string;
environment: "production" | "test";
sourceType: string;
boundCorpId?: string;
boundCorpRole?: "prodParent" | "testTarget";
boundCorpRoleDescription?: string;
};
summary: {
totalChecks: number;
passedChecks: number;
warningChecks: number;
failedChecks: number;
};
checks: TenantHealthCheck[];
quota: {
featureCode: string;
balance: number;
deductionAmount: number;
estimatedRuns: number;
status: "sufficient" | "low" | "exhausted";
};
rules: {
totalCount: number;
activeCount: number;
quotaUsed?: number;
quotaRemaining?: number;
};
webhooks: {
integrationCount: number;
hasReplayChannel: boolean;
activeWebhookId?: string;
};
}
export async function diagnoseTenantContract(
client: KyInstance,
corp: CorpConfig
): Promise<TenantDoctorDiagnosis> {
const checks: TenantHealthCheck[] = [];
const environment = corp.environment === "test" ? "test" : "production";
const boundCorpId = environment === "test" ? corp.prodCorpId : corp.testCorpId;
const boundCorpRole = environment === "test" ? "prodParent" : "testTarget";
const boundCorpRoleDescription = boundCorpId
? environment === "test"
? "已绑定生产母企业 (上游配置与样本源)"
: "已绑定测试靶场 (下游隔离演练环境)"
: undefined;
// 1. Auth & Admin Probe
let userDetail: any = null;
let tenantDetail: any = null;
try {
const whoami = await api.getMe(client);
userDetail = whoami.user;
tenantDetail = whoami.tenant;
const isAdmin = Boolean(userDetail?.isAdmin || userDetail?.permissions?.includes("*"));
if (isAdmin) {
checks.push({
id: "auth_identity",
name: "身份与权限契约",
status: "pass",
summary: `已认证为管理员「${userDetail.name ?? "未知"}」(${userDetail.id ?? ""}),具备完整操作权限`,
details: {
userId: userDetail.id,
userName: userDetail.name,
isAdmin: true,
permissionLevel: "超级管理员(具备完整操作权限)",
tenantName: tenantDetail?.name,
tenantSlug: tenantDetail?.tenantSlug,
permissions: userDetail.permissions
}
});
} else {
checks.push({
id: "auth_identity",
name: "身份与权限契约",
status: "warn",
summary: `已认证为普通用户「${userDetail.name ?? "未知"}」,非超级管理员,部分配置操作可能受限`,
details: {
userId: userDetail.id,
userName: userDetail.name,
isAdmin: false,
permissionLevel: "普通用户(部分管理配置受限)",
tenantName: tenantDetail?.name,
permissions: userDetail.permissions
},
recommendation: "建议使用具有管理权限的企业主账号执行规则修改与集成发布"
});
}
} catch (err) {
checks.push({
id: "auth_identity",
name: "身份与权限契约",
status: "fail",
summary: `鉴权握手失败:${err instanceof Error ? err.message : String(err)}`,
details: { error: String(err) },
recommendation: `请执行 seal-use auth login --corp ${corp.id} 重新登录或更新 Token`
});
}
// 2. Billing & AI Approval Quota Probe
let quotaInfo = {
featureCode: "ai-approval",
balance: 0,
deductionAmount: 120,
estimatedRuns: 0,
status: "exhausted" as "sufficient" | "low" | "exhausted"
};
let ruleQuota = {
used: 0,
remaining: 0
};
try {
const billing = await api.getBillingStatus(client);
const features = Array.isArray(billing.features) ? billing.features : [];
// Find AI Approval feature
const aiApproval = features.find((f: any) => f?.code === "ai-approval");
if (aiApproval) {
const balance = typeof aiApproval.balance === "number" ? aiApproval.balance : 0;
const deductionAmount = typeof aiApproval.deductionAmount === "number" && aiApproval.deductionAmount > 0
? aiApproval.deductionAmount
: 120;
const estimatedRuns = Math.floor(balance / deductionAmount);
quotaInfo.balance = balance;
quotaInfo.deductionAmount = deductionAmount;
quotaInfo.estimatedRuns = estimatedRuns;
if (balance <= 0) {
quotaInfo.status = "exhausted";
checks.push({
id: "billing_quota",
name: "AI 审批额度余量",
status: "fail",
summary: `当前额度已耗尽 (余量 0 点),无法执行审批模拟或回归测试`,
details: { balance, deductionAmount, estimatedRuns },
recommendation: `请前往后台充值补充额度 (可通过 seal-use auth link --corp ${corp.id} 免密直达)`
});
} else if (estimatedRuns < 10) {
quotaInfo.status = "low";
checks.push({
id: "billing_quota",
name: "AI 审批额度余量",
status: "warn",
summary: `额度偏低:剩余 ${balance} 点 (单笔扣除 ${deductionAmount} 点),仅可支持约 ${estimatedRuns} 笔审核`,
details: { balance, deductionAmount, estimatedRuns },
recommendation: `建议补充额度 (可通过 seal-use auth link --corp ${corp.id} 免密直达)`
});
} else {
quotaInfo.status = "sufficient";
checks.push({
id: "billing_quota",
name: "AI 审批额度余量",
status: "pass",
summary: `额度充裕:剩余 ${balance} 点,预估可支持 ${estimatedRuns} 笔审核单据`,
details: { balance, deductionAmount, estimatedRuns }
});
}
} else {
checks.push({
id: "billing_quota",
name: "AI 审批额度余量",
status: "warn",
summary: "未检索到「ai-approval」功能包额度明细,按默认通道运行",
details: { features: features.map((f: any) => f?.code) }
});
}
// Rule quota
const ruleFeat = features.find((f: any) => f?.code === "approval-rules");
if (ruleFeat) {
ruleQuota.used = typeof ruleFeat.used === "number" ? ruleFeat.used : 0;
ruleQuota.remaining = typeof ruleFeat.remaining === "number" ? ruleFeat.remaining : 0;
}
} catch (err) {
checks.push({
id: "billing_quota",
name: "AI 审批额度余量",
status: "warn",
summary: `读取计费状态失败:${err instanceof Error ? err.message : String(err)}`,
details: { error: String(err) }
});
}
// 3. Rules & Draft State Probe
let rulesSummary = {
totalCount: 0,
activeCount: 0,
quotaUsed: ruleQuota.used,
quotaRemaining: ruleQuota.remaining
};
try {
const rulesData = await api.listApprovalRules(client);
const rules = Array.isArray(rulesData.rules) ? rulesData.rules : [];
rulesSummary.totalCount = rules.length;
rulesSummary.activeCount = rules.filter((r) => r.status === "ACTIVE").length;
if (rules.length === 0) {
checks.push({
id: "rules_status",
name: "审核规则状态",
status: "warn",
summary: "当前租户未配置任何审核规则 (规则数为 0)",
details: { totalCount: 0, activeCount: 0 },
recommendation: environment === "test" && boundCorpId
? `可运行 seal-use corps sync-test --corp ${boundCorpId} 从生产企业同步规则`
: "可运行 seal-use rules add 创建基础规则"
});
} else {
checks.push({
id: "rules_status",
name: "审核规则状态",
status: "pass",
summary: `审核规则健康:共 ${rulesSummary.totalCount} 条规则,其中生效活跃 ${rulesSummary.activeCount} 条`,
details: {
totalCount: rulesSummary.totalCount,
activeCount: rulesSummary.activeCount,
quotaUsed: ruleQuota.used,
quotaRemaining: ruleQuota.remaining
}
});
}
} catch (err) {
checks.push({
id: "rules_status",
name: "审核规则状态",
status: "fail",
summary: `拉取规则列表失败:${err instanceof Error ? err.message : String(err)}`,
details: { error: String(err) }
});
}
// 4. Webhook Integration Probe
let webhooksSummary = {
integrationCount: 0,
hasReplayChannel: false,
activeWebhookId: undefined as string | undefined
};
try {
const integrations = await api.listWebhookIntegrations(client);
webhooksSummary.integrationCount = integrations.length;
const replayChannel = integrations.find(
(i) => i.name.includes("回放") || i.name.toLowerCase().includes("replay")
);
webhooksSummary.hasReplayChannel = Boolean(replayChannel);
webhooksSummary.activeWebhookId = replayChannel?.id ?? integrations[0]?.id;
if (integrations.length === 0) {
checks.push({
id: "webhook_integrations",
name: "单据推送 Webhook 通道",
status: "pass",
summary: "未配置任何 Webhook 集成通道 (日常审批无影响;若需自动化系统推流或单据重放将自动创建)",
details: { integrationCount: 0 }
});
} else {
checks.push({
id: "webhook_integrations",
name: "单据推送 Webhook 通道",
status: "pass",
summary: `Webhook 集成通道就绪:共 ${integrations.length} 个通道${replayChannel ? ` (含专属回放通道「${replayChannel.name}」)` : ""}`,
details: {
integrationCount: integrations.length,
hasReplayChannel: webhooksSummary.hasReplayChannel,
activeWebhookId: webhooksSummary.activeWebhookId
}
});
}
} catch (err) {
checks.push({
id: "webhook_integrations",
name: "单据推送 Webhook 通道",
status: "warn",
summary: `检测 Webhook 通道失败:${err instanceof Error ? err.message : String(err)}`,
details: { error: String(err) }
});
}
// 5. Environment Pairing Probe
if (environment === "test") {
if (boundCorpId) {
checks.push({
id: "environment_binding",
name: "测试环境配对契约",
status: "pass",
summary: `测试租户已绑定生产母企业「${boundCorpId}」,具备样本拉取与配置同步能力`,
details: { environment, boundCorpId, boundCorpRole, boundCorpRoleDescription }
});
} else {
checks.push({
id: "environment_binding",
name: "测试环境配对契约",
status: "warn",
summary: "测试租户尚未绑定对应的生产母企业,无法直接拉取生产样本执行自动化回归",
details: { environment },
recommendation: `可运行 seal-use corps bind-test <prodCorpId> ${corp.id} 建立 1 对 1 绑定`
});
}
} else {
if (boundCorpId) {
checks.push({
id: "environment_binding",
name: "生产环境安全隔离契约",
status: "pass",
summary: `生产企业已绑定沙箱测试靶场「${boundCorpId}」,回归测试将严格限制在靶场中运行`,
details: { environment, boundCorpId, boundCorpRole, boundCorpRoleDescription }
});
} else {
checks.push({
id: "environment_binding",
name: "生产环境安全隔离契约",
status: "warn",
summary: "生产企业尚未绑定任何测试企业,所有回归测试功能将触发安全拦截",
details: { environment },
recommendation: `可运行 seal-use corps bind-test ${corp.id} <testCorpId> 为该生产租户绑定测试靶场`
});
}
}
// Compute overall verdict
const failedChecks = checks.filter((c) => c.status === "fail").length;
const warningChecks = checks.filter((c) => c.status === "warn").length;
const passedChecks = checks.filter((c) => c.status === "pass").length;
let verdict: "HEALTHY" | "DEGRADED" | "BLOCKED" = "HEALTHY";
if (failedChecks > 0) {
verdict = "BLOCKED";
} else if (warningChecks > 0) {
verdict = "DEGRADED";
}
return {
ok: failedChecks === 0,
verdict,
timestamp: new Date().toISOString(),
corp: {
id: corp.id,
name: corp.name,
environment,
sourceType: corp.source?.type ?? "native",
boundCorpId,
boundCorpRole,
boundCorpRoleDescription
},
summary: {
totalChecks: checks.length,
passedChecks,
warningChecks,
failedChecks
},
checks,
quota: quotaInfo,
rules: rulesSummary,
webhooks: webhooksSummary
};
}
export function formatTenantDoctorDashboard(diagnosis: TenantDoctorDiagnosis): string {
const { corp, verdict, summary, checks, quota, rules, webhooks } = diagnosis;
const verdictBadge =
verdict === "HEALTHY"
? "🟢 健康良好 (HEALTHY)"
: verdict === "DEGRADED"
? "🟡 亚健康降级 (DEGRADED)"
: "🔴 阻断受限 (BLOCKED)";
const lines: string[] = [
"",
`🏥 [Seal Use Doctor] 租户全链路契约体检: ${corp.name} (${corp.id})`,
` 状态: ${verdictBadge} · 环境: ${corp.environment.toUpperCase()} · 耗时: 实时探针`,
" " + "─".repeat(60)
];
// Core metrics overview
lines.push(
` AI 审批余量: ${quota.balance} 点 (可审约 ${quota.estimatedRuns} 笔) | 规则数: ${rules.activeCount}/${rules.totalCount} | Webhook 通道: ${webhooks.integrationCount}`
);
if (corp.boundCorpId) {
lines.push(` 配对关系: ${corp.environment === "test" ? "来源生产母企业" : "绑定的测试靶场"} -> 「${corp.boundCorpId}」`);
}
lines.push(" " + "─".repeat(60));
for (const check of checks) {
const icon = check.status === "pass" ? "✓" : check.status === "warn" ? "!" : "✗";
lines.push(` [${icon}] ${check.name}: ${check.summary}`);
if (check.recommendation) {
lines.push(` 👉 建议: ${check.recommendation}`);
}
}
lines.push(" " + "─".repeat(60));
lines.push(` 检查汇总: 通过 ${summary.passedChecks} · 告警 ${summary.warningChecks} · 失败 ${summary.failedChecks}`);
if (quota.status === "exhausted" || quota.status === "low") {
lines.push(` 👉 Next action: seal-use auth link --corp ${corp.id}`);
}
lines.push("");
return lines.join("\n");
}
// Re-export from domain layer — this file is the legacy entry point.
// tenant-diagnose inherently depends on domains/seal/api, so it now lives there.
export {
type TenantHealthCheck,
type TenantDoctorDiagnosis,
diagnoseTenantContract,
formatTenantDoctorDashboard
} from "../../domains/seal/doctor/tenant-diagnose.js";
+58
View File
@@ -0,0 +1,58 @@
export type CliExitCode = 1 | 2 | 10 | 11 | 12;
export class CliError extends Error {
readonly exitCode: CliExitCode;
readonly nextAction?: string;
constructor(message: string, exitCode: CliExitCode, nextAction?: string) {
super(message);
this.name = "CliError";
this.exitCode = exitCode;
this.nextAction = nextAction;
}
}
export class PayloadTooLargeError extends CliError {
constructor(message: string, nextAction?: string) {
super(message, 12, nextAction);
this.name = "PayloadTooLargeError";
}
}
export function usageError(message: string, nextAction?: string): CliError {
return new CliError(message, 2, nextAction);
}
export function confirmationRequired(message: string, nextAction: string): CliError {
return new CliError(message, 10, nextAction);
}
export function classifyCliError(error: unknown): {
exitCode: CliExitCode;
nextAction?: string;
} {
if (error instanceof CliError) {
return { exitCode: error.exitCode, nextAction: error.nextAction };
}
const value = error instanceof Error ? error.message : String(error);
const status = responseStatus(error);
if (status === 401 || status === 403 || /(?:^|\s)(?:token|bearer|session) (?:expired|missing|invalid)/i.test(value)) {
return { exitCode: 11 };
}
if (/^(?:Usage:|Unknown (?:[a-z0-9_-]+ )?command|Invalid (?:number|boolean|command)|--json must|Missing required JSON field)/i.test(value)) {
return { exitCode: 2 };
}
if (/^Refusing to (?:clear|delete)|without --yes|without confirm=true/i.test(value)) {
return { exitCode: 10 };
}
return { exitCode: 1 };
}
function responseStatus(error: unknown): number | undefined {
if (!error || typeof error !== "object") return undefined;
const response = (error as { response?: unknown }).response;
if (!response || typeof response !== "object") return undefined;
const status = (response as { status?: unknown }).status;
return typeof status === "number" ? status : undefined;
}
+6
View File
@@ -0,0 +1,6 @@
import { homedir } from "node:os";
import { join } from "node:path";
export const SEAL_CONFIG_DIR = join(homedir(), ".config", "seal-use");
export const PRIMARY_LINTERS_DIR = join(SEAL_CONFIG_DIR, "linters");
export const OFFICIAL_LINTERS_DIR = join(PRIMARY_LINTERS_DIR, "official");
+426
View File
@@ -0,0 +1,426 @@
import type { KyInstance } from "ky";
import type { CorpConfig } from "../../../core/config/types.js";
import * as api from "../api.js";
export interface TenantHealthCheck {
id: string;
name: string;
status: "pass" | "warn" | "fail";
summary: string;
details: Record<string, unknown>;
recommendation?: string;
}
export interface TenantDoctorDiagnosis {
ok: boolean;
verdict: "HEALTHY" | "DEGRADED" | "BLOCKED";
timestamp: string;
corp: {
id: string;
name: string;
environment: "production" | "test";
sourceType: string;
boundCorpId?: string;
boundCorpRole?: "prodParent" | "testTarget";
boundCorpRoleDescription?: string;
};
summary: {
totalChecks: number;
passedChecks: number;
warningChecks: number;
failedChecks: number;
};
checks: TenantHealthCheck[];
quota: {
featureCode: string;
balance: number;
deductionAmount: number;
estimatedRuns: number;
status: "sufficient" | "low" | "exhausted";
};
rules: {
totalCount: number;
activeCount: number;
quotaUsed?: number;
quotaRemaining?: number;
};
webhooks: {
integrationCount: number;
hasReplayChannel: boolean;
activeWebhookId?: string;
};
}
export async function diagnoseTenantContract(
client: KyInstance,
corp: CorpConfig
): Promise<TenantDoctorDiagnosis> {
const checks: TenantHealthCheck[] = [];
const environment = corp.environment === "test" ? "test" : "production";
const boundCorpId = environment === "test" ? corp.prodCorpId : corp.testCorpId;
const boundCorpRole = environment === "test" ? "prodParent" : "testTarget";
const boundCorpRoleDescription = boundCorpId
? environment === "test"
? "已绑定生产母企业 (上游配置与样本源)"
: "已绑定测试靶场 (下游隔离演练环境)"
: undefined;
// 1. Auth & Admin Probe
let userDetail: any = null;
let tenantDetail: any = null;
try {
const whoami = await api.getMe(client);
userDetail = whoami.user;
tenantDetail = whoami.tenant;
const isAdmin = Boolean(userDetail?.isAdmin || userDetail?.permissions?.includes("*"));
if (isAdmin) {
checks.push({
id: "auth_identity",
name: "身份与权限契约",
status: "pass",
summary: `已认证为管理员「${userDetail.name ?? "未知"}」(${userDetail.id ?? ""}),具备完整操作权限`,
details: {
userId: userDetail.id,
userName: userDetail.name,
isAdmin: true,
permissionLevel: "超级管理员(具备完整操作权限)",
tenantName: tenantDetail?.name,
tenantSlug: tenantDetail?.tenantSlug,
permissions: userDetail.permissions
}
});
} else {
checks.push({
id: "auth_identity",
name: "身份与权限契约",
status: "warn",
summary: `已认证为普通用户「${userDetail.name ?? "未知"}」,非超级管理员,部分配置操作可能受限`,
details: {
userId: userDetail.id,
userName: userDetail.name,
isAdmin: false,
permissionLevel: "普通用户(部分管理配置受限)",
tenantName: tenantDetail?.name,
permissions: userDetail.permissions
},
recommendation: "建议使用具有管理权限的企业主账号执行规则修改与集成发布"
});
}
} catch (err) {
checks.push({
id: "auth_identity",
name: "身份与权限契约",
status: "fail",
summary: `鉴权握手失败:${err instanceof Error ? err.message : String(err)}`,
details: { error: String(err) },
recommendation: `请执行 seal-use auth login --corp ${corp.id} 重新登录或更新 Token`
});
}
// 2. Billing & AI Approval Quota Probe
let quotaInfo = {
featureCode: "ai-approval",
balance: 0,
deductionAmount: 120,
estimatedRuns: 0,
status: "exhausted" as "sufficient" | "low" | "exhausted"
};
let ruleQuota = {
used: 0,
remaining: 0
};
try {
const billing = await api.getBillingStatus(client);
const features = Array.isArray(billing.features) ? billing.features : [];
// Find AI Approval feature
const aiApproval = features.find((f: any) => f?.code === "ai-approval");
if (aiApproval) {
const balance = typeof aiApproval.balance === "number" ? aiApproval.balance : 0;
const deductionAmount = typeof aiApproval.deductionAmount === "number" && aiApproval.deductionAmount > 0
? aiApproval.deductionAmount
: 120;
const estimatedRuns = Math.floor(balance / deductionAmount);
quotaInfo.balance = balance;
quotaInfo.deductionAmount = deductionAmount;
quotaInfo.estimatedRuns = estimatedRuns;
if (balance <= 0) {
quotaInfo.status = "exhausted";
checks.push({
id: "billing_quota",
name: "AI 审批额度余量",
status: "fail",
summary: `当前额度已耗尽 (余量 0 点),无法执行审批模拟或回归测试`,
details: { balance, deductionAmount, estimatedRuns },
recommendation: `请前往后台充值补充额度 (可通过 seal-use auth link --corp ${corp.id} 免密直达)`
});
} else if (estimatedRuns < 10) {
quotaInfo.status = "low";
checks.push({
id: "billing_quota",
name: "AI 审批额度余量",
status: "warn",
summary: `额度偏低:剩余 ${balance} 点 (单笔扣除 ${deductionAmount} 点),仅可支持约 ${estimatedRuns} 笔审核`,
details: { balance, deductionAmount, estimatedRuns },
recommendation: `建议补充额度 (可通过 seal-use auth link --corp ${corp.id} 免密直达)`
});
} else {
quotaInfo.status = "sufficient";
checks.push({
id: "billing_quota",
name: "AI 审批额度余量",
status: "pass",
summary: `额度充裕:剩余 ${balance} 点,预估可支持 ${estimatedRuns} 笔审核单据`,
details: { balance, deductionAmount, estimatedRuns }
});
}
} else {
checks.push({
id: "billing_quota",
name: "AI 审批额度余量",
status: "warn",
summary: "未检索到「ai-approval」功能包额度明细,按默认通道运行",
details: { features: features.map((f: any) => f?.code) }
});
}
// Rule quota
const ruleFeat = features.find((f: any) => f?.code === "approval-rules");
if (ruleFeat) {
ruleQuota.used = typeof ruleFeat.used === "number" ? ruleFeat.used : 0;
ruleQuota.remaining = typeof ruleFeat.remaining === "number" ? ruleFeat.remaining : 0;
}
} catch (err) {
checks.push({
id: "billing_quota",
name: "AI 审批额度余量",
status: "warn",
summary: `读取计费状态失败:${err instanceof Error ? err.message : String(err)}`,
details: { error: String(err) }
});
}
// 3. Rules & Draft State Probe
let rulesSummary = {
totalCount: 0,
activeCount: 0,
quotaUsed: ruleQuota.used,
quotaRemaining: ruleQuota.remaining
};
try {
const rulesData = await api.listApprovalRules(client);
const rules = Array.isArray(rulesData.rules) ? rulesData.rules : [];
rulesSummary.totalCount = rules.length;
rulesSummary.activeCount = rules.filter((r) => r.status === "ACTIVE").length;
if (rules.length === 0) {
checks.push({
id: "rules_status",
name: "审核规则状态",
status: "warn",
summary: "当前租户未配置任何审核规则 (规则数为 0)",
details: { totalCount: 0, activeCount: 0 },
recommendation: environment === "test" && boundCorpId
? `可运行 seal-use corps sync-test --corp ${boundCorpId} 从生产企业同步规则`
: "可运行 seal-use rules add 创建基础规则"
});
} else {
checks.push({
id: "rules_status",
name: "审核规则状态",
status: "pass",
summary: `审核规则健康:共 ${rulesSummary.totalCount} 条规则,其中生效活跃 ${rulesSummary.activeCount} 条`,
details: {
totalCount: rulesSummary.totalCount,
activeCount: rulesSummary.activeCount,
quotaUsed: ruleQuota.used,
quotaRemaining: ruleQuota.remaining
}
});
}
} catch (err) {
checks.push({
id: "rules_status",
name: "审核规则状态",
status: "fail",
summary: `拉取规则列表失败:${err instanceof Error ? err.message : String(err)}`,
details: { error: String(err) }
});
}
// 4. Webhook Integration Probe
let webhooksSummary = {
integrationCount: 0,
hasReplayChannel: false,
activeWebhookId: undefined as string | undefined
};
try {
const integrations = await api.listWebhookIntegrations(client);
webhooksSummary.integrationCount = integrations.length;
const replayChannel = integrations.find(
(i) => i.name.includes("回放") || i.name.toLowerCase().includes("replay")
);
webhooksSummary.hasReplayChannel = Boolean(replayChannel);
webhooksSummary.activeWebhookId = replayChannel?.id ?? integrations[0]?.id;
if (integrations.length === 0) {
checks.push({
id: "webhook_integrations",
name: "单据推送 Webhook 通道",
status: "pass",
summary: "未配置任何 Webhook 集成通道 (日常审批无影响;若需自动化系统推流或单据重放将自动创建)",
details: { integrationCount: 0 }
});
} else {
checks.push({
id: "webhook_integrations",
name: "单据推送 Webhook 通道",
status: "pass",
summary: `Webhook 集成通道就绪:共 ${integrations.length} 个通道${replayChannel ? ` (含专属回放通道「${replayChannel.name}」)` : ""}`,
details: {
integrationCount: integrations.length,
hasReplayChannel: webhooksSummary.hasReplayChannel,
activeWebhookId: webhooksSummary.activeWebhookId
}
});
}
} catch (err) {
checks.push({
id: "webhook_integrations",
name: "单据推送 Webhook 通道",
status: "warn",
summary: `检测 Webhook 通道失败:${err instanceof Error ? err.message : String(err)}`,
details: { error: String(err) }
});
}
// 5. Environment Pairing Probe
if (environment === "test") {
if (boundCorpId) {
checks.push({
id: "environment_binding",
name: "测试环境配对契约",
status: "pass",
summary: `测试租户已绑定生产母企业「${boundCorpId}」,具备样本拉取与配置同步能力`,
details: { environment, boundCorpId, boundCorpRole, boundCorpRoleDescription }
});
} else {
checks.push({
id: "environment_binding",
name: "测试环境配对契约",
status: "warn",
summary: "测试租户尚未绑定对应的生产母企业,无法直接拉取生产样本执行自动化回归",
details: { environment },
recommendation: `可运行 seal-use corps bind-test <prodCorpId> ${corp.id} 建立 1 对 1 绑定`
});
}
} else {
if (boundCorpId) {
checks.push({
id: "environment_binding",
name: "生产环境安全隔离契约",
status: "pass",
summary: `生产企业已绑定沙箱测试靶场「${boundCorpId}」,回归测试将严格限制在靶场中运行`,
details: { environment, boundCorpId, boundCorpRole, boundCorpRoleDescription }
});
} else {
checks.push({
id: "environment_binding",
name: "生产环境安全隔离契约",
status: "warn",
summary: "生产企业尚未绑定任何测试企业,所有回归测试功能将触发安全拦截",
details: { environment },
recommendation: `可运行 seal-use corps bind-test ${corp.id} <testCorpId> 为该生产租户绑定测试靶场`
});
}
}
// Compute overall verdict
const failedChecks = checks.filter((c) => c.status === "fail").length;
const warningChecks = checks.filter((c) => c.status === "warn").length;
const passedChecks = checks.filter((c) => c.status === "pass").length;
let verdict: "HEALTHY" | "DEGRADED" | "BLOCKED" = "HEALTHY";
if (failedChecks > 0) {
verdict = "BLOCKED";
} else if (warningChecks > 0) {
verdict = "DEGRADED";
}
return {
ok: failedChecks === 0,
verdict,
timestamp: new Date().toISOString(),
corp: {
id: corp.id,
name: corp.name,
environment,
sourceType: corp.source?.type ?? "native",
boundCorpId,
boundCorpRole,
boundCorpRoleDescription
},
summary: {
totalChecks: checks.length,
passedChecks,
warningChecks,
failedChecks
},
checks,
quota: quotaInfo,
rules: rulesSummary,
webhooks: webhooksSummary
};
}
export function formatTenantDoctorDashboard(diagnosis: TenantDoctorDiagnosis): string {
const { corp, verdict, summary, checks, quota, rules, webhooks } = diagnosis;
const verdictBadge =
verdict === "HEALTHY"
? "🟢 健康良好 (HEALTHY)"
: verdict === "DEGRADED"
? "🟡 亚健康降级 (DEGRADED)"
: "🔴 阻断受限 (BLOCKED)";
const lines: string[] = [
"",
`🏥 [Seal Use Doctor] 租户全链路契约体检: ${corp.name} (${corp.id})`,
` 状态: ${verdictBadge} · 环境: ${corp.environment.toUpperCase()} · 耗时: 实时探针`,
" " + "─".repeat(60)
];
// Core metrics overview
lines.push(
` AI 审批余量: ${quota.balance} 点 (可审约 ${quota.estimatedRuns} 笔) | 规则数: ${rules.activeCount}/${rules.totalCount} | Webhook 通道: ${webhooks.integrationCount}`
);
if (corp.boundCorpId) {
lines.push(` 配对关系: ${corp.environment === "test" ? "来源生产母企业" : "绑定的测试靶场"} -> 「${corp.boundCorpId}」`);
}
lines.push(" " + "─".repeat(60));
for (const check of checks) {
const icon = check.status === "pass" ? "✓" : check.status === "warn" ? "!" : "✗";
lines.push(` [${icon}] ${check.name}: ${check.summary}`);
if (check.recommendation) {
lines.push(` 👉 建议: ${check.recommendation}`);
}
}
lines.push(" " + "─".repeat(60));
lines.push(` 检查汇总: 通过 ${summary.passedChecks} · 告警 ${summary.warningChecks} · 失败 ${summary.failedChecks}`);
if (quota.status === "exhausted" || quota.status === "low") {
lines.push(` 👉 Next action: seal-use auth link --corp ${corp.id}`);
}
lines.push("");
return lines.join("\n");
}
+2 -3
View File
@@ -1,16 +1,15 @@
import { existsSync, mkdirSync, readFileSync, readdirSync, rmSync, unlinkSync, writeFileSync } from "node:fs";
import { homedir } from "node:os";
import { isAbsolute, join, resolve } from "node:path";
import { pathToFileURL } from "node:url";
import { PRIMARY_LINTERS_DIR, OFFICIAL_LINTERS_DIR } from "../../../core/paths.js";
import { builtinRuleLinter } from "./builtin.js";
import { hlabRuleLinter } from "./hlab.js";
import { OFFICIAL_LINTER_TEMPLATES } from "./official-templates.js";
import { strictRuleLinter } from "./strict.js";
import type { RuleLintContext, RuleLintResult, RuleLintTarget, RuleLinterFn } from "./types.js";
export const PRIMARY_LINTERS_DIR = join(homedir(), ".config", "seal-use", "linters");
export { PRIMARY_LINTERS_DIR, OFFICIAL_LINTERS_DIR };
export const OFFICIAL_SUBDIR_NAME = "official";
export const OFFICIAL_LINTERS_DIR = join(PRIMARY_LINTERS_DIR, OFFICIAL_SUBDIR_NAME);
export const LOCAL_LINTERS_DIR = join(process.cwd(), "linters");
export interface LoadedLinter {
+1 -1
View File
@@ -1,5 +1,5 @@
import type { KyInstance } from "ky";
import { CliError } from "../../../cli/errors.js";
import { CliError } from "../../../core/errors.js";
import type { CorpConfig } from "../../../core/config/types.js";
import { resolveSealCustomHeaders } from "../../../core/http/request-headers.js";
import * as api from "../api.js";
+3 -4256
View File
File diff suppressed because it is too large. Load diff
+836
View File
@@ -0,0 +1,836 @@
import { z } from "zod";
import type { KyInstance } from "ky";
import { readFileSync } from "node:fs";
import { randomBytes } from "node:crypto";
import * as api from "../api.js";
import { defaultSealUrl, ensureHoseCloseApiToken, getHoseProvisionalAuthLink, probeHoseDomain } from "../../../core/auth/hose.js";
import type { CorpConfig } from "../../../core/config/types.js";
import { loadGlobalConfig, loadCorpConfigs, getEnterprisesDirCandidates } from "../../../core/config/loader.js";
import { resolveCorpConfig } from "../../../core/config/manager.js";
import { createSealClient, createSealClientForToken } from "../../../core/http/factory.js";
import { resolveSealCustomHeaders } from "../../../core/http/request-headers.js";
import { searchApprovalContent } from "../search.js";
import { diffRuleVersions, normalizedRuleCode, truncateRuleDiff } from "../rule-diff.js";
import { hydrateRuleVersionStableIds, savePublishedRuleVersionSnapshot } from "../rule-version-snapshot.js";
import { executeApprovalRunsReplay, resolveReplayCorpPair } from "../webhook-replay.js";
import { loadRuleLinter, lintRuleBatch, lintSingleRule, type RuleLintTarget } from "../linter/index.js";
import {
loadLocalRulesFile,
saveLocalRulesFile,
localRulesToLintTargets,
type LocalRuleItem
} from "../rules-local.js";
import {
checkWebhookReadiness,
previewMaterialPack,
pushMaterialPack,
readMaterialPackFile
} from "../material-pack/index.js";
import { MaterialPackFilePolicyPatchSchema, MaterialPackFilePolicySchema } from "../material-pack/policy.js";
import { extractApprovalRunAttachments } from "../attachments.js";
import { exportApprovalRunsToExcel, normalizeTimestamp } from "../approval-runs-export.js";
import {
alignApprovalRunsWithHoseFlow,
createHoseOpenClient,
getHoseOpenFlow
} from "../../hose/index.js";
import { exportInsightReportToExcel, type InsightExportOptions } from "../insight-export.js";
import {
ThinkingPolicySchema,
type ApprovalRule,
type ApprovalRun,
type RuleSetVersion,
type SimulationBatch,
type WebhookIntegration,
type WebhookMode,
type ThinkingPolicy,
type DecisionPreferences,
type HosecloudConfigInput
} from "../types.js";
import type {
ToolContext,
SealToolDefinition,
ApprovalRunSummary,
ApprovalRunsSummaryOptions,
RuleField,
RulePushPlan,
SimulationBatchCreateInput,
HumanResultMatch
} from "./helpers.js";
import * as helpers from "./helpers.js";
const {
presentWebhookIntegration,
getConfiguredSealBaseUrl,
projectApprovalRules,
pickRuleFields,
buildRulePushPlan,
rulesHaveSameContent,
ruleChangedFields,
normalizeRuleStrictness,
parseDurationMs,
redactIntegrationSecrets,
mutationPreview,
redactPreviewValue,
buildSimulationBatchParams,
summarizeSimulationBatch,
summarizeApprovalRun,
summarizeApprovalRuns,
parseFieldPaths,
pickRunFields,
approvalRunMetadata,
summarizeApprovalRunDetail,
summarizeApprovalRunResult,
summarizeApprovalRunDocument,
extractCitedRules,
firstPath,
countPathCandidates,
getPath,
setPath,
compactObject,
asRecord,
numberFromUnknown,
flattenDocumentFields,
collectDocumentFields,
firstByLabel,
collectInvoiceSummary,
collectInvoiceObjects,
findKeywordLines,
summarizeRunBridge,
summarizeRuleVersion,
resolveRuleVersionForLookup,
findRuleInVersion,
normalizeRuleCode,
runtimeRuleIndex,
runtimeRuleIdToCode,
formatRuleCode,
pickApprovalRunCandidate,
resolveApprovalRunForUrl,
resolveSealBaseUrl,
normalizeUrl,
stringFromUnknown,
pickApprovalRuns,
timestampOf,
resolveRuleVersion,
resolveRuleVersionSelector,
filterRuns,
scalarIncludes,
objectContainsScalar,
filterRunsByHumanResult,
withApprovalRunFilters,
resolveManualApprovalStatus,
prepareApprovalRuns,
approvalRunAliases,
extractHumanResult,
findHumanResultValue,
isHumanResultKey,
stringifyHumanResultValue,
matchesRunLookup,
countBy,
localDateKey,
formatLocalDateTime,
toDate,
localParts
} = helpers;
export const approvalRunsTools = [
{
name: "seal_approval_runs_search",
description: "查询 Seal 审批/审核运行记录总表,并整理合思单据到 Langfuse trace/session 的桥接字段",
parameters: z.object({
offset: z.number().int().nonnegative().optional(),
limit: z.number().int().positive().max(100).optional(),
fromTimestamp: z.string().optional(),
toTimestamp: z.string().optional(),
startDate: z.string().optional().describe("运行记录创建开始时间戳(毫秒),对应前端 startDate"),
endDate: z.string().optional().describe("运行记录创建结束时间戳(毫秒),对应前端 endDate"),
status: z.string().optional(),
taskMode: z.string().optional(),
manualApprovalStatus: z.union([z.string(), z.array(z.string())]).optional().describe("人工审核状态,如 TERMINATED 对应已驳回"),
sourceDocumentSN: z.string().optional(),
sourceDocumentId: z.string().optional(),
humanResult: z.string().optional().describe("按人工审批结果做本地包含匹配,如 驳回、通过、reject"),
query: z.string().optional().describe("在 id、sourceDocumentSN、sourceDocumentId、documentId、Langfuse traceId 中做本地包含匹配"),
includeBridge: z.boolean().optional().describe("是否返回完整 bridge 数组;默认 false,避免长输出")
}),
handler: async (
client: KyInstance,
params: {
offset?: number;
limit?: number;
fromTimestamp?: string;
toTimestamp?: string;
startDate?: string;
endDate?: string;
status?: string;
taskMode?: string;
manualApprovalStatus?: string | string[];
sourceDocumentSN?: string;
sourceDocumentId?: string;
humanResult?: string;
query?: string;
includeBridge?: boolean;
}
) => {
const query = params.query?.trim();
const data = await api.listApprovalRuns(client, withApprovalRunFilters({
...params,
search: query
}));
const records = await prepareApprovalRuns(client, data.records, {
humanResult: params.humanResult
});
return {
...data,
records: records.map(summarizeApprovalRun),
...(params.includeBridge ? { bridge: summarizeRunBridge(records) } : {})
};
}
},
{
name: "seal_approval_runs_summary",
description: "按本地日期/时区汇总 Seal 审批运行记录,返回状态、模式统计和精简记录,避免长 JSON 输出",
parameters: z.object({
date: z.string().optional().describe("本地日期,格式 YYYY-MM-DD;默认使用 timezone 下的今天"),
timezone: z.string().optional().describe("IANA 时区,默认 Asia/Shanghai"),
offset: z.number().int().nonnegative().optional(),
limit: z.number().int().positive().max(100).optional(),
startDate: z.string().optional().describe("运行记录创建开始时间戳(毫秒),对应前端 startDate"),
endDate: z.string().optional().describe("运行记录创建结束时间戳(毫秒),对应前端 endDate"),
status: z.string().optional(),
taskMode: z.string().optional(),
manualApprovalStatus: z.union([z.string(), z.array(z.string())]).optional().describe("人工审核状态,如 TERMINATED 对应已驳回"),
sourceDocumentSN: z.string().optional(),
sourceDocumentId: z.string().optional(),
humanResult: z.string().optional().describe("按人工审批结果做本地包含匹配,如 驳回、通过、reject"),
query: z.string().optional().describe("在 id、sourceDocumentSN、sourceDocumentId、documentId、Langfuse traceId 中做本地包含匹配")
}),
handler: async (
client: KyInstance,
params: {
date?: string;
timezone?: string;
offset?: number;
limit?: number;
startDate?: string;
endDate?: string;
status?: string;
taskMode?: string;
manualApprovalStatus?: string | string[];
sourceDocumentSN?: string;
sourceDocumentId?: string;
humanResult?: string;
query?: string;
}
) => {
const timezone = params.timezone ?? "Asia/Shanghai";
const date = params.date ?? localDateKey(Date.now(), timezone) ?? "";
const data = await api.listApprovalRuns(client, {
offset: params.offset,
limit: params.limit ?? 100,
startDate: params.startDate,
endDate: params.endDate,
status: params.status,
taskMode: params.taskMode,
manualApprovalStatus: resolveManualApprovalStatus(
params.manualApprovalStatus,
params.humanResult
),
sourceDocumentSN: params.sourceDocumentSN,
sourceDocumentId: params.sourceDocumentId
});
const records = (
await prepareApprovalRuns(client, data.records, {
query: params.query,
humanResult: params.humanResult
})
).filter((record) => localDateKey(record.createdAt, timezone) === date);
return summarizeApprovalRuns(records, {
date,
timezone,
fetched: data.records.length,
total: data.total
});
}
},
{
name: "seal_approval_runs_export",
description: "将企业的审批审核记录导出为高保真 Excel 报表(包含单据模板、AI决策、人工审核结论、驳回原因及企业规则列细分结果)",
parameters: z.object({
startDate: z.string().optional().describe("起始时间,支持 YYYY-MM-DD 或毫秒时间戳"),
endDate: z.string().optional().describe("截止时间,支持 YYYY-MM-DD 或毫秒时间戳"),
limit: z.number().int().positive().optional().describe("最大拉取记录条数"),
status: z.string().optional().describe("单据状态过滤,如 completed, processing, failed"),
manualApprovalStatus: z.union([z.string(), z.array(z.string())]).optional().describe("人工审核状态过滤,如 APPROVED, TERMINATED, PROCESSING"),
includeCompletedOnly: z.boolean().optional().describe("是否仅导出已完成单据"),
outputFile: z.string().optional().describe("输出 Excel 文件的自定义绝对或相对路径"),
toDownloads: z.boolean().optional().describe("是否直接保存到用户的系统下载目录")
}),
handler: async (
client: KyInstance,
params: {
startDate?: string;
endDate?: string;
limit?: number;
status?: string;
manualApprovalStatus?: string | string[];
includeCompletedOnly?: boolean;
outputFile?: string;
toDownloads?: boolean;
},
context: ToolContext
) => exportApprovalRunsToExcel(client, context.corp, params)
},
{
name: "seal_approval_run_get",
description: "获取 Seal 单条审批/审核运行记录详情;可用 fields 只取 metadata、document.fields、result.summary 等局部字段",
parameters: z.object({
recordId: z.string().describe("Seal approval run record ID"),
fields: z.union([z.string(), z.array(z.string())]).optional().describe("逗号分隔或数组形式的字段路径,如 metadata、document.fields、result.summary"),
summary: z.boolean().optional().describe("返回单据摘要、AI 结果、人工结果和版本号")
}),
handler: async (
client: KyInstance,
params: { recordId: string; fields?: string | string[]; summary?: boolean }
) => {
const record = await api.getApprovalRun(client, params.recordId);
if (params.summary) return summarizeApprovalRunDetail(record);
const full = {
...record,
aliases: approvalRunAliases(record),
humanResult: extractHumanResult(record)
};
const fields = parseFieldPaths(params.fields);
return fields.length > 0 ? pickRunFields(full, fields) : full;
}
},
{
name: "seal_approval_run_flow_get",
description: "获取合思原生审批流流转时间线、待办节点、员工意见、驳回原因及版本变更指标,并对齐 AI 运行记录与人工行为",
parameters: z.object({
target: z.string().optional().describe("合思单号 (sourceDocumentSN) 或 Seal 运行记录 ID (recordId)"),
recordId: z.string().optional().describe("Seal 运行记录 ID"),
sourceDocumentSN: z.string().optional().describe("合思单号 (sourceDocumentSN)")
}),
handler: async (
client: KyInstance,
params: { target?: string; recordId?: string; sourceDocumentSN?: string },
context: ToolContext
) => {
const corp = context.corp;
if (corp.source.type !== "hose") {
throw new Error(
`企业「${corp.name || corp.id}」非合思(hose)租户(来源类型: ${corp.source.type}),暂不支持合思原生审批流分析。`
);
}
const input = (params.target || params.sourceDocumentSN || params.recordId)?.trim();
if (!input) {
throw new Error("必须提供 target、recordId 或 sourceDocumentSN 参数。");
}
let sn = input;
let targetRecord: ApprovalRun | undefined;
try {
targetRecord = await api.getApprovalRun(client, input);
if (targetRecord?.sourceDocumentSN || targetRecord?.sourceDocumentId) {
sn = (targetRecord.sourceDocumentSN || targetRecord.sourceDocumentId)!;
}
} catch {
// Continue as SN
}
let runs: ApprovalRun[] = [];
try {
const runsData = await api.listApprovalRuns(client, {
search: sn,
sourceDocumentSN: sn,
limit: 100
});
runs = (runsData.records || []).filter(
(r) => r.sourceDocumentSN === sn || r.sourceDocumentId === sn || r.id === input
);
} catch {
// ignore
}
if (runs.length === 0 && targetRecord) {
runs = [targetRecord];
}
const flowId = targetRecord?.sourceDocumentId || runs[0]?.sourceDocumentId || sn;
const hoseClient = await createHoseOpenClient(corp);
const flow = await getHoseOpenFlow(hoseClient, flowId);
if (!flow) {
console.error(`⚠️ 单据「${sn}」在合思系统中未找到审批流数据(可能已在合思端删除或作废)。`);
const fallbackAlignments = alignApprovalRunsWithHoseFlow(runs, undefined);
const fallbackRuns = runs.map((run) => {
const align = fallbackAlignments.get(run.id);
return {
recordId: run.id,
createdAt: run.createdAt,
createdAtFormatted: run.createdAt
? new Date(Number(run.createdAt)).toLocaleString("zh-CN", { timeZone: "Asia/Shanghai" })
: undefined,
taskMode: run.taskMode,
status: run.status,
aiDecision: align?.aiDecision || "-",
aiAction: align?.aiAction || "-",
eHumanAction: "单据已删除",
eHumanComment: "合思系统中未找到该单据流转记录(已在合思端删除或作废)",
auditDrift: false,
auditDriftReason: undefined,
operator: undefined
};
});
return {
sourceDocumentSN: sn,
corpId: corp.id,
corpName: corp.name,
sourceSystem: corp.source.type,
found: false,
deleted: true,
message: `单据「${sn}」在合思系统中未找到审批流数据(可能已在合思端删除或作废)。`,
flow: undefined,
runsCount: runs.length,
runs: fallbackRuns,
auditDrift: false
};
}
const alignments = alignApprovalRunsWithHoseFlow(runs, flow);
const alignedRuns = runs.map((run) => {
const align = alignments.get(run.id);
return {
recordId: run.id,
createdAt: run.createdAt,
createdAtFormatted: run.createdAt
? new Date(Number(run.createdAt)).toLocaleString("zh-CN", { timeZone: "Asia/Shanghai" })
: undefined,
taskMode: run.taskMode,
status: run.status,
aiDecision: align?.aiDecision || "-",
aiAction: align?.aiAction || "-",
eHumanAction: align?.eHumanAction || "-",
eHumanComment: align?.eHumanComment || "-",
auditDrift: align?.auditDrift ?? false,
auditDriftReason: align?.auditDriftReason,
operator: align?.operator
};
});
const hasAuditDrift = alignedRuns.some((r) => r.auditDrift);
return {
sourceDocumentSN: sn,
corpId: corp.id,
corpName: corp.name,
sourceSystem: corp.source.type,
flow: {
backlogId: flow.backlogId,
flowId: flow.flowId,
billCode: flow.billCode,
title: flow.title,
state: flow.state,
rawState: flow.rawState,
currentNode: flow.currentNode,
specification: flow.specification,
submitter: flow.submitter,
owner: flow.owner,
metrics: flow.metrics,
rejections: flow.rejections,
staffOpinions: flow.staffOpinions,
timelineCount: flow.history.length,
pendingCount: flow.pending.length,
timeline: flow.history,
pending: flow.pending
},
runsCount: runs.length,
runs: alignedRuns,
auditDrift: hasAuditDrift
};
}
},
{
name: "seal_approval_run_cited_rules_get",
description: "从审批运行结果中抽取 AI 引用或命中的规则及应用分析",
parameters: z.object({
recordId: z.string().describe("Seal approval run record ID")
}),
handler: async (
client: KyInstance,
params: { recordId: string }
) => {
const record = await api.getApprovalRun(client, params.recordId);
return extractCitedRules(record);
}
},
{
name: "seal_approval_run_document_summary_get",
description: "返回单据关键字段、附件摘要、AI/人工结果,避免拉取完整原始单据",
parameters: z.object({
recordId: z.string().describe("Seal approval run record ID")
}),
handler: async (
client: KyInstance,
params: { recordId: string }
) => {
const record = await api.getApprovalRun(client, params.recordId);
return summarizeApprovalRunDocument(record);
}
},
{
name: "seal_approval_run_attachments_get",
description: "从审批运行记录中抽取附件、发票附件和字段位置,不返回完整单据正文和规则结果",
parameters: z.object({
recordId: z.string().describe("Seal approval run record ID"),
summary: z.boolean().optional().describe("只返回附件列表摘要")
}),
handler: async (
client: KyInstance,
params: { recordId: string; summary?: boolean }
) => {
const record = await api.getApprovalRun(client, params.recordId);
return extractApprovalRunAttachments(record, { summary: params.summary });
}
},
{
name: "seal_approval_run_result_get",
description: "返回审批运行结果摘要;summary=true 时只返回 decision、summary、风险点数量、命中规则数量、traceId 等",
parameters: z.object({
recordId: z.string().describe("Seal approval run record ID"),
summary: z.boolean().optional()
}),
handler: async (
client: KyInstance,
params: { recordId: string; summary?: boolean }
) => {
const record = await api.getApprovalRun(client, params.recordId);
if (params.summary) return summarizeApprovalRunResult(record);
return {
recordId: record.id,
result: record.result
};
}
},
{
name: "seal_approval_run_url_get",
description: "获取审批单的 Web 链接(支持 seal-result 审核页与 hose-document 原单据页,支持 --auto-login 免密直达)",
parameters: z.object({
recordId: z.string().optional().describe("Seal approval run record ID"),
sourceDocumentSN: z.string().optional().describe("合思/易快报单号"),
sourceDocumentId: z.string().optional().describe("合思/易快报源单据 ID"),
type: z.string().optional().describe("链接类型:'seal-result' (Seal AI 审核页,默认) 或 'hose-document' (合思原单据页)"),
autoLogin: z.boolean().optional().describe("是否生成带临时认证凭证的免密直达链接"),
sso: z.boolean().optional().describe("是否生成带临时认证凭证的免密直达链接 (兼容别名)"),
hoseSso: z.boolean().optional().describe("通过合思 OEM 换票生成直达该单据审核详情的免密直达链接 (兼容别名)"),
expiresIn: z.number().optional().describe("免密凭证有效秒数,默认 7200 (2小时)")
}),
handler: async (
client: KyInstance,
params: {
recordId?: string;
sourceDocumentSN?: string;
sourceDocumentId?: string;
type?: string;
autoLogin?: boolean;
sso?: boolean;
hoseSso?: boolean;
expiresIn?: number;
},
context: ToolContext
) => {
const hasDocumentLookup = Boolean(params.recordId || params.sourceDocumentSN || params.sourceDocumentId);
if (!hasDocumentLookup) {
throw new Error("recordId, sourceDocumentSN, or sourceDocumentId is required to generate approval run link");
}
const record = await resolveApprovalRunForUrl(client, params);
const source = context.corp.source;
const hoseDocumentUrl = stringFromUnknown(record?.sourceExtendData?.hosecloudViewUrl);
const sealBaseUrl = resolveSealBaseUrl(context.corp);
const sealResultUrl = `${sealBaseUrl}/approval-result/${record.id}`;
const rawType = (params.type ?? "seal-result").toLowerCase().replace(/_/g, "-");
const isHoseDoc = rawType === "hose-document" || rawType === "source-document" || rawType === "hose";
const linkType = isHoseDoc ? "hose_document" : "seal_result";
const useAutoLogin = Boolean(params.autoLogin ?? params.hoseSso ?? params.sso);
const expiresIn = params.expiresIn ?? 7200;
let ssoUrl: string | undefined;
let identity: { name?: string; staffId?: string; isAdmin?: boolean; providerUserId?: string } | undefined;
let warning: string | undefined;
if (useAutoLogin) {
if (isHoseDoc) {
throw new Error("Auto-login (--auto-login) is only supported for Seal AI audit links (type: seal-result). To generate an auto-login link for Hose document page, please use: seal-use auth hose-link");
}
if (source.type !== "hose") {
throw new Error(
`Auto-login direct links currently support Hose-integrated enterprises (corp '${context.corp.id}' uses '${source.type}'). For Seal-native enterprises, use 'seal-use auth link' for authorized access.`
);
}
const hoseAccess = await ensureHoseCloseApiToken(context.corp);
const provisionalToken = hoseAccess.token;
if (!provisionalToken) {
throw new Error("Failed to obtain Hose provisional authentication token");
}
const targetPath = `/approval-result/${record.id}`;
ssoUrl = `${sealBaseUrl}/api/auth/oauth2/session/oem-hosecloud?token=${encodeURIComponent(provisionalToken)}&path=${encodeURIComponent(targetPath)}`;
try {
const me = await api.getMe(client);
identity = {
name: me.user.name,
staffId: source.staffId,
isAdmin: me.user.isAdmin,
providerUserId: me.user.providerUserId
};
} catch {
identity = {
staffId: source.staffId
};
}
const userName = identity.name ?? "企业成员";
const roleLabel = identity.isAdmin ? " (管理员)" : "";
warning = `⚠️ 安全警示:该链接使用 [${userName}${roleLabel}] 身份签发,在 Seal AI 拥有全站操作权限。链接具备 ${Math.round(expiresIn / 3600 * 10) / 10} 小时时效,仅供受信任人员排查使用,请勿在外部公开分享。`;
console.error(
`⚠️ 安全警示 (免密直达链接):\n` +
`• 身份主体:${userName}${roleLabel}\n` +
`• 权限范围:持有该链接者在 Seal AI 中拥有该用户的完整操作权限(含系统设置与规则编辑)\n` +
`• 时效性:换票凭证有效时间 ${expiresIn} 秒(${Math.round(expiresIn / 60)} 分钟),在浏览器打开后将保留 30 天会话\n` +
`• 安全边界:该凭证绝不包含且无法访问合思 (Hose) 主系统;仅限内部排查,严禁在外部公开分享!`
);
}
const activeUrl = isHoseDoc ? hoseDocumentUrl : (useAutoLogin ? ssoUrl : sealResultUrl);
const activeMode = useAutoLogin ? "auto_login" : "direct";
return {
url: activeUrl,
type: linkType,
mode: activeMode,
sealResultUrl,
hoseDocumentUrl,
// Legacy compatibility fields
documentUrl: hoseDocumentUrl,
ssoUrl,
expiresIn: useAutoLogin ? expiresIn : undefined,
identity,
warning,
hoseDomain: source.type === "hose" ? normalizeUrl(source.domain) : undefined,
recordId: record.id,
sourceDocumentSN: record.sourceDocumentSN,
sourceDocumentId: record.sourceDocumentId,
sourceSystem: record.sourceSystem,
missing: {
hoseDocumentUrl: !hoseDocumentUrl ? "sourceExtendData.hosecloudViewUrl is absent from the approval run detail." : undefined
}
};
}
},
{
name: "seal_approval_run_pick",
description: "按合思单号或关键字查询运行记录,返回候选记录及其当时使用的规则版本,便于再取详情或查版本规则",
parameters: z.object({
query: z.string().optional().describe("合思单号、源单据 ID、运行记录 ID 或 trace 关键字"),
sn: z.string().optional().describe("合思/易快报单号;优先作为精确 sourceDocumentSN 查询"),
batchId: z.string().optional().describe("模拟批次 ID"),
latest: z.boolean().optional().describe("只返回最新一条匹配记录"),
fields: z.union([z.string(), z.array(z.string())]).optional().describe("限制返回字段"),
limit: z.number().int().positive().max(100).optional(),
maxScan: z.number().int().positive().max(5000).optional().describe("最多扫描多少条运行记录用于本地匹配,默认 1000"),
includeBridge: z.boolean().optional()
}),
handler: async (
client: KyInstance,
params: {
query?: string;
sn?: string;
batchId?: string;
latest?: boolean;
fields?: string | string[];
limit?: number;
maxScan?: number;
includeBridge?: boolean;
},
context: ToolContext
) => {
const query = params.sn ?? params.query;
if (!query) throw new Error("query or sn is required");
const picked = await pickApprovalRuns(client, {
query,
sn: params.sn,
batchId: params.batchId,
latest: params.latest,
limit: params.latest ? 1 : params.limit ?? 20,
maxScan: params.maxScan ?? 1000
});
const records = await Promise.all(
picked.records.map((record) => api.getApprovalRun(client, record.id))
);
const fields = parseFieldPaths(params.fields);
const projected = records.map((record) => pickApprovalRunCandidate(record, fields));
const nextRuleVersionNumber = records.find((record) => record.ruleSetVersionNumber !== undefined)?.ruleSetVersionNumber;
const nextRuleVersionSelector = nextRuleVersionNumber === undefined ? "latest" : String(nextRuleVersionNumber);
const nextRuleVersionPayload = nextRuleVersionNumber === undefined
? '"latestRuleVersion":true'
: `"ruleVersionNumber":${nextRuleVersionNumber}`;
return {
query,
sourceDocumentSN: params.sn,
simulationBatchId: params.batchId,
latest: params.latest ?? false,
total: picked.total,
scanned: picked.scanned,
matched: projected.length,
records: projected,
next: {
getSummary: `seal-use approval-runs get <recordId> --summary --corp ${context.corp.id}`,
getRuleVersion: `seal-use rules version ${nextRuleVersionSelector} --corp ${context.corp.id}`,
searchRuleVersion: `seal-use tool seal_approval_search --corp ${context.corp.id} --json '{"keywords":["关键词"],"areas":["rules"],"ruleVersionScope":"version",${nextRuleVersionPayload}}'`,
getVersionContext: `seal-use tool seal_approval_context_get --corp ${context.corp.id} --json '{${nextRuleVersionPayload}}'`
},
...(params.includeBridge ? { bridge: summarizeRunBridge(records) } : {})
};
}
},
{
name: "seal_approval_run_langfuse_bridge_get",
description: "从 Seal approval run 中抽取 Langfuse 定位信息;优先返回 _langfuseTraceId,没有时给出 hosecloud-{sourceDocumentSN} session 回退",
parameters: z.object({
recordId: z.string().optional(),
sourceDocumentSN: z.string().optional(),
sourceDocumentId: z.string().optional(),
simulationBatchId: z.string().optional(),
limit: z.number().int().positive().max(100).optional()
}),
handler: async (
client: KyInstance,
params: {
recordId?: string;
sourceDocumentSN?: string;
sourceDocumentId?: string;
simulationBatchId?: string;
limit?: number;
}
) => {
const records = params.simulationBatchId
? await api.listSimulationBatchRecords(client, params.simulationBatchId)
: (await api.listApprovalRuns(client, {
limit: params.limit ?? 50,
search: params.sourceDocumentSN ?? params.sourceDocumentId,
sourceDocumentSN: params.sourceDocumentSN,
sourceDocumentId: params.sourceDocumentId
})).records;
const filtered = records.filter((record) =>
matchesRunLookup(record, {
recordId: params.recordId,
sourceDocumentSN: params.sourceDocumentSN,
sourceDocumentId: params.sourceDocumentId
})
);
return {
count: filtered.length,
records: filtered.map(summarizeApprovalRun),
bridge: summarizeRunBridge(filtered)
};
}
},
{
name: "seal_approval_runs_stats",
description: "统计审核记录状态分布、来源系统分布及按单号/ID去重统计",
parameters: z.object({
since: z.string().optional().describe("时间范围,如 3months, 7days, 24hours"),
dedupeBy: z.enum(["sourceDocumentSN", "sourceDocumentId", "id"]).default("sourceDocumentSN").describe("去重字段"),
status: z.string().optional(),
sourceSystem: z.string().optional(),
taskMode: z.string().optional()
}),
handler: async (client: KyInstance, params: { since?: string; dedupeBy?: "sourceDocumentSN" | "sourceDocumentId" | "id"; status?: string; sourceSystem?: string; taskMode?: string }) => {
const runs = await api.listApprovalRuns(client, {
limit: 1000,
status: params.status,
sourceSystem: params.sourceSystem,
taskMode: params.taskMode
});
const dedupeBy = params.dedupeBy ?? "sourceDocumentSN";
const records = runs.records;
const byStatus: Record<string, number> = {};
const bySourceSystem: Record<string, number> = {};
const uniqueKeys = new Set<string>();
for (const r of records) {
const s = r.status ?? "unknown";
byStatus[s] = (byStatus[s] ?? 0) + 1;
const src = r.sourceSystem ?? "unknown";
bySourceSystem[src] = (bySourceSystem[src] ?? 0) + 1;
const key = (r as any)[dedupeBy];
if (key) uniqueKeys.add(String(key));
}
const duplicateRuns = Math.max(0, records.length - uniqueKeys.size);
return {
total: records.length,
dedupeBy,
unique: uniqueKeys.size,
duplicateRuns,
dedupeNote:
duplicateRuns > 0
? `存在 ${duplicateRuns} 笔重复运行记录 (同一单据重跑或修改重推)`
: "全部单据唯一,无重复记录",
byStatus,
bySourceSystem
};
}
},
{
name: "seal_approval_runs_count",
description: "统计符合条件的审核记录总数",
parameters: z.object({
status: z.string().optional(),
sourceSystem: z.string().optional(),
taskMode: z.string().optional(),
search: z.string().optional(),
startDate: z.string().optional().describe("起始时间戳(毫秒)或日期字符串"),
endDate: z.string().optional().describe("结束时间戳(毫秒)或日期字符串")
}),
handler: async (
client: KyInstance,
params: {
status?: string;
sourceSystem?: string;
taskMode?: string;
search?: string;
startDate?: string;
endDate?: string;
}
) => {
const runs = await api.listApprovalRuns(client, {
limit: 1,
status: params.status,
sourceSystem: params.sourceSystem,
taskMode: params.taskMode,
search: params.search,
startDate: normalizeTimestamp(params.startDate, false),
endDate: normalizeTimestamp(params.endDate, true)
});
return {
total: runs.total ?? runs.records.length
};
}
}
];
+179
View File
@@ -0,0 +1,179 @@
import { z } from "zod";
import type { KyInstance } from "ky";
import { readFileSync } from "node:fs";
import { randomBytes } from "node:crypto";
import * as api from "../api.js";
import { defaultSealUrl, ensureHoseCloseApiToken, getHoseProvisionalAuthLink, probeHoseDomain } from "../../../core/auth/hose.js";
import type { CorpConfig } from "../../../core/config/types.js";
import { loadGlobalConfig, loadCorpConfigs, getEnterprisesDirCandidates } from "../../../core/config/loader.js";
import { resolveCorpConfig } from "../../../core/config/manager.js";
import { createSealClient, createSealClientForToken } from "../../../core/http/factory.js";
import { resolveSealCustomHeaders } from "../../../core/http/request-headers.js";
import { searchApprovalContent } from "../search.js";
import { diffRuleVersions, normalizedRuleCode, truncateRuleDiff } from "../rule-diff.js";
import { hydrateRuleVersionStableIds, savePublishedRuleVersionSnapshot } from "../rule-version-snapshot.js";
import { executeApprovalRunsReplay, resolveReplayCorpPair } from "../webhook-replay.js";
import { loadRuleLinter, lintRuleBatch, lintSingleRule, type RuleLintTarget } from "../linter/index.js";
import {
loadLocalRulesFile,
saveLocalRulesFile,
localRulesToLintTargets,
type LocalRuleItem
} from "../rules-local.js";
import {
checkWebhookReadiness,
previewMaterialPack,
pushMaterialPack,
readMaterialPackFile
} from "../material-pack/index.js";
import { MaterialPackFilePolicyPatchSchema, MaterialPackFilePolicySchema } from "../material-pack/policy.js";
import { extractApprovalRunAttachments } from "../attachments.js";
import { exportApprovalRunsToExcel, normalizeTimestamp } from "../approval-runs-export.js";
import {
alignApprovalRunsWithHoseFlow,
createHoseOpenClient,
getHoseOpenFlow
} from "../../hose/index.js";
import { exportInsightReportToExcel, type InsightExportOptions } from "../insight-export.js";
import {
ThinkingPolicySchema,
type ApprovalRule,
type ApprovalRun,
type RuleSetVersion,
type SimulationBatch,
type WebhookIntegration,
type WebhookMode,
type ThinkingPolicy,
type DecisionPreferences,
type HosecloudConfigInput
} from "../types.js";
import type {
ToolContext,
SealToolDefinition,
ApprovalRunSummary,
ApprovalRunsSummaryOptions,
RuleField,
RulePushPlan,
SimulationBatchCreateInput,
HumanResultMatch
} from "./helpers.js";
import * as helpers from "./helpers.js";
const {
presentWebhookIntegration,
getConfiguredSealBaseUrl,
projectApprovalRules,
pickRuleFields,
buildRulePushPlan,
rulesHaveSameContent,
ruleChangedFields,
normalizeRuleStrictness,
parseDurationMs,
redactIntegrationSecrets,
mutationPreview,
redactPreviewValue,
buildSimulationBatchParams,
summarizeSimulationBatch,
summarizeApprovalRun,
summarizeApprovalRuns,
parseFieldPaths,
pickRunFields,
approvalRunMetadata,
summarizeApprovalRunDetail,
summarizeApprovalRunResult,
summarizeApprovalRunDocument,
extractCitedRules,
firstPath,
countPathCandidates,
getPath,
setPath,
compactObject,
asRecord,
numberFromUnknown,
flattenDocumentFields,
collectDocumentFields,
firstByLabel,
collectInvoiceSummary,
collectInvoiceObjects,
findKeywordLines,
summarizeRunBridge,
summarizeRuleVersion,
resolveRuleVersionForLookup,
findRuleInVersion,
normalizeRuleCode,
runtimeRuleIndex,
runtimeRuleIdToCode,
formatRuleCode,
pickApprovalRunCandidate,
resolveApprovalRunForUrl,
resolveSealBaseUrl,
normalizeUrl,
stringFromUnknown,
pickApprovalRuns,
timestampOf,
resolveRuleVersion,
resolveRuleVersionSelector,
filterRuns,
scalarIncludes,
objectContainsScalar,
filterRunsByHumanResult,
withApprovalRunFilters,
resolveManualApprovalStatus,
prepareApprovalRuns,
approvalRunAliases,
extractHumanResult,
findHumanResultValue,
isHumanResultKey,
stringifyHumanResultValue,
matchesRunLookup,
countBy,
localDateKey,
formatLocalDateTime,
toDate,
localParts
} = helpers;
export const billingTools = [
{
name: "seal_llm_config_get",
description: "查询当前 Seal 租户的大模型 (LLM) 配置",
parameters: z.object({}),
handler: async (client: KyInstance) => api.getLlmConfig(client)
},
{
name: "seal_llm_providers_list",
description: "查询支持的大模型 (LLM) 供应商与配置属性字段",
parameters: z.object({}),
handler: async (client: KyInstance) => api.listLlmProviders(client)
},
{
name: "seal_permissions_available_list",
description: "查询系统可选权限清单(如超级管理员、智能审核管理、数据管理等)",
parameters: z.object({}),
handler: async (client: KyInstance) => api.listAvailablePermissions(client)
},
{
name: "seal_permissions_configs_list",
description: "查询当前租户已绑定的权限配置",
parameters: z.object({}),
handler: async (client: KyInstance) => api.listPermissionConfigs(client)
},
{
name: "seal_billing_status_get",
description: "查询当前 Seal 租户的订阅状态与各功能额度(AI审批、审核规则、知识文档等)",
parameters: z.object({}),
handler: async (client: KyInstance) => api.getBillingStatus(client)
},
{
name: "seal_billing_plans_list",
description: "查询系统支持的订阅套餐列表",
parameters: z.object({}),
handler: async (client: KyInstance) => api.listBillingPlans(client)
},
{
name: "seal_billing_features_list",
description: "查询系统支持的功能特性定义列表",
parameters: z.object({}),
handler: async (client: KyInstance) => api.listBillingFeatures(client)
}
];
+176
View File
@@ -0,0 +1,176 @@
import { z } from "zod";
import type { KyInstance } from "ky";
import { readFileSync } from "node:fs";
import { randomBytes } from "node:crypto";
import * as api from "../api.js";
import { defaultSealUrl, ensureHoseCloseApiToken, getHoseProvisionalAuthLink, probeHoseDomain } from "../../../core/auth/hose.js";
import type { CorpConfig } from "../../../core/config/types.js";
import { loadGlobalConfig, loadCorpConfigs, getEnterprisesDirCandidates } from "../../../core/config/loader.js";
import { resolveCorpConfig } from "../../../core/config/manager.js";
import { createSealClient, createSealClientForToken } from "../../../core/http/factory.js";
import { resolveSealCustomHeaders } from "../../../core/http/request-headers.js";
import { searchApprovalContent } from "../search.js";
import { diffRuleVersions, normalizedRuleCode, truncateRuleDiff } from "../rule-diff.js";
import { hydrateRuleVersionStableIds, savePublishedRuleVersionSnapshot } from "../rule-version-snapshot.js";
import { executeApprovalRunsReplay, resolveReplayCorpPair } from "../webhook-replay.js";
import { loadRuleLinter, lintRuleBatch, lintSingleRule, type RuleLintTarget } from "../linter/index.js";
import {
loadLocalRulesFile,
saveLocalRulesFile,
localRulesToLintTargets,
type LocalRuleItem
} from "../rules-local.js";
import {
checkWebhookReadiness,
previewMaterialPack,
pushMaterialPack,
readMaterialPackFile
} from "../material-pack/index.js";
import { MaterialPackFilePolicyPatchSchema, MaterialPackFilePolicySchema } from "../material-pack/policy.js";
import { extractApprovalRunAttachments } from "../attachments.js";
import { exportApprovalRunsToExcel, normalizeTimestamp } from "../approval-runs-export.js";
import {
alignApprovalRunsWithHoseFlow,
createHoseOpenClient,
getHoseOpenFlow
} from "../../hose/index.js";
import { exportInsightReportToExcel, type InsightExportOptions } from "../insight-export.js";
import {
ThinkingPolicySchema,
type ApprovalRule,
type ApprovalRun,
type RuleSetVersion,
type SimulationBatch,
type WebhookIntegration,
type WebhookMode,
type ThinkingPolicy,
type DecisionPreferences,
type HosecloudConfigInput
} from "../types.js";
import type {
ToolContext,
SealToolDefinition,
ApprovalRunSummary,
ApprovalRunsSummaryOptions,
RuleField,
RulePushPlan,
SimulationBatchCreateInput,
HumanResultMatch
} from "./helpers.js";
import * as helpers from "./helpers.js";
const {
presentWebhookIntegration,
getConfiguredSealBaseUrl,
projectApprovalRules,
pickRuleFields,
buildRulePushPlan,
rulesHaveSameContent,
ruleChangedFields,
normalizeRuleStrictness,
parseDurationMs,
redactIntegrationSecrets,
mutationPreview,
redactPreviewValue,
buildSimulationBatchParams,
summarizeSimulationBatch,
summarizeApprovalRun,
summarizeApprovalRuns,
parseFieldPaths,
pickRunFields,
approvalRunMetadata,
summarizeApprovalRunDetail,
summarizeApprovalRunResult,
summarizeApprovalRunDocument,
extractCitedRules,
firstPath,
countPathCandidates,
getPath,
setPath,
compactObject,
asRecord,
numberFromUnknown,
flattenDocumentFields,
collectDocumentFields,
firstByLabel,
collectInvoiceSummary,
collectInvoiceObjects,
findKeywordLines,
summarizeRunBridge,
summarizeRuleVersion,
resolveRuleVersionForLookup,
findRuleInVersion,
normalizeRuleCode,
runtimeRuleIndex,
runtimeRuleIdToCode,
formatRuleCode,
pickApprovalRunCandidate,
resolveApprovalRunForUrl,
resolveSealBaseUrl,
normalizeUrl,
stringFromUnknown,
pickApprovalRuns,
timestampOf,
resolveRuleVersion,
resolveRuleVersionSelector,
filterRuns,
scalarIncludes,
objectContainsScalar,
filterRunsByHumanResult,
withApprovalRunFilters,
resolveManualApprovalStatus,
prepareApprovalRuns,
approvalRunAliases,
extractHumanResult,
findHumanResultValue,
isHumanResultKey,
stringifyHumanResultValue,
matchesRunLookup,
countBy,
localDateKey,
formatLocalDateTime,
toDate,
localParts
} = helpers;
export const contactsTools = [
{
name: "seal_contacts_departments_root_list",
description: "列出当前 Seal 租户通讯录的顶级部门",
parameters: z.object({}),
handler: async (client: KyInstance) => api.listRootDepartments(client)
},
{
name: "seal_contacts_department_get",
description: "获取指定通讯录部门的详细信息",
parameters: z.object({
departmentId: z.string().describe("部门 ID")
}),
handler: async (client: KyInstance, params: { departmentId: string }) =>
api.getDepartment(client, params.departmentId)
},
{
name: "seal_contacts_department_children_list",
description: "列出指定通讯录部门的直接子部门",
parameters: z.object({
departmentId: z.string().describe("部门 ID")
}),
handler: async (client: KyInstance, params: { departmentId: string }) =>
api.listDepartmentChildren(client, params.departmentId)
},
{
name: "seal_contacts_department_users_list",
description: "列出指定通讯录部门下的用户",
parameters: z.object({
departmentId: z.string().describe("部门 ID")
}),
handler: async (client: KyInstance, params: { departmentId: string }) =>
api.listDepartmentUsers(client, params.departmentId)
},
{
name: "seal_contacts_last_sync_time_get",
description: "查询通讯录最后同步时间",
parameters: z.object({}),
handler: async (client: KyInstance) => api.getContactsLastSyncTime(client)
}
];
+331
View File
@@ -0,0 +1,331 @@
import { z } from "zod";
import type { KyInstance } from "ky";
import { readFileSync } from "node:fs";
import { randomBytes } from "node:crypto";
import * as api from "../api.js";
import { defaultSealUrl, ensureHoseCloseApiToken, getHoseProvisionalAuthLink, probeHoseDomain } from "../../../core/auth/hose.js";
import type { CorpConfig } from "../../../core/config/types.js";
import { loadGlobalConfig, loadCorpConfigs, getEnterprisesDirCandidates } from "../../../core/config/loader.js";
import { resolveCorpConfig } from "../../../core/config/manager.js";
import { createSealClient, createSealClientForToken } from "../../../core/http/factory.js";
import { resolveSealCustomHeaders } from "../../../core/http/request-headers.js";
import { searchApprovalContent } from "../search.js";
import { diffRuleVersions, normalizedRuleCode, truncateRuleDiff } from "../rule-diff.js";
import { hydrateRuleVersionStableIds, savePublishedRuleVersionSnapshot } from "../rule-version-snapshot.js";
import { executeApprovalRunsReplay, resolveReplayCorpPair } from "../webhook-replay.js";
import { loadRuleLinter, lintRuleBatch, lintSingleRule, type RuleLintTarget } from "../linter/index.js";
import {
loadLocalRulesFile,
saveLocalRulesFile,
localRulesToLintTargets,
type LocalRuleItem
} from "../rules-local.js";
import {
checkWebhookReadiness,
previewMaterialPack,
pushMaterialPack,
readMaterialPackFile
} from "../material-pack/index.js";
import { MaterialPackFilePolicyPatchSchema, MaterialPackFilePolicySchema } from "../material-pack/policy.js";
import { extractApprovalRunAttachments } from "../attachments.js";
import { exportApprovalRunsToExcel, normalizeTimestamp } from "../approval-runs-export.js";
import {
alignApprovalRunsWithHoseFlow,
createHoseOpenClient,
getHoseOpenFlow
} from "../../hose/index.js";
import { exportInsightReportToExcel, type InsightExportOptions } from "../insight-export.js";
import {
ThinkingPolicySchema,
type ApprovalRule,
type ApprovalRun,
type RuleSetVersion,
type SimulationBatch,
type WebhookIntegration,
type WebhookMode,
type ThinkingPolicy,
type DecisionPreferences,
type HosecloudConfigInput
} from "../types.js";
import type {
ToolContext,
SealToolDefinition,
ApprovalRunSummary,
ApprovalRunsSummaryOptions,
RuleField,
RulePushPlan,
SimulationBatchCreateInput,
HumanResultMatch
} from "./helpers.js";
import * as helpers from "./helpers.js";
const {
presentWebhookIntegration,
getConfiguredSealBaseUrl,
projectApprovalRules,
pickRuleFields,
buildRulePushPlan,
rulesHaveSameContent,
ruleChangedFields,
normalizeRuleStrictness,
parseDurationMs,
redactIntegrationSecrets,
mutationPreview,
redactPreviewValue,
buildSimulationBatchParams,
summarizeSimulationBatch,
summarizeApprovalRun,
summarizeApprovalRuns,
parseFieldPaths,
pickRunFields,
approvalRunMetadata,
summarizeApprovalRunDetail,
summarizeApprovalRunResult,
summarizeApprovalRunDocument,
extractCitedRules,
firstPath,
countPathCandidates,
getPath,
setPath,
compactObject,
asRecord,
numberFromUnknown,
flattenDocumentFields,
collectDocumentFields,
firstByLabel,
collectInvoiceSummary,
collectInvoiceObjects,
findKeywordLines,
summarizeRunBridge,
summarizeRuleVersion,
resolveRuleVersionForLookup,
findRuleInVersion,
normalizeRuleCode,
runtimeRuleIndex,
runtimeRuleIdToCode,
formatRuleCode,
pickApprovalRunCandidate,
resolveApprovalRunForUrl,
resolveSealBaseUrl,
normalizeUrl,
stringFromUnknown,
pickApprovalRuns,
timestampOf,
resolveRuleVersion,
resolveRuleVersionSelector,
filterRuns,
scalarIncludes,
objectContainsScalar,
filterRunsByHumanResult,
withApprovalRunFilters,
resolveManualApprovalStatus,
prepareApprovalRuns,
approvalRunAliases,
extractHumanResult,
findHumanResultValue,
isHumanResultKey,
stringifyHumanResultValue,
matchesRunLookup,
countBy,
localDateKey,
formatLocalDateTime,
toDate,
localParts
} = helpers;
export const deployTools = [
{
name: "seal_deploy_hosecloud_requirements",
description: "获取 Seal AI 审批发布到合思费控所需配置字段与说明",
parameters: z.object({}),
handler: async () => {
return {
input: "JSON via --json '{\"apiKey\":\"...\",\"apiSecret\":\"...\",\"mode\":\"assisted\"}'",
questions: [
{ field: "apiOrigin", prompt: "使用哪一种合思版本或 API 环境?(production/custom,未指定时自动探测)", required: false, default: "production" },
{ field: "customApiUrl", prompt: "自定义环境的 API 地址是什么?(如专属私有云域名)", requiredWhen: "apiOrigin=custom" },
{ field: "apiKey", prompt: "合思 API Key(appKey)是什么?", required: true, secret: true },
{ field: "apiSecret", prompt: "合思 API Secret(appSecurity)是什么?", required: true, secret: true },
{ field: "mode", prompt: "使用全自动、半自动还是辅助审核?(fully_automatic/semi_automatic/assisted)", required: true, default: "assisted" },
{ field: "autoApprovalRate", prompt: "自动审批比例是多少?(0-100)", requiredWhen: "mode!=assisted" },
{ field: "rejectResubmitMethod", prompt: "驳回重提后从哪个节点继续?(node_default/to_ebot/from_start)" },
{ field: "autoApproveNodeNames", prompt: "哪些节点允许自动审批?(string[])" },
{ field: "outboundName", prompt: "合思审批流节点消息名称是什么?", default: "SealAI 审批" }
]
};
}
},
{
name: "seal_deploy_hosecloud_list",
description: "列出当前企业【Seal AI 审批发布到合思费控】的集成配置列表",
parameters: z.object({}),
handler: async (client: KyInstance) => {
const config = await api.getApprovalStylePreferences(client);
const integrations = (config.integrations ?? []).filter((item: any) => item.type === "hosecloud");
return {
count: integrations.length,
integrations: integrations.map(redactIntegrationSecrets)
};
}
},
{
name: "seal_deploy_hosecloud_get",
description: "查询【Seal AI 审批发布到合思费控】的单项配置详情",
parameters: z.object({
signKey: z.string().describe("合思集成 sign-key")
}),
handler: async (client: KyInstance, params: { signKey: string }) => {
const config = await api.getApprovalStylePreferences(client);
const integration = (config.integrations ?? []).find(
(item: any) => item.type === "hosecloud" && item.signKey === params.signKey
);
if (!integration) {
throw new Error(`未找到合思配置:${params.signKey}`);
}
return redactIntegrationSecrets(integration as Record<string, unknown>);
}
},
{
name: "seal_deploy_hosecloud_status",
description: "检查【Seal AI 审批发布到合思费控】与多平台集成状态",
parameters: z.object({}),
handler: async (client: KyInstance) => {
const status = await api.getSimulationIntegrationStatus(client);
const config = await api.getApprovalStylePreferences(client);
const integrations = (config.integrations ?? []).filter((item: any) => item.type === "hosecloud");
return {
status,
integrations: integrations.map(redactIntegrationSecrets)
};
}
},
{
name: "seal_deploy_hosecloud_configure",
description: "自动探测平台并保存【Seal AI 审批发布到合思费控】集成配置",
parameters: z.object({
apiKey: z.string().describe("合思 API Key (appKey)"),
apiSecret: z.string().describe("合思 API Secret (appSecurity)"),
signKey: z.string().optional().describe("集成 signKey,不提供则自动生成"),
outboundName: z.string().optional().describe("出站消息名称(合思审批流节点中显示)"),
specificationId: z.string().optional(),
specificationName: z.string().optional(),
mode: z.enum(["fully_automatic", "semi_automatic", "assisted"]).default("assisted"),
autoApprovalRate: z.number().min(0).max(100).optional(),
rejectResubmitMethod: z.enum(["node_default", "to_ebot", "from_start"]).optional(),
autoApproveNodeNames: z.array(z.string()).optional(),
apiOrigin: z.string().default("production"),
customApiUrl: z.string().optional(),
dryRun: z.boolean().optional().describe("只返回前后配置 Diff,不执行写入")
}),
handler: async (client: KyInstance, rawParams: HosecloudConfigInput, context: ToolContext) => {
const { dryRun, ...inputParams } = rawParams;
const apiKey = inputParams.apiKey ?? (inputParams as any).appKey;
const apiSecret = inputParams.apiSecret ?? (inputParams as any).appSecurity;
if (!apiKey || !apiSecret) {
throw new Error("缺少合思凭证:apiKey (或 appKey) 与 apiSecret (或 appSecurity) 为必填项");
}
const params = { ...inputParams, apiKey, apiSecret };
let effectiveApiOrigin = params.apiOrigin ?? "production";
let effectiveCustomApiUrl = params.customApiUrl;
// 自动平台/域名探测:当未提供 customApiUrl 时,并发探测合思 6 大标准公共 SaaS 平台域名
if (!effectiveCustomApiUrl && effectiveApiOrigin !== "custom") {
try {
const probe = await probeHoseDomain(params.apiKey, params.apiSecret);
if (probe?.domain) {
if (probe.domain === "https://app.ekuaibao.com") {
effectiveApiOrigin = "production";
effectiveCustomApiUrl = undefined;
} else {
effectiveApiOrigin = "custom";
effectiveCustomApiUrl = probe.domain;
}
}
} catch {
// 探测失败时平滑降级,由后续后端校验处理
}
}
if (effectiveApiOrigin === "custom" && !effectiveCustomApiUrl) {
throw new Error("自定义合思环境必须提供 customApiUrl");
}
const corpResult = await api.getHosecloudCorporation(client, {
apiKey: params.apiKey,
apiSecret: params.apiSecret,
apiOrigin: effectiveApiOrigin,
customApiUrl: effectiveCustomApiUrl
});
const config = await api.getApprovalStylePreferences(client);
const signKey = params.signKey ?? randomBytes(6).toString("hex");
const nextIntegration = {
type: "hosecloud",
...params,
apiOrigin: effectiveApiOrigin,
...(effectiveCustomApiUrl ? { customApiUrl: effectiveCustomApiUrl } : {}),
signKey,
corporationId: corpResult.corporationId
};
const existing = (config.integrations ?? []).filter(
(item: any) => item.type !== "hosecloud" || item.signKey !== signKey
);
existing.push(nextIntegration);
const nextConfig = {
...config,
integrationSystem: "hosecloud",
integrations: existing
};
if (dryRun) {
return mutationPreview(
context,
context.corp.seal.endpoints.approvalStylePreferences,
config,
nextConfig,
1
);
}
await api.updateApprovalStylePreferences(client, nextConfig, context.corp.seal.endpoints.approvalStylePreferences);
console.error(`✓ 配置已保存 (signKey: ${signKey})`);
console.error(`👉 Next action: seal-use deploy hosecloud sync ${signKey} --corp ${context.corp.id}`);
return {
integration: redactIntegrationSecrets(nextIntegration)
};
}
},
{
name: "seal_deploy_hosecloud_sync",
description: "一键将 Seal AI 审核配置同步发布到合思费控审批流",
parameters: z.object({
signKey: z.string().describe("合思集成 sign-key")
}),
handler: async (client: KyInstance, params: { signKey: string }, context: ToolContext) => {
const config = await api.getApprovalStylePreferences(client);
const integration = (config.integrations ?? []).find(
(item: any) => item.type === "hosecloud" && item.signKey === params.signKey
);
if (!integration) {
throw new Error(`未找到合思配置:${params.signKey}`);
}
const sealUrl = (context.corp.seal.url ?? `https://${context.corp.id.toLowerCase()}.sealai.cc`).replace(/\/+$/, "");
const messageName = (integration as any).outboundName ?? "SealAI 审批";
const result = await api.syncHosecloudOutbound(client, {
signKey: params.signKey,
webhookUrl: `${sealUrl}/api/hosecloud/outbound?config_id=${encodeURIComponent(params.signKey)}`,
completionWebhookUrl: `${sealUrl}/api/hosecloud/flow/completion?config_id=${encodeURIComponent(params.signKey)}`,
messageName,
mode: (integration as any).mode ?? "assisted"
});
console.error(`✓ 同步成功!出站消息已在合思开放平台创建/更新: "${messageName}"`);
console.error(`👉 发布完成:请登录合思后台在审批流中添加【EBot】节点并选择 "${messageName}"。`);
return {
signKey: params.signKey,
synced: true,
result
};
}
}
];
File diff suppressed because it is too large. Load diff
+251
View File
@@ -0,0 +1,251 @@
import { z } from "zod";
import type { KyInstance } from "ky";
import { readFileSync } from "node:fs";
import { randomBytes } from "node:crypto";
import * as api from "../api.js";
import { defaultSealUrl, ensureHoseCloseApiToken, getHoseProvisionalAuthLink, probeHoseDomain } from "../../../core/auth/hose.js";
import type { CorpConfig } from "../../../core/config/types.js";
import { loadGlobalConfig, loadCorpConfigs, getEnterprisesDirCandidates } from "../../../core/config/loader.js";
import { resolveCorpConfig } from "../../../core/config/manager.js";
import { createSealClient, createSealClientForToken } from "../../../core/http/factory.js";
import { resolveSealCustomHeaders } from "../../../core/http/request-headers.js";
import { searchApprovalContent } from "../search.js";
import { diffRuleVersions, normalizedRuleCode, truncateRuleDiff } from "../rule-diff.js";
import { hydrateRuleVersionStableIds, savePublishedRuleVersionSnapshot } from "../rule-version-snapshot.js";
import { executeApprovalRunsReplay, resolveReplayCorpPair } from "../webhook-replay.js";
import { loadRuleLinter, lintRuleBatch, lintSingleRule, type RuleLintTarget } from "../linter/index.js";
import {
loadLocalRulesFile,
saveLocalRulesFile,
localRulesToLintTargets,
type LocalRuleItem
} from "../rules-local.js";
import {
checkWebhookReadiness,
previewMaterialPack,
pushMaterialPack,
readMaterialPackFile
} from "../material-pack/index.js";
import { MaterialPackFilePolicyPatchSchema, MaterialPackFilePolicySchema } from "../material-pack/policy.js";
import { extractApprovalRunAttachments } from "../attachments.js";
import { exportApprovalRunsToExcel, normalizeTimestamp } from "../approval-runs-export.js";
import {
alignApprovalRunsWithHoseFlow,
createHoseOpenClient,
getHoseOpenFlow
} from "../../hose/index.js";
import { exportInsightReportToExcel, type InsightExportOptions } from "../insight-export.js";
import {
ThinkingPolicySchema,
type ApprovalRule,
type ApprovalRun,
type RuleSetVersion,
type SimulationBatch,
type WebhookIntegration,
type WebhookMode,
type ThinkingPolicy,
type DecisionPreferences,
type HosecloudConfigInput
} from "../types.js";
import type {
ToolContext,
SealToolDefinition,
ApprovalRunSummary,
ApprovalRunsSummaryOptions,
RuleField,
RulePushPlan,
SimulationBatchCreateInput,
HumanResultMatch
} from "./helpers.js";
import * as helpers from "./helpers.js";
const {
presentWebhookIntegration,
getConfiguredSealBaseUrl,
projectApprovalRules,
pickRuleFields,
buildRulePushPlan,
rulesHaveSameContent,
ruleChangedFields,
normalizeRuleStrictness,
parseDurationMs,
redactIntegrationSecrets,
mutationPreview,
redactPreviewValue,
buildSimulationBatchParams,
summarizeSimulationBatch,
summarizeApprovalRun,
summarizeApprovalRuns,
parseFieldPaths,
pickRunFields,
approvalRunMetadata,
summarizeApprovalRunDetail,
summarizeApprovalRunResult,
summarizeApprovalRunDocument,
extractCitedRules,
firstPath,
countPathCandidates,
getPath,
setPath,
compactObject,
asRecord,
numberFromUnknown,
flattenDocumentFields,
collectDocumentFields,
firstByLabel,
collectInvoiceSummary,
collectInvoiceObjects,
findKeywordLines,
summarizeRunBridge,
summarizeRuleVersion,
resolveRuleVersionForLookup,
findRuleInVersion,
normalizeRuleCode,
runtimeRuleIndex,
runtimeRuleIdToCode,
formatRuleCode,
pickApprovalRunCandidate,
resolveApprovalRunForUrl,
resolveSealBaseUrl,
normalizeUrl,
stringFromUnknown,
pickApprovalRuns,
timestampOf,
resolveRuleVersion,
resolveRuleVersionSelector,
filterRuns,
scalarIncludes,
objectContainsScalar,
filterRunsByHumanResult,
withApprovalRunFilters,
resolveManualApprovalStatus,
prepareApprovalRuns,
approvalRunAliases,
extractHumanResult,
findHumanResultValue,
isHumanResultKey,
stringifyHumanResultValue,
matchesRunLookup,
countBy,
localDateKey,
formatLocalDateTime,
toDate,
localParts
} = helpers;
export const identityTools = [
{
name: "seal_whoami",
description: "查询当前 Seal 用户身份及租户信息",
parameters: z.object({}),
handler: async (client: KyInstance) => api.getMe(client)
},
{
name: "seal_session_get",
description: "查询当前 Seal Bearer session、用户和过期时间",
parameters: z.object({}),
handler: async (client: KyInstance) => api.getSession(client)
},
{
name: "seal_delegation_list",
description: "查询当前 Seal 租户下的授权链接 (Delegation) 列表",
parameters: z.object({}),
handler: async (client: KyInstance) => api.listDelegations(client)
},
{
name: "seal_delegation_create",
description: "创建新的 Seal 授权链接 (Delegation)",
parameters: z.object({
note: z.string().optional().describe("授权链接的备注或说明信息")
}),
handler: async (client: KyInstance, params: { note?: string }) =>
api.createDelegation(client, params)
},
{
name: "seal_delegation_revoke",
description: "撤销/废除指定的 Seal 授权链接 (Delegation)",
parameters: z.object({
tokenId: z.string().describe("授权链接 ID (delegation record ID)")
}),
handler: async (client: KyInstance, params: { tokenId: string }) =>
api.revokeDelegation(client, params.tokenId)
},
{
name: "seal_user_create",
description: "创建本地 Seal 用户,生成并返回初始随机密码",
parameters: z.object({
name: z.string().describe("用户姓名"),
phone: z.string().describe("手机号码 (例如 13300001111 或 +8613300001111)"),
permissions: z.array(z.string()).optional().describe("权限列表,默认为 []"),
departmentIds: z.array(z.string()).optional().describe("关联部门 ID 数组")
}),
handler: async (
client: KyInstance,
params: { name: string; phone: string; permissions?: string[]; departmentIds?: string[] }
) => api.createLocalUser(client, params)
},
{
name: "seal_user_reset_password",
description: "重置指定 Seal 用户的默认/随机密码,并返回生成的新密码",
parameters: z.object({
userId: z.string().describe("用户 ID (_id)")
}),
handler: async (client: KyInstance, params: { userId: string }) =>
api.resetUserPassword(client, params.userId)
},
{
name: "seal_user_get",
description: "获取指定 Seal 用户的详细信息",
parameters: z.object({
userId: z.string().describe("用户 ID (_id)")
}),
handler: async (client: KyInstance, params: { userId: string }) =>
api.getUserDetail(client, params.userId)
},
{
name: "seal_user_search",
description: "按姓名、手机号或邮箱搜索 Seal 成员用户列表",
parameters: z.object({
keyword: z.string().optional().describe("搜索关键词(姓名、手机号、邮箱等),不传或传空字符串可列出租户成员")
}),
handler: async (client: KyInstance, params: { keyword?: string }) =>
api.searchUsers(client, params.keyword ?? "")
},
{
name: "seal_user_delete",
description: "删除指定 Seal 本地用户",
parameters: z.object({
userId: z.string().describe("用户 ID (_id)")
}),
handler: async (client: KyInstance, params: { userId: string }) =>
api.deleteLocalUser(client, params.userId)
},
{
name: "seal_user_activate",
description: "启用/激活已离职的 Seal 用户账号",
parameters: z.object({
userId: z.string().describe("用户 ID (_id)")
}),
handler: async (client: KyInstance, params: { userId: string }) =>
api.activateLocalUser(client, params.userId)
},
{
name: "seal_user_delegation_create",
description: "为指定 Seal 用户(按用户ID、手机号或姓名)重置密码登录并生成其专属授权链接 (Delegation)",
parameters: z.object({
userIdOrPhone: z.string().describe("目标用户 ID、手机号或姓名"),
note: z.string().optional().describe("授权链接备注信息")
}),
handler: async (
client: KyInstance,
params: { userIdOrPhone: string; note?: string },
context: ToolContext
) =>
api.createDelegationForUser(
client,
params,
(token) => createSealClientForToken(context.corp, token),
context.corp
)
}
];
+157
View File
@@ -0,0 +1,157 @@
import { identityTools } from "./identity.js";
import { contactsTools } from "./contacts.js";
import { insightTools } from "./insight.js";
import { billingTools } from "./billing.js";
import { rulesTools } from "./rules.js";
import { webhookTools } from "./webhook.js";
import { approvalRunsTools } from "./approval-runs.js";
import { simulationTools } from "./simulation.js";
import { deployTools } from "./deploy.js";
import { preferenceTools } from "./preference.js";
export * from "./helpers.js";
export const sealTools = [
...identityTools,
...contactsTools,
...insightTools,
...billingTools,
...rulesTools,
...webhookTools,
...approvalRunsTools,
...simulationTools,
...deployTools,
...preferenceTools
];
export type SealTool = (typeof sealTools)[number];
/**
* MCP read/write classification for the tool registry.
*
* The two sets are exhaustive by construction: `tools.test.ts` asserts they partition `sealTools`
* exactly, so a newly added tool fails the suite until it is classified here. The read-only MCP tool
* (`seal_cli`) may only invoke names in {@link SEAL_READ_ONLY_TOOLS}; everything else is reachable
* solely through `seal_cli_write`.
*
* Read-only means it reads tenant state, or writes only a local file. Anything that creates, updates,
* deletes, publishes, pushes, replays, uploads, activates or mints a credential counts as mutating —
* including when it reads like a query. `seal_insight_record_analyze` is the instructive case: it
* sounds like a read but issues a POST that starts an analysis server-side.
*/
export const SEAL_READ_ONLY_TOOLS: ReadonlySet<string> = new Set([
"seal_approval_context_get",
"seal_approval_document_get",
"seal_approval_documents_list",
"seal_approval_rule_get",
"seal_approval_rule_version_diff",
"seal_approval_rule_version_get",
"seal_approval_rule_versions_list",
"seal_approval_rules_lint",
"seal_approval_rules_list",
"seal_approval_rules_pull",
"seal_approval_run_attachments_get",
"seal_approval_run_cited_rules_get",
"seal_approval_run_document_summary_get",
"seal_approval_run_flow_get",
"seal_approval_run_get",
"seal_approval_run_langfuse_bridge_get",
"seal_approval_run_pick",
"seal_approval_run_result_get",
"seal_approval_run_url_get",
"seal_approval_runs_count",
"seal_approval_runs_export",
"seal_approval_runs_search",
"seal_approval_runs_stats",
"seal_approval_runs_summary",
"seal_approval_search",
"seal_approval_style_preferences_get",
"seal_billing_features_list",
"seal_billing_plans_list",
"seal_billing_status_get",
"seal_contacts_department_children_list",
"seal_contacts_department_get",
"seal_contacts_department_users_list",
"seal_contacts_departments_root_list",
"seal_contacts_last_sync_time_get",
"seal_delegation_list",
"seal_deploy_hosecloud_get",
"seal_deploy_hosecloud_list",
"seal_deploy_hosecloud_requirements",
"seal_deploy_hosecloud_status",
"seal_expenses_list",
"seal_insight_export",
"seal_insight_performance_get",
"seal_insight_risks_by_tag_get",
"seal_insight_stats_get",
"seal_invoices_list",
"seal_llm_config_get",
"seal_llm_providers_list",
"seal_permissions_available_list",
"seal_permissions_configs_list",
"seal_preference_get",
"seal_preference_thinking_depth_policies_list",
"seal_session_get",
"seal_simulation_batch_get",
"seal_simulation_batch_records_get",
"seal_simulation_batch_status",
"seal_simulation_batch_wait",
"seal_simulation_batches_list",
"seal_simulation_feishu_approval_definitions_list",
"seal_simulation_integrations_get",
"seal_simulation_specifications_list",
"seal_simulation_templates_get",
"seal_user_get",
"seal_user_search",
"seal_webhook_get",
"seal_webhook_list",
"seal_webhook_ready",
"seal_whoami"
]);
export const SEAL_MUTATING_TOOLS: ReadonlySet<string> = new Set([
"seal_approval_delete_document",
"seal_approval_document_create",
"seal_approval_document_update",
"seal_approval_rule_create",
"seal_approval_rule_delete",
"seal_approval_rule_update",
"seal_approval_rule_version_publish",
"seal_approval_rules_clear",
"seal_approval_rules_push",
"seal_approval_style_preferences_update",
"seal_delegation_create",
"seal_delegation_revoke",
"seal_deploy_hosecloud_configure",
"seal_deploy_hosecloud_sync",
"seal_insight_record_analyze",
"seal_preference_decision_update",
"seal_preference_thinking_depth_policies_remove",
"seal_preference_thinking_depth_policies_upsert",
"seal_preference_thinking_depth_set",
"seal_simulation_batch_clean",
"seal_simulation_batch_create",
"seal_simulation_material_package_upload",
"seal_user_activate",
"seal_user_create",
"seal_user_delegation_create",
"seal_user_delete",
"seal_user_reset_password",
"seal_webhook_add",
"seal_webhook_delete",
"seal_webhook_material_pack",
"seal_webhook_replay",
"seal_webhook_update"
]);
export function isReadOnlySealTool(name: string): boolean {
return SEAL_READ_ONLY_TOOLS.has(name);
}
const sealToolByName = new Map<string, SealTool>(
sealTools.map((tool) => [tool.name, tool])
);
export function findSealTool(name: string): SealTool | undefined {
return sealToolByName.get(name);
}
+227
View File
@@ -0,0 +1,227 @@
import { z } from "zod";
import type { KyInstance } from "ky";
import { readFileSync } from "node:fs";
import { randomBytes } from "node:crypto";
import * as api from "../api.js";
import { defaultSealUrl, ensureHoseCloseApiToken, getHoseProvisionalAuthLink, probeHoseDomain } from "../../../core/auth/hose.js";
import type { CorpConfig } from "../../../core/config/types.js";
import { loadGlobalConfig, loadCorpConfigs, getEnterprisesDirCandidates } from "../../../core/config/loader.js";
import { resolveCorpConfig } from "../../../core/config/manager.js";
import { createSealClient, createSealClientForToken } from "../../../core/http/factory.js";
import { resolveSealCustomHeaders } from "../../../core/http/request-headers.js";
import { searchApprovalContent } from "../search.js";
import { diffRuleVersions, normalizedRuleCode, truncateRuleDiff } from "../rule-diff.js";
import { hydrateRuleVersionStableIds, savePublishedRuleVersionSnapshot } from "../rule-version-snapshot.js";
import { executeApprovalRunsReplay, resolveReplayCorpPair } from "../webhook-replay.js";
import { loadRuleLinter, lintRuleBatch, lintSingleRule, type RuleLintTarget } from "../linter/index.js";
import {
loadLocalRulesFile,
saveLocalRulesFile,
localRulesToLintTargets,
type LocalRuleItem
} from "../rules-local.js";
import {
checkWebhookReadiness,
previewMaterialPack,
pushMaterialPack,
readMaterialPackFile
} from "../material-pack/index.js";
import { MaterialPackFilePolicyPatchSchema, MaterialPackFilePolicySchema } from "../material-pack/policy.js";
import { extractApprovalRunAttachments } from "../attachments.js";
import { exportApprovalRunsToExcel, normalizeTimestamp } from "../approval-runs-export.js";
import {
alignApprovalRunsWithHoseFlow,
createHoseOpenClient,
getHoseOpenFlow
} from "../../hose/index.js";
import { exportInsightReportToExcel, type InsightExportOptions } from "../insight-export.js";
import {
ThinkingPolicySchema,
type ApprovalRule,
type ApprovalRun,
type RuleSetVersion,
type SimulationBatch,
type WebhookIntegration,
type WebhookMode,
type ThinkingPolicy,
type DecisionPreferences,
type HosecloudConfigInput
} from "../types.js";
import type {
ToolContext,
SealToolDefinition,
ApprovalRunSummary,
ApprovalRunsSummaryOptions,
RuleField,
RulePushPlan,
SimulationBatchCreateInput,
HumanResultMatch
} from "./helpers.js";
import * as helpers from "./helpers.js";
const {
presentWebhookIntegration,
getConfiguredSealBaseUrl,
projectApprovalRules,
pickRuleFields,
buildRulePushPlan,
rulesHaveSameContent,
ruleChangedFields,
normalizeRuleStrictness,
parseDurationMs,
redactIntegrationSecrets,
mutationPreview,
redactPreviewValue,
buildSimulationBatchParams,
summarizeSimulationBatch,
summarizeApprovalRun,
summarizeApprovalRuns,
parseFieldPaths,
pickRunFields,
approvalRunMetadata,
summarizeApprovalRunDetail,
summarizeApprovalRunResult,
summarizeApprovalRunDocument,
extractCitedRules,
firstPath,
countPathCandidates,
getPath,
setPath,
compactObject,
asRecord,
numberFromUnknown,
flattenDocumentFields,
collectDocumentFields,
firstByLabel,
collectInvoiceSummary,
collectInvoiceObjects,
findKeywordLines,
summarizeRunBridge,
summarizeRuleVersion,
resolveRuleVersionForLookup,
findRuleInVersion,
normalizeRuleCode,
runtimeRuleIndex,
runtimeRuleIdToCode,
formatRuleCode,
pickApprovalRunCandidate,
resolveApprovalRunForUrl,
resolveSealBaseUrl,
normalizeUrl,
stringFromUnknown,
pickApprovalRuns,
timestampOf,
resolveRuleVersion,
resolveRuleVersionSelector,
filterRuns,
scalarIncludes,
objectContainsScalar,
filterRunsByHumanResult,
withApprovalRunFilters,
resolveManualApprovalStatus,
prepareApprovalRuns,
approvalRunAliases,
extractHumanResult,
findHumanResultValue,
isHumanResultKey,
stringifyHumanResultValue,
matchesRunLookup,
countBy,
localDateKey,
formatLocalDateTime,
toDate,
localParts
} = helpers;
export const insightTools = [
{
name: "seal_insight_stats_get",
description: "查询智能洞察风险标签统计及分析状态",
parameters: z.object({
startDate: z.string().optional().describe("统计开始时间(ISO 8601)"),
endDate: z.string().optional().describe("统计结束时间(ISO 8601)"),
limit: z.number().int().positive().max(100).optional().describe("最多返回的风险标签数量")
}),
handler: async (
client: KyInstance,
params: { startDate?: string; endDate?: string; limit?: number }
) => api.getInsightStats(client, params)
},
{
name: "seal_insight_risks_by_tag_get",
description: "按风险标签查询智能洞察风险单据明细及 AI 分析依据",
parameters: z.object({
tagId: z.string().describe("风险标签 ID(如 B.1.1、B.1.6)"),
startDate: z.string().optional().describe("统计开始时间(ISO 8601)"),
endDate: z.string().optional().describe("统计结束时间(ISO 8601)")
}),
handler: async (
client: KyInstance,
params: { tagId: string; startDate?: string; endDate?: string }
) => api.getInsightRisksByTag(client, params)
},
{
name: "seal_insight_performance_get",
description: "查询智能洞察审核效能指标(自动化率、准确率等)及决策流向桑基图",
parameters: z.object({
startDate: z.union([z.string(), z.number()]).optional().describe("统计开始时间(ISO 8601 或毫秒时间戳)"),
endDate: z.union([z.string(), z.number()]).optional().describe("统计结束时间(ISO 8601 或毫秒时间戳)")
}),
handler: async (
client: KyInstance,
params: { startDate?: string | number; endDate?: string | number }
) => api.getInsightPerformance(client, params)
},
{
name: "seal_insight_record_analyze",
description: "对指定的审批单运行记录按需触发智能洞察风险分析",
parameters: z.object({
recordId: z.string().describe("审批单运行记录 ID (recordId)")
}),
handler: async (
client: KyInstance,
params: { recordId: string }
) => api.analyzeInsightRecord(client, params.recordId)
},
{
name: "seal_insight_export",
description: "导出智能洞察风险研报为高保真 Excel 文件(含效能概览、Top风险标签、风险单据穿透明细)",
parameters: z.object({
startDate: z.string().optional().describe("统计开始时间(ISO 8601 或时间戳)"),
endDate: z.string().optional().describe("统计结束时间(ISO 8601 或时间戳)"),
limit: z.number().int().positive().optional().describe("最多下钻分析的风险标签数量"),
outputFile: z.string().optional().describe("自定义 Excel 保存路径"),
toDownloads: z.boolean().optional().describe("是否直接保存到用户的系统下载目录"),
force: z.boolean().optional().describe("时间跨度超过 180 天时是否强制导出")
}),
handler: async (
client: KyInstance,
params: InsightExportOptions,
context: ToolContext
) => exportInsightReportToExcel(client, context.corp, params)
},
{
name: "seal_expenses_list",
description: "分页查询费用明细",
parameters: z.object({
offset: z.number().int().nonnegative().optional(),
limit: z.number().int().positive().max(100).optional(),
startDate: z.string().optional().describe("开始时间"),
endDate: z.string().optional().describe("结束时间"),
search: z.string().optional().describe("搜索费用类型、描述或金额")
}),
handler: async (client: KyInstance, params: api.DataListParams) => api.listExpenses(client, params)
},
{
name: "seal_invoices_list",
description: "分页查询进项发票",
parameters: z.object({
offset: z.number().int().nonnegative().optional(),
limit: z.number().int().positive().max(100).optional(),
startDate: z.string().optional().describe("开始时间"),
endDate: z.string().optional().describe("结束时间"),
search: z.string().optional().describe("搜索发票号码或销售方")
}),
handler: async (client: KyInstance, params: api.DataListParams) => api.listInvoices(client, params)
}
];
+267
View File
@@ -0,0 +1,267 @@
import { z } from "zod";
import type { KyInstance } from "ky";
import { readFileSync } from "node:fs";
import { randomBytes } from "node:crypto";
import * as api from "../api.js";
import { defaultSealUrl, ensureHoseCloseApiToken, getHoseProvisionalAuthLink, probeHoseDomain } from "../../../core/auth/hose.js";
import type { CorpConfig } from "../../../core/config/types.js";
import { loadGlobalConfig, loadCorpConfigs, getEnterprisesDirCandidates } from "../../../core/config/loader.js";
import { resolveCorpConfig } from "../../../core/config/manager.js";
import { createSealClient, createSealClientForToken } from "../../../core/http/factory.js";
import { resolveSealCustomHeaders } from "../../../core/http/request-headers.js";
import { searchApprovalContent } from "../search.js";
import { diffRuleVersions, normalizedRuleCode, truncateRuleDiff } from "../rule-diff.js";
import { hydrateRuleVersionStableIds, savePublishedRuleVersionSnapshot } from "../rule-version-snapshot.js";
import { executeApprovalRunsReplay, resolveReplayCorpPair } from "../webhook-replay.js";
import { loadRuleLinter, lintRuleBatch, lintSingleRule, type RuleLintTarget } from "../linter/index.js";
import {
loadLocalRulesFile,
saveLocalRulesFile,
localRulesToLintTargets,
type LocalRuleItem
} from "../rules-local.js";
import {
checkWebhookReadiness,
previewMaterialPack,
pushMaterialPack,
readMaterialPackFile
} from "../material-pack/index.js";
import { MaterialPackFilePolicyPatchSchema, MaterialPackFilePolicySchema } from "../material-pack/policy.js";
import { extractApprovalRunAttachments } from "../attachments.js";
import { exportApprovalRunsToExcel, normalizeTimestamp } from "../approval-runs-export.js";
import {
alignApprovalRunsWithHoseFlow,
createHoseOpenClient,
getHoseOpenFlow
} from "../../hose/index.js";
import { exportInsightReportToExcel, type InsightExportOptions } from "../insight-export.js";
import {
ThinkingPolicySchema,
type ApprovalRule,
type ApprovalRun,
type RuleSetVersion,
type SimulationBatch,
type WebhookIntegration,
type WebhookMode,
type ThinkingPolicy,
type DecisionPreferences,
type HosecloudConfigInput
} from "../types.js";
import type {
ToolContext,
SealToolDefinition,
ApprovalRunSummary,
ApprovalRunsSummaryOptions,
RuleField,
RulePushPlan,
SimulationBatchCreateInput,
HumanResultMatch
} from "./helpers.js";
import * as helpers from "./helpers.js";
const {
presentWebhookIntegration,
getConfiguredSealBaseUrl,
projectApprovalRules,
pickRuleFields,
buildRulePushPlan,
rulesHaveSameContent,
ruleChangedFields,
normalizeRuleStrictness,
parseDurationMs,
redactIntegrationSecrets,
mutationPreview,
redactPreviewValue,
buildSimulationBatchParams,
summarizeSimulationBatch,
summarizeApprovalRun,
summarizeApprovalRuns,
parseFieldPaths,
pickRunFields,
approvalRunMetadata,
summarizeApprovalRunDetail,
summarizeApprovalRunResult,
summarizeApprovalRunDocument,
extractCitedRules,
firstPath,
countPathCandidates,
getPath,
setPath,
compactObject,
asRecord,
numberFromUnknown,
flattenDocumentFields,
collectDocumentFields,
firstByLabel,
collectInvoiceSummary,
collectInvoiceObjects,
findKeywordLines,
summarizeRunBridge,
summarizeRuleVersion,
resolveRuleVersionForLookup,
findRuleInVersion,
normalizeRuleCode,
runtimeRuleIndex,
runtimeRuleIdToCode,
formatRuleCode,
pickApprovalRunCandidate,
resolveApprovalRunForUrl,
resolveSealBaseUrl,
normalizeUrl,
stringFromUnknown,
pickApprovalRuns,
timestampOf,
resolveRuleVersion,
resolveRuleVersionSelector,
filterRuns,
scalarIncludes,
objectContainsScalar,
filterRunsByHumanResult,
withApprovalRunFilters,
resolveManualApprovalStatus,
prepareApprovalRuns,
approvalRunAliases,
extractHumanResult,
findHumanResultValue,
isHumanResultKey,
stringifyHumanResultValue,
matchesRunLookup,
countBy,
localDateKey,
formatLocalDateTime,
toDate,
localParts
} = helpers;
export const preferenceTools = [
{
name: "seal_preference_get",
description: "获取当前决策偏好、思考深度偏好与绑定的规则版本",
parameters: z.object({}),
handler: async (client: KyInstance) => {
const config = (await api.getApprovalStylePreferences(client)) as any;
return {
decisionPreferences: config.decisionPreferences,
thinkingDepthPreference: config.thinkingDepthPreference,
ruleSetVersionId: config.ruleSetVersionId
};
}
},
{
name: "seal_preference_decision_update",
description: "修改审核决策偏好(立即影响当前运行中的审核智能体及后续决策)",
parameters: z.object({
explicitApprove: z.string().optional(),
explicitReject: z.string().optional(),
exemptApprove: z.string().optional(),
review: z.string().optional(),
dryRun: z.boolean().optional().describe("只返回前后配置 Diff,不执行写入")
}),
handler: async (client: KyInstance, params: Partial<DecisionPreferences> & { dryRun?: boolean }, context: ToolContext) => {
const config = (await api.getApprovalStylePreferences(client, context.corp.seal.endpoints.approvalStylePreferences)) as any;
const { dryRun, ...changes } = params;
const updated = {
...config,
decisionPreferences: {
...config.decisionPreferences,
...changes
}
};
if (dryRun) return mutationPreview(context, context.corp.seal.endpoints.approvalStylePreferences, config, updated, 1);
await api.updateApprovalStylePreferences(client, updated, context.corp.seal.endpoints.approvalStylePreferences);
return {
decisionPreferences: updated.decisionPreferences
};
}
},
{
name: "seal_preference_thinking_depth_set",
description: "修改默认思考深度(medium 或 high)",
parameters: z.object({
defaultLevel: z.enum(["medium", "high"]).describe("默认思考深度"),
dryRun: z.boolean().optional().describe("只返回前后配置 Diff,不执行写入")
}),
handler: async (client: KyInstance, params: { defaultLevel: "medium" | "high"; dryRun?: boolean }, context: ToolContext) => {
const config = (await api.getApprovalStylePreferences(client, context.corp.seal.endpoints.approvalStylePreferences)) as any;
const updated = {
...config,
thinkingDepthPreference: {
defaultLevel: params.defaultLevel,
routingPolicies: config.thinkingDepthPreference?.routingPolicies ?? []
}
};
if (params.dryRun) return mutationPreview(context, context.corp.seal.endpoints.approvalStylePreferences, config, updated, 1);
await api.updateApprovalStylePreferences(client, updated, context.corp.seal.endpoints.approvalStylePreferences);
return {
thinkingDepthPreference: updated.thinkingDepthPreference
};
}
},
{
name: "seal_preference_thinking_depth_policies_list",
description: "列出思考深度路由策略列表",
parameters: z.object({}),
handler: async (client: KyInstance) => {
const config = (await api.getApprovalStylePreferences(client)) as any;
return {
policies: config.thinkingDepthPreference?.routingPolicies ?? []
};
}
},
{
name: "seal_preference_thinking_depth_policies_upsert",
description: "新增或修改思考深度路由策略",
parameters: ThinkingPolicySchema.extend({
dryRun: z.boolean().optional().describe("只返回前后配置 Diff,不执行写入")
}),
handler: async (client: KyInstance, policy: ThinkingPolicy & { dryRun?: boolean }, context: ToolContext) => {
const config = (await api.getApprovalStylePreferences(client, context.corp.seal.endpoints.approvalStylePreferences)) as any;
const { dryRun, ...cleanPolicy } = policy;
const existing: ThinkingPolicy[] = config.thinkingDepthPreference?.routingPolicies ?? [];
const next = existing.filter((item) => item.id !== cleanPolicy.id);
next.push(cleanPolicy);
const updated = {
...config,
thinkingDepthPreference: {
defaultLevel: config.thinkingDepthPreference?.defaultLevel ?? "medium",
routingPolicies: next
}
};
if (dryRun) return mutationPreview(context, context.corp.seal.endpoints.approvalStylePreferences, config, updated, 1);
await api.updateApprovalStylePreferences(client, updated, context.corp.seal.endpoints.approvalStylePreferences);
return {
policy: cleanPolicy,
policies: next
};
}
},
{
name: "seal_preference_thinking_depth_policies_remove",
description: "删除一条思考深度路由策略",
parameters: z.object({
policyId: z.string().describe("路由策略 ID"),
dryRun: z.boolean().optional().describe("只返回前后配置 Diff,不执行写入")
}),
handler: async (client: KyInstance, params: { policyId: string; dryRun?: boolean }, context: ToolContext) => {
const config = (await api.getApprovalStylePreferences(client, context.corp.seal.endpoints.approvalStylePreferences)) as any;
const existing: ThinkingPolicy[] = config.thinkingDepthPreference?.routingPolicies ?? [];
const next = existing.filter((item) => item.id !== params.policyId);
if (next.length === existing.length) {
throw new Error(`未找到路由策略:${params.policyId}`);
}
const updated = {
...config,
thinkingDepthPreference: {
defaultLevel: config.thinkingDepthPreference?.defaultLevel ?? "medium",
routingPolicies: next
}
};
if (params.dryRun) return mutationPreview(context, context.corp.seal.endpoints.approvalStylePreferences, config, updated, 1);
await api.updateApprovalStylePreferences(client, updated, context.corp.seal.endpoints.approvalStylePreferences);
return {
removedId: params.policyId,
policies: next
};
}
}
];
+938
View File
@@ -0,0 +1,938 @@
import { z } from "zod";
import type { KyInstance } from "ky";
import { readFileSync } from "node:fs";
import { randomBytes } from "node:crypto";
import * as api from "../api.js";
import { defaultSealUrl, ensureHoseCloseApiToken, getHoseProvisionalAuthLink, probeHoseDomain } from "../../../core/auth/hose.js";
import type { CorpConfig } from "../../../core/config/types.js";
import { loadGlobalConfig, loadCorpConfigs, getEnterprisesDirCandidates } from "../../../core/config/loader.js";
import { resolveCorpConfig } from "../../../core/config/manager.js";
import { createSealClient, createSealClientForToken } from "../../../core/http/factory.js";
import { resolveSealCustomHeaders } from "../../../core/http/request-headers.js";
import { searchApprovalContent } from "../search.js";
import { diffRuleVersions, normalizedRuleCode, truncateRuleDiff } from "../rule-diff.js";
import { hydrateRuleVersionStableIds, savePublishedRuleVersionSnapshot } from "../rule-version-snapshot.js";
import { executeApprovalRunsReplay, resolveReplayCorpPair } from "../webhook-replay.js";
import { loadRuleLinter, lintRuleBatch, lintSingleRule, type RuleLintTarget } from "../linter/index.js";
import {
loadLocalRulesFile,
saveLocalRulesFile,
localRulesToLintTargets,
type LocalRuleItem
} from "../rules-local.js";
import {
checkWebhookReadiness,
previewMaterialPack,
pushMaterialPack,
readMaterialPackFile
} from "../material-pack/index.js";
import { MaterialPackFilePolicyPatchSchema, MaterialPackFilePolicySchema } from "../material-pack/policy.js";
import { extractApprovalRunAttachments } from "../attachments.js";
import { exportApprovalRunsToExcel, normalizeTimestamp } from "../approval-runs-export.js";
import {
alignApprovalRunsWithHoseFlow,
createHoseOpenClient,
getHoseOpenFlow
} from "../../hose/index.js";
import { exportInsightReportToExcel, type InsightExportOptions } from "../insight-export.js";
import {
ThinkingPolicySchema,
type ApprovalRule,
type ApprovalRun,
type RuleSetVersion,
type SimulationBatch,
type WebhookIntegration,
type WebhookMode,
type ThinkingPolicy,
type DecisionPreferences,
type HosecloudConfigInput
} from "../types.js";
import type {
ToolContext,
SealToolDefinition,
ApprovalRunSummary,
ApprovalRunsSummaryOptions,
RuleField,
RulePushPlan,
SimulationBatchCreateInput,
HumanResultMatch
} from "./helpers.js";
import * as helpers from "./helpers.js";
const {
presentWebhookIntegration,
getConfiguredSealBaseUrl,
projectApprovalRules,
pickRuleFields,
buildRulePushPlan,
rulesHaveSameContent,
ruleChangedFields,
normalizeRuleStrictness,
parseDurationMs,
redactIntegrationSecrets,
mutationPreview,
redactPreviewValue,
buildSimulationBatchParams,
summarizeSimulationBatch,
summarizeApprovalRun,
summarizeApprovalRuns,
parseFieldPaths,
pickRunFields,
approvalRunMetadata,
summarizeApprovalRunDetail,
summarizeApprovalRunResult,
summarizeApprovalRunDocument,
extractCitedRules,
firstPath,
countPathCandidates,
getPath,
setPath,
compactObject,
asRecord,
numberFromUnknown,
flattenDocumentFields,
collectDocumentFields,
firstByLabel,
collectInvoiceSummary,
collectInvoiceObjects,
findKeywordLines,
summarizeRunBridge,
summarizeRuleVersion,
resolveRuleVersionForLookup,
findRuleInVersion,
normalizeRuleCode,
runtimeRuleIndex,
runtimeRuleIdToCode,
formatRuleCode,
pickApprovalRunCandidate,
resolveApprovalRunForUrl,
resolveSealBaseUrl,
normalizeUrl,
stringFromUnknown,
pickApprovalRuns,
timestampOf,
resolveRuleVersion,
resolveRuleVersionSelector,
filterRuns,
scalarIncludes,
objectContainsScalar,
filterRunsByHumanResult,
withApprovalRunFilters,
resolveManualApprovalStatus,
prepareApprovalRuns,
approvalRunAliases,
extractHumanResult,
findHumanResultValue,
isHumanResultKey,
stringifyHumanResultValue,
matchesRunLookup,
countBy,
localDateKey,
formatLocalDateTime,
toDate,
localParts
} = helpers;
export const rulesTools = [
{
name: "seal_approval_rules_list",
description: "列出 Seal 当前草稿审批规则;返回的 code 属于草稿编号体系,发布版本可能重新编码;支持 countOnly、fields、limit 以避免返回规则正文",
parameters: z.object({
countOnly: z.boolean().optional().describe("只返回规则数量,不返回规则列表"),
fields: z.array(z.enum([
"id",
"code",
"tenantId",
"status",
"strictness",
"scope",
"createdAt",
"updatedAt",
"description"
])).optional().describe("只返回指定字段;不传则返回完整规则"),
limit: z.number().int().nonnegative().optional().describe("最多返回多少条规则;0 可配合 fields 或 countOnly 只取数量"),
offset: z.number().int().nonnegative().optional().describe("跳过前多少条规则")
}),
handler: async (
client: KyInstance,
params: {
countOnly?: boolean;
fields?: RuleField[];
limit?: number;
offset?: number;
}
) => {
const data = await api.listApprovalRules(client);
return projectApprovalRules(data, params);
}
},
{
name: "seal_approval_rules_clear",
description: "清空 Seal 当前草稿审批规则;用于测试环境导入规则前重置草稿规则集",
parameters: z.object({
dryRun: z.boolean().optional().describe("只预览将删除的规则数量,不执行删除"),
recode: z.boolean().optional().describe("删除后尝试重新编排规则编号;失败会作为 warning 返回")
}),
handler: async (
client: KyInstance,
params: { dryRun?: boolean; recode?: boolean },
context: ToolContext
) => {
const before = await api.listApprovalRules(client);
if (params.dryRun) {
return {
...mutationPreview(context, "api/v1/rules", before.rules, [], before.rules.length),
corpId: context.corp.id,
corpName: context.corp.name,
dryRun: true,
beforeCount: before.rules.length,
deleted: 0,
afterCount: before.rules.length,
hasPendingDeletes: before.hasPendingDeletes
};
}
const failed: Array<{ ruleId: string; error: string }> = [];
let deleted = 0;
for (const rule of before.rules) {
try {
await api.deleteApprovalRule(client, rule.id);
deleted += 1;
} catch (error) {
failed.push({
ruleId: rule.id,
error: error instanceof Error ? error.message : String(error)
});
}
}
const warnings: string[] = [];
let recode: unknown;
if (deleted > 0 && params.recode !== false) {
recode = await api.recodeApprovalRules(client);
if (
recode &&
typeof recode === "object" &&
"ok" in recode &&
recode.ok !== true
) {
warnings.push("batch-recode did not complete; current rules were still deleted");
}
}
const after = await api.listApprovalRules(client);
return {
corpId: context.corp.id,
corpName: context.corp.name,
dryRun: false,
beforeCount: before.rules.length,
deleted,
failed,
afterCount: after.rules.length,
hasPendingDeletes: after.hasPendingDeletes,
warnings,
recode
};
}
},
{
name: "seal_approval_rule_create",
description: "新建 Seal 草稿审批规则",
parameters: z.object({
description: z.string().describe("规则描述"),
scope: z.string().describe("适用场景"),
strictness: z.enum(["MUST_FOLLOW", "SHOULD_FOLLOW", "SUGGESTION"]).describe("严格程度")
}),
handler: async (
client: KyInstance,
params: { description: string; scope: string; strictness: string }
) => api.createApprovalRule(client, params)
},
{
name: "seal_approval_rule_update",
description: "更新 Seal 草稿审批规则",
parameters: z.object({
ruleId: z.string().describe("规则 ID"),
description: z.string().optional(),
scope: z.string().optional(),
strictness: z.enum(["MUST_FOLLOW", "SHOULD_FOLLOW", "SUGGESTION"]).optional()
}),
handler: async (
client: KyInstance,
params: { ruleId: string; description?: string; scope?: string; strictness?: string }
) => {
let resolvedRuleId = params.ruleId;
if (resolvedRuleId && (resolvedRuleId.startsWith("#") || resolvedRuleId.startsWith("rule-") || resolvedRuleId.match(/^\d+$/))) {
const draftData = await api.listApprovalRules(client).catch(() => undefined);
if (draftData?.rules) {
const normalizedInput = normalizeRuleCode(resolvedRuleId);
const runtimeIdx = runtimeRuleIndex(resolvedRuleId);
const targetIndex = normalizedInput ? Number(normalizedInput.slice(1)) : runtimeIdx;
const matched = draftData.rules.find((r, idx) => {
const code = normalizeRuleCode(stringFromUnknown((r as any).code) ?? stringFromUnknown((r as any).ruleCode));
return code === normalizedInput || (targetIndex !== undefined && idx + 1 === targetIndex);
});
if (matched) {
resolvedRuleId = matched.id;
}
}
}
const { ruleId, ...rest } = params;
const result = await api.updateApprovalRule(client, resolvedRuleId, rest);
if (params.description) {
try {
const globalConfig = loadGlobalConfig();
if (globalConfig.lint?.enabled) {
const loaded = await loadRuleLinter(globalConfig.lint.activeLinter);
const lintResult = await lintSingleRule({ id: ruleId, description: params.description }, loaded);
if (lintResult.issues.length > 0) {
console.error(`⚠️ [Linter 质检提醒] 规则质量评分: ${lintResult.score}/100 (发现 ${lintResult.issues.length} 处潜在风险):`);
for (const issue of lintResult.issues) {
console.error(` • [${issue.level.toUpperCase()}] ${issue.message}${issue.snippet ? ` ("${issue.snippet}")` : ""}`);
if (issue.suggestion) {
console.error(` 👉 建议: ${issue.suggestion}`);
}
}
}
}
} catch {
// 容错降级:质检异常绝不阻断规则更新
}
}
return result;
}
},
{
name: "seal_approval_rule_delete",
description: "删除 Seal 草稿审批规则",
parameters: z.object({
ruleId: z.string().describe("规则 ID")
}),
handler: async (client: KyInstance, params: { ruleId: string }) => {
await api.deleteApprovalRule(client, params.ruleId);
return { success: true };
}
},
{
name: "seal_approval_rule_versions_list",
description: "列出 Seal 已发布审批规则版本摘要,不展开每个版本的规则快照",
parameters: z.object({}),
handler: async (client: KyInstance) => {
const versions = await api.listApprovalRuleVersions(client);
return {
count: versions.length,
latest: versions[0] ? summarizeRuleVersion(versions[0]) : undefined,
versions: versions.map(summarizeRuleVersion)
};
}
},
{
name: "seal_approval_rule_version_get",
description: "获取指定 Seal 已发布审批规则版本详情,包含该版本的规则快照",
parameters: z.object({
versionId: z.string().optional().describe("规则版本 ID"),
versionNumber: z.number().int().positive().optional().describe("规则版本号"),
latest: z.boolean().optional().describe("为 true 时获取最新版本")
}),
handler: async (
client: KyInstance,
params: { versionId?: string; versionNumber?: number; latest?: boolean }
) => {
if (params.versionId) return api.getApprovalRuleVersion(client, params.versionId);
const versions = await api.listApprovalRuleVersions(client);
const version = params.versionNumber
? versions.find((item) => item.versionNumber === params.versionNumber)
: versions[0];
if (!version) {
throw new Error(params.versionNumber
? `Rule version not found: ${params.versionNumber}`
: "No rule versions found");
}
return version;
}
},
{
name: "seal_approval_rule_version_diff",
description: "对比两个已发布审批规则版本;优先使用本地持久化稳定 ID,没有时回退到 code",
parameters: z.object({
from: z.string().min(1).describe("起始规则版本号、版本 ID 或 latest"),
to: z.string().min(1).describe("目标规则版本号、版本 ID 或 latest"),
ruleId: z.string().optional().describe("只对比指定稳定规则 ID"),
code: z.string().optional().describe("只对比指定规则 code"),
includeUnchanged: z.boolean().optional().describe("是否返回未变化规则,默认 false"),
full: z.boolean().optional().describe("超过默认 diff 上限时返回完整内容"),
format: z.enum(["unified", "json"]).default("unified").describe("输出格式;unified 将 diff 文本放入 unifiedDiff 字段")
}),
handler: async (
client: KyInstance,
params: {
from: string;
to: string;
ruleId?: string;
code?: string;
includeUnchanged?: boolean;
full?: boolean;
format?: "unified" | "json";
},
context: ToolContext
) => {
const fromVersion = hydrateRuleVersionStableIds(context.corp.id, await resolveRuleVersionSelector(client, params.from));
const toVersion = hydrateRuleVersionStableIds(context.corp.id, await resolveRuleVersionSelector(client, params.to));
let result = diffRuleVersions(fromVersion, toVersion, {
includeUnchanged: params.includeUnchanged
});
if (!params.ruleId && !params.code) return { ...truncateRuleDiff(result, 20_000, params.full === true), format: params.format ?? "unified" };
const changes = result.changes.filter((change) => {
if (params.ruleId && change.ruleId === params.ruleId) return true;
if (!params.code) return false;
return normalizedRuleCode(params.code) === normalizedRuleCode(change.before?.code ?? change.before?.ruleCode ?? change.after?.code ?? change.after?.ruleCode ?? change.ruleId);
});
const counts = { added: 0, removed: 0, modified: 0, unchanged: 0 };
for (const change of changes) counts[change.status] += 1;
result = {
...result,
counts,
changes,
unifiedDiff: changes.map((change) => change.diff).filter(Boolean).join("\n")
};
return { ...truncateRuleDiff(result, 20_000, params.full === true), format: params.format ?? "unified" };
}
},
{
name: "seal_approval_rule_version_publish",
description: "发布 Seal 草稿审批规则为新版本",
parameters: z.object({
versionName: z.string().describe("版本名称")
}),
handler: async (client: KyInstance, params: { versionName: string }, context: ToolContext) => {
const draft = await api.listApprovalRules(client).catch(() => undefined);
const published = await api.publishApprovalRuleVersion(client, params.versionName);
if (draft) {
try { savePublishedRuleVersionSnapshot(context.corp.id, published.version, draft.rules); } catch {}
}
return published;
}
},
{
name: "seal_approval_rule_get",
description: "按版本号/code/runtime-id/record-id 定位单条规则;code 只在选定的版本编号体系内有效,避免拉取整版规则快照",
parameters: z.object({
versionId: z.string().optional().describe("规则版本 ID"),
versionNumber: z.number().int().positive().optional().describe("规则版本号"),
latest: z.boolean().optional().describe("为 true 时取最新版本"),
code: z.string().optional().describe("规则展示编号,如 #0038;没有后端 code 时按版本内序号匹配"),
runtimeId: z.string().optional().describe("运行时规则 ID,如 rule-205;按版本内序号匹配"),
recordId: z.string().optional().describe("从运行记录推断 ruleSetVersionNumber")
}),
handler: async (
client: KyInstance,
params: {
versionId?: string;
versionNumber?: number;
latest?: boolean;
code?: string;
runtimeId?: string;
recordId?: string;
}
) => {
const version = await resolveRuleVersionForLookup(client, params);
const rule = findRuleInVersion(version, {
code: params.code,
runtimeId: params.runtimeId
});
if (!rule) {
throw new Error(`Rule not found in version ${version.versionNumber}`);
}
return rule;
}
},
{
name: "seal_approval_rules_lint",
description: "对 Seal 本地规则文件、草稿审批规则或指定发布版本规则进行质量与可执行性检查(模糊词、悬空例外检测)",
parameters: z.object({
file: z.string().optional().describe("指定本地规则文件路径进行离线质检(支持 .json),0网络请求、不污染远端草稿"),
linter: z.string().optional().describe("指定使用的校验器名称或脚本路径(如 builtin、strict、./my-linter.ts)"),
version: z.string().optional().describe("指定要质检的历史发布版本号或 ID(如 16 或 latest),不传默认质检当前草稿"),
code: z.string().optional().describe("按规则展示编号过滤(如 #0038)"),
ruleId: z.string().optional().describe("按规则 ID 过滤"),
minScore: z.number().optional().describe("最低合格质量分阈值(0~100),低于该分值抛出错误以返回非零退出码"),
level: z.enum(["all", "error", "warning"]).default("all").describe("问题报告等级过滤"),
summary: z.boolean().optional().describe("为 true 时仅返回存在瑕疵/扣分的规则")
}),
handler: async (
client: KyInstance,
params: {
file?: string;
linter?: string;
version?: string;
code?: string;
ruleId?: string;
minScore?: number;
level?: "all" | "error" | "warning";
summary?: boolean;
},
context: ToolContext
) => {
let targets: RuleLintTarget[] = [];
let versionNumber: number | undefined;
if (params.file) {
const local = loadLocalRulesFile(params.file);
targets = localRulesToLintTargets(local.rules);
versionNumber = local.meta.versionNumber;
} else if (params.version) {
const versions = await api.listApprovalRuleVersions(client);
const versionNumberParsed = Number(params.version);
const version = isNaN(versionNumberParsed)
? params.version === "latest"
? versions[0]
: versions.find((v) => v.id === params.version)
: versions.find((v) => v.versionNumber === versionNumberParsed);
if (!version) {
throw new Error(`未找到指定的规则版本: ${params.version}`);
}
versionNumber = version.versionNumber;
targets = (version.rules ?? []).map((r, idx) => ({
id: (r as any).id ?? (r as any).runtimeId,
code: (r as any).code ?? `#${String(idx + 1).padStart(4, "0")}`,
name: (r as any).name ?? (r as any).title,
description: r.description ?? "",
scope: (r as any).scope,
strictness: (r as any).strictness
}));
} else {
const draftData = await api.listApprovalRules(client);
targets = (draftData.rules ?? []).map((r, idx) => ({
id: r.id,
code: (r as any).code ?? `#${String(idx + 1).padStart(4, "0")}`,
name: (r as any).name ?? (r as any).title,
description: r.description ?? "",
scope: r.scope,
strictness: r.strictness
}));
}
if (params.code) {
targets = targets.filter(
(r) => r.code === params.code || r.code?.replace(/[#\s]/g, "") === params.code?.replace(/[#\s]/g, "")
);
}
if (params.ruleId) {
targets = targets.filter((r) => r.id === params.ruleId || r.code === params.ruleId);
}
const globalConfig = loadGlobalConfig();
const linterNameOrPath = params.linter ?? globalConfig.lint?.activeLinter ?? "builtin";
const loadedLinter = await loadRuleLinter(linterNameOrPath);
const batchResult = await lintRuleBatch(
targets,
loadedLinter,
{ corpId: context?.corp?.id, versionNumber, allRules: targets },
{ minScore: params.minScore, level: params.level, summary: params.summary }
);
if (params.minScore && batchResult.overallScore < params.minScore) {
throw new Error(
`[Linter 质量门禁未通过] 综合评分 ${batchResult.overallScore} 低于要求的最低分 ${params.minScore} 分 (共发现 ${batchResult.issueCount} 条问题规则)。`
);
}
return batchResult;
}
},
{
name: "seal_approval_rules_pull",
description: "从 Seal 远端拉取草稿或指定版本规则,保存至本地规则文件(支持离线编辑与本地 Lint,绝不污染远端草稿)",
parameters: z.object({
version: z.string().optional().describe("指定拉取的历史发布版本号或 ID(如 16 或 latest),不传默认拉取当前草稿规则"),
out: z.string().optional().describe("保存的目标本地文件路径,默认为 ./rules.local.json")
}),
handler: async (
client: KyInstance,
params: {
version?: string;
out?: string;
},
context: ToolContext
) => {
const outPath = params.out ?? "./rules.local.json";
let rules: LocalRuleItem[] = [];
let source = "draft";
let versionNumber: number | undefined;
if (params.version) {
const versions = await api.listApprovalRuleVersions(client);
const versionNumberParsed = Number(params.version);
const targetVersion = isNaN(versionNumberParsed)
? params.version === "latest"
? versions[0]
: versions.find((v) => v.id === params.version)
: versions.find((v) => v.versionNumber === versionNumberParsed);
if (!targetVersion) {
throw new Error(`未找到指定的规则版本: ${params.version}`);
}
versionNumber = targetVersion.versionNumber;
source = `version:${versionNumber}`;
rules = (targetVersion.rules ?? []).map((r, idx) => ({
code: (r as any).code ? Number(String((r as any).code).replace(/^#/, "")) || idx + 1 : idx + 1,
name: (r as any).name ?? (r as any).title,
description: r.description ?? "",
scope: (r as any).scope ?? "ALL",
strictness: (r as any).strictness ?? "MUST_FOLLOW"
}));
} else {
const draftData = await api.listApprovalRules(client);
rules = (draftData.rules ?? []).map((r, idx) => ({
id: r.id,
code: r.code ?? idx + 1,
name: (r as any).name ?? (r as any).title,
description: r.description ?? "",
scope: r.scope ?? "ALL",
strictness: r.strictness ?? "MUST_FOLLOW",
status: r.status
}));
}
const savedPath = saveLocalRulesFile(outPath, {
corpId: context.corp.id,
source,
versionNumber,
exportedAt: new Date().toISOString(),
rulesCount: rules.length,
rules
});
return {
saved: true,
path: savedPath,
rulesCount: rules.length,
corpId: context.corp.id,
source,
versionNumber
};
}
},
{
name: "seal_approval_rules_push",
description: "将本地规则文件增量同步到远端草稿;按规则 ID 更新/删除并保留未变更规则,支持直接发布为正式版本",
parameters: z.object({
file: z.string().optional().describe("要推送的本地规则文件路径,默认为 ./rules.local.json"),
dryRun: z.boolean().optional().describe("是否仅预览变更而不实际写入远端(默认 true,传 --yes 或 confirm: true 执行写入)"),
confirm: z.boolean().optional().describe("确认覆盖写入远端草稿"),
publish: z.boolean().optional().describe("写入草稿后是否直接发布为一个正式版本"),
versionName: z.string().optional().describe("发布版本的名称(仅在 publish=true 时有效)")
}),
handler: async (
client: KyInstance,
params: {
file?: string;
dryRun?: boolean;
confirm?: boolean;
publish?: boolean;
versionName?: string;
},
context: ToolContext
) => {
const filePath = params.file ?? "./rules.local.json";
const local = loadLocalRulesFile(filePath);
const isConfirmed = params.confirm === true;
const isDryRun = params.dryRun ?? !isConfirmed;
const before = await api.listApprovalRules(client);
const plan = buildRulePushPlan(before.rules, local.rules);
if (isDryRun) {
return {
...mutationPreview(
context,
"api/v1/rules",
before.rules,
local.rules.map((rule) => ({
description: rule.description,
scope: rule.scope ?? "ALL",
strictness: rule.strictness ?? "MUST_FOLLOW"
})),
before.rules.length + local.rules.length
),
corpId: context.corp.id,
dryRun: true,
localFile: local.resolvedPath,
localRulesCount: local.rules.length,
remoteDraftCount: before.rules.length,
changes: plan,
impactCount: plan.created.length + plan.updated.length + plan.deleted.length,
preservedRuleIds: [
...plan.updated.map((change) => change.id),
...plan.unchanged.map((rule) => rule.id)
],
warning: "Incremental mode preserves matched rule IDs and does not recode the draft rule set.",
willPublish: Boolean(params.publish),
message: "Preview mode. Use --yes or confirm=true to apply the listed incremental changes to the remote draft."
};
}
for (const rule of plan.deleted) {
await api.deleteApprovalRule(client, rule.id);
}
const created: Array<{ id: string; description: string; code?: string | number }> = [];
for (const rule of plan.created) {
const newRule = await api.createApprovalRule(client, {
description: rule.description,
scope: rule.scope ?? "ALL",
strictness: normalizeRuleStrictness(rule.strictness)
});
created.push({ id: newRule.id, description: newRule.description, code: newRule.code });
}
const updated: string[] = [];
for (const change of plan.updated) {
await api.updateApprovalRule(client, change.id, {
description: change.rule.description,
scope: change.rule.scope ?? "ALL",
strictness: normalizeRuleStrictness(change.rule.strictness)
});
updated.push(change.id);
}
let publishedVersion: unknown = undefined;
if (params.publish) {
const dateStr = new Date().toISOString().slice(0, 10).replace(/-/g, "");
const name = params.versionName || `v-local-${dateStr}-${Date.now().toString().slice(-4)}`;
publishedVersion = await api.publishApprovalRuleVersion(client, name);
try {
const draft = await api.listApprovalRules(client);
savePublishedRuleVersionSnapshot(context.corp.id, (publishedVersion as { version: RuleSetVersion }).version, draft.rules);
} catch {}
}
return {
corpId: context.corp.id,
dryRun: false,
localFile: local.resolvedPath,
deletedRules: plan.deleted.length,
createdRules: created.length,
updatedRules: updated.length,
unchangedRules: plan.unchanged.length,
preservedRuleIds: [
...updated,
...plan.unchanged.map((rule) => rule.id)
],
recoded: false,
published: publishedVersion ?? false
};
}
},
{
name: "seal_approval_documents_list",
description: "列出 Seal 审批知识文档",
parameters: z.object({
scenarios: z.array(z.string()).optional().describe("场景过滤"),
offset: z.number().int().nonnegative().optional(),
limit: z.number().int().positive().optional()
}),
handler: async (
client: KyInstance,
params: { scenarios?: string[]; offset?: number; limit?: number }
) => api.listApprovalDocuments(client, params)
},
{
name: "seal_approval_document_get",
description: "获取 Seal 审批知识文档详情",
parameters: z.object({
documentId: z.string().describe("文档 ID")
}),
handler: async (client: KyInstance, params: { documentId: string }) =>
api.getApprovalDocument(client, params.documentId)
},
{
name: "seal_approval_document_create",
description: "新建 Seal 审批知识文档",
parameters: z.object({
title: z.string(),
purpose: z.string(),
content: z.string().describe("正文,通常为 Markdown"),
contentType: z.string().optional(),
status: z.string().optional(),
enabled: z.boolean().optional(),
scenarios: z.array(z.string()).optional(),
tags: z.array(z.string()).optional()
}),
handler: async (
client: KyInstance,
params: {
title: string;
purpose: string;
content: string;
contentType?: string;
status?: string;
enabled?: boolean;
scenarios?: string[];
tags?: string[];
}
) => api.createApprovalDocument(client, params)
},
{
name: "seal_approval_document_update",
description: "更新 Seal 审批知识文档",
parameters: z.object({
documentId: z.string(),
title: z.string().optional(),
purpose: z.string().optional(),
content: z.string().optional(),
contentType: z.string().optional(),
status: z.string().optional(),
enabled: z.boolean().optional(),
scenarios: z.array(z.string()).optional(),
tags: z.array(z.string()).optional()
}),
handler: async (
client: KyInstance,
params: {
documentId: string;
title?: string;
purpose?: string;
content?: string;
contentType?: string;
status?: string;
enabled?: boolean;
scenarios?: string[];
tags?: string[];
}
) => {
const { documentId, ...rest } = params;
return api.updateApprovalDocument(client, documentId, rest);
}
},
{
name: "seal_approval_delete_document",
description: "删除 Seal 审批知识文档",
parameters: z.object({
documentId: z.string().describe("知识文档 ID")
}),
handler: (client: KyInstance, params: { documentId: string }) =>
api.deleteApprovalDocument(client, params.documentId)
},
{
name: "seal_approval_search",
description: "按关键词组检索 Seal 审批规则、审批文档和审批偏好配置,返回命中位置、字段、行号和前后三行上下文",
parameters: z.object({
keywords: z.array(z.string()).min(1).describe("关键词组"),
matchMode: z.enum(["any", "all"]).optional().describe("any 命中任一关键词,all 要求同一行命中全部关键词"),
areas: z.array(z.enum(["rules", "documents", "preferences"])).optional().describe("检索范围"),
caseSensitive: z.boolean().optional().describe("是否大小写敏感"),
contextLines: z.number().int().nonnegative().optional().describe("返回命中行前后几行,默认 3"),
documentLimit: z.number().int().positive().optional().describe("缓存刷新时最多拉取文档数,默认 100"),
maxResults: z.number().int().positive().optional().describe("最多返回命中数,默认 50"),
refresh: z.boolean().optional().describe("是否跳过 5 分钟内存缓存并强制刷新"),
ruleVersionScope: z.enum(["current", "all", "version"]).optional().describe("规则检索范围,默认 current;all 会检索所有已发布历史版本"),
ruleVersionId: z.string().optional().describe("ruleVersionScope=version 时指定版本 ID"),
ruleVersionNumber: z.number().int().positive().optional().describe("ruleVersionScope=version 时指定版本号"),
latestRuleVersion: z.boolean().optional().describe("ruleVersionScope=version 时取最新已发布版本"),
snippetOnly: z.boolean().optional().describe("只返回命中行,不返回前后文"),
maxChars: z.number().int().positive().optional().describe("每个文本片段最多返回字符数"),
fields: z.array(z.string()).optional().describe("只搜索指定字段,如 history.description、description、scope")
}),
handler: async (
client: KyInstance,
params: {
keywords: string[];
matchMode?: "any" | "all";
areas?: Array<"rules" | "documents" | "preferences">;
caseSensitive?: boolean;
contextLines?: number;
documentLimit?: number;
maxResults?: number;
refresh?: boolean;
ruleVersionScope?: "current" | "all" | "version";
ruleVersionId?: string;
ruleVersionNumber?: number;
latestRuleVersion?: boolean;
snippetOnly?: boolean;
maxChars?: number;
fields?: string[];
},
context: ToolContext
) => searchApprovalContent(client, context.corp, params)
},
{
name: "seal_approval_context_get",
description: "聚合获取 Seal 现有审批规则、审批文档和审批风格偏好",
parameters: z.object({
documentLimit: z.number().int().positive().optional().describe("最多返回的审批文档数量"),
ruleVersionId: z.string().optional().describe("指定已发布规则版本 ID;指定后 rules 返回该版本快照"),
ruleVersionNumber: z.number().int().positive().optional().describe("指定已发布规则版本号;指定后 rules 返回该版本快照"),
latestRuleVersion: z.boolean().optional().describe("为 true 时 rules 返回最新已发布版本快照")
}),
handler: async (
client: KyInstance,
params: {
documentLimit?: number;
ruleVersionId?: string;
ruleVersionNumber?: number;
latestRuleVersion?: boolean;
},
context: ToolContext
) => {
const currentContext = await api.getApprovalContext(client, {
documentLimit: params.documentLimit,
stylePreferencesEndpoint: context.corp.seal.endpoints.approvalStylePreferences
});
if (!params.ruleVersionId && !params.ruleVersionNumber && !params.latestRuleVersion) {
return currentContext;
}
const version = await resolveRuleVersion(client, params);
return {
...currentContext,
rules: {
version: summarizeRuleVersion(version),
rules: version.rules
}
};
}
},
{
name: "seal_approval_style_preferences_get",
description: "获取 Seal 审批风格偏好配置",
parameters: z.object({}),
handler: async (client: KyInstance, _params: unknown, context: ToolContext) =>
api.getApprovalStylePreferences(
client,
context.corp.seal.endpoints.approvalStylePreferences
)
},
{
name: "seal_approval_style_preferences_update",
description: "更新 Seal 审批风格偏好配置",
parameters: z.object({
tone: z.string().optional(),
language: z.string().optional(),
detailLevel: z.string().optional(),
outputFormat: z.string().optional(),
examples: z.array(z.string()).optional(),
prohibitedPhrases: z.array(z.string()).optional(),
customInstructions: z.string().optional()
}),
handler: async (
client: KyInstance,
params: Record<string, unknown>,
context: ToolContext
) =>
api.updateApprovalStylePreferences(
client,
params,
context.corp.seal.endpoints.approvalStylePreferences
)
}
];
+430
View File
@@ -0,0 +1,430 @@
import { z } from "zod";
import type { KyInstance } from "ky";
import { readFileSync } from "node:fs";
import { randomBytes } from "node:crypto";
import * as api from "../api.js";
import { defaultSealUrl, ensureHoseCloseApiToken, getHoseProvisionalAuthLink, probeHoseDomain } from "../../../core/auth/hose.js";
import type { CorpConfig } from "../../../core/config/types.js";
import { loadGlobalConfig, loadCorpConfigs, getEnterprisesDirCandidates } from "../../../core/config/loader.js";
import { resolveCorpConfig } from "../../../core/config/manager.js";
import { createSealClient, createSealClientForToken } from "../../../core/http/factory.js";
import { resolveSealCustomHeaders } from "../../../core/http/request-headers.js";
import { searchApprovalContent } from "../search.js";
import { diffRuleVersions, normalizedRuleCode, truncateRuleDiff } from "../rule-diff.js";
import { hydrateRuleVersionStableIds, savePublishedRuleVersionSnapshot } from "../rule-version-snapshot.js";
import { executeApprovalRunsReplay, resolveReplayCorpPair } from "../webhook-replay.js";
import { loadRuleLinter, lintRuleBatch, lintSingleRule, type RuleLintTarget } from "../linter/index.js";
import {
loadLocalRulesFile,
saveLocalRulesFile,
localRulesToLintTargets,
type LocalRuleItem
} from "../rules-local.js";
import {
checkWebhookReadiness,
previewMaterialPack,
pushMaterialPack,
readMaterialPackFile
} from "../material-pack/index.js";
import { MaterialPackFilePolicyPatchSchema, MaterialPackFilePolicySchema } from "../material-pack/policy.js";
import { extractApprovalRunAttachments } from "../attachments.js";
import { exportApprovalRunsToExcel, normalizeTimestamp } from "../approval-runs-export.js";
import {
alignApprovalRunsWithHoseFlow,
createHoseOpenClient,
getHoseOpenFlow
} from "../../hose/index.js";
import { exportInsightReportToExcel, type InsightExportOptions } from "../insight-export.js";
import {
ThinkingPolicySchema,
type ApprovalRule,
type ApprovalRun,
type RuleSetVersion,
type SimulationBatch,
type WebhookIntegration,
type WebhookMode,
type ThinkingPolicy,
type DecisionPreferences,
type HosecloudConfigInput
} from "../types.js";
import type {
ToolContext,
SealToolDefinition,
ApprovalRunSummary,
ApprovalRunsSummaryOptions,
RuleField,
RulePushPlan,
SimulationBatchCreateInput,
HumanResultMatch
} from "./helpers.js";
import * as helpers from "./helpers.js";
const {
presentWebhookIntegration,
getConfiguredSealBaseUrl,
projectApprovalRules,
pickRuleFields,
buildRulePushPlan,
rulesHaveSameContent,
ruleChangedFields,
normalizeRuleStrictness,
parseDurationMs,
redactIntegrationSecrets,
mutationPreview,
redactPreviewValue,
buildSimulationBatchParams,
summarizeSimulationBatch,
summarizeApprovalRun,
summarizeApprovalRuns,
parseFieldPaths,
pickRunFields,
approvalRunMetadata,
summarizeApprovalRunDetail,
summarizeApprovalRunResult,
summarizeApprovalRunDocument,
extractCitedRules,
firstPath,
countPathCandidates,
getPath,
setPath,
compactObject,
asRecord,
numberFromUnknown,
flattenDocumentFields,
collectDocumentFields,
firstByLabel,
collectInvoiceSummary,
collectInvoiceObjects,
findKeywordLines,
summarizeRunBridge,
summarizeRuleVersion,
resolveRuleVersionForLookup,
findRuleInVersion,
normalizeRuleCode,
runtimeRuleIndex,
runtimeRuleIdToCode,
formatRuleCode,
pickApprovalRunCandidate,
resolveApprovalRunForUrl,
resolveSealBaseUrl,
normalizeUrl,
stringFromUnknown,
pickApprovalRuns,
timestampOf,
resolveRuleVersion,
resolveRuleVersionSelector,
filterRuns,
scalarIncludes,
objectContainsScalar,
filterRunsByHumanResult,
withApprovalRunFilters,
resolveManualApprovalStatus,
prepareApprovalRuns,
approvalRunAliases,
extractHumanResult,
findHumanResultValue,
isHumanResultKey,
stringifyHumanResultValue,
matchesRunLookup,
countBy,
localDateKey,
formatLocalDateTime,
toDate,
localParts
} = helpers;
export const simulationTools = [
{
name: "seal_simulation_feishu_approval_definitions_list",
description: "列出飞书模拟测试可用的审批定义,便于选择 approvalCode",
parameters: z.object({}),
handler: async (client: KyInstance) => {
const approvalDefinitions = await api.listFeishuSimulationApprovalDefinitions(client);
return { count: approvalDefinitions.length, approvalDefinitions };
}
},
{
name: "seal_simulation_batch_records_get",
description: "获取某一次 Seal 模拟批次的运行记录,并整理对应 Langfuse trace/session 桥接字段",
parameters: z.object({
batchId: z.string().describe("simulation batch ID"),
query: z.string().optional().describe("在 id、sourceDocumentSN、sourceDocumentId、documentId、Langfuse traceId 中做本地包含匹配")
}),
handler: async (
client: KyInstance,
params: { batchId: string; query?: string }
) => {
const records = filterRuns(
await api.listSimulationBatchRecords(client, params.batchId),
params.query
);
return {
batchId: params.batchId,
count: records.length,
records: records.map(summarizeApprovalRun),
bridge: summarizeRunBridge(records)
};
}
},
{
name: "seal_simulation_batch_create",
description: "创建 Seal 模拟测试批次。支持合思指定单号(hosecloud)与材料包导入(material_pack)两种模式;其他取数模式通过 rawParams 预留透传。",
parameters: z.object({
mode: z.enum(["hosecloud", "material_pack"]).default("hosecloud").describe("来源模式: hosecloud=合思指定单号; material_pack=材料包导入"),
flowIds: z.array(z.string()).max(100).optional().describe("合思模式: 单据流水号列表"),
rejectNodeName: z.string().nullable().optional().describe("仅关注特定节点: 节点名称, 不设为 null 表示不限制"),
thinkingDepthOverride: z.enum(["default", "medium", "high"]).optional().describe("思考深度: default=按偏好设置, medium=标准, high=深度推理"),
skipInvoiceGeneration: z.boolean().optional().describe("跳过发票生成, 默认 true"),
skipExpenseExtraction: z.boolean().optional().describe("跳过费用提取, 默认 true"),
disableAttachmentCache: z.boolean().optional().describe("不使用附件缓存, 默认 false"),
signKey: z.string().optional().describe("合思集成标识; 缺省时自动取第一个合思集成"),
packageIds: z.array(z.string()).optional().describe("材料包模式: 材料包 id 列表(来自 material-packages upload 响应)"),
templateId: z.string().optional().describe("材料包模板 id, 例如 conference_reimbursement_v1; 缺省取 schemaConfig.id"),
schemaConfig: z.record(z.string(), z.unknown()).optional().describe("材料包字段映射(确认参数), 建议使用 material-packages upload 返回的 schemaConfig"),
noWait: z.boolean().optional().describe("创建后立即返回异步票据,不等待批次完成"),
rawParams: z.record(z.string(), z.unknown()).optional().describe("预留: 其他取数模式(如时间范围 startTime/endTime)透传参数, 覆盖上述构建结果")
}),
handler: async (
client: KyInstance,
params: {
mode?: "hosecloud" | "material_pack";
flowIds?: string[];
rejectNodeName?: string | null;
thinkingDepthOverride?: "default" | "medium" | "high";
skipInvoiceGeneration?: boolean;
skipExpenseExtraction?: boolean;
disableAttachmentCache?: boolean;
signKey?: string;
packageIds?: string[];
templateId?: string;
schemaConfig?: Record<string, unknown>;
noWait?: boolean;
rawParams?: Record<string, unknown>;
}
) => {
const mode = params.mode ?? "hosecloud";
let signKey = params.signKey;
if (mode === "hosecloud" && !signKey) {
const integrations = await api.listSimulationHosecloudIntegrations(client);
signKey = integrations.find((item) => item.signKey)?.signKey;
if (!signKey) {
throw new Error("未找到合思集成 signKey, 请通过 signKey 参数提供");
}
}
const payload = buildSimulationBatchParams({
mode,
flowIds: params.flowIds,
rejectNodeName: params.rejectNodeName,
thinkingDepthOverride: params.thinkingDepthOverride,
skipInvoiceGeneration: params.skipInvoiceGeneration,
skipExpenseExtraction: params.skipExpenseExtraction,
disableAttachmentCache: params.disableAttachmentCache,
signKey,
packageIds: params.packageIds,
templateId: params.templateId,
schemaConfig: params.schemaConfig,
rawParams: params.rawParams
});
const result = mode === "material_pack"
? await api.createMaterialPackBatch(client, payload)
: await api.createSimulationBatch(client, payload);
return {
...result,
created: true,
noWait: params.noWait ?? true,
asyncTicket: result.batchId,
next: {
status: `seal-use simulation status ${result.batchId}`,
wait: `seal-use simulation wait ${result.batchId}`,
getBatch: `seal-use simulation get ${result.batchId}`,
getRecords: `seal-use simulation batch-records ${result.batchId}`,
listBatches: "seal-use simulation list"
}
};
}
},
{
name: "seal_simulation_batches_list",
description: "列出 Seal 模拟测试批次摘要(含状态、统计计数与展示摘要)",
parameters: z.object({
limit: z.number().int().positive().max(100).optional().describe("最多返回批次数量, 默认 50")
}),
handler: async (client: KyInstance, params: { limit?: number }) => {
const batches = await api.listSimulationBatches(client, { limit: params.limit ?? 50 });
return {
count: batches.length,
batches: batches.map(summarizeSimulationBatch),
next: {
getBatch: "seal-use simulation get <batchId>",
getRecords: "seal-use simulation batch-records <batchId>"
}
};
}
},
{
name: "seal_simulation_batch_get",
description: "获取某一次 Seal 模拟测试批次的详情,包含服务端回显的创建参数、展示摘要和任务统计",
parameters: z.object({
batchId: z.string().describe("simulation batch ID")
}),
handler: async (client: KyInstance, params: { batchId: string }) => {
const batch = await api.getSimulationBatch(client, params.batchId);
return {
batch,
next: {
getRecords: "seal-use simulation batch-records <batchId>"
}
};
}
},
{
name: "seal_simulation_batch_status",
description: "单次读取 Seal 模拟批次状态,不阻塞等待;适合根据异步票据轮询",
parameters: z.object({
batchId: z.string().describe("simulation batch ID")
}),
handler: async (client: KyInstance, params: { batchId: string }) => {
const batch = await api.getSimulationBatch(client, params.batchId);
const status = String(batch.status ?? "UNKNOWN").toUpperCase();
const terminal = ["COMPLETED", "FAILED", "CANCELLED", "CANCELED"].includes(status);
return {
batchId: params.batchId,
status,
terminal,
totalCount: batch.totalCount,
processedCount: batch.processedCount,
successCount: batch.successCount,
failedCount: batch.failedCount,
createdAt: batch.createdAt,
updatedAt: batch.updatedAt,
next: terminal
? { getRecords: `seal-use simulation batch-records ${params.batchId}` }
: { status: `seal-use simulation status ${params.batchId}`, wait: `seal-use simulation wait ${params.batchId}` }
};
}
},
{
name: "seal_simulation_templates_get",
description: "列出 Seal 模拟测试模板(我的模板,保存常用配置快速复用)",
parameters: z.object({}),
handler: async (client: KyInstance) => {
const templates = await api.listSimulationTemplates(client);
return {
count: templates.length,
templates: templates.map((template) => ({
id: template.id,
name: template.name,
description: template.description,
approvalSystem: template.approvalSystem,
hosecloudConfig: template.hosecloudConfig,
updatedAt: template.updatedAt
})),
next: {
createBatch: "seal-use simulation create --mode hosecloud --flow-ids ..."
}
};
}
},
{
name: "seal_simulation_integrations_get",
description: "查询模拟测试可用的来源集成状态与合思集成选项(signKey 等)",
parameters: z.object({}),
handler: async (client: KyInstance) => {
const [status, hosecloudIntegrations] = await Promise.all([
api.getSimulationIntegrationStatus(client),
api.listSimulationHosecloudIntegrations(client)
]);
return { status, hosecloudIntegrations };
}
},
{
name: "seal_simulation_material_package_upload",
description: "上传材料包 ZIP 到 Seal 模拟测试;服务端解析 Excel/AI 推断配置并返回材料包 id 与 schemaConfig(字段映射确认后用于创建模拟批次)",
parameters: z.object({
filePath: z.string().describe("材料包 ZIP 文件路径(含 信息表.xlsx 与附件)")
}),
handler: async (client: KyInstance, params: { filePath?: string }) => {
if (!params.filePath) {
throw new Error("filePath is required");
}
const fileBuffer = readFileSync(params.filePath);
const fileName = params.filePath.split(/[\\/]/).pop() ?? "material-pack.zip";
const materialPackage = await api.uploadMaterialPackage(client, {
fileName,
fileBuffer
});
return {
materialPackage,
next: {
createBatch: `seal-use simulation create --mode material_pack --package-ids ${materialPackage.id} --schema-config schema.json`
}
};
}
},
{
name: "seal_simulation_batch_wait",
description: "等待 Seal 模拟测试批次完成(轮询状态直到 completed/failed/canceled 或超时)",
parameters: z.object({
batchId: z.string().describe("模拟批次 ID"),
timeout: z.string().default("10m").describe("最长等待时间, 默认 10m"),
pollInterval: z.string().default("2s").describe("轮询间隔, 默认 2s")
}),
handler: async (client: KyInstance, params: { batchId: string; timeout?: string; pollInterval?: string }) => {
const timeoutMs = parseDurationMs(params.timeout ?? "10m");
const pollIntervalMs = parseDurationMs(params.pollInterval ?? "2s");
const startedAt = Date.now();
while (true) {
const batch = await api.getSimulationBatch(client, params.batchId);
const status = (batch.status ?? "").toLowerCase();
if (["completed", "failed", "cancelled", "canceled"].includes(status)) {
return {
batch,
completed: true,
status,
elapsedMs: Date.now() - startedAt,
next: {
getRecords: `seal-use simulation batch-records ${params.batchId}`
}
};
}
if (Date.now() - startedAt >= timeoutMs) {
throw new Error(`等待模拟批次 ${params.batchId} 超时(已等待 ${(Date.now() - startedAt) / 1000}s)。可稍后执行 seal-use simulation get ${params.batchId} 查看状态`);
}
await new Promise((resolve) => setTimeout(resolve, pollIntervalMs));
}
}
},
{
name: "seal_simulation_batch_clean",
description: "删除模拟测试批次产生的测试数据",
parameters: z.object({
batchId: z.string().describe("模拟批次 ID")
}),
handler: async (client: KyInstance, params: { batchId: string }) => {
const result = await api.cleanSimulationBatch(client, params.batchId);
return {
batchId: params.batchId,
cleaned: true,
result
};
}
},
{
name: "seal_simulation_specifications_list",
description: "列出指定合思集成可用的单据模板列表",
parameters: z.object({
signKey: z.string().optional().describe("合思集成 sign-key")
}),
handler: async (client: KyInstance, params: { signKey?: string }) => {
const specifications = await api.listSimulationSpecifications(client, params.signKey);
return {
count: specifications.length,
specifications
};
}
}
];
+459
View File
@@ -0,0 +1,459 @@
import { z } from "zod";
import type { KyInstance } from "ky";
import { readFileSync } from "node:fs";
import { randomBytes } from "node:crypto";
import * as api from "../api.js";
import { defaultSealUrl, ensureHoseCloseApiToken, getHoseProvisionalAuthLink, probeHoseDomain } from "../../../core/auth/hose.js";
import type { CorpConfig } from "../../../core/config/types.js";
import { loadGlobalConfig, loadCorpConfigs, getEnterprisesDirCandidates } from "../../../core/config/loader.js";
import { resolveCorpConfig } from "../../../core/config/manager.js";
import { createSealClient, createSealClientForToken } from "../../../core/http/factory.js";
import { resolveSealCustomHeaders } from "../../../core/http/request-headers.js";
import { searchApprovalContent } from "../search.js";
import { diffRuleVersions, normalizedRuleCode, truncateRuleDiff } from "../rule-diff.js";
import { hydrateRuleVersionStableIds, savePublishedRuleVersionSnapshot } from "../rule-version-snapshot.js";
import { executeApprovalRunsReplay, resolveReplayCorpPair } from "../webhook-replay.js";
import { loadRuleLinter, lintRuleBatch, lintSingleRule, type RuleLintTarget } from "../linter/index.js";
import {
loadLocalRulesFile,
saveLocalRulesFile,
localRulesToLintTargets,
type LocalRuleItem
} from "../rules-local.js";
import {
checkWebhookReadiness,
previewMaterialPack,
pushMaterialPack,
readMaterialPackFile
} from "../material-pack/index.js";
import { MaterialPackFilePolicyPatchSchema, MaterialPackFilePolicySchema } from "../material-pack/policy.js";
import { extractApprovalRunAttachments } from "../attachments.js";
import { exportApprovalRunsToExcel, normalizeTimestamp } from "../approval-runs-export.js";
import {
alignApprovalRunsWithHoseFlow,
createHoseOpenClient,
getHoseOpenFlow
} from "../../hose/index.js";
import { exportInsightReportToExcel, type InsightExportOptions } from "../insight-export.js";
import {
ThinkingPolicySchema,
type ApprovalRule,
type ApprovalRun,
type RuleSetVersion,
type SimulationBatch,
type WebhookIntegration,
type WebhookMode,
type ThinkingPolicy,
type DecisionPreferences,
type HosecloudConfigInput
} from "../types.js";
import type {
ToolContext,
SealToolDefinition,
ApprovalRunSummary,
ApprovalRunsSummaryOptions,
RuleField,
RulePushPlan,
SimulationBatchCreateInput,
HumanResultMatch
} from "./helpers.js";
import * as helpers from "./helpers.js";
const {
presentWebhookIntegration,
getConfiguredSealBaseUrl,
projectApprovalRules,
pickRuleFields,
buildRulePushPlan,
rulesHaveSameContent,
ruleChangedFields,
normalizeRuleStrictness,
parseDurationMs,
redactIntegrationSecrets,
mutationPreview,
redactPreviewValue,
buildSimulationBatchParams,
summarizeSimulationBatch,
summarizeApprovalRun,
summarizeApprovalRuns,
parseFieldPaths,
pickRunFields,
approvalRunMetadata,
summarizeApprovalRunDetail,
summarizeApprovalRunResult,
summarizeApprovalRunDocument,
extractCitedRules,
firstPath,
countPathCandidates,
getPath,
setPath,
compactObject,
asRecord,
numberFromUnknown,
flattenDocumentFields,
collectDocumentFields,
firstByLabel,
collectInvoiceSummary,
collectInvoiceObjects,
findKeywordLines,
summarizeRunBridge,
summarizeRuleVersion,
resolveRuleVersionForLookup,
findRuleInVersion,
normalizeRuleCode,
runtimeRuleIndex,
runtimeRuleIdToCode,
formatRuleCode,
pickApprovalRunCandidate,
resolveApprovalRunForUrl,
resolveSealBaseUrl,
normalizeUrl,
stringFromUnknown,
pickApprovalRuns,
timestampOf,
resolveRuleVersion,
resolveRuleVersionSelector,
filterRuns,
scalarIncludes,
objectContainsScalar,
filterRunsByHumanResult,
withApprovalRunFilters,
resolveManualApprovalStatus,
prepareApprovalRuns,
approvalRunAliases,
extractHumanResult,
findHumanResultValue,
isHumanResultKey,
stringifyHumanResultValue,
matchesRunLookup,
countBy,
localDateKey,
formatLocalDateTime,
toDate,
localParts
} = helpers;
export const webhookTools = [
{
name: "seal_webhook_list",
description: "列出当前 Seal 租户的 Webhook 集成,可按 ID、名称或 URL 查找",
parameters: z.object({
query: z.string().optional().describe("按集成 ID、名称或 URL 做本地包含匹配"),
includeSecret: z.boolean().optional().describe("是否返回 Webhook secret;默认遮罩")
}),
handler: async (
client: KyInstance,
params: { query?: string; includeSecret?: boolean },
context: ToolContext
) => {
const integrations = api.filterWebhookIntegrations(
await api.listWebhookIntegrations(
client,
context.corp.seal.endpoints.approvalStylePreferences
),
params.query
);
return {
count: integrations.length,
integrations: integrations.map((integration) => presentWebhookIntegration(integration, params.includeSecret === true))
};
}
},
{
name: "seal_webhook_get",
description: "按 Webhook 集成 ID 或名称精确查找一条集成",
parameters: z.object({
selector: z.string().min(1).describe("Webhook 集成 ID 或名称"),
includeSecret: z.boolean().optional().describe("是否返回 Webhook secret;默认遮罩")
}),
handler: async (
client: KyInstance,
params: { selector: string; includeSecret?: boolean },
context: ToolContext
) => {
const integration = api.findWebhookIntegration(
await api.listWebhookIntegrations(
client,
context.corp.seal.endpoints.approvalStylePreferences
),
params.selector
);
return presentWebhookIntegration(integration, params.includeSecret === true);
}
},
{
name: "seal_webhook_add",
description: "新增 Webhook 集成;使用 dryRun=true 可只预览请求而不持久化",
parameters: z.object({
name: z.string().min(1).describe("集成名称"),
mode: z.enum(["assisted", "semi_automatic", "fully_automatic"]).optional(),
outgoingResultWebhook: z.string().url().describe("Seal 完成 AI 审核后回调的外部地址"),
autoApprovalRate: z.number().int().min(0).max(100).optional(),
secret: z.string().min(1).optional().describe("可选;不传则生成 32 位十六进制 secret"),
materialPackFilePolicy: MaterialPackFilePolicyPatchSchema.describe("材料包附件文件策略:大小和后缀白名单"),
dryRun: z.boolean().optional().describe("只返回前后配置 Diff,不执行写入")
}),
handler: async (
client: KyInstance,
params: {
name: string;
mode?: WebhookMode;
outgoingResultWebhook: string;
autoApprovalRate?: number;
secret?: string;
materialPackFilePolicy?: Partial<z.infer<typeof MaterialPackFilePolicySchema>>;
dryRun?: boolean;
},
context: ToolContext
) => {
const baseUrl = getConfiguredSealBaseUrl(context.corp);
const preview = params.dryRun
? await api.previewAddWebhookIntegration(client, baseUrl, params, context.corp.seal.endpoints.approvalStylePreferences)
: undefined;
const integration = preview?.integration ?? await api.addWebhookIntegration(
client,
baseUrl,
params,
context.corp.seal.endpoints.approvalStylePreferences
);
if (params.dryRun) {
return mutationPreview(
context,
context.corp.seal.endpoints.approvalStylePreferences,
preview!.before,
preview!.after,
1
);
}
return {
saved: true,
integration: presentWebhookIntegration(integration, true)
};
}
},
{
name: "seal_webhook_update",
description: "更新现有 Webhook 集成;使用 dryRun=true 可只预览请求而不持久化",
parameters: z.object({
selector: z.string().min(1).describe("Webhook 集成 ID 或名称"),
name: z.string().min(1).optional(),
mode: z.enum(["assisted", "semi_automatic", "fully_automatic"]).optional(),
outgoingResultWebhook: z.string().url().optional(),
autoApprovalRate: z.number().int().min(0).max(100).optional(),
secret: z.string().min(1).optional(),
rotateSecret: z.boolean().optional().describe("生成新 secret;与 secret 二选一"),
materialPackFilePolicy: MaterialPackFilePolicyPatchSchema.describe("材料包附件文件策略:大小和后缀白名单"),
dryRun: z.boolean().optional().describe("只返回前后配置 Diff,不执行写入")
}),
handler: async (
client: KyInstance,
params: {
selector: string;
name?: string;
mode?: WebhookMode;
outgoingResultWebhook?: string;
autoApprovalRate?: number;
secret?: string;
rotateSecret?: boolean;
materialPackFilePolicy?: Partial<z.infer<typeof MaterialPackFilePolicySchema>>;
dryRun?: boolean;
},
context: ToolContext
) => {
if (params.secret !== undefined && params.rotateSecret) {
throw new Error("Webhook secret and rotateSecret cannot be used together");
}
const preview = params.dryRun
? await api.previewUpdateWebhookIntegration(client, params.selector, params, context.corp.seal.endpoints.approvalStylePreferences)
: undefined;
const integration = preview?.integration ?? await api.updateWebhookIntegration(
client,
params.selector,
params,
context.corp.seal.endpoints.approvalStylePreferences
);
if (params.dryRun) {
return mutationPreview(
context,
context.corp.seal.endpoints.approvalStylePreferences,
preview!.before,
preview!.after,
1
);
}
return {
saved: true,
integration: presentWebhookIntegration(
integration,
params.secret !== undefined || params.rotateSecret === true
)
};
}
},
{
name: "seal_webhook_delete",
description: "删除指定 Webhook 集成;使用 dryRun=true 可只预览请求而不持久化",
parameters: z.object({
selector: z.string().min(1).describe("Webhook 集成 ID 或名称"),
confirm: z.boolean().optional().describe("执行删除时必须明确传 true;dryRun 可省略"),
dryRun: z.boolean().optional().describe("只返回前后配置 Diff,不执行删除")
}),
handler: async (
client: KyInstance,
params: { selector: string; confirm?: boolean; dryRun?: boolean },
context: ToolContext
) => {
if (!params.confirm && !params.dryRun) {
throw new Error("Refusing to delete Webhook integration without confirm=true");
}
const preview = params.dryRun
? await api.previewDeleteWebhookIntegration(client, params.selector, context.corp.seal.endpoints.approvalStylePreferences)
: undefined;
const integration = preview?.integration ?? await api.deleteWebhookIntegration(
client,
params.selector,
context.corp.seal.endpoints.approvalStylePreferences
);
if (params.dryRun) {
return mutationPreview(
context,
context.corp.seal.endpoints.approvalStylePreferences,
preview!.before,
preview!.after,
1
);
}
return {
deleted: true,
integration: presentWebhookIntegration(integration, false)
};
}
},
{
name: "seal_webhook_replay",
description: "将正式(生产)企业或指定企业的审批记录通过 Webhook 渠道重放到测试企业进行规则回归与模拟验证",
parameters: z.object({
recordId: z.string().optional().describe("待重放的单条审批记录 ID"),
sn: z.string().optional().describe("待重放的单据编号 (sourceDocumentSN)"),
sourceCorpId: z.string().optional().describe("单据来源企业 ID (若省略,基于绑定关系自动解析为正式企业)"),
targetCorpId: z.string().optional().describe("重放目标企业 ID (若省略,基于绑定关系自动解析为测试企业)"),
webhook: z.string().optional().describe("目标 Webhook 通道 ID 或名称"),
limit: z.number().optional().describe("批量重放单据数量 (默认 1)"),
status: z.string().optional().describe("单据状态过滤 (例如 completed, failed 等)"),
snPrefix: z.string().optional().describe("重放单号前缀"),
snSuffix: z.string().optional().describe("重放单号后缀"),
dryRun: z.boolean().optional().describe("是否仅执行预检转换而不实际推送 (默认 false)"),
force: z.boolean().optional().describe("若目标为生产环境,强制执行重放")
}),
handler: async (
client: KyInstance,
params: {
recordId?: string;
sn?: string;
sourceCorpId?: string;
targetCorpId?: string;
webhook?: string;
limit?: number;
status?: string;
snPrefix?: string;
snSuffix?: string;
dryRun?: boolean;
force?: boolean;
},
context: ToolContext
) => {
const selectCorpFn = (id?: string) => {
const corps = loadCorpConfigs();
const globalConfig = loadGlobalConfig();
return resolveCorpConfig(
corps,
{
stateful: globalConfig.stateful,
defaultCorpId: globalConfig.defaultCorpId,
corpId: id
},
getEnterprisesDirCandidates()
);
};
const { sourceCorp, targetCorp } = resolveReplayCorpPair(
{
sourceCorpId: params.sourceCorpId,
targetCorpId: params.targetCorpId,
activeCorp: context.corp,
force: params.force
},
selectCorpFn
);
const sourceClient = sourceCorp.id === context.corp.id ? client : await createSealClient(sourceCorp);
const targetClient = targetCorp.id === context.corp.id ? client : await createSealClient(targetCorp);
return executeApprovalRunsReplay({
query: {
recordId: params.recordId,
sn: params.sn,
limit: params.limit,
status: params.status
},
sourceClient,
targetClient,
sourceCorp,
targetCorp,
webhookSelector: params.webhook,
snPrefix: params.snPrefix,
snSuffix: params.snSuffix,
dryRun: params.dryRun
});
}
},
{
name: "seal_webhook_ready",
description: "检查当前企业的 Webhook 就绪状态看板(包括企业环境、租户身份、凭证连通性、已激活 Webhook 通道及材料包预检)",
parameters: z.object({
filePath: z.string().optional().describe("可选的材料包路径(ZIP 或 信息表.xlsx),用于同步做本地预检")
}),
handler: async (
client: KyInstance,
params: { filePath?: string },
context: ToolContext
) => {
return checkWebhookReadiness(client, context.corp, { filePath: params.filePath });
}
},
{
name: "seal_webhook_material_pack",
description: "将官方材料包格式本地校验、解析并通过 Seal 入站 Webhook 触发 AI 审批;preview 模式不联网,push 模式单通道自动选择",
parameters: z.object({
filePath: z.string().describe("材料包 ZIP 或 信息表.xlsx 文件路径"),
mode: z.enum(["preview", "push"]).default("preview"),
webhook: z.string().optional().describe("Webhook ID 或名称;当租户仅配置 1 个通道时可省略")
}),
handler: async (
client: KyInstance,
params: { filePath: string; mode?: "preview" | "push"; webhook?: string },
context: ToolContext
) => {
const input = readMaterialPackFile(params.filePath);
if (params.mode !== "push") return previewMaterialPack(input.fileBuffer, input.fileName);
const integrations = await api.listWebhookIntegrations(client);
let integration: WebhookIntegration;
if (params.webhook) {
integration = api.findWebhookIntegration(integrations, params.webhook);
} else if (integrations.length === 1) {
integration = integrations[0]!;
} else if (integrations.length > 1) {
const options = integrations.map((i) => `"${i.name}" (${i.id})`).join(", ");
throw new Error(`当前租户存在多个 Webhook 通道 [${options}],请通过 webhook 参数指定目标通道。`);
} else {
throw new Error("当前租户未配置任何 Webhook 集成通道。");
}
return pushMaterialPack(input.fileBuffer, input.fileName, {
webhookUrl: integration.incomingDocumentWebhook.url,
secret: integration.secret,
materialPackFilePolicy: integration.materialPackFilePolicy,
customHeaders: resolveSealCustomHeaders(context.corp.seal)
});
}
}
];
+1 -1
View File
@@ -2,7 +2,7 @@ import type { KyInstance } from "ky";
import type { ApprovalRun, WebhookIntegration } from "./types.js";
import type { MaterialField } from "./material-pack/types.js";
import { webhookHeaders } from "./material-pack/signature.js";
import { CliError } from "../../cli/errors.js";
import { CliError } from "../../core/errors.js";
import type { CorpConfig } from "../../core/config/types.js";
import { resolveSealCustomHeaders } from "../../core/http/request-headers.js";
import * as api from "./api.js";