@isdk/ai-tool 0.1.1 → 0.1.3

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-L3P7XZYM.mjs +1 -0
  2. package/dist/funcs.js +1 -1
  3. package/dist/funcs.mjs +1 -1
  4. package/dist/index.d.mts +30 -28
  5. package/dist/index.d.ts +30 -28
  6. package/dist/index.js +1 -1
  7. package/dist/index.mjs +1 -1
  8. package/dist/test/util.mjs +1 -1
  9. package/docs/classes/AbortError.md +8 -8
  10. package/docs/classes/AlreadyExistsError.md +8 -8
  11. package/docs/classes/BaseError.md +8 -8
  12. package/docs/classes/CancelableAbility.md +20 -20
  13. package/docs/classes/ClientTools.md +74 -74
  14. package/docs/classes/CommonError.md +8 -8
  15. package/docs/classes/ConfigFile.md +19 -19
  16. package/docs/classes/EventClient.md +96 -96
  17. package/docs/classes/EventServer.md +97 -97
  18. package/docs/classes/EventToolFunc.md +65 -65
  19. package/docs/classes/FStringPromptTemplate.md +47 -47
  20. package/docs/classes/FewShotPromptTemplate.md +51 -51
  21. package/docs/classes/GolangPromptTemplate.md +47 -47
  22. package/docs/classes/HFEnvironment.md +9 -9
  23. package/docs/classes/HFInterpreter.md +19 -19
  24. package/docs/classes/HFTemplate.md +4 -4
  25. package/docs/classes/HfPromptTemplate.md +47 -47
  26. package/docs/classes/IntSet.md +12 -12
  27. package/docs/classes/NotFoundError.md +8 -8
  28. package/docs/classes/NotImplementationError.md +8 -8
  29. package/docs/classes/PromptExampleSelector.md +8 -8
  30. package/docs/classes/PromptTemplate.md +46 -46
  31. package/docs/classes/ReadableStreamError.md +8 -8
  32. package/docs/classes/ResClientTools.md +80 -80
  33. package/docs/classes/ResServerTools.md +81 -81
  34. package/docs/classes/SSEChannel.md +15 -15
  35. package/docs/classes/Semaphore.md +14 -14
  36. package/docs/classes/ServerTools.md +70 -70
  37. package/docs/classes/TaskAbortController.md +7 -7
  38. package/docs/classes/ToolFunc.md +62 -62
  39. package/docs/enums/AsyncFeatureBits.md +3 -3
  40. package/docs/enums/AsyncFeatures.md +3 -3
  41. package/docs/enums/ErrorCode.md +21 -21
  42. package/docs/enums/XXHashAlgorithm.md +2 -2
  43. package/docs/interfaces/AIChatAssistantMessageParam.md +6 -6
  44. package/docs/interfaces/AIChatContentPartImage.md +2 -2
  45. package/docs/interfaces/AIChatContentPartText.md +2 -2
  46. package/docs/interfaces/AIChatMessageParamBase.md +1 -1
  47. package/docs/interfaces/AIChatMessageToolCall.md +3 -3
  48. package/docs/interfaces/AIChatSystemMessageParam.md +3 -3
  49. package/docs/interfaces/AIChatToolMessageParam.md +4 -4
  50. package/docs/interfaces/AIChatUserMessageParam.md +7 -7
  51. package/docs/interfaces/AIChoiceConfig.md +7 -7
  52. package/docs/interfaces/AIResult.md +5 -5
  53. package/docs/interfaces/AIStreamParser.md +1 -1
  54. package/docs/interfaces/AIStreamParserOptions.md +1 -1
  55. package/docs/interfaces/BaseFunc.md +9 -9
  56. package/docs/interfaces/BaseFuncItem.md +8 -8
  57. package/docs/interfaces/CancelableAbilityOptions.md +8 -8
  58. package/docs/interfaces/ClientFuncItem.md +11 -11
  59. package/docs/interfaces/DotenvExpandOptions.md +3 -3
  60. package/docs/interfaces/DotenvExpandOutput.md +2 -2
  61. package/docs/interfaces/EventClientFuncParams.md +4 -4
  62. package/docs/interfaces/EventServerFuncParams.md +5 -5
  63. package/docs/interfaces/FewShotPromptTemplateOptions.md +11 -11
  64. package/docs/interfaces/FuncItem.md +9 -9
  65. package/docs/interfaces/FuncParam.md +6 -6
  66. package/docs/interfaces/ParseObjectArgumentOptions.md +63 -0
  67. package/docs/interfaces/PromptExampleSelectorOptions.md +2 -2
  68. package/docs/interfaces/PromptTemplateOptions.md +6 -6
  69. package/docs/interfaces/RemoteFuncItem.md +11 -11
  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 +12 -12
  74. package/docs/interfaces/ServerFuncParams.md +2 -2
  75. package/docs/interfaces/StreamCallbacksAndOptions.md +4 -4
  76. package/docs/interfaces/TaskPromise.md +1 -1
  77. package/docs/interfaces/ToolFuncPackage.md +3 -3
  78. package/docs/modules.md +203 -181
  79. package/package.json +12 -10
  80. package/dist/chunk-4LD7IUUG.mjs +0 -1
  81. package/dist/chunk-U5DDQYSF.mjs +0 -1
  82. package/docs/interfaces/IOptions.md +0 -30
