@isdk/ai-tool 0.0.7 → 0.0.8

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (82) hide show
  1. package/dist/chunk-B7IE5ATQ.mjs +1 -0
  2. package/dist/funcs.d.mts +1 -1
  3. package/dist/funcs.d.ts +1 -1
  4. package/dist/funcs.js +1 -1
  5. package/dist/funcs.mjs +1 -1
  6. package/dist/{index-japi6bEq.d.mts → index-Dgo3ZXPQ.d.mts} +28 -2
  7. package/dist/{index-japi6bEq.d.ts → index-Dgo3ZXPQ.d.ts} +28 -2
  8. package/dist/index.d.mts +361 -52
  9. package/dist/index.d.ts +361 -52
  10. package/dist/index.js +1 -1
  11. package/dist/index.mjs +1 -1
  12. package/docs/classes/AbortError.md +8 -8
  13. package/docs/classes/AlreadyExistsError.md +8 -8
  14. package/docs/classes/BaseError.md +8 -8
  15. package/docs/classes/CancelableAbility.md +431 -0
  16. package/docs/classes/ClientTools.md +101 -51
  17. package/docs/classes/CommonError.md +8 -8
  18. package/docs/classes/EventClient.md +123 -73
  19. package/docs/classes/EventServer.md +121 -71
  20. package/docs/classes/EventToolFunc.md +91 -41
  21. package/docs/classes/FStringPromptTemplate.md +18 -18
  22. package/docs/classes/FewShotPromptTemplate.md +22 -22
  23. package/docs/classes/GolangPromptTemplate.md +18 -18
  24. package/docs/classes/HFEnvironment.md +9 -9
  25. package/docs/classes/HFInterpreter.md +17 -17
  26. package/docs/classes/HFTemplate.md +4 -4
  27. package/docs/classes/HfPromptTemplate.md +18 -18
  28. package/docs/classes/IntSet.md +249 -0
  29. package/docs/classes/NotFoundError.md +8 -8
  30. package/docs/classes/NotImplementationError.md +8 -8
  31. package/docs/classes/PromptExampleSelector.md +8 -8
  32. package/docs/classes/PromptTemplate.md +17 -17
  33. package/docs/classes/ReadableStreamError.md +8 -8
  34. package/docs/classes/ResClientTools.md +107 -57
  35. package/docs/classes/ResServerTools.md +105 -55
  36. package/docs/classes/SSEChannel.md +15 -15
  37. package/docs/classes/Semaphore.md +273 -0
  38. package/docs/classes/ServerTools.md +98 -48
  39. package/docs/classes/TaskAbortController.md +157 -0
  40. package/docs/classes/ToolFunc.md +80 -38
  41. package/docs/enums/AsyncFeatureBits.md +41 -0
  42. package/docs/enums/AsyncFeatures.md +41 -0
  43. package/docs/enums/ErrorCode.md +41 -19
  44. package/docs/enums/XXHashAlgorithm.md +2 -2
  45. package/docs/interfaces/AIChatAssistantMessageParam.md +6 -6
  46. package/docs/interfaces/AIChatContentPartImage.md +2 -2
  47. package/docs/interfaces/AIChatContentPartText.md +2 -2
  48. package/docs/interfaces/AIChatMessageParamBase.md +1 -1
  49. package/docs/interfaces/AIChatMessageToolCall.md +3 -3
  50. package/docs/interfaces/AIChatSystemMessageParam.md +3 -3
  51. package/docs/interfaces/AIChatToolMessageParam.md +4 -4
  52. package/docs/interfaces/AIChatUserMessageParam.md +7 -7
  53. package/docs/interfaces/AIResult.md +16 -5
  54. package/docs/interfaces/AIStreamParser.md +1 -1
  55. package/docs/interfaces/AIStreamParserOptions.md +1 -1
  56. package/docs/interfaces/BaseFunc.md +7 -7
  57. package/docs/interfaces/BaseFuncItem.md +6 -6
  58. package/docs/interfaces/CancelableAbilityOptions.md +126 -0
  59. package/docs/interfaces/ClientFuncItem.md +10 -10
  60. package/docs/interfaces/DotenvExpandOptions.md +3 -3
  61. package/docs/interfaces/DotenvExpandOutput.md +2 -2
  62. package/docs/interfaces/EventClientFuncParams.md +4 -4
  63. package/docs/interfaces/EventServerFuncParams.md +5 -5
  64. package/docs/interfaces/FewShotPromptTemplateOptions.md +11 -11
  65. package/docs/interfaces/FuncItem.md +7 -7
  66. package/docs/interfaces/FuncParam.md +16 -5
  67. package/docs/interfaces/PromptExampleSelectorOptions.md +2 -2
  68. package/docs/interfaces/PromptTemplateOptions.md +6 -6
  69. package/docs/interfaces/RemoteFuncItem.md +10 -10
  70. package/docs/interfaces/ResClientFuncParams.md +2 -2
  71. package/docs/interfaces/ResServerFuncParams.md +5 -5
  72. package/docs/interfaces/SanitizeFilenameOptions.md +2 -2
  73. package/docs/interfaces/ServerFuncItem.md +11 -11
  74. package/docs/interfaces/ServerFuncParams.md +2 -2
  75. package/docs/interfaces/StreamCallbacksAndOptions.md +124 -0
  76. package/docs/interfaces/TaskAbortControllers.md +7 -0
  77. package/docs/interfaces/TaskPromise.md +151 -0
  78. package/docs/interfaces/ToolFuncPackage.md +63 -0
  79. package/docs/modules.md +1124 -120
  80. package/package.json +3 -2
  81. package/dist/chunk-PYM7DCYB.mjs +0 -1
  82. package/docs/interfaces/AIStreamCallbacksAndOptions.md +0 -158
@@ -0,0 +1 @@
1
+ import{__export as t,__reExport as e}from"./chunk-U5DDQYSF.mjs";import{EventEmitter as r}from"events-ex";import{AdvancePropertyManager as n}from"property-manager";import{_createFunction as s}from"util-ex";import{AbstractError as i,createErrorClass as o}from"abstract-error";var a=(t=>(t[t.OK=200]="OK",t[t.Accepted=202]="Accepted",t[t.BadRequest=400]="BadRequest",t[t.InvalidArgument=400]="InvalidArgument",t[t.Unauthorized=401]="Unauthorized",t[t.PaymentRequired=402]="PaymentRequired",t[t.Forbidden=403]="Forbidden",t[t.NotFound=404]="NotFound",t[t.MethodNotAllowed=405]="MethodNotAllowed",t[t.NotAcceptable=406]="NotAcceptable",t[t.RequestTimeout=408]="RequestTimeout",t[t.Conflict=409]="Conflict",t[t.Corruption=409]="Corruption",t[t.TooManyRequests=429]="TooManyRequests",t[t.Aborted=499]="Aborted",t[t.InternalError=500]="InternalError",t[t.NotImplemented=501]="NotImplemented",t[t.NotSupported=501]="NotSupported",t[t.BadGateway=502]="BadGateway",t[t.ServiceUnavailable=503]="ServiceUnavailable",t[t.GatewayTimeout=504]="GatewayTimeout",t))(a||{}),c=500,u=501,h=404,l=409,f=499,p=class t extends i{static createErrorClass(e,r,n=t){return o(e,r,n)}constructor(t,e,r){super(t,e);const n=this.constructor;null!=e?this.code=e:n.code?this.code=n.code:this.code=n.name,r?"string"==typeof r?this.name=r:Object.assign(this,r):"string"==typeof this.code?this.name=this.code:this.name=n.name}toJSON(){const t={name:this.name,code:this.code,data:this.data,caller:this.caller,error:this.message,stack:this.stack};return Object.keys(t).forEach((e=>void 0===t[e]&&delete t[e])),t}fromJSON(e){const r=new t(e.message);return r.code=e.code,r.data=e.data,r.caller=e.caller,r.message=e.error,r.stack=e.stack,r}},w=class extends p{constructor(t,e,r=c){super(t,r,e)}},d=class extends w{constructor(t,e){t||(t="Not Implementation."),super(t,e,501)}};w[501]=d;var m=class extends w{static{this.code=h}constructor(t,e){super(`Could not find ${t}.`,e,h),this.data={what:t}}};w[404]=m;var y=class extends w{static{this.code=l}constructor(t,e){super(`The ${t} already exists.`,e,l),this.data={what:t}}};w[409]=y;var b=class extends w{static{this.code=f}constructor(t,e){e||(e="AbortError"),super(t?`The operation was aborted for ${t}.`:"The operation was aborted.",e,f),t&&(this.data={what:t})}};function g(t,e,r=c){const n=new(w[r]||w)(t,e,r);return"number"!=typeof n.code&&(n.code=r),n}function x(t,e,r=c){throw g(t,e,r)}w[499]=b;var v={};t(v,{AIChatRoles:()=>U,AIMessageTypes:()=>B,AIStream:()=>Be,AITextGenerationFinishReasons:()=>P,AbortError:()=>b,AbortErrorCode:()=>f,ActionNames:()=>$,AlreadyExistsError:()=>y,AlreadyExistsErrorCode:()=>l,BaseError:()=>p,CancelableAbility:()=>In,CommonError:()=>w,ConfigFile:()=>Zr,DefaultAsyncSemaphoreCapacity:()=>En,ErrorCode:()=>a,EventBusName:()=>Se,EventName:()=>Ee,FStringPromptTemplate:()=>te,FewShotPromptTemplate:()=>ie,FilenameReservedRegex:()=>mr,GolangPromptTemplate:()=>ne,HFBuiltins:()=>zt,HFEnvironment:()=>Dt,HFInterpreter:()=>Vt,HFTemplate:()=>Jt,HfPromptTemplate:()=>Kt,IntSet:()=>xn,InternalErrorCode:()=>c,NotFoundError:()=>m,NotFoundErrorCode:()=>h,NotImplementationError:()=>d,NotImplementedErrorCode:()=>501,PASSING_SCORE:()=>S,PromptExampleSelector:()=>H,PromptTemplate:()=>D,PromptTemplateTypes:()=>_,PromptTypes:()=>L,RStreamErrCode:()=>Ce,RateLimit:()=>Cn,ReadableStreamError:()=>Ne,RemoteToolFuncSchema:()=>k,ResponseRStreamErrCode:()=>je,SSEChannel:()=>Te,SSEChannelAlreadyClosedErrCode:()=>Ae,Semaphore:()=>On,TaskAbortController:()=>Fn,WindowsReservedNameRegex:()=>yr,XXHashAlgorithm:()=>fr,backendEventable:()=>$e,base32768:()=>or,createAbilityInjector:()=>E,createCallbacksTransformer:()=>Ve,createEmptyReadableStream:()=>Ie,createEndWithRepetitionDetector:()=>Ur,createError:()=>g,createEventStreamTransformer:()=>Re,createHfValueFunc:()=>Xt,dateToText:()=>R,defaultTemplateFormat:()=>z,expandEnv:()=>ue,expandObjEnv:()=>he,extNameLevel:()=>Cr,filenameReservedRegex:()=>Er,formatISO:()=>C,getAllEnumKeys:()=>Ir,getConfigFileNames:()=>cn,getConfigs:()=>un,getKeysPath:()=>Pr,getMultiLevelExtname:()=>Or,getRealFilepath:()=>Jr,getResponseErrorReadableStream:()=>Fe,hfParse:()=>$t,hfTokenize:()=>et,interpolateEnv:()=>ce,interpolateFString:()=>Zt,interpolateGolangTemplate:()=>re,isModelNameMatched:()=>Fr,isValidFilename:()=>$r,isValidFilepath:()=>kr,isWebStream:()=>Oe,jsonFilterToWhere:()=>dn,jsonToMarkdownStr:()=>gn,loadFileFromPaths:()=>_r,loadTextFromPaths:()=>zr,makeToolFuncCancelable:()=>Rn,matchUrlProtocol:()=>mn,messagesToText:()=>V,mimeType:()=>rn,paramsSizeToScaleStr:()=>yn,parseDateFormat:()=>T,parseFString:()=>Yt,parseISO:()=>j,parseJsJson:()=>Rr,parseYaml:()=>an,reControlCharsRegex:()=>Sr,readFilenamesRecursiveSync:()=>Dr,readableFromAsyncIterable:()=>Ue,registerYamlTag:()=>on,sanitizeFilename:()=>Ar,sanitizeFilepath:()=>Tr,saveConfigFile:()=>hn,scaleStrToParamsSize:()=>bn,sortedValues:()=>se,splitSentence:()=>be,stringifyYaml:()=>nn,textToDate:()=>M,throwError:()=>x,toDate:()=>N,toDateTime:()=>I,trimStartOfStreamHelper:()=>Pe,truncTo:()=>ge,uuid:()=>tr,uuidNIL:()=>Ze,uuidParse:()=>Ke,uuidStringify:()=>Ge,uuidValidate:()=>Xe,uuidVersion:()=>Ye,uuidv1:()=>Je,uuidv4:()=>We,uuidv5:()=>He,wait:()=>xe,xxhash:()=>pr,xxhash32:()=>hr,xxhash64:()=>lr,xxhashAsStr:()=>wr});import{createAbilityInjector as E}from"custom-ability";var S=.618,$=["get","post","put","delete","patch","list","res"],k={apiRoot:{type:"string",get(){return this._apiRoot??this.constructor.apiRoot},set(t){this._apiRoot=t}},action:{type:"string",assign:(t,e,r,n,s)=>t||"post"},fetchOptions:{type:"object"},allowExportFunc:{type:"boolean"},stream:{type:"boolean"}};import{format as A,parse as T,parseISO as O}from"date-fns";import{formatISO as C,parseISO as j,toDate as N}from"date-fns";var F="MMMM d, y 'at' h:m:s b 'GMT'x";function I(t){let e;try{"string"==typeof t?e=O(t):"number"==typeof t?e=new Date(t):t instanceof Date&&(e=t)}catch(t){console.error(t)}return e}function M(t,e=F){return T(t,e,new Date)}function R(t,e=F){return A(t,e)}var P=["stop","length","content-filter","tool-calls","abort","error","other",null],B=["human","ai","generic","system","tool"],U=["user","assistant","system","tool","tool_calls"];function V(t){let e="";for(const r of t)if(r.content){e+=r.role.toLowerCase()+":";let t=r.createdAt;if(t){const r=I(t);r&&(e+=" ["+R(r)+"]")}e+=" "+r.content+"\n"}return e}var L=["chat","char","plan"],_=["internal","hf","fill"];import{BaseFactory as q}from"custom-factory";var z="default",D=class t extends q{static from(t,e){return new this(t,e)}static async format(t){return new this(t).format()}static async formatIf(t){if(this.isTemplate(t)){return new this(t).format()}}static isTemplate(e){if(e?.template){const r=e.templateFormat||z,n=t.get(r);return n.isTemplate!==t.isTemplate&&n.isTemplate(e)}}filterData(t){return Array.isArray(this.inputVariables)&&(t=Object.fromEntries(Object.entries(t).filter((([t])=>this.inputVariables.includes(t))))),t}constructor(e,r){"string"==typeof e?(r||(r={}),r.template=e):e&&(e=(r=e).template);const{templateFormat:n}=r||{};if(super(r),this.constructor===t){const e=t.get(n||z);if(e)return Reflect.construct(e,arguments);throw new w(`Prompt template type ${n} not found`,"PromptTemplate",400)}}_initialize(t){throw new d("Not implemented","PromptTemplate")}initialize(e){this.constructor!==t&&(Object.assign(this,this.toJSON(e)),e?.ignoreInitialize||this._initialize(e))}_format(t){throw new d("Not implemented","PromptTemplate")}async format(e){const r=this.data;if(e={...r,...e},r)for(const[t,n]of Object.entries(r))e[t]===n&&"function"==typeof n&&(delete e[t],e[t]=await n(e));for(const[r,n]of Object.entries(e))n instanceof t&&(delete e[r],e[r]=await n.format(e));return this._format(e)}partial(t){t={...this.data,...t};const e=this.toJSON();return e.data=t,e.ignoreInitialize=!0,new this.constructor(e)}toJSON(e=this){let r={template:e.template,data:e.data,inputVariables:e.inputVariables,compiledTemplate:e.compiledTemplate};var n;return e.templateFormat&&t.get(e.templateFormat)!==this.constructor&&(r.templateFormat=e.templateFormat),n=r,r=Object.keys(n).reduce(((t,e)=>{const r=n[e];return null!=r&&(t[e]=r),t}),{}),r}};function J(t){return(e=t)&&"function"==typeof e[Symbol.iterator]?async function*(t){const e=t[Symbol.iterator]();let r;try{for(;;){r=!1;const t=e.next();if(r=!0,t.done)return r=!1,await t.value;yield await t.value}}finally{r&&await(e.return?.().value)}}(t):t;var e}var W=!1;(async function(){let t=!1,e=!1;try{for await(const e of function*(){try{yield Promise.reject()}finally{t=!0}}())throw new Error("impossible")}catch{e=!0}return e&&t})().then((t=>{W=t}));var H=class{constructor(t,e){this.initialize(t,e)}initialize(t,e){const r=e?.maxLength;var n;r>0&&(this.maxLength=r),void 0!==e?.threshold&&(!0===e.threshold?this.threshold=.5:!1!==e.threshold&&(this.threshold=e.threshold)),this.examples=(n=t,W?n:J(n))}selectExample(t,e){if(void 0===e||e<=this.threshold)return t}async*selectExamples(t=this.examples){let e=this.maxLength||1/0;for await(const r of t){const t="number"==typeof this.threshold?Math.random():void 0;if(this.selectExample(r,t)){if(--e<0)break;yield r}}}async*[Symbol.asyncIterator](){yield*this.selectExamples()}},G=Object.freeze({Text:"Text",NumericLiteral:"NumericLiteral",BooleanLiteral:"BooleanLiteral",StringLiteral:"StringLiteral",Identifier:"Identifier",Equals:"Equals",OpenParen:"OpenParen",CloseParen:"CloseParen",OpenStatement:"OpenStatement",CloseStatement:"CloseStatement",OpenExpression:"OpenExpression",CloseExpression:"CloseExpression",OpenSquareBracket:"OpenSquareBracket",CloseSquareBracket:"CloseSquareBracket",OpenCurlyBracket:"OpenCurlyBracket",CloseCurlyBracket:"CloseCurlyBracket",Comma:"Comma",Dot:"Dot",Colon:"Colon",Pipe:"Pipe",CallOperator:"CallOperator",AdditiveBinaryOperator:"AdditiveBinaryOperator",MultiplicativeBinaryOperator:"MultiplicativeBinaryOperator",ComparisonBinaryOperator:"ComparisonBinaryOperator",UnaryOperator:"UnaryOperator",Set:"Set",If:"If",For:"For",In:"In",Is:"Is",NotIn:"NotIn",Else:"Else",EndIf:"EndIf",ElseIf:"ElseIf",EndFor:"EndFor",And:"And",Or:"Or",Not:"UnaryOperator"}),K=Object.freeze({set:G.Set,for:G.For,in:G.In,is:G.Is,if:G.If,else:G.Else,endif:G.EndIf,elif:G.ElseIf,endfor:G.EndFor,and:G.And,or:G.Or,not:G.Not,"not in":G.NotIn,true:G.BooleanLiteral,false:G.BooleanLiteral}),X=class{constructor(t,e){this.value=t,this.type=e}};function Y(t){return/\w/.test(t)}function Z(t){return/[0-9]/.test(t)}var Q=[["{%",G.OpenStatement],["%}",G.CloseStatement],["{{",G.OpenExpression],["}}",G.CloseExpression],["(",G.OpenParen],[")",G.CloseParen],["{",G.OpenCurlyBracket],["}",G.CloseCurlyBracket],["[",G.OpenSquareBracket],["]",G.CloseSquareBracket],[",",G.Comma],[".",G.Dot],[":",G.Colon],["|",G.Pipe],["<=",G.ComparisonBinaryOperator],[">=",G.ComparisonBinaryOperator],["==",G.ComparisonBinaryOperator],["!=",G.ComparisonBinaryOperator],["<",G.ComparisonBinaryOperator],[">",G.ComparisonBinaryOperator],["+",G.AdditiveBinaryOperator],["-",G.AdditiveBinaryOperator],["*",G.MultiplicativeBinaryOperator],["/",G.MultiplicativeBinaryOperator],["%",G.MultiplicativeBinaryOperator],["=",G.Equals]],tt=new Map([["n","\n"],["t","\t"],["r","\r"],["b","\b"],["f","\f"],["v","\v"],["'","'"],['"','"'],["\\","\\"]]);function et(t,e={}){const r=[],n=function(t,e={}){return t.endsWith("\n")&&(t=t.slice(0,-1)),t=t.replace(/{#.*?#}/gs,"{##}"),e.lstrip_blocks&&(t=t.replace(/^[ \t]*({[#%])/gm,"$1")),e.trim_blocks&&(t=t.replace(/([#%]})\n/g,"$1")),t.replace(/{##}/g,"").replace(/-%}\s*/g,"%}").replace(/\s*{%-/g,"{%").replace(/-}}\s*/g,"}}").replace(/\s*{{-/g,"{{")}(t,e);let s=0;const i=t=>{let e="";for(;t(n[s]);)if("\\"!==n[s]){if(e+=n[s++],s>=n.length)throw new SyntaxError("Unexpected end of input")}else{if(++s,s>=n.length)throw new SyntaxError("Unexpected end of input");const t=n[s++],r=tt.get(t);if(void 0===r)throw new SyntaxError(`Unexpected escaped character: ${t}`);e+=r}return e};t:for(;s<n.length;){const t=r.at(-1)?.type;if(void 0===t||t===G.CloseStatement||t===G.CloseExpression){let t="";for(;s<n.length&&("{"!==n[s]||"%"!==n[s+1]&&"{"!==n[s+1]);)t+=n[s++];if(t.length>0){r.push(new X(t,G.Text));continue}}i((t=>/\s/.test(t)));const e=n[s];if("-"===e||"+"===e){const t=r.at(-1)?.type;if(t===G.Text||void 0===t)throw new SyntaxError(`Unexpected character: ${e}`);switch(t){case G.Identifier:case G.NumericLiteral:case G.BooleanLiteral:case G.StringLiteral:case G.CloseParen:case G.CloseSquareBracket:break;default:{++s;const t=i(Z);r.push(new X(`${e}${t}`,t.length>0?G.NumericLiteral:G.UnaryOperator));continue}}}for(const[t,e]of Q){if(n.slice(s,s+t.length)===t){r.push(new X(t,e)),s+=t.length;continue t}}if("'"!==e&&'"'!==e)if(Z(e)){const t=i(Z);r.push(new X(t,G.NumericLiteral))}else{if(!Y(e))throw new SyntaxError(`Unexpected character: ${e}`);{const t=i(Y),e=Object.hasOwn(K,t)?K[t]:G.Identifier;e===G.In&&r.at(-1)?.type===G.Not?(r.pop(),r.push(new X("not in",G.NotIn))):r.push(new X(t,e))}}else{++s;const t=i((t=>t!==e));r.push(new X(t,G.StringLiteral)),++s}}return r}var rt=class{constructor(){this.type="Statement"}},nt=class extends rt{constructor(t){super(),this.body=t,this.type="Program"}},st=class extends rt{constructor(t,e,r){super(),this.test=t,this.body=e,this.alternate=r,this.type="If"}},it=class extends rt{constructor(t,e,r){super(),this.loopvar=t,this.iterable=e,this.body=r,this.type="For"}},ot=class extends rt{constructor(t,e){super(),this.assignee=t,this.value=e,this.type="Set"}},at=class extends rt{constructor(){super(...arguments),this.type="Expression"}},ct=class extends at{constructor(t,e,r){super(),this.object=t,this.property=e,this.computed=r,this.type="MemberExpression"}},ut=class extends at{constructor(t,e){super(),this.callee=t,this.args=e,this.type="CallExpression"}},ht=class extends at{constructor(t){super(),this.value=t,this.type="Identifier"}},lt=class extends at{constructor(t){super(),this.value=t,this.type="Literal"}},ft=class extends lt{constructor(){super(...arguments),this.type="NumericLiteral"}},pt=class extends lt{constructor(){super(...arguments),this.type="StringLiteral"}},wt=class extends lt{constructor(){super(...arguments),this.type="BooleanLiteral"}},dt=class extends lt{constructor(){super(...arguments),this.type="ArrayLiteral"}},mt=class extends lt{constructor(){super(...arguments),this.type="TupleLiteral"}},yt=class extends lt{constructor(){super(...arguments),this.type="ObjectLiteral"}},bt=class extends at{constructor(t,e,r){super(),this.operator=t,this.left=e,this.right=r,this.type="BinaryExpression"}},gt=class extends at{constructor(t,e){super(),this.operand=t,this.filter=e,this.type="FilterExpression"}},xt=class extends at{constructor(t,e,r){super(),this.operand=t,this.negate=e,this.test=r,this.type="TestExpression"}},vt=class extends at{constructor(t,e){super(),this.operator=t,this.argument=e,this.type="UnaryExpression"}},Et=class extends at{constructor(t=void 0,e=void 0,r=void 0){super(),this.start=t,this.stop=e,this.step=r,this.type="SliceExpression"}},St=class extends at{constructor(t,e){super(),this.key=t,this.value=e,this.type="KeywordArgumentExpression"}};function $t(t){const e=new nt([]);let r=0;function n(e,n){const s=t[r++];if(!s||s.type!==e)throw new Error(`Parser Error: ${n}. ${s.type} !== ${e}.`);return s}function s(){let e;switch(t[r].type){case G.Text:e=new pt(n(G.Text,"Expected text token").value);break;case G.OpenStatement:e=function(){let e;switch(n(G.OpenStatement,"Expected opening statement token"),t[r].type){case G.Set:++r,e=a(),n(G.CloseStatement,"Expected closing statement token");break;case G.If:++r,e=c(),n(G.OpenStatement,"Expected {% token"),n(G.EndIf,"Expected endif token"),n(G.CloseStatement,"Expected %} token");break;case G.For:++r,e=function(){const t=u(!0);if(!(t instanceof ht||t instanceof mt))throw new SyntaxError(`Expected identifier/tuple for the loop variable, got ${t.type} instead`);n(G.In,"Expected `in` keyword following loop variable");const e=h();n(G.CloseStatement,"Expected closing statement token");const r=[];for(;i(G.OpenStatement,G.EndFor);)r.push(s());return new it(t,e,r)}(),n(G.OpenStatement,"Expected {% token"),n(G.EndFor,"Expected endfor token"),n(G.CloseStatement,"Expected %} token");break;default:throw new SyntaxError(`Unknown statement type: ${t[r].type} ${t[r].value}`)}return e}(),e.isStatement=!0;break;case G.OpenExpression:e=function(){n(G.OpenExpression,"Expected opening expression token");const t=h();return n(G.CloseExpression,"Expected closing expression token"),t}(),e.isStatement=!0;break;default:throw new SyntaxError(`Unexpected token type: ${t[r].type}`)}return e}function i(...e){return r+e.length<=t.length&&e.some(((e,n)=>e!==t[r+n].type))}function o(...e){return r+e.length<=t.length&&e.every(((e,n)=>e===t[r+n].type))}function a(){const t=h();if(o(G.Equals)){++r;const e=a();return new ot(t,e)}return t}function c(){const e=h();n(G.CloseStatement,"Expected closing statement token");const i=[],a=[];for(;t[r]?.type!==G.OpenStatement||t[r+1]?.type!==G.ElseIf&&t[r+1]?.type!==G.Else&&t[r+1]?.type!==G.EndIf;)i.push(s());if(t[r]?.type===G.OpenStatement&&t[r+1]?.type!==G.EndIf)if(++r,o(G.ElseIf))n(G.ElseIf,"Expected elseif token"),a.push(c());else for(n(G.Else,"Expected else token"),n(G.CloseStatement,"Expected closing statement token");t[r]?.type!==G.OpenStatement||t[r+1]?.type!==G.EndIf;)a.push(s());return new st(e,i,a)}function u(t=!1){const e=t?x:h,n=[e()],s=o(G.Comma);for(;s&&(++r,n.push(e()),o(G.Comma)););return s?new mt(n):n[0]}function h(){return function(){const t=l();if(o(G.If)){++r;const e=l();n(G.Else,"Expected else token");const s=l();return new st(e,[t],[s])}return t}()}function l(){let e=f();for(;o(G.Or);){const n=t[r];++r;const s=f();e=new bt(n,e,s)}return e}function f(){let e=p();for(;o(G.And);){const n=t[r];++r;const s=p();e=new bt(n,e,s)}return e}function p(){let e;for(;o(G.Not);){const n=t[r];++r;const s=p();e=new vt(n,s)}return e??function(){let e=w();for(;o(G.ComparisonBinaryOperator)||o(G.In)||o(G.NotIn);){const n=t[r];++r;const s=w();e=new bt(n,e,s)}return e}()}function w(){let e=b();for(;o(G.AdditiveBinaryOperator);){const n=t[r];++r;const s=b();e=new bt(n,e,s)}return e}function d(){const e=function(){let e=x();for(;o(G.Dot)||o(G.OpenSquareBracket);){const s=t[r];let i;++r;const o=s.type!==G.Dot;if(o)i=y(),n(G.CloseSquareBracket,"Expected closing square bracket");else if(i=x(),"Identifier"!==i.type)throw new SyntaxError("Expected identifier following dot operator");e=new ct(e,i,o)}return e}();return o(G.OpenParen)?m(e):e}function m(t){let e=new ut(t,function(){n(G.OpenParen,"Expected opening parenthesis for arguments list");const t=function(){const t=[];for(;!o(G.CloseParen);){let e=h();if(o(G.Equals)){if(++r,!(e instanceof ht))throw new SyntaxError("Expected identifier for keyword argument");const t=h();e=new St(e,t)}t.push(e),o(G.Comma)&&++r}return t}();return n(G.CloseParen,"Expected closing parenthesis for arguments list"),t}());return o(G.OpenParen)&&(e=m(e)),e}function y(){const t=[];let e=!1;for(;!o(G.CloseSquareBracket);)o(G.Colon)?(t.push(void 0),++r,e=!0):(t.push(h()),o(G.Colon)&&(++r,e=!0));if(0===t.length)throw new SyntaxError("Expected at least one argument for member/slice expression");if(e){if(t.length>3)throw new SyntaxError("Expected 0-3 arguments for slice expression");return new Et(...t)}return t[0]}function b(){let e=g();for(;o(G.MultiplicativeBinaryOperator);){const n=t[r];++r;const s=g();e=new bt(n,e,s)}return e}function g(){let t=function(){let t=d();for(;o(G.Pipe);){++r;let e=x();if(!(e instanceof ht))throw new SyntaxError("Expected identifier for the filter");o(G.OpenParen)&&(e=m(e)),t=new gt(t,e)}return t}();for(;o(G.Is);){++r;const e=o(G.Not);e&&++r;let n=x();if(n instanceof wt&&(n=new ht(n.value.toString())),!(n instanceof ht))throw new SyntaxError("Expected identifier for the test");t=new xt(t,e,n)}return t}function x(){const e=t[r];switch(e.type){case G.NumericLiteral:return++r,new ft(Number(e.value));case G.StringLiteral:return++r,new pt(e.value);case G.BooleanLiteral:return++r,new wt("true"===e.value);case G.Identifier:return++r,new ht(e.value);case G.OpenParen:{++r;const e=u();if(t[r].type!==G.CloseParen)throw new SyntaxError(`Expected closing parenthesis, got ${t[r].type} instead`);return++r,e}case G.OpenSquareBracket:{++r;const t=[];for(;!o(G.CloseSquareBracket);)t.push(h()),o(G.Comma)&&++r;return++r,new dt(t)}case G.OpenCurlyBracket:{++r;const t=new Map;for(;!o(G.CloseCurlyBracket);){const e=h();n(G.Colon,"Expected colon between key and value in object literal");const s=h();t.set(e,s),o(G.Comma)&&++r}return++r,new yt(t)}default:throw new SyntaxError(`Unexpected token: ${e.type}`)}}for(;r<t.length;)e.body.push(s());return e}function kt(t,e,r=1){void 0===e&&(e=t,t=0);const n=[];for(let s=t;s<e;s+=r)n.push(s);return n}function At(t,e,r,n=1){const s=Math.sign(n);s>=0?(e=(e??=0)<0?Math.max(t.length+e,0):Math.min(e,t.length),r=(r??=t.length)<0?Math.max(t.length+r,0):Math.min(r,t.length)):(e=(e??=t.length-1)<0?Math.max(t.length+e,-1):Math.min(e,t.length-1),r=(r??=-1)<-1?Math.max(t.length+r,-1):Math.min(r,t.length-1));const i=[];for(let o=e;s*o<s*r;o+=n)i.push(t[o]);return i}function Tt(t){return t.replace(/\b\w/g,(t=>t.toUpperCase()))}var Ot=class{constructor(t=void 0){this.type="RuntimeValue",this.builtins=new Map,this.value=t}__bool__(){return new Nt(!!this.value)}toString(){return""+this.value}toJSON(){return this.value}},Ct=class extends Ot{constructor(){super(...arguments),this.type="NumericValue"}},jt=class t extends Ot{constructor(){super(...arguments),this.type="StringValue",this.builtins=new Map([["upper",new Rt((()=>new t(this.value.toUpperCase())))],["lower",new Rt((()=>new t(this.value.toLowerCase())))],["strip",new Rt((()=>new t(this.value.trim())))],["title",new Rt((()=>new t(Tt(this.value))))],["length",new Ct(this.value.length)],["rstrip",new Rt((()=>new t(this.value.trimEnd())))],["lstrip",new Rt((()=>new t(this.value.trimStart())))]])}},Nt=class extends Ot{constructor(){super(...arguments),this.type="BooleanValue"}},Ft=class extends Ot{constructor(t,e){super(t),this.orgValue=e,this.type="ObjectValue",this.builtins=new Map([["get",new Rt((([t,e])=>{if(!(t instanceof jt))throw new Error(`Object key must be a string: got ${t.type}`);return this.value.get(t.value)??e??new Pt}))],["items",new Rt((()=>new It(Array.from(this.value.entries()).map((([t,e])=>new It([new jt(t),e]))))))]])}toString(){let t;return t=this.orgValue&&this.orgValue.toString!==Object.prototype.toString?this.orgValue.toString():JSON.stringify(Object.fromEntries(this.value.entries())),t}toJSON(){return this.orgValue?this.orgValue:Object.fromEntries(this.value.entries())}__bool__(){return new Nt(this.value.size>0)}},It=class extends Ot{constructor(){super(...arguments),this.type="ArrayValue",this.builtins=new Map([["length",new Ct(this.value.length)]])}__bool__(){return new Nt(this.value.length>0)}},Mt=class extends It{constructor(){super(...arguments),this.type="TupleValue"}},Rt=class extends Ot{constructor(){super(...arguments),this.type="FunctionValue"}},Pt=class extends Ot{constructor(){super(...arguments),this.type="NullValue"}},Bt=class extends Ot{constructor(){super(...arguments),this.type="UndefinedValue"}},Ut=class{constructor(t){this.parent=t,this.variables=new Map([["namespace",new Rt((t=>{if(0===t.length)return new Ft(new Map);if(1!==t.length||!(t[0]instanceof Ft))throw new Error("`namespace` expects either zero arguments or a single object argument");return t[0]}))]]),this.tests=new Map([["boolean",t=>"BooleanValue"===t.type],["callable",t=>t instanceof Rt],["odd",t=>{if("NumericValue"!==t.type)throw new Error(`Cannot apply test "odd" to type: ${t.type}`);return t.value%2!=0}],["even",t=>{if("NumericValue"!==t.type)throw new Error(`Cannot apply test "even" to type: ${t.type}`);return t.value%2==0}],["false",t=>"BooleanValue"===t.type&&!t.value],["true",t=>"BooleanValue"===t.type&&t.value],["number",t=>"NumericValue"===t.type],["integer",t=>"NumericValue"===t.type&&Number.isInteger(t.value)],["iterable",t=>t instanceof It||t instanceof jt],["lower",t=>{const e=t.value;return"StringValue"===t.type&&e===e.toLowerCase()}],["upper",t=>{const e=t.value;return"StringValue"===t.type&&e===e.toUpperCase()}],["none",t=>"NullValue"===t.type],["defined",t=>"UndefinedValue"!==t.type],["undefined",t=>"UndefinedValue"===t.type],["equalto",(t,e)=>t.value===e.value]])}set(t,e){return this.declareVariable(t,Lt(e))}declareVariable(t,e){if(this.variables.has(t))throw new SyntaxError(`Variable already declared: ${t}`);return this.variables.set(t,e),e}setVariable(t,e){return this.variables.set(t,e),e}resolve(t){if(this.variables.has(t))return this;if(this.parent)return this.parent.resolve(t);throw new Error(`Unknown variable: ${t}`)}lookupVariable(t){try{return this.resolve(t).variables.get(t)??new Bt}catch{return new Bt}}},Vt=class{constructor(t){this.global=t??new Ut}run(t){return this.evaluate(t,this.global)}evaluateBinaryExpression(t,e){const r=this.evaluate(t.left,e);switch(t.operator.value){case"and":return r.__bool__().value?this.evaluate(t.right,e):r;case"or":return r.__bool__().value?r:this.evaluate(t.right,e)}const n=this.evaluate(t.right,e);switch(t.operator.value){case"==":return new Nt(r.value==n.value);case"!=":return new Nt(r.value!=n.value)}if(r instanceof Bt||n instanceof Bt)throw new Error("Cannot perform operation on undefined values");if(r instanceof Pt||n instanceof Pt)throw new Error("Cannot perform operation on null values");if(r instanceof Ct&&n instanceof Ct)switch(t.operator.value){case"+":return new Ct(r.value+n.value);case"-":return new Ct(r.value-n.value);case"*":return new Ct(r.value*n.value);case"/":return new Ct(r.value/n.value);case"%":return new Ct(r.value%n.value);case"<":return new Nt(r.value<n.value);case">":return new Nt(r.value>n.value);case">=":return new Nt(r.value>=n.value);case"<=":return new Nt(r.value<=n.value)}else if(r instanceof It&&n instanceof It){if("+"===t.operator.value)return new It(r.value.concat(n.value))}else if(n instanceof It){const e=void 0!==n.value.find((t=>t.value===r.value));switch(t.operator.value){case"in":return new Nt(e);case"not in":return new Nt(!e)}}if((r instanceof jt||n instanceof jt)&&"+"===t.operator.value)return new jt(r.toString()+n.toString());if(r instanceof jt&&n instanceof jt)switch(t.operator.value){case"in":return new Nt(n.value.includes(r.value));case"not in":return new Nt(!n.value.includes(r.value))}if(r instanceof jt&&n instanceof Ft)switch(t.operator.value){case"in":return new Nt(n.value.has(r.value));case"not in":return new Nt(!n.value.has(r.value))}throw new SyntaxError(`Unknown operator "${t.operator.value}" between ${r.type} and ${n.type}`)}evaluateFilterExpression(t,e){const r=this.evaluate(t.operand,e);if("Identifier"===t.filter.type){const e=t.filter;if(r instanceof It)switch(e.value){case"list":return r;case"first":return r.value[0];case"last":return r.value[r.value.length-1];case"length":return new Ct(r.value.length);case"reverse":return new It(r.value.reverse());case"sort":return new It(r.value.sort(((t,e)=>{if(t.type!==e.type)throw new Error(`Cannot compare different types: ${t.type} and ${e.type}`);switch(t.type){case"NumericValue":return t.value-e.value;case"StringValue":return t.value.localeCompare(e.value);default:throw new Error(`Cannot compare type: ${t.type}`)}})));case"tojson":return new jt(JSON.stringify(r.value));default:throw new Error(`Unknown ArrayValue filter: ${e.value}`)}else if(r instanceof jt)switch(e.value){case"length":return new Ct(r.value.length);case"upper":return new jt(r.value.toUpperCase());case"lower":return new jt(r.value.toLowerCase());case"title":return new jt(Tt(r.value));case"capitalize":return new jt(r.value.charAt(0).toUpperCase()+r.value.slice(1));case"trim":return new jt(r.value.trim());case"trimStart":return new jt(r.value.trimStart());case"trimEnd":return new jt(r.value.trimEnd());default:throw new Error(`Unknown StringValue filter: ${e.value}`)}else{if(r instanceof Ct){if("abs"===e.value)return new Ct(Math.abs(r.value));throw new Error(`Unknown NumericValue filter: ${e.value}`)}if(r instanceof Ft)switch(e.value){case"items":return new It(Array.from(r.value.entries()).map((([t,e])=>new It([new jt(t),e]))));case"length":return new Ct(r.value.size);case"tojson":return new jt(JSON.stringify(r));case"string":return new jt(r.toString());default:throw new Error(`Unknown ObjectValue filter: ${e.value}`)}}throw new Error(`Cannot apply filter "${e.value}" to type: ${r.type}`)}if("CallExpression"===t.filter.type){const n=t.filter;if("Identifier"!==n.callee.type)throw new Error(`Unknown filter: ${n.callee.type}`);const s=n.callee.value,i=e.lookupVariable(s);if(i instanceof Rt)return i.value([r,...n.args.map((t=>this.evaluate(t,e)))],e);if(r instanceof It){if("selectattr"===s){if(r.value.some((t=>!(t instanceof Ft))))throw new Error("`selectattr` can only be applied to array of objects");if(n.args.some((t=>"StringLiteral"!==t.type)))throw new Error("arguments of `selectattr` must be strings");const[t,s,i]=n.args.map((t=>this.evaluate(t,e)));let o;if(s){const t=e.tests.get(s.value);if(!t)throw new Error(`Unknown test: ${s.value}`);o=t}else o=(...t)=>t[0].__bool__().value;const a=r.value.filter((e=>{const r=e.value.get(t.value);return!!r&&o(r,i)}));return new It(a)}throw new Error(`Unknown ArrayValue filter: ${s}`)}throw new Error(`Cannot apply filter "${s}" to type: ${r.type}`)}throw new Error(`Unknown filter: ${t.filter.type}`)}evaluateTestExpression(t,e){const r=this.evaluate(t.operand,e),n=e.tests.get(t.test.value);if(!n)throw new Error(`Unknown test: ${t.test.value}`);const s=n(r);return new Nt(t.negate?!s:s)}evaluateUnaryExpression(t,e){const r=this.evaluate(t.argument,e);if("not"===t.operator.value)return new Nt(!r.value);throw new SyntaxError(`Unknown operator: ${t.operator.value}`)}evalProgram(t,e){return this.evaluateBlock(t.body,e)}evaluateBlock(t,e){let r="";for(const n of t){const t=this.evaluate(n,e);"NullValue"!==t.type&&"UndefinedValue"!==t.type&&(r+=t)}return new jt(r)}evaluateIdentifier(t,e){return e.lookupVariable(t.value)}evaluateCallExpression(t,e){const r=[],n=new Map;for(const s of t.args)if("KeywordArgumentExpression"===s.type){const t=s;n.set(t.key.value,this.evaluate(t.value,e))}else r.push(this.evaluate(s,e));n.size>0&&r.push(new Ft(n));const s=this.evaluate(t.callee,e);if("FunctionValue"!==s.type)throw new Error(`Cannot call something that is not a function: got ${s.type}`);return s.value(r,e)}evaluateSliceExpression(t,e,r){if(!(t instanceof It||t instanceof jt))throw new Error("Slice object must be an array or string");const n=this.evaluate(e.start,r),s=this.evaluate(e.stop,r),i=this.evaluate(e.step,r);if(!(n instanceof Ct||n instanceof Bt))throw new Error("Slice start must be numeric or undefined");if(!(s instanceof Ct||s instanceof Bt))throw new Error("Slice stop must be numeric or undefined");if(!(i instanceof Ct||i instanceof Bt))throw new Error("Slice step must be numeric or undefined");return t instanceof It?new It(At(t.value,n.value,s.value,i.value)):new jt(At(Array.from(t.value),n.value,s.value,i.value).join(""))}evaluateMemberExpression(t,e){const r=this.evaluate(t.object,e);let n,s;if(t.computed){if("SliceExpression"===t.property.type)return this.evaluateSliceExpression(r,t.property,e);n=this.evaluate(t.property,e)}else n=new jt(t.property.value);if(r instanceof Ft){if(!(n instanceof jt))throw new Error(`Cannot access property with non-string: got ${n.type}`);s=r.value.get(n.value)??r.builtins.get(n.value)}else if(r instanceof It||r instanceof jt)if(n instanceof Ct)s=r.value.at(n.value),r instanceof jt&&(s=new jt(r.value.at(n.value)));else{if(!(n instanceof jt))throw new Error(`Cannot access property with non-string/non-number: got ${n.type}`);s=r.builtins.get(n.value)}else{if(!(n instanceof jt))throw new Error(`Cannot access property with non-string: got ${n.type}`);s=r.builtins.get(n.value)}return s instanceof Ot?s:new Bt}evaluateSet(t,e){const r=this.evaluate(t.value,e);if("Identifier"===t.assignee.type){const n=t.assignee.value;e.setVariable(n,r)}else{if("MemberExpression"!==t.assignee.type)throw new Error(`Invalid LHS inside assignment expression: ${JSON.stringify(t.assignee)}`);{const n=t.assignee,s=this.evaluate(n.object,e);if(!(s instanceof Ft))throw new Error("Cannot assign to member of non-object");if("Identifier"!==n.property.type)throw new Error("Cannot assign to member with non-identifier property");s.value.set(n.property.value,r)}}return new Pt}evaluateIf(t,e){const r=this.evaluate(t.test,e);return this.evaluateBlock(r.__bool__().value?t.body:t.alternate,e)}evaluateFor(t,e){const r=new Ut(e),n=this.evaluate(t.iterable,r);if(!(n instanceof It))throw new Error(`Expected iterable type in for loop: got ${n.type}`);let s="";for(let e=0;e<n.value.length;++e){const i=new Map([["index",new Ct(e+1)],["index0",new Ct(e)],["revindex",new Ct(n.value.length-e)],["revindex0",new Ct(n.value.length-e-1)],["first",new Nt(0===e)],["last",new Nt(e===n.value.length-1)],["length",new Ct(n.value.length)],["previtem",e>0?n.value[e-1]:new Bt],["nextitem",e<n.value.length-1?n.value[e+1]:new Bt]]);r.setVariable("loop",new Ft(i));const o=n.value[e];if("Identifier"===t.loopvar.type)r.setVariable(t.loopvar.value,o);else if("TupleLiteral"===t.loopvar.type){const e=t.loopvar;if("ArrayValue"!==o.type)throw new Error(`Cannot unpack non-iterable type: ${o.type}`);const n=o;if(e.value.length!==n.value.length)throw new Error(`Too ${e.value.length>n.value.length?"few":"many"} items to unpack`);for(let t=0;t<e.value.length;++t){if("Identifier"!==e.value[t].type)throw new Error(`Cannot unpack non-identifier type: ${e.value[t].type}`);r.setVariable(e.value[t].value,n.value[t])}}s+=this.evaluateBlock(t.body,r).value}return new jt(s)}evaluate(t,e){if(void 0===t)return new Bt;switch(t.type){case"Program":return this.evalProgram(t,e);case"Set":return this.evaluateSet(t,e);case"If":return this.evaluateIf(t,e);case"For":return this.evaluateFor(t,e);case"NumericLiteral":return new Ct(Number(t.value));case"StringLiteral":return new jt(t.value);case"BooleanLiteral":return new Nt(t.value);case"ArrayLiteral":return new It(t.value.map((t=>this.evaluate(t,e))));case"TupleLiteral":return new Mt(t.value.map((t=>this.evaluate(t,e))));case"ObjectLiteral":{const r=new Map;for(const[n,s]of t.value){const t=this.evaluate(n,e);if(!(t instanceof jt))throw new Error(`Object keys must be strings: got ${t.type}`);r.set(t.value,this.evaluate(s,e))}return new Ft(r,t.value)}case"Identifier":return this.evaluateIdentifier(t,e);case"CallExpression":return this.evaluateCallExpression(t,e);case"MemberExpression":return this.evaluateMemberExpression(t,e);case"UnaryExpression":return this.evaluateUnaryExpression(t,e);case"BinaryExpression":return this.evaluateBinaryExpression(t,e);case"FilterExpression":return this.evaluateFilterExpression(t,e);case"TestExpression":return this.evaluateTestExpression(t,e);default:throw new SyntaxError(`Unknown node type: ${t.type}`)}}};function Lt(t){switch(typeof t){case"number":return new Ct(t);case"string":return new jt(t);case"boolean":return new Nt(t);case"object":return null===t?new Pt:Array.isArray(t)?new It(t.map(Lt)):new Ft(new Map(Object.entries(t).map((([t,e])=>[t,Lt(e)]))),t);case"function":return new Rt(((e,r)=>{const n=e.map((t=>_t(t)));return Lt(t(...n)??null)}));case"undefined":return new Pt;default:throw new Error(`Cannot convert to runtime value: ${t}`)}}function _t(t){let e=t;return Array.isArray(t)?e=t.map((t=>_t(t))):t instanceof Map?(e={},t.forEach(((t,r)=>{e[r]=_t(t)}))):"ObjectValue"===t.type?t.orgValue?e=t.orgValue:(e={},t.forEach(((t,r)=>{e[r]=_t(t)}))):"ArrayValue"===t.type?e=t.value.map((t=>_t(t))):t.type&&(e=t.value),e}function qt(t,e=0){return Math.floor(Math.random()*(t-e+1))+e}var zt={randomInt:qt,select:function(t,e){if(Array.isArray(t)||"string"==typeof t)return void 0===e?e=qt(t.length-1):"string"==typeof e&&(e=parseInt(e)),e<0&&(e=t.length+e),t[e];if(t&&"object"==typeof t){if(void 0===e){const r=Object.keys(t);e=r[qt(r.length-1)]}return t[e]}}},Dt=class extends Ut{constructor(t){super(t),this.parent=t}assign(t){for(const[e,r]of Object.entries(t))this.set(e,r)}clear(){this.variables.clear()}},Jt=class t{static{this.global=new Dt}constructor(t,e={}){const r=et(t,e={lstrip_blocks:!0,trim_blocks:!0,...e});this.parsed=$t(r)}render(e){const r=new Ut(t.global);r.set("false",!1),r.set("true",!0),r.set("raise_exception",(t=>{throw new Error(t)})),r.set("range",kt);for(const[t,n]of Object.entries(e))r.set(t,n);return new Vt(r).run(this.parsed).toString()}};function Wt(t,e){let r;switch(t.type){case"Identifier":r=t.value;break;case"MemberExpression":r=Wt(t.object,e);break;case"FilterExpression":r=Wt(t.operand,e);break;case"Set":{e||(e=[]);const n=Wt(t.assignee);n&&e.push(n),r=Wt(t.value,e);break}}return r&&e?.includes(r)&&(r=void 0),r}function Ht(t){let e;if("Program"===t.type)e=t.body.some((t=>Ht(t)));else e=t.isStatement;return e}function Gt(t,e){let r=[];if(Array.isArray(t))r=t.map((t=>Gt(t,e))).filter(Boolean).flat();else switch(t.type){case"Program":r=t.body.map((t=>Gt(t,e))).filter(Boolean).flat();break;case"If":r=[Wt(t.test,e),...Gt(t.body,e),...Gt(t.alternate,e)].filter(Boolean);break;case"BinaryExpression":r=[Wt(t.left,e),Wt(t.right,e)].filter(Boolean);break;case"For":{const n=Wt(t.loopvar);n&&(e||(e=[]),e.push(n)),r=[Wt(t.iterable,e),...Gt(t.body,e)].filter(Boolean);break}case"CallExpression":r=[Wt(t.callee,e),...Gt(t.args,e)].filter(Boolean);break;default:r=[Wt(t,e)].filter(Boolean)}return r}Jt.global.assign(zt);var Kt=class extends D{static isTemplate(t){let e,r,n=!1;if("object"==typeof t?(r=t.template,e=t.compiledTemplate):r=t,!e&&r)try{e=new Jt(r)}catch(t){}return e&&(n=Ht(e.parsed)),n}getVariables(t=this.compiledTemplate){return Gt(t.parsed,[]).filter(((t,e,r)=>r.indexOf(t)===e))}_initialize(t){const e=t?.template;if("string"!=typeof e)throw new w("Prompt template must be a string","PromptTemplate",400);this.compiledTemplate=new Jt(e),this.inputVariables=Array.isArray(t?.inputVariables)?t.inputVariables:this.getVariables()}_format(t){return this.compiledTemplate.render(t)}};function Xt(t){return function(e){return t}}function Yt(t){const e=t.split(""),r=[],n=(t,r)=>{for(let n=r;n<e.length;n+=1)if(t.includes(e[n]))return n;return-1};let s=0;for(;s<e.length;)if("{"===e[s]&&s+1<e.length&&"{"===e[s+1])r.push({type:"literal",text:"{"}),s+=2;else if("}"===e[s]&&s+1<e.length&&"}"===e[s+1])r.push({type:"literal",text:"}"}),s+=2;else if("{"===e[s]){const t=n("}",s);if(t<0)throw new Error("Unclosed '{' in template.");r.push({type:"variable",name:e.slice(s+1,t).join("")}),s=t+1}else{if("}"===e[s])throw new Error("Single '}' in template.");{const t=n("{}",s),i=(t<0?e.slice(s):e.slice(s,t)).join("");r.push({type:"literal",text:i}),s=t<0?e.length:t}}return r}function Zt(t,e){return t.reduce(((t,r)=>{let n;return n="variable"===r.type?r.name in e?t+e[r.name]:t:t+r.text,n}),"")}function Qt(t){const e=new Set;return t.forEach((t=>{"variable"===t.type&&e.add(t.name)})),[...e]}D.register(Kt,{name:"hf",aliases:["huggingface","internal","default"]});var te=class extends D{static isTemplate(t){let e,r,n=!1;if("object"==typeof t?(r=t.template,e=t.compiledTemplate):r=t,!e&&r)try{e=Yt(r)}catch(t){}if(e){n=Qt(e).length>0}return n}getVariables(t=this.compiledTemplate){return Qt(t)}_initialize(t){const e=t?.template;if("string"!=typeof e)throw new w("Prompt template must be a string","PromptTemplate",400);this.compiledTemplate=Yt(e),this.inputVariables=Array.isArray(t?.inputVariables)?t.inputVariables:this.getVariables()}_format(t){return Zt(this.compiledTemplate,t)}};function ee(t,e){return"string"==typeof e&&(e=e.split(".").filter((t=>t.length))),e.reduce(((t,e)=>t?.[e]),t)}function re(t,e,r){let n=function(t,e,r){return t.replace(/{{\s*re_replace\s+\.(.+?)\s+(["'])([^\2]*?)\2\s+(["'])([^\4]*?)\4\s*}}/g,((t,n,s,i,o,a)=>{if(r)return e[n]=null,t;const c=new RegExp(i,"g");return ee(e,n).replace(c,a)}))}(t,e,r);return n=function(t,e,r){return t.replace(/{{\s*join\s+\.(.+?)\s+(["'])([^\2]*?)\2\s*}}/g,((t,n,s,i)=>r?(e[n]=null,t):ee(e,n).join(i)))}(n,e,r),n=function(t,e,r){return t.replace(/{{\s*if\s*(\S+?)\s*}}([^{]*)({{\s*else\s*}}([^{]*))?{{\s*end\s*}}/g,((t,n,s,i,o)=>{if(r)return n.startsWith(".")&&(n=n.substring(1)),e[n]=null,t;let a;if(!n.startsWith("."))throw new Error("Functionality not implemented");{const t=ee(e,n.substring(1));if(null==t)a=o??"";else if("string"==typeof t)a=t.length>0?s:o??"";else if(Array.isArray(t))a=t.length>0?s:o??"";else{if("boolean"!=typeof t)throw new Error(`Unexpected type for variable ${n}: ${typeof t}`);a=t?s:o??""}}return a}))}(n,e,r),n=function(t,e,r){return t.replace(/{{\s*range\s*[.$]([^{}\s]+?)\s*}}([^{]*?){{\.}}([^{]*?){{\s*end\s*}}/g,((t,n,s,i)=>{if(r)return e[n]=null,t;const o=ee(e,n);if(Array.isArray(o)){let t="";for(const e of o)t+=`${s}${e}${i}`;return t}return t}))}(n,e,r),n=function(t,e,r){return t.replace(/{{\s*\.([^{}\s]+?)\s*}}/g,((t,n)=>r?(e[n]=null,t):ee(e,n)||""))}(n,e,r),n=function(t,e,r){return t.replace(/{{\s*index\s*\.(.+?)\s+(.+?)\s*}}/g,((t,n,s)=>{if(r)return e[n]=null,t;const i=ee(e,n);let o;return o=isNaN(s)?i[s.substring(1,s.length-1)]:i[parseInt(s,10)],o||""}))}(n,e,r),n}D.register(te,{name:"fstring",aliases:["python","f-string","langchain"]});var ne=class extends D{static isTemplate(t){const e="string"==typeof t?t:t.template;return e?.includes("{{")&&e.includes("}}")}getVariables(t){const e={};return re(t,e,!0),[...Object.keys(e)]}_initialize(t){const e=t?.template;if("string"!=typeof e)throw new w("Prompt template must be a string","PromptTemplate",400);this.inputVariables=Array.isArray(t?.inputVariables)?t.inputVariables:this.getVariables(e)}_format(t){return re(this.template,t)}};function se(t){return Object.keys(t).sort().map((e=>t[e]))}D.register(ne,{name:"golang",aliases:["localai","ollama"]});var ie=class extends D{static from(t){return new this(t)}constructor(t){super(t)}_initialize(t){t&&(t.suffix&&(this.suffix=t.suffix),t.exampleSeparator&&(this.exampleSeparator=t.exampleSeparator),t.prefix&&(this.prefix=t.prefix),t.examplePrompt&&(this.examplePrompt=t.examplePrompt instanceof D?t.examplePrompt:D.from(t.examplePrompt)),t.examples&&(this.examples=t.examples)),this.prefix||(this.prefix=""),this.exampleSeparator||(this.exampleSeparator="\n\n"),this.suffix||(this.suffix="")}async _format(t){const e=[];for await(const t of this.examples)if(this.examplePrompt){const r=await this.examplePrompt.format(t);e.push(r)}else if("string"==typeof t)e.push(t);else if(t){const r=se(t);r.length>0&&e.push(...r)}const r=[this.prefix,...e,this.suffix].join(this.exampleSeparator),n=this.templateFormat;return await D.format({template:r,data:t,templateFormat:n})}toJSON(t=this){const e=super.toJSON(t);return t.suffix&&(e.suffix=t.suffix),t.exampleSeparator&&(e.exampleSeparator=t.exampleSeparator),t.prefix&&(e.prefix=t.prefix),t.examplePrompt&&(e.examplePrompt=t.examplePrompt),t.examples&&(e.examples=t.examples),e}};D.register(ie,{name:"fewshot",aliases:["few_shot"]});var oe=/(\\)?(\$)(?!\()(\{?)([\w.]+)(?::?-((?:\$\{(?:\$\{(?:\$\{[^}]*\}|[^}])*}|[^}])*}|[^}])+))?(\}?)/gi;function ae(t){return t.replace(/\\\$/g,"$")}function ce(t,e,r){return t.replace(oe,((n,s,i,o,a,c,u)=>"\\"===s?n.slice(1):e[a]?e[a]===r[a]?e[a]:ce(e[a],e,r):r[a]?r[a]===t?r[a]:ce(r[a],e,r):c?c.startsWith("$")?ce(c,e,r):c:""))}function ue(t){let e=process.env;t&&null!=t.processEnv&&(e=t.processEnv);for(const r in t.parsed){let n=t.parsed[r];if(!n)continue;n=Object.prototype.hasOwnProperty.call(e,r)?e[r]===t.parsed[r]?ce(n,e,t.parsed):e[r]:ce(n,e,t.parsed),t.parsed[r]=n?ae(n):n}for(const r in t.parsed)e[r]=t.parsed[r];return t}function he(t,e={},r){switch(r||(r=new WeakSet),e.processEnv||(e.processEnv={...process.env}),e.parsed||(e.parsed=e.processEnv),typeof t){case"string":t=ce(t,e.processEnv,e.parsed);break;case"object":if(r.has(t))return t;if(r.add(t),Array.isArray(t))for(let n=0;n<t.length;n++){const s=t[n];"string"!=typeof s&&"object"!=typeof s||(t[n]=he(t[n],e,r))}else for(const[n,s]of Object.entries(t))"string"!=typeof s&&"object"!=typeof s||(t[n]=he(s,e,r))}return t}var le="@",fe=/(\S.+?[.!?])(?=\s+|$)|(\S.+?)(?=[\n]|$)/g,pe=/([A-Z][a-z]{1,2}\.)\s(\w)/g,we=/(\.[a-zA-Z]\.)\s(\w)/g,de=new RegExp("([A-Z][a-z]{1,2}\\.)"+le+"(\\w)","g"),me=new RegExp("(\\.[a-zA-Z]\\.)"+le+"(\\w)","g");function ye(t,e,r){const n="$1"+e+"$2";let s=t;for(let t=0;t<r.length;t++)s=s.replace(r[t],n);return s}function be(t,e=!0){const r=(t=(t=(t=(t=(t=t.replace(/([。!??])\1+/g,"$1")).replace(/([。!??])([^”’])/g,"$1\n$2")).replace(/(\.{6})([^”’])/g,"$1\n$2")).replace(/(…{2})([^”’])/g,"$1\n$2")).replace(/([。!??][”’])([^,。!??])/g,"$1\n$2")).split("\n");let n=[];for(let t=0;t<r.length;t++){let s=r[t].trim();if(!s)continue;if(!e){n.push(s);continue}let i=ye(s,le,[pe,we]),o=Array.from(i.matchAll(fe));if(o.length)for(let t=0;t<o.length;t++){let e=ye(o[t][0]," ",[de,me]);n.push(e)}else n.push(s)}return n}function ge(t,e=2,r=.5){const n=10**e;return Math.trunc((t+Number.EPSILON+r/n)*n)/n}async function xe(t){return new Promise((e=>setTimeout(e,t)))}import{createAbilityInjector as ve}from"custom-ability";var Ee="event",Se="event-bus";var $e=ve((function(t){return class{static get emitter(){if(!this._emitter){const t=this.get(Se)?.emitter;t&&(this._emitter=t,this.prototype._events=t._events)}return this._emitter}get emitter(){return this.constructor._emitter}on(e,r){const n=t.emitter;if(!n)throw new TypeError("EventBackend required");return n.on(e,r)}once(e,r){const n=t.emitter;if(!n)throw new TypeError("EventBackend required");return n.once(e,r)}off(e,r){const n=t.emitter;if(!n)throw new TypeError("EventBackend required");return n.off(e,r)}emit(e,...r){const n=t.emitter;if(!n)throw new TypeError("EventBackend required");return"error"===e?this.emitError.apply(this,r):n.emit.call(this,e,this.name,...r)}emitError(e,...r){const n=t.emitter;if(!n)throw new TypeError("EventBackend required");return n.emit.call(this,"error",e,this.name,...r)}async emitAsync(e,...r){const n=t.emitter;if(!n)throw new TypeError("EventBackend required");return n.emitAsync.call(this,e,this.name,...r)}}}),!0);function ke(t,e){return!t||t.some((t=>t instanceof RegExp?t.test(e):t===e))}var Ae=498,Te=class{get active(){return this._active}set active(t){t!==this._active&&(t?(this.pingTimer&&(clearInterval(this.pingTimer),this.pingTimer=void 0),this.options.pingInterval>0&&(this.pingTimer=setInterval((()=>this.publish()),this.options.pingInterval))):(this.clients.size&&this.clearClients(),this.pingTimer&&(clearInterval(this.pingTimer),this.pingTimer=void 0)),this._active=t)}constructor(t){this.options=Object.assign({},{pingInterval:3e3,maxStreamDuration:3e4,clientRetryInterval:1e3,startId:1,historySize:100,rewind:0,cors:!1},t),this.nextID=this.options.startId,this.clients=new Set,this.messages=[],this.active=!0}publish(t,e){let r,n;this.active||x("Channel closed","SSEChannel",Ae);let s=e;if(t||e)n=this.nextID++,"object"==typeof t&&(t.event?(s=t.event,void 0!==t.data&&(t=JSON.stringify(t.data))):t=JSON.stringify(t)),t=t?t.split(/[\r\n]+/).map((t=>"data: "+t)).join("\n"):"",r="id: "+n+"\n"+(e?"event: "+e+"\n":"")+(t||"data: ")+"\n\n",this.messages.push({id:n,_eventName:s,output:r});else{if(!this.clients.size)return;r="data: \n\n"}for([...this.clients].filter((t=>!s||ke(t.events,s))).forEach(((t,e)=>{t.res.write(r)}));this.messages.length>this.options.historySize;)this.messages.shift();return n}subscribe(t,e,r){this.active||x("Channel closed","SSEChannel",Ae);const n={req:t,res:e,events:r},s=this.options.maxStreamDuration;let i="max-age=0, stale-while-revalidate=0, stale-if-error=0, no-transform";s>0&&(i+=", s-maxage="+(Math.floor(s/1e3)-1));const o={"Content-Type":"text/event-stream","Cache-Control":i,Connection:"keep-alive"};this.options.cors&&(o["access-control-allow-origin"]="*"),n.req.socket.setNoDelay(!0),n.res.writeHead(200,o);let a="retry: "+this.options.clientRetryInterval+"\n\n";const c=Number.parseInt(t.headers["last-event-id"],10),u=Number.isNaN(c)?this.options.rewind:this.nextID-1-c;return u&&this.messages.filter((t=>ke(n.events,t.eventName))).slice(0-u).forEach((t=>{a+=t.output})),n.res.write(a),this.clients.add(n),s>0&&setTimeout((()=>{n.res.writableEnded||this.unsubscribe(n)}),s),n.res.on("close",(()=>this.unsubscribe(n))),n}unsubscribe(t){t.res.end(),this.clients.delete(t)}clearClients(){this.clients.forEach((t=>t.res.end())),this.clients.clear()}listClients(){const t={};return this.clients.forEach((e=>{const r=e.req.socket.remoteAddress??"";r in t||(t[r]=0),t[r]++})),t}getSubscriberCount(){return this.clients.size}};function Oe(t){return t instanceof ReadableStream||t instanceof WritableStream}var Ce=600,je=601,Ne=class extends p{constructor(t,e=Ce){super(t,500)}};function Fe(t){if(t){const e=t.getReader();return new ReadableStream({async start(t){const{done:r,value:n}=await e.read();if(!r){const e=(new TextDecoder).decode(n);t.error(new Ne(`Response error: ${e}`,je))}}})}return new ReadableStream({start(t){t.error(new Ne("Response error: No response body",je))}})}function Ie(){return new ReadableStream({start(t){t.close()}})}import{createParser as Me}from"eventsource-parser";function Re(t){const e=new TextDecoder;let r;return new TransformStream({async start(e){r=Me((r=>{if("data"in r&&"event"===r.type&&"[DONE]"===r.data||"done"===r.event)e.terminate();else if("data"in r){const n=t?t(r.data,{event:r.event}):r.data;n&&e.enqueue(n)}}))},transform(t){r.feed(e.decode(t))}})}function Pe(){let t=!0;return e=>(t&&(e=e.trimStart())&&(t=!1),e)}function Be(t,e){if(!t.ok)return Fe(t.body);let r=t.body||new ReadableStream({start(t){t.close()}});return r instanceof ReadableStream||(r=ReadableStream.from(r)),r.pipeThrough(Re(e))}function Ue(t){let e=t[Symbol.asyncIterator]();return new ReadableStream({async pull(t){const{done:r,value:n}=await e.next();r?t.close():t.enqueue(n)},async cancel(t){await(e.return?.(t))}})}function Ve(t){const e=t||{};return new TransformStream({async start(t){const r=t.error;if(t.error=n=>{r.call(t,n),e.onError&&e.onError(n)},e.onStart)try{await e.onStart(t)}catch(e){t.error(e)}},async transform(t,r){try{let n;e.onTransform&&(n=await e.onTransform(t,r)),n||(n=t),r.enqueue(n)}catch(t){r.error(t)}},async flush(t){if(e.onFinal)try{await e.onFinal(t)}catch(e){return t.error(e)}t.terminate()}})}var Le={};t(Le,{XXHashAlgorithm:()=>fr,base32768:()=>or,uuid:()=>tr,uuidNIL:()=>Ze,uuidParse:()=>Ke,uuidStringify:()=>Ge,uuidValidate:()=>Xe,uuidVersion:()=>Ye,uuidv1:()=>Je,uuidv4:()=>We,uuidv5:()=>He,xxhash:()=>pr,xxhash32:()=>hr,xxhash64:()=>lr,xxhashAsStr:()=>wr});import{v1 as _e,v5 as qe,v4 as ze}from"uuid";import*as De from"base32768";import{v1 as Je,v4 as We,v5 as He,stringify as Ge,parse as Ke,validate as Xe,version as Ye,NIL as Ze}from"uuid";var Qe={1:_e,4:ze,5:qe};function tr(t=1,e){const r=Qe[t];return e?De.encode(r(null,[])):r()}var er={};t(er,{XXHashAlgorithm:()=>fr,base32768:()=>or,xxhash:()=>pr,xxhash32:()=>hr,xxhash64:()=>lr,xxhashAsStr:()=>wr}),e(er,ir);import rr from"xxhashjs";import*as nr from"base32768";import{canonicalize as sr}from"json-canonicalize";import*as ir from"json-canonicalize";var or=nr,{h32:ar,h64:cr}=rr,ur=588213;function hr(t,e=16){return"object"==typeof t&&(t=sr(t)),ar(t,ur).toString(e)}function lr(t,e=16){return"object"==typeof t&&(t=sr(t)),cr(t,ur).toString(e)}var fr=(t=>(t[t.xxhash64=111]="xxhash64",t[t.xxhash32=112]="xxhash32",t))(fr||{});function pr(t,e=111,r=ur){let n;return t.buffer&&(t=t.buffer),112!==e?(n=cr(t,r),n=new Uint16Array([n._a00,n._a16,n._a32,n._a48]),n=new Uint8Array(n.buffer)):(n=ar(t,r),n=new Uint16Array([n._low,n._high]),n=new Uint8Array(n.buffer)),n}function wr(t,e=111,r=ur){return nr.encode(pr(t,e,r))}e(Le,er),e(v,Le);import dr from"path";var mr=/[<>:"/\\|?*\u0000-\u001F]/,yr=/^(con|prn|aux|nul|com\d|lpt\d)$/i,br=100,gr=/^\.+(\\|\/)|^\.+$/,xr=/\.+$/,vr=/[\u0000-\u001F\u0080-\u009F\u200E\u200F\u202A-\u202E\u2066-\u2069]/;function Er(){return new RegExp(mr.source,"g")}function Sr(){return new RegExp(vr.source,"g")}function $r(t){return t&&!(mr.test(t)||Sr().test(t)||gr.test(t)||xr.test(t))}function kr(t){const e=t.split(dr.sep);return("/"===t[0]||e[0]&&dr.dirname(e[0])===e[0])&&e.shift(),e.every($r)}function Ar(t,e={}){const r=e.replacement||"!";if((mr.test(r)||vr.test(r))&&x("Replacement string cannot contain reserved filename characters","sanitizeFilename",400),r.length>0){const e=/([<>:"/\\|?*\u0000-\u001F]){2,}/;t=t.replace(e,"$1")}if(t=(t=(t=(t=(t=t.normalize("NFD")).replace(gr,r)).replace(Er(),r)).replace(Sr(),r)).replace(xr,""),r.length>0){"."===t[0]||"."!==t[0]||(t=r+t),"."===t[t.length-1]&&(t+=r)}t=yr.test(t)?t+r:t;const n="number"==typeof e.maxLength?e.maxLength:br;if(t.length>n){const e=t.lastIndexOf(".");if(-1===e)t=t.slice(0,n);else{const r=t.slice(0,e),s=t.slice(e);t=r.slice(0,Math.max(1,n-s.length))+s}}return t}function Tr(t,e={}){const r=t.split(dr.sep);let n;("/"===t[0]||r[0]&&dr.dirname(r[0])===r[0])&&(n=r.shift());const s=r.map((t=>Ar(t,e)));return void 0!==n&&s.unshift(n),s.join(dr.sep)}function Or(t,e=1){let r="";for(;e--;){const e=dr.extname(t);if(!e)break;r=e+r,t=dr.basename(t,e)}return r}function Cr(t){return t.split(".").length-1}import{isRegExpStr as jr,toRegExp as Nr}from"util-ex";function Fr(t,e){if("string"!=typeof t)throw new w("modelName must be a string","isModelNameMatched",400);switch(typeof e){case"string":if(jr(e)){const r=(e=Nr(e)).exec(t);if(r)return r}else if(t.toLowerCase()===e.toLowerCase())return e;break;case"object":if(Array.isArray(e)){for(const r of e)if("string"==typeof r){if(jr(r)){const n=(e=Nr(r)).exec(t);if(n)return n}else if(t.toLowerCase()===r.toLowerCase())return r}else if(r instanceof RegExp){const e=r.exec(t);if(e)return e}else if("function"==typeof r){const e=r.call(this,t);if(e)return e}}else if(e instanceof RegExp){const r=e.exec(t);if(r)return r}break;case"function":const r=e.call(this,t);if(r)return r}}function Ir(t){return Object.keys(t).filter((t=>Number.isNaN(Number(t))))}import{newFunction as Mr}from"util-ex";function Rr(t,e){if(e){const r=Object.keys(e);if(r.length){const n=Object.values(e);return Mr("expression",r,`return ${t}`)(...n)}}return Mr("expression",[],`return ${t}`)()}function Pr(t){return t?Br(t,[],""):[]}function Br(t,e,r="."){return Array.isArray(t)?t.flatMap(((t,r)=>Br(t,[...e,`[${r}]`]))):(n=t)&&n.constructor===Object?Object.entries(t).flatMap((([t,n])=>Br(n,[...e,r+t]))):[e.join("")];var n}function Ur(t){if(t<2)throw new w("repetitionThreshold must be greater than 1","createEndWithRepetitionDetector",400);const e=new RegExp(`([\\S\\s]+)(\\1{${t-1},})$`);return function(t){return e.exec(t)}}import Vr from"path";import*as Lr from"fs";function _r(t,e,r,n){let s;if(Vr.isAbsolute(t)?s=Lr.existsSync(t)?t:qr(Vr.basename(t),[Vr.dirname(t)],r,n?.exclude):(e||(e=["."]),s=qr(t,e,r,n?.exclude)),!s)throw new m(t,"loadFileFromPaths");{const t=s;s=Lr.readFileSync(s),n&&(n.filepath=t)}return s}function qr(t,e,r,n=[]){let s;const i=r?r.map((e=>Or(t,Cr(e)))):void 0;"string"==typeof n&&(n=[n]);for(const o of e){const e=Vr.resolve(o,t);if(i)for(let t=0;t<i.length;t++){const o=e+(i[t]!==r[t]?r[t]:"");if(!n.includes(o)&&Lr.existsSync(o)){s=o;break}}else if(!n.includes(e)&&Lr.existsSync(e)){s=e;break}}return s}function zr(t,e,r,n,s){let i;"string"==typeof n?(i=n,n=void 0):i=n?.encoding??"utf8";return _r(t,e,r,n).toString(i)}function Dr(t,e){const r=[],n="string"==typeof t?[t]:[...t],s=new Set;for(;n.length>0;){const t=Jr(n.pop()),i=Vr.resolve(t);if(s.has(i))continue;s.add(i);const o=Lr.statSync(t,{throwIfNoEntry:!1});if(o?.isDirectory()){const s=Lr.readdirSync(t,{withFileTypes:!0});for(let i=0;i<s.length;i++){const o=s[i],a=Vr.join(t,o.name);o.isDirectory()?n.push(a):!o.isFile()||e&&!e(a)||r.push(a)}}}return r}function Jr(t){const e=Lr.lstatSync(t,{throwIfNoEntry:!1});return e?.isSymbolicLink()&&(t=Lr.readlinkSync(t)),t}import{existsSync as Wr,mkdirSync as Hr,readdirSync as Gr,statSync as Kr,writeFileSync as Xr}from"fs";import Yr from"path";import{Config as Zr}from"load-config-file";import{parse as Qr,stringify as tn}from"yaml";import{regexp as en}from"yaml-types";import{mimeType as rn}from"mime-type/with-db";import{stringify as nn}from"yaml";var sn=[en];function on(t){Array.isArray(t)||(t=[t]);for(const e of t){-1===sn.indexOf(e)&&sn.push(e)}}function an(t){return Qr(t,{customTags:sn})}function cn(t,e){const r=[],n=e?.after,s=e?.exclude?"string"==typeof e.exclude?[e.exclude]:e.exclude:void 0,i=e?.extensions?"string"==typeof e.extensions?[e.extensions]:e.extensions.map((t=>t.startsWith(".")?t:"."+t)):[".yml",".yaml",".json"];return function(t,e){const r=Gr(t,{withFileTypes:!0,recursive:!0});for(const n of r){const r=Yr.join(t,n.name);n.isFile()&&e(r,n)}}(t,((t,e)=>{if(s?.includes(t))return;const o=Yr.extname(t),a=Kr(t);if(i.includes(o)){if(n?.hasOwnProperty(t)&&a.mtimeMs<=n[t])return;r.push(t)}})),r}function un(t,e){return cn(t,e).map((t=>Zr.loadSync(t))).filter((t=>void 0!==t))}function hn(t,e,r=1){"."===t[0]&&r++;const n=Or(t,r);(!n||n.split(".").length<=1)&&(t+=".yaml");const s=rn.lookup(t);if("application/json"===s)e=JSON.stringify(e,null,2);else{if("text/yaml"!==s)throw new Error(`${t} unsupported mime type: ${s}`);e=tn(e)}const i=Yr.dirname(t);Wr(i)||Hr(i,{recursive:!0}),Xr(t,e,{encoding:"utf8"})}function ln(t){t instanceof Date&&(t=t.toISOString());return function(t,e){return t?`'${e}'`:String(e)}("string"==typeof t,t)}function fn(t,e){return t.map((t=>dn(t,e))).join(" AND ")}function pn(t,e){return t.map((t=>dn(t,e))).join(" OR ")}function wn(t,e){const r=[];return Object.keys(e).forEach((n=>{const s=e[n];switch(n){case"$lt":case"<":r.push(`${t} < ${ln(s)}`);break;case"<=":case"$lte":r.push(`${t} <= ${ln(s)}`);break;case"$gt":case">":r.push(`${t} > ${ln(s)}`);break;case"$gte":case">=":r.push(`${t} >= ${ln(s)}`);break;case"$ne":case"!=":r.push(`${t} != ${ln(s)}`);break;case"=":case"$eq":r.push(`${t} = ${ln(s)}`);break;case"$in":r.push(`${t} IN (${s.map((t=>ln(t))).join(", ")})`);break;case"$nin":r.push(`${t} NOT IN (${s.map((t=>ln(t))).join(", ")})`);break;case"$regex":r.push(`${t} REGEXP '${s.source}'`);break;case"$like":r.push(`${t} LIKE '${s}'`);break;case"$nlike":r.push(`${t} NOT LIKE '${s}'`);break;case"$glob":r.push(`${t} GLOB '${s}'`);break;case"$nglob":r.push(`${t} NOT GLOB '${s}'`);break;default:throw new Error(`Unsupported condition operator: ${n}`)}})),r.join(" AND ")}function dn(t,e){const r=[];if("function"!=typeof e&&(e=t=>t),Array.isArray(t))r.push(fn(t,e));else for(const[n,s]of Object.entries(t))if("$and"===n)r.push(`(${fn(t[n],e)})`);else if("$or"===n)r.push(`(${pn(t[n],e)})`);else{const t=typeof s;if(null==s)r.push(`${e(n)} IS NULL`);else if(s instanceof Date)r.push(`${e(n)}='${s.toISOString()}'`);else if("object"!==t||Array.isArray(s))if("string"===t)r.push(`${e(n)}='${s}'`);else{if("number"!==t&&"boolean"!==t)throw new Error(`Unsupported value type for key ${n}`);r.push(`${e(n)}=${s}`)}else r.push(wn(e(n),s))}return r.length>1?r.join(" AND "):r[0]}function mn(t){const e=t.indexOf("://");if(e>0)return t.substring(0,e)}function yn(t,e=0){let r,n=t*10**e;return t>=1e12?(n=Math.round(n/1e12),r="T"):t>=1e9?(n=Math.round(n/1e9),r="B"):t>=1e6?(n=Math.round(n/1e6),r="M"):t>=1e3?(n=Math.round(n/1e3),r="K"):(n=Math.round(n),r=""),n/=10**e,n.toFixed(e)+r}function bn(t){const e=t.match(/^\s*[+]?(\d+(?:[.]\d+)?)\s*([TBMK])?\s*$/i);if(!e)throw new w("Invalid formatted parameter size string.","scaleToSize",400);const r=parseFloat(e[1]),n=e[2]?.toLowerCase();switch(n){case"t":return 1e12*r;case"b":return 1e9*r;case"m":return 1e6*r;case"k":return 1e3*r;default:return r}}function gn(t,e){const r=e?.level||0,n=e?.visiting||new Set,s=e?.objectTag||"*",i=e?.arrayTag||"-";let o=[];const a=" ".repeat(2*r);if(null!=t)switch(typeof t){case"object":n.has(t)?o=["[Circular]"]:(n.add(t),o=Array.isArray(t)?t.map((t=>i+c(t))):Object.entries(t).map((([t,e])=>s+" `"+t+"`:"+c(e))));break;case"string":return t;default:return JSON.stringify(t)}else o=["null"];return o.length?a+o.join("\n"+a):"";function c(t){return(null!=t&&"object"==typeof t?"\n":" ")+gn(t,{level:r+1,visiting:n})}}Zr.register([".yml",".yaml"],an),Zr.register([".json"],(function(t){return JSON.parse(t)}));var xn=class t{constructor(t=0){this.bitField=t}static has(t,e){return!!(t&1<<e)}static add(t,e){return t|1<<e}static delete(t,e){return t&~(1<<e)}add(t){return this.bitField|=1<<t,this}delete(t){return this.bitField&=~(1<<t),this}has(e){return t.has(this.bitField,e)}clear(){return this.bitField=0,this}valueOf(){return this.bitField}toString(){return this.bitField.toString()}toJSON(){return this.bitField}};import{EventEmitter as vn}from"events-ex";var En=32;function Sn(t){return e=Math.min(Math.max(16,t),1073741824),e>>>=0,e-=1,e|=e>>1,e|=e>>2,e|=e>>4,e|=e>>8,1+(e|=e>>16);var e}var $n=class{constructor(t){this._capacity=Sn(t),this._length=0,this._front=0,this.arr=[]}push(t){const e=this._length;this.checkCapacity(e+1);const r=this._front+e&this._capacity-1;return this.arr[r]=t,this._length=e+1,r}pop(){const t=this._length;if(0===t)return;const e=this._front+t-1&this._capacity-1,r=this.arr[e];return this.arr[e]=void 0,this._length=t-1,r}shift(){const t=this._length;if(0===t)return;const e=this._front,r=this.arr[e];return this.arr[e]=void 0,this._front=e+1&this._capacity-1,this._length=t-1,r}get length(){return this._length}checkCapacity(t){this._capacity<t&&this.resizeTo(Sn(1.5*this._capacity+16))}resizeTo(t){const e=this._capacity;this._capacity=t;const r=this._front,n=this._length;if(r+n>e){const t=r+n&e-1;!function(t,e,r,n,s){for(let i=0;i<s;++i)r[i+n]=t[i+e],t[i+e]=void 0}(this.arr,0,this.arr,e,t)}}},kn=class extends vn{};function An(t){return"function"==typeof t}function Tn(){return"1"}var On=class{constructor(t,{initFn:e=Tn,pauseFn:r,resumeFn:n,capacity:s=En}={}){if(An(r)!==An(n))throw new Error("pauseFn and resumeFn must be both set for pausing");this.maxConcurrency=t,this.free=new $n(t),this.waiting=new $n(s),this.releaseEmitter=new kn,this.useDefaultTokens=e===Tn,this.pauseFn=r,this.resumeFn=n,this.paused=!1,this.releaseEmitter.on("release",(t=>{const e=this.waiting.shift();e?e.resolve(t):(this.resumeFn&&this.paused&&(this.paused=!1,this.resumeFn()),this.free.push(t))}));for(let r=0;r<t;r++)this.free.push(e())}tryAcquire(){return this.free.pop()}acquire(t){let e=this.tryAcquire();return void 0!==e?Promise.resolve(e):new Promise(((e,r)=>{this.pauseFn&&!this.paused&&(this.paused=!0,this.pauseFn());const n=this.waiting.push({resolve:e,reject:r});return t&&t.addEventListener("abort",(()=>{this.waiting[n]=void 0;const e=t.reason instanceof Error?t.reason:new Error(t.reason||"aborted");t.alreadyRejected=!0,r(e)})),n}))}release(t){this.releaseEmitter.emit("release",this.useDefaultTokens?"1":t)}drain(){const t=new Array(this.maxConcurrency);for(let e=0;e<this.maxConcurrency;e++)t[e]=this.acquire();return Promise.all(t)}pendingCount(){return this.waiting.length}};function Cn(t,{timeUnit:e=1e3,uniformDistribution:r=!1}={}){const n=new On(r?1:t),s=r?e/t:e;return async function(){await n.acquire(),setTimeout((()=>n.release()),s)}}import{createAbilityInjector as jn}from"custom-ability";import{defineProperty as Nn}from"util-ex";var Fn=class extends AbortController{constructor(t){super(),Nn(this,"parent",t)}abort(t,e){this.signal.aborted||("string"==typeof t&&(t=new b(t)),t&&e&&"object"==typeof t&&Object.assign(t.data,e),super.abort(t))}throwRejected(t){const e=this.signal;if(e.aborted){if(void 0===t&&(t=e.alreadyRejected),t)return!0;throw e.reason instanceof Error?e.reason:new b(e.reason||"aborted")}}},In=class{get maxTaskConcurrency(){return this._maxTaskConcurrency}get semaphore(){const t=this._maxTaskConcurrency;let e=this.__task_semaphore;return t>0&&!e&&(e=this.__task_semaphore=new On(t-1)),e}isAborted(t){const e=this.hasAsyncFeature(Pn);let r=this.__task_aborter;if(r&&e){if(null==t)throw new w("Missing taskId",this.name+".isAborted",400);r=r[t]}return!r||r.signal.aborted}getRunningTask(t){const e=this.hasAsyncFeature(Pn);let r=this.__task_aborter;if(r&&e){if(null==t)throw new w("Missing taskId",this.name+".getRunningTask",400);r=r[t]}return r?.signal.aborted&&(e?this.__task_aborter[t]=void 0:this.__task_aborter=void 0,r=void 0),r}getRunningTaskCount(){let t;if(this.hasAsyncFeature(Pn)){const e=this.__task_aborter;t=e&&Object.entries(e).filter((([t,r])=>{if(!r?.signal.aborted)return!0;e[t]=void 0})).length}else{const e=this.__task_aborter;t=e?.signal.aborted?0:1}return t}_generateAsyncTaskId(t,e){if(e||(e=this.__task_aborter),null==t&&(t=0,e))for(;e[t];)t++;return t}$generateAsyncTaskId(t,e){const r=this.super,n=this.self||this;return t=r?r.call(n,t):this._generateAsyncTaskId(t,e)}createAborter(t,e,r=!0){const n=this.hasAsyncFeature(Pn);if(!n&&r&&this.getRunningTask())throw new w("The task is running",this.name,429);const s=t?.aborter||new Fn(this);if(!(s instanceof Fn)){if(!(s instanceof AbortController))throw new w("aborter should be an AbortController",this.name,400);Object.setPrototypeOf(s,new Fn(this))}if(n){null==this.__task_aborter&&(this.__task_aborter={});const t=this.__task_aborter;null==e&&(e=this.generateAsyncTaskId(e,t)),s.id=e,t[e]=s}else this.__task_aborter=s;const i=t?.timeout;return i>0&&(s.timeoutId=setTimeout((()=>{s.timeoutId=void 0,this.abort("timeout",{timeout:i})}),i)),s.signal.addEventListener("abort",(()=>{const t=s.timeoutId;t&&(s.timeoutId=void 0,clearTimeout(t));const e=s.signal;try{this.emit&&this.emit("aborting",e.reason,e.reason?.data)}finally{s.streamController?.error(e.reason)}})),s}$cleanMultiTaskAborter(t,e){const r=this.super,n=this.self||this;r?r.call(n,t,e):n._cleanMultiTaskAborter(t,e)}cleanTaskAborter(t){if(this.hasAsyncFeature(Pn)){const e=this.__task_aborter;this.cleanMultiTaskAborter(t.id,e)}else this.__task_aborter=void 0}_cleanMultiTaskAborter(t,e){"number"==typeof t?e[t]=void 0:delete e[t]}createTaskPromise(t,e,r){const n=this.createAborter(e,r?.taskId,r?.raiseError);void 0===e&&(e={}),"object"==typeof e&&(e.aborter=n);let s=t(e,n).then((t=>{if(t&&t instanceof ReadableStream){const e=()=>{this.cleanTaskAborter(n)},r=Ve({onStart:t=>{Nn(n,"streamController",t)},onFinal:e,onError:e,onTransform:(t,e)=>(t&&"object"==typeof t&&(t.taskId=n.id),t)});t=t.pipeThrough(r)}else this.cleanTaskAborter(n);return t})).catch((t=>{throw this.cleanTaskAborter(n),t})).finally((()=>{n.timeoutId&&(clearTimeout(n.timeoutId),n.timeoutId=void 0)}));return s.task=n,s}runAsyncCancelableTask(t={},e,r){let n=this.createTaskPromise(e,t,r);const s=this.semaphore;if(s){const t=n,e=t.task;n=s.acquire(e.signal).then((()=>t)).finally((()=>{s.release()})),n.task=e}return n}abort(t,e){let r=this.__task_aborter;if(r){const n=r;if(this.hasAsyncFeature(Pn)){const t=e?.taskId;if(null==t)throw new w("Missing data.taskId",this.name+".abort",400);r=r[t],this.cleanMultiTaskAborter(t,n)}else this.__task_aborter=void 0;r&&!r.signal.aborted&&r.abort(t,e)}}};In.prototype.generateAsyncTaskId=function(t,e){return this._generateAsyncTaskId(t,e)},In.prototype.cleanMultiTaskAborter=function(t,e){return this._cleanMultiTaskAborter(t,e)};var Mn,Rn=jn(In,"abort",{afterInjection:function(t,e){let r=t.prototype._asyncFeatures||0;r|=Ln.Cancelable,e&&(e.asyncFeatures&&(r|=e.asyncFeatures),e.maxTaskConcurrency>0&&(t.prototype._maxTaskConcurrency=e.maxTaskConcurrency)),t.prototype._asyncFeatures=r}}),Pn=0,Bn=1,Un=2,Vn=(t=>(t[t.MultiTask=Pn]="MultiTask",t[t.Cancelable=1]="Cancelable",t[t.Priority=2]="Priority",t))(Vn||{}),Ln=((Mn=Ln||{})[Mn.MultiTask=1<<Pn]="MultiTask",Mn[Mn.Cancelable=2]="Cancelable",Mn[Mn.Priority=4]="Priority",Mn),_n=class t extends n{static{this.items={}}static get(t){return this.items[t]}static list(){return this.items}static getByTag(t){let e;for(const r in this.list()){const n=this.get(r);let s=n.tags;if("string"==typeof s){if(s===t){e=n;break}}else if(Array.isArray(s)&&s.indexOf(t)>=0){e=n;break}}return e}static getAllByTag(t){let e=[];for(const r in this.list()){const n=this.get(r);let s=n.tags;"string"==typeof s?s===t&&e.push(n):Array.isArray(s)&&s.indexOf(t)>=0&&e.push(n)}return e}static hasAsyncFeature(t){const e=this.prototype;let r=e.asyncFeatures;return e._asyncFeatures&&(r|=e._asyncFeatures),xn.has(r,t)}static run(t,e){const r=this.get(t);if(r)return r.run(e);throw new m(`${t} to run`,this.name)}static runSync(t,e){const r=this.get(t);if(r)return r.runSync(e);throw new m(`${t} to run`,this.name)}static getFunc(t){const e=this.get(t);return e?.getFunc()}static runWithPos(t,...e){const r=this.get(t);if(r)return r.runWithPos(...e);throw new m(`${t} to run`,this.name)}static runWithPosSync(t,...e){const r=this.get(t);if(r)return r.runWithPosSync(...e);throw new m(`${t} to run`,this.name)}static getFuncWithPos(t){const e=this.get(t);return e?.getFuncWithPos()}static register(e,r={}){switch(typeof e){case"string":r.name=e;break;case"function":r.func=e;break;case"object":r=e}e=r.name;let n=!!this.get(e);if(n)n=!1;else{if(!(r instanceof t))return n=new this(r),n.register();this.items[e]=r,n=r}return n}static unregister(t){const e=this.items[t];return e&&delete this.items[t],e}constructor(t,e={}){switch(super(),typeof t){case"string":e.name=t;break;case"function":e.func=t;break;case"object":e=t}this.name=t=e.name,e.scope&&(this.scope=e.scope),"function"==typeof e.setup&&e.setup.call(this,e),this.initialize(e)}register(){const e=this.constructor,r=this.depends;if(r){const e=Object.keys(r);for(const n of e){const e=r[n];e instanceof t&&e.register()}}return e.register(this)}unregister(){return this.constructor.unregister(this.name)}arr2ObjParams(t){if(this.params&&(t.length>1||Array.isArray(t[0])||t[0]&&"object"!=typeof t[0])){const e={},r=Object.keys(this.params);let n=Math.min(r.length,t.length);for(let s=0;s<n;s++)e[r[s]]=t[s];t=[e]}return t}obj2ArrParams(t){const e=[];if(t&&this.params&&Array.isArray(this.params)){const r=Object.keys(t);let n=Math.min(r.length,this.params.length);for(let s=0;s<n;s++)e.push(t[r[s]])}return e}runSync(t){const e=this.params&&Array.isArray(this.params);if(Array.isArray(t)){if(e)return this.func(...t);x("the function is not support array params, the params must be object!",this.name)}return e?(t=this.obj2ArrParams(t),console.warn('Warning:Use runWithPos() instead of run() for the "'+this.name+'" is function with position params'),this.func(...t)):this.func(t)}run(t){return this.runSync(t)}runAs(t,e){return this.runAsSync(t,e)}runAsSync(t,e){return this.constructor.runSync(t,e)}getFunc(t){return t?this.constructor.getFunc(t):this.runSync.bind(this)}runWithPosSync(...t){return this.params&&!Array.isArray(this.params)&&(t=this.arr2ObjParams(t)),this.func(...t)}runWithPosAsSync(t,...e){return this.constructor.runWithPosSync(t,...e)}runWithPos(...t){return this.runWithPosSync(...t)}runWithPosAs(t,...e){return this.runWithPosAsSync(t,...e)}getFuncWithPos(t){return t?this.constructor.getFuncWithPos(t):this.runWithPosSync.bind(this)}hasAsyncFeature(t){let e=this.asyncFeatures;return this._asyncFeatures&&(e|=this._asyncFeatures),xn.has(e,t)}},qn={name:{type:"string"},description:{type:"string"},func:{type:"function",assign(t,e,r,n,i){let o=t;const a=typeof t;return i.isExported?o="function"===a?t.toString():t:t&&("string"!==a&&(t=t.toString()),o=s(t,e.scope)),o}},params:{type:"object"},result:{type:"any"},setup:{type:"function"},depends:{type:"object",exported:!1},tags:{type:["array","string"]},asyncFeatures:{type:"number"}};_n.defineProperties(_n,qn);var zn=class extends _n{constructor(){super(...arguments),this._emitter=new r,this.description="Return event bus",this.result="event"}get emitter(){return this._emitter}func(){return this.emitter}},Dn=new zn(Se);import{Cache as Jn}from"secondary-cache";function Wn({key:t,value:e,options:r}={}){return void 0!==t?null===e?this.cache.del(t):void 0!==e?this.cache.set(t,e,r):this.cache.get(t):(r&&this.cache.setDefaultOptions(r),this.cache)}function Hn(t,e){let r=_n.get(t);return r||(r=new _n(t,{func:Wn,description:"get/set LRU cache or return the LRUCache object",params:{key:{name:"key",type:"string",description:"the key is undefined means change the default cache options"},value:{name:"value",type:"any",description:"the value to store, if value is null means remove the key"},options:{name:"options",type:"object|number",description:"the optional cache options:{capacity,expires,cleanInterval} or expires"}},result:"any"}),r.cache=new Jn(e)),r}var Gn=Hn("lrucache"),Kn=class t extends _n{static get apiRoot(){return t._apiRoot}static setApiRoot(e){t._apiRoot=e}static async loadFrom(){if(this._apiRoot){const t=await fetch(this._apiRoot,{headers:{"Content-Type":"application/json"}}),e=await t.json();e&&this.loadFromSync(e)}else x("missing apiRoot to load tools","ClientTools")}static loadFromSync(e){for(const r in e){const n=this.get(r),s=e[r];n?n instanceof t?n.assign(s):x(`${r} already registered as ${n.constructor.name}`,"ClientTools"):this.register(s)}}static async fetch(t,e){const r=this.get(t);if(r&&r.fetch)return r.fetch(e)}getUrlParams(t){if(void 0!==t){const e=JSON.stringify(t);if("{}"!==e&&"[]"!==e&&'""'!==e)return"?p="+encodeURIComponent(e)}return""}async fetch(t,e,r){const n={...this.fetchOptions};let s;n.headers&&n.headers["Content-Type"]||(n.headers={"Content-Type":"application/json",...n.headers}),t?.stream&&!n.headers.Connection&&(n.headers.Connection="keep-alive"),e||(e=this.action||"post"),"res"===e&&(e="get"),r?("string"!=typeof r&&(r=JSON.stringify(r)),r=this.name+"/"+r):r=this.name,n.method=e.toUpperCase(),"get"===e||"delete"===e?s=r+this.getUrlParams(t):(n.body=JSON.stringify(t),s=r);const i=await fetch(`${this.apiRoot}/${s}`,n);if(!i.ok){throw await this.errorFrom(i)}return i}async errorFrom(t){let e,r=t.status,n=t.statusText,s=this.name;if(t.body){const r=await t.text();try{const t=JSON.parse(r);t&&(t.error&&(n=t.error),t.name&&(s=t.name),t.data&&(e=t.data,e.name=s,e.what&&(e.msg=n,n=e.what)),t.message&&(n=n+":"+t.message))}catch(t){console.warn("🚀 ~ parse error body to json:",t)}}return g(n,s,r)}async func(t){const e=await this.fetch(t);if(t?.stream)return e;return await e.json()}},Xn={...k};Kn.defineProperties(Kn,Xn);var Yn=class extends Kn{async fetch(t,e){if(t||(t={}),e&&"res"===this.action){if("get"===e||"delete"===e){let r=t.id;return r||x("id is required"),"string"==typeof r&&(r=encodeURIComponent(r)),delete t.id,super.fetch(t,e,r)}"list"===e?e="get":e.startsWith("$")&&(t.act=e,e="post")}return await super.fetch(t,e)}async _func(t,e){const r=await this.fetch(e,t);if(e?.stream)return r;return await r.json()}async func(t){const e=t.action;return e&&delete t.action,this._func(e,t)}assignMethods(t){if(Array.isArray(t))for(const e of t){const t=e.startsWith("$")?e.slice(1):e;this[t]||(this[t]=(t=>this._func.bind(this,t))(e))}}},Zn={methods:{type:"array",assign(t,e,r,n,s){s?.isExported||e.assignMethods(t)}}};Yn.defineProperties(Yn,Zn);var Qn=class extends Yn{constructor(){super(...arguments),this._sseEvents={},this._forwardEvents=new Set,this.name=Ee,this.description="subscribe server sent event",this.ebListener=async function(...t){const e=this.type;this.target.publish&&await this.target.publish({data:t,event:e})}}get evtSource(){let t=this._es;return t&&t.readyState!==EventSource.CLOSED||(t=this.initEventSource(this._esEvents)),t}get active(){return!!this._es&&this._es.readyState!==EventSource.CLOSED}set active(t){t!==this.active&&(t?this.initEventSource(this._esEvents):this._es&&(this._es.close(),this._es=void 0))}initEventSource(t){if("string"==typeof t&&(t=[t]),this._es&&this._es.readyState!==EventSource.CLOSED){if(!this._esEvents||t&&t.every((t=>this._esEvents.includes(t))))return this._es;this._es.close()}const e=t?this.getUrlParams({event:t}):"",r=`${this.apiRoot}/${this.name}${e}`,n=this._es=new EventSource(r);return Object.entries(this._sseEvents).forEach((([t,e])=>{n.addEventListener(t,e)})),this._esEvents=t,n}esListener(t){const e=t.data?JSON.parse(t.data):void 0,r=t.type;if(!this._forwardEvents.has(r)){const t=this.emitter;t&&e&&r&&(Array.isArray(e)?t.emit(r,...e):t.emit(r,e))}}async subscribe(t){const e=await this.sub({event:t});"string"==typeof t&&(t=[t]);const r=this.evtSource;for(const e of t)if(!this._sseEvents[e]){const t=this._sseEvents[e]=this.esListener.bind(this);r.addEventListener(e,t)}return e}async unsubscribe(t){const e=await this.unsub({event:t});"string"==typeof t&&(t=[t]);for(const e of t){const t=this._sseEvents[e];t&&(delete this._sseEvents[e],this.evtSource.removeEventListener(e,t))}return e}forwardEvent(t){"string"==typeof t&&(t=[t]);for(const e of t)this._forwardEvents.has(e)||(this._forwardEvents.add(e),this.on&&this.on(e,this.ebListener))}unforwardEvent(t){"string"==typeof t&&(t=[t]);for(const e of t)this._forwardEvents.has(e)&&(this._forwardEvents.delete(e),this.off&&this.off(e,this.ebListener))}async init(t){if(this.active=!1,this.initEventSource(t),t)return await this.subscribe(t)}},ts=new Qn(Ee);import{getAllNames as es}from"util-ex";var rs=class t extends _n{static get apiRoot(){return t._apiRoot}static setApiRoot(e){t._apiRoot=e}static toJSON(){const e={};for(const r in this.items){let n=this.items[r];n instanceof t&&(n.allowExportFunc||(n=n.toJSON(),delete n.func),e[r]=n)}return e}isStream(t){return this.stream}func({}){}},ns={...k};rs.defineProperties(rs,ns);var ss=class extends rs{constructor(t,e={}){super(t,e),this.action="res",this.params={id:{type:"string"},val:{type:"any"}};const r=this.methods=[];for(const t of $)"function"==typeof this[t]&&r.push(t);es(Object.getPrototypeOf(this)).filter((t=>t.startsWith("$")&&"function"==typeof this[t])).forEach((t=>{r.push(t);const e=t.slice(1);void 0===this[e]&&(this[e]=this[t])}))}cast(t,e){let r=this.params[t];return r&&("string"!=typeof r&&(r=r.type),"number"===r&&(e=Number(e))),e}getMethodFromParams(t){let e=t?._req?.method?.toLowerCase();return"get"===e&&void 0===t.id&&(e="list"),"post"===e&&t.act&&(e=t.act),e}func(t){const e=this.getMethodFromParams(t);if(e&&"function"==typeof this[e])return void 0!==t.id&&(t.id=this.cast("id",t.id)),this[e](t);throw new m(e,this.name)}},is={methods:{type:"array"}};ss.defineProperties(ss,is);var os=Dn.runSync(),as=class t extends ss{constructor(){super(...arguments),this.name=Ee,this.description="subscribe server sent event",this.result="event",this.depends={[Se]:Dn}}static get sse(){return this._sse||(this._sse=new Te),this._sse}get sse(){return this.constructor.sse}static publish(e,r){return t.sse.publish(e,r)}static{this.ebListener=function(...e){t.sse.publish(e,this.type)}}static subscribe(e,r,n){return t.sse.subscribe(e,r,n)}static alreadyForward(e){const r=os.listeners(e);for(const e of r)if(e===t.ebListener)return!0}publishSSE(t,e){return this.constructor.publish(t,e)}subscribeSSE(t,e,r){return"string"==typeof r&&(r=[r]),this.constructor.subscribe(t,e,r)}forward(e){Array.isArray(e)||(e=[e]);for(const r of e)t.alreadyForward(r)||os.on(r,t.ebListener)}unforward(e){"string"==typeof e&&(e=[e]);for(const r of e)os.off(r,t.ebListener)}list({_req:t,_res:e,event:r}){t&&e&&this.subscribeSSE(t,e,r)}$sub({event:t}){if(t)return this.forward(t),{event:t};x("event is required","sub",400)}$unsub({event:t}){if(t)return this.unforward(t),{event:t};x("event is required","unsub",400)}$publish({event:t,data:e}){if(t&&e){"string"==typeof t&&(t=[t]);for(const r of t)this.publishSSE(e,r);return{event:t}}x("event or data is required","pub",400)}isStream(t){return"list"===this.getMethodFromParams(t)}},cs=new as(Ee);function us(){Dn.register(),Gn.register()}export{S as PASSING_SCORE,$ as ActionNames,k as RemoteToolFuncSchema,a as ErrorCode,c as InternalErrorCode,u as NotImplementedErrorCode,h as NotFoundErrorCode,l as AlreadyExistsErrorCode,f as AbortErrorCode,p as BaseError,w as CommonError,d as NotImplementationError,m as NotFoundError,y as AlreadyExistsError,b as AbortError,g as createError,x as throwError,T as parseDateFormat,I as toDateTime,M as textToDate,R as dateToText,C as formatISO,j as parseISO,N as toDate,P as AITextGenerationFinishReasons,B as AIMessageTypes,U as AIChatRoles,V as messagesToText,L as PromptTypes,_ as PromptTemplateTypes,z as defaultTemplateFormat,D as PromptTemplate,H as PromptExampleSelector,et as tokenize,$t as parse,Vt as Interpreter,zt as builtins,Dt as EnvironmentEx,Jt as Template,Kt as HfPromptTemplate,Xt as createHfValueFunc,Yt as parseFString,Zt as interpolateFString,te as FStringPromptTemplate,re as interpolateGolangTemplate,ne as GolangPromptTemplate,se as sortedValues,ie as FewShotPromptTemplate,ce as interpolateEnv,ue as expandEnv,he as expandObjEnv,be as splitSentence,ge as truncTo,xe as wait,Ee as EventName,Se as EventBusName,$e as backendEventable,Ae as SSEChannelAlreadyClosedErrCode,Te as SSEChannel,Oe as isWebStream,Ce as RStreamErrCode,je as ResponseRStreamErrCode,Ne as ReadableStreamError,Fe as getResponseErrorReadableStream,Ie as createEmptyReadableStream,Re as createEventStreamTransformer,Pe as trimStartOfStreamHelper,Be as AIStream,Ue as readableFromAsyncIterable,Ve as createCallbacksTransformer,tr as uuid,Je as v1,We as v4,He as v5,Ge as stringify,Ke as parse2,Xe as validate,Ye as version,Ze as NIL,or as base32768,hr as xxhash32,lr as xxhash64,fr as XXHashAlgorithm,pr as xxhash,wr as xxhashAsStr,mr as FilenameReservedRegex,yr as WindowsReservedNameRegex,Er as filenameReservedRegex,Sr as reControlCharsRegex,$r as isValidFilename,kr as isValidFilepath,Ar as sanitizeFilename,Tr as sanitizeFilepath,Or as getMultiLevelExtname,Cr as extNameLevel,Fr as isModelNameMatched,Ir as getAllEnumKeys,Rr as parseJsJson,Pr as getKeysPath,Ur as createEndWithRepetitionDetector,_r as loadFileFromPaths,zr as loadTextFromPaths,Dr as readFilenamesRecursiveSync,Jr as getRealFilepath,Zr as ConfigFile,rn as mimeType,on as registerYamlTag,an as parseYaml,cn as getConfigFileNames,un as getConfigs,hn as saveConfigFile,nn as stringify2,dn as jsonFilterToWhere,mn as matchUrlProtocol,yn as paramsSizeToScaleStr,bn as scaleStrToParamsSize,gn as jsonToMarkdownStr,xn as IntSet,En as DefaultAsyncSemaphoreCapacity,On as Semaphore,Cn as RateLimit,Pn as ToolAsyncMultiTaskBit,Bn as ToolAsyncCancelableBit,Un as ToolAsyncPriorityBit,Vn as AsyncFeatureBits,Ln as AsyncFeatures,_n as ToolFunc,qn as ToolFuncSchema,Fn as TaskAbortController,In as CancelableAbility,Rn as makeToolFuncCancelable,v as utils_exports,E as createAbilityInjector,Kn as ClientTools,Xn as ClientToolFuncSchema,rs as ServerTools,ns as ServerToolFuncSchema,zn as EventToolFunc,Dn as event,Wn as _lrucache,Hn as createLRUCache,Gn as lrucache,Yn as ResClientTools,Zn as ResClientToolsSchema,Qn as EventClient,ts as eventClient,ss as ResServerTools,is as ResServerToolsSchema,as as EventServer,cs as eventServer,us as registerCoreTools};
package/dist/funcs.d.mts CHANGED
@@ -1,4 +1,4 @@
1
- export { W as EventClient, V as EventClientFuncParams, Z as EventServer, Y as EventServerFuncParams, M as EventToolFunc, _ as _lrucache, Q as createLRUCache, O as event, X as eventClient, $ as eventServer, U as lrucache, L as registerCoreTools } from './index-japi6bEq.mjs';
1
+ export { a1 as EventClient, a0 as EventClientFuncParams, a4 as EventServer, a3 as EventServerFuncParams, X as EventToolFunc, _ as _lrucache, Z as createLRUCache, Y as event, a2 as eventClient, a5 as eventServer, $ as lrucache, W as registerCoreTools } from './index-Dgo3ZXPQ.mjs';
2
2
  import 'events-ex';
3
3
  import 'property-manager';
4
4
  import 'secondary-cache';
package/dist/funcs.d.ts CHANGED
@@ -1,4 +1,4 @@
1
- export { W as EventClient, V as EventClientFuncParams, Z as EventServer, Y as EventServerFuncParams, M as EventToolFunc, _ as _lrucache, Q as createLRUCache, O as event, X as eventClient, $ as eventServer, U as lrucache, L as registerCoreTools } from './index-japi6bEq.js';
1
+ export { a1 as EventClient, a0 as EventClientFuncParams, a4 as EventServer, a3 as EventServerFuncParams, X as EventToolFunc, _ as _lrucache, Z as createLRUCache, Y as event, a2 as eventClient, a5 as eventServer, $ as lrucache, W as registerCoreTools } from './index-Dgo3ZXPQ.js';
2
2
  import 'events-ex';
3
3
  import 'property-manager';
4
4
  import 'secondary-cache';