package/dist/funcs.js CHANGED
@@ -1 +1 @@
1
- "use strict";var t,e=Object.create,r=Object.defineProperty,n=Object.getOwnPropertyDescriptor,s=Object.getOwnPropertyNames,i=Object.getPrototypeOf,o=Object.prototype.hasOwnProperty,a=(t,e)=>{for(var n in e)r(t,n,{get:e[n],enumerable:!0})},c=(t,e,i,a)=>{if(e&&"object"==typeof e||"function"==typeof e)for(let c of s(e))o.call(t,c)||c===i||r(t,c,{get:()=>e[c],enumerable:!(a=n(e,c))||a.enumerable});return t},u=(t,e,r)=>(c(t,e,"default"),r&&c(r,e,"default")),l=(t,n,s)=>(s=null!=t?e(i(t)):{},c(!n&&t&&t.__esModule?s:r(s,"default",{value:t,enumerable:!0}),t)),h={};a(h,{EventClient:()=>us,EventServer:()=>ys,EventToolFunc:()=>Yn,_lrucache:()=>es,createLRUCache:()=>rs,event:()=>Qn,eventClient:()=>ls,eventServer:()=>bs,lrucache:()=>ns,registerCoreTools:()=>gs}),module.exports=(t=h,c(r({},"__esModule",{value:!0}),t));var f=require("events-ex"),p=require("property-manager"),w=require("util-ex"),d=require("abstract-error"),m=(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))(m||{}),y=500,b=404,g=409,v=499,x=class t extends d.AbstractError{static createErrorClass(e,r,n=t){return(0,d.createErrorClass)(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}},E=class extends x{constructor(t,e,r=y){super(t,r,e)}},$=class extends E{constructor(t,e){t||(t="Not Implementation."),super(t,e,501)}};E[501]=$;var S=class extends E{static{this.code=b}constructor(t,e){super(`Could not find ${t}.`,e,b),this.data={what:t}}};E[404]=S;var k=class extends E{static{this.code=g}constructor(t,e){super(`The ${t} already exists.`,e,g),this.data={what:t}}};E[409]=k;var A=class extends E{static{this.code=v}constructor(t,e){e||(e="AbortError"),super(t?`The operation was aborted for ${t}.`:"The operation was aborted.",e,v),t&&(this.data={what:t})}};function O(t,e,r=y){const n=new(E[r]||E)(t,e,r);return"number"!=typeof n.code&&(n.code=r),n}function j(t,e,r=y){throw O(t,e,r)}E[499]=A;var T={};a(T,{AIArgProcessor:()=>Un,AIChatRoles:()=>L,AIMessageTypes:()=>_,AIStream:()=>De,AITextGenerationFinishReasons:()=>B,AbortError:()=>A,AbortErrorCode:()=>v,ActionNames:()=>I,AlreadyExistsError:()=>k,AlreadyExistsErrorCode:()=>g,BaseError:()=>x,CancelableAbility:()=>Cn,ChoiceArgProcessor:()=>qn,CommonError:()=>E,ConfigFile:()=>Zr.Config,DefaultAsyncSemaphoreCapacity:()=>gn,ErrorCode:()=>m,EventBusName:()=>Ne,EventName:()=>Ce,FStringPromptTemplate:()=>ce,FewShotPromptTemplate:()=>pe,FilenameReservedRegex:()=>wr,GolangPromptTemplate:()=>he,HFBuiltins:()=>Zt,HFEnvironment:()=>Yt,HFInterpreter:()=>Wt,HFTemplate:()=>Qt,HfPromptTemplate:()=>ne,IntSet:()=>yn,InternalErrorCode:()=>y,NotFoundError:()=>S,NotFoundErrorCode:()=>b,NotImplementationError:()=>$,NotImplementedErrorCode:()=>501,PASSING_SCORE:()=>N,PromptExampleSelector:()=>X,PromptTemplate:()=>H,PromptTemplateTypes:()=>D,PromptTypes:()=>J,RStreamErrCode:()=>qe,RateLimit:()=>An,ReadableStreamError:()=>Ue,RemoteToolFuncSchema:()=>F,ResponseRStreamErrCode:()=>Ve,SSEChannel:()=>Re,SSEChannelAlreadyClosedErrCode:()=>Me,Semaphore:()=>kn,TaskAbortController:()=>Tn,TemplateArgProcessor:()=>Vn,WindowsReservedNameRegex:()=>dr,XXHashAlgorithm:()=>lr,backendEventable:()=>Ie,base32768:()=>sr,countRegexMatches:()=>In,createAbilityInjector:()=>C.createAbilityInjector,createCallbacksTransformer:()=>Ke,createEmptyReadableStream:()=>_e,createEndWithRepetitionDetector:()=>Ur,createError:()=>O,createEventStreamTransformer:()=>ze,createHfValueFunc:()=>se,dateToText:()=>U,defaultTemplateFormat:()=>K,expandEnv:()=>ye,expandObjEnv:()=>be,extNameLevel:()=>Or,fileIsExists:()=>Lr,filenameReservedRegex:()=>vr,filterValidFnScope:()=>Pr,formatISO:()=>R.formatISO,getAllEnumKeys:()=>Cr,getConfigFileNames:()=>sn,getConfigs:()=>on,getKeysPath:()=>qr,getMultiLevelExtname:()=>Ar,getRealFilepath:()=>Kr,getResponseErrorReadableStream:()=>Be,hfParse:()=>Ct,hfTokenize:()=>it,interpolateEnv:()=>me,interpolateFString:()=>oe,interpolateGolangTemplate:()=>le,isModelNameMatched:()=>Tr,isValidFilename:()=>Er,isValidFilepath:()=>$r,isWebStream:()=>Pe,jsonFilterToWhere:()=>fn,jsonToMarkdownStr:()=>mn,loadFileFromPaths:()=>zr,loadTextFromPaths:()=>Dr,makeToolFuncCancelable:()=>Nn,matchUrlProtocol:()=>pn,messagesToText:()=>z,mimeType:()=>Qr.mimeType,paramsSizeToScaleStr:()=>wn,parseCommand:()=>Dn,parseDateFormat:()=>M.parse,parseFString:()=>ie,parseISO:()=>R.parseISO,parseJsJson:()=>Fr,parseObjectArgInfo:()=>zn,parseObjectArgumentInfos:()=>Pn,parseObjectArguments:()=>Rn,parseObjectArgumentsAsArgInfos:()=>Jn,parseYaml:()=>nn,quoteStr:()=>_n,reControlCharsRegex:()=>xr,readFilenamesRecursiveSync:()=>Wr,readableFromAsyncIterable:()=>We,registerYamlTag:()=>rn,sanitizeFilename:()=>Sr,sanitizeFilepath:()=>kr,saveConfigFile:()=>an,scaleStrToParamsSize:()=>dn,sortedValues:()=>fe,splitSentence:()=>Ae,stringifyYaml:()=>tn.stringify,textToDate:()=>V,throwError:()=>j,toDate:()=>R.toDate,toDateTime:()=>q,trimStartOfStreamHelper:()=>Je,truncTo:()=>Oe,uuid:()=>Qe,uuidNIL:()=>Xe.NIL,uuidParse:()=>Xe.parse,uuidStringify:()=>Xe.stringify,uuidValidate:()=>Xe.validate,uuidVersion:()=>Xe.version,uuidv1:()=>Xe.v1,uuidv4:()=>Xe.v4,uuidv5:()=>Xe.v5,wait:()=>je,xxhash:()=>hr,xxhash32:()=>cr,xxhash64:()=>ur,xxhashAsStr:()=>fr});var C=require("custom-ability"),N=.618,I=["get","post","put","delete","patch","list","res"],F={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"}},M=require("date-fns"),R=require("date-fns"),P="MMMM d, y 'at' h:m:s b 'GMT'x";function q(t){let e;try{"string"==typeof t?e=(0,M.parseISO)(t):"number"==typeof t?e=new Date(t):t instanceof Date&&(e=t)}catch(t){console.error(t)}return e}function V(t,e=P){return(0,M.parse)(t,e,new Date)}function U(t,e=P){return(0,M.format)(t,e)}var B=["stop","length","content-filter","tool-calls","abort","error","other",null],_=["human","ai","generic","system","tool"],L=["user","assistant","system","tool","tool_calls"];function z(t){let e="";for(const r of t)if(r.content){e+=r.role.toLowerCase()+":";let t=r.createdAt;if(t){const r=q(t);r&&(e+=" ["+U(r)+"]")}e+=" "+r.content+"\n"}return e}var J=["chat","char","plan"],D=["internal","hf","fill"],W=require("custom-factory");var K="default",H=class t extends W.BaseFactory{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||K,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||K);if(e)return Reflect.construct(e,arguments);throw new E(`Prompt template type ${n} not found`,"PromptTemplate",400)}}_initialize(t){throw new $("Not implemented","PromptTemplate")}initialize(e){this.constructor!==t&&(Object.assign(this,this.toJSON(e)),e?.ignoreInitialize||this._initialize(e))}_format(t){throw new $("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 G(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 Z=!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=>{Z=t}));var X=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,Z?n:G(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()}},Y=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",Macro:"Macro",EndMacro:"EndMacro"}),Q=Object.freeze({set:Y.Set,for:Y.For,in:Y.In,is:Y.Is,if:Y.If,else:Y.Else,endif:Y.EndIf,elif:Y.ElseIf,endfor:Y.EndFor,and:Y.And,or:Y.Or,not:Y.Not,"not in":Y.NotIn,macro:Y.Macro,endmacro:Y.EndMacro,true:Y.BooleanLiteral,false:Y.BooleanLiteral,True:Y.BooleanLiteral,False:Y.BooleanLiteral}),tt=class{constructor(t,e){this.value=t,this.type=e}};function et(t){return/\w/.test(t)}function rt(t){return/[0-9]/.test(t)}var nt=[["{%",Y.OpenStatement],["%}",Y.CloseStatement],["{{",Y.OpenExpression],["}}",Y.CloseExpression],["(",Y.OpenParen],[")",Y.CloseParen],["{",Y.OpenCurlyBracket],["}",Y.CloseCurlyBracket],["[",Y.OpenSquareBracket],["]",Y.CloseSquareBracket],[",",Y.Comma],[".",Y.Dot],[":",Y.Colon],["|",Y.Pipe],["<=",Y.ComparisonBinaryOperator],[">=",Y.ComparisonBinaryOperator],["==",Y.ComparisonBinaryOperator],["!=",Y.ComparisonBinaryOperator],["<",Y.ComparisonBinaryOperator],[">",Y.ComparisonBinaryOperator],["+",Y.AdditiveBinaryOperator],["-",Y.AdditiveBinaryOperator],["*",Y.MultiplicativeBinaryOperator],["/",Y.MultiplicativeBinaryOperator],["%",Y.MultiplicativeBinaryOperator],["=",Y.Equals]],st=new Map([["n","\n"],["t","\t"],["r","\r"],["b","\b"],["f","\f"],["v","\v"],["'","'"],['"','"'],["\\","\\"]]);function it(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=st.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===Y.CloseStatement||t===Y.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 tt(t,Y.Text));continue}}i((t=>/\s/.test(t)));const e=n[s];if("-"===e||"+"===e){const t=r.at(-1)?.type;if(t===Y.Text||void 0===t)throw new SyntaxError(`Unexpected character: ${e}`);switch(t){case Y.Identifier:case Y.NumericLiteral:case Y.BooleanLiteral:case Y.StringLiteral:case Y.CloseParen:case Y.CloseSquareBracket:break;default:{++s;const t=i(rt);r.push(new tt(`${e}${t}`,t.length>0?Y.NumericLiteral:Y.UnaryOperator));continue}}}for(const[t,e]of nt){if(n.slice(s,s+t.length)===t){r.push(new tt(t,e)),s+=t.length;continue t}}if("'"!==e&&'"'!==e)if(rt(e)){const t=i(rt);r.push(new tt(t,Y.NumericLiteral))}else{if(!et(e))throw new SyntaxError(`Unexpected character: ${e}`);{const t=i(et),e=Object.hasOwn(Q,t)?Q[t]:Y.Identifier;e===Y.In&&r.at(-1)?.type===Y.Not?(r.pop(),r.push(new tt("not in",Y.NotIn))):r.push(new tt(t,e))}}else{++s;const t=i((t=>t!==e));r.push(new tt(t,Y.StringLiteral)),++s}}return r}var ot=class{constructor(){this.type="Statement"}},at=class extends ot{constructor(t){super(),this.body=t,this.type="Program"}},ct=class extends ot{constructor(t,e,r){super(),this.test=t,this.body=e,this.alternate=r,this.type="If"}},ut=class extends ot{constructor(t,e,r,n){super(),this.loopvar=t,this.iterable=e,this.body=r,this.defaultBlock=n,this.type="For"}},lt=class extends ot{constructor(t,e){super(),this.assignee=t,this.value=e,this.type="Set"}},ht=class extends ot{constructor(t,e,r){super(),this.name=t,this.args=e,this.body=r,this.type="Macro"}},ft=class extends ot{constructor(){super(...arguments),this.type="Expression"}},pt=class extends ft{constructor(t,e,r){super(),this.object=t,this.property=e,this.computed=r,this.type="MemberExpression"}},wt=class extends ft{constructor(t,e){super(),this.callee=t,this.args=e,this.type="CallExpression"}},dt=class extends ft{constructor(t){super(),this.value=t,this.type="Identifier"}},mt=class extends ft{constructor(t){super(),this.value=t,this.type="Literal"}},yt=class extends mt{constructor(){super(...arguments),this.type="NumericLiteral"}},bt=class extends mt{constructor(){super(...arguments),this.type="StringLiteral"}},gt=class extends mt{constructor(){super(...arguments),this.type="BooleanLiteral"}},vt=class extends mt{constructor(){super(...arguments),this.type="ArrayLiteral"}},xt=class extends mt{constructor(){super(...arguments),this.type="TupleLiteral"}},Et=class extends mt{constructor(){super(...arguments),this.type="ObjectLiteral"}},$t=class extends ft{constructor(t,e,r){super(),this.operator=t,this.left=e,this.right=r,this.type="BinaryExpression"}},St=class extends ft{constructor(t,e){super(),this.operand=t,this.filter=e,this.type="FilterExpression"}},kt=class extends ft{constructor(t,e){super(),this.iterable=t,this.test=e,this.type="SelectExpression"}},At=class extends ft{constructor(t,e,r){super(),this.operand=t,this.negate=e,this.test=r,this.type="TestExpression"}},Ot=class extends ft{constructor(t,e){super(),this.operator=t,this.argument=e,this.type="UnaryExpression"}},jt=class extends ft{constructor(t=void 0,e=void 0,r=void 0){super(),this.start=t,this.stop=e,this.step=r,this.type="SliceExpression"}},Tt=class extends ft{constructor(t,e){super(),this.key=t,this.value=e,this.type="KeywordArgumentExpression"}};function Ct(t){const e=new at([]);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 Y.Text:e=new bt(n(Y.Text,"Expected text token").value);break;case Y.OpenStatement:e=function(){let e;switch(n(Y.OpenStatement,"Expected opening statement token"),t[r].type){case Y.Set:++r,e=a(),n(Y.CloseStatement,"Expected closing statement token");break;case Y.If:++r,e=c(),n(Y.OpenStatement,"Expected {% token"),n(Y.EndIf,"Expected endif token"),n(Y.CloseStatement,"Expected %} token");break;case Y.Macro:++r,e=function(){const t=x();if("Identifier"!==t.type)throw new SyntaxError("Expected identifier following macro statement");const e=y();n(Y.CloseStatement,"Expected closing statement token");const r=[];for(;i(Y.OpenStatement,Y.EndMacro);)r.push(s());return new ht(t,e,r)}(),n(Y.OpenStatement,"Expected {% token"),n(Y.EndMacro,"Expected endmacro token"),n(Y.CloseStatement,"Expected %} token");break;case Y.For:++r,e=function(){const t=u(!0);if(!(t instanceof dt||t instanceof xt))throw new SyntaxError(`Expected identifier/tuple for the loop variable, got ${t.type} instead`);n(Y.In,"Expected `in` keyword following loop variable");const e=l();n(Y.CloseStatement,"Expected closing statement token");const a=[];for(;i(Y.OpenStatement,Y.EndFor)&&i(Y.OpenStatement,Y.Else);)a.push(s());const c=[];if(o(Y.OpenStatement,Y.Else))for(++r,++r,n(Y.CloseStatement,"Expected closing statement token");i(Y.OpenStatement,Y.EndFor);)c.push(s());return new ut(t,e,a,c)}(),n(Y.OpenStatement,"Expected {% token"),n(Y.EndFor,"Expected endfor token"),n(Y.CloseStatement,"Expected %} token");break;default:throw new SyntaxError(`Unknown statement type: ${t[r].type} ${t[r].value}`)}return e}(),e.isStatement=!0;break;case Y.OpenExpression:e=function(){n(Y.OpenExpression,"Expected opening expression token");const t=l();return n(Y.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=l();if(o(Y.Equals)){++r;const e=a();return new lt(t,e)}return t}function c(){const e=l();n(Y.CloseStatement,"Expected closing statement token");const i=[],a=[];for(;t[r]?.type!==Y.OpenStatement||t[r+1]?.type!==Y.ElseIf&&t[r+1]?.type!==Y.Else&&t[r+1]?.type!==Y.EndIf;)i.push(s());if(t[r]?.type===Y.OpenStatement&&t[r+1]?.type!==Y.EndIf)if(++r,o(Y.ElseIf))n(Y.ElseIf,"Expected elseif token"),a.push(c());else for(n(Y.Else,"Expected else token"),n(Y.CloseStatement,"Expected closing statement token");t[r]?.type!==Y.OpenStatement||t[r+1]?.type!==Y.EndIf;)a.push(s());return new ct(e,i,a)}function u(t=!1){const e=t?x:l,n=[e()],s=o(Y.Comma);for(;s&&(++r,n.push(e()),o(Y.Comma)););return s?new xt(n):n[0]}function l(){return function(){const t=h();if(o(Y.If)){++r;const e=h();if(o(Y.Else)){++r;const n=h();return new ct(e,[t],[n])}return new kt(t,e)}return t}()}function h(){let e=f();for(;o(Y.Or);){const n=t[r];++r;const s=f();e=new $t(n,e,s)}return e}function f(){let e=p();for(;o(Y.And);){const n=t[r];++r;const s=p();e=new $t(n,e,s)}return e}function p(){let e;for(;o(Y.Not);){const n=t[r];++r;const s=p();e=new Ot(n,s)}return e??function(){let e=w();for(;o(Y.ComparisonBinaryOperator)||o(Y.In)||o(Y.NotIn);){const n=t[r];++r;const s=w();e=new $t(n,e,s)}return e}()}function w(){let e=g();for(;o(Y.AdditiveBinaryOperator);){const n=t[r];++r;const s=g();e=new $t(n,e,s)}return e}function d(){const e=function(){let e=x();for(;o(Y.Dot)||o(Y.OpenSquareBracket);){const s=t[r];let i;++r;const o=s.type!==Y.Dot;if(o)i=b(),n(Y.CloseSquareBracket,"Expected closing square bracket");else if(i=x(),"Identifier"!==i.type)throw new SyntaxError("Expected identifier following dot operator");e=new pt(e,i,o)}return e}();return o(Y.OpenParen)?m(e):e}function m(t){let e=new wt(t,y());return o(Y.OpenParen)&&(e=m(e)),e}function y(){n(Y.OpenParen,"Expected opening parenthesis for arguments list");const t=function(){const t=[];for(;!o(Y.CloseParen);){let e=l();if(o(Y.Equals)){if(++r,!(e instanceof dt))throw new SyntaxError("Expected identifier for keyword argument");const t=l();e=new Tt(e,t)}t.push(e),o(Y.Comma)&&++r}return t}();return n(Y.CloseParen,"Expected closing parenthesis for arguments list"),t}function b(){const t=[];let e=!1;for(;!o(Y.CloseSquareBracket);)o(Y.Colon)?(t.push(void 0),++r,e=!0):(t.push(l()),o(Y.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 jt(...t)}return t[0]}function g(){let e=v();for(;o(Y.MultiplicativeBinaryOperator);){const n=t[r];++r;const s=v();e=new $t(n,e,s)}return e}function v(){let t=function(){let t=d();for(;o(Y.Pipe);){++r;let e=x();if(!(e instanceof dt))throw new SyntaxError("Expected identifier for the filter");o(Y.OpenParen)&&(e=m(e)),t=new St(t,e)}return t}();for(;o(Y.Is);){++r;const e=o(Y.Not);e&&++r;let n=x();if(n instanceof gt&&(n=new dt(n.value.toString())),!(n instanceof dt))throw new SyntaxError("Expected identifier for the test");t=new At(t,e,n)}return t}function x(){const e=t[r];switch(e.type){case Y.NumericLiteral:return++r,new yt(Number(e.value));case Y.StringLiteral:return++r,new bt(e.value);case Y.BooleanLiteral:return++r,new gt("true"===e.value.toLowerCase());case Y.Identifier:return++r,new dt(e.value);case Y.OpenParen:{++r;const e=u();if(t[r].type!==Y.CloseParen)throw new SyntaxError(`Expected closing parenthesis, got ${t[r].type} instead`);return++r,e}case Y.OpenSquareBracket:{++r;const t=[];for(;!o(Y.CloseSquareBracket);)t.push(l()),o(Y.Comma)&&++r;return++r,new vt(t)}case Y.OpenCurlyBracket:{++r;const t=new Map;for(;!o(Y.CloseCurlyBracket);){const e=l();n(Y.Colon,"Expected colon between key and value in object literal");const s=l();t.set(e,s),o(Y.Comma)&&++r}return++r,new Et(t)}default:throw new SyntaxError(`Unexpected token: ${e.type}`)}}for(;r<t.length;)e.body.push(s());return e}function Nt(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 It(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 Ft(t){return t.replace(/\b\w/g,(t=>t.toUpperCase()))}var Mt=class{constructor(t=void 0){this.type="RuntimeValue",this.builtins=new Map,this.value=t}__bool__(){return new qt(!!this.value)}toString(){return""+this.value}toJSON(){return this.value}},Rt=class extends Mt{constructor(){super(...arguments),this.type="NumericValue"}},Pt=class t extends Mt{constructor(){super(...arguments),this.type="StringValue",this.builtins=new Map([["upper",new Lt((()=>new t(this.value.toUpperCase())))],["lower",new Lt((()=>new t(this.value.toLowerCase())))],["strip",new Lt((()=>new t(this.value.trim())))],["title",new Lt((()=>new t(Ft(this.value))))],["length",new Rt(this.value.length)],["rstrip",new Lt((()=>new t(this.value.trimEnd())))],["lstrip",new Lt((()=>new t(this.value.trimStart())))]])}},qt=class extends Mt{constructor(){super(...arguments),this.type="BooleanValue"}},Vt=class extends Mt{constructor(t,e){super(t),this.orgValue=e,this.type="ObjectValue",this.builtins=new Map([["get",new Lt((([t,e])=>{if(!(t instanceof Pt))throw new Error(`Object key must be a string: got ${t.type}`);return this.value.get(t.value)??e??new zt}))],["items",new Lt((()=>new Bt(Array.from(this.value.entries()).map((([t,e])=>new Bt([new Pt(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 qt(this.value.size>0)}},Ut=class extends Vt{constructor(){super(...arguments),this.type="KeywordArgumentsValue"}},Bt=class extends Mt{constructor(){super(...arguments),this.type="ArrayValue",this.builtins=new Map([["length",new Rt(this.value.length)]])}__bool__(){return new qt(this.value.length>0)}},_t=class extends Bt{constructor(){super(...arguments),this.type="TupleValue"}},Lt=class extends Mt{constructor(){super(...arguments),this.type="FunctionValue"}},zt=class extends Mt{constructor(){super(...arguments),this.type="NullValue"}},Jt=class extends Mt{constructor(){super(...arguments),this.type="UndefinedValue"}},Dt=class{constructor(t){this.parent=t,this.variables=new Map([["namespace",new Lt((t=>{if(0===t.length)return new Vt(new Map);if(1!==t.length||!(t[0]instanceof Vt))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 Lt],["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],["string",t=>"StringValue"===t.type],["number",t=>"NumericValue"===t.type],["integer",t=>"NumericValue"===t.type&&Number.isInteger(t.value)],["iterable",t=>t instanceof Bt||t instanceof Pt],["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],["eq",(t,e)=>t.value===e.value]])}set(t,e){return this.declareVariable(t,Kt(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 Jt}catch{return new Jt}}},Wt=class{constructor(t){this.global=t??new Dt}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 qt(r.value==n.value);case"!=":return new qt(r.value!=n.value)}if(r instanceof Jt||n instanceof Jt)throw new Error("Cannot perform operation on undefined values");if(r instanceof zt||n instanceof zt)throw new Error("Cannot perform operation on null values");if(r instanceof Rt&&n instanceof Rt)switch(t.operator.value){case"+":return new Rt(r.value+n.value);case"-":return new Rt(r.value-n.value);case"*":return new Rt(r.value*n.value);case"/":return new Rt(r.value/n.value);case"%":return new Rt(r.value%n.value);case"<":return new qt(r.value<n.value);case">":return new qt(r.value>n.value);case">=":return new qt(r.value>=n.value);case"<=":return new qt(r.value<=n.value)}else if(r instanceof Bt&&n instanceof Bt){if("+"===t.operator.value)return new Bt(r.value.concat(n.value))}else if(n instanceof Bt){const e=void 0!==n.value.find((t=>t.value===r.value));switch(t.operator.value){case"in":return new qt(e);case"not in":return new qt(!e)}}if((r instanceof Pt||n instanceof Pt)&&"+"===t.operator.value)return new Pt(r.toString()+n.toString());if(r instanceof Pt&&n instanceof Pt)switch(t.operator.value){case"in":return new qt(n.value.includes(r.value));case"not in":return new qt(!n.value.includes(r.value))}if(r instanceof Pt&&n instanceof Vt)switch(t.operator.value){case"in":return new qt(n.value.has(r.value));case"not in":return new qt(!n.value.has(r.value))}throw new SyntaxError(`Unknown operator "${t.operator.value}" between ${r.type} and ${n.type}`)}evaluateArguments(t,e){const r=[],n=new Map;for(const s of t)if("KeywordArgumentExpression"===s.type){const t=s;n.set(t.key.value,this.evaluate(t.value,e))}else{if(n.size>0)throw new Error("Positional arguments must come before keyword arguments");r.push(this.evaluate(s,e))}return[r,n]}evaluateFilterExpression(t,e){const r=this.evaluate(t.operand,e);if("Identifier"===t.filter.type){const n=t.filter,s=e.lookupVariable(n.value);if(s instanceof Lt)return s.value([r],e);if(r instanceof Bt)switch(n.value){case"list":return r;case"first":return r.value[0];case"last":return r.value[r.value.length-1];case"length":return new Rt(r.value.length);case"reverse":return new Bt(r.value.reverse());case"sort":return new Bt(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}`)}})));default:throw new Error(`Unknown ArrayValue filter: ${n.value}`)}else if(r instanceof Pt)switch(n.value){case"length":return new Rt(r.value.length);case"upper":return new Pt(r.value.toUpperCase());case"lower":return new Pt(r.value.toLowerCase());case"title":return new Pt(Ft(r.value));case"capitalize":return new Pt(r.value.charAt(0).toUpperCase()+r.value.slice(1));case"trim":return new Pt(r.value.trim());case"trimStart":return new Pt(r.value.trimStart());case"trimEnd":return new Pt(r.value.trimEnd());case"indent":return new Pt(r.value.split("\n").map(((t,e)=>0===e||0===t.length?t:" "+t)).join("\n"));case"string":return r;default:throw new Error(`Unknown StringValue filter: ${n.value}`)}else{if(r instanceof Rt){if("abs"===n.value)return new Rt(Math.abs(r.value));throw new Error(`Unknown NumericValue filter: ${n.value}`)}if(r instanceof Vt)switch(n.value){case"items":return new Bt(Array.from(r.value.entries()).map((([t,e])=>new Bt([new Pt(t),e]))));case"length":return new Rt(r.value.size);case"string":return new Pt(r.toString());default:throw new Error(`Unknown ObjectValue filter: ${n.value}`)}}throw new Error(`Cannot apply filter "${n.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 Lt){const[t,s]=this.evaluateArguments(n.args,e);return s.size>0&&t.push(new Ut(s)),i.value([r,...t],e)}if(r instanceof Bt){switch(s){case"selectattr":{if(r.value.some((t=>!(t instanceof Vt))))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 Bt(a)}case"map":{const[,t]=this.evaluateArguments(n.args,e);if(t.has("attribute")){const e=t.get("attribute");if(!(e instanceof Pt))throw new Error("attribute must be a string");const n=t.get("default"),s=r.value.map((t=>{if(!(t instanceof Vt))throw new Error("items in map must be an object");return t.value.get(e.value)??n??new Jt}));return new Bt(s)}throw new Error("`map` expressions without `attribute` set are not currently supported.")}}throw new Error(`Unknown ArrayValue filter: ${s}`)}if(r instanceof Pt){if("indent"===s){const[t,s]=this.evaluateArguments(n.args,e),i=t.at(0)??s.get("width")??new Rt(4);if(!(i instanceof Rt))throw new Error("width must be a number");const o=t.at(1)??s.get("first")??new qt(!1),a=t.at(2)??s.get("blank")??new qt(!1),c=r.value.split("\n"),u=" ".repeat(i.value),l=c.map(((t,e)=>!o.value&&0===e||!a.value&&0===t.length?t:u+t));return new Pt(l.join("\n"))}throw new Error(`Unknown StringValue 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 qt(t.negate?!s:s)}evaluateUnaryExpression(t,e){const r=this.evaluate(t.argument,e);if("not"===t.operator.value)return new qt(!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 Pt(r)}evaluateIdentifier(t,e){return e.lookupVariable(t.value)}evaluateCallExpression(t,e){const[r,n]=this.evaluateArguments(t.args,e);n.size>0&&r.push(new Ut(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 Bt||t instanceof Pt))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 Rt||n instanceof Jt))throw new Error("Slice start must be numeric or undefined");if(!(s instanceof Rt||s instanceof Jt))throw new Error("Slice stop must be numeric or undefined");if(!(i instanceof Rt||i instanceof Jt))throw new Error("Slice step must be numeric or undefined");return t instanceof Bt?new Bt(It(t.value,n.value,s.value,i.value)):new Pt(It(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 Pt(t.property.value);if(r instanceof Vt){if(!(n instanceof Pt))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 Bt||r instanceof Pt)if(n instanceof Rt)s=r.value.at(n.value),r instanceof Pt&&(s=new Pt(r.value.at(n.value)));else{if(!(n instanceof Pt))throw new Error(`Cannot access property with non-string/non-number: got ${n.type}`);s=r.builtins.get(n.value)}else{if(!(n instanceof Pt))throw new Error(`Cannot access property with non-string: got ${n.type}`);s=r.builtins.get(n.value)}return s instanceof Mt?s:new Jt}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 Vt))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 zt}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 Dt(e);let n,s;if("SelectExpression"===t.iterable.type){const e=t.iterable;s=this.evaluate(e.iterable,r),n=e.test}else s=this.evaluate(t.iterable,r);if(!(s instanceof Bt))throw new Error(`Expected iterable type in for loop: got ${s.type}`);const i=[],o=[];for(let e=0;e<s.value.length;++e){const a=new Dt(r),c=s.value[e];let u;if("Identifier"===t.loopvar.type)u=e=>e.setVariable(t.loopvar.value,c);else{if("TupleLiteral"!==t.loopvar.type)throw new Error(`Invalid loop variable(s): ${t.loopvar.type}`);{const e=t.loopvar;if("ArrayValue"!==c.type)throw new Error(`Cannot unpack non-iterable type: ${c.type}`);const r=c;if(e.value.length!==r.value.length)throw new Error(`Too ${e.value.length>r.value.length?"few":"many"} items to unpack`);u=t=>{for(let n=0;n<e.value.length;++n){if("Identifier"!==e.value[n].type)throw new Error(`Cannot unpack non-identifier type: ${e.value[n].type}`);t.setVariable(e.value[n].value,r.value[n])}}}}if(n){u(a);if(!this.evaluate(n,a).__bool__().value)continue}i.push(c),o.push(u)}let a="",c=!0;for(let e=0;e<i.length;++e){const n=new Map([["index",new Rt(e+1)],["index0",new Rt(e)],["revindex",new Rt(i.length-e)],["revindex0",new Rt(i.length-e-1)],["first",new qt(0===e)],["last",new qt(e===i.length-1)],["length",new Rt(i.length)],["previtem",e>0?i[e-1]:new Jt],["nextitem",e<i.length-1?i[e+1]:new Jt]]);r.setVariable("loop",new Vt(n)),o[e](r);a+=this.evaluateBlock(t.body,r).value,c=!1}if(c){a+=this.evaluateBlock(t.defaultBlock,r).value}return new Pt(a)}evaluateMacro(t,e){return e.setVariable(t.name.value,new Lt(((e,r)=>{const n=new Dt(r);let s;e=e.slice(),"KeywordArgumentsValue"===e.at(-1)?.type&&(s=e.pop());for(let r=0;r<t.args.length;++r){const i=t.args[r],o=e[r];if("Identifier"===i.type){const t=i;if(!o)throw new Error(`Missing positional argument: ${t.value}`);n.setVariable(t.value,o)}else{if("KeywordArgumentExpression"!==i.type)throw new Error(`Unknown argument type: ${i.type}`);{const t=i,e=o??s?.value.get(t.key.value)??this.evaluate(t.value,n);n.setVariable(t.key.value,e)}}}return this.evaluateBlock(t.body,n)}))),new zt}evaluate(t,e){if(void 0===t)return new Jt;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"Macro":return this.evaluateMacro(t,e);case"NumericLiteral":return new Rt(Number(t.value));case"StringLiteral":return new Pt(t.value);case"BooleanLiteral":return new qt(t.value);case"ArrayLiteral":return new Bt(t.value.map((t=>this.evaluate(t,e))));case"TupleLiteral":return new _t(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 Pt))throw new Error(`Object keys must be strings: got ${t.type}`);r.set(t.value,this.evaluate(s,e))}return new Vt(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 Kt(t){switch(typeof t){case"number":return new Rt(t);case"string":return new Pt(t);case"boolean":return new qt(t);case"undefined":return new Jt;case"object":return null===t?new zt:Array.isArray(t)?new Bt(t.map(Kt)):new Vt(new Map(Object.entries(t).map((([t,e])=>[t,Kt(e)]))),t);case"function":return new Lt(((e,r)=>{const n=e.map((t=>Ht(t)));return Kt(t(...n)??null)}));default:throw new Error(`Cannot convert to runtime value: ${t}`)}}function Ht(t){let e=t;if(Array.isArray(t))e=t.map((t=>Ht(t)));else if(t instanceof Map)e={},t.forEach(((t,r)=>{e[r]=Ht(t)}));else switch(t.type){case"NullValue":e=null;break;case"UndefinedValue":e=void 0;break;case"ArrayValue":e=t.value.map((t=>Ht(t)));break;case"KeywordArgumentsValue":case"ObjectValue":e=t.orgValue?t.orgValue:Ht(t.value),"KeywordArgumentsValue"===t.type&&Object.setPrototypeOf(e,{jinja_kargs:!0});break;default:t.type&&(e=t.value)}return e}function Gt(t,e=0){return Math.floor(Math.random()*(t-e+1))+e}var Zt={randomInt:Gt,select:function(t,e){if(Array.isArray(t)||"string"==typeof t)return void 0===e?e=Gt(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[Gt(r.length-1)]}return t[e]}},tojson:function(t,e,r){return e&&"object"==typeof e&&(e.depth&&(r=e.depth),e=e.indent),Xt(t,e,r)}};function Xt(t,e,r){let n="";const s=r??0;if(null===t)n="null";else{const r=typeof t;switch(r){case"undefined":n="null";case"number":case"string":case"boolean":return JSON.stringify(t);case"object":{const r=e?" ".repeat(e):"",n="\n"+r.repeat(s),i=n+r;if(Array.isArray(t)){const r=t.map((t=>Xt(t,e,s+1)));return e?`[${i}${r.join(`,${i}`)}${n}]`:`[${r.join(", ")}]`}{const r=Array.from(Object.entries(t)).map((([t,r])=>{const n=`"${t}": ${Xt(r,e,s+1)}`;return e?`${i}${n}`:n}));return e?`{${r.join(",")}${n}}`:`{${r.join(", ")}}`}}default:throw new Error(`Cannot convert to JSON: ${r}`)}}return n}var Yt=class extends Dt{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()}},Qt=class t{static{this.global=new Yt}constructor(t,e={}){const r=it(t,e={lstrip_blocks:!0,trim_blocks:!0,...e});this.parsed=Ct(r)}render(e){const r=new Dt(t.global);r.set("false",!1),r.set("true",!0),r.set("raise_exception",(t=>{throw new Error(t)})),r.set("range",Nt);for(const[t,n]of Object.entries(e))r.set(t,n);return new Wt(r).run(this.parsed).toString()}};function te(t,e){let r;switch(t.type){case"Identifier":r=t.value;break;case"MemberExpression":r=te(t.object,e);break;case"FilterExpression":r=te(t.operand,e);break;case"Set":{e||(e=[]);const n=te(t.assignee);n&&e.push(n),r=te(t.value,e);break}}return r&&e?.includes(r)&&(r=void 0),r}function ee(t){let e;if("Program"===t.type)e=t.body.some((t=>ee(t)));else e=t.isStatement;return e}function re(t,e){let r=[];if(Array.isArray(t))r=t.map((t=>re(t,e))).filter(Boolean).flat();else switch(t.type){case"Program":r=t.body.map((t=>re(t,e))).filter(Boolean).flat();break;case"If":r=[te(t.test,e),...re(t.body,e),...re(t.alternate,e)].filter(Boolean);break;case"BinaryExpression":r=[te(t.left,e),te(t.right,e)].filter(Boolean);break;case"For":{const n=te(t.loopvar);n&&(e||(e=[]),e.push(n)),r=[te(t.iterable,e),...re(t.body,e)].filter(Boolean);break}case"CallExpression":r=[te(t.callee,e),...re(t.args,e)].filter(Boolean);break;default:r=[te(t,e)].filter(Boolean)}return r}Qt.global.assign(Zt);var ne=class extends H{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 Qt(r)}catch(t){}return e&&(n=ee(e.parsed)),n}getVariables(t=this.compiledTemplate){return re(t.parsed,[]).filter(((t,e,r)=>r.indexOf(t)===e))}_initialize(t){const e=t?.template;if("string"!=typeof e)throw new E("Prompt template must be a string","PromptTemplate",400);this.compiledTemplate=new Qt(e),this.inputVariables=Array.isArray(t?.inputVariables)?t.inputVariables:this.getVariables()}_format(t){return this.compiledTemplate.render(t)}};function se(t){return function(e){return t}}function ie(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 oe(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 ae(t){const e=new Set;return t.forEach((t=>{"variable"===t.type&&e.add(t.name)})),[...e]}H.register(ne,{name:"hf",aliases:["huggingface","internal","default"]});var ce=class extends H{static isTemplate(t){let e,r,n=!1;if("object"==typeof t?(r=t.template,e=t.compiledTemplate):r=t,!e&&r)try{e=ie(r)}catch(t){}if(e){n=ae(e).length>0}return n}getVariables(t=this.compiledTemplate){return ae(t)}_initialize(t){const e=t?.template;if("string"!=typeof e)throw new E("Prompt template must be a string","PromptTemplate",400);this.compiledTemplate=ie(e),this.inputVariables=Array.isArray(t?.inputVariables)?t.inputVariables:this.getVariables()}_format(t){return oe(this.compiledTemplate,t)}};function ue(t,e){return"string"==typeof e&&(e=e.split(".").filter((t=>t.length))),e.reduce(((t,e)=>t?.[e]),t)}function le(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 ue(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):ue(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=ue(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=ue(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):ue(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=ue(e,n);let o;return o=isNaN(s)?i[s.substring(1,s.length-1)]:i[parseInt(s,10)],o||""}))}(n,e,r),n}H.register(ce,{name:"fstring",aliases:["python","f-string","langchain"]});var he=class extends H{static isTemplate(t){const e="string"==typeof t?t:t.template;return e?.includes("{{")&&e.includes("}}")}getVariables(t){const e={};return le(t,e,!0),[...Object.keys(e)]}_initialize(t){const e=t?.template;if("string"!=typeof e)throw new E("Prompt template must be a string","PromptTemplate",400);this.inputVariables=Array.isArray(t?.inputVariables)?t.inputVariables:this.getVariables(e)}_format(t){return le(this.template,t)}};function fe(t){return Object.keys(t).sort().map((e=>t[e]))}H.register(he,{name:"golang",aliases:["localai","ollama"]});var pe=class extends H{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 H?t.examplePrompt:H.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=fe(t);r.length>0&&e.push(...r)}const r=[this.prefix,...e,this.suffix].join(this.exampleSeparator),n=this.templateFormat;return await H.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}};H.register(pe,{name:"fewshot",aliases:["few_shot"]});var we=/(\\)?(\$)(?!\()(\{?)([\w.]+)(?::?-((?:\$\{(?:\$\{(?:\$\{[^}]*\}|[^}])*}|[^}])*}|[^}])+))?(\}?)/gi;function de(t){return t.replace(/\\\$/g,"$")}function me(t,e,r){return t.replace(we,((n,s,i,o,a,c,u)=>"\\"===s?n.slice(1):e[a]?e[a]===r[a]?e[a]:me(e[a],e,r):r[a]?r[a]===t?r[a]:me(r[a],e,r):c?c.startsWith("$")?me(c,e,r):c:""))}function ye(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]?me(n,e,t.parsed):e[r]:me(n,e,t.parsed),t.parsed[r]=n?de(n):n}for(const r in t.parsed)e[r]=t.parsed[r];return t}function be(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=me(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]=be(t[n],e,r))}else for(const[n,s]of Object.entries(t))"string"!=typeof s&&"object"!=typeof s||(t[n]=be(s,e,r))}return t}var ge="@",ve=/(\S.+?[.!?])(?=\s+|$)|(\S.+?)(?=[\n]|$)/g,xe=/([A-Z][a-z]{1,2}\.)\s(\w)/g,Ee=/(\.[a-zA-Z]\.)\s(\w)/g,$e=new RegExp("([A-Z][a-z]{1,2}\\.)"+ge+"(\\w)","g"),Se=new RegExp("(\\.[a-zA-Z]\\.)"+ge+"(\\w)","g");function ke(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 Ae(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=ke(s,ge,[xe,Ee]),o=Array.from(i.matchAll(ve));if(o.length)for(let t=0;t<o.length;t++){let e=ke(o[t][0]," ",[$e,Se]);n.push(e)}else n.push(s)}return n}function Oe(t,e=2,r=.5){const n=10**e;return Math.trunc((t+Number.EPSILON+r/n)*n)/n}async function je(t){return new Promise((e=>setTimeout(e,t)))}var Te=require("custom-ability"),Ce="event",Ne="event-bus";var Ie=(0,Te.createAbilityInjector)((function(t){return class{static get emitter(){if(!this._emitter){const t=this.get(Ne)?.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 Fe(t,e){return!t||t.some((t=>t instanceof RegExp?t.test(e):t===e))}var Me=498,Re=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||j("Channel closed","SSEChannel",Me);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||Fe(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||j("Channel closed","SSEChannel",Me);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=>Fe(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 Pe(t){return t instanceof ReadableStream||t instanceof WritableStream}var qe=600,Ve=601,Ue=class extends x{constructor(t,e=qe){super(t,500)}};function Be(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 Ue(`Response error: ${e}`,Ve))}}})}return new ReadableStream({start(t){t.error(new Ue("Response error: No response body",Ve))}})}function _e(){return new ReadableStream({start(t){t.close()}})}var Le=require("eventsource-parser");function ze(t){const e=new TextDecoder;let r;return new TransformStream({async start(e){r=(0,Le.createParser)((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 Je(){let t=!0;return e=>(t&&(e=e.trimStart())&&(t=!1),e)}function De(t,e){if(!t.ok)return Be(t.body);let r=t.body||new ReadableStream({start(t){t.close()}});return r instanceof ReadableStream||(r=ReadableStream.from(r)),r.pipeThrough(ze(e))}function We(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 Ke(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 He={};a(He,{XXHashAlgorithm:()=>lr,base32768:()=>sr,uuid:()=>Qe,uuidNIL:()=>Xe.NIL,uuidParse:()=>Xe.parse,uuidStringify:()=>Xe.stringify,uuidValidate:()=>Xe.validate,uuidVersion:()=>Xe.version,uuidv1:()=>Xe.v1,uuidv4:()=>Xe.v4,uuidv5:()=>Xe.v5,xxhash:()=>hr,xxhash32:()=>cr,xxhash64:()=>ur,xxhashAsStr:()=>fr});var Ge=require("uuid"),Ze=l(require("base32768")),Xe=require("uuid"),Ye={1:Ge.v1,4:Ge.v4,5:Ge.v5};function Qe(t=1,e){const r=Ye[t];return e?Ze.encode(r(null,[])):r()}var tr={};a(tr,{XXHashAlgorithm:()=>lr,base32768:()=>sr,xxhash:()=>hr,xxhash32:()=>cr,xxhash64:()=>ur,xxhashAsStr:()=>fr});var er=l(require("xxhashjs")),rr=l(require("base32768")),nr=require("json-canonicalize");u(tr,require("json-canonicalize"));var sr=rr,{h32:ir,h64:or}=er.default,ar=588213;function cr(t,e=16){return"object"==typeof t&&(t=(0,nr.canonicalize)(t)),ir(t,ar).toString(e)}function ur(t,e=16){return"object"==typeof t&&(t=(0,nr.canonicalize)(t)),or(t,ar).toString(e)}var lr=(t=>(t[t.xxhash64=111]="xxhash64",t[t.xxhash32=112]="xxhash32",t))(lr||{});function hr(t,e=111,r=ar){let n;return t.buffer&&(t=t.buffer),112!==e?(n=or(t,r),n=new Uint16Array([n._a00,n._a16,n._a32,n._a48]),n=new Uint8Array(n.buffer)):(n=ir(t,r),n=new Uint16Array([n._low,n._high]),n=new Uint8Array(n.buffer)),n}function fr(t,e=111,r=ar){return rr.encode(hr(t,e,r))}u(He,tr),u(T,He);var pr=l(require("path")),wr=/[<>:"/\\|?*\u0000-\u001F]/,dr=/^(con|prn|aux|nul|com\d|lpt\d)$/i,mr=100,yr=/^\.+(\\|\/)|^\.+$/,br=/\.+$/,gr=/[\u0000-\u001F\u0080-\u009F\u200E\u200F\u202A-\u202E\u2066-\u2069]/;function vr(){return new RegExp(wr.source,"g")}function xr(){return new RegExp(gr.source,"g")}function Er(t){return t&&!(wr.test(t)||xr().test(t)||yr.test(t)||br.test(t))}function $r(t){const e=t.split(pr.default.sep);return("/"===t[0]||e[0]&&pr.default.dirname(e[0])===e[0])&&e.shift(),e.every(Er)}function Sr(t,e={}){const r=e.replacement||"!";if((wr.test(r)||gr.test(r))&&j("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(yr,r)).replace(vr(),r)).replace(xr(),r)).replace(br,""),r.length>0){"."===t[0]||"."!==t[0]||(t=r+t),"."===t[t.length-1]&&(t+=r)}t=dr.test(t)?t+r:t;const n="number"==typeof e.maxLength?e.maxLength:mr;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 kr(t,e={}){const r=t.split(pr.default.sep);let n;("/"===t[0]||r[0]&&pr.default.dirname(r[0])===r[0])&&(n=r.shift());const s=r.map((t=>Sr(t,e)));return void 0!==n&&s.unshift(n),s.join(pr.default.sep)}function Ar(t,e=1){let r="";for(;e--;){const e=pr.default.extname(t);if(!e)break;r=e+r,t=pr.default.basename(t,e)}return r}function Or(t){return t.split(".").length-1}var jr=require("util-ex");function Tr(t,e){if("string"!=typeof t)throw new E("modelName must be a string","isModelNameMatched",400);switch(typeof e){case"string":if((0,jr.isRegExpStr)(e)){const r=(e=(0,jr.toRegExp)(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((0,jr.isRegExpStr)(r)){const n=(e=(0,jr.toRegExp)(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 Cr(t){return Object.keys(t).filter((t=>Number.isNaN(Number(t))))}var Nr=require("lodash-es"),Ir=require("util-ex");function Fr(t,e){if(e&&(e=Pr(e)),e){const r=Object.keys(e);if(r.length){const n=Object.values(e);return(0,Ir.newFunction)("expression",r,`return ${t}`)(...n)}}return(0,Ir.newFunction)("expression",[],`return ${t}`)()}var Mr=/^[a-zA-Z_$][0-9a-zA-Z_$]*$/,Rr=t=>Mr.test(t);function Pr(t){if(t){const e=Object.keys(t),r=e.length,n=e.filter((e=>Rr(e)&&null!==t[e]));if(r===n.length)return t;if(n.length)return t=(0,Nr.pick)(t,n)}}function qr(t){return t?Vr(t,[],""):[]}function Vr(t,e,r="."){return Array.isArray(t)?t.flatMap(((t,r)=>Vr(t,[...e,`[${r}]`]))):(n=t)&&n.constructor===Object?Object.entries(t).flatMap((([t,n])=>Vr(n,[...e,r+t]))):[e.join("")];var n}function Ur(t){if(t<2)throw new E("repetitionThreshold must be greater than 1","createEndWithRepetitionDetector",400);const e=new RegExp(`([\\S\\s]+)(\\1{${t-1},})$`);return function(t){return e.exec(t)}}var Br=l(require("path")),_r=l(require("fs"));function Lr(t){const e=_r.statSync(t,{throwIfNoEntry:!1});return e?.isFile()}function zr(t,e,r,n){const s=n?.signal,i=n?.exclude;let o;if(Br.default.isAbsolute(t)?o=Lr(t)?t:Jr(Br.default.basename(t),[Br.default.dirname(t)],{extNames:r,exclude:i,signal:s}):(e||(e=["."]),o=Jr(t,e,{extNames:r,exclude:i,signal:s})),!o)throw new S(t,"loadFileFromPaths");{const t=o;o=_r.readFileSync(o),n&&(n.filepath=t)}return o}function Jr(t,e,{extNames:r,signal:n,exclude:s=[]}){let i;const o=r?r.map((e=>Ar(t,Or(e)))):void 0;"string"==typeof s&&(s=[s]);for(const a of e){if(n?.aborted)throw n.reason;const e=Br.default.resolve(a,t);if(o)for(let t=0;t<o.length;t++){const n=e+(o[t]!==r[t]?r[t]:"");if(!s.includes(n)&&Lr(n)){i=n;break}}else if(!s.includes(e)&&Lr(e)){i=e;break}}return i}function Dr(t,e,r,n,s){let i;"string"==typeof n?(i=n,n=void 0):i=n?.encoding??"utf8";return zr(t,e,r,n).toString(i)}function Wr(t,e,r){const n=[],s="string"==typeof t?[t]:[...t],i=new Set;for(;s.length>0;){if(r?.aborted)throw r.reason;const t=Kr(s.pop()),o=Br.default.resolve(t);if(i.has(o))continue;i.add(o);const a=_r.statSync(t,{throwIfNoEntry:!1});if(a?.isDirectory()){const r=_r.readdirSync(t,{withFileTypes:!0});for(let i=0;i<r.length;i++){const o=r[i],a=Br.default.join(t,o.name);o.isDirectory()?s.push(a):!o.isFile()||e&&!e(a)||n.push(a)}}}return n}function Kr(t){const e=_r.lstatSync(t,{throwIfNoEntry:!1});return e?.isSymbolicLink()&&(t=_r.readlinkSync(t)),t}var Hr=require("fs"),Gr=l(require("path")),Zr=require("load-config-file"),Xr=require("yaml"),Yr=require("yaml-types"),Qr=require("mime-type/with-db"),tn=require("yaml"),en=[Yr.regexp];function rn(t){Array.isArray(t)||(t=[t]);for(const e of t){-1===en.indexOf(e)&&en.push(e)}}function nn(t){return(0,Xr.parse)(t,{customTags:en})}function sn(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=(0,Hr.readdirSync)(t,{withFileTypes:!0,recursive:!0});for(const n of r){const r=Gr.default.join(t,n.name);n.isFile()&&e(r,n)}}(t,((t,e)=>{if(s?.includes(t))return;const o=Gr.default.extname(t),a=(0,Hr.statSync)(t);if(i.includes(o)){if(n?.hasOwnProperty(t)&&a.mtimeMs<=n[t])return;r.push(t)}})),r}function on(t,e){return sn(t,e).map((t=>Zr.Config.loadSync(t))).filter((t=>void 0!==t))}function an(t,e,r=1){"."===t[0]&&r++;const n=Ar(t,r);(!n||n.split(".").length<=1)&&(t+=".yaml");const s=Qr.mimeType.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=(0,Xr.stringify)(e)}const i=Gr.default.dirname(t);return(0,Hr.existsSync)(i)||(0,Hr.mkdirSync)(i,{recursive:!0}),(0,Hr.writeFileSync)(t,e,{encoding:"utf8"}),t}function cn(t){t instanceof Date&&(t=t.toISOString());return function(t,e){return t?`'${e}'`:String(e)}("string"==typeof t,t)}function un(t,e){return t.map((t=>fn(t,e))).join(" AND ")}function ln(t,e){return t.map((t=>fn(t,e))).join(" OR ")}function hn(t,e){const r=[];return Object.keys(e).forEach((n=>{const s=e[n];switch(n){case"$lt":case"<":r.push(`${t} < ${cn(s)}`);break;case"<=":case"$lte":r.push(`${t} <= ${cn(s)}`);break;case"$gt":case">":r.push(`${t} > ${cn(s)}`);break;case"$gte":case">=":r.push(`${t} >= ${cn(s)}`);break;case"$ne":case"!=":r.push(`${t} != ${cn(s)}`);break;case"=":case"$eq":r.push(`${t} = ${cn(s)}`);break;case"$in":r.push(`${t} IN (${s.map((t=>cn(t))).join(", ")})`);break;case"$nin":r.push(`${t} NOT IN (${s.map((t=>cn(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 fn(t,e){const r=[];if("function"!=typeof e&&(e=t=>t),Array.isArray(t))r.push(un(t,e));else for(const[n,s]of Object.entries(t))if("$and"===n)r.push(`(${un(t[n],e)})`);else if("$or"===n)r.push(`(${ln(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(hn(e(n),s))}return r.length>1?r.join(" AND "):r[0]}function pn(t){const e=t.indexOf("://");if(e>0)return t.substring(0,e)}function wn(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 dn(t){const e=t.match(/^\s*[+]?(\d+(?:[.]\d+)?)\s*([TBMK])?\s*$/i);if(!e)throw new E("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 mn(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":" ")+mn(t,{level:r+1,visiting:n})}}Zr.Config.register([".yml",".yaml"],nn),Zr.Config.register([".json"],(function(t){return JSON.parse(t)}));var yn=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}},bn=require("events-ex"),gn=32;function vn(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 xn=class{constructor(t){this._capacity=vn(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(vn(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)}}},En=class extends bn.EventEmitter{};function $n(t){return"function"==typeof t}function Sn(){return"1"}var kn=class{constructor(t,{initFn:e=Sn,pauseFn:r,resumeFn:n,capacity:s=gn}={}){if($n(r)!==$n(n))throw new Error("pauseFn and resumeFn must be both set for pausing");this.maxConcurrency=t,this.free=new xn(t),this.waiting=new xn(s),this.releaseEmitter=new En,this.useDefaultTokens=e===Sn,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 An(t,{timeUnit:e=1e3,uniformDistribution:r=!1}={}){const n=new kn(r?1:t),s=r?e/t:e;return async function(){await n.acquire(),setTimeout((()=>n.release()),s)}}var On=require("custom-ability"),jn=require("util-ex"),Tn=class extends AbortController{constructor(t){super(),(0,jn.defineProperty)(this,"parent",t)}abort(t,e){this.signal.aborted||("string"==typeof t&&(t=new A(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 A(e.reason||"aborted")}}},Cn=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 kn(t-1)),e}isAborted(t){const e=this.hasAsyncFeature(Hn);let r=this.__task_aborter;if(r&&e){if(null==t)throw new E("Missing taskId",this.name+".isAborted",400);r=r[t]}return!r||r.signal.aborted}getRunningTask(t){const e=this.hasAsyncFeature(Hn);let r=this.__task_aborter;if(r&&e){if(null==t)throw new E("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(Hn)){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(Hn);if(!n&&r&&this.getRunningTask())throw new E("The task is running",this.name,429);const s=t?.aborter||new Tn(this);if(!(s instanceof Tn)){if(!(s instanceof AbortController))throw new E("aborter should be an AbortController",this.name,400);Object.setPrototypeOf(s,new Tn(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(Hn)){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=Ke({onStart:t=>{(0,jn.defineProperty)(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(Hn)){const t=e?.taskId;if(null==t)throw new E("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)}}};Cn.prototype.generateAsyncTaskId=function(t,e){return this._generateAsyncTaskId(t,e)},Cn.prototype.cleanMultiTaskAborter=function(t,e){return this._cleanMultiTaskAborter(t,e)};var Nn=(0,On.createAbilityInjector)(Cn,"abort",{afterInjection:function(t,e){let r=t.prototype._asyncFeatures||0;r|=Gn.Cancelable,e&&(e.asyncFeatures&&(r|=e.asyncFeatures),e.maxTaskConcurrency>0&&(t.prototype._maxTaskConcurrency=e.maxTaskConcurrency)),t.prototype._asyncFeatures=r}});function In(t,e){const r=e.global?e:new RegExp(e.source,`${e.flags}g`);let n,s=0;for(;null!==(n=r.exec(t));)s++;return s}var Fn=require("lodash-es"),Mn=require("util-ex");async function Rn(t,e,r){return Pn(Jn(t,e,r),e,r)}async function Pn(t,e,r){if(t.length){const n=await Promise.all(t.map(((t,n)=>zn(t,n,e,r?.argProcessor)))),s=r?.returnArrayOnly;let i=n?.length?Fr(`{${n.map((t=>function(t){const e={"\n":"\\n","\r":"\\r","\t":"\\t","\b":"\\b","\f":"\\f","\\":"\\\\"};return t.replace(/\\?[\n\r\t\b\f\\]/g,(t=>t.startsWith("\\")?t:e[t]))}(t))).join(",")}}`,e):void 0;if(i){const t=Object.keys(i);1===t.length&&void 0!==i[0]?i=i[0]:t.every((t=>!isNaN(parseInt(t))))&&(i=t.sort(((t,e)=>parseInt(t)-parseInt(e))).map((t=>i[t])))}if(i&&!s){const t=Object.entries(i);(1===t.length&&void 0!==i[0]||2===t.length&&"0"===t[0][0]&&t[0][1]===t[1][1])&&(i=i[0])}return i&&s&&1===Object.keys(i).length&&void 0!==i[0]?i[0]:i}}function qn(t,e,r){const[n,s]=t;if(!n&&"|"===s[0])return"choice: {"+function(t,e){const r=Jn(t,e,{delimiter:":"}),n={},s=r.map((([t,e],r)=>{if(t){const t=e.indexOf(":"),r=e.slice(0,t).trim();if(n[r])throw new Error("Only one "+r+" is allowed");return n[r]=!0,e}{if("|"===e[0]){if(n.items)throw new Error("Only one items is allowed");return n.items=!0,"items:["+function(t,e='"'){return t.map((t=>Bn(t)?t:e+t+e))}(e.split("|").filter(Boolean))+"]"}const t=parseInt(e.trim());if(!isNaN(t)){if(n.maxPick)throw new Error("Only one maxPick is allowed");return n.maxPick=!0,"maxPick:"+t}if("random"===e||"ai"===e)return n.type=!0,'type:"'+e+'"';if(Bn(e)){if(n.separator)throw new Error("Only one separator is allowed");return n.separator=!0,"separator:"+e}}}));return s}(s,r)+"}"}async function Vn([t,e],r,n){if(!n)return;let s,i;if(t){const t=e.split(":");s=t[0].trim(),i=t[1].trim()}else i=e,s=r+"";const o={template:i,data:n};n.templateFormat&&(o.templateFormat=n.templateFormat);const a=await H.formatIf(o);return a?(i=a,s+":"+_n(i)):void 0}async function Un(t,e,r){let n=qn(t,0,r);return n||(n=await Vn(t,e,r)),n}function Bn(t){const e=t[0];return('"'===e||"'"===e)&&t[t.length-1]===e}function _n(t){return'"'+t.replace(/(?<!\\)"(?!\\)/g,'\\"')+'"'}function Ln(t){return function(t,e=['""',"''","{}"]){return e.some((e=>t[0]===e[0]&&t[t.length-1]===e[1]))}(t)||!Number.isNaN(parseFloat(t))||"true"===t||"false"===t||(e=t,Wn.test(e));var e}async function zn(t,e,r,n){const[s,i]=t;if("function"==typeof n){const s=await n(t,e,r);if(s)return s}if(s)return i;if(r&&void 0!==(0,Fn.get)(r,i))return e+":"+i+', "'+i+'":'+i;if(Ln(i))return e+":"+i;try{const t=(0,Mn.newFunction)("async expression",[],`return ${i};`,Pr(r)),n=await t.call(this);switch(typeof n){case"number":case"boolean":case"undefined":return e+":"+n;case"function":return e+":"+t.toString();default:return e+":"+JSON.stringify(n)}}catch(t){}return e+":"+_n(i)}function Jn(t,e,r){const n=r?.delimiter??",";let s=[],i=!1,o="",a="",c=!1,u="";for(let e=0;e<t.length;e++){const r=t[e];if(r!==n||i||u)if("\\"===r)a+=r,e++,a+=t[e];else if("("!==r&&"["!==r||i)if(u&&r===u)u="",a+=r;else if("{"!==r||i)'"'===r||"'"===r?(i&&r===o?i=!1:i||(i=!0,o=r),a+=r):"="!==r||i||c||!/^[\p{L}\p{N}_ ]+$/u.test(a)?a+=r:(a+=":",c=!0);else{let n,s=e,i=!1,o="",c=-1;for(;s<t.length&&("}"!==(n=t[s])||i||c>0);)"\\"===n?s++:"{"!==n||i?"}"!==n||i?'"'!==n&&"'"!==n||(i&&r===o?i=!1:i||(i=!0,o=r)):c--:c++,s++;s<t.length&&(a+=t.substring(e,s+1),e=s)}else u="("===r?")":"]",a+=r;else a=a.trim(),a.endsWith(":")&&(a+="undefined"),s.push([c,a]),a="",c=!1}return a&&(a=a.trim(),a.endsWith(":")&&(a+="undefined"),s.push([c,a])),s}async function Dn(t,e,r){const n=t.match(/^([^(]+)(?:\((.*)\))?$/);if(!n)throw new Error("Invalid command format");const[,s,i]=n;let o;return i&&(o=await Rn(i,e,r)),{command:s.trim(),args:o}}var Wn=/^\s*\(\)|\(([a-zA-Z_$][\w\d$]*)(\s*,\s*([a-zA-Z_$][\w\d$]*))*\)=>/;var Kn,Hn=0,Gn=((Kn=Gn||{})[Kn.MultiTask=1<<Hn]="MultiTask",Kn[Kn.Cancelable=2]="Cancelable",Kn[Kn.Priority=4]="Priority",Kn),Zn=class t extends p.AdvancePropertyManager{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),yn.has(r,t)}static run(t,e){const r=this.get(t);if(r)return r.run(e);throw new S(`${t} to run`,this.name)}static runSync(t,e){const r=this.get(t);if(r)return r.runSync(e);throw new S(`${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 S(`${t} to run`,this.name)}static runWithPosSync(t,...e){const r=this.get(t);if(r)return r.runWithPosSync(...e);throw new S(`${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);j("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),yn.has(e,t)}isStream(t){return this.stream}},Xn={name:{type:"string"},description:{type:"string"},func:{type:"function",assign(t,e,r,n,s){let i=t;const o=typeof t;return s.isExported?i="function"===o?t.toString():t:t&&("string"!==o&&(t=t.toString()),i=(0,w._createFunction)(t,e.scope)),i}},params:{type:"object"},result:{type:"any"},setup:{type:"function"},depends:{type:"object",exported:!1},tags:{type:["array","string"]},isApi:{type:"boolean"},stream:{type:"boolean"},asyncFeatures:{type:"number"}};Zn.defineProperties(Zn,Xn);var Yn=class extends Zn{constructor(){super(...arguments),this._emitter=new f.EventEmitter,this.description="Return event bus",this.result="event"}get emitter(){return this._emitter}func(){return this.emitter}},Qn=new Yn(Ne),ts=require("secondary-cache");function es({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 rs(t,e){let r=Zn.get(t);return r||(r=new Zn(t,{func:es,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 ts.Cache(e)),r}var ns=rs("lrucache"),ss=class t extends Zn{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 j("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):j(`${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 O(n,s,r)}async func(t){const e=await this.fetch(t);if(t?.stream)return e;return await e.json()}},is={...F};ss.defineProperties(ss,is);var os=class extends ss{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))}}},as={methods:{type:"array",assign(t,e,r,n,s){s?.isExported||e.assignMethods(t)}}};os.defineProperties(os,as);var cs=class extends os{async fetch(t,e){if(t||(t={}),e&&"res"===this.action){if("get"===e||"delete"===e){let r=t.id;return r||j("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)}},us=class extends cs{constructor(){super(...arguments),this._sseEvents={},this._forwardEvents=new Set,this.name=Ce,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)}},ls=new us(Ce),hs=require("util-ex"),fs=class t extends Zn{static get apiRoot(){return this._apiRoot}static setApiRoot(t){this._apiRoot=t}static toJSON(){const e={};for(const r in this.items){let n=this.items[r];(n instanceof t||n.isApi)&&(n.allowExportFunc||(n=n.toJSON(),delete n.func),e[r]=n)}return e}func({}){}},ps={...F};fs.defineProperties(fs,ps);var ws=class extends fs{constructor(t,e={}){super(t,e),this.params={act:{type:"string"}};const r=this.methods=[];this.initRpcMethods(r)}get SpecialRpcMethodNames(){return this.constructor.SpecialRpcMethodNames}initRpcMethods(t=this.methods){const e=this.SpecialRpcMethodNames;if(Array.isArray(e))for(const r of e)"function"==typeof this[r]&&t.push(r);(0,hs.getAllNames)(Object.getPrototypeOf(this)).filter((t=>t.startsWith("$")&&"function"==typeof this[t])).forEach((e=>{t.push(e);const r=e.slice(1);void 0===this[r]&&(this[r]=this[e])}))}cast(t,e){let r=this.params[t];return r&&("string"!=typeof r&&(r=r.type),"number"===r&&(e=Number(e))),e}getMethodFromParams(t){const e=t?.act;return e}castParams(t){return t}func(t){const e=this.getMethodFromParams(t);if(e&&"function"==typeof this[e])return t=this.castParams(t),this[e](t);throw new S(e,this.name)}};ws.defineProperties(ws,{methods:{type:"array"}});var ds=class extends ws{constructor(t,e={}){super(t,e),this.action="res",this.params={id:{type:"string"},val:{type:"any"}}}static{this.SpecialRpcMethodNames=I}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}castParams(t){return void 0!==t.id&&(t.id=this.cast("id",t.id)),t}},ms=Qn.runSync(),ys=class t extends ds{constructor(){super(...arguments),this.name=Ce,this.description="subscribe server sent event",this.result="event",this.depends={[Ne]:Qn}}static get sse(){return this._sse||(this._sse=new Re),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=ms.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)||ms.on(r,t.ebListener)}unforward(e){"string"==typeof e&&(e=[e]);for(const r of e)ms.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};j("event is required","sub",400)}$unsub({event:t}){if(t)return this.unforward(t),{event:t};j("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}}j("event or data is required","pub",400)}isStream(t){return"list"===this.getMethodFromParams(t)}},bs=new ys(Ce);function gs(){Qn.register(),ns.register()}
1
+ "use strict";var t,e=Object.create,r=Object.defineProperty,n=Object.getOwnPropertyDescriptor,s=Object.getOwnPropertyNames,i=Object.getPrototypeOf,o=Object.prototype.hasOwnProperty,a=(t,e,i,a)=>{if(e&&"object"==typeof e||"function"==typeof e)for(let c of s(e))o.call(t,c)||c===i||r(t,c,{get:()=>e[c],enumerable:!(a=n(e,c))||a.enumerable});return t},c=(t,n,s)=>(s=null!=t?e(i(t)):{},a(!n&&t&&t.__esModule?s:r(s,"default",{value:t,enumerable:!0}),t)),u={};((t,e)=>{for(var n in e)r(t,n,{get:e[n],enumerable:!0})})(u,{EventClient:()=>ke,EventServer:()=>Me,EventToolFunc:()=>fe,_lrucache:()=>de,createLRUCache:()=>ye,event:()=>we,eventClient:()=>Se,eventServer:()=>qe,lrucache:()=>me,registerCoreTools:()=>Ie}),module.exports=(t=u,a(r({},"__esModule",{value:!0}),t));var h=require("events-ex"),l=require("property-manager"),f=require("util-ex"),w=require("abstract-error"),p=500,d=class t extends w.AbstractError{static createErrorClass(e,r,n=t){return(0,w.createErrorClass)(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}},y=class extends d{constructor(t,e,r=p){super(t,r,e)}},m=class extends y{constructor(t,e){t||(t="Not Implementation."),super(t,e,501)}};y[501]=m;var b=class extends y{static{this.code=404}constructor(t,e){super(`Could not find ${t}.`,e,404),this.data={what:t}}};y[404]=b;var g=class extends y{static{this.code=409}constructor(t,e){super(`The ${t} already exists.`,e,409),this.data={what:t}}};y[409]=g;var x=class extends y{static{this.code=499}constructor(t,e){e||(e="AbortError"),super(t?`The operation was aborted for ${t}.`:"The operation was aborted.",e,499),t&&(this.data={what:t})}};function E(t,e,r=p){const n=new(y[r]||y)(t,e,r);return"number"!=typeof n.code&&(n.code=r),n}function v(t,e,r=p){throw E(t,e,r)}y[499]=x;require("custom-ability");var k=["get","post","put","delete","patch","list","res"],S={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"}},$=(require("date-fns"),require("date-fns"),require("custom-factory"));var O="default",j=class t extends $.BaseFactory{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||O,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||O);if(e)return Reflect.construct(e,arguments);throw new y(`Prompt template type ${n} not found`,"PromptTemplate",400)}}_initialize(t){throw new m("Not implemented","PromptTemplate")}initialize(e){this.constructor!==t&&(Object.assign(this,this.toJSON(e)),e?.ignoreInitialize||this._initialize(e))}_format(t){throw new m("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}};(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=>{t}));var C=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",Macro:"Macro",EndMacro:"EndMacro"}),A=Object.freeze({set:C.Set,for:C.For,in:C.In,is:C.Is,if:C.If,else:C.Else,endif:C.EndIf,elif:C.ElseIf,endfor:C.EndFor,and:C.And,or:C.Or,not:C.Not,"not in":C.NotIn,macro:C.Macro,endmacro:C.EndMacro,true:C.BooleanLiteral,false:C.BooleanLiteral,True:C.BooleanLiteral,False:C.BooleanLiteral}),T=class{constructor(t,e){this.value=t,this.type=e}};function M(t){return/\w/.test(t)}function q(t){return/[0-9]/.test(t)}var I=[["{%",C.OpenStatement],["%}",C.CloseStatement],["{{",C.OpenExpression],["}}",C.CloseExpression],["(",C.OpenParen],[")",C.CloseParen],["{",C.OpenCurlyBracket],["}",C.CloseCurlyBracket],["[",C.OpenSquareBracket],["]",C.CloseSquareBracket],[",",C.Comma],[".",C.Dot],[":",C.Colon],["|",C.Pipe],["<=",C.ComparisonBinaryOperator],[">=",C.ComparisonBinaryOperator],["==",C.ComparisonBinaryOperator],["!=",C.ComparisonBinaryOperator],["<",C.ComparisonBinaryOperator],[">",C.ComparisonBinaryOperator],["+",C.AdditiveBinaryOperator],["-",C.AdditiveBinaryOperator],["*",C.MultiplicativeBinaryOperator],["/",C.MultiplicativeBinaryOperator],["%",C.MultiplicativeBinaryOperator],["=",C.Equals]],N=new Map([["n","\n"],["t","\t"],["r","\r"],["b","\b"],["f","\f"],["v","\v"],["'","'"],['"','"'],["\\","\\"]]);var V=class{constructor(){this.type="Statement"}},P=class extends V{constructor(t){super(),this.body=t,this.type="Program"}},U=class extends V{constructor(t,e,r){super(),this.test=t,this.body=e,this.alternate=r,this.type="If"}},B=class extends V{constructor(t,e,r,n){super(),this.loopvar=t,this.iterable=e,this.body=r,this.defaultBlock=n,this.type="For"}},F=class extends V{constructor(t,e){super(),this.assignee=t,this.value=e,this.type="Set"}},_=class extends V{constructor(t,e,r){super(),this.name=t,this.args=e,this.body=r,this.type="Macro"}},L=class extends V{constructor(){super(...arguments),this.type="Expression"}},R=class extends L{constructor(t,e,r){super(),this.object=t,this.property=e,this.computed=r,this.type="MemberExpression"}},J=class extends L{constructor(t,e){super(),this.callee=t,this.args=e,this.type="CallExpression"}},z=class extends L{constructor(t){super(),this.value=t,this.type="Identifier"}},W=class extends L{constructor(t){super(),this.value=t,this.type="Literal"}},K=class extends W{constructor(){super(...arguments),this.type="NumericLiteral"}},D=class extends W{constructor(){super(...arguments),this.type="StringLiteral"}},Z=class extends W{constructor(){super(...arguments),this.type="BooleanLiteral"}},H=class extends W{constructor(){super(...arguments),this.type="ArrayLiteral"}},G=class extends W{constructor(){super(...arguments),this.type="TupleLiteral"}},Q=class extends W{constructor(){super(...arguments),this.type="ObjectLiteral"}},X=class extends L{constructor(t,e,r){super(),this.operator=t,this.left=e,this.right=r,this.type="BinaryExpression"}},Y=class extends L{constructor(t,e){super(),this.operand=t,this.filter=e,this.type="FilterExpression"}},tt=class extends L{constructor(t,e){super(),this.iterable=t,this.test=e,this.type="SelectExpression"}},et=class extends L{constructor(t,e,r){super(),this.operand=t,this.negate=e,this.test=r,this.type="TestExpression"}},rt=class extends L{constructor(t,e){super(),this.operator=t,this.argument=e,this.type="UnaryExpression"}},nt=class extends L{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 L{constructor(t,e){super(),this.key=t,this.value=e,this.type="KeywordArgumentExpression"}};function it(t){const e=new P([]);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 C.Text:e=new D(n(C.Text,"Expected text token").value);break;case C.OpenStatement:e=function(){let e;switch(n(C.OpenStatement,"Expected opening statement token"),t[r].type){case C.Set:++r,e=a(),n(C.CloseStatement,"Expected closing statement token");break;case C.If:++r,e=c(),n(C.OpenStatement,"Expected {% token"),n(C.EndIf,"Expected endif token"),n(C.CloseStatement,"Expected %} token");break;case C.Macro:++r,e=function(){const t=E();if("Identifier"!==t.type)throw new SyntaxError("Expected identifier following macro statement");const e=m();n(C.CloseStatement,"Expected closing statement token");const r=[];for(;i(C.OpenStatement,C.EndMacro);)r.push(s());return new _(t,e,r)}(),n(C.OpenStatement,"Expected {% token"),n(C.EndMacro,"Expected endmacro token"),n(C.CloseStatement,"Expected %} token");break;case C.For:++r,e=function(){const t=u(!0);if(!(t instanceof z||t instanceof G))throw new SyntaxError(`Expected identifier/tuple for the loop variable, got ${t.type} instead`);n(C.In,"Expected `in` keyword following loop variable");const e=h();n(C.CloseStatement,"Expected closing statement token");const a=[];for(;i(C.OpenStatement,C.EndFor)&&i(C.OpenStatement,C.Else);)a.push(s());const c=[];if(o(C.OpenStatement,C.Else))for(++r,++r,n(C.CloseStatement,"Expected closing statement token");i(C.OpenStatement,C.EndFor);)c.push(s());return new B(t,e,a,c)}(),n(C.OpenStatement,"Expected {% token"),n(C.EndFor,"Expected endfor token"),n(C.CloseStatement,"Expected %} token");break;default:throw new SyntaxError(`Unknown statement type: ${t[r].type} ${t[r].value}`)}return e}(),e.isStatement=!0;break;case C.OpenExpression:e=function(){n(C.OpenExpression,"Expected opening expression token");const t=h();return n(C.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(C.Equals)){++r;const e=a();return new F(t,e)}return t}function c(){const e=h();n(C.CloseStatement,"Expected closing statement token");const i=[],a=[];for(;t[r]?.type!==C.OpenStatement||t[r+1]?.type!==C.ElseIf&&t[r+1]?.type!==C.Else&&t[r+1]?.type!==C.EndIf;)i.push(s());if(t[r]?.type===C.OpenStatement&&t[r+1]?.type!==C.EndIf)if(++r,o(C.ElseIf))n(C.ElseIf,"Expected elseif token"),a.push(c());else for(n(C.Else,"Expected else token"),n(C.CloseStatement,"Expected closing statement token");t[r]?.type!==C.OpenStatement||t[r+1]?.type!==C.EndIf;)a.push(s());return new U(e,i,a)}function u(t=!1){const e=t?E:h,n=[e()],s=o(C.Comma);for(;s&&(++r,n.push(e()),o(C.Comma)););return s?new G(n):n[0]}function h(){return function(){const t=l();if(o(C.If)){++r;const e=l();if(o(C.Else)){++r;const n=l();return new U(e,[t],[n])}return new tt(t,e)}return t}()}function l(){let e=f();for(;o(C.Or);){const n=t[r];++r;const s=f();e=new X(n,e,s)}return e}function f(){let e=w();for(;o(C.And);){const n=t[r];++r;const s=w();e=new X(n,e,s)}return e}function w(){let e;for(;o(C.Not);){const n=t[r];++r;const s=w();e=new rt(n,s)}return e??function(){let e=p();for(;o(C.ComparisonBinaryOperator)||o(C.In)||o(C.NotIn);){const n=t[r];++r;const s=p();e=new X(n,e,s)}return e}()}function p(){let e=g();for(;o(C.AdditiveBinaryOperator);){const n=t[r];++r;const s=g();e=new X(n,e,s)}return e}function d(){const e=function(){let e=E();for(;o(C.Dot)||o(C.OpenSquareBracket);){const s=t[r];let i;++r;const o=s.type!==C.Dot;if(o)i=b(),n(C.CloseSquareBracket,"Expected closing square bracket");else if(i=E(),"Identifier"!==i.type)throw new SyntaxError("Expected identifier following dot operator");e=new R(e,i,o)}return e}();return o(C.OpenParen)?y(e):e}function y(t){let e=new J(t,m());return o(C.OpenParen)&&(e=y(e)),e}function m(){n(C.OpenParen,"Expected opening parenthesis for arguments list");const t=function(){const t=[];for(;!o(C.CloseParen);){let e=h();if(o(C.Equals)){if(++r,!(e instanceof z))throw new SyntaxError("Expected identifier for keyword argument");const t=h();e=new st(e,t)}t.push(e),o(C.Comma)&&++r}return t}();return n(C.CloseParen,"Expected closing parenthesis for arguments list"),t}function b(){const t=[];let e=!1;for(;!o(C.CloseSquareBracket);)o(C.Colon)?(t.push(void 0),++r,e=!0):(t.push(h()),o(C.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 nt(...t)}return t[0]}function g(){let e=x();for(;o(C.MultiplicativeBinaryOperator);){const n=t[r];++r;const s=x();e=new X(n,e,s)}return e}function x(){let t=function(){let t=d();for(;o(C.Pipe);){++r;let e=E();if(!(e instanceof z))throw new SyntaxError("Expected identifier for the filter");o(C.OpenParen)&&(e=y(e)),t=new Y(t,e)}return t}();for(;o(C.Is);){++r;const e=o(C.Not);e&&++r;let n=E();if(n instanceof Z&&(n=new z(n.value.toString())),!(n instanceof z))throw new SyntaxError("Expected identifier for the test");t=new et(t,e,n)}return t}function E(){const e=t[r];switch(e.type){case C.NumericLiteral:return++r,new K(Number(e.value));case C.StringLiteral:return++r,new D(e.value);case C.BooleanLiteral:return++r,new Z("true"===e.value.toLowerCase());case C.Identifier:return++r,new z(e.value);case C.OpenParen:{++r;const e=u();if(t[r].type!==C.CloseParen)throw new SyntaxError(`Expected closing parenthesis, got ${t[r].type} instead`);return++r,e}case C.OpenSquareBracket:{++r;const t=[];for(;!o(C.CloseSquareBracket);)t.push(h()),o(C.Comma)&&++r;return++r,new H(t)}case C.OpenCurlyBracket:{++r;const t=new Map;for(;!o(C.CloseCurlyBracket);){const e=h();n(C.Colon,"Expected colon between key and value in object literal");const s=h();t.set(e,s),o(C.Comma)&&++r}return++r,new Q(t)}default:throw new SyntaxError(`Unexpected token: ${e.type}`)}}for(;r<t.length;)e.body.push(s());return e}function ot(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 ct(t){return t.replace(/\b\w/g,(t=>t.toUpperCase()))}var ut=class{constructor(t=void 0){this.type="RuntimeValue",this.builtins=new Map,this.value=t}__bool__(){return new ft(!!this.value)}toString(){return""+this.value}toJSON(){return this.value}},ht=class extends ut{constructor(){super(...arguments),this.type="NumericValue"}},lt=class t extends ut{constructor(){super(...arguments),this.type="StringValue",this.builtins=new Map([["upper",new mt((()=>new t(this.value.toUpperCase())))],["lower",new mt((()=>new t(this.value.toLowerCase())))],["strip",new mt((()=>new t(this.value.trim())))],["title",new mt((()=>new t(ct(this.value))))],["length",new ht(this.value.length)],["rstrip",new mt((()=>new t(this.value.trimEnd())))],["lstrip",new mt((()=>new t(this.value.trimStart())))]])}},ft=class extends ut{constructor(){super(...arguments),this.type="BooleanValue"}},wt=class extends ut{constructor(t,e){super(t),this.orgValue=e,this.type="ObjectValue",this.builtins=new Map([["get",new mt((([t,e])=>{if(!(t instanceof lt))throw new Error(`Object key must be a string: got ${t.type}`);return this.value.get(t.value)??e??new bt}))],["items",new mt((()=>new dt(Array.from(this.value.entries()).map((([t,e])=>new dt([new lt(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 ft(this.value.size>0)}},pt=class extends wt{constructor(){super(...arguments),this.type="KeywordArgumentsValue"}},dt=class extends ut{constructor(){super(...arguments),this.type="ArrayValue",this.builtins=new Map([["length",new ht(this.value.length)]])}__bool__(){return new ft(this.value.length>0)}},yt=class extends dt{constructor(){super(...arguments),this.type="TupleValue"}},mt=class extends ut{constructor(){super(...arguments),this.type="FunctionValue"}},bt=class extends ut{constructor(){super(...arguments),this.type="NullValue"}},gt=class extends ut{constructor(){super(...arguments),this.type="UndefinedValue"}},xt=class{constructor(t){this.parent=t,this.variables=new Map([["namespace",new mt((t=>{if(0===t.length)return new wt(new Map);if(1!==t.length||!(t[0]instanceof wt))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 mt],["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],["string",t=>"StringValue"===t.type],["number",t=>"NumericValue"===t.type],["integer",t=>"NumericValue"===t.type&&Number.isInteger(t.value)],["iterable",t=>t instanceof dt||t instanceof lt],["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],["eq",(t,e)=>t.value===e.value]])}set(t,e){return this.declareVariable(t,vt(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 gt}catch{return new gt}}},Et=class{constructor(t){this.global=t??new xt}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 ft(r.value==n.value);case"!=":return new ft(r.value!=n.value)}if(r instanceof gt||n instanceof gt)throw new Error("Cannot perform operation on undefined values");if(r instanceof bt||n instanceof bt)throw new Error("Cannot perform operation on null values");if(r instanceof ht&&n instanceof ht)switch(t.operator.value){case"+":return new ht(r.value+n.value);case"-":return new ht(r.value-n.value);case"*":return new ht(r.value*n.value);case"/":return new ht(r.value/n.value);case"%":return new ht(r.value%n.value);case"<":return new ft(r.value<n.value);case">":return new ft(r.value>n.value);case">=":return new ft(r.value>=n.value);case"<=":return new ft(r.value<=n.value)}else if(r instanceof dt&&n instanceof dt){if("+"===t.operator.value)return new dt(r.value.concat(n.value))}else if(n instanceof dt){const e=void 0!==n.value.find((t=>t.value===r.value));switch(t.operator.value){case"in":return new ft(e);case"not in":return new ft(!e)}}if((r instanceof lt||n instanceof lt)&&"+"===t.operator.value)return new lt(r.toString()+n.toString());if(r instanceof lt&&n instanceof lt)switch(t.operator.value){case"in":return new ft(n.value.includes(r.value));case"not in":return new ft(!n.value.includes(r.value))}if(r instanceof lt&&n instanceof wt)switch(t.operator.value){case"in":return new ft(n.value.has(r.value));case"not in":return new ft(!n.value.has(r.value))}throw new SyntaxError(`Unknown operator "${t.operator.value}" between ${r.type} and ${n.type}`)}evaluateArguments(t,e){const r=[],n=new Map;for(const s of t)if("KeywordArgumentExpression"===s.type){const t=s;n.set(t.key.value,this.evaluate(t.value,e))}else{if(n.size>0)throw new Error("Positional arguments must come before keyword arguments");r.push(this.evaluate(s,e))}return[r,n]}evaluateFilterExpression(t,e){const r=this.evaluate(t.operand,e);if("Identifier"===t.filter.type){const n=t.filter,s=e.lookupVariable(n.value);if(s instanceof mt)return s.value([r],e);if(r instanceof dt)switch(n.value){case"list":return r;case"first":return r.value[0];case"last":return r.value[r.value.length-1];case"length":return new ht(r.value.length);case"reverse":return new dt(r.value.reverse());case"sort":return new dt(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}`)}})));default:throw new Error(`Unknown ArrayValue filter: ${n.value}`)}else if(r instanceof lt)switch(n.value){case"length":return new ht(r.value.length);case"upper":return new lt(r.value.toUpperCase());case"lower":return new lt(r.value.toLowerCase());case"title":return new lt(ct(r.value));case"capitalize":return new lt(r.value.charAt(0).toUpperCase()+r.value.slice(1));case"trim":return new lt(r.value.trim());case"trimStart":return new lt(r.value.trimStart());case"trimEnd":return new lt(r.value.trimEnd());case"indent":return new lt(r.value.split("\n").map(((t,e)=>0===e||0===t.length?t:" "+t)).join("\n"));case"string":return r;default:throw new Error(`Unknown StringValue filter: ${n.value}`)}else{if(r instanceof ht){if("abs"===n.value)return new ht(Math.abs(r.value));throw new Error(`Unknown NumericValue filter: ${n.value}`)}if(r instanceof wt)switch(n.value){case"items":return new dt(Array.from(r.value.entries()).map((([t,e])=>new dt([new lt(t),e]))));case"length":return new ht(r.value.size);case"string":return new lt(r.toString());default:throw new Error(`Unknown ObjectValue filter: ${n.value}`)}}throw new Error(`Cannot apply filter "${n.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 mt){const[t,s]=this.evaluateArguments(n.args,e);return s.size>0&&t.push(new pt(s)),i.value([r,...t],e)}if(r instanceof dt){switch(s){case"selectattr":{if(r.value.some((t=>!(t instanceof wt))))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 dt(a)}case"map":{const[,t]=this.evaluateArguments(n.args,e);if(t.has("attribute")){const e=t.get("attribute");if(!(e instanceof lt))throw new Error("attribute must be a string");const n=t.get("default"),s=r.value.map((t=>{if(!(t instanceof wt))throw new Error("items in map must be an object");return t.value.get(e.value)??n??new gt}));return new dt(s)}throw new Error("`map` expressions without `attribute` set are not currently supported.")}}throw new Error(`Unknown ArrayValue filter: ${s}`)}if(r instanceof lt){if("indent"===s){const[t,s]=this.evaluateArguments(n.args,e),i=t.at(0)??s.get("width")??new ht(4);if(!(i instanceof ht))throw new Error("width must be a number");const o=t.at(1)??s.get("first")??new ft(!1),a=t.at(2)??s.get("blank")??new ft(!1),c=r.value.split("\n"),u=" ".repeat(i.value),h=c.map(((t,e)=>!o.value&&0===e||!a.value&&0===t.length?t:u+t));return new lt(h.join("\n"))}throw new Error(`Unknown StringValue 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 ft(t.negate?!s:s)}evaluateUnaryExpression(t,e){const r=this.evaluate(t.argument,e);if("not"===t.operator.value)return new ft(!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 lt(r)}evaluateIdentifier(t,e){return e.lookupVariable(t.value)}evaluateCallExpression(t,e){const[r,n]=this.evaluateArguments(t.args,e);n.size>0&&r.push(new pt(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 dt||t instanceof lt))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 ht||n instanceof gt))throw new Error("Slice start must be numeric or undefined");if(!(s instanceof ht||s instanceof gt))throw new Error("Slice stop must be numeric or undefined");if(!(i instanceof ht||i instanceof gt))throw new Error("Slice step must be numeric or undefined");return t instanceof dt?new dt(at(t.value,n.value,s.value,i.value)):new lt(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 lt(t.property.value);if(r instanceof wt){if(!(n instanceof lt))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 dt||r instanceof lt)if(n instanceof ht)s=r.value.at(n.value),r instanceof lt&&(s=new lt(r.value.at(n.value)));else{if(!(n instanceof lt))throw new Error(`Cannot access property with non-string/non-number: got ${n.type}`);s=r.builtins.get(n.value)}else{if(!(n instanceof lt))throw new Error(`Cannot access property with non-string: got ${n.type}`);s=r.builtins.get(n.value)}return s instanceof ut?s:new gt}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 wt))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 bt}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 xt(e);let n,s;if("SelectExpression"===t.iterable.type){const e=t.iterable;s=this.evaluate(e.iterable,r),n=e.test}else s=this.evaluate(t.iterable,r);if(!(s instanceof dt))throw new Error(`Expected iterable type in for loop: got ${s.type}`);const i=[],o=[];for(let e=0;e<s.value.length;++e){const a=new xt(r),c=s.value[e];let u;if("Identifier"===t.loopvar.type)u=e=>e.setVariable(t.loopvar.value,c);else{if("TupleLiteral"!==t.loopvar.type)throw new Error(`Invalid loop variable(s): ${t.loopvar.type}`);{const e=t.loopvar;if("ArrayValue"!==c.type)throw new Error(`Cannot unpack non-iterable type: ${c.type}`);const r=c;if(e.value.length!==r.value.length)throw new Error(`Too ${e.value.length>r.value.length?"few":"many"} items to unpack`);u=t=>{for(let n=0;n<e.value.length;++n){if("Identifier"!==e.value[n].type)throw new Error(`Cannot unpack non-identifier type: ${e.value[n].type}`);t.setVariable(e.value[n].value,r.value[n])}}}}if(n){u(a);if(!this.evaluate(n,a).__bool__().value)continue}i.push(c),o.push(u)}let a="",c=!0;for(let e=0;e<i.length;++e){const n=new Map([["index",new ht(e+1)],["index0",new ht(e)],["revindex",new ht(i.length-e)],["revindex0",new ht(i.length-e-1)],["first",new ft(0===e)],["last",new ft(e===i.length-1)],["length",new ht(i.length)],["previtem",e>0?i[e-1]:new gt],["nextitem",e<i.length-1?i[e+1]:new gt]]);r.setVariable("loop",new wt(n)),o[e](r);a+=this.evaluateBlock(t.body,r).value,c=!1}if(c){a+=this.evaluateBlock(t.defaultBlock,r).value}return new lt(a)}evaluateMacro(t,e){return e.setVariable(t.name.value,new mt(((e,r)=>{const n=new xt(r);let s;e=e.slice(),"KeywordArgumentsValue"===e.at(-1)?.type&&(s=e.pop());for(let r=0;r<t.args.length;++r){const i=t.args[r],o=e[r];if("Identifier"===i.type){const t=i;if(!o)throw new Error(`Missing positional argument: ${t.value}`);n.setVariable(t.value,o)}else{if("KeywordArgumentExpression"!==i.type)throw new Error(`Unknown argument type: ${i.type}`);{const t=i,e=o??s?.value.get(t.key.value)??this.evaluate(t.value,n);n.setVariable(t.key.value,e)}}}return this.evaluateBlock(t.body,n)}))),new bt}evaluate(t,e){if(void 0===t)return new gt;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"Macro":return this.evaluateMacro(t,e);case"NumericLiteral":return new ht(Number(t.value));case"StringLiteral":return new lt(t.value);case"BooleanLiteral":return new ft(t.value);case"ArrayLiteral":return new dt(t.value.map((t=>this.evaluate(t,e))));case"TupleLiteral":return new yt(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 lt))throw new Error(`Object keys must be strings: got ${t.type}`);r.set(t.value,this.evaluate(s,e))}return new wt(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 vt(t){switch(typeof t){case"number":return new ht(t);case"string":return new lt(t);case"boolean":return new ft(t);case"undefined":return new gt;case"object":return null===t?new bt:Array.isArray(t)?new dt(t.map(vt)):new wt(new Map(Object.entries(t).map((([t,e])=>[t,vt(e)]))),t);case"function":return new mt(((e,r)=>{const n=e.map((t=>kt(t)));return vt(t(...n)??null)}));default:throw new Error(`Cannot convert to runtime value: ${t}`)}}function kt(t){let e=t;if(Array.isArray(t))e=t.map((t=>kt(t)));else if(t instanceof Map)e={},t.forEach(((t,r)=>{e[r]=kt(t)}));else switch(t.type){case"NullValue":e=null;break;case"UndefinedValue":e=void 0;break;case"ArrayValue":e=t.value.map((t=>kt(t)));break;case"KeywordArgumentsValue":case"ObjectValue":e=t.orgValue?t.orgValue:kt(t.value),"KeywordArgumentsValue"===t.type&&Object.setPrototypeOf(e,{jinja_kargs:!0});break;default:t.type&&(e=t.value)}return e}function St(t,e=0){return Math.floor(Math.random()*(t-e+1))+e}var $t={randomInt:St,select:function(t,e){if(Array.isArray(t)||"string"==typeof t)return void 0===e?e=St(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[St(r.length-1)]}return t[e]}},tojson:function(t,e,r){return e&&"object"==typeof e&&(e.depth&&(r=e.depth),e=e.indent),Ot(t,e,r)}};function Ot(t,e,r){let n="";const s=r??0;if(null===t)n="null";else{const r=typeof t;switch(r){case"undefined":n="null";case"number":case"string":case"boolean":return JSON.stringify(t);case"object":{const r=e?" ".repeat(e):"",n="\n"+r.repeat(s),i=n+r;if(Array.isArray(t)){const r=t.map((t=>Ot(t,e,s+1)));return e?`[${i}${r.join(`,${i}`)}${n}]`:`[${r.join(", ")}]`}{const r=Array.from(Object.entries(t)).map((([t,r])=>{const n=`"${t}": ${Ot(r,e,s+1)}`;return e?`${i}${n}`:n}));return e?`{${r.join(",")}${n}}`:`{${r.join(", ")}}`}}default:throw new Error(`Cannot convert to JSON: ${r}`)}}return n}var jt=class extends xt{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()}},Ct=class t{static{this.global=new jt}constructor(t,e={}){const r=function(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=N.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===C.CloseStatement||t===C.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 T(t,C.Text));continue}}i((t=>/\s/.test(t)));const e=n[s];if("-"===e||"+"===e){const t=r.at(-1)?.type;if(t===C.Text||void 0===t)throw new SyntaxError(`Unexpected character: ${e}`);switch(t){case C.Identifier:case C.NumericLiteral:case C.BooleanLiteral:case C.StringLiteral:case C.CloseParen:case C.CloseSquareBracket:break;default:{++s;const t=i(q);r.push(new T(`${e}${t}`,t.length>0?C.NumericLiteral:C.UnaryOperator));continue}}}for(const[t,e]of I)if(n.slice(s,s+t.length)===t){r.push(new T(t,e)),s+=t.length;continue t}if("'"!==e&&'"'!==e)if(q(e)){const t=i(q);r.push(new T(t,C.NumericLiteral))}else{if(!M(e))throw new SyntaxError(`Unexpected character: ${e}`);{const t=i(M),e=Object.hasOwn(A,t)?A[t]:C.Identifier;e===C.In&&r.at(-1)?.type===C.Not?(r.pop(),r.push(new T("not in",C.NotIn))):r.push(new T(t,e))}}else{++s;const t=i((t=>t!==e));r.push(new T(t,C.StringLiteral)),++s}}return r}(t,e={lstrip_blocks:!0,trim_blocks:!0,...e});this.parsed=it(r)}render(e){const r=new xt(t.global);r.set("false",!1),r.set("true",!0),r.set("raise_exception",(t=>{throw new Error(t)})),r.set("range",ot);for(const[t,n]of Object.entries(e))r.set(t,n);return new Et(r).run(this.parsed).toString()}};function At(t,e){let r;switch(t.type){case"Identifier":r=t.value;break;case"MemberExpression":r=At(t.object,e);break;case"FilterExpression":r=At(t.operand,e);break;case"Set":{e||(e=[]);const n=At(t.assignee);n&&e.push(n),r=At(t.value,e);break}}return r&&e?.includes(r)&&(r=void 0),r}function Tt(t){let e;if("Program"===t.type)e=t.body.some((t=>Tt(t)));else e=t.isStatement;return e}function Mt(t,e){let r=[];if(Array.isArray(t))r=t.map((t=>Mt(t,e))).filter(Boolean).flat();else switch(t.type){case"Program":r=t.body.map((t=>Mt(t,e))).filter(Boolean).flat();break;case"If":r=[At(t.test,e),...Mt(t.body,e),...Mt(t.alternate,e)].filter(Boolean);break;case"BinaryExpression":r=[At(t.left,e),At(t.right,e)].filter(Boolean);break;case"For":{const n=At(t.loopvar);n&&(e||(e=[]),e.push(n)),r=[At(t.iterable,e),...Mt(t.body,e)].filter(Boolean);break}case"CallExpression":r=[At(t.callee,e),...Mt(t.args,e)].filter(Boolean);break;default:r=[At(t,e)].filter(Boolean)}return r}Ct.global.assign($t);function qt(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 It(t){const e=new Set;return t.forEach((t=>{"variable"===t.type&&e.add(t.name)})),[...e]}j.register(class extends j{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 Ct(r)}catch(t){}return e&&(n=Tt(e.parsed)),n}getVariables(t=this.compiledTemplate){return Mt(t.parsed,[]).filter(((t,e,r)=>r.indexOf(t)===e))}_initialize(t){const e=t?.template;if("string"!=typeof e)throw new y("Prompt template must be a string","PromptTemplate",400);this.compiledTemplate=new Ct(e),this.inputVariables=Array.isArray(t?.inputVariables)?t.inputVariables:this.getVariables()}_format(t){return this.compiledTemplate.render(t)}},{name:"hf",aliases:["huggingface","internal","default"]});function Nt(t,e){return"string"==typeof e&&(e=e.split(".").filter((t=>t.length))),e.reduce(((t,e)=>t?.[e]),t)}function Vt(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 Nt(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):Nt(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=Nt(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=Nt(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):Nt(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=Nt(e,n);let o;return o=isNaN(s)?i[s.substring(1,s.length-1)]:i[parseInt(s,10)],o||""}))}(n,e,r),n}j.register(class extends j{static isTemplate(t){let e,r,n=!1;if("object"==typeof t?(r=t.template,e=t.compiledTemplate):r=t,!e&&r)try{e=qt(r)}catch(t){}if(e){n=It(e).length>0}return n}getVariables(t=this.compiledTemplate){return It(t)}_initialize(t){const e=t?.template;if("string"!=typeof e)throw new y("Prompt template must be a string","PromptTemplate",400);this.compiledTemplate=qt(e),this.inputVariables=Array.isArray(t?.inputVariables)?t.inputVariables:this.getVariables()}_format(t){return e=this.compiledTemplate,r=t,e.reduce(((t,e)=>{let n;return n="variable"===e.type?e.name in r?t+r[e.name]:t:t+e.text,n}),"");var e,r}},{name:"fstring",aliases:["python","f-string","langchain"]});function Pt(t){return Object.keys(t).sort().map((e=>t[e]))}j.register(class extends j{static isTemplate(t){const e="string"==typeof t?t:t.template;return e?.includes("{{")&&e.includes("}}")}getVariables(t){const e={};return Vt(t,e,!0),[...Object.keys(e)]}_initialize(t){const e=t?.template;if("string"!=typeof e)throw new y("Prompt template must be a string","PromptTemplate",400);this.inputVariables=Array.isArray(t?.inputVariables)?t.inputVariables:this.getVariables(e)}_format(t){return Vt(this.template,t)}},{name:"golang",aliases:["localai","ollama"]});j.register(class extends j{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 j?t.examplePrompt:j.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=Pt(t);r.length>0&&e.push(...r)}const r=[this.prefix,...e,this.suffix].join(this.exampleSeparator),n=this.templateFormat;return await j.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}},{name:"fewshot",aliases:["few_shot"]});new RegExp("([A-Z][a-z]{1,2}\\.)@(\\w)","g"),new RegExp("(\\.[a-zA-Z]\\.)@(\\w)","g");var Ut=require("custom-ability"),Bt="event",Ft="event-bus";(0,Ut.createAbilityInjector)((function(t){return class{static get emitter(){if(!this._emitter){const t=this.get(Ft)?.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 _t(t,e){return!t||t.some((t=>t instanceof RegExp?t.test(e):t===e))}var Lt=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||v("Channel closed","SSEChannel",498);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||_t(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||v("Channel closed","SSEChannel",498);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=>_t(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}};require("eventsource-parser");require("uuid"),c(require("base32768")),require("uuid");var Rt=c(require("xxhashjs")),{h32:Jt,h64:zt}=(c(require("base32768")),require("json-canonicalize"),Rt.default),Wt=(require("util-ex"),require("lodash-es"),require("util-ex"),require("load-config-file")),Kt=require("yaml"),Dt=require("yaml-types"),Zt=(require("mime-type/with-db"),require("yaml"),[Dt.regexp]);Wt.Config.register([".yml",".yaml"],(function(t){return(0,Kt.parse)(t,{customTags:Zt})})),Wt.Config.register([".json"],(function(t){return JSON.parse(t)}));var Ht=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}},Gt=require("events-ex");function Qt(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 Xt=class{constructor(t){this._capacity=Qt(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(Qt(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)}}},Yt=class extends Gt.EventEmitter{};function te(t){return"function"==typeof t}function ee(){return"1"}var re=class{constructor(t,{initFn:e=ee,pauseFn:r,resumeFn:n,capacity:s=32}={}){if(te(r)!==te(n))throw new Error("pauseFn and resumeFn must be both set for pausing");this.maxConcurrency=t,this.free=new Xt(t),this.waiting=new Xt(s),this.releaseEmitter=new Yt,this.useDefaultTokens=e===ee,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}},ne=require("custom-ability"),se=require("util-ex"),ie=class extends AbortController{constructor(t){super(),(0,se.defineProperty)(this,"parent",t)}abort(t,e){this.signal.aborted||("string"==typeof t&&(t=new x(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 x(e.reason||"aborted")}}},oe=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 re(t-1)),e}isAborted(t){const e=this.hasAsyncFeature(ce);let r=this.__task_aborter;if(r&&e){if(null==t)throw new y("Missing taskId",this.name+".isAborted",400);r=r[t]}return!r||r.signal.aborted}getRunningTask(t){const e=this.hasAsyncFeature(ce);let r=this.__task_aborter;if(r&&e){if(null==t)throw new y("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(ce)){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(ce);if(!n&&r&&this.getRunningTask())throw new y("The task is running",this.name,429);const s=t?.aborter||new ie(this);if(!(s instanceof ie)){if(!(s instanceof AbortController))throw new y("aborter should be an AbortController",this.name,400);Object.setPrototypeOf(s,new ie(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(ce)){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=function(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()}})}({onStart:t=>{(0,se.defineProperty)(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(ce)){const t=e?.taskId;if(null==t)throw new y("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)}}};oe.prototype.generateAsyncTaskId=function(t,e){return this._generateAsyncTaskId(t,e)},oe.prototype.cleanMultiTaskAborter=function(t,e){return this._cleanMultiTaskAborter(t,e)};(0,ne.createAbilityInjector)(oe,"abort",{afterInjection:function(t,e){let r=t.prototype._asyncFeatures||0;r|=ue.Cancelable,e&&(e.asyncFeatures&&(r|=e.asyncFeatures),e.maxTaskConcurrency>0&&(t.prototype._maxTaskConcurrency=e.maxTaskConcurrency)),t.prototype._asyncFeatures=r}}),require("lodash-es"),require("util-ex"),c(require("memoizee")),require("json-canonicalize");var ae,ce=0,ue=((ae=ue||{})[ae.MultiTask=1<<ce]="MultiTask",ae[ae.Cancelable=2]="Cancelable",ae[ae.Priority=4]="Priority",ae),he=class t extends l.AdvancePropertyManager{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),Ht.has(r,t)}static run(t,e){const r=this.get(t);if(r)return r.run(e);throw new b(`${t} to run`,this.name)}static runSync(t,e){const r=this.get(t);if(r)return r.runSync(e);throw new b(`${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 b(`${t} to run`,this.name)}static runWithPosSync(t,...e){const r=this.get(t);if(r)return r.runWithPosSync(...e);throw new b(`${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);v("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),Ht.has(e,t)}isStream(t){return this.stream}},le={name:{type:"string"},description:{type:"string"},func:{type:"function",assign(t,e,r,n,s){let i=t;const o=typeof t;return s.isExported?i="function"===o?t.toString():t:t&&("string"!==o&&(t=t.toString()),i=(0,f._createFunction)(t,e.scope)),i}},params:{type:"object"},result:{type:"any"},setup:{type:"function"},depends:{type:"object",exported:!1},tags:{type:["array","string"]},isApi:{type:"boolean"},stream:{type:"boolean"},asyncFeatures:{type:"number"}};he.defineProperties(he,le);var fe=class extends he{constructor(){super(...arguments),this._emitter=new h.EventEmitter,this.description="Return event bus",this.result="event"}get emitter(){return this._emitter}func(){return this.emitter}},we=new fe(Ft),pe=require("secondary-cache");function de({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 ye(t,e){let r=he.get(t);return r||(r=new he(t,{func:de,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 pe.Cache(e)),r}var me=ye("lrucache"),be=class t extends he{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 v("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):v(`${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 E(n,s,r)}async func(t){const e=await this.fetch(t);if(t?.stream)return e;return await e.json()}},ge={...S};be.defineProperties(be,ge);var xe=class extends be{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))}}},Ee={methods:{type:"array",assign(t,e,r,n,s){s?.isExported||e.assignMethods(t)}}};xe.defineProperties(xe,Ee);var ve=class extends xe{async fetch(t,e){if(t||(t={}),e&&"res"===this.action){if("get"===e||"delete"===e){let r=t.id;return r||v("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)}},ke=class extends ve{constructor(){super(...arguments),this._sseEvents={},this._forwardEvents=new Set,this.name=Bt,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)}},Se=new ke(Bt),$e=require("util-ex"),Oe=class t extends he{static get apiRoot(){return this._apiRoot}static setApiRoot(t){this._apiRoot=t}static toJSON(){const e={};for(const r in this.items){let n=this.items[r];(n instanceof t||n.isApi)&&(n.allowExportFunc||(n=n.toJSON(),delete n.func),e[r]=n)}return e}func({}){}},je={...S};Oe.defineProperties(Oe,je);var Ce=class extends Oe{constructor(t,e={}){super(t,e),this.params={act:{type:"string"}};const r=this.methods=[];this.initRpcMethods(r)}get SpecialRpcMethodNames(){return this.constructor.SpecialRpcMethodNames}initRpcMethods(t=this.methods){const e=this.SpecialRpcMethodNames;if(Array.isArray(e))for(const r of e)"function"==typeof this[r]&&t.push(r);(0,$e.getAllNames)(Object.getPrototypeOf(this)).filter((t=>t.startsWith("$")&&"function"==typeof this[t])).forEach((e=>{t.push(e);const r=e.slice(1);void 0===this[r]&&(this[r]=this[e])}))}cast(t,e){let r=this.params[t];return r&&("string"!=typeof r&&(r=r.type),"number"===r&&(e=Number(e))),e}getMethodFromParams(t){const e=t?.act;return e}castParams(t){return t}func(t){const e=this.getMethodFromParams(t);if(e&&"function"==typeof this[e])return t=this.castParams(t),this[e](t);throw new b(e,this.name)}};Ce.defineProperties(Ce,{methods:{type:"array"}});var Ae=class extends Ce{constructor(t,e={}){super(t,e),this.action="res",this.params={id:{type:"string"},val:{type:"any"}}}static{this.SpecialRpcMethodNames=k}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}castParams(t){return void 0!==t.id&&(t.id=this.cast("id",t.id)),t}},Te=we.runSync(),Me=class t extends Ae{constructor(){super(...arguments),this.name=Bt,this.description="subscribe server sent event",this.result="event",this.depends={[Ft]:we}}static get sse(){return this._sse||(this._sse=new Lt),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=Te.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)||Te.on(r,t.ebListener)}unforward(e){"string"==typeof e&&(e=[e]);for(const r of e)Te.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};v("event is required","sub",400)}$unsub({event:t}){if(t)return this.unforward(t),{event:t};v("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}}v("event or data is required","pub",400)}isStream(t){return"list"===this.getMethodFromParams(t)}},qe=new Me(Bt);function Ie(){we.register(),me.register()}
package/dist/funcs.mjs CHANGED
@@ -1 +1 @@
1
- import{EventClient as m,EventServer as o,EventToolFunc as r,_lrucache as p,createLRUCache as t,event as D,eventClient as U,eventServer as c,lrucache as h,registerCoreTools as i}from"./chunk-4LD7IUUG.mjs";import"./chunk-U5DDQYSF.mjs";export{m as EventClient,o as EventServer,r as EventToolFunc,p as _lrucache,t as createLRUCache,D as event,U as eventClient,c as eventServer,h as lrucache,i as registerCoreTools};
1
+ import{EventClient as m,EventServer as o,EventToolFunc as r,_lrucache as p,createLRUCache as t,event as c,eventClient as e,eventServer as f,lrucache as h,registerCoreTools as i}from"./chunk-L3P7XZYM.mjs";export{m as EventClient,o as EventServer,r as EventToolFunc,p as _lrucache,t as createLRUCache,c as event,e as eventClient,f as eventServer,h as lrucache,i as registerCoreTools};
package/dist/index.d.mts CHANGED
@@ -6,8 +6,9 @@ export { e as AIModelNameRule, d as AIModelNameRuleFn, n as AbortError, j as Abo
6
6
  import { BaseFactory } from 'custom-factory';
7
7
  import { Event } from 'events-ex';
8
8
  import * as _base32768 from 'base32768';
9
+ import _memoize, { Options } from 'memoizee';
9
10
  export { NIL as uuidNIL, parse as uuidParse, stringify as uuidStringify, validate as uuidValidate, version as uuidVersion, v1 as uuidv1, v4 as uuidv4, v5 as uuidv5 } from 'uuid';
10
- export * from 'json-canonicalize';
11
+ export { canonicalize } from 'json-canonicalize';
11
12
  export { stringify as stringifyYaml } from 'yaml';
12
13
  export { mimeType } from 'mime-type/with-db';
13
14
  export { Config as ConfigFile } from 'load-config-file';
@@ -1315,16 +1316,21 @@ declare function loadTextFromPaths(filename: string, searchPaths?: string[], ext
1315
1316
  * Optionally filters the results using a file matching callback.
1316
1317
  *
1317
1318
  * @param dir - A single directory path or an array of directory paths to start the search from.
1318
- * @param isFileMatched - An optional callback that determines whether a file should be included in the result.
1319
+ * @param options.isFileMatched - An optional callback that determines whether a file should be included in the result.
1320
+ * @param options.signal - An optional signal to abort the operation.
1319
1321
  * @returns An array of file paths that match the criteria.
1320
1322
  *
1321
1323
  * @example
1322
1324
  * ```typescript
1323
- * const files = readFilenamesRecursiveSync('/path/to/directory', (filepath) => filepath.endsWith('.js'));
1325
+ * const files = readFilenamesRecursiveSync('/path/to/directory', {isFileMatched: (filepath) => filepath.endsWith('.js')});
1324
1326
  * console.log(files); // Outputs an array of JavaScript file paths.
1325
1327
  * ```
1326
1328
  */
1327
- declare function readFilenamesRecursiveSync(dir: string | string[], isFileMatched?: (filepath: string) => boolean, signal?: AbortSignal): string[];
1329
+ declare function readFilenamesRecursiveSync(dir: string | string[], options?: {
1330
+ isFileMatched?: (filepath: string) => boolean;
1331
+ signal?: AbortSignal;
1332
+ level?: number;
1333
+ }): string[];
1328
1334
  /**
1329
1335
  * Resolves the real file path, handling symbolic links.
1330
1336
  *
@@ -1479,7 +1485,7 @@ declare class IntSet {
1479
1485
  declare function countRegexMatches(content: string, regex: RegExp): number;
1480
1486
 
1481
1487
  type ArgInfo = [boolean, string];
1482
- type ArgProcessor = (arg: ArgInfo, ix: number, scope?: Record<string, any>) => string | void | Promise<string | void>;
1488
+ type ArgProcessor = (arg: ArgInfo, ix: number, scope?: Record<string, any>, options?: ParseObjectArgumentOptions) => string | void | Promise<string | void>;
1483
1489
  interface AIChoiceConfig {
1484
1490
  items?: string[];
1485
1491
  maxPick?: number;
@@ -1489,6 +1495,13 @@ interface AIChoiceConfig {
1489
1495
  type?: 'random' | 'ai';
1490
1496
  end?: string;
1491
1497
  }
1498
+ interface ParseObjectArgumentOptions {
1499
+ delimiter?: string;
1500
+ argProcessor?: ArgProcessor;
1501
+ returnArrayOnly?: boolean;
1502
+ templateFormat?: string;
1503
+ templateData?: Record<string, any>;
1504
+ }
1492
1505
  /**
1493
1506
  * Asynchronously parses a string of object arguments into an actual object.
1494
1507
  * @param argsStr The string of arguments to be parsed.
@@ -1528,21 +1541,14 @@ interface AIChoiceConfig {
1528
1541
  * console.log(arrayResult); // Output: [1, 2, 3]
1529
1542
  * ```
1530
1543
  */
1531
- declare function parseObjectArguments(argsStr: string, scope?: Record<string, any>, options?: {
1532
- delimiter?: string;
1533
- argProcessor?: ArgProcessor;
1534
- returnArrayOnly?: boolean;
1535
- }): Promise<any>;
1536
- declare function parseObjectArgumentInfos(args: ArgInfo[], scope?: Record<string, any>, options?: {
1537
- delimiter?: string;
1538
- argProcessor?: ArgProcessor;
1539
- returnArrayOnly?: boolean;
1540
- }): Promise<any>;
1541
- declare function ChoiceArgProcessor(argInfo: ArgInfo, _ix: number, scope?: Record<string, any>): string | undefined;
1542
- declare function TemplateArgProcessor([isNamedArg, arg]: ArgInfo, ix: number, scope?: Record<string, any>): Promise<string | undefined>;
1543
- declare function AIArgProcessor(argInfo: ArgInfo, ix: number, scope?: Record<string, any>): Promise<string | undefined>;
1544
+ declare function parseObjectArguments(argsStr: string, scope?: Record<string, any>, options?: ParseObjectArgumentOptions): Promise<any>;
1545
+ declare function simplifyObjectArguments(args: any): any;
1546
+ declare function parseObjectArgumentInfos(args: ArgInfo[], scope?: Record<string, any>, options?: ParseObjectArgumentOptions): Promise<any>;
1547
+ declare function ChoiceArgProcessor(argInfo: ArgInfo, _ix: number, scope?: Record<string, any>, options?: ParseObjectArgumentOptions): string | undefined;
1548
+ declare function TemplateArgProcessor([isNamedArg, arg]: ArgInfo, ix: number, scope?: Record<string, any>, options?: ParseObjectArgumentOptions): Promise<string | undefined>;
1549
+ declare function AIArgProcessor(argInfo: ArgInfo, ix: number, scope?: Record<string, any>, options?: ParseObjectArgumentOptions): Promise<string | undefined>;
1544
1550
  declare function quoteStr(str: string): string;
1545
- declare function parseObjectArgInfo(argInfo: ArgInfo, ix: number, scope?: Record<string, any>, argProcessor?: ArgProcessor): Promise<string>;
1551
+ declare function parseObjectArgInfo(argInfo: ArgInfo, ix: number, scope?: Record<string, any>, options?: ParseObjectArgumentOptions): Promise<string>;
1546
1552
  /**
1547
1553
  * Parses an object arguments string into an array of ArgInfo.
1548
1554
  *
@@ -1558,16 +1564,12 @@ declare function parseObjectArgInfo(argInfo: ArgInfo, ix: number, scope?: Record
1558
1564
  * @returns An array of parsed argument information, where each item contains a boolean indicating whether the argument is named,
1559
1565
  * and the string representation of the argument.
1560
1566
  */
1561
- declare function parseObjectArgumentsAsArgInfos(argsStr: string, scope?: Record<string, any>, options?: {
1562
- delimiter?: string;
1563
- argProcessor?: ArgProcessor;
1564
- }): ArgInfo[];
1565
- declare function parseCommand(commandStr: string, scope?: Record<string, any>, options?: {
1566
- delimiter?: string;
1567
- argProcessor?: ArgProcessor;
1568
- }): Promise<{
1567
+ declare function parseObjectArgumentsAsArgInfos(argsStr: string, scope?: Record<string, any>, options?: ParseObjectArgumentOptions): ArgInfo[];
1568
+ declare function parseCommand(commandStr: string, scope?: Record<string, any>, options?: ParseObjectArgumentOptions): Promise<{
1569
1569
  command: string;
1570
1570
  args?: Record<string, any>;
1571
1571
  }>;
1572
1572
 
1573
- export { AIArgProcessor, type AIChatAssistantMessageParam, type AIChatContentPart, type AIChatContentPartImage, type AIChatContentPartText, type AIChatMessageParam, type AIChatMessageParamBase, type AIChatMessageToolCall, type AIChatRole, AIChatRoles, type AIChatSystemMessageParam, type AIChatToolMessageParam, type AIChatUserMessageParam, type AIChoiceConfig, type AIMessageType, AIMessageTypes, AIModelNameRules, type AIResult, AIStream, type AIStreamParser, type AIStreamParserOptions, type AITextGenerationFinishReason, AITextGenerationFinishReasons, AsyncFeatures, type AsyncTaskId, BaseError, CancelableAbility, type CancelableAbilityOptions, ChoiceArgProcessor, CommonError, DefaultAsyncSemaphoreCapacity, type DotenvExpandOptions, type DotenvExpandOutput, type DotenvParseInput, type DotenvParseOutput, type DotenvPopulateInput, EventBusName, type EventErrorListenerFn, type EventListenerFn, EventName, FStringPromptTemplate, type FStringPromptTemplateNode, FewShotPromptTemplate, type FewShotPromptTemplateOptions, FilenameReservedRegex, GolangPromptTemplate, builtins as HFBuiltins, EnvironmentEx as HFEnvironment, Interpreter as HFInterpreter, Template as HFTemplate, HfPromptTemplate, IntSet, type JsonFilter, PromptExampleSelector, type PromptExampleSelectorOptions, type PromptExamples, PromptTemplate, type PromptTemplateOptions, type PromptTemplateType, PromptTemplateTypes, type PromptType, PromptTypes, RStreamErrCode, RateLimit, ReadableStreamError, ResponseRStreamErrCode, type SanitizeFilenameOptions, Semaphore, type StreamCallbacksAndOptions, TaskAbortController, type TaskAbortControllers, type TaskPromise, TemplateArgProcessor, ToolFunc, WindowsReservedNameRegex, XXHashAlgorithm, backendEventable, base32768, countRegexMatches, createCallbacksTransformer, createEmptyReadableStream, createEndWithRepetitionDetector, createEventStreamTransformer, createHfValueFunc, dateToText, defaultTemplateFormat, expandEnv, expandObjEnv, extNameLevel, fileIsExists, filenameReservedRegex, filterValidFnScope, getAllEnumKeys, getConfigFileNames, getConfigs, getKeysPath, getMultiLevelExtname, getRealFilepath, getResponseErrorReadableStream, parse as hfParse, tokenize as hfTokenize, interpolateEnv, interpolateFString, interpolateGolangTemplate, isModelNameMatched, isValidFilename, isValidFilepath, isWebStream, jsonFilterToWhere, jsonToMarkdownStr, loadFileFromPaths, loadTextFromPaths, makeToolFuncCancelable, matchUrlProtocol, messagesToText, paramsSizeToScaleStr, parseCommand, parseFString, parseJsJson, parseObjectArgInfo, parseObjectArgumentInfos, parseObjectArguments, parseObjectArgumentsAsArgInfos, parseYaml, quoteStr, reControlCharsRegex, readFilenamesRecursiveSync, readableFromAsyncIterable, registerYamlTag, sanitizeFilename, sanitizeFilepath, saveConfigFile, scaleStrToParamsSize, sortedValues, splitSentence, textToDate, toDateTime, trimStartOfStreamHelper, truncTo, uuid, wait, xxhash, xxhash32, xxhash64, xxhashAsStr };
1573
+ declare function memoize<F extends (...args: any[]) => any>(fn: any, options?: Options<F>): F & _memoize.Memoized<F>;
1574
+
1575
+ export { AIArgProcessor, type AIChatAssistantMessageParam, type AIChatContentPart, type AIChatContentPartImage, type AIChatContentPartText, type AIChatMessageParam, type AIChatMessageParamBase, type AIChatMessageToolCall, type AIChatRole, AIChatRoles, type AIChatSystemMessageParam, type AIChatToolMessageParam, type AIChatUserMessageParam, type AIChoiceConfig, type AIMessageType, AIMessageTypes, AIModelNameRules, type AIResult, AIStream, type AIStreamParser, type AIStreamParserOptions, type AITextGenerationFinishReason, AITextGenerationFinishReasons, AsyncFeatures, type AsyncTaskId, BaseError, CancelableAbility, type CancelableAbilityOptions, ChoiceArgProcessor, CommonError, DefaultAsyncSemaphoreCapacity, type DotenvExpandOptions, type DotenvExpandOutput, type DotenvParseInput, type DotenvParseOutput, type DotenvPopulateInput, EventBusName, type EventErrorListenerFn, type EventListenerFn, EventName, FStringPromptTemplate, type FStringPromptTemplateNode, FewShotPromptTemplate, type FewShotPromptTemplateOptions, FilenameReservedRegex, GolangPromptTemplate, builtins as HFBuiltins, EnvironmentEx as HFEnvironment, Interpreter as HFInterpreter, Template as HFTemplate, HfPromptTemplate, IntSet, type JsonFilter, type ParseObjectArgumentOptions, PromptExampleSelector, type PromptExampleSelectorOptions, type PromptExamples, PromptTemplate, type PromptTemplateOptions, type PromptTemplateType, PromptTemplateTypes, type PromptType, PromptTypes, RStreamErrCode, RateLimit, ReadableStreamError, ResponseRStreamErrCode, type SanitizeFilenameOptions, Semaphore, type StreamCallbacksAndOptions, TaskAbortController, type TaskAbortControllers, type TaskPromise, TemplateArgProcessor, ToolFunc, WindowsReservedNameRegex, XXHashAlgorithm, backendEventable, base32768, countRegexMatches, createCallbacksTransformer, createEmptyReadableStream, createEndWithRepetitionDetector, createEventStreamTransformer, createHfValueFunc, dateToText, defaultTemplateFormat, expandEnv, expandObjEnv, extNameLevel, fileIsExists, filenameReservedRegex, filterValidFnScope, getAllEnumKeys, getConfigFileNames, getConfigs, getKeysPath, getMultiLevelExtname, getRealFilepath, getResponseErrorReadableStream, parse as hfParse, tokenize as hfTokenize, interpolateEnv, interpolateFString, interpolateGolangTemplate, isModelNameMatched, isValidFilename, isValidFilepath, isWebStream, jsonFilterToWhere, jsonToMarkdownStr, loadFileFromPaths, loadTextFromPaths, makeToolFuncCancelable, matchUrlProtocol, memoize, messagesToText, paramsSizeToScaleStr, parseCommand, parseFString, parseJsJson, parseObjectArgInfo, parseObjectArgumentInfos, parseObjectArguments, parseObjectArgumentsAsArgInfos, parseYaml, quoteStr, reControlCharsRegex, readFilenamesRecursiveSync, readableFromAsyncIterable, registerYamlTag, sanitizeFilename, sanitizeFilepath, saveConfigFile, scaleStrToParamsSize, simplifyObjectArguments, sortedValues, splitSentence, textToDate, toDateTime, trimStartOfStreamHelper, truncTo, uuid, wait, xxhash, xxhash32, xxhash64, xxhashAsStr };